code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Main
where
import Control.Concurrent.Async.Lifted (async)
import Control.Exception (SomeException)
import Control.Monad (void, when)
import Control.Monad.Catch (catchAll)
import Data.List (intercalate, isPrefixOf)
import System.Environment (getEnv)
import Web.HZulip
main :: IO ()
main = withZulipEnv $ do
lift $ putStrLn "Subscribing to all streams..."
void addAllSubscriptions
lift $ putStrLn "Echoing..."
catchAll startEchoer onZulipError
startEchoer :: ZulipM ()
startEchoer = onNewMessage $ \msg -> do
nr <- nonRecursive msg
let c = messageContent msg
when (nr && "echo " `isPrefixOf` c) $ void $ async $ do
r <- case messageType msg of
"stream" ->
let Left stream = messageDisplayRecipient msg
topic = messageSubject msg
in sendStreamMessage stream topic c >> return topic
"private" ->
let Right users = messageDisplayRecipient msg
recipients = map userEmail users
in sendPrivateMessage recipients c >>
return (intercalate ", " recipients)
t -> fail $ "Unrecognized message type " ++ t
lift $ putStrLn $ "Echoed " ++ c ++ " to " ++ r
onZulipError :: SomeException -> ZulipM ()
onZulipError ex = lift $ putStrLn "Zulip Client errored:" >> print ex
nonRecursive :: Message -> ZulipM Bool
nonRecursive msg = do
z <- ask
return $ clientEmail z /= userEmail (messageSender msg)
withZulipEnv :: ZulipM a -> IO a
withZulipEnv action = do
user <- getEnv "ZULIP_USER"
key <- getEnv "ZULIP_KEY"
withZulipCreds user key action
| yamadapc/hzulip | examples/src/ZulipEchoBot.hs | gpl-2.0 | 1,670 | 11 | 27 | 459 | 497 | 240 | 257 | 42 | 3 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
module Network
( Layer(..)
, layer
, Network
, randomizeNetwork
, runNetwork
, trainN
)where
import Control.Monad.Random hiding (fromList)
import Numeric.LinearAlgebra
import ActFun
import Mux
data Layer = Layer { numNeurons :: Int
, numInputs :: Int
, weights :: Matrix Double
, actFuns :: [ActFun]
}
| Mux
deriving Show
{- Defines an unspecified layer -}
layer = Layer { weights = (0><0) []
, numNeurons = undefined
, numInputs = undefined
, actFuns = undefined
}
type Network = [Layer]
{- Randomization of layers -}
randomizeNetwork :: RandomGen g => Network -> Rand g Network
randomizeNetwork = mapM randomizeLayer
randomizeLayer :: RandomGen g => Layer -> Rand g Layer
randomizeLayer l =
randomizeLayerWeights l >>= \l -> randomizeLayerBiases l
randomizeLayerWeights :: RandomGen g => Layer -> Rand g Layer
randomizeLayerWeights Mux = return Mux
randomizeLayerWeights l@Layer{..} = do
rs <- getRandomRs (-1.0, 1.0)
return l { weights = (numNeurons >< numInputs) rs }
randomizeLayerBiases :: RandomGen g => Layer -> Rand g Layer
randomizeLayerBiases Mux = return Mux
randomizeLayerBiases l@Layer{..} = do
rs <- getRandomRs (-1.0, 1.0)
return l { actFuns = zipWith (\b af -> if xBias af /= 0.0 then af
else af { xBias = b }) rs actFuns }
{- Apply a network to an input vector -}
runNetwork :: Network -- network
-> Vector Double -- input
-> Vector Double -- output
runNetwork [] inp = inp
{- peel off the mux layer and run separately -}
runNetwork net@(last -> Mux) inp =
mux inp (runNetwork (init net) inp)
runNetwork (Mux:_) _ = error "Mux must be last layer"
runNetwork (Layer{..} : ls) inp =
runNetwork ls -- feed forward
$ fromList
$ zipWith (<$>) actFuns -- apply activation functions
$ toList (weights <> inp) -- compute weighted sum
{- Run network, but retain z-values (unactivated inputs)
- and activations for each layer
-}
runAndCollect :: Network -- network
-> [Vector Double] -- activations
-> [Vector Double] -- z-values
-> ([Vector Double], [Vector Double]) -- activations, z-values
runAndCollect [] as zs = (as, zs)
runAndCollect (Mux:_) _ _ = error "Mux must be last layer"
runAndCollect (Layer {..} : ls) as@(inp:_) zs =
runAndCollect ls (out:as) (z:zs)
where z = weights <> inp
out = zipListVectorWith (<$>) actFuns z
{- Compute delta for output layer to initiate backprop -}
deltas :: Vector Double -- actual
-> Vector Double -- expected
-> Network -- network
-> [Vector Double] -- z-values
-> [Vector Double] -- deltas
deltas actual expected net@(Layer{..}:_) (z:zs) = deltas' [d] zs net
where d = (actual - expected) * zipListVectorWith (<$^>) actFuns z
{- ^ hadamard product -}
{- Compute deltas for hidden layers -}
deltas' :: [Vector Double] -- deltas so far (accumulator)
-> [Vector Double] -- z-values
-> Network -- layers
-> [Vector Double] -- all deltas
deltas' ds _ [ ] = ds
deltas' ds _ [l] = ds
deltas' ds@(d:_) (z:zs) (nextLayer:thisLayer:ls) =
deltas' (d':ds) zs (thisLayer:ls)
where d' = (trans (weights nextLayer) <> d)
* zipListVectorWith (<$^>) (actFuns thisLayer) z
{- Utility function to apply list of activation functions to z-vector
- (done this way because activation functions are not instances of 'storable'
-}
zipListVectorWith f list vec = mapVectorWithIndex (\i v -> f (list !! i) v) vec
{- compute deltas and activations for all layers -}
deltasActs :: Network -- network
-> Vector Double -- input
-> Vector Double -- expected output
-> [(Vector Double, Vector Double)] -- (deltas, activations)
deltasActs net input expected = zipWith (,) ds (reverse as)
where ds = deltas out expected (reverse net) zs
((out:as), zs) = runAndCollect net [input] []
{- run one iteration of backpropagation -}
backProp :: Network -- network
-> Matrix Double -- learning rate (overloaded to 1x1 matrix)
-> [(Vector Double, Vector Double)] -- training samples
-> Network -- modified network
backProp net rate samples = change net weightChanges biasChanges
where {- compute deltas and activations for each sample -}
results = map (\(i,o) -> deltasActs net i o) samples
{- compute weight changes -}
weightChanges =
[ rate / size *
sum [ asColumn d <> asRow a
| (d,a) <- map (\l -> l !! n) results
]
| n <- [0..length net-1]
]
{- compute bias changes -}
biasChanges =
[ rate / size *
sum [ asColumn d
| (d,_) <- map (\l -> l !! n) results
]
| n <- [0..length net-1]
]
{- apply changes -}
change [] _ _ = []
change (Layer{..} : ls) (wc:wcs) (bc:bcs) =
Layer { weights = weights - wc
, actFuns = zipWith
(\ActFun{..} b -> ActFun{ xBias = xBias - b, .. })
actFuns ((concat.toLists) bc)
, .. } : (change ls wcs bcs)
size = fromIntegral (length samples)
trainN :: Integer -- number of iterations
-> Network -- network
-> Matrix Double -- learning rate (1x1 matrix)
-> [(Vector Double, Vector Double)] -- training samples
-> Network -- trained network
{- demux samples to provide accurate training data -}
trainN n net@(last -> Mux) rate muxed =
(trainN n (init net) rate samples) ++ [Mux]
where samples = map (\(i,o) -> (i, demux i o)) muxed
trainN 0 net _ _ = net
trainN n net rate samples = trainN (n-1) net' rate samples
where net' = backProp net rate samples
| morae/SortNet | Network.hs | gpl-2.0 | 6,261 | 0 | 16 | 2,002 | 1,818 | 985 | 833 | 122 | 2 |
{-# LANGUAGE CPP #-}
-- notmuch-haskell: notmuch MUA Haskell binding
-- test / demo program
-- Copyright © 2010 Bart Massey
-- Licensed LGPL v3: please see the file COPYING in this
-- source distribution for licensing information.
-- This program has two modes. When invoked with no
-- arguments, it creates a new notmuch database in /tmp.
-- When given a database argument, it does a search for
-- "subject:notmuch" in the notmuch database. It will
-- upgrade the database if necessary.
import Control.Monad
import Data.Time
import System.Environment
#if ! MIN_VERSION_time(1,5,0)
import System.Locale
#endif
import Foreign.Notmuch
dateString :: FormatTime t => t -> String
dateString = formatTime defaultTimeLocale "%c"
main :: IO ()
main = do
argv <- getArgs
db <- if (length argv == 0)
then
(do
db <- databaseCreate "/tmp"
databaseClose db
databaseOpen "/tmp" DatabaseModeReadOnly)
else
databaseOpen (head argv) DatabaseModeReadOnly
dbPath <- databaseGetPath db
putStrLn $ "database is at " ++ dbPath
version <- databaseGetVersion db
putStrLn $ "version is " ++ show version
upgrade <- databaseNeedsUpgrade db
when upgrade $ do
let cb msg progress = putStrLn $ msg ++ show progress
putStrLn "Upgrading database"
databaseUpgrade db (Just cb)
query <- queryCreate db "subject:notmuch"
nquery <- queryCountMessages query
putStrLn $ "subject:notmuch returns " ++ show nquery ++ " results..."
threads <- queryThreads query
nthreadss <- mapM threadCountMessages threads
putStr $ show (sum nthreadss) ++ "/" ++ show (length threads) ++ ": "
print nthreadss
case threads of
[] -> return ()
_ -> do
let thread = last threads
subject <- threadGetSubject thread
putStrLn subject
messages <- threadGetToplevelMessages thread
let message = head messages
subject' <- messageGetHeader message "Subject"
putStrLn subject'
date' <- messageGetHeader message "Date"
putStrLn date'
date <- messageGetDate message
putStrLn $ dateString date
localdate <- utcToLocalZonedTime date
putStrLn $ dateString localdate
databaseClose db
return ()
| bgamari/notmuch-haskell | NotmuchTest.hs | gpl-3.0 | 2,236 | 0 | 15 | 516 | 531 | 239 | 292 | 51 | 3 |
maybeTail :: List a -> Maybe (List a)
maybeTail Nil = Nothing
maybeTail (Cons _ t) = Just t | hmemcpy/milewski-ctfp-pdf | src/content/1.6/code/haskell/snippet31.hs | gpl-3.0 | 91 | 0 | 8 | 18 | 49 | 23 | 26 | 3 | 1 |
{-# OPTIONS_HADDOCK not-home #-}
{-|
A bridge between evaluated Tidal patterns and MIDI events.
This module contains functions necessary to mediate between
'Sound.Tidal.Time.Event's generated from a Tidal 'Sound.Tidal.Pattern.Pattern'
and plain MIDI events sent through 'Sound.PortMidi.PMStream'.
-}
module Sound.Tidal.MIDI.Output (
-- * Types
Output(..),
OutputState,
MidiDeviceMap,
TimedNote,
-- * Initialization
makeConnection,
flushBackend,
-- * Scheduling
sendevents,
store,
mkStore,
storeParams,
scheduleTime,
-- * Converters
toMidiValue,
cutShape,
stripDefaults,
-- * State handling
changeState,
readState,
-- * Low-level functions
useOutput,
displayOutputDevices,
outputDevice,
makeRawEvent,
noteOn,
noteOff,
makeCtrl
) where
-- generics
import Control.Applicative ((<$>), (<*>), pure)
import Control.Monad
import Control.Concurrent
import Control.Concurrent.MVar ()
import Data.Bits
import Data.List (sortBy, find, partition)
import qualified Data.Map as Map
import Data.Maybe
import Data.Ord (comparing)
import Data.Ratio (Ratio)
import Data.Time (getCurrentTime, UTCTime)
import Data.Time.Clock.POSIX
import Foreign.C
import Numeric
-- Tidal specific
import Sound.Tidal.Tempo (Tempo(Tempo))
import Sound.Tidal.Stream as S
-- MIDI specific
import Sound.Tidal.MIDI.Device
import Sound.Tidal.MIDI.Control
import qualified Sound.PortMidi as PM
type ConnectionCount = Int
type TickedConnectionCount = Int
type OutputOnline = Bool
{- |
Keep track of virtual streams
* Reflects the number of virtual streams that have already stored their events for this tick. Every time 'TickedConnectionCount' cycles, MIDI events will be sent out.
* 'ConnectionCount' is increased on every new stream created via `midiSetters`
* For each channel, currently used params and their values are kept.
* Output will only be scheduling, once __online__, i.e. when the first stream is initialized
-}
type OutputState = (
TickedConnectionCount,
ConnectionCount,
[ParamMap],
OutputOnline
)
type Tick = Int
type Onset = Double
type Offset = Double
type RelativeOffset = Double
type MIDITime = (Tempo, Tick, Onset, RelativeOffset)
type MIDIEvent = (MIDITime, MIDIMessage)
type MIDIChannel = CLong
type MIDIStatus = CLong
type MIDINote = MIDIDatum
type MIDIVelocity = MIDIDatum
type MIDIDatum = CLong
type MIDIDuration = Ratio Integer
type MIDIMessage = (MIDIChannel, MIDIStatus, MIDINote, MIDIVelocity)
-- | A Triplet of the deviation from the note @a5@, velocity and duration
type TimedNote = (CLong, MIDIVelocity, MIDIDuration)
type SentEvent = (CULong, Double, PM.PMEvent, CULong, UTCTime)
{-|
An abstract definition of a physical MIDI Output.
Manages virtual streams to multiple channels of a single connection to a MIDI device.
-}
data Output = Output {
cshape :: ControllerShape, -- ^ The ControllerShape defining which 'Param's will be available for use
conn :: PM.PMStream, -- ^ The physical connection to the device, uses 'PortMidi'
buffer :: MVar ([ParamMap], [MIDIEvent]), -- ^ A buffer of currently used 'Param's and their 'Value's as well as a list of 'MIDIEvent's to be sent on the next tick.
bufferstate :: MVar OutputState, -- ^ Keeps track of connected virtual streams during one tick
midistart :: CULong, -- ^ the MIDI time when this output was created
rstart :: UTCTime -- ^ the real time when this output was created
}
type MidiMap = Map.Map S.Param (Maybe Int)
type MidiDeviceMap = Map.Map String Output
-- | Initialize a connection to the given MIDI device by Name
makeConnection :: MVar MidiDeviceMap -- ^ The current list of already connected devices
-> String -- ^ The MIDI device name
-> Int -- ^ The MIDI channel
-> ControllerShape -- ^ The definition of useable 'Control's
-> IO (S.ToMessageFunc, Output) -- ^ A function to schedule MIDI events and the output that keeps track of connections
makeConnection devicesM displayname channel controllershape = do
moutput <- useOutput devicesM displayname controllershape
case moutput of
Just o -> do
s <- connected channel displayname o
return (s, o)
Nothing ->
error "Failed initializing MIDI connection"
{- |
Sends out MIDI events once all virtual streams have buffered their events.
This will be called after every tick
-}
flushBackend :: Output -> S.Shape -> Tempo -> Int -> IO ()
flushBackend o shape change ticks = do
changeState tickConnections o
cycling <- readState isCycling o
Control.Monad.when cycling (do
-- gather last sent params, update state with new
let buf = buffer o
(states, events) <- takeMVar buf
((_,_,newstates,_), (_,_,oldstates,_)) <- changeState' (resetParamStates states) o
-- find params that were removed
let mapDefaults = Map.mapWithKey (\k _ -> defaultValue k)
diffs = map mapDefaults $ zipWith Map.difference oldstates newstates
-- store additional "reset" events in buffer
-- schedule time must be exactly before/ontime with the next regular event to be sent. otherwise we risk
-- mixing order of ctrl messages, and resets get overridden
-- FIXME: when scheduling, note late CC messages and DROP THEM, otherwise everything is screwed
let offset = S.latency shape
mididiffs = map ((toMidiMap (cshape o)).(stripShape (toShape $ cshape o))) $ diffs
resetevents = concat $ zipWith (\x y -> makectrls o x (change,ticks,1,offset) y) [1..] mididiffs
-- send out MIDI events
(late, later) <- sendevents o shape change ticks events resetevents
-- finally clear buffered ParamMap for next tick
putMVar buf (replicate 16 Map.empty, later)
let len = length late
case len of
0 ->
return ()
_ -> do
putStrLn $ showLate $ head late
putStrLn $ "and " ++ show (len - 1) ++ " more")
-- Scheduling
{- |
Sends out MIDI events due for this tick.
-}
sendevents :: Output -- ^ The connection to be used
-> S.Shape -- ^ The shape to be queried for latency
-> Tempo -- ^ The current speed
-> Tick -- ^ The number of ticks elapsed since start, may be reset when using @cps (-1)@
-> [MIDIEvent] -- ^ A list of events potentially needed to be sent
-> [MIDIEvent] -- ^ A list of reset events potentially needed to be sent
-> IO ([SentEvent], [MIDIEvent]) -- ^ A list of events sent late and a list of events to send later
sendevents _ _ _ _ [] [] = return ([],[])
sendevents s shape change ticks evts resets = do
-- assumptions:
-- all reset events have the same timestamp
-- questions:
-- could there be any events in `evts` at all that need reset? or are these just in late from the last tick?
let output = conn s
toDescriptor midiTime now (o,_,t,e) = (o,t,e, midiTime, now)
calcOnsets (a@(tempo, tick, onset, offset), e) = (a, logicalOnset' tempo tick onset offset, e)
midiTime <- PM.time
now <- getCurrentTime
let offset = S.latency shape
nextTick = logicalOnset' change (ticks+1) 0 offset
mkEvent (t, o, e) = (midionset, t, o, makeRawEvent e midionset)
where midionset = scheduleTime (midistart s, rstart s) o
onsets = map calcOnsets evts
-- calculate temporary scheduling for resetevts
resetevts = map calcOnsets resets
-- split into events sent now and later (e.g. a noteOff that would otherwise cut off noteOn's in the next tick)
(evts', later) = span ((< nextTick).(\(_,o,_) -> o)) $ sortBy (comparing (\(_,o,_) -> o)) onsets
-- calculate MIDI time to schedule events, putting time into fn to create PM.PMEvents
evts'' = map mkEvent evts'
-- a list CC `names` that need to be reset
resetccs = map (\(_, _, (_, _, d1, _)) -> d1) resetevts
later' = map (\(t,_,e) -> (t,e)) later
findCC match list = find (\(_, _, (_, st, d1, _)) -> st == 0xB0 && (d1 `elem` match)) $ reverse list
-- 1. find the ccs that needs reset (search in `later` then in `evts`)
(evtstosend, laterevts) = case findCC resetccs later of
Nothing -> case findCC resetccs evts' of
-- 1c. no events at all need to be reset
-- 1cI. use the default passed in midionset for resets
-- 1cII. append `resets` to `evts` FIXME: make sure we really do by timing
-- 1cIII. send `evts`
Nothing -> (evts'' ++ map mkEvent resetevts, later')
-- 1b. only `evts` contain a CC to be reset
-- 1bI. set scheduletime for reset __after__ the latest CC that needs to be reset in `evts`
-- 1bII. add `resets` to `evts`
-- 1bIII. send `evts`
Just (_, latestO, _) -> (before ++
map (
\(t, o, e) ->
let midionset = scheduleTime (midistart s, rstart s) latestO
in (midionset, t,o,makeRawEvent e midionset)
) resetevts ++ after, later')
where
(before, after) = partition (\(m,_,o,_) -> m > scheduleTime (midistart s, rstart s) o) evts''
-- 1a. `later` contains a cc to be reset, (omit searching in evts)
-- 1aI. set scheduletime for reset __after__ the latest CC that needs to be reset in `later`
-- 1aII. add `resetevts` to `later`
-- 1aIII. send `evts`
Just (latestT, _, _) -> (evts'', later' ++ map (\(_, _, e) -> (latestT, e)) resetevts)
evtstosend' = map (\(_,_,_,e) -> e) evtstosend
-- filter events that are too late
late = map (toDescriptor midiTime now) $ filter (\(_,_,t,_) -> t < realToFrac (utcTimeToPOSIXSeconds now)) evtstosend
-- drop late CC events to avoid glitches
-- evtstosend'' = map (\(_,_,e,_,_) -> e) $ filter (not.isCC) late
-- write events for this tick to stream
err <- PM.writeEvents output evtstosend'
case err of
PM.NoError -> return (late, laterevts) -- return events for logging in outer scope
e -> do
putStrLn ("sending failed: " ++ show e)
return (late, laterevts)
isCC :: SentEvent -> Bool
isCC (_,_,e,_,_) = (0x0f .&. cc) == 0xB0
where
cc = PM.status $ PM.decodeMsg $ PM.message $ e
-- | Buffer a single tick's MIDI events for a single channel of a single connection
store :: Output -> Int -> Tempo -> Tick -> Onset -> Offset -> MidiMap -> ParamMap -> IO ()
store s ch change tick on off ctrls note = storemidi s ch' note' (change, tick, on, offset) ctrls
where
(note', nudge) = computeTiming' change on off note
ch' = fromIntegral ch
cshape' = cshape s
offset = Sound.Tidal.MIDI.Control.latency cshape' + nudge
{- |
Returns a function to be called on every tick,
splits the given @ParamMap@ into MIDI note information
and CCs.
-}
mkStore :: Int -> Output -> IO ToMessageFunc
mkStore channel s = return $ \ shape change tick (on,off,m) -> do
let ctrls = cutShape shape m
props = cutShape midiShape m
ctrls' = stripDefaults ctrls
ctrls'' = toMidiMap (cshape s) <$> ctrls'
store' = store s channel change tick on off <$> ctrls''
-- store even non-midi params, otherwise removing last ctrl results in a missing reset since diff in `flushBackend` would be empty
-- then buffer ctrl messages to be sent
-- with the appropriate note properties
($) <$> (storeParams s channel <$> stripDefaults (applyShape' shape m)) <*> (($) <$> store' <*> props)
-- | Union the currently stored paramstate for certain channel with the given one
storeParams :: Output -> Int -> ParamMap -> IO () -> IO ()
storeParams o ch m action = do
modifyMVar_ (buffer o) $ \(states, events) -> do
let (before,current:after) = splitAt (ch - 1) states
state' = Map.union m current
states' = before ++ [state'] ++ after
return (states', events)
action
-- | Thin wrapper around @computeTiming@ to convert onset/offset into onset/duration relative
computeTiming' :: Tempo -> Double -> Double -> ParamMap -> (TimedNote, Double)
computeTiming' tempo on off note = ((fromIntegral n, fromIntegral v, d), nudge)
where
((n,v,d), nudge) = computeTiming tempo (realToFrac (off - on) / S.ticksPerCycle) note
{- | Schedule sending all CC's default values.
Produces an `onTick` handler.
-}
connected :: Int -> String -> Output -> IO ToMessageFunc
connected channel displayname s = do
let cshape' = cshape s
shape = toShape $ cshape s
defaultParams = S.defaultMap shape
allctrls = toMidiMap cshape' defaultParams
putStrLn ("Successfully initialized Device '" ++ displayname ++ "'")
changeState goOnline s
now <- getCurrentTime
_ <- storeevents s $ makectrls s (fromIntegral channel) (Tempo now 0 1 False 0,0,0,0) allctrls
mkStore channel s
-- State handling
readState :: (OutputState -> b) -> Output -> IO b
readState f o = do
s <- readMVar $ bufferstate o
return $ f s
isCycling :: OutputState -> Bool
isCycling (0, _, _, True) = True
isCycling _ = False
-- displayState :: OutputState -> String
-- displayState (ticked, conns, paramstate, online) = show ticked ++ "/" ++ show conns ++ "[" ++ show online ++ "]" ++ " active params: " ++ show paramstate
changeState :: (OutputState -> OutputState) -> Output -> IO ()
changeState f o = do
_ <- changeState' f o
return ()
changeState' :: (OutputState -> OutputState) -> Output -> IO (OutputState, OutputState)
changeState' f o = do
bs <- takeMVar stateM
let fs = f bs
putMVar stateM fs
return (fs, bs)
where
stateM = bufferstate o
-- | Params in use get overwritten by new ones, except if new ones means _no params_, in this case keep old
resetParamStates :: [ParamMap] -> OutputState -> OutputState
resetParamStates newstates (ticked, conns, paramstates, online) = (ticked, conns, zipWith resetParamState newstates paramstates, online)
resetParamState :: ParamMap -> ParamMap -> ParamMap
resetParamState newstate currentstate
| Map.empty == newstate = currentstate -- updating with an empty state is a noop
| otherwise = newstate
goOnline :: OutputState -> OutputState
goOnline (ticked, conns, paramstate, _) = (ticked, conns, paramstate, True)
addConnection :: OutputState -> OutputState
addConnection (ticked, conns, paramstate, online) = (ticked, conns + 1, paramstate, online)
tickConnections :: OutputState -> OutputState
tickConnections (ticked, conns, paramstate, online) = ((ticked + 1) `mod` conns, conns, paramstate, online)
-- | open named MIDI output or use cached (PortMIDI doesn't like opening two connections to the same device!)
useOutput :: MVar MidiDeviceMap -> String -> ControllerShape -> IO (Maybe Output)
useOutput outsM displayname controllershape = do
outs <- readMVar outsM -- blocks
let outM = Map.lookup displayname outs -- maybe
-- if we have a valid output by now, return
case outM of
Just o -> do
putStrLn "Cached Device Output"
changeState addConnection o -- blocks
return $ Just o
Nothing -> do
-- otherwise open a new output and store the result in the mvar
devidM <- (>>= maybe (failed displayname "Failed opening MIDI Output Device ID") return) (getIDForDeviceName displayname)
econn <- outputDevice devidM 1 controllershape -- either
case econn of
Left o -> do
changeState addConnection o
_ <- swapMVar outsM $ Map.insert displayname o outs
return $ Just o
Right _ -> return Nothing
-- | Turn logicalOnset into MIDITime
scheduleTime :: (CULong, UTCTime)-> Double -> CULong
scheduleTime (mstart', rstart') logicalOnset = (+) mstart $ floor $ 1000 * (logicalOnset - rstart'')
where
rstart'' = realToFrac $ utcTimeToPOSIXSeconds rstart'
mstart = fromIntegral mstart'
-- Converters
{-|
Convert a @Param@'s @Value@ into a MIDI consumable datum.
Applies range mapping and scaling functions according to @ControllerShape@
-}
toMidiValue :: ControllerShape -> S.Param -> Value -> Maybe Int
toMidiValue s p (VF x) = ($) <$> mscale <*> mrange <*> pure x
where
mrange = fmap range mcc
mscale = fmap scalef mcc
mcc = paramN s p
toMidiValue _ _ (VI x) = Just x
toMidiValue _ _ (VS _) = Nothing -- ignore strings for now, we might 'read' them later
-- | Translates generic params into midi params
toMidiMap :: ControllerShape -> S.ParamMap -> MidiMap
toMidiMap s m = Map.mapWithKey (toMidiValue s) m
-- | Keep only params that are in a given shape, replace missing with defaults
cutShape :: S.Shape -> ParamMap -> Maybe ParamMap
cutShape s m = flip Map.intersection (S.defaultMap s) <$> S.applyShape' s m
-- | Keep only params that are in a given shape
stripShape :: S.Shape -> ParamMap -> ParamMap
stripShape s = Map.intersection p'
where
p' = S.defaultMap s
-- | Keep only params that are explicitly set (i.e. not default)
stripDefaults :: Maybe ParamMap -> Maybe ParamMap
stripDefaults m = Map.filterWithKey (\k v -> v /= defaultValue k) <$> m
-- Event creation
-- FIXME: throws if param cannot be found
makectrls :: Output -> MIDIChannel -> MIDITime -> MidiMap -> [MIDIEvent]
makectrls o ch t ctrls = concatMap (\(param', ctrl) -> makeCtrl ch (fromJust $ paramN shape param') (fromIntegral ctrl) t) ctrls'
where
shape = cshape o
ctrls' = filter ((>=0) . snd) $ Map.toList $ Map.mapMaybe id ctrls
makenote :: MIDIChannel -> TimedNote -> MIDITime -> [MIDIEvent]
makenote ch (note,vel,dur) (tempo,tick,onset,offset) = noteon' ++ noteoff'
where
noteon' = noteOn ch midinote vel (tempo,tick,onset,offset)
noteoff' = noteOff ch midinote (tempo,tick,onset,offset + fromRational dur)
midinote = note + 60
makemidi :: Output -> MIDIChannel -> TimedNote -> MIDITime -> MidiMap -> [MIDIEvent]
makemidi o ch (128,_,_) t ctrls = makectrls o ch t ctrls -- HACK: to send only CC use (n + 60) == 128
makemidi o ch note t ctrls = makectrls o ch t ctrls ++ makenote ch note t
-- Event buffering
storemidi :: Output -> MIDIChannel -> TimedNote -> MIDITime -> MidiMap -> IO ()
storemidi o ch n t ctrls = do
_ <- storeevents o $ makemidi o ch n t ctrls
return ()
makeEvent :: MIDIStatus -> MIDINote -> MIDIChannel -> MIDIVelocity -> MIDITime -> MIDIEvent
makeEvent st n ch v t = (t, msg)
where
msg = (ch, st, n, v)
storeevents :: Output -> [MIDIEvent] -> IO (Maybe a)
storeevents o evts = do
let buf = buffer o
(paramstate, cbuf) <- takeMVar buf
putMVar buf (paramstate, cbuf ++ evts)
return Nothing
-- Misc helpers
showLate :: SentEvent -> String
showLate (o, t, e, m, n) =
unwords ["late",
show $ (\x -> [PM.status x, PM.data1 x, PM.data2 x]) $ PM.decodeMsg $ PM.message e,
"midi now ", show m, " midi onset: ", show o,
"onset (relative): ", show $ showFFloat (Just 3) (t - realToFrac (utcTimeToPOSIXSeconds n)) "",
", sched: ", show $ PM.timestamp e]
showEvent :: PM.PMEvent -> String
showEvent e = show t ++ " " ++ show msg
where msg = PM.decodeMsg $ PM.message e
t = PM.timestamp e
showRawEvent :: (CULong, MIDITime, Double, PM.PMEvent) -> String
showRawEvent (_, (_,_,onset,offset), logicalOnset, e) = "(" ++ show onset ++ "," ++ show offset ++ ") / " ++ show logicalOnset ++ " " ++ showEvent e
failed :: (Show a, Show b) => a -> b -> c
failed di err = error (show err ++ ": " ++ show di)
---------------
-- LOW LEVEL --
---------------
-- MIDI Event wrapping
makeRawEvent :: MIDIMessage -> CULong -> PM.PMEvent
makeRawEvent (ch, st, n, v) = PM.PMEvent msg
where msg = PM.encodeMsg $ PM.PMMsg (encodeChannel ch st) n v
-- MIDI Utils
encodeChannel :: MIDIChannel -> MIDIStatus -> CLong
encodeChannel ch cc = (-) ch 1 .|. cc
-- MIDI Messages
noteOn :: MIDIChannel -> MIDINote -> MIDIVelocity -> MIDITime -> [MIDIEvent]
noteOn ch val vel t = [makeEvent 0x90 val ch vel t]
noteOff :: MIDIChannel -> MIDINote -> MIDITime -> [MIDIEvent]
noteOff ch val t = [makeEvent 0x80 val ch 60 t]
makeCtrl :: MIDIChannel -> ControlChange -> MIDIDatum -> MIDITime -> [MIDIEvent]
makeCtrl ch CC {midi=midi'} n t = makeCC ch (fromIntegral midi') n t -- FIXME: no SysEx support right now
makeCtrl ch NRPN {midi=midi'} n t = makeNRPN ch (fromIntegral midi') n t
makeCC :: MIDIChannel -> MIDIDatum -> MIDIDatum -> MIDITime -> [MIDIEvent]
makeCC ch c n t = [makeEvent 0xB0 c ch n t]
makeNRPN :: MIDIChannel -> MIDIDatum -> MIDIDatum -> MIDITime -> [MIDIEvent]
makeNRPN ch c n t = [
nrpn 0x63 ch (shift (c .&. 0x3F80) (-7)) t,
nrpn 0x62 ch (c .&. 0x7F) t,
nrpn 0x06 ch (shift (n .&. 0x3F80) (-7)) t,
nrpn 0x26 ch (n .&. 0x7F) t
]
where
nrpn = makeEvent 0xB0
-- | Creates an 'Output' wrapping a PortMidi device
outputDevice :: PM.DeviceID -> Int -> ControllerShape -> IO (Either Output PM.PMError)
outputDevice deviceID latency' shape = do
_ <- PM.initialize
result <- PM.openOutput deviceID latency'
bs <- newMVar (0, 0, replicate 16 Map.empty, False)
case result of
Left dev ->
do
info <- PM.getDeviceInfo deviceID
time <- getCurrentTime
mstart <- PM.time
putStrLn ("Opened: " ++ show (PM.interface info) ++ ": " ++ show (PM.name info))
b <- newMVar (replicate 16 Map.empty, [])
return (Left Output { cshape=shape, conn=dev, buffer=b, bufferstate=bs, midistart=mstart, rstart=time })
Right err -> return (Right err)
| tidalcycles/tidal-midi | Sound/Tidal/MIDI/Output.hs | gpl-3.0 | 21,918 | 362 | 22 | 5,365 | 5,280 | 2,996 | 2,284 | 338 | 4 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, UndecidableInstances, IncoherentInstances #-}
module StackManip(ToStack(..), TwoStack(..), (<|>)) where
import Control.Monad.Except
import Data.Char
import Environment
import Object
data TwoStack a b = TwoStack a b
class ToObject a where
toObject :: a -> FObject
class ToStack a where
toStack :: a -> InterpAct ()
class FromObject a where
fromObject :: FObject -> Maybe a
class FromStack a where
fromStack :: InterpAct (Maybe a)
infixr 9 <|>
(<|>) :: (FromStack a, ToStack b) => (a -> b) -> InterpAct () -> InterpAct ()
f <|> other = do
first <- fromStack
case first of
Just v -> toStack $ f v
Nothing -> other
instance (ToObject a) => ToStack a where
toStack = push . toObject
instance (ToStack a, ToStack b) => ToStack (TwoStack a b) where
toStack (TwoStack x y) = toStack x >> toStack y
instance ToStack () where
toStack = return
instance (ToStack a) => ToStack (IO a) where
toStack v = liftIO v >>= toStack
instance ToObject Integer where
toObject = Number
instance ToObject FObject where
toObject = id
instance ToObject String where
toObject = Str
instance (ToObject a, ToObject b) => ToObject (a, b) where
toObject (a, b) = Pair (toObject a) (toObject b)
instance (ToObject a) => ToObject [a] where
toObject = foldr (Pair . toObject) Nil
instance {-# OVERLAPPABLE #-} (FromObject a) => FromStack a where
fromStack = do
x <- pop
case fromObject x of
Just y -> return (Just y)
Nothing -> push x >> return Nothing
instance (FromObject FObject) where
fromObject = Just
instance (FromObject Integer) where
fromObject (Number x') = Just x'
fromObject _ = Nothing
instance (FromObject Int) where
fromObject = fmap fromInteger . fromObject
instance (FromObject String) where
fromObject (Str x') = Just x'
fromObject _ = Nothing
instance (FromObject a) => FromObject [a] where
fromObject Nil = return []
fromObject (Pair a b) = mapM fromObject $ dedotify a b
fromObject (Str s) = mapM (fromObject . cTn) s
where
cTn = Number . toInteger . ord
fromObject _ = Nothing
instance (FromStack a, FromStack b) => (FromStack (TwoStack a b)) where
fromStack = do
x <- fromStack
y <- fromStack
return $ liftM2 TwoStack x y
instance (FromObject a, FromObject b) => (FromObject (a, b)) where
fromObject (Pair b a) = liftM2 (,) (fromObject a) (fromObject b)
fromObject _ = Nothing
dedotify :: FObject -> FObject -> [FObject]
dedotify car Nil = [car]
dedotify car (Pair cadr cddr) = car : dedotify cadr cddr
dedotify car cdr = [car, cdr]
| kavigupta/N-programming-language | src/StackManip.hs | gpl-3.0 | 2,712 | 32 | 15 | 655 | 922 | 487 | 435 | 74 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Html.Cloudfront where
import Prelude
import Types
import Control.Monad
import Html.Url
import Text.Blaze.Html5
import qualified Data.Map.Strict as M
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes
import qualified Text.Blaze.Html5.Attributes as A
cloudfrontHtml :: CFDistros -> Html
cloudfrontHtml cfds = H.form ! method "POST" ! action (toValue UrlBucketLinkCF) $ do
legend "Linked Cloudfront Distros:"
forM_ (M.toList cfds) $ \(bucket, distro) -> do
let bucketValue = toValue bucket
H.div ! class_ "form-group" $ do
H.label ! for bucketValue $ toHtml bucket
input ! type_ "text" ! class_ "form-control" ! A.id bucketValue
! name bucketValue ! value (toValue distro)
button ! type_ "submit" ! class_ "btn btn-default" $ "Submit"
| schell/pusher | src/Html/Cloudfront.hs | gpl-3.0 | 872 | 0 | 20 | 183 | 256 | 133 | 123 | 21 | 1 |
module Database.Abstract.Types where
data QuoteStyle = PgSQLStyle | MySQLStyle | SQLiteStyle
type TableName = String
type ColumnName = String
data SQL =
NULL | TRUE | FALSE
| Literal String
| Everything
| Column ColumnName
| Table TableName
| QualifiedColumn TableName ColumnName
| QualifiedEverything TableName
| Function String [SQL]
| Select (NEL SQL) (NEL SQL) Criterion
deriving (Eq)
data Criterion =
NoWHERE
| RawSQL String
| Compare Comparator SQL SQL
| Not Criterion
| IsNull SQL
| In SQL (NEL SQL)
| And (NEL Criterion)
| Or (NEL Criterion)
deriving (Eq)
data Comparator =
Equal | Less | Greater | LessEqual | GreaterEqual | Like
deriving (Eq)
-- Type for non-empty lists.
data NEL a = NEL (a, [a]) deriving (Eq)
-- | Get the content of a 'NEL' as list.
fromNEL :: NEL a -> [a]
fromNEL (NEL (x, xs)) = x : xs
-- | Create a non-empty list with one single element.
singleNEL :: a -> NEL a
singleNEL a = NEL (a, [])
-- | Create a non-empty list from a list. Will crash if the list is empty.
toNEL :: [a] -> NEL a
toNEL s = NEL (head s, tail s)
| jkramer/database-abstract | Database/Abstract/Types.hs | gpl-3.0 | 1,309 | 0 | 8 | 456 | 353 | 203 | 150 | 35 | 1 |
import Control.Monad (replicateM)
import Data.Maybe (fromMaybe)
import Options.Applicative ((<>))
import KeygenOptions as Opts
import RSCoin.Core (derivePublicKey, keyGen, readPublicKey,
readSecretKey, sign, writePublicKey,
writeSecretKey, writeSignature)
main :: IO ()
main = do
command <- Opts.getOptions
case command of
Opts.Single keyName -> do
let fpSecret = keyName
fpPublic = keyName <> ".pub"
(sk,pk) <- keyGen
writeSecretKey fpSecret sk
writePublicKey fpPublic pk
Opts.Batch genNum genPath skPath -> do
masterSK <- readSecretKey skPath
keys <- replicateM genNum (generator masterSK)
let generatedKeys = unlines $ map show keys
writeFile genPath generatedKeys
Opts.Derive skPath output -> do
secretKey <- readSecretKey skPath
let publicKey = derivePublicKey secretKey
flip writePublicKey publicKey $
fromMaybe (skPath <> ".pub") output
Opts.Sign skPath pkPath output -> do
secretKey <- readSecretKey skPath
publicKey <- readPublicKey pkPath
let signature = sign secretKey publicKey
flip writeSignature signature $
fromMaybe (pkPath <> ".sig") output
where
generator masterSK = do
(sk, pk) <- keyGen
let sig = sign masterSK pk
masterPK = derivePublicKey masterSK
return (masterPK, (pk, sk), sig)
| input-output-hk/rscoin-haskell | src/Keygen/Main.hs | gpl-3.0 | 1,675 | 0 | 16 | 633 | 425 | 208 | 217 | 38 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Sheets.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Sheets.Types.Sum where
import Network.Google.Prelude
-- | What kind of data to paste.
data CopyPasteRequestPasteType
= PasteNormal
-- ^ @PASTE_NORMAL@
-- Paste values, formulas, formats, and merges.
| PasteValues
-- ^ @PASTE_VALUES@
-- Paste the values ONLY without formats, formulas, or merges.
| PasteFormat
-- ^ @PASTE_FORMAT@
-- Paste the format and data validation only.
| PasteNoBOrders
-- ^ @PASTE_NO_BORDERS@
-- Like PASTE_NORMAL but without borders.
| PasteFormula
-- ^ @PASTE_FORMULA@
-- Paste the formulas only.
| PasteDataValidation
-- ^ @PASTE_DATA_VALIDATION@
-- Paste the data validation only.
| PasteConditionalFormatting
-- ^ @PASTE_CONDITIONAL_FORMATTING@
-- Paste the conditional formatting rules only.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CopyPasteRequestPasteType
instance FromHttpApiData CopyPasteRequestPasteType where
parseQueryParam = \case
"PASTE_NORMAL" -> Right PasteNormal
"PASTE_VALUES" -> Right PasteValues
"PASTE_FORMAT" -> Right PasteFormat
"PASTE_NO_BORDERS" -> Right PasteNoBOrders
"PASTE_FORMULA" -> Right PasteFormula
"PASTE_DATA_VALIDATION" -> Right PasteDataValidation
"PASTE_CONDITIONAL_FORMATTING" -> Right PasteConditionalFormatting
x -> Left ("Unable to parse CopyPasteRequestPasteType from: " <> x)
instance ToHttpApiData CopyPasteRequestPasteType where
toQueryParam = \case
PasteNormal -> "PASTE_NORMAL"
PasteValues -> "PASTE_VALUES"
PasteFormat -> "PASTE_FORMAT"
PasteNoBOrders -> "PASTE_NO_BORDERS"
PasteFormula -> "PASTE_FORMULA"
PasteDataValidation -> "PASTE_DATA_VALIDATION"
PasteConditionalFormatting -> "PASTE_CONDITIONAL_FORMATTING"
instance FromJSON CopyPasteRequestPasteType where
parseJSON = parseJSONText "CopyPasteRequestPasteType"
instance ToJSON CopyPasteRequestPasteType where
toJSON = toJSONText
-- | The position of this axis.
data BasicChartAxisPosition
= BasicChartAxisPositionUnspecified
-- ^ @BASIC_CHART_AXIS_POSITION_UNSPECIFIED@
-- Default value, do not use.
| BottomAxis
-- ^ @BOTTOM_AXIS@
-- The axis rendered at the bottom of a chart. For most charts, this is the
-- standard major axis. For bar charts, this is a minor axis.
| LeftAxis
-- ^ @LEFT_AXIS@
-- The axis rendered at the left of a chart. For most charts, this is a
-- minor axis. For bar charts, this is the standard major axis.
| RightAxis
-- ^ @RIGHT_AXIS@
-- The axis rendered at the right of a chart. For most charts, this is a
-- minor axis. For bar charts, this is an unusual major axis.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartAxisPosition
instance FromHttpApiData BasicChartAxisPosition where
parseQueryParam = \case
"BASIC_CHART_AXIS_POSITION_UNSPECIFIED" -> Right BasicChartAxisPositionUnspecified
"BOTTOM_AXIS" -> Right BottomAxis
"LEFT_AXIS" -> Right LeftAxis
"RIGHT_AXIS" -> Right RightAxis
x -> Left ("Unable to parse BasicChartAxisPosition from: " <> x)
instance ToHttpApiData BasicChartAxisPosition where
toQueryParam = \case
BasicChartAxisPositionUnspecified -> "BASIC_CHART_AXIS_POSITION_UNSPECIFIED"
BottomAxis -> "BOTTOM_AXIS"
LeftAxis -> "LEFT_AXIS"
RightAxis -> "RIGHT_AXIS"
instance FromJSON BasicChartAxisPosition where
parseJSON = parseJSONText "BasicChartAxisPosition"
instance ToJSON BasicChartAxisPosition where
toJSON = toJSONText
-- | The dimension from which deleted cells will be replaced with. If ROWS,
-- existing cells will be shifted upward to replace the deleted cells. If
-- COLUMNS, existing cells will be shifted left to replace the deleted
-- cells.
data DeleteRangeRequestShiftDimension
= DimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| Rows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| Columns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DeleteRangeRequestShiftDimension
instance FromHttpApiData DeleteRangeRequestShiftDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right DimensionUnspecified
"ROWS" -> Right Rows
"COLUMNS" -> Right Columns
x -> Left ("Unable to parse DeleteRangeRequestShiftDimension from: " <> x)
instance ToHttpApiData DeleteRangeRequestShiftDimension where
toQueryParam = \case
DimensionUnspecified -> "DIMENSION_UNSPECIFIED"
Rows -> "ROWS"
Columns -> "COLUMNS"
instance FromJSON DeleteRangeRequestShiftDimension where
parseJSON = parseJSONText "DeleteRangeRequestShiftDimension"
instance ToJSON DeleteRangeRequestShiftDimension where
toJSON = toJSONText
-- | The minor axis that will specify the range of values for this series.
-- For example, if charting stocks over time, the \"Volume\" series may
-- want to be pinned to the right with the prices pinned to the left,
-- because the scale of trading volume is different than the scale of
-- prices. It is an error to specify an axis that isn\'t a valid minor axis
-- for the chart\'s type.
data BasicChartSeriesTargetAxis
= BCSTABasicChartAxisPositionUnspecified
-- ^ @BASIC_CHART_AXIS_POSITION_UNSPECIFIED@
-- Default value, do not use.
| BCSTABottomAxis
-- ^ @BOTTOM_AXIS@
-- The axis rendered at the bottom of a chart. For most charts, this is the
-- standard major axis. For bar charts, this is a minor axis.
| BCSTALeftAxis
-- ^ @LEFT_AXIS@
-- The axis rendered at the left of a chart. For most charts, this is a
-- minor axis. For bar charts, this is the standard major axis.
| BCSTARightAxis
-- ^ @RIGHT_AXIS@
-- The axis rendered at the right of a chart. For most charts, this is a
-- minor axis. For bar charts, this is an unusual major axis.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSeriesTargetAxis
instance FromHttpApiData BasicChartSeriesTargetAxis where
parseQueryParam = \case
"BASIC_CHART_AXIS_POSITION_UNSPECIFIED" -> Right BCSTABasicChartAxisPositionUnspecified
"BOTTOM_AXIS" -> Right BCSTABottomAxis
"LEFT_AXIS" -> Right BCSTALeftAxis
"RIGHT_AXIS" -> Right BCSTARightAxis
x -> Left ("Unable to parse BasicChartSeriesTargetAxis from: " <> x)
instance ToHttpApiData BasicChartSeriesTargetAxis where
toQueryParam = \case
BCSTABasicChartAxisPositionUnspecified -> "BASIC_CHART_AXIS_POSITION_UNSPECIFIED"
BCSTABottomAxis -> "BOTTOM_AXIS"
BCSTALeftAxis -> "LEFT_AXIS"
BCSTARightAxis -> "RIGHT_AXIS"
instance FromJSON BasicChartSeriesTargetAxis where
parseJSON = parseJSONText "BasicChartSeriesTargetAxis"
instance ToJSON BasicChartSeriesTargetAxis where
toJSON = toJSONText
-- | Determines how dates, times, and durations in the response should be
-- rendered. This is ignored if response_value_render_option is
-- FORMATTED_VALUE. The default dateTime render option is
-- [DateTimeRenderOption.SERIAL_NUMBER].
data BatchUpdateValuesRequestResponseDateTimeRenderOption
= SerialNumber
-- ^ @SERIAL_NUMBER@
-- Instructs date, time, datetime, and duration fields to be output as
-- doubles in \"serial number\" format, as popularized by Lotus 1-2-3. Days
-- are counted from December 31st 1899 and are incremented by 1, and times
-- are fractions of a day. For example, January 1st 1900 at noon would be
-- 1.5, 1 because it\'s 1 day offset from December 31st 1899, and .5
-- because noon is half a day. February 1st 1900 at 3pm would be 32.625.
-- This correctly treats the year 1900 as not a leap year.
| FormattedString
-- ^ @FORMATTED_STRING@
-- Instructs date, time, datetime, and duration fields to be output as
-- strings in their given number format (which is dependent on the
-- spreadsheet locale).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesRequestResponseDateTimeRenderOption
instance FromHttpApiData BatchUpdateValuesRequestResponseDateTimeRenderOption where
parseQueryParam = \case
"SERIAL_NUMBER" -> Right SerialNumber
"FORMATTED_STRING" -> Right FormattedString
x -> Left ("Unable to parse BatchUpdateValuesRequestResponseDateTimeRenderOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesRequestResponseDateTimeRenderOption where
toQueryParam = \case
SerialNumber -> "SERIAL_NUMBER"
FormattedString -> "FORMATTED_STRING"
instance FromJSON BatchUpdateValuesRequestResponseDateTimeRenderOption where
parseJSON = parseJSONText "BatchUpdateValuesRequestResponseDateTimeRenderOption"
instance ToJSON BatchUpdateValuesRequestResponseDateTimeRenderOption where
toJSON = toJSONText
-- | Whether rows or columns should be appended.
data AppendDimensionRequestDimension
= ADRDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| ADRDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| ADRDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AppendDimensionRequestDimension
instance FromHttpApiData AppendDimensionRequestDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right ADRDDimensionUnspecified
"ROWS" -> Right ADRDRows
"COLUMNS" -> Right ADRDColumns
x -> Left ("Unable to parse AppendDimensionRequestDimension from: " <> x)
instance ToHttpApiData AppendDimensionRequestDimension where
toQueryParam = \case
ADRDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
ADRDRows -> "ROWS"
ADRDColumns -> "COLUMNS"
instance FromJSON AppendDimensionRequestDimension where
parseJSON = parseJSONText "AppendDimensionRequestDimension"
instance ToJSON AppendDimensionRequestDimension where
toJSON = toJSONText
-- | The dimension of the span.
data DimensionRangeDimension
= DRDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| DRDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| DRDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DimensionRangeDimension
instance FromHttpApiData DimensionRangeDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right DRDDimensionUnspecified
"ROWS" -> Right DRDRows
"COLUMNS" -> Right DRDColumns
x -> Left ("Unable to parse DimensionRangeDimension from: " <> x)
instance ToHttpApiData DimensionRangeDimension where
toQueryParam = \case
DRDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
DRDRows -> "ROWS"
DRDColumns -> "COLUMNS"
instance FromJSON DimensionRangeDimension where
parseJSON = parseJSONText "DimensionRangeDimension"
instance ToJSON DimensionRangeDimension where
toJSON = toJSONText
-- | The dimension that data should be filled into.
data SourceAndDestinationDimension
= SADDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| SADDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| SADDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SourceAndDestinationDimension
instance FromHttpApiData SourceAndDestinationDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right SADDDimensionUnspecified
"ROWS" -> Right SADDRows
"COLUMNS" -> Right SADDColumns
x -> Left ("Unable to parse SourceAndDestinationDimension from: " <> x)
instance ToHttpApiData SourceAndDestinationDimension where
toQueryParam = \case
SADDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
SADDRows -> "ROWS"
SADDColumns -> "COLUMNS"
instance FromJSON SourceAndDestinationDimension where
parseJSON = parseJSONText "SourceAndDestinationDimension"
instance ToJSON SourceAndDestinationDimension where
toJSON = toJSONText
-- | The wrap strategy for the value in the cell.
data CellFormatWrapStrategy
= WrapStrategyUnspecified
-- ^ @WRAP_STRATEGY_UNSPECIFIED@
-- The default value, do not use.
| OverflowCell
-- ^ @OVERFLOW_CELL@
-- Lines that are longer than the cell width will be written in the next
-- cell over, so long as that cell is empty. If the next cell over is
-- non-empty, this behaves the same as CLIP. The text will never wrap to
-- the next line unless the user manually inserts a new line. Example: |
-- First sentence. | | Manual newline that is very long. \<- Text continues
-- into next cell | Next newline. |
| LegacyWrap
-- ^ @LEGACY_WRAP@
-- This wrap strategy represents the old Google Sheets wrap strategy where
-- words that are longer than a line are clipped rather than broken. This
-- strategy is not supported on all platforms and is being phased out.
-- Example: | Cell has a | | loooooooooo| \<- Word is clipped. | word. |
| Clip
-- ^ @CLIP@
-- Lines that are longer than the cell width will be clipped. The text will
-- never wrap to the next line unless the user manually inserts a new line.
-- Example: | First sentence. | | Manual newline t| \<- Text is clipped |
-- Next newline. |
| Wrap
-- ^ @WRAP@
-- Words that are longer than a line are wrapped at the character level
-- rather than clipped. Example: | Cell has a | | loooooooooo| \<- Word is
-- broken. | ong word. |
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatWrapStrategy
instance FromHttpApiData CellFormatWrapStrategy where
parseQueryParam = \case
"WRAP_STRATEGY_UNSPECIFIED" -> Right WrapStrategyUnspecified
"OVERFLOW_CELL" -> Right OverflowCell
"LEGACY_WRAP" -> Right LegacyWrap
"CLIP" -> Right Clip
"WRAP" -> Right Wrap
x -> Left ("Unable to parse CellFormatWrapStrategy from: " <> x)
instance ToHttpApiData CellFormatWrapStrategy where
toQueryParam = \case
WrapStrategyUnspecified -> "WRAP_STRATEGY_UNSPECIFIED"
OverflowCell -> "OVERFLOW_CELL"
LegacyWrap -> "LEGACY_WRAP"
Clip -> "CLIP"
Wrap -> "WRAP"
instance FromJSON CellFormatWrapStrategy where
parseJSON = parseJSONText "CellFormatWrapStrategy"
instance ToJSON CellFormatWrapStrategy where
toJSON = toJSONText
-- | How the input data should be interpreted.
data BatchUpdateValuesRequestValueInputOption
= InputValueOptionUnspecified
-- ^ @INPUT_VALUE_OPTION_UNSPECIFIED@
-- Default input value. This value must not be used.
| Raw
-- ^ @RAW@
-- The values the user has entered will not be parsed and will be stored
-- as-is.
| UserEntered
-- ^ @USER_ENTERED@
-- The values will be parsed as if the user typed them into the UI. Numbers
-- will stay as numbers, but strings may be converted to numbers, dates,
-- etc. following the same rules that are applied when entering text into a
-- cell via the Google Sheets UI.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesRequestValueInputOption
instance FromHttpApiData BatchUpdateValuesRequestValueInputOption where
parseQueryParam = \case
"INPUT_VALUE_OPTION_UNSPECIFIED" -> Right InputValueOptionUnspecified
"RAW" -> Right Raw
"USER_ENTERED" -> Right UserEntered
x -> Left ("Unable to parse BatchUpdateValuesRequestValueInputOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesRequestValueInputOption where
toQueryParam = \case
InputValueOptionUnspecified -> "INPUT_VALUE_OPTION_UNSPECIFIED"
Raw -> "RAW"
UserEntered -> "USER_ENTERED"
instance FromJSON BatchUpdateValuesRequestValueInputOption where
parseJSON = parseJSONText "BatchUpdateValuesRequestValueInputOption"
instance ToJSON BatchUpdateValuesRequestValueInputOption where
toJSON = toJSONText
-- | Determines how values in the response should be rendered. The default
-- render option is ValueRenderOption.FORMATTED_VALUE.
data BatchUpdateValuesRequestResponseValueRenderOption
= FormattedValue
-- ^ @FORMATTED_VALUE@
-- Values will be calculated & formatted in the reply according to the
-- cell\'s formatting. Formatting is based on the spreadsheet\'s locale,
-- not the requesting user\'s locale. For example, if \`A1\` is \`1.23\`
-- and \`A2\` is \`=A1\` and formatted as currency, then \`A2\` would
-- return \`\"$1.23\"\`.
| UnformattedValue
-- ^ @UNFORMATTED_VALUE@
-- Values will be calculated, but not formatted in the reply. For example,
-- if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as currency,
-- then \`A2\` would return the number \`1.23\`.
| Formula
-- ^ @FORMULA@
-- Values will not be calculated. The reply will include the formulas. For
-- example, if \`A1\` is \`1.23\` and \`A2\` is \`=A1\` and formatted as
-- currency, then A2 would return \`\"=A1\"\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchUpdateValuesRequestResponseValueRenderOption
instance FromHttpApiData BatchUpdateValuesRequestResponseValueRenderOption where
parseQueryParam = \case
"FORMATTED_VALUE" -> Right FormattedValue
"UNFORMATTED_VALUE" -> Right UnformattedValue
"FORMULA" -> Right Formula
x -> Left ("Unable to parse BatchUpdateValuesRequestResponseValueRenderOption from: " <> x)
instance ToHttpApiData BatchUpdateValuesRequestResponseValueRenderOption where
toQueryParam = \case
FormattedValue -> "FORMATTED_VALUE"
UnformattedValue -> "UNFORMATTED_VALUE"
Formula -> "FORMULA"
instance FromJSON BatchUpdateValuesRequestResponseValueRenderOption where
parseJSON = parseJSONText "BatchUpdateValuesRequestResponseValueRenderOption"
instance ToJSON BatchUpdateValuesRequestResponseValueRenderOption where
toJSON = toJSONText
-- | Where the legend of the pie chart should be drawn.
data PieChartSpecLegendPosition
= PieChartLegendPositionUnspecified
-- ^ @PIE_CHART_LEGEND_POSITION_UNSPECIFIED@
-- Default value, do not use.
| BottomLegend
-- ^ @BOTTOM_LEGEND@
-- The legend is rendered on the bottom of the chart.
| LeftLegend
-- ^ @LEFT_LEGEND@
-- The legend is rendered on the left of the chart.
| RightLegend
-- ^ @RIGHT_LEGEND@
-- The legend is rendered on the right of the chart.
| TopLegend
-- ^ @TOP_LEGEND@
-- The legend is rendered on the top of the chart.
| NoLegend
-- ^ @NO_LEGEND@
-- No legend is rendered.
| LabeledLegend
-- ^ @LABELED_LEGEND@
-- Each pie slice has a label attached to it.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PieChartSpecLegendPosition
instance FromHttpApiData PieChartSpecLegendPosition where
parseQueryParam = \case
"PIE_CHART_LEGEND_POSITION_UNSPECIFIED" -> Right PieChartLegendPositionUnspecified
"BOTTOM_LEGEND" -> Right BottomLegend
"LEFT_LEGEND" -> Right LeftLegend
"RIGHT_LEGEND" -> Right RightLegend
"TOP_LEGEND" -> Right TopLegend
"NO_LEGEND" -> Right NoLegend
"LABELED_LEGEND" -> Right LabeledLegend
x -> Left ("Unable to parse PieChartSpecLegendPosition from: " <> x)
instance ToHttpApiData PieChartSpecLegendPosition where
toQueryParam = \case
PieChartLegendPositionUnspecified -> "PIE_CHART_LEGEND_POSITION_UNSPECIFIED"
BottomLegend -> "BOTTOM_LEGEND"
LeftLegend -> "LEFT_LEGEND"
RightLegend -> "RIGHT_LEGEND"
TopLegend -> "TOP_LEGEND"
NoLegend -> "NO_LEGEND"
LabeledLegend -> "LABELED_LEGEND"
instance FromJSON PieChartSpecLegendPosition where
parseJSON = parseJSONText "PieChartSpecLegendPosition"
instance ToJSON PieChartSpecLegendPosition where
toJSON = toJSONText
-- | The vertical alignment of the value in the cell.
data CellFormatVerticalAlignment
= VerticalAlignUnspecified
-- ^ @VERTICAL_ALIGN_UNSPECIFIED@
-- The vertical alignment is not specified. Do not use this.
| Top
-- ^ @TOP@
-- The text is explicitly aligned to the top of the cell.
| Middle
-- ^ @MIDDLE@
-- The text is explicitly aligned to the middle of the cell.
| Bottom
-- ^ @BOTTOM@
-- The text is explicitly aligned to the bottom of the cell.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatVerticalAlignment
instance FromHttpApiData CellFormatVerticalAlignment where
parseQueryParam = \case
"VERTICAL_ALIGN_UNSPECIFIED" -> Right VerticalAlignUnspecified
"TOP" -> Right Top
"MIDDLE" -> Right Middle
"BOTTOM" -> Right Bottom
x -> Left ("Unable to parse CellFormatVerticalAlignment from: " <> x)
instance ToHttpApiData CellFormatVerticalAlignment where
toQueryParam = \case
VerticalAlignUnspecified -> "VERTICAL_ALIGN_UNSPECIFIED"
Top -> "TOP"
Middle -> "MIDDLE"
Bottom -> "BOTTOM"
instance FromJSON CellFormatVerticalAlignment where
parseJSON = parseJSONText "CellFormatVerticalAlignment"
instance ToJSON CellFormatVerticalAlignment where
toJSON = toJSONText
-- | The type of the number format. When writing, this field must be set.
data NumberFormatType
= NumberFormatTypeUnspecified
-- ^ @NUMBER_FORMAT_TYPE_UNSPECIFIED@
-- The number format is not specified and is based on the contents of the
-- cell. Do not explicitly use this.
| Text
-- ^ @TEXT@
-- Text formatting, e.g \`1000.12\`
| Number
-- ^ @NUMBER@
-- Number formatting, e.g, \`1,000.12\`
| Percent
-- ^ @PERCENT@
-- Percent formatting, e.g \`10.12%\`
| Currency
-- ^ @CURRENCY@
-- Currency formatting, e.g \`$1,000.12\`
| Date
-- ^ @DATE@
-- Date formatting, e.g \`9\/26\/2008\`
| Time
-- ^ @TIME@
-- Time formatting, e.g \`3:59:00 PM\`
| DateTime
-- ^ @DATE_TIME@
-- Date+Time formatting, e.g \`9\/26\/08 15:59:00\`
| Scientific
-- ^ @SCIENTIFIC@
-- Scientific number formatting, e.g \`1.01E+03\`
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable NumberFormatType
instance FromHttpApiData NumberFormatType where
parseQueryParam = \case
"NUMBER_FORMAT_TYPE_UNSPECIFIED" -> Right NumberFormatTypeUnspecified
"TEXT" -> Right Text
"NUMBER" -> Right Number
"PERCENT" -> Right Percent
"CURRENCY" -> Right Currency
"DATE" -> Right Date
"TIME" -> Right Time
"DATE_TIME" -> Right DateTime
"SCIENTIFIC" -> Right Scientific
x -> Left ("Unable to parse NumberFormatType from: " <> x)
instance ToHttpApiData NumberFormatType where
toQueryParam = \case
NumberFormatTypeUnspecified -> "NUMBER_FORMAT_TYPE_UNSPECIFIED"
Text -> "TEXT"
Number -> "NUMBER"
Percent -> "PERCENT"
Currency -> "CURRENCY"
Date -> "DATE"
Time -> "TIME"
DateTime -> "DATE_TIME"
Scientific -> "SCIENTIFIC"
instance FromJSON NumberFormatType where
parseJSON = parseJSONText "NumberFormatType"
instance ToJSON NumberFormatType where
toJSON = toJSONText
-- | A relative date (based on the current date). Valid only if the type is
-- DATE_BEFORE, DATE_AFTER, DATE_ON_OR_BEFORE or DATE_ON_OR_AFTER. Relative
-- dates are not supported in data validation. They are supported only in
-- conditional formatting and conditional filters.
data ConditionValueRelativeDate
= RelativeDateUnspecified
-- ^ @RELATIVE_DATE_UNSPECIFIED@
-- Default value, do not use.
| PastYear
-- ^ @PAST_YEAR@
-- The value is one year before today.
| PastMonth
-- ^ @PAST_MONTH@
-- The value is one month before today.
| PastWeek
-- ^ @PAST_WEEK@
-- The value is one week before today.
| Yesterday
-- ^ @YESTERDAY@
-- The value is yesterday.
| Today
-- ^ @TODAY@
-- The value is today.
| Tomorrow
-- ^ @TOMORROW@
-- The value is tomorrow.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ConditionValueRelativeDate
instance FromHttpApiData ConditionValueRelativeDate where
parseQueryParam = \case
"RELATIVE_DATE_UNSPECIFIED" -> Right RelativeDateUnspecified
"PAST_YEAR" -> Right PastYear
"PAST_MONTH" -> Right PastMonth
"PAST_WEEK" -> Right PastWeek
"YESTERDAY" -> Right Yesterday
"TODAY" -> Right Today
"TOMORROW" -> Right Tomorrow
x -> Left ("Unable to parse ConditionValueRelativeDate from: " <> x)
instance ToHttpApiData ConditionValueRelativeDate where
toQueryParam = \case
RelativeDateUnspecified -> "RELATIVE_DATE_UNSPECIFIED"
PastYear -> "PAST_YEAR"
PastMonth -> "PAST_MONTH"
PastWeek -> "PAST_WEEK"
Yesterday -> "YESTERDAY"
Today -> "TODAY"
Tomorrow -> "TOMORROW"
instance FromJSON ConditionValueRelativeDate where
parseJSON = parseJSONText "ConditionValueRelativeDate"
instance ToJSON ConditionValueRelativeDate where
toJSON = toJSONText
-- | The order data should be sorted.
data SortSpecSortOrder
= SortOrderUnspecified
-- ^ @SORT_ORDER_UNSPECIFIED@
-- Default value, do not use this.
| Ascending
-- ^ @ASCENDING@
-- Sort ascending.
| Descending
-- ^ @DESCENDING@
-- Sort descending.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SortSpecSortOrder
instance FromHttpApiData SortSpecSortOrder where
parseQueryParam = \case
"SORT_ORDER_UNSPECIFIED" -> Right SortOrderUnspecified
"ASCENDING" -> Right Ascending
"DESCENDING" -> Right Descending
x -> Left ("Unable to parse SortSpecSortOrder from: " <> x)
instance ToHttpApiData SortSpecSortOrder where
toQueryParam = \case
SortOrderUnspecified -> "SORT_ORDER_UNSPECIFIED"
Ascending -> "ASCENDING"
Descending -> "DESCENDING"
instance FromJSON SortSpecSortOrder where
parseJSON = parseJSONText "SortSpecSortOrder"
instance ToJSON SortSpecSortOrder where
toJSON = toJSONText
-- | A function to summarize the value. If formula is set, the only supported
-- values are SUM and CUSTOM. If sourceColumnOffset is set, then \`CUSTOM\`
-- is not supported.
data PivotValueSummarizeFunction
= PivotStandardValueFunctionUnspecified
-- ^ @PIVOT_STANDARD_VALUE_FUNCTION_UNSPECIFIED@
-- The default, do not use.
| Sum
-- ^ @SUM@
-- Corresponds to the \`SUM\` function.
| Counta
-- ^ @COUNTA@
-- Corresponds to the \`COUNTA\` function.
| Count
-- ^ @COUNT@
-- Corresponds to the \`COUNT\` function.
| Countunique
-- ^ @COUNTUNIQUE@
-- Corresponds to the \`COUNTUNIQUE\` function.
| Average
-- ^ @AVERAGE@
-- Corresponds to the \`AVERAGE\` function.
| Max
-- ^ @MAX@
-- Corresponds to the \`MAX\` function.
| Min
-- ^ @MIN@
-- Corresponds to the \`MIN\` function.
| Median
-- ^ @MEDIAN@
-- Corresponds to the \`MEDIAN\` function.
| Product
-- ^ @PRODUCT@
-- Corresponds to the \`PRODUCT\` function.
| Stdev
-- ^ @STDEV@
-- Corresponds to the \`STDEV\` function.
| Stdevp
-- ^ @STDEVP@
-- Corresponds to the \`STDEVP\` function.
| Var
-- ^ @VAR@
-- Corresponds to the \`VAR\` function.
| Varp
-- ^ @VARP@
-- Corresponds to the \`VARP\` function.
| Custom
-- ^ @CUSTOM@
-- Indicates the formula should be used as-is. Only valid if
-- PivotValue.formula was set.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PivotValueSummarizeFunction
instance FromHttpApiData PivotValueSummarizeFunction where
parseQueryParam = \case
"PIVOT_STANDARD_VALUE_FUNCTION_UNSPECIFIED" -> Right PivotStandardValueFunctionUnspecified
"SUM" -> Right Sum
"COUNTA" -> Right Counta
"COUNT" -> Right Count
"COUNTUNIQUE" -> Right Countunique
"AVERAGE" -> Right Average
"MAX" -> Right Max
"MIN" -> Right Min
"MEDIAN" -> Right Median
"PRODUCT" -> Right Product
"STDEV" -> Right Stdev
"STDEVP" -> Right Stdevp
"VAR" -> Right Var
"VARP" -> Right Varp
"CUSTOM" -> Right Custom
x -> Left ("Unable to parse PivotValueSummarizeFunction from: " <> x)
instance ToHttpApiData PivotValueSummarizeFunction where
toQueryParam = \case
PivotStandardValueFunctionUnspecified -> "PIVOT_STANDARD_VALUE_FUNCTION_UNSPECIFIED"
Sum -> "SUM"
Counta -> "COUNTA"
Count -> "COUNT"
Countunique -> "COUNTUNIQUE"
Average -> "AVERAGE"
Max -> "MAX"
Min -> "MIN"
Median -> "MEDIAN"
Product -> "PRODUCT"
Stdev -> "STDEV"
Stdevp -> "STDEVP"
Var -> "VAR"
Varp -> "VARP"
Custom -> "CUSTOM"
instance FromJSON PivotValueSummarizeFunction where
parseJSON = parseJSONText "PivotValueSummarizeFunction"
instance ToJSON PivotValueSummarizeFunction where
toJSON = toJSONText
-- | How a hyperlink, if it exists, should be displayed in the cell.
data CellFormatHyperlinkDisplayType
= HyperlinkDisplayTypeUnspecified
-- ^ @HYPERLINK_DISPLAY_TYPE_UNSPECIFIED@
-- The default value: the hyperlink is rendered. Do not use this.
| Linked
-- ^ @LINKED@
-- A hyperlink should be explicitly rendered.
| PlainText
-- ^ @PLAIN_TEXT@
-- A hyperlink should not be rendered.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatHyperlinkDisplayType
instance FromHttpApiData CellFormatHyperlinkDisplayType where
parseQueryParam = \case
"HYPERLINK_DISPLAY_TYPE_UNSPECIFIED" -> Right HyperlinkDisplayTypeUnspecified
"LINKED" -> Right Linked
"PLAIN_TEXT" -> Right PlainText
x -> Left ("Unable to parse CellFormatHyperlinkDisplayType from: " <> x)
instance ToHttpApiData CellFormatHyperlinkDisplayType where
toQueryParam = \case
HyperlinkDisplayTypeUnspecified -> "HYPERLINK_DISPLAY_TYPE_UNSPECIFIED"
Linked -> "LINKED"
PlainText -> "PLAIN_TEXT"
instance FromJSON CellFormatHyperlinkDisplayType where
parseJSON = parseJSONText "CellFormatHyperlinkDisplayType"
instance ToJSON CellFormatHyperlinkDisplayType where
toJSON = toJSONText
-- | The type of sheet. Defaults to GRID. This field cannot be changed once
-- set.
data SheetPropertiesSheetType
= SheetTypeUnspecified
-- ^ @SHEET_TYPE_UNSPECIFIED@
-- Default value, do not use.
| Grid
-- ^ @GRID@
-- The sheet is a grid.
| Object
-- ^ @OBJECT@
-- The sheet has no grid and instead has an object like a chart or image.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SheetPropertiesSheetType
instance FromHttpApiData SheetPropertiesSheetType where
parseQueryParam = \case
"SHEET_TYPE_UNSPECIFIED" -> Right SheetTypeUnspecified
"GRID" -> Right Grid
"OBJECT" -> Right Object
x -> Left ("Unable to parse SheetPropertiesSheetType from: " <> x)
instance ToHttpApiData SheetPropertiesSheetType where
toQueryParam = \case
SheetTypeUnspecified -> "SHEET_TYPE_UNSPECIFIED"
Grid -> "GRID"
Object -> "OBJECT"
instance FromJSON SheetPropertiesSheetType where
parseJSON = parseJSONText "SheetPropertiesSheetType"
instance ToJSON SheetPropertiesSheetType where
toJSON = toJSONText
-- | How the cells should be merged.
data MergeCellsRequestMergeType
= MergeAll
-- ^ @MERGE_ALL@
-- Create a single merge from the range
| MergeColumns
-- ^ @MERGE_COLUMNS@
-- Create a merge for each column in the range
| MergeRows
-- ^ @MERGE_ROWS@
-- Create a merge for each row in the range
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable MergeCellsRequestMergeType
instance FromHttpApiData MergeCellsRequestMergeType where
parseQueryParam = \case
"MERGE_ALL" -> Right MergeAll
"MERGE_COLUMNS" -> Right MergeColumns
"MERGE_ROWS" -> Right MergeRows
x -> Left ("Unable to parse MergeCellsRequestMergeType from: " <> x)
instance ToHttpApiData MergeCellsRequestMergeType where
toQueryParam = \case
MergeAll -> "MERGE_ALL"
MergeColumns -> "MERGE_COLUMNS"
MergeRows -> "MERGE_ROWS"
instance FromJSON MergeCellsRequestMergeType where
parseJSON = parseJSONText "MergeCellsRequestMergeType"
instance ToJSON MergeCellsRequestMergeType where
toJSON = toJSONText
-- | The horizontal alignment of the value in the cell.
data CellFormatHorizontalAlignment
= HorizontalAlignUnspecified
-- ^ @HORIZONTAL_ALIGN_UNSPECIFIED@
-- The horizontal alignment is not specified. Do not use this.
| Left'
-- ^ @LEFT@
-- The text is explicitly aligned to the left of the cell.
| Center
-- ^ @CENTER@
-- The text is explicitly aligned to the center of the cell.
| Right'
-- ^ @RIGHT@
-- The text is explicitly aligned to the right of the cell.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatHorizontalAlignment
instance FromHttpApiData CellFormatHorizontalAlignment where
parseQueryParam = \case
"HORIZONTAL_ALIGN_UNSPECIFIED" -> Right HorizontalAlignUnspecified
"LEFT" -> Right Left'
"CENTER" -> Right Center
"RIGHT" -> Right Right'
x -> Left ("Unable to parse CellFormatHorizontalAlignment from: " <> x)
instance ToHttpApiData CellFormatHorizontalAlignment where
toQueryParam = \case
HorizontalAlignUnspecified -> "HORIZONTAL_ALIGN_UNSPECIFIED"
Left' -> "LEFT"
Center -> "CENTER"
Right' -> "RIGHT"
instance FromJSON CellFormatHorizontalAlignment where
parseJSON = parseJSONText "CellFormatHorizontalAlignment"
instance ToJSON CellFormatHorizontalAlignment where
toJSON = toJSONText
-- | The type of condition.
data BooleanConditionType
= ConditionTypeUnspecified
-- ^ @CONDITION_TYPE_UNSPECIFIED@
-- The default value, do not use.
| NumberGreater
-- ^ @NUMBER_GREATER@
-- The cell\'s value must be greater than the condition\'s value. Supported
-- by data validation, conditional formatting and filters. Requires a
-- single ConditionValue.
| NumberGreaterThanEQ
-- ^ @NUMBER_GREATER_THAN_EQ@
-- The cell\'s value must be greater than or equal to the condition\'s
-- value. Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue.
| NumberLess
-- ^ @NUMBER_LESS@
-- The cell\'s value must be less than the condition\'s value. Supported by
-- data validation, conditional formatting and filters. Requires a single
-- ConditionValue.
| NumberLessThanEQ
-- ^ @NUMBER_LESS_THAN_EQ@
-- The cell\'s value must be less than or equal to the condition\'s value.
-- Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue.
| NumberEQ
-- ^ @NUMBER_EQ@
-- The cell\'s value must be equal to the condition\'s value. Supported by
-- data validation, conditional formatting and filters. Requires a single
-- ConditionValue.
| NumberNotEQ
-- ^ @NUMBER_NOT_EQ@
-- The cell\'s value must be not equal to the condition\'s value. Supported
-- by data validation, conditional formatting and filters. Requires a
-- single ConditionValue.
| NumberBetween
-- ^ @NUMBER_BETWEEN@
-- The cell\'s value must be between the two condition values. Supported by
-- data validation, conditional formatting and filters. Requires exactly
-- two ConditionValues.
| NumberNotBetween
-- ^ @NUMBER_NOT_BETWEEN@
-- The cell\'s value must not be between the two condition values.
-- Supported by data validation, conditional formatting and filters.
-- Requires exactly two ConditionValues.
| TextContains
-- ^ @TEXT_CONTAINS@
-- The cell\'s value must contain the condition\'s value. Supported by data
-- validation, conditional formatting and filters. Requires a single
-- ConditionValue.
| TextNotContains
-- ^ @TEXT_NOT_CONTAINS@
-- The cell\'s value must not contain the condition\'s value. Supported by
-- data validation, conditional formatting and filters. Requires a single
-- ConditionValue.
| TextStartsWith
-- ^ @TEXT_STARTS_WITH@
-- The cell\'s value must start with the condition\'s value. Supported by
-- conditional formatting and filters. Requires a single ConditionValue.
| TextEndsWith
-- ^ @TEXT_ENDS_WITH@
-- The cell\'s value must end with the condition\'s value. Supported by
-- conditional formatting and filters. Requires a single ConditionValue.
| TextEQ
-- ^ @TEXT_EQ@
-- The cell\'s value must be exactly the condition\'s value. Supported by
-- data validation, conditional formatting and filters. Requires a single
-- ConditionValue.
| TextIsEmail
-- ^ @TEXT_IS_EMAIL@
-- The cell\'s value must be a valid email address. Supported by data
-- validation. Requires no ConditionValues.
| TextIsURL
-- ^ @TEXT_IS_URL@
-- The cell\'s value must be a valid URL. Supported by data validation.
-- Requires no ConditionValues.
| DateEQ
-- ^ @DATE_EQ@
-- The cell\'s value must be the same date as the condition\'s value.
-- Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue.
| DateBefore
-- ^ @DATE_BEFORE@
-- The cell\'s value must be before the date of the condition\'s value.
-- Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue that may be a relative date.
| DateAfter
-- ^ @DATE_AFTER@
-- The cell\'s value must be after the date of the condition\'s value.
-- Supported by data validation, conditional formatting and filters.
-- Requires a single ConditionValue that may be a relative date.
| DateOnOrBefore
-- ^ @DATE_ON_OR_BEFORE@
-- The cell\'s value must be on or before the date of the condition\'s
-- value. Supported by data validation. Requires a single ConditionValue
-- that may be a relative date.
| DateOnOrAfter
-- ^ @DATE_ON_OR_AFTER@
-- The cell\'s value must be on or after the date of the condition\'s
-- value. Supported by data validation. Requires a single ConditionValue
-- that may be a relative date.
| DateBetween
-- ^ @DATE_BETWEEN@
-- The cell\'s value must be between the dates of the two condition values.
-- Supported by data validation. Requires exactly two ConditionValues.
| DateNotBetween
-- ^ @DATE_NOT_BETWEEN@
-- The cell\'s value must be outside the dates of the two condition values.
-- Supported by data validation. Requires exactly two ConditionValues.
| DateIsValid
-- ^ @DATE_IS_VALID@
-- The cell\'s value must be a date. Supported by data validation. Requires
-- no ConditionValues.
| OneOfRange
-- ^ @ONE_OF_RANGE@
-- The cell\'s value must be listed in the grid in condition value\'s
-- range. Supported by data validation. Requires a single ConditionValue,
-- and the value must be a valid range in A1 notation.
| OneOfList
-- ^ @ONE_OF_LIST@
-- The cell\'s value must in the list of condition values. Supported by
-- data validation. Supports any number of condition values, one per item
-- in the list. Formulas are not supported in the values.
| Blank
-- ^ @BLANK@
-- The cell\'s value must be empty. Supported by conditional formatting and
-- filters. Requires no ConditionValues.
| NotBlank
-- ^ @NOT_BLANK@
-- The cell\'s value must not be empty. Supported by conditional formatting
-- and filters. Requires no ConditionValues.
| CustomFormula
-- ^ @CUSTOM_FORMULA@
-- The condition\'s formula must evaluate to true. Supported by data
-- validation, conditional formatting and filters. Requires a single
-- ConditionValue.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BooleanConditionType
instance FromHttpApiData BooleanConditionType where
parseQueryParam = \case
"CONDITION_TYPE_UNSPECIFIED" -> Right ConditionTypeUnspecified
"NUMBER_GREATER" -> Right NumberGreater
"NUMBER_GREATER_THAN_EQ" -> Right NumberGreaterThanEQ
"NUMBER_LESS" -> Right NumberLess
"NUMBER_LESS_THAN_EQ" -> Right NumberLessThanEQ
"NUMBER_EQ" -> Right NumberEQ
"NUMBER_NOT_EQ" -> Right NumberNotEQ
"NUMBER_BETWEEN" -> Right NumberBetween
"NUMBER_NOT_BETWEEN" -> Right NumberNotBetween
"TEXT_CONTAINS" -> Right TextContains
"TEXT_NOT_CONTAINS" -> Right TextNotContains
"TEXT_STARTS_WITH" -> Right TextStartsWith
"TEXT_ENDS_WITH" -> Right TextEndsWith
"TEXT_EQ" -> Right TextEQ
"TEXT_IS_EMAIL" -> Right TextIsEmail
"TEXT_IS_URL" -> Right TextIsURL
"DATE_EQ" -> Right DateEQ
"DATE_BEFORE" -> Right DateBefore
"DATE_AFTER" -> Right DateAfter
"DATE_ON_OR_BEFORE" -> Right DateOnOrBefore
"DATE_ON_OR_AFTER" -> Right DateOnOrAfter
"DATE_BETWEEN" -> Right DateBetween
"DATE_NOT_BETWEEN" -> Right DateNotBetween
"DATE_IS_VALID" -> Right DateIsValid
"ONE_OF_RANGE" -> Right OneOfRange
"ONE_OF_LIST" -> Right OneOfList
"BLANK" -> Right Blank
"NOT_BLANK" -> Right NotBlank
"CUSTOM_FORMULA" -> Right CustomFormula
x -> Left ("Unable to parse BooleanConditionType from: " <> x)
instance ToHttpApiData BooleanConditionType where
toQueryParam = \case
ConditionTypeUnspecified -> "CONDITION_TYPE_UNSPECIFIED"
NumberGreater -> "NUMBER_GREATER"
NumberGreaterThanEQ -> "NUMBER_GREATER_THAN_EQ"
NumberLess -> "NUMBER_LESS"
NumberLessThanEQ -> "NUMBER_LESS_THAN_EQ"
NumberEQ -> "NUMBER_EQ"
NumberNotEQ -> "NUMBER_NOT_EQ"
NumberBetween -> "NUMBER_BETWEEN"
NumberNotBetween -> "NUMBER_NOT_BETWEEN"
TextContains -> "TEXT_CONTAINS"
TextNotContains -> "TEXT_NOT_CONTAINS"
TextStartsWith -> "TEXT_STARTS_WITH"
TextEndsWith -> "TEXT_ENDS_WITH"
TextEQ -> "TEXT_EQ"
TextIsEmail -> "TEXT_IS_EMAIL"
TextIsURL -> "TEXT_IS_URL"
DateEQ -> "DATE_EQ"
DateBefore -> "DATE_BEFORE"
DateAfter -> "DATE_AFTER"
DateOnOrBefore -> "DATE_ON_OR_BEFORE"
DateOnOrAfter -> "DATE_ON_OR_AFTER"
DateBetween -> "DATE_BETWEEN"
DateNotBetween -> "DATE_NOT_BETWEEN"
DateIsValid -> "DATE_IS_VALID"
OneOfRange -> "ONE_OF_RANGE"
OneOfList -> "ONE_OF_LIST"
Blank -> "BLANK"
NotBlank -> "NOT_BLANK"
CustomFormula -> "CUSTOM_FORMULA"
instance FromJSON BooleanConditionType where
parseJSON = parseJSONText "BooleanConditionType"
instance ToJSON BooleanConditionType where
toJSON = toJSONText
-- | The major dimension of the values. For output, if the spreadsheet data
-- is: \`A1=1,B1=2,A2=3,B2=4\`, then requesting
-- \`range=A1:B2,majorDimension=ROWS\` will return \`[[1,2],[3,4]]\`,
-- whereas requesting \`range=A1:B2,majorDimension=COLUMNS\` will return
-- \`[[1,3],[2,4]]\`. For input, with \`range=A1:B2,majorDimension=ROWS\`
-- then \`[[1,2],[3,4]]\` will set \`A1=1,B1=2,A2=3,B2=4\`. With
-- \`range=A1:B2,majorDimension=COLUMNS\` then \`[[1,2],[3,4]]\` will set
-- \`A1=1,B1=3,A2=2,B2=4\`. When writing, if this field is not set, it
-- defaults to ROWS.
data ValueRangeMajorDimension
= VRMDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| VRMDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| VRMDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ValueRangeMajorDimension
instance FromHttpApiData ValueRangeMajorDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right VRMDDimensionUnspecified
"ROWS" -> Right VRMDRows
"COLUMNS" -> Right VRMDColumns
x -> Left ("Unable to parse ValueRangeMajorDimension from: " <> x)
instance ToHttpApiData ValueRangeMajorDimension where
toQueryParam = \case
VRMDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
VRMDRows -> "ROWS"
VRMDColumns -> "COLUMNS"
instance FromJSON ValueRangeMajorDimension where
parseJSON = parseJSONText "ValueRangeMajorDimension"
instance ToJSON ValueRangeMajorDimension where
toJSON = toJSONText
-- | The order the values in this group should be sorted.
data PivotGroupSortOrder
= PGSOSortOrderUnspecified
-- ^ @SORT_ORDER_UNSPECIFIED@
-- Default value, do not use this.
| PGSOAscending
-- ^ @ASCENDING@
-- Sort ascending.
| PGSODescending
-- ^ @DESCENDING@
-- Sort descending.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PivotGroupSortOrder
instance FromHttpApiData PivotGroupSortOrder where
parseQueryParam = \case
"SORT_ORDER_UNSPECIFIED" -> Right PGSOSortOrderUnspecified
"ASCENDING" -> Right PGSOAscending
"DESCENDING" -> Right PGSODescending
x -> Left ("Unable to parse PivotGroupSortOrder from: " <> x)
instance ToHttpApiData PivotGroupSortOrder where
toQueryParam = \case
PGSOSortOrderUnspecified -> "SORT_ORDER_UNSPECIFIED"
PGSOAscending -> "ASCENDING"
PGSODescending -> "DESCENDING"
instance FromJSON PivotGroupSortOrder where
parseJSON = parseJSONText "PivotGroupSortOrder"
instance ToJSON PivotGroupSortOrder where
toJSON = toJSONText
-- | The type of the chart.
data BasicChartSpecChartType
= BasicChartTypeUnspecified
-- ^ @BASIC_CHART_TYPE_UNSPECIFIED@
-- Default value, do not use.
| Bar
-- ^ @BAR@
-- A </chart/interactive/docs/gallery/barchart bar chart>.
| Line
-- ^ @LINE@
-- A </chart/interactive/docs/gallery/linechart line chart>.
| Area
-- ^ @AREA@
-- An </chart/interactive/docs/gallery/areachart area chart>.
| Column
-- ^ @COLUMN@
-- A </chart/interactive/docs/gallery/columnchart column chart>.
| Scatter
-- ^ @SCATTER@
-- A </chart/interactive/docs/gallery/scatterchart scatter chart>.
| Combo
-- ^ @COMBO@
-- A </chart/interactive/docs/gallery/combochart combo chart>.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSpecChartType
instance FromHttpApiData BasicChartSpecChartType where
parseQueryParam = \case
"BASIC_CHART_TYPE_UNSPECIFIED" -> Right BasicChartTypeUnspecified
"BAR" -> Right Bar
"LINE" -> Right Line
"AREA" -> Right Area
"COLUMN" -> Right Column
"SCATTER" -> Right Scatter
"COMBO" -> Right Combo
x -> Left ("Unable to parse BasicChartSpecChartType from: " <> x)
instance ToHttpApiData BasicChartSpecChartType where
toQueryParam = \case
BasicChartTypeUnspecified -> "BASIC_CHART_TYPE_UNSPECIFIED"
Bar -> "BAR"
Line -> "LINE"
Area -> "AREA"
Column -> "COLUMN"
Scatter -> "SCATTER"
Combo -> "COMBO"
instance FromJSON BasicChartSpecChartType where
parseJSON = parseJSONText "BasicChartSpecChartType"
instance ToJSON BasicChartSpecChartType where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | The amount of time to wait before volatile functions are recalculated.
data SpreadsheetPropertiesAutoRecalc
= RecalculationIntervalUnspecified
-- ^ @RECALCULATION_INTERVAL_UNSPECIFIED@
-- Default value. This value must not be used.
| OnChange
-- ^ @ON_CHANGE@
-- Volatile functions are updated on every change.
| Minute
-- ^ @MINUTE@
-- Volatile functions are updated on every change and every minute.
| Hour
-- ^ @HOUR@
-- Volatile functions are updated on every change and hourly.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpreadsheetPropertiesAutoRecalc
instance FromHttpApiData SpreadsheetPropertiesAutoRecalc where
parseQueryParam = \case
"RECALCULATION_INTERVAL_UNSPECIFIED" -> Right RecalculationIntervalUnspecified
"ON_CHANGE" -> Right OnChange
"MINUTE" -> Right Minute
"HOUR" -> Right Hour
x -> Left ("Unable to parse SpreadsheetPropertiesAutoRecalc from: " <> x)
instance ToHttpApiData SpreadsheetPropertiesAutoRecalc where
toQueryParam = \case
RecalculationIntervalUnspecified -> "RECALCULATION_INTERVAL_UNSPECIFIED"
OnChange -> "ON_CHANGE"
Minute -> "MINUTE"
Hour -> "HOUR"
instance FromJSON SpreadsheetPropertiesAutoRecalc where
parseJSON = parseJSONText "SpreadsheetPropertiesAutoRecalc"
instance ToJSON SpreadsheetPropertiesAutoRecalc where
toJSON = toJSONText
-- | How that data should be oriented when pasting.
data CopyPasteRequestPasteOrientation
= Normal
-- ^ @NORMAL@
-- Paste normally.
| Transpose
-- ^ @TRANSPOSE@
-- Paste transposed, where all rows become columns and vice versa.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CopyPasteRequestPasteOrientation
instance FromHttpApiData CopyPasteRequestPasteOrientation where
parseQueryParam = \case
"NORMAL" -> Right Normal
"TRANSPOSE" -> Right Transpose
x -> Left ("Unable to parse CopyPasteRequestPasteOrientation from: " <> x)
instance ToHttpApiData CopyPasteRequestPasteOrientation where
toQueryParam = \case
Normal -> "NORMAL"
Transpose -> "TRANSPOSE"
instance FromJSON CopyPasteRequestPasteOrientation where
parseJSON = parseJSONText "CopyPasteRequestPasteOrientation"
instance ToJSON CopyPasteRequestPasteOrientation where
toJSON = toJSONText
-- | How the data should be pasted.
data PasteDataRequestType
= PDRTPasteNormal
-- ^ @PASTE_NORMAL@
-- Paste values, formulas, formats, and merges.
| PDRTPasteValues
-- ^ @PASTE_VALUES@
-- Paste the values ONLY without formats, formulas, or merges.
| PDRTPasteFormat
-- ^ @PASTE_FORMAT@
-- Paste the format and data validation only.
| PDRTPasteNoBOrders
-- ^ @PASTE_NO_BORDERS@
-- Like PASTE_NORMAL but without borders.
| PDRTPasteFormula
-- ^ @PASTE_FORMULA@
-- Paste the formulas only.
| PDRTPasteDataValidation
-- ^ @PASTE_DATA_VALIDATION@
-- Paste the data validation only.
| PDRTPasteConditionalFormatting
-- ^ @PASTE_CONDITIONAL_FORMATTING@
-- Paste the conditional formatting rules only.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PasteDataRequestType
instance FromHttpApiData PasteDataRequestType where
parseQueryParam = \case
"PASTE_NORMAL" -> Right PDRTPasteNormal
"PASTE_VALUES" -> Right PDRTPasteValues
"PASTE_FORMAT" -> Right PDRTPasteFormat
"PASTE_NO_BORDERS" -> Right PDRTPasteNoBOrders
"PASTE_FORMULA" -> Right PDRTPasteFormula
"PASTE_DATA_VALIDATION" -> Right PDRTPasteDataValidation
"PASTE_CONDITIONAL_FORMATTING" -> Right PDRTPasteConditionalFormatting
x -> Left ("Unable to parse PasteDataRequestType from: " <> x)
instance ToHttpApiData PasteDataRequestType where
toQueryParam = \case
PDRTPasteNormal -> "PASTE_NORMAL"
PDRTPasteValues -> "PASTE_VALUES"
PDRTPasteFormat -> "PASTE_FORMAT"
PDRTPasteNoBOrders -> "PASTE_NO_BORDERS"
PDRTPasteFormula -> "PASTE_FORMULA"
PDRTPasteDataValidation -> "PASTE_DATA_VALIDATION"
PDRTPasteConditionalFormatting -> "PASTE_CONDITIONAL_FORMATTING"
instance FromJSON PasteDataRequestType where
parseJSON = parseJSONText "PasteDataRequestType"
instance ToJSON PasteDataRequestType where
toJSON = toJSONText
-- | The direction of the text in the cell.
data CellFormatTextDirection
= TextDirectionUnspecified
-- ^ @TEXT_DIRECTION_UNSPECIFIED@
-- The text direction is not specified. Do not use this.
| LeftToRight
-- ^ @LEFT_TO_RIGHT@
-- The text direction of left-to-right was set by the user.
| RightToLeft
-- ^ @RIGHT_TO_LEFT@
-- The text direction of right-to-left was set by the user.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CellFormatTextDirection
instance FromHttpApiData CellFormatTextDirection where
parseQueryParam = \case
"TEXT_DIRECTION_UNSPECIFIED" -> Right TextDirectionUnspecified
"LEFT_TO_RIGHT" -> Right LeftToRight
"RIGHT_TO_LEFT" -> Right RightToLeft
x -> Left ("Unable to parse CellFormatTextDirection from: " <> x)
instance ToHttpApiData CellFormatTextDirection where
toQueryParam = \case
TextDirectionUnspecified -> "TEXT_DIRECTION_UNSPECIFIED"
LeftToRight -> "LEFT_TO_RIGHT"
RightToLeft -> "RIGHT_TO_LEFT"
instance FromJSON CellFormatTextDirection where
parseJSON = parseJSONText "CellFormatTextDirection"
instance ToJSON CellFormatTextDirection where
toJSON = toJSONText
-- | The type of this series. Valid only if the chartType is COMBO. Different
-- types will change the way the series is visualized. Only LINE, AREA, and
-- COLUMN are supported.
data BasicChartSeriesType
= BCSTBasicChartTypeUnspecified
-- ^ @BASIC_CHART_TYPE_UNSPECIFIED@
-- Default value, do not use.
| BCSTBar
-- ^ @BAR@
-- A </chart/interactive/docs/gallery/barchart bar chart>.
| BCSTLine
-- ^ @LINE@
-- A </chart/interactive/docs/gallery/linechart line chart>.
| BCSTArea
-- ^ @AREA@
-- An </chart/interactive/docs/gallery/areachart area chart>.
| BCSTColumn
-- ^ @COLUMN@
-- A </chart/interactive/docs/gallery/columnchart column chart>.
| BCSTScatter
-- ^ @SCATTER@
-- A </chart/interactive/docs/gallery/scatterchart scatter chart>.
| BCSTCombo
-- ^ @COMBO@
-- A </chart/interactive/docs/gallery/combochart combo chart>.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSeriesType
instance FromHttpApiData BasicChartSeriesType where
parseQueryParam = \case
"BASIC_CHART_TYPE_UNSPECIFIED" -> Right BCSTBasicChartTypeUnspecified
"BAR" -> Right BCSTBar
"LINE" -> Right BCSTLine
"AREA" -> Right BCSTArea
"COLUMN" -> Right BCSTColumn
"SCATTER" -> Right BCSTScatter
"COMBO" -> Right BCSTCombo
x -> Left ("Unable to parse BasicChartSeriesType from: " <> x)
instance ToHttpApiData BasicChartSeriesType where
toQueryParam = \case
BCSTBasicChartTypeUnspecified -> "BASIC_CHART_TYPE_UNSPECIFIED"
BCSTBar -> "BAR"
BCSTLine -> "LINE"
BCSTArea -> "AREA"
BCSTColumn -> "COLUMN"
BCSTScatter -> "SCATTER"
BCSTCombo -> "COMBO"
instance FromJSON BasicChartSeriesType where
parseJSON = parseJSONText "BasicChartSeriesType"
instance ToJSON BasicChartSeriesType where
toJSON = toJSONText
-- | Determines how the charts will use hidden rows or columns.
data ChartSpecHiddenDimensionStrategy
= ChartHiddenDimensionStrategyUnspecified
-- ^ @CHART_HIDDEN_DIMENSION_STRATEGY_UNSPECIFIED@
-- Default value, do not use.
| SkipHiddenRowsAndColumns
-- ^ @SKIP_HIDDEN_ROWS_AND_COLUMNS@
-- Charts will skip hidden rows and columns.
| SkipHiddenRows
-- ^ @SKIP_HIDDEN_ROWS@
-- Charts will skip hidden rows only.
| SkipHiddenColumns
-- ^ @SKIP_HIDDEN_COLUMNS@
-- Charts will skip hidden columns only.
| ShowAll
-- ^ @SHOW_ALL@
-- Charts will not skip any hidden rows or columns.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ChartSpecHiddenDimensionStrategy
instance FromHttpApiData ChartSpecHiddenDimensionStrategy where
parseQueryParam = \case
"CHART_HIDDEN_DIMENSION_STRATEGY_UNSPECIFIED" -> Right ChartHiddenDimensionStrategyUnspecified
"SKIP_HIDDEN_ROWS_AND_COLUMNS" -> Right SkipHiddenRowsAndColumns
"SKIP_HIDDEN_ROWS" -> Right SkipHiddenRows
"SKIP_HIDDEN_COLUMNS" -> Right SkipHiddenColumns
"SHOW_ALL" -> Right ShowAll
x -> Left ("Unable to parse ChartSpecHiddenDimensionStrategy from: " <> x)
instance ToHttpApiData ChartSpecHiddenDimensionStrategy where
toQueryParam = \case
ChartHiddenDimensionStrategyUnspecified -> "CHART_HIDDEN_DIMENSION_STRATEGY_UNSPECIFIED"
SkipHiddenRowsAndColumns -> "SKIP_HIDDEN_ROWS_AND_COLUMNS"
SkipHiddenRows -> "SKIP_HIDDEN_ROWS"
SkipHiddenColumns -> "SKIP_HIDDEN_COLUMNS"
ShowAll -> "SHOW_ALL"
instance FromJSON ChartSpecHiddenDimensionStrategy where
parseJSON = parseJSONText "ChartSpecHiddenDimensionStrategy"
instance ToJSON ChartSpecHiddenDimensionStrategy where
toJSON = toJSONText
-- | The style of the border.
data BOrderStyle
= StyleUnspecified
-- ^ @STYLE_UNSPECIFIED@
-- The style is not specified. Do not use this.
| Dotted
-- ^ @DOTTED@
-- The border is dotted.
| Dashed
-- ^ @DASHED@
-- The border is dashed.
| Solid
-- ^ @SOLID@
-- The border is a thin solid line.
| SolidMedium
-- ^ @SOLID_MEDIUM@
-- The border is a medium solid line.
| SolidThick
-- ^ @SOLID_THICK@
-- The border is a thick solid line.
| None
-- ^ @NONE@
-- No border. Used only when updating a border in order to erase it.
| Double
-- ^ @DOUBLE@
-- The border is two solid lines.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BOrderStyle
instance FromHttpApiData BOrderStyle where
parseQueryParam = \case
"STYLE_UNSPECIFIED" -> Right StyleUnspecified
"DOTTED" -> Right Dotted
"DASHED" -> Right Dashed
"SOLID" -> Right Solid
"SOLID_MEDIUM" -> Right SolidMedium
"SOLID_THICK" -> Right SolidThick
"NONE" -> Right None
"DOUBLE" -> Right Double
x -> Left ("Unable to parse BOrderStyle from: " <> x)
instance ToHttpApiData BOrderStyle where
toQueryParam = \case
StyleUnspecified -> "STYLE_UNSPECIFIED"
Dotted -> "DOTTED"
Dashed -> "DASHED"
Solid -> "SOLID"
SolidMedium -> "SOLID_MEDIUM"
SolidThick -> "SOLID_THICK"
None -> "NONE"
Double -> "DOUBLE"
instance FromJSON BOrderStyle where
parseJSON = parseJSONText "BOrderStyle"
instance ToJSON BOrderStyle where
toJSON = toJSONText
-- | What kind of data to paste. All the source data will be cut, regardless
-- of what is pasted.
data CutPasteRequestPasteType
= CPRPTPasteNormal
-- ^ @PASTE_NORMAL@
-- Paste values, formulas, formats, and merges.
| CPRPTPasteValues
-- ^ @PASTE_VALUES@
-- Paste the values ONLY without formats, formulas, or merges.
| CPRPTPasteFormat
-- ^ @PASTE_FORMAT@
-- Paste the format and data validation only.
| CPRPTPasteNoBOrders
-- ^ @PASTE_NO_BORDERS@
-- Like PASTE_NORMAL but without borders.
| CPRPTPasteFormula
-- ^ @PASTE_FORMULA@
-- Paste the formulas only.
| CPRPTPasteDataValidation
-- ^ @PASTE_DATA_VALIDATION@
-- Paste the data validation only.
| CPRPTPasteConditionalFormatting
-- ^ @PASTE_CONDITIONAL_FORMATTING@
-- Paste the conditional formatting rules only.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CutPasteRequestPasteType
instance FromHttpApiData CutPasteRequestPasteType where
parseQueryParam = \case
"PASTE_NORMAL" -> Right CPRPTPasteNormal
"PASTE_VALUES" -> Right CPRPTPasteValues
"PASTE_FORMAT" -> Right CPRPTPasteFormat
"PASTE_NO_BORDERS" -> Right CPRPTPasteNoBOrders
"PASTE_FORMULA" -> Right CPRPTPasteFormula
"PASTE_DATA_VALIDATION" -> Right CPRPTPasteDataValidation
"PASTE_CONDITIONAL_FORMATTING" -> Right CPRPTPasteConditionalFormatting
x -> Left ("Unable to parse CutPasteRequestPasteType from: " <> x)
instance ToHttpApiData CutPasteRequestPasteType where
toQueryParam = \case
CPRPTPasteNormal -> "PASTE_NORMAL"
CPRPTPasteValues -> "PASTE_VALUES"
CPRPTPasteFormat -> "PASTE_FORMAT"
CPRPTPasteNoBOrders -> "PASTE_NO_BORDERS"
CPRPTPasteFormula -> "PASTE_FORMULA"
CPRPTPasteDataValidation -> "PASTE_DATA_VALIDATION"
CPRPTPasteConditionalFormatting -> "PASTE_CONDITIONAL_FORMATTING"
instance FromJSON CutPasteRequestPasteType where
parseJSON = parseJSONText "CutPasteRequestPasteType"
instance ToJSON CutPasteRequestPasteType where
toJSON = toJSONText
-- | The position of the chart legend.
data BasicChartSpecLegendPosition
= BCSLPBasicChartLegendPositionUnspecified
-- ^ @BASIC_CHART_LEGEND_POSITION_UNSPECIFIED@
-- Default value, do not use.
| BCSLPBottomLegend
-- ^ @BOTTOM_LEGEND@
-- The legend is rendered on the bottom of the chart.
| BCSLPLeftLegend
-- ^ @LEFT_LEGEND@
-- The legend is rendered on the left of the chart.
| BCSLPRightLegend
-- ^ @RIGHT_LEGEND@
-- The legend is rendered on the right of the chart.
| BCSLPTopLegend
-- ^ @TOP_LEGEND@
-- The legend is rendered on the top of the chart.
| BCSLPNoLegend
-- ^ @NO_LEGEND@
-- No legend is rendered.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BasicChartSpecLegendPosition
instance FromHttpApiData BasicChartSpecLegendPosition where
parseQueryParam = \case
"BASIC_CHART_LEGEND_POSITION_UNSPECIFIED" -> Right BCSLPBasicChartLegendPositionUnspecified
"BOTTOM_LEGEND" -> Right BCSLPBottomLegend
"LEFT_LEGEND" -> Right BCSLPLeftLegend
"RIGHT_LEGEND" -> Right BCSLPRightLegend
"TOP_LEGEND" -> Right BCSLPTopLegend
"NO_LEGEND" -> Right BCSLPNoLegend
x -> Left ("Unable to parse BasicChartSpecLegendPosition from: " <> x)
instance ToHttpApiData BasicChartSpecLegendPosition where
toQueryParam = \case
BCSLPBasicChartLegendPositionUnspecified -> "BASIC_CHART_LEGEND_POSITION_UNSPECIFIED"
BCSLPBottomLegend -> "BOTTOM_LEGEND"
BCSLPLeftLegend -> "LEFT_LEGEND"
BCSLPRightLegend -> "RIGHT_LEGEND"
BCSLPTopLegend -> "TOP_LEGEND"
BCSLPNoLegend -> "NO_LEGEND"
instance FromJSON BasicChartSpecLegendPosition where
parseJSON = parseJSONText "BasicChartSpecLegendPosition"
instance ToJSON BasicChartSpecLegendPosition where
toJSON = toJSONText
-- | The type of error.
data ErrorValueType
= ErrorTypeUnspecified
-- ^ @ERROR_TYPE_UNSPECIFIED@
-- The default error type, do not use this.
| Error'
-- ^ @ERROR@
-- Corresponds to the \`#ERROR!\` error.
| NullValue
-- ^ @NULL_VALUE@
-- Corresponds to the \`#NULL!\` error.
| DivideByZero
-- ^ @DIVIDE_BY_ZERO@
-- Corresponds to the \`#DIV\/0\` error.
| Value
-- ^ @VALUE@
-- Corresponds to the \`#VALUE!\` error.
| Ref
-- ^ @REF@
-- Corresponds to the \`#REF!\` error.
| Name
-- ^ @NAME@
-- Corresponds to the \`#NAME?\` error.
| Num
-- ^ @NUM@
-- Corresponds to the \`#NUM\`! error.
| NA
-- ^ @N_A@
-- Corresponds to the \`#N\/A\` error.
| Loading
-- ^ @LOADING@
-- Corresponds to the \`Loading...\` state.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ErrorValueType
instance FromHttpApiData ErrorValueType where
parseQueryParam = \case
"ERROR_TYPE_UNSPECIFIED" -> Right ErrorTypeUnspecified
"ERROR" -> Right Error'
"NULL_VALUE" -> Right NullValue
"DIVIDE_BY_ZERO" -> Right DivideByZero
"VALUE" -> Right Value
"REF" -> Right Ref
"NAME" -> Right Name
"NUM" -> Right Num
"N_A" -> Right NA
"LOADING" -> Right Loading
x -> Left ("Unable to parse ErrorValueType from: " <> x)
instance ToHttpApiData ErrorValueType where
toQueryParam = \case
ErrorTypeUnspecified -> "ERROR_TYPE_UNSPECIFIED"
Error' -> "ERROR"
NullValue -> "NULL_VALUE"
DivideByZero -> "DIVIDE_BY_ZERO"
Value -> "VALUE"
Ref -> "REF"
Name -> "NAME"
Num -> "NUM"
NA -> "N_A"
Loading -> "LOADING"
instance FromJSON ErrorValueType where
parseJSON = parseJSONText "ErrorValueType"
instance ToJSON ErrorValueType where
toJSON = toJSONText
-- | Whether values should be listed horizontally (as columns) or vertically
-- (as rows).
data PivotTableValueLayout
= Horizontal
-- ^ @HORIZONTAL@
-- Values are laid out horizontally (as columns).
| Vertical
-- ^ @VERTICAL@
-- Values are laid out vertically (as rows).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PivotTableValueLayout
instance FromHttpApiData PivotTableValueLayout where
parseQueryParam = \case
"HORIZONTAL" -> Right Horizontal
"VERTICAL" -> Right Vertical
x -> Left ("Unable to parse PivotTableValueLayout from: " <> x)
instance ToHttpApiData PivotTableValueLayout where
toQueryParam = \case
Horizontal -> "HORIZONTAL"
Vertical -> "VERTICAL"
instance FromJSON PivotTableValueLayout where
parseJSON = parseJSONText "PivotTableValueLayout"
instance ToJSON PivotTableValueLayout where
toJSON = toJSONText
-- | How the value should be interpreted.
data InterpolationPointType
= IPTInterpolationPointTypeUnspecified
-- ^ @INTERPOLATION_POINT_TYPE_UNSPECIFIED@
-- The default value, do not use.
| IPTMin
-- ^ @MIN@
-- The interpolation point will use the minimum value in the cells over the
-- range of the conditional format.
| IPTMax
-- ^ @MAX@
-- The interpolation point will use the maximum value in the cells over the
-- range of the conditional format.
| IPTNumber
-- ^ @NUMBER@
-- The interpolation point will use exactly the value in
-- InterpolationPoint.value.
| IPTPercent
-- ^ @PERCENT@
-- The interpolation point will be the given percentage over all the cells
-- in the range of the conditional format. This is equivalent to NUMBER if
-- the value was: \`=(MAX(FLATTEN(range)) * (value \/ 100)) +
-- (MIN(FLATTEN(range)) * (1 - (value \/ 100)))\` (where errors in the
-- range are ignored when flattening).
| IPTPercentile
-- ^ @PERCENTILE@
-- The interpolation point will be the given percentile over all the cells
-- in the range of the conditional format. This is equivalent to NUMBER if
-- the value was: \`=PERCENTILE(FLATTEN(range), value \/ 100)\` (where
-- errors in the range are ignored when flattening).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InterpolationPointType
instance FromHttpApiData InterpolationPointType where
parseQueryParam = \case
"INTERPOLATION_POINT_TYPE_UNSPECIFIED" -> Right IPTInterpolationPointTypeUnspecified
"MIN" -> Right IPTMin
"MAX" -> Right IPTMax
"NUMBER" -> Right IPTNumber
"PERCENT" -> Right IPTPercent
"PERCENTILE" -> Right IPTPercentile
x -> Left ("Unable to parse InterpolationPointType from: " <> x)
instance ToHttpApiData InterpolationPointType where
toQueryParam = \case
IPTInterpolationPointTypeUnspecified -> "INTERPOLATION_POINT_TYPE_UNSPECIFIED"
IPTMin -> "MIN"
IPTMax -> "MAX"
IPTNumber -> "NUMBER"
IPTPercent -> "PERCENT"
IPTPercentile -> "PERCENTILE"
instance FromJSON InterpolationPointType where
parseJSON = parseJSONText "InterpolationPointType"
instance ToJSON InterpolationPointType where
toJSON = toJSONText
-- | The delimiter type to use.
data TextToColumnsRequestDelimiterType
= TTCRDTDelimiterTypeUnspecified
-- ^ @DELIMITER_TYPE_UNSPECIFIED@
-- Default value. This value must not be used.
| TTCRDTComma
-- ^ @COMMA@
-- \",\"
| TTCRDTSemicolon
-- ^ @SEMICOLON@
-- \";\"
| TTCRDTPeriod
-- ^ @PERIOD@
-- \".\"
| TTCRDTSpace
-- ^ @SPACE@
-- \" \"
| TTCRDTCustom
-- ^ @CUSTOM@
-- A custom value as defined in delimiter.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TextToColumnsRequestDelimiterType
instance FromHttpApiData TextToColumnsRequestDelimiterType where
parseQueryParam = \case
"DELIMITER_TYPE_UNSPECIFIED" -> Right TTCRDTDelimiterTypeUnspecified
"COMMA" -> Right TTCRDTComma
"SEMICOLON" -> Right TTCRDTSemicolon
"PERIOD" -> Right TTCRDTPeriod
"SPACE" -> Right TTCRDTSpace
"CUSTOM" -> Right TTCRDTCustom
x -> Left ("Unable to parse TextToColumnsRequestDelimiterType from: " <> x)
instance ToHttpApiData TextToColumnsRequestDelimiterType where
toQueryParam = \case
TTCRDTDelimiterTypeUnspecified -> "DELIMITER_TYPE_UNSPECIFIED"
TTCRDTComma -> "COMMA"
TTCRDTSemicolon -> "SEMICOLON"
TTCRDTPeriod -> "PERIOD"
TTCRDTSpace -> "SPACE"
TTCRDTCustom -> "CUSTOM"
instance FromJSON TextToColumnsRequestDelimiterType where
parseJSON = parseJSONText "TextToColumnsRequestDelimiterType"
instance ToJSON TextToColumnsRequestDelimiterType where
toJSON = toJSONText
-- | The dimension which will be shifted when inserting cells. If ROWS,
-- existing cells will be shifted down. If COLUMNS, existing cells will be
-- shifted right.
data InsertRangeRequestShiftDimension
= IRRSDDimensionUnspecified
-- ^ @DIMENSION_UNSPECIFIED@
-- The default value, do not use.
| IRRSDRows
-- ^ @ROWS@
-- Operates on the rows of a sheet.
| IRRSDColumns
-- ^ @COLUMNS@
-- Operates on the columns of a sheet.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InsertRangeRequestShiftDimension
instance FromHttpApiData InsertRangeRequestShiftDimension where
parseQueryParam = \case
"DIMENSION_UNSPECIFIED" -> Right IRRSDDimensionUnspecified
"ROWS" -> Right IRRSDRows
"COLUMNS" -> Right IRRSDColumns
x -> Left ("Unable to parse InsertRangeRequestShiftDimension from: " <> x)
instance ToHttpApiData InsertRangeRequestShiftDimension where
toQueryParam = \case
IRRSDDimensionUnspecified -> "DIMENSION_UNSPECIFIED"
IRRSDRows -> "ROWS"
IRRSDColumns -> "COLUMNS"
instance FromJSON InsertRangeRequestShiftDimension where
parseJSON = parseJSONText "InsertRangeRequestShiftDimension"
instance ToJSON InsertRangeRequestShiftDimension where
toJSON = toJSONText
| rueshyna/gogol | gogol-sheets/gen/Network/Google/Sheets/Types/Sum.hs | mpl-2.0 | 74,088 | 0 | 11 | 17,344 | 9,399 | 5,073 | 4,326 | 1,142 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Spanner.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Spanner.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | Required. The TypeCode for this type.
data TypeCode
= TypeCodeUnspecified
-- ^ @TYPE_CODE_UNSPECIFIED@
-- Not specified.
| Bool
-- ^ @BOOL@
-- Encoded as JSON \`true\` or \`false\`.
| INT64
-- ^ @INT64@
-- Encoded as \`string\`, in decimal format.
| FLOAT64
-- ^ @FLOAT64@
-- Encoded as \`number\`, or the strings \`\"NaN\"\`, \`\"Infinity\"\`, or
-- \`\"-Infinity\"\`.
| Timestamp
-- ^ @TIMESTAMP@
-- Encoded as \`string\` in RFC 3339 timestamp format. The time zone must
-- be present, and must be \`\"Z\"\`. If the schema has the column option
-- \`allow_commit_timestamp=true\`, the placeholder string
-- \`\"spanner.commit_timestamp()\"\` can be used to instruct the system to
-- insert the commit timestamp associated with the transaction commit.
| Date
-- ^ @DATE@
-- Encoded as \`string\` in RFC 3339 date format.
| String
-- ^ @STRING@
-- Encoded as \`string\`.
| Bytes
-- ^ @BYTES@
-- Encoded as a base64-encoded \`string\`, as described in RFC 4648,
-- section 4.
| Array
-- ^ @ARRAY@
-- Encoded as \`list\`, where the list elements are represented according
-- to array_element_type.
| Struct
-- ^ @STRUCT@
-- Encoded as \`list\`, where list element \`i\` is represented according
-- to [struct_type.fields[i]][google.spanner.v1.StructType.fields].
| Numeric
-- ^ @NUMERIC@
-- Encoded as \`string\`, in decimal format or scientific notation format.
-- Decimal format: \`[+-]Digits[.[Digits]]\` or \`+-.Digits\` Scientific
-- notation: \`[+-]Digits[.[Digits]][ExponentIndicator[+-]Digits]\` or
-- \`+-.Digits[ExponentIndicator[+-]Digits]\` (ExponentIndicator is
-- \`\"e\"\` or \`\"E\"\`)
| JSON
-- ^ @JSON@
-- Encoded as a JSON-formatted \'string\' as described in RFC 7159. The
-- following rules will be applied when parsing JSON input: - Whitespace
-- will be stripped from the document. - If a JSON object has duplicate
-- keys, only the first key will be preserved. - Members of a JSON object
-- are not guaranteed to have their order preserved. JSON array elements
-- will have their order preserved.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TypeCode
instance FromHttpApiData TypeCode where
parseQueryParam = \case
"TYPE_CODE_UNSPECIFIED" -> Right TypeCodeUnspecified
"BOOL" -> Right Bool
"INT64" -> Right INT64
"FLOAT64" -> Right FLOAT64
"TIMESTAMP" -> Right Timestamp
"DATE" -> Right Date
"STRING" -> Right String
"BYTES" -> Right Bytes
"ARRAY" -> Right Array
"STRUCT" -> Right Struct
"NUMERIC" -> Right Numeric
"JSON" -> Right JSON
x -> Left ("Unable to parse TypeCode from: " <> x)
instance ToHttpApiData TypeCode where
toQueryParam = \case
TypeCodeUnspecified -> "TYPE_CODE_UNSPECIFIED"
Bool -> "BOOL"
INT64 -> "INT64"
FLOAT64 -> "FLOAT64"
Timestamp -> "TIMESTAMP"
Date -> "DATE"
String -> "STRING"
Bytes -> "BYTES"
Array -> "ARRAY"
Struct -> "STRUCT"
Numeric -> "NUMERIC"
JSON -> "JSON"
instance FromJSON TypeCode where
parseJSON = parseJSONText "TypeCode"
instance ToJSON TypeCode where
toJSON = toJSONText
-- | Specifies which parts of the Scan should be returned in the response.
-- Note, if left unspecified, the FULL view is assumed.
data ProjectsInstancesDatabasesGetScansView
= ViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Not specified, equivalent to SUMMARY.
| Summary
-- ^ @SUMMARY@
-- Server responses only include \`name\`, \`details\`, \`start_time\` and
-- \`end_time\`. The default value. Note, the ListScans method may only use
-- this view type, others view types are not supported.
| Full
-- ^ @FULL@
-- Full representation of the scan is returned in the server response,
-- including \`data\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsInstancesDatabasesGetScansView
instance FromHttpApiData ProjectsInstancesDatabasesGetScansView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right ViewUnspecified
"SUMMARY" -> Right Summary
"FULL" -> Right Full
x -> Left ("Unable to parse ProjectsInstancesDatabasesGetScansView from: " <> x)
instance ToHttpApiData ProjectsInstancesDatabasesGetScansView where
toQueryParam = \case
ViewUnspecified -> "VIEW_UNSPECIFIED"
Summary -> "SUMMARY"
Full -> "FULL"
instance FromJSON ProjectsInstancesDatabasesGetScansView where
parseJSON = parseJSONText "ProjectsInstancesDatabasesGetScansView"
instance ToJSON ProjectsInstancesDatabasesGetScansView where
toJSON = toJSONText
-- | The aggregation function used to aggregate each key bucket
data MetricAggregation
= AggregationUnspecified
-- ^ @AGGREGATION_UNSPECIFIED@
-- Required default value.
| Max
-- ^ @MAX@
-- Use the maximum of all values.
| Sum
-- ^ @SUM@
-- Use the sum of all values.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable MetricAggregation
instance FromHttpApiData MetricAggregation where
parseQueryParam = \case
"AGGREGATION_UNSPECIFIED" -> Right AggregationUnspecified
"MAX" -> Right Max
"SUM" -> Right Sum
x -> Left ("Unable to parse MetricAggregation from: " <> x)
instance ToHttpApiData MetricAggregation where
toQueryParam = \case
AggregationUnspecified -> "AGGREGATION_UNSPECIFIED"
Max -> "MAX"
Sum -> "SUM"
instance FromJSON MetricAggregation where
parseJSON = parseJSONText "MetricAggregation"
instance ToJSON MetricAggregation where
toJSON = toJSONText
-- | The type of the restore source.
data RestoreInfoSourceType
= RISTTypeUnspecified
-- ^ @TYPE_UNSPECIFIED@
-- No restore associated.
| RISTBackup
-- ^ @BACKUP@
-- A backup was used as the source of the restore.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RestoreInfoSourceType
instance FromHttpApiData RestoreInfoSourceType where
parseQueryParam = \case
"TYPE_UNSPECIFIED" -> Right RISTTypeUnspecified
"BACKUP" -> Right RISTBackup
x -> Left ("Unable to parse RestoreInfoSourceType from: " <> x)
instance ToHttpApiData RestoreInfoSourceType where
toQueryParam = \case
RISTTypeUnspecified -> "TYPE_UNSPECIFIED"
RISTBackup -> "BACKUP"
instance FromJSON RestoreInfoSourceType where
parseJSON = parseJSONText "RestoreInfoSourceType"
instance ToJSON RestoreInfoSourceType where
toJSON = toJSONText
-- | Used to determine the type of node. May be needed for visualizing
-- different kinds of nodes differently. For example, If the node is a
-- SCALAR node, it will have a condensed representation which can be used
-- to directly embed a description of the node in its parent.
data PlanNodeKind
= KindUnspecified
-- ^ @KIND_UNSPECIFIED@
-- Not specified.
| Relational
-- ^ @RELATIONAL@
-- Denotes a Relational operator node in the expression tree. Relational
-- operators represent iterative processing of rows during query execution.
-- For example, a \`TableScan\` operation that reads rows from a table.
| Scalar
-- ^ @SCALAR@
-- Denotes a Scalar node in the expression tree. Scalar nodes represent
-- non-iterable entities in the query plan. For example, constants or
-- arithmetic operators appearing inside predicate expressions or
-- references to column names.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PlanNodeKind
instance FromHttpApiData PlanNodeKind where
parseQueryParam = \case
"KIND_UNSPECIFIED" -> Right KindUnspecified
"RELATIONAL" -> Right Relational
"SCALAR" -> Right Scalar
x -> Left ("Unable to parse PlanNodeKind from: " <> x)
instance ToHttpApiData PlanNodeKind where
toQueryParam = \case
KindUnspecified -> "KIND_UNSPECIFIED"
Relational -> "RELATIONAL"
Scalar -> "SCALAR"
instance FromJSON PlanNodeKind where
parseJSON = parseJSONText "PlanNodeKind"
instance ToJSON PlanNodeKind where
toJSON = toJSONText
-- | The unit for the key: e.g. \'key\' or \'chunk\'.
data VisualizationDataKeyUnit
= KeyUnitUnspecified
-- ^ @KEY_UNIT_UNSPECIFIED@
-- Required default value
| Key
-- ^ @KEY@
-- Each entry corresponds to one key
| Chunk
-- ^ @CHUNK@
-- Each entry corresponds to a chunk of keys
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable VisualizationDataKeyUnit
instance FromHttpApiData VisualizationDataKeyUnit where
parseQueryParam = \case
"KEY_UNIT_UNSPECIFIED" -> Right KeyUnitUnspecified
"KEY" -> Right Key
"CHUNK" -> Right Chunk
x -> Left ("Unable to parse VisualizationDataKeyUnit from: " <> x)
instance ToHttpApiData VisualizationDataKeyUnit where
toQueryParam = \case
KeyUnitUnspecified -> "KEY_UNIT_UNSPECIFIED"
Key -> "KEY"
Chunk -> "CHUNK"
instance FromJSON VisualizationDataKeyUnit where
parseJSON = parseJSONText "VisualizationDataKeyUnit"
instance ToJSON VisualizationDataKeyUnit where
toJSON = toJSONText
-- | Specifies which parts of the Scan should be returned in the response.
-- Note, only the SUMMARY view (the default) is currently supported for
-- ListScans.
data ScansListView
= SLVViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Not specified, equivalent to SUMMARY.
| SLVSummary
-- ^ @SUMMARY@
-- Server responses only include \`name\`, \`details\`, \`start_time\` and
-- \`end_time\`. The default value. Note, the ListScans method may only use
-- this view type, others view types are not supported.
| SLVFull
-- ^ @FULL@
-- Full representation of the scan is returned in the server response,
-- including \`data\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScansListView
instance FromHttpApiData ScansListView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right SLVViewUnspecified
"SUMMARY" -> Right SLVSummary
"FULL" -> Right SLVFull
x -> Left ("Unable to parse ScansListView from: " <> x)
instance ToHttpApiData ScansListView where
toQueryParam = \case
SLVViewUnspecified -> "VIEW_UNSPECIFIED"
SLVSummary -> "SUMMARY"
SLVFull -> "FULL"
instance FromJSON ScansListView where
parseJSON = parseJSONText "ScansListView"
instance ToJSON ScansListView where
toJSON = toJSONText
-- | Output only. The type of encryption.
data EncryptionInfoEncryptionType
= TypeUnspecified
-- ^ @TYPE_UNSPECIFIED@
-- Encryption type was not specified, though data at rest remains
-- encrypted.
| GoogleDefaultEncryption
-- ^ @GOOGLE_DEFAULT_ENCRYPTION@
-- The data is encrypted at rest with a key that is fully managed by
-- Google. No key version or status will be populated. This is the default
-- state.
| CustomerManagedEncryption
-- ^ @CUSTOMER_MANAGED_ENCRYPTION@
-- The data is encrypted at rest with a key that is managed by the
-- customer. The active version of the key. \`kms_key_version\` will be
-- populated, and \`encryption_status\` may be populated.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable EncryptionInfoEncryptionType
instance FromHttpApiData EncryptionInfoEncryptionType where
parseQueryParam = \case
"TYPE_UNSPECIFIED" -> Right TypeUnspecified
"GOOGLE_DEFAULT_ENCRYPTION" -> Right GoogleDefaultEncryption
"CUSTOMER_MANAGED_ENCRYPTION" -> Right CustomerManagedEncryption
x -> Left ("Unable to parse EncryptionInfoEncryptionType from: " <> x)
instance ToHttpApiData EncryptionInfoEncryptionType where
toQueryParam = \case
TypeUnspecified -> "TYPE_UNSPECIFIED"
GoogleDefaultEncryption -> "GOOGLE_DEFAULT_ENCRYPTION"
CustomerManagedEncryption -> "CUSTOMER_MANAGED_ENCRYPTION"
instance FromJSON EncryptionInfoEncryptionType where
parseJSON = parseJSONText "EncryptionInfoEncryptionType"
instance ToJSON EncryptionInfoEncryptionType where
toJSON = toJSONText
-- | The type of replica.
data ReplicaInfoType
= RITTypeUnspecified
-- ^ @TYPE_UNSPECIFIED@
-- Not specified.
| RITReadWrite
-- ^ @READ_WRITE@
-- Read-write replicas support both reads and writes. These replicas: *
-- Maintain a full copy of your data. * Serve reads. * Can vote whether to
-- commit a write. * Participate in leadership election. * Are eligible to
-- become a leader.
| RITReadOnly
-- ^ @READ_ONLY@
-- Read-only replicas only support reads (not writes). Read-only replicas:
-- * Maintain a full copy of your data. * Serve reads. * Do not participate
-- in voting to commit writes. * Are not eligible to become a leader.
| RITWitness
-- ^ @WITNESS@
-- Witness replicas don\'t support reads but do participate in voting to
-- commit writes. Witness replicas: * Do not maintain a full copy of data.
-- * Do not serve reads. * Vote whether to commit writes. * Participate in
-- leader election but are not eligible to become leader.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ReplicaInfoType
instance FromHttpApiData ReplicaInfoType where
parseQueryParam = \case
"TYPE_UNSPECIFIED" -> Right RITTypeUnspecified
"READ_WRITE" -> Right RITReadWrite
"READ_ONLY" -> Right RITReadOnly
"WITNESS" -> Right RITWitness
x -> Left ("Unable to parse ReplicaInfoType from: " <> x)
instance ToHttpApiData ReplicaInfoType where
toQueryParam = \case
RITTypeUnspecified -> "TYPE_UNSPECIFIED"
RITReadWrite -> "READ_WRITE"
RITReadOnly -> "READ_ONLY"
RITWitness -> "WITNESS"
instance FromJSON ReplicaInfoType where
parseJSON = parseJSONText "ReplicaInfoType"
instance ToJSON ReplicaInfoType where
toJSON = toJSONText
-- | Used to control the amount of debugging information returned in
-- ResultSetStats. If partition_token is set, query_mode can only be set to
-- QueryMode.NORMAL.
data ExecuteSQLRequestQueryMode
= Normal
-- ^ @NORMAL@
-- The default mode. Only the statement results are returned.
| Plan
-- ^ @PLAN@
-- This mode returns only the query plan, without any results or execution
-- statistics information.
| ProFile
-- ^ @PROFILE@
-- This mode returns both the query plan and the execution statistics along
-- with the results.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ExecuteSQLRequestQueryMode
instance FromHttpApiData ExecuteSQLRequestQueryMode where
parseQueryParam = \case
"NORMAL" -> Right Normal
"PLAN" -> Right Plan
"PROFILE" -> Right ProFile
x -> Left ("Unable to parse ExecuteSQLRequestQueryMode from: " <> x)
instance ToHttpApiData ExecuteSQLRequestQueryMode where
toQueryParam = \case
Normal -> "NORMAL"
Plan -> "PLAN"
ProFile -> "PROFILE"
instance FromJSON ExecuteSQLRequestQueryMode where
parseJSON = parseJSONText "ExecuteSQLRequestQueryMode"
instance ToJSON ExecuteSQLRequestQueryMode where
toJSON = toJSONText
-- | The severity of the diagnostic message.
data DiagnosticMessageSeverity
= SeverityUnspecified
-- ^ @SEVERITY_UNSPECIFIED@
-- Required default value.
| Info
-- ^ @INFO@
-- Lowest severity level \"Info\".
| Warning
-- ^ @WARNING@
-- Middle severity level \"Warning\".
| Error'
-- ^ @ERROR@
-- Severity level signaling an error \"Error\"
| Fatal
-- ^ @FATAL@
-- Severity level signaling a non recoverable error \"Fatal\"
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DiagnosticMessageSeverity
instance FromHttpApiData DiagnosticMessageSeverity where
parseQueryParam = \case
"SEVERITY_UNSPECIFIED" -> Right SeverityUnspecified
"INFO" -> Right Info
"WARNING" -> Right Warning
"ERROR" -> Right Error'
"FATAL" -> Right Fatal
x -> Left ("Unable to parse DiagnosticMessageSeverity from: " <> x)
instance ToHttpApiData DiagnosticMessageSeverity where
toQueryParam = \case
SeverityUnspecified -> "SEVERITY_UNSPECIFIED"
Info -> "INFO"
Warning -> "WARNING"
Error' -> "ERROR"
Fatal -> "FATAL"
instance FromJSON DiagnosticMessageSeverity where
parseJSON = parseJSONText "DiagnosticMessageSeverity"
instance ToJSON DiagnosticMessageSeverity where
toJSON = toJSONText
-- | The severity of this context.
data ContextValueSeverity
= CVSSeverityUnspecified
-- ^ @SEVERITY_UNSPECIFIED@
-- Required default value.
| CVSInfo
-- ^ @INFO@
-- Lowest severity level \"Info\".
| CVSWarning
-- ^ @WARNING@
-- Middle severity level \"Warning\".
| CVSError'
-- ^ @ERROR@
-- Severity level signaling an error \"Error\"
| CVSFatal
-- ^ @FATAL@
-- Severity level signaling a non recoverable error \"Fatal\"
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ContextValueSeverity
instance FromHttpApiData ContextValueSeverity where
parseQueryParam = \case
"SEVERITY_UNSPECIFIED" -> Right CVSSeverityUnspecified
"INFO" -> Right CVSInfo
"WARNING" -> Right CVSWarning
"ERROR" -> Right CVSError'
"FATAL" -> Right CVSFatal
x -> Left ("Unable to parse ContextValueSeverity from: " <> x)
instance ToHttpApiData ContextValueSeverity where
toQueryParam = \case
CVSSeverityUnspecified -> "SEVERITY_UNSPECIFIED"
CVSInfo -> "INFO"
CVSWarning -> "WARNING"
CVSError' -> "ERROR"
CVSFatal -> "FATAL"
instance FromJSON ContextValueSeverity where
parseJSON = parseJSONText "ContextValueSeverity"
instance ToJSON ContextValueSeverity where
toJSON = toJSONText
-- | Required. The encryption type of the restored database.
data RestoreDatabaseEncryptionConfigEncryptionType
= RDECETEncryptionTypeUnspecified
-- ^ @ENCRYPTION_TYPE_UNSPECIFIED@
-- Unspecified. Do not use.
| RDECETUseConfigDefaultOrBackupEncryption
-- ^ @USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION@
-- This is the default option when encryption_config is not specified.
| RDECETGoogleDefaultEncryption
-- ^ @GOOGLE_DEFAULT_ENCRYPTION@
-- Use Google default encryption.
| RDECETCustomerManagedEncryption
-- ^ @CUSTOMER_MANAGED_ENCRYPTION@
-- Use customer managed encryption. If specified, \`kms_key_name\` must
-- must contain a valid Cloud KMS key.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RestoreDatabaseEncryptionConfigEncryptionType
instance FromHttpApiData RestoreDatabaseEncryptionConfigEncryptionType where
parseQueryParam = \case
"ENCRYPTION_TYPE_UNSPECIFIED" -> Right RDECETEncryptionTypeUnspecified
"USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION" -> Right RDECETUseConfigDefaultOrBackupEncryption
"GOOGLE_DEFAULT_ENCRYPTION" -> Right RDECETGoogleDefaultEncryption
"CUSTOMER_MANAGED_ENCRYPTION" -> Right RDECETCustomerManagedEncryption
x -> Left ("Unable to parse RestoreDatabaseEncryptionConfigEncryptionType from: " <> x)
instance ToHttpApiData RestoreDatabaseEncryptionConfigEncryptionType where
toQueryParam = \case
RDECETEncryptionTypeUnspecified -> "ENCRYPTION_TYPE_UNSPECIFIED"
RDECETUseConfigDefaultOrBackupEncryption -> "USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION"
RDECETGoogleDefaultEncryption -> "GOOGLE_DEFAULT_ENCRYPTION"
RDECETCustomerManagedEncryption -> "CUSTOMER_MANAGED_ENCRYPTION"
instance FromJSON RestoreDatabaseEncryptionConfigEncryptionType where
parseJSON = parseJSONText "RestoreDatabaseEncryptionConfigEncryptionType"
instance ToJSON RestoreDatabaseEncryptionConfigEncryptionType where
toJSON = toJSONText
-- | Required. The encryption type of the backup.
data ProjectsInstancesBackupsCreateEncryptionConfigEncryptionType
= PIBCECETEncryptionTypeUnspecified
-- ^ @ENCRYPTION_TYPE_UNSPECIFIED@
-- Unspecified. Do not use.
| PIBCECETUseDatabaseEncryption
-- ^ @USE_DATABASE_ENCRYPTION@
-- Use the same encryption configuration as the database. This is the
-- default option when encryption_config is empty. For example, if the
-- database is using \`Customer_Managed_Encryption\`, the backup will be
-- using the same Cloud KMS key as the database.
| PIBCECETGoogleDefaultEncryption
-- ^ @GOOGLE_DEFAULT_ENCRYPTION@
-- Use Google default encryption.
| PIBCECETCustomerManagedEncryption
-- ^ @CUSTOMER_MANAGED_ENCRYPTION@
-- Use customer managed encryption. If specified, \`kms_key_name\` must
-- contain a valid Cloud KMS key.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsInstancesBackupsCreateEncryptionConfigEncryptionType
instance FromHttpApiData ProjectsInstancesBackupsCreateEncryptionConfigEncryptionType where
parseQueryParam = \case
"ENCRYPTION_TYPE_UNSPECIFIED" -> Right PIBCECETEncryptionTypeUnspecified
"USE_DATABASE_ENCRYPTION" -> Right PIBCECETUseDatabaseEncryption
"GOOGLE_DEFAULT_ENCRYPTION" -> Right PIBCECETGoogleDefaultEncryption
"CUSTOMER_MANAGED_ENCRYPTION" -> Right PIBCECETCustomerManagedEncryption
x -> Left ("Unable to parse ProjectsInstancesBackupsCreateEncryptionConfigEncryptionType from: " <> x)
instance ToHttpApiData ProjectsInstancesBackupsCreateEncryptionConfigEncryptionType where
toQueryParam = \case
PIBCECETEncryptionTypeUnspecified -> "ENCRYPTION_TYPE_UNSPECIFIED"
PIBCECETUseDatabaseEncryption -> "USE_DATABASE_ENCRYPTION"
PIBCECETGoogleDefaultEncryption -> "GOOGLE_DEFAULT_ENCRYPTION"
PIBCECETCustomerManagedEncryption -> "CUSTOMER_MANAGED_ENCRYPTION"
instance FromJSON ProjectsInstancesBackupsCreateEncryptionConfigEncryptionType where
parseJSON = parseJSONText "ProjectsInstancesBackupsCreateEncryptionConfigEncryptionType"
instance ToJSON ProjectsInstancesBackupsCreateEncryptionConfigEncryptionType where
toJSON = toJSONText
-- | Output only. The current database state.
data DatabaseState
= StateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Not specified.
| Creating
-- ^ @CREATING@
-- The database is still being created. Operations on the database may fail
-- with \`FAILED_PRECONDITION\` in this state.
| Ready
-- ^ @READY@
-- The database is fully created and ready for use.
| ReadyOptimizing
-- ^ @READY_OPTIMIZING@
-- The database is fully created and ready for use, but is still being
-- optimized for performance and cannot handle full load. In this state,
-- the database still references the backup it was restore from, preventing
-- the backup from being deleted. When optimizations are complete, the full
-- performance of the database will be restored, and the database will
-- transition to \`READY\` state.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DatabaseState
instance FromHttpApiData DatabaseState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right StateUnspecified
"CREATING" -> Right Creating
"READY" -> Right Ready
"READY_OPTIMIZING" -> Right ReadyOptimizing
x -> Left ("Unable to parse DatabaseState from: " <> x)
instance ToHttpApiData DatabaseState where
toQueryParam = \case
StateUnspecified -> "STATE_UNSPECIFIED"
Creating -> "CREATING"
Ready -> "READY"
ReadyOptimizing -> "READY_OPTIMIZING"
instance FromJSON DatabaseState where
parseJSON = parseJSONText "DatabaseState"
instance ToJSON DatabaseState where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | The type of the restore source.
data RestoreDatabaseMetadataSourceType
= RDMSTTypeUnspecified
-- ^ @TYPE_UNSPECIFIED@
-- No restore associated.
| RDMSTBackup
-- ^ @BACKUP@
-- A backup was used as the source of the restore.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RestoreDatabaseMetadataSourceType
instance FromHttpApiData RestoreDatabaseMetadataSourceType where
parseQueryParam = \case
"TYPE_UNSPECIFIED" -> Right RDMSTTypeUnspecified
"BACKUP" -> Right RDMSTBackup
x -> Left ("Unable to parse RestoreDatabaseMetadataSourceType from: " <> x)
instance ToHttpApiData RestoreDatabaseMetadataSourceType where
toQueryParam = \case
RDMSTTypeUnspecified -> "TYPE_UNSPECIFIED"
RDMSTBackup -> "BACKUP"
instance FromJSON RestoreDatabaseMetadataSourceType where
parseJSON = parseJSONText "RestoreDatabaseMetadataSourceType"
instance ToJSON RestoreDatabaseMetadataSourceType where
toJSON = toJSONText
-- | Priority for the request.
data RequestOptionsPriority
= PriorityUnspecified
-- ^ @PRIORITY_UNSPECIFIED@
-- \`PRIORITY_UNSPECIFIED\` is equivalent to \`PRIORITY_HIGH\`.
| PriorityLow
-- ^ @PRIORITY_LOW@
-- This specifies that the request is low priority.
| PriorityMedium
-- ^ @PRIORITY_MEDIUM@
-- This specifies that the request is medium priority.
| PriorityHigh
-- ^ @PRIORITY_HIGH@
-- This specifies that the request is high priority.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RequestOptionsPriority
instance FromHttpApiData RequestOptionsPriority where
parseQueryParam = \case
"PRIORITY_UNSPECIFIED" -> Right PriorityUnspecified
"PRIORITY_LOW" -> Right PriorityLow
"PRIORITY_MEDIUM" -> Right PriorityMedium
"PRIORITY_HIGH" -> Right PriorityHigh
x -> Left ("Unable to parse RequestOptionsPriority from: " <> x)
instance ToHttpApiData RequestOptionsPriority where
toQueryParam = \case
PriorityUnspecified -> "PRIORITY_UNSPECIFIED"
PriorityLow -> "PRIORITY_LOW"
PriorityMedium -> "PRIORITY_MEDIUM"
PriorityHigh -> "PRIORITY_HIGH"
instance FromJSON RequestOptionsPriority where
parseJSON = parseJSONText "RequestOptionsPriority"
instance ToJSON RequestOptionsPriority where
toJSON = toJSONText
-- | Output only. The current instance state. For CreateInstance, the state
-- must be either omitted or set to \`CREATING\`. For UpdateInstance, the
-- state must be either omitted or set to \`READY\`.
data InstanceState
= ISStateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Not specified.
| ISCreating
-- ^ @CREATING@
-- The instance is still being created. Resources may not be available yet,
-- and operations such as database creation may not work.
| ISReady
-- ^ @READY@
-- The instance is fully created and ready to do work such as creating
-- databases.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InstanceState
instance FromHttpApiData InstanceState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right ISStateUnspecified
"CREATING" -> Right ISCreating
"READY" -> Right ISReady
x -> Left ("Unable to parse InstanceState from: " <> x)
instance ToHttpApiData InstanceState where
toQueryParam = \case
ISStateUnspecified -> "STATE_UNSPECIFIED"
ISCreating -> "CREATING"
ISReady -> "READY"
instance FromJSON InstanceState where
parseJSON = parseJSONText "InstanceState"
instance ToJSON InstanceState where
toJSON = toJSONText
-- | Output only. The current state of the backup.
data BackupState
= BSStateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Not specified.
| BSCreating
-- ^ @CREATING@
-- The pending backup is still being created. Operations on the backup may
-- fail with \`FAILED_PRECONDITION\` in this state.
| BSReady
-- ^ @READY@
-- The backup is complete and ready for use.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BackupState
instance FromHttpApiData BackupState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right BSStateUnspecified
"CREATING" -> Right BSCreating
"READY" -> Right BSReady
x -> Left ("Unable to parse BackupState from: " <> x)
instance ToHttpApiData BackupState where
toQueryParam = \case
BSStateUnspecified -> "STATE_UNSPECIFIED"
BSCreating -> "CREATING"
BSReady -> "READY"
instance FromJSON BackupState where
parseJSON = parseJSONText "BackupState"
instance ToJSON BackupState where
toJSON = toJSONText
| brendanhay/gogol | gogol-spanner/gen/Network/Google/Spanner/Types/Sum.hs | mpl-2.0 | 30,700 | 0 | 11 | 6,949 | 4,042 | 2,181 | 1,861 | 473 | 0 |
module Opaleye.X
( module Opaleye.X.Aggregate
, module Opaleye.X.Array
, module Opaleye.X.Join
, module Opaleye.X.Maybe
, module Opaleye.X.Order
, module Opaleye.X.Optional
, module Opaleye.X.Table
, module Opaleye.X.TF
, module Opaleye.X.Transaction
)
where
-- opaleye-x -----------------------------------------------------------------
import Opaleye.X.Aggregate
import Opaleye.X.Array
import Opaleye.X.Join
import Opaleye.X.Maybe
import Opaleye.X.Order
import Opaleye.X.Optional
import Opaleye.X.Table
import Opaleye.X.TF
import Opaleye.X.Transaction
| duairc/opaleye-x | src/Opaleye/X.hs | mpl-2.0 | 685 | 0 | 5 | 183 | 126 | 87 | 39 | 19 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Translate.Projects.TranslateText
-- 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)
--
-- Translates input text and returns translated text.
--
-- /See:/ <https://cloud.google.com/translate/docs/quickstarts Cloud Translation API Reference> for @translate.projects.translateText@.
module Network.Google.Resource.Translate.Projects.TranslateText
(
-- * REST Resource
ProjectsTranslateTextResource
-- * Creating a Request
, projectsTranslateText
, ProjectsTranslateText
-- * Request Lenses
, pttParent
, pttXgafv
, pttUploadProtocol
, pttAccessToken
, pttUploadType
, pttPayload
, pttCallback
) where
import Network.Google.Prelude
import Network.Google.Translate.Types
-- | A resource alias for @translate.projects.translateText@ method which the
-- 'ProjectsTranslateText' request conforms to.
type ProjectsTranslateTextResource =
"v3" :>
CaptureMode "parent" "translateText" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TranslateTextRequest :>
Post '[JSON] TranslateTextResponse
-- | Translates input text and returns translated text.
--
-- /See:/ 'projectsTranslateText' smart constructor.
data ProjectsTranslateText =
ProjectsTranslateText'
{ _pttParent :: !Text
, _pttXgafv :: !(Maybe Xgafv)
, _pttUploadProtocol :: !(Maybe Text)
, _pttAccessToken :: !(Maybe Text)
, _pttUploadType :: !(Maybe Text)
, _pttPayload :: !TranslateTextRequest
, _pttCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsTranslateText' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pttParent'
--
-- * 'pttXgafv'
--
-- * 'pttUploadProtocol'
--
-- * 'pttAccessToken'
--
-- * 'pttUploadType'
--
-- * 'pttPayload'
--
-- * 'pttCallback'
projectsTranslateText
:: Text -- ^ 'pttParent'
-> TranslateTextRequest -- ^ 'pttPayload'
-> ProjectsTranslateText
projectsTranslateText pPttParent_ pPttPayload_ =
ProjectsTranslateText'
{ _pttParent = pPttParent_
, _pttXgafv = Nothing
, _pttUploadProtocol = Nothing
, _pttAccessToken = Nothing
, _pttUploadType = Nothing
, _pttPayload = pPttPayload_
, _pttCallback = Nothing
}
-- | Required. Project or location to make a call. Must refer to a caller\'s
-- project. Format: \`projects\/{project-number-or-id}\` or
-- \`projects\/{project-number-or-id}\/locations\/{location-id}\`. For
-- global calls, use
-- \`projects\/{project-number-or-id}\/locations\/global\` or
-- \`projects\/{project-number-or-id}\`. Non-global location is required
-- for requests using AutoML models or custom glossaries. Models and
-- glossaries must be within the same region (have same location-id),
-- otherwise an INVALID_ARGUMENT (400) error is returned.
pttParent :: Lens' ProjectsTranslateText Text
pttParent
= lens _pttParent (\ s a -> s{_pttParent = a})
-- | V1 error format.
pttXgafv :: Lens' ProjectsTranslateText (Maybe Xgafv)
pttXgafv = lens _pttXgafv (\ s a -> s{_pttXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pttUploadProtocol :: Lens' ProjectsTranslateText (Maybe Text)
pttUploadProtocol
= lens _pttUploadProtocol
(\ s a -> s{_pttUploadProtocol = a})
-- | OAuth access token.
pttAccessToken :: Lens' ProjectsTranslateText (Maybe Text)
pttAccessToken
= lens _pttAccessToken
(\ s a -> s{_pttAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pttUploadType :: Lens' ProjectsTranslateText (Maybe Text)
pttUploadType
= lens _pttUploadType
(\ s a -> s{_pttUploadType = a})
-- | Multipart request metadata.
pttPayload :: Lens' ProjectsTranslateText TranslateTextRequest
pttPayload
= lens _pttPayload (\ s a -> s{_pttPayload = a})
-- | JSONP
pttCallback :: Lens' ProjectsTranslateText (Maybe Text)
pttCallback
= lens _pttCallback (\ s a -> s{_pttCallback = a})
instance GoogleRequest ProjectsTranslateText where
type Rs ProjectsTranslateText = TranslateTextResponse
type Scopes ProjectsTranslateText =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-translation"]
requestClient ProjectsTranslateText'{..}
= go _pttParent _pttXgafv _pttUploadProtocol
_pttAccessToken
_pttUploadType
_pttCallback
(Just AltJSON)
_pttPayload
translateService
where go
= buildClient
(Proxy :: Proxy ProjectsTranslateTextResource)
mempty
| brendanhay/gogol | gogol-translate/gen/Network/Google/Resource/Translate/Projects/TranslateText.hs | mpl-2.0 | 5,673 | 0 | 16 | 1,226 | 787 | 462 | 325 | 114 | 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.Webmasters.Sitemaps.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a sitemap from this site.
--
-- /See:/ <https://developers.google.com/webmaster-tools/search-console-api/ Google Search Console API Reference> for @webmasters.sitemaps.delete@.
module Network.Google.Resource.Webmasters.Sitemaps.Delete
(
-- * REST Resource
SitemapsDeleteResource
-- * Creating a Request
, sitemapsDelete
, SitemapsDelete
-- * Request Lenses
, sdXgafv
, sdFeedpath
, sdUploadProtocol
, sdSiteURL
, sdAccessToken
, sdUploadType
, sdCallback
) where
import Network.Google.Prelude
import Network.Google.SearchConsole.Types
-- | A resource alias for @webmasters.sitemaps.delete@ method which the
-- 'SitemapsDelete' request conforms to.
type SitemapsDeleteResource =
"webmasters" :>
"v3" :>
"sites" :>
Capture "siteUrl" Text :>
"sitemaps" :>
Capture "feedpath" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a sitemap from this site.
--
-- /See:/ 'sitemapsDelete' smart constructor.
data SitemapsDelete =
SitemapsDelete'
{ _sdXgafv :: !(Maybe Xgafv)
, _sdFeedpath :: !Text
, _sdUploadProtocol :: !(Maybe Text)
, _sdSiteURL :: !Text
, _sdAccessToken :: !(Maybe Text)
, _sdUploadType :: !(Maybe Text)
, _sdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SitemapsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sdXgafv'
--
-- * 'sdFeedpath'
--
-- * 'sdUploadProtocol'
--
-- * 'sdSiteURL'
--
-- * 'sdAccessToken'
--
-- * 'sdUploadType'
--
-- * 'sdCallback'
sitemapsDelete
:: Text -- ^ 'sdFeedpath'
-> Text -- ^ 'sdSiteURL'
-> SitemapsDelete
sitemapsDelete pSdFeedpath_ pSdSiteURL_ =
SitemapsDelete'
{ _sdXgafv = Nothing
, _sdFeedpath = pSdFeedpath_
, _sdUploadProtocol = Nothing
, _sdSiteURL = pSdSiteURL_
, _sdAccessToken = Nothing
, _sdUploadType = Nothing
, _sdCallback = Nothing
}
-- | V1 error format.
sdXgafv :: Lens' SitemapsDelete (Maybe Xgafv)
sdXgafv = lens _sdXgafv (\ s a -> s{_sdXgafv = a})
-- | The URL of the actual sitemap. For example:
-- \`http:\/\/www.example.com\/sitemap.xml\`.
sdFeedpath :: Lens' SitemapsDelete Text
sdFeedpath
= lens _sdFeedpath (\ s a -> s{_sdFeedpath = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sdUploadProtocol :: Lens' SitemapsDelete (Maybe Text)
sdUploadProtocol
= lens _sdUploadProtocol
(\ s a -> s{_sdUploadProtocol = a})
-- | The site\'s URL, including protocol. For example:
-- \`http:\/\/www.example.com\/\`.
sdSiteURL :: Lens' SitemapsDelete Text
sdSiteURL
= lens _sdSiteURL (\ s a -> s{_sdSiteURL = a})
-- | OAuth access token.
sdAccessToken :: Lens' SitemapsDelete (Maybe Text)
sdAccessToken
= lens _sdAccessToken
(\ s a -> s{_sdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sdUploadType :: Lens' SitemapsDelete (Maybe Text)
sdUploadType
= lens _sdUploadType (\ s a -> s{_sdUploadType = a})
-- | JSONP
sdCallback :: Lens' SitemapsDelete (Maybe Text)
sdCallback
= lens _sdCallback (\ s a -> s{_sdCallback = a})
instance GoogleRequest SitemapsDelete where
type Rs SitemapsDelete = ()
type Scopes SitemapsDelete =
'["https://www.googleapis.com/auth/webmasters"]
requestClient SitemapsDelete'{..}
= go _sdSiteURL _sdFeedpath _sdXgafv
_sdUploadProtocol
_sdAccessToken
_sdUploadType
_sdCallback
(Just AltJSON)
searchConsoleService
where go
= buildClient (Proxy :: Proxy SitemapsDeleteResource)
mempty
| brendanhay/gogol | gogol-searchconsole/gen/Network/Google/Resource/Webmasters/Sitemaps/Delete.hs | mpl-2.0 | 4,889 | 0 | 19 | 1,190 | 787 | 458 | 329 | 113 | 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.DLP.Organizations.Locations.DeidentifyTemplates.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a DeidentifyTemplate. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates-deid to learn
-- more.
--
-- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.organizations.locations.deidentifyTemplates.get@.
module Network.Google.Resource.DLP.Organizations.Locations.DeidentifyTemplates.Get
(
-- * REST Resource
OrganizationsLocationsDeidentifyTemplatesGetResource
-- * Creating a Request
, organizationsLocationsDeidentifyTemplatesGet
, OrganizationsLocationsDeidentifyTemplatesGet
-- * Request Lenses
, oldtgXgafv
, oldtgUploadProtocol
, oldtgAccessToken
, oldtgUploadType
, oldtgName
, oldtgCallback
) where
import Network.Google.DLP.Types
import Network.Google.Prelude
-- | A resource alias for @dlp.organizations.locations.deidentifyTemplates.get@ method which the
-- 'OrganizationsLocationsDeidentifyTemplatesGet' request conforms to.
type OrganizationsLocationsDeidentifyTemplatesGetResource
=
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GooglePrivacyDlpV2DeidentifyTemplate
-- | Gets a DeidentifyTemplate. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates-deid to learn
-- more.
--
-- /See:/ 'organizationsLocationsDeidentifyTemplatesGet' smart constructor.
data OrganizationsLocationsDeidentifyTemplatesGet =
OrganizationsLocationsDeidentifyTemplatesGet'
{ _oldtgXgafv :: !(Maybe Xgafv)
, _oldtgUploadProtocol :: !(Maybe Text)
, _oldtgAccessToken :: !(Maybe Text)
, _oldtgUploadType :: !(Maybe Text)
, _oldtgName :: !Text
, _oldtgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrganizationsLocationsDeidentifyTemplatesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oldtgXgafv'
--
-- * 'oldtgUploadProtocol'
--
-- * 'oldtgAccessToken'
--
-- * 'oldtgUploadType'
--
-- * 'oldtgName'
--
-- * 'oldtgCallback'
organizationsLocationsDeidentifyTemplatesGet
:: Text -- ^ 'oldtgName'
-> OrganizationsLocationsDeidentifyTemplatesGet
organizationsLocationsDeidentifyTemplatesGet pOldtgName_ =
OrganizationsLocationsDeidentifyTemplatesGet'
{ _oldtgXgafv = Nothing
, _oldtgUploadProtocol = Nothing
, _oldtgAccessToken = Nothing
, _oldtgUploadType = Nothing
, _oldtgName = pOldtgName_
, _oldtgCallback = Nothing
}
-- | V1 error format.
oldtgXgafv :: Lens' OrganizationsLocationsDeidentifyTemplatesGet (Maybe Xgafv)
oldtgXgafv
= lens _oldtgXgafv (\ s a -> s{_oldtgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
oldtgUploadProtocol :: Lens' OrganizationsLocationsDeidentifyTemplatesGet (Maybe Text)
oldtgUploadProtocol
= lens _oldtgUploadProtocol
(\ s a -> s{_oldtgUploadProtocol = a})
-- | OAuth access token.
oldtgAccessToken :: Lens' OrganizationsLocationsDeidentifyTemplatesGet (Maybe Text)
oldtgAccessToken
= lens _oldtgAccessToken
(\ s a -> s{_oldtgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
oldtgUploadType :: Lens' OrganizationsLocationsDeidentifyTemplatesGet (Maybe Text)
oldtgUploadType
= lens _oldtgUploadType
(\ s a -> s{_oldtgUploadType = a})
-- | Required. Resource name of the organization and deidentify template to
-- be read, for example
-- \`organizations\/433245324\/deidentifyTemplates\/432452342\` or
-- projects\/project-id\/deidentifyTemplates\/432452342.
oldtgName :: Lens' OrganizationsLocationsDeidentifyTemplatesGet Text
oldtgName
= lens _oldtgName (\ s a -> s{_oldtgName = a})
-- | JSONP
oldtgCallback :: Lens' OrganizationsLocationsDeidentifyTemplatesGet (Maybe Text)
oldtgCallback
= lens _oldtgCallback
(\ s a -> s{_oldtgCallback = a})
instance GoogleRequest
OrganizationsLocationsDeidentifyTemplatesGet
where
type Rs OrganizationsLocationsDeidentifyTemplatesGet
= GooglePrivacyDlpV2DeidentifyTemplate
type Scopes
OrganizationsLocationsDeidentifyTemplatesGet
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
OrganizationsLocationsDeidentifyTemplatesGet'{..}
= go _oldtgName _oldtgXgafv _oldtgUploadProtocol
_oldtgAccessToken
_oldtgUploadType
_oldtgCallback
(Just AltJSON)
dLPService
where go
= buildClient
(Proxy ::
Proxy
OrganizationsLocationsDeidentifyTemplatesGetResource)
mempty
| brendanhay/gogol | gogol-dlp/gen/Network/Google/Resource/DLP/Organizations/Locations/DeidentifyTemplates/Get.hs | mpl-2.0 | 5,809 | 0 | 15 | 1,195 | 703 | 414 | 289 | 110 | 1 |
module Main (module Main) where
| lspitzner/brittany | data/Test136.hs | agpl-3.0 | 32 | 0 | 4 | 5 | 10 | 7 | 3 | 1 | 0 |
module Listener(
-- * Functions
listener
) where
import Control.Concurrent(forkIO)
import Network(PortNumber,PortID(PortNumber),withSocketsDo,listenOn)
import Network.Socket(Socket,accept)
-- | listener listens on the given port, accepting connections
-- to be handled by the given handler.
listener :: PortNumber -> (Socket -> IO ()) -> IO ()
listener port handler = withSocketsDo $ do
socket <- listenOn (PortNumber port)
sequence_ $ repeat $ accept socket >>= (forkIO . handler . fst)
| qpliu/lecache | hs/Listener.hs | lgpl-3.0 | 510 | 0 | 11 | 89 | 145 | 80 | 65 | 9 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionTabV2.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:16
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionTabV2 (
QqStyleOptionTabV2(..)
,QqStyleOptionTabV2_nf(..)
,qStyleOptionTabV2_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStyleOptionTabV2 x1 where
qStyleOptionTabV2 :: x1 -> IO (QStyleOptionTabV2 ())
instance QqStyleOptionTabV2 (()) where
qStyleOptionTabV2 ()
= withQStyleOptionTabV2Result $
qtc_QStyleOptionTabV2
foreign import ccall "qtc_QStyleOptionTabV2" qtc_QStyleOptionTabV2 :: IO (Ptr (TQStyleOptionTabV2 ()))
instance QqStyleOptionTabV2 ((QStyleOptionTab t1)) where
qStyleOptionTabV2 (x1)
= withQStyleOptionTabV2Result $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabV21 cobj_x1
foreign import ccall "qtc_QStyleOptionTabV21" qtc_QStyleOptionTabV21 :: Ptr (TQStyleOptionTab t1) -> IO (Ptr (TQStyleOptionTabV2 ()))
instance QqStyleOptionTabV2 ((QStyleOptionTabV2 t1)) where
qStyleOptionTabV2 (x1)
= withQStyleOptionTabV2Result $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabV22 cobj_x1
foreign import ccall "qtc_QStyleOptionTabV22" qtc_QStyleOptionTabV22 :: Ptr (TQStyleOptionTabV2 t1) -> IO (Ptr (TQStyleOptionTabV2 ()))
class QqStyleOptionTabV2_nf x1 where
qStyleOptionTabV2_nf :: x1 -> IO (QStyleOptionTabV2 ())
instance QqStyleOptionTabV2_nf (()) where
qStyleOptionTabV2_nf ()
= withObjectRefResult $
qtc_QStyleOptionTabV2
instance QqStyleOptionTabV2_nf ((QStyleOptionTab t1)) where
qStyleOptionTabV2_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabV21 cobj_x1
instance QqStyleOptionTabV2_nf ((QStyleOptionTabV2 t1)) where
qStyleOptionTabV2_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabV22 cobj_x1
instance QqiconSize (QStyleOptionTabV2 a) (()) where
qiconSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabV2_iconSize cobj_x0
foreign import ccall "qtc_QStyleOptionTabV2_iconSize" qtc_QStyleOptionTabV2_iconSize :: Ptr (TQStyleOptionTabV2 a) -> IO (Ptr (TQSize ()))
instance QiconSize (QStyleOptionTabV2 a) (()) where
iconSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabV2_iconSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QStyleOptionTabV2_iconSize_qth" qtc_QStyleOptionTabV2_iconSize_qth :: Ptr (TQStyleOptionTabV2 a) -> Ptr CInt -> Ptr CInt -> IO ()
qStyleOptionTabV2_delete :: QStyleOptionTabV2 a -> IO ()
qStyleOptionTabV2_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabV2_delete cobj_x0
foreign import ccall "qtc_QStyleOptionTabV2_delete" qtc_QStyleOptionTabV2_delete :: Ptr (TQStyleOptionTabV2 a) -> IO ()
| uduki/hsQt | Qtc/Gui/QStyleOptionTabV2.hs | bsd-2-clause | 3,299 | 0 | 12 | 472 | 768 | 401 | 367 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- Module : Documentation.Haddock.Parser
-- Copyright : (c) Mateusz Kowalczyk 2013-2014,
-- Simon Hengel 2013
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Parser used for Haddock comments. For external users of this
-- library, the most commonly used combination of functions is going
-- to be
--
-- @'toRegular' . '_doc' . 'parseParas'@
module Documentation.Haddock.Parser (
parseString,
parseParas,
overIdentifier,
toRegular,
Identifier
) where
import Control.Applicative
import Control.Arrow (first)
import Control.Monad
import Data.Char (chr, isUpper, isAlpha, isSpace)
import Data.List (intercalate, unfoldr, elemIndex)
import Data.Maybe (fromMaybe, mapMaybe)
import Data.Monoid
import qualified Data.Set as Set
import Documentation.Haddock.Doc
import Documentation.Haddock.Markup ( markup, plainMarkup )
import Documentation.Haddock.Parser.Monad
import Documentation.Haddock.Parser.Util
import Documentation.Haddock.Parser.Identifier
import Documentation.Haddock.Types
import Prelude hiding (takeWhile)
import qualified Prelude as P
import qualified Text.Parsec as Parsec
import Text.Parsec (try)
import qualified Data.Text as T
import Data.Text (Text)
-- $setup
-- >>> :set -XOverloadedStrings
-- | Drops the quotes/backticks around all identifiers, as if they
-- were valid but still 'String's.
toRegular :: DocH mod Identifier -> DocH mod String
toRegular = fmap (\(Identifier _ _ x _) -> x)
-- | Maps over 'DocIdentifier's over 'String' with potentially failing
-- conversion using user-supplied function. If the conversion fails,
-- the identifier is deemed to not be valid and is treated as a
-- regular string.
overIdentifier :: (Namespace -> String -> Maybe a)
-> DocH mod Identifier
-> DocH mod a
overIdentifier f d = g d
where
g (DocIdentifier (Identifier ns o x e)) = case f ns x of
Nothing -> DocString $ renderNs ns ++ [o] ++ x ++ [e]
Just x' -> DocIdentifier x'
g DocEmpty = DocEmpty
g (DocAppend x x') = DocAppend (g x) (g x')
g (DocString x) = DocString x
g (DocParagraph x) = DocParagraph $ g x
g (DocIdentifierUnchecked x) = DocIdentifierUnchecked x
g (DocModule (ModLink m x)) = DocModule (ModLink m (fmap g x))
g (DocWarning x) = DocWarning $ g x
g (DocEmphasis x) = DocEmphasis $ g x
g (DocMonospaced x) = DocMonospaced $ g x
g (DocBold x) = DocBold $ g x
g (DocUnorderedList x) = DocUnorderedList $ fmap g x
g (DocOrderedList x) = DocOrderedList $ fmap g x
g (DocDefList x) = DocDefList $ fmap (\(y, z) -> (g y, g z)) x
g (DocCodeBlock x) = DocCodeBlock $ g x
g (DocHyperlink (Hyperlink u x)) = DocHyperlink (Hyperlink u (fmap g x))
g (DocPic x) = DocPic x
g (DocMathInline x) = DocMathInline x
g (DocMathDisplay x) = DocMathDisplay x
g (DocAName x) = DocAName x
g (DocProperty x) = DocProperty x
g (DocExamples x) = DocExamples x
g (DocHeader (Header l x)) = DocHeader . Header l $ g x
g (DocTable (Table h b)) = DocTable (Table (map (fmap g) h) (map (fmap g) b))
choice' :: [Parser a] -> Parser a
choice' [] = empty
choice' [p] = p
choice' (p : ps) = try p <|> choice' ps
parse :: Parser a -> Text -> (ParserState, a)
parse p = either err id . parseOnly (p <* Parsec.eof)
where
err = error . ("Haddock.Parser.parse: " ++)
-- | Main entry point to the parser. Appends the newline character
-- to the input string.
parseParas :: Maybe Package
-> String -- ^ String to parse
-> MetaDoc mod Identifier
parseParas pkg input = case parseParasState input of
(state, a) -> MetaDoc { _meta = Meta { _version = parserStateSince state
, _package = pkg
}
, _doc = a
}
parseParasState :: String -> (ParserState, DocH mod Identifier)
parseParasState = parse (emptyLines *> p) . T.pack . (++ "\n") . filter (/= '\r')
where
p :: Parser (DocH mod Identifier)
p = docConcat <$> many (paragraph <* emptyLines)
emptyLines :: Parser ()
emptyLines = void $ many (try (skipHorizontalSpace *> "\n"))
parseParagraphs :: String -> Parser (DocH mod Identifier)
parseParagraphs input = case parseParasState input of
(state, a) -> Parsec.putState state *> pure a
-- | Variant of 'parseText' for 'String' instead of 'Text'
parseString :: String -> DocH mod Identifier
parseString = parseText . T.pack
-- | Parse a text paragraph. Actually just a wrapper over 'parseParagraph' which
-- drops leading whitespace.
parseText :: Text -> DocH mod Identifier
parseText = parseParagraph . T.dropWhile isSpace . T.filter (/= '\r')
parseParagraph :: Text -> DocH mod Identifier
parseParagraph = snd . parse p
where
p :: Parser (DocH mod Identifier)
p = docConcat <$> many (choice' [ monospace
, anchor
, identifier
, moduleName
, picture
, mathDisplay
, mathInline
, markdownImage
, markdownLink
, hyperlink
, bold
, emphasis
, encodedChar
, string'
, skipSpecialChar
])
-- | Parses and processes
-- <https://en.wikipedia.org/wiki/Numeric_character_reference Numeric character references>
--
-- >>> parseString "A"
-- DocString "A"
encodedChar :: Parser (DocH mod a)
encodedChar = "&#" *> c <* ";"
where
c = DocString . return . chr <$> num
num = hex <|> decimal
hex = ("x" <|> "X") *> hexadecimal
-- | List of characters that we use to delimit any special markup.
-- Once we have checked for any of these and tried to parse the
-- relevant markup, we can assume they are used as regular text.
specialChar :: [Char]
specialChar = "_/<@\"&'`# "
-- | Plain, regular parser for text. Called as one of the last parsers
-- to ensure that we have already given a chance to more meaningful parsers
-- before capturing their characers.
string' :: Parser (DocH mod a)
string' = DocString . unescape . T.unpack <$> takeWhile1_ (`notElem` specialChar)
where
unescape "" = ""
unescape ('\\':x:xs) = x : unescape xs
unescape (x:xs) = x : unescape xs
-- | Skips a single special character and treats it as a plain string.
-- This is done to skip over any special characters belonging to other
-- elements but which were not deemed meaningful at their positions.
skipSpecialChar :: Parser (DocH mod a)
skipSpecialChar = DocString . return <$> Parsec.oneOf specialChar
-- | Emphasis parser.
--
-- >>> parseString "/Hello world/"
-- DocEmphasis (DocString "Hello world")
emphasis :: Parser (DocH mod Identifier)
emphasis = DocEmphasis . parseParagraph <$>
disallowNewline ("/" *> takeWhile1_ (/= '/') <* "/")
-- | Bold parser.
--
-- >>> parseString "__Hello world__"
-- DocBold (DocString "Hello world")
bold :: Parser (DocH mod Identifier)
bold = DocBold . parseParagraph <$> disallowNewline ("__" *> takeUntil "__")
disallowNewline :: Parser Text -> Parser Text
disallowNewline = mfilter (T.all (/= '\n'))
-- | Like `takeWhile`, but unconditionally take escaped characters.
takeWhile_ :: (Char -> Bool) -> Parser Text
takeWhile_ p = scan p_ False
where
p_ escaped c
| escaped = Just False
| not $ p c = Nothing
| otherwise = Just (c == '\\')
-- | Like 'takeWhile1', but unconditionally take escaped characters.
takeWhile1_ :: (Char -> Bool) -> Parser Text
takeWhile1_ = mfilter (not . T.null) . takeWhile_
-- | Text anchors to allow for jumping around the generated documentation.
--
-- >>> parseString "#Hello world#"
-- DocAName "Hello world"
anchor :: Parser (DocH mod a)
anchor = DocAName . T.unpack <$>
("#" *> takeWhile1_ (\x -> x /= '#' && not (isSpace x)) <* "#")
-- | Monospaced strings.
--
-- >>> parseString "@cruel@"
-- DocMonospaced (DocString "cruel")
monospace :: Parser (DocH mod Identifier)
monospace = DocMonospaced . parseParagraph
<$> ("@" *> takeWhile1_ (/= '@') <* "@")
-- | Module names.
--
-- Note that we allow '#' and '\' to support anchors (old style anchors are of
-- the form "SomeModule\#anchor").
moduleName :: Parser (DocH mod a)
moduleName = DocModule . flip ModLink Nothing <$> ("\"" *> moduleNameString <* "\"")
-- | A module name, optionally with an anchor
--
moduleNameString :: Parser String
moduleNameString = modid `maybeFollowedBy` anchor_
where
modid = intercalate "." <$> conid `Parsec.sepBy1` "."
anchor_ = (++)
<$> (Parsec.string "#" <|> Parsec.string "\\#")
<*> many (Parsec.satisfy (\c -> c /= '"' && not (isSpace c)))
maybeFollowedBy pre suf = (\x -> maybe x (x ++)) <$> pre <*> optional suf
conid :: Parser String
conid = (:)
<$> Parsec.satisfy (\c -> isAlpha c && isUpper c)
<*> many conChar
conChar = Parsec.alphaNum <|> Parsec.char '_'
-- | A labeled link to an indentifier, module or url using markdown
-- syntax.
markdownLink :: Parser (DocH mod Identifier)
markdownLink = do
lbl <- markdownLinkText
choice' [ markdownModuleName lbl, markdownURL lbl ]
where
markdownModuleName lbl = do
mn <- "(" *> skipHorizontalSpace *>
"\"" *> moduleNameString <* "\""
<* skipHorizontalSpace <* ")"
pure $ DocModule (ModLink mn (Just lbl))
markdownURL lbl = do
target <- markdownLinkTarget
pure $ DocHyperlink $ Hyperlink target (Just lbl)
-- | Picture parser, surrounded by \<\< and \>\>. It's possible to specify
-- a title for the picture.
--
-- >>> parseString "<<hello.png>>"
-- DocPic (Picture {pictureUri = "hello.png", pictureTitle = Nothing})
-- >>> parseString "<<hello.png world>>"
-- DocPic (Picture {pictureUri = "hello.png", pictureTitle = Just "world"})
picture :: Parser (DocH mod a)
picture = DocPic . makeLabeled Picture
<$> disallowNewline ("<<" *> takeUntil ">>")
-- | Inline math parser, surrounded by \\( and \\).
--
-- >>> parseString "\\(\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}\\)"
-- DocMathInline "\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}"
mathInline :: Parser (DocH mod a)
mathInline = DocMathInline . T.unpack
<$> disallowNewline ("\\(" *> takeUntil "\\)")
-- | Display math parser, surrounded by \\[ and \\].
--
-- >>> parseString "\\[\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}\\]"
-- DocMathDisplay "\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}"
mathDisplay :: Parser (DocH mod a)
mathDisplay = DocMathDisplay . T.unpack
<$> ("\\[" *> takeUntil "\\]")
-- | Markdown image parser. As per the commonmark reference recommendation, the
-- description text for an image converted to its a plain string representation.
--
-- >>> parseString ""
-- DocPic (Picture "www.site.com" (Just "some emphasis in a description"))
markdownImage :: Parser (DocH mod Identifier)
markdownImage = do
text <- markup stringMarkup <$> ("!" *> markdownLinkText)
url <- markdownLinkTarget
pure $ DocPic (Picture url (Just text))
where
stringMarkup = plainMarkup (const "") renderIdent
renderIdent (Identifier ns l c r) = renderNs ns <> [l] <> c <> [r]
-- | Paragraph parser, called by 'parseParas'.
paragraph :: Parser (DocH mod Identifier)
paragraph = choice' [ examples
, table
, do indent <- takeIndent
choice' [ since
, unorderedList indent
, orderedList indent
, birdtracks
, codeblock
, property
, header
, textParagraphThatStartsWithMarkdownLink
, definitionList indent
, docParagraph <$> textParagraph
]
]
-- | Provides support for grid tables.
--
-- Tables are composed by an optional header and body. The header is composed by
-- a single row. The body is composed by a non-empty list of rows.
--
-- Example table with header:
--
-- > +----------+----------+
-- > | /32bit/ | 64bit |
-- > +==========+==========+
-- > | 0x0000 | @0x0000@ |
-- > +----------+----------+
--
-- Algorithms loosely follows ideas in
-- http://docutils.sourceforge.net/docutils/parsers/rst/tableparser.py
--
table :: Parser (DocH mod Identifier)
table = do
-- first we parse the first row, which determines the width of the table
firstRow <- parseFirstRow
let len = T.length firstRow
-- then we parse all consequtive rows starting and ending with + or |,
-- of the width `len`.
restRows <- many (try (parseRestRows len))
-- Now we gathered the table block, the next step is to split the block
-- into cells.
DocTable <$> tableStepTwo len (firstRow : restRows)
where
parseFirstRow :: Parser Text
parseFirstRow = do
skipHorizontalSpace
cs <- takeWhile (\c -> c == '-' || c == '+')
-- upper-left and upper-right corners are `+`
guard (T.length cs >= 2 &&
T.head cs == '+' &&
T.last cs == '+')
-- trailing space
skipHorizontalSpace
_ <- Parsec.newline
return cs
parseRestRows :: Int -> Parser Text
parseRestRows l = do
skipHorizontalSpace
bs <- scan predicate l
-- Left and right edges are `|` or `+`
guard (T.length bs >= 2 &&
(T.head bs == '|' || T.head bs == '+') &&
(T.last bs == '|' || T.last bs == '+'))
-- trailing space
skipHorizontalSpace
_ <- Parsec.newline
return bs
where
predicate n c
| n <= 0 = Nothing
| c == '\n' = Nothing
| otherwise = Just (n - 1)
-- Second step searchs for row of '+' and '=' characters, records it's index
-- and changes to '=' to '-'.
tableStepTwo
:: Int -- ^ width
-> [Text] -- ^ rows
-> Parser (Table (DocH mod Identifier))
tableStepTwo width = go 0 [] where
go _ left [] = tableStepThree width (reverse left) Nothing
go n left (r : rs)
| T.all (`elem` ['+', '=']) r =
tableStepThree width (reverse left ++ r' : rs) (Just n)
| otherwise =
go (n + 1) (r : left) rs
where
r' = T.map (\c -> if c == '=' then '-' else c) r
-- Third step recognises cells in the table area, returning a list of TC, cells.
tableStepThree
:: Int -- ^ width
-> [Text] -- ^ rows
-> Maybe Int -- ^ index of header separator
-> Parser (Table (DocH mod Identifier))
tableStepThree width rs hdrIndex = do
cells <- loop (Set.singleton (0, 0))
tableStepFour rs hdrIndex cells
where
height = length rs
loop :: Set.Set (Int, Int) -> Parser [TC]
loop queue = case Set.minView queue of
Nothing -> return []
Just ((y, x), queue')
| y + 1 >= height || x + 1 >= width -> loop queue'
| otherwise -> case scanRight x y of
Nothing -> loop queue'
Just (x2, y2) -> do
let tc = TC y x y2 x2
fmap (tc :) $ loop $ queue' `Set.union` Set.fromList
[(y, x2), (y2, x), (y2, x2)]
-- scan right looking for +, then try scan down
--
-- do we need to record + saw on the way left and down?
scanRight :: Int -> Int -> Maybe (Int, Int)
scanRight x y = go (x + 1) where
bs = rs !! y
go x' | x' >= width = fail "overflow right "
| T.index bs x' == '+' = scanDown x y x' <|> go (x' + 1)
| T.index bs x' == '-' = go (x' + 1)
| otherwise = fail $ "not a border (right) " ++ show (x,y,x')
-- scan down looking for +
scanDown :: Int -> Int -> Int -> Maybe (Int, Int)
scanDown x y x2 = go (y + 1) where
go y' | y' >= height = fail "overflow down"
| T.index (rs !! y') x2 == '+' = scanLeft x y x2 y' <|> go (y' + 1)
| T.index (rs !! y') x2 == '|' = go (y' + 1)
| otherwise = fail $ "not a border (down) " ++ show (x,y,x2,y')
-- check that at y2 x..x2 characters are '+' or '-'
scanLeft :: Int -> Int -> Int -> Int -> Maybe (Int, Int)
scanLeft x y x2 y2
| all (\x' -> T.index bs x' `elem` ['+', '-']) [x..x2] = scanUp x y x2 y2
| otherwise = fail $ "not a border (left) " ++ show (x,y,x2,y2)
where
bs = rs !! y2
-- check that at y2 x..x2 characters are '+' or '-'
scanUp :: Int -> Int -> Int -> Int -> Maybe (Int, Int)
scanUp x y x2 y2
| all (\y' -> T.index (rs !! y') x `elem` ['+', '|']) [y..y2] = return (x2, y2)
| otherwise = fail $ "not a border (up) " ++ show (x,y,x2,y2)
-- | table cell: top left bottom right
data TC = TC !Int !Int !Int !Int
deriving Show
tcXS :: TC -> [Int]
tcXS (TC _ x _ x2) = [x, x2]
tcYS :: TC -> [Int]
tcYS (TC y _ y2 _) = [y, y2]
-- | Fourth step. Given the locations of cells, forms 'Table' structure.
tableStepFour :: [Text] -> Maybe Int -> [TC] -> Parser (Table (DocH mod Identifier))
tableStepFour rs hdrIndex cells = case hdrIndex of
Nothing -> return $ Table [] rowsDoc
Just i -> case elemIndex i yTabStops of
Nothing -> return $ Table [] rowsDoc
Just i' -> return $ uncurry Table $ splitAt i' rowsDoc
where
xTabStops = sortNub $ concatMap tcXS cells
yTabStops = sortNub $ concatMap tcYS cells
sortNub :: Ord a => [a] -> [a]
sortNub = Set.toList . Set.fromList
init' :: [a] -> [a]
init' [] = []
init' [_] = []
init' (x : xs) = x : init' xs
rowsDoc = (fmap . fmap) parseParagraph rows
rows = map makeRow (init' yTabStops)
where
makeRow y = TableRow $ mapMaybe (makeCell y) cells
makeCell y (TC y' x y2 x2)
| y /= y' = Nothing
| otherwise = Just $ TableCell xts yts (extract (x + 1) (y + 1) (x2 - 1) (y2 - 1))
where
xts = length $ P.takeWhile (< x2) $ dropWhile (< x) xTabStops
yts = length $ P.takeWhile (< y2) $ dropWhile (< y) yTabStops
-- extract cell contents given boundaries
extract :: Int -> Int -> Int -> Int -> Text
extract x y x2 y2 = T.intercalate "\n"
[ T.stripEnd $ T.stripStart $ T.take (x2 - x + 1) $ T.drop x $ rs !! y'
| y' <- [y .. y2]
]
-- | Parse \@since annotations.
since :: Parser (DocH mod a)
since = ("@since " *> version <* skipHorizontalSpace <* endOfLine) >>= setSince >> return DocEmpty
where
version = decimal `Parsec.sepBy1` "."
-- | Headers inside the comment denoted with @=@ signs, up to 6 levels
-- deep.
--
-- >>> snd <$> parseOnly header "= Hello"
-- Right (DocHeader (Header {headerLevel = 1, headerTitle = DocString "Hello"}))
-- >>> snd <$> parseOnly header "== World"
-- Right (DocHeader (Header {headerLevel = 2, headerTitle = DocString "World"}))
header :: Parser (DocH mod Identifier)
header = do
let psers = map (string . flip T.replicate "=") [6, 5 .. 1]
pser = Parsec.choice psers
depth <- T.length <$> pser
line <- parseText <$> (skipHorizontalSpace *> nonEmptyLine)
rest <- try paragraph <|> return DocEmpty
return $ DocHeader (Header depth line) `docAppend` rest
textParagraph :: Parser (DocH mod Identifier)
textParagraph = parseText . T.intercalate "\n" <$> some nonEmptyLine
textParagraphThatStartsWithMarkdownLink :: Parser (DocH mod Identifier)
textParagraphThatStartsWithMarkdownLink = docParagraph <$> (docAppend <$> markdownLink <*> optionalTextParagraph)
where
optionalTextParagraph :: Parser (DocH mod Identifier)
optionalTextParagraph = choice' [ docAppend <$> whitespace <*> textParagraph
, pure DocEmpty ]
whitespace :: Parser (DocH mod a)
whitespace = DocString <$> (f <$> takeHorizontalSpace <*> optional "\n")
where
f :: Text -> Maybe Text -> String
f xs (fromMaybe "" -> x)
| T.null (xs <> x) = ""
| otherwise = " "
-- | Parses unordered (bullet) lists.
unorderedList :: Text -> Parser (DocH mod Identifier)
unorderedList indent = DocUnorderedList <$> p
where
p = ("*" <|> "-") *> innerList indent p
-- | Parses ordered lists (numbered or dashed).
orderedList :: Text -> Parser (DocH mod Identifier)
orderedList indent = DocOrderedList <$> p
where
p = (paren <|> dot) *> innerList indent p
dot = (decimal :: Parser Int) <* "."
paren = "(" *> decimal <* ")"
-- | Generic function collecting any further lines belonging to the
-- list entry and recursively collecting any further lists in the
-- same paragraph. Usually used as
--
-- > someListFunction = listBeginning *> innerList someListFunction
innerList :: Text -> Parser [DocH mod Identifier]
-> Parser [DocH mod Identifier]
innerList indent item = do
c <- takeLine
(cs, items) <- more indent item
let contents = docParagraph . parseText . dropNLs . T.unlines $ c : cs
return $ case items of
Left p -> [contents `docAppend` p]
Right i -> contents : i
-- | Parses definition lists.
definitionList :: Text -> Parser (DocH mod Identifier)
definitionList indent = DocDefList <$> p
where
p = do
label <- "[" *> (parseParagraph <$> takeWhile1_ (`notElem` ("]\n" :: String))) <* ("]" <* optional ":")
c <- takeLine
(cs, items) <- more indent p
let contents = parseText . dropNLs . T.unlines $ c : cs
return $ case items of
Left x -> [(label, contents `docAppend` x)]
Right i -> (label, contents) : i
-- | Drops all trailing newlines.
dropNLs :: Text -> Text
dropNLs = T.dropWhileEnd (== '\n')
-- | Main worker for 'innerList' and 'definitionList'.
-- We need the 'Either' here to be able to tell in the respective functions
-- whether we're dealing with the next list or a nested paragraph.
more :: Monoid a => Text -> Parser a
-> Parser ([Text], Either (DocH mod Identifier) a)
more indent item = choice' [ innerParagraphs indent
, moreListItems indent item
, moreContent indent item
, pure ([], Right mempty)
]
-- | Used by 'innerList' and 'definitionList' to parse any nested paragraphs.
innerParagraphs :: Text
-> Parser ([Text], Either (DocH mod Identifier) a)
innerParagraphs indent = (,) [] . Left <$> ("\n" *> indentedParagraphs indent)
-- | Attempts to fetch the next list if possibly. Used by 'innerList' and
-- 'definitionList' to recursively grab lists that aren't separated by a whole
-- paragraph.
moreListItems :: Text -> Parser a
-> Parser ([Text], Either (DocH mod Identifier) a)
moreListItems indent item = (,) [] . Right <$> indentedItem
where
indentedItem = string indent *> Parsec.spaces *> item
-- | Helper for 'innerList' and 'definitionList' which simply takes
-- a line of text and attempts to parse more list content with 'more'.
moreContent :: Monoid a => Text -> Parser a
-> Parser ([Text], Either (DocH mod Identifier) a)
moreContent indent item = first . (:) <$> nonEmptyLine <*> more indent item
-- | Parses an indented paragraph.
-- The indentation is 4 spaces.
indentedParagraphs :: Text -> Parser (DocH mod Identifier)
indentedParagraphs indent =
(T.unpack . T.concat <$> dropFrontOfPara indent') >>= parseParagraphs
where
indent' = string $ indent <> " "
-- | Grab as many fully indented paragraphs as we can.
dropFrontOfPara :: Parser Text -> Parser [Text]
dropFrontOfPara sp = do
currentParagraph <- some (try (sp *> takeNonEmptyLine))
followingParagraphs <-
choice' [ skipHorizontalSpace *> nextPar -- we have more paragraphs to take
, skipHorizontalSpace *> nlList -- end of the ride, remember the newline
, Parsec.eof *> return [] -- nothing more to take at all
]
return (currentParagraph ++ followingParagraphs)
where
nextPar = (++) <$> nlList <*> dropFrontOfPara sp
nlList = "\n" *> return ["\n"]
nonSpace :: Text -> Parser Text
nonSpace xs
| T.all isSpace xs = fail "empty line"
| otherwise = return xs
-- | Takes a non-empty, not fully whitespace line.
--
-- Doesn't discard the trailing newline.
takeNonEmptyLine :: Parser Text
takeNonEmptyLine = do
l <- takeWhile1 (/= '\n') >>= nonSpace
_ <- "\n"
pure (l <> "\n")
-- | Takes indentation of first non-empty line.
--
-- More precisely: skips all whitespace-only lines and returns indentation
-- (horizontal space, might be empty) of that non-empty line.
takeIndent :: Parser Text
takeIndent = do
indent <- takeHorizontalSpace
choice' [ "\n" *> takeIndent
, return indent
]
-- | Blocks of text of the form:
--
-- >> foo
-- >> bar
-- >> baz
--
birdtracks :: Parser (DocH mod a)
birdtracks = DocCodeBlock . DocString . T.unpack . T.intercalate "\n" . stripSpace <$> some line
where
line = try (skipHorizontalSpace *> ">" *> takeLine)
stripSpace :: [Text] -> [Text]
stripSpace = fromMaybe <*> mapM strip'
where
strip' t = case T.uncons t of
Nothing -> Just ""
Just (' ',t') -> Just t'
_ -> Nothing
-- | Parses examples. Examples are a paragraph level entitity (separated by an empty line).
-- Consecutive examples are accepted.
examples :: Parser (DocH mod a)
examples = DocExamples <$> (many (try (skipHorizontalSpace *> "\n")) *> go)
where
go :: Parser [Example]
go = do
prefix <- takeHorizontalSpace <* ">>>"
expr <- takeLine
(rs, es) <- resultAndMoreExamples
return (makeExample prefix expr rs : es)
where
resultAndMoreExamples :: Parser ([Text], [Example])
resultAndMoreExamples = choice' [ moreExamples, result, pure ([], []) ]
where
moreExamples :: Parser ([Text], [Example])
moreExamples = (,) [] <$> go
result :: Parser ([Text], [Example])
result = first . (:) <$> nonEmptyLine <*> resultAndMoreExamples
makeExample :: Text -> Text -> [Text] -> Example
makeExample prefix expression res =
Example (T.unpack (T.strip expression)) result
where
result = map (T.unpack . substituteBlankLine . tryStripPrefix) res
tryStripPrefix xs = fromMaybe xs (T.stripPrefix prefix xs)
substituteBlankLine "<BLANKLINE>" = ""
substituteBlankLine xs = xs
nonEmptyLine :: Parser Text
nonEmptyLine = try (mfilter (T.any (not . isSpace)) takeLine)
takeLine :: Parser Text
takeLine = try (takeWhile (/= '\n') <* endOfLine)
endOfLine :: Parser ()
endOfLine = void "\n" <|> Parsec.eof
-- | Property parser.
--
-- >>> snd <$> parseOnly property "prop> hello world"
-- Right (DocProperty "hello world")
property :: Parser (DocH mod a)
property = DocProperty . T.unpack . T.strip <$> ("prop>" *> takeWhile1 (/= '\n'))
-- |
-- Paragraph level codeblock. Anything between the two delimiting \@ is parsed
-- for markup.
codeblock :: Parser (DocH mod Identifier)
codeblock =
DocCodeBlock . parseParagraph . dropSpaces
<$> ("@" *> skipHorizontalSpace *> "\n" *> block' <* "@")
where
dropSpaces xs =
case splitByNl xs of
[] -> xs
ys -> case T.uncons (last ys) of
Just (' ',_) -> case mapM dropSpace ys of
Nothing -> xs
Just zs -> T.intercalate "\n" zs
_ -> xs
-- This is necessary because ‘lines’ swallows up a trailing newline
-- and we lose information about whether the last line belongs to @ or to
-- text which we need to decide whether we actually want to be dropping
-- anything at all.
splitByNl = unfoldr (\x -> case T.uncons x of
Just ('\n',x') -> Just (T.span (/= '\n') x')
_ -> Nothing)
. ("\n" <>)
dropSpace t = case T.uncons t of
Nothing -> Just ""
Just (' ',t') -> Just t'
_ -> Nothing
block' = scan p False
where
p isNewline c
| isNewline && c == '@' = Nothing
| isNewline && isSpace c = Just isNewline
| otherwise = Just $ c == '\n'
hyperlink :: Parser (DocH mod Identifier)
hyperlink = choice' [ angleBracketLink, autoUrl ]
angleBracketLink :: Parser (DocH mod a)
angleBracketLink =
DocHyperlink . makeLabeled (\s -> Hyperlink s . fmap DocString)
<$> disallowNewline ("<" *> takeUntil ">")
-- | The text for a markdown link, enclosed in square brackets.
markdownLinkText :: Parser (DocH mod Identifier)
markdownLinkText = parseParagraph . T.strip <$> ("[" *> takeUntil "]")
-- | The target for a markdown link, enclosed in parenthesis.
markdownLinkTarget :: Parser String
markdownLinkTarget = whitespace *> url
where
whitespace :: Parser ()
whitespace = skipHorizontalSpace <* optional ("\n" *> skipHorizontalSpace)
url :: Parser String
url = rejectWhitespace (decode <$> ("(" *> takeUntil ")"))
rejectWhitespace :: MonadPlus m => m String -> m String
rejectWhitespace = mfilter (all (not . isSpace))
decode :: Text -> String
decode = T.unpack . removeEscapes
-- | Looks for URL-like things to automatically hyperlink even if they
-- weren't marked as links.
autoUrl :: Parser (DocH mod a)
autoUrl = mkLink <$> url
where
url = mappend <$> choice' [ "http://", "https://", "ftp://"] <*> takeWhile1 (not . isSpace)
mkLink :: Text -> DocH mod a
mkLink s = case T.unsnoc s of
Just (xs,x) | x `elem` (",.!?" :: String) -> DocHyperlink (mkHyperlink xs) `docAppend` DocString [x]
_ -> DocHyperlink (mkHyperlink s)
mkHyperlink :: Text -> Hyperlink (DocH mod a)
mkHyperlink lnk = Hyperlink (T.unpack lnk) Nothing
-- | Parses identifiers with help of 'parseValid'.
identifier :: Parser (DocH mod Identifier)
identifier = DocIdentifier <$> parseValid
| haskell/haddock | haddock-library/src/Documentation/Haddock/Parser.hs | bsd-2-clause | 30,937 | 0 | 20 | 8,714 | 8,398 | 4,376 | 4,022 | 509 | 25 |
-- http://www.codewars.com/kata/54554846126a002d5b000854
module Gift where
buy :: (Num a, Eq a) => a -> [a] -> Maybe (Int, Int)
buy c is = if null os then Nothing else Just (head os) where
is' = zip [0..] is
os = [(fst a, fst b) | a<-is', b<-is', snd a + snd b == c, fst a /= fst b] | Bodigrim/katas | src/haskell/7-A-Gift-Well-Spent.hs | bsd-2-clause | 287 | 0 | 11 | 63 | 158 | 82 | 76 | 5 | 2 |
{- Copyright (c) 2014. Robert Dockins. -}
-- | This module defines the set of tokens produced by the lexer
-- and consumed by the parser.
module Orlin.Tokens where
-- | A 'Pn' indicates a position in a source file.
-- It contains the name of the source file, the line number and column number.
data Pn = Pn FilePath !Int !Int
deriving (Eq, Ord, Show)
-- | Display a position in the format 'filename:line:col:'
-- for printing error messages.
displayPn :: Pn -> String
displayPn (Pn f l c) = f ++ ":" ++ show l ++ ":" ++ show c ++ ": "
-- | @Located a@ represents an element of type @a@ paired with a location.
data Located a = L Pn a
deriving (Show, Eq, Ord)
-- | Retrieve the element from a 'Located' package.
unloc :: Located a -> a
unloc (L _ x) = x
-- | The main token datatype.
data Token
= LPAREN
| RPAREN
| LBRACK
| RBRACK
| LDATA
| RDATA
| LANGLE
| RANGLE
| CDOT
| SUPERSCRIPT String
| FORALL
| EXISTS
| DEFS
| DOT
| COMMA
| SEMI
| TIdent String
| DecNumberLit String
| HexNumberLit String
| StringLit String
| DCOLON
| COLON
| LBRACE
| RBRACE
| BIG_ARROW
| SM_ARROW
| BIG_LAMBDA
| SM_LAMBDA
| PLUS
| HYPHEN
| MINUS
| EQUAL
| PARTIAL
| LE
| GE
| LT
| GT
| NE
| STAR
| SLASH
| TOPOWER
| UNDERSCORE
| EOF
-- Keywords
| MODULE
| WHERE
| QUANTITY
| UNIT
| ALIAS
| CONVERSION
| CONSTANT
| PER
| SYMBOLIC
| REAL
| INT
| NAT
| RATIONAL
| PRIMITIVE
| TYPE
| OF
| DEFINITION
| WITH
deriving (Eq,Show,Ord)
-- | Given a string, this function determines if the string
-- represents a keyword. If so, it returns the corresponding
-- token. Otherwise, it return an identifier token containing
-- the given string.
--
keyword_or_ident :: String -> Token
keyword_or_ident "module" = MODULE
keyword_or_ident "where" = WHERE
keyword_or_ident "quantity" = QUANTITY
keyword_or_ident "unit" = UNIT
keyword_or_ident "alias" = ALIAS
keyword_or_ident "conversion" = CONVERSION
keyword_or_ident "constant" = CONSTANT
keyword_or_ident "per" = PER
keyword_or_ident "forall" = FORALL
keyword_or_ident "exists" = EXISTS
keyword_or_ident "symbolic" = SYMBOLIC
keyword_or_ident "real" = REAL
keyword_or_ident "nat" = NAT
keyword_or_ident "int" = INT
keyword_or_ident "rational" = RATIONAL
keyword_or_ident "primitive" = PRIMITIVE
keyword_or_ident "type" = TYPE
keyword_or_ident "of" = OF
keyword_or_ident "definition" = DEFINITION
keyword_or_ident "with" = WITH
keyword_or_ident s = TIdent s
-- | Extract a string from a token. Fails if the token is not
-- one of 'TIdent', 'Var', 'NumberLit' or 'StringLit'.
--
token_str :: Located Token -> String
token_str (L _ (TIdent x)) = x
token_str (L _ (DecNumberLit x)) = x
token_str (L _ (HexNumberLit x)) = x
token_str (L _ (StringLit x)) = x
token_str (L _ (SUPERSCRIPT x)) = x
token_str (L _ t) = error $ show t ++ " does not contain a string"
| robdockins/orlin | src/Orlin/Tokens.hs | bsd-2-clause | 3,021 | 0 | 9 | 748 | 704 | 394 | 310 | 105 | 1 |
module Acme.OmittedOrUndefinedSpec where
import Acme.OmittedOrUndefined
import Acme.Omitted
import Acme.Undefined
import Prelude hiding (undefined)
import qualified Prelude
import Test.Hspec
spec = do
describe "isOmitted" $ do
it "isOmitted 0 = False" $ do
isOmitted zero `shouldReturn` False
it "isOmitted undefined = False" $ do
isOmitted undefined `shouldReturn` False
it "isOmitted omitted = True" $ do
isOmitted omitted `shouldReturn` True
describe "isUndefined" $ do
it "isUndefined 0 = False" $ do
isUndefined zero `shouldReturn` False
it "isUndefined undefined = True" $ do
isUndefined undefined `shouldReturn` True
it "isUndefined omitted = False" $ do
isUndefined omitted `shouldReturn` False
it "isUndefined Prelude.undefined = False" $ do
isUndefined Prelude.undefined `shouldReturn` False
describe "isPreludeUndefined" $ do
it "isPreludeUndefined 0 = False" $ do
isPreludeUndefined zero `shouldReturn` False
it "isPreludeUndefined undefined = False" $ do
isPreludeUndefined undefined `shouldReturn` False
it "isPreludeUndefined omitted = False" $ do
isPreludeUndefined omitted `shouldReturn` False
it "isPreludeUndefined Prelude.undefined = True" $ do
isPreludeUndefined Prelude.undefined `shouldReturn` True
zero :: Integer
zero = 0
| joachifm/acme-omitted | tests/Acme/OmittedOrUndefinedSpec.hs | bsd-2-clause | 1,400 | 0 | 15 | 313 | 330 | 158 | 172 | 35 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
import Data.Time (UTCTime (..), fromGregorian)
import Text.XML.Light
import qualified Web.Atom as Atom
xmlgen :: Atom.XMLGen Element Content QName Attr
xmlgen = Atom.XMLGen
{ Atom.xmlElem = \n as ns -> Element n as ns Nothing
, Atom.xmlName = \nsMay name -> QName (T.unpack name)
(fmap T.unpack nsMay) Nothing
, Atom.xmlAttr = \k v -> Attr k (T.unpack v)
, Atom.xmlTextNode = \t -> Text $ CData CDataText (T.unpack t) Nothing
, Atom.xmlElemNode = Elem
}
feed :: Atom.Feed Element
feed = Atom.makeFeed
(Atom.unsafeURI "https://haskell.org/")
(Atom.TextHTML "The <em>Title</em>")
(UTCTime (fromGregorian 2015 7 8) 0)
main = putStr $ ppTopElement $ Atom.feedXML xmlgen feed
| cbaatz/atom-basic | examples/atom-xml/Main.hs | bsd-3-clause | 887 | 0 | 12 | 259 | 278 | 152 | 126 | 19 | 1 |
{-# LANGUAGE RankNTypes, DeriveDataTypeable, StandaloneDeriving, KindSignatures #-}
module Pathfinder.Race
( Race
, raceSize
, raceAdjust
) where
import Pathfinder.Misc
import Pathfinder.Character
import qualified Control.Monad.Random as Rand
import Control.Arrow
import Data.Data
import Data.Dynamic
type RandT = Rand.RandT
data Race
= Race
{ raceSize :: Size
, raceAdjust :: Monad m => Character m -> RandT g m (Character m)
}
{--
raceAdjust :: Monad m =>
Race -> Character m -> RandT g m (Character m)
raceAdjust _race _chr = return _chr -- error "raceAdjust: not implemented yet"
elfAdjust :: Monad m => Kleisli (RandT g m) (Character m) (Character m)
elfAdjust = undefined
test :: Monad m => Kleisli (RandT g m) (Character m) (Character m)
test = elfAdjust >>> elfAdjust
--}
{--
elfAdjust :: Monad m => Character m -> RandT g m (Character m)
elfAdjust =
setChrSize M >>>
setBaseSpeed 9 >>>
addRacialFeats Elf
[ ("Abilities", updateChrAbility (+2) DEX >>>
updateChrAbility (+2) INT >>>
updateChrAbility ((-)2) CON)
, ("Low-light vision", "Elves can see twice as far as humans in conditions of dim light.")
, ("Elven immunities", "Blablabla")
, ("Elven magic", "Blablabla")
, ("Keen senses", addSkillBonus (+2) Perception)
, ("Weapon familiarity", weaponsProficiency [LongBows, CompositeLongBows, ...])
, ("Languages", addLanguages [Common, Elven] >>> addAvailableLanguages [Celestial, ...])
--}
| Elarnon/npc-gen | Pathfinder/Race.hs | bsd-3-clause | 1,503 | 0 | 13 | 310 | 110 | 66 | 44 | 16 | 0 |
module Test.Themis.Provider.TestFramework (
buildTestSet
, runTFTests
, module Test.Themis.Test
) where
import Control.Exception (SomeException, catch)
import qualified Test.Framework as TF
import qualified Test.Framework.Providers.HUnit as TFH
import qualified Test.Framework.Providers.QuickCheck2 as TFQ
import qualified Test.HUnit as HU
import qualified Test.QuickCheck as QC
import Test.Themis.Test
buildTestCase :: TestCase -> TF.Test
buildTestCase = testCaseCata eval evalIO shrink group
where
shrink test tests = TF.testGroup "Shrink test group" (test:tests)
group name tests = TF.testGroup name tests
eval testName = assertion equals satisfies property err
where
equals expected found msg = TFH.testCase testName (HU.assertEqual msg expected found)
satisfies prop found msg = TFH.testCase testName (HU.assertEqual msg True (prop found))
property prop gen msg = TFQ.testProperty testName (QC.forAll gen prop)
err value msg = TFH.testCase testName $ checkException value msg
checkException value msg = do
ok <- catch (do { return $! value; return False })
emptyCatch
if ok
then return ()
else fail $ "Exception is not occured: " ++ msg
where
emptyCatch :: SomeException -> IO Bool
emptyCatch _ = return True
evalIO testName comp = TFH.testCase testName $ do
result <- comp
case result of
Left e -> fail $ show e
Right x -> return ()
buildTestSet :: TestSet -> [TF.Test]
buildTestSet = testSetCata (map buildTestCase)
runTFTests :: Test b -> IO ()
runTFTests = runTest (TF.defaultMain . buildTestSet)
| andorp/themis | src/Test/Themis/Provider/TestFramework.hs | bsd-3-clause | 1,724 | 0 | 14 | 434 | 509 | 267 | 242 | 37 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies, LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Futhark.CodeGen.ImpGen.Kernels
( compileProg
)
where
import Control.Monad.Except
import Control.Monad.Reader
import Control.Applicative
import Data.Maybe
import Data.Monoid
import qualified Data.HashMap.Lazy as HM
import qualified Data.HashSet as HS
import Data.List
import Prelude
import Futhark.MonadFreshNames
import Futhark.Transform.Rename
import Futhark.Representation.ExplicitMemory
import qualified Futhark.CodeGen.ImpCode.Kernels as Imp
import Futhark.CodeGen.ImpCode.Kernels (bytes)
import qualified Futhark.CodeGen.ImpGen as ImpGen
import qualified Futhark.Analysis.ScalExp as SE
import qualified Futhark.Representation.ExplicitMemory.IndexFunction as IxFun
import Futhark.CodeGen.SetDefaultSpace
import Futhark.Tools (partitionChunkedKernelLambdaParameters)
import Futhark.Util.IntegralExp (quotRoundingUp)
type CallKernelGen = ImpGen.ImpM Imp.HostOp
type InKernelGen = ImpGen.ImpM Imp.KernelOp
callKernelOperations :: ImpGen.Operations Imp.HostOp
callKernelOperations =
ImpGen.Operations { ImpGen.opsExpCompiler = expCompiler
, ImpGen.opsCopyCompiler = callKernelCopy
, ImpGen.opsOpCompiler = opCompiler
}
inKernelOperations :: ImpGen.Operations Imp.KernelOp
inKernelOperations = (ImpGen.defaultOperations cannotAllocInKernel)
{ ImpGen.opsCopyCompiler = inKernelCopy
, ImpGen.opsExpCompiler = inKernelExpCompiler
}
compileProg :: MonadFreshNames m => Prog -> m (Either String Imp.Program)
compileProg prog =
fmap (setDefaultSpace (Imp.Space "device")) <$>
ImpGen.compileProg callKernelOperations (Imp.Space "device") prog
opCompiler :: ImpGen.Destination -> Op ExplicitMemory
-> ImpGen.ImpM Imp.HostOp ()
opCompiler dest (Alloc e space) =
ImpGen.compileAlloc dest e space
opCompiler dest (Inner kernel) =
kernelCompiler dest kernel
cannotAllocInKernel :: ImpGen.Destination -> Op ExplicitMemory
-> ImpGen.ImpM Imp.KernelOp ()
cannotAllocInKernel _ _ =
throwError "Cannot allocate memory in kernel."
-- | Recognise kernels (maps), give everything else back.
kernelCompiler :: ImpGen.Destination -> Kernel ExplicitMemory
-> ImpGen.ImpM Imp.HostOp ()
kernelCompiler dest NumGroups = do
[v] <- ImpGen.funcallTargets dest
ImpGen.emit $ Imp.Op $ Imp.GetNumGroups v
kernelCompiler dest GroupSize = do
[v] <- ImpGen.funcallTargets dest
ImpGen.emit $ Imp.Op $ Imp.GetGroupSize v
kernelCompiler
(ImpGen.Destination dest)
(MapKernel _ _ global_thread_index ispace inps returns body) = do
let kernel_size = product $ map (ImpGen.compileSubExp . snd) ispace
global_thread_index_param = Imp.ScalarParam global_thread_index int32
shape = map (ImpGen.compileSubExp . snd) ispace
indices = map fst ispace
indices_lparams = [ Param index (Scalar int32) | index <- indices ]
bound_in_kernel = global_thread_index : indices ++ map kernelInputName inps
kernel_bnds = bodyBindings body
index_expressions = unflattenIndex shape $ Imp.ScalarVar global_thread_index
set_indices = forM_ (zip indices index_expressions) $ \(i, x) ->
ImpGen.emit $ Imp.SetScalar i x
read_params = mapM_ readKernelInput inps
perms = map snd returns
write_result =
sequence_ $ zipWith3 (writeThreadResult indices) perms dest $ bodyResult body
makeAllMemoryGlobal $ do
kernel_body <- fmap (setBodySpace $ Imp.Space "global") $
ImpGen.subImpM_ inKernelOperations $
ImpGen.withParams [global_thread_index_param] $
ImpGen.declaringLParams (indices_lparams ++ map kernelInputParam inps) $ do
ImpGen.comment "compute thread index" set_indices
ImpGen.comment "read kernel parameters" read_params
ImpGen.compileBindings kernel_bnds $
ImpGen.comment "write kernel result" write_result
(group_size, num_groups) <- computeMapKernelGroups kernel_size
-- Compute the variables that we need to pass to and from the
-- kernel.
uses <- computeKernelUses dest (kernel_size, kernel_body) bound_in_kernel
ImpGen.emit $ Imp.Op $ Imp.CallKernel $ Imp.Map Imp.MapKernel {
Imp.mapKernelThreadNum = global_thread_index
, Imp.mapKernelBody = kernel_body
, Imp.mapKernelUses = uses
, Imp.mapKernelSize = kernel_size
, Imp.mapKernelNumGroups = Imp.VarSize num_groups
, Imp.mapKernelGroupSize = Imp.VarSize group_size
}
kernelCompiler
(ImpGen.Destination dest)
(ChunkedMapKernel _ _ kernel_size o lam _) = do
(local_id, group_id, _, _) <- kernelSizeNames
(num_groups, group_size, per_thread_chunk, num_elements, _, num_threads) <-
compileKernelSize kernel_size
let num_nonconcat = chunkedKernelNonconcatOutputs lam
(nonconcat_targets, concat_targets) = splitAt num_nonconcat dest
(global_id, arr_chunk_param, _) =
partitionChunkedKernelLambdaParameters $ lambdaParams lam
(call_with_prologue, prologue) <-
makeAllMemoryGlobal $ ImpGen.subImpM inKernelOperations $
ImpGen.withPrimVar local_id int32 $
ImpGen.declaringPrimVar local_id int32 $
ImpGen.declaringPrimVar group_id int32 $
ImpGen.declaringLParams (lambdaParams lam) $ do
ImpGen.emit $
Imp.Op (Imp.GetLocalId local_id 0) <>
Imp.Op (Imp.GetGroupId group_id 0) <>
Imp.Op (Imp.GetGlobalId global_id 0)
let indexNonconcatTarget (Prim t) (ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory dest_loc) [_]) = do
(mem, space, offset) <-
ImpGen.fullyIndexArray' dest_loc [ImpGen.varIndex global_id] t
return $ ImpGen.ArrayElemDestination mem t space offset
indexNonconcatTarget _ (ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory dest_loc) (_:dest_dims)) = do
let dest_loc' = ImpGen.sliceArray dest_loc
[ImpGen.varIndex global_id]
return $ ImpGen.ArrayDestination (ImpGen.CopyIntoMemory dest_loc') dest_dims
indexNonconcatTarget _ _ =
throwError "indexNonconcatTarget: invalid target."
indexConcatTarget (ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory dest_loc) (_:dest_dims)) = do
let dest_loc' = ImpGen.offsetArray dest_loc $
ImpGen.sizeToScalExp per_thread_chunk *
ImpGen.varIndex global_id
return $ ImpGen.ArrayDestination (ImpGen.CopyIntoMemory dest_loc') $
Nothing : dest_dims
indexConcatTarget _ =
throwError "indexConcatTarget: invalid target."
nonconcat_elem_targets <-
zipWithM indexNonconcatTarget (lambdaReturnType lam) nonconcat_targets
concat_elem_targets <- mapM indexConcatTarget concat_targets
let map_dest =
ImpGen.Destination $ nonconcat_elem_targets <> concat_elem_targets
map_op <-
ImpGen.subImpM_ inKernelOperations $ do
computeThreadChunkSize
comm
(Imp.ScalarVar global_id)
(Imp.innerExp $ Imp.dimSizeToExp num_threads)
(ImpGen.dimSizeToExp per_thread_chunk)
(ImpGen.dimSizeToExp num_elements) $
paramName arr_chunk_param
ImpGen.compileBody map_dest $ lambdaBody lam
let bound_in_kernel = map paramName (lambdaParams lam) ++
[global_id,
local_id,
group_id]
return $ \prologue -> do
let body = mconcat [prologue, map_op]
uses <- computeKernelUses dest (freeIn body) bound_in_kernel
ImpGen.emit $ Imp.Op $ Imp.CallKernel $ Imp.AnyKernel Imp.Kernel
{ Imp.kernelBody = body
, Imp.kernelLocalMemory = mempty
, Imp.kernelUses = uses
, Imp.kernelNumGroups = num_groups
, Imp.kernelGroupSize = group_size
, Imp.kernelName = global_id
, Imp.kernelDesc = Just "chunkedmap"
}
call_with_prologue prologue
where comm = case o of Disorder -> Commutative
InOrder -> Noncommutative
kernelCompiler
(ImpGen.Destination dest)
(ReduceKernel _ _ kernel_size comm reduce_lam fold_lam _) = do
(local_id, group_id, wave_size, skip_waves) <- kernelSizeNames
(num_groups, group_size, per_thread_chunk, num_elements, _, num_threads) <-
compileKernelSize kernel_size
let num_reds = length $ lambdaReturnType reduce_lam
fold_lparams = lambdaParams fold_lam
(reduce_targets, arr_targets) = splitAt num_reds dest
(fold_i, fold_chunk_param, _) =
partitionChunkedKernelLambdaParameters $ lambdaParams fold_lam
reduce_lparams = lambdaParams reduce_lam
(reduce_i, other_index_param, actual_reduce_params) =
partitionChunkedKernelLambdaParameters $ lambdaParams reduce_lam
(reduce_acc_params, reduce_arr_params) =
splitAt num_reds actual_reduce_params
offset = paramName other_index_param
(acc_mem_params, acc_local_mem) <-
unzip <$> mapM (createAccMem group_size) reduce_acc_params
(call_with_prologue, prologue) <-
makeAllMemoryGlobal $ ImpGen.subImpM inKernelOperations $
ImpGen.withPrimVar local_id int32 $
ImpGen.declaringPrimVar local_id int32 $
ImpGen.declaringPrimVar group_id int32 $
ImpGen.declaringPrimVar wave_size int32 $
ImpGen.declaringPrimVar skip_waves int32 $
ImpGen.withParams acc_mem_params $
ImpGen.declaringLParams (fold_lparams++reduce_lparams) $ do
ImpGen.emit $
Imp.Op (Imp.GetLocalId local_id 0) <>
Imp.Op (Imp.GetGroupId group_id 0) <>
Imp.Op (Imp.GetGlobalId reduce_i 0) <>
Imp.Op (Imp.GetGlobalId fold_i 0) <>
Imp.Op (Imp.GetLockstepWidth wave_size)
ImpGen.Destination reduce_acc_targets <-
ImpGen.destinationFromParams reduce_acc_params
let indexArrayTarget (ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory dest_loc) (_:dest_dims))
| Noncommutative <- comm = do
let dest_loc' = ImpGen.offsetArray dest_loc $
ImpGen.sizeToScalExp per_thread_chunk *
ImpGen.varIndex fold_i
return $ ImpGen.ArrayDestination (ImpGen.CopyIntoMemory dest_loc') $
Nothing : dest_dims
| Commutative <- comm = do
let dest_loc' = ImpGen.strideArray
(ImpGen.offsetArray dest_loc $
ImpGen.varIndex fold_i) $
ImpGen.sizeToScalExp num_threads
return $ ImpGen.ArrayDestination (ImpGen.CopyIntoMemory dest_loc') $
Nothing : dest_dims
indexArrayTarget _ =
throwError "indexArrayTarget: invalid target for map-out."
arr_chunk_targets <- mapM indexArrayTarget arr_targets
let fold_dest =
ImpGen.Destination $ reduce_acc_targets <> arr_chunk_targets
fold_op <-
ImpGen.subImpM_ inKernelOperations $ do
computeThreadChunkSize
comm
(Imp.ScalarVar fold_i)
(Imp.innerExp $ Imp.dimSizeToExp num_threads)
(ImpGen.dimSizeToExp per_thread_chunk)
(ImpGen.dimSizeToExp num_elements) $
paramName fold_chunk_param
ImpGen.compileBody fold_dest $ lambdaBody fold_lam
write_fold_result <-
ImpGen.subImpM_ inKernelOperations $
zipWithM_ (writeParamToLocalMemory $ Imp.ScalarVar local_id)
acc_local_mem reduce_acc_params
let read_reduce_args = zipWithM_ (readReduceArgument local_id offset)
reduce_arr_params acc_local_mem
reduce_acc_dest = ImpGen.Destination reduce_acc_targets
reduce_op <-
ImpGen.subImpM_ inKernelOperations $ do
ImpGen.comment "read array element" read_reduce_args
ImpGen.compileBody reduce_acc_dest $ lambdaBody reduce_lam
write_result <-
ImpGen.subImpM_ inKernelOperations $
zipWithM_ (writeFinalResult [group_id]) reduce_targets reduce_acc_params
let bound_in_kernel = map paramName (lambdaParams fold_lam ++
lambdaParams reduce_lam) ++
[offset,
local_id,
group_id] ++
map Imp.paramName acc_mem_params
return $ \prologue -> do
-- wave_id, in_wave_id and num_waves will all be inlined
-- whereever they are used. This leads to ugly code, but
-- declaring them as variables (and setting them) early in
-- the kernel dramatically reduces performance on NVIDIAs
-- OpenCL implementation. I suspect it prevents unrolling
-- of the in-wave reduction loop. It is possible that we
-- may be able to declare these as variables just preceding
-- the loops where they are used, without losing
-- performance. This can be done when we become tired of
-- looking at ugly kernel code.
let wave_id = Imp.BinOp (SQuot Int32)
(Imp.ScalarVar local_id)
(Imp.ScalarVar wave_size)
in_wave_id = Imp.ScalarVar local_id -
(wave_id * Imp.ScalarVar wave_size)
num_waves = Imp.BinOp (SQuot Int32)
(Imp.innerExp (Imp.dimSizeToExp group_size) +
Imp.ScalarVar wave_size - 1)
(Imp.ScalarVar wave_size)
doing_in_wave_reductions =
Imp.CmpOp (CmpSlt Int32) (Imp.ScalarVar offset) $ Imp.ScalarVar wave_size
apply_in_in_wave_iteration =
Imp.CmpOp (CmpEq int32)
(Imp.BinOp (And Int32) in_wave_id (2 * Imp.ScalarVar offset - 1)) 0
in_wave_reductions =
Imp.SetScalar offset 1 <>
Imp.While doing_in_wave_reductions
(Imp.If apply_in_in_wave_iteration
(reduce_op <> write_fold_result) mempty <>
Imp.SetScalar offset (Imp.ScalarVar offset * 2))
doing_cross_wave_reductions =
Imp.CmpOp (CmpSlt Int32) (Imp.ScalarVar skip_waves) num_waves
is_first_thread_in_wave =
Imp.CmpOp (CmpEq int32) in_wave_id 0
wave_not_skipped =
Imp.CmpOp (CmpEq int32)
(Imp.BinOp (And Int32) wave_id (2 * Imp.ScalarVar skip_waves - 1))
0
apply_in_cross_wave_iteration =
Imp.BinOp LogAnd is_first_thread_in_wave wave_not_skipped
cross_wave_reductions =
Imp.SetScalar skip_waves 1 <>
Imp.While doing_cross_wave_reductions
(Imp.Op Imp.Barrier <>
Imp.SetScalar offset (Imp.ScalarVar skip_waves *
Imp.ScalarVar wave_size) <>
Imp.If apply_in_cross_wave_iteration
(reduce_op <> write_fold_result) mempty <>
Imp.SetScalar skip_waves (Imp.ScalarVar skip_waves * 2))
write_group_result =
Imp.If (Imp.CmpOp (CmpEq int32) (Imp.ScalarVar local_id) 0)
write_result mempty
body = mconcat [prologue,
fold_op,
write_fold_result,
in_wave_reductions,
cross_wave_reductions,
write_group_result]
local_mem = map (ensureAlignment $ alignmentMap body) acc_local_mem
uses <- computeKernelUses dest (freeIn body) bound_in_kernel
ImpGen.emit $ Imp.Op $ Imp.CallKernel $ Imp.AnyKernel Imp.Kernel
{ Imp.kernelBody = body
, Imp.kernelLocalMemory = local_mem
, Imp.kernelUses = uses
, Imp.kernelNumGroups = num_groups
, Imp.kernelGroupSize = group_size
, Imp.kernelName = fold_i
, Imp.kernelDesc = Just "reduce"
}
call_with_prologue prologue
where readReduceArgument local_id offset param (mem, _)
| Prim _ <- paramType param =
ImpGen.emit $
Imp.SetScalar (paramName param) $
Imp.Index mem (bytes i) bt (Space "local")
| otherwise =
return ()
where i = (Imp.ScalarVar local_id + Imp.ScalarVar offset) * Imp.SizeOf bt
bt = elemType $ paramType param
kernelCompiler
(ImpGen.Destination dest)
(ScanKernel _ _ kernel_size order lam input) = do
let (nes, arrs) = unzip input
(arrs_dest, partials_dest) = splitAt (length input) dest
(local_id, group_id, wave_size, global_id) <- kernelSizeNames
thread_chunk_size <- newVName "thread_chunk_size"
renamed_lam <- renameLambda lam
(num_groups, local_size, elements_per_thread,
num_elements, _offset_multiple, num_threads) <-
compileKernelSize kernel_size
let (lam_i, other_index_param, actual_params) =
partitionChunkedKernelLambdaParameters $ lambdaParams lam
(x_params, y_params) =
splitAt (length nes) actual_params
(acc_mem_params, acc_local_mem) <-
unzip <$> mapM (createAccMem local_size) x_params
let twoDimInput (ImpGen.ArrayEntry (ImpGen.MemLocation mem shape ixfun) bt) =
let shape' = [num_threads, elements_per_thread] ++ drop 1 shape
ixfun' = IxFun.reshape ixfun $
[DimNew $ SE.intSubExpToScalExp $ kernelNumThreads kernel_size,
DimNew $ SE.intSubExpToScalExp $ kernelElementsPerThread kernel_size] ++
map (DimNew . SE.intSubExpToScalExp . ImpGen.dimSizeToSubExp) (drop 1 shape)
in ImpGen.ArrayEntry (ImpGen.MemLocation mem shape' ixfun') bt
(call_with_body, body) <-
makeAllMemoryGlobal $ ImpGen.subImpM inKernelOperations $
ImpGen.declaringPrimVar local_id int32 $
ImpGen.declaringPrimVar group_id int32 $
ImpGen.declaringPrimVar wave_size int32 $
ImpGen.declaringPrimVar thread_chunk_size int32 $
ImpGen.declaringPrimVar global_id int32 $
ImpGen.withParams acc_mem_params $
ImpGen.declaringLParams (lambdaParams lam) $
ImpGen.declaringLParams (lambdaParams renamed_lam) $
ImpGen.modifyingArrays arrs twoDimInput $ do
ImpGen.emit $
Imp.Op (Imp.GetLocalId local_id 0) <>
Imp.Op (Imp.GetGroupId group_id 0) <>
Imp.Op (Imp.GetGlobalId global_id 0) <>
Imp.Op (Imp.GetLockstepWidth wave_size)
-- 'lam_i' is the offset of the element that the
-- current thread is responsible for. Since a single
-- workgroup processes more elements than it has threads, this
-- will change over time.
ImpGen.emit $
Imp.SetScalar lam_i $
Imp.ScalarVar global_id *
Imp.innerExp (Imp.dimSizeToExp elements_per_thread)
x_dest <- ImpGen.destinationFromParams x_params
y_dest <- ImpGen.destinationFromParams y_params
-- The number of elements processed by the thread so far.
elements_scanned <- newVName "elements_scanned"
let readScanElement param inp_arr =
ImpGen.copyDWIM (paramName param) []
(Var inp_arr) [ImpGen.varIndex global_id,
ImpGen.varIndex elements_scanned]
computeThreadChunkSize
Noncommutative
(Imp.ScalarVar global_id)
(Imp.innerExp $ Imp.dimSizeToExp num_threads)
(ImpGen.dimSizeToExp elements_per_thread)
(ImpGen.dimSizeToExp num_elements)
thread_chunk_size
zipWithM_ ImpGen.compileSubExpTo
(ImpGen.valueDestinations x_dest) nes
read_params <-
ImpGen.collect $ zipWithM_ readScanElement y_params arrs
let (indices, explode_n, explode_m) = case order of
ScanTransposed -> ([elements_scanned, global_id],
kernelElementsPerThread kernel_size,
kernelNumThreads kernel_size)
ScanFlat -> ([global_id, elements_scanned],
kernelNumThreads kernel_size,
kernelElementsPerThread kernel_size)
writeScanElement (ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory (ImpGen.MemLocation mem dims ixfun))
setdims) =
writeFinalResult indices $
ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory (ImpGen.MemLocation mem dims ixfun'))
setdims
where ixfun' = explodeOuterDimension
(Shape $ map sizeToSubExp dims)
explode_n explode_m ixfun
writeScanElement _ =
const $ fail "writeScanElement: invalid destination"
sizeToSubExp (Imp.ConstSize k) = constant k
sizeToSubExp (Imp.VarSize v) = Var v
write_arrs <-
ImpGen.collect $ zipWithM_ writeScanElement arrs_dest x_params
op_to_x <- ImpGen.collect $ ImpGen.compileBody x_dest $ lambdaBody lam
ImpGen.emit $
Imp.Comment "sequentially scan a chunk" $
Imp.For elements_scanned (Imp.ScalarVar thread_chunk_size) $
read_params <>
op_to_x <>
write_arrs <>
Imp.SetScalar lam_i
(Imp.BinOp (Add Int32) (Imp.ScalarVar lam_i) 1)
zipWithM_ (writeParamToLocalMemory $ Imp.ScalarVar local_id)
acc_local_mem x_params
let wave_id = Imp.BinOp (SQuot Int32)
(Imp.ScalarVar local_id)
(Imp.ScalarVar wave_size)
in_wave_id = Imp.ScalarVar local_id -
(wave_id * Imp.ScalarVar wave_size)
inWaveScan' = inWaveScan (Imp.ScalarVar wave_size) local_id acc_local_mem
inWaveScan' lam
ImpGen.emit $ Imp.Op Imp.Barrier
pack_wave_results <-
ImpGen.collect $
zipWithM_ (writeParamToLocalMemory wave_id) acc_local_mem y_params
let last_in_wave =
Imp.CmpOp (CmpEq int32) in_wave_id $ Imp.ScalarVar wave_size - 1
ImpGen.emit $
Imp.Comment "last thread of wave 'i' writes its result to offset 'i'" $
Imp.If last_in_wave pack_wave_results mempty
ImpGen.emit $ Imp.Op Imp.Barrier
let is_first_wave = Imp.CmpOp (CmpEq int32) wave_id 0
scan_first_wave <- ImpGen.collect $ inWaveScan' renamed_lam
ImpGen.emit $
Imp.Comment "scan the first wave, after which offset 'i' contains carry-in for warp 'i+1'" $
Imp.If is_first_wave scan_first_wave mempty
ImpGen.emit $ Imp.Op Imp.Barrier
read_carry_in <-
ImpGen.collect $
zipWithM_ (readParamFromLocalMemory
(paramName other_index_param) (wave_id - 1))
x_params acc_local_mem
op_to_y <- ImpGen.collect $ ImpGen.compileBody y_dest $ lambdaBody lam
ImpGen.emit $
Imp.Comment "carry-in for every wave except the first" $
Imp.If is_first_wave mempty $
Imp.Comment "read operands" read_carry_in <>
Imp.Comment "perform operation" op_to_y
zipWithM_ (writeFinalResult [group_id, local_id]) partials_dest y_params
return $ \body -> do
let local_mem = map (ensureAlignment $ alignmentMap body) acc_local_mem
bound_in_kernel = HM.keys (scopeOf lam) ++
HM.keys (scopeOf renamed_lam) ++
[local_id,
group_id,
global_id] ++
map Imp.paramName acc_mem_params
uses <- computeKernelUses dest (freeIn body) bound_in_kernel
ImpGen.emit $ Imp.Op $ Imp.CallKernel $ Imp.AnyKernel Imp.Kernel
{ Imp.kernelBody = body
, Imp.kernelLocalMemory = local_mem
, Imp.kernelUses = uses
, Imp.kernelNumGroups = num_groups
, Imp.kernelGroupSize = local_size
, Imp.kernelName = lam_i
, Imp.kernelDesc = Just "scan"
}
call_with_body body
kernelCompiler
(ImpGen.Destination dests)
(WriteKernel _cs ts i vs _as) = do
kernel_size <- ImpGen.compileSubExp . arraySize 0 <$> lookupType i
let arr_size = ImpGen.compileSubExp $ arraysSize 0 ts
global_thread_index <- newVName "write_thread_index"
write_index <- newVName "write_index"
let get_thread_index =
ImpGen.emit $ Imp.Op $ Imp.GetGlobalId global_thread_index 0
let check_thread_index body =
let cond = Imp.CmpOp (CmpSlt Int32)
(Imp.ScalarVar global_thread_index) kernel_size
in Imp.If cond body Imp.Skip
let find_index = do
(srcmem, space, srcoffset) <-
ImpGen.fullyIndexArray i $ map SE.intSubExpToScalExp [Var global_thread_index]
ImpGen.emit $ Imp.SetScalar write_index $
Imp.Index srcmem srcoffset int32 space
let -- If an index is out of bounds, just ignore it.
condOutOfBounds0 = Imp.CmpOp (Imp.CmpUlt Int32)
(Imp.ScalarVar write_index)
(Imp.Constant (IntValue (Int32Value 0)))
condOutOfBounds1 = Imp.CmpOp (Imp.CmpUle Int32)
arr_size
(Imp.ScalarVar write_index)
condOutOfBounds = Imp.BinOp LogOr condOutOfBounds0 condOutOfBounds1
let write_result = foldl (>>) (return ())
[ ImpGen.copyDWIMDest dest [ImpGen.varIndex write_index]
(Var v) [ImpGen.varIndex global_thread_index]
| (dest, v) <- zip dests vs
]
makeAllMemoryGlobal $ do
kernel_body <- ImpGen.subImpM_ inKernelOperations $ do
ImpGen.emit $ Imp.DeclareScalar global_thread_index int32
ImpGen.emit $ Imp.DeclareScalar write_index int32
body_body <- ImpGen.collect $ do
ImpGen.comment "find write index" find_index
body_body_body <- ImpGen.collect $
ImpGen.comment "write result" write_result
ImpGen.comment "check write index"
$ ImpGen.emit $ Imp.If condOutOfBounds Imp.Skip body_body_body
ImpGen.comment "get thread index" get_thread_index
ImpGen.comment "check thread index"
$ ImpGen.emit $ check_thread_index body_body
-- Calculate the group size and the number of groups.
(group_size, num_groups) <- computeMapKernelGroups kernel_size
-- Compute the variables that we need to pass to and from the kernel.
uses <- computeKernelUses dests (kernel_size, kernel_body) []
kernel_name <- newVName "a_write_kernel"
ImpGen.emit $ Imp.Op $ Imp.CallKernel $ Imp.AnyKernel Imp.Kernel
{ Imp.kernelBody = kernel_body
, Imp.kernelLocalMemory = mempty
, Imp.kernelUses = uses
, Imp.kernelNumGroups = Imp.VarSize num_groups
, Imp.kernelGroupSize = Imp.VarSize group_size
, Imp.kernelName = kernel_name
, Imp.kernelDesc = Just "write"
}
expCompiler :: ImpGen.ExpCompiler Imp.HostOp
-- We generate a simple kernel for itoa and replicate.
expCompiler target (PrimOp (Iota n x s)) = do
i <- newVName "i"
b <- newVName "b"
v <- newVName "v"
global_thread_index <- newVName "global_thread_index"
let bnd_b = Let (Pattern [] [PatElem b BindVar $ Scalar int32]) () $
PrimOp $ BinOp (Mul Int32) s $ Var i
bnd_v = Let (Pattern [] [PatElem v BindVar $ Scalar int32]) () $
PrimOp $ BinOp (Add Int32) (Var b) x
kernelCompiler target $
MapKernel [] n global_thread_index [(i,n)] [] [(Prim int32,[0])]
(Body () [bnd_b, bnd_v] [Var v])
return ImpGen.Done
expCompiler target (PrimOp (Replicate n se)) = do
global_thread_index <- newVName "global_thread_index"
t <- subExpType se
let row_rank = arrayRank t
row_dims = arrayDims t
i <- newVName "i"
js <- replicateM row_rank $ newVName "j"
let indices = (i,n) : zip js row_dims
kernelCompiler target =<<
case se of
Var v | row_rank > 0 -> do
input_name <- newVName "input"
let input = KernelInput (Param input_name $ Scalar $ elemType t)
v (map Var js)
return $
MapKernel [] n global_thread_index indices [input]
[(t,[0..row_rank])] (Body () [] [Var input_name])
_ ->
return $
MapKernel [] n global_thread_index [(i,n)] []
[(t,[0..arrayRank t])] (Body () [] [se])
return ImpGen.Done
-- Allocation in the "local" space is just a placeholder.
expCompiler _ (Op (Alloc _ (Space "local"))) =
return ImpGen.Done
expCompiler _ e =
return $ ImpGen.CompileExp e
kernelSizeNames :: ImpGen.ImpM Imp.HostOp (VName, VName, VName, VName)
kernelSizeNames = do
local_id <- newVName "local_id"
group_id <- newVName "group_id"
wave_size <- newVName "wave_size"
skip_waves <- newVName "skip_waves"
return (local_id, group_id, wave_size, skip_waves)
compileKernelSize :: KernelSize
-> ImpGen.ImpM op (Imp.DimSize, Imp.DimSize, Imp.DimSize,
Imp.DimSize, Imp.DimSize, Imp.DimSize)
compileKernelSize (KernelSize num_groups local_size per_thread_elements
num_elements offset_multiple num_threads) = do
num_groups' <- ImpGen.subExpToDimSize num_groups
local_size' <- ImpGen.subExpToDimSize local_size
per_thread_elements' <- ImpGen.subExpToDimSize per_thread_elements
num_elements' <- ImpGen.subExpToDimSize num_elements
offset_multiple' <- ImpGen.subExpToDimSize offset_multiple
num_threads' <- ImpGen.subExpToDimSize num_threads
return (num_groups', local_size', per_thread_elements',
num_elements', offset_multiple', num_threads')
callKernelCopy :: ImpGen.CopyCompiler Imp.HostOp
callKernelCopy bt
destloc@(ImpGen.MemLocation destmem destshape destIxFun)
srcloc@(ImpGen.MemLocation srcmem srcshape srcIxFun)
n
| Just (destoffset, srcoffset,
num_arrays, size_x, size_y) <- isMapTransposeKernel bt destloc srcloc =
ImpGen.emit $ Imp.Op $ Imp.CallKernel $
Imp.MapTranspose bt
destmem destoffset
srcmem srcoffset
num_arrays size_x size_y
| bt_size <- primByteSize bt,
Just destoffset <-
ImpGen.scalExpToImpExp =<<
IxFun.linearWithOffset destIxFun bt_size,
Just srcoffset <-
ImpGen.scalExpToImpExp =<<
IxFun.linearWithOffset srcIxFun bt_size = do
let row_size = product $ map ImpGen.dimSizeToExp $ drop 1 srcshape
srcspace <- ImpGen.entryMemSpace <$> ImpGen.lookupMemory srcmem
destspace <- ImpGen.entryMemSpace <$> ImpGen.lookupMemory destmem
ImpGen.emit $ Imp.Copy
destmem (bytes destoffset) destspace
srcmem (bytes srcoffset) srcspace $
(n * row_size) `Imp.withElemType` bt
| otherwise = do
global_thread_index <- newVName "copy_global_thread_index"
-- Note that the shape of the destination and the source are
-- necessarily the same.
let shape = map Imp.sizeToExp destshape
shape_se = map ImpGen.sizeToScalExp destshape
dest_is = unflattenIndex shape_se $ ImpGen.varIndex global_thread_index
src_is = dest_is
makeAllMemoryGlobal $ do
(_, destspace, destidx) <- ImpGen.fullyIndexArray' destloc dest_is bt
(_, srcspace, srcidx) <- ImpGen.fullyIndexArray' srcloc src_is bt
let body = Imp.Write destmem destidx bt destspace $
Imp.Index srcmem srcidx bt srcspace
destmem_size <- ImpGen.entryMemSize <$> ImpGen.lookupMemory destmem
let writes_to = [Imp.MemoryUse destmem destmem_size]
reads_from <- readsFromSet $
HS.singleton srcmem <>
freeIn destIxFun <> freeIn srcIxFun <> freeIn destshape
let kernel_size = Imp.innerExp n * product (drop 1 shape)
(group_size, num_groups) <- computeMapKernelGroups kernel_size
let bound_in_kernel = [global_thread_index]
body_uses <- computeKernelUses [] (kernel_size, body) bound_in_kernel
ImpGen.emit $ Imp.Op $ Imp.CallKernel $ Imp.Map Imp.MapKernel {
Imp.mapKernelThreadNum = global_thread_index
, Imp.mapKernelNumGroups = Imp.VarSize num_groups
, Imp.mapKernelGroupSize = Imp.VarSize group_size
, Imp.mapKernelSize = kernel_size
, Imp.mapKernelUses = nub $ body_uses ++ writes_to ++ reads_from
, Imp.mapKernelBody = body
}
-- | We have no bulk copy operation (e.g. memmove) inside kernels, so
-- turn any copy into a loop.
inKernelCopy :: ImpGen.CopyCompiler Imp.KernelOp
inKernelCopy = ImpGen.copyElementWise
inKernelExpCompiler :: ImpGen.ExpCompiler Imp.KernelOp
inKernelExpCompiler _ (PrimOp (Assert _ loc)) =
fail $ "Cannot compile assertion at " ++ locStr loc ++ " inside parallel kernel."
inKernelExpCompiler _ e =
return $ ImpGen.CompileExp e
computeKernelUses :: FreeIn a =>
[ImpGen.ValueDestination]
-> a -> [VName]
-> ImpGen.ImpM op [Imp.KernelUse]
computeKernelUses dest kernel_body bound_in_kernel = do
-- Find the memory blocks containing the output arrays.
let dest_mems = mapMaybe destMem dest
destMem (ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory
(ImpGen.MemLocation mem _ _)) _) =
Just mem
destMem _ =
Nothing
-- Compute the variables that we need to pass to the kernel.
reads_from <- readsFromSet $
freeIn kernel_body `HS.difference`
HS.fromList (dest_mems <> bound_in_kernel)
-- Compute what memory to copy out. Must be allocated on device
-- before kernel execution anyway.
writes_to <- fmap catMaybes $ forM dest $ \case
(ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory
(ImpGen.MemLocation mem _ _)) _) -> do
memsize <- ImpGen.entryMemSize <$> ImpGen.lookupMemory mem
return $ Just $ Imp.MemoryUse mem memsize
_ ->
return Nothing
return $ nub $ reads_from ++ writes_to
readsFromSet :: Names -> ImpGen.ImpM op [Imp.KernelUse]
readsFromSet free =
fmap catMaybes $
forM (HS.toList free) $ \var -> do
t <- lookupType var
case t of
Array {} -> return Nothing
Mem _ (Space "local") -> return Nothing
Mem memsize _ -> Just <$> (Imp.MemoryUse var <$>
ImpGen.subExpToDimSize memsize)
Prim bt ->
if bt == Cert
then return Nothing
else return $ Just $ Imp.ScalarUse var bt
-- | Change every memory block to be in the global address space.
-- This is fairly hacky and can be improved once the Futhark-level
-- memory representation supports address spaces. This only affects
-- generated code - we still need to make sure that the memory is
-- actually present on the device (and declared as variables in the
-- kernel).
makeAllMemoryGlobal :: CallKernelGen a
-> CallKernelGen a
makeAllMemoryGlobal =
local $ \env -> env { ImpGen.envVtable = HM.map globalMemory $ ImpGen.envVtable env
, ImpGen.envDefaultSpace = Imp.Space "global"
}
where globalMemory (ImpGen.MemVar entry) =
ImpGen.MemVar entry { ImpGen.entryMemSpace = Imp.Space "global" }
globalMemory entry =
entry
writeThreadResult :: [VName] -> [Int] -> ImpGen.ValueDestination -> SubExp
-> InKernelGen ()
writeThreadResult thread_idxs perm
(ImpGen.ArrayDestination
(ImpGen.CopyIntoMemory
(ImpGen.MemLocation mem dims ixfun)) _) se = do
set <- subExpType se
let ixfun' = IxFun.permute ixfun perm
destloc' = ImpGen.MemLocation mem (rearrangeShape perm dims) ixfun'
space <- ImpGen.entryMemSpace <$> ImpGen.lookupMemory mem
let is = map ImpGen.varIndex thread_idxs
case set of
Prim bt -> do
(_, _, elemOffset) <-
ImpGen.fullyIndexArray' destloc' is bt
ImpGen.compileSubExpTo (ImpGen.ArrayElemDestination mem bt space elemOffset) se
_ -> do
let memloc = ImpGen.sliceArray destloc' is
let dest = ImpGen.ArrayDestination (ImpGen.CopyIntoMemory memloc) $
replicate (arrayRank set) Nothing
ImpGen.compileSubExpTo dest se
writeThreadResult _ _ _ _ =
fail "Cannot handle kernel that does not return an array."
computeMapKernelGroups :: Imp.Exp -> ImpGen.ImpM Imp.HostOp (VName, VName)
computeMapKernelGroups kernel_size = do
group_size <- newVName "group_size"
num_groups <- newVName "num_groups"
let group_size_var = Imp.ScalarVar group_size
ImpGen.emit $ Imp.DeclareScalar group_size int32
ImpGen.emit $ Imp.DeclareScalar num_groups int32
ImpGen.emit $ Imp.Op $ Imp.GetGroupSize group_size
ImpGen.emit $ Imp.SetScalar num_groups $
kernel_size `quotRoundingUp` group_size_var
return (group_size, num_groups)
readKernelInput :: KernelInput ExplicitMemory
-> InKernelGen ()
readKernelInput inp =
when (primType t) $ do
(srcmem, space, srcoffset) <-
ImpGen.fullyIndexArray arr $ map SE.intSubExpToScalExp is
ImpGen.emit $ Imp.SetScalar name $
Imp.Index srcmem srcoffset (elemType t) space
where arr = kernelInputArray inp
name = kernelInputName inp
t = kernelInputType inp
is = kernelInputIndices inp
isMapTransposeKernel :: PrimType -> ImpGen.MemLocation -> ImpGen.MemLocation
-> Maybe (Imp.Exp, Imp.Exp,
Imp.Exp, Imp.Exp, Imp.Exp)
isMapTransposeKernel bt
(ImpGen.MemLocation _ _ destIxFun)
(ImpGen.MemLocation _ _ srcIxFun)
| Just (dest_offset, perm_and_destshape) <- IxFun.rearrangeWithOffset destIxFun bt_size,
(perm, destshape) <- unzip perm_and_destshape,
Just destshape' <- mapM ImpGen.scalExpToImpExp destshape,
Just src_offset <- IxFun.linearWithOffset srcIxFun bt_size,
Just (r1, r2, _) <- isMapTranspose perm =
isOk destshape' swap r1 r2 dest_offset src_offset
| Just dest_offset <- IxFun.linearWithOffset destIxFun bt_size,
Just (src_offset, perm_and_srcshape) <- IxFun.rearrangeWithOffset srcIxFun bt_size,
(perm, srcshape) <- unzip perm_and_srcshape,
Just srcshape' <- mapM ImpGen.scalExpToImpExp srcshape,
Just (r1, r2, _) <- isMapTranspose perm =
isOk srcshape' id r1 r2 dest_offset src_offset
| otherwise =
Nothing
where bt_size = primByteSize bt
swap (x,y) = (y,x)
isOk shape f r1 r2 dest_offset src_offset = do
dest_offset' <- ImpGen.scalExpToImpExp dest_offset
src_offset' <- ImpGen.scalExpToImpExp src_offset
let (num_arrays, size_x, size_y) = getSizes shape f r1 r2
return (dest_offset', src_offset',
num_arrays, size_x, size_y)
getSizes shape f r1 r2 =
let (mapped, notmapped) = splitAt r1 shape
(pretrans, posttrans) = f $ splitAt r2 notmapped
in (product mapped, product pretrans, product posttrans)
createAccMem :: Imp.DimSize
-> LParam
-> ImpGen.ImpM op (Imp.Param, (VName, Imp.Size))
createAccMem local_size param
| Prim bt <- paramType param = do
mem_shared <- newVName (baseString (paramName param) <> "_mem_local")
total_size <- newVName "total_size"
ImpGen.emit $
Imp.DeclareScalar total_size int32
ImpGen.emit $
Imp.SetScalar total_size $
Imp.SizeOf bt * Imp.innerExp (ImpGen.dimSizeToExp local_size)
return (Imp.MemParam mem_shared (Imp.VarSize total_size) $ Space "local",
(mem_shared, Imp.VarSize total_size))
| ArrayMem _ _ _ mem _ <- paramAttr param = do
mem_size <-
ImpGen.entryMemSize <$> ImpGen.lookupMemory mem
return (Imp.MemParam mem mem_size $ Space "local",
(mem, mem_size))
| otherwise =
fail $ "createAccMem: cannot deal with accumulator param " ++
pretty param
writeParamToLocalMemory :: Typed (MemBound u) =>
Imp.Exp -> (VName, t) -> Param (MemBound u)
-> ImpGen.ImpM op ()
writeParamToLocalMemory i (mem, _) param
| Prim _ <- paramType param =
ImpGen.emit $
Imp.Write mem (bytes i') bt (Space "local") $
Imp.ScalarVar (paramName param)
| otherwise =
return ()
where i' = i * Imp.SizeOf bt
bt = elemType $ paramType param
readParamFromLocalMemory :: Typed (MemBound u) =>
VName -> Imp.Exp -> Param (MemBound u) -> (VName, t)
-> ImpGen.ImpM op ()
readParamFromLocalMemory index i param (l_mem, _)
| Prim _ <- paramType param =
ImpGen.emit $
Imp.SetScalar (paramName param) $
Imp.Index l_mem (bytes i') bt (Space "local")
| otherwise =
ImpGen.emit $
Imp.SetScalar index i
where i' = i * Imp.SizeOf bt
bt = elemType $ paramType param
writeFinalResult :: Typed (MemBound u) =>
[VName]
-> ImpGen.ValueDestination
-> Param (MemBound u)
-> ImpGen.ImpM op ()
writeFinalResult is (ImpGen.ArrayDestination memdest _) acc_param
| ImpGen.CopyIntoMemory
memloc@(ImpGen.MemLocation out_arr_mem out_shape ixfun) <- memdest = do
target <-
case arrayDims $ paramType acc_param of
[] -> do
(_, space, offset) <-
ImpGen.fullyIndexArray' memloc (map ImpGen.varIndex is) bt
return $
ImpGen.ArrayElemDestination out_arr_mem bt space offset
ds -> do
let destloc = ImpGen.MemLocation out_arr_mem (drop 1 out_shape) $
IxFun.applyInd ixfun $ map ImpGen.varIndex is
return $
ImpGen.ArrayDestination (ImpGen.CopyIntoMemory destloc) $
map (const Nothing) ds
ImpGen.compileSubExpTo target $ Var $ paramName acc_param
where bt = elemType $ paramType acc_param
writeFinalResult _ _ _ =
fail "writeFinalResult: invalid destination"
computeThreadChunkSize :: Commutativity
-> Imp.Exp
-> Imp.Exp
-> Imp.Count Imp.Elements
-> Imp.Count Imp.Elements
-> VName
-> ImpGen.ImpM op ()
computeThreadChunkSize Commutative thread_index num_threads elements_per_thread num_elements chunk_var = do
remaining_elements <- newVName "remaining_elements"
ImpGen.emit $
Imp.DeclareScalar remaining_elements int32
ImpGen.emit $
Imp.SetScalar remaining_elements $
(Imp.innerExp num_elements - thread_index)
`quotRoundingUp`
num_threads
ImpGen.emit $
Imp.If (Imp.CmpOp (CmpSlt Int32)
(Imp.innerExp elements_per_thread)
(Imp.ScalarVar remaining_elements))
(Imp.SetScalar chunk_var (Imp.innerExp elements_per_thread))
(Imp.SetScalar chunk_var (Imp.ScalarVar remaining_elements))
computeThreadChunkSize Noncommutative thread_index _ elements_per_thread num_elements chunk_var = do
starting_point <- newVName "starting_point"
remaining_elements <- newVName "remaining_elements"
ImpGen.emit $
Imp.DeclareScalar starting_point int32
ImpGen.emit $
Imp.SetScalar starting_point $
thread_index * Imp.innerExp elements_per_thread
ImpGen.emit $
Imp.DeclareScalar remaining_elements int32
ImpGen.emit $
Imp.SetScalar remaining_elements $
Imp.innerExp num_elements - Imp.ScalarVar starting_point
let no_remaining_elements = Imp.CmpOp (CmpSle Int32)
(Imp.ScalarVar remaining_elements) 0
beyond_bounds = Imp.CmpOp (CmpSle Int32)
(Imp.innerExp num_elements)
(Imp.ScalarVar starting_point)
ImpGen.emit $
Imp.If (Imp.BinOp LogOr no_remaining_elements beyond_bounds)
(Imp.SetScalar chunk_var 0)
(Imp.If is_last_thread
(Imp.SetScalar chunk_var $ Imp.innerExp last_thread_elements)
(Imp.SetScalar chunk_var $ Imp.innerExp elements_per_thread))
where last_thread_elements =
num_elements - Imp.elements thread_index * elements_per_thread
is_last_thread =
Imp.CmpOp (CmpSlt Int32)
(Imp.innerExp num_elements)
((thread_index + 1) * Imp.innerExp elements_per_thread)
inWaveScan :: Imp.Exp
-> VName
-> [(VName, t)]
-> Lambda
-> ImpGen.ImpM op ()
inWaveScan wave_size local_id acc_local_mem scan_lam = do
skip_threads <- newVName "skip_threads"
let in_wave_thread_active =
Imp.CmpOp (CmpSle Int32) (Imp.ScalarVar skip_threads) in_wave_id
(scan_lam_i, other_index_param, actual_params) =
partitionChunkedKernelLambdaParameters $ lambdaParams scan_lam
(x_params, y_params) =
splitAt (length actual_params `div` 2) actual_params
read_operands <-
ImpGen.collect $
zipWithM_ (readParamFromLocalMemory (paramName other_index_param) $
Imp.ScalarVar local_id -
Imp.ScalarVar skip_threads)
x_params acc_local_mem
scan_y_dest <- ImpGen.destinationFromParams y_params
-- Set initial y values
zipWithM_ (readParamFromLocalMemory scan_lam_i $ Imp.ScalarVar local_id)
y_params acc_local_mem
op_to_y <- ImpGen.collect $ ImpGen.compileBody scan_y_dest $ lambdaBody scan_lam
write_operation_result <-
ImpGen.collect $
zipWithM_ (writeParamToLocalMemory $ Imp.ScalarVar local_id)
acc_local_mem y_params
ImpGen.emit $
Imp.Comment "in-wave scan (no barriers needed)" $
Imp.DeclareScalar skip_threads int32 <>
Imp.SetScalar skip_threads 1 <>
Imp.While (Imp.CmpOp (CmpSlt Int32) (Imp.ScalarVar skip_threads) wave_size)
(Imp.If in_wave_thread_active
(Imp.Comment "read operands" read_operands <>
Imp.Comment "perform operation" op_to_y <>
Imp.Comment "write result" write_operation_result)
mempty <>
Imp.SetScalar skip_threads (Imp.ScalarVar skip_threads * 2))
where wave_id = Imp.BinOp (SQuot Int32) (Imp.ScalarVar local_id) wave_size
in_wave_id = Imp.ScalarVar local_id - wave_id * wave_size
type AlignmentMap = HM.HashMap VName PrimType
lookupAlignment :: VName -> AlignmentMap -> PrimType
lookupAlignment = HM.lookupDefault smallestType
smallestType :: PrimType
smallestType = Bool
alignmentMap :: Imp.KernelCode -> AlignmentMap
alignmentMap = HM.map alignment . Imp.memoryUsage (const mempty)
where alignment = HS.foldr mostRestrictive smallestType
mostRestrictive bt1 bt2 =
if (primByteSize bt1 :: Int) > primByteSize bt2
then bt1 else bt2
ensureAlignment :: AlignmentMap
-> (VName, Imp.Size)
-> (VName, Imp.Size, PrimType)
ensureAlignment alignments (name, size) =
(name, size, lookupAlignment name alignments)
explodeOuterDimension :: Shape -> SubExp -> SubExp
-> IxFun.IxFun SE.ScalExp -> IxFun.IxFun SE.ScalExp
explodeOuterDimension orig_shape n m ixfun =
IxFun.reshape ixfun explode_dims
where explode_dims =
map (fmap SE.intSubExpToScalExp) $
reshapeOuter [DimNew n, DimNew m] 1 orig_shape
| CulpaBS/wbBach | src/Futhark/CodeGen/ImpGen/Kernels.hs | bsd-3-clause | 47,960 | 2 | 28 | 13,492 | 12,182 | 5,964 | 6,218 | 957 | 9 |
-- |Module to parse the command line
module Commandline
( TestMode(..)
, DataType(..)
, Options(..)
, parseCommandLineOptions
, checkOptionsConsistency
)
where
import Control.Monad
import Data.Char
import Data.List
import Error
import System.Console.GetOpt
import System.IO
import Text.Read
-- |Supported modes for testing
data TestMode
= EXPR -- ^ Test evaluation of expressions
| CONV -- ^ Test calling conventions
| LOOP -- ^ Test loops
deriving (Eq,Show,Read)
-- |Supported types for expression testing
data DataType
= UINT64
| UINT32
| UINT16
| UINT8
deriving (Eq,Show,Read)
-- |Command line options
data Options = Options
{ optMode :: TestMode -- ^ Mode for testing
, optExprType :: DataType -- ^ Base data type for expression testing
, optNumTests :: Int -- ^ Maximum number of test groups
, optChunkSize :: Int -- ^ Size of a test group
, optComplexity :: Int -- ^ Maximum complexity of test in a group
, optShowHelp :: Bool -- ^ Show help and terminate program
, optEnableShrink :: Bool -- ^ Try to shrink on failing tests
, optPointer64 :: Bool -- ^ Assume 64bit instead of 32bit wide pointers
, optFlowConstraints :: Bool -- ^ Flow constraints in loop tests
} deriving (Eq,Show)
-- |Default values for command line options
defaultOptions :: Options
defaultOptions = Options
{ optMode = EXPR
, optExprType = UINT64
, optNumTests = 100
, optChunkSize = 1
, optComplexity = 30
, optShowHelp = False
, optEnableShrink = True
, optPointer64 = False
, optFlowConstraints = False
}
-- |Option descriptions for GetOpt module
options :: [OptDescr (Options -> Either String Options)]
options =
[ Option ['h','?']
["help"]
(NoArg (\opts -> Right opts { optShowHelp = True }))
"Print this help message."
, Option ['m']
["mode"]
(ReqArg convertMode "MODE")
("Select mode for testing, either `expr', `conv', or `loop'. Defaults to `" ++ defaultMode ++ "'.")
, Option ['n']
["number"]
(ReqArg (convertInt "number of tests" (\i opts -> opts { optNumTests = i })) "NUMBER")
("Maximum number of calls to the external test-script. Defaults to " ++ defaultNumTests ++ ".")
, Option ['c']
["complexity"]
(ReqArg (convertInt "complexity for tests" (\i opts -> opts { optComplexity = i })) "NUMBER")
("Maximum complexity of each test. Defaults to " ++ defaultComplexity ++ ".")
, Option ['g']
["groupsize"]
(ReqArg (convertInt "number of tests" (\i opts -> opts { optChunkSize = i })) "NUMBER")
("Number of tests per call to external test-script. Defaults to " ++ defaultChunkSize ++ ".")
, Option ['t']
["type"]
(ReqArg convertType "TYPE")
("Set data type for mode `expr' to `uint8', `uint16', `uint32', or `uint64'. Defaults to `" ++ defaultExprType ++ "'.")
, Option []
["ptr64"]
(NoArg (\opts -> Right opts { optPointer64 = True }))
"Assume 64-bit pointers for mode `conv'. Defaults to 32-bit pointers."
, Option []
["flow"]
(NoArg (\opts -> Right opts { optFlowConstraints = True }))
"Generate flow constraints for mode `loop'."
, Option []
["noshrink"]
(NoArg (\opts -> Right opts { optEnableShrink = False }))
"Disable shrinking on test failure."
]
where
defaultMode = map toLower $ show $ optMode defaultOptions
defaultExprType = map toLower $ show $ optExprType defaultOptions
defaultNumTests = show $ optNumTests defaultOptions
defaultChunkSize = show $ optChunkSize defaultOptions
defaultComplexity = show $ optComplexity defaultOptions
convertMode :: String -> Options -> Either String Options
convertMode s opts = case readMaybe $ map toUpper s of
Just m -> Right opts { optMode = m }
_ -> Left $ "illegal mode `" ++ s ++ "'"
convertType :: String -> Options -> Either String Options
convertType s opts = case readMaybe $ map toUpper s of
Just t -> Right opts { optExprType = t }
_ -> Left $ "illegal data type `" ++ s ++ "'"
convertInt :: String -> (Int -> Options -> Options) -> String -> Options -> Either String Options
convertInt desc f s opts = case readMaybe s of
Just i | i > 0 -> Right $ f i opts
_ -> Left $ "illegal " ++ desc ++ " `" ++ s ++ "'"
-- |Usage info message
usage :: String
usage = usageInfo "Synopsis: fuzzer [options]" options
-- |Parse the commandline
parseCommandLineOptions :: [String] -> IO Options
parseCommandLineOptions argv =
case getOpt Permute options argv of
(acts, _, []) -> evalutate acts
(_, _, errs) -> exitWithError $ concatMap ("Error: " ++) (nub errs) ++ usage
where
evalutate acts = do
case foldM (flip ($)) defaultOptions acts of
Left err -> exitWithError $ "Error: " ++ err ++ "\n" ++ usage
Right opts -> do when (optShowHelp opts) $ exitWithInfo usage
return opts
-- |Consistency check for options
checkOptionsConsistency :: Options -> IO Options
checkOptionsConsistency opts = do
when (mode == CONV && complexity > 8192) $ exitWithError "Error: complexity for mode `conv' must be <= 8192."
when (complexity > 256) $ hPutStrLn stderr "Warning: selected complexity is very large."
when (chunkSize > 2048) $ hPutStrLn stderr "Warning: selected group size is very large."
return opts
where
mode = optMode opts
complexity = optComplexity opts
chunkSize = optChunkSize opts
| m-schmidt/fuzzer | src/Commandline.hs | bsd-3-clause | 5,669 | 0 | 17 | 1,486 | 1,418 | 770 | 648 | 122 | 4 |
module Wyas.Parser where
import Data.Char
import Text.ParserCombinators.Parsec hiding (string)
import Data.List (foldl')
import Numeric
import Wyas.LispVal
-- $setup
-- >>> import Data.Either (isLeft)
parseFile :: FilePath -> IO (Either ParseError LispVal)
parseFile f = do
str <- readFile f
case runParser lispExpr () f str of
Left err -> return (Left err)
Right v -> return (Right v)
parseLisp :: Parser LispVal -> String -> Either ParseError LispVal
parseLisp p = runParser p () ""
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
-- | Parses a String, consisting of many characters in quotes.
--
-- >>> parseLisp string "\"Hello world!\""
-- Right (String "Hello world!")
--
-- >>> parseLisp string " No quotes?? "
-- Left (line 1, column 1):
-- unexpected " "
-- expecting "\""
string :: Parser LispVal
string = String <$> (char '"' *> many safeQuotes <* char '"')
-- | Parses a character literal.
--
-- >>> parseLisp character "#\\space"
-- Right (Character ' ')
--
-- >>> parseLisp character "#\\a"
-- Right (Character 'a')
character :: Parser LispVal
character = char '#' >> char '\\' >> Character <$> lispChar
where
lispChar = spaceStr
<|> newLineStr
<|> anyChar
spaceStr = stringCaseInsensitive "space" >> return ' '
newLineStr = stringCaseInsensitive "newline" >> return '\n'
-- | Parses a list of lisp values separated by spaces.
--
-- >>> parseLisp list "1 2.0 (asdf \"hello\")"
-- Right (List [Number 1,Float 2.0,List [Atom "asdf",String "hello"]])
--
-- >>> parseLisp list "(print (\"hello\" \"world\"))"
-- Right (List [List [Atom "print",List [String "hello",String "world"]]])
list :: Parser LispVal
list = List <$> sepBy lispExpr spaces
quoted :: Parser LispVal
quoted = do
x <- char '\'' *> lispExpr
return $ List [Atom "quote", x]
float :: Parser LispVal
float = do
c <- option '+' (oneOf "+-")
digits <- many1 digit
post <- char '.' >> many1 digit
return (Float ((if c == '+' then id else negate) (read (concat [digits, ".", post]))))
charCaseInsensitive :: Char -> Parser Char
charCaseInsensitive c = char (toLower c) <|> char (toUpper c)
stringCaseInsensitive :: String -> Parser String
stringCaseInsensitive s = try (mapM charCaseInsensitive s) <?> "\"" ++ s ++ "\""
safeQuotes :: Parser Char
safeQuotes = nonQuoteCharacter <|> specialCharacter
nonQuoteCharacter :: Parser Char
nonQuoteCharacter = do
c <- noneOf "\"\\"
case c of
'"' -> fail "quotes"
'\\' -> fail "backslash"
_ -> return c
specialCharacter :: Parser Char
specialCharacter = do
_ <- char '\\'
c <- oneOf "nrt\\\""
return $ case c of
'n' -> '\n'
'r' -> '\r'
't' -> '\t'
'\\' -> '\\'
'"' -> '\"'
_ -> error "unexpect"
-- | Parses an Atom. This represents a symbol in Lisp which can be either
-- a keyword or variable.
--
-- >>> parseLisp atom "hello"
-- Right (Atom "hello")
--
-- >>> parseLisp atom "+"
-- Right (Atom "+")
--
-- >>> isLeft (parseLisp atom "#\a")
-- True
--
-- >>> parseLisp atom "#t"
-- Right (Bool True)
atom :: Parser LispVal
atom = do
first <- letter <|> symbol
case first of
'#' -> (Bool . (=='t')) <$> oneOf "tf"
_ -> do
rest <- many (letter <|> digit <|> symbol)
let atom' = first : rest
case atom' of
"#t" -> return $ Bool True
"#f" -> return $ Bool False
'#' : '\\' : _ -> fail "wrong"
_ -> return $ Atom atom'
int :: Parser LispVal
int = try altBase <|> do
s <- try (char '-') <|> return '0'
d <- many1 digit
return (Number (read (s:d)))
altBase :: Parser LispVal
altBase = do
c <- char '#' >> oneOf "bodx"
n <- case c of
'b' -> many (oneOf "01")
'o' -> many (oneOf "01234567")
'd' -> many digit
'x' -> many (digit <|> oneOf "abcdefABCDEF")
_ -> fail "wrong prefix"
let number = case c of
'b' -> readBinary n
'o' -> fst . head . readOct $ n
'd' -> read n
'x' -> fst . head . readHex $ n
_ -> error "Wrong prefix"
return (Number (fromIntegral number))
readBinary :: String -> Int
readBinary = foldl' (\acc c -> (acc * 2) + digitToInt c) 0
lispExpr :: Parser LispVal
lispExpr = pzero
<|> string
<|> try float
<|> try int
<|> try atom
<|> character
<|> quoted
<|> char '(' *> list <* char ')'
| parsonsmatt/wyas | src/Wyas/Parser.hs | bsd-3-clause | 4,469 | 7 | 20 | 1,174 | 1,320 | 650 | 670 | 106 | 9 |
module MPS.Light where
import Control.Arrow ((&&&), (>>>), (<<<))
import Control.Category (Category)
import Data.Char
import Data.Foldable (elem, foldl, foldl', toList, Foldable)
import Data.Function (on)
import Debug.Trace
import Prelude hiding ((.), (^), (>), (<), (/), (-), elem, foldl, foldl1)
import qualified Prelude as P
import System.FilePath ((</>))
import qualified Data.Array as A
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S
-- base DSL
{-# INLINE (.) #-}
(.) :: a -> (a -> b) -> b
a . f = f a
infixl 9 .
(>) :: (Category cat) => cat a b -> cat b c -> cat a c
(>) = (>>>)
infixl 8 >
(<) :: (Category cat) => cat b c -> cat a b -> cat a c
(<) = (<<<)
infixr 8 <
(^) :: (Functor f) => f a -> (a -> b) -> f b
(^) = flip fmap
infixl 8 ^
(/) :: FilePath -> FilePath -> FilePath
(/) = (</>)
infixl 5 /
{-# INLINE (-) #-}
(-) :: (a -> b) -> a -> b
f - x = f x
infixr 0 -
(<->) :: (Num a) => a -> a -> a
(<->) = (P.-)
infix 6 <->
-- List
join :: [a] -> [[a]] -> [a]
join = L.intercalate
join' :: [[a]] -> [a]
join' = concat
first, second, third, forth, fifth :: [a] -> a
sixth, seventh, eighth, ninth, tenth :: [a] -> a
first = head
second = at 1
third = at 2
forth = at 3
fifth = at 4
sixth = at 5
seventh = at 6
eighth = at 7
ninth = at 8
tenth = at 10
-- Set requires Ord instance, so use nub when
-- xs is not comparable
unique :: (Ord a) => [a] -> [a]
unique = to_set > to_list
is_unique :: (Ord a) => [a] -> Bool
is_unique xs = xs.unique.length == xs.length
same :: (Ord a) => [a] -> Bool
same = unique > length > is 1
times :: b -> Int -> [b]
times = flip replicate
upto :: (Enum a) => a -> a -> [a]
upto = flip enumFromTo
downto :: (Num t, Enum t) => t -> t -> [t]
downto m n = [n, n <-> 1.. m]
remove_at :: Int -> [a] -> [a]
remove_at n xs = xs.take n ++ xs.drop (n+1)
insert_at, replace_at :: Int -> a -> [a] -> [a]
insert_at n x xs = splitted.fst ++ [x] ++ splitted.snd
where splitted = xs.splitAt n
replace_at n x xs = xs.take n ++ [x] ++ xs.drop (n+1)
at :: Int -> [a] -> a
at = flip (!!)
slice :: Int -> Int -> [a] -> [a]
slice l r = take r > drop l
cherry_pick :: [Int] -> [a] -> [a]
cherry_pick ids xs = ids.map(xs !!)
reduce, reduce' :: (a -> a -> a) -> [a] -> a
reduce = L.foldl1
reduce' = L.foldl1'
inject, inject' :: (Foldable t) => a -> (a -> b -> a) -> t b -> a
inject = flip foldl
inject' = flip foldl'
none_of :: (a -> Bool) -> [a] -> Bool
none_of f = any f > not
select, reject :: (a -> Bool) -> [a] -> [a]
select = filter
reject f = filter (f > not)
inner_map :: (a -> b) -> [[a]] -> [[b]]
inner_map f = map (map f)
inner_reduce :: (a -> a -> a) -> [[a]] -> [a]
inner_reduce f = map (reduce f)
inner_inject :: (Foldable t) => a -> (a -> b -> a) -> [t b] -> [a]
inner_inject x f = map (inject x f)
label_by :: (a -> c) -> [a] -> [(c, a)]
label_by f = map (f &&& id)
labeling :: (a -> c') -> [a] -> [(a, c')]
labeling f = map(id &&& f)
in_group_of :: Int -> [t] -> [[t]]
in_group_of _ [] = []
in_group_of n xs = h : t.in_group_of(n) where (h, t) = xs.splitAt(n)
split_to :: Int -> [a] -> [[a]]
split_to n xs = xs.in_group_of(size) where
l = xs.length
size = if l P.< n then 1 else l `div` n
apply, send_to :: a -> (a -> b) -> b
apply x f = f x
send_to = apply
let_receive :: (a -> b -> c) -> b -> a -> c
let_receive f = flip f
map_send_to :: a -> [a -> b] -> [b]
map_send_to x = map (send_to(x))
belongs_to :: (Foldable t, Eq a) => t a -> a -> Bool
belongs_to = flip elem
has :: (Foldable t, Eq b) => b -> t b -> Bool
has = flip belongs_to
indexed :: (Num t, Enum t) => [b] -> [(t, b)]
indexed = zip([0..])
map_with_index :: (Num t, Enum t) => ((t, b) -> b1) -> [b] -> [b1]
map_with_index f = indexed > map f
ljust, rjust :: Int -> a -> [a] -> [a]
rjust n x xs
| n P.< xs.length = xs
| otherwise = ( n.times x ++ xs ).reverse.take n.reverse
ljust n x xs
| n P.< xs.length = xs
| otherwise = ( xs ++ n.times x ).take n
ub, lb :: (a -> Bool) -> [a] -> [a]
ub = takeWhile
lb f = dropWhile ( f > not )
between :: (a -> Bool) -> (a -> Bool) -> [a] -> [a]
between a b xs = xs.lb a .ub b
not_null :: [a] -> Bool
not_null = null > not
powerslice :: [a] -> [[a]]
powerslice xs = [ xs.slice j (j+i) |
i <- l.downto 1,
j <- [0..l <-> i]
]
where l = xs.length
-- only works for sorted list
-- but could be infinite
-- e.g. a `common` b `common` c
common :: (Ord a) => [a] -> [a] -> [a]
common _ [] = []
common [] _ = []
common a@(x:xs) b@(y:ys)
| x .is y = y : common xs b
| x P.< y = common xs b
| otherwise = common a ys
-- faster reverse sort
rsort :: (Ord a) => [a] -> [a]
rsort xs = xs.L.sortBy(\a b -> b `compare` a)
encode :: (Eq a) => [a] -> [(Int, a)]
encode xs = xs.L.group.map (length &&& head)
decode :: [(Int, a)] -> [a]
decode xs = xs.map(\(l,x) -> l.times x).join'
only_one :: [a] -> Bool
only_one [_] = True
only_one _ = False
concat_map :: (a -> [b]) -> [a] -> [b]
concat_map = concatMap
-- Fold
to_list :: (Foldable t) => t a -> [a]
to_list = toList
-- Set
to_set :: (Ord a) => [a] -> S.Set a
to_set = S.fromList
-- Map
to_h :: (Ord k) => [(k, a)] -> M.Map k a
to_h xs = xs.M.fromList
-- Array
to_a :: [a] -> A.Array Int a
to_a xs = A.listArray (0, xs.length <-> 1) xs
to_a' :: (A.Ix i) => (i, i) -> [e] -> A.Array i e
to_a' i xs = A.listArray i xs
hist :: (Num e, A.Ix i) => (i, i) -> [i] -> A.Array i e
hist bnds ns = A.accumArray (+) 0 bnds [(n, 1) | n <- ns, A.inRange bnds n]
-- Ord
compare_by :: (Ord b) => (a -> b) -> a -> a -> Ordering
compare_by = on compare
eq, is, is_not, isn't, aren't :: (Eq a) => a -> a -> Bool
eq = flip (==)
is = eq
is_not a b = not (is a b)
isn't = is_not
aren't = is_not
-- Tuple
swap :: (a, b) -> (b, a)
swap (x,y) = (y,x)
tuple2 :: [a] -> (a, a)
tuple2 = first &&& last
tuple3 :: [a] -> (a, a, a)
tuple3 xs = (xs.first, xs.second, xs.third)
list2 :: (a, a) -> [a]
list2 (x,y) = [x,y]
list3 :: (a, a, a) -> [a]
list3 (x,y,z) = [x,y,z]
filter_fst :: (a -> Bool) -> [(a, b)] -> [(a, b)]
filter_fst f = filter(fst > f)
filter_snd :: (b -> Bool) -> [(a, b)] -> [(a, b)]
filter_snd f = filter(snd > f)
only_fst :: [(a, b)] -> [a]
only_fst = map fst
only_snd :: [(a, b)] -> [b]
only_snd = map snd
map_fst :: (a -> b) -> [(a, c)] -> [(b, c)]
map_fst f = map(\(a,b) -> (f a, b))
map_snd :: (a -> b) -> [(c, a)] -> [(c, b)]
map_snd f = map(\(a,b) -> (a, f b))
pair :: ((a, b) -> c) -> a -> b -> c
pair f a b = f (a,b)
triple :: ((a, b, c) -> d) -> a -> b -> c -> d
triple f a b c = f (a,b,c)
splash :: (a -> b -> c) -> (a, b) -> c
splash f (a,b) = f a b
splash3 :: (a -> b -> c -> d) -> (a, b, c) -> d
splash3 f (a,b,c) = f a b c
twin :: a -> (a, a)
twin x = (x,x)
-- Integer
from_i :: (Integral a, Num b) => a -> b
from_i = fromIntegral
explode :: (Show a) => a -> [Int]
explode n = n.show.map digitToInt
-- String
lower, upper :: String -> String
lower = map toLower
upper = map toUpper
starts_with, ends_with :: String -> String -> Bool
starts_with = L.isPrefixOf
ends_with = L.isSuffixOf
capitalize :: String -> String
capitalize [] = []
capitalize (x:xs) = [x].upper ++ xs.lower
to_s :: (Show a) => a -> String
to_s = show
-- Simple Math
-- Var
is_palindrom :: (Eq a) => [a] -> Bool
is_palindrom s = s.reverse.is s
-- Debug
trace' :: (Show a) => a -> a
trace' x = trace (x.show) x
| nfjinjing/mps | src/MPS/Light.hs | bsd-3-clause | 7,411 | 5 | 12 | 1,842 | 4,263 | 2,393 | 1,870 | -1 | -1 |
module T492 where
import Data.Functor.Const
import Data.Functor.Const.Singletons
import Data.Proxy
import Data.Proxy.Singletons
import Prelude.Singletons hiding (Const, ConstSym0, ConstSym1)
f :: Const Bool Ordering
f = Const @Bool @Ordering True
sF1 :: SConst ('Const @Bool @Ordering True)
sF1 = SConst @Bool @Ordering STrue
sF2 :: SConst (ConstSym0 @Bool @Ordering @@ True)
sF2 = singFun1 @(ConstSym0 @Bool @Ordering) SConst @@ STrue
sF3 :: SConst (ConstSym1 @Bool @Ordering True)
sF3 = SConst @Bool @Ordering STrue
sP1 :: SProxy ('Proxy @Bool)
sP1 = SProxy @Bool
sP2 :: SProxy (ProxySym0 @Bool)
sP2 = SProxy @Bool
| goldfirere/singletons | singletons-base/tests/compile-and-dump/Singletons/T492.hs | bsd-3-clause | 624 | 7 | 7 | 96 | 176 | 110 | 66 | -1 | -1 |
{-# LANGUAGE PackageImports #-}
module GHC.IO.Buffer (module M) where
import "base" GHC.IO.Buffer as M
| silkapp/base-noprelude | src/GHC/IO/Buffer.hs | bsd-3-clause | 108 | 0 | 4 | 18 | 23 | 17 | 6 | 3 | 0 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2014 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE Safe #-}
{-# LANGUAGE PatternGuards #-}
module Cryptol.Eval (
moduleEnv
, EvalEnv()
, emptyEnv
, evalExpr
, evalDecls
, EvalError(..)
, WithBase(..)
) where
import Cryptol.Eval.Error
import Cryptol.Eval.Env
import Cryptol.Eval.Type
import Cryptol.Eval.Value
import Cryptol.TypeCheck.AST
import Cryptol.Utils.Panic (panic)
import Cryptol.Utils.PP
import Cryptol.Prims.Eval
import Data.List (transpose)
import Data.Monoid (Monoid(..),mconcat)
import qualified Data.Map as Map
-- Expression Evaluation -------------------------------------------------------
moduleEnv :: Module -> EvalEnv -> EvalEnv
moduleEnv m env = evalDecls (mDecls m) (evalNewtypes (mNewtypes m) env)
evalExpr :: EvalEnv -> Expr -> Value
evalExpr env expr = case expr of
ECon con -> evalECon con
EList es ty -> evalList env es (evalType env ty)
ETuple es -> VTuple (map eval es)
ERec fields -> VRecord [ (f,eval e) | (f,e) <- fields ]
ESel e sel -> evalSel env e sel
EIf c t f | fromVBit (eval c) -> eval t
| otherwise -> eval f
EComp l h gs -> evalComp env (evalType env l) h gs
EVar n -> case lookupVar n env of
Just val -> val
Nothing -> panic "[Eval] evalExpr"
["var `" ++ show (pp n) ++ "` is not defined"
, pretty (WithBase defaultPPOpts env)
]
ETAbs tv b -> VPoly $ \ty -> evalExpr (bindType (tpVar tv) ty env) b
ETApp e ty -> case eval e of
VPoly f -> f (evalType env ty)
val -> panic "[Eval] evalExpr"
["expected a polymorphic value"
, show (ppV val), show e, show ty
]
EApp f x -> case eval f of
VFun f' -> f' (eval x)
it -> panic "[Eval] evalExpr" ["not a function", show (ppV it) ]
EAbs n _ty b -> VFun (\ val -> evalExpr (bindVar n val env) b )
-- XXX these will likely change once there is an evidence value
EProofAbs _ e -> evalExpr env e
EProofApp e -> evalExpr env e
ECast e _ty -> evalExpr env e
EWhere e ds -> evalExpr (evalDecls ds env) e
where
eval = evalExpr env
ppV = ppValue defaultPPOpts
-- Newtypes --------------------------------------------------------------------
evalNewtypes :: Map.Map QName Newtype -> EvalEnv -> EvalEnv
evalNewtypes nts env = Map.foldl (flip evalNewtype) env nts
-- | Introduce the constructor function for a newtype.
evalNewtype :: Newtype -> EvalEnv -> EvalEnv
evalNewtype nt = bindVar (ntName nt) (foldr tabs con (ntParams nt))
where
tabs _tp body = tlam (\ _ -> body)
con = VFun id
-- Declarations ----------------------------------------------------------------
evalDecls :: [DeclGroup] -> EvalEnv -> EvalEnv
evalDecls dgs env = foldl (flip evalDeclGroup) env dgs
evalDeclGroup :: DeclGroup -> EvalEnv -> EvalEnv
evalDeclGroup dg env = env'
where
-- the final environment is passed in for each declaration, to permit
-- recursive values.
env' = case dg of
Recursive ds -> foldr (evalDecl env') env ds
NonRecursive d -> evalDecl env d env
evalDecl :: ReadEnv -> Decl -> EvalEnv -> EvalEnv
evalDecl renv d = bindVar (dName d) (evalExpr renv (dDefinition d))
-- Selectors -------------------------------------------------------------------
evalSel :: ReadEnv -> Expr -> Selector -> Value
evalSel env e sel = case sel of
TupleSel n _ -> tupleSel n val
RecordSel n _ -> recordSel n val
ListSel ix _ -> fromSeq val !! ix
where
val = evalExpr env e
tupleSel n v =
case v of
VTuple vs -> vs !! n
VSeq False vs -> VSeq False [ tupleSel n v1 | v1 <- vs ]
VStream vs -> VStream [ tupleSel n v1 | v1 <- vs ]
VFun f -> VFun (\x -> tupleSel n (f x))
_ -> evalPanic "Cryptol.Eval.evalSel"
[ "Unexpected value in tuple selection"
, show (ppValue defaultPPOpts v) ]
recordSel n v =
case v of
VRecord {} -> lookupRecord n v
VSeq False vs -> VSeq False [ recordSel n v1 | v1 <- vs ]
VStream vs -> VStream [recordSel n v1 | v1 <- vs ]
VFun f -> VFun (\x -> recordSel n (f x))
_ -> evalPanic "Cryptol.Eval.evalSel"
[ "Unexpected value in record selection"
, show (ppValue defaultPPOpts v) ]
-- List Comprehensions ---------------------------------------------------------
-- | Evaluate a comprehension.
evalComp :: ReadEnv -> TValue -> Expr -> [[Match]] -> Value
evalComp env seqty body ms
| Just (len,el) <- isTSeq seqty = toSeq len el [ evalExpr e body | e <- envs ]
| otherwise = evalPanic "Cryptol.Eval" [ "evalComp given a non sequence"
, show seqty
]
-- XXX we could potentially print this as a number if the type was available.
where
-- generate a new environment for each iteration of each parallel branch
benvs = map (branchEnvs env) ms
-- take parallel slices of each environment. when the length of the list
-- drops below the number of branches, one branch has terminated.
allBranches es = length es == length ms
slices = takeWhile allBranches (transpose benvs)
-- join environments to produce environments at each step through the process.
envs = map mconcat slices
-- | Turn a list of matches into the final environments for each iteration of
-- the branch.
branchEnvs :: ReadEnv -> [Match] -> [EvalEnv]
branchEnvs env matches = case matches of
m:ms -> do
env' <- evalMatch env m
branchEnvs env' ms
[] -> return env
-- | Turn a match into the list of environments it represents.
evalMatch :: EvalEnv -> Match -> [EvalEnv]
evalMatch env m = case m of
-- many envs
From n _ty expr -> do
e <- fromSeq (evalExpr env expr)
return (bindVar n e env)
-- XXX we don't currently evaluate these as though they could be recursive, as
-- they are typechecked that way; the read environment to evalDecl is the same
-- as the environment to bind a new name in.
Let d -> [evalDecl env d env]
-- Lists -----------------------------------------------------------------------
-- | Evaluate a list literal, optionally packing them into a word.
evalList :: EvalEnv -> [Expr] -> TValue -> Value
evalList env es ty = toPackedSeq w ty (map (evalExpr env) es)
where
w = TValue $ tNum $ length es
| TomMD/cryptol | src/Cryptol/Eval.hs | bsd-3-clause | 6,621 | 0 | 17 | 1,770 | 1,889 | 951 | 938 | 120 | 19 |
module Core.FreeVars where
import Core.Syntax
import Utilities
import qualified Data.Set as S
type FreeVars = S.Set Var
type BoundVars = S.Set Var
deleteList :: Ord a => [a] -> S.Set a -> S.Set a
deleteList = flip $ foldr S.delete
termFreeVars :: Term -> FreeVars
termFreeVars (Term e) = termFreeVars' termFreeVars e
taggedTermFreeVars :: TaggedTerm -> FreeVars
taggedTermFreeVars (TaggedTerm (Tagged _ e)) = termFreeVars' taggedTermFreeVars e
termFreeVars' :: (term -> FreeVars) -> TermF term -> FreeVars
termFreeVars' _ (Var x) = S.singleton x
termFreeVars' term (Value v) = valueFreeVars' term v
termFreeVars' term (App e x) = S.insert x $ term e
termFreeVars' term (PrimOp _ es) = S.unions $ map term es
termFreeVars' term (Case e alts) = term e `S.union` altsFreeVars' term alts
termFreeVars' term (LetRec xes e) = deleteList xs $ S.unions (map term es) `S.union` term e
where (xs, es) = unzip xes
altConOpenFreeVars :: AltCon -> (BoundVars, FreeVars) -> (BoundVars, FreeVars)
altConOpenFreeVars (DataAlt _ xs) (bvs, fvs) = (bvs `S.union` S.fromList xs, fvs)
altConOpenFreeVars (LiteralAlt _) (bvs, fvs) = (bvs, fvs)
altConOpenFreeVars (DefaultAlt mb_x) (bvs, fvs) = (maybe id S.insert mb_x bvs, fvs)
altConFreeVars :: AltCon -> FreeVars -> FreeVars
altConFreeVars (DataAlt _ xs) = deleteList xs
altConFreeVars (LiteralAlt _) = id
altConFreeVars (DefaultAlt mb_x) = maybe id S.delete mb_x
altFreeVars :: Alt -> FreeVars
altFreeVars = altFreeVars' termFreeVars
altFreeVars' :: (term -> FreeVars) -> AltF term -> FreeVars
altFreeVars' term (altcon, e) = altConFreeVars altcon $ term e
altsFreeVars :: [Alt] -> FreeVars
altsFreeVars = altsFreeVars' termFreeVars
taggedAltsFreeVars :: [TaggedAlt] -> FreeVars
taggedAltsFreeVars = altsFreeVars' taggedTermFreeVars
altsFreeVars' :: (term -> FreeVars) -> [AltF term] -> FreeVars
altsFreeVars' term = S.unions . map (altFreeVars' term)
valueFreeVars :: Value -> FreeVars
valueFreeVars = valueFreeVars' termFreeVars
taggedValueFreeVars :: TaggedValue -> FreeVars
taggedValueFreeVars = valueFreeVars' taggedTermFreeVars
valueFreeVars' :: (term -> FreeVars) -> ValueF term -> FreeVars
valueFreeVars' term (Lambda x e) = S.delete x $ term e
valueFreeVars' _ (Data _ xs) = S.fromList xs
valueFreeVars' _ (Literal _) = S.empty
| batterseapower/supercompilation-by-evaluation | Core/FreeVars.hs | bsd-3-clause | 2,331 | 0 | 9 | 396 | 866 | 447 | 419 | 46 | 1 |
module Graphics.Ascii.Haha.Bitmap where
import qualified Data.Map as M
import Prelude hiding (filter)
import Graphics.Ascii.Haha.Geometry
--------[ image data type ]----------------------------------------------------
data Bitmap u p = Bitmap { bits :: M.Map (Point u) p }
deriving (Show, Eq)
withBits :: (M.Map (Point u) p -> M.Map (Point v) q) -> Bitmap u p -> Bitmap v q
withBits f = Bitmap . f . bits
empty :: Bitmap u p
empty = Bitmap M.empty
get :: Ord u => Point u -> Bitmap u p -> Maybe p
get p img = M.lookup p (bits img)
put :: Ord u => Point u -> p -> Bitmap u p -> Bitmap u p
put p px = withBits (M.insert p px)
erase :: Ord u => Point u -> Bitmap u p -> Bitmap u p
erase p = withBits (M.delete p)
--mapPt :: (Point u -> p -> q) -> Bitmap u p -> Bitmap u q
mapPoints :: (Ord v) => (Point u -> Point v) -> Bitmap u p -> Bitmap v p
mapPoints f = withBits (M.mapKeys f)
{-mapPt :: (Point u -> p -> q) -> Bitmap u p -> Bitmap u q
mapPt f = withBits (M.mapWithKey f)
mapPtMaybe :: Ord u => (Point u -> p -> Maybe q) -> Bitmap u p -> Bitmap u q
mapPtMaybe f = withBits (M.mapMaybeWithKey f)-}
filterPt :: Ord u => (Point u -> p -> Bool) -> Bitmap u p -> Bitmap u p
filterPt f = withBits (M.filterWithKey f)
toList :: Bitmap u p -> [(Point u, p)]
toList = M.toAscList . bits
{-
fromList = Bitmap . M.fromList
points = M.keys . gr
filter = withBits . M.filter
filterWithKey = withBits . M.filterWithKey
member x = M.member x . gr-}
instance Functor (Bitmap u) where
fmap = withBits . M.map
{-instance Monoid (Bitmap a) where
mempty = empty
mappend x y = Bitmap $ M.union (bits x) (bits y)-}
--------[ clipping and sub-imaging ]-------------------------------------------
clip :: Ord u => Rect u -> Bitmap u p -> Bitmap u p
clip r img = filterPt (\p _ -> inRect p r) img
--------[ primitive drawing on the bits ]--------------------------------------
drawPoint :: Ord u => Point u -> p -> Bitmap u p -> Bitmap u p
drawPoint = put
drawList :: Ord u => [Point u] -> p -> Bitmap u p -> Bitmap u p
drawList l v g = foldr (flip drawPoint v) g l
drawLine :: (Fractional u, Ord u, Enum u) => Line u -> p -> Bitmap u p -> Bitmap u p
drawLine (Line (Point x0 y0) (Point x1 y1))
| xIsY = drawPoint (Point x0 y0)
| xOrY = drawList [Point s (y0 + (s - x0) * (y1 - y0) / (x1 - x0)) | s <- range x0 x1 ]
| True = drawList [Point (x0 + (s - y0) * (x1 - x0) / (y1 - y0)) s | s <- range y0 y1 ]
where
xIsY = x0 == x1 && y0 == y1
xOrY = abs (x1-x0) > abs (y1-y0)
range f t = if f < t then [f .. t] else reverse [t .. f]
drawPoly :: (Fractional u, Ord u, Enum u) => Poly u -> p -> Bitmap u p -> Bitmap u p
drawPoly (Poly (a:b:xs)) v =
drawLine (Line a b) v
. drawPoly (Poly (b:xs)) v
drawPoly _ _ = id
drawElipse :: (Floating u, Ord u, Enum u) => Elipse u -> u -> p -> Bitmap u p -> Bitmap u p
drawElipse (Elipse (Point x y) rx ry) s = drawPoly $ Poly
[ Point (x + rx * cos (2 * pi / s * t))
(y + ry * sin (2 * pi / s * t))
| t <- [0 .. s]]
drawCircle :: (Floating u, Ord u, Enum u) => Circle u -> u -> p -> Bitmap u p -> Bitmap u p
drawCircle (Circle p r) = drawElipse $ Elipse p r r
drawRect :: (Ord u, Enum u) => Rect u -> p -> Bitmap u p -> Bitmap u p
drawRect (Rect (Point x0 y0) (Point x1 y1)) = drawList
[Point x y | x <- [x0 .. x1], y <- [y0 .. y1]]
--------[ layers and masks functions ]-----------------------------------------
{-drawLayers :: [Bitmap p] -> Bitmap p
drawLayers = Bitmap . M.unions . map bits
drawMask :: Bitmap p -> Bitmap q -> Bitmap p
drawMask g m = mapPtMaybe (\p _ -> get p g) m-}
| sebastiaanvisser/haha | src/Graphics/Ascii/Haha/Bitmap.hs | bsd-3-clause | 3,583 | 0 | 15 | 848 | 1,515 | 763 | 752 | 53 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
-----------------------------------------------------------------------------
-- |
-- Module :
-- Copyright :
-- License :
--
-- Maintainer :
-- Stability : experimental
--
-- Emulate all hadoop operations locally
----------------------------------------------------------------------------
module Hadron.Run.Local where
-------------------------------------------------------------------------------
import Control.Applicative
import Control.Error
import Control.Lens
import Control.Monad.Reader
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Char8 as B
import Data.Conduit
import Data.Conduit.Binary (sourceFile)
import Data.Default
import Data.Hashable
import Data.List
import Data.Monoid
import System.Directory
import System.Environment
import System.Exit
import System.FilePath.Glob
import System.FilePath.Lens
import System.FilePath.Posix
import System.IO
import System.Process
-------------------------------------------------------------------------------
import Hadron.Logger
import Hadron.Run.FanOut
import qualified Hadron.Run.Hadoop as H
import Hadron.Utils
-------------------------------------------------------------------------------
#if MIN_VERSION_base(4, 7, 0)
#else
import System.Posix.Env
#endif
newtype LocalFile = LocalFile { _unLocalFile :: FilePath }
deriving (Eq,Show,Read,Ord)
makeLenses ''LocalFile
data LocalRunSettings = LocalRunSettings {
_lrsTempPath :: FilePath
-- ^ Root of the "file system" during a localrun
}
makeLenses ''LocalRunSettings
instance Default LocalRunSettings where
def = LocalRunSettings "tmp"
type Local = ReaderT LocalRunSettings IO
runLocal :: r -> ReaderT r m a -> m a
runLocal env f = runReaderT f env
-------------------------------------------------------------------------------
path :: (MonadIO m, MonadReader LocalRunSettings m) => LocalFile -> m FilePath
path (LocalFile fp) = do
root <- view lrsTempPath
let p = root </> fp
dir = p ^. directory
liftIO $ createDirectoryIfMissing True dir
return p
-------------------------------------------------------------------------------
getRecursiveDirectoryContents :: FilePath -> IO [FilePath]
getRecursiveDirectoryContents dir0 = go dir0
where
go dir = do
fs <- liftM (map (dir </>) . filter (not . flip elem [".", ".."])) $
getDirectoryContents' dir
fs' <- filterM (fmap not . doesDirectoryExist) fs
fss <- mapM go fs
return $ fs' ++ concat fss
-------------------------------------------------------------------------------
-- | A version that return [] instead of an error when directory does not exit.
getDirectoryContents' :: FilePath -> IO [FilePath]
getDirectoryContents' fp = do
chk <- doesDirectoryExist fp
case chk of
False -> return []
True -> getDirectoryContents fp
-------------------------------------------------------------------------------
-- | Recursive contents if given a directory, assumed glob pattern if not.
getInputFiles :: FilePath -> IO [FilePath]
getInputFiles fp = do
chk <- doesDirectoryExist fp
case chk of
True -> glob (fp </> "**")
False -> glob fp
-------------------------------------------------------------------------------
localMapReduce
:: MonadIO m
=> LocalRunSettings
-> String -- ^ MapReduceKey
-> String -- ^ RunToken
-> H.HadoopRunOpts
-> ExceptT String m ()
localMapReduce lrs mrKey token H.HadoopRunOpts{..} = do
exPath <- scriptIO getExecutablePath
echoInfo $ "Launching Hadoop job for MR key: " <> ls mrKey
expandedInput <- liftIO $ liftM concat $ forM _mrsInput $ \ inp ->
withLocalFile lrs (LocalFile inp) getInputFiles
let enableCompress = case _mrsCompress of
Nothing -> False
Just x -> isInfixOf "Gzip" x
-- Are the input files already compressed?
inputCompressed file = isInfixOf ".gz" file
outFile <- liftIO $ withLocalFile lrs (LocalFile _mrsOutput) $ \ fp ->
case fp ^. extension . to null of
False -> return fp
True -> do
createDirectoryIfMissing True fp
return $ fp </> ("0000.out" ++ if enableCompress then ".gz" else "")
let pipe = " | "
maybeCompress = if enableCompress
then pipe <> "gzip"
else ""
maybeGunzip fp = (if inputCompressed fp then ("gunzip" <> pipe) else "")
maybeReducer = case _mrsNumReduce of
Just 0 -> ""
_ -> pipe <> exPath <> " " <> token <> " " <> "reducer_" <> mrKey
-- map over each file individually and write results into a temp file
mapFile infile = clearExit . scriptIO . withTmpMapFile infile $ \ fp -> do
echoInfo ("Running command: " <> ls (command fp))
#if MIN_VERSION_base(4, 7, 0)
setEnv "mapreduce_map_input_file" infile
#else
setEnv "mapreduce_map_input_file" infile True
#endif
system (command fp)
where
command fp =
"cat " <> infile <> pipe <>
maybeGunzip infile <>
exPath <> " " <> token <> " " <> "mapper_" <> mrKey <>
" > " <> fp
-- a unique temp file for each input file
withTmpMapFile infile f = liftIO $
withLocalFile lrs (LocalFile ((show (hash infile)) <> "_mapout")) f
getTempMapFiles = mapM (flip withTmpMapFile return) expandedInput
-- concat all processed map output, sort and run through the reducer
reduceFiles = do
fs <- getTempMapFiles
echoInfo ("Running command: " <> ls (command fs))
scriptIO $ createDirectoryIfMissing True (outFile ^. directory)
clearExit $ scriptIO $ system (command fs)
where
command fs =
"cat " <> intercalate " " fs <> pipe <>
("sort -t$'\t' -k1," <> show (H.numSegs _mrsPart)) <>
maybeReducer <>
maybeCompress <>
" > " <> outFile
removeTempFiles = scriptIO $ do
fs <- getTempMapFiles
mapM_ removeFile fs
echoInfo "Mapping over individual local input files."
mapM_ mapFile expandedInput
echoInfo "Executing reduce stage."
reduceFiles
removeTempFiles
-------------------------------------------------------------------------------
echo :: (Applicative m, MonadIO m) => Severity -> LogStr -> m ()
echo sev msg = runLog $ logMsg "Local" sev msg
-------------------------------------------------------------------------------
echoInfo :: (Applicative m, MonadIO m) => LogStr -> m ()
echoInfo = echo InfoS
-------------------------------------------------------------------------------
-- | Fail if command not successful.
clearExit :: MonadIO m => ExceptT String m ExitCode -> ExceptT [Char] m ()
clearExit f = do
res <- f
case res of
ExitSuccess -> echoInfo "Command successful."
e -> do
echo ErrorS $ ls $ "Command failed: " ++ show e
hoistEither $ Left $ "Command failed with: " ++ show e
-------------------------------------------------------------------------------
-- | Check if the target file is present.
hdfsFileExists
:: (MonadIO m, MonadReader LocalRunSettings m)
=> LocalFile
-> m Bool
hdfsFileExists p = liftIO . chk =<< path p
where
chk fp = (||) <$> doesFileExist fp <*> doesDirectoryExist fp
-------------------------------------------------------------------------------
hdfsDeletePath
:: (MonadIO m, MonadReader LocalRunSettings m)
=> LocalFile
-> m ()
hdfsDeletePath p = do
fp <- path p
liftIO $ do
chk <- doesDirectoryExist fp
when chk (removeDirectoryRecursive fp)
chk2 <- doesFileExist fp
when chk2 (removeFile fp)
-------------------------------------------------------------------------------
hdfsLs
:: (MonadIO m, MonadReader LocalRunSettings m)
=> LocalFile -> m [File]
hdfsLs p = do
fs <- liftIO . getDirectoryContents' =<< path p
return $ map (File "" 1 "" "") $ map (_unLocalFile p </>) fs
-------------------------------------------------------------------------------
hdfsPut
:: (MonadIO m, MonadReader LocalRunSettings m)
=> LocalFile
-> LocalFile
-> m ()
hdfsPut src dest = do
src' <- path src
dest' <- path dest
liftIO $ copyFile src' dest'
-------------------------------------------------------------------------------
-- | Create a new multiple output file manager.
hdfsFanOut
:: (MonadIO m, MonadReader LocalRunSettings m)
=> FilePath
-- ^ Temporary file location.
-> m FanOut
hdfsFanOut tmp = do
env <- ask
liftIO $ mkFanOut (mkHandle env)
where
mkTmp fp = tmp </> fp
-- write into a temp file loc until we know the stage is
-- complete without failure
mkHandle env fp = do
fp' <- runLocal env $ path (LocalFile (mkTmp fp))
createDirectoryIfMissing True (fp' ^. directory)
h <- openFile fp' AppendMode
return (h, fin env fp)
-- move temp file to its final destination
fin env fp0 = do
temp <- runLocal env $ path (LocalFile (mkTmp fp0))
dest <- runLocal env $ path (LocalFile fp0)
createDirectoryIfMissing True (dest ^. directory)
renameFile temp dest
-------------------------------------------------------------------------------
hdfsMkdir
:: (MonadIO m, MonadReader LocalRunSettings m)
=> LocalFile
-> m ()
hdfsMkdir p = liftIO . createDirectoryIfMissing True =<< path p
-------------------------------------------------------------------------------
hdfsCat :: LocalFile -> Producer (ResourceT Local) B.ByteString
hdfsCat p = sourceFile =<< (lift . lift) (path p)
-------------------------------------------------------------------------------
hdfsGet
:: (MonadIO m, MonadReader LocalRunSettings m)
=> LocalFile
-> m LocalFile
hdfsGet fp = do
target <- randomFileName
hdfsPut fp target
return target
hdfsLocalStream :: LocalFile -> Producer (ResourceT Local) B.ByteString
hdfsLocalStream = hdfsCat
-------------------------------------------------------------------------------
randomFileName :: MonadIO m => m LocalFile
randomFileName = LocalFile `liftM` liftIO (randomToken 64)
-------------------------------------------------------------------------------
-- | Helper to work with relative paths using Haskell functions like
-- 'readFile' and 'writeFile'.
withLocalFile
:: MonadIO m
=> LocalRunSettings
-> LocalFile
-- ^ A relative path in our working folder
-> (FilePath -> m b)
-- ^ What to do with the absolute path.
-> m b
withLocalFile settings fp f = f =<< runLocal settings (path fp)
| dmjio/hadron | src/Hadron/Run/Local.hs | bsd-3-clause | 11,452 | 0 | 22 | 2,894 | 2,525 | 1,270 | 1,255 | -1 | -1 |
{-|
Module : $HEADER$
Description : Extra functions on List.
Copyright : (c) Justus Adam, 2015
License : BDS3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX, Windows
-}
{-# LANGUAGE UnicodeSyntax #-}
module Data.List.JAExtra
(
-- * Reading values
get
-- * Modifying lists
, slice, setIndex, setPred
-- * Tuple conversions
-- | \"to__N__Tuple\" functions match whether a list contains /only/ __N__
-- elements yielding an __N__-'Tuple' containing those elements.
--
-- This can for example also be used to extract elements from a section of the
-- list as a 'Tuple' like so:
--
-- > to3Tuple . take 3
, to1Value, to2Tuple, to3Tuple, to4Tuple, to5Tuple
, to6Tuple, to7Tuple, to8Tuple, to9Tuple, to10Tuple
-- * Zipping lists
-- | Zipping functions that do not stop when the shorter lists expire but when
-- the longer lists do.
-- ** Zipping to Maybe
-- | The fillZip__N__ function family takes __N__ lists and returns a list of
-- __N__-tuples.
--
-- Unlike 'zip' 'fillZip' does not stop when one of the lists is empty, but
-- keeps going inserting 'Nothing' for the missing values in the shorter lists.
, fillZip, fillZip2, fillZip3, fillZip4, fillZip5
-- ** Zipping Monoids
-- | The monoidFillZip__N__ function family takes __N__ lists and returns a
-- list of __N__-tuples.
--
-- Unlike 'zip', 'monoidFillZip' does not stop when one of the lists is empty,
-- but keeps going inserting 'mempty' for the missing values in the shorter
-- lists.
, monoidFillZip, monoidFillZip2, monoidFillZip3, monoidFillZip4, monoidFillZip5
) where
import Control.Monad
import Data.List
import Data.Monoid
import Data.Tuple.JAExtra
{-|
Completeness function that converts a singleton list into its only contained value.
This function is the single value version of the \"to__N__Tuple\" function family.
-}
to1Value ∷ [α] → Maybe α
to1Value [a] = return a
to1Value _ = Nothing
{-# INLINE to1Value #-}
to2Tuple ∷ [α] → Maybe (α, α)
to2Tuple [a1, a2] = return (a1, a2)
to2Tuple _ = Nothing
{-# INLINE to2Tuple #-}
to3Tuple ∷ [α] → Maybe (α, α, α)
to3Tuple [a1, a2, a3] = return (a1, a2, a3)
to3Tuple _ = Nothing
{-# INLINE to3Tuple #-}
to4Tuple ∷ [α] → Maybe (α, α, α, α)
to4Tuple [a1, a2, a3, a4] = return (a1, a2, a3, a4)
to4Tuple _ = Nothing
{-# INLINE to4Tuple #-}
to5Tuple ∷ [α] → Maybe (α, α, α, α, α)
to5Tuple [a1, a2, a3, a4, a5] = return (a1, a2, a3, a4, a5)
to5Tuple _ = Nothing
{-# INLINE to5Tuple #-}
to6Tuple ∷ [α] → Maybe (α, α, α, α, α, α)
to6Tuple [a1, a2, a3, a4, a5, a6] = return (a1, a2, a3, a4, a5, a6)
to6Tuple _ = Nothing
{-# INLINE to6Tuple #-}
to7Tuple ∷ [α] → Maybe (α, α, α, α, α, α, α)
to7Tuple [a1, a2, a3, a4, a5, a6, a7] = return (a1, a2, a3, a4, a5, a6, a7)
to7Tuple _ = Nothing
{-# INLINE to7Tuple #-}
to8Tuple ∷ [α] → Maybe (α, α, α, α, α, α, α, α)
to8Tuple [a1, a2, a3, a4, a5, a6, a7, a8] =
return (a1, a2, a3, a4, a5, a6, a7, a8)
to8Tuple _ = Nothing
{-# INLINE to8Tuple #-}
to9Tuple ∷ [α] → Maybe (α, α, α, α, α, α, α, α, α)
to9Tuple [a1, a2, a3, a4, a5, a6, a7, a8, a9] =
return (a1, a2, a3, a4, a5, a6, a7, a8, a9)
to9Tuple _ = Nothing
{-# INLINE to9Tuple #-}
to10Tuple ∷ [α] → Maybe (α, α, α, α, α, α, α, α, α, α)
to10Tuple [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10] =
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)
to10Tuple _ = Nothing
{-# INLINE to10Tuple #-}
{-|
The function that '!!' should be.
The 'get' function attempts to extract the element at the specified index from
the list, but instead of failing with an error returns a 'Maybe' value.
>>> get 0 [1, 2, 3]
Just 1
>>> get 2 [1, 2, 3]
Just 3
>>> get 3 [1, 2, 3]
Nothing
This function also accepts negative indexes, taking elements from the back of
the list, aka @get (-1)@ is the last element of the list and @get (-2)@ the
second to last.
Both positive and negative indexes are subject to boundary checks.
>>> get -1 [1, 2, 3]
Just 3
>>> get -4 [1, 2, 3]
Nothing
For infinite lists using negative indexes is _|_ (does not terminate).
Positive indexes do however do work with infinite lists.
-}
get ∷ Int → [α] → Maybe α
get index
| index >= 0 = get' index
| otherwise = get' (-index) . reverse
where
get' 0 (x:_) = return x
get' _ [] = mzero
get' i (_:xs) = (i-1) `get'` xs
{-|
@slice i j@ extracts a sublist from index i up to, but not including, j.
This function also accepts negative indexes which, again, are _|_ for infinite
lists.
>>> slice 1 3 [1, 2, 3, 4, 5]
[2, 3]
The index rules are the same as with 'get'.
-}
slice ∷ Int → Int → [α] → [α]
slice start end list = take (end' - start') $ drop start' list
where
len = length list
turn i
| i < 0 =
if (-i) >= len
then 0
else len + i
| otherwise = i
end'= turn end
start'= turn start
{-# INLINEABLE slice #-}
monoidFillZip2 ∷ (Monoid α, Monoid β) ⇒ [α] → [β] → [(α, β)]
monoidFillZip2 [] ys = zip (repeat mempty) ys
monoidFillZip2 xs [] = zip xs (repeat mempty)
monoidFillZip2 (x:xs) (y:ys) = (x, y) : monoidFillZip2 xs ys
monoidFillZip3 ∷ (Monoid α, Monoid β, Monoid γ) ⇒ [α] → [β] → [γ] → [(α, β, γ)]
monoidFillZip3 [] ys zs =
uncurry (zip3 (repeat mempty)) $ unzip $ monoidFillZip2 ys zs
monoidFillZip3 xs [] zs = zip3 xs' (repeat mempty) zs'
where (xs', zs') = unzip $ monoidFillZip2 xs zs
monoidFillZip3 xs ys [] =
uncurry zip3 (unzip $ monoidFillZip2 xs ys) (repeat mempty)
monoidFillZip3 (x:xs) (y:ys) (z:zs) = (x, y, z) : monoidFillZip3 xs ys zs
monoidFillZip4 ∷ (Monoid α, Monoid β, Monoid γ, Monoid δ) ⇒
[α] → [β] → [γ] → [δ] → [(α, β, γ, δ)]
monoidFillZip4 [] bs cs ds =
uncurry3 (zip4 (repeat mempty)) $ unzip3 $ monoidFillZip3 bs cs ds
monoidFillZip4 as [] cs ds = zip4 as' (repeat mempty) cs' ds'
where (as', cs', ds') = unzip3 $ monoidFillZip3 as cs ds
monoidFillZip4 as bs [] ds = zip4 as' bs' (repeat mempty) ds'
where (as', bs', ds') = unzip3 $ monoidFillZip3 as bs ds
monoidFillZip4 as bs cs [] =
uncurry3 zip4 (unzip3 $ monoidFillZip3 as bs cs) (repeat mempty)
monoidFillZip4 (a:as) (b:bs) (c:cs) (d:ds) =
(a, b, c, d) : monoidFillZip4 as bs cs ds
monoidFillZip5 ∷ (Monoid α, Monoid β, Monoid γ, Monoid δ, Monoid ζ) ⇒
[α] → [β] → [γ] → [δ] → [ζ] → [(α, β, γ, δ, ζ)]
monoidFillZip5 [] bs cs ds es =
uncurry4 (zip5 (repeat mempty)) $ unzip4 $ monoidFillZip4 bs cs ds es
monoidFillZip5 as [] cs ds es = zip5 as' (repeat mempty) cs' ds' es'
where (as', cs', ds', es') = unzip4 $ monoidFillZip4 as cs ds es
monoidFillZip5 as bs [] ds es = zip5 as' bs' (repeat mempty) ds' es'
where (as', bs', ds', es') = unzip4 $ monoidFillZip4 as bs ds es
monoidFillZip5 as bs cs [] es = zip5 as' bs' cs' (repeat mempty) es'
where (as', bs', cs', es') = unzip4 $ monoidFillZip4 as bs cs es
monoidFillZip5 as bs cs ds [] =
uncurry4 zip5 (unzip4 $ monoidFillZip4 as bs cs ds) (repeat mempty)
monoidFillZip5 (a:as) (b:bs) (c:cs) (d:ds) (e:es) =
(a, b, c, d, e) : monoidFillZip5 as bs cs ds es
{-|
Alias for 'monoidFillZip2'.
-}
monoidFillZip ∷ (Monoid α, Monoid β) ⇒ [α] → [β] → [(α, β)]
monoidFillZip = monoidFillZip2
fillZip2 ∷ [α] → [β] → [(Maybe α, Maybe β)]
fillZip2 [] ys = zip (repeat mzero) (map return ys)
fillZip2 xs [] = zip (map return xs) (repeat mzero)
fillZip2 (x:xs) (y:ys) = (return x, return y) : fillZip2 xs ys
fillZip3 ∷ [α] → [β] → [γ] → [(Maybe α, Maybe β, Maybe γ)]
fillZip3 [] ys zs = uncurry (zip3 (repeat mzero)) $ unzip $ fillZip2 ys zs
fillZip3 xs [] zs = zip3 xs' (repeat mzero) zs'
where (xs', zs') = unzip $ fillZip2 xs zs
fillZip3 xs ys [] = uncurry zip3 (unzip $ fillZip2 xs ys) (repeat mzero)
fillZip3 (x:xs) (y:ys) (z:zs) =
(return x, return y, return z) : fillZip3 xs ys zs
fillZip4 ∷ [α] → [β] → [γ] → [δ] → [(Maybe α, Maybe β, Maybe γ, Maybe δ)]
fillZip4 [] bs cs ds =
uncurry3 (zip4 (repeat mzero)) $ unzip3 $ fillZip3 bs cs ds
fillZip4 as [] cs ds = zip4 as' (repeat mzero) cs' ds'
where (as', cs', ds') = unzip3 $ fillZip3 as cs ds
fillZip4 as bs [] ds = zip4 as' bs' (repeat mzero) ds'
where (as', bs', ds') = unzip3 $ fillZip3 as bs ds
fillZip4 as bs cs [] = uncurry3 zip4 (unzip3 $ fillZip3 as bs cs) (repeat mzero)
fillZip4 (a:as) (b:bs) (c:cs) (d:ds) =
(return a, return b, return c, return d) : fillZip4 as bs cs ds
fillZip5 ∷ [α] → [β] → [γ] → [δ] → [ζ] →
[(Maybe α, Maybe β, Maybe γ, Maybe δ, Maybe ζ)]
fillZip5 [] bs cs ds es =
uncurry4 (zip5 (repeat mzero)) $ unzip4 $ fillZip4 bs cs ds es
fillZip5 as [] cs ds es = zip5 as' (repeat mzero) cs' ds' es'
where (as', cs', ds', es') = unzip4 $ fillZip4 as cs ds es
fillZip5 as bs [] ds es = zip5 as' bs' (repeat mzero) ds' es'
where (as', bs', ds', es') = unzip4 $ fillZip4 as bs ds es
fillZip5 as bs cs [] es = zip5 as' bs' cs' (repeat mzero) es'
where (as', bs', cs', es') = unzip4 $ fillZip4 as bs cs es
fillZip5 as bs cs ds [] =
uncurry4 zip5 (unzip4 $ fillZip4 as bs cs ds) (repeat mzero)
fillZip5 (a:as) (b:bs) (c:cs) (d:ds) (e:es) =
(return a, return b, return c, return d, return e) : fillZip5 as bs cs ds es
{-|
Alias for 'fillZip2'.
-}
fillZip ∷ [α] → [β] → [(Maybe α, Maybe β)]
fillZip = fillZip2
{-|
Set the element at a specific index in a list.
Accepts negative indexes, in which case the index is counted from the end of
the list (last element == -1).
Fails if | index | >= length of the list.
-}
setIndex :: Int -> a -> [a] -> Maybe [a]
setIndex i e l
| i < 0 = if (- i) > length l
then Nothing
else setIndex (length l + i) e l
| i == 0 = Just (e:l)
| otherwise =
case rest of
(_:tail') -> Just (head' ++ (e:tail'))
_ -> Nothing
where
(head', rest) = splitAt i l
{-|
Replace the first element in the list, for which the predicate holds true.
-}
setPred :: (a -> Bool) -> a -> [a] -> Maybe [a]
setPred predicate e l =
case rest of
(_:tail') -> Just (head' ++ (e:tail'))
_ -> Nothing
where
(head', rest) = break predicate l
| JustusAdam/ja-base-extra | src/Data/List/JAExtra.hs | bsd-3-clause | 10,433 | 0 | 13 | 2,428 | 3,987 | 2,171 | 1,816 | 168 | 3 |
-- !!! Conflicting re-exportation of dcon
module M (module Mod143_A,module M) where
import Mod143_A -- yes, this is intentionally Mod143_A
data Foo1 = Bar
| FranklinChen/Hugs | tests/static/mod144.hs | bsd-3-clause | 158 | 0 | 5 | 27 | 26 | 18 | 8 | 3 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Uninterpreted.Sort
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Test suite for uninterpreted sorts
-----------------------------------------------------------------------------
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ScopedTypeVariables #-}
module TestSuite.Uninterpreted.Sort where
import Data.SBV
import SBVTest
import Data.Generics
-- Test suite
testSuite :: SBVTestSuite
testSuite = mkTestSuite $ \_ -> test [
"unint-sort" ~: assert . (==4) . length . (extractModels :: AllSatResult -> [L]) =<< allSat p0
]
data L = Nil | Cons Int L deriving (Eq, Ord, Data, Typeable, Read, Show)
instance SymWord L
instance HasKind L
instance SatModel L where
parseCWs = undefined -- make GHC shut up about the missing method, we won't actually call it
type SList = SBV L
len :: SList -> SInteger
len = uninterpret "len"
p0 :: Symbolic SBool
p0 = do
[l, l0, l1] <- symbolics ["l", "l0", "l1"]
constrain $ len l0 .== 0
constrain $ len l1 .== 1
x :: SInteger <- symbolic "x"
constrain $ x .== 0 ||| x.== 1
return $ l .== l0 ||| l .== l1
| Copilot-Language/sbv-for-copilot | SBVUnitTest/TestSuite/Uninterpreted/Sort.hs | bsd-3-clause | 1,265 | 0 | 13 | 243 | 314 | 171 | 143 | -1 | -1 |
module Common (assert, datadir, getTestContext, KeyDirections(..), testKeySeq, ks) where
import Data.Maybe
import Control.Monad
import Text.XkbCommon
assert :: Bool -> String -> IO ()
assert False str = ioError (userError str)
assert _ _ = return ()
datadir = "data/"
getTestContext :: IO Context
getTestContext = do
ctx <- liftM fromJust $ newContext pureFlags
appendIncludePath ctx datadir
return ctx
data KeyDirections = Down | Up | Both | Repeat deriving (Show, Eq)
testKeySeq :: Keymap -> [(CKeycode, KeyDirections, Keysym)] -> IO [()]
testKeySeq km tests = do
st <- newKeyboardState km
return =<< mapM (testOne st) (zip tests [1..]) where
testOne st ((kc, dir, ks),n) = do
syms <- getStateSyms st kc
when (dir == Down || dir == Both) $ void (updateKeyboardStateKey st kc keyDown)
when (dir == Up || dir == Both) $ void (updateKeyboardStateKey st kc keyUp)
-- in this test, we always get exactly one keysym
assert (length syms == 1) "did not get right amount of keysyms"
assert (head syms == ks) ("did not get correct keysym " ++ show ks
++ " for keycode " ++ show kc
++ ", got " ++ show (head syms)
++ " in test " ++ show n)
-- this probably doesn't do anything since if we came this far, head syms == ks
assert (keysymName (head syms) == keysymName ks) ("keysym names differ: " ++ keysymName (head syms) ++ " and " ++ keysymName ks)
putStrLn $ keysymName ks
return ()
ks = fromJust.keysymFromName
| abooij/haskell-xkbcommon | tests/Common.hs | mit | 1,633 | 0 | 18 | 475 | 534 | 267 | 267 | 31 | 1 |
module Network.Slack.User
(
User(..),
users,
userFromId,
userFromName
)
where
import Network.Slack.Types (User(..), Slack(..), users)
import Data.List (find)
import Text.Printf (printf)
import Control.Applicative ((<$>))
import Control.Monad.Trans.Either (hoistEither)
-- |Converts a user ID to a user object, signaling an error if there's no such user ID
userFromId :: String -> Slack User
userFromId uid = do
maybeUser <- find (\u -> userId u == uid) <$> users :: Slack (Maybe User)
case maybeUser of
Nothing -> Slack . hoistEither . Left . printf "Could not find user with id: %s" $ uid
Just user -> Slack . hoistEither $ Right user
-- | Converts a user name to a user object, signaling an error if there's no such user name
userFromName :: String -> Slack User
userFromName uname = do
maybeUser <- find (\u -> userName u == uname) <$> users :: Slack (Maybe User)
case maybeUser of
Nothing -> Slack . hoistEither . Left . printf "Could not find user with name: %s" $ uname
Just user -> Slack . hoistEither $ Right user
| BeautifulDestinations/slack | Network/Slack/User.hs | mit | 1,109 | 0 | 13 | 260 | 322 | 172 | 150 | 23 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- |
-- Module: Aws.Sns.Commands.SetTopicAttributes
-- Copyright: Copyright © 2014 AlephCloud Systems, Inc.
-- License: MIT
-- Maintainer: Lars Kuhtz <[email protected]>
-- Stability: experimental
--
-- /API Version: 2013-03-31/
--
-- Allows a topic owner to set an attribute of the topic to a new value.
--
-- <http://docs.aws.amazon.com/sns/2010-03-31/api/API_SetTopicAttributes.html>
--
module Aws.Sns.Commands.SetTopicAttributes
( MutableTopicAttribute
, SetTopicAttributes(..)
, SetTopicAttributesResponse(..)
, SetTopicAttributesErrors(..)
) where
import Aws.Core
import Aws.General
import Aws.Sns.Core
import Aws.Sns.Types
import Aws.Sns.Policy
import Control.Applicative
import Data.Aeson (ToJSON, encode)
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Typeable
import qualified Network.HTTP.Types as HTTP
-- -------------------------------------------------------------------------- --
-- Mutable Topic Attribute
data MutableTopicAttribute
= MutableTopicAttributePolicy (Maybe SnsPolicy)
| MutableTopicAttributeDisplayName (Maybe T.Text)
| MutableTopicAttributeDeliveryPolicy (Maybe DeliveryPolicy)
deriving (Show, Eq, Typeable)
mutableTopicAttributeQuery :: MutableTopicAttribute -> HTTP.QueryText
mutableTopicAttributeQuery (MutableTopicAttributePolicy v) =
[ ("AttributeName", Just "Policy")
, ("AttributeValue", fmap encodeTextStrict v)
]
mutableTopicAttributeQuery (MutableTopicAttributeDisplayName v) =
[ ("AttributeName", Just "DisplayName")
, ("AttributeValue", v)
]
mutableTopicAttributeQuery (MutableTopicAttributeDeliveryPolicy v) =
[ ("AttributeName", Just "DeliveryPolicy")
, ("AttributeValue", fmap encodeTextStrict v)
]
encodeTextStrict :: ToJSON a => a -> T.Text
encodeTextStrict = T.decodeUtf8 . LB.toStrict . encode
-- -------------------------------------------------------------------------- --
-- SetTopicAttributes
setTopicAttributesAction :: SnsAction
setTopicAttributesAction = SnsActionSetTopicAttributes
data SetTopicAttributes = SetTopicAttributes
{ setTopicAttributesAttribute :: !MutableTopicAttribute
, setTopicAttributesTopicArn :: !Arn
}
deriving (Show, Eq, Typeable)
data SetTopicAttributesResponse = SetTopicAttributesResponse
{}
deriving (Show, Read, Eq, Ord, Typeable)
instance ResponseConsumer r SetTopicAttributesResponse where
type ResponseMetadata SetTopicAttributesResponse = SnsMetadata
responseConsumer _ = snsXmlResponseConsumer (const $ pure SetTopicAttributesResponse)
instance SignQuery SetTopicAttributes where
type ServiceConfiguration SetTopicAttributes = SnsConfiguration
signQuery SetTopicAttributes{..} = snsSignQuery SnsQuery
{ snsQueryMethod = Get
, snsQueryAction = setTopicAttributesAction
, snsQueryParameters
= ("TopicArn", Just $ toText setTopicAttributesTopicArn)
: mutableTopicAttributeQuery setTopicAttributesAttribute
, snsQueryBody = Nothing
}
instance Transaction SetTopicAttributes SetTopicAttributesResponse
instance AsMemoryResponse SetTopicAttributesResponse where
type MemoryResponse SetTopicAttributesResponse = SetTopicAttributesResponse
loadToMemory = return
-- -------------------------------------------------------------------------- --
-- Errors
--
-- Currently not used for requests. It's included for future usage
-- and as reference.
data SetTopicAttributesErrors
= SetTopicAttributesAuthorizationError
-- ^ Indicates that the user has been denied access to the requested resource.
--
-- /Code 403/
| SetTopicAttributesInternalError
-- ^ Indicates an internal service error.
--
-- /Code 500/
| SetTopicAttributesInvalidParameter
-- ^ Indicates that a request parameter does not comply with the associated constraints.
--
-- /Code 400/
| SetTopicAttributesNotFound
-- ^ Indicates that the requested resource does not exist.
--
-- /Code 404/
deriving (Show, Read, Eq, Ord, Enum, Bounded, Typeable)
| ababkin/hs-aws-sns | src/Aws/Sns/Commands/SetTopicAttributes.hs | mit | 4,336 | 1 | 12 | 677 | 654 | 391 | 263 | 74 | 1 |
{-# LANGUAGE OverloadedStrings, PatternGuards #-}
{-
Copyright (C) 2006-2015 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.Docbook
Copyright : Copyright (C) 2006-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to Docbook XML.
-}
module Text.Pandoc.Writers.Docbook ( writeDocbook) where
import Text.Pandoc.Definition
import Text.Pandoc.XML
import Text.Pandoc.Shared
import Text.Pandoc.Walk
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Options
import Text.Pandoc.Templates (renderTemplate')
import Text.Pandoc.Readers.TeXMath
import Data.List ( stripPrefix, isPrefixOf, intercalate, isSuffixOf )
import Data.Char ( toLower )
import Data.Monoid ( Any(..) )
import Text.Pandoc.Highlighting ( languages, languagesByExtension )
import Text.Pandoc.Pretty
import Text.Pandoc.ImageSize
import qualified Text.Pandoc.Builder as B
import Text.TeXMath
import qualified Text.XML.Light as Xml
import Data.Generics (everywhere, mkT)
-- | Convert list of authors to a docbook <author> section
authorToDocbook :: WriterOptions -> [Inline] -> B.Inlines
authorToDocbook opts name' =
let name = render Nothing $ inlinesToDocbook opts name'
colwidth = if writerWrapText opts == WrapAuto
then Just $ writerColumns opts
else Nothing
in B.rawInline "docbook" $ render colwidth $
if ',' `elem` name
then -- last name first
let (lastname, rest) = break (==',') name
firstname = triml rest in
inTagsSimple "firstname" (text $ escapeStringForXML firstname) <>
inTagsSimple "surname" (text $ escapeStringForXML lastname)
else -- last name last
let namewords = words name
lengthname = length namewords
(firstname, lastname) = case lengthname of
0 -> ("","")
1 -> ("", name)
n -> (intercalate " " (take (n-1) namewords), last namewords)
in inTagsSimple "firstname" (text $ escapeStringForXML firstname) $$
inTagsSimple "surname" (text $ escapeStringForXML lastname)
-- | Convert Pandoc document to string in Docbook format.
writeDocbook :: WriterOptions -> Pandoc -> String
writeDocbook opts (Pandoc meta blocks) =
let elements = hierarchicalize blocks
colwidth = if writerWrapText opts == WrapAuto
then Just $ writerColumns opts
else Nothing
render' = render colwidth
opts' = if "/book>" `isSuffixOf`
(trimr $ writerTemplate opts)
then opts{ writerChapters = True }
else opts
startLvl = if writerChapters opts' then 0 else 1
auths' = map (authorToDocbook opts) $ docAuthors meta
meta' = B.setMeta "author" auths' meta
Just metadata = metaToJSON opts
(Just . render colwidth . (vcat .
(map (elementToDocbook opts' startLvl)) . hierarchicalize))
(Just . render colwidth . inlinesToDocbook opts')
meta'
main = render' $ vcat (map (elementToDocbook opts' startLvl) elements)
context = defField "body" main
$ defField "mathml" (case writerHTMLMathMethod opts of
MathML _ -> True
_ -> False)
$ metadata
in if writerStandalone opts
then renderTemplate' (writerTemplate opts) context
else main
-- | Convert an Element to Docbook.
elementToDocbook :: WriterOptions -> Int -> Element -> Doc
elementToDocbook opts _ (Blk block) = blockToDocbook opts block
elementToDocbook opts lvl (Sec _ _num (id',_,_) title elements) =
-- Docbook doesn't allow sections with no content, so insert some if needed
let elements' = if null elements
then [Blk (Para [])]
else elements
tag = case lvl of
n | n == 0 -> "chapter"
| n >= 1 && n <= 5 -> if writerDocbook5 opts
then "section"
else "sect" ++ show n
| otherwise -> "simplesect"
idAttr = [("id", writerIdentifierPrefix opts ++ id') | not (null id')]
nsAttr = if writerDocbook5 opts && lvl == 0 then [("xmlns", "http://docbook.org/ns/docbook")]
else []
attribs = nsAttr ++ idAttr
in inTags True tag attribs $
inTagsSimple "title" (inlinesToDocbook opts title) $$
vcat (map (elementToDocbook opts (lvl + 1)) elements')
-- | Convert a list of Pandoc blocks to Docbook.
blocksToDocbook :: WriterOptions -> [Block] -> Doc
blocksToDocbook opts = vcat . map (blockToDocbook opts)
-- | Auxiliary function to convert Plain block to Para.
plainToPara :: Block -> Block
plainToPara (Plain x) = Para x
plainToPara x = x
-- | Convert a list of pairs of terms and definitions into a list of
-- Docbook varlistentrys.
deflistItemsToDocbook :: WriterOptions -> [([Inline],[[Block]])] -> Doc
deflistItemsToDocbook opts items =
vcat $ map (\(term, defs) -> deflistItemToDocbook opts term defs) items
-- | Convert a term and a list of blocks into a Docbook varlistentry.
deflistItemToDocbook :: WriterOptions -> [Inline] -> [[Block]] -> Doc
deflistItemToDocbook opts term defs =
let def' = concatMap (map plainToPara) defs
in inTagsIndented "varlistentry" $
inTagsIndented "term" (inlinesToDocbook opts term) $$
inTagsIndented "listitem" (blocksToDocbook opts def')
-- | Convert a list of lists of blocks to a list of Docbook list items.
listItemsToDocbook :: WriterOptions -> [[Block]] -> Doc
listItemsToDocbook opts items = vcat $ map (listItemToDocbook opts) items
-- | Convert a list of blocks into a Docbook list item.
listItemToDocbook :: WriterOptions -> [Block] -> Doc
listItemToDocbook opts item =
inTagsIndented "listitem" $ blocksToDocbook opts $ map plainToPara item
imageToDocbook :: WriterOptions -> Attr -> String -> Doc
imageToDocbook _ attr src = selfClosingTag "imagedata" $
("fileref", src) : idAndRole attr ++ dims
where
dims = go Width "width" ++ go Height "depth"
go dir dstr = case (dimension dir attr) of
Just a -> [(dstr, show a)]
Nothing -> []
-- | Convert a Pandoc block element to Docbook.
blockToDocbook :: WriterOptions -> Block -> Doc
blockToDocbook _ Null = empty
-- Add ids to paragraphs in divs with ids - this is needed for
-- pandoc-citeproc to get link anchors in bibliographies:
blockToDocbook opts (Div (ident,_,_) [Para lst]) =
let attribs = [("id", ident) | not (null ident)] in
if hasLineBreaks lst
then flush $ nowrap $ inTags False "literallayout" attribs
$ inlinesToDocbook opts lst
else inTags True "para" attribs $ inlinesToDocbook opts lst
blockToDocbook opts (Div _ bs) = blocksToDocbook opts $ map plainToPara bs
blockToDocbook _ (Header _ _ _) = empty -- should not occur after hierarchicalize
blockToDocbook opts (Plain lst) = inlinesToDocbook opts lst
-- title beginning with fig: indicates that the image is a figure
blockToDocbook opts (Para [Image attr txt (src,'f':'i':'g':':':_)]) =
let alt = inlinesToDocbook opts txt
capt = if null txt
then empty
else inTagsSimple "title" alt
in inTagsIndented "figure" $
capt $$
(inTagsIndented "mediaobject" $
(inTagsIndented "imageobject"
(imageToDocbook opts attr src)) $$
inTagsSimple "textobject" (inTagsSimple "phrase" alt))
blockToDocbook opts (Para lst)
| hasLineBreaks lst = flush $ nowrap $ inTagsSimple "literallayout" $ inlinesToDocbook opts lst
| otherwise = inTagsIndented "para" $ inlinesToDocbook opts lst
blockToDocbook opts (BlockQuote blocks) =
inTagsIndented "blockquote" $ blocksToDocbook opts blocks
blockToDocbook _ (CodeBlock (_,classes,_) str) =
text ("<programlisting" ++ lang ++ ">") <> cr <>
flush (text (escapeStringForXML str) <> cr <> text "</programlisting>")
where lang = if null langs
then ""
else " language=\"" ++ escapeStringForXML (head langs) ++
"\""
isLang l = map toLower l `elem` map (map toLower) languages
langsFrom s = if isLang s
then [s]
else languagesByExtension . map toLower $ s
langs = concatMap langsFrom classes
blockToDocbook opts (BulletList lst) =
let attribs = [("spacing", "compact") | isTightList lst]
in inTags True "itemizedlist" attribs $ listItemsToDocbook opts lst
blockToDocbook _ (OrderedList _ []) = empty
blockToDocbook opts (OrderedList (start, numstyle, _) (first:rest)) =
let numeration = case numstyle of
DefaultStyle -> []
Decimal -> [("numeration", "arabic")]
Example -> [("numeration", "arabic")]
UpperAlpha -> [("numeration", "upperalpha")]
LowerAlpha -> [("numeration", "loweralpha")]
UpperRoman -> [("numeration", "upperroman")]
LowerRoman -> [("numeration", "lowerroman")]
spacing = [("spacing", "compact") | isTightList (first:rest)]
attribs = numeration ++ spacing
items = if start == 1
then listItemsToDocbook opts (first:rest)
else (inTags True "listitem" [("override",show start)]
(blocksToDocbook opts $ map plainToPara first)) $$
listItemsToDocbook opts rest
in inTags True "orderedlist" attribs items
blockToDocbook opts (DefinitionList lst) =
let attribs = [("spacing", "compact") | isTightList $ concatMap snd lst]
in inTags True "variablelist" attribs $ deflistItemsToDocbook opts lst
blockToDocbook opts (RawBlock f str)
| f == "docbook" = text str -- raw XML block
| f == "html" = if writerDocbook5 opts
then empty -- No html in Docbook5
else text str -- allow html for backwards compatibility
| otherwise = empty
blockToDocbook _ HorizontalRule = empty -- not semantic
blockToDocbook opts (Table caption aligns widths headers rows) =
let captionDoc = if null caption
then empty
else inTagsIndented "title"
(inlinesToDocbook opts caption)
tableType = if isEmpty captionDoc then "informaltable" else "table"
percent w = show (truncate (100*w) :: Integer) ++ "*"
coltags = vcat $ zipWith (\w al -> selfClosingTag "colspec"
([("colwidth", percent w) | w > 0] ++
[("align", alignmentToString al)])) widths aligns
head' = if all null headers
then empty
else inTagsIndented "thead" $
tableRowToDocbook opts headers
body' = inTagsIndented "tbody" $
vcat $ map (tableRowToDocbook opts) rows
in inTagsIndented tableType $ captionDoc $$
(inTags True "tgroup" [("cols", show (length headers))] $
coltags $$ head' $$ body')
hasLineBreaks :: [Inline] -> Bool
hasLineBreaks = getAny . query isLineBreak . walk removeNote
where
removeNote :: Inline -> Inline
removeNote (Note _) = Str ""
removeNote x = x
isLineBreak :: Inline -> Any
isLineBreak LineBreak = Any True
isLineBreak _ = Any False
alignmentToString :: Alignment -> [Char]
alignmentToString alignment = case alignment of
AlignLeft -> "left"
AlignRight -> "right"
AlignCenter -> "center"
AlignDefault -> "left"
tableRowToDocbook :: WriterOptions
-> [[Block]]
-> Doc
tableRowToDocbook opts cols =
inTagsIndented "row" $ vcat $ map (tableItemToDocbook opts) cols
tableItemToDocbook :: WriterOptions
-> [Block]
-> Doc
tableItemToDocbook opts item =
inTags True "entry" [] $ vcat $ map (blockToDocbook opts) item
-- | Convert a list of inline elements to Docbook.
inlinesToDocbook :: WriterOptions -> [Inline] -> Doc
inlinesToDocbook opts lst = hcat $ map (inlineToDocbook opts) lst
-- | Convert an inline element to Docbook.
inlineToDocbook :: WriterOptions -> Inline -> Doc
inlineToDocbook _ (Str str) = text $ escapeStringForXML str
inlineToDocbook opts (Emph lst) =
inTagsSimple "emphasis" $ inlinesToDocbook opts lst
inlineToDocbook opts (Strong lst) =
inTags False "emphasis" [("role", "strong")] $ inlinesToDocbook opts lst
inlineToDocbook opts (Strikeout lst) =
inTags False "emphasis" [("role", "strikethrough")] $
inlinesToDocbook opts lst
inlineToDocbook opts (Superscript lst) =
inTagsSimple "superscript" $ inlinesToDocbook opts lst
inlineToDocbook opts (Subscript lst) =
inTagsSimple "subscript" $ inlinesToDocbook opts lst
inlineToDocbook opts (SmallCaps lst) =
inTags False "emphasis" [("role", "smallcaps")] $
inlinesToDocbook opts lst
inlineToDocbook opts (Quoted _ lst) =
inTagsSimple "quote" $ inlinesToDocbook opts lst
inlineToDocbook opts (Cite _ lst) =
inlinesToDocbook opts lst
inlineToDocbook opts (Span _ ils) =
inlinesToDocbook opts ils
inlineToDocbook _ (Code _ str) =
inTagsSimple "literal" $ text (escapeStringForXML str)
inlineToDocbook opts (Math t str)
| isMathML (writerHTMLMathMethod opts) =
case writeMathML dt <$> readTeX str of
Right r -> inTagsSimple tagtype
$ text $ Xml.ppcElement conf
$ fixNS
$ removeAttr r
Left _ -> inlinesToDocbook opts
$ texMathToInlines t str
| otherwise = inlinesToDocbook opts $ texMathToInlines t str
where (dt, tagtype) = case t of
InlineMath -> (DisplayInline,"inlineequation")
DisplayMath -> (DisplayBlock,"informalequation")
conf = Xml.useShortEmptyTags (const False) Xml.defaultConfigPP
removeAttr e = e{ Xml.elAttribs = [] }
fixNS' qname = qname{ Xml.qPrefix = Just "mml" }
fixNS = everywhere (mkT fixNS')
inlineToDocbook _ (RawInline f x) | f == "html" || f == "docbook" = text x
| otherwise = empty
inlineToDocbook _ LineBreak = text "\n"
inlineToDocbook _ Space = space
-- because we use \n for LineBreak, we can't do soft breaks:
inlineToDocbook _ SoftBreak = space
inlineToDocbook opts (Link attr txt (src, _))
| Just email <- stripPrefix "mailto:" src =
let emailLink = inTagsSimple "email" $ text $
escapeStringForXML $ email
in case txt of
[Str s] | escapeURI s == email -> emailLink
_ -> inlinesToDocbook opts txt <+>
char '(' <> emailLink <> char ')'
| otherwise =
(if isPrefixOf "#" src
then inTags False "link" $ ("linkend", drop 1 src) : idAndRole attr
else if writerDocbook5 opts
then inTags False "link" $ ("xlink:href", src) : idAndRole attr
else inTags False "ulink" $ ("url", src) : idAndRole attr ) $
inlinesToDocbook opts txt
inlineToDocbook opts (Image attr _ (src, tit)) =
let titleDoc = if null tit
then empty
else inTagsIndented "objectinfo" $
inTagsIndented "title" (text $ escapeStringForXML tit)
in inTagsIndented "inlinemediaobject" $ inTagsIndented "imageobject" $
titleDoc $$ imageToDocbook opts attr src
inlineToDocbook opts (Note contents) =
inTagsIndented "footnote" $ blocksToDocbook opts contents
isMathML :: HTMLMathMethod -> Bool
isMathML (MathML _) = True
isMathML _ = False
idAndRole :: Attr -> [(String, String)]
idAndRole (id',cls,_) = ident ++ role
where
ident = if null id'
then []
else [("id", id')]
role = if null cls
then []
else [("role", unwords cls)]
| infotroph/pandoc | src/Text/Pandoc/Writers/Docbook.hs | gpl-2.0 | 17,215 | 0 | 21 | 5,025 | 4,486 | 2,301 | 2,185 | 309 | 16 |
module Buildsome.Db
( Db, with
, registeredOutputsRef, leakedOutputsRef
, InputDesc(..), FileDesc(..)
, OutputDesc(..)
, ExecutionLog(..), executionLog
, FileContentDescCache(..), fileContentDescCache
, Reason(..)
, IRef(..)
, MFileContentDesc, MakefileParseCache(..), makefileParseCache
) where
import Buildsome.BuildId (BuildId)
import qualified Crypto.Hash.MD5 as MD5
import Data.Binary (Binary(..))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS8
import Data.Default (def)
import Data.IORef
import Data.Map (Map)
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as S
import Data.Time.Clock (DiffTime)
import Data.Time.Clock.POSIX (POSIXTime)
import qualified Database.LevelDB.Base as LevelDB
import GHC.Generics (Generic)
import Lib.Binary (encode, decode)
import Lib.Directory (catchDoesNotExist, createDirectories, makeAbsolutePath)
import Lib.Exception (bracket)
import qualified Lib.FSHook as FSHook
import Lib.FileDesc (FileContentDesc, FileModeDesc, FileStatDesc)
import Lib.FilePath (FilePath, (</>), (<.>))
import Lib.Makefile (Makefile)
import qualified Lib.Makefile as Makefile
import Lib.Makefile.Monad (PutStrLn)
import Lib.StdOutputs (StdOutputs(..))
import Lib.TimeInstances ()
import qualified System.Posix.ByteString as Posix
import Prelude.Compat hiding (FilePath)
schemaVersion :: ByteString
schemaVersion = "schema.ver.20"
data Db = Db
{ dbLevel :: LevelDB.DB
, dbRegisteredOutputs :: IORef (Set FilePath)
, dbLeakedOutputs :: IORef (Set FilePath)
}
data FileContentDescCache = FileContentDescCache
{ fcdcModificationTime :: POSIXTime
, fcdcFileContentDesc :: FileContentDesc
} deriving (Generic, Show)
instance Binary FileContentDescCache
data Reason
= BecauseSpeculative Reason
| BecauseHintFrom [FilePath]
| BecauseHooked FSHook.AccessDoc
| BecauseChildOfFullyRequestedDirectory Reason
| BecauseContainerDirectoryOfInput Reason FilePath
| BecauseContainerDirectoryOfOutput FilePath
| BecauseInput Reason FilePath
| BecauseRequested ByteString
deriving (Generic, Show)
instance Binary Reason
data InputDesc = InputDesc
{ idModeAccess :: Maybe (Reason, FileModeDesc)
, idStatAccess :: Maybe (Reason, FileStatDesc)
, idContentAccess :: Maybe (Reason, FileContentDesc)
} deriving (Generic, Show)
instance Binary InputDesc
data FileDesc ne e
= FileDescNonExisting ne
| FileDescExisting e
deriving (Generic, Eq, Ord, Show)
instance (Binary ne, Binary e) => Binary (FileDesc ne e)
data OutputDesc = OutputDesc
{ odStatDesc :: FileStatDesc
, odContentDesc :: Maybe FileContentDesc -- Nothing if directory
} deriving (Generic, Show)
instance Binary OutputDesc
data ExecutionLog = ExecutionLog
{ elBuildId :: BuildId
, elCommand :: ByteString -- Mainly for debugging
, elInputsDescs :: Map FilePath (FileDesc Reason (POSIXTime, InputDesc))
, elOutputsDescs :: Map FilePath (FileDesc () OutputDesc)
, elStdoutputs :: StdOutputs ByteString
, elSelfTime :: DiffTime
} deriving (Generic, Show)
instance Binary ExecutionLog
registeredOutputsRef :: Db -> IORef (Set FilePath)
registeredOutputsRef = dbRegisteredOutputs
leakedOutputsRef :: Db -> IORef (Set FilePath)
leakedOutputsRef = dbLeakedOutputs
setKey :: Binary a => Db -> ByteString -> a -> IO ()
setKey db key val = LevelDB.put (dbLevel db) def key $ encode val
getKey :: Binary a => Db -> ByteString -> IO (Maybe a)
getKey db key = fmap decode <$> LevelDB.get (dbLevel db) def key
deleteKey :: Db -> ByteString -> IO ()
deleteKey db = LevelDB.delete (dbLevel db) def
options :: LevelDB.Options
options =
LevelDB.defaultOptions
{ LevelDB.createIfMissing = True
, LevelDB.errorIfExists = False
}
withLevelDb :: FilePath -> (LevelDB.DB -> IO a) -> IO a
withLevelDb dbPath =
LevelDB.withDB (BS8.unpack (dbPath </> schemaVersion)) options
with :: FilePath -> (Db -> IO a) -> IO a
with rawDbPath body = do
dbPath <- makeAbsolutePath rawDbPath
createDirectories dbPath
withLevelDb dbPath $ \levelDb ->
withIORefFile (dbPath </> "outputs") $ \registeredOutputs ->
withIORefFile (dbPath </> "leaked_outputs") $ \leakedOutputs ->
body (Db levelDb registeredOutputs leakedOutputs)
where
withIORefFile path =
bracket (newIORef =<< decodeFileOrEmpty path) (writeBack path)
writeBack path ref = do
BS8.writeFile (BS8.unpack (path <.> "tmp")) .
BS8.unlines . S.toList =<< readIORef ref
Posix.rename (path <.> "tmp") path
decodeFileOrEmpty path =
(S.fromList . BS8.lines <$> BS8.readFile (BS8.unpack path))
`catchDoesNotExist` pure S.empty
data IRef a = IRef
{ readIRef :: IO (Maybe a)
, writeIRef :: a -> IO ()
, delIRef :: IO ()
}
mkIRefKey :: Binary a => ByteString -> Db -> IRef a
mkIRefKey key db = IRef
{ readIRef = getKey db key
, writeIRef = setKey db key
, delIRef = deleteKey db key
}
executionLog :: Makefile.Target -> Db -> IRef ExecutionLog
executionLog target = mkIRefKey targetKey
where
targetKey = MD5.hash $ Makefile.targetInterpolatedCmds target
fileContentDescCache :: FilePath -> Db -> IRef FileContentDescCache
fileContentDescCache = mkIRefKey
type MFileContentDesc = FileDesc () FileContentDesc
data MakefileParseCache = MakefileParseCache
{ mpcInputs :: (FilePath, Map FilePath MFileContentDesc)
, mpcOutput :: (Makefile, [PutStrLn])
} deriving (Generic)
instance Binary MakefileParseCache
makefileParseCache :: Db -> Makefile.Vars -> IRef MakefileParseCache
makefileParseCache db vars =
mkIRefKey ("makefileParseCache_Schema.1:" <> MD5.hash (encode vars)) db
| buildsome/buildsome | src/Buildsome/Db.hs | gpl-2.0 | 5,837 | 0 | 16 | 1,132 | 1,709 | 951 | 758 | 143 | 1 |
{-# OPTIONS_GHC -Wall -Wno-orphans -Wno-unticked-promoted-constructors #-}
module Graphics.Cairo
(
Cairo(..), cairoCreate, cairoDestroy
, runCairo
, cairoToGICairo
-- Temporary: until https://github.com/haskell-gi/haskell-gi/issues/188 is fixed
, pangoCairoCreateContext
, pangoLayoutNew
--
, crColor
, crMoveTo
-- * Font types
, FontSpec(..)
, Font(..), WFont, FKind(..)
, FontSizeRequest(..)
, FamilyName(..), FaceName(..)
, LayoutHeightLimit(..)
, TextSizeSpec(..), tssWidth, tssHeight
-- * Query
, fmDefault
, fmFamilies, fmResolution
, ffamName, ffamFaces
, ffaceName, ffacePISizes
, fontQuerySize
-- * Main API
, bindFont, bindWFontLayout, unbindFontLayout
-- * Layout
, laySetWidth, laySetHeight, laySetSize, layGetSize, laySetHeightLimit
, layPrintLimits , layRunTextForSize
, layDrawText
-- * FontMap
, FontKey(..), FontAlias(..), FontPreferences(..), FontMap(..)
, makeFontMap, lookupFont, lookupFont'
, errorMissingFontkey
, lookupFontsBySize
, makeFontLayout
)
where
import Data.Text as T (Text, unpack)
import qualified Generics.SOP as SOP
import qualified Data.GI.Base as GI
import qualified Data.GI.Base.CallStack as B.CallStack
import qualified Data.IORef as IO
import qualified Data.Map.Strict as Map
import qualified Foreign as F
import qualified Foreign.Concurrent as FC
import qualified Foreign.ForeignPtr.Unsafe as F
import qualified GI.Cairo as GIC
import qualified GI.GObject.Objects.Object as GI
import qualified GI.Pango as GIP
import qualified GI.PangoCairo.Functions as GIPC
import qualified GI.PangoCairo.Interfaces.FontMap as GIPC
import qualified Graphics.Rendering.Cairo as GRC
import qualified Graphics.Rendering.Cairo.Internal as GRC (Render(..), create, destroy)
import qualified Graphics.Rendering.Cairo.Types as GRC
import qualified System.IO.Unsafe as UN
import ExternalImports
import Elsewhere
import Graphics.Flatland
import Graphics.FlatDraw
newtype Cairo = Cairo { _unCairo ∷ F.ForeignPtr GRC.Cairo }
foreign import ccall "&cairo_destroy"
cairo_destroy ∷ F.FinalizerPtr GRC.Cairo
cairoCreate ∷ (MonadIO m) ⇒ GRC.Surface → m Cairo
cairoCreate s = Cairo <$> (liftIO $ F.newForeignPtr cairo_destroy =<< GRC.unCairo <$> GRC.create s)
cairoDestroy ∷ (MonadIO m) ⇒ Cairo → m ()
cairoDestroy (Cairo fpcr) = liftIO $ GRC.destroy $ GRC.Cairo $ F.unsafeForeignPtrToPtr $ fpcr
runCairo ∷ (MonadIO m) ⇒ Cairo → GRC.Render a → m a
runCairo (Cairo fpGRC) body =
liftIO $ F.withForeignPtr fpGRC $ \grc →
(`runReaderT` (GRC.Cairo grc)) $ GRC.runRender
body
cairoToGICairo ∷ (MonadIO m) ⇒ Cairo → m GIC.Context
cairoToGICairo (Cairo cairoFptr) =
liftIO $ GIC.Context <$> GI.newManagedPtr (F.castPtr $ F.unsafeForeignPtrToPtr cairoFptr) (F.touchForeignPtr cairoFptr)
foreign import ccall "pango_cairo_create_context" pango_cairo_create_context ::
F.Ptr GIC.Context -> -- cr : TInterface (Name {namespace = "cairo", name = "Context"})
IO (F.Ptr GIP.Context)
pangoCairoCreateContext ::
(B.CallStack.HasCallStack, MonadIO m) =>
GIC.Context
{- ^ /@cr@/: a Cairo context -}
-> m GIP.Context
{- ^ __Returns:__ the newly created 'GI.Pango.Objects.Context.Context'. Free with
'GI.GObject.Objects.Object.objectUnref'. -}
pangoCairoCreateContext cr = liftIO $ do
cr' <- GI.unsafeManagedPtrGetPtr cr
result <- pango_cairo_create_context cr'
checkUnexpectedReturnNULL "createContext" result
fPtr <- FC.newForeignPtr result (pure ())
GI.touchManagedPtr cr
isDisownedRef <- IO.newIORef Nothing
return $ GIP.Context $ GI.ManagedPtr
{ GI.managedForeignPtr = fPtr
, GI.managedPtrIsDisowned = isDisownedRef
, GI.managedPtrAllocCallStack = Nothing
}
foreign import ccall "pango_layout_new" pango_layout_new ::
F.Ptr GIP.Context -> -- context : TInterface (Name {namespace = "Pango", name = "Context"})
IO (F.Ptr GIP.Layout)
{- |
Create a new 'GI.Pango.Objects.Layout.Layout' object with attributes initialized to
default values for a particular 'GI.Pango.Objects.Context.Context'.
-}
pangoLayoutNew ::
(B.CallStack.HasCallStack, MonadIO m, GIP.IsContext a) =>
a
{- ^ /@context@/: a 'GI.Pango.Objects.Context.Context' -}
-> m GIP.Layout
{- ^ __Returns:__ the newly allocated 'GI.Pango.Objects.Layout.Layout', with a reference
count of one, which should be freed with
'GI.GObject.Objects.Object.objectUnref'. -}
pangoLayoutNew context = liftIO $ do
context' <- GI.unsafeManagedPtrCastPtr context
result <- pango_layout_new context'
checkUnexpectedReturnNULL "layoutNew" result
fPtr <- FC.newForeignPtr result (pure ())
GI.touchManagedPtr context
isDisownedRef <- IO.newIORef Nothing
return $ GIP.Layout $ GI.ManagedPtr
{ GI.managedForeignPtr = fPtr
, GI.managedPtrIsDisowned = isDisownedRef
, GI.managedPtrAllocCallStack = Nothing
}
crColor ∷ Co Double → GRC.Render ()
crColor (Co (V4 r g b a)) = GRC.setSourceRGBA r g b a
crMoveTo ∷ Po Double → GRC.Render ()
crMoveTo (Po (V2 dx dy)) = GRC.moveTo dx dy
-- $Font choice strategy.
--
-- The current font choice strategy is based on preference lists -- a list of
-- font specification tuples of (family, face, size, size-policy), where:
-- - 'size' is either in Pango units or in typographic points (at 72ppi)
-- - 'size-policy', when specified (as one of LT, EQ, GT), indicates a preference
-- for bitmapped fonts, and thereso specifies a decision procedure, for when an
-- exact size match is unavailable -- nearest smaller, failure, nearest larger.
--
-- Such a preference list is crossed against a fontmap, and the first matching
-- font is chosen.
--
-- Note, that this strategy has no explicit means to facilitate reliable character
-- display -- since, probably no known font provides for all Unicode characters.
-- The fontconfig mechanism underlying pangocairo font /might/ be able to help,
-- although it will likely need more work to engage that functionality.
--
-- If/when we decide to embark upon that journey, 'Pango.Objects.Context.contextLoadFontset'
-- would be our first point of contact.
--
-- $Known deficiencies.
--
-- 1. This library is specific to GI.PangoCairo.Context, which is a specialization of GI.Pango.Context.
--
-- Note [Fontmap type]
-- ~~~~~~~~~~~~~~~~~~~
-- We choose to entirely avoid GI.Pango.FontMap,
-- because it has no intrinsic concept of resolution, which we heavily rely upon.
-- Hence, we opt to GI.PangoCairo.FontMap everywhere.
--
instance Show GIPC.FontMap where
show = printf "FontMap { resolution = %fDΠ }" ∘ fromDΠ ∘ fmResolution
instance Show GIP.FontFamily where
show = printf "FontFamily { name = '%s' }" ∘ ffamName
instance Show GIP.FontFace where
show = printf "FontFace { name = '%s' }" ∘ ffaceName
fmDefault ∷ GIPC.FontMap
fmDefault = GIPC.fontMapGetDefault & UN.unsafePerformIO
fmFamilies ∷ GIP.IsFontMap a ⇒ a → [GIP.FontFamily]
fmFamilies = UN.unsafePerformIO ∘ GIP.fontMapListFamilies
-- | Get fontmap resolution.
-- This function isn't in IO, because the resolution mutation function isn't defined.
-- If ever something is exported that changes the fontmap resolution, this function's
-- signature must be moved to IO.
fmResolution ∷ GIPC.FontMap → DΠ
fmResolution = DΠ ∘ UN.unsafePerformIO ∘ GIPC.fontMapGetResolution
-- fmSetResolution ∷ GIPC.FontMap → DΠ → IO ()
-- fmSetResolution fm = GIPC.fontMapSetResolution fm ∘ fromDΠ
-- pcResolution ∷ GIP.Context → IO DΠ
-- pcResolution ctx = DΠ <$> GIPC.contextGetResolution ctx
-- pcSetResolution ∷ GIP.Context → DΠ → IO ()
-- pcSetResolution ctx = GIPC.contextSetResolution ctx ∘ fromDΠ
ffamName ∷ GIP.FontFamily → Text
ffamName = UN.unsafePerformIO ∘ GIP.fontFamilyGetName
ffamFaces ∷ GIP.FontFamily → [GIP.FontFace]
ffamFaces = UN.unsafePerformIO ∘ GIP.fontFamilyListFaces
ffaceName ∷ GIP.FontFace → Text
ffaceName = UN.unsafePerformIO ∘ GIP.fontFaceGetFaceName
ffacePISizes ∷ GIP.FontFace → Maybe [Unit PUI]
ffacePISizes fface = (fromIntegral <$>) <$> (UN.unsafePerformIO (GIP.fontFaceListSizes fface))
-- * Font sizes
-- | Set font size: XXX/upstream/inconsistency -- Double, yet PANGO_SCALE-d:
-- https://hackage.haskell.org/package/gi-pango-1.0.11/docs/GI-Pango-Structs-FontDescription.html#v:fontDescriptionSetAbsoluteSize
-- https://hackage.haskell.org/package/gi-pango-1.0.11/docs/GI-Pango-Structs-FontDescription.html#v:fontDescriptionSetSize
fdSetSize ∷ (MonadIO m) ⇒ GIP.FontDescription → Unit u → m ()
fdSetSize fd (PUs us) = GIP.fontDescriptionSetAbsoluteSize fd $ us * fromIntegral GIP.SCALE
fdSetSize fd (PUIs is) = GIP.fontDescriptionSetAbsoluteSize fd $ fromIntegral is
fdSetSize fd (Pts pts) = GIP.fontDescriptionSetSize fd $ pts * GIP.SCALE
data FontSizeRequest
= Outline
{ fsValue ∷ WUnit
}
| Bitmap
{ fsValue ∷ WUnit
, fsbPolicy ∷ Ordering
}
deriving (Eq, Generic, Read, Show)
--- XXX/expressivity:
-- let ascending = True in sortOn (if ascending then id else Down)
-- [0, 2, 1]
-- • Occurs check: cannot construct the infinite type: a ~ Down a
-- Expected type: Down a -> Down a
-- Actual type: a -> Down a
-- • In the expression: Down
-- In the first argument of ‘sortOn’, namely
-- ‘(if o then id else Down)’
-- In the expression: sortOn (if o then id else Down) [0, 2, 1]
newtype FamilyName = FamilyName { fromFamilyName ∷ Text } deriving (Eq, Show, IsString, Read) -- ^ Pango font family name
newtype FaceName = FaceName { fromFaceName ∷ Text } deriving (Eq, Show, IsString, Read) -- ^ Pango font face name
data FKind = Spec | Found | Bound
data FontSpec where
FontSpec ∷
{ frFamilyName ∷ FamilyName
, frFaceName ∷ FaceName
, frSizeRequest ∷ FontSizeRequest
} → FontSpec
deriving (Eq, Generic, Read)
data Font (k ∷ FKind) u where
FontSpec' ∷
{ frFontSpec ∷ FontSpec
} → Font Spec u
Font ∷
{ fFamilyName ∷ FamilyName
, fFaceName ∷ FaceName
, fSize ∷ Unit u
, fDΠ ∷ DΠ
, fMaxHeight ∷ He (Unit u)
--
, fDesc ∷ GIP.FontDescription
, fFontMap ∷ GIPC.FontMap
, fDetachedContext ∷ GIP.Context
, fDetachedLayout ∷ GIP.Layout
} → Font Found u
FontBinding ∷
{ fbFont ∷ Font Found u
, fbContext ∷ GIP.Context
} → Font Bound u
data WFont (k ∷ FKind) where
WFont ∷ FromUnit u ⇒
{ _fromWFont ∷ Font k u
} → WFont k
instance Show FontSpec where
show FontSpec{..} =
printf "FontSpec { family = %s, face = %s, size = %s }"
(fromFamilyName frFamilyName) (fromFaceName frFaceName) (show frSizeRequest)
instance Show (Font Found u) where
show Font{..} =
printf "Font { family = %s, face = %s, size = %s }"
(fromFamilyName fFamilyName) (fromFaceName fFaceName) (show fSize)
instance Eq (Font Spec u) where
FontSpec' fs == FontSpec' fs' =
fs == fs'
instance Eq (Font Found u) where
Font famnl facnl fszl fdπl _ _ _ _ _ == Font famnr facnr fszr fdπr _ _ _ _ _ =
famnl ≡ famnr ∧ facnl ≡ facnr ∧ fszl ≡ fszr ∧ fdπl ≡ fdπr
instance Eq (Font Bound u) where
FontBinding fl _ == FontBinding fr _ =
fl ≡ fr
validateFont ∷ (MonadIO m) ⇒ FromUnit u ⇒ GIPC.FontMap → Font Spec u → m (Either String (Font Found u))
validateFont fFontMap (FontSpec' (FontSpec
fFamilyName@(FamilyName ffamname)
fFaceName@(FaceName ffacename)
fSizeRequest)) =
let fams = filter ((≡ ffamname) ∘ ffamName) $ fmFamilies fFontMap
faces = filter ((≡ ffacename) ∘ ffaceName) $ concat $ ffamFaces <$> fams
fDΠ = fmResolution fFontMap
fPI = fromWUnit fDΠ $ fsValue fSizeRequest
in case (fams, faces) of
([],_) → pure ∘ Left $ printf "Missing font family '%s'." ffamname
(_:_,[]) → pure ∘ Left $ printf "No face '%s' in family '%s'." ffacename ffamname
(_:_,(fFace ∷ GIP.FontFace):_) → do
fDesc ← GIP.fontFaceDescribe fFace
let mayfPISizes = ffacePISizes fFace
eifSizeFail = case (fSizeRequest, mayfPISizes) of
(Outline fs, Nothing) → Right fs -- Outline font was requested, and was obtained: we can request any size
(Outline fs, Just fPISizes) →
if | fPI ∈ fPISizes → Right $ fs
| otherwise → Left $ printf "Bitmap font family '%s' does not provide for size %s." ffamname (show fs)
(Bitmap _ _, Nothing) → Left $ printf "Outline font family '%s' does not provide for bitmaps." ffamname
(Bitmap fs policy, Just fPISizes) →
case trace (printf "policy: %s, fPI: %s, sizes: %s" (show policy) (show fPI) (show fPISizes)) (policy, fPI ∈ fPISizes) of
(_, True) → Right fs
(EQ, False) → Left failure
(_, False) → -- an exact match was unavailable, so let's use the
-- policy-provided laxity and seek for a closest one:
let (findp, ordered) = if | policy ≡ LT → ((>), sortOn Down fPISizes)
| otherwise → ((<), sortOn id fPISizes)
in case find (findp fPI) ordered of
Nothing → Left failure
Just sz → Right $ UnitPUI $ fromUnit fDΠ sz
where failure = printf "Bitmap font face '%s' of family '%s' does not have font sizes matching policy %s against size %s, among %s."
ffacename ffamname (show policy) (show $ fromPU $ fromUnit fDΠ fPI) (show $ (fromPU ∘ fromUnit fDΠ) <$> fPISizes)
fontQueryMaxHeight ∷ ∀ m u. (MonadIO m, FromUnit u) ⇒ GIP.Layout → m (He (Unit u))
fontQueryMaxHeight fDetachedLayout = do
laySetHeightLimit fDetachedLayout OneLine
He ∘ (^.di'v._y) <$> layRunTextForSize fDetachedLayout fDΠ (Nothing ∷ Maybe (Wi (Unit u))) "ly"
case eifSizeFail of
Left failure → pure $ Left failure
Right wfSize → do
let fSize = fromWUnit fDΠ wfSize
fdSetSize fDesc fSize
-- liftIO $ putStrLn $ printf "---------------\n fdesc: %s" (show fDesc)
fDetachedContext ← GIP.fontMapCreateContext fFontMap
GIP.contextSetFontDescription fDetachedContext fDesc
GIPC.contextSetResolution fDetachedContext (fromDΠ fDΠ)
fDetachedLayout ← makeLayout fDetachedContext
fMaxHeight ← fontQueryMaxHeight fDetachedLayout
pure $ Right $ Font{..}
chooseFont ∷ (MonadIO m) ⇒ FromUnit u ⇒ GIPC.FontMap → [FontSpec] → m (Maybe (Font Found u), [String])
chooseFont fMap freqs = loop freqs []
where loop ∷ (MonadIO m) ⇒ FromUnit u ⇒ [FontSpec] → [String] → m (Maybe (Font Found u), [String])
loop [] failures = pure (Nothing, failures)
loop (fr:rest) fs = validateFont fMap (FontSpec' fr)
>>= (\case
Right font → pure (Just font, fs)
Left fail → loop rest $ fail:fs)
bindFont ∷ (MonadIO m, FromUnit u) ⇒ Font Found u → GIC.Context → m (Font Bound u)
bindFont fbFont@Font{..} gic = do
-- fbContext ← GIPC.createContext gic
fbContext ← pangoCairoCreateContext gic
GIP.contextSetFontDescription fbContext fDesc
GIPC.contextSetResolution fbContext (fromDΠ fDΠ)
pure $ FontBinding{..}
bindWFontLayout ∷ (MonadIO m, FromUnit u, FromUnit v) ⇒
DΠ → GIC.Context → Font Found u → Di (Unit v) → TextSizeSpec v → m (WFont Bound, GIP.Layout)
bindWFontLayout dπ gic font dim sizeSpec = do
fbound ← bindFont font gic
layout ← makeFontLayout dπ fbound dim (sizeSpec^.tssHeight)
pure (WFont fbound, layout)
unbindFontLayout ∷ (MonadIO m) ⇒ WFont Bound → GIP.Layout → m ()
unbindFontLayout (WFont FontBinding{..}) gipl = do
GI.objectUnref gipl
GI.objectUnref fbContext
-- | 'LayoutHeightLimit', quoting Pango documentation:
--
-- @height: the desired height of the layout in Pango units if positive,
-- or desired number of lines if negative.
-- Sets the height to which the #PangoLayout should be ellipsized at. There
-- are two different behaviors, based on whether @height is positive or
-- negative.
--
-- If @height is positive, it will be the maximum height of the layout. Only
-- lines would be shown that would fit, and if there is any text omitted,
-- an ellipsis added. At least one line is included in each paragraph regardless
-- of how small the height value is. A value of zero will render exactly one
-- line for the entire layout.
--
-- If @height is negative, it will be the (negative of) maximum number of lines per
-- paragraph. That is, the total number of lines shown may well be more than
-- this value if the layout contains multiple paragraphs of text.
-- The default value of -1 means that first line of each paragraph is ellipsized.
-- ...
-- Height setting only has effect if a positive width is set on
-- @layout and ellipsization mode of @layout is not %PANGO_ELLIPSIZE_NONE.
-- The behavior is undefined if a height other than -1 is set and
-- ellipsization mode is set to %PANGO_ELLIPSIZE_NONE, and may change in the
-- future.
data LayoutHeightLimit where
OneLine ∷ LayoutHeightLimit
ParaLines ∷ Int → LayoutHeightLimit
Units ∷ Unit PUI → LayoutHeightLimit
deriving (Eq, Show)
instance Semigroup LayoutHeightLimit where
l <> r = choosePartially OneLine l r
instance Monoid LayoutHeightLimit where
mempty = OneLine
data TextSizeSpec u where
TextSizeSpec ∷ FromUnit u ⇒
{ _tssWidth ∷ Maybe (Wi (Unit u))
, _tssHeight ∷ LayoutHeightLimit
} → TextSizeSpec u
tssWidth ∷ Lens' (TextSizeSpec u) (Maybe (Wi (Unit u)))
tssWidth f (TextSizeSpec w h) = flip TextSizeSpec h <$> f w
tssHeight ∷ Lens' (TextSizeSpec u) LayoutHeightLimit
tssHeight f (TextSizeSpec w h) = TextSizeSpec w <$> f h
instance StandardUnit TextSizeSpec where
convert dπ (TextSizeSpec mwi he) =
flip TextSizeSpec he $ mwi & _Just.wi'val %~ fromUnit dπ
fontQuerySize ∷ (HasCallStack, MonadIO m, FromUnit u) ⇒ Font Found u → TextSizeSpec u → Maybe T.Text → m (Either T.Text (Di (Unit u)))
fontQuerySize _ TextSizeSpec{_tssWidth=Nothing} Nothing = pure $ Left "Invariant failed: text size underconstrained."
fontQuerySize Font{..} TextSizeSpec{_tssWidth=Just wi} Nothing =
pure $ Right $ di wi fMaxHeight
fontQuerySize Font{..} TextSizeSpec{..} (Just text) = do
laySetHeightLimit fDetachedLayout _tssHeight
Right <$> layRunTextForSize fDetachedLayout fDΠ _tssWidth text
-- * Text
makeLayout ∷ (MonadIO m) ⇒ GIP.Context → m (GIP.Layout)
makeLayout gipc = do
-- gip ← GIP.layoutNew gipc
gip ← pangoLayoutNew gipc
GIP.layoutSetWrap gip GIP.WrapModeWord
GIP.layoutSetEllipsize gip GIP.EllipsizeModeEnd
pure gip
makeFontLayout ∷ (MonadIO m, FromUnit u, FromUnit v) ⇒
DΠ → Font Bound u → Di (Unit v) → LayoutHeightLimit → m GIP.Layout
makeFontLayout dπ FontBinding{..} dim heightLimit = do
layout ← makeLayout fbContext
laySetSize layout dπ dim
laySetHeightLimit layout heightLimit
pure layout
laySetWidth ∷ (MonadIO m) ⇒ FromUnit s ⇒ GIP.Layout → DΠ → Wi (Unit s) → m ()
laySetWidth lay dπ (Wi sz) = do
let csz = fromPUI $ fromUnit dπ sz
GIP.layoutSetWidth lay csz
laySetHeight ∷ (MonadIO m) ⇒ FromUnit s ⇒ GIP.Layout → DΠ → Wi (Unit s) → m ()
laySetHeight lay dπ (Wi sz) = do
let csz = fromPUI $ fromUnit dπ sz
GIP.layoutSetHeight lay csz
laySetHeightLimit ∷ (MonadIO m) ⇒ GIP.Layout → LayoutHeightLimit → m ()
laySetHeightLimit lay limit = do
GIP.layoutSetHeight lay $
case limit of
OneLine → 0
ParaLines x → fromIntegral (-1 ⋅ abs x)
Units x → fromIntegral $ fromPUI x
laySetSize ∷ (MonadIO m) ⇒ FromUnit s ⇒ GIP.Layout → DΠ → Di (Unit s) → m ()
laySetSize lay dπ sz = do
let (Di (V2 cx cy)) = fromPUI ∘ fromUnit dπ <$> sz
GIP.layoutSetWidth lay cx
GIP.layoutSetHeight lay cy
layGetSize ∷ (MonadIO m) ⇒ FromUnit s ⇒ GIP.Layout → DΠ → m (Di (Unit s))
layGetSize lay dπ = do
(pix, piy) ← GIP.layoutGetPixelSize lay
pure $ Di $ V2 (fromUnit dπ $ PUs $ fromIntegral pix) (fromUnit dπ $ PUs $ fromIntegral piy)
layPrintLimits ∷ (MonadIO m) ⇒ String → GIP.Layout → m ()
layPrintLimits key lay = do
w ← GIP.layoutGetWidth lay
h ← GIP.layoutGetHeight lay
liftIO $ printf "-- %s limw: %s, limh: %s\n" key (show w) (show h)
layRunTextForSize ∷ (MonadIO m) ⇒ (FromUnit s, FromUnit t) ⇒
GIP.Layout → DΠ → Maybe (Wi (Unit s)) → Text → m (Di (Unit t))
layRunTextForSize lay dπ mWidth text = do
case mWidth of
Nothing → pure ()
Just width → laySetWidth lay dπ width
GIP.layoutSetText lay text (-1)
sz ← layGetSize lay dπ
-- liftIO $ printf "LRTFS '%s' w=%s → %s\n" text (show $ width^.wiV) (show $ sz^.diV)
pure sz
layDrawText ∷ (MonadIO m) ⇒ Cairo → GIC.Context → GIP.Layout → Po Double → Co Double → T.Text → m ()
layDrawText cairo dGIC lay (Po (V2 cvx cvy)) tColor text =
runCairo cairo $ do
GRC.moveTo cvx cvy
coSetSourceColor tColor
-- GRC.selectFontFace ("Terminus" ∷ T.Text) GRC.FontSlantNormal GRC.FontWeightNormal
-- GRC.setFontSize 15
-- GRC.textPath text
-- GRC.fillPreserve
-- GRC.setLineWidth 1.0
-- GRC.stroke
-- GRC.restore
GIP.layoutSetText lay text (-1)
GIPC.showLayout dGIC lay
-- * Gadget to test scaling and alpha issues
--
-- crColor (co 0 1 0 0.1) >> GRC.rectangle 0 0 6 6 >> GRC.fill
-- crColor (co 1 0 0 0.5) >> GRC.rectangle 1 1 4 4 >> GRC.fill
-- crColor (co 0 0 1 1) >> GRC.rectangle 2 2 2 2 >> GRC.fill
-- | Fontmap: give fonts semantic names.
newtype FontKey
= FK { fromFK ∷ T.Text }
deriving (Eq, Ord, Show, IsString, Read, Generic)
newtype FontAlias
= Alias { fromAlias ∷ FontKey }
deriving (Eq, Ord, Show, IsString, Read, Generic)
data FontPreferences
= FontPreferences [(FontKey, Either FontAlias [FontSpec])]
deriving (Eq, Generic, Show)
instance SOP.Generic FontPreferences
instance SOP.HasDatatypeInfo FontPreferences
data FontMap u where
FontMap ∷
{ fmDΠ ∷ DΠ
, fmFonts ∷ Map FontKey (Font Found u)
, fmBySize ∷ Map (Unit u) [Font Found u]
} → FontMap u
deriving instance Show (FontMap u)
makeFontMap ∷ (MonadIO m, FromUnit u) ⇒ HasCallStack ⇒ DΠ → GIPC.FontMap → FontPreferences → m (FontMap u)
makeFontMap dπ gipcFM (FontPreferences prefsAndAliases) = do
pass1 ← foldM resolvePrefs Map.empty ((id *** fromRight (⊥)) <$> prefs)
let pass2 = foldl resolveAlias pass1 ((id *** fromLeft (⊥)) <$> aliases)
bySize = [ (,) fSize [f]
| f@Font{..} ← Map.elems pass2 ]
& Map.fromListWith (<>)
pure $ FontMap dπ pass2 bySize
where resolvePrefs acc (fkey, freqs) = do
(mFont, errs) ← chooseFont gipcFM freqs
let font = mFont &
fromMaybe (error $ printf "FATAL: while searching font for slot '%s', no suitable font among: %s. Failures: %s" (show fkey) (show freqs) (show errs))
pure $ Map.insert fkey font acc
resolveAlias fontmap (fk, (Alias alias)) = flip (Map.insert fk) fontmap
$ Map.lookup alias fontmap
& flip fromMaybe
$ error $ printf "ERROR: while resolving alias for slot '%s', no slot named '%s' exists."
(T.unpack $ fromFK fk) (T.unpack $ fromFK alias)
(aliases, prefs) = flip partition prefsAndAliases
(\(_, aEp) → isLeft aEp)
lookupFontsBySize ∷ (Ord (Unit u)) ⇒ FontMap u → Ordering → Unit u → [Font Found u]
lookupFontsBySize FontMap{..} ord val =
case (Map.splitLookup val fmBySize, ord) of
((_, Just xs, _), _) → xs
((l, _, _), LT) → fromMaybe [] $ fst <$> Map.maxView l
((_, _, r), GT) → fromMaybe [] $ fst <$> Map.minView r
(_, EQ) → []
lookupFont ∷ FromUnit u ⇒ FontMap u → FontKey → Maybe (Font Found u)
lookupFont FontMap{..} = flip Map.lookup fmFonts
lookupFont' ∷ FromUnit u ⇒ FontMap u → FontKey → Font Found u
lookupFont' fm fk = lookupFont fm fk
& fromMaybe (errorMissingFontkey fk)
errorMissingFontkey ∷ FontKey → a
errorMissingFontkey = error ∘ printf "ERROR: unexpected missing fontkey '%s'." ∘ show
| deepfire/mood | src/Graphics/Cairo.hs | agpl-3.0 | 25,605 | 41 | 32 | 6,168 | 6,575 | 3,442 | 3,133 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
{-
Copyright 2019 The CodeWorld Authors. All Rights Reserved.
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.
-}
module Blockly.Event ( Event(..)
,EventType(..)
,getType
,getWorkspaceId
,getBlockId
-- ,getIds
,addChangeListener
)
where
import GHCJS.Types
import Data.JSString (pack, unpack)
import GHCJS.Foreign
import GHCJS.Marshal
import GHCJS.Foreign.Callback
import Blockly.General
import Blockly.Workspace
import JavaScript.Array (JSArray)
newtype Event = Event JSVal
data EventType = CreateEvent Event
| DeleteEvent Event
| ChangeEvent Event
| MoveEvent Event
| UIEvent Event
| GeneralEvent Event
getType :: Event -> EventType
getType event = case unpack $ js_type event of
"create" -> CreateEvent event
"delete" -> DeleteEvent event
"change" -> ChangeEvent event
"move" -> MoveEvent event
"ui" -> UIEvent event
_ -> GeneralEvent event
getWorkspaceId :: Event -> UUID
getWorkspaceId event = UUID $ unpack $ js_workspaceId event
getBlockId :: Event -> UUID
getBlockId event = UUID $ unpack $ js_blockId event
getGroup :: Event -> UUID
getGroup event = UUID $ unpack $ js_group event
-- getIds :: Event -> UUID
-- getIds event = UUID $ unpack $ js_ids event
type EventCallback = Event -> IO ()
addChangeListener :: Workspace -> EventCallback -> IO ()
addChangeListener workspace func = do
cb <- syncCallback1 ContinueAsync (func . Event)
js_addChangeListener workspace cb
--- FFI
foreign import javascript unsafe "$1.addChangeListener($2)"
js_addChangeListener :: Workspace -> Callback a -> IO ()
-- One of Blockly.Events.CREATE, Blockly.Events.DELETE, Blockly.Events.CHANGE,
-- Blockly.Events.MOVE, Blockly.Events.UI.
foreign import javascript unsafe "$1.type"
js_type :: Event -> JSString
-- UUID of workspace
foreign import javascript unsafe "$1.workspaceId"
js_workspaceId :: Event -> JSString
-- UUID of block.
foreign import javascript unsafe "$1.blockId"
js_blockId :: Event -> JSString
-- UUID of group
foreign import javascript unsafe "$1.group"
js_group :: Event -> JSString
-- UUIDs of affected blocks
foreign import javascript unsafe "$1.ids"
js_ids :: Event -> JSArray
| alphalambda/codeworld | funblocks-client/src/Blockly/Event.hs | apache-2.0 | 3,031 | 15 | 11 | 773 | 507 | 273 | 234 | 54 | 6 |
module Reddit.Routes.Search where
import Reddit.Types.Options
import Reddit.Types.Post
import Reddit.Types.Subreddit
import qualified Reddit.Types.SearchOptions as Search
import Data.Maybe
import Data.Text (Text)
import Network.API.Builder.Routes
searchRoute :: Maybe SubredditName -> Options PostID -> Search.Order -> Text -> Text -> Route
searchRoute r opts sorder engine q =
Route (path r)
[ "after" =. after opts
, "before" =. before opts
, "restrict_sr" =. isJust r
, "sort" =. sorder
, "syntax" =. engine
, "q" =. Just q ]
"GET"
where
path (Just (R sub)) = [ "r", sub, "search" ]
path Nothing = [ "search" ]
| FranklinChen/reddit | src/Reddit/Routes/Search.hs | bsd-2-clause | 685 | 0 | 11 | 164 | 214 | 119 | 95 | 20 | 2 |
-- Run tests using the TCP transport.
--
module Main where
import TEST_SUITE_MODULE (tests)
import Network.Transport.Test (TestTransport(..))
import Network.Socket (sClose)
import Network.Transport.TCP
( createTransportExposeInternals
, TransportInternals(socketBetween)
, defaultTCPParameters
)
import Test.Framework (defaultMainWithArgs)
import Control.Concurrent (threadDelay)
import System.Environment (getArgs)
main :: IO ()
main = do
Right (transport, internals) <-
createTransportExposeInternals "127.0.0.1" "8080" defaultTCPParameters
ts <- tests TestTransport
{ testTransport = transport
, testBreakConnection = \addr1 addr2 -> do
sock <- socketBetween internals addr1 addr2
sClose sock
threadDelay 10000
}
args <- getArgs
-- Tests are time sensitive. Running the tests concurrently can slow them
-- down enough that threads using threadDelay would wake up later than
-- expected, thus changing the order in which messages were expected.
-- Therefore we run the tests sequentially by passing "-j 1" to
-- test-framework. This does not solve the issue but makes it less likely.
--
-- The problem was first detected with
-- 'Control.Distributed.Process.Tests.CH.testMergeChannels'
-- in particular.
defaultMainWithArgs ts ("-j" : "1" : args)
| haskell-distributed/distributed-process-tests | tests/runTCP.hs | bsd-3-clause | 1,367 | 0 | 15 | 280 | 220 | 125 | 95 | 23 | 1 |
module Fir where
import Language.StreamIt
fir :: Var Int -> Var (Array Float) -> Filter Float Float ()
fir n weights =
work Rate{pushRate=1, popRate=1, peekRate=ref n} $ do
result <- float' 0
for (0, ref n) $ \i -> do
let i' = ref i
result += ref (weights ! i') * peek i'
-- Looks pretty similar to StreamIt code..
-- But you can call Haskell functions in here!
pop
push (ref result)
for (lower,upper) fn = do
i <- int
for_ (i <== lower, ref i <. upper, i += 1) $ fn i
| adk9/haskell-streamit | Examples/fir/Fir.hs | bsd-3-clause | 529 | 0 | 16 | 157 | 230 | 114 | 116 | 14 | 1 |
module A (a) where
a :: Char
a = 'z'
| gridaphobe/hpc | tests/ghc_ghci/A.hs | bsd-3-clause | 39 | 0 | 4 | 12 | 19 | 12 | 7 | 3 | 1 |
-- Simple data type to keep track of character positions
-- within a text file or other text stream.
module Text.Packrat.Pos where
data Pos = Pos { posFile :: !String
, posLine :: !Int
, posCol :: !Int
}
nextPos :: Pos -> Char -> Pos
nextPos (Pos file line col) c
| c == '\n' = Pos file (line + 1) 1
| c == '\t' = Pos file line ((div (col + 8 - 1) 8) * 8 + 1)
| otherwise = Pos file line (col + 1)
instance Eq Pos where
Pos f1 l1 c1 == Pos f2 l2 c2 =
f1 == f2 && l1 == l2 && c1 == c2
instance Ord Pos where
Pos _ l1 c1 <= Pos _ l2 c2 =
(l1 < l2) || (l1 == l2 && c1 <= c2)
instance Show Pos where
show (Pos file line col) = file ++ ":" ++ show line ++ ":" ++ show col
showPosRel :: Pos -> Pos -> String
showPosRel (Pos file line _) (Pos file' line' col')
| file == file' =
if (line == line')
then "column " ++ show col'
else "line " ++ show line' ++ ", column " ++ show col'
| otherwise = show (Pos file' line' col')
| beni55/HaskellNet | src/Text/Packrat/Pos.hs | bsd-3-clause | 1,047 | 0 | 14 | 345 | 444 | 221 | 223 | 30 | 2 |
module TH_repPatSig_asserts where
import Language.Haskell.TH
assertFoo :: Q [Dec] -> Q [Dec]
assertFoo decsQ = do
decs <- decsQ
case decs of
[ SigD _ (AppT (AppT ArrowT (ConT t1)) (ConT t2)),
FunD _ [Clause [SigP (VarP _) (ConT t3)] (NormalB (VarE _)) []] ]
| t1 == ''Int && t2 == ''Int && t3 == ''Int -> return []
_ -> do reportError $ "Unexpected quote contents: " ++ show decs
return []
assertCon :: Q Exp -> Q [Dec]
assertCon expQ = do
exp <- expQ
case exp of
LamE [SigP (VarP _) (AppT (AppT ArrowT (AppT (AppT (ConT eitherT)
(ConT charT1))
(ConT intT1)))
(AppT (AppT (TupleT 2) (ConT charT2))
(ConT intT2)))]
(VarE _)
| eitherT == ''Either &&
charT1 == ''Char &&
charT2 == ''Char &&
intT1 == ''Int &&
intT2 == ''Int -> return []
_ -> do reportError $ "Unexpected quote contents: " ++ show exp
return []
assertVar :: Q Exp -> Q [Dec]
assertVar expQ = do
exp <- expQ
case exp of
LamE [SigP (VarP x) (AppT (ConT _) (VarT a))]
(CaseE (VarE x1) [Match (ConP _ [VarP y])
(NormalB (SigE (VarE y1) (VarT a1))) []])
| x1 == x &&
y1 == y &&
a1 == a -> return []
_ -> do reportError $ "Unexpected quote contents: " ++ show exp
return []
| ezyang/ghc | testsuite/tests/th/TH_repPatSig_asserts.hs | bsd-3-clause | 1,502 | 0 | 22 | 594 | 662 | 319 | 343 | -1 | -1 |
module T5281A where
{-# DEPRECATED deprec "This is deprecated" #-}
deprec :: Int
deprec = 5
| urbanslug/ghc | testsuite/tests/rename/should_fail/T5281A.hs | bsd-3-clause | 95 | 0 | 4 | 19 | 15 | 10 | 5 | 4 | 1 |
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Options (injectDefaults) where
import Control.Applicative
import qualified Control.Exception as E
import Control.Monad
import Data.Char (isAlphaNum, isSpace, toLower)
import Data.List (foldl')
import Data.List.Split (splitOn)
import qualified Data.Map as M
import Data.Maybe (catMaybes)
import Data.Monoid
import Options.Applicative
import Options.Applicative.Types
import System.Directory
import System.Environment
import System.FilePath ((</>))
-- | inject defaults from either files or environments
-- in order of priority:
-- 1. command line arguments: --long-option=value
-- 2. environment variables: PREFIX_COMMAND_LONGOPTION=value
-- 3. $HOME/.prefix/config: prefix.command.longoption=value
--
-- note: this automatically injects values for standard options and flags
-- (also inside subcommands), but not for more complex parsers that use BindP
-- (like `many'). As a workaround a single special case is supported,
-- for `many' arguments that generate a list of strings.
injectDefaults :: String -- ^ prefix, program name
-> [(String, a -> [String] -> a)] -- ^ append extra options for arguments that are lists of strings
-> ParserInfo a -- ^ original parsers
-> IO (ParserInfo a)
injectDefaults prefix lenses parser = do
e <- getEnvironment
config <- (readFile . (</> "config") =<< getAppUserDataDirectory prefix)
`E.catch` \(_::E.SomeException) -> return ""
let env = M.fromList . filter ((==[prefix]) . take 1 . fst) $
configLines config <> -- config first
map (\(k,v) -> (splitOn "_" $ map toLower k, v)) e -- env vars override config
p' = parser { infoParser = injectDefaultP env [prefix] (infoParser parser) }
return $ foldl' (\p (key,l) -> fmap (updateA env key l) p) p' lenses
updateA :: M.Map [String] String -> String -> (a -> [String] -> a) -> a -> a
updateA env key upd a =
case M.lookup (splitOn "." key) env of
Nothing -> a
Just v -> upd a (splitOn ":" v)
-- | really simple key/value file reader: x.y = z -> (["x","y"],"z")
configLines :: String -> [([String], String)]
configLines = catMaybes . map (mkLine . takeWhile (/='#')) . lines
where
trim = let f = reverse . dropWhile isSpace in f . f
mkLine l | (k, ('=':v)) <- break (=='=') l = Just (splitOn "." (trim k), trim v)
| otherwise = Nothing
-- | inject the environment into the parser
-- the map contains the paths with the value that's passed into the reader if the
-- command line parser gives no result
injectDefaultP :: M.Map [String] String -> [String] -> Parser a -> Parser a
injectDefaultP _env _path n@(NilP{}) = n
injectDefaultP env path p@(OptP o)
| (Option (CmdReader cmds f) props) <- o =
let cmdMap = M.fromList (map (\c -> (c, mkCmd c)) cmds)
mkCmd cmd =
let (Just parseri) = f cmd
in parseri { infoParser = injectDefaultP env (path ++ [normalizeName cmd]) (infoParser parseri) }
in OptP (Option (CmdReader cmds (`M.lookup` cmdMap)) props)
| (Option (OptReader names (CReader _ rdr)) _) <- o =
p <|> maybe empty pure (msum $ map (rdr <=< getEnvValue env path) names)
| (Option (FlagReader names a) _) <- o =
p <|> if any ((==Just "1") . getEnvValue env path) names then pure a else empty
| otherwise = p
injectDefaultP env path (MultP p1 p2) =
MultP (injectDefaultP env path p1) (injectDefaultP env path p2)
injectDefaultP env path (AltP p1 p2) =
AltP (injectDefaultP env path p1) (injectDefaultP env path p2)
injectDefaultP _env _path b@(BindP {}) = b
getEnvValue :: M.Map [String] String -> [String] -> OptName -> Maybe String
getEnvValue env path (OptLong l) = M.lookup (path ++ [normalizeName l]) env
getEnvValue _ _ _ = Nothing
normalizeName :: String -> String
normalizeName = map toLower . filter isAlphaNum
| piyush-kurur/yesod | yesod/Options.hs | mit | 4,306 | 0 | 18 | 1,218 | 1,282 | 679 | 603 | 64 | 2 |
import qualified Data.Map as Map
-- In hindsight, this problem is equivalent to counting the permutations of a
-- list containing 20 'down's and 20 'right's, which can be computed with a
-- single equation.
latticePaths :: Int -> Int
latticePaths n = fst $ f Map.empty n n
where
f m 0 _ = (1,m)
f m _ 0 = (1,m)
f m j k = let key = (min j k, max j k) in
case Map.lookup (min j k, max j k) m of
Just i -> (i,m)
Nothing ->
let (c1,m1) = f m (j-1) k
(c2,m2) = f m1 j (k-1)
ret = c1+c2 in
(ret, Map.insert (min j k, max j k) ret m2)
solve :: Int
solve = latticePaths 20
main = putStrLn $ show solve
| pshendry/project-euler-solutions | 0015/solution.hs | mit | 683 | 0 | 18 | 222 | 290 | 152 | 138 | 16 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-
Limits for memory, cpu time, etc. under a "sandbox"
-}
module Codex.Tester.Limits (
Limits(..),
lookupLimits,
) where
import Data.Configurator.Types(Config)
import qualified Data.Configurator as Configurator
import Control.Monad (mplus)
-- | SafeExec limits
data Limits
= Limits { maxCpuTime :: !(Maybe Int) -- seconds
, maxClockTime :: !(Maybe Int) -- seconds
, maxMemory :: !(Maybe Int) -- KB
, maxStack :: !(Maybe Int) -- KB
, maxFSize :: !(Maybe Int) -- KB
, maxCore :: !(Maybe Int) -- KB
, numProc :: !(Maybe Int)
} deriving (Eq, Show, Read)
instance Monoid Limits where
-- | empty element; no limits set
mempty
= Limits { maxCpuTime = Nothing
, maxClockTime = Nothing
, maxMemory = Nothing
, maxStack = Nothing
, numProc = Nothing
, maxFSize = Nothing
, maxCore = Nothing
}
instance Semigroup Limits where
-- | combine limits; left-hand side overrriding right-hand side
l <> r
= Limits { maxCpuTime = maxCpuTime l `mplus` maxCpuTime r,
maxClockTime = maxClockTime l `mplus` maxClockTime r,
maxMemory = maxMemory l `mplus` maxMemory r,
maxStack = maxStack l `mplus` maxStack r,
maxFSize = maxFSize l `mplus` maxFSize r,
maxCore = maxCore l `mplus` maxCore r,
numProc = numProc l `mplus` numProc r
}
-- | lookup limits from a subconfig
lookupLimits :: Config -> IO Limits
lookupLimits cfg = do
cpu <- Configurator.lookup cfg "max_cpu"
clock<- Configurator.lookup cfg "max_clock"
mem <- Configurator.lookup cfg "max_memory"
stack <- Configurator.lookup cfg "max_stack"
nproc <- Configurator.lookup cfg "num_proc"
max_fsize <- Configurator.lookup cfg "max_fsize"
max_core <- Configurator.lookup cfg "max_core"
return Limits { maxCpuTime = cpu
, maxClockTime = clock
, maxMemory = mem
, maxStack = stack
, numProc = nproc
, maxFSize = max_fsize
, maxCore = max_core
}
| pbv/codex | src/Codex/Tester/Limits.hs | mit | 2,384 | 0 | 11 | 863 | 548 | 306 | 242 | 64 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.TextTrackList
(js_item, item, js_getTrackById, getTrackById, js_getLength,
getLength, addTrack, change, removeTrack, TextTrackList,
castToTextTrackList, gTypeTextTrackList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"item\"]($2)" js_item ::
JSRef TextTrackList -> Word -> IO (JSRef TextTrack)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList.item Mozilla TextTrackList.item documentation>
item :: (MonadIO m) => TextTrackList -> Word -> m (Maybe TextTrack)
item self index
= liftIO ((js_item (unTextTrackList self) index) >>= fromJSRef)
foreign import javascript unsafe "$1[\"getTrackById\"]($2)"
js_getTrackById ::
JSRef TextTrackList -> JSString -> IO (JSRef TextTrack)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList.getTrackById Mozilla TextTrackList.getTrackById documentation>
getTrackById ::
(MonadIO m, ToJSString id) =>
TextTrackList -> id -> m (Maybe TextTrack)
getTrackById self id
= liftIO
((js_getTrackById (unTextTrackList self) (toJSString id)) >>=
fromJSRef)
foreign import javascript unsafe "$1[\"length\"]" js_getLength ::
JSRef TextTrackList -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList.length Mozilla TextTrackList.length documentation>
getLength :: (MonadIO m) => TextTrackList -> m Word
getLength self = liftIO (js_getLength (unTextTrackList self))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList.onaddtrack Mozilla TextTrackList.onaddtrack documentation>
addTrack :: EventName TextTrackList Event
addTrack = unsafeEventName (toJSString "addtrack")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList.onchange Mozilla TextTrackList.onchange documentation>
change :: EventName TextTrackList Event
change = unsafeEventName (toJSString "change")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList.onremovetrack Mozilla TextTrackList.onremovetrack documentation>
removeTrack :: EventName TextTrackList Event
removeTrack = unsafeEventName (toJSString "removetrack") | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/TextTrackList.hs | mit | 2,990 | 22 | 11 | 389 | 666 | 389 | 277 | 44 | 1 |
-- Head, Tail, Init and Last
-- http://www.codewars.com/kata/54592a5052756d5c5d0009c3
module ListOps where
import Prelude hiding (head, tail, init, last)
head (x:_) = x
tail (_:xs) = xs
init [x] = []
init (x:xs) = x : init xs
last [x] = x
last (_:xs) = last xs
| gafiatulin/codewars | src/7 kyu/ListOps.hs | mit | 349 | 0 | 7 | 134 | 118 | 66 | 52 | 8 | 1 |
module Drawhub.Region (
Size ( .. ),
scaleFixedWidth,
scaleFixedHeight,
Point ( .. ),
pointX,
pointY,
pointBimap,
add,
Region ( .. ),
regionTopLeft,
regionBottomRight,
regionWidth,
regionHeight,
regionSize,
isInclude
) where
data Size a = Size a a deriving Show
data Point a = Point a a deriving Show
data Region a = Region (Point a) (Point a) deriving Show
instance Functor Size where
fmap f (Size w h) = Size (f w) (f h)
instance Functor Point where
fmap f (Point x y) = Point (f x) (f y)
instance Eq a => Eq (Point a) where
(==) (Point x0 y0) (Point x1 y1) = x0 == x1 && y0 == y1
instance Functor Region where
fmap f (Region p0 p1) = Region (fmap f p0) (fmap f p1)
pointX :: Point a -> a
pointX (Point x _) = x
pointY :: Point a -> a
pointY (Point _ y) = y
pointBimap :: (a -> b) -> (a -> b) -> Point a -> Point b
pointBimap fx fy (Point x y) = Point (fx x) (fy y)
add :: Num a => Point a -> Point a -> Point a
(Point x0 y0) `add` (Point x1 y1) = Point (x0 + x1) (y0 + y1)
scaleFixedWidth :: Integral a => a -> Size a -> Size a
scaleFixedWidth width (Size w h) = Size width (ceiling $ fromIntegral h * ratio)
where ratio = fromIntegral width / fromIntegral w
scaleFixedHeight :: Integral a => a -> Size a -> Size a
scaleFixedHeight height (Size w h) = Size (ceiling $ fromIntegral w * ratio) height
where ratio = fromIntegral height / fromIntegral h
regionTopLeft :: Region a -> Point a
regionTopLeft (Region p _) = p
regionBottomRight :: Region a -> Point a
regionBottomRight (Region _ p) = p
regionDelta :: Num b => (Point a -> b) -> Region a -> b
regionDelta f region = f (regionBottomRight region) - f (regionTopLeft region)
regionWidth :: Num a => Region a -> a
regionWidth = regionDelta pointX
regionHeight :: Num a => Region a -> a
regionHeight = regionDelta pointY
regionSize :: Num a => Region a -> Size a
regionSize region = Size (regionWidth region) (regionHeight region)
-- check if second region is totally in first region
isInclude :: Ord a => Region a -> Region a -> Bool
isInclude limit sub
| pointX (regionTopLeft limit) > pointX (regionTopLeft sub) = False
| pointY (regionTopLeft limit) > pointY (regionTopLeft sub) = False
| pointX (regionBottomRight limit) < pointX (regionBottomRight sub) = False
| pointY (regionBottomRight limit) < pointY (regionBottomRight sub) = False
| otherwise = True
| TurpIF/Drawhub | src/main/Drawhub/Region.hs | mit | 2,443 | 0 | 11 | 565 | 1,078 | 537 | 541 | 60 | 1 |
module Rebase.Data.Semigroupoid.Static
(
module Data.Semigroupoid.Static
)
where
import Data.Semigroupoid.Static
| nikita-volkov/rebase | library/Rebase/Data/Semigroupoid/Static.hs | mit | 116 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
module L.L3.L3AST (
L3Func
,L3(..)
,D(..)
,V(..)
,E(..)
,foldV
,module L.Primitives
) where
import Control.Applicative
import Control.Monad
import Data.Int
import Data.Monoid
import qualified Data.Set as Set
import Data.Traversable hiding (sequence)
import L.Primitives
import L.Parser.SExpr
import L.Variable
import Prelude hiding (print)
type L3Func = Func E
data L3 = L3 E [L3Func]
data E = Let Variable D E | If V E E | DE D
data D = App V [V] | PrimApp PrimName [V] | VD V |
NewTuple [V] | MakeClosure Label V | ClosureProc V | ClosureVars V
data V = VarV Variable | NumV Int64 | LabelV Label
instance Show V where show = showSExpr
instance Show D where show = showSExpr
instance Show E where show = showSExpr
instance Show L3 where show = showSExpr
instance AsSExpr D where
asSExpr (App v vs) = asSExpr (asSExpr v : fmap asSExpr vs)
asSExpr (PrimApp p vs) = asSExpr (asSExpr p : fmap asSExpr vs)
asSExpr (VD v) = asSExpr v
asSExpr (NewTuple vs) = asSExpr (sym "new-tuple" : fmap asSExpr vs)
asSExpr (MakeClosure l v) = asSExpr (sym "make-closure", l, v)
asSExpr (ClosureProc v) = asSExpr (sym "closure-proc", v)
asSExpr (ClosureVars v) = asSExpr (sym "closure-vars", v)
instance AsSExpr E where
asSExpr (Let v d e) = asSExpr (sym "let", asSExpr [(v, d)], e)
asSExpr (If v te fe) = asSExpr (sym "if", v, te, fe)
asSExpr (DE d) = asSExpr d
instance AsSExpr L3 where
asSExpr (L3 e fs) = List $ asSExpr e : fmap asSExpr fs
-- v :: = x | l | num
instance FromSExpr V where
fromSExpr (AtomSym l@(':' : _)) = Right . LabelV $ Label l
fromSExpr (AtomSym v) = return . VarV $ Variable v
fromSExpr (AtomNum n) = return $ NumV (fromIntegral n)
fromSExpr bad = Left $ concat ["Parse Error: 'bad V' in: ", showSExpr bad]
instance AsSExpr V where
asSExpr (VarV (Variable v)) = AtomSym v
asSExpr (NumV n) = AtomNum n
asSExpr (LabelV (Label l)) = AtomSym l
{-
d ::= (biop v v) | (pred v) | (v v ...) | (new-array v v) | (new-tuple v ...)
(aref v v) | (aset v v v) | (alen v)
(print v) | (make-closure l v) | (closure-proc v) | (closure-vars v)
v
biop ::= + | - | * | < | <= | =
pred ::= number? | a?
-}
instance FromSExpr D where
fromSExpr = f where
f (List [AtomSym "make-closure", l, v]) = MakeClosure <$> fromSExpr l <*> fromSExpr v
f (List [AtomSym "closure-proc", v]) = ClosureProc <$> fromSExpr v
f (List [AtomSym "closure-vars", v]) = ClosureVars <$> fromSExpr v
-- TODO: this is bad because if they give the wrong number of args to a prim,
-- TODO: it'll parse a App
f (List [AtomSym "+", l, r]) = parsePrimApp2 Add l r
f (List [AtomSym "-", l, r]) = parsePrimApp2 Sub l r
f (List [AtomSym "*", l, r]) = parsePrimApp2 Mult l r
f (List [AtomSym "<", l, r]) = parsePrimApp2 LessThan l r
f (List [AtomSym "<=", l, r]) = parsePrimApp2 LTorEQ l r
f (List [AtomSym "=", l, r]) = parsePrimApp2 EqualTo l r
f (List [AtomSym "number?", v]) = parsePrimApp1 IsNumber v
f (List [AtomSym "a?", v]) = parsePrimApp1 IsArray v
f (List [AtomSym "new-array", s, v]) = parsePrimApp2 NewArray s v
f (List (AtomSym "new-tuple" : vs)) = NewTuple <$> traverse fromSExpr vs
f (List [AtomSym "aref", a, loc]) = parsePrimApp2 ARef a loc
f (List [AtomSym "aset", a, loc, v]) = parsePrimApp3 ASet a loc v
f (List [AtomSym "alen", v]) = parsePrimApp1 ALen v
f (List [AtomSym "print", v]) = parsePrimApp1 Print v
f (List (v : vs)) = App <$> fromSExpr v <*> traverse fromSExpr vs
f v = VD <$> fromSExpr v
parsePrimApp1 p v = (PrimApp p . return) <$> fromSExpr v
parsePrimApp2 b l r = (\v1 v2 -> PrimApp b [v1,v2]) <$> fromSExpr l <*> fromSExpr r
parsePrimApp3 b e1 e2 e3 =
(\v1 v2 v3 -> PrimApp b [v1,v2,v3]) <$> fromSExpr e1 <*> fromSExpr e2 <*> fromSExpr e3
-- e ::= (let ([x d]) e) | (if v e e) | d
instance FromSExpr E where
fromSExpr = f where
f (List [AtomSym "let", List [List [arg, d]], e]) = Let <$> fromSExpr arg <*> fromSExpr d <*> f e
f (List [AtomSym "if", v, te, fe]) = If <$> fromSExpr v <*> f te <*> f fe
f d = DE <$> fromSExpr d
-- p ::= (e (l (x ...) e) ...)
instance FromSExpr L3 where
fromSExpr = f where
f (List (main : funcs)) = L3 <$> fromSExpr main <*> traverse fromSExpr funcs
f bad = parseError_ "bad L3-program" bad
instance FreeVars E where
freeVars = f where
f (Let x r body) bv = f (DE r) bv <> f body (Set.insert x bv)
f (If e a b) bv = f (ve e) bv <> f a bv <> f b bv
f (DE (VD (VarV v))) bv = if Set.member v bv then mempty else Set.singleton v
f (DE (VD _)) _ = Set.empty
f (DE (MakeClosure _ v)) bv = f (ve v) bv
f (DE (ClosureProc v)) bv = f (ve v) bv
f (DE (ClosureVars v)) bv = f (ve v) bv
f (DE (App v vs)) bv = mconcat $ f (ve v) bv : fmap (flip f bv) (ve <$> vs)
f (DE (NewTuple vs)) bv = mconcat $ fmap (flip f bv) (ve <$> vs)
f (DE (PrimApp _ vs)) bv = mconcat $ fmap (flip f bv) (ve <$> vs)
ve = DE . VD
foldV :: (Variable -> a) -> (Int64 -> a) -> (Label -> a) -> V -> a
foldV f _ _ (VarV v) = f v
foldV _ f _ (NumV v) = f v
foldV _ _ f (LabelV v) = f v
| joshcough/L5-Haskell | src/L/L3/L3AST.hs | mit | 5,477 | 0 | 15 | 1,601 | 2,358 | 1,209 | 1,149 | 102 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module ZoomHub.Worker
( processExistingContent,
processExpiredActiveContent,
)
where
import Control.Concurrent (threadDelay)
import Control.Exception.Enclosed (catchAny)
import Control.Lens ((&), (.~), (^.))
import Control.Monad (forever)
import Control.Monad.IO.Class (liftIO)
import Data.Aeson (encode, object, (.=))
import Data.ByteString.Lazy (toStrict)
import Data.Foldable (for_)
import Data.Text (Text)
import Data.Time.Units (Second, fromMicroseconds, toMicroseconds)
import Data.Time.Units.Instances ()
import qualified Network.AWS as AWS
import qualified Network.AWS.Lambda as AWSLambda
import Squeal.PostgreSQL.Pool (runPoolPQ)
import System.Random (randomRIO)
import qualified ZoomHub.AWS as ZHAWS
import ZoomHub.Config (Config (..))
import ZoomHub.Log.Logger (logException, logInfo)
import ZoomHub.Storage.PostgreSQL (dequeueNextUnprocessed)
import ZoomHub.Types.Content (Content (contentId))
import ZoomHub.Types.ContentId (unContentId)
import qualified ZoomHub.Types.Environment as Environment
import ZoomHub.Utils (lenientDecodeUtf8)
-- Constants
processExistingContentInterval :: Second
processExistingContentInterval = 5
-- Public API
processExistingContent :: Config -> String -> IO ()
processExistingContent Config {..} workerId = forever $ do
-- logDebug "worker:start" ["worker" .= workerId]
go `catchAny` \ex ->
-- TODO: Mark as `completed:failure` or `initialized`:
logException "worker:error" ex extraLogMeta
-- logDebug "worker:end" extraLogMeta
let delta = (2 * toMicroseconds sleepBase) `div` 2
jitter <- randomRIO (0, delta)
let sleepDuration = fromMicroseconds $ delta + jitter :: Second
-- logDebug "Wait for next unprocessed content" $
-- ("sleepDuration" .= sleepDuration) : extraLogMeta
threadDelay . fromIntegral $ toMicroseconds sleepDuration
where
go = do
mContent <- liftIO $ runPoolPQ dequeueNextUnprocessed dbConnPool
for_ mContent $ \content -> do
logInfo
"worker:lambda:start"
[ "wwwURL" .= wwwURL content,
"apiURL" .= apiURL content
]
ZHAWS.run aws logLevel $ do
response <-
AWS.send $
AWSLambda.invoke
"processContent"
(toStrict . encode $ object ["contentURL" .= apiURL content])
& AWSLambda.iQualifier .~ (Just . Environment.toText $ environment)
for_ (response ^. AWSLambda.irsPayload) $ \output ->
liftIO $
logInfo
"worker:lambda:response"
[ "output" .= lenientDecodeUtf8 output,
"wwwURL" .= wwwURL content,
"apiURL" .= apiURL content
]
sleepBase = processExistingContentInterval
-- TODO: Split `BASE_URI` into `WWW_BASE_URI` and `API_BASE_URI`:
wwwURL c = mconcat [show baseURI, "/", unContentId (contentId c)]
apiURL c = mconcat [show baseURI, "/v1/content/", unContentId (contentId c)]
extraLogMeta =
[ "worker" .= workerId,
"topic" .= ("worker:process:existing" :: Text)
]
processExpiredActiveContent :: Config -> IO ()
processExpiredActiveContent Config {..} = pure ()
| zoomhub/zoomhub | src/ZoomHub/Worker.hs | mit | 3,322 | 0 | 26 | 703 | 779 | 441 | 338 | 69 | 1 |
import Data.List (foldl')
import Data.Numbers.Primes (primes)
sieve :: Int -> [Int] -> [Int]
sieve p = filter (\x -> x `mod` p /= 0)
phi :: Int -> Int -> Int
phi x a = length $ foldl' (flip sieve) [1..x] (take a primes)
isqrt :: Int -> Int
isqrt = floor . sqrt . fromIntegral
primePi :: Int -> Int
primePi 1 = 0
primePi x = phi x a + a - 1 where a = primePi $ isqrt x
main :: IO ()
main = print $ primePi 1000000 | genos/online_problems | prog_praxis/legendre_primes.hs | mit | 417 | 0 | 9 | 96 | 219 | 116 | 103 | 13 | 1 |
{-# LANGUAGE DeriveDataTypeable, RecordWildCards, FlexibleContexts #-}
--------------------------------------------------------------------------------
{- |
Module : Data.Acid.CenteredSlave.hs
Copyright : MIT
Maintainer : [email protected]
Portability : non-portable (uses GHC extensions)
The Slave part of a the Centered replication backend for acid state.
-}
--------------------------------------------------------------------------------
-- SLAVE part
module Data.Acid.Centered.Slave
(
enslaveState
, enslaveStateFrom
, enslaveRedState
, enslaveRedStateFrom
, SlaveState(..)
) where
import Data.Typeable
import Data.SafeCopy
import Data.Serialize (decode, encode, runPutLazy, runGetLazy)
import Data.Acid
import Data.Acid.Core
import Data.Acid.Abstract
import Data.Acid.Local
import Data.Acid.Log
import Data.Acid.Centered.Common
import Control.Concurrent (forkIO, ThreadId, myThreadId, killThread, threadDelay, forkIOWithUnmask)
import Control.Concurrent.MVar (MVar, newMVar, newEmptyMVar, isEmptyMVar,
withMVar, modifyMVar, modifyMVar_,
takeMVar, putMVar, tryPutMVar)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
import Control.Concurrent.STM.TVar (readTVar, writeTVar)
import Data.IORef (writeIORef)
import qualified Control.Concurrent.Event as Event
import Control.Monad.STM (atomically)
import Control.Monad (void, when, unless)
import Control.Exception (handle, throwTo, SomeException, ErrorCall(..))
import System.ZMQ4 (Context, Socket, Dealer(..),
setReceiveHighWM, setSendHighWM, setLinger, restrict,
poll, Poll(..), Event(..),
context, term, socket, close,
connect, disconnect, send, receive)
import System.FilePath ( (</>) )
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
--------------------------------------------------------------------------------
-- | Slave state structure, for internal use.
data SlaveState st
= SlaveState { slaveLocalState :: AcidState st
, slaveStateIsRed :: Bool
, slaveStateLock :: MVar ()
, slaveRepFinalizers :: MVar (IntMap (IO ()))
, slaveRepChan :: Chan SlaveRepItem
, slaveSyncDone :: Event.Event
, slaveRevision :: MVar NodeRevision
, slaveRequests :: MVar SlaveRequests
, slaveLastRequestID :: MVar RequestID
, slaveRepThreadId :: MVar ThreadId
, slaveReqThreadId :: MVar ThreadId
, slaveParentThreadId :: ThreadId
, slaveZmqContext :: Context
, slaveZmqAddr :: String
, slaveZmqSocket :: MVar (Socket Dealer)
} deriving (Typeable)
-- | Memory of own Requests sent to Master.
type SlaveRequests = IntMap (IO (IO ()),ThreadId)
-- | One Update + Metainformation to replicate.
data SlaveRepItem =
SRIEnd
| SRICheckpoint Revision
| SRIArchive Revision
| SRIUpdate Revision (Maybe RequestID) (Tagged ByteString)
-- | Open a local State as Slave for a Master.
--
-- The directory for the local state files is the default one ("state/[typeOf
-- state]").
enslaveState :: (IsAcidic st, Typeable st) =>
String -- ^ hostname of the Master
-> PortNumber -- ^ port to connect to
-> st -- ^ initial state
-> IO (AcidState st)
enslaveState address port initialState =
enslaveStateFrom ("state" </> show (typeOf initialState)) address port initialState
-- | Open a local State as Slave for a Master.
--
-- The directory for the local state files is the default one ("state/[typeOf
-- state]").
enslaveRedState :: (IsAcidic st, Typeable st) =>
String -- ^ hostname of the Master
-> PortNumber -- ^ port to connect to
-> st -- ^ initial state
-> IO (AcidState st)
enslaveRedState address port initialState =
enslaveRedStateFrom ("state" </> show (typeOf initialState)) address port initialState
-- | Open a local State as Slave for a Master. The directory of the local state
-- files can be specified.
enslaveStateFrom :: (IsAcidic st, Typeable st) =>
FilePath -- ^ location of the local state files.
-> String -- ^ hostname of the Master
-> PortNumber -- ^ port to connect to
-> st -- ^ initial state
-> IO (AcidState st)
enslaveStateFrom = enslaveMayRedStateFrom False
-- | Open a local State as Slave for a _redundant_ Master. The directory of the local state
-- files can be specified.
enslaveRedStateFrom :: (IsAcidic st, Typeable st) =>
FilePath -- ^ location of the local state files.
-> String -- ^ hostname of the Master
-> PortNumber -- ^ port to connect to
-> st -- ^ initial state
-> IO (AcidState st)
enslaveRedStateFrom = enslaveMayRedStateFrom True
-- | Open a local State as Slave for a Master, redundant or not.
-- The directory of the local state files can be specified.
enslaveMayRedStateFrom :: (IsAcidic st, Typeable st) =>
Bool -- ^ is redundant
-> FilePath -- ^ location of the local state files.
-> String -- ^ hostname of the Master
-> PortNumber -- ^ port to connect to
-> st -- ^ initial state
-> IO (AcidState st)
enslaveMayRedStateFrom isRed directory address port initialState = do
-- local
lst <- openLocalStateFrom directory initialState
lrev <- getLocalRevision lst
rev <- newMVar lrev
debug $ "Opening enslaved state at revision " ++ show lrev
srs <- newMVar IM.empty
lastReqId <- newMVar 0
repChan <- newChan
syncDone <- Event.new
reqTid <- newEmptyMVar
repTid <- newEmptyMVar
parTid <- myThreadId
repFin <- newMVar IM.empty
sLock <- newEmptyMVar
-- remote
let addr = "tcp://" ++ address ++ ":" ++ show port
ctx <- context
sock <- socket ctx Dealer
setReceiveHighWM (restrict (100*1000 :: Int)) sock
setSendHighWM (restrict (100*1000 :: Int)) sock
connect sock addr
msock <- newMVar sock
sendToMaster msock $ NewSlave lrev
let slaveState = SlaveState { slaveLocalState = lst
, slaveStateIsRed = isRed
, slaveStateLock = sLock
, slaveRepFinalizers = repFin
, slaveRepChan = repChan
, slaveSyncDone = syncDone
, slaveRevision = rev
, slaveRequests = srs
, slaveLastRequestID = lastReqId
, slaveReqThreadId = reqTid
, slaveRepThreadId = repTid
, slaveParentThreadId = parTid
, slaveZmqContext = ctx
, slaveZmqAddr = addr
, slaveZmqSocket = msock
}
void $ forkIOWithUnmask $ slaveRequestHandler slaveState
void $ forkIO $ slaveReplicationHandler slaveState
return $ slaveToAcidState slaveState
where
getLocalRevision =
atomically . readTVar . logNextEntryId . localEvents . downcast
-- | Replication handler of the Slave.
slaveRequestHandler :: (IsAcidic st, Typeable st) => SlaveState st -> (IO () -> IO ()) -> IO ()
slaveRequestHandler slaveState@SlaveState{..} unmask = do
mtid <- myThreadId
putMVar slaveReqThreadId mtid
let loop = handle (\e -> throwTo slaveParentThreadId (e :: SomeException)) $
unmask $ handle killHandler $ do
--waitRead =<< readMVar slaveZmqSocket
-- FIXME: we needn't poll if not for strange zmq behaviour
re <- withMVar slaveZmqSocket $ \sock -> poll 100 [Sock sock [In] Nothing]
unless (null $ head re) $ do
msg <- withMVar slaveZmqSocket receive
case decode msg of
Left str -> error $ "Data.Serialize.decode failed on MasterMessage: " ++ show str
Right mmsg -> handleMessage mmsg
loop
loop
where
killHandler :: AcidException -> IO ()
killHandler GracefulExit = return ()
handleMessage m = do
debug $ "Received: " ++ show m
case m of
-- We are sent an Update to replicate.
DoRep r i d -> queueRepItem slaveState (SRIUpdate r i d)
-- We are sent a Checkpoint for synchronization.
DoSyncCheckpoint r d -> replicateSyncCp slaveState r d
-- We are sent an Update to replicate for synchronization.
DoSyncRep r d -> replicateSyncUpdate slaveState r d
-- Master done sending all synchronization Updates.
SyncDone c -> onSyncDone slaveState c
-- We are sent a Checkpoint request.
DoCheckpoint r -> queueRepItem slaveState (SRICheckpoint r)
-- We are sent an Archive request.
DoArchive r -> queueRepItem slaveState (SRIArchive r)
-- Full replication of a revision
FullRep r -> modifyMVar_ slaveRepFinalizers $ \rf -> do
rf IM.! r
return $ IM.delete r rf
-- Full replication of events up to revision
FullRepTo r -> modifyMVar_ slaveRepFinalizers $ \rf -> do
let (ef, nrf) = IM.partitionWithKey (\k _ -> k <= r) rf
sequence_ (IM.elems ef)
return nrf
-- We are allowed to Quit.
MayQuit -> writeChan slaveRepChan SRIEnd
-- We are requested to Quit - shall be handled by
-- 'bracket' usage by user.
MasterQuit -> throwTo slaveParentThreadId $
ErrorCall "Data.Acid.Centered.Slave: Master quit."
-- no other messages possible, enforced by type checker
-- | After sync check CRC
onSyncDone :: (IsAcidic st, Typeable st) => SlaveState st -> Crc -> IO ()
onSyncDone SlaveState{..} crc = do
localCrc <- crcOfState slaveLocalState
if crc /= localCrc then
error "Data.Acid.Centered.Slave: CRC mismatch after sync."
else do
debug "Sync Done, CRC fine."
Event.set slaveSyncDone
-- | Queue Updates into Chan for replication.
-- We use the Chan so Sync-Updates and normal ones can be interleaved.
queueRepItem :: SlaveState st -> SlaveRepItem -> IO ()
queueRepItem SlaveState{..} repItem = do
debug "Queuing RepItem."
writeChan slaveRepChan repItem
-- | Replicates content of Chan.
slaveReplicationHandler :: Typeable st => SlaveState st -> IO ()
slaveReplicationHandler slaveState@SlaveState{..} = do
mtid <- myThreadId
putMVar slaveRepThreadId mtid
-- todo: timeout is magic variable, make customizable
noTimeout <- Event.waitTimeout slaveSyncDone $ 10*1000*1000
unless noTimeout $ throwTo slaveParentThreadId $
ErrorCall "Data.Acid.Centered.Slave: Took too long to sync. Timeout."
let loop = handle (\e -> throwTo slaveParentThreadId (e :: SomeException)) $ do
mayRepItem <- readChan slaveRepChan
case mayRepItem of
SRIEnd -> return ()
SRICheckpoint r -> repCheckpoint slaveState r >> loop
SRIArchive r -> repArchive slaveState r >> loop
SRIUpdate r i d -> replicateUpdate slaveState r i d False >> loop
loop
-- signal that we're done
void $ takeMVar slaveRepThreadId
-- | Replicate Sync-Checkpoints directly.
replicateSyncCp :: (IsAcidic st, Typeable st) =>
SlaveState st -> Revision -> ByteString -> IO ()
replicateSyncCp SlaveState{..} rev encoded = do
st <- decodeCheckpoint encoded
let lst = downcast slaveLocalState
let core = localCore lst
modifyMVar_ slaveRevision $ \sr -> do
when (sr > rev) $ error "Data.Acid.Centered.Slave: Revision mismatch for checkpoint: Slave is newer."
modifyCoreState_ core $ \_ -> do
writeIORef (localCopy lst) st
createCpFake lst encoded rev
adjustEventLogId lst rev
return st
return rev
where
adjustEventLogId l r = do
atomically $ writeTVar (logNextEntryId (localEvents l)) r
void $ cutFileLog (localEvents l)
createCpFake l e r = do
mvar <- newEmptyMVar
pushAction (localEvents l) $
pushEntry (localCheckpoints l) (Checkpoint r e) (putMVar mvar ())
takeMVar mvar
decodeCheckpoint e =
case runGetLazy safeGet e of
Left msg -> error $ "Data.Acid.Centered.Slave: Checkpoint could not be decoded: " ++ msg
Right val -> return val
-- | Replicate Sync-Updates directly.
replicateSyncUpdate :: Typeable st => SlaveState st -> Revision -> Tagged ByteString -> IO ()
replicateSyncUpdate slaveState rev event = replicateUpdate slaveState rev Nothing event True
-- | Replicate an Update as requested by Master.
-- Updates that were requested by this Slave are run locally and the result
-- put into the MVar in SlaveRequests.
-- Other Updates are just replicated without using the result.
replicateUpdate :: Typeable st => SlaveState st -> Revision -> Maybe RequestID -> Tagged ByteString -> Bool -> IO ()
replicateUpdate SlaveState{..} rev reqId event syncing = do
debug $ "Got an Update to replicate " ++ show rev
modifyMVar_ slaveRevision $ \nr -> if rev - 1 == nr
then do
-- commit / run it locally
case reqId of
Nothing -> replicateForeign
Just rid -> replicateOwn rid
-- send reply: we're done
unless syncing $ sendToMaster slaveZmqSocket $ RepDone rev
return rev
else do
sendToMaster slaveZmqSocket RepError
void $ error $
"Data.Acid.Centered.Slave: Replication failed at revision "
++ show nr ++ " -> " ++ show rev
return nr
where
replicateForeign =
if slaveStateIsRed then do
act <- newEmptyMVar >>= scheduleLocalColdUpdate' (downcast slaveLocalState) event
modifyMVar_ slaveRepFinalizers $ return . IM.insert rev act
else
void $ scheduleColdUpdate slaveLocalState event
replicateOwn rid = do
act <- modifyMVar slaveRequests $ \srs -> do
debug $ "This is the Update for Request " ++ show rid
let (icallback, timeoutId) = srs IM.! rid
callback <- icallback
killThread timeoutId
let nsrs = IM.delete rid srs
return (nsrs, callback)
when slaveStateIsRed $
modifyMVar_ slaveRepFinalizers $ return . IM.insert rev act
repCheckpoint :: SlaveState st -> Revision -> IO ()
repCheckpoint SlaveState{..} rev = do
debug $ "Got Checkpoint request at revision: " ++ show rev
withMVar slaveRevision $ \_ ->
-- create checkpoint
createCheckpoint slaveLocalState
repArchive :: SlaveState st -> Revision -> IO ()
repArchive SlaveState{..} rev = do
debug $ "Got Archive request at revision: " ++ show rev
withMVar slaveRevision $ \_ ->
createArchive slaveLocalState
-- | Update on slave site.
-- The steps are:
-- - Request Update from Master
-- - Master issues Update with same RequestID
-- - repHandler replicates and puts result in MVar
scheduleSlaveUpdate :: (UpdateEvent e, Typeable (EventState e)) => SlaveState (EventState e) -> e -> IO (MVar (EventResult e))
scheduleSlaveUpdate slaveState@SlaveState{..} event = do
unlocked <- isEmptyMVar slaveStateLock
if not unlocked then error "State is locked."
else do
debug "Update by Slave."
result <- newEmptyMVar
reqId <- getNextRequestId slaveState
modifyMVar_ slaveRequests $ \srs -> do
let encoded = runPutLazy (safePut event)
sendToMaster slaveZmqSocket $ ReqUpdate reqId (methodTag event, encoded)
timeoutID <- forkIO $ timeoutRequest slaveState reqId result
let callback = if slaveStateIsRed
then scheduleLocalUpdate' (downcast slaveLocalState) event result
else do
hd <- scheduleUpdate slaveLocalState event
void $ forkIO $ putMVar result =<< takeMVar hd
return (return ()) -- bogus finalizer
return $ IM.insert reqId (callback, timeoutID) srs
return result
-- | Cold Update on slave site. This enables for using Remote.
scheduleSlaveColdUpdate :: Typeable st => SlaveState st -> Tagged ByteString -> IO (MVar ByteString)
scheduleSlaveColdUpdate slaveState@SlaveState{..} encoded = do
unlocked <- isEmptyMVar slaveStateLock
if not unlocked then error "State is locked."
else do
debug "Cold Update by Slave."
result <- newEmptyMVar
-- slaveLastRequestID is only modified here - and used for locking the state
reqId <- getNextRequestId slaveState
modifyMVar_ slaveRequests $ \srs -> do
sendToMaster slaveZmqSocket $ ReqUpdate reqId encoded
timeoutID <- forkIO $ timeoutRequest slaveState reqId result
let callback = if slaveStateIsRed
then scheduleLocalColdUpdate' (downcast slaveLocalState) encoded result
else do
hd <- scheduleColdUpdate slaveLocalState encoded
void $ forkIO $ putMVar result =<< takeMVar hd
return (return ()) -- bogus finalizer
return $ IM.insert reqId (callback, timeoutID) srs
return result
-- | Generate ID for another request.
getNextRequestId :: SlaveState st -> IO RequestID
getNextRequestId SlaveState{..} = modifyMVar slaveLastRequestID $ \x -> return (x+1,x+1)
-- | Ensures requests are actually answered or fail.
-- On timeout the Slave dies, not the thread that invoked the Update.
timeoutRequest :: SlaveState st -> RequestID -> MVar m -> IO ()
timeoutRequest SlaveState{..} reqId mvar = do
threadDelay $ 5*1000*1000
stillThere <- withMVar slaveRequests (return . IM.member reqId)
when stillThere $ do
putMVar mvar $ error "Data.Acid.Centered.Slave: Update-Request timed out."
throwTo slaveParentThreadId $ ErrorCall "Data.Acid.Centered.Slave: Update-Request timed out."
-- | Send a message to Master.
sendToMaster :: MVar (Socket Dealer) -> SlaveMessage -> IO ()
sendToMaster msock smsg = withMVar msock $ \sock -> send sock [] (encode smsg)
-- | Close an enslaved State.
liberateState :: SlaveState st -> IO ()
liberateState SlaveState{..} =
-- lock state against updates: disallow requests
whenM (tryPutMVar slaveStateLock ()) $ do
debug "Closing Slave state..."
-- check / wait unprocessed requests
debug "Waiting for Requests to finish."
waitPoll 100 (withMVar slaveRequests (return . IM.null))
-- send master quit message
sendToMaster slaveZmqSocket SlaveQuit
-- wait replication chan, only if sync done
syncDone <- Event.isSet slaveSyncDone
when syncDone $ do
debug "Waiting for repChan to empty."
mtid <- myThreadId
putMVar slaveRepThreadId mtid
-- kill handler threads
debug "Killing request handler."
withMVar slaveReqThreadId $ flip throwTo GracefulExit
-- cleanup zmq
debug "Closing down zmq."
withMVar slaveZmqSocket $ \s -> do
-- avoid the socket hanging around
setLinger (restrict (1000 :: Int)) s
disconnect s slaveZmqAddr
close s
term slaveZmqContext
-- cleanup local state
debug "Closing local state."
closeAcidState slaveLocalState
slaveToAcidState :: (IsAcidic st, Typeable st) => SlaveState st -> AcidState st
slaveToAcidState slaveState
= AcidState { _scheduleUpdate = scheduleSlaveUpdate slaveState
, scheduleColdUpdate = scheduleSlaveColdUpdate slaveState
, _query = query $ slaveLocalState slaveState
, queryCold = queryCold $ slaveLocalState slaveState
, createCheckpoint = createCheckpoint $ slaveLocalState slaveState
, createArchive = createArchive $ slaveLocalState slaveState
, closeAcidState = liberateState slaveState
, acidSubState = mkAnyState slaveState
}
| sdx23/acid-state-dist | src/Data/Acid/Centered/Slave.hs | mit | 21,264 | 0 | 23 | 6,599 | 4,515 | 2,252 | 2,263 | 351 | 11 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module DBus.Reactive
( Network (..)
, newNet
, listen
, listen'
, sync
, signalEvent
, behaviourToProperty
, propertyBehaviour'
, propertyBehaviour
, eventMethod
, eventSignal
) where
import Control.Concurrent
import Control.Concurrent.STM
import qualified Control.Exception as Ex
import Control.Monad.Trans
import DBus
import DBus.Signal
import Data.IORef
import Data.Text (Text)
import Reactive.Banana
import Reactive.Banana.Frameworks
import System.Log.Logger
logError :: String -> IO ()
logError = errorM "DBus.Reactive"
logDebug :: String -> IO ()
logDebug = debugM "DBus.Reactive"
newtype Network = Network { run :: MomentIO () -> IO () }
newNet :: IO Network
newNet = do
(ah, call) <- newAddHandler
network <- compile (do
globalExecuteEV <- fromAddHandler ah
_ <- execute globalExecuteEV
return () )
actuate network
return $ Network { run = call
}
listen :: Event a -> (a -> IO ()) -> MomentIO ()
listen ev f = do
reactimate (f <$> ev)
listen' :: Event (Future a) -> (a -> IO ()) -> MomentIO ()
listen' ev f = do
reactimate' (fmap f <$> ev)
sync :: Network -> MomentIO a -> IO a
sync Network{run = run} f = do
ref <- newIORef (error "Network hasn't written result to ref")
run $ do
res <- f
liftIO $ writeIORef ref res
readIORef ref
-- | Handle incoming signals as events
signalEvent :: Representable a =>
SignalDescription (FlattenRepType (RepType a))
-> Maybe Text
-> Network
-> DBusConnection
-> IO (Event a)
signalEvent sigD mbRemote network con = do
(event, push) <- sync network $ newEvent
handleSignal sigD mbRemote mempty push con
return event
-- | Export a behaviour as a DBus property
behaviourToProperty :: Representable a =>
ObjectPath
-> Text
-> Text
-> Network
-> Behavior a
-> DBusConnection
-> IO (Property (RepType a))
behaviourToProperty path iface name net (b :: Behavior a) con = do
let get = Just . liftIO . sync net $ valueB b
set = Nothing
prop = mkProperty path iface name get set PECSTrue :: Property (RepType a)
sendSig v = emitPropertyChanged prop v con
_ <- sync net $ do
chs <- changes b
listen' chs sendSig
return prop
-- | Track a remote property as a behaviour
--
-- @throws: MsgError
propertyBehaviour' :: Representable a =>
Maybe a
-> RemoteProperty (RepType a)
-> Network
-> DBusConnection
-> IO (Behavior a)
propertyBehaviour' def rprop net con = do
mbInit <- getProperty rprop con
i <- case mbInit of
Left e -> case def of
Nothing -> Ex.throwIO e
Just v -> do
logError $ "Error getting initial value" ++ show e
return v
Right r -> return r
(bhv, push) <- sync net $ newBehavior i
handlePropertyChanged rprop (handleP push) con
return bhv
where
handleP push Nothing = do
mbP <- getProperty rprop con
case mbP of
Left _e -> logError "could not get remote property"
Right v -> push v
handleP push (Just v ) = do
logDebug $ "property changed: " ++ show rprop
push v
-- | Track a remote property as a behaviour, throws an exception if the initial
-- pull doesn't succeed
propertyBehaviour :: Representable a =>
RemoteProperty (RepType a)
-> Network
-> DBusConnection
-> IO (Behavior a)
propertyBehaviour = propertyBehaviour' Nothing
-- | Call a method when an event fires
eventMethod :: ( Representable args
, Representable res) =>
MethodDescription (FlattenRepType (RepType args))
(FlattenRepType (RepType res))
-> Text
-> Event args
-> Network
-> DBusConnection
-> IO (Event (Either MethodError res))
eventMethod methodDescription peer ev net con = sync net $ do
(ev' , push) <- newEvent
_ <- listen ev (\x -> do
res <- callAsync methodDescription peer x [] con
_ <- forkIO $ do
r <- atomically res
push r
return ()
)
return ev'
eventSignal :: Representable a =>
Event a
-> SignalDescription (FlattenRepType (RepType a))
-> DBusConnection
-> MomentIO ()
eventSignal event signal con = do
listen event $ \v -> emitSignal signal v con
| Philonous/d-bus-reactive | src/DBus/Reactive.hs | mit | 5,066 | 0 | 19 | 1,872 | 1,416 | 687 | 729 | 136 | 5 |
import Data.Char (digitToInt)
import Data.List (intercalate)
main = do
b <- readLn :: IO Integer
n <- readLn :: IO Integer
let cycle = sadCycle b n
putStrLn $ intercalate ", " $ map show cycle
sadCycle b n = runCycle b n []
runCycle b n l
| next `elem` l = reverse $ next : takeWhile (/=next) l
| otherwise = runCycle b next (next:l)
where next = nextSad b n
nextSad b = sum . map ((^b) . toInteger) . digits
digits = map digitToInt . show
| devonhollowood/dailyprog | 2015-05-18/sad_cycles.hs | mit | 477 | 0 | 10 | 127 | 222 | 110 | 112 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Unit.Validators.PasswordValidatorSpec (spec) where
import Test.Hspec
import Control.Exception (evaluate)
import Validators.PasswordValidator
import qualified Models.Errors.Code as EC
spec :: Spec
spec = do
describe "isValid" $ do
describe "the password is less than 8 characters" $ do
it "returns an error message" $ do
isValid "abcdef1" `shouldBe` Left [EC.passwordTooShort]
describe "the password does not contain a number" $ do
it "returns an error message" $ do
isValid "abcdefgh" `shouldBe` Left [EC.passwordNoNumber]
describe "the password does not contain a number and is less than 8 characters" $ do
it "returns both error messages" $ do
isValid "abcdefg" `shouldBe` Left [EC.passwordTooShort, EC.passwordNoNumber]
describe "the password is more than 8 characters and contains a number" $ do
it "returns Right []" $ do
isValid "abcdefg1" `shouldBe` Right []
| bocuma/users-service | test/Unit/Validators/PasswordValidatorSpec.hs | mit | 986 | 0 | 19 | 206 | 224 | 111 | 113 | 21 | 1 |
import Data.List
import Data.Maybe
primes :: [Integer]
primes = [2] ++ unfoldr ( \primes ->
let newPrime = fromJust $ find (\candidate ->
all (\x -> candidate `mod` x /= 0 ) primes
) [last primes + 1 ..]
in Just(newPrime, primes++[newPrime])
) [2]
factors :: Integer -> [Integer]
factors 1 = []
factors x =
let newFactor = fromJust $ find (\candidate -> x `mod` candidate == 0) primes
in [newFactor] ++ factors(x `div` newFactor)
result :: Integer
result = last $ factors 600851475143
main = putStrLn $ show(result)
| nbartlomiej/haskeuler | 003/problem-003.hs | mit | 557 | 0 | 21 | 131 | 244 | 133 | 111 | 17 | 1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes, BangPatterns, ScopedTypeVariables #-}
module Main where
import Data.Text (Text)
import Control.Applicative
import Control.Monad.Reader
import qualified Data.Map.Strict as M
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy as BL hiding (map, intersperse, zip, concat, putStrLn)
import qualified Data.ByteString.Lazy.Char8 as L8
import System.Environment (getArgs)
import Data.Aeson
import Data.Monoid
import Data.List (intersperse, zip)
import qualified Data.Attoparsec.Text as AT
import Data.Attoparsec.Lazy as Atto hiding (Result)
import Data.Attoparsec.ByteString.Char8 (endOfLine, sepBy)
import qualified Data.HashMap.Lazy as HM
import qualified Data.Vector as V
import Data.Scientific (Scientific, floatingOrInteger)
import qualified Data.Text as T
import qualified Data.Text.Lazy.IO as TL
import qualified Options.Applicative as O
import Control.Monad (when)
import System.Exit
import Data.String.QQ
import System.Process (readProcess, readProcessWithExitCode)
import qualified Text.Regex.PCRE.Light as R
import qualified Data.ByteString.Char8 as B
import qualified Data.Text.Encoding as T
opts = O.info (O.helper)
(O.fullDesc
<> O.progDesc [s|Convert all HTML in JSON objects strings to plain text.
On STDIN provide an input stream of newline-separated JSON objects. |]
<> O.header "jsonconvhtml"
<> O.footer "See https://github.com/danchoi/jsonconvhtml for more information.")
main = do
O.execParser opts
x <- BL.getContents
let xs :: [Value]
xs = decodeStream x
-- transform JSON
let bashFilter = io "elinks" ["-dump"] (Just isHtml)
xs' <- mapM (runFilter bashFilter) xs
mapM_ (L8.putStrLn . encode) xs'
io :: String -> [String] -> Maybe (Text -> Bool) -> Value -> IO Value
io prog args preFilter v =
case v of
String v' -> do
if runPreFilter v'
then do
res <- readProcess prog args (T.unpack v')
return . String . T.pack $ res
else return v -- no op
_ -> return v -- no op
where
runPreFilter v =
case preFilter of
Just preFilter' -> preFilter' v
_ -> True
htmlRegex :: R.Regex
htmlRegex = R.compile (B.pack regex) [R.caseless]
-- see https://hackage.haskell.org/package/pcre-light-0.3.1/docs/Text-Regex-PCRE-Light.html#t:PCREOption
-- for other options
where regex :: String
regex = "</(html|body|p|ul|a|h1|h2|h3|table) *>|<br */?>|<img *src"
isHtml :: Text -> Bool
isHtml x = case R.match htmlRegex (T.encodeUtf8 x) [] of
Just _ -> True
Nothing -> False
------------------------------------------------------------------------
data FilterEnv = FilterEnv { filterProg :: (Value -> IO Value) }
runFilter :: (Value -> IO Value) -> Value -> IO Value
runFilter ioFilter v =
case v of
(Object v') ->
runReaderT (runFilter' v) (FilterEnv ioFilter)
x -> error $ "Expected Object, but got " ++ show x
runFilter' :: Value -> ReaderT FilterEnv IO Value
runFilter' v = do
io' <- asks filterProg
case v of
(String _) -> liftIO $ io' v
Null -> return Null
(Number _) -> return v
(Bool _) -> return v
(Array _) -> return v -- no effect on Arrays
(Object hm) -> do
let pairs = HM.toList hm
pairs' <- mapM (\(k,v) -> (,) <$> pure k <*> runFilter' v) pairs
return . Object . HM.fromList $ pairs'
------------------------------------------------------------------------
-- decode JSON object stream
decodeStream :: (FromJSON a) => BL.ByteString -> [a]
decodeStream bs = case decodeWith json bs of
(Just x, xs) | xs == mempty -> [x]
(Just x, xs) -> x:(decodeStream xs)
(Nothing, _) -> []
decodeWith :: (FromJSON a) => Parser Value -> BL.ByteString -> (Maybe a, BL.ByteString)
decodeWith p s =
case Atto.parse p s of
Atto.Done r v -> f v r
Atto.Fail _ _ _ -> (Nothing, mempty)
where f v' r = (\x -> case x of
Success a -> (Just a, r)
_ -> (Nothing, r)) $ fromJSON v'
| danchoi/jsonconvhtml | Main.hs | mit | 4,142 | 0 | 18 | 971 | 1,270 | 689 | 581 | 97 | 6 |
module Parser where
import Text.Parsec
import Text.Parsec.String
import qualified Text.Parsec.Expr as Expr
import qualified Text.Parsec.Token as Token
import Lexer
import Syntax
-- Helper function to build the association table
binary sym func = Expr.Infix (reservedOperators sym >> return (BinOp func))
associationTable = [
-- Declare * and / to be left associative
[binary "*" Times Expr.AssocLeft, binary "/" Divide Expr.AssocLeft],
-- Declare + and - to be left associative
[binary "+" Plus Expr.AssocLeft, binary "-" Minus Expr.AssocLeft],
-- Declare >, >=, <, >= to be left associative
[binary ">" GreaterThan Expr.AssocLeft, binary ">=" GreaterOrEqual Expr.AssocLeft, binary "<" LessThan Expr.AssocLeft, binary "<=" LessOrEqual Expr.AssocLeft] ]
int :: Parser Expr
int = do
number <- integer
return $ Interesting number
afloat :: Parser Expr
afloat = do
number <- float
return $ Float number
variable :: Parser Expr
variable = do
name <- identifier
return $ Var name
funcDef :: Parser Expr
funcDef = do
_ <- reserved "fun"
args <- parentheses $ commaSeparated expr
body <- bodyExpr
return $ FuncDef args body
funcCall :: Parser Expr
funcCall = do
name <- identifier
args <- parentheses $ commaSeparated expr
return $ FuncCall name args
objectLit :: Parser Expr
objectLit = do
body <- braces $ commaSeparated pair
return $ Object body
arrayLit :: Parser Expr
arrayLit = do
body <- brackets $ commaSeparated expr
return $ ArrayLiteral body
bracketAccessor :: Parser Expr
bracketAccessor = do
obj <- identifier
item <- brackets expr
return $ BracketAccessor obj item
pair :: Parser Expr
pair = do
name <- identifier
separator <- colon
value <- expr
return $ Pair name value
parseIf :: Parser Expr
parseIf = do
_ <- reserved "if"
condition <- expr
_ <- reserved "then"
body <- expr
--result <- try (reserved "else" *> expr)
return $ If condition body --result
parseIfElse :: Parser Expr
parseIfElse = do
_ <- reserved "if"
condition <- expr
_ <- reserved "then"
body <- expr
_ <- reserved "else"
elsebody <- expr
return $ IfElse condition body elsebody
returnExp :: Parser Expr
returnExp = do
_ <- reserved "return"
val <- expr
return $ Return val
stringLit :: Parser Expr
stringLit = do
stringy <- Lexer.string
return $ StringLit stringy
expr :: Parser Expr
expr = Expr.buildExpressionParser associationTable factor
bodyExpr :: Parser Expr
bodyExpr = Expr.buildExpressionParser associationTable funcBodyFactor
bracesExpr :: Parser Expr
bracesExpr = do
body <- braces $ many expr
return $ BracesExpr body
assignmentHelper :: Parser (String, Expr)
assignmentHelper = do
name <- identifier
equals <- reservedOperators "="
expression <- expr
return (name, expression)
letStatement :: Parser Expr
letStatement = do
letItGo <- reserved "let"
(name, expression) <- assignmentHelper
return $ Let name expression
varStatement :: Parser Expr
varStatement = do
varItGo <- reserved "var"
(name, expression) <- assignmentHelper
return $ VarExp name expression
attrAccessor :: Parser Expr
attrAccessor = do
variable <- identifier
dotdot <- dot
property <- identifier
return $ Accessor variable property
bareStatement :: Parser Expr
bareStatement = do
(name, expression) <- assignmentHelper
return $ BareAssign name expression
-- The <|> operator is defined in parsec. It means "try this function, but if that doesn't work, try the next one"
factor :: Parser Expr
factor = try attrAccessor
<|> try afloat
<|> try int
<|> try letStatement
<|> try varStatement
<|> try bareStatement
<|> try bracketAccessor
<|> try stringLit
<|> try bracesExpr
<|> try arrayLit
<|> try funcDef
<|> try funcCall
<|> try variable
<|> try stringLit
<|> try parseIfElse
<|> try parseIf
<|> try objectLit
<|> parentheses expr
funcBodyFactor :: Parser Expr
funcBodyFactor = try returnExp <|> factor
inputContents contents = do
Token.whiteSpace lexer
marrow <- contents
eof
return marrow
parseExpr :: String -> Either ParseError Expr
parseExpr = parse (inputContents expr) "<stdin>"
| iankronquist/riemann | src/Parser.hs | mit | 4,154 | 0 | 22 | 823 | 1,282 | 610 | 672 | 141 | 1 |
module Graphics.Object (makeObject, Object) where
import Graphics.Rendering.OpenGL
import Control.Monad.Trans.Maybe (MaybeT)
import Control.Monad.IO.Class (liftIO)
import Data.Word (Word16)
import Graphics.Shaders (makeProgram)
import Graphics.Buffers (makeBufferWithData, ptrOffset)
import Graphics.ArrayObjects (makeArrayObject)
import Graphics.Renderable
data Object = Object Program BufferObject NumArrayIndices PrimitiveMode VertexArrayObject
enableVertexArray :: Program -> (String, VertexArrayDescriptor a) -> IO ()
enableVertexArray program (name, descriptor) = do
location <- get $ attribLocation program name
vertexAttribArray location $= Enabled
vertexAttribPointer location $= (ToFloat, descriptor)
makeObject :: [(ShaderType, FilePath)] -> [Float] ->
[(String, VertexArrayDescriptor a)] -> PrimitiveMode ->
NumArrayIndices ->MaybeT IO Object
makeObject programSpec vertices attribs mode num = do
program <- makeProgram programSpec
vertexBuffer <- liftIO $ makeBufferWithData ArrayBuffer vertices StaticDraw
vao <- liftIO makeArrayObject
liftIO $ do
bindVertexArrayObject $= Just vao
bindBuffer ArrayBuffer $= Just vertexBuffer
mapM_ (enableVertexArray program) attribs
bindVertexArrayObject $= Nothing
bindBuffer ArrayBuffer $= Nothing
return $ Object program vertexBuffer num mode vao
instance Renderable Object where
render object = renderWith object (\_ -> return ())
renderWith (Object program _ size mode vao) m = do
bindVertexArrayObject $= Just vao
currentProgram $= Just program
m program
drawArrays mode 0 size
bindVertexArrayObject $= Nothing
currentProgram $= Nothing
| sgillis/HOpenGL | src/Graphics/Object.hs | gpl-2.0 | 1,756 | 0 | 12 | 348 | 489 | 245 | 244 | 38 | 1 |
fmap f [] = []
fmap f (x:xs) = f x : fmap f xs | hmemcpy/milewski-ctfp-pdf | src/content/1.10/code/haskell/snippet10.hs | gpl-3.0 | 46 | 0 | 7 | 14 | 44 | 21 | 23 | 2 | 1 |
fibs :: [Integer]
fibs = base ++ (next base)
where base = [0, 1]
{-|
`f`is the (n+1)-th Fibonacci's number. Starting from a list containing n Fibonacci's
numbers, `next` computes the next number in a lazy way.
`uncurry (+)` gives as a result something like [(\(a, b) -> a + b)]
`last` takes the last pair of the list
`zip fs $ tail fs` gives a list of pair like [(n, n-1)], where `n` and `n-1` are
the n-th and the (n-1)-th Fibonacci's numbers.
The (n+1)-th number is computed iff the computation is necessary. Otherwise the
computation stops.
-}
next :: [Integer] -> [Integer]
next fs = f : next (fs ++ [f])
where f = uncurry (+) $ last $ zip fs $ tail fs
| mdipirro/functional-languages-homeworks | Christmas/Exercise4.hs | gpl-3.0 | 677 | 0 | 10 | 146 | 108 | 59 | 49 | 6 | 1 |
module SizeTreap where
import Data.Tree.Treap
testData :: [(Int, Int, Int)]
testData = [(1, 2, 1), (3, 6, 1), (6, 44, 1), (7, 0, 1), (2, 85, 1), (4, -2, 1), (5, 4, 1), (8, 21, 1)]
sizeOf :: (Ord a, Enum a, Ord b) => Treap a b Int -> Int
sizeOf Leaf = 0
sizeOf (Branch _ _ v _ _) = v
recalcSize :: (Ord a, Enum a, Ord b) => RecalcFunc a b Int
recalcSize l r = sizeOf l + sizeOf r + 1
kthElement :: (Ord a, Enum a, Ord b) => Int -> Treap a b Int -> Maybe (a, b, Int)
kthElement k Leaf = Nothing
kthElement k (Branch k1 p1 v1 l r) | sizeLeft == k = Just (k1, p1, v1)
| sizeLeft > k = kthElement k l
| sizeLeft < k = kthElement (k - sizeLeft - 1) r
where sizeLeft = (sizeOf l)
fromList' :: (Ord a, Enum a, Ord b) => [(a, b, Int)] -> Treap a b Int
fromList' = foldr (insert recalcSize) Leaf | graninas/Haskell-Algorithms | Tests/SizeTreap.hs | gpl-3.0 | 848 | 0 | 9 | 240 | 488 | 268 | 220 | 17 | 1 |
(=>=) :: (Product e a -> b) -> (Product e b -> c) -> (Product e a -> c)
f =>= g = \(Prod e a) -> let b = f (Prod e a)
c = g (Prod e b)
in c | hmemcpy/milewski-ctfp-pdf | src/content/3.7/code/haskell/snippet09.hs | gpl-3.0 | 188 | 0 | 12 | 90 | 114 | 57 | 57 | -1 | -1 |
module Graphics.UI.SDL.Extra.Keys where
import Graphics.UI.SDL hiding (init)
import Data.Char (isAlphaNum, isSpace)
keyToChar :: SDLKey -> Maybe Char
keyToChar SDLK_a = Just 'a'
keyToChar SDLK_b = Just 'b'
keyToChar SDLK_c = Just 'c'
keyToChar SDLK_d = Just 'd'
keyToChar SDLK_e = Just 'e'
keyToChar SDLK_f = Just 'f'
keyToChar SDLK_g = Just 'g'
keyToChar SDLK_h = Just 'h'
keyToChar SDLK_i = Just 'i'
keyToChar SDLK_j = Just 'j'
keyToChar SDLK_k = Just 'k'
keyToChar SDLK_l = Just 'l'
keyToChar SDLK_m = Just 'm'
keyToChar SDLK_n = Just 'n'
keyToChar SDLK_o = Just 'o'
keyToChar SDLK_p = Just 'p'
keyToChar SDLK_q = Just 'q'
keyToChar SDLK_r = Just 'r'
keyToChar SDLK_s = Just 's'
keyToChar SDLK_t = Just 't'
keyToChar SDLK_u = Just 'u'
keyToChar SDLK_v = Just 'v'
keyToChar SDLK_w = Just 'w'
keyToChar SDLK_x = Just 'x'
keyToChar SDLK_y = Just 'y'
keyToChar SDLK_z = Just 'z'
keyToChar SDLK_SPACE = Just ' '
keyToChar SDLK_BACKSPACE = Just '\DEL'
keyToChar SDLK_UNDERSCORE = Just '_'
keyToChar SDLK_RETURN = Just '\n'
keyToChar SDLK_MINUS = Just '-'
keyToChar _ = Nothing
getStringAndDo :: (String -> IO ()) -> IO (Maybe String)
getStringAndDo f = loop ""
where
good :: String -> Maybe String
good "" = Nothing
good s = if all (\i -> isAlphaNum i || isSpace i) s then Just s else Nothing
loop :: String -> IO (Maybe String)
loop [] = f [] >> pollEvent >>= \event ->
case event of
KeyDown (Keysym SDLK_RETURN _ _) -> return Nothing
KeyDown (Keysym key _ _) -> loop $ maybe "" (:[]) (keyToChar key)
_ -> loop []
loop line = f line >> pollEvent >>= \event ->
case event of
KeyDown (Keysym SDLK_RETURN _ _) -> return (good line)
KeyDown (Keysym SDLK_BACKSPACE _ _) -> loop $ init line
KeyDown (Keysym key _ _) -> loop $ maybe line ((line ++) . (:[])) (keyToChar key)
_ -> loop line
| mikeplus64/Level-0 | src/Graphics/UI/SDL/Extra/Keys.hs | gpl-3.0 | 2,015 | 0 | 17 | 553 | 769 | 372 | 397 | 53 | 9 |
module Classwork where
data Tree a = Leaf a | Branch (Tree a) a (Tree a)
instance (Eq a) => Eq (Tree a) where
(==) (Leaf x) (Leaf y) = x == y
(==) (Branch l1 v1 r1) (Branch l2 v2 r2) = v1 == v2 && l1 == l2 && r1 == r2
(==) _ _ = False
tr1 = Branch (Leaf 42) 15 (Branch (Leaf 0) 5 (Leaf 0))
tr2 = Branch (Leaf 42) 15 (Branch (Leaf 0) 5 (Leaf 0))
tr3 = Branch (Leaf 42) 15 (Branch (Leaf 0) 5 (Leaf 1))
tr4 = Branch (Leaf 42) 15 (Leaf 6)
inft n = Branch (inft (n + 1)) 1 (Leaf n)
inft_mirror n = Branch (Leaf n) 1 (inft_mirror (n + 1))
inft' n = Branch (inft' (n + 1)) n (inft' (n + 1))
inf_tr1 = inft 0
inf_tr2 = inft_mirror 0
inf_tr3 = inft' 0
elemTree tr x =
let helper [] x = False
helper ((Leaf y):ys) x = y == x || helper ys x
helper ((Branch le y rg):ys) x = y == x || helper (ys ++ [le, rg]) x
in helper [tr] x
instance Functor Tree where
-- :: (a -> b) -> Tree a -> Tree b
fmap f (Leaf x) = Leaf (f x)
fmap f (Branch le x rg) = Branch (fmap f le) (f x) (fmap f rg)
squared_tree_1 = fmap (^2) inf_tr1
data List a = Nil | Cons a (List a)
instance (Show a) => Show (List a) where
show Nil = "|"
show (Cons x tail) = "<" ++ (show x) ++ (show tail) ++ ">"
instance (Show a) => Show (Tree a) where
-- show (Leaf x) = show x
-- show (Branch le x rg) = "<" ++ (show le) ++ "{" ++ (show x) ++ "}" ++ (show rg) ++ ">"
showsPrec _ = myShowTree
myShowTree :: Show a => Tree a -> ShowS
myShowTree (Leaf x) = shows x
myShowTree (Branch le x rg) = ('<' :)
. shows le
. (('{':) .(shows x) .('}':))
. shows rg
. ('>' :)
instance (Read a) => Read (Tree a) where
readsPrec _ = myReadsTree
myReadsTree :: Read a => ReadS (Tree a)
myReadsTree ('<':s) = [(Branch le x rg, tail) | (le, '{':t1) <- myReadsTree s,
(x, '}':t2) <- reads t1,
(rg, '>':tail) <- reads t2]
myReadsTree s = [(Leaf x, tail) | (x, tail) <- reads s]
| ItsLastDay/academic_university_2016-2018 | subjects/Haskell/6/classwork.hs | gpl-3.0 | 2,104 | 2 | 13 | 708 | 1,067 | 551 | 516 | 45 | 3 |
module Typedrat.Templates.PostList (postListTemplate) where
import Data.Int
import qualified Data.Text as T
import Data.Time
import Lucid
import Typedrat.DB
import Typedrat.DB.Post
import Typedrat.Routes
import Typedrat.Templates.Types
postListTemplate :: TVContains a "posts" [(BlogPost Hask, Int64)] xs => RatTemplate xs ()
postListTemplate = askVar (K :: Key "posts") >>= section_ [class_ "post-list"] . mapM_ (uncurry listItem)
where
listItem :: BlogPost Hask -> Int64 -> RatTemplate ys ()
listItem post numComments = article_ [class_ "post"] $ do
a_ [href_ (renderPostUrl post)] . h1_ . toHtml . _postTitle $ post
p_ [class_ "post-dateline"] $ do
toHtml . formatTime defaultTimeLocale "%B %e, %Y" . _postTime $ post
" – "
a_ [href_ $ renderPostUrl post `T.append` "#comments"] . toHtml $
(show numComments) ++ " comments"
let Right body = renderPostBodyToHtml post
section_ body
| typedrat/typedrat-site | app/Typedrat/Templates/PostList.hs | gpl-3.0 | 1,025 | 0 | 20 | 264 | 320 | 161 | 159 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Printer.SPEC
(printProperty)
where
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Builder
import Data.Monoid
import Property
renderOp :: Op -> Builder
renderOp Ge = ">="
renderOp op = error $ "operand not supported for spec: " <> show op
renderConjunction :: (Show a) => Formula a -> Builder
renderConjunction (LinearInequation (Var x) op (Const c)) =
stringUtf8 (show x) <> renderOp op <> integerDec c
renderConjunction f@(LinearInequation {}) =
error $ "linear inequation not supported for spec: " <> show f
renderConjunction (Neg _) = error "negation not supported for spec"
renderConjunction (FTrue :&: p) = renderConjunction p
renderConjunction (p :&: FTrue) = renderConjunction p
renderConjunction (p :&: q) = renderConjunction p <> ", " <> renderConjunction q
renderConjunction f = error $ "formula not supported for spec: " <> show f
renderDisjunction :: (Show a) => Formula a -> Builder
renderDisjunction (FFalse :|: p) = renderDisjunction p
renderDisjunction (p :|: FFalse) = renderDisjunction p
renderDisjunction (p :|: q) = renderDisjunction p <> "\n" <> renderDisjunction q
renderDisjunction f = renderConjunction f
renderFormula :: (Show a) => Formula a -> Builder
renderFormula = renderDisjunction
renderProperty :: Property -> Builder
renderProperty (Property _ (Safety f)) = renderFormula f
renderProperty (Property _ (Liveness _)) =
error "liveness property not supported for spec"
renderProperty (Property _ (Structural _)) =
error "structural property not supported for spec"
printProperty :: Property -> L.ByteString
printProperty prop =
toLazyByteString $ renderProperty prop
| cryptica/slapnet | src/Printer/SPEC.hs | gpl-3.0 | 1,713 | 0 | 9 | 292 | 508 | 258 | 250 | 36 | 1 |
{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction, GADTs, ScopedTypeVariables, TemplateHaskell, StandaloneDeriving, ExtendedDefaultRules #-}
import Blender
import Data.Function
import Data.Vect.Double
import ExampleTriangulations
import Control.Monad
import StandardCoordinates
import Tetrahedron.NormalDisc
import Numeric.AD.Vector
import CheckAdmissibility
import NormalSurfaceBasic
spqwc = spqwc_oneTet
tr = spqwc_tr spqwc
main :: IO ()
main =
forM_
(map (toAdmissible stdCoordSys tr)
(AnyStandardCoords (normalTriList (tindex 0))
: fmap AnyStandardCoords (normalQuadList (tindex 0)) ))
(\stc ->
testBlender .
setCams [Cam (-2.8 *& vec3Y) ((pi/2) *& vec3X) defaultFOV] .
defaultScene .
transformCoords rot $
(fromSpqwcAndIntegerNormalSurface spqwc stc)
)
--`disjointUnion` abnormalCurve
rot :: FF Tup3 Tup3 Double
rot = liftVec3 . rotate3 (pi*0.05) vec3X . rotate3 (pi*0.42) vec3Z . tup3toVec3 . fmap realToFrac
| DanielSchuessler/hstri | bin/output_DiscTypes.hs | gpl-3.0 | 1,056 | 0 | 18 | 240 | 264 | 140 | 124 | 27 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.AdSense.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.AdSense.Types.Sum where
import Network.Google.Prelude
| rueshyna/gogol | gogol-adsense/gen/Network/Google/AdSense/Types/Sum.hs | mpl-2.0 | 598 | 0 | 4 | 109 | 29 | 25 | 4 | 8 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.StorageGateway.AddWorkingStorage
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation configures one or more gateway local disks as working storage
-- for a gateway. This operation is supported only for the gateway-stored volume
-- architecture. This operation is deprecated method in cached-volumes API
-- version (20120630). Use AddUploadBuffer instead.
--
-- Working storage is also referred to as upload buffer. You can also use the 'AddUploadBuffer' operation to add upload buffer to a stored-volume gateway.
--
-- In the request, you specify the gateway Amazon Resource Name (ARN) to which
-- you want to add working storage, and one or more disk IDs that you want to
-- configure as working storage.
--
-- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AddWorkingStorage.html>
module Network.AWS.StorageGateway.AddWorkingStorage
(
-- * Request
AddWorkingStorage
-- ** Request constructor
, addWorkingStorage
-- ** Request lenses
, awsDiskIds
, awsGatewayARN
-- * Response
, AddWorkingStorageResponse
-- ** Response constructor
, addWorkingStorageResponse
-- ** Response lenses
, awsrGatewayARN
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.StorageGateway.Types
import qualified GHC.Exts
data AddWorkingStorage = AddWorkingStorage
{ _awsDiskIds :: List "DiskIds" Text
, _awsGatewayARN :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'AddWorkingStorage' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'awsDiskIds' @::@ ['Text']
--
-- * 'awsGatewayARN' @::@ 'Text'
--
addWorkingStorage :: Text -- ^ 'awsGatewayARN'
-> AddWorkingStorage
addWorkingStorage p1 = AddWorkingStorage
{ _awsGatewayARN = p1
, _awsDiskIds = mempty
}
-- | An array of strings that identify disks that are to be configured as working
-- storage. Each string have a minimum length of 1 and maximum length of 300.
-- You can get the disk IDs from the 'ListLocalDisks' API.
awsDiskIds :: Lens' AddWorkingStorage [Text]
awsDiskIds = lens _awsDiskIds (\s a -> s { _awsDiskIds = a }) . _List
awsGatewayARN :: Lens' AddWorkingStorage Text
awsGatewayARN = lens _awsGatewayARN (\s a -> s { _awsGatewayARN = a })
newtype AddWorkingStorageResponse = AddWorkingStorageResponse
{ _awsrGatewayARN :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'AddWorkingStorageResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'awsrGatewayARN' @::@ 'Maybe' 'Text'
--
addWorkingStorageResponse :: AddWorkingStorageResponse
addWorkingStorageResponse = AddWorkingStorageResponse
{ _awsrGatewayARN = Nothing
}
awsrGatewayARN :: Lens' AddWorkingStorageResponse (Maybe Text)
awsrGatewayARN = lens _awsrGatewayARN (\s a -> s { _awsrGatewayARN = a })
instance ToPath AddWorkingStorage where
toPath = const "/"
instance ToQuery AddWorkingStorage where
toQuery = const mempty
instance ToHeaders AddWorkingStorage
instance ToJSON AddWorkingStorage where
toJSON AddWorkingStorage{..} = object
[ "GatewayARN" .= _awsGatewayARN
, "DiskIds" .= _awsDiskIds
]
instance AWSRequest AddWorkingStorage where
type Sv AddWorkingStorage = StorageGateway
type Rs AddWorkingStorage = AddWorkingStorageResponse
request = post "AddWorkingStorage"
response = jsonResponse
instance FromJSON AddWorkingStorageResponse where
parseJSON = withObject "AddWorkingStorageResponse" $ \o -> AddWorkingStorageResponse
<$> o .:? "GatewayARN"
| dysinger/amazonka | amazonka-storagegateway/gen/Network/AWS/StorageGateway/AddWorkingStorage.hs | mpl-2.0 | 4,587 | 0 | 10 | 941 | 524 | 319 | 205 | 61 | 1 |
{-
Habit of Fate, a game to incentivize habit formation.
Copyright (C) 2017 Gregory Crosswhite
This program is free software: you can redistribute it and/or modify
it under version 3 of the terms of the GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UnicodeSyntax #-}
module HabitOfFate.Server.Requests.Web.ChangeTimeZone (handler) where
import HabitOfFate.Prelude
import Data.Time.Zones.All (toTZName)
import Network.HTTP.Types.Status (badRequest400, ok200, temporaryRedirect307)
import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Web.Scotty (ScottyM)
import qualified Web.Scotty as Scotty
import HabitOfFate.Data.Account
import HabitOfFate.Data.Configuration
import HabitOfFate.Server.Common
import HabitOfFate.Server.Transaction
handleChangeTimeZoneGet ∷ Environment → ScottyM ()
handleChangeTimeZoneGet environment = do
Scotty.get "/timezone" <<< webTransaction environment $ do
timezone ← use $ configuration_ . timezone_
renderTopOnlyPageResult "Habit of Fate - Changing the Time Zone" (\_ → []) [] Nothing ok200 >>> pure $ \_ →
H.form ! A.method "post" $ do
H.div ! A.class_ "fields" $ do
H.div $ H.toHtml ("Time Zone:" ∷ Text)
H.select
! A.name "timezone"
! A.required "true"
$ flip foldMap [minBound..maxBound] $ \timezone' →
let option_prefix_1 = H.option ! A.value (H.toValue $ show timezone')
option_prefix_2
| timezone == timezone' =
option_prefix_1 ! A.selected "selected"
| otherwise =
option_prefix_1
in option_prefix_2 $ H.toHtml (toTZName timezone' |> decodeUtf8 ∷ Text)
H.input ! A.type_ "submit"
H.a ! A.href "/" $ H.toHtml ("Cancel" ∷ Text)
handleChangeTimeZonePost ∷ Environment → ScottyM ()
handleChangeTimeZonePost environment = do
Scotty.post "/timezone" <<< webTransaction environment $ do
maybe_timezone_label ← getParamMaybe "timezone"
case maybe_timezone_label of
Nothing → do
renderPageResult "Bad Time Zone Change" (\_ → []) [] Nothing badRequest400 >>> pure $ \_ → do
H.body $ do
H.h1 $ H.toHtml ("Missing Time Zone" ∷ Text)
H.p $ H.toHtml ("Timezone field was not present." ∷ Text)
Just timezone_label →
case readEither timezone_label of
Left error_message → do
renderPageResult "Bad Time Zone Change" (\_ → []) [] Nothing badRequest400 >>> pure $ \_ → do
H.body $ do
H.h1 $ H.toHtml ("Missing Time Zone" ∷ Text)
H.p $ H.toHtml ("Timezone field value was not recognized: " ⊕ error_message)
Right timezone → do
configuration_ . timezone_ .= timezone
pure $ redirectsToResult temporaryRedirect307 "/"
handler ∷ Environment → ScottyM ()
handler environment = do
handleChangeTimeZoneGet environment
handleChangeTimeZonePost environment
| gcross/habit-of-fate | sources/library/HabitOfFate/Server/Requests/Web/ChangeTimeZone.hs | agpl-3.0 | 3,628 | 0 | 28 | 903 | 785 | 401 | 384 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Motivators where
import Control.Concurrent (threadDelay)
import Control.Distributed.Process
import Control.Monad (forever)
import Data.Binary
import Data.Typeable
import GHC.Generics (Generic)
data Action =
ShareState
deriving (Generic, Typeable)
instance Binary Action
shareStateMotivator :: ProcessId -> Process ()
shareStateMotivator parent =
forever $ do
send parent ShareState
liftIO $ threadDelay 1000000 -- wait 0.1s
| mreluzeon/block-monad | src/Motivators.hs | lgpl-3.0 | 517 | 0 | 9 | 77 | 122 | 67 | 55 | 18 | 1 |
module Interface.Board where
type Cell = (Int, Int)
class BoardState b where
getLiving :: b -> [Cell]
isLiving :: Cell -> b -> Bool
alter :: Cell -> b -> b
next :: b -> b
previous :: b -> b
translate :: Cell -> Cell -> Cell
translate (x, y) (xVect, yVect) = (x + xVect, y + yVect)
| Sventimir/game-of-life | Interface/Board.hs | apache-2.0 | 305 | 0 | 8 | 84 | 132 | 75 | 57 | 10 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GADTs #-}
module Lycopene.Core.Project
( Project(..)
, ProjectStatus(..)
, ProjectId
, ProjectF(..)
, ProjectM
, newProject
, addProject
, removeProject
, updateProject
, fetchByNameProject
, fetchAllProject
, activateProject
, deactivateProject
) where
import Data.Char (toLower)
import qualified Data.Text as T
import GHC.Generics
import Data.Aeson (ToJSON(..), FromJSON(..))
import Data.Aeson.Types
(typeMismatch, Value(..), Parser
, genericToEncoding, genericParseJSON, Options(..)
, defaultOptions, withText)
import Lycopene.Core.Scalar
import Lycopene.Freer (Freer, liftR, foldFreer)
import Lycopene.Core.Store (Change)
import Lycopene.Core.Identifier (generate, nameIdGen)
import Lycopene.Core.Pure (VStore, VResult, runVStore, initial, values, save, fetch, remove, catch)
import Lycopene.Lens (Lens, set, get, field)
type ProjectId = Identifier
data ProjectStatus
= ProjectInactive -- ^ Indicate that a project is not proceeding or completed.
| ProjectActive -- ^ Indicate a project is working in progress.
deriving (Eq, Ord, Show)
instance ToJSON ProjectStatus where
toJSON ProjectActive = toJSON "active"
toJSON ProjectInactive = toJSON "inactive"
instance FromJSON ProjectStatus where
parseJSON = withText "active|inactive" $ \t ->
case T.unpack t of
"active" -> return ProjectActive
"inactive" -> return ProjectInactive
_ -> fail "active|inactive"
data Project
= Project
{ projectId :: !ProjectId
, projectName :: !Name
, projectDescription :: Description
, projectStatus :: !ProjectStatus
}
deriving (Show, Generic)
projectOptions :: Options
projectOptions =
defaultOptions
{ fieldLabelModifier = map toLower . drop (length "project") }
instance ToJSON Project where
toEncoding = genericToEncoding projectOptions
instance FromJSON Project where
parseJSON = genericParseJSON projectOptions
-- Project is identified by `projectId`
instance Eq Project where
x == y = (projectId x) == (projectId y)
-- Minimal lenses for Project
-- ==================================================================
_id :: Lens Project ProjectId
_id = field projectId (\a s -> s { projectId = a })
_name :: Lens Project Name
_name = field projectName (\a s -> s { projectName = a })
_status :: Lens Project ProjectStatus
_status = field projectStatus (\a s -> s { projectStatus = a })
-- | Operational primitives of Project
data ProjectF a where
AddProjectF :: Project -> ProjectF Project
RemoveProjectF :: Name -> ProjectF ()
UpdateProjectF :: Change Project -> Project -> ProjectF Project
FetchByNameProjectF :: Name -> ProjectF Project
FetchAllProjectF :: ProjectF [Project]
type ProjectM = Freer ProjectF
-- Lifting boiler plate
newProject :: Name -> Description -> Project
newProject n d =
let next = generate nameIdGen ("project", n)
in Project next n d ProjectActive
addProject :: Project -> ProjectM Project
addProject = liftR . AddProjectF
removeProject :: Name -> ProjectM ()
removeProject = liftR . RemoveProjectF
updateProject :: Change Project -> ProjectM Project -> ProjectM Project
updateProject f = (>>= (liftR . UpdateProjectF f))
fetchByNameProject :: Name -> ProjectM Project
fetchByNameProject = liftR . FetchByNameProjectF
fetchAllProject :: ProjectM [Project]
fetchAllProject = liftR FetchAllProjectF
activateProject :: ProjectM Project -> ProjectM Project
activateProject = (>>= (liftR . UpdateProjectF (set _status ProjectActive)))
deactivateProject :: ProjectM Project -> ProjectM Project
deactivateProject = (>>= (liftR . UpdateProjectF (set _status ProjectInactive)))
| utky/lycopene | src/Lycopene/Core/Project.hs | apache-2.0 | 3,831 | 0 | 11 | 771 | 986 | 553 | 433 | 98 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeApplication
, getApplicationDev
, makeFoundation
) where
import Import
import Settings
import Yesod.Auth
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Network.Wai.Middleware.RequestLogger
import qualified Database.Persist
import Network.HTTP.Conduit (newManager, def)
import System.IO (stdout)
import System.Log.FastLogger (mkLogger)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Home
import Handler.Paper
import Handler.View
import Handler.PaperList
import Handler.PaperListW2UI
import Handler.Resource
import Handler.Activity
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeApplication :: AppConfig DefaultEnv Extra -> IO Application
makeApplication conf = do
foundation <- makeFoundation conf
-- Initialize the logging middleware
logWare <- mkRequestLogger def
{ outputFormat =
if development
then Detailed True
else Apache FromSocket
, destination = Logger $ appLogger foundation
}
-- Create the WAI application and apply middlewares
app <- toWaiAppPlain foundation
return $ logWare app
-- | Loads up any necessary settings, creates your foundation datatype, and
-- performs some initialization.
makeFoundation :: AppConfig DefaultEnv Extra -> IO App
makeFoundation conf = do
manager <- newManager def
s <- staticSite
dbconf <- withYamlEnvironment "config/mongoDB.yml" (appEnv conf)
Database.Persist.loadConfig >>=
Database.Persist.applyEnv
p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf)
logger <- mkLogger True stdout
let foundation = App conf s p manager dbconf logger
return foundation
-- for yesod devel
getApplicationDev :: IO (Int, Application)
getApplicationDev =
defaultDevelApp loader makeApplication
where
loader = Yesod.Default.Config.loadConfig (configSettings Development)
{ csParseExtra = parseExtra
}
| hirokai/PaperServer | Application.hs | bsd-2-clause | 2,588 | 0 | 12 | 504 | 436 | 238 | 198 | 52 | 2 |
-- base
import Control.Concurrent (threadDelay)
import Data.Char (isAscii)
import Data.List (intercalate, isPrefixOf)
-- HUnit
import Test.HUnit ((@?=), assertBool, assertFailure)
-- test-framework
import Test.Framework (Test, defaultMain, testGroup)
-- test-framework-hunit
import Test.Framework.Providers.HUnit (testCase)
-- GLFW-b
import qualified Graphics.UI.GLFW as GLFW
--------------------------------------------------------------------------------
main :: IO ()
main = do
GLFW.setErrorCallback $ Just $ \e s ->
putStrLn $ unwords ["###", show e, show s]
True <- GLFW.init
Just mon <- GLFW.getPrimaryMonitor
GLFW.windowHint $ GLFW.WindowHint'Visible False
mwin@(Just win) <- GLFW.createWindow 100 100 "GLFW-b test" Nothing Nothing
GLFW.makeContextCurrent mwin
defaultMain $ tests mon win
-- TODO because of how defaultMain works, this code is not reached
GLFW.destroyWindow win
GLFW.terminate
--------------------------------------------------------------------------------
versionMajor, versionMinor :: Int
versionMajor = 3
versionMinor = 0
giveItTime :: IO ()
giveItTime = threadDelay 250000
joysticks :: [GLFW.Joystick]
joysticks =
[ GLFW.Joystick'1
, GLFW.Joystick'2
, GLFW.Joystick'3
, GLFW.Joystick'4
, GLFW.Joystick'5
, GLFW.Joystick'6
, GLFW.Joystick'7
, GLFW.Joystick'8
, GLFW.Joystick'9
, GLFW.Joystick'10
, GLFW.Joystick'11
, GLFW.Joystick'12
, GLFW.Joystick'13
, GLFW.Joystick'14
, GLFW.Joystick'15
, GLFW.Joystick'16
]
between :: Ord a => a -> (a,a) -> Bool
between n (l,h) = n >= l && n <= h
videoModeLooksValid :: GLFW.VideoMode -> Bool
videoModeLooksValid vm = and
[ GLFW.videoModeWidth vm `between` (0,4000)
, GLFW.videoModeHeight vm `between` (0,2000)
, GLFW.videoModeRedBits vm `between` (0, 32)
, GLFW.videoModeGreenBits vm `between` (0, 32)
, GLFW.videoModeBlueBits vm `between` (0, 32)
, GLFW.videoModeRefreshRate vm `between` (0, 120)
]
--------------------------------------------------------------------------------
tests :: GLFW.Monitor -> GLFW.Window -> [Test]
tests mon win =
[ testGroup "Initialization and version information"
[ testCase "getVersion" test_getVersion
, testCase "getVersionString" test_getVersionString
]
, testGroup "Monitor handling"
[ testCase "getMonitors" test_getMonitors
, testCase "getPrimaryMonitor" test_getPrimaryMonitor
, testCase "getMonitorPos" $ test_getMonitorPos mon
, testCase "getMonitorPhysicalSize" $ test_getMonitorPhysicalSize mon
, testCase "getMonitorName" $ test_getMonitorName mon
, testCase "getVideoModes" $ test_getVideoModes mon
, testCase "getVideoMode" $ test_getVideoMode mon
, testCase "getGamma" $ test_getGammaRamp mon
-- , testCase "setGamma" $ test_setGamma mon
-- , testCase "gamma ramp" $ test_gamma_ramp mon
]
, testGroup "Window handling"
[ testCase "defaultWindowHints" test_defaultWindowHints
, testCase "window close flag" $ test_window_close_flag win
, testCase "setWindowTitle" $ test_setWindowTitle win
, testCase "window pos" $ test_window_pos win
, testCase "window size" $ test_window_size win
, testCase "getFramebufferSize" $ test_getFramebufferSize win
, testCase "iconification" $ test_iconification win
-- , testCase "show/hide" $ test_show_hide win
, testCase "getWindowMonitor" $ test_getWindowMonitor win mon
, testCase "cursor pos" $ test_cursor_pos win
, testCase "getWindowFocused" $ test_getWindowFocused win
, testCase "getWindowResizable" $ test_getWindowResizable win
, testCase "getWindowDecorated" $ test_getWindowDecorated win
, testCase "getWindowClientAPI" $ test_getWindowClientAPI win
, testCase "window context version" $ test_window_context_version win
, testCase "getWindowContextRobustness" $ test_getWindowContextRobustness win
, testCase "getWindowOpenGLForwardCompat" $ test_getWindowOpenGLForwardCompat win
, testCase "getWindowOpenGLDebugContext" $ test_getWindowOpenGLDebugContext win
, testCase "getWindowOpenGLProfile" $ test_getWindowOpenGLProfile win
, testCase "pollEvents" test_pollEvents
, testCase "waitEvents" test_waitEvents
]
, testGroup "Input handling"
[ testCase "cursor input mode" $ test_cursor_input_mode win
, testCase "sticky keys input mode" $ test_sticky_keys_input_mode win
, testCase "sticky mouse buttons input mode" $ test_sticky_mouse_buttons_input_mode win
, testCase "joystickPresent" test_joystickPresent
, testCase "getJoystickAxes" test_getJoystickAxes
, testCase "getJoystickButtons" test_getJoystickButtons
, testCase "getJoystickName" test_getJoystickName
]
, testGroup "Time"
[ testCase "getTime" test_getTime
, testCase "setTime" test_setTime
]
, testGroup "Context"
[ testCase "getCurrentContext" $ test_getCurrentContext win
, testCase "swapBuffers" $ test_swapBuffers win
, testCase "swapInterval" test_swapInterval
, testCase "extensionSupported" test_extensionSupported
]
, testGroup "Clipboard"
[ testCase "clipboard" $ test_clipboard win
]
]
--------------------------------------------------------------------------------
test_getVersion :: IO ()
test_getVersion = do
v <- GLFW.getVersion
GLFW.versionMajor v @?= versionMajor
GLFW.versionMinor v @?= versionMinor
test_getVersionString :: IO ()
test_getVersionString = do
mvs <- GLFW.getVersionString
case mvs of
Just vs -> assertBool "" $ v `isPrefixOf` vs
Nothing -> assertFailure ""
where
v = intercalate "." $ map show [versionMajor, versionMinor]
test_getMonitors :: IO ()
test_getMonitors = do
r <- GLFW.getMonitors
case r of
Just ms -> assertBool "" $ (not . null) ms
Nothing -> assertFailure ""
test_getPrimaryMonitor :: IO ()
test_getPrimaryMonitor = do
r <- GLFW.getPrimaryMonitor
case r of
Just _ -> return ()
Nothing -> assertFailure ""
test_getMonitorPos :: GLFW.Monitor -> IO ()
test_getMonitorPos mon = do
(x, y) <- GLFW.getMonitorPos mon
assertBool "" $ x >= 0
assertBool "" $ y >= 0
test_getMonitorPhysicalSize :: GLFW.Monitor -> IO ()
test_getMonitorPhysicalSize mon = do
(w, h) <- GLFW.getMonitorPhysicalSize mon
assertBool "" $ w `between` (0, 1000)
assertBool "" $ h `between` (0, 500)
test_getMonitorName :: GLFW.Monitor -> IO ()
test_getMonitorName mon = do
mname <- GLFW.getMonitorName mon
case mname of
Nothing -> assertFailure ""
Just name -> do
assertBool "" $ length name `between` (0, 20)
assertBool "" $ all isAscii name
test_getVideoModes :: GLFW.Monitor -> IO ()
test_getVideoModes mon = do
mvms <- GLFW.getVideoModes mon
case mvms of
Nothing -> assertFailure ""
Just vms -> assertBool "" $ all videoModeLooksValid vms
test_getVideoMode :: GLFW.Monitor -> IO ()
test_getVideoMode mon = do
mvm <- GLFW.getVideoMode mon
case mvm of
Just vm -> assertBool "" $ videoModeLooksValid vm
Nothing -> assertFailure ""
test_getGammaRamp :: GLFW.Monitor -> IO ()
test_getGammaRamp mon = do
mgr <- GLFW.getGammaRamp mon
case mgr of
Nothing -> assertFailure ""
Just gr -> assertBool "" $
let rsl = length $ GLFW.gammaRampRed gr
gsl = length $ GLFW.gammaRampGreen gr
bsl = length $ GLFW.gammaRampBlue gr
in rsl > 0 && rsl == gsl && gsl == bsl
--------------------------------------------------------------------------------
test_defaultWindowHints :: IO ()
test_defaultWindowHints =
GLFW.defaultWindowHints
test_window_close_flag :: GLFW.Window -> IO ()
test_window_close_flag win = do
r0 <- GLFW.windowShouldClose win
r0 @?= False
GLFW.setWindowShouldClose win True
r1 <- GLFW.windowShouldClose win
r1 @?= True
GLFW.setWindowShouldClose win False
r2 <- GLFW.windowShouldClose win
r2 @?= False
test_setWindowTitle :: GLFW.Window -> IO ()
test_setWindowTitle win =
GLFW.setWindowTitle win "some new title"
-- This is a little strange. Depending on your window manager, etc, after
-- setting the window position to (x,y), the actual new window position might
-- be (x+5,y+5) due to borders. So we just check for consistency.
test_window_pos :: GLFW.Window -> IO ()
test_window_pos win = do
let x = 17
y = 37
xoff = 53
yoff = 149
(x0, y0, dx0, dy0) <- setGet x y
(x1, y1, dx1, dy1) <- setGet (x+xoff) (y+yoff)
dx0 @?= dx1
dy0 @?= dy1
x1 - x0 @?= xoff
y1 - y0 @?= yoff
where
setGet x0 y0 = do
GLFW.setWindowPos win x0 y0
giveItTime
(x1, y1) <- GLFW.getWindowPos win
let (dx, dy) = (x0-x1, y0-y1)
return (x1, y1, dx, dy)
test_window_size :: GLFW.Window -> IO ()
test_window_size win = do
let w = 17
h = 37
GLFW.setWindowSize win w h
giveItTime
(w', h') <- GLFW.getWindowSize win
w' @?= w
h' @?= h
test_getFramebufferSize :: GLFW.Window -> IO ()
test_getFramebufferSize win = do
(w, h) <- GLFW.getWindowSize win
(fw, fh) <- GLFW.getFramebufferSize win
fw @?= w
fh @?= h
test_iconification :: GLFW.Window -> IO ()
test_iconification win = do
is0 <- GLFW.getWindowIconified win
is0 @?= GLFW.IconifyState'NotIconified
GLFW.iconifyWindow win
giveItTime
is1 <- GLFW.getWindowIconified win
is1 @?= GLFW.IconifyState'Iconified
GLFW.restoreWindow win
-- test_show_hide :: GLFW.Window -> IO ()
-- test_show_hide win = do
-- v0 <- GLFW.getWindowVisible win
-- v0 @?= True
-- GLFW.hideWindow win
-- giveItTime
-- v1 <- GLFW.getWindowVisible win
-- v1 @?= False
-- GLFW.showWindow win
-- giveItTime
-- v2 <- GLFW.getWindowVisible win
-- v2 @?= True
test_getWindowMonitor :: GLFW.Window -> GLFW.Monitor -> IO ()
test_getWindowMonitor win _ = do
m <- GLFW.getWindowMonitor win
m @?= Nothing
test_cursor_pos :: GLFW.Window -> IO ()
test_cursor_pos win = do
(w, h) <- GLFW.getWindowSize win
let cx = fromIntegral w / 2
cy = fromIntegral h / 2
GLFW.setCursorPos win cx cy
giveItTime
(cx', cy') <- GLFW.getCursorPos win
cx' @?= cx
cy' @?= cy
test_getWindowFocused :: GLFW.Window -> IO ()
test_getWindowFocused win = do
fs <- GLFW.getWindowFocused win
fs @?= GLFW.FocusState'Defocused
test_getWindowResizable :: GLFW.Window -> IO ()
test_getWindowResizable win = do
b <- GLFW.getWindowResizable win
b @?= True
test_getWindowDecorated :: GLFW.Window -> IO ()
test_getWindowDecorated win = do
b <- GLFW.getWindowDecorated win
b @?= True
test_getWindowClientAPI :: GLFW.Window -> IO ()
test_getWindowClientAPI win = do
a <- GLFW.getWindowClientAPI win
a @?= GLFW.ClientAPI'OpenGL
test_window_context_version :: GLFW.Window -> IO ()
test_window_context_version win = do
v0 <- GLFW.getWindowContextVersionMajor win
v1 <- GLFW.getWindowContextVersionMinor win
v2 <- GLFW.getWindowContextVersionRevision win
assertBool "" $ all (`between` (0, 20)) [v0, v1, v2]
test_getWindowContextRobustness :: GLFW.Window -> IO ()
test_getWindowContextRobustness win = do
_ <- GLFW.getWindowContextRobustness win
return ()
test_getWindowOpenGLForwardCompat :: GLFW.Window -> IO ()
test_getWindowOpenGLForwardCompat win = do
_ <- GLFW.getWindowOpenGLForwardCompat win
return ()
test_getWindowOpenGLDebugContext :: GLFW.Window -> IO ()
test_getWindowOpenGLDebugContext win = do
_ <- GLFW.getWindowOpenGLDebugContext win
return ()
test_getWindowOpenGLProfile :: GLFW.Window -> IO ()
test_getWindowOpenGLProfile win = do
_ <- GLFW.getWindowOpenGLProfile win
return ()
test_pollEvents :: IO ()
test_pollEvents =
GLFW.pollEvents
test_waitEvents :: IO ()
test_waitEvents =
GLFW.waitEvents
--------------------------------------------------------------------------------
test_cursor_input_mode :: GLFW.Window -> IO ()
test_cursor_input_mode win = do
modes' <- mapM setGet modes
modes' @?= modes
where
modes =
[ GLFW.CursorInputMode'Disabled
, GLFW.CursorInputMode'Hidden
, GLFW.CursorInputMode'Normal
]
setGet m = do
GLFW.setCursorInputMode win m
GLFW.getCursorInputMode win
test_sticky_keys_input_mode :: GLFW.Window -> IO ()
test_sticky_keys_input_mode win = do
modes' <- mapM setGet modes
modes' @?= modes
where
modes =
[ GLFW.StickyKeysInputMode'Enabled
, GLFW.StickyKeysInputMode'Disabled
]
setGet m = do
GLFW.setStickyKeysInputMode win m
GLFW.getStickyKeysInputMode win
test_sticky_mouse_buttons_input_mode :: GLFW.Window -> IO ()
test_sticky_mouse_buttons_input_mode win = do
modes' <- mapM setGet modes
modes' @?= modes
where
modes =
[ GLFW.StickyMouseButtonsInputMode'Enabled
, GLFW.StickyMouseButtonsInputMode'Disabled
]
setGet m = do
GLFW.setStickyMouseButtonsInputMode win m
GLFW.getStickyMouseButtonsInputMode win
test_joystickPresent :: IO ()
test_joystickPresent = do
_ <- GLFW.joystickPresent GLFW.Joystick'1
r <- GLFW.joystickPresent GLFW.Joystick'16
assertBool "" $ not r
test_getJoystickAxes :: IO ()
test_getJoystickAxes =
mapM_ GLFW.getJoystickAxes joysticks
test_getJoystickButtons :: IO ()
test_getJoystickButtons =
mapM_ GLFW.getJoystickButtons joysticks
test_getJoystickName :: IO ()
test_getJoystickName =
mapM_ GLFW.getJoystickName joysticks
--------------------------------------------------------------------------------
test_getTime :: IO ()
test_getTime = do
mt <- GLFW.getTime
case mt of
Nothing -> assertFailure ""
Just t -> assertBool "" $ t `between` (0, 10)
test_setTime :: IO ()
test_setTime = do
let t = 37
GLFW.setTime t
mt <- GLFW.getTime
case mt of
Just t' -> assertBool "" $ t' `between` (t, t+10)
Nothing -> assertFailure ""
--------------------------------------------------------------------------------
test_getCurrentContext :: GLFW.Window -> IO ()
test_getCurrentContext win = do
mwin <- GLFW.getCurrentContext
case mwin of
Nothing -> assertFailure ""
Just win' -> win' @?= win
test_swapBuffers :: GLFW.Window -> IO ()
test_swapBuffers =
GLFW.swapBuffers
test_swapInterval :: IO ()
test_swapInterval =
GLFW.swapInterval 1
test_extensionSupported :: IO ()
test_extensionSupported = do
b0 <- GLFW.extensionSupported "GL_ARB_multisample"
b0 @?= True
b1 <- GLFW.extensionSupported "bogus"
b1 @?= False
--------------------------------------------------------------------------------
test_clipboard :: GLFW.Window -> IO ()
test_clipboard win = do
rs <- mapM setGet ss
rs @?= map Just ss
where
ss =
[ "abc 123 ???"
, "xyz 456 !!!"
]
setGet s = do
GLFW.setClipboardString win s
GLFW.getClipboardString win
--------------------------------------------------------------------------------
{-# ANN module "HLint: ignore Use camelCase" #-}
| phaazon/GLFW-b | Test.hs | bsd-2-clause | 15,828 | 0 | 17 | 3,809 | 4,050 | 1,993 | 2,057 | 373 | 2 |
{-# LANGUAGE ExistentialQuantification, TemplateHaskell, StandaloneDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans -O0 #-}
-- We have to disable optimisation here, as some versions of ghc otherwise
-- fail to compile this code, at least within reasonable memory limits (40g).
{-| Implementation of the opcodes.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.OpCodes
( pyClasses
, OpCode(..)
, ReplaceDisksMode(..)
, DiskIndex
, mkDiskIndex
, unDiskIndex
, opID
, opReasonSrcID
, allOpIDs
, allOpFields
, opSummary
, CommonOpParams(..)
, defOpParams
, MetaOpCode(..)
, resolveDependencies
, wrapOpCode
, setOpComment
, setOpPriority
) where
import Control.Monad.Fail (MonadFail)
import Data.List (intercalate)
import Data.Map (Map)
import qualified Text.JSON
import Text.JSON (readJSON, JSObject, JSON, JSValue(..), fromJSObject)
import qualified Ganeti.Constants as C
import qualified Ganeti.Hs2Py.OpDoc as OpDoc
import Ganeti.JSON (DictObject(..), readJSONfromDict, showJSONtoDict)
import Ganeti.OpParams
import Ganeti.PyValue ()
import Ganeti.Query.Language (queryTypeOpToRaw)
import Ganeti.THH
import Ganeti.Types
instance PyValue DiskIndex where
showValue = showValue . unDiskIndex
instance PyValue IDiskParams where
showValue _ = error "OpCodes.showValue(IDiskParams): unhandled case"
instance PyValue RecreateDisksInfo where
showValue RecreateDisksAll = "[]"
showValue (RecreateDisksIndices is) = showValue is
showValue (RecreateDisksParams is) = showValue is
instance PyValue a => PyValue (SetParamsMods a) where
showValue SetParamsEmpty = "[]"
showValue _ = error "OpCodes.showValue(SetParamsMods): unhandled case"
instance PyValue a => PyValue (NonNegative a) where
showValue = showValue . fromNonNegative
instance PyValue a => PyValue (NonEmpty a) where
showValue = showValue . fromNonEmpty
-- FIXME: should use the 'toRaw' function instead of being harcoded or
-- perhaps use something similar to the NonNegative type instead of
-- using the declareSADT
instance PyValue ExportMode where
showValue ExportModeLocal = show C.exportModeLocal
showValue ExportModeRemote = show C.exportModeLocal
instance PyValue CVErrorCode where
showValue = cVErrorCodeToRaw
instance PyValue VerifyOptionalChecks where
showValue = verifyOptionalChecksToRaw
instance PyValue INicParams where
showValue = error "instance PyValue INicParams: not implemented"
instance PyValue a => PyValue (JSObject a) where
showValue obj =
"{" ++ intercalate ", " (map showPair (fromJSObject obj)) ++ "}"
where showPair (k, v) = show k ++ ":" ++ showValue v
instance PyValue JSValue where
showValue (JSObject obj) = showValue obj
showValue x = show x
type JobIdListOnly = Map String [(Bool, Either String JobId)]
type InstanceMultiAllocResponse =
([(Bool, Either String JobId)], NonEmptyString)
type QueryFieldDef =
(NonEmptyString, NonEmptyString, TagKind, NonEmptyString)
type QueryResponse =
([QueryFieldDef], [[(QueryResultCode, JSValue)]])
type QueryFieldsResponse = [QueryFieldDef]
-- | OpCode representation.
--
-- We only implement a subset of Ganeti opcodes: those which are actually used
-- in the htools codebase.
$(genOpCode "OpCode"
[ ("OpClusterPostInit",
[t| Bool |],
OpDoc.opClusterPostInit,
[],
[])
, ("OpClusterDestroy",
[t| NonEmptyString |],
OpDoc.opClusterDestroy,
[],
[])
, ("OpClusterQuery",
[t| JSObject JSValue |],
OpDoc.opClusterQuery,
[],
[])
, ("OpClusterVerify",
[t| JobIdListOnly |],
OpDoc.opClusterVerify,
[ pDebugSimulateErrors
, pErrorCodes
, pSkipChecks
, pIgnoreErrors
, pVerbose
, pOptGroupName
, pVerifyClutter
],
[])
, ("OpClusterVerifyConfig",
[t| Bool |],
OpDoc.opClusterVerifyConfig,
[ pDebugSimulateErrors
, pErrorCodes
, pIgnoreErrors
, pVerbose
],
[])
, ("OpClusterVerifyGroup",
[t| Bool |],
OpDoc.opClusterVerifyGroup,
[ pGroupName
, pDebugSimulateErrors
, pErrorCodes
, pSkipChecks
, pIgnoreErrors
, pVerbose
, pVerifyClutter
],
"group_name")
, ("OpClusterVerifyDisks",
[t| JobIdListOnly |],
OpDoc.opClusterVerifyDisks,
[ pOptGroupName
],
[])
, ("OpGroupVerifyDisks",
[t| (Map String String, [String], Map String [[String]]) |],
OpDoc.opGroupVerifyDisks,
[ pGroupName
],
"group_name")
, ("OpClusterRepairDiskSizes",
[t| [(NonEmptyString, NonNegative Int, NonEmptyString, NonNegative Int)]|],
OpDoc.opClusterRepairDiskSizes,
[ pInstances
],
[])
, ("OpClusterConfigQuery",
[t| [JSValue] |],
OpDoc.opClusterConfigQuery,
[ pOutputFields
],
[])
, ("OpClusterRename",
[t| NonEmptyString |],
OpDoc.opClusterRename,
[ pName
],
"name")
, ("OpClusterSetParams",
[t| Either () JobIdListOnly |],
OpDoc.opClusterSetParams,
[ pForce
, pHvState
, pDiskState
, pVgName
, pEnabledHypervisors
, pClusterHvParams
, pClusterBeParams
, pOsHvp
, pClusterOsParams
, pClusterOsParamsPrivate
, pGroupDiskParams
, pCandidatePoolSize
, pMaxRunningJobs
, pMaxTrackedJobs
, pUidPool
, pAddUids
, pRemoveUids
, pMaintainNodeHealth
, pPreallocWipeDisks
, pNicParams
, withDoc "Cluster-wide node parameter defaults" pNdParams
, withDoc "Cluster-wide ipolicy specs" pIpolicy
, pDrbdHelper
, pDefaultIAllocator
, pDefaultIAllocatorParams
, pNetworkMacPrefix
, pMasterNetdev
, pMasterNetmask
, pReservedLvs
, pHiddenOs
, pBlacklistedOs
, pUseExternalMipScript
, pEnabledDiskTemplates
, pModifyEtcHosts
, pClusterFileStorageDir
, pClusterSharedFileStorageDir
, pClusterGlusterStorageDir
, pInstallImage
, pInstanceCommunicationNetwork
, pZeroingImage
, pCompressionTools
, pEnabledUserShutdown
, pEnabledDataCollectors
, pDataCollectorInterval
],
[])
, ("OpClusterRedistConf",
[t| () |],
OpDoc.opClusterRedistConf,
[],
[])
, ("OpClusterActivateMasterIp",
[t| () |],
OpDoc.opClusterActivateMasterIp,
[],
[])
, ("OpClusterDeactivateMasterIp",
[t| () |],
OpDoc.opClusterDeactivateMasterIp,
[],
[])
, ("OpClusterRenewCrypto",
[t| () |],
OpDoc.opClusterRenewCrypto,
[ pNodeSslCerts
, pRenewSshKeys
, pSshKeyType
, pSshKeyBits
, pVerbose
, pDebug
],
[])
, ("OpQuery",
[t| QueryResponse |],
OpDoc.opQuery,
[ pQueryWhat
, pUseLocking
, pQueryFields
, pQueryFilter
],
"what")
, ("OpQueryFields",
[t| QueryFieldsResponse |],
OpDoc.opQueryFields,
[ pQueryWhat
, pQueryFieldsFields
],
"what")
, ("OpOobCommand",
[t| [[(QueryResultCode, JSValue)]] |],
OpDoc.opOobCommand,
[ pNodeNames
, withDoc "List of node UUIDs to run the OOB command against" pNodeUuids
, pOobCommand
, pOobTimeout
, pIgnoreStatus
, pPowerDelay
],
[])
, ("OpRestrictedCommand",
[t| [(Bool, String)] |],
OpDoc.opRestrictedCommand,
[ pUseLocking
, withDoc
"Nodes on which the command should be run (at least one)"
pRequiredNodes
, withDoc
"Node UUIDs on which the command should be run (at least one)"
pRequiredNodeUuids
, pRestrictedCommand
],
[])
, ("OpNodeRemove",
[t| () |],
OpDoc.opNodeRemove,
[ pNodeName
, pNodeUuid
],
"node_name")
, ("OpNodeAdd",
[t| () |],
OpDoc.opNodeAdd,
[ pNodeName
, pHvState
, pDiskState
, pPrimaryIp
, pSecondaryIp
, pReadd
, pNodeGroup
, pMasterCapable
, pVmCapable
, pNdParams
, pNodeSetup
],
"node_name")
, ("OpNodeQueryvols",
[t| [JSValue] |],
OpDoc.opNodeQueryvols,
[ pOutputFields
, withDoc "Empty list to query all nodes, node names otherwise" pNodes
],
[])
, ("OpNodeQueryStorage",
[t| [[JSValue]] |],
OpDoc.opNodeQueryStorage,
[ pOutputFields
, pOptStorageType
, withDoc
"Empty list to query all, list of names to query otherwise"
pNodes
, pStorageName
],
[])
, ("OpNodeModifyStorage",
[t| () |],
OpDoc.opNodeModifyStorage,
[ pNodeName
, pNodeUuid
, pStorageType
, pStorageName
, pStorageChanges
],
"node_name")
, ("OpRepairNodeStorage",
[t| () |],
OpDoc.opRepairNodeStorage,
[ pNodeName
, pNodeUuid
, pStorageType
, pStorageName
, pIgnoreConsistency
],
"node_name")
, ("OpNodeSetParams",
[t| [(NonEmptyString, JSValue)] |],
OpDoc.opNodeSetParams,
[ pNodeName
, pNodeUuid
, pForce
, pHvState
, pDiskState
, pMasterCandidate
, withDoc "Whether to mark the node offline" pOffline
, pDrained
, pAutoPromote
, pMasterCapable
, pVmCapable
, pSecondaryIp
, pNdParams
, pPowered
],
"node_name")
, ("OpNodePowercycle",
[t| Maybe NonEmptyString |],
OpDoc.opNodePowercycle,
[ pNodeName
, pNodeUuid
, pForce
],
"node_name")
, ("OpNodeMigrate",
[t| JobIdListOnly |],
OpDoc.opNodeMigrate,
[ pNodeName
, pNodeUuid
, pMigrationMode
, pMigrationLive
, pMigrationTargetNode
, pMigrationTargetNodeUuid
, pAllowRuntimeChgs
, pIgnoreIpolicy
, pIallocator
],
"node_name")
, ("OpNodeEvacuate",
[t| JobIdListOnly |],
OpDoc.opNodeEvacuate,
[ pEarlyRelease
, pNodeName
, pNodeUuid
, pRemoteNode
, pRemoteNodeUuid
, pIallocator
, pEvacMode
, pIgnoreSoftErrors
],
"node_name")
, ("OpInstanceCreate",
[t| [NonEmptyString] |],
OpDoc.opInstanceCreate,
[ pInstanceName
, pForceVariant
, pWaitForSync
, pNameCheck
, pIgnoreIpolicy
, pOpportunisticLocking
, pInstBeParams
, pInstDisks
, pOptDiskTemplate
, pOptGroupName
, pFileDriver
, pFileStorageDir
, pInstHvParams
, pHypervisor
, pIallocator
, pResetDefaults
, pIpCheck
, pIpConflictsCheck
, pInstCreateMode
, pInstNics
, pNoInstall
, pInstOsParams
, pInstOsParamsPrivate
, pInstOsParamsSecret
, pInstOs
, pPrimaryNode
, pPrimaryNodeUuid
, pSecondaryNode
, pSecondaryNodeUuid
, pSourceHandshake
, pSourceInstance
, pSourceShutdownTimeout
, pSourceX509Ca
, pSrcNode
, pSrcNodeUuid
, pSrcPath
, pBackupCompress
, pStartInstance
, pForthcoming
, pCommit
, pInstTags
, pInstanceCommunication
, pHelperStartupTimeout
, pHelperShutdownTimeout
],
"instance_name")
, ("OpInstanceMultiAlloc",
[t| InstanceMultiAllocResponse |],
OpDoc.opInstanceMultiAlloc,
[ pOpportunisticLocking
, pIallocator
, pMultiAllocInstances
],
[])
, ("OpInstanceReinstall",
[t| () |],
OpDoc.opInstanceReinstall,
[ pInstanceName
, pInstanceUuid
, pForceVariant
, pInstOs
, pTempOsParams
, pTempOsParamsPrivate
, pTempOsParamsSecret
],
"instance_name")
, ("OpInstanceRemove",
[t| () |],
OpDoc.opInstanceRemove,
[ pInstanceName
, pInstanceUuid
, pShutdownTimeout
, pIgnoreFailures
],
"instance_name")
, ("OpInstanceRename",
[t| NonEmptyString |],
OpDoc.opInstanceRename,
[ pInstanceName
, pInstanceUuid
, withDoc "New instance name" pNewName
, pNameCheck
, pIpCheck
],
[])
, ("OpInstanceStartup",
[t| () |],
OpDoc.opInstanceStartup,
[ pInstanceName
, pInstanceUuid
, pForce
, pIgnoreOfflineNodes
, pTempHvParams
, pTempBeParams
, pNoRemember
, pStartupPaused
-- timeout to cleanup a user down instance
, pShutdownTimeout
],
"instance_name")
, ("OpInstanceShutdown",
[t| () |],
OpDoc.opInstanceShutdown,
[ pInstanceName
, pInstanceUuid
, pForce
, pIgnoreOfflineNodes
, pShutdownTimeout'
, pNoRemember
, pAdminStateSource
],
"instance_name")
, ("OpInstanceReboot",
[t| () |],
OpDoc.opInstanceReboot,
[ pInstanceName
, pInstanceUuid
, pShutdownTimeout
, pIgnoreSecondaries
, pRebootType
],
"instance_name")
, ("OpInstanceReplaceDisks",
[t| () |],
OpDoc.opInstanceReplaceDisks,
[ pInstanceName
, pInstanceUuid
, pEarlyRelease
, pIgnoreIpolicy
, pReplaceDisksMode
, pReplaceDisksList
, pRemoteNode
, pRemoteNodeUuid
, pIallocator
],
"instance_name")
, ("OpInstanceFailover",
[t| () |],
OpDoc.opInstanceFailover,
[ pInstanceName
, pInstanceUuid
, pShutdownTimeout
, pIgnoreConsistency
, pMigrationTargetNode
, pMigrationTargetNodeUuid
, pIgnoreIpolicy
, pMigrationCleanup
, pIallocator
],
"instance_name")
, ("OpInstanceMigrate",
[t| () |],
OpDoc.opInstanceMigrate,
[ pInstanceName
, pInstanceUuid
, pMigrationMode
, pMigrationLive
, pMigrationTargetNode
, pMigrationTargetNodeUuid
, pAllowRuntimeChgs
, pIgnoreIpolicy
, pMigrationCleanup
, pIallocator
, pAllowFailover
, pIgnoreHVVersions
],
"instance_name")
, ("OpInstanceMove",
[t| () |],
OpDoc.opInstanceMove,
[ pInstanceName
, pInstanceUuid
, pShutdownTimeout
, pIgnoreIpolicy
, pMoveTargetNode
, pMoveTargetNodeUuid
, pMoveCompress
, pIgnoreConsistency
],
"instance_name")
, ("OpInstanceConsole",
[t| JSObject JSValue |],
OpDoc.opInstanceConsole,
[ pInstanceName
, pInstanceUuid
],
"instance_name")
, ("OpInstanceActivateDisks",
[t| [(NonEmptyString, NonEmptyString, Maybe NonEmptyString)] |],
OpDoc.opInstanceActivateDisks,
[ pInstanceName
, pInstanceUuid
, pIgnoreDiskSize
, pWaitForSyncFalse
],
"instance_name")
, ("OpInstanceDeactivateDisks",
[t| () |],
OpDoc.opInstanceDeactivateDisks,
[ pInstanceName
, pInstanceUuid
, pForce
],
"instance_name")
, ("OpInstanceRecreateDisks",
[t| () |],
OpDoc.opInstanceRecreateDisks,
[ pInstanceName
, pInstanceUuid
, pRecreateDisksInfo
, withDoc "New instance nodes, if relocation is desired" pNodes
, withDoc "New instance node UUIDs, if relocation is desired" pNodeUuids
, pIallocator
],
"instance_name")
, ("OpInstanceQueryData",
[t| JSObject (JSObject JSValue) |],
OpDoc.opInstanceQueryData,
[ pUseLocking
, pInstances
, pStatic
],
[])
, ("OpInstanceSetParams",
[t| [(NonEmptyString, JSValue)] |],
OpDoc.opInstanceSetParams,
[ pInstanceName
, pInstanceUuid
, pForce
, pForceVariant
, pIgnoreIpolicy
, pInstParamsNicChanges
, pInstParamsDiskChanges
, pInstBeParams
, pRuntimeMem
, pInstHvParams
, pOptDiskTemplate
, pExtParams
, pFileDriver
, pFileStorageDir
, pPrimaryNode
, pPrimaryNodeUuid
, withDoc "Secondary node (used when changing disk template)" pRemoteNode
, withDoc
"Secondary node UUID (used when changing disk template)"
pRemoteNodeUuid
, pIallocator
, pOsNameChange
, pInstOsParams
, pInstOsParamsPrivate
, pWaitForSync
, withDoc "Whether to mark the instance as offline" pOffline
, pIpConflictsCheck
, pHotplug
, pHotplugIfPossible
, pOptInstanceCommunication
],
"instance_name")
, ("OpInstanceGrowDisk",
[t| () |],
OpDoc.opInstanceGrowDisk,
[ pInstanceName
, pInstanceUuid
, pWaitForSync
, pDiskIndex
, pDiskChgAmount
, pDiskChgAbsolute
, pIgnoreIpolicy
],
"instance_name")
, ("OpInstanceChangeGroup",
[t| JobIdListOnly |],
OpDoc.opInstanceChangeGroup,
[ pInstanceName
, pInstanceUuid
, pEarlyRelease
, pIallocator
, pTargetGroups
],
"instance_name")
, ("OpGroupAdd",
[t| Either () JobIdListOnly |],
OpDoc.opGroupAdd,
[ pGroupName
, pNodeGroupAllocPolicy
, pGroupNodeParams
, pGroupDiskParams
, pHvState
, pDiskState
, withDoc "Group-wide ipolicy specs" pIpolicy
],
"group_name")
, ("OpGroupAssignNodes",
[t| () |],
OpDoc.opGroupAssignNodes,
[ pGroupName
, pForce
, withDoc "List of nodes to assign" pRequiredNodes
, withDoc "List of node UUIDs to assign" pRequiredNodeUuids
],
"group_name")
, ("OpGroupSetParams",
[t| [(NonEmptyString, JSValue)] |],
OpDoc.opGroupSetParams,
[ pGroupName
, pNodeGroupAllocPolicy
, pGroupNodeParams
, pGroupDiskParams
, pHvState
, pDiskState
, withDoc "Group-wide ipolicy specs" pIpolicy
],
"group_name")
, ("OpGroupRemove",
[t| () |],
OpDoc.opGroupRemove,
[ pGroupName
],
"group_name")
, ("OpGroupRename",
[t| NonEmptyString |],
OpDoc.opGroupRename,
[ pGroupName
, withDoc "New group name" pNewName
],
[])
, ("OpGroupEvacuate",
[t| JobIdListOnly |],
OpDoc.opGroupEvacuate,
[ pGroupName
, pEarlyRelease
, pIallocator
, pTargetGroups
, pSequential
, pForceFailover
],
"group_name")
, ("OpOsDiagnose",
[t| [[JSValue]] |],
OpDoc.opOsDiagnose,
[ pOutputFields
, withDoc "Which operating systems to diagnose" pNames
],
[])
, ("OpExtStorageDiagnose",
[t| [[JSValue]] |],
OpDoc.opExtStorageDiagnose,
[ pOutputFields
, withDoc "Which ExtStorage Provider to diagnose" pNames
],
[])
, ("OpBackupPrepare",
[t| Maybe (JSObject JSValue) |],
OpDoc.opBackupPrepare,
[ pInstanceName
, pInstanceUuid
, pExportMode
],
"instance_name")
, ("OpBackupExport",
[t| (Bool, [Bool]) |],
OpDoc.opBackupExport,
[ pInstanceName
, pInstanceUuid
, pBackupCompress
, pShutdownTimeout
, pExportTargetNode
, pExportTargetNodeUuid
, pShutdownInstance
, pRemoveInstance
, pIgnoreRemoveFailures
, defaultField [| ExportModeLocal |] pExportMode
, pX509KeyName
, pX509DestCA
, pZeroFreeSpace
, pZeroingTimeoutFixed
, pZeroingTimeoutPerMiB
, pLongSleep
],
"instance_name")
, ("OpBackupRemove",
[t| () |],
OpDoc.opBackupRemove,
[ pInstanceName
, pInstanceUuid
],
"instance_name")
, ("OpTagsGet",
[t| [NonEmptyString] |],
OpDoc.opTagsGet,
[ pTagsObject
, pUseLocking
, withDoc "Name of object to retrieve tags from" pTagsName
],
"name")
, ("OpTagsSearch",
[t| [(NonEmptyString, NonEmptyString)] |],
OpDoc.opTagsSearch,
[ pTagSearchPattern
],
"pattern")
, ("OpTagsSet",
[t| () |],
OpDoc.opTagsSet,
[ pTagsObject
, pTagsList
, withDoc "Name of object where tag(s) should be added" pTagsName
],
[])
, ("OpTagsDel",
[t| () |],
OpDoc.opTagsDel,
[ pTagsObject
, pTagsList
, withDoc "Name of object where tag(s) should be deleted" pTagsName
],
[])
, ("OpTestDelay",
[t| () |],
OpDoc.opTestDelay,
[ pDelayDuration
, pDelayOnMaster
, pDelayOnNodes
, pDelayOnNodeUuids
, pDelayRepeat
, pDelayInterruptible
, pDelayNoLocks
],
"duration")
, ("OpTestAllocator",
[t| String |],
OpDoc.opTestAllocator,
[ pIAllocatorDirection
, pIAllocatorMode
, pIAllocatorReqName
, pIAllocatorNics
, pIAllocatorDisks
, pHypervisor
, pIallocator
, pInstTags
, pIAllocatorMemory
, pIAllocatorVCpus
, pIAllocatorOs
, pOptDiskTemplate
, pIAllocatorInstances
, pIAllocatorEvacMode
, pTargetGroups
, pIAllocatorSpindleUse
, pIAllocatorCount
, pOptGroupName
],
"iallocator")
, ("OpTestJqueue",
[t| Bool |],
OpDoc.opTestJqueue,
[ pJQueueNotifyWaitLock
, pJQueueNotifyExec
, pJQueueLogMessages
, pJQueueFail
],
[])
, ("OpTestOsParams",
[t| () |],
OpDoc.opTestOsParams,
[ pInstOsParamsSecret
],
[])
, ("OpTestDummy",
[t| () |],
OpDoc.opTestDummy,
[ pTestDummyResult
, pTestDummyMessages
, pTestDummyFail
, pTestDummySubmitJobs
],
[])
, ("OpNetworkAdd",
[t| () |],
OpDoc.opNetworkAdd,
[ pNetworkName
, pNetworkAddress4
, pNetworkGateway4
, pNetworkAddress6
, pNetworkGateway6
, pNetworkMacPrefix
, pNetworkAddRsvdIps
, pIpConflictsCheck
, withDoc "Network tags" pInstTags
],
"network_name")
, ("OpNetworkRemove",
[t| () |],
OpDoc.opNetworkRemove,
[ pNetworkName
, pForce
],
"network_name")
, ("OpNetworkRename",
[t| NonEmptyString |],
OpDoc.opNetworkRename,
[ pNetworkName
, withDoc "New network name" pNewName
],
[])
, ("OpNetworkSetParams",
[t| () |],
OpDoc.opNetworkSetParams,
[ pNetworkName
, pNetworkGateway4
, pNetworkAddress6
, pNetworkGateway6
, pNetworkMacPrefix
, withDoc "Which external IP addresses to reserve" pNetworkAddRsvdIps
, pNetworkRemoveRsvdIps
],
"network_name")
, ("OpNetworkConnect",
[t| () |],
OpDoc.opNetworkConnect,
[ pGroupName
, pNetworkName
, pNetworkMode
, pNetworkLink
, pNetworkVlan
, pIpConflictsCheck
],
"network_name")
, ("OpNetworkDisconnect",
[t| () |],
OpDoc.opNetworkDisconnect,
[ pGroupName
, pNetworkName
],
"network_name")
])
deriving instance Ord OpCode
-- | Returns the OP_ID for a given opcode value.
$(genOpID ''OpCode "opID")
-- | A list of all defined/supported opcode IDs.
$(genAllOpIDs ''OpCode "allOpIDs")
-- | Convert the opcode name to lowercase with underscores and strip
-- the @Op@ prefix.
$(genOpLowerStrip (C.opcodeReasonSrcOpcode ++ ":") ''OpCode "opReasonSrcID")
instance JSON OpCode where
readJSON = readJSONfromDict
showJSON = showJSONtoDict
-- | Generates the summary value for an opcode.
opSummaryVal :: OpCode -> Maybe String
opSummaryVal OpClusterVerifyGroup { opGroupName = s } = Just (fromNonEmpty s)
opSummaryVal OpGroupVerifyDisks { opGroupName = s } = Just (fromNonEmpty s)
opSummaryVal OpClusterRename { opName = s } = Just (fromNonEmpty s)
opSummaryVal OpQuery { opWhat = s } = Just (queryTypeOpToRaw s)
opSummaryVal OpQueryFields { opWhat = s } = Just (queryTypeOpToRaw s)
opSummaryVal OpNodeRemove { opNodeName = s } = Just (fromNonEmpty s)
opSummaryVal OpNodeAdd { opNodeName = s } = Just (fromNonEmpty s)
opSummaryVal OpNodeModifyStorage { opNodeName = s } = Just (fromNonEmpty s)
opSummaryVal OpRepairNodeStorage { opNodeName = s } = Just (fromNonEmpty s)
opSummaryVal OpNodeSetParams { opNodeName = s } = Just (fromNonEmpty s)
opSummaryVal OpNodePowercycle { opNodeName = s } = Just (fromNonEmpty s)
opSummaryVal OpNodeMigrate { opNodeName = s } = Just (fromNonEmpty s)
opSummaryVal OpNodeEvacuate { opNodeName = s } = Just (fromNonEmpty s)
opSummaryVal OpInstanceCreate { opInstanceName = s } = Just s
opSummaryVal OpInstanceReinstall { opInstanceName = s } = Just s
opSummaryVal OpInstanceRemove { opInstanceName = s } = Just s
-- FIXME: instance rename should show both names; currently it shows none
-- opSummaryVal OpInstanceRename { opInstanceName = s } = Just s
opSummaryVal OpInstanceStartup { opInstanceName = s } = Just s
opSummaryVal OpInstanceShutdown { opInstanceName = s } = Just s
opSummaryVal OpInstanceReboot { opInstanceName = s } = Just s
opSummaryVal OpInstanceReplaceDisks { opInstanceName = s } = Just s
opSummaryVal OpInstanceFailover { opInstanceName = s } = Just s
opSummaryVal OpInstanceMigrate { opInstanceName = s } = Just s
opSummaryVal OpInstanceMove { opInstanceName = s } = Just s
opSummaryVal OpInstanceConsole { opInstanceName = s } = Just s
opSummaryVal OpInstanceActivateDisks { opInstanceName = s } = Just s
opSummaryVal OpInstanceDeactivateDisks { opInstanceName = s } = Just s
opSummaryVal OpInstanceRecreateDisks { opInstanceName = s } = Just s
opSummaryVal OpInstanceSetParams { opInstanceName = s } = Just s
opSummaryVal OpInstanceGrowDisk { opInstanceName = s } = Just s
opSummaryVal OpInstanceChangeGroup { opInstanceName = s } = Just s
opSummaryVal OpGroupAdd { opGroupName = s } = Just (fromNonEmpty s)
opSummaryVal OpGroupAssignNodes { opGroupName = s } = Just (fromNonEmpty s)
opSummaryVal OpGroupSetParams { opGroupName = s } = Just (fromNonEmpty s)
opSummaryVal OpGroupRemove { opGroupName = s } = Just (fromNonEmpty s)
opSummaryVal OpGroupEvacuate { opGroupName = s } = Just (fromNonEmpty s)
opSummaryVal OpBackupPrepare { opInstanceName = s } = Just s
opSummaryVal OpBackupExport { opInstanceName = s } = Just s
opSummaryVal OpBackupRemove { opInstanceName = s } = Just s
opSummaryVal OpTagsGet { opKind = s } = Just (show s)
opSummaryVal OpTagsSearch { opTagSearchPattern = s } = Just (fromNonEmpty s)
opSummaryVal OpTestDelay { opDelayDuration = d } = Just (show d)
opSummaryVal OpTestAllocator { opIallocator = s } =
-- FIXME: Python doesn't handle None fields well, so we have behave the same
Just $ maybe "None" fromNonEmpty s
opSummaryVal OpNetworkAdd { opNetworkName = s} = Just (fromNonEmpty s)
opSummaryVal OpNetworkRemove { opNetworkName = s} = Just (fromNonEmpty s)
opSummaryVal OpNetworkSetParams { opNetworkName = s} = Just (fromNonEmpty s)
opSummaryVal OpNetworkConnect { opNetworkName = s} = Just (fromNonEmpty s)
opSummaryVal OpNetworkDisconnect { opNetworkName = s} = Just (fromNonEmpty s)
opSummaryVal _ = Nothing
-- | Computes the summary of the opcode.
opSummary :: OpCode -> String
opSummary op =
case opSummaryVal op of
Nothing -> op_suffix
Just s -> op_suffix ++ "(" ++ s ++ ")"
where op_suffix = drop 3 $ opID op
-- | Generic\/common opcode parameters.
$(buildObject "CommonOpParams" "op"
[ pDryRun
, pDebugLevel
, pOpPriority
, pDependencies
, pComment
, pReason
])
deriving instance Ord CommonOpParams
-- | Default common parameter values.
defOpParams :: CommonOpParams
defOpParams =
CommonOpParams { opDryRun = Nothing
, opDebugLevel = Nothing
, opPriority = OpPrioNormal
, opDepends = Nothing
, opComment = Nothing
, opReason = []
}
-- | Resolve relative dependencies to absolute ones, given the job ID.
resolveDependsCommon :: (MonadFail m) =>
CommonOpParams -> JobId -> m CommonOpParams
resolveDependsCommon p@(CommonOpParams { opDepends = Just deps}) jid = do
deps' <- mapM (`absoluteJobDependency` jid) deps
return p { opDepends = Just deps' }
resolveDependsCommon p _ = return p
-- | The top-level opcode type.
data MetaOpCode = MetaOpCode { metaParams :: CommonOpParams
, metaOpCode :: OpCode
} deriving (Show, Eq, Ord)
-- | Resolve relative dependencies to absolute ones, given the job Id.
resolveDependencies :: (MonadFail m) => MetaOpCode -> JobId -> m MetaOpCode
resolveDependencies mopc jid = do
mpar <- resolveDependsCommon (metaParams mopc) jid
return (mopc { metaParams = mpar })
instance DictObject MetaOpCode where
toDict (MetaOpCode meta op) = toDict meta ++ toDict op
fromDictWKeys dict = MetaOpCode <$> fromDictWKeys dict
<*> fromDictWKeys dict
instance JSON MetaOpCode where
readJSON = readJSONfromDict
showJSON = showJSONtoDict
-- | Wraps an 'OpCode' with the default parameters to build a
-- 'MetaOpCode'.
wrapOpCode :: OpCode -> MetaOpCode
wrapOpCode = MetaOpCode defOpParams
-- | Sets the comment on a meta opcode.
setOpComment :: String -> MetaOpCode -> MetaOpCode
setOpComment comment (MetaOpCode common op) =
MetaOpCode (common { opComment = Just comment}) op
-- | Sets the priority on a meta opcode.
setOpPriority :: OpSubmitPriority -> MetaOpCode -> MetaOpCode
setOpPriority prio (MetaOpCode common op) =
MetaOpCode (common { opPriority = prio }) op
| ganeti/ganeti | src/Ganeti/OpCodes.hs | bsd-2-clause | 30,079 | 0 | 12 | 7,728 | 5,906 | 3,620 | 2,286 | 955 | 2 |
module Test.Haddock.Xhtml
( Xml
, parseXml, dumpXml
, stripLinks, stripLinksWhen, stripAnchorsWhen, stripIdsWhen, stripFooter
) where
{-
This module used to actually parse the HTML (using the `xml` parsing library)
which made it was possible to do more proper normalization of things like ids or
names.
However, in the interests of being able to run this from within the GHC
testsuite (where non-bootlib dependencies are a liability), this was swapped
out for some simple string manipulation. Since the test cases aren't very
and since the `xhtml` library already handles the pretty-printing aspect,
this would appear to be a reasonable compromise for now.
-}
import Data.List ( stripPrefix, isPrefixOf )
import Data.Char ( isSpace )
-- | Simple wrapper around the pretty-printed HTML source
newtype Xml = Xml { unXml :: String }
-- | Part of parsing involves dropping the @DOCTYPE@ line
parseXml :: String -> Maybe Xml
parseXml = Just . Xml . dropDocTypeLine
where
dropDocTypeLine bs
| "<!DOCTYPE" `isPrefixOf` bs
= drop 1 (dropWhile (/= '\n') bs)
| otherwise
= bs
dumpXml :: Xml -> String
dumpXml = unXml
type Attr = String
type Value = String
-- | Almost all sanitization operations take the form of:
--
-- * match an attribute key
-- * check something about the value
-- * if the check succeeded, replace the value with a dummy value
--
stripAttrValueWhen
:: Attr -- ^ attribute key
-> Value -- ^ dummy attribute value
-> (Value -> Bool) -- ^ determine whether we should modify the attribute
-> Xml -- ^ input XML
-> Xml -- ^ output XML
stripAttrValueWhen key fallback p (Xml body) = Xml (filterAttrs body)
where
keyEq = key ++ "=\""
filterAttrs "" = ""
filterAttrs b@(c:cs)
| Just valRest <- stripPrefix keyEq b
, Just (val,rest) <- spanToEndOfString valRest
= if p val
then keyEq ++ fallback ++ "\"" ++ filterAttrs rest
else keyEq ++ val ++ "\"" ++ filterAttrs rest
| otherwise
= c : filterAttrs cs
-- | Spans to the next (unescaped) @\"@ character.
--
-- >>> spanToEndOfString "no closing quotation"
-- Nothing
-- >>> spanToEndOfString "foo\" bar \"baz\""
-- Just ("foo", " bar \"baz\"")
-- >>> spanToEndOfString "foo\\\" bar \"baz\""
-- Just ("foo\\\" bar ", "baz\"")
--
spanToEndOfString :: String -> Maybe (String, String)
spanToEndOfString ('"':rest) = Just ("", rest)
spanToEndOfString ('\\':c:rest)
| Just (str, rest') <- spanToEndOfString rest
= Just ('\\':c:str, rest')
spanToEndOfString (c:rest)
| Just (str, rest') <- spanToEndOfString rest
= Just (c:str, rest')
spanToEndOfString _ = Nothing
-- | Replace hyperlink targets with @\"#\"@ if they match a predicate
stripLinksWhen :: (Value -> Bool) -> Xml -> Xml
stripLinksWhen = stripAttrValueWhen "href" "#"
-- | Replace all hyperlink targets with @\"#\"@
stripLinks :: Xml -> Xml
stripLinks = stripLinksWhen (const True)
-- | Replace id's with @\"\"@ if they match a predicate
stripIdsWhen :: (Value -> Bool) -> Xml -> Xml
stripIdsWhen = stripAttrValueWhen "id" ""
-- | Replace names's with @\"\"@ if they match a predicate
stripAnchorsWhen :: (Value -> Bool) -> Xml -> Xml
stripAnchorsWhen = stripAttrValueWhen "name" ""
-- | Remove the @div@ which has @id=\"footer\"@
stripFooter :: Xml -> Xml
stripFooter (Xml body) = Xml (findDiv body)
where
findDiv "" = ""
findDiv b@(c:cs)
| Just divRest <- stripPrefix "<div id=\"footer\"" b
, Just rest <- dropToDiv divRest
= rest
| otherwise
= c : findDiv cs
dropToDiv "" = Nothing
dropToDiv b@(_:cs)
| Just valRest <- stripPrefix "</div" b
, valRest' <- dropWhile isSpace valRest
, Just valRest'' <- stripPrefix ">" valRest'
= Just valRest''
| otherwise
= dropToDiv cs
| haskell/haddock | haddock-test/src/Test/Haddock/Xhtml.hs | bsd-2-clause | 3,856 | 0 | 12 | 869 | 852 | 451 | 401 | 69 | 3 |
{-# LANGUAGE UndecidableInstances #-}
module Feldspar.Multicore.Channel.Representation where
import Control.Monad.Operational.Higher
import Control.Monad.Trans
import Data.Ix
import Data.Proxy
import Data.Typeable
import Data.TypedStruct
import GHC.Exts (Constraint)
import Feldspar
import Feldspar.Multicore.CoreId
import Feldspar.Primitive.Representation
import Feldspar.Representation
import Feldspar.Run
import Feldspar.Run.Concurrent
import Feldspar.Run.Representation
import qualified Language.Embedded.Concurrent as Imp
import qualified Language.Embedded.Concurrent.CMD as Imp
import qualified Language.Embedded.Expression as Imp
import qualified Language.Embedded.Imperative as Imp
data CoreChan (a :: *)
= CoreChanRun (Imp.Chan Imp.Closeable a)
| CoreChanComp ChanCompRep
type ChanRef = FunArg Data PrimType'
type ChanArgs = [FunArg Data PrimType']
data ChanCompRep
= HostChanRep ChanRef ChanArgs
| CoreChanRep ChanArgs
data CoreChanAllocCMD fs a where
NewChan :: pred a
=> CoreId
-> CoreId
-> Length
-> CoreChanAllocCMD (Param3 prog exp pred) (CoreChan a)
instance HFunctor CoreChanAllocCMD where
hfmap _ (NewChan f t sz) = NewChan f t sz
instance HBifunctor CoreChanAllocCMD where
hbimap _ _ (NewChan f t sz) = NewChan f t sz
instance (CoreChanAllocCMD :<: instr) => Reexpressible CoreChanAllocCMD instr env where
reexpressInstrEnv reexp (NewChan f t sz) = lift $ singleInj $ NewChan f t sz
runCoreChanAllocCMD :: CoreChanAllocCMD (Param3 Run Prim PrimType) a -> Run a
runCoreChanAllocCMD cmd@(NewChan _ _ sz) = do
let size = (value sz) `Imp.timesSizeOf` (chanElemType cmd)
c <- Run $ Imp.newCloseableChan' size
return $ CoreChanRun c
where
chanElemType :: cmd (Param3 p e pred) (CoreChan t) -> Proxy t
chanElemType _ = Proxy
instance Interp CoreChanAllocCMD Run (Param2 Prim PrimType)
where interp = runCoreChanAllocCMD
data CoreChanCMD fs a where
ReadChan :: (Typeable a, pred a)
=> CoreChan c -> exp Index -> exp Index
-> DArr a -> CoreChanCMD (Param3 prog exp pred) (exp Bool)
WriteOne :: (Typeable a, pred a)
=> CoreChan a -> exp a
-> CoreChanCMD (Param3 prog exp pred) (exp Bool)
WriteChan :: (Typeable a, pred a)
=> CoreChan c -> exp Index -> exp Index
-> DArr a -> CoreChanCMD (Param3 prog exp pred) (exp Bool)
CloseChan :: CoreChan a -> CoreChanCMD (Param3 prog exp pred) ()
instance HFunctor CoreChanCMD where
hfmap _ (ReadChan c f t a) = ReadChan c f t a
hfmap _ (WriteOne c x) = WriteOne c x
hfmap _ (WriteChan c f t a) = WriteChan c f t a
hfmap _ (CloseChan c) = CloseChan c
runCoreChanCMD :: CoreChanCMD (Param3 Run Data PrimType') a -> Run a
runCoreChanCMD (WriteOne (CoreChanRun c) v) =
Run $ (fmap Imp.valToExp) $ singleInj $ Imp.WriteOne c v
runCoreChanCMD (ReadChan (CoreChanRun c) off sz (Arr _ _ (Single arr))) =
Run $ (fmap Imp.valToExp) $ singleInj $ Imp.ReadChan c off sz arr
runCoreChanCMD (WriteChan (CoreChanRun c) off sz (Arr _ _ (Single arr))) =
Run $ (fmap Imp.valToExp) $ singleInj $ Imp.WriteChan c off sz arr
runCoreChanCMD (CloseChan (CoreChanRun c)) = Run $ Imp.closeChan c
instance Interp CoreChanCMD Run (Param2 Data PrimType')
where interp = runCoreChanCMD
| kmate/raw-feldspar-mcs | src/Feldspar/Multicore/Channel/Representation.hs | bsd-3-clause | 3,339 | 0 | 12 | 695 | 1,168 | 606 | 562 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Acc.Stencil where
import Data.Array.Accelerate as A
import Acc.Types
import Prelude as P
yxStencil3x3
:: forall a. Elt a
=> (Stencil3x3 a -> Exp a)
-> Acc (Cube a)
-> Acc (Cube a)
yxStencil3x3 s = stencil f A.Clamp
where
f :: Stencil3x3x3 a -> Exp a
f (_a,b,_c) = s b
yxStencil5x5
:: forall a. Elt a
=> (Stencil5x5 a -> Exp a)
-> Acc (Cube a)
-> Acc (Cube a)
yxStencil5x5 s = stencil f A.Clamp
where
f :: Stencil5x5x3 a -> Exp a
f (_a,b,_c) = s b
convolve5x5
:: (P.Num (Exp a), Elt a, IsNum a)
=> [Exp a]
-> Stencil5x5 a
-> Exp a
convolve5x5 kernel
(
(a1,a2,a3,a4,a5),
(b1,b2,b3,b4,b5),
(c1,c2,c3,c4,c5),
(d1,d2,d3,d4,d5),
(e1,e2,e3,e4,e5)
) = P.sum $ P.zipWith (*) kernel
[
a1,a2,a3,a4,a5,
b1,b2,b3,b4,b5,
c1,c2,c3,c4,c5,
d1,d2,d3,d4,d5,
e1,e2,e3,e4,e5
]
| cpdurham/accelerate-camera-sandbox | src/Acc/Stencil.hs | bsd-3-clause | 961 | 0 | 11 | 266 | 488 | 276 | 212 | 41 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.TimeGrain.GA.Rules
( rules ) where
import Data.Text (Text)
import Prelude
import Data.String
import Duckling.Dimensions.Types
import qualified Duckling.TimeGrain.Types as TG
import Duckling.Types
grains :: [(Text, String, TG.Grain)]
grains = [ ("soicind (grain)", "t?sh?oicind(\x00ed|i)?", TG.Second)
, ("nóiméad (grain)", "n[\x00f3o]im(\x00e9|e)[ai]da?", TG.Minute)
, ("uair (grain)", "([thn]-?)?uair(e|eanta)?", TG.Hour)
, ("lá (grain)", "l(ae(thanta)?|(\x00e1|a))", TG.Day)
, ("seachtain (grain)", "t?sh?eachtain(e|(\x00ed|i))?", TG.Week)
, ("mí (grain)", "mh?(\x00ed|i)(sa|nna)", TG.Month)
, ("ráithe (grain)", "r(\x00e1|a)ith(e|(\x00ed|i))", TG.Quarter)
, ("bliain (grain)", "m?bh?lia(in|na|nta)", TG.Year)
]
rules :: [Rule]
rules = map go grains
where
go (name, regexPattern, grain) = Rule
{ name = name
, pattern = [regex regexPattern]
, prod = \_ -> Just $ Token TimeGrain grain
}
| rfranek/duckling | Duckling/TimeGrain/GA/Rules.hs | bsd-3-clause | 1,380 | 0 | 11 | 277 | 272 | 173 | 99 | 25 | 1 |
import Types
import Graphics.GL.Pal
sphere :: Float -> [Cube]
sphere t =
[ newCube
{ cubeColor = colorHSL (x*0.1+t*0.5) 0.8 0.6
, cubeRotation = axisAngle (V3 0 0 1) t
, cubePosition = rotate (axisAngle (V3 0 1 0) (x*0.2))
. rotate (axisAngle (V3 1 0 0) (x*0.01))
$ (V3 0 1 1)
, cubeScale = V3
(realToFrac $ 0.1 * sin (x+t*5))
(realToFrac $ 0.15 * sin (x+t*4))
(realToFrac $ 0.2 * sin (x+t*6))
}
| x <- [0..n]
]
where n = fromIntegral $ abs $ (subtract (maxx `div` 2)) $ min maxx (mod (floor (t*50)) maxx)
maxx = 6000
| lukexi/cubensis | defs/Sphere.hs | bsd-3-clause | 697 | 0 | 14 | 281 | 330 | 175 | 155 | 17 | 1 |
module Data.Geo.GPX.Lens.RtesL where
import Data.Geo.GPX.Type.Rte
import Data.Lens.Common
class RtesL a where
rtesL :: Lens a [Rte]
| tonymorris/geo-gpx | src/Data/Geo/GPX/Lens/RtesL.hs | bsd-3-clause | 137 | 0 | 8 | 21 | 45 | 28 | 17 | 5 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module QueryTariff where
import Control.Lens
import Control.Monad.Trans.Except (ExceptT (..), throwE)
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.Char (isDigit)
import qualified Data.Text as T
import Data.Text.Read
import Data.Time (Day, diffDays)
import Data.Time.Clock (getCurrentTime, utctDay)
import Data.Time.Format (defaultTimeLocale, parseTimeM)
import Network.Wreq.StringLess
import qualified Network.Wreq.StringLess.Session as WS
import Network.Wreq.StringLess.Types (Postable)
import Protolude
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Match hiding (tagText)
import Text.StringLike
import Types
-- | query the actual tariff from the provider
--
queryTariff :: App Tariff
queryTariff = do
baseUrl <- asks acProviderBaseUrl
withSession $ \sess -> do
res <- lift $ WS.get sess (baseUrl <> "/de/tarif/mein-tarif")
let body = res ^. responseBody
today <- lift (utctDay <$> getCurrentTime)
either throwE pure $ extract today (parseTags body)
where extract :: Day -> [Tag LByteString] -> Either AppError Tariff
extract today tags = Tariff
<$> extractBalance tags
<*> extractUsage tags
<*> extractDaysLeft today tags
-- | extract the balance
--
-- <div id="ajaxReplaceQuickInfoBoxBalanceId">
-- <strong>
-- <p>20,13 €</p>
-- </strong>
-- </div>
--
extractBalance :: [Tag LByteString] -> Either AppError Balance
extractBalance tags = firstTagTextBy "Balance" locator tags >>= extract
where locator = drop 5 . dropWhile (~/== "<div id=ajaxReplaceQuickInfoBoxBalanceId>")
extract = readBalance . takeBalance . toS
takeBalance = T.takeWhile (liftM2 (||) isDigit (== ','))
tr f t = T.map (\c -> if(c == f) then t else c)
readBalance = bimap BalanceNotParsable Balance . rational' . (tr ',' '.')
-- | extract the usage
--
-- <p><strong>Internet-Flatrate XL</strong></p>
-- Daten<br>
-- <div class="display-mode-remaining progress-bar progress-bar--big">
-- <div class="progress" style="width:38.4375%;"></div>
-- </div>
-- <p class="small">
-- Noch 1968 von 5120 MB verfügbar
-- </p>
--
extractUsage :: [Tag LByteString] -> Either AppError Usage
extractUsage tags = maybeToRight UsageNotExtractable (locator tags) >>= extract
where locator = fmap fromTagText . headMay . drop 8 . dropWhile (not . tagOpen ( == "div") (anyAttrValue (T.isInfixOf "display-mode-remaining" . toS)))
-- this is our input:
--
-- "\n Noch 1968 von 5120 MB verf\195\188gbar\n "
extract ((T.words . T.strip . toS) -> _ : a : _ : q : _) = buildUsage q a
extract _ = Left UsageNotExtractable
buildUsage q a = let errOrQuota = decimal' q
errOrAvailable = decimal' a
errOrUsed = (-) <$> errOrQuota <*> errOrAvailable
errOrUsage = Usage <$> errOrQuota <*> errOrUsed <*> errOrAvailable
in over _Left UsageNotParsable errOrUsage
-- | extract how many days left
--
-- <tr class="t-row">
-- <td class="t-label">Laufzeitende</td>
-- <td>27.01.17</td>
-- <td> </td>
-- </tr>
--
extractDaysLeft :: Day -> [Tag LByteString] -> Either AppError Integer
extractDaysLeft today tags = firstTagTextBy "Days left" locator tags >>= extract
where locator = drop 4 . dropWhile (~/== "Laufzeitende")
extract (toS -> s) = bimap EndDateNotParsable calcDaysLeft $ parseTimeM True defaultTimeLocale "%d.%m.%y" s
calcDaysLeft end = diffDays end today
-- | Data.Text.Read.decimal wrapper
--
-- * skip's the rest content after parsing
-- * pack the error msg in 'Text'
--
decimal' :: Text -> Either Text Int
decimal' = bimap T.pack (view _1) . decimal
-- | Data.Text.Read.rational wrapper
--
-- * skip's the rest content after parsing
-- * pack the error msg in 'Text'
--
rational' :: Text -> Either Text Float
rational' = bimap T.pack (view _1) . rational
-- | Find the first Tag Text from the given Tag's with the given locator function
--
firstTagTextBy :: Text -> ([Tag LByteString] -> [Tag LByteString]) -> [Tag LByteString] -> Either AppError LByteString
firstTagTextBy id locator tags = firstTag (locator tags) >>= tagText
where firstTag = maybe (Left $ TagNotFound id) Right . listToMaybe
tagText = maybe (Left $ TagHasNoText id) Right . maybeTagText
-- | wrapper to handle the login in the background
--
withSession :: (WS.Session -> ExceptT AppError IO a) -> App a
withSession f = do
baseUrl <- asks acProviderBaseUrl
providerLogin <- asks acProviderLogin
lift $ (ExceptT $ login baseUrl providerLogin) >>= f
-- | login in the provider web app
--
login :: ProviderBaseUrl -> ProviderLogin -> IO (Either AppError WS.Session)
login baseUrl pl = WS.withSession $ \sess -> do
-- invalidate old session
_ <- WS.post sess (baseUrl <> "/de/logout") BSL.empty
-- go to the base url, and extract the actual login token
token <- extractToken . parseTags . view responseBody <$> WS.get sess baseUrl
-- build login params
let loginParams = ["_username" := plUser pl, "_password" := plPass pl, "_csrf_token" := token]
-- perform login
bimap (LoginError . show) (const sess) <$> tryPost sess (baseUrl <> "/de/login_check") loginParams
where tryPost :: Postable a => WS.Session -> Text -> a -> IO (Either SomeException (Response LByteString))
tryPost sess url payload = try $ WS.post sess url payload
extractToken :: [Tag LByteString] -> Maybe LByteString
extractToken = fmap (fromAttrib "value") . listToMaybe . dropWhile (~/== "<input name=_csrf_token")
-- | (~/==) Wrapper to fix the selector Type to [Char].
--
-- TagSoup has two Type Classes for the selector: [Char] and (TagRep (Tag str)).
-- With the use of 'OverloadedText', we get ambiguous Type Classes for the selector.
--
(~/==) :: StringLike str => Tag str -> [Char] -> Bool
(~/==) a b = a ~/= (b :: [Char])
| section77/datenverbrauch | src/QueryTariff.hs | bsd-3-clause | 6,813 | 0 | 17 | 1,982 | 1,526 | 819 | 707 | 82 | 2 |
{-# LANGUAGE FlexibleInstances #-}
-- ghc options
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- {-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
-- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-}
-- {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE CPP #-}
#ifdef DocTest
-- use with caution, but really want less warnings for the doctests here
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
#endif
-- |
-- Copyright : (c) Andreas Reuleaux 2015
-- License : BSD2
-- Maintainer: Andreas Reuleaux <[email protected]>
-- Stability : experimental
-- Portability: non-portable
--
-- This module provides pretty printing functionality for Pire's
-- abstract and concrete syntax: decls
module Pire.Pretty.Decl where
import Pire.Syntax.Decl
import Pire.Pretty.Common
import Pire.Pretty.Expr ()
import Pire.Pretty.Telescope ()
import Pire.Pretty.Constructor ()
import Text.PrettyPrint as TPP
#ifdef MIN_VERSION_GLASGOW_HASKELL
#if MIN_VERSION_GLASGOW_HASKELL(7,10,3,0)
-- ghc >= 7.10.3
#else
-- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined
#endif
#else
-- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x)
import Control.Applicative
#endif
import Pire.String2Text
import qualified Data.Text as T
import Data.Bifunctor
-- this unit test was in Pretty.Expr formerly,
-- but couldn't stay there [ghc7.10]: needed to import Pretty.Decl from Pretty.Expr
-- TODO should be tested here I guess
-- -- -- -- (cf. file Vec.pi):
-- -- -- -- >>> pp $ nopos $ parse decl_ "singleton = \\[A] x. Cons [0] x Nil"
-- -- -- -- singleton = \[A] x. Cons [0] x Nil
#ifdef DocTest
-- for the doctests
import Pire.Syntax.Modules (decls)
import Pire.Modules (getModules_)
import Control.Monad.Except (runExceptT)
import Control.Lens ((^.))
import Pire.NoPos (nopos)
import Data.Either.Combinators (fromRight')
#endif
-- reminder for myself: doctest manual
-- https://github.com/sol/doctest#readme
#ifdef PiForallInstalled
{-|
brackets in data types are are handled fine now:
>>> (runExceptT $ getModules_ ["pitestfiles"] "Vec") >>= return . pp . (!! 0) . (^. decls) . nopos . last . fromRight'
Parsing File "pitestfiles/Logic.pi"
Parsing File "pitestfiles/Equality.pi"
Parsing File "pitestfiles/Equality.pi"
Parsing File "pitestfiles/Equality.pi"
Parsing File "pitestfiles/Nat.pi"
Parsing File "pitestfiles/Fin.pi"
Parsing File "pitestfiles/Product.pi"
Parsing File "pitestfiles/Vec.pi"
data Vec (A : Type) (n : Nat) : Type where
Nil of [n = Zero]
Cons of [m:Nat][n = Succ m] (A) (Vec A m)
<BLANKLINE>
<BLANKLINE>
these should all work fine now:
@
(runExceptT $ getModules_ ["pitestfiles"] \"Vec\") >>= return . (!! 0) . (^. decls) . nopos . last . fromRight'
(runExceptT $ getModules_ ["pitestfiles"] \"Vec\") >>= return . (_decls) . nopos . last . fromRight'
@
likewise for @_constrs@:
@
(runExceptT $ getModules_ ["pitestfiles"] \"Vec\") >>= return . (_constrs) . nopos . last . fromRight'
(runExceptT $ getModules_ ["pitestfiles"] \"Vec\") >>= return . pp . (!! 2) . (^. decls) . nopos . last . fromRight'
(runExceptT $ getModules_ ["pitestfiles"] \"Vec\") >>= return . (!! 2) . _decls . nopos . last . fromRight'
@
-}
#endif
-- dispDecl :: Disp s => Decl_ s s -> M Doc
dispDecl :: Decl T.Text T.Text -> M Doc
dispDecl (Sig n ty) = do
dn <- disp n
dt <- disp ty
return $ dn <+> text ":" <+> dt
dispDecl (Sig_ nm col ty) = do
dn <- disp nm
dc <- disp col
dt <- disp ty
return $ dn <> dc <> dt
dispDecl (Def n term) = do
dn <- disp n
dt <- disp term
-- maybe an extra newline after the Defs for readablitiy
-- return $ dn <+> text "=" <+> dt <> text "\n"
return $ dn <+> text "=" <+> dt
dispDecl (Def_ n eq term) = do
dn <- disp n
de <- disp eq
dt <- disp term
return $ dn <> de <> dt
dispDecl (RecDef n term) = dispDecl $ Def n term
dispDecl (RecDef_ n eq term) = dispDecl $ Def_ n eq term
dispDecl (Data n params constructors) = do
dn <- disp n
dp <- disp params
dc <- mapM disp constructors
return $ hang (text "data" <+> dn <+> dp
<+> colon <+> text "Type"
<+> text "where") 2 $ vcat dc
-- -- todo: ws after data
-- -- moreover: rework for indentent blocks with braces+commas à la
-- -- { Foo ; Bar}
dispDecl (Data_ datatok nm tele col ty w bo constrs bc) = do
dd <- disp datatok
dn <- disp nm
dtele <- disp tele
dcol <- disp col
dty <- disp ty
dw <- disp w
-- dc <- mapM disp constrs
-- dc <- mapM disp [c | (c, _)<-constrs]
dc <- mapM (\(c, semicol) -> (<>) <$> (disp c) <*> (disp semicol)) constrs
dbo <- disp bo
dbc <- disp bc
return $ dd <> dn <> dtele <> dcol <> dty <> dw <> dbo <> hcat dc <> dbc
instance Disp (Decl T.Text T.Text) where
disp = dispDecl
instance Disp (Decl String String) where
disp = dispDecl . s2t
-- instance Disp s => Disp [Decl s s] where
instance Disp [Decl T.Text T.Text] where
-- disp ds = vcat <$> mapM disp ds
disp ds = hcat <$> mapM disp ds
instance Disp [Decl String String] where
disp = disp . s2t
instance Disp (Decl (T.Text, a) (T.Text, a)) where
disp = dispDecl . (bimap fst fst)
instance Disp (Decl (String, a) (String, a)) where
disp = dispDecl . s2t . (bimap fst fst)
| reuleaux/pire | src/Pire/Pretty/Decl.hs | bsd-3-clause | 5,470 | 0 | 16 | 1,109 | 1,012 | 534 | 478 | 67 | 1 |
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs, DataKinds, FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE StandaloneDeriving #-}
module CustomConstraintTest where
import PgInit
import qualified Data.Text as T
share [mkPersist sqlSettings, mkMigrate "customConstraintMigrate"] [persistLowerCase|
CustomConstraint1
some_field Text
deriving Show
CustomConstraint2
cc_id CustomConstraint1Id constraint=custom_constraint
deriving Show
CustomConstraint3
-- | This will lead to a constraint with the name custom_constraint3_cc_id1_fkey
cc_id1 CustomConstraint1Id
cc_id2 CustomConstraint1Id
deriving Show
|]
specs :: Spec
specs = do
describe "custom constraint used in migration" $ do
it "custom constraint is actually created" $ runConnAssert $ do
void $ runMigrationSilent customConstraintMigrate
void $ runMigrationSilent customConstraintMigrate -- run a second time to ensure the constraint isn't dropped
let query = T.concat ["SELECT DISTINCT COUNT(*) "
,"FROM information_schema.constraint_column_usage ccu, "
,"information_schema.key_column_usage kcu, "
,"information_schema.table_constraints tc "
,"WHERE tc.constraint_type='FOREIGN KEY' "
,"AND kcu.constraint_name=tc.constraint_name "
,"AND ccu.constraint_name=kcu.constraint_name "
,"AND kcu.ordinal_position=1 "
,"AND ccu.table_name=? "
,"AND ccu.column_name=? "
,"AND kcu.table_name=? "
,"AND kcu.column_name=? "
,"AND tc.constraint_name=?"]
[Single exists_] <- rawSql query [PersistText "custom_constraint1"
,PersistText "id"
,PersistText "custom_constraint2"
,PersistText "cc_id"
,PersistText "custom_constraint"]
liftIO $ 1 @?= (exists_ :: Int)
it "allows multiple constraints on a single column" $ runConnAssert $ do
void $ runMigrationSilent customConstraintMigrate
-- | Here we add another foreign key on the same column where the default one already exists. In practice, this could be a compound key with another field.
rawExecute "ALTER TABLE \"custom_constraint3\" ADD CONSTRAINT \"extra_constraint\" FOREIGN KEY(\"cc_id1\") REFERENCES \"custom_constraint1\"(\"id\")" []
-- | This is where the error is thrown in `getColumn`
void $ getMigration customConstraintMigrate
pure ()
| paul-rouse/persistent | persistent-postgresql/test/CustomConstraintTest.hs | mit | 3,160 | 0 | 17 | 990 | 278 | 148 | 130 | 46 | 1 |
{- DATX02-17-26, automated assessment of imperative programs.
- Copyright, 2017, see AUTHORS.md.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
{-# LANGUAGE
TupleSections
, FlexibleInstances
, MultiParamTypeClasses
#-}
-- | Unconsing lists an arbitrarily many times.
module Class.Product.Uncons where
import Data.List (uncons)
import Control.Arrow (first)
import Control.Monad ((>=>))
import Class.Product.HPair
import Class.Product.Flatten
--------------------------------------------------------------------------------
-- Classes:
--------------------------------------------------------------------------------
-- | Uncons of a list to an arbitrarily many pairs associating to the left.
-- Uses an inductive definition based on the "previous" instance of the class.
--
-- Unconsing many elements is a all or nothing proposition,
-- if the list is to small to get p back, you get Nothing.
class UnconsL p e where
-- | uncons an arbitrary many times, associating to the left.
unconsL :: [e] -> Maybe ( p, [e])
-- | uncons, but with the list passed in snd.
-- We could add a constraint: UnconsL z e to enforce the induction.
-- But not doing so adds power and let's the function
-- be used for other purposes.
unconsLZ :: (z, [e]) -> Maybe ((z, p), [e])
unconsLZ (z, xs) = first (z,) <$> unconsL xs
-- | Unconses a list according to UnconsL and then flattens the product.
unconsF :: (HFlatten p c, UnconsL p e) => [e] -> Maybe (c, [e])
unconsF = unconsL >=> pure . first hflatten
--------------------------------------------------------------------------------
-- Instances:
--------------------------------------------------------------------------------
instance UnconsL (L0 a) a where unconsL = pure . ((),)
instance UnconsL (L1 a) a where unconsL = uncons
instance UnconsL (L2 a) a where unconsL = unconsL >=> unconsLZ
instance UnconsL (L3 a) a where unconsL = unconsL >=> unconsLZ
instance UnconsL (L4 a) a where unconsL = unconsL >=> unconsLZ
instance UnconsL (L5 a) a where unconsL = unconsL >=> unconsLZ
instance UnconsL (L6 a) a where unconsL = unconsL >=> unconsLZ
instance UnconsL (L7 a) a where unconsL = unconsL >=> unconsLZ
instance UnconsL (L8 a) a where unconsL = unconsL >=> unconsLZ
instance UnconsL (L9 a) a where unconsL = unconsL >=> unconsLZ
instance UnconsL (L10 a) a where unconsL = unconsL >=> unconsLZ | DATX02-17-26/DATX02-17-26 | libsrc/Class/Product/Uncons.hs | gpl-2.0 | 3,063 | 0 | 10 | 541 | 506 | 286 | 220 | -1 | -1 |
{-|
Description : Data structures that represent models of temporal logic.
Maintainer : Guilherme G. Azzi <[email protected]>
Stability : provisional
-}
{-# LANGUAGE TypeFamilies #-}
module Logic.Model
(
-- * Kripke structures
KripkeStructure(..)
, State(..)
, Transition(..)
-- ** Looking up states
, stateIds
, lookupState
, getState
-- ** Looking up transitions
, transitionIds
, lookupTransition
, getTransition
-- ** Lookup by adjacency
, nextStates
, precedes
, prevStates
, follows
-- * Utilities for labeled elements
, Element(..)
, findById
) where
import Data.Maybe
-- | A Kripke structure is composed of a list of states and a list of
-- transitions between such states. States are labeled with the atomic
-- propositions that hold in it.
--
-- This particular kind of labeled transition system may be used as a model
-- for temporal logics. In particular, it may be used for model checking.
--
-- This structure is polymorphic on the type of atomic propositions.
data KripkeStructure a = KripkeStructure
{ states :: [State a] -- ^ List of labeled states of the Kripke structure
, transitions :: [Transition a] -- ^ List of transitions of the Kripke structure
}
deriving (Show, Read, Eq)
-- | A state contains its unique identifier and a list of atomic
-- propositions that hold in it.
data State a
= State Int [a]
deriving (Show, Read, Eq)
-- | A transition contains the identifiers of the source and target states.
data Transition a = Transition
{ transitionId :: Int
, source :: Int
, target :: Int
, transitionPayload :: [a]
}
deriving (Show, Read, Eq)
-- | List of all state IDs from a given Kripke structure
stateIds :: KripkeStructure a -> [Int]
stateIds =
map elementId . states
-- | Finds the state with given ID in the given Kripke structure
lookupState :: Int -> KripkeStructure a -> Maybe (State a)
lookupState i =
findById i . states
-- | Gets the state with given ID in the given Kripke structure, __fails if there is none__.
getState :: Int -> KripkeStructure a -> State a
getState i =
fromJust . lookupState i
-- | List of all transition IDs on a given Kripke structure
transitionIds :: KripkeStructure a -> [Int]
transitionIds =
map elementId . transitions
-- | Finds the transition with given ID in the given Kripke structure.
lookupTransition :: Int -> KripkeStructure a -> Maybe (Transition a)
lookupTransition i =
findById i . transitions
-- | Gets the transition with given ID in the given Kripke structure, __fails if there is none__.
getTransition :: Int -> KripkeStructure a -> Transition a
getTransition i =
fromJust . lookupTransition i
-- | Obtains the IDs of the states that are reachable by a single transition
-- from the state with given ID.
nextStates :: KripkeStructure a -> Int -> [Int]
nextStates (KripkeStructure _ transitions) state =
map target $ filter (\t -> source t == state) transitions
-- | Tests if the first given state is reachable from the second by a single transition
follows :: KripkeStructure a -> Int -> Int -> Bool
follows ts s1 s2 =
s1 `elem` nextStates ts s2
-- | Obtains the IDs of the states from which the given state is reachable by a single transition.
prevStates :: KripkeStructure a -> Int -> [Int]
prevStates (KripkeStructure _ transitions) state =
map source $ filter (\t -> target t == state) transitions
-- | Tests if the second given state is reachable from the first by a single transition
precedes :: KripkeStructure a -> Int -> Int -> Bool
precedes ts s1 s2 =
s1 `elem` prevStates ts s2
-- | Type class for elements that have a numeric identifier and a list of associated values.
class Element e where
-- | Type of associated values.
type Payload e :: *
-- | Obtain the numeric identifier of an element.
elementId :: e -> Int
-- | Obtain the associated values of an element.
values :: e -> [Payload e]
instance Element (State a) where
type Payload (State a) = a
elementId (State i _) = i
values (State _ v) = v
instance Element (Transition a) where
type Payload (Transition a) = a
elementId = transitionId
values = transitionPayload
-- | Given a list of elements, find the element with the given identifier.
findById :: Element a => Int -> [a] -> Maybe a
findById i elems =
listToMaybe $ filter (\e -> elementId e == i) elems
| rodrigo-machado/verigraph | src/library/Logic/Model.hs | gpl-3.0 | 4,417 | 0 | 10 | 954 | 857 | 473 | 384 | 77 | 1 |
module Minimal00001 where
class HasFoo a where
{-# MINIMAL foo #-}
foo :: a -> String
bar :: a -> String
class HasFoo' a where
foo' :: a -> String
{-# MINIMAL foo' #-}
bar' :: a -> String
class HasFoo'' a where
foo'' :: a -> String
bar'' :: a -> String
{-# MINIMAL foo'' #-}
| carymrobbins/intellij-haskforce | tests/gold/parser/Minimal00001.hs | apache-2.0 | 314 | 0 | 7 | 96 | 88 | 48 | 40 | 13 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.