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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
import XMonad
import Data.Default (def)
import Data.List (isPrefixOf)
import Data.Monoid (All, mempty)
import Data.Map (Map, fromList)
import System.Environment (lookupEnv)
import System.Exit (exitSuccess)
import System.Process (CmdSpec (RawCommand))
import XMonad.Actions.CycleWS (WSType(AnyWS))
import XMonad.Actions.CopyWindow (copy)
import XMonad.Actions.DynamicWorkspaces (addWorkspacePrompt
,removeEmptyWorkspace
,withWorkspace
,selectWorkspace
,toNthWorkspace)
import XMonad.Actions.DynamicWorkspaceOrder (moveTo
,shiftTo
,withNthWorkspace
,swapWith
,getSortByOrder
)
import XMonad.Actions.GridSelect (goToSelected)
import XMonad.Actions.Navigation2D (Navigation2D
,Direction2D
,lineNavigation
,centerNavigation
,fullScreenRect
,singleWindowRect
,switchLayer
,windowGo
,windowSwap
,windowToScreen
,screenGo
,screenSwap
)
import XMonad.Actions.TagWindows (addTag, tagDelPrompt, tagPrompt)
import XMonad.Actions.CycleWS (toggleWS)
import XMonad.Actions.WindowGo (runOrRaiseNext, raiseNextMaybe)
import XMonad.Actions.WorkspaceNames (renameWorkspace)
import XMonad.Hooks.EwmhDesktops (ewmh, ewmhDesktopsEventHook)
import XMonad.Hooks.ManageHelpers (isFullscreen
,doFullFloat
,composeOne,
(-?>)
)
import XMonad.Hooks.ManageDocks (Direction2D(L, R, U, D)
,ToggleStruts(..)
,manageDocks
,avoidStruts
)
import XMonad.Hooks.DynamicLog (PP
,dynamicLogString
,dynamicLogWithPP
,pad
,ppTitle
,ppLayout
,ppCurrent
,ppVisible
,ppHidden
,ppHiddenNoWindows
,ppUrgent
,ppSep
,ppOutput
,ppWsSep
,ppExtras
,wrap
,shorten
,xmobarColor
,ppSort
)
import XMonad.Layout.Decoration (Theme (..), DefaultShrinker(..))
import XMonad.Layout.NoBorders (smartBorders)
import XMonad.Layout.Groups.Helpers (moveToGroupUp
,moveToGroupDown
,swapUp
,swapDown
,swapMaster
,focusGroupUp
,focusGroupDown
,focusUp
,focusDown
)
import XMonad.Layout.Tabbed (Shrinker(..), addTabs)
import XMonad.Layout.Simplest (Simplest(..))
import XMonad.Layout.Groups (group)
import XMonad.Layout.Groups.Examples (TiledTabsConfig(..)
,tallTabs
,rowOfColumns, shrinkMasterGroups
,expandMasterGroups
,increaseNMasterGroups
,decreaseNMasterGroups
,shrinkText
)
import XMonad.Layout.Named (named)
import XMonad.Layout.Renamed (renamed, Rename(..))
import XMonad.Layout.LayoutHints (layoutHints)
import XMonad.Prompt (XPConfig (..)
,XPPosition(Bottom)
,font
,bgColor
,defaultXPKeymap
,fgColor
,fgHLight
,bgHLight
,borderColor
,promptBorderWidth
,promptKeymap
,completionKey
,changeModeKey
,position
,height
,historySize
,historyFilter
,defaultText
,autoComplete
,showCompletionOnTab
,searchPredicate
,alwaysHighlight
)
import XMonad.Prompt.Shell (shellPrompt)
import XMonad.Prompt.Window (windowPromptGoto)
import XMonad.Prompt.Pass (passPrompt)
import XMonad.StackSet (shiftMaster
,focusMaster
,sink
,greedyView
,shift
,view
,RationalRect(..)
)
import XMonad.Util.EZConfig (mkKeymap, checkKeymap, additionalKeys)
import XMonad.Util.Types (Direction1D(Next, Prev))
import XMonad.Util.Run (hPutStrLn, spawnPipe)
import XMonad.Util.Loggers (Logger
,logCmd
,loadAvg
,date
,battery)
colorBackground :: String
colorBackground = "#151515"
colorCurrentLine :: String
colorCurrentLine = "#B8D6AC"
colorSelection :: String
colorSelection = "#404040"
colorForeground :: String
colorForeground = "#D7D0C7"
colorComment :: String
colorComment = "#dddddd"
colorRed :: String
colorRed = "#E84F4F"
colorOrange :: String
colorOrange = "#F39D21"
colorYellow :: String
colorYellow = "#E1AA5D"
colorGreen :: String
colorGreen = "#B8D6AC"
colorAqua :: String
colorAqua = "#4E9FB1"
colorBlue :: String
colorBlue = "#7DC1CF"
colorPurple :: String
colorPurple = "#9B64FB"
myFocusFollowsMouse :: Bool
myFocusFollowsMouse = False
myBorderWidth = 1
myWorkspaces :: [String]
myWorkspaces = map show $ [1..9] ++ [0]
myModMask :: KeyMask
myModMask = mod4Mask
myNormalBorderColor :: String
myNormalBorderColor = colorBackground
myFocusedBorderColor :: String
myFocusedBorderColor = colorSelection
terminus :: String
terminus = "-*-terminus-medium-r-*-*-12-120-*-*-*-*-iso8859-*"
shiftLayout :: X ()
shiftLayout = sendMessage NextLayout
myTerm :: String
myTerm = "urxvtc"
myKeymap =
[ ("M-S-r", renameWorkspace myXPConfig)
, ("M-<Return>", spawn myTerm)
, ("M-S-c", kill)
, ("M-<Space>", shiftLayout)
, ("M-h", windowGo L False)
, ("M-j", focusGroupDown)
, ("M-k", focusGroupUp)
, ("M-l", windowGo R False)
, ("M-<Tab>", focusDown)
, ("M-`", raiseNextMaybe (return ()) (className =? "emacs"))
, ("M-S-`", spawn "~/bin/emc")
, ("M-S-<Tab>", focusUp)
, ("M-S-h", moveToGroupUp False)
, ("M-S-j", focusDown)
, ("M-S-k", focusUp)
, ("M-S-l", moveToGroupDown False)
, ("M-C-h", shrinkMasterGroups)
, ("M-C-j", increaseNMasterGroups)
, ("M-C-k", decreaseNMasterGroups)
, ("M-C-l", expandMasterGroups)
, ("M-s", goToSelected def)
, ("M-f", withFocused $ windows . sink)
, ("M-,", sendMessage (IncMasterN 1))
, ("M-.", sendMessage (IncMasterN (-1)))
, ("M-b", sendMessage ToggleStruts)
, ("M-C-q", io exitSuccess)
, ("M-i", runOrRaiseNext "firefox" (className =? "Firefox"))
, ("M-t", spawn "~/bin/tmux-urxvt")
, ("M-o", toggleWS)
, ("M-p", shellPrompt myXPConfig)
, ("M-/", windowPromptGoto myXPConfig {autoComplete = Just 500000})
, ("M-m", tagPrompt myXPConfig $ withFocused . addTag)
, ("M-S m", tagDelPrompt myXPConfig)
, ("M-v", selectWorkspace myXPConfig)
, ("M-C-m", withWorkspace myXPConfig (windows . copy))
, ("M-S-<Backspace>", removeEmptyWorkspace)
, ("M-S-a", addWorkspacePrompt myXPConfig)
, ("M-S-p", passPrompt myXPConfig)
, ("M-<R>", moveTo Next AnyWS)
, ("M-<L>", moveTo Prev AnyWS)
, ("M-S-<R>", swapWith Next AnyWS)
, ("M-S-<L>", swapWith Prev AnyWS)
]
myMouseBindings :: XConfig t -> Map (KeyMask, Button) (Window -> X ())
myMouseBindings (XConfig {XMonad.modMask = modm}) = fromList
-- mod-button1, Set the window to floating mode and move by dragging
[ ((modm, button1), \w -> focus w >> mouseMoveWindow w
>> windows shiftMaster)
-- mod-button2, Raise the window to the top of the stack
, ((modm, button2), \w -> focus w >> windows shiftMaster)
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modm, button3), \w -> focus w >> mouseResizeWindow w
>> windows shiftMaster)
]
myTheme :: Theme
myTheme = def { activeColor = colorSelection
, inactiveColor = colorBackground
, urgentColor = colorRed
, activeBorderColor = colorSelection
, inactiveBorderColor = colorBackground
, urgentBorderColor = colorBackground
, activeTextColor = colorGreen
, inactiveTextColor = colorComment
, urgentTextColor = "#FF0000"
, fontName = terminus
, decoWidth = 200
, decoHeight = 16
, windowTitleAddons = []
, windowTitleIcons = []
}
myLayout = avoidStruts $
tallTabs (TTC 1 0.5 (3/100) 1 0.5 (3/100) shrinkText myTheme)
||| smartBorders tiled
where
-- default tiling algorithm partitions the screen into two panes
tiled = Tall nmaster delta ratio
-- The default number of windows in the master pane
nmaster = 1
-- Default proportion of screen occupied by master pane
ratio = 3/5
-- Percent of screen to increment by when resizing panes
delta = 3/100
myManageHook :: ManageHook
myManageHook = manageDocks
<+> composeAll
[ className =? "MPlayer" --> doFloat
, className =? "Gimp" --> doFloat
, stringProperty "WM_NAME" =? "Firefox Preferences" --> doFloat
-- Float Firefox dialog windows
, (className =? "Firefox" <&&> resource =? "Dialog") --> doFloat
, resource =? "desktop_window" --> doIgnore
]
<+>
composeOne [isFullscreen -?> doFullFloat]
myEventHook :: Event -> X All
myEventHook = ewmhDesktopsEventHook
myLogHook :: X ()
myLogHook = return ()
myStartupHook :: X ()
myStartupHook = return ()
myXPConfig :: XPConfig
myXPConfig = XPC {
XMonad.Prompt.font = terminus
, bgColor = colorBackground
, fgColor = colorForeground
, fgHLight = colorForeground
, bgHLight = colorSelection
, borderColor = colorComment
, promptBorderWidth = 0
, promptKeymap = defaultXPKeymap
, completionKey = xK_Tab
, changeModeKey = xK_grave
, maxComplRows = Just 10
, position = Bottom
, height = 16
, historySize = 256
, historyFilter = id
, defaultText = []
, autoComplete = Nothing
, showCompletionOnTab = False
, searchPredicate = isPrefixOf
, alwaysHighlight = True
}
-- | Some nice xmobar defaults.
mybarPP :: PP
mybarPP = def { ppCurrent = xmobarColor colorBackground colorGreen . wrap "[" "]"
, ppTitle = xmobarColor colorGreen colorSelection . shorten 100
, ppHidden = xmobarColor colorBlue colorSelection
, ppHiddenNoWindows = xmobarColor colorAqua colorSelection
, ppSort = getSortByOrder
, ppUrgent = xmobarColor colorRed colorYellow
}
myExtraKeys =
-- mod-[1..9] %! Switch to workspace N
-- mod-shift-[1..9] %! Move client to workspace N
zip (zip (repeat myModMask) myWorkspaceKeys)
(map (withNthWorkspace greedyView) [0..])
++
zip (zip (repeat (myModMask .|. shiftMask)) myWorkspaceKeys)
(map (withNthWorkspace shift) [0..])
++
--
-- mod-{w,e}, Switch to screen 1 or 2
-- mod-shift-{w,e}, Move client to screen 1 or 2
--
[((m .|. myModMask, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e] [0..]
, (f, m) <- [(view, 0), (shift, shiftMask)]]
where myWorkspaceKeys = [xK_1, xK_2, xK_3, xK_4, xK_5,
xK_6, xK_7, xK_8, xK_9, xK_0]
myConfig = def {
focusFollowsMouse = myFocusFollowsMouse,
borderWidth = myBorderWidth,
modMask = myModMask,
workspaces = myWorkspaces,
normalBorderColor = myNormalBorderColor,
focusedBorderColor = myFocusedBorderColor,
keys = \c -> mkKeymap c myKeymap,
mouseBindings = myMouseBindings,
layoutHook = myLayout,
manageHook = myManageHook,
handleEventHook = myEventHook,
startupHook = return () >> checkKeymap myConfig myKeymap
} `additionalKeys` myExtraKeys
main :: IO ()
main = do
h <- spawnPipe "/home/nathan/.xmonad/xmobar/dist/build/xmobar/xmobar"
xmonad $ ewmh myConfig {
logHook = dynamicLogWithPP mybarPP { ppOutput = hPutStrLn h }
}
| nathantypanski/my-xmonad | my-xmonad.hs | bsd-3-clause | 14,363 | 0 | 14 | 5,808 | 2,744 | 1,656 | 1,088 | 318 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module ReadmeGen.Views.Index where
import Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes as A
import Text.Blaze.Html.Renderer.Text
import Data.Monoid ((<>))
render items isSearch =
H.html $ do
H.head $ do
H.title "Readme Generator"
H.link ! A.rel "stylesheet" ! A.type_ "text/css" ! A.href "/readmegen.css"
H.body $ do
H.h2 ! A.class_ "header" $ "Readme Generator"
H.form ! A.class_ "form" ! A.method "get" ! A.action "/search" $ do
H.input ! A.required "required" ! A.maxlength "60" !
A.placeholder "e.g 23456" ! A.name "bug"
H.input ! A.class_ "btn" ! A.type_ "submit" ! A.value "Find"
H.div ! A.class_ "container" $ do
H.a ! A.class_ "btn" ! A.href "/readme/new" $ "New Readme"
indexLink
H.table ! A.class_ "table" $ mapM_ renderLn items
where renderLn (id, bug, title) = H.tr $ do
H.td $ H.a ! A.href ("/readme/" <> H.stringValue (show id)) $
H.toHtml ("#" ++ bug)
H.td $ H.a ! A.href ("/readme/" <> H.stringValue (show id)) $
H.toHtml (title)
indexLink = if isSearch
then H.a ! A.class_ "btn" ! A.href "/readme" $ "Back"
else ""
| kmerz/readmegen | src/ReadmeGen/Views/Index.hs | bsd-3-clause | 1,233 | 2 | 22 | 321 | 484 | 237 | 247 | 29 | 2 |
{-# OPTIONS_GHC -fno-warn-tabs #-}
module Word24
( Word24
, toWord24
) where
import Common
import Data.Bits
import Data.Word
import GHC.Enum
newtype Word24 = Word24 { toWord32 :: Word32 } deriving (Eq, Ord)
toWord24 :: Integral a => a -> Word24
toWord24 i = Word24 $ fromIntegral i .&. 0xffffff
instance Bounded Word24 where
minBound = 0
maxBound = 0xffffff
instance Enum Word24 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word24"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word24"
toEnum i
| i >= 0 && i <= fromIntegral (maxBound::Word24)
= toWord24 i
| otherwise = toEnumError "Word24" i (minBound::Word24, maxBound::Word24)
fromEnum = fromEnum . toWord32
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word24 where
quot x y = toWord24 $ quot (toWord32 x) (toWord32 y)
rem x y = toWord24 $ rem (toWord32 x) (toWord32 y)
div x y = toWord24 $ div (toWord32 x) (toWord32 y)
mod x y = toWord24 $ mod (toWord32 x) (toWord32 y)
quotRem x y = (quot x y, rem x y)
divMod x y = (div x y, mod x y)
toInteger x = toInteger $ toWord32 x
instance Num Word24 where
(+) x y = toWord24 $ (+) (toWord32 x) (toWord32 y)
(-) x y = toWord24 $ (-) (toWord32 x) (toWord32 y)
(*) x y = toWord24 $ (*) (toWord32 x) (toWord32 y)
negate x = toWord24 $ negate (toWord32 x)
abs x = toWord24 $ abs (toWord32 x)
signum x = toWord24 $ signum (toWord32 x)
fromInteger i = toWord24 i
instance Read Word24 where
readsPrec p s = map (mapFst toWord24) $ readsPrec p s
instance Real Word24 where
toRational x = toRational (toWord32 x)
instance Show Word24 where
showsPrec p x = showsPrec p $ toWord24 x
instance FiniteBits Word24 where
finiteBitSize _ = 24
countLeadingZeros x = countLeadingZeros (toWord32 x) - 8
countTrailingZeros x = countTrailingZeros $ toWord32 x
instance Bits Word24 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(.&.) x y = toWord24 $ (.&.) (toWord32 x) (toWord32 y)
(.|.) x y = toWord24 $ (.|.) (toWord32 x) (toWord32 y)
xor x y = toWord24 $ xor (toWord32 x) (toWord32 y)
complement x = toWord24 $ complement (toWord32 x)
shiftL x i = toWord24 $ shiftL (toWord32 x) i
shiftR x i = toWord24 $ shiftR (toWord32 x) i
rotate x i = toWord24 $ rotate (toWord32 x) i
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount = popCount . toWord32
bit = bitDefault
testBit = testBitDefault
| andrewcchen/matasano-cryptopals-solutions | modules/Word24.hs | bsd-3-clause | 2,713 | 47 | 15 | 757 | 1,095 | 553 | 542 | 71 | 1 |
-- | Debug FRP networks by inspecting their behaviour inside.
module FRP.Yampa.Debug where
import Debug.Trace
import FRP.Yampa
import System.IO.Unsafe
-- | Signal Function that prints the value passing through using 'trace'.
traceSF :: Show a => SF a a
traceSF = traceSFWith show
-- | Signal Function that prints the value passing through using 'trace',
-- and a customizable 'show' function.
traceSFWith :: (a -> String) -> SF a a
traceSFWith f = arr (\x -> trace (f x) x)
-- | Execute an IO action using 'unsafePerformIO' at every step, and ignore the
-- result.
traceSFWithIO :: (a -> IO b) -> SF a a
traceSFWithIO f = arr (\x -> (unsafePerformIO (f x >> return x)))
| ivanperez-keera/Yampa | yampa-test/src/FRP/Yampa/Debug.hs | bsd-3-clause | 674 | 0 | 12 | 122 | 167 | 90 | 77 | 10 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Scripts.FCCForm471Common where
import ClassyPrelude
import qualified Data.Csv as Csv
newtype Form471Num = Form471Num Int
deriving (Show, Eq, Num)
instance Csv.FromField Form471Num where
parseField bs = Form471Num <$> Csv.parseField bs
| limaner2002/EPC-tools | USACScripts/src/Scripts/FCCForm471Common.hs | bsd-3-clause | 364 | 0 | 8 | 50 | 70 | 41 | 29 | 10 | 0 |
module PolyGraph.Buildable.Graph (
(@+~~@)
, (^+~~^)
, toSimpleGraph
) where
import PolyGraph.Common (UOPair(..), toPair)
import PolyGraph.Buildable
import qualified PolyGraph.ReadOnly as Base
import PolyGraph.ReadOnly.Graph (EdgeSemantics (..))
import Data.List (nub)
import Data.Foldable (toList)
(@+~~@) :: forall g v e t . (BuildableEdgeSemantics e v, EdgeSemantics e v, BuildableGraphDataSet g v e t) => v -> v -> g -> g
(@+~~@) = addDefaultEdge
(^+~~^) :: forall g v e t . (PrettyRead v, BuildableEdgeSemantics e v, EdgeSemantics e v, BuildableGraphDataSet g v e t) => String -> String -> g -> g
(^+~~^) s1 s2 g = let v1 = fromString s1 :: v
v2 = fromString s2 :: v
in addDefaultEdge v1 v2 g
toSimpleGraph :: forall g v e t . (EdgeSemantics e v, BuildableGraphDataSet g v e t ) => g -> g
toSimpleGraph g =
let toEdgeHelper :: e -> EdgeHelper e v
toEdgeHelper e = EdgeHelper (resolveEdge e) e
notALoop :: EdgeHelper e v -> Bool
notALoop eh = let UOPair(v1,v2) = vPair eh in v1 /= v2
withoutIsolatedVerts = fromEdgeList . map(edge) . (filter notALoop) . nub . map(toEdgeHelper) . toList . Base.edges $ g
in withoutIsolatedVerts ++@ (toList . Base.isolatedVertices $ g)
data EdgeHelper e v= EdgeHelper {
vPair:: UOPair v,
edge :: e
}
instance Eq v => Eq(EdgeHelper e v) where
nh1 == nh2 = vPair nh1 == vPair nh2
| rpeszek/GraphPlay | src/PolyGraph/Buildable/Graph.hs | bsd-3-clause | 1,504 | 0 | 17 | 416 | 542 | 298 | 244 | -1 | -1 |
--------------------------------------------------------------------------------
module Language.Haskell.Stylish.Parse.Tests
( tests
) where
--------------------------------------------------------------------------------
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, assert)
--------------------------------------------------------------------------------
import Language.Haskell.Stylish.Parse
--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "Language.Haskell.Stylish.Parse"
[ testCase "UTF-8 Byte Order Mark" testBom
, testCase "Extra extensions" testExtraExtensions
, testCase "Multiline CPP" testMultilineCpp
, testCase "Haskell2010 extension" testHaskell2010
, testCase "Shebang" testShebang
]
--------------------------------------------------------------------------------
testBom :: Assertion
testBom = assert $ isRight $ parseModule [] Nothing input
where
input = unlines
[ '\xfeff' : "foo :: Int"
, "foo = 3"
]
--------------------------------------------------------------------------------
testExtraExtensions :: Assertion
testExtraExtensions = assert $ isRight $
parseModule ["TemplateHaskell"] Nothing "$(foo)"
--------------------------------------------------------------------------------
testMultilineCpp :: Assertion
testMultilineCpp = assert $ isRight $ parseModule [] Nothing $ unlines
[ "{-# LANGUAGE CPP #-}"
, "#define foo bar \\"
, " qux"
]
--------------------------------------------------------------------------------
testHaskell2010 :: Assertion
testHaskell2010 = assert $ isRight $ parseModule [] Nothing $ unlines
[ "{-# LANGUAGE Haskell2010 #-}"
, "module X where"
, "foo x | Just y <- x = y"
]
--------------------------------------------------------------------------------
testShebang :: Assertion
testShebang = assert $ isRight $ parseModule [] Nothing $ unlines
[ "#!runhaskell"
, "module Main where"
, "main = return ()"
]
--------------------------------------------------------------------------------
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
| eigengrau/stylish-haskell | tests/Language/Haskell/Stylish/Parse/Tests.hs | bsd-3-clause | 2,409 | 0 | 9 | 463 | 358 | 201 | 157 | 39 | 1 |
module Game.Innovation
( module X
) where
import Game.Innovation.Cards as X
import Game.Innovation.Rules as X
import Game.Innovation.ActionTokens as X
| maximilianhuber/innovation | lib/Game/Innovation.hs | bsd-3-clause | 160 | 0 | 4 | 28 | 36 | 26 | 10 | 5 | 0 |
{-# LANGUAGE DeriveGeneric, TypeSynonymInstances, FlexibleInstances, DeriveDataTypeable, StandaloneDeriving #-}
module XMonad.TimeTracker.Types where
import Control.Applicative
import Data.Typeable
import Data.Time
import Data.Binary as Binary
import GHC.Generics (Generic)
deriving instance Generic TimeZone
instance Binary TimeZone
data ZonedUTC =
ZonedUTC {
getUTC :: UTCTime,
getTimeZone :: TimeZone
}
deriving (Eq, Show, Generic)
data TEvent =
BaseEvent {
eTimestamp :: ZonedUTC
, eWindowTitle :: String
, eWindowClass :: String
, eWorkspace :: String
, eAtoms :: [(String, String)]
, eIdleTime :: Int
}
| SetMeta String String
| Quit
| IdleEvent {
eTimestamp :: ZonedUTC
, eIdleTime :: Int
}
deriving (Show, Generic, Typeable)
instance Eq TEvent where
SetMeta k1 v1 == SetMeta k2 v2 = k1 == k2 && v1 == v2
Quit == Quit = True
e1@(BaseEvent {}) == e2@(BaseEvent {}) =
(eWindowTitle e1 == eWindowTitle e2) &&
(eWindowClass e1 == eWindowClass e2) &&
(eWorkspace e1 == eWorkspace e2) &&
(eAtoms e1 == eAtoms e2) &&
(eIdleTime e1 == eIdleTime e2)
(IdleEvent _ it1) == (IdleEvent _ it2) = it1 == it2
e1 == e2 = False
instance Binary Day where
put (ModifiedJulianDay d) = Binary.put d
get = ModifiedJulianDay <$> get
instance Binary UTCTime where
put (UTCTime d t) = do
Binary.put d
Binary.put (toRational t)
get = do
d <- Binary.get
t <- Binary.get
return $ UTCTime d ({-# SCC diffTimeFromRational #-} fromRational t)
instance Binary ZonedUTC
instance Binary TEvent
| portnov/xtt | XMonad/TimeTracker/Types.hs | bsd-3-clause | 1,650 | 0 | 12 | 412 | 531 | 278 | 253 | -1 | -1 |
{-# LANGUAGE FlexibleContexts, OverloadedStrings, RecordWildCards, ScopedTypeVariables, ConstraintKinds, PatternGuards, CPP #-}
-- |The HTTP/JSON plumbing used to implement the 'WD' monad.
--
-- These functions can be used to create your own 'WebDriver' instances, providing extra functionality for your application if desired. All exports
-- of this module are subject to change at any point.
module Test.WebDriver.Internal
( mkRequest, sendHTTPRequest
, getJSONResult, handleJSONErr, handleRespSessionId
, WDResponse(..)
) where
import Test.WebDriver.Class
import Test.WebDriver.JSON
import Test.WebDriver.Session
import Test.WebDriver.Exceptions.Internal
import Network.HTTP.Client (httpLbs, Request(..), RequestBody(..), Response(..))
import qualified Network.HTTP.Client as HTTPClient
import Data.Aeson
import Data.Aeson.Types (typeMismatch)
import Network.HTTP.Types.Header
import Network.HTTP.Types.Status (Status(..))
import qualified Data.ByteString.Base64.Lazy as B64
import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.ByteString.Lazy.Char8 as LBS (unpack, null)
import qualified Data.ByteString.Lazy.Internal as LBS (ByteString(..))
import Data.CallStack
import Data.Text as T (Text, splitOn, null)
import qualified Data.Text.Encoding as TE
import Control.Applicative
import Control.Exception (Exception, SomeException(..), toException, fromException, try)
import Control.Exception.Lifted (throwIO)
import Control.Monad.Base
import Data.String (fromString)
import Data.Word (Word8)
#if !MIN_VERSION_http_client(0,4,30)
import Data.Default.Class
#endif
import Prelude -- hides some "unused import" warnings
--This is the defintion of fromStrict used by bytestring >= 0.10; we redefine it here to support bytestring < 0.10
fromStrict :: BS.ByteString -> LBS.ByteString
fromStrict bs | BS.null bs = LBS.Empty
| otherwise = LBS.Chunk bs LBS.Empty
--Compatability function to support http-client < 0.4.30
defaultRequest :: Request
#if MIN_VERSION_http_client(0,4,30)
defaultRequest = HTTPClient.defaultRequest
#else
defaultRequest = def
#endif
-- |Constructs an HTTP 'Request' value when given a list of headers, HTTP request method, and URL fragment
mkRequest :: (WDSessionState s, ToJSON a) =>
Method -> Text -> a -> s Request
mkRequest meth wdPath args = do
WDSession {..} <- getSession
let body = case toJSON args of
Null -> "" --passing Null as the argument indicates no request body
other -> encode other
return defaultRequest
{ host = wdSessHost
, port = wdSessPort
, path = wdSessBasePath `BS.append` TE.encodeUtf8 wdPath
, requestBody = RequestBodyLBS body
, requestHeaders = wdSessRequestHeaders
++ [ (hAccept, "application/json;charset=UTF-8")
, (hContentType, "application/json;charset=UTF-8") ]
, method = meth
#if !MIN_VERSION_http_client(0,5,0)
, checkStatus = \_ _ _ -> Nothing
#endif
}
-- |Sends an HTTP request to the remote WebDriver server
sendHTTPRequest :: (WDSessionStateIO s) => Request -> s (Either SomeException (Response ByteString))
sendHTTPRequest req = do
s@WDSession{..} <- getSession
(nRetries, tryRes) <- liftBase . retryOnTimeout wdSessHTTPRetryCount $ httpLbs req wdSessHTTPManager
let h = SessionHistory { histRequest = req
, histResponse = tryRes
, histRetryCount = nRetries
}
putSession s { wdSessHist = wdSessHistUpdate h wdSessHist }
return tryRes
retryOnTimeout :: Int -> IO a -> IO (Int, (Either SomeException a))
retryOnTimeout maxRetry go = retry' 0
where
retry' nRetries = do
eitherV <- try go
case eitherV of
(Left e)
#if MIN_VERSION_http_client(0,5,0)
| Just (HTTPClient.HttpExceptionRequest _ HTTPClient.ResponseTimeout) <- fromException e
#else
| Just HTTPClient.ResponseTimeout <- fromException e
#endif
, maxRetry > nRetries
-> retry' (succ nRetries)
other -> return (nRetries, other)
-- |Parses a 'WDResponse' object from a given HTTP response.
getJSONResult :: (HasCallStack, WDSessionStateControl s, FromJSON a) => Response ByteString -> s (Either SomeException a)
getJSONResult r
--malformed request errors
| code >= 400 && code < 500 = do
lastReq <- mostRecentHTTPRequest <$> getSession
returnErr . UnknownCommand . maybe reason show $ lastReq
--server-side errors
| code >= 500 && code < 600 =
case lookup hContentType headers of
Just ct
| "application/json" `BS.isInfixOf` ct ->
parseJSON'
(maybe body fromStrict $ lookup "X-Response-Body-Start" headers)
>>= handleJSONErr
>>= maybe returnNull returnErr
| otherwise ->
returnHTTPErr ServerError
Nothing ->
returnHTTPErr (ServerError . ("HTTP response missing content type. Server reason was: "++))
--redirect case (used as a response to createSession requests)
| code == 302 || code == 303 =
case lookup hLocation headers of
Nothing -> returnErr . HTTPStatusUnknown code $ LBS.unpack body
Just loc -> do
let sessId = last . filter (not . T.null) . splitOn "/" . fromString $ BS.unpack loc
modifySession $ \sess -> sess {wdSessId = Just (SessionId sessId)}
returnNull
-- No Content response
| code == 204 = returnNull
-- HTTP Success
| code >= 200 && code < 300 =
if LBS.null body
then returnNull
else do
rsp@WDResponse {rspVal = val} <- parseJSON' body
handleJSONErr rsp >>= maybe
(handleRespSessionId rsp >> Right <$> fromJSON' val)
returnErr
-- other status codes: return error
| otherwise = returnHTTPErr (HTTPStatusUnknown code)
where
--helper functions
returnErr :: (Exception e, Monad m) => e -> m (Either SomeException a)
returnErr = return . Left . toException
returnHTTPErr errType = returnErr . errType $ reason
returnNull = Right <$> fromJSON' Null
--HTTP response variables
code = statusCode status
reason = BS.unpack $ statusMessage status
status = responseStatus r
body = responseBody r
headers = responseHeaders r
handleRespSessionId :: (HasCallStack, WDSessionStateIO s) => WDResponse -> s ()
handleRespSessionId WDResponse{rspSessId = sessId'} = do
sess@WDSession { wdSessId = sessId} <- getSession
case (sessId, (==) <$> sessId <*> sessId') of
-- if our monad has an uninitialized session ID, initialize it from the response object
(Nothing, _) -> putSession sess { wdSessId = sessId' }
-- if the response ID doesn't match our local ID, throw an error.
(_, Just False) -> throwIO . ServerError $ "Server response session ID (" ++ show sessId'
++ ") does not match local session ID (" ++ show sessId ++ ")"
_ -> return ()
handleJSONErr :: (HasCallStack, WDSessionStateControl s) => WDResponse -> s (Maybe SomeException)
handleJSONErr WDResponse{rspStatus = 0} = return Nothing
handleJSONErr WDResponse{rspVal = val, rspStatus = status} = do
sess <- getSession
errInfo <- fromJSON' val
let screen = B64.decodeLenient <$> errScreen errInfo
seleniumStack = errStack errInfo
errInfo' = errInfo { errSess = Just sess
-- Append the Haskell stack frames to the ones returned from Selenium
, errScreen = screen
, errStack = seleniumStack ++ (fmap callStackItemToStackFrame externalCallStack) }
e errType = toException $ FailedCommand errType errInfo'
return . Just $ case status of
7 -> e NoSuchElement
8 -> e NoSuchFrame
9 -> toException . UnknownCommand . errMsg $ errInfo
10 -> e StaleElementReference
11 -> e ElementNotVisible
12 -> e InvalidElementState
13 -> e UnknownError
15 -> e ElementIsNotSelectable
17 -> e JavascriptError
19 -> e XPathLookupError
21 -> e Timeout
23 -> e NoSuchWindow
24 -> e InvalidCookieDomain
25 -> e UnableToSetCookie
26 -> e UnexpectedAlertOpen
27 -> e NoAlertOpen
28 -> e ScriptTimeout
29 -> e InvalidElementCoordinates
30 -> e IMENotAvailable
31 -> e IMEEngineActivationFailed
32 -> e InvalidSelector
33 -> e SessionNotCreated
34 -> e MoveTargetOutOfBounds
51 -> e InvalidXPathSelector
52 -> e InvalidXPathSelectorReturnType
_ -> e UnknownError
-- |Internal type representing the JSON response object
data WDResponse = WDResponse {
rspSessId :: Maybe SessionId
, rspStatus :: Word8
, rspVal :: Value
}
deriving (Eq, Show)
instance FromJSON WDResponse where
parseJSON (Object o) = WDResponse <$> o .:?? "sessionId" .!= Nothing
<*> o .: "status"
<*> o .:?? "value" .!= Null
parseJSON v = typeMismatch "WDResponse" v
| kallisti-dev/hs-webdriver | src/Test/WebDriver/Internal.hs | bsd-3-clause | 9,159 | 0 | 21 | 2,267 | 2,188 | 1,156 | 1,032 | 171 | 26 |
{-# LANGUAGE MagicHash,
UnboxedTuples, FlexibleInstances #-}
module TokenDef where
import UU.Scanner.Token
import UU.Scanner.GenToken
import UU.Scanner.Position
import UU.Parsing.MachineInterface(Symbol(..))
import Data.Char(isPrint,ord)
import HsToken
import CommonTypes
instance Symbol Token where
deleteCost (Reserved key _) = case key of
"DATA" -> 7#
"EXT" -> 7#
"ATTR" -> 7#
"SEM" -> 7#
"USE" -> 7#
"INCLUDE" -> 7#
_ -> 5#
deleteCost (ValToken v _ _) = case v of
TkError -> 0#
_ -> 5#
tokensToStrings :: [HsToken] -> [(Pos,String)]
tokensToStrings
= map tokenToString
tokenToString :: HsToken -> (Pos, String)
tokenToString tk
= case tk of
AGLocal var pos _ -> (pos, "@" ++ getName var)
AGField field attr pos _ -> (pos, "@" ++ getName field ++ "." ++ getName attr)
HsToken value pos -> (pos, value)
CharToken value pos -> (pos, show value)
StrToken value pos -> (pos, show value)
Err mesg pos -> (pos, " ***" ++ mesg ++ "*** ")
showTokens :: [(Pos,String)] -> [String]
showTokens [] = []
showTokens xs = map showLine . shiftLeft . getLines $ xs
getLines :: [(Pos, a)] -> [[(Pos, a)]]
getLines [] = []
getLines ((p,t):xs) = let (txs,rest) = span sameLine xs
sameLine (q,_) = line p == line q
in ((p,t):txs) : getLines rest
shiftLeft :: [[(Pos, a)]] -> [[(Pos, a)]]
shiftLeft lns = let sh = let m = minimum . checkEmpty . filter (>=1) . map (column.fst.head) $ lns
checkEmpty [] = [1]
checkEmpty x = x
in if m >= 1 then m-1 else 0
shift (p,t) = (if column p >= 1 then case p of (Pos l c f) -> Pos l (c - sh) f else p, t)
in map (map shift) lns
showLine :: [(Pos, [Char])] -> [Char]
showLine ts = let f (p,t) r = let ct = column p
in \c -> spaces (ct-c) ++ t ++ r (length t+ct)
spaces x | x < 0 = ""
| otherwise = replicate x ' '
in foldr f (const "") ts 1
showStrShort :: String -> String
showStrShort xs = "\"" ++ concatMap f xs ++ "\""
where f '"' = "\\\""
f x = showCharShort' x
showCharShort :: Char -> String
showCharShort '\'' = "'" ++ "\\'" ++ "'"
showCharShort c = "'" ++ showCharShort' c ++ "'"
showCharShort' :: Char -> String
showCharShort' '\a' = "\\a"
showCharShort' '\b' = "\\b"
showCharShort' '\t' = "\\t"
showCharShort' '\n' = "\\n"
showCharShort' '\r' = "\\r"
showCharShort' '\f' = "\\f"
showCharShort' '\v' = "\\v"
showCharShort' '\\' = "\\\\"
showCharShort' x | isPrint x = [x]
| otherwise = '\\' : show (ord x)
| norm2782/uuagc | src/TokenDef.hs | bsd-3-clause | 3,057 | 0 | 18 | 1,151 | 1,124 | 589 | 535 | 73 | 6 |
{-# LANGUAGE OverloadedStrings,
GeneralizedNewtypeDeriving,
FlexibleInstances,
MultiParamTypeClasses #-}
module Main (main) where
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.Set as Set
import Control.Monad.Reader
import Network.Kontiki.Raft
type Log a = IntMap (Entry a)
newtype MemLog a r = MemLog { unMemLog :: Reader (Log a) r }
deriving ( Functor
, Applicative
, Monad
, MonadReader (Log a)
)
instance MonadLog (MemLog a) a where
logEntry i = IntMap.lookup (fromIntegral $ unIndex i) `fmap` ask
logLastEntry = do
l <- ask
return $ if IntMap.null l
then Nothing
else Just $ snd $ IntMap.findMax l
runMemLog :: MemLog a r -> Log a -> r
runMemLog = runReader . unMemLog
type Value = String
config :: Config
config = Config { _configNodeId = "node0"
, _configNodes = Set.fromList ["node0", "node1"]
, _configElectionTimeout = 10
, _configHeartbeatTimeout = 2
}
main :: IO ()
main = print $ runMemLog (handle config initialState EHeartbeatTimeout) (IntMap.empty :: Log Value)
| NicolasT/kontiki | bin/demo.hs | bsd-3-clause | 1,244 | 0 | 12 | 382 | 335 | 188 | 147 | 33 | 1 |
{-# LANGUAGE BangPatterns, CPP #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Safe #-}
{-# LANGUAGE DeriveGeneric #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Text.PrettyPrint.MarkedHughesPJ
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Andy Gill <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- Provides a collection of pretty printer combinators, a set of API's
-- that provides a way to easily print out text in a consistent format
-- of your choosing.
--
-- Originally designed by John Hughes's and Simon Peyton Jones's.
--
-- Marking added by Andy Gill, Oct 08.
--
-- For more information you can refer to the
-- <http://belle.sourceforge.net/doc/hughes95design.pdf original paper> that
-- serves as the basis for this libraries design:
-- /The Design -- of a Pretty-printing Library/ by John Hughes, in Advanced
-- Functional Programming, 1995
--
-----------------------------------------------------------------------------
module Text.PrettyPrint.MarkedHughesPJ (
-- * The document type
Doc, -- Type synonym
MDoc, -- Abstract
TextDetails(..),
-- * Constructing documents
-- ** Converting values into documents
char, text, ptext, sizedText, zeroWidthText,
int, integer, float, double, rational,
-- ** Simple derived documents
semi, comma, colon, space, equals,
lparen, rparen, lbrack, rbrack, lbrace, rbrace,
-- ** Wrapping documents in delimiters
parens, brackets, braces, quotes, doubleQuotes,
maybeParens, maybeBrackets, maybeBraces, maybeQuotes, maybeDoubleQuotes,
-- ** Combining documents
empty,
(<>), (<+>), hcat, hsep,
($$), ($+$), vcat,
sep, cat,
fsep, fcat,
nest,
hang, punctuate,
-- * Predicates on documents
isEmpty,
-- * Utility functions for documents
first, reduceDoc,
-- * Rendering documents
-- ** Default rendering
render,
-- ** Rendering with a particular style
Style(..),
style,
renderStyle,
Mode(..),
-- ** General rendering
fullRender,
-- ** Markup extension
mark
) where
import Control.DeepSeq ( NFData(rnf) )
import Data.Function ( on )
#if __GLASGOW_HASKELL__ < 709
import Data.Monoid ( Monoid(mempty, mappend) )
#endif
import Data.String ( IsString(fromString) )
import GHC.Generics
-- ---------------------------------------------------------------------------
-- The MDoc calculus
{-
Laws for $$
~~~~~~~~~~~
<a1> (x $$ y) $$ z = x $$ (y $$ z)
<a2> empty $$ x = x
<a3> x $$ empty = x
...ditto $+$...
Laws for <>
~~~~~~~~~~~
<b1> (x <> y) <> z = x <> (y <> z)
<b2> empty <> x = empty
<b3> x <> empty = x
...ditto <+>...
Laws for text
~~~~~~~~~~~~~
<t1> text s <> text t = text (s++t)
<t2> text "" <> x = x, if x non-empty
** because of law n6, t2 only holds if x doesn't
** start with `nest'.
Laws for nest
~~~~~~~~~~~~~
<n1> nest 0 x = x
<n2> nest k (nest k' x) = nest (k+k') x
<n3> nest k (x <> y) = nest k x <> nest k y
<n4> nest k (x $$ y) = nest k x $$ nest k y
<n5> nest k empty = empty
<n6> x <> nest k y = x <> y, if x non-empty
** Note the side condition on <n6>! It is this that
** makes it OK for empty to be a left unit for <>.
Miscellaneous
~~~~~~~~~~~~~
<m1> (text s <> x) $$ y = text s <> ((text "" <> x) $$
nest (-length s) y)
<m2> (x $$ y) <> z = x $$ (y <> z)
if y non-empty
Laws for list versions
~~~~~~~~~~~~~~~~~~~~~~
<l1> sep (ps++[empty]++qs) = sep (ps ++ qs)
...ditto hsep, hcat, vcat, fill...
<l2> nest k (sep ps) = sep (map (nest k) ps)
...ditto hsep, hcat, vcat, fill...
Laws for oneLiner
~~~~~~~~~~~~~~~~~
<o1> oneLiner (nest k p) = nest k (oneLiner p)
<o2> oneLiner (x <> y) = oneLiner x <> oneLiner y
You might think that the following verion of <m1> would
be neater:
<3 NO> (text s <> x) $$ y = text s <> ((empty <> x)) $$
nest (-length s) y)
But it doesn't work, for if x=empty, we would have
text s $$ y = text s <> (empty $$ nest (-length s) y)
= text s <> nest (-length s) y
-}
-- ---------------------------------------------------------------------------
-- Operator fixity
infixl 6 <>
infixl 6 <+>
infixl 5 $$, $+$
-- ---------------------------------------------------------------------------
-- The MDoc data type
-- An Doc is a Marked Doc (MDoc) with no interesting markings.
type Doc = MDoc ()
-- | The abstract type of documents.
-- An MDoc represents a *set* of layouts. A MDoc with
-- no occurrences of Union or NoDoc represents just one layout.
data MDoc a
= Empty -- empty
| NilAbove (MDoc a) -- text "" $$ x
| TextBeside !(TextDetails a) {-# UNPACK #-} !Int (MDoc a) -- text s <> x
| Nest {-# UNPACK #-} !Int (MDoc a) -- nest k x
| Union (MDoc a) (MDoc a) -- ul `union` ur
| NoDoc -- The empty set of documents
| Beside (MDoc a) Bool (MDoc a) -- True <=> space between
| Above (MDoc a) Bool (MDoc a) -- True <=> never overlap
#if __GLASGOW_HASKELL__ >= 701
deriving (Generic)
#endif
{-
Here are the invariants:
1) The argument of NilAbove is never Empty. Therefore
a NilAbove occupies at least two lines.
2) The argument of @TextBeside@ is never @Nest@.
3) The layouts of the two arguments of @Union@ both flatten to the same
string.
4) The arguments of @Union@ are either @TextBeside@, or @NilAbove@.
5) A @NoDoc@ may only appear on the first line of the left argument of an
union. Therefore, the right argument of an union can never be equivalent
to the empty set (@NoDoc@).
6) An empty document is always represented by @Empty@. It can't be
hidden inside a @Nest@, or a @Union@ of two @Empty@s.
7) The first line of every layout in the left argument of @Union@ is
longer than the first line of any layout in the right argument.
(1) ensures that the left argument has a first line. In view of
(3), this invariant means that the right argument must have at
least two lines.
Notice the difference between
* NoDoc (no documents)
* Empty (one empty document; no height and no width)
* text "" (a document containing the empty string;
one line high, but has no width)
-}
-- | RDoc is a "reduced GDoc", guaranteed not to have a top-level Above or Beside.
type RDoc a = MDoc a
-- | The TextDetails data type
--
-- A TextDetails represents a fragment of text that will be
-- output at some point.
data TextDetails a = Chr {-# UNPACK #-} !Char -- ^ A single Char fragment
| Str String -- ^ A whole String fragment
| PStr String -- ^ Used to represent a Fast String fragment
-- but now deprecated and identical to the
-- Str constructor.
| Mark a
#if __GLASGOW_HASKELL__ >= 701
deriving (Show, Eq, Generic)
#endif
-- Combining @MDoc@ values
instance Monoid (MDoc a) where
mempty = empty
mappend = (<>)
instance IsString (MDoc a) where
fromString = text
instance Show (MDoc a) where
showsPrec _ doc cont = fullRender (mode style) (lineLength style)
(ribbonsPerLine style)
txtPrinter cont doc
instance Eq (MDoc a) where
(==) = (==) `on` render
instance NFData a => NFData (MDoc a) where
rnf Empty = ()
rnf (NilAbove d) = rnf d
rnf (TextBeside td i d) = rnf td `seq` rnf i `seq` rnf d
rnf (Nest k d) = rnf k `seq` rnf d
rnf (Union ur ul) = rnf ur `seq` rnf ul
rnf NoDoc = ()
rnf (Beside ld s rd) = rnf ld `seq` rnf s `seq` rnf rd
rnf (Above ud s ld) = rnf ud `seq` rnf s `seq` rnf ld
instance NFData a => NFData (TextDetails a) where
rnf (Chr c) = rnf c
rnf (Str str) = rnf str
rnf (PStr str) = rnf str
rnf (Mark a) = rnf a
-- ---------------------------------------------------------------------------
-- Values and Predicates on GDocs and TextDetails
-- | A document of height and width 1, containing a literal character.
char :: Char -> MDoc a
char c = textBeside_ (Chr c) 1 Empty
-- | A document of height 1 containing a literal string.
-- 'text' satisfies the following laws:
--
-- * @'text' s '<>' 'text' t = 'text' (s'++'t)@
--
-- * @'text' \"\" '<>' x = x@, if @x@ non-empty
--
-- The side condition on the last law is necessary because @'text' \"\"@
-- has height 1, while 'empty' has no height.
text :: String -> MDoc a
text s = case length s of {sl -> textBeside_ (Str s) sl Empty}
-- | Same as @text@. Used to be used for Bytestrings.
ptext :: String -> MDoc a
ptext s = case length s of {sl -> textBeside_ (PStr s) sl Empty}
-- | Some text with any width. (@text s = sizedText (length s) s@)
sizedText :: Int -> String -> MDoc a
sizedText l s = textBeside_ (Str s) l Empty
-- | Some text, but without any width. Use for non-printing text
-- such as a HTML or Latex tags
zeroWidthText :: String -> MDoc a
zeroWidthText = sizedText 0
-- | The empty document, with no height and no width.
-- 'empty' is the identity for '<>', '<+>', '$$' and '$+$', and anywhere
-- in the argument list for 'sep', 'hcat', 'hsep', 'vcat', 'fcat' etc.
empty :: MDoc a
empty = Empty
-- | Returns 'True' if the document is empty
isEmpty :: MDoc a -> Bool
isEmpty Empty = True
isEmpty _ = False
-- | Produce spacing for indenting the amount specified.
--
-- an old version inserted tabs being 8 columns apart in the output.
indent :: Int -> String
indent !n = replicate n ' '
{-
Q: What is the reason for negative indentation (i.e. argument to indent
is < 0) ?
A:
This indicates an error in the library client's code.
If we compose a <> b, and the first line of b is more indented than some
other lines of b, the law <n6> (<> eats nests) may cause the pretty
printer to produce an invalid layout:
doc |0123345
------------------
d1 |a...|
d2 |...b|
|c...|
d1<>d2 |ab..|
c|....|
Consider a <> b, let `s' be the length of the last line of `a', `k' the
indentation of the first line of b, and `k0' the indentation of the
left-most line b_i of b.
The produced layout will have negative indentation if `k - k0 > s', as
the first line of b will be put on the (s+1)th column, effectively
translating b horizontally by (k-s). Now if the i^th line of b has an
indentation k0 < (k-s), it is translated out-of-page, causing
`negative indentation'.
-}
semi :: MDoc a -- ^ A ';' character
comma :: MDoc a -- ^ A ',' character
colon :: MDoc a -- ^ A ':' character
space :: MDoc a -- ^ A space character
equals :: MDoc a -- ^ A '=' character
lparen :: MDoc a -- ^ A '(' character
rparen :: MDoc a -- ^ A ')' character
lbrack :: MDoc a -- ^ A '[' character
rbrack :: MDoc a -- ^ A ']' character
lbrace :: MDoc a -- ^ A '{' character
rbrace :: MDoc a -- ^ A '}' character
semi = char ';'
comma = char ','
colon = char ':'
space = char ' '
equals = char '='
lparen = char '('
rparen = char ')'
lbrack = char '['
rbrack = char ']'
lbrace = char '{'
rbrace = char '}'
spaceText, nlText :: TextDetails a
spaceText = Chr ' '
nlText = Chr '\n'
int :: Int -> MDoc a -- ^ @int n = text (show n)@
integer :: Integer -> MDoc a -- ^ @integer n = text (show n)@
float :: Float -> MDoc a -- ^ @float n = text (show n)@
double :: Double -> MDoc a -- ^ @double n = text (show n)@
rational :: Rational -> MDoc a -- ^ @rational n = text (show n)@
int n = text (show n)
integer n = text (show n)
float n = text (show n)
double n = text (show n)
rational n = text (show n)
parens :: MDoc a -> MDoc a -- ^ Wrap document in @(...)@
brackets :: MDoc a -> MDoc a -- ^ Wrap document in @[...]@
braces :: MDoc a -> MDoc a -- ^ Wrap document in @{...}@
quotes :: MDoc a -> MDoc a -- ^ Wrap document in @\'...\'@
doubleQuotes :: MDoc a -> MDoc a -- ^ Wrap document in @\"...\"@
quotes p = char '\'' <> p <> char '\''
doubleQuotes p = char '"' <> p <> char '"'
parens p = char '(' <> p <> char ')'
brackets p = char '[' <> p <> char ']'
braces p = char '{' <> p <> char '}'
-- | Apply 'parens' to 'MDoc' if boolean is true.
maybeParens :: Bool -> MDoc a -> MDoc a
maybeParens False = id
maybeParens True = parens
-- | Apply 'brackets' to 'MDoc' if boolean is true.
maybeBrackets :: Bool -> MDoc a -> MDoc a
maybeBrackets False = id
maybeBrackets True = brackets
-- | Apply 'braces' to 'MDoc' if boolean is true.
maybeBraces :: Bool -> MDoc a -> MDoc a
maybeBraces False = id
maybeBraces True = braces
-- | Apply 'quotes' to 'MDoc' if boolean is true.
maybeQuotes :: Bool -> MDoc a -> MDoc a
maybeQuotes False = id
maybeQuotes True = quotes
-- | Apply 'doubleQuotes' to 'MDoc' if boolean is true.
maybeDoubleQuotes :: Bool -> MDoc a -> MDoc a
maybeDoubleQuotes False = id
maybeDoubleQuotes True = doubleQuotes
-- ---------------------------------------------------------------------------
-- Structural operations on GDocs
-- | Perform some simplification of a built up @GDoc@.
reduceDoc :: MDoc a -> RDoc a
reduceDoc (Beside p g q) = beside p g (reduceDoc q)
reduceDoc (Above p g q) = above p g (reduceDoc q)
reduceDoc p = p
-- | List version of '<>'.
hcat :: [MDoc a] -> MDoc a
hcat = snd . reduceHoriz . foldr (\p q -> Beside p False q) empty
-- | List version of '<+>'.
hsep :: [MDoc a] -> MDoc a
hsep = snd . reduceHoriz . foldr (\p q -> Beside p True q) empty
-- | List version of '$$'.
vcat :: [MDoc a] -> MDoc a
vcat = snd . reduceVert . foldr (\p q -> Above p False q) empty
-- | Nest (or indent) a document by a given number of positions
-- (which may also be negative). 'nest' satisfies the laws:
--
-- * @'nest' 0 x = x@
--
-- * @'nest' k ('nest' k' x) = 'nest' (k+k') x@
--
-- * @'nest' k (x '<>' y) = 'nest' k z '<>' 'nest' k y@
--
-- * @'nest' k (x '$$' y) = 'nest' k x '$$' 'nest' k y@
--
-- * @'nest' k 'empty' = 'empty'@
--
-- * @x '<>' 'nest' k y = x '<>' y@, if @x@ non-empty
--
-- The side condition on the last law is needed because
-- 'empty' is a left identity for '<>'.
nest :: Int -> MDoc a -> MDoc a
nest k p = mkNest k (reduceDoc p)
-- | @hang d1 n d2 = sep [d1, nest n d2]@
hang :: MDoc a -> Int -> MDoc a -> MDoc a
hang d1 n d2 = sep [d1, nest n d2]
-- | @punctuate p [d1, ... dn] = [d1 \<> p, d2 \<> p, ... dn-1 \<> p, dn]@
punctuate :: MDoc a -> [MDoc a] -> [MDoc a]
punctuate _ [] = []
punctuate p (x:xs) = go x xs
where go y [] = [y]
go y (z:zs) = (y <> p) : go z zs
-- mkNest checks for Nest's invariant that it doesn't have an Empty inside it
mkNest :: Int -> MDoc a -> MDoc a
mkNest k _ | k `seq` False = undefined
mkNest k (Nest k1 p) = mkNest (k + k1) p
mkNest _ NoDoc = NoDoc
mkNest _ Empty = Empty
mkNest 0 p = p
mkNest k p = nest_ k p
-- mkUnion checks for an empty document
mkUnion :: MDoc a -> MDoc a -> MDoc a
mkUnion Empty _ = Empty
mkUnion p q = p `union_` q
data IsEmpty = IsEmpty | NotEmpty
reduceHoriz :: MDoc a -> (IsEmpty, MDoc a)
reduceHoriz (Beside p g q) = eliminateEmpty Beside (snd (reduceHoriz p)) g (reduceHoriz q)
reduceHoriz doc = (NotEmpty, doc)
reduceVert :: MDoc a -> (IsEmpty, MDoc a)
reduceVert (Above p g q) = eliminateEmpty Above (snd (reduceVert p)) g (reduceVert q)
reduceVert doc = (NotEmpty, doc)
{-# INLINE eliminateEmpty #-}
eliminateEmpty ::
(MDoc a -> Bool -> MDoc a -> MDoc a) ->
MDoc a -> Bool -> (IsEmpty, MDoc a) -> (IsEmpty, MDoc a)
eliminateEmpty _ Empty _ q = q
eliminateEmpty cons p g q =
(NotEmpty,
-- We're not empty whether or not q is empty, so for laziness-sake,
-- after checking that p isn't empty, we put the NotEmpty result
-- outside independent of q. This allows reduceAB to immediately
-- return the appropriate constructor (Above or Beside) without
-- forcing the entire nested MDoc. This allows the foldr in vcat,
-- hsep, and hcat to be lazy on its second argument, avoiding a
-- stack overflow.
case q of
(NotEmpty, q') -> cons p g q'
(IsEmpty, _) -> p)
nilAbove_ :: RDoc a -> RDoc a
nilAbove_ = NilAbove
-- Arg of a TextBeside is always an RDoc
textBeside_ :: TextDetails a -> Int -> RDoc a -> RDoc a
textBeside_ = TextBeside
nest_ :: Int -> RDoc a -> RDoc a
nest_ = Nest
union_ :: RDoc a -> RDoc a -> RDoc a
union_ = Union
-- ---------------------------------------------------------------------------
-- Vertical composition @$$@
-- | Above, except that if the last line of the first argument stops
-- at least one position before the first line of the second begins,
-- these two lines are overlapped. For example:
--
-- > text "hi" $$ nest 5 (text "there")
--
-- lays out as
--
-- > hi there
--
-- rather than
--
-- > hi
-- > there
--
-- '$$' is associative, with identity 'empty', and also satisfies
--
-- * @(x '$$' y) '<>' z = x '$$' (y '<>' z)@, if @y@ non-empty.
--
($$) :: MDoc a -> MDoc a -> MDoc a
p $$ q = above_ p False q
-- | Above, with no overlapping.
-- '$+$' is associative, with identity 'empty'.
($+$) :: MDoc a -> MDoc a -> MDoc a
p $+$ q = above_ p True q
above_ :: MDoc a -> Bool -> MDoc a -> MDoc a
above_ p _ Empty = p
above_ Empty _ q = q
above_ p g q = Above p g q
above :: MDoc a -> Bool -> RDoc a -> RDoc a
above (Above p g1 q1) g2 q2 = above p g1 (above q1 g2 q2)
above p@(Beside{}) g q = aboveNest (reduceDoc p) g 0 (reduceDoc q)
above p g q = aboveNest p g 0 (reduceDoc q)
-- Specfication: aboveNest p g k q = p $g$ (nest k q)
aboveNest :: RDoc a -> Bool -> Int -> RDoc a -> RDoc a
aboveNest _ _ k _ | k `seq` False = undefined
aboveNest NoDoc _ _ _ = NoDoc
aboveNest (p1 `Union` p2) g k q = aboveNest p1 g k q `union_`
aboveNest p2 g k q
aboveNest Empty _ k q = mkNest k q
aboveNest (Nest k1 p) g k q = nest_ k1 (aboveNest p g (k - k1) q)
-- p can't be Empty, so no need for mkNest
aboveNest (NilAbove p) g k q = nilAbove_ (aboveNest p g k q)
aboveNest (TextBeside s sl p) g k q = textBeside_ s sl rest
where
!k1 = k - sl
rest = case p of
Empty -> nilAboveNest g k1 q
_ -> aboveNest p g k1 q
aboveNest (Above {}) _ _ _ = error "aboveNest Above"
aboveNest (Beside {}) _ _ _ = error "aboveNest Beside"
-- Specification: text s <> nilaboveNest g k q
-- = text s <> (text "" $g$ nest k q)
nilAboveNest :: Bool -> Int -> RDoc a -> RDoc a
nilAboveNest _ k _ | k `seq` False = undefined
nilAboveNest _ _ Empty = Empty
-- Here's why the "text s <>" is in the spec!
nilAboveNest g k (Nest k1 q) = nilAboveNest g (k + k1) q
nilAboveNest g k q | not g && k > 0 -- No newline if no overlap
= textBeside_ (Str (indent k)) k q
| otherwise -- Put them really above
= nilAbove_ (mkNest k q)
-- ---------------------------------------------------------------------------
-- Horizontal composition @<>@
-- We intentionally avoid Data.Monoid.(<>) here due to interactions of
-- Data.Monoid.(<>) and (<+>). See
-- http://www.haskell.org/pipermail/libraries/2011-November/017066.html
-- | Beside.
-- '<>' is associative, with identity 'empty'.
(<>) :: MDoc a -> MDoc a -> MDoc a
p <> q = beside_ p False q
-- | Beside, separated by space, unless one of the arguments is 'empty'.
-- '<+>' is associative, with identity 'empty'.
(<+>) :: MDoc a -> MDoc a -> MDoc a
p <+> q = beside_ p True q
beside_ :: MDoc a -> Bool -> MDoc a -> MDoc a
beside_ p _ Empty = p
beside_ Empty _ q = q
beside_ p g q = Beside p g q
-- Specification: beside g p q = p <g> q
beside :: MDoc a -> Bool -> RDoc a -> RDoc a
beside NoDoc _ _ = NoDoc
beside (p1 `Union` p2) g q = beside p1 g q `union_` beside p2 g q
beside Empty _ q = q
beside (Nest k p) g q = nest_ k $! beside p g q
beside p@(Beside p1 g1 q1) g2 q2
| g1 == g2 = beside p1 g1 $! beside q1 g2 q2
| otherwise = beside (reduceDoc p) g2 q2
beside p@(Above{}) g q = let !d = reduceDoc p in beside d g q
beside (NilAbove p) g q = nilAbove_ $! beside p g q
beside (TextBeside s sl p) g q = textBeside_ s sl $! rest
where
rest = case p of
Empty -> nilBeside g q
_ -> beside p g q
-- Specification: text "" <> nilBeside g p
-- = text "" <g> p
nilBeside :: Bool -> RDoc a -> RDoc a
nilBeside _ Empty = Empty -- Hence the text "" in the spec
nilBeside g (Nest _ p) = nilBeside g p
nilBeside g p | g = textBeside_ spaceText 1 p
| otherwise = p
-- ---------------------------------------------------------------------------
-- Separate, @sep@
-- Specification: sep ps = oneLiner (hsep ps)
-- `union`
-- vcat ps
-- | Either 'hsep' or 'vcat'.
sep :: [MDoc a] -> MDoc a
sep = sepX True -- Separate with spaces
-- | Either 'hcat' or 'vcat'.
cat :: [MDoc a] -> MDoc a
cat = sepX False -- Don't
sepX :: Bool -> [MDoc a] -> MDoc a
sepX _ [] = empty
sepX x (p:ps) = sep1 x (reduceDoc p) 0 ps
-- Specification: sep1 g k ys = sep (x : map (nest k) ys)
-- = oneLiner (x <g> nest k (hsep ys))
-- `union` x $$ nest k (vcat ys)
sep1 :: Bool -> RDoc a -> Int -> [MDoc a] -> RDoc a
sep1 _ _ k _ | k `seq` False = undefined
sep1 _ NoDoc _ _ = NoDoc
sep1 g (p `Union` q) k ys = sep1 g p k ys `union_`
aboveNest q False k (reduceDoc (vcat ys))
sep1 g Empty k ys = mkNest k (sepX g ys)
sep1 g (Nest n p) k ys = nest_ n (sep1 g p (k - n) ys)
sep1 _ (NilAbove p) k ys = nilAbove_
(aboveNest p False k (reduceDoc (vcat ys)))
sep1 g (TextBeside s sl p) k ys = textBeside_ s sl (sepNB g p (k - sl) ys)
sep1 _ (Above {}) _ _ = error "sep1 Above"
sep1 _ (Beside {}) _ _ = error "sep1 Beside"
-- Specification: sepNB p k ys = sep1 (text "" <> p) k ys
-- Called when we have already found some text in the first item
-- We have to eat up nests
sepNB :: Bool -> MDoc a -> Int -> [MDoc a] -> MDoc a
sepNB g (Nest _ p) k ys
= sepNB g p k ys -- Never triggered, because of invariant (2)
sepNB g Empty k ys
= oneLiner (nilBeside g (reduceDoc rest)) `mkUnion`
-- XXX: TODO: PRETTY: Used to use True here (but GHC used False...)
nilAboveNest False k (reduceDoc (vcat ys))
where
rest | g = hsep ys
| otherwise = hcat ys
sepNB g p k ys
= sep1 g p k ys
-- ---------------------------------------------------------------------------
-- @fill@
-- | \"Paragraph fill\" version of 'cat'.
fcat :: [MDoc a] -> MDoc a
fcat = fill False
-- | \"Paragraph fill\" version of 'sep'.
fsep :: [MDoc a] -> MDoc a
fsep = fill True
-- Specification:
--
-- fill g docs = fillIndent 0 docs
--
-- fillIndent k [] = []
-- fillIndent k [p] = p
-- fillIndent k (p1:p2:ps) =
-- oneLiner p1 <g> fillIndent (k + length p1 + g ? 1 : 0)
-- (remove_nests (oneLiner p2) : ps)
-- `Union`
-- (p1 $*$ nest (-k) (fillIndent 0 ps))
--
-- $*$ is defined for layouts (not Docs) as
-- layout1 $*$ layout2 | hasMoreThanOneLine layout1 = layout1 $$ layout2
-- | otherwise = layout1 $+$ layout2
fill :: Bool -> [MDoc a] -> RDoc a
fill _ [] = empty
fill g (p:ps) = fill1 g (reduceDoc p) 0 ps
fill1 :: Bool -> RDoc a -> Int -> [MDoc a] -> MDoc a
fill1 _ _ k _ | k `seq` False = undefined
fill1 _ NoDoc _ _ = NoDoc
fill1 g (p `Union` q) k ys = fill1 g p k ys `union_`
aboveNest q False k (fill g ys)
fill1 g Empty k ys = mkNest k (fill g ys)
fill1 g (Nest n p) k ys = nest_ n (fill1 g p (k - n) ys)
fill1 g (NilAbove p) k ys = nilAbove_ (aboveNest p False k (fill g ys))
fill1 g (TextBeside s sl p) k ys = textBeside_ s sl (fillNB g p (k - sl) ys)
fill1 _ (Above {}) _ _ = error "fill1 Above"
fill1 _ (Beside {}) _ _ = error "fill1 Beside"
fillNB :: Bool -> MDoc a -> Int -> [MDoc a] -> MDoc a
fillNB _ _ k _ | k `seq` False = undefined
fillNB g (Nest _ p) k ys = fillNB g p k ys
-- Never triggered, because of invariant (2)
fillNB _ Empty _ [] = Empty
fillNB g Empty k (Empty:ys) = fillNB g Empty k ys
fillNB g Empty k (y:ys) = fillNBE g k y ys
fillNB g p k ys = fill1 g p k ys
fillNBE :: Bool -> Int -> MDoc a -> [MDoc a] -> MDoc a
fillNBE g k y ys
= nilBeside g (fill1 g ((elideNest . oneLiner . reduceDoc) y) k' ys)
-- XXX: TODO: PRETTY: Used to use True here (but GHC used False...)
`mkUnion` nilAboveNest False k (fill g (y:ys))
where k' = if g then k - 1 else k
elideNest :: MDoc a -> MDoc a
elideNest (Nest _ d) = d
elideNest d = d
-- ---------------------------------------------------------------------------
-- Selecting the best layout
best :: Int -- Line length
-> Int -- Ribbon length
-> RDoc a
-> RDoc a -- No unions in here!
best w0 r = get w0
where
get w _ | w == 0 && False = undefined
get _ Empty = Empty
get _ NoDoc = NoDoc
get w (NilAbove p) = nilAbove_ (get w p)
get w (TextBeside s sl p) = textBeside_ s sl (get1 w sl p)
get w (Nest k p) = nest_ k (get (w - k) p)
get w (p `Union` q) = nicest w r (get w p) (get w q)
get _ (Above {}) = error "best get Above"
get _ (Beside {}) = error "best get Beside"
get1 w _ _ | w == 0 && False = undefined
get1 _ _ Empty = Empty
get1 _ _ NoDoc = NoDoc
get1 w sl (NilAbove p) = nilAbove_ (get (w - sl) p)
get1 w sl (TextBeside t tl p) = textBeside_ t tl (get1 w (sl + tl) p)
get1 w sl (Nest _ p) = get1 w sl p
get1 w sl (p `Union` q) = nicest1 w r sl (get1 w sl p)
(get1 w sl q)
get1 _ _ (Above {}) = error "best get1 Above"
get1 _ _ (Beside {}) = error "best get1 Beside"
nicest :: Int -> Int -> MDoc a -> MDoc a -> MDoc a
nicest !w !r = nicest1 w r 0
nicest1 :: Int -> Int -> Int -> MDoc a -> MDoc a -> MDoc a
nicest1 !w !r !sl p q | fits ((w `min` r) - sl) p = p
| otherwise = q
fits :: Int -- Space available
-> MDoc a
-> Bool -- True if *first line* of MDoc fits in space available
fits n _ | n < 0 = False
fits _ NoDoc = False
fits _ Empty = True
fits _ (NilAbove _) = True
fits n (TextBeside _ sl p) = fits (n - sl) p
fits _ (Above {}) = error "fits Above"
fits _ (Beside {}) = error "fits Beside"
fits _ (Union {}) = error "fits Union"
fits _ (Nest {}) = error "fits Nest"
-- | @first@ returns its first argument if it is non-empty, otherwise its second.
first :: MDoc a -> MDoc a -> MDoc a
first p q | nonEmptySet p = p -- unused, because (get OneLineMode) is unused
| otherwise = q
nonEmptySet :: MDoc a -> Bool
nonEmptySet NoDoc = False
nonEmptySet (_ `Union` _) = True
nonEmptySet Empty = True
nonEmptySet (NilAbove _) = True
nonEmptySet (TextBeside _ _ p) = nonEmptySet p
nonEmptySet (Nest _ p) = nonEmptySet p
nonEmptySet (Above {}) = error "nonEmptySet Above"
nonEmptySet (Beside {}) = error "nonEmptySet Beside"
-- @oneLiner@ returns the one-line members of the given set of @GDoc@s.
oneLiner :: MDoc a -> MDoc a
oneLiner NoDoc = NoDoc
oneLiner Empty = Empty
oneLiner (NilAbove _) = NoDoc
oneLiner (TextBeside s sl p) = textBeside_ s sl (oneLiner p)
oneLiner (Nest k p) = nest_ k (oneLiner p)
oneLiner (p `Union` _) = oneLiner p
oneLiner (Above {}) = error "oneLiner Above"
oneLiner (Beside {}) = error "oneLiner Beside"
-- ---------------------------------------------------------------------------
-- Rendering
-- | A rendering style.
data Style
= Style { mode :: Mode -- ^ The rendering mode
, lineLength :: Int -- ^ Length of line, in chars
, ribbonsPerLine :: Float -- ^ Ratio of line length to ribbon length
}
#if __GLASGOW_HASKELL__ >= 701
deriving (Show, Eq, Generic)
#endif
-- | The default style (@mode=PageMode, lineLength=100, ribbonsPerLine=1.5@).
style :: Style
style = Style { lineLength = 100, ribbonsPerLine = 1.5, mode = PageMode }
-- | Rendering mode.
data Mode = PageMode -- ^ Normal
| ZigZagMode -- ^ With zig-zag cuts
| LeftMode -- ^ No indentation, infinitely long lines
| OneLineMode -- ^ All on one line
#if __GLASGOW_HASKELL__ >= 701
deriving (Show, Eq, Generic)
#endif
-- | Render the @MDoc@ to a String using the default @Style@.
render :: MDoc a -> String
render = fullRender (mode style) (lineLength style) (ribbonsPerLine style)
txtPrinter ""
-- | Render the @MDoc@ to a String using the given @Style@.
renderStyle :: Style -> MDoc a -> String
renderStyle s = fullRender (mode s) (lineLength s) (ribbonsPerLine s)
txtPrinter ""
-- | Default TextDetails printer
txtPrinter :: TextDetails a -> String -> String
txtPrinter (Chr c) s = c:s
txtPrinter (Str s1) s2 = s1 ++ s2
txtPrinter (PStr s1) s2 = s1 ++ s2
txtPrinter (Mark _) s2 = s2
-- | The general rendering interface.
fullRender :: Mode -- ^ Rendering mode
-> Int -- ^ Line length
-> Float -- ^ Ribbons per line
-> (TextDetails b -> a -> a) -- ^ What to do with text
-> a -- ^ What to do at the end
-> MDoc b -- ^ The document
-> a -- ^ Result
fullRender OneLineMode _ _ txt end doc
= easyDisplay spaceText (\_ y -> y) txt end (reduceDoc doc)
fullRender LeftMode _ _ txt end doc
= easyDisplay nlText first txt end (reduceDoc doc)
fullRender m lineLen ribbons txt rest doc
= display m lineLen ribbonLen txt rest doc'
where
doc' = best bestLineLen ribbonLen (reduceDoc doc)
bestLineLen, ribbonLen :: Int
ribbonLen = round (fromIntegral lineLen / ribbons)
bestLineLen = case m of
ZigZagMode -> maxBound
_ -> lineLen
easyDisplay :: TextDetails b
-> (MDoc b -> MDoc b -> MDoc b)
-> (TextDetails b -> a -> a)
-> a
-> MDoc b
-> a
easyDisplay nlSpaceText choose txt end
= lay
where
lay NoDoc = error "easyDisplay: NoDoc"
lay (Union p q) = lay (choose p q)
lay (Nest _ p) = lay p
lay Empty = end
lay (NilAbove p) = nlSpaceText `txt` lay p
lay (TextBeside s _ p) = s `txt` lay p
lay (Above {}) = error "easyDisplay Above"
lay (Beside {}) = error "easyDisplay Beside"
display :: Mode -> Int -> Int -> (TextDetails b -> a -> a) -> a -> MDoc b -> a
display m !page_width !ribbon_width txt end doc
= case page_width - ribbon_width of { gap_width ->
case gap_width `quot` 2 of { shift ->
let
lay k _ | k `seq` False = undefined
lay k (Nest k1 p) = lay (k + k1) p
lay _ Empty = end
lay k (NilAbove p) = nlText `txt` lay k p
lay k (TextBeside s sl p)
= case m of
ZigZagMode | k >= gap_width
-> nlText `txt` (
Str (replicate shift '/') `txt` (
nlText `txt`
lay1 (k - shift) s sl p ))
| k < 0
-> nlText `txt` (
Str (replicate shift '\\') `txt` (
nlText `txt`
lay1 (k + shift) s sl p ))
_ -> lay1 k s sl p
lay _ (Above {}) = error "display lay Above"
lay _ (Beside {}) = error "display lay Beside"
lay _ NoDoc = error "display lay NoDoc"
lay _ (Union {}) = error "display lay Union"
lay1 !k s !sl p = let !r = k + sl
in Str (indent k) `txt` (s `txt` lay2 r p)
lay2 k _ | k `seq` False = undefined
lay2 k (NilAbove p) = nlText `txt` lay k p
lay2 k (TextBeside s sl p) = s `txt` lay2 (k + sl) p
lay2 k (Nest _ p) = lay2 k p
lay2 _ Empty = end
lay2 _ (Above {}) = error "display lay2 Above"
lay2 _ (Beside {}) = error "display lay2 Beside"
lay2 _ NoDoc = error "display lay2 NoDoc"
lay2 _ (Union {}) = error "display lay2 Union"
in
lay 0 doc
}}
------------------------------------------------------------------------------
-- | mark inserts a zero width mark into the output document
mark :: a -> MDoc a
mark m = textBeside_ (Mark m) 0 Empty | ku-fpg/marked-pretty | src/Text/PrettyPrint/MarkedHughesPJ.hs | bsd-3-clause | 34,684 | 0 | 26 | 11,156 | 8,688 | 4,515 | 4,173 | 490 | 18 |
-- {-# LANGUAGE #-}
{-# OPTIONS_GHC -Wall -fno-warn-missing-signatures #-}
----------------------------------------------------------------------
-- |
-- Module : Play.CseTest
-- Copyright : (c) Conal Elliott 2009
-- License : GPL-3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Test misc simplifications
----------------------------------------------------------------------
module Play.Simplify where
-- import Data.VectorSpace
import Text.PrettyPrint.Leijen.DocExprV (Expr,HasExpr(expr))
import Graphics.Shady.Language.Exp
import Graphics.Shady.Color3
import Graphics.Shady.Complex
-- import Graphics.Shady.Transform2
import Graphics.Shady.Image
x :: HasExpr a => a -> Expr
x = expr
y :: ColorE -> Expr
y = expr . colorToR4
z :: PointE -> Expr
z = expr . pointToR2
q,r :: Exp R1
q = Var (variable "q")
r = Var (variable "r")
w :: Exp R2
w = Var (variable "w")
t1 = 0 * q
t2 = q * 0
t3 = (1 - q) * 0
t4 = q * 1
c :: ComplexE R
c = q :+ r
| conal/shady-gen | src/Shady/Play/Simplify.hs | agpl-3.0 | 1,001 | 0 | 7 | 185 | 242 | 144 | 98 | 24 | 1 |
module FP.DerivingPrism where
import FP.Core
import FP.TH
import Language.Haskell.TH
import Data.Char
-- makePrismLogic [C, D] ty [a, b] Con [fty, gty] := [|
-- fieldL :: (C, D) => Prism (ty a b) (fty, bty)
-- fieldL := Prism
-- { view = \ v -> case v of
-- Con f g -> Just (f, g)
-- _ -> Nothing
-- , inject = Con
-- }
-- |]
makePrismLogic :: (Monad m, MonadQ m) => Cxt -> Name -> [TyVarBndr] -> Name -> [Type] -> Int -> m [Dec]
makePrismLogic cx ty tyargs con args numcons = do
let lensName = mkName $ lowerCase (nameBase con) ++ toChars "L"
x <- liftQ $ newName $ toChars "x"
argVars <- liftQ $ mapOnM args $ const $ newName $ toChars "a"
return
[ SigD lensName $
ForallT tyargs cx $ app (ConT ''Prism)
[ ConT ty #@| map (VarT . tyVarBndrName) tyargs
, tup args
]
, FunD lensName
[ sclause [] $ app (ConE 'Prism)
[ LamE [tup $ map VarP argVars] $ ConE con #@| map VarE argVars
, LamE [VarP x] $
CaseE (VarE x) $ concat
[ single $ smatch (ConP con $ map VarP argVars) $
ConE 'Just #@ tup (map VarE argVars)
, if numcons <= 1 then [] else single $ smatch WildP $ ConE 'Nothing
]
]
]
]
where lowerCase = mapHead toLower
makePrisms :: Name -> Q [Dec]
makePrisms name = do
(cx, ty, tyargs, cs, _) <- maybeZero . (coerceADT *. view tyConIL) *$ liftQ $ reify name
scs <- mapM (maybeZero . coerceSimpleCon) cs
concat ^$ mapOnM scs $ \ (cname, args) -> do
makePrismLogic cx ty tyargs cname args $ length scs
| davdar/maam | src/FP/DerivingPrism.hs | bsd-3-clause | 1,655 | 0 | 23 | 539 | 575 | 290 | 285 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances, TemplateHaskell, QuasiQuotes, MultiParamTypeClasses, FlexibleInstances, DeriveDataTypeable, NamedFieldPuns, ScopedTypeVariables #-}
module Pnm where
import qualified Data.Char as Char
import Language.Pads.Padsc
import Control.Monad
_ws = one_or_more Char.isSpace
where one_or_more = undefined
ws, wsnl, whitechar :: RE
ws = REd "[ \t\n\r]+" " " -- whitespace
wsnl = let REd wplus _ = ws in REd wplus "\n" -- whitespace output as \n
whitechar = REd "[ \t\n\r]" "\n" -- one white character
[pads|
data PGMx a = PGM "P5" ws Header whitechar (Pixmap a)
data Header = Header -- fields should be separated by whitespace
{ width :: Int
ws , height :: Int
wsnl , constrain denominator :: Int
where <| 0 <= denominator && denominator < 65536 |>
}
data Pixmap a (h::Header) = Rows [Row a h | wsnl] length <| height h |>
data Row a (h::Header) = Pixels [a h | ws] length <| width h |>
newtype Greypix (h::Header) =
G constrain g::Int16 where <| 0 <= g && g <= denominator h |>
data PGM = PGMx Int16 Greypix
|]
pgm file = do (rep, md) <- parseFile file
return rep | GaloisInc/pads-haskell | Examples/Pnm.hs | bsd-3-clause | 1,217 | 0 | 9 | 318 | 136 | 77 | 59 | -1 | -1 |
module Idris.Imports where
import Control.Applicative ((<$>))
import Data.List (isSuffixOf)
import Idris.AbsSyntax
import Idris.Error
import Idris.Core.TT
import IRTS.System (getIdrisLibDir)
import System.FilePath
import System.Directory
import Control.Monad.State.Strict
data IFileType = IDR FilePath | LIDR FilePath | IBC FilePath IFileType
deriving (Show, Eq)
-- | Get the index file name for a package name
pkgIndex :: String -> FilePath
pkgIndex s = "00" ++ s ++ "-idx.ibc"
srcPath :: FilePath -> FilePath
srcPath fp = let (n, ext) = splitExtension fp in
case ext of
".idr" -> fp
_ -> fp ++ ".idr"
lsrcPath :: FilePath -> FilePath
lsrcPath fp = let (n, ext) = splitExtension fp in
case ext of
".lidr" -> fp
_ -> fp ++ ".lidr"
-- Get name of byte compiled version of an import
ibcPath :: FilePath -> Bool -> FilePath -> FilePath
ibcPath ibcsd use_ibcsd fp = let (d_fp, n_fp) = splitFileName fp
d = if (not use_ibcsd) || ibcsd == ""
then d_fp
else d_fp </> ibcsd
n = dropExtension n_fp
in d </> n <.> "ibc"
ibcPathWithFallback :: FilePath -> FilePath -> IO FilePath
ibcPathWithFallback ibcsd fp = do let ibcp = ibcPath ibcsd True fp
ibc <- doesFileExist' ibcp
return (if ibc
then ibcp
else ibcPath ibcsd False fp)
ibcPathNoFallback :: FilePath -> FilePath -> FilePath
ibcPathNoFallback ibcsd fp = ibcPath ibcsd True fp
findImport :: [FilePath] -> FilePath -> FilePath -> Idris IFileType
findImport [] ibcsd fp = ierror . Msg $ "Can't find import " ++ fp
findImport (d:ds) ibcsd fp = do let fp_full = d </> fp
ibcp <- runIO $ ibcPathWithFallback ibcsd fp_full
let idrp = srcPath fp_full
let lidrp = lsrcPath fp_full
ibc <- runIO $ doesFileExist' ibcp
idr <- runIO $ doesFileExist' idrp
lidr <- runIO $ doesFileExist' lidrp
-- when idr $ putStrLn $ idrp ++ " ok"
-- when lidr $ putStrLn $ lidrp ++ " ok"
-- when ibc $ putStrLn $ ibcp ++ " ok"
let isrc = if lidr
then LIDR lidrp
else IDR idrp
if ibc
then return (IBC ibcp isrc)
else if (idr || lidr)
then return isrc
else findImport ds ibcsd fp
-- find a specific filename somewhere in a path
findInPath :: [FilePath] -> FilePath -> IO FilePath
findInPath [] fp = fail $ "Can't find file " ++ fp
findInPath (d:ds) fp = do let p = d </> fp
e <- doesFileExist' p
if e then return p else findInPath ds fp
findPkgIndex :: String -> Idris FilePath
findPkgIndex p = do let idx = pkgIndex p
ids <- allImportDirs
runIO $ findInPath ids idx
installedPackages :: IO [String]
installedPackages = do
idir <- getIdrisLibDir
filterM (goodDir idir) =<< dirContents idir
where
allFilesInDir base fp = do
let fullpath = base </> fp
isDir <- doesDirectoryExist' fullpath
if isDir
then fmap concat (mapM (allFilesInDir fullpath) =<< dirContents fullpath)
else return [fp]
dirContents = fmap (filter (not . (`elem` [".", ".."]))) . getDirectoryContents
goodDir idir d = any (".ibc" `isSuffixOf`) <$> allFilesInDir idir d
-- Case sensitive file existence check for Mac OS X.
doesFileExist' :: FilePath -> IO Bool
doesFileExist' = caseSensitive doesFileExist
-- Case sensitive directory existence check for Mac OS X.
doesDirectoryExist' :: FilePath -> IO Bool
doesDirectoryExist' = caseSensitive doesDirectoryExist
caseSensitive :: (FilePath -> IO Bool) -> FilePath -> IO Bool
caseSensitive existsCheck name =
do exists <- existsCheck name
if exists
then do contents <- getDirectoryContents (takeDirectory name)
return $ (takeFileName name) `elem` contents
else return False
| bkoropoff/Idris-dev | src/Idris/Imports.hs | bsd-3-clause | 4,614 | 0 | 15 | 1,785 | 1,155 | 584 | 571 | 88 | 4 |
-- |
-- Module : Graphics.Formats.Assimp
-- Copyright : (c) Joel Burget 2011-2012
-- License : BSD3
--
-- Maintainer : Joel Burget <[email protected]>
-- Stability : experimental
-- Portability : non-portable
module Graphics.Formats.Assimp (
module Graphics.Formats.Assimp.Anim
, module Graphics.Formats.Assimp.Camera
, module Graphics.Formats.Assimp.Color4D
, module Graphics.Formats.Assimp.Config
, module Graphics.Formats.Assimp.Fun
, module Graphics.Formats.Assimp.Light
, module Graphics.Formats.Assimp.Material
, module Graphics.Formats.Assimp.Matrix
, module Graphics.Formats.Assimp.Mesh
, module Graphics.Formats.Assimp.PostProcess
, module Graphics.Formats.Assimp.Quaternion
, module Graphics.Formats.Assimp.Scene
, module Graphics.Formats.Assimp.Texture
, module Graphics.Formats.Assimp.Types
, module Graphics.Formats.Assimp.Version
) where
import Graphics.Formats.Assimp.Anim
import Graphics.Formats.Assimp.Camera
import Graphics.Formats.Assimp.Color4D
import Graphics.Formats.Assimp.Config
import Graphics.Formats.Assimp.Fun
import Graphics.Formats.Assimp.Light
import Graphics.Formats.Assimp.Material
import Graphics.Formats.Assimp.Matrix
import Graphics.Formats.Assimp.Mesh
import Graphics.Formats.Assimp.PostProcess
import Graphics.Formats.Assimp.Quaternion
import Graphics.Formats.Assimp.Scene
import Graphics.Formats.Assimp.Texture
import Graphics.Formats.Assimp.Types
import Graphics.Formats.Assimp.Version
| haraldsteinlechner/assimp | Graphics/Formats/Assimp.hs | bsd-3-clause | 1,479 | 0 | 5 | 161 | 242 | 179 | 63 | 31 | 0 |
module Plugins (
FrontendPlugin(..), defaultFrontendPlugin,
Plugin(..), CommandLineOption,
defaultPlugin
) where
-- import CoreMonad ( CoreToDo, CoreM )
-- import TcRnTypes ( TcPlugin )
-- import GhcMonad
-- import DriverPhases
type CoreM a = Maybe a
type Ghc a = Maybe a
type CoreToDo = Int
type Phase = Int
type TcPlugin = Int
-- | Command line options gathered from the -PModule.Name:stuff syntax
-- are given to you as this type
type CommandLineOption = String
-- | 'Plugin' is the core compiler plugin data type. Try to avoid
-- constructing one of these directly, and just modify some fields of
-- 'defaultPlugin' instead: this is to try and preserve source-code
-- compatability when we add fields to this.
--
-- Nonetheless, this API is preliminary and highly likely to change in
-- the future.
data Plugin = Plugin {
installCoreToDos :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
-- ^ Modify the Core pipeline that will be used for compilation.
-- This is called as the Core pipeline is built for every module
-- being compiled, and plugins get the opportunity to modify the
-- pipeline in a nondeterministic order.
, tcPlugin :: [CommandLineOption] -> Maybe TcPlugin
-- ^ An optional typechecker plugin, which may modify the
-- behaviour of the constraint solver.
}
-- | Default plugin: does nothing at all! For compatability reasons
-- you should base all your plugin definitions on this default value.
defaultPlugin :: Plugin
defaultPlugin = Plugin {
installCoreToDos = const return
, tcPlugin = const Nothing
}
type FrontendPluginAction = [String] -> [(String, Maybe Phase)] -> Ghc ()
data FrontendPlugin = FrontendPlugin {
frontend :: FrontendPluginAction
}
defaultFrontendPlugin :: FrontendPlugin
defaultFrontendPlugin = FrontendPlugin { frontend = \_ _ -> return () }
| tolysz/prepare-ghcjs | spec-lts8/ghc/main/Plugins.hs | bsd-3-clause | 1,892 | 0 | 12 | 385 | 254 | 160 | 94 | 22 | 1 |
{-# LANGUAGE NoMonomorphismRestriction, FlexibleContexts, FlexibleInstances, TypeSynonymInstances, DeriveDataTypeable #-}
module PTS.Error
( Errors
, PTSError (..)
, Position (..)
, annotatePos
, annotateCode
, showErrors
, strMsg
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Errors.Class
import Control.Monad.Trans.Error (ErrorList (..))
import Data.Char
import Data.Data
import Data.List (intercalate)
import Data.Typeable
import Text.Printf (printf)
data PTSError
= Error (Maybe Position) (Maybe String) [String] (Maybe [String])
deriving (Show, Eq)
type Errors = [PTSError]
data Position
= Position String Int Int Int Int
deriving (Show, Eq, Data, Typeable)
instance ErrorList PTSError where
listMsg msg = pure (Error empty (pure msg) empty empty)
annotateError p' e' m' c' = annotate (map update) where
update (Error p e m c) = Error (p <|> p') (e <|> e') (m <|> m') (c <|> c')
annotatePos p = annotateError (pure p) empty empty empty
annotateErr e = annotateError empty (pure e) empty empty
annotateMsg m = annotateError empty empty (pure m) empty
annotateCode c = annotateError empty empty empty (pure c)
showErrors :: Errors -> String
showErrors = unlines . map showError
errorPrefix = ""
moreLinePrefix = " "
showError :: PTSError -> String
showError (Error p e m c) = unlines allLines where
allLines = firstLine : moreLines
firstLine = maybePosition ++ head maybeError
moreLines = map (moreLinePrefix ++) (tail maybeError ++ maybeSource ++ maybeMessages)
maybePosition = maybe "" ((++ " ") . showPosition) p
maybeError = lines $ maybe "Unknown Error" id e
maybeSource = maybe [] (" " :) (showSource <$> p <*> c)
maybeMessages = m
showSource (Position f r1 r2 c1 c2) src = result where
result | r1 /= r2 = []
| otherwise = mark c1 c2 70 (src !! pred r1)
showPosition :: Position -> String
showPosition (Position f r1 r2 c1 c2)
= printf "%s:%d.%d-%d.%d:" f r1 c1 r2 c2
mark :: Int -> Int -> Int -> String -> [String]
mark c1 c2 width line = [code, mark] where
(leaveOut, keep, pre, post, markerLength) = compress c1 c2 width line
code = pre ++ (take keep . drop leaveOut $ line) ++ post
mark = replicate (c1 - leaveOut + length pre - 1) ' '
++ replicate markerLength '^'
compress :: Int -> Int -> Int -> String -> (Int, Int, String, String, Int)
compress c1 c2 width text = result where
prespace = min c1 (length . takeWhile isSpace $ text)
postspace = length . takeWhile isSpace . reverse . drop c2 $ text
cropped = drop prespace . take (length text {- - prespace -} - postspace) $ text
cc1 = c1 - prespace
cc2 = c2 - prespace
tlen = length cropped
clen = c2 - c1 + 1
left = ((width - clen) + 1) `div` 2
right = (width - clen) `div` 2
result | tlen <= width = (prespace, tlen, "", "", clen)
| cc1 == 1 && clen > width - 3 = (prespace, width - 3, "", "...", width)
| cc1 > 1 && clen > width - 6 = (c1 - 1, width - 6, "...", "...", width - 3)
| cc1 - 1 <= left = (prespace, width - 3, "", "...", clen)
| cc2 <= right = (prespace + tlen - width + 3, width - 3, "...", "", clen)
| otherwise = (c1 - 1 - left + 3, width - 6, "...", "...", clen)
| Toxaris/pts | src-lib/PTS/Error.hs | bsd-3-clause | 3,249 | 0 | 13 | 727 | 1,318 | 707 | 611 | 75 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.Output (
-- * The Output Widget
OutputWidget,
-- * Constructor
mkOutputWidget,
-- * Using the output widget
appendOutput,
clearOutput,
clearOutput_,
replaceOutput,
) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (when, join)
import Data.Aeson
import Data.HashMap.Strict as HM
import Data.IORef (newIORef)
import Data.Text (Text)
import Data.Vinyl (Rec(..), (<+>))
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
-- | An 'OutputWidget' represents a Output widget from IPython.html.widgets.
type OutputWidget = IPythonWidget OutputType
-- | Create a new output widget
mkOutputWidget :: IO OutputWidget
mkOutputWidget = do
-- Default properties, with a random uuid
uuid <- U.random
let widgetState = WidgetState $ defaultDOMWidget "OutputView"
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
initData = object ["model_name" .= str "WidgetModel"]
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget initData $ toJSON widgetState
-- Return the image widget
return widget
-- | Append to the output widget
appendOutput :: IHaskellDisplay a => OutputWidget -> a -> IO ()
appendOutput widget out = do
disp <- display out
widgetPublishDisplay widget disp
-- | Clear the output widget immediately
clearOutput :: OutputWidget -> IO ()
clearOutput widget = widgetClearOutput widget False
-- | Clear the output widget on next append
clearOutput_ :: OutputWidget -> IO ()
clearOutput_ widget = widgetClearOutput widget True
-- | Replace the currently displayed output for output widget
replaceOutput :: IHaskellDisplay a => OutputWidget -> a -> IO ()
replaceOutput widget d = do
clearOutput_ widget
appendOutput widget d
instance IHaskellDisplay OutputWidget where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget OutputWidget where
getCommUUID = uuid
| FranklinChen/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Output.hs | mit | 2,349 | 0 | 13 | 509 | 454 | 244 | 210 | 50 | 1 |
{-# LANGUAGE RankNTypes, FlexibleInstances, FlexibleContexts, TypeOperators, MultiParamTypeClasses, ConstraintKinds, ScopedTypeVariables #-}
{- |
Module : ApplyTransCFJava
Description : Translation of FCore to Java with Apply-opt
Copyright : (c) 2014—2015 The F2J Project Developers (given in AUTHORS.txt)
License : BSD3
Maintainer : Jeremy <[email protected]>, Tomas <[email protected]>
Stability : experimental
Portability : non-portable (MPTC)
This module augments the basic translation of FCore to Java with
multi-argument function optimization.
-}
module ApplyTransCFJava where
-- TODO: isolate all hardcoded strings to StringPrefixes (e.g. Fun)
import qualified Language.Java.Syntax as J
import BaseTransCFJava
import ClosureF
import Inheritance
import JavaEDSL
import MonadLib
import StringPrefixes
data ApplyOptTranslate m = NT {toT :: Translate m}
instance (:<) (ApplyOptTranslate m) (Translate m) where
up = up . toT
instance (:<) (ApplyOptTranslate m) (ApplyOptTranslate m) where
up = id
isMultiBinder :: EScope Int (Var, Type Int) -> Bool
isMultiBinder (Type _ _) = False
isMultiBinder (Kind _) = True
isMultiBinder (Body _) = True
-- main translation function
transApply :: (MonadState Int m,
MonadReader Int m,
MonadReader InitVars m,
selfType :< ApplyOptTranslate m,
selfType :< Translate m)
=> Mixin selfType (Translate m) (ApplyOptTranslate m)
transApply this super = NT {toT = super {
translateM =
\e -> case e of
App e1 e2 -> do (n :: Int) <- ask
let flag = case e1 of Var _ _ -> True
_ -> False
translateApply (up this)
flag
(local (\(_ :: Int) -> n + 1) $ translateM (up this) e1)
(local (\(_ :: Int) -> 0) $ translateM (up this) e2)
_ -> translateM super e,
genClosureVar =
\flag arity j1 ->
do (n :: Int) <- ask
if flag && arity > n
then return $ J.MethodInv (J.PrimaryMethodCall (unwrap j1) [] (J.Ident "clone") [])
else return (unwrap j1),
translateScopeTyp = \x1 f initVars nextInClosure m closureClass ->
if isMultiBinder nextInClosure
then do (initVars' :: InitVars) <- ask
translateScopeTyp super x1 f (initVars ++ initVars') nextInClosure (local (\(_ :: InitVars) -> []) m) closureClass
else do (s,je,t1) <- local (initVars ++) m
let refactored = modifiedScopeTyp (unwrap je) s x1 f closureClass
return (refactored,t1),
genApply = \f t x y z ->
do applyGen <- genApply super f t x y z
return [bStmt $ J.IfThen (fieldAccess f "hasApply") (J.StmtBlock (block applyGen))],
genClone = return True
}}
modifiedScopeTyp :: J.Exp -> [J.BlockStmt] -> Int -> Int -> String -> [J.BlockStmt]
modifiedScopeTyp oexpr ostmts x1 f closureClass = completeClosure
where closureType' = classTy closureClass
currentInitialDeclaration = memberDecl $ fieldDecl closureType' (varDecl (localvarstr ++ show x1) J.This)
setApplyFlag = assignField (fieldAccExp (left $ var (localvarstr ++ show x1)) "hasApply") (J.Lit (J.Boolean False))
fc = f
completeClosure = [localClassDecl (closureTransName ++ show fc) closureClass
(closureBodyGen
[currentInitialDeclaration, J.InitDecl False (block (setApplyFlag : ostmts ++ [bsAssign (name [closureOutput]) oexpr]))]
[]
fc
True
closureType')]
-- Alternate version of transApply that works with Stack translation
transAS :: (MonadState Int m,
MonadReader Int m,
MonadReader Bool m,
MonadReader InitVars m,
selfType :< ApplyOptTranslate m,
selfType :< Translate m)
=> Mixin selfType (Translate m) (ApplyOptTranslate m)
transAS this super = NT {toT = (up (transApply this super)) {
translateM =
\e -> case e of
App e1 e2 -> do (n :: Int) <- ask
let flag = case e1 of Var _ _ -> True
_ -> False
translateApply (up this)
flag
(local (False &&) $ local (\ (_ :: Int) -> n + 1) (translateM (up this) e1))
(local (False &&) $ local (\(_ :: Int) -> 0) (translateM (up this) e2))
_ -> translateM super e,
genApply = \f t tempOut outType z ->
do applyGen <- genApply super f t tempOut outType z
let tempDecl = localVar outType
(varDecl tempOut (case outType of
J.PrimType J.IntT -> J.Lit (J.Int 0)
_ -> J.Lit J.Null))
let elseDecl = bsAssign (name [tempOut]) (cast outType (J.FieldAccess (fieldAccExp (cast z f) closureOutput)))
if length applyGen == 2
then return applyGen
else return [tempDecl, bStmt $ J.IfThenElse (fieldAccess f "hasApply")
(J.StmtBlock (block applyGen))
(J.StmtBlock (block [elseDecl]))]
}}
| bixuanzju/fcore | lib/ApplyTransCFJava.hs | bsd-2-clause | 5,629 | 0 | 25 | 2,030 | 1,601 | 825 | 776 | 95 | 5 |
{-# LANGUAGE TemplateHaskell #-}
{-| Implementation of the Ganeti Ssconf interface.
-}
{-
Copyright (C) 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Ssconf
( SSKey(..)
, sSKeyToRaw
, sSKeyFromRaw
, hvparamsSSKey
, getPrimaryIPFamily
, parseNodesVmCapable
, getNodesVmCapable
, getMasterCandidatesIps
, getMasterNode
, parseHypervisorList
, getHypervisorList
, parseEnabledUserShutdown
, getEnabledUserShutdown
, keyToFilename
, sSFilePrefix
, SSConf(..)
, emptySSConf
) where
import Control.Arrow ((&&&))
import Control.Applicative ((<$>))
import Control.Exception
import Control.Monad (forM, liftM)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified Network.Socket as Socket
import System.FilePath ((</>))
import System.IO.Error (isDoesNotExistError)
import qualified Text.JSON as J
import qualified AutoConf
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import qualified Ganeti.ConstantUtils as CU
import Ganeti.JSON (GenericContainer(..), HasStringRepr(..))
import qualified Ganeti.Path as Path
import Ganeti.THH
import Ganeti.Types (Hypervisor)
import qualified Ganeti.Types as Types
import Ganeti.Utils
-- * Reading individual ssconf entries
-- | Maximum ssconf file size we support.
maxFileSize :: Int
maxFileSize = 131072
-- | ssconf file prefix, re-exported from Constants.
sSFilePrefix :: FilePath
sSFilePrefix = C.ssconfFileprefix
$(declareLADT ''String "SSKey" (
map (ssconfConstructorName &&& id) . CU.toList $ C.validSsKeys
))
instance HasStringRepr SSKey where
fromStringRepr = sSKeyFromRaw
toStringRepr = sSKeyToRaw
-- | For a given hypervisor get the corresponding SSConf key that contains its
-- parameters.
--
-- The corresponding SSKeys are generated automatically by TH, but since we
-- don't have convenient infrastructure for generating this function, it's just
-- manual. All constructors must be given explicitly so that adding another
-- hypervisor will trigger "incomplete pattern" warning and force the
-- corresponding addition.
hvparamsSSKey :: Types.Hypervisor -> SSKey
hvparamsSSKey Types.Kvm = SSHvparamsKvm
hvparamsSSKey Types.XenPvm = SSHvparamsXenPvm
hvparamsSSKey Types.Chroot = SSHvparamsChroot
hvparamsSSKey Types.XenHvm = SSHvparamsXenHvm
hvparamsSSKey Types.Lxc = SSHvparamsLxc
hvparamsSSKey Types.Fake = SSHvparamsFake
-- | Convert a ssconf key into a (full) file path.
keyToFilename :: FilePath -- ^ Config path root
-> SSKey -- ^ Ssconf key
-> FilePath -- ^ Full file name
keyToFilename cfgpath key =
cfgpath </> sSFilePrefix ++ sSKeyToRaw key
-- | Runs an IO action while transforming any error into 'Bad'
-- values. It also accepts an optional value to use in case the error
-- is just does not exist.
catchIOErrors :: Maybe a -- ^ Optional default
-> IO a -- ^ Action to run
-> IO (Result a)
catchIOErrors def action =
Control.Exception.catch
(do
result <- action
return (Ok result)
) (\err -> let bad_result = Bad (show err)
in return $ if isDoesNotExistError err
then maybe bad_result Ok def
else bad_result)
-- | Read an ssconf file.
readSSConfFile :: Maybe FilePath -- ^ Optional config path override
-> Maybe String -- ^ Optional default value
-> SSKey -- ^ Desired ssconf key
-> IO (Result String)
readSSConfFile optpath def key = do
dpath <- Path.dataDir
result <- catchIOErrors def . readFile .
keyToFilename (fromMaybe dpath optpath) $ key
return (liftM (take maxFileSize) result)
-- | Parses a key-value pair of the form "key=value" from 'str', fails
-- with 'desc' otherwise.
parseKeyValue :: Monad m => String -> String -> m (String, String)
parseKeyValue desc str =
case sepSplit '=' str of
[key, value] -> return (key, value)
_ -> fail $ "Failed to parse key-value pair for " ++ desc
-- | Parses a string containing an IP family
parseIPFamily :: Int -> Result Socket.Family
parseIPFamily fam | fam == AutoConf.pyAfInet4 = Ok Socket.AF_INET
| fam == AutoConf.pyAfInet6 = Ok Socket.AF_INET6
| otherwise = Bad $ "Unknown af_family value: " ++ show fam
-- | Read the primary IP family.
getPrimaryIPFamily :: Maybe FilePath -> IO (Result Socket.Family)
getPrimaryIPFamily optpath = do
result <- readSSConfFile optpath
(Just (show AutoConf.pyAfInet4))
SSPrimaryIpFamily
return (liftM rStripSpace result >>=
tryRead "Parsing af_family" >>= parseIPFamily)
-- | Parse the nodes vm capable value from a 'String'.
parseNodesVmCapable :: String -> Result [(String, Bool)]
parseNodesVmCapable str =
forM (lines str) $ \line -> do
(key, val) <- parseKeyValue "Parsing node_vm_capable" line
val' <- tryRead "Parsing value of node_vm_capable" val
return (key, val')
-- | Read and parse the nodes vm capable.
getNodesVmCapable :: Maybe FilePath -> IO (Result [(String, Bool)])
getNodesVmCapable optPath =
(parseNodesVmCapable =<<) <$> readSSConfFile optPath Nothing SSNodeVmCapable
-- | Read the list of IP addresses of the master candidates of the cluster.
getMasterCandidatesIps :: Maybe FilePath -> IO (Result [String])
getMasterCandidatesIps optPath = do
result <- readSSConfFile optPath Nothing SSMasterCandidatesIps
return $ liftM lines result
-- | Read the name of the master node.
getMasterNode :: Maybe FilePath -> IO (Result String)
getMasterNode optPath = do
result <- readSSConfFile optPath Nothing SSMasterNode
return (liftM rStripSpace result)
-- | Parse the list of enabled hypervisors from a 'String'.
parseHypervisorList :: String -> Result [Hypervisor]
parseHypervisorList str =
mapM Types.hypervisorFromRaw $ lines str
-- | Read and parse the list of enabled hypervisors.
getHypervisorList :: Maybe FilePath -> IO (Result [Hypervisor])
getHypervisorList optPath =
(parseHypervisorList =<<) <$>
readSSConfFile optPath Nothing SSHypervisorList
-- | Parse whether user shutdown is enabled from a 'String'.
parseEnabledUserShutdown :: String -> Result Bool
parseEnabledUserShutdown str =
tryRead "Parsing enabled_user_shutdown" (rStripSpace str)
-- | Read and parse whether user shutdown is enabled.
getEnabledUserShutdown :: Maybe FilePath -> IO (Result Bool)
getEnabledUserShutdown optPath =
(parseEnabledUserShutdown =<<) <$>
readSSConfFile optPath Nothing SSEnabledUserShutdown
-- * Working with the whole ssconf map
-- | The data type used for representing the ssconf.
newtype SSConf = SSConf { getSSConf :: M.Map SSKey [String] }
deriving (Eq, Ord, Show)
instance J.JSON SSConf where
showJSON = J.showJSON . GenericContainer . getSSConf
readJSON = liftM (SSConf . fromContainer) . J.readJSON
emptySSConf :: SSConf
emptySSConf = SSConf M.empty
| bitemyapp/ganeti | src/Ganeti/Ssconf.hs | bsd-2-clause | 8,257 | 0 | 14 | 1,665 | 1,458 | 786 | 672 | 135 | 2 |
module Foo where
import Prelude hiding (putStr)
import qualified System.IO
import Data.Maybe
import qualified ValidSubs
ps :: String -> IO ()
ps = putStrLn
test :: [Maybe a] -> [a]
test = _
test2 :: Integer -> ValidSubs.Moo
test2 = _
main :: IO ()
main = _ "hello, world"
| ezyang/ghc | testsuite/tests/typecheck/should_compile/valid_substitutions.hs | bsd-3-clause | 278 | 0 | 7 | 56 | 104 | 60 | 44 | 13 | 1 |
main = do
print (sqrt (-7 :: Double))
print (sqrt (-7 :: Float))
| sdiehl/ghc | libraries/base/tests/Numeric/sqrt.hs | bsd-3-clause | 73 | 1 | 11 | 21 | 49 | 23 | 26 | 3 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Foreign
-- Copyright : (c) The University of Glasgow, 2008-2011
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable
--
-- Foreign marshalling support for CStrings with configurable encodings
--
-----------------------------------------------------------------------------
module GHC.Foreign (
-- * C strings with a configurable encoding
-- conversion of C strings into Haskell strings
--
peekCString, -- :: TextEncoding -> CString -> IO String
peekCStringLen, -- :: TextEncoding -> CStringLen -> IO String
-- conversion of Haskell strings into C strings
--
newCString, -- :: TextEncoding -> String -> IO CString
newCStringLen, -- :: TextEncoding -> String -> IO CStringLen
-- conversion of Haskell strings into C strings using temporary storage
--
withCString, -- :: TextEncoding -> String -> (CString -> IO a) -> IO a
withCStringLen, -- :: TextEncoding -> String -> (CStringLen -> IO a) -> IO a
charIsRepresentable, -- :: TextEncoding -> Char -> IO Bool
) where
import Foreign.Marshal.Array
import Foreign.C.Types
import Foreign.Ptr
import Foreign.Storable
import Data.Word
-- Imports for the locale-encoding version of marshallers
import Control.Monad
import Data.Tuple (fst)
import Data.Maybe
import {-# SOURCE #-} System.Posix.Internals (puts)
import GHC.Show ( show )
import Foreign.Marshal.Alloc
import Foreign.ForeignPtr
import GHC.Err (undefined)
import GHC.List
import GHC.Num
import GHC.Base
import GHC.IO
import GHC.IO.Exception
import GHC.IO.Buffer
import GHC.IO.Encoding.Types
c_DEBUG_DUMP :: Bool
c_DEBUG_DUMP = False
putDebugMsg :: String -> IO ()
putDebugMsg | c_DEBUG_DUMP = puts
| otherwise = const (return ())
-- These definitions are identical to those in Foreign.C.String, but copied in here to avoid a cycle:
type CString = Ptr CChar
type CStringLen = (Ptr CChar, Int)
-- exported functions
-- ------------------
-- | Marshal a NUL terminated C string into a Haskell string.
--
peekCString :: TextEncoding -> CString -> IO String
peekCString enc cp = do
sz <- lengthArray0 nUL cp
peekEncodedCString enc (cp, sz * cCharSize)
-- | Marshal a C string with explicit length into a Haskell string.
--
peekCStringLen :: TextEncoding -> CStringLen -> IO String
peekCStringLen = peekEncodedCString
-- | Marshal a Haskell string into a NUL terminated C string.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * new storage is allocated for the C string and must be
-- explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCString :: TextEncoding -> String -> IO CString
newCString enc = liftM fst . newEncodedCString enc True
-- | Marshal a Haskell string into a C string (ie, character array) with
-- explicit length information.
--
-- * new storage is allocated for the C string and must be
-- explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCStringLen :: TextEncoding -> String -> IO CStringLen
newCStringLen enc = newEncodedCString enc False
-- | Marshal a Haskell string into a NUL terminated C string using temporary
-- storage.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCString :: TextEncoding -> String -> (CString -> IO a) -> IO a
withCString enc s act = withEncodedCString enc True s $ \(cp, _sz) -> act cp
-- | Marshal a Haskell string into a C string (ie, character array)
-- in temporary storage, with explicit length information.
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCStringLen :: TextEncoding -> String -> (CStringLen -> IO a) -> IO a
withCStringLen enc = withEncodedCString enc False
-- | Determines whether a character can be accurately encoded in a 'CString'.
--
-- Pretty much anyone who uses this function is in a state of sin because
-- whether or not a character is encodable will, in general, depend on the
-- context in which it occurs.
charIsRepresentable :: TextEncoding -> Char -> IO Bool
charIsRepresentable enc c = withCString enc [c] (fmap (== [c]) . peekCString enc) `catchException` (\e -> let _ = e :: IOException in return False)
-- auxiliary definitions
-- ----------------------
-- C's end of string character
nUL :: CChar
nUL = 0
-- Size of a CChar in bytes
cCharSize :: Int
cCharSize = sizeOf (undefined :: CChar)
{-# INLINE peekEncodedCString #-}
peekEncodedCString :: TextEncoding -- ^ Encoding of CString
-> CStringLen
-> IO String -- ^ String in Haskell terms
peekEncodedCString (TextEncoding { mkTextDecoder = mk_decoder }) (p, sz_bytes)
= bracket mk_decoder close $ \decoder -> do
let chunk_size = sz_bytes `max` 1 -- Decode buffer chunk size in characters: one iteration only for ASCII
from0 <- fmap (\fp -> bufferAdd sz_bytes (emptyBuffer fp sz_bytes ReadBuffer)) $ newForeignPtr_ (castPtr p)
to <- newCharBuffer chunk_size WriteBuffer
let go iteration from = do
(why, from', to') <- encode decoder from to
if isEmptyBuffer from'
then
-- No input remaining: @why@ will be InputUnderflow, but we don't care
withBuffer to' $ peekArray (bufferElems to')
else do
-- Input remaining: what went wrong?
putDebugMsg ("peekEncodedCString: " ++ show iteration ++ " " ++ show why)
(from'', to'') <- case why of InvalidSequence -> recover decoder from' to' -- These conditions are equally bad because
InputUnderflow -> recover decoder from' to' -- they indicate malformed/truncated input
OutputUnderflow -> return (from', to') -- We will have more space next time round
putDebugMsg ("peekEncodedCString: from " ++ summaryBuffer from ++ " " ++ summaryBuffer from' ++ " " ++ summaryBuffer from'')
putDebugMsg ("peekEncodedCString: to " ++ summaryBuffer to ++ " " ++ summaryBuffer to' ++ " " ++ summaryBuffer to'')
to_chars <- withBuffer to'' $ peekArray (bufferElems to'')
fmap (to_chars++) $ go (iteration + 1) from''
go (0 :: Int) from0
{-# INLINE withEncodedCString #-}
withEncodedCString :: TextEncoding -- ^ Encoding of CString to create
-> Bool -- ^ Null-terminate?
-> String -- ^ String to encode
-> (CStringLen -> IO a) -- ^ Worker that can safely use the allocated memory
-> IO a
withEncodedCString (TextEncoding { mkTextEncoder = mk_encoder }) null_terminate s act
= bracket mk_encoder close $ \encoder -> withArrayLen s $ \sz p -> do
from <- fmap (\fp -> bufferAdd sz (emptyBuffer fp sz ReadBuffer)) $ newForeignPtr_ p
let go iteration to_sz_bytes = do
putDebugMsg ("withEncodedCString: " ++ show iteration)
allocaBytes to_sz_bytes $ \to_p -> do
mb_res <- tryFillBufferAndCall encoder null_terminate from to_p to_sz_bytes act
case mb_res of
Nothing -> go (iteration + 1) (to_sz_bytes * 2)
Just res -> return res
-- If the input string is ASCII, this value will ensure we only allocate once
go (0 :: Int) (cCharSize * (sz + 1))
{-# INLINE newEncodedCString #-}
newEncodedCString :: TextEncoding -- ^ Encoding of CString to create
-> Bool -- ^ Null-terminate?
-> String -- ^ String to encode
-> IO CStringLen
newEncodedCString (TextEncoding { mkTextEncoder = mk_encoder }) null_terminate s
= bracket mk_encoder close $ \encoder -> withArrayLen s $ \sz p -> do
from <- fmap (\fp -> bufferAdd sz (emptyBuffer fp sz ReadBuffer)) $ newForeignPtr_ p
let go iteration to_p to_sz_bytes = do
putDebugMsg ("newEncodedCString: " ++ show iteration)
mb_res <- tryFillBufferAndCall encoder null_terminate from to_p to_sz_bytes return
case mb_res of
Nothing -> do
let to_sz_bytes' = to_sz_bytes * 2
to_p' <- reallocBytes to_p to_sz_bytes'
go (iteration + 1) to_p' to_sz_bytes'
Just res -> return res
-- If the input string is ASCII, this value will ensure we only allocate once
let to_sz_bytes = cCharSize * (sz + 1)
to_p <- mallocBytes to_sz_bytes
go (0 :: Int) to_p to_sz_bytes
tryFillBufferAndCall :: TextEncoder dstate -> Bool -> Buffer Char -> Ptr Word8 -> Int
-> (CStringLen -> IO a) -> IO (Maybe a)
tryFillBufferAndCall encoder null_terminate from0 to_p to_sz_bytes act = do
to_fp <- newForeignPtr_ to_p
go (0 :: Int) (from0, emptyBuffer to_fp to_sz_bytes WriteBuffer)
where
go iteration (from, to) = do
(why, from', to') <- encode encoder from to
putDebugMsg ("tryFillBufferAndCall: " ++ show iteration ++ " " ++ show why ++ " " ++ summaryBuffer from ++ " " ++ summaryBuffer from')
if isEmptyBuffer from'
then if null_terminate && bufferAvailable to' == 0
then return Nothing -- We had enough for the string but not the terminator: ask the caller for more buffer
else do
-- Awesome, we had enough buffer
let bytes = bufferElems to'
withBuffer to' $ \to_ptr -> do
when null_terminate $ pokeElemOff to_ptr (bufR to') 0
fmap Just $ act (castPtr to_ptr, bytes) -- NB: the length information is specified as being in *bytes*
else case why of -- We didn't consume all of the input
InputUnderflow -> recover encoder from' to' >>= go (iteration + 1) -- These conditions are equally bad
InvalidSequence -> recover encoder from' to' >>= go (iteration + 1) -- since the input was truncated/invalid
OutputUnderflow -> return Nothing -- Oops, out of buffer during decoding: ask the caller for more
| mightymoose/liquidhaskell | benchmarks/ghc-7.4.1/Foreign.hs | bsd-3-clause | 10,706 | 0 | 25 | 2,740 | 2,052 | 1,076 | 976 | 137 | 5 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module Cook.Ci.Process
( runInteractiveProcess
)
where
import Control.Concurrent
import Control.Monad (when)
import System.Exit (ExitCode(..))
import System.IO
import qualified Control.Exception as C
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy as BSL
import qualified System.Process as P
runInteractiveProcess :: String
-> [String]
-> Maybe FilePath
-> (BS.ByteString -> IO ())
-> BSL.ByteString -- ^ standard input
-> IO ( ExitCode
, BSL.ByteString
, BSL.ByteString) -- ^ (exitcode, stdout, stderr)
runInteractiveProcess process args workDir errorLogger input =
C.catch (C.bracketOnError startProcess closeProcess withProcess)
(\(exc::C.IOException) ->
do errorLogger (BSC.pack $ msg ++ " failed: " ++ show exc)
C.throwIO exc)
where
msg = ("running process " ++ process)
startProcess = P.runInteractiveProcess process args workDir Nothing
closeProcess (_inh, _outh, _errh, pid) =
do P.terminateProcess pid
_ <- P.waitForProcess pid
return ()
withProcess (inh, outh, errh, pid) =
do hSetBinaryMode inh True
hSetBinaryMode outh True
hSetBinaryMode errh True
getOut <- startHandleReader outh
getErr <- startHandleReader errh
threadDelay 100000 --- 100 ms
-- now write and flush any input
when (not (BSL.null input)) $
do errorLogger (BSC.pack $ "Writing " ++ show (BSL.length input) ++ " to stdin of process.")
BSL.hPutStr inh input
errorLogger ("Flushing stdin of process.")
hFlush inh
errorLogger ("Closing stdin of process.")
hClose inh -- done with stdin
errorLogger ("Done closing stdin of process.")
-- wait on the output
out <- getOut
errorLogger ("Done waiting for out")
err <- getErr
errorLogger ("Done waiting for err")
ecode <- P.waitForProcess pid
return (ecode, out, err)
startHandleReader h =
do resMVar <- newEmptyMVar
_ <- forkIO $
try $ BS.hGetContents h >>= putMVar resMVar . (BSL.fromChunks . (:[]))
return (takeMVar resMVar)
try :: IO () -> IO ()
try action =
C.catch action $
\(exc :: C.IOException) ->
do errorLogger (BSC.pack $ msg ++ ": " ++ show exc)
return ()
| factisresearch/cookci | src/Cook/Ci/Process.hs | mit | 2,860 | 0 | 19 | 1,032 | 716 | 363 | 353 | 64 | 1 |
module Misc(anyValue) where
-- just like Prelude.any but returns the item as Maybe a
anyValue :: (a -> Maybe b) -> [a] -> Maybe b
anyValue _ [] = Nothing
anyValue predicate (i:rest) = case predicate i of
Nothing -> anyValue predicate rest
x -> x
| Noeda/Megaman | src/Misc.hs | mit | 318 | 0 | 8 | 118 | 92 | 48 | 44 | 6 | 2 |
-- Copyright 2013 Thomas Szczarkowski
import Network.HTTP.Server
import Network.HTTP.Server.Logger
import Network.URI
import Codec.Binary.UTF8.String
import Data.Word
import Data.List
import Control.Concurrent
import Control.DeepSeq
import Control.Applicative
import Control.Arrow
import Control.Monad
import System.Environment
import Data.Time.Clock.POSIX
import Text.Parsec
import Text.ParserCombinators.Parsec
import Bytes
import CryptoRandom
import OpenSSL.Random
import MAC
data Params = Params { getHmacKey :: [Word8], getDelay_us :: Int, getMac :: [Word8] }
-- ./TimingLeakServer delay_us
main = do
hmacKey <- Bytes.decode <$> cryptoRandomBytes 64
delay <- read <$> head <$> getArgs :: IO Int
-- precompute to save time
-- (imagine the server caches file MACs)
txt <- readFile "TimingLeakServer.hs" -- the file the timing attack targets
let mac = hmac hmacKey $ Bytes.decode txt
putStrLn $ "MAC: " ++ show (Bytes.encode mac :: Hex)
let params = Params hmacKey delay mac
serverWith defaultConfig { srvPort = 9000 } (handler params)
handler (Params hmacKey delay mac) sockAddr url request =
case parseQueryString (uriQuery $ rqURI request) of
Left _ -> return $ sendText BadRequest ""
Right pairs -> case sequence [join $ lookup "file" pairs,
join $ lookup "signature" pairs] of
Just (fn:sig:_) -> do eqp <- (insecureCompare delay) mac (Bytes.transcode $ Hex sig)
return $ if eqp
then sendText OK ""
else sendText InternalServerError ""
Nothing -> return $ sendText BadRequest ""
insecureCompare delay (a:as) (b:bs) = do
q <- preciseDelay delay
q `deepseq` (
if (a /= b)
then return False
else insecureCompare delay as bs)
insecureCompare _ _ _ = return True
parseQueryString qs =
parse query "" qs
where query = string "?" >>
pair `sepBy1` string "&"
pair = do key <- many1 (noneOf "?&=")
val <- optionMaybe (string "=" >>
many1 (noneOf "?&="))
return (key, val)
-- from http-server docs
sendText :: StatusCode -> String -> Response String
sendText s v = insertHeader HdrContentLength (show (length txt))
$ insertHeader HdrContentEncoding "UTF-8"
$ insertHeader HdrContentEncoding "text/plain"
$ (respond s :: Response String) { rspBody = txt }
where txt = v
-- OS sleep() is too imprecise;
-- this function spins in a loop
preciseDelay us =
let until t' = do
t <- microseconds
if (t > t') then return () else until t'
in microseconds >>= \t -> until (t+us)
microseconds = (fromIntegral . floor . (10^6*)) <$> getPOSIXTime
| tom-szczarkowski/matasano-crypto-puzzles-solutions | set4/TimingLeakServer.hs | mit | 2,992 | 2 | 17 | 935 | 852 | 435 | 417 | 65 | 4 |
{-# LANGUAGE
RecordWildCards ,
OverloadedStrings,
GADTs
#-}
{- |
Module : HSat.Problem.Internal
Description : Internal representation of Problem
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : [email protected]
Stability : experimental
Portability : Unknown
Exports the underlying representation of a 'Problem'
-}
module HSat.Problem.Internal (
Problem(..)
) where
import HSat.Printer
import HSat.Problem.ProblemExpr.Class
import HSat.Problem.Source
{-|
A 'Problem' represents both a problem expression and its source
-}
data Problem where
MkProblem :: {
-- | The 'Source' of the 'ProblemExpr'
source :: Source ,
-- | The 'ProblemExpr' describing the 'Problem'
problemExpr :: ProblemExpr
} -> Problem
instance Eq Problem where
(MkProblem s p) == (MkProblem s' p') = s == s' && p == p'
instance Show Problem where
showsPrec = show'
instance Printer Problem where
compact = printProblem Compact
noUnicode = printProblem NoUnicode
unicode = printProblem Unicode
printProblem :: PrinterType -> Problem -> Doc
printProblem pType MkProblem{..} =
preamble <>
space' <>
printSource <>
line <>
printExpr
where
preamble :: Doc
preamble = case pType of
Compact -> "Problem -"
_ -> "Problem:"
space' :: Doc
space' = case pType of
Compact -> space
_ -> line
printSource :: Doc
printSource = pTypeToDoc pType source
printExpr :: Doc
printExpr = pTypeToDoc pType problemExpr
| aburnett88/HSat | src/HSat/Problem/Internal.hs | mit | 1,594 | 0 | 9 | 425 | 284 | 158 | 126 | 41 | 3 |
{- |
Module : Language.Javascript.JMacro
Copyright : (c) Gershom Bazerman, 2010
License : BSD 3 Clause
Maintainer : [email protected]
Stability : experimental
Simple DSL for lightweight (untyped) programmatic generation of Javascript.
A number of examples are available in the source of "Language.Javascript.JMacro.Prelude".
Functions to generate generic RPC wrappers (using json serialization) are available in
"Language.Javascript.JMacro.Rpc".
usage:
> renderJs [$jmacro|fun id x -> x|]
The above produces the id function at the top level.
> renderJs [$jmacro|var id = \x -> x;|]
So does the above here. However, as id is brought into scope by the keyword var, you do not get a variable named id in the generated javascript, but a variable with an arbitrary unique identifier.
> renderJs [$jmacro|var !id = \x -> x;|]
The above, by using the bang special form in a var declaration, produces a variable that really is named id.
> renderJs [$jmacro|function id(x) {return x;}|]
The above is also id.
> renderJs [$jmacro|function !id(x) {return x;}|]
As is the above (with the correct name).
> renderJs [$jmacro|fun id x {return x;}|]
As is the above.
> renderJs [$jmacroE|foo(x,y)|]
The above is an expression representing the application of foo to x and y.
> renderJs [$jmacroE|foo x y|]]
As is the above.
> renderJs [$jmacroE|foo (x,y)|]
While the above is an error. (i.e. standard javascript function application cannot seperate the leading parenthesis of the argument from the function being applied)
> \x -> [$jmacroE|foo `(x)`|]
The above is a haskell expression that provides a function that takes an x, and yields an expression representing the application of foo to the value of x as transformed to a Javascript expression.
> [$jmacroE|\x ->`(foo x)`|]
Meanwhile, the above lambda is in Javascript, and brings the variable into scope both in javascript and in the enclosed antiquotes. The expression is a Javascript function that takes an x, and yields an expression produced by the application of the Haskell function foo as applied to the identifier x (which is of type JExpr -- i.e. a Javascript expression).
Other than that, the language is essentially Javascript (1.5). Note however that one must use semicolons in a principled fashion -- i.e. to end statements consistently. Otherwise, the parser will mistake the whitespace for a whitespace application, and odd things will occur. A further gotcha exists in regex literals, whicch cannot begin with a space. @x / 5 / 4@ parses as ((x / 5) / 4). However, @x /5 / 4@ will parse as x(/5 /, 4). Such are the perils of operators used as delimeters in the presence of whitespace application.
Additional features in jmacro (documented on the wiki) include an infix application operator, and an enhanced destructuring bind.
Additional datatypes can be marshalled to Javascript by proper instance declarations for the ToJExpr class.
An experimental typechecker is available in the "Language.Javascript.JMacro.Typed" module.
-}
-- module names have been changed for temporary inclusion in GHCJS tree
module Compiler.JMacro (
module Compiler.JMacro.Base,
module Compiler.JMacro.Lens,
module Compiler.JMacro.QQ
) where
import Compiler.JMacro.Base hiding (expr2stat)
import Compiler.JMacro.Lens
import Compiler.JMacro.QQ
| ghcjs/ghcjs | src/Compiler/JMacro.hs | mit | 3,334 | 0 | 5 | 564 | 55 | 38 | 17 | 7 | 0 |
module Language.MSH.CodeGenMonad where
import Control.Monad.State
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Language.MSH.CodeGen.Shared
type CodeGen = StateT StateEnv Q | mbg/monadic-state-hierarchies | Language/MSH/CodeGenMonad.hs | mit | 198 | 0 | 5 | 20 | 44 | 29 | 15 | 6 | 0 |
module Text.Pandoc.TikZ.Hash (hash) where
import Data.ByteString.Char8 (pack, unpack)
import Data.ByteString.Base16 (encode)
import qualified Crypto.Hash.SHA256 as SHA256
hash :: String -> String
hash = unpack . encode . SHA256.hash . pack
| claudio-mattera/pandoc-tikz | src/Text/Pandoc/TikZ/Hash.hs | mit | 252 | 0 | 7 | 41 | 75 | 47 | 28 | 6 | 1 |
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-}
module GetOpt.Declarative.EnvironmentSpec (spec) where
import Prelude ()
import Helper
import GetOpt.Declarative.Types
import GetOpt.Declarative.Environment
spec :: Spec
spec = do
describe "parseEnvironmentOption" $ do
context "with NoArg" $ do
let
option :: Option Bool
option = Option {
optionName = "some-flag"
, optionSetter = NoArg $ const True
}
it "accepts 'yes'" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "yes")] False option `shouldBe` Right True
it "rejects other values" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "no")] False option `shouldBe` invalidValue "FOO_SOME_FLAG" "no"
context "with Flag" $ do
let
option :: Option Bool
option = Option {
optionName = "some-flag"
, optionSetter = Flag $ \ value _ -> value
}
it "accepts 'yes'" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "yes")] False option `shouldBe` Right True
it "accepts 'no'" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "no")] True option `shouldBe` Right False
it "rejects other values" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "nay")] True option `shouldBe` invalidValue "FOO_SOME_FLAG" "nay"
context "with OptArg" $ do
let
option :: Option String
option = Option {
optionName = "some-flag"
, optionSetter = OptArg undefined $ \ (Just arg) _ -> guard (arg == "yes") >> Just arg
}
it "accepts valid values" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "yes")] "" option `shouldBe` Right "yes"
it "rejects invalid values" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "no")] "" option `shouldBe` invalidValue "FOO_SOME_FLAG" "no"
context "with Arg" $ do
let
option :: Option String
option = Option {
optionName = "some-flag"
, optionSetter = Arg undefined $ \ arg _ -> guard (arg == "yes") >> Just arg
}
it "accepts valid values" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "yes")] "" option `shouldBe` Right "yes"
it "rejects invalid values" $ do
parseEnvironmentOption "FOO" [("FOO_SOME_FLAG", "no")] "" option `shouldBe` invalidValue "FOO_SOME_FLAG" "no"
where
invalidValue name = Left . InvalidValue name
| hspec/hspec | hspec-core/test/GetOpt/Declarative/EnvironmentSpec.hs | mit | 2,555 | 0 | 23 | 694 | 690 | 352 | 338 | 53 | 1 |
module Pangram
( isPangram
) where
import Data.Char (toLower, isLetter)
import Data.HashSet (fromList, isSubsetOf)
isPangram :: String -> Bool
isPangram text = alphabet `isSubsetOf` letters
where
letters = fromList [toLower c | c <- text, isLetter c]
alphabet = fromList ['a' .. 'z'] | enolive/exercism | haskell/pangram/src/Pangram.hs | mit | 299 | 0 | 10 | 58 | 103 | 58 | 45 | 8 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Hogldev.Mesh (
Mesh
, loadMesh
, renderMesh
) where
import Control.Monad (when)
import Data.Foldable (forM_)
import Data.Maybe (fromJust, isJust)
import Foreign.Storable (sizeOf)
import Foreign.Marshal.Array (withArray)
import Text.Printf (printf)
import System.FilePath (splitFileName)
import qualified Data.Vector as V
import qualified Codec.Soten as S
import Graphics.GLUtil
import Graphics.Rendering.OpenGL
import Hogldev.Texture
import Hogldev.Vertex (TNTVertex(..))
data MeshEntry = MeshEntry
{ vb :: !BufferObject
, ib :: !BufferObject
, numIndices :: !GLint
, materialIndex :: !(Maybe Int)
} deriving Show
data Mesh = Mesh
{ entries :: ![MeshEntry]
, textures :: ![Texture]
} deriving Show
type VertexData = TNTVertex
vertexSize = sizeOf (TNTVertex (Vertex3 0 0 0) (TexCoord2 0 0) (Vertex3 0 0 0) (Vertex3 0 0 0))
loadMesh :: FilePath -> IO Mesh
loadMesh fileName = S.readModelFileWithProcess fileName processes >>= either
(error . printf "Error parsing '%s': '%s'" fileName)
(initFromScene fileName)
where
processes = [S.Triangulate, S.GenFaceNormals, S.FlipUVs, S.CalcTangentSpace]
initFromScene :: FilePath -> S.Scene -> IO Mesh
initFromScene fileName scene = do
meshEntries <- V.mapM newMeshEntry (S._sceneMeshes scene)
meshTextures <- initMaterials scene fileName
return Mesh { entries = V.toList meshEntries, textures = meshTextures }
-- TODO: make it safe / add meaningfull fail message
initMaterials :: S.Scene -> FilePath -> IO [Texture]
initMaterials S.Scene{..} fileName = map fromJust <$> V.toList <$>
V.mapM readTexture _sceneMaterials
where
readTexture S.Material{..} = textureLoad textureName Texture2D
where
textureName = V.foldl findTexturePropery
"assets/white.png" _materialProperties
findTexturePropery :: String -> S.MaterialProperty -> String
findTexturePropery _ (S.MaterialTexture S.TextureTypeDiffuse name) =
dir ++ name
findTexturePropery name _ = name
(dir, _) = splitFileName fileName
newMeshEntry :: S.Mesh -> IO MeshEntry
newMeshEntry mesh = initMeshEntry vertices indices (S._meshMaterialIndex mesh)
where
verticesCount = V.length (S._meshVertices mesh)
meshTextures = if S.hasTextureCoords mesh 0
then S._meshTextureCoords mesh
else V.replicate verticesCount (S.V3 0 0 0)
vertices = V.toList $ V.zipWith4 toVert
(S._meshVertices mesh)
(S._meshNormals mesh)
meshTextures
(S._meshTangents mesh)
toVert :: S.V3 Float -> S.V3 Float -> S.V3 Float -> S.V3 Float
-> VertexData
toVert (S.V3 px py pz) (S.V3 nx ny nz) (S.V3 tx ty _) (S.V3 tnx tny tnz) =
TNTVertex pos text norm tans
where
pos = Vertex3 (realToFrac px) (realToFrac py) (realToFrac pz)
text = TexCoord2 (realToFrac tx) (realToFrac ty)
norm = Vertex3 (realToFrac nx) (realToFrac ny) (realToFrac nz)
tans = Vertex3 (realToFrac tnx) (realToFrac tny) (realToFrac tnz)
indices = map fromIntegral $ V.toList $
V.concatMap S._faceIndices (S._meshFaces mesh)
initMeshEntry :: [VertexData] -> [GLuint] -> Maybe Int -> IO MeshEntry
initMeshEntry vertices indices matIndex = do
vbo <- createVertexBuffer vertices
ibo <- createIndexBuffer indices
return MeshEntry
{ vb = vbo
, ib = ibo
, numIndices = fromIntegral (length indices)
, materialIndex = matIndex
}
createVertexBuffer :: [VertexData] -> IO BufferObject
createVertexBuffer vertices = do
vbo <- genObjectName
bindBuffer ArrayBuffer $= Just vbo
withArray vertices $ \ptr ->
bufferData ArrayBuffer $= (size, ptr, StaticDraw)
return vbo
where
numVertices = length vertices
vertexSize = sizeOf (head vertices)
size = fromIntegral (numVertices * vertexSize)
createIndexBuffer :: [GLuint] -> IO BufferObject
createIndexBuffer indices = do
ibo <- genObjectName
bindBuffer ElementArrayBuffer $= Just ibo
withArray indices $ \ptr ->
bufferData ElementArrayBuffer $= (size, ptr, StaticDraw)
return ibo
where
numIndices = length indices
indexSize = sizeOf (head indices)
size = fromIntegral (numIndices * indexSize)
renderMesh :: Mesh -> IO ()
renderMesh Mesh{..} = do
vertexAttribArray vPosition $= Enabled
vertexAttribArray vTextCoord $= Enabled
vertexAttribArray vNormals $= Enabled
vertexAttribArray vTangent $= Enabled
forM_ entries renderEntry
vertexAttribArray vPosition $= Disabled
vertexAttribArray vTextCoord $= Disabled
vertexAttribArray vNormals $= Disabled
vertexAttribArray vTangent $= Disabled
where
vPosition = AttribLocation 0
vTextCoord = AttribLocation 1
vNormals = AttribLocation 2
vTangent = AttribLocation 3
renderEntry :: MeshEntry -> IO ()
renderEntry MeshEntry{..} = do
bindBuffer ArrayBuffer $= Just vb
vertexAttribPointer vPosition $=
( ToFloat
, VertexArrayDescriptor 3 Float (fromIntegral vertexSize)
offset0
)
vertexAttribPointer vTextCoord $=
( ToFloat
, VertexArrayDescriptor 2 Float (fromIntegral vertexSize)
(offsetPtr (sizeOf (Vertex3 0 0 0 :: Vertex3 GLfloat)))
)
vertexAttribPointer vNormals $=
( ToFloat
, VertexArrayDescriptor 3 Float (fromIntegral vertexSize)
(offsetPtr (
sizeOf (Vertex3 0 0 0 :: Vertex3 GLfloat)
+ sizeOf (TexCoord2 0 0 :: TexCoord2 GLfloat))
)
)
vertexAttribPointer vTangent $=
( ToFloat
, VertexArrayDescriptor 3 Float (fromIntegral vertexSize)
(offsetPtr (
sizeOf (Vertex3 0 0 0 :: Vertex3 GLfloat) -- Position
+ sizeOf (TexCoord2 0 0 :: TexCoord2 GLfloat) -- Texture
+ sizeOf (Vertex3 0 0 0 :: Vertex3 GLfloat)) -- Normal
)
)
bindBuffer ElementArrayBuffer $= Just ib
when (isJust materialIndex) $
textureBind (textures !! fromJust materialIndex)(TextureUnit 0)
drawIndexedTris (numIndices `div` 3)
| triplepointfive/hogldev | common/Hogldev/Mesh.hs | mit | 6,524 | 0 | 19 | 1,824 | 1,895 | 954 | 941 | 156 | 2 |
{-# OPTIONS -Wall #-}
{-# LANGUAGE NamedFieldPuns #-}
import Helpers.Parse
import Text.Parsec
data Command = Forward Int | Down Int | Up Int
deriving (Show)
data Position = Position {horizontal :: Int, depth :: Int}
main :: IO ()
main = do
commands <- parseInput
let Position {horizontal, depth} = foldl move initialPosition commands
let answer = horizontal * depth
print answer
initialPosition :: Position
initialPosition = Position {horizontal = 0, depth = 0}
move :: Position -> Command -> Position
move position (Forward n) = position {horizontal = horizontal position + n}
move position (Up n) = position {depth = depth position - n}
move position (Down n) = position {depth = depth position + n}
parseInput :: IO [Command]
parseInput = parseLinesIO $ do
constructor <-
try (string "forward" >> pure Forward)
<|> try (string "down" >> pure Down)
<|> try (string "up" >> pure Up)
_ <- many1 space
amount <- read <$> many1 digit
return $ constructor amount
| SamirTalwar/advent-of-code | 2021/AOC_02_1.hs | mit | 1,001 | 8 | 14 | 203 | 386 | 190 | 196 | 28 | 1 |
{-# LANGUAGE LambdaCase, ViewPatterns,ScopedTypeVariables, NoMonomorphismRestriction #-}
module Syntax.ShellQQ.Pipes where
import Language.Haskell.TH
import Language.Haskell.TH.Quote
| ducis/shqq | Syntax/ShellQQ/Pipes.hs | mit | 186 | 0 | 4 | 16 | 21 | 15 | 6 | 4 | 0 |
module UtilSpec
( main
, spec
) where
import Ch06SVM.Util
import Test.Hspec
spec :: Spec
spec = return ()
main :: IO ()
main = hspec spec
| rcook/mlutil | ch06-svm/spec/UtilSpec.hs | mit | 173 | 0 | 6 | 62 | 55 | 31 | 24 | 9 | 1 |
-- https://projecteuler.net/problem=40
-- Champernowne's constant
-- An irrational decimal fraction is created by concatenating the positive integers:
-- 0.123456789101112131415161718192021...
-- It can be seen that the 12th digit of the fractional part is 1.
-- If dn represents the nth digit of the fractional part, find the value of the following expression.
-- d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
module Euler40 where
import Data.Numbers.Primes
import Data.List
digit :: Integer -> Integer
digit a
| a < 10 = a
| a >= 10 && a < 20 && (a `mod` 2 == 0) = 1
| a >= 10 && a < 20 && (a `mod` 2 == 1) = a `mod` 10 `quot` 2
| kirhgoff/haskell-sandbox | euler40/euler40.hs | mit | 656 | 0 | 11 | 133 | 137 | 78 | 59 | 8 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.CSSKeyframeRule
(js_setKeyText, setKeyText, js_getKeyText, getKeyText, js_getStyle,
getStyle, CSSKeyframeRule, castToCSSKeyframeRule,
gTypeCSSKeyframeRule)
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[\"keyText\"] = $2;"
js_setKeyText :: CSSKeyframeRule -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframeRule.keyText Mozilla CSSKeyframeRule.keyText documentation>
setKeyText ::
(MonadIO m, ToJSString val) => CSSKeyframeRule -> val -> m ()
setKeyText self val
= liftIO (js_setKeyText (self) (toJSString val))
foreign import javascript unsafe "$1[\"keyText\"]" js_getKeyText ::
CSSKeyframeRule -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframeRule.keyText Mozilla CSSKeyframeRule.keyText documentation>
getKeyText ::
(MonadIO m, FromJSString result) => CSSKeyframeRule -> m result
getKeyText self = liftIO (fromJSString <$> (js_getKeyText (self)))
foreign import javascript unsafe "$1[\"style\"]" js_getStyle ::
CSSKeyframeRule -> IO (Nullable CSSStyleDeclaration)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframeRule.style Mozilla CSSKeyframeRule.style documentation>
getStyle ::
(MonadIO m) => CSSKeyframeRule -> m (Maybe CSSStyleDeclaration)
getStyle self = liftIO (nullableToMaybe <$> (js_getStyle (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/CSSKeyframeRule.hs | mit | 2,248 | 20 | 10 | 299 | 552 | 331 | 221 | 35 | 1 |
module XML where
import Data.Maybe
import Text.XML.Light
import Data.Tree
import Data.List
import Data.List.Split
import Data.Char
import qualified Data.Set as Set
import qualified Data.Map as Map
import Control.Monad
import Parsers hiding (trim)
import DataStructures
parseXMLOutput :: FilePath -> IO [(CStructure,FStructure)]
parseXMLOutput file = do
contents <- readFile file
dom <- return $ fromJustWithMsg ("Oops, it seems that XLE generated a non-valid XML file...\n" ++ contents) $ parseXMLDoc contents
choiceTree <- return $ collectContexts dom
cxtGroups <- return $ contextGroups choiceTree
equivalenceMap <- return $ collectEquivalences dom
concreteContexts <- return $ collectTerminals choiceTree
contextMap <- return $ createContextMap concreteContexts cxtGroups
cstructures <- return $ getCStructures dom concreteContexts contextMap equivalenceMap
fstructures <- return $ getFStructures dom concreteContexts contextMap equivalenceMap
return $ pair cstructures fstructures
-- case choiceTree == no_context of
-- False -> do
-- cxtGroups <- return $ contextGroups choiceTree
-- equivalenceMap <- return $ collectEquivalences dom
-- concreteContexts <- return $ collectTerminals choiceTree
-- contextMap <- return $ createContextMap concreteContexts cxtGroups
-- cstructures <- return $ getCStructures dom concreteContexts contextMap equivalenceMap
-- fstructures <- return $ getFStructures dom concreteContexts contextMap equivalenceMap
-- return $ pair cstructures fstructures
-- True -> do
-- -- do something
-- return undefined
pair :: Eq a => [(a,b)] -> [(a,c)] -> [(b,c)]
pair [] _ = []
pair ((a,b) : rest) cs = (b,unsafeLookup cs) : (pair rest) cs where
unsafeLookup [] = error "Unsafe lookup in pair"
unsafeLookup ((a',c) : rest) | a == a' = c
| otherwise = unsafeLookup rest
verify :: a -> Maybe a -> a
verify a Nothing = a
verify _ (Just a) = a
safeHead :: a -> [a] -> a
safeHead a [] = a
safeHead _ (a : _) = a
no_context :: ChoiceTree
no_context = Node "" []
trim :: String -> String
trim "" = ""
trim s = reverse $ dropWhile isSpace $ reverse $ dropWhile isSpace s
getContext el = fromJustWithMsg ("Mmm I was expecting this element to have a 'context' attribute" ++ show el) $ findAttr (unqual "context") el
getContexts el = parseContext $ fromJustWithMsg ("Mmm I was expecting this element to have a 'context' attribute" ++ show el) $ findAttr (unqual "context") el
collectTerminals :: Tree a -> [a]
collectTerminals (Node a []) = [a]
collectTerminals (Node _ children) = concat $ map collectTerminals children
createContextMap :: [Context] -> Set.Set (Set.Set Context) -> Map.Map Context (Set.Set Context)
createContextMap cxts equivs = aux cxts equivs Map.empty where
aux [] _ m = m
aux (c : cs) equivs m = aux cs equivs $ Map.insert c (Set.findMin $ Set.filter (Set.member c) equivs) m
collectContexts :: Element -> ChoiceTree
collectContexts dom =
case findElements (unqual "alternatives_for") dom of
[] -> no_context
(first : rest) -> construct_tree first_tree rest where
construct_tree t [] = t
construct_tree t (el : rest) = construct_tree (append (toTree el) t) rest
first_tree = toTree first
toTree el = Node cont children where
cont = getContext el
raw_children = strContent el
children = map (\x -> Node (trim x) []) $ splitOn "," $ reverse $ tail $ reverse $ tail raw_children
append t (Node a children) =
case (rootLabel t) == a of
True -> t
False -> Node a $ map (append t) children
contextGroups :: ChoiceTree -> Set.Set (Set.Set Context)
contextGroups t = aux t Set.empty where
aux (Node c []) current = Set.singleton $ Set.insert c current
aux (Node c children) current =
foldr Set.union Set.empty $ map (\x -> aux x (Set.insert c current)) children
collectEquivalences :: Element -> EquivalenceMap
collectEquivalences dom =
case findElements (unqual "definition_of") dom of
[] -> Map.empty
defs -> foldr aux Map.empty defs where
aux el m = Map.insert cont equivs m where
cont = getContext el
equivs = parseEquivalence $ strContent el
getCStructures :: Element -> [Context] -> Map.Map Context (Set.Set Context) -> EquivalenceMap -> [(Context,CStructure)]
getCStructures dom concreteContexts contextMap equivalenceMap = do
phiMappings <- return $ collectPhiMappings dom
phiMappings <- return $ expandEquivalenceMap phiMappings equivalenceMap
phiMappings <- return $ createPhiMapping phiMappings contextMap
subtrees <- return $ collectSubtrees dom
subtrees <- return $ expandEquivalenceMap subtrees equivalenceMap
guard ((not $ null subtrees) && (not $ Map.null phiMappings))
roottree <- return $ head subtrees -- here I'm assuming that the first subtree is always the root...
currentcontext <- concreteContexts
phi <- return $ case Map.lookup currentcontext phiMappings of
Nothing -> error $ "Lookup error in trying to find the phi mapping for context " ++ currentcontext ++ " in phiMappings: " ++ show phiMappings
Just a -> a
return (currentcontext,CStructure { tree = reconstructTree currentcontext roottree subtrees contextMap
, phiMapping = Map.fromList phi})
expandEquivalenceMap:: [(Context,a)] -> EquivalenceMap -> [(Context,a)]
expandEquivalenceMap subs equivmap = Map.foldrWithKey aux subs equivmap where
aux k cxts subs = foldr (\cxt subs -> foldr (\t subs -> subs ++ [(cxt,t)]) subs ts) subs cxts where
ts = map snd $ filter (\(c,_) -> c == k) subs
reconstructTree :: Context -> (Context,BinTree (Id,Label)) -> [(Context,BinTree (Id,Label))] -> Map.Map Context (Set.Set Context) -> BinTree (Id,Label)
reconstructTree _ (_,t@(Terminal _)) _ _ = t
reconstructTree cxt (_,(Unary a (Terminal (id,_)))) subtrees contextMap = Unary a t where
t = reconstructTree cxt t' subtrees contextMap
t' = findSuitableTree cxt id subtrees contextMap
reconstructTree cxt (_,(Binary (Terminal (l_id,_)) a (Terminal (r_id,_)))) subtrees contextMap = Binary l a r where
l = reconstructTree cxt l' subtrees contextMap
l' = findSuitableTree cxt l_id subtrees contextMap
r = reconstructTree cxt r' subtrees contextMap
r' = findSuitableTree cxt r_id subtrees contextMap
reconstructTree _ _ _ _ = undefined
findSuitableTree :: Context -> Id -> [(Context,BinTree (Id,Label))] -> Map.Map Context (Set.Set Context) -> (Context,BinTree (Id,Label))
findSuitableTree cxt id subtrees contextMap =
let aux legalContexts [] = error $ "Error in findSuitableTree, current context " ++ cxt ++ ", looking for id " ++ show id ++ ", in subtrees " ++ show subtrees ++ ", allowing the following legal contexts " ++ show legalContexts
aux legalContexts ((cxt,t) : rest) | Set.member cxt legalContexts && id == getId t = (cxt,t)
| otherwise = aux legalContexts rest
getId (Terminal (id,_)) = id
getId (Unary (id,_) _) = id
getId (Binary _ (id,_) _) = id
in aux ((Map.!) contextMap cxt) subtrees
unknown_label = "UNKNOWN LABEL"
hasLabel :: Element -> String -> Bool
hasLabel el label = case findChild (unqual "label") el of
Nothing -> False
Just a -> strContent a == label
getArg :: String -> Element -> String
getArg n el = trim $ strContent $ head $ filterChildren p el where
p el = elName el == (unqual "arg") && isJust (findAttr (unqual "no") el) && (fromJustWithMsg ("Mmm I was expecting this element to have a 'no' attribute" ++ show el) $ findAttr (unqual "no") el) == n
getArgAsElement :: String -> Element -> Element
getArgAsElement n el = head $ filterChildren p el where
p el = elName el == (unqual "arg") && isJust (findAttr (unqual "no") el) && (fromJustWithMsg ("Mmm I was expecting this element to have a 'no' attribute" ++ show el) $ findAttr (unqual "no") el) == n
createPhiMapping :: [(Context,(Id,FVar))] -> Map.Map Context (Set.Set Context) -> Map.Map Context [(Id,FVar)]
createPhiMapping x cxtMap =
let raw = foldr (\(cxt,pair) m -> Map.insertWith (++) cxt [pair] m) Map.empty x
aux k v = let ancestors = case Map.member k cxtMap of
False -> []
True -> concat $ Set.toList $ Set.map subaux $ (Map.!) cxtMap k
subaux c = case Map.lookup c raw of
Just a -> a
Nothing -> [] -- error $ "Error in createPhiMapping, when building ancestors, for parent context " ++ c ++ " in raw phi " ++ show raw ++ " with original constraints " ++ show x
in v ++ ancestors
in Map.mapWithKey aux raw
collectPhiMappings :: Element -> [(Context,(Id,FVar))]
collectPhiMappings dom = do
cStructureElem <- findChildren (unqual "cstructure") dom
constraint <- findChildren (unqual "constraint") cStructureElem
guard (hasLabel constraint "phi")
cxts constraint >>= \cxt -> return (cxt,(read (id constraint), fvar constraint)) where
cxts el = case findAttr (unqual "context") el of
Nothing -> [""]
Just a -> parseContext a
id el = getArg "1" el
fvar el = getArg "2" el
collectSubtrees :: Element -> [(Context,BinTree (Id,Label))]
collectSubtrees dom = do
cStructureElem <- findChildren (unqual "cstructure") dom
constraint <- findChildren (unqual "constraint") cStructureElem
guard (isSubTree constraint || isTerminal constraint)
toContextualizedTree constraint where
isSubTree el = hasLabel el "subtree"
isTerminal el = hasLabel el "terminal"
toContextualizedTree el = cxts >>= \cxt -> return (cxt,t) where
cxts = case findAttr (unqual "context") el of
Nothing -> [""]
Just a -> parseContext a
t = case isTerminal el of
True -> Terminal (read arg1, arg2) where
arg1 = getArg "1" el
arg2 = getArg "2" el
False -> let arg1 = getArg "1" el
arg2 = getArg "2" el
arg3 = getArg "3" el
arg4 = getArg "4" el
in case arg3 == "-" of
True -> Unary (read arg1,arg2) (Terminal (read arg4, unknown_label))
False -> Binary (Terminal (read arg3, unknown_label)) (read arg1, arg2) (Terminal (read arg4, unknown_label))
getFStructures :: Element -> [Context] -> Map.Map Context (Set.Set Context) -> EquivalenceMap -> [(Context,FStructure)]
getFStructures dom concreteContexts contextMap equivalenceMap = do
fconstraints <- return $ collectFConstraints dom
fconstraints <- return $ expandEquivalenceMap fconstraints equivalenceMap
guard (not $ null fconstraints)
currentcontext <- concreteContexts
return (currentcontext, reconstructFStructure currentcontext contextMap fconstraints)
no_feature = "NO_FEATURE"
collectFConstraints :: Element -> [(Context,(FVar,Feature,Relation,Value))]
collectFConstraints dom = do
fStructureElem <- findChildren (unqual "fstructure") dom
constraint <- findChildren (unqual "constraint") fStructureElem
generateConstraint constraint where
generateConstraint constr = cxts >>= \cxt -> return (cxt,(fvar,feature,rel,val)) where
cxts = case findAttr (unqual "context") constr of
Nothing -> [""]
Just a -> parseContext a
arg1 = getArgAsElement "1" constr
arg2 = getArgAsElement "2" constr
fvar = case rel of
Equality -> getArg "1" arg1
InSet -> trim $ strContent arg2
feature = case rel of
Equality -> getArg "2" arg1
InSet -> no_feature
rel = case trim $ strContent $ fromJustWithMsg ("Mmm I was expecting this element (while looking for the type of relation in an f-constraint) to have a 'label' child:" ++ show constr) $ findChild (unqual "label") constr of
"eq" -> Equality
"in_set" -> InSet
_ -> undefined
val = case rel of
Equality -> valFun arg2
InSet -> valFun arg1
valFun arg = case findChild (unqual "label") arg of
Nothing -> let arg2str = trim $ strContent $ arg
in case isPrefixOf "var:" arg2str of
True -> FVar arg2str
False -> Atom arg2str
Just _ -> SemForm $ getArg "1" arg
reconstructFStructure :: Context -> Map.Map Context (Set.Set Context) -> [(Context,(FVar,Feature,Relation,Value))] -> FStructure
reconstructFStructure cxt contextMap fconstraints = foldr aux Map.empty constraints where
constraints = (filter (\(c,_) -> c == cxt) fconstraints) ++ ancestorsConstraints
ancestorsConstraints = concat $ map (\cxt' -> filter (\(c,_) -> c == cxt') fconstraints) (Set.toList $ Map.findWithDefault Set.empty cxt contextMap)
aux (_,(fvar,feat,Equality,value)) m = Map.insert fvar newVal m where
newVal = case Map.lookup fvar m of
Nothing -> (Set.empty,Map.singleton feat value)
Just (s,fmap) -> (s,Map.insert feat value fmap)
aux (_,(fvar,_,InSet,value)) m = Map.insert fvar newVal m where
newVal = case Map.lookup fvar m of
Nothing -> (Set.singleton (fromValue value), Map.empty)
Just (s,fmap) -> (Set.insert (fromValue value) s, fmap)
fromValue (FVar fvar) = fvar
fromValue _ = undefined
-- Debug and pretty printing
printXMLResults :: FilePath -> IO ()
printXMLResults fp = parseXMLOutput fp >>= mapM_ (\(c,f) -> putStrLn $ (drawCStructure c) ++ "\n" ++ (drawFStructure f))
fromJustWithMsg :: String -> Maybe a -> a
fromJustWithMsg _ (Just a) = a
fromJustWithMsg m Nothing = error m | gianlucagiorgolo/glue-xle | XML.hs | mit | 14,547 | 0 | 22 | 4,044 | 4,635 | 2,351 | 2,284 | 231 | 9 |
-- Fibonacci number. Tail Recursion.
module Fibonacci where
fibonacci :: Integer -> Integer
fibonacci index
| index < 0 = error "Negative index."
| otherwise = fibonacci' index 0 1
where
fibonacci' :: Integer -> Integer -> Integer -> Integer
fibonacci' 0 _ _ = 0
fibonacci' 1 _ numberAccumulator = numberAccumulator
fibonacci' index intermediate numberAccumulator
= fibonacci' (index - 1) numberAccumulator $! (numberAccumulator + intermediate)
{- GHCi>
fibonacci (-1)
fibonacci 0
fibonacci 1
fibonacci 2
fibonacci 3
fibonacci 4
fibonacci 5
-}
-- *** Exception: Negative index.
-- 0
-- 1
-- 2
-- 3
-- 5
| pascal-knodel/haskell-craft | Examples/· Recursion/· Tail Recursion/Calculation/Fibonacci.hs | mit | 708 | 0 | 10 | 203 | 136 | 72 | 64 | 10 | 3 |
import qualified Control.Monad as C
import qualified Data.Map.Strict as M
import qualified Data.Ratio as R
import qualified Text.Printf as T
newtype PList a = PList { pList :: [(a, Rational)] }
instance Functor PList where
fmap = C.liftM
instance Applicative PList where
pure = return
(<*>) = C.ap
instance Monad PList where
return a = PList [(a,1)]
m >>= f = PList $ concat $ map f' $ pList m
where f' (a,p) = map (\(a',p') -> (a',p*p')) (pList $ f a)
coin_toss :: Int -> PList Int
coin_toss x = PList [(x, 1 R.% 2), (x + 1, 1 R.% 2)]
dice_roll :: Int -> PList Int
dice_roll x = PList $ map (\x' -> (x+x',1 R.% 6)) [1..6]
multi_rand_event :: t -> Int -> (t -> PList t) -> PList t
multi_rand_event initial rounds event = f initial
where f = foldr (C.<=<) return (replicate rounds event)
lookup_default :: Ord k => k -> (M.Map k v) -> v -> v
lookup_default k m d = case M.lookup k m of
(Just x) -> x
otherwise -> d
to_histo :: PList Int -> M.Map Int Rational
to_histo (PList []) = M.fromList []
to_histo (PList ((a,p):xs)) = let
m = to_histo (PList xs)
p' = lookup_default a m 0
in M.insert a (p'+p) m
main = do
let raw_results = multi_rand_event 0 8 dice_roll
let histo = M.toList $ to_histo raw_results
print histo
| candide-guevara/programming_challenges | haskell_learning/probabilistic_monad.hs | gpl-2.0 | 1,260 | 1 | 12 | 278 | 633 | 334 | 299 | 35 | 2 |
import System.IO (readFile)
import System.Environment (getArgs)
main :: IO ()
main = do
paths <- getArgs
conts <- mapM readFile paths
let cat = concat conts
putStr cat
| friedbrice/Haskell | ch09/cat.hs | gpl-2.0 | 178 | 1 | 10 | 38 | 76 | 35 | 41 | 8 | 1 |
{- |
Module : $Header$
Description : basic ShATermConvertible instances
Copyright : (c) Christian Maeder, Uni Bremen 2005-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
a few basic 'ShATermConvertible' instances needed by "Haskell.ATC_Haskell"
-}
module Haskell.BaseATC () where
import ATerm.Lib
import Data.Typeable
import SrcLoc
_tcSrcLocTc :: TyCon
_tcSrcLocTc = mkTyCon "SrcLoc.SrcLoc"
instance Typeable SrcLoc where
typeOf _ = mkTyConApp _tcSrcLocTc []
instance ShATermConvertible SrcLoc where
toShATermAux att0 xv = case xv of
SrcLoc a b c d -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
(att3, c') <- toShATerm' att2 c
(att4, d') <- toShATerm' att3 d
return $ addATerm (ShAAppl "SrcLoc" [a',b',c',d'] []) att4
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "SrcLoc" [a,b,c,d] _ ->
case fromShATerm' a att0 of { (att1, a') ->
case fromShATerm' b att1 of { (att2, b') ->
case fromShATerm' c att2 of { (att3, c') ->
case fromShATerm' d att3 of { (att4, d') ->
(att4, SrcLoc a' b' c' d') }}}}
u -> fromShATermError "SrcLoc" u
| nevrenato/Hets_Fork | Haskell/BaseATC.hs | gpl-2.0 | 1,259 | 0 | 22 | 289 | 366 | 194 | 172 | 24 | 1 |
module System.DevUtils.Base.Url.ZMQ (
ZMQ(..),
defaultZMQConnection,
defaultZMQ
) where
import qualified System.DevUtils.Base.Url.Connection as C
data ZMQ = ZMQ {
_con :: C.Connection
} deriving (Show, Read)
defaultZMQConnection :: C.Connection
defaultZMQConnection = C.Connection {
C._dest = "localhost", C._port = 0, C._type = C.TCP
}
defaultZMQ :: ZMQ
defaultZMQ = ZMQ {
_con = defaultZMQConnection
}
| adarqui/DevUtils-Base | src/System/DevUtils/Base/Url/ZMQ.hs | gpl-3.0 | 418 | 0 | 9 | 67 | 123 | 78 | 45 | 14 | 1 |
{-|
Module : To87
Description : Converts 8 bits to 7 bits
Copyright : (c) Frédéric BISSON, 2014
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
This module converts 8 bits bytes to 7 bits bytes.
-}
module Minitel.Generate.Photo.To87 ( to87 ) where
import Data.Word
import Data.Bits
import Data.Binary.Bits.Get
import Data.Binary.Get (runGet)
import qualified Data.ByteString.Lazy.Char8 as BS
convert87 :: Int -> BitGet [Word8]
convert87 n
| n < 8 = do bits <- getWord8 n
return [shiftL bits (7 - n)]
| otherwise = do bits <- getWord8 7
rest <- convert87 (n-7)
return $ bits : rest
to87 :: BS.ByteString -> [Word8]
to87 datas = runGet (runBitGet (convert87 len)) datas
where len = fromIntegral $ BS.length datas * 8
| Zigazou/HaMinitel | src/Minitel/Generate/Photo/To87.hs | gpl-3.0 | 864 | 0 | 12 | 229 | 222 | 117 | 105 | 16 | 1 |
{-- SecPAL language spec -}
module Logic.SecPAL.Language where
import Logic.General.Entities
import Logic.General.Constraints
data D = Zero
| Infinity
deriving (Eq,Show)
data VerbPhrase = Predicate { predicate :: String, args :: [E] }
| CanSay { delegation :: D, what :: Fact }
| CanActAs { whom :: E }
deriving (Eq,Show)
data Fact = Fact { subject :: E, verb :: VerbPhrase }
deriving (Eq,Show)
data Claim = Claim { fact :: Fact, conditions :: [Fact], constraint :: C }
deriving (Eq,Show)
data Assertion = Assertion { who :: E, says :: Claim }
deriving (Eq,Show)
data AC = AC [Assertion]
deriving (Eq,Show)
acs :: AC -> [Assertion]
acs (AC as) = as
| bogwonch/SecPAL | src/Logic/SecPAL/Language.hs | gpl-3.0 | 764 | 0 | 9 | 228 | 258 | 155 | 103 | 20 | 1 |
{-# OPTIONS -Wall #-}
module Codec.TPTP.Import(parse,parseFile
,parseWithComment,parseWithCommentFile
,Token(..)) where
import Lexer
import Parser
import ParserC
import Codec.TPTP.Base
parse :: String -> [TPTP_Input]
parse = parseTPTP . map snd . alexScanTokens
parseFile :: FilePath -> IO [TPTP_Input]
parseFile x = parse `fmap` readFile x
parseWithComment :: String -> [TPTP_Input_C]
parseWithComment = parseTPTPwithComment . map snd . alexScanTokens
parseWithCommentFile :: FilePath -> IO [TPTP_Input_C]
parseWithCommentFile x = parseWithComment `fmap` readFile x
| DanielSchuessler/logic-TPTP | Codec/TPTP/Import.hs | gpl-3.0 | 623 | 0 | 7 | 125 | 164 | 94 | 70 | 16 | 1 |
import Data.Char as DC
main =
if hIsEOF linea
then
do
putStrLn "Hola"
else
do
linea <- getLine
putStrLn $ mayusculas linea
putStrLn $ minusculas linea
main
mayusculas :: [Char] -> [Char]
mayusculas (x:xs) = [DC.toUpper x] ++ (mayusculas xs)
mayusculas [] = []
minusculas :: [Char] -> [Char]
minusculas (x:xs) = [DC.toLower x] ++ (minusculas xs)
minusculas [] = []
| rysard/cursos | haskell/problemas/cadenas.hs | gpl-3.0 | 418 | 1 | 9 | 115 | 183 | 92 | 91 | 16 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module : Network.AWS.S3.Encryption.Decrypt
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.S3.Encryption.Decrypt where
import Control.Monad.Trans.AWS
import Data.Coerce
import Data.Proxy
import Network.AWS.Prelude hiding (coerce)
import Network.AWS.S3
import Network.AWS.S3.Encryption.Envelope
import Network.AWS.S3.Encryption.Instructions
import Network.AWS.S3.Encryption.Types
decrypted :: GetObject
-> (Decrypt GetObject, GetInstructions)
decrypted x = (Decrypt x, getInstructions x)
newtype Decrypt a = Decrypt a
newtype Decrypted a = Decrypted
(forall m r. (AWSConstraint r m, HasKeyEnv r) => Maybe Envelope -> m a)
instance AWSRequest (Decrypt GetObject) where
type Rs (Decrypt GetObject) = Decrypted GetObjectResponse
request (Decrypt x) = coerce (request x)
response l s p r = do
(n, rs) <- response l s (proxy p) r
return ( n
, Decrypted $ \m -> do
key <- view envKey
env <- view environment
e <- case m of
Nothing -> fromMetadata key env (rs ^. gorsMetadata)
Just e' -> pure e'
return (rs & gorsBody %~ bodyDecrypt e)
)
proxy :: forall a. Proxy (Decrypt a) -> Proxy a
proxy = const Proxy
| olorin/amazonka | amazonka-s3-encryption/src/Network/AWS/S3/Encryption/Decrypt.hs | mpl-2.0 | 1,753 | 0 | 20 | 537 | 407 | 224 | 183 | 34 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module BookIndexer.BookMetadataReader where
import Codec.Epub (getPkgPathXmlFromBS, getMetadata, getPackage)
import Codec.Epub.Data.Metadata (Metadata(..), Creator(..), Title(..))
import Codec.Epub.Data.Package (Package(pkgVersion))
import Control.Monad.Catch (MonadThrow)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Error.Class (MonadError)
import qualified Data.ByteString.Lazy as BL (toStrict)
import Data.Text (Text, takeEnd, intercalate, pack)
import Onedrive.Items (content)
import Onedrive.Session (Session)
data BookMetadata =
BookMetadata
{ author :: Text
, title :: Text
, epubVersion :: Text
}
loadMetadata :: (MonadThrow m, MonadIO m, MonadError String m) => Session -> Text -> Text -> m (Maybe BookMetadata)
loadMetadata session filename itemId = do
if isEpub filename
then do
c <- content session itemId
(_, xmlString) <- getPkgPathXmlFromBS $ BL.toStrict c
package <- getPackage xmlString
metadata <- getMetadata xmlString
let
epubVsn = pack $ pkgVersion package
return $ Just $ BookMetadata (getAuthor metadata) (getTitle metadata) epubVsn
else
return Nothing
where
isEpub fn =
let
ext = takeEnd 5 fn
in
ext == ".epub"
getAuthor :: Metadata -> Text
getAuthor meta =
intercalate ", " $ map (pack . creatorText) $ metaCreators meta
getTitle :: Metadata -> Text
getTitle meta =
intercalate "; " $ map (pack . titleText) $ metaTitles meta
| asvyazin/my-books.purs | server/my-books/BookIndexer/BookMetadataReader.hs | mpl-2.0 | 1,539 | 0 | 14 | 292 | 475 | 260 | 215 | 40 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Network.TelegramBot.Files where
import Control.Monad.IO.Class
import Control.Monad.Trans.Either
import Control.Monad.Trans.Resource
import Data.ByteString.Lazy (ByteString)
import Data.Proxy
import Network.Wai
import Network.Wai.Handler.Warp (run)
import Network.Wai.Parse
import Servant.API
import Servant.Server
-- Backends for file upload: in memory or in /tmp ?
data Mem
data Tmp
class KnownBackend b where
type Storage b :: *
withBackend :: Proxy b -> (BackEnd (Storage b) -> IO r) -> IO r
instance KnownBackend Mem where
type Storage Mem = ByteString
withBackend Proxy f = f lbsBackEnd
instance KnownBackend Tmp where
type Storage Tmp = FilePath
withBackend Proxy f = runResourceT . withInternalState $ \s ->
f (tempFileBackEnd s)
-- * Files combinator, to get all of the uploaded files
data Files b
type MultiPartData b = ([Param], [File (Storage b)])
instance (KnownBackend b, HasServer api) => HasServer (Files b :> api) where
type ServerT (Files b :> api) m =
MultiPartData b -> ServerT api m
route Proxy subserver req respond = withBackend pb $ \b -> do
dat <- parseRequestBody b req
route (Proxy :: Proxy api) (subserver dat) req respond
where pb = Proxy :: Proxy b
type FilesMem = Files Mem
type FilesTmp = Files Tmp
{-
-- test
type API = "files" :> FilesTmp :> Post '[JSON] ()
:<|> Raw
api :: Proxy API
api = Proxy
server :: Server API
server = filesHandler :<|> serveDirectory "."
where filesHandler :: MultiPartData Tmp -> EitherT ServantErr IO ()
filesHandler (inputs, files) = do
liftIO $ mapM_ ppFile files
liftIO $ mapM_ print inputs
ppFile :: File FilePath -> IO ()
ppFile (name, fileinfo) = do
putStrLn $ "Input name: " ++ show name
putStrLn $ "File name: " ++ show (fileName fileinfo)
putStrLn $ "Content type: " ++ show (fileContentType fileinfo)
putStrLn $ "------- Content --------"
readFile (fileContent fileinfo) >>= putStrLn
putStrLn $ "------------------------"
app :: Application
app = serve api server
-}
| bb010g/telegram-bot | src/Network/TelegramBot/Files.hs | agpl-3.0 | 2,314 | 0 | 13 | 504 | 419 | 232 | 187 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Various splices used in the job board
module Snap.Snaplet.JobBoard.Splices where
import Data.Text (Text)
import Data.Text.Lazy as TL (toStrict, take)
import Data.Text.Format as TF (format, Only(..))
import qualified Text.XmlHtml as X
import Database.PostgreSQL.Simple.Time
import Heist.Interpreted
import Snap.Snaplet.JobBoard.Types
link :: Text -> Text -> X.Node
link target text = X.Element "a" [("href", target)] [X.TextNode text]
elText :: Text -> Text -> X.Node
elText el text = X.Element el [] [X.TextNode text]
loginLink :: X.Node
loginLink = X.Element "li" [] [link "/login" "Login"]
logoutLink :: X.Node
logoutLink = X.Element "li" [] [link "/a/logout" "Logout"]
-- | Create a splice from a Job with an index.
-- TODO: Probably should redo this with runChildrenWith, because
-- several text fields are defaulted to null strings.
jobSplice :: Monad m => Id Int Job -> Splice m
jobSplice (Id (i, job)) = runChildrenWithText
[("job-url", toStrict . format "/job/{}" $ Only i)
,("job-employer", _employer job)
,("job-employerLink", maybe "#" id $ _employerLink job)
,("job-link", maybe "#" id $ _link job)
,("job-title", _title job)
,("job-location", _location job)
,("job-type", jobTypeText . _type $ job)
,("job-description", _description job)
,("job-instructions", maybe "" id $ _instructions job)
{-,("job-open", f $ _open job)-}
,("job-updated", f $ _updated job)
]
-- Hackily convert infinite sql times to a short text format.
where f (Finite t) = toStrict . TL.take 10 . TF.format "{}" $ Only t
f _ = "Unknown"
{-- Jobs list previews --}
renderPreviews :: Monad m => [Id Int Job] -> Splice m
renderPreviews = mapSplices jobSplice
| statusfailed/snaplet-job-board | src/Snap/Snaplet/JobBoard/Splices.hs | agpl-3.0 | 1,738 | 0 | 11 | 307 | 544 | 300 | 244 | 33 | 2 |
{-
Bustle.Monitor: Haskell binding for pcap-monitor.c
Copyright © 2012 Collabora Ltd.
Copyright © 2018 Will Thompson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-}
{-# LANGUAGE ForeignFunctionInterface #-}
module Bustle.Monitor
(
-- * Types
Monitor
, BusType(..)
-- * Methods
, monitorNew
, monitorStop
-- * Signals
, monitorMessageLogged
, monitorStopped
)
where
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.C
import qualified Data.ByteString as BS
import System.Glib.GObject
import System.Glib.GError
import System.Glib.Signals
import Bustle.Types (Microseconds)
-- Gtk2HS boilerplate
newtype Monitor = Monitor { unMonitor :: ForeignPtr Monitor }
deriving (Eq, Ord)
mkMonitor :: (ForeignPtr Monitor -> Monitor, FinalizerPtr a)
mkMonitor = (Monitor, objectUnref)
instance GObjectClass Monitor where
toGObject = GObject . castForeignPtr . unMonitor
unsafeCastGObject = Monitor . castForeignPtr . unGObject
-- Foreign imports
foreign import ccall "bustle_pcap_monitor_new"
bustle_pcap_monitor_new :: CInt
-> CString
-> CString
-> Ptr (Ptr ())
-> IO (Ptr Monitor)
foreign import ccall "bustle_pcap_monitor_stop"
bustle_pcap_monitor_stop :: Ptr Monitor
-> IO ()
-- Bindings for said imports
data BusType = BusTypeNone
| BusTypeSystem
| BusTypeSession
deriving
Enum
-- Throws a GError if the file can't be opened, we can't get on the bus, or whatever.
monitorNew :: Either BusType String
-> FilePath
-> IO Monitor
monitorNew target filename =
wrapNewGObject mkMonitor $
propagateGError $ \gerrorPtr ->
withAddress $ \c_address ->
withCString filename $ \c_filename ->
bustle_pcap_monitor_new c_busType c_address c_filename gerrorPtr
where
c_busType = fromIntegral . fromEnum $ case target of
Left busType -> busType
Right _ -> BusTypeNone
withAddress f = case target of
Left _ -> f nullPtr
Right address -> withCString address f
monitorStop :: Monitor
-> IO ()
monitorStop monitor =
withForeignPtr (unMonitor monitor) bustle_pcap_monitor_stop
messageLoggedHandler :: (Microseconds -> BS.ByteString -> IO ())
-> a
-> CLong
-> CLong
-> Ptr CChar
-> CUInt
-> IO ()
messageLoggedHandler user _obj sec usec blob blobLength = do
blobBS <- BS.packCStringLen (blob, fromIntegral blobLength)
let µsec = fromIntegral sec * (10 ^ (6 :: Int)) + fromIntegral usec
failOnGError $ user µsec blobBS
monitorMessageLogged :: Signal Monitor (Microseconds -> BS.ByteString -> IO ())
monitorMessageLogged =
Signal $ \after_ obj user ->
connectGeneric "message-logged" after_ obj $ messageLoggedHandler user
stoppedHandler :: (Quark -> Int -> String -> IO ())
-> a
-> CUInt
-> CInt
-> Ptr CChar
-> IO ()
stoppedHandler user _obj domain code messagePtr = do
message <- peekCString messagePtr
failOnGError $ user domain (fromIntegral code) message
monitorStopped :: Signal Monitor (Quark -> Int -> String -> IO ())
monitorStopped =
Signal $ \after_ obj user ->
connectGeneric "stopped" after_ obj $ stoppedHandler user
| wjt/bustle | Bustle/Monitor.hs | lgpl-2.1 | 4,124 | 0 | 14 | 1,089 | 819 | 426 | 393 | 85 | 3 |
-- | Backend specific glue for platform
module ViperVM.Platform.Peer.PlatformPeer (
PlatformPeer(..),initPlatform
) where
import qualified ViperVM.Backends.Host.Driver as Host
import qualified ViperVM.Backends.OpenCL.Driver as CL
import qualified ViperVM.Platform.Peer.MemoryPeer as Peer
import qualified ViperVM.Platform.Peer.LinkPeer as Peer
import qualified ViperVM.Platform.Peer.ProcPeer as Peer
import ViperVM.Platform.Configuration
import ViperVM.Platform.Memory
import ViperVM.Platform.Link
import ViperVM.Platform.Proc
import Data.Traversable (forM)
data PlatformPeer = PlatformPeer {
memories :: [Memory],
links :: [Link],
processors :: [Proc]
}
initPlatform :: Configuration -> IO PlatformPeer
initPlatform config = do
-- Initialize Host driver
(hostMems,hostLinks) <- Host.initHost config
let hostMemsPeer = fmap Peer.HostMemory hostMems
hostLinksPeer = fmap Peer.HostLink hostLinks
-- Initialize OpenCL driver
(clMems,clLinks,clProcs) <- CL.initOpenCL config hostMems
let clMemsPeer = fmap Peer.CLMemory clMems
clLinksPeer = fmap Peer.CLLink clLinks
clProcsPeer = fmap Peer.CLProc clProcs
-- Wrap entities
let memsPeer = hostMemsPeer ++ clMemsPeer
linksPeer = hostLinksPeer ++ clLinksPeer
procsPeer = clProcsPeer
mems <- forM (memsPeer `zip` [0..]) (uncurry wrapMemory)
lnks <- forM linksPeer (wrapLink mems)
procs <- forM (procsPeer `zip` [0..]) (uncurry (wrapProc mems))
return $ PlatformPeer mems lnks procs
| hsyl20/HViperVM | lib/ViperVM/Platform/Peer/PlatformPeer.hs | lgpl-3.0 | 1,516 | 0 | 12 | 257 | 398 | 229 | 169 | 32 | 1 |
{-# LANGUAGE RecordWildCards, TypeOperators, StandaloneDeriving, FlexibleContexts, UndecidableInstances #-}
module Language.Pascal.Parser (parseSource, pProgram) where
import Control.Applicative ((<$>))
import qualified Data.Map as M
import Text.Parsec
import qualified Text.Parsec.Token as P
import Text.Parsec.Language
import Text.Parsec.Expr
import Language.Pascal.Types
type Parser a = Parsec String () a
pascal = P.makeTokenParser $ javaStyle {
P.commentStart = "(*",
P.commentEnd = "*)",
P.reservedNames = ["program", "function", "begin", "end", "var", "true", "false",
"return", "if", "then", "else", "for", "to", "do", "of",
"exit", "procedure", "break", "continue", "array", "record",
"const", "type" ] }
symbol = P.symbol pascal
reserved = P.reserved pascal
reservedOp = P.reservedOp pascal
identifier = P.identifier pascal
stringLiteral = P.stringLiteral pascal
integer = P.integer pascal
semi = P.semi pascal
colon = P.colon pascal
comma = P.comma pascal
dot = P.dot pascal
parens = P.parens pascal
brackets = P.brackets pascal
withAnnotation :: Parser x -> Parser (Annotate x SrcPos)
withAnnotation p = do
pos <- getPosition
x <- p
return $ Annotate x $ SrcPos {
srcLine = sourceLine pos,
srcColumn = sourceColumn pos }
pProgram :: Parser (Program :~ SrcPos)
pProgram = withAnnotation $ do
reserved "program"
identifier
semi
consts <- option [] pConsts
types <- M.fromList <$> option [] pTypes
vars <- option [] pVars
fns <- many (try pFunction <|> pProcedure)
reserved "begin"
sts <- pStatement `sepEndBy1` semi
reserved "end"
dot
return $ Program consts types vars fns sts
readType str =
case str of
"integer" -> TInteger
"string" -> TString
"boolean" -> TBool
"void" -> TVoid
s -> TUser s
pVars :: Parser [Annotate Symbol SrcPos]
pVars = do
reserved "var"
lists <- pVarsList `sepEndBy1` semi
return $ concat lists
pTypes :: Parser [(Id, Type)]
pTypes = do
reserved "type"
res <- many1 $ do
name <- identifier
reservedOp "="
tp <- pType
semi
return (name, content tp)
return $ map rename res
where
rename (name, TRecord _ fs) = (name, TRecord (Just name) fs)
rename x = x
pConsts :: Parser [(Id, Expression :~ SrcPos)]
pConsts = do
reserved "const"
many1 $ do
name <- identifier
reservedOp "="
value <- pExpression
semi
return (name, value)
pVarsList :: Parser [Annotate Symbol SrcPos]
pVarsList = do
pos <- getPosition
names <- identifier `sepBy` comma
colon
tp <- pType
return $ map (ret tp pos) names
where
ret tp pos name = Annotate (name # content tp) $
SrcPos {
srcLine = sourceLine pos,
srcColumn = sourceColumn pos }
pType :: Parser (Annotate Type SrcPos)
pType = try arrayType <|> try recordType <|> simpleType
where
arrayType = withAnnotation $ do
reserved "array"
sz <- brackets integer
reserved "of"
tp <- pType
return (TArray sz $ content tp)
recordType = withAnnotation $ do
reserved "record"
fields <- field `sepEndBy1` semi
reserved "end"
return (TRecord Nothing fields)
field = do
name <- identifier
colon
tp <- pType
return (name, content tp)
simpleType = withAnnotation $ do
name <- identifier
return (readType name)
pNameType :: Parser (Annotate Symbol SrcPos)
pNameType = withAnnotation $ do
name <- identifier
colon
tp <- pType
return $ name # content tp
pFunction :: Parser (Function :~ SrcPos)
pFunction = withAnnotation $ do
reserved "function"
name <- identifier
args <- parens $ pNameType `sepBy` comma
colon
res <- identifier
semi
vars <- option [] pVars
reserved "begin"
body <- pStatement `sepEndBy1` semi
reserved "end"
semi
return $ Function name args (readType res) vars body
pProcedure :: Parser (Function :~ SrcPos)
pProcedure = withAnnotation $ do
reserved "procedure"
name <- identifier
args <- parens $ pNameType `sepBy` comma
semi
vars <- option [] pVars
reserved "begin"
body <- pStatement `sepEndBy1` semi
reserved "end"
semi
return $ Function name args TVoid vars body
pStatement :: Parser (Statement :~ SrcPos)
pStatement =
try pIfThenElse
<|> try pAssign
<|> try pProcedureCall
<|> try (withAnnotation (reserved "break" >> return Break))
<|> try (withAnnotation (reserved "continue" >> return Continue))
<|> try (withAnnotation (reserved "exit" >> return Exit))
<|> try pReturn
<|> pFor
pAssign :: Parser (Statement :~ SrcPos)
pAssign = withAnnotation $ do
lv <- pLValue
symbol ":="
expr <- pExpression
return $ Assign lv expr
pLValue :: Parser (LValue :~ SrcPos)
pLValue = try arrayItem <|> try recordField <|> variable
where
arrayItem = withAnnotation $ do
arr <- identifier
ix <- brackets pExpression
return (LArray arr ix)
variable = withAnnotation (LVariable <$> identifier)
recordField = withAnnotation $ do
base <- identifier
dot
field <- identifier
return (LField base field)
pProcedureCall = withAnnotation $ do
name <- identifier
args <- parens $ pExpression `sepBy` comma
return $ Procedure name args
pReturn :: Parser (Statement :~ SrcPos)
pReturn = withAnnotation $ do
reserved "return"
x <- pExpression
return $ Return x
pIfThenElse :: Parser (Statement :~ SrcPos)
pIfThenElse = withAnnotation $ do
reserved "if"
cond <- pExpression
reserved "then"
ok <- pBlock
el <- option [] $ try $ do
reserved "else"
pBlock
return $ IfThenElse cond ok el
pBlock = try (one <$> pStatement) <|> do
reserved "begin"
sts <- pStatement `sepEndBy1` semi
reserved "end"
-- semi
return sts
where
one x = [x]
pFor = withAnnotation $ do
reserved "for"
var <- identifier
reserved ":="
start <- pExpression
reserved "to"
end <- pExpression
reserved "do"
sts <- pBlock
return $ For var start end sts
pExpression :: Parser (Expression :~ SrcPos)
pExpression = buildExpressionParser table term <?> "expression"
where
table = [
[binary "^" Pow AssocLeft],
[binary "*" Mul AssocLeft, binary "/" Div AssocLeft, binary "%" Mod AssocLeft ],
[binary "+" Add AssocLeft, binary "-" Sub AssocLeft ],
[binary "=" IsEQ AssocLeft, binary "!=" IsNE AssocLeft, binary ">" IsGT AssocLeft, binary "<" IsLT AssocLeft ]
]
binary name fun assoc = Infix (op name fun) assoc
op name fun = do
pos <- getPosition
reservedOp name
return $ \x y -> Annotate (Op fun x y) $ SrcPos {
srcLine = sourceLine pos,
srcColumn = sourceColumn pos }
term = parens pExpression
<|> try (withAnnotation $ Literal <$> pLiteral)
<|> try pCall
<|> try pArrayItem
<|> try pRecordField
<|> pVariable
pLiteral = try stringLit <|> try intLit <|> boolLit
where
stringLit = LString <$> stringLiteral
intLit = LInteger <$> integer
boolLit = try (reserved "true" >> return (LBool True)) <|> (reserved "false" >> return (LBool False))
pVariable :: Parser (Expression :~ SrcPos)
pVariable = withAnnotation $ Variable <$> identifier
pArrayItem :: Parser (Expression :~ SrcPos)
pArrayItem = withAnnotation $ do
arr <- identifier
ix <- brackets pExpression
return (ArrayItem arr ix)
pRecordField :: Parser (Expression :~ SrcPos)
pRecordField = withAnnotation $ do
base <- identifier
dot
field <- identifier
return (RecordField base field)
pCall :: Parser (Expression :~ SrcPos)
pCall = withAnnotation $ do
name <- identifier
args <- parens $ pExpression `sepBy` comma
return $ Call name args
parseSource :: FilePath -> IO (Program :~ SrcPos)
parseSource path = do
src <- readFile path
case parse pProgram path src of
Left err -> fail $ show err
Right x -> return x
| portnov/simple-pascal-compiler | Language/Pascal/Parser.hs | lgpl-3.0 | 8,092 | 0 | 15 | 2,068 | 2,781 | 1,351 | 1,430 | 258 | 5 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module HW05 where
import Data.ByteString.Lazy (ByteString)
import Data.Bits (xor)
import Data.Map.Strict (Map)
import System.Environment (getArgs)
import qualified Data.ByteString.Lazy as BS
import qualified Data.Map.Strict as Map
import qualified Data.List as List
import Parser
-- Exercise 1 -----------------------------------------
getSecret :: FilePath -> FilePath -> IO ByteString
getSecret encoded_path original_path = do
encoded_image <- BS.readFile encoded_path
original_image <- BS.readFile original_path
return $ BS.filter (/= 0) $ BS.pack $ BS.zipWith (xor) encoded_image original_image
-- Exercise 2 -----------------------------------------
decryptWithKey :: ByteString -> FilePath -> IO ()
decryptWithKey encryption_key file_path = do
encrypted_json <- BS.readFile (file_path ++ ".enc")
BS.writeFile file_path $ BS.pack $ BS.zipWith (xor) (BS.cycle encryption_key) encrypted_json
-- Exercise 3 -----------------------------------------
parseFile :: FromJSON a => FilePath -> IO (Maybe a)
parseFile json_path = do
transactions <- BS.readFile json_path
return $ decode transactions
-- Exercise 4 -----------------------------------------
getBadTs :: FilePath -> FilePath -> IO (Maybe [Transaction])
getBadTs victims_path transaction_path = do
victims_tid <- (parseFile victims_path) :: IO (Maybe [TId])
transactions <- (parseFile transaction_path) :: IO (Maybe [Transaction])
return $ (\vs ts -> filter (\z -> elem (tid z) vs) ts) <$> victims_tid <*> transactions
-- Exercise 5 -----------------------------------------
getFlow :: [Transaction] -> Map String Integer
getFlow = foldr flows Map.empty
where flows t = Map.insertWith (+) (to t) (amount t) .
Map.insertWith (+) (from t) (negate $ amount t)
-- Exercise 6 -----------------------------------------
getCriminal :: Map String Integer -> String
getCriminal = fst . foldr1 (\max_value value -> if (snd max_value) > (snd value) then max_value else value) . Map.toList
-- Exercise 7 -----------------------------------------
undoTs :: Map String Integer -> [TId] -> [Transaction]
undoTs flow_map tid = zipWith (\id (from, to, amount) -> Transaction from to amount id) tid $ repay (getPayers flow_map) (getPayees flow_map)
where repay :: [(String, Integer)] -> [(String, Integer)] -> [(String, String, Integer)]
repay [] _ = []
repay _ [] = []
repay (payer:payers) (payee:payees)
| minimum_amount == (snd payer) = (from_name, to_name, minimum_amount) : repay payers ((to_name, to_amount):payees)
| minimum_amount == ((negate . snd) payee) = (from_name, to_name, minimum_amount) : repay ((from_name, from_amount):payers) payees
| otherwise = repay payers payees
where minimum_amount = min (snd payer) ((negate . snd) payee)
from_name = fst payer
from_amount = (snd payer) - minimum_amount
to_name = fst payee
to_amount = (snd payee) + minimum_amount
getPayers = List.sortBy descendingOrder . Map.toList . Map.filter (>0)
getPayees = reverse . List.sortBy descendingOrder . Map.toList . Map.filter (<0)
descendingOrder (_, x) (_, y) = compare y x
-- Exercise 8 -----------------------------------------
writeJSON :: ToJSON a => FilePath -> a -> IO ()
writeJSON file_path = BS.writeFile file_path . encode
-- Exercise 9 -----------------------------------------
doEverything :: FilePath -> FilePath -> FilePath -> FilePath -> FilePath
-> FilePath -> IO String
doEverything dog1 dog2 trans vict fids out = do
key <- getSecret dog1 dog2
decryptWithKey key vict
mts <- getBadTs vict trans
case mts of
Nothing -> error "No Transactions"
Just ts -> do
mids <- parseFile fids
case mids of
Nothing -> error "No ids"
Just ids -> do
let flow = getFlow ts
writeJSON out (undoTs flow ids)
return (getCriminal flow)
main :: IO ()
main = do
args <- getArgs
crim <-
case args of
dog1:dog2:trans:vict:ids:out:_ ->
doEverything dog1 dog2 trans vict ids out
_ -> doEverything "dog-original.jpg"
"dog.jpg"
"transactions.json"
"victims.json"
"new-ids.json"
"new-transactions.json"
putStrLn crim
| redongjun/haskellschool | homework/HW05/HW05.hs | unlicense | 4,482 | 0 | 20 | 1,014 | 1,407 | 723 | 684 | 84 | 3 |
module Network.JSONRPC
( -- * Introduction
-- $introduction
module Network.JSONRPC.Interface
, module Network.JSONRPC.Data
) where
import Network.JSONRPC.Arbitrary ()
import Network.JSONRPC.Data
import Network.JSONRPC.Interface
-- $introduction
--
-- This JSON-RPC library is fully-compatible with JSON-RPC 2.0 and 1.0. It
-- provides an interface that combines a JSON-RPC client and server. It can
-- set and keep track of request ids to parse responses. There is support
-- for sending and receiving notifications. You may use any underlying
-- transport. Basic TCP client and server provided.
--
-- A JSON-RPC application using this interface is considered to be
-- peer-to-peer, as it can send and receive all types of JSON-RPC message
-- independent of whether it originated the connection.
| xenog/json-rpc | src/Network/JSONRPC.hs | unlicense | 835 | 0 | 5 | 155 | 56 | 42 | 14 | 7 | 0 |
-- Copyright 2020-2021 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
module TestUtils
( type (<), theFin, theSInt
, atNat, asFin, showTyped, showsPrecTyped
) where
import Data.Fin.Int (Fin)
import Data.SInt (SInt)
import Data.Typeable (Typeable, typeOf)
import GHC.TypeNats (CmpNat)
type m < n = CmpNat m n ~ 'LT
theSInt :: SInt n -> SInt n
theSInt = id
theFin :: Fin n -> Fin n
theFin = id
atNat :: SInt n -> p n -> p n
atNat _ = id
asFin :: Fin n -> SInt n -> Fin n
asFin = const
showsPrecTyped :: (Show a, Typeable a) => Int -> a -> ShowS
showsPrecTyped p x = showParen (p > 0) $
shows x . showString " :: " . shows (typeOf x)
showTyped :: (Show a, Typeable a) => a -> String
showTyped x = showsPrecTyped 0 x ""
| google/hs-dependent-literals | dependent-literals-plugin/tests/TestUtils.hs | apache-2.0 | 1,392 | 0 | 10 | 288 | 323 | 180 | 143 | -1 | -1 |
{-# LANGUAGE DeriveFunctor #-}
-- |CmdLine.hs
--
-- Command-line options parsing, using optparser-applicative.
--
--
--
-- Copyright (C) 2014 Braa Research, LLC.
module DNA.CmdOpts (
StartOpt(..)
, UnixStart(..)
, CommonOpt(..)
, dnaParseOptions
) where
import Control.Monad
import Options.Applicative
import System.Environment
-- | Options for different methods of starting DNA program
data StartOpt
= Unix Int -- ^ UNIX start
| UnixWorker UnixStart
| Slurm
| SlurmWorker FilePath
deriving (Show)
-- | Options for UNIX start
data UnixStart = UnixStart
{ dnaUnixNProc :: Int -- ^ Total N of processes
, dnaUnixPID :: String -- ^ PID of process
, dnaUnixRank :: Int -- ^ Rank of process
, dnaUnixWDir :: FilePath -- ^ Working directory for program
}
deriving (Show)
-- | Options common for all method of starting DNA program.
data CommonOpt = CommonOpt
{ dnaBasePort :: Int -- ^ Base port for program
}
deriving (Show)
-- | Obtain startup options for
dnaParseOptions :: IO (StartOpt, CommonOpt)
dnaParseOptions = do
-- Parse command line parameters
args <- getArgs
-- FIXME: Alternative instance doesn't work properly for composite
-- parsers. Probably bug should be filed for that
let a <.> b = (,) <$> a <*> b
let run p = execParserPure ParserPrefs
{ prefMultiSuffix = "VAR"
, prefDisambiguate = False
, prefShowHelpOnError = True
, prefBacktrack = True
, prefColumns = 80
}
(wrapParser p) args
-- FIXME: better error reporting required
case run (optUnixWorker <.> optCommon) of
Success a -> return a
_ -> case run (optUnix <.> optCommon) of
Success a -> return a
_ -> case run (optSlurmWorker <.> optCommon) of
Success a -> return a
_ -> case run (optSlurm <.> optCommon) of
Success a -> return a
_ -> error "Cannot parse command line parameters"
where
wrapParser p = info (helper <*> p)
( fullDesc
<> progDesc "Start DNA program"
<> header ("DNA Cloud Haskell implementation")
)
--
optUnix = Unix <$> optNProcs
optUnixWorker = UnixWorker <$>
( UnixStart
<$> optNProcs
<*> optPID
<*> optRank
<*> optWDir
)
optSlurm = pure Slurm
optSlurmWorker = SlurmWorker <$> optWDir
optCommon = CommonOpt <$> optBasePort
-- Parsers for
optWDir = option str
( metavar "DIR"
<> long "workdir"
<> help "Working directory for program"
)
optRank = option positiveNum
( metavar "RANK"
<> long "internal-rank"
<> hidden
<> help "specify rank of process [DO NOT USE MANUALLY!]"
)
<|> pure 0
optPID = option str
( metavar "PID"
<> long "internal-pid"
<> hidden
<> help "specify Job ID of process"
)
optBasePort = option readPort
( metavar "PORT"
<> long "base-port"
<> help "set base port for processes (default 40000)"
)
<|> pure 40000
optNProcs = option positiveNum
( metavar "N"
<> long "nprocs"
<> help "number of processe to spawn"
)
positiveNum :: (Read a, Ord a, Num a) => ReadM a
positiveNum = do
a <- auto
guard (a >= 0)
return a
readPort :: ReadM Int
readPort = do
a <- auto
guard (a > 0 && a < 65535)
return a
| SKA-ScienceDataProcessor/RC | MS2/lib/DNA/CmdOpts.hs | apache-2.0 | 3,821 | 8 | 20 | 1,421 | 704 | 386 | 318 | 92 | 5 |
module Delahaye.A338034Spec (main, spec) where
import Test.Hspec
import Delahaye.A338034 (a338034)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A338034" $
it "correctly computes the first 20 elements" $
take 20 (map a338034 [1..]) `shouldBe` expectedValue where
expectedValue = [0, 0, 0, 0, 1, 0, 0, 3, 3, 0, 0, 7, 9, 7, 0, 0, 12, 21, 21, 12]
| peterokagey/haskellOEIS | test/Delahaye/A338034Spec.hs | apache-2.0 | 374 | 0 | 10 | 78 | 160 | 95 | 65 | 10 | 1 |
module Database.Sophia.Types where
import qualified Bindings.Sophia as S
newtype Db = Db { unDb :: S.Db }
newtype Env = Env { unEnv :: S.Env }
newtype Cursor = Cursor { unCursor :: S.Cursor }
| Peaker/hssophia | Database/Sophia/Types.hs | bsd-2-clause | 194 | 0 | 7 | 37 | 60 | 41 | 19 | 5 | 0 |
{-# OPTIONS -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Data.ZoomCache
-- Copyright : Conrad Parker
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Conrad Parker <[email protected]>
-- Stability : unstable
-- Portability : unknown
--
-- API for implementing ZoomCache applications
----------------------------------------------------------------------
module Data.ZoomCache (
-- * TimeStamps
TimeStamp (..)
, TimeStampDiff(..)
, timeStampDiff
, timeStampFromSO
, Timestampable(..)
, before
, UTCTimestampable(..)
, beforeUTC
, timeStampFromUTCTime
, utcTimeFromTimeStamp
-- * Types
, SampleOffset(..)
, TrackNo
, Codec(..)
, IdentifyCodec
, SampleRateType(..)
, Global(..)
, CacheFile(..)
, ZoomReadable(..)
, ZoomRaw(..)
, ZoomSummary(..)
, Packet(..)
, Summary(..)
, ZoomSummaryUTC(..)
, PacketUTC(..)
, SummaryUTC(..)
, ZoomSummarySO(..)
, PacketSO(..)
, SummarySO(..)
-- * Track specification
, TrackMap
, TrackSpec(..)
-- * The ZoomWrite class
, ZoomWrite(..)
, ZoomWritable(..)
-- * The ZoomW monad
, ZoomW
, withFileWrite
, flush
-- * ZoomWHandle IO functions
, ZoomWHandle
, openWrite
, closeWrite
-- * Watermarks
, watermark
, setWatermark
-- * TrackSpec helpers
, setCodec
, setCodecMultichannel
, mkTrackSpec
, oneTrack
-- * Standard identifiers
, standardIdentifiers
-- * Iteratee parsers
, module Data.Iteratee.ZoomCache
-- * Pretty printing
, module Data.ZoomCache.Pretty
) where
import Data.Int
import Data.Word
import Data.ZoomCache.Write
import Data.Iteratee.ZoomCache
import Data.ZoomCache.Common
import Data.ZoomCache.Identify
import Data.ZoomCache.Pretty
import Data.ZoomCache.TrackSpec
import Data.ZoomCache.Types
-- Track Types
import Data.ZoomCache.Bool()
import Data.ZoomCache.Unit()
import Data.ZoomCache.Numeric.IEEE754()
import Data.ZoomCache.Numeric.Int()
import Data.ZoomCache.Numeric.Word()
----------------------------------------------------------------------
-- | 'IdentifyTrack' functions provided for standard codecs provided
-- by the zoom-cache library.
standardIdentifiers :: [IdentifyCodec]
standardIdentifiers =
[ identifyCodec (undefined :: Float)
, identifyCodec (undefined :: Double)
, identifyCodec (undefined :: Int)
, identifyCodec (undefined :: Int8)
, identifyCodec (undefined :: Int16)
, identifyCodec (undefined :: Int32)
, identifyCodec (undefined :: Int64)
, identifyCodec (undefined :: Word)
, identifyCodec (undefined :: Word8)
, identifyCodec (undefined :: Word16)
, identifyCodec (undefined :: Word32)
, identifyCodec (undefined :: Word64)
, identifyCodec (undefined :: Integer)
, identifyCodec (undefined :: ())
, identifyCodec (undefined :: Bool)
]
| kfish/zoom-cache | Data/ZoomCache.hs | bsd-2-clause | 3,009 | 0 | 8 | 653 | 572 | 383 | 189 | 80 | 1 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1993-1998
This is useful, general stuff for the Native Code Generator.
Provide trees (of instructions), so that lists of instructions
can be appended in linear time.
-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE BangPatterns #-}
module OrdList (
OrdList,
nilOL, isNilOL, unitOL, appOL, consOL, snocOL, concatOL, lastOL,
headOL,
mapOL, fromOL, toOL, foldrOL, foldlOL, reverseOL, fromOLReverse,
strictlyEqOL, strictlyOrdOL
) where
import GhcPrelude
import Data.Foldable
import Outputable
import qualified Data.Semigroup as Semigroup
infixl 5 `appOL`
infixl 5 `snocOL`
infixr 5 `consOL`
data OrdList a
= None
| One a
| Many [a] -- Invariant: non-empty
| Cons a (OrdList a)
| Snoc (OrdList a) a
| Two (OrdList a) -- Invariant: non-empty
(OrdList a) -- Invariant: non-empty
deriving (Functor)
instance Outputable a => Outputable (OrdList a) where
ppr ol = ppr (fromOL ol) -- Convert to list and print that
instance Semigroup (OrdList a) where
(<>) = appOL
instance Monoid (OrdList a) where
mempty = nilOL
mappend = (Semigroup.<>)
mconcat = concatOL
instance Foldable OrdList where
foldr = foldrOL
foldl' = foldlOL
toList = fromOL
null = isNilOL
length = lengthOL
instance Traversable OrdList where
traverse f xs = toOL <$> traverse f (fromOL xs)
nilOL :: OrdList a
isNilOL :: OrdList a -> Bool
unitOL :: a -> OrdList a
snocOL :: OrdList a -> a -> OrdList a
consOL :: a -> OrdList a -> OrdList a
appOL :: OrdList a -> OrdList a -> OrdList a
concatOL :: [OrdList a] -> OrdList a
headOL :: OrdList a -> a
lastOL :: OrdList a -> a
lengthOL :: OrdList a -> Int
nilOL = None
unitOL as = One as
snocOL as b = Snoc as b
consOL a bs = Cons a bs
concatOL aas = foldr appOL None aas
headOL None = panic "headOL"
headOL (One a) = a
headOL (Many as) = head as
headOL (Cons a _) = a
headOL (Snoc as _) = headOL as
headOL (Two as _) = headOL as
lastOL None = panic "lastOL"
lastOL (One a) = a
lastOL (Many as) = last as
lastOL (Cons _ as) = lastOL as
lastOL (Snoc _ a) = a
lastOL (Two _ as) = lastOL as
lengthOL None = 0
lengthOL (One _) = 1
lengthOL (Many as) = length as
lengthOL (Cons _ as) = 1 + length as
lengthOL (Snoc as _) = 1 + length as
lengthOL (Two as bs) = length as + length bs
isNilOL None = True
isNilOL _ = False
None `appOL` b = b
a `appOL` None = a
One a `appOL` b = Cons a b
a `appOL` One b = Snoc a b
a `appOL` b = Two a b
fromOL :: OrdList a -> [a]
fromOL a = go a []
where go None acc = acc
go (One a) acc = a : acc
go (Cons a b) acc = a : go b acc
go (Snoc a b) acc = go a (b:acc)
go (Two a b) acc = go a (go b acc)
go (Many xs) acc = xs ++ acc
fromOLReverse :: OrdList a -> [a]
fromOLReverse a = go a []
-- acc is already in reverse order
where go :: OrdList a -> [a] -> [a]
go None acc = acc
go (One a) acc = a : acc
go (Cons a b) acc = go b (a : acc)
go (Snoc a b) acc = b : go a acc
go (Two a b) acc = go b (go a acc)
go (Many xs) acc = reverse xs ++ acc
mapOL :: (a -> b) -> OrdList a -> OrdList b
mapOL = fmap
foldrOL :: (a->b->b) -> b -> OrdList a -> b
foldrOL _ z None = z
foldrOL k z (One x) = k x z
foldrOL k z (Cons x xs) = k x (foldrOL k z xs)
foldrOL k z (Snoc xs x) = foldrOL k (k x z) xs
foldrOL k z (Two b1 b2) = foldrOL k (foldrOL k z b2) b1
foldrOL k z (Many xs) = foldr k z xs
-- | Strict left fold.
foldlOL :: (b->a->b) -> b -> OrdList a -> b
foldlOL _ z None = z
foldlOL k z (One x) = k z x
foldlOL k z (Cons x xs) = let !z' = (k z x) in foldlOL k z' xs
foldlOL k z (Snoc xs x) = let !z' = (foldlOL k z xs) in k z' x
foldlOL k z (Two b1 b2) = let !z' = (foldlOL k z b1) in foldlOL k z' b2
foldlOL k z (Many xs) = foldl' k z xs
toOL :: [a] -> OrdList a
toOL [] = None
toOL [x] = One x
toOL xs = Many xs
reverseOL :: OrdList a -> OrdList a
reverseOL None = None
reverseOL (One x) = One x
reverseOL (Cons a b) = Snoc (reverseOL b) a
reverseOL (Snoc a b) = Cons b (reverseOL a)
reverseOL (Two a b) = Two (reverseOL b) (reverseOL a)
reverseOL (Many xs) = Many (reverse xs)
-- | Compare not only the values but also the structure of two lists
strictlyEqOL :: Eq a => OrdList a -> OrdList a -> Bool
strictlyEqOL None None = True
strictlyEqOL (One x) (One y) = x == y
strictlyEqOL (Cons a as) (Cons b bs) = a == b && as `strictlyEqOL` bs
strictlyEqOL (Snoc as a) (Snoc bs b) = a == b && as `strictlyEqOL` bs
strictlyEqOL (Two a1 a2) (Two b1 b2) = a1 `strictlyEqOL` b1 && a2 `strictlyEqOL` b2
strictlyEqOL (Many as) (Many bs) = as == bs
strictlyEqOL _ _ = False
-- | Compare not only the values but also the structure of two lists
strictlyOrdOL :: Ord a => OrdList a -> OrdList a -> Ordering
strictlyOrdOL None None = EQ
strictlyOrdOL None _ = LT
strictlyOrdOL (One x) (One y) = compare x y
strictlyOrdOL (One _) _ = LT
strictlyOrdOL (Cons a as) (Cons b bs) =
compare a b `mappend` strictlyOrdOL as bs
strictlyOrdOL (Cons _ _) _ = LT
strictlyOrdOL (Snoc as a) (Snoc bs b) =
compare a b `mappend` strictlyOrdOL as bs
strictlyOrdOL (Snoc _ _) _ = LT
strictlyOrdOL (Two a1 a2) (Two b1 b2) =
(strictlyOrdOL a1 b1) `mappend` (strictlyOrdOL a2 b2)
strictlyOrdOL (Two _ _) _ = LT
strictlyOrdOL (Many as) (Many bs) = compare as bs
strictlyOrdOL (Many _ ) _ = GT
| sdiehl/ghc | compiler/utils/OrdList.hs | bsd-3-clause | 5,746 | 0 | 10 | 1,691 | 2,526 | 1,276 | 1,250 | 148 | 6 |
module Main where
#if ! MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif
import Control.Monad (forever)
import Control.Concurrent.MVar
( newEmptyMVar
, putMVar
, takeMVar
, withMVar
)
import qualified Network.Transport as NT (Transport)
import Network.Transport.TCP()
import Control.Distributed.Process.Platform.Time
import Control.Distributed.Process
import Control.Distributed.Process.Node
import Control.Distributed.Process.Serializable()
import Control.Distributed.Process.Platform.Timer
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Control.Distributed.Process.Platform.Test
import TestUtils
testSendAfter :: TestResult Bool -> Process ()
testSendAfter result =
let delay = seconds 1 in do
sleep $ seconds 10
pid <- getSelfPid
_ <- sendAfter delay pid Ping
hdInbox <- receiveTimeout (asTimeout (seconds 2)) [
match (\m@(Ping) -> return m)
]
case hdInbox of
Just Ping -> stash result True
Nothing -> stash result False
testRunAfter :: TestResult Bool -> Process ()
testRunAfter result =
let delay = seconds 2 in do
parentPid <- getSelfPid
_ <- spawnLocal $ do
_ <- runAfter delay $ send parentPid Ping
return ()
msg <- expectTimeout ((asTimeout delay) * 4)
case msg of
Just Ping -> stash result True
Nothing -> stash result False
return ()
testCancelTimer :: TestResult Bool -> Process ()
testCancelTimer result = do
let delay = milliSeconds 50
pid <- periodically delay noop
ref <- monitor pid
sleep $ seconds 1
cancelTimer pid
_ <- receiveWait [
match (\(ProcessMonitorNotification ref' pid' _) ->
stash result $ ref == ref' && pid == pid')
]
return ()
testPeriodicSend :: TestResult Bool -> Process ()
testPeriodicSend result = do
let delay = milliSeconds 100
self <- getSelfPid
ref <- ticker delay self
listener 0 ref
liftIO $ putMVar result True
where listener :: Int -> TimerRef -> Process ()
listener n tRef | n > 10 = cancelTimer tRef
| otherwise = waitOne >> listener (n + 1) tRef
-- get a single tick, blocking indefinitely
waitOne :: Process ()
waitOne = do
Tick <- expect
return ()
testTimerReset :: TestResult Int -> Process ()
testTimerReset result = do
let delay = seconds 10
counter <- liftIO $ newEmptyMVar
listenerPid <- spawnLocal $ do
stash counter 0
-- we continually listen for 'ticks' and increment counter for each
forever $ do
Tick <- expect
liftIO $ withMVar counter (\n -> (return (n + 1)))
-- this ticker will 'fire' every 10 seconds
ref <- ticker delay listenerPid
sleep $ seconds 2
resetTimer ref
-- at this point, the timer should be back to roughly a 5 second count down
-- so our few remaining cycles no ticks ought to make it to the listener
-- therefore we kill off the timer and the listener now and take the count
cancelTimer ref
kill listenerPid "stop!"
-- how many 'ticks' did the listener observer? (hopefully none!)
count <- liftIO $ takeMVar counter
liftIO $ putMVar result count
testTimerFlush :: TestResult Bool -> Process ()
testTimerFlush result = do
let delay = seconds 1
self <- getSelfPid
ref <- ticker delay self
-- sleep so we *should* have a message in our 'mailbox'
sleep $ milliSeconds 2
-- flush it out if it's there
flushTimer ref Tick (Delay $ seconds 3)
m <- expectTimeout 10
case m of
Nothing -> stash result True
Just Tick -> stash result False
testSleep :: TestResult Bool -> Process ()
testSleep r = do
sleep $ seconds 20
stash r True
--------------------------------------------------------------------------------
-- Utilities and Plumbing --
--------------------------------------------------------------------------------
tests :: LocalNode -> [Test]
tests localNode = [
testGroup "Timer Tests" [
testCase "testSendAfter"
(delayedAssertion
"expected Ping within 1 second"
localNode True testSendAfter)
, testCase "testRunAfter"
(delayedAssertion
"expecting run (which pings parent) within 2 seconds"
localNode True testRunAfter)
, testCase "testCancelTimer"
(delayedAssertion
"expected cancelTimer to exit the timer process normally"
localNode True testCancelTimer)
, testCase "testPeriodicSend"
(delayedAssertion
"expected ten Ticks to have been sent before exiting"
localNode True testPeriodicSend)
, testCase "testTimerReset"
(delayedAssertion
"expected no Ticks to have been sent before resetting"
localNode 0 testTimerReset)
, testCase "testTimerFlush"
(delayedAssertion
"expected all Ticks to have been flushed"
localNode True testTimerFlush)
, testCase "testSleep"
(delayedAssertion
"why am I not seeing a delay!?"
localNode True testTimerFlush)
]
]
timerTests :: NT.Transport -> IO [Test]
timerTests transport = do
localNode <- newLocalNode transport initRemoteTable
let testData = tests localNode
return testData
main :: IO ()
main = testMain $ timerTests
| haskell-distributed/distributed-process-platform | tests/TestTimer.hs | bsd-3-clause | 5,568 | 0 | 21 | 1,564 | 1,355 | 658 | 697 | 136 | 2 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RankNTypes #-}
module Fragment.TyAll.Rules.Type (
TyAllNormalizeConstraint
, tyAllNormalizeRules
) where
import Control.Lens (review, preview)
import Rules.Type
import Ast.Type
import Fragment.TyAll.Ast.Type
type TyAllNormalizeConstraint ki ty a = AsTyAll ki ty
normalizeAll :: TyAllNormalizeConstraint ki ty a
=> (forall b. Type ki ty b -> Type ki ty b)
-> Type ki ty a
-> Maybe (Type ki ty a)
normalizeAll normalizeFn ty = do
(k, s) <- preview _TyAll ty
return $ review _TyAll (k, scopeAppTy normalizeFn s)
tyAllNormalizeRules :: TyAllNormalizeConstraint ki ty a
=> NormalizeInput ki ty a
tyAllNormalizeRules =
NormalizeInput
[ NormalizeTypeRecurse normalizeAll ]
| dalaing/type-systems | src/Fragment/TyAll/Rules/Type.hs | bsd-3-clause | 948 | 0 | 10 | 213 | 221 | 119 | 102 | 22 | 1 |
module ArbitraryCards where
import Game.Cards.CardSuit
import Game.Cards.CardValue
import Game.Cards.Card
import Test.QuickCheck
instance Arbitrary CardSuit where
arbitrary = elements [Spades, Clubs, Hearts, Diamonds]
instance Arbitrary CardValue where
arbitrary = elements [Two .. Ace]
| erm0l0v/Cards | test/ArbitraryCards.hs | bsd-3-clause | 295 | 0 | 7 | 40 | 77 | 46 | 31 | 9 | 0 |
{-# LANGUAGE ConstraintKinds, DataKinds, FlexibleContexts, FlexibleInstances, GADTs, MultiParamTypeClasses, PolyKinds, RankNTypes, ScopedTypeVariables, TypeFamilies, TypeOperators #-}
module Data.Functor.Union where
import qualified Control.Concurrent as CC
import qualified Control.Exception as E
import Control.Monad.Free.Freer
import Control.Monad.IO.Class
import Data.Functor.Classes
import Data.Kind
import qualified Foreign.C.String as C
import Foreign.Ptr
import qualified Foreign.Marshal.Alloc as A
import qualified Foreign.Storable as S
data Union (fs :: [k -> *]) (a :: k) where
Here :: f a -> Union (f ': fs) a
There :: Union fs a -> Union (f ': fs) a
type Eff fs = Freer (Union fs)
data Product (fs :: [*]) where
Nil :: Product '[]
(:.) :: a -> Product as -> Product (a ': as)
infixr 5 :.
wrapU :: InUnion fs f => f (Freer (Union fs) a) -> Freer (Union fs) a
wrapU = wrap . inj
runM :: Monad m => Freer m a -> m a
runM = foldFreer id
foldFreer :: Monad m => (forall x. f x -> m x) -> Freer f a -> m a
foldFreer f = iterFreerA ((>>=) . f)
weaken :: Superset fs gs => Union gs a -> Union fs a
weaken (Here f) = inj f
weaken (There t) = weaken t
weaken1 :: Union fs a -> Union (f ': fs) a
weaken1 = There
strengthen :: Union '[f] a -> f a
strengthen (Here f) = f
strengthen _ = undefined
send :: InUnion fs f => f a -> Eff fs a
send = liftF . inj
sendIO :: InUnion fs IO => IO a -> Eff fs a
sendIO = send
hoistUnion :: (f a -> g a) -> Union (f ': fs) a -> Union (g ': fs) a
hoistUnion f (Here e) = Here (f e)
hoistUnion _ (There t) = There t
type family Superset (fs :: [k]) (gs :: [k]) :: Constraint where
Superset fs (f ': gs) = (InUnion fs f, Superset fs gs)
Superset fs '[] = ()
type family Map (f :: k -> l) (as :: [k]) :: [l] where
Map f (a ': as) = f a ': Map f as
Map _ '[] = '[]
-- Injection and projection
class InUnion (fs :: [k -> *]) (f :: k -> *) where
inj :: f a -> Union fs a
prj :: Union fs a -> Maybe (f a)
instance {-# OVERLAPPABLE #-} InUnion (f ': fs) f where
inj = Here
prj (Here f) = Just f
prj _ = Nothing
instance {-# OVERLAPPABLE #-} InUnion fs f => InUnion (g ': fs) f where
inj = There . inj
prj (There fs) = prj fs
prj _ = Nothing
class Case (fs :: [k -> *]) where
type Patterns fs (a :: k) b :: [*]
caseU :: Union fs a -> Product (Patterns fs a b) -> b
instance Case fs => Case (f ': fs) where
type Patterns (f ': fs) a b = (f a -> b) ': Patterns fs a b
caseU (Here f) (here :. _) = here f
caseU (There fs) (_ :. there) = caseU fs there
instance Case '[] where
type Patterns '[] a b = '[]
caseU _ _ = error "case analysis on empty union"
instance (Show1 f, Show1 (Union fs)) => Show1 (Union (f ': fs)) where
liftShowsPrec sp sl d (Here f) = showsUnaryWith (liftShowsPrec sp sl) "inj" d f
liftShowsPrec sp sl d (There t) = liftShowsPrec sp sl d t
instance (Foldable f, Foldable (Union fs)) => Foldable (Union (f ': fs)) where
foldMap f (Here r) = foldMap f r
foldMap f (There r) = foldMap f r
instance Foldable (Union '[]) where
foldMap _ _ = mempty
instance Functor f => Functor (Union '[f]) where
fmap f = Here . fmap f . strengthen
instance (Functor f, Functor (Union (g ': hs))) => Functor (Union (f ': g ': hs)) where
fmap f (Here e) = Here (fmap f e)
fmap f (There t) = There (fmap f t)
instance Applicative f => Applicative (Union '[f]) where
pure = Here . pure
f <*> a = Here $ strengthen f <*> strengthen a
instance Monad m => Monad (Union '[m]) where
return = pure
m >>= f = Here $ strengthen m >>= strengthen . f
instance InUnion fs IO => MonadIO (Freer (Union fs)) where
liftIO = send
allocaBytes :: InUnion fs IO => Int -> (Ptr a -> Eff fs b) -> Eff fs b
allocaBytes i f = inj (A.allocaBytes i (return . f)) `Then` id
alloca :: forall a b fs. (InUnion fs IO, S.Storable a) => (Ptr a -> Eff fs b) -> Eff fs b
alloca = allocaBytes (sizeOf (undefined :: a))
bracket :: InUnion fs IO => Eff fs a -> (a -> Eff fs b) -> (a -> Eff fs c) -> Eff fs c
bracket before after thing = inj (E.bracket (return before) (return . (>>= after)) (return . (>>= thing))) `Then` id
finally :: InUnion fs IO => Eff fs a -> Eff fs b -> Eff fs a
finally thing ender = inj (E.finally (return thing) (return ender)) `Then` id
peek :: (MonadIO m, S.Storable a) => Ptr a -> m a
peek = liftIO . S.peek
poke :: (MonadIO m, S.Storable a) => Ptr a -> a -> m ()
poke = (liftIO .) . S.poke
pokeElemOff :: (MonadIO m, S.Storable a) => Ptr a -> Int -> a -> m ()
pokeElemOff = ((liftIO .) .) . S.pokeElemOff
sizeOf :: S.Storable a => a -> Int
sizeOf = S.sizeOf
peekCString :: MonadIO m => C.CString -> m String
peekCString = liftIO . C.peekCString
withCString :: InUnion fs IO => String -> (C.CString -> Eff fs a) -> Eff fs a
withCString string f = inj (C.withCString string (return . f)) `Then` id
runInBoundThread :: InUnion fs IO => Eff fs a -> Eff fs a
runInBoundThread action = inj (CC.runInBoundThread (return action)) `Then` id
catch :: (InUnion fs IO, E.Exception e) => Eff fs a -> (e -> Eff fs a) -> Eff fs a
catch act handler = inj (E.catch (return act) (return . handler)) `Then` id
| robrix/ui-effects | src/Data/Functor/Union.hs | bsd-3-clause | 5,127 | 0 | 11 | 1,154 | 2,614 | 1,358 | 1,256 | 113 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Hasmin.Parser.Selector
-- Copyright : (c) 2017 Cristian Adrián Ontivero
-- License : BSD3
-- Stability : experimental
-- Portability : unknown
--
-----------------------------------------------------------------------------
module Hasmin.Parser.Selector
( selectors
, selector
) where
import Control.Applicative ((<|>), many, some, empty, optional)
import Data.Attoparsec.Combinator (sepBy)
import Data.Attoparsec.Text (asciiCI, char, Parser, satisfy, string)
import qualified Data.Attoparsec.Text as A
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Functor (($>))
import qualified Data.Text.Lazy.Builder as LB
import Data.List.NonEmpty (NonEmpty( (:|) ))
import Hasmin.Parser.Utils
import Hasmin.Parser.String
import Hasmin.Utils
import Hasmin.Types.Selector
import Hasmin.Types.String
-- | Parser for CSS complex selectors (see 'Selector' for more details).
selector :: Parser Selector
selector = Selector <$> compoundSelector <*> combinatorsAndSelectors
where combinatorsAndSelectors = many $ mzip (combinator <* skipComments) compoundSelector
-- First tries with '>>' (descendant), '>' (child), '+' (adjacent sibling), and
-- '~' (general sibling) combinators. If those fail, it tries with the
-- descendant (whitespace) combinator. This is done to allow comments in-between.
--
-- | Parser for selector combinators, i.e. ">>" (descendant), '>' (child), '+'
-- (adjacent sibling), '~' (general sibling), and ' ' (descendant) combinators.
combinator :: Parser Combinator
combinator = (skipComments *> ((string ">>" $> DescendantBrackets)
<|> (char '>' $> Child)
<|> (char '+' $> AdjacentSibling)
<|> (char '~' $> GeneralSibling)))
<|> (satisfy ws $> DescendantSpace)
where ws c = c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'
compoundSelector :: Parser CompoundSelector
compoundSelector = cs1 <|> cs2
where cs1 = do
sel <- typeSelector <|> universal
sels <- many p
pure $ sel:|sels
cs2 = (Universal mempty :|) <$> some p
p = idSel <|> classSel <|> attributeSel <|> pseudo
-- | Parses a \"number sign\" (U+0023, \#) immediately followed by the ID value,
-- which must be a CSS identifier.
idSel :: Parser SimpleSelector
idSel = do
_ <- char '#'
name <- mconcat <$> some nmchar
pure . IdSel . TL.toStrict $ LB.toLazyText name
-- class: '.' IDENT
classSel :: Parser SimpleSelector
classSel = char '.' *> (ClassSel <$> ident)
{-
attrib
: '[' S* [ namespace_prefix ]? IDENT S*
[ [ PREFIXMATCH |
SUFFIXMATCH |
SUBSTRINGMATCH |
'=' |
INCLUDES |
DASHMATCH ] S* [ IDENT | STRING ] S*
]? ']'
;
-}
-- FIXME namespace prefixes aren't allowed inside attribute selectors,
-- but they should be.
attributeSel :: Parser SimpleSelector
attributeSel = do
_ <- char '['
attId <- lexeme ident
g <- A.option Attribute attValue
_ <- char ']'
pure $ AttributeSel (g attId)
where attValue = do
f <- ((string "^=" $> (:^=:)) <|>
(string "$=" $> (:$=:)) <|>
(string "*=" $> (:*=:)) <|>
(string "=" $> (:=:)) <|>
(string "~=" $> (:~=:)) <|>
(string "|=" $> (:|=:))) <* skipComments
attval <- identOrString <* skipComments
pure (`f` attval)
-- type_selector: [namespace_prefix]? element_name
typeSelector :: Parser SimpleSelector
typeSelector = Type <$> opt namespacePrefix <*> ident
-- universal: [ namespace_prefix ]? '*'
universal :: Parser SimpleSelector
universal = Universal <$> opt namespacePrefix <* char '*'
-- namespace_prefix: [ IDENT | '*' ]? '|'
namespacePrefix :: Parser Text
namespacePrefix = opt (ident <|> string "*") <* char '|'
{- '::' starts a pseudo-element, ':' a pseudo-class
Exceptions: :first-line, :first-letter, :before and :after.
Note that pseudo-elements are restricted to one per selector and
occur only in the last simple_selector_sequence.
<pseudo-class-selector> = ':' <ident-token> |
':' <function-token> <any-value> ')'
<pseudo-element-selector> = ':' <pseudo-class-selector>
-}
-- pseudo: ':' ':'? [ IDENT | functional_pseudo ]
pseudo :: Parser SimpleSelector
pseudo = char ':' *> (pseudoElementSelector <|> pseudoClassSelector)
where pseudoClassSelector = do
i <- ident
c <- A.peekChar
case c of
Just '(' -> char '(' *> case Map.lookup (T.toLower i) fpcMap of
Just p -> functionParser p
Nothing -> functionParser (FunctionalPseudoClass i <$> A.takeWhile (/= ')'))
_ -> pure $ PseudoClass i
pseudoElementSelector =
(char ':' *> (PseudoElem <$> ident)) <|> (ident >>= handleSpecialCase)
where
handleSpecialCase :: Text -> Parser SimpleSelector
handleSpecialCase t
| isSpecialPseudoElement = pure $ PseudoElem t
| otherwise = empty
where isSpecialPseudoElement = T.toLower t `elem` specialPseudoElements
-- \<An+B> microsyntax parser.
anplusb :: Parser AnPlusB
anplusb = (asciiCI "even" $> Even)
<|> (asciiCI "odd" $> Odd)
<|> do
s <- optional parseSign
dgts <- A.option mempty digits
case dgts of
[] -> ciN *> skipComments *> A.option (A s Nothing) (AB s Nothing <$> bValue)
_ -> let n = read dgts :: Int
in (ciN *> skipComments *> A.option (A s $ Just n) (AB s (Just n) <$> bValue))
<|> (pure . B $ getSign s * n)
where ciN = satisfy (\c -> c == 'N' || c == 'n')
parseSign = (char '-' $> Minus) <|> (char '+' $> Plus)
getSign (Just Minus) = -1
getSign _ = 1
bValue = do
readPlus <- (char '-' $> False) <|> (char '+' $> True)
d <- skipComments *> digits
if readPlus
then pure $ read d
else pure $ read ('-':d)
-- Functional pseudo classes parsers map
fpcMap :: Map Text (Parser SimpleSelector)
fpcMap = Map.fromList
[buildTuple "nth-of-type" (\x -> FunctionalPseudoClass2 x <$> anplusb)
,buildTuple "nth-last-of-type" (\x -> FunctionalPseudoClass2 x <$> anplusb)
,buildTuple "nth-column" (\x -> FunctionalPseudoClass2 x <$> anplusb)
,buildTuple "nth-last-column" (\x -> FunctionalPseudoClass2 x <$> anplusb)
,buildTuple "not" (\x -> FunctionalPseudoClass1 x <$> compoundSelectorList)
,buildTuple "matches" (\x -> FunctionalPseudoClass1 x <$> compoundSelectorList)
,buildTuple "nth-child" (anbAndSelectors . FunctionalPseudoClass3)
,buildTuple "nth-last-child" (anbAndSelectors . FunctionalPseudoClass3)
,buildTuple "lang" (const (Lang <$> identOrString))
--
-- :drop( [ active || valid || invalid ]? )
-- The :drop() functional pseudo-class is identical to :drop
-- ,("drop", anplusb)
--
-- It accepts a comma-separated list of one or more language ranges as its
-- argument. Each language range in :lang() must be a valid CSS <ident> or
-- <string>.
-- ,("lang", anplusb)
--
-- ,("dir", text)
-- ,("has", relative selectors)
]
where buildTuple t c = (t, c t)
compoundSelectorList = (:) <$> compoundSelector <*> many (comma *> compoundSelector)
anbAndSelectors constructor = do
a <- anplusb <* skipComments
o <- A.option [] (asciiCI "of" *> skipComments *> compoundSelectorList)
pure $ constructor a o
-- | Parse a list of comma-separated selectors, ignoring whitespace and
-- comments.
selectors :: Parser [Selector]
selectors = lexeme selector `sepBy` char ','
identOrString :: Parser (Either Text StringType)
identOrString = (Left <$> ident) <|> (Right <$> stringtype)
| contivero/hasmin | src/Hasmin/Parser/Selector.hs | bsd-3-clause | 8,248 | 0 | 21 | 2,152 | 1,891 | 1,007 | 884 | 127 | 4 |
import Network
import Char
import Control.Concurrent
import System.IO (hGetChar, hGetLine, hClose, hPutStr, hSetBuffering, BufferMode(..), Handle,stdout)
main = withSocketsDo $ do
putStrLn "Welcome to my haskell websocket example"
hSetBuffering stdout NoBuffering
server --or client
putStrLn "Done"
--client
client = putStrLn("Not Yet")
--server
server = do
sock <- listenOn (PortNumber 1234)
putStrLn("Listening...")
(h, host, port) <- accept sock --Accept the socket
putStrLn $ "connection!"
hSetBuffering h NoBuffering
putStrLn "Handshaking..."
handShake h
putStrLn "Handshaken!"
--forkIO $ doTick h 0 --Not yet
wsInteract h sock 0
putStrLn "Stopping Server"
hClose h
sClose sock
wsInteract :: Handle -> Socket -> Int -> IO ()
wsInteract h s tick = do
stuff <- receive h ""
wsSend h $ "out ! "++stuff
doTick h tick
wsInteract h s (tick + 1)
doTick :: Handle -> Int -> IO ()
doTick h tick = do
wsSend h $ "clock ! tick"++show(tick)
handShake h = do
stuff <- hGetLine h
putStrLn $ "Handshake got: "++stuff
stuff <- hGetLine h
putStrLn $ "Handshake got: "++stuff
stuff <- hGetLine h
putStrLn $ "Handshake got: "++stuff
stuff <- hGetLine h
putStrLn $ "Handshake got: "++stuff
stuff <- hGetLine h
putStrLn $ "Handshake got: "++stuff
stuff <- hGetLine h
putStrLn $ "Handshake got: "++stuff
putStrLn "Done getting header - now sending ours"
hPutStr h "HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nWebSocket-Origin: http://localhost:8888\r\nWebSocket-Location: ws://localhost:1234/websession\r\n\r\n"
wsSend :: Handle -> String -> IO ()
wsSend h str = do
putStr "wsSending: "
putStrLn str
hPutStr h $ "\x00"++str++"\xff"
receive h str = do
new <- hGetChar h
putChar new
if new == chr 0 -- "\x00"
then receive h ""
else if new == chr 255 --"\xff"
then return str
else receive h (str++[new])
| fos/fos-legacy | scratch/very_scratch/server/example2/Wsocket.hs | bsd-3-clause | 1,973 | 15 | 12 | 422 | 645 | 299 | 346 | 60 | 3 |
module MSF.Event.Handler where
import qualified Control.Exception as X
import qualified Data.Map as Map
type Handler a = HandlerRef -> a -> IO ()
type HandlerRef = Int
data HandlerMap a = HandlerMap
{ handlers :: Map.Map HandlerRef (Handler a)
, handlerNextId :: HandlerRef
}
-- | An empty map of handlers.
emptyHandlerMap :: HandlerMap a
emptyHandlerMap = HandlerMap
{ handlers = Map.empty
, handlerNextId = 0
}
-- | Add a handler to a handler map.
addHandler :: Handler a -> HandlerMap a -> (HandlerRef,HandlerMap a)
addHandler k hs = (ref, hs')
where
ref = handlerNextId hs
hs' = HandlerMap
{ handlers = Map.insert (handlerNextId hs) k (handlers hs)
, handlerNextId = handlerNextId hs + 1
}
-- | Remove a handler from a handler map.
removeHandler :: HandlerRef -> HandlerMap a -> HandlerMap a
removeHandler k hs = hs
{ handlers = Map.delete k (handlers hs)
}
-- | Run a set of handlers over a value.
dispatchHandlers :: HandlerMap a -> a -> IO ()
dispatchHandlers hs a = mapM_ run (Map.toList (handlers hs))
where
run (ref,k) = k ref a `X.catch` handler
-- swallow exceptions to prevent handlers from killing the enclosing thread
handler :: X.SomeException -> IO ()
handler e = do
putStrLn "Encountered exception, swallowing."
print e
return ()
| GaloisInc/msf-haskell | src/MSF/Event/Handler.hs | bsd-3-clause | 1,330 | 0 | 11 | 296 | 392 | 211 | 181 | 29 | 1 |
module Type.Effect.Literal where
import qualified AST.Literal as L
import qualified Data.Map as Map
import qualified Reporting.Region as R
--import qualified Type.Environment as Env
import Type.Effect
constrain
:: Environment
-> R.Region
-> L.Literal
-> TypeAnnot
-> IO AnnotConstr
constrain _ region literal tipe =
return $ CEqual region tipe $ SinglePattern (toCtorString literal) []
toCtorString :: L.Literal -> String
toCtorString literal =
case literal of
L.IntNum i ->
( show i
)
L.FloatNum f ->
(show f
)
L.Chr c ->
( show c
)
L.Str s ->
( "\"" ++ s ++ "\""
)
L.Boolean b ->
( show b
)
| JoeyEremondi/elm-pattern-effects | src/Type/Effect/Literal.hs | bsd-3-clause | 793 | 0 | 10 | 301 | 218 | 115 | 103 | 26 | 5 |
-----------------------------------------------------------------------------
-- |
-- Module : System.FilePath.Lens
-- Copyright : (C) 2012-16 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : Rank2Types
--
----------------------------------------------------------------------------
module System.FilePath.Lens
(
-- * Operators
(</>~), (<</>~), (<<</>~), (<.>~), (<<.>~), (<<<.>~)
, (</>=), (<</>=), (<<</>=), (<.>=), (<<.>=), (<<<.>=)
-- * Lenses
, basename, directory, extension, filename
) where
import Prelude ()
import Control.Monad.State as State
import System.FilePath
( (</>), (<.>), splitExtension
, takeBaseName, takeDirectory
, takeExtension, takeFileName
)
import Control.Lens.Internal.Prelude
import Control.Lens hiding ((<.>))
-- $setup
-- >>> :set -XNoOverloadedStrings
{- NB: Be very careful if you are planning to modify the doctest output in
this module! Path separators are OS-dependent (\\ with Windows, / with Posix),
so we take great care to avoid using separators in doctest output so that they
will be valid on all operating systems.
If you find yourself wanting to test a function that uses path separators in
the output, it would be wise to:
1. Compare the tested expression and the expected results explicitly using (==).
2. Always use the </> function (and derived combinators) to construct path
separators instead of typing them manually. That is, don't type out
"foo/bar", but rather "foo" </> "bar".
This way we can avoid leaking path separators into the output. See the doctest
example for (</>~) for an example of how to do this.
-}
infixr 4 </>~, <</>~, <<</>~, <.>~, <<.>~, <<<.>~
infix 4 </>=, <</>=, <<</>=, <.>=, <<.>=, <<<.>=
-- | Modify the path by adding another path.
--
-- >>> (both </>~ "bin" $ ("hello","world")) == ("hello" </> "bin", "world" </> "bin")
-- True
--
-- @
-- ('</>~') :: 'Setter' s a 'FilePath' 'FilePath' -> 'FilePath' -> s -> a
-- ('</>~') :: 'Iso' s a 'FilePath' 'FilePath' -> 'FilePath' -> s -> a
-- ('</>~') :: 'Lens' s a 'FilePath' 'FilePath' -> 'FilePath' -> s -> a
-- ('</>~') :: 'Traversal' s a 'FilePath' 'FilePath' -> 'FilePath' -> s -> a
-- @
(</>~) :: ASetter s t FilePath FilePath -> FilePath -> s -> t
l </>~ n = over l (</> n)
{-# INLINE (</>~) #-}
-- | Modify the target(s) of a 'Lens'', 'Iso'', 'Setter'' or 'Traversal'' by adding a path.
--
-- >>> execState (both </>= "bin") ("hello","world") == ("hello" </> "bin", "world" </> "bin")
-- True
--
-- @
-- ('</>=') :: 'MonadState' s m => 'Setter'' s 'FilePath' -> 'FilePath' -> m ()
-- ('</>=') :: 'MonadState' s m => 'Iso'' s 'FilePath' -> 'FilePath' -> m ()
-- ('</>=') :: 'MonadState' s m => 'Lens'' s 'FilePath' -> 'FilePath' -> m ()
-- ('</>=') :: 'MonadState' s m => 'Traversal'' s 'FilePath' -> 'FilePath' -> m ()
-- @
(</>=) :: MonadState s m => ASetter' s FilePath -> FilePath -> m ()
l </>= b = State.modify (l </>~ b)
{-# INLINE (</>=) #-}
-- | Add a path onto the end of the target of a 'Lens' and return the result
--
-- When you do not need the result of the operation, ('</>~') is more flexible.
(<</>~) :: LensLike ((,)FilePath) s a FilePath FilePath -> FilePath -> s -> (FilePath, a)
l <</>~ m = l <%~ (</> m)
{-# INLINE (<</>~) #-}
-- | Add a path onto the end of the target of a 'Lens' into
-- your monad's state and return the result.
--
-- When you do not need the result of the operation, ('</>=') is more flexible.
(<</>=) :: MonadState s m => LensLike' ((,)FilePath) s FilePath -> FilePath -> m FilePath
l <</>= r = l <%= (</> r)
{-# INLINE (<</>=) #-}
-- | Add a path onto the end of the target of a 'Lens' and return the original
-- value.
--
-- When you do not need the original value, ('</>~') is more flexible.
(<<</>~) :: Optical' (->) q ((,)FilePath) s FilePath -> FilePath -> q s (FilePath, s)
l <<</>~ b = l $ \a -> (a, a </> b)
{-# INLINE (<<</>~) #-}
-- | Add a path onto the end of a target of a 'Lens' into your monad's state
-- and return the old value.
--
-- When you do not need the result of the operation, ('</>=') is more flexible.
(<<</>=) :: MonadState s m => LensLike' ((,)FilePath) s FilePath -> FilePath -> m FilePath
l <<</>= b = l %%= \a -> (a, a </> b)
{-# INLINE (<<</>=) #-}
-- | Modify the path by adding an extension.
--
-- >>> both <.>~ "txt" $ ("hello","world")
-- ("hello.txt","world.txt")
--
-- @
-- ('<.>~') :: 'Setter' s a 'FilePath' 'FilePath' -> 'String' -> s -> a
-- ('<.>~') :: 'Iso' s a 'FilePath' 'FilePath' -> 'String' -> s -> a
-- ('<.>~') :: 'Lens' s a 'FilePath' 'FilePath' -> 'String' -> s -> a
-- ('<.>~') :: 'Traversal' s a 'FilePath' 'FilePath' -> 'String' -> s -> a
-- @
(<.>~) :: ASetter s a FilePath FilePath -> String -> s -> a
l <.>~ n = over l (<.> n)
{-# INLINE (<.>~) #-}
-- | Modify the target(s) of a 'Lens'', 'Iso'', 'Setter'' or 'Traversal'' by adding an extension.
--
-- >>> execState (both <.>= "txt") ("hello","world")
-- ("hello.txt","world.txt")
--
-- @
-- ('<.>=') :: 'MonadState' s m => 'Setter'' s 'FilePath' -> 'String' -> m ()
-- ('<.>=') :: 'MonadState' s m => 'Iso'' s 'FilePath' -> 'String' -> m ()
-- ('<.>=') :: 'MonadState' s m => 'Lens'' s 'FilePath' -> 'String' -> m ()
-- ('<.>=') :: 'MonadState' s m => 'Traversal'' s 'FilePath' -> 'String' -> m ()
-- @
(<.>=) :: MonadState s m => ASetter' s FilePath -> String -> m ()
l <.>= b = State.modify (l <.>~ b)
{-# INLINE (<.>=) #-}
-- | Add an extension onto the end of the target of a 'Lens' and return the result
--
-- >>> _1 <<.>~ "txt" $ ("hello","world")
-- ("hello.txt",("hello.txt","world"))
--
-- When you do not need the result of the operation, ('<.>~') is more flexible.
(<<.>~) :: LensLike ((,)FilePath) s a FilePath FilePath -> String -> s -> (FilePath, a)
l <<.>~ m = l <%~ (<.> m)
{-# INLINE (<<.>~) #-}
-- | Add an extension onto the end of the target of a 'Lens' into
-- your monad's state and return the result.
--
-- >>> evalState (_1 <<.>= "txt") ("hello","world")
-- "hello.txt"
--
-- When you do not need the result of the operation, ('<.>=') is more flexible.
(<<.>=) :: MonadState s m => LensLike' ((,)FilePath) s FilePath -> String -> m FilePath
l <<.>= r = l <%= (<.> r)
{-# INLINE (<<.>=) #-}
-- | Add an extension onto the end of the target of a 'Lens' but
-- return the old value
--
-- >>> _1 <<<.>~ "txt" $ ("hello","world")
-- ("hello",("hello.txt","world"))
--
-- When you do not need the old value, ('<.>~') is more flexible.
(<<<.>~) :: Optical' (->) q ((,)FilePath) s FilePath -> String -> q s (FilePath, s)
l <<<.>~ b = l $ \a -> (a, a <.> b)
{-# INLINE (<<<.>~) #-}
-- | Add an extension onto the end of the target of a 'Lens' into your monad's
-- state and return the old value.
--
-- >>> runState (_1 <<<.>= "txt") ("hello","world")
-- ("hello",("hello.txt","world"))
--
-- When you do not need the old value, ('<.>=') is more flexible.
(<<<.>=) :: MonadState s m => LensLike' ((,)FilePath) s FilePath -> String -> m FilePath
l <<<.>= b = l %%= \a -> (a, a <.> b)
{-# INLINE (<<<.>=) #-}
-- | A 'Lens' for reading and writing to the basename
--
-- Note: This is 'not' a legal 'Lens' unless the outer 'FilePath' has both a directory
-- and filename component and the generated basenames are not null and contain no directory
-- separators.
--
-- >>> (basename .~ "filename" $ "path" </> "name.png") == "path" </> "filename.png"
-- True
basename :: Lens' FilePath FilePath
basename f p = (<.> takeExtension p) . (takeDirectory p </>) <$> f (takeBaseName p)
{-# INLINE basename #-}
-- | A 'Lens' for reading and writing to the directory
--
-- Note: this is /not/ a legal 'Lens' unless the outer 'FilePath' already has a directory component,
-- and generated directories are not null.
--
-- >>> (("long" </> "path" </> "name.txt") ^. directory) == "long" </> "path"
-- True
directory :: Lens' FilePath FilePath
directory f p = (</> takeFileName p) <$> f (takeDirectory p)
{-# INLINE directory #-}
-- | A 'Lens' for reading and writing to the extension
--
-- Note: This is /not/ a legal 'Lens', unless you are careful to ensure that generated
-- extension 'FilePath' components are either null or start with 'System.FilePath.extSeparator'
-- and do not contain any internal 'System.FilePath.extSeparator's.
--
-- >>> (extension .~ ".png" $ "path" </> "name.txt") == "path" </> "name.png"
-- True
extension :: Lens' FilePath FilePath
extension f p = (n <.>) <$> f e
where
(n, e) = splitExtension p
{-# INLINE extension #-}
-- | A 'Lens' for reading and writing to the full filename
--
-- Note: This is /not/ a legal 'Lens', unless you are careful to ensure that generated
-- filename 'FilePath' components are not null and do not contain any
-- elements of 'System.FilePath.pathSeparators's.
--
-- >>> (filename .~ "name.txt" $ "path" </> "name.png") == "path" </> "name.txt"
-- True
filename :: Lens' FilePath FilePath
filename f p = (takeDirectory p </>) <$> f (takeFileName p)
{-# INLINE filename #-}
| ddssff/lens | src/System/FilePath/Lens.hs | bsd-3-clause | 9,006 | 0 | 10 | 1,685 | 1,280 | 775 | 505 | 64 | 1 |
{-# OPTIONS_GHC -fno-warn-tabs #-}
{- $Id: TestsWFG.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* Y A M P A *
* *
* Module: TestsWFG *
* Purpose: Test cases for wave-form generation *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module TestsWFG (wfg_tr, wfg_trs) where
import FRP.Yampa
import TestsCommon
------------------------------------------------------------------------------
-- Test cases for wave-form generation
------------------------------------------------------------------------------
wfg_inp1 = deltaEncode 1.0 $
[NoEvent, NoEvent, Event 1.0, NoEvent,
Event 2.0, NoEvent, NoEvent, NoEvent,
Event 3.0, Event 4.0, Event 4.0, NoEvent,
Event 0.0, NoEvent, NoEvent, NoEvent]
++ repeat NoEvent
wfg_inp2 = deltaEncode 1.0 $
[Event 1.0, NoEvent, NoEvent, NoEvent,
Event 2.0, NoEvent, NoEvent, NoEvent,
Event 3.0, Event 4.0, Event 4.0, NoEvent,
Event 0.0, NoEvent, NoEvent, NoEvent]
++ repeat NoEvent
wfg_t0 :: [Double]
wfg_t0 = take 16 $ embed (hold 99.99) wfg_inp1
wfg_t0r =
[99.99, 99.99, 1.0, 1.0,
2.0, 2.0, 2.0, 2.0,
3.0, 4.0, 4.0, 4.0,
0.0, 0.0, 0.0, 0.0]
wfg_t1 :: [Double]
wfg_t1 = take 16 $ embed (hold 99.99) wfg_inp2
wfg_t1r =
[1.0, 1.0, 1.0, 1.0,
2.0, 2.0, 2.0, 2.0,
3.0, 4.0, 4.0, 4.0,
0.0, 0.0, 0.0, 0.0]
wfg_inp3 = deltaEncode 1.0 $
[Nothing, Nothing, Just 1.0, Just 2.0, Just 3.0,
Just 4.0, Nothing, Nothing, Nothing, Just 3.0,
Just 2.0, Nothing, Just 1.0, Just 0.0, Just 1.0,
Just 2.0, Just 3.0, Nothing, Nothing, Just 4.0]
++ repeat Nothing
wfg_inp4 = deltaEncode 1.0 $
[Just 0.0, Nothing, Just 1.0, Just 2.0, Just 3.0,
Just 4.0, Nothing, Nothing, Nothing, Just 3.0,
Just 2.0, Nothing, Just 1.0, Just 0.0, Just 1.0,
Just 2.0, Just 3.0, Nothing, Nothing, Just 4.0]
++ repeat Nothing
wfg_t2 :: [Double]
wfg_t2 = take 25 $ embed (trackAndHold 99.99) wfg_inp3
wfg_t2r =
[99.99, 99.99, 1.0, 2.0, 3.0,
4.0, 4.0, 4.0, 4.0, 3.0,
2.0, 2.0, 1.0, 0.0, 1.0,
2.0, 3.0, 3.0, 3.0, 4.0,
4.0, 4.0, 4.0, 4.0, 4.0]
wfg_t3 :: [Double]
wfg_t3 = take 25 $ embed (trackAndHold 99.99) wfg_inp4
wfg_t3r =
[0.0, 0.0, 1.0, 2.0, 3.0,
4.0, 4.0, 4.0, 4.0, 3.0,
2.0, 2.0, 1.0, 0.0, 1.0,
2.0, 3.0, 3.0, 3.0, 4.0,
4.0, 4.0, 4.0, 4.0, 4.0]
wfg_trs =
[ wfg_t0 ~= wfg_t0r,
wfg_t1 ~= wfg_t1r,
wfg_t2 ~= wfg_t2r,
wfg_t3 ~= wfg_t3r
]
wfg_tr = and wfg_trs
| ivanperez-keera/Yampa | yampa/tests/TestsWFG.hs | bsd-3-clause | 3,128 | 0 | 8 | 1,047 | 859 | 498 | 361 | 64 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE ConstraintKinds #-}
module Fragment.Record.Rules.Kind.Infer.SyntaxDirected (
RecordInferKindContext
, recordInferKindRules
) where
import Data.Foldable (traverse_)
import Control.Lens (review, preview)
import Control.Monad.Except (MonadError)
import Data.Functor.Classes (Eq1)
import Ast.Kind
import Ast.Type
import Ast.Error.Common
import Rules.Kind.Infer.SyntaxDirected
import Fragment.KiBase.Ast.Kind
import Fragment.Record.Ast.Type
inferTyRecord :: (MonadError e m, AsUnexpectedKind e ki, Eq1 ki, AsKiBase ki, AsTyRecord ki ty)
=> (Type ki ty a -> m (Kind ki))
-> Type ki ty a
-> Maybe (m (Kind ki))
inferTyRecord inferFn ty = do
tys <- preview _TyRecord ty
return $ do
let ki = review _KiBase()
traverse_ (\(_, tyR) -> mkCheckKind inferFn tyR ki) tys
return . review _KiBase $ ()
type RecordInferKindContext e w s r m ki ty a = (MonadError e m, AsUnexpectedKind e ki, Eq1 ki, AsKiBase ki, AsTyRecord ki ty)
recordInferKindRules :: RecordInferKindContext e w s r m ki ty a
=> InferKindInput e w s r m ki ty a
recordInferKindRules =
InferKindInput
[InferKindRecurse inferTyRecord]
| dalaing/type-systems | src/Fragment/Record/Rules/Kind/Infer/SyntaxDirected.hs | bsd-3-clause | 1,344 | 0 | 14 | 277 | 396 | 216 | 180 | 30 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell #-}
module Kerchief
( Kerchief
, getDeck
, getDecksDir
, getKerchiefDir
, getSoundbytesDir
, isDeckLoaded
, isModified
, loadDeck
, readSoundbyte
, runKerchief
, saveDeck
, saveSoundbyte
, setDeck
) where
import Control.Applicative
import Control.Lens
import Control.Monad.Reader
import Control.Monad.State (MonadState)
import Control.Monad.Trans (MonadIO)
import Control.Monad.Trans.State
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Maybe (isJust)
import Data.Serialize (encode, decode)
import System.Directory (getHomeDirectory)
import System.FilePath ((</>))
import System.IO
import Deck
import Kerchief.Prelude (io)
import Utils (catchNothing, eitherToMaybe, safeReadFile, whenJust)
data KerchiefConfig = KConfig
{ kcDir :: FilePath
}
data KerchiefState = KState
{ _ksDeck :: Maybe Deck
, _ksModified :: Bool -- Keep track of in-memory changes to current deck.
}
makeLenses ''KerchiefState
newtype Kerchief a =
Kerchief { unKerchief :: ReaderT KerchiefConfig (StateT KerchiefState IO) a }
deriving (Functor, Applicative, Monad, MonadIO, MonadState KerchiefState, MonadReader KerchiefConfig)
runKerchief :: Kerchief a -> IO a
runKerchief (Kerchief r) = do
config <- initKerchiefConfig
evalStateT (runReaderT r config) initKerchiefState
initKerchiefState :: KerchiefState
initKerchiefState = KState Nothing False
initKerchiefConfig :: IO KerchiefConfig
initKerchiefConfig = KConfig . (</> ".kerchief") <$> getHomeDirectory
isDeckLoaded :: Kerchief Bool
isDeckLoaded = isJust <$> getDeck
getKerchiefDir :: Kerchief FilePath
getKerchiefDir = asks kcDir
getDecksDir :: Kerchief FilePath
getDecksDir = (</> "decks") <$> getKerchiefDir
getSoundbytesDir :: Kerchief FilePath
getSoundbytesDir = (</> "soundbytes") <$> getKerchiefDir
-- | Get the current deck.
getDeck :: Kerchief (Maybe Deck)
getDeck = use ksDeck
isModified :: Kerchief Bool
isModified = use ksModified
-- | Overwrite the current deck without saving it.
setDeck :: Deck -> Kerchief ()
setDeck deck = do
ksDeck .= Just deck
ksModified .= True
-- | Load the given deck, given its name. Return the deck if the load
-- was successful (i.e. does the deck exist?).
loadDeck :: String -> Kerchief (Maybe Deck)
loadDeck name = getDeck >>= \mdeck -> case mdeck of
Nothing -> loadDeck'
Just deck
| name == deck^.deckName -> return (Just deck)
| otherwise -> loadDeck'
where
loadDeck' :: Kerchief (Maybe Deck)
loadDeck' = readDeck name >>=
maybe (return Nothing) (\d -> do
ksDeck .= Just d
ksModified .= False
return (Just d))
-- | Read a deck from file, by deck name. Also update it after reading, since
-- this function is the single function with which decks are read from file.
readDeck :: String -> Kerchief (Maybe Deck)
readDeck name = getDecksDir
>>= io . catchNothing . fmap (eitherToMaybe . decode) . BS.readFile . (</> name)
>>= maybe (return Nothing) (fmap Just . io . updateDeck)
-- | Save the current deck to file, creating the file first if it doesn't exist.
-- If there is no current deck, do nothing.
saveDeck :: Kerchief ()
saveDeck = getDeck >>= whenJust saveDeck'
where
saveDeck' :: Deck -> Kerchief ()
saveDeck' deck = do
path <- (</> deck^.deckName) <$> getDecksDir
io $ withBinaryFile path WriteMode (`BS.hPut` encode deck)
ksModified .= False
-- | Save a soundbyte to disk, given its url and contents (mp3 binary).
saveSoundbyte :: String -> ByteString -> Kerchief ()
saveSoundbyte url bytes = getSoundbytePath url >>= io . flip BS.writeFile bytes
-- | Read a soundbyte from disk, given its url.
readSoundbyte :: String -> Kerchief (Maybe ByteString)
readSoundbyte url = getSoundbytePath url >>= io . safeReadFile
-- | Given a url, get its soundbyte path (replace '/' with '-')
getSoundbytePath :: String -> Kerchief FilePath
getSoundbytePath = getSoundbytePath' . map (\c -> if c == '/' then '-' else c)
where
getSoundbytePath' :: String -> Kerchief FilePath
getSoundbytePath' url = (</> url) <$> getSoundbytesDir
| mitchellwrosen/kerchief | src/Kerchief.hs | bsd-3-clause | 4,522 | 0 | 15 | 1,120 | 1,059 | 569 | 490 | 95 | 2 |
module Storage (
module Storage
, module Exports
) where
import Din
import Storage.Db as Exports
import Storage.Schema (dinSchema)
import Control.Monad (when)
import Database.SQL (SQLTable,tabName)
import Database.SQLite (defineTable)
-- Initialization --------------------------------------------------------------
-- | Create tables in the database, if it's freshly created.
initDb :: Din ()
initDb = do
isFresh <- freshDb
logDebug ("Fresh database: " ++ show isFresh)
when isFresh (mapM_ createTable dinSchema)
-- | Given a specification, create a table in the database.
createTable :: SQLTable -> Din ()
createTable def = do
logInfo ("Creating table " ++ tabName def)
h <- dbHandle
mb <- io (defineTable h def)
case mb of
Just _ -> return ()
Nothing -> logError ("Failed when creating table: " ++ tabName def)
| elliottt/din | src/Storage.hs | bsd-3-clause | 853 | 0 | 13 | 159 | 227 | 118 | 109 | 22 | 2 |
module Slack
( slack
, slackA
, runRtmBot
, debug
, Channel
) where
import Control.Lens ((.~), (&), (^?), (^.))
import Control.Monad (forever, unless)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Reader (ask)
import Data.Aeson (eitherDecode, encode)
import Data.Aeson.Lens (Primitive(..), _Primitive, _String, key)
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as BC
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import qualified Network.Socket as S
import qualified Network.URI as URI
import qualified Network.WebSockets as WS
import qualified Network.WebSockets.Stream as WS
import Network.Wreq (FormParam, get, postWith, defaults, param, responseBody)
import qualified OpenSSL as SSL
import qualified OpenSSL.Session as SSL
import qualified System.IO.Streams.Internal as StreamsIO
import System.IO.Streams.SSL (sslToStreams)
import Types
import Util
type Channel = T.Text
slack :: Channel -> T.Text -> Z ()
slack channel text = slackA channel text []
slackA :: Channel -> T.Text -> [(T.Text, T.Text)] -> Z ()
slackA channel text attached = do
conf <- ask
let opts = defaults
& param "token" .~ [apiToken conf]
& param "channel" .~ [channel]
& param "text" .~ [text]
& param "username" .~ [botName conf]
& param "as_user" .~ ["false" :: T.Text]
& param "icon_emoji" .~ [":star2:" :: T.Text]
& param "attachments" .~ [formatAttachments attached]
let body = [] :: [FormParam]
_ <- liftIO $ postWith opts "http://slack.com/api/chat.postMessage" body
-- TODO: check response, handle non-200s
return ()
formatAttachments :: [(T.Text, T.Text)] -> T.Text
formatAttachments pairs =
decodeUtf8 . BC.toStrict . encode $ map mkAttachment pairs
where
mkAttachment (k,v) = Attachment
{ atId = -1
, atFallback = ""
, atFields =
[ AttachmentField
{ afTitle = k
, afValue = v
, afShort = False
}
]
}
runRtmBot :: (Z () -> IO ()) -> T.Text -> (Event -> Z ()) -> IO ()
runRtmBot runIO token directives = do
(host, path) <- getSlackWebsocket token
SSL.withOpenSSL $ do
stream <- getStreamForWebsocket host
WS.runClientWithStream stream host path WS.defaultConnectionOptions [] wsApp
where
wsApp ws = do
WS.forkPingThread ws 10
runIO . forever $ handleEvents directives ws
parseWebsocket :: T.Text -> (S.HostName, String)
parseWebsocket url =
let
parsed = do
uri <- URI.parseURI $ T.unpack url
name <- URI.uriRegName <$> URI.uriAuthority uri
return (name, URI.uriPath uri)
in case parsed of
Just (name, path) -> (name, path)
_ -> error $ "Couldn't parse Slack websocket URL from " ++ T.unpack url
getSlackWebsocket :: T.Text -> IO (S.HostName, String)
getSlackWebsocket token = do
r <- get $ "https://slack.com/api/rtm.start?token=" ++ (T.unpack token)
let Just (BoolPrim ok) = r ^? responseBody . key "ok" . _Primitive
unless ok $ do
putStrLn "Unable to connect"
ioError . userError . T.unpack $ r ^. responseBody . key "error" . _String
let Just url = r ^? responseBody . key "url" . _String
return $ parseWebsocket url
getStreamForWebsocket :: S.HostName -> IO WS.Stream
getStreamForWebsocket host = do
ctx <- SSL.context
is <- S.getAddrInfo Nothing (Just host) (Just "443")
let a = S.addrAddress $ head is
f = S.addrFamily $ head is
s <- S.socket f S.Stream S.defaultProtocol
S.connect s a
ssl <- SSL.connection ctx s
SSL.connect ssl
(i,o) <- sslToStreams ssl
WS.makeStream (StreamsIO.read i) (\b -> StreamsIO.write (B.toStrict <$> b) o )
handleEvents :: (Event -> Z ()) -> WS.Connection -> Z ()
handleEvents directives ws = do
raw <- liftIO $ WS.receiveData ws
case eitherDecode raw of
Left e -> liftIO $ do
putStrLn $ "Failed to parse event: " ++ e
BC.putStrLn $ pprint raw
putStrLn ""
Right event -> directives event
debug :: T.Text -> Z ()
debug = slack "#_robots"
| jamesdabbs/zorya | src/Slack.hs | bsd-3-clause | 4,420 | 0 | 24 | 1,258 | 1,459 | 764 | 695 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module DatabaseApi (getSumFromDb) where
import Database.PostgreSQL.Simple
getSumFromDb :: Connection -> IO Int
getSumFromDb connection = do
xs <- query_ connection "select 2 + 2"
return $ (fromOnly $ head xs :: Int)
| jorgen/scotty-postgres | src/DatabaseApi.hs | bsd-3-clause | 261 | 0 | 10 | 46 | 68 | 36 | 32 | 7 | 1 |
module Monadic where
import Language.Haskell.Liquid.Prelude ((==>))
class MyMonad m where
unit :: Arrow a (m a)
bind :: Arrow (m a) (Arrow (Arrow a (m b)) (m b))
instance MyMonad L where
unit = lunit
bind = lbind
lunit = A $ \x -> C x N -- axiom: runFun unit x == C x N
lbind = A $ \xs -> A $ \f ->
case xs of
N -> N -- axiom: runFun (runFun bind N) f == N
(C x xs) -> -- axiom: runFun (runFun bind (C x xs)) f
-- == runFun f x `append` runFun (runFun bind xs) f
runFun f x `append` runFun (runFun lbind xs) f
-- bind N f = N
-- bind (C x xs) f = f x `append` bind xs f
data Arrow a b = A {runFun :: a -> b}
{-@ data Arrow a b <p :: a -> b -> Prop> = A {runFun :: x:a -> b<p x>} @-}
-- | Express Left Identity
{-@ measure runFun :: (Arrow a b) -> a -> b @-}
-- use abstract refinements to do this:
-- unit and bind should have the appropriate properties to prove left Identity.
prop_left_identity_List :: a -> Arrow a (L b) -> Proof
prop_left_identity_List = prop_left_identity lunit lbind
{-@ type ProofLeftIdentity Unit Bind F X = {v:Proof | runFun (runFun Bind (runFun Unit X)) F == runFun F X } @-}
{-@ prop_left_identity :: forall <p :: a -> m a -> Prop,
q :: m a -> Arrow (Arrow a (m b)) (m b) -> Prop>.
{unit::Arrow<p> a (m a),bind :: Arrow<q> (m a) (Arrow (Arrow a (m b)) (m b)), x :: a, f :: Arrow a (m b) |- Proof <: ProofLeftIdentity unit bind f x}
unit: Arrow<p> a (m a) -> bind: Arrow<q> (m a) (Arrow (Arrow a (m b)) (m b))
-> x:a -> f:Arrow a (m b)
-> ProofLeftIdentity unit bind f x
@-}
prop_left_identity :: (Arrow a (m a)) -> (Arrow (m a) (Arrow (Arrow a (m b)) (m b)))
-> a -> (Arrow a (m b))
-> Proof
prop_left_identity iunit ibind x f = Proof
-- | Express Left Identity in Haskell
prop_left_identity_HS :: (Eq (m a), Eq (m b)) => (Arrow a (m a)) -> (Arrow (m a) (Arrow (Arrow a (m b)) (m b)))
-> a -> (Arrow a (m b))
-> Bool
prop_left_identity_HS unit bind x f
= runFun (runFun bind (runFun unit x)) f == runFun f x
-- | Proof library:
data Proof = Proof
{-@ toProof :: l:a -> r:{a|l = r} -> {v:Proof | l = r } @-}
toProof :: a -> a -> Proof
toProof x y = Proof
{-@ (===) :: l:a -> r:a -> {v:Proof | l = r} -> {v:a | v = l } @-}
(===) :: a -> a -> Proof -> a
(===) x y _ = y
-- | Proof: map
{-@ type Equal X Y = {v:Proof | X == Y} @-}
{- invariant {v:Proof | v == Proof } @-}
{-@ bound chain @-}
chain :: (Proof -> Bool) -> (Proof -> Bool) -> (Proof -> Bool) -> Proof -> Bool
chain p q r v = p v ==> q v ==> r v
{-@ assume by :: forall <p :: Proof -> Prop, q :: Proof -> Prop, r :: Proof -> Prop>.
(Chain p q r) => Proof<p> -> Proof<q> -> Proof<r>
@-}
by :: Proof -> Proof -> Proof
by p r = r
{-@ refl :: x:a -> Equal x x @-}
refl :: a -> Proof
refl x = Proof
-- | End library
-- | Append
data L a = N | C a (L a) deriving (Eq)
{-@ N :: {v:L a | llen v == 0 && v == N } @-}
{-@ C :: x:a -> xs:L a -> {v:L a | llen v == llen xs + 1 && v == C x xs } @-}
{-@ data L [llen] @-}
{-@ invariant {v: L a | llen v >= 0} @-}
{-@ measure llen :: L a -> Int @-}
llen :: L a -> Int
llen N = 0
llen (C x xs) = 1 + llen xs
append :: L a -> L a -> L a
append N xs = xs
append (C y ys) xs = C y (append ys xs)
-- | All the followin will be autocatically generated by the definition of append
-- | and a liquid annotation
-- |
-- | axiomatize append
-- |
{-@ measure append :: L a -> L a -> L a @-}
{-@ assume append :: xs:L a -> ys:L a -> {v:L a | v == append xs ys } @-}
{-@ assume axiom_append_nil :: xs:L a -> {v:Proof | append N xs == xs} @-}
axiom_append_nil :: L a -> Proof
axiom_append_nil xs = Proof
{-@ assume axiom_append_cons :: x:a -> xs: L a -> ys: L a
-> {v:Proof | append (C x xs) ys == C x (append xs ys) } @-}
axiom_append_cons :: a -> L a -> L a -> Proof
axiom_append_cons x xs ys = Proof
-- | End append
| abakst/liquidhaskell | tests/equationalproofs/todo/MonadicLaws.hs | bsd-3-clause | 4,140 | 0 | 15 | 1,292 | 922 | 495 | 427 | 48 | 2 |
module Network.Protocol.Uri.Printer where
import Network.Protocol.Uri.Data
instance Show Path where
showsPrec _ (Path ("":xs)) = sc '/' . shows (Path xs)
showsPrec _ (Path xs) = intersperseS (sc '/') (map ss xs)
instance Show IPv4 where
showsPrec _ (IPv4 a b c d) = intersperseS (sc '.') (map shows [a, b, c, d])
instance Show Domain where
showsPrec _ (Domain d) = intersperseS (sc '.') (map ss d)
instance Show Host where
showsPrec _ (Hostname d) = shows d
showsPrec _ (IP i) = shows i
showsPrec _ (RegName r) = ss r
instance Show Authority where
showsPrec _ (Authority u h p) =
let u' = if null u then id else ss u . ss "@"
p' = maybe id (\s -> sc ':' . shows s) p
in u' . shows h . p'
instance Show Uri where
showsPrec _ (Uri _ s a p q f) =
let s' = if null s then id else ss s . sc ':'
a' = show a
p' = shows p
q' = if null q then id else sc '?' . ss q
f' = if null f then id else sc '#' . ss f
t' = if null a' then id else ss "//"
in s' . t' . ss a' . p' . q' . f'
ss :: String -> ShowS
ss = showString
sc :: Char -> ShowS
sc = showChar
-- | ShowS version of intersperse.
intersperseS :: ShowS -> [ShowS] -> ShowS
intersperseS _ [] = id
intersperseS s (x:xs) = foldl (\a b -> a.s.b) x xs
| sebastiaanvisser/salvia-protocol | src/Network/Protocol/Uri/Printer.hs | bsd-3-clause | 1,304 | 0 | 14 | 377 | 638 | 323 | 315 | 34 | 1 |
{-# LANGUAGE TypeOperators, FlexibleContexts #-}
-- | An instance of the 'MonadIO' class for a zipper:
--
-- @
-- instance ('MonadIO' (t2 m), 'MonadT' t1, 'MonadT' t2, 'Monad' m) => 'MonadIO' ((t1 ':>' t2) m)
-- @
--
-- Re-exports "Control.Monad.IO.Class" for convenience.
module Control.Monatron.Zipper.IO (module Control.Monad.IO.Class) where
import Control.Monatron.Monatron (MonadT(..), Monad)
import Control.Monatron.Zipper ((:>), zipper)
import Control.Monad.IO.Class
instance (MonadIO (t2 m), MonadT t1, MonadT t2, Monad m) => MonadIO ((t1 :> t2) m) where
liftIO = zipper . lift . liftIO
| TobBrandt/Monatron-IO | Control/Monatron/Zipper/IO.hs | bsd-3-clause | 610 | 0 | 9 | 98 | 134 | 84 | 50 | 7 | 0 |
--------------------------------------------------------------------------------
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Rank2Types #-}
module DB
( DB (..)
, initDB
, extendID
, sql
)
where
import Control.Monad (void)
import Data.String (fromString)
import Data.Text (Text)
import Database.PostgreSQL.Simple.SqlQQ (sql)
import qualified Data.Text as T
import qualified Database.PostgreSQL.Simple as P
import qualified Database.PostgreSQL.Simple.Types as P
--------------------------------------------------------------------------------
data DB = DB
{ execute :: (P.ToRow q) => q -> P.Query -> IO ()
, execute_ :: P.Query -> IO ()
, query :: (P.ToRow q, P.FromRow r) => q -> P.Query -> IO [r]
, query_ :: (P.FromRow r) => P.Query -> IO [r]
, query1 :: (P.ToRow q, P.FromRow r) => q -> P.Query -> IO (Maybe r)
, query1_ :: (P.FromRow r) => P.Query -> IO (Maybe r)
, withTransaction :: forall a . IO a -> IO a
}
data DBState = DBState
{ db' :: P.Connection
}
--------------------------------------------------------------------------------
initDB :: String -> IO DB
initDB dburl = do
db <- P.connectPostgreSQL (fromString dburl)
let
st = DBState
{ db' = db
}
return $ DB
{ execute = execute' st
, execute_ = execute_' st
, query = query' st
, query_ = query_' st
, query1 = query1' st
, query1_ = query1_' st
, withTransaction = withTransaction' st
}
extendID :: P.Identifier -> Text -> P.Identifier
extendID base ext =
P.Identifier (T.append (P.fromIdentifier base) ext)
--------------------------------------------------------------------------------
execute' :: (P.ToRow q) => DBState -> q -> P.Query -> IO ()
execute' st qargs q =
void (P.execute (db' st) q qargs)
execute_' :: DBState -> P.Query -> IO ()
execute_' st q =
void (P.execute_ (db' st) q)
query' :: (P.ToRow q, P.FromRow r) => DBState -> q -> P.Query -> IO [r]
query' st qargs q =
P.query (db' st) q qargs
query_' :: (P.FromRow r) => DBState -> P.Query -> IO [r]
query_' st q =
P.query_ (db' st) q
query1' :: (P.ToRow q, P.FromRow r) => DBState -> q -> P.Query -> IO (Maybe r)
query1' st qargs q =
P.query (db' st) q qargs >>= \case
[] -> return Nothing
[r] -> return (Just r)
_ -> error ("dbQuery1: query " ++ show q ++ " returned more than 1 row")
query1_' :: (P.FromRow r) => DBState -> P.Query -> IO (Maybe r)
query1_' st q =
P.query_ (db' st) q >>= \case
[] -> return Nothing
[r] -> return (Just r)
_ -> error ("dbQuery1_: query " ++ show q ++ " returned more than 1 row")
withTransaction' :: DBState -> IO a -> IO a
withTransaction' st act =
P.withTransaction (db' st) act
--------------------------------------------------------------------------------
| mietek/untitled-wai | src/DB.hs | bsd-3-clause | 2,965 | 0 | 14 | 767 | 1,050 | 554 | 496 | 68 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Config where
import qualified Data.ByteString as BS
import Control.Applicative
import Data.Map
import Data.Yaml
import Types
--------------------------------------------------------------------------------
instance FromJSON Colour where
parseJSON (Object v) = Colour <$>
v .: "r" <*>
v .: "g" <*>
v .: "b"
instance FromJSON Config where
parseJSON (Object v) = Config <$>
v .: "borderColour" <*>
v .: "wraparound" <*>
v .: "nations" <*>
(mapKeys read <$> v .: "provinces")
loadConfig :: FilePath -> IO Config
loadConfig path = do
yaml <- BS.readFile path
case decodeEither yaml of
Left err -> error $ "Failed to load config file: " ++ err
Right config -> return config
| Ornedan/dom3conquestmaptool | Config.hs | bsd-3-clause | 935 | 0 | 12 | 331 | 213 | 109 | 104 | 24 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.HTools.Instance
( testHTools_Instance
, genInstanceSmallerThanNode
, genInstanceMaybeBiggerThanNode
, genInstanceSmallerThan
, genInstanceOnNodeList
, genInstanceList
, Instance.Instance(..)
) where
import Test.QuickCheck hiding (Result)
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Test.Ganeti.HTools.Types ()
import Ganeti.BasicTypes
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Loader as Loader
import qualified Ganeti.HTools.Types as Types
-- * Arbitrary instances
-- | Generates a random instance with maximum disk/mem/cpu values.
genInstanceSmallerThan :: Int -> Int -> Int -> Gen Instance.Instance
genInstanceSmallerThan lim_mem lim_dsk lim_cpu = do
name <- genFQDN
mem <- choose (0, lim_mem)
dsk <- choose (0, lim_dsk)
run_st <- arbitrary
pn <- arbitrary
sn <- arbitrary
vcpus <- choose (0, lim_cpu)
dt <- arbitrary
return $ Instance.create name mem dsk [dsk] vcpus run_st [] True pn sn dt 1
-- | Generates an instance smaller than a node.
genInstanceSmallerThanNode :: Node.Node -> Gen Instance.Instance
genInstanceSmallerThanNode node =
genInstanceSmallerThan (Node.availMem node `div` 2)
(Node.availDisk node `div` 2)
(Node.availCpu node `div` 2)
-- | Generates an instance possibly bigger than a node.
genInstanceMaybeBiggerThanNode :: Node.Node -> Gen Instance.Instance
genInstanceMaybeBiggerThanNode node =
genInstanceSmallerThan (Node.availMem node + Types.unitMem * 2)
(Node.availDisk node + Types.unitDsk * 3)
(Node.availCpu node + Types.unitCpu * 4)
-- | Generates an instance with nodes on a node list.
-- The following rules are respected:
-- 1. The instance is never bigger than its primary node
-- 2. If possible the instance has different pnode and snode
-- 3. Else disk templates which require secondary nodes are disabled
genInstanceOnNodeList :: Node.List -> Gen Instance.Instance
genInstanceOnNodeList nl = do
let nsize = Container.size nl
pnode <- choose (0, nsize-1)
let (snodefilter, dtfilter) =
if nsize >= 2
then ((/= pnode), const True)
else (const True, not . Instance.hasSecondary)
snode <- choose (0, nsize-1) `suchThat` snodefilter
i <- genInstanceSmallerThanNode (Container.find pnode nl) `suchThat` dtfilter
return $ i { Instance.pNode = pnode, Instance.sNode = snode }
-- | Generates an instance list given an instance generator.
genInstanceList :: Gen Instance.Instance -> Gen Instance.List
genInstanceList igen = fmap (snd . Loader.assignIndices) names_instances
where names_instances =
(fmap . map) (\n -> (Instance.name n, n)) $ listOf igen
-- let's generate a random instance
instance Arbitrary Instance.Instance where
arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu
-- * Test cases
-- Simple instance tests, we only have setter/getters
prop_creat :: Instance.Instance -> Property
prop_creat inst =
Instance.name inst ==? Instance.alias inst
prop_setIdx :: Instance.Instance -> Types.Idx -> Property
prop_setIdx inst idx =
Instance.idx (Instance.setIdx inst idx) ==? idx
prop_setName :: Instance.Instance -> String -> Bool
prop_setName inst name =
Instance.name newinst == name &&
Instance.alias newinst == name
where newinst = Instance.setName inst name
prop_setAlias :: Instance.Instance -> String -> Bool
prop_setAlias inst name =
Instance.name newinst == Instance.name inst &&
Instance.alias newinst == name
where newinst = Instance.setAlias inst name
prop_setPri :: Instance.Instance -> Types.Ndx -> Property
prop_setPri inst pdx =
Instance.pNode (Instance.setPri inst pdx) ==? pdx
prop_setSec :: Instance.Instance -> Types.Ndx -> Property
prop_setSec inst sdx =
Instance.sNode (Instance.setSec inst sdx) ==? sdx
prop_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool
prop_setBoth inst pdx sdx =
Instance.pNode si == pdx && Instance.sNode si == sdx
where si = Instance.setBoth inst pdx sdx
prop_shrinkMG :: Instance.Instance -> Property
prop_shrinkMG inst =
Instance.mem inst >= 2 * Types.unitMem ==>
case Instance.shrinkByType inst Types.FailMem of
Ok inst' -> Instance.mem inst' ==? Instance.mem inst - Types.unitMem
Bad msg -> failTest msg
prop_shrinkMF :: Instance.Instance -> Property
prop_shrinkMF inst =
forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem ->
let inst' = inst { Instance.mem = mem}
in isBad $ Instance.shrinkByType inst' Types.FailMem
prop_shrinkCG :: Instance.Instance -> Property
prop_shrinkCG inst =
Instance.vcpus inst >= 2 * Types.unitCpu ==>
case Instance.shrinkByType inst Types.FailCPU of
Ok inst' -> Instance.vcpus inst' ==? Instance.vcpus inst - Types.unitCpu
Bad msg -> failTest msg
prop_shrinkCF :: Instance.Instance -> Property
prop_shrinkCF inst =
forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus ->
let inst' = inst { Instance.vcpus = vcpus }
in isBad $ Instance.shrinkByType inst' Types.FailCPU
prop_shrinkDG :: Instance.Instance -> Property
prop_shrinkDG inst =
Instance.dsk inst >= 2 * Types.unitDsk ==>
case Instance.shrinkByType inst Types.FailDisk of
Ok inst' -> Instance.dsk inst' ==? Instance.dsk inst - Types.unitDsk
Bad msg -> failTest msg
prop_shrinkDF :: Instance.Instance -> Property
prop_shrinkDF inst =
forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk ->
let inst' = inst { Instance.dsk = dsk, Instance.disks = [dsk] }
in isBad $ Instance.shrinkByType inst' Types.FailDisk
prop_setMovable :: Instance.Instance -> Bool -> Property
prop_setMovable inst m =
Instance.movable inst' ==? m
where inst' = Instance.setMovable inst m
testSuite "HTools/Instance"
[ 'prop_creat
, 'prop_setIdx
, 'prop_setName
, 'prop_setAlias
, 'prop_setPri
, 'prop_setSec
, 'prop_setBoth
, 'prop_shrinkMG
, 'prop_shrinkMF
, 'prop_shrinkCG
, 'prop_shrinkCF
, 'prop_shrinkDG
, 'prop_shrinkDF
, 'prop_setMovable
]
| sarahn/ganeti | test/hs/Test/Ganeti/HTools/Instance.hs | gpl-2.0 | 7,162 | 0 | 13 | 1,461 | 1,779 | 935 | 844 | 136 | 2 |
module LayoutOk13 where
x = id (case x of { 3 -> 4 }) | roberth/uu-helium | test/parser/LayoutOk13.hs | gpl-3.0 | 61 | 0 | 9 | 21 | 27 | 16 | 11 | 2 | 1 |
module Isotope.IonSpec (spec) where
import Isotope
import Isotope.Ion
import Test.Hspec
spec :: Spec
spec = do
describe "mz" $ do
it "The mass-to-charge ratio of protonated water should be 19.01838971626" $
mz (Protonated water) `shouldBe` Mz {getMz = 19.01838971626}
it "The mass-to-charge ratio of deprotonated water should be 17.0027396518" $
mz (Deprotonated water) `shouldBe` Mz {getMz = 17.0027396518}
describe "polarity" $ do
it "The polarity of protonated water should be Positive" $
polarity (Protonated water) `shouldBe` Positive
it "The polarity of deprotonated water should be Negative" $
polarity (Deprotonated water) `shouldBe` Negative
water :: MolecularFormula
water = mkMolecularFormula [(H, 2), (O, 1)]
| Michaelt293/Element-isotopes | test/Isotope/IonSpec.hs | gpl-3.0 | 769 | 0 | 14 | 150 | 201 | 106 | 95 | 18 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.OpsWorks.StartStack
-- 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)
--
-- Starts a stack\'s instances.
--
-- __Required Permissions__: To use this action, an IAM user must have a
-- Manage permissions level for the stack, or an attached policy that
-- explicitly grants permissions. For more information on user permissions,
-- see
-- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>.
--
-- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_StartStack.html AWS API Reference> for StartStack.
module Network.AWS.OpsWorks.StartStack
(
-- * Creating a Request
startStack
, StartStack
-- * Request Lenses
, staStackId
-- * Destructuring the Response
, startStackResponse
, StartStackResponse
) where
import Network.AWS.OpsWorks.Types
import Network.AWS.OpsWorks.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'startStack' smart constructor.
newtype StartStack = StartStack'
{ _staStackId :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartStack' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'staStackId'
startStack
:: Text -- ^ 'staStackId'
-> StartStack
startStack pStackId_ =
StartStack'
{ _staStackId = pStackId_
}
-- | The stack ID.
staStackId :: Lens' StartStack Text
staStackId = lens _staStackId (\ s a -> s{_staStackId = a});
instance AWSRequest StartStack where
type Rs StartStack = StartStackResponse
request = postJSON opsWorks
response = receiveNull StartStackResponse'
instance ToHeaders StartStack where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("OpsWorks_20130218.StartStack" :: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON StartStack where
toJSON StartStack'{..}
= object
(catMaybes [Just ("StackId" .= _staStackId)])
instance ToPath StartStack where
toPath = const "/"
instance ToQuery StartStack where
toQuery = const mempty
-- | /See:/ 'startStackResponse' smart constructor.
data StartStackResponse =
StartStackResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartStackResponse' with the minimum fields required to make a request.
--
startStackResponse
:: StartStackResponse
startStackResponse = StartStackResponse'
| olorin/amazonka | amazonka-opsworks/gen/Network/AWS/OpsWorks/StartStack.hs | mpl-2.0 | 3,304 | 0 | 12 | 720 | 403 | 245 | 158 | 57 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.DirectConnect.AllocateConnectionOnInterconnect
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Creates a hosted connection on an interconnect.
--
-- Allocates a VLAN number and a specified amount of bandwidth for use by a
-- hosted connection on the given interconnect.
--
-- <http://docs.aws.amazon.com/directconnect/latest/APIReference/API_AllocateConnectionOnInterconnect.html>
module Network.AWS.DirectConnect.AllocateConnectionOnInterconnect
(
-- * Request
AllocateConnectionOnInterconnect
-- ** Request constructor
, allocateConnectionOnInterconnect
-- ** Request lenses
, acoiBandwidth
, acoiConnectionName
, acoiInterconnectId
, acoiOwnerAccount
, acoiVlan
-- * Response
, AllocateConnectionOnInterconnectResponse
-- ** Response constructor
, allocateConnectionOnInterconnectResponse
-- ** Response lenses
, acoirBandwidth
, acoirConnectionId
, acoirConnectionName
, acoirConnectionState
, acoirLocation
, acoirOwnerAccount
, acoirPartnerName
, acoirRegion
, acoirVlan
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.DirectConnect.Types
import qualified GHC.Exts
data AllocateConnectionOnInterconnect = AllocateConnectionOnInterconnect
{ _acoiBandwidth :: Text
, _acoiConnectionName :: Text
, _acoiInterconnectId :: Text
, _acoiOwnerAccount :: Text
, _acoiVlan :: Int
} deriving (Eq, Ord, Read, Show)
-- | 'AllocateConnectionOnInterconnect' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'acoiBandwidth' @::@ 'Text'
--
-- * 'acoiConnectionName' @::@ 'Text'
--
-- * 'acoiInterconnectId' @::@ 'Text'
--
-- * 'acoiOwnerAccount' @::@ 'Text'
--
-- * 'acoiVlan' @::@ 'Int'
--
allocateConnectionOnInterconnect :: Text -- ^ 'acoiBandwidth'
-> Text -- ^ 'acoiConnectionName'
-> Text -- ^ 'acoiOwnerAccount'
-> Text -- ^ 'acoiInterconnectId'
-> Int -- ^ 'acoiVlan'
-> AllocateConnectionOnInterconnect
allocateConnectionOnInterconnect p1 p2 p3 p4 p5 = AllocateConnectionOnInterconnect
{ _acoiBandwidth = p1
, _acoiConnectionName = p2
, _acoiOwnerAccount = p3
, _acoiInterconnectId = p4
, _acoiVlan = p5
}
-- | Bandwidth of the connection.
--
-- Example: "/500Mbps/"
--
-- Default: None
acoiBandwidth :: Lens' AllocateConnectionOnInterconnect Text
acoiBandwidth = lens _acoiBandwidth (\s a -> s { _acoiBandwidth = a })
-- | Name of the provisioned connection.
--
-- Example: "/500M Connection to AWS/"
--
-- Default: None
acoiConnectionName :: Lens' AllocateConnectionOnInterconnect Text
acoiConnectionName =
lens _acoiConnectionName (\s a -> s { _acoiConnectionName = a })
-- | ID of the interconnect on which the connection will be provisioned.
--
-- Example: dxcon-456abc78
--
-- Default: None
acoiInterconnectId :: Lens' AllocateConnectionOnInterconnect Text
acoiInterconnectId =
lens _acoiInterconnectId (\s a -> s { _acoiInterconnectId = a })
-- | Numeric account Id of the customer for whom the connection will be
-- provisioned.
--
-- Example: 123443215678
--
-- Default: None
acoiOwnerAccount :: Lens' AllocateConnectionOnInterconnect Text
acoiOwnerAccount = lens _acoiOwnerAccount (\s a -> s { _acoiOwnerAccount = a })
-- | The dedicated VLAN provisioned to the connection.
--
-- Example: 101
--
-- Default: None
acoiVlan :: Lens' AllocateConnectionOnInterconnect Int
acoiVlan = lens _acoiVlan (\s a -> s { _acoiVlan = a })
data AllocateConnectionOnInterconnectResponse = AllocateConnectionOnInterconnectResponse
{ _acoirBandwidth :: Maybe Text
, _acoirConnectionId :: Maybe Text
, _acoirConnectionName :: Maybe Text
, _acoirConnectionState :: Maybe ConnectionState
, _acoirLocation :: Maybe Text
, _acoirOwnerAccount :: Maybe Text
, _acoirPartnerName :: Maybe Text
, _acoirRegion :: Maybe Text
, _acoirVlan :: Maybe Int
} deriving (Eq, Read, Show)
-- | 'AllocateConnectionOnInterconnectResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'acoirBandwidth' @::@ 'Maybe' 'Text'
--
-- * 'acoirConnectionId' @::@ 'Maybe' 'Text'
--
-- * 'acoirConnectionName' @::@ 'Maybe' 'Text'
--
-- * 'acoirConnectionState' @::@ 'Maybe' 'ConnectionState'
--
-- * 'acoirLocation' @::@ 'Maybe' 'Text'
--
-- * 'acoirOwnerAccount' @::@ 'Maybe' 'Text'
--
-- * 'acoirPartnerName' @::@ 'Maybe' 'Text'
--
-- * 'acoirRegion' @::@ 'Maybe' 'Text'
--
-- * 'acoirVlan' @::@ 'Maybe' 'Int'
--
allocateConnectionOnInterconnectResponse :: AllocateConnectionOnInterconnectResponse
allocateConnectionOnInterconnectResponse = AllocateConnectionOnInterconnectResponse
{ _acoirOwnerAccount = Nothing
, _acoirConnectionId = Nothing
, _acoirConnectionName = Nothing
, _acoirConnectionState = Nothing
, _acoirRegion = Nothing
, _acoirLocation = Nothing
, _acoirBandwidth = Nothing
, _acoirVlan = Nothing
, _acoirPartnerName = Nothing
}
-- | Bandwidth of the connection.
--
-- Example: 1Gbps (for regular connections), or 500Mbps (for hosted connections)
--
-- Default: None
acoirBandwidth :: Lens' AllocateConnectionOnInterconnectResponse (Maybe Text)
acoirBandwidth = lens _acoirBandwidth (\s a -> s { _acoirBandwidth = a })
acoirConnectionId :: Lens' AllocateConnectionOnInterconnectResponse (Maybe Text)
acoirConnectionId =
lens _acoirConnectionId (\s a -> s { _acoirConnectionId = a })
acoirConnectionName :: Lens' AllocateConnectionOnInterconnectResponse (Maybe Text)
acoirConnectionName =
lens _acoirConnectionName (\s a -> s { _acoirConnectionName = a })
acoirConnectionState :: Lens' AllocateConnectionOnInterconnectResponse (Maybe ConnectionState)
acoirConnectionState =
lens _acoirConnectionState (\s a -> s { _acoirConnectionState = a })
acoirLocation :: Lens' AllocateConnectionOnInterconnectResponse (Maybe Text)
acoirLocation = lens _acoirLocation (\s a -> s { _acoirLocation = a })
acoirOwnerAccount :: Lens' AllocateConnectionOnInterconnectResponse (Maybe Text)
acoirOwnerAccount =
lens _acoirOwnerAccount (\s a -> s { _acoirOwnerAccount = a })
acoirPartnerName :: Lens' AllocateConnectionOnInterconnectResponse (Maybe Text)
acoirPartnerName = lens _acoirPartnerName (\s a -> s { _acoirPartnerName = a })
acoirRegion :: Lens' AllocateConnectionOnInterconnectResponse (Maybe Text)
acoirRegion = lens _acoirRegion (\s a -> s { _acoirRegion = a })
acoirVlan :: Lens' AllocateConnectionOnInterconnectResponse (Maybe Int)
acoirVlan = lens _acoirVlan (\s a -> s { _acoirVlan = a })
instance ToPath AllocateConnectionOnInterconnect where
toPath = const "/"
instance ToQuery AllocateConnectionOnInterconnect where
toQuery = const mempty
instance ToHeaders AllocateConnectionOnInterconnect
instance ToJSON AllocateConnectionOnInterconnect where
toJSON AllocateConnectionOnInterconnect{..} = object
[ "bandwidth" .= _acoiBandwidth
, "connectionName" .= _acoiConnectionName
, "ownerAccount" .= _acoiOwnerAccount
, "interconnectId" .= _acoiInterconnectId
, "vlan" .= _acoiVlan
]
instance AWSRequest AllocateConnectionOnInterconnect where
type Sv AllocateConnectionOnInterconnect = DirectConnect
type Rs AllocateConnectionOnInterconnect = AllocateConnectionOnInterconnectResponse
request = post "AllocateConnectionOnInterconnect"
response = jsonResponse
instance FromJSON AllocateConnectionOnInterconnectResponse where
parseJSON = withObject "AllocateConnectionOnInterconnectResponse" $ \o -> AllocateConnectionOnInterconnectResponse
<$> o .:? "bandwidth"
<*> o .:? "connectionId"
<*> o .:? "connectionName"
<*> o .:? "connectionState"
<*> o .:? "location"
<*> o .:? "ownerAccount"
<*> o .:? "partnerName"
<*> o .:? "region"
<*> o .:? "vlan"
| romanb/amazonka | amazonka-directconnect/gen/Network/AWS/DirectConnect/AllocateConnectionOnInterconnect.hs | mpl-2.0 | 9,166 | 0 | 25 | 1,936 | 1,329 | 793 | 536 | 138 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Network.HTTP.Download
( verifiedDownload
, DownloadRequest(..)
, drRetryPolicyDefault
, HashCheck(..)
, DownloadException(..)
, CheckHexDigest(..)
, LengthCheck
, VerifiedDownloadException(..)
, download
, redownload
, downloadJSON
, parseRequest
, parseUrlThrow
, liftHTTP
, ask
, getHttpManager
, MonadReader
, HasHttpManager
) where
import Control.Exception (Exception)
import Control.Exception.Enclosed (handleIO)
import Control.Monad (void)
import Control.Monad.Catch (MonadMask, throwM)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger (MonadLogger, logDebug)
import Control.Monad.Reader (MonadReader, ReaderT, ask,
runReaderT)
import Data.Aeson.Extended (FromJSON, parseJSON)
import Data.Aeson.Parser (json')
import Data.Aeson.Types (parseEither)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Conduit (($$))
import Data.Conduit.Attoparsec (sinkParser)
import Data.Conduit.Binary (sinkHandle, sourceHandle)
import qualified Data.Conduit.Binary as CB
import Data.Foldable (forM_)
import Data.Monoid ((<>))
import Data.Text.Encoding.Error (lenientDecode)
import Data.Text.Encoding (decodeUtf8With)
import Data.Typeable (Typeable)
import Network.HTTP.Client (path, checkResponse)
import Network.HTTP.Client.Conduit (HasHttpManager, Manager, Request,
Response, parseRequest,
getHttpManager, parseUrlThrow,
requestHeaders, responseBody,
responseHeaders, responseStatus,
withResponse)
import Network.HTTP.Download.Verified
import Network.HTTP.Types (status200, status304)
import Path (Abs, File, Path, toFilePath)
import System.Directory (createDirectoryIfMissing,
removeFile,
renameFile)
import System.FilePath (takeDirectory, (<.>))
import System.IO (IOMode (ReadMode),
IOMode (WriteMode),
withBinaryFile)
-- | Download the given URL to the given location. If the file already exists,
-- no download is performed. Otherwise, creates the parent directory, downloads
-- to a temporary file, and on file download completion moves to the
-- appropriate destination.
--
-- Throws an exception if things go wrong
download :: (MonadReader env m, HasHttpManager env, MonadIO m, MonadLogger m)
=> Request
-> Path Abs File -- ^ destination
-> m Bool -- ^ Was a downloaded performed (True) or did the file already exist (False)?
download req destpath = do
let downloadReq = DownloadRequest
{ drRequest = req
, drHashChecks = []
, drLengthCheck = Nothing
, drRetryPolicy = drRetryPolicyDefault
}
let progressHook _ = return ()
verifiedDownload downloadReq destpath progressHook
-- | Same as 'download', but will download a file a second time if it is already present.
--
-- Returns 'True' if the file was downloaded, 'False' otherwise
redownload :: (MonadReader env m, HasHttpManager env, MonadIO m, MonadLogger m)
=> Request
-> Path Abs File -- ^ destination
-> m Bool
redownload req0 dest = do
$logDebug $ "Downloading " <> decodeUtf8With lenientDecode (path req0)
let destFilePath = toFilePath dest
etagFilePath = destFilePath <.> "etag"
metag <- liftIO $ handleIO (const $ return Nothing) $ fmap Just $
withBinaryFile etagFilePath ReadMode $ \h ->
sourceHandle h $$ CB.take 512
let req1 =
case metag of
Nothing -> req0
Just etag -> req0
{ requestHeaders =
requestHeaders req0 ++
[("If-None-Match", L.toStrict etag)]
}
req2 = req1 { checkResponse = \_ _ -> return () }
env <- ask
liftIO $ recoveringHttp drRetryPolicyDefault $ flip runReaderT env $
withResponse req2 $ \res -> case () of
()
| responseStatus res == status200 -> liftIO $ do
createDirectoryIfMissing True $ takeDirectory destFilePath
-- Order here is important: first delete the etag, then write the
-- file, then write the etag. That way, if any step fails, it will
-- force the download to happen again.
handleIO (const $ return ()) $ removeFile etagFilePath
let destFilePathTmp = destFilePath <.> "tmp"
withBinaryFile destFilePathTmp WriteMode $ \h ->
responseBody res $$ sinkHandle h
renameFile destFilePathTmp destFilePath
forM_ (lookup "ETag" (responseHeaders res)) $ \e -> do
let tmp = etagFilePath <.> "tmp"
S.writeFile tmp e
renameFile tmp etagFilePath
return True
| responseStatus res == status304 -> return False
| otherwise -> throwM $ RedownloadFailed req2 dest $ void res
-- | Download a JSON value and parse it using a 'FromJSON' instance.
downloadJSON :: (FromJSON a, MonadReader env m, HasHttpManager env, MonadIO m, MonadMask m)
=> Request
-> m a
downloadJSON req = do
val <- recoveringHttp drRetryPolicyDefault $
liftHTTP $ withResponse req $ \res ->
responseBody res $$ sinkParser json'
case parseEither parseJSON val of
Left e -> throwM $ DownloadJSONException req e
Right x -> return x
data DownloadException
= DownloadJSONException Request String
| RedownloadFailed Request (Path Abs File) (Response ())
deriving (Show, Typeable)
instance Exception DownloadException
-- | A convenience method for asking for the environment and then running an
-- action with its 'Manager'. Useful for avoiding a 'MonadBaseControl'
-- constraint.
liftHTTP :: (MonadIO m, MonadReader env m, HasHttpManager env)
=> ReaderT Manager IO a
-> m a
liftHTTP inner = do
env <- ask
liftIO $ runReaderT inner $ getHttpManager env
| AndrewRademacher/stack | src/Network/HTTP/Download.hs | bsd-3-clause | 7,084 | 0 | 23 | 2,500 | 1,411 | 771 | 640 | 132 | 2 |
module Main where
import MidiSynth
import qualified Codec.SoundFont as SF
import Player.Gtk
import SynthParams
import Numeric
import System.Environment
import System.Console.GetOpt
data Flag =
SampleRate String
| SoundFontFile FilePath
| MidiFile FilePath
| Output FilePath
deriving Show
options :: [OptDescr Flag]
options =
[ Option ['r'] ["samplerate"] (ReqArg SampleRate "SAMPLERATE")
"synthesizer sampling rate"
, Option ['s'] ["soundfont"] (ReqArg SoundFontFile "FILE")
"SoundFont FILE"
]
main :: IO ()
main = do
argv <- getArgs
(sampleRate', soundFontFile) <-
case getOpt Permute options argv of
([SampleRate srs, SoundFontFile sf], _,_) -> do
sr <- case (readDec srs) of
[] -> fail "SAMPLERATE must be a decimal integer number"
(i,_) : _ -> return i
return (sr, sf)
_ -> fail $ usageInfo "all options are mandatory\n" options
putStrLn "Importing SoundFont file ... This may take a while ..."
eSoundFont <- SF.importFile soundFontFile
soundFont <- case eSoundFont of
Left err -> fail err
Right sf -> return sf
putStrLn "Done."
putStrLn "If you are getting interruptions decrase sampling rate."
let paramsGen = soundFontToSynthParams soundFont
Player.Gtk.play sampleRate' 512 2 (midiSynth paramsGen)
putStrLn "Done." | todesking/YampaSynth | src/Main/Gtk.hs | bsd-3-clause | 1,333 | 0 | 18 | 288 | 383 | 195 | 188 | 41 | 4 |
{-
worms - a very simple FunGEn example.
http://www.cin.ufpe.br/~haskell/fungen
Copyright (C) 2001 Andre Furtado <[email protected]>
This code 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.
-}
module Main where
import Text.Printf
import Graphics.UI.Fungen
import Graphics.Rendering.OpenGL (GLdouble)
import Paths_FunGEn (getDataFileName)
data GameAttribute = GA Int Int Int (GLdouble,GLdouble) Int
data ObjectAttribute = NoObjectAttribute | Tail Int
data GameState = LevelStart Int | Level Int | GameOver
data TileAttribute = NoTileAttribute
type WormsAction a = IOGame GameAttribute ObjectAttribute GameState TileAttribute a
type WormsObject = GameObject ObjectAttribute
type WormsTile = Tile TileAttribute
type WormsMap = TileMatrix TileAttribute
tileSize, speedMod :: GLdouble
tileSize = 30.0
speedMod = 30.0
initPos, tail0Pos, tail1Pos :: (GLdouble,GLdouble)
initPos = (45.0,105.0)
tail0Pos = (45.0,75.0)
tail1Pos = (45.0,45.0)
maxFood, initTailSize, defaultTimer :: Int
maxFood = 10
initTailSize = 2
defaultTimer = 10
magenta :: InvList
magenta = Just [(255,0,255)]
bmpList :: FilePictureList
bmpList = [("level1.bmp", Nothing),
("level2.bmp", Nothing),
("level3.bmp", Nothing),
("gameover.bmp", magenta),
("congratulations.bmp", magenta),
("headn.bmp", magenta),
("heads.bmp", magenta),
("heade.bmp", magenta),
("headw.bmp", magenta),
("food.bmp", magenta),
("segment.bmp", magenta),
("border1.bmp", magenta),
("border2.bmp", magenta),
("border3.bmp", magenta),
("free1.bmp", magenta),
("free2.bmp", magenta),
("free3.bmp", magenta)]
-- position of the paths in the list:
border1, border2, border3, free1, free2, free3 :: Int
border1 = 11
border2 = 12
border3 = 13
free1 = 14
free2 = 15
free3 = 16
main :: IO ()
main = do
let winConfig = ((200,100),(780,600),"WORMS - by Andre Furtado")
gameMap = multiMap [(tileMap map1 tileSize tileSize),
(tileMap map2 tileSize tileSize),
(tileMap map3 tileSize tileSize)] 0
gameAttribute = GA defaultTimer maxFood initTailSize initPos 0
groups = [(objectGroup "messages" createMsgs ),
(objectGroup "head" [createHead]),
(objectGroup "food" [createFood]),
(objectGroup "tail" createTail )]
input = [
(SpecialKey KeyLeft, Press, turnLeft ),
(SpecialKey KeyRight, Press, turnRight),
(SpecialKey KeyUp, Press, turnUp ),
(SpecialKey KeyDown, Press, turnDown )
,(Char 'q', Press, \_ _ -> funExit)
]
bmpList' <- mapM (\(a,b) -> do { a' <- getDataFileName ("examples/worms/"++a); return (a', b)}) bmpList
funInit winConfig gameMap groups (LevelStart 1) gameAttribute input gameCycle (Timer 150) bmpList'
createMsgs :: [WormsObject]
createMsgs =
let picLevel1 = Tex (150,50) 0
picLevel2 = Tex (150,50) 1
picLevel3 = Tex (150,50) 2
picGameOver = Tex (300,100) 3
picCongratulations = Tex (300,100) 4
in [(object "level1" picLevel1 True (395,300) (0,0) NoObjectAttribute),
(object "level2" picLevel2 True (395,300) (0,0) NoObjectAttribute),
(object "level3" picLevel3 True (395,300) (0,0) NoObjectAttribute),
(object "gameover" picGameOver True (395,300) (0,0) NoObjectAttribute),
(object "congratulations" picCongratulations True (395,300) (0,0) NoObjectAttribute)]
createHead :: WormsObject
createHead = let pic = Tex (tileSize,tileSize) 5
in object "head" pic True initPos (0,speedMod) NoObjectAttribute
createFood :: WormsObject
createFood = let pic = Tex (tileSize,tileSize) 9
in object "food" pic True (0,0) (0,0) NoObjectAttribute
createTail :: [WormsObject]
createTail = let picTail = Tex (tileSize,tileSize) 10
in (object "tail0" picTail False tail0Pos (0,0) (Tail 0)):
(object "tail1" picTail False tail1Pos (0,0) (Tail 1)):
(createAsleepTails initTailSize (initTailSize + maxFood - 1) picTail)
createAsleepTails :: Int -> Int -> ObjectPicture -> [WormsObject]
createAsleepTails tMin tMax pic
| (tMin > tMax) = []
| otherwise = (object ("tail" ++ (show tMin)) pic True (0,0) (0,0) (Tail 0)):(createAsleepTails (tMin + 1) tMax pic)
turnLeft :: Modifiers -> Position -> WormsAction ()
turnLeft _ _ = do
snakeHead <- findObject "head" "head"
setObjectCurrentPicture 8 snakeHead
setObjectSpeed (-speedMod,0) snakeHead
turnRight :: Modifiers -> Position -> WormsAction ()
turnRight _ _ = do
snakeHead <- findObject "head" "head"
setObjectCurrentPicture 7 snakeHead
setObjectSpeed (speedMod,0) snakeHead
turnUp :: Modifiers -> Position -> WormsAction ()
turnUp _ _ = do
snakeHead <- findObject "head" "head"
setObjectCurrentPicture 5 snakeHead
setObjectSpeed (0,speedMod) snakeHead
turnDown :: Modifiers -> Position -> WormsAction ()
turnDown _ _ = do
snakeHead <- findObject "head" "head"
setObjectCurrentPicture 6 snakeHead
setObjectSpeed (0,-speedMod) snakeHead
gameCycle :: WormsAction ()
gameCycle = do
(GA timer remainingFood tailSize previousHeadPos score) <- getGameAttribute
gState <- getGameState
case gState of
LevelStart n -> case n of
4 -> do
congratulations <- findObject "congratulations" "messages"
drawObject congratulations
if (timer == 0)
then funExit
else (setGameAttribute (GA (timer - 1) remainingFood tailSize previousHeadPos score))
_ -> do
disableGameFlags
level <- findObject ("level" ++ (show n)) "messages"
drawObject level
if (timer == 0)
then (do setGameState (Level n)
enableGameFlags
snakeHead <- findObject "head" "head"
setObjectAsleep False snakeHead
setObjectPosition initPos snakeHead
setObjectSpeed (0.0,speedMod) snakeHead
setObjectCurrentPicture 5 snakeHead
setGameAttribute (GA defaultTimer remainingFood tailSize previousHeadPos score)
destroyObject level
setNewMap n)
else setGameAttribute (GA (timer - 1) remainingFood tailSize previousHeadPos score)
Level n -> do
if (remainingFood == 0) -- advance level!
then (do setGameState (LevelStart (n + 1))
resetTails
disableGameFlags
setGameAttribute (GA timer maxFood initTailSize initPos score))
else if (timer == 0) -- put a new food in the map
then (do food <- findObject "food" "food"
newPos <- createNewFoodPosition
setObjectPosition newPos food
newFood <- findObject "food" "food"
setObjectAsleep False newFood
setGameAttribute (GA (-1) remainingFood tailSize previousHeadPos score)
snakeHead <- findObject "head" "head"
checkSnakeCollision snakeHead
snakeHeadPosition <- getObjectPosition snakeHead
moveTail snakeHeadPosition)
else if (timer > 0) -- there is no food in the map, so decrease the food timer
then (do setGameAttribute (GA (timer - 1) remainingFood tailSize previousHeadPos score)
snakeHead <- findObject "head" "head"
checkSnakeCollision snakeHead
snakeHeadPosition <- getObjectPosition snakeHead
moveTail snakeHeadPosition)
else (do -- there is a food in the map
food <- findObject "food" "food"
snakeHead <- findObject "head" "head"
col <- objectsCollision snakeHead food
if col
then (do snakeHeadPosition <- getObjectPosition snakeHead
setGameAttribute (GA defaultTimer (remainingFood-1) (tailSize + 1) snakeHeadPosition (score + 1))
addTail previousHeadPos
setObjectAsleep True food)
else (do checkSnakeCollision snakeHead
snakeHeadPosition <- getObjectPosition snakeHead
moveTail snakeHeadPosition))
showScore
GameOver -> do
disableMapDrawing
gameover <- findObject "gameover" "messages"
drawMap
drawObject gameover
if (timer == 0)
then funExit
else (setGameAttribute (GA (timer - 1) 0 0 (0,0) 0))
showScore :: WormsAction ()
showScore = do
(GA _ remainingFood _ _ score) <- getGameAttribute
printOnScreen (printf "Score: %d Food remaining: %d" score remainingFood) TimesRoman24 (40,8) 1.0 1.0 1.0
showFPS TimesRoman24 (780-60,8) 1.0 0.0 0.0
setNewMap :: Int -> WormsAction ()
setNewMap 2 = setCurrentMapIndex 1
setNewMap 3 = setCurrentMapIndex 2
setNewMap _ = return ()
resetTails :: WormsAction ()
resetTails = do
tail0 <- findObject "tail0" "tail"
setObjectPosition tail0Pos tail0
setObjectAttribute (Tail 0) tail0
tail1 <- findObject "tail1" "tail"
setObjectPosition tail1Pos tail1
setObjectAttribute (Tail 1) tail1
resetOtherTails initTailSize
resetOtherTails :: Int -> WormsAction ()
resetOtherTails n | (n == initTailSize + maxFood) = return ()
| otherwise = do tailn <- findObject ("tail" ++ (show n)) "tail"
setObjectAsleep True tailn
resetOtherTails (n + 1)
addTail :: (GLdouble,GLdouble) -> WormsAction ()
addTail presentHeadPos = do
tails <- getObjectsFromGroup "tail"
aliveTails <- getAliveTails tails []
asleepTail <- getAsleepTail tails
setObjectAsleep False asleepTail
setObjectPosition presentHeadPos asleepTail
setObjectAttribute (Tail 0) asleepTail
addTailNumber aliveTails
getAliveTails :: [WormsObject] -> [WormsObject] -> WormsAction [WormsObject]
getAliveTails [] t = return t
getAliveTails (o:os) t = do
sleeping <- getObjectAsleep o
if sleeping
then getAliveTails os t
else getAliveTails os (o:t)
getAsleepTail :: [WormsObject] -> WormsAction WormsObject
getAsleepTail [] = error "the impossible has happened!"
getAsleepTail (o:os) = do
sleeping <- getObjectAsleep o
if sleeping
then return o
else getAsleepTail os
addTailNumber :: [WormsObject] -> WormsAction ()
addTailNumber [] = return ()
addTailNumber (a:as) = do
(Tail n) <- getObjectAttribute a
setObjectAttribute (Tail (n + 1)) a
addTailNumber as
moveTail :: (GLdouble,GLdouble) -> WormsAction ()
moveTail presentHeadPos = do
(GA timer remainingFood tailSize previousHeadPos score) <- getGameAttribute
tails <- getObjectsFromGroup "tail"
aliveTails <- getAliveTails tails []
lastTail <- findLastTail aliveTails
setObjectPosition previousHeadPos lastTail
setGameAttribute (GA timer remainingFood tailSize presentHeadPos score)
changeTailsAttribute tailSize aliveTails
findLastTail :: [WormsObject] -> WormsAction WormsObject
findLastTail [] = error "the impossible has happened!"
findLastTail (t1:[]) = return t1
findLastTail (t1:t2:ts) = do (Tail na) <- getObjectAttribute t1
(Tail nb) <- getObjectAttribute t2
if (na > nb)
then findLastTail (t1:ts)
else findLastTail (t2:ts)
changeTailsAttribute :: Int -> [WormsObject] -> WormsAction ()
changeTailsAttribute _ [] = return ()
changeTailsAttribute tailSize (a:as) = do
Tail n <- getObjectAttribute a
setObjectAttribute (Tail (mod (n + 1) tailSize)) a
changeTailsAttribute tailSize as
checkSnakeCollision :: WormsObject -> WormsAction ()
checkSnakeCollision snakeHead = do
headPos <- getObjectPosition snakeHead
tile <- getTileFromWindowPosition headPos
tails <- getObjectsFromGroup "tail"
col <- objectListObjectCollision tails snakeHead
if ( (getTileBlocked tile) || col)
then (do setGameState GameOver
disableObjectsDrawing
disableObjectsMoving
setGameAttribute (GA defaultTimer 0 0 (0,0) 0))
else return ()
createNewFoodPosition :: WormsAction (GLdouble,GLdouble)
createNewFoodPosition = do
x <- randomInt (1,18)
y <- randomInt (1,24)
mapPositionOk <- checkMapPosition (x,y)
tails <- getObjectsFromGroup "tail"
tailPositionNotOk <- pointsObjectListCollision (toPixelCoord y) (toPixelCoord x) tileSize tileSize tails
if (mapPositionOk && not tailPositionNotOk)
then (return (toPixelCoord y,toPixelCoord x))
else createNewFoodPosition
where toPixelCoord a = (tileSize/2) + (fromIntegral a) * tileSize
checkMapPosition :: (Int,Int) -> WormsAction Bool
checkMapPosition (x,y) = do
mapTile <- getTileFromIndex (x,y)
return (not (getTileBlocked mapTile))
b,f,g,h,i,j :: WormsTile
b = (border1, True, 0.0, NoTileAttribute)
f = (free1, False, 0.0, NoTileAttribute)
g = (border2, True, 0.0, NoTileAttribute)
h = (free2, False, 0.0, NoTileAttribute)
i = (border3, True, 0.0, NoTileAttribute)
j = (free3, False, 0.0, NoTileAttribute)
map1 :: WormsMap
map1 = [[b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,b],
[b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b]]
map2 :: WormsMap
map2 = [[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,g,g,g,g,g,g,g,g,g,g,g,g,g,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,g,g,g,g,g,g,g,g,g,g,g,g,g,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,g],
[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g]]
map3 :: WormsMap
map3 = [[i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i],
[i,j,j,j,j,j,j,i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,i,i,i,i,i,i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,i,i,i,i,i,i,i,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i,j,j,j,j,j,j,j,i],
[i,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,i,j,j,j,j,j,j,j,i],
[i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i]]
| haskell-game/fungen | examples/worms/worms.hs | bsd-3-clause | 19,289 | 0 | 26 | 6,039 | 8,914 | 5,335 | 3,579 | 361 | 11 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE CPP #-}
-- | This is a legacy module from the pre-GHC HaRe, and will disappear
-- eventually.
module Language.Haskell.Refact.Utils.TypeSyn where
-- Modules from GHC
import qualified GHC as GHC
import qualified Name as GHC
import qualified Outputable as GHC
type HsExpP = GHC.HsExpr GHC.RdrName
type HsPatP = GHC.Pat GHC.RdrName
type HsDeclP = GHC.LHsDecl GHC.RdrName
type HsDeclsP = GHC.HsGroup GHC.Name
type InScopes = [GHC.Name]
type Export = GHC.LIE GHC.RdrName
-- ---------------------------------------------------------------------
-- From old/tools/base/defs/PNT.hs
-- | HsName is a name as it is found in the source
-- This seems to be quite a close correlation
type HsName = GHC.RdrName
-- |The PN is the name as it occurs to the parser, and
-- corresponds with the GHC.RdrName
-- type PN = GHC.RdrName
newtype PName = PN HsName deriving (Eq)
-- | The PNT is the unique name, after GHC renaming. It corresponds to
-- GHC.Name data PNT = PNT GHC.Name deriving (Data,Typeable) -- Note:
-- GHC.Name has SrcLoc in it already
instance Show GHC.NameSpace where
show ns
| ns == GHC.tcName = "TcClsName"
| ns == GHC.dataName = "DataName"
| ns == GHC.varName = "VarName"
| ns == GHC.tvName = "TvName"
| otherwise = "UnknownNamespace"
instance GHC.Outputable GHC.NameSpace where
ppr x = GHC.text $ show x
instance GHC.Outputable (GHC.MatchGroup GHC.Name (GHC.LHsExpr GHC.Name)) where
ppr (GHC.MG ms _ _ _) = GHC.text "MatchGroup" GHC.<+> GHC.ppr ms
instance GHC.Outputable (GHC.Match GHC.Name (GHC.LHsExpr GHC.Name)) where
ppr (GHC.Match _fn pats mtyp grhs) = GHC.text "Match" GHC.<+> GHC.ppr pats
GHC.<+> GHC.ppr mtyp
GHC.<+> GHC.ppr grhs
instance GHC.Outputable (GHC.GRHSs GHC.Name (GHC.LHsExpr GHC.Name)) where
ppr (GHC.GRHSs grhss binds) = GHC.text "GRHSs" GHC.<+> GHC.ppr grhss
GHC.<+> GHC.ppr binds
instance GHC.Outputable (GHC.GRHS GHC.Name (GHC.LHsExpr GHC.Name)) where
ppr (GHC.GRHS guards rhs) = GHC.text "GRHS" GHC.<+> GHC.ppr guards
GHC.<+> GHC.ppr rhs
instance GHC.Outputable (GHC.HsTupArg GHC.Name) where
ppr (GHC.Present e) = GHC.text "Present" GHC.<+> GHC.ppr e
ppr (GHC.Missing _typ) = GHC.text "Missing"
#if !(defined(MIN_VERSION_GLASGOW_HASKELL) && (MIN_VERSION_GLASGOW_HASKELL(8,0,1,1)))
instance GHC.Outputable (GHC.ConDeclField GHC.Name) where
ppr (GHC.ConDeclField name typ doc) = GHC.text "ConDeclField"
GHC.<+> GHC.ppr name
GHC.<+> GHC.ppr typ
GHC.<+> GHC.ppr doc
#endif
#if __GLASGOW_HASKELL__ <= 710
instance GHC.Outputable (GHC.TyFamEqn GHC.Name (GHC.LHsTyVarBndrs GHC.Name)) where
ppr (GHC.TyFamEqn name pats rhs) = GHC.text "TyFamEqn"
GHC.<+> GHC.ppr name
GHC.<+> GHC.ppr pats
GHC.<+> GHC.ppr rhs
#endif
-- ---------------------------------------------------------------------
| RefactoringTools/HaRe | src/Language/Haskell/Refact/Utils/TypeSyn.hs | bsd-3-clause | 3,353 | 0 | 10 | 940 | 817 | 419 | 398 | 49 | 0 |
<?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="sq-AL">
<title>Image Locaiton and Privacy Scanner | 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> | kingthorin/zap-extensions | addOns/imagelocationscanner/src/main/javahelp/org/zaproxy/zap/extension/imagelocationscanner/resources/help_sq_AL/helpset_sq_AL.hs | apache-2.0 | 995 | 83 | 52 | 162 | 402 | 212 | 190 | -1 | -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="it-IT">
<title>GraphQL Support Add-on</title>
<maps>
<homeID>graphql</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> | thc202/zap-extensions | addOns/graphql/src/main/javahelp/org/zaproxy/addon/graphql/resources/help_it_IT/helpset_it_IT.hs | apache-2.0 | 971 | 82 | 53 | 157 | 396 | 209 | 187 | -1 | -1 |
module RefacIntroThreshold (refacIntroThreshold) where
import PrettyPrint
import PosSyntax
import Data.Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import Data.List
import RefacUtils
import PFE0 (findFile)
import MUtils(( # ))
import AbstractIO
import Debug.Trace
import RefacMvDefBtwMod (addImport)
import LocalSettings (evalFilePath)
import RefacGenDef (generaliseDef2)
refacIntroThreshold args =
do let fileName = args!!0
thresholdValue = args!!1
thresholdName = args!!2
beginRow = read (args!!3)::Int
beginCol = read (args!!4)::Int
endRow = read (args!!5)::Int
endCol = read (args!!6)::Int
-- modName <- fileNameToModName fileName
(inscps, exps, mod, tokList) <- parseSourceFile fileName
unless ( isHidden ["rseq", "rpar", "runEval"] (concat (findImportsHiddenLists mod)) == [] )
$ error "rseq, rpar and/or runEval are explicitly hidden. Please unhide and try again."
let theSeq = checkForQualifiers "rseq" inscps
theRPar = checkForQualifiers "rpar" inscps
expr = grabSelection (beginRow, beginCol) (endRow, endCol) tokList mod
fileContent <- AbstractIO.readFile evalFilePath
unless (fileContent /= []) $ error "No active eval monad! Please activate an evaluation monad to continue!"
let runEval = read (fileContent) :: HsPatP
-- add the threshold to the function...
(m, tokList', mod', refactoredClients) <- generaliseDef2 fileName thresholdName (beginRow, beginCol) (endRow, endCol) (nameToExp thresholdValue) inscps exps mod tokList
AbstractIO.putStrLn $ show (length refactoredClients)
((_,m'), (newToks, newMod)) <- applyRefac (doIntroduce expr thresholdValue thresholdName runEval theRPar theSeq) (Just (inscps, exps, mod', tokList')) fileName
-- writeRefactoredFiles True [((fileName, m), (newToks, newMod))]
writeRefactoredFiles False $ ((fileName, m'), (newToks, newMod)):refactoredClients
AbstractIO.putStrLn "refacIntroThreshold Completed."
checkForQualifiers r inscps
= ck1 r inscps
where
ck1 r i
| isInScopeAndUnqualified r i = r
| length res == 0 = r
| length res > 1 = error (r ++ " is qualified more than once. " ++ r ++ " must only be qualified once or not at all to proceed.")
| otherwise = if res /= [] then (modNameToStr (head res)) ++"."++ r else r
where res = hsQualifier2 (nameToPNT r) i
addTheImport ss mod
= addImport "" (strToModName "Control.Parallel.Strategies") (map nameToPN ss) mod
isHidden [] ys = []
isHidden (x:xs) ys
| elem x ys = x : isHidden xs ys
| otherwise = isHidden xs ys
findImportsHiddenLists
= applyTU (full_tdTU (constTU [] `adhocTU` inImport))
where
inImport (HsImportDecl loc modName qual _ (Just (True, h))::HsImportDeclP) = return ((map (\(Var x) -> (pNTtoName x))) h)
inImport _ = return []
grabSelection pos1 pos2 toks mod
| expr == defaultExp = if pat == defaultPat then error "Select pattern/sub-expr is not valid for thresholding!"
else pNtoExp (patToPN pat)
| otherwise = expr
where
expr = locToExp pos1 pos2 toks mod
pat = locToPat pos1 pos2 toks mod
doIntroduce expr thresholdValue thresholdName runEval theRPar theSeq (_, _, t)
= do mod <- doIntroduce' expr thresholdValue thresholdName runEval theRPar theSeq t
if mod == t
then return t
else do
mod' <- addTheImport [theSeq] mod
return mod'
doIntroduce' expr thresholdValue thresholdName runEval theRPar theSeq t
= applyTP (once_buTP (failTP `adhocTP` inMatch) `choiceTP` failure) t
where
-- has to be a match: generalising already converted pattern bindings
-- to a match
inMatch (match@(HsMatch l name pats rhs ds)::HsMatchP)
| findEntity expr match
&& runEval `myElem` ds
= do (f,d) <- hsFDNamesFromInside match
-- error (show ((f++d), thresholdName))
-- unless (not (thresholdName `elem` (f++d))) $ error "Error: name of threshold parameter is already used on RHS!"
let runEval' = findPat runEval ds
if runEval' == Nothing
then mzero
else do
let newName = mkNewName "rpar_abs" (f++d) 1
newRunEval = modifyRunEval expr thresholdValue thresholdName newName theRPar theSeq (fromJust runEval')
-- match' <- addDecl match Nothing ([newParAbs], Nothing) False
match'' <- update (fromJust runEval') newRunEval match
return match''
inMatch _ = mzero
-- inModule (mod::HsModuleP)
-- | isDeclaredIn (
failure = idTP `adhocTP` mod
where mod (m::HsModuleP) = error "Cannot find the activated Eval Monad! Please activate a run eval monad within scope of the selected entity."
modifyRunEval expr thresholdValue thresholdName newName theRPar theSeq (pat@(Dec (HsPatBind l p rhs ds)))
= Dec (HsPatBind l p (convertToSeq newName rhs) (ds++[mkParAbs newName theRPar theSeq])) -- (Dec (HsPatBind l p (addGuards rhs) ds))
{- where
addGuards (HsGuard es) = error "Cannot add threshold to an eval monad with guards already defined!"
addGuards (HsBody e) = HsGuard [(loc0, theGuard, convertToSeq e), (loc0, nameToExp "otherwise", e)]
theGuard = Exp (HsInfixApp expr (theOpp) (nameToExp thresholdName))
theOpp = HsVar (nameToPNT "<")
-}
mkParAbs name theRPar theRSeq = (Dec (HsPatBind loc0 (nameToPat name) addGuards []))
where
addGuards = HsGuard [(loc0, theGuard, nameToExp theRPar), (loc0, nameToExp "otherwise", nameToExp theRSeq)]
theGuard = Exp (HsInfixApp expr (theOpp) (nameToExp thresholdName))
theOpp = HsVar (nameToPNT ">")
convertToSeq :: (Term t) => String -> t -> t
convertToSeq newName e
= runIdentity (applyTP (full_tdTP (idTP `adhocTP` exp)) e)
where
exp (Exp (HsId (HsVar i))::HsExpP)
| pNTtoName i == "rpar" = return $ nameToExp newName
exp x = return x
findPat :: HsPatP -> [HsDeclP] -> Maybe HsDeclP
findPat p [] = Nothing -- error "Cannot find active Eval Monad pattern binding!"
findPat p ((Dec (HsFunBind s m)):ds) = findPat p ds
findPat p (a@(Dec (HsPatBind l p2 rhs _)):ds)
| p == p2 = Just $ a
| otherwise = findPat p ds
findPat p (_:ds) = findPat p ds
myElem :: HsPatP -> [HsDeclP] -> Bool
myElem p [] = False
myElem p ((Dec (HsFunBind s m)):ds) = myElem p ds
myElem p ((Dec (HsPatBind l p2 rhs _)):ds)
| p == p2 = True
| otherwise = myElem p ds
myElem p (_:ds) = myElem p ds
| RefactoringTools/HaRe | old/refactorer/RefacIntroThreshold.hs | bsd-3-clause | 6,806 | 0 | 18 | 1,760 | 1,999 | 1,028 | 971 | -1 | -1 |
{-# LANGUAGE CPP #-}
------------------------------------------------------------------------------
-- |
-- Module: ColorCache
-- Copyright: (c) 2012 Jose Antonio Ortega Ruiz
-- License: BSD3-style (see LICENSE)
--
-- Maintainer: [email protected]
-- Stability: unstable
-- Portability: unportable
-- Created: Mon Sep 10, 2012 00:27
--
--
-- Caching X colors
--
------------------------------------------------------------------------------
#if defined XFT
module ColorCache(withColors, withDrawingColors) where
import MinXft
#else
module ColorCache(withColors) where
#endif
import Data.IORef
import System.IO.Unsafe (unsafePerformIO)
import Control.Monad.Trans (MonadIO, liftIO)
import Control.Exception (SomeException, handle)
import Graphics.X11.Xlib
data DynPixel = DynPixel Bool Pixel
initColor :: Display -> String -> IO DynPixel
initColor dpy c = handle black $ initColor' dpy c
where
black :: SomeException -> IO DynPixel
black = const . return $ DynPixel False (blackPixel dpy $ defaultScreen dpy)
type ColorCache = [(String, Color)]
{-# NOINLINE colorCache #-}
colorCache :: IORef ColorCache
colorCache = unsafePerformIO $ newIORef []
getCachedColor :: String -> IO (Maybe Color)
getCachedColor color_name = lookup color_name `fmap` readIORef colorCache
putCachedColor :: String -> Color -> IO ()
putCachedColor name c_id = modifyIORef colorCache $ \c -> (name, c_id) : c
initColor' :: Display -> String -> IO DynPixel
initColor' dpy c = do
let colormap = defaultColormap dpy (defaultScreen dpy)
cached_color <- getCachedColor c
c' <- case cached_color of
Just col -> return col
_ -> do (c'', _) <- allocNamedColor dpy colormap c
putCachedColor c c''
return c''
return $ DynPixel True (color_pixel c')
withColors :: MonadIO m => Display -> [String] -> ([Pixel] -> m a) -> m a
withColors d cs f = do
ps <- mapM (liftIO . initColor d) cs
f $ map (\(DynPixel _ pixel) -> pixel) ps
#ifdef XFT
type AXftColorCache = [(String, AXftColor)]
{-# NOINLINE xftColorCache #-}
xftColorCache :: IORef AXftColorCache
xftColorCache = unsafePerformIO $ newIORef []
getXftCachedColor :: String -> IO (Maybe AXftColor)
getXftCachedColor name = lookup name `fmap` readIORef xftColorCache
putXftCachedColor :: String -> AXftColor -> IO ()
putXftCachedColor name cptr =
modifyIORef xftColorCache $ \c -> (name, cptr) : c
initAXftColor' :: Display -> Visual -> Colormap -> String -> IO AXftColor
initAXftColor' d v cm c = do
cc <- getXftCachedColor c
c' <- case cc of
Just col -> return col
_ -> do c'' <- mallocAXftColor d v cm c
putXftCachedColor c c''
return c''
return c'
initAXftColor :: Display -> Visual -> Colormap -> String -> IO AXftColor
initAXftColor d v cm c = handle black $ (initAXftColor' d v cm c)
where
black :: SomeException -> IO AXftColor
black = (const $ initAXftColor' d v cm "black")
withDrawingColors :: -- MonadIO m =>
Display -> Drawable -> String -> String
-> (AXftDraw -> AXftColor -> AXftColor -> IO ()) -> IO ()
withDrawingColors dpy drw fc bc f = do
let screen = defaultScreenOfDisplay dpy
colormap = defaultColormapOfScreen screen
visual = defaultVisualOfScreen screen
fc' <- initAXftColor dpy visual colormap fc
bc' <- initAXftColor dpy visual colormap bc
withAXftDraw dpy drw visual colormap $ \draw -> f draw fc' bc'
#endif
| dsalisbury/xmobar | src/ColorCache.hs | bsd-3-clause | 3,516 | 0 | 15 | 767 | 1,033 | 526 | 507 | 34 | 2 |
module A5 where
import D5
main
= (sumFun [1 .. 4]) + (sum (map (f f_gen) [1 .. 7]))
| kmate/HaRe | old/testing/generaliseDef/A5_AstOut.hs | bsd-3-clause | 89 | 0 | 11 | 24 | 54 | 31 | 23 | 4 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.