code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Tarefa2_2017li1g180 where
import LI11718
import Data.List
import Data.Maybe
import Safe
import Tarefa1_2017li1g180
testesT2 :: [Tabuleiro]
testesT2 = tabs
validaPos :: Posicao -> Tabuleiro -> Bool
-- hpacheco: mudei para incluir parede
validaPos (x,y) t = x <= maybe 0 length (headMay t) && y <= length t
ponto2Pos :: Ponto -> Posicao
ponto2Pos (x,y) = (i,j)
where x' = floor x
y' = floor y
i = x'
j = y'
validaPonto :: Ponto -> Tabuleiro -> Bool
-- hpacheco: mudei para incluir parede
validaPonto (a,b) t = x <= maybe 0 length (headMay t) && y <= length t && x >= 0 && y >= 0
where (x,y) = ponto2Pos (a,b)
valida :: Mapa -> Bool
valida (Mapa _ []) = False
valida (Mapa (p,d) m) | not (validaTabuleiro m) = False
| c == [] = False
| otherwise = validaPos p m && (daVolta c) && (naoDesperdica c t) && (sequencial c a)
where c = percorre [] m p d
(Peca t0 x,_,_) = head c
a = if t0 == Rampa (roda (roda d True) True) then (x+1) else x
t = todoPiso (0,0) m
validaTabuleiro :: Tabuleiro -> Bool
validaTabuleiro m | length (nub (map length m)) > 1 = False
| not (bordaLava m) = False
| otherwise = True
bordaLava :: Tabuleiro -> Bool
bordaLava t = head t == h && last t == h && map head t == v && map last t == v
where h = replicate (length (head t)) (Peca Lava altLava)
v = replicate (length t) (Peca Lava altLava)
percorre :: [(Peca,Posicao,Orientacao)] -> Tabuleiro -> Posicao -> Orientacao -> [(Peca,Posicao,Orientacao)]
percorre vs m (i,j) d | i < 0 || j < 0 || i >= length (head m) || j >= length m = vs
| d' == Nothing = vs
| v `elem` vs = vs++[v]
| otherwise = percorre (vs++[v]) m (mexe (i,j) (fromJust d')) (fromJust d')
where v = (atNote2 "percorre" m j i,(i,j),d)
d' = curva d (atNote2 "percorre" m j i)
lookMap :: Tabuleiro -> Int -> Int -> Peca
lookMap xs j i | j < length xs && i < maybe 0 length (headMay xs) = atNote "lookMap" (atNote "lookMap" xs j) i
lookMap xs j i = error $ "lookMap " ++ show xs ++ " " ++ show j ++ " " ++ show i
todoPiso :: Posicao -> [[Peca]] -> [Posicao]
todoPiso (i,j) m | j >= length m = []
| i >= length (head m) = todoPiso (0,j+1) m
| lookMap m j i == Peca Lava altLava = todoPiso (i+1,j) m
| otherwise = (i,j) : todoPiso (i+1,j) m
daVolta :: [(Peca,Posicao,Orientacao)] -> Bool
daVolta [] = False
daVolta [_] = False
daVolta p = (head p) == (last p)
sequencial :: [(Peca,Posicao,Orientacao)] -> Altura -> Bool
sequencial [] _ = True
sequencial ((Peca (Rampa d') a',_,d):c) a = maybe False (sequencial c) a''
where a'' = subir (a,d) (a',d')
sequencial ((Peca _ a',_,_):c) a | a /= a' = False
| otherwise = sequencial c a
subir :: (Altura,Orientacao) -> (Altura,Orientacao) -> Maybe Altura
subir (a,d) (a',d') | d == d' && a == a' = Just (a+1)
| d == roda (roda d' True) True && a == a' + 1 = Just a'
| otherwise = Nothing
naoDesperdica :: [(Peca,Posicao,Orientacao)] -> [Posicao] -> Bool
naoDesperdica c p = length (nub (map (\(_,x,_) -> x) c)) == length (nub p)
curva :: Orientacao -> Peca -> Maybe Orientacao
curva o (Peca (Curva c) _) | o == c = Just $ roda o True
| o == (roda c False) = Just $ roda o False
| otherwise = Nothing
curva _ (Peca Lava _) = Nothing
curva o _ = Just o
tabs = [mm_ex1,mm_ex2,mm_ex3,mm_exPI,mm_exLV,mm_exEX,mm_exLH,mm_why,mm_NSq,mm_Rec,mm_Rec']
-- mapa nao geravel por caminhos, lava extra a volta
mm_ex1 = [[Peca Lava 2, Peca Lava 2, Peca Lava 2, Peca Lava 2]
,[Peca Lava 2, Peca (Curva Norte) 2,Peca (Curva Este) 2, Peca Lava 2]
,[Peca Lava 2, Peca (Curva Oeste) 2,Peca (Curva Sul) 2, Peca Lava 2]
,[Peca Lava 2, Peca Lava 2, Peca Lava 2, Peca Lava 2]]
-- mapa nao geravel por caminhos, altura /= inicial sem possibilidade de rampas
mm_ex2 = [[Peca (Curva Norte) 5,Peca (Curva Este) 5],[Peca (Curva Oeste) 5,Peca (Curva Sul) 5]]
-- mapa minimo sem vizinhos
mm_ex3 = [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Lava 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
-- posicao inicial invalida
mm_exPI = [[Peca (Curva Norte) 2,Peca (Curva Este) 2],[Peca (Curva Oeste) 2,Peca (Curva Sul) 2]]
-- mapa so lava
mm_exLV = theFloorIsLava (5,10)
-- mapa com caminho extra
mm_exEX = [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Recta 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
-- altura da lava invalida
mm_exLH = [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Lava 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
mm_why = [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Recta 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
mm_NSq = [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 5,Peca (Curva Este) 5, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 5,Peca (Curva Sul) 5, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
mm_Rec = [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca Recta 5,Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
mm_Rec' = [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Recta 5, Peca Recta 5,Peca Recta 5]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
|
hpacheco/HAAP
|
examples/plab/svn/2017li1g180/src/Tarefa2_2017li1g180.hs
|
mit
| 5,923 | 0 | 14 | 1,573 | 2,938 | 1,524 | 1,414 | 95 | 2 |
module Shikensu.Utilities
( (!~>)
, (~>)
, io
, lsequence
, mapIO
) where
import Data.Aeson (FromJSON, ToJSON, fromJSON)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Text (Text)
import Flow
import Shikensu.Internal.Types
import qualified Data.Aeson as Json (Object, Result(..), encode)
import qualified Data.Aeson.KeyMap as KeyMap (lookup)
import qualified Data.Aeson.Key as Key (fromText)
import qualified Data.List as List (unzip, zip)
import qualified Data.Text as Text (unpack)
import qualified Data.Text.Lazy as Lazy.Text (unpack)
import qualified Data.Text.Lazy.Encoding as Lazy.Text (decodeUtf8)
import qualified Data.Tuple as Tuple (fst, snd)
-- IO
{-| IO Sequence helpers
-}
io :: ([Definition] -> [IO Definition]) -> Dictionary -> IO Dictionary
io fn =
fn .> sequence
mapIO :: (Definition -> IO Definition) -> Dictionary -> IO Dictionary
mapIO =
fmap .> io
{-| One way to deal with multiple dictionaries.
> lsequence
> [ ( "pages", Shikensu.list ["src/pages/**/*.html"] rootDir )
> , ( "js", Shikensu.list ["src/javascript/**/*.js"] rootDir )
> ]
From multiple IO monads to a single IO monad.
-}
lsequence :: Monad m => [( id, m a )] -> m [( id, a )]
lsequence list =
let
unzippedList =
List.unzip list
identifiers =
Tuple.fst unzippedList
dictionaries =
Tuple.snd unzippedList
in
dictionaries
|> sequence
|> fmap (List.zip identifiers)
-- PURE
{-| Get stuff out of the metadata.
Returns a `Maybe`.
-}
(~>) :: (FromJSON a, ToJSON a) => Metadata -> Text -> Maybe a
(~>) obj key =
obj
|> KeyMap.lookup (Key.fromText key)
|> fmap fromJSON
|> fmap fromJSONResult
{-| Get stuff out of the metadata.
Does NOT return a `Maybe`, but gives an error if it isn't found.
-}
(!~>) :: (FromJSON a, ToJSON a) => Metadata -> Text -> a
(!~>) obj key =
case (obj ~> key) of
Just x -> x
Nothing -> error <|
"Could not find the key `" <> Text.unpack key <> "` " <>
"on the metadata object `" <> aesonObjectToString obj <> "` using (!~>)"
-- Private
fromJSONResult :: ToJSON a => Json.Result a -> a
fromJSONResult result =
case result of
Json.Success x -> x
Json.Error err -> error err
aesonObjectToString :: Json.Object -> String
aesonObjectToString =
Json.encode .> Lazy.Text.decodeUtf8 .> Lazy.Text.unpack
|
icidasset/shikensu
|
src/Shikensu/Utilities.hs
|
mit
| 2,512 | 0 | 14 | 647 | 668 | 381 | 287 | 59 | 2 |
{- Find the Kth element of a list. -}
nth :: [a] -> Int -> a
nth [] _ = error "cannot perform nth in a empty list"
nth (h:t) 0 = h
nth (h:t) p = nth t (p - 1)
|
andrewaguiar/s99-haskell
|
p03.hs
|
mit
| 160 | 0 | 7 | 42 | 79 | 41 | 38 | 4 | 1 |
{-# 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.Sqlite (createSqlitePool, runSqlPool,
sqlDatabase, sqlPoolSize)
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.Thing
import Handler.Profile
-- 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 $ createSqlitePool
(sqlDatabase $ appDatabaseConf appSettings)
(sqlPoolSize $ 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 [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
|
rpeszek/crud-ex-backend-yesod
|
Application.hs
|
mit
| 6,981 | 0 | 13 | 1,790 | 1,058 | 567 | 491 | -1 | -1 |
module Physics.Scenes.Rolling where
import Control.Monad.ST
import Physics.Constraint
import Physics.Contact.Types
import Physics.Engine
import Physics.Scenes.Scene
import Physics.World
shapeA :: PhysicalObj
shapeA = makePhysicalObj (0, 0) 0 (0, -6) 0 (0, 0)
shapeB :: PhysicalObj
shapeB = makePhysicalObj (0, 0) (-3) (-7, 12) 0 (1, 0.5)
shapeA' :: label -> WorldObj label
shapeA' = makeWorldObj shapeA 0.5 0 $ makeHull [(9, -0.5), (-9, 10), (-9, -0.5)]
shapeB' :: label -> WorldObj label
shapeB' =
makeWorldObj shapeB 0.5 0 $
makeHull
[(2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)]
world :: label -> label -> ST s (World s label)
world a b = makeWorld [shapeA' a, shapeB' b]
externals :: External
externals = makeConstantAccel (0, -4)
contactBehavior :: ContactBehavior
contactBehavior = ContactBehavior 0.01 0.02
scene :: label -> label -> ST s (Scene s label)
scene a b = do
w <- world a b
return $ Scene w externals contactBehavior
|
ublubu/shapes
|
shapes/src/Physics/Scenes/Rolling.hs
|
mit
| 1,043 | 0 | 9 | 237 | 461 | 259 | 202 | 28 | 1 |
module Hoqus.MtxFun where
import Data.List (transpose)
-- | Diagonal of a matrix. This function ignores the non-sqare part of the
-- matrix.
diag :: [[a]] -> [a]
diag m = zipWith (!!) m [0..((min (length m) (length $ transpose m))-1)]
-- | Trace of a matrix. This function ignores the non-sqare part of the matrix.
tr :: Num a => [[a]] -> a
tr m = sum (diag m)
|
jmiszczak/hoqus
|
alternative/MtxFunLists.hs
|
mit
| 364 | 0 | 13 | 72 | 129 | 72 | 57 | 6 | 1 |
module App where
import Gol3d.Life hiding ( Position )
import Data.IORef
import qualified Data.Map as M
import Graphics.UI.GLUT
import Types
-- | Get the position of the cursor in the game with a given radius from
-- the camera position.
cursorLocation' :: GLfloat -> CamState -> Vector3 GLfloat
cursorLocation' r (CamState { camPos = Vector3 x y z
, camAngle = Vector2 theta phi
}) = Vector3 x' y' z'
where x' = x + r * cos theta * sin phi
y' = y + r * cos phi
z' = z + r * sin theta * sin phi
-- | Get the position of the cursor in the game.
-- The game cursor is location a distance r away from the current camera
-- position in the direction of the camera orientation. Equally, this is
-- the forwards movement direction.
cursorLocation :: CamState -> Vector3 GLfloat
cursorLocation cs@(CamState { cursorRadius = r }) = cursorLocation' r cs
gameCursorLocation :: CamState -> Vector3 GLint
gameCursorLocation = fmap round . cursorLocation
-- | Transform the camera state advancing the camera by the given amount in
-- the current direction of the camera.
advanceCamera :: GLfloat -> CamState -> CamState
advanceCamera amt s = s { camPos = cursorLocation' amt s }
-- | Impurely transform the game state given as an "IORef" advancing the
-- camera by a given amount in the direction of the camera.
advanceCamera' :: IORef State -> GLfloat -> IO ()
advanceCamera' stateR k = do
s <- readIORef stateR
let cs' = advanceCamera (k * moveSpeed s) (camState s)
writeIORef stateR (s { camState = cs' })
-- | Impurely transform the game state given as an "IORef" translating the
-- camera by the given vector.
-- Translations are applied relative to the current view as given by the
-- angles "theta" and "phi" in the "State".
transCamera' :: IORef State -> Vector2 GLfloat -> IO ()
transCamera' stateR (Vector2 dx dy) = do
s@(State { camState = cs@(CamState { camPos = Vector3 x y z
, camAngle = Vector2 theta phi
})
, moveSpeed = spd
}) <- get stateR
let rho = theta + (pi/2)
x' = x + spd * dx * cos rho
y' = y + spd * dy
z' = z + spd * dx * sin rho
cs' = cs { camPos = Vector3 x' y' z' }
writeIORef stateR (s { camState = cs' })
-- | Transform a given "CamState" to adjust its angles according to a two
-- dimensional vector. The displacement (in pixels) represented by the vector
-- is multiplied by a scaling factor in radians per pixel.
adjustCameraAngle :: GLfloat -> Vector2 GLint -> CamState -> CamState
adjustCameraAngle aspd (Vector2 dx dy) s@(CamState { camAngle = Vector2 theta phi }) =
s { camAngle = Vector2 theta' phi' }
where theta' = between 0 tau tau $ theta + aspd * fromIntegral dx
phi' = boundedBy 0 pi $ phi + aspd * fromIntegral dy
tau = 2 * pi
boundedBy lo hi x
| x < lo = lo
| x > hi = hi
| otherwise = x
between lo hi adj x
| x < lo = between lo hi adj (x + adj)
| x > hi = between lo hi adj (x - adj)
| otherwise = x
-- | Bring the "CellMap" contained by a "State" to the next generation.
-- This also updates the "lastEvolve" time of "State".
evolveState stateR = do
s@(State { cellMap = cm
, lastEvolve = le
}) <- readIORef stateR
et <- get elapsedTime
writeIORef stateR (s { cellMap = evolve cm
, lastEvolve = et
})
postRedisplay Nothing
-- | Set the OpenGL projection to correspond with the given "CamState".
setCamera (CamState { camPos = Vector3 x y z
, camAngle = Vector2 theta phi
}) = do
matrixMode $= Projection
loadIdentity
(_, Size w h) <- get viewport
perspective 45.0 (fromIntegral w / fromIntegral h) 1.0 100.0
matrixMode $= Modelview 0
loadIdentity
let offX = x + cos theta * sin phi
offY = y + cos phi
offZ = z + sin theta * sin phi
let cast = fromRational . toRational
lookAt (fmap cast $ Vertex3 x y z) (fmap cast $ Vertex3 offX offY offZ) $
(Vector3 0 1 0)
-- | Switch between ViewMode and BuildMode
toggleMode :: GameMode -> GameMode
toggleMode BuildMode = ViewMode
toggleMode ViewMode = BuildMode
-- | Insert a new "Cell" into a "CellMap" given its position.
-- This is simply a monomorphic version of "Data.Map.insert".
insertCell' :: Vector3 Int -> CellMap -> CellMap
insertCell' k = M.insert k (newCell k)
-- | Insert a "Cell" into a "CellMap".
insertCell :: Cell -> CellMap -> CellMap
insertCell c = insertCell' (cellPos c)
-- | Delete a "Cell" from a "CellMap" given its position.
-- This is simply a monomorphic version of "Data.Map.delete".
deleteCell' :: Vector3 Int -> CellMap -> CellMap
deleteCell' = M.delete
-- | Delete a "Cell" from a "CellMap".
deleteCell :: Cell -> CellMap -> CellMap
deleteCell c = deleteCell' (cellPos c)
|
labcoders/gol3d-hs
|
src/App.hs
|
mit
| 5,069 | 0 | 18 | 1,442 | 1,315 | 671 | 644 | 84 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-environment.html
module Stratosphere.ResourceProperties.BatchJobDefinitionEnvironment where
import Stratosphere.ResourceImports
-- | Full data type definition for BatchJobDefinitionEnvironment. See
-- 'batchJobDefinitionEnvironment' for a more convenient constructor.
data BatchJobDefinitionEnvironment =
BatchJobDefinitionEnvironment
{ _batchJobDefinitionEnvironmentName :: Maybe (Val Text)
, _batchJobDefinitionEnvironmentValue :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON BatchJobDefinitionEnvironment where
toJSON BatchJobDefinitionEnvironment{..} =
object $
catMaybes
[ fmap (("Name",) . toJSON) _batchJobDefinitionEnvironmentName
, fmap (("Value",) . toJSON) _batchJobDefinitionEnvironmentValue
]
-- | Constructor for 'BatchJobDefinitionEnvironment' containing required
-- fields as arguments.
batchJobDefinitionEnvironment
:: BatchJobDefinitionEnvironment
batchJobDefinitionEnvironment =
BatchJobDefinitionEnvironment
{ _batchJobDefinitionEnvironmentName = Nothing
, _batchJobDefinitionEnvironmentValue = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-environment.html#cfn-batch-jobdefinition-environment-name
bjdeName :: Lens' BatchJobDefinitionEnvironment (Maybe (Val Text))
bjdeName = lens _batchJobDefinitionEnvironmentName (\s a -> s { _batchJobDefinitionEnvironmentName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-environment.html#cfn-batch-jobdefinition-environment-value
bjdeValue :: Lens' BatchJobDefinitionEnvironment (Maybe (Val Text))
bjdeValue = lens _batchJobDefinitionEnvironmentValue (\s a -> s { _batchJobDefinitionEnvironmentValue = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/BatchJobDefinitionEnvironment.hs
|
mit
| 1,985 | 0 | 12 | 205 | 264 | 151 | 113 | 27 | 1 |
module Main (main) where
import Codec.Archive.Zip
import qualified Data.ByteString.Lazy as B
import Control.Monad
import Control.Applicative ((<$>))
import Data.List
import Data.Bits
import Data.Maybe
import Data.Char
import Data.Array.ST
import Data.Array.Unboxed
import Data.Binary
import Data.Binary.Get
import System.Console.GetOpt
import System.Environment
import Text.Regex.TDFA
import JarFind
-- Types related to cmdline arguments
newtype SearchSource = SearchSource (Class->Bool)
data SearchTarget = SearchClass
| SearchMember (Member->Bool)
data Args = Args { dataSource :: [ClassFileSource]
, searchSource :: SearchSource
, searchTarget :: SearchTarget
}
data Result = FoundClass Location Class
| FoundMember Location Class Member
deriving Show
----------------------------------------------------------------
-- ARGUMENTS PARSING --
----------------------------------------------------------------
data PlainArgs = PlainArgs { typeRegex :: Maybe String
, memberRegex :: Maybe String
, typeAccess :: Maybe String
, memberAccess :: Maybe String
, target :: Maybe String
}
emptyArgs :: PlainArgs
emptyArgs = PlainArgs Nothing Nothing Nothing Nothing Nothing
data MemberKind = FieldKind | MethodKind deriving Eq
parseArgs :: PlainArgs -> [String] -> Args
parseArgs a paths = Args dataSource (SearchSource typeFilter) searchTarget
where searchTarget = case (memberRegex a, memberAccess a, target a) of
(Nothing, Nothing, Nothing) -> SearchClass
_ -> SearchMember memberFilter
searchMembers = isJust (memberRegex a)
typeFilter = accessAndRegex (access (typeAccess a)) (typeRegex a) clsAccess clsName
memberFilter mem = (memKind `maybeEq` kind mem)
&& accessAndRegex (access (memberAccess a)) (memberRegex a)
mAccess mName mem
where kind (Field _ _ _) = FieldKind
kind (Method _ _ _) = MethodKind
memKind = case (target a) of
Just ('f':_) -> Just FieldKind
Just ('m':_) -> Just MethodKind
_ -> Nothing
dataSource = map toDataSource paths
toDataSource p | ".jar" `isSuffixOf` p = JarFile p
| ".class" `isSuffixOf` p = ClassFile p
| ":" `isInfixOf` p = ClassPath . map toDataSource $ (==':') `unjoin` p
| otherwise = error $ "Unsupported datasource type: "++p
accessAndRegex acc rx getAcc getName x = (acc `maybeEq` (getAcc x))
&& (nameMatchesRegex x)
where nameMatchesRegex x = case rx of
Nothing -> True
Just rx -> getName x =~ rx
maybeEq Nothing _ = True
maybeEq (Just a) b = a == b
access a = case a of
Just "public" -> Just Public
Just "private" -> Just Private
Just "protected" -> Just Protected
Just "package" -> Just Package
_ -> Nothing
unjoin :: (a -> Bool) -> [a] -> [[a]]
unjoin p s = go [] [] s
where go res cur [] = reverse (cur:res)
go res cur (x:xs) | p x = go (cur:res) [] xs
| otherwise = go res (x:cur) xs
----------------------------------------------------------------
-- MAIN --
----------------------------------------------------------------
main :: IO ()
main = do
(opts, paths, errs) <- getOpt Permute options `liftM` getArgs
let compose = foldr (.) id
case errs of
[] -> run (parseArgs (compose opts emptyArgs) paths)
_ -> mapM_ putStrLn errs >> showHelp
options :: [OptDescr (PlainArgs -> PlainArgs)]
options = [ Option ['c'] [] (OptArg (\s a -> a { typeRegex = s }) "RX")
"Search for/in types whose name (with package) contains a match of this regex",
Option ['m'] [] (OptArg (\s a -> a { memberRegex = s }) "RX")
"Search for members whose name contains a match of this regex",
Option [] ["ca"] (OptArg (\s a -> a { typeAccess = s })"ACCESS")
"Search for/in types having the specified access (public/private/protected/package)",
Option [] ["ma"] (OptArg (\s a -> a { memberAccess = s }) "ACCESS")
"Search for members having the specified access (public/private/protected/package)",
Option ['t'] ["target"] (OptArg (\s a -> a { target = s }) "TYPE")
"Search for members of the given type (field=f/method=m)"]
showHelp :: IO ()
showHelp = putStrLn $ usageInfo usage options
where usage="jarf [OPTION]... FILE... - Search for classes/methods/interfaces in JAR file(s)"
run :: Args -> IO ()
run (Args dataS searchS searchT) = do
classes <- parseFileSource (ClassPath dataS)
mapM_ (putStrLn . present) . concatMap (search searchS searchT) $ classes
-- Results presentation
present :: Result -> String
present (FoundClass loc cls) = presentLoc loc ++ ": " ++ presentClass cls
present (FoundMember loc cls mem) = presentLoc loc ++ ": " ++
presentClass cls ++ ": " ++
show (mAccess mem) ++ " " ++
(mName mem) ++ " :: " ++
(mSig mem)
presentLoc :: Location -> String
presentLoc (InFile path) = path
presentLoc (InJar jp ip) = jp ++ "!" ++ ip
presentClass :: Class -> String
presentClass (Class name acc False _) = show acc ++ " class " ++ name
presentClass (Class name acc True _) = show acc ++ " interface " ++ name
-- Search
search :: SearchSource -> SearchTarget -> (Location,Class) -> [Result]
search (SearchSource classP) SearchClass (loc,c) =
if (classP c) then [FoundClass loc c] else []
search (SearchSource classP) (SearchMember memP) (loc,c) =
if (classP c) then [FoundMember loc c mem | mem <- clsMembers c, memP mem]
else []
|
jkff/jarfind
|
Main.hs
|
gpl-2.0
| 6,722 | 0 | 14 | 2,450 | 1,835 | 968 | 867 | 117 | 5 |
-- circulos_trasladados_ampliados.hs
-- Círculos trasladados y ampliados.
-- José A. Alonso Jiménez <[email protected]>
-- Sevilla, 20 de Mayo de 2013
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
-- Ejercicio. ¿Qué dibujo genera el siguiente programa?
-- ---------------------------------------------------------------------
import Graphics.Gloss
main :: IO ()
main = display (InWindow "Dibujo" (500,300) (20,20)) white dibujo
dibujo :: Picture
dibujo = pictures [translate x 0 (circle x) | x <- [10,20..100]]
|
jaalonso/I1M-Cod-Temas
|
src/Tema_25/circulos_trasladados_ampliados.hs
|
gpl-2.0
| 616 | 0 | 9 | 68 | 103 | 59 | 44 | 5 | 1 |
{- | Module : $Header$
- Description : Implementation of generic data structures and functions
- Copyright : (c) Daniel Hausmann & Georgel Calin & Lutz Schroeder, DFKI Lab Bremen,
- Rob Myers & Dirk Pattinson, Department of Computing, ICL
- License : GPLv2 or higher, see LICENSE.txt
- Maintainer : [email protected]
- Stability : provisional
- Portability : portable
-
- Provides the implementation of the generic algorithm for checking
- satisfiability/provability of several types of modal logics.
-}
module GMP.Generic where
import List
import Ratio
import Maybe
import Debug.Trace
--------------------------------------------------------------------------------
-- basic data types
--------------------------------------------------------------------------------
-- Formulas
data L a
= F | T | Atom Int
| Neg (L a) | And (L a) (L a) | Or (L a) (L a)
| M a [L a]
deriving (Eq,Show)
-- A sequent is a list of formulas
type Sequent a = [L a]
-- A premise is a list of sequents
type Premise a = [Sequent a]
-- Logic class: consists of a Modal logic type with a rule for matching clauses
class (Eq a,Show a) => Logic a where
-- The matching function for the sequent calculus. Takes the current
-- sequent returns a list of possible premises (a premise being a list
-- of sequents)
match :: Sequent a -> [Premise a]
-- Container class: consists of a container type with rules for accessing it
class (Eq elem,Show elem) => Container cont elem | cont -> elem where
-- Is the container empty?
is_empty :: cont -> Bool
-- Construct the empty container
empty_container :: cont
-- Add an element to the end of a container
container_add :: cont -> elem -> cont
-- Add an element to the front of a container
add_to_container :: elem -> cont -> cont
-- Merge two containers into one
container_cons :: cont -> cont -> cont
-- Get the first element from a container
get_from_container :: cont -> elem
-- Remove the first element from a container
remove_from_container :: cont -> cont
-- Instantiation of container class to lists
instance (Eq a,Show a) => Container [a] a where
is_empty [] = True
is_empty (x:xs) = False
empty_container = []
container_add cont phi = cont ++ [phi]
add_to_container phi cont = [phi] ++ cont
container_cons cont1 cont2 = cont1 ++ cont2
get_from_container cont = head cont
remove_from_container cont = tail cont
--------------------------------------------------------------------------------
-- generic functions for containers
--------------------------------------------------------------------------------
-- Remove all elements NOT fulfilling the condition from a container
container_filter :: (Container cont elem) => (elem -> Bool) -> cont -> cont
container_filter cond cont = case is_empty(cont) of
True -> empty_container;
False -> case cond (get_from_container cont) of
True-> add_to_container (get_from_container cont) (container_filter cond (remove_from_container cont));
False-> container_filter cond (remove_from_container cont)
-- Apply function to each element in the container
container_map :: (Container cont1 elem1, Container cont2 elem2) => (elem1 -> elem2) -> cont1 -> cont2
container_map op cont = case is_empty(cont) of
True -> empty_container;
False -> add_to_container (op (get_from_container cont)) (container_map op (remove_from_container cont));
--------------------------------------------------------------------------------
-- pretty printing functions
--------------------------------------------------------------------------------
-- pretty print formula
pretty :: (Logic a) => L a -> String
pretty F = "F"; pretty T = "T";
pretty (Atom k) = "p" ++ (show k);
pretty (Or (Neg x) y) = "("++ (pretty x) ++ ") --> (" ++ (pretty y) ++ ")"
pretty (Neg x) = "!" ++ (pretty x)
pretty (Or x y) = "(" ++ (pretty x) ++ ") OR (" ++ (pretty y) ++ ")"
pretty (And x y) = "(" ++ (pretty x) ++ ") AND (" ++ (pretty y) ++ ")"
pretty (M a x) = "[" ++ (show a) ++ "](" ++ (show (map pretty x)) ++ ")"
-- pretty print sequent
pretty_seq :: (Logic a) => Sequent a -> String
pretty_seq [] = "\n\t .. Sequent finished"
pretty_seq (x:xs) = (pretty x) ++ (pretty_seq xs)
|
nevrenato/Hets_Fork
|
GMP/versioning/gmp-coloss-0.0.3/GMP/Generic.hs
|
gpl-2.0
| 4,476 | 10 | 15 | 1,021 | 1,017 | 545 | 472 | -1 | -1 |
import QHaskell.QDSL
import qualified QHaskell.Environment.Typed as ET
import qualified QHaskell.Environment.Scoped as ES
import qualified QHaskell.Type.GADT as TG
import qualified QHaskell.Nat.GADT as NG
import QHaskell.Expression.Utils.TemplateHaskell as TH
iff :: Bool -> a -> a -> a
iff l m n = if l then m else n
-- below is generated automatically by the tool using Template Haskell
et = ET.Ext (TG.Arr TG.Bol (TG.Arr (TG.TVr NG.Zro)
(TG.Arr (TG.TVr NG.Zro) (TG.TVr NG.Zro)))) ET.Emp
-- below is generated automatically by the tool using Template Haskell
es = ES.Ext (TH.stripNameSpace ('iff)) ES.Emp
testQ1 :: Qt (Bool -> Float)
testQ1 = [|| \ x -> iff x 1.1 1.1 ||]
miniFeldspar1 = translateFWith et es testQ1
{- gives us
(\ x0 -> (Prm $(nat 0 "") (
Ext (x0) (
Ext (ConF (1.1)) (
Ext (ConF (1.1)) (Emp))))))
which with some clean ups to make it more human readable it
would be equivalent to
(\ x0 -> Prm 0 (x0 <+> ConF 1.1 <+> ConF 1.1 <+> Emp))
where 0 ranges over the provided environment, representing iff
-}
testQ2 :: Qt Float
testQ2 = [|| (\ x -> iff x 1.1 1.1) True ||]
miniFeldspar2 = translateWith et es testQ2
{- gives us
Prm $(nat 0 "") (
Ext (ConB (True)) (
Ext (ConF (1.1)) (
Ext (ConF (1.1)) (Emp))))
which with some clean ups to make it more human readable it
would be equivalent to
Prm 0 (ConB True <+> ConF 1.1 <+> ConF 1.1 <+> Emp)
where 0 ranges over the provided environment, representing iff
-}
-- I am no implementing free evaluator and optimiser
-- (e.g. partial evaluator), which would for example reduce above to
-- ConF 1.1 (based on Haskell semantics)
|
shayan-najd/QHaskell
|
Tests/PolyMorphism.hs
|
gpl-3.0
| 1,667 | 6 | 14 | 361 | 302 | 172 | 130 | -1 | -1 |
-- One of many possible language extensions
-- Here is the error we get from the compiler when we remove this clause:
--
-- Sound.hs:74:9:
-- Ambiguous type variable `a0' in the constraints:
-- (RealFrac a0) arising from a use of `truncate' at Sound.hs:74:9-16
-- (Num a0) arising from a use of `*' at Sound.hs:74:28
-- (Integral a0) arising from a use of `fromIntegral'
-- at Sound.hs:36:25-36
-- (Enum a0) arising from the arithmetic sequence `0 .. n'
-- at Sound.hs:36:47-54
-- Possible cause: the monomorphism restriction applied to the following:
-- computeSound :: forall a.
-- (Ord a, Floating a) =>
-- a0 -> a0 -> a -> [a]
-- (bound at Sound.hs:86:1)
-- slice :: forall a. a0 -> [a] -> [a] (bound at Sound.hs:73:1)
-- wave :: forall b. Floating b => a0 -> [b] (bound at Sound.hs:21:1)
-- samplingRate :: a0 (bound at Sound.hs:17:1)
-- Probable fix: give these definition(s) an explicit type signature
-- or use -XNoMonomorphismRestriction
-- In the expression: truncate
-- In the first argument of `take', namely
-- `(truncate $ seconds * samplingRate)'
-- In the expression:
-- take (truncate $ seconds * samplingRate) repeatWave
--
-- Monomorphism restriction's definition is rather complex (see Haskell Report 4.5.5 for details)
-- but its meaning is quite simple: When a type variable is free within a type expression it
-- cannot be generalized (eg. implicitly universally quantified) even if this would be perfectly legal. Here we do not
-- have an explicit type for @samplingRate@ hence it's type is a variable which occurs free in the reported
-- context, hence it cannot be generalized and becomes "ambiguous" when used in two places with two different
-- possible types. Another way to fix the problem would be to declare explicitly a type for sampling rate:
--
-- samplingRate :: (Num a) => a
--
{-# LANGUAGE NoMonomorphismRestriction #-}
{-| A module for low-level sound generation routines.
By default modules export all the symbols they define.
-}
module Sound where
-- | A simple type alias.
-- Type aliases are stricly syntactic: The symbol is replaced by its definition before
-- typechecking. Common aliases are
-- @@
-- type String = [Char]
-- @@
type Wave = [Double]
-- | This a CAF: Constant Applicative Form.
samplingRate = 44000
-- | A function producing a sinusoidal sampling of a given frequency
-- depending on the sampling rate.
wave frequency =
-- @let@ keyword introduces variable definition scope. For all practical purpose
-- a let scope can contain any definition that would be valid at the toplevel but
-- of course the symbols are visible only within the scope of the let environment.
-- Note that mutually recursive definitions are perfectly legal in a let environment,
-- just like it is legal at the top-level.
--
-- Note here the use of a symbol in infix notation using backquotes. All binary function
-- symbols may be used as operators using backquotes. Conversely, all operators may be
-- used in prefix form using parens.
let n = samplingRate `div` frequency
in map
(sin . (* (2 * pi))) -- a common idiom in Haskell: Using "function pipelines" in so-called
-- point-free notation. The use of a partially applied operators @(* x)@
-- is called a _section_.
[ fromIntegral i / fromIntegral n | i <- [0 .. n]] -- a list comprehension, similar to a for-loop in Scala
-- |Defining an operator is identical to declaring a function.
-- An operator is any (valid) symbol which does not start with an alphabetic letter.
-- Note the use of an explicit type declaration which is never mandatory excepts in
-- situation where there is an ambiguity (for example due to conflicting type-classes existing
-- in scope)
(°) :: Wave -> Wave -> Wave
-- Operator's definition can use infix notation.
w ° w' = zipWith avg w1 w2
-- a @where@ clause is similar to a let-environment excepts its scope is the preceding expression.
where
avg a b = (a + b) /2
w1 = w ++ w1
w2 = w' ++ w2
-- |A typical definition of a recursive function using pattern-matching.
-- There is a very close match with inductive proofs in mathematics and practically this
-- form is quite useful to prove properties or derive more efficient forms from an existing
-- definition. However the order of clauses is important when they may overlap as this gets translated into
-- a sequence of possibly nested cases. The compiler can however issue warnings when it
-- it detects overlapping clauses (which could be the case here as 0 is a special case of n).
duplicate :: Int -> [a] -> [a]
-- define the behaviour for base case which usually stops the recursion
duplicate 0 l = l
-- recursively call the function, "reducing" step-by-step its scope until
-- it reaches the base case.
duplicate n l = l ++ duplicate (n-1) l
-- | This function's definition uses a *guard* to select cases depending on
-- the value of an expression, not only the structure of the parameters. All
-- the variables defined in patterns are in scope in the guard.
amplitude ratio | ratio > 0 && ratio < 1 = map (*ratio)
-- otherwise is simply an alias for True.
| otherwise = id
slice seconds wave =
take (truncate $ seconds * samplingRate) repeatWave
where
-- We take advantage of laziness to define concisely and efficiently a repeating structure
-- This expression and each subexpression will be evaluated only if its value is actually
-- needed at runtime to make progress in the computation (of the top-level main function).
repeatWave = wave ++ repeatWave
-- |Scale a list of doubles between -1 and 1 to an integer interval
scale :: (Int,Int) -> [Double] -> [Int]
scale (min,max) (x:xs) = truncate (((x + 1) / 2) * fromIntegral (max - min)) + min : scale (min,max) xs
scale _ [] = []
computeSound frequency duration volume =
slice duration $ amplitude volume $ wave frequency
|
abailly/haskell-synthesizer
|
Sound.hs
|
gpl-3.0
| 6,220 | 0 | 13 | 1,477 | 529 | 319 | 210 | 27 | 1 |
{-# LANGUAGE CPP, OverloadedStrings #-}
-- |
-- Copyright : (C) 2014-2018 Jens Petersen
--
-- Maintainer : Jens Petersen <[email protected]>
--
-- Explanation: Updating of Upstream Release Monitoring bugs
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
module Main where
#if (defined(MIN_VERSION_base) && MIN_VERSION_base(4,8,0))
#else
import Control.Applicative ((<$>))
#endif
import Control.Monad (unless, when)
import Data.Char (isLetter)
import Data.List (dropWhileEnd, intercalate, isPrefixOf)
import Data.Maybe (fromMaybe, listToMaybe)
import Data.Time.Clock (diffUTCTime, getCurrentTime)
import System.Directory ({-doesFileExist, getCurrentDirectory,-} getModificationTime)
import System.Console.GetOpt (ArgDescr (..), ArgOrder (..), OptDescr (..),
getOpt, usageInfo)
import System.Environment (getArgs, getEnv, getProgName)
import System.FilePath ((</>))
import Distribution.Fedora (Dist, getRawhideDist)
import Koji (kojicmd)
import SimpleCmd ((+-+), cmd, cmd_, cmdStdErr, removeStrictPrefix, removeSuffix)
data BugState = BugState {
bugNo :: String,
component :: String,
status :: String,
summary :: String,
whiteboard :: String
}
data Flag = Check | Force | DryRun | NoComment | Refresh | State String
deriving (Eq, Show)
isState :: Flag -> Bool
isState (State _) = True
isState _ = False
options :: [OptDescr Flag]
options =
[ Option "f" ["force"] (NoArg Force) "update even if no version change (implies --refresh)"
, Option "n" ["dryrun"] (NoArg DryRun) "do not update bugzilla"
, Option "r" ["refresh"] (NoArg Refresh) "update if status changed"
, Option "s" ["state"] (ReqArg State "BUGSTATE") "bug state (default NEW)"
, Option "N" ["no-comment"] (NoArg NoComment) "update the whiteboard only"
, Option "c" ["check"] (NoArg Check) "check update for missing deps"
]
parseOpts :: [String] -> IO ([Flag], [String])
parseOpts argv =
case getOpt Permute options argv of
(os,ps,[]) -> return (os,ps)
(_,_,errs) -> do
prog <- getProgName
error $ concat errs ++ usageInfo (header prog) options
where header prog = "Usage:" +-+ prog +-+ "[OPTION...] [PACKAGE...]"
main :: IO ()
main = do
(opts, args) <- getArgs >>= parseOpts
when (null args) $ error "must give one or more packages"
let state = fromMaybe "NEW" $ listToMaybe $ map (\ (State s) -> s) $ filter isState opts
bugs <- parseLines . lines <$> bugzillaQuery (["--bug_status=" ++ state, "--short_desc=is available", "--outputformat=%{id}\n%{component}\n%{bug_status}\n%{summary}\n%{status_whiteboard}"] ++ ["--component=" ++ intercalate "," args])
rawhide <- getRawhideDist
mapM_ (checkBug rawhide opts) bugs
bugzillaQuery :: [String] -> IO String
bugzillaQuery args = cmd "bugzilla" ("query":args)
bugzillaModify :: [String] -> IO ()
bugzillaModify args = cmd_ "bugzilla" ("modify":args)
parseLines :: [String] -> [BugState]
parseLines [] = []
-- final empty whiteboard eaten by lines
parseLines [bid, bcomp, bst, bsum] = [BugState bid bcomp bst bsum ""]
parseLines (bid:bcomp:bst:bsum:bwh:rest) =
BugState bid bcomp bst bsum bwh : parseLines rest
parseLines _ = error "Bad bugzilla query output!"
checkBug :: Dist -> [Flag] -> BugState -> IO ()
checkBug rawhide opts (BugState bid bcomp _bst bsum bwh) =
unless (bcomp `elem` excludedPkgs) $ do
let hkg = removeGhcPrefix bcomp
(hkgver, state) = colon bwh
pkgver = removeSuffix " is available" bsum
hkgver' = removeGhcPrefix pkgver
unless (null hkgver || hkg `isPrefixOf` hkgver) $
putStrLn $ "Whiteboard format warning for" +-+ hkgver' ++ ":" +-+ bwh +-+ "<" ++ "http://bugzilla.redhat.com/" ++ bid ++ ">"
-- should not happen!
unless (hkg `isPrefixOf` hkgver') $
putStrLn $ "Component and Summary inconsistent!" +-+ hkg +-+ hkgver' +-+ "<" ++ "http://bugzilla.redhat.com/" ++ bid ++ ">"
if Check `notElem` opts then closeBug rawhide opts bid bcomp pkgver else do
let force = Force `elem` opts
refresh = Refresh `elem` opts
when (hkgver /= hkgver' || force || refresh) $ do
cabalUpdate
(missing, err) <- cmdStdErr "cblrpm" ["missingdeps", hkgver']
let state' = if null missing && null err then "ok" else "deps"
when ((hkgver, state) /= (hkgver', state') || force) $ do
let statemsg = if null state || state == state' then state' else state +-+ "->" +-+ state'
putStrLn $ if hkgver == hkgver'
then hkgver ++ ":" +-+ statemsg
else (if null bwh then "New" else hkgver +-+ "->") +-+ hkgver' ++ ":" +-+ statemsg
unless (null missing) $
putStrLn missing
putStrLn ""
unless (DryRun `elem` opts) $ do
let nocomment = NoComment `elem` opts
updateBug bid bcomp hkgver' missing state' nocomment
excludedPkgs :: [String]
excludedPkgs = ["ghc", "emacs-haskell-mode"]
removeGhcPrefix :: String -> String
removeGhcPrefix p@('g':'h':'c':'-':rest) | isLetter $ head rest = rest
| otherwise = p
removeGhcPrefix pkg = pkg
-- comma :: String -> String
-- comma nv = reverse eman ++ "," ++ reverse rev
-- where
-- (rev, '-':eman) = break (== '-') $ reverse nv
colon :: String -> (String, String)
colon "" = ("","")
colon ps = (nv, if null s then "" else removeStrictPrefix ":" s)
where
(nv, s) = break (== ':') ps
closeBug :: Dist -> [Flag] -> String -> String -> String -> IO ()
closeBug rawhide opts bid bcomp pkgver = do
latest <- cmd (kojicmd rawhide) ["latest-pkg", "rawhide", bcomp, "--quiet"]
unless (null latest) $ do
let nvr = (head . words) latest
let nv = removeRelease nvr
when (nv == pkgver) $ do
putStrLn $ "closing" +-+ bid ++ ":" +-+ nv +-+ "in rawhide"
unless (DryRun `elem` opts) $
bugzillaModify ["--close=RAWHIDE", "--fixed_in=" ++ nvr, "--comment=Closed with fhbz from fedora-haskell-tools", bid]
where
removeRelease = init . dropWhileEnd (/= '-')
updateBug :: String -> String -> String -> String -> String -> Bool -> IO ()
updateBug bid _bcomp hkgver missing state nocomment = do
-- rebuilds <- if null missing then tail <$> cmdLines "cblrepo" ["build", removeGhcPrefix bcomp] else return []
progname <- getProgName
let comment = progname ++ ":" +-+
if null missing
then "No missing dependencies for" +-+ hkgver +-+ "\naccording to cblrpm missingdeps" {-++ (if null rebuilds then "\nwithout any other package rebuilds." else ".\n\nIt would require also rebuilding:\n" +-+ unwords rebuilds)-}
else "cblrpm missingdeps output for" +-+ hkgver ++ ":\n\n" ++ missing
bugzillaModify $ ["--whiteboard==" ++ hkgver ++ ":" ++ state] ++
["--comment=" ++ comment | not nocomment] ++ [bid]
cabalUpdate :: IO ()
cabalUpdate = do
home <- getEnv "HOME"
pkgs <- getModificationTime (home </> ".cabal/packages/hackage.haskell.org/01-index.tar.gz")
now <- getCurrentTime
let diff = diffUTCTime now pkgs
when (diff > 3600) $
cmd_ "cabal" ["update"]
|
fedora-haskell/fedora-haskell-tools
|
fhbz.hs
|
gpl-3.0
| 7,304 | 0 | 24 | 1,566 | 2,146 | 1,140 | 1,006 | 128 | 6 |
{- Types
Gregory W. Schwartz
Collections the types used in the program.
-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Types where
-- Standard
import GHC.Generics
import Control.DeepSeq (NFData)
-- Cabal
import qualified Data.Text as T
import Data.Aeson
import qualified Foreign.R as R
import Foreign.R (SEXP, SEXPTYPE)
import Language.R.Instance as R
import Language.R.QQ
-- Local
-- Algebraic
data Database
= Ensembl
| HUGO T.Text
| UniProt
| RGene (String, String, String)
| MSigDBRData (String, String, String)
deriving (Read,Show)
data DescFields = UniProtOther T.Text
| Synonyms
| Description
deriving (Read,Show)
-- Basic
newtype File = File String
newtype UnknownAnn = UnknownAnn { unUnknownAnn :: T.Text }
newtype Ann = Ann { unAnn :: T.Text }
deriving (NFData)
newtype Desc = Desc { unDesc :: T.Text }
deriving (NFData)
newtype HUGOType = HUGOType { unHUGOType :: T.Text }
newtype RType = RType { unRType :: (String, String, String) }
newtype MSigDBType = MSigDBType { unMSigDBType :: (String, String, String) }
newtype RMart s = RMart { unRMart :: (R.SomeSEXP s) }
newtype RData s = RData { unRData :: (R.SomeSEXP s) }
-- Advanced
|
GregorySchwartz/convert-annotation
|
src/Types.hs
|
gpl-3.0
| 1,350 | 0 | 9 | 354 | 330 | 215 | 115 | 33 | 0 |
{-|
Module : Data.HdrHistogram
Copyright : (c) Josh Bohde, 2015
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
A Haskell implementation of <http://www.hdrhistogram.org/ HdrHistogram>.
It allows storing counts of observed values within a range,
while maintaining precision to a configurable number of significant
digits.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.HdrHistogram (
-- * Histogram
Histogram(..), empty, fromConfig,
-- * Writing
record, recordValues,
-- * Reading
Range(..),
percentile,
-- * Re-exports
Config, HasConfig
) where
import Data.Bits (Bits, FiniteBits)
import Data.HdrHistogram.Config
import Data.HdrHistogram.Config.Internal
import Data.Proxy (Proxy (Proxy))
import Data.Tagged (Tagged (Tagged))
import Data.Vector.Unboxed ((!), (//))
import qualified Data.Vector.Unboxed as U
-- | A pure 'Histogram'
data Histogram config value count = Histogram {
_config :: HistogramConfig value,
totalCount :: count,
counts :: U.Vector count
} deriving (Eq, Show)
-- | Construct a 'Histogram'.
empty :: forall config value count. (HasConfig config, Integral value, FiniteBits value, U.Unbox count, Integral count) => Histogram config value count
empty = fromConfig (Tagged c :: Tagged config (HistogramConfig value))
where
p = Proxy :: Proxy config
c = getConfig p
-- | Construct a 'Histogram' from the given 'HistogramConfig'. In this
-- case 'c' is a phantom type.
fromConfig :: (U.Unbox count, Integral count) => Tagged c (HistogramConfig value) -> Histogram c value count
fromConfig (Tagged c) = Histogram {
_config = c,
totalCount = 0,
counts = U.replicate (size c) 0
}
instance (HasConfig config, Integral value, FiniteBits value, U.Unbox count, Integral count) =>
Monoid (Histogram config value count) where
mempty = empty
Histogram config' t c `mappend` Histogram _ t' c' = Histogram config' (t + t') (U.zipWith (+) c c')
-- | Record a single value to the 'Histogram'
record :: (U.Unbox count,
Integral count, Integral value, FiniteBits value)
=> Histogram config value count
-> value
-> Histogram config value count
record h val = recordValues h val 1
-- | Record a multiple instances of a value value to the 'Histogram'
recordValues :: (U.Unbox count, Integral count, Integral value, FiniteBits value) => Histogram config value count -> value -> count -> Histogram config value count
recordValues h val count = h {
totalCount = totalCount h + count,
counts = counts h // [(index, (counts h ! index) + count)]
}
where
index = indexForValue (_config h) val
-- recordCorrectedValues :: Integral value => Histogram value count -> value -> value -> Histogram value count
-- recordCorrectedValues = undefined
-- | Calculate the 'Range' of values at the given percentile
percentile :: (Integral value, Integral count, U.Unbox count, Bits value)
=> Histogram config value count
-> Float -- ^ The percentile in the range 0 to 100
-> Range value
percentile h q = case U.find ((>= count) . snd) totals of
Nothing -> Range 0 0
Just (i, _) -> rangeForIndex c i
where
c = _config h
q' = min q 100
count = floor $ (q' / 100) * fromIntegral (totalCount h) + 0.5
totals = U.scanl f (0 :: Int, 0) withIndex
where
f (_, v') (i, v) = (i, v' + v)
withIndex = U.imap (,) (counts h)
|
joshbohde/hdr-histogram
|
src/Data/HdrHistogram.hs
|
gpl-3.0
| 3,657 | 0 | 13 | 907 | 957 | 528 | 429 | -1 | -1 |
module Simplify where
import Expr
import Lit
simplify :: Expr -> Either String Lit
simplify = simp
simp :: Expr -> Either String Lit
simp e = Left "tst"
simp (Add x y) = Left "" --case simplify x of
{-
simp (Sub x y) =
simp (Mul x y) =
simp (Div x y) =
-}
{-
simp :: Expr -> Either String Lit
simp (Add x y) = if areFloats (Add x y) then
Right (fromRight (eval Empty (Add x y)))
else case eval Empty x of
Left s -> Left "x"
Right v -> case eval Empty y of
Left ss -> Left $ show v ++ "+" ++ show ss
Right vv -> Left $ show v ++ "+" ++ show vv
-- function to convert variable expression to variable name
getVarName :: Expr -> String
getVarName (Ident x) = x
-- function to convert expression name to symbol
stringToSymbol :: Expr -> String
stringToSymbol (Add x y) = show $ show x ++ "+" ++ show y
-- function that returns true if operand is ident
isIdent :: Expr -> Bool
isIdent (Ident x) = True
isIdent _ = False
-- function to decide if x or y is a variable
areIdents :: Expr -> Bool
areIdents e = not $ areFloats e
-- function that returns true if both operands are floats
areFloats :: Expr -> Bool
areFloats e = case eval Empty e of
Right v -> True
Left s -> False
-- function that returns true if operand is float
isFloat :: Expr -> Bool
isFloat (Val x) = True
isFloat _ = False
-}
|
MaximKN/Haskell1
|
src/Simplify.hs
|
gpl-3.0
| 1,388 | 0 | 7 | 374 | 76 | 41 | 35 | 8 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Database.Design.Ampersand.Output.ToJSON.MySQLInstaller
(MySQLInstaller)
where
import Database.Design.Ampersand.Output.ToJSON.JSONutils
import Database.Design.Ampersand.Prototype.Generate
data MySQLInstaller = MySQLInstaller
{ msiJSONallDBstructQueries :: [String]
, msiJSONallDefPopQueries :: [String]
} deriving (Generic, Show)
instance ToJSON MySQLInstaller where
toJSON = amp2Jason
instance JSON FSpec MySQLInstaller where
fromAmpersand fSpec _ = MySQLInstaller
{ msiJSONallDBstructQueries = generateDBstructQueries fSpec
, msiJSONallDefPopQueries = generateAllDefPopQueries fSpec
}
|
4ZP6Capstone2015/ampersand
|
src/Database/Design/Ampersand/Output/ToJSON/MySQLInstaller.hs
|
gpl-3.0
| 725 | 0 | 9 | 91 | 126 | 78 | 48 | 17 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- |
-- Module : Network.Google.Internal.Logger
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
--
-- Types and functions for constructing loggers and emitting log messages.
module Network.Google.Internal.Logger
(
-- * Constructing a Logger
Logger
, newLogger
-- * Levels
, LogLevel (..)
, logError
, logInfo
, logDebug
, logTrace
-- * Building Messages
, ToLog (..)
, buildLines
) where
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO (..))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.ByteString.Builder (Builder)
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Builder as Build
import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI
import Data.Int (Int16, Int8)
import Data.List (intersperse)
import qualified Data.Text.Encoding as Text
import qualified Data.Text.Lazy as LText
import qualified Data.Text.Lazy.Encoding as LText
import Data.Word (Word16)
import Network.Google.Prelude hiding (Header, Request)
import Network.HTTP.Conduit
import Network.HTTP.Types
import Numeric (showFFloat)
import System.IO
-- | A function threaded through various request and serialisation routines
-- to log informational and debug messages.
type Logger = LogLevel -> Builder -> IO ()
data LogLevel
= Info -- ^ Info messages supplied by the user - this level is not emitted by the library.
| Error -- ^ Error messages only.
| Debug -- ^ Useful debug information + info + error levels.
| Trace -- ^ Includes potentially credentials metadata, and non-streaming response bodies.
deriving (Eq, Ord, Enum, Show, Data, Typeable)
-- | This is a primitive logger which can be used to log builds to a 'Handle'.
--
-- /Note:/ A more sophisticated logging library such as
-- <http://hackage.haskell.org/package/tinylog tinylog> or
-- <http://hackage.haskell.org/package/FastLogger fast-logger>
-- should be used in production code.
newLogger :: MonadIO m => LogLevel -> Handle -> m Logger
newLogger x hd = liftIO $ do
hSetBinaryMode hd True
hSetBuffering hd LineBuffering
return $ \y b ->
when (x >= y) $
Build.hPutBuilder hd (b <> "\n")
logError, logInfo, logDebug, logTrace
:: (MonadIO m, ToLog a) => Logger -> a -> m ()
logError f = liftIO . f Error . build
logInfo f = liftIO . f Info . build
logDebug f = liftIO . f Debug . build
logTrace f = liftIO . f Trace . build
class ToLog a where
-- | Convert a value to a loggable builder.
build :: a -> Builder
instance ToLog Builder where build = id
instance ToLog LBS.ByteString where build = Build.lazyByteString
instance ToLog ByteString where build = Build.byteString
instance ToLog Int where build = Build.intDec
instance ToLog Int8 where build = Build.int8Dec
instance ToLog Int16 where build = Build.int16Dec
instance ToLog Int32 where build = Build.int32Dec
instance ToLog Int64 where build = Build.int64Dec
instance ToLog Integer where build = Build.integerDec
instance ToLog Word where build = Build.wordDec
instance ToLog Word8 where build = Build.word8Dec
instance ToLog Word16 where build = Build.word16Dec
instance ToLog Word32 where build = Build.word32Dec
instance ToLog Word64 where build = Build.word64Dec
instance ToLog UTCTime where build = Build.stringUtf8 . show
instance ToLog Float where build = build . ($ "") . showFFloat Nothing
instance ToLog Double where build = build . ($ "") . showFFloat Nothing
instance ToLog Text where build = build . Text.encodeUtf8
instance ToLog LText.Text where build = build . LText.encodeUtf8
instance ToLog Char where build = build . BS8.singleton
instance ToLog [Char] where build = build . BS8.pack
instance ToLog StdMethod where build = build . renderStdMethod
-- | Intercalate a list of 'Builder's with newlines.
buildLines :: [Builder] -> Builder
buildLines = mconcat . intersperse "\n"
instance ToLog a => ToLog (CI a) where
build = build . CI.foldedCase
instance ToLog a => ToLog (Maybe a) where
build Nothing = "Nothing"
build (Just x) = "Just " <> build x
instance ToLog Bool where
build True = "True"
build False = "False"
instance ToLog Status where
build x = build (statusCode x) <> " " <> build (statusMessage x)
instance ToLog [Header] where
build = mconcat
. intersperse "; "
. map (\(k, v) -> build k <> ": " <> build v)
instance ToLog HttpVersion where
build HttpVersion{..} =
"HTTP/"
<> build httpMajor
<> build '.'
<> build httpMinor
instance ToLog RequestBody where
build = \case
RequestBodyBuilder n _ -> " <msger:" <> build n <> ">"
RequestBodyStream n _ -> " <stream:" <> build n <> ">"
RequestBodyLBS lbs
| n <= 4096 -> build lbs
| otherwise -> " <lazy:" <> build n <> ">"
where
n = LBS.length lbs
RequestBodyBS bs
| n <= 4096 -> build bs
| otherwise -> " <strict:" <> build n <> ">"
where
n = BS.length bs
_ -> " <chunked>"
instance ToLog HttpException where
build x = "[HttpException] {\n" <> build (show x) <> "\n}"
instance ToLog Request where
build x = buildLines
[ "[Client Request] {"
, " host = " <> build (host x) <> ":" <> build (port x)
, " secure = " <> build (secure x)
, " method = " <> build (method x)
, " timeout = " <> build (show (responseTimeout x))
, " redirects = " <> build (redirectCount x)
, " path = " <> build (path x)
, " query = " <> build (queryString x)
, " headers = " <> build (requestHeaders x)
, " body = " <> build (requestBody x)
, "}"
]
instance ToLog (Response a) where
build x = buildLines
[ "[Client Response] {"
, " status = " <> build (responseStatus x)
, " headers = " <> build (responseHeaders x)
, "}"
]
|
rueshyna/gogol
|
gogol/src/Network/Google/Internal/Logger.hs
|
mpl-2.0
| 7,057 | 0 | 13 | 2,155 | 1,685 | 909 | 776 | 137 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.YouTubeReporting.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.YouTubeReporting.Types.Product where
import Network.Google.Prelude
import Network.Google.YouTubeReporting.Types.Sum
-- | Response message for ReportingService.ListReports.
--
-- /See:/ 'listReportsResponse' smart constructor.
data ListReportsResponse = ListReportsResponse'
{ _lrrNextPageToken :: !(Maybe Text)
, _lrrReports :: !(Maybe [Report])
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListReportsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lrrNextPageToken'
--
-- * 'lrrReports'
listReportsResponse
:: ListReportsResponse
listReportsResponse =
ListReportsResponse'
{ _lrrNextPageToken = Nothing
, _lrrReports = Nothing
}
-- | A token to retrieve next page of results. Pass this value in the
-- ListReportsRequest.page_token field in the subsequent call to
-- \`ListReports\` method to retrieve the next page of results.
lrrNextPageToken :: Lens' ListReportsResponse (Maybe Text)
lrrNextPageToken
= lens _lrrNextPageToken
(\ s a -> s{_lrrNextPageToken = a})
-- | The list of report types.
lrrReports :: Lens' ListReportsResponse [Report]
lrrReports
= lens _lrrReports (\ s a -> s{_lrrReports = a}) .
_Default
. _Coerce
instance FromJSON ListReportsResponse where
parseJSON
= withObject "ListReportsResponse"
(\ o ->
ListReportsResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "reports" .!= mempty))
instance ToJSON ListReportsResponse where
toJSON ListReportsResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lrrNextPageToken,
("reports" .=) <$> _lrrReports])
-- | A generic empty message that you can re-use to avoid defining duplicated
-- empty messages in your APIs. A typical example is to use it as the
-- request or the response type of an API method. For instance: service Foo
-- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The
-- JSON representation for \`Empty\` is empty JSON object \`{}\`.
--
-- /See:/ 'empty' smart constructor.
data Empty =
Empty'
deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'Empty' with the minimum fields required to make a request.
--
empty
:: Empty
empty = Empty'
instance FromJSON Empty where
parseJSON = withObject "Empty" (\ o -> pure Empty')
instance ToJSON Empty where
toJSON = const emptyObject
-- | A report\'s metadata including the URL from which the report itself can
-- be downloaded.
--
-- /See:/ 'report' smart constructor.
data Report = Report'
{ _rJobId :: !(Maybe Text)
, _rStartTime :: !(Maybe DateTime')
, _rDownloadURL :: !(Maybe Text)
, _rEndTime :: !(Maybe DateTime')
, _rId :: !(Maybe Text)
, _rCreateTime :: !(Maybe DateTime')
, _rJobExpireTime :: !(Maybe DateTime')
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'Report' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rJobId'
--
-- * 'rStartTime'
--
-- * 'rDownloadURL'
--
-- * 'rEndTime'
--
-- * 'rId'
--
-- * 'rCreateTime'
--
-- * 'rJobExpireTime'
report
:: Report
report =
Report'
{ _rJobId = Nothing
, _rStartTime = Nothing
, _rDownloadURL = Nothing
, _rEndTime = Nothing
, _rId = Nothing
, _rCreateTime = Nothing
, _rJobExpireTime = Nothing
}
-- | The ID of the job that created this report.
rJobId :: Lens' Report (Maybe Text)
rJobId = lens _rJobId (\ s a -> s{_rJobId = a})
-- | The start of the time period that the report instance covers. The value
-- is inclusive.
rStartTime :: Lens' Report (Maybe UTCTime)
rStartTime
= lens _rStartTime (\ s a -> s{_rStartTime = a}) .
mapping _DateTime
-- | The URL from which the report can be downloaded (max. 1000 characters).
rDownloadURL :: Lens' Report (Maybe Text)
rDownloadURL
= lens _rDownloadURL (\ s a -> s{_rDownloadURL = a})
-- | The end of the time period that the report instance covers. The value is
-- exclusive.
rEndTime :: Lens' Report (Maybe UTCTime)
rEndTime
= lens _rEndTime (\ s a -> s{_rEndTime = a}) .
mapping _DateTime
-- | The server-generated ID of the report.
rId :: Lens' Report (Maybe Text)
rId = lens _rId (\ s a -> s{_rId = a})
-- | The date\/time when this report was created.
rCreateTime :: Lens' Report (Maybe UTCTime)
rCreateTime
= lens _rCreateTime (\ s a -> s{_rCreateTime = a}) .
mapping _DateTime
-- | The date\/time when the job this report belongs to will expire\/expired.
rJobExpireTime :: Lens' Report (Maybe UTCTime)
rJobExpireTime
= lens _rJobExpireTime
(\ s a -> s{_rJobExpireTime = a})
. mapping _DateTime
instance FromJSON Report where
parseJSON
= withObject "Report"
(\ o ->
Report' <$>
(o .:? "jobId") <*> (o .:? "startTime") <*>
(o .:? "downloadUrl")
<*> (o .:? "endTime")
<*> (o .:? "id")
<*> (o .:? "createTime")
<*> (o .:? "jobExpireTime"))
instance ToJSON Report where
toJSON Report'{..}
= object
(catMaybes
[("jobId" .=) <$> _rJobId,
("startTime" .=) <$> _rStartTime,
("downloadUrl" .=) <$> _rDownloadURL,
("endTime" .=) <$> _rEndTime, ("id" .=) <$> _rId,
("createTime" .=) <$> _rCreateTime,
("jobExpireTime" .=) <$> _rJobExpireTime])
-- | Response message for ReportingService.ListReportTypes.
--
-- /See:/ 'listReportTypesResponse' smart constructor.
data ListReportTypesResponse = ListReportTypesResponse'
{ _lrtrNextPageToken :: !(Maybe Text)
, _lrtrReportTypes :: !(Maybe [ReportType])
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListReportTypesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lrtrNextPageToken'
--
-- * 'lrtrReportTypes'
listReportTypesResponse
:: ListReportTypesResponse
listReportTypesResponse =
ListReportTypesResponse'
{ _lrtrNextPageToken = Nothing
, _lrtrReportTypes = Nothing
}
-- | A token to retrieve next page of results. Pass this value in the
-- ListReportTypesRequest.page_token field in the subsequent call to
-- \`ListReportTypes\` method to retrieve the next page of results.
lrtrNextPageToken :: Lens' ListReportTypesResponse (Maybe Text)
lrtrNextPageToken
= lens _lrtrNextPageToken
(\ s a -> s{_lrtrNextPageToken = a})
-- | The list of report types.
lrtrReportTypes :: Lens' ListReportTypesResponse [ReportType]
lrtrReportTypes
= lens _lrtrReportTypes
(\ s a -> s{_lrtrReportTypes = a})
. _Default
. _Coerce
instance FromJSON ListReportTypesResponse where
parseJSON
= withObject "ListReportTypesResponse"
(\ o ->
ListReportTypesResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "reportTypes" .!= mempty))
instance ToJSON ListReportTypesResponse where
toJSON ListReportTypesResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lrtrNextPageToken,
("reportTypes" .=) <$> _lrtrReportTypes])
-- | Media resource.
--
-- /See:/ 'media' smart constructor.
newtype Media = Media'
{ _mResourceName :: Maybe Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'Media' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mResourceName'
media
:: Media
media =
Media'
{ _mResourceName = Nothing
}
-- | Name of the media resource.
mResourceName :: Lens' Media (Maybe Text)
mResourceName
= lens _mResourceName
(\ s a -> s{_mResourceName = a})
instance FromJSON Media where
parseJSON
= withObject "Media"
(\ o -> Media' <$> (o .:? "resourceName"))
instance ToJSON Media where
toJSON Media'{..}
= object
(catMaybes [("resourceName" .=) <$> _mResourceName])
-- | A job creating reports of a specific type.
--
-- /See:/ 'job' smart constructor.
data Job = Job'
{ _jName :: !(Maybe Text)
, _jId :: !(Maybe Text)
, _jSystemManaged :: !(Maybe Bool)
, _jReportTypeId :: !(Maybe Text)
, _jExpireTime :: !(Maybe DateTime')
, _jCreateTime :: !(Maybe DateTime')
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'Job' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'jName'
--
-- * 'jId'
--
-- * 'jSystemManaged'
--
-- * 'jReportTypeId'
--
-- * 'jExpireTime'
--
-- * 'jCreateTime'
job
:: Job
job =
Job'
{ _jName = Nothing
, _jId = Nothing
, _jSystemManaged = Nothing
, _jReportTypeId = Nothing
, _jExpireTime = Nothing
, _jCreateTime = Nothing
}
-- | The name of the job (max. 100 characters).
jName :: Lens' Job (Maybe Text)
jName = lens _jName (\ s a -> s{_jName = a})
-- | The server-generated ID of the job (max. 40 characters).
jId :: Lens' Job (Maybe Text)
jId = lens _jId (\ s a -> s{_jId = a})
-- | True if this a system-managed job that cannot be modified by the user;
-- otherwise false.
jSystemManaged :: Lens' Job (Maybe Bool)
jSystemManaged
= lens _jSystemManaged
(\ s a -> s{_jSystemManaged = a})
-- | The type of reports this job creates. Corresponds to the ID of a
-- ReportType.
jReportTypeId :: Lens' Job (Maybe Text)
jReportTypeId
= lens _jReportTypeId
(\ s a -> s{_jReportTypeId = a})
-- | The date\/time when this job will expire\/expired. After a job expired,
-- no new reports are generated.
jExpireTime :: Lens' Job (Maybe UTCTime)
jExpireTime
= lens _jExpireTime (\ s a -> s{_jExpireTime = a}) .
mapping _DateTime
-- | The creation date\/time of the job.
jCreateTime :: Lens' Job (Maybe UTCTime)
jCreateTime
= lens _jCreateTime (\ s a -> s{_jCreateTime = a}) .
mapping _DateTime
instance FromJSON Job where
parseJSON
= withObject "Job"
(\ o ->
Job' <$>
(o .:? "name") <*> (o .:? "id") <*>
(o .:? "systemManaged")
<*> (o .:? "reportTypeId")
<*> (o .:? "expireTime")
<*> (o .:? "createTime"))
instance ToJSON Job where
toJSON Job'{..}
= object
(catMaybes
[("name" .=) <$> _jName, ("id" .=) <$> _jId,
("systemManaged" .=) <$> _jSystemManaged,
("reportTypeId" .=) <$> _jReportTypeId,
("expireTime" .=) <$> _jExpireTime,
("createTime" .=) <$> _jCreateTime])
-- | Response message for ReportingService.ListJobs.
--
-- /See:/ 'listJobsResponse' smart constructor.
data ListJobsResponse = ListJobsResponse'
{ _ljrNextPageToken :: !(Maybe Text)
, _ljrJobs :: !(Maybe [Job])
} deriving (Eq,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:
--
-- * 'ljrNextPageToken'
--
-- * 'ljrJobs'
listJobsResponse
:: ListJobsResponse
listJobsResponse =
ListJobsResponse'
{ _ljrNextPageToken = Nothing
, _ljrJobs = Nothing
}
-- | A token to retrieve next page of results. Pass this value in the
-- ListJobsRequest.page_token field in the subsequent call to \`ListJobs\`
-- method to retrieve the next page of results.
ljrNextPageToken :: Lens' ListJobsResponse (Maybe Text)
ljrNextPageToken
= lens _ljrNextPageToken
(\ s a -> s{_ljrNextPageToken = a})
-- | The list of jobs.
ljrJobs :: Lens' ListJobsResponse [Job]
ljrJobs
= lens _ljrJobs (\ s a -> s{_ljrJobs = a}) . _Default
. _Coerce
instance FromJSON ListJobsResponse where
parseJSON
= withObject "ListJobsResponse"
(\ o ->
ListJobsResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "jobs" .!= mempty))
instance ToJSON ListJobsResponse where
toJSON ListJobsResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _ljrNextPageToken,
("jobs" .=) <$> _ljrJobs])
-- | A report type.
--
-- /See:/ 'reportType' smart constructor.
data ReportType = ReportType'
{ _rtName :: !(Maybe Text)
, _rtId :: !(Maybe Text)
, _rtDeprecateTime :: !(Maybe DateTime')
, _rtSystemManaged :: !(Maybe Bool)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ReportType' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rtName'
--
-- * 'rtId'
--
-- * 'rtDeprecateTime'
--
-- * 'rtSystemManaged'
reportType
:: ReportType
reportType =
ReportType'
{ _rtName = Nothing
, _rtId = Nothing
, _rtDeprecateTime = Nothing
, _rtSystemManaged = Nothing
}
-- | The name of the report type (max. 100 characters).
rtName :: Lens' ReportType (Maybe Text)
rtName = lens _rtName (\ s a -> s{_rtName = a})
-- | The ID of the report type (max. 100 characters).
rtId :: Lens' ReportType (Maybe Text)
rtId = lens _rtId (\ s a -> s{_rtId = a})
-- | The date\/time when this report type was\/will be deprecated.
rtDeprecateTime :: Lens' ReportType (Maybe UTCTime)
rtDeprecateTime
= lens _rtDeprecateTime
(\ s a -> s{_rtDeprecateTime = a})
. mapping _DateTime
-- | True if this a system-managed report type; otherwise false. Reporting
-- jobs for system-managed report types are created automatically and can
-- thus not be used in the \`CreateJob\` method.
rtSystemManaged :: Lens' ReportType (Maybe Bool)
rtSystemManaged
= lens _rtSystemManaged
(\ s a -> s{_rtSystemManaged = a})
instance FromJSON ReportType where
parseJSON
= withObject "ReportType"
(\ o ->
ReportType' <$>
(o .:? "name") <*> (o .:? "id") <*>
(o .:? "deprecateTime")
<*> (o .:? "systemManaged"))
instance ToJSON ReportType where
toJSON ReportType'{..}
= object
(catMaybes
[("name" .=) <$> _rtName, ("id" .=) <$> _rtId,
("deprecateTime" .=) <$> _rtDeprecateTime,
("systemManaged" .=) <$> _rtSystemManaged])
|
rueshyna/gogol
|
gogol-youtube-reporting/gen/Network/Google/YouTubeReporting/Types/Product.hs
|
mpl-2.0
| 15,556 | 0 | 17 | 4,069 | 3,086 | 1,777 | 1,309 | 346 | 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.Routes.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)
--
-- Returns the specified Route resource. Get a list of available routes by
-- making a list() request.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.routes.get@.
module Network.Google.Resource.Compute.Routes.Get
(
-- * REST Resource
RoutesGetResource
-- * Creating a Request
, routesGet
, RoutesGet
-- * Request Lenses
, rrProject
, rrRoute
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.routes.get@ method which the
-- 'RoutesGet' request conforms to.
type RoutesGetResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"routes" :>
Capture "route" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Route
-- | Returns the specified Route resource. Get a list of available routes by
-- making a list() request.
--
-- /See:/ 'routesGet' smart constructor.
data RoutesGet = RoutesGet'
{ _rrProject :: !Text
, _rrRoute :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'RoutesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rrProject'
--
-- * 'rrRoute'
routesGet
:: Text -- ^ 'rrProject'
-> Text -- ^ 'rrRoute'
-> RoutesGet
routesGet pRrProject_ pRrRoute_ =
RoutesGet'
{ _rrProject = pRrProject_
, _rrRoute = pRrRoute_
}
-- | Project ID for this request.
rrProject :: Lens' RoutesGet Text
rrProject
= lens _rrProject (\ s a -> s{_rrProject = a})
-- | Name of the Route resource to return.
rrRoute :: Lens' RoutesGet Text
rrRoute = lens _rrRoute (\ s a -> s{_rrRoute = a})
instance GoogleRequest RoutesGet where
type Rs RoutesGet = Route
type Scopes RoutesGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient RoutesGet'{..}
= go _rrProject _rrRoute (Just AltJSON)
computeService
where go
= buildClient (Proxy :: Proxy RoutesGetResource)
mempty
|
rueshyna/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/Routes/Get.hs
|
mpl-2.0
| 3,148 | 0 | 15 | 782 | 393 | 237 | 156 | 63 | 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.Gmail.Users.Drafts.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)
--
-- Immediately and permanently deletes the specified draft. Does not simply
-- trash it.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.drafts.delete@.
module Network.Google.Resource.Gmail.Users.Drafts.Delete
(
-- * REST Resource
UsersDraftsDeleteResource
-- * Creating a Request
, usersDraftsDelete
, UsersDraftsDelete
-- * Request Lenses
, uddXgafv
, uddUploadProtocol
, uddAccessToken
, uddUploadType
, uddUserId
, uddId
, uddCallback
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.drafts.delete@ method which the
-- 'UsersDraftsDelete' request conforms to.
type UsersDraftsDeleteResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"drafts" :>
Capture "id" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Immediately and permanently deletes the specified draft. Does not simply
-- trash it.
--
-- /See:/ 'usersDraftsDelete' smart constructor.
data UsersDraftsDelete =
UsersDraftsDelete'
{ _uddXgafv :: !(Maybe Xgafv)
, _uddUploadProtocol :: !(Maybe Text)
, _uddAccessToken :: !(Maybe Text)
, _uddUploadType :: !(Maybe Text)
, _uddUserId :: !Text
, _uddId :: !Text
, _uddCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersDraftsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uddXgafv'
--
-- * 'uddUploadProtocol'
--
-- * 'uddAccessToken'
--
-- * 'uddUploadType'
--
-- * 'uddUserId'
--
-- * 'uddId'
--
-- * 'uddCallback'
usersDraftsDelete
:: Text -- ^ 'uddId'
-> UsersDraftsDelete
usersDraftsDelete pUddId_ =
UsersDraftsDelete'
{ _uddXgafv = Nothing
, _uddUploadProtocol = Nothing
, _uddAccessToken = Nothing
, _uddUploadType = Nothing
, _uddUserId = "me"
, _uddId = pUddId_
, _uddCallback = Nothing
}
-- | V1 error format.
uddXgafv :: Lens' UsersDraftsDelete (Maybe Xgafv)
uddXgafv = lens _uddXgafv (\ s a -> s{_uddXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uddUploadProtocol :: Lens' UsersDraftsDelete (Maybe Text)
uddUploadProtocol
= lens _uddUploadProtocol
(\ s a -> s{_uddUploadProtocol = a})
-- | OAuth access token.
uddAccessToken :: Lens' UsersDraftsDelete (Maybe Text)
uddAccessToken
= lens _uddAccessToken
(\ s a -> s{_uddAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
uddUploadType :: Lens' UsersDraftsDelete (Maybe Text)
uddUploadType
= lens _uddUploadType
(\ s a -> s{_uddUploadType = a})
-- | The user\'s email address. The special value \`me\` can be used to
-- indicate the authenticated user.
uddUserId :: Lens' UsersDraftsDelete Text
uddUserId
= lens _uddUserId (\ s a -> s{_uddUserId = a})
-- | The ID of the draft to delete.
uddId :: Lens' UsersDraftsDelete Text
uddId = lens _uddId (\ s a -> s{_uddId = a})
-- | JSONP
uddCallback :: Lens' UsersDraftsDelete (Maybe Text)
uddCallback
= lens _uddCallback (\ s a -> s{_uddCallback = a})
instance GoogleRequest UsersDraftsDelete where
type Rs UsersDraftsDelete = ()
type Scopes UsersDraftsDelete =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.addons.current.action.compose",
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/gmail.modify"]
requestClient UsersDraftsDelete'{..}
= go _uddUserId _uddId _uddXgafv _uddUploadProtocol
_uddAccessToken
_uddUploadType
_uddCallback
(Just AltJSON)
gmailService
where go
= buildClient
(Proxy :: Proxy UsersDraftsDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Drafts/Delete.hs
|
mpl-2.0
| 5,096 | 0 | 19 | 1,257 | 791 | 462 | 329 | 115 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.HUnit
import Test.HUnit
import Control.Monad (when)
import Control.Monad.State
import qualified Data.Set as Set
import Data.Monoid
import Data.List
import System.Exit (exitFailure)
import DBus (objectPath_, busName_, ReceivedMessage(ReceivedMethodReturn), firstSerial, methodReturn)
import Bustle.Types
import Bustle.Renderer
main :: IO ()
main = defaultMain tests
where
tests = [ testGroup "Disconnections don't affect participants"
[ testCase "One participant, no disconnection" test_participants
, testCase "One participant, which disconnects" test_participants_with_disconnect
]
, testGroup "Incremential rendering matches all-at-once rendering"
[ testCase "rrCentreOffset" $ test_incremental_simple rrCentreOffset
, testCase "rrTopOffset" $ test_incremental_simple rrTopOffset
, testCase "rrShapes" $ test_incremental_list rrShapes
, testCase "rrRegions" $ test_incremental_list rrRegions
, testCase "rrApplications" $ test_incremental_simple rrApplications
, testCase "rrWarnings" $ test_incremental_simple rrWarnings
]
]
-- Tests that services visible in a log are listed as participants even if they
-- disconnect from the bus before the end of the log. This is a regression test
-- for a bug I almost introduced.
activeService = UniqueName ":1.1"
dummyReceivedMessage = ReceivedMethodReturn firstSerial (methodReturn firstSerial)
swaddle messages timestamps = map (\(e, ts) -> Detailed ts e 0 dummyReceivedMessage)
(zip messages timestamps)
sessionLogWithoutDisconnect =
[ NOCEvent $ Connected activeService
, MessageEvent $ Signal (U activeService) Nothing $ Member (objectPath_ "/") Nothing "Hello"
]
sessionLogWithDisconnect = sessionLogWithoutDisconnect ++ [ NOCEvent $ Disconnected activeService ]
expectedParticipants = [ (activeService, Set.empty) ]
test_ l expected = expected @=? ps
where
rr = process (swaddle l [1..]) []
ps = sessionParticipants (rrApplications rr)
test_participants = test_ sessionLogWithoutDisconnect expectedParticipants
test_participants_with_disconnect = test_ sessionLogWithDisconnect expectedParticipants
-- Test that incremental rendering matches all-at-once rendering
u1 = UniqueName ":1.1"
u2 = UniqueName ":2.2"
-- This is enough names that the log needs to be rejustified to the top
os = map (OtherName . busName_ . ("Foo." ++) . (:"potato")) ['a'..'z']
m = Member "/" Nothing "Hi"
bareLog = [ NOCEvent $ Connected u1
, MessageEvent $ Signal (U u1) Nothing m
, NOCEvent $ Connected u2
]
++ map (\o -> NOCEvent (NameChanged o (Claimed u2))) os ++
[ MessageEvent $ MethodCall 0 (U u1) (O (head os)) m ]
sessionLog = swaddle bareLog [1,3..]
systemLog = swaddle bareLog [2,4..]
test_incremental_simple :: (Show b, Eq b)
=> (RendererResult Participants -> b)
-> Assertion
test_incremental_simple f =
test_incremental $ \full incremental -> f full @=? f incremental
test_incremental_list :: (Show b, Eq b)
=> (RendererResult Participants -> [b])
-> Assertion
test_incremental_list f =
test_incremental $ \fullRR incrementalRR -> do
let full = f fullRR
incr = f incrementalRR
-- Compare each element in turn
mapM_ (uncurry (@=?)) $ zip full incr
when (length full /= length incr) $
full @=? incr
test_incremental :: ( RendererResult Participants
-> RendererResult Participants
-> Assertion
)
-> Assertion
test_incremental f = f fullRR incrementalRR
-- TODO: it should be possible to make this work for side-by-side logs too.
-- Currently it doesn't seem to...
fullRR, incrementalRR :: RendererResult Participants
fullRR = process sessionLog []
incrementalRR = mconcat rrs
where
processOne m = state $ processSome [m] []
(rrs, _) = runState (mapM processOne sessionLog) rendererStateNew
|
wjt/bustle
|
Test/Renderer.hs
|
lgpl-2.1
| 4,353 | 0 | 14 | 1,067 | 1,002 | 529 | 473 | 77 | 1 |
module RomanNumerals where
import Data.List
type Numeral = String
type MixedNumber = (String, Int)
data RomanDigit = RomanDigit String Int
digits = reverse [
RomanDigit "I" 1,
RomanDigit "IV" 4,
RomanDigit "V" 5,
RomanDigit "IX" 9,
RomanDigit "X" 10,
RomanDigit "XL" 40,
RomanDigit "L" 50,
RomanDigit "XM" 90,
RomanDigit "M" 100
]
convert :: Int -> Numeral
convert n = concat $ unfoldr nextRomanNumber n
nextRomanNumber :: Int -> Maybe MixedNumber
nextRomanNumber n = fmap next $ find isUsableDigit digits
where
isUsableDigit (RomanDigit _ number) = number <= n
next (RomanDigit numeral number) = (numeral, n - number)
|
joelea/haskell-roman-numerals
|
src/RomanNumerals.hs
|
apache-2.0
| 717 | 0 | 9 | 196 | 224 | 117 | 107 | 21 | 1 |
-- Type-Safe Observable sharing
-- shallow embedding
newtype Bit = Bit [Bool] deriving Show
xor :: Bit -> Bit -> Bit
xor (Bit xs) (Bit ys) = Bit $ zipWith (/=) xs ys
delay :: Bit -> Bit
delay (Bit xs) = Bit $ False : xs
run :: (Bit -> Bit) -> [Bool] -> [Bool]
run f bs = rs
where
(Bit rs) = f (Bit bs)
-- > run parity [True, False,True,False]
-- [True,True,False,False]
parity :: Bit -> Bit
parity input = output
where
output = xor (delay output) input
|
egaburov/funstuff
|
Haskell/sharing/observable0.hs
|
apache-2.0
| 477 | 0 | 9 | 116 | 192 | 103 | 89 | 11 | 1 |
import Helpers.ListHelpers (cartesianProduct)
isVisible [(x1,y1),(x2,y2)] = 1 == gcd (x1 - x2) (y1 - y2)
-- Probably correct.
a331771 n = length $ filter isVisible $ cartesianProduct 2 points where
points = [(x, y) | x <- [1..n], y <- [1..n]]
|
peterokagey/haskellOEIS
|
src/Sandbox/VisiblePoints.hs
|
apache-2.0
| 247 | 0 | 10 | 45 | 127 | 70 | 57 | 4 | 1 |
{-| Implementation of cluster-wide logic.
This module holds all pure cluster-logic; I\/O related functionality
goes into the /Main/ module for the individual binaries.
-}
{-
Copyright (C) 2009, 2010, 2011, 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.Cluster
(
-- * Types
AllocDetails(..)
, Table(..)
, CStats(..)
, AllocNodes
, AllocResult
, AllocMethod
, GenericAllocSolutionList
, AllocSolutionList
-- * Generic functions
, totalResources
, computeAllocationDelta
, hasRequiredNetworks
-- * First phase functions
, computeBadItems
-- * Second phase functions
, printSolutionLine
, formatCmds
, involvedNodes
, getMoves
, splitJobs
-- * Display functions
, printNodes
, printInsts
-- * Balacing functions
, doNextBalance
, tryBalance
, iMoveToJob
-- * IAllocator functions
, genAllocNodes
, tryAlloc
, tryGroupAlloc
, tryMGAlloc
, filterMGResults
, sortMGResults
, tryChangeGroup
, allocList
-- * Allocation functions
, iterateAlloc
, tieredAlloc
-- * Node group functions
, instanceGroup
, findSplitInstances
) where
import Control.Applicative ((<$>), liftA2)
import Control.Arrow ((&&&))
import Control.Monad (unless)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Maybe (fromJust, fromMaybe, isJust, isNothing)
import Data.Ord (comparing)
import Text.Printf (printf)
import Ganeti.BasicTypes
import Ganeti.HTools.AlgorithmParams (AlgorithmOptions(..), defaultOptions)
import qualified Ganeti.HTools.Container as Container
import Ganeti.HTools.Cluster.AllocationSolution
( AllocElement, GenericAllocSolution(..) , AllocSolution, emptyAllocSolution
, sumAllocs, extractNl, updateIl
, annotateSolution, solutionDescription, collapseFailures
, emptyAllocCollection, concatAllocCollections, collectionToSolution )
import Ganeti.HTools.Cluster.Evacuate ( EvacSolution(..), emptyEvacSolution
, updateEvacSolution, reverseEvacSolution
, nodeEvacInstance)
import Ganeti.HTools.Cluster.Metrics ( compCV, compCVfromStats
, compClusterStatistics
, updateClusterStatisticsTwice)
import Ganeti.HTools.Cluster.Moves (setInstanceLocationScore, applyMoveEx)
import Ganeti.HTools.Cluster.Utils (splitCluster, instancePriGroup
, availableGroupNodes, iMoveToJob)
import Ganeti.HTools.GlobalN1 (allocGlobalN1)
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Nic as Nic
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Group as Group
import Ganeti.HTools.Types
import Ganeti.Compat
import Ganeti.Utils
import Ganeti.Utils.Statistics
import Ganeti.Types (EvacMode(..))
-- * Types
-- | Allocation details for an instance, specifying
-- required number of nodes, and
-- an optional group (name) to allocate to
data AllocDetails = AllocDetails Int (Maybe String)
deriving (Show)
-- | Allocation results, as used in 'iterateAlloc' and 'tieredAlloc'.
type AllocResult = (FailStats, Node.List, Instance.List,
[Instance.Instance], [CStats])
-- | Type alias for easier handling.
type GenericAllocSolutionList a =
[(Instance.Instance, GenericAllocSolution a)]
type AllocSolutionList = GenericAllocSolutionList Score
-- | A type denoting the valid allocation mode/pairs.
--
-- For a one-node allocation, this will be a @Left ['Ndx']@, whereas
-- for a two-node allocation, this will be a @Right [('Ndx',
-- ['Ndx'])]@. In the latter case, the list is basically an
-- association list, grouped by primary node and holding the potential
-- secondary nodes in the sub-list.
type AllocNodes = Either [Ndx] [(Ndx, [Ndx])]
-- | The complete state for the balancing solution.
data Table = Table Node.List Instance.List Score [Placement]
deriving (Show)
-- | Cluster statistics data type.
data CStats = CStats
{ csFmem :: Integer -- ^ Cluster free mem
, csFdsk :: Integer -- ^ Cluster free disk
, csFspn :: Integer -- ^ Cluster free spindles
, csAmem :: Integer -- ^ Cluster allocatable mem
, csAdsk :: Integer -- ^ Cluster allocatable disk
, csAcpu :: Integer -- ^ Cluster allocatable cpus
, csMmem :: Integer -- ^ Max node allocatable mem
, csMdsk :: Integer -- ^ Max node allocatable disk
, csMcpu :: Integer -- ^ Max node allocatable cpu
, csImem :: Integer -- ^ Instance used mem
, csIdsk :: Integer -- ^ Instance used disk
, csIspn :: Integer -- ^ Instance used spindles
, csIcpu :: Integer -- ^ Instance used cpu
, csTmem :: Double -- ^ Cluster total mem
, csTdsk :: Double -- ^ Cluster total disk
, csTspn :: Double -- ^ Cluster total spindles
, csTcpu :: Double -- ^ Cluster total cpus
, csVcpu :: Integer -- ^ Cluster total virtual cpus
, csNcpu :: Double -- ^ Equivalent to 'csIcpu' but in terms of
-- physical CPUs, i.e. normalised used phys CPUs
, csXmem :: Integer -- ^ Unnacounted for mem
, csNmem :: Integer -- ^ Node own memory
, csScore :: Score -- ^ The cluster score
, csNinst :: Int -- ^ The total number of instances
} deriving (Show)
-- | A simple type for allocation functions.
type AllocMethod = Node.List -- ^ Node list
-> Instance.List -- ^ Instance list
-> Maybe Int -- ^ Optional allocation limit
-> Instance.Instance -- ^ Instance spec for allocation
-> AllocNodes -- ^ Which nodes we should allocate on
-> [Instance.Instance] -- ^ Allocated instances
-> [CStats] -- ^ Running cluster stats
-> Result AllocResult -- ^ Allocation result
-- * Utility functions
-- | Verifies the N+1 status and return the affected nodes.
verifyN1 :: [Node.Node] -> [Node.Node]
verifyN1 = filter Node.failN1
{-| Computes the pair of bad nodes and instances.
The bad node list is computed via a simple 'verifyN1' check, and the
bad instance list is the list of primary and secondary instances of
those nodes.
-}
computeBadItems :: Node.List -> Instance.List ->
([Node.Node], [Instance.Instance])
computeBadItems nl il =
let bad_nodes = verifyN1 $ getOnline nl
bad_instances = map (`Container.find` il) .
sort . nub $
concatMap (\ n -> Node.sList n ++ Node.pList n) bad_nodes
in
(bad_nodes, bad_instances)
-- | Zero-initializer for the CStats type.
emptyCStats :: CStats
emptyCStats = CStats 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
-- | Update stats with data from a new node.
updateCStats :: CStats -> Node.Node -> CStats
updateCStats cs node =
let CStats { csFmem = x_fmem, csFdsk = x_fdsk,
csAmem = x_amem, csAcpu = x_acpu, csAdsk = x_adsk,
csMmem = x_mmem, csMdsk = x_mdsk, csMcpu = x_mcpu,
csImem = x_imem, csIdsk = x_idsk, csIcpu = x_icpu,
csTmem = x_tmem, csTdsk = x_tdsk, csTcpu = x_tcpu,
csVcpu = x_vcpu, csNcpu = x_ncpu,
csXmem = x_xmem, csNmem = x_nmem, csNinst = x_ninst,
csFspn = x_fspn, csIspn = x_ispn, csTspn = x_tspn
}
= cs
inc_amem = Node.fMem node - Node.rMem node
inc_amem' = if inc_amem > 0 then inc_amem else 0
inc_adsk = Node.availDisk node
inc_imem = truncate (Node.tMem node) - Node.nMem node
- Node.xMem node - Node.fMem node
inc_icpu = Node.uCpu node
inc_idsk = truncate (Node.tDsk node) - Node.fDsk node
inc_ispn = Node.tSpindles node - Node.fSpindles node
inc_vcpu = Node.hiCpu node
inc_acpu = Node.availCpu node
inc_ncpu = fromIntegral (Node.uCpu node) /
iPolicyVcpuRatio (Node.iPolicy node)
in cs { csFmem = x_fmem + fromIntegral (Node.fMem node)
, csFdsk = x_fdsk + fromIntegral (Node.fDsk node)
, csFspn = x_fspn + fromIntegral (Node.fSpindles node)
, csAmem = x_amem + fromIntegral inc_amem'
, csAdsk = x_adsk + fromIntegral inc_adsk
, csAcpu = x_acpu + fromIntegral inc_acpu
, csMmem = max x_mmem (fromIntegral inc_amem')
, csMdsk = max x_mdsk (fromIntegral inc_adsk)
, csMcpu = max x_mcpu (fromIntegral inc_acpu)
, csImem = x_imem + fromIntegral inc_imem
, csIdsk = x_idsk + fromIntegral inc_idsk
, csIspn = x_ispn + fromIntegral inc_ispn
, csIcpu = x_icpu + fromIntegral inc_icpu
, csTmem = x_tmem + Node.tMem node
, csTdsk = x_tdsk + Node.tDsk node
, csTspn = x_tspn + fromIntegral (Node.tSpindles node)
, csTcpu = x_tcpu + Node.tCpu node
, csVcpu = x_vcpu + fromIntegral inc_vcpu
, csNcpu = x_ncpu + inc_ncpu
, csXmem = x_xmem + fromIntegral (Node.xMem node)
, csNmem = x_nmem + fromIntegral (Node.nMem node)
, csNinst = x_ninst + length (Node.pList node)
}
-- | Compute the total free disk and memory in the cluster.
totalResources :: Node.List -> CStats
totalResources nl =
let cs = foldl' updateCStats emptyCStats . Container.elems $ nl
in cs { csScore = compCV nl }
-- | Compute the delta between two cluster state.
--
-- This is used when doing allocations, to understand better the
-- available cluster resources. The return value is a triple of the
-- current used values, the delta that was still allocated, and what
-- was left unallocated.
computeAllocationDelta :: CStats -> CStats -> AllocStats
computeAllocationDelta cini cfin =
let CStats {csImem = i_imem, csIdsk = i_idsk, csIcpu = i_icpu,
csNcpu = i_ncpu, csIspn = i_ispn } = cini
CStats {csImem = f_imem, csIdsk = f_idsk, csIcpu = f_icpu,
csTmem = t_mem, csTdsk = t_dsk, csVcpu = f_vcpu,
csNcpu = f_ncpu, csTcpu = f_tcpu,
csIspn = f_ispn, csTspn = t_spn } = cfin
rini = AllocInfo { allocInfoVCpus = fromIntegral i_icpu
, allocInfoNCpus = i_ncpu
, allocInfoMem = fromIntegral i_imem
, allocInfoDisk = fromIntegral i_idsk
, allocInfoSpn = fromIntegral i_ispn
}
rfin = AllocInfo { allocInfoVCpus = fromIntegral (f_icpu - i_icpu)
, allocInfoNCpus = f_ncpu - i_ncpu
, allocInfoMem = fromIntegral (f_imem - i_imem)
, allocInfoDisk = fromIntegral (f_idsk - i_idsk)
, allocInfoSpn = fromIntegral (f_ispn - i_ispn)
}
runa = AllocInfo { allocInfoVCpus = fromIntegral (f_vcpu - f_icpu)
, allocInfoNCpus = f_tcpu - f_ncpu
, allocInfoMem = truncate t_mem - fromIntegral f_imem
, allocInfoDisk = truncate t_dsk - fromIntegral f_idsk
, allocInfoSpn = truncate t_spn - fromIntegral f_ispn
}
in (rini, rfin, runa)
-- | Compute online nodes from a 'Node.List'.
getOnline :: Node.List -> [Node.Node]
getOnline = filter (not . Node.offline) . Container.elems
-- * Balancing functions
-- | Compute best table. Note that the ordering of the arguments is important.
compareTables :: Table -> Table -> Table
compareTables a@(Table _ _ a_cv _) b@(Table _ _ b_cv _ ) =
if a_cv > b_cv then b else a
-- | Tries to allocate an instance on one given node.
allocateOnSingle :: AlgorithmOptions
-> Node.List -> Instance.Instance -> Ndx
-> OpResult AllocElement
allocateOnSingle opts nl inst new_pdx =
let p = Container.find new_pdx nl
new_inst = Instance.setBoth inst new_pdx Node.noSecondary
force = algIgnoreSoftErrors opts
in do
Instance.instMatchesPolicy inst (Node.iPolicy p) (Node.exclStorage p)
new_p <- Node.addPriEx force p inst
let new_nl = Container.add new_pdx new_p nl
new_score = compCV new_nl
return (new_nl, new_inst, [new_p], new_score)
-- | Tries to allocate an instance on a given pair of nodes.
allocateOnPair :: AlgorithmOptions
-> [Statistics]
-> Node.List -> Instance.Instance -> Ndx -> Ndx
-> OpResult AllocElement
allocateOnPair opts stats nl inst new_pdx new_sdx =
let tgt_p = Container.find new_pdx nl
tgt_s = Container.find new_sdx nl
force = algIgnoreSoftErrors opts
in do
Instance.instMatchesPolicy inst (Node.iPolicy tgt_p)
(Node.exclStorage tgt_p)
let new_inst = Instance.setBoth (setInstanceLocationScore inst tgt_p tgt_s)
new_pdx new_sdx
new_p <- Node.addPriEx force tgt_p new_inst
new_s <- Node.addSec tgt_s new_inst new_pdx
let new_nl = Container.addTwo new_pdx new_p new_sdx new_s nl
new_stats = updateClusterStatisticsTwice stats
(tgt_p, new_p) (tgt_s, new_s)
return (new_nl, new_inst, [new_p, new_s], compCVfromStats new_stats)
-- | Tries to perform an instance move and returns the best table
-- between the original one and the new one.
checkSingleStep :: Bool -- ^ Whether to unconditionally ignore soft errors
-> Table -- ^ The original table
-> Instance.Instance -- ^ The instance to move
-> Table -- ^ The current best table
-> IMove -- ^ The move to apply
-> Table -- ^ The final best table
checkSingleStep force ini_tbl target cur_tbl move =
let Table ini_nl ini_il _ ini_plc = ini_tbl
tmp_resu = applyMoveEx force ini_nl target move
in case tmp_resu of
Bad _ -> cur_tbl
Ok (upd_nl, new_inst, pri_idx, sec_idx) ->
let tgt_idx = Instance.idx target
upd_cvar = compCV upd_nl
upd_il = Container.add tgt_idx new_inst ini_il
upd_plc = (tgt_idx, pri_idx, sec_idx, move, upd_cvar):ini_plc
upd_tbl = Table upd_nl upd_il upd_cvar upd_plc
in compareTables cur_tbl upd_tbl
-- | Given the status of the current secondary as a valid new node and
-- the current candidate target node, generate the possible moves for
-- a instance.
possibleMoves :: MirrorType -- ^ The mirroring type of the instance
-> Bool -- ^ Whether the secondary node is a valid new node
-> Bool -- ^ Whether we can change the primary node
-> (Bool, Bool) -- ^ Whether migration is restricted and whether
-- the instance primary is offline
-> Ndx -- ^ Target node candidate
-> [IMove] -- ^ List of valid result moves
possibleMoves MirrorNone _ _ _ _ = []
possibleMoves MirrorExternal _ False _ _ = []
possibleMoves MirrorExternal _ True _ tdx =
[ FailoverToAny tdx ]
possibleMoves MirrorInternal _ False _ tdx =
[ ReplaceSecondary tdx ]
possibleMoves MirrorInternal _ _ (True, False) tdx =
[ ReplaceSecondary tdx
]
possibleMoves MirrorInternal True True (False, _) tdx =
[ ReplaceSecondary tdx
, ReplaceAndFailover tdx
, ReplacePrimary tdx
, FailoverAndReplace tdx
]
possibleMoves MirrorInternal True True (True, True) tdx =
[ ReplaceSecondary tdx
, ReplaceAndFailover tdx
, FailoverAndReplace tdx
]
possibleMoves MirrorInternal False True _ tdx =
[ ReplaceSecondary tdx
, ReplaceAndFailover tdx
]
-- | Compute the best move for a given instance.
checkInstanceMove :: AlgorithmOptions -- ^ Algorithmic options for balancing
-> [Ndx] -- ^ Allowed target node indices
-> Table -- ^ Original table
-> Instance.Instance -- ^ Instance to move
-> Table -- ^ Best new table for this instance
checkInstanceMove opts nodes_idx ini_tbl@(Table nl _ _ _) target =
let force = algIgnoreSoftErrors opts
disk_moves = algDiskMoves opts
inst_moves = algInstanceMoves opts
rest_mig = algRestrictedMigration opts
opdx = Instance.pNode target
osdx = Instance.sNode target
bad_nodes = [opdx, osdx]
nodes = filter (`notElem` bad_nodes) nodes_idx
mir_type = Instance.mirrorType target
use_secondary = elem osdx nodes_idx && inst_moves
aft_failover = if mir_type == MirrorInternal && use_secondary
-- if drbd and allowed to failover
then checkSingleStep force ini_tbl target ini_tbl
Failover
else ini_tbl
primary_drained = Node.offline
. flip Container.find nl
$ Instance.pNode target
all_moves =
if disk_moves
then concatMap (possibleMoves mir_type use_secondary inst_moves
(rest_mig, primary_drained))
nodes
else []
in
-- iterate over the possible nodes for this instance
foldl' (checkSingleStep force ini_tbl target) aft_failover all_moves
-- | Compute the best next move.
checkMove :: AlgorithmOptions -- ^ Algorithmic options for balancing
-> [Ndx] -- ^ Allowed target node indices
-> Table -- ^ The current solution
-> [Instance.Instance] -- ^ List of instances still to move
-> Table -- ^ The new solution
checkMove opts nodes_idx ini_tbl victims =
let Table _ _ _ ini_plc = ini_tbl
-- we're using rwhnf from the Control.Parallel.Strategies
-- package; we don't need to use rnf as that would force too
-- much evaluation in single-threaded cases, and in
-- multi-threaded case the weak head normal form is enough to
-- spark the evaluation
tables = parMap rwhnf (checkInstanceMove opts nodes_idx ini_tbl)
victims
-- iterate over all instances, computing the best move
best_tbl = foldl' compareTables ini_tbl tables
Table _ _ _ best_plc = best_tbl
in if length best_plc == length ini_plc
then ini_tbl -- no advancement
else best_tbl
-- | Check if we are allowed to go deeper in the balancing.
doNextBalance :: Table -- ^ The starting table
-> Int -- ^ Remaining length
-> Score -- ^ Score at which to stop
-> Bool -- ^ The resulting table and commands
doNextBalance ini_tbl max_rounds min_score =
let Table _ _ ini_cv ini_plc = ini_tbl
ini_plc_len = length ini_plc
in (max_rounds < 0 || ini_plc_len < max_rounds) && ini_cv > min_score
-- | Run a balance move.
tryBalance :: AlgorithmOptions -- ^ Algorithmic options for balancing
-> Table -- ^ The starting table
-> Maybe Table -- ^ The resulting table and commands
tryBalance opts ini_tbl =
let evac_mode = algEvacMode opts
mg_limit = algMinGainLimit opts
min_gain = algMinGain opts
Table ini_nl ini_il ini_cv _ = ini_tbl
all_inst = Container.elems ini_il
all_nodes = Container.elems ini_nl
(offline_nodes, online_nodes) = partition Node.offline all_nodes
all_inst' = if evac_mode
then let bad_nodes = map Node.idx offline_nodes
in filter (any (`elem` bad_nodes) .
Instance.allNodes) all_inst
else all_inst
reloc_inst = filter (\i -> Instance.movable i &&
Instance.autoBalance i) all_inst'
node_idx = map Node.idx online_nodes
fin_tbl = checkMove opts node_idx ini_tbl reloc_inst
(Table _ _ fin_cv _) = fin_tbl
in
if fin_cv < ini_cv && (ini_cv > mg_limit || ini_cv - fin_cv >= min_gain)
then Just fin_tbl -- this round made success, return the new table
else Nothing
-- * Allocation functions
-- | Generate the valid node allocation singles or pairs for a new instance.
genAllocNodes :: Group.List -- ^ Group list
-> Node.List -- ^ The node map
-> Int -- ^ The number of nodes required
-> Bool -- ^ Whether to drop or not
-- unallocable nodes
-> Result AllocNodes -- ^ The (monadic) result
genAllocNodes gl nl count drop_unalloc =
let filter_fn = if drop_unalloc
then filter (Group.isAllocable .
flip Container.find gl . Node.group)
else id
all_nodes = filter_fn $ getOnline nl
all_pairs = [(Node.idx p,
[Node.idx s | s <- all_nodes,
Node.idx p /= Node.idx s,
Node.group p == Node.group s]) |
p <- all_nodes]
in case count of
1 -> Ok (Left (map Node.idx all_nodes))
2 -> Ok (Right (filter (not . null . snd) all_pairs))
_ -> Bad "Unsupported number of nodes, only one or two supported"
-- | Try to allocate an instance on the cluster.
tryAlloc :: (Monad m) =>
AlgorithmOptions
-> Node.List -- ^ The node list
-> Instance.List -- ^ The instance list
-> Instance.Instance -- ^ The instance to allocate
-> AllocNodes -- ^ The allocation targets
-> m AllocSolution -- ^ Possible solution list
tryAlloc _ _ _ _ (Right []) = fail "Not enough online nodes"
tryAlloc opts nl il inst (Right ok_pairs) =
let cstat = compClusterStatistics $ Container.elems nl
n1pred = if algCapacity opts
then allocGlobalN1 nl il
else const True
psols = parMap rwhnf (\(p, ss) ->
collectionToSolution FailN1 n1pred $
foldl (\cstate ->
concatAllocCollections cstate
. allocateOnPair opts cstat nl inst p)
emptyAllocCollection ss) ok_pairs
sols = foldl' sumAllocs emptyAllocSolution psols
in return $ annotateSolution sols
tryAlloc _ _ _ _ (Left []) = fail "No online nodes"
tryAlloc opts nl il inst (Left all_nodes) =
let sols = foldl (\cstate ->
concatAllocCollections cstate
. allocateOnSingle opts nl inst
) emptyAllocCollection all_nodes
n1pred = if algCapacity opts
then allocGlobalN1 nl il
else const True
in return . annotateSolution
$ collectionToSolution FailN1 n1pred sols
-- | From a list of possibly bad and possibly empty solutions, filter
-- only the groups with a valid result. Note that the result will be
-- reversed compared to the original list.
filterMGResults :: [(Group.Group, Result (GenericAllocSolution a))]
-> [(Group.Group, GenericAllocSolution a)]
filterMGResults = foldl' fn []
where unallocable = not . Group.isAllocable
fn accu (grp, rasol) =
case rasol of
Bad _ -> accu
Ok sol | isNothing (asSolution sol) -> accu
| unallocable grp -> accu
| otherwise -> (grp, sol):accu
-- | Sort multigroup results based on policy and score.
sortMGResults :: Ord a
=> [(Group.Group, GenericAllocSolution a)]
-> [(Group.Group, GenericAllocSolution a)]
sortMGResults sols =
let extractScore (_, _, _, x) = x
solScore (grp, sol) = (Group.allocPolicy grp,
(extractScore . fromJust . asSolution) sol)
in sortBy (comparing solScore) sols
-- | Determines if a group is connected to the networks required by the
-- | instance.
hasRequiredNetworks :: Group.Group -> Instance.Instance -> Bool
hasRequiredNetworks ng = all hasNetwork . Instance.nics
where hasNetwork = maybe True (`elem` Group.networks ng) . Nic.network
-- | Removes node groups which can't accommodate the instance
filterValidGroups :: [(Group.Group, (Node.List, Instance.List))]
-> Instance.Instance
-> ([(Group.Group, (Node.List, Instance.List))], [String])
filterValidGroups [] _ = ([], [])
filterValidGroups (ng:ngs) inst =
let (valid_ngs, msgs) = filterValidGroups ngs inst
in if hasRequiredNetworks (fst ng) inst
then (ng:valid_ngs, msgs)
else (valid_ngs,
("group " ++ Group.name (fst ng) ++
" is not connected to a network required by instance " ++
Instance.name inst):msgs)
-- | Finds an allocation solution for an instance on a group
findAllocation :: AlgorithmOptions
-> Group.List -- ^ The group list
-> Node.List -- ^ The node list
-> Instance.List -- ^ The instance list
-> Gdx -- ^ The group to allocate to
-> Instance.Instance -- ^ The instance to allocate
-> Int -- ^ Required number of nodes
-> Result (AllocSolution, [String])
findAllocation opts mggl mgnl mgil gdx inst cnt = do
let belongsTo nl' nidx = nidx `elem` map Node.idx (Container.elems nl')
nl = Container.filter ((== gdx) . Node.group) mgnl
il = Container.filter (belongsTo nl . Instance.pNode) mgil
group' = Container.find gdx mggl
unless (hasRequiredNetworks group' inst) . failError
$ "The group " ++ Group.name group' ++ " is not connected to\
\ a network required by instance " ++ Instance.name inst
solution <- genAllocNodes mggl nl cnt False >>= tryAlloc opts nl il inst
return (solution, solutionDescription (group', return solution))
-- | Finds the best group for an instance on a multi-group cluster.
--
-- Only solutions in @preferred@ and @last_resort@ groups will be
-- accepted as valid, and additionally if the allowed groups parameter
-- is not null then allocation will only be run for those group
-- indices.
findBestAllocGroup :: AlgorithmOptions
-> Group.List -- ^ The group list
-> Node.List -- ^ The node list
-> Instance.List -- ^ The instance list
-> Maybe [Gdx] -- ^ The allowed groups
-> Instance.Instance -- ^ The instance to allocate
-> Int -- ^ Required number of nodes
-> Result (Group.Group, AllocSolution, [String])
findBestAllocGroup opts mggl mgnl mgil allowed_gdxs inst cnt =
let groups_by_idx = splitCluster mgnl mgil
groups = map (\(gid, d) -> (Container.find gid mggl, d)) groups_by_idx
groups' = maybe groups
(\gs -> filter ((`elem` gs) . Group.idx . fst) groups)
allowed_gdxs
(groups'', filter_group_msgs) = filterValidGroups groups' inst
sols = map (\(gr, (nl, il)) ->
(gr, genAllocNodes mggl nl cnt False >>=
tryAlloc opts nl il inst))
groups''::[(Group.Group, Result AllocSolution)]
all_msgs = filter_group_msgs ++ concatMap solutionDescription sols
goodSols = filterMGResults sols
sortedSols = sortMGResults goodSols
in case sortedSols of
[] -> Bad $ if null groups'
then "no groups for evacuation: allowed groups was " ++
show allowed_gdxs ++ ", all groups: " ++
show (map fst groups)
else intercalate ", " all_msgs
(final_group, final_sol):_ -> return (final_group, final_sol, all_msgs)
-- | Try to allocate an instance on a multi-group cluster.
tryMGAlloc :: AlgorithmOptions
-> Group.List -- ^ The group list
-> Node.List -- ^ The node list
-> Instance.List -- ^ The instance list
-> Instance.Instance -- ^ The instance to allocate
-> Int -- ^ Required number of nodes
-> Result AllocSolution -- ^ Possible solution list
tryMGAlloc opts mggl mgnl mgil inst cnt = do
(best_group, solution, all_msgs) <-
findBestAllocGroup opts mggl mgnl mgil Nothing inst cnt
let group_name = Group.name best_group
selmsg = "Selected group: " ++ group_name
return $ solution { asLog = selmsg:all_msgs }
-- | Try to allocate an instance to a group.
tryGroupAlloc :: AlgorithmOptions
-> Group.List -- ^ The group list
-> Node.List -- ^ The node list
-> Instance.List -- ^ The instance list
-> String -- ^ The allocation group (name)
-> Instance.Instance -- ^ The instance to allocate
-> Int -- ^ Required number of nodes
-> Result AllocSolution -- ^ Solution
tryGroupAlloc opts mggl mgnl ngil gn inst cnt = do
gdx <- Group.idx <$> Container.findByName mggl gn
(solution, msgs) <- findAllocation opts mggl mgnl ngil gdx inst cnt
return $ solution { asLog = msgs }
-- | Try to allocate a list of instances on a multi-group cluster.
allocList :: AlgorithmOptions
-> Group.List -- ^ The group list
-> Node.List -- ^ The node list
-> Instance.List -- ^ The instance list
-> [(Instance.Instance, AllocDetails)] -- ^ The instance to
-- allocate
-> AllocSolutionList -- ^ Possible solution
-- list
-> Result (Node.List, Instance.List,
AllocSolutionList) -- ^ The final solution
-- list
allocList _ _ nl il [] result = Ok (nl, il, result)
allocList opts gl nl il ((xi, AllocDetails xicnt mgn):xies) result = do
ares <- case mgn of
Nothing -> tryMGAlloc opts gl nl il xi xicnt
Just gn -> tryGroupAlloc opts gl nl il gn xi xicnt
let sol = asSolution ares
nl' = extractNl nl il sol
il' = updateIl il sol
allocList opts gl nl' il' xies ((xi, ares):result)
-- | Change-group IAllocator mode main function.
--
-- This is very similar to 'tryNodeEvac', the only difference is that
-- we don't choose as target group the current instance group, but
-- instead:
--
-- 1. at the start of the function, we compute which are the target
-- groups; either no groups were passed in, in which case we choose
-- all groups out of which we don't evacuate instance, or there were
-- some groups passed, in which case we use those
--
-- 2. for each instance, we use 'findBestAllocGroup' to choose the
-- best group to hold the instance, and then we do what
-- 'tryNodeEvac' does, except for this group instead of the current
-- instance group.
--
-- Note that the correct behaviour of this function relies on the
-- function 'nodeEvacInstance' to be able to do correctly both
-- intra-group and inter-group moves when passed the 'ChangeAll' mode.
tryChangeGroup :: AlgorithmOptions
-> Group.List -- ^ The cluster groups
-> Node.List -- ^ The node list (cluster-wide)
-> Instance.List -- ^ Instance list (cluster-wide)
-> [Gdx] -- ^ Target groups; if empty, any
-- groups not being evacuated
-> [Idx] -- ^ List of instance (indices) to be evacuated
-> Result (Node.List, Instance.List, EvacSolution)
tryChangeGroup opts gl ini_nl ini_il gdxs idxs =
let evac_gdxs = nub $ map (instancePriGroup ini_nl .
flip Container.find ini_il) idxs
target_gdxs = (if null gdxs
then Container.keys gl
else gdxs) \\ evac_gdxs
offline = map Node.idx . filter Node.offline $ Container.elems ini_nl
excl_ndx = foldl' (flip IntSet.insert) IntSet.empty offline
group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx
(Container.elems nl))) $
splitCluster ini_nl ini_il
(fin_nl, fin_il, esol) =
foldl' (\state@(nl, il, _) inst ->
let solution = do
let ncnt = Instance.requiredNodes $
Instance.diskTemplate inst
(grp, _, _) <- findBestAllocGroup opts gl nl il
(Just target_gdxs) inst ncnt
let gdx = Group.idx grp
av_nodes <- availableGroupNodes group_ndx
excl_ndx gdx
nodeEvacInstance defaultOptions
nl il ChangeAll inst gdx av_nodes
in updateEvacSolution state (Instance.idx inst) solution
)
(ini_nl, ini_il, emptyEvacSolution)
(map (`Container.find` ini_il) idxs)
in return (fin_nl, fin_il, reverseEvacSolution esol)
-- | Standard-sized allocation method.
--
-- This places instances of the same size on the cluster until we're
-- out of space. The result will be a list of identically-sized
-- instances.
iterateAlloc :: AlgorithmOptions -> AllocMethod
iterateAlloc opts nl il limit newinst allocnodes ixes cstats =
let depth = length ixes
newname = printf "new-%d" depth::String
newidx = Container.size il
newi2 = Instance.setIdx (Instance.setName newinst newname) newidx
newlimit = fmap (flip (-) 1) limit
in case tryAlloc ( opts { algCapacity = False } ) nl il newi2 allocnodes of
Bad s -> Bad s
Ok (AllocSolution { asFailures = errs, asSolution = sols3 }) ->
let newsol = Ok (collapseFailures errs, nl, il, ixes, cstats) in
case sols3 of
Nothing -> newsol
Just (xnl, xi, _, _) ->
if limit == Just 0
then newsol
else iterateAlloc opts xnl (Container.add newidx xi il)
newlimit newinst allocnodes (xi:ixes)
(totalResources xnl:cstats)
-- | Predicate whether shrinking a single resource can lead to a valid
-- allocation.
sufficesShrinking :: (Instance.Instance -> AllocSolution) -> Instance.Instance
-> FailMode -> Maybe Instance.Instance
sufficesShrinking allocFn inst fm =
case dropWhile (isNothing . asSolution . fst)
. takeWhile (liftA2 (||) (elem fm . asFailures . fst)
(isJust . asSolution . fst))
. map (allocFn &&& id) $
iterateOk (`Instance.shrinkByType` fm) inst
of x:_ -> Just . snd $ x
_ -> Nothing
-- | Tiered allocation method.
--
-- This places instances on the cluster, and decreases the spec until
-- we can allocate again. The result will be a list of decreasing
-- instance specs.
tieredAlloc :: AlgorithmOptions -> AllocMethod
tieredAlloc opts nl il limit newinst allocnodes ixes cstats =
case iterateAlloc opts nl il limit newinst allocnodes ixes cstats of
Bad s -> Bad s
Ok (errs, nl', il', ixes', cstats') ->
let newsol = Ok (errs, nl', il', ixes', cstats')
ixes_cnt = length ixes'
(stop, newlimit) = case limit of
Nothing -> (False, Nothing)
Just n -> (n <= ixes_cnt,
Just (n - ixes_cnt))
sortedErrs = map fst $ sortBy (comparing snd) errs
suffShrink = sufficesShrinking
(fromMaybe emptyAllocSolution
. flip (tryAlloc opts nl' il') allocnodes)
newinst
bigSteps = filter isJust . map suffShrink . reverse $ sortedErrs
progress (Ok (_, _, _, newil', _)) (Ok (_, _, _, newil, _)) =
length newil' > length newil
progress _ _ = False
in if stop then newsol else
let newsol' = case Instance.shrinkByType newinst . last
$ sortedErrs of
Bad _ -> newsol
Ok newinst' -> tieredAlloc opts nl' il' newlimit
newinst' allocnodes ixes' cstats'
in if progress newsol' newsol then newsol' else
case bigSteps of
Just newinst':_ -> tieredAlloc opts nl' il' newlimit
newinst' allocnodes ixes' cstats'
_ -> newsol
-- * Formatting functions
-- | Given the original and final nodes, computes the relocation description.
computeMoves :: Instance.Instance -- ^ The instance to be moved
-> String -- ^ The instance name
-> IMove -- ^ The move being performed
-> String -- ^ New primary
-> String -- ^ New secondary
-> (String, [String])
-- ^ Tuple of moves and commands list; moves is containing
-- either @/f/@ for failover or @/r:name/@ for replace
-- secondary, while the command list holds gnt-instance
-- commands (without that prefix), e.g \"@failover instance1@\"
computeMoves i inam mv c d =
case mv of
Failover -> ("f", [mig])
FailoverToAny _ -> (printf "fa:%s" c, [mig_any])
FailoverAndReplace _ -> (printf "f r:%s" d, [mig, rep d])
ReplaceSecondary _ -> (printf "r:%s" d, [rep d])
ReplaceAndFailover _ -> (printf "r:%s f" c, [rep c, mig])
ReplacePrimary _ -> (printf "f r:%s f" c, [mig, rep c, mig])
where morf = if Instance.isRunning i then "migrate" else "failover"
mig = printf "%s -f %s" morf inam::String
mig_any = printf "%s -f -n %s %s" morf c inam::String
rep n = printf "replace-disks -n %s %s" n inam::String
-- | Converts a placement to string format.
printSolutionLine :: Node.List -- ^ The node list
-> Instance.List -- ^ The instance list
-> Int -- ^ Maximum node name length
-> Int -- ^ Maximum instance name length
-> Placement -- ^ The current placement
-> Int -- ^ The index of the placement in
-- the solution
-> (String, [String])
printSolutionLine nl il nmlen imlen plc pos =
let pmlen = (2*nmlen + 1)
(i, p, s, mv, c) = plc
old_sec = Instance.sNode inst
inst = Container.find i il
inam = Instance.alias inst
npri = Node.alias $ Container.find p nl
nsec = Node.alias $ Container.find s nl
opri = Node.alias $ Container.find (Instance.pNode inst) nl
osec = Node.alias $ Container.find old_sec nl
(moves, cmds) = computeMoves inst inam mv npri nsec
-- FIXME: this should check instead/also the disk template
ostr = if old_sec == Node.noSecondary
then printf "%s" opri::String
else printf "%s:%s" opri osec::String
nstr = if s == Node.noSecondary
then printf "%s" npri::String
else printf "%s:%s" npri nsec::String
in (printf " %3d. %-*s %-*s => %-*s %12.8f a=%s"
pos imlen inam pmlen ostr pmlen nstr c moves,
cmds)
-- | Return the instance and involved nodes in an instance move.
--
-- Note that the output list length can vary, and is not required nor
-- guaranteed to be of any specific length.
involvedNodes :: Instance.List -- ^ Instance list, used for retrieving
-- the instance from its index; note
-- that this /must/ be the original
-- instance list, so that we can
-- retrieve the old nodes
-> Placement -- ^ The placement we're investigating,
-- containing the new nodes and
-- instance index
-> [Ndx] -- ^ Resulting list of node indices
involvedNodes il plc =
let (i, np, ns, _, _) = plc
inst = Container.find i il
in nub . filter (>= 0) $ [np, ns] ++ Instance.allNodes inst
-- | From two adjacent cluster tables get the list of moves that transitions
-- from to the other
getMoves :: (Table, Table) -> [MoveJob]
getMoves (Table _ initial_il _ initial_plc, Table final_nl _ _ final_plc) =
let
plctoMoves (plc@(idx, p, s, mv, _)) =
let inst = Container.find idx initial_il
inst_name = Instance.name inst
affected = involvedNodes initial_il plc
np = Node.alias $ Container.find p final_nl
ns = Node.alias $ Container.find s final_nl
(_, cmds) = computeMoves inst inst_name mv np ns
in (affected, idx, mv, cmds)
in map plctoMoves . reverse . drop (length initial_plc) $ reverse final_plc
-- | Inner function for splitJobs, that either appends the next job to
-- the current jobset, or starts a new jobset.
mergeJobs :: ([JobSet], [Ndx]) -> MoveJob -> ([JobSet], [Ndx])
mergeJobs ([], _) n@(ndx, _, _, _) = ([[n]], ndx)
mergeJobs (cjs@(j:js), nbuf) n@(ndx, _, _, _)
| null (ndx `intersect` nbuf) = ((n:j):js, ndx ++ nbuf)
| otherwise = ([n]:cjs, ndx)
-- | Break a list of moves into independent groups. Note that this
-- will reverse the order of jobs.
splitJobs :: [MoveJob] -> [JobSet]
splitJobs = fst . foldl mergeJobs ([], [])
-- | Given a list of commands, prefix them with @gnt-instance@ and
-- also beautify the display a little.
formatJob :: Int -> Int -> (Int, MoveJob) -> [String]
formatJob jsn jsl (sn, (_, _, _, cmds)) =
let out =
printf " echo job %d/%d" jsn sn:
printf " check":
map (" gnt-instance " ++) cmds
in if sn == 1
then ["", printf "echo jobset %d, %d jobs" jsn jsl] ++ out
else out
-- | Given a list of commands, prefix them with @gnt-instance@ and
-- also beautify the display a little.
formatCmds :: [JobSet] -> String
formatCmds =
unlines .
concatMap (\(jsn, js) -> concatMap (formatJob jsn (length js))
(zip [1..] js)) .
zip [1..]
-- | Print the node list.
printNodes :: Node.List -> [String] -> String
printNodes nl fs =
let fields = case fs of
[] -> Node.defaultFields
"+":rest -> Node.defaultFields ++ rest
_ -> fs
snl = sortBy (comparing Node.idx) (Container.elems nl)
(header, isnum) = unzip $ map Node.showHeader fields
in printTable "" header (map (Node.list fields) snl) isnum
-- | Print the instance list.
printInsts :: Node.List -> Instance.List -> String
printInsts nl il =
let sil = sortBy (comparing Instance.idx) (Container.elems il)
helper inst = [ if Instance.isRunning inst then "R" else " "
, Instance.name inst
, Container.nameOf nl (Instance.pNode inst)
, let sdx = Instance.sNode inst
in if sdx == Node.noSecondary
then ""
else Container.nameOf nl sdx
, if Instance.autoBalance inst then "Y" else "N"
, printf "%3d" $ Instance.vcpus inst
, printf "%5d" $ Instance.mem inst
, printf "%5d" $ Instance.dsk inst `div` 1024
, printf "%5.3f" lC
, printf "%5.3f" lM
, printf "%5.3f" lD
, printf "%5.3f" lN
]
where DynUtil lC lM lD lN = Instance.util inst
header = [ "F", "Name", "Pri_node", "Sec_node", "Auto_bal"
, "vcpu", "mem" , "dsk", "lCpu", "lMem", "lDsk", "lNet" ]
isnum = False:False:False:False:False:repeat True
in printTable "" header (map helper sil) isnum
-- * Node group functions
-- | Computes the group of an instance.
instanceGroup :: Node.List -> Instance.Instance -> Result Gdx
instanceGroup nl i =
let sidx = Instance.sNode i
pnode = Container.find (Instance.pNode i) nl
snode = if sidx == Node.noSecondary
then pnode
else Container.find sidx nl
pgroup = Node.group pnode
sgroup = Node.group snode
in if pgroup /= sgroup
then fail ("Instance placed accross two node groups, primary " ++
show pgroup ++ ", secondary " ++ show sgroup)
else return pgroup
-- | Compute the list of badly allocated instances (split across node
-- groups).
findSplitInstances :: Node.List -> Instance.List -> [Instance.Instance]
findSplitInstances nl =
filter (not . isOk . instanceGroup nl) . Container.elems
|
dimara/ganeti
|
src/Ganeti/HTools/Cluster.hs
|
bsd-2-clause
| 46,104 | 0 | 23 | 14,427 | 9,940 | 5,409 | 4,531 | 758 | 8 |
call :: (Delta d, AAM aam) => d -> aam
-> Time aam -> Env aam -> Store d aam -> Call
-> Set (Call, Env aam, Store d aam)
call d aam t e s (If a tc fc) =
eachInSet (atom d e s a) $ \ v ->
eachInSet (elimBool d v) $ \ b ->
setSingleton (if b then tc else fc, e, s)
call d aam t e s (App fa xas) =
eachInSet (atom d e s fa) $ \ v ->
eachInSet (elimClo d v) $ \ (xs,c,e') ->
setFromMaybe $ bindMany aam t xs xas e' s
call _ _ _ e s (Halt a) = setSingleton (Halt a, e, s)
|
davdar/quals
|
writeup-old/sections/03AAMByExample/03AbstractSemantics/01Call.hs
|
bsd-3-clause
| 505 | 0 | 14 | 157 | 303 | 154 | 149 | 12 | 2 |
{-# LANGUAGE TupleSections #-}
module PolyPaver.Simplify.Substitution
--(
-- simplifyUsingSubstitutions
--)
where
import PolyPaver.Form
import PolyPaver.Subterms
import PolyPaver.Vars (getFormFreeVars)
import qualified Data.Set as Set
simplifyUsingSubstitutions ::
Form TermHash -> [(Form TermHash, String)]
simplifyUsingSubstitutions form =
{-
1. Identify all hypotheses that are inclusions or inequalities.
2. Extract possible substitutions (term pairs with monotonicity types).
3. Try to apply each substitution to the conclusion.
4. Ignore substitutions that do not reduce the conclusion arity.
5. Remove all hypotheses that feature a removed variable.
6. Assemble the simplified conjectures, regenerating hashes.
-}
strongerForms
where
strongerForms =
maybeFormWithoutNonConclusionVars ++
(concat $ map buildFormFromConclusion conclusionsWithDescriptions)
where
maybeFormWithoutNonConclusionVars
| length hypotheses == length hypothesesWithOnlyConclusionVars = []
| otherwise = [(addHashesInForm reducedForm, description)]
where
description =
"removed hypotheses that contain variables not in the conclusion"
++ "\n\n original formula:\n"
++ showForm 1000000 const form
++ "\n"
++ "\n simplified formula:\n"
++ showForm 1000000 const reducedForm
++ "\n"
reducedForm =
joinHypothesesAndConclusion (hypothesesWithOnlyConclusionVars, conclusion)
hypothesesWithOnlyConclusionVars =
filter (hasOnlyVars conclusionVars) hypotheses
buildFormFromConclusion (c, reducedVars, description)
| length hypothesesWithoutReducedVars == length hypothesesWithOnlyConclusionVars =
[(addHashesInForm reducedForm1, description1)]
| otherwise =
[(addHashesInForm reducedForm1, description1),
(addHashesInForm reducedForm2, description2)]
where
description1 =
description ++ "; removed hypotheses that contain a reduced variable"
++ "\n simplified formula:\n"
++ showForm 1000000 const reducedForm1
++ "\n"
description2 =
description ++ "; removed hypotheses that contain variables not in the conclusion"
++ "\n simplified formula:\n"
++ showForm 1000000 const reducedForm2
++ "\n"
reducedForm1 =
joinHypothesesAndConclusion (hypothesesWithoutReducedVars, c)
reducedForm2 =
joinHypothesesAndConclusion (hypothesesWithOnlyConclusionVars, c)
hypothesesWithOnlyConclusionVars =
filter (hasOnlyVars $ getFormFreeVars c) hypotheses
hypothesesWithoutReducedVars =
filter hasNoReducedVar hypotheses -- remove hypotheses that feature a removed variable
hasNoReducedVar h =
Set.null $ reducedVars `Set.intersection` (getFormFreeVars h)
hasOnlyVars vars h =
getFormFreeVars h `Set.isSubsetOf` vars
conclusionsWithDescriptions =
map addDescription $
filter hasReducedTheArity $ -- ignoring substitutions that do not reduce arity
map addReducedVariables strongerConclusionsAndSubstitutions
where
addDescription ((c,s), reducedVars) =
(c, reducedVars, description)
where
description =
"substitution:\n" ++ showSubstitution s -- ++ "; reducedVars = " ++ show reducedVars
++ "\n\n original formula:\n"
++ showForm 1000000 const form
++ "\n"
hasReducedTheArity (_, reducedVars) = not $ Set.null reducedVars
addReducedVariables (c,s) = ((c,s), conclusionVars `Set.difference` getFormFreeVars c)
strongerConclusionsAndSubstitutions =
concat $ map (\(s, cs) -> map (,s) cs) $ zip substitutions strongerConclusionsLists
strongerConclusionsLists =
-- apply each substitution onto the conclusion, ignoring those that have no effect:
map (makeStrengtheningSubstitution conclusion) substitutions
-- identify substitutions from hypotheses:
substitutions = concat $ map extractSubstitutionsFromHypothesis hypotheses
conclusionVars = getFormFreeVars conclusion
(hypotheses, conclusion) = getHypothesesAndConclusion form
-- Old code that tested for elimination only at the substitution level and removed only the hypothesis that
-- gave birth to the substitution:
-- strongerConclusions = concat $ map (makeStrengtheningSubstitution conclusion) substitutionsAndGaps2
-- substitutionsAndGaps2 = filter (eliminatesVar . fst) substitutionsAndGaps
-- substitutionsAndGaps = concat $ zipWith addToAll hypothesesGaps (map extractSubstitutionsFromHypothesis hypotheses)
-- addToAll e2 l = [(e1,e2) | e1 <- l]
-- hypothesesGaps = f hypotheses []
-- where
-- f [] _ = []
-- f (h:t) p = ((reverse p) ++ t) : f t (h:p)
-- eliminatesVar subst =
-- not $ Set.null $
-- (getTermFreeVars $ subst_source subst) `Set.difference` (getTermFreeVars $ subst_target subst)
data Substitution =
Substitution
{
subst_source :: Term TermHash,
subst_target :: Term TermHash,
subst_monotonicityType :: MonotonicityType
}
showSubstitution :: Substitution -> String
showSubstitution substitution =
"[" ++ sourceS ++ " -> " ++ targetS ++ "]"
where
sourceS = showTerm const source
targetS = showTerm const target
source = subst_source substitution
target = subst_target substitution
data MonotonicityType =
Equal | Increasing | Decreasing | Expanding
deriving (Eq)
monoTypeMatches :: MonotonicityType -> MonotonicityType -> Bool
monoTypeMatches Equal _ = True
monoTypeMatches Expanding Equal = False
monoTypeMatches Expanding _ = True
monoTypeMatches mt1 mt2 = mt1 == mt2
monoTypeNegate :: MonotonicityType -> MonotonicityType
monoTypeNegate Increasing = Decreasing
monoTypeNegate Decreasing = Increasing
monoTypeNegate t = t
monoTypeBothSigns :: MonotonicityType -> MonotonicityType
monoTypeBothSigns Increasing = Equal
monoTypeBothSigns Decreasing = Equal
monoTypeBothSigns t = t
extractSubstitutionsFromHypothesis ::
Form TermHash -> [Substitution]
extractSubstitutionsFromHypothesis form =
case form of
Le _ l r -> substFromLess l r
Leq _ l r -> substFromLess l r
Ge _ l r -> substFromLess r l
Geq _ l r -> substFromLess r l
Eq _ l r -> substFromEq l r
ContainedIn _ l r -> substFromContained l r
_ -> []
where
substFromLess l r =
[Substitution l r Increasing,
Substitution r l Decreasing]
substFromEq l r =
[Substitution l r Equal,
Substitution r l Equal]
substFromContained l r =
[Substitution l r Expanding]
makeStrengtheningSubstitution :: Form TermHash -> Substitution -> [Form TermHash]
makeStrengtheningSubstitution form substitution
| formHasChanged = [addHashesInForm formS]
| otherwise = []
where
Term (_, sourceHash) = subst_source substitution
target = subst_target substitution
availableMonoType = subst_monotonicityType substitution
(formS, formHasChanged) = subF True form
subF shouldStrengthen form2 =
case form2 of
Not arg ->
(Not argS, ch)
where
(argS, ch) = subF (not shouldStrengthen) arg
Or left right ->
(Or leftS rightS, chL || chR)
where
(leftS, chL) = subF shouldStrengthen left
(rightS, chR) = subF shouldStrengthen right
And left right ->
(And leftS rightS, chL || chR)
where
(leftS, chL) = subF shouldStrengthen left
(rightS, chR) = subF shouldStrengthen right
Implies left right ->
(Implies leftS rightS, chL || chR)
where
(leftS, chL) = subF (not shouldStrengthen) left
(rightS, chR) = subF shouldStrengthen right
Le lab left right ->
(Le lab leftS rightS, chL || chR)
where
(leftS, chL) = subT Increasing left
(rightS, chR) = subT Decreasing right
Leq lab left right ->
(Leq lab leftS rightS, chL || chR)
where
(leftS, chL) = subT Increasing left
(rightS, chR) = subT Decreasing right
Ge lab left right ->
(Ge lab leftS rightS, chL || chR)
where
(leftS, chL) = subT Decreasing left
(rightS, chR) = subT Increasing right
Geq lab left right ->
(Geq lab leftS rightS, chL || chR)
where
(leftS, chL) = subT Decreasing left
(rightS, chR) = subT Increasing right
Eq lab left right ->
(Eq lab leftS rightS, chL || chR)
where
(leftS, chL) = subT Equal left
(rightS, chR) = subT Equal right
Neq lab left right ->
(Neq lab leftS rightS, chL || chR)
where
(leftS, chL) = subT Equal left
(rightS, chR) = subT Equal right
ContainedIn lab left right ->
(ContainedIn lab leftS rightS, chL || chR)
where
(leftS, chL) = subT Expanding left
(rightS, chR) = subT Equal right
IsRange lab arg1 arg2 arg3 ->
(IsRange lab arg1S arg2S arg3S, ch1 || ch2 || ch3)
where
(arg1S, ch1) = subT Expanding arg1
(arg2S, ch2) = subT Increasing arg2
(arg3S, ch3) = subT Decreasing arg3
IsIntRange lab arg1 arg2 arg3 ->
(IsIntRange lab arg1S arg2S arg3S, ch1 || ch2 || ch3)
where
(arg1S, ch1) = subT Equal arg1
(arg2S, ch2) = subT Increasing arg2
(arg3S, ch3) = subT Decreasing arg3
IsInt lab arg ->
(IsInt lab argS, ch)
where
(argS, ch) = subT Equal arg
subT requiredMonoType term@(Term (term', hash))
{-
Need to also perform a range analysis to identify some expressions
that are always positive or always negative.
-}
| hash == sourceHash && availableMonoType `monoTypeMatches` requiredMonoType =
(target, True)
| otherwise =
case term' of
Hull left right -> subT2 requiredMonoType requiredMonoType Hull left right
Plus left right -> subT2 requiredMonoType requiredMonoType Plus left right
Minus left right ->
subT2 requiredMonoType (monoTypeNegate requiredMonoType) Minus left right
Neg arg -> subT1 (monoTypeNegate requiredMonoType) Neg arg
Times left right ->
subT2 (monoTypeBothSigns requiredMonoType) (monoTypeBothSigns requiredMonoType) Times left right
Square arg -> subT1 (monoTypeBothSigns requiredMonoType) Square arg
IntPower left right ->
subT2 (monoTypeBothSigns requiredMonoType) Equal IntPower left right
Recip arg -> subT1 (monoTypeBothSigns requiredMonoType) Recip arg
Over left right ->
subT2 (monoTypeBothSigns requiredMonoType) (monoTypeBothSigns requiredMonoType) Over left right
Abs arg -> subT1 (monoTypeBothSigns requiredMonoType) Abs arg
Min left right -> subT2 requiredMonoType requiredMonoType Min left right
Max left right -> subT2 requiredMonoType requiredMonoType Max left right
Sqrt arg -> subT1 requiredMonoType Sqrt arg
Exp arg -> subT1 requiredMonoType Exp arg
Sin arg -> subT1 (monoTypeBothSigns requiredMonoType) Sin arg
Cos arg -> subT1 (monoTypeBothSigns requiredMonoType) Cos arg
Atan arg -> subT1 requiredMonoType Atan arg
Integral ivarId ivarName lower upper integrand ->
subT3 (monoTypeBothSigns requiredMonoType) (monoTypeBothSigns requiredMonoType) requiredMonoType
(Integral ivarId ivarName) lower upper integrand
FRound rel abse arg ->
subT1 requiredMonoType (FRound rel abse) arg
FPlus rel abse left right ->
subT2 requiredMonoType requiredMonoType (FPlus rel abse) left right
FMinus rel abse left right ->
subT2 requiredMonoType (monoTypeNegate requiredMonoType)
(FMinus rel abse) left right
FTimes rel abse left right ->
subT2 (monoTypeBothSigns requiredMonoType) (monoTypeBothSigns requiredMonoType)
(FTimes rel abse) left right
FSquare rel abse arg ->
subT1 (monoTypeBothSigns requiredMonoType) (FSquare rel abse) arg
FSqrt rel abse arg ->
subT1 requiredMonoType (FSqrt rel abse) arg
FSin rel abse arg ->
subT1 (monoTypeBothSigns requiredMonoType) (FSin rel abse) arg
FCos rel abse arg ->
subT1 (monoTypeBothSigns requiredMonoType) (FCos rel abse) arg
FOver rel abse left right ->
subT2 (monoTypeBothSigns requiredMonoType) (monoTypeBothSigns requiredMonoType)
(FOver rel abse) left right
FExp rel abse arg ->
subT1 requiredMonoType (FExp rel abse) arg
_ -> (term, False)
where
subT1 mt1 constr arg1 =
(Term (constr arg1S, 0), ch1)
where
(arg1S, ch1) = subT mt1 arg1
subT2 mt1 mt2 constr arg1 arg2 =
(Term (constr arg1S arg2S, 0), ch1 || ch2)
where
(arg1S, ch1) = subT mt1 arg1
(arg2S, ch2) = subT mt2 arg2
subT3 mt1 mt2 mt3 constr arg1 arg2 arg3 =
(Term (constr arg1S arg2S arg3S, 0), ch1 || ch2 || ch3)
where
(arg1S, ch1) = subT mt1 arg1
(arg2S, ch2) = subT mt2 arg2
(arg3S, ch3) = subT mt3 arg3
--test1 :: [(Form TermHash, Set.Set Int)]
--test1 =
-- simplifyUsingSubstitutions $
-- addHashesInForm formEx1
--
--formEx1 :: Form ()
--formEx1 =
-- x |>=| 1 ---> x |>=| 0
-- where
-- x = termVar 0 "x"
--
--test2 :: [(Form TermHash, Set.Set Int)]
--test2 =
-- simplifyUsingSubstitutions $
-- addHashesInForm formEx2
--
--formEx2 :: Form ()
--formEx2 =
-- y |<=| 1 ---> x |<-| (hull 1 y) ---> x |<-| (hull 0 (y + 1))
-- where
-- x = termVar 0 "x"
-- y = termVar 1 "y"
--
|
michalkonecny/polypaver
|
src/PolyPaver/Simplify/Substitution.hs
|
bsd-3-clause
| 15,476 | 0 | 16 | 5,293 | 3,365 | 1,722 | 1,643 | 254 | 42 |
module Lang.Parser where
import Control.Monad
import Lang.Types
import Text.ParserCombinators.Parsec
import Text.Parsec.Token (LanguageDef, commentStart, commentEnd, commentLine,
nestedComments, identStart, identLetter, opStart, opLetter,
reservedOpNames, reservedNames, caseSensitive, makeTokenParser
)
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (emptyDef)
langStyle :: LanguageDef st
langStyle = emptyDef
{ commentStart = ""
, commentEnd = ""
, commentLine = ""
, nestedComments = True
, identStart = letter <|> char '_'
, identLetter = alphaNum <|> oneOf "_?!"
, opStart = opLetter emptyDef
, opLetter = oneOf ":#$%&*+./<=>@\\^|-~"
, reservedOpNames= []
, reservedNames = []
, caseSensitive = True
}
lexer = makeTokenParser langStyle
whiteSpace= P.whiteSpace lexer
lexeme = P.lexeme lexer
symbol = P.symbol lexer
natural = P.natural lexer
parens = P.parens lexer
semi = P.semi lexer
identifier= P.identifier lexer
reserved = P.reserved lexer
reservedOp= P.reservedOp lexer
float = P.float lexer
int = P.integer lexer
stringLiteral = P.stringLiteral lexer
funcall :: Parser LangExpr
funcall = do{ symbol "["
; f <- many expr
; symbol "]"
; return $ FunCall f
}
<?> "function call"
variable :: Parser LangExpr
variable = do{ i <- identifier
;return $ Identifier i
}
<?> "variable"
intExpr :: Parser LangExpr
intExpr = do{ i <- int; return $ IntExpr i}
stringExpr :: Parser LangExpr
stringExpr = do{ s <- stringLiteral; return $ StrExpr s}
floatExpr :: Parser LangExpr
floatExpr = do{f <- float; return $ FloatExpr f}
expr :: Parser LangExpr
expr = (parens expr)
<|> try floatExpr
<|> intExpr
<|> stringExpr
<|> variable
<|> funcall
<?> "expression"
compoundExpr :: Parser LangExpr
compoundExpr = do { e <- sepBy1 expr (symbol ";")
; return $ CompoundExpr e
}
<?> "compound expression"
multiexpr :: Parser [LangExpr]
multiexpr = do{ whiteSpace
; m <- many (lexeme expr)
; eof
; return m
}
run :: Show a => Parser a -> String -> IO ()
run p input
= case (parse p "" input) of
Left err -> do{ putStr "parse error at "
; print err
}
Right x -> print x
runLex :: Show a => Parser a -> String -> IO ()
runLex p input
= run (do{ whiteSpace
; x <- p
; eof
; return x
}) input
|
jasonbaker/lang
|
Lang/Parser.hs
|
bsd-3-clause
| 2,780 | 0 | 12 | 945 | 813 | 428 | 385 | 81 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
module Math.Logic.Formula where
import Control.Applicative
import Control.Lens
import Data.Set (Set)
import Data.Foldable (Foldable(..))
import Data.UniformPair.Lens
type Form = Formula Pair Int
data Formula f literal = Lit literal
| Neg (Formula f literal)
| Con (f (Formula f literal))
| Dis (f (Formula f literal))
deriving instance Eq lit => Eq (Formula Pair lit)
deriving instance Eq lit => Eq (Formula Set lit)
deriving instance Eq lit => Eq (Formula [] lit)
deriving instance Ord lit => Ord (Formula Pair lit)
deriving instance Ord lit => Ord (Formula Set lit)
deriving instance Ord lit => Ord (Formula [] lit)
deriving instance Show lit => Show (Formula Pair lit)
deriving instance Show lit => Show (Formula Set lit)
deriving instance Show lit => Show (Formula [] lit)
instance Functor f => Functor (Formula f) where
fmap f form = case form of
Lit l -> Lit (f l)
Neg form' -> Neg (fmap f form')
Con ff -> Con (fmap (fmap f) ff)
Dis ff -> Dis (fmap (fmap f) ff)
instance Foldable f => Foldable (Formula f) where
foldMap f form = case form of
Lit l -> f l
Neg form' -> foldMap f form'
Con ff -> foldMap (foldMap f) ff
Dis ff -> foldMap (foldMap f) ff
instance Traversable f => Traversable (Formula f) where
traverse = lits
foldForm :: Foldable f => Fold (Formula f a) a
foldForm = folded
lits :: Traversable f => Traversal (Formula f a) (Formula f b) a b
lits = litsOf traverse
litsOf :: (forall c d. Traversal (f c) (f d) c d) -> Traversal (Formula f a) (Formula f b) a b
litsOf _ f (Lit l) = Lit <$> f l
litsOf t f (Neg form) = Neg <$> litsOf t f form
litsOf t f (Con ff) = Con <$> traverseOf t (litsOf t f) ff
litsOf t f (Dis ff) = Dis <$> traverseOf t (litsOf t f) ff
|
gwils/formulas
|
src/Math/Logic/Formula.hs
|
bsd-3-clause
| 2,130 | 0 | 13 | 624 | 857 | 426 | 431 | 48 | 1 |
module Main where
import Idris.Core.TT
import Idris.AbsSyntax
import Idris.ElabDecls
import Idris.Main
import IRTS.Compiler
import IRTS.CodegenJavaScript
import System.Environment
import System.Exit
import Paths_idris
data Opts = Opts { inputs :: [FilePath]
, output :: FilePath
}
showUsage = do putStrLn "A code generator which is intended to be called by the compiler, not by a user."
putStrLn "Usage: idris-codegen-node <ibc-files> [-o <output-file>]"
exitWith ExitSuccess
getOpts :: IO Opts
getOpts = do xs <- getArgs
return $ process (Opts [] "main.js") xs
where
process opts ("-o":o:xs) = process (opts { output = o }) xs
process opts (x:xs) = process (opts { inputs = x:inputs opts }) xs
process opts [] = opts
jsMain :: Opts -> Idris ()
jsMain opts = do elabPrims
loadInputs (inputs opts) Nothing
mainProg <- elabMain
ir <- compile (Via IBCFormat "node") (output opts) (Just mainProg)
runIO $ codegenNode ir
main :: IO ()
main = do opts <- getOpts
if (null (inputs opts))
then showUsage
else runMain (jsMain opts)
|
enolan/Idris-dev
|
codegen/idris-codegen-node/Main.hs
|
bsd-3-clause
| 1,227 | 0 | 12 | 367 | 372 | 190 | 182 | 32 | 3 |
{-# LANGUAGE KindSignatures, GADTs, FlexibleInstances, ScopedTypeVariables #-}
module Network.LambdaBridge.Bus where
import Network.LambdaBridge.Bridge
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Applicative
import Data.Monoid
import Data.Word
import Control.Monad.Writer
import Data.Map as Map
import qualified Data.ByteString as BS
import Data.ByteString (ByteString)
{-
data BusCmdPacket = BusCmdPacket U16 [BusCmd]
data BusCmd
= WriteBus U16 U8 -- single read
| ReadBus U16 -- single write
| ReplyBus U8 -- Send back a specific msg
data BusReplyPacket = BusReplyPacket U16 [U8]
-}
data BusCmd :: * -> * where
BusWrite :: Word16 -> Word8 -> BusCmd ()
BusRead :: Word16 -> BusCmd Word8
Pure :: a -> BusCmd a
Apply :: BusCmd (a -> b)
-> BusCmd a -> BusCmd b
instance Applicative BusCmd where
pure = Pure
(<*>) = Apply
instance Monoid (BusCmd ()) where
mempty = pure ()
mappend b1 b2 = b1 *> b2
instance Functor BusCmd where
fmap f a = pure f <*> a
newtype Board = Board (Frame -> IO (Maybe Frame)) -- Will time out in a Board-specific way
-- ((Frame -> IO ()) -> IO ()) -- request callback on interupt
-- send, waits for response, can time out
send :: Board -> BusCmd a -> IO (Maybe a)
send (Board fn) cmds = do
let req_msg = cmdToRequest cmds
print req_msg
rep_msg <- fn (Frame (BS.pack req_msg))
print rep_msg
case rep_msg of
Nothing -> return Nothing
Just (Frame rep) ->
case cmdWithReply cmds (BS.unpack rep) of
Just (a,[]) -> return (Just a)
Just (a,_) -> return Nothing -- fail "bad format replied"
Nothing -> return Nothing
cmdToRequest :: BusCmd a -> [Word8]
cmdToRequest (BusWrite addr val) = [tagWrite] ++ seq16 addr ++ [val]
cmdToRequest (BusRead addr) = [tagRead] ++ seq16 addr
cmdToRequest (Pure a) = []
cmdToRequest (Apply b1 b2) = cmdToRequest b1 ++ cmdToRequest b2
cmdWithReply :: BusCmd a -> [Word8] -> Maybe (a,[Word8])
cmdWithReply (BusWrite {}) rep = return ((),rep)
cmdWithReply (BusRead _) (val:rep) = return (val,rep)
cmdWithReply (BusRead _) [] = fail "bus reply error"
cmdWithReply (Pure a) rep = return (a,rep)
cmdWithReply (Apply b1 b2) rep0 = do
(f,rep1) <- cmdWithReply b1 rep0
(a,rep2) <- cmdWithReply b2 rep1
return (f a,rep2)
tagWrite, tagRead :: Word8
tagWrite = 0x1
tagRead = 0x2
hi, low :: Word16 -> Word8
hi = fromIntegral . (`div` 256)
low = fromIntegral . (`mod` 256)
seq16 :: Word16 -> [Word8]
seq16 v = [hi v,low v]
unseq16 :: [Word8] -> Word16
unseq16 [h,l] = fromIntegral h * 256 + fromIntegral l
test = do
send brd $
BusWrite 0 1 *>
BusWrite 2 3 *>
BusRead 5 <*
BusWrite 9 10
brd = Board $ error ""
--boardFromBridgeFrame :: Bridge Frame -> IO Board
----------------------------------------------------------------
-- | connectBoard takes an initial timeout time,
-- and a Bridge Frame to the board, and returns
-- an abstact handle to the physical board.
connectBoard :: Float -> Bridge Frame -> IO Board
connectBoard timeoutTime bridge = do
uniq :: MVar Word16 <- newEmptyMVar
forkIO $ let loop n = do
putMVar uniq n
loop (succ n)
in loop 0
callbacks :: Callback Word16 (Maybe Frame) <- liftM Callback $ newMVar Map.empty
forkIO $ forever $ do
Frame bs0 <- fromBridge bridge
case do (a,bs1) <- BS.uncons bs0
(b,bs2) <- BS.uncons bs1
return (unseq16 [a,b],bs2) of
Just (uq,rest)
-- good packet, try respond
| BS.length rest > 0 -> callback callbacks uq (Just (Frame rest))
Nothing -> return () -- faulty packet?
let send (Frame msg) = do
uq <- takeMVar uniq
rep :: MVar (Maybe Frame) <- newEmptyMVar
-- register the callback
register callbacks uq $ putMVar rep
-- set up a delayed timeout response
forkIO $ do
threadDelay (round (timeoutTime * 1000 * 1000))
callback callbacks uq Nothing
toBridge bridge (Frame (BS.append (BS.pack (seq16 uq)) msg))
-- And wait for the callback
takeMVar rep
return $ Board send
-- General code
data Callback k a = Callback (MVar (Map k (a -> IO ())))
register :: (Ord k) => Callback k a -> k -> (a -> IO ()) -> IO ()
register (Callback callbacks) key callback = do
fm <- takeMVar callbacks
putMVar callbacks (insert key callback fm)
callback :: (Ord k) => Callback k a -> k -> a -> IO ()
callback (Callback callbacks) key val = do
fm <- takeMVar callbacks
case Map.lookup key fm of
Nothing -> putMVar callbacks fm -- done
Just f -> do
putMVar callbacks (delete key fm)
f val
|
andygill/lambda-bridge
|
Network/LambdaBridge/Bus.hs
|
bsd-3-clause
| 5,454 | 4 | 17 | 1,909 | 1,645 | 828 | 817 | 110 | 4 |
module Lucid.FoundationSpec (main, spec) where
import Lucid.Foundation
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Instances
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should work fine" $ do
property someFunction
someFunction :: Bool -> Bool -> Property
someFunction x y = x === y
|
athanclark/lucid-foundation
|
test/Lucid/FoundationSpec.hs
|
bsd-3-clause
| 363 | 0 | 13 | 70 | 116 | 61 | 55 | 14 | 1 |
latticePaths :: Num a => Int -> a
latticePaths size = iterate (scanl1 (+)) (repeat 1) !! size !! size
main :: IO ()
main = print $ latticePaths 20
|
JacksonGariety/euler.hs
|
015.hs
|
bsd-3-clause
| 148 | 0 | 9 | 31 | 79 | 38 | 41 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module NejlaCommon.Config
( getConfGenericMaybe
, getConfGeneric
, getConf'
, getConfMaybe'
, getConf
, getConfMaybe
, getConfBool
, getConfBoolMaybe
, loadConf
, Conf.Config
, Conf.Name
) where
import Control.Monad.Logger
import Control.Monad.Trans
import qualified Data.Char as Char
import qualified Data.Configurator as Conf
import qualified Data.Configurator.Types as Conf
import Data.Maybe ( catMaybes )
import Data.Text ( Text )
import qualified Data.Text as Text
import NejlaCommon.Helpers
import System.Environment
import qualified System.Exit as Exit
-- | Generic function to retrieve a configuration option.
--
-- Returns 'Nothing' if the option could not be found
getConfGenericMaybe
:: (MonadLogger m, MonadIO m, Conf.Configured a)
=> (String -> Maybe a) -- ^ Function to convert from string
-> String -- ^ Environment variable to read option from
-> Conf.Name -- ^ Config name to read option from
-> Conf.Config -- ^ Config object to read option from
-> m (Maybe a)
getConfGenericMaybe fromString env confName conf = do
mbConfVal <- liftIO $ Conf.lookup conf confName
case mbConfVal of
Just v -> return $ Just v
Nothing -> do
mbVal <- liftIO $ lookupEnv env
return $ fromString =<< mbVal
-- | Generic function to retrieve a configuration option
getConfGeneric
:: (MonadLogger m, MonadIO m, Conf.Configured a)
=> (String -> Maybe a) -- ^ Function to convert from string
-> String -- ^ Environment variable to read option from
-> Conf.Name -- ^ Config name to read option from
-> Either Text a -- ^ Default value to use when option could not
-- be found or a description of the object to
-- display as an error message
-> Conf.Config -- ^ Config object to read option from
-> m a
getConfGeneric fromString env confName mbDefault conf = do
mbC <- getConfGenericMaybe fromString env confName conf
case mbC of
Nothing -> case mbDefault of
Right d -> return d
Left e -> do
$logError $ "Configuration of `" <> e <> "` is required. \n"
<> " Set environment variable " <> Text.pack env
<> " or configuration variable " <> confName <> "."
liftIO Exit.exitFailure
Just v -> return v
-- | Get configuration option based on Read instance
--
-- /NB/: Do NOT use this for boolean options, use 'getConfBool' instead
getConf' :: (Conf.Configured a, MonadLogger m, MonadIO m, Read a)
=> String -- ^ Environment variable to read option from
-> Conf.Name -- ^ Config name to read option from
-> Either Text a -- ^ Default value to use when option could not be
-- found or a description of the object to display as
-- an error message
-> Conf.Config
-> m a
getConf' = getConfGeneric safeRead
-- | Get configuration option based on Read instance
--
-- /NB/: Do NOT use this for boolean options, use 'getConfBoolMaybe' instead
getConfMaybe' :: (Conf.Configured a, MonadLogger m, MonadIO m, Read a)
=> String -- ^ Environment variable to read option from
-> Conf.Name -- ^ Config name to read option from
-> Conf.Config
-> m (Maybe a)
getConfMaybe' = getConfGenericMaybe safeRead
-- | Get text config option
getConf :: (MonadLogger m, MonadIO m)
=> String -- ^ Environment variable to read option from
-> Conf.Name -- ^ Config name to read option from
-> Either Text Text -- ^ Default value to use when option could not be
-- found or a description of the object to display
-- as an error message
-> Conf.Config
-> m Text
getConf = getConfGeneric (Just . Text.pack)
-- | Get text config option
getConfMaybe :: (MonadLogger m, MonadIO m)
=> String -- ^ Environment variable to read option from
-> Conf.Name -- ^ Config name to read option from
-> Conf.Config
-> m (Maybe Text)
getConfMaybe = getConfGenericMaybe (Just . Text.pack)
-- | Get boolean config option
getConfBool :: (MonadIO m, MonadLogger m)
=> String -- ^ Environment variable to read option from
-> Conf.Name -- ^ Config name to read option from
-> Either Text Bool -- ^ Default value to use when option could not
-- be found or a description of the object to
-- display as an error message
-> Conf.Config
-> m Bool
getConfBool = getConfGeneric parseBool
where
parseBool str
| map Char.toLower str == "true" = Just True
| map Char.toLower str == "false" = Just False
| otherwise = Nothing
-- | Get boolean config option
getConfBoolMaybe :: (MonadIO m, MonadLogger m)
=> String -- ^ Environment variable to read option from
-> Conf.Name -- ^ Config name to read option from
-> Conf.Config
-> m (Maybe Bool)
getConfBoolMaybe = getConfGenericMaybe parseBool
where
parseBool str
| map Char.toLower str == "true" = Just True
| map Char.toLower str == "false" = Just False
| otherwise = Nothing
-- | Load configuration file.
--
-- The file will be read from the location set in CONF_PATH
-- or /data/appname.conf
loadConf :: MonadIO m
=> String -- ^ config file name (appname)
-> m Conf.Config
loadConf appname = liftIO $ do
mbConfPath <- lookupEnv "CONF_PATH"
Conf.load $ catMaybes [ Just . Conf.Optional $ "/data/" <> appname <> ".conf"
, Conf.Required <$> mbConfPath
]
|
nejla/nejla-common
|
src/NejlaCommon/Config.hs
|
bsd-3-clause
| 5,952 | 0 | 23 | 1,814 | 1,117 | 590 | 527 | 112 | 3 |
{-# LANGUAGE QuasiQuotes, TemplateHaskell, ViewPatterns #-}
-- modules of THIS package
import Data.Graph.EasyGrapher
import Data.Graph.PageRank
-- module of fgl
import Data.Graph.Inductive
-- Standard EGGraph Notation & buildGraph
egg1 :: EGGraph String
egg1 = [
"D1" :=> "D2", "D1" :=> "D3", "D1" :=> "D4", "D2" :=> "D3", "D2" :=> "D5",
"D3" :=> "D4", "D4" :=> "D1", "D5" :=> "D3"
]
graph1 :: Gr String ()
graph1 = buildGraph egg1 -- use function "buildGraph" to Build Graph.
-- Same Graph by Quasi Quotes
-- Quasi Quotes supports only (Gr String ()) for time being.
graph1' :: Gr String ()
graph1' = [$gr| D1 -> D2, D1 -> D3, D1 -> D4, D2 -> D3, D2 -> D5,
D3->D4, D4->D1, D5->D3 |]
-- Antiquote pattern
-- Node starting with ' is antiquote. For example, "'s" means
-- the value of local variable s.
mkCyclicGraphWith :: String -> Gr String ()
mkCyclicGraphWith s = [$gr| 's -> 1, 1 -> a, a -> 3c, 3c -> 's |]
-- Pattern Match
-- QuasiQuote is defiend for EGGraph, so we have to convert (gr a ())
-- into (EGGraph a) using fromGr. Use "View pattern" (ghc extension)
-- to use pattern match with type (gr a ()).
leftOfSingleton :: (Ord a) => (Gr a ()) -> Maybe a
leftOfSingleton (fromGr -> [$gr| 'x -> 'y |]) = Just x
leftOfSingleton _ = Nothing
-- |Version 0.3.7 features
-- Polymorphism Support (Only for Expression Quasi Quotations)
-- You can create (Read a, Data a) => (Gr a ()) using Quasi Quotations!
pgr1 :: Gr Int ()
pgr1 = [$gr| 12 -> 23, 23 -> 34, 4, 23 -> 56, 56 -> 12 |]
-- Supported literal notation (for String & Char at this time)
pgr2 :: Gr Char ()
pgr2 = [$gr| 'a' -> 'b', 'c' -> 'd', 'f' |]
pgr3 :: Gr String ()
pgr3 = [$gr| "hoge" -> "bar", "foo bar baz" -> "bar" |]
-- You can omit ' or " if the value of literal doesn't contain whitespace.
pgr2' :: Gr Char ()
pgr2' = [$gr| a -> b, c -> 'd', f |]
pgr3' :: Gr String ()
pgr3' = [$gr| hoge -> bar, "foo bar baz" -> bar |]
-- Group notation
pgr4 :: Gr (Maybe Int) ()
pgr4 = [$gr| (Just 3) -> Nothing, (Just 2) -> (Just 3) |]
main = do
putStr "This is the graph converted from standard EGGraph form."
print graph1
putStrLn "\nThis is converted from following EGGraph: "
print egg1
putStr "\nAnd this is the same graph converted from Quasi Quotes:"
print graph1'
putStr "\n\nAntiquote.\nmkCyclicGraphWith \"foobar\" = "
print $ mkCyclicGraphWith "foobar"
putStrLn "\n\nWe can calculate Pageranks."
putStr "pageRanks graph1 0.4 0.05 = "
print $ pageRanks graph1 0.4 0.05
putStr "\n\nPattern match.\n leftOfSingleton [$gr| 1 |] = "
print (leftOfSingleton [$gr| 1 |] :: Maybe String)
putStr " leftOfSingleton [$gr| 12 -> 23 |] = "
print (leftOfSingleton [$gr| 12 -> 23 |] :: Maybe String)
putStr " leftOfSingleton [$gr| 12 -> 23, 23 -> 34 |] = "
print (leftOfSingleton [$gr| 12 ->23, 23 ->34 |] :: Maybe String)
|
konn/graph-utils
|
Sample.hs
|
bsd-3-clause
| 2,844 | 57 | 10 | 585 | 765 | 419 | 346 | 47 | 1 |
module Main where
import qualified MainCabal as MC
import qualified MainHoogle as MH
import Paths_simple_hunt
import System.Directory (copyFile, createDirectoryIfMissing)
import System.IO
main = do
hSetBuffering stdout NoBuffering
-- create json/00-schema.js
schemaPath <- getDataFileName "00-schema.js"
createDirectoryIfMissing True "json"
copyFile schemaPath "json/00-schema.json"
putStrLn "copied 00-schema.json"
-- create 01-packages.js and 02-ranking.js
MC.main "index.tar.gz"
MH.main "hoogle.tar.gz"
|
erantapaa/simple-hunt
|
app/Main.hs
|
bsd-3-clause
| 527 | 0 | 8 | 73 | 100 | 52 | 48 | 14 | 1 |
module PFDS.Sec5.Ex1 where
import Prelude hiding (head, last, tail, init)
{-| Doctests for Deque
>>> foldl snoc (empty :: BatchedDeque Int) [1..10]
Q [1] [10,9,8,7,6,5,4,3,2]
>>> cons (empty :: BatchedDeque Int) 1
Q [1] []
>>> cons (cons (empty :: BatchedDeque Int) 1) 2
Q [2] [1]
>>> head $ Q [1] []
1
>>> head $ Q [] [1]
1
>>> head $ Q [1] [2]
1
>>> foldl cons (empty :: BatchedDeque Int) [1..10]
Q [10,9,8,7,6,5,4,3,2] [1]
>>> tail $ Q [1,2,3,4,5,6,7,8,9] [10]
Q [2,3,4,5,6,7,8,9] [10]
>>> tail $ Q [1] [2]
Q [] [2]
>>> tail $ Q [1] [10,9,8,7,6,5,4,3,2]
Q [2,3,4,5,6] [10,9,8,7]
>>> init $ Q [1] [10,9,8,7,6,5,4,3,2]
Q [1] [9,8,7,6,5,4,3,2]
>>> init $ Q [1] [2]
Q [1] []
>>> init $ Q [1,2,3,4,5,6,7,8,9] [10]
Q [1,2,3,4] [9,8,7,6,5]
-}
class Deque q where
empty :: q a
isEmpty :: q a -> Bool
cons :: q a -> a -> q a
snoc :: q a -> a -> q a
head :: q a -> a
last :: q a -> a
tail :: q a -> q a
init :: q a -> q a
data BatchedDeque a = Q [a] [a] deriving (Show)
instance Deque BatchedDeque where
empty = Q [] []
isEmpty (Q [] []) = True
isEmpty _ = False
cons (Q f r) x = check (x:f) r
snoc (Q f r) x = check f (x:r)
head (Q [] []) = error "empty"
head (Q [] [x]) = x
head (Q (x:_) _) = x
last (Q [] []) = error "empty"
last (Q [x] []) = x
last (Q _ (x:_)) = x
tail (Q [] []) = error "empty"
tail (Q [] _) = empty
tail (Q (_:f) r) = check f r
init (Q [] []) = error "empty"
init (Q _ []) = empty
init (Q f (_:r)) = check f r
check :: [a] -> [a] -> BatchedDeque a
check [f] [] = Q [f] []
check [] [r] = Q [] [r]
check f [] = Q ff (reverse fr) where (ff, fr) = halve f
check [] r = Q (reverse rr) rf where (rf, rr) = halve r
check f r = Q f r
halve :: [a] -> ([a], [a])
halve xs = splitAt (length xs `div` 2) xs
|
matonix/pfds
|
src/PFDS/Sec5/Ex1.hs
|
bsd-3-clause
| 1,880 | 0 | 10 | 559 | 770 | 395 | 375 | 38 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns#-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -ddump-splices #-}
import Test.Hspec
import Test.HUnit ((@?=))
import Data.Text (Text, pack, unpack, singleton)
import Yesod.Routes.Class hiding (Route)
import qualified Yesod.Routes.Class as YRC
import Yesod.Routes.Parse (parseRoutesFile, parseRoutesNoCheck, parseTypeTree, TypeTree (..))
import Yesod.Routes.Overlap (findOverlapNames)
import Yesod.Routes.TH hiding (Dispatch)
import Language.Haskell.TH.Syntax
import Hierarchy
import qualified Data.ByteString.Char8 as S8
import qualified Data.Set as Set
data MyApp = MyApp
data MySub = MySub
instance RenderRoute MySub where
data
Route
MySub = MySubRoute ([Text], [(Text, Text)])
deriving (Show, Eq, Read)
renderRoute (MySubRoute x) = x
instance ParseRoute MySub where
parseRoute = Just . MySubRoute
getMySub :: MyApp -> MySub
getMySub MyApp = MySub
data MySubParam = MySubParam Int
instance RenderRoute MySubParam where
data
Route
MySubParam = ParamRoute Char
deriving (Show, Eq, Read)
renderRoute (ParamRoute x) = ([singleton x], [])
instance ParseRoute MySubParam where
parseRoute ([unpack -> [x]], _) = Just $ ParamRoute x
parseRoute _ = Nothing
getMySubParam :: MyApp -> Int -> MySubParam
getMySubParam _ = MySubParam
do
texts <- [t|[Text]|]
let resLeaves = map ResourceLeaf
[ Resource "RootR" [] (Methods Nothing ["GET"]) ["foo", "bar"] True
, Resource "BlogPostR" [Static "blog", Dynamic $ ConT ''Text] (Methods Nothing ["GET", "POST"]) [] True
, Resource "WikiR" [Static "wiki"] (Methods (Just texts) []) [] True
, Resource "SubsiteR" [Static "subsite"] (Subsite (ConT ''MySub) "getMySub") [] True
, Resource "SubparamR" [Static "subparam", Dynamic $ ConT ''Int] (Subsite (ConT ''MySubParam) "getMySubParam") [] True
]
resParent = ResourceParent
"ParentR"
True
[ Static "foo"
, Dynamic $ ConT ''Text
]
[ ResourceLeaf $ Resource "ChildR" [] (Methods Nothing ["GET"]) ["child"] True
]
ress = resParent : resLeaves
rrinst <- mkRenderRouteInstance [] (ConT ''MyApp) ress
rainst <- mkRouteAttrsInstance [] (ConT ''MyApp) ress
prinst <- mkParseRouteInstance [] (ConT ''MyApp) ress
dispatch <- mkDispatchClause MkDispatchSettings
{ mdsRunHandler = [|runHandler|]
, mdsSubDispatcher = [|subDispatch dispatcher|]
, mdsGetPathInfo = [|fst|]
, mdsMethod = [|snd|]
, mdsSetPathInfo = [|\p (_, m) -> (p, m)|]
, mds404 = [|pack "404"|]
, mds405 = [|pack "405"|]
, mdsGetHandler = defaultGetHandler
, mdsUnwrapper = return
} ress
return
#if MIN_VERSION_template_haskell(2,11,0)
$ InstanceD Nothing
#else
$ InstanceD
#endif
[]
(ConT ''Dispatcher
`AppT` ConT ''MyApp
`AppT` ConT ''MyApp)
[FunD (mkName "dispatcher") [dispatch]]
: prinst
: rainst
: rrinst
instance Dispatcher MySub master where
dispatcher env (pieces, _method) =
( pack $ "subsite: " ++ show pieces
, Just $ envToMaster env route
)
where
route = MySubRoute (pieces, [])
instance Dispatcher MySubParam master where
dispatcher env (pieces, _method) =
case map unpack pieces of
[[c]] ->
let route = ParamRoute c
toMaster = envToMaster env
MySubParam i = envSub env
in ( pack $ "subparam " ++ show i ++ ' ' : [c]
, Just $ toMaster route
)
_ -> (pack "404", Nothing)
{-
thDispatchAlias
:: (master ~ MyApp, sub ~ MyApp, handler ~ String, app ~ (String, Maybe (YRC.Route MyApp)))
=> master
-> sub
-> (YRC.Route sub -> YRC.Route master)
-> app -- ^ 404 page
-> handler -- ^ 405 page
-> Text -- ^ method
-> [Text]
-> app
--thDispatchAlias = thDispatch
thDispatchAlias master sub toMaster app404 handler405 method0 pieces0 =
case dispatch pieces0 of
Just f -> f master sub toMaster app404 handler405 method0
Nothing -> app404
where
dispatch = toDispatch
[ Route [] False $ \pieces ->
case pieces of
[] -> do
Just $ \master' sub' toMaster' _app404' handler405' method ->
let handler =
case Map.lookup method methodsRootR of
Just f -> f
Nothing -> handler405'
in runHandler handler master' sub' RootR toMaster'
_ -> error "Invariant violated"
, Route [D.Static "blog", D.Dynamic] False $ \pieces ->
case pieces of
[_, x2] -> do
y2 <- fromPathPiece x2
Just $ \master' sub' toMaster' _app404' handler405' method ->
let handler =
case Map.lookup method methodsBlogPostR of
Just f -> f y2
Nothing -> handler405'
in runHandler handler master' sub' (BlogPostR y2) toMaster'
_ -> error "Invariant violated"
, Route [D.Static "wiki"] True $ \pieces ->
case pieces of
_:x2 -> do
y2 <- fromPathMultiPiece x2
Just $ \master' sub' toMaster' _app404' _handler405' _method ->
let handler = handleWikiR y2
in runHandler handler master' sub' (WikiR y2) toMaster'
_ -> error "Invariant violated"
, Route [D.Static "subsite"] True $ \pieces ->
case pieces of
_:x2 -> do
Just $ \master' sub' toMaster' app404' handler405' method ->
dispatcher master' (getMySub sub') (toMaster' . SubsiteR) app404' handler405' method x2
_ -> error "Invariant violated"
, Route [D.Static "subparam", D.Dynamic] True $ \pieces ->
case pieces of
_:x2:x3 -> do
y2 <- fromPathPiece x2
Just $ \master' sub' toMaster' app404' handler405' method ->
dispatcher master' (getMySubParam sub' y2) (toMaster' . SubparamR y2) app404' handler405' method x3
_ -> error "Invariant violated"
]
methodsRootR = Map.fromList [("GET", getRootR)]
methodsBlogPostR = Map.fromList [("GET", getBlogPostR), ("POST", postBlogPostR)]
-}
main :: IO ()
main = hspec $ do
describe "RenderRoute instance" $ do
it "renders root correctly" $ renderRoute RootR @?= ([], [])
it "renders blog post correctly" $ renderRoute (BlogPostR $ pack "foo") @?= (map pack ["blog", "foo"], [])
it "renders wiki correctly" $ renderRoute (WikiR $ map pack ["foo", "bar"]) @?= (map pack ["wiki", "foo", "bar"], [])
it "renders subsite correctly" $ renderRoute (SubsiteR $ MySubRoute (map pack ["foo", "bar"], [(pack "baz", pack "bin")]))
@?= (map pack ["subsite", "foo", "bar"], [(pack "baz", pack "bin")])
it "renders subsite param correctly" $ renderRoute (SubparamR 6 $ ParamRoute 'c')
@?= (map pack ["subparam", "6", "c"], [])
describe "thDispatch" $ do
let disp m ps = dispatcher
(Env
{ envToMaster = id
, envMaster = MyApp
, envSub = MyApp
})
(map pack ps, S8.pack m)
it "routes to root" $ disp "GET" [] @?= (pack "this is the root", Just RootR)
it "POST root is 405" $ disp "POST" [] @?= (pack "405", Just RootR)
it "invalid page is a 404" $ disp "GET" ["not-found"] @?= (pack "404", Nothing :: Maybe (YRC.Route MyApp))
it "routes to blog post" $ disp "GET" ["blog", "somepost"]
@?= (pack "some blog post: somepost", Just $ BlogPostR $ pack "somepost")
it "routes to blog post, POST method" $ disp "POST" ["blog", "somepost2"]
@?= (pack "POST some blog post: somepost2", Just $ BlogPostR $ pack "somepost2")
it "routes to wiki" $ disp "DELETE" ["wiki", "foo", "bar"]
@?= (pack "the wiki: [\"foo\",\"bar\"]", Just $ WikiR $ map pack ["foo", "bar"])
it "routes to subsite" $ disp "PUT" ["subsite", "baz"]
@?= (pack "subsite: [\"baz\"]", Just $ SubsiteR $ MySubRoute ([pack "baz"], []))
it "routes to subparam" $ disp "PUT" ["subparam", "6", "q"]
@?= (pack "subparam 6 q", Just $ SubparamR 6 $ ParamRoute 'q')
describe "route parsing" $ do
it "subsites work" $ do
parseRoute ([pack "subsite", pack "foo"], [(pack "bar", pack "baz")]) @?=
Just (SubsiteR $ MySubRoute ([pack "foo"], [(pack "bar", pack "baz")]))
describe "routing table parsing" $ do
it "recognizes trailing backslashes as line continuation directives" $ do
let routes :: [ResourceTree String]
routes = $(parseRoutesFile "test/fixtures/routes_with_line_continuations.yesodroutes")
length routes @?= 3
describe "overlap checking" $ do
it "catches overlapping statics" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/foo Foo1
/foo Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping dynamics" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/#Int Foo1
/#String Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping statics and dynamics" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/foo Foo1
/#String Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping multi" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/foo Foo1
/##*Strings Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping subsite" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/foo Foo1
/foo Foo2 Subsite getSubsite
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "no false positives" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/foo Foo1
/bar/#String Foo2
|]
findOverlapNames routes @?= []
it "obeys ignore rules" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/foo Foo1
/#!String Foo2
/!foo Foo3
|]
findOverlapNames routes @?= []
it "obeys multipiece ignore rules #779" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/foo Foo1
/+![String] Foo2
|]
findOverlapNames routes @?= []
it "ignore rules for entire route #779" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/foo Foo1
!/+[String] Foo2
!/#String Foo3
!/foo Foo4
|]
findOverlapNames routes @?= []
it "ignore rules for hierarchy" $ do
let routes :: [ResourceTree String]
routes = [parseRoutesNoCheck|
/+[String] Foo1
!/foo Foo2:
/foo Foo3
/foo Foo4:
/!#foo Foo5
|]
findOverlapNames routes @?= []
it "proper boolean logic" $ do
let routes = [parseRoutesNoCheck|
/foo/bar Foo1
/foo/baz Foo2
/bar/baz Foo3
|]
findOverlapNames routes @?= []
describe "routeAttrs" $ do
it "works" $ do
routeAttrs RootR @?= Set.fromList [pack "foo", pack "bar"]
it "hierarchy" $ do
routeAttrs (ParentR (pack "ignored") ChildR) @?= Set.singleton (pack "child")
hierarchy
describe "parseRouteType" $ do
let success s t = it s $ parseTypeTree s @?= Just t
failure s = it s $ parseTypeTree s @?= Nothing
success "Int" $ TTTerm "Int"
success "(Int)" $ TTTerm "Int"
failure "(Int"
failure "(Int))"
failure "[Int"
failure "[Int]]"
success "[Int]" $ TTList $ TTTerm "Int"
success "Foo-Bar" $ TTApp (TTTerm "Foo") (TTTerm "Bar")
success "Foo-Bar-Baz" $ TTApp (TTTerm "Foo") (TTTerm "Bar") `TTApp` TTTerm "Baz"
success "Foo Bar" $ TTApp (TTTerm "Foo") (TTTerm "Bar")
success "Foo Bar Baz" $ TTApp (TTTerm "Foo") (TTTerm "Bar") `TTApp` TTTerm "Baz"
getRootR :: Text
getRootR = pack "this is the root"
getBlogPostR :: Text -> String
getBlogPostR t = "some blog post: " ++ unpack t
postBlogPostR :: Text -> Text
postBlogPostR t = pack $ "POST some blog post: " ++ unpack t
handleWikiR :: [Text] -> String
handleWikiR ts = "the wiki: " ++ show ts
getChildR :: Text -> Text
getChildR = id
|
geraldus/yesod
|
yesod-core/test/RouteSpec.hs
|
mit
| 13,589 | 2 | 22 | 4,321 | 3,079 | 1,575 | 1,504 | 217 | 1 |
{-# LANGUAGE DeriveFunctor, DeriveFoldable #-}
module Types
( module Types, Word8, Word16, Word32 )
where
import qualified Data.ByteString.Lazy as B
import Data.Word
import qualified Data.Map as M
import Data.Foldable (Foldable)
-- Main data types
type Offset = Word32
type Segment = (Offset, Word32, [String])
type Segments = [Segment]
data Register = RegPos Word16 | RegName String
deriving (Show, Eq, Ord)
type ResReg = Word16
data TVal r
= Reg r
| Const Word16
deriving (Eq, Functor, Foldable)
data Conditional r = Cond (TVal r) CondOp (TVal r)
deriving (Eq, Functor, Foldable)
data CondOp
= Eq
| Gt
| Lt
| GEq
| LEq
| NEq
| Unknowncond B.ByteString
deriving (Eq)
data ArithOp
= Inc | Dec | Mult | Div | Mod | And | Or | XOr | Set
deriving (Eq, Bounded, Enum)
data Command r
= Play Word16
| Random Word8 Word8
| Cancel
| Game Word16
| ArithOp ArithOp r (TVal r)
| Neg r
| Unknown B.ByteString r (TVal r)
| Jump (TVal r)
| NamedJump String -- Only in YAML files, never read from GMEs
deriving (Eq, Functor, Foldable)
type PlayList = [Word16]
data Line r = Line Offset [Conditional r] [Command r] PlayList
deriving (Functor, Foldable)
type ProductID = Word32
data TipToiFile = TipToiFile
{ ttProductId :: ProductID
, ttRawXor :: Word32
, ttComment :: B.ByteString
, ttDate :: B.ByteString
, ttInitialRegs :: [Word16]
, ttWelcome :: [PlayList]
, ttScripts :: [(Word16, Maybe [Line ResReg])]
, ttGames :: [Game]
, ttAudioFiles :: [B.ByteString]
, ttAudioFilesDoubles :: Bool
, ttAudioXor :: Word8
, ttBinaries1 :: [(B.ByteString, B.ByteString)]
, ttBinaries2 :: [(B.ByteString, B.ByteString)]
, ttBinaries3 :: [(B.ByteString, B.ByteString)]
, ttBinaries4 :: [(B.ByteString, B.ByteString)]
, ttSpecialOIDs :: Maybe (Word16, Word16)
, ttChecksum :: Word32
, ttChecksumCalc :: Word32
}
type PlayListList = [PlayList]
type GameId = Word16
data Game
= Game6 Word16 B.ByteString [PlayListList] [SubGame] [SubGame] B.ByteString [PlayListList] PlayList
| Game7 Word16 Word16 B.ByteString [PlayListList] [SubGame] B.ByteString [PlayListList] PlayListList
| Game8 Word16 Word16 B.ByteString [PlayListList] [SubGame] B.ByteString [PlayListList] [OID] [GameId] PlayListList PlayListList
| Game9
| Game10
| Game16
| Game253
| UnknownGame Word16 Word16 Word16 B.ByteString [PlayListList] [SubGame] B.ByteString [PlayListList]
deriving Show
type OID = Word16
data SubGame
= SubGame B.ByteString [OID] [OID] [OID] [PlayListList]
deriving Show
type Transscript = M.Map Word16 String
type CodeMap = M.Map String Word16
|
christiannolte/tip-toi-reveng
|
src/Types.hs
|
mit
| 2,752 | 0 | 13 | 633 | 879 | 528 | 351 | 83 | 0 |
--
--
--
-----------------
-- Exercise 7.15.
-----------------
--
--
--
module E'7'15 where
import E'7'12 ( iSort )
import Test.QuickCheck
-- If we sort the same set of 'objects in any order', the result should always be the same sorted set.
-- Especially an already sorted sets' elements should preserve their order when sorted again.
prop_iSort_idempotency :: [Integer] -> Bool
prop_iSort_idempotency integerList
= sortedIntegerList == iSort sortedIntegerList
where
sortedIntegerList :: [Integer]
sortedIntegerList = iSort integerList
-- GHCi> quickCheck prop_iSort_idempotency
|
pascal-knodel/haskell-craft
|
_/links/E'7'15.hs
|
mit
| 607 | 0 | 7 | 107 | 74 | 47 | 27 | 8 | 1 |
-- The 'unix' module provides 'RawFilePath'-variants of all functions, but
-- higher-level wrappers of it such as 'directory' or 'process' doesn't.
-- This module provides it.
--
module RawFilePath
( RawFilePath
, callProcess
, callProcessSilent
, readProcess
, rwProcess
, eraseProcess
, getDirectoryContents
, getDirectoryContentsSuffix
, copyFile
, getHomeDirectory
, getAppDirectory
, fileExist
, changeWorkingDirectory
, tryRemoveFile
, (</>)
) where
import Data.Monoid
import Control.Monad
import Control.Exception
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import System.IO
import System.IO.Error
import System.Exit (ExitCode(..), exitFailure)
import Foreign.Marshal.Alloc (allocaBytes)
import System.Posix.ByteString
infixr 5 </>
(</>) :: RawFilePath -> RawFilePath -> RawFilePath
a </> b = mconcat [a, "/", b]
callProcess :: RawFilePath -> [ByteString] -> IO ()
callProcess cmd args = do
pid <- forkProcess $ executeFile cmd True args Nothing
getProcessStatus True False pid >>= \ mstatus -> case mstatus of
Just status -> case status of
Exited exitCode -> case exitCode of
ExitSuccess -> return ()
ExitFailure _ -> die cmd
_ -> die cmd
Nothing -> die cmd
callProcessSilent :: RawFilePath -> [ByteString] -> IO ExitCode
callProcessSilent cmd args = do
pid <- forkProcess $ do
closeFd stdOutput
closeFd stdError
executeFile cmd True args Nothing
getProcessStatus True False pid >>= \ mstatus -> case mstatus of
Just status -> case status of
Exited exitCode -> return exitCode
_ -> die cmd
Nothing -> die cmd
readProcess
:: RawFilePath -> [ByteString]
-> IO (Either ByteString ByteString)
readProcess cmd args = do
(fd0, fd1) <- createPipe
(efd0, efd1) <- createPipe
pid <- forkProcess $ do
closeFd fd0
closeFd stdOutput
void $ dupTo fd1 stdOutput
closeFd efd0
closeFd stdError
void $ dupTo efd1 stdError
executeFile cmd True args Nothing
closeFd fd1
closeFd efd1
content <- closeFd efd0 *> getAndClose fd0
getProcessStatus True False pid >>= \ mstatus -> case mstatus of
Just status -> case status of
Exited exitCode -> case exitCode of
ExitSuccess -> return $ Right content
ExitFailure _ -> fmap Left $
closeFd fd0 *> getAndClose efd0
_ -> die cmd
Nothing -> die cmd
where
getAndClose fd = fdToHandle fd >>= \h -> B.hGetContents h <* hClose h
rwProcess
:: RawFilePath -> [ByteString]
-> IO (ProcessID, Handle, Handle)
rwProcess cmd args = do
(fd0, fd1) <- createPipe
pid <- forkProcess $ do
closeFd stdInput
closeFd stdOutput
void $ dupTo fd0 stdInput
void $ dupTo fd1 stdOutput
executeFile cmd True args Nothing
h0 <- fdToHandle fd0
h1 <- fdToHandle fd1
return (pid, h1, h0)
eraseProcess :: ProcessID -> IO ()
eraseProcess pid = do
signalProcess sigKILL pid
void $ getProcessStatus True False pid
getDirectoryContents :: RawFilePath -> IO [RawFilePath]
getDirectoryContents dirPath = bracket open close repeatRead
where
open = openDirStream dirPath
close = closeDirStream
repeatRead stream = do
d <- readDirStream stream
if B.length d == 0 then return [] else do
rest <- repeatRead stream
return $ d : rest
getDirectoryContentsSuffix :: RawFilePath -> ByteString -> IO [RawFilePath]
getDirectoryContentsSuffix dirPath suffix = bracket open close repeatRead
where
open = openDirStream dirPath
close = closeDirStream
repeatRead stream = do
d <- readDirStream stream
if B.length d == 0 then return [] else do
rest <- repeatRead stream
return $ (if suffix `B.isSuffixOf` d then (d :) else id) rest
defaultFlags :: OpenFileFlags
defaultFlags = OpenFileFlags
{ append = False
, exclusive = False
, noctty = True
, nonBlock = False
, trunc = False
}
-- Buffer size for file copy
bufferSize :: Int
bufferSize = 4096
copyFile :: RawFilePath -> RawFilePath -> IO ()
copyFile srcPath tgtPath = do
bracket ropen hClose $ \ hi ->
bracket topen hClose $ \ ho ->
allocaBytes bufferSize $ copyContents hi ho
rename tmpPath tgtPath
where
ropen = openFd srcPath ReadOnly Nothing defaultFlags >>= fdToHandle
topen = createFile tmpPath stdFileMode >>= fdToHandle
tmpPath = tgtPath <> ".copyFile.tmp"
copyContents hi ho buffer = do
count <- hGetBuf hi buffer bufferSize
when (count > 0) $ do
hPutBuf ho buffer count
copyContents hi ho buffer
-- A function that "tries" to remove a file.
-- If the file does not exist, nothing happens.
tryRemoveFile :: RawFilePath -> IO ()
tryRemoveFile path = catchIOError (removeLink path) $
\ e -> unless (isDoesNotExistError e) $ ioError e
getHomeDirectory :: IO RawFilePath
getHomeDirectory = getEnv "HOME" >>= maybe (die noHomeErrMsg) return
getAppDirectory :: RawFilePath -> IO RawFilePath
getAppDirectory app = fmap (</> ".config" </> app) getHomeDirectory
die :: ByteString -> IO a
die msg = B.putStr ("Error: " <> msg) *> exitFailure
noHomeErrMsg :: ByteString
noHomeErrMsg = "This application requires the $HOME environment variable.\n"
|
kinoru/prospect
|
src/RawFilePath.hs
|
agpl-3.0
| 5,532 | 0 | 20 | 1,473 | 1,594 | 791 | 803 | 146 | 4 |
-- |
-- Copyright : (c) Sam Truzjan 2013
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Every node maintains a routing table of known good nodes. The
-- nodes in the routing table are used as starting points for
-- queries in the DHT. Nodes from the routing table are returned in
-- response to queries from other nodes.
--
-- For more info see:
-- <http://www.bittorrent.org/beps/bep_0005.html#routing-table>
--
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DeriveGeneric #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Network.BitTorrent.DHT.Routing
( -- * Table
Table
-- * Attributes
, BucketCount
, defaultBucketCount
, BucketSize
, defaultBucketSize
, NodeCount
-- * Query
, Network.BitTorrent.DHT.Routing.null
, Network.BitTorrent.DHT.Routing.full
, thisId
, shape
, Network.BitTorrent.DHT.Routing.size
, Network.BitTorrent.DHT.Routing.depth
-- * Lookup
, K
, defaultK
, TableKey (..)
, kclosest
-- * Construction
, Network.BitTorrent.DHT.Routing.nullTable
, Network.BitTorrent.DHT.Routing.insert
-- * Conversion
, Network.BitTorrent.DHT.Routing.TableEntry
, Network.BitTorrent.DHT.Routing.toList
-- * Routing
, Timestamp
, Routing
, runRouting
) where
import Control.Applicative as A
import Control.Arrow
import Control.Monad
import Data.Function
import Data.List as L hiding (insert)
import Data.Maybe
import Data.Monoid
import Data.PSQueue as PSQ
import Data.Serialize as S hiding (Result, Done)
import Data.Time
import Data.Time.Clock.POSIX
import Data.Word
import GHC.Generics
import Text.PrettyPrint as PP hiding ((<>))
import Text.PrettyPrint.Class
import Data.Torrent
import Network.BitTorrent.Address
{-----------------------------------------------------------------------
-- Routing monad
-----------------------------------------------------------------------}
-- | Last time the node was responding to our queries.
--
-- Not all nodes that we learn about are equal. Some are \"good\" and
-- some are not. Many nodes using the DHT are able to send queries
-- and receive responses, but are not able to respond to queries
-- from other nodes. It is important that each node's routing table
-- must contain only known good nodes. A good node is a node has
-- responded to one of our queries within the last 15 minutes. A
-- node is also good if it has ever responded to one of our queries
-- and has sent us a query within the last 15 minutes. After 15
-- minutes of inactivity, a node becomes questionable. Nodes become
-- bad when they fail to respond to multiple queries in a row. Nodes
-- that we know are good are given priority over nodes with unknown
-- status.
--
type Timestamp = POSIXTime
-- | Some routing operations might need to perform additional IO.
data Routing ip result
= Full
| Done result
| GetTime ( Timestamp -> Routing ip result)
| NeedPing (NodeAddr ip) ( Bool -> Routing ip result)
| Refresh NodeId ([NodeInfo ip] -> Routing ip result)
instance Functor (Routing ip) where
fmap _ Full = Full
fmap f (Done r) = Done ( f r)
fmap f (GetTime g) = GetTime (fmap f . g)
fmap f (NeedPing addr g) = NeedPing addr (fmap f . g)
fmap f (Refresh nid g) = Refresh nid (fmap f . g)
instance Monad (Routing ip) where
return = Done
Full >>= _ = Full
Done r >>= m = m r
GetTime f >>= m = GetTime $ \ t -> f t >>= m
NeedPing a f >>= m = NeedPing a $ \ p -> f p >>= m
Refresh n f >>= m = Refresh n $ \ i -> f i >>= m
instance Applicative (Routing ip) where
pure = return
(<*>) = ap
instance Alternative (Routing ip) where
empty = Full
Full <|> m = m
Done a <|> _ = Done a
GetTime f <|> m = GetTime $ \ t -> f t <|> m
NeedPing a f <|> m = NeedPing a $ \ p -> f p <|> m
Refresh n f <|> m = Refresh n $ \ i -> f i <|> m
-- | Run routing table operation.
runRouting :: (Monad m, Eq ip)
=> (NodeAddr ip -> m Bool) -- ^ ping the specific node;
-> (NodeId -> m [NodeInfo ip]) -- ^ get closest nodes;
-> m Timestamp -- ^ get current time;
-> Routing ip f -- ^ operation to run;
-> m (Maybe f) -- ^ operation result;
runRouting ping_node find_nodes timestamper = go
where
go Full = return (Nothing)
go (Done r) = return (Just r)
go (GetTime f) = do
t <- timestamper
go (f t)
go (NeedPing addr f) = do
pong <- ping_node addr
go (f pong)
go (Refresh nid f) = do
infos <- find_nodes nid
go (f infos)
getTime :: Routing ip Timestamp
getTime = GetTime return
{-# INLINE getTime #-}
needPing :: NodeAddr ip -> Routing ip Bool
needPing addr = NeedPing addr return
{-# INLINE needPing #-}
refresh :: NodeId -> Routing ip [NodeInfo ip]
refresh nid = Refresh nid return
{-# INLINE refresh #-}
{-----------------------------------------------------------------------
Bucket
-----------------------------------------------------------------------}
-- TODO: add replacement cache to the bucket
--
-- When a k-bucket is full and a new node is discovered for that
-- k-bucket, the least recently seen node in the k-bucket is
-- PINGed. If the node is found to be still alive, the new node is
-- place in a secondary list, a replacement cache. The replacement
-- cache is used only if a node in the k-bucket stops responding. In
-- other words: new nodes are used only when older nodes disappear.
-- | Timestamp - last time this node is pinged.
type NodeEntry ip = Binding (NodeInfo ip) Timestamp
instance (Serialize k, Serialize v) => Serialize (Binding k v) where
get = (:->) <$> get <*> get
put (k :-> v) = put k >> put v
-- TODO instance Pretty where
-- | Number of nodes in a bucket.
type BucketSize = Int
-- | Maximum number of 'NodeInfo's stored in a bucket. Most clients
-- use this value.
defaultBucketSize :: BucketSize
defaultBucketSize = 8
-- | Bucket is also limited in its length — thus it's called k-bucket.
-- When bucket becomes full, we should split it in two lists by
-- current span bit. Span bit is defined by depth in the routing
-- table tree. Size of the bucket should be choosen such that it's
-- very unlikely that all nodes in bucket fail within an hour of
-- each other.
--
type Bucket ip = PSQ (NodeInfo ip) Timestamp
instance (Serialize k, Serialize v, Ord k, Ord v)
=> Serialize (PSQ k v) where
get = PSQ.fromList <$> get
put = put . PSQ.toList
-- | Get the most recently changed node entry, if any.
lastChanged :: Eq ip => Bucket ip -> Maybe (NodeEntry ip)
lastChanged bucket
| L.null timestamps = Nothing
| otherwise = Just (L.maximumBy (compare `on` prio) timestamps)
where
timestamps = PSQ.toList bucket
leastRecently :: Eq ip => Bucket ip -> Maybe (NodeEntry ip, Bucket ip)
leastRecently = minView
-- | Update interval, in seconds.
delta :: NominalDiffTime
delta = 15 * 60
-- | Should maintain a set of stable long running nodes.
insertBucket :: Eq ip => Timestamp -> NodeInfo ip -> Bucket ip
-> ip `Routing` Bucket ip
insertBucket curTime info bucket
-- just update timestamp if a node is already in bucket
| Just _ <- PSQ.lookup info bucket = do
return $ PSQ.insertWith max info curTime bucket
-- Buckets that have not been changed in 15 minutes should be "refreshed."
| Just (NodeInfo {..} :-> lastSeen) <- lastChanged bucket
, curTime - lastSeen > delta = do
infos <- refresh nodeId
refTime <- getTime
let newBucket = L.foldr (\ x -> PSQ.insertWith max x refTime) bucket infos
insertBucket refTime info newBucket
-- If there are any questionable nodes in the bucket have not been
-- seen in the last 15 minutes, the least recently seen node is
-- pinged. If any nodes in the bucket are known to have become bad,
-- then one is replaced by the new node in the next insertBucket
-- iteration.
| Just ((old @ NodeInfo {..} :-> leastSeen), rest) <- leastRecently bucket
, curTime - leastSeen > delta = do
pong <- needPing nodeAddr
pongTime <- getTime
let newBucket = if pong then PSQ.insert old pongTime bucket else rest
insertBucket pongTime info newBucket
-- bucket is good, but not full => we can insert a new node
| PSQ.size bucket < defaultBucketSize = do
return $ PSQ.insert info curTime bucket
-- When the bucket is full of good nodes, the new node is simply discarded.
| otherwise = A.empty
insertNode :: Eq ip => NodeInfo ip -> Bucket ip -> ip `Routing` Bucket ip
insertNode info bucket = do
curTime <- getTime
insertBucket curTime info bucket
type BitIx = Word
split :: Eq ip => BitIx -> Bucket ip -> (Bucket ip, Bucket ip)
split i = (PSQ.fromList *** PSQ.fromList) . partition spanBit . PSQ.toList
where
spanBit entry = testIdBit (nodeId (key entry)) i
{-----------------------------------------------------------------------
-- Table
-----------------------------------------------------------------------}
-- | Number of buckets in a routing table.
type BucketCount = Int
defaultBucketCount :: BucketCount
defaultBucketCount = 20
-- | The routing table covers the entire 'NodeId' space from 0 to 2 ^
-- 160. The routing table is subdivided into 'Bucket's that each cover
-- a portion of the space. An empty table has one bucket with an ID
-- space range of @min = 0, max = 2 ^ 160@. When a node with ID \"N\"
-- is inserted into the table, it is placed within the bucket that has
-- @min <= N < max@. An empty table has only one bucket so any node
-- must fit within it. Each bucket can only hold 'K' nodes, currently
-- eight, before becoming 'Full'. When a bucket is full of known good
-- nodes, no more nodes may be added unless our own 'NodeId' falls
-- within the range of the 'Bucket'. In that case, the bucket is
-- replaced by two new buckets each with half the range of the old
-- bucket and the nodes from the old bucket are distributed among the
-- two new ones. For a new table with only one bucket, the full bucket
-- is always split into two new buckets covering the ranges @0..2 ^
-- 159@ and @2 ^ 159..2 ^ 160@.
--
data Table ip
-- most nearest bucket
= Tip NodeId BucketCount (Bucket ip)
-- left biased tree branch
| Zero (Table ip) (Bucket ip)
-- right biased tree branch
| One (Bucket ip) (Table ip)
deriving (Show, Generic)
instance Eq ip => Eq (Table ip) where
(==) = (==) `on` Network.BitTorrent.DHT.Routing.toList
instance Serialize NominalDiffTime where
put = putWord32be . fromIntegral . fromEnum
get = (toEnum . fromIntegral) <$> getWord32be
-- | Normally, routing table should be saved between invocations of
-- the client software. Note that you don't need to store /this/
-- 'NodeId' since it is already included in routing table.
instance (Eq ip, Serialize ip) => Serialize (Table ip)
-- | Shape of the table.
instance Pretty (Table ip) where
pretty t
| bucketCount < 6 = hcat $ punctuate ", " $ L.map PP.int ss
| otherwise = brackets $
PP.int (L.sum ss) <> " nodes, " <>
PP.int bucketCount <> " buckets"
where
bucketCount = L.length ss
ss = shape t
-- | Empty table with specified /spine/ node id.
nullTable :: Eq ip => NodeId -> BucketCount -> Table ip
nullTable nid n = Tip nid (bucketCount (pred n)) PSQ.empty
where
bucketCount x = max 0 (min 159 x)
-- | Test if table is empty. In this case DHT should start
-- bootstrapping process until table becomes 'full'.
null :: Table ip -> Bool
null (Tip _ _ b) = PSQ.null b
null _ = False
-- | Test if table have maximum number of nodes. No more nodes can be
-- 'insert'ed, except old ones becomes bad.
full :: Table ip -> Bool
full (Tip _ n _) = n == 0
full (Zero t b) = PSQ.size b == defaultBucketSize && full t
full (One b t) = PSQ.size b == defaultBucketSize && full t
-- | Get the /spine/ node id.
thisId :: Table ip -> NodeId
thisId (Tip nid _ _) = nid
thisId (Zero table _) = thisId table
thisId (One _ table) = thisId table
-- | Number of nodes in a bucket or a table.
type NodeCount = Int
-- | Internally, routing table is similar to list of buckets or a
-- /matrix/ of nodes. This function returns the shape of the matrix.
shape :: Table ip -> [BucketSize]
shape (Tip _ _ bucket) = [PSQ.size bucket]
shape (Zero t bucket) = PSQ.size bucket : shape t
shape (One bucket t ) = PSQ.size bucket : shape t
-- | Get number of nodes in the table.
size :: Table ip -> NodeCount
size = L.sum . shape
-- | Get number of buckets in the table.
depth :: Table ip -> BucketCount
depth = L.length . shape
lookupBucket :: NodeId -> Table ip -> Maybe (Bucket ip)
lookupBucket nid = go 0
where
go i (Zero table bucket)
| testIdBit nid i = pure bucket
| otherwise = go (succ i) table
go i (One bucket table)
| testIdBit nid i = go (succ i) table
| otherwise = pure bucket
go _ (Tip _ _ bucket) = pure bucket
-- | Count of closest nodes in find_node request.
type K = Int
-- | Default 'K' is equal to 'defaultBucketSize'.
defaultK :: K
defaultK = 8
class TableKey k where
toNodeId :: k -> NodeId
instance TableKey NodeId where
toNodeId = id
instance TableKey InfoHash where
toNodeId = either (error msg) id . S.decode . S.encode
where -- TODO unsafe coerse?
msg = "tableKey: impossible"
-- | Get a list of /K/ closest nodes using XOR metric. Used in
-- 'find_node' and 'get_peers' queries.
kclosest :: Eq ip => TableKey a => K -> a -> Table ip -> [NodeInfo ip]
kclosest k (toNodeId -> nid)
= L.take k . rank nid
. L.map PSQ.key . PSQ.toList . fromMaybe PSQ.empty
. lookupBucket nid
{-----------------------------------------------------------------------
-- Routing
-----------------------------------------------------------------------}
splitTip :: Eq ip => NodeId -> BucketCount -> BitIx -> Bucket ip -> Table ip
splitTip nid n i bucket
| testIdBit nid i = (One zeros (Tip nid (pred n) ones))
| otherwise = (Zero (Tip nid (pred n) zeros) ones)
where
(zeros, ones) = split i bucket
-- | Used in each query.
insert :: Eq ip => NodeInfo ip -> Table ip -> ip `Routing` Table ip
insert info @ NodeInfo {..} = go (0 :: BitIx)
where
go i (Zero table bucket)
| testIdBit nodeId i = Zero table <$> insertNode info bucket
| otherwise = (`Zero` bucket) <$> go (succ i) table
go i (One bucket table )
| testIdBit nodeId i = One bucket <$> go (succ i) table
| otherwise = (`One` table) <$> insertNode info bucket
go i (Tip nid n bucket)
| n == 0 = Tip nid n <$> insertNode info bucket
| otherwise = Tip nid n <$> insertNode info bucket
<|> go (succ i) (splitTip nid n i bucket)
{-----------------------------------------------------------------------
-- Conversion
-----------------------------------------------------------------------}
type TableEntry ip = (NodeInfo ip, Timestamp)
tableEntry :: NodeEntry ip -> TableEntry ip
tableEntry (a :-> b) = (a, b)
-- | Non-empty list of buckets.
toBucketList :: Table ip -> [Bucket ip]
toBucketList (Tip _ _ b) = [b]
toBucketList (Zero t b) = b : toBucketList t
toBucketList (One b t) = b : toBucketList t
toList :: Eq ip => Table ip -> [[TableEntry ip]]
toList = L.map (L.map tableEntry . PSQ.toList) . toBucketList
|
DavidAlphaFox/bittorrent
|
src/Network/BitTorrent/DHT/Routing.hs
|
bsd-3-clause
| 15,882 | 3 | 16 | 3,887 | 3,815 | 1,983 | 1,832 | -1 | -1 |
--------------------------------------------------------------------
-- |
-- Module : Text.RSS.Syntax
-- Copyright : (c) Galois, Inc. 2008
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <[email protected]>
-- Stability : provisional
-- Description: The basic syntax for putting together feeds. For instance,
-- to create a feed with a single item item:
-- (nullRSS \"rss title\" \"link\") {rssChannel=(nullChannel \"channel title\" \"link\") {rssItems=[(nullItem \"item title\")]}}
--------------------------------------------------------------------
module Text.RSS.Syntax where
import Text.XML.Light as XML
-- * Core Types
-- ^The Radio Userland version of RSS documents\/feeds.
-- (versions 0.9x, 2.x)
data RSS
= RSS
{ rssVersion :: String
, rssAttrs :: [XML.Attr]
, rssChannel :: RSSChannel
, rssOther :: [XML.Element]
}
deriving (Show)
type URLString = String
-- | RFC 822 conforming.
type DateString = String
data RSSChannel
= RSSChannel
{ rssTitle :: String
, rssLink :: URLString
, rssDescription :: String
, rssItems :: [RSSItem]
, rssLanguage :: Maybe String
, rssCopyright :: Maybe String
, rssEditor :: Maybe String
, rssWebMaster :: Maybe String
, rssPubDate :: Maybe DateString -- ^ rfc 822 conforming.
, rssLastUpdate :: Maybe DateString -- ^ rfc 822 conforming.
, rssCategories :: [RSSCategory]
, rssGenerator :: Maybe String
, rssDocs :: Maybe URLString
, rssCloud :: Maybe RSSCloud
, rssTTL :: Maybe Integer
, rssImage :: Maybe RSSImage
, rssRating :: Maybe String
, rssTextInput :: Maybe RSSTextInput
, rssSkipHours :: Maybe [Integer]
, rssSkipDays :: Maybe [String]
, rssChannelOther :: [XML.Element]
}
deriving (Show)
data RSSItem
= RSSItem
{ rssItemTitle :: Maybe String
, rssItemLink :: Maybe URLString
, rssItemDescription :: Maybe String -- ^if not present, the title is. (per spec, at least.)
, rssItemAuthor :: Maybe String
, rssItemCategories :: [RSSCategory]
, rssItemComments :: Maybe URLString
, rssItemEnclosure :: Maybe RSSEnclosure
, rssItemGuid :: Maybe RSSGuid
, rssItemPubDate :: Maybe DateString
, rssItemSource :: Maybe RSSSource
, rssItemAttrs :: [XML.Attr]
, rssItemOther :: [XML.Element]
}
deriving (Show)
data RSSSource
= RSSSource
{ rssSourceURL :: URLString
, rssSourceAttrs :: [XML.Attr]
, rssSourceTitle :: String
}
deriving (Show)
data RSSEnclosure
= RSSEnclosure
{ rssEnclosureURL :: URLString
, rssEnclosureLength :: Integer
, rssEnclosureType :: String
, rssEnclosureAttrs :: [XML.Attr]
}
deriving (Show)
data RSSCategory
= RSSCategory
{ rssCategoryDomain :: Maybe String
, rssCategoryAttrs :: [XML.Attr]
, rssCategoryValue :: String
}
deriving (Show)
data RSSGuid
= RSSGuid
{ rssGuidPermanentURL :: Maybe Bool
, rssGuidAttrs :: [XML.Attr]
, rssGuidValue :: String
}
deriving (Show)
data RSSImage
= RSSImage
{ rssImageURL :: URLString -- the URL to the image resource.
, rssImageTitle :: String
, rssImageLink :: URLString -- URL that the image resource should be an href to.
, rssImageWidth :: Maybe Integer
, rssImageHeight :: Maybe Integer
, rssImageDesc :: Maybe String
, rssImageOther :: [XML.Element]
}
deriving (Show)
data RSSCloud
= RSSCloud
{ rssCloudDomain :: Maybe String
, rssCloudPort :: Maybe String -- on purpose (i.e., not an int)
, rssCloudPath :: Maybe String
, rssCloudRegister :: Maybe String
, rssCloudProtocol :: Maybe String
, rssCloudAttrs :: [XML.Attr]
}
deriving (Show)
data RSSTextInput
= RSSTextInput
{ rssTextInputTitle :: String
, rssTextInputDesc :: String
, rssTextInputName :: String
, rssTextInputLink :: URLString
, rssTextInputAttrs :: [XML.Attr]
, rssTextInputOther :: [XML.Element]
}
deriving (Show)
-- * Default Constructors:
nullRSS :: String -- ^channel title
-> URLString -- ^channel link
-> RSS
nullRSS title link =
RSS
{ rssVersion = "2.0"
, rssAttrs = []
, rssChannel = nullChannel title link
, rssOther = []
}
nullChannel :: String -- ^rssTitle
-> URLString -- ^rssLink
-> RSSChannel
nullChannel title link =
RSSChannel
{ rssTitle = title
, rssLink = link
, rssDescription = title
, rssItems = []
, rssLanguage = Nothing
, rssCopyright = Nothing
, rssEditor = Nothing
, rssWebMaster = Nothing
, rssPubDate = Nothing
, rssLastUpdate = Nothing
, rssCategories = []
, rssGenerator = Nothing
, rssDocs = Nothing
, rssCloud = Nothing
, rssTTL = Nothing
, rssImage = Nothing
, rssRating = Nothing
, rssTextInput = Nothing
, rssSkipHours = Nothing
, rssSkipDays = Nothing
, rssChannelOther = []
}
nullItem :: String -- ^title
-> RSSItem
nullItem title =
RSSItem
{ rssItemTitle = Just title
, rssItemLink = Nothing
, rssItemDescription = Nothing
, rssItemAuthor = Nothing
, rssItemCategories = []
, rssItemComments = Nothing
, rssItemEnclosure = Nothing
, rssItemGuid = Nothing
, rssItemPubDate = Nothing
, rssItemSource = Nothing
, rssItemAttrs = []
, rssItemOther = []
}
nullSource :: URLString -- ^source URL
-> String -- ^title
-> RSSSource
nullSource url title =
RSSSource
{ rssSourceURL = url
, rssSourceAttrs = []
, rssSourceTitle = title
}
nullEnclosure :: URLString -- ^enclosure URL
-> Integer -- ^enclosure length
-> String -- ^enclosure type
-> RSSEnclosure
nullEnclosure url len ty =
RSSEnclosure
{ rssEnclosureURL = url
, rssEnclosureLength = len
, rssEnclosureType = ty
, rssEnclosureAttrs = []
}
newCategory :: String -- ^category Value
-> RSSCategory
newCategory nm =
RSSCategory
{ rssCategoryDomain = Nothing
, rssCategoryAttrs = []
, rssCategoryValue = nm
}
nullGuid :: String -- ^guid value
-> RSSGuid
nullGuid v =
RSSGuid
{ rssGuidPermanentURL = Nothing
, rssGuidAttrs = []
, rssGuidValue = v
}
nullPermaGuid :: String -- ^guid value
-> RSSGuid
nullPermaGuid v = (nullGuid v){rssGuidPermanentURL=Just True}
nullImage :: URLString -- ^imageURL
-> String -- ^imageTitle
-> URLString -- ^imageLink
-> RSSImage
nullImage url title link =
RSSImage
{ rssImageURL = url
, rssImageTitle = title
, rssImageLink = link
, rssImageWidth = Nothing
, rssImageHeight = Nothing
, rssImageDesc = Nothing
, rssImageOther = []
}
nullCloud :: RSSCloud
nullCloud =
RSSCloud
{ rssCloudDomain = Nothing
, rssCloudPort = Nothing
, rssCloudPath = Nothing
, rssCloudRegister = Nothing
, rssCloudProtocol = Nothing
, rssCloudAttrs = []
}
nullTextInput :: String -- ^inputTitle
-> String -- ^inputName
-> URLString -- ^inputLink
-> RSSTextInput
nullTextInput title nm link =
RSSTextInput
{ rssTextInputTitle = title
, rssTextInputDesc = title
, rssTextInputName = nm
, rssTextInputLink = link
, rssTextInputAttrs = []
, rssTextInputOther = []
}
|
GaloisInc/feed
|
Text/RSS/Syntax.hs
|
bsd-3-clause
| 8,060 | 0 | 10 | 2,621 | 1,550 | 947 | 603 | 223 | 1 |
{-# OPTIONS -fallow-undecidable-instances #-}
import Testsuite
import Data.Array.Parallel.Unlifted
class (Eq a, UA a) => U a
instance (Eq a, UA a) => U a
$(testcases [ "" <@ [t| ( (), Char, Bool, Int ) |]
, "acc" <@ [t| ( (), Int ) |]
, "num" <@ [t| ( Int ) |]
, "ord" <@ [t| ( (), Char, Bool, Int ) |]
, "enum" <@ [t| ( (), Char, Bool, Int ) |]
]
[d|
-- if this doesn't work nothing else will, so run this first
prop_fromSU_toSU :: U a => [[a]] -> Bool
prop_fromSU_toSU xss = fromSU (toSU xss) == xss
prop_concatSU :: U a => SUArr a -> SUArr a -> Bool
prop_concatSU xss yss =
(concatSU xss == concatSU yss)
== (concat (fromSU xss) == concat (fromSU yss))
prop_flattenSU :: U a => SUArr a -> SUArr a -> Bool
prop_flattenSU xss yss =
(xss == yss) == (flattenSU xss == flattenSU yss)
-- missing: (>:)
-- missing: segmentU
prop_replicateSU :: U a => UArr (Int :*: a) -> Bool
prop_replicateSU ps = let (ms :*: xs) = unzipU ps
ns = mapU abs ms
in
fromSU (replicateSU ns xs) == zipWith replicate (fromU ns) (fromU xs)
prop_foldlSU :: (U a, U b) => (a -> b -> a) -> a -> SUArr b -> Bool
prop_foldlSU f z xss =
fromU (foldlSU f z xss) == map (foldl f z) (fromSU xss)
-- missing: foldSU
-- missing: loopSU
prop_andSU :: SUArr Bool -> Bool
prop_andSU bss =
fromU (andSU bss) == map and (fromSU bss)
prop_orSU :: SUArr Bool -> Bool
prop_orSU bss =
fromU (orSU bss) == map or (fromSU bss)
prop_sumSU :: (U num, Num num) => SUArr num -> Bool
prop_sumSU nss =
fromU (sumSU nss) == map sum (fromSU nss)
prop_productSU :: (U num, Num num) => SUArr num -> Bool
prop_productSU nss =
fromU (productSU nss) == map product (fromSU nss)
-- missing: maximumSU
-- missing: minimumSU
-- missing: enumFromToSU
-- missing: enumFromThenToSU
-- missing: fusion rules
|])
|
mainland/dph
|
dph-test/old/UnliftedSU.hs
|
bsd-3-clause
| 2,034 | 0 | 9 | 632 | 127 | 79 | 48 | -1 | -1 |
module PTS.Process
( main
, processFile
) where
import PTS.Process.File
import PTS.Process.Main
|
Toxaris/pts
|
src-lib/PTS/Process.hs
|
bsd-3-clause
| 103 | 0 | 4 | 19 | 26 | 17 | 9 | 5 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RecordWildCards #-}
module Tinc.Nix (
NixCache
, cabal
, nixShell
, resolverFile
, createDerivations
#ifdef TEST
, Function (..)
, defaultDerivation
, shellDerivation
, resolverDerivation
, pkgImport
, parseNixFunction
, disableTests
, extractDependencies
, derivationFile
#endif
) where
import Data.Char
import Data.Maybe
import Data.List
import System.Directory
import System.FilePath
import System.Process.Internals (translate)
import System.Process
import System.IO
import Tinc.Facts
import Tinc.Package
import Tinc.Types
import Tinc.SourceDependency
import Util
type NixExpression = String
type Argument = String
type HaskellDependency = String
type SystemDependency = String
data Function = Function {
_functionArguments :: [Argument]
, _functionBody :: NixExpression
} deriving (Eq, Show)
packageFile :: FilePath
packageFile = "package.nix"
resolverFile :: FilePath
resolverFile = "tinc.nix"
defaultFile :: FilePath
defaultFile = "default.nix"
shellFile :: FilePath
shellFile = "shell.nix"
formatNixResolver :: Facts -> String
formatNixResolver Facts{..} = maybe "haskellPackages" (("haskell.packages." ++) . show) factsNixResolver
cabal :: Facts -> [String] -> (String, [String])
cabal facts args = ("nix-shell", ["-p", "curl", formatNixResolver facts ++ ".ghcWithPackages (p: [ p.cabal-install ])", "--pure", "--run", unwords $ "cabal" : map translate args])
nixShell :: String -> [String] -> (String, [String])
nixShell command args = ("nix-shell", [shellFile, "--run", unwords $ command : map translate args])
createDerivations :: Facts -> [Package] -> IO ()
createDerivations facts@Facts{..} dependencies = do
mapM_ (populateCache factsSourceDependencyCache factsNixCache) dependencies
pkgDerivation <- cabalToNix "."
let knownHaskellDependencies = map packageName dependencies
mapM (readDependencies factsNixCache knownHaskellDependencies) dependencies >>= resolverDerivation facts >>= writeFile resolverFile
writeFile packageFile pkgDerivation
writeFile defaultFile defaultDerivation
writeFile shellFile shellDerivation
populateCache :: Path SourceDependencyCache -> Path NixCache -> Package -> IO ()
populateCache sourceDependencyCache cache pkg = do
_ <- cachedIO (derivationFile cache pkg) $ disableDocumentation . disableTests <$> go
return ()
where
go = case pkg of
Package _ (Version _ Nothing) -> cabalToNix ("cabal://" ++ showPackage pkg)
Package name (Version _ (Just ref)) -> do
let p = path . sourceDependencyPath sourceDependencyCache $ SourceDependency name ref
canonicalizePath p >>= cabalToNix
disable :: String -> NixExpression -> NixExpression
disable s xs = case lines xs of
ys | attribute `elem` ys -> xs
ys -> unlines . (++ [attribute, "}"]) . init $ ys
where
attribute = " " ++ s ++ " = false;"
disableTests :: NixExpression -> NixExpression
disableTests = disable "doCheck"
disableDocumentation :: NixExpression -> NixExpression
disableDocumentation = disable "doHaddock"
cabalToNix :: String -> IO NixExpression
cabalToNix uri = do
hPutStrLn stderr $ "cabal2nix " ++ uri
readProcess "cabal2nix" [uri] ""
defaultDerivation :: NixExpression
defaultDerivation = unlines [
"let"
, " default = { nixpkgs ? import <nixpkgs> {} }:"
, " (import ./" ++ resolverFile ++ " { inherit nixpkgs; }).resolver.callPackage ./" ++ packageFile ++ " {};"
, " overrideFile = ./default-override.nix;"
, " expr = if builtins.pathExists overrideFile then import overrideFile else default;"
, "in expr"
]
shellDerivation :: NixExpression
shellDerivation = unlines [
"{ nixpkgs ? import <nixpkgs> {} }:"
, "(import ./" ++ defaultFile ++ " { inherit nixpkgs; }).env"
]
indent :: Int -> [String] -> [String]
indent n = map f
where
f xs = case xs of
"" -> ""
_ -> replicate n ' ' ++ xs
resolverDerivation :: Facts -> [(Package, [HaskellDependency], [SystemDependency])] -> IO NixExpression
resolverDerivation facts@Facts{..} dependencies = do
overrides <- concat <$> mapM getPkgDerivation dependencies
return . unlines $ [
"{ nixpkgs }:"
, "rec {"
, " compiler = nixpkgs." ++ formatNixResolver facts ++ ";"
, " resolver ="
] ++ indent 4 [
"let"
, " callPackage = compiler.callPackage;"
, ""
, " overrideFunction = self: super: rec {"
] ++ indent 8 overrides ++
indent 4 [
" };"
, ""
, " newResolver = compiler.override {"
, " overrides = overrideFunction;"
, " };"
, ""
, "in newResolver;"
] ++ ["}"]
where
getPkgDerivation packageDeps@(package, _, _) = pkgImport packageDeps <$> readFile (derivationFile factsNixCache package)
pkgImport :: (Package, [HaskellDependency], [SystemDependency]) -> NixExpression -> [String]
pkgImport ((Package name _), haskellDependencies, systemDependencies) derivation = begin : indent 2 definition
where
begin = name ++ " = callPackage"
derivationLines = lines derivation
inlineDerivation = ["("] ++ indent 2 derivationLines ++ [")"]
args = "{ " ++ inheritHaskellDependencies ++ inheritSystemDependencies ++ "};"
definition = inlineDerivation ++ [args]
inheritHaskellDependencies
| null haskellDependencies = ""
| otherwise = "inherit " ++ intercalate " " haskellDependencies ++ "; "
inheritSystemDependencies
| null systemDependencies = ""
| otherwise = "inherit (nixpkgs) " ++ intercalate " " systemDependencies ++ "; "
readDependencies :: Path NixCache -> [HaskellDependency] -> Package -> IO (Package, [HaskellDependency], [SystemDependency])
readDependencies cache knownHaskellDependencies package = do
(\(haskellDeps, systemDeps) -> (package, haskellDeps, systemDeps)) . (`extractDependencies` knownHaskellDependencies) . parseNixFunction <$> readFile (derivationFile cache package)
derivationFile :: Path NixCache -> Package -> FilePath
derivationFile cache package = path cache </> showPackage package ++ rev ++ ".nix"
where
rev = case packageVersion package of
Version _ (Just hash) -> "-" ++ hash
_ -> ""
parseNixFunction :: NixExpression -> Function
parseNixFunction xs = case break (== '}') xs of
(args, body) -> Function (split . filter (not . isSpace). dropWhile (`elem` "{ ") $ args) (dropWhile (`elem` "}: ") body)
where
split :: String -> [Argument]
split = go ""
where
go acc ys = case ys of
',' : zs -> reverse acc : go "" zs
z : zs -> go (z : acc) zs
"" -> [reverse acc]
extractDependencies :: Function -> [HaskellDependency] -> ([HaskellDependency], [SystemDependency])
extractDependencies (Function args body) knownHaskellDependencies =
(haskellDependencies, systemDependencies)
where
haskellDependencies = filter (`notElem` systemDependencies) . filter (`elem` knownHaskellDependencies) $ args
systemDependencies = parseSystemDependencies body
parseSystemDependencies :: NixExpression -> [SystemDependency]
parseSystemDependencies body = concatMap (words . takeWhile (/= ']')) . mapMaybe (stripPrefix "librarySystemDepends = [" . dropWhile isSpace) . lines $ body
|
sol/tinc
|
src/Tinc/Nix.hs
|
mit
| 7,313 | 0 | 17 | 1,460 | 1,997 | 1,066 | 931 | 153 | 3 |
{- path manipulation
-
- Copyright 2010-2014 Joey Hess <[email protected]>
-
- License: BSD-2-clause
-}
{-# LANGUAGE PackageImports, CPP #-}
{-# OPTIONS_GHC -fno-warn-tabs #-}
module Utility.Path where
import Data.String.Utils
import System.FilePath
import System.Directory
import Data.List
import Data.Maybe
import Data.Char
import Control.Applicative
import Prelude
#ifdef mingw32_HOST_OS
import qualified System.FilePath.Posix as Posix
#else
import System.Posix.Files
import Utility.Exception
#endif
import qualified "MissingH" System.Path as MissingH
import Utility.Monad
import Utility.UserInfo
{- Simplifies a path, removing any ".." or ".", and removing the trailing
- path separator.
-
- On Windows, preserves whichever style of path separator might be used in
- the input FilePaths. This is done because some programs in Windows
- demand a particular path separator -- and which one actually varies!
-
- This does not guarantee that two paths that refer to the same location,
- and are both relative to the same location (or both absolute) will
- yeild the same result. Run both through normalise from System.FilePath
- to ensure that.
-}
simplifyPath :: FilePath -> FilePath
simplifyPath path = dropTrailingPathSeparator $
joinDrive drive $ joinPath $ norm [] $ splitPath path'
where
(drive, path') = splitDrive path
norm c [] = reverse c
norm c (p:ps)
| p' == ".." = norm (drop 1 c) ps
| p' == "." = norm c ps
| otherwise = norm (p:c) ps
where
p' = dropTrailingPathSeparator p
{- Makes a path absolute.
-
- The first parameter is a base directory (ie, the cwd) to use if the path
- is not already absolute.
-
- Does not attempt to deal with edge cases or ensure security with
- untrusted inputs.
-}
absPathFrom :: FilePath -> FilePath -> FilePath
absPathFrom dir path = simplifyPath (combine dir path)
{- On Windows, this converts the paths to unix-style, in order to run
- MissingH's absNormPath on them. -}
absNormPathUnix :: FilePath -> FilePath -> Maybe FilePath
#ifndef mingw32_HOST_OS
absNormPathUnix dir path = MissingH.absNormPath dir path
#else
absNormPathUnix dir path = todos <$> MissingH.absNormPath (fromdos dir) (fromdos path)
where
fromdos = replace "\\" "/"
todos = replace "/" "\\"
#endif
{- takeDirectory "foo/bar/" is "foo/bar". This instead yields "foo" -}
parentDir :: FilePath -> FilePath
parentDir = takeDirectory . dropTrailingPathSeparator
{- Just the parent directory of a path, or Nothing if the path has no
- parent (ie for "/" or ".") -}
upFrom :: FilePath -> Maybe FilePath
upFrom dir
| length dirs < 2 = Nothing
| otherwise = Just $ joinDrive drive (join s $ init dirs)
where
-- on Unix, the drive will be "/" when the dir is absolute, otherwise ""
(drive, path) = splitDrive dir
dirs = filter (not . null) $ split s path
s = [pathSeparator]
prop_upFrom_basics :: FilePath -> Bool
prop_upFrom_basics dir
| null dir = True
| dir == "/" = p == Nothing
| otherwise = p /= Just dir
where
p = upFrom dir
{- Checks if the first FilePath is, or could be said to contain the second.
- For example, "foo/" contains "foo/bar". Also, "foo", "./foo", "foo/" etc
- are all equivilant.
-}
dirContains :: FilePath -> FilePath -> Bool
dirContains a b = a == b || a' == b' || (addTrailingPathSeparator a') `isPrefixOf` b'
where
a' = norm a
b' = norm b
norm = normalise . simplifyPath
{- Converts a filename into an absolute path.
-
- Unlike Directory.canonicalizePath, this does not require the path
- already exists. -}
absPath :: FilePath -> IO FilePath
absPath file = do
cwd <- getCurrentDirectory
return $ absPathFrom cwd file
{- Constructs a relative path from the CWD to a file.
-
- For example, assuming CWD is /tmp/foo/bar:
- relPathCwdToFile "/tmp/foo" == ".."
- relPathCwdToFile "/tmp/foo/bar" == ""
-}
relPathCwdToFile :: FilePath -> IO FilePath
relPathCwdToFile f = do
c <- getCurrentDirectory
relPathDirToFile c f
{- Constructs a relative path from a directory to a file. -}
relPathDirToFile :: FilePath -> FilePath -> IO FilePath
relPathDirToFile from to = relPathDirToFileAbs <$> absPath from <*> absPath to
{- This requires the first path to be absolute, and the
- second path cannot contain ../ or ./
-
- On Windows, if the paths are on different drives,
- a relative path is not possible and the path is simply
- returned as-is.
-}
relPathDirToFileAbs :: FilePath -> FilePath -> FilePath
relPathDirToFileAbs from to
| takeDrive from /= takeDrive to = to
| otherwise = join s $ dotdots ++ uncommon
where
s = [pathSeparator]
pfrom = split s from
pto = split s to
common = map fst $ takeWhile same $ zip pfrom pto
same (c,d) = c == d
uncommon = drop numcommon pto
dotdots = replicate (length pfrom - numcommon) ".."
numcommon = length common
prop_relPathDirToFile_basics :: FilePath -> FilePath -> Bool
prop_relPathDirToFile_basics from to
| null from || null to = True
| from == to = null r
| otherwise = not (null r)
where
r = relPathDirToFileAbs from to
prop_relPathDirToFile_regressionTest :: Bool
prop_relPathDirToFile_regressionTest = same_dir_shortcurcuits_at_difference
where
{- Two paths have the same directory component at the same
- location, but it's not really the same directory.
- Code used to get this wrong. -}
same_dir_shortcurcuits_at_difference =
relPathDirToFileAbs (joinPath [pathSeparator : "tmp", "r", "lll", "xxx", "yyy", "18"])
(joinPath [pathSeparator : "tmp", "r", ".git", "annex", "objects", "18", "gk", "SHA256-foo", "SHA256-foo"])
== joinPath ["..", "..", "..", "..", ".git", "annex", "objects", "18", "gk", "SHA256-foo", "SHA256-foo"]
{- Given an original list of paths, and an expanded list derived from it,
- which may be arbitrarily reordered, generates a list of lists, where
- each sublist corresponds to one of the original paths.
-
- When the original path is a directory, any items in the expanded list
- that are contained in that directory will appear in its segment.
-
- The order of the original list of paths is attempted to be preserved in
- the order of the returned segments. However, doing so has a O^NM
- growth factor. So, if the original list has more than 100 paths on it,
- we stop preserving ordering at that point. Presumably a user passing
- that many paths in doesn't care too much about order of the later ones.
-}
segmentPaths :: [FilePath] -> [FilePath] -> [[FilePath]]
segmentPaths [] new = [new]
segmentPaths [_] new = [new] -- optimisation
segmentPaths (l:ls) new = found : segmentPaths ls rest
where
(found, rest) = if length ls < 100
then partition (l `dirContains`) new
else break (\p -> not (l `dirContains` p)) new
{- This assumes that it's cheaper to call segmentPaths on the result,
- than it would be to run the action separately with each path. In
- the case of git file list commands, that assumption tends to hold.
-}
runSegmentPaths :: ([FilePath] -> IO [FilePath]) -> [FilePath] -> IO [[FilePath]]
runSegmentPaths a paths = segmentPaths paths <$> a paths
{- Converts paths in the home directory to use ~/ -}
relHome :: FilePath -> IO String
relHome path = do
home <- myHomeDir
return $ if dirContains home path
then "~/" ++ relPathDirToFileAbs home path
else path
{- Checks if a command is available in PATH.
-
- The command may be fully-qualified, in which case, this succeeds as
- long as it exists. -}
inPath :: String -> IO Bool
inPath command = isJust <$> searchPath command
{- Finds a command in PATH and returns the full path to it.
-
- The command may be fully qualified already, in which case it will
- be returned if it exists.
-}
searchPath :: String -> IO (Maybe FilePath)
searchPath command
| isAbsolute command = check command
| otherwise = getSearchPath >>= getM indir
where
indir d = check $ d </> command
check f = firstM doesFileExist
#ifdef mingw32_HOST_OS
[f, f ++ ".exe"]
#else
[f]
#endif
{- Checks if a filename is a unix dotfile. All files inside dotdirs
- count as dotfiles. -}
dotfile :: FilePath -> Bool
dotfile file
| f == "." = False
| f == ".." = False
| f == "" = False
| otherwise = "." `isPrefixOf` f || dotfile (takeDirectory file)
where
f = takeFileName file
{- Converts a DOS style path to a Cygwin style path. Only on Windows.
- Any trailing '\' is preserved as a trailing '/' -}
toCygPath :: FilePath -> FilePath
#ifndef mingw32_HOST_OS
toCygPath = id
#else
toCygPath p
| null drive = recombine parts
| otherwise = recombine $ "/cygdrive" : driveletter drive : parts
where
(drive, p') = splitDrive p
parts = splitDirectories p'
driveletter = map toLower . takeWhile (/= ':')
recombine = fixtrailing . Posix.joinPath
fixtrailing s
| hasTrailingPathSeparator p = Posix.addTrailingPathSeparator s
| otherwise = s
#endif
{- Maximum size to use for a file in a specified directory.
-
- Many systems have a 255 byte limit to the name of a file,
- so that's taken as the max if the system has a larger limit, or has no
- limit.
-}
fileNameLengthLimit :: FilePath -> IO Int
#ifdef mingw32_HOST_OS
fileNameLengthLimit _ = return 255
#else
fileNameLengthLimit dir = do
-- getPathVar can fail due to statfs(2) overflow
l <- catchDefaultIO 0 $
fromIntegral <$> getPathVar dir FileNameLimit
if l <= 0
then return 255
else return $ minimum [l, 255]
where
#endif
{- Given a string that we'd like to use as the basis for FilePath, but that
- was provided by a third party and is not to be trusted, returns the closest
- sane FilePath.
-
- All spaces and punctuation and other wacky stuff are replaced
- with '_', except for '.'
- "../" will thus turn into ".._", which is safe.
-}
sanitizeFilePath :: String -> FilePath
sanitizeFilePath = map sanitize
where
sanitize c
| c == '.' = c
| isSpace c || isPunctuation c || isSymbol c || isControl c || c == '/' = '_'
| otherwise = c
{- Similar to splitExtensions, but knows that some things in FilePaths
- after a dot are too long to be extensions. -}
splitShortExtensions :: FilePath -> (FilePath, [String])
splitShortExtensions = splitShortExtensions' 5 -- enough for ".jpeg"
splitShortExtensions' :: Int -> FilePath -> (FilePath, [String])
splitShortExtensions' maxextension = go []
where
go c f
| len > 0 && len <= maxextension && not (null base) =
go (ext:c) base
| otherwise = (f, c)
where
(base, ext) = splitExtension f
len = length ext
|
sjfloat/propellor
|
src/Utility/Path.hs
|
bsd-2-clause
| 10,401 | 18 | 15 | 2,015 | 1,895 | 984 | 911 | 140 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Tests.Readers.Org (tests) where
import Text.Pandoc.Definition
import Test.Framework
import Tests.Helpers
import Text.Pandoc.Builder
import Text.Pandoc
import Data.List (intersperse)
import Data.Monoid (mempty, mappend, mconcat)
import Text.Pandoc.Error
org :: String -> Pandoc
org = handleError . readOrg def
orgSmart :: String -> Pandoc
orgSmart = handleError . readOrg def { readerSmart = True }
infix 4 =:
(=:) :: ToString c
=> String -> (String, c) -> Test
(=:) = test org
spcSep :: [Inlines] -> Inlines
spcSep = mconcat . intersperse space
simpleTable' :: Int
-> [Blocks]
-> [[Blocks]]
-> Blocks
simpleTable' n = table "" (take n $ repeat (AlignDefault, 0.0))
tests :: [Test]
tests =
[ testGroup "Inlines" $
[ "Plain String" =:
"Hello, World" =?>
para (spcSep [ "Hello,", "World" ])
, "Emphasis" =:
"/Planet Punk/" =?>
para (emph . spcSep $ ["Planet", "Punk"])
, "Strong" =:
"*Cider*" =?>
para (strong "Cider")
, "Strong Emphasis" =:
"/*strength*/" =?>
para (emph . strong $ "strength")
, "Strikeout" =:
"+Kill Bill+" =?>
para (strikeout . spcSep $ [ "Kill", "Bill" ])
, "Verbatim" =:
"=Robot.rock()=" =?>
para (code "Robot.rock()")
, "Code" =:
"~word for word~" =?>
para (code "word for word")
, "Math $..$" =:
"$E=mc^2$" =?>
para (math "E=mc^2")
, "Math $$..$$" =:
"$$E=mc^2$$" =?>
para (displayMath "E=mc^2")
, "Math \\[..\\]" =:
"\\[E=ℎν\\]" =?>
para (displayMath "E=ℎν")
, "Math \\(..\\)" =:
"\\(σ_x σ_p ≥ \\frac{ℏ}{2}\\)" =?>
para (math "σ_x σ_p ≥ \\frac{ℏ}{2}")
, "Symbol" =:
"A * symbol" =?>
para (str "A" <> space <> str "*" <> space <> "symbol")
, "Superscript simple expression" =:
"2^-λ" =?>
para (str "2" <> superscript "-λ")
, "Superscript multi char" =:
"2^{n-1}" =?>
para (str "2" <> superscript "n-1")
, "Subscript simple expression" =:
"a_n" =?>
para (str "a" <> subscript "n")
, "Subscript multi char" =:
"a_{n+1}" =?>
para (str "a" <> subscript "n+1")
, "Linebreak" =:
"line \\\\ \nbreak" =?>
para ("line" <> linebreak <> "break")
, "Inline note" =:
"[fn::Schreib mir eine E-Mail]" =?>
para (note $ para "Schreib mir eine E-Mail")
, "Markup-chars not occuring on word break are symbols" =:
unlines [ "this+that+ +so+on"
, "seven*eight* nine*"
, "+not+funny+"
] =?>
para (spcSep [ "this+that+", "+so+on"
, "seven*eight*", "nine*"
, strikeout "not+funny"
])
, "No empty markup" =:
"// ** __ ++ == ~~ $$" =?>
para (spcSep [ "//", "**", "__", "++", "==", "~~", "$$" ])
, "Adherence to Org's rules for markup borders" =:
"/t/& a/ / ./r/ (*l*) /e/! /b/." =?>
para (spcSep [ emph $ "t/&" <> space <> "a"
, "/"
, "./r/"
, "(" <> (strong "l") <> ")"
, (emph "e") <> "!"
, (emph "b") <> "."
])
, "Quotes are forbidden border chars" =:
"/'nope/ *nope\"*" =?>
para ("/'nope/" <> space <> "*nope\"*")
, "Commata are forbidden border chars" =:
"/nada,/" =?>
para "/nada,/"
, "Markup should work properly after a blank line" =:
unlines ["foo", "", "/bar/"] =?>
(para $ text "foo") <> (para $ emph $ text "bar")
, "Inline math must stay within three lines" =:
unlines [ "$a", "b", "c$", "$d", "e", "f", "g$" ] =?>
para ((math "a\nb\nc") <> space <>
spcSep [ "$d", "e", "f", "g$" ])
, "Single-character math" =:
"$a$ $b$! $c$?" =?>
para (spcSep [ math "a"
, "$b$!"
, (math "c") <> "?"
])
, "Markup may not span more than two lines" =:
unlines [ "/this *is +totally", "nice+ not*", "emph/" ] =?>
para (spcSep [ "/this"
, (strong (spcSep
[ "is"
, (strikeout ("totally" <> space <> "nice"))
, "not"
]))
, "emph/" ])
, "Sub- and superscript expressions" =:
unlines [ "a_(a(b)(c)d)"
, "e^(f(g)h)"
, "i_(jk)l)"
, "m^()n"
, "o_{p{q{}r}}"
, "s^{t{u}v}"
, "w_{xy}z}"
, "1^{}2"
, "3_{{}}"
, "4^(a(*b(c*)d))"
] =?>
para (spcSep [ "a" <> subscript "(a(b)(c)d)"
, "e" <> superscript "(f(g)h)"
, "i" <> (subscript "(jk)") <> "l)"
, "m" <> (superscript "()") <> "n"
, "o" <> subscript "p{q{}r}"
, "s" <> superscript "t{u}v"
, "w" <> (subscript "xy") <> "z}"
, "1" <> (superscript "") <> "2"
, "3" <> subscript "{}"
, "4" <> superscript ("(a(" <> strong "b(c" <> ")d))")
])
, "Image" =:
"[[./sunset.jpg]]" =?>
(para $ image "./sunset.jpg" "" "")
, "Explicit link" =:
"[[http://zeitlens.com/][pseudo-random /nonsense/]]" =?>
(para $ link "http://zeitlens.com/" ""
("pseudo-random" <> space <> emph "nonsense"))
, "Self-link" =:
"[[http://zeitlens.com/]]" =?>
(para $ link "http://zeitlens.com/" "" "http://zeitlens.com/")
, "Absolute file link" =:
"[[/url][hi]]" =?>
(para $ link "file:///url" "" "hi")
, "Link to file in parent directory" =:
"[[../file.txt][moin]]" =?>
(para $ link "../file.txt" "" "moin")
, "Empty link (for gitit interop)" =:
"[[][New Link]]" =?>
(para $ link "" "" "New Link")
, "Image link" =:
"[[sunset.png][dusk.svg]]" =?>
(para $ link "sunset.png" "" (image "dusk.svg" "" ""))
, "Image link with non-image target" =:
"[[http://example.com][logo.png]]" =?>
(para $ link "http://example.com" "" (image "logo.png" "" ""))
, "Plain link" =:
"Posts on http://zeitlens.com/ can be funny at times." =?>
(para $ spcSep [ "Posts", "on"
, link "http://zeitlens.com/" "" "http://zeitlens.com/"
, "can", "be", "funny", "at", "times."
])
, "Angle link" =:
"Look at <http://moltkeplatz.de> for fnords." =?>
(para $ spcSep [ "Look", "at"
, link "http://moltkeplatz.de" "" "http://moltkeplatz.de"
, "for", "fnords."
])
, "Absolute file link" =:
"[[file:///etc/passwd][passwd]]" =?>
(para $ link "file:///etc/passwd" "" "passwd")
, "File link" =:
"[[file:target][title]]" =?>
(para $ link "target" "" "title")
, "Anchor" =:
"<<anchor>> Link here later." =?>
(para $ spanWith ("anchor", [], []) mempty <>
"Link" <> space <> "here" <> space <> "later.")
, "Inline code block" =:
"src_emacs-lisp{(message \"Hello\")}" =?>
(para $ codeWith ( ""
, [ "commonlisp", "rundoc-block" ]
, [ ("rundoc-language", "emacs-lisp") ])
"(message \"Hello\")")
, "Inline code block with arguments" =:
"src_sh[:export both :results output]{echo 'Hello, World'}" =?>
(para $ codeWith ( ""
, [ "bash", "rundoc-block" ]
, [ ("rundoc-language", "sh")
, ("rundoc-export", "both")
, ("rundoc-results", "output")
]
)
"echo 'Hello, World'")
, "Citation" =:
"[@nonexistent]" =?>
let citation = Citation
{ citationId = "nonexistent"
, citationPrefix = []
, citationSuffix = []
, citationMode = NormalCitation
, citationNoteNum = 0
, citationHash = 0}
in (para $ cite [citation] "[@nonexistent]")
, "Citation containing text" =:
"[see @item1 p. 34-35]" =?>
let citation = Citation
{ citationId = "item1"
, citationPrefix = [Str "see"]
, citationSuffix = [Space ,Str "p.",Space,Str "34-35"]
, citationMode = NormalCitation
, citationNoteNum = 0
, citationHash = 0}
in (para $ cite [citation] "[see @item1 p. 34-35]")
, "Inline LaTeX symbol" =:
"\\dots" =?>
para "…"
, "Inline LaTeX command" =:
"\\textit{Emphasised}" =?>
para (emph "Emphasised")
, "Inline LaTeX math symbol" =:
"\\tau" =?>
para (emph "τ")
, "Unknown inline LaTeX command" =:
"\\notacommand{foo}" =?>
para (rawInline "latex" "\\notacommand{foo}")
, "MathML symbol in LaTeX-style" =:
"There is a hackerspace in Lübeck, Germany, called nbsp (unicode symbol: '\\nbsp')." =?>
para ("There is a hackerspace in Lübeck, Germany, called nbsp (unicode symbol: ' ').")
, "MathML symbol in LaTeX-style, including braces" =:
"\\Aacute{}stor" =?>
para "Ástor"
, "MathML copy sign" =:
"\\copy" =?>
para "©"
, "LaTeX citation" =:
"\\cite{Coffee}" =?>
let citation = Citation
{ citationId = "Coffee"
, citationPrefix = []
, citationSuffix = []
, citationMode = AuthorInText
, citationNoteNum = 0
, citationHash = 0}
in (para . cite [citation] $ rawInline "latex" "\\cite{Coffee}")
]
, testGroup "Meta Information" $
[ "Comment" =:
"# Nothing to see here" =?>
(mempty::Blocks)
, "Not a comment" =:
"#-tag" =?>
para "#-tag"
, "Comment surrounded by Text" =:
unlines [ "Before"
, "# Comment"
, "After"
] =?>
mconcat [ para "Before"
, para "After"
]
, "Title" =:
"#+TITLE: Hello, World" =?>
let titleInline = toList $ "Hello," <> space <> "World"
meta = setMeta "title" (MetaInlines titleInline) $ nullMeta
in Pandoc meta mempty
, "Author" =:
"#+author: Albert /Emacs-Fanboy/ Krewinkel" =?>
let author = toList . spcSep $ [ "Albert", emph "Emacs-Fanboy", "Krewinkel" ]
meta = setMeta "author" (MetaInlines author) $ nullMeta
in Pandoc meta mempty
, "Date" =:
"#+Date: Feb. *28*, 2014" =?>
let date = toList . spcSep $ [ "Feb.", (strong "28") <> ",", "2014" ]
meta = setMeta "date" (MetaInlines date) $ nullMeta
in Pandoc meta mempty
, "Description" =:
"#+DESCRIPTION: Explanatory text" =?>
let description = toList . spcSep $ [ "Explanatory", "text" ]
meta = setMeta "description" (MetaInlines description) $ nullMeta
in Pandoc meta mempty
, "Properties drawer" =:
unlines [ " :PROPERTIES:"
, " :setting: foo"
, " :END:"
] =?>
(mempty::Blocks)
, "Logbook drawer" =:
unlines [ " :LogBook:"
, " - State \"DONE\" from \"TODO\" [2014-03-03 Mon 11:00]"
, " :END:"
] =?>
(mempty::Blocks)
, "Drawer surrounded by text" =:
unlines [ "Before"
, ":PROPERTIES:"
, ":END:"
, "After"
] =?>
para "Before" <> para "After"
, "Drawer start is the only text in first line of a drawer" =:
unlines [ " :LOGBOOK: foo"
, " :END:"
] =?>
para (spcSep [ ":LOGBOOK:", "foo", ":END:" ])
, "Drawers with unknown names are just text" =:
unlines [ ":FOO:"
, ":END:"
] =?>
para (":FOO:" <> space <> ":END:")
, "Anchor reference" =:
unlines [ "<<link-here>> Target."
, ""
, "[[link-here][See here!]]"
] =?>
(para (spanWith ("link-here", [], []) mempty <> "Target.") <>
para (link "#link-here" "" ("See" <> space <> "here!")))
, "Search links are read as emph" =:
"[[Wally][Where's Wally?]]" =?>
(para (emph $ "Where's" <> space <> "Wally?"))
, "Link to nonexistent anchor" =:
unlines [ "<<link-here>> Target."
, ""
, "[[link$here][See here!]]"
] =?>
(para (spanWith ("link-here", [], []) mempty <> "Target.") <>
para (emph ("See" <> space <> "here!")))
, "Link abbreviation" =:
unlines [ "#+LINK: wp https://en.wikipedia.org/wiki/%s"
, "[[wp:Org_mode][Wikipedia on Org-mode]]"
] =?>
(para (link "https://en.wikipedia.org/wiki/Org_mode" ""
("Wikipedia" <> space <> "on" <> space <> "Org-mode")))
, "Link abbreviation, defined after first use" =:
unlines [ "[[zl:non-sense][Non-sense articles]]"
, "#+LINK: zl http://zeitlens.com/tags/%s.html"
] =?>
(para (link "http://zeitlens.com/tags/non-sense.html" ""
("Non-sense" <> space <> "articles")))
, "Link abbreviation, URL encoded arguments" =:
unlines [ "#+link: expl http://example.com/%h/foo"
, "[[expl:Hello, World!][Moin!]]"
] =?>
(para (link "http://example.com/Hello%2C%20World%21/foo" "" "Moin!"))
, "Link abbreviation, append arguments" =:
unlines [ "#+link: expl http://example.com/"
, "[[expl:foo][bar]]"
] =?>
(para (link "http://example.com/foo" "" "bar"))
]
, testGroup "Basic Blocks" $
[ "Paragraph" =:
"Paragraph\n" =?>
para "Paragraph"
, "First Level Header" =:
"* Headline\n" =?>
headerWith ("headline", [], []) 1 "Headline"
, "Third Level Header" =:
"*** Third Level Headline\n" =?>
headerWith ("third-level-headline", [], [])
3
("Third" <> space <> "Level" <> space <> "Headline")
, "Compact Headers with Paragraph" =:
unlines [ "* First Level"
, "** Second Level"
, " Text"
] =?>
mconcat [ headerWith ("first-level", [], [])
1
("First" <> space <> "Level")
, headerWith ("second-level", [], [])
2
("Second" <> space <> "Level")
, para "Text"
]
, "Separated Headers with Paragraph" =:
unlines [ "* First Level"
, ""
, "** Second Level"
, ""
, " Text"
] =?>
mconcat [ headerWith ("first-level", [], [])
1
("First" <> space <> "Level")
, headerWith ("second-level", [], [])
2
("Second" <> space <> "Level")
, para "Text"
]
, "Headers not preceded by a blank line" =:
unlines [ "** eat dinner"
, "Spaghetti and meatballs tonight."
, "** walk dog"
] =?>
mconcat [ headerWith ("eat-dinner", [], [])
2
("eat" <> space <> "dinner")
, para $ spcSep [ "Spaghetti", "and", "meatballs", "tonight." ]
, headerWith ("walk-dog", [], [])
2
("walk" <> space <> "dog")
]
, "Tagged headers" =:
unlines [ "* Personal :PERSONAL:"
, "** Call Mom :@PHONE:"
, "** Call John :@PHONE:JOHN: "
] =?>
let tagSpan t = spanWith ("", ["tag"], [("data-tag-name", t)]) mempty
in mconcat [ headerWith ("personal", [], [])
1
("Personal" <> tagSpan "PERSONAL")
, headerWith ("call-mom", [], [])
2
("Call Mom" <> tagSpan "@PHONE")
, headerWith ("call-john", [], [])
2
("Call John" <> tagSpan "@PHONE" <> tagSpan "JOHN")
]
, "Untagged header containing colons" =:
"* This: is not: tagged" =?>
headerWith ("this-is-not-tagged", [], []) 1 "This: is not: tagged"
, "Comment Trees" =:
unlines [ "* COMMENT A comment tree"
, " Not much going on here"
, "** This will be dropped"
, "* Comment tree above"
] =?>
headerWith ("comment-tree-above", [], []) 1 "Comment tree above"
, "Nothing but a COMMENT header" =:
"* COMMENT Test" =?>
(mempty::Blocks)
, "Tree with :noexport:" =:
unlines [ "* Should be ignored :archive:noexport:old:"
, "** Old stuff"
, " This is not going to be exported"
] =?>
(mempty::Blocks)
, "Paragraph starting with an asterisk" =:
"*five" =?>
para "*five"
, "Paragraph containing asterisk at beginning of line" =:
unlines [ "lucky"
, "*star"
] =?>
para ("lucky" <> space <> "*star")
, "Example block" =:
unlines [ ": echo hello"
, ": echo dear tester"
] =?>
codeBlockWith ("", ["example"], []) "echo hello\necho dear tester\n"
, "Example block surrounded by text" =:
unlines [ "Greetings"
, ": echo hello"
, ": echo dear tester"
, "Bye"
] =?>
mconcat [ para "Greetings"
, codeBlockWith ("", ["example"], [])
"echo hello\necho dear tester\n"
, para "Bye"
]
, "Horizontal Rule" =:
unlines [ "before"
, "-----"
, "after"
] =?>
mconcat [ para "before"
, horizontalRule
, para "after"
]
, "Not a Horizontal Rule" =:
"----- five dashes" =?>
(para $ spcSep [ "-----", "five", "dashes" ])
, "Comment Block" =:
unlines [ "#+BEGIN_COMMENT"
, "stuff"
, "bla"
, "#+END_COMMENT"] =?>
(mempty::Blocks)
, "Figure" =:
unlines [ "#+caption: A very courageous man."
, "#+name: goodguy"
, "[[edward.jpg]]"
] =?>
para (image "edward.jpg" "fig:goodguy" "A very courageous man.")
, "Unnamed figure" =:
unlines [ "#+caption: A great whistleblower."
, "[[snowden.png]]"
] =?>
para (image "snowden.png" "" "A great whistleblower.")
, "Figure with `fig:` prefix in name" =:
unlines [ "#+caption: Used as a metapher in evolutionary biology."
, "#+name: fig:redqueen"
, "[[the-red-queen.jpg]]"
] =?>
para (image "the-red-queen.jpg" "fig:redqueen"
"Used as a metapher in evolutionary biology.")
, "Footnote" =:
unlines [ "A footnote[1]"
, ""
, "[1] First paragraph"
, ""
, "second paragraph"
] =?>
para (mconcat
[ "A", space, "footnote"
, note $ mconcat [ para ("First" <> space <> "paragraph")
, para ("second" <> space <> "paragraph")
]
])
, "Two footnotes" =:
unlines [ "Footnotes[fn:1][fn:2]"
, ""
, "[fn:1] First note."
, ""
, "[fn:2] Second note."
] =?>
para (mconcat
[ "Footnotes"
, note $ para ("First" <> space <> "note.")
, note $ para ("Second" <> space <> "note.")
])
, "Footnote followed by header" =:
unlines [ "Another note[fn:yay]"
, ""
, "[fn:yay] This is great!"
, ""
, "** Headline"
] =?>
mconcat
[ para (mconcat
[ "Another", space, "note"
, note $ para ("This" <> space <> "is" <> space <> "great!")
])
, headerWith ("headline", [], []) 2 "Headline"
]
]
, testGroup "Lists" $
[ "Simple Bullet Lists" =:
("- Item1\n" ++
"- Item2\n") =?>
bulletList [ plain "Item1"
, plain "Item2"
]
, "Indented Bullet Lists" =:
(" - Item1\n" ++
" - Item2\n") =?>
bulletList [ plain "Item1"
, plain "Item2"
]
, "Unindented *" =:
("- Item1\n" ++
"* Item2\n") =?>
bulletList [ plain "Item1"
] <>
headerWith ("item2", [], []) 1 "Item2"
, "Multi-line Bullet Lists" =:
("- *Fat\n" ++
" Tony*\n" ++
"- /Sideshow\n" ++
" Bob/") =?>
bulletList [ plain $ strong ("Fat" <> space <> "Tony")
, plain $ emph ("Sideshow" <> space <> "Bob")
]
, "Nested Bullet Lists" =:
("- Discovery\n" ++
" + One More Time\n" ++
" + Harder, Better, Faster, Stronger\n" ++
"- Homework\n" ++
" + Around the World\n"++
"- Human After All\n" ++
" + Technologic\n" ++
" + Robot Rock\n") =?>
bulletList [ mconcat
[ plain "Discovery"
, bulletList [ plain ("One" <> space <>
"More" <> space <>
"Time")
, plain ("Harder," <> space <>
"Better," <> space <>
"Faster," <> space <>
"Stronger")
]
]
, mconcat
[ plain "Homework"
, bulletList [ plain ("Around" <> space <>
"the" <> space <>
"World")
]
]
, mconcat
[ plain ("Human" <> space <> "After" <> space <> "All")
, bulletList [ plain "Technologic"
, plain ("Robot" <> space <> "Rock")
]
]
]
, "Bullet List with Decreasing Indent" =:
(" - Discovery\n\
\ - Human After All\n") =?>
mconcat [ bulletList [ plain "Discovery" ]
, bulletList [ plain ("Human" <> space <> "After" <> space <> "All")]
]
, "Header follows Bullet List" =:
(" - Discovery\n\
\ - Human After All\n\
\* Homework") =?>
mconcat [ bulletList [ plain "Discovery"
, plain ("Human" <> space <> "After" <> space <> "All")
]
, headerWith ("homework", [], []) 1 "Homework"
]
, "Bullet List Unindented with trailing Header" =:
("- Discovery\n\
\- Homework\n\
\* NotValidListItem") =?>
mconcat [ bulletList [ plain "Discovery"
, plain "Homework"
]
, headerWith ("notvalidlistitem", [], []) 1 "NotValidListItem"
]
, "Simple Ordered List" =:
("1. Item1\n" ++
"2. Item2\n") =?>
let listStyle = (1, DefaultStyle, DefaultDelim)
listStructure = [ plain "Item1"
, plain "Item2"
]
in orderedListWith listStyle listStructure
, "Simple Ordered List with Parens" =:
("1) Item1\n" ++
"2) Item2\n") =?>
let listStyle = (1, DefaultStyle, DefaultDelim)
listStructure = [ plain "Item1"
, plain "Item2"
]
in orderedListWith listStyle listStructure
, "Indented Ordered List" =:
(" 1. Item1\n" ++
" 2. Item2\n") =?>
let listStyle = (1, DefaultStyle, DefaultDelim)
listStructure = [ plain "Item1"
, plain "Item2"
]
in orderedListWith listStyle listStructure
, "Nested Ordered Lists" =:
("1. One\n" ++
" 1. One-One\n" ++
" 2. One-Two\n" ++
"2. Two\n" ++
" 1. Two-One\n"++
" 2. Two-Two\n") =?>
let listStyle = (1, DefaultStyle, DefaultDelim)
listStructure = [ mconcat
[ plain "One"
, orderedList [ plain "One-One"
, plain "One-Two"
]
]
, mconcat
[ plain "Two"
, orderedList [ plain "Two-One"
, plain "Two-Two"
]
]
]
in orderedListWith listStyle listStructure
, "Ordered List in Bullet List" =:
("- Emacs\n" ++
" 1. Org\n") =?>
bulletList [ (plain "Emacs") <>
(orderedList [ plain "Org"])
]
, "Bullet List in Ordered List" =:
("1. GNU\n" ++
" - Freedom\n") =?>
orderedList [ (plain "GNU") <> bulletList [ (plain "Freedom") ] ]
, "Definition List" =:
unlines [ "- PLL :: phase-locked loop"
, "- TTL ::"
, " transistor-transistor logic"
, "- PSK::phase-shift keying"
, ""
, " a digital modulation scheme"
] =?>
definitionList [ ("PLL", [ plain $ "phase-locked" <> space <> "loop" ])
, ("TTL", [ plain $ "transistor-transistor" <> space <>
"logic" ])
, ("PSK", [ mconcat
[ para $ "phase-shift" <> space <> "keying"
, para $ spcSep [ "a", "digital"
, "modulation", "scheme" ]
]
])
]
, "Definition list with multi-word term" =:
" - Elijah Wood :: He plays Frodo" =?>
definitionList [ ("Elijah" <> space <> "Wood", [plain $ "He" <> space <> "plays" <> space <> "Frodo"])]
, "Compact definition list" =:
unlines [ "- ATP :: adenosine 5' triphosphate"
, "- DNA :: deoxyribonucleic acid"
, "- PCR :: polymerase chain reaction"
, ""
] =?>
definitionList
[ ("ATP", [ plain $ spcSep [ "adenosine", "5'", "triphosphate" ] ])
, ("DNA", [ plain $ spcSep [ "deoxyribonucleic", "acid" ] ])
, ("PCR", [ plain $ spcSep [ "polymerase", "chain", "reaction" ] ])
]
, "Definition List With Trailing Header" =:
"- definition :: list\n\
\- cool :: defs\n\
\* header" =?>
mconcat [ definitionList [ ("definition", [plain "list"])
, ("cool", [plain "defs"])
]
, headerWith ("header", [], []) 1 "header"
]
, "Loose bullet list" =:
unlines [ "- apple"
, ""
, "- orange"
, ""
, "- peach"
] =?>
bulletList [ para "apple"
, para "orange"
, para "peach"
]
]
, testGroup "Tables"
[ "Single cell table" =:
"|Test|" =?>
simpleTable' 1 mempty [[plain "Test"]]
, "Multi cell table" =:
"| One | Two |" =?>
simpleTable' 2 mempty [ [ plain "One", plain "Two" ] ]
, "Multi line table" =:
unlines [ "| One |"
, "| Two |"
, "| Three |"
] =?>
simpleTable' 1 mempty
[ [ plain "One" ]
, [ plain "Two" ]
, [ plain "Three" ]
]
, "Empty table" =:
"||" =?>
simpleTable' 1 mempty mempty
, "Glider Table" =:
unlines [ "| 1 | 0 | 0 |"
, "| 0 | 1 | 1 |"
, "| 1 | 1 | 0 |"
] =?>
simpleTable' 3 mempty
[ [ plain "1", plain "0", plain "0" ]
, [ plain "0", plain "1", plain "1" ]
, [ plain "1", plain "1", plain "0" ]
]
, "Table between Paragraphs" =:
unlines [ "Before"
, "| One | Two |"
, "After"
] =?>
mconcat [ para "Before"
, simpleTable' 2 mempty [ [ plain "One", plain "Two" ] ]
, para "After"
]
, "Table with Header" =:
unlines [ "| Species | Status |"
, "|--------------+--------------|"
, "| cervisiae | domesticated |"
, "| paradoxus | wild |"
] =?>
simpleTable [ plain "Species", plain "Status" ]
[ [ plain "cervisiae", plain "domesticated" ]
, [ plain "paradoxus", plain "wild" ]
]
, "Table with final hline" =:
unlines [ "| cervisiae | domesticated |"
, "| paradoxus | wild |"
, "|--------------+--------------|"
] =?>
simpleTable' 2 mempty
[ [ plain "cervisiae", plain "domesticated" ]
, [ plain "paradoxus", plain "wild" ]
]
, "Table in a box" =:
unlines [ "|---------|---------|"
, "| static | Haskell |"
, "| dynamic | Lisp |"
, "|---------+---------|"
] =?>
simpleTable' 2 mempty
[ [ plain "static", plain "Haskell" ]
, [ plain "dynamic", plain "Lisp" ]
]
, "Table with alignment row" =:
unlines [ "| Numbers | Text | More |"
, "| <c> | <r> | |"
, "| 1 | One | foo |"
, "| 2 | Two | bar |"
] =?>
table "" (zip [AlignCenter, AlignRight, AlignDefault] [0, 0, 0])
[]
[ [ plain "Numbers", plain "Text", plain "More" ]
, [ plain "1" , plain "One" , plain "foo" ]
, [ plain "2" , plain "Two" , plain "bar" ]
]
, "Pipe within text doesn't start a table" =:
"Ceci n'est pas une | pipe " =?>
para (spcSep [ "Ceci", "n'est", "pas", "une", "|", "pipe" ])
, "Missing pipe at end of row" =:
"|incomplete-but-valid" =?>
simpleTable' 1 mempty [ [ plain "incomplete-but-valid" ] ]
, "Table with differing row lengths" =:
unlines [ "| Numbers | Text "
, "|-"
, "| <c> | <r> |"
, "| 1 | One | foo |"
, "| 2"
] =?>
table "" (zip [AlignCenter, AlignRight, AlignDefault] [0, 0, 0])
[ plain "Numbers", plain "Text" , plain mempty ]
[ [ plain "1" , plain "One" , plain "foo" ]
, [ plain "2" , plain mempty , plain mempty ]
]
, "Table with caption" =:
unlines [ "#+CAPTION: Hitchhiker's Multiplication Table"
, "| x | 6 |"
, "| 9 | 42 |"
] =?>
table "Hitchhiker's Multiplication Table"
[(AlignDefault, 0), (AlignDefault, 0)]
[]
[ [ plain "x", plain "6" ]
, [ plain "9", plain "42" ]
]
]
, testGroup "Blocks and fragments"
[ "Source block" =:
unlines [ " #+BEGIN_SRC haskell"
, " main = putStrLn greeting"
, " where greeting = \"moin\""
, " #+END_SRC" ] =?>
let attr' = ("", ["haskell"], [])
code' = "main = putStrLn greeting\n" ++
" where greeting = \"moin\"\n"
in codeBlockWith attr' code'
, "Source block between paragraphs" =:
unlines [ "Low German greeting"
, " #+BEGIN_SRC haskell"
, " main = putStrLn greeting"
, " where greeting = \"Moin!\""
, " #+END_SRC" ] =?>
let attr' = ("", ["haskell"], [])
code' = "main = putStrLn greeting\n" ++
" where greeting = \"Moin!\"\n"
in mconcat [ para $ spcSep [ "Low", "German", "greeting" ]
, codeBlockWith attr' code'
]
, "Source block with rundoc/babel arguments" =:
unlines [ "#+BEGIN_SRC emacs-lisp :exports both"
, "(progn (message \"Hello, World!\")"
, " (+ 23 42))"
, "#+END_SRC" ] =?>
let classes = [ "commonlisp" -- as kate doesn't know emacs-lisp syntax
, "rundoc-block"
]
params = [ ("rundoc-language", "emacs-lisp")
, ("rundoc-exports", "both")
]
code' = unlines [ "(progn (message \"Hello, World!\")"
, " (+ 23 42))" ]
in codeBlockWith ("", classes, params) code'
, "Source block with results and :exports both" =:
unlines [ "#+BEGIN_SRC emacs-lisp :exports both"
, "(progn (message \"Hello, World!\")"
, " (+ 23 42))"
, "#+END_SRC"
, ""
, "#+RESULTS:"
, ": 65"] =?>
let classes = [ "commonlisp" -- as kate doesn't know emacs-lisp syntax
, "rundoc-block"
]
params = [ ("rundoc-language", "emacs-lisp")
, ("rundoc-exports", "both")
]
code' = unlines [ "(progn (message \"Hello, World!\")"
, " (+ 23 42))" ]
results' = "65\n"
in codeBlockWith ("", classes, params) code'
<>
codeBlockWith ("", ["example"], []) results'
, "Source block with results and :exports code" =:
unlines [ "#+BEGIN_SRC emacs-lisp :exports code"
, "(progn (message \"Hello, World!\")"
, " (+ 23 42))"
, "#+END_SRC"
, ""
, "#+RESULTS:"
, ": 65" ] =?>
let classes = [ "commonlisp" -- as kate doesn't know emacs-lisp syntax
, "rundoc-block"
]
params = [ ("rundoc-language", "emacs-lisp")
, ("rundoc-exports", "code")
]
code' = unlines [ "(progn (message \"Hello, World!\")"
, " (+ 23 42))" ]
in codeBlockWith ("", classes, params) code'
, "Source block with results and :exports results" =:
unlines [ "#+BEGIN_SRC emacs-lisp :exports results"
, "(progn (message \"Hello, World!\")"
, " (+ 23 42))"
, "#+END_SRC"
, ""
, "#+RESULTS:"
, ": 65" ] =?>
let results' = "65\n"
in codeBlockWith ("", ["example"], []) results'
, "Source block with results and :exports none" =:
unlines [ "#+BEGIN_SRC emacs-lisp :exports none"
, "(progn (message \"Hello, World!\")"
, " (+ 23 42))"
, "#+END_SRC"
, ""
, "#+RESULTS:"
, ": 65" ] =?>
rawBlock "html" ""
, "Example block" =:
unlines [ "#+begin_example"
, "A chosen representation of"
, "a rule."
, "#+eND_exAMPle"
] =?>
codeBlockWith ("", ["example"], [])
"A chosen representation of\na rule.\n"
, "HTML block" =:
unlines [ "#+BEGIN_HTML"
, "<aside>HTML5 is pretty nice.</aside>"
, "#+END_HTML"
] =?>
rawBlock "html" "<aside>HTML5 is pretty nice.</aside>\n"
, "Quote block" =:
unlines [ "#+BEGIN_QUOTE"
, "/Niemand/ hat die Absicht, eine Mauer zu errichten!"
, "#+END_QUOTE"
] =?>
blockQuote (para (spcSep [ emph "Niemand", "hat", "die", "Absicht,"
, "eine", "Mauer", "zu", "errichten!"
]))
, "Verse block" =:
unlines [ "The first lines of Goethe's /Faust/:"
, "#+begin_verse"
, "Habe nun, ach! Philosophie,"
, "Juristerei und Medizin,"
, "Und leider auch Theologie!"
, "Durchaus studiert, mit heißem Bemühn."
, "#+end_verse"
] =?>
mconcat
[ para $ spcSep [ "The", "first", "lines", "of"
, "Goethe's", emph "Faust" <> ":"]
, para $ mconcat
[ spcSep [ "Habe", "nun,", "ach!", "Philosophie," ]
, linebreak
, spcSep [ "Juristerei", "und", "Medizin," ]
, linebreak
, spcSep [ "Und", "leider", "auch", "Theologie!" ]
, linebreak
, spcSep [ "Durchaus", "studiert,", "mit", "heißem", "Bemühn." ]
]
]
, "Verse block with newlines" =:
unlines [ "#+BEGIN_VERSE"
, "foo"
, ""
, "bar"
, "#+END_VERSE"
] =?>
para ("foo" <> linebreak <> linebreak <> "bar")
, "LaTeX fragment" =:
unlines [ "\\begin{equation}"
, "X_i = \\begin{cases}"
, " G_{\\alpha(i)} & \\text{if }\\alpha(i-1) = \\alpha(i)\\\\"
, " C_{\\alpha(i)} & \\text{otherwise}"
, " \\end{cases}"
, "\\end{equation}"
] =?>
rawBlock "latex"
(unlines [ "\\begin{equation}"
, "X_i = \\begin{cases}"
, " G_{\\alpha(i)} & \\text{if }\\alpha(i-1) =" ++
" \\alpha(i)\\\\"
, " C_{\\alpha(i)} & \\text{otherwise}"
, " \\end{cases}"
, "\\end{equation}"
])
, "Code block with caption" =:
unlines [ "#+CAPTION: Functor laws in Haskell"
, "#+NAME: functor-laws"
, "#+BEGIN_SRC haskell"
, "fmap id = id"
, "fmap (p . q) = (fmap p) . (fmap q)"
, "#+END_SRC"
] =?>
divWith
nullAttr
(mappend
(plain $ spanWith ("", ["label"], [])
(spcSep [ "Functor", "laws", "in", "Haskell" ]))
(codeBlockWith ("functor-laws", ["haskell"], [])
(unlines [ "fmap id = id"
, "fmap (p . q) = (fmap p) . (fmap q)"
])))
, "Convert blank lines in blocks to single newlines" =:
unlines [ "#+begin_html"
, ""
, "<span>boring</span>"
, ""
, "#+end_html"
] =?>
rawBlock "html" "\n<span>boring</span>\n\n"
, "Non-letter chars in source block parameters" =:
unlines [ "#+BEGIN_SRC C :tangle xxxx.c :city Zürich"
, "code body"
, "#+END_SRC"
] =?>
let classes = [ "c", "rundoc-block" ]
params = [ ("rundoc-language", "C")
, ("rundoc-tangle", "xxxx.c")
, ("rundoc-city", "Zürich")
]
in codeBlockWith ( "", classes, params) "code body\n"
]
, testGroup "Smart punctuation"
[ test orgSmart "quote before ellipses"
("'...hi'"
=?> para (singleQuoted "…hi"))
, test orgSmart "apostrophe before emph"
("D'oh! A l'/aide/!"
=?> para ("D’oh! A l’" <> emph "aide" <> "!"))
, test orgSmart "apostrophe in French"
("À l'arrivée de la guerre, le thème de l'«impossibilité du socialisme»"
=?> para "À l’arrivée de la guerre, le thème de l’«impossibilité du socialisme»")
, test orgSmart "Quotes cannot occur at the end of emphasized text"
("/say \"yes\"/" =?>
para ("/say" <> space <> doubleQuoted "yes" <> "/"))
, test orgSmart "Dashes are allowed at the borders of emphasis'"
("/foo---/" =?>
para (emph "foo—"))
]
]
|
ddssff/pandoc
|
tests/Tests/Readers/Org.hs
|
gpl-2.0
| 45,121 | 0 | 22 | 21,277 | 8,271 | 4,509 | 3,762 | 996 | 1 |
{-|
Purely functional weight balanced trees, aka trees of bounded balance.
* J. Nievergelt and E.M. Reingold, \"Binary search trees of
bounded balance\", Proceedings of the fourth annual ACM symposium on
Theory of computing, pp 137-142, 1972.
* S. Adams, \"Implementing sets efficiently in a functional language\",
Technical Report CSTR 92-10, University of Southampton, 1992.
<http://groups.csail.mit.edu/mac/users/adams/BB/>
* S. Adam, \"Efficient sets: a balancing act\",
Journal of Functional Programming, Vol 3, Issue 4, pp 553-562.
* Y. Hirai and K. Yamamoto,
\"Balancing Weight-Balanced Trees\",
Journal of Functional Programming. Vol 21, Issue 03, pp 287-307.
<http://mew.org/~kazu/proj/weight-balanced-tree/>
* M. Strake, \"Adams' Trees Revisited - Correct and Efficient Implementation\",
TFP 2011.
<http://fox.ucw.cz/papers/bbtree/>
-}
module Data.Set.WBTree (
-- * Data structures
WBTree(..)
, Size
, size
-- * Creating sets
, empty
, singleton
, insert
, fromList
-- * Converting to a list
, toList
-- * Membership
, member
-- * Deleting
, delete
, deleteMin
, deleteMax
-- * Checking
, null
-- * Set operations
, union
, intersection
, difference
-- * Helper functions
, join
, merge
, split
, minimum
, maximum
, valid
-- , showTree
-- , printTree
) where
import Data.List (foldl')
import Prelude hiding (minimum, maximum, null)
----------------------------------------------------------------
type Size = Int
data WBTree a = Leaf | Node Size (WBTree a) a (WBTree a) deriving (Show)
instance (Eq a) => Eq (WBTree a) where
t1 == t2 = toList t1 == toList t2
size :: WBTree a -> Size
size Leaf = 0
size (Node sz _ _ _) = sz
----------------------------------------------------------------
{-|
See if the set is empty.
>>> Data.Set.WBTree.null empty
True
>>> Data.Set.WBTree.null (singleton 1)
False
-}
null :: Eq a => WBTree a -> Bool
null t = t == Leaf
----------------------------------------------------------------
{-| Empty set.
>>> size empty
0
-}
empty :: WBTree a
empty = Leaf
{-| Singleton set.
>>> size (singleton 'a')
1
-}
singleton :: a -> WBTree a
singleton x = Node 1 Leaf x Leaf
----------------------------------------------------------------
node :: WBTree a -> a -> WBTree a -> WBTree a
node l x r = Node (size l + size r + 1) l x r
----------------------------------------------------------------
{-| Insertion. O(log N)
>>> insert 5 (fromList [5,3]) == fromList [3,5]
True
>>> insert 7 (fromList [5,3]) == fromList [3,5,7]
True
>>> insert 5 empty == singleton 5
True
-}
insert :: Ord a => a -> WBTree a -> WBTree a
insert k Leaf = singleton k
insert k (Node sz l x r) = case compare k x of
LT -> balanceR (insert k l) x r
GT -> balanceL l x (insert k r)
EQ -> Node sz l x r
{-| Creating a set from a list. O(N log N)
>>> empty == fromList []
True
>>> singleton 'a' == fromList ['a']
True
>>> fromList [5,3,5] == fromList [5,3]
True
-}
fromList :: Ord a => [a] -> WBTree a
fromList = foldl' (flip insert) empty
----------------------------------------------------------------
{-| Creating a list from a set. O(N)
>>> toList (fromList [5,3])
[3,5]
>>> toList empty
[]
-}
toList :: WBTree a -> [a]
toList t = inorder t []
where
inorder Leaf xs = xs
inorder (Node _ l x r) xs = inorder l (x : inorder r xs)
----------------------------------------------------------------
{-| Checking if this element is a member of a set?
>>> member 5 (fromList [5,3])
True
>>> member 1 (fromList [5,3])
False
-}
member :: Ord a => a -> WBTree a -> Bool
member _ Leaf = False
member k (Node _ l x r) = case compare k x of
LT -> member k l
GT -> member k r
EQ -> True
----------------------------------------------------------------
balanceL :: WBTree a -> a -> WBTree a -> WBTree a
balanceL l x r
| isBalanced l r = node l x r
| otherwise = rotateL l x r
balanceR :: WBTree a -> a -> WBTree a -> WBTree a
balanceR l x r
| isBalanced r l = node l x r
| otherwise = rotateR l x r
rotateL :: WBTree a -> a -> WBTree a -> WBTree a
rotateL l x r@(Node _ rl _ rr)
| isSingle rl rr = singleL l x r
| otherwise = doubleL l x r
rotateL _ _ _ = error "rotateL"
rotateR :: WBTree a -> a -> WBTree a -> WBTree a
rotateR l@(Node _ ll _ lr) x r
| isSingle lr ll = singleR l x r
| otherwise = doubleR l x r
rotateR _ _ _ = error "rotateR"
singleL :: WBTree a -> a -> WBTree a -> WBTree a
singleL l x (Node _ rl rx rr) = node (node l x rl) rx rr
singleL _ _ _ = error "singleL"
singleR :: WBTree a -> a -> WBTree a -> WBTree a
singleR (Node _ ll lx lr) x r = node ll lx (node lr x r)
singleR _ _ _ = error "singleR"
doubleL :: WBTree a -> a -> WBTree a -> WBTree a
doubleL l x (Node _ (Node _ rll rlx rlr) rx rr) = node (node l x rll) rlx (node rlr rx rr)
doubleL _ _ _ = error "doubleL"
doubleR :: WBTree a -> a -> WBTree a -> WBTree a
doubleR (Node _ ll lx (Node _ lrl lrx lrr)) x r = node (node ll lx lrl) lrx (node lrr x r)
doubleR _ _ _ = error "doubleR"
----------------------------------------------------------------
{-| Deleting the minimum element. O(log N)
>>> deleteMin (fromList [5,3,7]) == fromList [5,7]
True
>>> deleteMin empty == empty
True
-}
deleteMin :: WBTree a -> WBTree a
deleteMin (Node _ Leaf _ r) = r
deleteMin (Node _ l x r) = balanceL (deleteMin l) x r
deleteMin Leaf = Leaf
{-| Deleting the maximum
>>> deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")]
True
>>> deleteMax empty == empty
True
-}
deleteMax :: WBTree a -> WBTree a
deleteMax (Node _ l _ Leaf) = l
deleteMax (Node _ l x r) = balanceR l x (deleteMax r)
deleteMax Leaf = Leaf
----------------------------------------------------------------
{-| Deleting this element from a set. O(log N)
>>> delete 5 (fromList [5,3]) == singleton 3
True
>>> delete 7 (fromList [5,3]) == fromList [3,5]
True
>>> delete 5 empty == empty
True
-}
delete :: Ord a => a -> WBTree a -> WBTree a
delete k t = case t of
Leaf -> Leaf
Node _ l x r -> case compare k x of
LT -> balanceL (delete k l) x r
GT -> balanceR l x (delete k r)
EQ -> glue l r
----------------------------------------------------------------
{-| Checking validity of a set.
-}
valid :: Ord a => WBTree a -> Bool
valid t = balanced t && ordered t && validsize t
balanced :: WBTree a -> Bool
balanced Leaf = True
balanced (Node _ l _ r) = isBalanced l r && isBalanced r l
&& balanced l && balanced r
ordered :: Ord a => WBTree a -> Bool
ordered t = bounded (const True) (const True) t
where
bounded lo hi t' = case t' of
Leaf -> True
Node _ l x r -> lo x && hi x && bounded lo (<x) l && bounded (>x) hi r
validsize :: WBTree a -> Bool
validsize t = realsize t == Just (size t)
where
realsize t' = case t' of
Leaf -> Just 0
Node s l _ r -> case (realsize l,realsize r) of
(Just n,Just m) | n+m+1 == s -> Just s
_ -> Nothing
----------------------------------------------------------------
{-| Joining two sets with an element. O(log N)
Each element of the left set must be less than the element.
Each element of the right set must be greater than the element.
-}
join :: Ord a => WBTree a -> a -> WBTree a -> WBTree a
join Leaf x r = insert x r
join l x Leaf = insert x l
join l@(Node _ ll lx lr) x r@(Node _ rl rx rr)
| bal1 && bal2 = node l x r
| bal1 = balanceL ll lx (join lr x r)
| otherwise = balanceR (join l x rl) rx rr
where
bal1 = isBalanced l r
bal2 = isBalanced r l
{-| Merging two sets. O(log N)
Each element of the left set must be less than each element of
the right set.
-}
merge :: WBTree a -> WBTree a -> WBTree a
merge Leaf r = r
merge l Leaf = l
merge l@(Node _ ll lx lr) r@(Node _ rl rx rr)
| bal1 && bal2 = glue l r
| bal1 = balanceL ll lx (merge lr r)
| otherwise = balanceR (merge l rl) rx rr
where
bal1 = isBalanced l r
bal2 = isBalanced r l
glue :: WBTree a -> WBTree a -> WBTree a
glue Leaf r = r
glue l Leaf = l
glue l r
| size l > size r = balanceL (deleteMax l) (maximum l) r
| otherwise = balanceR l (minimum r) (deleteMin r)
{-| Splitting a set. O(log N)
>>> split 2 (fromList [5,3]) == (empty, fromList [3,5])
True
>>> split 3 (fromList [5,3]) == (empty, singleton 5)
True
>>> split 4 (fromList [5,3]) == (singleton 3, singleton 5)
True
>>> split 5 (fromList [5,3]) == (singleton 3, empty)
True
>>> split 6 (fromList [5,3]) == (fromList [3,5], empty)
True
-}
split :: Ord a => a -> WBTree a -> (WBTree a, WBTree a)
split _ Leaf = (Leaf,Leaf)
split k (Node _ l x r) = case compare k x of
LT -> let (lt,gt) = split k l in (lt,join gt x r)
GT -> let (lt,gt) = split k r in (join l x lt,gt)
EQ -> (l,r)
----------------------------------------------------------------
{-| Finding the minimum element. O(log N)
>>> minimum (fromList [3,5,1])
1
>>> minimum empty
*** Exception: minimum
-}
minimum :: WBTree a -> a
minimum (Node _ Leaf x _) = x
minimum (Node _ l _ _) = minimum l
minimum _ = error "minimum"
{-| Finding the maximum element. O(log N)
>>> maximum (fromList [3,5,1])
5
>>> maximum empty
*** Exception: maximum
-}
maximum :: WBTree a -> a
maximum (Node _ _ x Leaf) = x
maximum (Node _ _ _ r) = maximum r
maximum _ = error "maximum"
----------------------------------------------------------------
{-| Creating a union set from two sets. O(N + M)
>>> union (fromList [5,3]) (fromList [5,7]) == fromList [3,5,7]
True
-}
union :: Ord a => WBTree a -> WBTree a -> WBTree a
union t1 Leaf = t1
union Leaf t2 = t2
union t1 (Node _ l x r) = join (union l' l) x (union r' r)
where
(l',r') = split x t1
{-| Creating a intersection set from sets. O(N + N)
>>> intersection (fromList [5,3]) (fromList [5,7]) == singleton 5
True
-}
intersection :: Ord a => WBTree a -> WBTree a -> WBTree a
intersection Leaf _ = Leaf
intersection _ Leaf = Leaf
intersection t1 (Node _ l x r)
| member x t1 = join (intersection l' l) x (intersection r' r)
| otherwise = merge (intersection l' l) (intersection r' r)
where
(l',r') = split x t1
{-| Creating a difference set from sets. O(N + N)
>>> difference (fromList [5,3]) (fromList [5,7]) == singleton 3
True
-}
difference :: Ord a => WBTree a -> WBTree a -> WBTree a
difference Leaf _ = Leaf
difference t1 Leaf = t1
difference t1 (Node _ l x r) = merge (difference l' l) (difference r' r)
where
(l',r') = split x t1
----------------------------------------------------------------
delta :: Int
delta = 3
gamma :: Int
gamma = 2
isBalanced :: WBTree a -> WBTree a -> Bool
isBalanced a b = delta * (size a + 1) >= (size b + 1)
isSingle :: WBTree a -> WBTree a -> Bool
isSingle a b = (size a + 1) < gamma * (size b + 1)
{- Adams's variant
isBalanced :: WBTree a -> WBTree a -> Bool
isBalanced a b = x + y <= 1 || delta * x >= y
where x = size a
y = size b
isSingle :: WBTree a -> WBTree a -> Bool
isSingle a b = size a < gamma * size b
-}
|
mightymoose/liquidhaskell
|
benchmarks/llrbtree-0.1.1/Data/Set/WBTree.hs
|
bsd-3-clause
| 11,431 | 0 | 18 | 2,946 | 3,424 | 1,687 | 1,737 | 184 | 4 |
import qualified Data.Vector as U
main = print . U.null . U.filter (>10) . U.map (subtract 6) . U.enumFromTo 1 $ (100000000 :: Int)
|
dolio/vector
|
old-testsuite/microsuite/null.hs
|
bsd-3-clause
| 133 | 1 | 10 | 25 | 70 | 36 | 34 | 2 | 1 |
{-# LANGUAGE RankNTypes #-}
module T12082 where
import Data.Typeable (Typeable)
import Control.Monad.ST (RealWorld)
f :: forall a. (forall b. Typeable b => b -> a) -> a
f = undefined :: (RealWorld -> a) -> a
|
ezyang/ghc
|
testsuite/tests/typecheck/should_compile/T12082.hs
|
bsd-3-clause
| 211 | 0 | 10 | 39 | 78 | 46 | 32 | 6 | 1 |
{-# LANGUAGE TemplateHaskell #-}
-- Two sliced declarations bind the same variable.
-- This test checks that there's a reasonable error message
module ShouldCompile where
$( [d| x = 1 |] )
$( [d| x = 2 |] )
|
ryantm/ghc
|
testsuite/tests/th/TH_dupdecl.hs
|
bsd-3-clause
| 211 | 0 | 6 | 43 | 29 | 20 | 9 | 4 | 0 |
{-# LANGUAGE DeriveGeneric #-}
module RunnyBabbot.TwitterData
( Tweet(..)
, User(..)
, TweetResponse(..)
) where
import Data.Aeson
import GHC.Generics
import Data.Text (Text)
-- LHS in these records is not camelcase since it's the data format
-- that Twitter gives us in JSON.
data User = User { screen_name :: !Text } deriving (Show, Generic)
data Tweet = Tweet
{ text :: !Text
, id :: Integer
, user :: User
} deriving (Show, Generic)
instance FromJSON User
instance FromJSON Tweet
data TweetResponse = TweetResponse
{ status :: String
, in_reply_to_status_id :: Integer } deriving (Show, Eq)
|
jsl/RunnyBabbot
|
src/RunnyBabbot/TwitterData.hs
|
mit
| 644 | 0 | 9 | 144 | 164 | 98 | 66 | 23 | 0 |
module Network.Stun.MappedAddress where
import Control.Applicative ((<$>))
import Control.Monad
import Data.Bits
import Data.Serialize
import Data.Word
import Network.Endian
import Network.Socket
import Network.Stun.Base
xmaAttributeType :: Word16
xmaAttributeType = 0x0020
maAttributeType :: Word16
maAttributeType = 0x0001
newtype MappedAddress = MA{unMA :: SockAddr }
deriving (Eq, Show)
instance Serialize MappedAddress where
put = putAddress . unMA
get = MA `liftM` getAddress
instance IsAttribute MappedAddress where
attributeTypeValue _ = 0x0001
newtype XorMappedAddress = XMA{unXMA :: SockAddr }
deriving (Eq, Show)
instance Serialize XorMappedAddress where
put = putAddress . unXMA
get = XMA `liftM` getAddress
instance IsAttribute XorMappedAddress where
attributeTypeValue _ = 0x0020
-- most significant 16 bits of the magic cookie
halfCookie :: Word16
halfCookie = fromIntegral $ cookie `shiftR` 16
putAddress :: SockAddr -> PutM ()
putAddress (SockAddrInet port address) = do
putWord8 0
putWord8 1
putWord16be $ fromIntegral port
putWord32host address -- address already is BE
putAddress (SockAddrInet6 port _ (addr1, addr2, addr3, addr4) _ ) = do
putWord8 0
putWord8 2
putWord16be $ fromIntegral port
putWord32be addr1
putWord32be addr2
putWord32be addr3
putWord32be addr4
putAddress _ = error "putAddress: Address type not implemented"
getAddress :: Get SockAddr
getAddress = do
guard . (== 0) =<< getWord8
family <- getWord8
port <- fromIntegral <$> getWord16be
case family of
1 -> do
address <- getWord32host
return $ SockAddrInet port address
2 -> do
addr1 <- getWord32be
addr2 <- getWord32be
addr3 <- getWord32be
addr4 <- getWord32be
return $ (SockAddrInet6 port 0 (addr1, addr2, addr3, addr4)) 0
_ -> mzero
fromXorMappedAddress :: TransactionID -> XorMappedAddress -> SockAddr
fromXorMappedAddress tid (XMA addr) = xorAddress tid addr
xorMappedAddress :: TransactionID -> SockAddr -> XorMappedAddress
xorMappedAddress tid addr = XMA $ xorAddress tid addr
xorAddress :: TransactionID -> SockAddr -> SockAddr
xorAddress _ (SockAddrInet port address) =
SockAddrInet (fromIntegral (halfCookie `xor` (fromIntegral port)))
(htonl cookie `xor` address)
xorAddress (TID tid1 tid2 tid3)
(SockAddrInet6 port fi (addr1, addr2, addr3, addr4) sid) =
SockAddrInet6 (fromIntegral (halfCookie `xor` (fromIntegral port)))
fi
( cookie `xor` addr1
, tid1 `xor` addr2
, tid2 `xor` addr3
, tid3 `xor` addr4
)
sid
xorAddress _ _ = error "xorAddress does not work on SockAddrUnix"
|
Philonous/hs-stun
|
source/Network/Stun/MappedAddress.hs
|
mit
| 2,833 | 0 | 16 | 702 | 788 | 415 | 373 | 78 | 3 |
--------------------------------------------------------------------
{-|
Module : SDL.Cairo.Image.Loader
Copyright : Copyright (c) 2015 Yun-Yan Chi
License : MIT
Maintainer : [email protected]
This module exposes wrapper functions to load image files into memory
by using JuicyPixel (See <https://hackage.haskell.org/package/JuicyPixels>).
So far, supported file formats are only PNG, JPG, BMP.
Plus, merely four pixel formats
'PixelRGB8', 'PixelRGB16', 'PixelRGBA8' and 'PixelRGBA16'
are supported.
-}
--------------------------------------------------------------------
module SDL.Cairo.Image.Load
(
-- * loading 'Image'
loadRGB8
, loadRGB16
, loadRGBA8
, loadRGBA16
-- * loadable format
, ImgType (..)
-- * Default 5x5 'Image'
, defImageRGB8
, defImageRGB16
, defImageRGBA8
, defImageRGBA16
) where
--
import Codec.Picture
import qualified Data.Vector.Storable as VecS (fromList)
--
-- |
data ImgType = PNG | JPG | BMP deriving (Show,Eq)
loadRGB8 :: ImgType -> FilePath -> IO (Image PixelRGB8)
loadRGB8 PNG fp = do
ei <- readPng fp
case ei of
Right (ImageRGB8 img) -> do
return img
_ -> do
return defImageRGB8
--
loadRGB8 JPG fp = do
ei <- readJpeg fp
case ei of
Right (ImageRGB8 img) -> do
return img
_ -> do
return defImageRGB8
--
loadRGB8 BMP fp = do
ei <- readBitmap fp
case ei of
Right (ImageRGB8 img) -> do
return img
_ -> do
return defImageRGB8
--
loadRGB16 :: ImgType -> FilePath -> IO (Image PixelRGB16)
loadRGB16 PNG fp = do
ei <- readPng fp
case ei of
Right (ImageRGB16 img) -> do
return img
_ -> do
return defImageRGB16
--
loadRGB16 JPG fp = do
ei <- readJpeg fp
case ei of
Right (ImageRGB16 img) -> do
return img
_ -> do
return defImageRGB16
--
loadRGB16 BMP fp = do
ei <- readBitmap fp
case ei of
Right (ImageRGB16 img) -> do
return img
_ -> do
return defImageRGB16
--
loadRGBA8 :: ImgType -> FilePath -> IO (Image PixelRGBA8)
loadRGBA8 PNG fp = do
ei <- readPng fp
case ei of
Right (ImageRGBA8 img) -> do
return img
_ -> do
return defImageRGBA8
--
loadRGBA8 JPG fp = do
ei <- readJpeg fp
case ei of
Right (ImageRGBA8 img) -> do
return img
_ -> do
return defImageRGBA8
--
loadRGBA8 BMP fp = do
ei <- readBitmap fp
case ei of
Right (ImageRGBA8 img) -> do
return img
_ -> do
return defImageRGBA8
--
loadRGBA16 :: ImgType -> FilePath -> IO (Image PixelRGBA16)
loadRGBA16 PNG fp = do
ei <- readPng fp
case ei of
Right (ImageRGBA16 img) -> do
return img
_ -> do
return defImageRGBA16
--
loadRGBA16 JPG fp = do
ei <- readJpeg fp
case ei of
Right (ImageRGBA16 img) -> do
return img
_ -> do
return defImageRGBA16
--
loadRGBA16 BMP fp = do
ei <- readBitmap fp
case ei of
Right (ImageRGBA16 img) -> do
return img
_ -> do
return defImageRGBA16
--
defImageRGB8 :: Image PixelRGB8
defImageRGB8 = Image
{ imageWidth = 5
, imageHeight = 5
, imageData = VecS.fromList
[ 255,0,0, 0,0,0, 0,0,0, 0,0,0, 255,0,0
, 0,0,0, 255,0,0, 0,0,0, 255,0,0, 0,0,0
, 0,0,0, 0,0,0, 255,0,0, 0,0,0, 0,0,0
, 0,0,0, 255,0,0, 0,0,0, 255,0,0, 0,0,0
, 255,0,0, 0,0,0, 0,0,0, 0,0,0, 255,0,0
]
}
--
defImageRGB16 :: Image PixelRGB16
defImageRGB16 = Image
{ imageWidth = 5
, imageHeight = 5
, imageData = VecS.fromList
[ 255,0,0, 0,0,0, 0,0,0, 0,0,0, 255,0,0
, 0,0,0, 255,0,0, 0,0,0, 255,0,0, 0,0,0
, 0,0,0, 0,0,0, 255,0,0, 0,0,0, 0,0,0
, 0,0,0, 255,0,0, 0,0,0, 255,0,0, 0,0,0
, 255,0,0, 0,0,0, 0,0,0, 0,0,0, 255,0,0
]
}
--
defImageRGBA8 :: Image PixelRGBA8
defImageRGBA8 = Image
{ imageWidth = 5
, imageHeight = 5
, imageData = VecS.fromList
[ 255,0,0,255, 0,0,0,255, 0,0,0,255, 0,0,0,255, 255,0,0,255
, 0,0,0,255, 255,0,0,255, 0,0,0,255, 255,0,0,255, 0,0,0,255
, 0,0,0,255, 0,0,0,255, 255,0,0,255, 0,0,0,255, 0,0,0,255
, 0,0,0,255, 255,0,0,255, 0,0,0,255, 255,0,0,255, 0,0,0,255
, 255,0,0,255, 0,0,0,255, 0,0,0,255, 0,0,0,255, 255,0,0,255
]
}
--
defImageRGBA16 :: Image PixelRGBA16
defImageRGBA16 = Image
{ imageWidth = 5
, imageHeight = 5
, imageData = VecS.fromList
[ 255,0,0,255, 0,0,0,255, 0,0,0,255, 0,0,0,255, 255,0,0,255
, 0,0,0,255, 255,0,0,255, 0,0,0,255, 255,0,0,255, 0,0,0,255
, 0,0,0,255, 0,0,0,255, 255,0,0,255, 0,0,0,255, 0,0,0,255
, 0,0,0,255, 255,0,0,255, 0,0,0,255, 255,0,0,255, 0,0,0,255
, 255,0,0,255, 0,0,0,255, 0,0,0,255, 0,0,0,255, 255,0,0,255
]
}
|
jaiyalas/sdl2-cairo-image
|
src/SDL/Cairo/Image/Load.hs
|
mit
| 4,960 | 0 | 12 | 1,471 | 2,118 | 1,223 | 895 | 142 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Hpack.UtilSpec (main, spec) where
import Data.Aeson
import Data.Aeson.QQ
import Data.Aeson.Types
import Helper
import System.Directory
import Hpack.Config
import Hpack.Util
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "sort" $ do
it "sorts lexicographically" $ do
sort ["foo", "Foo"] `shouldBe` ["Foo", "foo" :: String]
describe "parseMain" $ do
it "accepts source file" $ do
parseMain "Main.hs" `shouldBe` ("Main.hs", [])
it "accepts literate source file" $ do
parseMain "Main.lhs" `shouldBe` ("Main.lhs", [])
it "accepts module" $ do
parseMain "Foo" `shouldBe` ("Foo.hs", ["-main-is Foo"])
it "accepts hierarchical module" $ do
parseMain "Foo.Bar.Baz" `shouldBe` ("Foo/Bar/Baz.hs", ["-main-is Foo.Bar.Baz"])
it "accepts qualified identifier" $ do
parseMain "Foo.bar" `shouldBe` ("Foo.hs", ["-main-is Foo.bar"])
describe "toModule" $ do
it "maps .hs paths to module names" $ do
toModule ["Foo", "Bar", "Baz.hs"] `shouldBe` Just "Foo.Bar.Baz"
it "maps .lhs paths to module names" $ do
toModule ["Foo", "Bar", "Baz.lhs"] `shouldBe` Just "Foo.Bar.Baz"
it "maps .hsc paths to module names" $ do
toModule ["Foo", "Bar", "Baz.hsc"] `shouldBe` Just "Foo.Bar.Baz"
it "rejects invalid module names" $ do
toModule ["resources", "hello.hs"] `shouldBe` Nothing
describe "getFilesRecursive" $ do
it "gets all files from given directory and all its subdirectories" $ do
inTempDirectoryNamed "test" $ do
touch "foo/bar"
touch "foo/baz"
touch "foo/foobar/baz"
actual <- getFilesRecursive "foo"
actual `shouldMatchList` [
["bar"]
, ["baz"]
, ["foobar", "baz"]
]
describe "List" $ do
let invalid = [aesonQQ|{
name: "hpack",
gi: "sol/hpack",
ref: "master"
}|]
parseError :: String -> Either String (List Dependency)
parseError prefix = Left (prefix ++ ": neither key \"git\" nor key \"github\" present")
context "when parsing single values" $ do
it "returns the value in a singleton list" $ do
fromJSON (toJSON $ Number 23) `shouldBe` Success (List [23 :: Int])
it "returns error messages from element parsing" $ do
parseEither parseJSON invalid `shouldBe` parseError "Error in $"
context "when parsing a list of values" $ do
it "returns the list" $ do
fromJSON (toJSON [Number 23, Number 42]) `shouldBe` Success (List [23, 42 :: Int])
it "propagates parse error messages of invalid elements" $ do
parseEither parseJSON (toJSON [String "foo", invalid]) `shouldBe` parseError "Error in $[1]"
describe "tryReadFile" $ do
it "reads file" $ do
inTempDirectory $ do
writeFile "foo" "bar"
tryReadFile "foo" `shouldReturn` Just "bar"
it "returns Nothing if file does not exist" $ do
inTempDirectory $ do
tryReadFile "foo" `shouldReturn` Nothing
describe "expandGlobs" $ around withTempDirectory $ do
it "accepts simple files" $ \dir -> do
touch (dir </> "foo.js")
expandGlobs "field-name" dir ["foo.js"] `shouldReturn` ([], ["foo.js"])
it "removes duplicates" $ \dir -> do
touch (dir </> "foo.js")
expandGlobs "field-name" dir ["foo.js", "*.js"] `shouldReturn` ([], ["foo.js"])
it "rejects directories" $ \dir -> do
touch (dir </> "foo")
createDirectory (dir </> "bar")
expandGlobs "field-name" dir ["*"] `shouldReturn` ([], ["foo"])
it "rejects character ranges" $ \dir -> do
touch (dir </> "foo1")
touch (dir </> "foo2")
touch (dir </> "foo[1,2]")
expandGlobs "field-name" dir ["foo[1,2]"] `shouldReturn` ([], ["foo[1,2]"])
context "when expanding *" $ do
it "expands by extension" $ \dir -> do
let files = [
"files/foo.js"
, "files/bar.js"
, "files/baz.js"]
mapM_ (touch . (dir </>)) files
touch (dir </> "files/foo.hs")
expandGlobs "field-name" dir ["files/*.js"] `shouldReturn` ([], sort files)
it "rejects dot-files" $ \dir -> do
touch (dir </> "foo/bar")
touch (dir </> "foo/.baz")
expandGlobs "field-name" dir ["foo/*"] `shouldReturn` ([], ["foo/bar"])
it "accepts dot-files when explicitly asked to" $ \dir -> do
touch (dir </> "foo/bar")
touch (dir </> "foo/.baz")
expandGlobs "field-name" dir ["foo/.*"] `shouldReturn` ([], ["foo/.baz"])
it "matches at most one directory component" $ \dir -> do
touch (dir </> "foo/bar/baz.js")
touch (dir </> "foo/bar.js")
expandGlobs "field-name" dir ["*/*.js"] `shouldReturn` ([], ["foo/bar.js"])
context "when expanding **" $ do
it "matches arbitrary many directory components" $ \dir -> do
let file = "foo/bar/baz.js"
touch (dir </> file)
expandGlobs "field-name" dir ["**/*.js"] `shouldReturn` ([], [file])
context "when a pattern does not match anything" $ do
it "warns" $ \dir -> do
expandGlobs "field-name" dir ["foo"] `shouldReturn`
(["Specified pattern \"foo\" for field-name does not match any files"], [])
context "when a pattern only matches a directory" $ do
it "warns" $ \dir -> do
createDirectory (dir </> "foo")
expandGlobs "field-name" dir ["foo"] `shouldReturn`
(["Specified pattern \"foo\" for field-name does not match any files"], [])
|
deech/hpack
|
test/Hpack/UtilSpec.hs
|
mit
| 5,702 | 0 | 21 | 1,535 | 1,660 | 829 | 831 | 121 | 1 |
{-
Copyright (C) 2012-2017 Jimmy Liang <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
module Language.Clafer.IG.Process (Process, executableDirectory, waitFor, getContentsVerbatim, getMessage, readMessage, putMessage, pipeProcess) where
import Control.Monad
import Control.Monad.IO.Class
import System.Environment.Executable
import System.IO
import System.Process
import GHC.IO.Exception
data Process = Process{stdIn::Handle, stdOut::Handle, procHandle::ProcessHandle}
executableDirectory :: IO FilePath
executableDirectory = fst `liftM` splitExecutablePath
-- | Start another process and return the piped std_in, std_out stream
pipeProcess :: FilePath -> [String] -> IO Process
pipeProcess exec args =
do
let process = (proc exec args) { std_in = CreatePipe, std_out = CreatePipe }
(Just stdIn', Just stdOut', _, proceHandle) <- createProcess process
hSetNewlineMode stdIn' noNewlineTranslation
return $ Process stdIn' stdOut' proceHandle -- Pipe always has a handle according to docs
-- | Wait until the process terminates
waitFor :: Process -> IO ExitCode
waitFor proce = waitForProcess (procHandle proce)
-- | Reads the entire output verbatim
getContentsVerbatim :: Process -> IO String
getContentsVerbatim proce =
do
contents <- hGetContents $ stdOut proce
-- hGetContents is lazy. Force it to evaluate by mapping over everything doing nothing
mapM_ return contents
return contents
-- | Read the message
getMessage :: MonadIO m => Process -> m String
getMessage proce =
liftIO $ do
len <- read `liftM` hGetLine (stdOut proce)
mapM hGetChar $ replicate len (stdOut proce)
readMessage :: (Read r, MonadIO m) => Process -> m r
readMessage proce = read `liftM` getMessage proce
-- | Put the message
putMessage :: MonadIO m => Process -> String -> m ()
putMessage proce message =
liftIO $ do
hPutStrLn (stdIn proce) (show $ length message)
hPutStr (stdIn proce) message
hFlush (stdIn proce)
|
gsdlab/claferIG
|
src/Language/Clafer/IG/Process.hs
|
mit
| 3,050 | 0 | 12 | 580 | 516 | 270 | 246 | 38 | 1 |
module Main where
import qualified HackerRank.Tutorials.Statistics.Day5 as M
main :: IO ()
main = M.main1
|
4e6/sandbox
|
haskell/hackerrank/tutorials/statistics/Day5.hs
|
mit
| 108 | 0 | 6 | 17 | 31 | 20 | 11 | 4 | 1 |
{-# LANGUAGE GADTs #-}
module Handler.Fob
( fobs
) where
import Handler.Helpers
import Model
import View.Fob
fobs :: App Response
fobs = routeResource $ defaultActions {
resActionList = fobList
, resActionNew = fobNew
, resActionEdit = fobEdit
, resActionCreate = fobCreate
, resActionUpdate = fobUpdate
}
fobRes :: Resource Fob
fobRes = defaultResource {
resNewView = fobNewView
, resEditView = fobEditView
, resIndexUri = "/fobs"
}
fobList :: App Response
fobList = do
fobs <- runDB $ selectList [] [] :: App [Entity Fob]
ok $ toResponse $ fobListView fobs
fobNew :: App Response
fobNew = do
view <- getForm "fob" (fobForm Nothing)
ok $ toResponse $ fobNewView view
fobEdit :: Entity Fob -> App Response
fobEdit ent@(Entity key fob) = do
view <- getForm "fob" (fobForm (Just fob))
ok $ toResponse $ fobEditView ent view
fobCreate :: App Response
fobCreate = do
post <- runForm "fob" (fobForm Nothing)
handleCreate fobRes post
fobUpdate :: Entity Fob -> App Response
fobUpdate ent@(Entity key fob) = do
post <- runForm "fob" (fobForm (Just fob))
handleUpdate fobRes ent post
fobForm :: Monad m => Formlet Text m Fob
fobForm f = Fob
<$> "key" .: validate notEmpty (string (fobKey <$> f))
|
flipstone/glados
|
src/Handler/Fob.hs
|
mit
| 1,253 | 0 | 12 | 263 | 445 | 226 | 219 | 41 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import qualified SearchEngine as E
import Persister as P
main = do
state <- P.readFromFile
let newState = E.addRecord "TestTitle" ("http://my.test", E.Title) state
print newState
|
AlexanderTankov/Hahoo-Search-Engine
|
src/Main.hs
|
mit
| 222 | 1 | 12 | 37 | 62 | 32 | 30 | 7 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Description : All message type definitions.
module IHaskell.Types (
Message(..),
MessageHeader(..),
MessageType(..),
dupHeader,
Username,
Metadata(..),
replyType,
ExecutionState(..),
StreamType(..),
MimeType(..),
DisplayData(..),
EvaluationResult(..),
ExecuteReplyStatus(..),
KernelState(..),
LintStatus(..),
Width,
Height,
Display(..),
defaultKernelState,
extractPlain,
kernelOpts,
KernelOpt(..),
IHaskellDisplay(..),
IHaskellWidget(..),
Widget(..),
WidgetMsg(..),
WidgetMethod(..),
KernelSpec(..),
) where
import IHaskellPrelude
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as CBS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Aeson (Value, (.=), object)
import Data.Aeson.Types (emptyObject)
import qualified Data.ByteString.Char8 as Char
import Data.Function (on)
import Data.Serialize
import GHC.Generics
import IHaskell.IPython.Kernel
-- | A class for displayable Haskell types.
--
-- IHaskell's displaying of results behaves as if these two overlapping/undecidable instances also
-- existed:
--
-- > instance (Show a) => IHaskellDisplay a
-- > instance Show a where shows _ = id
class IHaskellDisplay a where
display :: a -> IO Display
-- | Display as an interactive widget.
class IHaskellDisplay a => IHaskellWidget a where
-- | Output target name for this widget. The actual input parameter should be ignored. By default
-- evaluate to "ipython.widget", which is used by IPython for its backbone widgets.
targetName :: a -> String
targetName _ = "ipython.widget"
-- | Get the uuid for comm associated with this widget. The widget is responsible for storing the
-- UUID during initialization.
getCommUUID :: a -> UUID
-- | Called when the comm is opened. Allows additional messages to be sent after comm open.
open :: a -- ^ Widget to open a comm port with.
-> (Value -> IO ()) -- ^ A function for sending messages.
-> IO ()
open _ _ = return ()
-- | Respond to a comm data message. Called when a message is recieved on the comm associated with
-- the widget.
comm :: a -- ^ Widget which is being communicated with.
-> Value -- ^ Data recieved from the frontend.
-> (Value -> IO ()) -- ^ Way to respond to the message.
-> IO ()
comm _ _ _ = return ()
-- | Called when a comm_close is recieved from the frontend.
close :: a -- ^ Widget to close comm port with.
-> Value -- ^ Data recieved from the frontend.
-> IO ()
close _ _ = return ()
data Widget = forall a. IHaskellWidget a => Widget a
deriving Typeable
instance IHaskellDisplay Widget where
display (Widget widget) = display widget
instance IHaskellWidget Widget where
targetName (Widget widget) = targetName widget
getCommUUID (Widget widget) = getCommUUID widget
open (Widget widget) = open widget
comm (Widget widget) = comm widget
close (Widget widget) = close widget
instance Show Widget where
show _ = "<Widget>"
instance Eq Widget where
(==) = (==) `on` getCommUUID
-- | Wrapper for ipython-kernel's DisplayData which allows sending multiple results from the same
-- expression.
data Display = Display [DisplayData]
| ManyDisplay [Display]
deriving (Show, Typeable, Generic)
instance Serialize Display
instance Monoid Display where
mempty = Display []
ManyDisplay a `mappend` ManyDisplay b = ManyDisplay (a ++ b)
ManyDisplay a `mappend` b = ManyDisplay (a ++ [b])
a `mappend` ManyDisplay b = ManyDisplay (a : b)
a `mappend` b = ManyDisplay [a, b]
-- | All state stored in the kernel between executions.
data KernelState =
KernelState
{ getExecutionCounter :: Int
, getLintStatus :: LintStatus -- Whether to use hlint, and what arguments to pass it.
, useSvg :: Bool
, useShowErrors :: Bool
, useShowTypes :: Bool
, usePager :: Bool
, openComms :: Map UUID Widget
, kernelDebug :: Bool
, supportLibrariesAvailable :: Bool
}
deriving Show
defaultKernelState :: KernelState
defaultKernelState = KernelState
{ getExecutionCounter = 1
, getLintStatus = LintOn
, useSvg = True
, useShowErrors = False
, useShowTypes = False
, usePager = True
, openComms = mempty
, kernelDebug = False
, supportLibrariesAvailable = True
}
-- | Kernel options to be set via `:set` and `:option`.
data KernelOpt =
KernelOpt
{ getOptionName :: [String] -- ^ Ways to set this option via `:option`
, getSetName :: [String] -- ^ Ways to set this option via `:set`
, getUpdateKernelState :: KernelState -> KernelState -- ^ Function to update the kernel
-- state.
}
kernelOpts :: [KernelOpt]
kernelOpts =
[ KernelOpt ["lint"] [] $ \state -> state { getLintStatus = LintOn }
, KernelOpt ["no-lint"] [] $ \state -> state { getLintStatus = LintOff }
, KernelOpt ["svg"] [] $ \state -> state { useSvg = True }
, KernelOpt ["no-svg"] [] $ \state -> state { useSvg = False }
, KernelOpt ["show-types"] ["+t"] $ \state -> state { useShowTypes = True }
, KernelOpt ["no-show-types"] ["-t"] $ \state -> state { useShowTypes = False }
, KernelOpt ["show-errors"] [] $ \state -> state { useShowErrors = True }
, KernelOpt ["no-show-errors"] [] $ \state -> state { useShowErrors = False }
, KernelOpt ["pager"] [] $ \state -> state { usePager = True }
, KernelOpt ["no-pager"] [] $ \state -> state { usePager = False }
]
-- | Current HLint status.
data LintStatus = LintOn
| LintOff
deriving (Eq, Show)
-- | Send JSON objects with specific formats
data WidgetMsg = Open Widget Value Value
|
-- ^ Cause the interpreter to open a new comm, and register the associated widget in
-- the kernelState. Also sends a Value with comm_open, and then sends an initial
-- state update Value.
Update Widget Value
|
-- ^ Cause the interpreter to send a comm_msg containing a state update for the
-- widget. Can be used to send fragments of state for update. Also updates the value
-- of widget stored in the kernelState
View Widget
|
-- ^ Cause the interpreter to send a comm_msg containing a display command for the
-- frontend.
Close Widget Value
|
-- ^ Cause the interpreter to close the comm associated with the widget. Also sends
-- data with comm_close.
Custom Widget Value
|
-- ^ A [method .= custom, content = value] message
JSONValue Widget Value
|
-- ^ A json object that is sent to the widget without modifications.
DispMsg Widget Display
|
-- ^ A 'display_data' message, sent as a [method .= custom] comm_msg
ClrOutput Widget Bool
-- ^ A 'clear_output' message, sent as a [method .= custom] comm_msg
deriving (Show, Typeable)
data WidgetMethod = UpdateState Value
| CustomContent Value
| DisplayWidget
instance ToJSON WidgetMethod where
toJSON DisplayWidget = object ["method" .= "display"]
toJSON (UpdateState v) = object ["method" .= "update", "state" .= v]
toJSON (CustomContent v) = object ["method" .= "custom", "content" .= v]
-- | Output of evaluation.
data EvaluationResult =
-- | An intermediate result which communicates what has been printed thus
-- far.
IntermediateResult
{ outputs :: Display -- ^ Display outputs.
}
|
FinalResult
{ outputs :: Display -- ^ Display outputs.
, pagerOut :: [DisplayData] -- ^ Mimebundles to display in the IPython
-- pager.
, commMsgs :: [WidgetMsg] -- ^ Comm operations
}
deriving Show
-- | Duplicate a message header, giving it a new UUID and message type.
dupHeader :: MessageHeader -> MessageType -> IO MessageHeader
dupHeader header messageType = do
uuid <- liftIO random
return header { messageId = uuid, msgType = messageType }
|
wyager/IHaskell
|
src/IHaskell/Types.hs
|
mit
| 8,976 | 0 | 13 | 2,684 | 1,674 | 990 | 684 | 161 | 1 |
module Threase.BoardSpec (spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Threase.Board
import Threase.Direction (Direction (..))
import Threase.Tile (Tile (..))
import Threase.Vector (Vector (..))
spec :: Spec
spec = do
describe "canMove" $ do
it "" $ do
let n = Nothing
t = Just (Tile 1)
b = Board [Vector [n, n] , Vector [n, t]]
(b `canMove` West) `shouldBe` True
(b `canMove` South) `shouldBe` False
(b `canMove` East) `shouldBe` False
(b `canMove` North) `shouldBe` True
describe "canShift" $ do
it "returns False for an empty board" $ do
let t = Nothing
v = Vector (replicate 4 t)
b = Board (replicate 4 v)
canShift b `shouldBe` False
it "returns False if none of the vectors can be shifted" $ do
let n = Nothing
t = Just (Tile 1)
v = Vector [t, n, n, n]
b = Board (replicate 4 v)
canShift b `shouldBe` False
it "returns True if any of the vectors can be shifted" $ do
let n = Nothing
t = Just (Tile 1)
v = Vector [t, n, n, n]
v' = Vector [n, t, n, n]
b = Board [v, v, v, v']
canShift b `shouldBe` True
describe "isOver" $ do
it "returns True for an empty board" $ do
let t = Nothing
v = Vector (replicate 4 t)
b = Board (replicate 4 v)
isOver b `shouldBe` True
it "returns True if none of the rotations can be shifted" $ do
let t = Just (Tile 1)
v = Vector (replicate 4 t)
b = Board (replicate 4 v)
isOver b `shouldBe` True
it "returns False if any of the vectors can be shifted" $ do
let n = Nothing
t = Just (Tile 1)
v = Vector [t, n, n, n]
b = Board (replicate 4 v)
isOver b `shouldBe` False
describe "move" $ do
it "returns the moved board" $ do
let n = Nothing
t = Just (Tile 1)
v = Vector [t, n, n, n]
b = Board (replicate 4 v)
v' = Vector [n, t, n, n]
b' = Board (replicate 4 v')
move b East `shouldBe` b'
describe "render" $ do
it "returns the rendered vectors joined by newlines" $ do
let n = Nothing
t = Just (Tile 1)
b = Board [Vector [n, n], Vector [n, t]]
render b `shouldBe` "-\t-\n-\t1\n"
describe "rotate" $ do
it "returns the board rotated clockwise" $ do
let n = Nothing
t = Just (Tile 1)
b = Board [Vector [n, n], Vector [n, t]]
b' = Board [Vector [n, n], Vector [t, n]]
rotate b `shouldBe` b'
describe "rotateTo" $ do
it "returns the rotated board" $ do
let n = Nothing
t = Just (Tile 1)
b = Board [Vector [n, n], Vector [n, t]]
b' = Board [Vector [t, n], Vector [n, n]]
(b `rotateTo` East) `shouldBe` b'
describe "rotations" $ do
it "returns the rotations in clockwise order" $ do
let n = Nothing
t = Just (Tile 1)
b = Board [Vector [n, n], Vector [n, t]]
rotations b `shouldBe`
[ Board [Vector [n, n], Vector [n, t]]
, Board [Vector [n, n], Vector [t, n]]
, Board [Vector [t, n], Vector [n, n]]
, Board [Vector [n, t], Vector [n, n]]
]
prop "returns 4 boards" $
\ n -> length (rotations (Board [Vector [Just (Tile n)]])) == 4
describe "score" $ do
it "returns 0 for an empty board" $ do
let t = Nothing
v = Vector (replicate 4 t)
b = Board (replicate 4 v)
score b `shouldBe` 0
it "returns the sum of the scores of the vectors" $ do
let t = Just (Tile 3)
v = Vector (replicate 4 t)
b = Board (replicate 4 v)
score b `shouldBe` 48
describe "shift" $ do
it "returns itself for an empty board" $ do
let t = Nothing
v = Vector (replicate 4 t)
b = Board (replicate 4 v)
shift b `shouldBe` b
it "returns a board with all the vectors shifted" $ do
let n = Nothing
t = Just (Tile 3)
b = Board
[ Vector [n, n, n, n]
, Vector [t, n, n, n]
, Vector [n, n, n, t]
, Vector [t, t, t, t]
]
t' = Just (Tile 6)
b' = Board
[ Vector [n, n, n, n]
, Vector [t, n, n, n]
, Vector [n, n, t, n]
, Vector [t', t, t, n]
]
shift b `shouldBe` b'
describe "shiftWith" $ do
it "does nothing if the board can't be shifted" $ do
let t = Just (Tile 1)
v = Vector (replicate 4 t)
b = Board (replicate 4 v)
shiftWith b (Tile 1) 0 `shouldBe` b
it "inserts the new tile" $ do
let n = Nothing
t = Just (Tile 1)
t' = Tile 2
v = Vector [n, t, n, n]
b = Board (replicate 4 v)
b' = Board
[ Vector [t, n, n, Just t']
, Vector [t, n, n, n]
, Vector [t, n, n, n]
, Vector [t, n, n, n]
]
shiftWith b t' 0 `shouldBe` b'
|
tfausak/threase
|
test-suite/Threase/BoardSpec.hs
|
mit
| 5,975 | 0 | 23 | 2,807 | 2,135 | 1,109 | 1,026 | 145 | 1 |
-- Testing the theorem prover
module Main where
import Test.HUnit hiding (State)
import Test.QuickCheck
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (empty)
import qualified Data.Map as Map
--import Control.Monad.State
import Control.Monad
import TP
import System.Exit
import Parser (parseSequent)
import DataTypes
-- Test stuff
-- |Tries to prove a linear sequent (i.e. identities must be of the form a => a),
-- returns True if proven, False otherwise
-- we use this as a sort of golden standard given that it's much cleaner than the version with curry-howard
-- prove :: Sequent -> Bool
-- prove s@(gamma,f) = any (==True) proofs where
-- proofs = left ++ right
-- right = [r s | r <- [implicationRight, monadRight]]
-- left = [r g (delete g gamma,f) | g <- gamma, r <- [identity,implicationLeft,monadLeft]]
-- identity :: Formula -> Sequent -> Bool
-- identity a ([],a') = a == a'
-- identity _ _ = False
-- implicationLeft :: Formula -> Sequent -> Bool
-- implicationLeft (a :->: b) (gamma,c) = any (==True) proofs where
-- proofs = do
-- (g,g') <- split gamma
-- return $ (prove (g,a)) && (prove (b : g',c))
-- implicationLeft _ _ = False
-- monadLeft :: Formula -> Sequent -> Bool
-- monadLeft (M a) (gamma,M b) = prove (a : gamma, M b)
-- monadLeft _ _ = False
-- implicationRight :: Sequent -> Bool
-- implicationRight (gamma,a :->: b) = prove (a : gamma,b)
-- implicationRight _ = False
-- monadRight :: Sequent -> Bool
-- monadRight (gamma,M a) = prove (gamma,a)
-- monadRight _ = False
a = Atom "a" (TAtomic "a")
b = Atom "b" (TAtomic "b")
c = Atom "c" (TAtomic "c")
(.->.) :: Formula -> Formula -> Formula
f .->. g = I f g $ TFunctional (getType f) (getType g)
infixr 7 .->.
(.*.) :: Formula -> Formula -> Formula
a .*. b = P a b $ TPair (getType a) (getType b)
mon :: Formula -> Formula
mon f = M f $ TMonadic $ getType f
atom :: String -> Formula
atom s = Atom s (TAtomic s)
var :: String -> String -> Formula
var x t = Var x (TAtomic t)
-- |Given a pool of atomic formulae and a maximum depth generates all possible formulae
generateFormulae :: [Formula] -> Int -> Set Formula
generateFormulae [] _ = Set.empty
generateFormulae l 0 = Set.fromList l
generateFormulae l n = Set.fromList new where
new = monadic ++ functional ++ lower
monadic = [mon f | f <- lower]
functional = [f .->. g | f <- lower , g <- lower]
lower = Set.toList $ generateFormulae l (n-1)
maxDepth :: Formula -> Int
maxDepth (Atom _ _) = 0
maxDepth (Var _ _) = 0
maxDepth (M f _) = 1 + (maxDepth f)
maxDepth (I f g _) = 1 + (max (maxDepth f) (maxDepth g))
maxDepth (P a b _) = 1 + (max (maxDepth a) (maxDepth b))
-- |This function is used for test, it reduces the information about proofs
-- to a boolean answer
compress :: [a] -> Bool
compress [] = False
compress _ = True
broofs s = do
ds <- toDecorated s
proofs ds
kompress ps = compress (evaluateState ps startState)
-- HUnit
tests = TestList [ testGenerateFormualae
, testMaxDepth
-- , testProve
, testSplit
, testProofs
, testSub
, testCollectVars
, testAlphaEquivalent
, testEtaReduce
, testBetaReduce
, testMonadReduce
, testEquivalentDecoratedSequent
, testMixMap
, testParsers ]
testGenerateFormualae = "generateFormulae" ~: TestList
[ generateFormulae [] 0 ~?= Set.empty
, generateFormulae [a] 0 ~?= Set.fromList [a]
, generateFormulae [a,b] 0 ~?= Set.fromList [a,b]
, generateFormulae [a] 1 ~?= Set.fromList [a, mon a, a .->. a]
, generateFormulae [a,b] 1 ~?= Set.fromList [a,b,mon a,mon b, a .->. a, a .->. b, b .->. b, b .->. a]]
testMaxDepth = "maxDepth" ~: TestList
[ maxDepth a ~?= 0
, maxDepth (mon a) ~?= 1
, maxDepth (a .->. (b .->. c)) ~?= 2
, all (\x -> maxDepth x <= 3) (Set.toList $ generateFormulae [a] 3) ~?= True]
-- testProve = "prove" ~: TestList
-- [ prove ([a],a) ~?= True
-- , prove ([a],b) ~?= False
-- , prove ([a :->: b, a],b) ~?= True
-- , prove ([a :->: c, b],c) ~?= False
-- , prove ([a :->: b, b],b) ~?= False
-- , prove ([a :->: b, a],b) ~?= True
-- , prove ([a :->: b], (M a) :->: (M b)) ~?= True ]
testSplit = "split" ~: TestList
[ split ([] :: Context) ~?= [([],[])]
, Set.fromList (split [a]) ~?= Set.fromList ([([],[a]),([a],[])])
, Set.fromList (split [a,b]) ~?= Set.fromList ([([],[a,b])
,([a],[b])
,([b],[a])
,([a,b],[])])]
testProofs = "proofs" ~: TestList
[ kompress (broofs ([a],a)) ~?= True
, kompress (broofs ([a],b)) ~?= False
, kompress (broofs ([a .->. b, a],b)) ~?= True
, kompress (broofs ([a .->. c, b],c)) ~?= False
, kompress (broofs ([a .->. b, b],b)) ~?= False
, kompress (broofs ([a .->. b, a],b)) ~?= True
, kompress (broofs ([a,b],a .*. b)) ~?= True
, kompress (broofs ([a .->. b, a, c], b .*. c)) ~?= True
, kompress (broofs ([a .->. b, a], a .*. b)) ~?= False
, kompress (broofs ([a .->. b], (mon a) .->. (mon b))) ~?= True
, kompress (broofs ([mon a .->. b], a .->. b)) ~?= True
, kompress (broofs ([mon (a .->. b)], mon a .->. mon b)) ~?= True
-- theorems from the papers
, kompress (broofs ([a, (mon b) .->. a .->. c, mon b], c)) ~?= True
, kompress (broofs ([a, (mon b) .->. a .->. c, (b .->. c) .->. c], c)) ~?= True
, kompress (broofs ([var "X" "x"],var "X" "x")) ~?= True
, kompress (broofs ([a],var "X" "a")) ~?= True
, kompress (broofs ([var "X" "b" .->. a,b],a)) ~?= True
, kompress (broofs ([a .->. b .->. c, (a .->. (var "X" "c")) .->. (var "X" "c"), (b .->. (var "Y" "c")) .->. (var "Y" "c")],c)) ~?= True ]
testSub = "sub" ~: TestList
[ sub (V 1) (V 2) (V 3) ~?= V 3
, sub (V 1) (V 2) (V 2) ~?= V 1
, sub (V 1) (V 2) (Lambda (V 3) (V 2)) ~?= (Lambda (V 3) (V 1))
, sub (V 1) (V 2) (Lambda (V 2) (V 2)) ~?= (Lambda (V 2) (V 2))
, sub (V 1) (V 2) (App (Lambda (V 2) (V 2)) (Lambda (V 3) (V 2))) ~?= (App (Lambda (V 2) (V 2)) (Lambda (V 3) (V 1)))]
testCollectVars = "collectVars" ~: TestList
[ collectVars (Branch ImpL (Leaf Id ([DF {identifier = -3, term = V (-11), formula = atom "a"}],DF {identifier = -7, term = V (-11), formula = atom "a"})) ([DF {identifier = -1, term = V (-13), formula = atom "a" .->. atom "b"},DF {identifier = -3, term = V (-11), formula = atom "a"}],DF {identifier = -5, term = App (V (-13)) (V (-11)), formula = atom "b"}) (Leaf Id ([DF {identifier = -8, term = V (-12), formula = atom "b"}],DF {identifier = -5, term = V (-12), formula = atom "b"}))) ~?= Set.fromList [V (-11), V (-13), V (-12)]]
testAlphaEquivalent = "alphaEquivalent" ~: TestList
[ alphaEquivalent (V 1) (V 2) m ~?= False
, alphaEquivalent (V 1) (V 1) m ~?= True
, alphaEquivalent (C "a") (C "a") m ~?= True
, alphaEquivalent (C "a") (C "b") m ~?= False
, alphaEquivalent (Lambda (V 1) (V 1)) (Lambda (V 2) (V 2)) m ~?= True
, alphaEquivalent (Lambda (V 1) (V 2)) (Lambda (V 1) (V 1)) m ~?= False
, alphaEquivalent (App (Lambda (V 1) (V 1)) (V 3)) (App (Lambda (V 2) (V 2)) (V 3)) m ~?= True
, alphaEquivalent (Eta (V 1)) (Eta (V 1)) m ~?= True
, alphaEquivalent ((V 1) :*: (Lambda (V 1) (V 2))) ((V 1) :*: (Lambda (V 1) (V 2))) m ~?= True
, alphaEquivalent (Lambda (V 1) (V 1)) (Lambda (V 2) (V 1)) m ~?= False] where
m = empty
testEtaReduce = "etaReduce" ~: TestList
[ etaReduce (Lambda (V 1) (App (V 2) (V 1))) ~?= (V 2)
, etaReduce (V 1) ~?= (V 1)
, etaReduce (App (V 2) (V 1)) ~?= (App (V 2) (V 1))
, etaReduce (Lambda (V 1) (App (Lambda (V 2) (App (V 3) (V 2))) (V 1))) ~?= (V 3) ]
testBetaReduce = "betaReduce" ~: TestList
[ betaReduce (V 1) ~?= (V 1)
, betaReduce (Lambda (V 1) (V 1)) ~?= (Lambda (V 1) (V 1))
, betaReduce (App (Lambda (V 1) (V 1)) (V 2)) ~?= (V 2)
, betaReduce (App (Lambda (V 1) (V 2)) (V 3)) ~?= (V 2)
, betaReduce (App (Lambda (V 1) (Pair (V 1) (V 1))) (V 2)) ~?= (Pair (V 2) (V 2))
, betaReduce (App (Lambda (V 1) (Pair (V 1) (V 3))) (V 2)) ~?= (Pair (V 2) (V 3))
, betaReduce (App (Lambda (V 1) ((V 1) :*: (V 3))) (V 2)) ~?= ((V 2) :*: (V 3))
, betaReduce (App (Lambda (V 1) (Eta (V 1))) (V 2)) ~?= (Eta (V 2))
, betaReduce (App (Lambda (V 1) (FirstProjection (V 1))) (V 2)) ~?= (FirstProjection (V 2))
, betaReduce (App (Lambda (V 1) (SecondProjection (V 1))) (V 2)) ~?= (SecondProjection (V 2)) ]
testMonadReduce = "monadReduce" ~: TestList
[ monadReduce ((Eta (V 1)) :*: (V 2)) ~?= (App (V 2) (V 1))
, monadReduce ((V 1) :*: (Lambda (V 2) (Eta (V 2)))) ~?= (V 1)
, monadReduce ((V 1) :*: (Lambda (V 2) (Eta (V 3)))) ~?= ((V 1) :*: (Lambda (V 2) (Eta (V 3)))) ]
testEquivalentDecoratedSequent = "equivalentDecoratedSequent" ~: TestList
[ equivalentDecoratedSequent ([] , DF 1 (V 1) a)
([] , DF 1 (V 1) a) ~?= True
, equivalentDecoratedSequent ([] , DF 1 (V 1) a)
([] , DF 2 (V 1) a) ~?= True
, equivalentDecoratedSequent ([] , DF 1 (V 2) a)
([] , DF 1 (V 1) a) ~?= False
, equivalentDecoratedSequent ([] , DF 1 (V 1) b)
([] , DF 1 (V 1) a) ~?= False
, equivalentDecoratedSequent ([DF 1 (V 1) a], DF 2 (V 1) a)
([DF 1 (V 2) a], DF 2 (V 2) a) ~?= True
, equivalentDecoratedSequent ([DF 1 (V 1) a, DF 2 (V 2) b], DF 2 (V 1) a)
([DF 1 (V 2) a, DF 2 (V 3) b], DF 2 (V 2) a) ~?= True ]
testMixMap = "mixMaps" ~: TestList
[ mixMaps empty empty ~?= empty
, mixMaps (Map.fromList [(a,1)]) (Map.fromList [(a,2)]) ~?= Map.fromList [(1,2)]
, mixMaps (Map.fromList [(a,1),(b,2)]) (Map.fromList [(a,3),(b,2)]) ~?= Map.fromList [(1,3),(2,2)] ]
testParsers = "Parsers" ~: TestList
[ read "a.a" ~?= atom "a"
, read "A.a" ~?= var "A" "a"
, read " A123 . a" ~?= var "A123" "a"
, read " abc123 .abc123 " ~?= atom "abc123"
, read "<>a.a" ~?= mon (atom "a")
, read "a.a -> b.b" ~?= (atom "a") .->. (atom "b")
, read "a.a -> b.b -> c.c" ~?= (atom "a") .->. ((atom "b") .->. (atom "c"))
, read "a.a * b.b * c.c" ~?= (atom "a") .*. ((atom "b") .*. (atom "c"))
, read "(a.a)" ~?= atom "a"
, read "<> (a.a)" ~?= mon (atom "a")
, read "(<> a.a)" ~?= mon (atom "a")
, read "(a.a -> b.b) -> c.c" ~?= ((atom "a") .->. (atom "b")) .->. (atom "c")
, read "(<> a.a -> b.b) -> <> c.c" ~?= ((mon $ atom "a") .->. (atom "b")) .->. (mon $ atom "c")
, read "<><><>a.a -> b.b" ~?= (mon $ mon $ mon $ atom "a") .->. (atom "b")
, read "<><><>(a.a -> b.b)" ~?= (mon $ mon $ mon $ (atom "a") .->. (atom "b"))
, parseSequent "a.a -> b.b , c.c , a.a => a.a" ~?= Right (Left (([a .->. b, c , a],a) :: Sequent))
, parseSequent "f : a.a -> b.b, x : a.a => b.b" ~?= Right (Right ([(C "f", a .->. b) , (C "x", a)],b)) ]
testMonadicTP = runTestTT tests
-- QuickCheck
randFormula = sized aux where
aux 0 = liftM atom (elements ["a","b","c","d"])
aux n = oneof [ liftM atom (elements ["a","b","c","d"])
, liftM mon subformula1
, liftM2 (.->.) subformula2 subformula2] where
subformula1 = aux (n `div` 2)
subformula2 = aux (n `div` 2)
instance Arbitrary Formula where
arbitrary = randFormula
-- quickTest = quickCheck (\s -> kompress (broofs s) == prove s)
main = do
counts <- testMonadicTP
if errors counts == 0 && failures counts == 0 then exitSuccess else exitFailure
|
gianlucagiorgolo/glue-tp
|
TestTP.hs
|
mit
| 11,719 | 0 | 20 | 3,114 | 5,518 | 2,916 | 2,602 | 185 | 2 |
{-# OPTIONS_GHC -O2 -Wall -fwarn-tabs -Werror #-}
-------------------------------------------------------------------------------
-- |
-- Module : Lorenz.SDL
-- Copyright : Copyright (c) 2014 Michael R. Shannon
-- License : MIT
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : portable
--
-- SDL Specific code.
-------------------------------------------------------------------------------
module Lorenz.SDL
( initilizeSDL
) where
import Lorenz.Data
import Lorenz.Logic
import Lorenz.OpenGL(reshape)
import Control.Monad
import Graphics.UI.SDL
import Data.Version(showVersion)
import Paths_lorenz(version)
-- | OpenGL attributes to apply to window.
glAttributes :: [(GLAttr, GLValue)]
glAttributes =
[ (glRedSize , 8) -- 8 bit red buffer.
, (glGreenSize , 8) -- 8 bit green buffer.
, (glBlueSize , 8) -- 8 bit blue buffer.
, (glAlphaSize , 8) -- 8 bit alpha buffer.
, (glDepthSize , 24) -- 24 bit depth buffer.
, (glDoubleBuffer , 1) -- Use double buffers.
, (glMultiSampleSamples , 8)
]
-- | Apply a list of tuples of OpenGL attributes.
glApplyAttributes :: [(GLAttr, GLValue)] -> IO ()
glApplyAttributes atts = forM_ atts $ uncurry glSetAttribute
-- TODO: There is a small bug that will cause the projection to be off until a
-- resize on tiling window managers. This is not a problem on floating
-- window managers.
-- | Initilize SDL and open a window with an OpenGL context.
initilizeSDL :: (App -> IO ()) -> App -> IO ()
initilizeSDL nextAction app@(App { appWindow = appWin}) =
withInit [InitEverything] $ do
-- Set OpenGL attributes and create a window.
glApplyAttributes glAttributes
reshape screenWidth screenHeight
-- _ <- setVideoMode screenWidth screenHeight screenBpp [OpenGL, Resizable]
setCaption ("Lorenz (v" ++ showVersion version ++ ")") "Lorenz"
let (t, v) = solveLorenz (appFunction app)
-- Run the next action.
nextAction (app { appData = Just (AppData t v) })
where
AppWindow screenWidth screenHeight = appWin
|
mrshannon/lorenz
|
src/Lorenz/SDL.hs
|
mit
| 2,233 | 0 | 14 | 550 | 377 | 220 | 157 | 30 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Yesod.Auth.Autotool.Type
(module Yesod.Auth.Autotool.Type,
module Yesod.Auth.Autotool.Message
) where
import Yesod.Auth.Autotool.Message
import Yesod.Auth
import Yesod.Core
import Control.Monad
import Data.Int
import Data.Maybe
import System.IO
import Control.Student.Type
import qualified Control.Schule.Typ as Schule
import Control.Types
class YesodAuth site => YesodAuthAutotool site where
type AuthSchool
type AuthStudent
getStudentByMNr :: MonadIO (a site IO) =>
UNr -> MNr -> a site IO [Student]
getStudentByAuthStudent ::
(Monad (a site IO), MonadIO (a site IO)) =>
AuthSchool -> AuthStudent -> a site IO [Student]
getSchools :: (Monad (a site IO), MonadIO (a site IO)) =>
a site IO [Schule.Schule]
getSchool :: (Monad (a site IO), MonadIO (a site IO)) =>
Maybe AuthSchool -> a site IO (Maybe Schule.Schule)
toSchool :: (Monad (a site IO), MonadIO (a site IO)) =>
Int -> a site IO (Maybe Schule.Schule)
studentToAuthStudent :: Monad (a site IO) => Student -> a site IO AuthStudent
schoolToAuthSchool :: Monad (a site IO) => Schule.Schule -> a site IO AuthSchool
signinR :: AuthRoute
signinR = PluginR "autotool" ["login"]
signinSchoolR :: PathPiece AuthSchool => AuthSchool -> AuthRoute
signinSchoolR u = PluginR "autotool" ["login", toPathPiece u]
loginR :: PathPiece AuthSchool => Maybe AuthSchool -> AuthRoute
loginR u = case u of
Nothing -> signinR
Just u' -> signinSchoolR u'
createAccountR :: AuthRoute
createAccountR = PluginR "autotool" ["create"]
createAccountSchoolR :: PathPiece AuthSchool => AuthSchool -> AuthRoute
createAccountSchoolR u = PluginR "autotool" ["create", toPathPiece u]
resetPasswordR ::
(PathPiece AuthSchool, PathPiece AuthStudent) =>
AuthSchool -> AuthStudent -> AuthRoute
resetPasswordR u m = PluginR "autotool" ["reset", toPathPiece u, toPathPiece m]
{-
modifyR :: AuthSchool -> AuthRoute
modifyR unr = PluginR "autotool" ["modify", toText unr]
-}
|
marcellussiegburg/autotool
|
yesod/Yesod/Auth/Autotool/Type.hs
|
gpl-2.0
| 2,215 | 0 | 12 | 465 | 646 | 343 | 303 | 49 | 2 |
import Data.List
import Data.Ord (comparing)
import Numeric.LinearAlgebra.Algorithms
length' [] = 0
length' (xh:xt) = length' xt + 1
join' [] y = y
join' (xh:xt) y = xh:(join' xt y)
head' (xh:xt) = xh
tail' (xh:xt) = xt
last' (xh:[]) = xh
last' (xh:xt) = last' xt
map' _ [] = []
map' f (xh:xt) = f xh : (map' f xt)
zip' f (xh:xt) (yh:yt) = (f xh yh) : (zip' f xt yt)
zip' _ _ _ = []
sum' [] = 0
sum' (xh:xt) = xh + (sum xt)
mean' x = (sum' x) / (fromIntegral $ length' x)
acc' x [] = x
acc' [] (yh:yt) = acc' [yh] yt
acc' x (yh:yt) = acc' (x ++ [last' x + yh]) yt
accumulate' = acc' []
transpose' :: [[a]]->[[a]]
transpose' ([]:_) = []
transpose' x = map head' x : transpose' (map tail' x)
dot' [] _ = 0
dot' _ [] = 0
dot' (uh:ut) (vh:vt) = uh*vh + (dot' ut vt)
rev' [] a = a
rev' (xh:xt) a = rev' xt (xh:a)
reverse' x = rev' x []
-- |Numerically stable mean
mean :: Floating a => [a] -> a
mean x = fst $ foldl' (\(!m, !n) x -> (m+(x-m)/(n+1),n+1)) (0,0) x
-- |Sample Covariance
cov :: (Floating a) => [a] -> [a] -> a
cov xs ys = sum (zipWith (*) (map f1 xs) (map f2 ys)) / (n-1)
where
n = fromIntegral $ length $ xs
m1 = mean xs
m2 = mean ys
f1 = \x -> (x - m1)
f2 = \x -> (x - m2)
covMatrix m = map (\x -> (map (cov x) (transpose m))) (transpose m)
|
rhennigan/code
|
haskell/pcdSimplification/src/test.hs
|
gpl-2.0
| 1,369 | 18 | 13 | 399 | 983 | 473 | 510 | -1 | -1 |
Store f :: s -> Store f s
|
hmemcpy/milewski-ctfp-pdf
|
src/content/3.7/code/haskell/snippet35.hs
|
gpl-3.0
| 25 | 0 | 6 | 7 | 21 | 9 | 12 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Text as T
import Data.Text.IO as TIO
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Util
modifytestContent file = do
filecontent <- TIO.readFile file
TIO.writeFile file (T.replace "- src//" "- Drone_src//" filecontent)
main :: IO()
main = do
test_yamls <- getDirectoryFilesIO "" ["test/test_*.yml"]
mapM_ modifytestContent test_yamls
|
JackTheEngineer/Drone
|
bld/Replacer.hs
|
gpl-3.0
| 472 | 0 | 10 | 70 | 125 | 65 | 60 | 14 | 1 |
module Sara.Ast.Types where
import Sara.Ast.Operators
import qualified Data.Map.Strict as Map
data Type
= Unit
| Boolean
| Integer
| Double
deriving (Eq, Ord, Show, Enum, Bounded)
types :: [Type]
types = enumFrom minBound
data TypedUnOp
= TypedUnOp UnaryOperator Type
deriving (Eq, Ord, Show)
typedUnOps :: Map.Map TypedUnOp Type
typedUnOps = Map.fromList [ (TypedUnOp UnaryPlus Sara.Ast.Types.Integer, Sara.Ast.Types.Integer)
, (TypedUnOp UnaryPlus Sara.Ast.Types.Double, Sara.Ast.Types.Double)
, (TypedUnOp UnaryMinus Sara.Ast.Types.Integer, Sara.Ast.Types.Integer)
, (TypedUnOp UnaryMinus Sara.Ast.Types.Double, Sara.Ast.Types.Double)
, (TypedUnOp BitwiseNot Sara.Ast.Types.Integer, Sara.Ast.Types.Integer)
, (TypedUnOp LogicalNot Sara.Ast.Types.Boolean, Sara.Ast.Types.Boolean)]
data TypedBinOp
= TypedBinOp BinaryOperator Type Type
deriving (Eq, Ord, Show)
typedBinOps :: Map.Map TypedBinOp Type
typedBinOps = Map.fromList $
map (\op -> (TypedBinOp op Sara.Ast.Types.Integer Sara.Ast.Types.Integer, Sara.Ast.Types.Integer)) intBinOps
++ map (\op -> (TypedBinOp op Sara.Ast.Types.Integer Sara.Ast.Types.Integer, Sara.Ast.Types.Integer)) intDoubleBinOps
++ map (\op -> (TypedBinOp op Sara.Ast.Types.Double Sara.Ast.Types.Double, Sara.Ast.Types.Double)) intDoubleBinOps
++ map (\op -> (TypedBinOp op Sara.Ast.Types.Integer Sara.Ast.Types.Integer, Sara.Ast.Types.Boolean)) relOps
++ map (\op -> (TypedBinOp op Sara.Ast.Types.Double Sara.Ast.Types.Double, Sara.Ast.Types.Boolean)) relOps
++ map (\op -> (TypedBinOp op Sara.Ast.Types.Boolean Sara.Ast.Types.Boolean, Sara.Ast.Types.Boolean)) boolOps
where intBinOps = [LeftShift, RightShift, BitwiseAnd, BitwiseXor, BitwiseOr]
intDoubleBinOps = [Times, DividedBy, Modulo, Plus, Minus, Assign]
relOps = [LessThan, AtMost, GreaterThan, AtLeast, EqualTo, NotEqualTo]
boolOps = [LogicalAnd, LogicalXor, LogicalOr, Implies, ImpliedBy, EquivalentTo, NotEquivalentTo, Assign]
|
Lykos/Sara
|
src/lib/Sara/Ast/Types.hs
|
gpl-3.0
| 2,182 | 0 | 16 | 459 | 653 | 394 | 259 | 36 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Handler.Rating where
import Import
import Data.Maybe (fromJust)
import Yesod.Auth (requireAuthId)
$(deriveJSON defaultOptions ''Rating)
getRatingR :: UserId -> Handler Value
getRatingR uId = do
user <- runDB $ get uId
case user of
Just _ -> do
ratings <- runDB $ selectList [ RatingReviewed ==. uId ] []
let ratingNums = map ratingRating . map entityVal $ ratings
let avgRating = if (length ratingNums) > 0 then (sum ratingNums) `div` (length ratingNums) else 0
return $ object [ "rating" .= avgRating, "num_ratings" .= (length ratingNums) ]
Nothing -> return $ object [ "rating" .= (0 :: Int), "num_ratings" .= (0 :: Int) ]
postAddRatingR :: Handler Value
postAddRatingR = do
logged_in <- requireAuthId
(PartialRating reviewed comments score) <- runInputPost $ PartialRating
<$> ((fromJust . fromPathPiece) <$> ireq textField "Reviewed")
<*> iopt textField "Comment"
<*> ireq intField "Rating"
prevRating <- runDB $ selectFirst [ RatingReviewed ==. reviewed, RatingReviewer ==. logged_in ] []
case prevRating of
Nothing -> do
rId <- runDB $ insert (Rating logged_in reviewed comments score)
return $ object [ "rating_id" .= rId ]
Just _ ->
return $ object [ "result" .= ("already reviewed" :: Text) ]
data PartialRating = PartialRating UserId (Maybe Text) Int
|
weshack/thelist
|
TheList/Handler/Rating.hs
|
gpl-3.0
| 1,443 | 0 | 18 | 338 | 474 | 238 | 236 | -1 | -1 |
module Estuary.Types.RenderState where
import Data.Time.Clock
import qualified Data.Map as Map
import Data.IntMap.Strict
import qualified Sound.Tidal.Context as Tidal
import qualified Sound.Punctual.PunctualW as Punctual
import qualified Sound.Punctual.WebGL as Punctual
import qualified Sound.Punctual.Resolution as Punctual
import Sound.MusicW.AudioContext
import Sound.MusicW.Node as MusicW
import GHCJS.DOM.Types (HTMLCanvasElement,HTMLDivElement)
import Data.Text (Text)
import Sound.Punctual.GL
import Data.Tempo
import Estuary.Types.Definition
import Estuary.Types.RenderInfo
import Estuary.Types.NoteEvent
import Estuary.Types.MovingAverage
import Estuary.Types.TextNotation
import qualified Estuary.Languages.CineCer0.CineCer0State as CineCer0
import qualified Estuary.Languages.CineCer0.Spec as CineCer0
import qualified Estuary.Languages.CineCer0.Parser as CineCer0
import qualified Sound.TimeNot.AST as TimeNot
import qualified Sound.Seis8s.Program as Seis8s
import qualified Estuary.Languages.Hydra.Render as Hydra
import Estuary.Languages.JSoLang
data RenderState = RenderState {
animationOn :: Bool,
animationFpsLimit :: Maybe NominalDiffTime,
wakeTimeAudio :: !Double,
wakeTimeSystem :: !UTCTime,
renderStart :: !UTCTime,
renderPeriod :: !NominalDiffTime,
renderEnd :: !UTCTime,
cachedDefs :: !DefinitionMap,
paramPatterns :: !(IntMap Tidal.ControlPattern),
noteEvents :: ![NoteEvent],
tidalEvents :: ![(UTCTime,Tidal.ValueMap)],
baseNotations :: !(IntMap TextNotation),
punctuals :: !(IntMap Punctual.PunctualW),
punctualWebGL :: Punctual.PunctualWebGL,
cineCer0Specs :: !(IntMap CineCer0.Spec),
cineCer0States :: !(IntMap CineCer0.CineCer0State),
timeNots :: IntMap TimeNot.Program,
seis8ses :: IntMap Seis8s.Program,
hydras :: IntMap Hydra.Hydra,
evaluationTimes :: IntMap UTCTime, -- this is probably temporary
renderTime :: !MovingAverage,
wakeTimeAnimation :: !UTCTime,
animationDelta :: !MovingAverage, -- time between frame starts, ie. 1/FPS
animationTime :: !MovingAverage, -- time between frame start and end of drawing operations
zoneRenderTimes :: !(IntMap MovingAverage),
zoneAnimationTimes :: !(IntMap MovingAverage),
info :: !RenderInfo,
glContext :: GLContext,
canvasElement :: HTMLCanvasElement,
hydraCanvas :: HTMLCanvasElement,
videoDivCache :: Maybe HTMLDivElement,
tempoCache :: Tempo,
jsoLangs :: Map.Map Text JSoLang,
valueMap :: Tidal.ValueMap
}
-- Map.mapKeys T.unpack -- Map Text a -> Map String a
-- fmap Tidal.toValue ... -- Map a Double -> Map a Value
initialRenderState :: MusicW.Node -> MusicW.Node -> HTMLCanvasElement -> GLContext -> HTMLCanvasElement -> UTCTime -> AudioTime -> IO RenderState
initialRenderState pIn pOut cvsElement glCtx hCanvas t0System t0Audio = do
pWebGL <- Punctual.newPunctualWebGL (Just pIn) (Just pOut) Punctual.HD 1.0 glCtx
return $ RenderState {
animationOn = False,
animationFpsLimit = Just 0.030,
wakeTimeSystem = t0System,
wakeTimeAudio = t0Audio,
renderStart = t0System,
renderPeriod = 0,
renderEnd = t0System,
cachedDefs = empty,
paramPatterns = empty,
noteEvents = [],
tidalEvents = [],
baseNotations = empty,
punctuals = empty,
punctualWebGL = pWebGL,
cineCer0Specs = empty,
cineCer0States = empty,
timeNots = empty,
seis8ses = empty,
hydras = empty,
evaluationTimes = empty,
renderTime = newAverage 20,
wakeTimeAnimation = t0System,
animationDelta = newAverage 20,
animationTime = newAverage 20,
zoneRenderTimes = empty,
zoneAnimationTimes = empty,
info = emptyRenderInfo,
glContext = glCtx,
canvasElement = cvsElement,
hydraCanvas = hCanvas,
videoDivCache = Nothing,
tempoCache = Tempo { freq = 0.5, time = t0System, count = 0 },
jsoLangs = Map.empty,
valueMap = Map.empty
}
|
d0kt0r0/estuary
|
client/src/Estuary/Types/RenderState.hs
|
gpl-3.0
| 3,877 | 0 | 12 | 635 | 890 | 550 | 340 | 139 | 1 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE UndecidableInstances #-}
module HLinear.Utility.Fraction
where
import HLinear.Utility.Prelude
import HFlint.FMPZ.FFI ( fmpz_divexact, fmpz_mul )
import qualified Data.Vector as V
import HLinear.Matrix.Definition ( Matrix(..) )
import qualified HLinear.Matrix.Basic as M
data Fraction n d = Fraction n d
deriving Show
instance ( NFData n, NFData d ) => NFData (Fraction n d) where
rnf (Fraction n d) = seq (rnf n) $ seq (rnf d) ()
class IsFraction a n d | a -> n d where
toFraction :: a -> Fraction n d
fromFraction :: Fraction n d -> a
fromNumerator :: n -> a
fromDenominator :: d -> a
instance
( IsFraction a n (NonZero d)
, EuclideanDomain d, MultiplicativeSemigroupRightAction d n )
=> IsFraction (Vector a) (Vector n) (NonZero d)
where
{-# NOINLINE[1] toFraction #-}
toFraction v
| V.null v = Fraction mempty one
| otherwise =
let den = foldr1 lcm ds
(ns,ds) = V.unzip $ (`fmap` v) $ \a ->
let Fraction n (NonZero d) = toFraction a
in (,d) $ n .* (den `quot` d)
in Fraction ns (NonZero den)
{-# INLINABLE fromFraction #-}
fromFraction (Fraction v d) = fmap (\a -> fromFraction $ Fraction a d) v
{-# INLINABLE fromNumerator #-}
fromNumerator = fmap fromNumerator
{-# INLINABLE fromDenominator #-}
fromDenominator = error "isFraction (Vector a): fromDenominator would require size"
instance IsFraction FMPQ FMPZ (NonZero FMPZ) where
{-# INLINABLE toFraction #-}
toFraction a = let (n,d) = toFMPZs a in Fraction n d
{-# INLINABLE fromFraction #-}
fromFraction (Fraction n (NonZero d)) = fromFMPZs n d
{-# INLINABLE fromNumerator #-}
fromNumerator n = fromFMPZs n one
{-# INLINABLE fromDenominator #-}
fromDenominator = fromFMPZs one . fromNonZero
{-# RULES
"toFraction/Vector FMPQ" toFraction = toFractionVectorFMPQ
#-}
{-# INLINABLE toFractionVectorFMPQ #-}
toFractionVectorFMPQ :: Vector FMPQ -> Fraction (Vector FMPZ) (NonZero FMPZ)
toFractionVectorFMPQ v
| V.null v = Fraction mempty one
| otherwise =
let den = foldr1 lcm ds
(ns,ds) = V.unzip $ fmap (normalize . toFMPZs) v
normalize (n, NonZero d) = (,d) $ unsafePerformIO $
withNewFMPZ_ $ \bptr ->
withFMPZ_ den $ \denptr ->
withFMPZ_ d $ \dptr ->
withFMPZ_ n $ \nptr -> do
fmpz_divexact bptr denptr dptr
fmpz_mul bptr bptr nptr
in Fraction ns (NonZero den)
|
martinra/hlinear
|
src/HLinear/Utility/Fraction.hs
|
gpl-3.0
| 2,621 | 0 | 20 | 659 | 802 | 418 | 384 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Monitoring.Projects.MetricDescriptors.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a single metric descriptor. This method does not require a
-- Workspace.
--
-- /See:/ <https://cloud.google.com/monitoring/api/ Cloud Monitoring API Reference> for @monitoring.projects.metricDescriptors.get@.
module Network.Google.Resource.Monitoring.Projects.MetricDescriptors.Get
(
-- * REST Resource
ProjectsMetricDescriptorsGetResource
-- * Creating a Request
, projectsMetricDescriptorsGet
, ProjectsMetricDescriptorsGet
-- * Request Lenses
, pmdgXgafv
, pmdgUploadProtocol
, pmdgAccessToken
, pmdgUploadType
, pmdgName
, pmdgCallback
) where
import Network.Google.Monitoring.Types
import Network.Google.Prelude
-- | A resource alias for @monitoring.projects.metricDescriptors.get@ method which the
-- 'ProjectsMetricDescriptorsGet' request conforms to.
type ProjectsMetricDescriptorsGetResource =
"v3" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] MetricDescriptor
-- | Gets a single metric descriptor. This method does not require a
-- Workspace.
--
-- /See:/ 'projectsMetricDescriptorsGet' smart constructor.
data ProjectsMetricDescriptorsGet =
ProjectsMetricDescriptorsGet'
{ _pmdgXgafv :: !(Maybe Xgafv)
, _pmdgUploadProtocol :: !(Maybe Text)
, _pmdgAccessToken :: !(Maybe Text)
, _pmdgUploadType :: !(Maybe Text)
, _pmdgName :: !Text
, _pmdgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsMetricDescriptorsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pmdgXgafv'
--
-- * 'pmdgUploadProtocol'
--
-- * 'pmdgAccessToken'
--
-- * 'pmdgUploadType'
--
-- * 'pmdgName'
--
-- * 'pmdgCallback'
projectsMetricDescriptorsGet
:: Text -- ^ 'pmdgName'
-> ProjectsMetricDescriptorsGet
projectsMetricDescriptorsGet pPmdgName_ =
ProjectsMetricDescriptorsGet'
{ _pmdgXgafv = Nothing
, _pmdgUploadProtocol = Nothing
, _pmdgAccessToken = Nothing
, _pmdgUploadType = Nothing
, _pmdgName = pPmdgName_
, _pmdgCallback = Nothing
}
-- | V1 error format.
pmdgXgafv :: Lens' ProjectsMetricDescriptorsGet (Maybe Xgafv)
pmdgXgafv
= lens _pmdgXgafv (\ s a -> s{_pmdgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pmdgUploadProtocol :: Lens' ProjectsMetricDescriptorsGet (Maybe Text)
pmdgUploadProtocol
= lens _pmdgUploadProtocol
(\ s a -> s{_pmdgUploadProtocol = a})
-- | OAuth access token.
pmdgAccessToken :: Lens' ProjectsMetricDescriptorsGet (Maybe Text)
pmdgAccessToken
= lens _pmdgAccessToken
(\ s a -> s{_pmdgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pmdgUploadType :: Lens' ProjectsMetricDescriptorsGet (Maybe Text)
pmdgUploadType
= lens _pmdgUploadType
(\ s a -> s{_pmdgUploadType = a})
-- | Required. The metric descriptor on which to execute the request. The
-- format is:
-- projects\/[PROJECT_ID_OR_NUMBER]\/metricDescriptors\/[METRIC_ID] An
-- example value of [METRIC_ID] is
-- \"compute.googleapis.com\/instance\/disk\/read_bytes_count\".
pmdgName :: Lens' ProjectsMetricDescriptorsGet Text
pmdgName = lens _pmdgName (\ s a -> s{_pmdgName = a})
-- | JSONP
pmdgCallback :: Lens' ProjectsMetricDescriptorsGet (Maybe Text)
pmdgCallback
= lens _pmdgCallback (\ s a -> s{_pmdgCallback = a})
instance GoogleRequest ProjectsMetricDescriptorsGet
where
type Rs ProjectsMetricDescriptorsGet =
MetricDescriptor
type Scopes ProjectsMetricDescriptorsGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring",
"https://www.googleapis.com/auth/monitoring.read",
"https://www.googleapis.com/auth/monitoring.write"]
requestClient ProjectsMetricDescriptorsGet'{..}
= go _pmdgName _pmdgXgafv _pmdgUploadProtocol
_pmdgAccessToken
_pmdgUploadType
_pmdgCallback
(Just AltJSON)
monitoringService
where go
= buildClient
(Proxy :: Proxy ProjectsMetricDescriptorsGetResource)
mempty
|
brendanhay/gogol
|
gogol-monitoring/gen/Network/Google/Resource/Monitoring/Projects/MetricDescriptors/Get.hs
|
mpl-2.0
| 5,346 | 0 | 15 | 1,150 | 710 | 418 | 292 | 106 | 1 |
module HEP.Jet.FastJet.Class.Error where
|
wavewave/HFastJet
|
oldsrc/HEP/Jet/FastJet/Class/Error.hs
|
lgpl-2.1
| 42 | 0 | 3 | 4 | 9 | 7 | 2 | 1 | 0 |
{-
Copyright (C) 2009 Andrejs Sisojevs <[email protected]>
All rights reserved.
For license and copyright information, see the file COPYRIGHT
-}
--------------------------------------------------------------------------
--------------------------------------------------------------------------
-- | This is a usual set for modules, that are to be imported by modules
-- dedicated to declaring 'ShowAsPCSI' and 'HasStaticRawPCLTs' instances
module Text.PCLT.SH__ (
module Text.PCLT.CatalogMaths
, module Text.PCLT.HasStaticRawPCLTs
, module Text.PCLT.ShowAsPCSI
, module Text.PCLT.PCSI
, module Text.PCLT.Template
, module Text.PCLT.SDL
) where
import Text.PCLT.CatalogMaths
import Text.PCLT.HasStaticRawPCLTs
import Text.PCLT.ShowAsPCSI
import Text.PCLT.PCSI
import Text.PCLT.Template
import Text.PCLT.SDL
|
Andrey-Sisoyev/haskell-PCLT
|
Text/PCLT/SH__.hs
|
lgpl-2.1
| 901 | 0 | 5 | 163 | 92 | 65 | 27 | 13 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Z where
------------------------------------------------------------------------------
import MakeClassy
------------------------------------------------------------------------------
import Control.Lens
import Control.Monad.Trans.RWS.Strict
import qualified Data.Map.Strict as Map
import Protolude hiding (get, gets, round, to)
------------------------------------------------------------------------------
newtype Author = Author { _aAuthor :: Text } deriving (Eq, Ord, Show)
newtype Epoch = Epoch { _eEpoch :: Int } deriving (Eq, Num, Ord, Show)
newtype HashValue = HashValue{ _hvHashValue :: ByteString } deriving (Eq, Ord, Show)
newtype Round = Round { _rRound :: Int } deriving (Eq, Num, Ord, Show)
data BlockInfo = BlockInfo
{ _biAuthor :: !Author
, _biEpoch :: !Epoch
, _biRound :: !Round
, _biId :: !HashValue
} deriving (Eq, Show)
data VoteData = VoteData
{ _vdProposed :: !BlockInfo
, _vdParent :: !BlockInfo
} deriving (Eq, Show)
data BlockTree a = BlockTree
{ _btVoteDataMap :: !(Map HashValue VoteData)
, _btRootId :: !HashValue
} deriving (Eq, Show)
data BlockStore a = BlockStore
{ _bsInner :: BlockTree a
, _bsStuff :: Text
} deriving (Eq, Show)
data Pacemaker = Pacemaker
{ _pHighestCommittedRound :: !Round
, _pCurrentRound :: !Round
} deriving (Eq, Show)
data Vote = Vote
{ _vVoteData :: !VoteData
, _vAuthor :: !Author
} deriving (Eq, Show)
data EventProcessor a = EventProcessor
{ _epAuthor :: !Author
, _epBlockStore :: !(BlockStore a)
, _epPacemaker :: !Pacemaker
, _epLastVoteSend :: !(Maybe (Vote, Round))
} deriving (Eq, Show)
obmMakeClassy ''Author
obmMakeClassy ''Epoch
obmMakeClassy ''HashValue
obmMakeClassy ''Round
obmMakeClassy ''EventProcessor
obmMakeClassy ''BlockStore
obmMakeClassy ''Pacemaker
obmMakeClassy ''BlockTree
instance RWBlockStore (EventProcessor a) a where
lBlockStore = lens _epBlockStore (\x y -> x { _epBlockStore = y})
instance RWBlockTree (EventProcessor a) a where
lBlockTree = lens (^.epBlockStore.bsInner) (\x y -> x & epBlockStore.bsInner .~ y)
instance RWPacemaker (EventProcessor a) where
lPacemaker = lens _epPacemaker (\x y -> x { _epPacemaker = y})
instance RWAuthor (EventProcessor a) where
lAuthor = lens _epAuthor (\x y -> x { _epAuthor = y})
------------------------------------------------------------------------------
-- EventProcessor
ep :: (RWAuthor s, RWPacemaker s, RWBlockStore s a, RWBlockTree s a)
=> RWS () [Text] s ()
ep = do
pm
author <- use lAuthor
bs author
------------------------------------------------------------------------------
-- Pacemaker
pm :: RWPacemaker s
=> RWS () [Text] s ()
pm = do
r <- use (lPacemaker.pHighestCommittedRound)
tell ["PM " <> show r]
------------------------------------------------------------------------------
-- BlockStore
bs :: (RWBlockStore s a, RWBlockTree s a)
=> Author -> RWS () [Text] s ()
bs author = do
s <- use (lBlockStore.bsStuff)
tell ["BS " <> show s]
bt author
------------------------------------------------------------------------------
-- BlockTree
bt :: (RWBlockTree s a)
=> Author -> RWS () [Text] s ()
bt author = do
vdm <- use (lBlockTree.btVoteDataMap)
let vd = Map.lookup (HashValue "junk") vdm
tell ["BT " <> show author <> " " <> show vd]
------------------------------------------------------------------------------
-- run
run :: EventProcessor a -> [Text]
run ep0 = let (_,_,t) = runRWS ep () ep0 in t
runEpT :: [Text]
runEpT = run epT
------------------------------------------------------------------------------
biT :: BlockInfo
biT = BlockInfo (Author "biauthor") (Epoch 0) (Round 0) (HashValue "0")
epT :: EventProcessor ByteString
epT = EventProcessor
(Author "epauthor")
(BlockStore (BlockTree Map.empty (HashValue "btrootid")) "bsstuff")
(Pacemaker (Round 100) (Round 101))
(Just ( Vote
(VoteData biT biT)
(Author "epauthor")
, Round 45))
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/topic/lens/hc-usage/src/Z.hs
|
unlicense
| 4,672 | 0 | 12 | 1,036 | 1,287 | 693 | 594 | -1 | -1 |
import Test.Framework
import Network.JsonRpc.Tests
main :: IO ()
main = defaultMain (tests)
|
anton-dessiatov/json-rpc
|
test/main.hs
|
unlicense
| 94 | 0 | 6 | 14 | 33 | 18 | 15 | 4 | 1 |
{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction #-}
module NeuralNetwork where
import Control.Arrow hiding (app)
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List
import Numeric.LinearAlgebra.HMatrix
import System.Random
import qualified Data.Vector.Storable as V
-- ActivationFunction wraps a function with its derivative, along with a name (for printing)
data ActivationFunction a = AF (a -> a) (a -> a) String
instance Show (ActivationFunction a) where show (AF _ _ n) = "ActivationFunction " ++ n
tanhAF = AF tanh (\x -> 1 - (tanh x)^2) "tanh"
logisticAF = AF f (\x -> f x * (1 - f x)) "logistic" where f x = (1 / (1 + exp (-x)))
data NeuralNetwork a = NN {
getWeightMatrices :: [Matrix a],
getActivationFunction :: ActivationFunction a
} deriving Show
applyNN :: Numeric a => NeuralNetwork a -> Vector a -> Vector a
applyNN (NN mats (AF theta _ _)) x = foldl' ((cmap theta .) . flip (app . tr) . V.cons 1) x mats
-- (forwardPropagate nn x) returns the values at all the intermediate layers, before and after the activation function is applied
forwardPropagate :: Numeric a => NeuralNetwork a -> Vector a -> ([Vector a], [Vector a])
forwardPropagate (NN mats (AF theta _ _)) x = first tail . unzip $ scanl aux (undefined, V.cons 1 x) mats where
aux (_,z) w = let v = app (tr w) z in (v, V.cons 1 (cmap theta v))
-- (backPropagate nn x y) returns all the errors (in the same shape as the weights) of applying nn to x, with target value y
backPropagate :: (Num (Vector a), Numeric a) => NeuralNetwork a -> Vector a -> Vector a -> [Matrix a]
backPropagate nn@(NN mats (AF theta theta' _)) x y = gradient where
deltaStep (ds, d) (v, w) = let d' = (cmap theta' v) * (V.tail $ app w d) in (d':ds, d')
(v:vs, zs) = first reverse $ forwardPropagate nn x
ws = reverse mats
dLast = 2 * (cmap theta v - y)
ds = fst $ foldl' deltaStep ([dLast], dLast) (zip vs ws)
gradient = zipWith outer zs ds
batchUpdate alpha nn@(NN oldWeights _) dataset = let
(gradient, size) = foldr (\(x, y) (gr, n) -> (zipWith (+) gr (backPropagate nn x y), n+1)) (cycle [scalar 0], 0) dataset
step = map (*scalar (alpha / size)) gradient
newWeights = zipWith (-) oldWeights step
in nn {getWeightMatrices = newWeights}
stochasticGradientDescent dataset alpha nn = foldl' (\nn' pt -> batchUpdate alpha nn' [pt]) nn dataset
initializeMatrix mkEntry (m, n) = runState (fmap (matrix m) $ replicateM (m*n) (state mkEntry))
randomlyWeightedNetwork seed dims af = NN (evalState (mapM mkMat (zip dims (tail dims))) (mkStdGen seed)) af where
mkMat (m, n) = state $ initializeMatrix (randomR (-1, 1)) (n,m+1)
|
aweinstock314/neural-networks
|
NeuralNetwork.hs
|
apache-2.0
| 2,671 | 0 | 15 | 523 | 1,132 | 599 | 533 | 39 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Templates.Topic where
import Data.Text.Encoding (decodeUtf8)
import Network.HTTP.Types.Method (methodGet, methodPost, methodPut, methodDelete)
import CourseStitch.Templates.Topic
import CourseStitch.Templates.Utils
import CourseStitch.Templates.Concept
topicForm :: Maybe (Entity Topic) -> Html ()
topicForm topic = do
form_ [action_ uri, method_ method] $ do
fieldset_ $ do
input "Title" "title" $ get topicTitle
textInput "Summary" "summary" $ get topicSummary
input_ [type_ "submit"]
script_ [src_ "/js/form-methods.js"] ("" :: String)
where get f = fmap (f . entityVal) topic
uri = case topic of
Just topic -> topicUri topic
Nothing -> "/topic"
method = case topic of
Just _ -> decodeUtf8 methodPut
Nothing -> decodeUtf8 methodPost
topicDetailed :: Entity Topic -> [Entity Concept] -> Html ()
topicDetailed topic concepts = do
topicLink topic $ topicHeading topic
topicText topic
topicConceptsHeading
case concepts of
[] -> topicConceptsMissing
concepts -> unorderedList $ map conceptSimple concepts
topicConceptsHeading = h2_ "Concepts"
topicConceptsMissing = p_ "This topic has no concepts"
|
coursestitch/coursestitch-api
|
src/Templates/Topic.hs
|
apache-2.0
| 1,327 | 0 | 14 | 337 | 363 | 179 | 184 | 32 | 3 |
{-# LANGUAGE FlexibleContexts, TypeOperators #-}
module Codec.FFMpeg.Format (
openInput,
seekFrame, readFrames
) where
import Control.Eff
import Control.Eff.Coroutine
import Control.Eff.Exception
import Control.Eff.Lift
import Control.Eff.Reader.Strict
import Control.Monad ( when )
import Data.Word ( Word64 )
import Foreign ( Ptr )
import Foreign.C.String ( withCString )
import Foreign.C.Types ( CInt(..) )
import Foreign.Marshal.Alloc ( alloca )
import Foreign.Marshal.Utils ( with )
import Foreign.Ptr ( castPtr, nullPtr )
import Foreign.Storable ( peek, poke )
import Codec.FFMpeg.Internal.Codec
import Codec.FFMpeg.Internal.Format
openInput :: (SetMember Lift (Lift IO) r, Member (Exc IOError) r) => String -> Eff (Reader AVFormatContext :> r) a -> Eff r a
openInput filename eff = do
eavctx <- lift $ alloca $ \ctx ->
withCString filename $ \cstr -> do
poke (castPtr ctx) nullPtr
r <- c_avformat_open_input ctx cstr nullPtr nullPtr
if (r /= 0)
then return $ Left $ "ffmpeg failed opening file: " ++ show r
else peek ctx >>= return . Right
case eavctx of
Left e -> throwExc $ userError e
Right avctx -> do
r <- runReader eff avctx
lift $ with avctx c_avformat_close_input
return r
seekFrame
:: (SetMember Lift (Lift IO) r, Member (Exc IOError) r, Member (Reader AVFormatContext) r)
=> Integer
-> Eff r ()
seekFrame ts = ask >>= \ctx -> lift (c_av_seek_frame ctx (-1) (fromIntegral ts) 0) >>=
\r -> when (r < 0) $ throwExc (userError $ "seek failed: " ++ show r)
readFrames
:: (SetMember Lift (Lift IO) r, Member (Reader AVFormatContext) r, Member (Yield AVPacket) r)
=> Eff r ()
readFrames = ask >>= \ctx -> do
p <- lift newAVPacket
r <- lift $ withAvPacket p (c_av_read_frame ctx)
if r == 0
then yield p >> readFrames
else return ()
-------------------------------------------------------------------------------
-- Imports
-------------------------------------------------------------------------------
foreign import ccall "av_seek_frame"
c_av_seek_frame :: AVFormatContext -> CInt -> Word64 -> CInt -> IO CInt
foreign import ccall "av_read_frame"
c_av_read_frame :: AVFormatContext -> Ptr AVPacket' -> IO CInt
|
waldheinz/ffmpeg-effects
|
src/Codec/FFMpeg/Format.hs
|
apache-2.0
| 2,350 | 0 | 17 | 542 | 747 | 393 | 354 | 54 | 3 |
module Main where
allEven :: [Integer] -> [Integer]
allEven [] = []
allEven (h:t) = if even h then h:allEven t else allEven t
allEven2 numbers = [n | n <- numbers, (even n)]
allEven3 numbers = filter even numbers
|
frankiesardo/seven-languages-in-seven-weeks
|
src/main/haskell/day1/allEven.hs
|
apache-2.0
| 234 | 0 | 8 | 61 | 109 | 57 | 52 | 6 | 2 |
{-# LANGUAGE BangPatterns #-}
-- |
-- Module : GRN.StateTransition
-- Copyright : (c) 2011 Jason Knight
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Handles the creation of a Karnaugh map or species pathway diagram from
-- ParseData. Also handles the simulation of the long run probabilities and
-- calcuation of the SSA Transform
--
module GRN.StateTransition where
import GRN.Parse
import GRN.Types
import GRN.Utils
import qualified Data.Vector as V
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import Data.Vector.Strategies
import Control.Parallel.Strategies
import System.Cmd
import Control.Monad
import Data.List
import Data.Bits
import Data.Ord (comparing)
import Data.Maybe
import qualified Data.Map as M
import Text.Printf
import System.Environment
import System.Console.ParseArgs
import Data.Graph.Analysis
import System.Random
import System.IO.Unsafe
fullIteration = {-# SCC "fullIteration" #-} iterateProbs2.iterateProbs
-- |Push from edges back to the nodes
iterateProbs2 :: ColoredStateGraph -> ColoredStateGraph
iterateProbs2 !sgraph = {-# SCC "iterate2" #-} gmap flowProbs sgraph
where
flowProbs (adj1, node, !(NodeInfo a oldprob), adj2)=
{-# SCC "flowProbs2" #-}(newIns, node, NodeInfo a newProb, newOuts)
where
newProb = {-# SCC "newProb" #-}
sum $ map (\(_,_,(EdgeInfo a _))->a) (inn sgraph node)
newOuts = {-# SCC "newOuts" #-} map (\((EdgeInfo _ w),e)->((EdgeInfo 0.0 w),e)) adj2
newIns = {-# SCC "newIns" #-} map (\((EdgeInfo _ w),e)->((EdgeInfo 0.0 w),e)) adj1
-- |Push to the edges from the nodes
iterateProbs :: ColoredStateGraph -> ColoredStateGraph
iterateProbs !sgraph = {-# SCC "iterate1" #-} gmap flowProbs sgraph
where
flowProbs (adj1, node, !(NodeInfo a oldprob), adj2) =
{-# SCC "flowProbs1" #-} (newIns, node, NodeInfo a 0, newOuts)
where
newOuts =
{-# SCC "newOuts1" #-} map (\((EdgeInfo _ w),n) ->((EdgeInfo (oldprob*w) w),n)) adj2
newIns = {-# SCC "newIns1" #-} map updateIns adj1
updateIns ((EdgeInfo _ w),n) = {-# SCC "updateIns1" #-}
let (_,_,(NodeInfo _ p),_) = context sgraph n
in ((EdgeInfo (p*w) w),n)
-- Take probabilities from oldg, and apply them to newg to allow for a change
-- in external conditions or something like that.
convertProbsGG :: ColoredStateGraph -> ColoredStateGraph -> ColoredStateGraph
convertProbsGG oldg blankg = gmap copyProb (emap (\(EdgeInfo _ w)->(EdgeInfo 0.0 w)) blankg)
where
copyProb (adj1, node, NodeInfo a y, adj2) = (adj1, node, NodeInfo a p, adj2)
where p = case (lab oldg node) of
Just (NodeInfo _ p) -> p
Nothing -> 0.0
convertProbsVG :: SSD -> ColoredStateGraph -> ColoredStateGraph
convertProbsVG ssd blankg = gmap copyProb (emap (\(EdgeInfo _ w)->(EdgeInfo 0.0 w)) blankg)
where
copyProb (adj1, node, NodeInfo a y, adj2) = (adj1, node, NodeInfo a p, adj2)
where p = ssd U.! node
convertProbsGV :: ColoredStateGraph -> SSD
convertProbsGV gr = U.fromList $ map (\(_,(NodeInfo _ p))->p) $ labNodes gr
buildKmaps :: ParseData -> KmapSet
buildKmaps = M.map buildKmap
buildKmap :: GeneInfo -> Kmap
buildKmap (GeneInfo n (Just val) _ _ _) = Kmap n [] (M.singleton [] (V 0 (valconv val)))
buildKmap (GeneInfo n _ _ [] []) = Kmap n [] (M.singleton [] Const)
buildKmap gi = Kmap (name gi) predictors (foldl updateMap initMap spways)
where
-- Sorted Pathways by ascending number of predictors
spways = sortBy (comparing (\(Pathway x _ _ _)->length x)) $ pathways gi
-- Sorted list of predictors
predictors = sort.depends $ gi
nump = length predictors
positions :: [[Int]]
positions = [[0],[1]] >>= foldr (<=<) return (replicate (nump-1) (\x->[x++[0],x++[1]]))
initMap = M.fromList $ zip positions (repeat X)
updateMap :: M.Map [Int] Kentry -> Pathway -> M.Map [Int] Kentry
updateMap k (Pathway up pre post _) = foldl (\k pos-> updateLoc k pos (valconv post) (length up)) k upposses
where upposses = foldl (filterPoses pre) positions up
updateLoc :: M.Map [Int] Kentry -> [Int] -> Double -> Int -> M.Map [Int] Kentry
updateLoc k loc val num = M.insert loc (updateRule (k M.! loc) (V num val) num) k
updateRule X val num = val
updateRule (C i) val num
| i < num = val
| i == num = C i
| otherwise = error "Should never reach another pathway with less than the conflict"
updateRule (V i d) val@(V ni nd) num
| i < num = val
| i == num = if d == nd then V i d else C i
| otherwise = error "Should never reach this pathway 2"
filterPoses :: Bool -> [[Int]] -> Gene -> [[Int]]
filterPoses val xs gene
| head gene == '!' = filterPoses (not val) xs (tail gene)
| otherwise = filter ((==(if val then 1 else 0)).(!!ind)) xs
where Just ind = elemIndex gene predictors
-- Boolean to Double
valconv :: Bool -> Double
valconv val = if val then 1 else 0
fuzzGraphEdges :: ParseData -> KmapSet-> (Int, ColoredStateGraph) -> (Int, ColoredStateGraph)
fuzzGraphEdges pdata ks (x,orig) = (newX, mkGraph permedNodeStates edges)
where
newX = if x>0 then x+1 else x -- 0 is the deterministic seed
permedStates = map ((dec2bin nGenes).fst) permedNodeStates
permedNodeStates = labNodes orig
nGenes = length genes
genes = M.keys pdata
edges = concatMap genEdges permedStates
genEdges :: [Int] -> [(Int,Int,EdgeInfo)]
genEdges st = map (\(val,to)-> (from,bin2dec to,EdgeInfo 0.0 val)) tos
where
from = bin2dec st
tos = [(1.0,[])] >>= foldr (>=>) return (stateKmapLus x st genes ks)
kmapToStateGraph :: KmapSet -> ColoredStateGraph
kmapToStateGraph kset = mkGraph permedNodeStates edges
where
genes = M.keys kset
nGenes = length genes
nStates = 2^nGenes
intStates = [0..nStates-1]
permedStates = map (dec2bin nGenes) intStates
stringStates = map (concatMap show) permedStates
permedNodeStates =
zip intStates (map (\x->NodeInfo x (1.0/(fromIntegral nStates))) stringStates)
edges = concatMap genEdges permedStates
genEdges :: [Int] -> [(Int,Int,EdgeInfo)]
genEdges st = map (\(val,to)-> (from,bin2dec to,EdgeInfo 0.0 val)) tos
where
from = bin2dec st
tos = [(1.0,[])] >>= foldr (>=>) return (stateKmapLus 0 st genes kset)
stateKmapLus :: Int -> [Int] -> [Gene] -> KmapSet -> [(Double,[Int]) -> [(Double,[Int])]]
stateKmapLus x st genes ks = map (evaluator.stateKmapLu x st genes) $ M.elems ks
stateKmapLu :: Int -> [Int] -> [Gene] -> Kmap -> Double
stateKmapLu x st genes (Kmap g gs k) = case M.lookup loc k of
Just X -> 0.5 --if x==0 then 0.5 else randUnsafe x
Just (C _) -> 0.5 --if x==0 then 0.5 else randUnsafe x
Just (V _ d) -> d
Just Const -> fromIntegral $ st !! thisInd
Nothing -> error ("Something wrong here " ++ show loc ++ show k ++ show inds ++ show gs ++ show genes)
where
loc = map (st!!) inds
inds = concatMap (flip elemIndices genes) gs
Just thisInd = elemIndex g genes
evaluator :: Double -> ((Double,[Int]) -> [(Double,[Int])])
evaluator val
| val == 1.0 = det1
| val == 0.0 = det0
| otherwise = rand
where rand (d,xs) = [(d*ival,xs++[0]),(d*val,xs++[1])]
det0 (d,xs) = [(d,xs++[0])]
det1 (d,xs) = [(d,xs++[1])]
ival = 1.0 - val
randUnsafe x = unsafePerformIO $ do
setStdGen (mkStdGen x)
y <- randomRIO (0,1)
return y
buildGeneGraph :: ParseData -> DirectedGraph
buildGeneGraph pdata = mkGraph lnodes edges
where nodes = zipWith (\a (b,c)->(a,b,c)) [1..] (M.assocs pdata)
lnodes = map (\(a,b,c)->(a,b)) nodes
edges = concatMap edges1 nodes
edges1 (n,g,gi) =
zip3 (map n2N (allUpStream gi)) (repeat n) (repeat "")
filt name = if head name == '!' then tail name else name
n2N name = case lookup (filt name) name2NodeMap of
Just x -> x
Nothing -> error (name ++ " gene: no node mapping for this gene")
name2NodeMap = zip (M.keys pdata) [1..]
allUpStream = concatMap (\(Pathway xs _ _ _)->xs) . pathways
simulate :: Args String -> ColoredStateGraph -> ColoredStateGraph
simulate args
| gotArg args "reduce" = reduceSim
| otherwise = regSim
where
n1 = getRequiredArg args "n1"
n2 = getRequiredArg args "n2"
reduceSim = (pass n2 fullIteration).
(pass n1 (stripTransNodes.fullIteration))
regSim = pass (n1+n2) fullIteration
pass n f = last.take n.iterate f
-- Strips nodes that have no incoming edges
stripTransNodes :: Graph gr => gr NodeInfo b -> gr NodeInfo b
stripTransNodes orig = foldr strip orig (nodes orig)
where strip node gr
| null $ inn orig node = delNode node gr
| otherwise = gr
prob i = let Just (NodeInfo _ p) = i in p
-- Will only strip nodes that have no incoming edges and one outgoing edge
-- (deterministic transient nodes).
stripTransFuzzyNodes :: ColoredStateGraph -> ColoredStateGraph
stripTransFuzzyNodes orig = foldl' strip orig (nodes orig)
where
strip gr node
| null inedges && null (tail outedges) = delNode node gr
| otherwise = gr
where
inedges = inn gr node
outedges = out gr node
sumMass :: ColoredStateGraph -> Double
sumMass g = sum $ map ((\(NodeInfo _ pr)->pr).snd) (labNodes g)
calcSSAs :: Args String -> ParseData -> KmapSet -> ColoredStateGraph -> GeneMC
calcSSAs args p ks = zipNames . allgenes . ssaVec . simVec . seedList
where
n2 = getRequiredArg args "n2" -- Number of iterations per simulation
n3 = getRequiredArg args "n3" -- Number of simruns
n4 = getRequiredArg args "n4" -- Starting Seed
pass n f = last.take n.iterate f
-- Create list of random seeds and the starting graph
seedList :: ColoredStateGraph -> V.Vector (Int,ColoredStateGraph)
seedList gr = V.fromList $ zip [n4..(n4+n3)] (repeat gr)
-- Get a new randomized graph and simulate
simVec :: V.Vector (Int,ColoredStateGraph) -> V.Vector (Int,ColoredStateGraph)
simVec = G.map ((\(x,g)->(x,(pass n2 fullIteration g))).(fuzzGraphEdges p ks))
-- Now get the SSAs of these
ssaVec :: V.Vector (Int,ColoredStateGraph) -> V.Vector SSA
ssaVec xv = G.map (genSSA.snd) xv `using` (parVector 2)
-- Basically a transpose, to get a list of SSA for each gene instead of
-- each simulation run
allgenes :: V.Vector SSA -> V.Vector (U.Vector Double)
allgenes ssas = G.map (\x-> G.convert $ G.map (G.!x) ssas) (V.fromList [0..(length $ M.keys p)-1])
zipNames :: V.Vector (U.Vector Double) -> M.Map Gene (U.Vector Double)
zipNames xv = M.fromList $ zip (M.keys p) (G.toList xv)
normalizeGraph :: ColoredStateGraph -> (Double, ColoredStateGraph)
normalizeGraph g = (tot, nmap (\(NodeInfo a pr)->(NodeInfo a (pr/tot))) g)
where tot = sumMass g
printSSA :: SSA -> IO()
printSSA vec = do
G.mapM_ (printf "%7.3f") vec
putStrLn ""
-- Average the SSA over several graphs to avoid periodicities
genSSA :: ColoredStateGraph -> SSA
genSSA g = G.map (/denom) $ foldl1 (G.zipWith (+)) ssaList
where
denom = fromIntegral n
n = 8
ssaList = map genSSAForGraph glist
glist = take n $ iterate fullIteration g
genSSAForGraph :: ColoredStateGraph -> SSA
genSSAForGraph g = G.foldr (G.zipWith (+)) (U.replicate len 0) filt2
where len = length $ name $ G.head filt1
filt1 = V.fromList $ map snd (labNodes g)
filt2 = G.map weight filt1
weight (NodeInfo a pr) = U.fromList $ map ((*pr).conv) a
conv = (\x->if x=='1' then 1 else 0)
name (NodeInfo a pr) = a
|
binarybana/grn-pathways
|
GRN/StateTransition.hs
|
bsd-2-clause
| 12,397 | 2 | 16 | 3,346 | 4,425 | 2,349 | 2,076 | 214 | 5 |
{-# LANGUAGE ScopedTypeVariables, CPP #-}
module IndexDirector (indexFileName, indexDatabase, indexWrapper, fullIndex, lookKeywords, parseKeywords) where
import Data.List hiding (union, insert)
import Control.Monad
import System.Directory
import System.IO
import Data.Char
import Data.Function
import Data.List
import System.Environment
import Data.IORef
import System.FilePath
import Control.Exception
import Control.Arrow
import Data.Maybe
import System.IO.Error
import Data.ByteString.Char8 (unpack, hGet)
import Prelude hiding (catch)
import Replace
import Unpacks
import Normalize
import Driveletters
import Indexing
toUpperCase s = map toUpper s
indexFileName = return "/mnt/export/temporary/Index.dat"{-do
dir <- getAppUserDataDirectory "Indexing"
createDirectoryIfMissing False dir
return (appendDelimiter dir ++ "Index.dat")-}
-- I maintain a distinction between "names" and "logical names," in order
-- to handle files that have been unpacked from archives. The logical names
-- are the names the user will see, and are a concatenation of paths
-- separated by @s. The other names are the places where you find the
-- temporary files that resulted from unpacking.
details1 name logicalName idx code = putStrLn logicalName >> maybe
code
(\f -> catch
(f name $ \unpacked -> indexDirectory False unpacked (logicalName ++ "@") idx)
(\(ex :: IOError) -> putStr "*** " >> print ex))
(lookup (takeExtension name) unpacks)
details2 name code = do
userdata <- getAppUserDataDirectory "Indexing"
tmp <- getTemporaryDirectory
unless
(name == appendDelimiter userdata || name == appendDelimiter tmp || name == "/dev" || name == "/sys")
code
details3 code = catch (catch code
(\(ex :: IndexingError) -> putStr "*** " >> print ex))
(\(ex :: IOError) -> putStr "*** " >> print ex)
-- When a file is an unpackable archive, I do the unpacking, then start
-- indexing the resulting temporary directory.
indexDirectory noRecurse dir logicalDir idx = details3 $ do
contents <- getDirectoryContents dir
mapM_ (\nm -> let
name = dir ++ nm
logicalName = logicalDir ++ nm in
unless (nm == "." || nm == "..") $ do
index idx logicalName logicalName True
b <- doesFileExist name
if b then
details1 name logicalName idx {-Primary control flow:-}(bracket (openBinaryFile name ReadMode)
hClose
$ \hdl -> do
contents <- hGetContents hdl
catch (index idx logicalName contents False) (\(ex :: IndexingError) -> putStr "*** " >> print ex))
else
unless noRecurse (details2 name {-Primary control flow:-}(indexDirectory noRecurse (name ++ [pathDelimiter]) (logicalName ++ [pathDelimiter]) idx)))
contents
indexDatabase ident idx = error ""{-do
tables <- database ident
mapM_ (\tab -> do
recs <- getTable ident tab
mapM_ (\rec -> do
Rec ls <- record ident tab rec
index idx (appendDelimiter ident ++ appendDelimiter tab ++ rec) $ concatMap (maybe "@" ('@':) . snd) ls)
recs)
tables-}
indexWrapper noRec dir = do
idxNm <- indexFileName
idx <- openIndex idxNm
finally
(indexDirectory noRec dir dir idx)
(closeIndex idx)
#ifdef WIN32
fullIndex = do
letters <- driveLetters
mapM_ (indexWrapper False) letters
#else
fullIndex = indexWrapper False "/"
#endif
intersection ((x, y):xs) ls = if null with then
intersection xs ls
else
(x, y ++ concatMap snd with) : intersection xs without where
(with, without) = partition ((==x) . fst) ls
intersection [] _ = []
intersects ls = foldl1 intersection (map (map (\(x, y) -> (x, [y]))) ls)
-- The process of doing a keyword search:
-- lookKeywords deals with all the keywords the user has entered,
-- lookUp deals with a single keyword.
-- First it acquires a list, /possibilities/, which is a superset of the correct
-- results. Then it winnows this list down by searching for the keywords
-- in the texts of the files.
lookKeywords idx keywords options = do
keywords <- return $ map normalizeText keywords
results <- liftM intersects $ mapM (lookUp idx options) keywords
mapM (contexts keywords) results
-- This function produces the contexts for a search.
contexts keywords (name, locs) = catch (liftM ((,) name) $ mapM (\(k, (unpackName, loc)) -> do
hdl <- openBinaryFile unpackName ReadMode
sz <- hFileSize hdl
hSeek hdl AbsoluteSeek $ toInteger $ (loc - 33) `max` 0
bs <- hGet hdl $ 67 `min` (fromInteger sz - (fromIntegral loc - 33))
hClose hdl
return $ "..." ++ replace [("\n", " "), ("\t", " "), ("\r", " ")] (unpack bs ++ "..."))
$ zip keywords locs)
(\(_ :: IOError) -> return (name, []))
parseKeywords (c:cs)
| c == '"' = let (kw, rest) = break (=='"') cs in
kw : parseKeywords (drop 2 rest)
| otherwise = let (kw, rest) = break (==' ') (c:cs) in
kw : parseKeywords (drop 1 rest)
parseKeywords [] = []
|
jacinabox/Indexing
|
IndexDirector.hs
|
bsd-2-clause
| 4,757 | 50 | 27 | 855 | 1,449 | 754 | 695 | 89 | 2 |
module Statistics.Information.Discrete.MutualInfo where
import Data.Matrix
import Statistics.Information.Discrete.Entropy
mi :: Eq a => Int -> Matrix a -> Matrix a -> Double
mi base xs ys = entropy base xs + entropy base ys - entropy base (xs <|> ys)
cmi :: Eq a => Int -> Matrix a -> Matrix a -> Matrix a -> Double
cmi base xs ys zs = hxz + hyz - hxyz - hz where
hxz = entropy base (xs <|> zs)
hyz = entropy base (ys <|> zs)
hxyz = entropy base (xs <|> ys <|> zs)
hz = entropy base zs
|
eligottlieb/Shannon
|
src/Statistics/Information/Discrete/MutualInfo.hs
|
bsd-3-clause
| 497 | 0 | 10 | 109 | 222 | 113 | 109 | 11 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE OverloadedStrings #-}
module SingletonsBaseTestSuiteUtils (
compileAndDumpTest
, compileAndDumpStdTest
, testCompileAndDumpGroup
, ghcOpts
, cleanFiles
) where
import Build_singletons_base ( ghcPath, ghcFlags, rootDir )
import Control.Exception ( Exception )
import Data.Foldable ( asum )
import Data.Text ( Text )
import Data.String ( IsString(fromString) )
import System.FilePath ( takeBaseName, pathSeparator )
import System.FilePath ( (</>) )
import System.IO ( IOMode(..), openFile )
import System.Process ( CreateProcess(..), StdStream(..)
, createProcess, proc, waitForProcess
, callCommand )
import Test.Tasty ( TestTree, testGroup )
import Test.Tasty.Golden ( goldenVsFileDiff )
import qualified Turtle
-- Some infractructure for handling external process errors
newtype ProcessException = ProcessException String
deriving newtype (Eq, Ord, Show)
deriving anyclass Exception
-- directory storing compile-and-run tests and golden files
goldenPath :: FilePath
goldenPath = rootDir </> "tests/compile-and-dump/"
-- GHC options used when running the tests
ghcOpts :: [String]
ghcOpts = ghcFlags ++ [
"-v0"
, "-c"
, "-ddump-splices"
, "-dsuppress-uniques"
, "-fforce-recomp"
, "-fprint-explicit-kinds"
, "-O0"
, "-i" ++ goldenPath
, "-XGHC2021"
, "-XTemplateHaskell"
, "-XDataKinds"
, "-XTypeFamilies"
, "-XGADTs"
, "-XUndecidableInstances"
, "-XIncoherentInstances"
, "-XLambdaCase"
, "-XUnboxedTuples"
, "-XDefaultSignatures"
, "-XCPP"
, "-XNoStarIsType"
, "-XNoNamedWildCards"
]
-- Compile a test using specified GHC options. Save output to file, normalize
-- and compare it with golden file. This function also builds golden file
-- from a template file. Putting it here is a bit of a hack but it's easy and it
-- works.
--
-- First parameter is a path to the test file relative to goldenPath directory
-- with no ".hs".
compileAndDumpTest :: FilePath -> [String] -> TestTree
compileAndDumpTest testName opts =
goldenVsFileDiff
(takeBaseName testName)
(\ref new -> ["diff", "-w", "-B", ref, new]) -- see Note [Diff options]
goldenFilePath
actualFilePath
compileWithGHC
where
testPath = testName ++ ".hs"
goldenFilePath = goldenPath ++ testName ++ ".golden"
actualFilePath = goldenPath ++ testName ++ ".actual"
compileWithGHC :: IO ()
compileWithGHC = do
hActualFile <- openFile actualFilePath WriteMode
(_, _, _, pid) <- createProcess (proc ghcPath (testPath : opts))
{ std_out = UseHandle hActualFile
, std_err = UseHandle hActualFile
, cwd = Just goldenPath }
_ <- waitForProcess pid -- see Note [Ignore exit code]
normalizeOutput actualFilePath -- see Note [Output normalization]
return ()
-- Compile-and-dump test using standard GHC options defined by the testsuite.
-- It takes two parameters: name of a file containing a test (no ".hs"
-- extension) and directory where the test is located (relative to
-- goldenPath). Test name and path are passed separately so that this function
-- can be used easily with testCompileAndDumpGroup.
compileAndDumpStdTest :: FilePath -> FilePath -> TestTree
compileAndDumpStdTest testName testPath =
compileAndDumpTest (testPath ++ (pathSeparator : testName)) ghcOpts
-- A convenience function for defining a group of compile-and-dump tests stored
-- in the same subdirectory. It takes the name of subdirectory and list of
-- functions that given the name of subdirectory create a TestTree. Designed for
-- use with compileAndDumpStdTest.
testCompileAndDumpGroup :: FilePath -> [FilePath -> TestTree] -> TestTree
testCompileAndDumpGroup testDir tests =
testGroup testDir $ map ($ testDir) tests
{-
Note [Ignore exit code]
~~~~~~~~~~~~~~~~~~~~~~~
It may happen that the compilation of a source file fails. We could find out
whether that happened by inspecting the exit code of the `ghc` process. But it
would be tricky to get a helpful message from the failing test; we would need
to display the stderr that we just wrote into a file. Luckliy, we don't have to
do that - we can ignore the problem here and let the test fail when the
actual file is compared with the golden file.
Note [Diff options]
~~~~~~~~~~~~~~~~~~~
We use following diff options:
-w - Ignore all white space.
-B - Ignore changes whose lines are all blank.
Note [Output normalization]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output file is normalized inplace. Line numbers generated in splices:
Foo:(40,3)-(42,4)
Foo.hs:7:3:
Equals_1235967303
are turned into:
Foo:(0,0)-(0,0)
Foo.hs:0:0:
Equals_0123456789
This allows inserting comments into test files without the need to modify the
golden file to adjust line numbers.
-}
normalizeOutput :: FilePath -> IO ()
normalizeOutput file = Turtle.inplace pat (fromString file)
where
pat :: Turtle.Pattern Text
pat = asum
[ "(0,0)-(0,0)" <$ numPair <* "-" <* numPair
, ":0:0:" <$ ":" <* d <* ":" <* d <* "-" <* d
, ":0:0" <$ ":" <* d <* ":" <* d
, fromString @Text . numPeriod <$> Turtle.lowerBounded 10 Turtle.digit
, fromString @Text . ('%' <$) <$> Turtle.lowerBounded 10 punctSym
-- Remove pretty-printed references to the singletons package
-- (e.g., turn `singletons-2.4.1:Sing` into `Sing`) to make the output
-- more stable.
, "" <$ "singletons-" <* verNum <* ":"
]
verNum = d `Turtle.sepBy` Turtle.char '.'
numPair = () <$ "(" <* d <* "," <* d <* ")"
punctSym = Turtle.oneOf "!#$%&*+./>"
numPeriod = zipWith const (cycle "0123456789876543210")
d = Turtle.some Turtle.digit
cleanFiles :: IO ()
cleanFiles = callCommand $ "rm -f " ++ rootDir </> "tests/compile-and-dump/*/*.{hi,o}"
|
goldfirere/singletons
|
singletons-base/tests/SingletonsBaseTestSuiteUtils.hs
|
bsd-3-clause
| 6,312 | 0 | 15 | 1,608 | 942 | 537 | 405 | -1 | -1 |
-- | This modul exports the list of supported datatype libraries.
-- It also exports the main functions to validate an XML instance value
-- with respect to a datatype.
module Yuuko.Text.XML.HXT.RelaxNG.DataTypeLibraries
( datatypeLibraries
, datatypeEqual
, datatypeAllows
)
where
import Yuuko.Text.XML.HXT.DOM.Interface
( relaxNamespace
)
import Yuuko.Text.XML.HXT.RelaxNG.DataTypeLibUtils
import Yuuko.Text.XML.HXT.RelaxNG.DataTypeLibMysql
( mysqlDatatypeLib )
import Yuuko.Text.XML.HXT.RelaxNG.XmlSchema.DataTypeLibW3C
( w3cDatatypeLib )
import Data.Maybe
( fromJust )
-- ------------------------------------------------------------
-- | List of all supported datatype libraries which can be
-- used within the Relax NG validator modul.
datatypeLibraries :: DatatypeLibraries
datatypeLibraries
= [ relaxDatatypeLib
, relaxDatatypeLib'
, mysqlDatatypeLib
, w3cDatatypeLib
]
{- |
Tests whether a XML instance value matches a value-pattern.
The following tests are performed:
* 1. : does the uri exist in the list of supported datatype libraries
- 2. : does the library support the datatype
- 3. : does the XML instance value match the value-pattern
The hard work is done by the specialized 'DatatypeEqual' function
(see also: 'DatatypeCheck') of the datatype library.
-}
datatypeEqual :: Uri -> DatatypeEqual
datatypeEqual uri d s1 c1 s2 c2
= if elem uri (map fst datatypeLibraries)
then dtEqFct d s1 c1 s2 c2
else Just ( "Unknown DatatypeLibrary " ++ show uri )
where
DTC _ dtEqFct _ = fromJust $ lookup uri datatypeLibraries
{- |
Tests whether a XML instance value matches a data-pattern.
The following tests are performed:
* 1. : does the uri exist in the list of supported datatype libraries
- 2. : does the library support the datatype
- 3. : does the XML instance value match the data-pattern
- 4. : does the XML instance value match all params
The hard work is done by the specialized 'DatatypeAllows' function
(see also: 'DatatypeCheck') of the datatype library.
-}
datatypeAllows :: Uri -> DatatypeAllows
datatypeAllows uri d params s1 c1
= if elem uri (map fst datatypeLibraries)
then dtAllowFct d params s1 c1
else Just ( "Unknown DatatypeLibrary " ++ show uri )
where
DTC dtAllowFct _ _ = fromJust $ lookup uri datatypeLibraries
-- --------------------------------------------------------------------------------------
-- Relax NG build in datatype library
relaxDatatypeLib :: DatatypeLibrary
relaxDatatypeLib = (relaxNamespace, DTC datatypeAllowsRelax datatypeEqualRelax relaxDatatypes)
-- | if there is no datatype uri, the built in datatype library is used
relaxDatatypeLib' :: DatatypeLibrary
relaxDatatypeLib' = ("", DTC datatypeAllowsRelax datatypeEqualRelax relaxDatatypes)
-- | The build in Relax NG datatype lib supportes only the token and string datatype,
-- without any params.
relaxDatatypes :: AllowedDatatypes
relaxDatatypes
= map ( (\ x -> (x, [])) . fst ) relaxDatatypeTable
datatypeAllowsRelax :: DatatypeAllows
datatypeAllowsRelax d p v _
= maybe notAllowed' allowed . lookup d $ relaxDatatypeTable
where
notAllowed'
= Just $ errorMsgDataTypeNotAllowed relaxNamespace d p v
allowed _
= Nothing
-- | If the token datatype is used, the values have to be normalized
-- (trailing and leading whitespaces are removed).
-- token does not perform any changes to the values.
datatypeEqualRelax :: DatatypeEqual
datatypeEqualRelax d s1 _ s2 _
= maybe notAllowed' checkValues . lookup d $ relaxDatatypeTable
where
notAllowed'
= Just $ errorMsgDataTypeNotAllowed2 relaxNamespace d s1 s2
checkValues predicate
= if predicate s1 s2
then Nothing
else Just $ errorMsgEqual d s1 s2
relaxDatatypeTable :: [(String, String -> String -> Bool)]
relaxDatatypeTable
= [ ("string", (==))
, ("token", \ s1 s2 -> normalizeWhitespace s1 == normalizeWhitespace s2 )
]
-- --------------------------------------------------------------------------------------
|
nfjinjing/yuuko
|
src/Yuuko/Text/XML/HXT/RelaxNG/DataTypeLibraries.hs
|
bsd-3-clause
| 4,208 | 20 | 11 | 894 | 630 | 353 | 277 | 58 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TupleSections #-}
module PullRequestFiles (filesByPullRequest, prsTouchingFile) where
import BasicPrelude
import Data.Text (unpack)
import Github.PullRequests
fromEither :: String -> Either Error a -> IO a
fromEither msgPrefix (Left e) = fail $ msgPrefix ++ ": " ++ unpack (show e)
fromEither _ (Right a) = return a
filesByPullRequest :: String -> String -> IO [(Int, [File])]
filesByPullRequest user repo = do
pullReqs <- fromEither "pull requests" =<< pullRequestsFor user repo
mapM (combine . pullRequestNumber) pullReqs
where
combine prNum = (prNum, ) <$> (fromEither ("files for " ++ unpack (show prNum)) =<< pullRequestFiles user repo prNum)
prsTouchingFile :: String -> String -> String -> IO [Int]
prsTouchingFile file user repo = map fst . filter (any ((== file) . fileFilename) . snd) <$> filesByPullRequest user repo
|
greenrd/github-utils
|
PullRequestFiles.hs
|
bsd-3-clause
| 947 | 0 | 15 | 201 | 307 | 158 | 149 | 16 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
-- | This module is intended to be imported @qualified@, for example:
--
-- > import qualified Test.Tasty.Lens.Prism as Prism
--
module Test.Tasty.Lens.Prism
(
-- * Tests
test
, testSeries
, testExhaustive
) where
import Data.Proxy (Proxy(..))
import Control.Lens
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.DumbCheck -- (testProperty)
import Control.Lens.Prism.Laws (yin, yang)
import qualified Test.Tasty.Lens.Traversal as Traversal
-- | A 'Prism'' is only legal if it's a valid 'Traversal'' and if the following
-- laws hold:
--
-- 1. @preview l (review l b) ≡ Just b"@
--
-- 2. @maybe s (review l) (preview l s) ≡ s@
--
-- It uses the 'Serial' and 'CoSerial' instances for @s@ and @a@. If you are
-- not creating your own orphan instances be aware of combinatorial explosion
-- since the default implementations usually aim for exhaustivity.
--
-- This also uses "Test.Tasty.Lens.Traversal"@.@'Traversal.test', with the
-- 'Maybe' functor, to validate the 'Prism'' is a valid 'Traversal''.
test
:: (Eq s, Eq a, Show s, Show a, Serial s, Serial a)
=> Prism' s a -> TestTree
test l = testSeries l series
-- | A 'Prism'' is only legal if it's a valid 'Traversal'' and if the following
-- laws hold:
--
-- 1. @preview l (review l b) ≡ Just b"@
--
-- 2. @maybe s (review l) (preview l s) ≡ s@
--
-- Here you explicitly pass a custom 'Series' for @s@, while for @a@ the
-- @Serial@ instance is used. If you want to fine tune both 'Series', you
-- should create your own 'TestTree'.
--
-- This also uses "Test.Tasty.Lens.Traversal"@.@'Traversal.testSeries', with
-- the 'Maybe' functor and the custom @s@ 'Series', to validate the 'Prism'' is
-- a valid 'Traversal''.
testSeries
:: (Eq s, Eq a, Show s, Show a, Serial a)
=> Prism' s a -> Series s -> TestTree
testSeries l ss = testGroup "Prism Laws"
[ testSerialProperty "preview l (review l b) ≡ Just b" (yin l)
, testSeriesProperty "maybe s (review l) (preview l s) ≡ s" (yang l) ss
, Traversal.testSeries (Proxy :: Proxy Maybe) l ss
]
-- | A 'Prism'' is only legal if it's a valid 'Traversal'' and if the following
-- laws hold:
--
-- 1. @preview l (review l b) ≡ Just b"@
--
-- 2. @maybe s (review l) (preview l s) ≡ s@
--
-- This is the same as 'test' except it uses
-- "Test.Tasty.Lens.Traversal"@.@'Traversal.testExhaustive' to validate
-- 'Traversal'' laws. Be aware of combinatorial explosions.
testExhaustive
:: ( Eq s, Eq a, Show s, Show a
, Serial s, Serial a
)
=> Prism' s a -> TestTree
testExhaustive l = testGroup "Prism Laws"
[ testSerialProperty "preview l (review l b) ≡ Just b" (yin l)
, testSerialProperty "maybe s (review l) (preview l s) ≡ s" (yang l)
, Traversal.testExhaustive (Proxy :: Proxy Maybe) l
]
|
jdnavarro/tasty-lens
|
Test/Tasty/Lens/Prism.hs
|
bsd-3-clause
| 2,835 | 0 | 9 | 544 | 426 | 250 | 176 | 32 | 1 |
--------------------------------------------------------------------------------
-- | Internal module to parse metadata
module Hakyll.Core.Provider.Metadata
( loadMetadata
, metadata
, page
) where
--------------------------------------------------------------------------------
import Control.Applicative
import Control.Arrow (second)
import qualified Data.ByteString.Char8 as BC
import Data.List (intercalate)
import qualified Data.Map as M
import System.IO as IO
import Text.Parsec ((<?>))
import qualified Text.Parsec as P
import Text.Parsec.String (Parser)
--------------------------------------------------------------------------------
import Hakyll.Core.Identifier
import Hakyll.Core.Metadata
import Hakyll.Core.Provider.Internal
import Hakyll.Core.Util.String
--------------------------------------------------------------------------------
loadMetadata :: Provider -> Identifier -> IO (Metadata, Maybe String)
loadMetadata p identifier = do
hasHeader <- probablyHasMetadataHeader fp
(md, body) <- if hasHeader
then second Just <$> loadMetadataHeader fp
else return (M.empty, Nothing)
emd <- case mi of
Nothing -> return M.empty
Just mi' -> loadMetadataFile $ resourceFilePath p mi'
return (M.union md emd, body)
where
fp = resourceFilePath p identifier
mi = M.lookup identifier (providerFiles p) >>= resourceInfoMetadata
--------------------------------------------------------------------------------
loadMetadataHeader :: FilePath -> IO (Metadata, String)
loadMetadataHeader fp = do
contents <- readFile fp
case P.parse page fp contents of
Left err -> error (show err)
Right (md, b) -> return (M.fromList md, b)
--------------------------------------------------------------------------------
loadMetadataFile :: FilePath -> IO Metadata
loadMetadataFile fp = do
contents <- readFile fp
case P.parse metadata fp contents of
Left err -> error (show err)
Right md -> return $ M.fromList md
--------------------------------------------------------------------------------
-- | Check if a file "probably" has a metadata header. The main goal of this is
-- to exclude binary files (which are unlikely to start with "---").
probablyHasMetadataHeader :: FilePath -> IO Bool
probablyHasMetadataHeader fp = do
handle <- IO.openFile fp IO.ReadMode
bs <- BC.hGet handle 1024
IO.hClose handle
return $ isMetadataHeader bs
where
isMetadataHeader bs =
let pre = BC.takeWhile (\x -> x /= '\n' && x /= '\r') bs
in BC.length pre >= 3 && BC.all (== '-') pre
--------------------------------------------------------------------------------
-- | Space or tab, no newline
inlineSpace :: Parser Char
inlineSpace = P.oneOf ['\t', ' '] <?> "space"
--------------------------------------------------------------------------------
-- | Parse Windows newlines as well (i.e. "\n" or "\r\n")
newline :: Parser String
newline = P.string "\n" <|> P.string "\r\n"
--------------------------------------------------------------------------------
-- | Parse a single metadata field
metadataField :: Parser (String, String)
metadataField = do
key <- P.manyTill P.alphaNum $ P.char ':'
P.skipMany1 inlineSpace <?> "space followed by metadata for: " ++ key
value <- P.manyTill P.anyChar newline
trailing' <- P.many trailing
return (key, trim $ intercalate " " $ value : trailing')
where
trailing = P.many1 inlineSpace *> P.manyTill P.anyChar newline
--------------------------------------------------------------------------------
-- | Parse a metadata block
metadata :: Parser [(String, String)]
metadata = P.many metadataField
--------------------------------------------------------------------------------
-- | Parse a metadata block, including delimiters and trailing newlines
metadataBlock :: Parser [(String, String)]
metadataBlock = do
open <- P.many1 (P.char '-') <* P.many inlineSpace <* newline
metadata' <- metadata
_ <- P.choice $ map (P.string . replicate (length open)) ['-', '.']
P.skipMany inlineSpace
P.skipMany1 newline
return metadata'
--------------------------------------------------------------------------------
-- | Parse a page consisting of a metadata header and a body
page :: Parser ([(String, String)], String)
page = do
metadata' <- P.option [] metadataBlock
body <- P.many P.anyChar
return (metadata', body)
|
bergmark/hakyll
|
src/Hakyll/Core/Provider/Metadata.hs
|
bsd-3-clause
| 4,733 | 0 | 16 | 1,012 | 1,064 | 550 | 514 | 77 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE CPP #-}
-- | Module implementaing the PVM file reading.
module Codec.Volume.Pvm( readPVM, decodePVM ) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative( (*>), (<$>) )
#endif
import Data.Bifunctor( bimap )
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Vector.Storable as VS
import Text.Read( readMaybe )
import Data.Binary( Binary( get ) )
import Data.Binary.Get( Get
, runGetOrFail
, getByteString )
import Codec.Volume.VectorByteConversion
import Codec.Volume.Types
import Codec.Volume.Dds
import Data.Binary.Ascii
-- | Decode a PVM (potentially with dds compression) in memory.
decodePVM :: B.ByteString -> Either String DynamicVolume
decodePVM = decodeDecompressed . decodeDDS
-- | Read a pvm file potentially with DDS compression.
readPVM :: FilePath -> IO (Either String DynamicVolume)
readPVM fname = decodePVM <$> B.readFile fname
decodeDecompressed :: B.ByteString -> Either String DynamicVolume
decodeDecompressed str
| pvmSig `B.isPrefixOf` str = go 1 . BL.fromStrict $ B.drop (B.length pvmSig) str
| pvm2Sig `B.isPrefixOf` str = go 2 . BL.fromStrict $ B.drop (B.length pvm2Sig) str
| pvm3Sig `B.isPrefixOf` str = go 3 . BL.fromStrict $ B.drop (B.length pvm3Sig) str
| otherwise = Left "Unknown pvm signature"
where
pvmSig = "PVM\n"
pvm2Sig = "PVM2\n"
pvm3Sig = "PVM3\n"
parser 1 = (, VoxelSize 1 1 1,) <$> getSizes <*> getBytePerSample
parser 2 = do
!sizes <- getSizes
!voxSize <- getVoxelSize
!bps <- getBytePerSample
return (sizes, voxSize, bps)
parser 3 = parser 2
parser _ = fail "Unknown PVM version"
third (_, _, v) = v
go :: Int -> BL.ByteString -> Either String DynamicVolume
go ver vstr = bimap third third . flip runGetOrFail vstr $ do
(volumeSize, voxelSize, sizePerComp) <- parser ver
let sampCount = samplesInVolume volumeSize
toVolume = Volume volumeSize voxelSize
samples <- getByteString $ sampCount * sizePerComp
case sizePerComp of
1 -> pure . Volume8 . toVolume $ byteStringToVector samples
2 -> pure . Volume16 . toVolume . VS.map endianSwap $ byteStringToVector samples
_ -> fail "Invlid volume size"
getSizes :: Get VolumeSize
getSizes = do
BCD w <- get <* getSpaces
BCD h <- get <* getSpaces
BCD d <- get <* getSpaces
NewLine <- get
return $ VolumeSize w h d
getVoxelSize :: Get (VoxelSize Float)
getVoxelSize = do
n1 <- eatWhile (/= ' ') <* getSpaces
n2 <- eatWhile (/= ' ') <* getSpaces
n3 <- eatWhile (`notElem` (" \r\n" :: String)) <* getSpaces
NewLine <- get
case (,,) <$> readMaybe n1 <*> readMaybe n2 <*> readMaybe n3 of
Nothing -> fail "Invalid sizes"
Just (sw, sh, sd) -> pure $ VoxelSize sw sh sd
getBytePerSample :: Get Int
getBytePerSample = do
BCD bps <- get
NewLine <- get
pure bps
|
Twinside/Juicy.Voxels
|
src/Codec/Volume/Pvm.hs
|
bsd-3-clause
| 3,074 | 0 | 16 | 670 | 945 | 489 | 456 | 73 | 6 |
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving #-}
module Physics.FunPart.ParticleTest
( runTests
, AParticleType(..)
, ADynParticle(..)
, AParticle(..)
) where
import Test.QuickCheck
import Data.Maybe (isNothing, isJust, fromMaybe)
import Control.Lens (view, set)
import qualified Physics.FunPart.VecTest as VT
import Physics.FunPart.VecSpace
import Physics.FunPart.Particle
import Physics.FunPart.Approx
newtype AParticleType = AParticleType { aParticleType :: ParticleType }
deriving (Show, Eq)
newtype ADynParticle = ADynParticle { aDynParticle :: DynParticle }
deriving (Show, Eq)
newtype AParticle = AParticle { aParticle :: Particle }
deriving (Show, Eq)
instance Arbitrary AParticleType where
arbitrary = elements $ map AParticleType [Neutron, Photon]
instance Arbitrary ADynParticle where
arbitrary = do ar <- arbitrary
ap <- arbitrary
return $ ADynParticle $ mkDynParticle (Pos $ VT.aVec ar) (Mom $ VT.aVec ap)
instance Arbitrary AParticle where
arbitrary = do atype <- arbitrary
adyn <- arbitrary
return $ AParticle $ mkParticleFromDyn (aParticleType atype) (aDynParticle adyn)
instance Approx ADynParticle where
distance (ADynParticle dp0) (ADynParticle dp1) =
let dpos = distance (view position dp0) (view position dp1)
dmom = distance (view momentum dp0) (view momentum dp1)
in dpos+dmom
instance Approx AParticle where
distance (AParticle p0) (AParticle p1) =
let dpart = distance (ADynParticle $ view dynPart p0) (ADynParticle $ view dynPart p1)
dtype = if view ptype p0 == view ptype p1 then 0.0 else 1.0
in dpart+dtype
prop_pushNotFails :: Distance -> ADynParticle -> Property
prop_pushNotFails dist (ADynParticle dpart) =
mag (view (momentum.momentumVec) dpart) > 0.0 ==> isJust $ push dist dpart
prop_pPushNotFails :: Distance -> AParticle -> Property
prop_pPushNotFails dist (AParticle part) =
mag (view pMomentumVec part) > 0.0 ==> isJust $ push dist part
prop_pushFailsOnZeroMom :: Distance -> ADynParticle -> Bool
prop_pushFailsOnZeroMom dist (ADynParticle dpart) =
let dpart' = set momentum (Mom zero) dpart
in isNothing $ push dist dpart'
prop_pPushFailsOnZeroMom :: Distance -> AParticle -> Bool
prop_pPushFailsOnZeroMom dist (AParticle part) =
let part' = set pMomentum (Mom zero) part
in isNothing $ push dist part'
backAndForth :: Pushable a => Distance -> a -> a
backAndForth dist p =
fromMaybe p $ do
p' <- push dist p
push (-dist) p'
prop_pushAndComeBack :: Distance -> ADynParticle -> Property
prop_pushAndComeBack dist (ADynParticle dpart) =
mag (view (momentum.momentumVec) dpart) > 0.0 ==>
let dpart' = backAndForth dist dpart
in ADynParticle dpart ~== ADynParticle dpart'
prop_pPushAndComeBack :: Distance -> AParticle -> Property
prop_pPushAndComeBack dist (AParticle part) =
mag (view pMomentumVec part) > 0.0 ==>
let part' = backAndForth dist part
in AParticle part ~== AParticle part'
return []
runTests :: IO Bool
runTests = $quickCheckAll
|
arekfu/funpart
|
test/Physics/FunPart/ParticleTest.hs
|
bsd-3-clause
| 3,195 | 0 | 13 | 705 | 990 | 508 | 482 | 71 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.TexgenReflection
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/NV/texgen_reflection.txt NV_texgen_reflection> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.TexgenReflection (
-- * Enums
gl_NORMAL_MAP_NV,
gl_REFLECTION_MAP_NV
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/NV/TexgenReflection.hs
|
bsd-3-clause
| 681 | 0 | 4 | 81 | 40 | 33 | 7 | 4 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
-- http://cgit.gitano.org.uk/youtube/bf.git/tree/bf.hs
-- http://llvm.org/docs/tutorial/OCamlLangImpl3.html
-- http://augustss.blogspot.com/2009/01/llvm-llvm-low-level-virtual-machine-is.html
import Control.Monad (join)
import Data.Int
import Data.Word
import Foreign.Marshal.Array
import LLVM.Core
import LLVM.ExecutionEngine
data Ty
= TyBool
| TyArr Ty Ty
deriving (Eq, Show)
data Term
= TmTrue
| TmFalse
| TmIf Term Term Term
| TmVar Int Int
| TmAbs String Ty Term
| TmApp Term Term
deriving (Eq, Show)
{-
type Context = [(Text, Binding)]
isVal :: Context -> Term -> Bool
isVal _ TmAbs{} = True
isVal _ _ = False
eval1 :: Context -> Term -> Maybe Term
eval1 ctx (TmApp _ (TmAbs _ _ _ t12) v2) | isVal ctx v2 = Just $
termSubstTop v2 t12
eval1 ctx (TmApp fi v1 t2) | isVal ctx v1 = TmApp fi v1 `fmap` eval1 ctx t2
eval1 ctx (TmApp fi t1 t2) = (\x -> TmApp fi x t2) `fmap` eval1 ctx t1
eval1 _ _ = Nothing
eval :: Context -> Term -> Term
eval ctx t = case eval1 ctx t of
Just t' -> eval ctx t'
Nothing -> t
-}
execute :: Term -> IO ()
execute tm = join $ simpleFunction $ createFunction ExternalLinkage (ret $ compile tm)
-- CodeGenFunction r a
-- r is not used / phantom?
-- a is return value
compile :: Term -> CodeGenFunction r (Value Bool)
compile TmTrue = return $ valueOf True
compile TmFalse = return $ valueOf False
compile (TmIf tmC tm1 tm2) = do
br1 <- newBasicBlock
br2 <- newBasicBlock
-- (test :: Value Bool) <- compile tmC :: CodeGenFunction (Value Bool) Terminate
-- condBr test br1 br2 :: CodeGenFunction () Terminate
test <- compile tmC
condBr test br1 br2
defineBasicBlock br1
v1 <- compile tm1
call v1
defineBasicBlock br2
v2 <- compile tm2
call v2
-- compile (TmVar x y)
-- compile (TmAbs str _ tm)
-- compile (TmApp tm1 tm2)
-- f x y z = (x + y) * z
mAddMul :: CodeGenModule (Function (Int32 -> Int32 -> Int32 -> IO Int32))
mAddMul = createFunction ExternalLinkage $ \x y z -> do
t <- add x y
r <- mul t z
ret r
mFib :: CodeGenModule (Function (Word32 -> IO Word32))
mFib = do
fib <- newFunction ExternalLinkage
defineFunction fib $ \arg -> do
recurse <- newBasicBlock
exit <- newBasicBlock
-- only move on to recurse if arg > 2
test <- cmp CmpGT arg (2::Word32)
condBr test recurse exit
defineBasicBlock exit
ret (1::Word32)
defineBasicBlock recurse
x1 <- sub arg (1::Word32)
fibx1 <- call fib x1
x2 <- sub arg (2::Word32)
fibx2 <- call fib x2
r <- add fibx1 fibx2
ret r
return fib
bldGreet :: CodeGenModule (Function (IO ()))
bldGreet = do
puts <- newNamedFunction ExternalLinkage "puts" :: TFunction (Ptr Word8 -> IO Word32)
withStringNul "Hello, World!" $ \greetz -> createFunction ExternalLinkage $ do
tmp <- getElementPtr greetz (0::Word32, (0::Word32, ()))
call puts tmp -- Throw away return value (?)
ret ()
mAbs :: CodeGenModule (Function (Int32 -> IO Int32))
mAbs = createFunction ExternalLinkage $ \x -> do
top <- getCurrentBasicBlock
xneg <- newBasicBlock
xpos <- newBasicBlock
t <- cmp CmpLT x (0::Int32)
condBr t xneg xpos
defineBasicBlock xneg
x' <- sub (0::Int32) x
br xpos
defineBasicBlock xpos
r <- phi [(x, top), (x', xneg)]
r1 <- add r (1::Int32)
ret r1
mDotProd :: CodeGenModule (Function (Word32 -> Ptr Double -> Ptr Double -> IO Double))
mDotProd = createFunction ExternalLinkage $ \size aPtr bPtr -> do
top <- getCurrentBasicBlock
loop <- newBasicBlock
body <- newBasicBlock
exit <- newBasicBlock
br loop
defineBasicBlock loop
i <- phi [(valueOf (0 :: Word32), top)]
s <- phi [(valueOf 0, top)]
t <- cmp CmpNE i size
condBr t body exit
defineBasicBlock body
ap <- getElementPtr aPtr (i, ())
bp <- getElementPtr bPtr (i, ())
a <- load ap
b <- load bp
ab <- mul a b
s' <- add s ab
i' <- add i (valueOf (1 :: Word32))
addPhiInputs i [(i', body)]
addPhiInputs s [(s', body)]
br loop
defineBasicBlock exit
ret (s :: Value Double)
main = do
initializeNativeTarget
addMul <- unsafePurify `fmap` simpleFunction mAddMul
fib <- unsafePurify `fmap` simpleFunction mFib
greet <- simpleFunction bldGreet
abs <- unsafePurify `fmap` simpleFunction mAbs
ioDotProd <- simpleFunction mDotProd
let dotProd a b =
unsafePurify $
withArrayLen a $ \aLen aPtr ->
withArrayLen b $ \bLen bPtr ->
ioDotProd (fromIntegral (aLen `min` bLen)) aPtr bPtr
print $ addMul 2 3 4
print $ fib 35
greet
print $ abs 10
print $ [1, 2, 3] `dotProd` [4, 5, 6]
|
joelburget/tapl
|
llvm.hs
|
bsd-3-clause
| 4,857 | 0 | 18 | 1,288 | 1,482 | 716 | 766 | 122 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Develop.Compile (toJavaScript) where
import qualified Data.Aeson as Json
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import qualified Data.Text.IO as Text
import System.Directory (removeFile)
import qualified Elm.Compiler as Compiler
import qualified Elm.Compiler.Module as Module
import qualified Elm.Utils as Utils
import qualified Develop.StaticFiles as StaticFiles
-- ACTUALLY COMPILE STUFF
compile :: FilePath -> IO (Either String (BS.ByteString, String))
compile filePath =
let
tempJsFile =
"it-is-safe-to-delete-this-file.js"
in
do result <- Utils.unwrappedRun "elm-make" [ "--yes", "--debug", filePath, "--output=" ++ tempJsFile ]
case result of
Left (Utils.MissingExe msg) ->
return $ Left msg
Left (Utils.CommandFailed out err) ->
return $ Left (out ++ err)
Right _ ->
do code <- BS.readFile tempJsFile
removeFile tempJsFile
source <- Text.readFile filePath
return $ Right $ (,) code $
case Compiler.parseDependencies Nothing source of
Left _ ->
error "impossible"
Right (_, name, _) ->
Module.nameToString name
-- TO JAVASCRIPT
toJavaScript :: FilePath -> IO BS.ByteString
toJavaScript filePath =
do result <- compile filePath
case result of
Right (code, name) ->
return $ BS.append code $ BS.pack $
"var runElmProgram = Elm." ++ name ++ ".fullscreen;"
Left errMsg ->
return $ BS.concat $
[ StaticFiles.errors
, BS.pack $ "function runElmProgram() {\n\tElm.Errors.fullscreen("
, LBS.toStrict (Json.encode errMsg)
, ");\n}"
]
|
evancz/cli
|
src/Develop/Compile.hs
|
bsd-3-clause
| 1,902 | 0 | 19 | 556 | 474 | 254 | 220 | 46 | 4 |
{- CIS 194 HW 10
due Monday, 1 April
-}
module Spring13.Week10.AParser where
import Control.Applicative
import Control.Monad
import Data.Char
-- A parser for a value of type a is a function which takes a String
-- represnting the input to be parsed, and succeeds or fails; if it
-- succeeds, it returns the parsed value along with the remainder of
-- the input.
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
-- For example, 'satisfy' takes a predicate on Char, and constructs a
-- parser which succeeds only if it sees a Char that satisfies the
-- predicate (which it then returns). If it encounters a Char that
-- does not satisfy the predicate (or an empty input), it fails.
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser f
where
f [] = Nothing -- fail on the empty input
f (x:xs) -- check if x satisfies the predicate
-- if so, return x along with the remainder
-- of the input (that is, xs)
| p x = Just (x, xs)
| otherwise = Nothing -- otherwise, fail
-- Using satisfy, we can define the parser 'char c' which expects to
-- see exactly the character c, an d fails otherwise.
char :: Char -> Parser Char
char c = satisfy (== c)
{- For example:
*Parser> runParser (satisfy isUpper) "ABC"
Just ('A',"BC")
*Parser> runParser (satisfy isUpper) "abc"
Nothing
*Parser> runParser (char 'x') "xyz"
Just ('x',"yz")
-}
-- For convenience, we've also provided a parser for positive
-- integers.
posInt :: Parser Integer
posInt = Parser f
where
f xs
| null ns = Nothing
| otherwise = Just (read ns, rest)
where (ns, rest) = span isDigit xs
------------------------------------------------------------
-- Your code goes below here
------------------------------------------------------------
first :: (a -> b) -> (a, c) -> (b, c)
first f (a, c) = (f a, c)
instance Functor Parser where
fmap f p = Parser (fmap (first f) . runParser p)
instance Applicative Parser where
pure a = Parser {runParser = \str -> Just (a,str)}
p1 <*> p2 =
Parser (\str ->
case runParser p1 str of
Nothing -> Nothing
Just (f,remaining) -> runParser (f <$> p2) remaining)
abParser :: Parser (Char, Char)
abParser = (\a b -> (a, b)) <$> char 'a' <*> char 'b'
abParser_ :: Parser ()
abParser_ = (\_ _ -> ()) <$> char 'a' <*> char 'b'
intPair :: Parser [Integer]
intPair = (\a _ c -> [a, c]) <$> posInt <*> char ' ' <*> posInt
instance Alternative Parser where
empty = Parser (const Nothing)
p1 <|> p2 = Parser (\str -> case runParser p1 str of
Nothing -> runParser p2 str
something -> something)
intOrUppercase :: Parser ()
intOrUppercase = void posInt <|> void (satisfy isUpper)
|
bibaijin/cis194
|
src/Spring13/Week10/AParser.hs
|
bsd-3-clause
| 2,873 | 0 | 14 | 756 | 696 | 373 | 323 | 43 | 2 |
module App.TeamDetails.AppService (getValidTeam, createNewTeam, findTeamAndAddPerson) where
-- TODO Move to TeamDetails package
import App.Roster.DomainService (validateTeam, validateTeamName, validatePersonName, tryAddPersonToTeam)
import App.TeamDetails.Repository (getTeam, findTeam, saveTeam, saveNewTeam)
import App.TeamDetails.Types as Team (TeamDetails(..), Person(..), newTeam, newPerson)
getValidTeam :: String -> IO (Either String TeamDetails)
getValidTeam name = do
eitherTeam <- getTeam name
return $ validateTeam =<< eitherTeam
createNewTeam :: String -> IO (Either String TeamDetails)
createNewTeam teamName = do
let eitherNewTeam = newTeam <$> validateTeamName teamName
case eitherNewTeam of
Left msg -> return $ Left msg
Right team -> saveNewTeam team
findTeamAndAddPerson :: String -> String -> IO (Either String TeamDetails)
findTeamAndAddPerson personName teamName = do
maybeTeam <- findTeam teamName
case maybeTeam of
Nothing -> return $ Left ("Team " ++ teamName ++ "does not exist")
Just team -> liftResult saveAndReturnSaved (addNewPersonToTeam personName team)
-- Private
---------------
--TODO review this two functions Unify the save return type.
saveAndReturnSaved :: TeamDetails -> IO TeamDetails
saveAndReturnSaved team = saveTeam team >> return team
addNewPersonToTeam :: String -> TeamDetails -> Either String TeamDetails
addNewPersonToTeam pName team = tryAddPersonToTeam team =<< newPerson <$> validatePersonName pName
--TODO Useless function?
liftResult :: (a -> IO b) -> Either String a -> IO (Either String b)
liftResult _ (Left msg) = return $ Left msg
liftResult f (Right a) = do
myB <- f a
return $ Right myB
|
afcastano/cafe-duty
|
src/App/TeamDetails/AppService.hs
|
bsd-3-clause
| 1,894 | 0 | 14 | 464 | 488 | 249 | 239 | 29 | 2 |
-- ------------------------------------------------------------
{- |
Module : Yuuko.Text.XML.HXT.XPath.XPathEval
Copyright : Copyright (C) 2006 Uwe Schmidt
License : MIT
Maintainer : Uwe Schmidt ([email protected])
Stability : experimental
Portability: portable
Version : $Id: XPathEval.hs,v 1.8 2006/10/12 11:51:29 hxml Exp $
The core functions for evaluating the different types of XPath expressions.
Each 'Expr'-constructor is mapped to an evaluation function.
-}
-- ------------------------------------------------------------
module Yuuko.Text.XML.HXT.XPath.XPathEval
( getXPath
, getXPathWithNsEnv
, getXPathSubTrees
, getXPathSubTreesWithNsEnv
, getXPathNodeSet
, getXPathNodeSetWithNsEnv
, evalExpr
)
where
import Yuuko.Text.XML.HXT.XPath.XPathFct
import Yuuko.Text.XML.HXT.XPath.XPathDataTypes
import Yuuko.Text.XML.HXT.XPath.XPathArithmetic
( xPathAdd
, xPathDiv
, xPathMod
, xPathMulti
, xPathUnary
)
import Yuuko.Text.XML.HXT.XPath.XPathParser
( parseXPath )
import Yuuko.Text.XML.HXT.XPath.XPathToString
( xPValue2XmlTrees )
import Yuuko.Text.XML.HXT.XPath.XPathToNodeSet
( xPValue2NodeSet
, emptyNodeSet
)
import Text.ParserCombinators.Parsec
( runParser )
import Data.Maybe
( fromJust )
-- ----------------------------------------
-- the DOM functions
import Yuuko.Text.XML.HXT.DOM.Interface
import qualified Yuuko.Text.XML.HXT.DOM.XmlNode as XN
-- ----------------------------------------
-- the list arrow functions
import Control.Arrow ( (>>>), (>>^) )
import Yuuko.Control.Arrow.ArrowList ( arrL, isA )
import Yuuko.Control.Arrow.ArrowIf ( filterA )
import Yuuko.Control.Arrow.ListArrow ( runLA )
import qualified
Yuuko.Control.Arrow.ArrowTree as AT
import Yuuko.Text.XML.HXT.Arrow.XmlArrow ( ArrowDTD, isDTD, getDTDAttrl )
import Yuuko.Text.XML.HXT.Arrow.Edit ( canonicalizeForXPath )
-- -----------------------------------------------------------------------------
-- |
-- Select parts of a document by an XPath expression.
--
-- The main filter for selecting parts of a document via XPath.
-- The string argument must be a XPath expression with an absolute location path,
-- the argument tree must be a complete document tree.
-- Result is a possibly empty list of XmlTrees forming the set of selected XPath values.
-- XPath values other than XmlTrees (numbers, attributes, tagnames, ...)
-- are convertet to text nodes.
getXPath :: String -> XmlTree -> XmlTrees
getXPath = getXPathWithNsEnv []
-- |
-- Select parts of a document by a namespace aware XPath expression.
--
-- Works like 'getXPath' but the prefix:localpart names in the XPath expression
-- are interpreted with respect to the given namespace environment
getXPathWithNsEnv :: Attributes -> String -> XmlTree -> XmlTrees
getXPathWithNsEnv env s = runLA ( canonicalizeForXPath
>>>
arrL (getXPathValues xPValue2XmlTrees xPathErr (toNsEnv env) s)
)
-- |
-- Select parts of an XML tree by a XPath expression.
--
-- The main filter for selecting parts of an arbitrary XML tree via XPath.
-- The string argument must be a XPath expression with an absolute location path,
-- There are no restrictions on the arument tree.
--
-- No canonicalization is performed before evaluating the query
--
-- Result is a possibly empty list of XmlTrees forming the set of selected XPath values.
-- XPath values other than XmlTrees (numbers, attributes, tagnames, ...)
-- are convertet to text nodes.
getXPathSubTrees :: String -> XmlTree -> XmlTrees
getXPathSubTrees = getXPathSubTreesWithNsEnv []
-- | Same as 'getXPathSubTrees' but with namespace aware XPath expression
getXPathSubTreesWithNsEnv :: Attributes -> String -> XmlTree -> XmlTrees
getXPathSubTreesWithNsEnv nsEnv xpStr
= getXPathValues xPValue2XmlTrees xPathErr (toNsEnv nsEnv) xpStr
-- | compute the node set of an XPath query
getXPathNodeSet :: String -> XmlTree -> XmlNodeSet
getXPathNodeSet = getXPathNodeSetWithNsEnv []
-- | compute the node set of a namespace aware XPath query
getXPathNodeSetWithNsEnv :: Attributes -> String -> XmlTree -> XmlNodeSet
getXPathNodeSetWithNsEnv nsEnv xpStr
= getXPathValues xPValue2NodeSet (const (const emptyNodeSet)) (toNsEnv nsEnv) xpStr
-- | parse xpath, evaluate xpath expr and prepare results
getXPathValues :: (XPathValue -> a) -> (String -> String -> a) -> NsEnv -> String -> XmlTree -> a
getXPathValues cvRes cvErr nsEnv xpStr t
= case (runParser parseXPath nsEnv "" xpStr) of
Left parseError
-> cvErr xpStr (show parseError)
Right xpExpr
-> evalXP xpExpr
where
evalXP xpe
= cvRes xpRes
where
t' = addRoot t -- we need a root node for starting xpath eval
idAttr = ( ("", "idAttr") -- id attributes from DTD (if there)
, idAttributesToXPathValue . getIdAttributes $ t'
)
navTD = ntree t'
xpRes = evalExpr (idAttr:(getVarTab varEnv),[]) (1, 1, navTD) xpe (XPVNode [navTD])
addRoot :: XmlTree -> XmlTree
addRoot t
| XN.isRoot t
= t
| otherwise
= XN.mkRoot [] [t]
xPathErr :: String -> String -> [XmlTree]
xPathErr xpStr parseError
= [XN.mkError c_err ("Syntax error in XPath expression " ++ show xpStr ++ ": " ++ show parseError)]
-- |
-- The main evaluation entry point.
-- Each XPath-'Expr' is mapped to an evaluation function. The 'Env'-parameter contains the set of global variables
-- for the evaluator, the 'Context'-parameter the root of the tree in which the expression is evaluated.
--
evalExpr :: Env -> Context -> Expr -> XPathFilter
evalExpr env cont (GenExpr Or ex)
= boolEval env cont Or ex
evalExpr env cont (GenExpr And ex)
= boolEval env cont And ex
evalExpr env cont (GenExpr Eq ex)
= relEqEval env cont Eq . evalExprL env cont ex
evalExpr env cont (GenExpr NEq ex)
= relEqEval env cont NEq . evalExprL env cont ex
evalExpr env cont (GenExpr Less ex)
= relEqEval env cont Less . evalExprL env cont ex
evalExpr env cont (GenExpr LessEq ex)
= relEqEval env cont LessEq . evalExprL env cont ex
evalExpr env cont (GenExpr Greater ex)
= relEqEval env cont Greater . evalExprL env cont ex
evalExpr env cont (GenExpr GreaterEq ex)
= relEqEval env cont GreaterEq . evalExprL env cont ex
evalExpr env cont (GenExpr Plus ex)
= numEval xPathAdd Plus . toXValue xnumber cont env . evalExprL env cont ex
evalExpr env cont (GenExpr Minus ex)
= numEval xPathAdd Minus . toXValue xnumber cont env . evalExprL env cont ex
evalExpr env cont (GenExpr Div ex)
= numEval xPathDiv Div . toXValue xnumber cont env . evalExprL env cont ex
evalExpr env cont (GenExpr Mod ex)
= numEval xPathMod Mod . toXValue xnumber cont env . evalExprL env cont ex
evalExpr env cont (GenExpr Mult ex)
= numEval xPathMulti Mult . toXValue xnumber cont env . evalExprL env cont ex
evalExpr env cont (GenExpr Unary ex)
= xPathUnary . xnumber cont env . evalExprL env cont ex
evalExpr env cont (GenExpr Union ex)
= unionEval . evalExprL env cont ex
evalExpr env cont (FctExpr name args)
= fctEval env cont name args
evalExpr env _ (PathExpr Nothing (Just lp))
= locPathEval env lp
evalExpr env cont (PathExpr (Just fe) (Just lp))
= locPathEval env lp . evalExpr env cont fe
evalExpr env cont (FilterExpr ex)
= filterEval env cont ex
evalExpr env _ ex
= evalSpezExpr env ex
evalExprL :: Env -> Context -> [Expr] -> XPathValue -> [XPathValue]
evalExprL env cont ex ns
= map (\e -> evalExpr env cont e ns) ex
evalSpezExpr :: Env -> Expr -> XPathFilter
evalSpezExpr _ (NumberExpr (Float 0)) _
= XPVNumber Pos0
evalSpezExpr _ (NumberExpr (Float f)) _
= XPVNumber (Float f)
evalSpezExpr _ (LiteralExpr s) _
= XPVString s
evalSpezExpr env (VarExpr name) v
= getVariable env name v
evalSpezExpr _ _ _
= XPVError "Call to evalExpr with a wrong argument"
-- -----------------------------------------------------------------------------
-- |
-- filter for evaluating a filter-expression
filterEval :: Env -> Context -> [Expr] -> XPathFilter
filterEval env cont (prim:predicates) ns
= case evalExpr env cont prim ns of
new_ns@(XPVNode _) -> evalPredL env predicates new_ns
_ -> XPVError "Return of a filterexpression is not a nodeset"
filterEval _ _ _ _
= XPVError "Call to filterEval without an expression"
-- |
-- returns the union of its arguments, the arguments have to be node-sets.
unionEval :: [XPathValue] -> XPathValue
unionEval
= createDocumentOrder . remDups . unionEval'
where
unionEval' (e@(XPVError _):_) = e
unionEval' (_:e@(XPVError _):_) = e
unionEval' [n@(XPVNode _)] = n
unionEval' ((XPVNode n):(XPVNode m):xs) = unionEval ( (XPVNode (n ++ m)):xs)
unionEval' _ = XPVError "The value of a union ( | ) is not a nodeset"
-- |
-- Equality or relational test for node-sets, numbers, boolean values or strings,
-- each computation of two operands is done by relEqEv'
relEqEval :: Env -> Context -> Op -> [XPathValue] -> XPathValue
relEqEval env cont op
= foldl1 (relEqEv' env cont op)
relEqEv' :: Env -> Context -> Op -> XPathValue -> XPathFilter
relEqEv' _ _ _ e@(XPVError _) _ = e
relEqEv' _ _ _ _ e@(XPVError _) = e
-- two node-sets
relEqEv' env cont op a@(XPVNode _) b@(XPVNode _)
= relEqTwoNodes env cont op a b
-- one node-set
relEqEv' env cont op a b@(XPVNode _)
= relEqOneNode env cont (fromJust $ getOpFct op) a b
relEqEv' env cont op a@(XPVNode _) b
= relEqOneNode env cont (flip $ fromJust $ getOpFct op) b a
-- test without a node-set and equality or not-equality operator
relEqEv' env cont Eq a b = eqEv env cont (==) a b
relEqEv' env cont NEq a b = eqEv env cont (/=) a b
-- test without a node-set and less, less-equal, greater or greater-equal operator
relEqEv' env cont op a b
= XPVBool ((fromJust $ getOpFct op) (toXNumber a) (toXNumber b))
where
toXNumber x = xnumber cont env [x]
-- |
-- Equality or relational test for two node-sets.
-- The comparison will be true if and only if there is a node in the first node-set
-- and a node in the second node-set such that the result of performing the
-- comparison on the string-values of the two nodes is true
relEqTwoNodes :: Env -> Context -> Op -> XPathValue -> XPathFilter
relEqTwoNodes _ _ op (XPVNode ns) (XPVNode ms)
= XPVBool (foldr (\n -> (any (fct op n) (getStrValues ms) ||)) False ns)
where
fct op' n' = (fromJust $ getOpFct op') (stringValue n')
getStrValues = map stringValue
relEqTwoNodes _ _ _ _ _
= XPVError "Call to relEqTwoNodes without a nodeset"
-- |
-- Comparison between a node-set and different type.
-- The node-set is converted in a boolean value if the second argument is of type boolean.
-- If the argument is of type number, the node-set is converted in a number, otherwise it is converted
-- in a string value.
relEqOneNode :: Env -> Context -> (XPathValue -> XPathValue -> Bool) -> XPathValue -> XPathFilter
relEqOneNode env cont fct arg (XPVNode ns)
= XPVBool (any (fct arg) (getStrValues arg ns))
where
getStrValues arg' = map ((fromJust $ getConvFct arg') cont env . wrap) . map stringValue
wrap x = [x]
relEqOneNode _ _ _ _ _
= XPVError "Call to relEqOneNode without a nodeset"
-- |
-- No node-set is involved and the operator is equality or not-equality.
-- The arguments are converted in a common type. If one argument is a boolean value
-- then it is the boolean type. If a number is involved, the arguments have to converted in numbers,
-- else the string type is the common type.
eqEv :: Env -> Context -> (XPathValue -> XPathValue -> Bool) -> XPathValue -> XPathFilter
eqEv env cont fct f@(XPVBool _) g
= XPVBool (f `fct` xboolean cont env [g])
eqEv env cont fct f g@(XPVBool _)
= XPVBool (xboolean cont env [f] `fct` g)
eqEv env cont fct f@(XPVNumber _) g
= XPVBool (f `fct` xnumber cont env [g])
eqEv env cont fct f g@(XPVNumber _)
= XPVBool (xnumber cont env [f] `fct` g)
eqEv env cont fct f g
= XPVBool (xstring cont env [f] `fct` xstring cont env [g])
getOpFct :: Op -> Maybe (XPathValue -> XPathValue -> Bool)
getOpFct Eq = Just (==)
getOpFct NEq = Just (/=)
getOpFct Less = Just (<)
getOpFct LessEq = Just (<=)
getOpFct Greater = Just (>)
getOpFct GreaterEq = Just (>=)
getOpFct _ = Nothing
-- |
-- Filter for accessing the root element of a document tree
getRoot :: XPathFilter
getRoot (XPVNode (n:_))
= XPVNode [getRoot' n]
where
getRoot' tree
= case upNT tree of
Nothing -> tree
Just t -> getRoot' t
getRoot _
= XPVError "Call to getRoot without a nodeset"
-- |
-- Filter for accessing all nodes of a XPath-axis
--
-- * 1.parameter as : axis specifier
--
getAxisNodes :: AxisSpec -> XPathFilter
getAxisNodes as (XPVNode ns)
= XPVNode (concat $ map (fromJust $ lookup as axisFctL) ns)
getAxisNodes _ _
= XPVError "Call to getAxis without a nodeset"
-- |
-- Axis-Function-Table.
-- Each XPath axis-specifier is mapped to the corresponding axis-function
axisFctL :: [(AxisSpec, (NavXmlTree -> NavXmlTrees))]
axisFctL = [ (Ancestor, ancestorAxis)
, (AncestorOrSelf, ancestorOrSelfAxis)
, (Attribute, attributeAxis)
, (Child, childAxis)
, (Descendant, descendantAxis)
, (DescendantOrSelf, descendantOrSelfAxis)
, (Following, followingAxis)
, (FollowingSibling, followingSiblingAxis)
, (Parent, parentAxis)
, (Preceding, precedingAxis)
, (PrecedingSibling, precedingSiblingAxis)
, (Self, selfAxis)
]
-- |
-- evaluates a location path,
-- evaluation of an absolute path starts at the document root,
-- the relative path at the context node
locPathEval :: Env -> LocationPath -> XPathFilter
locPathEval env (LocPath Rel steps)
= evalSteps env steps
locPathEval env (LocPath Abs steps)
= evalSteps env steps . getRoot
evalSteps :: Env -> [XStep] -> XPathFilter
evalSteps env steps ns
= foldl (evalStep env) ns steps
-- |
-- evaluate a single XPath step
-- namespace-axis is not supported
evalStep :: Env -> XPathValue -> XStep -> XPathValue
evalStep _ _ (Step Namespace _ _) = XPVError "namespace-axis not supported"
evalStep _ ns (Step Attribute nt _) = evalAttr nt (getAxisNodes Attribute ns)
evalStep env ns (Step axisSpec nt pr) = evalStep' env pr nt (getAxisNodes axisSpec ns)
evalAttr :: NodeTest -> XPathFilter
evalAttr nt (XPVNode ns)
= XPVNode (foldr (\n -> (evalAttrNodeTest nt n ++)) [] ns)
evalAttr _ _
= XPVError "Call to evalAttr without a nodeset"
evalAttrNodeTest :: NodeTest -> NavXmlTree -> NavXmlTrees
evalAttrNodeTest (NameTest qn) ns@(NT (NTree (XAttr qn1) _) _ _ _)
= if ( ( uri == uri1 && lp == lp1)
||
((uri == "" || uri == uri1) && lp == "*")
)
then [ns]
else []
where
uri = namespaceUri qn
uri1 = namespaceUri qn1
lp = localPart qn
lp1 = localPart qn1
evalAttrNodeTest (TypeTest XPNode) ns@(NT (NTree (XAttr _) _) _ _ _)
= [ns]
evalAttrNodeTest _ _
= []
evalStep' :: Env -> [Expr] -> NodeTest -> XPathFilter
evalStep' env pr nt
= evalPredL env pr . nodeTest nt
evalPredL :: Env -> [Expr] -> XPathFilter
evalPredL env pr n@(XPVNode ns)
= remDups $ foldl (evalPred env 1 (length ns)) n pr
evalPredL _ _ _
= XPVError "Call to evalPredL without a nodeset"
evalPred :: Env -> Int -> Int -> XPathValue -> Expr -> XPathValue
evalPred _ _ _ ns@(XPVNode []) _ = ns
evalPred env pos len (XPVNode (x:xs)) ex
= case testPredicate env (pos, len, x) ex (XPVNode [x]) of
e@(XPVError _) -> e
XPVBool True -> XPVNode (x : n)
XPVBool False -> nextNode
_ -> XPVError "Value of testPredicate is not a boolean"
where nextNode@(XPVNode n) = evalPred env (pos+1) len (XPVNode xs) ex
evalPred _ _ _ _ _
= XPVError "Call to evalPred without a nodeset"
testPredicate :: Env -> Context -> Expr -> XPathFilter
testPredicate env context@(pos, _, _) ex ns
= case evalExpr env context ex ns of
XPVNumber (Float f) -> XPVBool (f == fromIntegral pos)
XPVNumber _ -> XPVBool False
_ -> xboolean context env [evalExpr env context ex ns]
-- |
-- filter for selecting a special type of nodes from the current fragment tree
--
-- the filter works with namespace activated and without namespaces.
-- If namespaces occur in XPath names, the uris are used for matching,
-- else the name prefix
--
-- Bugfix : "*" (or any other name-test) must not match the root node
nodeTest :: NodeTest -> XPathFilter
-- nodeTest (NameTest (QN "" "*" "")) = filterNodes (\n -> isXTagNode n && not (isRootNode n))
-- nodeTest (NameTest (QN _ "*" uri)) = filterNodes (filterd uri)
nodeTest (NameTest q)
| isWildcardTest
= filterNodes (wildcardTest q)
| otherwise
= filterNodes (nameTest q) -- old: (isOfTagNode1 q)
where
isWildcardTest = localPart q == "*"
nodeTest (PI n) = filterNodes isPiNode
where
isPiNode = maybe False ((== n) . qualifiedName) . XN.getPiName
nodeTest (TypeTest t) = typeTest t
nameTest :: QName -> XNode -> Bool
nameTest xpName (XTag elemName _)
| namespaceAware
= localPart xpName == localPart elemName
&&
namespaceUri xpName == namespaceUri elemName
| otherwise
= qualifiedName xpName == qualifiedName elemName
where
namespaceAware = not . null . namespaceUri $ xpName
nameTest _ _ = False
wildcardTest :: QName -> XNode -> Bool
wildcardTest xpName (XTag elemName _)
| namespaceAware
= namespaceUri xpName == namespaceUri elemName
| prefixMatch
= namePrefix xpName == namePrefix elemName
| otherwise
= localPart elemName /= t_root -- all names except the root name "/"
where
namespaceAware = not . null . namespaceUri $ xpName
prefixMatch = not . null . namePrefix $ xpName
wildcardTest _ _ = False
-- |
-- tests whether a node is of a special type
--
typeTest :: XPathNode -> XPathFilter
typeTest XPNode = id
typeTest XPCommentNode = filterNodes XN.isCmt
typeTest XPPINode = filterNodes XN.isPi
typeTest XPTextNode = filterNodes XN.isText
-- |
-- the filter selects the NTree part of a navigable tree and
-- tests whether the node is of the necessary type
--
-- * 1.parameter fct : filter function from the XmlTreeFilter module which tests the type of a node
--
filterNodes :: (XNode -> Bool) -> XPathFilter
filterNodes fct (XPVNode ns)
= XPVNode ([n | n@(NT (NTree node _) _ _ _) <- ns , fct node])
filterNodes _ _
= XPVError "Call to filterNodes without a nodeset"
-- |
-- evaluates a boolean expression, the evaluation is non-strict
boolEval :: Env -> Context -> Op -> [Expr] -> XPathFilter
boolEval _ _ op [] _
= XPVBool (op==And)
boolEval env cont Or (x:xs) ns
= case xboolean cont env [evalExpr env cont x ns] of
e@(XPVError _) -> e
XPVBool True -> XPVBool True
_ -> boolEval env cont Or xs ns
boolEval env cont And (x:xs) ns
= case xboolean cont env [evalExpr env cont x ns] of
e@(XPVError _) -> e
XPVBool True -> boolEval env cont And xs ns
_ -> XPVBool False
boolEval _ _ _ _ _
= XPVError "Call to boolEval with a wrong argument"
-- |
-- returns the value of a variable
getVariable :: Env -> VarName -> XPathFilter
getVariable env name _
= case lookup name (getVarTab env) of
Nothing -> XPVError ("Variable: " ++ show name ++ " not found")
Just v -> v
-- |
-- evaluates a function,
-- computation is done by 'XPathFct.evalFct' which is defined in "XPathFct".
fctEval :: Env -> Context -> FctName -> [Expr] -> XPathFilter
fctEval env cont name args
= evalFct name env cont . evalExprL env cont args
-- |
-- evaluates an arithmetic operation.
--
-- 1.parameter f : arithmetic function from "XPathArithmetic"
--
numEval :: (Op -> XPathValue -> XPathValue -> XPathValue) -> Op -> [XPathValue] -> XPathValue
numEval f op = foldl1 (f op)
-- |
-- Convert list of ID attributes from DTD into a space separated 'XPVString'
--
idAttributesToXPathValue :: XmlTrees -> XPathValue
idAttributesToXPathValue ts
= XPVString (foldr (\ n -> ( (valueOfDTD a_value n ++ " ") ++)) [] ts)
-- |
-- Extracts all ID-attributes from the document type definition (DTD).
--
getIdAttributes :: XmlTree -> XmlTrees
getIdAttributes
= runLA $
AT.getChildren
>>>
isDTD
>>>
AT.deep (isIdAttrType)
-- ----------------------------------------
isIdAttrType :: ArrowDTD a => a XmlTree XmlTree
isIdAttrType = hasDTDAttrValue a_type (== k_id)
valueOfDTD :: String -> XmlTree -> String
valueOfDTD n = concat . runLA ( getDTDAttrl >>^ lookup1 n )
hasDTDAttrValue :: ArrowDTD a => String -> (String -> Bool) -> a XmlTree XmlTree
hasDTDAttrValue an p = filterA $
getDTDAttrl >>> isA (p . lookup1 an)
-- ------------------------------------------------------------
|
nfjinjing/yuuko
|
src/Yuuko/Text/XML/HXT/XPath/XPathEval.hs
|
bsd-3-clause
| 21,272 | 108 | 14 | 4,825 | 5,757 | 3,024 | 2,733 | 364 | 5 |
module Main where
import Test.Tasty
import Test.Tasty.TestSet
import qualified Test.Unit.Module
import qualified Test.Unit.Persistence
import qualified Test.Unit.UserStory
import qualified Test.Property.Persistence
main = do
Test.Tasty.defaultMain $ buildTestTree "" $ do
Test.Unit.Module.tests
Test.Unit.Persistence.tests
Test.Unit.UserStory.tests
Test.Property.Persistence.tests
{-
main = do
Test.Property.Persistence.createTestData 1
-}
|
pgj/bead
|
test/TestMain.hs
|
bsd-3-clause
| 464 | 0 | 10 | 63 | 94 | 58 | 36 | 13 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.