code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE UnliftedFFITypes #-}
{-# LANGUAGE GHCForeignImportPrim #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE EmptyDataDecls #-}
{- |
Dynamically export Haskell values to JavaScript
-}
module GHCJS.Foreign.Export
( Export
, export
, withExport
, derefExport
, releaseExport
) where
import Control.Exception (bracket)
import GHC.Exts (Any)
import GHC.Fingerprint
import Data.Typeable
import Data.Word
import Unsafe.Coerce
import qualified GHC.Exts as Exts
import GHCJS.Prim
import GHCJS.Types
newtype Export a = Export JSVal
instance IsJSVal (Export a)
{- |
Export any Haskell value to a JavaScript reference without evaluating it.
The JavaScript reference can be passed to foreign code and used to retrieve
the value later.
The data referenced by the value will be kept in memory until you call
'releaseExport', even if no foreign code references the export anymore.
-}
export :: Typeable a => a -> IO (Export a)
export x = js_export w1 w2 (unsafeCoerce x)
where
Fingerprint w1 w2 = typeRepFingerprint (typeOf x)
{- |
Export the value and run the action. The value is only exported for the
duration of the action. Dereferencing it after the 'withExport' call
has returned will always return 'Nothing'.
-}
-- fixme is this safe with nested exports?
withExport :: Typeable a => a -> (Export a -> IO b) -> IO b
withExport x m = bracket (export x) releaseExport m
{- |
Retrieve the Haskell value from an export. Returns 'Nothing' if the
type does not match or the export has already been released.
-}
derefExport :: forall a. Typeable a => Export a -> IO (Maybe a)
derefExport e = do
let Fingerprint w1 w2 = typeRepFingerprint (typeOf (undefined :: a))
r <- js_derefExport w1 w2 e
if isNull r
then return Nothing
else Just . unsafeCoerce <$> js_toHeapObject r
{- |
Release all memory associated with the export. Subsequent calls to
'derefExport' will return 'Nothing'
-}
releaseExport :: Export a -> IO ()
releaseExport e = js_releaseExport e
-- ----------------------------------------------------------------------------
foreign import javascript unsafe
"h$exportValue"
js_export :: Word64 -> Word64 -> Any -> IO (Export a)
foreign import javascript unsafe
"h$derefExport"
js_derefExport :: Word64 -> Word64 -> Export a -> IO JSVal
foreign import javascript unsafe
"$r = $1;" js_toHeapObject :: JSVal -> IO Any
foreign import javascript unsafe
"h$releaseExport"
js_releaseExport :: Export a -> IO ()
| ghcjs/ghcjs-base | GHCJS/Foreign/Export.hs | mit | 2,683 | 14 | 14 | 534 | 503 | 263 | 240 | 47 | 2 |
module Kantour.TH where
import Language.Haskell.TH
import Data.Maybe
genSubcommands :: Q Exp
genSubcommands = do
(Just subcmdTypeName) <- lookupTypeName "Subcommand"
ClassI _ ins <- reify subcmdTypeName
(Just proxyTypeName) <- lookupTypeName "Proxy"
(Just proxyValName) <- lookupValueName "Proxy"
(Just esubValName) <- lookupValueName "ESub"
let typNames = mapMaybe getTypes ins
gen :: Name -> Exp
gen n = AppE (ConE esubValName) inner
where
innerV = ConE proxyValName
innerT = AppT (ConT proxyTypeName) (ConT n)
inner = innerV `SigE` innerT
pure (ListE (gen <$> typNames))
where
getTypes :: InstanceDec -> Maybe Name
getTypes (InstanceD _ _ (AppT _ (ConT tyN)) _) = Just tyN
getTypes _ = Nothing
| Javran/tuppence | src/Kantour/TH.hs | mit | 803 | 0 | 14 | 209 | 272 | 133 | 139 | 20 | 2 |
module HotDB.Core.Transformation (
transform
, transformDirected
, Side(..)
) where
import Prelude hiding (Left, Right)
import Control.Monad
import Data.Int (Int64)
import qualified Data.List as L
import qualified Data.Text as T
import Text.Read (readMaybe)
import HotDB.Core.Operation
import qualified HotDB.Core.Path as P
data Side = Left | Right deriving (Eq, Ord)
type Tiebreaker = Int64
isLeft :: Side -> Bool
isLeft Left = True
isLeft _ = False
isRight :: Side -> Bool
isRight s = not $ isLeft s
winsTiebreaker :: Tiebreaker -> Tiebreaker -> Side -> Bool
winsTiebreaker tb1 tb2 side = (tb1, side) > (tb2, oppositeSide side)
where oppositeSide Left = Right
oppositeSide Right = Left
losesTiebreaker :: Tiebreaker -> Tiebreaker -> Side -> Bool
losesTiebreaker tb1 tb2 side = not $ winsTiebreaker tb1 tb2 side
ifCanInc :: Position -> Maybe a -> Maybe a
ifCanInc p m = if (p + 1) == 0
then Nothing -- Increment would cause overflow
else m
transform :: Operation -> Operation -> Side -> Maybe Operation
transform (RootSet v tb) (RootSet av atb) side
| tb < atb || (losesTiebreaker tb atb side) || (v == av) = Just NoOp
| otherwise = Just $ RootSet v tb
transform (IntInc v) (IntInc _) _ = Just $ IntInc v
transform (TextInsert p c tb) (TextInsert ap _ atb) side
| p < ap || (p == ap && (winsTiebreaker tb atb side)) = Just $ TextInsert p c tb
| otherwise = ifCanInc p $ Just $ TextInsert (p + 1) c tb
transform (TextInsert p c tb) (TextDelete ap) _
| ap < p = Just $ TextInsert (p - 1) c tb
| otherwise = Just $ TextInsert p c tb
transform (TextDelete p) (TextInsert ap _ _) _
| ap <= p = ifCanInc p $ Just $ TextDelete (p + 1)
| otherwise = Just $ TextDelete p
transform (TextDelete p) (TextDelete ap) _
| p == ap = Just NoOp
| ap < p = Just $ TextDelete (p - 1)
| otherwise = Just $ TextDelete p
transform (SequenceSet p v tb) (SequenceSet ap av atb) side
| p == ap && ((losesTiebreaker tb atb side) || (v == av)) = Just NoOp
| otherwise = Just $ SequenceSet p v tb
transform (SequenceSet p v tb) (SequenceInsert ap _ _) _
| ap <= p = ifCanInc p $ Just $ SequenceSet (p + 1) v tb
| otherwise = Just $ SequenceSet p v tb
transform (SequenceSet p v tb) (SequenceDelete ap) _
| ap == p = Just NoOp
| ap < p = Just $ SequenceSet (p - 1) v tb
| otherwise = Just $ SequenceSet p v tb
transform (SequenceInsert p v tb) (SequenceSet _ _ _) _ = Just $ SequenceInsert p v tb
transform (SequenceInsert p v tb) (SequenceInsert ap av atb) side
| p < ap || ((p == ap) && (winsTiebreaker tb atb side)) = Just $ SequenceInsert p v tb
| otherwise = ifCanInc p $ Just $ SequenceInsert (p + 1) v tb
transform (SequenceInsert p v tb) (SequenceDelete ap) _
| ap < p = Just $ SequenceInsert (p - 1) v tb
| otherwise = Just $ SequenceInsert p v tb
transform (SequenceDelete p) (SequenceSet _ _ _) _ = Just $ SequenceDelete p
transform (SequenceDelete p) (SequenceInsert ap _ _) _
| ap <= p = ifCanInc p $ Just $ SequenceDelete (p + 1)
| otherwise = Just $ SequenceDelete p
transform (SequenceDelete p) (SequenceDelete ap) _
| p == ap = Just NoOp
| ap < p = Just $ SequenceDelete (p - 1)
| otherwise = Just $ SequenceDelete p
transform (MapSet k v tb) (MapSet ak av atb) side
| k == ak && ((losesTiebreaker tb atb side) || (v == av)) = Just NoOp
| otherwise = Just $ MapSet k v tb
transform (MapSet k v tb) (MapUnset _) _ = Just $ MapSet k v tb
transform (MapUnset k) (MapSet ak _ _) _
| k == ak = Just NoOp
| otherwise = Just $ MapUnset k
transform (MapUnset k) (MapUnset ak) _
| k == ak = Just NoOp
| otherwise = Just $ MapUnset k
transform op NoOp _ = Just op
transform _ _ _ = Nothing -- Incompatible transformation
transformDirected :: DirectedOperation -> DirectedOperation -> Side -> Maybe DirectedOperation
transformDirected dop@(DirectedOperation p op) (DirectedOperation ap aop) side =
case P.removePrefix ap p of
Nothing -> Just dop
Just p' -> if P.isEmpty p'
then do
op' <- transform op aop side
return $ DirectedOperation p op'
else do
DirectedOperation newRelPath op <- transformChild (DirectedOperation p' op) aop
return $ DirectedOperation (newRelPath `P.relativeTo` ap) op
transformChild :: DirectedOperation -> Operation -> Maybe DirectedOperation
transformChild _ (RootSet _ _) = Just directedNoOp
transformChild dop@(DirectedOperation p _) (SequenceSet i _ _) = do
t <- P.head p
pi <- readMaybe $ T.unpack t
if pi == i
then Just directedNoOp
else Just dop
transformChild dop@(DirectedOperation p op) (SequenceInsert i _ _) = do
t <- P.head p
pi <- readMaybe $ T.unpack t
if i <= pi
then ifCanInc pi $ do
p' <- P.replaceHead p (T.pack $ show $ pi + 1)
Just $ DirectedOperation p' op
else Just dop
transformChild dop@(DirectedOperation p op) (SequenceDelete i) = do
t <- P.head p
pi <- readMaybe $ T.unpack t
if i == pi
then Just directedNoOp
else if i < pi
then do
p' <- P.replaceHead p (T.pack $ show $ pi - 1)
Just $ DirectedOperation p' op
else Just dop
transformChild dop@(DirectedOperation p _) (MapSet k _ _) = do
t <- P.head p
if t == k
then Just directedNoOp
else Just dop
transformChild dop@(DirectedOperation p _) (MapUnset k) = do
t <- P.head p
if t == k
then Just directedNoOp
else Just dop
transformChild _ _ = Nothing
| jjwchoy/hotdb | src/HotDB/Core/Transformation.hs | mit | 5,573 | 0 | 17 | 1,425 | 2,441 | 1,193 | 1,248 | 132 | 7 |
{-# LANGUAGE NamedFieldPuns #-}
module Plotserver.Api (
plotUrl, plotCat, plotUpdate, plotDelete
) where
import Network.Curl
import Control.Applicative ((<$>))
import Plotserver.Types
------ API ------
plotUrl :: PlotConfig -> String -> String
plotUrl (PlotConfig {server}) dataset = server ++ "/" ++ dataset
plotCat :: PlotConfig -> String -> IO (Either String PlotData)
plotCat config dataset = parseResponse <$> curlGetResponse_ url_ opts where
url_ = actionUrl config dataset "download"
opts = defaultOpts config
-- TODO write real Maybe!
parseResponse = response2either $ Just . (read :: (String -> PlotData))
plotUpdate :: PlotConfig -> String -> PlotDataRow -> IO (Either String PlotData)
plotUpdate config dataset row = parseResponse <$> curlGetResponse_ url_ opts where
postData = show $ PlotData [row]
url_ = actionUrl config dataset "update"
opts = defaultOpts config ++ [
CurlPost True,
CurlPostFields [postData]
]
parseResponse = response2either $ matchString2MaybePlotdata "File written."
plotDelete :: PlotConfig -> String -> IO (Either String PlotData)
plotDelete config dataset = parseResponse <$> curlGetResponse_ url_ opts where
url_ = actionUrl config dataset "delete"
opts = defaultOpts config
parseResponse = response2either $ matchString2MaybePlotdata "File deleted."
------ helpers ------
matchString2MaybePlotdata :: String -> String -> Maybe PlotData
matchString2MaybePlotdata expected real = if real == expected
then Just $ PlotData []
else Nothing
defaultOpts :: PlotConfig -> [CurlOption]
defaultOpts PlotConfig {username, password} = [
CurlUserPwd (username ++ ":" ++ password),
CurlFollowLocation True
]
actionUrl :: PlotConfig -> String -> String -> String
actionUrl config dataset action = plotUrl config dataset ++ "?" ++ action
response2either :: (String -> Maybe PlotData) -> CurlResponse_ [(String, String)] String -> Either String PlotData
response2either parser response
| respStatus response == 200 = case parser (respBody response) of
Just res -> Right res
Nothing -> Left $ "Parse error: " ++ (respBody response)
| otherwise = Left err where
err = "Curl error: " ++ show (respStatus response) ++ " " ++ (respStatusLine response)
| dtorok/plotserver-hsapi | Plotserver/Api.hs | mit | 2,254 | 20 | 12 | 391 | 688 | 354 | 334 | 43 | 2 |
module HSudoku where
import Data.List
import Data.Ord (comparing)
import Data.List.Split (chunksOf)
import Data.Array.IArray
import Data.Either (rights)
import Data.Maybe (isJust, fromJust, isNothing)
import Data.Function (on)
import qualified Data.Set as S
import Control.Monad (foldM)
data Letter = A
| B
| C
| D
| E
| F
| G
| H
| I deriving (Show, Read, Eq, Ord, Enum, Ix)
data Digit = One
| Two
| Three
| Four
| Five
| Six
| Seven
| Eight
| Nine deriving (Eq, Ord, Enum, Ix)
type Coord = (Letter, Digit)
type Unit = [Coord]
type Cell = Either [Digit] Digit
type Grid = Array Coord Cell
type Technique = Grid -> Maybe Grid
instance Show Digit where
show One = "1"
show Two = "2"
show Three = "3"
show Four = "4"
show Five = "5"
show Six = "6"
show Seven = "7"
show Eight = "8"
show Nine = "9"
digits :: [Digit]
digits = [One .. Nine]
letters :: [Letter]
letters = [A .. I]
coords :: [Coord]
coords = cross letters digits
box :: (Coord, Coord)
box = ((A, One), (I, Nine))
units :: Array Coord [Unit]
units = array box [(c, [cs | cs <- unitList, c `elem` cs]) | c <- coords]
peers :: Array Coord [Coord]
peers = array box [(c, filter (/=c) . S.toList . S.fromList . concat $ (units ! c)) | c <- coords]
unitList :: [Unit]
unitList = [cross letters [c] | c <- digits] ++
[cross [r] digits | r <- letters] ++
[cross ls ds | ls <- chunksOf 3 letters, ds <- chunksOf 3 digits]
techniques :: [Technique]
techniques = [single, hiddenSingle, hiddenDouble, double]
--techniques = [single, hiddenSingle, hiddenDouble, hiddenTripple, double, tripple]
--techniques = [single, hiddenSingle, hiddenDouble, hiddenTripple, double, tripple]
--techniques = [single, hiddenSingle, hiddenDouble, hiddenTripple, double, tripple]
--techniques = [single, hiddenSingle, hiddenDouble, hiddenTripple, double, tripple]
emptyGrid :: Grid
emptyGrid = array box [(c, Left digits) | c <- coords]
--Logic
-- |Takes a grid and returns [(Unit, [[Coord]])] where each
-- (Unit, [[Coord]]) represents a unit and its kindred sets where
-- each list of Coord represents the locations of the kindred cells
-- Whether or not a cell is kindred with another is determined by the Int.
-- For cells to belong in a kindred set they must contain x number of possible
-- digits and there must be exactly x number of kindreds in the unit
findKindredCells :: Grid -> Int -> [(Unit, [[Coord]])]
findKindredCells g n = kindreds
where
unsolvedList = map (filter (not . cellFilled . (g !))) unitList
nsList = map (filter ((==n) . length . (\(Left x) -> x) . (g !)))
unsolvedList
eqList = map (filter ((==n) . length) . groupBy ((==) `on` (!) g))
nsList
kindreds = filter (not . null . snd) (zip unitList eqList)
--eqList = groupBy ((\(Left a) (Left b) -> a == b) . (g !)) nsList
--findSingles :: Grid -> [([Coord], [Digit])]
single :: Technique
single g = ng
where
oneks = findKindredCells g 1
assignments = S.toList . S.fromList $
[ (coord, head ds) | (_, ones) <- oneks
, one <- ones, coord <- one
, let ds = (\(Left x) -> x) (g ! coord)
]
ng = if not . null $ assignments
then foldM assign g (S.toList . S.fromList $ assignments)
else Nothing
hiddenSingle :: Technique
hiddenSingle g = ng
where
ums = zip unitList (map (missing g) unitList)
hss = S.toList . S.fromList $
[ (coord, digit) | (unit, ms) <- ums, digit <- ms
, let cs = possibles g unit [digit]
, let coord = head cs, length cs == 1
]
ng = if not . null $ hss then foldM assign g hss else Nothing
hiddenDouble :: Technique
hiddenDouble g = ng
where
uhd u = S.toList . S.fromList $
[ hd | a <- twops, b <- twops \\ [a]
, let hd = (sort [fst a, fst b], snd a)
, snd a == snd b
]
where
ms = missing g u
twops = [ (m, cs) | m <- ms
, let cs = possibles g u [m]
, length cs == 2
]
uhds = filter ((>0) . length . snd) $ zip unitList (map uhd unitList)
toElim =
[ (c, d) | (u, uhd') <- uhds, c <- u, (hds, hcs) <- uhd'
, let psb = (\a -> case a of
Left x -> x
Right _ -> []) (g ! c)
, let ds = if c `elem` hcs
then psb \\ hds
else filter (`elem` hds) psb
, d <- ds
, case g ! c of
Left _ -> True
Right _ -> False
]
ng = if not . null $ toElim then foldM eliminate g toElim else Nothing
hiddenTripple :: Technique
hiddenTripple g = ng
where
uht u = S.toList . S.fromList $
[ ht | a <- trips
, b <- trips \\ [a]
, c <- trips \\ [a, b]
, let ht = (sort [fst a, fst b, fst c], snd a)
, snd a == snd b, snd a == snd c
]
where
ms = missing g u
trips = [ (m, coords) | m <- ms
, let cs = possibles g u [m]
, length cs == 3
]
uhts = filter ((>0) . length . snd) $ zip unitList (map uht unitList)
toElim =
[ (c, d) | (u, uht') <- uhts, c <- u, (hts, hcs) <- uht'
, let psb = (\a -> case a of
Left x -> x
Right _ -> []) (g ! c)
, let ds = if c `elem` hcs
then psb \\ hts
else filter (`elem` hts) psb
, d <- ds
, case g ! c of
Left _ -> True
Right _ -> False
]
ng = if not . null $ toElim then foldM eliminate g toElim else Nothing
double :: Technique
double g = ng
where
twoks = findKindredCells g 2
toElim = S.toList . S.fromList $
[ (c, ds) | (u, twos) <- twoks
, two <- twos, c <- u \\ two
, ds <- (\(Left x) -> x) (g ! head two)
]
ng = if not . null $ toElim then foldM eliminate g toElim else Nothing
tripple :: Technique
tripple g = ng
where
tripks = findKindredCells g 3
toElim = S.toList . S.fromList $
[ (c, ds) | (u, trips) <- tripks
, trip <- trips, c <- u \\ trip
, ds <- (\(Left x) -> x) (g ! head trip)
]
ng = if not . null $ toElim then foldM eliminate g toElim else Nothing
applyTechnique :: Technique -> Grid -> Maybe Grid
applyTechnique t g
| isNothing ng = Nothing
| fromJust ng == g = Nothing
| otherwise = ng
where
ng = t g
applyTechniques :: [Technique] -> Grid -> Maybe Grid
applyTechniques (t:ts) g = case ng of
Nothing -> applyTechniques ts g
Just _ -> ng
where
ng = applyTechnique t g
applyTechniques _ _ = Nothing
eliminate :: Grid -> (Coord, Digit) -> Maybe Grid
eliminate g (c, d) = case currentCell of
Right _ -> Just g
Left ds -> let newDigits = delete d ds in
if null newDigits
then Nothing
else Just (g // [(c, Left newDigits)])
where
currentCell = g ! c
assign :: Grid -> (Coord, Digit) -> Maybe Grid
assign g (c, d) = case oldCell of
Right _ -> Just g
Left _ -> foldM eliminate ng (zip cellPeers (repeat d))
where
oldCell = g ! c
newCell = (c, Right d)
cellPeers = peers ! c
ng = g // [newCell]
unsolvedByCertainty :: Grid -> [(Coord, [Digit])]
unsolvedByCertainty g = sortBy (comparing (length . snd)) unsolvedAssocs
where unsolvedAssocs = [(coord, psbs) | (coord, Left psbs) <- assocs g]
mostCertainUnsolved :: Grid -> Maybe (Coord, [Digit])
mostCertainUnsolved g = if null usbc then Nothing else Just (head usbc)
where usbc = unsolvedByCertainty g
search :: Grid -> Maybe Grid
search g = if isJust mostC && length digits > 1 then
case solve ng of
Just x -> Just x
Nothing -> solve (g // [(coord, if length ndigits > 1
then Left ndigits
else Right $ head ndigits)])
else Nothing
where
mostC = mostCertainUnsolved g
coord = fst . fromJust $ mostC
ds = snd . fromJust $ mostC
digit = head ds
ndigits = delete digit digits
ng = g // [(coord, Right digit)]
trySolve :: Grid -> Either Grid Grid
trySolve g = if isSolved result
then Right result
else Left result
where
result = maybeUntilNoDiff (applyTechniques techniques) g
solve :: Grid -> Maybe Grid
solve g = case result of
Left x -> search x
Right x -> Just x
where
result = trySolve g
--Util
-- |Takes a grid and a list of coordinates to check against a list of digits
-- Returns a list of coordinates where the digits are possible
possibles :: Grid -> [Coord] -> [Digit] -> [Coord] -- TODO: Optimize
possibles g cs ds = ps
where
dict = [(coord, cell) | coord <- cs, let cell = g ! coord]
ps = [coord | (coord, Left ds') <- dict, all (`elem` ds') ds]
missing :: Grid -> Unit -> [Digit]
missing g u = digits \\ rs
where
rs = rights (map (g!) u)
maybeUntilNoDiff :: Eq a => (a -> Maybe a) -> a -> a
maybeUntilNoDiff f a = case na of
Nothing -> a
Just x -> if x == a then a else maybeUntilNoDiff f x
where
na = f a
untilNoDiff :: Eq a => (a -> a) -> a -> a
untilNoDiff f a = if a == na then a else untilNoDiff f na where na = f a
cross :: [l] -> [d] -> [(l,d)]
cross ls ds = [(l,d) | l <- ls, d <- ds]
cellFilled :: Cell -> Bool
cellFilled c = case c of
Right _ -> True
Left _ -> False
isSolved :: Grid -> Bool
isSolved g = all (==[One .. Nine]) $ map (sort.rights) [map (g !) u | u <- unitList]
--Parse
parseGrid :: String -> Maybe Grid
parseGrid s = foldM assign emptyGrid assignments
where
czip = zip coords s
vals = filter ((`elem` ['1' .. '9']) . snd) czip
assignments = [ (c, d) | (c, dc) <- vals, let d = readDigit dc]
--Read / Show
showCoord :: Coord -> String
showCoord (l, d) = show l ++ show d
readDigit :: Char -> Digit
readDigit c
| c == '1' = One
| c == '2' = Two
| c == '3' = Three
| c == '4' = Four
| c == '5' = Five
| c == '6' = Six
| c == '7' = Seven
| c == '8' = Eight
| c == '9' = Nine
| otherwise = error $ "Invalid Char: " ++ [c]
showCell :: Cell -> String
showCell (Right d) = show d
showCell (Left _) = "."
showGrid :: Grid -> String
showGrid = concatMap showCell . elems
formatGridString :: String -> String
formatGridString s = unlines $ [upperline] ++ vprawls ++ [lowerline]
where
upperline = "βββββββββββββ³ββββββββββββ³ββββββββββββ"
innerline = "β£ββββββββββββββββββββββββββββββββββββ«"
lowerline = "βββββββββββββ»ββββββββββββ»ββββββββββββ"
boxline = "βββββΌββββΌββββββββΌββββΌββββββββΌββββΌββββ"
rawls = chunksOf 9 s
prawls = map (intersperse ' ' . (\x -> "β" ++ x ++ "β") .
intercalate "β" . map (intersperse 'β') . chunksOf 3) rawls
vprawls = intercalate [innerline] . chunksOf 5 .
concatMap (intersperse boxline) . chunksOf 3 $ prawls
--IO
printSideBySideGridStrings :: (String, String) -> IO ()
printSideBySideGridStrings (s1, s2) = putStrLn lmerge
where
lmerge = unlines [a ++ " " ++ b |
(a, b) <- zip
(lines $ formatGridString s1)
(lines $ formatGridString s2)]
printSideBySideGrids :: (Grid, Grid) -> IO ()
printSideBySideGrids (a, b) = printSideBySideGridStrings
(showGrid a, showGrid b)
printGrid :: Grid -> IO ()
printGrid = putStrLn . formatGridString . showGrid
| Kirez/hsudoku | src/HSudoku.hs | mit | 12,553 | 0 | 18 | 4,274 | 4,465 | 2,379 | 2,086 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html
module Stratosphere.ResourceProperties.EventsRuleInputTransformer where
import Stratosphere.ResourceImports
-- | Full data type definition for EventsRuleInputTransformer. See
-- 'eventsRuleInputTransformer' for a more convenient constructor.
data EventsRuleInputTransformer =
EventsRuleInputTransformer
{ _eventsRuleInputTransformerInputPathsMap :: Maybe Object
, _eventsRuleInputTransformerInputTemplate :: Val Text
} deriving (Show, Eq)
instance ToJSON EventsRuleInputTransformer where
toJSON EventsRuleInputTransformer{..} =
object $
catMaybes
[ fmap (("InputPathsMap",) . toJSON) _eventsRuleInputTransformerInputPathsMap
, (Just . ("InputTemplate",) . toJSON) _eventsRuleInputTransformerInputTemplate
]
-- | Constructor for 'EventsRuleInputTransformer' containing required fields
-- as arguments.
eventsRuleInputTransformer
:: Val Text -- ^ 'eritInputTemplate'
-> EventsRuleInputTransformer
eventsRuleInputTransformer inputTemplatearg =
EventsRuleInputTransformer
{ _eventsRuleInputTransformerInputPathsMap = Nothing
, _eventsRuleInputTransformerInputTemplate = inputTemplatearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html#cfn-events-rule-inputtransformer-inputpathsmap
eritInputPathsMap :: Lens' EventsRuleInputTransformer (Maybe Object)
eritInputPathsMap = lens _eventsRuleInputTransformerInputPathsMap (\s a -> s { _eventsRuleInputTransformerInputPathsMap = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html#cfn-events-rule-inputtransformer-inputtemplate
eritInputTemplate :: Lens' EventsRuleInputTransformer (Val Text)
eritInputTemplate = lens _eventsRuleInputTransformerInputTemplate (\s a -> s { _eventsRuleInputTransformerInputTemplate = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EventsRuleInputTransformer.hs | mit | 2,093 | 0 | 13 | 210 | 253 | 145 | 108 | 28 | 1 |
-- $ ghc -o hello hello.hs && ./hello
main = putStrLn "Hello, World!"
| jwhitfieldseed/sandbox | haskell/hello.hs | mit | 70 | 0 | 5 | 13 | 10 | 5 | 5 | 1 | 1 |
-- This file is based on:
--
-- "The SMT-LIB Standard, Version 2.0"
-- by Clark Barrett Aaron Stump Cesare Tinelli
-- Release: December 21, 2010
-- Appendix C
--
-- URL:
-- http://goedel.cs.uiowa.edu/smtlib/papers/smt-lib-reference-v2.0-r10.12.21.pdf
{-# LANGUAGE OverloadedStrings, Safe, DeriveDataTypeable #-}
module SMTLib2.AST where
import Data.Typeable
import Data.Data
import Data.String(IsString(..))
newtype Name = N String
deriving (Eq,Ord,Show,Data,Typeable)
data Ident = I Name [Integer]
deriving (Eq,Ord,Show,Data,Typeable)
data Quant = Exists | Forall
deriving (Eq,Ord,Show,Data,Typeable)
data Binder = Bind { bindVar :: Name, bindType :: Type }
deriving (Eq,Ord,Show,Data,Typeable)
data Defn = Defn { defVar :: Name, defExpr :: Expr }
deriving (Eq,Ord,Show,Data,Typeable)
data Literal = LitBV Integer Integer -- ^ value, width (in bits)
| LitNum Integer
| LitFrac Rational
| LitStr String
deriving (Eq,Ord,Show,Data,Typeable)
data Type = TApp Ident [Type]
| TVar Name
deriving (Eq,Ord,Show,Data,Typeable)
data Expr = Lit Literal
| App Ident (Maybe Type) [Expr]
| Quant Quant [Binder] Expr
| Let [Defn] Expr
| Annot Expr [Attr]
deriving (Eq,Ord,Show,Data,Typeable)
data Attr = Attr { attrName :: Name , attrVal :: Maybe AttrVal }
deriving (Eq,Ord,Show,Data,Typeable)
type AttrVal = Expr -- A bit of an approximation....
data Option
= OptPrintSuccess Bool
| OptExpandDefinitions Bool
| OptInteractiveMode Bool
| OptProduceProofs Bool
| OptProduceUnsatCores Bool
| OptProduceModels Bool
| OptProduceAssignments Bool
| OptRegularOutputChannel String
| OptDiagnosticOutputChannel String
| OptRandomSeed Integer
| OptVerbosity Integer
| OptAttr Attr
deriving (Data,Typeable)
data InfoFlag
= InfoAllStatistics
| InfoErrorBehavior
| InfoName
| InfoAuthors
| InfoVersion
| InfoStatus
| InfoReasonUnknown
| InfoAttr Attr
deriving (Data,Typeable)
data Command
= CmdSetLogic Name
| CmdSetOption Option
| CmdSetInfo Attr
| CmdDeclareType Name Integer
| CmdDefineType Name [Name] Type
| CmdDeclareConst Name Type
| CmdDeclareFun Name [Type] Type
| CmdDeclareDatatype Name [Name] [(Name, [(Name, Type)])]
| CmdDeclareDatatypes [(Name, Integer)] [([Name], [(Name, [(Name, Type)])])]
| CmdDefineFun Name [Binder] Type Expr
| CmdPush Integer
| CmdPop Integer
| CmdAssert Expr
| CmdCheckSat
| CmdGetAssertions
| CmdGetValue [Expr]
| CmdGetProof
| CmdGetUnsatCore
| CmdGetInfo InfoFlag
| CmdGetOption Name
| CmdComment String
| CmdExit
deriving (Data,Typeable)
newtype Script = Script [Command]
--------------------------------------------------------------------------------
-- To make it a bit simpler to write terms in the above AST
-- we provide some instances. They are intended to be used only
-- for writing simple literals, and not any of the computational
-- operations associated with the classes.
-- Strings
instance IsString Name where fromString = N
instance IsString Ident where fromString x = I (fromString x) []
instance IsString Type where fromString x = TApp (fromString x) []
instance IsString Expr where fromString = Lit . LitStr . fromString
-- Integers
-- NOTE: Some of these might not mean anything, depending on the theory.
instance Num Expr where
fromInteger x = Lit (LitNum x)
x + y = app "+" [x,y]
x - y = app "-" [x,y]
x * y = app "*" [x,y]
signum x = app "signum" [x]
abs x = app "abs" [x]
-- Fractional numbers
instance Fractional Expr where
fromRational x = Lit (LitFrac x)
x / y = app "/" [x,y]
app :: Ident -> [Expr] -> Expr
app f es = App f Nothing es
| yav/smtLib | src/SMTLib2/AST.hs | mit | 3,989 | 0 | 12 | 1,023 | 1,099 | 623 | 476 | 97 | 1 |
module Main where
import Control.Monad.State.Strict
import qualified Data.IntMap.Strict as IM
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe, fromJust)
import Data.Char (isLetter)
import Parser
main :: IO ()
main = do
p <- readProgram "./prg.txt"
putStrLn $ "part 1: " ++ (show $ part1 p)
type Runtime a = State Env a
data Env
= Env
{ program :: Program
, instructionPointer :: Int
, registers :: M.Map Register Int
, output :: [Int]
} deriving Show
type Program = IM.IntMap Instruction
data Instruction
= Copy Value Value
| Increase Value
| Decrease Value
| JumpNotZero Value Value
| Output Value
deriving (Show, Eq, Ord)
data Value
= Constant Int
| Register Register
deriving (Show, Eq, Ord)
type Register = Char
part1 :: Program -> Int
part1 prg = head $ filter (isSignal . flip tryInp prg) [1..]
where isSignal = all id . zipWith (==) (cycle [0,1])
tryInp :: Int -> Program -> [Int]
tryInp a prg =
reverse . output $ execState (setRegister (a + 2541) 'a' >> run 50000) (Env prg 0 M.empty [])
run :: Int -> Runtime ()
run 0 = return ()
run n = do
inst <- getInstruction
case inst of
Nothing -> return ()
Just i -> do
regs <- gets registers
step i
run (n-1)
step :: Instruction -> Runtime ()
step (Copy val (Register reg)) = do
v <- getValue val
setRegister v reg
moveNext
step (Copy _ (Constant _)) =
moveNext
step (Increase (Register reg)) = do
incrRegister reg
moveNext
step (Increase (Constant _)) =
moveNext
step (Decrease (Register reg)) = do
decrRegister reg
moveNext
step (Decrease (Constant _)) =
moveNext
step (JumpNotZero b j) = do
bv <- getValue b
if bv /= 0
then do
jv <- getValue j
jump (+ jv)
else moveNext
step (Output val) = do
v <- getValue val
addOutput v
moveNext
getValue :: Value -> Runtime Int
getValue (Constant n) = return n
getValue (Register r) = readRegister r
readRegister :: Register -> Runtime Int
readRegister reg = fromMaybe 0 <$> gets (\env -> M.lookup reg (registers env))
incrRegister :: Register -> Runtime ()
incrRegister = modRegister (+ 1)
decrRegister :: Register -> Runtime ()
decrRegister = modRegister (subtract 1)
setRegister :: Int -> Register -> Runtime ()
setRegister val reg = modify' (\env -> env { registers = M.insert reg val (registers env) })
modRegister :: (Int -> Int) -> Register -> Runtime ()
modRegister upd reg = modify' (\env -> env { registers = M.update (Just . upd) reg (registers env) })
addOutput :: Int -> Runtime ()
addOutput v = modify' (\env -> env { output = v : output env })
getInstruction :: Runtime (Maybe Instruction)
getInstruction = gets (\env -> instructionPointer env `IM.lookup` program env)
modifyInstruction :: (Instruction -> Instruction) -> Int -> Runtime ()
modifyInstruction upd delta = modify' (\env -> env { program = IM.alter (fmap upd) (instructionPointer env + delta) (program env) })
moveNext :: Runtime ()
moveNext = jump (+1)
jump :: (Int -> Int) -> Runtime ()
jump jmp = modify' (\env -> env { instructionPointer = jmp (instructionPointer env) })
readProgram :: FilePath -> IO Program
readProgram file =
IM.fromList . zip [0..] . map (fromJust . eval instructionP) . lines <$> readFile file
instructionP :: Parser Instruction
instructionP = parseOneOf [ copyP, incP, decP, jumpP, outputP ]
where
copyP = Copy <$> (parseString "cpy " *> valueP) <*> valueP
incP = Increase <$> (parseString "inc " *> valueP)
decP = Decrease <$> (parseString "dec " *> valueP)
jumpP = JumpNotZero <$> (parseString "jnz " *> valueP) <*> valueP
outputP = Output <$> (parseString "out " *> valueP)
valueP = (parseEither regP constP) <* ignoreWhiteSpace
regP = Register <$> parsePred isLetter
constP = Constant <$> parseInt
| CarstenKoenig/AdventOfCode2016 | Day25/Main.hs | mit | 3,866 | 0 | 14 | 873 | 1,552 | 799 | 753 | 112 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Main (main) where
import qualified SDL
import qualified SDL.Image
import qualified Common as C
import Control.Monad (unless)
import Control.Monad.IO.Class (MonadIO)
import Data.Foldable (foldl')
data World = World
{ exiting :: Bool
, frame :: Int
}
data Intent = Idle | Quit
initialApp :: World
initialApp = World
{ exiting = False
, frame = 0
}
main :: IO ()
main = C.withSDL $ C.withSDLImage $ do
C.setHintQuality
C.withWindow "Lesson 14" (640, 480) $ \w ->
C.withRenderer w $ \r -> do
t <- SDL.Image.loadTexture r "./assets/walk.png"
let doRender = renderApp r t
runApp (appLoop doRender) initialApp
SDL.destroyTexture t
runApp :: (Monad m) => (World -> m World) -> World -> m ()
runApp f = repeatUntil f exiting
repeatUntil :: (Monad m) => (a -> m a) -> (a -> Bool) -> a -> m ()
repeatUntil f p = go
where go a = f a >>= \b -> unless (p b) (go b)
appLoop :: (MonadIO m) => (World -> m ())-> World -> m World
appLoop r a
= updateApp a <$> pollIntents
>>= \a' -> a' <$ r a'
updateApp :: World -> [Intent] -> World
updateApp a = stepFrame . foldl' applyIntent a
pollIntents :: (MonadIO m) => m [Intent]
pollIntents = eventToIntent `fmap2` SDL.pollEvents
where
fmap2 = fmap . fmap
eventToIntent :: SDL.Event -> Intent
eventToIntent (SDL.Event _t SDL.QuitEvent) = Quit
eventToIntent _ = Idle
applyIntent :: World -> Intent -> World
applyIntent a Quit = a { exiting = True }
applyIntent a Idle = a
stepFrame :: World -> World
stepFrame a = a { frame = frame a + 1 }
renderApp :: (MonadIO m) => SDL.Renderer -> SDL.Texture -> World -> m ()
renderApp r t a = do
SDL.clear r
SDL.copy r t (Just mask) (Just pos)
SDL.present r
where
x = (frame a `div` 8) `mod` 8
mask = fromIntegral <$> C.mkRect (x * 48) 0 48 48
s = C.mkRect 0 0 192 (192 :: Double)
w = C.mkRect 0 0 640 480
pos = floor <$> centerWithin s w
centerWithin :: (Fractional a) => SDL.Rectangle a -> SDL.Rectangle a -> SDL.Rectangle a
centerWithin (SDL.Rectangle _ iz) (SDL.Rectangle (SDL.P op) oz)
= SDL.Rectangle p iz
where
p = SDL.P $ op + (oz - iz) / 2
| palf/haskellSDL2Examples | examples/lesson14/src/Lesson14.hs | gpl-2.0 | 2,330 | 0 | 17 | 569 | 947 | 497 | 450 | 64 | 1 |
module Network.Gitit.Plugins.IncludeAsCodeBlock (plugin) where
{-
This plugin allows you to include any code file inside the current
code block.
~~~ {.csv include-code="my-file.csv"}
This will be replaced by the content of the csv file.
~~~
-}
import Network.Gitit.Interface
-- from the utf8-string package on HackageDB:
--import Data.ByteString.Lazy.UTF8 (fromString)
-- from the SHA package on HackageDB:
import System.FilePath ((</>), normalise, takeDirectory )
import System.Directory(doesFileExist)
import Control.Monad.Trans (liftIO)
import Data.FileStore.Types(retrieve, FileStoreError(..))
import Data.List(stripPrefix)
import Control.Exception (catch)
plugin :: Plugin
plugin = mkPageTransformM transformBlock
transformBlock :: Block -> PluginM Block
transformBlock (CodeBlock (id, classes, namevals) _) | "include-code" `elem` map fst namevals = do
--cfg <- askConfig
rq <- askRequest
fs <- askFileStore
let
handledAttrs = ["include-code"]
unhandledAttrs = filter (\e -> not (elem (fst e) handledAttrs)) namevals
userUrl = maybe "" (\x -> x) $ lookup "include-code" namevals
formattedUrl = urlFromFSRoot (rqUri rq) userUrl
errorHandler :: FileStoreError -> IO (String)
errorHandler e = return $ "Could not access to: \"" ++ formattedUrl ++ "\""
liftIO $ do
fileContent <- catch
(retrieve fs formattedUrl Nothing)
errorHandler
return $ CodeBlock (id, classes, unhandledAttrs) fileContent
transformBlock x = return x
urlFromFSRoot requestUri ressourceUrl =
stripPreview impl
where relUrlToCurrentDir = drop 1 . takeDirectory $ requestUri
impl | isRelUri ressourceUrl = relUrlToCurrentDir ++ "/" ++ ressourceUrl
| otherwise = drop 1 ressourceUrl
stripPreview ori = maybe ori (\x -> x) (stripPrefix "_preview/" ori)
isRelUri :: String -> Bool
isRelUri uri = take 1 uri /= "/" | jraygauthier/jrg-gitit-plugins | src/Network/Gitit/Plugins/IncludeAsCodeBlock.hs | gpl-2.0 | 2,029 | 0 | 18 | 486 | 492 | 261 | 231 | 35 | 1 |
-- Copyright Β© 2015 Mykola Orliuk <[email protected]>
-- Distributed under the terms of the GNU General Public License v2
{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE FlexibleInstances #-}
module ExRender.Base
( module ExRender.Base
, module Text.PrettyPrint
) where
import Text.PrettyPrint
-- | Wrap width soft limit
exWrapWidth β· Int
exWrapWidth = 100
class ExRender a where
-- | Renders 'a' into a 'Doc' representing some part of exheres
exDisp β· a β Doc
class ExRenderQ a where
-- | Renders 'a' into a 'Doc' to be placed within double-quotes inside of exheres
exDispQ β· a β Doc
-- | Double-quoted string for bash
dquoted β· String β String
dquoted [] = []
dquoted ('\\':xs) = "\\\\" ++ dquoted xs
dquoted ('"':xs) = "\\\"" ++ dquoted xs
dquoted ('`':xs) = "\\`" ++ dquoted xs
dquoted ('$':xs) = "\\$" ++ dquoted xs
dquoted (x:xs) = x : dquoted xs
-- | Split String in lines according to soft limit
softWidth β· Int β [String] β [[String]]
softWidth width = build 0 [] where
build _ ys [] = [reverse ys]
build 0 [] (w:ws) = build (length w) [w] ws
build n ys (w:ws) | n' > width = reverse ys : build 0 [] (w:ws)
| otherwise = build n' (w : ys) ws
where
n' = length w + n
-- | Build a Doc out of String respecting soft width limit
reflow β· Int β String β Doc
reflow width = vcat . map (text . unwords) . softWidth width . words
-- | Wrap doc with spaces around if non-empty
spaces β· Doc β Doc
spaces doc | isEmpty doc = empty
| otherwise = space <> doc <> space
-- | Wrap with brackets non-empty doc
nbrackets β· Doc β Doc
nbrackets doc | isEmpty doc = empty
| otherwise = brackets doc
-- | Render a multi-line meta-field of Exheres if non-empty value
exFieldDoc β· String β Doc β Doc
exFieldDoc name value | isEmpty value = empty
| otherwise = vcat [text name <> text "=\"", value, char '"']
-- |Render a single-line with potential wrap meta-field of Exheres if non-empty value
exField β· String β String β Doc
exField _ "" = empty
exField name x | length singleLine <= exWrapWidth = text singleLine
| otherwise = exFieldDoc name (reflow exWrapWidth (dquoted x))
where
singleLine = name ++ "=\"" ++ dquoted x ++ "\""
instance ExRender String where
exDisp "" = empty
exDisp s = text s
instance ExRenderQ String where
-- TODO: exDispQ = sep . map text . words . dquoted
exDispQ = text . dquoted
| ony/exherbo-cabal | src/ExRender/Base.hs | gpl-2.0 | 2,524 | 0 | 11 | 620 | 738 | 374 | 364 | 47 | 3 |
{-# LANGUAGE FlexibleContexts #-}
-- |
-- This module contains only function to run 'SpacewalkRPC' code.
-- Bindings can be found in @Spacewalk.Api.*@ modules.
-- As of now they are incomplete, however contributors are welcome.
--
-- If there is unimplemented method, you can use @Spacewalk.ApiInternal@.
--
-- Spacewalk API methods that return @1@ or throw exception
-- in this api return @()@ or throw exception.
module Spacewalk.Api ( runSwAPI, runSwAPI' ) where
import Control.Monad.Reader
import Control.Monad.State
import Spacewalk.ApiTypes
import qualified Spacewalk.Api.Auth as Auth
-- | Run 'SpacewalkRPC' code. Performs authentification for you.
--
-- > main :: IO ()
-- > main = do
-- > [server, user, pass] <- getArgs
-- > runSwAPI server user pass $ do
-- > User.listUsers >>= mapM_ (liftIO . print)
runSwAPI
:: String
-- ^ XML-RPC entrypoint URL (usually @http:\/\/\<FQDN\>\/rpc\/api@).
-> String
-- ^ Login.
-> String
-- ^ Password.
-> SpacewalkRPC a
-> IO a
runSwAPI s u p a = runSwAPI' s u p (Auth.login >> a >>= \ x -> Auth.logout >> return x)
-- | For the rare cases you need to handle authentification yourselves. Otherwise use 'runSwAPI'.
runSwAPI'
:: String
-- ^ XML-RPC entrypoint URL (usually @http:\/\/\<FQDN\>\/rpc\/api@).
-> String
-- ^ Login.
-> String
-- ^ Password.
-> SpacewalkRPC a
-> IO a
runSwAPI' s u p a = fst `fmap` runStateT (runReaderT a re) st where
st = SwS { key = Nothing }
re = SwR { apiurl = s, username = u, password = p }
| xkollar/spacewalk-api-hs | src/Spacewalk/Api.hs | gpl-3.0 | 1,562 | 0 | 10 | 345 | 241 | 144 | 97 | 22 | 1 |
module Utilities.Login.Internal.Cookies where
import qualified Data.Text as T
import Data.Time.Clock
import Web.Cookie
import Web.Scotty.Cookie
import Web.Scotty.Trans
setSimpleCookieExpr :: (Monad m, ScottyError e)
=> T.Text
-> T.Text
-> UTCTime
-> ActionT e m ()
setSimpleCookieExpr n v t = setCookie
((makeSimpleCookie n v) { setCookieExpires = Just t})
| ProLambda/Times | Utilities/Login/Internal/Cookies.hs | gpl-3.0 | 500 | 0 | 10 | 190 | 121 | 69 | 52 | 13 | 1 |
module Frame.Internal.Padding where
import qualified Control.Monad.Except as Except
import qualified Data.Binary.Get as Get
import qualified Data.Binary.Put as Put
import qualified Data.Bits as Bits
import Control.Monad.Except(ExceptT)
import Control.Monad.Trans.Class(lift)
import Data.Binary.Get(Get)
import Data.Binary.Put(Put)
import Data.ByteString.Lazy(ByteString)
import ProjectPrelude
import ErrorCodes
data PaddingDesc = PaddingDesc {
ppLength :: Word8,
ppPadding :: ByteString
} deriving Show
testPadFlag :: FrameFlags -> Bool
testPadFlag = flip Bits.testBit 3
getLength :: FrameLength -> FrameFlags -> ExceptT ConnError Get (FrameLength, Maybe Word8)
getLength len flags =
if testPadFlag flags then
if len >= 1 then
lift $ (,) (len - 1) . Just <$> Get.getWord8
else
Except.throwError $ ConnError ConnectionError ProtocolError
else
return (len, Nothing)
putLength :: Maybe PaddingDesc -> Put
putLength Nothing = return ()
putLength (Just PaddingDesc { ppLength }) = Put.putWord8 ppLength
getPadding :: Maybe Word8 -> Get (Maybe PaddingDesc)
getPadding Nothing = return Nothing
getPadding (Just ppLength) = do
ppPadding <- Get.getLazyByteString (fromIntegral ppLength)
return $ Just $ PaddingDesc { ppLength, ppPadding }
putPadding :: Maybe PaddingDesc -> Put
putPadding Nothing = return ()
putPadding (Just PaddingDesc { ppPadding }) = Put.putLazyByteString ppPadding
| authchir/SoSe17-FFP-haskell-http2-server | src/Frame/Internal/Padding.hs | gpl-3.0 | 1,423 | 0 | 12 | 223 | 441 | 243 | 198 | -1 | -1 |
{-# LANGUAGE ViewPatterns #-}
module Language.Mulang.Analyzer.EdlQueryCompiler(
compileTopQuery) where
import Data.Char (toUpper)
import Data.Count (encode)
import Data.Function.Extra (orElse, andAlso, never)
import Language.Mulang
import Language.Mulang.Consult (Consult)
import Language.Mulang.Counter (plus)
import Language.Mulang.Inspector.Primitive (atLeast, atMost, exactly)
import Language.Mulang.Inspector.Literal (isNil, isNumber, isBool, isChar, isString, isSymbol, isSelf, isLiteral)
import Language.Mulang.Analyzer.Synthesizer (decodeIsInspection, decodeUsageInspection, decodeDeclarationInspection)
import qualified Language.Mulang.Edl.Expectation as E
import Data.Maybe (fromMaybe)
import Data.List.Split (splitOn)
type Scope = (ContextualizedInspection -> ContextualizedInspection, IdentifierPredicate -> IdentifierPredicate)
compileTopQuery :: E.Query -> Inspection
compileTopQuery = fromMaybe (const True) . compileQuery
compileQuery :: E.Query -> Maybe Inspection
compileQuery (E.Decontextualize query) = compileCQuery id query >>= (return . decontextualize)
compileQuery (E.Within name query) | (scope, p) <- compileWithin name = fmap (decontextualize.scope) (compileCQuery p query)
compileQuery (E.Through name query) | (scope, p) <- compileThrough name = fmap (decontextualize.scope) (compileCQuery p query)
compileQuery (E.Not query) = fmap never (compileQuery query)
compileQuery (E.And query1 query2) = andAlso <$> (compileQuery query1) <*> (compileQuery query2)
compileQuery (E.Or query1 query2) = orElse <$> (compileQuery query1) <*> (compileQuery query2)
compileWithin, compileThrough :: String -> Scope
compileWithin name = scopeFor scopedList name
compileThrough name = scopeFor transitiveList name
scopeFor :: ([Identifier] -> Inspection -> Inspection) -> Identifier -> Scope
scopeFor f name = (contextualized (f names), andAlso (except (last names)))
where names = splitOn "." name
compileCQuery :: (IdentifierPredicate -> IdentifierPredicate) -> E.CQuery -> Maybe ContextualizedInspection
compileCQuery pm (E.Inspection i p m) = ($ (compilePredicate pm p)) <$> compileInspection (compileVerb i) m
compileCQuery pm (E.AtLeast n q) = contextualized (atLeast (encode n)) <$> compileTQuery pm q
compileCQuery pm (E.AtMost n q) = contextualized (atMost (encode n)) <$> compileTQuery pm q
compileCQuery pm (E.Exactly n q) = contextualized (exactly (encode n)) <$> compileTQuery pm q
compileCQuery pm (E.CNot q) = contextualized never <$> compileCQuery pm q
compileCQuery pm (E.CAnd q1 q2) = contextualized2 andAlso <$> compileCQuery pm q1 <*> compileCQuery pm q2
compileCQuery pm (E.COr q1 q2) = contextualized2 orElse <$> compileCQuery pm q1 <*> compileCQuery pm q2
compileTQuery :: (IdentifierPredicate -> IdentifierPredicate) -> E.TQuery -> Maybe ContextualizedCounter
compileTQuery pm (E.Counter i p m) = ($ (compilePredicate pm p)) <$> compileCounter (compileVerb i) m
compileTQuery pm (E.Plus q1 q2) = contextualized2 plus <$> (compileTQuery pm q1) <*> (compileTQuery pm q2)
compilePredicate :: (IdentifierPredicate -> IdentifierPredicate) -> E.Predicate -> IdentifierPredicate
compilePredicate p E.Any = p $ anyone
compilePredicate _ (E.Named name) = named name
compilePredicate p (E.Except name) = p $ except name
compilePredicate p (E.Like name) = p $ like name
compilePredicate p (E.Unlike name) = p $ unlike name
compilePredicate _ (E.AnyOf ns) = anyOf ns
compilePredicate p (E.NoneOf ns) = p $ noneOf ns
compilePredicate p (E.LikeAnyOf ns) = p $ likeAnyOf ns
compilePredicate p (E.LikeNoneOf ns) = p $ likeNoneOf ns
compileVerb :: String -> String
compileVerb = concat . map headToUpper . words
where headToUpper (x:xs) = toUpper x : xs
compileCounter :: String -> E.Matcher -> Maybe (ContextualizedBoundCounter)
compileCounter = f
where
f "Calls" m = boundMatching countCalls m
f "DeclaresAttribute" m = boundMatching countAttributes m
f "DeclaresClass" m = boundMatching countClasses m
f "DeclaresFunction" m = boundMatching countFunctions m
f "DeclaresInterface" m = boundMatching countInterfaces m
f "DeclaresMethod" m = boundMatching countMethods m
f "DeclaresObject" m = boundMatching countObjects m
f "DeclaresProcedure" m = boundMatching countProcedures m
f "DeclaresVariable" m = boundMatching countVariables m
f "Returns" m = plainMatching countReturns m
f "Uses" E.Unmatching = bound countUses
f "UsesFor" m = plainMatching countFors m
f "UsesForEach" m = plainMatching countForEaches m
f "UsesForLoop" m = plainMatching countForLoops m
f "UsesIf" m = plainMatching countIfs m
f "UsesLambda" m = plainMatching countLambdas m
f "UsesPrint" m = plainMatching countPrints m
f "UsesRepeat" m = plainMatching countRepeats m
f "UsesSwitch" m = plainMatching countSwitches m
f "UsesWhile" m = plainMatching countWhiles m
f "UsesYield" m = plainMatching countYiels m
f (primitiveUsage -> Just p) E.Unmatching = plain (countUsesPrimitive p)
f _ _ = Nothing
compileInspection :: String -> E.Matcher -> Maybe ContextualizedBoundInspection
compileInspection = f
where
f "Assigns" m = boundMatching assignsMatching m
f "Calls" m = boundMatching callsMatching m
f "Declares" E.Unmatching = bound declares
f "DeclaresAttribute" m = boundMatching declaresAttributeMatching m
f "DeclaresClass" m = boundMatching declaresClassMatching m
f "DeclaresComputation" E.Unmatching = bound declaresComputation
f "DeclaresComputationWithArity0" E.Unmatching = bound (declaresComputationWithArity 0)
f "DeclaresComputationWithArity1" E.Unmatching = bound (declaresComputationWithArity 1)
f "DeclaresComputationWithArity2" E.Unmatching = bound (declaresComputationWithArity 2)
f "DeclaresComputationWithArity3" E.Unmatching = bound (declaresComputationWithArity 3)
f "DeclaresComputationWithArity4" E.Unmatching = bound (declaresComputationWithArity 4)
f "DeclaresComputationWithArity5" E.Unmatching = bound (declaresComputationWithArity 5)
f "DeclaresEntryPoint" m = boundMatching declaresEntryPointMatching m
f "DeclaresEnumeration" E.Unmatching = bound declaresEnumeration
f "DeclaresFact" E.Unmatching = bound declaresFact
f "DeclaresFunction" m = boundMatching declaresFunctionMatching m
f "DeclaresInterface" m = boundMatching declaresInterfaceMatching m
f "DeclaresMethod" m = boundMatching declaresMethodMatching m
f "DeclaresObject" m = boundMatching declaresObjectMatching m
f "DeclaresPredicate" E.Unmatching = bound declaresPredicate
f "DeclaresProcedure" m = boundMatching declaresProcedureMatching m
f "DeclaresRecursively" E.Unmatching = bound declaresRecursively
f "DeclaresRule" E.Unmatching = bound declaresRule
f "DeclaresSuperclass" E.Unmatching = bound declaresSuperclass
f "DeclaresTypeAlias" E.Unmatching = bound declaresTypeAlias
f "DeclaresTypeSignature" E.Unmatching = bound declaresTypeSignature
f "DeclaresVariable" m = boundMatching declaresVariableMatching m
f "Delegates" E.Unmatching = contextualizedBound delegates'
f "Implements" E.Unmatching = bound implements
f "Includes" E.Unmatching = bound includes
f "Inherits" E.Unmatching = bound inherits
f "Instantiates" E.Unmatching = bound instantiates
f "IsClass" E.Unmatching = bound isClass
f "IsDeclaration" E.Unmatching = bound isDeclaration
f "IsFunction" E.Unmatching = bound isFunction
f "IsLValue" E.Unmatching = bound isLValue
f "IsVariable" E.Unmatching = bound isVariable
f "IsNil" E.Unmatching = plain isNil
f "IsSelf" E.Unmatching = plain isSelf
f "IsLiteral" E.Unmatching = plain isLiteral
f "Raises" E.Unmatching = bound raises
f "Rescues" E.Unmatching = bound rescues
f "Returns" m = plainMatching returnsMatching m
f "SubordinatesDeclarationsTo" E.Unmatching = bound subordinatesDeclarationsTo
f "SubordinatesDeclarationsToEntryPoint" E.Unmatching = plain subordinatesDeclarationsToEntryPoint
f "TypesAs" E.Unmatching = bound typesAs
f "TypesParameterAs" E.Unmatching = bound typesParameterAs
f "TypesReturnAs" E.Unmatching = bound typesReturnAs
f "Uses" E.Unmatching = bound uses
f "UsesAnonymousVariable" E.Unmatching = plain usesAnonymousVariable
f "UsesComposition" E.Unmatching = plain usesComposition
f "UsesComprehension" E.Unmatching = f "UsesForComprehension" E.Unmatching
f "UsesConditional" E.Unmatching = plain usesConditional
f "UsesDynamicPolymorphism" E.Unmatching = contextual usesDynamicPolymorphism'
f "UsesDynamicMethodOverload" E.Unmatching = plain usesDynamicMethodOverload
f "UsesExceptionHandling" E.Unmatching = plain usesExceptionHandling
f "UsesExceptions" E.Unmatching = plain usesExceptions
f "UsesFindall" E.Unmatching = plain usesFindall
f "UsesFor" m = plainMatching usesForMatching m
f "UsesForall" E.Unmatching = plain usesForall
f "UsesForComprehension" E.Unmatching = plain usesForComprehension
f "UsesForeach" m = plainMatching usesForEachMatching m
f "UsesForLoop" m = plainMatching usesForLoopMatching m
f "UsesGuards" E.Unmatching = plain usesGuards
f "UsesIf" m = plainMatching usesIfMatching m
f "UsesInheritance" E.Unmatching = plain usesInheritance
f "UsesLambda" m = plainMatching usesLambdaMatching m
f "UsesLogic" E.Unmatching = plain usesLogic
f "UsesLoop" E.Unmatching = plain usesLoop
f "UsesMath" E.Unmatching = plain usesMath
f "UsesMixins" E.Unmatching = plain usesMixins
f "UsesNot" E.Unmatching = plain usesNot
f "UsesObjectComposition" E.Unmatching = plain usesObjectComposition
f "UsesPatternMatching" E.Unmatching = plain usesPatternMatching
f "UsesPrint" m = plainMatching usesPrintMatching m
f "UsesRepeat" m = plainMatching usesRepeatMatching m
f "UsesStaticMethodOverload" E.Unmatching = plain usesStaticMethodOverload
f "UsesStaticPolymorphism" E.Unmatching = contextual usesStaticPolymorphism'
f "UsesSwitch" m = plainMatching usesSwitchMatching m
f "UsesTemplateMethod" E.Unmatching = plain usesTemplateMethod
f "UsesType" E.Unmatching = bound usesType
f "UsesWhile" m = plainMatching usesWhileMatching m
f "UsesYield" m = plainMatching usesYieldMatching m
f (primitiveDeclaration -> Just p) E.Unmatching = plain (declaresPrimitive p)
f (primitiveUsage -> Just p) E.Unmatching = plain (usesPrimitive p)
f (primitiveEssence -> Just p) E.Unmatching = plain (isPrimitive p)
f _ _ = Nothing
primitiveEssence = decodeIsInspection
primitiveUsage = decodeUsageInspection
primitiveDeclaration = decodeDeclarationInspection
contextual :: ContextualizedConsult a -> Maybe (ContextualizedBoundConsult a)
contextual = Just . contextualizedBind
contextualizedBound :: ContextualizedBoundConsult a -> Maybe (ContextualizedBoundConsult a)
contextualizedBound = Just
plain :: Consult a -> Maybe (ContextualizedBoundConsult a)
plain = Just . contextualizedBind . contextualize
bound :: BoundConsult a -> Maybe (ContextualizedBoundConsult a)
bound = Just . boundContextualize
boundMatching :: (Matcher -> BoundConsult a) -> E.Matcher -> Maybe (ContextualizedBoundConsult a)
boundMatching f m = bound (f (compileMatcher m))
plainMatching :: (Matcher -> Consult a) -> E.Matcher -> Maybe (ContextualizedBoundConsult a)
plainMatching f m = plain (f (compileMatcher m))
compileMatcher :: E.Matcher -> Matcher
compileMatcher (E.Matching clauses) = compileClauses clauses
compileMatcher _ = const True
compileClauses :: [E.Clause] -> Matcher
compileClauses = withEvery . f
where
f :: [E.Clause] -> [Inspection]
f (E.IsAnything:args) = isAnything : (f args)
f (E.IsChar value:args) = isChar value : (f args)
f (E.IsFalse:args) = isBool False : (f args)
f (E.IsLiteral:args) = isLiteral : (f args)
f (E.IsLogic:args) = usesLogic : (f args)
f (E.IsMath:args) = usesMath : (f args)
f (E.IsNil:args) = isNil : (f args)
f (E.IsNonliteral:args) = isNonliteral : (f args)
f (E.IsSelf:args) = isSelf : (f args)
f (E.IsTrue:args) = isBool True : (f args)
f (E.IsNumber value:args) = isNumber value : (f args)
f (E.IsString value:args) = isString value : (f args)
f (E.IsSymbol value:args) = isSymbol value : (f args)
f (E.That expectation:args) = compileTopQuery expectation : (f args)
f [] = []
| mumuki/mulang | src/Language/Mulang/Analyzer/EdlQueryCompiler.hs | gpl-3.0 | 14,973 | 0 | 11 | 4,588 | 3,879 | 1,914 | 1,965 | 205 | 87 |
module Mescaline.Sampler.MIDI (
module System.MIDI
, findSources
, findSource
) where
import Control.Exception (PatternMatchFail(..), catch, evaluate)
import Control.Monad (filterM)
import Prelude hiding (catch)
import System.MIDI
findSources :: (String -> String -> String -> Bool) -> IO [Source]
findSources f = filterM p =<< enumerateSources
where
p s = do
s1 <- getManufacturer s
s2 <- getModel s
s3 <- getName s
evaluate (f s1 s2 s3) `catch` (\(PatternMatchFail _) -> return False)
findSource :: (String -> String -> String -> Bool) -> IO (Maybe Source)
findSource f = do
l <- findSources f
case l of
[] -> return Nothing
(s:_) -> return (Just s)
| kaoskorobase/mescaline | tools/sampler/Mescaline/Sampler/MIDI.hs | gpl-3.0 | 750 | 0 | 13 | 203 | 280 | 146 | 134 | 21 | 2 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
module Lamdu.GUI.WidgetIds
( module Lamdu.GUI.WidgetIds
, module Lamdu.GUI.WidgetIdIRef
) where
import Control.Lens.Operators
import Data.ByteString.Char8 (ByteString)
import Data.UUID.Types (UUID)
import qualified Data.UUID.Utils as UUIDUtils
import Graphics.UI.Bottle.Animation (AnimId)
import qualified Graphics.UI.Bottle.Widget as Widget
import Graphics.UI.Bottle.WidgetId (Id(..))
import Lamdu.GUI.WidgetIdIRef
import qualified Lamdu.Sugar.EntityId as EntityId
import qualified Lamdu.Sugar.Types as Sugar
import System.Random.Utils (randFunc)
import Prelude.Compat
fromBS :: ByteString -> Id
fromBS = Id . (: [])
fromEntityId :: Sugar.EntityId -> Id
fromEntityId = fromBS . EntityId.bs
fromExprPayload :: Sugar.Payload m a -> Id
fromExprPayload pl = fromEntityId (pl ^. Sugar.plEntityId)
nameEditOf :: Id -> Id
nameEditOf = delegatingId
fromUUID :: UUID -> Id
fromUUID = fromBS . UUIDUtils.toSBS16
hash :: Show a => a -> Id
hash = fromUUID . randFunc . show
branchSelection :: Id
branchSelection = Id ["selected branch"]
goUpId :: Id
goUpId = Id ["go up"]
parenHighlightId :: AnimId
parenHighlightId = ["paren highlight"]
parensPrefix :: AnimId -> AnimId
parensPrefix = flip mappend ["parens"]
underlineId :: AnimId -> AnimId
underlineId = flip mappend ["underline"]
activePaneBackground :: AnimId
activePaneBackground = ["active def bg"]
flyNav :: AnimId
flyNav = ["flyNav"]
delegatingId :: Id -> Id
delegatingId = flip Widget.joinId ["delegating"]
notDelegatingId :: Id -> Id
notDelegatingId = flip Widget.joinId ["non-delegating"]
| da-x/lamdu | Lamdu/GUI/WidgetIds.hs | gpl-3.0 | 1,702 | 0 | 8 | 310 | 447 | 267 | 180 | 46 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Language.Documents.AnalyzeEntities
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Finds named entities (currently proper names and common nouns) in the
-- text along with entity types, salience, mentions for each entity, and
-- other properties.
--
-- /See:/ <https://cloud.google.com/natural-language/ Cloud Natural Language API Reference> for @language.documents.analyzeEntities@.
module Network.Google.Resource.Language.Documents.AnalyzeEntities
(
-- * REST Resource
DocumentsAnalyzeEntitiesResource
-- * Creating a Request
, documentsAnalyzeEntities
, DocumentsAnalyzeEntities
-- * Request Lenses
, daeXgafv
, daeUploadProtocol
, daeAccessToken
, daeUploadType
, daePayload
, daeCallback
) where
import Network.Google.Language.Types
import Network.Google.Prelude
-- | A resource alias for @language.documents.analyzeEntities@ method which the
-- 'DocumentsAnalyzeEntities' request conforms to.
type DocumentsAnalyzeEntitiesResource =
"v1" :>
"documents:analyzeEntities" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AnalyzeEntitiesRequest :>
Post '[JSON] AnalyzeEntitiesResponse
-- | Finds named entities (currently proper names and common nouns) in the
-- text along with entity types, salience, mentions for each entity, and
-- other properties.
--
-- /See:/ 'documentsAnalyzeEntities' smart constructor.
data DocumentsAnalyzeEntities =
DocumentsAnalyzeEntities'
{ _daeXgafv :: !(Maybe Xgafv)
, _daeUploadProtocol :: !(Maybe Text)
, _daeAccessToken :: !(Maybe Text)
, _daeUploadType :: !(Maybe Text)
, _daePayload :: !AnalyzeEntitiesRequest
, _daeCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DocumentsAnalyzeEntities' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'daeXgafv'
--
-- * 'daeUploadProtocol'
--
-- * 'daeAccessToken'
--
-- * 'daeUploadType'
--
-- * 'daePayload'
--
-- * 'daeCallback'
documentsAnalyzeEntities
:: AnalyzeEntitiesRequest -- ^ 'daePayload'
-> DocumentsAnalyzeEntities
documentsAnalyzeEntities pDaePayload_ =
DocumentsAnalyzeEntities'
{ _daeXgafv = Nothing
, _daeUploadProtocol = Nothing
, _daeAccessToken = Nothing
, _daeUploadType = Nothing
, _daePayload = pDaePayload_
, _daeCallback = Nothing
}
-- | V1 error format.
daeXgafv :: Lens' DocumentsAnalyzeEntities (Maybe Xgafv)
daeXgafv = lens _daeXgafv (\ s a -> s{_daeXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
daeUploadProtocol :: Lens' DocumentsAnalyzeEntities (Maybe Text)
daeUploadProtocol
= lens _daeUploadProtocol
(\ s a -> s{_daeUploadProtocol = a})
-- | OAuth access token.
daeAccessToken :: Lens' DocumentsAnalyzeEntities (Maybe Text)
daeAccessToken
= lens _daeAccessToken
(\ s a -> s{_daeAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
daeUploadType :: Lens' DocumentsAnalyzeEntities (Maybe Text)
daeUploadType
= lens _daeUploadType
(\ s a -> s{_daeUploadType = a})
-- | Multipart request metadata.
daePayload :: Lens' DocumentsAnalyzeEntities AnalyzeEntitiesRequest
daePayload
= lens _daePayload (\ s a -> s{_daePayload = a})
-- | JSONP
daeCallback :: Lens' DocumentsAnalyzeEntities (Maybe Text)
daeCallback
= lens _daeCallback (\ s a -> s{_daeCallback = a})
instance GoogleRequest DocumentsAnalyzeEntities where
type Rs DocumentsAnalyzeEntities =
AnalyzeEntitiesResponse
type Scopes DocumentsAnalyzeEntities =
'["https://www.googleapis.com/auth/cloud-language",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient DocumentsAnalyzeEntities'{..}
= go _daeXgafv _daeUploadProtocol _daeAccessToken
_daeUploadType
_daeCallback
(Just AltJSON)
_daePayload
languageService
where go
= buildClient
(Proxy :: Proxy DocumentsAnalyzeEntitiesResource)
mempty
| brendanhay/gogol | gogol-language/gen/Network/Google/Resource/Language/Documents/AnalyzeEntities.hs | mpl-2.0 | 5,155 | 0 | 16 | 1,139 | 710 | 416 | 294 | 105 | 1 |
module Data.GI.GIR.Arg
( Arg(..)
, Direction(..)
, Scope(..)
, parseArg
, parseTransfer
) where
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.GI.GIR.BasicTypes (Transfer(..), Type)
import Data.GI.GIR.Parser
import Data.GI.GIR.Type (parseType)
data Direction = DirectionIn
| DirectionOut
| DirectionInout
deriving (Show, Eq, Ord)
data Scope = ScopeTypeInvalid
| ScopeTypeCall
| ScopeTypeAsync
| ScopeTypeNotified
deriving (Show, Eq, Ord)
data Arg = Arg {
argCName :: Text, -- ^ "C" name for the argument. For a
-- escaped name valid in Haskell code, use
-- `GI.SymbolNaming.escapedArgName`.
argType :: Type,
direction :: Direction,
mayBeNull :: Bool,
argScope :: Scope,
argClosure :: Int,
argDestroy :: Int,
argCallerAllocates :: Bool,
transfer :: Transfer
} deriving (Show, Eq, Ord)
parseTransfer :: Parser Transfer
parseTransfer = getAttr "transfer-ownership" >>= \case
"none" -> return TransferNothing
"container" -> return TransferContainer
"full" -> return TransferEverything
t -> parseError $ "Unknown transfer type \"" <> t <> "\""
parseScope :: Text -> Parser Scope
parseScope "call" = return ScopeTypeCall
parseScope "async" = return ScopeTypeAsync
parseScope "notified" = return ScopeTypeNotified
parseScope s = parseError $ "Unknown scope type \"" <> s <> "\""
parseDirection :: Text -> Parser Direction
parseDirection "in" = return DirectionIn
parseDirection "out" = return DirectionOut
parseDirection "inout" = return DirectionInout
parseDirection d = parseError $ "Unknown direction \"" <> d <> "\""
parseArg :: Parser Arg
parseArg = do
name <- getAttr "name"
ownership <- parseTransfer
scope <- optionalAttr "scope" ScopeTypeInvalid parseScope
d <- optionalAttr "direction" DirectionIn parseDirection
closure <- optionalAttr "closure" (-1) parseIntegral
destroy <- optionalAttr "destroy" (-1) parseIntegral
nullable <- optionalAttr "nullable" False parseBool
callerAllocates <- optionalAttr "caller-allocates" False parseBool
t <- parseType
return $ Arg { argCName = name
, argType = t
, direction = d
, mayBeNull = nullable
, argScope = scope
, argClosure = closure
, argDestroy = destroy
, argCallerAllocates = callerAllocates
, transfer = ownership
}
| hamishmack/haskell-gi | lib/Data/GI/GIR/Arg.hs | lgpl-2.1 | 2,660 | 0 | 11 | 781 | 628 | 345 | 283 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString.Lazy as BSL
import Data.ByteString.Lazy.UTF8 (toString)
import qualified Data.HashMap.Strict as HMS
import Data.IORef (atomicModifyIORef, modifyIORef',
newIORef, readIORef, writeIORef)
import Data.String (fromString)
import qualified Network.FCP as FCP
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.FilePath (takeDirectory, (</>), makeRelative)
import Text.HTML.TagSoup (fromAttrib, parseTags, (~==))
data State = State
{
fcpConn :: FCP.Connection,
nextId :: Integer
}
extractLinks :: String -> BSL.ByteString -> [ String ]
extractLinks baseUrl bs = links' where
tags = parseTags bs
links = map (fromAttrib "href") $ filter (~== ("<a>" :: String)) tags
links' = map (\l -> baseUrl </> (toString l)) links
data FetchJob = FetchJob
{ uri :: String
}
outBase :: String
outBase = "hspider-store"
main :: IO ()
main = do
putStrLn "hspider starting"
c <- FCP.connect "hspider" "localhost" 9481
todo <- newIORef $ [ startUrl ]
running <- newIORef $ HMS.empty
nextId <- newIORef (1 :: Integer )
let
storeFile url = outBase ++ "/" ++ url
startOne = do
tds <- readIORef todo
case tds of
[] -> putStrLn "nothing to do"
(x:xs) -> do
let
sf = storeFile x
exists <- doesFileExist sf
writeIORef todo xs
if exists
then do
putStrLn $ "already have " ++ x
else do
i <- atomicModifyIORef nextId (\x -> (x + 1, x))
modifyIORef' running (\r -> HMS.insert (show i) x r)
putStrLn $ "starting " ++ x
FCP.sendRequest c $ FCP.ClientGet x (show i)
saveFile url bs = do
let
fname = storeFile url
createDirectoryIfMissing True (takeDirectory fname)
BSL.writeFile fname bs
FCP.processMessages c $ \msg -> case FCP.msgName msg of
"AllData" -> do
case FCP.msgPayload msg of
Nothing -> putStrLn "got AllData without payload?!"
Just bs -> do
case FCP.msgField "Identifier" msg of
Nothing -> putStrLn "got AllData without identifier?!"
Just i -> do
murl <- atomicModifyIORef running (\r -> (HMS.delete i r, HMS.lookup i r))
case murl of
Nothing -> putStrLn $ "could not find download " ++ i
Just url -> do
saveFile url bs
case FCP.msgField "Metadata.ContentType" msg of
Just "text/html" -> do
modifyIORef' todo (\t -> (t ++ extractLinks (takeDirectory url) bs))
startOne
_ -> return ()
return True
_ -> do
-- putStrLn $ show msg
startOne
return True
return ()
| waldheinz/h-fcp | hspider/Main.hs | lgpl-3.0 | 3,567 | 0 | 41 | 1,606 | 883 | 447 | 436 | 77 | 8 |
module Main where
import qualified Data.ByteString.Lazy as B
import Text.VCard.Format.Directory
import System.IO
import System.Environment
import System.Exit
printUsage = putStrLn "vcard2vcard [FILE]" >> exitFailure
main = do
args <- getArgs
(filename, handle) <-
case args of
[file] -> openFile file ReadMode >>= return . ((,) file)
[] -> return ("<stdin>", stdin)
_ -> printUsage
input <- B.hGetContents handle
mapM_ (\v -> B.putStr (writeVCard v) >> B.putStr "\r\n") $ readVCards filename input
| mboes/vCard | t/Main.hs | lgpl-3.0 | 540 | 0 | 14 | 112 | 185 | 98 | 87 | 16 | 3 |
-- Haskell session 5 of block 3
import FP_Core
import FPPrac.Trees
--Exercise 2
codeGenerator :: Expr -> [Instr]
codeGenerator expr = codeGenerator' expr ++ [EndProg]
codeGenerator' (Const n) = [PushConst n]
codeGenerator' (BinExpr op left right) = codeGenerator' left ++ codeGenerator' right ++ [Calc op]
--Exercise 3
ppExpr :: Expr -> RoseTree
ppExpr (Const n) = RoseNode (show n) []
ppExpr (BinExpr op left right) = RoseNode (show op) [ppExpr left, ppExpr right]
--Exercise 4
--
--Exercise 5
codeGenerator2 :: Stmnt -> [Instr]
codeGenerator2 (Assign n expr) = codeGenerator' expr ++ [Store n, EndProg]
--Exercise 6
class CodeGen a where
codeGen :: a -> [Instr]
codeGen' :: a -> [Instr]
pp :: a -> RoseTree
instance CodeGen Expr where
codeGen expr = codeGen' expr ++ [EndProg]
codeGen' (Const n) = [PushConst n]
codeGen' (Var pointer) = [PushAddr pointer]
codeGen' (BinExpr op left right) = codeGen' left ++ codeGen' right ++ [Calc op]
pp (Const n) = RoseNode (show n) []
pp (Var pointer) = RoseNode ("Var " ++ show pointer) []
pp (BinExpr op left right) = RoseNode (show op) [pp left, pp right]
instance CodeGen Stmnt where
codeGen stmnt = codeGen' stmnt ++ [EndProg]
codeGen' (Assign pointer expr) = codeGen' expr ++ [Store pointer]
codeGen' (Repeat expr ss) = [PushPC] ++ codeGen' expr ++ (concat $ map codeGen' ss) ++ [EndRep]
pp (Assign pointer expr) = RoseNode ("Assign " ++ show pointer) [pp expr]
pp (Repeat (Const n) ss) = RoseNode ("Repeat " ++ show n) (map pp ss)
pp (Repeat (Var n) ss) = RoseNode ("Repeat Var" ++ show n) (map pp ss)
pp (Repeat (BinExpr op left right) ss) = RoseNode "Repeat tree" (map pp ss)
--Exercise 7
--
--Exercise 8
repexpr = Repeat (Const 3) [Assign 3 (Const 0), Assign 5 (Const 10), Assign 2 (Var 5)]
repexpr2 = Repeat (Const 3) [Assign 3 (BinExpr Add (Const 0) (Const 1)), Assign 5 (Const 10), Assign 2 (Var 5)]
repexpr3 = Repeat (BinExpr Add (Const 1) (Const 2)) [Assign 3 (BinExpr Add (Const 0) (Const 1)), Assign 5 (Const 10), Assign 2 (Var 5)]
incexpr = Repeat (Const 10) [Assign 0 (BinExpr Add (Var 0) (Const 1)), Assign 1 (BinExpr Add (Var 0) (Var 1))]
incexprb = Repeat (Const 5) [Repeat (Const 2) [Assign 0 (BinExpr Add (Var 0) (Const 1)), Assign 1 (BinExpr Add (Var 0) (Var 1))]]
incexprc = Repeat (Const 3) [Repeat (Const 5) [Repeat (Const 2) [Assign 0 (BinExpr Add (Var 0) (Const 1)), Assign 1 (BinExpr Add (Var 0) (Var 1))]]]
| Pieterjaninfo/PP | FP/block3s5.hs | unlicense | 2,466 | 0 | 15 | 507 | 1,235 | 621 | 614 | 37 | 1 |
-- Copyright 2011 The Text.XHtml Authors.
--
-- 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.
--
-- Contributors:
-- Ian Lynagh <[email protected]>
-- | This module contains functions for displaying
-- HTML as a pretty tree.
module Text.XHtml.Debug ( HtmlTree(..), treeHtml, treeColors, debugHtml ) where
import Text.XHtml.Internals
import Text.XHtml.Extras
import Text.XHtml.Table
import Text.XHtml.Strict.Elements
import Text.XHtml.Strict.Attributes
--
-- * Tree Displaying Combinators
--
-- | The basic idea is you render your structure in the form
-- of this tree, and then use treeHtml to turn it into a Html
-- object with the structure explicit.
data HtmlTree
= HtmlLeaf Html
| HtmlNode Html [HtmlTree] Html
treeHtml :: [String] -> HtmlTree -> Html
treeHtml colors h = table ! [
border 0,
cellpadding 0,
cellspacing 2] << treeHtml' colors h
where
manycolors = scanr (:) []
treeHtmls :: [[String]] -> [HtmlTree] -> HtmlTable
treeHtmls c ts = aboves (zipWith treeHtml' c ts)
treeHtml' :: [String] -> HtmlTree -> HtmlTable
treeHtml' _ (HtmlLeaf leaf) = cell
(td ! [width "100%"]
<< bold
<< leaf)
treeHtml' (c:cs@(c2:_)) (HtmlNode hopen ts hclose) =
if null ts && isNoHtml hclose
then
cell hd
else if null ts
then
hd </> bar `beside` (td ! [bgcolor' c2] << spaceHtml)
</> tl
else
hd </> (bar `beside` treeHtmls morecolors ts)
</> tl
where
-- This stops a column of colors being the same
-- color as the immeduately outside nesting bar.
morecolors = filter ((/= c).head) (manycolors cs)
bar = td ! [bgcolor' c,width "10"] << spaceHtml
hd = td ! [bgcolor' c] << hopen
tl = td ! [bgcolor' c] << hclose
treeHtml' _ _ = error "The imposible happens"
instance HTML HtmlTree where
toHtml x = treeHtml treeColors x
-- type "length treeColors" to see how many colors are here.
treeColors :: [String]
treeColors = ["#88ccff","#ffffaa","#ffaaff","#ccffff"] ++ treeColors
--
-- * Html Debugging Combinators
--
-- | This uses the above tree rendering function, and displays the
-- Html as a tree structure, allowing debugging of what is
-- actually getting produced.
debugHtml :: (HTML a) => a -> Html
debugHtml obj = table ! [border 0] <<
( th ! [bgcolor' "#008888"]
<< underline'
<< "Debugging Output"
</> td << (toHtml (debug' (toHtml obj)))
)
where
debug' :: Html -> [HtmlTree]
debug' (Html markups) = map debug markups
debug :: HtmlElement -> HtmlTree
debug (HtmlString str) = HtmlLeaf (spaceHtml +++
linesToHtml (lines str))
debug (HtmlTag {
markupTag = tag',
markupContent = content',
markupAttrs = attrs
}) =
case content' of
Html [] -> HtmlNode hd [] noHtml
Html xs -> HtmlNode hd (map debug xs) tl
where
args = if null attrs
then ""
else " " ++ unwords (map show attrs)
hd = xsmallFont << ("<" ++ tag' ++ args ++ ">")
tl = xsmallFont << ("</" ++ tag' ++ ">")
bgcolor' :: String -> HtmlAttr
bgcolor' c = thestyle ("background-color:" ++ c)
underline' :: Html -> Html
underline' = thespan ! [thestyle ("text-decoration:underline")]
xsmallFont :: Html -> Html
xsmallFont = thespan ! [thestyle ("font-size:x-small")]
| robinbb/hs-text-xhtml | Text/XHtml/Debug.hs | apache-2.0 | 4,390 | 0 | 15 | 1,461 | 960 | 531 | 429 | 69 | 5 |
import Text.CSV
import Data.List
import Text.Nagato.NagatoIO as NagatoIO
import Text.Nagato.Models as Models
import Text.Nagato.MeCabTools as MeCabTools
import qualified Text.Nagato.Classify as NC
import qualified Text.Nagato.Train as Train
import qualified Text.Nagato.Train_complement as Train_compl
main = do
classes <- NagatoIO.readFromFile "classes.bin"
classesComplement <- NagatoIO.readFromFile "complementClasses.bin"
print $ fst $ unzip classes
print $ fst $ unzip classesComplement
putStrLn "Please type in a sentence:"
sentence <- getLine
wordsWakati <- MeCabTools.parseWakati sentence
let wordsList = words wordsWakati
putStrLn "normal:"
let classified = NC.classify wordsList classes
print classified
putStrLn "complement:"
let classifiedComplement = NC.classifyComplement wordsList classesComplement
print classifiedComplement
| haru2036/nagato | samples/tester_manual.hs | apache-2.0 | 870 | 0 | 11 | 121 | 212 | 107 | 105 | 23 | 1 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Language.Nano.CmdLine (getOpts) where
import Language.Nano.Types (Config (..))
import System.Console.CmdArgs
---------------------------------------------------------------------------------
-- | Parsing Command Line -------------------------------------------------------
---------------------------------------------------------------------------------
esc = Esc {
files = def &= typ "TARGET"
&= args
&= typFile
, incdirs = def &= typDir
&= help "Paths to Spec Include Directory "
} &= help "Extended Static Checker for Nano"
tc = TC {
files = def &= typ "TARGET"
&= args
&= typFile
, incdirs = def &= typDir
&= help "Paths to Spec Include Directory "
} &= help "Type Checker for Nano"
liquid = Liquid {
files = def &= typ "TARGET"
&= args
&= typFile
, incdirs = def &= typDir
&= help "Paths to Spec Include Directory "
} &= help "Refinement Type Checker for Nano"
config = modes [esc, tc, liquid]
&= help "nanojs is a suite of toy program verifiers"
&= program "nanojs"
&= summary "nanojs Β© Copyright 2013 Regents of the University of California."
&= verbosity
&= verbosity
getOpts :: IO Config
getOpts = do md <- cmdArgs config
putStrLn $ banner md
return $ md
banner args = "nanojs Β© Copyright 2013 Regents of the University of California.\n"
++ "All Rights Reserved.\n"
++ "nanojs" ++ show args ++ "\n"
| UCSD-PL/nano-js | Language/Nano/CmdLine.hs | bsd-3-clause | 1,787 | 0 | 11 | 612 | 307 | 162 | 145 | 39 | 1 |
module Data.RecordAccess (
set,
update,
Ref,
ref,
(.)
) where
import Prelude hiding ((.))
import qualified Prelude
data FRef s a = FRef
{ get :: s -> a
, set :: a -> s -> s
}
update :: FRef s a -> (a -> a) -> (s -> s)
update ref f s = set ref (f (get ref s)) s
compose :: FRef b c -> FRef a b -> FRef a c
compose bc ab = FRef
{ get = get bc . get ab
, set = update ab . set bc
}
class Ref r where
ref :: (a -> b) -> (b -> a -> a) -> r a b
(.) :: r b c -> r a b -> r a c
instance Ref FRef where
ref = FRef
(.) = compose
instance Ref (->) where
ref = const
(.) = (Prelude..) | petermarks/record-access | src/Data/RecordAccess.hs | bsd-3-clause | 659 | 0 | 11 | 236 | 334 | 184 | 150 | 26 | 1 |
{-# LANGUAGE LambdaCase #-}
module GLObjects where
import Codec.Picture
import Control.Arrow
import Control.Monad
import Control.Monad.Trans.State.Strict (State, runState, gets, modify)
import Data.Foldable
import Data.Functor.Contravariant
import Data.Functor.Contravariant.Divisible
import Data.Maybe (catMaybes)
import Data.Monoid
import Data.Text (Text, unpack)
import Data.Traversable
import Foreign
import Foreign.C
import Graphics.GL.ARB.DirectStateAccess
import Graphics.GL.ARB.SeparateShaderObjects
import Graphics.GL.Core33
import Linear
import qualified Codec.Wavefront as Wavefront
import qualified Data.Map.Strict as Map
import qualified Data.Text.IO as T
import qualified Data.Vector as V
import qualified Data.Vector.Storable as SV
newtype Texture =
Texture {textureName :: GLuint}
deriving (Eq, Ord)
newTexture2D
:: GLsizei -> GLenum -> GLsizei -> GLsizei -> IO Texture
newTexture2D levels internalFormat width height =
do name <-
create (glCreateTextures GL_TEXTURE_2D)
glTextureStorage2D name levels internalFormat width height
pure (Texture name)
uploadTexture2D :: (Foldable t,Storable a)
=> t [a] -> IO Texture
uploadTexture2D pixels =
do t <- newTexture2D 1 GL_RGBA32F 4 4
glPixelStorei GL_UNPACK_LSB_FIRST 0
glPixelStorei GL_UNPACK_SWAP_BYTES 0
glPixelStorei GL_UNPACK_ROW_LENGTH 0
glPixelStorei GL_UNPACK_IMAGE_HEIGHT 0
glPixelStorei GL_UNPACK_SKIP_ROWS 0
glPixelStorei GL_UNPACK_SKIP_PIXELS 0
glPixelStorei GL_UNPACK_SKIP_IMAGES 0
glPixelStorei GL_UNPACK_ALIGNMENT 1
withArray (concat pixels)
(glTextureSubImage2D (textureName t)
0
0
0
4
4
GL_RGBA
GL_FLOAT .
castPtr)
pure t
loadTexture :: FilePath -> IO Texture
loadTexture filePath =
do res <- readImage filePath
t <-
case res of
Left e -> error e
Right img ->
case img of
ImageY8 _ -> error "ImageY8"
ImageY16 _ -> error "(Image Pixel16)"
ImageYF _ -> error "(Image PixelF)"
ImageYA8 _ -> error "(Image PixelYA8)"
ImageYA16 _ -> error "(Image PixelYA16)"
ImageRGB16 _ -> error "(Image PixelRGB16)"
ImageRGBF _ -> error "(Image PixelRGBF)"
ImageYCbCr8 _ -> error "(Image PixelYCbCr8)"
ImageCMYK8 _ -> error "(Image PixelCMYK8)"
ImageCMYK16 _ -> error "(Image PixelCMYK16)"
ImageRGBA8 (Image width height pixels) ->
do t <-
newTexture2D (floor (logBase 2 (fromIntegral (max width height))))
GL_SRGB8
(fromIntegral width)
(fromIntegral height)
SV.unsafeWith
pixels
(glTextureSubImage2D (textureName t)
0
0
0
(fromIntegral width)
(fromIntegral height)
GL_RGBA
GL_UNSIGNED_BYTE .
castPtr)
pure t
ImageRGB8 (Image width height pixels) ->
do t <-
newTexture2D (floor (logBase 2 (fromIntegral (max width height))))
GL_SRGB8
(fromIntegral width)
(fromIntegral height)
SV.unsafeWith
pixels
(glTextureSubImage2D (textureName t)
0
0
0
(fromIntegral width)
(fromIntegral height)
GL_RGB
GL_UNSIGNED_BYTE .
castPtr)
return t
glActiveTexture GL_TEXTURE1 -- https://bugs.freedesktop.org/show_bug.cgi?id=91847
glGenerateTextureMipmap (textureName t)
glTextureParameteri (textureName t)
GL_TEXTURE_MIN_FILTER
(fromIntegral GL_LINEAR_MIPMAP_LINEAR)
glTextureParameteri (textureName t)
GL_TEXTURE_MAG_FILTER
(fromIntegral GL_LINEAR)
pure t
newtype Renderbuffer =
Renderbuffer {renderbufferName :: GLuint}
deriving (Eq, Ord)
newRenderbuffer :: GLenum -> GLsizei -> GLsizei -> IO Renderbuffer
newRenderbuffer internalFormat width height =
do name <- create glCreateRenderbuffers
glNamedRenderbufferStorage name internalFormat width height
pure (Renderbuffer name)
newtype Framebuffer =
Framebuffer {framebufferName :: GLuint}
deriving (Eq, Ord)
data AttachTo
= AttachToTexture Texture
GLint
| AttachToRenderbuffer Renderbuffer
data FramebufferAttachment
= ColorAttachment GLenum
| DepthAttachment
| StencilAttachment
attachmentForGL :: FramebufferAttachment -> GLenum
attachmentForGL (ColorAttachment n) = GL_COLOR_ATTACHMENT0 + fromIntegral n
attachmentForGL DepthAttachment = GL_DEPTH_ATTACHMENT
attachmentForGL StencilAttachment = GL_STENCIL_ATTACHMENT
newFramebuffer
:: (FramebufferAttachment -> Maybe AttachTo) -> IO Framebuffer
newFramebuffer f =
do name <- create glCreateFramebuffers
maxColorAttachments <-
alloca (\ptr ->
glGetIntegerv GL_MAX_COLOR_ATTACHMENTS ptr *> peek ptr)
for_ (DepthAttachment :
StencilAttachment :
map ColorAttachment [0 .. fromIntegral maxColorAttachments - 1])
(\attachment ->
for_ (f attachment)
(\case
AttachToTexture (Texture t) level ->
glNamedFramebufferTexture name
(attachmentForGL attachment)
t
level
AttachToRenderbuffer (Renderbuffer rb) ->
glNamedFramebufferRenderbuffer name
(attachmentForGL attachment)
GL_RENDERBUFFER
rb))
status <-
glCheckNamedFramebufferStatus name GL_FRAMEBUFFER
putStrLn (case status of
GL_FRAMEBUFFER_UNDEFINED -> "Framebuffer undefined"
GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT -> "Incomplete attachment"
GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT -> "Missing attachment"
GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER -> "Incomplete draw buffer"
GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER -> "Incomplete read buffer"
GL_FRAMEBUFFER_UNSUPPORTED -> "Unsupported"
GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE -> "Incomplete multisample"
GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS -> "Incomplete layer targets"
GL_FRAMEBUFFER_COMPLETE -> "Complete"
_ -> "Unknown status")
pure (Framebuffer name)
data StageSource
= VertexShader
| FragmentShader
deriving (Show)
glShaderStage :: StageSource -> GLenum
glShaderStage VertexShader = GL_VERTEX_SHADER
glShaderStage FragmentShader = GL_FRAGMENT_SHADER
newtype Program =
Program {programName :: GLuint}
deriving (Eq, Ord)
newProgram
:: (StageSource -> Maybe Text) -> IO Program
newProgram f =
do name <- glCreateProgram
shaders <-
for [VertexShader,FragmentShader]
(\stage ->
for (f stage)
(\src ->
do shaderName <-
glCreateShader (glShaderStage stage)
withCString
(unpack src)
(\srcPtr ->
withArray [srcPtr]
(\srcs ->
glShaderSource shaderName 1 srcs nullPtr))
glCompileShader shaderName
compiled <-
alloca (\ptr ->
glGetShaderiv shaderName GL_COMPILE_STATUS ptr *>
peek ptr)
unless (fromIntegral compiled == GL_TRUE)
(do putStrLn ("Shader stage failed to compile: " <>
show stage)
T.putStrLn src
logLen <-
alloca (\ptr ->
glGetShaderiv shaderName GL_INFO_LOG_LENGTH ptr *>
peek ptr)
allocaBytes (fromIntegral logLen) $
\infoLogPtr ->
alloca $
\lenPtr ->
do glGetShaderInfoLog shaderName 1024 lenPtr infoLogPtr
peekCString infoLogPtr >>= putStrLn)
glAttachShader name shaderName
pure shaderName))
withCString "a_position"
(glBindAttribLocation name attribPosition)
withCString "a_normal"
(glBindAttribLocation name attribNormal)
withCString "a_uv"
(glBindAttribLocation name attribUV)
glLinkProgram name
compiled <-
alloca (\ptr ->
glGetProgramiv name GL_LINK_STATUS ptr *> peek ptr)
unless (fromIntegral compiled == GL_TRUE)
(do putStrLn "Program failed to link"
logLen <-
alloca (\ptr ->
glGetProgramiv name GL_INFO_LOG_LENGTH ptr *>
peek ptr)
allocaBytes (fromIntegral logLen) $
\infoLogPtr ->
alloca $
\lenPtr ->
do glGetProgramInfoLog name 1024 lenPtr infoLogPtr
peekCString infoLogPtr >>= putStrLn)
for_ (catMaybes shaders) (glDetachShader name)
pure (Program name)
create :: (Num a,Storable b)
=> (a -> Ptr b -> IO c) -> IO b
create m = alloca (\ptr -> m 1 ptr *> peek ptr)
attribPosition, attribNormal, attribUV :: GLuint
attribPosition = 0
attribNormal = 1
attribUV = 2
newtype VertexArrayObject =
VertexArrayObject {vertexArrayObjectName :: GLuint}
deriving (Eq, Ord)
newtype UniformSetter a =
UniformSetter {setUniform :: Program -> String -> a -> IO ()}
m44 :: UniformSetter (M44 Float)
m44 =
UniformSetter
(\(Program p) uniform value ->
do uView <-
withCString uniform
(glGetUniformLocation p)
with value
(glProgramUniformMatrix4fv p
uView
1
(fromIntegral GL_TRUE) .
castPtr))
v4Array :: UniformSetter [V4 Float]
v4Array =
UniformSetter
(\(Program p) uniform value ->
do location <-
withCString uniform
(glGetUniformLocation p)
withArray value
(glProgramUniform4fv p
location
(fromIntegral (length value)) .
castPtr))
textureUnit :: UniformSetter GLint
textureUnit =
UniformSetter
(\(Program p) uniform value ->
do location <-
withCString uniform
(glGetUniformLocation p)
glProgramUniform1i p location value)
data Vertex =
Vertex (V3 Float)
(V3 Float)
(V2 Float)
deriving (Show, Eq, Ord)
objVertexAttribs :: VertexAttrib Vertex
objVertexAttribs =
divide (\(Vertex a b c) -> (a,(b,c)))
position
(divided normal uv)
loadObj :: FilePath -> IO VertexArrayObject
loadObj objPath =
do obj <-
fmap (either error id)
(Wavefront.fromFile objPath)
let mkVertex fi =
Vertex (case Wavefront.objLocations obj V.!
pred (Wavefront.faceLocIndex fi) of
Wavefront.Location x y z _ -> fmap realToFrac (V3 x y z))
(case Wavefront.faceNorIndex fi of
Just i ->
case Wavefront.objNormals obj V.! pred i of
Wavefront.Normal x y z -> fmap realToFrac (V3 x y z)
Nothing -> 0)
(case Wavefront.faceTexCoordIndex fi of
Just i ->
case Wavefront.objTexCoords obj V.! pred i of
Wavefront.TexCoord u v _ ->
fmap realToFrac (V2 u (1 - v))
Nothing -> 0)
objTriangles =
concatMap (\case
Wavefront.Triangle a b c -> [map mkVertex [a,b,c]]
Wavefront.Quad a b c d ->
[map mkVertex [a,b,c],map mkVertex [a,c,d]]
faces -> error (show faces)) $
(fmap Wavefront.elValue (Wavefront.objFaces obj))
uploadTriangles objVertexAttribs objTriangles
loadVertexFragmentProgram :: FilePath -> FilePath -> IO Program
loadVertexFragmentProgram vs fs =
do do depthVS <- T.readFile vs
depthFS <- T.readFile fs
newProgram
(\case
VertexShader -> Just depthVS
FragmentShader -> Just depthFS)
data Attribute = Position | Normal | UV
data VertexAttrib a =
VertexAttrib {vertexAttribSize :: GLuint
,vertexAttribPoke :: Ptr a -> a -> IO ()
,vertexAttribFormat :: [(Attribute,GLint,GLenum,GLenum,GLuint)]}
instance Contravariant VertexAttrib where
contramap f (VertexAttrib sz poke_ fmt) =
VertexAttrib
sz
(\ptr v ->
poke_ (castPtr ptr)
(f v))
fmt
instance Divisible VertexAttrib where
conquer =
VertexAttrib 0
(\_ _ -> return ())
[]
divide f fb fc =
VertexAttrib {vertexAttribSize = vertexAttribSize fb + vertexAttribSize fc
,vertexAttribPoke =
\ptr a ->
do let (b,c) = f a
vertexAttribPoke fb
(castPtr ptr)
b
vertexAttribPoke
fc
(castPtr ptr `plusPtr`
fromIntegral (vertexAttribSize fb))
c
,vertexAttribFormat =
vertexAttribFormat fb <>
(map (\(a,b,c,d,e) ->
(a,b,c,d,e + vertexAttribSize fb))
(vertexAttribFormat fc))}
position :: VertexAttrib (V3 Float)
position =
VertexAttrib {vertexAttribSize =
fromIntegral (sizeOf (0 :: V3 Float))
,vertexAttribPoke = poke
,vertexAttribFormat =
[(Position,3,GL_FLOAT,GL_FALSE,0)]}
normal :: VertexAttrib (V3 Float)
normal =
VertexAttrib {vertexAttribSize =
fromIntegral (sizeOf (0 :: V3 Float))
,vertexAttribPoke = poke
,vertexAttribFormat =
[(Normal,3,GL_FLOAT,GL_FALSE,0)]}
uv :: VertexAttrib (V2 Float)
uv =
VertexAttrib {vertexAttribSize =
fromIntegral (sizeOf (0 :: V2 Float))
,vertexAttribPoke = poke
,vertexAttribFormat =
[(UV,2,GL_FLOAT,GL_FALSE,0)]}
uploadTriangles
:: Ord v
=> VertexAttrib v -> [[v]] -> IO VertexArrayObject
uploadTriangles attribs triangles =
do let sizeInBytes =
fromIntegral (vertexAttribSize attribs) * length vertices
buffer <- mallocBytes sizeInBytes
sequence_ (zipWith (\v offset ->
vertexAttribPoke
attribs
(buffer `plusPtr` fromIntegral offset)
v)
vertices
(iterate (+ vertexAttribSize attribs) 0))
vbo <- create glCreateBuffers
glNamedBufferData vbo
(fromIntegral sizeInBytes)
buffer
GL_STATIC_DRAW
vao <- create glCreateVertexArrays
let bindingIndex = 0
glVertexArrayVertexBuffer vao
bindingIndex
vbo
0
(fromIntegral (vertexAttribSize attribs))
for_ (vertexAttribFormat attribs)
(\(attribTy,components,compTy,normalized,offset) ->
do let attribIndex =
case attribTy of
Position -> attribPosition
Normal -> attribNormal
UV -> attribUV
glEnableVertexArrayAttrib vao attribIndex
glVertexArrayAttribBinding vao attribIndex bindingIndex
glVertexArrayAttribFormat vao
attribIndex
components
compTy
(fromIntegral normalized)
offset)
ebo <- create glCreateBuffers
withArray indices
(\ptr ->
glNamedBufferData
ebo
(fromIntegral (length indices * sizeOf (0 :: GLuint)))
ptr
GL_STATIC_DRAW)
glVertexArrayElementBuffer vao ebo
pure (VertexArrayObject vao)
where (indices,vertices) =
let (indices,(_,vertices)) =
runState (traverse dedupVertex dat)
(mempty,mempty)
in (indices,V.toList vertices)
dedupVertex
:: Ord v
=> v -> State (Map.Map v GLuint,V.Vector v) GLuint
dedupVertex v =
do vertices <- gets fst
case Map.lookup v vertices of
Just index -> pure index
Nothing ->
do let i = fromIntegral (Map.size vertices)
modify (Map.insert v i *** flip V.snoc v)
pure i
dat =
[v | tri <- triangles
, v <- tri]
| ocharles/SSAO-example | src/GLObjects.hs | bsd-3-clause | 19,273 | 0 | 27 | 8,355 | 4,283 | 2,141 | 2,142 | 470 | 13 |
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}
module Github.Data.Definitions where
import Control.DeepSeq (NFData)
import Data.Time
import Data.Data
import GHC.Generics (Generic)
import qualified Control.Exception as E
import qualified Data.Map as M
-- | The options for querying commits.
data CommitQueryOption = CommitQuerySha String
| CommitQueryPath String
| CommitQueryAuthor String
| CommitQuerySince GithubDate
| CommitQueryUntil GithubDate
deriving (Show, Eq, Ord)
-- | Errors have been tagged according to their source, so you can more easily
-- dispatch and handle them.
data Error =
HTTPConnectionError E.SomeException -- ^ A HTTP error occurred. The actual caught error is included.
| ParseError String -- ^ An error in the parser itself.
| JsonError String -- ^ The JSON is malformed or unexpected.
| UserError String -- ^ Incorrect input.
deriving Show
-- | A date in the Github format, which is a special case of ISO-8601.
newtype GithubDate = GithubDate { fromGithubDate :: UTCTime }
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GithubDate
data Commit = Commit {
commitSha :: String
,commitParents :: [Tree]
,commitUrl :: String
,commitGitCommit :: GitCommit
,commitCommitter :: Maybe GithubOwner
,commitAuthor :: Maybe GithubOwner
,commitFiles :: [File]
,commitStats :: Maybe Stats
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Commit
data Tree = Tree {
treeSha :: String
,treeUrl :: String
,treeGitTrees :: [GitTree]
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Tree
data GitTree = GitTree {
gitTreeType :: String
,gitTreeSha :: String
-- Can be empty for submodule
,gitTreeUrl :: Maybe String
,gitTreeSize :: Maybe Int
,gitTreePath :: String
,gitTreeMode :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GitTree
data GitCommit = GitCommit {
gitCommitMessage :: String
,gitCommitUrl :: String
,gitCommitCommitter :: GitUser
,gitCommitAuthor :: GitUser
,gitCommitTree :: Tree
,gitCommitSha :: Maybe String
,gitCommitParents :: [Tree]
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GitCommit
data GithubOwner = GithubUser {
githubOwnerAvatarUrl :: String
,githubOwnerLogin :: String
,githubOwnerUrl :: String
,githubOwnerId :: Int
,githubOwnerGravatarId :: Maybe String
}
| GithubOrganization {
githubOwnerAvatarUrl :: String
,githubOwnerLogin :: String
,githubOwnerUrl :: String
,githubOwnerId :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GithubOwner
data GitUser = GitUser {
gitUserName :: String
,gitUserEmail :: String
,gitUserDate :: GithubDate
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GitUser
data File = File {
fileBlobUrl :: String
,fileStatus :: String
,fileRawUrl :: String
,fileAdditions :: Int
,fileSha :: String
,fileChanges :: Int
,filePatch :: String
,fileFilename :: String
,fileDeletions :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData File
data Stats = Stats {
statsAdditions :: Int
,statsTotal :: Int
,statsDeletions :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Stats
data Comment = Comment {
commentPosition :: Maybe Int
,commentLine :: Maybe Int
,commentBody :: String
,commentCommitId :: Maybe String
,commentUpdatedAt :: UTCTime
,commentHtmlUrl :: Maybe String
,commentUrl :: String
,commentCreatedAt :: Maybe UTCTime
,commentPath :: Maybe String
,commentUser :: GithubOwner
,commentId :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Comment
data NewComment = NewComment {
newCommentBody :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData NewComment
data EditComment = EditComment {
editCommentBody :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData EditComment
data Diff = Diff {
diffStatus :: String
,diffBehindBy :: Int
,diffPatchUrl :: String
,diffUrl :: String
,diffBaseCommit :: Commit
,diffCommits :: [Commit]
,diffTotalCommits :: Int
,diffHtmlUrl :: String
,diffFiles :: [File]
,diffAheadBy :: Int
,diffDiffUrl :: String
,diffPermalinkUrl :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Diff
data Gist = Gist {
gistUser :: GithubOwner
,gistGitPushUrl :: String
,gistUrl :: String
,gistDescription :: Maybe String
,gistCreatedAt :: GithubDate
,gistPublic :: Bool
,gistComments :: Int
,gistUpdatedAt :: GithubDate
,gistHtmlUrl :: String
,gistId :: String
,gistFiles :: [GistFile]
,gistGitPullUrl :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Gist
data GistFile = GistFile {
gistFileType :: String
,gistFileRawUrl :: String
,gistFileSize :: Int
,gistFileLanguage :: Maybe String
,gistFileFilename :: String
,gistFileContent :: Maybe String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GistFile
data GistComment = GistComment {
gistCommentUser :: GithubOwner
,gistCommentUrl :: String
,gistCommentCreatedAt :: GithubDate
,gistCommentBody :: String
,gistCommentUpdatedAt :: GithubDate
,gistCommentId :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GistComment
data Blob = Blob {
blobUrl :: String
,blobEncoding :: String
,blobContent :: String
,blobSha :: String
,blobSize :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Blob
data NewGitReference = NewGitReference {
newGitReferenceRef :: String
,newGitReferenceSha :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData NewGitReference
data GitReference = GitReference {
gitReferenceObject :: GitObject
,gitReferenceUrl :: String
,gitReferenceRef :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GitReference
data GitObject = GitObject {
gitObjectType :: String
,gitObjectSha :: String
,gitObjectUrl :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData GitObject
data Issue = Issue {
issueClosedAt :: Maybe GithubDate
,issueUpdatedAt :: GithubDate
,issueEventsUrl :: String
,issueHtmlUrl :: Maybe String
,issueClosedBy :: Maybe GithubOwner
,issueLabels :: [IssueLabel]
,issueNumber :: Int
,issueAssignee :: Maybe GithubOwner
,issueUser :: GithubOwner
,issueTitle :: String
,issuePullRequest :: Maybe PullRequestReference
,issueUrl :: String
,issueCreatedAt :: GithubDate
,issueBody :: Maybe String
,issueState :: String
,issueId :: Int
,issueComments :: Int
,issueMilestone :: Maybe Milestone
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Issue
data NewIssue = NewIssue {
newIssueTitle :: String
, newIssueBody :: Maybe String
, newIssueAssignee :: Maybe String
, newIssueMilestone :: Maybe Int
, newIssueLabels :: Maybe [String]
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData NewIssue
data EditIssue = EditIssue {
editIssueTitle :: Maybe String
, editIssueBody :: Maybe String
, editIssueAssignee :: Maybe String
, editIssueState :: Maybe String
, editIssueMilestone :: Maybe Int
, editIssueLabels :: Maybe [String]
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData EditIssue
data Milestone = Milestone {
milestoneCreator :: GithubOwner
,milestoneDueOn :: Maybe GithubDate
,milestoneOpenIssues :: Int
,milestoneNumber :: Int
,milestoneClosedIssues :: Int
,milestoneDescription :: Maybe String
,milestoneTitle :: String
,milestoneUrl :: String
,milestoneCreatedAt :: GithubDate
,milestoneState :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Milestone
data IssueLabel = IssueLabel {
labelColor :: String
,labelUrl :: String
,labelName :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData IssueLabel
data PullRequestReference = PullRequestReference {
pullRequestReferenceHtmlUrl :: Maybe String
,pullRequestReferencePatchUrl :: Maybe String
,pullRequestReferenceDiffUrl :: Maybe String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData PullRequestReference
data IssueComment = IssueComment {
issueCommentUpdatedAt :: GithubDate
,issueCommentUser :: GithubOwner
,issueCommentUrl :: String
,issueCommentHtmlUrl :: String
,issueCommentCreatedAt :: GithubDate
,issueCommentBody :: String
,issueCommentId :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData IssueComment
-- | Data describing an @Event@.
data EventType =
Mentioned -- ^ The actor was @mentioned in an issue body.
| Subscribed -- ^ The actor subscribed to receive notifications for an issue.
| Unsubscribed -- ^ The issue was unsubscribed from by the actor.
| Referenced -- ^ The issue was referenced from a commit message. The commit_id attribute is the commit SHA1 of where that happened.
| Merged -- ^ The issue was merged by the actor. The commit_id attribute is the SHA1 of the HEAD commit that was merged.
| Assigned -- ^ The issue was assigned to the actor.
| Closed -- ^ The issue was closed by the actor. When the commit_id is present, it identifies the commit that closed the issue using βcloses / fixes #NNβ syntax.
| Reopened -- ^ The issue was reopened by the actor.
| ActorUnassigned -- ^ The issue was unassigned to the actor
| Labeled -- ^ A label was added to the issue.
| Unlabeled -- ^ A label was removed from the issue.
| Milestoned -- ^ The issue was added to a milestone.
| Demilestoned -- ^ The issue was removed from a milestone.
| Renamed -- ^ The issue title was changed.
| Locked -- ^ The issue was locked by the actor.
| Unlocked -- ^ The issue was unlocked by the actor.
| HeadRefDeleted -- ^ The pull requestβs branch was deleted.
| HeadRefRestored -- ^ The pull requestβs branch was restored.
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData EventType
data Event = Event {
eventActor :: GithubOwner
,eventType :: EventType
,eventCommitId :: Maybe String
,eventUrl :: String
,eventCreatedAt :: GithubDate
,eventId :: Int
,eventIssue :: Maybe Issue
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Event
data SimpleOrganization = SimpleOrganization {
simpleOrganizationUrl :: String
,simpleOrganizationAvatarUrl :: String
,simpleOrganizationId :: Int
,simpleOrganizationLogin :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData SimpleOrganization
data Organization = Organization {
organizationType :: String
,organizationBlog :: Maybe String
,organizationLocation :: Maybe String
,organizationLogin :: String
,organizationFollowers :: Int
,organizationCompany :: Maybe String
,organizationAvatarUrl :: String
,organizationPublicGists :: Int
,organizationHtmlUrl :: String
,organizationEmail :: Maybe String
,organizationFollowing :: Int
,organizationPublicRepos :: Int
,organizationUrl :: String
,organizationCreatedAt :: GithubDate
,organizationName :: Maybe String
,organizationId :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Organization
data PullRequest = PullRequest {
pullRequestClosedAt :: Maybe GithubDate
,pullRequestCreatedAt :: GithubDate
,pullRequestUser :: GithubOwner
,pullRequestPatchUrl :: String
,pullRequestState :: String
,pullRequestNumber :: Int
,pullRequestHtmlUrl :: String
,pullRequestUpdatedAt :: GithubDate
,pullRequestBody :: String
,pullRequestIssueUrl :: String
,pullRequestDiffUrl :: String
,pullRequestUrl :: String
,pullRequestLinks :: PullRequestLinks
,pullRequestMergedAt :: Maybe GithubDate
,pullRequestTitle :: String
,pullRequestId :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData PullRequest
data DetailedPullRequest = DetailedPullRequest {
-- this is a duplication of a PullRequest
detailedPullRequestClosedAt :: Maybe GithubDate
,detailedPullRequestCreatedAt :: GithubDate
,detailedPullRequestUser :: GithubOwner
,detailedPullRequestPatchUrl :: String
,detailedPullRequestState :: String
,detailedPullRequestNumber :: Int
,detailedPullRequestHtmlUrl :: String
,detailedPullRequestUpdatedAt :: GithubDate
,detailedPullRequestBody :: String
,detailedPullRequestIssueUrl :: String
,detailedPullRequestDiffUrl :: String
,detailedPullRequestUrl :: String
,detailedPullRequestLinks :: PullRequestLinks
,detailedPullRequestMergedAt :: Maybe GithubDate
,detailedPullRequestTitle :: String
,detailedPullRequestId :: Int
,detailedPullRequestMergedBy :: Maybe GithubOwner
,detailedPullRequestChangedFiles :: Int
,detailedPullRequestHead :: PullRequestCommit
,detailedPullRequestComments :: Int
,detailedPullRequestDeletions :: Int
,detailedPullRequestAdditions :: Int
,detailedPullRequestReviewComments :: Int
,detailedPullRequestBase :: PullRequestCommit
,detailedPullRequestCommits :: Int
,detailedPullRequestMerged :: Bool
,detailedPullRequestMergeable :: Maybe Bool
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData DetailedPullRequest
data EditPullRequest = EditPullRequest {
editPullRequestTitle :: Maybe String
,editPullRequestBody :: Maybe String
,editPullRequestState :: Maybe EditPullRequestState
} deriving (Show, Generic)
instance NFData EditPullRequest
data CreatePullRequest =
CreatePullRequest
{ createPullRequestTitle :: String
, createPullRequestBody :: String
, createPullRequestHead :: String
, createPullRequestBase :: String
}
| CreatePullRequestIssue
{ createPullRequestIssueNum :: Int
, createPullRequestHead :: String
, createPullRequestBase :: String
}
deriving (Show, Generic)
instance NFData CreatePullRequest
data PullRequestLinks = PullRequestLinks {
pullRequestLinksReviewComments :: String
,pullRequestLinksComments :: String
,pullRequestLinksHtml :: String
,pullRequestLinksSelf :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData PullRequestLinks
data PullRequestCommit = PullRequestCommit {
pullRequestCommitLabel :: String
,pullRequestCommitRef :: String
,pullRequestCommitSha :: String
,pullRequestCommitUser :: GithubOwner
,pullRequestCommitRepo :: Repo
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData PullRequestCommit
data SearchReposResult = SearchReposResult {
searchReposTotalCount :: Int
,searchReposRepos :: [Repo]
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData SearchReposResult
data Repo = Repo {
repoSshUrl :: Maybe String
,repoDescription :: Maybe String
,repoCreatedAt :: Maybe GithubDate
,repoHtmlUrl :: String
,repoSvnUrl :: Maybe String
,repoForks :: Maybe Int
,repoHomepage :: Maybe String
,repoFork :: Maybe Bool
,repoGitUrl :: Maybe String
,repoPrivate :: Bool
,repoCloneUrl :: Maybe String
,repoSize :: Maybe Int
,repoUpdatedAt :: Maybe GithubDate
,repoWatchers :: Maybe Int
,repoOwner :: GithubOwner
,repoName :: String
,repoLanguage :: Maybe String
,repoMasterBranch :: Maybe String
,repoPushedAt :: Maybe GithubDate -- ^ this is Nothing for new repositories
,repoId :: Int
,repoUrl :: String
,repoOpenIssues :: Maybe Int
,repoHasWiki :: Maybe Bool
,repoHasIssues :: Maybe Bool
,repoHasDownloads :: Maybe Bool
,repoParent :: Maybe RepoRef
,repoSource :: Maybe RepoRef
,repoHooksUrl :: String
,repoStargazersCount :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Repo
data RepoRef = RepoRef GithubOwner String -- Repo owner and name
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData RepoRef
data SearchCodeResult = SearchCodeResult {
searchCodeTotalCount :: Int
,searchCodeCodes :: [Code]
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData SearchCodeResult
data Code = Code {
codeName :: String
,codePath :: String
,codeSha :: String
,codeUrl :: String
,codeGitUrl :: String
,codeHtmlUrl :: String
,codeRepo :: Repo
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Code
data Content
= ContentFile ContentFileData
| ContentDirectory [ContentItem]
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Content
data ContentFileData = ContentFileData {
contentFileInfo :: ContentInfo
,contentFileEncoding :: String
,contentFileSize :: Int
,contentFileContent :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData ContentFileData
-- | An item in a directory listing.
data ContentItem = ContentItem {
contentItemType :: ContentItemType
,contentItemInfo :: ContentInfo
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData ContentItem
data ContentItemType = ItemFile | ItemDir
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData ContentItemType
-- | Information common to both kinds of Content: files and directories.
data ContentInfo = ContentInfo {
contentName :: String
,contentPath :: String
,contentSha :: String
,contentUrl :: String
,contentGitUrl :: String
,contentHtmlUrl :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData ContentInfo
data Contributor
-- | An existing Github user, with their number of contributions, avatar
-- URL, login, URL, ID, and Gravatar ID.
= KnownContributor Int String String String Int String
-- | An unknown Github user with their number of contributions and recorded name.
| AnonymousContributor Int String
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Contributor
-- | This is only used for the FromJSON instance.
data Languages = Languages { getLanguages :: [Language] }
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Languages
-- | A programming language with the name and number of characters written in
-- it.
data Language = Language String Int
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Language
data Tag = Tag {
tagName :: String
,tagZipballUrl :: String
,tagTarballUrl :: String
,tagCommit :: BranchCommit
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Tag
data Branch = Branch {
branchName :: String
,branchCommit :: BranchCommit
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData Branch
data BranchCommit = BranchCommit {
branchCommitSha :: String
,branchCommitUrl :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData BranchCommit
data DetailedOwner = DetailedUser {
detailedOwnerCreatedAt :: GithubDate
,detailedOwnerType :: String
,detailedOwnerPublicGists :: Int
,detailedOwnerAvatarUrl :: String
,detailedOwnerFollowers :: Int
,detailedOwnerFollowing :: Int
,detailedOwnerHireable :: Maybe Bool
,detailedOwnerGravatarId :: Maybe String
,detailedOwnerBlog :: Maybe String
,detailedOwnerBio :: Maybe String
,detailedOwnerPublicRepos :: Int
,detailedOwnerName :: Maybe String
,detailedOwnerLocation :: Maybe String
,detailedOwnerCompany :: Maybe String
,detailedOwnerEmail :: Maybe String
,detailedOwnerUrl :: String
,detailedOwnerId :: Int
,detailedOwnerHtmlUrl :: String
,detailedOwnerLogin :: String
}
| DetailedOrganization {
detailedOwnerCreatedAt :: GithubDate
,detailedOwnerType :: String
,detailedOwnerPublicGists :: Int
,detailedOwnerAvatarUrl :: String
,detailedOwnerFollowers :: Int
,detailedOwnerFollowing :: Int
,detailedOwnerBlog :: Maybe String
,detailedOwnerBio :: Maybe String
,detailedOwnerPublicRepos :: Int
,detailedOwnerName :: Maybe String
,detailedOwnerLocation :: Maybe String
,detailedOwnerCompany :: Maybe String
,detailedOwnerUrl :: String
,detailedOwnerId :: Int
,detailedOwnerHtmlUrl :: String
,detailedOwnerLogin :: String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData DetailedOwner
data RepoWebhook = RepoWebhook {
repoWebhookUrl :: String
,repoWebhookTestUrl :: String
,repoWebhookId :: Integer
,repoWebhookName :: String
,repoWebhookActive :: Bool
,repoWebhookEvents :: [RepoWebhookEvent]
,repoWebhookConfig :: M.Map String String
,repoWebhookLastResponse :: RepoWebhookResponse
,repoWebhookUpdatedAt :: GithubDate
,repoWebhookCreatedAt :: GithubDate
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData RepoWebhook
data RepoWebhookEvent =
WebhookWildcardEvent
| WebhookCommitCommentEvent
| WebhookCreateEvent
| WebhookDeleteEvent
| WebhookDeploymentEvent
| WebhookDeploymentStatusEvent
| WebhookForkEvent
| WebhookGollumEvent
| WebhookIssueCommentEvent
| WebhookIssuesEvent
| WebhookMemberEvent
| WebhookPageBuildEvent
| WebhookPublicEvent
| WebhookPullRequestReviewCommentEvent
| WebhookPullRequestEvent
| WebhookPushEvent
| WebhookReleaseEvent
| WebhookStatusEvent
| WebhookTeamAddEvent
| WebhookWatchEvent
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData RepoWebhookEvent
data RepoWebhookResponse = RepoWebhookResponse {
repoWebhookResponseCode :: Maybe Int
,repoWebhookResponseStatus :: String
,repoWebhookResponseMessage :: Maybe String
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData RepoWebhookResponse
data PullRequestEvent = PullRequestEvent {
pullRequestEventAction :: PullRequestEventType
,pullRequestEventNumber :: Int
,pullRequestEventPullRequest :: DetailedPullRequest
,pullRequestRepository :: Repo
,pullRequestSender :: GithubOwner
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData PullRequestEvent
data PullRequestEventType =
PullRequestOpened
| PullRequestClosed
| PullRequestSynchronized
| PullRequestReopened
| PullRequestAssigned
| PullRequestUnassigned
| PullRequestLabeled
| PullRequestUnlabeled
deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData PullRequestEventType
data PingEvent = PingEvent {
pingEventZen :: String
,pingEventHook :: RepoWebhook
,pingEventHookId :: Int
} deriving (Show, Data, Typeable, Eq, Ord, Generic)
instance NFData PingEvent
data EditPullRequestState =
EditPullRequestStateOpen
| EditPullRequestStateClosed
deriving (Show, Generic)
instance NFData EditPullRequestState
| adarqui/github | Github/Data/Definitions.hs | bsd-3-clause | 22,677 | 0 | 10 | 4,048 | 5,441 | 3,142 | 2,299 | 626 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Util.ToJSON where
import VCS.Multirec
import Language.Clojure.Lang
import Language.Clojure.PrettyPrint (ppConstr)
import Language.Clojure.ToJSON
import Language.Common
import Data.Aeson
import Data.Text
import qualified Data.Vector as V
mkNode :: Object -> V.Vector Value -> Value
mkNode obj children = object [ "text" .= obj
, "children" .= Array children ]
mkLeaf :: Object -> Value
mkLeaf obj = mkNode obj V.empty
toJSONArray :: Value -> Value
toJSONArray val = Array (V.singleton val)
instance ToJSON (Spine (At AlmuH) (Al (At AlmuH)) u) where
toJSON Scp = object [ "text" .= object [ "name" .= ("Scp" :: Text) ] ]
toJSON (Scns c p) = object [
"text" .= object [ "name" .= ("Scns" :: Text)
, "value" .= show (ppConstr c) ]
, "children" .= toJSON p ]
toJSON (Schg i j p) = object [
"text" .= object [ "name" .= ("Schg" :: Text)
, "from" .= show (ppConstr i)
, "to" .= show (ppConstr j) ]
, "children" .= toJSON p ]
instance ToJSON (Almu u v) where
toJSON (Alspn s) = object [
"text" .= object [ "name" .= ("Alspn" :: Text) ]
, "children" .= toJSONArray (toJSON s) ]
toJSON (Aldel d ctx) = object [
"text" .= object [ "name" .= ("Aldel" :: Text)
, "value" .= show (ppConstr d) ]
, "children" .= toJSON ctx]
toJSON (Alins i ctx) = object [
"text" .= object [ "name" .= ("Alins" :: Text)
, "value" .= show (ppConstr i) ]
, "children" .= toJSON ctx ]
instance ToJSON (Al (At AlmuH) p1 p2) where
toJSON al = Array $ go al
where go :: (Al (At AlmuH) p1 p2) -> V.Vector Value
go A0 = V.empty
go (Ains i al) = (object [
"text" .= object ["name" .= ("Ains" :: Text)]
, "children" .= toJSONArray (toJSON i) ])
`V.cons` go al
go (Adel d al) = (object [
"text" .= object ["name" .= ("Adel" :: Text)]
, "children" .= toJSONArray (toJSON d) ])
`V.cons` go al
go (Amod m al) = (object [
"text" .= object ["name" .= ("Amod" :: Text)]
, "children" .= toJSONArray (toJSON m) ])
`V.cons` go al
instance ToJSON (Ctx (AtmuPos u) v) where
toJSON ctx = Array $ go ctx
where
go :: (Ctx (AtmuPos u) v) -> V.Vector Value
go (Here r p) = value `V.cons` rest
where
value = object [ "text" .= object [
"name" .= ("Here" :: Text) ]
, "children" .= toJSONArray (toJSON r ) ]
(Array rest) = toJSON p
go (There u p) = value `V.cons` go p
where
value = object [ "text" .= object [
"name" .= ("There" :: Text) ]
, "children" .= toJSONArray (toJSON u) ]
instance ToJSON (Ctx (AtmuNeg u) v) where
toJSON ctx = Array $ go ctx
where
go :: (Ctx (AtmuNeg u) v) -> V.Vector Value
go (Here r p) = value `V.cons` rest
where
value = object [ "text" .= object [
"name" .= ("Here" :: Text) ]
, "children" .= toJSONArray (toJSON r) ]
(Array rest) = toJSON p
go (There u p) = value `V.cons` go p
where
value = object [ "text" .= object [
"name" .= ("There" :: Text) ]
, "children" .= toJSONArray (toJSON u) ]
instance ToJSON (At AlmuH l) where
toJSON (Ai r) = toJSON r
toJSON (As t) = toJSON t
instance ToJSON (AlmuH u) where
instance ToJSON (AtmuPos u v) where
instance ToJSON (AtmuNeg u v) where
instance ToJSON (ConstrFor u v) where
toJSON c = object [ "text" .= object [ "value" .= show (ppConstr c) ]]
instance ToJSON (All (At AlmuH) l) where
toJSON as = Array $ go as
where
go :: All (At AlmuH) l -> V.Vector Value
go An = V.empty
go (b `Ac` bs) = toJSON b `V.cons` go bs
instance ToJSON (All Usingl l) where
toJSON as = Array $ go as
where
go :: All Usingl l -> V.Vector Value
go An = V.empty
go (b `Ac` bs) = toJSON b `V.cons` go bs
instance ToJSON (Contract Usingl l) where
toJSON c = if old == new
then object [ "text" .= object [
"value" .= show new ] ]
else object [ "text" .= object [
"src" .= show old
, "dst" .= show new ] ]
where
(old, new) = unContract c
| nazrhom/vcs-clojure | src/Util/ToJSON.hs | bsd-3-clause | 4,718 | 0 | 16 | 1,674 | 1,808 | 933 | 875 | 109 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GADTs #-}
-- | Make changes to project or global configuration.
module Stack.ConfigCmd
(ConfigCmdSet(..)
,configCmdSetParser
,cfgCmdSet
,cfgCmdSetName
,cfgCmdName) where
import Control.Applicative
import Control.Monad
import Control.Monad.Catch (throwM)
import Control.Monad.IO.Class
import Control.Monad.Logger
import qualified Data.ByteString as S
import qualified Data.HashMap.Strict as HMap
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Yaml as Yaml
import qualified Options.Applicative as OA
import qualified Options.Applicative.Types as OA
import Path
import Path.IO
import Prelude -- Silence redundant import warnings
import Stack.BuildPlan
import Stack.Config (makeConcreteResolver, getProjectConfig, getImplicitGlobalProjectDir)
import Stack.Constants
import Stack.Types.Config
import Stack.Types.Resolver
data ConfigCmdSet
= ConfigCmdSetResolver AbstractResolver
| ConfigCmdSetSystemGhc CommandScope
Bool
| ConfigCmdSetInstallGhc CommandScope
Bool
data CommandScope
= CommandScopeGlobal
-- ^ Apply changes to the global configuration,
-- typically at @~/.stack/config.yaml@.
| CommandScopeProject
-- ^ Apply changes to the project @stack.yaml@.
configCmdSetScope :: ConfigCmdSet -> CommandScope
configCmdSetScope (ConfigCmdSetResolver _) = CommandScopeProject
configCmdSetScope (ConfigCmdSetSystemGhc scope _) = scope
configCmdSetScope (ConfigCmdSetInstallGhc scope _) = scope
cfgCmdSet
:: (StackMiniM env m, HasConfig env, HasGHCVariant env)
=> GlobalOpts -> ConfigCmdSet -> m ()
cfgCmdSet go cmd = do
conf <- view configL
configFilePath <-
liftM
toFilePath
(case configCmdSetScope cmd of
CommandScopeProject -> do
mstackYamlOption <- forM (globalStackYaml go) resolveFile'
mstackYaml <- getProjectConfig mstackYamlOption
case mstackYaml of
Just stackYaml -> return stackYaml
Nothing -> liftM (</> stackDotYaml) (getImplicitGlobalProjectDir conf)
CommandScopeGlobal -> return (configUserConfigPath conf))
-- We don't need to worry about checking for a valid yaml here
(config :: Yaml.Object) <-
liftIO (Yaml.decodeFileEither configFilePath) >>= either throwM return
newValue <- cfgCmdSetValue cmd
let cmdKey = cfgCmdSetOptionName cmd
config' = HMap.insert cmdKey newValue config
if config' == config
then $logInfo
(T.pack configFilePath <>
" already contained the intended configuration and remains unchanged.")
else do
liftIO (S.writeFile configFilePath (Yaml.encode config'))
$logInfo (T.pack configFilePath <> " has been updated.")
cfgCmdSetValue
:: (StackMiniM env m, HasConfig env, HasGHCVariant env)
=> ConfigCmdSet -> m Yaml.Value
cfgCmdSetValue (ConfigCmdSetResolver newResolver) = do
concreteResolver <- makeConcreteResolver newResolver
case concreteResolver of
-- Check that the snapshot actually exists
ResolverSnapshot snapName -> void $ loadMiniBuildPlan snapName
ResolverCompiler _ -> return ()
-- TODO: custom snapshot support? Would need a way to specify on CLI
ResolverCustom _ _ -> error "'stack config set resolver' does not support custom resolvers"
return (Yaml.String (resolverName concreteResolver))
cfgCmdSetValue (ConfigCmdSetSystemGhc _ bool) =
return (Yaml.Bool bool)
cfgCmdSetValue (ConfigCmdSetInstallGhc _ bool) =
return (Yaml.Bool bool)
cfgCmdSetOptionName :: ConfigCmdSet -> Text
cfgCmdSetOptionName (ConfigCmdSetResolver _) = "resolver"
cfgCmdSetOptionName (ConfigCmdSetSystemGhc _ _) = configMonoidSystemGHCName
cfgCmdSetOptionName (ConfigCmdSetInstallGhc _ _) = configMonoidInstallGHCName
cfgCmdName :: String
cfgCmdName = "config"
cfgCmdSetName :: String
cfgCmdSetName = "set"
configCmdSetParser :: OA.Parser ConfigCmdSet
configCmdSetParser =
OA.hsubparser $
mconcat
[ OA.command
"resolver"
(OA.info
(ConfigCmdSetResolver <$>
OA.argument
readAbstractResolver
(OA.metavar "RESOLVER" <>
OA.help "E.g. \"nightly\" or \"lts-7.2\""))
(OA.progDesc
"Change the resolver of the current project. See https://docs.haskellstack.org/en/stable/yaml_configuration/#resolver for more info."))
, OA.command
(T.unpack configMonoidSystemGHCName)
(OA.info
(ConfigCmdSetSystemGhc <$> scopeFlag <*> boolArgument)
(OA.progDesc
"Configure whether stack should use a system GHC installation or not."))
, OA.command
(T.unpack configMonoidInstallGHCName)
(OA.info
(ConfigCmdSetInstallGhc <$> scopeFlag <*> boolArgument)
(OA.progDesc
"Configure whether stack should automatically install GHC when necessary."))
]
scopeFlag :: OA.Parser CommandScope
scopeFlag =
OA.flag
CommandScopeProject
CommandScopeGlobal
(OA.long "global" <>
OA.help
"Modify the global configuration (typically at \"~/.stack/config.yaml\") instead of the project stack.yaml.")
readBool :: OA.ReadM Bool
readBool = do
s <- OA.readerAsk
case s of
"true" -> return True
"false" -> return False
_ -> OA.readerError ("Invalid value " ++ show s ++ ": Expected \"true\" or \"false\"")
boolArgument :: OA.Parser Bool
boolArgument = OA.argument readBool (OA.metavar "true/false")
| AndreasPK/stack | src/Stack/ConfigCmd.hs | bsd-3-clause | 6,253 | 0 | 20 | 1,744 | 1,178 | 613 | 565 | 139 | 4 |
{-# LANGUAGE TemplateHaskell #-}
module System.Monitoring.GC
( updateStats
, rtsStats
) where
import Control.Monad
import Data.Aeson
import Data.Aeson.TH
import GHC.Stats
import Foreign.Ptr
import Foreign.Concurrent
import System.Mem.Weak
import System.Monitoring
onNextGC :: IO () -> IO ()
onNextGC = void . newForeignPtr nullPtr
onGC :: IO () -> IO ()
onGC action = onNextGC $ action >> onGC action
$(deriveJSON id ''GCStats)
signalStats :: Monitor -> GCStats -> IO ()
signalStats es stats = signalEvent es $ Update "GC" x
where
Object x = toJSON stats
{-
signalEvent es $ Update "numGCs" $ fromIntegral numGcs
signalEvent es $ Update "bytesAllocated" $ fromIntegral bytesAllocated
signalEvent es $ Update "peakMegabytesAllocated" $ fromIntegral peakMegabytesAllocated
signalEvent es $ Update "currentBytesSlop" $ fromIntegral currentBytesSlop
signalEvent es $ Update "maxBytesSlop" $ fromIntegral maxBytesSlop
signalEvent es $ Update "currentBytesUsed" $ fromIntegral currentBytesUsed
signalEvent es $ Update "cumulativeBytesUsed" $ fromIntegral cumulativeBytesUsed
signalEvent es $ Update "maxBytesUsed" $ fromIntegral maxBytesUsed
signalEvent es $ Update "bytesCopied" $ fromIntegral bytesCopied
signalEvent es $ Update "parTotBytesCopied" $ fromIntegral parTotBytesCopied
signalEvent es $ Update "parMaxBytesCopied" $ fromIntegral parMaxBytesCopied
signalEvent es $ Update "mutatorCpuSeconds" $ floor mutatorCpuSeconds
signalEvent es $ Update "mutatorWallSeconds" $ floor mutatorWallSeconds
signalEvent es $ Update "gcCpuSeconds" $ floor gcCpuSeconds
signalEvent es $ Update "gcWallSeconds" $ floor gcWallSeconds
signalEvent es $ Update "cpuSeconds" $ floor cpuSeconds
signalEvent es $ Update "wallSeconds" $ floor wallSeconds
-}
updateStats :: Monitor -> IO ()
updateStats es = getGCStats >>= signalStats es
rtsStats :: Monitor -> IO ()
rtsStats es = do
updateStats es
onGC (updateStats es)
| pxqr/monitoring | src/System/Monitoring/GC.hs | bsd-3-clause | 2,109 | 0 | 9 | 461 | 265 | 134 | 131 | 26 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Playground24 where
import System.Environment
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import System.Random
import Control.Monad
-- import qualified Data.Text.Encoding as E
-- E.encodeUtf8 :: T.Text -> BC.ByteString
-- E.decodeUtf8 :: BC.ByteString -> T.Text
-- main :: IO ()
-- main = do
-- args <- getArgs
-- let fileName = head args
-- imageFile <- BC.readFile fileName
-- glitched <- randomReplaceByte imageFile
-- let glitchedFileName = mconcat ["glitched_",fileName]
-- BC.writeFile glitchedFileName glitched
-- print "all done"
intToChar :: Int -> Char
intToChar int = toEnum safeInt
where safeInt = int `mod` 255
intToBC :: Int -> BC.ByteString
intToBC int = BC.pack [intToChar int]
replaceByte :: Int -> Int -> BC.ByteString -> BC.ByteString
replaceByte loc charVal bytes = mconcat [before,newChar,after]
where (before,rest) = BC.splitAt loc bytes
after = BC.drop 1 rest
newChar = intToBC charVal
randomReplaceByte :: BC.ByteString -> IO BC.ByteString
randomReplaceByte bytes = do
let bytesLength = BC.length bytes
location <- randomRIO (1,bytesLength)
charVal <- randomRIO (0,255)
return (replaceByte location charVal bytes)
sortSection :: Int -> Int -> BC.ByteString -> BC.ByteString
sortSection start size bytes = mconcat [before,changed,after]
where (before,rest) = BC.splitAt start bytes
(target,after) = BC.splitAt size rest
changed = BC.reverse $(BC.sort target)
randomSortSection :: BC.ByteString -> IO BC.ByteString
randomSortSection bytes = do
let sectionSize = 25
let bytesLength = BC.length bytes
start <- randomRIO (0,(bytesLength - sectionSize))
return (sortSection start sectionSize bytes)
glitchActions :: [BC.ByteString -> IO BC.ByteString]
glitchActions = [randomReplaceByte
,randomSortSection
,randomReplaceByte
,randomSortSection
,randomReplaceByte]
main :: IO ()
main = do
args <- getArgs
let fileName = head args
imageFile <- BC.readFile fileName
glitched <- foldM (\bytes func -> func bytes) imageFile glitchActions
let glitchedFileName = mconcat ["glitched_",fileName]
BC.writeFile glitchedFileName glitched
print "all done" | stefanocerruti/haskell-primer-alpha | src/Playground24.hs | bsd-3-clause | 2,425 | 0 | 11 | 569 | 620 | 324 | 296 | 49 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- -----------------------------------------------------------------------------
-- |
-- Module : Ircfs.Process
-- Copyright : (c) Andreas-Christoph Bernstein 2011
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : not portable
--
-- Process incoming file system messages.
--------------------------------------------------------------------------------
module Ircfs.Process
(
processIrc
) where
import Prelude hiding ((.), id)
import Control.Category
import qualified Data.Lens.Common as L
import qualified Data.ByteString.Char8 as B
import Data.Monoid
import Data.Maybe (maybeToList, fromMaybe)
import Foreign.C.Types (CTime)
import qualified Network.IRC.Message as I
import Ircfs.Types
import Ircfs.Filesystem
import Ircfs.Misc (Endomorphism, stamp')
-- | Process incomming irc messages.
processIrc :: CTime -> I.Message -> Endomorphism Fs
processIrc time (I.Message _ (I.CmdNumericReply 001) (I.Params _ _)) st =
let now s = B.pack $ stamp' (timeZone s) time
text s = mconcat [now s," RPL_WELCOME -- connected\n"]
in event time (text st) st
processIrc time m@(I.Message _ (I.CmdNumericReply 433) _) st =
let now s = B.pack $ stamp' (timeZone s) time
text s = mconcat [
now s," ERR_NICKNAMEINUSE "
, I.encode m
, "please change your nick, or you will be disconneted at any moment now.\n"
]
in event time (text st) st
processIrc time (I.Message (Just (I.PrefixNick n _ _)) I.NICK (I.Params [] (Just new))) st =
let yourNick = L.getL nickLens
someone = event time (mconcat [n," changed nick to ",new,"\n"])
you = event time (mconcat ["You're now known as ",new,"\n"])
. touch Qnick time
. substitute Qnick new
in if Just n == yourNick st then you st else someone st
processIrc time (I.Message (Just (I.PrefixNick n _ _)) I.NICK (I.Params (new:_) _)) st =
let yourNick s = fromMaybe mempty (L.getL nickLens s) -- nick st
you = event time (mconcat ["You're now known as ",new,"\n"])
. touch Qnick time
. substitute Qnick new
someone = event time (mconcat [n," changed nick to ",new,"\n"])
in if n == yourNick st then you st else someone st
processIrc time (I.Message (Just (I.PrefixNick n _ _)) I.JOIN (I.Params [] (Just c))) st =
let yourNick = L.getL nickLens
ins = insertChannel c time
-- someone = "add user to users file"
in if Just n == yourNick st then ins st else st
processIrc time (I.Message (Just (I.PrefixNick n _ _)) I.JOIN (I.Params (c:_) _)) st =
let yourNick = L.getL nickLens
ins = insertChannel c time
-- someone = "add user to users file"
in if Just n == yourNick st then ins st else st
processIrc time (I.Message (Just (I.PrefixNick n _ _)) I.PART (I.Params (c:_) _)) st =
let yourNick = L.getL nickLens
rm = removeChannel c time
-- someone = "say user left to users file"
in if Just n == yourNick st then rm st else st
processIrc time (I.Message Nothing I.PRIVMSG (I.Params (c:cs) t)) st =
let n = fromMaybe mempty (L.getL nickLens st) -- nick st
tm = L.getL (targetMapLens' c) st
now s = B.pack $ stamp' (timeZone s) time
ts = maybeToList t
f k = touch (Qdata k) time
. append (Qdata k) (mconcat [now st," < ",n,"> ",B.unwords (cs++ts),"\n"])
in maybe st (`f` st) tm
processIrc time (I.Message (Just (I.PrefixNick n _ _)) I.PRIVMSG (I.Params (c:cs) t)) st =
let tm = L.getL (targetMapLens' c) st
ts = maybeToList t
now s = B.pack $ stamp' (timeZone s) time
f k s = touch (Qdata k) time
. append (Qdata k) (mconcat [now s," < ",n,"> ",B.unwords (cs++ts),"\n"])
$ s
in maybe st (`f` st) tm
processIrc time m@(I.Message _ I.ERROR _) st =
event time (mconcat ["error ",I.encode m]) st
processIrc _ _ st = st
privmsg :: [B.ByteString] -> B.ByteString -> I.Message
privmsg targets x = I.Message Nothing I.PRIVMSG (I.Params targets (Just x))
| bernstein/ircfs | Ircfs/Process.hs | bsd-3-clause | 4,192 | 0 | 17 | 1,040 | 1,582 | 819 | 763 | 74 | 6 |
{-|
Module : Werewolf.Command.Status
Description : Handler for the status subcommand.
Copyright : (c) Henry J. Wylde, 2016
License : BSD3
Maintainer : [email protected]
Handler for the status subcommand.
-}
module Werewolf.Command.Status (
-- * Handle
handle,
) where
import Control.Monad.Except
import Control.Monad.Extra
import Control.Monad.State
import Control.Monad.Writer
import Data.Text (Text)
import Game.Werewolf
import Game.Werewolf.Command
import Game.Werewolf.Command.Status
import Game.Werewolf.Message.Error
import Werewolf.System
handle :: MonadIO m => Text -> Text -> m ()
handle callerName tag = do
unlessM (doesGameExist tag) $ exitWith failure
{ messages = [noGameRunningMessage callerName]
}
game <- readGame tag
let command = statusCommand callerName
case runExcept . execWriterT $ execStateT (apply command) game of
Left errorMessages -> exitWith failure { messages = errorMessages }
Right messages -> exitWith success { messages = messages }
| hjwylde/werewolf | app/Werewolf/Command/Status.hs | bsd-3-clause | 1,052 | 0 | 12 | 212 | 235 | 127 | 108 | 21 | 2 |
module LSC2008.TestListSet1 where
import LazySmallCheck
import Benchmarks.ListSet
import System.Environment
bench d = depthCheck (read d) prop_insertSet
| UoYCS-plasma/LazySmallCheck2012 | suite/performance/LSC2008/TestListSet1.hs | bsd-3-clause | 156 | 0 | 7 | 19 | 38 | 21 | 17 | 5 | 1 |
-- | TRS to C compilation.
module C.Compiler
( compile
, Word (..)
) where
import Control.Monad hiding (join)
import qualified Data.List as List
import qualified Data.Map as Map
import Data.Maybe
import System.Exit
import System.IO
import TRS.Checker
import TRS.Types
import Utils
-- | The Configuration of the generated C code and the target machine.
-- Word width of the target machine.
data Word = Word8 | Word16 | Word32 | Word64 deriving Show
{-
-- The structure of the generated C code.
data Structure
= Callable -- | No main function. Intended to be called by another program. Also produces a header file.
| StandAlone -- | A normal main function. Initializes, then runs forever.
| Verification -- | A main function for verification. Initializes, then runs until all assertions have been checked.
-}
wordWidth :: Word -> Int
wordWidth Word8 = 8
wordWidth Word16 = 16
wordWidth Word32 = 32
wordWidth Word64 = 64
wordCount :: Word -> Int -> Int
wordCount _ w | w <= 0 = 0
wordCount word w = 1 + wordCount word (w - wordWidth word)
mask :: Word -> Int -> Integer
mask word width = power 2 (toInteger widthMSB) - 1
where
widthMSB :: Int
widthMSB = if width `mod` wordWidth word == 0 then wordWidth word else width `mod` wordWidth word
cType :: Word -> String
cType Word8 = "unsigned char"
cType Word16 = "unsigned short int"
cType Word32 = "unsigned long int"
cType Word64 = "unsigned long long int"
-- | Compiles a TRS 'System' to C.
compile :: String -> Word -> System () -> IO ()
compile name word system = do
sys <- extract system
case sys of
Nothing -> putStrLn "ERROR: Design rule checks failed. Compilation aborted." >> exitWith (ExitFailure 1)
Just (SystemElab rules regs asserts exprs) -> do
asserts' <- filterM isAssertSupported asserts
writeFile (name ++ ".c") (code word rules regs asserts' exprs)
where
isAssertSupported :: Assert -> IO Bool
isAssertSupported (Assert name prop) = case prop of
PropertyAlways (PropertyExpr _) -> return True
PropertyAlways (PropertyImply (PropertyExpr _) (PropertyExpr _)) -> return True
_ -> do
putStrLn $ "WARNING: Assertion " ++ name ++ " is not supported in C."
return False
code :: Word -> [Rule] -> [Reg] -> [Assert] -> [Expr] -> String
code word rules regs asserts exprs =
declare word regs asserts assertId exprs exprId ++
primitives word ++
assertions word asserts assertId exprId ++
initialize word regs asserts assertId ++
calcRules word exprId rules ++
main
where
exprId :: Expr -> Int
exprId = (Map.!) (Map.fromList (zip exprs [0 .. length exprs - 1]))
assertId :: Assert -> Int
assertId = (Map.!) (Map.fromList (zip asserts [0 .. length asserts - 1]))
declare :: Word -> [Reg] -> [Assert] -> (Assert -> Int) -> [Expr] -> (Expr -> Int) -> String
declare word regs asserts assertId exprs exprId = unlines
[ "#include <stdlib.h>"
, "#include <stdio.h>"
, ""
, join (map declareReg regs) "\n"
, join (map declareExpr exprs) "\n"
, join (map declareAssert asserts) "\n"
, "unsigned char assertions_pass;"
, ""
]
where
declareReg (Reg uid name width _) = cType word ++ " r" ++ show uid ++ "[" ++ show (wordCount word width) ++ "]; // Register " ++ name
declareExpr expr = case expr of
Val (Reg uid _ _ _) -> cType word ++ " * e" ++ show (exprId expr) ++ " = r" ++ show uid ++ ";"
Const w v -> cType word ++ " e" ++ show (exprId expr) ++ "[" ++ show (wordCount word w) ++ "] = {" ++ join (map show (constant word w v)) ", " ++ "};"
_ -> cType word ++ " e" ++ show (exprId expr) ++ "[" ++ show (wordCount word (width expr)) ++ "];"
declareAssert assert = "unsigned char a" ++ show (assertId assert) ++ ";"
expression :: Word -> (Expr -> Int) -> [Expr] -> String
expression word exprId exprs = if null code then "" else code ++ "\n"
where
code = join (mapMaybe f (topological exprs)) "\n"
f :: Expr -> Maybe String
f x = case x of
Add a b -> Just $ prim "add" [xWords, xMask, var a, var b, var x]
Sub a b -> Just $ prim "sub" [xWords, xMask, var a, var b, var x]
Not a -> Just $ prim "not" [xWords, xMask, var a, var x]
And a b -> Just $ prim "and" [xWords, xMask, var a, var b, var x]
Xor a b -> Just $ prim "xor" [xWords, xMask, var a, var b, var x]
Or a b -> Just $ prim "or" [xWords, xMask, var a, var b, var x]
Select _ _ _ -> error "Bit selection not supported yet." --XXX
Concat _ _ -> error "Concatenation not supported yet." --XXX
Mux c h l -> Just $ prim "mux" [xWords, var c, var h, var l, var x]
Eq a b -> Just $ prim "eq" [words a, var a, var b, var x]
Lt a b -> Just $ prim "lt" [words a, var a, var b, var x]
Const _ _ -> Nothing
Nondet _ -> error "Nondeterministic values not supported."
Val _ -> Nothing
where
var expr = "e" ++ show (exprId expr)
words expr = show (wordCount word (width expr))
xWords = words x
xMask = show (mask word (width x))
prim :: String -> [String] -> String
prim name args = " trs_" ++ name ++ "(" ++ join args ", " ++ ");"
assertions :: Word -> [Assert] -> (Assert -> Int) -> (Expr -> Int) -> String
assertions word asserts assertId exprId = unlines
[ "void check_assertions () {"
, join (map assertion asserts) "\n"
, " if (1" ++ concatMap (\ assert -> " && a" ++ show (assertId assert)) asserts ++ ") {"
, " exit (! assertions_pass);"
, " }"
, "}"
, ""
]
where
assertion :: Assert -> String
assertion assert@(Assert name (PropertyAlways (PropertyExpr check))) =
expression word exprId [check] ++
" a" ++ show (assertId assert) ++ " = 1;\n" ++
" if (e" ++ show (exprId check) ++ "[0]) {\n" ++
" printf(\"Assertion passed: " ++ name ++ "\\n\");\n" ++
" }\n" ++
" else {\n" ++
" printf(\"ERROR: Assertion failed: " ++ name ++ "\\n\");\n" ++
" assertions_pass = 0;\n" ++
" }"
assertion assert@(Assert name (PropertyAlways (PropertyImply (PropertyExpr cond) (PropertyExpr check)))) =
expression word exprId [cond, check] ++
" if (e" ++ show (exprId cond) ++ "[0]) {\n" ++
" a" ++ show (assertId assert) ++ " = 1;\n" ++
" if (e" ++ show (exprId check) ++ "[0]) {\n" ++
" printf(\"Assertion passed: " ++ name ++ "\\n\");\n" ++
" }\n" ++
" else {\n" ++
" printf(\"ERROR: Assertion failed: " ++ name ++ "\\n\");\n" ++
" assertions_pass = 0;\n" ++
" }\n" ++
" }"
assertion _ = error "Assertion not supported."
initialize :: Word -> [Reg] -> [Assert] -> (Assert -> Int) -> String
initialize word regs asserts assertId = unlines
[ "void init () {"
, join (map initReg regs) "\n"
, join (map initAssert asserts) "\n"
, " assertions_pass = 1;"
, " check_assertions ();"
, "}"
, ""
]
where
initReg (Reg uid _ w (Just v)) = constant' ("r" ++ show uid) w v
initReg (Reg uid _ w Nothing ) = constant' ("r" ++ show uid) w 0 --XXX Add a note that nondet init values are set to 0.
initAssert a = " a" ++ show (assertId a) ++ " = 0;"
constant' :: String -> Int -> Integer -> String
constant' name w value = join (map (\ (i,v) -> " " ++ name ++ "[" ++ show i ++ "] = " ++ show v ++ ";") (enum (constant word w value))) "\n"
constant :: Word -> Int -> Integer -> [Integer]
constant word w v = constant' (wordCount word w) v
where
constant' i _ | i <= 0 = []
constant' i v = (v `mod` toInteger shift) : constant' (i - 1) (v `div` toInteger shift)
shift = power 2 (toInteger $ wordWidth word)
calcRules :: Word -> (Expr -> Int) -> [Rule] -> String
calcRules word exprId rules = unlines
[ "void rules () {"
, join (map (rule word exprId) rules) "\n"
, "}"
, ""
]
rule :: Word -> (Expr -> Int) -> Rule -> String
rule word exprId (Rule name condition assigns) =
" // Rule " ++ name ++ "\n" ++
expression word exprId [condition] ++
" if (e" ++ show (exprId condition) ++ ") {\n" ++
expression word exprId exprs ++
concatMap assign assigns ++
" }\n" ++
" check_assertions ();\n"
where
(_,exprs) = unzip assigns
assign (reg,expr) = " " ++ prim "copy" [show (wordCount word (width expr)), "e" ++ show (exprId expr), "r" ++ show (uid reg)]
main :: String
main = unlines
[ "int main () {"
, " init ();"
, " while (1)"
, " rules ();"
, " return 0;"
, "}"
, ""
]
primitives :: Word -> String
primitives word = unlines
[ "void trs_copy(int words, " ++ single ++ "* a, " ++ single ++ "* x)"
, "{"
, " int i;"
, " for (i = 0; i < words; i++)"
, " x[i] = a[i];"
, "}"
, ""
, "void trs_mask(int words, " ++ single ++ " mask, " ++ single ++ "* x)"
, "{"
, " x[words - 1] = x[words - 1] & mask;"
, "}"
, ""
, "void trs_not(int words, " ++ single ++ " mask, " ++ single ++ "* a, " ++ single ++ "* x)"
, "{"
, " int i;"
, " for (i = 0; i < words; i++)"
, " x[i] = ~ a[i];"
, " trs_mask(words, mask, x);"
, "}"
, ""
, "void trs_and(int words, " ++ single ++ " mask, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " for (i = 0; i < words; i++)"
, " x[i] = a[i] & b[i];"
, " trs_mask(words, mask, x);"
, "}"
, ""
, "void trs_xor(int words, " ++ single ++ " mask, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " for (i = 0; i < words; i++)"
, " x[i] = a[i] ^ b[i];"
, " trs_mask(words, mask, x);"
, "}"
, ""
, "void trs_or(int words, " ++ single ++ " mask, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " for (i = 0; i < words; i++)"
, " x[i] = a[i] | b[i];"
, " trs_mask(words, mask, x);"
, "}"
, ""
, "void trs_concat_over(int words_a, int words_b, int shift_left, int shift_right, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " int j;"
, " for (i = 0; i < words_b; i++)"
, " x[i] = b[i];"
, " for (i = 0, j = words_b - 1; i < words_a; i++, j++) {"
, " x[j] = x[j] | (" ++ mask ++ " & (a[i] << shift_left));"
, " x[j + 1] = a[i] >> shift_right;"
, " }"
, "}"
, ""
, "void trs_concat_under(int words_a, int words_b, int shift_left, int shift_right, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " int j;"
, " for (i = 0; i < words_b; i++)"
, " x[i] = b[i];"
, " for (i = 0, j = words_b - 1; i < words_a - 1; i++, j++) {"
, " x[j] = x[j] | (" ++ mask ++ " & (a[i] << shift_left));"
, " x[j + 1] = a[i] >> shift_right;"
, " }"
, " x[j] = x[j] | (" ++ mask ++ " & (a[i] << shift_left));"
, "}"
, ""
, "void trs_concat_simple(int words_a, int words_b, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " int j;"
, " for (i = 0; i < words_b; i++)"
, " x[i] = b[i];"
, " for (i = 0, j = words_b; i < words_a; i++, j++)"
, " x[j] = a[i];"
, "}"
, ""
, "void trs_select(int word, int bit, " ++ single ++ "* a, " ++ single ++ "* x)"
, "{"
, " x[0] = 1 & (a[word] >> bit);"
, "}"
, ""
, "void trs_eq(int words, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " x[0] = 1;"
, " for (i = 0; i < words; i++)"
, " x[0] = x[0] && a[i] == b[i];"
, "}"
, ""
, "void trs_lt(int words, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " x[0] = 0;"
, " for (i = words - 1; i >= 0; i--) {"
, " if (a[i] < b[i]) {"
, " x[0] = 1;"
, " return;"
, " }"
, " else if (a[i] > b[i]) {"
, " return;"
, " }"
, " }"
, "}"
, ""
, "void trs_add(int words, " ++ single ++ " mask, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " " ++ double ++ " tmp = 0;"
, " for (i = 0; i < words; i++) {"
, " tmp = (" ++ double ++ ") a[i] + (" ++ double ++ ") b[i] + tmp;"
, " x[i] = (" ++ single ++ ") (tmp & " ++ mask ++ ");"
, " tmp = (tmp >> " ++ width ++ ") & 1;"
, " }"
, " trs_mask(words, mask, x);"
, "}"
, ""
, "void trs_sub(int words, " ++ single ++ " mask, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i;"
, " " ++ double ++ " tmp = 0;"
, " for (i = 0; i < words; i++) {"
, " tmp = (" ++ double ++ " ) a[i] - (" ++ double ++ " ) b[i] - tmp;"
, " x[i] = (" ++ single ++ ") (tmp & " ++ mask ++ ");"
, " tmp = (tmp >> " ++ width ++ ") & 1;"
, " }"
, " trs_mask(words, mask, x);"
, "}"
, ""
, "void trs_mul(int words, " ++ single ++ " mask, " ++ single ++ "* a, " ++ single ++ "* b, " ++ single ++ "* x)"
, "{"
, " int i, ia, ib, ic;"
, " " ++ double ++ " tmp;"
, " for (i = 0; i < words; i++) x[i] = 0;"
, " for (i = 0; i < words; i++) {"
, " for (ia = i, ib = 0; ia >= 0; ia--, ib++) {"
, " tmp = (" ++ double ++ ") (a[ia]) * (" ++ double ++ ") (b[ib]);"
, " for (ic = i; ic < words; ic++) {"
, " tmp = tmp + (" ++ double ++ ") x[ic];"
, " x[ic] = (" ++ single ++ ") (tmp & " ++ mask ++ ");"
, " tmp = (tmp >> 8);"
, " }"
, " }"
, " }"
, " trs_mask(words, mask, x);"
, "}"
, ""
, "void trs_mux(int words, " ++ single ++ "* select, " ++ single ++ "* on_1, " ++ single ++ "* on_0, " ++ single ++ "* x)"
, "{"
, " int i;"
, " for (i = 0; i < words; i++)"
, " x[i] = select[0] ? on_1[i] : on_0[i];"
, "}"
, ""
, "void trs_ff(int words, " ++ single ++ "* clk, " ++ single ++ "* q)"
, "{"
, " int i;"
, " " ++ single ++ "* state_clk = & q[words];"
, " " ++ single ++ "* state_d = & q[words + 1];"
, " if (clk[0] && ! state_clk[0]) "
, " for (i = 0; i < words; i++)"
, " q[i] = state_d[i];"
, " state_clk[0] = clk[0];"
, "}"
, ""
, "void trs_ff_update(int words, " ++ single ++ "* data, " ++ single ++ "* q)"
, "{"
, " int i;"
, " " ++ single ++ "* state_d = & q[words + 1];"
, " for (i = 0; i < words; i++)"
, " state_d[i] = data[i];"
, "}"
, ""
, "void trs_ffc(int words, " ++ single ++ "* clr, " ++ single ++ "* clk, " ++ single ++ "* q)"
, "{"
, " int i;"
, " " ++ single ++ "* state_clr = & q[words];"
, " " ++ single ++ "* state_clk = & q[words + 1];"
, " " ++ single ++ "* state_d = & q[words + 2];"
, " if (clr[0] && ! state_clr[0])"
, " for (i = 0; i < words; i++)"
, " q[i] = 0;"
, " else if (clk[0] && ! state_clk[0]) "
, " for (i = 0; i < words; i++)"
, " q[i] = state_d[i];"
, " state_clr[0] = clr[0];"
, " state_clk[0] = clk[0];"
, "}"
, ""
, "void trs_ffc_update(int words, " ++ single ++ "* data, " ++ single ++ "* q)"
, "{"
, " int i;"
, " " ++ single ++ "* state_d = & q[words + 2];"
, " for (i = 0; i < words; i++)"
, " state_d[i] = data[i];"
, "}"
, ""
]
where
single = cType word
double = case word of
Word8 -> "unsigned short int"
Word16 -> "unsigned long int"
Word32 -> "unsigned long long int"
Word64 -> "unsigned long long long int"
width = show (wordWidth word)
mask = "0x" ++ replicate (wordWidth word `div` 4) 'F'
| tomahawkins/trs | attic/C/Compiler.hs | bsd-3-clause | 15,320 | 0 | 28 | 4,418 | 4,519 | 2,384 | 2,135 | 385 | 15 |
module Lang.Util.EitherT where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Data.Text (Text)
newtype EitherT e m a = EitherT { runEitherT :: m (Either e a) }
class EitherTErr e where
textError :: Text -> e
instance (Functor m) => Functor (EitherT e m) where
fmap f z = EitherT (fmap f <$> runEitherT z)
instance (Applicative m, Monad m) => Applicative (EitherT e m) where
pure = EitherT . pure . Right
(<*>) = ap
instance (Monad m) => Monad (EitherT e m) where
return = EitherT . return . Right
z >>= f = EitherT . (=<< runEitherT z) $ \c -> case c of
(Right x) -> runEitherT (f x)
(Left e) -> return (Left e)
instance MonadTrans (EitherT e) where
lift m = EitherT $ (return . Right) =<< m
instance MonadIO m => MonadIO (EitherT e m) where
liftIO m = EitherT $ (return . Right) =<< liftIO m
err :: Monad m => e -> EitherT e m a
err = EitherT . return . Left
| Alasdair/Mella | Lang/Util/EitherT.hs | bsd-3-clause | 991 | 0 | 13 | 234 | 425 | 225 | 200 | 25 | 1 |
-- ------------------------------------------------------ --
-- Copyright Β© 2012 AlephCloud Systems, Inc.
-- ------------------------------------------------------ --
-- | GET GetChange
--
-- Returns the current status of change batch request.
--
-- <http://docs.amazonwebservices.com/Route53/latest/APIReference/API_GetChange.html>
--
module Aws.Route53.Commands.GetChange where
import Aws.Core
import Aws.Route53.Core
import qualified Data.Text.Encoding as T
data GetChange = GetChange
{ changeId :: ChangeId
} deriving (Show)
data GetChangeResponse = GetChangeResponse
{ gcrChangeInfo :: ChangeInfo
} deriving (Show)
getChange :: ChangeId -> GetChange
getChange changeId = GetChange changeId
-- | ServiceConfiguration: 'Route53Configuration'
instance SignQuery GetChange where
type ServiceConfiguration GetChange = Route53Configuration
signQuery GetChange{..} = route53SignQuery method resource query body
where
method = Get
resource = T.encodeUtf8 . qualifiedIdText $ changeId
query = []
body = Nothing
instance ResponseConsumer r GetChangeResponse where
type ResponseMetadata GetChangeResponse = Route53Metadata
responseConsumer _ = route53ResponseConsumer parse
where
parse cursor = do
route53CheckResponseType () "GetChangeResponse" cursor
changeInfo <- r53Parse cursor
return $ GetChangeResponse changeInfo
instance Transaction GetChange GetChangeResponse
| memcachier/aws-route53 | Aws/Route53/Commands/GetChange.hs | bsd-3-clause | 1,582 | 0 | 11 | 366 | 257 | 142 | 115 | -1 | -1 |
{-# LANGUAGE CPP #-}
module Tinc.GhcPkgSpec (spec) where
import Helper
import Tinc.GhcPkg
import Tinc.Package
globalPackages :: [String]
globalPackages = [
"array"
, "base"
, "binary"
, "bin-package-db"
, "bytestring"
, "Cabal"
, "containers"
, "deepseq"
, "directory"
, "filepath"
, "ghc"
, "ghc-prim"
, "hoopl"
, "hpc"
, "integer-gmp"
, "pretty"
, "process"
, "rts"
, "template-haskell"
, "time"
, "unix"
, "haskeline"
, "terminfo"
, "transformers"
, "xhtml"
#if __GLASGOW_HASKELL__ < 710
, "haskell2010"
, "haskell98"
, "old-locale"
, "old-time"
#endif
]
spec :: Spec
spec = do
describe "listGlobalPackages" $ do
it "lists packages from global package database" $ do
packages <- listGlobalPackages
map packageName packages `shouldMatchList` globalPackages
| beni55/tinc | test/Tinc/GhcPkgSpec.hs | bsd-3-clause | 873 | 0 | 14 | 224 | 178 | 108 | 70 | 42 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Cloud.AWS.EC2.Types.ConversionTask
( ConversionTask(..)
, ConversionTaskState(..)
, DiskImage(..)
, DiskImageDescription(..)
, DiskImageVolumeDescription(..)
, ImportInstanceTaskDetailItem(..)
, ImportInstanceTaskDetails(..)
, ImportVolumeRequestImage(..)
, ImportVolumeTaskDetails(..)
, LaunchSpecification(..)
) where
import Cloud.AWS.EC2.Types.Common (Architecture, ShutdownBehavior)
import Cloud.AWS.Lib.FromText (deriveFromText)
import Data.Text (Text)
import Data.IP (IPv4)
data ConversionTask = ConversionTask
{ conversionTaskId :: Text
, conversionTaskExpirationTime :: Text
, conversionTaskImportVolume :: Maybe ImportVolumeTaskDetails
, conversionTaskImportInstance :: Maybe ImportInstanceTaskDetails
, conversionTaskState :: ConversionTaskState
, conversionTaskStatusMessage :: Text
}
deriving (Show, Read, Eq)
data ConversionTaskState
= ConversionTaskActive
| ConversionTaskCancelling
| ConversionTaskCancelled
| ConversionTaskCompleted
deriving (Show, Read, Eq)
data DiskImage = DiskImage
{ diskImageFormat :: Text
, diskImageBytes :: Int
, diskImageImportManifestUrl :: Text
, diskImageDescripsion :: Maybe Text
, diskImageVolumeSize :: Int
}
deriving (Show, Read, Eq)
data DiskImageDescription = DiskImageDescription
{ diskImageDescriptionFormat :: Text
, diskImageDescriptionSize :: Int
, diskImageDescriptionImportManifestUrl :: Text
, diskImageDescriptionChecksum :: Maybe Text
}
deriving (Show, Read, Eq)
data DiskImageVolumeDescription = DiskImageVolumeDescription
{ diskImageVolumeDescriptionSize :: Int
, diskImageVolumeDescriptionId :: Maybe Text
}
deriving (Show, Read, Eq)
data ImportInstanceTaskDetailItem = ImportInstanceTaskDetailItem
{ importInstanceTaskDetailItemBytesConverted :: Int
, importInstanceTaskDetailItemAvailabilityZone :: Text
, importInstanceTaskDetailItemImage :: DiskImageDescription
, importInstanceTaskDetailItemDescription :: Maybe Text
, importInstanceTaskDetailItemVolume :: DiskImageVolumeDescription
, importInstanceTaskDetailItemStatus :: Text
, importInstanceTaskDetailItemStatusMessage :: Maybe Text
}
deriving (Show, Read, Eq)
data ImportInstanceTaskDetails = ImportInstanceTaskDetails
{ importInstanceTaskDetailsVolumes :: [ImportInstanceTaskDetailItem]
, importInstanceTaskDetailsInstanceId :: Text
, importInstanceTaskDetailsPlatform :: Maybe Text
, importInstanceTaskDetailsDescription :: Maybe Text
}
deriving (Show, Read, Eq)
data ImportVolumeRequestImage = ImportVolumeRequestImage
{ importVolumeRequestImageFormat :: Text
, importVolumeRequestImageBytes :: Int
, importVolumeRequestImageImportManifestUrl :: Text
}
deriving (Show, Read, Eq)
data ImportVolumeTaskDetails = ImportVolumeTaskDetails
{ importVolumeTaskDetailsBytesConverted :: Int
, importVolumeTaskDetailsAvailabilityZone :: Text
, importVolumeTaskDetailsDescription :: Maybe Text
, importVolumeTaskDetailsImage :: DiskImageDescription
, importVolumeTaskDetailsVolume :: DiskImageVolumeDescription
}
deriving (Show, Read, Eq)
data LaunchSpecification = LaunchSpecification
{ launchSpecificationArchitecture :: Architecture
, launchSpecificationGroupNames :: [Text]
, launchSpecificationUserData :: Maybe Text
, launchSpecificationInstanceType :: Text
, launchSpecificationPlacementAvailabilityZone :: Maybe Text
, launchSpecificationMonitoringEnabled :: Maybe Bool
, launchSpecificationSubnetId :: Maybe Text
, launchSpecificationInstanceInitiatedShutdownBehavior
:: Maybe ShutdownBehavior
, launchSpecificationPrivateIpAddress :: Maybe IPv4
}
deriving (Show, Read, Eq)
deriveFromText "ConversionTaskState"
["active", "cancelling", "cancelled", "completed"]
| worksap-ate/aws-sdk | Cloud/AWS/EC2/Types/ConversionTask.hs | bsd-3-clause | 3,947 | 0 | 9 | 659 | 721 | 436 | 285 | 88 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PackageImports #-}
module Snap.Internal.Http.Parser.Benchmark
( benchmarks )
where
import Control.Monad
import Criterion.Main hiding (run)
import qualified Data.ByteString as S
import Snap.Internal.Http.Server.Parser
import Snap.Internal.Http.Parser.Data
import qualified System.IO.Streams as Streams
parseGet :: S.ByteString -> IO ()
parseGet s = do
(Just !_) <- Streams.fromList [s] >>= parseRequest
return $! ()
benchmarks :: Benchmark
benchmarks = bgroup "parser"
[ bench "firefoxget" $ whnfIO $! replicateM_ 1000
$! parseGet parseGetData
]
| afcowie/new-snap-server | benchmark/Snap/Internal/Http/Parser/Benchmark.hs | bsd-3-clause | 786 | 0 | 10 | 207 | 165 | 96 | 69 | 20 | 1 |
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving,
FlexibleInstances, MultiParamTypeClasses #-}
module Ling.Term.Checker where
import Ling.Abs (Name)
import Ling.Utils
import Ling.Print
import Ling.Proto
import Ling.Norm
import Ling.Subst
import Ling.Equiv
import Ling.ErrM
import qualified Data.Map as Map
import Data.Map (Map)
import Data.List (sort)
import Control.Monad.Reader
import Control.Monad.Error.Class
import Control.Applicative
import Control.Lens
data ProcDef = ProcDef Name [ChanDec] Proc Proto
data TCEnv = TCEnv
{ _verbosity :: Verbosity
, _evars :: Map Name Typ
-- ^ Term types
, _edefs :: Map Name Term
-- ^ Term definitions
, _pdefs :: Map Name ProcDef
-- ^ Processes definitions
, _ddefs :: Map Name [Name]
-- ^ Datatypes definitions
, _ctyps :: Map Name Name
-- ^ Data constructor β¦ type name
}
$(makeLenses ''TCEnv)
emptyTCEnv :: TCEnv
emptyTCEnv = TCEnv False Map.empty Map.empty Map.empty Map.empty Map.empty
newtype TC a = MkTC { unTC :: ReaderT TCEnv Err a }
deriving (Functor, Applicative, Monad, MonadReader TCEnv)
instance MonadError String TC where
throwError = MkTC . lift . Bad
catchError = error "catchError: not implemented for TC"
checkEquality :: (Print a, Eq a) => String -> a -> a -> TC ()
checkEquality msg t0 t1 = assertEqual t0 t1
[msg
,"Expected:"
," " ++ pretty t0
,"Inferred:"
," " ++ pretty t1
]
tcEqEnv :: TC EqEnv
tcEqEnv = emptyEqEnv <$> view edefs
checkEquivalence :: (Print a, Eq a, Equiv a) => String -> a -> a -> TC ()
checkEquivalence msg t0 t1 = do
env <- tcEqEnv
{-
debugEdefs <- view edefs
when (t0 /= t1) . debug $
["checkEquivalence:"
," " ++ pretty t0
,"against"
," " ++ pretty t1
,"env:"
]
++ prettyMap debugEdefs
-}
assert (equiv env t0 t1)
[msg
,"Expected:"
," " ++ pretty t0
,"Inferred:"
," " ++ pretty t1
]
checkTypeEquivalence :: Typ -> Typ -> TC ()
checkTypeEquivalence = checkEquivalence "Types are not equivalent."
checkTyp :: Typ -> TC ()
checkTyp = checkTerm TTyp
checkVarDef :: Name -> Typ -> Maybe Term -> TC a -> TC a
checkVarDef x typ mt kont = do
checkTyp typ
checkMaybeTerm typ mt
local ((evars . at x .~ Just typ)
. (edefs . at x .~ mt)) kont
checkVarDec :: VarDec -> TC a -> TC a
checkVarDec (Arg x typ) = checkVarDef x typ Nothing
-- TODO: Here I assume that sessions are well formed
checkSessions :: [RSession] -> TC ()
checkSessions = mapM_ checkRSession
checkRSession :: RSession -> TC ()
checkRSession (Repl s t) = checkSession s >> checkTerm int t
checkSession :: Session -> TC ()
checkSession s0 = case s0 of
Atm _ n -> checkTerm tSession (Def n [])
End -> return ()
Snd t s -> checkTyp t >> checkSession s
Rcv t s -> checkTyp t >> checkSession s
Par ss -> checkSessions ss
Ten ss -> checkSessions ss
Seq ss -> checkSessions ss
checkNoDups :: (Print a, Eq a) => String -> [a] -> TC ()
checkNoDups _ [] = return ()
checkNoDups msg (x:xs)
| x `elem` xs = throwError $ pretty x ++ " appears twice " ++ msg
| otherwise = checkNoDups msg xs
allSame :: Eq a => [a] -> Bool
allSame [] = False
allSame [_] = True
allSame (x0:x1:xs) = x0 == x1 && allSame (x0:xs)
inferCase :: Term -> Typ -> [(Name,Typ)] -> TC Typ
inferCase t ty brs =
case ty of
Def d [] -> do
def <- view $ ddefs . at d
case def of
Just cs -> do
checkEquality "Labels are not equal." (sort cs) (map fst brs)
return $ if allSame (map snd brs) then snd (head brs)
else Case t brs
_ -> throwError $ "Case on a non data type: " ++ pretty ty
_ -> throwError $ "Case on a non data type: " ++ pretty ty
inferBranch :: (Name,Term) -> TC (Name,Typ)
inferBranch (n,t) = (,) n <$> inferTerm t
conTypeName :: Name -> TC Name
conTypeName c =
maybe (throwError $ "No such constructor " ++ pretty c) return =<< view (ctyps . at c)
def0 :: Name -> Term
def0 x = Def x []
conType :: Name -> TC Typ
conType = fmap def0 . conTypeName
inferTerm :: Term -> TC Typ
inferTerm e0 = case e0 of
Lit _ -> return int
TTyp -> return TTyp -- type-in-type
Def x es -> inferDef x es
Lam arg t -> TFun arg <$> checkVarDec arg (inferTerm t)
Con n -> conType n
Case t brs -> join $ inferCase t <$> inferTerm t <*> mapM inferBranch brs
Proc{} -> throwError "inferTerm: NProc"
TFun arg s -> checkVarDec arg (checkTyp s) >> return TTyp
TSig arg s -> checkVarDec arg (checkTyp s) >> return TTyp
TProto sessions -> checkSessions sessions >> return TTyp
checkTerm :: Typ -> Term -> TC ()
checkTerm typ e = inferTerm e >>= checkTypeEquivalence typ
checkMaybeTerm :: Typ -> Maybe Term -> TC ()
checkMaybeTerm _ Nothing = return ()
checkMaybeTerm typ (Just tm) = checkTerm typ tm
inferDef :: Name -> [Term] -> TC Typ
inferDef f es = do
mtyp <- view $ evars . at f
case mtyp of
Just typ -> checkApp typ es
Nothing -> throwError $ "unknown definition " ++ unName f
unDefTC :: Term -> TC Term
unDefTC tm = unDef <$> view edefs <*> return tm
checkApp :: Typ -> [Term] -> TC Typ
checkApp typ [] = return typ
checkApp typ (e:es) = do
typ' <- unDefTC typ
case typ' of
TFun (Arg x t) s -> do
checkTerm t e
checkApp (subst1 (x,e) s) es
_ -> throwError "checkApp: impossible"
debug :: [Msg] -> TC ()
debug xs = do
v <- view verbosity
debugTraceWhen v xs (return ())
assert :: Bool -> [Msg] -> TC ()
assert True _ = return ()
assert False msgs = throwError (unlines msgs)
assertEqual :: Eq a => a -> a -> [Msg] -> TC ()
assertEqual x y = assert (x == y)
data CheckOpts = CheckOpts { _debugChecker :: Bool }
$(makeLenses ''CheckOpts)
defaultCheckOpts :: CheckOpts
defaultCheckOpts = CheckOpts False
runTC :: CheckOpts -> TC a -> Err a
runTC opts tc = runReaderT (unTC tc) (emptyTCEnv & verbosity .~ (opts ^. debugChecker))
| jyp/ling | Ling/Term/Checker.hs | bsd-3-clause | 5,990 | 0 | 19 | 1,503 | 2,294 | 1,139 | 1,155 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
-- | This module communicates and manages the state of clients
-- connected to the server.
module Hulk.Client
where
import Hulk.Auth
import Hulk.Types
import Control.Monad.RWS hiding (pass)
import Data.CaseInsensitive (mk)
import Data.Char
import Data.List
import Data.List.Split
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Set as S
import Data.Text (Text, pack)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8,encodeUtf8)
import Data.Time hiding (readTime)
import Network.FastIRC (Command (..), CommandArg, Message (..), UserSpec(..))
import qualified Network.FastIRC as IRC
import Prelude hiding (log)
--------------------------------------------------------------------------------
-- * Top-level dispatchers
-- | Run the client monad.
handleCommand
:: Config -- ^ Server configuration.
-> HulkState -- ^ Server state.
-> UTCTime -- ^ Current time.
-> Conn -- ^ Current client connection.
-> (String,String) -- ^ Authorization info.
-> Command -- ^ The command.
-> ((), HulkState, [HulkWriter]) -- ^ The new transformed state and any instructions.
handleCommand config state' now conn auth cmd = do
runRWS (runHulk (handleCmd cmd))
(HulkReader now conn config Nothing auth)
state'
-- | Handle an incoming command.
handleCmd :: Command -- ^ A command which shouldn't be logged (e.g. PASS).
-> Hulk ()
handleCmd cmd = do
case cmd of
PassCmd (decodeUtf8 -> pass) -> do
incoming cmd
asUnregistered $ handlePass pass
StringCmd "PINGPONG" _ -> do
incoming cmd
handlePingPong
_ -> handleMsgSafeToLog cmd
-- | Handle commands that are safe to log.
handleMsgSafeToLog :: Command -- ^ A command which is safe to log
-- (PONG, NICK, etc.).
-> Hulk ()
handleMsgSafeToLog cmd = do
incoming cmd
updateLastPong
case cmd of
PongCmd{} -> handlePong
NickCmd (decodeUtf8 -> nick) _ -> handleNick nick
PingCmd (decodeUtf8 -> param) _ -> handlePing param
UserCmd (decodeUtf8 -> user) _ _ (decodeUtf8 -> realname) ->
asUnregistered $ handleUser user realname
QuitCmd mmsg ->
handleQuit RequestedQuit
(maybe "Quit (no message given)"
decodeUtf8
mmsg)
StringCmd "DISCONNECT" _ ->
handleQuit SocketQuit "Connection lost."
_ -> handleMsgReg'd cmd
-- | Handle commands that can only be used when registered.
handleMsgReg'd :: Command -- ^ A command that users use after
-- registration (e.g. JOIN, PART, etc.).
-> Hulk ()
handleMsgReg'd cmd =
asRegistered $
case cmd of
JoinCmd names ->
mapM_ handleJoin (map decodeUtf8 (M.keys names))
PartCmd names mmsg ->
mapM_ (flip handlePart (maybe "" decodeUtf8 mmsg))
(map decodeUtf8 (S.toList names))
PrivMsgCmd targets msg ->
mapM_ (flip handlePrivmsg (decodeUtf8 msg))
(map decodeUtf8 (S.toList targets))
TopicCmd chan (fmap decodeUtf8 -> Just topic) -> handleTopic (decodeUtf8 chan) topic
NoticeCmd targets msg ->
mapM_ (flip handleNotice (decodeUtf8 msg))
(map decodeUtf8 (S.toList targets))
-- TODO: Try to get these messages into the fastirc library.
StringCmd "AWAY" (listToMaybe -> mmsg) -> handleAway (fmap decodeUtf8 mmsg)
StringCmd "WHOIS" [nick] -> handleWhoIs (decodeUtf8 nick)
StringCmd "ISON" people -> handleIsOn (map decodeUtf8 people)
StringCmd "NAMES" [chan] -> handleNames (decodeUtf8 chan)
_ -> invalidCmd cmd
-- | Log an invalid cmd.
invalidCmd :: Command -- ^ The given command that we don't know how to handle.
-> Hulk ()
invalidCmd cmd = do
errorReply $ "Invalid or unknown message type, or not" <>
" enough parameters: " <> decodeUtf8 (IRC.showCommand cmd)
--------------------------------------------------------------------------------
-- * Command handlers
-- | Handle the AWAY command.
handleAway :: Maybe Text -> Hulk ()
handleAway mmsg = do
ref <- getRef
let adjust client@Client{..} = client { clientAwayMsg = mmsg }
modifyClients $ M.adjust adjust ref
-- | Handle the PONG command. This updates the user's βlast seenβ
-- value on file.
handlePong :: Hulk ()
handlePong = do
now <- asks readTime
withRegistered $ \RegUser{regUserUser=user} -> do
tell [UpdateUserData UserData { userDataUser = user
, userDataLastSeen = now
}]
-- | Handle the PINGPONG event. Disconnect the client if timedout.
handlePingPong :: Hulk ()
handlePingPong = do
lastPong <- clientLastPong <$> getClient
now <- asks readTime
let n = diffUTCTime now lastPong
if n > 60*4
then handleQuit RequestedQuit $ "Ping timeout: " <> pack (show n) <> " seconds"
else do hostname <- asks (connServerName . readConn)
thisCmdReply RPL_PING [hostname]
-- | Handle the PASS message.
handlePass :: Text -> Hulk ()
handlePass pass = do
modifyUnregistered $ \u -> u { unregUserPass = Just pass }
notice "Received password."
tryRegister
-- | Handle the USER message.
handleUser :: Text -> Text -> Hulk ()
handleUser user realname = do
withSentPass $
if validUser user
then do modifyUnregistered $ \u -> u { unregUserUser = Just (UserName (mk user))
, unregUserName = Just realname }
notice "Recieved user details."
tryRegister
else errorReply "Invalid user format."
-- | Handle the USER message.
handleNick :: Text -> Hulk ()
handleNick nick' =
withSentPass $
withValidNick nick' $ \nick ->
ifNotMyNick nick $
ifUniqueNick nick (updateNickAndTryRegistration nick)
Nothing
where updateNickAndTryRegistration nick = do
ref <- getRef
withRegistered $ \RegUser{regUserNick=rnick} ->
modifyNicks $ M.delete rnick
withUnregistered $ \UnregUser{unregUserNick=rnick} ->
maybe (return ()) (modifyNicks . M.delete) rnick
modifyNicks $ M.insert nick ref
modifyUnregistered $ \u -> u { unregUserNick = Just nick }
tryRegister
asRegistered $ do
thisClientReply RPL_NICK [nickText nick]
(myChannels >>=) $ mapM_ $ \Channel{..} -> do
channelReply channelName RPL_NICK [nickText nick] ExcludeMe
modifyRegistered $ \u -> u { regUserNick = nick }
-- | Handle the PING message.
handlePing :: Text -> Hulk ()
handlePing p = do
hostname <- asks (connServerName . readConn)
thisServerReply RPL_PONG [hostname,p]
-- | Handle the QUIT message.
handleQuit :: QuitType -> Text -> Hulk ()
handleQuit quitType msg = do
clearQuittedUser msg
when (quitType == RequestedQuit) $
tell [Close]
-- | Handle the TELL message.
handleTell :: Text -> Text -> Hulk ()
handleTell name msg = sendMsgTo RPL_NOTICE name msg
-- | Handle the NAMES list request.
handleNames :: Text -> Hulk ()
handleNames chan = do
withValidChanName chan sendNamesList
-- | Handle the JOIN message.
handleJoin :: Text -> Hulk ()
handleJoin chans = do
let names = T.split (==',') chans
forM_ names $ flip withValidChanName $ \name -> do
exists <- M.member name <$> gets stateChannels
unless exists $ insertChannel name
joined <- inChannel name
unless joined $ joinChannel name
-- | Handle the PART message.
handlePart :: Text -> Text -> Hulk ()
handlePart name msg =
withValidChanName name $ \vname -> do
removeFromChan vname
channelReply vname RPL_PART [msg] IncludeMe
-- | Handle the TOPIC message.
handleTopic :: Text -> Text -> Hulk ()
handleTopic name' topic =
withValidChanName name' $ \name -> do
let setTopic c = c { channelTopic = Just topic }
modifyChannels $ M.adjust setTopic name
channelReply name RPL_TOPIC [channelNameText name,topic] IncludeMe
-- | Handle the PRIVMSG message.
handlePrivmsg :: Text -> Text -> Hulk ()
handlePrivmsg name msg = do
sendMsgTo RPL_PRIVMSG name msg
historyLog RPL_PRIVMSG [name,msg]
-- | Handle the NOTICE message.
handleNotice :: Text -> Text -> Hulk ()
handleNotice name msg = sendMsgTo RPL_NOTICE name msg
-- | Handle WHOIS message.
handleWhoIs :: Text -> Hulk ()
handleWhoIs nick' =
withValidNick nick' $ \nick ->
withClientByNick nick $ \Client{..} ->
withRegUserByNick nick $ \RegUser{..} -> do
thisNickServerReply RPL_WHOISUSER
[nickText regUserNick
,userText regUserUser
,clientHostname
,"*"
,regUserName]
thisNickServerReply RPL_ENDOFWHOIS
[nickText regUserNick
,"End of WHOIS list."]
-- | Handle the ISON ('is on?') message.
handleIsOn :: [Text] -> Hulk ()
handleIsOn (catMaybes . map readNick -> nicks') =
asRegistered $ do
online <- catMaybes <$> mapM regUserByNick nicks'
let nicks = T.unwords $ map (nickText.regUserNick) online
unless (T.null nicks) $ thisNickServerReply RPL_ISON [nicks <> " "]
--------------------------------------------------------------------------------
-- * General actions
-- | Send a message to a user or a channel (it figures it out).
sendMsgTo :: RPL -> Text -> Text -> Hulk ()
sendMsgTo typ name' msg =
if validChannel name'
then withValidChanName name' $ \name ->
channelReply name typ [channelNameText name,msg] ExcludeMe
else userReply name' typ [name',msg]
--------------------------------------------------------------------------------
-- * Users
-- | Is a username valid?
validUser :: Text -> Bool
validUser = validNick
-- | Get the username.
getUsername :: Hulk (Maybe UserName)
getUsername = do
user <- getUser
return $ case user of
Unregistered (UnregUser{unregUserUser=username}) -> username
Registered (RegUser{regUserUser=username}) -> Just username
-- | Get the current connection ref.
getRef :: Hulk Ref
getRef = connRef <$> asks readConn
-- | Bump off the given nick.
bumpOff :: Nick -> Hulk ()
bumpOff nick = ifNotMyNick nick $ do
notice $ "Bumping off user " <> nickText nick <> "β¦"
withClientByNick nick $ \Client{clientRef=ref} ->
local (\r -> r { readConn = (readConn r) { connRef = ref } }) $ do
clearQuittedUser msg
tell [Bump ref]
where msg = "Bumped off."
-- | Clear a quitted user from channels and nick list, and notify
-- people in channels of their leaving.
clearQuittedUser :: Text -> Hulk ()
clearQuittedUser msg = do
(myChannels >>=) $ mapM_ $ \Channel{..} -> do
channelReply channelName RPL_QUIT [msg] ExcludeMe
removeFromChan channelName
withRegistered $ \RegUser{regUserNick=nick} -> do
modifyNicks $ M.delete nick
withUnregistered $ \UnregUser{unregUserNick=nick} -> do
maybe (return ()) (modifyNicks . M.delete) nick
ref <- getRef
modifyClients $ M.delete ref
notice msg
-- | Update the last pong reply time.
updateLastPong :: Hulk ()
updateLastPong = do
ref <- getRef
now <- asks readTime
let adjust client@Client{..} = client { clientLastPong = now }
modifyClients $ M.adjust adjust ref
-- | Send a client reply to a user.
userReply :: Text -> RPL -> [Text] -> Hulk ()
userReply nick' typ ps =
withValidNick nick' $ \nick ->
withClientByNick nick $ \Client{..} ->
clientReply clientRef typ ps
-- | Perform an action with a registered user by its nickname.
withRegUserByNick :: Nick -> (RegUser -> Hulk ()) -> Hulk ()
withRegUserByNick nick m = do
user <- regUserByNick nick
case user of
Just user' -> m user'
Nothing -> sendNoSuchNick nick
-- | Send the RPL_NOSUCHNICK reply.
sendNoSuchNick :: Nick -> Hulk ()
sendNoSuchNick nick =
thisServerReply ERR_NOSUCHNICK [nickText nick,"No such nick."]
-- | Modify the current user.
modifyUser :: (User -> User) -> Hulk ()
modifyUser f = do
ref <- getRef
let modUser c = c { clientUser = f (clientUser c) }
modClient = M.adjust modUser ref
modify $ \env -> env { stateClients = modClient (stateClients env) }
-- | Get the current client's user.
getUser :: Hulk User
getUser = clientUser <$> getClient
--------------------------------------------------------------------------------
-- * Clients
-- | Get the current client.
getClientByRef :: Ref -> Hulk (Maybe Client)
getClientByRef ref = do
clients <- gets stateClients
return $ M.lookup ref clients
-- | Get a client by nickname.
clientByNick :: Nick -> Hulk (Maybe Client)
clientByNick nick = do
clients <- gets stateClients
(M.lookup nick >=> (`M.lookup` clients)) <$> gets stateNicks
-- | Perform an action with a client by nickname.
withClientByNick :: Nick -> (Client -> Hulk ()) -> Hulk ()
withClientByNick nick m = do
client' <- clientByNick nick
case client' of
Nothing -> sendNoSuchNick nick
Just client@Client{..}
| isRegistered clientUser -> m client
| otherwise -> sendNoSuchNick nick
-- | Get the current client.
getClient :: Hulk Client
getClient = do
ref <- getRef
clients <- gets stateClients
case M.lookup ref clients of
Just client -> return $ client
Nothing -> makeNewClient
-- | Modify the clients table.
modifyClients :: (Map Ref Client -> Map Ref Client) -> Hulk ()
modifyClients f = modify $ \env -> env { stateClients = f (stateClients env) }
-- | Make a current client based on the current connection.
makeNewClient :: Hulk Client
makeNewClient = do
Conn{..} <- asks readConn
let client = Client { clientRef = connRef
, clientHostname = connHostname
, clientUser = newUnregisteredUser
, clientLastPong = connTime
, clientAwayMsg = Nothing
}
modifyClients $ M.insert connRef client
return client
--------------------------------------------------------------------------------
-- * Registration
-- | Get a registered user by nickname.
regUserByNick :: Nick -> Hulk (Maybe RegUser)
regUserByNick nick = do
c <- clientByNick nick
case clientUser <$> c of
Just (Registered u) -> return $ Just u
_ -> return Nothing
-- | Maybe get a registered user from a client.
clientRegUser :: Client -> Maybe RegUser
clientRegUser Client{..} =
case clientUser of
Registered u -> Just u
_ -> Nothing
-- | Modify the current user if unregistered.
modifyUnregistered :: (UnregUser -> UnregUser) -> Hulk ()
modifyUnregistered f = do
modifyUser $ \user ->
case user of
Unregistered user' -> Unregistered (f user')
u -> u
-- | Modify the current user if registered.
modifyRegistered :: (RegUser -> RegUser) -> Hulk ()
modifyRegistered f = do
modifyUser $ \user ->
case user of
Registered user' -> Registered (f user')
u -> u
-- | Only perform command if the client is registered.
asRegistered :: Hulk () -> Hulk ()
asRegistered m = do
registered <- isRegistered <$> getUser
when registered m
-- | Perform command with a registered user.
withRegistered :: (RegUser -> Hulk ()) -> Hulk ()
withRegistered m = do
user <- getUser
case user of
Registered user' -> m user'
_ -> return ()
-- | With sent pass.
withSentPass :: Hulk () -> Hulk ()
withSentPass m = do
asRegistered m
withUnregistered $ \UnregUser{..} -> do
case unregUserPass of
Just{} -> m
Nothing -> return ()
-- | Perform command with a registered user.
withUnregistered :: (UnregUser -> Hulk ()) -> Hulk ()
withUnregistered m = do
user <- getUser
case user of
Unregistered user' -> m user'
_ -> return ()
-- | Only perform command if the client is registered.
asUnregistered :: Hulk () -> Hulk ()
asUnregistered m = do
registered <- isRegistered <$> getUser
unless registered m
-- | Is a user registered?
isRegistered :: User -> Bool
isRegistered Registered{} = True
isRegistered _ = False
-- | Make a new unregistered user.
newUnregisteredUser :: User
newUnregisteredUser = Unregistered $ UnregUser {
unregUserName = Nothing
,unregUserNick = Nothing
,unregUserUser = Nothing
,unregUserPass = Nothing
}
-- | Try to register the user with the USER/NICK/PASS that have been given.
tryRegister :: Hulk ()
tryRegister =
withUnregistered $ \unreg -> do
check <- isAuthentic unreg
case check of
(True,Just (name,user,nick)) -> do
modifyUser $ \_ ->
Registered $ RegUser name nick user ""
sendWelcome
sendMotd
sendEvents
(False,Just{}) -> errorReply $ "Wrong user/pass."
_ -> return ()
isAuthentic :: UnregUser -> Hulk (Bool,Maybe (Text,UserName,Nick))
isAuthentic UnregUser{..} = do
let details = (,,,) <$> unregUserName
<*> unregUserNick
<*> unregUserUser
<*> unregUserPass
case details of
Nothing -> return (False,Nothing)
Just (name,nick,user,pass) -> do
(keystr,passwords) <- asks readAuth
let authentic = authenticate keystr passwords (userText user) pass
return (authentic,Just (name,user,nick))
--------------------------------------------------------------------------------
-- * Nicknames
-- | Read a valid nick.
readNick :: Text -> Maybe Nick
readNick n | validNick n = Just $ NickName (mk n)
| otherwise = Nothing
-- | Modify the nicks mapping.
modifyNicks :: (Map Nick Ref -> Map Nick Ref) -> Hulk ()
modifyNicks f = modify $ \env -> env { stateNicks = f (stateNicks env) }
-- | With a valid nickname, perform an action.
withValidNick :: Text -> (Nick -> Hulk ()) -> Hulk ()
withValidNick nick m
| validNick nick = m (NickName (mk nick))
| otherwise = errorReply $ "Invalid nick format: " <> nick
-- | Perform an action if a nickname is unique, otherwise send error.
ifUniqueNick :: Nick -> Hulk () -> Maybe ((Text -> Hulk ()) -> Hulk ()) -> Hulk ()
ifUniqueNick nick then_m else_m = do
clients <- gets stateClients
client <- (M.lookup nick >=> (`M.lookup` clients)) <$> gets stateNicks
case client of
Nothing -> then_m
Just{} -> do
case else_m of
Just else_m' -> else_m' error_reply
Nothing -> error_reply ""
where error_reply x = thisServerReply ERR_NICKNAMEINUSE
[nickText nick,"Nick is already in use." <> x]
-- | Is a nickname valid? Digit/letter or one of these: -_/\\;()[]{}?`'
validNick :: Text -> Bool
validNick s = T.all ok s && T.length s > 0 where
ok c = isDigit c || isLetter c || elem c ("-_/\\;()[]{}?`'"::String)
-- | If the given nick is not my nick name, β¦.
ifNotMyNick :: Nick -> Hulk () -> Hulk ()
ifNotMyNick nick m = do
user <- getUser
case user of
Registered RegUser{..} | regUserNick /= nick -> m
Unregistered UnregUser{..} | unregUserNick /= Just nick -> m
_ -> return ()
--------------------------------------------------------------------------------
-- * Channels
-- | Valid channel name?
validChannel :: Text -> Bool
validChannel (T.uncons -> Just ('#',cs)) = T.all ok cs && T.length cs > 0 where
ok c = isDigit c || isLetter c || elem c ("-_/\\;()[]{}?`'"::String)
validChannel _ = False
-- | Remove a user from a channel.
removeFromChan :: ChannelName -> Hulk ()
removeFromChan name = do
ref <- getRef
let remMe c = c { channelUsers = S.delete ref (channelUsers c) }
modifyChannels $ M.adjust remMe name
-- | Get channels that the current client is in.
myChannels :: Hulk [Channel]
myChannels = do
ref <- getRef
filter (S.member ref . channelUsers) . map snd . M.toList <$> gets stateChannels
-- | Join a channel.
joinChannel :: ChannelName -> Hulk ()
joinChannel name = do
ref <- getRef
let addMe c = c { channelUsers = S.insert ref (channelUsers c) }
modifyChannels $ M.adjust addMe name
channelReply name RPL_JOIN [channelNameText name] IncludeMe
sendNamesList name
withChannel name $ \Channel{..} -> do
case channelTopic of
Just topic -> thisServerReply RPL_TOPIC [channelNameText name,topic]
Nothing -> return ()
-- | Send the names list of a channel.
sendNamesList :: ChannelName -> Hulk ()
sendNamesList name = do
asRegistered $
withChannel name $ \Channel{..} -> do
clients <- catMaybes <$> mapM getClientByRef (S.toList channelUsers)
let nicks = map regUserNick . catMaybes . map clientRegUser $ clients
forM_ (chunksOf 10 nicks) $ \nicks' ->
thisNickServerReply RPL_NAMEREPLY ["@",channelNameText name
,T.unwords $ map nickText nicks']
thisNickServerReply RPL_ENDOFNAMES [channelNameText name
,"End of /NAMES list."]
-- | Am I in a channel?
inChannel :: ChannelName -> Hulk Bool
inChannel name = do
chan <- M.lookup name <$> gets stateChannels
case chan of
Nothing -> return False
Just Channel{..} -> (`S.member` channelUsers) <$> getRef
-- | Insert a new channel.
insertChannel :: ChannelName -> Hulk ()
insertChannel name = modifyChannels $ M.insert name newChan where
newChan = Channel { channelName = name
, channelTopic = Nothing
, channelUsers = S.empty
}
-- | Modify the channel map.
modifyChannels :: (Map ChannelName Channel -> Map ChannelName Channel)
-> Hulk ()
modifyChannels f = modify $ \e -> e { stateChannels = f (stateChannels e) }
withValidChanName :: Text -> (ChannelName -> Hulk ())
-> Hulk ()
withValidChanName name m
| validChannel name = m $ ChannelName (mk name)
| otherwise = errorReply $ "Invalid channel name: " <> name
-- | Perform an action with an existing channel, sends error if not exists.
withChannel :: ChannelName -> (Channel -> Hulk ()) -> Hulk ()
withChannel name m = do
chan <- M.lookup name <$> gets stateChannels
case chan of
Nothing -> thisServerReply ERR_NOSUCHCHANNEL [channelNameText name
,"No such channel."]
Just chan' -> m chan'
-- | Send a client reply to everyone in a channel.
channelReply :: ChannelName -> RPL -> [Text]
-> ChannelReplyType
-> Hulk ()
channelReply name cmd params typ = do
withChannel name $ \Channel{..} -> do
ref <- getRef
forM_ (S.toList channelUsers) $ \theirRef -> do
unless (typ == ExcludeMe && ref == theirRef) $
clientReply theirRef cmd params
--------------------------------------------------------------------------------
-- * Client replies
-- | Send a client reply to the current client.
thisClientReply :: RPL -> [Text] -> Hulk ()
thisClientReply typ params = do
ref <- getRef
clientReply ref typ params
-- | Send a client reply of the given type with the given params, on
-- the given connection reference.
clientReply :: Ref -> RPL -> [Text] -> Hulk ()
clientReply ref typ params = do
withRegistered $ \user -> do
client <- getClient
msg <- newClientMsg client user typ params
reply ref msg
-- | Make a new IRC message from the current client.
newClientMsg :: Client -> RegUser -> RPL -> [Text]
-> Hulk Message
newClientMsg Client{..} RegUser{..} cmd ps = do
return (Message (Just (User (encodeUtf8 (nickText regUserNick))
(encodeUtf8 (userText regUserUser))
(encodeUtf8 clientHostname)))
(makeCommand cmd ps))
--------------------------------------------------------------------------------
-- * Server replies
-- | Send the welcome message.
sendWelcome :: Hulk ()
sendWelcome = do
withRegistered $ \RegUser{..} -> do
thisNickServerReply RPL_WELCOME ["Welcome."]
-- | Send the MOTD.
sendMotd :: Hulk ()
sendMotd = do
asRegistered $ do
thisNickServerReply RPL_MOTDSTART ["MOTD"]
motd <- fmap (fmap T.lines) (asks readMotd)
let motdLine line = thisNickServerReply RPL_MOTD [line]
case motd of
Nothing -> motdLine "None."
Just lines' -> mapM_ motdLine lines'
thisNickServerReply RPL_ENDOFMOTD ["/MOTD."]
-- | Send events that the user missed.
sendEvents :: Hulk ()
sendEvents = do
chans <- configLogChans <$> asks readConfig
unless (null chans) $ do
withRegistered $ \RegUser{regUserUser=user} -> do
ref <- getRef
forM_ chans handleJoin
tell [SendEvents ref user]
--------------------------------------------------------------------------------
-- * Output functions
-- | Send a message reply.
notice :: Text -> Hulk ()
notice msg = thisServerReply RPL_NOTICE ["*",msg]
thisNickServerReply :: RPL -> [Text] -> Hulk ()
thisNickServerReply typ params = do
withRegistered $ \RegUser{regUserNick=nick} ->
thisServerReply typ (nickText nick : params)
-- | Send a server reply of the given type with the given params.
thisServerReply :: RPL -> [Text] -> Hulk ()
thisServerReply typ params = do
ref <- getRef
serverReply ref typ params
-- | Send a server reply of the given type with the given params.
serverReply :: Ref -> RPL -> [Text] -> Hulk ()
serverReply ref typ params = do
msg <- newServerMsg typ params
reply ref msg
-- | Make a new IRC message from the server.
newServerMsg :: RPL -> [Text] -> Hulk Message
newServerMsg cmd ps = do
hostname <- asks (connServerName.readConn)
return (Message (Just (Nick (encodeUtf8 hostname)))
(makeCommand cmd ps))
-- | Send a cmd reply of the given type with the given params.
thisCmdReply :: RPL -> [Text] -> Hulk ()
thisCmdReply typ params = do
ref <- getRef
cmdReply ref typ params
-- | Send a cmd reply of the given type with the given params.
cmdReply :: Ref -> RPL -> [Text] -> Hulk ()
cmdReply ref typ params = do
let msg = newCmdMsg typ params
reply ref msg
-- | Send an error reply.
errorReply :: Text -> Hulk ()
errorReply m = do
notice $ "ERROR: " <> m
log $ "ERROR: " <> m
-- | Send a message reply.
reply :: Ref -> Message -> Hulk ()
reply ref msg = do
outgoing msg
tell . return $ MessageReply ref msg
-- | Log an incoming line.
incoming :: Command -> Hulk ()
incoming = log . ("<- " <>) . decodeUtf8 . IRC.showCommand
-- | Log an outgoing line.
outgoing :: Message -> Hulk ()
outgoing msg = do
ref <- getRef
tell [outgoingWriter ref msg]
-- | Log a line.
log :: Text -> Hulk ()
log line = do
ref <- getRef
tell . return . LogReply $ pack (show (unRef ref)) <> ": " <> line
-- | Make a writer reply.
outgoingWriter :: Ref -> Message -> HulkWriter
outgoingWriter ref =
LogReply .
(pack (show (unRef ref)) <>) .
(": -> " <>) .
decodeUtf8 .
IRC.showMessage
historyLog :: RPL -> [Text] -> Hulk ()
historyLog rpl params = do
chans <- asks (configLogChans . readConfig)
unless (null chans) $ do
withRegistered $ \RegUser{regUserUser=name} -> do
let send = tell [SaveLog (userText name) rpl params]
case (rpl,params) of
(RPL_PRIVMSG,[chan])
| chan `elem` chans -> send
| otherwise -> return ()
_ -> send
--------------------------------------------------------------------------------
-- * Command Construction
-- | Make a command.
makeCommand :: RPL -> [Text] -> Command
makeCommand rpl xs = fromRPL rpl (map encodeUtf8 xs)
-- | Convert from a reply to an appropriate protocol format.
fromRPL :: RPL -> ([CommandArg] -> Command)
fromRPL RPL_NICK = StringCmd "NICK"
fromRPL RPL_PONG = StringCmd "PONG"
fromRPL RPL_QUIT = StringCmd "QUIT"
fromRPL RPL_JOIN = StringCmd "JOIN"
fromRPL RPL_NOTICE = StringCmd "NOTICE"
fromRPL RPL_PART = StringCmd "PART"
fromRPL RPL_PRIVMSG = StringCmd "PRIVMSG"
fromRPL RPL_JOINS = StringCmd "JOIN"
fromRPL RPL_TOPIC = StringCmd "TOPIC"
fromRPL RPL_PING = StringCmd "PING"
fromRPL RPL_WHOISUSER = NumericCmd 311
fromRPL RPL_ISON = NumericCmd 303
fromRPL RPL_NAMEREPLY = NumericCmd 353
fromRPL RPL_ENDOFNAMES = NumericCmd 366
fromRPL RPL_WELCOME = NumericCmd 001
fromRPL RPL_MOTDSTART = NumericCmd 375
fromRPL RPL_MOTD = NumericCmd 372
fromRPL RPL_ENDOFMOTD = NumericCmd 376
fromRPL RPL_WHOISIDLE = NumericCmd 317
fromRPL RPL_WHOISCHANNELS = NumericCmd 319
fromRPL RPL_ENDOFWHOIS = NumericCmd 318
fromRPL ERR_NICKNAMEINUSE = NumericCmd 433
fromRPL ERR_NOSUCHNICK = NumericCmd 401
fromRPL ERR_NOSUCHCHANNEL = NumericCmd 403
-- | Make a new IRC message from the cmd.
newCmdMsg :: RPL -> [Text] -> Message
newCmdMsg cmd ps = Message Nothing (makeCommand cmd ps)
| chrisdone/hulk | src/Hulk/Client.hs | bsd-3-clause | 29,110 | 0 | 21 | 7,315 | 8,226 | 4,084 | 4,142 | 620 | 10 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Solver
import Performer
import Parser
import Types
import Control.Concurrent
import Control.Monad
import Control.Exception
import System.Timeout
performOperations :: [Operation] -> IO ()
performOperations [] = return ()
performOperations (Move _ PHua:ops) = performOperations ops
{- performOperations op@(Move _ (PTR _):ops) = do -}
{- print (head op) -}
{- mousemove'' (0, 0) -- don't block -}
{- let seriesPTR = length $ takeWhile isMoveToPTR ops -}
{- threadDelay $ 300000 * (seriesPTR + 1) -}
{- return op -}
performOperations (op:ops) = do
print op
performOperation op
if all isMoveToPTR ops -- this sometimes will fail
then do
performOperation (head ops)
threadDelay $ 350000 * length ops
else performOperations ops
main :: IO ()
main = do
{- b <- getBoard -}
{- print . length . dfs $ b -}
main'
main' :: IO ()
main' = do
{- threadDelay 1000000 -}
(b' :: Either SomeException Board) <- try getBoard
case b' of
Left err -> do
putStrLn "wait 1 more rounds"
getBoard' 1 >>= perform
Right b -> perform b
startNewGame
startNewGame :: IO ()
startNewGame = do
mousemove'' (1220, 728)
threadDelay 150000
mousedown
threadDelay 150000
mouseup
threadDelay 5000000
main'
isMoveToPTR :: Operation -> Bool
isMoveToPTR (Move _ (PTR _)) = True
isMoveToPTR _ = False
perform :: Board -> IO ()
perform b = do
r <- timeout 22000000 (return $! dfs b)
case r of
Nothing -> startNewGame
Just [] -> return ()
Just ops -> performOperations ops
{- print op -}
{- if all isMoveToPTR allop -}
{- then threadDelay 5000000 >> startNewGame -}
{- else do -}
{- performOperation op -}
{- r <- performOperations op_ -}
{- unless (null r) main' -}
finishedBoard :: Board
finishedBoard = Board (TLFull, TLFull, TLFull) HSSingleton
(TRTaken (Wan 9), TRTaken (Tong 9), TRTaken (Tiao 9)) (replicate 8 [])
getBoard' :: Int -> IO Board
getBoard' 0 = return finishedBoard -- something's wrong, or finished
getBoard' n = do
(b :: Either InvalidBoard Board) <- try getBoard
case b of
Left _ -> threadDelay 2000000 >> getBoard' (n - 1)
Right b' -> return b'
| Frefreak/solitaire-solver | app/Main.hs | bsd-3-clause | 2,410 | 0 | 13 | 681 | 634 | 313 | 321 | 62 | 3 |
module Lib
( getData
) where
import Data.RDF
parse :: String -> IO (Either ParseFailure HashMapS)
parse = parseURL (TurtleParser Nothing Nothing)
getData :: IO HashMapS
getData = do
r <- parse "http://wikidata.dbpedia.org/downloads/sample/wikidatawiki-20150330-raw-reified.ttl"
return $ fromEither r
| seantalts/hasktrip | src/Lib.hs | bsd-3-clause | 319 | 0 | 8 | 56 | 83 | 42 | 41 | 9 | 1 |
-- | Types used in LRC.
module Pos.Chain.Lrc.Types
( RichmenSet
, RichmenStakes
, FullRichmenData
) where
import Universum
import Pos.Core.Common (Coin, StakeholderId)
-- | Hashset of richmen (i. e. stakeholders whose stake is greater
-- than some threshold).
type RichmenSet = HashSet StakeholderId
-- | Richmen and their stakes.
type RichmenStakes = HashMap StakeholderId Coin
-- | Full richmen data consists of total stake at some point and stake
-- distribution among richmen.
type FullRichmenData = (Coin, RichmenStakes)
| input-output-hk/pos-haskell-prototype | chain/src/Pos/Chain/Lrc/Types.hs | mit | 580 | 0 | 5 | 132 | 74 | 49 | 25 | 9 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Vim.Netbeans
( Netbeans
, runNetbeans
, runForkedNetbeans
, NetbeansCallbacks(..)
, P.Event(..)
, P.BufId
, P.Color(..)
, P.AnnoTypeNum
, P.AnnoNum
, nextEvent
, tryNextEvent
-- commands
, addAnno
, close
, create
, defineAnnoType
, editFile
, endAtomic
, guard
, initDone
, insertDone
, setNetbeansBuffer
, clearNetbeansBuffer
, putBufferNumber
, raise
, removeAnno
, save
, saveDone
, setBufferNumber
, setDot
, setExitDelay
, setFullName
, setModified
, setUnmodified
, setReadonly
, setTitle
, setVisible
, showBalloon
, specialKeys
, startAtomic
, startDocumentListen
, stopDocumentListen
, unguard
-- functions
, getCursor
, getLength
, getAnno
, getModified
, getModifiedBuffer
, getText
, insert
, remove
, saveAndExit
)
where
import Control.Monad (forM_, forever, liftM)
import Control.Monad.Error (Error (..), ErrorT,
MonadError (..), runErrorT)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Reader (MonadReader (..),
ReaderT (..))
import Control.Monad.Trans (MonadTrans, lift, liftIO)
import GHC.IO.Handle (Handle, hClose, hFlush,
hPutStr, hSetBinaryMode)
import Network (PortID, accept, listenOn)
import System.IO (hGetContents, hPutStrLn,
stderr)
import Data.List (delete, find, isPrefixOf)
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Char
import Control.Applicative (Applicative (..), (<$>))
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (MVar, newMVar, putMVar,
takeMVar, withMVar)
import Control.Concurrent.STM.TChan (TChan, dupTChan,
isEmptyTChan, newTChan,
readTChan, tryReadTChan,
writeTChan)
import Control.Monad.STM (atomically)
import qualified Vim.Netbeans.Protocol as P
newtype Netbeans m a = Netbeans { unNetbeans :: ReaderT ConnState m a }
deriving ( Monad
, Functor
, Applicative
, MonadIO
, MonadTrans
, MonadReader ConnState
, MonadError e)
data ConnState = ConnState
{ sequenceCounter :: MVar Int
, connHandle :: MVar Handle
, bufNumber :: MVar Int
, annoTypeNumber :: MVar Int
, annoNumber :: MVar Int
, protVersion :: String
, messageQueue :: TChan P.VimMessage
, parserMap :: MVar P.ParserMap
}
data NetbeansCallbacks m = NetbeansCallbacks
{ preAccept :: m
, initMsgReceived :: P.Event -> m
}
runNetbeans :: (Error e, MonadIO m, MonadError e m)
=> PortID -- ^ Port
-> String -- ^ Expected password
-> NetbeansCallbacks (m ()) -- ^ functions invoked during stages of life cycle
-> Netbeans m () -- ^ Monad to run
-> m () -- ^ Internal monad
runNetbeans port password callbacks = runForkedNetbeans port password callbacks []
runForkedNetbeans :: (Error e, MonadIO m, MonadError e m)
=> PortID -- ^ Port
-> String -- ^ Expected password
-> NetbeansCallbacks (m ()) -- ^ functions invoked during stages of life cycle
-> [Netbeans IO ()] -- ^ Monads to fork
-> Netbeans m () -- ^ Monad to run
-> m () -- ^ Internal monad
runForkedNetbeans port password callbacks forkedCallbacks (Netbeans runCallback) = do
s <- liftIO $ listenOn port
preAccept callbacks
(handleC, hostC, portC) <- liftIO $ accept s
liftIO $ hSetBinaryMode handleC True
pm <- liftIO $ newMVar []
q <- liftIO $ atomically $ newTChan
seqCounter <- liftIO $ newMVar 1
hMVar <- liftIO $ newMVar handleC
bufMVar <- liftIO $ newMVar 1
annoTypeMVar <- liftIO $ newMVar 1
annoMVar <- liftIO $ newMVar 1
liftIO $ forkIO $ messageReader pm handleC q
-- preflight
P.EventMessage _ _ authEvent@(P.Auth message) <- liftIO $ atomically $ readTChan q
initMsgReceived callbacks authEvent
version <- liftIO $ pollVersion q
initMsgReceived callbacks (P.Version version)
P.EventMessage _ _ P.StartupDone <- liftIO $ atomically $ readTChan q
initMsgReceived callbacks P.StartupDone
-- end preflight
let env = (ConnState
seqCounter
hMVar
bufMVar
annoTypeMVar
annoMVar
version
q
pm)
liftIO $ forM_ forkedCallbacks $ \forkedCallback ->
forkIO $ runReaderT (unNetbeans forkedCallback) env
runReaderT runCallback env
return ()
pollVersion :: TChan P.VimMessage -> IO String
pollVersion q = do
P.EventMessage _ _ (P.Version version) <- atomically $ readTChan q
return version
messageReader :: MVar P.ParserMap -> Handle -> TChan P.VimMessage -> IO ()
messageReader pm h q = do
contents <- hGetContents h
let lineList = lines contents
forM_ lineList $ \line -> do
m <- takeMVar pm
let msg = P.parseMessage m line
case msg of
Left s -> do
putMVar pm m
hPutStrLn stderr $ "Failed to parse message: " ++ s
Right eventMsg@(P.EventMessage _ _ _) -> do
putMVar pm m
atomically $ writeTChan q eventMsg
Right funcMsg@(P.ReplyMessage seqNo _) -> do
let m1 = filter ((seqNo /=) . fst) m
putMVar pm m1
atomically $ writeTChan q funcMsg
{- | Returns next event from the event queue. Blocks if no events available
at the moment. -}
nextEvent :: MonadIO m => Netbeans m (P.BufId, P.Event)
nextEvent = do
q <- messageQueue `liftM` ask
message <- liftIO $ atomically $ readTChan q
case message of
P.EventMessage bufId seqNo event -> return (bufId, event)
P.ReplyMessage _ _ -> nextEvent
{- | Returns Just next event from the event queue or Nothing if no events
available. -}
tryNextEvent :: MonadIO m => Netbeans m (Maybe (P.BufId, P.Event))
tryNextEvent = do
q <- messageQueue `liftM` ask
message <- liftIO $ atomically $ tryReadTChan q
case message of
Just (P.EventMessage bufId seqNo event) -> return $ Just (bufId, event)
Nothing -> return Nothing
Just (P.ReplyMessage _ _) -> tryNextEvent
takeReply :: MonadIO m => TChan P.VimMessage -> Int -> Netbeans m P.Reply
takeReply q seqNo = do
message <- liftIO $ atomically $ readTChan q
case message of
P.EventMessage _ _ _ -> takeReply q seqNo
P.ReplyMessage sn reply -> if seqNo == sn
then return reply
else takeReply q seqNo
yieldCommandNumber :: MonadIO m => Netbeans m Int
yieldCommandNumber = do
st <- ask
let seqNoMVar = sequenceCounter st
seqNo <- liftIO $ takeMVar seqNoMVar
liftIO $ putMVar seqNoMVar (seqNo + 1)
return seqNo
yieldBufferId :: MonadIO m => Netbeans m P.BufId
yieldBufferId = do
st <- ask
let bufNumberMVar = bufNumber st
bufNo <- liftIO $ takeMVar bufNumberMVar
liftIO $ putMVar bufNumberMVar (bufNo + 1)
return $ P.BufId bufNo
yieldAnnoTypeNum :: MonadIO m => Netbeans m P.AnnoTypeNum
yieldAnnoTypeNum = do
st <- ask
let annoMVar = annoTypeNumber st
annoNo <- liftIO $ takeMVar annoMVar
liftIO $ putMVar annoMVar (annoNo + 1)
return $ P.AnnoTypeNum annoNo
yieldAnnoNum :: MonadIO m => Netbeans m P.AnnoNum
yieldAnnoNum = do
st <- ask
let annoMVar = annoNumber st
annoNo <- liftIO $ takeMVar annoMVar
liftIO $ putMVar annoMVar (annoNo + 1)
return $ P.AnnoNum annoNo
sendCommand :: MonadIO m => P.BufId -> P.Command -> Netbeans m ()
sendCommand bufId cmdMsg = do
seqNo <- yieldCommandNumber
hMVar <- connHandle `liftM` ask
let message = P.printMessage $ P.CommandMessage bufId seqNo cmdMsg
liftIO $ withMVar hMVar $ \h -> do
hPutStrLn h message
hFlush h
sendFunction :: MonadIO m => P.BufId
-> P.Function
-> Parser P.Reply
-> Netbeans m P.Reply
sendFunction bufId funcMsg parser = do
seqNo <- yieldCommandNumber
hMVar <- connHandle `liftM` ask
q <- messageQueue `liftM` ask
mq <- liftIO $ atomically $ dupTChan q
pm <- parserMap `liftM` ask
m <- liftIO $ takeMVar pm
liftIO $ putMVar pm ((seqNo, parser) : m)
let message = P.printMessage $ P.FunctionMessage bufId seqNo funcMsg
liftIO $ withMVar hMVar $ \h -> do
hPutStrLn h message
hFlush h
reply <- takeReply mq seqNo
return reply
-- | Place an annotation in the buffer.
addAnno :: MonadIO m => P.BufId -- ^ buffer id where to place the annotation
-> P.AnnoTypeNum -- ^ id of annotation type
-> Int -- ^ offset of the annotation
-> Netbeans m P.AnnoNum -- ^ id of the placed annotation
addAnno bufId typeNum off = do
annoId <- yieldAnnoNum
sendCommand bufId $ P.AddAnno annoId typeNum off 0
return annoId
{- | Close the buffer. This leaves us without current buffer, very dangerous to
use -}
close :: MonadIO m => P.BufId -> Netbeans m ()
close bufId =
sendCommand bufId $ P.Close
{- | Creates a buffer without a name. Replaces the current buffer. (it's hidden
when it was changed). The Vim Controller should use this as the first command
for a file that is being opened. The sequence of commands could be:
* create
* setModified (no effect)
* startDocumentListen
* setTitle
* setFullName
-}
create :: MonadIO m => P.BufId -> Netbeans m ()
create bufId =
sendCommand bufId $ P.Close
{- | Define a type of annotation for this buffer.
Vim will define a sign for the annotation.
When \"glyphFile\" is empty, no text sign is used (new in protocol version 2.1).
When \"glyphFile\" is one or two characters long, a text sign is defined
(new in protocol version 2.1).
Note: the annotations will be defined in sequence, and the annotation type
number is later used with addAnno.
-}
defineAnnoType :: MonadIO m => P.BufId -- ^ buffer id
-> String -- ^ type name
-> String -- ^ tooltip
-> String -- ^ glyph file
-> P.Color -- ^ fg
-> P.Color -- ^ bg
-> Netbeans m P.AnnoTypeNum -- ^ type num
defineAnnoType bufId typeName toolTip glyphFile fg bg = do
annoTypeId <- yieldAnnoTypeNum
sendCommand bufId $
P.DefineAnnoType
annoTypeId
typeName
toolTip
glyphFile
fg
bg
return $ annoTypeId
{- | Set the name for the buffer and edit the file path, a string argument.
Normal way for the IDE to tell the editor to edit a file.
It will trigger an event fileOpened with a bufId of 0 but the buffer
has been assigned.
If the IDE is going to pass the file text to the editor use these commands
instead:
* setFullName
* insert
* initDone
New in version 2.1.
-}
editFile :: MonadIO m => String -- ^ file path
-> Netbeans m P.BufId -- ^ assigned buffer id
editFile path = do
bufId <- yieldBufferId
sendCommand bufId $ P.EditFile path
return bufId
{- | End an atomic operation. After startAtomic the screen is not changed until
endAtomic. Redraws the screen when necessary. -}
endAtomic :: MonadIO m => P.BufId -> Netbeans m ()
endAtomic bufId =
sendCommand bufId $ P.EndAtomic
{- | Mark an area in the buffer as guarded. This means it cannot be edited.
off and len are numbers and specify the text to be guarded.
-}
guard :: MonadIO m => P.BufId -- ^ buffer id
-> Int -- ^ off
-> Int -- ^ len
-> Netbeans m ()
guard bufId off len =
sendCommand bufId $ P.Guard off len
{- | Mark the buffer as ready for use. Implicitly makes the buffer the current
buffer. Fires the BufReadPost autocommand event. -}
initDone :: MonadIO m => P.BufId -> Netbeans m ()
initDone bufId =
sendCommand bufId $ P.InitDone
{- | Sent by Vim Controller to tell Vim an initial file insert is done.
This triggers a read message being printed. Prior to protocol version 2.3,
no read messages were displayed after opening a file.
New in protocol version 2.3. -}
insertDone :: MonadIO m => P.BufId -> Netbeans m ()
insertDone bufId =
sendCommand bufId $ P.InsertDone
{- | After invocation the buffer is owned by netbeans.
New in protocol version 2.2 -}
setNetbeansBuffer :: MonadIO m => P.BufId -> Netbeans m ()
setNetbeansBuffer bufId =
sendCommand bufId $ P.NetbeansBuffer True
{- | Clears netbeans' ownership of the buffer.
New in protocol version 2.2 -}
clearNetbeansBuffer :: MonadIO m => P.BufId -> Netbeans m ()
clearNetbeansBuffer bufId =
sendCommand bufId $ P.NetbeansBuffer False
{- | Associate a buffer number with the Vim buffer by the name
pathname, a string argument. To be used when the editor
reported editing another file to the IDE and the IDE needs to
tell the editor what buffer number it will use for this file.
Also marks the buffer as initialized.
New in version 2.1.
-}
putBufferNumber :: MonadIO m => String -- ^ pathname
-> Netbeans m P.BufId -- ^ buffer id
putBufferNumber pathname = do
bufId <- yieldBufferId
sendCommand bufId $ P.PutBufferNumber pathname
return bufId
{- | Bring the editor to the foreground. Only when Vim is run with GUI.
New in protocol version 2.1 -}
raise :: MonadIO m => P.BufId -> Netbeans m ()
raise bufId =
sendCommand bufId $ P.Raise
{- | Remove a previously placed annotation for this buffer.
serNum is the same number used in addAnno. -}
removeAnno :: MonadIO m => P.BufId -> P.AnnoNum -> Netbeans m ()
removeAnno bufId annoNum =
sendCommand bufId $ P.RemoveAnno annoNum
{- | Save the buffer when it was modified. The other side of the
interface is expected to write the buffer and invoke setModified to reset
the changed flag of the buffer. The writing is skipped when one of these
conditions is true:
* 'write' is not set
* the buffer is read-only
* the buffer does not have a file name
* 'buftype' disallows writing
New in version 2.2.
-}
save :: MonadIO m => P.BufId -> Netbeans m ()
save bufId =
sendCommand bufId $ P.Save
{- | Sent by Vim Controller to tell Vim a save is done. This triggers a save
message being printed. Prior to protocol version 2.3, no save messages were
displayed after a save.
New in protocol version 2.3.
-}
saveDone :: MonadIO m => P.BufId -> Netbeans m ()
saveDone bufId =
sendCommand bufId $ P.SaveDone
{- | Associate a buffer number with Vim buffer by the name pathname.
To be used when the editor reported editing another file to the IDE and
the IDE needs to tell the editor what buffer number it will use for this file.
Has the side effect of making the buffer the current buffer.
See putBufferNumber for a more useful command.
-}
setBufferNumber :: MonadIO m => String -> Netbeans m P.BufId
setBufferNumber pathname = do
bufId <- yieldBufferId
sendCommand bufId $ P.SetBufferNumber pathname
return bufId
{- | Make the buffer the current buffer and set the cursor at the specified
position. If the buffer is open in another window than make that window the
current window. If there are folds they are opened to make the cursor
line visible.
In protocol version 2.1 lnum/col can be used instead of off.
However this function doesn't support lnum/col.
-}
setDot :: MonadIO m => P.BufId -> Int -> Netbeans m ()
setDot bufId off =
sendCommand bufId $ P.SetDot off
{- | Set the delay for exiting to seconds, a number. This delay is used to
give the IDE a chance to handle things before really exiting.
The default delay is two seconds.
New in protocol version 2.1.
Obsolete in protocol version 2.3.
-}
setExitDelay :: MonadIO m => Int -> Netbeans m ()
setExitDelay seconds =
sendCommand (P.BufId 0) $ P.SetExitDelay seconds
{- | Set the file name to be used for a buffer to pathname, a string argument.
Used when the IDE wants to edit a file under control of the IDE.
This makes the buffer the current buffer, but does not read the file.
insert commands will be used next to set the contents.
-}
setFullName :: MonadIO m => P.BufId -> String -> Netbeans m ()
setFullName bufId pathname =
sendCommand bufId $ P.SetFullName pathname
-- | Mark the buffer as modified.
setModified :: MonadIO m => P.BufId -> Netbeans m ()
setModified bufId =
sendCommand bufId $ P.SetModified True
-- | Mark the buffer as unmodified.
setUnmodified :: MonadIO m => P.BufId -> Netbeans m ()
setUnmodified bufId =
sendCommand bufId $ P.SetModified False
{- | Set a file as readonly.
New in protocol version 2.3.
-}
setReadonly :: MonadIO m => P.BufId -> Netbeans m ()
setReadonly bufId =
sendCommand bufId $ P.SetReadOnly
{- | Set the title for the buffer to name, a string argument. The title is
only used for the Vim Controller functions, not by Vim.
-}
setTitle :: MonadIO m => P.BufId -> String -> Netbeans m ()
setTitle bufId name =
sendCommand bufId $ P.SetTitle name
-- | Go to the buffer.
setVisible :: MonadIO m => P.BufId -> Netbeans m ()
setVisible bufId =
sendCommand bufId $ P.SetVisible True
{- | Show a balloon (popup window) at the mouse pointer position, containing
text, a string argument. The balloon should disappear when the mouse is moved
more than a few pixels. Only when Vim is run with a GUI.
New in protocol version 2.1.
-}
showBalloon :: MonadIO m => P.BufId -> String -> Netbeans m ()
showBalloon bufId text =
sendCommand bufId $ P.ShowBalloon text
{- | Map a set of keys (mostly function keys) to be passed back to the Vim
Controller for processing. This lets regular IDE hotkeys be used from Vim.
Implemented in protocol version 2.3.
-}
specialKeys :: MonadIO m => P.BufId -> Netbeans m ()
specialKeys bufId =
sendCommand bufId $ P.SpecialKeys
{- | Begin an atomic operation. The screen will not be updated until
endAtomic is given.
-}
startAtomic :: MonadIO m => P.BufId -> Netbeans m ()
startAtomic bufId =
sendCommand bufId $ P.StartAtomic
{- | Mark the buffer to report changes to the IDE with the insert and
remove events. The default is to report changes.
-}
startDocumentListen :: MonadIO m => P.BufId -> Netbeans m ()
startDocumentListen bufId =
sendCommand bufId $ P.StartDocumentListen
{- | Mark the buffer to stop reporting changes to the IDE. Opposite of
startDocumentListen. NOTE: if netbeansBuffer was used to mark this buffer as a
NetBeans buffer, then the buffer is deleted in Vim. This is for compatibility
with Sun Studio 10.
-}
stopDocumentListen :: MonadIO m => P.BufId -> Netbeans m ()
stopDocumentListen bufId =
sendCommand bufId $ P.StopDocumentListen
{- | Opposite of guard, remove guarding for a text area. Also sets the
current buffer, if necessary. -}
unguard :: MonadIO m => P.BufId -> Int -> Int -> Netbeans m ()
unguard bufId off len =
sendCommand bufId $ P.Unguard off len
{- | Return the current buffer and cursor position.
bufID = buffer ID of the current buffer (if this is unknown -1 is used)
lnum = line number of the cursor (first line is one)
col = column number of the cursor (in bytes, zero based)
off = offset of the cursor in the buffer (in bytes)
New in version 2.1.
-}
getCursor :: MonadIO m => Netbeans m (P.BufId, Int, Int, Int)
getCursor = do
P.GetCursorReply bufId lnum col off <- sendFunction
(P.BufId 0)
P.GetCursor
P.getCursorReplyParser
-- TODO clarify situation with -1 buf id
return (bufId, lnum, col, off)
-- | Return the length of the buffer in bytes.
getLength :: MonadIO m => P.BufId -> Netbeans m Int
getLength bufId = do
P.GetLengthReply value <- sendFunction
bufId
P.GetLength
P.getLengthReplyParser
return value
-- | Return the line number of the annotation in the buffer.
getAnno :: MonadIO m => P.BufId -> Int -> Netbeans m Int
getAnno bufId serNum = do
P.GetAnnoReply lnum <- sendFunction
bufId
(P.GetAnno serNum)
P.getAnnoReplyParser
return lnum
{- | Return the number of buffers with changes.
When the result is zero it's safe to tell Vim to exit.
New in protocol version 2.1.
-}
getModified :: MonadIO m => Netbeans m Int
getModified = do
P.GetModifiedReply count <- sendFunction
(P.BufId 0)
P.GetModified
P.getModifiedReplyParser
return count
{- | Return zero if the buffer does not have changes,
one if it does have changes.
New in protocol version 2.1.
-}
getModifiedBuffer :: MonadIO m => P.BufId -> Netbeans m Bool
getModifiedBuffer bufId = do
P.GetModifiedReply count <- sendFunction
bufId
P.GetModified
P.getModifiedReplyParser
return $ case count of
0 -> False
_ -> True
-- | Return the contents of the buffer as a string.
getText :: MonadIO m => P.BufId -> Netbeans m String
getText bufId = do
P.GetTextReply text <- sendFunction
bufId
P.GetText
P.getTextReplyParser
return text
{- | Insert text before position off. text is a string argument, off a number.
text should have a \\n (newline) at the end of each line. Or \\r\\n when
fileformat is dos. When using insert in an empty buffer Vim will set
fileformat accordingly. When off points to the start of a line the text is
inserted above this line. Thus when off is zero lines are inserted before
the first line. When off points after the start of a line, possibly on the
NUL at the end of a line, the first line of text is appended to this line.
Further lines come below it.
-}
insert :: (Error e, MonadIO m, MonadError e m) => P.BufId -> Int -> String -> Netbeans m ()
insert bufId off text = do
replyMessage <- sendFunction
bufId
(P.Insert off text)
P.insertReplyParser
case replyMessage of
P.InsertReplySuccess -> return ()
P.InsertReplyError s -> throwError $ strMsg s
-- | Delete length bytes of text at position off. Both arguments are numbers.
remove :: (Error e, MonadIO m, MonadError e m) => P.BufId -> Int -> Int -> Netbeans m ()
remove bufId off len = do
replyMessage <- sendFunction
bufId
(P.Remove off len)
P.insertReplyParser
case replyMessage of
P.RemoveReplySuccess -> return ()
P.RemoveReplyError s -> throwError $ strMsg s
{- | Perform the equivalent of closing Vim: :confirm qall. If there are
no changed files or the user does not cancel the operation Vim exits and
no result is sent back. The IDE can consider closing the connection as
a successful result. If the user cancels the operation the number of modified
buffers that remains is returned and Vim does not exit.
New in protocol version 2.1.
-}
saveAndExit :: MonadIO m => Netbeans m ()
saveAndExit = do
seqNo <- yieldCommandNumber
hMVar <- connHandle `liftM` ask
q <- messageQueue `liftM` ask
mq <- liftIO $ atomically $ dupTChan q
let message = P.printMessage $ P.FunctionMessage (P.BufId 0) seqNo P.SaveAndExit
liftIO $ withMVar hMVar $ \h -> do
hPutStrLn h message
hFlush h
return ()
| ababkin/railoscopy | src/Vim/Netbeans.hs | mit | 24,879 | 0 | 22 | 7,509 | 5,022 | 2,494 | 2,528 | 440 | 3 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Test.AWS.Gen.CloudFront
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Test.AWS.Gen.CloudFront where
import Data.Proxy
import Test.AWS.Fixture
import Test.AWS.Prelude
import Test.Tasty
import Network.AWS.CloudFront
import Test.AWS.CloudFront.Internal
-- Auto-generated: the actual test selection needs to be manually placed into
-- the top-level so that real test data can be incrementally added.
--
-- This commented snippet is what the entire set should look like:
-- fixtures :: TestTree
-- fixtures =
-- [ testGroup "request"
-- [ testDeleteStreamingDistribution $
-- deleteStreamingDistribution
--
-- , testUpdateStreamingDistribution $
-- updateStreamingDistribution
--
-- , testCreateDistribution $
-- createDistribution
--
-- , testGetDistributionConfig $
-- getDistributionConfig
--
-- , testGetDistribution $
-- getDistribution
--
-- , testUpdateCloudFrontOriginAccessIdentity $
-- updateCloudFrontOriginAccessIdentity
--
-- , testDeleteCloudFrontOriginAccessIdentity $
-- deleteCloudFrontOriginAccessIdentity
--
-- , testListStreamingDistributions $
-- listStreamingDistributions
--
-- , testGetStreamingDistributionConfig $
-- getStreamingDistributionConfig
--
-- , testGetCloudFrontOriginAccessIdentityConfig $
-- getCloudFrontOriginAccessIdentityConfig
--
-- , testCreateStreamingDistribution $
-- createStreamingDistribution
--
-- , testCreateCloudFrontOriginAccessIdentity $
-- createCloudFrontOriginAccessIdentity
--
-- , testListCloudFrontOriginAccessIdentities $
-- listCloudFrontOriginAccessIdentities
--
-- , testGetInvalidation $
-- getInvalidation
--
-- , testListInvalidations $
-- listInvalidations
--
-- , testCreateInvalidation $
-- createInvalidation
--
-- , testGetCloudFrontOriginAccessIdentity $
-- getCloudFrontOriginAccessIdentity
--
-- , testGetStreamingDistribution $
-- getStreamingDistribution
--
-- , testUpdateDistribution $
-- updateDistribution
--
-- , testDeleteDistribution $
-- deleteDistribution
--
-- , testListDistributions $
-- listDistributions
--
-- ]
-- , testGroup "response"
-- [ testDeleteStreamingDistributionResponse $
-- deleteStreamingDistributionResponse
--
-- , testUpdateStreamingDistributionResponse $
-- updateStreamingDistributionResponse
--
-- , testCreateDistributionResponse $
-- createDistributionResponse
--
-- , testGetDistributionConfigResponse $
-- getDistributionConfigResponse
--
-- , testGetDistributionResponse $
-- getDistributionResponse
--
-- , testUpdateCloudFrontOriginAccessIdentityResponse $
-- updateCloudFrontOriginAccessIdentityResponse
--
-- , testDeleteCloudFrontOriginAccessIdentityResponse $
-- deleteCloudFrontOriginAccessIdentityResponse
--
-- , testListStreamingDistributionsResponse $
-- listStreamingDistributionsResponse
--
-- , testGetStreamingDistributionConfigResponse $
-- getStreamingDistributionConfigResponse
--
-- , testGetCloudFrontOriginAccessIdentityConfigResponse $
-- getCloudFrontOriginAccessIdentityConfigResponse
--
-- , testCreateStreamingDistributionResponse $
-- createStreamingDistributionResponse
--
-- , testCreateCloudFrontOriginAccessIdentityResponse $
-- createCloudFrontOriginAccessIdentityResponse
--
-- , testListCloudFrontOriginAccessIdentitiesResponse $
-- listCloudFrontOriginAccessIdentitiesResponse
--
-- , testGetInvalidationResponse $
-- getInvalidationResponse
--
-- , testListInvalidationsResponse $
-- listInvalidationsResponse
--
-- , testCreateInvalidationResponse $
-- createInvalidationResponse
--
-- , testGetCloudFrontOriginAccessIdentityResponse $
-- getCloudFrontOriginAccessIdentityResponse
--
-- , testGetStreamingDistributionResponse $
-- getStreamingDistributionResponse
--
-- , testUpdateDistributionResponse $
-- updateDistributionResponse
--
-- , testDeleteDistributionResponse $
-- deleteDistributionResponse
--
-- , testListDistributionsResponse $
-- listDistributionsResponse
--
-- ]
-- ]
-- Requests
testDeleteStreamingDistribution :: DeleteStreamingDistribution -> TestTree
testDeleteStreamingDistribution = req
"DeleteStreamingDistribution"
"fixture/DeleteStreamingDistribution.yaml"
testUpdateStreamingDistribution :: UpdateStreamingDistribution -> TestTree
testUpdateStreamingDistribution = req
"UpdateStreamingDistribution"
"fixture/UpdateStreamingDistribution.yaml"
testCreateDistribution :: CreateDistribution -> TestTree
testCreateDistribution = req
"CreateDistribution"
"fixture/CreateDistribution.yaml"
testGetDistributionConfig :: GetDistributionConfig -> TestTree
testGetDistributionConfig = req
"GetDistributionConfig"
"fixture/GetDistributionConfig.yaml"
testGetDistribution :: GetDistribution -> TestTree
testGetDistribution = req
"GetDistribution"
"fixture/GetDistribution.yaml"
testUpdateCloudFrontOriginAccessIdentity :: UpdateCloudFrontOriginAccessIdentity -> TestTree
testUpdateCloudFrontOriginAccessIdentity = req
"UpdateCloudFrontOriginAccessIdentity"
"fixture/UpdateCloudFrontOriginAccessIdentity.yaml"
testDeleteCloudFrontOriginAccessIdentity :: DeleteCloudFrontOriginAccessIdentity -> TestTree
testDeleteCloudFrontOriginAccessIdentity = req
"DeleteCloudFrontOriginAccessIdentity"
"fixture/DeleteCloudFrontOriginAccessIdentity.yaml"
testListStreamingDistributions :: ListStreamingDistributions -> TestTree
testListStreamingDistributions = req
"ListStreamingDistributions"
"fixture/ListStreamingDistributions.yaml"
testGetStreamingDistributionConfig :: GetStreamingDistributionConfig -> TestTree
testGetStreamingDistributionConfig = req
"GetStreamingDistributionConfig"
"fixture/GetStreamingDistributionConfig.yaml"
testGetCloudFrontOriginAccessIdentityConfig :: GetCloudFrontOriginAccessIdentityConfig -> TestTree
testGetCloudFrontOriginAccessIdentityConfig = req
"GetCloudFrontOriginAccessIdentityConfig"
"fixture/GetCloudFrontOriginAccessIdentityConfig.yaml"
testCreateStreamingDistribution :: CreateStreamingDistribution -> TestTree
testCreateStreamingDistribution = req
"CreateStreamingDistribution"
"fixture/CreateStreamingDistribution.yaml"
testCreateCloudFrontOriginAccessIdentity :: CreateCloudFrontOriginAccessIdentity -> TestTree
testCreateCloudFrontOriginAccessIdentity = req
"CreateCloudFrontOriginAccessIdentity"
"fixture/CreateCloudFrontOriginAccessIdentity.yaml"
testListCloudFrontOriginAccessIdentities :: ListCloudFrontOriginAccessIdentities -> TestTree
testListCloudFrontOriginAccessIdentities = req
"ListCloudFrontOriginAccessIdentities"
"fixture/ListCloudFrontOriginAccessIdentities.yaml"
testGetInvalidation :: GetInvalidation -> TestTree
testGetInvalidation = req
"GetInvalidation"
"fixture/GetInvalidation.yaml"
testListInvalidations :: ListInvalidations -> TestTree
testListInvalidations = req
"ListInvalidations"
"fixture/ListInvalidations.yaml"
testCreateInvalidation :: CreateInvalidation -> TestTree
testCreateInvalidation = req
"CreateInvalidation"
"fixture/CreateInvalidation.yaml"
testGetCloudFrontOriginAccessIdentity :: GetCloudFrontOriginAccessIdentity -> TestTree
testGetCloudFrontOriginAccessIdentity = req
"GetCloudFrontOriginAccessIdentity"
"fixture/GetCloudFrontOriginAccessIdentity.yaml"
testGetStreamingDistribution :: GetStreamingDistribution -> TestTree
testGetStreamingDistribution = req
"GetStreamingDistribution"
"fixture/GetStreamingDistribution.yaml"
testUpdateDistribution :: UpdateDistribution -> TestTree
testUpdateDistribution = req
"UpdateDistribution"
"fixture/UpdateDistribution.yaml"
testDeleteDistribution :: DeleteDistribution -> TestTree
testDeleteDistribution = req
"DeleteDistribution"
"fixture/DeleteDistribution.yaml"
testListDistributions :: ListDistributions -> TestTree
testListDistributions = req
"ListDistributions"
"fixture/ListDistributions.yaml"
-- Responses
testDeleteStreamingDistributionResponse :: DeleteStreamingDistributionResponse -> TestTree
testDeleteStreamingDistributionResponse = res
"DeleteStreamingDistributionResponse"
"fixture/DeleteStreamingDistributionResponse.proto"
cloudFront
(Proxy :: Proxy DeleteStreamingDistribution)
testUpdateStreamingDistributionResponse :: UpdateStreamingDistributionResponse -> TestTree
testUpdateStreamingDistributionResponse = res
"UpdateStreamingDistributionResponse"
"fixture/UpdateStreamingDistributionResponse.proto"
cloudFront
(Proxy :: Proxy UpdateStreamingDistribution)
testCreateDistributionResponse :: CreateDistributionResponse -> TestTree
testCreateDistributionResponse = res
"CreateDistributionResponse"
"fixture/CreateDistributionResponse.proto"
cloudFront
(Proxy :: Proxy CreateDistribution)
testGetDistributionConfigResponse :: GetDistributionConfigResponse -> TestTree
testGetDistributionConfigResponse = res
"GetDistributionConfigResponse"
"fixture/GetDistributionConfigResponse.proto"
cloudFront
(Proxy :: Proxy GetDistributionConfig)
testGetDistributionResponse :: GetDistributionResponse -> TestTree
testGetDistributionResponse = res
"GetDistributionResponse"
"fixture/GetDistributionResponse.proto"
cloudFront
(Proxy :: Proxy GetDistribution)
testUpdateCloudFrontOriginAccessIdentityResponse :: UpdateCloudFrontOriginAccessIdentityResponse -> TestTree
testUpdateCloudFrontOriginAccessIdentityResponse = res
"UpdateCloudFrontOriginAccessIdentityResponse"
"fixture/UpdateCloudFrontOriginAccessIdentityResponse.proto"
cloudFront
(Proxy :: Proxy UpdateCloudFrontOriginAccessIdentity)
testDeleteCloudFrontOriginAccessIdentityResponse :: DeleteCloudFrontOriginAccessIdentityResponse -> TestTree
testDeleteCloudFrontOriginAccessIdentityResponse = res
"DeleteCloudFrontOriginAccessIdentityResponse"
"fixture/DeleteCloudFrontOriginAccessIdentityResponse.proto"
cloudFront
(Proxy :: Proxy DeleteCloudFrontOriginAccessIdentity)
testListStreamingDistributionsResponse :: ListStreamingDistributionsResponse -> TestTree
testListStreamingDistributionsResponse = res
"ListStreamingDistributionsResponse"
"fixture/ListStreamingDistributionsResponse.proto"
cloudFront
(Proxy :: Proxy ListStreamingDistributions)
testGetStreamingDistributionConfigResponse :: GetStreamingDistributionConfigResponse -> TestTree
testGetStreamingDistributionConfigResponse = res
"GetStreamingDistributionConfigResponse"
"fixture/GetStreamingDistributionConfigResponse.proto"
cloudFront
(Proxy :: Proxy GetStreamingDistributionConfig)
testGetCloudFrontOriginAccessIdentityConfigResponse :: GetCloudFrontOriginAccessIdentityConfigResponse -> TestTree
testGetCloudFrontOriginAccessIdentityConfigResponse = res
"GetCloudFrontOriginAccessIdentityConfigResponse"
"fixture/GetCloudFrontOriginAccessIdentityConfigResponse.proto"
cloudFront
(Proxy :: Proxy GetCloudFrontOriginAccessIdentityConfig)
testCreateStreamingDistributionResponse :: CreateStreamingDistributionResponse -> TestTree
testCreateStreamingDistributionResponse = res
"CreateStreamingDistributionResponse"
"fixture/CreateStreamingDistributionResponse.proto"
cloudFront
(Proxy :: Proxy CreateStreamingDistribution)
testCreateCloudFrontOriginAccessIdentityResponse :: CreateCloudFrontOriginAccessIdentityResponse -> TestTree
testCreateCloudFrontOriginAccessIdentityResponse = res
"CreateCloudFrontOriginAccessIdentityResponse"
"fixture/CreateCloudFrontOriginAccessIdentityResponse.proto"
cloudFront
(Proxy :: Proxy CreateCloudFrontOriginAccessIdentity)
testListCloudFrontOriginAccessIdentitiesResponse :: ListCloudFrontOriginAccessIdentitiesResponse -> TestTree
testListCloudFrontOriginAccessIdentitiesResponse = res
"ListCloudFrontOriginAccessIdentitiesResponse"
"fixture/ListCloudFrontOriginAccessIdentitiesResponse.proto"
cloudFront
(Proxy :: Proxy ListCloudFrontOriginAccessIdentities)
testGetInvalidationResponse :: GetInvalidationResponse -> TestTree
testGetInvalidationResponse = res
"GetInvalidationResponse"
"fixture/GetInvalidationResponse.proto"
cloudFront
(Proxy :: Proxy GetInvalidation)
testListInvalidationsResponse :: ListInvalidationsResponse -> TestTree
testListInvalidationsResponse = res
"ListInvalidationsResponse"
"fixture/ListInvalidationsResponse.proto"
cloudFront
(Proxy :: Proxy ListInvalidations)
testCreateInvalidationResponse :: CreateInvalidationResponse -> TestTree
testCreateInvalidationResponse = res
"CreateInvalidationResponse"
"fixture/CreateInvalidationResponse.proto"
cloudFront
(Proxy :: Proxy CreateInvalidation)
testGetCloudFrontOriginAccessIdentityResponse :: GetCloudFrontOriginAccessIdentityResponse -> TestTree
testGetCloudFrontOriginAccessIdentityResponse = res
"GetCloudFrontOriginAccessIdentityResponse"
"fixture/GetCloudFrontOriginAccessIdentityResponse.proto"
cloudFront
(Proxy :: Proxy GetCloudFrontOriginAccessIdentity)
testGetStreamingDistributionResponse :: GetStreamingDistributionResponse -> TestTree
testGetStreamingDistributionResponse = res
"GetStreamingDistributionResponse"
"fixture/GetStreamingDistributionResponse.proto"
cloudFront
(Proxy :: Proxy GetStreamingDistribution)
testUpdateDistributionResponse :: UpdateDistributionResponse -> TestTree
testUpdateDistributionResponse = res
"UpdateDistributionResponse"
"fixture/UpdateDistributionResponse.proto"
cloudFront
(Proxy :: Proxy UpdateDistribution)
testDeleteDistributionResponse :: DeleteDistributionResponse -> TestTree
testDeleteDistributionResponse = res
"DeleteDistributionResponse"
"fixture/DeleteDistributionResponse.proto"
cloudFront
(Proxy :: Proxy DeleteDistribution)
testListDistributionsResponse :: ListDistributionsResponse -> TestTree
testListDistributionsResponse = res
"ListDistributionsResponse"
"fixture/ListDistributionsResponse.proto"
cloudFront
(Proxy :: Proxy ListDistributions)
| fmapfmapfmap/amazonka | amazonka-cloudfront/test/Test/AWS/Gen/CloudFront.hs | mpl-2.0 | 15,148 | 0 | 7 | 2,399 | 1,264 | 746 | 518 | 219 | 1 |
{-# LANGUAGE NoMonomorphismRestriction, FlexibleInstances #-}
module PTS.Syntax.Pretty
( Pretty (pretty)
, singleLine
, multiLine
, showCtx
, prettyAlgebra
, showAssertion
, showPretty
) where
import Control.Arrow (first)
import Data.List (intersperse, intercalate)
import Data.Set (Set)
import qualified Data.Set as Set
import PTS.Syntax.Algebra
import PTS.Syntax.Constants
import PTS.Syntax.Names
import PTS.Syntax.Statement
import PTS.Syntax.Term
import PTS.Dynamics.TypedTerm
import Text.PrettyPrint.HughesPJ
class Pretty p where
pretty :: Int -> p -> Doc
instance Pretty [Char] where
pretty _ = text
instance Pretty Doc where
pretty _ x = x
when f True = f
when f False = id
singleLine :: Pretty p => p -> String
singleLine p = renderStyle (Style OneLineMode 80 1.0) (pretty 0 p)
multiLine :: Pretty p => Int -> p -> String
multiLine n p = renderStyle (Style PageMode n 1.5) (pretty 0 p)
-- priorities
pAppR = 3
pApp = 2
pArrL = 2
pArr = 1
pLam = 1
pPi = 1
pIf0 = 2
-- pretty printing
instance Pretty Name where
pretty _ name = text (show name)
instance Pretty C where
pretty _ (C 0) = text "Int"
pretty _ (C n) = text (replicate n '*')
data PrettyChain
= AppChain Bool Doc [Doc]
| LamChain [(Doc, Doc)] Doc
| PiChain [(Doc, Doc)] Doc
| ArrChain [Doc] Doc
| Atomic Doc
| Composite Priority Doc
instance Pretty BinOp where
pretty _ Add = text "add"
pretty _ Sub = text "sub"
pretty _ Mul = text "mul"
pretty _ Div = text "div"
type Priority = Int
instance Pretty PrettyChain where
pretty p (AppChain atomic operator arguments) =
parens `when` (pApp < p) $
(if atomic then hsep else sep)
[operator, nest 2 . sep . reverse $ arguments]
pretty p (LamChain lams body) =
parens `when` (pLam < p) $
sep [ sep . map (\(n, q) -> text "lambda" <+> pretty 0 n <+> text ":" <+> q <+> text ".") $ lams
, nest 2 $ body ]
pretty p (PiChain pis body) =
parens `when` (pPi < p) $
sep [ sep . map (\(n, q) -> text "Pi" <+> n <+> text ":" <+> q <+> text ".") $ pis
, nest 2 $ body ]
pretty p (ArrChain arrs body) =
parens `when` (pArr < p) $
sep $ [sep . map (\q -> q <+> text "->") $ arrs, body] -- TODO is this correct?
pretty p (Atomic t) =
t
pretty p (Composite p' t) =
parens `when` (p' < p) $
t
prettyAlgebra :: PreAlgebra (Names, PrettyChain) PrettyChain
prettyAlgebra (Int n) = Atomic $
integer n
prettyAlgebra (IntOp n (_, a) (_, b)) = Composite pApp $
pretty 0 n <+> pretty pAppR a <+> pretty pAppR b
prettyAlgebra (IfZero (_, c) (_, t) (_, e)) = Composite pIf0 $
sep [ text "if0" <+> pretty pIf0 c
, nest 2 $ text "then" <+> pretty pIf0 t
, nest 2 $ text "else" <+> pretty pIf0 e ]
prettyAlgebra (Infer n) = Atomic $ text "_" <> integer n
prettyAlgebra (Var n) = Atomic $
pretty 0 n
prettyAlgebra (Const c) = Atomic $
pretty 0 c
prettyAlgebra (App (_, AppChain atomic operator arguments) (_, argument)) =
AppChain atomic operator (pretty pAppR argument : arguments)
prettyAlgebra (App (_, Atomic operator) (_, argument)) =
AppChain True (pretty pApp operator) [pretty pAppR argument]
prettyAlgebra (App (_, operator) (_, argument)) =
AppChain False (pretty pApp operator) [pretty pAppR argument]
prettyAlgebra (Lam name (_, qualifier) (_, LamChain lams body)) =
LamChain ((pretty 0 name, pretty pLam qualifier) : lams) body
prettyAlgebra (Lam name (_, qualifier) (_, body)) =
LamChain [(pretty 0 name, pretty pLam qualifier)] (pretty pLam body)
prettyAlgebra (Pi name (_, qualifier) (freevars, PiChain lams body) _) | name `Set.member` freevars =
PiChain ((pretty 0 name, pretty pPi qualifier) : lams) body
prettyAlgebra (Pi name (_, qualifier) (freevars, body) _) | name `Set.member` freevars =
PiChain [(pretty 0 name, pretty pPi qualifier)] (pretty pPi body)
prettyAlgebra (Pi name (_, qualifier) (freevars, ArrChain lams body) _) | name `Set.notMember` freevars =
ArrChain (pretty pArrL qualifier : lams) body
prettyAlgebra (Pi name (_, qualifier) (freevars, body) _) | name `Set.notMember` freevars =
ArrChain [pretty pArrL qualifier] (pretty pArr body)
prettyAlgebra (Pos _ (_, t)) = t
instance Pretty Term where
pretty p t = pretty p (snd (fold (depZip freevarsAlgebra prettyAlgebra) t))
instance Pretty (TypedTerm m) where
pretty p t = pretty p (snd (fold (depZip freevarsAlgebra prettyAlgebra) t))
prettyArgs :: [([Name], Term)] -> Doc
prettyArgs args = sep (map f args) where
f (ns, q) = hsep [pretty 0 n | n <- ns] <+> text ":" <+> pretty 0 q
instance Pretty Stmt where
pretty p (Bind n args Nothing t) = pretty 0 n <+> prettyArgs args <+> text "=" <+> pretty 0 t
pretty p (Bind n args (Just t') t) = pretty 0 n <+> prettyArgs args <+> text ":" <+> pretty 0 t' <+> text "=" <+> pretty 0 t
pretty p (Term t) = pretty 0 t
pretty p (Assertion t q' t') = text "assert" <+> prettyAssertion t q' t'
pretty p (Import n) = text "import" <+> pretty 0 n
pretty p (Export mod) = text "export" <+> pretty 0 mod
prettyAssertion t q' t' =
pretty 0 t <+> pq' <+> pt' where
pq' = case q' of
Nothing -> empty
Just q' -> text ":" <+> pretty 0 q'
pt' = case t' of
Nothing -> empty
Just t' -> text "=" <+> pretty 0 t'
showAssertion t q' t' = singleLine (prettyAssertion t q' t')
instance Pretty ModuleName where
pretty p m = text (intercalate "." (parts m))
showPretty :: Pretty p => p -> String
showPretty = singleLine
showCtx :: Pretty a => [(Name, a)] -> String
showCtx = concat . intersperse ", " . map (\(n, t) -> show n ++ " : " ++ showPretty t)
| Toxaris/pts | src-lib/PTS/Syntax/Pretty.hs | bsd-3-clause | 5,632 | 0 | 18 | 1,270 | 2,515 | 1,298 | 1,217 | 143 | 3 |
{-# LANGUAGE DataKinds, DeriveDataTypeable, GeneralizedNewtypeDeriving,
MultiParamTypeClasses, OverloadedStrings, TemplateHaskell,
TypeFamilies, TypeOperators #-}
module TutorialUsers where
import Control.Monad (liftM, mzero)
import Data.Readable (Readable(fromText))
import Data.Typeable
import qualified Data.Vector as V
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Unboxed as VU
import Frames.InCore (VectorFor)
import Frames
data GenderT = Male | Female deriving (Enum,Eq,Ord,Show,Typeable)
type instance VectorFor GenderT = V.Vector
instance Readable GenderT where
fromText "M" = return Male
fromText "F" = return Female
fromText _ = mzero
type MyColumns = GenderT ': CommonColumns
-- * Packed Representation
newtype GenderU = GenderU { getGenderU :: GenderT }
deriving (Eq,Ord,Show,Enum,Typeable)
-- Let's go all the way and support an efficient packed representation
-- for our type. If you don't want to, or can't, provide an 'VU.Unbox'
-- or 'Storable' instance for your type, define a 'VectorFor' type
-- instance that uses a boxed vector for your type.
newtype instance VU.MVector s GenderU = MV_Gender (VU.MVector s Bool)
newtype instance VU.Vector GenderU = V_Gender (VU.Vector Bool)
instance VGM.MVector VU.MVector GenderU where
{-# INLINE basicLength #-}
basicLength (MV_Gender v) = VGM.basicLength v
{-# INLINE basicUnsafeSlice #-}
basicUnsafeSlice start len (MV_Gender v) = MV_Gender $
VGM.basicUnsafeSlice start len v
{-# INLINE basicOverlaps #-}
basicOverlaps (MV_Gender v) (MV_Gender w) = VGM.basicOverlaps v w
{-# INLINE basicUnsafeNew #-}
basicUnsafeNew n = liftM MV_Gender (VGM.basicUnsafeNew n)
{-# INLINE basicUnsafeRead #-}
basicUnsafeRead (MV_Gender v) = liftM (toEnum . fromEnum)
. VGM.basicUnsafeRead v
{-# INLINE basicUnsafeWrite #-}
basicUnsafeWrite (MV_Gender v) i x = VGM.basicUnsafeWrite v i
$ toEnum (fromEnum x)
instance VG.Vector VU.Vector GenderU where
{-# INLINE basicLength #-}
basicLength (V_Gender v) = VG.basicLength v
{-# INLINE basicUnsafeSlice #-}
basicUnsafeSlice start len (V_Gender v) = V_Gender $
VG.basicUnsafeSlice start len v
{-# INLINE basicUnsafeFreeze #-}
basicUnsafeFreeze (MV_Gender v) = liftM V_Gender $ VG.basicUnsafeFreeze v
{-# INLINE basicUnsafeThaw #-}
basicUnsafeThaw (V_Gender v) = liftM MV_Gender $ VG.basicUnsafeThaw v
{-# INLINE basicUnsafeIndexM #-}
basicUnsafeIndexM (V_Gender v) = liftM (toEnum . fromEnum) . VG.basicUnsafeIndexM v
instance VU.Unbox GenderU where
type instance VectorFor GenderU = VU.Vector
| codygman/Frames | demo/TutorialUsers.hs | bsd-3-clause | 2,808 | 0 | 9 | 584 | 639 | 345 | 294 | 54 | 0 |
{-# LANGUAGE RankNTypes,
FunctionalDependencies,
PartialTypeSignatures,
OverloadedStrings,
ScopedTypeVariables,
TemplateHaskell
#-}
module SecondTransfer.TLS.CoreServer (
-- * Simpler interfaces
-- These functions are simple enough but don't work with controllable
-- processes.
tlsServeWithALPN
, tlsServeWithALPNNSSockAddr
--, tlsSessionHandler
, tlsServeWithALPNUnderSOCKS5SockAddr
-- * Interfaces for a pre-fork scenario
-- The first part of the invocation opens and
-- bind the socket, the second part does the accepting...
, NormalTCPHold
, tlsServeWithALPNNSSockAddr_Prepare
, tlsServeWithALPNNSSockAddr_Do
, Socks5Hold
, tlsServeWithALPNUnderSOCKS5SockAddr_Prepare
, tlsServeWithALPNUnderSOCKS5SockAddr_Do
, coreListen
-- * Utility
, NamedAttendants
, chooseProtocol
-- * Conduit-based session management
-- , coreItcli
) where
import Control.Concurrent
import qualified Control.Exception as E
--import Control.Monad.IO.Class (liftIO)
import Control.Monad (when)
import Control.Lens ( (^.), makeLenses, over, set )
import GHC.Stack
--import Data.Conduit
-- import qualified Data.Conduit as Con(yield)
--import qualified Data.Conduit.List as CL
import Data.Typeable (Proxy(..))
import Data.List (elemIndex)
import Data.Maybe (-- fromMaybe,
isJust)
import qualified Data.ByteString as B
--import Data.ByteString.Char8 (pack, unpack)
import Data.Int (Int64)
import qualified Data.HashMap.Strict as HS
-- import Data.IORef
--import qualified Data.ByteString.Lazy as LB
--import qualified Data.ByteString.Builder as Bu
import qualified Network.Socket as NS
import SecondTransfer.MainLoop.Protocol
import SecondTransfer.IOCallbacks.Types
import SecondTransfer.TLS.Types
import SecondTransfer.IOCallbacks.SocketServer
import SecondTransfer.IOCallbacks.WrapSocket (
HasSocketPeer(..),
AcceptErrorCondition(..)
)
import SecondTransfer.Socks5.Session (
-- tlsSOCKS5Serve,
tlsSOCKS5Serve',
initSocks5ServerState)
import SecondTransfer.Socks5.Types (Socks5ConnectionCallbacks)
import SecondTransfer.Exception (forkIOExc, IOProblem)
import SecondTransfer.Sessions.HashableSockAddr (hashableSockAddrFromNSSockAddr,
HashableSockAddr
)
--import Debug.Trace (traceStack)
data SessionHandlerState = SessionHandlerState {
_liveSessions_S :: !Int64
, _nextConnId_S :: !Int64
, _connCallbacks_S :: ConnectionCallbacks
}
makeLenses ''SessionHandlerState
-- | A fixed constant for how long can a TLS handshake last.
-- Let's set it at three seconds.
tlsHandshakeTimeout :: Int
tlsHandshakeTimeout = 3000000
-- | How many TLS handshakes can be in transit from the
-- same host at any given time
maxHandshakesInTransit :: Int
maxHandshakesInTransit = 8
-- | A simple Alias
type NamedAttendants = [(String, Attendant)]
data NoStore
instance TLSSessionStorage NoStore
-- | Convenience function to open a port and listen there for connections and
-- select protocols and so on.
tlsServeWithALPN :: forall ctx session . (TLSContext ctx session)
=> (Proxy ctx ) -- ^ This is a simple proxy type from Typeable that is used to select the type
-- of TLS backend to use during the invocation
-> ConnectionCallbacks -- ^ Control and log connections
-> B.ByteString -- ^ String with contents of certificate chain
-> B.ByteString -- ^ String with contents of PKCS #8 key
-> String -- ^ Name of the network interface
-> NamedAttendants -- ^ List of attendants and their handlers
-> Int -- ^ Port to listen for connections
-> IO ()
tlsServeWithALPN proxy conn_callbacks cert_filename key_filename interface_name attendants interface_port = do
-- let
-- tls_serve socket
listen_socket <- createAndBindListeningSocket interface_name interface_port
coreListen
proxy
conn_callbacks
cert_filename
key_filename
listen_socket
(tlsServe closing)
(Nothing :: Maybe NoStore)
attendants
where
closing = case conn_callbacks ^. serviceIsClosing_CoCa of
Just clbk -> clbk
Nothing -> (return False)
-- | Use a previously given network address
tlsServeWithALPNNSSockAddr :: forall ctx session . (TLSContext ctx session)
=> (Proxy ctx ) -- ^ This is a simple proxy type from Typeable that is used to select the type
-- of TLS backend to use during the invocation
-> ConnectionCallbacks -- ^ Control and regulate SOCKS5 connections
-> B.ByteString -- ^ String with contents of certificate chain
-> B.ByteString -- ^ String with contents of PKCS #8 key
-> NS.SockAddr -- ^ Address to bind to
-> NamedAttendants -- ^ List of attendants and their handlers
-> IO ()
tlsServeWithALPNNSSockAddr proxy conn_callbacks cert_filename key_filename sock_addr attendants = do
listen_socket <- createAndBindListeningSocketNSSockAddr sock_addr
-- Close the socket if need comes
coreListen
proxy
conn_callbacks
cert_filename
key_filename
listen_socket
(tlsServe closing)
(Nothing :: Maybe NoStore)
attendants
where
closing = case conn_callbacks ^. serviceIsClosing_CoCa of
Just clbk -> clbk
Nothing -> (return False)
data NormalTCPHold = NormalTCPHold ( IO () )
-- | The prefork way requires a first step where we create the sockets and then we listen on them...
-- This function is identical otherwise to the one without _Prepare. The real thing is done by the
-- one with _Do below...
tlsServeWithALPNNSSockAddr_Prepare :: forall ctx session resumption_store . (TLSContext ctx session, TLSSessionStorage resumption_store)
=> (Proxy ctx ) -- ^ This is a simple proxy type from Typeable that is used to select the type
-- of TLS backend to use during the invocation
-> ConnectionCallbacks -- ^ Control and regulate SOCKS5 connections
-> B.ByteString -- ^ String with contents of certificate chain
-> B.ByteString -- ^ String with contents of PKCS #8 key
-> NS.SockAddr -- ^ Address to bind to
-> Maybe resumption_store
-> IO NamedAttendants -- ^ Will-be list of attendants and their handlers
-> IO NormalTCPHold
tlsServeWithALPNNSSockAddr_Prepare
proxy
conn_callbacks
cert_filename
key_filename
sock_addr
maybe_resumption_store
make_attendants
= do
listen_socket <- createAndBindListeningSocketNSSockAddr sock_addr
return . NormalTCPHold $ do
attendants <- make_attendants
coreListen
proxy
conn_callbacks
cert_filename
key_filename
listen_socket
(tlsServe closing)
maybe_resumption_store
attendants
where
closing = case conn_callbacks ^. serviceIsClosing_CoCa of
Just clbk -> clbk
Nothing -> (return False)
-- | Actually listen, possibly at the other side of the fork.
tlsServeWithALPNNSSockAddr_Do :: NormalTCPHold -> IO ()
tlsServeWithALPNNSSockAddr_Do (NormalTCPHold action) = action
tlsServeWithALPNUnderSOCKS5SockAddr :: forall ctx session . (TLSContext ctx session)
=> Proxy ctx -- ^ This is a simple proxy type from Typeable that is used to select the type
-- of TLS backend to use during the invocation
-> ConnectionCallbacks -- ^ Log and control of the inner TLS session
-> Socks5ConnectionCallbacks -- ^ Log and control the outer SOCKS5 session
-> B.ByteString -- ^ String with contents of certificate chain
-> B.ByteString -- ^ String with contents of PKCS #8 key
-> NS.SockAddr -- ^ Address to bind to
-> NamedAttendants -- ^ List of attendants and their handlers,
-> [B.ByteString] -- ^ Names of "internal" hosts
-> Bool -- ^ Should I forward connection requests?
-> IO ()
tlsServeWithALPNUnderSOCKS5SockAddr
proxy
conn_callbacks
socks5_callbacks
cert_filename
key_filename
host_addr
attendants
internal_hosts
forward_no_internal = do
let
approver :: B.ByteString -> Bool
approver name = isJust $ elemIndex name internal_hosts
socks5_state_mvar <- newMVar initSocks5ServerState
listen_socket <- createAndBindListeningSocketNSSockAddr host_addr
-- let
-- handler_fn :: NS.Socket
-- -> (Either AcceptErrorCondition b0 -> IO ()) -> IO ()
-- handler_fn socket =
-- tlsSOCKS5Serve socks5_state_mvar socks5_callbacks approver forward_no_internal
coreListen
proxy
conn_callbacks
cert_filename
key_filename
listen_socket
(tlsSOCKS5Serve' socks5_state_mvar socks5_callbacks approver forward_no_internal)
(Nothing :: Maybe NoStore)
attendants
-- | Opaque hold type
data Socks5Hold = Socks5Hold (IO ())
tlsServeWithALPNUnderSOCKS5SockAddr_Prepare :: forall ctx session . (TLSContext ctx session)
=> Proxy ctx -- ^ This is a simple proxy type from Typeable that is used to select the type
-- of TLS backend to use during the invocation
-> ConnectionCallbacks -- ^ Log and control of the inner TLS session
-> Socks5ConnectionCallbacks -- ^ Log and control the outer SOCKS5 session
-> B.ByteString -- ^ String with contents of certificate chain
-> B.ByteString -- ^ String with contents of PKCS #8 key
-> NS.SockAddr -- ^ Address to bind to
-> IO NamedAttendants -- ^ List of attendants and their handlers, as it will be built
-> [B.ByteString] -- ^ Names of "internal" hosts
-> Bool -- ^ Should I forward connection requests?
-> IO Socks5Hold
tlsServeWithALPNUnderSOCKS5SockAddr_Prepare
proxy
conn_callbacks
socks5_callbacks
cert_pemfile_data
key_pemfile_data
host_addr
make_attendants
internal_hosts
forward_no_internal = do
let
approver :: B.ByteString -> Bool
approver name = isJust $ elemIndex name internal_hosts
socks5_state_mvar <- newMVar initSocks5ServerState
listen_socket <- createAndBindListeningSocketNSSockAddr host_addr
return . Socks5Hold $ do
attendants <- make_attendants
coreListen
proxy
conn_callbacks
cert_pemfile_data
key_pemfile_data
listen_socket
(tlsSOCKS5Serve' socks5_state_mvar socks5_callbacks approver forward_no_internal)
(Nothing :: Maybe NoStore)
attendants
tlsServeWithALPNUnderSOCKS5SockAddr_Do :: Socks5Hold -> IO ()
tlsServeWithALPNUnderSOCKS5SockAddr_Do (Socks5Hold action) = action
type InFlightRegistry =HS.HashMap HashableSockAddr Int
tlsSessionHandler ::
(TLSContext ctx session, TLSServerIO encrypted_io, HasSocketPeer encrypted_io) =>
MVar SessionHandlerState
-> NamedAttendants
-> ctx
-> encrypted_io
-> MVar InFlightRegistry -- ^ Just know how many sessions are open for ip addresses
-> IO ()
tlsSessionHandler session_handler_state_mvar attendants ctx encrypted_io inflight = do
-- Have the handshake happen in another thread
_ <- forkIOExc "tlsSessionHandler" $ do
-- Get a new connection id... this is a pretty safe block, exceptions should
-- be uncommon here.
(new_conn_id, live_now) <- modifyMVar session_handler_state_mvar $ \ s -> do
let new_conn_id = s ^. nextConnId_S
live_now_ = (s ^. liveSessions_S) + 1
new_s = over nextConnId_S ( + 1 ) s
new_new_s = live_now_ `seq` set liveSessions_S live_now_ new_s
return $ new_new_s `seq` (new_new_s, (new_conn_id, live_now_) )
connection_callbacks <- withMVar session_handler_state_mvar $ \ s -> do
return $ s ^. connCallbacks_S
let
log_events_maybe = connection_callbacks ^. logEvents_CoCa
log_event :: ConnectionEvent -> IO ()
log_event ev = case log_events_maybe of
Nothing -> return ()
Just c -> c ev
wconn_id = ConnectionId new_conn_id
report_minus_one_connection _mark = do
log_event (Ended_CoEv wconn_id)
-- putStrLn $ "mark: " ++ _mark
modifyMVar_ session_handler_state_mvar $ \ s -> do
let
live_now_ = (s ^. liveSessions_S) - 1
new_new_s = set liveSessions_S live_now_ s
new_new_s `seq` return new_new_s
-- If the connection has been closed, we will get some sort of exception here.
either_sock_addr <- E.try $ getSocketPeerAddress encrypted_io
case either_sock_addr :: Either E.IOException NS.SockAddr of
Left _exc -> do
report_minus_one_connection "no-peer"
-- Close the connection
io_callbacks <- handshake encrypted_io
io_callbacks ^. closeAction_IOC
Right sock_addr -> do
let
hashable_addr = hashableSockAddrFromNSSockAddr sock_addr
connection_data = ConnectionData
{
_addr_CnD = hashable_addr
, _connId_CnD = wconn_id
}
-- If there are too many connections, drop this one
proceed <- case hashable_addr of
Just hashable_addr_strict -> do
connections_now <- withMVar inflight $ \ inflight_hm -> let
count = HS.lookupDefault 0 hashable_addr_strict inflight_hm
in return count
return $ connections_now < maxHandshakesInTransit
-- If I don't have a source address, proceed always. The lack
-- of source address can be due to some SOCKS5 or strange
-- transport weirdiness.
Nothing -> return True
if proceed
then do
case hashable_addr of
Just hashable_addr_strict -> do
modifyMVar_ inflight $ \ inflight_hm -> let
count = HS.lookupDefault 0 hashable_addr_strict inflight_hm
new_count = count + 1
new_inflight = HS.insert hashable_addr_strict new_count inflight_hm
in return new_inflight
-- If I don't have a source address, proceed always. The lack
-- of source address can be due to some SOCKS5 or strange
-- transport weirdiness.
Nothing -> return ()
E.finally
(continueToHandshake
log_event
sock_addr
wconn_id
live_now
ctx
encrypted_io
connection_callbacks
connection_data
report_minus_one_connection
attendants
)
(case hashable_addr of
Just hashable_addr_strict -> do
modifyMVar_ inflight $ \ inflight_hm -> let
count = HS.lookupDefault 0 hashable_addr_strict inflight_hm
new_count = count - 1
new_inflight = HS.insert hashable_addr_strict new_count inflight_hm
in return new_inflight
-- If I don't have a source address, proceed always. The lack
-- of source address can be due to some SOCKS5 or strange
-- transport weirdiness.
Nothing -> return ()
)
else do
-- Just close the connection, without adding a new one, but report
-- the event
plaintext_io_callbacks <- handshake encrypted_io
log_event (TooManyInHandshake_CoEv sock_addr)
plaintext_io_callbacks ^. closeAction_IOC
report_minus_one_connection "too-many-from-same"
-- Tell the upper layer that this in-flux socket has been passed to an
-- attendant (and thus will be managed by the Tidal manager)
return ()
continueToHandshake :: forall cipherio ctx session .
(TLSContext ctx session, TLSServerIO cipherio) =>
(ConnectionEvent -> IO ())
-> NS.SockAddr
-> ConnectionId
-> Int64
-> ctx
-> cipherio
-> ConnectionCallbacks
-> ConnectionData
-> (String -> IO () )
-> [(String, ConnectionData -> IOCallbacks -> IO ())]
-> IO ()
continueToHandshake
log_event
sock_addr
wconn_id
live_now
ctx
encrypted_io
connection_callbacks
connection_data
report_minus_one_connection
attendants
= do
log_event (Established_CoEv sock_addr wconn_id live_now)
-- Let's decrypt stuff ... This function usually doesn't throw,
-- as it mainly does channel setup and very little or none actual
-- IO. TODO: But we may need to watch it for problems.
session <- {-# SCC u1 #-} unencryptTLSServerIO ctx encrypted_io
-- The handshake is more about setting up channels and actions, no
-- actual TLS handshake is expected to happen here. In fact, this
-- action and the unencryptTLSServerIO could be together. The
-- reason to have them separated is the ctx argument above.
plaintext_io_callbacks_u' <- {-# SCC u2 #-} handshake session :: IO IOCallbacks
-- Modulate the IO callbacks if that has been instructed.
plaintext_io_callbacks_u <- case (connection_callbacks ^. blanketPlainTextIO_CoCa) of
Nothing -> return plaintext_io_callbacks_u'
Just u -> u connection_data plaintext_io_callbacks_u'
-- Using a different MVar, don't change line below.
close_reported_outer <- newMVar False
let
instr = do
modifyMVar_ close_reported_outer $ \ close_reported_x -> do
if (not close_reported_x) then do
-- We can close just once
plaintext_io_callbacks_u ^. closeAction_IOC
report_minus_one_connection "normal-close"
return True
else
return close_reported_x
plaintext_io_callbacks = set closeAction_IOC instr plaintext_io_callbacks_u
-- Next point where things can go wrong: a handshake may never
-- finish, and we may never get the protocol.
-- Deep in Botan.hs this function is just waiting on an MVar for
-- at least one thing: to have the TLS handshake finish and the
-- protocol to be selected.
-- Now let's allow for that to timeout.
-- transit_state: odd numbers are bad, even numbers mean everything is going
-- according to plans
transit_state <- newMVar (0 :: Int)
done_waiting <- newEmptyMVar
_ <- forkIOExc "tlsSessionHandler.mayTimeOut" $ do
either_maybe_sel_prot <- E.try $ getSelectedProtocol session
proceed <- modifyMVar transit_state $ \ i ->
if i == 0
then
return (2,True)
else
return (i,False)
when proceed $ do
case either_maybe_sel_prot :: Either IOProblem HttpProtocolVersion of
Right maybe_sel_prot -> do
let maybe_attendant =
case maybe_sel_prot of
Http11_HPV ->
lookup "http/1.1" attendants
Http2_HPV ->
lookup "h2" attendants
case maybe_attendant of
Just use_attendant ->
{-# SCC u4 #-} use_attendant connection_data plaintext_io_callbacks
Nothing -> do
log_event (ALPNFailed_CoEv wconn_id)
plaintext_io_callbacks ^. closeAction_IOC
modifyMVar_ transit_state $ \ _ ->
return 4
putMVar done_waiting ()
Left _exc -> do
plaintext_io_callbacks ^. closeAction_IOC
report_minus_one_connection "io-problem"
modifyMVar_ transit_state $ \ _ ->
return 5
putMVar done_waiting ()
_ <- forkIOExc "tlsSessionHandler.doTimeOut" $ do
threadDelay tlsHandshakeTimeout
dosignal <- modifyMVar transit_state $ \ i ->
if i == 0
then do
return (1, True)
else do
return (i, False)
when dosignal $ do
log_event (TLSHandshakeTimeOut_CoEv sock_addr)
plaintext_io_callbacks ^. closeAction_IOC
report_minus_one_connection "handshake-tiemout"
putMVar done_waiting ()
-- Wait for one of the two branches to arrive here: either the
-- one that does I/O or the one that does waiting for a timeout.
readMVar done_waiting
return ()
chooseProtocol :: [(String, a)] -> HttpProtocolVersion
chooseProtocol (("http/1.1" , _):_ ) = Http11_HPV
chooseProtocol (("h2", _):_ ) = Http2_HPV
chooseProtocol _ = Http11_HPV
coreListen ::
forall a ctx session b resumption_store .
(TLSContext ctx session, TLSServerIO b, HasSocketPeer b, TLSSessionStorage resumption_store)
=> (Proxy ctx ) -- ^ This is a simple proxy type from Typeable that is used to select the type
-- of TLS backend to use during the invocation
-> ConnectionCallbacks -- ^ Functions to log and control behaviour of the server
-> B.ByteString -- ^ PEM-encoded certificate chain, in this string
-> B.ByteString -- ^ PEM-encoded, un-encrypted PKCS #8 key in this string
-> a -- ^ An entity that is used to fork new handlers
-> ( a -> (Either AcceptErrorCondition b -> IO()) -> IO () ) -- ^ The fork-handling functionality
-> Maybe resumption_store
-> [(String, Attendant)] -- ^ List of attendants and their handlers
-> IO ()
coreListen
_
conn_callbacks
certificate_pemfile_data
key_pemfile_data
listen_abstraction
session_forker
resumption_store
attendants
= do
let
state = SessionHandlerState {
_liveSessions_S = 0
, _nextConnId_S = 0
, _connCallbacks_S = conn_callbacks
}
state_mvar <- newMVar state
ctx <-
newTLSContextFromMemory
certificate_pemfile_data
key_pemfile_data
(chooseProtocol attendants) :: IO ctx
inflight <- newMVar HS.empty
_session_resumption_enabled <- case resumption_store of
Just really_there -> enableSessionResumption ctx really_there
Nothing -> return False
let
tls_session_handler :: forall w .
(TLSServerIO w, HasSocketPeer w) =>
Either AcceptErrorCondition w -> IO ()
tls_session_handler either_aerr =
case either_aerr of
Left connect_condition ->
case (conn_callbacks ^. logEvents_CoCa) of
Just lgfn -> lgfn $ AcceptError_CoEv connect_condition
Nothing -> return ()
Right good ->
case (conn_callbacks ^. serviceIsClosing_CoCa) of
Nothing ->
tlsSessionHandler state_mvar attendants ctx good inflight
Just clbk -> do
service_is_closing <- clbk
if not service_is_closing
then
tlsSessionHandler state_mvar attendants ctx good inflight
else do
-- Close inmediately the connection, without doing
-- anything else
ioc <- handshake good
ioc ^. closeAction_IOC
session_forker listen_abstraction tls_session_handler
| shimmercat/second-transfer | hs-src/SecondTransfer/TLS/CoreServer.hs | bsd-3-clause | 28,164 | 0 | 33 | 11,440 | 3,632 | 1,881 | 1,751 | -1 | -1 |
module SourceTarball where
import Control.Monad (forM_)
import Development.Shake
import Development.Shake.FilePath
import Config
import Dirs
import LocalCommand
import Paths
import PlatformDB
import Templates
import Types
import Utils
sourceTarballRules :: FilePath -> Rules ()
sourceTarballRules srcTarFile = do
packageListRule listCore corePackages
packageListRule listSource platformPackages
cabalFileRule
srcTarFile %> \out -> do
hpRelease <- askHpRelease
bc <- askBuildConfig
tarFileAction out bc hpRelease
where
packageListRule target pkgFn =
target %> \out -> do
hpRelease <- askHpRelease
bc <- askBuildConfig
let pkgs = pkgFn (bcIncludeExtra bc) hpRelease
writeFileLinesChanged out (map show pkgs)
tarFileAction :: FilePath -> BuildConfig -> Release -> Action ()
tarFileAction out bc hpRelease = do
need $ concat
[ map (dir . packageSourceDir) sources
, lists
, [hpCabalFile, dir ghcLocalDir]
, topFiles
]
removeDirectoryRecursive topDir
makeDirectory topDir
makeDirectory etcDir
makeDirectory packagesDir
forM_ sources $ \sPkg ->
command_ [] "cp"
[ "-pR"
, packageSourceDir sPkg
, hpSourcePackageDir hp sPkg]
forM_ lists $ \l -> do
let dest = etcDir </> takeFileName l
putLoud $ "copyFile' " ++ l ++ " " ++ dest
copyFile' l dest
copyFile' hpCabalFile $ topDir </> takeFileName hpCabalFile
forM_ topFiles $ \f -> copyFile' f $ topDir </> f
localCommand' [Cwd hptoolSourceDir]
"cabal" [ "sdist"
, "--output-directory=" ++ hptoolDistDir `relativeToDir` hptoolSourceDir ]
-- this is a hack because adding os-extras to hptool's .cabal file would
-- be inordinately painful
command_ [] "cp"
[ "-pR"
, hptoolSourceDir </> "os-extras"
, hptoolDistDir
]
command_ [Cwd upDir]
"tar" ["czf", out `relativeToDir` upDir, takeFileName topDir]
where
hp = relVersion hpRelease
upDir = takeDirectory topDir
topDir = hpSourceDir hp
etcDir = hpSourceEtcDir hp
packagesDir = hpSourcePackagesDir hp
hptoolSourceDir = "hptool"
hptoolDistDir = topDir </> "hptool"
lists = [listBuild, listCore, listSource]
topFiles =
[ "LICENSE"
, "platform.sh"
, "README"
, "windows-platform.sh"
]
sources = platformPackages (bcIncludeExtra bc) hpRelease
cabalFileRule :: Rules ()
cabalFileRule =
hpCabalFile %> \cFile -> do
ctx <- releaseContext
let ctx' = ctx `ctxAppend` errorCtx
copyExpandedFile ctx' cabalTemplate cFile
where
cabalTemplate = "hptool/templates/haskell-platform.cabal.mu" -- FIXME
| erantapaa/haskell-platform | hptool/src/SourceTarball.hs | bsd-3-clause | 2,835 | 0 | 16 | 788 | 700 | 352 | 348 | 79 | 1 |
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
-- |
-- Module : System.Taffybar.Widget.CommandRunner
-- Copyright : (c) Arseniy Seroka
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Arseniy Seroka <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Simple function which runs user defined command and
-- returns it's output in PollingLabel widget
--------------------------------------------------------------------------------
module System.Taffybar.Widget.CommandRunner ( commandRunnerNew ) where
import Control.Monad.IO.Class
import qualified GI.Gtk
import System.Log.Logger
import System.Taffybar.Util
import System.Taffybar.Widget.Generic.PollingLabel
import Text.Printf
import qualified Data.Text as T
-- | Creates a new command runner widget. This is a 'PollingLabel' fed by
-- regular calls to command given by argument. The results of calling this
-- function are displayed as string.
commandRunnerNew
:: MonadIO m
=> Double -- ^ Polling period (in seconds).
-> String -- ^ Command to execute. Should be in $PATH or an absolute path
-> [String] -- ^ Command argument. May be @[]@
-> T.Text -- ^ If command fails this will be displayed.
-> m GI.Gtk.Widget
commandRunnerNew interval cmd args defaultOutput =
pollingLabelNew interval $ runCommandWithDefault cmd args defaultOutput
runCommandWithDefault :: FilePath -> [String] -> T.Text -> IO T.Text
runCommandWithDefault cmd args def =
T.filter (/= '\n') <$> (runCommand cmd args >>= either logError (return . T.pack))
where logError err =
logM "System.Taffybar.Widget.CommandRunner" ERROR
(printf "Got error in CommandRunner %s" err) >> return def
| teleshoes/taffybar | src/System/Taffybar/Widget/CommandRunner.hs | bsd-3-clause | 1,825 | 0 | 11 | 332 | 257 | 150 | 107 | 24 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Dependency.TopDown.Types
-- Copyright : (c) Duncan Coutts 2008
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Types for the top-down dependency resolver.
-----------------------------------------------------------------------------
module Distribution.Client.Dependency.TopDown.Types where
import Distribution.Client.Types
( SourcePackage(..), InstalledPackage, OptionalStanza )
import Distribution.Package
( PackageIdentifier, Dependency
, Package(packageId), PackageFixedDeps(depends) )
import Distribution.PackageDescription
( FlagAssignment )
-- ------------------------------------------------------------
-- * The various kinds of packages
-- ------------------------------------------------------------
type SelectablePackage
= InstalledOrSource InstalledPackageEx UnconfiguredPackage
type SelectedPackage
= InstalledOrSource InstalledPackageEx SemiConfiguredPackage
data InstalledOrSource installed source
= InstalledOnly installed
| SourceOnly source
| InstalledAndSource installed source
deriving Eq
type TopologicalSortNumber = Int
data InstalledPackageEx
= InstalledPackageEx
InstalledPackage
!TopologicalSortNumber
[PackageIdentifier] -- transitive closure of installed deps
data UnconfiguredPackage
= UnconfiguredPackage
SourcePackage
!TopologicalSortNumber
FlagAssignment
[OptionalStanza]
data SemiConfiguredPackage
= SemiConfiguredPackage
SourcePackage -- package info
FlagAssignment -- total flag assignment for the package
[OptionalStanza] -- enabled optional stanzas
[Dependency] -- dependencies we end up with when we apply
-- the flag assignment
instance Package InstalledPackageEx where
packageId (InstalledPackageEx p _ _) = packageId p
instance PackageFixedDeps InstalledPackageEx where
depends (InstalledPackageEx _ _ deps) = deps
instance Package UnconfiguredPackage where
packageId (UnconfiguredPackage p _ _ _) = packageId p
instance Package SemiConfiguredPackage where
packageId (SemiConfiguredPackage p _ _ _) = packageId p
instance (Package installed, Package source)
=> Package (InstalledOrSource installed source) where
packageId (InstalledOnly p ) = packageId p
packageId (SourceOnly p ) = packageId p
packageId (InstalledAndSource p _) = packageId p
-- | We can have constraints on selecting just installed or just source
-- packages.
--
-- In particular, installed packages can only depend on other installed
-- packages while packages that are not yet installed but which we plan to
-- install can depend on installed or other not-yet-installed packages.
--
data InstalledConstraint = InstalledConstraint
| SourceConstraint
deriving (Eq, Show)
| DavidAlphaFox/ghc | libraries/Cabal/cabal-install/Distribution/Client/Dependency/TopDown/Types.hs | bsd-3-clause | 3,075 | 0 | 8 | 607 | 428 | 246 | 182 | 55 | 0 |
module SimplerNotation () where
{-@ myDiv :: x:Int -> y:{Int | y != 0} -> {v:Int | v = x / y} @-}
myDiv :: Int -> Int -> Int
myDiv = div
| mightymoose/liquidhaskell | tests/pos/SimplerNotation.hs | bsd-3-clause | 138 | 0 | 6 | 34 | 26 | 16 | 10 | 3 | 1 |
import Control.Monad (forM_)
main :: IO ()
main = forM_ [0..0xffff] $ \i -> do
putStrLn $ ".section s" ++ show i ++ ",\"\",@progbits"
putStrLn $ ".asciz \"Section " ++ show i ++ "\""
putStrLn ""
| ezyang/ghc | testsuite/tests/driver/recomp015/Generate.hs | bsd-3-clause | 205 | 0 | 11 | 46 | 85 | 41 | 44 | 6 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Language.PureScript.CodeGen.Lua.Monad where
import Control.Applicative
import Control.Monad.State.Strict
import Language.PureScript.Names
import Language.PureScript.Environment
import Language.PureScript.Lua.Options
data CGState = CGState
{ cgOpts :: Options
, cgEnv :: Environment
, cgModName :: ModuleName
, cgFreshVar :: Int
} deriving (Show)
newtype CG a = CG { runCG :: State CGState a }
deriving (Functor, Applicative, Monad, MonadState CGState)
fresh :: CG String
fresh = do
v <- gets cgFreshVar
let ret = "fresh_" ++ show v
modify $ \s -> s{cgFreshVar = v + 1}
return ret
| osa1/psc-lua | src/Language/PureScript/CodeGen/Lua/Monad.hs | mit | 689 | 0 | 11 | 145 | 190 | 110 | 80 | 21 | 1 |
-- Alternativ 2
-- Sett inn for n og lΓΈs for m
f m = 2 * (3240/m) + 2*m - 4 == 230
main = let [n, m] = map round $ filter f [1..3240] in
putStrLn $ show n ++ " " ++ show m
| MAPSuio/spring-challenge16 | puzzle_dimension/larstvei2.hs | mit | 181 | 0 | 11 | 55 | 96 | 48 | 48 | 3 | 1 |
module Arm.Internal.Type (
wordToSRType, wordToRegister, instructionSignedExtendBits,
instructionArrayBits, instructionFlag, parseRegister,
decodeImmediateShift, parseCondAt, decodeRegisterList,
wordToEndianState,
undefinedInstruction,
InstructionStreamState(..),
ArmRegister(..),
ArmInstr(..),
ArgumentsInstruction(..),
Cond(..),
InstrClass(..),
SRType(..),
Shift(..),
ArmBlock(..),
InstructionState(..),
) where
import Data.Binary
import Data.List
import Text.Printf
import Control.Applicative
import Data.Bits
import Data.Int (Int64)
class (Functor m, Monad m, Applicative m) => InstructionStreamState m where
instructionBits :: Int -> Int -> m Word32
parseInstruction :: m ArmInstr
nextInstruction :: m ()
instructionOffset :: m Int64
instructionOpcode :: m Word32
decodingState :: m InstructionState
data ArmRegister = R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | FP | R12 | SP | LR | PC
deriving (Show,Eq)
data ArmInstr =
ArmInstr {blockOffset :: Int64, code :: Word32, cond :: Cond, memonic :: InstrClass, isFlags :: Bool, args :: ArgumentsInstruction }
| NotParsed
| Undefined Int64 Word32
data InstructionState = ThumbState | ArmState
data ArmBlock = ArmBlock { sectionOffset :: Int64, block :: [ArmInstr], next :: [Int64], parseState :: InstructionState}
newtype Shift = Shift (SRType, Word32)
data EndianState = BE | LE
data Cond = CondEQ | CondNE | CondCS | CondCC | CondMI | CondPL | CondVS | CondVC | CondHI | CondLS | CondGE | CondLT | CondGT | CondLE | CondAL | Uncond
data ArgumentsInstruction =
RegisterShiftedArgs -- ^ Used for And, Eor, Sub, Rsb, Add, Sbc, Adc and related arithmetic instruction
ArmRegister -- ^ The rn register
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rs register
ArmRegister -- ^ The rm register
SRType -- ^ Shift type
| RegisterShiftShiftedArgs -- ^ For Lsl, Lsr, Asr, Ror instruction
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rm register
ArmRegister -- ^ The rn register
| RegisterShiftedTestArgs
ArmRegister -- ^ The rn register
ArmRegister -- ^ The rs register
ArmRegister -- ^ The rm register
SRType -- ^ Shift type
| RegisterShiftedMvnArgs
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rs register
ArmRegister -- ^ The rm register
SRType -- ^ Shift type
| RegisterArgs
ArmRegister -- ^ The rn register
ArmRegister -- ^ The rd regsiter
ArmRegister -- ^ The rm register
SRType -- ^ Shift type
Word32 -- ^ Immediate value to shift
| RegisterToRegisterArgs
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rm register
| RegisterMvnArgs
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rm register
SRType -- ^ Shift type
Word32 -- ^ Immediate value to shift
| ImmediateArgs
ArmRegister -- ^ The rn register
ArmRegister -- ^ The rd register
Word32 -- ^ Immediate value
| ImmediateMovArgs
ArmRegister -- ^ The rd register
Word32 -- ^ Immediate value
| ImmediateTestArgs
ArmRegister -- ^ The rn register
Word32 -- ^ The immediate value
| ImmediateRelativeArgs -- ^ For adr
ArmRegister -- ^ The rd register
Word32 -- ^ The relative immediate value
Bool -- ^ Add the relative value or not
| RegisterTestArgs
ArmRegister -- ^ The rn register
ArmRegister -- ^ The rm register
SRType -- ^ Shift type
Word32 -- ^ Immediate value to shift
| ShiftArgs
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rm register
Word32 -- ^ Immediate value to shift
| SaturateArgs
ArmRegister -- ^ The rn register
ArmRegister -- ^ The rd register
Word32 -- ^ Saturate value
SRType -- ^ Shift type
Word32 -- ^ The value to shift
| BranchArgs
Int -- ^ Immediate value to branch
| BranchExchangeArgs
ArmRegister -- ^ The rm register
| CompareBranchArgs
ArmRegister -- ^ The rn register
Word32 -- ^ The value to branch to
| MultiplyAccArgs
ArmRegister -- ^ The rd register
ArmRegister -- ^ The ra register
ArmRegister -- ^ The rm register
ArmRegister -- ^ The rn register
Bool -- ^ If we take the high bits of rm
Bool -- ^ If we take the high bits of rn
| MultiplyAccWordArgs
ArmRegister -- ^ The rd register
ArmRegister -- ^ The ra register
ArmRegister -- ^ The rm register
ArmRegister -- ^ The rn register
Bool -- ^ If we take the high bits of rm
| MultiplyHalfArgs
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rm register
ArmRegister -- ^ The rn register
Bool -- ^ If we take the high bits of rm
| MultiplyAccLongArgs
ArmRegister -- ^ The rdhi register
ArmRegister -- ^ The rdlo register
ArmRegister -- ^ The rm register
ArmRegister -- ^ The rn register
Bool -- ^ If we take the high bits of rm
Bool -- ^ If we take the high bits of rn
| MultiplyArgs
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rm register
ArmRegister -- ^ The rn register
Bool -- ^ If we take the high bits of rm
Bool -- ^ If we take the high bits of rn
| LoadLiteralArgs
ArmRegister -- ^ The rt register
Word32 -- ^ The immediate value to fetch
Bool -- ^ Add immediate value
| LoadStoreRegisterArgs
ArmRegister -- ^ The rm register
ArmRegister -- ^ The rn register
ArmRegister -- ^ The rt register
Word32 -- ^ Indicate a LSL shift
| LoadStoreImmediateArgs
ArmRegister -- ^ The rn register
ArmRegister -- ^ The rt register
Word32 -- ^ The immediate value offset
Bool -- ^ Wback information
Bool -- ^ Index information
Bool -- ^ Add information
| ExtendArgs
ArmRegister -- ^ The rm register
ArmRegister -- ^ The rd register
Word32 -- ^ The rotation
| ExtendAddArgs
ArmRegister -- ^ The rn regsiter
ArmRegister -- ^ The rd register
ArmRegister -- ^ The rm register
Word32 -- ^ Rotation
| LoadAndStoreRegisterListArgs -- ^ For stm/ldm
ArmRegister -- ^ The rn register
Bool -- ^ Store or load way back
[ArmRegister] -- ^ The list of register
| RegisterListArgs -- ^ For pop/push
[ArmRegister] -- ^ The list of register
| SettingEndiannessArgs
EndianState -- ^ BE or LE
| ChangeProcessorStateArgs
Bool -- ^ True interupt enabled
Bool -- ^ Affect the A flag
Bool -- ^ Affect the I flag
Bool -- ^ Affect the F flag
Bool -- ^ True the mode is changed
Word32 -- ^ The number of mode to change
| StoreReturnStateArgs -- ^ For srs{db|ai} instruction
Bool -- ^ Direction of the write
Word32 -- ^ The mode to store
| ReturnArgs
ArmRegister -- ^ The rn register
Bool -- ^ wback flag
| ItBlockArgs
Cond -- ^ The condition that apply
[Bool] -- ^ Array for the second third and fourth instruction. Ture=then False=else
| NoArgs -- ^ Instruction with no argument
| NullArgs -- ^ For instruction that is not parsed
{-- This is not used for the time being
| ImmediatePcArgs
ArmRegister -- ^ The rd register
Word32 -- ^ The immediate value --}
-- | The ARM instruction memonic
data InstrClass =
Add | Adc | And | Asr | Adr |
Bkpt | Bic | B | Bl | Blx | Bx | Bxj |
Clz | Cmp | Cmn | Cbnz | Cbz | Cps |
Eor | Eret |
Hvc |
It |
Ldr | Ldrsb | Ldrh | Ldrb | Ldrsh | Ldrt | Ldm | Ldmdb |
Lsl | Lsr |
Mvn | Msr | Mov | Movw | Movs | Movt | Mrs | Mul |
Nop |
Orr | Orn |
Push | Pld | Pldw | Pop | Pkh |
Rsb | Rsc | Rrx | Ror | Rev | Rev16 | Revsh | Rfedb | Rfeia |
Sbc | Smc | Smla | Smlaw | Smulw | Smlal | Sub | Subs | Smul | Setend |
Srsdb | Srsia | Str | Strt | Strh | Strht | Strb | Strbt | Stm | Stmdb | Svc |
Sxth | Sxtb | Sxtab | Sxtah | Sxtab16 | Sxtb16 | Sev |
Tst | Teq |
Udf | Uxth | Uxtah | Uxtb | Uxtab | Uxtab16 | Uxtb16 |
Wfe | Wfi |
Yield
deriving (Show)
data SRType = ASR | LSL | LSR | ROR | RRX
instance Show ArgumentsInstruction where
show (RegisterArgs rn rd rm st n) = printf "%s,%s,%s %s" (show rd) (show rn) (show rm) (show $ decodeImmediateShift st n)
show (RegisterShiftShiftedArgs rd rm rn) = printf "%s,%s,%s" (show rd) (show rn) (show rm)
show (RegisterToRegisterArgs rd rm) = printf "%s,%s" (show rd) (show rm)
show (RegisterShiftedArgs rn rd rs rm st) = printf "%s,%s,%s %s %s" (show rd) (show rn) (show rm) (show st) (show rs)
show (RegisterShiftedTestArgs rn rs rm st) = printf "%s,%s %s %s" (show rn) (show rm) (show st) (show rs)
show (RegisterShiftedMvnArgs rd rs rm st) = printf "%s,%s %s %s" (show rd) (show rm) (show st) (show rs)
show (ImmediateArgs rn rd imm) = printf "%s,%s, #%d" (show rd) (show rn) imm
show (ImmediateMovArgs rd imm) = printf "%s, #%d" (show rd) imm
show (ImmediateTestArgs rd imm) = printf "%s, #%d" (show rd) imm
show (RegisterTestArgs rn rm st n) = printf "%s, %s %s" (show rn) (show rm) (show $ decodeImmediateShift st n)
show (RegisterMvnArgs rd rm st n) = printf "%s, %s %s" (show rd) (show rm) (show $ decodeImmediateShift st n)
show (ShiftArgs rd rm n) = printf "%s, %s #%d" (show rd) (show rm) n
show (BranchArgs imm) = printf "<PC+%x>" imm
show (BranchExchangeArgs rm) = (show rm)
show (LoadLiteralArgs rt imm True) = printf "%s, [PC, #%d]" (show rt) imm
show (LoadLiteralArgs rt imm False) = printf "%s, [PC, #-%d]" (show rt) imm
show (LoadStoreRegisterArgs rm rn rt 0) = printf "%s, [%s,%s]" (show rt) (show rn) (show rm)
show (LoadStoreRegisterArgs rm rn rt shift) = printf "%s, [%s,%s lsl #%d]" (show rt) (show rn) (show rm) shift
show (LoadStoreImmediateArgs rn rt imm False True add) = printf "%s, [%s, %s]" (show rt) (show rn) (showImmediate imm add)
show (LoadStoreImmediateArgs rn rt imm True True add) = printf "%s, [%s, %s]!" (show rt) (show rn) (showImmediate imm add)
show (LoadStoreImmediateArgs rn rt imm True False add) = printf "%s, [%s], %s" (show rt) (show rn) (showImmediate imm add)
show (ExtendArgs rm rd 0) = printf "%s, %s" (show rd) (show rm)
show (ExtendArgs rm rd rot) = printf "%s, %s, ROR #%d" (show rd) (show rm) rot
show (ExtendAddArgs rn rd rm 0) = printf "%s, %s, %s" (show rd) (show rn) (show rm)
show (ExtendAddArgs rn rd rm rot) = printf "%s, %s, %s, ROR #%d" (show rd) (show rn) (show rm) rot
show (CompareBranchArgs rn imm) = printf "%s, <PC+%x>" (show rn) imm
show (RegisterListArgs list) = printf "{%s}" (intercalate ", " (map show list))
show (ChangeProcessorStateArgs effect a i f chmode mode) = printf "%s %s%s" (showeffect effect) (showflag [a,i,f]) (showmode chmode mode)
where
showeffect True = "ie"
showeffect False = "id"
selectflag True text = text
selectflag False text = ""
showflag lst = intercalate "," (filter (not . null) (zipWith selectflag lst ["A","I","F"]))
showmode False _ = ""
showmode True mode = printf ", #%d" mode
show (LoadAndStoreRegisterListArgs rn wback reglist) = printf "%s%s %s" (show rn) (showwback wback) (intercalate ", " (map show reglist))
where
showwback True = "!"
showwback False = ""
show (StoreReturnStateArgs wback mode) = printf "SP%s, #%d" (showwback wback) mode
where
showwback True = "!"
showwback False = ""
show (ReturnArgs rn wback) = printf "%s%" (show rn) (showwback wback)
where
showwback True = "!"
showwback False = ""
show (ImmediateRelativeArgs rd imm adding) = printf "%s, <PC+#%s%d>" (show rd) (showsign adding) imm
where
showsign True = ""
showsign False = "-"
show (SaturateArgs rn rd sat st imm) = printf "%s, #%d, %s%s" (show rd) sat (show rn) (show $ decodeImmediateShift st imm)
show (ItBlockArgs cond lst) = printf "%s %s" (concat . (map toIt) $ lst) (show cond)
where
toIt True = "t"
toIt False = "e"
show NoArgs = ""
show NullArgs = "not parse args"
instance Show Shift where
show (Shift (_,0)) = ""
show (Shift (st,n)) = printf "%s #%d" (show st) n
instance Show SRType where
show ASR = "asr"
show LSL = "lsl"
show LSR = "lsr"
show ROR = "ror"
instance Show ArmInstr where
show ArmInstr {blockOffset=off, code=co, cond=c,memonic=m, isFlags=flgs, args=arguments} = printf "%08X: %08X %s%s %s" off co (show m) (show c) (show arguments)
show NotParsed = "Unknown"
show (Undefined blockOffset code) = printf "%08X: %08X Undefined" blockOffset code
instance Show Cond where
show CondEQ = ".eq"
show CondNE = ".ne"
show CondCS = ".cs"
show CondCC = ".cc"
show CondMI = ".mi"
show CondPL = ".pl"
show CondVS = ".vs"
show CondVC = ".vc"
show CondHI = ".hi"
show CondLS = ".ls"
show CondGE = ".ge"
show CondLT = ".lt"
show CondGT = ".gt"
show CondLE = ".le"
show CondAL = ""
show Uncond = ""
showImmediate :: Word32 -> Bool -> String
showImmediate w True = printf "#%d" w
showImmediate w False = printf "#-%d" w
wordToSRType :: Word32 -> SRType
wordToSRType 0 = LSL
wordToSRType 1 = LSR
wordToSRType 2 = ASR
wordToSRType 3 = ROR
wordToRegister :: Word32 -> ArmRegister
wordToRegister 0 = R0
wordToRegister 1 = R1
wordToRegister 2 = R2
wordToRegister 3 = R3
wordToRegister 4 = R4
wordToRegister 5 = R5
wordToRegister 6 = R6
wordToRegister 7 = R7
wordToRegister 8 = R8
wordToRegister 9 = R9
wordToRegister 10 = R10
wordToRegister 11 = FP
wordToRegister 12 = R12
wordToRegister 13 = SP
wordToRegister 14 = LR
wordToRegister 15 = PC
parseRegister :: InstructionStreamState m => Int -> m ArmRegister
parseRegister off = do
wordToRegister <$> instructionBits off 4
instructionFlag :: InstructionStreamState m => Int -> m Bool
instructionFlag off = (`testBit` 0) <$> instructionBits off 1
instructionSignedExtendBits :: InstructionStreamState m => Int -> Int -> m Word32
instructionSignedExtendBits off count = do
sig <- instructionBits (count - 1) 1
case sig of
0 -> instructionBits off count
1 -> (.|. complement ((2^count) - 1) ) <$> instructionBits off count
instructionArrayBits :: InstructionStreamState m => [Int] -> m [Word32]
instructionArrayBits = sequence . (fmap (`instructionBits` 1))
-- | Decoding of shift information.
-- See section A8.4.3 of thereference manual.
decodeImmediateShift :: SRType -> Word32 -> Shift
decodeImmediateShift LSL imm = Shift (LSL,imm)
decodeImmediateShift LSR 0 = Shift (LSR,32)
decodeImmediateShift LSR imm = Shift (LSR,imm)
decodeImmediateShift ASR 0 = Shift (ASR,32)
decodeImmediateShift ASR imm = Shift (ASR,imm)
decodeImmediateShift ROR 0 = Shift (RRX,1)
decodeImmediateShift ROR imm = Shift (ROR,imm)
-- | Convert a word to EndianState
wordToEndianState :: Word32 -> EndianState
wordToEndianState 1 = BE
wordToEndianState 0 = LE
-- | Decode the cond field in an instruction stream
parseCondAt :: InstructionStreamState m => Int -> m Cond
parseCondAt off = do
cond <- instructionBits off 4
case cond of
0 -> return CondEQ
1 -> return CondNE
2 -> return CondCS
3 -> return CondCC
4 -> return CondMI
5 -> return CondPL
6 -> return CondVS
7 -> return CondVC
8 -> return CondHI
9 -> return CondLS
10 -> return CondGE
11 -> return CondLT
12 -> return CondGT
13 -> return CondLE
14 -> return CondAL
15 -> return Uncond
-- | Return the undefined instruction
undefinedInstruction :: InstructionStreamState m => m ArmInstr
undefinedInstruction = Undefined <$> instructionOffset <*> instructionOpcode
-- We should validate that the length of the array is 16.
decodeRegisterList :: [Word32] -> [ArmRegister]
decodeRegisterList = reverse . fst . (foldr regselect ([],0))
where regselect 0 (r,i) = (r,i+1)
regselect 1 (r,i) = ((wordToRegister i):r,i+1)
| mathk/arm-isa | Arm/Internal/Type.hs | mit | 17,931 | 0 | 16 | 5,912 | 4,289 | 2,337 | 1,952 | 374 | 16 |
module P003 (main, solveBasic) where
{-
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
-}
import qualified Common as C
input :: Integer
input = 600851475143
main :: IO ()
main =
C.time "P003(Basic): " $ solveBasic input
-- η΄ ε ζ°εθ§£γγ¦γγ
-- η΅ε±γγγδΈηͺιγγ£γ
solveBasic :: Integer -> Integer
solveBasic = maximum . map snd . C.primeFactors
| yyotti/euler_haskell | src/P003.hs | mit | 440 | 0 | 7 | 77 | 85 | 49 | 36 | 9 | 1 |
divideByTen :: (Floating a) => a -> a
divideByTen = (/10)
isUpperAlphaNum :: Char -> Bool
isUpperAlphaNum :: (`elem` ['A'..'Z'])
| v0lkan/learning-haskell | sections.hs | mit | 130 | 2 | 6 | 21 | 56 | 32 | 24 | -1 | -1 |
-- https://www.reddit.com/r/dailyprogrammer/comments/pii6j/difficult_challenge_1/
module Main where
import System.IO
data Bounds =
Bounds { lower :: Int
, upper :: Int
}
updateBounds :: Ordering -> Int -> Bounds -> Maybe Bounds
updateBounds ord k bnd =
case ord of
LT -> Just $ bnd { upper = min (k - 1) $ upper bnd }
EQ -> Nothing
GT -> Just $ bnd { lower = max (k + 1) $ lower bnd }
guessNumber :: Bounds -> (Bool, Int)
guessNumber bnd = (iAmSure, myGuess) where
iAmSure = lower bnd == upper bnd
myGuess = (upper bnd + lower bnd) `quot` 2
readAnswer :: IO Ordering
readAnswer = do
c <- getChar
putStrLn ""
case c of
'h' -> return GT
'e' -> return EQ
'l' -> return LT
_ -> putStrLn "Malformed input!" >> readAnswer
loop :: Bounds -> IO ()
loop bnd = do
let (b , n) = guessNumber bnd
putStrLn $ "Is your number higher (h), equal to (e)\
\ or lower than (l) " ++ show n ++ "?"
ord <- readAnswer
let bnd' = updateBounds ord n bnd
maybe (putStrLn "Nice!")
(if b then const (putStrLn "Bullshit!") else loop)
bnd'
main :: IO ()
main = do
hSetBuffering stdin NoBuffering
putStrLn "Pick a number between 1 and 100."
putStrLn "I'm going to try to guess it!"
loop $ Bounds 1 100
| gallais/dailyprogrammer | difficult/001/Main.hs | mit | 1,287 | 0 | 14 | 343 | 451 | 224 | 227 | 40 | 4 |
module Actions where
import Direction
import Data.Char
import Data.List
data Action = Move Direction | Inventory | Pickup String | Drop String | Use String | Quit deriving (Eq, Show)
-- I need to create an association list of [ terms ] - builder
type AdvancedList = [([String], String -> Action)]
advanced :: AdvancedList
advanced = [ (pickupVerbs, Pickup), (dropVerbs, Drop), (useVerbs, Use) ]
findAdvanced :: String -> AdvancedList -> Maybe Action
findAdvanced input adv =
foldr (\(vs, f) b ->
let command = find (\c -> isPrefixOf c input) vs
in maybe b (\c -> Just $ f (drop (length c + 1) input)) command
) Nothing adv
findAction :: String -> Either String Action
findAction "N" = Right (Move North)
findAction "S" = Right (Move South)
findAction "E" = Right (Move East)
findAction "W" = Right (Move West)
findAction "LIST" = Right Inventory
findAction "Q" = Right Quit
findAction action =
maybe (Left action) Right (findAdvanced action advanced)
pickupVerbs = [ "TAKE", "PICK UP" ]
dropVerbs = [ "DROP", "PUT DOWN" ]
useVerbs = [ "USE" ]
getAction :: IO (Either String Action)
getAction = fmap (findAction . map toUpper) getLine
| disquieting-silence/adventure | src/Actions.hs | mit | 1,178 | 0 | 19 | 237 | 435 | 234 | 201 | 28 | 1 |
module DictCC.Output
( printResults
) where
import Prelude hiding (length, maximum, replicate)
import Data.Int
import qualified Data.List as List
import Data.Text.Lazy
import Data.Text.Format as F
import DictCC.DictCC
type Header = Text
type ColumnWidth = Int64
type HeaderDescription = (Header, ColumnWidth)
type Limit = Int
printResults :: Results -> Limit -> IO ()
printResults Results{ translations = [] } _ = putStrLn "No translations found."
printResults results limit = do
let limitedTrans = limitResults limit $ translations results
let maxFromLen = List.maximum $ List.map (length . source) limitedTrans
let maxToLen = List.maximum $ List.map (length . target) limitedTrans
printHeaders ((fromHeader results, maxFromLen), (toHeader results, maxToLen))
mapM_ (printResult (maxFromLen, maxToLen)) limitedTrans
where
limitResults :: Int -> [a] -> [a]
limitResults limit xs =
case limit of
0 -> xs
x -> List.take x xs
-- Print a translation
printResult :: (ColumnWidth, ColumnWidth) -> Translation -> IO ()
printResult (toLen, frLen) (Translation from to vote _) =
let votes = if vote == 0 then (pack "") else (pack $ " [" ++ show vote ++ " \10003]")
in F.print "{} {}{}\n"
(justifyLeft frLen ' ' from,
justifyRight (toLen - length votes)' ' to,
votes)
-- Prints the headers and the underline taking
printHeaders :: (HeaderDescription, HeaderDescription) -> IO ()
printHeaders (frHeader, toHeader) =
let (fr, frLen) = frHeader
(to, toLen) = toHeader
frUnderline = underline $ length fr + 3
toUnderline = underline $ length to + 3
in F.print "{} {}\n"
(justifyLeft frLen ' ' fr,
justifyRight toLen ' ' to)
>> F.print "{} {}\n"
(justifyLeft frLen ' ' frUnderline,
justifyRight toLen ' ' toUnderline)
-- Creates a header underline of specified length
underline = flip replicate "="
| matt-snider/dict.cc | src/DictCC/Output.hs | mit | 2,105 | 0 | 13 | 598 | 627 | 334 | 293 | 45 | 2 |
-- Ball Upwards
-- http://www.codewars.com/kata/566be96bb3174e155300001b/
module Codewars.G964.Ball where
maxBall :: Int -> Int
maxBall v0 = round $ (10.0 * fromIntegral v0)/(3.6 * 9.81)
| gafiatulin/codewars | src/7 kyu/Ball.hs | mit | 189 | 0 | 9 | 26 | 51 | 29 | 22 | 3 | 1 |
{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving,
MultiParamTypeClasses, DeriveFunctor, DeriveGeneric, ViewPatterns #-}
module Rubik.Cube.Moves.Internal where
import Rubik.Cube.Coord
import Rubik.Cube.Cubie.Internal
import Rubik.Misc
import Control.DeepSeq
import Control.Monad.Loops ( iterateUntil )
import Control.Monad.Random
import Control.Newtype
import Data.Binary.Storable
import Data.Char ( toLower )
import Data.Function ( on )
import Data.List
import Data.Maybe
import Data.Monoid
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import GHC.Generics
newtype MoveTag m a = MoveTag { unMoveTag :: a }
deriving (Eq, Ord, Functor, Show, Binary, NFData)
instance Newtype (MoveTag m a) a where
pack = MoveTag
unpack = unMoveTag
data Move18
data Move10
-- | Associate every elementary move with an 'ElemMove'.
move18Names :: MoveTag Move18 [ElemMove]
move10Names :: MoveTag Move10 [ElemMove]
move18Names = MoveTag [ (n, m) | m <- [U .. D], n <- [1 .. 3] ]
move10Names
= MoveTag $ [ (n, m) | m <- [U, D], n <- [1 .. 3] ] ++ [ (2, m) | m <- [L .. B] ]
-- Elementary moves
u_ =
unsafeCube' ([1, 2, 3, 0] ++ [4..7])
(replicate 8 0)
([1, 2, 3, 0] ++ [4..11])
(replicate 12 0)
-- | Up
u = u_
-- | Left
l = surf3 ?? d
-- | Front
f = surf3 ?? r
-- | Right
r = surf3 ?? u
-- | Back
b = surf3 ?? l
-- | Down
d = sf2 ?? u
-- | List of the 6 generating moves.
--
-- > move6 = [u,l,f,r,b,d]
move6 = [u, l, f, r, b, d]
-- | List of the 18 elementary moves.
--
-- > move18 = [u, u <>^ 2, u <>^ 3, ...]
move18 :: MoveTag Move18 [Cube]
move18 = MoveTag $ move6 >>= \x -> [x, x <>^ 2, x <>^ 3]
-- | Generating set of @G1@
move6' = [u,d] ++ map (<>^ 2) [l, f, r, b]
-- | > G1 = <U, D, L2, F2, R2, B2>
move10 :: MoveTag Move10 [Cube]
move10 = MoveTag $ ([u, d] >>= \x -> [x, x <>^ 2, x <>^ 3]) ++ drop 2 move6'
-- Symmetries
-- | Rotation of the whole cube
-- around the diagonal axis through corners URF and LBD
surf3 =
unsafeCube' [4, 5, 2, 1, 6, 3, 0, 7]
[2, 1, 2, 1, 2, 1, 2, 1]
[5, 9, 1, 8, 7, 11, 3, 10, 6, 2, 4, 0]
[1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1]
-- | Half-turn of the whole cube
-- around the FB axis
sf2 =
unsafeCube' [6, 5, 4, 7, 2, 1, 0, 3]
(replicate 8 0)
[6, 5, 4, 7, 2, 1, 0, 3, 9, 8, 11, 10]
(replicate 12 0)
-- | Quarter-turn around the UD axis
su4 =
unsafeCube' [1, 2, 3, 0, 5, 6, 7, 4]
(replicate 8 0)
[1, 2, 3, 0, 5, 6, 7, 4, 9, 11, 8, 10]
(replicate 8 0 ++ [1, 1, 1, 1])
-- | Reflection w.r.t. the RL slice plane
slr2 =
unsafeCube' [3, 2, 1, 0, 5, 4, 7, 6]
(replicate 8 5)
[2, 1, 0, 3, 6, 5, 4, 7, 9, 8, 11, 10]
(replicate 12 0)
-- | Index of a symmetry
newtype SymCode s = SymCode { unSymCode :: Int } deriving (Eq, Ord, Show)
data Symmetry sym = Symmetry
{ symAsCube :: Cube
, symAsMovePerm :: [Int]
}
data Symmetric sym a
rawMoveSym :: Symmetry sym -> [a] -> [a]
rawMoveSym sym moves = composeList moves (symAsMovePerm sym)
rawCast :: RawCoord a -> RawCoord (Symmetric sym a)
rawCast = RawCoord . unRawCoord
symmetry_urf3 = Symmetry surf3 [ 3 * f + i | f <- [2, 5, 3, 0, 1, 4], i <- [0, 1, 2] ]
symmetry_urf3' = Symmetry (surf3 <>^ 2) (composeList sym sym)
where sym = symAsMovePerm symmetry_urf3
mkSymmetry :: Cube -> Symmetry sym
mkSymmetry s = Symmetry s (fmap f moves)
where
f m = fromJust $ findIndex (== s <> m <> inverse s) moves
MoveTag moves = move18
-- x <- [0..47]
-- 2 * 4 * 2 * 3 = 48
-- 2 * 4 * 2 = 16
-- | Translate an integer to a symmetry.
symDecode :: SymCode s -> Cube
symDecode = (es V.!) . unSymCode
where es = V.generate 48 eSym'
eSym' x = (surf3 <>^ x1)
<> (sf2 <>^ x2)
<> (su4 <>^ x3)
<> (slr2 <>^ x4)
where x4 = x `mod` 2
x3 = (x `div` 2) `mod` 4
x2 = (x `div` 8) `mod` 2
x1 = x `div` 16 -- < 3
data UDFix
-- | Octahedral group
data CubeSyms
-- | Symmetries which preserve the UD axis
-- (generated by 'sf2', 'su4' and 'slr2')
sym16Codes :: [SymCode UDFix]
sym16Codes = map SymCode [0..15]
sym16 :: [Symmetry UDFix]
sym16 = map mkSymmetry sym16'
sym16' = map symDecode sym16Codes
-- | All symmetries of the whole cube
sym48Codes :: [SymCode CubeSyms]
sym48Codes = map SymCode [0..47]
sym48 :: [Symmetry CubeSyms]
sym48 = map mkSymmetry sym48'
sym48' = map symDecode sym48Codes
--
composeSym :: SymCode sym -> SymCode sym -> SymCode sym
composeSym = \(SymCode i) (SymCode j) -> SymCode (symMatrix U.! flatIndex 48 i j)
where
symMatrix = U.fromList [ c i j | i <- [0 .. 47], j <- [0 .. 47] ]
c i j = fromJust $ findIndex (== s i <> s j) sym48'
s = symDecode . SymCode
invertSym :: SymCode sym -> SymCode sym
invertSym = \(SymCode i) -> SymCode (symMatrix U.! i)
where
symMatrix = U.fromList (fmap inv [0 .. 47])
inv j = fromJust $ findIndex (== inverse (s j)) sym48'
s = symDecode . SymCode
-- | Minimal set of moves
data BasicMove = U | L | F | R | B | D
deriving (Enum, Eq, Ord, Show, Read, Generic)
instance NFData BasicMove
-- | Quarter turns, clock- and anti-clockwise, half turns
type ElemMove = (Int, BasicMove)
-- | Moves generated by 'BasicMove', 'group'-ed
type Move = [ElemMove]
infixr 5 `consMove`
-- Trivial reductions
consMove :: ElemMove -> Move -> Move
consMove nm [] = [nm]
consMove nm@(n, m) (nm'@(n', m') : moves)
| m == m' = case (n + n') `mod` 4 of
0 -> moves
p -> (p, m) : moves
| oppositeAndGT m m' = nm' `consMove` nm `consMove` moves
consMove nm moves = nm : moves
-- | Relation between faces
--
-- @oppositeAndGT X Y == True@ if X and Y are opposite faces and @X > Y@.
oppositeAndGT :: BasicMove -> BasicMove -> Bool
oppositeAndGT = curry (`elem` [(D, U), (R, L), (B, F)])
-- | Perform "trivial" reductions of the move sequence.
reduceMove :: Move -> Move
reduceMove = foldr consMove []
-- | Scramble the solved cube.
moveToCube :: Move -> Cube
moveToCube = moveToCube' . reduceMove
moveToCube' :: Move -> Cube
moveToCube' [] = iden
moveToCube' (m : ms) = elemMoveToCube m <> moveToCube' ms
basicMoveToCube :: BasicMove -> Cube
basicMoveToCube = (move6 !!) . fromEnum
elemMoveToCube :: ElemMove -> Cube
elemMoveToCube (n, m) = unMoveTag move18 !! (fromEnum m * 3 + n - 1)
-- | Show the move sequence.
moveToString :: Move -> String
moveToString =
intercalate " "
. (mapMaybe $ \(n, m)
-> (show m ++) <$> lookup (n `mod` 4) [(1, ""), (2, "2"), (3, "'")])
-- | Associates s character in @"ULFRBD"@ or the same in lowercase
-- to a generating move.
decodeMove :: Char -> Maybe BasicMove
decodeMove = (`lookup` zip "ulfrbd" [U .. D]) . toLower
-- | Reads a space-free sequence of moves.
-- If the string is incorrectly formatted,
-- the first wrong character is returned.
--
-- @([ulfrbd][23']?)*@
stringToMove :: String -> Either Char Move
stringToMove [] = return []
stringToMove (x : xs) = do
m <- maybe (Left x) Right $ decodeMove x
let (m_, next) =
case xs of
o : next | o `elem` ['\'', '3'] -> ((3, m), next)
'2' : next -> ((2, m), next)
_ -> ((1, m), xs)
(m_ :) <$> stringToMove next
-- | Remove moves that result in duplicate actions on the Rubik's cube
nubMove :: [Move] -> [Move]
nubMove = nubBy ((==) `on` moveToCube)
-- * Random cube
-- | Decode a whole @Cube@ from coordinates.
coordToCube
:: RawCoord CornerPermu
-> RawCoord CornerOrien
-> RawCoord EdgePermu
-> RawCoord EdgeOrien
-> Cube
coordToCube n1 n2 n3 n4 = Cube (Corner cp co) (Edge ep eo)
where
cp = decode n1
co = decode n2
ep = decode n3
eo = decode n4
-- | Generate a random solvable 'Cube'.
--
-- Relies on 'randomRIO'.
randomCube :: MonadRandom m => m Cube
randomCube = iterateUntil solvable $
coordToCube
<$> randomRawCoord
<*> randomRawCoord
<*> randomRawCoord
<*> randomRawCoord
| Lysxia/twentyseven | src/Rubik/Cube/Moves/Internal.hs | mit | 8,061 | 0 | 17 | 2,065 | 2,894 | 1,665 | 1,229 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
module Handler.Result where
import Foundation
import Yesod.Core
import Yesod.Persist
import Yesod.Auth
getResultR :: ResultId -> Handler Html
getResultR x = do
maid <- maybeAuthId
(Result a b c d _) <- runDB $ get404 x
defaultLayout $ do
setTitle "Haskell Calculator - Results"
addStylesheetRemote "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
[whamlet|
<nav class="navbar navbar-inverse navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation
<span class="icon-bar">
<span class="icon-bar">
<a class="navbar-brand" href=@{HomeR}>Calculator
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">
<a href=@{HomeR}>Home
<li>
<a href=@{HistoryR}>Latest Results
<ul class="nav navbar-nav navbar-right">
$maybe _ <- maid
<li><a href="@{AuthR LogoutR}">Logout</a>
$nothing
<li><a href="@{AuthR LoginR}">Login</a>
<div class="container">
<div class="jumbotron">
<h2> #{a} #{c} #{b} = #{d}
<div class="page-header">
<p> If you tried to divide by 0, you will be returned a result of 0. This is due to the fact that dividing by 0 can't be done.
<footer class="footer">
(c) Peter McNeil 2017 - 15848156
|]
| petermcneil/yesod-calculator | Handler/Result.hs | mit | 1,968 | 0 | 10 | 717 | 108 | 56 | 52 | 16 | 1 |
-- let's have a little file for taking the KJV and making a little bible verse generator
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe
import Control.Monad.Random
import Data.Char
import Data.List
import Control.Monad
import BibleRot
type Table = Map [String] [(String, Rational)] -- invariant: the lists all must be the same length or else the algorithm doesn't work
-- if what you're looking for doesn't show up then let's presume that we can drop down to just the
-- last word used as a singlet instead
nextStep :: RandomGen g => [String] -> Table -> Rand g String
nextStep ss t = case (M.lookup ss t) of
Nothing -> case (M.lookup [last ss] t) of
Nothing -> error $ "howwww: " ++ (last ss)
Just ws -> fromList ws
Just ws -> fromList ws
-- the argument for the very first call needs to be a seed, from there the further
-- calls are generated from the results of the previous call
generateStrings :: RandomGen g => Int -> [String] -> Table -> Rand g [String]
generateStrings 0 _ _ = return []
generateStrings n strs t = do
s <- nextStep strs t
ss <- generateStrings (n-1) (tail strs ++ [s]) t
return $ s : ss
-- now we make a table from a file
-- parseBible returns [(String, [[String]])] which isn't quite right format.
-- Need to cut punctuation out and turn to all lower case as well
toWords :: String -> [String]
toWords = words . map toLower . filter (\x -> isAlpha x || isSpace x)
where punc c = and [c /= '.', c /= '!', c /= ',', c /= '"', c /= ';', c /= ',', c/= ':']
digit c = and $ map (\d -> c /= chr d) [0..9]
nGroup :: Int -> [a] -> [[a]]
nGroup n [] = []
nGroup n xs = (take n xs) : (nGroup n (drop n xs))
-- we're going to specialize to groups of 3 from here on
-- the invariant here is that the length of the first arg is one less than the lengths of
-- the inner lists of the second arg and lord am I dying for vector types right about now
prefixToFrequencies :: Eq a => [a] -> [[a]] -> [(a, Rational)]
prefixToFrequencies testXs groups = let short = length testXs
groups' = group $ filter (\xs -> take short xs == testXs) groups
in map (\l -> (last (head l), fromIntegral $ length l)) groups'
dropLast :: [a] -> [a]
dropLast = reverse . tail . reverse
groupsToFrequencies :: (Ord a , Eq a) => [[a]] -> Map [a] [(a, Rational)]
groupsToFrequencies ts = let tGroups = nub $ map dropLast ts
in M.fromList $ map (\ x -> (x, prefixToFrequencies x ts)) tGroups
verseGenerator :: String -> Int -> IO ()
verseGenerator f n = do
s <- readFile f
let strs = toWords $ take 1000000 s
tab1 = groupsToFrequencies $ nGroup 3 strs
tab2 = groupsToFrequencies $ nGroup 2 strs
tab = M.union tab1 tab2
x <- liftM unwords $ evalRandIO $ generateStrings n ["the", "lord"] tab
putStrLn $ "the lord " ++ x
| clarissalittler/nanogenmo-2015 | markov.hs | mit | 2,986 | 0 | 14 | 793 | 947 | 496 | 451 | 46 | 3 |
module ParametrizedTypes where
import Data.List (intercalate)
import qualified Data.Map as Map
import Data.Maybe (isNothing)
data Triple a = Triple a a a deriving Show
first :: Triple a -> a
first (Triple x _ _) = x
second :: Triple a -> a
second (Triple _ x _) = x
third :: Triple a -> a
third (Triple _ _ x) = x
transform :: (a -> a) -> Triple a -> Triple a
transform f (Triple x y z) = Triple (f x) (f y) (f z)
toList :: Triple a -> [a]
toList (Triple x y z) = [x, y, z]
type Point3D = Triple Double
aPoint :: Point3D
aPoint = Triple 0.1 53.2 12.3
cool_stuff_you_can_do_with_transform = transform (* 3) aPoint
-- Lists
-- Ξ»> :info []
-- data [] a = [] | a : [a] -- Defined in βGHC.Typesβ
-- Ξ»> :type []
-- [] :: [t]
-- Ξ»> :kind []
-- [] :: * -> *
-- Kinds are deprecated now (now it's Types). From GHC 8.6 (Should check, not sure).
data List a = Empty | Cons a (List a) deriving Show
-- mapL (+15) (Cons 10 (Cons 5 Empty))
mapL :: (a -> b) -> List a -> List b
mapL _ Empty = Empty
mapL f (Cons x xs) = Cons (f x) (mapL f xs)
data Organ = Heart | Brain | Kidney | Spleen deriving (Show, Eq, Ord)
-- The idea is to put organs into labeled lockers (let's create this labels)
ids :: [Int]
ids = [2,7,13,14,21,24]
organs :: [Organ]
organs = [Heart, Heart, Brain, Spleen, Spleen, Kidney]
-- We'll use Map.fromList to create the Map!
-- Ξ»> Map.fromList
-- Map.fromList :: Ord k => [(k, a)] -> Map.Map k a
-- keys sould be Ord-ered because of the lookup way.
pairs = [(2, Heart), (7, Heart), (13, Brain)]
organPairs :: [(Int, Organ)]
organPairs = zip ids organs
organCatalog :: Map.Map Int Organ
organCatalog = Map.fromList organPairs
-- My organ inventory. Organ is key.
-- Value - is list of lockers. (it's better to use Set I guess)
organInventory :: Map.Map Organ [Int]
organInventory = Map.fromList [(Heart, [1,2,3])]
possibleDrawers :: [Int]
possibleDrawers = [1..50]
getDrawerContents :: [Int] -> Map.Map Int Organ -> [Maybe Organ]
getDrawerContents ids catalog = map getContents ids
where getContents = \id -> Map.lookup id catalog
availableOrgans :: [Maybe Organ]
availableOrgans = getDrawerContents possibleDrawers organCatalog
countOrgan :: Organ -> [Maybe Organ] -> Int
countOrgan organ available = length (filter
(\x -> x == Just organ)
available)
-- Let's create a beautifull printing for
-- Maybe organs.
isSomething :: Maybe Organ -> Bool
isSomething Nothing = False
isSomething (Just _) = True
justTheOrgans :: [Maybe Organ]
justTheOrgans = filter isSomething availableOrgans
showOrgan :: Maybe Organ -> String
showOrgan (Just organ) = show organ
showOrgan Nothing = ""
organList :: [String]
organList = map showOrgan justTheOrgans
cleanList :: String
cleanList = intercalate ", " organList
-- Next task:
-- Youβll be given a drawer ID.
-- You need to retrieve an item from the drawer.
-- Then youβll put the organ in the appropriate container (a vat, a cooler, or a bag).
-- Finally, youβll put the container in the correct location.
-- Here are the rules for containers and locations:
-- For containers:
-- ο‘ Brains go in a vat.
-- ο‘ Hearts go in a cooler.
-- ο‘ Spleens and kidneys go in a bag.
-- For locations:
-- ο‘ Vats and coolers go to the lab.
-- ο‘ Bags go to the kitchen.
data Container = Vat Organ | Cooler Organ | Bag Organ
instance Show Container where
show (Vat organ) = show organ ++ " in a vat"
show (Cooler organ) = show organ ++ " in a cooler"
show (Bag organ) = show organ ++ " in a bag"
data Location = Lab | Kitchen | Bathroom deriving Show
organToContainer :: Organ -> Container
organToContainer Brain = Vat Brain
organToContainer Heart = Cooler Heart
organToContainer organ = Bag organ
placeInLocation :: Container -> (Location, Container)
placeInLocation (Vat a) = (Lab, Vat a)
placeInLocation (Cooler a) = (Lab, Cooler a)
placeInLocation (Bag a) = (Kitchen, Bag a)
process :: Organ -> (Location, Container)
process organ = placeInLocation (organToContainer organ)
report :: (Location, Container) -> String
report (location, container) = show container ++ " in the " ++ show location
proccessRequest :: Int -> Map.Map Int Organ -> String
proccessRequest id catalog = processAndReport organ
where organ = Map.lookup id catalog
-- Right now your processRequest function handles
-- reporting when thereβs an error.
-- Ideally, youβd like the report function to handle this.
-- But to do that given your knowledge so far,
-- youβd have to rewrite process to accept a Maybe.
-- Youβd be in a worse situation, because youβd no
-- longer have the advantage of writing a processing function
-- that you can guarantee doesnβt have to worry about a missing value.
processAndReport :: (Maybe Organ) -> String
processAndReport (Just organ) = report (process organ)
processAndReport Nothing = "error, id not found"
-- q19.1
emptyDrawers :: Int
emptyDrawers = length $ filter isNothing $ availableOrgans
| raventid/coursera_learning | haskell/will_kurt/18_parametrized_types_worksheet.hs | mit | 4,998 | 0 | 11 | 992 | 1,346 | 738 | 608 | 84 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Widgets.Setting where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Ref
import Data.Default
import Data.Dependent.Map (DSum (..))
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid ((<>))
import GHCJS.DOM
import GHCJS.DOM.Element
import GHCJS.DOM.Element
import GHCJS.DOM.HTMLInputElement
import GHCJS.DOM.HTMLLabelElement
import GHCJS.DOM.HTMLSelectElement
import GHCJS.DOM.Node (nodeAppendChild)
import GHCJS.DOM.Types (Element (..))
import GHCJS.Foreign
import GHCJS.Types
import Reflex
import Reflex
import Reflex.Dom
import Reflex.Dom
import Reflex.Host.Class
import Formats
import LocalStorage
import Widgets.Misc (icon)
#ifdef __GHCJS__
#define JS(name, js, type) foreign import javascript unsafe js name :: type
#else
#define JS(name, js, type) name :: type ; name = undefined
#endif
JS(makeCheckbox, "jQuery($1)['checkbox']()", Element -> IO ())
JS(makeDropdown, "dropdownOnChange($1, $2)", Element -> JSFun (JSString -> IO ()) -> IO ())
JS(dropdownSetValue,"jQuery($1)['dropdown']('set text', $2)", Element -> JSString -> IO ())
data Setting t =
Setting {_setting_value :: Dynamic t Bool}
data Selection t =
Selection {_selection_value :: Dynamic t String
,_selection_setValue :: Event t String}
data SelectionConfig t =
SelectionConfig {_selectionConfig_initialValue :: String
,_selectionConfig_label :: String
,_selectionConfig_options :: Dynamic t (Map String String)
,_selectionConfig_setValue :: Event t String}
instance Reflex t => Default (SelectionConfig t) where
def =
SelectionConfig {_selectionConfig_initialValue = ""
,_selectionConfig_label = ""
,_selectionConfig_options = constDyn mempty
,_selectionConfig_setValue = never}
setting :: MonadWidget t m => String -> Bool -> m (Setting t)
setting labelText initial =
do val <- liftIO (getPref labelText initial)
(parent,(input,_)) <-
elAttr' "div" ("class" =: "ui toggle checkbox") $
do el "label" (text labelText)
elAttr' "input"
("type" =: "checkbox" <>
if val
then "checked" =: "checked"
else mempty) $
return ()
liftIO (makeCheckbox $ _el_element parent)
eClick <-
wrapDomEvent (_el_element parent)
elementOnclick $
liftIO $
do checked <-
htmlInputElementGetChecked
(castToHTMLInputElement $ _el_element input)
setPref labelText $ show checked
return checked
dValue <- holdDyn val eClick
return (Setting dValue)
selection :: MonadWidget t m
=> SelectionConfig t -> m (Selection t)
selection (SelectionConfig k0 labelText options eSet) =
do (eRaw,_) <-
elAttr' "div" ("class" =: "ui dropdown compact search button") $
do elClass "span" "text" (text labelText)
icon "dropdown"
divClass "menu" $
do optionsWithDefault <-
mapDyn (`Map.union` (k0 =: "")) options
listWithKey optionsWithDefault $
\k v ->
elAttr "div"
("data-value" =: k <> "class" =: "item")
(dynText v)
postGui <- askPostGui
runWithActions <- askRunWithActions
(eRecv,eRecvTriggerRef) <- newEventWithTriggerRef
onChangeFun <-
liftIO $
syncCallback1
AlwaysRetain
True
(\kStr ->
do let val = fromJSString kStr
maybe (return ())
(\t ->
postGui $
runWithActions
[t :=>
Just val]) =<<
readRef eRecvTriggerRef)
liftIO $
makeDropdown (_el_element eRaw)
onChangeFun
let readKey opts mk =
fromMaybe k0 $
do k <- mk
guard $
Map.member k opts
return k
performEvent_ $
fmap (liftIO .
dropdownSetValue (_el_element eRaw) .
toJSString .
flip (Map.findWithDefault "md") sourceFormats .
extToSource)
eSet
dValue <-
combineDyn readKey options =<<
holdDyn (Just k0)
(leftmost [fmap Just eSet,eRecv])
return (Selection dValue never)
instance HasValue (Setting t) where
type Value (Setting t) = Dynamic t Bool
value = _setting_value
instance HasValue (Selection t) where
type Value (Selection t) = Dynamic t String
value = _selection_value
| osener/markup.rocks | src/Widgets/Setting.hs | mit | 5,329 | 7 | 22 | 1,931 | 1,222 | 638 | 584 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module GradientAscentSpec
( main
, spec
) where
import Ch05LogisticRegression.GradientAscent
import DataFiles
import qualified Data.Vector.Unboxed as VU
import MLUtil
import MLUtil.Test
import System.Random
import Test.Hspec
spec :: Spec
spec = do
describe "gradAscent" $ do
it "computes correct weights" $ do
Just LabelledMatrix{..} <- getDataFileName "testSet.txt" >>= readLabelledMatrix
let values = ones (rows lmValues, 1) ||| lmValues
labels = col (map fromIntegral (VU.toList lmLabelIds))
weights = toLists $ gradAscent 0.001 500 values labels
length weights `shouldBe` 3
length (weights !! 0) `shouldBe` 1
length (weights !! 1) `shouldBe` 1
length (weights !! 2) `shouldBe` 1
concat weights `shouldRoundTo` [4.12414, 0.48007, -0.61685]
describe "stocGradAscent0" $ do
it "computes correct weights" $ do
Just LabelledMatrix{..} <- getDataFileName "testSet.txt" >>= readLabelledMatrix
let values = ones (rows lmValues, 1) ||| lmValues
labels = col (map fromIntegral (VU.toList lmLabelIds))
weights = toLists $ stocGradAscent0 0.01 values labels
length weights `shouldBe` 3
length (weights !! 0) `shouldBe` 1
length (weights !! 1) `shouldBe` 1
length (weights !! 2) `shouldBe` 1
concat weights `shouldRoundTo` [1.01702, 0.85914, -0.3658]
describe "stocGradAscent1" $ do
it "computes correct weights" $ do
Just LabelledMatrix{..} <- getDataFileName "testSet.txt" >>= readLabelledMatrix
let values = ones (rows lmValues, 1) ||| lmValues
labels = col (map fromIntegral (VU.toList lmLabelIds))
rowCount = rows lmValues
g = mkStdGen 0
(eis, _) = foldl (\(eis, g) _ -> let Just (ei, g') = choiceExtractIndices' g rowCount rowCount in (ei : eis, g')) ([], g) [1 .. 150]
weights = toLists $ stocGradAscent1 0.01 values labels eis
length weights `shouldBe` 3
length (weights !! 0) `shouldBe` 1
length (weights !! 1) `shouldBe` 1
length (weights !! 2) `shouldBe` 1
concat weights `shouldRoundTo` [15.46236, 1.35436, -2.17271]
main :: IO ()
main = hspec spec
| rcook/mlutil | ch05-logistic-regression/spec/GradientAscentSpec.hs | mit | 2,495 | 0 | 24 | 797 | 783 | 402 | 381 | 51 | 1 |
module Examples.ExampleSpec where
import qualified Examples.Reader as Rd
import qualified Examples.Exception as Exc
import qualified Examples.Writer as Wrt
import qualified Examples.Search as Srch
import qualified Examples.Combined as Cmb
import Test.Hspec
import Test.QuickCheck
import Data.Either (isLeft, isRight)
spec :: Spec
spec = do
describe "A reader handler" $ do
it "Returns the same value with simple ask" $
property $ \x -> Rd.prg1res x == x
describe "An exception handler" $ do
it "Retruns a Left value if an exception was thrown" $
(isLeft Exc.prg1res) `shouldBe` True
it "Returns a Right value if no exeption was thrown" $
property $ \x -> Exc.prg2res x == (Right $ x + 1)
describe "Reader and Exception handler combined" $ do
it "Handle both effects" $ do
property $ \x ->
let res = Exc.prg3res x in
if x < 15
then res == (Left $ show x)
else res == (Right $ x + 1)
describe "Default value exception handler" $ do
it "Provides default value if exception is thrown" $ do
property $ \d x ->
let res = Exc.prg4res d x in
if x < 10
then res == d
else res == x + 1
describe "Writer handler"$ do
it "join the monoidal value of tell and return the result and log" $ do
Wrt.prg1res `shouldBe` ((), ["hello", "world"])
describe "DFS handler" $ do
it "works like [] for choose and fail on finite lists" $ do
Srch.prg1res `shouldBe` [(1,3), (1,4)]
describe
"Backtracking handler" $
it "works like dfs for choose and fail" $ do
Srch.prg1res2 `shouldBe` Just (1,3)
describe "Combined handler" $
it "runs" $
(isRight $ Cmb.testPrgRes 10) `shouldBe` True
| edofic/effect-handlers | test/Examples/ExampleSpec.hs | mit | 1,769 | 0 | 21 | 485 | 521 | 269 | 252 | 46 | 3 |
-- multi return values
vals :: () -> (Int, Int)
vals () = (3, 7)
main = do
let (a, b) = vals ()
print a
print b
let (_, c) = vals ()
print c
| solvery/lang-features | haskell/function_2.hs | gpl-2.0 | 164 | 0 | 11 | 59 | 100 | 49 | 51 | 8 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.LevelPuzzle.LevelPuzzleWorld.Wall
(
Wall (..),
makeWall,
) where
import MyPrelude
import Game
import Game.Grid
data Wall =
Wall
{
wallIsDouble :: !Bool,
wallNode :: !Node,
wallX :: !Node,
wallY :: !Node
}
makeWall :: Bool -> Node -> Node -> Node -> Wall
makeWall dbl node x y =
Wall dbl node x y
| karamellpelle/grid | source/Game/LevelPuzzle/LevelPuzzleWorld/Wall.hs | gpl-3.0 | 1,130 | 0 | 9 | 263 | 131 | 83 | 48 | 24 | 1 |
module LinguisticVariables.AccelLinguisticVariables where
import Domains.Domain
import Domains.DomainElement
import Domains.SimpleDomain
import FuzzySets.CalculatedFuzzySet
import FuzzySets.FuzzySet
import FuzzySets.FuzzySetHelper
acceleration :: ADomain
acceleration = ADomain $ simpleDomain (-80) 80
accelerationDomainIndex :: Int -> Int
accelerationDomainIndex e = indexOfElement acceleration $ domainElement [e]
neutralAccelI :: Int
neutralAccelI = accelerationDomainIndex 0
topAccelI :: Int
topAccelI = accelerationDomainIndex 80
brakeI :: Int
brakeI = accelerationDomainIndex (-80)
normalAccelI :: Int
normalAccelI = accelerationDomainIndex 32
accelerationFuzzySet :: MembershipFunction -> AFuzzySet
accelerationFuzzySet f = AFuzzySet $ calculatedFuzzySet f acceleration
brake :: AFuzzySet
brake = accelerationFuzzySet $ lFunctionGenerator brakeI neutralAccelI
topAccel :: AFuzzySet
topAccel = accelerationFuzzySet $ gammaFunctionGenerator normalAccelI topAccelI
weakAccel :: AFuzzySet
weakAccel = accelerationFuzzySet $ lambdaFunctionGenerator neutralAccelI normalAccelI topAccelI
neutralAccel :: AFuzzySet
neutralAccel = accelerationFuzzySet $ lambdaFunctionGenerator (accelerationDomainIndex (-5)) neutralAccelI (accelerationDomainIndex 5)
slightDeccel :: AFuzzySet
slightDeccel = accelerationFuzzySet $ lambdaFunctionGenerator (accelerationDomainIndex (-10)) (accelerationDomainIndex (-5)) (accelerationDomainIndex 0)
| mrlovre/super-memory | Pro3/src/LinguisticVariables/AccelLinguisticVariables.hs | gpl-3.0 | 1,501 | 0 | 10 | 210 | 319 | 171 | 148 | 31 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module WJR.ParamDefs
( ParamField(..), FieldType(..), paramDefs
) where
import WJR.GeneticCodes
import Data.Text (Text)
import qualified Data.Text as T
import Data.String
data FieldType = TextField
| CheckBoxField
| ListField [(Text,Text)]
data ParamField s m = ParamField { name :: Text
, label :: String
, tip :: String
, field :: FieldType
, defVal :: Maybe Text
, toRun :: ParamField s m -> Text -> [Text]
}
pairs = map (\x -> (x,x))
paramDefs :: [ParamField s m]
paramDefs =
let gcodes = map (\(a,b) -> (fromString $ b ++ " : " ++ a, fromString b)) geneticCodes
grams = pairs ["Ignore","+ve","-ve"]
in [ParamField "name" "Project Name" "A name for you to identifying this job by" TextField Nothing runNo
,ParamField "locustag" "Locus tag prefix" "Locus tag prefix" TextField (Just "PROKKA") runId
,ParamField "genus" "Genus" "Genus name - will be used to aid annotation" TextField (Just "Genus") runId
,ParamField "species" "Species" "Species name" TextField Nothing runId
,ParamField "strain" "Strain" "Strain name" TextField Nothing runId
,ParamField "gcode" "Genetic Code" "Genetic Code / Translation table" (ListField gcodes) (Just "11") runId
,ParamField "gram" "Gram" "Gram +ve or Gram -ve" (ListField grams) Nothing runGram
,ParamField "addgenes" "Add genes" "Add 'gene' features for each 'CDS' feature" CheckBoxField Nothing runBool
,ParamField "usegenus" "Use genus" "Use genus-specific BLAST databases (requires 'Genus' above to be defined)" CheckBoxField Nothing runBool
,ParamField "email" "Send Email" "Send an email upon job completion" CheckBoxField (Just "yes") runNo
]
runNo, runId, runBool, runGram :: ParamField a b -> Text -> [Text]
runNo _ _ = []
runId fld val = ["--" `T.append` name fld, val]
runBool fld val
| val=="yes" = ["--" `T.append` name fld]
| otherwise = []
runGram fld val
| val=="Ignore" = []
| otherwise = runId fld val
| drpowell/Prokka-web | WJR/ParamDefs.hs | gpl-3.0 | 2,283 | 0 | 15 | 649 | 596 | 326 | 270 | 41 | 1 |
-- | MΓ³dulo para la lista de iconViews de predicados.
module Sat.GUI.PredicateList where
import Graphics.UI.Gtk hiding (eventButton, eventSent,get)
import Control.Monad
import Control.Monad.Trans.RWS (ask)
import Control.Lens
import Sat.GUI.GState
import Sat.GUI.IconTable
import Sat.Core
type MakeIcon = Predicate -> GuiMonad IconT
-- | La configuraciΓ³n de la lista de figuras propiamente hablando.
configPredicateList :: [([Predicate],MakeIcon)] -> GuiMonad ()
configPredicateList = foldM_ configPredList (return ())
configPredList :: GuiMonad () -> ([Predicate],MakeIcon) -> GuiMonad (GuiMonad ())
configPredList makeSep (ps,makeIcon) = ask >>= \content -> do
let predBox = content ^. gSatPredBox
addSep predBox
t <- io $ tableNew 1 1 False
makeSep
io $ boxPackStart predBox t PackNatural 1
io $ widgetShowAll t
iconList <- makeIconsT ps
configIconTable 3 t iconList (Just drawPrevFig)
return $ return ()
where
makeIconsT :: [Predicate] -> GuiMonad [IconT]
makeIconsT = mapM makeIcon
addSep :: HBox -> GuiMonad ()
addSep predBox = io $ do
vs <- vSeparatorNew
boxPackStart predBox vs PackNatural 0
widgetShowAll vs
| manugunther/sat | Sat/GUI/PredicateList.hs | gpl-3.0 | 1,327 | 0 | 12 | 363 | 371 | 192 | 179 | 29 | 1 |
-- Author: Matthew Wraith
module Teapot where
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
import qualified Data.Vector as V
import Control.Monad
-- Data structure for holding the model
-- We have vertex, normal, and texture data
data Model = Model
{ vertices :: !(V.Vector (Vertex3 GLdouble))
, normals :: !(V.Vector (Normal3 GLdouble))
, texcoord :: !(V.Vector (TexCoord2 GLdouble))
} deriving (Show)
-- Calculate the texture coordinates for each vertex
teapotTexCoord (Vertex3 x y z) =
let theta = atan2 z x
s = (theta + pi) / (2 * pi)
t = y
in TexCoord2 s t
-- Render the vertices, normals, and textures
renderVNT vs ns ts = do
let vnts = zip3 vs ns ts
forM_ vnts $ \(v,n,t) -> do
normal n
texCoord t
vertex v
-- Draw the teapot model
drawModel (Model vs ns ts,fs) = do
V.forM_ fs $ \is -> do
let vs' = fromIndecies vs is
let ns' = fromIndecies ns is
let ts' = fromIndecies ts is
renderPrimitive Triangles $ do
renderVNT vs' ns' ts'
where fromIndecies xs = map (\i -> xs V.! (i - 1))
-- Speed of the teapot
tpspeed = 1.0
-- A dictionary of keys and functions to change the position of the teapot
-- K, I, J, L make the teapot move in the x-z plane
-- U and N make the teapot move vertically
teapotCommands =
[ ('k', \(x,y,z) -> (x,y,z + tpspeed))
, ('i', \(x,y,z) -> (x,y,z - tpspeed))
, ('l', \(x,y,z) -> (x + tpspeed,y,z))
, ('j', \(x,y,z) -> (x - tpspeed,y,z))
, ('u', \(x,y,z) -> (x,y + tpspeed,z))
, ('n', \(x,y,z) -> (x,y - tpspeed,z))
]
-- Acquire the teapot position functions from teapotCommands
keyboardTeapot :: (HasSetter s, HasGetter s) =>
s (GLdouble, GLdouble, GLdouble) -> Key -> KeyState -> IO ()
keyboardTeapot pos (Char k) Down = do
p <- get pos
case lookup k teapotCommands of
Just posf -> pos $=! posf p
Nothing -> return ()
keyboardTeapot _ _ _ = return ()
| WraithM/HTeapots | src/Teapot.hs | gpl-3.0 | 1,994 | 0 | 14 | 530 | 749 | 410 | 339 | 51 | 2 |
{-
teafree, a Haskell utility for tea addicts
Copyright (C) 2013 Fabien Dubosson <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Teafree.Core.Monad
( Teafree
, runTeafree
, liftIO
, ask
, failure
, return
, catchAny
, abort
, throwError
) where
import Control.Monad.Error
import Control.Monad.Reader
import Teafree.Core.Environment
import Teafree.Core.TeafreeError
newtype Teafree t = T {runT ::Β ErrorT TeafreeError (ReaderT Environment IO) t}
deriving (Monad, MonadError TeafreeError, MonadReader Environment, MonadIO)
runTeafree :: Teafree t -> Environment -> IO (Either TeafreeError t)
runTeafree t = runReaderT $ runErrorT (runT t)
failure :: String -> Teafree t
failure = throwError . strMsg
abort ::Β Teafree t
abort = throwError Aborted
catchAny :: Teafree t -> (TeafreeError -> Teafree t) -> Teafree t
catchAny = catchError
| StreakyCobra/teafree | src/Teafree/Core/Monad.hs | gpl-3.0 | 1,586 | 0 | 9 | 332 | 233 | 130 | 103 | 25 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-------------------------------------------------------------------------------
-- |
-- Module : OpenSandbox.Protocol.Handle.Handshaking
-- Copyright : (c) 2016 Michael Carpenter
-- License : GPL3
-- Maintainer : Michael Carpenter <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------
module OpenSandbox.Protocol.Handle.Handshaking
( handleHandshaking
, deserializeHandshaking
) where
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Lazy
import qualified Control.Monad.Trans.State.Lazy as State
import qualified Data.Attoparsec.ByteString as Decode
import qualified Data.ByteString as B
import Data.Conduit
import Data.Serialize
import qualified Data.Text as T
import OpenSandbox.Logger
import OpenSandbox.Protocol.Packet (SBHandshaking(..),SBStatus(..))
import OpenSandbox.Protocol.Types
logMsg :: Logger -> Lvl -> String -> IO ()
logMsg logger lvl msg = logIO logger "OpenSandbox.Protocol.Handle.Handshaking" lvl (T.pack msg)
handleHandshaking :: Logger -> Conduit (SBHandshaking,Maybe SBStatus) (StateT ProtocolState IO) SBStatus
handleHandshaking logger = awaitForever $ \handshake -> do
liftIO $ logMsg logger LvlDebug $ "Recieving: " ++ show handshake
case handshake of
(SBHandshake _ _ _ ProtocolHandshake,_) -> do
liftIO $ logMsg logger LvlDebug "Redundant handshake"
return ()
(SBHandshake _ _ _ ProtocolStatus,status) -> do
liftIO $ logMsg logger LvlDebug "Switching protocol state to STATUS"
lift $ State.put ProtocolStatus
forM_ status yield
(SBHandshake _ _ _ ProtocolLogin,_) -> do
liftIO $ logMsg logger LvlDebug "Switching protocol state to LOGIN"
lift $ State.put ProtocolLogin
return ()
(SBHandshake _ _ _ ProtocolPlay,_) -> do
liftIO $ logMsg logger LvlDebug "Rejecting attempt to set protocol state to PLAY"
return ()
(SBLegacyServerListPing,_) -> do
liftIO $ logMsg logger LvlDebug "Recieved LegacyServerListPing"
return ()
deserializeHandshaking :: Conduit B.ByteString (StateT ProtocolState IO) (SBHandshaking,Maybe SBStatus)
deserializeHandshaking = do
maybeBS <- await
case maybeBS of
Nothing -> return ()
Just bs ->
if B.take 2 bs /= "\254\SOH"
then
case runGet getSBHandshaking' bs of
Left _ -> leftover bs
Right (handshake,status) -> yield (handshake,status)
else
case Decode.parseOnly (Decode.takeByteString <* Decode.endOfInput) (B.tail bs) of
Left _ -> leftover bs
Right _ -> yield (SBLegacyServerListPing,Nothing)
where
getSBHandshaking' = do
ln <- getVarInt
bs <- getBytes ln
case decode bs of
Left err -> fail err
Right handshake -> do
end <- isEmpty
if end
then return (handshake,Nothing)
else do
ln' <- getVarInt
earlyBs <- getBytes ln'
case decode earlyBs of
Left _ -> return (handshake,Nothing)
Right earlyStatus -> return (handshake,Just earlyStatus)
| oldmanmike/opensandbox | src/OpenSandbox/Protocol/Handle/Handshaking.hs | gpl-3.0 | 3,286 | 0 | 22 | 740 | 836 | 430 | 406 | 68 | 8 |
module Hinance.User.Tag where
data Tag = TagAsset | TagExpense | TagIncome
| TagDiscount | TagShipping | TagTax | TagOther
deriving (Read, Show, Enum, Bounded, Eq, Ord)
| hinance/hinance | src/default/user_tag.hs | gpl-3.0 | 173 | 0 | 6 | 30 | 59 | 35 | 24 | 4 | 0 |
module Builtin.String where
import String as S
import AST
import Object
import Eval
import Context
import Err
import Builtin.Utils
import qualified Data.Map as M
import qualified Data.Text.Lazy as T
import Control.Monad.Except
import Data.Monoid
stringClass = buildClassEx "String" bootstrap bootClass
bootstrap = M.fromList [
("length" , VFunction lengthFn (0,Just 0))
, ("==" , VFunction eq (1,Just 2))
]
bootClass = M.fromList [
("concat" , VFunction concatFn (1,Nothing))
]
lengthFn :: [Value] -> EvalM ()
lengthFn [] = do
(VString s) <- innerValue
replyM_ $ VInt $ stringLength s
lengthFN _ = throwError $ Err "RunTimeError" "String#Length does not take arguments" []
eq :: [Value] -> EvalM ()
eq ((VString t):_) = do
(VString s) <- innerValue
if ( s == t)
then replyM_ VTrue
else replyM_ VFalse
eq [val] = do
slf <- innerValue
callT val "==" [slf,VTrue]
eq (val:_) = replyM_ VFalse
concatFn :: [Value] -> EvalM ()
concatFn [] = replyM_ $ VString $ mkStringLiteral ""
concatFn (s@(VString _):[]) = replyM_ s
concatFn ((VString s):(VString t):vals) = concatFn ((VString (s `mappend` t)):vals)
concatFn (s@(VString _):t:vals) = do
t' <- toString' t
concatFn (s:t':vals)
concatFn (s:vals) = do
s' <- toString' s
concatFn (s':vals)
toString' :: Value -> EvalM Value
toString' val = loop val 12
where
loop s@(VString str) _ = return s
loop _ 0 = throwError $ Err "RunTimeError" "Value refuses to be converted to a String" [val]
loop val' n = do
val'' <- eval (Call (EValue val') "to_s" [])
loop val'' (n-1)
| antarestrader/sapphire | Builtin/String.hs | gpl-3.0 | 1,608 | 0 | 14 | 348 | 701 | 365 | 336 | 50 | 3 |
module Main where
p1 = "([{"
p2 = "}])"
main = do
x <- getLine
print $ f [] x
f [] [] = True
f [] (a:as) = if elem a p1 then f [a] as else False
f (a:as) (b:bs) | elem b p1 = f (b:a:as) bs
| check_pair a b = f as bs
| otherwise = False
f _ [] = False
check_pair '(' b = b == ')'
check_pair '[' b = b == ']'
check_pair '{' b = b == '}' | cwlmyjm/haskell | Learning/parentheses.hs | mpl-2.0 | 354 | 2 | 9 | 107 | 230 | 114 | 116 | 15 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Addresses.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the specified address resource.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.addresses.get@.
module Network.Google.Resource.Compute.Addresses.Get
(
-- * REST Resource
AddressesGetResource
-- * Creating a Request
, addressesGet
, AddressesGet
-- * Request Lenses
, addProject
, addAddress
, addRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.addresses.get@ method which the
-- 'AddressesGet' request conforms to.
type AddressesGetResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"addresses" :>
Capture "address" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Address
-- | Returns the specified address resource.
--
-- /See:/ 'addressesGet' smart constructor.
data AddressesGet =
AddressesGet'
{ _addProject :: !Text
, _addAddress :: !Text
, _addRegion :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AddressesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'addProject'
--
-- * 'addAddress'
--
-- * 'addRegion'
addressesGet
:: Text -- ^ 'addProject'
-> Text -- ^ 'addAddress'
-> Text -- ^ 'addRegion'
-> AddressesGet
addressesGet pAddProject_ pAddAddress_ pAddRegion_ =
AddressesGet'
{ _addProject = pAddProject_
, _addAddress = pAddAddress_
, _addRegion = pAddRegion_
}
-- | Project ID for this request.
addProject :: Lens' AddressesGet Text
addProject
= lens _addProject (\ s a -> s{_addProject = a})
-- | Name of the address resource to return.
addAddress :: Lens' AddressesGet Text
addAddress
= lens _addAddress (\ s a -> s{_addAddress = a})
-- | Name of the region for this request.
addRegion :: Lens' AddressesGet Text
addRegion
= lens _addRegion (\ s a -> s{_addRegion = a})
instance GoogleRequest AddressesGet where
type Rs AddressesGet = Address
type Scopes AddressesGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient AddressesGet'{..}
= go _addProject _addRegion _addAddress
(Just AltJSON)
computeService
where go
= buildClient (Proxy :: Proxy AddressesGetResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Addresses/Get.hs | mpl-2.0 | 3,492 | 0 | 16 | 850 | 466 | 278 | 188 | 76 | 1 |
-- "Dao/Count.hs" newtype wrapping the 'Data.Int.Int64' data type but
-- instantiating 'Data.Monoid.Monoid' with integer addition.
--
-- Copyright (C) 2008-2015 Ramin Honary.
--
-- Dao is free software: you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation, either version 3 of the License, or (at your option) any later
-- version.
--
-- Dao 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 (see the file called "LICENSE"). If not, see the URL:
-- <http://www.gnu.org/licenses/agpl.html>.
-- | This module provides the 'Count' data type, which is a newtype wrapping
-- the 'Data.Word.Word' data type used to keep count characters, lines,
-- columns, or whatever. Instantiates 'Data.Monoid.Monoid' with the functions
-- for integer addition.
module Dao.Count (Count(Count), countToInt) where
import Control.DeepSeq
import qualified Data.Array.IArray as A
import Data.Int
import Data.Monoid
import Data.Typeable
-- | A newtype wrapping the 'Data.Word.Word' data type used to keep count characters, lines,
-- columns, or whatever. Instantiates 'Data.Monoid.Monoid' with the functions for integer addition.
-- All classes necessary for using a 'Count' as an ordinary integer value are instantiated. This
-- means you can write @1::'Count'@ and it will wokr.
newtype Count = Count { countToInt :: Int64 } deriving (Eq, Ord, Bounded, A.Ix, Typeable)
instance Show Count where { show (Count o) = show o }
instance Read Count where { readsPrec p = fmap (\ (a, rem) -> (Count a, rem)) . readsPrec p }
instance Monoid Count where
mempty = Count 0
mappend = (+)
instance Num Count where
(Count a) + (Count b) = Count $ a+b
(Count a) * (Count b) = Count $ a*b
(Count a) - (Count b) = Count $ a-b
negate (Count a) = Count $ negate a
abs = id
signum (Count a) = if a==0 then 0 else 1
fromInteger = Count . fromInteger
instance Integral Count where
quotRem (Count a) (Count b) = let (a', b') = quotRem a b in (Count a', Count b')
toInteger (Count a) = toInteger a
instance Real Count where { toRational (Count a) = toRational a }
instance Enum Count where
succ (Count a) = Count $ succ a
pred (Count a) = Count $ pred a
toEnum = Count . toEnum
fromEnum (Count a) = fromIntegral a
enumFrom (Count a) = fmap Count $ enumFrom a
enumFromThen (Count a) (Count b) = fmap Count $ enumFromThen a b
enumFromTo (Count a) (Count b) = fmap Count $ enumFromTo a b
enumFromThenTo (Count a) (Count b) (Count c) = fmap Count $ enumFromThenTo a b c
instance NFData Count where { rnf (Count i) = deepseq i (); }
| printedheart/Dao | src/Dao/Count.hs | agpl-3.0 | 2,943 | 0 | 11 | 592 | 727 | 387 | 340 | 36 | 0 |
module Schizo.Expression where
import Data.Map as Map
data SchExp = Symbol String
| Operator String
| List [SchExp]
| Tuple [SchExp]
| Sequence [SchExp]
| Application (SchExp, [SchExp])
| Int64 Int
| Float64 Double
| String String
| Bool Bool
deriving (Eq, Show)
data Environment =
Environment { operators :: Map String Int -- infix operators
, impMacros :: Map String SchExp -- imported macros
, privMacros :: Map String SchExp -- private macros
, expMacros :: Map String SchExp -- exported macros
}
deriving Show
infixl 9 ?>?
(?>?) :: Maybe a -> Maybe a -> Maybe a
Just x ?>? _ = Just x
Nothing ?>? y = y
sxLookup :: String
-> Environment
-> Maybe SchExp
sxLookup s e = Map.lookup s (expMacros e)
?>? Map.lookup s (privMacros e)
?>? Map.lookup s (impMacros e)
?>? case Map.lookup s (operators e) of
Just i -> Just $ Operator s
Nothing -> Nothing
{-
-- Macro evaluation
-}
eval :: Environment
-> SchExp
-> (Environment, SchExp)
eval env e =
case e of
Symbol s ->
case sxLookup s env of
Just v -> eval env v -- recursively evaluate until all is exhausted
Nothing -> (env, e) -- return the same symbol (unresolved)
Application (h, args) -> apply env h args
_ -> (env, e)
apply :: Environment
-> SchExp
-> [SchExp]
-> (Environment, SchExp)
apply env e args = error "not implemented"
| eloraiby/SchizoHS | src/Schizo/Expression.hs | agpl-3.0 | 1,800 | 0 | 11 | 754 | 484 | 258 | 226 | 48 | 4 |
{-# language ViewPatterns, ScopedTypeVariables #-}
module Base.Score (
Scores,
HighScoreFile(..),
Record(..),
saveScore,
getScores,
setScores,
getHighScores,
mkScoreString,
showScore,
timeFormat,
batteryFormat,
sumOfEpisodeBatteries,
) where
import Data.Map as Map (Map, empty, lookup, insert)
import Data.Binary
import Data.Binary.Strict
import Data.Initial
import Data.Accessor
import Text.Printf
import Text.Logging
import System.FilePath
import System.Directory
import Utils
import Base.Paths
import Base.Types
import StoryMode.Types
type Scores = Map LevelUID Score
-- | type representing the Map of HighScores,
-- which will be written to file.
-- HighScoreFile has versioned constructors.
-- Serialisation uses the Binary class.
data HighScoreFile
= HighScoreFile_0 {
highScores :: Scores
}
| HighScoreFile_1 {
highScores :: Scores,
episodeScores :: Map EpisodeUID EpisodeScore
}
deriving Show
instance Initial HighScoreFile where
initial = HighScoreFile_1 empty empty
convertToNewest :: HighScoreFile -> HighScoreFile
convertToNewest (HighScoreFile_0 lhs) = HighScoreFile_1 lhs empty
convertToNewest x = x
-- Binary instance for serialisation
-- (to provide minimal cheating protection).
-- This instance has to work with the versioned
-- constructors!!!
instance Binary HighScoreFile where
put s@(HighScoreFile_0 _) = put $ convertToNewest s
put (HighScoreFile_1 lhs ehs) = do
putWord8 1
put lhs
put ehs
get = do
i <- getWord8
case i of
0 -> convertToNewest <$> HighScoreFile_0 <$> get
1 -> HighScoreFile_1 <$> get <*> get
data Record
= NoNewRecord
| NewRecord
| RecordTied
-- | Checks, if the given score is a new record (time- or battery-wise)
-- If yes, saves the new record.
-- Returns (Maybe oldHighScore, newTimeRecord, newBatteryRecord)
saveScore :: LevelFile -> Score -> IO (Maybe Score, Record, Record)
saveScore (levelUID -> uid) currentScore = do
highScores <- getHighScores
let mHighScore = Map.lookup uid highScores
case (currentScore, mHighScore) of
(_, Nothing) -> do
setHighScore uid currentScore
return (Nothing, NoNewRecord, NoNewRecord)
(Score_1_Tried, Just highScore) ->
return (Just highScore, NoNewRecord, NoNewRecord)
(Score_1_Passed _scoreTime scoreBatteryPower, oldHighScore)
| oldHighScore `elem` [Nothing, Just Score_1_Tried] -> do
setHighScore uid currentScore
let batteryRecord = if scoreBatteryPower == 0 then NoNewRecord else NewRecord
return (Nothing, NewRecord, batteryRecord)
(Score_1_Passed _scoreTime _scoreBatteryPower, Just highScore@Score_1_Passed{}) -> do
let newHighScore =
updateRecord timeCompare scoreTimeA currentScore $
updateRecord compare scoreBatteryPowerA currentScore $
highScore
when (newHighScore /= highScore) $
setHighScore uid newHighScore
return (Just highScore,
record timeCompare scoreTimeA currentScore highScore,
record batteryCompare scoreBatteryPowerA currentScore highScore)
where
timeCompare a b = swapOrdering $ compare a b
batteryCompare 0 _ = LT
batteryCompare a b = compare a b
updateRecord :: Compare a -> Accessor Score a -> Score -> Score -> Score
updateRecord compare acc current high =
case compare (current ^. acc) (high ^. acc) of
GT -> acc ^= (current ^. acc) $ high
_ -> high
record :: Compare a -> Accessor Score a -> Score -> Score -> Record
record compare acc current high =
case compare (current ^. acc) (high ^. acc) of
GT -> NewRecord
EQ -> RecordTied
LT -> NoNewRecord
type Compare a = a -> a -> Ordering
getScores :: IO HighScoreFile
getScores = do
filePath <- getHighScoreFilePath
content :: Maybe HighScoreFile <- decodeFileStrict filePath
case content of
Nothing -> do
logg Warning "highscore file not readable."
return initial
Just c -> return c
setScores scores = do
filePath <- getHighScoreFilePath
encodeFileStrict filePath scores
getHighScores :: IO Scores
getHighScores = highScores <$> getScores
setHighScores :: Scores -> IO ()
setHighScores m = do
eps <- episodeScores <$> getScores
let content :: HighScoreFile = HighScoreFile_1 m eps
setScores content
setHighScore :: LevelUID -> Score -> IO ()
setHighScore uid score = do
setHighScores . insert uid score =<< getHighScores
-- * pretty printing
mkScoreString :: Maybe Integer -> Maybe Score -> String
mkScoreString _ Nothing =
-- unplayed levels
showScore Nothing Nothing Nothing
mkScoreString mBatteries (Just score) =
inner score
where
inner :: Score -> String
inner Score_1_Tried =
showScore Nothing Nothing mBatteries
inner (Score_1_Passed time batteries) =
showScore (Just time) (Just batteries) mBatteries
showScore :: Maybe Seconds -> Maybe Integer -> Maybe Integer -> String
showScore mTime mCollected mTotal =
printf "[ %s | %s/%s ]"
(maybe "--:--:--" timeFormat mTime)
(maybe "---" batteryFormat mCollected)
(maybe "---" batteryFormat mTotal)
-- | formats the time (MM:SS:MM)
timeFormat :: Seconds -> String
timeFormat time =
printf "%02i:%02i:%02i" minutes seconds centiSeconds
where
(intSeconds, fractionSeconds) = properFraction time
intMinutes = floor (time / 60)
minutes :: Int = min 99 intMinutes
seconds :: Int = min 59 (intSeconds - (intMinutes * 60))
centiSeconds :: Int = min 99 $ ceiling (fractionSeconds * 100)
batteryFormat :: Integer -> String
batteryFormat = printf "%03i"
-- * file paths
-- | Returns the filepath to the highscore file
-- Initializes the file, if it doesn't exist.
getHighScoreFilePath :: IO FilePath
getHighScoreFilePath = do
confDir <- getConfigurationDirectory
let highScoreFilePath = confDir </> "highscores"
exists <- doesFileExist highScoreFilePath
when (not exists) $ do
-- initialize the file
let content :: HighScoreFile = initial
encodeFileStrict highScoreFilePath content
return highScoreFilePath
-- * episodes
-- | Adds up all collected batteries for one episode.
-- Does not account for batteries in an currently played level.
sumOfEpisodeBatteries :: Scores -> Episode LevelFile -> Integer
sumOfEpisodeBatteries highscore episode =
sum $ ftoList $ fmap getBatteryPower episode
where
getBatteryPower :: LevelFile -> Integer
getBatteryPower lf = case Map.lookup (levelUID lf) highscore of
Nothing -> 0
Just Score_1_Tried -> 0
Just (Score_1_Passed _ bp) -> bp
| nikki-and-the-robots/nikki | src/Base/Score.hs | lgpl-3.0 | 6,942 | 0 | 17 | 1,731 | 1,719 | 874 | 845 | 160 | 9 |
module External.A262343 (a262343) where
a262343 :: Integral a => a -> a
a262343 n
| m == 0 = div n 2 - 1
| m == 1 = 3 * n - 6
| m == 2 = 3 * div n 2 - 3
| m == 3 = n - 2
| m == 4 = 3 * div n 2 - 3
| m == 5 = 3 * n - 6 where
m = mod n 6
| peterokagey/haskellOEIS | src/External/A262343.hs | apache-2.0 | 279 | 0 | 8 | 125 | 177 | 85 | 92 | 10 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
-- |Various join strategies. The basic joins are of the 'summaryJoin' family.
-- These can be augmented with the @overwriteWith*@ difference handlers.
module System.IO.FileSync.JoinStrategies (
-- * Summary joins
summaryJoin,
summaryLeftJoin,
summaryRightJoin,
summaryInnerJoin,
summaryOuterJoin,
-- ** Utility functions for summary joins
performFileAction,
askSummaryJoin,
dontAskSummaryJoin,
reportSummaryJoin,
performSummaryJoin,
showFileAction,
-- ** Handlers for summary joins.
overwriteWithNewer,
overwriteWithLarger,
overwriteWithLeft,
overwriteWithRight,
) where
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Class (lift)
import qualified Control.Monad.Trans.State as S
import qualified Data.Conduit as Con
import qualified Data.Conduit.Lift as ConLift
import qualified Data.Conduit.List as ConL
import qualified Data.Text as T
import qualified Data.Tree as Tr
import System.Directory
import System.FilePath
import System.IO.Error
import System.REPL
import System.IO.FileSync.Types
import System.IO.FileSync.IO
-- import Debug.Trace
pattern JNode fp side <- Tr.Node (FTD fp _, side) _typ
-- Summary joins
-------------------------------------------------------------------------------
-- |Generic summary join. Creates a list of actions to be performed,
-- which can be run with 'performSummaryJoin'.
--
-- The Continue-part of the return value will be True iff the action handler
-- returns Nothing.
summaryJoin
:: DifferenceHandler -- ^Action for "left only" parts.
-> DifferenceHandler -- ^Action for "right only" parts.
-> DifferenceHandler -- ^Action for parts present in both trees.
-> JoinStrategy FileAction
summaryJoin lA rA bA _ _ path (JNode fp diff) = do
{- traceM $ "[summaryJoin] node: " ++ fp ++ " | " ++ show diff -}
let handler = case diff of {LeftOnly -> lA; RightOnly -> rA; Both -> bA}
act <- liftIO $ handler (path </> fp)
{- traceM $ "[summaryJoin] act: " ++ show act -}
case act of
Nothing -> return Yes
Just act' -> Con.yield act' >> return No
summaryJoin _ _ _ _ _ _ _ = error "summaryJoin: pattern match failure. This should never happen."
-- |Left join. See 'summaryJoin'.
summaryLeftJoin :: JoinStrategy FileAction
summaryLeftJoin = summaryJoin (return . Just . Copy LeftSide)
(return . Just . Delete RightSide)
(const $ return Nothing)
-- |Right join. See 'summaryJoin'.
summaryRightJoin :: JoinStrategy FileAction
summaryRightJoin = summaryJoin (return . Just . Delete LeftSide)
(return . Just . Copy RightSide)
(const $ return Nothing)
-- |Inner join. See 'summaryJoin'.
summaryInnerJoin :: JoinStrategy FileAction
summaryInnerJoin = summaryJoin (return . Just . Delete LeftSide)
(return . Just . Delete RightSide)
(const $ return Nothing)
-- |Full outer join. See 'summaryJoin'.
summaryOuterJoin :: JoinStrategy FileAction
summaryOuterJoin = summaryJoin (return . Just . Copy LeftSide)
(return . Just . Copy RightSide)
(const $ return Nothing)
-- |Prints a summary of actions to be done and asks the user whether to proceed.
-- If the user enters "yes", the consumed file actions are yielded back.
-- Otherwise, nothing is yielded.
--
-- Note that this function lists all actions to be done and therefore
-- pulls them all into memory.
askSummaryJoin :: LeftRoot -> RightRoot -> Con.Conduit FileAction IO (Either Int FileAction)
askSummaryJoin lr rr = do
actions <- ConL.consume
let total = length actions
liftIO $ putStrLn $ "You are about to perform the following " ++ show total ++ " operations:"
liftIO $ putStrLn $ "Left directory: " ++ getFilePath lr
liftIO $ putStrLn $ "Right directory: " ++ getFilePath rr
liftIO $ mapM (putStrLn . showFileAction) actions
(answer :: YesNo) <- ask' yesNoAsker
if answer == Yes
then do
liftIO $ putStrLn "Performing actions..."
Con.yield (Left $ length actions)
mapM_ (Con.yield . Right) actions
else
liftIO $ putStrLn "Doing nothing."
-- |Prints a header about the actions to be performed and yields them all back.
-- Note that this function yields the number of actions to be done and therefore
-- pulls them all into memory.
dontAskSummaryJoin :: LeftRoot -> RightRoot -> Con.Conduit FileAction IO (Either Int FileAction)
dontAskSummaryJoin lr rr = do
actions <- ConL.consume
let total = length actions
liftIO $ putStrLn $ "You are about to perform the following " ++ show total ++ " operations:"
liftIO $ putStrLn $ "Left directory: " ++ getFilePath lr
liftIO $ putStrLn $ "Right directory: " ++ getFilePath rr
liftIO $ putStrLn "Performing actions..."
Con.yield (Left $ length actions)
mapM_ (Con.yield . Right) actions
-- |Passes through 'FileAction's unchanged, but prints each to the CLI.
reportSummaryJoin
:: Con.Conduit (Either Int FileAction) IO FileAction
-- ^The StateT contains the current and total number of file actions performed.
reportSummaryJoin = ConLift.evalStateLC (1,0) $ do
Con.awaitForever $ \action -> case action of
-- Left case: we received the number of file actions in total
-- and store that in our state.
Left total -> lift $ S.modify (\(c,0) -> (c,total))
-- Right (regular) case: we receive, show, and yield a file action.
Right action' -> do
(cur, total) <- lift S.get
let counter = "(" ++ show cur ++ "/" ++ show total ++ ") "
lift $ S.put (cur+1,total)
liftIO $ putStrLn $ counter ++ showFileAction action'
Con.yield action'
-- |Takes a list of 'FileAction's and performs each in succession.
performSummaryJoin :: LeftRoot -> RightRoot -> Con.Sink FileAction IO ()
performSummaryJoin left right = do
action <- Con.await
case action of
Nothing -> liftIO $ putStrLn "Done."
Just a -> do liftIO $ performFileAction left right a
performSummaryJoin left right
yesNoAsker :: Monad m => Asker m T.Text YesNo
yesNoAsker = predAsker
"Perform these actions (y/n)? "
(\t -> return $ if elem (T.strip t) ["y","Y"] then Right Yes
else if elem (T.strip t) ["n","N"] then Right No
else Left $ genericPredicateError "Expected y/n.")
-- |Shows a 'FileAction' as a short line.
-- The path is printed, along with a code:
--
-- 1. "Copy to right": "C -->"
-- 1. "Copy to left": "C <--"
-- 1. "Delete from left": "D L"
-- 1. "Delete from right": "D R"
showFileAction :: FileAction -> String
showFileAction (Copy LeftSide fp) = "C -->: " ++ fp
showFileAction (Copy RightSide fp) = "C <--: " ++ fp
showFileAction (Delete LeftSide fp) = "D L: " ++ fp
showFileAction (Delete RightSide fp) = "D R: " ++ fp
-- |Performs a 'FileAction' (copying or deleting a file/directory).
-- Uses 'applyDeleteAction' and 'applyInsertAction'.
performFileAction :: LeftRoot -> RightRoot -> FileAction -> IO ()
performFileAction left right (Copy LeftSide fp) = applyInsertAction left right fp
performFileAction left right (Copy RightSide fp) = applyInsertAction right left fp
performFileAction left _ (Delete LeftSide fp) = applyDeleteAction left fp
performFileAction _ right (Delete RightSide fp) = applyDeleteAction right fp
-- Handlers for summary joins
-------------------------------------------------------------------------------
-- |Checks the modification times of two files/directories
-- and returns a 'FileAction' to copy the newer over the older one.
--
-- Returns Nothing if any one of these holds:
--
-- * Getting the modification time of either entry throws a 'PermissionError', or
-- * both entries have the same modification time.
--
-- Does not handle exceptions besides 'PermissionError'.
overwriteWithNewer :: LeftRoot
-> RightRoot
-> DifferenceHandler
overwriteWithNewer (LR lr) (RR rr) fp = let
lfp = lr </> fp
rfp = rr </> fp
in do
areDirs <- (&&) <$> doesDirectoryExist lfp <*> doesDirectoryExist rfp
if areDirs then return Nothing
else do lT <- handleIOErrors [isPermissionError] $ getModificationTime lfp
rT <- handleIOErrors [isPermissionError] $ getModificationTime rfp
return $ if lT > rT then Just (Copy LeftSide fp)
else if lT < rT then Just (Copy RightSide fp)
else Nothing
-- |Checks the modification times of two files/directories
-- and returns a 'FileAction' to copy the newer over the older one.
--
-- Returns Nothing if:
--
-- * Either of the two entries is not a file
-- * Getting the file size of either entry throws a 'PermissionError'.
-- * Both entries have the same size.
--
-- Does not handle exceptions besides 'InappropriateType' and 'PermissionError'.
overwriteWithLarger
:: LeftRoot
-> RightRoot
-> DifferenceHandler
overwriteWithLarger (LR lr) (RR rr) fp = do
lT <- handleIOErrors [isPermissionError, isInappropriateTypeError] $ getFileSize (lr </> fp)
rT <- handleIOErrors [isPermissionError, isInappropriateTypeError] $ getFileSize (rr </> fp)
return $ if lT > rT then Just (Copy LeftSide fp)
else if lT < rT then Just (Copy RightSide fp)
else Nothing
-- |If the path refers to a file, this function overwrites the right file with the left one.
-- Does nothing if the path refers to a directory.
overwriteWithLeft :: LeftRoot -> DifferenceHandler
overwriteWithLeft (LR root) fp = do
isFile <- doesFileExist (root </> fp)
return $ if isFile then Just $ Copy LeftSide fp else Nothing
-- |If the path refers to a file, this function overwrites the left file with the right one.
-- Does nothing if the path refers to a directory.
overwriteWithRight :: RightRoot -> DifferenceHandler
overwriteWithRight (RR root) fp = do
isFile <- doesFileExist (root </> fp)
return $ if isFile then Just $ Copy RightSide fp else Nothing
-- Utility functions
-------------------------------------------------------------------------------
-- |Deletes a file or directory. Does not handle exceptions.
-- This function tries to remove the target of the given path
-- as a directory. If that fails, it tries to remove it as a
-- file.
--
-- The path to remove is given by @S </> P@.
applyDeleteAction
:: FileRoot src
=> src -- ^Root S of the source.
-> FilePath -- ^Path P in the tree, starting from the root.
-> IO ()
applyDeleteAction src path =
catchThese [isDoesNotExistError, isInappropriateTypeError]
(removeDirectoryRecursive sPath)
(removeFile sPath)
where
sPath = getFilePath src </> path
-- |Copies a file or directory. This funciton tries to
-- to copy the given path as a directory. If that fails,
-- it tries to copy it as a file.
--
-- The source is given by @S </> P@. The target is given
-- by @T </> P@.
applyInsertAction
:: (FileRoot src, FileRoot trg)
=> src -- ^Root S of the source.
-> trg -- ^Root T of the target.
-> FilePath -- ^Path P in the tree, starting from the roots.
-> IO ()
applyInsertAction src trg path =
catchThese [isDoesNotExistError, isInappropriateTypeError]
(copyDirectory sPath tPath)
(copyFile sPath tPath)
where
sPath = getFilePath src </> path
tPath = getFilePath trg </> path
| jtapolczai/FileSync | System/IO/FileSync/JoinStrategies.hs | apache-2.0 | 11,684 | 0 | 22 | 2,641 | 2,349 | 1,234 | 1,115 | 177 | 4 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Phaedrus.Types
( Phaedrus(..)
, runPhaedrus
, PhaedrusOpts(..)
, Division(..)
, WindowSize
, WindowOffset
, WindowSpec
, Split(..)
, splitPath
, splitId
, splitN
, splitEvidence
, splitText
, Speech(..)
, speaker
, speechN
, TextLoc(..)
, tlTitle
, tlFile
, tlSpeech
, tlPage
, tlSection
, tlEvidence
, tlText
, EvidencePoint(..)
, epTitle
, epSection
, EvidenceSet
, BetaCode
, unBeta
, toBeta
, FreqPair(..)
, freqTotal
, freqDoc
, Frequencies
, Corpus(..)
, corpusDocuments
, corpusTypes
, Document
) where
import Control.Applicative
import Control.Error
import Control.Lens
import Control.Monad.IO.Class
import Data.Hashable
import qualified Data.HashMap.Strict as M
import qualified Data.HashSet as S
import Data.Monoid
import Data.Text
import qualified Data.Vector.Unboxed as V
import Filesystem.Path.CurrentOS
import GHC.Generics (Generic)
import Prelude hiding (FilePath)
import Phaedrus.Text.BetaCode (BetaCode, toBeta, unBeta)
newtype Phaedrus a = Phaedrus { unPhaedrus :: Script a }
deriving (Functor, Applicative, Monad, MonadIO)
data PhaedrusOpts
= PhO
{ phoVersion :: !Bool
, phoDataDir :: !FilePath
, phoOutput :: !(Maybe FilePath)
, phoDivision :: !Division
, phoWindow :: !WindowSize
, phoOffset :: !WindowOffset
, phoEvidenceFile :: !(Maybe FilePath)
, phoTrainingSize :: !Int
, phoEvidenceRatio :: !Double
} deriving (Eq, Show)
data Hole = Hole
runPhaedrus :: Phaedrus a -> IO a
runPhaedrus = runScript . unPhaedrus
data Division = Document | Section | Page | Speaking
deriving (Show, Read, Eq, Enum)
type WindowSize = Int
type WindowOffset = Int
type WindowSpec = (WindowSize, WindowOffset)
data Split
= Split
{ _splitPath :: !FilePath
, _splitId :: !Text
, _splitEvidence :: !Bool
, _splitN :: !Int
, _splitText :: !Text
} deriving (Show)
$(makeLenses ''Split)
data Speech
= Speech
{ _speaker :: !(Maybe Text)
, _speechN :: !Int
} deriving (Show)
$(makeLenses ''Speech)
data TextLoc
= TextLoc
{ _tlTitle :: !Text
, _tlFile :: !FilePath
, _tlSpeech :: !Speech
, _tlPage :: !Int
, _tlSection :: !Text
, _tlEvidence :: !Bool
, _tlText :: !Text
} deriving (Show)
$(makeLenses ''TextLoc)
data EvidencePoint
= Evidence
{ _epTitle :: !BetaCode
, _epSection :: !Text
} deriving (Eq, Show, Generic)
$(makeLenses ''EvidencePoint)
instance Hashable EvidencePoint
type EvidenceSet = S.HashSet EvidencePoint
type Frequencies a = M.HashMap a Int
data FreqPair = FreqPair
{ _freqTotal :: !Int
, _freqDoc :: !Int
} deriving (Show)
$(makeLenses ''FreqPair)
instance Monoid FreqPair where
mempty = FreqPair 0 0
a `mappend` b = FreqPair (_freqTotal a + _freqTotal b)
(_freqDoc a + _freqDoc b)
data Corpus a = Corpus
{ _corpusDocuments :: !Int
, _corpusTypes :: !(M.HashMap a FreqPair)
}
$(makeLenses ''Corpus)
type Document a = [a]
| erochest/phaedrus | Phaedrus/Types.hs | apache-2.0 | 3,847 | 0 | 12 | 1,365 | 922 | 538 | 384 | 188 | 1 |
--
-- Copyright (c) 2013, Carl Joachim Svenn
-- 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 GUI.GUIState
(
GUIState (..),
GUITick,
GUIShape (..),
GUIPos (..),
) where
import MyPrelude
import GUI.GUIShade
import OpenGL
import OpenGL.Helpers
-- (fixme: verify this)
-- INVARIANTS WHEN DRAWING A NEW WIDGET
--
-- * GUIState resembles GL-state, except FillTex
-- * all textures used shall be upside down (consistent with 2D drawing (FillTex))
-- * Program == ShadeGUI
-- * DepthTest enabled
-- * DepthFunc == GL_LEQUAL
-- * StencilTest disabled
-- * FrontFace == GL_CCW ? (vs 3D)
-- * CullFace disabled ? (vs 3D)
-- * y-direction is top to bottom
data GUIState =
GUIState
{
-- time
guistateTick :: !GUITick,
-- GL
guistateGUIShade :: GUIShade,
guistateAlpha :: !Float,
guistateProjModv :: !Mat4,
guistateWth :: !Float,
guistateHth :: !Float,
-- (fixme: more general, ProjModv :: Mat4)
guistatePos :: !GUIPos,
guistateScaleX :: !Float,
guistateScaleY :: !Float,
guistateDepth :: !Float,
guistateFocus :: !Float,
guistateFillTex :: !GLuint
}
-- | GUIShape's are relative to vertex xy-space
data GUIShape =
GUIShape
{
shapeWth :: !Float,
shapeHth :: !Float
}
-- | GUIPos's are relative to vertex xy-space
data GUIPos =
GUIPos
{
posX :: !Float,
posY :: !Float
}
type GUITick =
Double
| karamellpelle/MEnv | source/GUI/GUIState.hs | bsd-2-clause | 2,885 | 0 | 9 | 737 | 234 | 157 | 77 | 64 | 0 |
{-# LANGUAGE TemplateHaskell, OverloadedStrings, ScopedTypeVariables, TypeOperators #-}
module Handler.Root where
-- friends
import Foundation
-- | Root page redirects immediately to effects list page.
--
getHomeR :: Handler RepHtml
getHomeR = redirect RedirectSeeOther ListEffectsR
-- | 'About' page.
--
getAboutR :: Handler RepHtml
getAboutR = defaultLayout $ addWidget $(widgetFile "about")
| sseefried/funky-foto | Handler/Root.hs | bsd-2-clause | 399 | 0 | 9 | 55 | 60 | 34 | 26 | 7 | 1 |
module Text.Twine.Parser.Types where
import Data.ByteString.Char8 (ByteString)
type Key = ByteString
type Name = ByteString
type Template = [TemplateCode]
data Expr =
Func Name [Expr]
| Var Name
| StringLiteral ByteString
| NumberLiteral Integer
| Accessor Expr Expr
deriving (Show,Read,Eq)
data TemplateCode =
Text ByteString
| Slot Expr
| Loop Expr Key [TemplateCode]
| Cond Expr [TemplateCode]
| Incl FilePath
| Assign Key Expr
| Macro Name [Name] [TemplateCode]
deriving (Show)
| jamessanders/twine | src/Text/Twine/Parser/Types.hs | bsd-2-clause | 534 | 0 | 7 | 122 | 161 | 97 | 64 | 21 | 0 |
{- |
Module : Codec.Goat.TimeFrame
Description : Top-level header for time compression
Copyright : (c) Daniel Lovasko, 2016-2017
License : BSD3
Maintainer : Daniel Lovasko <[email protected]>
Stability : stable
Portability : portable
-}
module Codec.Goat.TimeFrame
( TimeFrame(..)
, timeDecode
, timeEncode
) where
import Codec.Goat.TimeFrame.Decode
import Codec.Goat.TimeFrame.Encode
import Codec.Goat.TimeFrame.Types
| lovasko/goat | src/Codec/Goat/TimeFrame.hs | bsd-2-clause | 443 | 0 | 5 | 66 | 44 | 31 | 13 | 7 | 0 |
module HSync.Client.Download where
import Network
import HSync.Client.Import hiding (newManager)
import HSync.Client.Actions
import HSync.Client.Foundation
import System.Environment
main = runMain $ do
b <- login
liftIO $ print b
-- storeDirectory (Path ["foo"])
tr <- getCurrentRealm (Path [])
liftIO $ print tr
downloadCurrent (Path [])
| noinia/hsync-client | src/HSync/Client/Download.hs | bsd-3-clause | 365 | 0 | 12 | 69 | 108 | 57 | 51 | 12 | 1 |
-- | Contains implementation of complete binary tree.
-- Declares the tree type as instance of type classes
-- Functor, Foldable, Traversable.
module Struct.Internal.CompleteBinaryTree where
import Prelude hiding (foldr)
import Control.Applicative
import Data.Monoid
import Data.Foldable
import Data.Traversable
data Tree a = Leaf a | Node a (Tree a) (Tree a)
deriving (Show)
count :: Tree a -> Int
count = foldr (+) 0 . fmap (const 1)
instance Functor Tree where
fmap f (Leaf x) = Leaf $ f x
fmap f (Node x l r) = Node (f x) (f `fmap` l) (f `fmap` r)
instance Foldable Tree where
foldMap f (Leaf x) = f x
foldMap f (Node x l r) = f x `mappend` (foldMap f l) `mappend` (foldMap f r)
instance Traversable Tree where
traverse f (Leaf x) = Leaf <$> f x
traverse f (Node x l r) = Node <$> f x <*> traverse f l <*> traverse f r
| roman-kashitsyn/pfds | src/Struct/Internal/CompleteBinaryTree.hs | bsd-3-clause | 862 | 0 | 9 | 195 | 350 | 185 | 165 | 19 | 1 |
import System.Environment (getArgs)
import Data.List (sort, transpose)
import Data.List.Split (splitOn)
unflatten :: Int -> [Int] -> [[Int]]
unflatten _ [] = []
unflatten x ys = take x ys : unflatten x (drop x ys)
sudosqus :: Int -> [Int] -> Bool
sudosqus 4 ys = sudorows 4 (take 2 ys ++ take 2 (drop 4 ys))
sudosqus 9 ys = sudorows 9 (take 3 ys ++ take 3 (drop 9 ys) ++ take 3 (drop 18 ys) ++
take 3 (drop 3 ys) ++ take 3 (drop 12 ys) ++ take 3 (drop 21 ys) ++
take 3 (drop 27 ys) ++ take 3 (drop 36 ys) ++ take 3 (drop 45 ys) ++
take 3 (drop 30 ys) ++ take 3 (drop 39 ys) ++ take 3 (drop 48 ys))
sudosqus _ _ = False
sudocols :: Int -> [Int] -> Bool
sudocols x ys = sudorows x (concat (transpose (unflatten x ys)))
sudorows :: Int -> [Int] -> Bool
sudorows _ [] = True
sudorows x ys | sort (take x ys) == [1..x] = sudorows x (drop x ys)
| otherwise = False
sudok :: Int -> [Int] -> Bool
sudok x ys = sudorows x ys && sudocols x ys && sudosqus x ys
sudoku :: [String] -> String
sudoku [xs, ys] | sudok (read xs) (map read $ splitOn "," ys) = "True"
| otherwise = "False"
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (sudoku . splitOn ";") $ lines input
| nikai3d/ce-challenges | moderate/sudoku.hs | bsd-3-clause | 1,416 | 0 | 20 | 472 | 698 | 344 | 354 | 29 | 1 |
module Framework where
import Framework.Api
| ojw/admin-and-dev | src/Framework.hs | bsd-3-clause | 46 | 0 | 4 | 7 | 9 | 6 | 3 | 2 | 0 |
module A
where
import qualified B
exportedString :: String
exportedString = "another string"
aString :: String
aString = B.exportedString
| 23Skidoo/ghc-parmake | tests/data/executable-mutrec/A.hs | bsd-3-clause | 148 | 0 | 5 | 29 | 30 | 19 | 11 | 6 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.