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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings #-}
module InnerEar.Widgets.SpecEval where
import Reflex
import Reflex.Dom
import Data.Map
import Control.Monad
import qualified Data.Text as T
import Data.Monoid((<>))
import Data.Maybe (fromJust)
import InnerEar.Types.Frequency
import InnerEar.Widgets.Utility
import InnerEar.Widgets.Bars
import InnerEar.Types.Score
import InnerEar.Widgets.Labels
evalGraphFrame :: MonadWidget t m => String -> String -> m ()
evalGraphFrame xMainLabel graphLabel = do
faintedYaxis "faintedYaxis"
hzMainLabel "hzMainLabel" xMainLabel
countMainLabel "countMainLabel" "#"
percentageMainLabel "percentageMainLabel" "%"
elClass "div" "graphLabel" $ text graphLabel
return ()
displayMultipleChoiceEvaluationGraph :: (MonadWidget t m, Show a, Ord a) => (String, String, String, String) -> String -> String -> [a] -> Dynamic t (Map a Score) -> m ()
displayMultipleChoiceEvaluationGraph (scoreBarWrapperClass, svgBarContainerClass, svgFaintedLineClass, xLabelClass) graphLabel qLabel possibilities scoreMap = elClass "div" "specEvalWrapper" $ do
scoreList <- mapDyn (\x -> fmap (\y -> Data.Map.lookup y x) possibilities) scoreMap -- m (Dynamic t [Maybe Score])
scoreMap' <- mapDyn (\x -> fromList $ zip possibilities x) scoreList -- (Dynamic t (Map a (Maybe Score)))
-- evalGraphFrame qLabel graphLabel
listWithKey scoreMap' f
return ()
where f k d = scoreBar (scoreBarWrapperClass, svgBarContainerClass, svgFaintedLineClass, xLabelClass) (show k) d
--a historical evaluation graph
displayHistoricalEvaluationGraph :: (MonadWidget t m, Show a, Ord a) => String -> String -> [a] -> Dynamic t (Map a Score) -> m ()
displayHistoricalEvaluationGraph graphLabel qLabel possibilities currentScoreMap = elClass "div" "specEvalWrapper" $ do
currentScoreList <- mapDyn (\x -> fmap (\y -> Data.Map.lookup y x) possibilities) currentScoreMap
currentScoreMap' <- mapDyn (\x -> fromList $ zip possibilities x) currentScoreList
evalGraphFrame qLabel graphLabel
listWithKey currentScoreMap' f -- Dynamic t (Map k v) -> (k -> Dynamic t v -> m a) -> m (Dynamic t (Map k a))
return ()
where
f k d = scoreBarH ("scoreBarWrapperHist","svgBarContainerCurrent", "svgBarContainerHist", "svgFaintedLineCurrent","svgFaintedLineHist", "xLabel") (show k) d
{- x graphLabel qLabel possibilities scoreMap = do
listOfScores <- mapDyn ...
let qLabel' = Line 400 300 200 200
let possibilities = Rect 400 300 200 100
scores <- mapDyn (\x -> Line x 300 150 100) listOfScores
allDrawingInstructions <- mapDyn (\x -> qLabel':possibilities:x) scores
dynSvg allDrawingInstructions -}
| d0kt0r0/InnerEar | src/InnerEar/Widgets/SpecEval.hs | gpl-3.0 | 2,680 | 0 | 16 | 455 | 648 | 337 | 311 | 37 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Shows and processes the upload form.
module Handler.Upload (Options (..), getUploadR, postUploadR, uploadForm, score)
where
import Import
import Control.Monad.Writer hiding (lift)
import Data.Map (elems)
import qualified Data.Text as T
import Database.Persist.Sql (rawSql)
import Network.HTTP.Types.Status (requestEntityTooLarge413)
import Network.Mail.Mime (Address (..), simpleMail, renderSendMail)
import Text.Blaze.Renderer.Text (renderMarkup)
import Text.Hamlet (hamletFile)
import Text.Julius (rawJS)
import Text.Shakespeare.Text (st)
import Account (getUser)
import Handler.Upload.Processing (UploadError (..), processFile, score)
import Util.API (
sendObjectCreated, sendErrorResponse, tooManyRequests429, withFormSuccess
)
import Util.Hmac (Hmac (..))
import Util.Pretty (PrettyFileSize (..), wrappedText)
-- | Options which can be selected by the user when uploading a file.
data Options = Options {
optPublic :: Bool
, optEmail :: Maybe Text
} deriving (Show, Read)
-- Handlers --------------------------------------------------------------------
-- | Shows the home page with the upload form.
getUploadR :: Handler Html
getUploadR = do
((filesWidget, optsWidget), enctype) <- generateFormPost uploadForm
topImages <- runDB getTopImages
extras <- getExtra
let maxFileSize = extraMaxFileSize extras
let maxRequestSize = extraMaxRequestSize extras
defaultLayout $ do
setTitle "Upload a file | getwebb"
$(widgetFile "upload")
where
-- Searchs the ten most popular images. Returns a list of uploads and the
-- URL to their miniatures.
getTopImages = do
let sql = T.unlines [
"SELECT ??"
, "FROM Upload AS upload"
, "INNER JOIN File AS f ON f.id = upload.file"
, "WHERE f.type = 'Image' AND upload.public = 1"
, "ORDER BY upload.score DESC"
, "LIMIT 40;"
]
imgs <- rawSql sql []
return [ (i, DownloadMiniatureR (uploadHmac i)) | Entity _ i <- imgs ]
-- | Uploads a file to the server. Returns a 201 Created with a JSON object
-- which contains the id of the upload, or a 400/413/429 with a JSON array of
-- errors.
postUploadR :: Handler ()
postUploadR = do
-- Allows cross-domain AJAX requests.
-- See <https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS>.
addHeader "Access-Control-Allow-Origin" "*"
((res, _), _) <- runFormPostNoToken uploadForm
withFormSuccess res $ \ (~(file:_), Options public mEmail) -> do
-- Allocates an new admin key if the client doesn't have one.
mAdminKey <- getAdminKey
adminKeyId <- case mAdminKey of
Just (AdminKeyUser (Entity i _) _ _) -> return i
Just (AdminKeyAnon (Entity i _)) -> return i
Nothing -> do
adminKeyId <- runDB newAdminKey
setAdminKey adminKeyId
return adminKeyId
-- Process the file.
eUpload <- processFile adminKeyId file public
case eUpload of
Right upload -> do
let hmac = uploadHmac upload
route = ViewR $ toPathPiece hmac
whenJust mEmail (sendEmailLink upload route)
sendObjectCreated hmac route
Left err -> do
let status = case err of
DailyIPLimitReached -> tooManyRequests429
FileTooLarge -> requestEntityTooLarge413
sendErrorResponse status [err]
--------------------------------------------------------------------------------
-- | Creates a form for the upload and its options.
uploadForm :: Html
-- | Returns two widgets. The first one is for the files selector
-- widget and the second for the options\' widget.
-> MForm Handler (FormResult ([FileInfo], Options), (Widget, Widget))
uploadForm extra = do
tell Multipart
-- File selector
let filesId = "files" :: Text
let filesWidget = [whamlet|
<input name=#{filesId} type=file multiple tabindex=1 autofocus>
^{extra}
|]
-- Retrieves the list of uploaded files.
files <- askFiles
let filesRes = case concat <$> elems <$> files of
Just fs | not (null fs)
-> FormSuccess fs
_
-> FormFailure ["Send at least one file to upload."]
-- Options form
defPriv <- maybe True (userDefaultPublic . entityVal . fst) <$> lift getUser
let publicSettings = FieldSettings {
fsLabel = "Share this file"
, fsTooltip = Just "Publish this file in the public gallery."
, fsId = Nothing, fsName = Just "public", fsAttrs = []
}
(publicRes, publicView) <- mreq checkBoxField publicSettings (Just defPriv)
let emailSettings = FieldSettings {
fsLabel = "Send link by email"
, fsTooltip = Just "Send the link to the uploaded file by email."
, fsId = Nothing, fsName = Just "email"
, fsAttrs = [("placeholder", "Enter an email or leave empty")]
}
(emailRes, emailView) <- mopt emailField emailSettings Nothing
let optsWidget = [whamlet|
<div id="^{toHtml $ fvId publicView}_div">
^{fvInput publicView}
<label for=^{toHtml $ fvId publicView}>^{fvLabel publicView}
<div id="^{toHtml $ fvId emailView}_div">
<label for=^{toHtml $ fvId emailView}>^{fvLabel emailView}
^{fvInput emailView}
|]
-- Combines the results of the form.
let res = (,) <$> filesRes <*> (Options <$> publicRes <*> emailRes)
return (res, (filesWidget, optsWidget))
-- | Sends the link to the upload by email.
sendEmailLink :: Upload -> Route App -> Text -> Handler ()
sendEmailLink upload route email = do
rdr <- getUrlRenderParams
extra <- getExtra
let wrappedTitle = wrappedText (uploadTitle upload) 50
from = Address (Just $ extraAdmin extra) (extraAdminMail extra)
to = Address Nothing email
subject = [st|#{wrappedTitle} | getwebb|]
text = renderMarkup $ [hamlet|
A file named #{wrappedTitle} has been send to you via getwebb.org.
$with Hmac hmacTxt <- uploadHmac upload
Click here on the following link to download this file:
@{ViewR hmacTxt}
Sincerely, the getwebb administrators.
|] rdr
html = renderMarkup $ $(hamletFile "templates/email.hamlet") rdr
liftIO $ simpleMail to from subject text html [] >>= renderSendMail
| RaphaelJ/getwebb.org | Handler/Upload.hs | gpl-3.0 | 6,794 | 18 | 16 | 1,966 | 1,323 | 722 | 601 | -1 | -1 |
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
-- |
-- Module : Main
-- Description : Coursework 2 submission for CM20219 course ran in
-- University of Bath in 2013. Submission by mk440
-- Copyright : (c) Mateusz Kowalczyk 2013
-- License : GPLv3
-- Maintainer : [email protected]
{-# LANGUAGE TemplateHaskell, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import Control.Applicative
import Control.Monad
import Control.Lens
import Data.Time.Clock
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
import Data.IORef
import System.Exit
-- | Specifies a glVertex3f from a 'GLfloat' triple.
vertex3f :: (GLfloat, GLfloat, GLfloat) -> IO ()
vertex3f (x, y, z) = vertex $ Vertex3 x y z
-- Here we create field instances for Vertex3 as convenience.
instance Field1 (Vertex3 a) (Vertex3 a) a a where
_1 k (Vertex3 x y z) = indexed k (0 :: Int) x <&> \x' -> Vertex3 x' y z
instance Field2 (Vertex3 a) (Vertex3 a) a a where
_2 k (Vertex3 x y z) = indexed k (0 :: Int) y <&> \y' -> Vertex3 x y' z
instance Field3 (Vertex3 a) (Vertex3 a) a a where
_3 k (Vertex3 x y z) = indexed k (0 :: Int) z <&> \z' -> Vertex3 x y z'
-- | Encoding of the status of three mouse buttons. Each button is
-- in a state specified by 'KeyState'
data MouseState = MouseState { _leftButton :: KeyState
, _rightButton :: KeyState
, _middleButton :: KeyState
} deriving (Eq, Show)
-- | The position of the eye camera from the origin.
data CameraShift = CameraShift { _cTheta :: GLdouble
, _cPhi :: GLdouble
, _cRadius :: GLdouble
}
deriving (Eq, Show)
-- | Various program flags. Note that rendering 'Info' or other text
-- results in pretty hefty frame rate drop on my (very slow) netbook so it's
-- not advisable to use this unless it's for debugging.
data Flag = Info -- ^ Display information on the screen
| ExtraInfo -- ^ Printing of extra information produced
-- throughout the program.
| Flags -- ^ Show enabled flags in the information.
| ShiftInfo -- ^ Information on current 'CameraShift'
| Middle -- ^ Translate to the middle of many shapes. Only useful
-- with 'dl'. Currently broken
| Shapes -- ^ Render a lot more shapes. For fun.
| DragInfo -- ^ Show information on mouse drag.
| MouseInfo -- ^ Information on 'MouseState'
| Fill -- ^ Fill the shapes we are rendering.
| Lights -- ^ Turns on lighting.
| FramesPerSecond -- ^ Renders frames per seconds. Ironically
-- this causes the FPS to drop.
| Axis -- ^ X/Y/Z axis drawing. X = Red Y = Green Z = Blue
-- Draw from origin to positive <relatively large number>.
| FocusPoint -- ^ Show the current camera focus point.
deriving (Show, Eq)
-- | We carry program state using this data type. We do the disgusting thing
-- and wrap it in 'IORef' (or 'MVar'. It's not as evil as it normally would be
-- considering we're running in the IO monad anyway for OpenGL/GLUT but it's not
-- ideal either.
data ProgramState = ProgramState
{ _cameraShift :: CameraShift
, _mouseState :: MouseState
, _angleState :: GLfloat
, _dragState :: (MouseState, Maybe Position)
-- ^ The second element of the pair
-- indicates the last position we were at
-- during a mouse drag.
, _extraInfo :: [String]
, _flags :: [Flag]
, _timeState :: (DiffTime, Int, Int)
-- ^ Timing information. Last second,
-- number of frames since last second and
-- number of frames in the second
-- beforehand.
, _cameraFocus :: ([Vertex3 GLdouble], Int)
}
-- We generate lenses with Template Haskell here.
makeLenses ''MouseState
makeLenses ''ProgramState
makeLenses ''CameraShift
-- | Enable a 'Flag' for a given 'ProgramState'.
addFlag :: IORef ProgramState -> Flag -> IO ()
addFlag ps f = do
p <- get ps
ps $$! p & flags %~ (\fl -> if f `elem` fl then fl else f : fl)
-- | Clear a 'Flag' from the 'ProgramState'
clearFlag :: IORef ProgramState -> Flag -> IO ()
clearFlag ps f = get ps >>= \p -> ps $$! p & flags %~ filter (/= f)
-- | Toggles a 'Flag' in a 'ProgramState'
toggleFlag :: IORef ProgramState -> Flag -> IO ()
toggleFlag ps f = do
p <- get ps
if f `elem` p ^. flags then clearFlag ps f else addFlag ps f
-- | Helper for '_extraInfo' that will only keep a preset amount of
-- logging information.
(++?) :: [a] -> [a] -> [a]
x ++? y
| length x >= 20 = tail x ++ y
| otherwise = x ++ y
-- | A sensible starting state for the program.
defaultState :: ProgramState
defaultState = ProgramState
{ _cameraShift = CameraShift 3.8 6.8 15
, _mouseState = MouseState Up Up Up
, _angleState = 0.0
, _dragState = (MouseState Up Up Up, Nothing)
, _extraInfo = []
, _flags = [ Flags, Lights, FramesPerSecond
, Main.Fill, DragInfo, MouseInfo, ShiftInfo
, Shapes, Axis, FocusPoint
]
, _timeState = (secondsToDiffTime 0, 0, 0)
, _cameraFocus = (Vertex3 0 0 0 : map tvd (cubeCorners cubeSize), 0)
}
-- | Same as '($=!)' except with left fixity of 0 for convenience. Clashes with
-- '($)' but that's usually not a problem with lenses.
($$!) :: HasSetter s => s a -> a -> IO ()
($$!) = ($=!)
infixl 0 $$!
-- | Helper to convert a 'CameraShift' to 'Vertex3' parametrised
-- by 'GLdouble'.
ctvf :: CameraShift -> Vertex3 GLdouble
ctvf (CameraShift x y z) = Vertex3 x y z
tvd :: (GLfloat, GLfloat, GLfloat) -> Vertex3 GLdouble
tvd (x, y, z) = Vertex3 (realToFrac x) (realToFrac y) (realToFrac z)
cubeVertices :: GLfloat -> [(GLfloat, GLfloat, GLfloat)]
cubeVertices w =
[ ( w, w, w), ( w, w,-w), ( w,-w,-w), ( w,-w, w),
( w, w, w), ( w, w,-w), (-w, w,-w), (-w, w, w),
( w, w, w), ( w,-w, w), (-w,-w, w), (-w, w, w),
(-w, w, w), (-w, w,-w), (-w,-w,-w), (-w,-w, w),
( w,-w, w), ( w,-w,-w), (-w,-w,-w), (-w,-w, w),
( w, w,-w), ( w,-w,-w), (-w,-w,-w), (-w, w,-w) ]
cubeCorners :: GLfloat -> [(GLfloat, GLfloat, GLfloat)]
cubeCorners w =
[ (w, w, w), (-w, w, w), (-w, -w, w), (w, -w, w)
, (w, w, -w), (-w, w, -w), (-w, -w, -w), (w, -w, -w) ]
-- | Renders a cube with edges of a specified length.
cube :: GLfloat -> IO ()
cube w = renderPrimitive Quads $ mapM_ vertex3f (cubeVertices w)
-- | Renders a frame for a cube with edges of a specified length.
cubeFrame :: GLfloat -> IO ()
cubeFrame w = renderPrimitive Lines $ mapM_ vertex3f
[ ( w,-w, w), ( w, w, w), ( w, w, w), (-w, w, w),
(-w, w, w), (-w,-w, w), (-w,-w, w), ( w,-w, w),
( w,-w, w), ( w,-w,-w), ( w, w, w), ( w, w,-w),
(-w, w, w), (-w, w,-w), (-w,-w, w), (-w,-w,-w),
( w,-w,-w), ( w, w,-w), ( w, w,-w), (-w, w,-w),
(-w, w,-w), (-w,-w,-w), (-w,-w,-w), ( w,-w,-w) ]
-- | Update current time in the 'ProgramState' to allow us to count
-- | frames per second rendered.
updateTime :: IORef ProgramState -> IO ()
updateTime ps = do
programState <- get ps
t <- utctDayTime <$> getCurrentTime
let oldTime = programState ^. timeState . _1
let p' = if t - oldTime >= 1
then let allFrames = programState ^. timeState . _2
in programState & timeState .~ (t, 0, allFrames)
else programState
ps $$! p' & timeState . _2 %~ succ
preservingColor :: IO a -> IO ()
preservingColor f = get currentColor >>= \c -> f >> color c
-- | Display callback.
display :: IORef ProgramState -> DisplayCallback
display ps = do
programState <- get ps
let l = Lights `elem` programState ^. flags
f = Main.Fill `elem` programState ^. flags
CameraShift theta phi radius = programState ^. cameraShift
(points, focn) = programState ^. cameraFocus
Vertex3 x y z = points !! focn
clear [ColorBuffer, DepthBuffer]
when (Axis `elem` programState ^. flags)
(preservingMatrix drawAxis >> return ())
loadIdentity
preservingMatrix (renderInfo programState)
lighting $= if' l Enabled Disabled
-- Camera movement
let [nx, ny, nz] = [ radius * cos theta * sin phi
, radius * sin theta * sin phi
, radius * cos phi
]
translate $ Vector3 x y (-z + (-radius))
rotate ((theta - pi) * (180 / pi)) $ Vector3 1 0 0
rotate ((-phi) * (180/pi)) $ Vector3 0 1 0
preservingColor . preservingMatrix $ do
drawCube f
ps $$! programState & angleState %~ (+ 1.0)
writeLog ps [nx, ny, nz]
updateTime ps
swapBuffers
-- | Draws the X, Y and Z axis from origin towards positive <relatively
-- large number>. X axis is red, Y axis is green and Z axis is green.
-- Additionally, horizontal spacers are drawn every 1 unit on each axis.
drawAxis :: IO DisplayList
drawAxis = do
defineNewList CompileAndExecute $ do
c <- get currentColor
let len = 500.0
step = 1
apply3 f (x, y, z) = (f x, f y, f z)
xv = (1.0, 0, 0)
yv = (0.0, 1.0, 0)
zv = (0.0, 0.0, 1.0)
rl = [step , step + step .. len]
preservingMatrix $ do
-- X
color $ Color3 1.0 0.0 (0.0 :: GLfloat)
renderPrimitive Lines $ mapM_ vertex3f $
[ (0.0, 0.0, 0.0)
, apply3 (* len) xv
] ++ concat (map (\x -> [(x, 0, -1) , (x, 0, 1)] ) rl)
-- Y
color $ Color3 0.0 1.0 (0.0 :: GLfloat)
renderPrimitive Lines $ mapM_ vertex3f $
[ (0.0, 0.0, 0.0)
, apply3 (* len) yv
] ++ concat (map (\x -> [(-1, x, 0) , (1, x, 0)] ) rl)
++ concat (map (\x -> [(0, x, -1) , (0, x, 1)] ) rl)
-- Z
color $ Color3 0.0 0.0 (1.0 :: GLfloat)
renderPrimitive Lines $ mapM_ vertex3f $
[ (0.0, 0.0, 0.0)
, apply3 (* len) zv
] ++ concat (map (\x -> [(-1, 0, x) , (1, 0, x)] ) rl)
color c
-- | Renders information using the current 'ProgramState'
renderInfo :: ProgramState -> IO ()
renderInfo p = do
let h f g = if f `elem` p ^. flags then [p ^. g ^. to show] else []
info = if Main.Info `elem` p ^. flags
then (if ExtraInfo `elem` p ^. flags then p ^. extraInfo else [])
++ h MouseInfo mouseState ++ h DragInfo dragState
++ h ShiftInfo cameraShift
++ if FocusPoint `elem` p ^. flags
then let n = p ^. cameraFocus . _2
in [show $ (p ^. cameraFocus . _1) !! n]
else []
++ h Flags flags
else []
fps = if FramesPerSecond `elem` p ^. flags
then map (++ " FPS") (h FramesPerSecond (timeState . _3))
else []
c <- get currentColor
matrixMode $= Projection
preservingMatrix $ do
loadIdentity
Size x y <- get windowSize
ortho2D 0.0 (fromIntegral x) 0.0 (fromIntegral y)
matrixMode $= Modelview 0
preservingMatrix $ do
color $ Color3 1.0 0.0 (0.0 :: GLfloat)
let positions = [ Vertex2 22 (x' :: GLint) | x' <- [22, 44 .. ] ]
r = zip positions . reverse $
if FramesPerSecond `elem` p ^. flags
then info ++ fps
else info
mapM_ (\(p', t) -> rasterPos p' >> renderString Helvetica18 t) r
color c
-- | Draw a face of a cube. Used by 'drawCube'.
drawFace :: Bool -> GLfloat -> IO ()
drawFace filled s =
renderPrimitive (if filled then Polygon else LineLoop) $ do
vertex3f(-s, -s, s)
vertex3f(s, -s, s)
vertex3f(s, s, s)
vertex3f(-s, s, s)
-- | Traditional if_then_else as a function.
if' :: Bool -> a -> a -> a
if' p f g = if p then f else g
cubeSize :: GLfloat
cubeSize = 0.5
-- | Draws a cube or a cube wireframe dependending on the passed in
-- value.
drawCube :: Bool -- ^ If true, the cube is solid. Else, it's wireframe.
-> IO ()
drawCube filled = do
color $ Color3 1.0 0 (0 :: GLdouble)
drawFace filled cubeSize
mapM_ (const $ r q 1 0 0 >> drawFace filled cubeSize) [1 .. 3 :: Integer]
r q 1 0 0
r q 0 1 0
drawFace filled cubeSize
r f 0 1 0
drawFace filled cubeSize
where
f, q :: GLfloat
f = 180.0
q = 90.0
r :: GLfloat -> GLfloat -> GLfloat -> GLfloat -> IO ()
r r' x y z = rotate r' $ Vector3 x y z
main :: IO ()
main = do
_ <- getArgsAndInitialize
initialDisplayMode $= [DoubleBuffered, RGBMode, WithDepthBuffer]
_ <- createWindow "Spinning cube"
ps <- newIORef defaultState
displayCallback $= display ps
idleCallback $= Just idle
keyboardMouseCallback $= Just (keyboardMouse ps)
reshapeCallback $= Just reshape
motionCallback $= Just (motion ps)
depthFunc $= Just Lequal
matrixMode $= Projection
perspective 40.0 1.0 1.0 10.0
matrixMode $= Modelview 0
initGL
mainLoop
-- | Reshape callback. Takes in window size.
reshape :: Size -> IO ()
reshape (Size w h) = do
viewport $= (Position 0 0, Size w h)
matrixMode $= Projection
loadIdentity
frustum (-1) 1 (-1) 1 5 11500
matrixMode $= Modelview 0
-- | Initialize OpenGL options. Includes light model and material
-- attributes.
initGL :: IO ()
initGL = do
lighting $= Enabled
light l $= Enabled
lightModelTwoSide $= Disabled
lightModelAmbient $= Color4 1 1 1 1
materialDiffuse Front $= whiteDir
materialSpecular Front $= whiteDir
materialShininess Front $= 200
diffuse l $= whiteDir
specular l $= whiteDir
position l $= Vertex4 30 30 30 1
shadeModel $= Smooth
clearColor $= Color4 0.5 1.0 0.75 0.0
-- clearColor $= Color4 0.0 0.0 0.0 0.0
cullFace $= Just Back
hint PerspectiveCorrection $= Nicest
initLight
where
l = Light 0
whiteDir = Color4 2 2 2 1
-- | Initialise light (position, diffuse, ambient, …).
initLight :: IO ()
initLight = do
let mSpec = Color4 1 1 1 1
sh = 128
pos = Vertex4 0.2 0.2 0.9 0.0
amb = Color4 0.05 0.05 0.05 1.0
lSpec = Color4 0.99 0.99 0.99 1.0
diff = Color4 0.7 0.7 0.7 1.0
l :: Light
l = Light 0
shadeModel $= Smooth
materialSpecular Front $= mSpec
materialShininess Front $= sh
position l $= pos
specular l $= lSpec
ambient l $= amb
diffuse l $= diff
colorMaterial $= Just (Front, Diffuse)
lighting $= Enabled
light l $= Enabled
-- | Add a line to '_extraInfo' in the program state.
writeLog :: Show a => IORef ProgramState -> a -> IO ()
writeLog ps s = get ps >>= \p -> ps $$! p & extraInfo %~ (++? [show s])
-- | Clears the '_extraInfo' log.
clearLog :: IORef ProgramState -> IO ()
clearLog ps = get ps >>= \p -> ps $$! p & extraInfo .~ []
-- | Idle callback. We just redraw the frame whenever possible.
idle :: IdleCallback
idle = postRedisplay Nothing
-- | A callback for mouse dragging. Deals with offsetting the 'CameraShift' in
-- 'ProgramState'.
motion :: IORef ProgramState -> MotionCallback
motion ps p@(Position newX newY) = do
pState <- get ps
let nowMS = pState ^. mouseState
(oldMS, oldPos) = pState ^. dragState
case oldPos of
Nothing -> ps $$! pState & dragState .~ (nowMS, Just p)
Just (Position oldX oldY) ->
if oldMS == nowMS
then do
let CameraShift st sp sr = pState ^. cameraShift
zDifference = fromIntegral (newY - oldY) + sr
dx = fromIntegral $ newX - oldX
dy = fromIntegral $ newY - oldY
newTheta = st + dy * (pi / 800)
newPhi = sp - dx * (pi / 800)
let p' = case nowMS of
MouseState Down _ _ -> pState & cameraShift
.~ CameraShift newTheta newPhi sr
MouseState _ Down _ -> pState & cameraShift
.~ CameraShift st sp zDifference
MouseState _ _ _ -> pState
ps $$! p' & dragState . _2 .~ Just p
else ps $$! pState & dragState .~ (nowMS, Just p)
-- | Advances camera focus between pre-defined points on the cube. Effectively a
-- poor-man's zipper.
advanceFocus :: IORef ProgramState -> IO ()
advanceFocus ps = do
p <- get ps
let (points, n) = p ^. cameraFocus
ps $$! p & cameraFocus . _2 %~ if n >= (length points - 1)
then const 0
else (+ 1)
-- | Keyboard and mouse callback. Deals with flag toggling and camera shifting.
keyboardMouse :: IORef ProgramState -> KeyboardMouseCallback
keyboardMouse ps key Down _ _ = case key of
Char 'q' -> exitSuccess
Char 'f'-> toggleFlag ps Main.Fill
Char 'r' -> get ps >>= \p -> ps $$! p & cameraShift
.~ defaultState ^. cameraShift
Char 'x' -> onCoord cTheta (+ (pi / 200))
Char 'y' -> onCoord cPhi (+ (pi / 200))
Char 'z' -> onCoord cRadius succ
Char 'X' -> onCoord cTheta (flip (-) (pi / 200))
Char 'Y' -> onCoord cPhi (flip (-) (pi / 200))
Char 'Z' -> onCoord cRadius pred
Char 'l' -> toggleFlag ps Lights
Char 's' -> toggleFlag ps Flags
Char 'i' -> toggleFlag ps Main.Info
Char 'e' -> toggleFlag ps ExtraInfo
Char 'd' -> toggleFlag ps DragInfo
Char 'm' -> toggleFlag ps MouseInfo
Char 't' -> toggleFlag ps ShiftInfo
Char 'p' -> toggleFlag ps FramesPerSecond
Char 'M' -> toggleFlag ps Middle
Char 'S' -> toggleFlag ps Shapes
Char 'a' -> toggleFlag ps Axis
Char 'n' -> advanceFocus ps
MouseButton LeftButton -> setB leftButton
MouseButton RightButton -> setB rightButton
MouseButton MiddleButton -> setB middleButton
MouseButton WheelDown -> get ps >>= \p -> ps $$! p & cameraShift . cRadius
%~ succ
_ -> return ()
where
setB f = do
p <- get ps
ps $$! p & mouseState . f .~ Down & dragState . _2 .~ Nothing
onCoord f g = get ps >>= \p -> ps $$! p & cameraShift . f %~ g
keyboardMouse ps key Up _ _ = case key of
MouseButton LeftButton -> setB leftButton
MouseButton RightButton -> setB rightButton
MouseButton MiddleButton -> setB middleButton
MouseButton WheelUp -> get ps >>= \p -> ps $$! p & cameraShift . cRadius
%~ pred
_ -> return ()
where
setB f = get ps >>= \p -> ps $$! p & mouseState . f .~ Up
| Fuuzetsu/cwk2-cm20219-2013 | Main.hs | gpl-3.0 | 19,244 | 6 | 35 | 5,713 | 6,237 | 3,306 | 2,931 | -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.Dataflow.Projects.Locations.FlexTemplates.Launch
-- 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)
--
-- Launch a job with a FlexTemplate.
--
-- /See:/ <https://cloud.google.com/dataflow Dataflow API Reference> for @dataflow.projects.locations.flexTemplates.launch@.
module Network.Google.Resource.Dataflow.Projects.Locations.FlexTemplates.Launch
(
-- * REST Resource
ProjectsLocationsFlexTemplatesLaunchResource
-- * Creating a Request
, projectsLocationsFlexTemplatesLaunch
, ProjectsLocationsFlexTemplatesLaunch
-- * Request Lenses
, plftlXgafv
, plftlUploadProtocol
, plftlLocation
, plftlAccessToken
, plftlUploadType
, plftlPayload
, plftlProjectId
, plftlCallback
) where
import Network.Google.Dataflow.Types
import Network.Google.Prelude
-- | A resource alias for @dataflow.projects.locations.flexTemplates.launch@ method which the
-- 'ProjectsLocationsFlexTemplatesLaunch' request conforms to.
type ProjectsLocationsFlexTemplatesLaunchResource =
"v1b3" :>
"projects" :>
Capture "projectId" Text :>
"locations" :>
Capture "location" Text :>
"flexTemplates:launch" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] LaunchFlexTemplateRequest :>
Post '[JSON] LaunchFlexTemplateResponse
-- | Launch a job with a FlexTemplate.
--
-- /See:/ 'projectsLocationsFlexTemplatesLaunch' smart constructor.
data ProjectsLocationsFlexTemplatesLaunch =
ProjectsLocationsFlexTemplatesLaunch'
{ _plftlXgafv :: !(Maybe Xgafv)
, _plftlUploadProtocol :: !(Maybe Text)
, _plftlLocation :: !Text
, _plftlAccessToken :: !(Maybe Text)
, _plftlUploadType :: !(Maybe Text)
, _plftlPayload :: !LaunchFlexTemplateRequest
, _plftlProjectId :: !Text
, _plftlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsFlexTemplatesLaunch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plftlXgafv'
--
-- * 'plftlUploadProtocol'
--
-- * 'plftlLocation'
--
-- * 'plftlAccessToken'
--
-- * 'plftlUploadType'
--
-- * 'plftlPayload'
--
-- * 'plftlProjectId'
--
-- * 'plftlCallback'
projectsLocationsFlexTemplatesLaunch
:: Text -- ^ 'plftlLocation'
-> LaunchFlexTemplateRequest -- ^ 'plftlPayload'
-> Text -- ^ 'plftlProjectId'
-> ProjectsLocationsFlexTemplatesLaunch
projectsLocationsFlexTemplatesLaunch pPlftlLocation_ pPlftlPayload_ pPlftlProjectId_ =
ProjectsLocationsFlexTemplatesLaunch'
{ _plftlXgafv = Nothing
, _plftlUploadProtocol = Nothing
, _plftlLocation = pPlftlLocation_
, _plftlAccessToken = Nothing
, _plftlUploadType = Nothing
, _plftlPayload = pPlftlPayload_
, _plftlProjectId = pPlftlProjectId_
, _plftlCallback = Nothing
}
-- | V1 error format.
plftlXgafv :: Lens' ProjectsLocationsFlexTemplatesLaunch (Maybe Xgafv)
plftlXgafv
= lens _plftlXgafv (\ s a -> s{_plftlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plftlUploadProtocol :: Lens' ProjectsLocationsFlexTemplatesLaunch (Maybe Text)
plftlUploadProtocol
= lens _plftlUploadProtocol
(\ s a -> s{_plftlUploadProtocol = a})
-- | Required. The [regional endpoint]
-- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints)
-- to which to direct the request. E.g., us-central1, us-west1.
plftlLocation :: Lens' ProjectsLocationsFlexTemplatesLaunch Text
plftlLocation
= lens _plftlLocation
(\ s a -> s{_plftlLocation = a})
-- | OAuth access token.
plftlAccessToken :: Lens' ProjectsLocationsFlexTemplatesLaunch (Maybe Text)
plftlAccessToken
= lens _plftlAccessToken
(\ s a -> s{_plftlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plftlUploadType :: Lens' ProjectsLocationsFlexTemplatesLaunch (Maybe Text)
plftlUploadType
= lens _plftlUploadType
(\ s a -> s{_plftlUploadType = a})
-- | Multipart request metadata.
plftlPayload :: Lens' ProjectsLocationsFlexTemplatesLaunch LaunchFlexTemplateRequest
plftlPayload
= lens _plftlPayload (\ s a -> s{_plftlPayload = a})
-- | Required. The ID of the Cloud Platform project that the job belongs to.
plftlProjectId :: Lens' ProjectsLocationsFlexTemplatesLaunch Text
plftlProjectId
= lens _plftlProjectId
(\ s a -> s{_plftlProjectId = a})
-- | JSONP
plftlCallback :: Lens' ProjectsLocationsFlexTemplatesLaunch (Maybe Text)
plftlCallback
= lens _plftlCallback
(\ s a -> s{_plftlCallback = a})
instance GoogleRequest
ProjectsLocationsFlexTemplatesLaunch
where
type Rs ProjectsLocationsFlexTemplatesLaunch =
LaunchFlexTemplateResponse
type Scopes ProjectsLocationsFlexTemplatesLaunch =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/userinfo.email"]
requestClient
ProjectsLocationsFlexTemplatesLaunch'{..}
= go _plftlProjectId _plftlLocation _plftlXgafv
_plftlUploadProtocol
_plftlAccessToken
_plftlUploadType
_plftlCallback
(Just AltJSON)
_plftlPayload
dataflowService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsFlexTemplatesLaunchResource)
mempty
| brendanhay/gogol | gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Locations/FlexTemplates/Launch.hs | mpl-2.0 | 6,667 | 0 | 20 | 1,501 | 874 | 510 | 364 | 138 | 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.StorageTransfer.GoogleServiceAccounts.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 Google service account that is used by Storage Transfer
-- Service to access buckets in the project where transfers run or in other
-- projects. Each Google service account is associated with one Google
-- Cloud Platform Console project. Users should add this service account to
-- the Google Cloud Storage bucket ACLs to grant access to Storage Transfer
-- Service. This service account is created and owned by Storage Transfer
-- Service and can only be used by Storage Transfer Service.
--
-- /See:/ <https://cloud.google.com/storage-transfer/docs Storage Transfer API Reference> for @storagetransfer.googleServiceAccounts.get@.
module Network.Google.Resource.StorageTransfer.GoogleServiceAccounts.Get
(
-- * REST Resource
GoogleServiceAccountsGetResource
-- * Creating a Request
, googleServiceAccountsGet
, GoogleServiceAccountsGet
-- * Request Lenses
, gsagXgafv
, gsagUploadProtocol
, gsagAccessToken
, gsagUploadType
, gsagProjectId
, gsagCallback
) where
import Network.Google.Prelude
import Network.Google.StorageTransfer.Types
-- | A resource alias for @storagetransfer.googleServiceAccounts.get@ method which the
-- 'GoogleServiceAccountsGet' request conforms to.
type GoogleServiceAccountsGetResource =
"v1" :>
"googleServiceAccounts" :>
Capture "projectId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GoogleServiceAccount
-- | Returns the Google service account that is used by Storage Transfer
-- Service to access buckets in the project where transfers run or in other
-- projects. Each Google service account is associated with one Google
-- Cloud Platform Console project. Users should add this service account to
-- the Google Cloud Storage bucket ACLs to grant access to Storage Transfer
-- Service. This service account is created and owned by Storage Transfer
-- Service and can only be used by Storage Transfer Service.
--
-- /See:/ 'googleServiceAccountsGet' smart constructor.
data GoogleServiceAccountsGet =
GoogleServiceAccountsGet'
{ _gsagXgafv :: !(Maybe Xgafv)
, _gsagUploadProtocol :: !(Maybe Text)
, _gsagAccessToken :: !(Maybe Text)
, _gsagUploadType :: !(Maybe Text)
, _gsagProjectId :: !Text
, _gsagCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleServiceAccountsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gsagXgafv'
--
-- * 'gsagUploadProtocol'
--
-- * 'gsagAccessToken'
--
-- * 'gsagUploadType'
--
-- * 'gsagProjectId'
--
-- * 'gsagCallback'
googleServiceAccountsGet
:: Text -- ^ 'gsagProjectId'
-> GoogleServiceAccountsGet
googleServiceAccountsGet pGsagProjectId_ =
GoogleServiceAccountsGet'
{ _gsagXgafv = Nothing
, _gsagUploadProtocol = Nothing
, _gsagAccessToken = Nothing
, _gsagUploadType = Nothing
, _gsagProjectId = pGsagProjectId_
, _gsagCallback = Nothing
}
-- | V1 error format.
gsagXgafv :: Lens' GoogleServiceAccountsGet (Maybe Xgafv)
gsagXgafv
= lens _gsagXgafv (\ s a -> s{_gsagXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
gsagUploadProtocol :: Lens' GoogleServiceAccountsGet (Maybe Text)
gsagUploadProtocol
= lens _gsagUploadProtocol
(\ s a -> s{_gsagUploadProtocol = a})
-- | OAuth access token.
gsagAccessToken :: Lens' GoogleServiceAccountsGet (Maybe Text)
gsagAccessToken
= lens _gsagAccessToken
(\ s a -> s{_gsagAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
gsagUploadType :: Lens' GoogleServiceAccountsGet (Maybe Text)
gsagUploadType
= lens _gsagUploadType
(\ s a -> s{_gsagUploadType = a})
-- | Required. The ID of the Google Cloud Platform Console project that the
-- Google service account is associated with.
gsagProjectId :: Lens' GoogleServiceAccountsGet Text
gsagProjectId
= lens _gsagProjectId
(\ s a -> s{_gsagProjectId = a})
-- | JSONP
gsagCallback :: Lens' GoogleServiceAccountsGet (Maybe Text)
gsagCallback
= lens _gsagCallback (\ s a -> s{_gsagCallback = a})
instance GoogleRequest GoogleServiceAccountsGet where
type Rs GoogleServiceAccountsGet =
GoogleServiceAccount
type Scopes GoogleServiceAccountsGet =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient GoogleServiceAccountsGet'{..}
= go _gsagProjectId _gsagXgafv _gsagUploadProtocol
_gsagAccessToken
_gsagUploadType
_gsagCallback
(Just AltJSON)
storageTransferService
where go
= buildClient
(Proxy :: Proxy GoogleServiceAccountsGetResource)
mempty
| brendanhay/gogol | gogol-storage-transfer/gen/Network/Google/Resource/StorageTransfer/GoogleServiceAccounts/Get.hs | mpl-2.0 | 5,905 | 0 | 16 | 1,262 | 711 | 420 | 291 | 106 | 1 |
module OptimizeThis where
digitSum :: Integer -> Integer
-- this is not fast enough!
-- digitSum n = if n<10 then n else n `rem` 10 + digitSum (n `div` 10)
-- this is not either
digitSum = sum . (read <$>) . (return <$>) . show
| ice1000/OI-codes | codewars/301-400/micro-optimization-digit-sum.hs | agpl-3.0 | 230 | 0 | 8 | 49 | 41 | 26 | 15 | 3 | 1 |
module Physics.Object where
import qualified Data.Vec as V
import Data.Vec
import Physics.Mesh
import Physics.Mesh.FaceVertex
import Data.Vec.Quaternion
type Quat = Quaternion Double
-- | Objects within a space are identified by integers.
type ObjectId = Int
data Body = Body {
bMass :: !Double,
bPosition :: !(Vec3 Double), -- ^ The absolute position of the center of mass.
bVelocity :: !(Vec3 Double),
bForce :: !(Vec3 Double), -- ^ Force accumulator; zeroed every timestep.
bAngularMass :: !Mat33D, -- ^ Also known as the mass moment of inertia.
bAngularPosition :: !Quat, -- ^ Unit quaternion. Transforms object frame to world frame.
bAngularVelocity :: !(Vec3 Double), -- ^ Axis-magnitude representation of angular velocity.
-- TODO: use angular momentum instead, Equal to the product of angular mass and angular velocity.
bAngularForce :: !(Vec3 Double), -- ^ Torque accumulator; zeroed every timestep.
bDrag :: !Double, -- ^ The coefficient of linear, velocity-dependent drag.
bAngularDrag :: !Double -- ^ Coefficient of linear, angular-velocity-dependent drag.
}
deriving (Show)
defaultBody :: Body
defaultBody = Body {
bMass = 1,
bPosition = vec 0,
bVelocity = vec 0,
bForce = vec 0,
bAngularMass = packMat $ diagonal (vec 1),
bAngularPosition = Q (1:.0:.0:.0:.()),
bAngularVelocity = vec 0,
bAngularForce = vec 0,
bDrag = 0,
bAngularDrag = 0
}
addForce :: Vec3 Double -> Body -> Body
addForce f b = b { bForce = bForce b + f }
-- | @addForceAt r f@ increments a 'Body''s force and torque accumulators to have a force @f@ applied at the point @r@ in global coordinates.
addForceAt :: Vec3 Double -> Vec3 Double -> Body -> Body
addForceAt r f b = b {
bForce = bForce b + f,
bAngularForce = bAngularForce b + crossp (r - bPosition b) f
}
-- | @addTorque r@ adds a pure torque with no associated linear force.
addTorque :: Vec3 Double -> Body -> Body
addTorque r b = b {
bAngularForce = bAngularForce b + r
}
-- | Map from body coordinates to space coordinates.
bodyToSpace :: Body -> Vec3 Double -> Vec3 Double
bodyToSpace b r = bPosition b + qrotate (bAngularPosition b) r
-- | Map from space (global) coordinates to body coordinates.
spaceToBody :: Body -> Vec3 Double -> Vec3 Double
spaceToBody b r = qrotate (recip (bAngularPosition b)) (r - bPosition b)
-- TODO: provide utilities for calculating angular masses
-- TODO later: parameterize on the Mesh type, or use an object-oriented adapter
-- | Collision geometry in body coordinates.
data Shape
= TriMesh !FaceVertexMesh
-- TODO: | Sphere !Double
scaleShape :: Vec3 Double -> Shape -> Shape
scaleShape s (TriMesh m) = TriMesh (mapVertices (s*) m)
data Object = Object {
oBody :: Body,
oShape :: Shape
}
oModifyBody :: (Body -> Body) -> Object -> Object
oModifyBody f o = o { oBody = f (oBody o) }
-- | 'Packed' version of 'cross'.
-- TODO: move this function somewhere appropriate
crossp :: Vec3 Double -> Vec3 Double -> Vec3 Double
crossp a b = (a2*b3-a3*b2):.(a3*b1-a1*b3):.(a1*b2-a2*b1):.()
where (a1,a2,a3) = (get n0 a, get n1 a, get n2 a)
(b1,b2,b3) = (get n0 b, get n1 b, get n2 b)
-- | Like 'normalize', but returns the zero vector instead of NaN when the norm is zero.
-- TODO: move this function somewhere appropriate
normalize' :: (Eq b, Floating b, Num u, ZipWith b b b u u u, Map b b u u, Fold u b) => u -> u
normalize' v = let n = norm v in if n == 0 then v else V.map (/n) v
| gmaslov/rigbo3 | src/Physics/Object.hs | lgpl-3.0 | 3,523 | 0 | 12 | 762 | 983 | 532 | 451 | 82 | 2 |
{- Um número inteiro não negativo diz-se perfeito se é igual à soma dos seus
divisores próprios. Por exemplo, 6=2+3+1. Faça um programa que recebe
um inteiro e decide se este é ou não perfeito.
-}
divisoresDeNumero :: Int -> [Int]
divisoresDeNumero num =
[ x | x <- [1 .. metadeNumero], ((mod num x) == 0)]
where metadeNumero = floor(fromIntegral num / 2)
ehPerfeito :: Int -> Bool
ehPerfeito num = if ((sum (divisoresDeNumero num)) == num) then True else False
main = do
valor1 <- getLine
print (ehPerfeito (read valor1))
| erijonhson/ufcg-plp-e-aplicacoes | praticando_programacao_funcional_parte_1/numero-perfeito.hs | apache-2.0 | 560 | 0 | 11 | 121 | 152 | 80 | 72 | 9 | 2 |
{- #############################################################################
Sample code from:
Simon Thompson - Haskell: the Craft of Functional Programming, 2011
++++ Addison-Wesley ++++
http://www.haskellcraft.com/craft3e/Home.html
############################################################################# -}
module Craft3e.Chapter07 where
import Test.QuickCheck
import Data.Char
import Prelude hiding ( product
, and
, or
, concat
, getLine
, (++))
numbers :: [Integer]
numbers = [42, 15, 78, 9, 1]
singleton :: [Integer]
singleton = [42]
xs :: [Integer]
xs = [4, 2, 1, 3, 2, 3]
{-
Ex 7.1: returns the first integer in a list plus one, if there is one, and
returns zero otherwise.
-}
firstPlusOne :: [Integer] -> Integer
firstPlusOne [] = 0
firstPlusOne (x:_) = x + 1
{-
Ex 7.2: adds together the first two integers in a list, if a list contains
at least two elements; returns the head element if the list contains one,
and returns zero otherwise.
-}
addFirstTwo :: [Integer] -> Integer
addFirstTwo [] = 0
addFirstTwo [x] = x
addFirstTwo (x:y:ys) = x + y
{- Ex 7.3 -}
firstPlusOne' :: [Integer] -> Integer
firstPlusOne' xs = sum $ take 1 (map (+1) xs)
addFirstTwo' :: [Integer] -> Integer
addFirstTwo' xs = sum $ take 2 xs
{- Ex 7.4: returns the first digit (0 - 9) in the string -}
firstDigit :: String -> Char
firstDigit "" = '\0'
firstDigit (c:cs) | isDigit c = c
| otherwise = firstDigit cs
{- Ex 7.5 -}
product :: [Integer] -> Integer
product [] = 1
product (x:xs) = x * product xs
{- Ex 7.6 -}
and :: [Bool] -> Bool
and [] = True
and (False:_) = False
and (True:xs) = and xs
or :: [Bool] -> Bool
or [] = False
or (x:xs) | x == True = True
| otherwise = or xs
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
concat :: [[a]] -> [a]
concat [] = []
concat (xs:xss) = xs ++ concat xss
elem' :: Integer -> [Integer] -> Bool
elem' _ [] = False
elem' x' (x:xs) | x == x' = True
| otherwise = elem' x' xs
doubleAll :: [Integer] -> [Integer]
doubleAll [] = []
doubleAll (x:xs) = (x * 2) : doubleAll xs
doubleAll' :: [Integer] -> [Integer]
doubleAll' xs = [2 * x | x <- xs]
selectEven :: [Integer] -> [Integer]
selectEven (x:y:ys) = y : selectEven ys
selectEven _ = []
selectEven' :: [Integer] -> [Integer]
selectEven' xs = [x | (i,x) <- zip [1..] xs , even i]
iSort :: [Integer] -> [Integer]
iSort [] = []
iSort (x:xs) = ins x (iSort xs)
ins :: Integer -> [Integer] -> [Integer]
ins x [] = [x]
ins x rest@(y:ys) | x <= y = x : rest
| otherwise = y : (ins x ys)
{- Ex 7.8 -}
elemNum :: Integer -> [Integer] -> Integer
elemNum _ [] = 0
elemNum x (y:ys) = (if x == y then 1 else 0) + elemNum x ys
{-
Ex 7.9 returns the list of elements of xs which occur exactly once.
For example, unique [4, 2, 1, 3, 2, 3] is [4, 1]
The function is O(n^2)
-}
unique :: [Integer] -> [Integer]
unique [] = []
unique (x:xs) = let rest = [y | y <- xs , y /= x]
in if isDupl x then unique rest
else x : unique rest
where isDupl x = any (== x) xs
{- Ex 7.11 -}
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
unzip' :: [(a, b)] -> ([a], [b])
unzip' [] = ([], [])
unzip' ((x,y):ys) = let (f, s) = unzip' ys
in (x : f, y : s)
{- Ex 7.12 -}
minAndMax :: [Integer] -> (Integer, Integer)
minAndMax [] = error "Empty list"
minAndMax [x] = (x, x)
minAndMax (x:xs) = let (min', max') = minAndMax xs
in (min x min', max x max')
minAndMax' :: [Integer] -> (Integer, Integer)
minAndMax' [] = error "Prelude.minAndMax: empty list"
minAndMax' [x] = (x, x)
minAndMax' xs = let (y:ys) = iSort xs
in (y, last ys)
{- Ex 7.16 -}
iSort' :: (Integer -> [Integer] -> [Integer]) -> [Integer] -> [Integer]
iSort' _ [] = []
iSort' f (x:xs) = f x (iSort' f xs)
ins' :: Integer -> [Integer] -> [Integer]
ins' x [] = [x]
ins' x (y:ys) | x >= y = x : (y : ys)
| otherwise = y : (ins' x ys)
ins'' :: Integer -> [Integer] -> [Integer]
ins'' x [] = [x]
ins'' x l@(y:ys) | x == y = l
| x <= y = x : l
| otherwise = y : (ins'' x ys)
{- Ex 7.19 -}
sortPairs :: [(Integer, Integer)] -> [(Integer, Integer)]
sortPairs [] = []
sortPairs (x:xs) = ins x (sortPairs xs)
where ins x [] = [x]
ins x@(k,v) (y@(k',_):ys) | k <= k' = x : y : ys
| otherwise = y : (ins x ys)
partition :: (a -> Bool) -> [a] -> ([a], [a])
partition _ [] = ([], [])
partition p (x:xs) = let (t, f) = partition p xs
in if (p x) then (x : t, f)
else (t, x : f)
qSort :: [Integer] -> [Integer]
qSort [] = []
qSort (pivot:xs) = let (left, right) = partition (<=pivot) xs
in (qSort left) ++ [pivot] ++ (qSort right)
{- Ex 7.20 -}
drop' :: Int -> [a] -> [a]
drop' _ [] = []
drop' n l@(x:xs) | n <= 0 = l
| n > 0 = drop' (n - 1) xs
drop_prop :: Int -> [Integer] -> Bool
drop_prop n xs = drop n xs == drop' n xs
splitAt' :: Int -> [a] -> ([a], [a])
splitAt' _ [] = ([], [])
splitAt' n l@(x:xs) | n <= 0 = ([], l)
| otherwise = let (f, s) = splitAt' (n - 1) xs
in (x : f, s)
splitAt_prop :: Int -> [Integer] -> Bool
splitAt_prop n xs = splitAt n xs == splitAt' n xs
{- Ex 7.21 -}
take' :: Int -> [a] -> [a]
take' n (x:xs) | n > 0 = x : take' (n - 1) xs
take' _ _ = []
{- Ex 7.22 -}
zip' :: ([a], [b]) -> [(a, b)]
zip' ((x:xs),(y:ys)) = (x,y) : zip' (xs, ys)
zip' _ = []
zipAndUnzip_prop :: [Integer] -> [Integer] -> Property
zipAndUnzip_prop xs ys = (length xs == length ys) ==>
let ps = (xs, ys)
in unzip' (zip' ps) == ps
{- Ex 7.23 -}
zip3' :: [a] -> [b] -> [c] -> [(a, b, c)]
zip3' (x:xs) (y:ys) (z:zs) = (x, y, z) : (zip3' xs ys zs)
zip3' _ _ _ = []
zip3'' :: [a] -> [b] -> [c] -> [(a, b, c)]
zip3'' xs ys zs = map (\ ((x,y),z) -> (x,y,z)) $ zip (zip xs ys) zs
{- Ex 7.24 -}
qSort' :: [Integer] -> [Integer]
qSort' [] = []
qSort' (pivot:xs) = let (l, r) = partition (<= pivot) xs
in (qSort' r) ++ [pivot] ++ (qSort' l)
qSort'' :: [Integer] -> [Integer]
qSort'' [] = []
qSort'' (pivot:xs) = (qSort'' l) ++ [pivot] ++ (qSort'' r)
where l = [x | x <- xs , x < pivot]
r = [x | x <- xs , x > pivot]
{- Ex 7.25 -}
sublist :: Eq a => [a] -> [a] -> Bool
sublist [] _ = True
sublist _ [] = False
sublist (x:xs) (y:ys) = if (x == y)
then sublist xs ys
else sublist (x:xs) ys
subseq :: Eq a => [a] -> [a] -> Bool
subseq [] _ = True
subseq _ [] = False
subseq xs ys = find xs ys False
where find _ [] found = found
find [] _ found = found
find (h:hs) (s:ss) found = if (h == s)
then find hs ss True
else find xs ss False
{- Example: text processing -}
whitespace :: [Char]
whitespace = ['\n', '\t', ' ']
isWhitespace :: Char -> Bool
isWhitespace = \ch -> elem ch whitespace
getWord :: String -> String
getWord [] = []
getWord (c:cs) = if isWhitespace c
then ""
else c : getWord cs
dropWord :: String -> String
dropWord [] = []
dropWord (c:cs) = if isWhitespace c
then c : cs
else dropWord cs
dropSpace :: String -> String
dropSpace [] = []
dropSpace (c:cs) | isWhitespace c = dropSpace cs
| otherwise = c : cs
type Word = String
type Line = [Word]
splitWords :: String -> [Word]
splitWords "" = []
splitWords xs = let str = dropSpace xs
in (getWord str) : splitWords (dropSpace $ dropWord str)
getLine :: Int -> [Word] -> Line
getLine _ [] = []
getLine 0 _ = []
getLine len (w:ws) = let wordLength = length w
remaining = len - wordLength
in if remaining <= 0
then []
else w : getLine remaining ws
{- Ex 7.27 -}
dropLine :: Int -> [Word] -> Line
dropLine _ [] = []
dropLine 0 ws = ws
dropLine len (w:ws) = let wordLength = length w
remaining = len - wordLength
in if remaining > 0
then dropLine remaining ws
else w: ws
lineLen :: Int
lineLen = 20
oneRing :: String
oneRing = "One Ring to rule them all, One Ring to find them, " ++
"One Ring to bring them all and in the darkness bind them"
splitLines :: [Word] -> [Line]
splitLines [] = []
splitLines ws = (getLine lineLen ws) : splitLines (dropLine lineLen ws)
fill :: String -> [Line]
fill = splitLines . splitWords
{- Ex 7.28 -}
joinLine :: Line -> String
joinLine [] = ""
joinLine (w:ws) = w ++ " " ++ joinLine ws
{- Ex 7.29 -}
joinLines :: [Line] -> String
joinLines [] = ""
joinLines (l:ls) = (joinLine l) ++ joinLines ls
{- Ex 7.32: returns the number of characters, words and lines -}
wc :: String -> (Int,Int,Int)
wc [] = (0, 0, 0)
wc cs = (length chars, length words, length lines)
where lines = fill $ dropSpace cs
words = concat [words | words <- lines]
chars = concat [ch | ch <- words]
{- Ex 7.11 -}
isPalin :: String -> Bool
isPalin s = let str = [c | c <- s , isLetter c] in compare str (reverse str)
where compare "" "" = True
compare (a:as) (b:bs) = if compCh a b
then True && compare as bs
else False
compCh m n = toUpper m == toUpper n | CarloMicieli/fun-with-haskell | src/craft3e/Chapter07.hs | apache-2.0 | 10,172 | 13 | 13 | 3,493 | 4,211 | 2,291 | 1,920 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Site.Vault where
import Prelude hiding (id)
import Blaze.ByteString.Builder (toByteString)
import Control.Monad.Trans
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (unpack)
import Data.List (sort)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
-- import Heist
import qualified Heist.Interpreted as I
-- import qualified Heist.Compiled as C
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Hdbc
import Snap.Snaplet.Heist
import Snap.Snaplet.Session
import Text.JSON
import Text.XmlHtml hiding (render)
import Application
import Config
import Database
import Site.Common
import Site.Utils
import Types
-- |
-- Vault action
--
vault :: AppHandler ()
vault = do
isAdminLogin <- with sessLens $ getFromSession "isAdminLogin"
maybe (render "vaultlogin") (\_ -> vaultMain) isAdminLogin
vaultMain :: AppHandler ()
vaultMain = render "vault"
vaultPostsList :: AppHandler ()
vaultPostsList = do
posts <- vaultGetPostsList
writeBS $ T.encodeUtf8 $ T.pack $ showJSValue (JSObject $ toJSObject
[ ("success", JSBool True)
, ("result", showJSON posts)
]) ""
vaultEdit :: AppHandler ()
vaultEdit = do
request <- getRequest
id <- decodedParam "id"
post <- getPost' id
case rqMethod request of
POST -> vaultSave
_ -> heistLocal (I.bindSplice "vault-form" $ vaultPostForm post) $
render "vaultedit"
where
getPost' :: HasHdbc m c s => ByteString -> m Post
getPost' "" = liftIO newPost
getPost' id = getPostById id
-- TODO there should be a way to simplify this function
vaultGetPost :: AppHandler Post
vaultGetPost = do
id <- decodedPostParam "id"
title <- decodedPostParam "title"
text <- decodedPostParam "text"
url <- decodedPostParam "url"
date <- decodedPostParam "date"
published <- decodedPostParam "published"
special <- decodedPostParam "special"
tags <- decodedPostParam "tags"
return Post
{ postId = read $ unpack id -- TODO validate
, postTitle = T.decodeUtf8 title
, postText = T.replace "\r\n" "\n" $ T.decodeUtf8 text
, postDate = read $ unpack date -- TODO check for format errors
, postUrl = T.decodeUtf8 url -- TODO check for duplicate
, postPublished = published /= ""
, postSpecial = special /= ""
, postTags = sort $ stringToTags $ T.decodeUtf8 tags
}
vaultSave :: AppHandler ()
vaultSave = do
post <- vaultGetPost
savePost post
redirect "/vault"
-- TODO digestive functors
vaultPostForm :: Post -> I.Splice AppHandler
vaultPostForm (Post id title text url date published special tags) =
return
[ Element "form"
[ ("class", "form-horizontal post-form")
, ("method", "post")
]
[ Element "input"
[ ("type", "hidden")
, ("name", "id")
, ("id", "post-id")
, ("value", T.pack $ show id)
] []
, Element "fieldset" []
[ Element "legend" [] [TextNode "Редактирование записи"]
, inputText "Заголовок" "title" title
, inputText "Url" "url" url
, inputText "Дата" "date" $ T.pack $ show date
, inputCheckbox "Опубликовано" "published" published
, inputCheckbox "Специальный" "special" special
, textarea "Текст" "text" text
, inputText "Теги" "tags" $ tagsToString tags
, Element "div" [("class", "form-actions")]
[ Element "button"
[ ("type", "submit")
, ("class", "btn btn-primary")
]
[TextNode "Сохранить"]
, Element "button"
[ ("type", "reset")
, ("class", "btn")
]
[TextNode "Отмена"]
, Element "button"
[ ("class", "btn btn-refresh") ]
[ TextNode "Обновить" ]
]
]
]
]
where
inputText :: Text -> Text -> Text -> Node
inputText fieldLabel name value = field fieldLabel name [
Element "input" [("type", "text"), ("name", name),
("class", "input-fullwidth"), ("id", "post-" `T.append` name),
("value", value)] []
]
inputCheckbox :: Text -> Text -> Bool -> Node
inputCheckbox fieldLabel name value = field fieldLabel name [
Element "input"
([("type", "checkbox"), ("name", name),
("id", "post-" `T.append` name)] ++
[("checked", "checked") | value])
[]
]
textarea :: Text -> Text -> Text -> Node
textarea fieldLabel name value = field fieldLabel name [
Element "textarea" [("name", name),
("id", "post-" `T.append` name),
("class", "input-fullwidth monospace"), ("rows", "20")]
[TextNode value]
]
field :: Text -> Text -> [Node] -> Node
field fieldLabel fieldName fieldControl =
Element "div" [("class", "control-group")] [
Element "label" [("class", "control-label"),
("for", "post-" `T.append` fieldName)] [
TextNode fieldLabel
],
Element "div" [("class", "controls")] fieldControl
]
vaultRenderPost :: AppHandler ()
vaultRenderPost = do
post <- vaultGetPost
writeBS $ toByteString $ renderHtmlFragment UTF8 [renderSinglePost False post]
vaultCheckUrl :: AppHandler ()
vaultCheckUrl = do
id' <- decodedPostParam "id"
url <- decodedPostParam "url"
result <- vaultValidateUrl (T.decodeUtf8 id') (T.decodeUtf8 url)
if result
then writeBS "{\"result\":true}"
else writeBS "{\"result\":false}"
vaultAction :: AppHandler ()
vaultAction = do
action <- decodedPostParam "action"
case action of
"login" -> do
login <- decodedPostParam "login"
password <- decodedPostParam "password"
if (login == adminLogin) && (password == adminPassword)
then do
with sessLens $ do
setInSession "isAdminLogin" "1"
commitSession
redirect "/vault"
else heistLocal (I.bindString "error" "Неверные данные") $
render "vaultlogin"
"logout" -> do
with sessLens $ do
deleteFromSession "isAdminLogin"
commitSession
redirect "/vault"
_ -> redirect "/vault"
vaultDelete :: AppHandler ()
vaultDelete = do
id <- decodedParam "id"
deletePost id
redirect "/vault"
vaultAllowed :: AppHandler () -> AppHandler ()
vaultAllowed action = do
isAdminLogin <- with sessLens $ getFromSession "isAdminLogin"
maybe (redirect "/vault") (\_ -> action) isAdminLogin
| dikmax/haskell-blog | src/Site/Vault.hs | bsd-2-clause | 6,838 | 0 | 18 | 1,901 | 1,883 | 988 | 895 | 174 | 4 |
-- ghost-control is the server-side tool to add new repositories and users.
{-# OPTIONS_GHC -fno-cse #-}
{-# Language CPP #-}
{-# Language DeriveDataTypeable #-}
{-# Language RecordWildCards #-}
module Main where
import Paths_ghost (version)
import Data.Version (showVersion)
import System.Console.CmdArgs.Implicit
import System.Directory
( copyFile, createDirectoryIfMissing, doesFileExist, getHomeDirectory
)
import System.FilePath ((</>), (<.>))
import System.IO (hFlush, hPutStrLn, withFile, IOMode(WriteMode), stdout)
import Ghost (refreshAuthorizedKeys, runAndWaitProcess)
versionString :: String
versionString =
"Ghost " ++ showVersion version ++ " Copyright (c) 2012 Vo Minh Thu."
#ifdef USE_LINODE
++ "\n(Ghost is built with Linode API support.)"
#endif
main :: IO ()
main = (processCmd =<<) $ cmdArgs $
modes
[ cmdInit, cmdAddUser, cmdAddRepository
]
&= summary versionString
&= program "ghost-control"
data Cmd =
Init
| AddUser
{ addUserPublicKeyPath :: String
, addUserName :: String
}
| AddRepository
{ addRepoName :: String
, addRepoUserName :: String
}
deriving (Data, Typeable)
cmdInit :: Cmd
cmdInit = Init
&= help "Initialize Ghost (server-side)."
cmdAddUser :: Cmd
cmdAddUser = AddUser
{ addUserPublicKeyPath = ""
&= typ "PUBLIC KEY PATH"
&= help "path to user's public key"
&= explicit
&= name "k"
&= name "key"
, addUserName = ""
&= typ "USERNAME"
&= help "user name"
&= explicit
&= name "u"
&= name "user"
} &= help "Add a user to Ghost."
&= explicit
&= name "add-user"
cmdAddRepository :: Cmd
cmdAddRepository = AddRepository
{ addRepoName = ""
&= typ "REPOSITORY NAME"
&= help "the name of repository to create"
&= explicit
&= name "repo"
, addRepoUserName = ""
&= typ "USERNAME"
&= help "user name for which to add a new repository"
&= explicit
&= name "u"
&= name "user"
} &= help "Add a repository to Ghost."
&= explicit
&= name "add-repository"
processCmd :: Cmd -> IO ()
processCmd Init = do
putStrLn "Ghost: server-side initialization."
home <- getHomeDirectory
let authorizedKeys = home </> ".ssh" </> "authorized_keys"
administratorKeys = home </> "administrator" </> "keys"
_ <- createDirectoryIfMissing True $ home </> "administrator"
_ <- createDirectoryIfMissing True $ home </> "users"
_ <- createDirectoryIfMissing True $ home </> "gits"
_ <- createDirectoryIfMissing True $ home </> "run/staging/nginx"
_ <- createDirectoryIfMissing True $ home </> "run/production/nginx"
withFile (home </> "run" </> "nginx.conf") WriteMode $ \h -> do
hPutStrLn h $ "include " ++ home ++ "/run/staging/nginx/*.conf;"
hPutStrLn h $ "include " ++ home ++ "/run/production/nginx/*.conf;"
b <- doesFileExist $ authorizedKeys
if b
then do
putStrLn $ "Prior authorized_keys file found, " ++
"copying it as administrator key."
-- TODO make sure there is a single key in it. For now, it assumes this
-- is the key copied by setup-ghost-archlinux.sh.
copyFile authorizedKeys administratorKeys
else putStrLn $ "No prior authorized_keys file found."
refreshAuthorizedKeys "/home/ghost/bin/ghost-command"
putStrLn "Ghost server-side initialization complete."
putStrLn "Add the following line to your main Nginx configuration"
putStrLn "file (inside an `http {..}` block.):"
putStrLn $ " include " ++ home ++ "/run/nginx.conf;"
putStrLn "Add the following line to your sudoers file:"
putStrLn " ghost ALL=(ALL) NOPASSWD: /etc/rc.d/nginx"
putStrLn "(so the post-update hook can instruct Nginx to reload its configuration)."
processCmd AddUser{..} = do
putStrLn "Ghost: adding a new user."
home <- getHomeDirectory
-- TODO validate username (forbid "administrator", just in case)
-- TODO validate key
-- TODO actually handle more than one key
let userKeys = home </> "users" </> addUserName </> "keys"
_ <- createDirectoryIfMissing True $ home </> "users" </> addUserName
b <- doesFileExist addUserPublicKeyPath
if b
then do
copyFile addUserPublicKeyPath userKeys
else putStrLn $ "File " ++ addUserPublicKeyPath ++ " not found."
refreshAuthorizedKeys "/home/ghost/bin/ghost-command"
processCmd AddRepository{..} = do
putStrLn "Ghost: adding a new repository."
hFlush stdout
home <- getHomeDirectory
let repoDir = home </> "users" </> addRepoUserName </> addRepoName <.> "git"
-- TODO check username
-- TODO check repository name
_ <- runAndWaitProcess "git"
["init", "--bare", repoDir]
Nothing
copyFile ("bin" </> "ghost-post-update")
(repoDir </> "hooks" </> "post-update")
return ()
| noteed/ghost | bin/ghost-control.hs | bsd-3-clause | 4,731 | 0 | 15 | 970 | 1,021 | 512 | 509 | 118 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Api.Theorems
( API
, handlers
) where
import Api.Base
import Api.Helpers
import Data.Aeson
import qualified Models.Theorem as Theorem
type API = Paginated Theorem
:<|> Body Theorem :> Authenticated :> POST (Entity Theorem)
:<|> Capture "theorem_id" TheoremId
:> ( GET (Entity Theorem)
:<|> "revisions" :> Paginated Revision
:<|> Body Theorem :> Authenticated :> PUT (Entity Theorem)
:<|> Authenticated :> DELETE (Entity Theorem)
)
handlers :: ServerT API Handler
handlers = getPage []
:<|> withUser . Theorem.create
:<|> ( \_id -> get404 _id
:<|> revisions _id
:<|> withUser . Theorem.update _id
:<|> (withUser $ Theorem.delete _id)
)
instance FromText TheoremId where
fromText = idFromText
instance FromJSON Theorem where
parseJSON = error "Theorem parseJSON"
instance ToJSON (Page Theorem) where
toJSON = pageJSON "theorems" $
\(Entity _id Theorem{..}) -> object
[ "id" .= _id
, "antecedent" .= theoremAntecedent
, "consequent" .= theoremConsequent
]
instance ToJSON (Entity Theorem) where
toJSON (Entity _id Theorem{..}) = object
[ "id" .= _id
, "antecedent" .= theoremAntecedent
, "consequent" .= theoremConsequent
, "description" .= theoremDescription
]
| jamesdabbs/pi-base-2 | src/Api/Theorems.hs | bsd-3-clause | 1,627 | 0 | 20 | 454 | 399 | 208 | 191 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{- |
Module : Data.Graph.Simple.Vertex
Description : Newtype wrapper for graph vertices
Copyright : Stefan Höck
Maintainer : Stefan Höck
Stability : experimental
This module provides an abstract newtype wrapper for
graph vertices. This gives certain guaranties about vertices,
mainly that they stay within certain bounds. Vertices
can range from 0 to an upper bound which depends on the
system on which the application runs (see 'maxVertex').
-}
module Data.Graph.Simple.Vertex (
-- * Class
Vertex, unVertex
-- * Constructors
, vertex, vertexMay, unsafeVertex
-- * Bounds
, minVAsInt, maxVAsInt, minVertex, maxVertex
) where
import Control.DeepSeq (NFData)
-- | Newtype representing vertices in a graph
--
-- Internally, a vertex is just an Int but to make
-- sure that only valid vertices are created, the
-- newtype's constructor is not made publi.
newtype Vertex = Vertex { unVertex ∷ Int }
deriving (Eq, Ord, NFData)
instance Show Vertex where
show = show . unVertex
instance Bounded Vertex where
minBound = minVertex
maxBound = maxVertex
instance Enum Vertex where
fromEnum = unVertex
toEnum = vertex
-- This is a hack for uncluttering the syntax when using
-- vertices. Not sure whether we should really do this.
instance Num Vertex where
(Vertex a) + (Vertex b) = vertex $ a + b
(Vertex a) * (Vertex b) = vertex $ a * b
abs = id
negate = id
signum _ = Vertex 1
fromInteger = vertex . fromInteger
-- | Create a vertex from an Int
-- Returns Nothing if the Int is out of
-- valid bounds.
vertexMay ∷ Int → Maybe Vertex
vertexMay v | isValidVertex v = Just $ Vertex v
| otherwise = Nothing
-- | Create a vertex from an Int
-- Used i `mod` maxVAsInt if i is out of bounds.
vertex ∷ Int → Vertex
vertex v | isValidVertex v = Vertex v
| otherwise = Vertex $ v `mod` maxVAsInt
-- | Create a vertex from an Int
-- No bounds checking for maximum performance. Highly
-- unsafe! USE AT YOUR OWN RISK
{-# INLINE unsafeVertex #-}
unsafeVertex ∷ Int → Vertex
unsafeVertex = Vertex
-- | Min and max integer bounds for vertices
minVAsInt, maxVAsInt ∷ Int
minVAsInt = 0
maxVAsInt = (floor . sqrt $ maxD) - 1
where maxD ∷ Double
maxD = fromIntegral (maxBound ∷ Int)
-- | The minimum vertex
minVertex ∷ Vertex
minVertex = Vertex minVAsInt
-- | The maximal allowed vertex
--
-- Note that this corresponds to √(maxBound ∷ Int), so
-- on 32-Bit systems, this is 46'339, while on 64-Bit
-- systems, it is 3'037'000'498.
maxVertex ∷ Vertex
maxVertex = Vertex maxVAsInt
isValidVertex ∷ Int → Bool
isValidVertex v = minVAsInt <= v && v <= maxVAsInt
| stefan-hoeck/labeled-graph | Data/Graph/Simple/Vertex.hs | bsd-3-clause | 2,754 | 0 | 8 | 603 | 471 | 266 | 205 | -1 | -1 |
module Main where
import System.Environment(getArgs)
import LevOps
main = do
[s,m,n] <- fmap (map read) getArgs
mapM_ (print . maxDegree s) [m..n]
| cullina/Extractor | src/DegreeMain.hs | bsd-3-clause | 153 | 0 | 10 | 28 | 72 | 39 | 33 | 6 | 1 |
module Toy.Execution.Data
( In
, Out
, InOut
, Meta (..)
, withEmptyInput
) where
import Data.Text (Text)
import Data.Text.Buildable (Buildable (..))
import Formatting ((%))
import qualified Formatting as F
import Toy.Base (Value)
type In = [Value]
type Out = [Value]
type InOut = (In, Out)
data Meta = Meta
{ metaName :: Text
, metaBody :: Text
}
instance Buildable Meta where
build Meta{..} =
F.bprint ("\n=== "%F.stext%" ===\n"%F.stext%"\n--^--^--\n")
metaName metaBody
withEmptyInput :: Out -> InOut
withEmptyInput = ([], )
| Martoon-00/toy-compiler | src/Toy/Execution/Data.hs | bsd-3-clause | 669 | 0 | 12 | 222 | 204 | 125 | 79 | -1 | -1 |
{-# LANGUAGE ImplicitParams, TupleSections #-}
module Frontend.StatementInline(statSimplify,
statAddNullTypes,
procStatToCFA) where
import Control.Monad
import Control.Monad.State
import Data.List
import Data.Maybe
import qualified Data.Traversable as Tr
import Util hiding (name,trace)
import Frontend.Inline
import Frontend.Spec
import Pos
import Name
import Frontend.NS
import Frontend.Statement
import Frontend.Expr
import Frontend.TVar
import Frontend.Method
import Frontend.Type
import Frontend.TypeOps
import Frontend.ExprOps
import Frontend.ExprInline
import Internal.PID
import qualified Internal.IExpr as I
import qualified Internal.CFA as I
import qualified Internal.IVar as I
import qualified Internal.ISpec as I
import qualified Internal.IType as I
statSimplify :: (?spec::Spec, ?scope::Scope) => Statement -> NameGen Statement
statSimplify s = (liftM $ sSeq (pos s) (stLab s)) $ statSimplify' s
statSimplify' :: (?spec::Spec, ?scope::Scope) => Statement -> NameGen [Statement]
statSimplify' (SVarDecl p _ v) =
case varInit v of
Just e -> do asn <- statSimplify' $ SAssign p Nothing (ETerm (pos $ varName v) [varName v]) e
return $ (SVarDecl p Nothing v) : asn
Nothing -> return [SVarDecl p Nothing v]
statSimplify' (SReturn p _ (Just e)) = do
(ss,e') <- exprSimplify e
return $ ss ++ [SReturn p Nothing (Just e')]
statSimplify' (SSeq p _ ss) = (liftM $ return . SSeq p Nothing) $ mapM statSimplify ss
statSimplify' (SPar p _ ss) = (liftM $ return . SPar p Nothing) $ mapM statSimplify ss
statSimplify' (SForever p _ s) = (liftM $ return . SForever p Nothing) $ statSimplify s
statSimplify' (SDo p _ b c) = do (ss,c') <- exprSimplify c
b' <- statSimplify b
return [SDo p Nothing (sSeq (pos b) Nothing (b':ss)) c']
statSimplify' (SWhile p _ c b) = do (ss,c') <- exprSimplify c
b' <- statSimplify b
return $ ss ++ [SWhile p Nothing c' (sSeq (pos b) Nothing (b':ss))]
statSimplify' (SFor p _ (mi, c, s) b) = do i' <- case mi of
Nothing -> return []
Just i -> (liftM return) $ statSimplify i
(ss,c') <- exprSimplify c
s' <- statSimplify s
b' <- statSimplify b
return $ i' ++ ss ++ [SFor p Nothing (Nothing, c',s') (sSeq (pos b) Nothing (b':ss))]
statSimplify' (SChoice p _ ss) = liftM (return . SChoice p Nothing) $ mapM statSimplify ss
statSimplify' (SInvoke p _ mref mas) = -- Order of argument evaluation is undefined in C;
-- Go left-to-right
do (ss, as') <- liftM unzip $ mapM (maybe (return ([], Nothing)) ((liftM $ mapSnd Just) . exprSimplify)) mas
return $ (concat ss) ++ [SInvoke p Nothing mref as']
statSimplify' (SWait p _ c) = do (ss,c') <- exprSimplify c
return $ case ss of
[] -> [SWait p Nothing c']
_ -> (SPause p Nothing) : (ss ++ [SAssume p Nothing c'])
statSimplify' (SAssert p _ c) = do (ss,c') <- exprSimplify c
return $ ss ++ [SAssert p Nothing c']
statSimplify' (SAssume p _ c) = do (ss,c') <- exprSimplify c
return $ ss ++ [SAssume p Nothing c']
statSimplify' (SAssign p _ l r) = -- Evaluate lhs first
do (ssl,l') <- exprSimplify l
ssr <- exprSimplifyAsn p l' r
return $ ssl ++ ssr
statSimplify' (SITE p _ c t me) = do (ss,c') <- exprSimplify c
t' <- statSimplify t
me' <- Tr.sequence $ fmap statSimplify me
return $ ss ++ [SITE p Nothing c' t' me']
statSimplify' (SCase p _ c cs md) = -- Case labels must be side-effect-free, so it is ok to
-- evaluate them in advance
do (ssc,c') <- exprSimplify c
(sscs,clabs') <- (liftM unzip) $ mapM exprSimplify (fst $ unzip cs)
cstats <- mapM statSimplify (snd $ unzip cs)
md' <- Tr.sequence $ fmap statSimplify md
return $ concat sscs ++ ssc ++ [SCase p Nothing c' (zip clabs' cstats) md']
statSimplify' st = return [st{stLab = Nothing}]
----------------------------------------------------------
-- Convert statement to CFA
----------------------------------------------------------
statToCFA :: (?spec::Spec, ?procs::[I.Process], ?nestedmb::Bool, ?xducer::Bool) => I.Loc -> Statement -> State CFACtx I.Loc
statToCFA before s = do
when (isJust $ stLab s) $ ctxPushLabel (sname $ fromJust $ stLab s)
after <- statToCFA0 before s
when (isJust $ stLab s) ctxPopLabel
return after
statToCFA0 :: (?spec::Spec, ?procs::[I.Process], ?nestedmb::Bool, ?xducer::Bool) => I.Loc -> Statement -> State CFACtx I.Loc
statToCFA0 before (SSeq _ _ ss) = foldM statToCFA before ss
statToCFA0 before s@(SIn _ _ l r) = do sc <- gets ctxScope
let ?scope = sc
li <- exprToIExprDet l
ri <- exprToIExprDet r
ctxLocSetAct before (I.ActStat s)
ctxIn before li ri (I.ActStat s)
statToCFA0 before s@(SOut _ _ l r) = do sc <- gets ctxScope
let ?scope = sc
let SeqSpec _ t = tspec $ typ' $ exprType r
li <- exprToIExpr l t
ri <- exprToIExprDet r
ctxLocSetAct before (I.ActStat s)
ctxInsTrans' before $ I.TranStat $ I.SOut li ri
statToCFA0 before s@(SPause _ _) = do ctxLocSetAct before (I.ActStat s)
ctxPause before I.true (I.ActStat s)
statToCFA0 before s@(SWait _ _ c) = do ctxLocSetAct before (I.ActStat s)
ci <- exprToIExprDet c
ctxPause before ci (I.ActStat s)
statToCFA0 before s@(SStop _ _) = do ctxLocSetAct before (I.ActStat s)
ctxFinal before
statToCFA0 before (SVarDecl _ _ v) | isJust (varInit v) = return before
statToCFA0 before (SVarDecl _ _ v) | otherwise = do
sc <- gets ctxScope
let ?scope = sc
let scalars = exprScalars $ ETerm nopos [name v]
foldM (\loc e -> do e' <- exprToIExprDet e
let val = case tspec $ typ' $ exprType e of
BoolSpec _ -> I.BoolVal False
UIntSpec _ w -> I.UIntVal w 0
SIntSpec _ w -> I.SIntVal w 0
EnumSpec _ es -> I.EnumVal $ sname $ head es
PtrSpec _ t -> I.NullVal $ mkType $ Type sc t
ctxInsTrans' loc $ I.TranStat $ e' I.=: I.EConst val)
before scalars
statToCFA0 before s@stat = do ctxLocSetAct before (I.ActStat s)
after <- ctxInsLoc
statToCFA' before after stat
return after
-- Only safe to call from statToCFA. Do not call this function directly!
statToCFA' :: (?spec::Spec, ?procs::[I.Process], ?nestedmb::Bool, ?xducer::Bool) => I.Loc -> I.Loc -> Statement -> State CFACtx ()
statToCFA' before _ (SReturn _ _ rval) = do
-- add transition before before to return location
mlhs <- gets ctxLHS
ret <- gets ctxRetLoc
case rval of
Nothing -> ctxInsTrans before ret I.TranReturn
Just v -> case mlhs of
Nothing -> ctxInsTrans before ret I.TranReturn
Just lhs -> do sc@(ScopeMethod _ m) <- gets ctxScope
let t = fromJust $ methRettyp m
vi <- exprToIExprs v t
let asns = map I.TranStat
$ zipWith I.SAssign (I.exprScalars lhs (mkType $ Type sc t))
(concatMap (uncurry I.exprScalars) vi)
aftargs <- ctxInsTransMany' before asns
ctxInsTrans aftargs ret I.TranReturn
statToCFA' before after s@(SPar _ _ ps) = do
Just (EPIDProc pid) <- gets ctxEPID
-- child process pids
let pids = map (childPID pid . sname . fromJust . stLab) ps
-- enable child processes
aften <- ctxInsTransMany' before $ map (\pid' -> I.TranStat $ mkEnVar pid' Nothing I.=: I.true) pids
let mkFinalCheck n = I.disj $ map (\loc -> mkPCEq pcfa pid' (mkPC pid' loc)) $ I.cfaFinal pcfa
where pid' = childPID pid n
p = fromJustMsg ("mkFinalCheck: process " ++ show pid' ++ " unknown")
$ find ((== n) . I.procName) ?procs
pcfa = I.procCFA p
-- pause and wait for all of them to reach final states
aftwait <- ctxPause aften (I.conj $ map (mkFinalCheck . sname . fromJust . stLab) ps) (I.ActStat s)
-- Disable forked processes and bring them back to initial states
aftreset <- ctxInsTransMany' aftwait $ map (\st -> let n = sname $ fromJust $ stLab st
pid' = childPID pid n
pcfa = I.procCFA $ fromJust $ find ((== n) . I.procName) ?procs
in mkPCAsn pcfa pid' (mkPC pid' I.cfaInitLoc)) ps
aftdisable <- ctxInsTransMany' aftreset $ map (\pid' -> I.TranStat $ mkEnVar pid' Nothing I.=: I.false) pids
ctxInsTrans aftdisable after I.TranNop
statToCFA' before after (SForever _ _ stat) = do
ctxPushBrkLoc after
-- create target for loopback transition
loopback <- ctxInsTrans' before I.TranNop
-- loc' = end of loop body
loc' <- statToCFA loopback stat
-- loop-back transition
ctxInsTrans loc' loopback I.TranNop
ctxPopBrkLoc
statToCFA' before after (SDo _ _ stat cond) = do
cond' <- exprToIExpr cond (BoolSpec nopos)
ctxPushBrkLoc after
-- create target for loopback transition
loopback <- ctxInsTrans' before I.TranNop
aftbody <- statToCFA loopback stat
ctxLocSetAct aftbody (I.ActExpr cond)
ctxPopBrkLoc
-- loop-back transition
ctxInsTrans aftbody loopback (I.TranStat $ I.SAssume cond')
-- exit loop transition
ctxInsTrans aftbody after (I.TranStat $ I.SAssume $ I.EUnOp Not cond')
statToCFA' before after (SWhile _ _ cond stat) = do
cond' <- exprToIExpr cond (BoolSpec nopos)
-- create target for loopback transition
loopback <- ctxInsTrans' before I.TranNop
ctxLocSetAct loopback (I.ActExpr cond)
ctxInsTrans loopback after (I.TranStat $ I.SAssume $ I.EUnOp Not cond')
-- after condition has been checked, before the body
befbody <- ctxInsTrans' loopback (I.TranStat $ I.SAssume cond')
-- body
ctxPushBrkLoc after
aftbody <- statToCFA befbody stat
-- loop-back transition
ctxInsTrans aftbody loopback I.TranNop
ctxPopBrkLoc
statToCFA' before after (SFor _ _ (minit, cond, inc) body) = do
cond' <- exprToIExpr cond (BoolSpec nopos)
aftinit <- case minit of
Nothing -> return before
Just st -> statToCFA before st
-- create target for loopback transition
loopback <- ctxInsTrans' aftinit I.TranNop
ctxLocSetAct loopback (I.ActExpr cond)
ctxInsTrans loopback after (I.TranStat $ I.SAssume $ I.EUnOp Not cond')
-- before loop body
befbody <- ctxInsTrans' loopback $ I.TranStat $ I.SAssume cond'
ctxPushBrkLoc after
aftbody <- statToCFA befbody body
-- after increment is performed at the end of loop iteration
aftinc <- statToCFA aftbody inc
ctxPopBrkLoc
-- loopback transition
ctxInsTrans aftinc loopback I.TranNop
statToCFA' before after (SChoice _ _ ss) = do
v <- ctxInsTmpVar Nothing $ mkChoiceType $ length ss
_ <- mapIdxM (\s i -> do aftAssume <- ctxInsTrans' before (I.TranStat $ I.SAssume $ I.EVar (I.varName v) I.=== mkChoice v i)
aft <- statToCFA aftAssume s
ctxInsTrans aft after I.TranNop) ss
return ()
statToCFA' before _ (SBreak _ _) = do
brkLoc <- gets ctxBrkLoc
ctxInsTrans before brkLoc I.TranNop
statToCFA' before after s@(SInvoke _ _ mref mas) = do
sc <- gets ctxScope
let meth = snd $ getMethod sc mref
methInline before after meth mas Nothing (I.ActStat s)
statToCFA' before after (SAssert _ _ cond) | ?xducer = do
cond' <- exprToIExprDet cond
ctxInsTrans before after (I.TranStat $ I.SAssert cond')
statToCFA' before after (SAssert _ _ cond) = do
cond' <- exprToIExprDet cond
when (cond' /= I.false) $ ctxInsTrans before after (I.TranStat $ I.SAssume cond')
when (cond' /= I.true) $ do aftcond <- ctxInsTrans' before (I.TranStat $ I.SAssume $ I.EUnOp Not cond')
ctxErrTrans aftcond after
statToCFA' before after (SAssume _ _ cond) = do
cond' <- exprToIExprDet cond
ctxInsTrans before after (I.TranStat $ I.SAssume cond')
statToCFA' before after (SAssign _ _ lhs e@(EApply _ mref margs)) = do
sc <- gets ctxScope
let meth = snd $ getMethod sc mref
methInline before after meth margs (Just lhs) (I.ActExpr e)
statToCFA' before after (SAssign _ _ lhs rhs) = do
sc <- gets ctxScope
let ?scope = sc
let t = mkType $ exprType lhs
lhs' <- exprToIExprDet lhs
rhs' <- exprToIExprs rhs (exprTypeSpec lhs)
ctxInsTransMany before after $ map I.TranStat
$ zipWith I.SAssign (I.exprScalars lhs' t)
(concatMap (uncurry I.exprScalars) rhs')
statToCFA' before after (SITE _ _ cond sthen mselse) = do
cond' <- exprToIExpr cond (BoolSpec nopos)
befthen <- ctxInsTrans' before (I.TranStat $ I.SAssume cond')
aftthen <- statToCFA befthen sthen
ctxInsTrans aftthen after I.TranNop
befelse <- ctxInsTrans' before (I.TranStat $ I.SAssume $ I.EUnOp Not cond')
aftelse <- case mselse of
Nothing -> return befelse
Just selse -> statToCFA befelse selse
ctxInsTrans aftelse after I.TranNop
statToCFA' before after (SCase _ _ e cs mdef) = do
e' <- exprToIExprDet e
let (vs,ss) = unzip cs
vs0 <- mapM exprToIExprDet vs
let vs1 = map (\(c, prev) -> let cond = (I.EBinOp Eq e' c)
dist = let ?pred = [] in
map (I.EBinOp Neq c)
$ filter ((\eq -> (not $ I.isConstExpr eq) || I.evalConstExpr eq == I.BoolVal True) . I.EBinOp Eq c)
$ prev
in I.conj (cond:dist))
$ zip vs0 (inits vs0)
let negs = I.conj $ map (I.EBinOp Neq e') vs0
let cs' = case mdef of
Nothing -> (zip vs1 $ map Just ss) ++ [(negs, Nothing)]
Just def -> (zip vs1 $ map Just ss) ++ [(negs, Just def)]
_ <- mapM (\(c,mst) -> do befst <- ctxInsTrans' before (I.TranStat $ I.SAssume c)
aftst <- case mst of
Nothing -> return befst
Just st -> statToCFA befst st
ctxInsTrans aftst after I.TranNop) cs'
return ()
statToCFA' before after s@(SMagic _ _) | ?nestedmb = do
-- move action label to the pause location below
ctxLocSetAct before I.ActNone
-- don't wait for $magic in a nested magic block
aftpause <- ctxPause before I.true (I.ActStat s) -- (I.ActStat $ atPos s p)
-- debugger expects a nop-transition here
ctxInsTrans aftpause after I.TranNop
| otherwise = do
ctxLocSetAct before I.ActNone
-- magic block flag
---aftcheck <- ctxInsTrans' before $ I.TranStat $ I.SAssume $ mkMagicVar I.=== I.false
aftmag <- ctxInsTrans' before $ I.TranStat $ mkMagicVar I.=: I.true
-- wait for magic flag to be false
aftwait <- ctxPause aftmag mkMagicDoneCond (I.ActStat s) --(I.ActStat $ atPos s p)
ctxInsTrans aftwait after I.TranNop
-- where
-- p = case constr of
-- Left i -> pos i
-- Right c -> pos c
statToCFA' before after (SMagExit _ _) =
ctxInsTrans before after $ I.TranStat $ mkMagicVar I.=: I.false
statToCFA' before after (SDoNothing _ _) =
ctxInsTrans before after $ I.TranNop
methInline :: (?spec::Spec, ?procs::[I.Process], ?nestedmb::Bool, ?xducer::Bool) => I.Loc -> I.Loc -> Method -> [Maybe Expr] -> Maybe Expr -> I.LocAction -> State CFACtx ()
methInline before after meth margs mlhs act = do
-- save current context
mepid <- gets ctxEPID
let mpid = case mepid of
Just (EPIDProc pid) -> Just pid
_ -> Nothing
let sc = ScopeMethod tmMain meth
lhs <- case mlhs of
Nothing -> return Nothing
Just lhs -> (liftM Just) $ exprToIExprDet lhs
-- set input arguments
aftarg <- setArgs before meth margs
-- set return location
retloc <- ctxInsLoc
aftret <- ctxInsTrans' retloc I.TranReturn
--ctxLocSetAct aftret act
-- clear break location
ctxPushBrkLoc $ error "break outside a loop"
-- change syntactic scope
ctxPushScope sc aftret lhs (methodLMap mpid meth)
-- build CFA of the method
aftcall <- ctxInsTrans' aftarg (I.TranCall meth aftret)
aftbody <- statToCFA aftcall (fromRight $ methBody meth)
ctxInsTrans aftbody retloc I.TranNop
-- restore syntactic scope
ctxPopScope
-- copy out arguments
aftout <- copyOutArgs aftret meth margs
-- pause after task invocation
aftpause <- if elem (methCat meth) [Task Controllable] && (mepid /= Just EPIDCont || ?nestedmb == True)
then ctxPause aftout I.true act
else do ctxLocSetAct aftout act
return aftout
ctxInsTrans aftpause after I.TranNop
-- restore context
ctxPopBrkLoc
-- assign input arguments to a method
setArgs :: (?spec::Spec) => I.Loc -> Method -> [Maybe Expr] -> State CFACtx I.Loc
setArgs before meth margs = do
mepid <- gets ctxEPID
let nsid = maybe (NSID Nothing Nothing) (\epid -> epid2nsid epid (ScopeMethod tmMain meth)) mepid
foldM (\bef (farg,Just aarg) -> do aarg' <- exprToIExprs aarg (tspec farg)
let t = mkType $ Type (ScopeTemplate tmMain) (tspec farg)
ctxInsTransMany' bef $ map I.TranStat
$ zipWith I.SAssign (I.exprScalars (mkVar nsid farg) t)
(concatMap (uncurry I.exprScalars) aarg'))
before $ filter (\(a,_) -> argDir a == ArgIn) $ zip (methArg meth) margs
-- copy out arguments
copyOutArgs :: (?spec::Spec) => I.Loc -> Method -> [Maybe Expr] -> State CFACtx I.Loc
copyOutArgs loc meth margs = do
mepid <- gets ctxEPID
let nsid = maybe (NSID Nothing Nothing) (\epid -> epid2nsid epid (ScopeMethod tmMain meth)) mepid
foldM (\loc' (farg,aarg) -> do aarg' <- exprToIExprDet aarg
let t = mkType $ Type (ScopeTemplate tmMain) (tspec farg)
ctxInsTransMany' loc' $ map I.TranStat
$ zipWith I.SAssign (I.exprScalars aarg' t)
(I.exprScalars (mkVar nsid farg) t)) loc
$ map (mapSnd fromJust)
$ filter (isJust . snd)
$ filter ((== ArgOut) . argDir . fst)
$ zip (methArg meth) margs
------------------------------------------------------------------------------
-- Postprocessing
------------------------------------------------------------------------------
statAddNullTypes :: I.Spec -> I.Statement -> I.Statement
statAddNullTypes spec (I.SAssume (I.EBinOp Eq e (I.EConst (I.NullVal _)))) = let ?spec = spec in
I.SAssume (I.EBinOp Eq e (I.EConst $ I.NullVal $ I.exprType e))
statAddNullTypes _ s = s
----------------------------------------------------------
-- Top-level function: convert process statement to CFA
----------------------------------------------------------
procStatToCFA :: (?spec::Spec, ?procs::[I.Process], ?nestedmb::Bool, ?xducer::Bool) => Statement -> I.Loc -> State CFACtx I.Loc
procStatToCFA stat before = do
after <- statToCFA before stat
ctxAddNullPtrTrans
return after
| termite2/tsl | Frontend/StatementInline.hs | bsd-3-clause | 22,876 | 0 | 32 | 8,817 | 6,828 | 3,314 | 3,514 | 339 | 7 |
{-# LANGUAGE Trustworthy, ExplicitForAll, ScopedTypeVariables #-}
{- VERY TRUST WORTHY :) -}
module Numerical.HBLAS.UtilsFFI(
withAllocaPrim
, unsafeWithPrim
, withRStorable_
, withRWStorable
, withRStorable
, unsafeWithPurePrim
, unsafeWithPrimLen
, unsafeWithPurePrimLen
, storablePtrZero ) where
import Data.Vector.Storable.Mutable as M
import Control.Monad.Primitive
import Foreign.ForeignPtr
import qualified Foreign.ForeignPtr.Unsafe as FFU
import Foreign.Storable.Complex()
import Data.Vector.Storable as S
--import Foreign.Ptr
import GHC.Ptr (Ptr(..))
import Foreign.Storable
import Foreign.Marshal (alloca)
import Data.Primitive.Addr
import Data.Word
{-
the IO version of these various utils is in Base.
but would like to have the
-}
storablePtrZero :: forall a m . (Storable a, PrimMonad m) => Ptr a -> m ()
{-# INLINE storablePtrZero #-}
storablePtrZero = \ (Ptr p ) -> let
x :: a
x = undefined
byteSize :: Int
byteSize = sizeOf x
in
if byteSize /= 0 then
do
let q = Addr p
setAddr q byteSize (0 :: Word8)
else return ()
withAllocaPrim :: (Storable a, PrimMonad m, PrimBase min) => (Ptr a -> min b) -> m b
withAllocaPrim = \ f -> unsafePrimToPrim $ alloca ( unsafePrimToIO . f )
--withAllocaZerodPrim
withRWStorable:: (Storable a, PrimMonad m)=> a -> (Ptr a -> m b) -> m a
withRWStorable val fun = do
valVect <- M.replicate 1 val
_ <- unsafeWithPrim valVect fun
M.unsafeRead valVect 0
{-# INLINE withRWStorable #-}
withRStorable :: (Storable a, PrimMonad m)=> a -> (Ptr a -> m b) -> m b
withRStorable val fun = do
valVect <- M.replicate 1 val
unsafeWithPrim valVect fun
{-# INLINE withRStorable #-}
withRStorable_ :: (Storable a, PrimMonad m)=> a -> (Ptr a -> m ()) -> m ()
withRStorable_ val fun = do
valVect <- M.replicate 1 val
unsafeWithPrim valVect fun
return ()
{-# INLINE withRStorable_ #-}
withForeignPtrPrim :: PrimMonad m => ForeignPtr a -> (Ptr a -> m b) -> m b
withForeignPtrPrim fo act
= do r <- act (FFU.unsafeForeignPtrToPtr fo)
touchForeignPtrPrim fo
return r
{-# INLINE withForeignPtrPrim #-}
touchForeignPtrPrim ::PrimMonad m => ForeignPtr a -> m ()
touchForeignPtrPrim fp = unsafePrimToPrim $! touchForeignPtr fp
{-# NOINLINE touchForeignPtrPrim #-}
unsafeWithPrim ::( Storable a, PrimMonad m )=> MVector (PrimState m) a -> (Ptr a -> m b) -> m b
{-# INLINE unsafeWithPrim #-}
unsafeWithPrim (MVector _ fp) fun = withForeignPtrPrim fp fun
unsafeWithPrimLen ::( Storable a, PrimMonad m )=> MVector (PrimState m) a -> ((Ptr a, Int )-> m b) -> m b
{-# INLINE unsafeWithPrimLen #-}
unsafeWithPrimLen (MVector n fp ) fun = withForeignPtrPrim fp (\x -> fun (x,n))
unsafeWithPurePrim ::( Storable a, PrimMonad m )=> Vector a -> ((Ptr a)-> m b) -> m b
{-# INLINE unsafeWithPurePrim #-}
unsafeWithPurePrim v fun = case S.unsafeToForeignPtr0 v of
(fp,_) -> do
res <- withForeignPtrPrim fp (\x -> fun x)
touchForeignPtrPrim fp
return res
unsafeWithPurePrimLen ::( Storable a, PrimMonad m )=> Vector a -> ((Ptr a, Int )-> m b) -> m b
{-# INLINE unsafeWithPurePrimLen #-}
unsafeWithPurePrimLen v fun = case S.unsafeToForeignPtr0 v of
(fp,n) -> do
res <- withForeignPtrPrim fp (\x -> fun (x,n))
touchForeignPtrPrim fp
return res
| wellposed/hblas | src/Numerical/HBLAS/UtilsFFI.hs | bsd-3-clause | 3,511 | 0 | 15 | 864 | 1,127 | 579 | 548 | 82 | 2 |
-- | A CSS 2.1 Parser.
--
-- See <http://www.w3.org/TR/CSS21/syndata.html> for a description of
-- CSS 2.1 syntax, grammer and data types. This parser follows the
-- more restrictive grammer found in
-- <http://www.w3.org/TR/CSS21/grammar.html>. Many of the names below
-- come directly from this document. Most parsers are a direct
-- translation of the specification. Higher level parsers may differ a
-- bit in order to account for additional CSS semantics not expressed
-- in the grammer. Any parts of this specification which are not
-- implemented will be listed here. They are left as an excersice for
-- the reader. :)
--
module Text.CSS.CSSParser
( -- * Compound Parsers
nmchar
, escape
-- * Simple Parsers
, nonascii
, unicode
, comment
, num
, w
, s
, nl
-- * Run
, run
) where
import Text.ParserCombinators.Parsec
-- | Parse a name character.
--
-- > [_a-z0-9-]|{nonascii}|{escape}
--
nmchar :: Parser String
nmchar = (do x <- (letter <|> digit <|> oneOf "_-")
return [x]) <|> (try nonascii) <|> escape <?> "nmchar"
hexDigits = ['0'..'9'] ++ ['a'..'f'] ++ ['A'..'F']
-- | Parse an escape character.
--
-- > {unicode}|\\[^\r\n\f0-9a-f]
--
-- An escape character is either a unicode character or a backslash
-- followed by any character other than \\r, \\n, \\f or a hexadecimal
-- digit.
escape :: Parser String
escape = (try unicode) <|> (do a <- char '\\'
b <- noneOf ("\n\r\f"++hexDigits)
return $ (a:[b])) <?> "escape"
-- | Parse a nonascii character.
--
-- > [\240-\377]
--
-- A nonascii character is a character in the octal range 240-377. The
-- specification uses the upper limit of 377 because that is the
-- highest character number that current version of Flex can deal
-- with. The actual upper limit is \\4177777 (decimal 1114111 and hex
-- \\x10ffff) which is the highest possible code point in
-- Unicode/ISO-10646. This parser is implemented to use the correct
-- upper bound.
nonascii :: Parser String
nonascii = do x <- anyChar
if x >= '\o240' && x <= '\o4177777'
then return [x]
else unexpected "ascii character"
-- Question: Is there a way I can make the above error message show up
-- in the expecting clause of the output error message?
-- | Find the end of a unicode character treating \\r\\n as a single
-- white space character.
unicodeEnd :: Parser String
unicodeEnd = try (string "\r\n")
<|> string " "
<|> string "\n"
<|> string "\r"
<|> string "\t"
<|> string "\f" <?> "unicode end"
-- | Parse a unicode character.
--
-- > \\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?
--
-- A unicode character starts with a backslash and then contains up to
-- six hex digits. If a character in the range [0-9a-fA-F] follows the
-- hexadecimal number, the end of the number needs to be made
-- clear. This is done by providing exactly 6 digits or by adding a
-- single white space character at the end.
--
-- This parser will grab any valid hexadecimal number. The following
-- restriction is not implemented in this parser.
--
-- If the number is outside the range allowed by Unicode (e.g.,
-- "\110000" is above the maximum 10FFFF allowed in current Unicode),
-- the UA may replace the escape with the "replacement character"
-- (U+FFFD).
--
-- This should implemented at a level above the parser.
--
-- See
-- <http://www.w3.org/International/questions/qa-escapes#cssescapes>
-- for another example of how these are used.
unicode :: Parser String
unicode = (do a <- string "\\"
b <- try (count 6 hexDigit)
<|> (do c <- many1 hexDigit
unicodeEnd
return c) <?> "unicode digits"
return $ a ++ b) <?> "unicode"
-- | Parse a comment.
--
-- > \/\* [^*]*\*+ ([^/*][^*]*\*+)* \/
--
-- A comment starts with \/* and ends with *\/ and may contain
-- anything except for the sequence \"*\/\" (which would end the
-- comment early and leave a stranded comment tail). No nested
-- comments. Parsing will fail if there are nested comments.
--
-- Comments may appear anywhere outside of other tokens. This means
-- that a \/* ... *\/ sequence may appear within a token and must not
-- be interpreted as a comment. Because of this, removeing comments
-- with a preprocessor is difficult.
comment :: Parser String
comment = (do a <- (string "/*")
b <- manyTill anyChar (try (string "*/"))
return $ (a ++ b ++ "*/")) <?> "comment"
-- | Parse a number.
--
-- > [0-9]+|[0-9]*\.[0-9]+
--
-- Numbers may have the follwing format:
--
-- > 42, 4.2 or .42
--
num :: Parser String
num = try (do a <- many digit
b <- string "."
c <- many1 digit
return $ (a ++ b ++ c)) <|> (many1 digit) <?> "number"
-- | Parse whitespace.
--
-- > {s}?
--
-- Whitespace is 0 or 1 spaces, remembering that spaces have 1 or more
-- space characters.
w :: Parser String
w = (do x <- many s
return $ concat x)
<?> "whitespace"
-- | Helper function for parsing spaces. Parse a single space character.
s_char :: Parser String
s_char = string " "
<|> string "\t"
<|> string "\r"
<|> string "\n"
<|> string "\f"
<?> "space character"
-- | Parse spaces.
--
-- > [ \t\r\n\f]+
--
-- Spaces are 1 or more space characters.
s :: Parser String
s = (do x <- many1 s_char
return $ concat x)
<?> "spaces"
-- | Parse a single new line.
--
-- > \n|\r\n|\r|\f
--
nl :: Parser String
nl = try (string "\r\n")
<|> string "\n"
<|> string "\r"
<|> string "\f"
<?> "new line"
-- | Run a parser on a CSS formatted string.
run :: Show a => Parser a -> String -> Either ParseError a
run p input = parse p "" input
| brentonashworth/css-parser | src/Text/CSS/CSSParser.hs | bsd-3-clause | 5,870 | 0 | 16 | 1,485 | 892 | 491 | 401 | 72 | 2 |
-- hisg - IRC stats generator.
--
-- Copyright (c) 2009, 2010 Antoine Kalmbach <antoine dot kalmbach at jyu dot fi>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * 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.
-- * Neither the name of the author nor the
-- names of its contributors may be used to endorse or promote products
-- derived from this software without specific prior written permission.
--
-- For further details, see LICENSE.
{-# OPTIONS_GHC -cpp -fglasgow-exts #-}
{-# LANGUAGE CPP #-}
module Main where
import Data.Maybe
import Data.Array
import Data.Time.Clock
import System.Console.GetOpt
import System.Environment (getArgs)
import Control.Monad
import Control.Monad.Trans
import Control.Monad.State.Lazy
import Hisg.Core
import Hisg.Formatter
import Hisg.IRCLog
version_ = "0.1.0"
version = "hisg v" ++ version_
exactVersion = version ++ " compiled on " ++ __DATE__ ++ " at " ++ __TIME__
data Opts = Help
| Version
| File String
options :: [OptDescr Opts]
options =
[ Option "v" ["version"] (NoArg Version) "Show version information",
Option "h" ["help"] (NoArg Help) "Show this help" ]
-- | Usage string.
usage :: String
usage = usageInfo "Usage: hisg [option...] INPUTFILES" options
-- | Formats a log file, producing HTML ouput.
layout :: String -> IRCLog -> NominalDiffTime -> FormatterM String
layout chan logfile elapsedTime = do
headers chan
scoreboard 15
hourlyActivity
charsToLinesRatio
footer $ "0.1.0 in " ++ show elapsedTime
getFinalOutput
-- | Parses the command line options and then processes files (if any).
runHisg :: [String] -> HisgM ()
runHisg [] = do
currentTime <- liftIO getCurrentTime
loadFile "sekopaat.log"
processFiles currentTime layout -- TEST LOG, REPLACE WITH USAGE
runHisg args = do
currentTime <- liftIO getCurrentTime
runArgs args
processFiles currentTime layout
runArgs :: [String] -> HisgM ()
runArgs args =
case (getOpt (ReturnInOrder File) options args) of
(o, [], []) -> mapM_ decide o
(_, _, errs) -> fail (concat errs)
decide :: Opts -> HisgM ()
decide opt =
case opt of
Help -> liftIO $ putStrLn usage
Version -> liftIO $ putStrLn exactVersion
File fn -> loadFile fn
main = do
args <- getArgs
runStateT (runHisg args) (Hisg [])
| ane/hisg | src/Hisg.hs | bsd-3-clause | 2,840 | 0 | 10 | 634 | 556 | 294 | 262 | 57 | 3 |
{- |
Module : Protocol.ROC.OpCodeTable
Description : OpCodeTable Lookup for Roc
Copyright : Plow Technologies LLC
License : MIT License
Maintainer : Scott Murphy
OpCode Table Lookup is different than TLP lookup
| -}
module Protocol.ROC.OpCodeTable () where
| plow-technologies/roc-translator | src/Protocol/ROC/OpCodeTable.hs | bsd-3-clause | 275 | 0 | 3 | 55 | 11 | 8 | 3 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad
import Couchbase.Raw
import qualified Data.ByteString as B
import Foreign.Ptr
import Test.Hspec
assertLcbSuccess :: Monad m => String -> LcbError -> m ()
assertLcbSuccess msg err =
when (err /= LcbSuccess) $ error msg
defaultParams :: ConnectionParams
defaultParams =
ConnectionParams
{ connectionString = "couchbase://localhost/default"
, password = Nothing
, lcbType = LcbTypeBucket
}
withConnection :: (Lcb -> IO ()) -> IO ()
withConnection f = do
(err, lcb) <- lcbCreate defaultParams
assertLcbSuccess "lcbCreate() failed" err
lcbConnect lcb >>= assertLcbSuccess "lcbConnect() failed"
lcbWait lcb >>= assertLcbSuccess "lcbWait() failed"
lcbGetBootstrapStatus lcb >>= assertLcbSuccess "lcbGetBootstrapStatus() failed"
f lcb
setValue :: B.ByteString -> B.ByteString -> IO ()
setValue k v =
withConnection $ \lcb -> do
let cmd = LcbCmdStore LcbSet k v Nothing
lcbStore3 lcb nullPtr cmd >>= assertLcbSuccess "lcbStore3() failed"
lcbWait lcb >>= assertLcbSuccess "lcbWait() failed"
removeKey :: B.ByteString -> IO ()
removeKey k =
withConnection $ \lcb -> do
lcbRemove3 lcb nullPtr k >>= assertLcbSuccess "lcbRemove3() failed"
lcbWait lcb >>= assertLcbSuccess "lcbWait() failed"
main :: IO ()
main = hspec $ do
describe "connect" $
it "to localhost" $ do
(err, lcb) <- lcbCreate defaultParams
err `shouldBe` LcbSuccess
lcbConnect lcb `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGetBootstrapStatus lcb `shouldReturn` LcbSuccess
describe "lcbGet3" $ do
it "succeeds" $ do
setValue "key" "value"
withConnection $ \lcb ->
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
it "calls callback" $ do
setValue "key" "value"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \resp -> do
lcbRespGetGetStatus resp `shouldReturn` LcbSuccess
lcbRespGetGetValue resp `shouldReturn` "value"
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
describe "lcbRemove3" $ do
it "succeeds" $ do
setValue "key" "value"
withConnection $ \lcb -> do
lcbRemove3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "calls callback" $ do
setValue "key" "value"
withConnection $ \lcb -> do
lcbInstallRemoveCallback lcb $ \resp ->
lcbRespRemoveGetStatus resp `shouldReturn` LcbSuccess
lcbRemove3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "actually removes key" $ do
setValue "key" "value"
withConnection $ \lcb -> do
lcbRemove3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbInstallGetCallback lcb $ \resp ->
lcbRespGetGetStatus resp `shouldReturn` LcbKeyEnoent
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when there is nothing to remove" $ do
removeKey "key"
withConnection $ \lcb -> do
lcbInstallRemoveCallback lcb $ \resp ->
lcbRespRemoveGetStatus resp `shouldReturn` LcbKeyEnoent
lcbRemove3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
describe "lcbStore3" $ do
it "replaces existing key with LcbReplace" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
let cmd = LcbCmdStore LcbReplace "key" "value2" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbInstallGetCallback lcb $ \resp ->
lcbRespGetGetValue resp `shouldReturn` "value2"
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback with LcbReplace when there is no key to replace" $ do
removeKey "key"
withConnection $ \lcb -> do
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEnoent
let cmd = LcbCmdStore LcbReplace "key" "value" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "replaces existing key with LcbSet" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
let cmd = LcbCmdStore LcbSet "key" "value2" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbInstallGetCallback lcb $ \resp ->
lcbRespGetGetValue resp `shouldReturn` "value2"
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "sets value with LcbSet even when there is no existing key" $ do
removeKey "key"
withConnection $ \lcb -> do
let cmd = LcbCmdStore LcbSet "key" "value" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbInstallGetCallback lcb $ \resp ->
lcbRespGetGetValue resp `shouldReturn` "value"
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "adds value with LcbAdd" $ do
removeKey "key"
withConnection $ \lcb -> do
let cmd = LcbCmdStore LcbAdd "key" "value" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbInstallGetCallback lcb $ \resp ->
lcbRespGetGetValue resp `shouldReturn` "value"
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback with LcbAdd when there is the key in database already" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbAdd "key" "value2" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "calls callback" $
withConnection $ \lcb -> do
lcbInstallStoreCallback lcb $ \resp -> do
lcbRespStoreGetStatus resp `shouldReturn` LcbSuccess
lcbRespStoreGetOp resp `shouldReturn` LcbSet
let cmd = LcbCmdStore LcbSet "key" "value" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "appends value with LcbAppend" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
let cmd = LcbCmdStore LcbAppend "key" "value2" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbInstallGetCallback lcb $ \resp ->
lcbRespGetGetValue resp `shouldReturn` "value1value2"
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "prepends value with LcbPrepend" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
let cmd = LcbCmdStore LcbPrepend "key" "value2" Nothing
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbInstallGetCallback lcb $ \resp ->
lcbRespGetGetValue resp `shouldReturn` "value2value1"
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "changes CAS with LcbReplace" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp -> do
lcbRespStoreGetStatus resp `shouldReturn` LcbSuccess
lcbRespStoreGetCas resp `shouldNotReturn` oldCas
let cmd = LcbCmdStore LcbReplace "key" "value2" (Just oldCas)
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "changes CAS with LcbSet" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp -> do
lcbRespStoreGetStatus resp `shouldReturn` LcbSuccess
lcbRespStoreGetCas resp `shouldNotReturn` oldCas
let cmd = LcbCmdStore LcbSet "key" "value2" (Just oldCas)
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "changes CAS with LcbAppend" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp -> do
lcbRespStoreGetStatus resp `shouldReturn` LcbSuccess
lcbRespStoreGetCas resp `shouldNotReturn` oldCas
let cmd = LcbCmdStore LcbAppend "key" "value2" (Just oldCas)
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "changes CAS with LcbPrepend" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp -> do
lcbRespStoreGetStatus resp `shouldReturn` LcbSuccess
lcbRespStoreGetCas resp `shouldNotReturn` oldCas
let cmd = LcbCmdStore LcbPrepend "key" "value2" (Just oldCas)
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when you try LcbReplace with CAS - 1" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbReplace "key" "value2" (Just (oldCas - 1))
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when you try LcbSet with CAS - 1" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbSet "key" "value2" (Just (oldCas - 1))
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when you try LcbAppend with CAS - 1" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbAppend "key" "value2" (Just (oldCas - 1))
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when you try LcbPrepend with CAS - 1" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbPrepend "key" "value2" (Just (oldCas - 1))
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when you try LcbReplace with CAS + 1" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbReplace "key" "value2" (Just (oldCas + 1))
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when you try LcbSet with CAS + 1" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbSet "key" "value2" (Just (oldCas + 1))
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when you try LcbAppend with CAS + 1" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbAppend "key" "value2" (Just (oldCas + 1))
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
it "returns error in callback when you try LcbPrepend with CAS + 1" $ do
setValue "key" "value1"
withConnection $ \lcb -> do
lcbInstallGetCallback lcb $ \respGet -> do
oldCas <- lcbRespGetGetCas respGet
lcbInstallStoreCallback lcb $ \resp ->
lcbRespStoreGetStatus resp `shouldReturn` LcbKeyEexists
let cmd = LcbCmdStore LcbPrepend "key" "value2" (Just (oldCas + 1))
lcbStore3 lcb nullPtr cmd `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
lcbGet3 lcb nullPtr "key" `shouldReturn` LcbSuccess
lcbWait lcb `shouldReturn` LcbSuccess
| asvyazin/libcouchbase.hs | test/tests.hs | bsd-3-clause | 15,533 | 0 | 29 | 4,034 | 4,057 | 1,931 | 2,126 | 319 | 1 |
module Main where
import Code20
main :: IO ()
main = putStrLn $ display (countdown5 831 [1,3,7,10,25,50])
| sampou-org/pfad | Code/countdown5.hs | bsd-3-clause | 108 | 0 | 9 | 19 | 55 | 32 | 23 | 4 | 1 |
module Goblin.Workshop.Types where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Data.Either
import Goblin.Workshop.Graph
import System.Log.Logger
import Text.Printf
---------
-- Models
---------
type Progress = Double
-- Workshop
newtype Workshop m = Workshop { graph :: Graph TaskId (Task m)
}
type WorkshopBus = TChan WorkshopMessage
-- Dispatcher
newtype Dispatcher m =
Dispatcher { runDispatcher :: Monad m
=> Workshop m
-> DispatcherBus m
-> SchedulerBus m
-> Maybe WorkshopBus
-> m ()
}
-- Scheduler
newtype Scheduler m =
Scheduler { runScheduler :: Monad m
=> SchedulerBus m
-> DispatcherBus m
-> Maybe WorkshopBus
-> m ()
}
-- Task
type TaskId = Int
type UniqueTask m = (TaskId, Task m)
instance {-# OVERLAPPING #-} Eq (UniqueTask m) where
a == b = fst a == fst b
data Task m = Task (m Result)
| TalkativeTask ((TaskMessage -> m ()) -> m Result)
type Err = String
type Ok = String
type Result = Either Err Ok
ok :: Ok -> Result
ok s = Right s
err :: Err -> Result
err s = Left s
isOk :: Result -> Bool
isOk = isRight
isErr :: Result -> Bool
isErr = isLeft
-----------
-- Messages
-----------
data WorkshopMessage = WStart
| WTaskStateChange TaskId WTaskState
| WTaskTalk TaskId WTaskTalk
| WFin
deriving (Eq, Show)
data WTaskState = WNotStarted
| WRunning Progress
| WDone
| WCanceled
deriving (Eq, Show)
data WTaskTalk = WTaskTalkProgress Progress
| WTaskTalkOutput String
deriving (Eq, Show)
data DispatcherMessage m = DTaskDone TaskId Result
| DTaskCanceled TaskId
| DDebug String
data SchedulerMessage m = SSpawnTask TaskId (Task m)
| SKillTask TaskId
| SQueryState TaskId
| STaskDone TaskId Result
| STaskError TaskId
| STaskTalk TaskId STaskTalk
| SDebug String
| SFin
data STaskTalk = STaskTalkProgress Progress
| STaskTalkOutput String
deriving (Eq, Show)
data TaskMessage = TProgress Progress
| TOutput String
deriving (Eq, Show)
--------
-- Buses
--------
type DispatcherBus m = TChan (DispatcherMessage m)
type SchedulerBus m = TChan (SchedulerMessage m)
| y-usuzumi/goblin-workshop | src/Goblin/Workshop/Types.hs | bsd-3-clause | 2,899 | 0 | 13 | 1,209 | 639 | 363 | 276 | 73 | 1 |
--
-- Copyright © 2014-2015 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
module Main where
import System.Exit
main :: IO ()
main = exitSuccess
| anchor/synchronise | test/tests.hs | bsd-3-clause | 362 | 0 | 6 | 72 | 32 | 22 | 10 | 4 | 1 |
{-# LANGUAGE CPP #-}
module ZM.Type.Prims() where
import qualified ZM.Type.Words as Z
import Data.Model
import qualified Data.Word as H
import qualified Data.Int as H
import Numeric.Natural as H
import qualified Prelude as H
#include "MachDeps.h"
#if WORD_SIZE_IN_BITS == 64
instance Model H.Word where envType _ = envType (Proxy::Proxy Z.Word64)
instance Model H.Int where envType _ = envType (Proxy::Proxy Z.Int64)
#elif WORD_SIZE_IN_BITS == 32
instance Model H.Word where envType _ = envType (Proxy::Proxy Z.Word32)
instance Model H.Int where envType _ = envType (Proxy::Proxy Z.Int32)
#else
#error expected WORD_SIZE_IN_BITS to be 32 or 64
#endif
instance Model H.Word8 where envType _ = envType (Proxy::Proxy Z.Word8)
instance Model H.Word16 where envType _ = envType (Proxy::Proxy Z.Word16)
instance Model H.Word32 where envType _ = envType (Proxy::Proxy Z.Word32)
instance Model H.Word64 where envType _ = envType (Proxy::Proxy Z.Word64)
instance Model H.Int8 where envType _ = envType (Proxy::Proxy Z.Int8)
instance Model H.Int16 where envType _ = envType (Proxy::Proxy Z.Int16)
instance Model H.Int32 where envType _ = envType (Proxy::Proxy Z.Int32)
instance Model H.Int64 where envType _ = envType (Proxy::Proxy Z.Int64)
instance Model H.Integer where envType _ = envType (Proxy::Proxy Z.Int)
instance Model H.Natural where envType _ = envType (Proxy::Proxy Z.Word)
| tittoassini/typed | src/ZM/Type/Prims.hs | bsd-3-clause | 1,457 | 0 | 9 | 274 | 442 | 236 | 206 | -1 | -1 |
{-|
Module : Idris.Package.Parser
Description : `iPKG` file parser and package description information.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE CPP, ConstraintKinds, FlexibleInstances, TypeSynonymInstances #-}
module Idris.Package.Parser where
import Idris.CmdOptions
import Idris.Package.Common
import Idris.Parser.Helpers hiding (stringLiteral)
import Control.Applicative
import Control.Monad.State.Strict
import Data.List (union)
import System.Directory (doesFileExist)
import System.Exit
import System.FilePath (isValid, takeExtension, takeFileName)
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import Text.Trifecta hiding (char, charLiteral, natural, span, string, symbol,
whiteSpace)
type PParser = StateT PkgDesc IdrisInnerParser
instance HasLastTokenSpan PParser where
getLastTokenSpan = return Nothing
#if MIN_VERSION_base(4,9,0)
instance {-# OVERLAPPING #-} DeltaParsing PParser where
line = lift line
{-# INLINE line #-}
position = lift position
{-# INLINE position #-}
slicedWith f (StateT m) = StateT $ \s -> slicedWith (\(a,s') b -> (f a b, s')) $ m s
{-# INLINE slicedWith #-}
rend = lift rend
{-# INLINE rend #-}
restOfLine = lift restOfLine
{-# INLINE restOfLine #-}
#endif
instance {-# OVERLAPPING #-} TokenParsing PParser where
someSpace = many (simpleWhiteSpace <|> singleLineComment <|> multiLineComment) *> pure ()
parseDesc :: FilePath -> IO PkgDesc
parseDesc fp = do
when (not $ takeExtension fp == ".ipkg") $ do
putStrLn $ unwords ["The presented iPKG file does not have a '.ipkg' extension:", show fp]
exitWith (ExitFailure 1)
res <- doesFileExist fp
if res
then do
p <- readFile fp
case runparser pPkg defaultPkg fp p of
Failure (ErrInfo err _) -> fail (show $ PP.plain err)
Success x -> return x
else do
putStrLn $ unwords [ "The presented iPKG file does not exist:", show fp]
exitWith (ExitFailure 1)
pPkg :: PParser PkgDesc
pPkg = do
reserved "package"
p <- filename
st <- get
put (st { pkgname = p })
some pClause
st <- get
eof
return st
-- | Parses a filename.
-- |
-- | Treated for now as an identifier or a double-quoted string.
filename :: (MonadicParsing m, HasLastTokenSpan m) => m String
filename = (do
filename <- token $
-- Treat a double-quoted string as a filename to support spaces.
-- This also moves away from tying filenames to identifiers, so
-- it will also accept hyphens
-- (https://github.com/idris-lang/Idris-dev/issues/2721)
stringLiteral
<|>
-- Through at least version 0.9.19.1, IPKG executable values were
-- possibly namespaced identifiers, like foo.bar.baz.
show <$> fst <$> iName []
case filenameErrorMessage filename of
Just errorMessage -> fail errorMessage
Nothing -> return filename)
<?> "filename"
where
-- TODO: Report failing span better! We could lookAhead,
-- or do something with DeltaParsing?
filenameErrorMessage :: FilePath -> Maybe String
filenameErrorMessage path = either Just (const Nothing) $ do
checkEmpty path
checkValid path
checkNoDirectoryComponent path
where
checkThat ok message =
if ok then Right () else Left message
checkEmpty path =
checkThat (path /= "") "filename must not be empty"
checkValid path =
checkThat (System.FilePath.isValid path)
"filename must contain only valid characters"
checkNoDirectoryComponent path =
checkThat (path == takeFileName path)
"filename must contain no directory component"
pClause :: PParser ()
pClause = do reserved "executable"; lchar '=';
exec <- filename
st <- get
put (st { execout = Just exec })
<|> do reserved "main"; lchar '=';
main <- fst <$> iName []
st <- get
put (st { idris_main = Just main })
<|> do reserved "sourcedir"; lchar '=';
src <- fst <$> identifier
st <- get
put (st { sourcedir = src })
<|> do reserved "opts"; lchar '=';
opts <- stringLiteral
st <- get
let args = pureArgParser (words opts)
put (st { idris_opts = args ++ idris_opts st })
<|> do reserved "pkgs"; lchar '=';
ps <- sepBy1 (fst <$> identifier) (lchar ',')
st <- get
let pkgs = pureArgParser $ concatMap (\x -> ["-p", x]) ps
put (st { pkgdeps = ps `union` (pkgdeps st)
, idris_opts = pkgs ++ idris_opts st})
<|> do reserved "modules"; lchar '=';
ms <- sepBy1 (fst <$> iName []) (lchar ',')
st <- get
put (st { modules = modules st ++ ms })
<|> do reserved "libs"; lchar '=';
ls <- sepBy1 (fst <$> identifier) (lchar ',')
st <- get
put (st { libdeps = libdeps st ++ ls })
<|> do reserved "objs"; lchar '=';
ls <- sepBy1 (fst <$> identifier) (lchar ',')
st <- get
put (st { objs = objs st ++ ls })
<|> do reserved "makefile"; lchar '=';
mk <- fst <$> iName []
st <- get
put (st { makefile = Just (show mk) })
<|> do reserved "tests"; lchar '=';
ts <- sepBy1 (fst <$> iName []) (lchar ',')
st <- get
put st { idris_tests = idris_tests st ++ ts }
<|> do reserved "version"
lchar '='
vStr <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgversion = Just vStr}
<|> do reserved "readme"
lchar '='
rme <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put (st { pkgreadme = Just rme })
<|> do reserved "license"
lchar '='
lStr <- many (satisfy (not . isEol))
eol
st <- get
put st {pkglicense = Just lStr}
<|> do reserved "homepage"
lchar '='
www <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkghomepage = Just www}
<|> do reserved "sourceloc"
lchar '='
srcpage <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgsourceloc = Just srcpage}
<|> do reserved "bugtracker"
lchar '='
src <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgbugtracker = Just src}
<|> do reserved "brief"
lchar '='
brief <- stringLiteral
st <- get
someSpace
put st {pkgbrief = Just brief}
<|> do reserved "author"; lchar '=';
author <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgauthor = Just author}
<|> do reserved "maintainer"; lchar '=';
maintainer <- many (satisfy (not . isEol))
eol
someSpace
st <- get
put st {pkgmaintainer = Just maintainer}
| uuhan/Idris-dev | src/Idris/Package/Parser.hs | bsd-3-clause | 7,655 | 0 | 29 | 2,757 | 2,171 | 1,043 | 1,128 | 172 | 3 |
{-# LANGUAGE CPP #-}
module Main (main) where
import Development.Shake as Shake
import System.Directory
import System.Environment
import Development.Shake.FilePath
import Data.Char
import Data.List
#if MIN_VERSION_base(4,8,0)
import Prelude hiding ((*>))
#endif
-- local repos to use; later look at the srcs to figure out what the external repo does
repos :: [String]
repos = [ "../sunroof-compiler" -- the sunroof compiler
, "../sunroof-server"
]
findExecs :: [String] -> [(String,Exec)]
findExecs (xs:xss) = case words xs of
["Executable",nm] ->
let loop (xs':xss') o
| all isSpace xs' = loop xss' o
| isSpace (head xs') = case words xs' of
("Main-is:":ns) -> loop xss (o { the_main = unwords ns })
("Hs-Source-Dirs:":ns) -> loop xss' (o { the_dir = unwords ns })
("Ghc-Options:":ns) -> loop xss' (o { the_opts = unwords ns })
_ -> loop xss' o
| otherwise = (nm,o) : findExecs (xs':xss')
loop [] o = (nm,o) : []
in loop xss (Exec "" "" "")
_ -> findExecs xss
findExecs [] = []
data Exec = Exec
{ the_main :: String
, the_dir :: String
, the_opts :: String
}
deriving Show
main :: IO ()
main = do
args <- getArgs
execs <- readFile "sunroof-examples.cabal" >>= return . findExecs . lines
main2 args execs
main2 :: [String] -> [(String, Exec)] -> IO ()
main2 [] execs = do
putStrLn "usage: Shake [all] exec_1 exec_2 ..."
putStrLn ""
putStrLn "to clean, use cabal clean"
putStrLn ""
putStrLn "Executables"
putStrLn "-----------"
putStr $ unlines
[ "Executable " ++ nm ++ " (" ++ the_main exec ++ " in " ++ the_dir exec ++ " with " ++ the_opts exec ++ ")"
| (nm,exec) <- execs
]
-- to clean, use cabal clean
main2 xs execs = shake (shakeOptions) $ do
let autogen = "inplace-autogen/Paths_sunroof_examples.hs"
let targets =
[ "dist" </> "build" </> nm </> nm
| (nm,_ex) <- execs
, xs == ["all" ]|| nm `elem` xs
]
want [autogen]
want targets
autogen *> \ out -> do
pwd <- liftIO $ getCurrentDirectory
writeFile' out $ unlines
[ "module Paths_sunroof_examples where"
, "getDataDir :: IO String"
, "getDataDir = return " ++ show pwd
]
targets **> \ out -> do
liftIO $ print out
let nm = takeFileName out
liftIO $ print nm
let Just exec = lookup nm execs
liftIO $ print exec
need [ the_dir exec </> the_main exec]
sequence_
[ do files <- getDirectoryFiles repo ["*.cabal"]
liftIO $ print files
need $ map (repo </>) files
files' <- getDirectoryFiles repo ["//*.hs"]
liftIO $ print files'
need $ map (repo </>) files'
| repo <- repos
]
liftIO $ putStrLn $ "Building: " ++ out
-- compile inside the build dir
let cache = takeDirectory out </> "cache"
systemCwd "."
"ghc"
["--make",the_dir exec </> the_main exec, the_opts exec,
"-hidir",cache,"-odir",cache,
"-dcore-lint",
"-o", out,
"-i" ++ concat (intersperse ":" (the_dir exec : "inplace-autogen" : repos))
]
| ku-fpg/sunroof-examples | Shake.hs | bsd-3-clause | 4,035 | 0 | 21 | 1,759 | 1,083 | 545 | 538 | 85 | 6 |
module Printable where
| Megaleo/Electras | src/Printable.hs | bsd-3-clause | 23 | 0 | 2 | 3 | 4 | 3 | 1 | 1 | 0 |
-- inspired by http://dlaing.org/cofun/posts/free_and_cofree.html
module PolyGraph.Common.DslSupport.Product
(
Product(..)
, (:*:)
, (*:*)
, (:>:) ()
)
where
import Control.Applicative
data Product f g a = Pair (f a) (g a) deriving (Functor, Show)
type f :*: g = Product f g
--instance (Functor f, Functor g) => Functor (Product f g) where
-- fmap h (Pair f g) = Pair (fmap h f) (fmap h g)
(*:*) :: (Functor f, Functor g) => (a -> f a) -> (a -> g a) -> a -> (f :*: g) a
(*:*) = liftA2 Pair
class (Functor big, Functor small) => big :>: small where
prj :: big a -> small a
instance Functor f => f :>: f where
prj = id
instance {-# OVERLAPPING #-} (Functor f, Functor g) => (f :*: g) :>: f where
prj (Pair fa _) = fa
instance {-# OVERLAPPABLE #-} (Functor f, Functor g, Functor h, g :>: f) => (h :*: g) :>: f where
prj (Pair _ ga) = prj ga
| rpeszek/GraphPlay | src/PolyGraph/Common/DslSupport/Product.hs | bsd-3-clause | 867 | 0 | 11 | 198 | 346 | 192 | 154 | -1 | -1 |
{- Copyright (c) 2008 David Roundy
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.
3. Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. -}
{-# OPTIONS_GHC -fomit-interface-pragmas #-}
module Distribution.Franchise.Darcs
( inDarcs, darcsDist, darcsRelease, darcsPatchLevel )
where
import System.Directory ( doesDirectoryExist )
import Data.List ( (\\) )
import Distribution.Franchise.Buildable
import Distribution.Franchise.ConfigureState
import Distribution.Franchise.Util
import Distribution.Franchise.GhcState ( getVersion )
import Distribution.Franchise.ReleaseType ( ReleaseType(..), releaseRegexp )
import Distribution.Franchise.Permissions ( setExecutable )
inDarcs :: C Bool
inDarcs = io $ doesDirectoryExist "_darcs"
darcsPatchLevel :: ReleaseType -> C Int
darcsPatchLevel t =
do patches' <- systemOut "darcs" ["changes","--from-tag",
releaseRegexp t,"--count"]
((patches'',_):_) <- return $ reads patches'
return $ max 0 (patches'' - 1)
darcsRelease :: ReleaseType -> C String
darcsRelease t =
do xxx <- systemOut "darcs" ["annotate","-t",releaseRegexp t,"-s"]
((_:zzz):_) <- return $ filter ("tagged" `elem`) $
map words $ reverse $ lines xxx
return $ unwords zzz
darcsDist :: String -> [String] -> C String
darcsDist dn tocopy = withRootdir $
do v <- getVersion
let distname = dn++"-"++v
tarname = distname++".tar.gz"
rule [phony "sdist",tarname] [] $
do putS $ "making tarball as "++tarname
rm_rf distname
system "darcs" ["get","-t",v,".",distname]
c <- nubs `fmap` getExtra "to-clean"
dc <- nubs `fmap` getExtra "to-distclean"
withDirectory distname $
do setExecutable "Setup.hs" `catchC` \_ -> return ()
let wanted = (".releaseVersion":".latestRelease":
".lastTag":".lastTagPatchLevel":
".releaseVersionPatchLevel":
".latestReleasePatchLevel":tocopy)
system "./Setup.hs" wanted
mapM_ rm_rf $
("_darcs":".arcs-prefs":c++dc) \\ wanted
system "tar" ["zcf",tarname,distname]
rm_rf distname
return tarname
| droundy/franchise | Distribution/Franchise/Darcs.hs | bsd-3-clause | 3,873 | 0 | 23 | 1,087 | 620 | 323 | 297 | 48 | 1 |
module Main where
import Test.Tasty
import qualified Data.Aeson.Casing.Test as Casing
main :: IO ()
main = defaultMain $ testGroup "Tests"
[ Casing.tests
]
| AndrewRademacher/aeson-casing | test/Main.hs | mit | 185 | 0 | 8 | 52 | 48 | 29 | 19 | 6 | 1 |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Text.PrettyPrint.Final.Rendering.HTML
Description : Monospaced text output to be included in HTML
Copyright : (c) David Darais, David Christiansen, and Weixi Ma 2016-2017
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : Portable
HTML has its own conventions around whitespace and newlines. This
modules contains a renderer that inserts the appropriate non-breaking
spaces and line break tags.
-}
module Text.PrettyPrint.Final.Rendering.HTML (render) where
import Control.Monad
import Control.Applicative
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.State
import Control.Monad.RWS
import Data.List
import Data.String (IsString(..))
import Data.Text (Text)
import qualified Data.Text as T
import Text.PrettyPrint.Final
renderChunk :: Chunk Int -> Text
renderChunk (CText t) = t
renderChunk (CSpace w) = T.replicate w " "
renderAtom :: Atom Int -> Text
renderAtom (AChunk c) = T.concatMap swapSpace $ renderChunk c
where
swapSpace ' ' = " "
swapSpace c = T.singleton c
renderAtom ANewline = "<br/>"
-- | Render an document to a string suitable for inclusion in HTML.
-- The HTML should use a monospaced font for the code.
render :: forall ann . (ann -> Text -> Text) -> POut Int ann -> Text
render renderAnnotation out = render' out
where render' :: POut Int ann -> Text
render' pout = case pout of
PNull -> T.pack ""
PAtom a -> renderAtom a
PSeq o1 o2 -> render' o1 `T.append` render' o2
PAnn a o -> renderAnnotation a $ render' o
| david-christiansen/final-pretty-printer | Text/PrettyPrint/Final/Rendering/HTML.hs | mit | 1,967 | 0 | 11 | 352 | 364 | 198 | 166 | 38 | 4 |
myCheck :: Int -> Bool
myCheck n = ord n == 6
-- ord & chr bij elkaar in groepje, Bastiaan?
| roberth/uu-helium | test/thompson/Thompson30.hs | gpl-3.0 | 95 | 0 | 6 | 24 | 26 | 13 | 13 | 2 | 1 |
{-# LANGUAGE Arrows, InstanceSigs #-}
module Bot.Seen where
import Control.Auto
import Data.Map as M
import Data.Time.Clock
import Prelude hiding ((.), id) -- we use (.) and id from `Control.Category`
import Control.Monad.IO.Class
import Bot.Types
seenBot :: MonadIO m => RoomBot m
seenBot = proc (InMessage nick msg _ time) -> do
now <- effect (liftIO getCurrentTime) -< ()
seens <- trackSeens -< (nick, time)
queryB <- queryBlips -< msg
let respond :: Nick -> [Message]
respond qry = case M.lookup qry seens of
Just t -> [qry ++ " last seen "++ breakTime (diffUTCTime now t) ++ "ago."]
Nothing -> ["No record of " ++ qry ++ "."]
id -< respond <$> queryB
where
trackSeens :: Monad m => Auto m (Nick, UTCTime) (Map Nick UTCTime)
trackSeens = accum (\mp (nick, time) -> M.insert nick time mp) M.empty
queryBlips :: Auto m Message (Blip Nick)
queryBlips = emitJusts (getRequest . words)
where
getRequest ("@seen":nick:_) = Just nick
getRequest _ = Nothing
breakTime :: NominalDiffTime -> String
breakTime diffTime =
let rounded = round diffTime
(m',s) = quotRem rounded 60
(h', m) = quotRem m' 60
(d, h) = quotRem h' 24
sh = show
in sh d ++ " days " ++ sh h ++ " hours " ++ sh m ++ " minutes and " ++ sh s ++ " seconds "
| urbanslug/nairobi-bot | src/Bot/Seen.hs | gpl-3.0 | 1,394 | 1 | 19 | 397 | 503 | 261 | 242 | 32 | 3 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Main
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Main (main) where
import Test.Tasty
import Test.AWS.ECS
import Test.AWS.ECS.Internal
main :: IO ()
main = defaultMain $ testGroup "ECS"
[ testGroup "tests" tests
, testGroup "fixtures" fixtures
]
| olorin/amazonka | amazonka-ecs/test/Main.hs | mpl-2.0 | 522 | 0 | 8 | 103 | 76 | 47 | 29 | 9 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sk-SK">
<title>Export Report | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/exportreport/src/main/javahelp/org/zaproxy/zap/extension/exportreport/resources/help_sk_SK/helpset_sk_SK.hs | apache-2.0 | 975 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, ScopedTypeVariables #-}
-- |
-- Module : Data.Vector.Primitive.Mutable
-- Copyright : (c) Roman Leshchinskiy 2008-2010
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Mutable primitive vectors.
--
module Data.Vector.Primitive.Mutable (
-- * Mutable vectors of primitive types
MVector(..), IOVector, STVector, Prim,
-- * Accessors
-- ** Length information
length, null,
-- ** Extracting subvectors
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
-- ** Overlapping
overlaps,
-- * Construction
-- ** Initialisation
new, unsafeNew, replicate, replicateM, clone,
-- ** Growing
grow, unsafeGrow,
-- ** Restricting memory usage
clear,
-- * Accessing individual elements
read, write, swap,
unsafeRead, unsafeWrite, unsafeSwap,
-- * Modifying vectors
-- ** Filling and copying
set, copy, move, unsafeCopy, unsafeMove
) where
import qualified Data.Vector.Generic.Mutable as G
import Data.Primitive.ByteArray
import Data.Primitive ( Prim, sizeOf )
import Control.Monad.Primitive
import Control.Monad ( liftM )
import Control.DeepSeq ( NFData )
import Prelude hiding ( length, null, replicate, reverse, map, read,
take, drop, splitAt, init, tail )
import Data.Typeable ( Typeable )
#include "vector.h"
-- | Mutable vectors of primitive types.
data MVector s a = MVector {-# UNPACK #-} !Int
{-# UNPACK #-} !Int
{-# UNPACK #-} !(MutableByteArray s)
deriving ( Typeable )
type IOVector = MVector RealWorld
type STVector s = MVector s
instance NFData (MVector s a)
instance Prim a => G.MVector MVector a where
basicLength (MVector _ n _) = n
basicUnsafeSlice j m (MVector i n arr)
= MVector (i+j) m arr
{-# INLINE basicOverlaps #-}
basicOverlaps (MVector i m arr1) (MVector j n arr2)
= sameMutableByteArray arr1 arr2
&& (between i j (j+n) || between j i (i+m))
where
between x y z = x >= y && x < z
{-# INLINE basicUnsafeNew #-}
basicUnsafeNew n = MVector 0 n
`liftM` newByteArray (n * sizeOf (undefined :: a))
{-# INLINE basicUnsafeRead #-}
basicUnsafeRead (MVector i n arr) j = readByteArray arr (i+j)
{-# INLINE basicUnsafeWrite #-}
basicUnsafeWrite (MVector i n arr) j x = writeByteArray arr (i+j) x
{-# INLINE basicUnsafeCopy #-}
basicUnsafeCopy (MVector i n dst) (MVector j _ src)
= copyMutableByteArray dst (i*sz) src (j*sz) (n*sz)
where
sz = sizeOf (undefined :: a)
{-# INLINE basicUnsafeMove #-}
basicUnsafeMove (MVector i n dst) (MVector j _ src)
= moveByteArray dst (i*sz) src (j*sz) (n * sz)
where
sz = sizeOf (undefined :: a)
{-# INLINE basicSet #-}
basicSet (MVector i n arr) x = setByteArray arr i n x
-- Length information
-- ------------------
-- | Length of the mutable vector.
length :: Prim a => MVector s a -> Int
{-# INLINE length #-}
length = G.length
-- | Check whether the vector is empty
null :: Prim a => MVector s a -> Bool
{-# INLINE null #-}
null = G.null
-- Extracting subvectors
-- ---------------------
-- | Yield a part of the mutable vector without copying it.
slice :: Prim a => Int -> Int -> MVector s a -> MVector s a
{-# INLINE slice #-}
slice = G.slice
take :: Prim a => Int -> MVector s a -> MVector s a
{-# INLINE take #-}
take = G.take
drop :: Prim a => Int -> MVector s a -> MVector s a
{-# INLINE drop #-}
drop = G.drop
splitAt :: Prim a => Int -> MVector s a -> (MVector s a, MVector s a)
{-# INLINE splitAt #-}
splitAt = G.splitAt
init :: Prim a => MVector s a -> MVector s a
{-# INLINE init #-}
init = G.init
tail :: Prim a => MVector s a -> MVector s a
{-# INLINE tail #-}
tail = G.tail
-- | Yield a part of the mutable vector without copying it. No bounds checks
-- are performed.
unsafeSlice :: Prim a
=> Int -- ^ starting index
-> Int -- ^ length of the slice
-> MVector s a
-> MVector s a
{-# INLINE unsafeSlice #-}
unsafeSlice = G.unsafeSlice
unsafeTake :: Prim a => Int -> MVector s a -> MVector s a
{-# INLINE unsafeTake #-}
unsafeTake = G.unsafeTake
unsafeDrop :: Prim a => Int -> MVector s a -> MVector s a
{-# INLINE unsafeDrop #-}
unsafeDrop = G.unsafeDrop
unsafeInit :: Prim a => MVector s a -> MVector s a
{-# INLINE unsafeInit #-}
unsafeInit = G.unsafeInit
unsafeTail :: Prim a => MVector s a -> MVector s a
{-# INLINE unsafeTail #-}
unsafeTail = G.unsafeTail
-- Overlapping
-- -----------
-- Check whether two vectors overlap.
overlaps :: Prim a => MVector s a -> MVector s a -> Bool
{-# INLINE overlaps #-}
overlaps = G.overlaps
-- Initialisation
-- --------------
-- | Create a mutable vector of the given length.
new :: (PrimMonad m, Prim a) => Int -> m (MVector (PrimState m) a)
{-# INLINE new #-}
new = G.new
-- | Create a mutable vector of the given length. The length is not checked.
unsafeNew :: (PrimMonad m, Prim a) => Int -> m (MVector (PrimState m) a)
{-# INLINE unsafeNew #-}
unsafeNew = G.unsafeNew
-- | Create a mutable vector of the given length (0 if the length is negative)
-- and fill it with an initial value.
replicate :: (PrimMonad m, Prim a) => Int -> a -> m (MVector (PrimState m) a)
{-# INLINE replicate #-}
replicate = G.replicate
-- | Create a mutable vector of the given length (0 if the length is negative)
-- and fill it with values produced by repeatedly executing the monadic action.
replicateM :: (PrimMonad m, Prim a) => Int -> m a -> m (MVector (PrimState m) a)
{-# INLINE replicateM #-}
replicateM = G.replicateM
-- | Create a copy of a mutable vector.
clone :: (PrimMonad m, Prim a)
=> MVector (PrimState m) a -> m (MVector (PrimState m) a)
{-# INLINE clone #-}
clone = G.clone
-- Growing
-- -------
-- | Grow a vector by the given number of elements. The number must be
-- positive.
grow :: (PrimMonad m, Prim a)
=> MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
{-# INLINE grow #-}
grow = G.grow
-- | Grow a vector by the given number of elements. The number must be
-- positive but this is not checked.
unsafeGrow :: (PrimMonad m, Prim a)
=> MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
{-# INLINE unsafeGrow #-}
unsafeGrow = G.unsafeGrow
-- Restricting memory usage
-- ------------------------
-- | Reset all elements of the vector to some undefined value, clearing all
-- references to external objects. This is usually a noop for unboxed vectors.
clear :: (PrimMonad m, Prim a) => MVector (PrimState m) a -> m ()
{-# INLINE clear #-}
clear = G.clear
-- Accessing individual elements
-- -----------------------------
-- | Yield the element at the given position.
read :: (PrimMonad m, Prim a) => MVector (PrimState m) a -> Int -> m a
{-# INLINE read #-}
read = G.read
-- | Replace the element at the given position.
write :: (PrimMonad m, Prim a) => MVector (PrimState m) a -> Int -> a -> m ()
{-# INLINE write #-}
write = G.write
-- | Swap the elements at the given positions.
swap :: (PrimMonad m, Prim a) => MVector (PrimState m) a -> Int -> Int -> m ()
{-# INLINE swap #-}
swap = G.swap
-- | Yield the element at the given position. No bounds checks are performed.
unsafeRead :: (PrimMonad m, Prim a) => MVector (PrimState m) a -> Int -> m a
{-# INLINE unsafeRead #-}
unsafeRead = G.unsafeRead
-- | Replace the element at the given position. No bounds checks are performed.
unsafeWrite
:: (PrimMonad m, Prim a) => MVector (PrimState m) a -> Int -> a -> m ()
{-# INLINE unsafeWrite #-}
unsafeWrite = G.unsafeWrite
-- | Swap the elements at the given positions. No bounds checks are performed.
unsafeSwap
:: (PrimMonad m, Prim a) => MVector (PrimState m) a -> Int -> Int -> m ()
{-# INLINE unsafeSwap #-}
unsafeSwap = G.unsafeSwap
-- Filling and copying
-- -------------------
-- | Set all elements of the vector to the given value.
set :: (PrimMonad m, Prim a) => MVector (PrimState m) a -> a -> m ()
{-# INLINE set #-}
set = G.set
-- | Copy a vector. The two vectors must have the same length and may not
-- overlap.
copy :: (PrimMonad m, Prim a)
=> MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
{-# INLINE copy #-}
copy = G.copy
-- | Copy a vector. The two vectors must have the same length and may not
-- overlap. This is not checked.
unsafeCopy :: (PrimMonad m, Prim a)
=> MVector (PrimState m) a -- ^ target
-> MVector (PrimState m) a -- ^ source
-> m ()
{-# INLINE unsafeCopy #-}
unsafeCopy = G.unsafeCopy
-- | Move the contents of a vector. The two vectors must have the same
-- length.
--
-- If the vectors do not overlap, then this is equivalent to 'copy'.
-- Otherwise, the copying is performed as if the source vector were
-- copied to a temporary vector and then the temporary vector was copied
-- to the target vector.
move :: (PrimMonad m, Prim a)
=> MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
{-# INLINE move #-}
move = G.move
-- | Move the contents of a vector. The two vectors must have the same
-- length, but this is not checked.
--
-- If the vectors do not overlap, then this is equivalent to 'unsafeCopy'.
-- Otherwise, the copying is performed as if the source vector were
-- copied to a temporary vector and then the temporary vector was copied
-- to the target vector.
unsafeMove :: (PrimMonad m, Prim a)
=> MVector (PrimState m) a -- ^ target
-> MVector (PrimState m) a -- ^ source
-> m ()
{-# INLINE unsafeMove #-}
unsafeMove = G.unsafeMove
| rleshchinskiy/vector | Data/Vector/Primitive/Mutable.hs | bsd-3-clause | 9,846 | 0 | 12 | 2,293 | 2,448 | 1,338 | 1,110 | 171 | 1 |
{-# LANGUAGE CPP #-}
-- | Note [Base Dir]
-- ~~~~~~~~~~~~~~~~~
--
-- GHC's base directory or top directory containers miscellaneous settings and
-- the package database. The main compiler of course needs this directory to
-- read those settings and read and write packages. ghc-pkg uses it to find the
-- global package database too.
--
-- In the interest of making GHC builds more relocatable, many settings also
-- will expand `${top_dir}` inside strings so GHC doesn't need to know it's on
-- installation location at build time. ghc-pkg also can expand those variables
-- and so needs the top dir location to do that too.
module GHC.BaseDir where
import Prelude -- See Note [Why do we import Prelude here?]
import Data.List
import System.FilePath
-- Windows
#if defined(mingw32_HOST_OS)
import System.Environment (getExecutablePath)
-- POSIX
#elif defined(darwin_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
import System.Environment (getExecutablePath)
#endif
-- | Expand occurrences of the @$topdir@ interpolation in a string.
expandTopDir :: FilePath -> String -> String
expandTopDir = expandPathVar "topdir"
-- | @expandPathVar var value str@
--
-- replaces occurrences of variable @$var@ with @value@ in str.
expandPathVar :: String -> FilePath -> String -> String
expandPathVar var value str
| Just str' <- stripPrefix ('$':var) str
, null str' || isPathSeparator (head str')
= value ++ expandPathVar var value str'
expandPathVar var value (x:xs) = x : expandPathVar var value xs
expandPathVar _ _ [] = []
-- | Calculate the location of the base dir
getBaseDir :: IO (Maybe String)
#if defined(mingw32_HOST_OS)
getBaseDir = Just . (\p -> p </> "lib") . rootDir <$> getExecutablePath
where
-- locate the "base dir" when given the path
-- to the real ghc executable (as opposed to symlink)
-- that is running this function.
rootDir :: FilePath -> FilePath
rootDir = takeDirectory . takeDirectory . normalise
#elif defined(darwin_HOST_OS) || defined(linux_HOST_OS) || defined(freebsd_HOST_OS)
-- on unix, this is a bit more confusing.
-- The layout right now is something like
--
-- /bin/ghc-X.Y.Z <- wrapper script (1)
-- /bin/ghc <- symlink to wrapper script (2)
-- /lib/ghc-X.Y.Z/bin/ghc <- ghc executable (3)
-- /lib/ghc-X.Y.Z <- $topdir (4)
--
-- As such, we first need to find the absolute location to the
-- binary.
--
-- getExecutablePath will return (3). One takeDirectory will
-- give use /lib/ghc-X.Y.Z/bin, and another will give us (4).
--
-- This of course only works due to the current layout. If
-- the layout is changed, such that we have ghc-X.Y.Z/{bin,lib}
-- this would need to be changed accordingly.
--
getBaseDir = Just . (\p -> p </> "lib") . takeDirectory . takeDirectory <$> getExecutablePath
#else
getBaseDir = return Nothing
#endif
| sdiehl/ghc | libraries/ghc-boot/GHC/BaseDir.hs | bsd-3-clause | 2,836 | 0 | 11 | 491 | 278 | 158 | 120 | 16 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Hpc
-- Copyright : Thomas Tuegel 2011
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides functions for locating various HPC-related paths and
-- a function for adding the necessary options to a PackageDescription to
-- build test suites with HPC enabled.
{- All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
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
OWNER 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 Distribution.Simple.Hpc
( enableCoverage
, htmlDir
, tixDir
, tixFilePath
, markupPackage
, markupTest
) where
import Control.Monad ( when )
import Distribution.Compiler ( CompilerFlavor(..) )
import Distribution.ModuleName ( main )
import Distribution.PackageDescription
( BuildInfo(..)
, Library(..)
, PackageDescription(..)
, TestSuite(..)
, testModules
)
import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) )
import Distribution.Simple.Program ( hpcProgram, requireProgram )
import Distribution.Simple.Program.Hpc ( markup, union )
import Distribution.Simple.Utils ( notice )
import Distribution.Text
import Distribution.Verbosity ( Verbosity() )
import System.Directory ( createDirectoryIfMissing, doesFileExist )
import System.FilePath
-- -------------------------------------------------------------------------
-- Haskell Program Coverage
-- | Conditionally enable Haskell Program Coverage by adding the necessary
-- GHC options to a PackageDescription.
--
-- TODO: do this differently in the build stage by constructing local build
-- info, not by modifying the original PackageDescription.
--
enableCoverage :: Bool -- ^ Enable coverage?
-> String -- ^ \"dist/\" prefix
-> PackageDescription
-> PackageDescription
enableCoverage False _ x = x
enableCoverage True distPref p =
p { library = fmap enableLibCoverage (library p)
, testSuites = map enableTestCoverage (testSuites p)
}
where
enableBICoverage name oldBI =
let oldOptions = options oldBI
oldGHCOpts = lookup GHC oldOptions
newGHCOpts = case oldGHCOpts of
Just xs -> (GHC, hpcOpts ++ xs)
_ -> (GHC, hpcOpts)
newOptions = (:) newGHCOpts $ filter ((== GHC) . fst) oldOptions
hpcOpts = ["-fhpc", "-hpcdir", mixDir distPref name]
in oldBI { options = newOptions }
enableLibCoverage l =
l { libBuildInfo = enableBICoverage (display $ package p)
(libBuildInfo l)
}
enableTestCoverage t =
t { testBuildInfo = enableBICoverage (testName t) (testBuildInfo t) }
hpcDir :: FilePath -- ^ \"dist/\" prefix
-> FilePath -- ^ Directory containing component's HPC .mix files
hpcDir distPref = distPref </> "hpc"
mixDir :: FilePath -- ^ \"dist/\" prefix
-> FilePath -- ^ Component name
-> FilePath -- ^ Directory containing test suite's .mix files
mixDir distPref name = hpcDir distPref </> "mix" </> name
tixDir :: FilePath -- ^ \"dist/\" prefix
-> FilePath -- ^ Component name
-> FilePath -- ^ Directory containing test suite's .tix files
tixDir distPref name = hpcDir distPref </> "tix" </> name
-- | Path to the .tix file containing a test suite's sum statistics.
tixFilePath :: FilePath -- ^ \"dist/\" prefix
-> FilePath -- ^ Component name
-> FilePath -- ^ Path to test suite's .tix file
tixFilePath distPref name = tixDir distPref name </> name <.> "tix"
htmlDir :: FilePath -- ^ \"dist/\" prefix
-> FilePath -- ^ Component name
-> FilePath -- ^ Path to test suite's HTML markup directory
htmlDir distPref name = hpcDir distPref </> "html" </> name
-- | Generate the HTML markup for a test suite.
markupTest :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^ \"dist/\" prefix
-> String -- ^ Library name
-> TestSuite
-> IO ()
markupTest verbosity lbi distPref libName suite = do
tixFileExists <- doesFileExist $ tixFilePath distPref $ testName suite
when tixFileExists $ do
(hpc, _) <- requireProgram verbosity hpcProgram $ withPrograms lbi
markup hpc verbosity (tixFilePath distPref $ testName suite)
(mixDir distPref libName)
(htmlDir distPref $ testName suite)
(testModules suite ++ [ main ])
notice verbosity $ "Test coverage report written to "
++ htmlDir distPref (testName suite)
</> "hpc_index" <.> "html"
-- | Generate the HTML markup for all of a package's test suites.
markupPackage :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^ \"dist/\" prefix
-> String -- ^ Library name
-> [TestSuite]
-> IO ()
markupPackage verbosity lbi distPref libName suites = do
let tixFiles = map (tixFilePath distPref . testName) suites
tixFilesExist <- mapM doesFileExist tixFiles
when (and tixFilesExist) $ do
(hpc, _) <- requireProgram verbosity hpcProgram $ withPrograms lbi
let outFile = tixFilePath distPref libName
mixDir' = mixDir distPref libName
htmlDir' = htmlDir distPref libName
excluded = concatMap testModules suites ++ [ main ]
createDirectoryIfMissing True $ takeDirectory outFile
union hpc verbosity tixFiles outFile excluded
markup hpc verbosity outFile mixDir' htmlDir' excluded
notice verbosity $ "Package coverage report written to "
++ htmlDir' </> "hpc_index.html"
| IreneKnapp/Faction | libfaction/Distribution/Simple/Hpc.hs | bsd-3-clause | 7,289 | 0 | 15 | 1,909 | 1,108 | 598 | 510 | 102 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Reflex.Dom.Widget.Resize where
import Reflex.Class
import Reflex.Time
import Reflex.Dom.Builder.Class
import Reflex.Dom.Builder.Immediate
import Reflex.Dom.Class
import Reflex.Dom.Widget.Basic
import Reflex.PerformEvent.Class
import Reflex.PostBuild.Class
import Reflex.TriggerEvent.Class
import Control.Monad
import Control.Monad.Fix
import Control.Monad.IO.Class
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import GHCJS.DOM.Element
import GHCJS.DOM.EventM (on)
import qualified GHCJS.DOM.GlobalEventHandlers as Events (scroll)
import GHCJS.DOM.Types (MonadJSM, liftJSM, uncheckedCastTo, HTMLElement(..))
import GHCJS.DOM.HTMLElement (getOffsetWidth, getOffsetHeight)
import qualified GHCJS.DOM.Types as DOM
-- | A widget that wraps the given widget in a div and fires an event when resized.
-- Adapted from @github.com\/marcj\/css-element-queries@
--
-- This function can cause strange scrollbars to appear in some circumstances.
-- These can be hidden with pseudo selectors, for example, in webkit browsers:
-- .wrapper *::-webkit-scrollbar { width: 0px; background: transparent; }
resizeDetector :: (MonadJSM m, DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadJSM (Performable m), MonadFix m) => m a -> m (Event t (Maybe Double, Maybe Double), a)
resizeDetector = resizeDetectorWithStyle ""
resizeDetectorWithStyle :: (MonadJSM m, DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadJSM (Performable m), MonadFix m)
=> Text -- ^ A css style string. Warning: It should not contain the "position" style attribute.
-> m a -- ^ The embedded widget
-> m (Event t (Maybe Double, Maybe Double), a) -- ^ An 'Event' that fires on resize, and the result of the embedded widget
resizeDetectorWithStyle styleString = resizeDetectorWithAttrs ("style" =: styleString)
resizeDetectorWithAttrs :: (MonadJSM m, DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadJSM (Performable m), MonadFix m)
=> Map Text Text -- ^ A map of attributes. Warning: It should not modify the "position" style attribute.
-> m a -- ^ The embedded widget
-> m (Event t (Maybe Double, Maybe Double), a) -- ^ An 'Event' that fires on resize, and the result of the embedded widget
resizeDetectorWithAttrs attrs w = do
let childStyle = "position: absolute; left: 0; top: 0;"
containerAttrs = "style" =: "position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: scroll; z-index: -1; visibility: hidden;"
(parent, (expand, expandChild, shrink, w')) <- elAttr' "div" (Map.unionWith (<>) attrs ("style" =: "position: relative;")) $ do
w' <- w
elAttr "div" containerAttrs $ do
(expand, (expandChild, _)) <- elAttr' "div" containerAttrs $ elAttr' "div" ("style" =: childStyle) $ return ()
(shrink, _) <- elAttr' "div" containerAttrs $ elAttr "div" ("style" =: (childStyle <> "width: 200%; height: 200%;")) $ return ()
return (expand, expandChild, shrink, w')
let p = uncheckedCastTo HTMLElement $ _element_raw parent
reset = do
let e = uncheckedCastTo HTMLElement $ _element_raw expand
s = _element_raw shrink
eow <- getOffsetWidth e
eoh <- getOffsetHeight e
let ecw = eow + 10
ech = eoh + 10
setAttribute (_element_raw expandChild) ("style" :: Text) (childStyle <> "width: " <> T.pack (show ecw) <> "px;" <> "height: " <> T.pack (show ech) <> "px;")
esw <- getScrollWidth e
setScrollLeft e esw
esh <- getScrollHeight e
setScrollTop e esh
ssw <- getScrollWidth s
setScrollLeft s ssw
ssh <- getScrollHeight s
setScrollTop s ssh
lastWidth <- getOffsetWidth p
lastHeight <- getOffsetHeight p
return (Just lastWidth, Just lastHeight)
resetIfChanged ds = do
pow <- getOffsetWidth p
poh <- getOffsetHeight p
if ds == (Just pow, Just poh)
then return Nothing
else fmap Just reset
pb <- delay 0 =<< getPostBuild
expandScroll <- wrapDomEvent (DOM.uncheckedCastTo DOM.HTMLElement $ _element_raw expand) (`on` Events.scroll) $ return ()
shrinkScroll <- wrapDomEvent (DOM.uncheckedCastTo DOM.HTMLElement $ _element_raw shrink) (`on` Events.scroll) $ return ()
size0 <- performEvent $ fmap (const $ liftJSM reset) pb
rec resize <- performEventAsync $ fmap (\d cb -> (liftIO . cb) =<< liftJSM (resetIfChanged d)) $ tag (current dimensions) $ leftmost [expandScroll, shrinkScroll]
dimensions <- holdDyn (Nothing, Nothing) $ leftmost [ size0, fmapMaybe id resize ]
return (updated dimensions, w')
| reflex-frp/reflex-dom | reflex-dom-core/src/Reflex/Dom/Widget/Resize.hs | bsd-3-clause | 5,041 | 0 | 21 | 959 | 1,415 | 733 | 682 | 83 | 2 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * 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.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- 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 Feldspar.Core.Frontend.Future where
import Language.Syntactic
import Feldspar.Core.Types
import Feldspar.Core.Constructs
import Feldspar.Core.Constructs.Future
import Feldspar.Core.Frontend.Save
newtype Future a = Future { unFuture :: Data (FVal (Internal a)) }
later :: (Syntax a, Syntax b) => (a -> b) -> Future a -> Future b
later f = future . f . await
pval :: (Syntax a, Syntax b) => (a -> b) -> a -> b
pval f x = await $ force $ future (f x)
instance Syntax a => Syntactic (Future a)
where
type Domain (Future a) = FeldDomain
type Internal (Future a) = FVal (Internal a)
desugar = desugar . unFuture
sugar = Future . sugar
future :: Syntax a => a -> Future a
future = sugarSymF MkFuture
await :: Syntax a => Future a -> a
await = sugarSymF Await
| emwap/feldspar-language | src/Feldspar/Core/Frontend/Future.hs | bsd-3-clause | 2,562 | 0 | 11 | 479 | 351 | 203 | 148 | 25 | 1 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Attoparsec/ByteString.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE Trustworthy #-}
-- |
-- Module : Data.Attoparsec.ByteString
-- Copyright : Bryan O'Sullivan 2007-2015
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : unknown
--
-- Simple, efficient combinator parsing for 'B.ByteString' strings,
-- loosely based on the Parsec library.
module Data.Attoparsec.ByteString
(
-- * Differences from Parsec
-- $parsec
-- * Incremental input
-- $incremental
-- * Performance considerations
-- $performance
-- * Parser types
I.Parser
, Result
, T.IResult(..)
, I.compareResults
-- * Running parsers
, parse
, feed
, I.parseOnly
, parseWith
, parseTest
-- ** Result conversion
, maybeResult
, eitherResult
-- * Parsing individual bytes
, I.word8
, I.anyWord8
, I.notWord8
, I.satisfy
, I.satisfyWith
, I.skip
-- ** Lookahead
, I.peekWord8
, I.peekWord8'
-- ** Byte classes
, I.inClass
, I.notInClass
-- * Efficient string handling
, I.string
, I.skipWhile
, I.take
, I.scan
, I.runScanner
, I.takeWhile
, I.takeWhile1
, I.takeTill
-- ** Consume all remaining input
, I.takeByteString
, I.takeLazyByteString
-- * Combinators
, try
, (<?>)
, choice
, count
, option
, many'
, many1
, many1'
, manyTill
, manyTill'
, sepBy
, sepBy'
, sepBy1
, sepBy1'
, skipMany
, skipMany1
, eitherP
, I.match
-- * State observation and manipulation functions
, I.endOfInput
, I.atEnd
) where
import Data.Attoparsec.Combinator
import Data.List (intercalate)
import qualified Data.Attoparsec.ByteString.Internal as I
import qualified Data.Attoparsec.Internal as I
import qualified Data.ByteString as B
import Data.Attoparsec.ByteString.Internal (Result, parse)
import qualified Data.Attoparsec.Internal.Types as T
-- $parsec
--
-- Compared to Parsec 3, attoparsec makes several tradeoffs. It is
-- not intended for, or ideal for, all possible uses.
--
-- * While attoparsec can consume input incrementally, Parsec cannot.
-- Incremental input is a huge deal for efficient and secure network
-- and system programming, since it gives much more control to users
-- of the library over matters such as resource usage and the I/O
-- model to use.
--
-- * Much of the performance advantage of attoparsec is gained via
-- high-performance parsers such as 'I.takeWhile' and 'I.string'.
-- If you use complicated combinators that return lists of bytes or
-- characters, there is less performance difference between the two
-- libraries.
--
-- * Unlike Parsec 3, attoparsec does not support being used as a
-- monad transformer.
--
-- * attoparsec is specialised to deal only with strict 'B.ByteString'
-- input. Efficiency concerns rule out both lists and lazy
-- bytestrings. The usual use for lazy bytestrings would be to
-- allow consumption of very large input without a large footprint.
-- For this need, attoparsec's incremental input provides an
-- excellent substitute, with much more control over when input
-- takes place. If you must use lazy bytestrings, see the
-- "Data.Attoparsec.ByteString.Lazy" module, which feeds lazy chunks
-- to a regular parser.
--
-- * Parsec parsers can produce more helpful error messages than
-- attoparsec parsers. This is a matter of focus: attoparsec avoids
-- the extra book-keeping in favour of higher performance.
-- $incremental
--
-- attoparsec supports incremental input, meaning that you can feed it
-- a bytestring that represents only part of the expected total amount
-- of data to parse. If your parser reaches the end of a fragment of
-- input and could consume more input, it will suspend parsing and
-- return a 'T.Partial' continuation.
--
-- Supplying the 'T.Partial' continuation with a bytestring will
-- resume parsing at the point where it was suspended, with the
-- bytestring you supplied used as new input at the end of the
-- existing input. You must be prepared for the result of the resumed
-- parse to be another 'T.Partial' continuation.
--
-- To indicate that you have no more input, supply the 'T.Partial'
-- continuation with an empty bytestring.
--
-- Remember that some parsing combinators will not return a result
-- until they reach the end of input. They may thus cause 'T.Partial'
-- results to be returned.
--
-- If you do not need support for incremental input, consider using
-- the 'I.parseOnly' function to run your parser. It will never
-- prompt for more input.
--
-- /Note/: incremental input does /not/ imply that attoparsec will
-- release portions of its internal state for garbage collection as it
-- proceeds. Its internal representation is equivalent to a single
-- 'ByteString': if you feed incremental input to a parser, it will
-- require memory proportional to the amount of input you supply.
-- (This is necessary to support arbitrary backtracking.)
-- $performance
--
-- If you write an attoparsec-based parser carefully, it can be
-- realistic to expect it to perform similarly to a hand-rolled C
-- parser (measuring megabytes parsed per second).
--
-- To actually achieve high performance, there are a few guidelines
-- that it is useful to follow.
--
-- Use the 'B.ByteString'-oriented parsers whenever possible,
-- e.g. 'I.takeWhile1' instead of 'many1' 'I.anyWord8'. There is
-- about a factor of 100 difference in performance between the two
-- kinds of parser.
--
-- For very simple byte-testing predicates, write them by hand instead
-- of using 'I.inClass' or 'I.notInClass'. For instance, both of
-- these predicates test for an end-of-line byte, but the first is
-- much faster than the second:
--
-- >endOfLine_fast w = w == 13 || w == 10
-- >endOfLine_slow = inClass "\r\n"
--
-- Make active use of benchmarking and profiling tools to measure,
-- find the problems with, and improve the performance of your parser.
-- | Run a parser and print its result to standard output.
parseTest :: (Show a) => I.Parser a -> B.ByteString -> IO ()
parseTest p s = print (parse p s)
-- | Run a parser with an initial input string, and a monadic action
-- that can supply more input if needed.
parseWith :: Monad m =>
(m B.ByteString)
-- ^ An action that will be executed to provide the parser
-- with more input, if necessary. The action must return an
-- 'B.empty' string when there is no more input available.
-> I.Parser a
-> B.ByteString
-- ^ Initial input for the parser.
-> m (Result a)
parseWith refill p s = step $ parse p s
where step (T.Partial k) = (step . k) =<< refill
step r = return r
{-# INLINE parseWith #-}
-- | Convert a 'Result' value to a 'Maybe' value. A 'T.Partial' result
-- is treated as failure.
maybeResult :: Result r -> Maybe r
maybeResult (T.Done _ r) = Just r
maybeResult _ = Nothing
-- | Convert a 'Result' value to an 'Either' value. A 'T.Partial'
-- result is treated as failure.
eitherResult :: Result r -> Either String r
eitherResult (T.Done _ r) = Right r
eitherResult (T.Fail _ [] msg) = Left msg
eitherResult (T.Fail _ ctxs msg) = Left (intercalate " > " ctxs ++ ": " ++ msg)
eitherResult _ = Left "Result: incomplete input"
| phischu/fragnix | tests/packages/scotty/Data.Attoparsec.ByteString.hs | bsd-3-clause | 7,604 | 0 | 11 | 1,757 | 742 | 475 | 267 | 83 | 2 |
factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)
| maggy96/haskell | smaller snippets/myfac.hs | mit | 88 | 0 | 8 | 21 | 49 | 25 | 24 | 3 | 1 |
module Specify.Check where
import Specify.Definition
import Specify.Constraint
import Specify.Eval
import Autolib.Reporter
import Autolib.ToDoc
full :: System
-> Program
-> Int
-> Reporter [ ( Maybe Bool, Doc ) ]
full ( System cs ) p num = do
results <- mapM ( \ c -> single c p num ) cs
return $ concat results
single :: Constraint
-> Program
-> Int
-> Reporter [ ( Maybe Bool, Doc ) ]
single con @ ( Constraint vars body ) p num = do
sequence $ do
values <- take num $ candidates $ length vars
return $ do
let pairs = zip vars values
let ( mmx, doc ) = export $ do
inform $ text "Constraint:" <+> toDoc con
when ( not $ null pairs )
$ inform $ text "Belegung:" <+> bform pairs
nested 4 $ do
inform $ text "dabei berechnete Funktionswerte:"
eval ( extend p pairs ) body
case mmx of
Nothing -> reject $ doc
Just mx -> return ( mx, doc )
bform pairs = hsep $ do
( i, v ) <- pairs
return $ hsep [ toDoc i, text "=", toDoc v, semi ]
-- | all tuples of naturals of given length,
-- listed in order of increasing sum.
-- produces infinite list.
candidates 0 = return []
candidates l = do
let handle s 1 = return [s]
handle s l = do
x <- [ 0 .. s ]
xs <- handle (s - x) (l-1)
return $ x : xs
s <- [ 0 .. ]
handle s l
| florianpilz/autotool | src/Specify/Check.hs | gpl-2.0 | 1,517 | 3 | 27 | 567 | 544 | 265 | 279 | 44 | 2 |
module Text.XML.HaXml.TypeMapping
(
-- * A class to get an explicit type representation for any value
HTypeable(..) -- sole method, toHType
-- * Explicit representation of Haskell datatype information
, HType(..) -- instance of Eq, Show
, Constr(..) -- instance of Eq, Show
-- * Helper functions to extract type info as strings
, showHType -- :: HType -> ShowS
, showConstr -- :: Int -> HType -> String
-- * Conversion from Haskell datatype to DTD
, toDTD
) where
import Text.XML.HaXml.Types
import Data.List (partition, intersperse)
import Text.PrettyPrint.HughesPJ (render)
import qualified Text.XML.HaXml.Pretty as PP
------------------------------------------------------------------------
-- idea: in DrIFT,
-- named field == primitive type, becomes an attribute
-- named field == single-constructor type, renames the tag
-- named field == multi-constructor type, as normal
-- if prefix of all named fields is roughly typename, delete it
-- | @HTypeable@ promises that we can create an explicit representation of
-- of the type of any value.
class HTypeable a where
toHType :: a -> HType
-- | A concrete representation of any Haskell type.
data HType =
Maybe HType
| List HType
| Tuple [HType]
| Prim String String -- ^ separate Haskell name and XML name
| String
| Defined String [HType] [Constr]
-- ^ A user-defined type has a name, a sequence of type variables,
-- and a set of constructors. (The variables might already be
-- instantiated to actual types.)
deriving (Show)
instance Eq HType where
(Maybe x) == (Maybe y) = x==y
(List x) == (List y) = x==y
(Tuple xs) == (Tuple ys) = xs==ys
(Prim x _) == (Prim y _) = x==y
String == String = True
(Defined n _xs _) == (Defined m _ys _) = n==m -- && xs==ys
_ == _ = False
-- | A concrete representation of any user-defined Haskell constructor.
-- The constructor has a name, and a sequence of component types. The
-- first sequence of types represents the minimum set of free type
-- variables occurring in the (second) list of real component types.
-- If there are fieldnames, they are contained in the final list, and
-- correspond one-to-one with the component types.
data Constr = Constr String [HType] [HType] -- (Maybe [String])
deriving (Eq,Show)
-- | Project the n'th constructor from an HType and convert it to a string
-- suitable for an XML tagname.
showConstr :: Int -> HType -> String
showConstr n (Defined _ _ cs) = flatConstr (cs!!n) ""
showConstr _ _ = error "no constructors for builtin types"
------------------------------------------------------------------------
-- Some instances
instance HTypeable Bool where
toHType _ = Prim "Bool" "bool"
instance HTypeable Int where
toHType _ = Prim "Int" "int"
instance HTypeable Integer where
toHType _ = Prim "Integer" "integer"
instance HTypeable Float where
toHType _ = Prim "Float" "float"
instance HTypeable Double where
toHType _ = Prim "Double" "double"
instance HTypeable Char where
toHType _ = Prim "Char" "char"
instance HTypeable () where
toHType _ = Prim "unit" "unit"
instance (HTypeable a, HTypeable b) => HTypeable (a,b) where
toHType p = Tuple [toHType a, toHType b]
where (a,b) = p
instance (HTypeable a, HTypeable b, HTypeable c) => HTypeable (a,b,c) where
toHType p = Tuple [toHType a, toHType b, toHType c]
where (a,b,c) = p
instance (HTypeable a, HTypeable b, HTypeable c, HTypeable d) =>
HTypeable (a,b,c,d) where
toHType p = Tuple [toHType a, toHType b, toHType c, toHType d]
where (a,b,c,d) = p
instance (HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e) =>
HTypeable (a,b,c,d,e) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e ]
where (a,b,c,d,e) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f) =>
HTypeable (a,b,c,d,e,f) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f ]
where (a,b,c,d,e,f) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g) =>
HTypeable (a,b,c,d,e,f,g) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g ]
where (a,b,c,d,e,f,g) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g, HTypeable h) =>
HTypeable (a,b,c,d,e,f,g,h) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g, toHType h ]
where (a,b,c,d,e,f,g,h) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g, HTypeable h, HTypeable i) =>
HTypeable (a,b,c,d,e,f,g,h,i) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g, toHType h
, toHType i ]
where (a,b,c,d,e,f,g,h,i) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g, HTypeable h, HTypeable i, HTypeable j) =>
HTypeable (a,b,c,d,e,f,g,h,i,j) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g, toHType h
, toHType i, toHType j ]
where (a,b,c,d,e,f,g,h,i,j) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g, HTypeable h, HTypeable i, HTypeable j
, HTypeable k) =>
HTypeable (a,b,c,d,e,f,g,h,i,j,k) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g, toHType h
, toHType i, toHType j, toHType k ]
where (a,b,c,d,e,f,g,h,i,j,k) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g, HTypeable h, HTypeable i, HTypeable j
, HTypeable k, HTypeable l) =>
HTypeable (a,b,c,d,e,f,g,h,i,j,k,l) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g, toHType h
, toHType i, toHType j, toHType k, toHType l ]
where (a,b,c,d,e,f,g,h,i,j,k,l) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g, HTypeable h, HTypeable i, HTypeable j
, HTypeable k, HTypeable l, HTypeable m) =>
HTypeable (a,b,c,d,e,f,g,h,i,j,k,l,m) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g, toHType h
, toHType i, toHType j, toHType k, toHType l
, toHType m ]
where (a,b,c,d,e,f,g,h,i,j,k,l,m) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g, HTypeable h, HTypeable i, HTypeable j
, HTypeable k, HTypeable l, HTypeable m, HTypeable n) =>
HTypeable (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g, toHType h
, toHType i, toHType j, toHType k, toHType l
, toHType m, toHType n ]
where (a,b,c,d,e,f,g,h,i,j,k,l,m,n) = p
instance ( HTypeable a, HTypeable b, HTypeable c, HTypeable d, HTypeable e
, HTypeable f, HTypeable g, HTypeable h, HTypeable i, HTypeable j
, HTypeable k, HTypeable l, HTypeable m, HTypeable n, HTypeable o) =>
HTypeable (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where
toHType p = Tuple [ toHType a, toHType b, toHType c, toHType d
, toHType e, toHType f, toHType g, toHType h
, toHType i, toHType j, toHType k, toHType l
, toHType m, toHType n, toHType o ]
where (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) = p
instance (HTypeable a) => HTypeable (Maybe a) where
toHType m = Maybe (toHType x) where (Just x) = m
instance (HTypeable a, HTypeable b) => HTypeable (Either a b) where
toHType m = Defined "Either" [hx, hy]
[ Constr "Left" [hx] [hx] {-Nothing-}
, Constr "Right" [hy] [hy] {-Nothing-}]
where (Left x) = m
(Right y) = m
hx = toHType x
hy = toHType y
instance HTypeable a => HTypeable [a] where
toHType xs = case toHType x of (Prim "Char" _) -> String
_ -> List (toHType x)
where (x:_) = xs
------------------------------------------------------------------------
-- | 'toDTD' converts a concrete representation of the Haskell type of
-- a value (obtained by the method 'toHType') into a real DocTypeDecl.
-- It ensures that PERefs are defined before they are used, and that no
-- element or attribute-list is declared more than once.
toDTD :: HType -> DocTypeDecl
toDTD ht =
DTD (toplevel ht) Nothing (macrosFirst (reverse (h2d True [] [] [ht])))
where
macrosFirst :: [MarkupDecl] -> [MarkupDecl]
macrosFirst decls = concat [p, p'] where (p, p') = partition f decls
f (Entity _) = True
f _ = False
toplevel ht@(Defined _ _ _) = N $ showHType ht "-XML"
toplevel ht@_ = N $ showHType ht ""
c0 = False
h2d :: Bool -> [HType] -> [Constr] -> [HType] -> [MarkupDecl]
-- toplevel? history history remainingwork result
h2d _c _history _chist [] = []
h2d c history chist (ht:hts) =
if ht `elem` history then h2d c0 history chist hts
else
case ht of
Maybe ht0 -> declelem ht: h2d c0 (ht:history) chist (ht0:hts)
List ht0 -> declelem ht: h2d c0 (ht:history) chist (ht0:hts)
Tuple hts0 -> (c ? (declelem ht:))
(h2d c0 history chist (hts0++hts))
Prim _ _ -> declprim ht ++ h2d c0 (ht:history) chist hts
String -> declstring: h2d c0 (ht:history) chist hts
Defined _ _ cs ->
let hts0 = concatMap grab cs in
(c ? (decltopelem ht:)) (declmacro ht chist)
++ h2d c0 (ht:history) (cs++chist) (hts0++hts)
declelem ht =
Element (ElementDecl (N $ showHType ht "")
(ContentSpec (outerHtExpr ht)))
decltopelem ht = -- hack to avoid peref at toplevel
Element (ElementDecl (N $ showHType ht "-XML")
(ContentSpec (innerHtExpr ht None)))
declmacro ht@(Defined _ _ cs) chist =
Entity (EntityPEDecl (PEDecl (showHType ht "") (PEDefEntityValue ev))):
concatMap (declConstr chist) cs
where ev = EntityValue [EVString (render (PP.cp (outerHtExpr ht)))]
declConstr chist c@(Constr s fv hts)
| c `notElem` chist = [Element (ElementDecl (N $ flatConstr c "")
(ContentSpec (constrHtExpr c)))]
| otherwise = []
declprim (Prim _ t) =
[ Element (ElementDecl (N t) EMPTY)
, AttList (AttListDecl (N t) [AttDef (N "value") StringType REQUIRED])]
declstring =
Element (ElementDecl (N "string") (Mixed PCDATA))
grab (Constr _ _ hts) = hts
(?) :: Bool -> (a->a) -> (a->a)
b ? f | b = f
| not b = id
-- Flatten an HType to a String suitable for an XML tagname.
showHType :: HType -> ShowS
showHType (Maybe ht) = showString "maybe-" . showHType ht
showHType (List ht) = showString "list-" . showHType ht
showHType (Tuple hts) = showString "tuple" . shows (length hts)
. showChar '-'
. foldr1 (.) (intersperse (showChar '-')
(map showHType hts))
showHType (Prim _ t) = showString t
showHType String = showString "string"
showHType (Defined s fv _)
= showString s . ((length fv > 0) ? (showChar '-'))
. foldr (.) id (intersperse (showChar '-')
(map showHType fv))
flatConstr :: Constr -> ShowS
flatConstr (Constr s fv _)
= showString s . ((length fv > 0) ? (showChar '-'))
. foldr (.) id (intersperse (showChar '-') (map showHType fv))
outerHtExpr :: HType -> CP
outerHtExpr (Maybe ht) = innerHtExpr ht Query
outerHtExpr (List ht) = innerHtExpr ht Star
outerHtExpr (Defined _s _fv cs) =
Choice (map (\c->TagName (N $ flatConstr c "") None) cs) None
outerHtExpr ht = innerHtExpr ht None
innerHtExpr :: HType -> Modifier -> CP
innerHtExpr (Prim _ t) m = TagName (N t) m
innerHtExpr (Tuple hts) m = Seq (map (\c-> innerHtExpr c None) hts) m
innerHtExpr ht@(Defined _ _ _) m = -- CPPE (showHType ht "") (outerHtExpr ht)
TagName (N ('%': showHType ht ";")) m
-- ***HACK!!!***
innerHtExpr ht m = TagName (N $ showHType ht "") m
constrHtExpr :: Constr -> CP
constrHtExpr (Constr _s _fv []) = TagName (N "EMPTY") None -- ***HACK!!!***
constrHtExpr (Constr _s _fv hts) = innerHtExpr (Tuple hts) None
------------------------------------------------------------------------
| Ian-Stewart-Binks/courseography | dependencies/HaXml-1.25.3/src/Text/XML/HaXml/TypeMapping.hs | gpl-3.0 | 14,222 | 0 | 18 | 4,599 | 5,122 | 2,723 | 2,399 | 233 | 10 |
module TokenDef(tokenDef) where
-- This is a sample TokenDef module. Usually one exists in the
-- same directory as the file that imports ParserAll
import StdTokenDef
import CommentDef
stratusStyle = haskellStyle
{ commentEnd = cEnd
, commentStart = cStart
, commentLine = cLine
, nestedComments = nestedC
, reservedNames = ["let","case","in","of","data","where"]
, reservedOpNames= ["=","\\"]
}
tokenDef = stratusStyle
| cartazio/omega | src/TokenDefExample.hs | bsd-3-clause | 448 | 0 | 7 | 86 | 89 | 59 | 30 | 11 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Reading from external processes.
module System.Process.Read
(readProcessStdout
,readProcessStderrStdout
,tryProcessStdout
,tryProcessStderrStdout
,sinkProcessStdout
,sinkProcessStderrStdout
,sinkProcessStderrStdoutHandle
,logProcessStderrStdout
,readProcess
,EnvOverride(..)
,unEnvOverride
,mkEnvOverride
,modifyEnvOverride
,envHelper
,doesExecutableExist
,findExecutable
,getEnvOverride
,envSearchPath
,preProcess
,readProcessNull
,ReadProcessException (..)
,augmentPath
,augmentPathMap
,resetExeCache
)
where
import Control.Applicative
import Control.Arrow ((***), first)
import Control.Concurrent.Async (concurrently)
import Control.Exception hiding (try, catch)
import Control.Monad (join, liftM, unless, void)
import Control.Monad.Catch (MonadThrow, MonadCatch, throwM, try, catch)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger
import Control.Monad.Trans.Control (MonadBaseControl, liftBaseWith)
import qualified Data.ByteString as S
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy as L
import Data.Conduit
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.Conduit.Process hiding (callProcess)
import Data.IORef
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (isJust, maybeToList, fromMaybe)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding.Error (lenientDecode)
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.Encoding as LT
import Data.Typeable (Typeable)
import Distribution.System (OS (Windows), Platform (Platform))
import Language.Haskell.TH as TH (location)
import Path
import Path.Extra
import Path.IO hiding (findExecutable)
import Prelude -- Fix AMP warning
import qualified System.Directory as D
import System.Environment (getEnvironment)
import System.Exit
import qualified System.FilePath as FP
import System.IO (Handle, hClose)
import System.Process.Log
import Prelude () -- Hide post-AMP warnings
-- | Override the environment received by a child process.
data EnvOverride = EnvOverride
{ eoTextMap :: Map Text Text -- ^ Environment variables as map
, eoStringList :: [(String, String)] -- ^ Environment variables as association list
, eoPath :: [FilePath] -- ^ List of directories searched for executables (@PATH@)
, eoExeCache :: IORef (Map FilePath (Either ReadProcessException (Path Abs File)))
, eoExeExtensions :: [String] -- ^ @[""]@ on non-Windows systems, @["", ".exe", ".bat"]@ on Windows
, eoPlatform :: Platform
}
-- | Get the environment variables from an 'EnvOverride'.
unEnvOverride :: EnvOverride -> Map Text Text
unEnvOverride = eoTextMap
-- | Get the list of directories searched (@PATH@).
envSearchPath :: EnvOverride -> [FilePath]
envSearchPath = eoPath
-- | Modify the environment variables of an 'EnvOverride'.
modifyEnvOverride :: MonadIO m
=> EnvOverride
-> (Map Text Text -> Map Text Text)
-> m EnvOverride
modifyEnvOverride eo f = mkEnvOverride
(eoPlatform eo)
(f $ eoTextMap eo)
-- | Create a new 'EnvOverride'.
mkEnvOverride :: MonadIO m
=> Platform
-> Map Text Text
-> m EnvOverride
mkEnvOverride platform tm' = do
ref <- liftIO $ newIORef Map.empty
return EnvOverride
{ eoTextMap = tm
, eoStringList = map (T.unpack *** T.unpack) $ Map.toList tm
, eoPath =
(if isWindows then (".":) else id)
(maybe [] (FP.splitSearchPath . T.unpack) (Map.lookup "PATH" tm))
, eoExeCache = ref
, eoExeExtensions =
if isWindows
then let pathext = fromMaybe
".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC"
(Map.lookup "PATHEXT" tm)
in map T.unpack $ "" : T.splitOn ";" pathext
else [""]
, eoPlatform = platform
}
where
-- Fix case insensitivity of the PATH environment variable on Windows.
tm
| isWindows = Map.fromList $ map (first T.toUpper) $ Map.toList tm'
| otherwise = tm'
-- Don't use CPP so that the Windows code path is at least type checked
-- regularly
isWindows =
case platform of
Platform _ Windows -> True
_ -> False
-- | Helper conversion function.
envHelper :: EnvOverride -> Maybe [(String, String)]
envHelper = Just . eoStringList
-- | Read from the process, ignoring any output.
--
-- Throws a 'ReadProcessException' exception if the process fails.
readProcessNull :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> Maybe (Path Abs Dir) -- ^ Optional working directory
-> EnvOverride
-> String -- ^ Command
-> [String] -- ^ Command line arguments
-> m ()
readProcessNull wd menv name args =
sinkProcessStdout wd menv name args CL.sinkNull
-- | Try to produce a strict 'S.ByteString' from the stdout of a
-- process.
tryProcessStdout :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> Maybe (Path Abs Dir) -- ^ Optional directory to run in
-> EnvOverride
-> String -- ^ Command
-> [String] -- ^ Command line arguments
-> m (Either ReadProcessException S.ByteString)
tryProcessStdout wd menv name args =
try (readProcessStdout wd menv name args)
-- | Try to produce strict 'S.ByteString's from the stderr and stdout of a
-- process.
tryProcessStderrStdout :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> Maybe (Path Abs Dir) -- ^ Optional directory to run in
-> EnvOverride
-> String -- ^ Command
-> [String] -- ^ Command line arguments
-> m (Either ReadProcessException (S.ByteString, S.ByteString))
tryProcessStderrStdout wd menv name args =
try (readProcessStderrStdout wd menv name args)
-- | Produce a strict 'S.ByteString' from the stdout of a process.
--
-- Throws a 'ReadProcessException' exception if the process fails.
readProcessStdout :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> Maybe (Path Abs Dir) -- ^ Optional directory to run in
-> EnvOverride
-> String -- ^ Command
-> [String] -- ^ Command line arguments
-> m S.ByteString
readProcessStdout wd menv name args =
sinkProcessStdout wd menv name args CL.consume >>=
liftIO . evaluate . S.concat
-- | Produce strict 'S.ByteString's from the stderr and stdout of a process.
--
-- Throws a 'ReadProcessException' exception if the process fails.
readProcessStderrStdout :: (MonadIO m, MonadLogger m, MonadBaseControl IO m)
=> Maybe (Path Abs Dir) -- ^ Optional directory to run in
-> EnvOverride
-> String -- ^ Command
-> [String] -- ^ Command line arguments
-> m (S.ByteString, S.ByteString)
readProcessStderrStdout wd menv name args = do
(e, o) <- sinkProcessStderrStdout wd menv name args CL.consume CL.consume
liftIO $ (,) <$> evaluate (S.concat e) <*> evaluate (S.concat o)
-- | An exception while trying to read from process.
data ReadProcessException
= ProcessFailed CreateProcess ExitCode L.ByteString L.ByteString
-- ^ @'ProcessFailed' createProcess exitCode stdout stderr@
| NoPathFound
| ExecutableNotFound String [FilePath]
| ExecutableNotFoundAt FilePath
deriving Typeable
instance Show ReadProcessException where
show (ProcessFailed cp ec out err) = concat $
[ "Running "
, showSpec $ cmdspec cp] ++
maybe [] (\x -> [" in directory ", x]) (cwd cp) ++
[ " exited with "
, show ec
, "\n\n"
, toStr out
, "\n"
, toStr err
]
where
toStr = LT.unpack . LT.decodeUtf8With lenientDecode
showSpec (ShellCommand str) = str
showSpec (RawCommand cmd args) =
unwords $ cmd : map (T.unpack . showProcessArgDebug) args
show NoPathFound = "PATH not found in EnvOverride"
show (ExecutableNotFound name path) = concat
[ "Executable named "
, name
, " not found on path: "
, show path
]
show (ExecutableNotFoundAt name) =
"Did not find executable at specified path: " ++ name
instance Exception ReadProcessException
-- | Consume the stdout of a process feeding strict 'S.ByteString's to a consumer.
-- If the process fails, spits out stdout and stderr as error log
-- level. Should not be used for long-running processes or ones with
-- lots of output; for that use 'sinkProcessStdoutLogStderr'.
--
-- Throws a 'ReadProcessException' if unsuccessful.
sinkProcessStdout
:: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> Maybe (Path Abs Dir) -- ^ Optional directory to run in
-> EnvOverride
-> String -- ^ Command
-> [String] -- ^ Command line arguments
-> Sink S.ByteString IO a -- ^ Sink for stdout
-> m a
sinkProcessStdout wd menv name args sinkStdout = do
stderrBuffer <- liftIO (newIORef mempty)
stdoutBuffer <- liftIO (newIORef mempty)
(_,sinkRet) <-
catch
(sinkProcessStderrStdout
wd
menv
name
args
(CL.mapM_ (\bytes -> liftIO (modifyIORef' stderrBuffer (<> byteString bytes))))
(CL.iterM (\bytes -> liftIO (modifyIORef' stdoutBuffer (<> byteString bytes))) $=
sinkStdout))
(\(ProcessExitedUnsuccessfully cp ec) ->
do stderrBuilder <- liftIO (readIORef stderrBuffer)
stdoutBuilder <- liftIO (readIORef stdoutBuffer)
throwM $ ProcessFailed
cp
ec
(toLazyByteString stdoutBuilder)
(toLazyByteString stderrBuilder))
return sinkRet
logProcessStderrStdout
:: (MonadIO m, MonadBaseControl IO m, MonadLogger m)
=> Maybe (Path Abs Dir)
-> String
-> EnvOverride
-> [String]
-> m ()
logProcessStderrStdout mdir name menv args = liftBaseWith $ \restore -> do
let logLines = CB.lines =$ CL.mapM_ (void . restore . monadLoggerLog $(TH.location >>= liftLoc) "" LevelInfo . toLogStr)
void $ restore $ sinkProcessStderrStdout mdir menv name args logLines logLines
-- | Consume the stdout and stderr of a process feeding strict 'S.ByteString's to the consumers.
--
-- Throws a 'ReadProcessException' if unsuccessful in launching, or 'ProcessExitedUnsuccessfully' if the process itself fails.
sinkProcessStderrStdout :: forall m e o. (MonadIO m, MonadLogger m)
=> Maybe (Path Abs Dir) -- ^ Optional directory to run in
-> EnvOverride
-> String -- ^ Command
-> [String] -- ^ Command line arguments
-> Sink S.ByteString IO e -- ^ Sink for stderr
-> Sink S.ByteString IO o -- ^ Sink for stdout
-> m (e,o)
sinkProcessStderrStdout wd menv name args sinkStderr sinkStdout = do
name' <- preProcess wd menv name
$withProcessTimeLog name' args $
liftIO $ withCheckedProcess
(proc name' args) { env = envHelper menv, cwd = fmap toFilePath wd }
(\ClosedStream out err -> f err out)
where
-- There is a bug in streaming-commons or conduit-extra which
-- leads to a file descriptor leak. Ideally, we should be able to
-- simply use the following code. Instead, we're using the code
-- below it, which is explicit in closing Handles. When the
-- upstream bug is fixed, we can consider moving back to the
-- simpler code, though there's really no downside to the more
-- complex version used here.
--
-- f :: Source IO S.ByteString -> Source IO S.ByteString -> IO (e, o)
-- f err out = (err $$ sinkStderr) `concurrently` (out $$ sinkStdout)
f :: Handle -> Handle -> IO (e, o)
f err out = ((CB.sourceHandle err $$ sinkStderr) `concurrently` (CB.sourceHandle out $$ sinkStdout))
`finally` hClose err `finally` hClose out
-- | Like sinkProcessStderrStdout, but receives Handles for stderr and stdout instead of 'Sink's.
--
-- Throws a 'ReadProcessException' if unsuccessful in launching, or 'ProcessExitedUnsuccessfully' if the process itself fails.
sinkProcessStderrStdoutHandle :: (MonadIO m, MonadLogger m)
=> Maybe (Path Abs Dir) -- ^ Optional directory to run in
-> EnvOverride
-> String -- ^ Command
-> [String] -- ^ Command line arguments
-> Handle
-> Handle
-> m ()
sinkProcessStderrStdoutHandle wd menv name args err out = do
name' <- preProcess wd menv name
$withProcessTimeLog name' args $
liftIO $ withCheckedProcess
(proc name' args)
{ env = envHelper menv
, cwd = fmap toFilePath wd
, std_err = UseHandle err
, std_out = UseHandle out
}
(\ClosedStream UseProvidedHandle UseProvidedHandle -> return ())
-- | Perform pre-call-process tasks. Ensure the working directory exists and find the
-- executable path.
--
-- Throws a 'ReadProcessException' if unsuccessful.
preProcess :: (MonadIO m)
=> Maybe (Path Abs Dir) -- ^ Optional directory to create if necessary
-> EnvOverride -- ^ How to override environment
-> String -- ^ Command name
-> m FilePath
preProcess wd menv name = do
name' <- liftIO $ liftM toFilePath $ join $ findExecutable menv name
maybe (return ()) ensureDir wd
return name'
-- | Check if the given executable exists on the given PATH.
doesExecutableExist :: (MonadIO m)
=> EnvOverride -- ^ How to override environment
-> String -- ^ Name of executable
-> m Bool
doesExecutableExist menv name = liftM isJust $ findExecutable menv name
-- | Find the complete path for the executable.
--
-- Throws a 'ReadProcessException' if unsuccessful.
findExecutable :: (MonadIO m, MonadThrow n)
=> EnvOverride -- ^ How to override environment
-> String -- ^ Name of executable
-> m (n (Path Abs File)) -- ^ Full path to that executable on success
findExecutable eo name0 | any FP.isPathSeparator name0 = do
let names0 = map (name0 ++) (eoExeExtensions eo)
testNames [] = return $ throwM $ ExecutableNotFoundAt name0
testNames (name:names) = do
exists <- liftIO $ D.doesFileExist name
if exists
then do
path <- liftIO $ resolveFile' name
return $ return path
else testNames names
testNames names0
findExecutable eo name = liftIO $ do
m <- readIORef $ eoExeCache eo
epath <- case Map.lookup name m of
Just epath -> return epath
Nothing -> do
let loop [] = return $ Left $ ExecutableNotFound name (eoPath eo)
loop (dir:dirs) = do
let fp0 = dir FP.</> name
fps0 = map (fp0 ++) (eoExeExtensions eo)
testFPs [] = loop dirs
testFPs (fp:fps) = do
exists <- D.doesFileExist fp
existsExec <- if exists then liftM D.executable $ D.getPermissions fp else return False
if existsExec
then do
fp' <- D.makeAbsolute fp >>= parseAbsFile
return $ return fp'
else testFPs fps
testFPs fps0
epath <- loop $ eoPath eo
() <- atomicModifyIORef (eoExeCache eo) $ \m' ->
(Map.insert name epath m', ())
return epath
return $ either throwM return epath
-- | Reset the executable cache.
resetExeCache :: MonadIO m => EnvOverride -> m ()
resetExeCache eo = liftIO (atomicModifyIORef (eoExeCache eo) (const mempty))
-- | Load up an 'EnvOverride' from the standard environment.
getEnvOverride :: MonadIO m => Platform -> m EnvOverride
getEnvOverride platform =
liftIO $
getEnvironment >>=
mkEnvOverride platform
. Map.fromList . map (T.pack *** T.pack)
newtype PathException = PathsInvalidInPath [FilePath]
deriving Typeable
instance Exception PathException
instance Show PathException where
show (PathsInvalidInPath paths) = unlines $
[ "Would need to add some paths to the PATH environment variable \
\to continue, but they would be invalid because they contain a "
++ show FP.searchPathSeparator ++ "."
, "Please fix the following paths and try again:"
] ++ paths
-- | Augment the PATH environment variable with the given extra paths.
augmentPath :: MonadThrow m => [Path Abs Dir] -> Maybe Text -> m Text
augmentPath dirs mpath =
do let illegal = filter (FP.searchPathSeparator `elem`) (map toFilePath dirs)
unless (null illegal) (throwM $ PathsInvalidInPath illegal)
return $ T.intercalate (T.singleton FP.searchPathSeparator)
$ map (T.pack . toFilePathNoTrailingSep) dirs
++ maybeToList mpath
-- | Apply 'augmentPath' on the PATH value in the given Map.
augmentPathMap :: MonadThrow m => [Path Abs Dir] -> Map Text Text
-> m (Map Text Text)
augmentPathMap dirs origEnv =
do path <- augmentPath dirs mpath
return $ Map.insert "PATH" path origEnv
where
mpath = Map.lookup "PATH" origEnv
| Fuuzetsu/stack | src/System/Process/Read.hs | bsd-3-clause | 18,638 | 0 | 30 | 5,523 | 4,036 | 2,150 | 1,886 | 351 | 8 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
module Distribution.Client.GlobalFlags (
GlobalFlags(..)
, defaultGlobalFlags
, RepoContext(..)
, withRepoContext
, withRepoContext'
) where
import Prelude ()
import Distribution.Client.Compat.Prelude
import Distribution.Client.Types
( Repo(..), RemoteRepo(..) )
import Distribution.Simple.Setup
( Flag(..), fromFlag, flagToMaybe )
import Distribution.Utils.NubList
( NubList, fromNubList )
import Distribution.Client.HttpUtils
( HttpTransport, configureTransport )
import Distribution.Verbosity
( Verbosity )
import Distribution.Simple.Utils
( info )
import Control.Concurrent
( MVar, newMVar, modifyMVar )
import Control.Exception
( throwIO )
import System.FilePath
( (</>) )
import Network.URI
( URI, uriScheme, uriPath )
import qualified Data.Map as Map
import qualified Hackage.Security.Client as Sec
import qualified Hackage.Security.Util.Path as Sec
import qualified Hackage.Security.Util.Pretty as Sec
import qualified Hackage.Security.Client.Repository.Cache as Sec
import qualified Hackage.Security.Client.Repository.Local as Sec.Local
import qualified Hackage.Security.Client.Repository.Remote as Sec.Remote
import qualified Distribution.Client.Security.HTTP as Sec.HTTP
import qualified Distribution.Client.Security.DNS as Sec.DNS
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------
-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
globalVersion :: Flag Bool,
globalNumericVersion :: Flag Bool,
globalConfigFile :: Flag FilePath,
globalSandboxConfigFile :: Flag FilePath,
globalConstraintsFile :: Flag FilePath,
globalRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers.
globalCacheDir :: Flag FilePath,
globalLocalRepos :: NubList FilePath,
globalLogsDir :: Flag FilePath,
globalWorldFile :: Flag FilePath,
globalRequireSandbox :: Flag Bool,
globalIgnoreSandbox :: Flag Bool,
globalIgnoreExpiry :: Flag Bool, -- ^ Ignore security expiry dates
globalHttpTransport :: Flag String,
globalNix :: Flag Bool -- ^ Integrate with Nix
} deriving Generic
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags = GlobalFlags {
globalVersion = Flag False,
globalNumericVersion = Flag False,
globalConfigFile = mempty,
globalSandboxConfigFile = mempty,
globalConstraintsFile = mempty,
globalRemoteRepos = mempty,
globalCacheDir = mempty,
globalLocalRepos = mempty,
globalLogsDir = mempty,
globalWorldFile = mempty,
globalRequireSandbox = Flag False,
globalIgnoreSandbox = Flag False,
globalIgnoreExpiry = Flag False,
globalHttpTransport = mempty,
globalNix = Flag False
}
instance Monoid GlobalFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup GlobalFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Repo context
-- ------------------------------------------------------------
-- | Access to repositories
data RepoContext = RepoContext {
-- | All user-specified repositories
repoContextRepos :: [Repo]
-- | Get the HTTP transport
--
-- The transport will be initialized on the first call to this function.
--
-- NOTE: It is important that we don't eagerly initialize the transport.
-- Initializing the transport is not free, and especially in contexts where
-- we don't know a-priori whether or not we need the transport (for instance
-- when using cabal in "nix mode") incurring the overhead of transport
-- initialization on _every_ invocation (eg @cabal build@) is undesirable.
, repoContextGetTransport :: IO HttpTransport
-- | Get the (initialized) secure repo
--
-- (the 'Repo' type itself is stateless and must remain so, because it
-- must be serializable)
, repoContextWithSecureRepo :: forall a.
Repo
-> (forall down. Sec.Repository down -> IO a)
-> IO a
-- | Should we ignore expiry times (when checking security)?
, repoContextIgnoreExpiry :: Bool
}
-- | Wrapper around 'Repository', hiding the type argument
data SecureRepo = forall down. SecureRepo (Sec.Repository down)
withRepoContext :: Verbosity -> GlobalFlags -> (RepoContext -> IO a) -> IO a
withRepoContext verbosity globalFlags =
withRepoContext'
verbosity
(fromNubList (globalRemoteRepos globalFlags))
(fromNubList (globalLocalRepos globalFlags))
(fromFlag (globalCacheDir globalFlags))
(flagToMaybe (globalHttpTransport globalFlags))
(flagToMaybe (globalIgnoreExpiry globalFlags))
withRepoContext' :: Verbosity -> [RemoteRepo] -> [FilePath]
-> FilePath -> Maybe String -> Maybe Bool
-> (RepoContext -> IO a)
-> IO a
withRepoContext' verbosity remoteRepos localRepos
sharedCacheDir httpTransport ignoreExpiry = \callback -> do
transportRef <- newMVar Nothing
let httpLib = Sec.HTTP.transportAdapter
verbosity
(getTransport transportRef)
initSecureRepos verbosity httpLib secureRemoteRepos $ \secureRepos' ->
callback RepoContext {
repoContextRepos = allRemoteRepos
++ map RepoLocal localRepos
, repoContextGetTransport = getTransport transportRef
, repoContextWithSecureRepo = withSecureRepo secureRepos'
, repoContextIgnoreExpiry = fromMaybe False ignoreExpiry
}
where
secureRemoteRepos =
[ (remote, cacheDir) | RepoSecure remote cacheDir <- allRemoteRepos ]
allRemoteRepos =
[ (if isSecure then RepoSecure else RepoRemote) remote cacheDir
| remote <- remoteRepos
, let cacheDir = sharedCacheDir </> remoteRepoName remote
isSecure = remoteRepoSecure remote == Just True
]
getTransport :: MVar (Maybe HttpTransport) -> IO HttpTransport
getTransport transportRef =
modifyMVar transportRef $ \mTransport -> do
transport <- case mTransport of
Just tr -> return tr
Nothing -> configureTransport verbosity httpTransport
return (Just transport, transport)
withSecureRepo :: Map Repo SecureRepo
-> Repo
-> (forall down. Sec.Repository down -> IO a)
-> IO a
withSecureRepo secureRepos repo callback =
case Map.lookup repo secureRepos of
Just (SecureRepo secureRepo) -> callback secureRepo
Nothing -> throwIO $ userError "repoContextWithSecureRepo: unknown repo"
-- | Initialize the provided secure repositories
--
-- Assumed invariant: `remoteRepoSecure` should be set for all these repos.
initSecureRepos :: forall a. Verbosity
-> Sec.HTTP.HttpLib
-> [(RemoteRepo, FilePath)]
-> (Map Repo SecureRepo -> IO a)
-> IO a
initSecureRepos verbosity httpLib repos callback = go Map.empty repos
where
go :: Map Repo SecureRepo -> [(RemoteRepo, FilePath)] -> IO a
go !acc [] = callback acc
go !acc ((r,cacheDir):rs) = do
cachePath <- Sec.makeAbsolute $ Sec.fromFilePath cacheDir
initSecureRepo verbosity httpLib r cachePath $ \r' ->
go (Map.insert (RepoSecure r cacheDir) r' acc) rs
-- | Initialize the given secure repo
--
-- The security library has its own concept of a "local" repository, distinct
-- from @cabal-install@'s; these are secure repositories, but live in the local
-- file system. We use the convention that these repositories are identified by
-- URLs of the form @file:/path/to/local/repo@.
initSecureRepo :: Verbosity
-> Sec.HTTP.HttpLib
-> RemoteRepo -- ^ Secure repo ('remoteRepoSecure' assumed)
-> Sec.Path Sec.Absolute -- ^ Cache dir
-> (SecureRepo -> IO a) -- ^ Callback
-> IO a
initSecureRepo verbosity httpLib RemoteRepo{..} cachePath = \callback -> do
requiresBootstrap <- withRepo [] Sec.requiresBootstrap
mirrors <- if requiresBootstrap
then do
info verbosity $ "Trying to locate mirrors via DNS for " ++
"initial bootstrap of secure " ++
"repository '" ++ show remoteRepoURI ++
"' ..."
Sec.DNS.queryBootstrapMirrors verbosity remoteRepoURI
else pure []
withRepo mirrors $ \r -> do
when requiresBootstrap $ Sec.uncheckClientErrors $
Sec.bootstrap r
(map Sec.KeyId remoteRepoRootKeys)
(Sec.KeyThreshold (fromIntegral remoteRepoKeyThreshold))
callback $ SecureRepo r
where
-- Initialize local or remote repo depending on the URI
withRepo :: [URI] -> (forall down. Sec.Repository down -> IO a) -> IO a
withRepo _ callback | uriScheme remoteRepoURI == "file:" = do
dir <- Sec.makeAbsolute $ Sec.fromFilePath (uriPath remoteRepoURI)
Sec.Local.withRepository dir
cache
Sec.hackageRepoLayout
Sec.hackageIndexLayout
logTUF
callback
withRepo mirrors callback =
Sec.Remote.withRepository httpLib
(remoteRepoURI:mirrors)
Sec.Remote.defaultRepoOpts
cache
Sec.hackageRepoLayout
Sec.hackageIndexLayout
logTUF
callback
cache :: Sec.Cache
cache = Sec.Cache {
cacheRoot = cachePath
, cacheLayout = Sec.cabalCacheLayout {
Sec.cacheLayoutIndexTar = cacheFn "01-index.tar"
, Sec.cacheLayoutIndexIdx = cacheFn "01-index.tar.idx"
, Sec.cacheLayoutIndexTarGz = cacheFn "01-index.tar.gz"
}
}
cacheFn :: FilePath -> Sec.CachePath
cacheFn = Sec.rootPath . Sec.fragment
-- We display any TUF progress only in verbose mode, including any transient
-- verification errors. If verification fails, then the final exception that
-- is thrown will of course be shown.
logTUF :: Sec.LogMessage -> IO ()
logTUF = info verbosity . Sec.pretty
| mydaum/cabal | cabal-install/Distribution/Client/GlobalFlags.hs | bsd-3-clause | 11,087 | 0 | 17 | 3,225 | 2,024 | 1,119 | 905 | 202 | 4 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sk-SK">
<title>All In One Notes Add-On</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/allinonenotes/src/main/javahelp/org/zaproxy/zap/extension/allinonenotes/resources/help_sk_SK/helpset_sk_SK.hs | apache-2.0 | 968 | 77 | 67 | 159 | 417 | 211 | 206 | -1 | -1 |
module D1 where
{-demote 'sq' to 'sumSquares'. This refactoring
affects module 'D1' and 'C1' -}
sumSquares (x:xs) = sq + sumSquares xs
where
sq = x ^pow
sumSquares [] = 0
pow = 2
main = sumSquares [1..4]
| mpickering/HaRe | old/testing/demote/D1_TokOut.hs | bsd-3-clause | 220 | 0 | 7 | 54 | 66 | 36 | 30 | 6 | 1 |
{-# OPTIONS -fglasgow-exts #-}
{-# LANGUAGE MultiParamTypeClasses, OverlappingInstances, UndecidableInstances, FunctionalDependencies, NoMonomorphismRestriction #-}
module DirUtils where
import Prelude hiding (catch,ioError)
import MUtils
import Data.List(isSuffixOf,nub)
import AbstractIO
import PathUtils(pathSep)
optCreateDirectory d = unlessM (doesDirectoryExist d) (createDirectory d)
getModificationTimeMaybe path = maybeM (getModificationTime path)
{-
do ifM (doesFileExist path)
(Just # getModificationTime path)
(return Nothing)
-}
-- GHC deficiency workaround:
getModificationTime' path = getModificationTime path `catch` handle
where
handle err = if isDoesNotExistError err
then fail $ "Missing: "++path
else ioError err
latestModTime paths = maximum # mapM getModificationTime' paths
-- Remove a directory and its contents:
rmR = system . unwords . ("rm -rf":)
-- Expand directory names to all the Haskell files (.hs & .lhs) in that
-- directory:
expand fs = concat # mapM expand1 (nub fs)
expand1 f =
do isdir <- doesDirectoryExist f
if isdir
then do fs <- getDirectoryContents f
return [f++[pathSep]++f'|f'<-fs,haskellSuffix f']
else return [f]
haskellSuffix f = ".hs" `isSuffixOf` f || ".lhs" `isSuffixOf` f
{-
-- Recursively collect Haskell files from subdirectories:
recurse = recurse' "" . nub
recurse' path fs = concat # mapM (recurse1 path) fs
recurse1 path f =
do let path' = extend path f
isdir <- doesDirectoryExist path'
if isdir
then if okDir f
then do fs <- getDirectoryContents path'
recurse' path' [f|f<-fs,f `notElem` [".",".."]]
else return []
else if haskellSuffix f
then return [path']
else return []
okDir f = f `notElem` ["objs","CVS","hi","tests","old","spec"]
extend "" f = f
extend "." f = f
extend d f = d++"/"++f
-}
| kmate/HaRe | old/tools/base/lib/DirUtils.hs | bsd-3-clause | 1,891 | 4 | 14 | 386 | 307 | 164 | 143 | 24 | 2 |
module TreeIn2 where
data Tree a = Leaf a | Branch (Tree a) (Tree a)
fringe :: Tree a -> [a]
fringe (Leaf x) = [x]
fringe (Branch left right@(Leaf b_1))
= (fringe left) ++ (fringe right)
fringe (Branch left right@(Branch b_1 b_2))
= (fringe left) ++ (fringe right)
fringe (Branch left right)
= (fringe left) ++ (fringe right)
| kmate/HaRe | old/testing/subIntroPattern/TreeIn2_TokOut.hs | bsd-3-clause | 341 | 0 | 10 | 74 | 181 | 95 | 86 | 10 | 1 |
-- Example.hs -- Examples from HUnit user's guide
-- $Id: Example.hs,v 1.2 2002/02/19 17:05:21 heringto Exp $
module Main where
import HUnit
foo :: Int -> (Int, Int)
foo x = (1, x)
partA :: Int -> IO (Int, Int)
partA v = return (v+2, v+3)
partB :: Int -> IO Bool
partB v = return (v > 5)
test1 = TestCase (assertEqual "for (foo 3)," (1,2) (foo 3))
test2 = TestCase (do (x,y) <- partA 3
assertEqual "for the first result of partA," 5 x
b <- partB y
assertBool ("(partB " ++ show y ++ ") failed") b)
tests = TestList [TestLabel "test1" test1, TestLabel "test2" test2]
tests' = test [ "test1" ~: "(foo 3)" ~: (1,2) ~=? (foo 3),
"test2" ~: do (x, y) <- partA 3
assertEqual "for the first result of partA," 5 x
partB y @? "(partB " ++ show y ++ ") failed" ]
main = do runTestTT tests
runTestTT tests'
| alekar/hugs | packages/Cabal/tests/HUnit-1.0/src/Example.hs | bsd-3-clause | 962 | 0 | 13 | 324 | 340 | 173 | 167 | 20 | 1 |
{-# LANGUAGE ScopedTypeVariables, DataKinds, PolyKinds, TypeOperators,
TypeFamilies, GADTs #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.Glambda.Shift
-- Copyright : (C) 2015 Richard Eisenberg
-- License : BSD-style (see LICENSE)
-- Maintainer : Richard Eisenberg ([email protected])
-- Stability : experimental
--
-- de Bruijn shifting and substitution
--
----------------------------------------------------------------------------
module Language.Glambda.Shift ( shift, subst ) where
import Language.Glambda.Exp
-- | @Length xs@ tells you how long a list @xs@ is.
-- @LZ :: Length xs@ says that @xs@ is empty.
-- @LS len :: Length xs@ tells you that @xs@ has one more element
-- than @len@ says.
data Length :: [a] -> * where
LZ :: Length '[]
LS :: Length xs -> Length (x ': xs)
type family (xs :: [a]) ++ (ys :: [a]) :: [a]
type instance '[] ++ ys = ys
type instance (x ': xs) ++ ys = x ': (xs ++ ys)
infixr 5 ++
-- | Convert an expression typed in one context to one typed in a larger
-- context. Operationally, this amounts to de Bruijn index shifting.
-- As a proposition, this is the weakening lemma.
shift :: forall ts2 t ty. Exp ts2 ty -> Exp (t ': ts2) ty
shift = go LZ
where
go :: forall ts1 ty. Length ts1 -> Exp (ts1 ++ ts2) ty -> Exp (ts1 ++ t ': ts2) ty
go l_ts1 (Var v) = Var (shift_elem l_ts1 v)
go l_ts1 (Lam body) = Lam (go (LS l_ts1) body)
go l_ts1 (App e1 e2) = App (go l_ts1 e1) (go l_ts1 e2)
go l_ts1 (Arith e1 op e2) = Arith (go l_ts1 e1) op (go l_ts1 e2)
go l_ts1 (Cond e1 e2 e3) = Cond (go l_ts1 e1) (go l_ts1 e2) (go l_ts1 e3)
go l_ts1 (Fix e) = Fix (go l_ts1 e)
go _ (IntE n) = IntE n
go _ (BoolE b) = BoolE b
shift_elem :: Length ts1 -> Elem (ts1 ++ ts2) x
-> Elem (ts1 ++ t ': ts2) x
shift_elem LZ e = ES e
shift_elem (LS _) EZ = EZ
shift_elem (LS l) (ES e) = ES (shift_elem l e)
-- | Substitute the first expression into the second. As a proposition,
-- this is the substitution lemma.
subst :: forall ts2 s t.
Exp ts2 s -> Exp (s ': ts2) t -> Exp ts2 t
subst e = go LZ
where
go :: forall ts1 t. Length ts1 -> Exp (ts1 ++ s ': ts2) t -> Exp (ts1 ++ ts2) t
go len (Var v) = subst_var len v
go len (Lam body) = Lam (go (LS len) body)
go len (App e1 e2) = App (go len e1) (go len e2)
go len (Arith e1 op e2) = Arith (go len e1) op (go len e2)
go len (Cond e1 e2 e3) = Cond (go len e1) (go len e2) (go len e3)
go len (Fix e) = Fix (go len e)
go _ (IntE n) = IntE n
go _ (BoolE b) = BoolE b
subst_var :: forall ts1 t.
Length ts1 -> Elem (ts1 ++ s ': ts2) t
-> Exp (ts1 ++ ts2) t
subst_var LZ EZ = e
subst_var LZ (ES v) = Var v
subst_var (LS _) EZ = Var EZ
subst_var (LS len) (ES v) = shift (subst_var len v)
| ajnsit/glambda | src/Language/Glambda/Shift.hs | bsd-3-clause | 3,052 | 4 | 13 | 908 | 1,136 | 587 | 549 | 46 | 11 |
import Data.Monoid
import Control.Applicative
import Data.Text (Text)
import Data.String
import Text.Blaze.Html.Renderer.Pretty (renderHtml)
import Text.Blaze.XHtml5
import Text.Blaze.XHtml5.Attributes hiding (form, name)
import SimpleForm.Combined hiding (text, name)
import SimpleForm.Digestive.Combined
import SimpleForm.Render.XHTML5
s :: (IsString s) => String -> s
s = fromString
data Category = Web | Text | Math deriving (Bounded, Enum, Eq, Show, Read)
data Package = Package {
name :: Text,
category :: Category
} deriving (Show)
main = putStrLn =<< renderHtml <$>
form ! action (s "/post/here") ! method (s"POST") <$>
getSimpleForm render Nothing (do
name' <- input_ (s"name") (Just . name)
category' <- input_ (s"category") (Just . SelectEnum . category)
return $ Package <$> name' <*> fmap unSelectEnum category'
)
| singpolyma/simple-form-haskell | examples/combined.hs | isc | 852 | 10 | 14 | 137 | 311 | 172 | 139 | 23 | 1 |
import Test.Hspec
import Complex
import Limit
import AsciiRenderer
import Data.Array
main :: IO ()
main = hspec $ do
describe "Complex" $ do
describe "real" $ do
it "return real part of a complex number" $ do
real (Complex 12 23) `shouldBe` 12
describe "imag" $ do
it "return image part of a complex number" $ do
imag (Complex 12 23) `shouldBe` 23
describe "add" $ do
it "adds two complex numbers" $ do
add (Complex 12 23) (Complex (-12) 43) `shouldBe` (Complex 0 66)
(Complex 12 23) + (Complex (-12) 43) `shouldBe` (Complex 0 66)
describe "mul" $ do
it "multiplies two complex numbers" $ do
mul (Complex 3 2) (Complex 1 7) `shouldBe` (Complex (-11) 23)
(Complex 3 2) * (Complex 1 7) `shouldBe` (Complex (-11) 23)
describe "square" $ do
it "squares the complex number" $ do
square (Complex 1 1) `shouldBe` Complex 0 2
(Complex 1 1)^2 `shouldBe` Complex 0 2
describe "modulo" $ do
it "gives the squared magnitude of a complex number" $ do
modulo (Complex 3 4) `shouldBe` 25
describe "Limit" $ do
describe "projection" $ do
it "builds the sequence of numbers" $ do
take 3 (projection (add (Complex 1 2)) (Complex 0 0)) `shouldBe` [(Complex 0 0), (Complex 1 2), (Complex 2 4)]
describe "limit_checked" $ do
it "convert sequence of elements to boolean" $ do -- TODO try to redo it with where
take 3 (limit_checked (\z -> (modulo z) > 4) (projection (add (Complex 1 1)) (Complex 0 0))) `shouldBe` [False, False, True]
-- TODO ask David Overtone about code style
describe "indexed" $ do
it "builds the sequence of indexed numbers" $ do
take 3 (indexed (limit_checked ((>10) . modulo) (projection (add (Complex 1 2)) (Complex 0 0)))) `shouldBe` [(0, False), (1, False), (2, True)]
describe "only_for" $ do
it "returns a part of projection" $ do
only_for 3 (projection (+1) 0) `shouldBe` [0, 1, 2]
describe "limit" $ do
it "returns a limit" $ do
limit 0 (+1) 10 (>5) `shouldBe` Just 6
limit 0 (+1) 10 (>20) `shouldBe` Nothing
describe "AsciiRenderer" $ do
describe "limit_to_color" $ do
it "return presentation of limit" $ do
let chars = listArray (0, 4) ['W', '=', '_', '.', ' ']
limit_to_color Nothing chars 10 `shouldBe` 'W'
limit_to_color (Just 0) chars 10 `shouldBe` 'W'
limit_to_color (Just 1) chars 10 `shouldBe` 'W'
limit_to_color (Just 2) chars 10 `shouldBe` '='
limit_to_color (Just 3) chars 10 `shouldBe` '='
| kirhgoff/haskell-sandbox | complex_numbers/specs.hs | mit | 2,639 | 0 | 28 | 731 | 1,073 | 534 | 539 | 55 | 1 |
main :: IO ()
main =
putStr "Input a: " >>
getLine >>=
(\a's ->
putStr "Input b: " >>
getLine >>=
(\b's ->
let num :: Double
num = read a's + read b's
in putStrLn $ "the sum is: " ++ show num))
| sclereid/collections | haskell-learning/a+b.hs | mit | 239 | 0 | 16 | 90 | 91 | 45 | 46 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Snap.Core
import Snap.Http.Server
import Network.HTTP.Conduit
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Control.Monad.IO.Class (liftIO)
main :: IO ()
main = quickHttpServe site
site :: Snap ()
site =
ifTop homeHandler
homeHandler :: Snap ()
homeHandler = do
let url = "https://dl.dropboxusercontent.com/u/28596024/taskwarrior.txt"
raw <- liftIO $ simpleHttp url
let stuff = B.concat $ L.toChunks raw
writeBS "<html>"
writeBS "<head><title>what is noon doing</title></head>"
writeBS "<h2>what is noon doing?</h2>"
writeBS "<pre>"
writeBS stuff
writeBS "</pre>"
writeBS "<small><a href='http://github.com/silky/cupduck'>source</a></small>"
writeBS "</html>"
| silky/cupduck | src/Main.hs | mit | 862 | 0 | 12 | 189 | 193 | 97 | 96 | 26 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
-- | Form wrapper
module QuickForm.Form where
import Data.Aeson
import Data.Aeson.Types
import Data.Default
import Data.HashMap.Strict (HashMap)
import Data.Proxy
import Data.Text (Text)
import Data.Semigroup
import GHC.TypeLits (KnownSymbol, symbolVal, Symbol)
import qualified Data.Text as T
import qualified Data.HashMap.Strict as HM
import qualified Data.Vector as V
import QuickForm.TypeLevel
-- Type functions --------------------------------------------------------------
-- | Encoding of the form input data
-- This should have a nice JSON encoding
newtype Form q = Form { unForm :: ToForm q }
deriving instance Eq (ToForm q) => Eq (Form q)
deriving instance Show (ToForm q) => Show (Form q)
deriving instance Semigroup (ToForm q) => Semigroup (Form q)
deriving instance Monoid (ToForm q) => Monoid (Form q)
deriving instance Default (ToForm q) => Default (Form q)
type family ToForm (q :: QuickForm) where
ToForm (Validated e a q) = ToForm q
ToForm (Field n a) = a
ToForm (Fields qs) = TList (FormList qs)
type family FormList (q :: [QuickForm]) where
FormList '[] = '[]
FormList (q ': qs) = ToForm q ': FormList qs
-- | Encoding of the form output data
type family FormOutput (q :: QuickForm) where
FormOutput (Validated e a q) = a
FormOutput (Field n a) = a
FormOutput (Fields qs) = TList (FormOutputList qs)
type family FormOutputList (q :: [QuickForm]) where
FormOutputList '[] = '[]
FormOutputList (q ': qs) = FormOutput q ': FormOutputList qs
type Lens' s a = Lens s s a a
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
-- type Lens' s a = forall f. Functor f => (a -> f a) -> s -> f s
class FormLens e (form :: QuickForm) (sub :: QuickForm) where
formLens :: Proxy sub -> Lens' (FormError form) (Maybe e)
instance FormLens e (Validated e a q) (Validated e a q) where
formLens Proxy f (ValidatedError e q) = (\e' -> ValidatedError e' q) <$> f e
instance FormLens e q sub => FormLens e (Validated e1 a q) sub where
formLens Proxy f (ValidatedError e q) = ValidatedError e <$> formLens @e @q @sub Proxy f q
-- | Encoding of the form errors
data FormError (q :: QuickForm) where
ValidatedError :: Maybe e -> FormError q -> FormError (Validated e a q)
FieldError :: FormError (Field n a)
FieldsError :: TList (Map FormError qs) -> FormError (Fields qs)
instance (Show e, Show (FormError q)) => Show (FormError (Validated e a q)) where
show (ValidatedError e q) = unwords ["ValidatedError", show e, show q]
instance Show (TList (Map FormError qs)) => Show (FormError (Fields qs)) where
show (FieldsError l) = unwords ["FormError", show l]
instance Show (FormError (Field n a)) where
show FieldError = "FieldError"
instance (Eq e, Eq (FormError q)) => Eq (FormError (Validated e a q)) where
ValidatedError e q == ValidatedError e' q' = e == e' && q == q'
instance Eq (TList (Map FormError qs)) => Eq (FormError (Fields qs)) where
FieldsError l == FieldsError l' = l == l'
instance Eq (FormError (Field n a)) where
FieldError == FieldError = True
instance (Semigroup e, Semigroup (FormError q)) => Semigroup (FormError (Validated e a q)) where
ValidatedError e q <> ValidatedError e' q' = ValidatedError (e <> e') (q <> q')
instance Semigroup (FormError (Field a q)) where
FieldError <> FieldError = FieldError
instance Semigroup (TList (Map FormError qs)) => Semigroup (FormError (Fields qs)) where
FieldsError l <> FieldsError l' = FieldsError (l <> l')
instance (Semigroup (FormError q), Default (FormError q)) => Monoid (FormError q) where
mempty = def
mappend = (<>)
instance (Default (FormError q))
=> Default (FormError (Validated e a q)) where
def = ValidatedError Nothing def
instance Default (TList (Map FormError qs))
=> Default (FormError (Fields qs)) where
def = FieldsError def
instance Default (FormError (Field n a)) where
def = FieldError
instance (ToJSON e, ToJSON (FormError q)) => ToJSON (FormError (Validated e a q)) where
toJSON (ValidatedError e q) = Object $ HM.fromList [("error", toJSON e), ("subform", toJSON q)]
instance ToJSON a => ToJSON (FormError (Field n a)) where
toJSON FieldError = Null
instance ToValueList (Map FormError qs) => ToJSON (FormError (Fields qs)) where
toJSON (FieldsError l) = Array $ V.fromList $ toValueList l
class ToValueList l where
toValueList :: TList l -> [Value]
instance ToValueList '[] where
toValueList Nil = []
instance (ToJSON a, ToValueList as) => ToValueList (a ': as) where
toValueList (a :| as) = toJSON a : toValueList as
class FromValueList l where
fromValueList :: [Value] -> Parser (TList l)
instance FromValueList '[] where
fromValueList [] = pure Nil
fromValueList _ = fail "FromValueList: too many items"
instance (FromJSON a, FromValueList as) => FromValueList (a ': as) where
fromValueList [] = fail "FromValueList: not enough items"
fromValueList (a : as) = (:|) <$> parseJSON a <*> fromValueList as
instance (FromJSON e, FromJSON (FormError q)) => FromJSON (FormError (Validated e a q)) where
parseJSON = withObject "ValidatedError" $ \o -> ValidatedError <$> o .: "error" <*> o .: "subform"
instance FromJSON a => FromJSON (FormError (Field n a)) where
parseJSON _ = pure FieldError
instance FromValueList (Map FormError qs) => FromJSON (FormError (Fields qs)) where
parseJSON = withArray "FieldsError" $ fmap FieldsError . fromValueList . V.toList
--------------------------------------------------------------------------------
class ToHashMap q where
toHashMap :: Form q -> HashMap Text Value
instance ToHashMap q => ToHashMap (Validated e a q) where
toHashMap (Form q) = toHashMap (Form @q q)
instance (ToJSON a, KnownSymbol n)
=> ToHashMap (Field n a) where
toHashMap (Form value) = HM.singleton name $ toJSON value
where name = T.pack $ symbolVal $ Proxy @n
instance ToHashMap (Fields '[]) where
toHashMap (Form Nil) = HM.empty
instance (ToHashMap q, ToHashMap (Fields qs))
=> ToHashMap (Fields (q ': qs)) where
toHashMap (Form (q :| qs))
= toHashMap (Form @q q) <> toHashMap @(Fields qs) (Form qs)
instance ToHashMap q => ToJSON (Form q) where
toJSON q = Object $ toHashMap q
--------------------------------------------------------------------------------
class FromHashMap q where
fromHashMap :: HashMap Text Value -> Parser (Form q)
instance FromHashMap q => FromHashMap (Validated e a q) where
fromHashMap = fmap (Form . unForm @q) . fromHashMap
instance FromHashMap (Fields '[]) where
fromHashMap _ = pure $ Form Nil
instance (FromHashMap q, FromHashMap (Fields qs))
=> FromHashMap (Fields (q ': qs)) where
fromHashMap hm = (\(Form r) (Form rs) -> Form $ r :| rs)
<$> fromHashMap @q hm <*> fromHashMap @(Fields qs) hm
instance (FromJSON a, KnownSymbol n)
=> FromHashMap (Field n a) where
fromHashMap hm = case HM.lookup k hm of
Nothing -> fail $ "Missing form key: " ++ n
Just v -> Form <$> parseJSON v
where k = T.pack n
n = symbolVal (Proxy @n)
instance FromHashMap q => FromJSON (Form q) where
parseJSON = withObject "Form" fromHashMap
| tomsmalley/quickform | src/QuickForm/Form.hs | mit | 7,330 | 0 | 11 | 1,361 | 2,906 | 1,481 | 1,425 | -1 | -1 |
{-# LANGUAGE
DeriveGeneric
, DeriveDataTypeable
#-}
module Veva.Types.User
( User(..)
, module Veva.Types.User.Id
, module Veva.Types.User.Email
) where
import Data.JSON.Schema
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Data.Aeson (FromJSON(..), ToJSON(..))
import Data.Time (UTCTime)
import Veva.Types.User.Id
import Veva.Types.User.Email
data User = User
{ id :: Id
, email :: Email
, created_at :: UTCTime
, updated_at :: UTCTime
} deriving (Eq, Show, Generic, Typeable)
instance FromJSON User
instance ToJSON User
instance JSONSchema User where schema = gSchema
| L8D/veva | lib/Veva/Types/User.hs | mit | 692 | 0 | 8 | 176 | 183 | 114 | 69 | 23 | 0 |
import System.IO
import System.Exit
import XMonad hiding ( (|||) ) -- don't use the normal ||| operator
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers
import XMonad.Hooks.SetWMName
import XMonad.Hooks.ToggleHook
import XMonad.Layout.Named
import XMonad.Layout.Fullscreen
import XMonad.Layout.NoBorders
import XMonad.Layout.Tabbed
import XMonad.Layout.LayoutCombinators -- use the one from LayoutCombinators instead
import XMonad.Actions.UpdatePointer
import XMonad.Actions.CopyWindow
import qualified XMonad.StackSet as W
import qualified Data.Map as M
import Graphics.X11.ExtraTypes.XF86
import Data.Monoid
import XMonad.Hooks.SetWMName
import XMonad.Util.XUtils (fi)
import XMonad.Util.WorkspaceCompare
import XMonad.Util.NamedScratchpad
import ResizeableGrid
myScratchPads = [ NS "terminal" "spawnon NS_terminal st" (workspace =? "NS_terminal") (customFloating $ W.RationalRect 0 0 1 0.25) ] -- left top width height
where
workspace = stringProperty "XMONAD_WORKSPACE"
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $
[
-- ((controlMask, xK_q ), spawn "noctrlq"),
((modm .|. controlMask, xK_1 ), spawn "screenlayout-only-internal"),
((modm .|. controlMask, xK_2 ), spawn "screenlayout-both"),
((modm .|. controlMask, xK_3 ), spawn "screenlayout-only-external"),
((modm .|. controlMask, xK_9 ), spawn "screenlayout-reset"),
((modm .|. controlMask, xK_c ), spawn "xkill"),
((modm .|. controlMask, xK_p ), spawn "pomodoro toggle 15"),
((modm .|. controlMask, xK_x ), spawn "import -window $(xwininfo -int | awk '/Window id:/{print $4}') $(zenity --file-selection --save || echo png:-) | xclip -selection clipboard -t image/png -i"),
((modm .|. shiftMask, xK_Return), spawn "zeal"),
((modm .|. shiftMask, xK_Tab ), windows W.focusUp),
((modm .|. shiftMask, xK_c ), kill),
((modm .|. shiftMask, xK_g ), spawn "amixer -D pulse sset Capture toggle,toggle"),
((modm .|. shiftMask, xK_j ), windows W.swapDown),
((modm .|. shiftMask, xK_k ), windows W.swapUp),
((modm .|. shiftMask, xK_l ), spawn "xautolock -locknow"),
((modm .|. shiftMask, xK_m ), spawn "gromit-mpx -q"),
((modm .|. shiftMask, xK_x ), spawn "import -window root $(zenity --file-selection --save || echo png:-) | xclip -selection clipboard -t image/png -i"),
((modm .|. shiftMask, xK_p ), spawn "pomodoro toggle 5"),
((modm .|. shiftMask, xK_q ), spawn "quitxmonad"),
((modm .|. shiftMask, xK_v ), killAllOtherCopies),
((modm, xK_Return), spawn $ XMonad.terminal conf),
((modm, xK_Tab ), windows W.focusDown),
((modm, xK_a ), sendMessage $ JumpToLayout "grid"),
((modm, xK_b ), sendMessage ToggleStruts),
((modm, xK_comma ), sendMessage (IncMasterN 1)),
((modm, xK_d ), sendMessage $ JumpToLayout "tabbed"),
((modm, xK_f ), sendMessage $ JumpToLayout "fullscreen"),
((modm, xK_h ), sendMessage Shrink),
((modm, xK_i ), broadcastMessage Expand >> refresh),
((modm, xK_j ), windows W.focusDown),
((modm, xK_k ), windows W.focusUp ),
((modm, xK_l ), sendMessage Expand),
((modm, xK_m ), spawn "(pgrep gromit-mpx || gromit-mpx --key XF86Tools --undo-key XF86WLAN -a) && gromit-mpx -t"),
((modm, xK_n ), sendMessage Reset),
((modm, xK_o ), namedScratchpadAction myScratchPads "terminal"),
((modm, xK_p ), spawn "pomodoro toggle 25"),
((modm, xK_period), sendMessage (IncMasterN (-1))),
((modm, xK_q ), spawn "xmonad --restart"),
((modm, xK_r ), refresh),
((modm, xK_s ), sendMessage $ JumpToLayout "tiled"),
((modm, xK_space ), withWindowSet $ \ws -> spawn ("spawnon " ++ (W.currentTag ws) ++ " dmenu_run -nb '#141414' -nf '#F8F8F2' -sb '#21889B' -fn 'Hack:size=10.8'")),
((modm, xK_t ), withFocused $ windows . W.sink),
((modm, xK_u ), broadcastMessage Shrink >> refresh),
((modm, xK_v ), windows copyToAll),
-- modm, xK_w does not work
((modm, xK_x ), spawn "import $(zenity --file-selection --save || echo png:- ) | xclip -selection clipboard -t image/png -i"),
((modm, xK_z ), windows W.swapMaster),
((noModMask, xF86XK_AudioLowerVolume ), spawn "amixer -D pulse sset Master 5%-,5%-"),
((noModMask, xF86XK_AudioMute ), spawn "amixer -D pulse sset Master toggle,toggle"),
((noModMask, xF86XK_AudioRaiseVolume ), spawn "amixer -D pulse sset Master 5%+,5%+"),
((noModMask, xF86XK_MonBrightnessDown), spawn "brightnessctl s 5%-"),
((noModMask, xF86XK_MonBrightnessUp ), spawn "brightnessctl s 5%+")
]
++
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
-- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
[ ((modm, button1), (\w -> focus w >> mouseMoveWindow w
>> windows W.shiftMaster))
, ((modm, button2), (\w -> focus w >> windows W.shiftMaster))
, ((modm, button3), (\w -> focus w >> mouseResizeWindow w
>> windows W.shiftMaster))
]
myLayout = named "grid" (avoidStruts(ResizeableGrid 0 50 (-250)))
||| named "tiled" (smartBorders $ avoidStruts(Tall nmaster delta frac))
||| named "tabbed" (avoidStruts(simpleTabbed))
||| named "fullscreen" (noBorders Full)
where nmaster = 1
frac = 1/2
delta = 3/100
myEventHook :: Event -> X All
myEventHook = myEwmhDesktopsEventHookCustom id <+> docksEventHook
myEwmhDesktopsEventHookCustom :: ([WindowSpace] -> [WindowSpace]) -> Event -> X All
myEwmhDesktopsEventHookCustom f e = handle f e >> return (All True)
handle :: ([WindowSpace] -> [WindowSpace]) -> Event -> X ()
handle f (ClientMessageEvent {
ev_window = w,
ev_message_type = mt,
ev_data = d
}) = withWindowSet $ \s -> do
sort' <- getSortByIndex
let ws = f $ sort' $ W.workspaces s
a_cd <- getAtom "XMONAD_CURRENT_DESKTOP"
a_d <- getAtom "XMONAD_WM_DESKTOP"
a_aw <- getAtom "XMONAD_ACTIVE_WINDOW"
a_cw <- getAtom "XMONAD_CLOSE_WINDOW"
a_ignore <- mapM getAtom ["XMONAD_TIMER"]
if mt == a_cd then do
let n = head d
if 0 <= n && fi n < length ws then
windows $ W.view (W.tag (ws !! fi n))
else
trace $ "Bad XMONAD_CURRENT_DESKTOP with data[0]="++show n
else if mt == a_d then do
let n = head d
if 0 <= n && fi n < length ws then
windows $ W.shiftWin (W.tag (ws !! fi n)) w
else
trace $ "Bad XMONAD_DESKTOP with data[0]="++show n
else if mt == a_aw then do
windows $ W.focusWindow w
else if mt == a_cw then do
killWindow w
else if mt `elem` a_ignore then do
return ()
else do
return ()
handle _ _ = return ()
-- for className use xprop
myManageHook = manageDocks <+> composeOne
[ isDialog -?> doFloat
, className =? "owncloud" -?> unfloat
, className =? "XClock" -?> doFloat
, className =? "Xmessage" -?> doFloat
, className =? "Gxmessage" -?> doFloat
, className =? "Ncview" -?> doCenterFloat
, workspace =? "1" -?> doShift "1"
, workspace =? "2" -?> doShift "2"
, workspace =? "3" -?> doShift "3"
, workspace =? "4" -?> doShift "4"
, workspace =? "5" -?> doShift "5"
, workspace =? "6" -?> doShift "6"
, workspace =? "7" -?> doShift "7"
, workspace =? "8" -?> doShift "8"
, workspace =? "9" -?> doShift "9"
, className =? "panel" -?> doIgnore
, resource =? "desktop_window" -?> doIgnore
, role =? "pop-up" -?> doCenterFloat
--, transience -- if window is transient move it to its parent
]
<+> (doF W.swapDown)
<+> namedScratchpadManageHook myScratchPads
where role = stringProperty "WM_WINDOW_ROLE"
workspace = stringProperty "XMONAD_WORKSPACE"
unfloat = ask >>= doF . W.sink
main = do
spawn "pkill polybar; polybar main"
xmonad $ defaultConfig {
terminal = "st",
focusFollowsMouse = True,
borderWidth = 1,
modMask = mod4Mask, -- super key
workspaces = map show [1..9],
normalBorderColor = "#141414",
focusedBorderColor = "#141414",
keys = myKeys,
mouseBindings = myMouseBindings,
layoutHook = myLayout,
manageHook = myManageHook,
handleEventHook = myEventHook,
startupHook = setWMName "LG3D" <+> ewmhDesktopsStartup <+> docksStartupHook,
logHook = updatePointer (0.5, 0.5) (0, 0) <+> ewmhDesktopsLogHookCustom namedScratchpadFilterOutWorkspace
}
| swillner/dotfiles | dotfiles/xmonad/xmonad.hs | mit | 10,267 | 0 | 20 | 3,245 | 2,740 | 1,547 | 1,193 | 177 | 8 |
module Main where
import Control.Monad (mapM_)
import Data.List (sortBy, nub)
import qualified Data.Bimap as BM
import Data.Maybe (mapMaybe)
import Data.Ord (comparing)
import Data.Tuple (swap)
import System.Environment (getArgs)
import Picosat
import Encoder
import PBEncoder
import Encodings
import Parser
import Types
constraints :: Int -> [Encoder CNF]
constraints n =
[ atLeastOne
, atMostOne bitwise
, antiCollocation bitwise
, capacityLimit generalizedTotalizer
, serverUpperLimit n generalizedTotalizer
]
encoder :: [Encoder CNF] -> Encoder CNF
encoder es = concat <$> sequence es
cnf :: Environment -> Int -> CNF
cnf env n = encode env (encoder (constraints n))
type Assignment = [(VM,Server)]
solution2assignment :: Environment -> Solution -> Maybe Assignment
solution2assignment env (Solution sol) =
let lookup = flip BM.lookup (bimap env)
in Just
$ sortBy (comparing (jobID . fst))
$ sortBy (comparing (vmIndex . fst))
$ map swap
$ mapMaybe lookup sol
solution2assignment _ _ = Nothing
output :: Assignment -> IO ()
output a = do
putStrLn $ "o " ++ show optimumValue
mapM_ putVS a
where
optimumValue = length $ nub $ snd <$> a
putVS (v,s) = putStrLn . concat $
[ show (jobID v)
, " "
, show (vmIndex v)
, " -> "
, show (serverID s)
]
main = (!!0) <$> getArgs >>= main'
main' fileName = do
Just problem <- parse fileName
let env = populate problem
Just a <- solution2assignment env <$> main'' env
output a
main'' :: Environment -> IO Solution
main'' env = loop (length $ servers env) Unknown
where
loop :: Int -> Solution -> IO Solution
loop n previousSolution =
case previousSolution of
Solution _ -> check
Unknown -> check
Unsatisfiable -> error "loop: unsat"
where
check :: IO Solution
check = do
newSolution <- solve (cnf env n)
case newSolution of
Unsatisfiable -> return previousSolution
Solution _ -> loop (n-1) newSolution
Unknown -> error "check: unknown"
| rodamber/vmc-hs | sat/Main.hs | mit | 2,109 | 0 | 16 | 540 | 728 | 370 | 358 | 67 | 5 |
-- v2 (cleanup) of DL reasoner
{-# LANGUAGE DeriveGeneric, DefaultSignatures #-}
import Prelude
import Test.Hspec
import qualified Data.Map as Map
import Data.List (nub, find)
import Data.Maybe (fromMaybe, isJust)
import Data.Serialize
import GHC.Exts hiding (Any)
import GHC.Generics (Generic)
-- a constant represents an individual in the kb
data Constant = C String
deriving (Show, Eq, Generic)
instance Serialize Constant
type ConceptName = String
type RoleName = String
-- map of atomic concept definitions
type AtomicDefMap = Map.Map ConceptName Concept
data Concept = Atomic ConceptName
| All RoleName Concept
| Exists Int RoleName
| Fills RoleName Constant
| And [Concept]
deriving (Show, Eq, Generic)
instance Serialize Concept
data Role = Role Constant Constant
deriving (Show, Eq)
data Subsumption = Sub Concept Concept
deriving (Show, Eq)
data Equivalence = Equiv Concept Concept
deriving (Show, Eq)
data Member = Member Constant Concept
deriving (Show, Eq)
-- KB definition, easier to write
data KbDef = KbDef [Subsumption] [Equivalence] [Member]
-- KB type used in computations, easier to use
data Kb = Kb {
atomicDefs :: AtomicDefMap
,memberAssertions :: [Member]
,subsumptionAssertions :: [Subsumption]
} deriving (Show, Eq)
-- ============= --
-- normalization --
-- ============= --
flatten :: [Concept] -> [Concept]
flatten (And concepts:xs) = concepts ++ flatten xs
flatten (x:xs) = x : flatten xs
flatten [] = []
combineAlls :: [Concept] -> AtomicDefMap -> [Concept]
combineAlls cs atomics =
-- TODO how to simplify this lambda?
let (noCombine:toCombine) = groupWith (\x -> case x of (All r _) -> Just r
_ -> Nothing) cs
getConcept (All _ c) = normalize c atomics
combine [c] = normalize c atomics
combine cs2@(All r _:_) = All r . (`normalize` atomics) $ And (map getConcept cs2)
in noCombine ++ map combine toCombine
combineExists :: [Concept] -> [Concept]
combineExists cs =
-- TODO use standard groupBy
let groups = groupWith (\x -> case x of (Exists _ r) -> Just r
_ -> Nothing) cs
(noCombine, toCombine) = break (\x -> case x of (Exists _ _:_) -> True
_ -> False) groups
getMinRel (Exists n _) = n
combine [c] = c
combine cs2@(Exists _ rn:_) = let maxN = foldl (flip $ max . getMinRel) 0 cs2
in Exists maxN rn
in concat noCombine ++ map combine toCombine
normalize :: Concept -> AtomicDefMap -> Concept
normalize c@(Atomic cname) atomics = fromMaybe c (Map.lookup cname atomics)
normalize (All rn innerC) atomics = All rn (normalize innerC atomics)
normalize (And components) atomics =
let cs = map (`normalize` atomics) components
cs' = flatten cs
cs'' = combineAlls cs' atomics
cs''' = combineExists cs''
in case length cs''' of 1 -> head cs'''
_ -> And $ nub cs'''
normalize c _ = c -- covers exists and fills
normalize2 :: Concept -> AtomicDefMap -> Concept
normalize2 c@(And _) defs = normalize c defs
normalize2 c defs = And [normalize c defs]
normalizationTests :: Spec
normalizationTests =
let atomics = Map.fromList [("SomeExists", Exists 2 "Something"),
("Jess", Exists 1 "AJess")]
in describe ">>> normalization tests" $ do
-- trivial test of replacing an atomic with it's definition
it "should resolve simple atomics" $
normalize (Atomic "SomeExists") atomics `shouldBe` Exists 2 "Something"
-- test `normalize' handling of `All'
it "should normalize ALL's component" $
normalize (All "xyz" (Atomic "SomeExists")) atomics `shouldBe`
All "xyz" (Exists 2 "Something")
-- test of `combineAlls'
it "should combine ALLs" $
combineAlls [All "a" $ Atomic "Jess",
Atomic "Separator",
All "b" $ Atomic "SomethingElseEntirely",
All "a" $ And [Atomic "Michael", Atomic "Balint"]] atomics
`shouldBe` [Atomic "Separator",
All "a" (And [Atomic "Michael",
Atomic "Balint",
Exists 1 "AJess"]),
All "b" (Atomic "SomethingElseEntirely")]
-- test of `combineExists'
it "should combine EXISTSs" $
combineExists [Exists 2 "Monkey",
Atomic "Separator",
Exists 8 "Fireball",
Exists 3 "Monkey"]
`shouldBe` [Atomic "Separator",Exists 8 "Fireball",Exists 3 "Monkey"]
-- same as previous through `normalize'
it "should combine EXISTSs with `normalize'" $
normalize (And [Exists 2 "Monkey",
Atomic "Separator",
Exists 8 "Fireball",
Exists 3 "Monkey"]) atomics
`shouldBe` And [Atomic "Separator",Exists 8 "Fireball",Exists 3 "Monkey"]
-- XXXX
it "should normalize a complex structure" $
let complexConcept =
All "a" $ And [Exists 2 "AJess", Atomic "Jess"]
in normalize complexConcept atomics
`shouldBe` All "a" (Exists 2 "AJess")
it "should normalize an example" $
let atomics' = Map.fromList
[("WellRoundedCo", And [Atomic "Company",
-- where all managers are biz school grads
All "Manager" (And [Atomic "B-SchoolGrad",
-- and have at least 1 tech degree
Exists 1 "TechnicalDegree"])]),
("HighTechCo", And [Atomic "Company",
Fills "Exchange" (C "nasdaq"),
All "Manager" (Atomic "Techie")]),
("Techie", Exists 2 "TechnicalDegree")]
exampleConcept = And [Atomic "WellRoundedCo", Atomic "HighTechCo"]
in normalize exampleConcept atomics'
`shouldBe` And [Atomic "Company",Fills "Exchange" (C "nasdaq"),All "Manager" (And [Atomic "B-SchoolGrad",Exists 2 "TechnicalDegree"])]
-- =========== --
-- subsumption --
-- =========== --
-- check by structure matching
-- e = subsuming concept
-- d = set to search for subsumed concept
findSubsumed :: Concept -> [Concept] -> Maybe Concept
findSubsumed e@(Atomic cn) d = find (\x -> case x of Atomic cn2 | cn == cn2 -> True
And cs -> isJust $ findSubsumed e cs
_ -> False) d
findSubsumed e@(Fills rn c) d = find (\x -> case x of Fills rn2 c2 | rn == rn2 && c == c2 -> True
And cs -> isJust $ findSubsumed e cs
_ -> False) d
findSubsumed e@(Exists 1 r) d = find (\x -> case x of Fills r2 _ | r == r2 -> True
Exists n r2 | r == r2 && n >= 1 -> True
And cs -> isJust $ findSubsumed e cs
_ -> False) d
findSubsumed e@(Exists n r) d = find (\x -> case x of Exists n2 r2 | r == r2 && n2 >= n -> True
And cs -> isJust $ findSubsumed e cs
_ -> False) d
findSubsumed e@(All rn c) d = find (\x -> case x of All rn2 c2 | rn == rn2 && isJust (findSubsumed c [c2]) -> True
And cs -> isJust $ findSubsumed e cs
_ -> False) d
-- given: AND_1 = {c_1, ..., c_i}, AND_2 = {d_1, ..., d_j}
-- AND_1 \sqsubseteq AND_2 iff \forall d_n \in AND_2 \exists c_m \in AND_1 s.t. c_m \sqsubseteq d_n
findSubsumed (And cs) d =
let dAnds = filter (\x -> case x of And _ -> True
_ -> False) d
in find (\(And d_n) -> all isJust $ map (`findSubsumed` d_n) cs) dAnds
subsumedBy :: Concept -> Concept -> Bool
subsumedBy (And subsumedCs) (And subsumerCs) = (foldl . flip) ((&&) . isJust) True $ map (`findSubsumed` subsumedCs) subsumerCs
subsumptionTests :: Spec
subsumptionTests =
describe ">>> subsumption tests" $ do
it "should find a subsumed FILLS for EXISTS 1" $
let subsumed = findSubsumed (Exists 1 "SomeRole") [Fills "SomeRole" $ C "X"]
in subsumed `shouldBe` Just (Fills "SomeRole" $ C "X")
it "should find a subsumed EXIST 2 for EXISTS 1" $
let subsumed = findSubsumed (Exists 1 "SomeRole") [Exists 2 "SomeRole"]
in subsumed `shouldBe` Just (Exists 2 "SomeRole")
it "should find NOT a subsumed EXIST 1 for EXISTS 2" $
let subsumed = findSubsumed (Exists 2 "SomeRole") [Exists 1 "SomeRole"]
in subsumed `shouldBe` Nothing
it "should find subsumed recursively for ALL (simple)" $
let subsumed = findSubsumed (All "People" $ Atomic "HaveLegs") [All "People" $ Atomic "HaveLegs"]
in subsumed `shouldBe` Just (All "People" $ Atomic "HaveLegs")
it "should find subsumed for basic AND case" $
-- let subsumed = And [Atomic "B", Exists 1 "SomeRole", Atomic "C"]
-- subsumer = And [Exists 2 "SomeRole", Atomic "B"]
let subsumed = And [Atomic "B", Exists 3 "SomeRole", Atomic "C"]
subsumer = And [Atomic "B", Exists 2 "SomeRole"]
in (findSubsumed subsumer [subsumed], subsumedBy subsumed subsumer)
`shouldBe` (Just (And [Atomic "B",Exists 3 "SomeRole", Atomic "C"]), True)
it "should work with an example" $
let subsumer = And [All "Manager" (Atomic "B-SchoolGrad"),
Exists 1 "Exchange"]
subsumed = And [Atomic "Company",
All "Manager" (And [Atomic "B-SchoolGrad",
Exists 2 "TechnicalDegree"]),
Fills "Exchange" $ C "nasdaq"]
in subsumedBy subsumed subsumer `shouldBe` True
it "should find specific `All' concepts inside AND" $
findSubsumed (All "m" (Atomic "n")) [And [Atomic "A",
Exists 1 "x",
All "m" (Atomic "n")]]
`shouldBe` Just (And [Atomic "A",Exists 1 "x",All "m" (Atomic "n")])
it "should find specific `Exists' concepts inside AND" $
let subsumed = And [Atomic "A", Exists 3 "x"]
in findSubsumed (Exists 1 "x") [subsumed] `shouldBe` Just subsumed
main :: IO ()
main = do
putStrLn "hey"
hspec normalizationTests
hspec subsumptionTests
return ()
-- let enc :: Data.ByteString.Internal.ByteString ; enc = encode $ And [Atomic "Jess", Atomic "Andy"]; dec :: Either String Concept ; dec = decode enc in dec
| jbalint/banshee-sympatico | meera/dl2.hs | mit | 11,072 | 0 | 24 | 3,768 | 3,175 | 1,607 | 1,568 | 187 | 13 |
module Types where
import qualified Data.Vector as V
import qualified Data.Vector.Storable as S
import Linear
type Event a = V3 a
type Events a = S.Vector (Event a)
type Patch a = Events a
type Phi a = Events a
type PushV a = Events a
type As a = S.Vector a
type Patches a = V.Vector (Patch a)
type Phis a = V.Vector (Phi a)
type PushVs a = V.Vector (PushV a)
| fhaust/aer-utils | src/Types.hs | mit | 386 | 0 | 7 | 99 | 148 | 89 | 59 | 13 | 0 |
-- The sequence of triangle numbers is generated by adding the natural
-- numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6
-- + 7 = 28. The first ten terms would be:
-- 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
-- Let us list the factors of the first seven triangle numbers:
-- 1: 1
-- 3: 1,3
-- 6: 1,2,3,6
-- 10: 1,2,5,10
-- 15: 1,3,5,15
-- 21: 1,3,7,21
-- 28: 1,2,4,7,14,28
-- We can see that 28 is the first triangle number to have over five
-- divisors.
-- What is the value of the first triangle number to have over five
-- hundred divisors?
module Euler.Problem012
( solution
, divisors
, triangles
) where
import Data.List (nub)
solution :: Int -> Integer
solution minDivs = head . filter f $ triangles
where f = (> minDivs) . length . divisors
divisors :: Integer -> [Integer]
divisors n = nub . concatMap pair . filter f $ [1..(limit n)]
where pair x = [x, div n x]
f x = rem n x == 0
limit = floor . sqrt . (fromIntegral :: Integer -> Double)
triangles :: [Integer]
triangles = scanl (+) 1 [2..]
| whittle/euler | src/Euler/Problem012.hs | mit | 1,125 | 0 | 9 | 314 | 225 | 130 | 95 | 15 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGForeignObjectElement
(js_getX, getX, js_getY, getY, js_getWidth, getWidth, js_getHeight,
getHeight, SVGForeignObjectElement, castToSVGForeignObjectElement,
gTypeSVGForeignObjectElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"x\"]" js_getX ::
SVGForeignObjectElement -> IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGForeignObjectElement.x Mozilla SVGForeignObjectElement.x documentation>
getX ::
(MonadIO m) =>
SVGForeignObjectElement -> m (Maybe SVGAnimatedLength)
getX self = liftIO (nullableToMaybe <$> (js_getX (self)))
foreign import javascript unsafe "$1[\"y\"]" js_getY ::
SVGForeignObjectElement -> IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGForeignObjectElement.y Mozilla SVGForeignObjectElement.y documentation>
getY ::
(MonadIO m) =>
SVGForeignObjectElement -> m (Maybe SVGAnimatedLength)
getY self = liftIO (nullableToMaybe <$> (js_getY (self)))
foreign import javascript unsafe "$1[\"width\"]" js_getWidth ::
SVGForeignObjectElement -> IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGForeignObjectElement.width Mozilla SVGForeignObjectElement.width documentation>
getWidth ::
(MonadIO m) =>
SVGForeignObjectElement -> m (Maybe SVGAnimatedLength)
getWidth self = liftIO (nullableToMaybe <$> (js_getWidth (self)))
foreign import javascript unsafe "$1[\"height\"]" js_getHeight ::
SVGForeignObjectElement -> IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGForeignObjectElement.height Mozilla SVGForeignObjectElement.height documentation>
getHeight ::
(MonadIO m) =>
SVGForeignObjectElement -> m (Maybe SVGAnimatedLength)
getHeight self = liftIO (nullableToMaybe <$> (js_getHeight (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGForeignObjectElement.hs | mit | 2,780 | 24 | 10 | 375 | 638 | 377 | 261 | 43 | 1 |
module Spaceship where
import Utils
-- Hard Reset Spaceship informations
resetSpaceship :: (Bool, Position, Int, Int)
resetSpaceship = (False, (-44, 100), 1, 150) | joeyinbox/space-invaders-haskell | src/Spaceship.hs | gpl-2.0 | 165 | 0 | 7 | 25 | 50 | 33 | 17 | 4 | 1 |
{-|
Module : Multilinear.Generic.MultiCore
Description : Generic implementation of tensor as nested arrays, evaluated in sequential manner
Copyright : (c) Artur M. Brodzki, 2018
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : Windows/POSIX
-}
module Multilinear.Generic.MultiCore (
-- * Generic tensor datatype and its instances
Tensor(..),
-- * Auxiliary functions
_mergeScalars, _elemByElem, zipT,
-- * Additional functions
(.+), (.-), (.*), (+.), (-.), (*.),
Multilinear.Generic.MultiCore.map,
Multilinear.Generic.MultiCore.zipWith
) where
import Control.DeepSeq
import qualified Control.Parallel.Strategies as Parallel
import Data.Foldable
import Data.List
import Data.Maybe
import qualified Data.Vector as Boxed
import qualified Data.Vector.Unboxed as Unboxed
import Foreign.Storable
import GHC.Generics
import Multilinear.Class as Multilinear
import qualified Multilinear.Index as Index
import qualified Multilinear.Index.Finite as Finite
{-| ERROR MESSAGE -}
incompatibleTypes :: String
incompatibleTypes = "Incompatible tensor types!"
{-| ERROR MESSAGE -}
scalarIndices :: String
scalarIndices = "Scalar has no indices!"
{-| ERROR MESSAGE -}
indexNotFound :: String
indexNotFound = "This tensor has not such index!"
{-| ERROR MESSAGE -}
tensorOfScalars :: String
tensorOfScalars = "Tensor construction error! Vector of scalars"
{-| Tensor defined recursively as scalar or list of other tensors -}
{-| @c@ is type of a container, @i@ is type of index size and @a@ is type of tensor elements -}
data Tensor a where
{-| Scalar -}
Scalar :: {
scalarVal :: a
} -> Tensor a
{-| Simple, one-dimensional finite tensor -}
SimpleFinite :: {
tensorFiniteIndex :: Finite.Index,
tensorScalars :: Unboxed.Vector a
} -> Tensor a
{-| Finite array of other tensors -}
FiniteTensor :: {
{-| Finite index "Mutltilinear.Index.Finite" of tensor -}
tensorFiniteIndex :: Finite.Index,
{-| Array of tensors on deeper recursion level -}
tensorsFinite :: Boxed.Vector (Tensor a)
} -> Tensor a
deriving (Eq, Generic)
-- | NFData instance
instance NFData a => NFData (Tensor a)
-- | Print tensor
instance (
Multilinear Tensor a, Show a, Unboxed.Unbox a, NFData a
) => Show (Tensor a) where
-- merge errors first and then print whole tensor
show = show' . standardize
where
show' x = case x of
-- Scalar is showed simply as its value
Scalar v -> show v
-- SimpleFinite is shown dependent on its index...
SimpleFinite index ts -> show index ++ "S: " ++ case index of
-- If index is contravariant, show tensor components vertically
Finite.Contravariant _ _ -> "\n" ++ tail (Unboxed.foldl' (\string e -> string ++ "\n |" ++ show e) "" ts)
-- If index is covariant or indifferent, show tensor compoments horizontally
_ -> "[" ++ tail (Unboxed.foldl' (\string e -> string ++ "," ++ show e) "" ts) ++ "]"
-- FiniteTensor is shown dependent on its index...
FiniteTensor index ts -> show index ++ "T: " ++ case index of
-- If index is contravariant, show tensor components vertically
Finite.Contravariant _ _ -> "\n" ++ tail (Boxed.foldl' (\string e -> string ++ "\n |" ++ show e) "" ts)
-- If index is covariant or indifferent, show tensor compoments horizontally
_ -> "[" ++ tail (Boxed.foldl' (\string e -> string ++ "," ++ show e) "" ts) ++ "]"
{-| Merge FiniteTensor of Scalars to SimpleFinite tensor for performance improvement -}
{-# INLINE _mergeScalars #-}
_mergeScalars :: Unboxed.Unbox a => Tensor a -> Tensor a
_mergeScalars x = case x of
(FiniteTensor index1 ts1) -> case ts1 Boxed.! 0 of
Scalar _ -> SimpleFinite index1 $ Unboxed.generate (Boxed.length ts1) (\i -> scalarVal (ts1 Boxed.! i))
_ -> FiniteTensor index1 $ _mergeScalars <$> ts1
_ -> x
{-| Transpose Vector of Vectors, analogous to Data.List.transpose function. It is assumed, that all vectors on deeper recursion level have the same length. -}
_transpose :: (
NFData a
) => Boxed.Vector (Boxed.Vector a) -- ^ Vector of vectors to transpose
-> Boxed.Vector (Boxed.Vector a)
_transpose v =
let outerS = Boxed.length v
innerS = Boxed.length $ v Boxed.! 0
l = Boxed.toList $ Boxed.generate innerS (\i -> Boxed.generate outerS $ \j -> v Boxed.! j Boxed.! i)
lp = l `Parallel.using` Parallel.parListChunk (innerS `div` 8) Parallel.rdeepseq
in Boxed.fromList lp
{-| Apply a tensor operator (here denoted by (+) ) elem by elem, trying to connect as many common indices as possible -}
{-# INLINE _elemByElem' #-}
_elemByElem' :: (Num a, Multilinear Tensor a, NFData a)
=> Tensor a -- ^ First argument of operator
-> Tensor a -- ^ Second argument of operator
-> (a -> a -> a) -- ^ Operator on tensor elements if indices are different
-> (Tensor a -> Tensor a -> Tensor a) -- ^ Tensor operator called if indices are the same
-> Tensor a -- ^ Result tensor
-- @Scalar x + Scalar y = Scalar x + y@
_elemByElem' (Scalar x1) (Scalar x2) f _ = Scalar $ f x1 x2
-- @Scalar x + Tensor t[i] = Tensor r[i] | r[i] = x + t[i]@
_elemByElem' (Scalar x) t f _ = (x `f`) `Multilinear.Generic.MultiCore.map` t
-- @Tensor t[i] + Scalar x = Tensor r[i] | r[i] = t[i] + x@
_elemByElem' t (Scalar x) f _ = (`f` x) `Multilinear.Generic.MultiCore.map` t
-- Two simple tensors case
_elemByElem' t1@(SimpleFinite index1 v1) t2@(SimpleFinite index2 _) f op
| Index.indexName index1 == Index.indexName index2 = op t1 t2
| otherwise = FiniteTensor index1 $ Boxed.generate (Unboxed.length v1)
(\i -> (\x -> f x `Multilinear.Generic.MultiCore.map` t2) (v1 Unboxed.! i))
-- Two finite tensors case
_elemByElem' t1@(FiniteTensor index1 v1) t2@(FiniteTensor index2 v2) f op
| Index.indexName index1 == Index.indexName index2 = op t1 t2
| Index.indexName index1 `Data.List.elem` indicesNames t2 =
let len2 = Finite.indexSize index2
rl = Boxed.toList $ (\x -> _elemByElem' t1 x f op) <$> v2
rlp = rl `Parallel.using` Parallel.parListChunk (len2 `div` 8) Parallel.rdeepseq
in FiniteTensor index2 $ Boxed.fromList rlp
| otherwise =
let len1 = Finite.indexSize index1
rl = Boxed.toList $ (\x -> _elemByElem' x t2 f op) <$> v1
rlp = rl `Parallel.using` Parallel.parListChunk (len1 `div` 8) Parallel.rdeepseq
in FiniteTensor index1 $ Boxed.fromList rlp
-- Simple and finite tensor case
_elemByElem' t1@(SimpleFinite index1 _) t2@(FiniteTensor index2 v2) f op
| Index.indexName index1 == Index.indexName index2 = op t1 t2
| otherwise =
let len2 = Finite.indexSize index2
rl = Boxed.toList $ (\x -> _elemByElem' t1 x f op) <$> v2
rlp = rl `Parallel.using` Parallel.parListChunk (len2 `div` 8) Parallel.rdeepseq
in FiniteTensor index2 $ Boxed.fromList rlp
-- Finite and simple tensor case
_elemByElem' t1@(FiniteTensor index1 v1) t2@(SimpleFinite index2 _) f op
| Index.indexName index1 == Index.indexName index2 = op t1 t2
| otherwise =
let len1 = Finite.indexSize index1
rl = Boxed.toList $ (\x -> _elemByElem' x t2 f op) <$> v1
rlp = rl `Parallel.using` Parallel.parListChunk (len1 `div` 8) Parallel.rdeepseq
in FiniteTensor index1 $ Boxed.fromList rlp
{-| Apply a tensor operator elem by elem and merge scalars to simple tensor at the and -}
{-# INLINE _elemByElem #-}
_elemByElem :: (Num a, Multilinear Tensor a, NFData a)
=> Tensor a -- ^ First argument of operator
-> Tensor a -- ^ Second argument of operator
-> (a -> a -> a) -- ^ Operator on tensor elements if indices are different
-> (Tensor a -> Tensor a -> Tensor a) -- ^ Tensor operator called if indices are the same
-> Tensor a -- ^ Result tensor
_elemByElem t1 t2 f op =
let commonIndices =
if indices t1 /= indices t2 then
Data.List.filter (`Data.List.elem` indicesNames t2) $ indicesNames t1
else []
t1' = foldl' (|>>>) t1 commonIndices
t2' = foldl' (|>>>) t2 commonIndices
in _mergeScalars $ _elemByElem' t1' t2' f op
-- | Zipping two tensors with a combinator, assuming they have the same indices.
{-# INLINE zipT #-}
zipT :: (
Num a, Multilinear Tensor a, NFData a
) => (a -> a -> a) -- ^ The zipping combinator
-> Tensor a -- ^ First tensor to zip
-> Tensor a -- ^ Second tensor to zip
-> Tensor a -- ^ Result tensor
-- Two simple tensors case
zipT f t1@(SimpleFinite index1 v1) t2@(SimpleFinite index2 v2) =
if index1 == index2 then
SimpleFinite index1 $ Unboxed.zipWith f v1 v2
else dot t1 t2
--Two finite tensors case
zipT f t1@(FiniteTensor index1 v1) t2@(FiniteTensor index2 v2) =
if index1 == index2 then let
l1l = Boxed.length v1
l3 = Boxed.toList (Boxed.zipWith (zipT f) v1 v2) `Parallel.using` Parallel.parListChunk (l1l `div` 8) Parallel.rdeepseq
in FiniteTensor index1 $ Boxed.fromList l3
else dot t1 t2
-- Zipping something with scalar is impossible
zipT _ _ _ = error $ "zipT: " ++ scalarIndices
-- | dot product of two tensors
{-# INLINE dot #-}
dot :: (Num a, Multilinear Tensor a, NFData a)
=> Tensor a -- ^ First dot product argument
-> Tensor a -- ^ Second dot product argument
-> Tensor a -- ^ Resulting dot product
-- Two simple tensors product
dot (SimpleFinite i1@(Finite.Covariant count1 _) ts1') (SimpleFinite i2@(Finite.Contravariant count2 _) ts2')
| count1 == count2 =
Scalar $ Unboxed.sum $ Unboxed.zipWith (*) ts1' ts2'
| otherwise = contractionErr "simple-simple" (Index.toTIndex i1) (Index.toTIndex i2)
dot (SimpleFinite i1@(Finite.Contravariant count1 _) ts1') (SimpleFinite i2@(Finite.Covariant count2 _) ts2')
| count1 == count2 =
Scalar $ Unboxed.sum $ Unboxed.zipWith (*) ts1' ts2'
| otherwise = contractionErr "simple-simple" (Index.toTIndex i1) (Index.toTIndex i2)
dot t1@(SimpleFinite _ _) t2@(SimpleFinite _ _) = zipT (*) t1 t2
-- Two finite tensors product
dot (FiniteTensor i1@(Finite.Covariant count1 _) ts1') (FiniteTensor i2@(Finite.Contravariant count2 _) ts2')
| count1 == count2 =
let zipList = Boxed.toList $ Boxed.zipWith (*) ts1' ts2'
zipListPar = zipList `Parallel.using` Parallel.parListChunk (count1 `div` 8) Parallel.rdeepseq
in Boxed.sum $ Boxed.fromList zipListPar
| otherwise = contractionErr "finite-finite" (Index.toTIndex i1) (Index.toTIndex i2)
dot (FiniteTensor i1@(Finite.Contravariant count1 _) ts1') (FiniteTensor i2@(Finite.Covariant count2 _) ts2')
| count1 == count2 =
let zipList = Boxed.toList $ Boxed.zipWith (*) ts1' ts2'
zipListPar = zipList `Parallel.using` Parallel.parListChunk (count1 `div` 8) Parallel.rdeepseq
in Boxed.sum $ Boxed.fromList zipListPar
| otherwise = contractionErr "finite-finite" (Index.toTIndex i1) (Index.toTIndex i2)
dot t1@(FiniteTensor _ _) t2@(FiniteTensor _ _) = zipT (*) t1 t2
-- Other cases cannot happen!
dot t1' t2' = contractionErr "other" (head $ indices t1') (head $ indices t2')
-- | contraction error
{-# INLINE contractionErr #-}
contractionErr :: String -- ^ dot function variant where error occured
-> Index.TIndex -- ^ Index of first dot product parameter
-> Index.TIndex -- ^ Index of second dot product parameter
-> Tensor a -- ^ Erorr message
contractionErr variant i1' i2' = error $
"Tensor product: " ++ variant ++ " - " ++ incompatibleTypes ++
" - index1 is " ++ show i1' ++
" and index2 is " ++ show i2'
-- | zipping error
{-# INLINE zipErr #-}
zipErr :: String -- ^ zipT function variant where the error occured
-> Index.TIndex -- ^ Index of first dot product parameter
-> Index.TIndex -- ^ Index of second dot product parameter
-> Tensor a -- ^ Erorr message
zipErr variant i1' i2' = error $
"zipT: " ++ variant ++ " - " ++ incompatibleTypes ++
" - index1 is " ++ show i1' ++
" and index2 is " ++ show i2'
-- | Tensors can be added, subtracted and multiplicated
instance (Num a, Multilinear Tensor a, NFData a) => Num (Tensor a) where
-- Adding - element by element
{-# INLINE (+) #-}
t1 + t2 = _elemByElem t1 t2 (+) $ zipT (+)
-- Subtracting - element by element
{-# INLINE (-) #-}
t1 - t2 = _elemByElem t1 t2 (-) $ zipT (-)
-- Multiplicating is treated as tensor product
-- Tensor product applies Einstein summation convention
{-# INLINE (*) #-}
t1 * t2 = _elemByElem t1 t2 (*) dot
-- Absolute value - element by element
{-# INLINE abs #-}
abs t = abs `Multilinear.Generic.MultiCore.map` t
-- Signum operation - element by element
{-# INLINE signum #-}
signum t = signum `Multilinear.Generic.MultiCore.map` t
-- Simple integer can be conveted to Scalar
{-# INLINE fromInteger #-}
fromInteger x = Scalar $ fromInteger x
-- | Tensors can be divided by each other
instance (Fractional a, Multilinear Tensor a, NFData a) => Fractional (Tensor a) where
-- Tensor dividing: TODO
{-# INLINE (/) #-}
_ / _ = error "TODO"
-- A scalar can be generated from rational number
{-# INLINE fromRational #-}
fromRational x = Scalar $ fromRational x
-- Real-number functions on tensors.
-- Function of tensor is tensor of function of its elements
-- E.g. exp [1,2,3,4] = [exp 1, exp2, exp3, exp4]
instance (Floating a, Multilinear Tensor a, NFData a) => Floating (Tensor a) where
{-| PI number -}
{-# INLINE pi #-}
pi = Scalar pi
{-| Exponential function. (exp t)[i] = exp( t[i] ) -}
{-# INLINE exp #-}
exp t = exp `Multilinear.Generic.MultiCore.map` t
{-| Natural logarithm. (log t)[i] = log( t[i] ) -}
{-# INLINE log #-}
log t = log `Multilinear.Generic.MultiCore.map` t
{-| Sinus. (sin t)[i] = sin( t[i] ) -}
{-# INLINE sin #-}
sin t = sin `Multilinear.Generic.MultiCore.map` t
{-| Cosinus. (cos t)[i] = cos( t[i] ) -}
{-# INLINE cos #-}
cos t = cos `Multilinear.Generic.MultiCore.map` t
{-| Inverse sinus. (asin t)[i] = asin( t[i] ) -}
{-# INLINE asin #-}
asin t = asin `Multilinear.Generic.MultiCore.map` t
{-| Inverse cosinus. (acos t)[i] = acos( t[i] ) -}
{-# INLINE acos #-}
acos t = acos `Multilinear.Generic.MultiCore.map` t
{-| Inverse tangent. (atan t)[i] = atan( t[i] ) -}
{-# INLINE atan #-}
atan t = atan `Multilinear.Generic.MultiCore.map` t
{-| Hyperbolic sinus. (sinh t)[i] = sinh( t[i] ) -}
{-# INLINE sinh #-}
sinh t = sinh `Multilinear.Generic.MultiCore.map` t
{-| Hyperbolic cosinus. (cosh t)[i] = cosh( t[i] ) -}
{-# INLINE cosh #-}
cosh t = cosh `Multilinear.Generic.MultiCore.map` t
{-| Inverse hyperbolic sinus. (asinh t)[i] = asinh( t[i] ) -}
{-# INLINE asinh #-}
asinh t = acosh `Multilinear.Generic.MultiCore.map` t
{-| Inverse hyperbolic cosinus. (acosh t)[i] = acosh (t[i] ) -}
{-# INLINE acosh #-}
acosh t = acosh `Multilinear.Generic.MultiCore.map` t
{-| Inverse hyperbolic tangent. (atanh t)[i] = atanh( t[i] ) -}
{-# INLINE atanh #-}
atanh t = atanh `Multilinear.Generic.MultiCore.map` t
-- Multilinear operations
instance (NFData a, Unboxed.Unbox a, Storable a, NFData a) => Multilinear Tensor a where
-- Generic tensor constructor
-- If only one upper index is given, generate a SimpleFinite tensor with upper index
fromIndices [u] [] [s] [] f =
SimpleFinite (Finite.Contravariant s [u]) $ Unboxed.generate s $ \x -> f [x] []
-- If only one lower index is given, generate a SimpleFinite tensor with lower index
fromIndices [] [d] [] [s] f =
SimpleFinite (Finite.Covariant s [d]) $ Unboxed.generate s $ \x -> f [] [x]
-- If many indices are given, first generate upper indices recursively from indices list
fromIndices (u:us) d (s:size) dsize f =
FiniteTensor (Finite.Contravariant s [u]) $ Boxed.generate s (\x -> fromIndices us d size dsize (\uss dss -> f (x:uss) dss) )
-- After upper indices, generate lower indices recursively from indices list
fromIndices u (d:ds) usize (s:size) f =
FiniteTensor (Finite.Covariant s [d]) $ Boxed.generate s (\x -> fromIndices u ds usize size (\uss dss -> f uss (x:dss)) )
-- If there are indices without size or sizes without names, throw an error
fromIndices _ _ _ _ _ = error "Indices and its sizes incompatible!"
{-| Accessing tensor elements -}
{-# INLINE el #-}
-- Scalar has only one element
el (Scalar x) _ = Scalar x
-- simple tensor case
el t1@(SimpleFinite index1 ts) (inds,vals) =
-- zip indices with their given values
let indvals = zip inds vals
-- find value for simple tensor index if given
val = Data.List.find (\(n,_) -> [n] == Index.indexName index1) indvals
-- if value for current index is given
in if isJust val
-- then get it from current tensor
then Scalar $ ts Unboxed.! snd (fromJust val)
-- otherwise return whole tensor - no filtering defined
else t1
-- finite tensor case
el (FiniteTensor index1 v1) (inds,vals) =
-- zip indices with their given values
let indvals = zip inds vals
-- find value for current index if given
val = Data.List.find (\(n,_) -> [n] == Index.indexName index1) indvals
-- and remove used index from indices list
indvals1 = Data.List.filter (\(n,_) -> [n] /= Index.indexName index1) indvals
-- indices unused so far
inds1 = Data.List.map fst indvals1
-- and its corresponding values
vals1 = Data.List.map snd indvals1
-- if value for current index was given
in if isJust val
-- then get it from current tensor and recursively process other indices
then el (v1 Boxed.! snd (fromJust val)) (inds1,vals1)
-- otherwise recursively access elements of all child tensors
else FiniteTensor index1 $ (\t -> el t (inds,vals)) <$> v1
-- List of all tensor indices
{-# INLINE indices #-}
indices x = case x of
Scalar _ -> []
FiniteTensor i ts -> Index.toTIndex i : indices (head $ toList ts)
SimpleFinite i _ -> [Index.toTIndex i]
-- Get tensor order [ (contravariant,covariant)-type ]
{-# INLINE order #-}
order x = case x of
Scalar _ -> (0,0)
SimpleFinite index _ -> case index of
Finite.Contravariant _ _ -> (1,0)
Finite.Covariant _ _ -> (0,1)
FiniteTensor _ ts -> let (cnvr, covr) = order $ ts Boxed.! 0
in case (head $ indices x) of
Index.Contravariant _ _ -> (cnvr+1,covr)
Index.Covariant _ _ -> (cnvr,covr+1)
-- Get size of tensor index or Left if index is infinite or tensor has no such index
{-# INLINE size #-}
size t iname = case t of
Scalar _ -> error scalarIndices
SimpleFinite index _ ->
if Index.indexName index == iname
then Finite.indexSize index
else error indexNotFound
FiniteTensor index ts ->
if Index.indexName index == iname
then Finite.indexSize index
else size (ts Boxed.! 0) iname
-- Rename tensor indices
{-# INLINE ($|) #-}
Scalar x $| _ = Scalar x
SimpleFinite (Finite.Contravariant isize _) ts $| (u:_, _) = SimpleFinite (Finite.Contravariant isize [u]) ts
SimpleFinite (Finite.Covariant isize _) ts $| (_, d:_) = SimpleFinite (Finite.Covariant isize [d]) ts
FiniteTensor (Finite.Contravariant isize _) ts $| (u:us, ds) = FiniteTensor (Finite.Contravariant isize [u]) $ ($| (us,ds)) <$> ts
FiniteTensor (Finite.Covariant isize _) ts $| (us, d:ds) = FiniteTensor (Finite.Covariant isize [d]) $ ($| (us,ds)) <$> ts
t $| _ = t
-- Raise an index
{-# INLINE (/\) #-}
Scalar x /\ _ = Scalar x
FiniteTensor index ts /\ n
| Index.indexName index == n =
FiniteTensor (Finite.Contravariant (Finite.indexSize index) n) $ (/\ n) <$> ts
| otherwise =
FiniteTensor index $ (/\ n) <$> ts
t1@(SimpleFinite index ts) /\ n
| Index.indexName index == n =
SimpleFinite (Finite.Contravariant (Finite.indexSize index) n) ts
| otherwise = t1
-- Lower an index
{-# INLINE (\/) #-}
Scalar x \/ _ = Scalar x
FiniteTensor index ts \/ n
| Index.indexName index == n =
FiniteTensor (Finite.Covariant (Finite.indexSize index) n) $ (\/ n) <$> ts
| otherwise =
FiniteTensor index $ (\/ n) <$> ts
t1@(SimpleFinite index ts) \/ n
| Index.indexName index == n =
SimpleFinite (Finite.Covariant (Finite.indexSize index) n) ts
| otherwise = t1
{-| Transpose a tensor (switch all indices types) -}
{-# INLINE transpose #-}
transpose (Scalar x) = Scalar x
transpose (FiniteTensor (Finite.Covariant count name) ts) =
FiniteTensor (Finite.Contravariant count name) (Multilinear.transpose <$> ts)
transpose (FiniteTensor (Finite.Contravariant count name) ts) =
FiniteTensor (Finite.Covariant count name) (Multilinear.transpose <$> ts)
transpose (SimpleFinite (Finite.Covariant count name) ts) =
SimpleFinite (Finite.Contravariant count name) ts
transpose (SimpleFinite (Finite.Contravariant count name) ts) =
SimpleFinite (Finite.Covariant count name) ts
{-| Shift tensor index right -}
{-| Moves given index one level deeper in recursion -}
-- Scalar has no indices to shift
Scalar x `shiftRight` _ = Scalar x
-- Simple tensor has only one index which cannot be shifted
t1@(SimpleFinite _ _) `shiftRight` _ = t1
-- Finite tensor is shifted by converting to list and transposing it
t1@(FiniteTensor index1 ts1) `shiftRight` ind
-- We don't shift this index
| Data.List.length (indicesNames t1) > 1 && Index.indexName index1 /= ind =
FiniteTensor index1 $ (|>> ind) <$> ts1
-- We found index to shift
| Data.List.length (indicesNames t1) > 1 && Index.indexName index1 == ind =
-- Next index
let index2 = tensorFiniteIndex (ts1 Boxed.! 0)
-- Elements to transpose
dane = if isSimple (ts1 Boxed.! 0)
then (\un -> Boxed.generate (Unboxed.length un) (\i -> Scalar $ un Unboxed.! i)) <$>
(tensorScalars <$> ts1)
else tensorsFinite <$> ts1
result = FiniteTensor index2 $ FiniteTensor index1 <$> (_transpose dane)
-- reconstruct tensor with transposed elements
in _mergeScalars result
-- there is only one index and therefore it cannot be shifted
| otherwise = t1
-- | Move contravariant indices to lower recursion level
standardize tens = foldl' (<<<|) tens $ Index.indexName <$> (Index.isContravariant `Prelude.filter` indices tens)
-- | Filter tensor
filter _ (Scalar x) = Scalar x
filter f (SimpleFinite index ts) =
let iname = Finite.indexName' index
ts' = (\i _ -> f iname i) `Unboxed.ifilter` ts
in SimpleFinite index { Finite.indexSize = Unboxed.length ts' } ts'
filter f (FiniteTensor index ts) =
let iname = Finite.indexName' index
ts' = Multilinear.filter f <$> ((\i _ -> f iname i) `Boxed.ifilter` ts)
ts'' =
(\case
(SimpleFinite _ ts) -> not $ Unboxed.null ts
(FiniteTensor _ ts) -> not $ Boxed.null ts
_ -> error $ "Filter: " ++ tensorOfScalars
) `Boxed.filter` ts'
in FiniteTensor index { Finite.indexSize = Boxed.length ts'' } ts''
-- Add scalar right
{-# INLINE (.+) #-}
(.+) :: (
Num a, Multilinear Tensor a, NFData a
) => Tensor a
-> a
-> Tensor a
t .+ x = (+x) `Multilinear.Generic.MultiCore.map` t
-- Subtract scalar right
{-# INLINE (.-) #-}
(.-) :: (
Num a, Multilinear Tensor a, NFData a
) => Tensor a
-> a
-> Tensor a
t .- x = (\p -> p - x) `Multilinear.Generic.MultiCore.map` t
-- Multiplicate by scalar right
{-# INLINE (.*) #-}
(.*) :: (
Num a, Multilinear Tensor a, NFData a
) => Tensor a
-> a
-> Tensor a
t .* x = (*x) `Multilinear.Generic.MultiCore.map` t
-- Add scalar left
{-# INLINE (+.) #-}
(+.) :: (
Num a, Multilinear Tensor a, NFData a
) => a
-> Tensor a
-> Tensor a
x +. t = (x+) `Multilinear.Generic.MultiCore.map` t
-- Subtract scalar left
{-# INLINE (-.) #-}
(-.) :: (
Num a, Multilinear Tensor a, NFData a
) => a
-> Tensor a
-> Tensor a
x -. t = (x-) `Multilinear.Generic.MultiCore.map` t
-- Multiplicate by scalar left
{-# INLINE (*.) #-}
(*.) :: (
Num a, Multilinear Tensor a, NFData a
) => a
-> Tensor a
-> Tensor a
x *. t = (x*) `Multilinear.Generic.MultiCore.map` t
-- | Simple mapping
map :: (
Multilinear Tensor a, Multilinear Tensor b,
NFData a, NFData b
) => (a -> b)
-> Tensor a
-> Tensor b
map f x = case x of
-- Mapping scalar simply maps its value
Scalar v -> Scalar $ f v
-- Mapping complex tensor does mapping element by element
SimpleFinite index ts -> SimpleFinite index (f `Unboxed.map` ts)
FiniteTensor index ts ->
let len = Boxed.length ts
lts = Boxed.toList $ Multilinear.Generic.MultiCore.map f <$> ts
ltsp = lts `Parallel.using` Parallel.parListChunk (len `div` 8) Parallel.rdeepseq
in FiniteTensor index $ Boxed.fromList ltsp
{-| Zip tensors with binary combinator, assuming they have all indices the same -}
{-# INLINE zipWith' #-}
zipWith' :: (
Multilinear Tensor a, Multilinear Tensor b, Multilinear Tensor c,
NFData a, NFData b, NFData c
) => (a -> b -> c)
-> Tensor a
-> Tensor b
-> Tensor c
-- Zipping two Scalars simply combines their values
zipWith' f (Scalar x1) (Scalar x2) = Scalar $ f x1 x2
-- zipping complex tensor with scalar
zipWith' f t (Scalar x) = (`f` x) `Multilinear.Generic.MultiCore.map` t
-- zipping scalar with complex tensor
zipWith' f (Scalar x) t = (x `f`) `Multilinear.Generic.MultiCore.map` t
-- Two simple tensors case
zipWith' f (SimpleFinite index1 v1) (SimpleFinite index2 v2) =
if index1 == index2 then
SimpleFinite index1 $ Unboxed.zipWith f v1 v2
else zipErr "simple-simple" (Index.toTIndex index1) (Index.toTIndex index2)
--Two finite tensors case
zipWith' f (FiniteTensor index1 v1) (FiniteTensor index2 v2) =
if index1 == index2 then
FiniteTensor index1 $ Boxed.zipWith (Multilinear.Generic.MultiCore.zipWith f) v1 v2
else zipErr "finite-finite" (Index.toTIndex index1) (Index.toTIndex index2)
-- Other cases cannot happen!
zipWith' _ _ _ = error "Invalid indices to peroform zip!"
{-# INLINE zipWith #-}
zipWith :: (
Multilinear Tensor a, Multilinear Tensor b, Multilinear Tensor c,
NFData a, NFData b, NFData c
) => (a -> b -> c)
-> Tensor a
-> Tensor b
-> Tensor c
zipWith f t1 t2 =
let t1' = standardize t1
t2' = standardize t2
in zipWith' f t1' t2'
| ArturB/Multilinear | src/Multilinear/Generic/MultiCore.hs | gpl-3.0 | 28,404 | 0 | 23 | 7,905 | 7,572 | 4,002 | 3,570 | -1 | -1 |
module Eval
(eval)
where
import Ast(Def(..),Expr(..))
import Value(Value,union,intersect,diff,fromList,toList,combinations)
eval :: [Value] -> Expr -> Value
eval bindings expr = e expr
where
e (ExprBag _ elts) = fromList (map (fmap (eval bindings)) elts)
e (ExprBound _ _ index) = bindings !! index
e (ExprUnion _ lhs rhs) = union (eval bindings lhs) (eval bindings rhs)
e (ExprIntersect _ lhs rhs) =
intersect (eval bindings lhs) (eval bindings rhs)
e (ExprDiff _ lhs rhs) = diff (eval bindings lhs) (eval bindings rhs)
e (ExprFuncall _ (Def _ _ expr) args)
| or (map fst args) =
fromList (map (evalFuncall expr) (combinations (map evalArg args)))
| otherwise = eval (map (eval bindings . snd) args) expr
evalArg (False,expr) = [(1,eval bindings expr)]
evalArg (True,expr) = toList (eval bindings expr)
evalFuncall expr args = (product (map fst args),eval (map snd args) expr)
| qpliu/esolang | gbagbo/hs/Eval.hs | gpl-3.0 | 954 | 0 | 14 | 215 | 464 | 239 | 225 | 19 | 7 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import System.LogFS (runLogFS, Packet(..))
import System.Fuse (defaultExceptionHandler)
import System.Environment (getArgs)
import Control.Concurrent (forkIO)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan, dupChan)
import Control.Monad (forever)
import Data.ByteString.Base64 (encode)
import qualified Data.ByteString.Char8 as B
import qualified Data.PerfectHash as Hash
import Data.Maybe (isJust)
usage :: IO ()
usage = do
putStrLn $ "usage: ./simple <number of concurrent threads> [suffixes,to,consider,as,directories] <fuse options>"
genList :: String -> [String]
genList s = read s :: [String]
runBackendStdout :: Integer -> Chan Packet -> IO ()
runBackendStdout n ch = do
pkt <- readChan ch
putStrLn $ "got("++show n++"): " ++ show pkt
runBackendFile :: String -> Chan Packet -> IO ()
runBackendFile file ch = do
pkt <- readChan ch
appendFile file $ (B.unpack $ encode $ B.pack $ show pkt) ++ "\n"
launch :: Integer -> [String] -> [String] -> IO ()
launch max' suffixes argv = do
ch <- newChan
mapM_ (\n -> forkIO $ dupChan ch >>= \nch -> forever $ runBackendStdout n nch) [1..max']
mapM_ (\n -> forkIO $ dupChan ch >>= \nch -> forever $ runBackendFile ("/tmp/logfs."++show n++".log") nch) [1..max']
let
hash :: Hash.PerfectHash Bool
hash = Hash.fromList $ map (\x -> (B.pack x, True)) suffixes
let
backendHandler :: Packet -> IO ()
backendHandler pkt = do
writeChan ch pkt
dirFilter :: String -> Bool
dirFilter s = isJust $ Hash.lookup hash (B.pack s)
runLogFS "logfs" argv backendHandler dirFilter defaultExceptionHandler
main :: IO ()
main = do
(tmax':suffixes':argv) <- getArgs
let tmax = read tmax' :: Integer
let suffixes = genList suffixes'
case (tmax > 0) of
False -> usage
_ -> launch tmax suffixes argv
| adarqui/LogFS | examples/simple.hs | gpl-3.0 | 1,839 | 0 | 17 | 318 | 696 | 359 | 337 | 48 | 2 |
{-# LANGUAGE UnicodeSyntax #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Authinfo
( readAuthInfo
, readAuthInfoFile
, getPassword )
where
import Control.Applicative ((<|>))
import Control.Monad (join)
import Data.List (find)
import Data.Monoid ((<>))
import Prelude.Unicode
import qualified System.Environment
import qualified Text.Parser.Char as P
import qualified Text.Parser.Combinators as P
import qualified Text.Parser.Token as P
import qualified Text.Trifecta.Parser as P
-- * Credentials storage: ~/.authinfo (ex-hsauthinfo) -- TODO:
gettok ∷ (Monad p, P.TokenParsing p) ⇒ Bool → String → p a → p a
gettok lastp key val = do
P.string key
(P.skipSome $ P.oneOf " \t") P.<?> "non-breaking whitespace"
ret ← val
(if lastp then P.skipMany else P.skipSome) $ P.oneOf " \t"
pure ret
readAuthInfoLine ∷ (Monad p, P.TokenParsing p) ⇒ p (String, String, String, Maybe String)
readAuthInfoLine = do
P.whiteSpace
machine ← gettok False "machine" $ P.some $ P.alphaNum <|> P.oneOf "-."
login ← gettok False "login" $ P.some P.alphaNum
mport ← P.optional $ gettok False "port" $ P.some P.alphaNum
password ← gettok True "password" $ P.some $ P.noneOf " \t\n\r"
pure (machine, login, password, mport)
readAuthInfo ∷ (Monad p, P.TokenParsing p) ⇒ p [(String, String, String, Maybe String)]
readAuthInfo = do
lines' ← P.sepEndBy readAuthInfoLine (P.newline)
P.whiteSpace
P.eof
pure lines'
readAuthInfoFile ∷ String → IO (Maybe [(String, String, String, Maybe String)])
readAuthInfoFile aipath = do
P.parseFromFile readAuthInfo aipath
getPassword ∷ Maybe String → String → String → IO (Maybe (String, Maybe String))
getPassword maipath host user = do
aipath ← case maipath of
Nothing → fmap (<> "/.authinfo") $ System.Environment.getEnv "HOME"
Just p → pure p
mainfo ← readAuthInfoFile aipath
pure $ join $ fmap (fmap (\ (_,_,pass,port) -> (pass,port))
∘
find (\ (h,u,_,_) -> h == host && u == user))
mainfo
| deepfire/youtrack | src/Authinfo.hs | gpl-3.0 | 2,302 | 0 | 16 | 623 | 742 | 392 | 350 | 50 | 2 |
import Prelude hiding (even, odd, div, compare, Num, Int, Integer, Float, Double, Rational, Word)
data Peano = Zero | Succ Peano deriving (Eq, Show)
add, sub, mul, div :: Peano -> Peano -> Peano
-- Addition
add Zero x = x
add x Zero = x
add x (Succ Zero) = Succ x
add (Succ Zero) x = Succ x
add x (Succ y) = Succ (add x y)
-- Subtraction
sub x Zero = x
sub Zero _ = error "negative number"
sub (Succ x) (Succ y) = sub x y
-- Multiplication
mul Zero _ = Zero
mul _ Zero = Zero
mul x (Succ Zero) = x
mul (Succ Zero) x = x
mul x (Succ y) = add x (mul x y)
-- Integer division
div _ Zero = error "divide by 0"
div Zero _ = Zero
div x (Succ Zero) = x
div (Succ Zero) _ = Zero
div x y = case (compare x y) of LT -> Zero
EQ -> Succ Zero
GT -> Succ (div (sub x y) y)
even, odd :: Peano -> Bool
-- Even
even Zero = True
even (Succ x)= not (even x)
-- Odd
odd x = not (even x)
compare :: Peano -> Peano -> Ordering
-- Compare
compare Zero Zero = EQ
compare Zero _ = LT
compare _ Zero = GT
compare (Succ x) (Succ y) = compare x y
| YPBlib/NaiveFunGame_hs | cw/pe.hs | gpl-3.0 | 1,092 | 0 | 12 | 310 | 551 | 286 | 265 | 32 | 3 |
{-# 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.TagManager.Accounts.Containers.Workspaces.Zones.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a GTM Zone.
--
-- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.zones.delete@.
module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Zones.Delete
(
-- * REST Resource
AccountsContainersWorkspacesZonesDeleteResource
-- * Creating a Request
, accountsContainersWorkspacesZonesDelete
, AccountsContainersWorkspacesZonesDelete
-- * Request Lenses
, acwzdXgafv
, acwzdUploadProtocol
, acwzdPath
, acwzdAccessToken
, acwzdUploadType
, acwzdCallback
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.workspaces.zones.delete@ method which the
-- 'AccountsContainersWorkspacesZonesDelete' request conforms to.
type AccountsContainersWorkspacesZonesDeleteResource
=
"tagmanager" :>
"v2" :>
Capture "path" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a GTM Zone.
--
-- /See:/ 'accountsContainersWorkspacesZonesDelete' smart constructor.
data AccountsContainersWorkspacesZonesDelete =
AccountsContainersWorkspacesZonesDelete'
{ _acwzdXgafv :: !(Maybe Xgafv)
, _acwzdUploadProtocol :: !(Maybe Text)
, _acwzdPath :: !Text
, _acwzdAccessToken :: !(Maybe Text)
, _acwzdUploadType :: !(Maybe Text)
, _acwzdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsContainersWorkspacesZonesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acwzdXgafv'
--
-- * 'acwzdUploadProtocol'
--
-- * 'acwzdPath'
--
-- * 'acwzdAccessToken'
--
-- * 'acwzdUploadType'
--
-- * 'acwzdCallback'
accountsContainersWorkspacesZonesDelete
:: Text -- ^ 'acwzdPath'
-> AccountsContainersWorkspacesZonesDelete
accountsContainersWorkspacesZonesDelete pAcwzdPath_ =
AccountsContainersWorkspacesZonesDelete'
{ _acwzdXgafv = Nothing
, _acwzdUploadProtocol = Nothing
, _acwzdPath = pAcwzdPath_
, _acwzdAccessToken = Nothing
, _acwzdUploadType = Nothing
, _acwzdCallback = Nothing
}
-- | V1 error format.
acwzdXgafv :: Lens' AccountsContainersWorkspacesZonesDelete (Maybe Xgafv)
acwzdXgafv
= lens _acwzdXgafv (\ s a -> s{_acwzdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
acwzdUploadProtocol :: Lens' AccountsContainersWorkspacesZonesDelete (Maybe Text)
acwzdUploadProtocol
= lens _acwzdUploadProtocol
(\ s a -> s{_acwzdUploadProtocol = a})
-- | GTM Zone\'s API relative path. Example:
-- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id}\/zones\/{zone_id}
acwzdPath :: Lens' AccountsContainersWorkspacesZonesDelete Text
acwzdPath
= lens _acwzdPath (\ s a -> s{_acwzdPath = a})
-- | OAuth access token.
acwzdAccessToken :: Lens' AccountsContainersWorkspacesZonesDelete (Maybe Text)
acwzdAccessToken
= lens _acwzdAccessToken
(\ s a -> s{_acwzdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
acwzdUploadType :: Lens' AccountsContainersWorkspacesZonesDelete (Maybe Text)
acwzdUploadType
= lens _acwzdUploadType
(\ s a -> s{_acwzdUploadType = a})
-- | JSONP
acwzdCallback :: Lens' AccountsContainersWorkspacesZonesDelete (Maybe Text)
acwzdCallback
= lens _acwzdCallback
(\ s a -> s{_acwzdCallback = a})
instance GoogleRequest
AccountsContainersWorkspacesZonesDelete
where
type Rs AccountsContainersWorkspacesZonesDelete = ()
type Scopes AccountsContainersWorkspacesZonesDelete =
'["https://www.googleapis.com/auth/tagmanager.edit.containers"]
requestClient
AccountsContainersWorkspacesZonesDelete'{..}
= go _acwzdPath _acwzdXgafv _acwzdUploadProtocol
_acwzdAccessToken
_acwzdUploadType
_acwzdCallback
(Just AltJSON)
tagManagerService
where go
= buildClient
(Proxy ::
Proxy
AccountsContainersWorkspacesZonesDeleteResource)
mempty
| brendanhay/gogol | gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Zones/Delete.hs | mpl-2.0 | 5,367 | 0 | 16 | 1,142 | 706 | 413 | 293 | 108 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module Core.ModelSpec where
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map.Strict as M
import qualified GHC.Generics as GN
import qualified Misc.Json as Json
import Core.Database ((=:))
import Core.Model
import SpecHelper
data Post = Post
{ postId :: Maybe BS.ByteString
, count :: Integer
, email :: BS.ByteString
, password :: BS.ByteString
} deriving (GN.Generic)
instance Model Post
spec :: Spec
spec =
describe "Core.ModelSpec" $
context "Simple Text" $ do
it "parses json with postId" $
gToJson (GN.from dataWithPostId) `shouldBe`
Json.JSObject (M.fromList
[ ("count", Json.JSInt 3)
, ("email", Json.JSString "[email protected]")
, ("password", Json.JSString "SHA256")
, ("postId", Json.JSString "Hello")
])
it "parses json without postId" $
gToJson (GN.from dataWithoutPostId) `shouldBe`
Json.JSObject (M.fromList
[ ("count", Json.JSInt 2)
, ("email", Json.JSString "[email protected]")
, ("password", Json.JSString "MD5")
])
it "parses bson with postId" $
gToDocument (GN.from dataWithPostId) `shouldBe`
[ "postId" =: ("Hello" :: BS.ByteString)
, "count" =: (3 :: Int)
, "email" =: ("[email protected]" :: BS.ByteString)
, "password" =: ("SHA256" :: BS.ByteString)
]
it "parses bson without postId" $
gToDocument (GN.from dataWithoutPostId) `shouldBe`
[ "count" =: (2 :: Int)
, "email" =: ("[email protected]" :: BS.ByteString)
, "password" =: ("MD5" :: BS.ByteString)
]
where
dataWithPostId = Post (Just "Hello") 3 "[email protected]" "SHA256"
dataWithoutPostId = Post Nothing 2 "[email protected]" "MD5"
main :: IO ()
main = hspec spec
| inq/manicure | spec/Core/ModelSpec.hs | agpl-3.0 | 1,919 | 0 | 15 | 528 | 530 | 297 | 233 | 48 | 1 |
--
-- Copyright 2017-2018 Azad Bolour
-- Licensed under GNU Affero General Public License v3.0 -
-- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md
--
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE DisambiguateRecordFields #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleContexts #-}
-- TODO. Use the generic Bolour.Util.Cache to implement the game cache.
module BoardGame.Server.Domain.GameCache (
mkGameCache
, cacheGetGamesMap
, insert
, lookup
, delete
, deleteItems
, GameCache(..)
) where
import Prelude hiding (lookup)
import Data.IORef
import qualified Data.Map.Strict as Map
import Control.Exception (bracket_)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Except (ExceptT(ExceptT), MonadError(..))
import Control.Concurrent (MVar, newMVar, takeMVar, putMVar)
import BoardGame.Server.Domain.Game(Game)
import qualified BoardGame.Server.Domain.Game as Game
import BoardGame.Server.Domain.GameError
import Bolour.Util.MiscUtil (IOEither, IOExceptT)
-- | Cache of active games.
data GameCache = GameCache {
capacity :: Int
, lock :: MVar ()
, gameMapRef :: IORef (Map.Map String Game)
}
gameMap :: Map.Map String Game
gameMap = Map.empty
mkGameCache :: Int -> IO GameCache
mkGameCache capacity = do
ref <- newIORef gameMap
lock <- newMVar ()
return $ GameCache capacity lock ref
-- type GameIOEither a = IO (Either GameError a)
-- TODO. Just use generic Cache for game cache. Most of this code is duplicated in Cache.
-- But generic cache uses String for errors not GameError used here.
-- Generic cache should use a generic error class.
-- That class will need to get translated to GameError in clients of Cache.do
-- This module can then be removed.
-- TODO. Don't know how to use bracket with constraints MonadIO m, MonadError GameError m to return an m.
insert :: Game -> GameCache -> IOExceptT GameError ()
insert game (cache @ (GameCache {lock})) =
let ioEither = bracket_ (takeMVar lock) (putMVar lock ()) (insertInternal game cache)
in ExceptT ioEither
insertInternal :: Game -> GameCache -> IOEither GameError ()
insertInternal game (GameCache {gameMapRef}) = do
let gameId = Game.gameId game
map <- readIORef gameMapRef
let numGames = Map.size map
if numGames < 100 -- TODO. Use configured number.
then do
res <- modifyIORef gameMapRef (Map.insert gameId game)
return $ Right res
else return $ Left SystemOverloadedError
-- TODO. If game is not in cache check the database.
-- Differentiate timed-out games from non-existent games.
-- For now assume that the game existed and was timed out and ejected from the cache.
lookup :: String -> GameCache -> IOExceptT GameError Game
lookup game (cache @ (GameCache {lock})) =
let ioEither = bracket_ (takeMVar lock) (putMVar lock ()) (lookupInternal game cache)
in ExceptT ioEither
lookupInternal :: String -> GameCache -> IOEither GameError Game
lookupInternal gameId (GameCache {gameMapRef}) = do
map <- readIORef gameMapRef
let maybeGame = Map.lookup gameId map
case maybeGame of
Nothing -> return $ Left $ GameTimeoutError gameId
Just game -> return $ Right game
delete :: String -> GameCache -> IOExceptT GameError ()
delete gameId (cache @ (GameCache {lock})) =
let ioEither = bracket_ (takeMVar lock) (putMVar lock ()) (deleteInternal gameId cache)
in ExceptT ioEither
deleteInternal :: String -> GameCache -> IOEither GameError ()
deleteInternal gameId (GameCache {gameMapRef}) = do
map <- readIORef gameMapRef
let maybeGame = Map.lookup gameId map
case maybeGame of
Nothing -> return $ Left $ GameTimeoutError gameId
Just game -> do
res <- modifyIORef gameMapRef (Map.delete gameId)
return $ Right res
deleteInternalIfExists :: String -> GameCache -> IO ()
deleteInternalIfExists gameId (GameCache {gameMapRef}) = do
map <- readIORef gameMapRef
let maybeGame = Map.lookup gameId map
case maybeGame of
Nothing -> return ()
Just game -> modifyIORef gameMapRef (Map.delete gameId)
deleteItems :: [String] -> GameCache -> IOExceptT GameError ()
deleteItems gameIds (cache @ GameCache {lock}) =
let ioEither = bracket_ (takeMVar lock) (putMVar lock ()) (deleteItemsInternal gameIds cache)
in ExceptT ioEither
deleteItemsInternal :: [String] -> GameCache -> IOEither GameError ()
deleteItemsInternal gameIds cache =
let dummy = flip deleteInternalIfExists cache <$> gameIds
in return $ Right ()
cacheGetGamesMap :: (MonadIO m) => GameCache -> m (Map.Map String Game)
cacheGetGamesMap GameCache {gameMapRef, lock} =
liftIO $ bracket_ (takeMVar lock) (putMVar lock ()) $ readIORef gameMapRef
| azadbolour/boardgame | haskell-server/src/BoardGame/Server/Domain/GameCache.hs | agpl-3.0 | 4,656 | 7 | 16 | 811 | 1,278 | 661 | 617 | 90 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Database.Persist.Postgresql
import THIS.Database.Entities
main :: IO ()
main = do
withPostgresqlConn "dbname=this" $ runSqlConn $ do
runMigration migrateAll
| portnov/integration-server | this-install-db.hs | lgpl-3.0 | 207 | 0 | 10 | 31 | 49 | 25 | 24 | 7 | 1 |
module Git.Command.Rerere (run) where
run :: [String] -> IO ()
run args = return () | wereHamster/yag | Git/Command/Rerere.hs | unlicense | 84 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
module KthDifferences.A328190Spec (main, spec) where
import Test.Hspec
import KthDifferences.A328190 (a328190)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A328190" $
it "correctly computes the first 20 elements" $
take 20 (map a328190 [1..]) `shouldBe` expectedValue where
expectedValue = [1, 3, 7, 5, 11, 8, 17, 10, 22, 13, 27, 15, 31, 18, 37, 20, 41, 23, 47, 25]
| peterokagey/haskellOEIS | test/KthDifferences/A328190Spec.hs | apache-2.0 | 397 | 0 | 10 | 78 | 160 | 95 | 65 | 10 | 1 |
-- http://www.codewars.com/kata/55d2aee99f30dbbf8b000001
module Codewars.Kata.ScoringTests where
scoreTest :: (Integral a) => [a] -> a -> a -> a -> a
scoreTest li a b c = sum $ map f li
where
f 0 = a
f 1 = b
f 2 = -c | Bodigrim/katas | src/haskell/7-Scoring-Tests.hs | bsd-2-clause | 231 | 0 | 9 | 57 | 92 | 49 | 43 | 6 | 3 |
{-# LANGUAGE DeriveDataTypeable, BangPatterns #-}
module Data.Mathematica where
import Data.Typeable
import Data.Data
{-
data Atom = MSymbol String
| MNumber Double
| MString String
deriving (Show, Eq, Typeable, Data)
-}
data MExpression = MSymbol !String
| MInteger !Integer
| MReal !Double
| MString !String
| MExp { exp_head :: MExpression
, exp_elements :: [MExpression] }
deriving (Show, Eq, Typeable, Data) | wavewave/mathematica-data | lib/Data/Mathematica.hs | bsd-2-clause | 569 | 0 | 9 | 216 | 85 | 49 | 36 | 19 | 0 |
{-# language CPP #-}
-- No documentation found for Chapter "FrontFace"
module Vulkan.Core10.Enums.FrontFace (FrontFace( FRONT_FACE_COUNTER_CLOCKWISE
, FRONT_FACE_CLOCKWISE
, ..
)) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showsPrec)
import Vulkan.Zero (Zero)
import Foreign.Storable (Storable)
import Data.Int (Int32)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
-- | VkFrontFace - Interpret polygon front-facing orientation
--
-- = Description
--
-- Any triangle which is not front-facing is back-facing, including
-- zero-area triangles.
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo',
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetFrontFace',
-- 'Vulkan.Extensions.VK_EXT_extended_dynamic_state.cmdSetFrontFaceEXT'
newtype FrontFace = FrontFace Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'FRONT_FACE_COUNTER_CLOCKWISE' specifies that a triangle with positive
-- area is considered front-facing.
pattern FRONT_FACE_COUNTER_CLOCKWISE = FrontFace 0
-- | 'FRONT_FACE_CLOCKWISE' specifies that a triangle with negative area is
-- considered front-facing.
pattern FRONT_FACE_CLOCKWISE = FrontFace 1
{-# complete FRONT_FACE_COUNTER_CLOCKWISE,
FRONT_FACE_CLOCKWISE :: FrontFace #-}
conNameFrontFace :: String
conNameFrontFace = "FrontFace"
enumPrefixFrontFace :: String
enumPrefixFrontFace = "FRONT_FACE_C"
showTableFrontFace :: [(FrontFace, String)]
showTableFrontFace = [(FRONT_FACE_COUNTER_CLOCKWISE, "OUNTER_CLOCKWISE"), (FRONT_FACE_CLOCKWISE, "LOCKWISE")]
instance Show FrontFace where
showsPrec =
enumShowsPrec enumPrefixFrontFace showTableFrontFace conNameFrontFace (\(FrontFace x) -> x) (showsPrec 11)
instance Read FrontFace where
readPrec = enumReadPrec enumPrefixFrontFace showTableFrontFace conNameFrontFace FrontFace
| expipiplus1/vulkan | src/Vulkan/Core10/Enums/FrontFace.hs | bsd-3-clause | 2,187 | 1 | 10 | 376 | 306 | 188 | 118 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Pass.Robust
-- Copyright : (C) 2012-2013 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GADTs, Rank2Types)
--
----------------------------------------------------------------------------
module Data.Pass.Robust
( Robust(..)
, median
, iqm
, idm
, tercile, t1, t2
, quartile, q1, q2, q3
, quintile, qu1, qu2, qu3, qu4
, percentile
, permille
) where
import Data.Pass.Type
import Data.Pass.Calc
import Data.Pass.Fun
import Data.Pass.Thrist
import Data.Pass.L
import Data.Pass.L.Estimator
-- | embedding for L-estimators
class Robust l where
robust :: L a b -> l a b
winsorized :: (Fractional b, Ord b) => Rational -> L a b -> l a b
winsorized p f = robust $ Winsorized p f
trimmed :: (Fractional b, Ord b) => Rational -> L a b -> l a b
trimmed p f = robust $ Trimmed p f
jackknifed :: (Fractional b, Ord b) => L a b -> l a b
jackknifed f = robust $ Jackknifed f
lscale :: (Fractional a, Ord a) => l a a
lscale = robust LScale
quantile :: (Fractional a, Ord a) => Rational -> l a a
quantile p = robust $ QuantileBy R2 p
midhinge :: (Fractional a, Ord a) => l a a
midhinge = robust $ 0.5 :* (q1 :+ q3)
-- | Tukey's trimean
trimean :: (Fractional a, Ord a) => l a a
trimean = robust $ 0.25 :* (q1 :+ 2 :* q2 :+ q3)
-- | interquartile range
iqr :: (Fractional a, Ord a) => l a a
iqr = robust $ ((-1) :* q1) :+ q3
idr :: (Fractional a, Ord a) => l a a
idr = robust $ ((-1) :* quantile 0.1) :+ quantile 0.9
-- | interquartile mean
iqm :: (Robust l, Fractional a, Ord a) => l a a
iqm = trimmed 0.25 LMean
idm :: (Robust l, Fractional a, Ord a) => l a a
idm = trimmed 0.1 LMean
median :: (Robust l, Fractional a, Ord a) => l a a
median = quantile 0.5
tercile :: (Robust l, Fractional a, Ord a) => Rational -> l a a
tercile n = quantile (n/3)
-- | terciles 1 and 2
t1, t2 :: (Robust l, Fractional a, Ord a) => l a a
t1 = tercile 1
t2 = tercile 2
quartile :: (Robust l, Fractional a, Ord a) => Rational -> l a a
quartile n = quantile (n/4)
-- | quantiles, with breakdown points 25%, 50%, and 25% respectively
q1, q2, q3 :: (Robust l, Fractional a, Ord a) => l a a
q1 = quantile 0.25
q2 = median
q3 = quantile 0.75
quintile :: (Robust l, Fractional a, Ord a) => Rational -> l a a
quintile n = quantile (n/5)
-- | quintiles 1 through 4
qu1, qu2, qu3, qu4 :: (Robust l, Fractional a, Ord a) => l a a
qu1 = quintile 1
qu2 = quintile 2
qu3 = quintile 3
qu4 = quintile 4
percentile :: (Robust l, Fractional a, Ord a) => Rational -> l a a
percentile n = quantile (n/100)
permille :: (Robust l, Fractional a, Ord a) => Rational -> l a a
permille n = quantile (n/1000)
instance Robust L where
robust = id
instance Robust l => Robust (Fun l) where
robust = Fun . robust
newtype Flip f a b = Flip { flop :: f b a }
instance Robust (Pass k) where
robust l = L id (flop (eqL l (Flip l))) (eqL l Nil)
midhinge = (q1 + q3) / 2
trimean = (q1 + 2 * q2 + q3) / 4
iqr = q3 - q1
instance Robust (Calc k) where
robust l = robust l :& Stop
midhinge = midhinge :& Stop
trimean = trimean :& Stop
iqr = iqr :& Stop
| ekmett/multipass | Data/Pass/Robust.hs | bsd-3-clause | 3,341 | 0 | 12 | 789 | 1,382 | 741 | 641 | 79 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Main where
import Control.Natural
import Data.Aeson
import qualified Data.Text.IO as TIO
import qualified Data.Text.Lazy as LT
import Data.Text.Lazy.Encoding (decodeUtf8)
import Control.Monad (when)
import Control.Remote.Monad.JSON
import Control.Remote.Monad.JSON.Router
import System.Exit
import Test (Test (..), readTests)
f :: Call a -> IO a
f (CallMethod "subtract" (List [Number a,Number b])) = return $ Number (a - b)
f (CallMethod "subtract" (Named xs))
| Just (Number a) <- lookup "minuend" xs
, Just (Number b) <- lookup "subtrahend" xs
= return $ Number (a - b)
f (CallMethod "sum" args) = case args of
List xs -> return $ Number $ sum $ [ x | Number x <- xs ]
_ -> invalidParams
f (CallMethod "get_data" None) = return $ toJSON [String "hello", Number 5]
f (CallMethod "error" (List [String msg])) = error $ show msg
f (CallMethod "fail" (List [String msg])) = fail $ show msg
f (CallNotification "update" _) = return $ ()
f (CallNotification "notify_hello" _) = return $ ()
f (CallNotification "notify_sum" _) = return $ ()
f _ = methodNotFound
main = do
tests <- readTests "tests/spec/Spec.txt"
let testWith i testName (Right v_req) v_expect = do
putStrLn $ ("--> " ++) $ LT.unpack $ decodeUtf8 $ encode v_req
r <- router sequence (wrapNT f) # (Receive v_req)
showResult i testName r v_expect
testWith i testName (Left bad) v_expect = do
putStr "--> "
TIO.putStr $ bad
let r = Just $ parseError
showResult i testName r v_expect
showResult i testName Nothing v_expect = do
testResult i testName Nothing v_expect
showResult i testName (Just v_resp) v_expect = do
putStrLn $ ("<-- " ++) $ LT.unpack $ decodeUtf8 $ encode v_resp
testResult i testName (Just v_resp) v_expect
testResult i testName r v_expect = do
r <- if (r /= v_expect)
then do putStrLn $ ("exp " ++) $ LT.unpack $ decodeUtf8 $ encode v_expect
return $ Just (i,testName)
else return Nothing
putStrLn ""
return r
res <- sequence
[ do when (i == 1) $ do
putStr "#"
TIO.putStrLn $ testName
testWith i testName v_req v_expect
| (Test testName subTests) <- tests
, (i,(v_req,v_expect)) <- [1..] `zip` subTests
]
let failing = [ x | Just x <- res ]
if (null failing)
then putStrLn $ "ALL " ++ show (length res) ++ " TEST(S) PASS"
else do
putStrLn $ show (length failing) ++ " test(s) failed"
putStrLn $ unlines $ map show failing
exitFailure
| ku-fpg/remote-json | tests/spec/Spec.hs | bsd-3-clause | 3,008 | 0 | 20 | 1,011 | 1,033 | 516 | 517 | 67 | 5 |
{-# LANGUAGE BangPatterns #-}
-- BANNERSTART
-- - Copyright 2006-2008, Galois, Inc.
-- - This software is distributed under a standard, three-clause BSD license.
-- - Please see the file LICENSE, distributed with this software, for specific
-- - terms and conditions.
-- Author: Adam Wick <[email protected]>
-- BANNEREND
-- |A module providing checksum computations to other parts of Hans. The
-- checksum here is the standard Internet 16-bit checksum (the one's
-- complement of the one's complement sum of the data).
module Hans.Utils.Checksum(
computeChecksum
, computePartialChecksum
, clearChecksum
, pokeChecksum
)
where
import Control.Exception (assert)
import Data.Bits (Bits(shiftL,shiftR,complement,clearBit,(.&.),rotate))
import Data.Word (Word8,Word16,Word32)
import Foreign.Storable (pokeByteOff)
import qualified Data.ByteString as S
import qualified Data.ByteString.Unsafe as S
-- | Clear the two bytes at the checksum offset of a rendered packet.
clearChecksum :: S.ByteString -> Int -> IO S.ByteString
clearChecksum b off = S.unsafeUseAsCStringLen b $ \(ptr,len) -> do
assert (len > off + 1) (pokeByteOff ptr off (0 :: Word16))
return b
-- | Poke a checksum into a bytestring.
pokeChecksum :: Word16 -> S.ByteString -> Int -> IO S.ByteString
pokeChecksum cs b off = S.unsafeUseAsCStringLen b $ \(ptr,len) -> do
assert (off < len + 1) (pokeByteOff ptr off (rotate cs 8))
return b
-- | Compute the final checksum, using the given initial value.
computeChecksum :: Word32 -> S.ByteString -> Word16
computeChecksum c0 =
complement . fromIntegral . fold32 . fold32 . computePartialChecksum c0
-- | Compute a partial checksum, yielding a value suitable to be passed to
-- computeChecksum.
computePartialChecksum :: Word32 -> S.ByteString -> Word32
computePartialChecksum base b = result
where
!n' = S.length b
!result
| odd n' = step most hi 0
| otherwise = most
where hi = S.unsafeIndex b (n'-1)
!most = loop (fromIntegral base) 0
loop !acc off
| off < n = loop (step acc hi lo) (off + 2)
| otherwise = acc
where hi = S.unsafeIndex b off
lo = S.unsafeIndex b (off+1)
n = clearBit n' 0
step :: Word32 -> Word8 -> Word8 -> Word32
step acc hi lo = acc + fromIntegral hi `shiftL` 8 + fromIntegral lo
fold32 :: Word32 -> Word32
fold32 x = (x .&. 0xFFFF) + (x `shiftR` 16)
| Tener/HaNS | src/Hans/Utils/Checksum.hs | bsd-3-clause | 2,425 | 0 | 13 | 513 | 639 | 345 | 294 | 41 | 1 |
{-#LANGUAGE OverloadedStrings#-}
{-
Min Zhang
3-26-2015
Translate DNA/RNA to protein aa sequence.
v.0.1.1 (Oct 14, 2015): switch from Data.Text to Data.Text.Lazy
-}
module Main
where
import qualified Data.Text.Lazy.IO as TextIO
import qualified Data.Text.Lazy as T
import Control.Applicative
import System.Environment
import Data.Monoid
import Dna
import IO
import DataTypes
translate :: T.Text -> T.Text
translate "" = mempty
translate rna = codon (T.take 3 rna) `mappend` translate (T.drop 3 rna)
codon :: T.Text -> T.Text
codon r
|T.take 2 r == "UU" = if lastUC r then "F" else "L"
|T.take 2 r == "UC" = "S"
|T.take 2 r == "UA" = if lastUC r then "Y" else "s"
|T.take 2 r == "UG" = if lastUC r then "C" else if T.last r == 'A' then "s" else "W"
|T.take 2 r == "CU" = "L"
|T.take 2 r == "CC" = "P"
|T.take 2 r == "CA" = if lastUC r then "H" else "Q"
|T.take 2 r == "CG" = "R"
|T.take 2 r == "AU" = if lastUC r then "I" else if T.last r == 'A' then "I" else "M"
|T.take 2 r == "AC" = "T"
|T.take 2 r == "AA" = if lastUC r then "N" else "K"
|T.take 2 r == "AG" = if lastUC r then "S" else "R"
|T.take 2 r == "GU" = "V"
|T.take 2 r == "GC" = "A"
|T.take 2 r == "GA" = if lastUC r then "D" else "E"
|T.take 2 r == "GG" = "G"
|otherwise = "x"
lastUC r = T.last r == 'U' || T.last r == 'C'
faDnaToRna fa = Fasta (faname fa) ((dnaToRna . faseq) fa)
faRnaToProtein fa = Fasta (faname fa) ((T.init . translate . faseq) fa)
intro = do
TextIO.putStrLn "Translate RNA/DNA to protein sequence.\n"
TextIO.putStrLn "Translate [input DNA Fasta] [output Fasta]\n"
-- IO
readRNA inpath outpath = do
dna <- map faDnaToRna <$> importFasta inpath
let protein = map faRnaToProtein dna
outputFasta outpath protein
main = do
intro
[inpath, outpath] <- take 2 <$> getArgs
readRNA inpath outpath
| Min-/fourseq | src/utils/Translate.hs | bsd-3-clause | 1,852 | 0 | 11 | 421 | 786 | 386 | 400 | 46 | 11 |
module ScannerSpec (spec) where
import Data.Maybe (fromJust)
import Test.Hspec
import Scanner
import Types
scanAndExtractFirst :: String -> Token
scanAndExtractFirst = head . fromJust . scan
spec :: Spec
spec =
describe "The Scanner" $ do
it "scans the empty String" $
scan "" `shouldBe` Just []
it "scans a newline" $
scanAndExtractFirst "\n" `shouldBe` TokenNewline
it "scans a blank" $
scanAndExtractFirst " h a l l o" `shouldBe` TokenBlanks 1
it "scans 10 blanks" $
scanAndExtractFirst " h a l l o"
`shouldBe` TokenBlanks 10
it "scans H1" $
scanAndExtractFirst "# Hallo" `shouldBe` TokenH 1
it "scans H2" $
scanAndExtractFirst "## Hallo" `shouldBe` TokenH 2
it "scans H3" $
scanAndExtractFirst "### Hallo" `shouldBe` TokenH 3
it "scans H4" $
scanAndExtractFirst "#### Hallo" `shouldBe` TokenH 4
it "scans H5" $
scanAndExtractFirst "##### Hallo" `shouldBe` TokenH 5
it "scans H6" $
scanAndExtractFirst "###### Hallo" `shouldBe` TokenH 6
it "scans no H7 gut a Text" $
scanAndExtractFirst "####### Hallo"
`shouldBe` TokenText "#######"
it "scans H4 without a following blank" $
scanAndExtractFirst "####Hallo" `shouldBe` TokenH 4
it "scans a string" $
scanAndExtractFirst "Hallo" `shouldBe` TokenText "Hallo"
| ob-cs-hm-edu/compiler-md2html | test/ScannerSpec.hs | bsd-3-clause | 1,572 | 0 | 10 | 544 | 354 | 170 | 184 | 38 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, MagicHash
, UnboxedTuples
#-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.TopHandler
-- Copyright : (c) The University of Glasgow, 2001-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Support for catching exceptions raised during top-level computations
-- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports)
--
-----------------------------------------------------------------------------
module GHC.TopHandler (
runMainIO, runIO, runIOFastExit, runNonIO,
topHandler, topHandlerFastExit,
reportStackOverflow, reportError,
flushStdHandles
) where
#include "HsBaseConfig.h"
import Control.Exception
import Data.Maybe
import Foreign
import Foreign.C
import GHC.Base
import GHC.Conc hiding (throwTo)
import GHC.Real
import GHC.IO
import GHC.IO.Handle.FD
import GHC.IO.Handle
import GHC.IO.Exception
import GHC.Weak
#if defined(mingw32_HOST_OS)
import GHC.ConsoleHandler
#else
import Data.Dynamic (toDyn)
#endif
-- | 'runMainIO' is wrapped around 'Main.main' (or whatever main is
-- called in the program). It catches otherwise uncaught exceptions,
-- and also flushes stdout\/stderr before exiting.
runMainIO :: IO a -> IO a
runMainIO main =
do
main_thread_id <- myThreadId
weak_tid <- mkWeakThreadId main_thread_id
install_interrupt_handler $ do
m <- deRefWeak weak_tid
case m of
Nothing -> return ()
Just tid -> throwTo tid (toException UserInterrupt)
main -- hs_exit() will flush
`catch`
topHandler
install_interrupt_handler :: IO () -> IO ()
#if defined(ghcjs_HOST_OS)
install_interrupt_handler _ = return ()
#elif defined(mingw32_HOST_OS)
install_interrupt_handler handler = do
_ <- GHC.ConsoleHandler.installHandler $
Catch $ \event ->
case event of
ControlC -> handler
Break -> handler
Close -> handler
_ -> return ()
return ()
#else
#include "rts/Signals.h"
-- specialised version of System.Posix.Signals.installHandler, which
-- isn't available here.
install_interrupt_handler handler = do
let sig = CONST_SIGINT :: CInt
_ <- setHandler sig (Just (const handler, toDyn handler))
_ <- stg_sig_install sig STG_SIG_RST nullPtr
-- STG_SIG_RST: the second ^C kills us for real, just in case the
-- RTS or program is unresponsive.
return ()
foreign import ccall unsafe
stg_sig_install
:: CInt -- sig no.
-> CInt -- action code (STG_SIG_HAN etc.)
-> Ptr () -- (in, out) blocked
-> IO CInt -- (ret) old action code
#endif
-- | 'runIO' is wrapped around every @foreign export@ and @foreign
-- import \"wrapper\"@ to mop up any uncaught exceptions. Thus, the
-- result of running 'System.Exit.exitWith' in a foreign-exported
-- function is the same as in the main thread: it terminates the
-- program.
--
runIO :: IO a -> IO a
runIO main = catch main topHandler
-- | Like 'runIO', but in the event of an exception that causes an exit,
-- we don't shut down the system cleanly, we just exit. This is
-- useful in some cases, because the safe exit version will give other
-- threads a chance to clean up first, which might shut down the
-- system in a different way. For example, try
--
-- main = forkIO (runIO (exitWith (ExitFailure 1))) >> threadDelay 10000
--
-- This will sometimes exit with "interrupted" and code 0, because the
-- main thread is given a chance to shut down when the child thread calls
-- safeExit. There is a race to shut down between the main and child threads.
--
runIOFastExit :: IO a -> IO a
runIOFastExit main = catch main topHandlerFastExit
-- NB. this is used by the testsuite driver
-- | The same as 'runIO', but for non-IO computations. Used for
-- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these
-- are used to export Haskell functions with non-IO types.
--
runNonIO :: a -> IO a
runNonIO a = catch (a `seq` return a) topHandler
topHandler :: SomeException -> IO a
topHandler err = catch (real_handler safeExit err) topHandler
topHandlerFastExit :: SomeException -> IO a
topHandlerFastExit err =
catchException (real_handler fastExit err) topHandlerFastExit
-- Make sure we handle errors while reporting the error!
-- (e.g. evaluating the string passed to 'error' might generate
-- another error, etc.)
--
real_handler :: (Int -> IO a) -> SomeException -> IO a
real_handler exit se = do
flushStdHandles -- before any error output
case fromException se of
Just StackOverflow -> do
reportStackOverflow
exit 2
Just UserInterrupt -> exitInterrupted
_ -> case fromException se of
-- only the main thread gets ExitException exceptions
Just ExitSuccess -> exit 0
Just (ExitFailure n) -> exit n
-- EPIPE errors received for stdout are ignored (#2699)
_ -> catch (case fromException se of
Just IOError{ ioe_type = ResourceVanished,
ioe_errno = Just ioe,
ioe_handle = Just hdl }
| Errno ioe == ePIPE, hdl == stdout -> exit 0
_ -> do reportError se
exit 1
) (disasterHandler exit) -- See Note [Disaster with iconv]
-- don't use errorBelch() directly, because we cannot call varargs functions
-- using the FFI.
foreign import ccall unsafe "HsBase.h errorBelch2"
errorBelch :: CString -> CString -> IO ()
disasterHandler :: (Int -> IO a) -> IOError -> IO a
disasterHandler exit _ =
withCAString "%s" $ \fmt ->
withCAString msgStr $ \msg ->
errorBelch fmt msg >> exit 1
where
msgStr =
"encountered an exception while trying to report an exception." ++
"One possible reason for this is that we failed while trying to " ++
"encode an error message. Check that your locale is configured " ++
"properly."
{- Note [Disaster with iconv]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When using iconv, it's possible for things like iconv_open to fail in
restricted environments (like an initram or restricted container), but
when this happens the error raised inevitably calls `peekCString`,
which depends on the users locale, which depends on using
`iconv_open`... which causes an infinite loop.
This occurrence is also known as tickets #10298 and #7695. So to work
around it we just set _another_ error handler and bail directly by
calling the RTS, without iconv at all.
-}
-- try to flush stdout/stderr, but don't worry if we fail
-- (these handles might have errors, and we don't want to go into
-- an infinite loop).
flushStdHandles :: IO ()
flushStdHandles = do
hFlush stdout `catchAny` \_ -> return ()
hFlush stderr `catchAny` \_ -> return ()
safeExit, fastExit :: Int -> IO a
safeExit = exitHelper useSafeExit
fastExit = exitHelper useFastExit
unreachable :: IO a
unreachable = fail "If you can read this, shutdownHaskellAndExit did not exit."
exitHelper :: CInt -> Int -> IO a
#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS)
exitHelper exitKind r =
shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable
#else
-- On Unix we use an encoding for the ExitCode:
-- 0 -- 255 normal exit code
-- -127 -- -1 exit by signal
-- For any invalid encoding we just use a replacement (0xff).
exitHelper exitKind r
| r >= 0 && r <= 255
= shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable
| r >= -127 && r <= -1
= shutdownHaskellAndSignal (fromIntegral (-r)) exitKind >> unreachable
| otherwise
= shutdownHaskellAndExit 0xff exitKind >> unreachable
foreign import ccall "shutdownHaskellAndSignal"
shutdownHaskellAndSignal :: CInt -> CInt -> IO ()
#endif
exitInterrupted :: IO a
exitInterrupted =
#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS)
safeExit 252
#else
-- we must exit via the default action for SIGINT, so that the
-- parent of this process can take appropriate action (see #2301)
safeExit (-CONST_SIGINT)
#endif
-- NOTE: shutdownHaskellAndExit must be called "safe", because it *can*
-- re-enter Haskell land through finalizers.
foreign import ccall "Rts.h shutdownHaskellAndExit"
shutdownHaskellAndExit :: CInt -> CInt -> IO ()
useFastExit, useSafeExit :: CInt
useFastExit = 1
useSafeExit = 0
| tolysz/prepare-ghcjs | spec-lts8/base/GHC/TopHandler.hs | bsd-3-clause | 8,746 | 0 | 22 | 2,029 | 1,022 | 548 | 474 | 118 | 6 |
-- | Mostly GLFW stuff.
-- See http://www.glfw.org/docs/3.0/moving.html#moving_window_handle
--
module App.App ( App(..)
, runApp
) where
import App.Types
import App.Clock
import App.Input
import App.UserApp
import Control.Monad.State
import Control.Concurrent
import Control.Lens
import Data.Maybe
import System.Exit ( exitSuccess, exitFailure )
import Graphics.Rendering.OpenGL hiding ( Matrix )
import Graphics.UI.GLFW hiding ( getTime )
runApp :: String -> UserApp a -> IO ()
runApp title userData = initializeApp title userData >>= startWithMVar
initializeApp :: String -> UserApp a -> IO (AppVar a)
initializeApp title uApp = do
mWin <- initGLFW title
case mWin of
Nothing -> do putStrLn "Could not create a window."
exitFailure
Just win -> do makeContextCurrent mWin
time <- getTime
mvar <- newEmptyMVar
-- When True this gives us a moment
-- to attach an OGL profiler.
when False $ do
putStrLn "Waiting for any button press..."
void getChar
return ()
-- Register our resize window function.
setWindowSizeCallback win $ Just (\win' w h -> do
app <- readMVar mvar
let input = flip execState (_userInput app) $ do
inputEvents %= (WindowSizeChangedTo (w,h):)
inputState.windowSize .= (w,h)
userData' = (app^.userApp.onInput) input (app^.userApp.userData)
renderUserApp win' $ app^.userApp & userData .~ userData')
let clock' = tickClock time emptyClock
app = App { _userApp = uApp
, _userInput = emptyInput
, _clock = clock'
, _window = Just win
}
putMVar mvar app
return mvar
startWithMVar :: AppVar a -> IO ()
startWithMVar mvar = do
app <- takeMVar mvar
uData <- app^.userApp.onStart $ app^.userApp.userData
putMVar mvar $ (app & userApp.userData .~ uData)
iterateWithMVar mvar
-- Iterates stepApp over the state until shouldQuit evaluates false.
iterateWithMVar :: AppVar a
-> IO ()
iterateWithMVar mvar = iterate'
where iterate' = do app <- readMVar mvar
unless (app^.userApp.shouldQuit $ app^.userApp.userData) $
do stepApp mvar
iterate'
renderUserApp :: Window -> UserApp a -> IO ()
renderUserApp win uApp = do
clear [ColorBuffer, DepthBuffer]
uApp^.onRender $ uApp^.userData
swapBuffers win
stepApp :: AppVar a -> IO ()
stepApp mvar = do
app <- readMVar mvar
case _window app of
Just win -> do
t <- getTime
input' <- getInput win $ _userInput app
let clock' = tickClock t $ _clock app
userData' = (app^.userApp.onInput) input' $ app^.userApp.userData
app' = app { _clock = clock'
, _userInput = input'
}
userData'' <- (app^.userApp.onStep) clock' userData'
let app'' = app' & userApp.userData .~ userData''
swapMVar mvar app''
renderUserApp win $ app''^.userApp
when ((app^.userApp.shouldQuit) userData'') $
(app^.userApp.onQuit) userData''
return ()
Nothing -> do putStrLn "Window is nothing, quitting."
app^.userApp.onQuit $ app^.userApp.userData
void shutdown
initGLFW :: String -> IO (Maybe Window)
initGLFW s = do
putStrLn "Initializing the OpenGL window and context."
True <- Graphics.UI.GLFW.init
-- Set our window hints.
setWindowHints
-- Get the prime monitor.
--mMon <- getPrimaryMonitor
-- Create our window.
mWin <- createWindow 800 600 s Nothing Nothing
when (isJust mWin) $
do let Just w = mWin
-- Window will show at upper left corner.
setWindowPos w 0 0
return mWin
setWindowHints :: IO ()
setWindowHints = do
defaultWindowHints
--windowHint $ WindowHint'DepthBits 1
windowHint $ WindowHint'OpenGLProfile OpenGLProfile'Any
shutdown :: IO Bool
shutdown = do
terminate
exitSuccess
| schell/blocks | src/App/App.hs | bsd-3-clause | 4,807 | 0 | 27 | 1,907 | 1,155 | 559 | 596 | -1 | -1 |
-- |
-- Module : Data.Array.Accelerate.CUDA.Array.Sugar
-- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller
-- [2009..2014] Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Trevor L. McDonell <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.CUDA.Array.Sugar (
module Data.Array.Accelerate.Array.Sugar,
newArray, allocateArray, useArray, useArrayAsync,
) where
import Data.Array.Accelerate.CUDA.State
import Data.Array.Accelerate.CUDA.Array.Data
import Data.Array.Accelerate.Array.Sugar hiding (newArray, allocateArray)
import qualified Data.Array.Accelerate.Array.Sugar as Sugar
-- Create an array from its representation function, uploading the result to the
-- device
--
newArray :: (Shape sh, Elt e) => sh -> (sh -> e) -> CIO (Array sh e)
newArray sh f =
let arr = Sugar.newArray sh f
in do
useArray arr
return arr
-- Allocate a new, uninitialised Accelerate array on host and device
--
allocateArray :: (Shape dim, Elt e) => dim -> CIO (Array dim e)
allocateArray sh = do
arr <- fmap Sugar.allocateArray (return sh)
mallocArray arr
return arr
| mikusp/accelerate-cuda | Data/Array/Accelerate/CUDA/Array/Sugar.hs | bsd-3-clause | 1,239 | 0 | 10 | 240 | 255 | 150 | 105 | 18 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Temperature.PT.Rules
( rules ) where
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Temperature.Helpers
import Duckling.Temperature.Types (TemperatureData (..))
import qualified Duckling.Temperature.Types as TTemperature
import Duckling.Types
ruleLatentTempTemp :: Rule
ruleLatentTempTemp = Rule
{ name = "<latent temp> temp"
, pattern =
[ dimension Temperature
, regex "(graus?)|\x00b0"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Degree td
_ -> Nothing
}
ruleTempCelsius :: Rule
ruleTempCelsius = Rule
{ name = "<temp> Celsius"
, pattern =
[ dimension Temperature
, regex "(cent(i|\x00ed)grados?|c(el[cs]?(ius)?)?\\.?)"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Celsius td
_ -> Nothing
}
ruleTempFahrenheit :: Rule
ruleTempFahrenheit = Rule
{ name = "<temp> Fahrenheit"
, pattern =
[ dimension Temperature
, regex "f(ah?reh?n(h?eit)?)?\\.?"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Fahrenheit td
_ -> Nothing
}
ruleLatentTempTempAbaixoDeZero :: Rule
ruleLatentTempTempAbaixoDeZero = Rule
{ name = "<latent temp> temp abaixo de zero"
, pattern =
[ dimension Temperature
, regex "((graus?)|\x00b0)?( abaixo (de)? zero)"
]
, prod = \tokens -> case tokens of
(Token Temperature td@(TemperatureData {TTemperature.value = v}):_) ->
case TTemperature.unit td of
Nothing -> Just . Token Temperature . withUnit TTemperature.Degree $
td {TTemperature.value = - v}
_ -> Just . Token Temperature $ td {TTemperature.value = - v}
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleLatentTempTemp
, ruleLatentTempTempAbaixoDeZero
, ruleTempCelsius
, ruleTempFahrenheit
]
| rfranek/duckling | Duckling/Temperature/PT/Rules.hs | bsd-3-clause | 2,392 | 0 | 18 | 528 | 542 | 306 | 236 | 60 | 3 |
module Main where
import System.Environment (getProgName, getArgs)
import System.Console.GetOpt
import System.Exit
import Control.Monad (when)
import Data.Maybe (listToMaybe)
import Data.List (intercalate)
import DroidSignatureFileFilter
-- | Construct a usage message header.
header :: String -> String
header progName = intercalate "\n"
[ "The DROID Signature File Minimizer - filter a signature file based on"
, "a list of PUIDs and keep only entries for those file formats that you"
, "really need."
, ""
, "Usage: " ++ progName ++ " [options] [signature-file]"
, ""
]
-- | Data type for command line options.
data Options = Options
{ optHelp :: Bool
, optPuids :: [String]
, optPuidsFile :: Maybe FilePath
, optList :: Bool
, optSupertypes :: Bool
, optSubtypes :: Bool
, optOutFile :: Maybe FilePath
} deriving (Show)
-- | Default vaules for command line options.
defaultOptions :: Options
defaultOptions = Options
{ optHelp = False
, optPuids = []
, optPuidsFile = Nothing
, optList = False
, optSupertypes = False
, optSubtypes = False
, optOutFile = Nothing
}
-- | Description of the command line options and how to merge the supplied
-- options with the default values by transforming an Options record.
options :: [OptDescr (Options -> Options)]
options =
[ Option "h" ["help"]
(NoArg (\opts -> opts { optHelp = True }))
"show help message"
, Option "p" ["puid"]
(ReqArg (\p opts -> opts { optPuids = p : optPuids opts }) "PUID")
"include file format with this PUID in the output"
, Option "P" ["puids-from-file"]
(ReqArg (\f opts -> opts { optPuidsFile = Just f }) "FILE")
"like -p, but read list of PUIDs from file (one PUID per line)"
, Option "l" ["list"]
(NoArg (\opts -> opts { optList = True }))
"return a list of PUIDs instead of XML"
, Option "S" ["include-supertypes"]
(NoArg (\opts -> opts { optSupertypes = True }))
"include file formats that are supertypes of the selected formats"
, Option "s" ["include-subtypes"]
(NoArg (\opts -> opts { optSubtypes = True }))
"include file formats that are subtypes of the selected formats"
, Option "o" ["output"]
(ReqArg (\f opts -> opts { optOutFile = Just f }) "FILE")
"output file"
]
-- | Parse command line options.
parseArgs :: String -> [String] -> (Options, Maybe FilePath)
parseArgs hdr argv =
case getOpt Permute options argv of
(os, as, []) -> (foldr id defaultOptions os, listToMaybe as)
(_, _, es) -> error $ concat es ++ usageInfo hdr options
-- | Read from a file or from STDIN if no file is specified.
input :: Maybe FilePath -> IO String
input (Just f) = readFile f
input Nothing = getContents
-- | Read from a file or return an empty string if no file is specified.
input' :: Maybe FilePath -> IO String
input' (Just f) = readFile f
input' Nothing = return ""
-- | Write to a file or to STDOUT if no file is specified.
output :: Maybe FilePath -> String -> IO ()
output (Just f) = writeFile f
output Nothing = putStrLn
-- | Collect PUIDs from command line options -p and -P.
collectPuids :: Options -> IO [String]
collectPuids opts = do
content <- input' $ optPuidsFile opts
return $ optPuids opts ++ lines content
main = do
prg <- getProgName
(opts, sigFile) <- fmap (parseArgs $ header prg) getArgs
when (optHelp opts) $ do
putStr $ usageInfo (header prg) options
exitSuccess
content <- input sigFile
puids <- collectPuids opts
let filterOpts = [WithSupertypes | optSupertypes opts] ++
[WithSubtypes | optSubtypes opts]
output (optOutFile opts) $
(if optList opts then intercalate "\n" . listFileFormats else id) $
filterSigFile filterOpts puids content
| marhop/droidsfmin | src/Main.hs | bsd-3-clause | 3,948 | 0 | 14 | 1,020 | 1,020 | 550 | 470 | 88 | 2 |
module LSC2008.TestMate where
import LazySmallCheck
import Benchmarks.Mate
import System.Environment
instance Serial Kind where
series = cons0 King
\/ cons0 Queen
\/ cons0 Rook
\/ cons0 Bishop
\/ cons0 Knight
\/ cons0 Pawn
instance Serial Colour where
series = cons0 Black \/ cons0 White
instance Serial Board where
series = cons2 Board
bench d = depthCheck (read d) prop_checkmate
| UoYCS-plasma/LazySmallCheck2012 | suite/performance/LSC2008/TestMate.hs | bsd-3-clause | 424 | 0 | 11 | 100 | 128 | 63 | 65 | 16 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Reporting
-- Copyright : (c) David Waern 2008
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Anonymous build report data structure, printing and parsing
--
-----------------------------------------------------------------------------
module Distribution.Client.BuildReports.Anonymous (
BuildReport(..),
InstallOutcome(..),
Outcome(..),
-- * Constructing and writing reports
new,
-- * parsing and pretty printing
parse,
parseList,
show,
-- showList,
) where
import qualified Distribution.Client.Types as BR
( BuildOutcome, BuildFailure(..), BuildResult(..)
, DocsResult(..), TestsResult(..) )
import Distribution.Client.Utils
( mergeBy, MergeResult(..) )
import qualified Paths_cabal_install (version)
import Distribution.Package
( PackageIdentifier(..), PackageName(..) )
import Distribution.PackageDescription
( FlagName(..), FlagAssignment )
--import Distribution.Version
-- ( Version )
import Distribution.System
( OS, Arch )
import Distribution.Compiler
( CompilerId(..) )
import qualified Distribution.Text as Text
( Text(disp, parse) )
import Distribution.ParseUtils
( FieldDescr(..), ParseResult(..), Field(..)
, simpleField, listField, ppFields, readFields
, syntaxError, locatedErrorMsg )
import Distribution.Simple.Utils
( comparing )
import qualified Distribution.Compat.ReadP as Parse
( ReadP, pfail, munch1, skipSpaces )
import qualified Text.PrettyPrint as Disp
( Doc, render, char, text )
import Text.PrettyPrint
( (<+>), (<>) )
import Data.List
( unfoldr, sortBy )
import Data.Char as Char
( isAlpha, isAlphaNum )
import Prelude hiding (show)
data BuildReport
= BuildReport {
-- | The package this build report is about
package :: PackageIdentifier,
-- | The OS and Arch the package was built on
os :: OS,
arch :: Arch,
-- | The Haskell compiler (and hopefully version) used
compiler :: CompilerId,
-- | The uploading client, ie cabal-install-x.y.z
client :: PackageIdentifier,
-- | Which configurations flags we used
flagAssignment :: FlagAssignment,
-- | Which dependent packages we were using exactly
dependencies :: [PackageIdentifier],
-- | Did installing work ok?
installOutcome :: InstallOutcome,
-- Which version of the Cabal library was used to compile the Setup.hs
-- cabalVersion :: Version,
-- Which build tools we were using (with versions)
-- tools :: [PackageIdentifier],
-- | Configure outcome, did configure work ok?
docsOutcome :: Outcome,
-- | Configure outcome, did configure work ok?
testsOutcome :: Outcome
}
data InstallOutcome
= PlanningFailed
| DependencyFailed PackageIdentifier
| DownloadFailed
| UnpackFailed
| SetupFailed
| ConfigureFailed
| BuildFailed
| TestsFailed
| InstallFailed
| InstallOk
deriving Eq
data Outcome = NotTried | Failed | Ok
deriving Eq
new :: OS -> Arch -> CompilerId -> PackageIdentifier -> FlagAssignment
-> [PackageIdentifier] -> BR.BuildOutcome -> BuildReport
new os' arch' comp pkgid flags deps result =
BuildReport {
package = pkgid,
os = os',
arch = arch',
compiler = comp,
client = cabalInstallID,
flagAssignment = flags,
dependencies = deps,
installOutcome = convertInstallOutcome,
-- cabalVersion = undefined
docsOutcome = convertDocsOutcome,
testsOutcome = convertTestsOutcome
}
where
convertInstallOutcome = case result of
Left BR.PlanningFailed -> PlanningFailed
Left (BR.DependentFailed p) -> DependencyFailed p
Left (BR.DownloadFailed _) -> DownloadFailed
Left (BR.UnpackFailed _) -> UnpackFailed
Left (BR.ConfigureFailed _) -> ConfigureFailed
Left (BR.BuildFailed _) -> BuildFailed
Left (BR.TestsFailed _) -> TestsFailed
Left (BR.InstallFailed _) -> InstallFailed
Right (BR.BuildResult _ _ _) -> InstallOk
convertDocsOutcome = case result of
Left _ -> NotTried
Right (BR.BuildResult BR.DocsNotTried _ _) -> NotTried
Right (BR.BuildResult BR.DocsFailed _ _) -> Failed
Right (BR.BuildResult BR.DocsOk _ _) -> Ok
convertTestsOutcome = case result of
Left (BR.TestsFailed _) -> Failed
Left _ -> NotTried
Right (BR.BuildResult _ BR.TestsNotTried _) -> NotTried
Right (BR.BuildResult _ BR.TestsOk _) -> Ok
cabalInstallID :: PackageIdentifier
cabalInstallID =
PackageIdentifier (PackageName "cabal-install") Paths_cabal_install.version
-- ------------------------------------------------------------
-- * External format
-- ------------------------------------------------------------
initialBuildReport :: BuildReport
initialBuildReport = BuildReport {
package = requiredField "package",
os = requiredField "os",
arch = requiredField "arch",
compiler = requiredField "compiler",
client = requiredField "client",
flagAssignment = [],
dependencies = [],
installOutcome = requiredField "install-outcome",
-- cabalVersion = Nothing,
-- tools = [],
docsOutcome = NotTried,
testsOutcome = NotTried
}
where
requiredField fname = error ("required field: " ++ fname)
-- -----------------------------------------------------------------------------
-- Parsing
parse :: String -> Either String BuildReport
parse s = case parseFields s of
ParseFailed perror -> Left msg where (_, msg) = locatedErrorMsg perror
ParseOk _ report -> Right report
parseFields :: String -> ParseResult BuildReport
parseFields input = do
fields <- mapM extractField =<< readFields input
let merged = mergeBy (\desc (_,name,_) -> compare (fieldName desc) name)
sortedFieldDescrs
(sortBy (comparing (\(_,name,_) -> name)) fields)
checkMerged initialBuildReport merged
where
extractField :: Field -> ParseResult (Int, String, String)
extractField (F line name value) = return (line, name, value)
extractField (Section line _ _ _) = syntaxError line "Unrecognized stanza"
extractField (IfBlock line _ _ _) = syntaxError line "Unrecognized stanza"
checkMerged report [] = return report
checkMerged report (merged:remaining) = case merged of
InBoth fieldDescr (line, _name, value) -> do
report' <- fieldSet fieldDescr line value report
checkMerged report' remaining
OnlyInRight (line, name, _) ->
syntaxError line ("Unrecognized field " ++ name)
OnlyInLeft fieldDescr ->
fail ("Missing field " ++ fieldName fieldDescr)
parseList :: String -> [BuildReport]
parseList str =
[ report | Right report <- map parse (split str) ]
where
split :: String -> [String]
split = filter (not . null) . unfoldr chunk . lines
chunk [] = Nothing
chunk ls = case break null ls of
(r, rs) -> Just (unlines r, dropWhile null rs)
-- -----------------------------------------------------------------------------
-- Pretty-printing
show :: BuildReport -> String
show = Disp.render . ppFields fieldDescrs
-- -----------------------------------------------------------------------------
-- Description of the fields, for parsing/printing
fieldDescrs :: [FieldDescr BuildReport]
fieldDescrs =
[ simpleField "package" Text.disp Text.parse
package (\v r -> r { package = v })
, simpleField "os" Text.disp Text.parse
os (\v r -> r { os = v })
, simpleField "arch" Text.disp Text.parse
arch (\v r -> r { arch = v })
, simpleField "compiler" Text.disp Text.parse
compiler (\v r -> r { compiler = v })
, simpleField "client" Text.disp Text.parse
client (\v r -> r { client = v })
, listField "flags" dispFlag parseFlag
flagAssignment (\v r -> r { flagAssignment = v })
, listField "dependencies" Text.disp Text.parse
dependencies (\v r -> r { dependencies = v })
, simpleField "install-outcome" Text.disp Text.parse
installOutcome (\v r -> r { installOutcome = v })
, simpleField "docs-outcome" Text.disp Text.parse
docsOutcome (\v r -> r { docsOutcome = v })
, simpleField "tests-outcome" Text.disp Text.parse
testsOutcome (\v r -> r { testsOutcome = v })
]
sortedFieldDescrs :: [FieldDescr BuildReport]
sortedFieldDescrs = sortBy (comparing fieldName) fieldDescrs
dispFlag :: (FlagName, Bool) -> Disp.Doc
dispFlag (FlagName name, True) = Disp.text name
dispFlag (FlagName name, False) = Disp.char '-' <> Disp.text name
parseFlag :: Parse.ReadP r (FlagName, Bool)
parseFlag = do
name <- Parse.munch1 (\c -> Char.isAlphaNum c || c == '_' || c == '-')
case name of
('-':flag) -> return (FlagName flag, False)
flag -> return (FlagName flag, True)
instance Text.Text InstallOutcome where
disp PlanningFailed = Disp.text "PlanningFailed"
disp (DependencyFailed pkgid) = Disp.text "DependencyFailed" <+> Text.disp pkgid
disp DownloadFailed = Disp.text "DownloadFailed"
disp UnpackFailed = Disp.text "UnpackFailed"
disp SetupFailed = Disp.text "SetupFailed"
disp ConfigureFailed = Disp.text "ConfigureFailed"
disp BuildFailed = Disp.text "BuildFailed"
disp TestsFailed = Disp.text "TestsFailed"
disp InstallFailed = Disp.text "InstallFailed"
disp InstallOk = Disp.text "InstallOk"
parse = do
name <- Parse.munch1 Char.isAlphaNum
case name of
"PlanningFailed" -> return PlanningFailed
"DependencyFailed" -> do Parse.skipSpaces
pkgid <- Text.parse
return (DependencyFailed pkgid)
"DownloadFailed" -> return DownloadFailed
"UnpackFailed" -> return UnpackFailed
"SetupFailed" -> return SetupFailed
"ConfigureFailed" -> return ConfigureFailed
"BuildFailed" -> return BuildFailed
"TestsFailed" -> return TestsFailed
"InstallFailed" -> return InstallFailed
"InstallOk" -> return InstallOk
_ -> Parse.pfail
instance Text.Text Outcome where
disp NotTried = Disp.text "NotTried"
disp Failed = Disp.text "Failed"
disp Ok = Disp.text "Ok"
parse = do
name <- Parse.munch1 Char.isAlpha
case name of
"NotTried" -> return NotTried
"Failed" -> return Failed
"Ok" -> return Ok
_ -> Parse.pfail
| sopvop/cabal | cabal-install/Distribution/Client/BuildReports/Anonymous.hs | bsd-3-clause | 11,508 | 0 | 17 | 3,305 | 2,701 | 1,474 | 1,227 | 222 | 15 |
{-|
Module : Git.DiffTree
Description : Types for the results of @git diff-tree@
Copyright : (c) Michael Klein, 2016
License : BSD3
Maintainer : lambdamichael(at)gmail.com
-}
module Data.Git.DiffTree where
import Git.Types ( DiffMode
, Path
, SHA1(..)
)
-- | The source or destination of an update/change, as shown by @git tree-diff@
data DiffCommit = DiffCommit { diffMode :: DiffMode
, diffSHA1 :: SHA1
, diffPath :: Maybe Path
} deriving (Eq, Ord, Show)
-- | A single @git tree-diff@ result
data DiffTree = DiffTree { src :: DiffCommit
, dst :: DiffCommit
, status :: Status
} deriving (Eq, Ord, Show)
-- | A percentage
newtype Percent = Percent Int deriving (Eq, Ord)
-- | Show a percentage with the @%@ sign
instance Show Percent where
show (Percent p) = show p ++ "%"
-- | The `Status` of a diff, as shown by @git tree-diff@
data Status = Addition
| Copy Percent
| Delete
| Modify (Maybe Percent)
| Rename Percent
| TypeChange
| Unmerged
| Unknown deriving (Eq, Ord, Show)
| michaeljklein/git-details | src/Data/Git/DiffTree.hs | bsd-3-clause | 1,406 | 0 | 9 | 600 | 223 | 132 | 91 | 23 | 0 |
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad.IO.Class (liftIO)
import Servant (Proxy(..), (:<|>)(..))
import Servant.Crud (API, DeleteFile, GetFile, PutFile)
import Servant.Server (Server, serve)
import Turtle (argInt, options)
import qualified Data.Text.IO as Text
import qualified Network.Wai.Handler.Warp as Warp
import qualified System.Directory as Directory
-- | Handler for the `PutFile` endpoint
putFile :: Server PutFile
putFile file contents = liftIO (Text.writeFile file contents)
-- | Handler for the `GetFile` endpoint
getFile :: Server GetFile
getFile file = liftIO (Text.readFile file)
-- | Handler for the `DeleteFile` endpoint
deleteFile :: Server DeleteFile
deleteFile file = liftIO (Directory.removeFile file)
-- | Handler for the entire REST `API`
server :: Server API
server = putFile
:<|> getFile
:<|> deleteFile
-- | Serve the `API` on port 8080
main :: IO ()
main = do
port <- options "CRUD server" (argInt "port" "The port to listen on")
Warp.run port (serve (Proxy :: Proxy API) server)
| Gabriel439/servant-crud | exec/Server.hs | bsd-3-clause | 1,066 | 0 | 11 | 190 | 278 | 159 | 119 | 23 | 1 |
module Action.Issue ( parseIssueFromDoc
, createNewIssue
, NewIssue(..)
)where
import Action.Internal.Issue (createNewIssue, parseIssueFromDoc)
import Github.Issues (NewIssue (..))
| smurphy8/issue-add | src/Action/Issue.hs | bsd-3-clause | 271 | 0 | 6 | 107 | 49 | 32 | 17 | 5 | 0 |
{-# LANGUAGE DeriveDataTypeable, MultiParamTypeClasses, FlexibleInstances, TypeSynonymInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Decoration
-- Copyright : (c) 2010 Audun Skaugen
-- License : BSD-style (see xmonad/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : unportable
--
-- Hooks for sending messages about fullscreen windows to layouts, and
-- a few example layout modifier that implement fullscreen windows.
-----------------------------------------------------------------------------
module XMonad.Layout.Fullscreen
( -- * Usage:
-- $usage
fullscreenFull
,fullscreenFocus
,fullscreenFullRect
,fullscreenFocusRect
,fullscreenFloat
,fullscreenFloatRect
,fullscreenEventHook
,fullscreenManageHook
,fullscreenManageHookWith
,FullscreenMessage(..)
-- * Types for reference
,FullscreenFloat, FullscreenFocus, FullscreenFull
) where
import XMonad
import XMonad.Layout.LayoutModifier
import XMonad.Util.WindowProperties
import XMonad.Hooks.ManageHelpers (isFullscreen)
import qualified XMonad.StackSet as W
import Data.List
import Data.Maybe
import Data.Monoid
import qualified Data.Map as M
import Control.Monad
import Control.Arrow (second)
-- $usage
-- Provides a ManageHook and an EventHook that sends layout messages
-- with information about fullscreening windows. This allows layouts
-- to make their own decisions about what they should to with a
-- window that requests fullscreen.
--
-- The module also includes a few layout modifiers as an illustration
-- of how such layouts should behave.
--
-- To use this module, add 'fullscreenEventHook' and 'fullscreenManageHook'
-- to your config, i.e.
--
-- > xmonad defaultconfig { handleEventHook = fullscreenEventHook,
-- > manageHook = fullscreenManageHook,
-- > layoutHook = myLayouts }
--
-- Now you can use layouts that respect fullscreen, for example the
-- provided 'fullscreenFull':
--
-- > myLayouts = fullscreenFull someLayout
--
-- | Messages that control the fullscreen state of the window.
-- AddFullscreen and RemoveFullscreen are sent to all layouts
-- when a window wants or no longer wants to be fullscreen.
-- FullscreenChanged is sent to the current layout after one
-- of the above have been sent.
data FullscreenMessage = AddFullscreen Window
| RemoveFullscreen Window
| FullscreenChanged
deriving (Typeable)
instance Message FullscreenMessage
data FullscreenFull a = FullscreenFull W.RationalRect [a]
deriving (Read, Show)
data FullscreenFocus a = FullscreenFocus W.RationalRect [a]
deriving (Read, Show)
data FullscreenFloat a = FullscreenFloat W.RationalRect (M.Map a (W.RationalRect, Bool))
deriving (Read, Show)
instance LayoutModifier FullscreenFull Window where
pureMess ff@(FullscreenFull frect fulls) m = case fromMessage m of
Just (AddFullscreen win) -> Just $ FullscreenFull frect $ nub $ win:fulls
Just (RemoveFullscreen win) -> Just $ FullscreenFull frect $ delete win $ fulls
Just FullscreenChanged -> Just ff
_ -> Nothing
pureModifier (FullscreenFull frect fulls) rect _ list =
(map (flip (,) rect') visfulls ++ rest, Nothing)
where visfulls = intersect fulls $ map fst list
rest = filter (flip notElem visfulls . fst) list
rect' = scaleRationalRect rect frect
instance LayoutModifier FullscreenFocus Window where
pureMess ff@(FullscreenFocus frect fulls) m = case fromMessage m of
Just (AddFullscreen win) -> Just $ FullscreenFocus frect $ nub $ win:fulls
Just (RemoveFullscreen win) -> Just $ FullscreenFocus frect $ delete win $ fulls
Just FullscreenChanged -> Just ff
_ -> Nothing
pureModifier (FullscreenFocus frect fulls) rect (Just (W.Stack {W.focus = f})) list
| f `elem` fulls = ((f, rect') : rest, Nothing)
| otherwise = (list, Nothing)
where rest = filter ((/= f) . fst) list
rect' = scaleRationalRect rect frect
pureModifier _ _ Nothing list = (list, Nothing)
instance LayoutModifier FullscreenFloat Window where
handleMess (FullscreenFloat frect fulls) m = case fromMessage m of
Just (AddFullscreen win) -> do
mrect <- (M.lookup win . W.floating) `fmap` gets windowset
return $ case mrect of
Just rect -> Just $ FullscreenFloat frect $ M.insert win (rect,True) fulls
Nothing -> Nothing
Just (RemoveFullscreen win) ->
return $ Just $ FullscreenFloat frect $ M.adjust (second $ const False) win fulls
-- Modify the floating member of the stack set directly; this is the hackish part.
Just FullscreenChanged -> do
state <- get
let ws = windowset state
flt = W.floating ws
flt' = M.intersectionWith doFull fulls flt
put state {windowset = ws {W.floating = M.union flt' flt}}
return $ Just $ FullscreenFloat frect $ M.filter snd fulls
where doFull (_, True) _ = frect
doFull (rect, False) _ = rect
Nothing -> return Nothing
-- | Layout modifier that makes fullscreened window fill the
-- entire screen.
fullscreenFull :: LayoutClass l a =>
l a -> ModifiedLayout FullscreenFull l a
fullscreenFull = fullscreenFullRect $ W.RationalRect 0 0 1 1
-- | As above, but the fullscreened window will fill the
-- specified rectangle instead of the entire screen.
fullscreenFullRect :: LayoutClass l a =>
W.RationalRect -> l a -> ModifiedLayout FullscreenFull l a
fullscreenFullRect r = ModifiedLayout $ FullscreenFull r []
-- | Layout modifier that makes the fullscreened window fill
-- the entire screen only if it is currently focused.
fullscreenFocus :: LayoutClass l a =>
l a -> ModifiedLayout FullscreenFocus l a
fullscreenFocus = fullscreenFocusRect $ W.RationalRect 0 0 1 1
-- | As above, but the fullscreened window will fill the
-- specified rectangle instead of the entire screen.
fullscreenFocusRect :: LayoutClass l a =>
W.RationalRect -> l a -> ModifiedLayout FullscreenFocus l a
fullscreenFocusRect r = ModifiedLayout $ FullscreenFocus r []
-- | Hackish layout modifier that makes floating fullscreened
-- windows fill the entire screen.
fullscreenFloat :: LayoutClass l a =>
l a -> ModifiedLayout FullscreenFloat l a
fullscreenFloat = fullscreenFloatRect $ W.RationalRect 0 0 1 1
-- | As above, but the fullscreened window will fill the
-- specified rectangle instead of the entire screen.
fullscreenFloatRect :: LayoutClass l a =>
W.RationalRect -> l a -> ModifiedLayout FullscreenFloat l a
fullscreenFloatRect r = ModifiedLayout $ FullscreenFloat r M.empty
-- | The event hook required for the layout modifiers to work
fullscreenEventHook :: Event -> X All
fullscreenEventHook (ClientMessageEvent _ _ _ dpy win typ (action:dats)) = do
state <- getAtom "_NET_WM_STATE"
fullsc <- getAtom "_NET_WM_STATE_FULLSCREEN"
wstate <- fromMaybe [] `fmap` getProp32 state win
let fi :: (Integral i, Num n) => i -> n
fi = fromIntegral
isFull = fi fullsc `elem` wstate
remove = 0
add = 1
toggle = 2
ptype = 4
chWState f = io $ changeProperty32 dpy win state ptype propModeReplace (f wstate)
when (typ == state && fi fullsc `elem` dats) $ do
when (action == add || (action == toggle && not isFull)) $ do
chWState (fi fullsc:)
broadcastMessage $ AddFullscreen win
sendMessage FullscreenChanged
when (action == remove || (action == toggle && isFull)) $ do
chWState $ delete (fi fullsc)
broadcastMessage $ RemoveFullscreen win
sendMessage FullscreenChanged
return $ All True
fullscreenEventHook (DestroyWindowEvent {ev_window = w}) = do
-- When a window is destroyed, the layouts should remove that window
-- from their states.
broadcastMessage $ RemoveFullscreen w
cw <- (W.workspace . W.current) `fmap` gets windowset
sendMessageWithNoRefresh FullscreenChanged cw
return $ All True
fullscreenEventHook _ = return $ All True
-- | Manage hook that sets the fullscreen property for
-- windows that are initially fullscreen
fullscreenManageHook :: ManageHook
fullscreenManageHook = fullscreenManageHook' isFullscreen
-- | A version of fullscreenManageHook that lets you specify
-- your own query to decide whether a window should be fullscreen.
fullscreenManageHookWith :: Query Bool -> ManageHook
fullscreenManageHookWith h = fullscreenManageHook' $ isFullscreen <||> h
fullscreenManageHook' :: Query Bool -> ManageHook
fullscreenManageHook' isFull = isFull --> do
w <- ask
liftX $ do
broadcastMessage $ AddFullscreen w
cw <- (W.workspace . W.current) `fmap` gets windowset
sendMessageWithNoRefresh FullscreenChanged cw
idHook
| reenberg/XMonadContrib | XMonad/Layout/Fullscreen.hs | bsd-3-clause | 8,814 | 0 | 17 | 1,771 | 2,008 | 1,040 | 968 | 137 | 1 |
{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}
module B.Shake.Rerun(
defaultRuleRerun, alwaysRerun
) where
import B.Shake.Core
import B.Shake.Classes
newtype AlwaysRerunQ = AlwaysRerunQ ()
deriving (Typeable,Eq,Hashable,Binary,NFData)
instance Show AlwaysRerunQ where show _ = "AlwaysRerunQ"
newtype AlwaysRerunA = AlwaysRerunA ()
deriving (Typeable,Hashable,Binary,NFData)
instance Show AlwaysRerunA where show _ = "AlwaysRerunA"
instance Eq AlwaysRerunA where a == b = False
instance Rule AlwaysRerunQ AlwaysRerunA where
storedValue _ = return Nothing
-- | Always rerun the associated action. Useful for defining rules that query
-- the environment. For example:
--
-- @
-- \"ghcVersion.txt\" 'Development.Shake.*>' \\out -> do
-- 'alwaysRerun'
-- (stdout,_) <- 'Development.Shake.systemOutput' \"ghc\" [\"--version\"]
-- 'Development.Shake.writeFileChanged' out stdout
-- @
alwaysRerun :: Action ()
alwaysRerun = do AlwaysRerunA _ <- apply1 $ AlwaysRerunQ (); return ()
defaultRuleRerun :: Rules ()
defaultRuleRerun = defaultRule $ \AlwaysRerunQ{} -> Just $ return $ AlwaysRerunA()
| strager/b-shake | B/Shake/Rerun.hs | bsd-3-clause | 1,189 | 0 | 10 | 181 | 255 | 138 | 117 | 18 | 1 |
import Network.OpenID
import MonadLib
import Network.Socket
import System.Environment
import OpenSSL
main = withSocketsDo $ withOpenSSL $ do
[ident,check] <- getArgs
case normalizeIdentifier (Identifier ident) of
Nothing -> putStrLn "Unable to normalize identifier"
Just i -> do
let resolve = makeRequest True
rpi <- discover resolve i
case rpi of
Left err -> putStrLn $ "discover: " ++ show err
Right (p,i) -> do
putStrLn ("found provider: " ++ show p)
putStrLn ("found identity: " ++ show i)
eam <- associate emptyAssociationMap True resolve p
case eam of
Left err -> putStrLn $ "associate: " ++ show err
Right am -> do
let au = authenticationURI am Setup p i check Nothing Nothing
print au
line <- getLine
let params = parseParams line
print =<< verifyAuthentication am params check resolve
| elliottt/hsopenid | examples/test.hs | bsd-3-clause | 981 | 0 | 26 | 316 | 297 | 137 | 160 | 26 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module HStyle.Rules.LineLength.Tests
( tests
) where
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion)
import qualified Data.Text as T
import HStyle.Rule
import HStyle.Rules.LineLength
import HStyle.Tests.Util
-- | Instantiation for 78 characters
lineLengthRule' :: Rule
lineLengthRule' = lineLengthRule 78
tests :: Test
tests = testGroup "HStyle.Rules.LineLength.Tests"
[ testCase "lineLength_01" lineLength_01
, testCase "lineLength_02" lineLength_02
]
lineLength_01 :: Assertion
lineLength_01 = testRuleAccept lineLengthRule' $ T.replicate 78 "-"
lineLength_02 :: Assertion
lineLength_02 = testRuleReject lineLengthRule' $ T.replicate 79 "-"
| jaspervdj/hstyle | tests/HStyle/Rules/LineLength/Tests.hs | bsd-3-clause | 775 | 0 | 7 | 108 | 167 | 97 | 70 | 20 | 1 |
Subsets and Splits