code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
module Main where
import System.Environment
import WoofParse
import WoofToBC
import IO
main :: IO ()
main = do s <- hGetContents stdin
ast <- return $ readAST s
case ast of
ASTNull errMsg -> do putStr errMsg
otherwise -> emitBC ast
|
aemoncannon/woof
|
compiler/woof_main.hs
|
Haskell
|
mit
| 295
|
{-# LANGUAGE OverloadedStrings #-}
{-|
Controls host muting in Datadog.
-}
module Network.Datadog.Host
( muteHost
, unmuteHost
) where
import Control.Monad (void)
import Data.Aeson
import Data.Text (Text, unpack)
import Data.Time.Clock
import Data.Time.Clock.POSIX
import Network.HTTP.Types
import Network.Datadog.Internal
muteHost :: Environment -> Text -> Maybe UTCTime -> Bool -> IO ()
-- ^ Do not allow alerts to trigger on a specific host
muteHost env hostname mtime override =
let path = "host/" ++ unpack hostname ++ "/mute"
q = [("override", "true") | override]
body = object $
prependMaybe (\a -> "end" .= (ceiling (utcTimeToPOSIXSeconds a) :: Integer)) mtime $
prependBool override ("override" .= True)
["hostname" .= hostname]
in void $ datadogHttp env path q POST $ Just $ encode body
unmuteHost :: Environment -> Text -> IO ()
-- ^ Allow alerts to trigger on a specific host
unmuteHost env hostname =
let path = "host/" ++ unpack hostname ++ "/unmute"
body = object ["hostname" .= hostname]
in void $ datadogHttp env path [] POST $ Just $ encode body
|
iand675/datadog
|
src/Network/Datadog/Host.hs
|
Haskell
|
mit
| 1,139
|
{-# LANGUAGE NoImplicitPrelude, DeriveFunctor #-}
module IHaskell.Flags (
IHaskellMode(..),
Argument(..),
Args(..),
LhsStyle(..),
NotebookFormat(..),
lhsStyleBird,
parseFlags,
help,
) where
import IHaskellPrelude
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as CBS
import System.Console.CmdArgs.Explicit
import System.Console.CmdArgs.Text
import Data.List (findIndex)
import IHaskell.Types
-- Command line arguments to IHaskell. A set of arguments is annotated with the mode being invoked.
data Args = Args IHaskellMode [Argument]
deriving Show
data Argument = ConfFile String -- ^ A file with commands to load at startup.
| OverwriteFiles -- ^ Present when output should overwrite existing files.
| GhcLibDir String -- ^ Where to find the GHC libraries.
| KernelDebug -- ^ Spew debugging output from the kernel.
| Help -- ^ Display help text.
| ConvertFrom String
| ConvertTo String
| ConvertFromFormat NotebookFormat
| ConvertToFormat NotebookFormat
| ConvertLhsStyle (LhsStyle String)
| KernelspecInstallPrefix String
deriving (Eq, Show)
data LhsStyle string =
LhsStyle
{ lhsCodePrefix :: string -- ^ @>@
, lhsOutputPrefix :: string -- ^ @<<@
, lhsBeginCode :: string -- ^ @\\begin{code}@
, lhsEndCode :: string -- ^ @\\end{code}@
, lhsBeginOutput :: string -- ^ @\\begin{verbatim}@
, lhsEndOutput :: string -- ^ @\\end{verbatim}@
}
deriving (Eq, Functor, Show)
data NotebookFormat = LhsMarkdown
| IpynbFile
deriving (Eq, Show)
-- Which mode IHaskell is being invoked in.
data IHaskellMode = ShowHelp String
| InstallKernelSpec
| ConvertLhs
| Kernel (Maybe String)
deriving (Eq, Show)
-- | Given a list of command-line arguments, return the IHaskell mode and arguments to process.
parseFlags :: [String] -> Either String Args
parseFlags flags =
let modeIndex = findIndex (`elem` modeFlags) flags
in case modeIndex of
Nothing ->
-- Treat no mode as 'console'.
if "--help" `elem` flags
then Left $ showText (Wrap 100) $ helpText [] HelpFormatAll ihaskellArgs
else process ihaskellArgs flags
Just 0 -> process ihaskellArgs flags
Just idx ->
-- If mode not first, move it to be first.
let (start, first:end) = splitAt idx flags
in process ihaskellArgs $ first : start ++ end
where
modeFlags = concatMap modeNames allModes
allModes :: [Mode Args]
allModes = [installKernelSpec, kernel, convert]
-- | Get help text for a given IHaskell ode.
help :: IHaskellMode -> String
help mode = showText (Wrap 100) $ helpText [] HelpFormatAll $ chooseMode mode
where
chooseMode InstallKernelSpec = installKernelSpec
chooseMode (Kernel _) = kernel
chooseMode ConvertLhs = convert
ghcLibFlag :: Flag Args
ghcLibFlag = flagReq ["ghclib", "l"] (store GhcLibDir) "<path>" "Library directory for GHC."
kernelDebugFlag :: Flag Args
kernelDebugFlag = flagNone ["debug"] addDebug "Print debugging output from the kernel."
where
addDebug (Args mode prev) = Args mode (KernelDebug : prev)
confFlag :: Flag Args
confFlag = flagReq ["conf", "c"] (store ConfFile) "<rc.hs>"
"File with commands to execute at start; replaces ~/.ihaskell/rc.hs."
installPrefixFlag :: Flag Args
installPrefixFlag = flagReq ["prefix"] (store KernelspecInstallPrefix) "<install-dir>"
"Installation prefix for kernelspec (see Jupyter's --prefix option)"
helpFlag = flagHelpSimple (add Help)
add flag (Args mode flags) = Args mode $ flag : flags
store :: (String -> Argument) -> String -> Args -> Either String Args
store constructor str (Args mode prev) = Right $ Args mode $ constructor str : prev
installKernelSpec :: Mode Args
installKernelSpec =
mode "install" (Args InstallKernelSpec []) "Install the Jupyter kernelspec." noArgs
[ghcLibFlag, kernelDebugFlag, confFlag, installPrefixFlag, helpFlag]
kernel :: Mode Args
kernel = mode "kernel" (Args (Kernel Nothing) []) "Invoke the IHaskell kernel." kernelArg
[ghcLibFlag, kernelDebugFlag, confFlag]
where
kernelArg = flagArg update "<json-kernel-file>"
update filename (Args _ flags) = Right $ Args (Kernel $ Just filename) flags
convert :: Mode Args
convert = mode "convert" (Args ConvertLhs []) description unnamedArg convertFlags
where
description = "Convert between Literate Haskell (*.lhs) and Ipython notebooks (*.ipynb)."
convertFlags = [ flagReq ["input", "i"] (store ConvertFrom) "<file>" "File to read."
, flagReq ["output", "o"] (store ConvertTo) "<file>" "File to write."
, flagReq ["from", "f"] (storeFormat ConvertFromFormat) "lhs|ipynb"
"Format of the file to read."
, flagReq ["to", "t"] (storeFormat ConvertToFormat) "lhs|ipynb"
"Format of the file to write."
, flagNone ["force"] consForce "Overwrite existing files with output."
, flagReq ["style", "s"] storeLhs "bird|tex"
"Type of markup used for the literate haskell file"
, flagNone ["bird"] (consStyle lhsStyleBird) "Literate haskell uses >"
, flagNone ["tex"] (consStyle lhsStyleTex) "Literate haskell uses \\begin{code}"
, helpFlag
]
consForce (Args mode prev) = Args mode (OverwriteFiles : prev)
unnamedArg = Arg (store ConvertFrom) "<file>" False
consStyle style (Args mode prev) = Args mode (ConvertLhsStyle style : prev)
storeFormat constructor str (Args mode prev) =
case T.toLower (T.pack str) of
"lhs" -> Right $ Args mode $ constructor LhsMarkdown : prev
"ipynb" -> Right $ Args mode $ constructor IpynbFile : prev
_ -> Left $ "Unknown format requested: " ++ str
storeLhs str previousArgs =
case T.toLower (T.pack str) of
"bird" -> success lhsStyleBird
"tex" -> success lhsStyleTex
_ -> Left $ "Unknown lhs style: " ++ str
where
success lhsStyle = Right $ consStyle lhsStyle previousArgs
lhsStyleBird, lhsStyleTex :: LhsStyle String
lhsStyleBird = LhsStyle "> " "\n<< " "" "" "" ""
lhsStyleTex = LhsStyle "" "" "\\begin{code}" "\\end{code}" "\\begin{verbatim}" "\\end{verbatim}"
ihaskellArgs :: Mode Args
ihaskellArgs =
let descr = "Haskell for Interactive Computing."
helpStr = showText (Wrap 100) $ helpText [] HelpFormatAll ihaskellArgs
onlyHelp = [flagHelpSimple (add Help)]
noMode = mode "IHaskell" (Args (ShowHelp helpStr) []) descr noArgs onlyHelp
in noMode { modeGroupModes = toGroup allModes }
where
add flag (Args mode flags) = Args mode $ flag : flags
noArgs = flagArg unexpected ""
where
unexpected a = error $ "Unexpected argument: " ++ a
|
beni55/IHaskell
|
src/IHaskell/Flags.hs
|
Haskell
|
mit
| 7,280
|
module Git.Sanity.Internal where
import Data.Machine
-- TODO Contribute to machine?
slide :: Process a (a, a)
slide = f Nothing where
f Nothing = await (\x -> f $ Just x)
f (Just x) = await (\y -> machine $ Yield (x, y) $ f $ Just y)
await f = machine $ Await f Refl stopped
machine = MachineT . return
|
aloiscochard/git-sanity
|
src/Git/Sanity/Internal.hs
|
Haskell
|
apache-2.0
| 316
|
{- | A BSON document is a JSON-like object with a standard binary encoding defined at bsonspec.org. This implements version 1.0 of that spec.
Use the GHC language extension /OverloadedStrings/ to automatically convert String literals to UString (UTF8) -}
{-# LANGUAGE OverloadedStrings, TypeSynonymInstances, FlexibleInstances, DeriveDataTypeable, RankNTypes, OverlappingInstances, IncoherentInstances, ScopedTypeVariables, ForeignFunctionInterface, BangPatterns, CPP #-}
module Data.Bson (
-- * UTF-8 String
module Data.UString,
-- * Document
Document, look, lookup, valueAt, at, include, exclude, merge,
-- * Field
Field(..), (=:), (=?),
Label,
-- * Value
Value(..), Val(..), fval, cast, typed, typeOfVal,
-- * Special Bson value types
Binary(..), Function(..), UUID(..), MD5(..), UserDefined(..),
Regex(..), Javascript(..), Symbol(..), MongoStamp(..), MinMaxKey(..),
-- ** ObjectId
ObjectId(..), timestamp, genObjectId
#ifdef TEST
, composite
, roundTo
#endif
) where
import Prelude hiding (lookup)
import Control.Applicative ((<$>), (<*>))
import Data.Typeable hiding (cast)
import Data.Int
import Data.Word
import Data.UString (UString, u, unpack) -- plus Show and IsString instances
import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX
import Data.Time.Format () -- for Show and Read instances of UTCTime
import Data.List (find, findIndex)
import Data.Bits (shift, (.|.))
import qualified Data.ByteString as BS (ByteString, unpack, take)
import qualified Data.ByteString.Char8 as BSC (pack)
import qualified Crypto.Hash.MD5 as MD5 (hash)
import Numeric (readHex, showHex)
import Network.BSD (getHostName)
import System.IO.Unsafe (unsafePerformIO)
import Data.IORef
import Data.Maybe (maybeToList, mapMaybe)
import Control.Monad.Identity
import qualified Text.ParserCombinators.ReadP as R
import qualified Text.ParserCombinators.ReadPrec as R (lift, readS_to_Prec)
import Text.Read (Read(..))
getProcessID :: IO Int
-- ^ Get the current process id.
getProcessID = c_getpid
foreign import ccall unsafe "getpid"
c_getpid :: IO Int
roundTo :: (RealFrac a) => a -> a -> a
-- ^ Round second number to nearest multiple of first number. Eg: roundTo (1/1000) 0.12345 = 0.123
roundTo mult n = fromIntegral (round (n / mult)) * mult
showHexLen :: (Integral n) => Int -> n -> ShowS
-- ^ showHex of n padded with leading zeros if necessary to fill d digits
showHexLen d n = showString (replicate (d - sigDigits n) '0') . showHex n where
sigDigits 0 = 1
sigDigits n' = truncate (logBase 16 $ fromIntegral n') + 1
-- * Document
type Document = [Field]
-- ^ A BSON document is a list of 'Field's
look :: (Monad m) => Label -> Document -> m Value
-- ^ Value of field in document, or fail (Nothing) if field not found
look k doc = maybe notFound (return . value) (find ((k ==) . label) doc) where
notFound = fail $ "expected " ++ show k ++ " in " ++ show doc
lookup :: (Val v, Monad m) => Label -> Document -> m v
-- ^ Lookup value of field in document and cast to expected type. Fail (Nothing) if field not found or value not of expected type.
lookup k doc = cast =<< look k doc
valueAt :: Label -> Document -> Value
-- ^ Value of field in document. Error if missing.
valueAt k = runIdentity . look k
at :: forall v. (Val v) => Label -> Document -> v
-- ^ Typed value of field in document. Error if missing or wrong type.
at k doc = maybe err id (lookup k doc) where
err = error $ "expected (" ++ show k ++ " :: " ++ show (typeOf (undefined :: v)) ++ ") in " ++ show doc
include :: [Label] -> Document -> Document
-- ^ Only include fields of document in label list
include keys doc = mapMaybe (\k -> find ((k ==) . label) doc) keys
exclude :: [Label] -> Document -> Document
-- ^ Exclude fields from document in label list
exclude keys doc = filter (\(k := _) -> notElem k keys) doc
merge :: Document -> Document -> Document
-- ^ Merge documents with preference given to first one when both have the same label. I.e. for every (k := v) in first argument, if k exists in second argument then replace its value with v, otherwise add (k := v) to second argument.
merge es doc = foldl f doc es where
f doc (k := v) = case findIndex ((k ==) . label) doc of
Nothing -> doc ++ [k := v]
Just i -> let (x, _ : y) = splitAt i doc in x ++ [k := v] ++ y
-- * Field
infix 0 :=, =:, =?
data Field = (:=) {label :: !Label, value :: Value} deriving (Typeable, Eq)
-- ^ A BSON field is a named value, where the name (label) is a string and the value is a BSON 'Value'
(=:) :: (Val v) => Label -> v -> Field
-- ^ Field with given label and typed value
k =: v = k := val v
(=?) :: (Val a) => Label -> Maybe a -> Document
-- ^ If Just value then return one field document, otherwise return empty document
k =? ma = maybeToList (fmap (k =:) ma)
instance Show Field where
showsPrec d (k := v) = showParen (d > 0) $ showString (' ' : unpack k) . showString ": " . showsPrec 1 v
type Label = UString
-- ^ The name of a BSON field
-- * Value
-- | A BSON value is one of the following types of values
data Value =
Float Double |
String UString |
Doc Document |
Array [Value] |
Bin Binary |
Fun Function |
Uuid UUID |
Md5 MD5 |
UserDef UserDefined |
ObjId ObjectId |
Bool Bool |
UTC UTCTime |
Null |
RegEx Regex |
JavaScr Javascript |
Sym Symbol |
Int32 Int32 |
Int64 Int64 |
Stamp MongoStamp |
MinMax MinMaxKey
deriving (Typeable, Eq)
instance Show Value where
showsPrec d v = fval (showsPrec d) v
fval :: (forall a . (Val a) => a -> b) -> Value -> b
-- ^ Apply generic function to typed value
fval f v = case v of
Float x -> f x
String x -> f x
Doc x -> f x
Array x -> f x
Bin x -> f x
Fun x -> f x
Uuid x -> f x
Md5 x -> f x
UserDef x -> f x
ObjId x -> f x
Bool x -> f x
UTC x -> f x
Null -> f (Nothing :: Maybe Value)
RegEx x -> f x
JavaScr x -> f x
Sym x -> f x
Int32 x -> f x
Int64 x -> f x
Stamp x -> f x
MinMax x -> f x
-- * Value conversion
cast :: forall m a. (Val a, Monad m) => Value -> m a
-- ^ Convert Value to expected type, or fail (Nothing) if not of that type
cast v = maybe notType return (cast' v) where
notType = fail $ "expected " ++ show (typeOf (undefined :: a)) ++ ": " ++ show v
typed :: (Val a) => Value -> a
-- ^ Convert Value to expected type. Error if not that type.
typed = runIdentity . cast
typeOfVal :: Value -> TypeRep
-- ^ Type of typed value
typeOfVal = fval typeOf
-- ** conversion class
-- | Haskell types of this class correspond to BSON value types
class (Typeable a, Show a, Eq a) => Val a where
val :: a -> Value
cast' :: Value -> Maybe a
instance Val Double where
val = Float
cast' (Float x) = Just x
cast' (Int32 x) = Just (fromIntegral x)
cast' (Int64 x) = Just (fromIntegral x)
cast' _ = Nothing
instance Val Float where
val = Float . realToFrac
cast' (Float x) = Just (realToFrac x)
cast' (Int32 x) = Just (fromIntegral x)
cast' (Int64 x) = Just (fromIntegral x)
cast' _ = Nothing
instance Val UString where
val = String
cast' (String x) = Just x
cast' (Sym (Symbol x)) = Just x
cast' _ = Nothing
instance Val String where
val = String . u
cast' (String x) = Just (unpack x)
cast' (Sym (Symbol x)) = Just (unpack x)
cast' _ = Nothing
instance Val Document where
val = Doc
cast' (Doc x) = Just x
cast' _ = Nothing
instance Val [Value] where
val = Array
cast' (Array x) = Just x
cast' _ = Nothing
instance (Val a) => Val [a] where
val = Array . map val
cast' (Array x) = mapM cast x
cast' _ = Nothing
instance Val Binary where
val = Bin
cast' (Bin x) = Just x
cast' _ = Nothing
instance Val Function where
val = Fun
cast' (Fun x) = Just x
cast' _ = Nothing
instance Val UUID where
val = Uuid
cast' (Uuid x) = Just x
cast' _ = Nothing
instance Val MD5 where
val = Md5
cast' (Md5 x) = Just x
cast' _ = Nothing
instance Val UserDefined where
val = UserDef
cast' (UserDef x) = Just x
cast' _ = Nothing
instance Val ObjectId where
val = ObjId
cast' (ObjId x) = Just x
cast' _ = Nothing
instance Val Bool where
val = Bool
cast' (Bool x) = Just x
cast' _ = Nothing
instance Val UTCTime where
val = UTC . posixSecondsToUTCTime . roundTo (1/1000) . utcTimeToPOSIXSeconds
cast' (UTC x) = Just x
cast' _ = Nothing
instance Val POSIXTime where
val = UTC . posixSecondsToUTCTime . roundTo (1/1000)
cast' (UTC x) = Just (utcTimeToPOSIXSeconds x)
cast' _ = Nothing
instance Val (Maybe Value) where
val Nothing = Null
val (Just v) = v
cast' Null = Just Nothing
cast' v = Just (Just v)
instance (Val a) => Val (Maybe a) where
val Nothing = Null
val (Just a) = val a
cast' Null = Just Nothing
cast' v = fmap Just (cast' v)
instance Val Regex where
val = RegEx
cast' (RegEx x) = Just x
cast' _ = Nothing
instance Val Javascript where
val = JavaScr
cast' (JavaScr x) = Just x
cast' _ = Nothing
instance Val Symbol where
val = Sym
cast' (Sym x) = Just x
cast' (String x) = Just (Symbol x)
cast' _ = Nothing
instance Val Int32 where
val = Int32
cast' (Int32 x) = Just x
cast' (Int64 x) = fitInt x
cast' (Float x) = Just (round x)
cast' _ = Nothing
instance Val Int64 where
val = Int64
cast' (Int64 x) = Just x
cast' (Int32 x) = Just (fromIntegral x)
cast' (Float x) = Just (round x)
cast' _ = Nothing
instance Val Int where
val n = maybe (Int64 $ fromIntegral n) Int32 (fitInt n)
cast' (Int32 x) = Just (fromIntegral x)
cast' (Int64 x) = Just (fromEnum x)
cast' (Float x) = Just (round x)
cast' _ = Nothing
instance Val Integer where
val n = maybe (maybe err Int64 $ fitInt n) Int32 (fitInt n) where
err = error $ show n ++ " is too large for Bson Int Value"
cast' (Int32 x) = Just (fromIntegral x)
cast' (Int64 x) = Just (fromIntegral x)
cast' (Float x) = Just (round x)
cast' _ = Nothing
instance Val MongoStamp where
val = Stamp
cast' (Stamp x) = Just x
cast' _ = Nothing
instance Val MinMaxKey where
val = MinMax
cast' (MinMax x) = Just x
cast' _ = Nothing
fitInt :: forall n m. (Integral n, Integral m, Bounded m) => n -> Maybe m
-- ^ If number fits in type m then cast to m, otherwise Nothing
fitInt n = if fromIntegral (minBound :: m) <= n && n <= fromIntegral (maxBound :: m)
then Just (fromIntegral n)
else Nothing
-- * Haskell types corresponding to special Bson value types
-- ** Binary types
newtype Binary = Binary BS.ByteString deriving (Typeable, Show, Read, Eq)
newtype Function = Function BS.ByteString deriving (Typeable, Show, Read, Eq)
newtype UUID = UUID BS.ByteString deriving (Typeable, Show, Read, Eq)
newtype MD5 = MD5 BS.ByteString deriving (Typeable, Show, Read, Eq)
newtype UserDefined = UserDefined BS.ByteString deriving (Typeable, Show, Read, Eq)
-- ** Regex
data Regex = Regex UString UString deriving (Typeable, Show, Read, Eq)
-- ^ The first string is the regex pattern, the second is the regex options string. Options are identified by characters, which must be listed in alphabetical order. Valid options are *i* for case insensitive matching, *m* for multiline matching, *x* for verbose mode, *l* to make \\w, \\W, etc. locale dependent, *s* for dotall mode (\".\" matches everything), and *u* to make \\w, \\W, etc. match unicode.
-- ** Javascript
data Javascript = Javascript Document UString deriving (Typeable, Show, Eq)
-- ^ Javascript code with possibly empty environment mapping variables to values that the code may reference
-- ** Symbol
newtype Symbol = Symbol UString deriving (Typeable, Show, Read, Eq)
-- ** MongoStamp
newtype MongoStamp = MongoStamp Int64 deriving (Typeable, Show, Read, Eq)
-- ** MinMax
data MinMaxKey = MinKey | MaxKey deriving (Typeable, Show, Read, Eq)
-- ** ObjectId
data ObjectId = Oid Word32 Word64 deriving (Typeable, Eq, Ord)
-- ^ A BSON ObjectID is a 12-byte value consisting of a 4-byte timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process id, and a 3-byte counter. Note that the timestamp and counter fields must be stored big endian unlike the rest of BSON. This is because they are compared byte-by-byte and we want to ensure a mostly increasing order.
instance Show ObjectId where
showsPrec _ (Oid x y) = showHexLen 8 x . showHexLen 16 y
instance Read ObjectId where
readPrec = do
[(x, "")] <- readHex <$> R.lift (R.count 8 R.get)
y <- R.readS_to_Prec $ const readHex
return (Oid x y)
timestamp :: ObjectId -> UTCTime
-- ^ Time when objectId was created
timestamp (Oid time _) = posixSecondsToUTCTime (fromIntegral time)
genObjectId :: IO ObjectId
-- ^ Create a fresh ObjectId
genObjectId = do
time <- truncate <$> getPOSIXTime
pid <- fromIntegral <$> getProcessID
inc <- nextCount
return $ Oid time (composite machineId pid inc)
where
machineId :: Word24
machineId = unsafePerformIO (makeWord24 . BS.unpack . BS.take 3 . MD5.hash . BSC.pack <$> getHostName)
{-# NOINLINE machineId #-}
counter :: IORef Word24
counter = unsafePerformIO (newIORef 0)
{-# NOINLINE counter #-}
nextCount :: IO Word24
nextCount = atomicModifyIORef counter $ \n -> (wrap24 (n + 1), n)
composite :: Word24 -> Word16 -> Word24 -> Word64
composite mid pid inc = fromIntegral mid `shift` 40 .|. fromIntegral pid `shift` 24 .|. fromIntegral inc
type Word24 = Word32
-- ^ low 3 bytes only, high byte must be zero
wrap24 :: Word24 -> Word24
wrap24 n = n `mod` 0x1000000
makeWord24 :: [Word8] -> Word24
-- ^ Put last 3 bytes into a Word24. Expected to be called on very short list
makeWord24 = foldl (\a b -> a `shift` 8 .|. fromIntegral b) 0
{- Authors: Tony Hannan <tony@10gen.com>
Copyright 2010 10gen Inc.
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. -}
|
mongodb/bson-haskell
|
Data/Bson.hs
|
Haskell
|
apache-2.0
| 14,020
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE UndecidableInstances #-}
module Tersus.DataTypes.TError where
import Control.Exception.Base
import Data.Text
import Data.Typeable
import Prelude
import Tersus.DataTypes.TypeSynonyms
import Yesod.Handler
import GHC.Generics (Generic)
import Data.Aeson (FromJSON, ToJSON, decode, encode)
data TError =
--General errors
TheImpossibleHappened Text -- if we catch these types of errors, we ought to fix them in the code
-- Database errors
| RedisTError Text
-- From requests
| MissingParameter Text Text -- parameter name, parameter description
| TUserIdNotFound UserId
| TUserNicknameNotFound Username
| TAppIdNotFound ApplicationIdentifier
| TFileIdNotFound FileId
| TFilePathNotFound Path deriving (Eq,Show,Typeable,Generic)
instance ToJSON TError
instance Exception TError
|
kmels/tersus
|
Tersus/DataTypes/TError.hs
|
Haskell
|
bsd-2-clause
| 867
|
{-# LANGUAGE BangPatterns, PatternGuards #-}
module Data.BTree
( -- * Types
BTree
-- * Creation
, empty
, singleton
, fromList
-- * Queries
, size
, lookup
, minimumKey
-- * Insertion
, insert
, insertWith
-- * Debugging
, showBTree
) where
import Prelude hiding (lookup)
-- import qualified Prelude as P
import Data.List (foldl')
import Data.BTree.Array.Search
import Data.BTree.Internal
import qualified Data.BTree.Array as A
import qualified Data.BTree.Array.Util as A
-- | Create an empty 'BTree'
empty :: Ord k => BTree k v
empty = Leaf 0 A.empty A.empty
{-# INLINE empty #-}
-- | Create a 'BTree' holding a single element
singleton :: Ord k => k -> v -> BTree k v
singleton k v = Leaf 1 (A.singleton k) (A.singleton v)
{-# INLINE singleton #-}
-- | Create a 'BTree' from an associative list
fromList :: Ord k => [(k, v)] -> BTree k v
fromList = foldl' insert' empty
where
insert' t (k, v) = insert k v t
-- | Find the number of values in the 'BTree'
size :: BTree k v -> Int
size (Leaf s _ _) = s
size (Node _ tv _ _ ) = tv
-- | Find an element in the 'BTree'
lookup :: Ord k => k -> BTree k v -> Maybe v
lookup k = lookup'
where
lookup' (Leaf s ks vs) = fmap (A.unsafeIndex vs) (search s k ks)
lookup' (Node s _ ks cs) = searchWith found notFound s k ks
where
found i = lookup' (A.unsafeIndex cs (i + 1))
{-# INLINE found #-}
notFound i = lookup' (A.unsafeIndex cs i)
{-# INLINE notFound #-}
{-# INLINE lookup #-}
-- | Find the minimum key in a 'BTree'
minimumKey :: Ord k => BTree k v -> k
minimumKey (Leaf _ ks _) = A.unsafeIndex ks 0
minimumKey (Node _ _ _ cs) = minimumKey (A.unsafeIndex cs 0)
-- | Signals for insertion
data Insert k v = Ok !(BTree k v)
| Split !(BTree k v) !(BTree k v)
-- | Insert an element into the 'BTree'
insert :: Ord k => k -> v -> BTree k v -> BTree k v
insert = insertWith const
{-# INLINE insert #-}
-- | Insert an element into the 'BTree'
insertWith :: Ord k => (v -> v -> v) -> k -> v -> BTree k v -> BTree k v
insertWith f k v btree =
-- Insertion in the root
case insert' btree of
Ok btree' -> btree'
-- Split the root
Split l r ->
let !s = 1
!tv = size l + size r
!ks = A.singleton (minimumKey r)
!cs = A.pair l r
in Node s tv ks cs
where
-- Insertion in a leaf node
insert' (Leaf s ks vs) = searchWith found notFound s k ks
where
-- Overwrite the value
found i =
let ov = A.unsafeIndex vs i -- Do not force ov!
in Ok $ Leaf s ks (A.unsafePut s i (f ov v) vs)
-- Insert the value
notFound i
-- We have enough place, so just insert it
| s + 1 <= maxNodeSize = Ok $ Leaf
(s + 1) (A.unsafeInsert s i k ks) (A.unsafeInsert s i v vs)
-- We need to split this leaf and insert left
| i < s' =
let lks = A.unsafeInsertIn 0 s' i k ks
lvs = A.unsafeInsertIn 0 s' i v vs
rks = A.unsafeCopyRange s' s' ks
rvs = A.unsafeCopyRange s' s' vs
l = Leaf (s' + 1) lks lvs
r = Leaf s' rks rvs
in Split l r
-- We need to split this leaf and insert right
| otherwise =
let lks = A.unsafeCopyRange 0 s' ks
lvs = A.unsafeCopyRange 0 s' vs
rks = A.unsafeInsertIn s' s' (i - s') k ks
rvs = A.unsafeInsertIn s' s' (i - s') v vs
l = Leaf s' lks lvs
r = Leaf (s' + 1) rks rvs
in Split l r
where
s' = s `div` 2
-- Insertion in a parent node
insert' (Node s tv ks cs) = searchWith found notFound s k ks
where
-- Found: we continue in the right child child. We also know the size
-- cannot change (since no new key is added).
found i = case insert' (A.unsafeIndex cs (i + 1)) of
Ok c' -> Ok $ Node s tv ks (A.unsafePut (s + 1) (i + 1) c' cs)
_ -> error "Data.BTree.insert: internal error!"
-- Not found: left child. Now, it is possible that we have to split our
-- node in order to balance the tree
-- TODO: update size!
notFound i = case insert' (A.unsafeIndex cs i) of
Ok c' -> Ok $ Node s tv ks (A.unsafePut (s + 1) i c' cs)
Split l r
-- We're still good
| s + 1 <= maxNodeSize ->
let -- Key to copy
!k' = minimumKey r
!ks' = A.unsafeInsert s i k' ks
!cs' = A.unsafePutPair (s + 1) i l r cs
in Ok $ Node (s + 1) tv ks' cs'
-- We need to split this node. This should not happen often.
-- TODO: This implementation can be written using at least one
-- less copy.
| otherwise ->
let -- Create a "too large" node
!k' = minimumKey r
!ks' = A.unsafeInsert s i k' ks
!cs' = A.unsafePutPair (s + 1) i l r cs
-- Currently: number of keys: s + 1, and s + 2 children
-- s + 1 is odd, so we can drop the key in the middle
!s' = s `div` 2
-- Select the left part
!lks = A.unsafeCopyRange 0 s' ks'
!lcs = A.unsafeCopyRange 0 (s' + 1) cs'
l' = Node s' tv lks lcs
-- Select the right part
!rks = A.unsafeCopyRange (s' + 1) s' ks'
!rcs = A.unsafeCopyRange (s' + 1) (s' + 1) cs'
r' = Node s' tv rks rcs
in Split l' r'
{-# INLINE insertWith #-}
|
jaspervdj/b-tree
|
src/Data/BTree.hs
|
Haskell
|
bsd-3-clause
| 6,073
|
module HM.Normal where
import HM.Types
import HM.Monad
import Data.IORef
import Data.List( (\\) )
import Debug.Trace
import Text.PrettyPrint.HughesPJ
typecheck :: Term -> Tc Sigma
typecheck e = do { ty <- inferSigma e
; zonkType ty }
data Expected a = Infer (IORef a) | Check a
checkRho :: Term -> Rho -> Tc ()
checkRho expr ty = tcRho expr (Check ty)
inferRho :: Term -> Tc Rho
inferRho expr
= do { ref <- newTcRef (error "inferRho: empty result")
; tcRho expr (Infer ref)
; readTcRef ref }
tcRho :: Term -> Expected Rho -> Tc ()
tcRho (Lit _) exp_ty = instSigma intType exp_ty
tcRho (Var v) exp_ty
= do { v_sigma <- lookupVar v
; instSigma v_sigma exp_ty
}
tcRho (App fun arg) exp_ty
= do { fun_ty <- inferRho fun
; (arg_ty, res_ty) <- unifyFun fun_ty
; checkSigma arg arg_ty
; instSigma res_ty exp_ty
}
tcRho (Lam var body) (Check exp_ty)
= do { (var_ty, body_ty) <- unifyFun exp_ty
; extendVarEnv var var_ty (checkRho body body_ty)
}
tcRho (Lam var body) (Infer ref)
= do { var_ty <- newTyVarTy
; body_ty <- extendVarEnv var var_ty (inferRho body)
; writeTcRef ref (var_ty --> body_ty)
}
tcRho (Let var rhs body) exp_ty
= do { var_ty <- inferSigma rhs
; traceM $ ("tcRho Let var_ty = " ++ show var_ty)
; extendVarEnv var var_ty (tcRho body exp_ty)
}
tcRho (Ann body ann_ty) exp_ty
= do { checkSigma body ann_ty
; instSigma ann_ty exp_ty
}
tcRho (ALam var var_ty body) exp_ty = fail "annotated lambda is not supported in hindley milner"
inferSigma :: Term -> Tc Sigma
inferSigma e
= do { exp_ty <- inferRho e
; traceM $ ("inferRho result = " ++ show exp_ty)
; env_tys <- getEnvTypes
; env_tvs <- getMetaTyVars env_tys
; res_tvs <- getMetaTyVars [exp_ty]
; let forall_tvs = res_tvs \\ env_tvs
; quantify forall_tvs exp_ty }
checkSigma :: Term -> Sigma -> Tc ()
checkSigma expr sigma
= do { (skol_tvs, rho) <- shallowskol sigma
; checkRho expr rho
; env_tys <- getEnvTypes
; esc_tvs <- getFreeTyVars (sigma : env_tys)
; let bad_tvs = filter (`elem` esc_tvs) skol_tvs
; check (null bad_tvs) (text "Type not polymorphic enough")
}
instSigma :: Sigma -> Expected Rho -> Tc ()
instSigma t1 (Check t2) = unify t1 t2
instSigma t1 (Infer r) = do { t1' <- instantiate t1
; writeTcRef r t1'
}
|
MnO2/hindley-milner
|
src/HM/Normal.hs
|
Haskell
|
bsd-3-clause
| 2,533
|
import Data.Function
import Data.List
import Data.Monoid
import qualified Data.Set as S
import Data.Foldable.Strict
import qualified Data.Map.Strict as M
import Control.Lens
import MinIR.CorpusStats as CS
import MinIR.TermIndex as TI
import MinIR.OrderedIndex as OI
import MinIR.UnorderedIndex as UI
import MinIR.SequentialDependence as SD
documents :: [(Int, [Int])]
documents =
[ (100, [1,2,3,4])
, (101, [1,2,3,4])
, (102, [1,3])
, (103, [1,3,5])
] ++ map (\i->(i,[10..20])) [200..30000]
main = do
let idx = foldMap' (uncurry TI.fromTerms) documents
oidx = foldMap' (uncurry $ OI.fromTerms 8) documents
cstats = foldMap' (\(doc,terms)->CS.fromDocument doc (length terms)) documents
Prelude.mapM_ (print . sortBy (flip compare `on` snd) . TI.termScore 0.1 cstats idx) [1..5]
print $ take 10 $ sortBy (flip compare `on` snd)
$ M.toList $ OI.termsScore 2 0.1 cstats oidx [1..8]
|
bgamari/minir
|
Test.hs
|
Haskell
|
bsd-3-clause
| 940
|
module Util
( untilFixed
, untilFixedBy
, untilFixedM
, mapFst
, mapSnd
, commonPrefix
, replaceOne
, replaceAll
) where
-- Yields the result of applying f until a fixed point is reached.
untilFixedBy :: (a -> a -> Bool) -> (a -> a) -> a -> a
untilFixedBy eq f x = fst . head . filter (uncurry eq) $
zip (iterate f x) (tail $ iterate f x)
untilFixed :: (Eq a) => (a -> a) -> a -> a
untilFixed = untilFixedBy (==)
-- Note that we apply until the entire "monadic environment" is fixed, not just
-- until the value in the monad is fixed.
untilFixedM :: (Eq (m a), Monad m) => (a -> m a) -> a -> m a
untilFixedM f x = untilFixed (>>=f) (return x)
-- Apply functions across 1st and 2nd in tuple
mapFst :: (a -> b) -> (a,c) -> (b,c)
mapFst f (x,y) = (f x, y)
mapSnd :: (a -> b) -> (c,a) -> (c,b)
mapSnd f (x,y) = (x, f y)
-- Find common prefix of list of lists. This algorithm sucks but at least it
-- was easy to write.
commonPrefix :: (Eq a) => [[a]] -> [a]
commonPrefix [] = []
commonPrefix ([]:_) = []
commonPrefix xss@((x:_):_) = if and $ map (\xs' ->
not (null xs') && x == head xs')
xss
then x:(commonPrefix $ map tail xss)
else []
-- Find / replace elements in a list
replaceOne :: (Eq a) => a -> a -> [a] -> [a]
replaceOne _ _ [] = []
replaceOne x x' (y:ys) | x == y = (x':ys)
| otherwise = (y:replaceOne x x' ys)
replaceAll :: (Eq a) => a -> a -> [a] -> [a]
replaceAll x x' = map f
where f y | x == y = x'
f y | otherwise = y
replaceAllL :: (Eq a) => a -> [a] -> [a] -> [a]
replaceAllL x xs' = concat . map f
where f y | x == y = xs'
f y | otherwise = [y]
|
akerber47/train
|
Util.hs
|
Haskell
|
bsd-3-clause
| 1,785
|
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -F -pgmF htfpp #-}
-- | test documents
module Web.MangoPay.DocumentsTest where
import Web.MangoPay
import Web.MangoPay.TestUtils
import Data.Default
import Test.Framework
import Test.HUnit (Assertion)
import Data.Maybe (isJust, fromJust)
import qualified Data.ByteString as BS
-- | test document API
test_Document :: Assertion
test_Document = do
usL<-testMP $ listUsers def (Just $ Pagination 1 1)
assertEqual 1 (length $ plData usL)
let uid=urId $ head $ plData usL
euser <- testMP $ getUser uid
let d=Document Nothing Nothing Nothing IDENTITY_PROOF (Just CREATED) Nothing Nothing
testEventTypes [KYC_CREATED,KYC_VALIDATION_ASKED] $ do
d2<-testMP $ createDocument uid d
assertBool (isJust $ dId d2)
assertBool (isJust $ dCreationDate d2)
assertEqual IDENTITY_PROOF (dType d2)
assertEqual Light $ getKindOfAuthentication euser [d2]
tf<-BS.readFile "data/test.jpg"
-- document has to be in CREATED status
testMP $ createPage uid (fromJust $ dId d2) tf
tf2<-BS.readFile "data/test.png"
testMP $ createPage uid (fromJust $ dId d2) tf2
d3<-testMP $ modifyDocument uid d2{dStatus=Just VALIDATION_ASKED}
assertEqual (Just VALIDATION_ASKED) (dStatus d3)
assertEqual (dId d2) (dId d3)
d4<-testMP $ fetchDocument uid (fromJust $ dId d2)
assertEqual (Just VALIDATION_ASKED) (dStatus d4)
docsUser <- testMP $ getAll $ listDocuments uid def def
assertBool $ d3 `elem` docsUser
docsUserI <- testMP $ getAll $ listDocuments uid def{dfType=Just IDENTITY_PROOF} def
assertBool $ d3 `elem` docsUserI
docsUserA <- testMP $ getAll $ listDocuments uid def{dfType=Just ADDRESS_PROOF} def
assertBool $ not $ d3 `elem` docsUserA
docsAll <- testMP $ getAll $ listAllDocuments def def
assertBool $ d3 `elem` docsAll
docsAllI <- testMP $ getAll $ listAllDocuments def{dfType=Just IDENTITY_PROOF} def
assertBool $ d3 `elem` docsAllI
docsAllA <- testMP $ getAll $ listAllDocuments def{dfType=Just ADDRESS_PROOF} def
assertBool $ not $ d3 `elem` docsAllA
return $ dId d2
-- | test type of authentication
test_KindOfAuthentication :: Assertion
test_KindOfAuthentication = do
usL<-testMP $ listUsers def (Just $ Pagination 1 1)
assertEqual 1 (length $ plData usL)
let uid=urId $ head $ plData usL
euser <- testMP $ getUser uid
assertEqual Light $ getKindOfAuthentication euser []
|
prowdsponsor/mangopay
|
mangopay/test/Web/MangoPay/DocumentsTest.hs
|
Haskell
|
bsd-3-clause
| 2,439
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
-- | This module provides some functions to use Linux
-- terminals
module Haskus.System.Linux.Terminal
( stdin
, stdout
, stderr
, writeStr
, writeStrLn
, readChar
)
where
import Haskus.System.Linux.ErrorCode
import Haskus.System.Linux.FileSystem.ReadWrite
import Haskus.System.Linux.Handle
import Haskus.Utils.Flow
import Haskus.Format.Text
import Haskus.Format.String
import Haskus.Format.Binary.Buffer
-- | Standard input (by convention)
stdin :: Handle
stdin = Handle 0
-- | Standard output (by convention)
stdout :: Handle
stdout = Handle 1
-- | Standard error output (by convention)
stderr :: Handle
stderr = Handle 2
-- | Write a String in the given file descriptor
writeStr :: MonadInIO m => Handle -> String -> FlowT '[ErrorCode] m ()
writeStr fd = writeBuffer fd . stringEncodeUtf8
-- | Write a String with a newline character in the given
-- file descriptor
writeStrLn :: MonadInIO m => Handle -> String -> FlowT '[ErrorCode] m ()
writeStrLn fd = writeBuffer fd . stringEncodeUtf8 . (++ "\n")
-- | Read a single character
--
-- Warning: only the first byte of multi-byte characters (e.g. utf8) will be
-- read
readChar :: MonadInIO m => Handle -> FlowT ReadErrors' m Char
readChar fd = handleReadBuffer fd Nothing 1
||> (castCCharToChar . bufferPeekStorable)
|
hsyl20/ViperVM
|
haskus-system/src/lib/Haskus/System/Linux/Terminal.hs
|
Haskell
|
bsd-3-clause
| 1,363
|
module Main where
import Control.Monad
import System.Exit (exitFailure)
import System.Environment
import L3.ParL
import L3.ErrM
import L3ToL2.Compile
import L2.PrintL
main :: IO ()
main = do
args <- getArgs
when (length args /= 1) $ do
putStrLn "usage: filename"
exitFailure
ts <- liftM myLexer $ readFile (head args)
case pProgram ts of
Bad s -> do
putStrLn "\nParse Failed...\n"
putStrLn "Tokens:"
print ts
putStrLn s
Ok prog -> putStrLn . printTree . translate $ prog
|
mhuesch/scheme_compiler
|
src/L3ToL2/Main.hs
|
Haskell
|
bsd-3-clause
| 561
|
{-# Language BangPatterns,FlexibleContexts,TypeFamilies #-}
module Numeric.Utilities.GaussElimination {-(
-- gaussElem
)-} where
import Control.Arrow((&&&))
import Data.Array.Repa as R
import Data.Array.Repa.Unsafe as R
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
-- ================> Types <=====================
type Augmented = Array U DIM2 Double
type Coefficients = Array U DIM2 Double
type Constants = Array U DIM1 Double
type Triangular = V.Vector (U.Vector Double)
data GaussElem = GaussElem { getCoeff :: !Coefficients
,getConst :: !Constants
} deriving Show
-- ===========================> GAUSS ELIMINATION <====================
gaussElem :: Monad m => Coefficients -> Constants -> m (Maybe (Array U DIM1 Double))
gaussElem mtx vec = eliminationPhase mtx vec (Z:.0:.0) >>= \gauss ->
case gauss of
Nothing -> return Nothing
Just gauss -> return . Just $ substitution gauss
{-gaussElem :: Monad m => Coefficients -> Constants -> m (Maybe (Array U DIM1 Double))
gaussElem mtx vec = eliminationPhase mtx vec (Z:.0:.0) >>= \gauss ->
return $ substitution gauss -}
-- ============> Elimination Phase <==============
eliminationCoeff :: Monad m => Coefficients -> DIM2 -> m Coefficients
eliminationCoeff !mtx pivot@(Z:. k :. _k) = computeUnboxedP . fromFunction (extent mtx) $
(\sh@(Z:.i:.j) ->
if i > k && j >= k
then let alpha = (mtx ! (Z:. i:. k)) / (mtx ! pivot)
in (mtx ! sh) - alpha*(mtx ! (Z:. k :. j))
else mtx ! sh)
eliminationConst :: Monad m => Coefficients -> Constants -> DIM2 -> m Constants
eliminationConst !mtx !vec pivot@(Z:. k :. _k) =
computeUnboxedP . fromFunction (extent vec) $
(\sh@(Z:. i) ->
if (i<=k) then vec ! sh
else
let alpha = (mtx ! (Z:. i:. k)) / (mtx ! pivot)
in (vec ! sh) - alpha*(vec ! (Z:. k)) )
eliminationPhase :: Monad m => Coefficients -> Constants -> DIM2 -> m (Maybe GaussElem)
eliminationPhase !mtx !vec sh@(Z:. n:. _n)
| (extent mtx) > sh = eliminationCoeff mtx sh >>= \mtx2 ->
eliminationConst mtx vec sh >>= \vec2 ->
eliminationPhase mtx2 vec2 (Z:. (n+1):. (n+1))
| otherwise = return $ if (not $ linearIndependence mtx) || anyInfinite
then Nothing
else Just $ GaussElem mtx vec
where (Z:. dim:. _dim) = extent mtx
anyInfinite = U.any ( \x -> isNaN x || isInfinite x) $ R.toUnboxed mtx
linearIndependence :: Coefficients -> Bool
linearIndependence mtx = U.foldl1' (&&) . U.map genVec $ U.generate dim id
where genVec k = U.any (\x -> abs x > 1e-6) . toUnboxed . computeUnboxedS $ slice mtx (Any :. k :. All)
(Z:.dim:._) = R.extent mtx
-- ==============> Substitution Phase <===============
substitution :: GaussElem -> Array U DIM1 Double
substitution !ge = R.fromUnboxed (Z :. dim) $
V.foldr (backTracking cs) U.empty tvs
where (mtx,cs) = getCoeff &&& getConst $ ge
tvs = toTriang (R.toUnboxed mtx) dim
(Z:.dim) = extent cs
backTracking :: Array U DIM1 Double -> U.Vector Double -> U.Vector Double -> U.Vector Double
backTracking cs v acc =
let b = cs ! (Z:.k)
k = n-m
(Z:.n) = extent cs
m = U.length v
akk = U.head v
sumAx = U.sum $ U.zipWith (*) acc (U.tail v)
val = (b - sumAx) * recip akk
in val `U.cons` acc
toTriang :: U.Vector Double -> Int -> V.Vector (U.Vector Double)
toTriang !vecU !dim = V.generate dim (\n -> U.slice (n*(dim+1)) (dim-n) vecU)
q1 :: U.Unbox Double => Array U DIM2 Double
q1 = R.fromListUnboxed (Z:. 3 :. 3 :: DIM2) [4.0, -2.0, 1.0, -2.0, 4.0, -2.0, 1.0, -2.0, 4.0]
v1 :: U.Unbox Double => Array U DIM1 Double
v1 = R.fromListUnboxed (Z:. 3 :: DIM1) [11.0,-16.0,17.0]
|
felipeZ/OptimizationAlgorithms
|
Numeric/Utilities/GaussElimination.hs
|
Haskell
|
bsd-3-clause
| 4,258
|
{-# LANGUAGE TypeFamilies #-}
module Network.TwoPhase.STM
where
import Control.Applicative
import Control.Concurrent.STM
import Data.ByteString
import Data.Map (Map)
import qualified Data.Map as M
import Network.TwoPhase
type Message = (Addr STMNetwork, ByteString, Addr STMNetwork)
data STMNetwork = STMNetwork (ByteString) (Map ByteString (TChan Message)) (Storage STMNetwork)
instance TPNetwork STMNetwork where
type Addr STMNetwork = ByteString
send (STMNetwork from s _) m to =
case M.lookup to s of
Nothing -> return ()
Just x -> atomically $ writeTChan x (from,m,to)
instance TPStorage STMNetwork where
getStore (STMNetwork _ _ s) = s
mkNetwork :: ByteString -> [ByteString] -> IO STMNetwork
mkNetwork n bs = STMNetwork n <$> (M.fromList <$> mapM (\x -> (,) x <$> newTChanIO) (n:bs))
<*> mkStorage
cloneNetwork :: STMNetwork -> ByteString -> IO STMNetwork
cloneNetwork (STMNetwork _ a _) f = STMNetwork f a <$> mkStorage
extractCh :: STMNetwork -> ByteString -> Maybe (TChan Message)
extractCh (STMNetwork _ a _) b = M.lookup b a
|
qnikst/2pc-haskell
|
Network/TwoPhase/STM.hs
|
Haskell
|
bsd-3-clause
| 1,104
|
{-# LANGUAGE RecordWildCards #-}
module HLint(hlint, Suggestion, suggestionLocation, suggestionSeverity, Severity(..)) where
import Control.Applicative
import Control.Monad
import System.Console.CmdArgs.Verbosity
import Data.List
import System.Exit
import CmdLine
import Settings
import Report
import Idea
import Apply
import Test.Standard
import Grep
import Test.Proof
import Util
import Parallel
import HSE.All
-- | A suggestion - the @Show@ instance is of particular use.
newtype Suggestion = Suggestion {fromSuggestion :: Idea}
deriving (Eq,Ord)
instance Show Suggestion where
show = show . fromSuggestion
-- | From a suggestion, extract the file location it refers to.
suggestionLocation :: Suggestion -> SrcLoc
suggestionLocation = getPointLoc . ideaSpan . fromSuggestion
-- | From a suggestion, determine how severe it is.
suggestionSeverity :: Suggestion -> Severity
suggestionSeverity = ideaSeverity . fromSuggestion
-- | This function takes a list of command line arguments, and returns the given suggestions.
-- To see a list of arguments type @hlint --help@ at the console.
-- This function writes to the stdout/stderr streams, unless @--quiet@ is specified.
--
-- As an example:
--
-- > do hints <- hlint ["src", "--ignore=Use map","--quiet"]
-- > when (length hints > 3) $ error "Too many hints!"
hlint :: [String] -> IO [Suggestion]
hlint args = do
cmd <- getCmd args
case cmd of
CmdMain{} -> hlintMain cmd
CmdGrep{} -> hlintGrep cmd >> return []
CmdHSE{} -> hlintHSE cmd >> return []
CmdTest{} -> hlintTest cmd >> return []
hlintHSE :: Cmd -> IO ()
hlintHSE CmdHSE{..} = do
v <- getVerbosity
forM_ cmdFiles $ \x -> do
putStrLn $ "Parse result of " ++ x ++ ":"
res <- parseFile x
case res of
x@ParseFailed{} -> print x
ParseOk m -> case v of
Loud -> print m
Quiet -> print $ prettyPrint m
_ -> print $ fmap (const ()) m
putStrLn ""
hlintTest :: Cmd -> IO ()
hlintTest cmd@CmdTest{..} = do
if notNull cmdProof then do
files <- cmdHintFiles cmd
s <- readSettings2 cmdDataDir files []
let reps = if cmdReports == ["report.html"] then ["report.txt"] else cmdReports
mapM_ (proof reps s) cmdProof
else do
failed <- test (\args -> do errs <- hlint args; when (length errs > 0) $ exitWith $ ExitFailure 1) cmdDataDir cmdGivenHints
when (failed > 0) exitFailure
hlintGrep :: Cmd -> IO ()
hlintGrep cmd@CmdGrep{..} = do
encoding <- readEncoding cmdEncoding
let flags = parseFlagsSetExtensions (cmdExtensions cmd) $ defaultParseFlags{cppFlags=cmdCpp cmd, encoding=encoding}
if null cmdFiles then
exitWithHelp
else do
files <- concatMapM (resolveFile cmd) cmdFiles
if null files then
error "No files found"
else
runGrep cmdPattern flags files
hlintMain :: Cmd -> IO [Suggestion]
hlintMain cmd@CmdMain{..} = do
encoding <- readEncoding cmdEncoding
let flags = parseFlagsSetExtensions (cmdExtensions cmd) $ defaultParseFlags{cppFlags=cmdCpp cmd, encoding=encoding}
if null cmdFiles && notNull cmdFindHints then do
hints <- concatMapM (resolveFile cmd) cmdFindHints
mapM_ (\x -> putStrLn . fst =<< findSettings2 flags x) hints >> return []
else if null cmdFiles then
exitWithHelp
else do
files <- concatMapM (resolveFile cmd) cmdFiles
if null files then
error "No files found"
else
runHints cmd{cmdFiles=files} flags
readAllSettings :: Cmd -> ParseFlags -> IO [Setting]
readAllSettings cmd@CmdMain{..} flags = do
files <- cmdHintFiles cmd
settings1 <- readSettings2 cmdDataDir files cmdWithHints
settings2 <- concatMapM (fmap snd . findSettings2 flags) cmdFindHints
settings3 <- return [SettingClassify $ Classify Ignore x "" "" | x <- cmdIgnore]
return $ settings1 ++ settings2 ++ settings3
runHints :: Cmd -> ParseFlags -> IO [Suggestion]
runHints cmd@CmdMain{..} flags = do
let outStrLn = whenNormal . putStrLn
settings <- readAllSettings cmd flags
ideas <- if cmdCross
then applyHintFiles flags settings cmdFiles
else concat <$> parallel [listM' =<< applyHintFile flags settings x Nothing | x <- cmdFiles]
let (showideas,hideideas) = partition (\i -> cmdShowAll || ideaSeverity i /= Ignore) ideas
showItem <- if cmdColor then showANSI else return show
mapM_ (outStrLn . showItem) showideas
if null showideas then
when (cmdReports /= []) $ outStrLn "Skipping writing reports"
else
forM_ cmdReports $ \x -> do
outStrLn $ "Writing report to " ++ x ++ " ..."
writeReport cmdDataDir x showideas
outStrLn $
(let i = length showideas in if i == 0 then "No suggestions" else show i ++ " suggestion" ++ ['s'|i/=1]) ++
(let i = length hideideas in if i == 0 then "" else " (" ++ show i ++ " ignored)")
return $ map Suggestion showideas
|
bergmark/hlint
|
src/HLint.hs
|
Haskell
|
bsd-3-clause
| 5,099
|
--------------------------------------------------------------------------------
-- | The LLVM Metadata System.
--
-- The LLVM metadata feature is poorly documented but roughly follows the
-- following design:
-- * Metadata can be constructed in a few different ways (See below).
-- * After which it can either be attached to LLVM statements to pass along
-- extra information to the optimizer and code generator OR specificially named
-- metadata has an affect on the whole module (i.e., linking behaviour).
--
--
-- # Constructing metadata
-- Metadata comes largely in three forms:
--
-- * Metadata expressions -- these are the raw metadata values that encode
-- information. They consist of metadata strings, metadata nodes, regular
-- LLVM values (both literals and references to global variables) and
-- metadata expressions (i.e., recursive data type). Some examples:
-- !{ metadata !"hello", metadata !0, i32 0 }
-- !{ metadata !1, metadata !{ i32 0 } }
--
-- * Metadata nodes -- global metadata variables that attach a metadata
-- expression to a number. For example:
-- !0 = metadata !{ [<metadata expressions>] !}
--
-- * Named metadata -- global metadata variables that attach a metadata nodes
-- to a name. Used ONLY to communicated module level information to LLVM
-- through a meaningful name. For example:
-- !llvm.module.linkage = !{ !0, !1 }
--
--
-- # Using Metadata
-- Using metadata depends on the form it is in:
--
-- * Attach to instructions -- metadata can be attached to LLVM instructions
-- using a specific reference as follows:
-- %l = load i32* @glob, !nontemporal !10
-- %m = load i32* @glob, !nontemporal !{ i32 0, metadata !{ i32 0 } }
-- Only metadata nodes or expressions can be attached, named metadata cannot.
-- Refer to LLVM documentation for which instructions take metadata and its
-- meaning.
--
-- * As arguments -- llvm functions can take metadata as arguments, for
-- example:
-- call void @llvm.dbg.value(metadata !{ i32 0 }, i64 0, metadata !1)
-- As with instructions, only metadata nodes or expressions can be attached.
--
-- * As a named metadata -- Here the metadata is simply declared in global
-- scope using a specific name to communicate module level information to LLVM.
-- For example:
-- !llvm.module.linkage = !{ !0, !1 }
--
module Llvm.MetaData where
import Llvm.Types
import Outputable
-- | LLVM metadata expressions
data MetaExpr = MetaStr LMString
| MetaNode Int
| MetaVar LlvmVar
| MetaStruct [MetaExpr]
deriving (Eq)
instance Outputable MetaExpr where
ppr (MetaStr s ) = text "metadata !\"" <> ftext s <> char '"'
ppr (MetaNode n ) = text "metadata !" <> int n
ppr (MetaVar v ) = ppr v
ppr (MetaStruct es) = text "metadata !{ " <> ppCommaJoin es <> char '}'
-- | Associates some metadata with a specific label for attaching to an
-- instruction.
data MetaAnnot = MetaAnnot LMString MetaExpr
deriving (Eq)
-- | Metadata declarations. Metadata can only be declared in global scope.
data MetaDecl
-- | Named metadata. Only used for communicating module information to
-- LLVM. ('!name = !{ [!<n>] }' form).
= MetaNamed LMString [Int]
-- | Metadata node declaration.
-- ('!0 = metadata !{ <metadata expression> }' form).
| MetaUnamed Int MetaExpr
|
ekmett/ghc
|
compiler/llvmGen/Llvm/MetaData.hs
|
Haskell
|
bsd-3-clause
| 3,383
|
module Util.Handlebars
( module Util.JSON
, compile
, render
, render'
, Collection
) where
import UHC.Ptr
import Util.JSON
import Util.String
compile :: forall a. String -> IO (Ptr a -> IO PackedString)
compile source = __compile (pack source) >>= return . __mkFun
render :: (ToJSON a) => (Ptr a -> IO PackedString) -> a -> IO String
render f obj = render' f obj >>= return . unpack
render' :: (ToJSON a) => (Ptr a -> IO PackedString) -> a -> IO PackedString
render' f obj = (__parse $ pack $ toStr obj) >>= f
foreign import js "Handlebars.compile(%*)"
__compile :: PackedString -> IO (FunPtr (Ptr a -> IO PackedString))
foreign import js "dynamic"
__mkFun :: FunPtr (Ptr a -> IO PackedString) -> Ptr a -> IO PackedString
foreign import js "JSON.parse(%*)"
__parse :: PackedString -> IO (Ptr a)
newtype Collection a = Collection [a]
|
johanneshilden/liquid-epsilon
|
Util/Handlebars.hs
|
Haskell
|
bsd-3-clause
| 882
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Common types for actions
module VK.API.Actions.Types where
import Data.List (stripPrefix)
import Data.Maybe (fromMaybe, maybeToList)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Network.API.Builder
import VK.API.CommonTypes (OwnerId, ownerIdToInt)
import VK.Internal.Utils
data SortOrder = Asc | Desc
deriving (Show, Generic)
instance ToQuery SortOrder where
toQuery n = toQuery n . T.toLower . T.pack . show
data VideoSort = VideoByDate
| VideoBySize
| VideoByDuration
| VideoByRelevance
deriving (Show, Eq, Enum, Bounded)
instance ToQuery VideoSort where
toQuery n v = toQuery n (fromEnum v)
data QualityFilter = AnyQuality
| HD
deriving (Show, Eq, Enum, Bounded)
instance ToQuery QualityFilter where
toQuery n v = toQuery n (fromEnum v)
data AdultFilter = NoAdult
| Adult
deriving (Show, Eq, Enum, Bounded)
instance ToQuery AdultFilter where
toQuery n v = toQuery n (fromEnum v)
-- | 'ShortVideo' - возвращать только короткие видеозаписи
-- 'LongVideo' - возвращать только длинные видеозаписи
data CriteriaFilter = MP4
| Youtube
| Vimeo
| ShortVideo
| LongVideo
deriving (Show, Eq, Enum, Bounded)
instance ToQuery CriteriaFilter where
toQuery n v = toQuery n (T.toLower . T.pack $ show v)
-- | 'AnyRecords' - не искать по записям пользователя (по умолчанию)
-- 'OwnRecords' - искать по записям пользователя
data OwnFilter = AnyRecords
| OwnRecords
deriving (Show, Eq, Enum, Bounded)
instance ToQuery OwnFilter where
toQuery n v = toQuery n (fromEnum v)
-- | возвращать дополнительные объекты profiles и groups,
-- которые содержат id и имя/название владельцев видео.
data AddExtended = NoExtended
| AddExtended
deriving (Show, Eq, Enum, Bounded)
instance ToQuery AddExtended where
toQuery n v = toQuery n (fromEnum v)
data VideoId = VideoId {
videoidOwnerId :: !OwnerId
, videoidId :: Int
, videoidAccessKey :: !(Maybe T.Text)
}
deriving Show
instance ToQuery VideoId where
toQuery n (VideoId oid vid ac) =
toQuery n $
T.intercalate "_" $
map (T.pack . show) [ownerIdToInt oid, vid] ++ maybeToList ac
data AttachmentType = PhotoAttachment
| VideoAttachment
| AudioAttachment
| DocAttachment
deriving (Show, Enum)
data Attachment = Attachment {
attachmentType :: AttachmentType
, attachmentOwnerId :: OwnerId
, attachmentMediaId :: Int
}
deriving Show
instance ToQuery Attachment where
toQuery n (Attachment at oid mid) =
let attxt = case T.stripSuffix "Attachment" $ tshow at of
Nothing ->
error "should never happen"
Just v ->
T.toLower v
in
toQuery n $
T.intercalate "_" $
[T.append attxt (tshow $ ownerIdToInt oid)
, tshow mid
]
data ReportReason = Spam
| ChildPorno
| Extremism
| Violence
| DrugsPropaganda
| AdultMaterial
| Offence
deriving (Show, Eq, Enum, Bounded)
instance ToQuery ReportReason where
toQuery n v = toQuery n (fromEnum v)
-- audio
data AudioSort = AudioByDate
| AudioByDuration
| AudioByPopularity
deriving (Show, Eq, Enum, Bounded)
instance ToQuery AudioSort where
toQuery n v = toQuery n (fromEnum v)
data BroadcastsFilter = FriendsBroadcasts
| GroupBroadcasts
| AllBroadcasts
deriving (Show, Eq, Enum, Bounded)
instance ToQuery BroadcastsFilter where
toQuery n v = toQuery n (T.toLower $ tshow v)
data TargetAudio = TargetAudio {
targetaudioOwnerId :: !OwnerId
, targetaudioAudioId :: !Int
}
deriving Show
instance ToQuery TargetAudio where
toQuery n (TargetAudio oid aid) =
toQuery n $
T.intercalate "_" $ map (T.pack . show) [ownerIdToInt oid, aid]
data GetUserId = GetUserId !Int
| GetUserName !T.Text
deriving Show
instance ToQuery GetUserId where
toQuery n (GetUserId uid) =
toQuery n $ tshow uid
toQuery n (GetUserName un) =
toQuery n un
-- users
-- | дополнительное поле профиля пользователя, которое необходимо вернуть
data UserField = UserFieldSex
| UserFieldBdate
| UserFieldCity
| UserFieldCountry
| UserFieldPhoto50
| UserFieldPhoto100
| UserFieldPhoto200Orig
| UserFieldPhoto200
| UserFieldPhoto400Orig
| UserFieldPhotoMax
| UserFieldPhotoMaxOrig
| UserFieldPhotoId
| UserFieldOnline
| UserFieldOnlineMobile
| UserFieldDomain
| UserFieldHasMobile
| UserFieldContacts
| UserFieldConnections
| UserFieldSite
| UserFieldEducation
| UserFieldUniversities
| UserFieldSchools
| UserFieldCanPost
| UserFieldCanSeeAllPosts
| UserFieldCanSeeAudio
| UserFieldCanWritePrivateMessage
| UserFieldStatus
| UserFieldLastSeen
| UserFieldCommonCount
| UserFieldRelation
| UserFieldRelatives
| UserFieldCounters
| UserFieldScreenName
| UserFieldMaidenName
| UserFieldTimezone
| UserFieldOccupation
| UserFieldActivities
| UserFieldInterests
| UserFieldMusic
| UserFieldMovies
| UserFieldTv
| UserFieldBooks
| UserFieldGames
| UserFieldAbout
| UserFieldQuotes
| UserFieldPersonal
| UserFieldFriend_status
| UserFieldMilitary
| UserFieldCareer
deriving Show
instance ToQuery UserField where
toQuery n v = toQuery n qval
where
qval = T.pack $ aesonPhotoCase (fromMaybe vstr $ stripPrefix "UserField" vstr)
vstr = show v
-- | падеж для склонения имени и фамилии пользователя
data NameCase = NameCaseNom -- ^ именительный
| NameCaseGen -- ^ родительный
| NameCaseDat -- ^ дательный
| NameCaseAcc -- ^ винительный
| NameCaseIns -- ^ творительный
| NameCaseAbl -- ^ предложный
deriving Show
instance ToQuery NameCase where
toQuery n v = toQuery n qval
where
qval = T.toLower . T.pack $ (fromMaybe vstr $ stripPrefix "NameCase" vstr)
vstr = show v
data UsersSort = UsersByPopularity
| UsersByRegistrationDate
deriving (Show, Eq, Enum, Bounded)
instance ToQuery UsersSort where
toQuery n v = toQuery n (fromEnum v)
data UserSearchSection = UserFriends
| UserSubscriptions
deriving (Show, Eq, Enum, Bounded)
instance ToQuery UserSearchSection where
toQuery n v = toQuery n qval
where
qval = T.toLower . T.pack $ (fromMaybe vstr $ stripPrefix "User" vstr)
vstr = show v
data NearByRadius = NearByRadiusUnknown
| M300 -- ^ 1 — 300 метров;
| M2400 -- ^ 2 — 2400 метров;
| KM18 -- ^ 3 — 18 километров;
| KM150 -- ^ 4 — 150 километров.
deriving (Show, Eq, Enum, Bounded)
instance ToQuery NearByRadius where
toQuery n v = toQuery n (fromEnum v)
|
eryx67/vk-api
|
src/VK/API/Actions/Types.hs
|
Haskell
|
bsd-3-clause
| 8,527
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeFamilies #-}
-- ---------------------------------------------------------------------------
-- |
-- Module : Data.Vector.Algorithms.Search
-- Copyright : (c) 2009-2015 Dan Doel, 2015 Tim Baumann
-- Maintainer : Dan Doel <dan.doel@gmail.com>
-- Stability : Experimental
-- Portability : Non-portable (bang patterns)
--
-- This module implements several methods of searching for indicies to insert
-- elements into a sorted vector.
module Data.Vector.Algorithms.Search
( binarySearch
, binarySearchBy
, binarySearchByBounds
, binarySearchL
, binarySearchLBy
, binarySearchLByBounds
, binarySearchR
, binarySearchRBy
, binarySearchRByBounds
, binarySearchP
, binarySearchPBounds
, gallopingSearchLeftP
, gallopingSearchLeftPBounds
, gallopingSearchRightP
, gallopingSearchRightPBounds
, Comparison
) where
import Prelude hiding (read, length)
import Control.Monad.Primitive
import Data.Bits
import Data.Vector.Generic.Mutable
import Data.Vector.Algorithms.Common (Comparison)
-- | Finds an index in a given sorted vector at which the given element could
-- be inserted while maintaining the sortedness of the vector.
binarySearch :: (PrimMonad m, MVector v e, Ord e)
=> v (PrimState m) e -> e -> m Int
binarySearch = binarySearchBy compare
{-# INLINE binarySearch #-}
-- | Finds an index in a given vector, which must be sorted with respect to the
-- given comparison function, at which the given element could be inserted while
-- preserving the vector's sortedness.
binarySearchBy :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> e -> m Int
binarySearchBy cmp vec e = binarySearchByBounds cmp vec e 0 (length vec)
{-# INLINE binarySearchBy #-}
-- | Given a vector sorted with respect to a given comparison function in indices
-- in [l,u), finds an index in [l,u] at which the given element could be inserted
-- while preserving sortedness.
binarySearchByBounds :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> e -> Int -> Int -> m Int
binarySearchByBounds cmp vec e = loop
where
loop !l !u
| u <= l = return l
| otherwise = do e' <- unsafeRead vec k
case cmp e' e of
LT -> loop (k+1) u
EQ -> return k
GT -> loop l k
where k = (u + l) `shiftR` 1
{-# INLINE binarySearchByBounds #-}
-- | Finds the lowest index in a given sorted vector at which the given element
-- could be inserted while maintaining the sortedness.
binarySearchL :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> e -> m Int
binarySearchL = binarySearchLBy compare
{-# INLINE binarySearchL #-}
-- | Finds the lowest index in a given vector, which must be sorted with respect to
-- the given comparison function, at which the given element could be inserted
-- while preserving the sortedness.
binarySearchLBy :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> e -> m Int
binarySearchLBy cmp vec e = binarySearchLByBounds cmp vec e 0 (length vec)
{-# INLINE binarySearchLBy #-}
-- | Given a vector sorted with respect to a given comparison function on indices
-- in [l,u), finds the lowest index in [l,u] at which the given element could be
-- inserted while preserving sortedness.
binarySearchLByBounds :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> e -> Int -> Int -> m Int
binarySearchLByBounds cmp vec e = binarySearchPBounds p vec
where p e' = case cmp e' e of LT -> False ; _ -> True
{-# INLINE binarySearchLByBounds #-}
-- | Finds the greatest index in a given sorted vector at which the given element
-- could be inserted while maintaining sortedness.
binarySearchR :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> e -> m Int
binarySearchR = binarySearchRBy compare
{-# INLINE binarySearchR #-}
-- | Finds the greatest index in a given vector, which must be sorted with respect to
-- the given comparison function, at which the given element could be inserted
-- while preserving the sortedness.
binarySearchRBy :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> e -> m Int
binarySearchRBy cmp vec e = binarySearchRByBounds cmp vec e 0 (length vec)
{-# INLINE binarySearchRBy #-}
-- | Given a vector sorted with respect to the given comparison function on indices
-- in [l,u), finds the greatest index in [l,u] at which the given element could be
-- inserted while preserving sortedness.
binarySearchRByBounds :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> e -> Int -> Int -> m Int
binarySearchRByBounds cmp vec e = binarySearchPBounds p vec
where p e' = case cmp e' e of GT -> True ; _ -> False
{-# INLINE binarySearchRByBounds #-}
-- | Given a predicate that is guaraneteed to be monotone on the given vector,
-- finds the first index at which the predicate returns True, or the length of
-- the array if the predicate is false for the entire array.
binarySearchP :: (PrimMonad m, MVector v e) => (e -> Bool) -> v (PrimState m) e -> m Int
binarySearchP p vec = binarySearchPBounds p vec 0 (length vec)
{-# INLINE binarySearchP #-}
-- | Given a predicate that is guaranteed to be monotone on the indices [l,u) in
-- a given vector, finds the index in [l,u] at which the predicate turns from
-- False to True (yielding u if the entire interval is False).
binarySearchPBounds :: (PrimMonad m, MVector v e)
=> (e -> Bool) -> v (PrimState m) e -> Int -> Int -> m Int
binarySearchPBounds p vec = loop
where
loop !l !u
| u <= l = return l
| otherwise = unsafeRead vec k >>= \e -> if p e then loop l k else loop (k+1) u
where k = (u + l) `shiftR` 1
{-# INLINE binarySearchPBounds #-}
-- | Given a predicate that is guaranteed to be monotone on the vector elements
-- in order, finds the index at which the predicate turns from False to True.
-- The length of the vector is returned if the predicate is False for the entire
-- vector.
--
-- Begins searching at the start of the vector, in increasing steps of size 2^n.
gallopingSearchLeftP
:: (PrimMonad m, MVector v e) => (e -> Bool) -> v (PrimState m) e -> m Int
gallopingSearchLeftP p vec = gallopingSearchLeftPBounds p vec 0 (length vec)
{-# INLINE gallopingSearchLeftP #-}
-- | Given a predicate that is guaranteed to be monotone on the vector elements
-- in order, finds the index at which the predicate turns from False to True.
-- The length of the vector is returned if the predicate is False for the entire
-- vector.
--
-- Begins searching at the end of the vector, in increasing steps of size 2^n.
gallopingSearchRightP
:: (PrimMonad m, MVector v e) => (e -> Bool) -> v (PrimState m) e -> m Int
gallopingSearchRightP p vec = gallopingSearchRightPBounds p vec 0 (length vec)
{-# INLINE gallopingSearchRightP #-}
-- | Given a predicate that is guaranteed to be monotone on the indices [l,u) in
-- a given vector, finds the index in [l,u] at which the predicate turns from
-- False to True (yielding u if the entire interval is False).
-- Begins searching at l, going right in increasing (2^n)-steps.
gallopingSearchLeftPBounds :: (PrimMonad m, MVector v e)
=> (e -> Bool)
-> v (PrimState m) e
-> Int -- ^ l
-> Int -- ^ u
-> m Int
gallopingSearchLeftPBounds p vec l u
| u <= l = return l
| otherwise = do x <- unsafeRead vec l
if p x then return l else iter (l+1) l 2
where
binSearch = binarySearchPBounds p vec
iter !i !j !_stepSize | i >= u - 1 = do
x <- unsafeRead vec (u-1)
if p x then binSearch (j+1) (u-1) else return u
iter !i !j !stepSize = do
x <- unsafeRead vec i
if p x then binSearch (j+1) i else iter (i+stepSize) i (2*stepSize)
{-# INLINE gallopingSearchLeftPBounds #-}
-- | Given a predicate that is guaranteed to be monotone on the indices [l,u) in
-- a given vector, finds the index in [l,u] at which the predicate turns from
-- False to True (yielding u if the entire interval is False).
-- Begins searching at u, going left in increasing (2^n)-steps.
gallopingSearchRightPBounds :: (PrimMonad m, MVector v e)
=> (e -> Bool)
-> v (PrimState m) e
-> Int -- ^ l
-> Int -- ^ u
-> m Int
gallopingSearchRightPBounds p vec l u
| u <= l = return l
| otherwise = iter (u-1) (u-1) (-1)
where
binSearch = binarySearchPBounds p vec
iter !i !j !_stepSize | i <= l = do
x <- unsafeRead vec l
if p x then return l else binSearch (l+1) j
iter !i !j !stepSize = do
x <- unsafeRead vec i
if p x then iter (i+stepSize) i (2*stepSize) else binSearch (i+1) j
{-# INLINE gallopingSearchRightPBounds #-}
|
tolysz/vector-algorithms
|
src/Data/Vector/Algorithms/Search.hs
|
Haskell
|
bsd-3-clause
| 9,078
|
module Text.WikiEngine
( RenderCfg (..)
, LinkType(..)
, CodeRenderType(..)
, defaultRenderCfg
-- * parsed types
, Block(..)
, Inline(..)
, parseDocument
-- * renderer
, renderAsHtml
) where
import Text.WikiEngine.Configuration
import Text.WikiEngine.HTML
import Text.WikiEngine.Parse
import Text.WikiEngine.Type
renderAsHtml = render
|
vincenthz/wikiengine
|
Text/WikiEngine.hs
|
Haskell
|
bsd-3-clause
| 349
|
module BaseSpec where
import Test.Hspec (Spec, describe, it, hspec)
import Test.Hspec.HUnit ()
import Test.Hspec.Expectations
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Prelude.head" $ do
it "returns the first element of a list" $ do
head [23 ..] `shouldBe` (23 :: Int)
-- BaseSpec.hs ends here
|
jwiegley/script-template
|
test/BaseSpec.hs
|
Haskell
|
bsd-3-clause
| 345
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PatternGuards #-}
#if MIN_VERSION_base(4,9,0)
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Text.CSL.Proc.Disamb
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Andrea Rossato <andrea.rossato@unitn.it>
-- Stability : unstable
-- Portability : unportable
--
-- This module provides functions for processing the evaluated
-- 'Output' for citation disambiguation.
--
-- Describe the disambiguation process.
--
-----------------------------------------------------------------------------
module Text.CSL.Proc.Disamb where
import Prelude
import Control.Arrow (second, (&&&), (>>>))
import Data.List (elemIndex, find, findIndex, groupBy,
isPrefixOf, mapAccumL, nub, nubBy, sortOn)
import Data.Maybe
import Text.CSL.Eval
import Text.CSL.Reference
import Text.CSL.Style
import Text.CSL.Util (proc, query)
import Text.Pandoc.Shared (ordNub)
-- | Given the 'Style', the list of references and the citation
-- groups, disambiguate citations according to the style options.
disambCitations :: Style -> [Reference] -> Citations -> [CitationGroup]
-> ([(String, String)], [CitationGroup])
disambCitations s bibs cs groups
= (,) yearSuffs citOutput
where
-- utils
when_ b f = if b then f else []
filter_ f = concatMap (map fst . filter f . uncurry zip)
-- the list of the position and the reference of each citation
-- for each citation group.
refs = processCites bibs cs
-- name data of name duplicates
nameDupls = getDuplNameData groups
-- citation data of ambiguous cites
duplics = getDuplCiteData giveNameDisamb hasNamesOpt hasYSuffOpt groups
-- check the options set in the style
disOpts = getCitDisambOptions s
hasNamesOpt = "disambiguate-add-names" `elem` disOpts
hasGNameOpt = "disambiguate-add-givenname" `elem` disOpts
hasYSuffOpt = "disambiguate-add-year-suffix" `elem` disOpts
giveNameDisamb = case getOptionVal "givenname-disambiguation-rule"
(citOptions (citation s)) of
"by-cite" -> ByCite
"all-names" -> AllNames
"all-names-with-initials" -> AllNames
"primary-name" -> PrimaryName
"primary-name-with-initials" -> PrimaryName
_ -> ByCite -- default as of CSL 1.0
clean = if hasGNameOpt then id else proc rmHashAndGivenNames
withNames = flip map duplics $ same . clean .
map (if hasNamesOpt then disambData else return . disambYS)
needNames = filter_ (not . snd) $ zip duplics withNames
needYSuff = filter_ snd $ zip duplics withNames
newNames :: [CiteData]
newNames = when_ (hasNamesOpt || hasGNameOpt) $ disambAddNames giveNameDisamb $ needNames ++
if hasYSuffOpt && giveNameDisamb == NoGiven then [] else needYSuff
newGName :: [NameData]
newGName = when_ hasGNameOpt $ concatMap disambAddGivenNames nameDupls
-- the list of citations that need re-evaluation with the
-- \"disambiguate\" condition set to 'True'
reEval = let chk = if hasYSuffOpt then filter ((==) [] . citYear) else id
in chk needYSuff
reEvaluated = if or (query hasIfDis s) && not (null reEval)
then zipWith (reEvaluate s reEval) refs groups
else groups
withYearS = addNames $
if hasYSuffOpt
then map (mapCitationGroup
(setYearSuffCollision hasNamesOpt needYSuff))
reEvaluated
else rmYearSuff reEvaluated
yearSuffs = when_ hasYSuffOpt . generateYearSuffix bibs . concatMap getYearSuffixes $ withYearS
addNames = proc (updateContrib giveNameDisamb newNames newGName)
processed = if hasYSuffOpt
then proc (updateYearSuffixes yearSuffs) withYearS
else withYearS
citOutput = if disOpts /= [] then processed else reEvaluated
mapDisambData :: (Output -> Output) -> CiteData -> CiteData
mapDisambData f (CD k c ys d r s y) = CD k c ys (proc f d) r s y
mapCitationGroup :: ([Output] -> [Output]) -> CitationGroup -> CitationGroup
mapCitationGroup f (CG cs fm d os) = CG cs fm d (zip (map fst os) . f $ map snd os)
data GiveNameDisambiguation
= NoGiven -- TODO this is no longer used?
| ByCite
| AllNames
| PrimaryName
deriving (Show, Eq)
disambAddNames :: GiveNameDisambiguation -> [CiteData] -> [CiteData]
disambAddNames b needName = addLNames
where
clean = if b == NoGiven then proc rmHashAndGivenNames else id
disSolved = zip needName' . disambiguate . map disambData $ needName'
needName' = nub' needName []
addLNames = map (\(c,n) -> c { disambed = if null n then collision c else head n }) disSolved
nub' [] r = r
nub' (x:xs) r = case elemIndex (disambData $ clean x)
(map (disambData . clean) r) of
Nothing -> nub' xs (x:r)
Just i -> let y = r !! i
in nub' xs (y {sameAs = key x : sameAs y}
: filter (/= y) r)
disambAddGivenNames :: [NameData] -> [NameData]
disambAddGivenNames needName = addGName
where
disSolved = zip needName (disambiguate $ map nameDisambData needName)
addGName = map (\(c,n) -> c { nameDataSolved = if null n then nameCollision c else head n }) disSolved
updateContrib :: GiveNameDisambiguation -> [CiteData] -> [NameData] -> Output -> Output
updateContrib g c n o
| OContrib k r s d dd <- o = case filter (key &&& sameAs >>> uncurry (:) >>> elem k) c of
x:_ | clean (disambData x) == clean (d:dd) ->
OContrib k r (map processGNames $ disambed x) [] dd
_ | null c, AllNames <- g -> OContrib k r (map processGNames s) d dd
| otherwise -> o
| otherwise = o
where
clean = if g == NoGiven then proc rmHashAndGivenNames else id
processGNames = if g /= NoGiven then updateOName n else id
updateOName :: [NameData] -> Output -> Output
updateOName n o
| OName _ _ [] _ <- o = o
| OName k x _ f <- o = case elemIndex (ND k (clean x) [] []) n of
Just i -> OName emptyAgent (nameDataSolved $ n !! i) [] f
_ -> o
| otherwise = o
where
clean = proc rmGivenNames
-- | Evaluate again a citation group with the 'EvalState' 'disamb'
-- field set to 'True' (for matching the @\"disambiguate\"@
-- condition).
reEvaluate :: Style
-> [CiteData]
-> [(Cite, Maybe Reference)]
-> CitationGroup
-> CitationGroup
reEvaluate Style{citation = ct, csMacros = ms , styleLocale = lo,
styleAbbrevs = as} l cr (CG a f d os)
= CG a f d . flip concatMap (zip cr os) $
\((c,mbr),out) ->
case mbr of
Just r | unLiteral (refId r) `elem` lkeys ->
return . second (flip Output emptyFormatting) $
(,) c $ evalLayout (citLayout ct) (EvalCite c) True lo ms (citOptions ct) as mbr
_ -> [out]
where lkeys = map key l
-- | Check if the 'Style' has any conditional for disambiguation. In
-- this case the conditional will be try after all other
-- disambiguation strategies have failed. To be used with the generic
-- 'query' function.
hasIfDis :: IfThen -> [Bool]
hasIfDis (IfThen Condition{disambiguation = (_:_)} _ _) = [True]
hasIfDis _ = [False]
-- | Get the list of disambiguation options set in the 'Style' for
-- citations.
getCitDisambOptions :: Style -> [String]
getCitDisambOptions
= map fst . filter ((==) "true" . snd) .
filter (isPrefixOf "disambiguate" . fst) . citOptions . citation
-- | Group citation data (with possible alternative names) of
-- citations which have a duplicate (same 'collision', and same
-- 'citYear' if year suffix disambiiguation is used). If the first
-- 'Bool' is 'False', then we need to retrieve data for year suffix
-- disambiguation. The second 'Bool' is 'True' when comparing both
-- year and contributors' names for finding duplicates (when the
-- year-suffix option is set).
getDuplCiteData :: GiveNameDisambiguation -> Bool -> Bool -> [CitationGroup] -> [[CiteData]]
getDuplCiteData giveNameDisamb b1 b2 g
= groupBy (\x y -> collide x == collide y) . sortOn collide
$ duplicates
where
whatToGet = if b1 then collision else disambYS
collide = proc (rmExtras giveNameDisamb) .
proc rmHashAndGivenNames .
whatToGet
citeData = nubBy (\a b -> collide a == collide b && key a == key b) $
concatMap (mapGroupOutput getCiteData) g
duplicates = [c | c <- citeData , d <- citeData , collides c d]
collides x y = x /= y && (collide x == collide y)
&& (not b2 || citYear x == citYear y)
rmExtras :: GiveNameDisambiguation -> [Output] -> [Output]
rmExtras g os
| Output x _ : xs <- os = case rmExtras g x of
[] -> rmExtras g xs
ys -> ys ++ rmExtras g xs
| OContrib _ _ (y:ys) _ _ : xs <- os
= if g == PrimaryName
then OContrib [] [] [y] [] [] : rmExtras g xs
else OContrib [] [] (y:ys) [] [] : rmExtras g xs
| OYear{} : xs <- os = rmExtras g xs
| OYearSuf{} : xs <- os = rmExtras g xs
| OLabel{} : xs <- os = rmExtras g xs
| ODel _ : xs <- os = rmExtras g xs
| OLoc _ _ : xs <- os = rmExtras g xs
| x : xs <- os = x : rmExtras g xs
| otherwise = []
-- | For an evaluated citation get its 'CiteData'. The disambiguated
-- citation and the year fields are empty. Only the first list of
-- contributors' disambiguation data are collected for disambiguation
-- purposes.
getCiteData :: Output -> [CiteData]
getCiteData out
= (contribs &&& years >>> zipData) out
where
contribs x = case query contribsQ x of
[] -> [CD [] [out] [] [] [] [] []]
-- allow title to disambiguate
xs -> xs
years o = case query getYears o of
[] -> [([],[])]
r -> r
zipData = uncurry . zipWith $ \c y -> if key c /= []
then c {citYear = snd y}
else c {key = fst y
,citYear = snd y}
contribsQ o
| OContrib k _ _ d dd <- o = [CD k [out] d (d:dd) [] [] []]
| otherwise = []
getYears :: Output -> [(String,String)]
getYears o
| OYear x k _ <- o = [(k,x)]
| otherwise = []
getDuplNameData :: [CitationGroup] -> [[NameData]]
getDuplNameData g
= groupBy (\a b -> collide a == collide b) . sortOn collide $ duplicates
where
collide = nameCollision
nameData = nub $ concatMap (mapGroupOutput getName) g
duplicates = filter (flip elem (getDuplNames g) . collide) nameData
getDuplNames :: [CitationGroup] -> [[Output]]
getDuplNames = ordNub . catMaybes . snd . mapAccumL dupl [] . getData
where
getData = concatMap (mapGroupOutput getName)
dupl a c = if nameCollision c `elem` map nameCollision a
then (a,Just $ nameCollision c)
else (c:a,Nothing)
getName :: Output -> [NameData]
getName = query getName'
where
getName' o
| OName i n ns _ <- o = [ND i n (n:ns) []]
| otherwise = []
generateYearSuffix :: [Reference] -> [(String, [Output])] -> [(String,String)]
generateYearSuffix refs
= concatMap (`zip` suffs) .
-- sort clashing cites using their position in the sorted bibliography
getFst . map (sort' . filter ((/=) 0 . snd) . map getP) .
-- group clashing cites
getFst . filter (\grp -> length grp >= 2) . map nub .
groupBy (\a b -> snd a == snd b) .
sort' . filter (not . null . snd)
where
sort' :: (Ord a, Ord b) => [(a,b)] -> [(a,b)]
sort' = sortOn snd
getFst = map $ map fst
getP k = case findIndex ((==) k . unLiteral . refId) refs of
Just x -> (k, x + 1)
_ -> (k, 0)
suffs = letters ++ [x ++ y | x <- letters, y <- letters ]
letters = map (:[]) ['a'..'z']
setYearSuffCollision :: Bool -> [CiteData] -> [Output] -> [Output]
setYearSuffCollision b cs = proc (setYS cs) .
map (\x -> if hasYearSuf x then x else addYearSuffix x)
where
setYS c o
| OYearSuf _ k _ f <- o = OYearSuf [] k (getCollision k c) f
| otherwise = o
collide = if b then disambed else disambYS
getCollision k c = case find ((==) k . key) c of
Just x -> case collide x of
[] -> [OStr (citYear x) emptyFormatting]
ys -> ys
_ -> []
updateYearSuffixes :: [(String, String)] -> Output -> Output
updateYearSuffixes yss o
| OYearSuf _ k c f <- o = case lookup k yss of
Just x -> OYearSuf x k c f
_ -> ONull
| otherwise = o
getYearSuffixes :: CitationGroup -> [(String,[Output])]
getYearSuffixes (CG _ _ _ d) = map go d
where go (c,x) = (citeId c, relevant False [x])
relevant :: Bool -> [Output] -> [Output] -- bool is true if has contrib
-- we're only interested in OContrib and OYear,
-- unless there is no OContrib
relevant c (Output xs _ : rest) = relevant c xs ++ relevant c rest
relevant c (OYear n _ _ : rest) = OStr n emptyFormatting : relevant c rest
relevant c (ODate xs : rest) = relevant c xs ++ relevant c rest
relevant False (OStr s _ : rest) = OStr s emptyFormatting : relevant False rest
relevant False (OSpace : rest) = OSpace : relevant False rest
relevant False (OPan ils : rest) = OPan ils : relevant False rest
relevant _ (OContrib _ _ v _ _ : rest ) = relevant False v ++ relevant True rest
relevant c (OName _ v _ _ : rest ) = relevant c v ++ relevant c rest
relevant c (_ : rest) = relevant c rest
relevant _ [] = []
rmYearSuff :: [CitationGroup] -> [CitationGroup]
rmYearSuff = proc rmYS
where
rmYS o
| OYearSuf{} <- o = ONull
| otherwise = o
-- List Utilities
-- | Try to disambiguate a list of lists by returning the first non
-- colliding element, if any, of each list:
--
-- > disambiguate [[1,2],[1,3],[2]] = [[2],[3],[2]]
disambiguate :: (Eq a) => [[a]] -> [[a]]
disambiguate [] = []
disambiguate l
= if hasMult l && not (allTheSame l) && hasDuplicates heads
then disambiguate (rest l)
else heads
where
heads = map (take 1) l
rest = map (\(b,x) -> if b then tail_ x else take 1 x) . zip (same heads)
hasMult = foldr (\x -> (||) (length x > 1)) False
tail_ [x] = [x]
tail_ x = if null x then x else tail x
-- | For each element a list of 'Bool': 'True' if the element has a
-- duplicate in the list:
--
-- > same [1,2,1] = [True,False,True]
same :: Eq a => [a] -> [Bool]
same l = map (`elem` dupl) l
where
dupl = catMaybes . snd . macc [] $ l
macc = mapAccumL $ \a x -> if x `elem` a
then (a,Just x)
else (x:a,Nothing)
hasDuplicates :: Eq a => [a] -> Bool
hasDuplicates = or . same
allTheSame :: Eq a => [a] -> Bool
allTheSame [] = True
allTheSame (x:xs) = all (== x) xs
-- | Add the year suffix to the year. Needed for disambiguation.
addYearSuffix :: Output -> Output
addYearSuffix o
| OYear y k f <- o = Output [ OYear y k emptyFormatting
, OYearSuf [] k [] emptyFormatting] f
| ODate (x:xs) <- o = if any hasYear xs
then Output (x : [addYearSuffix $ ODate xs]) emptyFormatting
else addYearSuffix (Output (x:xs) emptyFormatting)
| Output (x:xs) f <- o = if any hasYearSuf (x : xs)
then Output (x : xs) f
else if hasYear x
then Output (addYearSuffix x : xs) f
else Output (x : [addYearSuffix $ Output xs emptyFormatting]) f
| otherwise = o
hasYear :: Output -> Bool
hasYear = not . null . query getYear
where getYear o
| OYear{} <- o = [o]
| otherwise = []
hasYearSuf :: Output -> Bool
hasYearSuf = not . null . query getYearSuf
where getYearSuf :: Output -> [String]
getYearSuf o
| OYearSuf{} <- o = ["a"]
| otherwise = []
-- | Removes all given names and name hashes from OName elements.
rmHashAndGivenNames :: Output -> Output
rmHashAndGivenNames (OName _ s _ f) = OName emptyAgent s [] f
rmHashAndGivenNames o = o
rmGivenNames :: Output -> Output
rmGivenNames (OName a s _ f) = OName a s [] f
rmGivenNames o = o
-- | Add, with 'proc', a give name to the family name. Needed for
-- disambiguation.
addGivenNames :: [Output] -> [Output]
addGivenNames
= addGN True
where
addGN _ [] = []
addGN b (o:os)
| OName i _ xs f <- o
, xs /= [] = if b then OName i (head xs) (tail xs) f : addGN False os else o:os
| otherwise = o : addGN b os
-- | Map the evaluated output of a citation group.
mapGroupOutput :: (Output -> [a]) -> CitationGroup -> [a]
mapGroupOutput f (CG _ _ _ os) = concatMap (f . snd) os
|
adunning/pandoc-citeproc
|
src/Text/CSL/Proc/Disamb.hs
|
Haskell
|
bsd-3-clause
| 18,750
|
module NoteScript
( module N
) where
import NoteScript.LendingClub as N
import NoteScript.Prosper as N
import NoteScript.Syntax as N
|
WraithM/notescript
|
src/NoteScript.hs
|
Haskell
|
bsd-3-clause
| 181
|
module Grid
( Grid
, makeGrid
, getSize
, getRows
, getCols
, getCell
, setCell
, update
-- Only functions are exported but not Data.Matrix module.
-- These functions might not be used always. So no need to
-- export module for that. It would be better to export it
-- manually when it is needed.
, toMatrix
, fromMatrix
, aliveCoords
) where
{-
This module implements a grid of cells. Grid's
indexes are C'like. The isOutOfRange function
from Pos module is used to check whether
indexes are valid or not.
-}
import Data.List
import qualified Data.Matrix as M
import qualified Cell as C
import Pos
-- Type of grid.
type Grid = M.Matrix C.Cell
-- Converts grid to matrix from Data.Matrix.
-- It allows to use all nice functions from
-- Data.Matrix over Grid.
toMatrix :: Grid -> M.Matrix C.Cell
toMatrix = id
-- Symmetric to toMatrix: once all nice functions
-- from Data.Matrix were applied, it is time to turn
-- matrix back into a grid.
fromMatrix :: M.Matrix C.Cell -> Grid
fromMatrix = id
-- Returns new grid of supplied size.
makeGrid :: Int -> Int -> Grid
makeGrid r c = M.matrix r c $ const C.dead
-- Returns a number of rows in a grid.
getRows :: Grid -> Int
getRows = M.nrows
-- Returns a number of cols in a grid.
getCols :: Grid -> Int
getCols = M.ncols
-- Returns size of grid.
getSize :: Grid -> (Int, Int)
getSize g = (getRows g, getCols g)
-- Returns a cell by it's coordinates.
getCell :: Pos -> Grid -> C.Cell
getCell p@(y, x) g =
let (r, c) = getSize g in
if isOutOfRange r c p
then error $ "getCell: " ++ show p ++ " is out of range!"
else M.getElem (y + 1) (x + 1) g
-- Returns a neighbours of cell at supplied position.
getNeighborsOfCellByPos :: Pos -> Grid -> [C.Cell]
getNeighborsOfCellByPos p g =
let (r, c) = getSize g
pNs = neighbors p
vNs = filter (not . isOutOfRange r c) pNs
in map (flip getCell g) vNs
-- Updates grid at supplied position.
update :: Grid -> Grid
update g =
let (r, c) = getSize g
in M.matrix r c
(\ (y', x') ->
let p = (y' - 1, x' - 1)
cell = getCell p g
ns = getNeighborsOfCellByPos p g
in C.update cell ns)
-- Sets cell on grid.
setCell :: C.Cell -> Pos -> Grid -> Grid
setCell c (y, x) g = M.setElem c (y + 1, x + 1) g
-- Returns a list of coordinates of alive cells on a grid.
aliveCoords :: Grid -> [(Int, Int)]
aliveCoords g =
-- Transfrom matrix to a list of lists.
let lists = M.toLists g
-- Index each cell and each list.
iLists = zip [0..] $ map (zip [0..]) lists
-- Push list index to cell index.
iCells = concatMap
(\ (n, xs)
-> map (\ (m, c) -> ((n, m), c)) xs
) iLists
-- Filter alive cells.
fCells = filter (C.isAlive . snd) iCells
-- Get rid of cell.
in map fst fCells
|
wowofbob/gol
|
src/Grid.hs
|
Haskell
|
bsd-3-clause
| 3,002
|
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
module Web.Slack.Types.Error where
import Data.Aeson
import Control.Lens.TH
data SlackError = SlackError deriving Show
makeLenses ''SlackError
instance FromJSON SlackError where
parseJSON = withObject "SlackError" (\_ -> return SlackError)
|
mpickering/slack-api
|
src/Web/Slack/Types/Error.hs
|
Haskell
|
mit
| 299
|
{-# LANGUAGE TupleSections, ParallelListComp #-}
-- | Convert the concrete syntax into the syntax of cubical TT.
module Concrete where
import Exp.Abs
import qualified CTT as C
import Pretty
import Control.Applicative
import Control.Arrow (second)
import Control.Monad.Trans
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Error hiding (throwError)
import Control.Monad.Error (throwError)
import Control.Monad (when)
import Data.Functor.Identity
import Data.List (nub)
type Tele = [(AIdent,Exp)]
type Ter = C.Ter
-- | Useful auxiliary functions
-- Applicative cons
(<:>) :: Applicative f => f a -> f [a] -> f [a]
a <:> b = (:) <$> a <*> b
-- un-something functions
unAIdent :: AIdent -> C.Ident
unAIdent (AIdent (_,x)) = x
unVar :: Exp -> Maybe AIdent
unVar (Var x) = Just x
unVar _ = Nothing
unWhere :: ExpWhere -> Exp
unWhere (Where e ds) = Let ds e
unWhere (NoWhere e) = e
-- tail recursive form to transform a sequence of applications
-- App (App (App u v) ...) w into (u, [v, …, w])
-- (cleaner than the previous version of unApps)
unApps :: Exp -> [Exp] -> (Exp, [Exp])
unApps (App u v) ws = unApps u (v : ws)
unApps u ws = (u, ws)
vTele :: [VTDecl] -> Tele
vTele decls = [ (i, typ) | VTDecl id ids typ <- decls, i <- id:ids ]
-- turns an expression of the form App (... (App id1 id2) ... idn)
-- into a list of idents
pseudoIdents :: Exp -> Maybe [AIdent]
pseudoIdents = mapM unVar . uncurry (:) . flip unApps []
pseudoTele :: [PseudoTDecl] -> Maybe Tele
pseudoTele [] = return []
pseudoTele (PseudoTDecl exp typ : pd) = do
ids <- pseudoIdents exp
pt <- pseudoTele pd
return $ map (,typ) ids ++ pt
-------------------------------------------------------------------------------
-- | Resolver and environment
type Arity = Int
data SymKind = Variable | Constructor Arity
deriving (Eq,Show)
-- local environment for constructors
data Env = Env { envModule :: String,
variables :: [(C.Binder,SymKind)] }
deriving (Eq, Show)
type Resolver a = ReaderT Env (ErrorT String Identity) a
emptyEnv :: Env
emptyEnv = Env "" []
runResolver :: Resolver a -> Either String a
runResolver x = runIdentity $ runErrorT $ runReaderT x emptyEnv
updateModule :: String -> Env -> Env
updateModule mod e = e {envModule = mod}
insertBinder :: (C.Binder,SymKind) -> Env -> Env
insertBinder (x@(n,_),var) e
| n == "_" || n == "undefined" = e
| otherwise = e {variables = (x, var) : variables e}
insertBinders :: [(C.Binder,SymKind)] -> Env -> Env
insertBinders = flip $ foldr insertBinder
insertVar :: C.Binder -> Env -> Env
insertVar x = insertBinder (x,Variable)
insertVars :: [C.Binder] -> Env -> Env
insertVars = flip $ foldr insertVar
insertCon :: (C.Binder,Arity) -> Env -> Env
insertCon (x,a) = insertBinder (x,Constructor a)
insertCons :: [(C.Binder,Arity)] -> Env -> Env
insertCons = flip $ foldr insertCon
getModule :: Resolver String
getModule = envModule <$> ask
getVariables :: Resolver [(C.Binder,SymKind)]
getVariables = variables <$> ask
getLoc :: (Int,Int) -> Resolver C.Loc
getLoc l = C.Loc <$> getModule <*> pure l
resolveBinder :: AIdent -> Resolver C.Binder
resolveBinder (AIdent (l,x)) = (x,) <$> getLoc l
-- Eta expand constructors
expandConstr :: Arity -> String -> [Exp] -> Resolver Ter
expandConstr a x es = do
let r = a - length es
binders = map (('_' :) . show) [1..r]
args = map C.Var binders
ts <- mapM resolveExp es
return $ C.mkLams binders $ C.mkApps (C.Con x []) (ts ++ args)
resolveVar :: AIdent -> Resolver Ter
resolveVar (AIdent (l,x))
| (x == "_") || (x == "undefined") = C.PN <$> C.Undef <$> getLoc l
| otherwise = do
modName <- getModule
vars <- getVariables
case C.getIdent x vars of
Just Variable -> return $ C.Var x
Just (Constructor a) -> expandConstr a x []
_ -> throwError $
"Cannot resolve variable" <+> x <+> "at position" <+>
show l <+> "in module" <+> modName
lam :: AIdent -> Resolver Ter -> Resolver Ter
lam a e = do x <- resolveBinder a; C.Lam x <$> local (insertVar x) e
lams :: [AIdent] -> Resolver Ter -> Resolver Ter
lams = flip $ foldr lam
bind :: (Ter -> Ter -> Ter) -> (AIdent, Exp) -> Resolver Ter -> Resolver Ter
bind f (x,t) e = f <$> resolveExp t <*> lam x e
binds :: (Ter -> Ter -> Ter) -> Tele -> Resolver Ter -> Resolver Ter
binds f = flip $ foldr $ bind f
resolveExp :: Exp -> Resolver Ter
resolveExp U = return C.U
resolveExp (Var x) = resolveVar x
resolveExp (App t s) = case unApps t [s] of
(x@(Var (AIdent (_,n))),xs) -> do
-- Special treatment in the case of a constructor in order not to
-- eta expand too much
vars <- getVariables
case C.getIdent n vars of
Just (Constructor a) -> expandConstr a n xs
_ -> C.mkApps <$> resolveExp x <*> mapM resolveExp xs
(x,xs) -> C.mkApps <$> resolveExp x <*> mapM resolveExp xs
resolveExp (Sigma t b) = case pseudoTele t of
Just tele -> binds C.Sigma tele (resolveExp b)
Nothing -> throwError "Telescope malformed in Sigma"
resolveExp (Pi t b) = case pseudoTele t of
Just tele -> binds C.Pi tele (resolveExp b)
Nothing -> throwError "Telescope malformed in Pigma"
resolveExp (Fun a b) = bind C.Pi (AIdent ((0,0),"_"), a) (resolveExp b)
resolveExp (Lam x xs t) = lams (x:xs) (resolveExp t)
resolveExp (Fst t) = C.Fst <$> resolveExp t
resolveExp (Snd t) = C.Snd <$> resolveExp t
resolveExp (Pair t0 t1) = C.SPair <$> resolveExp t0 <*> resolveExp t1
resolveExp (Split brs) = do
brs' <- mapM resolveBranch brs
loc <- getLoc (case brs of Branch (AIdent (l,_)) _ _:_ -> l ; _ -> (0,0))
return $ C.Split loc brs'
resolveExp (Let decls e) = do
(rdecls,names) <- resolveDecls decls
C.mkWheres rdecls <$> local (insertBinders names) (resolveExp e)
resolveWhere :: ExpWhere -> Resolver Ter
resolveWhere = resolveExp . unWhere
resolveBranch :: Branch -> Resolver (C.Label,([C.Binder],C.Ter))
resolveBranch (Branch lbl args e) = do
binders <- mapM resolveBinder args
re <- local (insertVars binders) $ resolveWhere e
return (unAIdent lbl, (binders, re))
resolveTele :: [(AIdent,Exp)] -> Resolver C.Tele
resolveTele [] = return []
resolveTele ((i,d):t) = do
x <- resolveBinder i
((x,) <$> resolveExp d) <:> local (insertVar x) (resolveTele t)
resolveLabel :: Label -> Resolver (C.Binder, C.Tele)
resolveLabel (Label n vdecl) =
(,) <$> resolveBinder n <*> resolveTele (vTele vdecl)
declsLabels :: [Decl] -> Resolver [(C.Binder,Arity)]
declsLabels decls = do
let sums = concat [sum | DeclData _ _ sum <- decls]
sequence [ (,length args) <$> resolveBinder lbl | Label lbl args <- sums ]
-- Resolve Data or Def declaration
resolveDDecl :: Decl -> Resolver (C.Ident, C.Ter)
resolveDDecl (DeclDef (AIdent (_,n)) args body) =
(n,) <$> lams args (resolveWhere body)
resolveDDecl (DeclData x@(AIdent (l,n)) args sum) =
(n,) <$> lams args (C.Sum <$> resolveBinder x <*> mapM resolveLabel sum)
resolveDDecl d = throwError $ "Definition expected" <+> show d
-- Resolve mutual declarations (possibly one)
resolveMutuals :: [Decl] -> Resolver (C.Decls,[(C.Binder,SymKind)])
resolveMutuals decls = do
binders <- mapM resolveBinder idents
cs <- declsLabels decls
let cns = map (fst . fst) cs ++ names
when (nub cns /= cns) $
throwError $ "Duplicated constructor or ident:" <+> show cns
rddecls <-
mapM (local (insertVars binders . insertCons cs) . resolveDDecl) ddecls
when (names /= map fst rddecls) $
throwError $ "Mismatching names in" <+> show decls
rtdecls <- resolveTele tdecls
return ([ (x,t,d) | (x,t) <- rtdecls | (_,d) <- rddecls ],
map (second Constructor) cs ++ map (,Variable) binders)
where
idents = [ x | DeclType x _ <- decls ]
names = [ unAIdent x | x <- idents ]
tdecls = [ (x,t) | DeclType x t <- decls ]
ddecls = filter (not . isTDecl) decls
isTDecl d = case d of DeclType{} -> True; _ -> False
-- Resolve opaque/transparent decls
resolveOTDecl :: (C.Binder -> C.ODecls) -> AIdent -> [Decl] ->
Resolver ([C.ODecls],[(C.Binder,SymKind)])
resolveOTDecl c n ds = do
vars <- getVariables
(rest,names) <- resolveDecls ds
case C.getBinder (unAIdent n) vars of
Just x -> return (c x : rest, names)
Nothing -> throwError $ "Not in scope:" <+> show n
-- Resolve declarations
resolveDecls :: [Decl] -> Resolver ([C.ODecls],[(C.Binder,SymKind)])
resolveDecls [] = return ([],[])
resolveDecls (DeclOpaque n:ds) = resolveOTDecl C.Opaque n ds
resolveDecls (DeclTransp n:ds) = resolveOTDecl C.Transp n ds
resolveDecls (td@DeclType{}:d:ds) = do
(rtd,names) <- resolveMutuals [td,d]
(rds,names') <- local (insertBinders names) $ resolveDecls ds
return (C.ODecls rtd : rds, names' ++ names)
resolveDecls (DeclPrim x t:ds) = case C.mkPN (unAIdent x) of
Just pn -> do
b <- resolveBinder x
rt <- resolveExp t
(rds,names) <- local (insertVar b) $ resolveDecls ds
return (C.ODecls [(b, rt, C.PN pn)] : rds, names ++ [(b,Variable)])
Nothing -> throwError $ "Primitive notion not defined:" <+> unAIdent x
resolveDecls (DeclMutual defs : ds) = do
(rdefs,names) <- resolveMutuals defs
(rds, names') <- local (insertBinders names) $ resolveDecls ds
return (C.ODecls rdefs : rds, names' ++ names)
resolveDecls (decl:_) = throwError $ "Invalid declaration:" <+> show decl
resolveModule :: Module -> Resolver ([C.ODecls],[(C.Binder,SymKind)])
resolveModule (Module n imports decls) =
local (updateModule $ unAIdent n) $ resolveDecls decls
resolveModules :: [Module] -> Resolver ([C.ODecls],[(C.Binder,SymKind)])
resolveModules [] = return ([],[])
resolveModules (mod:mods) = do
(rmod, names) <- resolveModule mod
(rmods,names') <- local (insertBinders names) $ resolveModules mods
return (rmod ++ rmods, names' ++ names)
|
simhu/cubical
|
Concrete.hs
|
Haskell
|
mit
| 9,974
|
{-# LANGUAGE CPP #-}
import Control.Monad
import Data.IORef
import Control.Exception (SomeException, catch)
import Distribution.Simple
import Distribution.Simple.BuildPaths (autogenModulesDir)
import Distribution.Simple.InstallDirs as I
import Distribution.Simple.LocalBuildInfo as L
import qualified Distribution.Simple.Setup as S
import qualified Distribution.Simple.Program as P
import Distribution.Simple.Utils (createDirectoryIfMissingVerbose, rewriteFile, notice, installOrdinaryFiles)
import Distribution.Compiler
import Distribution.PackageDescription
import Distribution.Text
import System.Environment
import System.Exit
import System.FilePath ((</>), splitDirectories,isAbsolute)
import System.Directory
import qualified System.FilePath.Posix as Px
import System.Process
-- After Idris is built, we need to check and install the prelude and other libs
-- -----------------------------------------------------------------------------
-- Idris Command Path
-- make on mingw32 exepects unix style separators
#ifdef mingw32_HOST_OS
(<//>) = (Px.</>)
idrisCmd local = Px.joinPath $ splitDirectories $ ".." <//> ".." <//> buildDir local <//> "idris" <//> "idris"
#else
idrisCmd local = ".." </> ".." </> buildDir local </> "idris" </> "idris"
#endif
-- -----------------------------------------------------------------------------
-- Make Commands
-- use GNU make on FreeBSD
#if defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS)\
|| defined(openbsd_HOST_OS) || defined(netbsd_HOST_OS)
mymake = "gmake"
#else
mymake = "make"
#endif
make verbosity =
P.runProgramInvocation verbosity . P.simpleProgramInvocation mymake
#ifdef mingw32_HOST_OS
windres verbosity = P.runProgramInvocation verbosity . P.simpleProgramInvocation "windres"
#endif
-- -----------------------------------------------------------------------------
-- Flags
usesGMP :: S.ConfigFlags -> Bool
usesGMP flags =
case lookup (FlagName "gmp") (S.configConfigurationsFlags flags) of
Just True -> True
Just False -> False
Nothing -> False
execOnly :: S.ConfigFlags -> Bool
execOnly flags =
case lookup (FlagName "execonly") (S.configConfigurationsFlags flags) of
Just True -> True
Just False -> False
Nothing -> False
isRelease :: S.ConfigFlags -> Bool
isRelease flags =
case lookup (FlagName "release") (S.configConfigurationsFlags flags) of
Just True -> True
Just False -> False
Nothing -> False
isFreestanding :: S.ConfigFlags -> Bool
isFreestanding flags =
case lookup (FlagName "freestanding") (S.configConfigurationsFlags flags) of
Just True -> True
Just False -> False
Nothing -> False
-- -----------------------------------------------------------------------------
-- Clean
idrisClean _ flags _ _ = cleanStdLib
where
verbosity = S.fromFlag $ S.cleanVerbosity flags
cleanStdLib = makeClean "libs"
makeClean dir = make verbosity [ "-C", dir, "clean", "IDRIS=idris" ]
-- -----------------------------------------------------------------------------
-- Configure
gitHash :: IO String
gitHash = do h <- Control.Exception.catch (readProcess "git" ["rev-parse", "--short", "HEAD"] "")
(\e -> let e' = (e :: SomeException) in return "PRE")
return $ takeWhile (/= '\n') h
-- Put the Git hash into a module for use in the program
-- For release builds, just put the empty string in the module
generateVersionModule verbosity dir release = do
hash <- gitHash
let versionModulePath = dir </> "Version_idris" Px.<.> "hs"
putStrLn $ "Generating " ++ versionModulePath ++
if release then " for release" else " for prerelease " ++ hash
createDirectoryIfMissingVerbose verbosity True dir
rewriteFile versionModulePath (versionModuleContents hash)
where versionModuleContents h = "module Version_idris where\n\n" ++
"gitHash :: String\n" ++
if release
then "gitHash = \"\"\n"
else "gitHash = \"git:" ++ h ++ "\"\n"
-- Generate a module that contains the lib path for a freestanding Idris
generateTargetModule verbosity dir targetDir = do
let absPath = isAbsolute targetDir
let targetModulePath = dir </> "Target_idris" Px.<.> "hs"
putStrLn $ "Generating " ++ targetModulePath
createDirectoryIfMissingVerbose verbosity True dir
rewriteFile targetModulePath (versionModuleContents absPath targetDir)
where versionModuleContents absolute td = "module Target_idris where\n\n" ++
"import System.FilePath\n" ++
"import System.Environment\n" ++
"getDataDir :: IO String\n" ++
if absolute
then "getDataDir = return \"" ++ td ++ "\"\n"
else "getDataDir = do \n" ++
" expath <- getExecutablePath\n" ++
" execDir <- return $ dropFileName expath\n" ++
" return $ execDir ++ \"" ++ td ++ "\"\n"
++ "getDataFileName :: FilePath -> IO FilePath\n"
++ "getDataFileName name = do\n"
++ " dir <- getDataDir\n"
++ " return (dir ++ \"/\" ++ name)"
-- a module that has info about existence and location of a bundled toolchain
generateToolchainModule verbosity srcDir toolDir = do
let commonContent = "module Tools_idris where\n\n"
let toolContent = case toolDir of
Just dir -> "hasBundledToolchain = True\n" ++
"getToolchainDir = \"" ++ dir ++ "\"\n"
Nothing -> "hasBundledToolchain = False\n" ++
"getToolchainDir = \"\""
let toolPath = srcDir </> "Tools_idris" Px.<.> "hs"
createDirectoryIfMissingVerbose verbosity True srcDir
rewriteFile toolPath (commonContent ++ toolContent)
idrisConfigure _ flags _ local = do
configureRTS
generateVersionModule verbosity (autogenModulesDir local) (isRelease (configFlags local))
if isFreestanding $ configFlags local
then do
toolDir <- lookupEnv "IDRIS_TOOLCHAIN_DIR"
generateToolchainModule verbosity (autogenModulesDir local) toolDir
targetDir <- lookupEnv "IDRIS_LIB_DIR"
case targetDir of
Just d -> generateTargetModule verbosity (autogenModulesDir local) d
Nothing -> error $ "Trying to build freestanding without a target directory."
++ " Set it by defining IDRIS_LIB_DIR."
else
generateToolchainModule verbosity (autogenModulesDir local) Nothing
where
verbosity = S.fromFlag $ S.configVerbosity flags
version = pkgVersion . package $ localPkgDescr local
-- This is a hack. I don't know how to tell cabal that a data file needs
-- installing but shouldn't be in the distribution. And it won't make the
-- distribution if it's not there, so instead I just delete
-- the file after configure.
configureRTS = make verbosity ["-C", "rts", "clean"]
idrisPreSDist args flags = do
let dir = S.fromFlag (S.sDistDirectory flags)
let verb = S.fromFlag (S.sDistVerbosity flags)
generateVersionModule verb "src" True
generateTargetModule verb "src" "./libs"
generateToolchainModule verb "src" Nothing
preSDist simpleUserHooks args flags
idrisSDist sdist pkgDesc bi hooks flags = do
pkgDesc' <- addGitFiles pkgDesc
sdist pkgDesc' bi hooks flags
where
addGitFiles :: PackageDescription -> IO PackageDescription
addGitFiles pkgDesc = do
files <- gitFiles
return $ pkgDesc { extraSrcFiles = extraSrcFiles pkgDesc ++ files}
gitFiles :: IO [FilePath]
gitFiles = liftM lines (readProcess "git" ["ls-files"] "")
idrisPostSDist args flags desc lbi = do
Control.Exception.catch (do let file = "src" </> "Version_idris" Px.<.> "hs"
let targetFile = "src" </> "Target_idris" Px.<.> "hs"
putStrLn $ "Removing generated modules:\n "
++ file ++ "\n" ++ targetFile
removeFile file
removeFile targetFile)
(\e -> let e' = (e :: SomeException) in return ())
postSDist simpleUserHooks args flags desc lbi
-- -----------------------------------------------------------------------------
-- Build
getVersion :: Args -> S.BuildFlags -> IO HookedBuildInfo
getVersion args flags = do
hash <- gitHash
let buildinfo = (emptyBuildInfo { cppOptions = ["-DVERSION="++hash] }) :: BuildInfo
return (Just buildinfo, [])
idrisPreBuild args flags = do
#ifdef mingw32_HOST_OS
createDirectoryIfMissingVerbose verbosity True dir
windres verbosity ["icons/idris_icon.rc","-o", dir++"/idris_icon.o"]
return (Nothing, [("idris", emptyBuildInfo { ldOptions = [dir ++ "/idris_icon.o"] })])
where
verbosity = S.fromFlag $ S.buildVerbosity flags
dir = S.fromFlagOrDefault "dist" $ S.buildDistPref flags
#else
return (Nothing, [])
#endif
idrisBuild _ flags _ local = unless (execOnly (configFlags local)) $ do
buildStdLib
buildRTS
where
verbosity = S.fromFlag $ S.buildVerbosity flags
buildStdLib = do
putStrLn "Building libraries..."
makeBuild "libs"
where
makeBuild dir = make verbosity [ "-C", dir, "build" , "IDRIS=" ++ idrisCmd local]
buildRTS = make verbosity (["-C", "rts", "build"] ++
gmpflag (usesGMP (configFlags local)))
gmpflag False = []
gmpflag True = ["GMP=-DIDRIS_GMP"]
-- -----------------------------------------------------------------------------
-- Copy/Install
idrisInstall verbosity copy pkg local = unless (execOnly (configFlags local)) $ do
installStdLib
installRTS
installManPage
where
target = datadir $ L.absoluteInstallDirs pkg local copy
installStdLib = do
let target' = target -- </> "libs"
putStrLn $ "Installing libraries in " ++ target'
makeInstall "libs" target'
installRTS = do
let target' = target </> "rts"
putStrLn $ "Installing run time system in " ++ target'
makeInstall "rts" target'
installManPage = do
let mandest = mandir (L.absoluteInstallDirs pkg local copy) ++ "/man1"
notice verbosity $ unwords ["Copying man page to", mandest]
installOrdinaryFiles verbosity mandest [("man", "idris.1")]
makeInstall src target =
make verbosity [ "-C", src, "install" , "TARGET=" ++ target, "IDRIS=" ++ idrisCmd local]
-- -----------------------------------------------------------------------------
-- Test
-- There are two "dataDir" in cabal, and they don't relate to each other.
-- When fetching modules, idris uses the second path (in the pkg record),
-- which by default is the root folder of the project.
-- We want it to be the install directory where we put the idris libraries.
fixPkg pkg target = pkg { dataDir = target }
idrisTestHook args pkg local hooks flags = do
let target = datadir $ L.absoluteInstallDirs pkg local NoCopyDest
testHook simpleUserHooks args (fixPkg pkg target) local hooks flags
-- -----------------------------------------------------------------------------
-- Main
-- Install libraries during both copy and install
-- See https://github.com/haskell/cabal/issues/709
main = defaultMainWithHooks $ simpleUserHooks
{ postClean = idrisClean
, postConf = idrisConfigure
, preBuild = idrisPreBuild
, postBuild = idrisBuild
, postCopy = \_ flags pkg local ->
idrisInstall (S.fromFlag $ S.copyVerbosity flags)
(S.fromFlag $ S.copyDest flags) pkg local
, postInst = \_ flags pkg local ->
idrisInstall (S.fromFlag $ S.installVerbosity flags)
NoCopyDest pkg local
, preSDist = idrisPreSDist
, sDistHook = idrisSDist (sDistHook simpleUserHooks)
, postSDist = idrisPostSDist
, testHook = idrisTestHook
}
|
Heather/Idris-dev
|
Setup.hs
|
Haskell
|
bsd-3-clause
| 12,556
|
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.ScreenCorners
-- Copyright : (c) 2009 Nils Schweinsberg, 2015 Evgeny Kurnevsky
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Nils Schweinsberg <mail@n-sch.de>
-- Stability : unstable
-- Portability : unportable
--
-- Run @X ()@ actions by touching the edge of your screen with your mouse.
--
-----------------------------------------------------------------------------
module XMonad.Hooks.ScreenCorners
(
-- * Usage
-- $usage
-- * Adding screen corners
ScreenCorner (..)
, addScreenCorner
, addScreenCorners
-- * Event hook
, screenCornerEventHook
-- * Layout hook
, screenCornerLayoutHook
) where
import Data.Monoid
import Data.List (find)
import XMonad
import XMonad.Util.XUtils (fi)
import XMonad.Layout.LayoutModifier
import qualified Data.Map as M
import qualified XMonad.Util.ExtensibleState as XS
data ScreenCorner = SCUpperLeft
| SCUpperRight
| SCLowerLeft
| SCLowerRight
deriving (Eq, Ord, Show)
--------------------------------------------------------------------------------
-- ExtensibleState modifications
--------------------------------------------------------------------------------
newtype ScreenCornerState = ScreenCornerState (M.Map Window (ScreenCorner, X ()))
deriving Typeable
instance ExtensionClass ScreenCornerState where
initialValue = ScreenCornerState M.empty
-- | Add one single @X ()@ action to a screen corner
addScreenCorner :: ScreenCorner -> X () -> X ()
addScreenCorner corner xF = do
ScreenCornerState m <- XS.get
(win,xFunc) <- case find (\(_,(sc,_)) -> sc == corner) (M.toList m) of
Just (w, (_,xF')) -> return (w, xF' >> xF) -- chain X actions
Nothing -> flip (,) xF `fmap` createWindowAt corner
XS.modify $ \(ScreenCornerState m') -> ScreenCornerState $ M.insert win (corner,xFunc) m'
-- | Add a list of @(ScreenCorner, X ())@ tuples
addScreenCorners :: [ (ScreenCorner, X ()) ] -> X ()
addScreenCorners = mapM_ (\(corner, xF) -> addScreenCorner corner xF)
--------------------------------------------------------------------------------
-- Xlib functions
--------------------------------------------------------------------------------
-- "Translate" a ScreenCorner to real (x,y) Positions
createWindowAt :: ScreenCorner -> X Window
createWindowAt SCUpperLeft = createWindowAt' 0 0
createWindowAt SCUpperRight = withDisplay $ \dpy ->
let w = displayWidth dpy (defaultScreen dpy) - 1
in createWindowAt' (fi w) 0
createWindowAt SCLowerLeft = withDisplay $ \dpy ->
let h = displayHeight dpy (defaultScreen dpy) - 1
in createWindowAt' 0 (fi h)
createWindowAt SCLowerRight = withDisplay $ \dpy ->
let w = displayWidth dpy (defaultScreen dpy) - 1
h = displayHeight dpy (defaultScreen dpy) - 1
in createWindowAt' (fi w) (fi h)
-- Create a new X window at a (x,y) Position
createWindowAt' :: Position -> Position -> X Window
createWindowAt' x y = withDisplay $ \dpy -> io $ do
rootw <- rootWindow dpy (defaultScreen dpy)
let
visual = defaultVisualOfScreen $ defaultScreenOfDisplay dpy
attrmask = cWOverrideRedirect
w <- allocaSetWindowAttributes $ \attributes -> do
set_override_redirect attributes True
createWindow dpy -- display
rootw -- parent window
x -- x
y -- y
1 -- width
1 -- height
0 -- border width
0 -- depth
inputOnly -- class
visual -- visual
attrmask -- valuemask
attributes -- attributes
-- we only need mouse entry events
selectInput dpy w enterWindowMask
mapWindow dpy w
sync dpy False
return w
--------------------------------------------------------------------------------
-- Event hook
--------------------------------------------------------------------------------
-- | Handle screen corner events
screenCornerEventHook :: Event -> X All
screenCornerEventHook CrossingEvent { ev_window = win } = do
ScreenCornerState m <- XS.get
case M.lookup win m of
Just (_, xF) -> xF
Nothing -> return ()
return (All True)
screenCornerEventHook _ = return (All True)
--------------------------------------------------------------------------------
-- Layout hook
--------------------------------------------------------------------------------
data ScreenCornerLayout a = ScreenCornerLayout
deriving ( Read, Show )
instance LayoutModifier ScreenCornerLayout a where
hook ScreenCornerLayout = withDisplay $ \dpy -> do
ScreenCornerState m <- XS.get
io $ mapM_ (raiseWindow dpy) $ M.keys m
unhook = hook
screenCornerLayoutHook :: l a -> ModifiedLayout ScreenCornerLayout l a
screenCornerLayoutHook = ModifiedLayout ScreenCornerLayout
--------------------------------------------------------------------------------
-- $usage
--
-- This extension adds KDE-like screen corners to XMonad. By moving your cursor
-- into one of your screen corners you can trigger an @X ()@ action, for
-- example @"XMonad.Actions.GridSelect".goToSelected@ or
-- @"XMonad.Actions.CycleWS".nextWS@ etc.
--
-- To use it, import it on top of your @xmonad.hs@:
--
-- > import XMonad.Hooks.ScreenCorners
--
-- Then add your screen corners in our startup hook:
--
-- > myStartupHook = do
-- > ...
-- > addScreenCorner SCUpperRight (goToSelected defaultGSConfig { gs_cellwidth = 200})
-- > addScreenCorners [ (SCLowerRight, nextWS)
-- > , (SCLowerLeft, prevWS)
-- > ]
--
-- Then add layout hook:
--
-- > myLayout = screenCornerLayoutHook $ tiled ||| Mirror tiled ||| Full where
-- > tiled = Tall nmaster delta ratio
-- > nmaster = 1
-- > ratio = 1 / 2
-- > delta = 3 / 100
--
-- And finally wait for screen corner events in your event hook:
--
-- > myEventHook e = do
-- > ...
-- > screenCornerEventHook e
|
CaptainPatate/xmonad-contrib
|
XMonad/Hooks/ScreenCorners.hs
|
Haskell
|
bsd-3-clause
| 6,431
|
{-# LANGUAGE RankNTypes, TypeFamilies #-}
-- Unification yielding a coercion under a forall
module Data.Vector.Unboxed where
import Control.Monad.ST ( ST )
import Data.Kind (Type)
data MVector s a = MV
data Vector a = V
type family Mutable (v :: Type -> Type) :: Type -> Type -> Type
type instance Mutable Vector = MVector
create :: (forall s. MVector s a) -> Int
create = create1
-- Here we get Couldn't match expected type `forall s. MVector s a'
-- with actual type `forall s. Mutable Vector s a1'
-- Reason: when unifying under a for-all we don't solve type
-- equalities. Think more about this.
create1 :: (forall s. Mutable Vector s a) -> Int
create1 _ = error "urk"
|
sdiehl/ghc
|
testsuite/tests/indexed-types/should_compile/T4120.hs
|
Haskell
|
bsd-3-clause
| 719
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
module Aws.Iam.Commands.DeleteUserPolicy
( DeleteUserPolicy(..)
, DeleteUserPolicyResponse(..)
) where
import Aws.Core
import Aws.Iam.Core
import Aws.Iam.Internal
import Data.Text (Text)
import Data.Typeable
-- | Deletes the specified policy associated with the specified user.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteUserPolicy.html>
data DeleteUserPolicy
= DeleteUserPolicy {
dupPolicyName :: Text
-- ^ Name of the policy to be deleted.
, dupUserName :: Text
-- ^ Name of the user with whom the policy is associated.
}
deriving (Eq, Ord, Show, Typeable)
instance SignQuery DeleteUserPolicy where
type ServiceConfiguration DeleteUserPolicy = IamConfiguration
signQuery DeleteUserPolicy{..}
= iamAction "DeleteUserPolicy" [
("PolicyName", dupPolicyName)
, ("UserName", dupUserName)
]
data DeleteUserPolicyResponse = DeleteUserPolicyResponse
deriving (Eq, Ord, Show, Typeable)
instance ResponseConsumer DeleteUserPolicy DeleteUserPolicyResponse where
type ResponseMetadata DeleteUserPolicyResponse = IamMetadata
responseConsumer _ = iamResponseConsumer (const $ return DeleteUserPolicyResponse)
instance Transaction DeleteUserPolicy DeleteUserPolicyResponse
instance AsMemoryResponse DeleteUserPolicyResponse where
type MemoryResponse DeleteUserPolicyResponse = DeleteUserPolicyResponse
loadToMemory = return
|
Soostone/aws
|
Aws/Iam/Commands/DeleteUserPolicy.hs
|
Haskell
|
bsd-3-clause
| 1,647
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash #-}
{-# OPTIONS_HADDOCK hide #-}
module Take (
take0
, take
) where
import Data.Maybe
import GHC.Base
import Language.Haskell.Liquid.Prelude (liquidAssert, liquidError)
{-@ assert take0 :: n: {v: Int | 0 <= v} -> [a] -> {v:[a] | (len(v) = n)} @-}
take0 :: Int -> [a] -> [a]
take0 (I# n#) xs = take_unsafe_UInt0 n# xs
take_unsafe_UInt0 :: Int# -> [a] -> [a]
take_unsafe_UInt0 0# _ = []
take_unsafe_UInt0 n (x:xs) = x : take_unsafe_UInt0 (n -# 1#) xs
take_unsafe_UInt0 _ _ = error "unsafe take"
{-@ assert take :: n: {v: Int | v >= 0 } -> xs:[a] -> {v:[a] | len v = if len xs < n then (len xs) else n } @-}
take (I# n#) xs = takeUInt n# xs
-- take (I# n#) xs = take_unsafe_UInt n# xs
takeUInt :: Int# -> [a] -> [a]
takeUInt n xs
| isTrue# (n >=# 0#) = take_unsafe_UInt n xs
| otherwise = liquidAssert False []
take_unsafe_UInt :: Int# -> [a] -> [a]
take_unsafe_UInt 0# _ = []
take_unsafe_UInt n ls =
case ls of
[] -> []
(x:xs) -> x : take_unsafe_UInt (n -# 1#) xs
|
mightymoose/liquidhaskell
|
tests/pos/take.hs
|
Haskell
|
bsd-3-clause
| 1,130
|
{-# LANGUAGE BangPatterns, OverloadedStrings #-}
-- |
-- Module: Data.Aeson.Parser
-- Copyright: (c) 2012-2015 Bryan O'Sullivan
-- (c) 2011 MailRank, Inc.
-- License: Apache
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: experimental
-- Portability: portable
--
-- Efficiently and correctly parse a JSON string. The string must be
-- encoded as UTF-8.
--
-- It can be useful to think of parsing as occurring in two phases:
--
-- * Identification of the textual boundaries of a JSON value. This
-- is always strict, so that an invalid JSON document can be
-- rejected as soon as possible.
--
-- * Conversion of a JSON value to a Haskell value. This may be
-- either immediate (strict) or deferred (lazy); see below for
-- details.
--
-- The question of whether to choose a lazy or strict parser is
-- subtle, but it can have significant performance implications,
-- resulting in changes in CPU use and memory footprint of 30% to 50%,
-- or occasionally more. Measure the performance of your application
-- with each!
module Data.Aeson.Parser
(
-- * Lazy parsers
-- $lazy
json
, value
, jstring
-- * Strict parsers
-- $strict
, json'
, value'
) where
import Data.Aeson.Parser.Internal (json, json', jstring, value, value')
-- $lazy
--
-- The 'json' and 'value' parsers decouple identification from
-- conversion. Identification occurs immediately (so that an invalid
-- JSON document can be rejected as early as possible), but conversion
-- to a Haskell value is deferred until that value is needed.
--
-- This decoupling can be time-efficient if only a smallish subset of
-- elements in a JSON value need to be inspected, since the cost of
-- conversion is zero for uninspected elements. The trade off is an
-- increase in memory usage, due to allocation of thunks for values
-- that have not yet been converted.
-- $strict
--
-- The 'json'' and 'value'' parsers combine identification with
-- conversion. They consume more CPU cycles up front, but have a
-- smaller memory footprint.
|
abbradar/aeson
|
Data/Aeson/Parser.hs
|
Haskell
|
bsd-3-clause
| 2,097
|
module Resources (
GameData(..)
, Glyph(..)
, Lump(..)
, loadPalette
, loadSignon
, loadGameData
, module WL6
) where
import qualified Data.ByteString as B
import qualified Data.Bitstream as BS
import Data.Binary.Get
import Data.Word
import Graphics.UI.SDL
-- Internal modules import
import Common
import Resources.Configuration as Config
import Resources.Dictionary as Huff
import Resources.Header as Header
import Resources.Map as Map
import Resources.OMF as OMF
import Resources.PageFile as PM
import Resources.Gfxv_wl6 as WL6
import Settings
import Utils
type BitL = BS.Bitstream BS.Left
type BitR = BS.Bitstream BS.Right
--
--
data Lump = Lump { w :: Int
, h :: Int
, pxs :: [Word8]
}
deriving (Show)
data Glyph = Glyph { gWidth :: Int
, gHeight :: Int
, gData :: [Word8]
}
deriving (Show)
--
--
data GameData = GameData { startFont :: [Glyph]
, menuFont :: [Glyph]
, lumps :: [Lump]
, maps :: [MapData]
, swap :: SwapData
}
-- |The 'loadPalette' returns a palette stored into
-- GAMEPAL.OBJ file. Parsing handled by OMF loader.
--
-- The coefficient 4.0 selected as 2^(8-6) bit correction
--
loadPalette :: IO [Color]
loadPalette = do
dat <- OMF.findResource "_gamepal" (gameSrcPath ++ "OBJ/GAMEPAL.OBJ")
return $ wordsToColor dat
where
wordsToColor [] = []
wordsToColor (r:g:b:res) = (Color (fromIntegral r * 4)
(fromIntegral g * 4)
(fromIntegral b * 4)) : wordsToColor res
-- |Loads signOn screen from the SIGNON.OBJ file.
-- Parsing handled by OMF loader.
--
loadSignon :: IO [Word8]
loadSignon = OMF.findResource "_signon" (gameSrcPath ++ "OBJ/SIGNON.OBJ")
-- @todo some kinds of chunks have implicit size (see STARTTILE8M for example)
-- @todo huffman returns *more* data than expected. Now I put 'take' here to
-- truncate, but think it's better to find a reason why it happens
--
unpackChunk :: Int -> Dictionary -> [ChunkHead] -> B.ByteString -> [Word8]
unpackChunk chunkId dict heads gtData = take unp_size unp_data
where
(ofst, comp_size) = heads !! chunkId
data_seg = B.drop (fromIntegral ofst) gtData
unp_size = bytesToInt . B.unpack . B.take 4 $ data_seg
comp_data = B.take comp_size . B.drop 4 $ data_seg
unp_data = Huff.decode dict $ BS.unpack (BS.fromByteString comp_data :: BitL)
--
--
buildPicTable :: [Word8] -> [(Int, Int)]
buildPicTable [] = []
buildPicTable (wLo:wHi:hLo:hHi:xs) =
(bytesToInt [wLo, wHi], bytesToInt [hLo, hHi]) : buildPicTable xs
-- @kludge rework it ASAP!
--
buildFont :: [Word8] -> [Glyph]
buildFont (hLo:hHi:xs) =
map (\(o, w) -> Glyph w h (take (w * h) . drop (o - 770) $ d)) $ zip ofs ws
where
ofs = map2 bytesToInt $ take (256 * 2) xs
ws = map fromIntegral $ take 256 . drop (256 * 2) $ xs
d = drop (256 * 3) xs
h = bytesToInt [hLo, hHi]
map2 _ [] = []
map2 f (x:y:xs) = (f [x,y]) : map2 f xs
-- |Rebuilds 4x4-planes image into common pixel format
-- All credits go to Constantine Zakharchenko for his
-- brilliant idea of transformation
--
rebuildLump :: Lump -> Lump
rebuildLump (Lump w h pxs) = Lump w h (shuffle pxs)
where
shuffle = riffle . riffle
where
split pxs = splitAt ((length pxs) `div` 2) pxs
merge ( [], []) = []
merge (f:fs, s:ss) = f:s:merge (fs, ss)
riffle ar = merge (split ar)
-- | Process game resources and builds internal structures
--
loadGameData :: BuildVariant -> IO GameData
loadGameData v = do
-- cache game data
grCache <- B.readFile $ gameBinPath ++ "VGAGRAPH" ++ gameBinExt v
hdCache <- B.readFile $ gameBinPath ++ "VGAHEAD" ++ gameBinExt v
dictCache <- B.readFile $ gameBinPath ++ "VGADICT" ++ gameBinExt v
mapHdr <- B.readFile $ gameBinPath ++ "MAPHEAD" ++ gameBinExt v
mapData <- B.readFile $ gameBinPath ++ "GAMEMAPS" ++ gameBinExt v
pageData <- B.readFile $ gameBinPath ++ "VSWAP" ++ gameBinExt v
let
dict = Huff.loadDictionary dictCache
heads = Header.loadHeader hdCache
pictable = buildPicTable $ unpackChunk (fromEnum WL6.STRUCTPIC) dict heads grCache
startfont = buildFont $ unpackChunk (fromEnum WL6.STARTFONT) dict heads grCache
menufont = buildFont $ unpackChunk ((fromEnum WL6.STARTFONT) + 1) dict heads grCache
lumps = map (\(n, (w, h)) -> rebuildLump $ Lump w h (unpackChunk n dict heads grCache)) $
zip [3..] pictable
maps = Map.loadData mapData mapHdr
swap = PM.loadData pageData
return $
GameData startfont
menufont
lumps
maps
swap
|
vTurbine/w3dhs
|
src/Resources.hs
|
Haskell
|
mit
| 5,377
|
-----------------------------------------------------------------------------
--
-- Module : Graphics.GPipe.Orphans
-- Copyright : Tobias Bexelius
-- License : MIT
--
-- Maintainer : Tobias Bexelius
-- Stability : Experimental
-- Portability : Portable
--
-- |
-- Orphan boolean instances for linear types. These are placed in a separate module so you can choose to not import them
-- (in that case, do not import the @Graphics.GPipe@ conveniance module but take all sub modules instead, leaving this one out).
-----------------------------------------------------------------------------
module Graphics.GPipe.Orphans where
import Graphics.GPipe.Internal.Orphans
|
Teaspot-Studio/GPipe-Core
|
src/Graphics/GPipe/Orphans.hs
|
Haskell
|
mit
| 687
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
module Codec.Xlsx.Types (
-- * The main types
Xlsx(..)
, Styles(..)
, DefinedNames(..)
, ColumnsProperties(..)
, PageSetup(..)
, Worksheet(..)
, CellMap
, CellValue(..)
, CellFormula(..)
, FormulaExpression(..)
, Cell.SharedFormulaIndex(..)
, Cell.SharedFormulaOptions(..)
, Cell(..)
, RowHeight(..)
, RowProperties (..)
-- * Lenses
-- ** Workbook
, xlSheets
, xlStyles
, xlDefinedNames
, xlCustomProperties
, xlDateBase
-- ** Worksheet
, wsColumnsProperties
, wsRowPropertiesMap
, wsCells
, wsDrawing
, wsMerges
, wsSheetViews
, wsPageSetup
, wsConditionalFormattings
, wsDataValidations
, wsPivotTables
, wsAutoFilter
, wsTables
, wsProtection
, wsSharedFormulas
-- ** Cells
, Cell.cellValue
, Cell.cellStyle
, Cell.cellComment
, Cell.cellFormula
-- * Style helpers
, emptyStyles
, renderStyleSheet
, parseStyleSheet
-- * Misc
, simpleCellFormula
, sharedFormulaByIndex
, def
, toRows
, fromRows
, module X
) where
import Control.Exception (SomeException, toException)
#ifdef USE_MICROLENS
import Lens.Micro.TH
#else
import Control.Lens.TH
#endif
import Control.DeepSeq (NFData)
import qualified Data.ByteString.Lazy as L
import Data.Default
import Data.Function (on)
import Data.List (groupBy)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe (catMaybes, isJust)
import Data.Text (Text)
import GHC.Generics (Generic)
import Text.XML (parseLBS, renderLBS)
import Text.XML.Cursor
import Codec.Xlsx.Parser.Internal
import Codec.Xlsx.Types.AutoFilter as X
import Codec.Xlsx.Types.Cell as Cell
import Codec.Xlsx.Types.Comment as X
import Codec.Xlsx.Types.Common as X
import Codec.Xlsx.Types.ConditionalFormatting as X
import Codec.Xlsx.Types.DataValidation as X
import Codec.Xlsx.Types.Drawing as X
import Codec.Xlsx.Types.Drawing.Chart as X
import Codec.Xlsx.Types.Drawing.Common as X
import Codec.Xlsx.Types.PageSetup as X
import Codec.Xlsx.Types.PivotTable as X
import Codec.Xlsx.Types.Protection as X
import Codec.Xlsx.Types.RichText as X
import Codec.Xlsx.Types.SheetViews as X
import Codec.Xlsx.Types.StyleSheet as X
import Codec.Xlsx.Types.Table as X
import Codec.Xlsx.Types.Variant as X
import Codec.Xlsx.Writer.Internal
-- | Height of a row in points (1/72in)
data RowHeight
= CustomHeight !Double
-- ^ Row height is set by the user
| AutomaticHeight !Double
-- ^ Row height is set automatically by the program
deriving (Eq, Ord, Show, Read, Generic)
instance NFData RowHeight
-- | Properties of a row. See §18.3.1.73 "row (Row)" for more details
data RowProperties = RowProps
{ rowHeight :: Maybe RowHeight
-- ^ Row height in points
, rowStyle :: Maybe Int
-- ^ Style to be applied to row
, rowHidden :: Bool
-- ^ Whether row is visible or not
} deriving (Eq, Ord, Show, Read, Generic)
instance NFData RowProperties
instance Default RowProperties where
def = RowProps { rowHeight = Nothing
, rowStyle = Nothing
, rowHidden = False
}
-- | Column range (from cwMin to cwMax) properties
data ColumnsProperties = ColumnsProperties
{ cpMin :: Int
-- ^ First column affected by this 'ColumnWidth' record.
, cpMax :: Int
-- ^ Last column affected by this 'ColumnWidth' record.
, cpWidth :: Maybe Double
-- ^ Column width measured as the number of characters of the
-- maximum digit width of the numbers 0, 1, 2, ..., 9 as rendered in
-- the normal style's font.
--
-- See longer description in Section 18.3.1.13 "col (Column Width &
-- Formatting)" (p. 1605)
, cpStyle :: Maybe Int
-- ^ Default style for the affected column(s). Affects cells not yet
-- allocated in the column(s). In other words, this style applies
-- to new columns.
, cpHidden :: Bool
-- ^ Flag indicating if the affected column(s) are hidden on this
-- worksheet.
, cpCollapsed :: Bool
-- ^ Flag indicating if the outlining of the affected column(s) is
-- in the collapsed state.
, cpBestFit :: Bool
-- ^ Flag indicating if the specified column(s) is set to 'best
-- fit'.
} deriving (Eq, Show, Generic)
instance NFData ColumnsProperties
instance FromCursor ColumnsProperties where
fromCursor c = do
cpMin <- fromAttribute "min" c
cpMax <- fromAttribute "max" c
cpWidth <- maybeAttribute "width" c
cpStyle <- maybeAttribute "style" c
cpHidden <- fromAttributeDef "hidden" False c
cpCollapsed <- fromAttributeDef "collapsed" False c
cpBestFit <- fromAttributeDef "bestFit" False c
return ColumnsProperties {..}
instance FromXenoNode ColumnsProperties where
fromXenoNode root = parseAttributes root $ do
cpMin <- fromAttr "min"
cpMax <- fromAttr "max"
cpWidth <- maybeAttr "width"
cpStyle <- maybeAttr "style"
cpHidden <- fromAttrDef "hidden" False
cpCollapsed <- fromAttrDef "collapsed" False
cpBestFit <- fromAttrDef "bestFit" False
return ColumnsProperties {..}
-- | Xlsx worksheet
data Worksheet = Worksheet
{ _wsColumnsProperties :: [ColumnsProperties] -- ^ column widths
, _wsRowPropertiesMap :: Map Int RowProperties -- ^ custom row properties (height, style) map
, _wsCells :: CellMap -- ^ data mapped by (row, column) pairs
, _wsDrawing :: Maybe Drawing -- ^ SpreadsheetML Drawing
, _wsMerges :: [Range] -- ^ list of cell merges
, _wsSheetViews :: Maybe [SheetView]
, _wsPageSetup :: Maybe PageSetup
, _wsConditionalFormattings :: Map SqRef ConditionalFormatting
, _wsDataValidations :: Map SqRef DataValidation
, _wsPivotTables :: [PivotTable]
, _wsAutoFilter :: Maybe AutoFilter
, _wsTables :: [Table]
, _wsProtection :: Maybe SheetProtection
, _wsSharedFormulas :: Map SharedFormulaIndex SharedFormulaOptions
} deriving (Eq, Show, Generic)
instance NFData Worksheet
makeLenses ''Worksheet
instance Default Worksheet where
def =
Worksheet
{ _wsColumnsProperties = []
, _wsRowPropertiesMap = M.empty
, _wsCells = M.empty
, _wsDrawing = Nothing
, _wsMerges = []
, _wsSheetViews = Nothing
, _wsPageSetup = Nothing
, _wsConditionalFormattings = M.empty
, _wsDataValidations = M.empty
, _wsPivotTables = []
, _wsAutoFilter = Nothing
, _wsTables = []
, _wsProtection = Nothing
, _wsSharedFormulas = M.empty
}
-- | Raw worksheet styles, for structured implementation see 'StyleSheet'
-- and functions in "Codec.Xlsx.Types.StyleSheet"
newtype Styles = Styles {unStyles :: L.ByteString}
deriving (Eq, Show, Generic)
instance NFData Styles
-- | Structured representation of Xlsx file (currently a subset of its contents)
data Xlsx = Xlsx
{ _xlSheets :: [(Text, Worksheet)]
, _xlStyles :: Styles
, _xlDefinedNames :: DefinedNames
, _xlCustomProperties :: Map Text Variant
, _xlDateBase :: DateBase
-- ^ date base to use when converting serial value (i.e. 'CellDouble d')
-- into date-time. Default value is 'DateBase1900'
--
-- See also 18.17.4.1 "Date Conversion for Serial Date-Times" (p. 2067)
} deriving (Eq, Show, Generic)
instance NFData Xlsx
-- | Defined names
--
-- Each defined name consists of a name, an optional local sheet ID, and a value.
--
-- This element defines the collection of defined names for this workbook.
-- Defined names are descriptive names to represent cells, ranges of cells,
-- formulas, or constant values. Defined names can be used to represent a range
-- on any worksheet.
--
-- Excel also defines a number of reserved names with a special interpretation:
--
-- * @_xlnm.Print_Area@ specifies the workbook's print area.
-- Example value: @SheetName!$A:$A,SheetName!$1:$4@
-- * @_xlnm.Print_Titles@ specifies the row(s) or column(s) to repeat
-- at the top of each printed page.
-- * @_xlnm.Sheet_Title@:refers to a sheet title.
--
-- and others. See Section 18.2.6, "definedNames (Defined Names)" (p. 1728) of
-- the spec (second edition).
--
-- NOTE: Right now this is only a minimal implementation of defined names.
newtype DefinedNames = DefinedNames [(Text, Maybe Text, Text)]
deriving (Eq, Show, Generic)
instance NFData DefinedNames
makeLenses ''Xlsx
instance Default Xlsx where
def = Xlsx [] emptyStyles def M.empty DateBase1900
instance Default DefinedNames where
def = DefinedNames []
emptyStyles :: Styles
emptyStyles = Styles "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"></styleSheet>"
-- | Render 'StyleSheet'
--
-- This is used to render a structured 'StyleSheet' into a raw XML 'Styles'
-- document. Actually /replacing/ 'Styles' with 'StyleSheet' would mean we
-- would need to write a /parser/ for 'StyleSheet' as well (and would moreover
-- require that we support the full style sheet specification, which is still
-- quite a bit of work).
renderStyleSheet :: StyleSheet -> Styles
renderStyleSheet = Styles . renderLBS def . toDocument
-- | Parse 'StyleSheet'
--
-- This is used to parse raw 'Styles' into structured 'StyleSheet'
-- currently not all of the style sheet specification is supported
-- so parser (and the data model) is to be completed
parseStyleSheet :: Styles -> Either SomeException StyleSheet
parseStyleSheet (Styles bs) = parseLBS def bs >>= parseDoc
where
parseDoc doc = case fromCursor (fromDocument doc) of
[stylesheet] -> Right stylesheet
_ -> Left . toException $ ParseException "Could not parse style sheets"
-- | converts cells mapped by (row, column) into rows which contain
-- row index and cells as pairs of column indices and cell values
toRows :: CellMap -> [(Int, [(Int, Cell)])]
toRows cells =
map extractRow $ groupBy ((==) `on` (fst . fst)) $ M.toList cells
where
extractRow row@(((x,_),_):_) =
(x, map (\((_,y),v) -> (y,v)) row)
extractRow _ = error "invalid CellMap row"
-- | reverse to 'toRows'
fromRows :: [(Int, [(Int, Cell)])] -> CellMap
fromRows rows = M.fromList $ concatMap mapRow rows
where
mapRow (r, cells) = map (\(c, v) -> ((r, c), v)) cells
instance ToElement ColumnsProperties where
toElement nm ColumnsProperties {..} = leafElement nm attrs
where
attrs =
["min" .= cpMin, "max" .= cpMax] ++
catMaybes
[ "style" .=? (justNonDef 0 =<< cpStyle)
, "width" .=? cpWidth
, "customWidth" .=? justTrue (isJust cpWidth)
, "hidden" .=? justTrue cpHidden
, "collapsed" .=? justTrue cpCollapsed
, "bestFit" .=? justTrue cpBestFit
]
|
qrilka/xlsx
|
src/Codec/Xlsx/Types.hs
|
Haskell
|
mit
| 10,888
|
module Example15 where
import qualified WeightedLPA as WLPA
import Graph
import qualified Data.Map as M
import qualified Data.Set as S
import Polynomial
import LaurentPolynomial
weighted_graph_F :: WeightedGraph String String
weighted_graph_F = WeightedGraph (buildGraphFromEdges [("e",("v","u")),("f",("v","u")),("g",("u","v")),("h",("u","v"))]) (M.fromList [("e",1),("f",2),("g",1),("h",2)])
weighted_graph_G :: WeightedGraph String String
weighted_graph_G = WeightedGraph (buildGraphFromEdges [("e",("v","u")),("f",("v","u"))]) (M.fromList [("e",1),("f",2)])
atom = WLPA.Atom 1
vertex = atom . WLPA.vertex
edge = atom . (flip WLPA.edge 1)
ghostEdge = atom . (flip WLPA.ghostEdge 1)
edge2 = atom . (flip WLPA.edge 2)
ghostEdge2 = atom . (flip WLPA.ghostEdge 2)
s = WLPA.adjoint
v = vertex "v"
u = vertex "u"
e1 = edge "e"
f1 = edge "f"
f2 = edge2 "f"
g1 = edge "g"
h1 = edge "h"
h2 = edge2 "h"
z = LaurentPolynomial (constant WLPA.Zero) 0
c y = LaurentPolynomial (constant y) 0
x y = LaurentPolynomial (constant y) 1
adjoint isZero m = (reverseLaurentPolynomial isZero . fmap (WLPA.adjoint)) m
--phi :: WLPA.AtomType String String -> Matrix2x2 (LaurentPolynomial (WLPA.Term String String Integer))
phi (WLPA.AVertex "u") = c u
phi (WLPA.AVertex "v") = c v
phi (WLPA.AEdge "e" 1) = x e1
phi (WLPA.AEdge "f" 1) = x f1
phi (WLPA.AEdge "f" 2) = x f2
phi (WLPA.AEdge "g" 1) = x (s f2)
phi (WLPA.AEdge "h" 1) = x (s f1)
phi (WLPA.AEdge "h" 2) = x (s e1)
phi (WLPA.AGhostEdge e w) = (adjoint isZero) (phi (WLPA.AEdge e w))
where isZero = WLPA.equal_wrt_graph weighted_graph_G WLPA.Zero
phi _ = z
testHomomorphism :: [LaurentPolynomial (WLPA.Term String String Integer)]
testHomomorphism = WLPA.wLPA_relations_map phi weighted_graph_F
fmapBasisForm wgraph = fmap (WLPA.convertToBasisForm wgraph)
check = map (fmapBasisForm weighted_graph_G) testHomomorphism
main = putStrLn$unlines$map show check
{-
wLPA_relations_show wg = wLPA_relations_map (Atom 1) wg
wLPA_relations_present f wgraph rgraph = do
let check = wLPA_relations_check f wgraph rgraph
let relations = wLPA_relations_show wgraph
putStr $ unlines $ map show $ zip check relations
print (and check)
-}
|
rzil/honours
|
LeavittPathAlgebras/Example15.hs
|
Haskell
|
mit
| 2,186
|
{-# htermination filterFM :: (() -> b -> Bool) -> FiniteMap () b -> FiniteMap () b #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_filterFM_2.hs
|
Haskell
|
mit
| 104
|
{-|
Module : Language.Java.Lexer.Internal
Description : Lexer for Java program.
Copyright : (c) Evan Sebastian 2014
License : MIT
Maintainer : evan.sebastian@u.nus.edu
Stability : experimental
Portability : GHC 7.8.2
This module defines lexer for Java program.
Use lexJava to break a string into a list of 'Token's.
>>> lexJava "public class Main { }"
-}
module Language.Java.Lexer where
import Control.Applicative ((<*), (*>))
import Text.Parsec
import Text.Parsec.Token hiding (identifier, stringLiteral, charLiteral, dot)
import Text.Parsec.String
import Language.Java.Lexer.Internal
import Language.Java.AST
lexJava :: String -> [Token]
lexJava = runTokenizer
nextToken :: Parser Token
nextToken = choice $ map (lexeme javaLexer . try)
[ comm, period, at, lParen, rParen, lSquare, rSquare, lBrace, rBrace,
semiColon, tokNull, tokBool, tokString, tokChar, identOrKeyword,
tokDouble, tokInt, dColon, op ]
tokenize :: Parser [Token]
tokenize = whiteSpace javaLexer *> many nextToken <* eof
runTokenizer :: String -> [Token]
runTokenizer s = case parse tokenize "" s of
Left pe -> error (show pe)
Right toks -> toks
|
evansb/jasper
|
src/Language/Java/Lexer.hs
|
Haskell
|
mit
| 1,207
|
module Mish.Config where
import Mish.HexagonalGrid
data Config =
Config { radius :: Radius
, roomAttempts :: Int
, minRoomRadius :: Int
, maxRoomRadius :: Int
, doubleConnectorChance :: Float
}
deriving Show
defaultConfig :: Config
defaultConfig =
Config { radius = 32
, roomAttempts = 1000
, minRoomRadius = 2
, maxRoomRadius = 4
, doubleConnectorChance = 0.25
}
invalidConfig :: Config -> Maybe String
invalidConfig c
| not roomAttemptsCheck = Just "Room attempts are no good (see if you have a sane value)."
| not largerThanMinimumSize = Just "Bounds too small."
| not roomRadiusCheck = Just "Room radii are no good."
| not doubleConnectorChanceCheck = Just "0.0 <= doubleConnectorChance <= 1.0"
| otherwise = Nothing
where roomAttemptsCheck = roomAttempts c > 20 &&
roomAttempts c < 5000
largerThanMinimumSize = radius c > 5
roomRadiusCheck = minRoomRadius c <= maxRoomRadius c &&
minRoomRadius c >= 1 &&
minRoomRadius c <= (radius c - 2) &&
maxRoomRadius c <= (radius c - 2)
doubleConnectorChanceCheck = doubleConnectorChance c >= 0.0 &&
doubleConnectorChance c <= 1.0
|
halvorgb/mish
|
src/Mish/Config.hs
|
Haskell
|
mit
| 1,507
|
module Rebase.Data.ByteString.Lazy.Internal
(
module Data.ByteString.Lazy.Internal
)
where
import Data.ByteString.Lazy.Internal
|
nikita-volkov/rebase
|
library/Rebase/Data/ByteString/Lazy/Internal.hs
|
Haskell
|
mit
| 131
|
module Feature.AuthSpec where
import Network.Wai (Application)
import Network.HTTP.Types
import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON
import PostgREST.Config.PgVersion (PgVersion, pgVersion112)
import Protolude hiding (get)
import SpecHelper
spec :: PgVersion -> SpecWith ((), Application)
spec actualPgVersion = describe "authorization" $ do
let single = ("Accept","application/vnd.pgrst.object+json")
it "denies access to tables that anonymous does not own" $
get "/authors_only" `shouldRespondWith` (
if actualPgVersion >= pgVersion112 then
[json| {
"hint":null,
"details":null,
"code":"42501",
"message":"permission denied for table authors_only"} |]
else
[json| {
"hint":null,
"details":null,
"code":"42501",
"message":"permission denied for relation authors_only"} |]
)
{ matchStatus = 401
, matchHeaders = ["WWW-Authenticate" <:> "Bearer"]
}
it "denies access to tables that postgrest_test_author does not own" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIn0.Xod-F15qsGL0WhdOCr2j3DdKuTw9QJERVgoFD3vGaWA" in
request methodGet "/private_table" [auth] ""
`shouldRespondWith` (
if actualPgVersion >= pgVersion112 then
[json| {
"hint":null,
"details":null,
"code":"42501",
"message":"permission denied for table private_table"} |]
else
[json| {
"hint":null,
"details":null,
"code":"42501",
"message":"permission denied for relation private_table"} |]
)
{ matchStatus = 403
, matchHeaders = []
}
it "denies execution on functions that anonymous does not own" $
post "/rpc/privileged_hello" [json|{"name": "anonymous"}|] `shouldRespondWith` 401
it "allows execution on a function that postgrest_test_author owns" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIn0.Xod-F15qsGL0WhdOCr2j3DdKuTw9QJERVgoFD3vGaWA" in
request methodPost "/rpc/privileged_hello" [auth] [json|{"name": "jdoe"}|]
`shouldRespondWith` [json|"Privileged hello to jdoe"|]
{ matchStatus = 200
, matchHeaders = [matchContentTypeJson]
}
it "returns jwt functions as jwt tokens" $
request methodPost "/rpc/login" [single]
[json| { "id": "jdoe", "pass": "1234" } |]
`shouldRespondWith` [json| {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xuYW1lIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.KO-0PGp_rU-utcDBP6qwdd-Th2Fk-ICVt01I7QtTDWs"} |]
{ matchStatus = 200
, matchHeaders = [matchContentTypeSingular]
}
it "sql functions can encode custom and standard claims" $
request methodPost "/rpc/jwt_test" [single] "{}"
`shouldRespondWith` [json| {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJqb2UiLCJzdWIiOiJmdW4iLCJhdWQiOiJldmVyeW9uZSIsImV4cCI6MTMwMDgxOTM4MCwibmJmIjoxMzAwODE5MzgwLCJpYXQiOjEzMDA4MTkzODAsImp0aSI6ImZvbyIsInJvbGUiOiJwb3N0Z3Jlc3RfdGVzdCIsImh0dHA6Ly9wb3N0Z3Jlc3QuY29tL2ZvbyI6dHJ1ZX0.G2REtPnOQMUrVRDA9OnkPJTd8R0tf4wdYOlauh1E2Ek"} |]
{ matchStatus = 200
, matchHeaders = [matchContentTypeSingular]
}
it "sql functions can read custom and standard claims variables" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmdW4iLCJqdGkiOiJmb28iLCJuYmYiOjEzMDA4MTkzODAsImV4cCI6OTk5OTk5OTk5OSwiaHR0cDovL3Bvc3RncmVzdC5jb20vZm9vIjp0cnVlLCJpc3MiOiJqb2UiLCJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWF0IjoxMzAwODE5MzgwfQ.V5fEpXfpb7feqwVqlcDleFdKu86bdwU2cBRT4fcMhXg"
request methodPost "/rpc/reveal_big_jwt" [auth] "{}"
`shouldRespondWith` [json|[{"iss":"joe","sub":"fun","exp":9999999999,"nbf":1300819380,"iat":1300819380,"jti":"foo","http://postgrest.com/foo":true}]|]
it "allows users with permissions to see their tables" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.B-lReuGNDwAlU1GOC476MlO0vAt9JNoHIlxg2vwMaO0"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
it "works with tokens which have extra fields" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIiwia2V5MSI6InZhbHVlMSIsImtleTIiOiJ2YWx1ZTIiLCJrZXkzIjoidmFsdWUzIiwiYSI6MSwiYiI6MiwiYyI6M30.b0eglDKYEmGi-hCvD-ddSqFl7vnDO5qkUaviaHXm3es"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
-- this test will stop working 9999999999s after the UNIX EPOCH
it "succeeds with an unexpired token" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjk5OTk5OTk5OTksInJvbGUiOiJwb3N0Z3Jlc3RfdGVzdF9hdXRob3IiLCJpZCI6Impkb2UifQ.Dpss-QoLYjec5OTsOaAc3FNVsSjA89wACoV-0ra3ClA"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
it "fails with an expired token" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NDY2NzgxNDksInJvbGUiOiJwb3N0Z3Jlc3RfdGVzdF9hdXRob3IiLCJpZCI6Impkb2UifQ.f8__E6VQwYcDqwHmr9PG03uaZn8Zh1b0vbJ9DYS0AdM"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` [json| {"message":"JWT expired"} |]
{ matchStatus = 401
, matchHeaders = [
"WWW-Authenticate" <:>
"Bearer error=\"invalid_token\", error_description=\"JWT expired\""
]
}
it "hides tables from users with invalid JWT" $ do
let auth = authHeaderJWT "ey9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.y4vZuu1dDdwAl0-S00MCRWRYMlJ5YAMSir6Es6WtWx0"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` [json| {"message":"JWSError (CompactDecodeError Invalid number of parts: Expected 3 parts; got 2)"} |]
{ matchStatus = 401
, matchHeaders = [
"WWW-Authenticate" <:>
"Bearer error=\"invalid_token\", error_description=\"JWSError (CompactDecodeError Invalid number of parts: Expected 3 parts; got 2)\""
]
}
it "should fail when jwt contains no claims" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.CUIP5V9thWsGGFsFyGijSZf1fJMfarLHI9CEJL-TGNk"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 401
it "hides tables from users with JWT that contain no claims about role" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Impkb2UifQ.RVlZDaSyKbFPvxUf3V_NQXybfRB4dlBIkAUQXVXLUAI"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 401
it "recovers after 401 error with logged in user" $ do
_ <- post "/authors_only" [json| { "owner": "jdoe", "secret": "test content" } |]
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.B-lReuGNDwAlU1GOC476MlO0vAt9JNoHIlxg2vwMaO0"
_ <- request methodPost "/rpc/problem" [auth] ""
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
describe "custom pre-request proc acting on id claim" $ do
it "able to switch to postgrest_test_author role (id=1)" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MX0.gKw7qI50i9hMrSJW8BlTpdMEVmMXJYxlAqueGqpa_mE" in
request methodPost "/rpc/get_current_user" [auth]
[json| {} |]
`shouldRespondWith` [json|"postgrest_test_author"|]
{ matchStatus = 200
, matchHeaders = []
}
it "able to switch to postgrest_test_default_role (id=2)" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Mn0.nwzjMI0YLvVGJQTeoCPEBsK983b__gxdpLXisBNaO2A" in
request methodPost "/rpc/get_current_user" [auth]
[json| {} |]
`shouldRespondWith` [json|"postgrest_test_default_role"|]
{ matchStatus = 200
, matchHeaders = []
}
it "raises error (id=3)" $
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6M30.OGxEJAf60NKZiTn-tIb2jy4rqKs_ZruLGWZ40TjrJsM" in
request methodPost "/rpc/get_current_user" [auth]
[json| {} |]
`shouldRespondWith` [json|{"hint":"Please contact administrator","details":null,"code":"P0001","message":"Disabled ID --> 3"}|]
{ matchStatus = 400
, matchHeaders = []
}
it "allows 'Bearer' and 'bearer' as authentication schemes" $ do
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.B-lReuGNDwAlU1GOC476MlO0vAt9JNoHIlxg2vwMaO0"
request methodGet "/authors_only" [authHeader "Bearer" token] ""
`shouldRespondWith` 200
request methodGet "/authors_only" [authHeader "bearer" token] ""
`shouldRespondWith` 200
|
steve-chavez/postgrest
|
test/Feature/AuthSpec.hs
|
Haskell
|
mit
| 9,003
|
import Control.Applicative
import Control.Monad
import Data.List
import System.IO
rotate :: Int -> [a] -> [a]
rotate _ [] = []
rotate n xs = zipWith const (drop n (cycle xs)) xs
main :: IO ()
main = do
n_temp <- getLine
let n_t = words n_temp
let n = read $ n_t!!0 :: Int
let k = read $ n_t!!1 :: Int
a_temp <- getLine
let a = map read $ words a_temp :: [Int]
putStrLn $ intercalate " " $ map show $ rotate (k `mod` n) a
|
nbrendler/hackerrank-exercises
|
array-left-rotation/Main.hs
|
Haskell
|
mit
| 451
|
{-# LANGUAGE NoImplicitPrelude, ViewPatterns, DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
module Graphics.Caramia.Buffer.Internal where
import Data.Data
import qualified Data.Set as S
import GHC.Generics
import Graphics.Caramia.Internal.OpenGLCApi
import Graphics.Caramia.OpenGLResource
import Graphics.Caramia.Prelude
import Graphics.Caramia.Resource
-- | Buffer data type.
data Buffer = Buffer
{ resource :: !(Resource Buffer_)
, status :: !(IORef BufferStatus)
, viewAllowedMappings :: !AccessFlags -- ^ Returns the allowed mappings.
, viewSize :: !Int -- ^ Returns the size of the buffer, in bytes.
, ordIndex :: !Unique
}
deriving ( Typeable )
instance OpenGLResource GLuint Buffer where
getRaw buf = do
Buffer_ name <- getRaw (WrappedOpenGLResource $ resource buf)
return name
touch buf = touch (WrappedOpenGLResource $ resource buf)
finalize buf = finalize (WrappedOpenGLResource $ resource buf)
instance Ord Buffer where
(ordIndex -> o1) `compare` (ordIndex -> o2) = o1 `compare` o2
data BufferStatus = BufferStatus
{ mapped :: !(Maybe (S.Set MapFlag)) }
instance Show Buffer where
show (Buffer{..}) = "<Buffer bytesize(" <> show viewSize <> ")>"
instance Eq Buffer where
(resource -> res1) == (resource -> res2) = res1 == res2
newtype Buffer_ = Buffer_ GLuint
-- | Describes a style of mapping.
data AccessFlags =
ReadAccess -- ^ The mapping can be read from.
| WriteAccess -- ^ The mapping can be written to.
| ReadWriteAccess -- ^ Both reading and writing can be done.
| NoAccess -- ^ No access; you cannot map the buffer at all after
-- creation.
deriving ( Eq, Ord, Show, Read, Typeable, Enum, Data, Generic )
-- | Additional mapping flags.
data MapFlag =
UnSynchronized -- ^ Map the buffer without synchronization.
-- You will have to use synchronization primitives
-- to make sure you and OpenGL won't be using
-- the buffer at the same time.
| ExplicitFlush -- ^ If set, you need to explicitly flush ranges of
-- the mapping after you have modified them, with
-- `explicitFlush`. The mapping must allow writes.
-- Requires OpenGL 3.0 or greater or
-- \"GL_ARB_map_buffer_range\", but if neither of
-- these are available, then this flag is no-op and
-- so is `explicitFlush`.
--
-- Explicit flushing can be useful when you map a
-- large buffer but don't know beforehand how much
-- of that buffer you are going to modify.
deriving ( Eq, Ord, Show, Read, Typeable, Enum, Data, Generic )
|
Noeda/caramia
|
src/Graphics/Caramia/Buffer/Internal.hs
|
Haskell
|
mit
| 3,087
|
{- Seth Brown
2014-12-13
GHC 7.8.3
sethbrown AT drbunsen DOT ORG
Copyright 2014 Seth Brown. All rights reserved.
data from: http://www.beeradvocate.com/lists/top/
$ runghc ba-top-breweries.hs < data.txt
======================================
Hill Farmstead Brewery,24
Brasserie Cantillon,11
The Bruery,10
Russian River Brewing Company,9
Alpine Beer Company,8
Toppling Goliath Brewing Company,6
Trillium Brewing Company,6
AleSmith Brewing Company,5
Firestone Walker Brewing Co.,5
Founders Brewing Company,5
-}
import qualified Data.ByteString.Lazy.Char8 as LC
import qualified Data.List as DL
import qualified Control.Arrow as CA
main = LC.getContents >>= mapM_ putStrLn . proc
-- process input data and count most frequent breweries
proc xs = top10
. freqs
. names
$ process xs
-- reduce over the input and capture brewery names
names xs = DL.foldl (\acc el -> if mod (fst el) 3 == 1
then (acc ++ [snd el])
else acc) [] xs
-- count and sort the frequencies of each brewery name
freqs xs = DL.sortBy sortDescFreq
. map (head CA.&&& length) . DL.group $ DL.sort xs
where
sortDescFreq (_, i) (_, j)
| i > j = LT
| i < j = GT
| i == j = compare i j
-- filter the most frequent breweries
top10 xs = format . DL.takeWhile (\(i, el) -> i < 10) $ zip [0..] xs
-- stringify results into a list
format = map (\(i,(el, freq)) -> DL.intercalate "," [el, show freq])
-- lazy unpack bytestrings to an enumerated list of lines
process xs = (DL.zip [0..] . DL.lines . LC.unpack) xs
|
drbunsen/Beer-Advocate-Top-Breweries
|
ba-top-breweries.hs
|
Haskell
|
mit
| 1,738
|
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- A weaker version of State, where updates are restricted to addition for some
-- monoid.
module Philed.Control.Monad.Record (RecordT, runRecordT, evalRecordT, execRecordT
,MonadRecord, record, get) where
import Control.Applicative
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.Writer
import qualified Control.Monad.State as S
import Data.Monoid
class Monad m => MonadRecord s m | m -> s where
record :: s -> m ()
get :: m s
newtype RecordT s m a = RecordT { unRecordT :: S.StateT s m a }
deriving (Applicative, Functor, Monad)
runRecordT :: (Monoid s, Monad m) => RecordT s m a -> m (a,s)
runRecordT x = S.runStateT (unRecordT x) mempty
evalRecordT :: (Monoid s, Monad m) => RecordT s m a -> m a
evalRecordT x = S.evalStateT (unRecordT x) mempty
execRecordT :: (Monoid s, Monad m) => RecordT s m a -> m s
execRecordT x = S.execStateT (unRecordT x) mempty
instance (Monoid s, Monad m) => MonadRecord s (RecordT s m) where
record x = RecordT (S.modify $ (<> x))
get = RecordT S.get
instance MonadTrans (RecordT s) where
lift = RecordT . lift
instance (Monad m, MonadError e m) => MonadError e (RecordT s m) where
throwError = lift . throwError
catchError x h = RecordT (catchError (unRecordT x) (unRecordT . h))
instance (Monad m, S.MonadState s m) => S.MonadState s (RecordT t m) where
get = lift S.get
put = lift . S.put
instance MonadPlus m => Alternative (RecordT s m) where
empty = lift mzero
(<|>) x y = RecordT (unRecordT x <|> unRecordT y)
instance MonadPlus m => MonadPlus (RecordT s m) where
mzero = empty
mplus = (<|>)
instance (Monad m, MonadReader r m) => MonadReader r (RecordT e m) where
ask = lift ask
local f (RecordT s) = RecordT (local f s)
instance (Monad m, MonadWriter w m) => MonadWriter w (RecordT e m) where
tell = lift . tell
listen (RecordT s) = RecordT (listen s)
pass (RecordT s) = RecordT (pass s)
instance (Monad m, MonadRecord s m) => MonadRecord s (ExceptT e m) where
record = lift . record
get = lift get
instance MonadIO m => MonadIO (RecordT s m) where
liftIO = lift . liftIO
|
Chattered/PhilEdCommon
|
Philed/Control/Monad/Record.hs
|
Haskell
|
mit
| 2,403
|
module WhenView.Process (process) where
import Control.Monad (join)
import WhenView.Stage1.Parser (entries)
import WhenView.Stage1.Serializer (calTokens)
import WhenView.Stage2.Parser (years)
import WhenView.I18n (Months)
import Text.ParserCombinators.Parsec (runParser, ParseError)
import WhenView.Html (calendarPage)
import Text.Blaze.Html.Renderer.Pretty (renderHtml)
process :: Months -> String -> Either ParseError String
process months input =
renderHtml . calendarPage <$> join
(runParser years () "tokens" <$>
calTokens <$>
runParser (entries months) () "stdin" input)
|
zenhack/whenview
|
src/WhenView/Process.hs
|
Haskell
|
mit
| 609
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import Game.Halma.TelegramBot.CmdLineOptions
import Game.Halma.TelegramBot.Controller (halmaBot)
import Game.Halma.TelegramBot.Controller.BotM (evalGlobalBotM)
import Game.Halma.TelegramBot.Controller.Types (BotConfig (..))
import Game.Halma.TelegramBot.Controller.Persistence (noPersistence, filePersistence)
import Network.HTTP.Client (newManager)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import System.Exit (exitFailure)
import System.IO (hPrint, stderr)
import qualified Options.Applicative as OA
main :: IO ()
main = do
opts <- OA.execParser optionsParserInfo
manager <- newManager tlsManagerSettings
let
persistence =
case boOutputDirectory opts of
Nothing -> noPersistence
Just outDir -> filePersistence outDir
cfg =
BotConfig
{ bcToken = boToken opts
, bcPersistence = persistence
, bcManager = manager
}
print opts
evalGlobalBotM halmaBot cfg >>= \case
Left e -> do
hPrint stderr e
exitFailure
Right () -> return ()
|
timjb/halma
|
halma-telegram-bot/ServerMain.hs
|
Haskell
|
mit
| 1,207
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE CPP #-}
-- | Field functions allow you to easily create and validate forms, cleanly handling the uncertainty of parsing user input.
--
-- When possible, the field functions use a specific input type (e.g. "number"), allowing supporting browsers to validate the input before form submission. Browsers can also improve usability with this information; for example, mobile browsers might present a specialized keyboard for an input of type "email" or "number".
--
-- See the Yesod book <http://www.yesodweb.com/book/forms chapter on forms> for a broader overview of forms in Yesod.
module Yesod.Form.Fields
( -- * i18n
FormMessage (..)
, defaultFormMessage
-- * Fields
, textField
, passwordField
, textareaField
, hiddenField
, intField
, dayField
, timeField
, timeFieldTypeTime
, timeFieldTypeText
, htmlField
, emailField
, multiEmailField
, searchField
, AutoFocus
, urlField
, doubleField
, parseDate
, parseTime
, Textarea (..)
, boolField
, checkBoxField
, fileField
-- * File 'AForm's
, fileAFormReq
, fileAFormOpt
-- * Options
-- $optionsOverview
, selectFieldHelper
, selectField
, selectFieldList
, radioField
, radioFieldList
, checkboxesField
, checkboxesFieldList
, multiSelectField
, multiSelectFieldList
, Option (..)
, OptionList (..)
, mkOptionList
, optionsPersist
, optionsPersistKey
, optionsPairs
, optionsEnum
) where
import Yesod.Form.Types
import Yesod.Form.I18n.English
import Yesod.Form.Functions (parseHelper)
import Yesod.Core
import Text.Blaze (ToMarkup (toMarkup), unsafeByteString)
#define ToHtml ToMarkup
#define toHtml toMarkup
#define preEscapedText preEscapedToMarkup
import Data.Time (Day, TimeOfDay(..))
import qualified Text.Email.Validate as Email
import Data.Text.Encoding (encodeUtf8, decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Network.URI (parseURI)
import Database.Persist.Sql (PersistField, PersistFieldSql (..))
#if MIN_VERSION_persistent(2,5,0)
import Database.Persist (Entity (..), SqlType (SqlString), PersistRecordBackend, PersistQueryRead)
#else
import Database.Persist (Entity (..), SqlType (SqlString), PersistEntity, PersistQuery, PersistEntityBackend)
#endif
import Text.HTML.SanitizeXSS (sanitizeBalance)
import Control.Monad (when, unless)
import Data.Either (partitionEithers)
import Data.Maybe (listToMaybe, fromMaybe)
import qualified Blaze.ByteString.Builder.Html.Utf8 as B
import Blaze.ByteString.Builder (writeByteString, toLazyByteString)
import Blaze.ByteString.Builder.Internal.Write (fromWriteList)
import Text.Blaze.Html.Renderer.String (renderHtml)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Text as T ( Text, append, concat, cons, head
, intercalate, isPrefixOf, null, unpack, pack, splitOn
)
import qualified Data.Text as T (drop, dropWhile)
import qualified Data.Text.Read
import qualified Data.Map as Map
import Yesod.Persist (selectList, Filter, SelectOpt, Key)
import Control.Arrow ((&&&))
import Control.Applicative ((<$>), (<|>))
import Data.Attoparsec.Text (Parser, char, string, digit, skipSpace, endOfInput, parseOnly)
import Yesod.Persist.Core
import Data.String (IsString)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
#endif
defaultFormMessage :: FormMessage -> Text
defaultFormMessage = englishFormMessage
-- | Creates a input with @type="number"@ and @step=1@.
intField :: (Monad m, Integral i, RenderMessage (HandlerSite m) FormMessage) => Field m i
intField = Field
{ fieldParse = parseHelper $ \s ->
case Data.Text.Read.signed Data.Text.Read.decimal s of
Right (a, "") -> Right a
_ -> Left $ MsgInvalidInteger s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="number" step=1 :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where
showVal = either id (pack . showI)
showI x = show (fromIntegral x :: Integer)
-- | Creates a input with @type="number"@ and @step=any@.
doubleField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Double
doubleField = Field
{ fieldParse = parseHelper $ \s ->
case Data.Text.Read.double (prependZero s) of
Right (a, "") -> Right a
_ -> Left $ MsgInvalidNumber s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="number" step=any :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . show)
-- | Creates an input with @type="date"@, validating the input using the 'parseDate' function.
--
-- Add the @time@ package and import the "Data.Time.Calendar" module to use this function.
dayField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Day
dayField = Field
{ fieldParse = parseHelper $ parseDate . unpack
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="date" :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . show)
-- | An alias for 'timeFieldTypeTime'.
timeField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeField = timeFieldTypeTime
-- | Creates an input with @type="time"@. <http://caniuse.com/#search=time%20input%20type Browsers not supporting this type> will fallback to a text field, and Yesod will parse the time as described in 'timeFieldTypeText'.
--
-- Add the @time@ package and import the "Data.Time.LocalTime" module to use this function.
--
-- Since 1.4.2
timeFieldTypeTime :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeFieldTypeTime = timeFieldOfType "time"
-- | Creates an input with @type="text"@, parsing the time from an [H]H:MM[:SS] format, with an optional AM or PM (if not given, AM is assumed for compatibility with the 24 hour clock system).
--
-- This function exists for backwards compatibility with the old implementation of 'timeField', which used to use @type="text"@. Consider using 'timeField' or 'timeFieldTypeTime' for improved UX and validation from the browser.
--
-- Add the @time@ package and import the "Data.Time.LocalTime" module to use this function.
--
-- Since 1.4.2
timeFieldTypeText :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeFieldTypeText = timeFieldOfType "text"
timeFieldOfType :: Monad m => RenderMessage (HandlerSite m) FormMessage => Text -> Field m TimeOfDay
timeFieldOfType inputType = Field
{ fieldParse = parseHelper parseTime
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="#{inputType}" :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where
showVal = either id (pack . show . roundFullSeconds)
roundFullSeconds tod =
TimeOfDay (todHour tod) (todMin tod) fullSec
where
fullSec = fromInteger $ floor $ todSec tod
-- | Creates a @\<textarea>@ tag whose input is sanitized to prevent XSS attacks and is validated for having balanced tags.
htmlField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Html
htmlField = Field
{ fieldParse = parseHelper $ Right . preEscapedText . sanitizeBalance
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<textarea :isReq:required="" id="#{theId}" name="#{name}" *{attrs}>#{showVal val}
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . renderHtml)
-- | A newtype wrapper around a 'Text' whose 'ToMarkup' instance converts newlines to HTML @\<br>@ tags.
--
-- (When text is entered into a @\<textarea>@, newline characters are used to separate lines.
-- If this text is then placed verbatim into HTML, the lines won't be separated, thus the need for replacing with @\<br>@ tags).
-- If you don't need this functionality, simply use 'unTextarea' to access the raw text.
newtype Textarea = Textarea { unTextarea :: Text }
deriving (Show, Read, Eq, PersistField, Ord, ToJSON, FromJSON, IsString)
instance PersistFieldSql Textarea where
sqlType _ = SqlString
instance ToHtml Textarea where
toHtml =
unsafeByteString
. S.concat
. L.toChunks
. toLazyByteString
. fromWriteList writeHtmlEscapedChar
. unpack
. unTextarea
where
-- Taken from blaze-builder and modified with newline handling.
writeHtmlEscapedChar '\r' = mempty
writeHtmlEscapedChar '\n' = writeByteString "<br>"
writeHtmlEscapedChar c = B.writeHtmlEscapedChar c
-- | Creates a @\<textarea>@ tag whose returned value is wrapped in a 'Textarea'; see 'Textarea' for details.
textareaField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Textarea
textareaField = Field
{ fieldParse = parseHelper $ Right . Textarea
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<textarea id="#{theId}" name="#{name}" :isReq:required="" *{attrs}>#{either id unTextarea val}
|]
, fieldEnctype = UrlEncoded
}
-- | Creates an input with @type="hidden"@; you can use this to store information in a form that users shouldn't see (for example, Yesod stores CSRF tokens in a hidden field).
hiddenField :: (Monad m, PathPiece p, RenderMessage (HandlerSite m) FormMessage)
=> Field m p
hiddenField = Field
{ fieldParse = parseHelper $ maybe (Left MsgValueRequired) Right . fromPathPiece
, fieldView = \theId name attrs val _isReq -> toWidget [hamlet|
$newline never
<input type="hidden" id="#{theId}" name="#{name}" *{attrs} value="#{either id toPathPiece val}">
|]
, fieldEnctype = UrlEncoded
}
-- | Creates a input with @type="text"@.
textField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
textField = Field
{ fieldParse = parseHelper $ Right
, fieldView = \theId name attrs val isReq ->
[whamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="text" :isReq:required value="#{either id id val}">
|]
, fieldEnctype = UrlEncoded
}
-- | Creates an input with @type="password"@.
passwordField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
passwordField = Field
{ fieldParse = parseHelper $ Right
, fieldView = \theId name attrs _ isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="password" :isReq:required="">
|]
, fieldEnctype = UrlEncoded
}
readMay :: Read a => String -> Maybe a
readMay s = case filter (Prelude.null . snd) $ reads s of
(x, _):_ -> Just x
[] -> Nothing
-- | Parses a 'Day' from a 'String'.
parseDate :: String -> Either FormMessage Day
parseDate = maybe (Left MsgInvalidDay) Right
. readMay . replace '/' '-'
-- | Replaces all instances of a value in a list by another value.
-- from http://hackage.haskell.org/packages/archive/cgi/3001.1.7.1/doc/html/src/Network-CGI-Protocol.html#replace
replace :: Eq a => a -> a -> [a] -> [a]
replace x y = map (\z -> if z == x then y else z)
parseTime :: Text -> Either FormMessage TimeOfDay
parseTime = either (Left . fromMaybe MsgInvalidTimeFormat . readMay . drop 2 . dropWhile (/= ':')) Right . parseOnly timeParser
timeParser :: Parser TimeOfDay
timeParser = do
skipSpace
h <- hour
_ <- char ':'
m <- minsec MsgInvalidMinute
hasSec <- (char ':' >> return True) <|> return False
s <- if hasSec then minsec MsgInvalidSecond else return 0
skipSpace
isPM <-
(string "am" >> return (Just False)) <|>
(string "AM" >> return (Just False)) <|>
(string "pm" >> return (Just True)) <|>
(string "PM" >> return (Just True)) <|>
return Nothing
h' <-
case isPM of
Nothing -> return h
Just x
| h <= 0 || h > 12 -> fail $ show $ MsgInvalidHour $ pack $ show h
| h == 12 -> return $ if x then 12 else 0
| otherwise -> return $ h + (if x then 12 else 0)
skipSpace
endOfInput
return $ TimeOfDay h' m s
where
hour = do
x <- digit
y <- (return Control.Applicative.<$> digit) <|> return []
let xy = x : y
let i = read xy
if i < 0 || i >= 24
then fail $ show $ MsgInvalidHour $ pack xy
else return i
minsec :: Num a => (Text -> FormMessage) -> Parser a
minsec msg = do
x <- digit
y <- digit <|> fail (show $ msg $ pack [x])
let xy = [x, y]
let i = read xy
if i < 0 || i >= 60
then fail $ show $ msg $ pack xy
else return $ fromIntegral (i :: Int)
-- | Creates an input with @type="email"@. Yesod will validate the email's correctness according to RFC5322 and canonicalize it by removing comments and whitespace (see "Text.Email.Validate").
emailField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
emailField = Field
{ fieldParse = parseHelper $
\s ->
case Email.canonicalizeEmail $ encodeUtf8 s of
Just e -> Right $ decodeUtf8With lenientDecode e
Nothing -> Left $ MsgInvalidEmail s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="email" :isReq:required="" value="#{either id id val}">
|]
, fieldEnctype = UrlEncoded
}
-- | Creates an input with @type="email"@ with the <http://w3c.github.io/html/sec-forms.html#the-multiple-attribute multiple> attribute; browsers might implement this as taking a comma separated list of emails. Each email address is validated as described in 'emailField'.
--
-- Since 1.3.7
multiEmailField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m [Text]
multiEmailField = Field
{ fieldParse = parseHelper $
\s ->
let addrs = map validate $ splitOn "," s
in case partitionEithers addrs of
([], good) -> Right good
(bad, _) -> Left $ MsgInvalidEmail $ cat bad
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="email" multiple :isReq:required="" value="#{either id cat val}">
|]
, fieldEnctype = UrlEncoded
}
where
-- report offending address along with error
validate a = case Email.validate $ encodeUtf8 a of
Left e -> Left $ T.concat [a, " (", pack e, ")"]
Right r -> Right $ emailToText r
cat = intercalate ", "
emailToText = decodeUtf8With lenientDecode . Email.toByteString
type AutoFocus = Bool
-- | Creates an input with @type="search"@. For <http://caniuse.com/#search=autofocus browsers without autofocus support>, a JS fallback is used if @AutoFocus@ is true.
searchField :: Monad m => RenderMessage (HandlerSite m) FormMessage => AutoFocus -> Field m Text
searchField autoFocus = Field
{ fieldParse = parseHelper Right
, fieldView = \theId name attrs val isReq -> do
[whamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="search" :isReq:required="" :autoFocus:autofocus="" value="#{either id id val}">
|]
when autoFocus $ do
-- we want this javascript to be placed immediately after the field
[whamlet|
$newline never
<script>if (!('autofocus' in document.createElement('input'))) {document.getElementById('#{theId}').focus();}
|]
toWidget [cassius|
##{theId}
-webkit-appearance: textfield
|]
, fieldEnctype = UrlEncoded
}
-- | Creates an input with @type="url"@, validating the URL according to RFC3986.
urlField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
urlField = Field
{ fieldParse = parseHelper $ \s ->
case parseURI $ unpack s of
Nothing -> Left $ MsgInvalidUrl s
Just _ -> Right s
, fieldView = \theId name attrs val isReq ->
[whamlet|<input ##{theId} name=#{name} *{attrs} type=url :isReq:required value=#{either id id val}>|]
, fieldEnctype = UrlEncoded
}
-- | Creates a @\<select>@ tag for selecting one option. Example usage:
--
-- > areq (selectFieldList [("Value 1" :: Text, "value1"),("Value 2", "value2")]) "Which value?" Nothing
selectFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) a
selectFieldList = selectField . optionsPairs
-- | Creates a @\<select>@ tag for selecting one option. Example usage:
--
-- > areq (selectField $ optionsPairs [(MsgValue1, "value1"),(MsgValue2, "value2")]) "Which value?" Nothing
selectField :: (Eq a, RenderMessage site FormMessage)
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
selectField = selectFieldHelper
(\theId name attrs inside -> [whamlet|
$newline never
<select ##{theId} name=#{name} *{attrs}>^{inside}
|]) -- outside
(\_theId _name isSel -> [whamlet|
$newline never
<option value=none :isSel:selected>_{MsgSelectNone}
|]) -- onOpt
(\_theId _name _attrs value isSel text -> [whamlet|
$newline never
<option value=#{value} :isSel:selected>#{text}
|]) -- inside
-- | Creates a @\<select>@ tag for selecting multiple options.
multiSelectFieldList :: (Eq a, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) [a]
multiSelectFieldList = multiSelectField . optionsPairs
-- | Creates a @\<select>@ tag for selecting multiple options.
multiSelectField :: Eq a
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) [a]
multiSelectField ioptlist =
Field parse view UrlEncoded
where
parse [] _ = return $ Right Nothing
parse optlist _ = do
mapopt <- olReadExternal <$> ioptlist
case mapM mapopt optlist of
Nothing -> return $ Left "Error parsing values"
Just res -> return $ Right $ Just res
view theId name attrs val isReq = do
opts <- fmap olOptions $ handlerToWidget ioptlist
let selOpts = map (id &&& (optselected val)) opts
[whamlet|
<select ##{theId} name=#{name} :isReq:required multiple *{attrs}>
$forall (opt, optsel) <- selOpts
<option value=#{optionExternalValue opt} :optsel:selected>#{optionDisplay opt}
|]
where
optselected (Left _) _ = False
optselected (Right vals) opt = (optionInternalValue opt) `elem` vals
-- | Creates an input with @type="radio"@ for selecting one option.
radioFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) a
radioFieldList = radioField . optionsPairs
-- | Creates an input with @type="checkbox"@ for selecting multiple options.
checkboxesFieldList :: (Eq a, RenderMessage site msg) => [(msg, a)]
-> Field (HandlerFor site) [a]
checkboxesFieldList = checkboxesField . optionsPairs
-- | Creates an input with @type="checkbox"@ for selecting multiple options.
checkboxesField :: Eq a
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) [a]
checkboxesField ioptlist = (multiSelectField ioptlist)
{ fieldView =
\theId name attrs val _isReq -> do
opts <- fmap olOptions $ handlerToWidget ioptlist
let optselected (Left _) _ = False
optselected (Right vals) opt = (optionInternalValue opt) `elem` vals
[whamlet|
<span ##{theId}>
$forall opt <- opts
<label>
<input type=checkbox name=#{name} value=#{optionExternalValue opt} *{attrs} :optselected val opt:checked>
#{optionDisplay opt}
|]
}
-- | Creates an input with @type="radio"@ for selecting one option.
radioField :: (Eq a, RenderMessage site FormMessage)
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
radioField = selectFieldHelper
(\theId _name _attrs inside -> [whamlet|
$newline never
<div ##{theId}>^{inside}
|])
(\theId name isSel -> [whamlet|
$newline never
<label .radio for=#{theId}-none>
<div>
<input id=#{theId}-none type=radio name=#{name} value=none :isSel:checked>
_{MsgSelectNone}
|])
(\theId name attrs value isSel text -> [whamlet|
$newline never
<label .radio for=#{theId}-#{value}>
<div>
<input id=#{theId}-#{value} type=radio name=#{name} value=#{value} :isSel:checked *{attrs}>
\#{text}
|])
-- | Creates a group of radio buttons to answer the question given in the message. Radio buttons are used to allow differentiating between an empty response (@Nothing@) and a no response (@Just False@). Consider using the simpler 'checkBoxField' if you don't need to make this distinction.
--
-- If this field is optional, the first radio button is labeled "\<None>", the second \"Yes" and the third \"No".
--
-- If this field is required, the first radio button is labeled \"Yes" and the second \"No".
--
-- (Exact label titles will depend on localization).
boolField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Bool
boolField = Field
{ fieldParse = \e _ -> return $ boolParser e
, fieldView = \theId name attrs val isReq -> [whamlet|
$newline never
$if not isReq
<input id=#{theId}-none *{attrs} type=radio name=#{name} value=none checked>
<label for=#{theId}-none>_{MsgSelectNone}
<input id=#{theId}-yes *{attrs} type=radio name=#{name} value=yes :showVal id val:checked>
<label for=#{theId}-yes>_{MsgBoolYes}
<input id=#{theId}-no *{attrs} type=radio name=#{name} value=no :showVal not val:checked>
<label for=#{theId}-no>_{MsgBoolNo}
|]
, fieldEnctype = UrlEncoded
}
where
boolParser [] = Right Nothing
boolParser (x:_) = case x of
"" -> Right Nothing
"none" -> Right Nothing
"yes" -> Right $ Just True
"on" -> Right $ Just True
"no" -> Right $ Just False
"true" -> Right $ Just True
"false" -> Right $ Just False
t -> Left $ SomeMessage $ MsgInvalidBool t
showVal = either (\_ -> False)
-- | Creates an input with @type="checkbox"@.
-- While the default @'boolField'@ implements a radio button so you
-- can differentiate between an empty response (@Nothing@) and a no
-- response (@Just False@), this simpler checkbox field returns an empty
-- response as @Just False@.
--
-- Note that this makes the field always optional.
--
checkBoxField :: Monad m => Field m Bool
checkBoxField = Field
{ fieldParse = \e _ -> return $ checkBoxParser e
, fieldView = \theId name attrs val _ -> [whamlet|
$newline never
<input id=#{theId} *{attrs} type=checkbox name=#{name} value=yes :showVal id val:checked>
|]
, fieldEnctype = UrlEncoded
}
where
checkBoxParser [] = Right $ Just False
checkBoxParser (x:_) = case x of
"yes" -> Right $ Just True
"on" -> Right $ Just True
_ -> Right $ Just False
showVal = either (\_ -> False)
-- | A structure holding a list of options. Typically you can use a convenience function like 'mkOptionList' or 'optionsPairs' instead of creating this directly.
data OptionList a = OptionList
{ olOptions :: [Option a]
, olReadExternal :: Text -> Maybe a -- ^ A function mapping from the form's value ('optionExternalValue') to the selected Haskell value ('optionInternalValue').
}
-- | Since 1.4.6
instance Functor OptionList where
fmap f (OptionList options readExternal) =
OptionList ((fmap.fmap) f options) (fmap f . readExternal)
-- | Creates an 'OptionList', using a 'Map' to implement the 'olReadExternal' function.
mkOptionList :: [Option a] -> OptionList a
mkOptionList os = OptionList
{ olOptions = os
, olReadExternal = flip Map.lookup $ Map.fromList $ map (optionExternalValue &&& optionInternalValue) os
}
data Option a = Option
{ optionDisplay :: Text -- ^ The user-facing label.
, optionInternalValue :: a -- ^ The Haskell value being selected.
, optionExternalValue :: Text -- ^ The representation of this value stored in the form.
}
-- | Since 1.4.6
instance Functor Option where
fmap f (Option display internal external) = Option display (f internal) external
-- | Creates an 'OptionList' from a list of (display-value, internal value) pairs.
optionsPairs :: (MonadHandler m, RenderMessage (HandlerSite m) msg)
=> [(msg, a)] -> m (OptionList a)
optionsPairs opts = do
mr <- getMessageRender
let mkOption external (display, internal) =
Option { optionDisplay = mr display
, optionInternalValue = internal
, optionExternalValue = pack $ show external
}
return $ mkOptionList (zipWith mkOption [1 :: Int ..] opts)
-- | Creates an 'OptionList' from an 'Enum', using its 'Show' instance for the user-facing value.
optionsEnum :: (MonadHandler m, Show a, Enum a, Bounded a) => m (OptionList a)
optionsEnum = optionsPairs $ map (\x -> (pack $ show x, x)) [minBound..maxBound]
-- | Selects a list of 'Entity's with the given 'Filter' and 'SelectOpt's. The @(a -> msg)@ function is then used to derive the display value for an 'OptionList'. Example usage:
--
-- > Country
-- > name Text
-- > deriving Eq -- Must derive Eq
--
-- > data CountryForm = CountryForm
-- > { country :: Entity Country
-- > }
-- >
-- > countryNameForm :: AForm Handler CountryForm
-- > countryNameForm = CountryForm
-- > <$> areq (selectField countries) "Which country do you live in?" Nothing
-- > where
-- > countries = optionsPersist [] [Asc CountryName] countryName
#if MIN_VERSION_persistent(2,5,0)
optionsPersist :: ( YesodPersist site
, PersistQueryRead backend
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ backend
, PersistRecordBackend a backend
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Entity a))
#else
optionsPersist :: ( YesodPersist site, PersistEntity a
, PersistQuery (PersistEntityBackend a)
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ PersistEntityBackend a
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Entity a))
#endif
optionsPersist filts ords toDisplay = fmap mkOptionList $ do
mr <- getMessageRender
pairs <- runDB $ selectList filts ords
return $ map (\(Entity key value) -> Option
{ optionDisplay = mr (toDisplay value)
, optionInternalValue = Entity key value
, optionExternalValue = toPathPiece key
}) pairs
-- | An alternative to 'optionsPersist' which returns just the 'Key' instead of
-- the entire 'Entity'.
--
-- Since 1.3.2
#if MIN_VERSION_persistent(2,5,0)
optionsPersistKey
:: (YesodPersist site
, PersistQueryRead backend
, PathPiece (Key a)
, RenderMessage site msg
, backend ~ YesodPersistBackend site
, PersistRecordBackend a backend
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Key a))
#else
optionsPersistKey
:: (YesodPersist site
, PersistEntity a
, PersistQuery (PersistEntityBackend a)
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ PersistEntityBackend a
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Key a))
#endif
optionsPersistKey filts ords toDisplay = fmap mkOptionList $ do
mr <- getMessageRender
pairs <- runDB $ selectList filts ords
return $ map (\(Entity key value) -> Option
{ optionDisplay = mr (toDisplay value)
, optionInternalValue = key
, optionExternalValue = toPathPiece key
}) pairs
-- |
-- A helper function for constucting 'selectField's. You may want to use this when you define your custom 'selectField's or 'radioField's.
--
-- @since 1.6.2
selectFieldHelper
:: (Eq a, RenderMessage site FormMessage)
=> (Text -> Text -> [(Text, Text)] -> WidgetFor site () -> WidgetFor site ()) -- ^ Outermost part of the field
-> (Text -> Text -> Bool -> WidgetFor site ()) -- ^ An option for None if the field is optional
-> (Text -> Text -> [(Text, Text)] -> Text -> Bool -> Text -> WidgetFor site ()) -- ^ Other options
-> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
selectFieldHelper outside onOpt inside opts' = Field
{ fieldParse = \x _ -> do
opts <- opts'
return $ selectParser opts x
, fieldView = \theId name attrs val isReq -> do
opts <- fmap olOptions $ handlerToWidget opts'
outside theId name attrs $ do
unless isReq $ onOpt theId name $ not $ render opts val `elem` map optionExternalValue opts
flip mapM_ opts $ \opt -> inside
theId
name
((if isReq then (("required", "required"):) else id) attrs)
(optionExternalValue opt)
((render opts val) == optionExternalValue opt)
(optionDisplay opt)
, fieldEnctype = UrlEncoded
}
where
render _ (Left _) = ""
render opts (Right a) = maybe "" optionExternalValue $ listToMaybe $ filter ((== a) . optionInternalValue) opts
selectParser _ [] = Right Nothing
selectParser opts (s:_) = case s of
"" -> Right Nothing
"none" -> Right Nothing
x -> case olReadExternal opts x of
Nothing -> Left $ SomeMessage $ MsgInvalidEntry x
Just y -> Right $ Just y
-- | Creates an input with @type="file"@.
fileField :: Monad m
=> Field m FileInfo
fileField = Field
{ fieldParse = \_ files -> return $
case files of
[] -> Right Nothing
file:_ -> Right $ Just file
, fieldView = \id' name attrs _ isReq -> toWidget [hamlet|
<input id=#{id'} name=#{name} *{attrs} type=file :isReq:required>
|]
, fieldEnctype = Multipart
}
fileAFormReq :: (MonadHandler m, RenderMessage (HandlerSite m) FormMessage)
=> FieldSettings (HandlerSite m) -> AForm m FileInfo
fileAFormReq fs = AForm $ \(site, langs) menvs ints -> do
let (name, ints') =
case fsName fs of
Just x -> (x, ints)
Nothing ->
let i' = incrInts ints
in (pack $ 'f' : show i', i')
id' <- maybe newIdent return $ fsId fs
let (res, errs) =
case menvs of
Nothing -> (FormMissing, Nothing)
Just (_, fenv) ->
case Map.lookup name fenv of
Just (fi:_) -> (FormSuccess fi, Nothing)
_ ->
let t = renderMessage site langs MsgValueRequired
in (FormFailure [t], Just $ toHtml t)
let fv = FieldView
{ fvLabel = toHtml $ renderMessage site langs $ fsLabel fs
, fvTooltip = fmap (toHtml . renderMessage site langs) $ fsTooltip fs
, fvId = id'
, fvInput = [whamlet|
$newline never
<input type=file name=#{name} ##{id'} *{fsAttrs fs}>
|]
, fvErrors = errs
, fvRequired = True
}
return (res, (fv :), ints', Multipart)
fileAFormOpt :: MonadHandler m
=> FieldSettings (HandlerSite m)
-> AForm m (Maybe FileInfo)
fileAFormOpt fs = AForm $ \(master, langs) menvs ints -> do
let (name, ints') =
case fsName fs of
Just x -> (x, ints)
Nothing ->
let i' = incrInts ints
in (pack $ 'f' : show i', i')
id' <- maybe newIdent return $ fsId fs
let (res, errs) =
case menvs of
Nothing -> (FormMissing, Nothing)
Just (_, fenv) ->
case Map.lookup name fenv of
Just (fi:_) -> (FormSuccess $ Just fi, Nothing)
_ -> (FormSuccess Nothing, Nothing)
let fv = FieldView
{ fvLabel = toHtml $ renderMessage master langs $ fsLabel fs
, fvTooltip = fmap (toHtml . renderMessage master langs) $ fsTooltip fs
, fvId = id'
, fvInput = [whamlet|
$newline never
<input type=file name=#{name} ##{id'} *{fsAttrs fs}>
|]
, fvErrors = errs
, fvRequired = False
}
return (res, (fv :), ints', Multipart)
incrInts :: Ints -> Ints
incrInts (IntSingle i) = IntSingle $ i + 1
incrInts (IntCons i is) = (i + 1) `IntCons` is
-- | Adds a '0' to some text so that it may be recognized as a double.
-- The read ftn does not recognize ".3" as 0.3 nor "-.3" as -0.3, so this
-- function changes ".xxx" to "0.xxx" and "-.xxx" to "-0.xxx"
prependZero :: Text -> Text
prependZero t0 = if T.null t1
then t1
else if T.head t1 == '.'
then '0' `T.cons` t1
else if "-." `T.isPrefixOf` t1
then "-0." `T.append` (T.drop 2 t1)
else t1
where t1 = T.dropWhile ((==) ' ') t0
-- $optionsOverview
-- These functions create inputs where one or more options can be selected from a list.
--
-- The basic datastructure used is an 'Option', which combines a user-facing display value, the internal Haskell value being selected, and an external 'Text' stored as the @value@ in the form (used to map back to the internal value). A list of these, together with a function mapping from an external value back to a Haskell value, form an 'OptionList', which several of these functions take as an argument.
--
-- Typically, you won't need to create an 'OptionList' directly and can instead make one with functions like 'optionsPairs' or 'optionsEnum'. Alternatively, you can use functions like 'selectFieldList', which use their @[(msg, a)]@ parameter to create an 'OptionList' themselves.
|
s9gf4ult/yesod
|
yesod-form/Yesod/Form/Fields.hs
|
Haskell
|
mit
| 35,208
|
module Handler.Thread where
import Authentification (isModeratorBySession, getValidNickBySession)
import Captcha
import CustomForms (postMForm)
import Helper (minusToSpaces, updatePosts)
import Import
import Widgets (accountLinksW, postWidget, threadWidget)
getThreadR :: Text -> Handler Html
getThreadR title = do
-- captcha
equation <- liftIO $ createMathEq
setSession "captcha" (eqResult equation)
-- form
(widget, enctype) <- generateFormPost $ postMForm equation "Submit post" Nothing
-- db
(Entity tid thread, isMod) <- runDB $ do
ethread <- getBy404 $ UniqueTitle $ minusToSpaces title
isMod <- isModeratorBySession
return (ethread, isMod)
-- widgets
setUltDestCurrent
let headline = threadTitle thread
leftWidget = threadWidget isMod tid thread
rightWidget = postWidget enctype widget
defaultLayout $(widgetFile "left-right-layout")
postThreadR :: Text -> Handler Html
postThreadR title = do
-- captcha
equation <- liftIO $ createMathEq
captcha <- getCaptchaBySession
setSession "captcha" $ eqResult equation
-- db
((Entity tid thread), isMod, nick) <- runDB $ do
entity <- getBy404 $ UniqueTitle $ minusToSpaces title
isMod <- isModeratorBySession
nick <- getValidNickBySession
return (entity, isMod, nick)
-- form
((result, widget), enctype) <- runFormPost $ postMForm equation "Submit post" Nothing
(newWidget, newEnctype) <- generateFormPost $ postMForm equation "Submit post" Nothing
case result of
(FormSuccess mpost) -> do
let post = mpost nick
case (postCaptcha post) == captcha of
True -> do
(Entity newTid newThread) <- runDB $ do
(_) <- update tid [ThreadPosts =. (updatePosts (threadPosts thread) post), ThreadLastUpdate =. (postTime post)]
entity <- getBy404 $ UniqueTitle $ minusToSpaces title
return entity
let headline = threadTitle newThread
leftWidget = threadWidget isMod newTid newThread
rightWidget = postWidget newEnctype newWidget
defaultLayout $(widgetFile "left-right-layout")
(_) -> do
let headline = threadTitle thread
leftWidget = threadWidget isMod tid thread
rightWidget = [whamlet|<span .simpleBlack> Sorry, the captcha is wrong|] >> postWidget enctype widget
defaultLayout $(widgetFile "left-right-layout")
(FormFailure (err:_)) -> do
let headline = threadTitle thread
leftWidget = threadWidget isMod tid thread
rightWidget = [whamlet|<span .simpleBlack> #{err}|] >> postWidget enctype widget
defaultLayout $(widgetFile "left-right-layout")
(_) -> do
let headline = threadTitle thread
leftWidget = threadWidget isMod tid thread
rightWidget = [whamlet|<span .simpleBlack> Something went wrong, please try again|] >> postWidget enctype widget
defaultLayout $(widgetFile "left-right-layout")
|
cirquit/HaskellPie
|
HaskellPie/Handler/Thread.hs
|
Haskell
|
mit
| 3,300
|
-- Ссылка на задание: https://gist.github.com/astynax/1eb88e195c4bab2b8d31d04921b18dd0
-- Это тоже самое задание, что в части 1, только сделанное прямо на занятии по-другому
module Main where
data Row a = Row a a a a
data Color = Red | Blue
data Field =
Field (Row (Row (Maybe Color)))
empty :: Field
empty = Field (Row r r r r)
where
r = Row
(Nothing)
(Nothing)
(Nothing)
(Nothing)
main = putStrLn $ drawField empty
drawField :: Field -> String
drawField (Field r) =
unlines
$ map fromRow
$ toList r
toList :: Row a -> [a]
toList (Row a b c d) = [a, b, c, d]
fromRow :: Row (Maybe Color) -> String
fromRow r =
unwords
$ map fromCell
$ toList r
fromCell :: Maybe Color -> String
fromCell (Just Red) = "R"
fromCell (Just Blue) = "B"
fromCell _ = "."
|
aquatir/remember_java_api
|
code-sample-haskell/typed_fp_basics_cource/02_function_in_haskell/task.hs
|
Haskell
|
mit
| 981
|
-- | This module re-exports all you need in order to /read/ package
-- databases and module info files created by compilers that use
-- haskell-packages.
--
-- If you are writing a compiler, i.e. a program that creates or writes
-- package databases or module info files — then take a look at
-- "Distribution.HaskellSuite.Compiler". It provides command-line
-- options handling and Cabal integration.
module Distribution.HaskellSuite
( module Distribution.HaskellSuite.Packages
, module Distribution.HaskellSuite.Modules
)
where
import Distribution.HaskellSuite.Packages
import Distribution.HaskellSuite.Modules
|
haskell-suite/haskell-packages
|
src/Distribution/HaskellSuite.hs
|
Haskell
|
mit
| 624
|
module IHaskell.Eval.Util (
-- * Initialization
initGhci,
-- * Flags and extensions
-- ** Set and unset flags.
extensionFlag, setExtension,
ExtFlag(..),
setFlags,
-- * Code Evaluation
evalImport,
isImportSafe,
evalDeclarations,
getType,
-- * Pretty printing
doc,
) where
-- GHC imports.
import DynFlags
import FastString
import GHC
import GhcMonad
import HsImpExp
import HscTypes
import InteractiveEval
import Module
import Outputable
import Packages
import RdrName
import qualified Pretty
import Control.Monad (void)
import Data.Function (on)
import Data.List (find)
import Data.String.Utils (replace)
-- | A extension flag that can be set or unset.
data ExtFlag
= SetFlag ExtensionFlag
| UnsetFlag ExtensionFlag
-- | Find the extension that corresponds to a given flag. Create the
-- corresponding 'ExtFlag' via @SetFlag@ or @UnsetFlag@.
-- If no such extension exist, yield @Nothing@.
extensionFlag :: String -- Extension name, such as @"DataKinds"@
-> Maybe ExtFlag
extensionFlag ext =
case find (flagMatches ext) xFlags of
Just (_, flag, _) -> Just $ SetFlag flag
-- If it doesn't match an extension name, try matching against
-- disabling an extension.
Nothing ->
case find (flagMatchesNo ext) xFlags of
Just (_, flag, _) -> Just $ UnsetFlag flag
Nothing -> Nothing
where
-- Check if a FlagSpec matches an extension name.
flagMatches ext (name, _, _) = ext == name
-- Check if a FlagSpec matches "No<ExtensionName>".
-- In that case, we disable the extension.
flagMatchesNo ext (name, _, _) = ext == "No" ++ name
-- | Set an extension and update flags.
-- Return @Nothing@ on success. On failure, return an error message.
setExtension :: GhcMonad m => String -> m (Maybe String)
setExtension ext = do
flags <- getSessionDynFlags
case extensionFlag ext of
Nothing -> return $ Just $ "Could not parse extension name: " ++ ext
Just flag -> do
setSessionDynFlags $
case flag of
SetFlag ghcFlag -> xopt_set flags ghcFlag
UnsetFlag ghcFlag -> xopt_unset flags ghcFlag
return Nothing
-- | Set a list of flags, as per GHCi's `:set`.
-- This was adapted from GHC's InteractiveUI.hs (newDynFlags).
-- It returns a list of error messages.
setFlags :: GhcMonad m => [String] -> m [String]
setFlags ext = do
-- Try to parse flags.
flags <- getSessionDynFlags
(flags', unrecognized, warnings) <- parseDynamicFlags flags (map noLoc ext)
-- First, try to check if this flag matches any extension name.
let restorePkg x = x { packageFlags = packageFlags flags }
let restoredPkgs = flags' { packageFlags = packageFlags flags}
GHC.setProgramDynFlags restoredPkgs
GHC.setInteractiveDynFlags restoredPkgs
-- Create the parse errors.
let noParseErrs = map (("Could not parse: " ++) . unLoc) unrecognized
allWarns = map unLoc warnings ++
["-package not supported yet" | packageFlags flags /= packageFlags flags']
warnErrs = map ("Warning: " ++) allWarns
return $ noParseErrs ++ warnErrs
-- | Convert an 'SDoc' into a string. This is similar to the family of
-- 'showSDoc' functions, but does not impose an arbitrary width limit on
-- the output (in terms of number of columns). Instead, it respsects the
-- 'pprCols' field in the structure returned by 'getSessionDynFlags', and
-- thus gives a configurable width of output.
doc :: GhcMonad m => SDoc -> m String
doc sdoc = do
flags <- getSessionDynFlags
unqual <- getPrintUnqual
let style = mkUserStyle unqual AllTheWay
let cols = pprCols flags
d = runSDoc sdoc (initSDocContext flags style)
return $ Pretty.fullRender Pretty.PageMode cols 1.5 string_txt "" d
where
string_txt :: Pretty.TextDetails -> String -> String
string_txt (Pretty.Chr c) s = c:s
string_txt (Pretty.Str s1) s2 = s1 ++ s2
string_txt (Pretty.PStr s1) s2 = unpackFS s1 ++ s2
string_txt (Pretty.LStr s1 _) s2 = unpackLitString s1 ++ s2
-- | Initialize the GHC API. Run this as the first thing in the `runGhc`.
-- This initializes some dyn flags (@ExtendedDefaultRules@,
-- @NoMonomorphismRestriction@), sets the target to interpreted, link in
-- memory, sets a reasonable output width, and potentially a few other
-- things. It should be invoked before other functions from this module.
initGhci :: GhcMonad m => m ()
initGhci = do
-- Initialize dyn flags.
-- Start with -XExtendedDefaultRules and -XNoMonomorphismRestriction.
originalFlags <- getSessionDynFlags
let flag = flip xopt_set
unflag = flip xopt_unset
dflags = flag Opt_ExtendedDefaultRules . unflag Opt_MonomorphismRestriction $ originalFlags
void $ setSessionDynFlags $ dflags { hscTarget = HscInterpreted,
ghcLink = LinkInMemory,
pprCols = 300 }
checkAdd :: GhcMonad m => InteractiveImport -> m (Bool,String)
checkAdd ii = do
dflags <- getDynFlags
let safe = safeLanguageOn dflags
case ii of
IIModule modname
| safe -> return (False,"can't use * imports with Safe Haskell")
| otherwise -> return (True,"")
IIDecl d -> do
let modname = unLoc (ideclName d)
pkgqual = ideclPkgQual d
m <- GHC.lookupModule modname pkgqual
if safe then do
t <- GHC.isModuleTrusted m
if (not t) then return (False,"Import is not trusted") else return (True,"")
else return (True,"")
isImportSafe :: GhcMonad m => String -> m (Bool,String)
isImportSafe imports = do
importDecl <- parseImportDecl imports
checkAdd (IIDecl importDecl)
-- | Evaluate a single import statement.
-- If this import statement is importing a module which was previously
-- imported implicitly (such as `Prelude`) or if this module has a `hiding`
-- annotation, the previous import is removed.
evalImport :: GhcMonad m => String -> m ()
evalImport imports = do
importDecl <- parseImportDecl imports
context <- getContext
dflags <- getSessionDynFlags
--liftIO $ print (safeHaskellOn dflags)
-- If we've imported this implicitly, remove the old import.
let noImplicit = filter (not . implicitImportOf importDecl) context
-- If this is a `hiding` import, remove previous non-`hiding` imports.
oldImps = if isHiddenImport importDecl
then filter (not . importOf importDecl) context
else noImplicit
canAdd <- checkAdd (IIDecl importDecl)
-- Replace the context.
if (fst canAdd)
then do
setContext $ IIDecl importDecl : oldImps
else do
setContext $ oldImps
where
-- Check whether an import is the same as another import (same module).
importOf :: ImportDecl RdrName -> InteractiveImport -> Bool
importOf _ (IIModule _) = False
importOf imp (IIDecl decl) = ((==) `on` (unLoc . ideclName)) decl imp
-- Check whether an import is an *implicit* import of something.
implicitImportOf :: ImportDecl RdrName -> InteractiveImport -> Bool
implicitImportOf _ (IIModule _) = False
implicitImportOf imp (IIDecl decl) = ideclImplicit decl && imp `importOf` IIDecl decl
-- Check whether an import is hidden.
isHiddenImport :: ImportDecl RdrName -> Bool
isHiddenImport imp = case ideclHiding imp of
Just (True, _) -> True
_ -> False
-- | Evaluate a series of declarations.
-- Return all names which were bound by these declarations.
evalDeclarations :: GhcMonad m => String -> m [String]
evalDeclarations decl = do
names <- runDecls decl
flags <- getSessionDynFlags
return $ map (replace ":Interactive." "" . showPpr flags) names
-- | Get the type of an expression and convert it to a string.
getType :: GhcMonad m => String -> m String
getType expr = do
result <- exprType expr
flags <- getSessionDynFlags
let typeStr = showSDocUnqual flags $ ppr result
return typeStr
|
aostiles/LiveHaskell
|
src/IHaskell/Eval/Util.hs
|
Haskell
|
mit
| 7,996
|
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE UndecidableInstances #-}
module Type.Sequence where
import Prelude
import GHC.TypeLits
type family Succ (a :: k) :: k
type instance Succ (a :: Nat) = a + 1
type family Empty :: k
type instance Empty = '[]
type family Zero :: k
type instance Zero = 0
type family Range (begin :: k) (end :: k) :: [k] where
Range b b = Empty
Range b e = b ': Range (Succ b) e
type family Enumerate end where Enumerate end = Range Zero end -- Implemented as TF because #11375
|
wdanilo/typelevel
|
src/Type/Sequence.hs
|
Haskell
|
apache-2.0
| 518
|
import Controller (withYwitter)
import Network.Wai.Handler.Warp (run)
main :: IO ()
main = withYwitter $ run 3000
|
tanakh/Ywitter
|
production.hs
|
Haskell
|
bsd-2-clause
| 115
|
module Stats (statsMiddleware) where
import Prelude
import Control.Concurrent
import Control.Concurrent.STM
import qualified Network.Wai as Wai
import qualified Data.ByteString.Char8 as BC
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad
import Control.Monad.Trans (liftIO)
import qualified Data.Text as T
import Control.Monad.Trans.Resource (runResourceT)
import Foundation (DBPool, withDBPool, BitloveEnv)
import Model.Stats (addCounter)
import Model.Download (InfoHash (InfoHash))
type Key = (T.Text, BC.ByteString)
type StatsBuffer = TVar (Map Key (TVar Integer))
statsMiddleware :: BitloveEnv -> DBPool -> IO Wai.Middleware
statsMiddleware env pool = do
tBuf <- newTVarIO $ Map.empty
return $ \app req ->
do liftIO $ countRequest env pool tBuf req
app req
countRequest :: BitloveEnv -> DBPool -> StatsBuffer -> Wai.Request -> IO ()
countRequest env pool tBuf req
| "/static/" `BC.isPrefixOf` Wai.rawPathInfo req =
-- Ignore static resources
return ()
| Wai.rawPathInfo req == "/by-enclosure.json" =
-- Track referrer for API calls
let referrer = fromMaybe "" $ "Referer" `lookup` Wai.requestHeaders req
in increaseCounter pool tBuf ("by-enclosure.json", referrer) 1
| otherwise =
-- All others: just method & path
let kind = "ui/" `T.append` T.pack (show env)
info = Wai.requestMethod req `BC.append`
" " `BC.append`
Wai.rawPathInfo req
in increaseCounter pool tBuf (kind, info) 1
increaseCounter :: DBPool -> StatsBuffer -> Key -> Integer -> IO ()
increaseCounter pool tBuf key increment = do
isNew <-
atomically $ do
buf <- readTVar tBuf
case key `Map.lookup` buf of
Nothing ->
do tIncrement <- newTVar increment
writeTVar tBuf $ Map.insert key tIncrement buf
return True
Just tIncrement ->
do modifyTVar tIncrement (+ increment)
return False
when isNew $ do
forkIO $ do
threadDelay second
flushCounter pool tBuf key
return ()
second :: Int
second = 1000000
flushCounter :: DBPool -> StatsBuffer -> Key -> IO ()
flushCounter pool tBuf key = do
increment <-
atomically $ do
buf <- readTVar tBuf
increment <- maybe (return 0) readTVar $
key `Map.lookup` buf
writeTVar tBuf $ Map.delete key buf
return increment
let (kind, info) = key
case increment of
increment
| increment > 0 ->
runResourceT $
withDBPool pool $
addCounter kind (InfoHash info) increment
_ ->
putStrLn $ "Warning: stale counter for " ++ show key
|
jannschu/bitlove-ui
|
Stats.hs
|
Haskell
|
bsd-2-clause
| 2,832
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE Unsafe #-}
module Concurrent.Primitive.Ref
(
-- * Primitive References
PrimRef(..)
, newPrimRef
, newPinnedPrimRef
, newAlignedPinnedPrimRef
, readPrimRef
, writePrimRef
, primRefContents
-- * Frozen Primitive References
, FrozenPrimRef(..)
, newFrozenPrimRef
, unsafeFreezePrimRef
, unsafeThawPrimRef
, indexFrozenPrimRef
, frozenPrimRefContents
-- * Atomic Operations
, casInt
, fetchAddInt
, fetchSubInt
, fetchAndInt
, fetchNandInt
, fetchOrInt
, fetchXorInt
, atomicReadInt
, atomicWriteInt
-- * Prefetching
, prefetchPrimRef0
, prefetchPrimRef1
, prefetchPrimRef2
, prefetchPrimRef3
, prefetchFrozenPrimRef0
, prefetchFrozenPrimRef1
, prefetchFrozenPrimRef2
, prefetchFrozenPrimRef3
) where
import Concurrent.Primitive.Array
import Control.Monad.Primitive
import Control.Monad.ST
import Data.Data
import Data.Primitive
import GHC.Prim
import GHC.Types (Int(I#))
#ifdef HLINT
{-# ANN module "HLint: ignore Eta reduce" #-}
{-# ANN module "HLint: ignore Reduce duplication" #-}
#endif
--------------------------------------------------------------------------------
-- * Primitive References
--------------------------------------------------------------------------------
newtype PrimRef s a = PrimRef (MutableByteArray s)
#ifndef HLINT
type role PrimRef nominal nominal
#endif
-- | Create a primitive reference.
newPrimRef :: (PrimMonad m, Prim a) => a -> m (PrimRef (PrimState m) a)
newPrimRef a = do
m <- newByteArray (sizeOf a)
writeByteArray m 0 a
return (PrimRef m)
{-# INLINE newPrimRef #-}
-- | Create a pinned primitive reference.
newPinnedPrimRef :: (PrimMonad m, Prim a) => a -> m (PrimRef (PrimState m) a)
newPinnedPrimRef a = do
m <- newPinnedByteArray (sizeOf a)
writeByteArray m 0 a
return (PrimRef m)
{-# INLINE newPinnedPrimRef #-}
-- | Create a pinned primitive reference with the appropriate alignment for its contents.
newAlignedPinnedPrimRef :: (PrimMonad m, Prim a) => a -> m (PrimRef (PrimState m) a)
newAlignedPinnedPrimRef a = do
m <- newAlignedPinnedByteArray (sizeOf a) (alignment a)
writeByteArray m 0 a
return (PrimRef m)
{-# INLINE newAlignedPinnedPrimRef #-}
-- | Read a primitive value from the reference
readPrimRef :: (PrimMonad m, Prim a) => PrimRef (PrimState m) a -> m a
readPrimRef (PrimRef m) = readByteArray m 0
{-# INLINE readPrimRef #-}
-- | Write a primitive value to the reference
writePrimRef :: (PrimMonad m, Prim a) => PrimRef (PrimState m) a -> a -> m ()
writePrimRef (PrimRef m) a = writeByteArray m 0 a
{-# INLINE writePrimRef #-}
instance Eq (PrimRef s a) where
PrimRef m == PrimRef n = sameMutableByteArray m n
{-# INLINE (==) #-}
-- | Yield a pointer to the data of a 'PrimRef'. This operation is only safe on pinned byte arrays allocated by
-- 'newPinnedPrimRef' or 'newAlignedPinnedPrimRef'.
primRefContents :: PrimRef s a -> Addr
primRefContents (PrimRef m) = mutableByteArrayContents m
{-# INLINE primRefContents #-}
--------------------------------------------------------------------------------
-- * Frozen Primitive References
--------------------------------------------------------------------------------
-- | Convert a mutable 'PrimRef' to an immutable one without copying. The reference should not be modified after the conversion.
unsafeFreezePrimRef :: PrimMonad m => PrimRef (PrimState m) a -> m (FrozenPrimRef a)
unsafeFreezePrimRef (PrimRef m) = FrozenPrimRef <$> unsafeFreezeByteArray m
{-# INLINE unsafeFreezePrimRef #-}
newtype FrozenPrimRef a = FrozenPrimRef ByteArray
#ifndef HLINT
type role FrozenPrimRef nominal
#endif
newFrozenPrimRef :: Prim a => a -> FrozenPrimRef a
newFrozenPrimRef a = runST $ newPrimRef a >>= unsafeFreezePrimRef
-- | Read the stored primitive value from the frozen reference.
indexFrozenPrimRef :: Prim a => FrozenPrimRef a -> a
indexFrozenPrimRef (FrozenPrimRef ba) = indexByteArray ba 0
{-# INLINE indexFrozenPrimRef #-}
-- | Convert an immutable primitive reference to a mutable one without copying. The original reference should not be used after the conversion.
unsafeThawPrimRef :: PrimMonad m => FrozenPrimRef a -> m (PrimRef (PrimState m) a)
unsafeThawPrimRef (FrozenPrimRef m) = PrimRef <$> unsafeThawByteArray m
{-# INLINE unsafeThawPrimRef #-}
-- | Yield a pointer to the data of a 'FrozenPrimRef'. This operation is only safe on pinned byte arrays allocated by
-- 'newPinnedPrimRef' or 'newAlignedPinnedPrimRef' and then subsequently frozen.
frozenPrimRefContents :: FrozenPrimRef a -> Addr
frozenPrimRefContents (FrozenPrimRef m) = byteArrayContents m
{-# INLINE frozenPrimRefContents #-}
--------------------------------------------------------------------------------
-- * Atomic Operations
--------------------------------------------------------------------------------
-- | Given a primitive reference, the expected old value, and the new value, perform an atomic compare and swap i.e. write the new value if the current value matches the provided old value. Returns the value of the element before the operation. Implies a full memory barrier.
casInt :: PrimMonad m => PrimRef (PrimState m) Int -> Int -> Int -> m Int
casInt (PrimRef (MutableByteArray m)) (I# old) (I# new) = primitive $ \s -> case casIntArray# m 0# old new s of
(# s', result #) -> (# s', I# result #)
-- | Given a reference, and a value to add, atomically add the value to the element. Returns the value of the element before the operation. Implies a full memory barrier.
fetchAddInt :: PrimMonad m => PrimRef (PrimState m) Int -> Int -> m Int
fetchAddInt (PrimRef (MutableByteArray m)) (I# x) = primitive $ \s -> case fetchAddIntArray# m 0# x s of
(# s', result #) -> (# s', I# result #)
-- | Given a reference, and a value to subtract, atomically subtract the value from the element. Returns the value of the element before the operation. Implies a full memory barrier.
fetchSubInt :: PrimMonad m => PrimRef (PrimState m) Int -> Int -> m Int
fetchSubInt (PrimRef (MutableByteArray m)) (I# x) = primitive $ \s -> case fetchSubIntArray# m 0# x s of
(# s', result #) -> (# s', I# result #)
-- | Given a reference, and a value to bitwise and, atomically and the value with the element. Returns the value of the element before the operation. Implies a full memory barrier.
fetchAndInt :: PrimMonad m => PrimRef (PrimState m) Int -> Int -> m Int
fetchAndInt (PrimRef (MutableByteArray m)) (I# x) = primitive $ \s -> case fetchAndIntArray# m 0# x s of
(# s', result #) -> (# s', I# result #)
-- | Given a reference, and a value to bitwise nand, atomically nand the value with the element. Returns the value of the element before the operation. Implies a full memory barrier.
fetchNandInt :: PrimMonad m => PrimRef (PrimState m) Int -> Int -> m Int
fetchNandInt (PrimRef (MutableByteArray m)) (I# x) = primitive $ \s -> case fetchNandIntArray# m 0# x s of
(# s', result #) -> (# s', I# result #)
-- | Given a reference, and a value to bitwise or, atomically or the value with the element. Returns the value of the element before the operation. Implies a full memory barrier.
fetchOrInt :: PrimMonad m => PrimRef (PrimState m) Int -> Int -> m Int
fetchOrInt (PrimRef (MutableByteArray m)) (I# x) = primitive $ \s -> case fetchOrIntArray# m 0# x s of
(# s', result #) -> (# s', I# result #)
-- | Given a reference, and a value to bitwise xor, atomically xor the value with the element. Returns the value of the element before the operation. Implies a full memory barrier.
fetchXorInt :: PrimMonad m => PrimRef (PrimState m) Int -> Int -> m Int
fetchXorInt (PrimRef (MutableByteArray m)) (I# x) = primitive $ \s -> case fetchXorIntArray# m 0# x s of
(# s', result #) -> (# s', I# result #)
-- | Given a reference, read an element. Implies a full memory barrier.
atomicReadInt :: PrimMonad m => PrimRef (PrimState m) Int -> m Int
atomicReadInt (PrimRef (MutableByteArray m)) = primitive $ \s -> case atomicReadIntArray# m 0# s of
(# s', result #) -> (# s', I# result #)
-- | Given a reference, write an element. Implies a full memory barrier.
atomicWriteInt :: PrimMonad m => PrimRef (PrimState m) Int -> Int -> m ()
atomicWriteInt (PrimRef (MutableByteArray m)) (I# x) = primitive_ $ \s -> atomicWriteIntArray# m 0# x s
instance (Prim a, Data a) => Data (FrozenPrimRef a) where
gfoldl f z m = z newFrozenPrimRef `f` indexFrozenPrimRef m
toConstr _ = newFrozenPrimRefConstr
gunfold k z c = case constrIndex c of
1 -> k (z newFrozenPrimRef)
_ -> error "gunfold"
dataTypeOf _ = frozenPrimRefDataType
newFrozenPrimRefConstr :: Constr
newFrozenPrimRefConstr = mkConstr frozenPrimRefDataType "newFrozenPrimRef" [] Prefix
frozenPrimRefDataType :: DataType
frozenPrimRefDataType = mkDataType "Data.Transient.Primitive.FrozenPrimRef" [newFrozenPrimRefConstr]
prefetchPrimRef0, prefetchPrimRef1, prefetchPrimRef2, prefetchPrimRef3 :: PrimMonad m => PrimRef (PrimState m) a -> m ()
prefetchPrimRef0 (PrimRef m) = prefetchMutableByteArray0 m 0
prefetchPrimRef1 (PrimRef m) = prefetchMutableByteArray1 m 0
prefetchPrimRef2 (PrimRef m) = prefetchMutableByteArray2 m 0
prefetchPrimRef3 (PrimRef m) = prefetchMutableByteArray3 m 0
prefetchFrozenPrimRef0, prefetchFrozenPrimRef1, prefetchFrozenPrimRef2, prefetchFrozenPrimRef3 :: PrimMonad m => FrozenPrimRef a -> m ()
prefetchFrozenPrimRef0 (FrozenPrimRef m) = prefetchByteArray0 m 0
prefetchFrozenPrimRef1 (FrozenPrimRef m) = prefetchByteArray1 m 0
prefetchFrozenPrimRef2 (FrozenPrimRef m) = prefetchByteArray2 m 0
prefetchFrozenPrimRef3 (FrozenPrimRef m) = prefetchByteArray3 m 0
|
ekmett/concurrent
|
src/Concurrent/Primitive/Ref.hs
|
Haskell
|
bsd-2-clause
| 9,700
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
module Playlistach.Soundcloud (searchTracks, getStreamUrl) where
import Data.Coerce
import Data.Aeson
import Control.Monad (mzero)
import Control.Monad.Trans.Either (EitherT(..))
import Control.Exception (throwIO)
import Network.HTTP.Types.Method (methodGet)
import Servant
import Servant.Client
import Formatting
import Playlistach.Common
import Playlistach.ServantExt
import Playlistach.Model.Track (Track)
import qualified Playlistach.Model.Track as T
import qualified Playlistach.Model.Origin as Origin
newtype ScTrack = ScTrack Track
instance FromJSON ScTrack where
parseJSON (Object v) = do
id <- v .: "id"
title <- v .: "title"
duration <- v .: "duration"
url <- v .: "permalink_url"
return $ ScTrack $ T.Track
{ T.externalId = show (id :: Int)
, T.title = title
, T.duration = duration `div` 1000
, T.streamUrl = Nothing
, T.permalinkUrl = Just url
, T.origin = Origin.SC }
parseJSON _ = mzero
type API = "tracks" :> RequiredParam "client_id" String :> RequiredParam "q" String :> Get '[JSON] [ScTrack]
_searchTracks = client (Proxy :: Proxy API) $ BaseUrl Https "api.soundcloud.com" 443
searchTracks :: String -> String -> IO [Track]
searchTracks clientId query = runServantClient $
coerce $ _searchTracks clientId query
getStreamUrl :: String -> Track -> String
getStreamUrl clientId track =
formatToString template (T.externalId track) clientId
where
template = "https://api.soundcloud.com/tracks/" % string % "/stream?client_id=" % string
|
aemxdp/playlistach
|
backend/Playlistach/Soundcloud.hs
|
Haskell
|
bsd-3-clause
| 1,856
|
{-# LANGUAGE OverloadedStrings #-}
module MySQL.Token where
import qualified Data.ByteString as BS
import Data.List (intersperse)
-- | MySQL tokens
data LToken = LTokAdd -- ADD (R)
| LTokAll -- ALL (R)
| LTokAlter -- ALTER (R)
| LTokAnd -- AND (R)
| LTokAs -- AS (R)
| LTokAsc -- ASC (R)
| LTokBefore -- BEFORE (R)
| LTokBetween -- BETWEEN (R)
| LTokBigInt -- BIGINT (R)
-- | LTokBinary -- BINARY (R)
| LTokBlob -- BLOB (R)
| LTokBoth -- BOTH (R)
| LTokBy -- BY (R)
-- | LTokCase -- CASE (R)
| LTokChar -- CHAR (R)
| LTokCharacter -- CHARACTER (R)
| LTokCheck -- CHECK (R)
| LTokCollate -- COLLATE (R)
| LTokColumn -- COLUMN (R)
| LTokConstraint -- CONSTRAINT (R)
| LTokCreate -- CREATE (R)
| LTokCross -- CROSS (R)
| LTokDecimal -- DECIMAL (R)
| LTokDeclare -- DECLARE (R)
| LTokDefault -- DEFAULT (R)
| LTokDelete -- DELETE (R)
| LTokDesc -- DESC (R)
| LTokDistinct -- DISTINCT (R)
-- | LTokIntDiv -- DIV (R)
| LTokDouble -- DOUBLE (R)
| LTokDrop -- DROP (R)
| LTokExists -- EXISTS (R)
| LTokFalse -- FALSE (R)
| LTokFloat -- FLOAT (R)
| LTokForeign -- FOREIGN (R)
| LTokFrom -- FROM (R)
| LTokFullText -- FULLTEXT (R)
| LTokGroup -- GROUP (R)
| LTokHaving -- HAVING (R)
| LTokIgnore -- IGNORE (R)
| LTokIn -- IN (R)
| LTokIndex -- INDEX (R)
| LTokInner -- INNER (R)
| LTokInsert -- INSERT (R)
| LTokInt -- INT (R)
| LTokInteger -- INTEGER (R)
| LTokInterval -- INTERVAL (R)
| LTokInto -- INTO (R)
-- | LTokIs -- IS (R)
| LTokJoin -- JOIN (R)
| LTokKey -- KEY (R)
| LTokKeys -- KEYS (R)
| LTokLeft -- LEFT (R)
-- | LTokLike -- LIKE (R)
| LTokLimit -- LIMIT (R)
| LTokLong -- LONG (R)
| LTokMatch -- MATCH (R)
| LTokMediumInt -- MEDIUMINT (R)
-- | LTokMod -- MOD (R)
| LTokNot -- NOT (R)
| LTokNull -- NULL (R)
| LTokOn -- ON (R)
| LTokOr -- OR (R)
| LTokOrder -- ORDER (R)
| LTokOuter -- OUTER (R)
| LTokPrimary -- PRIMARY (R)
| LTokRange -- RANGE (R)
| LTokReal -- REAL (R)
| LTokReferences -- REFERENCES (R)
| LTokReplace -- REPLACE (R)
| LTokRight -- RIGHT (R)
| LTokSchema -- SCHEMA (R)
| LTokSelect -- SELECT (R)
| LTokSet -- SET (R)
| LTokSmallInt -- SMALLINT (R)
| LTokStraightJoin -- STRAIGHT_JOIN (R)
| LTokTable -- TABLE (R)
| LTokTinyInt -- TINYINT (R)
| LTokTrue -- TRUE (R)
| LTokUnion -- UNION (R)
| LTokUnique -- UNIQUE (R)
| LTokUnsigned -- UNSIGNED (R)
| LTokUpdate -- UPDATE (R)
| LTokUsing -- USING (R)
| LTokValues -- VALUES (R)
| LTokVarChar -- VARCHAR (R)
| LTokVarying -- VARYING (R)
| LTokWhere -- WHERE (R)
| LTokWith -- WITH (R)
-- Syntax
--
| LTokOpenPar -- (
| LTokClosePar -- )
| LTokComma -- ,
-- String Operators
--
| LTokBinary -- BINARY
| LTokCase -- CASE
| LTokIntDiv -- DIV
| LTokIs -- IS
| LTokIsNot -- IS NOT
| LTokIsNotNull -- IS NOT NULL
| LTokIsNull -- IS NULL
| LTokLike -- LIKE
| LTokNotLike -- NOT LIKE
| LTokNotRegexp -- NOT REGEXP
| LTokRegexp -- REGEXP
| LTokSoundsLike -- SOUNDS LIKE
| LTokXOr -- XOR
-- Operators
--
| LTokBitAnd -- &
| LTokBitInv -- ~
| LTokBitOr -- '|'
| LTokBitXOr -- '^'
| LTokDiv -- /
| LTokLShift -- <<
| LTokMinus -- -
| LTokMod -- MOD, %
| LTokPlus -- +
| LTokRShift -- >>
| LTokMul -- '*'
-- Comparison Operators
--
| LTokEq -- =
| LTokSafeNotEq -- <=>
| LTokGT -- >
| LTokGTE -- >=
| LTokLT -- <
| LTokLTE -- <=
| LTokNotEq -- !=, <>
-- Logical Operators
--
| LTokAndOp -- &&
| LTokNotOp -- !
| LTokOrOp -- '||'
-- Assignment Operators
--
| LTokAssign -- :=
-- Terms with values
--
| LTokNum String -- number constant
| LTokStr String -- string constant
| LTokIdent LIdentToken -- identifier
| LTokEof -- end of file
-- Symbolic terms
--
| LTokSymbolic Integer -- BS.ByteString
deriving Eq
data LIdentToken = LIdentSimpleToken String
| LIdentQualifiedToken String String
| LIdentDoubleQualifiedToken String String String
deriving Eq
instance Show LToken where
show LTokAdd = "ADD"
show LTokAll = "ALL"
show LTokAlter = "ALTER"
show LTokAnd = "AND"
show LTokAs = "AS"
show LTokAsc = "ASC"
show LTokBefore = "BEFORE"
show LTokBetween = "BETWEEN"
show LTokBigInt = "BIGINT"
-- show LTokBinary = "BINARY"
show LTokBlob = "BLOB"
show LTokBoth = "BOTH"
show LTokBy = "BY"
-- show LTokCase = "CASE"
show LTokChar = "CHAR"
show LTokCharacter = "CHARACTER"
show LTokCheck = "CHECK"
show LTokCollate = "COLLATE"
show LTokColumn = "COLUMN"
show LTokConstraint = "CONSTRAINT"
show LTokCreate = "CREATE"
show LTokCross = "CROSS"
show LTokDecimal = "DECIMAL"
show LTokDeclare = "DECLARE"
show LTokDefault = "DEFAULT"
show LTokDelete = "DELETE"
show LTokDesc = "DESC"
show LTokDistinct = "DISTINCT"
-- show LTokDiv = "DIV"
show LTokDouble = "DOUBLE"
show LTokDrop = "DROP"
show LTokExists = "EXISTS"
show LTokFalse = "FALSE"
show LTokFloat = "FLOAT"
show LTokForeign = "FOREIGN"
show LTokFrom = "FROM"
show LTokFullText = "FULLTEXT"
show LTokGroup = "GROUP"
show LTokHaving = "HAVING"
show LTokIgnore = "IGNORE"
show LTokIn = "IN"
show LTokIndex = "INDEX"
show LTokInner = "INNER"
show LTokInsert = "INSERT"
show LTokInt = "INT"
show LTokInteger = "INTEGER"
show LTokInterval = "INTERVAL"
show LTokInto = "INTO"
-- show LTokIs = "IS"
show LTokJoin = "JOIN"
show LTokKey = "KEY"
show LTokKeys = "KEYS"
show LTokLeft = "LEFT"
-- show LTokLike = "LIKE"
show LTokLimit = "LIMIT"
show LTokLong = "LONG"
show LTokMatch = "MATCH"
show LTokMediumInt = "MEDIUMINT"
-- show LTokMod = "MOD"
show LTokNot = "NOT"
show LTokNull = "NULL"
show LTokOn = "ON"
show LTokOr = "OR"
show LTokOrder = "ORDER"
show LTokOuter = "OUTER"
show LTokPrimary = "PRIMARY"
show LTokRange = "RANGE"
show LTokReal = "REAL"
show LTokReferences = "REFERENCES"
show LTokReplace = "REPLACE"
show LTokRight = "RIGHT"
show LTokSchema = "SCHEMA"
show LTokSelect = "SELECT"
show LTokSet = "SET"
show LTokSmallInt = "SMALLINT"
show LTokStraightJoin = "STRAIGHT_JOIN"
show LTokTable = "TABLE"
show LTokTinyInt = "TINYINT"
show LTokTrue = "TRUE"
show LTokUnion = "UNION"
show LTokUnique = "UNIQUE"
show LTokUnsigned = "UNSIGNED"
show LTokUpdate = "UPDATE"
show LTokUsing = "USING"
show LTokValues = "VALUES"
show LTokVarChar = "VARCHAR"
show LTokVarying = "VARYING"
show LTokWhere = "WHERE"
show LTokWith = "WITH"
-- Syntax
show LTokOpenPar = "("
show LTokClosePar = ")"
show LTokComma = ","
-- String Operators
--
show LTokBinary = "BINARY"
show LTokCase = "CASE"
show LTokIntDiv = "DIV"
show LTokIs = "IS"
show LTokIsNot = "IS NOT"
show LTokIsNotNull = "IS NOT NULL"
show LTokIsNull = "IS NULL"
show LTokLike = "LIKE"
show LTokNotLike = "NOT LIKE"
show LTokNotRegexp = "NOT REGEXP"
show LTokRegexp = "REGEXP"
show LTokSoundsLike = "SOUNDS LIKE"
show LTokXOr = "XOR"
-- Operators
--
show LTokBitAnd = "&"
show LTokBitInv = "~"
show LTokBitOr = "|"
show LTokBitXOr = "^"
show LTokDiv = "/"
show LTokLShift = "<<"
show LTokMinus = "-"
show LTokMod = "%"
show LTokPlus = "+"
show LTokRShift = ">>"
show LTokMul = "*"
-- Comparison Operators
--
show LTokEq = "="
show LTokSafeNotEq = "<=>"
show LTokGT = ">"
show LTokGTE = ">="
show LTokLT = "<"
show LTokLTE = "<="
show LTokNotEq = "!= (or <>)"
-- Logical Operators
--
show LTokAndOp = "&&"
show LTokNotOp = "!"
show LTokOrOp = "||"
-- Assignment Operators
--
show LTokAssign = ":="
show (LTokNum n) = "number: " ++ n
show (LTokStr s) = "string: " ++ s
show (LTokIdent i) = "identifier: " ++ show i
show LTokEof = "EOF"
show (LTokSymbolic n) = "@symbolic" ++ show n ++ "@"
instance Show LIdentToken where
show (LIdentSimpleToken s) = s
show (LIdentQualifiedToken s1 s2) = s1 ++ "." ++ s2
show (LIdentDoubleQualifiedToken s1 s2 s3) = concat $ intersperse "." [s1, s2, s3]
|
sukwon0709/mysql
|
src/MySQL/Token.hs
|
Haskell
|
bsd-3-clause
| 11,494
|
module Main where
import Folly.DSL
import Folly.TPTP
import Control.Monad
import Control.Applicative
p = predicate "p"
q = predicate "q"
s = relation "s"
[a,b,c,d] = map (satsbokstav . return) "abcd"
main :: IO ()
main = zipWithM_ writeTPTP [ "test" ++ show i ++ ".p" | i <- [0 :: Integer ..] ]
[ [ axiom' $ forall' $ \ x y z -> s x y /\ s y z ==> s x z
, axiom' $ forall' $ \ x -> neg (s x x)
, conjecture' $ forall' $ \ x y -> s x y ==> neg (s y x)
]
, [ axiom' $ (exists' $ \ x -> p x) ==> a
, conjecture' $ forall' $ \ x -> p x ==> a
]
, [ axiom' $ forall' ((==>) <$> p <*> q)
, conjecture' $ forall' p ==> forall' q
]
, [ axiom' $ forall' ((==>) <$> p <*> (neg . q))
, conjecture' $ neg $ exists' ((/\) <$> p <*> q)
]
, [ axiom' $ forall' ((==>) <$> p <*> (neg . q))
, conjecture' $ neg $ exists' ((/\) <$> p <*> q)
]
, [ axiom' $ (a /\ b /\ c) \/ d
, conjecture' $ (a \/ d) /\ (b \/ d) /\ (c \/ d)
]
]
|
danr/folly
|
examples/Test.hs
|
Haskell
|
bsd-3-clause
| 1,060
|
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
data Pair a = P a Int | D a Bool
goo z = P z z
baz = goo 10
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/adt0.hs
|
Haskell
|
bsd-3-clause
| 158
|
-- Copyright 2011 Wu Xingbo
-- LANGUAGE {{{
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DoAndIfThenElse #-}
-- }}}
-- module export {{{
module Eval.DServ (
aHandler, ioaHandler,
AHandler, IOHandler,
DServerInfo(..), DService(..), DServerData(..),
ZKInfo(..), DResp(..),
respOK, respFail,
findDefaultZK,
commonInitial,
forkServer, closeServer,
waitCloseCmd, waitCloseSignal,
listServer, accessServer,
forkWatcher, forkChildrenWatcher, forkValueWatcher,
clientNoRecv, clientTwoStage, clientRecvA,
putObject, getObject,
putObjectLazy, getObjectLazy,
) where
-- }}}
-- import {{{
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified System.Posix.Signals as Sig
----
import Prelude (($), (.), (/), (-), (+), (>), (==), Eq, Ord,
String, fromIntegral, id, Float, fst, Integral, Integer)
import Control.Applicative ((<$>))
import Control.Monad (Monad(..), void, when,)
import Control.Concurrent (forkIO, yield, ThreadId,)
import Control.Concurrent.MVar (MVar, putMVar, takeMVar,
newEmptyMVar, tryPutMVar,)
import Control.Exception (SomeException, Exception,
handle, bracket, catch, throwTo,)
import Data.Either (Either(..))
import Data.Serialize (Serialize(..), encode, decode, encodeLazy, decodeLazy, )
import Data.Int (Int)
import Data.Bool (Bool(..))
import Data.IORef (IORef, newIORef, writeIORef, readIORef,)
import Data.List ((++), map, tail, break, head, lines)
import Data.Maybe (Maybe(..), maybe,)
import Data.Typeable (Typeable(..),)
import GHC.Generics (Generic)
import Network (HostName, PortID(..), Socket, connectTo,
accept, listenOn, sClose,)
import Network.Socket(getNameInfo, SockAddr(..),)
import System.IO (IO, hGetLine, hFlush, hPutStrLn, Handle, hClose, getLine,
hSetBuffering, BufferMode(..), putStrLn, hWaitForInput,
readFile, stdin)
import System.Directory (getHomeDirectory,)
import Text.Read (read)
import Text.Show (Show(..))
import Text.Printf (printf)
import qualified Zookeeper as Zoo
-- }}}
-- data/type {{{
-- handler on a Handle (Socket or FD)
type IOHandler = AHandler ()
type AHandler a = Handle -> IO a
-- DServerInfo: on ZK. {{{
data DServerInfo = DServerInfo
{ dsiHostName :: HostName,
dsiPortNumber :: Integer,
dsiServType :: String
} deriving (Generic, Eq, Ord)
instance Serialize DServerInfo where
instance Show DServerInfo where
show (DServerInfo h p t) = printf "#DServerInfo: [ %s:%d ] (%s)" h p t
-- }}}
-- DServerData: on local process. {{{
data DServerData = DServerData
{ dsdThreadID :: ThreadId,
dsdPortNumber :: Integer,
dsdZooKeeper :: Zoo.ZHandle,
dsdRunning :: IORef Bool,
dsdService :: DService,
dsdServerInfo :: DServerInfo
}
instance Show DServerData where
show (DServerData tid port zk _ _ info) =
"DServerData:" ++ show (tid, port, zk, info)
-- }}}
-- DService: what it do {{{
data DService = DService
{ dsType :: String,
dsHandler :: IOHandler,
dsCloseHook :: Maybe IOHandler
}
-- }}}
-- ZKInfo: zookeeper info {{{
data ZKInfo = ZKInfo String deriving (Show)
-- }}}
-- CloseException: close server {{{
data CloseException = CloseException
deriving (Typeable, Show)
instance Exception CloseException where
-- }}}
-- DSResp {{{
data DResp = DRFail | DROkay deriving (Generic, Show)
instance Serialize DResp where
-- }}}
-- }}}
-- common {{{
-- findDefaultZK {{{
findDefaultZK :: IO (Maybe ZKInfo)
findDefaultZK = do
rcfile <- (++ "/.zkrc") <$> getHomeDirectory
(Just . ZKInfo . head . lines <$> readFile rcfile) `catch` aHandler Nothing
-- }}}
-- commonInitial {{{
commonInitial :: IO ()
commonInitial = do
void $ Sig.installHandler Sig.sigPIPE Sig.Ignore Nothing
Zoo.setDebugLevel Zoo.LogError
-- }}}
-- getHostName {{{
getHostName :: IO HostName
getHostName = do
mbhost <- fst <$> getNameInfo [] True False (SockAddrUnix "localhost")
return $ maybe "localhost" id mbhost
-- }}}
-- portNumber {{{
portNumber :: Integral a => a -> PortID
portNumber a = PortNumber $ fromIntegral a
-- }}}
-- aHandler {{{
aHandler :: a -> SomeException -> IO a
aHandler a e = do
putStrLn $ "aHandler caught Exception: " ++ show e
return a
-- }}}
-- ioaHandler {{{
ioaHandler :: IO () -> a -> SomeException -> IO a
ioaHandler io a e = do
putStrLn $ "ioaHandler caught Exception: " ++ show e
io
return a
-- }}}
-- respOK {{{
respOK :: Handle -> IO ()
respOK remoteH = putObject remoteH DROkay
-- }}}
-- respFail {{{
respFail :: Handle -> IO ()
respFail remoteH = putObject remoteH DRFail
-- }}}
-- }}}
-- server {{{
-- listenSS {{{
listenSS :: Integer -> IO (Maybe Socket)
listenSS port = (Just <$> listenOn pn) `catch` aHandler Nothing
where pn = portNumber port
-- }}}
-- showDServerInfo {{{
showDServerInfo :: DServerInfo -> String
showDServerInfo (DServerInfo host port ty) =
printf "%s:%s:%s" ty host (show port)
-- }}}
-- registerZK: connect && create -> Just handle {{{
registerZK :: ZKInfo -> DServerInfo -> IO (Maybe Zoo.ZHandle)
registerZK (ZKInfo hostport) dsi = do
mbzh <- Zoo.initSafe hostport Nothing 100000
case mbzh of
Just zh -> do
mbpath <- Zoo.createSafe zh zkName (Just $ encode dsi)
Zoo.OpenAclUnsafe (Zoo.CreateMode True False)
maybe (return Nothing) (\_ -> return mbzh) mbpath
_ -> do
return Nothing
where zkName = "/d/" ++ showDServerInfo dsi
-- }}}
-- loopServer {{{
loopServer :: IORef Bool -> Socket -> DService -> IO ()
loopServer ref sock ds = do
running <- readIORef ref
when running $ do
--putStrLn "loopServer: waiting for client"
oneServer sock ds `catch` ioaHandler (writeIORef ref False) ()
--putStrLn "loopServer: oneServer forked"
loopServer ref sock ds
-- }}}
-- oneServer {{{
oneServer :: Socket -> DService -> IO ()
oneServer sock ds = do
(h, _, _) <- accept sock
hSetBuffering h $ BlockBuffering Nothing --LineBuffering
void $ forkIO $ (dsHandler ds) h `catch` aHandler ()
-- }}}
-- forkServer {{{
forkServer :: ZKInfo -> DService -> Integer -> IO (Maybe DServerData)
forkServer zki ds port = do
commonInitial
hostname <- getHostName
mbsock <- listenSS port
case mbsock of
Just sock -> do
--putStrLn "Listen OK"
let dsi = DServerInfo hostname port (dsType ds)
mbzk <- registerZK zki dsi
case mbzk of
Just zk -> do
--putStrLn "ZK OK"
ref <- newIORef True
tid <- forkIO $ loopServer ref sock ds
return $ Just $ DServerData tid port zk ref ds dsi
Nothing -> do
sClose sock
return Nothing
Nothing -> do
return Nothing
-- }}}
-- closeServer {{{
closeServer :: DServerData -> IO ()
closeServer dsd = do
Zoo.close (dsdZooKeeper dsd)
case dsCloseHook $ dsdService dsd of
Just hook -> void $ accessServer (dsdServerInfo dsd) hook
_ -> return ()
throwTo (dsdThreadID dsd) CloseException
yield
-- }}}
-- waitCloseCmd {{{
waitCloseCmd :: DServerData -> IO ()
waitCloseCmd dsd = do
iP <- hWaitForInput stdin 1000000
if iP
then do
line <- getLine
case line of
"x" -> Zoo.close (dsdZooKeeper dsd)
_ -> waitCloseCmd dsd
else waitCloseCmd dsd
-- }}}
-- waitCloseSignal {{{
waitCloseSignal :: DServerData -> IO ()
waitCloseSignal dsd = do
(mvar :: MVar ()) <- newEmptyMVar
installH Sig.sigTERM (sigHandler mvar)
installH Sig.sigINT (sigHandler mvar)
installH Sig.sigQUIT (sigHandler mvar)
takeMVar mvar
putStrLn "closed!"
where
sigHandler mvar = do
void $ tryPutMVar mvar ()
Zoo.close (dsdZooKeeper dsd)
installH sig handler = void $
Sig.installHandler sig (Sig.CatchOnce $ handler) Nothing
-- }}}
-- }}}
-- client {{{
-- listServer {{{
-- list online servers, lookup info. from ZK.
listServer :: ZKInfo -> IO (Maybe [DServerInfo])
listServer (ZKInfo hostport) = do
mbzh <- Zoo.initSafe hostport Nothing 100000
case mbzh of
Just zh -> do
-- putStrLn "client: init ok"
mbChildList <- Zoo.getChildrenSafe zh "/d" Zoo.NoWatch
case mbChildList of
Just list -> return $ Just $ map parseDServerInfo list
Nothing -> return Nothing
Nothing -> return Nothing
-- }}}
-- parseDServerInfo {{{
parseDServerInfo :: String -> DServerInfo
parseDServerInfo str = DServerInfo host port ty
where
(ty,rest1) = break (== ':') str
(host, rest2) = break (== ':') $ tail rest1
port = fromIntegral $ (read $ tail rest2 :: Integer)
-- }}}
-- connectSocket {{{
connectSocket :: DServerInfo -> IO Handle
connectSocket (DServerInfo n p _) = do
--putStrLn $ show dsi
h <- connectTo n $ portNumber p
--putStrLn "client -> Server ok"
hSetBuffering h $ BlockBuffering Nothing --LineBuffering
return h
-- }}}
-- accessServer {{{
accessServer :: DServerInfo -> AHandler a -> IO (Maybe a)
accessServer dsi handler = (Just <$> runner) `catch` exHandler
where
runner = bracket (connectSocket dsi) hClose handler
exHandler (e :: SomeException) = do
putStrLn $ "accessServer, error" ++ show e
return Nothing
-- }}}
-- clientTwoStage {{{
-- two OK
clientTwoStage :: (Serialize r) => r -> AHandler Bool -> AHandler Bool
clientTwoStage req h remoteH = do
putObject remoteH req
(mbResp1 :: Maybe DResp) <- getObject remoteH
case mbResp1 of
Just DROkay -> do
ok <- h remoteH `catch` aHandler False
case ok of
True -> do
(mbResp2 :: Maybe DResp) <- getObject remoteH
case mbResp2 of
Just DROkay -> return True
Just DRFail -> putStrLn "resp2 failed" >> return False
_ -> putStrLn "recv resp2 failed" >> return False
False -> putStrLn "the work failed" >> return False
Just DRFail -> putStrLn "resp1 failed" >> return False
_ -> putStrLn "recv resp1 failed" >> return False
-- }}}
-- clientNoRecv {{{
-- only 1 OK
clientNoRecv :: (Serialize r) => r -> AHandler Bool
clientNoRecv req remoteH = do
putObject remoteH req
(mbResp1 :: Maybe DResp) <- getObject remoteH
case mbResp1 of
Just DROkay -> return True
Just DRFail -> putStrLn "resp failed" >> return False
_ -> putStrLn "recv resp failed" >> return False
-- }}}
-- clientRecvA {{{
-- two OK
clientRecvA :: (Serialize r, Serialize a) => r -> AHandler (Maybe a)
clientRecvA req remoteH = do
putObject remoteH $ req
(mbResp1 :: Maybe DResp) <- getObject remoteH
case mbResp1 of
Just DROkay -> do
(mbA :: Maybe a) <- getObject remoteH
case mbA of
Just _ -> do
(mbResp2 :: Maybe DResp) <- getObject remoteH
case mbResp2 of
Just DROkay -> return mbA
Just DRFail -> putStrLn "resp2 failed" >> return Nothing
_ -> putStrLn "recv resp2 failed" >> return Nothing
_ -> putStrLn "get A failed" >> return Nothing
Just DRFail -> putStrLn "resp1 failed" >> return Nothing
_ -> putStrLn "get resp1 failed" >> return Nothing
-- }}}
-- }}}
-- with ZK {{{
-- forkChildrenWatcher {{{
forkChildrenWatcher :: ZKInfo -> String -> ([String] -> IO a) -> IO Bool
forkChildrenWatcher zkinfo path action = do
forkWatcher zkinfo rewatcher action
where
rewatcher zh = maybe [] id <$> Zoo.getChildrenSafe zh path Zoo.Watch
-- }}}
-- forkValueWatcher {{{
forkValueWatcher :: ZKInfo -> String -> (Maybe BS.ByteString -> IO a) -> IO Bool
forkValueWatcher zkinfo path action = do
forkWatcher zkinfo rewatcher action
where
rewatcher zh = maybe Nothing fst <$> Zoo.getSafe zh path Zoo.Watch
-- }}}
-- forkWatcher {{{
forkWatcher :: ZKInfo -> (Zoo.ZHandle -> IO a) -> (a -> IO b) -> IO Bool
forkWatcher (ZKInfo hostport) rewatcher action = do
mbzh <- Zoo.initSafe hostport Nothing 100000
case mbzh of
Just zh -> do
mvar <- newEmptyMVar
Zoo.setWatcher zh $ Just $ watcher mvar
void $ rewatcher zh
void $ forkIO $ handler mvar
return True
_ -> return False
where
watcher mvar zh _ _ _ = do
--putStrLn "get event"
putMVar mvar zh
handler mvar = do
--putStrLn "handler: waiting"
zh <- takeMVar mvar
a <- rewatcher zh
void $ action a
handler mvar
-- }}}
-- }}}
-- put/get BS {{{
-- put ByteString {{{
putBS :: Handle -> BS.ByteString -> IO ()
putBS hdl bs = do
handle exHandler $ do
hPutStrLn hdl $ (show $ BS.length bs) ++ " "
BS.hPut hdl bs
hFlush hdl
where
exHandler (_ :: SomeException) = return ()
-- }}}
-- get ByteString {{{
getBS :: Handle -> IO (BS.ByteString)
getBS hdl = do
line <- hGetLine hdl
bs <- BS.hGet hdl (read $ line :: Int)
return bs
-- }}}
-- put Object on System.IO.Handle {{{
putObject :: (Serialize a) => Handle -> a -> IO ()
putObject h obj = putBS h (encode obj)
-- }}}
-- get Object on System.IO.Handle {{{
getObject :: (Serialize a) => Handle -> IO (Maybe a)
getObject h = do
ea <- decode <$> getBS h
case ea of
Left _ -> return Nothing
Right a -> return $ Just a
-- }}}
-- }}}
-- put/get BSL {{{
-- put ByteString {{{
putBSL :: Handle -> BSL.ByteString -> IO ()
putBSL hdl bs = do
handle exHandler $ do
hPutStrLn hdl $ (show $ BSL.length bs) ++ " "
BSL.hPut hdl bs
hFlush hdl
where
exHandler (_ :: SomeException) = return ()
-- }}}
-- get ByteString {{{
getBSL :: Handle -> IO (BSL.ByteString)
getBSL hdl = do
line <- hGetLine hdl
bs <- BSL.hGet hdl (read $ line :: Int)
return bs
-- }}}
-- put Object on System.IO.Handle {{{
putObjectLazy :: (Serialize a) => Handle -> a -> IO ()
putObjectLazy h obj = putBSL h (encodeLazy obj)
-- }}}
-- get Object on System.IO.Handle {{{
getObjectLazy :: (Serialize a) => Handle -> IO (Maybe a)
getObjectLazy h = do
ea <- decodeLazy <$> getBSL h
case ea of
Left _ -> return Nothing
Right a -> return $ Just a
-- }}}
-- }}}
-- vim:fdm=marker
|
wuxb45/eval
|
Eval/DServ.hs
|
Haskell
|
bsd-3-clause
| 13,891
|
module Main where
import Prelude hiding (splitAt,lines,words)
import Data.Char
import Data.String hiding (lines,words)
import Data.Monoid
import Data.Bifunctor
import qualified Data.List (intersperse,splitAt)
import qualified Data.List.Split as Split
import qualified Data.Monoid.Factorial as SFM
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Control.Foldl as L
import Control.Foldl.Transduce
import Control.Foldl.Transduce.Text
{- $quickcheck
Notes for quickchecking on the REPL:
cabal repl tests
:t sample
sample :: Show a => Gen a -> IO ()
sample (arbitrary :: Gen WordA)
-}
main :: IO ()
main = defaultMain tests
testCaseEq :: (Eq a, Show a) => TestName -> a -> a -> TestTree
testCaseEq name a1 a2 = testCase name (assertEqual "" a1 a2)
blank :: T.Text -> Bool
blank = T.all isSpace
nl :: T.Text
nl = T.pack "\n"
sp :: T.Text
sp = T.pack " "
c :: T.Text
c = T.pack "c"
{- $words
-}
newtype WordA = WordA { getWord :: T.Text } deriving (Show)
instance Arbitrary WordA where
arbitrary = do
firstChar <- oneof [pure ' ', pure '\n', arbitrary]
lastChar <- oneof [pure ' ', pure '\n', arbitrary]
middle <- listOf (frequency [(1,pure ' '),(4,arbitrary)])
return (WordA (T.pack (firstChar : (middle ++ [lastChar]))))
{- $paragraphs
-}
newtype TextChunksA = TextChunksA { getChunks :: [T.Text] } deriving (Show)
instance Arbitrary TextChunksA where
arbitrary = flip suchThat (not . blank . mconcat . getChunks) (do
TextChunksA <$> partz)
where
chunkz = frequency [
(20::Int, flip T.replicate sp <$> choose (1,40))
, (20, flip T.replicate sp <$> choose (1,3))
, (50, pure nl)
, (20, flip T.replicate c <$> choose (1,30))
, (20, flip T.replicate c <$> choose (1,3))
]
combined = mconcat <$> vectorOf 40 chunkz
partitions = infiniteListOf (choose (1::Int,7))
partz = partition [] <$> combined <*> partitions
partition :: [T.Text] -> T.Text -> [Int] -> [T.Text]
partition accum text (x:xs) =
if x >= T.length text
then reverse (text:accum)
else
let (point,rest) = T.splitAt x text
in
partition (point:accum) rest xs
partition _ _ [] = error "never happens"
shrink (TextChunksA texts) =
let removeIndex i xs =
let (xs',xs'') = Data.List.splitAt i xs
in xs' ++ tail xs''
l = length texts
in
if l == 1
then []
else map (\i -> TextChunksA (removeIndex i texts)) [0..l-1]
paragraphsBaseline
:: T.Text -> [T.Text]
paragraphsBaseline =
map (T.unlines . map T.stripStart . T.lines)
. map mconcat
. map (`mappend` [nl])
. map (Data.List.intersperse nl)
. filter (not . null)
. Split.splitWhen blank
. T.lines
ignoreLastNewline :: [T.Text] -> [T.Text]
ignoreLastNewline ts =
let
lastt = last ts
lastt' = if T.last lastt == '\n' then T.init lastt else lastt
in init ts ++ [lastt']
-- (paragraphs,chunks)
splittedParagraphs :: T.Text -> [Int] -> [([T.Text],[T.Text])]
splittedParagraphs txt splitsizes =
let
splitted = paragraphsBaseline txt
in
zip (repeat splitted) (map (flip T.chunksOf txt) splitsizes)
paragraphsUnderTest
:: [T.Text] -> [T.Text]
paragraphsUnderTest txt =
map mconcat (L.fold (folds paragraphs L.list L.list) txt)
sectionsUnderTest
:: [T.Text] -> [T.Text] -> [T.Text]
sectionsUnderTest stns txt =
map mconcat (L.fold (folds (sections stns) L.list L.list) txt)
paragraph01 :: T.Text
paragraph01 =
T.pack
" \n \n\n \n \n \
\a aa aaa \nb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bb \n \
\ ccccccccccccccccccccccc cccccccc \n\n \n \n\n ccc\
\ \n \n \nd\n\n\ne \
\\n"
paragraph02 :: T.Text
paragraph02 = T.pack " cc "
tests :: TestTree
tests =
testGroup "Tests"
[
testGroup "surround"
[
testCaseEq "surroundempty"
"prefixsuffix"
(L.fold (transduce (surround "prefix" "suffix") L.list) "")
],
testGroup "chunksOf"
[
testCaseEq "emptyList3"
([]::[[Int]])
(L.fold (folds (chunksOf 3) L.list L.list) [])
,
testCaseEq "size1"
([[1],[2],[3],[4],[5],[6],[7]]::[[Int]])
(L.fold (folds (chunksOf 1) L.list L.list) [1..7])
,
testCaseEq "size3"
([[1,2,3],[4,5,6],[7]]::[[Int]])
(L.fold (folds (chunksOf 3) L.list L.list) [1..7])
],
testGroup "textualBreak"
[
testCaseEq "beginwithdot"
".bb"
(L.fold (bisect (textualBreak (=='.')) ignore (reify id) L.mconcat) ["aa",".bb"])
,
testCaseEq "endwithdot"
"."
(L.fold (bisect (textualBreak (=='.')) ignore (reify id) L.mconcat) ["aa","bb."])
],
testGroup "newline"
[
testCaseEq "newlineempty"
(T.pack "\n")
(mconcat (L.fold (transduce newline L.list) (map T.pack [])))
,
testCaseEq "newlinenull"
(T.pack "\n")
(mconcat (L.fold (transduce newline L.list) (map T.pack [""])))
],
testGroup "words"
[
testGroup "quickcheck"
[
testProperty "quickcheck1" (\chunks -> -- list of words
let tchunks = fmap getWord chunks
in
TL.words (TL.fromChunks tchunks)
==
(fmap TL.fromChunks (L.fold (folds words L.list L.list) tchunks)))
]
],
testGroup "paragraphs"
[
testCase "paragraphs01"
(mapM_
(\(x,y) -> assertEqual "" (ignoreLastNewline x) (ignoreLastNewline (paragraphsUnderTest y)))
(splittedParagraphs paragraph01 [1..7])),
testCaseEq "newlineAtEnd"
(map T.pack ["aa\n"])
(paragraphsUnderTest (map T.pack ["a","a","\n"])),
testCaseEq "noNewlineAtEnd"
(map T.pack ["aa"])
(paragraphsUnderTest (map T.pack ["a","a"])),
testGroup "quickcheck"
[
testProperty "quickcheck1" (\(TextChunksA chunks) ->
ignoreLastNewline (paragraphsUnderTest chunks)
==
ignoreLastNewline (paragraphsBaseline (mconcat chunks)))
]
],
testGroup "sections"
[
testCaseEq "no separators at all"
(map T.pack ["aaabbcc"])
(sectionsUnderTest (map T.pack []) (map T.pack ["a","aa","bbc","c"])),
testCaseEq "incomplete separator"
(map T.pack ["123#_","aa","bb#"])
(sectionsUnderTest (map T.pack ["1234","#"]) (map T.pack ["1","23","#_1234aa#b","b#"])),
testCaseEq "small chunks"
(map T.pack ["0","01","aa","a#bb","c"])
(sectionsUnderTest (map T.pack ["_","_","##","##","##"]) (map T.pack ["0","_","0","1_","a","a","#","#a","#","b","b#","#","c"])),
testCaseEq "big chunk with multiple seps"
(map T.pack ["1x","aa","bb","cc1x","dd"])
(sectionsUnderTest (map T.pack (cycle ["12"])) (map T.pack ["1","x12aa12bb12cc1","x1","2dd"]))
]
]
|
danidiaz/foldl-transduce
|
tests/tests.hs
|
Haskell
|
bsd-3-clause
| 7,956
|
{-# LANGUAGE
DataKinds
, EmptyDataDecls
, KindSignatures
, Rank2Types
, RecordWildCards #-}
module Control.Monad.Trans.Ref.Integer
( Region
, Ref
, RefSupply
, runRefSupply
, RefSupplyT
, runRefSupplyT
, newRef
, readRef
, writeRef
, modifyRef
, liftCatch
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Strict (StateT (..), evalStateT)
import qualified Control.Monad.Trans.State.Strict as State
import Data.Functor.Identity
import Data.Hashable
import Data.HashMap.Lazy (HashMap, (!))
import qualified Data.HashMap.Lazy as Map
import GHC.Exts (Any)
import Unsafe.Coerce (unsafeCoerce)
type Map = HashMap
data Region
newtype Ref (s :: Region) a = Ref { unRef :: Integer } deriving (Eq, Show)
instance Hashable (Ref s a) where
hash = hash . unRef
hashWithSalt salt = hashWithSalt salt . unRef
type RefSupply s = RefSupplyT s Identity
runRefSupply :: (forall s . RefSupply s a) -> a
runRefSupply = runIdentity . runRefSupplyT
newtype RefSupplyT (s :: Region) m a
= RefSupplyT { unRefSupplyT :: StateT S m a
}
instance Functor m => Functor (RefSupplyT s m) where
fmap f = RefSupplyT . fmap f . unRefSupplyT
a <$ m = RefSupplyT $ a <$ unRefSupplyT m
instance (Functor m, Monad m) => Applicative (RefSupplyT s m) where
pure = RefSupplyT . pure
f <*> a = RefSupplyT $ unRefSupplyT f <*> unRefSupplyT a
a *> b = RefSupplyT $ unRefSupplyT a *> unRefSupplyT b
a <* b = RefSupplyT $ unRefSupplyT a <* unRefSupplyT b
instance (Functor m, MonadPlus m) => Alternative (RefSupplyT s m) where
empty = mzero
(<|>) = mplus
instance Monad m => Monad (RefSupplyT s m) where
return = RefSupplyT . return
m >>= k = RefSupplyT $ unRefSupplyT m >>= unRefSupplyT . k
m >> n = RefSupplyT $ unRefSupplyT m >> unRefSupplyT n
fail = RefSupplyT . fail
instance MonadPlus m => MonadPlus (RefSupplyT s m) where
mzero = RefSupplyT mzero
m `mplus` n = RefSupplyT $ unRefSupplyT m `mplus` unRefSupplyT n
instance MonadFix m => MonadFix (RefSupplyT s m) where
mfix = RefSupplyT . mfix . (unRefSupplyT .)
instance MonadTrans (RefSupplyT s) where
lift = RefSupplyT . lift
instance MonadIO m => MonadIO (RefSupplyT s m) where
liftIO = lift . liftIO
data S
= S { refCount :: !Integer
, refMap :: Map Integer Any
}
initS :: S
initS = S { refCount = 0, refMap = Map.empty }
get :: Monad m => RefSupplyT s m S
get = RefSupplyT State.get
gets :: Monad m => (S -> a) -> RefSupplyT s m a
gets = RefSupplyT . State.gets
modify :: Monad m => (S -> S) -> RefSupplyT s m ()
modify = RefSupplyT . State.modify
put :: Monad m => S -> RefSupplyT s m ()
put = RefSupplyT . State.put
runRefSupplyT :: Monad m => (forall s . RefSupplyT s m a) -> m a
runRefSupplyT m = evalStateT (unRefSupplyT m) initS
newRef :: Monad m => a -> RefSupplyT s m (Ref s a)
newRef a = do
S {..} <- get
put S { refCount = refCount + 1
, refMap = Map.insert refCount (unsafeCoerce a) refMap
}
return $ Ref refCount
readRef :: Monad m => Ref s a -> RefSupplyT s m a
readRef ref = gets $ unsafeCoerce . (!unRef ref) . refMap
writeRef :: Monad m => Ref s a -> a -> RefSupplyT s m ()
writeRef ref a = modify f
where
f s@S {..} =
s { refMap = Map.insert (unRef ref) (unsafeCoerce a) refMap }
modifyRef :: Monad m => Ref s a -> (a -> a) -> RefSupplyT s m ()
modifyRef ref f =
modify $ \ s@S {..} -> s { refMap = Map.adjust f' (unRef ref) refMap }
where
f' = unsafeCoerce . f . unsafeCoerce
liftCatch :: (forall a' . m a' -> (e -> n a') -> n a') ->
RefSupplyT s m a ->
(e -> RefSupplyT s n a) ->
RefSupplyT s n a
liftCatch catch m h = RefSupplyT $ State.StateT $ \ s ->
State.runStateT (unRefSupplyT m) s `catch` \ e ->
State.runStateT (unRefSupplyT $ h e) s
|
sonyandy/unify
|
src/Control/Monad/Trans/Ref/Integer.hs
|
Haskell
|
bsd-3-clause
| 3,984
|
module Main (main) where
import Control.Monad
import Data.Char
import Data.List
import System.Directory
import System.Environment
import System.Process
-- | Take the arguments passed from the commandline and the filename of the
-- Shakefile, then execute it, passing the arguments.
runShakefile :: [String] -> String -> IO ()
runShakefile args fn = void . system $ unwords ["runghc", fn, unwords args]
-- | Determine if the filename specified is a Shakefile. Any file who's
-- name starts with Shakefile is marked as a Shakefile. Filenames are
-- case-insensitive.
isShakefile :: String -> Bool
isShakefile fn = "shakefile" `isPrefixOf` map toLower fn
-- | Get the commandline arguments, if any, look for a Shakefile, and try
-- to execute it. Error out if no shakefile is found.
main :: IO ()
main = do
args <- getArgs
files <- getDirectoryContents =<< getCurrentDirectory
maybe (error "No shakefile found") (runShakefile args) $ find isShakefile files
|
norm2782/shake-bin
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 1,034
|
n m=unwords[concat[(words ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..")!!((ord x)-65)|x<-l]|l<-words m]
|
eeue56/code-golf
|
morsecode/morse.hs
|
Haskell
|
bsd-3-clause
| 169
|
-- 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.
{-# LANGUAGE GADTs #-}
module Duckling.Rules.AF
( defaultRules
, langRules
, localeRules
) where
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Types
import qualified Duckling.Numeral.AF.Rules as Numeral
defaultRules :: Seal Dimension -> [Rule]
defaultRules = langRules
localeRules :: Region -> Seal Dimension -> [Rule]
localeRules region (Seal (CustomDimension dim)) = dimLocaleRules region dim
localeRules _ _ = []
langRules :: Seal Dimension -> [Rule]
langRules (Seal AmountOfMoney) = []
langRules (Seal CreditCardNumber) = []
langRules (Seal Distance) = []
langRules (Seal Duration) = []
langRules (Seal Email) = []
langRules (Seal Numeral) = Numeral.rules
langRules (Seal Ordinal) = []
langRules (Seal PhoneNumber) = []
langRules (Seal Quantity) = []
langRules (Seal RegexMatch) = []
langRules (Seal Temperature) = []
langRules (Seal Time) = []
langRules (Seal TimeGrain) = []
langRules (Seal Url) = []
langRules (Seal Volume) = []
langRules (Seal (CustomDimension dim)) = dimLangRules AF dim
|
facebookincubator/duckling
|
Duckling/Rules/AF.hs
|
Haskell
|
bsd-3-clause
| 1,244
|
{-# LANGUAGE OverloadedStrings #-}
module HCSV.CSV where
import Prelude hiding (takeWhile)
import qualified Data.ByteString as BS
import Control.Applicative ((<|>), (<*), (*>), many)
import Data.Attoparsec
import Data.Attoparsec.Combinator
import Data.Conduit
import Data.Conduit.Attoparsec
import Data.Word
import HCSV.Options
import HCSV.Types
quote :: Word8
quote = 34
comma :: Word8
comma = 44
-- | Parse a CSV records.
recordParser :: Parser Record
recordParser = (fieldParser `sepBy` (word8 comma)) <* (takeWhile $ inClass "\r\n")
-- | Parse a CSV field (quoted or unquoted).
fieldParser :: Parser Field
fieldParser = try (quotedField <|> unquotedField)
-- | Parse an unquoted field.
unquotedField :: Parser Field
unquotedField = takeWhile (notInClass ",\n\r\"")
-- | Parse a quoted field.
--
-- XXX TODO: Make this suck less. See issue #1
quotedField :: Parser Field
quotedField = (word8 quote) *> (content) <* (word8 quote)
where qs = word8 quote *> word8 quote
content = do
ws <- many (notWord8 quote <|> qs)
return $ BS.pack ws
-- | A conduit Sink to parse CSV records.
recordSink :: (MonadThrow m) => Sink BS.ByteString m Record
recordSink = sinkParser recordParser
-- | Convert a Record for output.
recordText :: HCSVOptions -> Record -> BS.ByteString
recordText opt r = (BS.intercalate "," fields) `BS.append` "\r\n"
where fields = map (escapeField' opt) r
-- | Quote a field if requested or required.
escapeField' :: HCSVOptions -> Field -> Field
escapeField' opt f = let quote = (optQuoteAll opt) || BS.any (inClass ",\n\r\"") f
in if quote then BS.concat ["\"", escapeField f, "\""] else f
-- | Escape quotes within fields.
escapeField :: Field -> Field
escapeField f = BS.intercalate "\"\"" $ BS.split quote f
|
thsutton/hcsv
|
src/HCSV/CSV.hs
|
Haskell
|
bsd-3-clause
| 1,882
|
{-# LANGUAGE PackageImports #-}
module Main (main) where
import Control.Applicative ((<$>))
import Control.Monad (void, forever)
import "monads-tf" Control.Monad.State (StateT(..), runStateT, liftIO)
import Control.Concurrent (forkIO)
import System.Environment (getArgs)
import Network (listenOn, accept)
import "crypto-random" Crypto.Random (CPRG(..), SystemRNG, createEntropyPool)
import TestServer (server)
import CommandLine (readOptions)
main :: IO ()
main = do
(prt, cs, rsa, ec, mcs, _td) <- readOptions =<< getArgs
g0 <- cprgCreate <$> createEntropyPool :: IO SystemRNG
soc <- listenOn prt
void . (`runStateT` g0) . forever $ do
(h, _, _) <- liftIO $ accept soc
g <- StateT $ return . cprgFork
liftIO . forkIO $ server g h cs rsa ec mcs
|
YoshikuniJujo/forest
|
subprojects/tls-analysis/server/runServer.hs
|
Haskell
|
bsd-3-clause
| 758
|
{-# LANGUAGE TupleSections #-}
module RandMonadT where
-- base
import Control.Monad.IO.Class
import Control.Applicative
import Control.Monad
-- transformers
import Control.Monad.Trans.Class
-- primitive
import Control.Monad.Primitive (PrimState)
-- mwc-random
import qualified System.Random.MWC as R
newtype RandMonadT m a = RandMonadT { runRandMonadT :: R.Gen (PrimState m) -> m (a, R.Gen (PrimState m)) }
instance (Monad m) => Functor (RandMonadT m) where
fmap f a = RandMonadT $ \r -> do
(x, r') <- runRandMonadT a r
return (f x, r')
instance (Monad m) => Applicative (RandMonadT m) where
pure = return
(<*>) = ap
instance (Monad m) => Monad (RandMonadT m) where
return x = RandMonadT $ \r -> return (x, r)
x >>= fm = RandMonadT $ \r ->
do (a, r') <- runRandMonadT x r
runRandMonadT (fm a) r'
instance MonadTrans RandMonadT where
lift x = RandMonadT $ \r -> liftM (,r) x
instance (MonadIO m) => MonadIO (RandMonadT m) where
liftIO = lift . liftIO
liftR :: (Monad m) => (R.Gen (PrimState m) -> m a) -> RandMonadT m a
liftR f = RandMonadT $ \r -> f r >>= return.(,r)
|
kgadek/evil-pareto-tests
|
src/RandMonadT.hs
|
Haskell
|
bsd-3-clause
| 1,135
|
{-# LANGUAGE JavaScriptFFI, GeneralizedNewtypeDeriving, FlexibleInstances, UndecidableInstances #-}
module GHCJS.Three.Material (
Material(..), mkMaterial, IsMaterial(..),
MaterialRenderFace, materialFrontSide, materialBackSide, materialDoubleSide,
MeshBasicMaterial(..), mkMeshBasicMaterial, setWireFrame, setWireFrameLineWidth,
MeshNormalMaterial(..), mkMeshNormalMaterial,
MeshLambertMaterial(..), mkMeshLambertMaterial,
MeshPhongMaterial(..), mkMeshPhongMaterial,
TexturedMaterial(..),
LineBasicMaterial(..), mkLineBasicMaterial,
LineDashedMaterial(..), mkLineDashedMaterial,
LineMaterial(..), IsLineMaterial(..),
setDashSize, setGapSize
) where
import GHCJS.Types
import GHCJS.Three.Monad
import GHCJS.Three.Color
import GHCJS.Three.Texture
import GHCJS.Three.Disposable
import GHCJS.Three.Visible
-- | generic Material
newtype Material = Material {
materialObject :: BaseObject
} deriving (ThreeJSVal)
instance HasColor Material
instance Visible Material
instance Disposable Material
foreign import javascript unsafe "new window['THREE']['Material']()"
thr_mkMaterial :: Three JSVal
-- | create a new Material instance
mkMaterial :: Three Material
mkMaterial = fromJSVal <$> thr_mkMaterial
-- private imported functions
foreign import javascript unsafe "($1)['opacity']"
thr_opacity :: JSVal -> Three Double
foreign import javascript unsafe "($2)['opacity'] = $1"
thr_setOpacity :: Double -> JSVal -> Three ()
foreign import javascript unsafe "($1)['transparent']"
thr_transparent :: JSVal -> Three Bool
foreign import javascript unsafe "($2)['transparent'] = $1 === 1"
thr_setTransparent :: Int -> JSVal -> Three ()
type MaterialRenderFace = Int
foreign import javascript unsafe "window['THREE']['FrontSide']"
materialFrontSide :: MaterialRenderFace
foreign import javascript unsafe "window['THREE']['BackSide']"
materialBackSide :: MaterialRenderFace
foreign import javascript unsafe "window['THREE']['DoubleSide']"
materialDoubleSide :: MaterialRenderFace
foreign import javascript unsafe "($1)['side']"
thr_side :: JSVal -> Three MaterialRenderFace
foreign import javascript unsafe "($2)['side'] = $1"
thr_setSide :: MaterialRenderFace -> JSVal -> Three ()
foreign import javascript unsafe "($2)['polygonOffset'] = $1"
thr_setPolygonOffset :: Bool -> JSVal -> Three ()
foreign import javascript unsafe "($2)['polygonOffsetFactor'] = $1"
thr_setPolygonOffsetFactor :: Double -> JSVal -> Three ()
foreign import javascript unsafe "($2)['precision'] = $1"
thr_setPrecision :: JSString -> JSVal -> Three ()
class ThreeJSVal m => IsMaterial m where
toMaterial :: m -> Material
toMaterial = fromJSVal . toJSVal
fromMaterial :: Material -> m
fromMaterial = fromJSVal . toJSVal
-- | get opacity
opacity :: m -> Three Double
opacity = thr_opacity . toJSVal
-- | set opacity
setOpacity :: Double -> m -> Three ()
setOpacity o m = thr_setOpacity o $ toJSVal m
-- | get transparent
transparent :: m -> Three Bool
transparent = thr_transparent . toJSVal
-- | set transparent
setTransparent :: Bool -> m -> Three ()
setTransparent t m = thr_setTransparent (if t then 1 else 0) $ toJSVal m
side :: m -> Three MaterialRenderFace
side = thr_side . toJSVal
setSide :: MaterialRenderFace -> m -> Three ()
setSide s m = thr_setSide s $ toJSVal m
setPolygonOffset :: Bool -> m -> Three ()
setPolygonOffset o m = thr_setPolygonOffset o (toJSVal m)
setPolygonOffsetFactor :: Double -> m -> Three ()
setPolygonOffsetFactor f m = thr_setPolygonOffsetFactor f (toJSVal m)
setPrecision :: JSString -> m -> Three ()
setPrecision p m = thr_setPrecision p (toJSVal m)
instance IsMaterial Material
foreign import javascript unsafe "($2)['wireframe'] = $1 === 1"
thr_setWireFrame :: Int -> JSVal -> Three ()
setWireFrame :: IsMaterial m => Bool -> m -> Three ()
setWireFrame b mesh = thr_setWireFrame (if b then 1 else 0) $ toJSVal mesh
foreign import javascript unsafe "($2)['wireframeLineWidth'] = $1"
thr_setWireFrameLineWidth :: Int -> JSVal -> Three ()
setWireFrameLineWidth :: IsMaterial m => Int -> m -> Three ()
setWireFrameLineWidth w mesh = thr_setWireFrameLineWidth w $ toJSVal mesh
-- | MeshBasicMaterial
newtype MeshBasicMaterial = MeshBasicMaterial {
basicMaterial :: Material
} deriving (ThreeJSVal, IsMaterial, Visible, HasColor, Disposable)
foreign import javascript unsafe "new window['THREE']['MeshBasicMaterial']()"
thr_mkMeshBasicMaterial :: Three JSVal
-- | create a new MeshBasicMaterial
mkMeshBasicMaterial :: Three MeshBasicMaterial
mkMeshBasicMaterial = fromJSVal <$> thr_mkMeshBasicMaterial
-- | MeshNormalMaterial
newtype MeshNormalMaterial = MeshNormalMaterial {
normalMaterial :: Material
} deriving (ThreeJSVal, IsMaterial, HasColor, Visible, Disposable)
foreign import javascript unsafe "new window['THREE']['MeshNormalMaterial']()"
thr_mkMeshNormalMaterial :: Three JSVal
-- | create a new MeshNormalMaterial
mkMeshNormalMaterial :: Three MeshNormalMaterial
mkMeshNormalMaterial = fromJSVal <$> thr_mkMeshNormalMaterial
-- | class for materials that can get and set textures
foreign import javascript unsafe "($2)['map'] = $1"
thr_setTextureMap :: JSVal -> JSVal -> Three ()
foreign import javascript unsafe "($1)['map']"
thr_textureMap :: JSVal -> Three JSVal
class IsMaterial m => TexturedMaterial m where
setTextureMap :: Texture -> m -> Three ()
setTextureMap t m = thr_setTextureMap (toJSVal t) (toJSVal m)
textureMap :: m -> Three Texture
textureMap = fmap fromJSVal . thr_textureMap . toJSVal
-- | MeshLambertMaterial
newtype MeshLambertMaterial = MeshLambertMaterial {
lambertMaterial :: Material
} deriving (ThreeJSVal, IsMaterial, HasColor, Visible, Disposable)
instance TexturedMaterial MeshLambertMaterial
foreign import javascript unsafe "new window['THREE']['MeshLambertMaterial']()"
thr_mkMeshLambertMaterial :: Three JSVal
-- | create a new MeshLambertMaterial
mkMeshLambertMaterial :: Three MeshLambertMaterial
mkMeshLambertMaterial = fromJSVal <$> thr_mkMeshLambertMaterial
-- | MeshPhongMaterial
newtype MeshPhongMaterial = MeshPhongMaterial {
phongMaterial :: Material
} deriving (ThreeJSVal, IsMaterial, HasColor, Visible, Disposable)
instance TexturedMaterial MeshPhongMaterial
foreign import javascript unsafe "new window['THREE']['MeshPhongMaterial']()"
thr_mkMeshPhongMaterial :: Three JSVal
-- | create a new MeshPhongMaterial
mkMeshPhongMaterial :: Three MeshPhongMaterial
mkMeshPhongMaterial = fromJSVal <$> thr_mkMeshPhongMaterial
-- | LineBasicMaterial
newtype LineBasicMaterial = LineBasicMaterial {
lineBasicMaterial :: Material
} deriving (ThreeJSVal, IsMaterial, HasColor, Visible, Disposable)
foreign import javascript unsafe "new window['THREE']['LineBasicMaterial']()"
thr_mkLineBasicMaterial :: Three JSVal
mkLineBasicMaterial :: Three LineBasicMaterial
mkLineBasicMaterial = fromJSVal <$> thr_mkLineBasicMaterial
-- | LineDashedMaterial
newtype LineDashedMaterial = LineDashedMaterial {
lineDashedMaterial :: Material
} deriving (ThreeJSVal, IsMaterial, HasColor, Visible, Disposable)
foreign import javascript unsafe "new window['THREE']['LineDashedMaterial']()"
thr_mkLineDashedMaterial :: Three JSVal
mkLineDashedMaterial :: Three LineDashedMaterial
mkLineDashedMaterial = fromJSVal <$> thr_mkLineDashedMaterial
-- private functions
foreign import javascript unsafe "($1)['linewidth']"
thr_lineWidth :: JSVal -> Three Int
foreign import javascript unsafe "($2)['linewidth'] = $1"
thr_setLineWidth :: Int -> JSVal -> Three ()
foreign import javascript unsafe "($2)['dashSize'] = $1"
thr_setDashSize :: Double -> JSVal -> Three ()
foreign import javascript unsafe "($2)['gapSize'] = $1"
thr_setGapSize :: Double -> JSVal -> Three ()
setDashSize :: Double -> LineDashedMaterial -> Three ()
setDashSize s m = thr_setDashSize s $ toJSVal m
setGapSize :: Double -> LineDashedMaterial -> Three ()
setGapSize s m = thr_setGapSize s $ toJSVal m
newtype LineMaterial = LineMaterial Material deriving (ThreeJSVal, IsMaterial)
class (ThreeJSVal l, IsMaterial l) => IsLineMaterial l where
toLineMaterial :: l -> LineMaterial
toLineMaterial = fromMaterial . toMaterial
fromLineMaterial :: LineMaterial -> l
fromLineMaterial = fromMaterial . toMaterial
lineWidth :: l -> Three Int
lineWidth = thr_lineWidth . toJSVal
setLineWidth :: Int -> l -> Three ()
setLineWidth w l = thr_setLineWidth w $ toJSVal l
instance IsLineMaterial LineMaterial
instance IsLineMaterial LineBasicMaterial
instance IsLineMaterial LineDashedMaterial
|
manyoo/ghcjs-three
|
src/GHCJS/Three/Material.hs
|
Haskell
|
bsd-3-clause
| 8,769
|
-- | Parsing all context-free grammars using Earley's algorithm.
module Text.Earley
( -- * Context-free grammars
Prod, terminal, (<?>), Grammar, rule
, -- * Derived operators
satisfy, token, namedToken, list, listLike
, -- * Deprecated operators
symbol, namedSymbol, word
, -- * Parsing
Report(..), Result(..), parser, allParses, fullParses
-- * Recognition
, report
)
where
import Text.Earley.Grammar
import Text.Earley.Derived
import Text.Earley.Parser
|
sboosali/Earley
|
Text/Earley.hs
|
Haskell
|
bsd-3-clause
| 489
|
-- |
-- Module : Crypto.Hash.MD5
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
-- Module containing the binding functions to work with the
-- MD5 cryptographic hash.
--
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
module Crypto.Hash.MD5 ( MD5 (..) ) where
import Crypto.Hash.Types
import Foreign.Ptr (Ptr)
import Data.Data
import Data.Typeable
import Data.Word (Word8, Word32)
-- | MD5 cryptographic hash algorithm
data MD5 = MD5
deriving (Show,Data,Typeable)
instance HashAlgorithm MD5 where
type HashBlockSize MD5 = 64
type HashDigestSize MD5 = 16
type HashInternalContextSize MD5 = 96
hashBlockSize _ = 64
hashDigestSize _ = 16
hashInternalContextSize _ = 96
hashInternalInit = c_md5_init
hashInternalUpdate = c_md5_update
hashInternalFinalize = c_md5_finalize
foreign import ccall unsafe "cryptonite_md5_init"
c_md5_init :: Ptr (Context a)-> IO ()
foreign import ccall "cryptonite_md5_update"
c_md5_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO ()
foreign import ccall unsafe "cryptonite_md5_finalize"
c_md5_finalize :: Ptr (Context a) -> Ptr (Digest a) -> IO ()
|
tekul/cryptonite
|
Crypto/Hash/MD5.hs
|
Haskell
|
bsd-3-clause
| 1,430
|
module Language.GroteTrap.Range (
-- * Types
Pos, Range, Ranged(..),
-- * Utility functions
distRange, inRange, includes, unionRange, size, validRange
) where
-- | A @Pos@ is a position in between two elements in a list. For example, position @0@ marks the beginning of the list, and position @length list@ marks the end of the list. There are @n + 1@ valid positions for a list of length @n@.
type Pos = Int
-- 1 :: Pos
-- |
-- 0 1 2 3 4 5 6 7 8 9
-- k a a s b r o o d
-- 0 1 2 3 4 5 6 7 8 9
-- \_______/
-- (0,4) :: Range
-- | A range's positions mark the begin and end of a sublist, respectively.
type Range = (Pos, Pos)
-- | Something that knows its range as sublist in a larger list. Minimal complete definition: either 'range' or both 'begin' and 'end'.
class Ranged a where
-- | Yields the element's range.
range :: a -> Range
range x = (begin x, end x)
-- | Yields the element's begin position.
begin :: a -> Pos
begin = fst . range
-- | Yields the element's end position.
end :: a -> Pos
end = snd . range
-- | A range's size is the number of elements it contains.
size :: Range -> Int
size (b,e) = e-b
-- | Whether a position falls within a range, including the range's edges.
inRange :: Pos -> Range -> Bool
inRange pos (begin, end) = pos >= begin && pos <= end
-- | @unionRange x y@ yields the smallest range z such that @x ``includes`` z@ and @y ``includes`` z@.
unionRange :: Range -> Range -> Range
unionRange = min **** max
-- | Yields whether the second argument completely falls within the first argument.
includes :: Range -> Range -> Bool
includes r (b,e) = b `inRange` r && e `inRange` r
-- | @distRange (b1, e1) (b2, e2)@ is defined as @|b1 - b2| + |e1 - e2|@.
distRange :: Range -> Range -> Int
distRange (b1,e1) (b2,e2) = db + de
where db = abs (b1 - b2)
de = abs (e1 - e2)
(****) :: (a -> b -> c) -> (d -> e -> f) -> (a,d) -> (b,e) -> (c,f)
(****) fl fr (a,d) (b,e) = (fl a b, fr d e)
-- | A range is valid if its positions are nonnegative and begin < end.
validRange :: Range -> Bool
validRange (b, e) = b >= 0 && e >= 0 && b <= e
|
MedeaMelana/GroteTrap
|
Language/GroteTrap/Range.hs
|
Haskell
|
bsd-3-clause
| 2,122
|
{-# LANGUAGE CPP, MagicHash, UnboxedTuples, ForeignFunctionInterface, GHCForeignImportPrim, UnliftedFFITypes #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
module Control.ChunkedTL2.STM
(
readTVar,
writeTVar,
atomically,
STM(..),
printStats,
newTVar,
module Control.Common.STM
)
where
import GHC.Base(State#, RealWorld, IO(..), ap)
import GHC.Prim(Any, unsafeCoerce# )
import GHC.Conc.Sync(TVar(..))
import Control.Common.STM
newtype STM a = STM {unSTM :: State# RealWorld -> (# State# RealWorld, a #)}
instance Monad STM where
return a = STM $ \s -> (# s, a #)
m >>= k = STM $ \s -> let (# s', t #) = unSTM m s in unSTM (k t) s'
instance Applicative STM where
(<*>) = ap
pure = return
instance Functor STM where
fmap f m = m >>= (return . f)
newTVar :: a -> STM (TVar a)
newTVar x = STM $ \s -> case unsafeCoerce# newTVar# x s of
(# s', tv #) -> (# s', TVar tv #)
readTVar :: TVar a -> STM a
readTVar (TVar tv) = STM $ \s-> unsafeCoerce# readTVar# tv s
writeTVar :: TVar a -> a -> STM ()
writeTVar (TVar tv) a = STM $ \s ->
case unsafeCoerce# writeTVar# tv a s of
(# s', tv #) -> (# s', () #)
atomically :: STM a -> IO a
atomically (STM c) = IO (\s -> unsafeCoerce# atomically# c s)
foreign import prim safe "stg_tl2_atomicallyzh" atomically#
:: Any() -> State# s -> (# State# s, Any() #)
foreign import prim safe "stg_tl2_readTVarzh" readTVar#
:: Any() -> State# s -> (# State# s, a #)
foreign import prim safe "stg_tl2_writeTVarzh" writeTVar#
:: Any() -> Any() -> State# RealWorld -> (# State# RealWorld, a #)
foreign import ccall "c_tl2_printSTMStats" printStats :: IO ()
|
ml9951/ghc
|
libraries/pastm/Control/ChunkedTL2/STM.hs
|
Haskell
|
bsd-3-clause
| 1,748
|
module Web.Client.Capacity.Internal
(
) where
|
athanclark/client-capacity
|
src/Web/Client/Capacity/Internal.hs
|
Haskell
|
bsd-3-clause
| 54
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Lens hiding (children)
import Graphics.Svg
import Linear.V2
import VirtualHom.Element
import VirtualHom.Html hiding (content, main)
import VirtualHom.Rendering(renderingOptions)
import VirtualHom.Bootstrap(container, row, btnDefault)
import VirtualHom.View(View, renderUI)
aCircle :: Monad m => View m Int
aCircle i = [svg
& attributes . at "viewBox" ?~ "0 0 500 200"
& children .~ [
circle
& attributes . at "cx" ?~ "60"
& attributes . at "cy" ?~ "60"
& attributes . at "r" ?~ "50",
polygon [V2 10 10, V2 20 20, V2 30 20]
]]
main :: IO ()
main = do
let options = renderingOptions "iso-svg"
let interp = return . runIdentity
renderUI options aCircle interp 1
|
j-mueller/iso-svg
|
examples/simple/Main.hs
|
Haskell
|
bsd-3-clause
| 774
|
module Pos.Infra.Communication.Relay.Util
( expectInv
, expectData
) where
import Universum
import Pos.Infra.Communication.Relay.Types
(RelayError (UnexpectedData, UnexpectedInv))
import Pos.Infra.Communication.Types.Relay (DataMsg, InvMsg,
InvOrData)
expectInv
:: MonadThrow m
=> (InvMsg key -> m a) -> InvOrData key contents -> m a
expectInv call = either call (\_ -> throwM UnexpectedData)
expectData
:: MonadThrow m
=> (DataMsg contents -> m a) -> InvOrData key contents -> m a
expectData call = either (\_ -> throwM UnexpectedInv) call
|
input-output-hk/pos-haskell-prototype
|
infra/src/Pos/Infra/Communication/Relay/Util.hs
|
Haskell
|
mit
| 654
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
module Language.LSP.Test.Files
( swapFiles
, rootDir
)
where
import Language.LSP.Types
import Language.LSP.Types.Lens hiding (id)
import Control.Lens
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import Data.Maybe
import System.Directory
import System.FilePath
import Data.Time.Clock
data Event
= ClientEv UTCTime FromClientMessage
| ServerEv UTCTime FromServerMessage
swapFiles :: FilePath -> [Event] -> IO [Event]
swapFiles relCurBaseDir msgs = do
let capturedBaseDir = rootDir msgs
curBaseDir <- (</> relCurBaseDir) <$> getCurrentDirectory
let transform uri =
let fp = fromMaybe (error "Couldn't transform uri") (uriToFilePath uri)
newFp = curBaseDir </> makeRelative capturedBaseDir fp
in filePathToUri newFp
newMsgs = map (mapUris transform) msgs
return newMsgs
rootDir :: [Event] -> FilePath
rootDir (ClientEv _ (FromClientMess SInitialize req):_) =
fromMaybe (error "Couldn't find root dir") $ do
rootUri <- req ^. params .rootUri
uriToFilePath rootUri
rootDir _ = error "Couldn't find initialize request in session"
mapUris :: (Uri -> Uri) -> Event -> Event
mapUris f event =
case event of
ClientEv t msg -> ClientEv t (fromClientMsg msg)
ServerEv t msg -> ServerEv t (fromServerMsg msg)
where
--TODO: Handle all other URIs that might need swapped
fromClientMsg (FromClientMess m@SInitialize r) = FromClientMess m $ params .~ transformInit (r ^. params) $ r
fromClientMsg (FromClientMess m@STextDocumentDidOpen n) = FromClientMess m $ swapUri (params . textDocument) n
fromClientMsg (FromClientMess m@STextDocumentDidChange n) = FromClientMess m $ swapUri (params . textDocument) n
fromClientMsg (FromClientMess m@STextDocumentWillSave n) = FromClientMess m $ swapUri (params . textDocument) n
fromClientMsg (FromClientMess m@STextDocumentDidSave n) = FromClientMess m $ swapUri (params . textDocument) n
fromClientMsg (FromClientMess m@STextDocumentDidClose n) = FromClientMess m $ swapUri (params . textDocument) n
fromClientMsg (FromClientMess m@STextDocumentDocumentSymbol n) = FromClientMess m $ swapUri (params . textDocument) n
fromClientMsg (FromClientMess m@STextDocumentRename n) = FromClientMess m $ swapUri (params . textDocument) n
fromClientMsg x = x
fromServerMsg :: FromServerMessage -> FromServerMessage
fromServerMsg (FromServerMess m@SWorkspaceApplyEdit r) = FromServerMess m $ params . edit .~ swapWorkspaceEdit (r ^. params . edit) $ r
fromServerMsg (FromServerMess m@STextDocumentPublishDiagnostics n) = FromServerMess m $ swapUri params n
fromServerMsg (FromServerRsp m@STextDocumentDocumentSymbol r) =
let swapUri' :: (List DocumentSymbol |? List SymbolInformation) -> List DocumentSymbol |? List SymbolInformation
swapUri' (InR si) = InR (swapUri location <$> si)
swapUri' (InL dss) = InL dss -- no file locations here
in FromServerRsp m $ r & result %~ (fmap swapUri')
fromServerMsg (FromServerRsp m@STextDocumentRename r) = FromServerRsp m $ r & result %~ (fmap swapWorkspaceEdit)
fromServerMsg x = x
swapWorkspaceEdit :: WorkspaceEdit -> WorkspaceEdit
swapWorkspaceEdit e =
let swapDocumentChangeUri :: DocumentChange -> DocumentChange
swapDocumentChangeUri (InL textDocEdit) = InL $ swapUri textDocument textDocEdit
swapDocumentChangeUri (InR (InL createFile)) = InR $ InL $ swapUri id createFile
-- for RenameFile, we swap `newUri`
swapDocumentChangeUri (InR (InR (InL renameFile))) = InR $ InR $ InL $ newUri .~ f (renameFile ^. newUri) $ renameFile
swapDocumentChangeUri (InR (InR (InR deleteFile))) = InR $ InR $ InR $ swapUri id deleteFile
newDocChanges = fmap (fmap swapDocumentChangeUri) $ e ^. documentChanges
newChanges = fmap (swapKeys f) $ e ^. changes
in WorkspaceEdit newChanges newDocChanges Nothing
swapKeys :: (Uri -> Uri) -> HM.HashMap Uri b -> HM.HashMap Uri b
swapKeys f = HM.foldlWithKey' (\acc k v -> HM.insert (f k) v acc) HM.empty
swapUri :: HasUri b Uri => Lens' a b -> a -> a
swapUri lens x =
let newUri = f (x ^. lens . uri)
in (lens . uri) .~ newUri $ x
-- | Transforms rootUri/rootPath.
transformInit :: InitializeParams -> InitializeParams
transformInit x =
let newRootUri = fmap f (x ^. rootUri)
newRootPath = do
fp <- T.unpack <$> x ^. rootPath
let uri = filePathToUri fp
T.pack <$> uriToFilePath (f uri)
in (rootUri .~ newRootUri) $ (rootPath .~ newRootPath) x
|
alanz/haskell-lsp
|
lsp-test/src/Language/LSP/Test/Files.hs
|
Haskell
|
mit
| 4,962
|
{-# Language RebindableSyntax #-}
{-# Language TypeOperators #-}
{-# Language FlexibleContexts #-}
{-# Language ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module PingMulti02 where
import Prelude hiding ((>>=), (>>), fail, return)
import Symmetry.Language
import Symmetry.Verify
pingServer :: (DSL repr) => repr (Process repr ())
pingServer = do myPid <- self
p <- recv
send p myPid
master :: (DSL repr) => repr (RMulti -> Int -> Process repr ())
master = lam $ \r -> lam $ \n ->
do ps <- spawnMany r n pingServer
myPid <- self
doMany "l0" ps (lam $ \p -> do
send p myPid
(_ :: repr (Pid RSing)) <- recv
return tt)
return tt
mainProc :: (DSL repr) => repr (Int -> ())
mainProc = lam $ \n -> exec $ do r <- newRMulti
app (app master r) n
main :: IO ()
main = checkerMain (arb |> mainProc)
|
abakst/symmetry
|
checker/tests/pos/PingMulti02.hs
|
Haskell
|
mit
| 1,069
|
module Idris.REPL.Commands where
import Idris.AbsSyntaxTree
import Idris.Colours
import Idris.Core.TT
-- | REPL commands
data Command = Quit
| Help
| Eval PTerm
| NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
| Undefine [Name]
| Check PTerm
| Core PTerm
| DocStr (Either Name Const) HowMuchDocs
| TotCheck Name
| Reload
| Watch
| Load FilePath (Maybe Int) -- up to maximum line number
| RunShellCommand FilePath
| ChangeDirectory FilePath
| ModImport String
| Edit
| Compile Codegen String
| Execute PTerm
| ExecVal PTerm
| Metavars
| Prove Bool Name -- ^ If false, use prover, if true, use elab shell
| AddProof (Maybe Name)
| RmProof Name
| ShowProof Name
| Proofs
| Universes
| LogLvl Int
| LogCategory [LogCat]
| Verbosity Int
| Spec PTerm
| WHNF PTerm
| TestInline PTerm
| Defn Name
| Missing Name
| DynamicLink FilePath
| ListDynamic
| Pattelab PTerm
| Search [String] PTerm
| CaseSplitAt Bool Int Name
| AddClauseFrom Bool Int Name
| AddProofClauseFrom Bool Int Name
| AddMissing Bool Int Name
| MakeWith Bool Int Name
| MakeCase Bool Int Name
| MakeLemma Bool Int Name
| DoProofSearch Bool -- update file
Bool -- recursive search
Int -- depth
Name -- top level name
[Name] -- hints
| SetOpt Opt
| UnsetOpt Opt
| NOP
| SetColour ColourType IdrisColour
| ColourOn
| ColourOff
| ListErrorHandlers
| SetConsoleWidth ConsoleWidth
| SetPrinterDepth (Maybe Int)
| Apropos [String] String
| WhoCalls Name
| CallsWho Name
| Browse [String]
| MakeDoc String -- IdrisDoc
| Warranty
| PrintDef Name
| PPrint OutputFmt Int PTerm
| TransformInfo Name
-- Debugging commands
| DebugInfo Name
| DebugUnify PTerm PTerm
|
jmitchell/Idris-dev
|
src/Idris/REPL/Commands.hs
|
Haskell
|
bsd-3-clause
| 2,668
|
module Control.Concurrent.MVar.YC (
modifyMVarPure, writeMVar
) where
import Control.Applicative ()
import Control.Concurrent.MVar (MVar, modifyMVar_)
modifyMVarPure :: MVar a -> (a -> a) -> IO ()
modifyMVarPure mvar = modifyMVar_ mvar . fmap return
writeMVar :: MVar a -> a -> IO ()
writeMVar mvar = modifyMVarPure mvar . const
|
yairchu/peakachu
|
src/Control/Concurrent/MVar/YC.hs
|
Haskell
|
bsd-3-clause
| 341
|
-- -----------------------------------------------------------------------------
-- ALEX TEMPLATE
--
-- This code is in the PUBLIC DOMAIN; you may copy it freely and use
-- it for any purpose whatsoever.
-- -----------------------------------------------------------------------------
-- INTERNALS and main scanner engine
#ifdef ALEX_GHC
#undef __GLASGOW_HASKELL__
#define ALEX_IF_GHC_GT_500 #if __GLASGOW_HASKELL__ > 500
#define ALEX_IF_GHC_LT_503 #if __GLASGOW_HASKELL__ < 503
#define ALEX_IF_GHC_GT_706 #if __GLASGOW_HASKELL__ > 706
#define ALEX_ELIF_GHC_500 #elif __GLASGOW_HASKELL__ == 500
#define ALEX_IF_BIGENDIAN #ifdef WORDS_BIGENDIAN
#define ALEX_ELSE #else
#define ALEX_ENDIF #endif
#define ALEX_DEFINE #define
#endif
#ifdef ALEX_GHC
#define ILIT(n) n#
#define IBOX(n) (I# (n))
#define FAST_INT Int#
-- Do not remove this comment. Required to fix CPP parsing when using GCC and a clang-compiled alex.
ALEX_IF_GHC_GT_706
ALEX_DEFINE GTE(n,m) (tagToEnum# (n >=# m))
ALEX_DEFINE EQ(n,m) (tagToEnum# (n ==# m))
ALEX_ELSE
ALEX_DEFINE GTE(n,m) (n >=# m)
ALEX_DEFINE EQ(n,m) (n ==# m)
ALEX_ENDIF
#define PLUS(n,m) (n +# m)
#define MINUS(n,m) (n -# m)
#define TIMES(n,m) (n *# m)
#define NEGATE(n) (negateInt# (n))
#define IF_GHC(x) (x)
#else
#define ILIT(n) (n)
#define IBOX(n) (n)
#define FAST_INT Int
#define GTE(n,m) (n >= m)
#define EQ(n,m) (n == m)
#define PLUS(n,m) (n + m)
#define MINUS(n,m) (n - m)
#define TIMES(n,m) (n * m)
#define NEGATE(n) (negate (n))
#define IF_GHC(x)
#endif
#ifdef ALEX_GHC
data AlexAddr = AlexA# Addr#
-- Do not remove this comment. Required to fix CPP parsing when using GCC and a clang-compiled alex.
ALEX_IF_GHC_LT_503
uncheckedShiftL# = shiftL#
ALEX_ENDIF
{-# INLINE alexIndexInt16OffAddr #-}
alexIndexInt16OffAddr (AlexA# arr) off =
ALEX_IF_BIGENDIAN
narrow16Int# i
where
i = word2Int# ((high `uncheckedShiftL#` 8#) `or#` low)
high = int2Word# (ord# (indexCharOffAddr# arr (off' +# 1#)))
low = int2Word# (ord# (indexCharOffAddr# arr off'))
off' = off *# 2#
ALEX_ELSE
indexInt16OffAddr# arr off
ALEX_ENDIF
#else
alexIndexInt16OffAddr arr off = arr ! off
#endif
#ifdef ALEX_GHC
{-# INLINE alexIndexInt32OffAddr #-}
alexIndexInt32OffAddr (AlexA# arr) off =
ALEX_IF_BIGENDIAN
narrow32Int# i
where
i = word2Int# ((b3 `uncheckedShiftL#` 24#) `or#`
(b2 `uncheckedShiftL#` 16#) `or#`
(b1 `uncheckedShiftL#` 8#) `or#` b0)
b3 = int2Word# (ord# (indexCharOffAddr# arr (off' +# 3#)))
b2 = int2Word# (ord# (indexCharOffAddr# arr (off' +# 2#)))
b1 = int2Word# (ord# (indexCharOffAddr# arr (off' +# 1#)))
b0 = int2Word# (ord# (indexCharOffAddr# arr off'))
off' = off *# 4#
ALEX_ELSE
indexInt32OffAddr# arr off
ALEX_ENDIF
#else
alexIndexInt32OffAddr arr off = arr ! off
#endif
#ifdef ALEX_GHC
ALEX_IF_GHC_LT_503
quickIndex arr i = arr ! i
ALEX_ELSE
-- GHC >= 503, unsafeAt is available from Data.Array.Base.
quickIndex = unsafeAt
ALEX_ENDIF
#else
quickIndex arr i = arr ! i
#endif
-- -----------------------------------------------------------------------------
-- Main lexing routines
data AlexReturn a
= AlexEOF
| AlexError !AlexInput
| AlexSkip !AlexInput !Int
| AlexToken !AlexInput !Int a
-- alexScan :: AlexInput -> StartCode -> AlexReturn a
alexScan input IBOX(sc)
= alexScanUser undefined input IBOX(sc)
alexScanUser user input IBOX(sc)
= case alex_scan_tkn user input ILIT(0) input sc AlexNone of
(AlexNone, input') ->
case alexGetByte input of
Nothing ->
#ifdef ALEX_DEBUG
trace ("End of input.") $
#endif
AlexEOF
Just _ ->
#ifdef ALEX_DEBUG
trace ("Error.") $
#endif
AlexError input'
(AlexLastSkip input'' len, _) ->
#ifdef ALEX_DEBUG
trace ("Skipping.") $
#endif
AlexSkip input'' len
(AlexLastAcc k input''' len, _) ->
#ifdef ALEX_DEBUG
trace ("Accept.") $
#endif
AlexToken input''' len k
-- Push the input through the DFA, remembering the most recent accepting
-- state it encountered.
alex_scan_tkn user orig_input len input s last_acc =
input `seq` -- strict in the input
let
new_acc = (check_accs (alex_accept `quickIndex` IBOX(s)))
in
new_acc `seq`
case alexGetByte input of
Nothing -> (new_acc, input)
Just (c, new_input) ->
#ifdef ALEX_DEBUG
trace ("State: " ++ show IBOX(s) ++ ", char: " ++ show c) $
#endif
case fromIntegral c of { IBOX(ord_c) ->
let
base = alexIndexInt32OffAddr alex_base s
offset = PLUS(base,ord_c)
check = alexIndexInt16OffAddr alex_check offset
new_s = if GTE(offset,ILIT(0)) && EQ(check,ord_c)
then alexIndexInt16OffAddr alex_table offset
else alexIndexInt16OffAddr alex_deflt s
in
case new_s of
ILIT(-1) -> (new_acc, input)
-- on an error, we want to keep the input *before* the
-- character that failed, not after.
_ -> alex_scan_tkn user orig_input (if c < 0x80 || c >= 0xC0 then PLUS(len,ILIT(1)) else len)
-- note that the length is increased ONLY if this is the 1st byte in a char encoding)
new_input new_s new_acc
}
where
check_accs (AlexAccNone) = last_acc
check_accs (AlexAcc a ) = AlexLastAcc a input IBOX(len)
check_accs (AlexAccSkip) = AlexLastSkip input IBOX(len)
#ifndef ALEX_NOPRED
check_accs (AlexAccPred a predx rest)
| predx user orig_input IBOX(len) input
= AlexLastAcc a input IBOX(len)
| otherwise
= check_accs rest
check_accs (AlexAccSkipPred predx rest)
| predx user orig_input IBOX(len) input
= AlexLastSkip input IBOX(len)
| otherwise
= check_accs rest
#endif
data AlexLastAcc a
= AlexNone
| AlexLastAcc a !AlexInput !Int
| AlexLastSkip !AlexInput !Int
instance Functor AlexLastAcc where
fmap f AlexNone = AlexNone
fmap f (AlexLastAcc x y z) = AlexLastAcc (f x) y z
fmap f (AlexLastSkip x y) = AlexLastSkip x y
data AlexAcc a user
= AlexAccNone
| AlexAcc a
| AlexAccSkip
#ifndef ALEX_NOPRED
| AlexAccPred a (AlexAccPred user) (AlexAcc a user)
| AlexAccSkipPred (AlexAccPred user) (AlexAcc a user)
type AlexAccPred user = user -> AlexInput -> Int -> AlexInput -> Bool
-- -----------------------------------------------------------------------------
-- Predicates on a rule
alexAndPred p1 p2 user in1 len in2
= p1 user in1 len in2 && p2 user in1 len in2
--alexPrevCharIsPred :: Char -> AlexAccPred _
alexPrevCharIs c _ input _ _ = c == alexInputPrevChar input
alexPrevCharMatches f _ input _ _ = f (alexInputPrevChar input)
--alexPrevCharIsOneOfPred :: Array Char Bool -> AlexAccPred _
alexPrevCharIsOneOf arr _ input _ _ = arr ! alexInputPrevChar input
--alexRightContext :: Int -> AlexAccPred _
alexRightContext IBOX(sc) user _ _ input =
case alex_scan_tkn user input ILIT(0) input sc AlexNone of
(AlexNone, _) -> False
_ -> True
-- TODO: there's no need to find the longest
-- match when checking the right context, just
-- the first match will do.
#endif
-- used by wrappers
iUnbox IBOX(i) = i
|
hvr/alex
|
templates/GenericTemplate.hs
|
Haskell
|
bsd-3-clause
| 7,074
|
{-# OPTIONS -fno-warn-orphans #-}
module Network.BitTorrent.Internal.ProgressSpec (spec) where
import Control.Applicative
import Test.Hspec
import Test.QuickCheck
import Network.BitTorrent.Internal.Progress
instance Arbitrary Progress where
arbitrary = Progress <$> arbitrary <*> arbitrary <*> arbitrary
spec :: Spec
spec = return ()
|
DavidAlphaFox/bittorrent
|
tests/Network/BitTorrent/Internal/ProgressSpec.hs
|
Haskell
|
bsd-3-clause
| 339
|
module Tuura.Library (Library, libraryFile, loadLibrary) where
newtype Library = Library FilePath
libraryFile :: Library -> FilePath
libraryFile (Library file) = file
loadLibrary :: FilePath -> Library
loadLibrary = Library
|
allegroCoder/scenco-1
|
src/Tuura/Library.hs
|
Haskell
|
bsd-3-clause
| 227
|
-----------------------------------------------------------------------------
-- |
-- Module : Window
-- Copyright : (c) 2011-13 Jose A. Ortega Ruiz
-- : (c) 2012 Jochen Keil
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org>
-- Stability : unstable
-- Portability : unportable
--
-- Window manipulation functions
--
-----------------------------------------------------------------------------
module Window where
import Prelude
import Control.Monad (when, unless)
import Graphics.X11.Xlib hiding (textExtents, textWidth)
import Graphics.X11.Xlib.Extras
import Graphics.X11.Xinerama
import Foreign.C.Types (CLong)
import Data.Maybe(fromMaybe)
import System.Posix.Process (getProcessID)
import Config
import XUtil
-- $window
-- | The function to create the initial window
createWin :: Display -> XFont -> Config -> IO (Rectangle,Window)
createWin d fs c = do
let dflt = defaultScreen d
srs <- getScreenInfo d
rootw <- rootWindow d dflt
(as,ds) <- textExtents fs "0"
let ht = as + ds + 4
r = setPosition (position c) srs (fi ht)
win <- newWindow d (defaultScreenOfDisplay d) rootw r (overrideRedirect c)
setProperties c d win
setStruts r c d win srs
when (lowerOnStart c) $ lowerWindow d win
unless (hideOnStart c) $ showWindow r c d win
return (r,win)
-- | Updates the size and position of the window
repositionWin :: Display -> Window -> XFont -> Config -> IO Rectangle
repositionWin d win fs c = do
srs <- getScreenInfo d
(as,ds) <- textExtents fs "0"
let ht = as + ds + 4
r = setPosition (position c) srs (fi ht)
moveResizeWindow d win (rect_x r) (rect_y r) (rect_width r) (rect_height r)
setStruts r c d win srs
return r
setPosition :: XPosition -> [Rectangle] -> Dimension -> Rectangle
setPosition p rs ht =
case p' of
Top -> Rectangle rx ry rw h
TopP l r -> Rectangle (rx + fi l) ry (rw - fi l - fi r) h
TopW a i -> Rectangle (ax a i) ry (nw i) h
TopSize a i ch -> Rectangle (ax a i) ry (nw i) (mh ch)
Bottom -> Rectangle rx ny rw h
BottomW a i -> Rectangle (ax a i) ny (nw i) h
BottomP l r -> Rectangle (rx + fi l) ny (rw - fi l - fi r) h
BottomSize a i ch -> Rectangle (ax a i) (ny' ch) (nw i) (mh ch)
Static cx cy cw ch -> Rectangle (fi cx) (fi cy) (fi cw) (fi ch)
OnScreen _ p'' -> setPosition p'' [scr] ht
where
(scr@(Rectangle rx ry rw rh), p') =
case p of OnScreen i x -> (fromMaybe (head rs) $ safeIndex i rs, x)
_ -> (head rs, p)
ny = ry + fi (rh - ht)
center i = rx + fi (div (remwid i) 2)
right i = rx + fi (remwid i)
remwid i = rw - pw (fi i)
ax L = const rx
ax R = right
ax C = center
pw i = rw * min 100 i `div` 100
nw = fi . pw . fi
h = fi ht
mh h' = max (fi h') h
ny' h' = ry + fi (rh - mh h')
safeIndex i = lookup i . zip [0..]
setProperties :: Config -> Display -> Window -> IO ()
setProperties c d w = do
let mkatom n = internAtom d n False
card <- mkatom "CARDINAL"
atom <- mkatom "ATOM"
setTextProperty d w "xmobar" wM_CLASS
setTextProperty d w "xmobar" wM_NAME
wtype <- mkatom "_NET_WM_WINDOW_TYPE"
dock <- mkatom "_NET_WM_WINDOW_TYPE_DOCK"
changeProperty32 d w wtype atom propModeReplace [fi dock]
when (allDesktops c) $ do
desktop <- mkatom "_NET_WM_DESKTOP"
changeProperty32 d w desktop card propModeReplace [0xffffffff]
pid <- mkatom "_NET_WM_PID"
getProcessID >>= changeProperty32 d w pid card propModeReplace . return . fi
setStruts' :: Display -> Window -> [Foreign.C.Types.CLong] -> IO ()
setStruts' d w svs = do
let mkatom n = internAtom d n False
card <- mkatom "CARDINAL"
pstrut <- mkatom "_NET_WM_STRUT_PARTIAL"
strut <- mkatom "_NET_WM_STRUT"
changeProperty32 d w pstrut card propModeReplace svs
changeProperty32 d w strut card propModeReplace (take 4 svs)
setStruts :: Rectangle -> Config -> Display -> Window -> [Rectangle] -> IO ()
setStruts r c d w rs = do
let svs = map fi $ getStrutValues r (position c) (getRootWindowHeight rs)
setStruts' d w svs
getRootWindowHeight :: [Rectangle] -> Int
getRootWindowHeight srs = maximum (map getMaxScreenYCoord srs)
where
getMaxScreenYCoord sr = fi (rect_y sr) + fi (rect_height sr)
getStrutValues :: Rectangle -> XPosition -> Int -> [Int]
getStrutValues r@(Rectangle x y w h) p rwh =
case p of
OnScreen _ p' -> getStrutValues r p' rwh
Top -> [0, 0, st, 0, 0, 0, 0, 0, nx, nw, 0, 0]
TopP _ _ -> [0, 0, st, 0, 0, 0, 0, 0, nx, nw, 0, 0]
TopW _ _ -> [0, 0, st, 0, 0, 0, 0, 0, nx, nw, 0, 0]
TopSize {} -> [0, 0, st, 0, 0, 0, 0, 0, nx, nw, 0, 0]
Bottom -> [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, nx, nw]
BottomP _ _ -> [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, nx, nw]
BottomW _ _ -> [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, nx, nw]
BottomSize {} -> [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, nx, nw]
Static {} -> getStaticStrutValues p rwh
where st = fi y + fi h
sb = rwh - fi y
nx = fi x
nw = fi (x + fi w - 1)
-- get some reaonable strut values for static placement.
getStaticStrutValues :: XPosition -> Int -> [Int]
getStaticStrutValues (Static cx cy cw ch) rwh
-- if the yPos is in the top half of the screen, then assume a Top
-- placement, otherwise, it's a Bottom placement
| cy < (rwh `div` 2) = [0, 0, st, 0, 0, 0, 0, 0, xs, xe, 0, 0]
| otherwise = [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, xs, xe]
where st = cy + ch
sb = rwh - cy
xs = cx -- a simple calculation for horizontal (x) placement
xe = xs + cw
getStaticStrutValues _ _ = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
drawBorder :: Border -> Display -> Drawable -> GC -> Pixel
-> Dimension -> Dimension -> IO ()
drawBorder b d p gc c wi ht = case b of
NoBorder -> return ()
TopB -> drawBorder (TopBM 0) d p gc c w h
BottomB -> drawBorder (BottomBM 0) d p gc c w h
FullB -> drawBorder (FullBM 0) d p gc c w h
TopBM m -> sf >> drawLine d p gc 0 (fi m) (fi w) 0
BottomBM m -> let rw = fi h - fi m in
sf >> drawLine d p gc 0 rw (fi w) rw
FullBM m -> let pad = 2 * fi m; mp = fi m in
sf >> drawRectangle d p gc mp mp (w - pad) (h - pad)
where sf = setForeground d gc c
(w, h) = (wi - 1, ht - 1)
hideWindow :: Display -> Window -> IO ()
hideWindow d w = do
setStruts' d w (replicate 12 0)
unmapWindow d w >> sync d False
showWindow :: Rectangle -> Config -> Display -> Window -> IO ()
showWindow r c d w = do
mapWindow d w
getScreenInfo d >>= setStruts r c d w
sync d False
isMapped :: Display -> Window -> IO Bool
isMapped d w = fmap ism $ getWindowAttributes d w
where ism (WindowAttributes { wa_map_state = wms }) = wms /= waIsUnmapped
|
tsiliakis/xmobar
|
src/Window.hs
|
Haskell
|
bsd-3-clause
| 6,866
|
module Data.JSTarget.Op where
import Prelude hiding (GT, LT)
data BinOp
= Add
| Mul
| Sub
| Div
| Mod
| And
| Or
| Eq
| StrictEq
| Neq
| StrictNeq
| LT
| GT
| LTE
| GTE
| Shl
| ShrL
| ShrA
| BitAnd
| BitOr
| BitXor
deriving (Eq)
instance Show BinOp where
show Add = "+"
show Mul = "*"
show Sub = "-"
show Div = "/"
show Mod = "%"
show And = "&&"
show Or = "||"
show Eq = "=="
show StrictEq = "==="
show Neq = "!="
show StrictNeq = "!=="
show LT = "<"
show GT = ">"
show LTE = "<="
show GTE = ">="
show Shl = "<<"
show ShrL = ">>>"
show ShrA = ">>"
show BitAnd = "&"
show BitOr = "|"
show BitXor = "^"
-- | Returns the precedence of the given operator as an int. Higher number
-- means higher priority.
opPrec :: BinOp -> Int
opPrec Mul = 100
opPrec Div = 100
opPrec Mod = 100
opPrec Add = 70
opPrec Sub = 70
opPrec Shl = 60
opPrec ShrA = 60
opPrec ShrL = 60
opPrec LT = 50
opPrec GT = 50
opPrec LTE = 50
opPrec GTE = 50
opPrec Eq = 30
opPrec StrictEq = 30
opPrec Neq = 30
opPrec StrictNeq = 30
opPrec BitAnd = 25
opPrec BitXor = 24
opPrec BitOr = 23
opPrec And = 20
opPrec Or = 10
-- | Is the given operator associative?
opIsAssoc :: BinOp -> Bool
opIsAssoc Mul = True
opIsAssoc Add = True
opIsAssoc BitAnd = True
opIsAssoc BitOr = True
opIsAssoc BitXor = True
opIsAssoc And = True
opIsAssoc Or = True
opIsAssoc _ = False
|
beni55/haste-compiler
|
src/Data/JSTarget/Op.hs
|
Haskell
|
bsd-3-clause
| 1,653
|
{-# LANGUAGE ScopedTypeVariables
, MultiParamTypeClasses
, FlexibleInstances
, FunctionalDependencies
, FlexibleContexts
, UndecidableInstances
, KindSignatures
, GADTs
, OverlappingInstances
, EmptyDataDecls
, DeriveDataTypeable #-}
module Control.Distributed.Process.Internal.Closure.Explicit
(
RemoteRegister
, MkTDict(..)
, mkStaticVal
, mkClosureValSingle
, mkClosureVal
, call'
) where
import Control.Distributed.Static
import Control.Distributed.Process.Serializable
import Control.Distributed.Process.Internal.Closure.BuiltIn
( -- Static dictionaries and associated operations
staticDecode
)
import Control.Distributed.Process
import Data.Rank1Dynamic
import Data.Rank1Typeable
import Data.Binary(encode,put,get,Binary)
import qualified Data.ByteString.Lazy as B
-- | A RemoteRegister is a trasformer on a RemoteTable to register additional static values.
type RemoteRegister = RemoteTable -> RemoteTable
-- | This takes an explicit name and a value, and produces both a static reference to the name and a RemoteRegister for it.
mkStaticVal :: Serializable a => String -> a -> (Static a, RemoteRegister)
mkStaticVal n v = (staticLabel n_s, registerStatic n_s (toDynamic v))
where n_s = n
class MkTDict a where
mkTDict :: String -> a -> RemoteRegister
instance (Serializable b) => MkTDict (Process b) where
mkTDict _ _ = registerStatic (show (typeOf (undefined :: b)) ++ "__staticDict") (toDynamic (SerializableDict :: SerializableDict b))
instance MkTDict a where
mkTDict _ _ = id
-- | This takes an explicit name, a function of arity one, and creates a creates a function yielding a closure and a remote register for it.
mkClosureValSingle :: forall a b. (Serializable a, Typeable b, MkTDict b) => String -> (a -> b) -> (a -> Closure b, RemoteRegister)
mkClosureValSingle n v = (c, registerStatic n_s (toDynamic v) .
registerStatic n_sdict (toDynamic sdict) .
mkTDict n_tdict (undefined :: b)
) where
n_s = n
n_sdict = n ++ "__sdict"
n_tdict = n ++ "__tdict"
c = closure decoder . encode
decoder = (staticLabel n_s :: Static (a -> b)) `staticCompose` staticDecode (staticLabel n_sdict :: Static (SerializableDict a))
sdict :: (SerializableDict a)
sdict = SerializableDict
-- | This takes an explict name, a function of any arity, and creates a function yielding a closure and a remote register for it.
mkClosureVal :: forall func argTuple result closureFunction.
(Curry (argTuple -> Closure result) closureFunction,
MkTDict result,
Uncurry HTrue argTuple func result,
Typeable result, Serializable argTuple, IsFunction func HTrue) =>
String -> func -> (closureFunction, RemoteRegister)
mkClosureVal n v = (curryFun c, rtable)
where
uv :: argTuple -> result
uv = uncurry' reify v
n_s = n
n_sdict = n ++ "__sdict"
n_tdict = n ++ "__tdict"
c :: argTuple -> Closure result
c = closure decoder . encode
decoder :: Static (B.ByteString -> result)
decoder = (staticLabel n_s :: Static (argTuple -> result)) `staticCompose` staticDecode (staticLabel n_sdict :: Static (SerializableDict argTuple))
rtable = registerStatic n_s (toDynamic uv) .
registerStatic n_sdict (toDynamic sdict) .
mkTDict n_tdict (undefined :: result)
sdict :: (SerializableDict argTuple)
sdict = SerializableDict
-- | Works just like standard call, but with a simpler signature.
call' :: forall a. Serializable a => NodeId -> Closure (Process a) -> Process a
call' = call (staticLabel $ (show $ typeOf $ (undefined :: a)) ++ "__staticDict")
data EndOfTuple deriving Typeable
instance Binary EndOfTuple where
put _ = return ()
get = return undefined
-- This generic curry is straightforward
class Curry a b | a -> b where
curryFun :: a -> b
instance Curry ((a,EndOfTuple) -> b) (a -> b) where
curryFun f = \x -> f (x,undefined)
instance Curry (b -> c) r => Curry ((a,b) -> c) (a -> r) where
curryFun f = \x -> curryFun (\y -> (f (x,y)))
-- This generic uncurry courtesy Andrea Vezzosi
data HTrue
data HFalse
data Fun :: * -> * -> * -> * where
Done :: Fun EndOfTuple r r
Moar :: Fun xs f r -> Fun (x,xs) (x -> f) r
class Uncurry'' args func result | func -> args, func -> result, args result -> func where
reify :: Fun args func result
class Uncurry flag args func result | flag func -> args, flag func -> result, args result -> func where
reify' :: flag -> Fun args func result
instance Uncurry'' rest f r => Uncurry HTrue (a,rest) (a -> f) r where
reify' _ = Moar reify
instance Uncurry HFalse EndOfTuple a a where
reify' _ = Done
instance (IsFunction func b, Uncurry b args func result) => Uncurry'' args func result where
reify = reify' (undefined :: b)
uncurry' :: Fun args func result -> func -> args -> result
uncurry' Done r _ = r
uncurry' (Moar fun) f (x,xs) = uncurry' fun (f x) xs
class IsFunction t b | t -> b
instance (b ~ HTrue) => IsFunction (a -> c) b
instance (b ~ HFalse) => IsFunction a b
|
qnikst/distributed-process
|
src/Control/Distributed/Process/Internal/Closure/Explicit.hs
|
Haskell
|
bsd-3-clause
| 5,218
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, PatternGuards, TypeSynonymInstances #-}
-- --------------------------------------------------------------------------
-- |
-- Module : XMonad.Operations
-- Copyright : (c) Spencer Janssen 2007
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : dons@cse.unsw.edu.au
-- Stability : unstable
-- Portability : not portable, Typeable deriving, mtl, posix
--
-- Operations.
--
-----------------------------------------------------------------------------
module XMonad.Operations where
import XMonad.Core
import XMonad.Layout (Full(..))
import qualified XMonad.StackSet as W
import Data.Maybe
import Data.Monoid (Endo(..))
import Data.List (nub, (\\), find)
import Data.Bits ((.|.), (.&.), complement, testBit)
import Data.Ratio
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Applicative
import Control.Monad.Reader
import Control.Monad.State
import qualified Control.Exception.Extensible as C
import System.Posix.Process (executeFile)
import Graphics.X11.Xlib
import Graphics.X11.Xinerama (getScreenInfo)
import Graphics.X11.Xlib.Extras
-- ---------------------------------------------------------------------
-- |
-- Window manager operations
-- manage. Add a new window to be managed in the current workspace.
-- Bring it into focus.
--
-- Whether the window is already managed, or not, it is mapped, has its
-- border set, and its event mask set.
--
manage :: Window -> X ()
manage w = whenX (not <$> isClient w) $ withDisplay $ \d -> do
sh <- io $ getWMNormalHints d w
let isFixedSize = sh_min_size sh /= Nothing && sh_min_size sh == sh_max_size sh
isTransient <- isJust <$> io (getTransientForHint d w)
rr <- snd `fmap` floatLocation w
-- ensure that float windows don't go over the edge of the screen
let adjust (W.RationalRect x y wid h) | x + wid > 1 || y + h > 1 || x < 0 || y < 0
= W.RationalRect (0.5 - wid/2) (0.5 - h/2) wid h
adjust r = r
f ws | isFixedSize || isTransient = W.float w (adjust rr) . W.insertUp w . W.view i $ ws
| otherwise = W.insertUp w ws
where i = W.tag $ W.workspace $ W.current ws
mh <- asks (manageHook . config)
g <- appEndo <$> userCodeDef (Endo id) (runQuery mh w)
windows (g . f)
-- | unmanage. A window no longer exists, remove it from the window
-- list, on whatever workspace it is.
--
unmanage :: Window -> X ()
unmanage = windows . W.delete
-- | Kill the specified window. If we do kill it, we'll get a
-- delete notify back from X.
--
-- There are two ways to delete a window. Either just kill it, or if it
-- supports the delete protocol, send a delete event (e.g. firefox)
--
killWindow :: Window -> X ()
killWindow w = withDisplay $ \d -> do
wmdelt <- atom_WM_DELETE_WINDOW ; wmprot <- atom_WM_PROTOCOLS
protocols <- io $ getWMProtocols d w
io $ if wmdelt `elem` protocols
then allocaXEvent $ \ev -> do
setEventType ev clientMessage
setClientMessageEvent ev w wmprot 32 wmdelt 0
sendEvent d w False noEventMask ev
else killClient d w >> return ()
-- | Kill the currently focused client.
kill :: X ()
kill = withFocused killWindow
-- ---------------------------------------------------------------------
-- Managing windows
-- | windows. Modify the current window list with a pure function, and refresh
windows :: (WindowSet -> WindowSet) -> X ()
windows f = do
XState { windowset = old } <- get
let oldvisible = concatMap (W.integrate' . W.stack . W.workspace) $ W.current old : W.visible old
newwindows = W.allWindows ws \\ W.allWindows old
ws = f old
XConf { display = d , normalBorder = nbc, focusedBorder = fbc } <- ask
mapM_ setInitialProperties newwindows
whenJust (W.peek old) $ \otherw -> io $ setWindowBorder d otherw nbc
modify (\s -> s { windowset = ws })
-- notify non visibility
let tags_oldvisible = map (W.tag . W.workspace) $ W.current old : W.visible old
gottenhidden = filter (flip elem tags_oldvisible . W.tag) $ W.hidden ws
mapM_ (sendMessageWithNoRefresh Hide) gottenhidden
-- for each workspace, layout the currently visible workspaces
let allscreens = W.screens ws
summed_visible = scanl (++) [] $ map (W.integrate' . W.stack . W.workspace) allscreens
rects <- fmap concat $ forM (zip allscreens summed_visible) $ \ (w, vis) -> do
let wsp = W.workspace w
this = W.view n ws
n = W.tag wsp
tiled = (W.stack . W.workspace . W.current $ this)
>>= W.filter (`M.notMember` W.floating ws)
>>= W.filter (`notElem` vis)
viewrect = screenRect $ W.screenDetail w
-- just the tiled windows:
-- now tile the windows on this workspace, modified by the gap
(rs, ml') <- runLayout wsp { W.stack = tiled } viewrect `catchX`
runLayout wsp { W.stack = tiled, W.layout = Layout Full } viewrect
updateLayout n ml'
let m = W.floating ws
flt = [(fw, scaleRationalRect viewrect r)
| fw <- filter (flip M.member m) (W.index this)
, Just r <- [M.lookup fw m]]
vs = flt ++ rs
io $ restackWindows d (map fst vs)
-- return the visible windows for this workspace:
return vs
let visible = map fst rects
mapM_ (uncurry tileWindow) rects
whenJust (W.peek ws) $ \w -> io $ setWindowBorder d w fbc
mapM_ reveal visible
setTopFocus
-- hide every window that was potentially visible before, but is not
-- given a position by a layout now.
mapM_ hide (nub (oldvisible ++ newwindows) \\ visible)
-- all windows that are no longer in the windowset are marked as
-- withdrawn, it is important to do this after the above, otherwise 'hide'
-- will overwrite withdrawnState with iconicState
mapM_ (flip setWMState withdrawnState) (W.allWindows old \\ W.allWindows ws)
isMouseFocused <- asks mouseFocused
unless isMouseFocused $ clearEvents enterWindowMask
asks (logHook . config) >>= userCodeDef ()
-- | Produce the actual rectangle from a screen and a ratio on that screen.
scaleRationalRect :: Rectangle -> W.RationalRect -> Rectangle
scaleRationalRect (Rectangle sx sy sw sh) (W.RationalRect rx ry rw rh)
= Rectangle (sx + scale sw rx) (sy + scale sh ry) (scale sw rw) (scale sh rh)
where scale s r = floor (toRational s * r)
-- | setWMState. set the WM_STATE property
setWMState :: Window -> Int -> X ()
setWMState w v = withDisplay $ \dpy -> do
a <- atom_WM_STATE
io $ changeProperty32 dpy w a a propModeReplace [fromIntegral v, fromIntegral none]
-- | hide. Hide a window by unmapping it, and setting Iconified.
hide :: Window -> X ()
hide w = whenX (gets (S.member w . mapped)) $ withDisplay $ \d -> do
cMask <- asks $ clientMask . config
io $ do selectInput d w (cMask .&. complement structureNotifyMask)
unmapWindow d w
selectInput d w cMask
setWMState w iconicState
-- this part is key: we increment the waitingUnmap counter to distinguish
-- between client and xmonad initiated unmaps.
modify (\s -> s { waitingUnmap = M.insertWith (+) w 1 (waitingUnmap s)
, mapped = S.delete w (mapped s) })
-- | reveal. Show a window by mapping it and setting Normal
-- this is harmless if the window was already visible
reveal :: Window -> X ()
reveal w = withDisplay $ \d -> do
setWMState w normalState
io $ mapWindow d w
whenX (isClient w) $ modify (\s -> s { mapped = S.insert w (mapped s) })
-- | Set some properties when we initially gain control of a window
setInitialProperties :: Window -> X ()
setInitialProperties w = asks normalBorder >>= \nb -> withDisplay $ \d -> do
setWMState w iconicState
asks (clientMask . config) >>= io . selectInput d w
bw <- asks (borderWidth . config)
io $ setWindowBorderWidth d w bw
-- we must initially set the color of new windows, to maintain invariants
-- required by the border setting in 'windows'
io $ setWindowBorder d w nb
-- | refresh. Render the currently visible workspaces, as determined by
-- the 'StackSet'. Also, set focus to the focused window.
--
-- This is our 'view' operation (MVC), in that it pretty prints our model
-- with X calls.
--
refresh :: X ()
refresh = windows id
-- | clearEvents. Remove all events of a given type from the event queue.
clearEvents :: EventMask -> X ()
clearEvents mask = withDisplay $ \d -> io $ do
sync d False
allocaXEvent $ \p -> fix $ \again -> do
more <- checkMaskEvent d mask p
when more again -- beautiful
-- | tileWindow. Moves and resizes w such that it fits inside the given
-- rectangle, including its border.
tileWindow :: Window -> Rectangle -> X ()
tileWindow w r = withDisplay $ \d -> do
bw <- (fromIntegral . wa_border_width) <$> io (getWindowAttributes d w)
-- give all windows at least 1x1 pixels
let least x | x <= bw*2 = 1
| otherwise = x - bw*2
io $ moveResizeWindow d w (rect_x r) (rect_y r)
(least $ rect_width r) (least $ rect_height r)
-- ---------------------------------------------------------------------
-- | Returns 'True' if the first rectangle is contained within, but not equal
-- to the second.
containedIn :: Rectangle -> Rectangle -> Bool
containedIn r1@(Rectangle x1 y1 w1 h1) r2@(Rectangle x2 y2 w2 h2)
= and [ r1 /= r2
, x1 >= x2
, y1 >= y2
, fromIntegral x1 + w1 <= fromIntegral x2 + w2
, fromIntegral y1 + h1 <= fromIntegral y2 + h2 ]
-- | Given a list of screens, remove all duplicated screens and screens that
-- are entirely contained within another.
nubScreens :: [Rectangle] -> [Rectangle]
nubScreens xs = nub . filter (\x -> not $ any (x `containedIn`) xs) $ xs
-- | Cleans the list of screens according to the rules documented for
-- nubScreens.
getCleanedScreenInfo :: MonadIO m => Display -> m [Rectangle]
getCleanedScreenInfo = io . fmap nubScreens . getScreenInfo
-- | rescreen. The screen configuration may have changed (due to
-- xrandr), update the state and refresh the screen, and reset the gap.
rescreen :: X ()
rescreen = do
xinesc <- withDisplay getCleanedScreenInfo
windows $ \ws@(W.StackSet { W.current = v, W.visible = vs, W.hidden = hs }) ->
let (xs, ys) = splitAt (length xinesc) $ map W.workspace (v:vs) ++ hs
(a:as) = zipWith3 W.Screen xs [0..] $ map SD xinesc
in ws { W.current = a
, W.visible = as
, W.hidden = ys }
-- ---------------------------------------------------------------------
-- | setButtonGrab. Tell whether or not to intercept clicks on a given window
setButtonGrab :: Bool -> Window -> X ()
setButtonGrab grab w = do
pointerMode <- asks $ \c -> if clickJustFocuses (config c)
then grabModeAsync
else grabModeSync
withDisplay $ \d -> io $ if grab
then forM_ [button1, button2, button3] $ \b ->
grabButton d b anyModifier w False buttonPressMask
pointerMode grabModeSync none none
else ungrabButton d anyButton anyModifier w
-- ---------------------------------------------------------------------
-- Setting keyboard focus
-- | Set the focus to the window on top of the stack, or root
setTopFocus :: X ()
setTopFocus = withWindowSet $ maybe (setFocusX =<< asks theRoot) setFocusX . W.peek
-- | Set focus explicitly to window 'w' if it is managed by us, or root.
-- This happens if X notices we've moved the mouse (and perhaps moved
-- the mouse to a new screen).
focus :: Window -> X ()
focus w = local (\c -> c { mouseFocused = True }) $ withWindowSet $ \s -> do
let stag = W.tag . W.workspace
curr = stag $ W.current s
mnew <- maybe (return Nothing) (fmap (fmap stag) . uncurry pointScreen)
=<< asks mousePosition
root <- asks theRoot
case () of
_ | W.member w s && W.peek s /= Just w -> windows (W.focusWindow w)
| Just new <- mnew, w == root && curr /= new
-> windows (W.view new)
| otherwise -> return ()
-- | Call X to set the keyboard focus details.
setFocusX :: Window -> X ()
setFocusX w = withWindowSet $ \ws -> do
dpy <- asks display
-- clear mouse button grab and border on other windows
forM_ (W.current ws : W.visible ws) $ \wk ->
forM_ (W.index (W.view (W.tag (W.workspace wk)) ws)) $ \otherw ->
setButtonGrab True otherw
-- If we ungrab buttons on the root window, we lose our mouse bindings.
whenX (not <$> isRoot w) $ setButtonGrab False w
hints <- io $ getWMHints dpy w
protocols <- io $ getWMProtocols dpy w
wmprot <- atom_WM_PROTOCOLS
wmtf <- atom_WM_TAKE_FOCUS
currevt <- asks currentEvent
let inputHintSet = wmh_flags hints `testBit` inputHintBit
when ((inputHintSet && wmh_input hints) || (not inputHintSet)) $
io $ do setInputFocus dpy w revertToPointerRoot 0
when (wmtf `elem` protocols) $
io $ allocaXEvent $ \ev -> do
setEventType ev clientMessage
setClientMessageEvent ev w wmprot 32 wmtf $ maybe currentTime event_time currevt
sendEvent dpy w False noEventMask ev
where event_time ev =
if (ev_event_type ev) `elem` timedEvents then
ev_time ev
else
currentTime
timedEvents = [ keyPress, keyRelease, buttonPress, buttonRelease, enterNotify, leaveNotify, selectionRequest ]
------------------------------------------------------------------------
-- Message handling
-- | Throw a message to the current 'LayoutClass' possibly modifying how we
-- layout the windows, then refresh.
sendMessage :: Message a => a -> X ()
sendMessage a = do
w <- W.workspace . W.current <$> gets windowset
ml' <- handleMessage (W.layout w) (SomeMessage a) `catchX` return Nothing
whenJust ml' $ \l' ->
windows $ \ws -> ws { W.current = (W.current ws)
{ W.workspace = (W.workspace $ W.current ws)
{ W.layout = l' }}}
-- | Send a message to all layouts, without refreshing.
broadcastMessage :: Message a => a -> X ()
broadcastMessage a = withWindowSet $ \ws -> do
let c = W.workspace . W.current $ ws
v = map W.workspace . W.visible $ ws
h = W.hidden ws
mapM_ (sendMessageWithNoRefresh a) (c : v ++ h)
-- | Send a message to a layout, without refreshing.
sendMessageWithNoRefresh :: Message a => a -> W.Workspace WorkspaceId (Layout Window) Window -> X ()
sendMessageWithNoRefresh a w =
handleMessage (W.layout w) (SomeMessage a) `catchX` return Nothing >>=
updateLayout (W.tag w)
-- | Update the layout field of a workspace
updateLayout :: WorkspaceId -> Maybe (Layout Window) -> X ()
updateLayout i ml = whenJust ml $ \l ->
runOnWorkspaces $ \ww -> return $ if W.tag ww == i then ww { W.layout = l} else ww
-- | Set the layout of the currently viewed workspace
setLayout :: Layout Window -> X ()
setLayout l = do
ss@(W.StackSet { W.current = c@(W.Screen { W.workspace = ws })}) <- gets windowset
handleMessage (W.layout ws) (SomeMessage ReleaseResources)
windows $ const $ ss {W.current = c { W.workspace = ws { W.layout = l } } }
------------------------------------------------------------------------
-- Utilities
-- | Return workspace visible on screen 'sc', or 'Nothing'.
screenWorkspace :: ScreenId -> X (Maybe WorkspaceId)
screenWorkspace sc = withWindowSet $ return . W.lookupWorkspace sc
-- | Apply an 'X' operation to the currently focused window, if there is one.
withFocused :: (Window -> X ()) -> X ()
withFocused f = withWindowSet $ \w -> whenJust (W.peek w) f
-- | 'True' if window is under management by us
isClient :: Window -> X Bool
isClient w = withWindowSet $ return . W.member w
-- | Combinations of extra modifier masks we need to grab keys\/buttons for.
-- (numlock and capslock)
extraModifiers :: X [KeyMask]
extraModifiers = do
nlm <- gets numberlockMask
return [0, nlm, lockMask, nlm .|. lockMask ]
-- | Strip numlock\/capslock from a mask
cleanMask :: KeyMask -> X KeyMask
cleanMask km = do
nlm <- gets numberlockMask
return (complement (nlm .|. lockMask) .&. km)
-- | Get the 'Pixel' value for a named color
initColor :: Display -> String -> IO (Maybe Pixel)
initColor dpy c = C.handle (\(C.SomeException _) -> return Nothing) $
(Just . color_pixel . fst) <$> allocNamedColor dpy colormap c
where colormap = defaultColormap dpy (defaultScreen dpy)
------------------------------------------------------------------------
-- | @restart name resume@. Attempt to restart xmonad by executing the program
-- @name@. If @resume@ is 'True', restart with the current window state.
-- When executing another window manager, @resume@ should be 'False'.
restart :: String -> Bool -> X ()
restart prog resume = do
broadcastMessage ReleaseResources
io . flush =<< asks display
let wsData = show . W.mapLayout show . windowset
maybeShow (t, Right (PersistentExtension ext)) = Just (t, show ext)
maybeShow (t, Left str) = Just (t, str)
maybeShow _ = Nothing
extState = return . show . catMaybes . map maybeShow . M.toList . extensibleState
args <- if resume then gets (\s -> "--resume":wsData s:extState s) else return []
catchIO (executeFile prog True args Nothing)
------------------------------------------------------------------------
-- | Floating layer support
-- | Given a window, find the screen it is located on, and compute
-- the geometry of that window wrt. that screen.
floatLocation :: Window -> X (ScreenId, W.RationalRect)
floatLocation w = withDisplay $ \d -> do
ws <- gets windowset
wa <- io $ getWindowAttributes d w
let bw = (fromIntegral . wa_border_width) wa
sc <- fromMaybe (W.current ws) <$> pointScreen (fi $ wa_x wa) (fi $ wa_y wa)
let sr = screenRect . W.screenDetail $ sc
rr = W.RationalRect ((fi (wa_x wa) - fi (rect_x sr)) % fi (rect_width sr))
((fi (wa_y wa) - fi (rect_y sr)) % fi (rect_height sr))
(fi (wa_width wa + bw*2) % fi (rect_width sr))
(fi (wa_height wa + bw*2) % fi (rect_height sr))
return (W.screen sc, rr)
where fi x = fromIntegral x
-- | Given a point, determine the screen (if any) that contains it.
pointScreen :: Position -> Position
-> X (Maybe (W.Screen WorkspaceId (Layout Window) Window ScreenId ScreenDetail))
pointScreen x y = withWindowSet $ return . find p . W.screens
where p = pointWithin x y . screenRect . W.screenDetail
-- | @pointWithin x y r@ returns 'True' if the @(x, y)@ co-ordinate is within
-- @r@.
pointWithin :: Position -> Position -> Rectangle -> Bool
pointWithin x y r = x >= rect_x r &&
x < rect_x r + fromIntegral (rect_width r) &&
y >= rect_y r &&
y < rect_y r + fromIntegral (rect_height r)
-- | Make a tiled window floating, using its suggested rectangle
float :: Window -> X ()
float w = do
(sc, rr) <- floatLocation w
windows $ \ws -> W.float w rr . fromMaybe ws $ do
i <- W.findTag w ws
guard $ i `elem` map (W.tag . W.workspace) (W.screens ws)
f <- W.peek ws
sw <- W.lookupWorkspace sc ws
return (W.focusWindow f . W.shiftWin sw w $ ws)
-- ---------------------------------------------------------------------
-- Mouse handling
-- | Accumulate mouse motion events
mouseDrag :: (Position -> Position -> X ()) -> X () -> X ()
mouseDrag f done = do
drag <- gets dragging
case drag of
Just _ -> return () -- error case? we're already dragging
Nothing -> do
XConf { theRoot = root, display = d } <- ask
io $ grabPointer d root False (buttonReleaseMask .|. pointerMotionMask)
grabModeAsync grabModeAsync none none currentTime
modify $ \s -> s { dragging = Just (motion, cleanup) }
where
cleanup = do
withDisplay $ io . flip ungrabPointer currentTime
modify $ \s -> s { dragging = Nothing }
done
motion x y = do z <- f x y
clearEvents pointerMotionMask
return z
-- | XXX comment me
mouseMoveWindow :: Window -> X ()
mouseMoveWindow w = whenX (isClient w) $ withDisplay $ \d -> do
io $ raiseWindow d w
wa <- io $ getWindowAttributes d w
(_, _, _, ox', oy', _, _, _) <- io $ queryPointer d w
let ox = fromIntegral ox'
oy = fromIntegral oy'
mouseDrag (\ex ey -> io $ moveWindow d w (fromIntegral (fromIntegral (wa_x wa) + (ex - ox)))
(fromIntegral (fromIntegral (wa_y wa) + (ey - oy))))
(float w)
-- | XXX comment me
mouseResizeWindow :: Window -> X ()
mouseResizeWindow w = whenX (isClient w) $ withDisplay $ \d -> do
io $ raiseWindow d w
wa <- io $ getWindowAttributes d w
sh <- io $ getWMNormalHints d w
io $ warpPointer d none w 0 0 0 0 (fromIntegral (wa_width wa)) (fromIntegral (wa_height wa))
mouseDrag (\ex ey ->
io $ resizeWindow d w `uncurry`
applySizeHintsContents sh (ex - fromIntegral (wa_x wa),
ey - fromIntegral (wa_y wa)))
(float w)
-- ---------------------------------------------------------------------
-- | Support for window size hints
type D = (Dimension, Dimension)
-- | Given a window, build an adjuster function that will reduce the given
-- dimensions according to the window's border width and size hints.
mkAdjust :: Window -> X (D -> D)
mkAdjust w = withDisplay $ \d -> liftIO $ do
sh <- getWMNormalHints d w
bw <- fmap (fromIntegral . wa_border_width) $ getWindowAttributes d w
return $ applySizeHints bw sh
-- | Reduce the dimensions if needed to comply to the given SizeHints, taking
-- window borders into account.
applySizeHints :: Integral a => Dimension -> SizeHints -> (a, a) -> D
applySizeHints bw sh =
tmap (+ 2 * bw) . applySizeHintsContents sh . tmap (subtract $ 2 * fromIntegral bw)
where
tmap f (x, y) = (f x, f y)
-- | Reduce the dimensions if needed to comply to the given SizeHints.
applySizeHintsContents :: Integral a => SizeHints -> (a, a) -> D
applySizeHintsContents sh (w, h) =
applySizeHints' sh (fromIntegral $ max 1 w, fromIntegral $ max 1 h)
-- | XXX comment me
applySizeHints' :: SizeHints -> D -> D
applySizeHints' sh =
maybe id applyMaxSizeHint (sh_max_size sh)
. maybe id (\(bw, bh) (w, h) -> (w+bw, h+bh)) (sh_base_size sh)
. maybe id applyResizeIncHint (sh_resize_inc sh)
. maybe id applyAspectHint (sh_aspect sh)
. maybe id (\(bw,bh) (w,h) -> (w-bw, h-bh)) (sh_base_size sh)
-- | Reduce the dimensions so their aspect ratio falls between the two given aspect ratios.
applyAspectHint :: (D, D) -> D -> D
applyAspectHint ((minx, miny), (maxx, maxy)) x@(w,h)
| or [minx < 1, miny < 1, maxx < 1, maxy < 1] = x
| w * maxy > h * maxx = (h * maxx `div` maxy, h)
| w * miny < h * minx = (w, w * miny `div` minx)
| otherwise = x
-- | Reduce the dimensions so they are a multiple of the size increments.
applyResizeIncHint :: D -> D -> D
applyResizeIncHint (iw,ih) x@(w,h) =
if iw > 0 && ih > 0 then (w - w `mod` iw, h - h `mod` ih) else x
-- | Reduce the dimensions if they exceed the given maximum dimensions.
applyMaxSizeHint :: D -> D -> D
applyMaxSizeHint (mw,mh) x@(w,h) =
if mw > 0 && mh > 0 then (min w mw,min h mh) else x
|
atupal/xmonad-mirror
|
xmonad/src/XMonad/Operations.hs
|
Haskell
|
mit
| 24,176
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PatternGuards #-}
-- This is the runner for the package-tests suite. The actual
-- tests are in in PackageTests.Tests
module Main where
import PackageTests.Options
import PackageTests.PackageTester
import PackageTests.Tests
import Distribution.Simple.Configure
( ConfigStateFileError(..), findDistPrefOrDefault, getConfigStateFile
, interpretPackageDbFlags, configCompilerEx )
import Distribution.Simple.Compiler (PackageDB(..), PackageDBStack, CompilerFlavor(GHC))
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..))
import Distribution.Simple.Program (defaultProgramConfiguration)
import Distribution.Simple.Setup (Flag(..), readPackageDbList, showPackageDbList)
import Distribution.Simple.Utils (cabalVersion)
import Distribution.Text (display)
import Distribution.Verbosity (normal, flagToVerbosity, lessVerbose)
import Distribution.ReadE (readEOrFail)
import Distribution.Compat.Time (calibrateMtimeChangeDelay)
import Control.Exception
import Data.Proxy ( Proxy(..) )
import Distribution.Compat.Environment ( lookupEnv )
import System.Directory
import Test.Tasty
import Test.Tasty.Options
import Test.Tasty.Ingredients
#if MIN_VERSION_base(4,6,0)
import System.Environment ( getExecutablePath )
#endif
main :: IO ()
main = do
-- In abstract, the Cabal test suite makes calls to the "Setup"
-- executable and tests the output of Cabal. However, we have to
-- responsible for building this executable in the first place,
-- since (1) Cabal doesn't support a test-suite depending on an
-- executable, so we can't put a "Setup" executable in the Cabal
-- file and then depend on it, (2) we don't want to call the Cabal
-- functions *directly* because we need to capture and save the
-- stdout and stderr, and (3) even if we could do all that, we will
-- want to test some Custom setup scripts, which will be specific to
-- the test at hand and need to be compiled against Cabal.
--
-- To be able to build the executable, there is some information
-- we need:
--
-- 1. We need to know what ghc to use,
--
-- 2. We need to know what package databases (plural!) contain
-- all of the necessary dependencies to make our Cabal package
-- well-formed.
--
-- We could have the user pass these all in as arguments, but
-- there's a more convenient way to get this information: the *build
-- configuration* that was used to build the Cabal library (and this
-- test suite) in the first place. To do this, we need to find the
-- 'dist' directory that was set as the build directory for Cabal.
-- First, figure out the dist directory associated with this Cabal.
dist_dir :: FilePath <- guessDistDir
-- Next, attempt to read out the LBI. This may not work, in which
-- case we'll try to guess the correct parameters. This is ignored
-- if values are explicitly passed into the test suite.
mb_lbi <- getPersistBuildConfig_ (dist_dir </> "setup-config")
-- You need to run the test suite in the right directory, sorry.
-- This variable is modestly misnamed: this refers to the base
-- directory of Cabal (so, CHECKOUT_DIR/Cabal, not
-- CHECKOUT_DIR/Cabal/test).
cabal_dir <- getCurrentDirectory
-- TODO: make this controllable by a flag. We do have a flag
-- parser but it's not called early enough for this verbosity...
verbosity <- maybe normal (readEOrFail flagToVerbosity)
`fmap` lookupEnv "VERBOSE"
-------------------------------------------------------------------
-- SETTING UP GHC AND GHC-PKG
-------------------------------------------------------------------
-- NOTE: There are TWO configurations of GHC we have to manage
-- when running the test suite.
--
-- 1. The primary GHC is the one that was used to build the
-- copy of Cabal that we are testing. This configuration
-- can be pulled out of the LBI.
--
-- 2. The "with" GHC is the version of GHC we ask the Cabal
-- we are testing to use (i.e., using --with-compiler). Notice
-- that this does NOT have to match the version we compiled
-- the library with! (Not all tests will work in this situation,
-- however, since some need to link against the Cabal library.)
-- By default we use the same configuration as the one from the
-- LBI, but a user can override it to test against a different
-- version of GHC.
mb_ghc_path <- lookupEnv "CABAL_PACKAGETESTS_GHC"
mb_ghc_pkg_path <- lookupEnv "CABAL_PACKAGETESTS_GHC_PKG"
boot_programs <-
case (mb_ghc_path, mb_ghc_pkg_path) of
(Nothing, Nothing) | Just lbi <- mb_lbi -> do
putStrLn "Using configuration from LBI"
return (withPrograms lbi)
_ -> do
putStrLn "(Re)configuring test suite (ignoring LBI)"
(_comp, _compPlatform, programsConfig)
<- configCompilerEx
(Just GHC) mb_ghc_path mb_ghc_pkg_path
-- NB: if we accept full ConfigFlags parser then
-- should use (mkProgramsConfig cfg (configPrograms cfg))
-- instead.
defaultProgramConfiguration
(lessVerbose verbosity)
return programsConfig
mb_with_ghc_path <- lookupEnv "CABAL_PACKAGETESTS_WITH_GHC"
mb_with_ghc_pkg_path <- lookupEnv "CABAL_PACKAGETESTS_WITH_GHC_PKG"
with_programs <-
case (mb_with_ghc_path, mb_with_ghc_path) of
(Nothing, Nothing) -> return boot_programs
_ -> do
putStrLn "Configuring test suite for --with-compiler"
(_comp, _compPlatform, with_programs)
<- configCompilerEx
(Just GHC) mb_with_ghc_path mb_with_ghc_pkg_path
defaultProgramConfiguration
(lessVerbose verbosity)
return with_programs
-------------------------------------------------------------------
-- SETTING UP THE DATABASE STACK
-------------------------------------------------------------------
-- Figure out what database stack to use. (This is the tricky bit,
-- because we need to have enough databases to make the just-built
-- Cabal package well-formed).
db_stack_env <- lookupEnv "CABAL_PACKAGETESTS_DB_STACK"
let packageDBStack0 = case db_stack_env of
Just str -> interpretPackageDbFlags True -- user install? why not.
(concatMap readPackageDbList
(splitSearchPath str))
Nothing ->
case mb_lbi of
Just lbi -> withPackageDB lbi
-- A wild guess!
Nothing -> interpretPackageDbFlags True []
-- Package DBs are not guaranteed to be absolute, so make them so in
-- case a subprocess using the package DB needs a different CWD.
packageDBStack1 <- mapM canonicalizePackageDB packageDBStack0
-- The LBI's database stack does *not* contain the inplace installed
-- Cabal package. So we need to add that to the stack.
let package_db_stack
= packageDBStack1 ++
[SpecificPackageDB
(dist_dir </> "package.conf.inplace")]
-- NB: It's possible that our database stack is broken (e.g.,
-- it's got a database for the wrong version of GHC, or it
-- doesn't have enough to let us build Cabal.) We'll notice
-- when we attempt to compile setup.
-- There is also is a parameter for the stack for --with-compiler,
-- since if GHC is a different version we need a different set of
-- databases. The default should actually be quite reasonable
-- as, unlike in the case of the GHC used to build Cabal, we don't
-- expect htere to be a Cabal available.
with_ghc_db_stack_env :: Maybe String
<- lookupEnv "CABAL_PACKAGETESTS_WITH_GHC_DB_STACK"
let withGhcDBStack0 :: PackageDBStack
withGhcDBStack0 =
interpretPackageDbFlags True
$ case with_ghc_db_stack_env of
Nothing -> []
Just str -> concatMap readPackageDbList (splitSearchPath str)
with_ghc_db_stack :: PackageDBStack
<- mapM canonicalizePackageDB withGhcDBStack0
-- THIS ISN'T EVEN MY FINAL FORM. The package database stack
-- controls where we install a package; specifically, the package is
-- installed to the top-most package on the stack (this makes the
-- most sense, since it could depend on any of the packages below
-- it.) If the test wants to register anything (as opposed to just
-- working in place), then we need to have another temporary
-- database we can install into (and not accidentally clobber any of
-- the other stacks.) This is done on a per-test basis.
--
-- ONE MORE THING. On the subject of installing the package (with
-- copy/register) it is EXTREMELY important that we also overload
-- the install directories, so we don't clobber anything in the
-- default install paths. VERY IMPORTANT.
-- Figure out how long we need to delay for recompilation tests
(mtimeChange, mtimeChange') <- calibrateMtimeChangeDelay
let suite = SuiteConfig
{ cabalDistPref = dist_dir
, bootProgramsConfig = boot_programs
, withProgramsConfig = with_programs
, packageDBStack = package_db_stack
, withGhcDBStack = with_ghc_db_stack
, suiteVerbosity = verbosity
, absoluteCWD = cabal_dir
, mtimeChangeDelay = mtimeChange'
}
let toMillis :: Int -> Double
toMillis x = fromIntegral x / 1000.0
putStrLn $ "Cabal test suite - testing cabal version "
++ display cabalVersion
putStrLn $ "Cabal build directory: " ++ dist_dir
putStrLn $ "Cabal source directory: " ++ cabal_dir
putStrLn $ "File modtime calibration: " ++ show (toMillis mtimeChange')
++ " (maximum observed: " ++ show (toMillis mtimeChange) ++ ")"
-- TODO: it might be useful to factor this out so that ./Setup
-- configure dumps this file, so we can read it without in a version
-- stable way.
putStrLn $ "Environment:"
putStrLn $ "CABAL_PACKAGETESTS_GHC=" ++ show (ghcPath suite) ++ " \\"
putStrLn $ "CABAL_PACKAGETESTS_GHC_PKG=" ++ show (ghcPkgPath suite) ++ " \\"
putStrLn $ "CABAL_PACKAGETESTS_WITH_GHC=" ++ show (withGhcPath suite) ++ " \\"
putStrLn $ "CABAL_PACKAGETESTS_WITH_GHC_PKG=" ++ show (withGhcPkgPath suite) ++ " \\"
-- For brevity, we use the pre-canonicalized values
let showDBStack = show
. intercalate [searchPathSeparator]
. showPackageDbList
. uninterpretPackageDBFlags
putStrLn $ "CABAL_PACKAGETESTS_DB_STACK=" ++ showDBStack packageDBStack0
putStrLn $ "CABAL_PACKAGETESTS_WITH_DB_STACK=" ++ showDBStack withGhcDBStack0
-- Create a shared Setup executable to speed up Simple tests
putStrLn $ "Building shared ./Setup executable"
rawCompileSetup verbosity suite [] "tests"
defaultMainWithIngredients options $
runTestTree "Package Tests" (tests suite)
-- Reverse of 'interpretPackageDbFlags'.
-- prop_idem stk b
-- = interpretPackageDbFlags b (uninterpretPackageDBFlags stk) == stk
uninterpretPackageDBFlags :: PackageDBStack -> [Maybe PackageDB]
uninterpretPackageDBFlags stk = Nothing : map (\x -> Just x) stk
-- | Guess what the 'dist' directory Cabal was installed in is. There's
-- no 100% reliable way to find this, but there are a few good shots:
--
-- 1. Test programs are ~always built in-place, in a directory
-- that looks like dist/build/package-tests/package-tests;
-- thus the directory can be determined by looking at $0.
-- This method is robust against sandboxes, Nix local
-- builds, and Stack, but doesn't work if you're running
-- in an interpreter.
--
-- 2. We can use the normal input methods (as per Cabal),
-- checking for the CABAL_BUILDDIR environment variable as
-- well as the default location in the current working directory.
--
-- NB: If you update this, also update its copy in cabal-install's
-- IntegrationTests
guessDistDir :: IO FilePath
guessDistDir = do
#if MIN_VERSION_base(4,6,0)
-- Method (1)
-- TODO: this needs to be BC'ified, probably.
exe_path <- canonicalizePath =<< getExecutablePath
-- exe_path is something like /path/to/dist/build/package-tests/package-tests
let dist0 = dropFileName exe_path </> ".." </> ".."
b <- doesFileExist (dist0 </> "setup-config")
#else
let dist0 = error "no path"
b = False
#endif
-- Method (2)
if b then canonicalizePath dist0
else findDistPrefOrDefault NoFlag >>= canonicalizePath
canonicalizePackageDB :: PackageDB -> IO PackageDB
canonicalizePackageDB (SpecificPackageDB path)
= SpecificPackageDB `fmap` canonicalizePath path
canonicalizePackageDB x = return x
-- | Like Distribution.Simple.Configure.getPersistBuildConfig but
-- doesn't check that the Cabal version matches, which it doesn't when
-- we run Cabal's own test suite, due to bootstrapping issues.
-- Here's the situation:
--
-- 1. There's some system Cabal-1.0 installed. We use this
-- to build Setup.hs
-- 2. We run ./Setup configure, which uses Cabal-1.0 to
-- write out the LocalBuildInfo
-- 3. We build the Cabal library, whose version is Cabal-2.0
-- 4. We build the package-tests executable, which LINKS AGAINST
-- Cabal-2.0
-- 5. We try to read the LocalBuildInfo that ./Setup configure
-- wrote out, but it's Cabal-1.0 format!
--
-- It's a bit skeevy that we're trying to read Cabal-1.0 LocalBuildInfo
-- using Cabal-2.0's parser, but this seems to work OK in practice
-- because LocalBuildInfo is a slow-moving data structure. If
-- we ever make a major change, this won't work, and we'll have to
-- take a different approach (either setting "build-type: Custom"
-- so we bootstrap with the most recent Cabal, or by writing the
-- information we need in another format.)
getPersistBuildConfig_ :: FilePath -> IO (Maybe LocalBuildInfo)
getPersistBuildConfig_ filename = do
eLBI <- try $ getConfigStateFile filename
case eLBI of
-- If the version doesn't match but we still got a successful
-- parse, don't complain and just use it!
Left (ConfigStateFileBadVersion _ _ (Right lbi)) -> return (Just lbi)
Left _ -> return Nothing
Right lbi -> return (Just lbi)
options :: [Ingredient]
options = includingOptions
[Option (Proxy :: Proxy OptionEnableAllTests)] :
defaultIngredients
|
kolmodin/cabal
|
Cabal/tests/PackageTests.hs
|
Haskell
|
bsd-3-clause
| 15,012
|
module IfFrom where
{- map2 xs = map (if xs == [] then (+) else (-)) [ 1 ,2 .. 5] -}
map2 xs = (case ((+), [1,2..5]) of
(f, []) -> []
(f, (x : xs)) -> (f x) : (map (if xs == [] then (+) else (-))
[1,2 .. 5]))
|
SAdams601/HaRe
|
old/testing/generativeFold/IfFrom.hs
|
Haskell
|
bsd-3-clause
| 287
|
module Main where
import qualified MsgGen
import qualified TopicTest
import Test.Tasty
main :: IO ()
main = do genTests <- MsgGen.tests
defaultMain $ testGroup "roshask" [
testGroup "roshask executable"
[ genTests ]
, testGroup "roshask library"
[ TopicTest.topicTests]]
|
bitemyapp/roshask
|
Tests/AllTests.hs
|
Haskell
|
bsd-3-clause
| 342
|
import qualified Data.ByteString.Char8 as B
import Parse
import Gen
main = do parseResult <- parseMsg "LaserScan.msg"
let txt = case parseResult of
Right msg -> generateMsgType msg
Left err -> error err
putStr (B.unpack txt)
B.writeFile "LaserScan.hs" txt
|
bitemyapp/roshask
|
src/executable/Test.hs
|
Haskell
|
bsd-3-clause
| 330
|
module Bug (tst) where
tst :: Float -> Bool
tst x = truncate x > (0::Int)
|
urbanslug/ghc
|
testsuite/tests/codeGen/should_compile/T1916.hs
|
Haskell
|
bsd-3-clause
| 74
|
-- re-exporting m2 outside of C(..)
module Mod118_A( C(m1), m2) where
class C a where
m1 :: a -> Int
m2 :: a -> Bool
instance C Int where
m1 _ = 1
m2 _ = True
|
urbanslug/ghc
|
testsuite/tests/module/Mod118_A.hs
|
Haskell
|
bsd-3-clause
| 170
|
-- https://www.hackerrank.com/challenges/grading/problem
-- Constants
threshold = 3
lowerLimit = 38
toInt :: String -> Int
toInt string = read string :: Int
calculateNextMultipleOfFive :: Int -> Int
calculateNextMultipleOfFive grade = grade + 5 - (grade `mod` 5)
gradeStudent :: Int -> Int
gradeStudent grade
| grade < lowerLimit = grade
| otherwise = if difference < threshold then nextMultiple else grade
where
nextMultiple = calculateNextMultipleOfFive grade
difference = nextMultiple - grade
readGrades :: String -> [String]
readGrades = tail . lines
main :: IO ()
main =
interact $ unlines . map (show . gradeStudent . toInt) . readGrades
|
julianespinel/training
|
hackerrank/Grading.hs
|
Haskell
|
mit
| 667
|
{-# LANGUAGE FlexibleContexts #-}
module Server (
server, authServerContext, AuthMap
) where
import Servant
import API
import Config
import Server.Main
import Server.Login
import Server.Swagger
import Server.Static
server :: AuthMap -> Config -> Server API
server m cfg = convertServer cfg (mainServer :<|> loginServer m)
:<|> swaggerServer
:<|> staticServer cfg
|
lierdakil/markco
|
server/src/Server.hs
|
Haskell
|
mit
| 378
|
module FRP.Jalapeno.Sample where
-------------
-- Imports --
import Control.Concurrent
import Data.Time.Clock
import FRP.Jalapeno.Behavior
----------
-- Code --
{--- | Sampling a @'Behavior'@ in real time at a maximum number of times per-}
{--- second.-}
{-intermittentSample :: (Monad m, Show a) => Behavior m a -> Int -> IO ()-}
{-intermittentSample b rate = do-}
{-ct <- getCurrentTime-}
{-intermittentSample' ct 0 b rate-}
{-where intermittentSample' :: (Monad m, Show a) => UTCTime -> Double -> Behavior m a -> Int -> IO ()-}
{-intermittentSample' lt t b rate = do-}
{-runBehavior t b >>= print-}
{--- Non-reactive delay. Could fix later to make sure that if it's-}
{--- running slowly it doesn't apply the delay.-}
{-threadDelay $ 1000000 `div` rate-}
{-ct <- getCurrentTime-}
{-intermittentSample' ct-}
{-(t + (fromRational $ toRational $ diffUTCTime ct lt))-}
{-b-}
{-rate-}
{--- | Sampling a @'Behavior'@ at around 100 samples per second.-}
{-sample :: (Monad m, Show a) => Behavior m a -> IO ()-}
{-sample b = intermittentSample b 60-}
|
crockeo/jalapeno
|
src/lib/FRP/Jalapeno/Sample.hs
|
Haskell
|
mit
| 1,219
|
module U.Codebase.Sqlite.Branch.Format where
import Data.Vector (Vector)
import U.Codebase.Sqlite.Branch.Diff (LocalDiff)
import U.Codebase.Sqlite.Branch.Full (LocalBranch)
import U.Codebase.Sqlite.DbId (CausalHashId, BranchObjectId, ObjectId, PatchObjectId, TextId)
import Data.ByteString (ByteString)
-- |you can use the exact same `BranchLocalIds` when converting between `Full` and `Diff`
data BranchFormat
= Full BranchLocalIds LocalBranch
| Diff BranchObjectId BranchLocalIds LocalDiff
deriving Show
data BranchLocalIds = LocalIds
{ branchTextLookup :: Vector TextId,
branchDefnLookup :: Vector ObjectId,
branchPatchLookup :: Vector PatchObjectId,
branchChildLookup :: Vector (BranchObjectId, CausalHashId)
}
deriving Show
data SyncBranchFormat
= SyncFull BranchLocalIds ByteString
| SyncDiff BranchObjectId BranchLocalIds ByteString
|
unisonweb/platform
|
codebase2/codebase-sqlite/U/Codebase/Sqlite/Branch/Format.hs
|
Haskell
|
mit
| 872
|
module Problem0012 where
import Data.List
--http://www.mathsisfun.com/algebra/triangular-numbers.html
nthTriangleNumber nth =
round
$(nth * ( nth + 1)) / 2
infiniteListOfTriangleNumbers = [nthTriangleNumber x | x <- [1..]]
--http://rosettacode.org/wiki/Factors_of_an_integer#Haskell
factors n = lows ++ (reverse $ map (div n) lows)
where lows = filter ((== 0) . mod n) [1..truncate . sqrt $ fromIntegral n]
firstTriangleNumberWithMoreThanHowManyFactors n =
head $ filter (\x -> (length $ factors x) > n) infiniteListOfTriangleNumbers
|
Sobieck00/practice
|
pe/nonvisualstudio/haskell/OldWork/Implementation/Problem0012.hs
|
Haskell
|
mit
| 570
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.