code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-| Module : Utils Description : Utility functions -} module Utils where import Data.Map (Map) import qualified Data.Map.Strict as M -- |Unsafely lookup a value in a map by key unsafeLookup :: (Show k, Show v, Ord k) => k -> Map k v -> v unsafeLookup k m = case M.lookup k m of Nothing -> error $ "unsafeLookup on key " ++ show k ++ " in map " ++ show m Just x -> x -- |Safely get the last value of a list safeLast :: [a] -> Maybe a safeLast [] = Nothing safeLast [x] = Just x safeLast (x : xs) = safeLast xs
adamschoenemann/simple-frp
src/Utils.hs
mit
528
0
11
128
180
95
85
12
2
module Network.Statsd.UdpClient ( UdpClient , fromURI , send ) where import Control.Monad import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BLazy import qualified Data.ByteString.Char8 as BC import Data.ByteString.Lazy.Builder (int64LE, toLazyByteString) import Data.Byteable import System.Time import System.IO.Error import Crypto.Hash import Crypto.Random.DRBG import qualified Network.Socket as Net hiding (send, sendTo, recv, recvFrom) import qualified Network.Socket.ByteString as Net import Network.URI type Hostname = String type Port = Int type Key = String type Namespace = String type Payload = B.ByteString type Nonce = B.ByteString data UdpClient = UdpClient { getSocket :: Net.Socket , getNamespace :: Namespace , getSigningKey :: Maybe Key } fromURI :: URI -> IO UdpClient fromURI (URI "statsd:" (Just (URIAuth auth regname port)) path _ _) = let regname' = uriRegName' regname port' = if null port then 8126 else read $ stripLeading ':' port prefix = replace '/' '.' $ stripLeading '/' path key = case break (==':') (stripTrailing '@' auth) of (u, ':':p) -> Just p _ -> Nothing in client regname' port' prefix key where replace :: Eq a => a -> a -> [a] -> [a] replace from to list = (\a -> if a == from then to else a) <$> list uriRegName' :: String -> String uriRegName' = takeWhile (/=']') . dropWhile (=='[') stripLeading :: Eq a => a -> [a] -> [a] stripLeading x [] = [] stripLeading x y@(y':ys') | x == y' = ys' | otherwise = y stripTrailing :: Eq a => a -> [a] -> [a] stripTrailing x [] = [] stripTrailing x xs = let init' = init xs last' = last xs in if last' == x then init' else xs fromURI uri = error $ "invalid URI" ++ show uri client :: Hostname -> Port -> Namespace -> Maybe Key -> IO UdpClient client host port namespace key = do (addr:_) <- Net.getAddrInfo Nothing (Just host) (Just $ show port) sock <- Net.socket (Net.addrFamily addr) Net.Datagram Net.defaultProtocol Net.connect sock (Net.addrAddress addr) return $ UdpClient sock namespace key send :: UdpClient -> String -> IO (Either IOError ()) send client datagram = do let namespace = getNamespace client let message = if null namespace then datagram else namespace ++ "." ++ datagram signedPayload <- signed (getSigningKey client) (BC.pack message) tryIOError . void $ Net.send (getSocket client) signedPayload signed :: Maybe Key -> Payload -> IO Payload signed Nothing payload = return payload signed (Just key) payload = do (TOD sec _) <- getClockTime let timestamp = B.concat . BLazy.toChunks . toLazyByteString . int64LE $ fromIntegral sec gen <- newGenIO :: IO CtrDRBG let (nonce, _) = throwLeft $ genBytes 4 gen let newPayload = B.concat [timestamp, nonce, payload] return $ sign key newPayload sign :: Key -> Payload -> Payload sign key payload = let keyBytes = BC.pack key signature = toBytes (hmac keyBytes payload :: HMAC SHA256) in B.append signature payload
keithduncan/statsd-client
src/Network/Statsd/UdpClient.hs
mit
3,318
0
14
904
1,152
603
549
79
7
----------------------------------------------------------------------------- -- -- Module : Main -- Copyright : -- License : AllRightsReserved -- -- Maintainer : -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Main ( main ) where import Topology (cycles) import Path (path, pathFailed, broadcast, broadcastFailed) import Data.List (intercalate) -- render :: (Show a) => [(a, a)] -> String -- render = intercalate ", " . map (\(f,t) -> show f ++ " -> " ++ show t) -- -- renders = intercalate "\n" . map render main :: IO () main = print $ cycles 4
uvNikita/TopologyRouting
src/Main.hs
mit
654
0
6
120
83
56
27
7
1
-- | Contains master-related actions, like finding a specific master release by id -- or getting a list of all master versions. module Discogs.Actions.Master ( getMaster, getMasterVersions ) where import Discogs.Types.Master import Discogs.Types.Discogs import qualified Discogs.Routes.Master as Route import Control.Monad import Data.Default.Class import Data.Aeson import qualified Data.Text as Text -- | Get the information on a master release with the specified id -- -- GET \/masters\/:masterId -- -- @ -- runDiscogsAnon $ Discogs.Actions.getMaster $ MasterID "1000" -- @ getMaster :: Monad m => MasterID -> DiscogsT m Master getMaster = runRoute . Route.getMaster -- | Get a list of all master versions with a specific id -- -- GET \/masters\/:masterId\/versions -- -- @ -- runDiscogsAnon $ Discogs.Actions.getMasterVersions $ MasterID "1000" -- @ getMasterVersions :: Monad m => MasterID -> DiscogsT m MasterVersionsList getMasterVersions = runRoute . Route.getMasterVersions
accraze/discogs-haskell
src/Discogs/Actions/Master.hs
mit
1,003
0
7
157
140
89
51
14
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-licensespecification.html module Stratosphere.ResourceProperties.EC2LaunchTemplateLicenseSpecification where import Stratosphere.ResourceImports -- | Full data type definition for EC2LaunchTemplateLicenseSpecification. See -- 'ec2LaunchTemplateLicenseSpecification' for a more convenient -- constructor. data EC2LaunchTemplateLicenseSpecification = EC2LaunchTemplateLicenseSpecification { _eC2LaunchTemplateLicenseSpecificationLicenseConfigurationArn :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON EC2LaunchTemplateLicenseSpecification where toJSON EC2LaunchTemplateLicenseSpecification{..} = object $ catMaybes [ fmap (("LicenseConfigurationArn",) . toJSON) _eC2LaunchTemplateLicenseSpecificationLicenseConfigurationArn ] -- | Constructor for 'EC2LaunchTemplateLicenseSpecification' containing -- required fields as arguments. ec2LaunchTemplateLicenseSpecification :: EC2LaunchTemplateLicenseSpecification ec2LaunchTemplateLicenseSpecification = EC2LaunchTemplateLicenseSpecification { _eC2LaunchTemplateLicenseSpecificationLicenseConfigurationArn = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-licensespecification.html#cfn-ec2-launchtemplate-licensespecification-licenseconfigurationarn ecltlsLicenseConfigurationArn :: Lens' EC2LaunchTemplateLicenseSpecification (Maybe (Val Text)) ecltlsLicenseConfigurationArn = lens _eC2LaunchTemplateLicenseSpecificationLicenseConfigurationArn (\s a -> s { _eC2LaunchTemplateLicenseSpecificationLicenseConfigurationArn = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EC2LaunchTemplateLicenseSpecification.hs
mit
1,813
0
12
158
174
101
73
22
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} module Oden.Infer.Unification ( UnificationError(..), Constraint, runSolve, unifyMany, unifies ) where import Control.Monad.Except import Control.Monad.Identity import qualified Data.Map as Map import qualified Data.Set as Set import Oden.Identifier import Oden.Infer.Substitution import Oden.Metadata import Oden.SourceInfo import Oden.Type.Polymorphic data UnificationError = UnificationFail SourceInfo Type Type | RowFieldUnificationFail SourceInfo (Identifier, Type) (Identifier, Type) | InfiniteType SourceInfo TVar Type | UnificationMismatch SourceInfo [Type] [Type] deriving (Show, Eq) type Constraint = (SourceInfo, Type, Type) instance FTV Constraint where ftv (_, t1, t2) = ftv t1 `Set.union` ftv t2 instance Substitutable Constraint where apply s (si, t1, t2) = (si, apply s t1, apply s t2) -- | Constraint solver monad. type Solve a = ExceptT UnificationError Identity a -- | Unifies the corresponding types in the lists (like a zip). unifyMany :: SourceInfo -> [Type] -> [Type] -> Solve Subst unifyMany _ [] [] = return emptySubst unifyMany si (t1 : ts1) (t2 : ts2) = do su1 <- unifies si t1 t2 su2 <- unifyMany si (apply su1 ts1) (apply su1 ts2) return (su2 `compose` su1) unifyMany si t1 t2 = throwError $ UnificationMismatch si t1 t2 -- | Unify two types, returning the resulting substitution. unifies :: SourceInfo -> Type -> Type -> Solve Subst unifies _ (TVar _ v) t = v `bind` t unifies _ t (TVar _ v) = v `bind` t unifies _ (TCon _ n1) (TCon _ n2) | n1 == n2 = return emptySubst unifies si (TFn _ t1 t2) (TFn _ t3 t4) = unifyMany si [t1, t2] [t3, t4] unifies si (TNoArgFn _ t1) (TNoArgFn _ t2) = unifies si t1 t2 unifies si (TForeignFn _ v1 ps1 rs1) (TForeignFn _ v2 ps2 rs2) | v1 == v2 = do p <- unifyMany si ps1 ps2 r <- unifyMany si rs1 rs2 return (r `compose` p) unifies si (TTuple _ f1 s1 r1) (TTuple _ f2 s2 r2) = do f <- unifies si f1 f2 s <- unifies si s1 s2 r <- unifyMany si r1 r2 return (f `compose` s `compose` r) unifies si (TSlice _ t1) (TSlice _ t2) = unifies si t1 t2 unifies si (TNamed _ n1 t1) (TNamed _ n2 t2) | n1 == n2 = unifies si t1 t2 unifies si t1 (TNamed _ _ t2) = unifies si t1 t2 unifies si (TNamed _ _ t1) t2 = unifies si t1 t2 unifies si (TRecord _ r1) (TRecord _ r2) = unifies si r1 r2 unifies _ REmpty{} REmpty{} = return emptySubst unifies si r1@RExtension{} r2@RExtension{} = do -- Get all fields in the rows. let f1 = Map.fromList (rowToList r1) f2 = Map.fromList (rowToList r2) -- Get the unique fields in each row. onlyInR1 = f1 `Map.difference` f2 onlyInR2 = f2 `Map.difference` f1 -- Unify the common field with matching labels. substs <- sequence (Map.elems (Map.intersectionWith (unifies si) f1 f2)) -- For both rows, unify the leaf row (possibly a row variable) with unique -- fields in the other row. In case both leafs are row variables, just unify -- those. leafSubst <- case (getLeafRow r1, getLeafRow r2) of (leaf1@TVar{}, leaf2@TVar{}) -> compose <$> unifies si leaf1 (rowFromList (Map.assocs onlyInR2) leaf2) <*> unifies si leaf2 (rowFromList (Map.assocs onlyInR1) leaf1) (leaf1, leaf2) -> compose <$> unifies si leaf1 (rowFromList (Map.assocs onlyInR2) (REmpty (Metadata si))) <*> unifies si leaf2 (rowFromList (Map.assocs onlyInR1) (REmpty (Metadata si))) -- Return all substitutions. return $ foldl1 compose (leafSubst : substs) unifies si t1 t2 = throwError $ UnificationFail si t1 t2 -- Unification solver solver :: Subst -> [Constraint] -> Solve Subst solver su cs = case cs of [] -> return su ((si, t1, t2): cs0) -> do su1 <- unifies si t1 t2 solver (su1 `compose` su) (apply su1 cs0) -- | Create a substitution from the 'TVar' to the 'Type', as long as the 'TVar' -- does not occur in the 'Type'. In that case we have an infinite type, which -- is an error. bind :: TVar -> Type -> Solve Subst bind a (TVar _ v) | v == a = return emptySubst bind a t | occursCheck a t = throwError $ InfiniteType (getSourceInfo t) a t | otherwise = return (Subst $ Map.singleton a t) -- | Check if the 'TVar' occurs in the 'Type'. occursCheck :: Substitutable a => TVar -> a -> Bool occursCheck a t = a `Set.member` ftv t -- | Run the constraint solver runSolve :: [Constraint] -> Either UnificationError Subst runSolve cs = runIdentity $ runExceptT $ solver emptySubst cs
AlbinTheander/oden
src/Oden/Infer/Unification.hs
mit
4,690
0
19
1,140
1,678
867
811
90
2
-- | -- Module : Data.Logic.Propositional -- Copyright : (c) K. Isom (2015) -- License : BSD-style -- -- Maintainer : coder@kyleisom.net -- Stability : stable -- Portability : portable -- -- This is a library for representing and implementing propositional logic -- proofs. module Data.Logic.Propositional ( Result (..) , prove , interactive ) where import Control.Monad.Except import Data.Logic.Propositional.Class import qualified Data.Logic.Propositional.Parser as Parser import qualified System.IO as IO ------------------------------------------------------------------------------- -------------------------------- Truth Tables --------------------------------- ------------------------------------------------------------------------------- truth :: Bindings -> Term -> ProofError Bool truth bindings term = do liftIO $ putStrLn $ "Evaluating term: " ++ (show term) truthTable bindings term -- | Evaluates a term in the context of a set of bindings; it returns a -- 'ProofError' containing either an error in the proof or a 'Bool' -- result of the logical operation. truthTable :: Bindings -> Term -> ProofError Bool truthTable bindings (Value v) = return v truthTable bindings (Variable name) = getName bindings name >>= truth bindings truthTable bindings (Implies p q) = do p' <- truth bindings p q' <- truth bindings q return (if p' && (not q') then False else True) truthTable bindings (Conjunction p q) = do p' <- truth bindings p q' <- truth bindings q return $ p' && q' truthTable bindings (Disjunction p q) = do p' <- truth bindings p q' <- truth bindings q return $ p' || q' truthTable bindings (Equivalence p q) = do p' <- truth bindings p q' <- truth bindings q return $ p' == q' truthTable bindings (Negation p) = do p' <- truth bindings p return $ not p' -- | A 'Result' contains the result of a proof. data Result = Result Bindings [Theorem] Bool showResult :: Result -> String showResult (Result b _ v) = "Result:\n-------\nBindings:\n" ++ (show b) ++ "Result: " ++ (show v) instance Show Result where show = showResult proofResult :: Proof -> Result proofResult (Proof b thms) = Result b thms False data Step = Step Bindings Bool instance Show Step where show (Step b v) = "Result: " ++ show v ++ "\nBindings:\n" ++ show b evaluate :: Bindings -> Theorem -> ProofError Step evaluate bindings (Axiom name value) = do result <- bindName bindings name value liftIO $ putStrLn $ "Axiom " ++ name ++ " <- " ++ (show value) ++ " entered." return $ Step result True evaluate bindings (Theorem term) = truth bindings term >>= return . Step bindings step :: Result -> ProofError Result step (Result bindings (theorem:theorems) _) = do liftIO $ putStrLn $ "Evaluating theorem: " ++ (show theorem) result <- liftIO $ runExceptT $ evaluate bindings theorem case result of Right (Step bindings' v) -> do liftIO $ putStrLn $ "Truth value: " ++ (show v) return $ Result bindings' theorems v Left err -> throwError err step (Result b thms v) = return $ Result b thms v check :: Proof -> ProofError Result check (Proof b thms) = check' (Result b thms False) where check' proof@(Result _ (_:_) _) = step proof >>= check' check' result@(Result _ [] _) = return result -- | 'prove' runs through the proof, ensuring that it is valid and that -- it isn't inconsistent. prove :: Proof -> ProofError Bindings prove proof = do result <- liftIO $ runExceptT $ check proof case result of Left err -> throwError err Right (Result b _ True) -> return b Right (Result _ _ False) -> throwError Invalid prnFlush :: String -> IO () prnFlush s = putStr s >> IO.hFlush IO.stdout readPrompt :: String -> IO String readPrompt prompt = prnFlush prompt >> IO.getLine displayResult :: Either Error Step -> IO String displayResult proof = do return $ case proof of Left err -> show err Right s -> show s evalLine :: Bindings -> String -> ProofError Step evalLine b line = Parser.readExpr line >>= evaluate b -- | interactive runs a sort of REPL; users enter their proof, one line -- at a time, and PLC builds a proof from that. The REPL runs until -- the user enters "quit". interactive :: Bindings -> IO () interactive initial = do line <- readPrompt "PLC> " case line of "quit" -> putStrLn "Goodbye." "clear" -> putStrLn "Cleared bindings." >> interactive newBindings "bindings" -> putStrLn $ show initial _ -> interactiveEval initial line interactiveEval :: Bindings -> String -> IO () interactiveEval b s = do let result = runExceptT $ evalLine b s result >>= displayResult >>= putStrLn result' <- result case result' of Left err -> interactive b Right (Step b' _) -> interactive b'
kisom/plc
src/Data/Logic/Propositional.hs
mit
4,966
1
14
1,166
1,476
723
753
101
4
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.WebKitCSSMatrix (newWebKitCSSMatrix, setMatrixValue, multiply, multiply_, inverse, inverse_, translate, translate_, scale, scale_, rotate, rotate_, rotateAxisAngle, rotateAxisAngle_, skewX, skewX_, skewY, skewY_, toString, toString_, setA, getA, setB, getB, setC, getC, setD, getD, setE, getE, setF, getF, setM11, getM11, setM12, getM12, setM13, getM13, setM14, getM14, setM21, getM21, setM22, getM22, setM23, getM23, setM24, getM24, setM31, getM31, setM32, getM32, setM33, getM33, setM34, getM34, setM41, getM41, setM42, getM42, setM43, getM43, setM44, getM44, WebKitCSSMatrix(..), gTypeWebKitCSSMatrix) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix Mozilla WebKitCSSMatrix documentation> newWebKitCSSMatrix :: (MonadDOM m, ToJSString cssValue) => Maybe cssValue -> m WebKitCSSMatrix newWebKitCSSMatrix cssValue = liftDOM (WebKitCSSMatrix <$> new (jsg "WebKitCSSMatrix") [toJSVal cssValue]) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.setMatrixValue Mozilla WebKitCSSMatrix.setMatrixValue documentation> setMatrixValue :: (MonadDOM m, ToJSString string) => WebKitCSSMatrix -> Maybe string -> m () setMatrixValue self string = liftDOM (void (self ^. jsf "setMatrixValue" [toJSVal string])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.multiply Mozilla WebKitCSSMatrix.multiply documentation> multiply :: (MonadDOM m) => WebKitCSSMatrix -> Maybe WebKitCSSMatrix -> m WebKitCSSMatrix multiply self secondMatrix = liftDOM ((self ^. jsf "multiply" [toJSVal secondMatrix]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.multiply Mozilla WebKitCSSMatrix.multiply documentation> multiply_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe WebKitCSSMatrix -> m () multiply_ self secondMatrix = liftDOM (void (self ^. jsf "multiply" [toJSVal secondMatrix])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.inverse Mozilla WebKitCSSMatrix.inverse documentation> inverse :: (MonadDOM m) => WebKitCSSMatrix -> m WebKitCSSMatrix inverse self = liftDOM ((self ^. jsf "inverse" ()) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.inverse Mozilla WebKitCSSMatrix.inverse documentation> inverse_ :: (MonadDOM m) => WebKitCSSMatrix -> m () inverse_ self = liftDOM (void (self ^. jsf "inverse" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.translate Mozilla WebKitCSSMatrix.translate documentation> translate :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix translate self x y z = liftDOM ((self ^. jsf "translate" [toJSVal x, toJSVal y, toJSVal z]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.translate Mozilla WebKitCSSMatrix.translate documentation> translate_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> Maybe Double -> Maybe Double -> m () translate_ self x y z = liftDOM (void (self ^. jsf "translate" [toJSVal x, toJSVal y, toJSVal z])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.scale Mozilla WebKitCSSMatrix.scale documentation> scale :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix scale self scaleX scaleY scaleZ = liftDOM ((self ^. jsf "scale" [toJSVal scaleX, toJSVal scaleY, toJSVal scaleZ]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.scale Mozilla WebKitCSSMatrix.scale documentation> scale_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> Maybe Double -> Maybe Double -> m () scale_ self scaleX scaleY scaleZ = liftDOM (void (self ^. jsf "scale" [toJSVal scaleX, toJSVal scaleY, toJSVal scaleZ])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.rotate Mozilla WebKitCSSMatrix.rotate documentation> rotate :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix rotate self rotX rotY rotZ = liftDOM ((self ^. jsf "rotate" [toJSVal rotX, toJSVal rotY, toJSVal rotZ]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.rotate Mozilla WebKitCSSMatrix.rotate documentation> rotate_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> Maybe Double -> Maybe Double -> m () rotate_ self rotX rotY rotZ = liftDOM (void (self ^. jsf "rotate" [toJSVal rotX, toJSVal rotY, toJSVal rotZ])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.rotateAxisAngle Mozilla WebKitCSSMatrix.rotateAxisAngle documentation> rotateAxisAngle :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix rotateAxisAngle self x y z angle = liftDOM ((self ^. jsf "rotateAxisAngle" [toJSVal x, toJSVal y, toJSVal z, toJSVal angle]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.rotateAxisAngle Mozilla WebKitCSSMatrix.rotateAxisAngle documentation> rotateAxisAngle_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> Maybe Double -> Maybe Double -> Maybe Double -> m () rotateAxisAngle_ self x y z angle = liftDOM (void (self ^. jsf "rotateAxisAngle" [toJSVal x, toJSVal y, toJSVal z, toJSVal angle])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.skewX Mozilla WebKitCSSMatrix.skewX documentation> skewX :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> m WebKitCSSMatrix skewX self angle = liftDOM ((self ^. jsf "skewX" [toJSVal angle]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.skewX Mozilla WebKitCSSMatrix.skewX documentation> skewX_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> m () skewX_ self angle = liftDOM (void (self ^. jsf "skewX" [toJSVal angle])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.skewY Mozilla WebKitCSSMatrix.skewY documentation> skewY :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> m WebKitCSSMatrix skewY self angle = liftDOM ((self ^. jsf "skewY" [toJSVal angle]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.skewY Mozilla WebKitCSSMatrix.skewY documentation> skewY_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> m () skewY_ self angle = liftDOM (void (self ^. jsf "skewY" [toJSVal angle])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.toString Mozilla WebKitCSSMatrix.toString documentation> toString :: (MonadDOM m, FromJSString result) => WebKitCSSMatrix -> m result toString self = liftDOM ((self ^. jsf "toString" ()) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.toString Mozilla WebKitCSSMatrix.toString documentation> toString_ :: (MonadDOM m) => WebKitCSSMatrix -> m () toString_ self = liftDOM (void (self ^. jsf "toString" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.a Mozilla WebKitCSSMatrix.a documentation> setA :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setA self val = liftDOM (self ^. jss "a" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.a Mozilla WebKitCSSMatrix.a documentation> getA :: (MonadDOM m) => WebKitCSSMatrix -> m Double getA self = liftDOM ((self ^. js "a") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.b Mozilla WebKitCSSMatrix.b documentation> setB :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setB self val = liftDOM (self ^. jss "b" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.b Mozilla WebKitCSSMatrix.b documentation> getB :: (MonadDOM m) => WebKitCSSMatrix -> m Double getB self = liftDOM ((self ^. js "b") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.c Mozilla WebKitCSSMatrix.c documentation> setC :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setC self val = liftDOM (self ^. jss "c" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.c Mozilla WebKitCSSMatrix.c documentation> getC :: (MonadDOM m) => WebKitCSSMatrix -> m Double getC self = liftDOM ((self ^. js "c") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.d Mozilla WebKitCSSMatrix.d documentation> setD :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setD self val = liftDOM (self ^. jss "d" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.d Mozilla WebKitCSSMatrix.d documentation> getD :: (MonadDOM m) => WebKitCSSMatrix -> m Double getD self = liftDOM ((self ^. js "d") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.e Mozilla WebKitCSSMatrix.e documentation> setE :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setE self val = liftDOM (self ^. jss "e" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.e Mozilla WebKitCSSMatrix.e documentation> getE :: (MonadDOM m) => WebKitCSSMatrix -> m Double getE self = liftDOM ((self ^. js "e") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.f Mozilla WebKitCSSMatrix.f documentation> setF :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setF self val = liftDOM (self ^. jss "f" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.f Mozilla WebKitCSSMatrix.f documentation> getF :: (MonadDOM m) => WebKitCSSMatrix -> m Double getF self = liftDOM ((self ^. js "f") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m11 Mozilla WebKitCSSMatrix.m11 documentation> setM11 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM11 self val = liftDOM (self ^. jss "m11" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m11 Mozilla WebKitCSSMatrix.m11 documentation> getM11 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM11 self = liftDOM ((self ^. js "m11") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m12 Mozilla WebKitCSSMatrix.m12 documentation> setM12 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM12 self val = liftDOM (self ^. jss "m12" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m12 Mozilla WebKitCSSMatrix.m12 documentation> getM12 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM12 self = liftDOM ((self ^. js "m12") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m13 Mozilla WebKitCSSMatrix.m13 documentation> setM13 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM13 self val = liftDOM (self ^. jss "m13" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m13 Mozilla WebKitCSSMatrix.m13 documentation> getM13 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM13 self = liftDOM ((self ^. js "m13") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m14 Mozilla WebKitCSSMatrix.m14 documentation> setM14 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM14 self val = liftDOM (self ^. jss "m14" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m14 Mozilla WebKitCSSMatrix.m14 documentation> getM14 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM14 self = liftDOM ((self ^. js "m14") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m21 Mozilla WebKitCSSMatrix.m21 documentation> setM21 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM21 self val = liftDOM (self ^. jss "m21" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m21 Mozilla WebKitCSSMatrix.m21 documentation> getM21 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM21 self = liftDOM ((self ^. js "m21") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m22 Mozilla WebKitCSSMatrix.m22 documentation> setM22 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM22 self val = liftDOM (self ^. jss "m22" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m22 Mozilla WebKitCSSMatrix.m22 documentation> getM22 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM22 self = liftDOM ((self ^. js "m22") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m23 Mozilla WebKitCSSMatrix.m23 documentation> setM23 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM23 self val = liftDOM (self ^. jss "m23" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m23 Mozilla WebKitCSSMatrix.m23 documentation> getM23 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM23 self = liftDOM ((self ^. js "m23") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m24 Mozilla WebKitCSSMatrix.m24 documentation> setM24 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM24 self val = liftDOM (self ^. jss "m24" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m24 Mozilla WebKitCSSMatrix.m24 documentation> getM24 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM24 self = liftDOM ((self ^. js "m24") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m31 Mozilla WebKitCSSMatrix.m31 documentation> setM31 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM31 self val = liftDOM (self ^. jss "m31" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m31 Mozilla WebKitCSSMatrix.m31 documentation> getM31 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM31 self = liftDOM ((self ^. js "m31") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m32 Mozilla WebKitCSSMatrix.m32 documentation> setM32 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM32 self val = liftDOM (self ^. jss "m32" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m32 Mozilla WebKitCSSMatrix.m32 documentation> getM32 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM32 self = liftDOM ((self ^. js "m32") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m33 Mozilla WebKitCSSMatrix.m33 documentation> setM33 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM33 self val = liftDOM (self ^. jss "m33" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m33 Mozilla WebKitCSSMatrix.m33 documentation> getM33 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM33 self = liftDOM ((self ^. js "m33") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m34 Mozilla WebKitCSSMatrix.m34 documentation> setM34 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM34 self val = liftDOM (self ^. jss "m34" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m34 Mozilla WebKitCSSMatrix.m34 documentation> getM34 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM34 self = liftDOM ((self ^. js "m34") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m41 Mozilla WebKitCSSMatrix.m41 documentation> setM41 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM41 self val = liftDOM (self ^. jss "m41" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m41 Mozilla WebKitCSSMatrix.m41 documentation> getM41 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM41 self = liftDOM ((self ^. js "m41") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m42 Mozilla WebKitCSSMatrix.m42 documentation> setM42 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM42 self val = liftDOM (self ^. jss "m42" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m42 Mozilla WebKitCSSMatrix.m42 documentation> getM42 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM42 self = liftDOM ((self ^. js "m42") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m43 Mozilla WebKitCSSMatrix.m43 documentation> setM43 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM43 self val = liftDOM (self ^. jss "m43" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m43 Mozilla WebKitCSSMatrix.m43 documentation> getM43 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM43 self = liftDOM ((self ^. js "m43") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m44 Mozilla WebKitCSSMatrix.m44 documentation> setM44 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m () setM44 self val = liftDOM (self ^. jss "m44" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m44 Mozilla WebKitCSSMatrix.m44 documentation> getM44 :: (MonadDOM m) => WebKitCSSMatrix -> m Double getM44 self = liftDOM ((self ^. js "m44") >>= valToNumber)
ghcjs/jsaddle-dom
src/JSDOM/Generated/WebKitCSSMatrix.hs
mit
18,985
0
12
2,956
4,461
2,343
2,118
236
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2017.M09.D20.Solution where import Control.Monad (void) import Data.ByteString.Lazy.Char8 (ByteString) import qualified Data.ByteString.Lazy.Char8 as BL import Data.Map (Map) import qualified Data.Map as Map import Data.Tuple (swap) import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.ToRow import Database.PostgreSQL.Simple.ToField import Network.HTTP.Conduit -- below imports available via 1HaskellADay git repository import Control.Logic.Frege ((<<-)) import Store.SQL.Connection (connectInfo) import Store.SQL.Util.Inserts (inserter) {-- This week we have been working on encoding and decoding strings to ints and back, using a 'dictionary,' or mapping between to the two to facilitate these translations. Today we're going to take it up a notch. --} import Y2017.M09.D14.Solution {-- The above import was an exercise to store article text, and some metadata about the articles in a PostgreSQL data store. Today, using these articles, we're going to rip and to rend them apart into keywords... --} import Y2017.M09.D15.Solution {-- And then store these keywords into a dictionary AND a keyword-strength store... ON LINE! Ooh! How exciting! Okay, let's get to it. The keyword table in the database is structured thus: --} data Key = Key { keyId :: Int, keyword :: String } deriving (Eq, Ord, Show) -- Given an insert statement for a new keyword is: insertKeyStmt :: Query insertKeyStmt = [sql|INSERT INTO keyword (id, keyword) VALUES (?,?)|] -- Question 1: what is its ToRow instance definition? instance ToRow Key where toRow (Key k v) = [toField k, toField v] {-- Today we're going to be tying together the results of Y2017.M09.D15.Exercise's keyword extraction with the data store, so we also need a keywords-with-their- strengths-per-article table, and this we call article_keyword in the database. It is structured thus: --} data ArticleKeyWord = AKW { artId :: Int, kw :: KeyWord } deriving (Eq, Ord, Show) -- given the insert statement for a keyword for an article is: insertAKWStmt :: Query insertAKWStmt = [sql|INSERT INTO article_keyword (article_id, keyword_id, keyword_count, keyword_strength) VALUES (?,?,?,?)|] -- Question 2: what is ArticleKeyWord's ToRow instance definition? instance ToRow ArticleKeyWord where toRow (AKW art (KW key cnt str)) = let strength = (fromRational str) :: Float in [toField art, toField key, toField cnt, toField strength] -- Question 3: the biggy {-- Let's say the results of the query select id from article where article_id = 'AP900327-0094.txt'; against the data store returns the id = 2 1. populate the keyword table with the dictionary resulting from >>> wordcontext <- kea 0 Map.empty <$> BL.readFile testFile --} insertAllKeys :: Connection -> Dictionary -> IO () insertAllKeys conn = inserter conn insertKeyStmt . map (uncurry Key . swap) . Map.toList -- the above function assumes an empty keyword table -- hint: you may wish to convert the Dictionary value to [Key] {-- >>> connectInfo ConnectInfo {connectHost = "..." ...} >>> conn <- connect it >>> length (dict wordcontext) 91 >>> insertAllKeys conn (dict wordcontext) Now, in the database: select count(1) from keyword; 91 So the insert worked! Let's take a look: select * from keyword LIMIT 5; id keyword --------------- 37 a 25 about 10 after 16 agency 73 am shows the first 5 keywords stored in the database. n.b., they are stored alphabetically. --} -- then 2. insert all the keywords for AP900327-0094.txt into article_keyword insertAllArticleKeyWords :: Connection -> Int -> Map Int KeyWord -> IO () insertAllArticleKeyWords conn artId = inserter conn insertAKWStmt . map (AKW artId) . Map.elems -- hint: you may wish to convert kws to [ArticleKeyWord] {-- >>> length (kws wordcontext) 91 >>> insertAllArticleKeyWords conn 2 (kws wordcontext) then at the database: select * from article_keyword LIMIT 5; id article_id keyword_id keyword_strength keyword_count ----------------------------------------------------------------------------- 1 2 0 0.07913669 11 2 2 1 0.02877698 4 3 2 2 0.007194245 1 4 2 3 0.021582734 3 5 2 4 0.007194245 1 WOOT! >>> close conn --} -- We'll look at reading from these tables tomorrow.
geophf/1HaskellADay
exercises/HAD/Y2017/M09/D20/Solution.hs
mit
4,390
0
11
774
499
296
203
38
1
-- shorter concat [reverse longer] -- http://www.codewars.com/kata/54557d61126a00423b000a45 module ReverseLonger where reverseLonger :: String -> String -> String reverseLonger a b | length a >= length b = b ++ reverse a ++ b | otherwise = a ++ reverse b ++ a
gafiatulin/codewars
src/7 kyu/ReverseLonger.hs
mit
280
0
9
62
76
37
39
4
1
module Core.Passes( passes, printPass, ppIO ) where import Core import Core.Helper import Flags import Pretty import Core.Renamer import Core.Simplify import Core.ReduceLinear import Core.Atomize import Core.Inliner passes :: [Function] -> CompilerM [Function] passes fs = printPass DumpCore fs >>= fixLits >>= rename >>= printPass DumpRename >>= runSimplify >>= printPass DumpSimp >>= put >>= inline >>= printPass DumpInline >>= rename >>= printPass DumpRename >>= runSimplify >>= printPass DumpSimp >>= atomize >>= printPass DumpAtom >>= reduceLinear >>= printPass DumpLin printPass :: Flag -> [Function] -> CompilerM [Function] printPass fl fs = do ifSet fl $ do inIO $ putStrLn $ banner (show fl) inIO $ mapM_ (putStrLn . pp False) fs return fs ppIO :: Pretty p => p -> IO () ppIO p = let s = pp False p in putStrLn s bind :: CompilerM [Function] -> ([Function] -> CompilerM a) -> CompilerM a bind fs func = {-fs >>= (mapM putFunction) >>= return fs >>= func-} fs >>= func put :: [Function] -> CompilerM [Function] put fs = do mapM_ putFunction fs return fs
C-Elegans/linear
Core/Passes.hs
mit
1,224
0
21
336
400
199
201
42
1
import Data.ByteString.Char8 (pack) import Crypto.Hash main = do let input = "vkjiggvb" result = compute input print result type Coord = (Int, Int) type Dir = Char type State = (Coord, [Dir], String) bounds :: Int bounds = 3 start :: Coord start = (0,0) initState :: String -> State initState input = (start, [], input) compute :: String -> String compute input = path where Just (_, path, _) = search [initState input] isGoal :: State -> Bool isGoal (coord, _, _) = coord == (bounds, bounds) nextStates :: State -> [State] nextStates s@(coord, dirs, input) = up ++ down ++ left ++ right where h = take 4 $ getHash (input ++ dirs) up = if open (h !! 0) then moveState 'U' s else [] down = if open (h !! 1) then moveState 'D' s else [] left = if open (h !! 2) then moveState 'L' s else [] right = if open (h !! 3) then moveState 'R' s else [] open :: Char -> Bool open c = c `elem` "bcdef" moveState :: Char -> State -> [State] moveState 'U' ((x, y), dirs, input) | y == 0 = [] | otherwise = [((x, y - 1), dirs ++ ['U'], input)] moveState 'D' ((x, y), dirs, input) | y == bounds = [] | otherwise = [((x, y + 1), dirs ++ ['D'], input)] moveState 'L' ((x, y), dirs, input) | x == 0 = [] | otherwise = [((x - 1, y), dirs ++ ['L'], input)] moveState 'R' ((x, y), dirs, input) | x == bounds = [] | otherwise = [((x + 1, y), dirs ++ ['R'], input)] -- Breadth-first search search :: [State] -> Maybe State search [] = Nothing search (current : rest) | isGoal current = Just current | otherwise = search (rest ++ (nextStates current)) getHash :: String -> String getHash input = show (hash $ pack input :: Digest MD5)
aBhallo/AoC2016
Day 17/day17part1.hs
mit
1,773
0
10
488
858
471
387
49
5
sumOfCorners n = 4*n*n - 6*n + 6 solution = 1 + (sum $ map sumOfCorners [3,5 .. 1001]) main = print solution
drcabana/euler-fp
source/hs/P28.hs
epl-1.0
121
0
9
35
67
35
32
5
1
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, OverloadedStrings #-} module API ( Task , getCurrent , stopTask , description ) where import Data.Maybe import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy as B import qualified Data.ByteString.Lazy.Char8 as BC import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as T import qualified Data.Text.Lazy.Encoding as T import Control.Monad import Control.Lens import GHC.Generics import Network.Wreq import Data.Aeson import Settings data Task = Task { id :: Maybe Int , wid :: Maybe Int , pid :: Maybe Int , guid :: Maybe T.Text , duration :: Maybe Int , billable :: Maybe Bool , duronly :: Maybe Bool , start :: Maybe T.Text , stop :: Maybe T.Text , description :: Maybe T.Text , at :: Maybe T.Text , tags :: Maybe T.Text } deriving (Show, Generic) instance FromJSON Task instance ToJSON Task data Wrap1 = Wrap1 { _data :: Task } deriving (Show, Generic) instance FromJSON Wrap1 where parseJSON (Object v) = Wrap1 <$> v .: "data" parseJSON _ = mzero parseResponse1 :: B.ByteString -> Maybe Task parseResponse1 str = _data <$> wrap where wrap = decode $ str :: Maybe Wrap1 toggl_url :: String toggl_url = "https://www.toggl.com/api/v8/" getOption :: IO Options getOption = do token <- getApiToken return $ defaults & auth ?~ basicAuth (S.pack token) "api_token" getCurrent :: IO (Maybe Task) getCurrent = do opts <- getOption r <- getWith opts $ toggl_url ++ "time_entries/current" return $ parseResponse1 $ r ^. responseBody stopTask :: Task -> IO (Maybe Task) stopTask task = do opts <- getOption r <- putWith opts (toggl_url ++ "time_entries/" ++ (show $ fromJust $ API.id task) ++ "/stop") B.empty return $ parseResponse1 $ r ^. responseBody
termoshtt/toggl-cli
API.hs
gpl-2.0
1,904
0
15
440
582
320
262
60
1
module Main where import Options.Applicative import DarkPlaces.DemoMetadata import DarkPlaces.Text import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC import System.Directory (doesFileExist) import System.Exit import Control.Monad.Error import Text.Printf import Data.Either import Data.Fixed (mod') import Control.Exception (catch) import Network.HTTP.Client import Network.HTTP.Client.TLS (tlsManagerSettings) import Control.Concurrent.Async import Data.String data CommandArgs = CommandArgs { onlyMapname :: Bool, checkUrls :: Bool, colorsOutput :: Bool, filename :: String } deriving(Show, Eq) data ResourceDownload = ResourceDownload { as :: String, for :: String, url :: String } deriving (Show, Eq) data FileMetadata = FileMetadata { mapName :: String, demoTime :: Float, downloads :: [ResourceDownload] } deriving (Show, Eq) type MaybeError = ErrorT String IO argsParser :: Parser CommandArgs argsParser = CommandArgs <$> switch ( long "map" <> short 'm' <> help "Print only map name") <*> switch ( long "urls" <> short 'u' <> help "Check download urls") <*> switch ( long "colors" <> short 'c' <> help "Output colorful text ever if stdout is not terminal device") <*> argument str ( metavar "FILE" <> help "Input demo file") printMessages :: Bool -> MetadataList -> IO () printMessages col metadata = putStrLn "Messages:" >> (mapM_ print $ filter pred metadata) where pred (DemoMessage _ _) = True pred _ = False print (DemoMessage _ m) = printDPText col m print _ = return () openFile :: CommandArgs -> MaybeError BL.ByteString openFile args = do let file = filename args exist <- liftIO $ doesFileExist file if exist then liftIO $ BL.readFile file else throwError $ printf "File \"%s\" does not exists\n" file formatTime :: Float -> String formatTime d | d <= 60 = s_repr | d <= (60 * 60) = printf "%s %s" m_repr s_repr | otherwise = printf "%s %s %s" h_repr m_repr s_repr where s = d `mod'` 60 :: Float m = (truncate $ d / 60) `rem` 60 :: Int h = (truncate $ d / (60 * 60)) `rem` 24 :: Int s_repr = choose "second" "seconds" s m_repr = choose "minute" "minutes" m h_repr = choose "hour" "hours" h choose s1 s2 v | v == 1 = show v ++ " " ++ s1 | otherwise = show v ++ " " ++ s2 checkUrl :: String -> Manager -> IO Bool checkUrl url m = catch urlResponse exceptionHandler where redir_count = 10 headRequest url = do r <- parseUrl url return $ r {method=fromString "HEAD", redirectCount=redir_count} urlResponse = do req <- headRequest url _ <- httpNoBody req m -- get response return True exceptionHandler :: HttpException -> IO Bool exceptionHandler _ = return False formatMetadata :: MetadataList -> CommandArgs -> MaybeError () formatMetadata metadata args = do liftIO $ putStrLn $ printf "Map: %s" $ mapName meta liftIO $ putStrLn $ printf "Time: %s" $ formatTime $ demoTime meta liftIO $ printUrls meta liftIO $ printMessages colorful metadata return () where meta = foldMetadata metadata initState check_urls = checkUrls args colorful = colorsOutput args printUrls = if check_urls then printDownloadsWithCheck colorful else printDownloads initState = FileMetadata "" 0 [] foldMetadata ((MapName m):xs) ms = foldMetadata xs $ ms {mapName=m} foldMetadata ((DemoTime t):xs) ms = foldMetadata xs $ ms {demoTime=t} foldMetadata ((CurlDownload as for url):xs) ms = foldMetadata xs ms' where ms' = ms {downloads=(ResourceDownload (BLC.unpack as) (BLC.unpack for) (BLC.unpack url)): downloads ms} foldMetadata (_:xs) ms = foldMetadata xs ms foldMetadata [] ms = ms {downloads= reverse $ downloads ms} printDownloads meta = mapM_ printDownload $ downloads meta where printDownload d = putStrLn $ printf "Download: %s -- as %s" (url d) (as d) printDownloadsWithCheck col meta = do m <- newManager tlsManagerSettings down <- forM (downloads meta) $ \d -> do aok <- async $ checkUrl (url d) m return (d, aok) forM_ down $ \(d, aok) -> do ok <- wait aok let ok_str = fromString $ if ok then "^2OK" else "^1BROKEN" putStr $ printf "Download: %s -- as %s is " (url d) (as d) printDPText col ok_str >> putStrLn "" processDemo :: CommandArgs -> MaybeError () processDemo args = do file_data <- openFile args if onlyMapname $ args then do let maybe_map = getMapname file_data case maybe_map of (Right (Just m)) -> liftIO $ putStrLn $ printf "Map: %s" m (Right Nothing) -> liftIO $ putStrLn "No map information in demo file" (Left _) -> throwError "Error during parsing file" else do let (errors, metadata) = partitionEithers $ getMetadata file_data if null errors then formatMetadata metadata args else throwError "Error during parsing file" demoInfo :: CommandArgs -> IO () demoInfo args = do r <- runErrorT $ processDemo args case r of Right _ -> exitSuccess Left e -> putStrLn e >> exitFailure main :: IO () main = demoInfo =<< execParser opts where opts = info (helper <*> argsParser) (fullDesc <> progDesc "Get demo file metada")
bacher09/darkplaces-demo
utils/DemoInfo.hs
gpl-2.0
5,616
0
18
1,534
1,819
917
902
146
7
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, PatternGuards #-} {- Copyright (C) 2006-2015 John MacFarlane <jgm@berkeley.edu> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Writers.LaTeX Copyright : Copyright (C) 2006-2015 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <jgm@berkeley.edu> Stability : alpha Portability : portable Conversion of 'Pandoc' format into LaTeX. -} module Text.Pandoc.Writers.LaTeX ( writeLaTeX ) where import Text.Pandoc.Definition import Text.Pandoc.Walk import Text.Pandoc.Shared import Text.Pandoc.Writers.Shared import Text.Pandoc.Options import Text.Pandoc.Templates import Text.Printf ( printf ) import Network.URI ( isURI, unEscapeString ) import Data.Aeson (object, (.=), FromJSON) import Data.List ( (\\), isInfixOf, stripPrefix, intercalate, intersperse, nub, nubBy ) import Data.Char ( toLower, isPunctuation, isAscii, isLetter, isDigit, ord ) import Data.Maybe ( fromMaybe, isJust, catMaybes ) import qualified Data.Text as T import Control.Applicative ((<|>)) import Control.Monad.State import qualified Text.Parsec as P import Text.Pandoc.Pretty import Text.Pandoc.ImageSize import Text.Pandoc.Slides import Text.Pandoc.Highlighting (highlight, styleToLaTeX, formatLaTeXInline, formatLaTeXBlock, toListingsLanguage) data WriterState = WriterState { stInNote :: Bool -- true if we're in a note , stInQuote :: Bool -- true if in a blockquote , stInMinipage :: Bool -- true if in minipage , stInHeading :: Bool -- true if in a section heading , stNotes :: [Doc] -- notes in a minipage , stOLLevel :: Int -- level of ordered list nesting , stOptions :: WriterOptions -- writer options, so they don't have to be parameter , stVerbInNote :: Bool -- true if document has verbatim text in note , stTable :: Bool -- true if document has a table , stStrikeout :: Bool -- true if document has strikeout , stUrl :: Bool -- true if document has visible URL link , stGraphics :: Bool -- true if document contains images , stLHS :: Bool -- true if document has literate haskell code , stBook :: Bool -- true if document uses book or memoir class , stCsquotes :: Bool -- true if document uses csquotes , stHighlighting :: Bool -- true if document has highlighted code , stIncremental :: Bool -- true if beamer lists should be displayed bit by bit , stInternalLinks :: [String] -- list of internal link targets , stUsesEuro :: Bool -- true if euro symbol used } -- | Convert Pandoc to LaTeX. writeLaTeX :: WriterOptions -> Pandoc -> String writeLaTeX options document = evalState (pandocToLaTeX options document) $ WriterState { stInNote = False, stInQuote = False, stInMinipage = False, stInHeading = False, stNotes = [], stOLLevel = 1, stOptions = options, stVerbInNote = False, stTable = False, stStrikeout = False, stUrl = False, stGraphics = False, stLHS = False, stBook = writerChapters options, stCsquotes = False, stHighlighting = False, stIncremental = writerIncremental options, stInternalLinks = [], stUsesEuro = False } pandocToLaTeX :: WriterOptions -> Pandoc -> State WriterState String pandocToLaTeX options (Pandoc meta blocks) = do -- Strip off final 'references' header if --natbib or --biblatex let method = writerCiteMethod options let blocks' = if method == Biblatex || method == Natbib then case reverse blocks of (Div (_,["references"],_) _):xs -> reverse xs _ -> blocks else blocks -- see if there are internal links let isInternalLink (Link _ _ ('#':xs,_)) = [xs] isInternalLink _ = [] modify $ \s -> s{ stInternalLinks = query isInternalLink blocks' } let template = writerTemplate options -- set stBook depending on documentclass let colwidth = if writerWrapText options == WrapAuto then Just $ writerColumns options else Nothing metadata <- metaToJSON options (fmap (render colwidth) . blockListToLaTeX) (fmap (render colwidth) . inlineListToLaTeX) meta let bookClasses = ["memoir","book","report","scrreprt","scrbook"] let documentClass = case P.parse pDocumentClass "template" template of Right r -> r Left _ -> "" case lookup "documentclass" (writerVariables options) `mplus` fmap stringify (lookupMeta "documentclass" meta) of Just x | x `elem` bookClasses -> modify $ \s -> s{stBook = True} | otherwise -> return () Nothing | documentClass `elem` bookClasses -> modify $ \s -> s{stBook = True} | otherwise -> return () -- check for \usepackage...{csquotes}; if present, we'll use -- \enquote{...} for smart quotes: let headerIncludesField :: FromJSON a => Maybe a headerIncludesField = getField "header-includes" metadata let headerIncludes = fromMaybe [] $ mplus (fmap return headerIncludesField) headerIncludesField when (any (isInfixOf "{csquotes}") (template : headerIncludes)) $ modify $ \s -> s{stCsquotes = True} let (blocks'', lastHeader) = if writerCiteMethod options == Citeproc then (blocks', []) else case last blocks' of Header 1 _ il -> (init blocks', il) _ -> (blocks', []) blocks''' <- if writerBeamer options then toSlides blocks'' else return blocks'' body <- mapM (elementToLaTeX options) $ hierarchicalize blocks''' (biblioTitle :: String) <- liftM (render colwidth) $ inlineListToLaTeX lastHeader let main = render colwidth $ vsep body st <- get titleMeta <- stringToLaTeX TextString $ stringify $ docTitle meta authorsMeta <- mapM (stringToLaTeX TextString . stringify) $ docAuthors meta let docLangs = nub $ query (extract "lang") blocks let hasStringValue x = isJust (getField x metadata :: Maybe String) let geometryFromMargins = intercalate [','] $ catMaybes $ map (\(x,y) -> ((x ++ "=") ++) <$> getField y metadata) [("lmargin","margin-left") ,("rmargin","margin-right") ,("tmargin","margin-top") ,("bmargin","margin-bottom") ] let context = defField "toc" (writerTableOfContents options) $ defField "toc-depth" (show (writerTOCDepth options - if stBook st then 1 else 0)) $ defField "body" main $ defField "title-meta" titleMeta $ defField "author-meta" (intercalate "; " authorsMeta) $ defField "documentclass" (if writerBeamer options then ("beamer" :: String) else if stBook st then "book" else "article") $ defField "verbatim-in-note" (stVerbInNote st) $ defField "tables" (stTable st) $ defField "strikeout" (stStrikeout st) $ defField "url" (stUrl st) $ defField "numbersections" (writerNumberSections options) $ defField "lhs" (stLHS st) $ defField "graphics" (stGraphics st) $ defField "book-class" (stBook st) $ defField "euro" (stUsesEuro st) $ defField "listings" (writerListings options || stLHS st) $ defField "beamer" (writerBeamer options) $ (if stHighlighting st then defField "highlighting-macros" (styleToLaTeX $ writerHighlightStyle options ) else id) $ (case writerCiteMethod options of Natbib -> defField "biblio-title" biblioTitle . defField "natbib" True Biblatex -> defField "biblio-title" biblioTitle . defField "biblatex" True _ -> id) $ -- set lang to something so polyglossia/babel is included defField "lang" (if null docLangs then ""::String else "en") $ defField "otherlangs" docLangs $ defField "colorlinks" (any hasStringValue ["citecolor", "urlcolor", "linkcolor", "toccolor"]) $ defField "dir" (if (null $ query (extract "dir") blocks) then ""::String else "ltr") $ defField "section-titles" True $ defField "geometry" geometryFromMargins $ metadata let toPolyObj lang = object [ "name" .= T.pack name , "options" .= T.pack opts ] where (name, opts) = toPolyglossia lang let lang = maybe [] (splitBy (=='-')) $ getField "lang" context otherlangs = maybe [] (map $ splitBy (=='-')) $ getField "otherlangs" context let context' = defField "babel-lang" (toBabel lang) $ defField "babel-otherlangs" (map toBabel otherlangs) $ defField "babel-newcommands" (concatMap (\(poly, babel) -> -- \textspanish and \textgalician are already used by babel -- save them as \oritext... and let babel use that if poly `elem` ["spanish", "galician"] then "\\let\\oritext" ++ poly ++ "\\text" ++ poly ++ "\n" ++ "\\AddBabelHook{" ++ poly ++ "}{beforeextras}" ++ "{\\renewcommand{\\text" ++ poly ++ "}{\\oritext" ++ poly ++ "}}\n" ++ "\\AddBabelHook{" ++ poly ++ "}{afterextras}" ++ "{\\renewcommand{\\text" ++ poly ++ "}[2][]{\\foreignlanguage{" ++ poly ++ "}{##2}}}\n" else "\\newcommand{\\text" ++ poly ++ "}[2][]{\\foreignlanguage{" ++ babel ++ "}{#2}}\n" ++ "\\newenvironment{" ++ poly ++ "}[1]{\\begin{otherlanguage}{" ++ babel ++ "}}{\\end{otherlanguage}}\n" ) -- eliminate duplicates that have same polyglossia name $ nubBy (\a b -> fst a == fst b) -- find polyglossia and babel names of languages used in the document $ map (\l -> let lng = splitBy (=='-') l in (fst $ toPolyglossia lng, toBabel lng) ) docLangs ) $ defField "polyglossia-lang" (toPolyObj lang) $ defField "polyglossia-otherlangs" (map toPolyObj otherlangs) $ defField "latex-dir-rtl" (case (getField "dir" context)::Maybe String of Just "rtl" -> True _ -> False) $ context return $ if writerStandalone options then renderTemplate' template context' else main -- | Convert Elements to LaTeX elementToLaTeX :: WriterOptions -> Element -> State WriterState Doc elementToLaTeX _ (Blk block) = blockToLaTeX block elementToLaTeX opts (Sec level _ (id',classes,_) title' elements) = do modify $ \s -> s{stInHeading = True} header' <- sectionHeader ("unnumbered" `elem` classes) id' level title' modify $ \s -> s{stInHeading = False} innerContents <- mapM (elementToLaTeX opts) elements return $ vsep (header' : innerContents) data StringContext = TextString | URLString | CodeString deriving (Eq) -- escape things as needed for LaTeX stringToLaTeX :: StringContext -> String -> State WriterState String stringToLaTeX _ [] = return "" stringToLaTeX ctx (x:xs) = do opts <- gets stOptions rest <- stringToLaTeX ctx xs let ligatures = writerTeXLigatures opts && ctx == TextString let isUrl = ctx == URLString when (x == '€') $ modify $ \st -> st{ stUsesEuro = True } return $ case x of '€' -> "\\euro{}" ++ rest '{' -> "\\{" ++ rest '}' -> "\\}" ++ rest '$' | not isUrl -> "\\$" ++ rest '%' -> "\\%" ++ rest '&' -> "\\&" ++ rest '_' | not isUrl -> "\\_" ++ rest '#' -> "\\#" ++ rest '-' | not isUrl -> case xs of -- prevent adjacent hyphens from forming ligatures ('-':_) -> "-\\/" ++ rest _ -> '-' : rest '~' | not isUrl -> "\\textasciitilde{}" ++ rest '^' -> "\\^{}" ++ rest '\\'| isUrl -> '/' : rest -- NB. / works as path sep even on Windows | otherwise -> "\\textbackslash{}" ++ rest '|' | not isUrl -> "\\textbar{}" ++ rest '<' -> "\\textless{}" ++ rest '>' -> "\\textgreater{}" ++ rest '[' -> "{[}" ++ rest -- to avoid interpretation as ']' -> "{]}" ++ rest -- optional arguments '\'' | ctx == CodeString -> "\\textquotesingle{}" ++ rest '\160' -> "~" ++ rest '\x2026' -> "\\ldots{}" ++ rest '\x2018' | ligatures -> "`" ++ rest '\x2019' | ligatures -> "'" ++ rest '\x201C' | ligatures -> "``" ++ rest '\x201D' | ligatures -> "''" ++ rest '\x2014' | ligatures -> "---" ++ rest '\x2013' | ligatures -> "--" ++ rest _ -> x : rest toLabel :: String -> State WriterState String toLabel z = go `fmap` stringToLaTeX URLString z where go [] = "" go (x:xs) | (isLetter x || isDigit x) && isAscii x = x:go xs | elem x ("-+=:;." :: String) = x:go xs | otherwise = "ux" ++ printf "%x" (ord x) ++ go xs -- | Puts contents into LaTeX command. inCmd :: String -> Doc -> Doc inCmd cmd contents = char '\\' <> text cmd <> braces contents toSlides :: [Block] -> State WriterState [Block] toSlides bs = do opts <- gets stOptions let slideLevel = fromMaybe (getSlideLevel bs) $ writerSlideLevel opts let bs' = prepSlides slideLevel bs concat `fmap` (mapM (elementToBeamer slideLevel) $ hierarchicalize bs') elementToBeamer :: Int -> Element -> State WriterState [Block] elementToBeamer _slideLevel (Blk b) = return [b] elementToBeamer slideLevel (Sec lvl _num (ident,classes,kvs) tit elts) | lvl > slideLevel = do bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts return $ Para ( RawInline "latex" "\\begin{block}{" : tit ++ [RawInline "latex" "}"] ) : bs ++ [RawBlock "latex" "\\end{block}"] | lvl < slideLevel = do bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts return $ (Header lvl (ident,classes,kvs) tit) : bs | otherwise = do -- lvl == slideLevel -- note: [fragile] is required or verbatim breaks let hasCodeBlock (CodeBlock _ _) = [True] hasCodeBlock _ = [] let hasCode (Code _ _) = [True] hasCode _ = [] let fragile = "fragile" `elem` classes || not (null $ query hasCodeBlock elts ++ query hasCode elts) let frameoptions = ["allowdisplaybreaks", "allowframebreaks", "b", "c", "t", "environment", "label", "plain", "shrink"] let optionslist = ["fragile" | fragile] ++ [k | k <- classes, k `elem` frameoptions] ++ [k ++ "=" ++ v | (k,v) <- kvs, k `elem` frameoptions] let options = if null optionslist then "" else "[" ++ intercalate "," optionslist ++ "]" let slideStart = Para $ RawInline "latex" ("\\begin{frame}" ++ options) : if tit == [Str "\0"] -- marker for hrule then [] else (RawInline "latex" "{") : tit ++ [RawInline "latex" "}"] let slideEnd = RawBlock "latex" "\\end{frame}" -- now carve up slide into blocks if there are sections inside bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts return $ slideStart : bs ++ [slideEnd] isListBlock :: Block -> Bool isListBlock (BulletList _) = True isListBlock (OrderedList _ _) = True isListBlock (DefinitionList _) = True isListBlock _ = False isLineBreakOrSpace :: Inline -> Bool isLineBreakOrSpace LineBreak = True isLineBreakOrSpace SoftBreak = True isLineBreakOrSpace Space = True isLineBreakOrSpace _ = False -- | Convert Pandoc block element to LaTeX. blockToLaTeX :: Block -- ^ Block to convert -> State WriterState Doc blockToLaTeX Null = return empty blockToLaTeX (Div (identifier,classes,kvs) bs) = do beamer <- writerBeamer `fmap` gets stOptions ref <- toLabel identifier let linkAnchor = if null identifier then empty else "\\hypertarget" <> braces (text ref) <> braces empty let align dir txt = inCmd "begin" dir $$ txt $$ inCmd "end" dir let wrapDir = case lookup "dir" kvs of Just "rtl" -> align "RTL" Just "ltr" -> align "LTR" _ -> id wrapLang txt = case lookup "lang" kvs of Just lng -> let (l, o) = toPolyglossiaEnv lng ops = if null o then "" else brackets $ text o in inCmd "begin" (text l) <> ops $$ blankline <> txt <> blankline $$ inCmd "end" (text l) Nothing -> txt wrapNotes txt = if beamer && "notes" `elem` classes then "\\note" <> braces txt -- speaker notes else linkAnchor $$ txt fmap (wrapDir . wrapLang . wrapNotes) $ blockListToLaTeX bs blockToLaTeX (Plain lst) = inlineListToLaTeX $ dropWhile isLineBreakOrSpace lst -- title beginning with fig: indicates that the image is a figure blockToLaTeX (Para [Image attr@(ident, _, _) txt (src,'f':'i':'g':':':tit)]) = do inNote <- gets stInNote modify $ \st -> st{ stInMinipage = True, stNotes = [] } capt <- inlineListToLaTeX txt notes <- gets stNotes modify $ \st -> st{ stInMinipage = False, stNotes = [] } -- We can't have footnotes in the list of figures, so remove them: captForLof <- if null notes then return empty else brackets <$> inlineListToLaTeX (walk deNote txt) img <- inlineToLaTeX (Image attr txt (src,tit)) let footnotes = notesToLaTeX notes lab <- labelFor ident let caption = "\\caption" <> captForLof <> braces capt <> lab figure <- hypertarget ident (cr <> "\\begin{figure}[htbp]" $$ "\\centering" $$ img $$ caption $$ "\\end{figure}" <> cr) return $ if inNote -- can't have figures in notes then "\\begin{center}" $$ img $+$ capt $$ "\\end{center}" else figure $$ footnotes -- . . . indicates pause in beamer slides blockToLaTeX (Para [Str ".",Space,Str ".",Space,Str "."]) = do beamer <- writerBeamer `fmap` gets stOptions if beamer then blockToLaTeX (RawBlock "latex" "\\pause") else inlineListToLaTeX [Str ".",Space,Str ".",Space,Str "."] blockToLaTeX (Para lst) = inlineListToLaTeX $ dropWhile isLineBreakOrSpace lst blockToLaTeX (BlockQuote lst) = do beamer <- writerBeamer `fmap` gets stOptions case lst of [b] | beamer && isListBlock b -> do oldIncremental <- gets stIncremental modify $ \s -> s{ stIncremental = not oldIncremental } result <- blockToLaTeX b modify $ \s -> s{ stIncremental = oldIncremental } return result _ -> do oldInQuote <- gets stInQuote modify (\s -> s{stInQuote = True}) contents <- blockListToLaTeX lst modify (\s -> s{stInQuote = oldInQuote}) return $ "\\begin{quote}" $$ contents $$ "\\end{quote}" blockToLaTeX (CodeBlock (identifier,classes,keyvalAttr) str) = do opts <- gets stOptions ref <- toLabel identifier let linkAnchor = if null identifier then empty else "\\hypertarget" <> braces (text ref) <> braces ("\\label" <> braces (text ref)) let lhsCodeBlock = do modify $ \s -> s{ stLHS = True } return $ flush (linkAnchor $$ "\\begin{code}" $$ text str $$ "\\end{code}") $$ cr let rawCodeBlock = do st <- get env <- if stInNote st then modify (\s -> s{ stVerbInNote = True }) >> return "Verbatim" else return "verbatim" return $ flush (linkAnchor $$ text ("\\begin{" ++ env ++ "}") $$ text str $$ text ("\\end{" ++ env ++ "}")) <> cr let listingsCodeBlock = do st <- get let params = if writerListings (stOptions st) then (case getListingsLanguage classes of Just l -> [ "language=" ++ l ] Nothing -> []) ++ [ "numbers=left" | "numberLines" `elem` classes || "number" `elem` classes || "number-lines" `elem` classes ] ++ [ (if key == "startFrom" then "firstnumber" else key) ++ "=" ++ attr | (key,attr) <- keyvalAttr ] ++ (if identifier == "" then [] else [ "label=" ++ ref ]) else [] printParams | null params = empty | otherwise = brackets $ hcat (intersperse ", " (map text params)) return $ flush ("\\begin{lstlisting}" <> printParams $$ text str $$ "\\end{lstlisting}") $$ cr let highlightedCodeBlock = case highlight formatLaTeXBlock ("",classes,keyvalAttr) str of Nothing -> rawCodeBlock Just h -> modify (\st -> st{ stHighlighting = True }) >> return (flush $ linkAnchor $$ text h) case () of _ | isEnabled Ext_literate_haskell opts && "haskell" `elem` classes && "literate" `elem` classes -> lhsCodeBlock | writerListings opts -> listingsCodeBlock | writerHighlight opts && not (null classes) -> highlightedCodeBlock | otherwise -> rawCodeBlock blockToLaTeX (RawBlock f x) | f == Format "latex" || f == Format "tex" = return $ text x | otherwise = return empty blockToLaTeX (BulletList []) = return empty -- otherwise latex error blockToLaTeX (BulletList lst) = do incremental <- gets stIncremental let inc = if incremental then "[<+->]" else "" items <- mapM listItemToLaTeX lst let spacing = if isTightList lst then text "\\tightlist" else empty return $ text ("\\begin{itemize}" ++ inc) $$ spacing $$ vcat items $$ "\\end{itemize}" blockToLaTeX (OrderedList _ []) = return empty -- otherwise latex error blockToLaTeX (OrderedList (start, numstyle, numdelim) lst) = do st <- get let inc = if stIncremental st then "[<+->]" else "" let oldlevel = stOLLevel st put $ st {stOLLevel = oldlevel + 1} items <- mapM listItemToLaTeX lst modify (\s -> s {stOLLevel = oldlevel}) let tostyle x = case numstyle of Decimal -> "\\arabic" <> braces x UpperRoman -> "\\Roman" <> braces x LowerRoman -> "\\roman" <> braces x UpperAlpha -> "\\Alph" <> braces x LowerAlpha -> "\\alph" <> braces x Example -> "\\arabic" <> braces x DefaultStyle -> "\\arabic" <> braces x let todelim x = case numdelim of OneParen -> x <> ")" TwoParens -> parens x Period -> x <> "." _ -> x <> "." let enum = text $ "enum" ++ map toLower (toRomanNumeral oldlevel) let stylecommand = if numstyle == DefaultStyle && numdelim == DefaultDelim then empty else "\\def" <> "\\label" <> enum <> braces (todelim $ tostyle enum) let resetcounter = if start == 1 || oldlevel > 4 then empty else "\\setcounter" <> braces enum <> braces (text $ show $ start - 1) let spacing = if isTightList lst then text "\\tightlist" else empty return $ text ("\\begin{enumerate}" ++ inc) $$ stylecommand $$ resetcounter $$ spacing $$ vcat items $$ "\\end{enumerate}" blockToLaTeX (DefinitionList []) = return empty blockToLaTeX (DefinitionList lst) = do incremental <- gets stIncremental let inc = if incremental then "[<+->]" else "" items <- mapM defListItemToLaTeX lst let spacing = if all isTightList (map snd lst) then text "\\tightlist" else empty return $ text ("\\begin{description}" ++ inc) $$ spacing $$ vcat items $$ "\\end{description}" blockToLaTeX HorizontalRule = return $ "\\begin{center}\\rule{0.5\\linewidth}{\\linethickness}\\end{center}" blockToLaTeX (Header level (id',classes,_) lst) = do modify $ \s -> s{stInHeading = True} hdr <- sectionHeader ("unnumbered" `elem` classes) id' level lst modify $ \s -> s{stInHeading = False} return hdr blockToLaTeX (Table caption aligns widths heads rows) = do headers <- if all null heads then return empty else do contents <- (tableRowToLaTeX True aligns widths) heads return ("\\toprule" $$ contents $$ "\\midrule") let endhead = if all null heads then empty else text "\\endhead" let endfirsthead = if all null heads then empty else text "\\endfirsthead" captionText <- inlineListToLaTeX caption let capt = if isEmpty captionText then empty else text "\\caption" <> braces captionText <> "\\tabularnewline" $$ headers $$ endfirsthead rows' <- mapM (tableRowToLaTeX False aligns widths) rows let colDescriptors = text $ concat $ map toColDescriptor aligns modify $ \s -> s{ stTable = True } return $ "\\begin{longtable}[]" <> braces ("@{}" <> colDescriptors <> "@{}") -- the @{} removes extra space at beginning and end $$ capt $$ (if all null heads then "\\toprule" else empty) $$ headers $$ endhead $$ vcat rows' $$ "\\bottomrule" $$ "\\end{longtable}" toColDescriptor :: Alignment -> String toColDescriptor align = case align of AlignLeft -> "l" AlignRight -> "r" AlignCenter -> "c" AlignDefault -> "l" blockListToLaTeX :: [Block] -> State WriterState Doc blockListToLaTeX lst = vsep `fmap` mapM blockToLaTeX lst tableRowToLaTeX :: Bool -> [Alignment] -> [Double] -> [[Block]] -> State WriterState Doc tableRowToLaTeX header aligns widths cols = do -- scale factor compensates for extra space between columns -- so the whole table isn't larger than columnwidth let scaleFactor = 0.97 ** fromIntegral (length aligns) let widths' = map (scaleFactor *) widths cells <- mapM (tableCellToLaTeX header) $ zip3 widths' aligns cols return $ hsep (intersperse "&" cells) <> "\\tabularnewline" -- For simple latex tables (without minipages or parboxes), -- we need to go to some lengths to get line breaks working: -- as LineBreak bs = \vtop{\hbox{\strut as}\hbox{\strut bs}}. fixLineBreaks :: Block -> Block fixLineBreaks (Para ils) = Para $ fixLineBreaks' ils fixLineBreaks (Plain ils) = Plain $ fixLineBreaks' ils fixLineBreaks x = x fixLineBreaks' :: [Inline] -> [Inline] fixLineBreaks' ils = case splitBy (== LineBreak) ils of [] -> [] [xs] -> xs chunks -> RawInline "tex" "\\vtop{" : concatMap tohbox chunks ++ [RawInline "tex" "}"] where tohbox ys = RawInline "tex" "\\hbox{\\strut " : ys ++ [RawInline "tex" "}"] -- We also change display math to inline math, since display -- math breaks in simple tables. displayMathToInline :: Inline -> Inline displayMathToInline (Math DisplayMath x) = Math InlineMath x displayMathToInline x = x tableCellToLaTeX :: Bool -> (Double, Alignment, [Block]) -> State WriterState Doc tableCellToLaTeX _ (0, _, blocks) = blockListToLaTeX $ walk fixLineBreaks $ walk displayMathToInline blocks tableCellToLaTeX header (width, align, blocks) = do modify $ \st -> st{ stInMinipage = True, stNotes = [] } cellContents <- blockListToLaTeX blocks notes <- gets stNotes modify $ \st -> st{ stInMinipage = False, stNotes = [] } let valign = text $ if header then "[b]" else "[t]" let halign = case align of AlignLeft -> "\\raggedright" AlignRight -> "\\raggedleft" AlignCenter -> "\\centering" AlignDefault -> "\\raggedright" return $ ("\\begin{minipage}" <> valign <> braces (text (printf "%.2f\\columnwidth" width)) <> (halign <> "\\strut" <> cr <> cellContents <> cr) <> "\\strut\\end{minipage}") $$ notesToLaTeX notes notesToLaTeX :: [Doc] -> Doc notesToLaTeX [] = empty notesToLaTeX ns = (case length ns of n | n > 1 -> "\\addtocounter" <> braces "footnote" <> braces (text $ show $ 1 - n) | otherwise -> empty) $$ vcat (intersperse ("\\addtocounter" <> braces "footnote" <> braces "1") $ map (\x -> "\\footnotetext" <> braces x) $ reverse ns) listItemToLaTeX :: [Block] -> State WriterState Doc listItemToLaTeX lst -- we need to put some text before a header if it's the first -- element in an item. This will look ugly in LaTeX regardless, but -- this will keep the typesetter from throwing an error. | ((Header _ _ _) :_) <- lst = blockListToLaTeX lst >>= return . (text "\\item ~" $$) . (nest 2) | otherwise = blockListToLaTeX lst >>= return . (text "\\item" $$) . (nest 2) defListItemToLaTeX :: ([Inline], [[Block]]) -> State WriterState Doc defListItemToLaTeX (term, defs) = do term' <- inlineListToLaTeX term -- put braces around term if it contains an internal link, -- since otherwise we get bad bracket interactions: \item[\hyperref[..] let isInternalLink (Link _ _ ('#':_,_)) = True isInternalLink _ = False let term'' = if any isInternalLink term then braces term' else term' def' <- liftM vsep $ mapM blockListToLaTeX defs return $ case defs of (((Header _ _ _) : _) : _) -> "\\item" <> brackets term'' <> " ~ " $$ def' _ -> "\\item" <> brackets term'' $$ def' -- | Craft the section header, inserting the secton reference, if supplied. sectionHeader :: Bool -- True for unnumbered -> [Char] -> Int -> [Inline] -> State WriterState Doc sectionHeader unnumbered ident level lst = do txt <- inlineListToLaTeX lst plain <- stringToLaTeX TextString $ foldl (++) "" $ map stringify lst let noNote (Note _) = Str "" noNote x = x let lstNoNotes = walk noNote lst txtNoNotes <- inlineListToLaTeX lstNoNotes let star = if unnumbered then text "*" else empty -- footnotes in sections don't work (except for starred variants) -- unless you specify an optional argument: -- \section[mysec]{mysec\footnote{blah}} optional <- if unnumbered || lstNoNotes == lst then return empty else do return $ brackets txtNoNotes let contents = if render Nothing txt == plain then braces txt else braces (text "\\texorpdfstring" <> braces txt <> braces (text plain)) let stuffing = star <> optional <> contents book <- gets stBook opts <- gets stOptions let level' = if book || writerChapters opts then level - 1 else level let sectionType = case level' of 0 | writerBeamer opts -> "part" | otherwise -> "chapter" 1 -> "section" 2 -> "subsection" 3 -> "subsubsection" 4 -> "paragraph" 5 -> "subparagraph" _ -> "" inQuote <- gets stInQuote let prefix = if inQuote && level' >= 4 then text "\\mbox{}%" -- needed for \paragraph, \subparagraph in quote environment -- see http://tex.stackexchange.com/questions/169830/ else empty lab <- labelFor ident stuffing' <- hypertarget ident $ text ('\\':sectionType) <> stuffing <> lab return $ if level' > 5 then txt else prefix $$ stuffing' $$ if unnumbered then "\\addcontentsline{toc}" <> braces (text sectionType) <> braces txtNoNotes else empty hypertarget :: String -> Doc -> State WriterState Doc hypertarget ident x = do ref <- text `fmap` toLabel ident internalLinks <- gets stInternalLinks return $ if ident `elem` internalLinks then text "\\hypertarget" <> braces ref <> braces x else x labelFor :: String -> State WriterState Doc labelFor "" = return empty labelFor ident = do ref <- text `fmap` toLabel ident return $ text "\\label" <> braces ref -- | Convert list of inline elements to LaTeX. inlineListToLaTeX :: [Inline] -- ^ Inlines to convert -> State WriterState Doc inlineListToLaTeX lst = mapM inlineToLaTeX (fixBreaks $ fixLineInitialSpaces lst) >>= return . hcat -- nonbreaking spaces (~) in LaTeX don't work after line breaks, -- so we turn nbsps after hard breaks to \hspace commands. -- this is mostly used in verse. where fixLineInitialSpaces [] = [] fixLineInitialSpaces (LineBreak : Str s@('\160':_) : xs) = LineBreak : fixNbsps s ++ fixLineInitialSpaces xs fixLineInitialSpaces (x:xs) = x : fixLineInitialSpaces xs fixNbsps s = let (ys,zs) = span (=='\160') s in replicate (length ys) hspace ++ [Str zs] hspace = RawInline "latex" "\\hspace*{0.333em}" -- linebreaks after blank lines cause problems: fixBreaks [] = [] fixBreaks ys@(LineBreak : LineBreak : _) = case span (== LineBreak) ys of (lbs, rest) -> RawInline "latex" ("\\\\[" ++ show (length lbs) ++ "\\baselineskip]") : fixBreaks rest fixBreaks (y:ys) = y : fixBreaks ys isQuoted :: Inline -> Bool isQuoted (Quoted _ _) = True isQuoted _ = False -- | Convert inline element to LaTeX inlineToLaTeX :: Inline -- ^ Inline to convert -> State WriterState Doc inlineToLaTeX (Span (id',classes,kvs) ils) = do ref <- toLabel id' let linkAnchor = if null id' then empty else "\\protect\\hypertarget" <> braces (text ref) <> braces empty let cmds = ["textup" | "csl-no-emph" `elem` classes] ++ ["textnormal" | "csl-no-strong" `elem` classes || "csl-no-smallcaps" `elem` classes] ++ ["RL" | ("dir", "rtl") `elem` kvs] ++ ["LR" | ("dir", "ltr") `elem` kvs] ++ (case lookup "lang" kvs of Just lng -> let (l, o) = toPolyglossia $ splitBy (=='-') lng ops = if null o then "" else ("[" ++ o ++ "]") in ["text" ++ l ++ ops] Nothing -> []) contents <- inlineListToLaTeX ils return $ linkAnchor <> if null cmds then braces contents else foldr inCmd contents cmds inlineToLaTeX (Emph lst) = inlineListToLaTeX lst >>= return . inCmd "emph" inlineToLaTeX (Strong lst) = inlineListToLaTeX lst >>= return . inCmd "textbf" inlineToLaTeX (Strikeout lst) = do -- we need to protect VERB in an mbox or we get an error -- see #1294 contents <- inlineListToLaTeX $ protectCode lst modify $ \s -> s{ stStrikeout = True } return $ inCmd "sout" contents inlineToLaTeX (Superscript lst) = inlineListToLaTeX lst >>= return . inCmd "textsuperscript" inlineToLaTeX (Subscript lst) = do inlineListToLaTeX lst >>= return . inCmd "textsubscript" inlineToLaTeX (SmallCaps lst) = inlineListToLaTeX lst >>= return . inCmd "textsc" inlineToLaTeX (Cite cits lst) = do st <- get let opts = stOptions st case writerCiteMethod opts of Natbib -> citationsToNatbib cits Biblatex -> citationsToBiblatex cits _ -> inlineListToLaTeX lst inlineToLaTeX (Code (_,classes,_) str) = do opts <- gets stOptions inHeading <- gets stInHeading case () of _ | writerListings opts && not inHeading -> listingsCode | writerHighlight opts && not (null classes) -> highlightCode | otherwise -> rawCode where listingsCode = do inNote <- gets stInNote when inNote $ modify $ \s -> s{ stVerbInNote = True } let chr = case "!\"&'()*,-./:;?@_" \\ str of (c:_) -> c [] -> '!' return $ text $ "\\lstinline" ++ [chr] ++ str ++ [chr] highlightCode = do case highlight formatLaTeXInline ("",classes,[]) str of Nothing -> rawCode Just h -> modify (\st -> st{ stHighlighting = True }) >> return (text h) rawCode = liftM (text . (\s -> "\\texttt{" ++ escapeSpaces s ++ "}")) $ stringToLaTeX CodeString str where escapeSpaces = concatMap (\c -> if c == ' ' then "\\ " else [c]) inlineToLaTeX (Quoted qt lst) = do contents <- inlineListToLaTeX lst csquotes <- liftM stCsquotes get opts <- gets stOptions if csquotes then return $ "\\enquote" <> braces contents else do let s1 = if (not (null lst)) && (isQuoted (head lst)) then "\\," else empty let s2 = if (not (null lst)) && (isQuoted (last lst)) then "\\," else empty let inner = s1 <> contents <> s2 return $ case qt of DoubleQuote -> if writerTeXLigatures opts then text "``" <> inner <> text "''" else char '\x201C' <> inner <> char '\x201D' SingleQuote -> if writerTeXLigatures opts then char '`' <> inner <> char '\'' else char '\x2018' <> inner <> char '\x2019' inlineToLaTeX (Str str) = liftM text $ stringToLaTeX TextString str inlineToLaTeX (Math InlineMath str) = return $ "\\(" <> text str <> "\\)" inlineToLaTeX (Math DisplayMath str) = return $ "\\[" <> text str <> "\\]" inlineToLaTeX (RawInline f str) | f == Format "latex" || f == Format "tex" = return $ text str | otherwise = return empty inlineToLaTeX (LineBreak) = return $ "\\\\" <> cr inlineToLaTeX SoftBreak = do wrapText <- gets (writerWrapText . stOptions) case wrapText of WrapAuto -> return space WrapNone -> return space WrapPreserve -> return cr inlineToLaTeX Space = return space inlineToLaTeX (Link _ txt ('#':ident, _)) = do contents <- inlineListToLaTeX txt lab <- toLabel ident return $ text "\\protect\\hyperlink" <> braces (text lab) <> braces contents inlineToLaTeX (Link _ txt (src, _)) = case txt of [Str x] | escapeURI x == src -> -- autolink do modify $ \s -> s{ stUrl = True } src' <- stringToLaTeX URLString (escapeURI src) return $ text $ "\\url{" ++ src' ++ "}" [Str x] | Just rest <- stripPrefix "mailto:" src, escapeURI x == rest -> -- email autolink do modify $ \s -> s{ stUrl = True } src' <- stringToLaTeX URLString (escapeURI src) contents <- inlineListToLaTeX txt return $ "\\href" <> braces (text src') <> braces ("\\nolinkurl" <> braces contents) _ -> do contents <- inlineListToLaTeX txt src' <- stringToLaTeX URLString (escapeURI src) return $ text ("\\href{" ++ src' ++ "}{") <> contents <> char '}' inlineToLaTeX (Image attr _ (source, _)) = do modify $ \s -> s{ stGraphics = True } opts <- gets stOptions let showDim dir = let d = text (show dir) <> "=" in case (dimension dir attr) of Just (Pixel a) -> [d <> text (showInInch opts (Pixel a)) <> "in"] Just (Percent a) -> [d <> text (showFl (a / 100)) <> "\\textwidth"] Just dim -> [d <> text (show dim)] Nothing -> [] dimList = showDim Width ++ showDim Height dims = if null dimList then empty else brackets $ cat (intersperse "," dimList) source' = if isURI source then source else unEscapeString source source'' <- stringToLaTeX URLString (escapeURI source') inHeading <- gets stInHeading return $ (if inHeading then "\\protect\\includegraphics" else "\\includegraphics") <> dims <> braces (text source'') inlineToLaTeX (Note contents) = do inMinipage <- gets stInMinipage modify (\s -> s{stInNote = True}) contents' <- blockListToLaTeX contents modify (\s -> s {stInNote = False}) let optnl = case reverse contents of (CodeBlock _ _ : _) -> cr _ -> empty let noteContents = nest 2 contents' <> optnl opts <- gets stOptions -- in beamer slides, display footnote from current overlay forward let beamerMark = if writerBeamer opts then text "<.->" else empty modify $ \st -> st{ stNotes = noteContents : stNotes st } return $ if inMinipage then "\\footnotemark{}" -- note: a \n before } needed when note ends with a Verbatim environment else "\\footnote" <> beamerMark <> braces noteContents protectCode :: [Inline] -> [Inline] protectCode [] = [] protectCode (x@(Code ("",[],[]) _) : xs) = x : protectCode xs protectCode (x@(Code _ _) : xs) = ltx "\\mbox{" : x : ltx "}" : xs where ltx = RawInline (Format "latex") protectCode (x : xs) = x : protectCode xs citationsToNatbib :: [Citation] -> State WriterState Doc citationsToNatbib (one:[]) = citeCommand c p s k where Citation { citationId = k , citationPrefix = p , citationSuffix = s , citationMode = m } = one c = case m of AuthorInText -> "citet" SuppressAuthor -> "citeyearpar" NormalCitation -> "citep" citationsToNatbib cits | noPrefix (tail cits) && noSuffix (init cits) && ismode NormalCitation cits = citeCommand "citep" p s ks where noPrefix = all (null . citationPrefix) noSuffix = all (null . citationSuffix) ismode m = all (((==) m) . citationMode) p = citationPrefix $ head $ cits s = citationSuffix $ last $ cits ks = intercalate ", " $ map citationId cits citationsToNatbib (c:cs) | citationMode c == AuthorInText = do author <- citeCommand "citeauthor" [] [] (citationId c) cits <- citationsToNatbib (c { citationMode = SuppressAuthor } : cs) return $ author <+> cits citationsToNatbib cits = do cits' <- mapM convertOne cits return $ text "\\citetext{" <> foldl combineTwo empty cits' <> text "}" where combineTwo a b | isEmpty a = b | otherwise = a <> text "; " <> b convertOne Citation { citationId = k , citationPrefix = p , citationSuffix = s , citationMode = m } = case m of AuthorInText -> citeCommand "citealt" p s k SuppressAuthor -> citeCommand "citeyear" p s k NormalCitation -> citeCommand "citealp" p s k citeCommand :: String -> [Inline] -> [Inline] -> String -> State WriterState Doc citeCommand c p s k = do args <- citeArguments p s k return $ text ("\\" ++ c) <> args citeArguments :: [Inline] -> [Inline] -> String -> State WriterState Doc citeArguments p s k = do let s' = case s of (Str (x:[]) : r) | isPunctuation x -> dropWhile (== Space) r (Str (x:xs) : r) | isPunctuation x -> Str xs : r _ -> s pdoc <- inlineListToLaTeX p sdoc <- inlineListToLaTeX s' let optargs = case (isEmpty pdoc, isEmpty sdoc) of (True, True ) -> empty (True, False) -> brackets sdoc (_ , _ ) -> brackets pdoc <> brackets sdoc return $ optargs <> braces (text k) citationsToBiblatex :: [Citation] -> State WriterState Doc citationsToBiblatex (one:[]) = citeCommand cmd p s k where Citation { citationId = k , citationPrefix = p , citationSuffix = s , citationMode = m } = one cmd = case m of SuppressAuthor -> "autocite*" AuthorInText -> "textcite" NormalCitation -> "autocite" citationsToBiblatex (c:cs) = do args <- mapM convertOne (c:cs) return $ text cmd <> foldl (<>) empty args where cmd = case citationMode c of AuthorInText -> "\\textcites" _ -> "\\autocites" convertOne Citation { citationId = k , citationPrefix = p , citationSuffix = s } = citeArguments p s k citationsToBiblatex _ = return empty -- Determine listings language from list of class attributes. getListingsLanguage :: [String] -> Maybe String getListingsLanguage [] = Nothing getListingsLanguage (x:xs) = toListingsLanguage x <|> getListingsLanguage xs -- Extract a key from divs and spans extract :: String -> Block -> [String] extract key (Div attr _) = lookKey key attr extract key (Plain ils) = concatMap (extractInline key) ils extract key (Para ils) = concatMap (extractInline key) ils extract key (Header _ _ ils) = concatMap (extractInline key) ils extract _ _ = [] -- Extract a key from spans extractInline :: String -> Inline -> [String] extractInline key (Span attr _) = lookKey key attr extractInline _ _ = [] -- Look up a key in an attribute and give a list of its values lookKey :: String -> Attr -> [String] lookKey key (_,_,kvs) = maybe [] words $ lookup key kvs -- In environments \Arabic instead of \arabic is used toPolyglossiaEnv :: String -> (String, String) toPolyglossiaEnv l = case toPolyglossia $ (splitBy (=='-')) l of ("arabic", o) -> ("Arabic", o) x -> x -- Takes a list of the constituents of a BCP 47 language code and -- converts it to a Polyglossia (language, options) tuple -- http://mirrors.concertpass.com/tex-archive/macros/latex/contrib/polyglossia/polyglossia.pdf toPolyglossia :: [String] -> (String, String) toPolyglossia ("ar":"DZ":_) = ("arabic", "locale=algeria") toPolyglossia ("ar":"IQ":_) = ("arabic", "locale=mashriq") toPolyglossia ("ar":"JO":_) = ("arabic", "locale=mashriq") toPolyglossia ("ar":"LB":_) = ("arabic", "locale=mashriq") toPolyglossia ("ar":"LY":_) = ("arabic", "locale=libya") toPolyglossia ("ar":"MA":_) = ("arabic", "locale=morocco") toPolyglossia ("ar":"MR":_) = ("arabic", "locale=mauritania") toPolyglossia ("ar":"PS":_) = ("arabic", "locale=mashriq") toPolyglossia ("ar":"SY":_) = ("arabic", "locale=mashriq") toPolyglossia ("ar":"TN":_) = ("arabic", "locale=tunisia") toPolyglossia ("de":"1901":_) = ("german", "spelling=old") toPolyglossia ("de":"AT":"1901":_) = ("german", "variant=austrian, spelling=old") toPolyglossia ("de":"AT":_) = ("german", "variant=austrian") toPolyglossia ("de":"CH":"1901":_) = ("german", "variant=swiss, spelling=old") toPolyglossia ("de":"CH":_) = ("german", "variant=swiss") toPolyglossia ("de":_) = ("german", "") toPolyglossia ("dsb":_) = ("lsorbian", "") toPolyglossia ("el":"polyton":_) = ("greek", "variant=poly") toPolyglossia ("en":"AU":_) = ("english", "variant=australian") toPolyglossia ("en":"CA":_) = ("english", "variant=canadian") toPolyglossia ("en":"GB":_) = ("english", "variant=british") toPolyglossia ("en":"NZ":_) = ("english", "variant=newzealand") toPolyglossia ("en":"UK":_) = ("english", "variant=british") toPolyglossia ("en":"US":_) = ("english", "variant=american") toPolyglossia ("grc":_) = ("greek", "variant=ancient") toPolyglossia ("hsb":_) = ("usorbian", "") toPolyglossia ("la":"x-classic":_) = ("latin", "variant=classic") toPolyglossia ("sl":_) = ("slovenian", "") toPolyglossia x = (commonFromBcp47 x, "") -- Takes a list of the constituents of a BCP 47 language code and -- converts it to a Babel language string. -- http://mirrors.concertpass.com/tex-archive/macros/latex/required/babel/base/babel.pdf -- Note that the PDF unfortunately does not contain a complete list of supported languages. toBabel :: [String] -> String toBabel ("de":"1901":_) = "german" toBabel ("de":"AT":"1901":_) = "austrian" toBabel ("de":"AT":_) = "naustrian" toBabel ("de":_) = "ngerman" toBabel ("dsb":_) = "lowersorbian" toBabel ("el":"polyton":_) = "polutonikogreek" toBabel ("en":"AU":_) = "australian" toBabel ("en":"CA":_) = "canadian" toBabel ("en":"GB":_) = "british" toBabel ("en":"NZ":_) = "newzealand" toBabel ("en":"UK":_) = "british" toBabel ("en":"US":_) = "american" toBabel ("fr":"CA":_) = "canadien" toBabel ("fra":"aca":_) = "acadian" toBabel ("grc":_) = "polutonikogreek" toBabel ("hsb":_) = "uppersorbian" toBabel ("la":"x-classic":_) = "classiclatin" toBabel ("sl":_) = "slovene" toBabel x = commonFromBcp47 x -- Takes a list of the constituents of a BCP 47 language code -- and converts it to a string shared by Babel and Polyglossia. -- https://tools.ietf.org/html/bcp47#section-2.1 commonFromBcp47 :: [String] -> String commonFromBcp47 [] = "" commonFromBcp47 ("pt":"BR":_) = "brazilian" commonFromBcp47 x = fromIso $ head x where fromIso "af" = "afrikaans" fromIso "am" = "amharic" fromIso "ar" = "arabic" fromIso "ast" = "asturian" fromIso "bg" = "bulgarian" fromIso "bn" = "bengali" fromIso "bo" = "tibetan" fromIso "br" = "breton" fromIso "ca" = "catalan" fromIso "cy" = "welsh" fromIso "cs" = "czech" fromIso "cop" = "coptic" fromIso "da" = "danish" fromIso "dv" = "divehi" fromIso "el" = "greek" fromIso "en" = "english" fromIso "eo" = "esperanto" fromIso "es" = "spanish" fromIso "et" = "estonian" fromIso "eu" = "basque" fromIso "fa" = "farsi" fromIso "fi" = "finnish" fromIso "fr" = "french" fromIso "fur" = "friulan" fromIso "ga" = "irish" fromIso "gd" = "scottish" fromIso "gl" = "galician" fromIso "he" = "hebrew" fromIso "hi" = "hindi" fromIso "hr" = "croatian" fromIso "hy" = "armenian" fromIso "hu" = "magyar" fromIso "ia" = "interlingua" fromIso "id" = "indonesian" fromIso "ie" = "interlingua" fromIso "is" = "icelandic" fromIso "it" = "italian" fromIso "jp" = "japanese" fromIso "km" = "khmer" fromIso "kn" = "kannada" fromIso "ko" = "korean" fromIso "la" = "latin" fromIso "lo" = "lao" fromIso "lt" = "lithuanian" fromIso "lv" = "latvian" fromIso "ml" = "malayalam" fromIso "mn" = "mongolian" fromIso "mr" = "marathi" fromIso "nb" = "norsk" fromIso "nl" = "dutch" fromIso "nn" = "nynorsk" fromIso "no" = "norsk" fromIso "nqo" = "nko" fromIso "oc" = "occitan" fromIso "pl" = "polish" fromIso "pms" = "piedmontese" fromIso "pt" = "portuguese" fromIso "rm" = "romansh" fromIso "ro" = "romanian" fromIso "ru" = "russian" fromIso "sa" = "sanskrit" fromIso "se" = "samin" fromIso "sk" = "slovak" fromIso "sq" = "albanian" fromIso "sr" = "serbian" fromIso "sv" = "swedish" fromIso "syr" = "syriac" fromIso "ta" = "tamil" fromIso "te" = "telugu" fromIso "th" = "thai" fromIso "tk" = "turkmen" fromIso "tr" = "turkish" fromIso "uk" = "ukrainian" fromIso "ur" = "urdu" fromIso "vi" = "vietnamese" fromIso _ = "" deNote :: Inline -> Inline deNote (Note _) = RawInline (Format "latex") "" deNote x = x pDocumentOptions :: P.Parsec String () [String] pDocumentOptions = do P.char '[' opts <- P.sepBy (P.many $ P.spaces *> P.noneOf (" ,]" :: String) <* P.spaces) (P.char ',') P.char ']' return opts pDocumentClass :: P.Parsec String () String pDocumentClass = do P.skipMany (P.satisfy (/='\\')) P.string "\\documentclass" classOptions <- pDocumentOptions <|> return [] if ("article" :: String) `elem` classOptions then return "article" else do P.skipMany (P.satisfy (/='{')) P.char '{' P.manyTill P.letter (P.char '}')
fibsifan/pandoc
src/Text/Pandoc/Writers/LaTeX.hs
gpl-2.0
57,173
0
42
19,530
15,749
7,957
7,792
1,129
76
{-# LANGUAGE TemplateHaskell #-} module RAM.Property where import Autolib.Reader import Autolib.ToDoc import Data.Typeable import RAM.Builtin data Property = Builtins [ Builtin ] | No_While | No_Loop deriving ( Typeable , Eq ) $(derives [makeReader, makeToDoc] [''Property]) example :: [ Property ] example = [ Builtins [ ] , No_While ] -- local variables: -- mode: haskell -- end
florianpilz/autotool
src/RAM/Property.hs
gpl-2.0
435
2
9
112
108
64
44
14
1
{-# language DeriveDataTypeable #-} {-# language StandaloneDeriving #-} {-# language Rank2Types #-} module Operate.Types where import Types.TT import Types.Basic import Types.Signed as S import Types.Documented as D import Types.ServerInfo import Types.TaskTree import Types.TaskDescription import Types.Config import Types.Instance as I import Types.Solution import qualified Util.Xml.Output as UXO import qualified Service.Interface as SI import qualified Control.Aufgabe.Typ as A import qualified Control.Aufgabe.DB as A import Control.Types ( toString, fromCGI, ok ) import Control.Applicative import Data.Tree import Data.Typeable import Gateway.CGI ( embed, io, open, close, table, row, plain, textarea, submit, html, Form, get_preferred_language ) import Autolib.ToDoc ( ToDoc, toDoc, text, Doc, vcat ) import Autolib.Reporter.IO.Type ( inform, reject ) import Autolib.Output as O import qualified Autolib.Multilingual as M import qualified Autolib.Multilingual.Html as H import Inter.Types ( CacheFun ) -- import qualified Text.XHtml as X import Util.Xml.Output import Control.Monad ( mzero) import qualified Control.Exception as CE type Server = String data Make = Make { server :: Server , task :: Task } deriving Typeable instance Show Make where show m = task m make = Make get_task_tree server = do tts <- SI.get_task_types server return $ Category { category_name = "all" , sub_trees = tts } tt_to_tree server tt = case tt of Task {} -> Data.Tree.Node ( Right ( task_name tt , make server (task_name tt) ) ) [] Category {} -> Data.Tree.Node ( Left $ category_name tt ) $ map (tt_to_tree server) $ sub_trees tt safe_io msg action = do out <- io $ CE.try action case out of Left ex -> do embed $ inform $ vcat [ text $ "internal error - please report the following:" , text $ unwords [ "source:", msg ] , text $ unwords [ "exception:", show (ex::CE.SomeException) ] ] mzero Right res -> return res get_task_config mk lang = do td <- safe_io "get_task_config" $ SI.get_task_description_localized ( server mk ) ( task mk ) lang let conf = task_sample_config td -- embed $ inform $ toDoc $ D.documentation conf -- return $ D.contents conf return conf verify_task_config mk conf lang = do SI.verify_task_config_localized ( server mk ) ( task mk ) conf lang instance ToDoc Description where toDoc (DString s) = text s task_config_editor title mk mauf = do lang <- get_preferred_language open row plain title docconf <- case mauf of Nothing -> get_task_config mk lang Just auf -> do -- ugly: since we do not put documentation in DB -- we have to ask the server again docco <- get_task_config mk lang return $ docco { D.contents = CString $ toString $ A.config auf } let CString conf = D.contents docconf DString doc = D.documentation docconf out = UXO.xmlStringToOutput doc open table open row ms <- textarea $ conf close -- row open row ; open table ; open row plain $ M.specialize lang $ M.make [ (M.DE, "Der Typ der Konfiguration ist:" ) , (M.UK, "configuration is of type:") ] html $ M.specialize lang $ ( O.render :: O.Output -> H.Html ) $ out close ; close ; close open row sconf <- submit "submit" close -- row close -- table close -- row ver <- safe_io "verify_task_config.1" $ verify_task_config mk ( CString $ case ms of Nothing -> conf Just s -> s ) lang case ver of Left err -> do html $ M.specialize M.DE $ ( O.render ( descr err) :: H.Html ) mzero Right stc -> do return stc signed_task_config auf = Signed { S.contents = ( toString $ A.typ auf , CString $ toString $ A.config auf ) , S.signature = toString $ A.signature auf } update_signature_if_missing auf = if toString (A.signature auf) == "missing" then do ver <- safe_io "verify_task_config-2" $ SI.verify_task_config ( toString $ A.server auf ) ( toString $ A.typ auf ) ( CString $ toString $ A.config auf ) case ver of Left err -> do html $ M.specialize M.DE $ ( O.render ( descr err) :: H.Html ) mzero Right stc -> do plain $ "warning: update_signature_if_missing" let auf' = auf { A.signature = fromCGI $ signature stc } io $ A.put_signature (Just $ A.anr auf) auf' return auf' else return auf -- FIXME: where's the cache used? generate :: A.Aufgabe -> Integer -> CacheFun -> Form IO ( Signed (Task,Instance) -- , Doc , Documented Solution , Output ) generate auf seed cache = do auf <- update_signature_if_missing auf lang <- get_preferred_language ( sti, desc, docsol ) <- do safe_io "get_task_instance" $ SI.get_task_instance_localized (toString $ A.server auf) ( signed_task_config auf ) ( show seed ) -- ? lang let SString sol = D.contents docsol return ( sti, docsol {- text sol -} , descr desc ) {- evaluate :: A.Aufgabe -> Signed (Task,Instance) -> String -> -} evaluate auf sti s lang = do result <- SI.grade_task_solution_localized (toString $ A.server auf) sti ( SString s ) lang case result of Left err -> return ( Nothing, descr err ) Right dd -> return ( Just $ ok $ round $ D.contents dd , descr $ D.documentation dd ) -- doc = descr . D.documentation descr desc = let DString d = desc in xmlStringToOutput d
marcellussiegburg/autotool
db/src/Operate/Types.hs
gpl-2.0
6,459
2
20
2,297
1,768
902
866
160
4
-- | Common JSON settings. module JSON ( jsonOptions, ) where import Data.Aeson (Options (..), camelTo2, defaultOptions) jsonOptions :: Options jsonOptions = defaultOptions { fieldLabelModifier = camelTo2 '_', omitNothingFields = True }
phaazon/phaazon.net
backend/src/JSON.hs
gpl-3.0
259
0
7
54
58
37
21
8
1
-- This lexer is not completely to spec. We accept certain characters that the -- spec would not allow, simplifying our lexer as suggested by Bermudez during -- lecture. For example, our strings could contain any arbitrary Unicode -- code-point, while the spec's can only handle a certain subset of ASCII. -- -- We use POSIX regular expressions because regex is awesome. Sure it slows down -- the lexer, but this isn't part of the critical path, so who cares? module Lexer ( Token(..) , getToken , getTokens ) where import Text.Regex.TDFA -- Text.Regex.Posix sucks import Data.Maybe data Token = TokenKeyword String | TokenIdentifier String | TokenInteger Integer | TokenOperator String | TokenString String | TokenPunction String | TokenDelete String -- Temporary placeholder, gets removed in the end | TokenComment String -- Discarded now, treated separately in case we might -- ever want to use this in the AST later deriving (Show, Eq) -- A given matcher should consume the first token it sees in the string, and -- then stop. Getting all the tokens can be done recursively (and lazily). tokenMatchers :: [(Regex, String -> Token)] tokenMatchers = [ (mr "[A-Za-z][A-Za-z0-9_]*", TokenIdentifier) , (mr "[0-9]+", \s -> TokenInteger $ read s) -- Stolen from http://stackoverflow.com/a/1016356/130598 , (mr "'(\\\\.|[^\'])*'", TokenString) , (mr "//.*", TokenComment) -- Must be processed before operator -- You have to be really careful with character ordering in the -- regex, so that `]`, `"`, and `-` get treated properly , (mr "[][+*<>&.@/:=~|$!#%^_{}\"`?-]+", TokenOperator) , (mr "[();,]", TokenPunction) , (mr "[ \t\n\r]+", TokenDelete) ] where mr m = makeRegex $ "\\`" ++ m -- Get applied in sequence, and can perform simple one-to-one transformations on -- tokens tokenTransformers :: [Token -> Token] tokenTransformers = [ transformKeyword ] transformToken :: Token -> Token transformToken token = foldr ($) token tokenTransformers -- Certain `TokenIdentifier`s should be be treated as keywords transformKeyword :: Token -> Token transformKeyword (TokenIdentifier name) = if isKeyword then TokenKeyword name else TokenIdentifier name where isKeyword = case name of "let" -> True "in" -> True "fn" -> True "aug" -> True "or" -> True "gr" -> True "ge" -> True "ls" -> True "le" -> True "eq" -> True "ne" -> True "not" -> True "where" -> True "within" -> True "and" -> True "rec" -> True "true" -> True "false" -> True "nil" -> True "dummy" -> True _ -> False transformKeyword token = token -- These terminals should be discarded by getToken isIgnored :: Token -> Bool isIgnored (TokenDelete _) = True isIgnored (TokenComment _) = True isIgnored _ = False getToken :: String -> Maybe (Token, String) getToken source = if null source then Nothing else let (token, sourceTail) = getTokenPartial tokenMatchers source in if isIgnored token then getToken sourceTail else Just (token, sourceTail) getTokens :: String -> [Token] getTokens source = let r = getToken source in if isJust r then let (token, sourceTail) = fromJust r in [token] ++ getTokens sourceTail else [] getTokenPartial :: [(Regex, String -> Token)] -> String -> (Token, String) getTokenPartial matchers source = let (m, t) = head matchers in if match m source then (transformToken $ t (match m source :: String), drop (length (match m source :: String)) source) else getTokenPartial (tail matchers) (source)
bgw/hs-rpal
src/Lexer.hs
gpl-3.0
4,118
0
13
1,280
813
446
367
78
22
{-# LANGUAGE TypeSynonymInstances #-} module Geometry where import Data.List import Data.Maybe import Control.Monad data Vector = Vector !Double !Double !Double deriving (Show, Read) instance Eq Vector where Vector x1 y1 z1 == Vector x2 y2 z2 = x1 ~= x2 && y1 ~= y2 && z1 ~= z2 (~=) :: (Floating a, Ord a) => a -> a -> Bool a ~= b = let c = abs (a - b) in -0.00001 < c && c < 0.00001 (~~) :: (Floating a, Ord a) => a -> a -> Bool a ~~ b | a == 0 = -0.001 < b && b < 0.001 | b == 0 = -0.001 < a && a < 0.001 | otherwise = let c = a / b in 0.999 < c && c < 1.001 instance Num Vector where Vector x1 y1 z1 + Vector x2 y2 z2 = Vector (x1 + x2) (y1 + y2) (z1 + z2) Vector x1 y1 z1 - Vector x2 y2 z2 = Vector (x1 - x2) (y1 - y2) (z1 - z2) Vector x1 y1 z1 * Vector x2 y2 z2 = Vector (y1 * z2 - z1 * y2) (z1 * x2 - x1 * z2) (x1 * y2 - y1 * x2) negate (Vector x y z) = Vector (-x) (-y) (-z) abs (Vector x y z) = Vector (abs x) (abs y) (abs z) signum v = (1 / norm v) |*| v fromInteger n = Vector (fromInteger n) (fromInteger n) (fromInteger n) unit :: Vector -> Vector unit = signum (|*|) :: Double -> Vector -> Vector k |*| Vector x y z = Vector (k * x) (k * y) (k * z) norm :: Vector -> Double norm (Vector x y z) = sqrt (x^2 + y^2 + z^2) scaleTo :: Vector -> Double -> Vector v `scaleTo` l = l |*| unit v distance :: Point -> Point -> Double distance p1 p2 = norm (p1 - p2) dot :: Vector -> Vector -> Double Vector x1 y1 z1 `dot` Vector x2 y2 z2 = x1 * x2 + y1 * y2 + z1 * z2 type Angle = Double angleBetween :: Vector -> Vector -> Angle angleBetween u v = acos (clamp (-1,1) (unit u `dot` unit v)) basicAngle :: Angle -> Angle basicAngle ang | ang < 0 = basicAngle (ang + tpi) | ang > tpi = basicAngle (ang - tpi) | otherwise = ang where tpi = 2 * pi type Point = Vector origin :: Point origin = Vector 0 0 0 type Polygon = [Point] midpoint :: Point -> Point -> Point midpoint a b = 0.5 |*| (a + b) centroid :: Polygon -> Point centroid [] = origin centroid ps = (1 / fromIntegral (length ps)) |*| sum ps polygonNormal :: Polygon -> Vector polygonNormal (a:b:c:_) = unit ((b - a) * (c - a)) class Transform3D a where translate3D :: Vector -> a -> a rotate3D :: Vector -> Angle -> a -> a scale3D :: Double -> a -> a instance Transform3D Vector where translate3D trans = (+ trans) rotate3D z t v = (cos t |*| v) + (sin t |*| (z * v)) + (((z `dot` v) * (1 - cos t)) |*| z) -- Rodrigue's Formula scale3D = (|*|) instance (Transform3D a) => Transform3D [a] where translate3D v = map (translate3D v) rotate3D axis ang = map (rotate3D axis ang) scale3D k = map (scale3D k) instance (Transform3D a, Transform3D b) => Transform3D (a,b) where translate3D v (a,b) = (translate3D v a, translate3D v b) rotate3D axis ang (a,b) = (rotate3D axis ang a, rotate3D axis ang b) scale3D k (a,b) = (scale3D k a, scale3D k b) alignToTwist :: (Transform3D a) => Vector -> Vector -> Angle -> a -> a alignToTwist v' v1 twist a = rotate3D (rotAxis v1 v') (angleBetween v1 v' + twist) a alignTo :: (Transform3D a) => Vector -> Vector -> a -> a alignTo v' v1 a = alignToTwist v' v1 0 a rotAxis v1 v' = let axis' = v1 * v' in if axis' == Vector 0 0 0 then let Vector vx vy vz = v1 vec | vx == 0 = Vector 0 vz (-vy) | vy == 0 = Vector vz 0 (-vx) | otherwise = Vector vy (-vx) 0 in unit vec else unit axis' type Rotation = (Vector, Angle) identity :: Rotation identity = (Vector 0 0 1, 0) class (Ord a) => Interval a where clamp :: (a,a) -> a -> a transformToInterval :: (a,a) -> (a,a) -> a -> a instance Interval Double where clamp (a,b) c | c < a = a | c > b = b | otherwise = c transformToInterval (a,b) (c,d) e = let dInt = d - c in if dInt == 0 then b else a + (e - c) * (b - a) / dInt instance Interval Float where clamp (a,b) c | c < a = a | c > b = b | otherwise = c transformToInterval (a,b) (c,d) e = let dInt = d - c in if dInt == 0 then b else a + (e - c) * (b - a) / dInt data HullPoint = HullPoint {hullPosition :: Point, hullRadius :: Double} deriving (Show, Eq, Read) instance Transform3D HullPoint where translate3D v (HullPoint p r) = HullPoint (translate3D v p) r rotate3D axis ang (HullPoint p r) = HullPoint (rotate3D axis ang p) r scale3D k (HullPoint p r) = HullPoint (scale3D k p) r type HullSegment = (HullPoint, HullPoint) type HullPolygon = [HullPoint] data Plane = Plane Vector Double deriving (Show, Eq) instance Transform3D Plane where translate3D v (Plane n c) = Plane n (c + v `dot` n) rotate3D axis ang (Plane n c) = Plane (rotate3D axis ang n) c scale3D k (Plane n c) = if k < 0 then Plane (-n) (-c * k) else Plane n (c * k) data HullFace = HullFace {hullFacePolygon :: HullPolygon, hullFacePlane :: Plane} deriving (Show, Eq) instance Transform3D HullFace where translate3D v (HullFace hps pl) = HullFace (translate3D v hps) (translate3D v pl) rotate3D axis ang (HullFace hps pl) = HullFace (rotate3D axis ang hps) (rotate3D axis ang pl) scale3D k (HullFace hps pl) = HullFace (scale3D k hps) (scale3D k pl) data ConvexHull = ConvexHull [HullPoint] [HullSegment] [HullFace] deriving (Show, Eq) instance Transform3D ConvexHull where translate3D v (ConvexHull hps hss hfs) = ConvexHull (translate3D v hps) (translate3D v hss) (translate3D v hfs) rotate3D axis ang (ConvexHull hps hss hfs) = ConvexHull (rotate3D axis ang hps) (rotate3D axis ang hss) (rotate3D axis ang hfs) scale3D k (ConvexHull hps hss hfs) = ConvexHull (scale3D k hps) (scale3D k hss) (scale3D k hfs) atan3 y x = if x == 0 then if y > 0 then pi/2 else 3*pi/2 else if x > 0 then if y > 0 then atan (y/x) else atan (y/x) + 2*pi else atan (y/x) + pi threeSpheresTangentPlane :: HullPoint -> HullPoint -> HullPoint -> Vector -> Plane threeSpheresTangentPlane (HullPoint p1' r1') (HullPoint p2' r2') (HullPoint p3' r3') v = if r1' ~= r2' && r2' ~= r3' then let zv = unit ((p2' - p1') * (p3' - p1')) n = if zv `dot` v > 0 then zv else -zv in Plane n ((n `dot` p1') + r1') else let [(p1,r1),(p2,r2),(p3,r3)] | r1' ~= r2' = [(p3',r3'),(p1',r1'),(p2',r2')] | r2' ~= r3' = [(p1',r1'),(p2',r2'),(p3',r3')] | r3' ~= r1' = [(p2',r2'),(p3',r3'),(p1',r1')] | otherwise = sortBy (\(_,a) (_,b) -> compare (-a) (-b)) [(p1',r1'),(p2',r2'),(p3',r3')] sc2 = similarityCenter p1 r1 p2 r2 sc3 = similarityCenter p1 r1 p3 r3 d1 = norm ((sc2 - p1) * (sc3 - p1)) / distance sc2 sc3 ang = asin (r1 / d1) zv = unit ((p2 - p1) * (p3 - p1)) n = if zv `dot` v > 0 then rotate3D (unit (sc3 - sc2)) ang zv else rotate3D (unit (sc2 - sc3)) ang (-zv) in Plane n (n `dot` sc2) similarityCenter p1 r1 p2 r2 = let k = distance p1 p2 l = r1 * k / (r2 - r1) in p2 + ((p1 - p2) `scaleTo` (l + k)) insideHalfSpace :: HullPoint -> HullFace -> Bool HullPoint p r `insideHalfSpace` HullFace _ (Plane v k) = let a = p `dot` v b = k - r in a ~= b || a < b inConeOf :: HullPoint -> HullPoint -> HullPoint -> Bool inConeOf (HullPoint p2' r2') (HullPoint p1' r1') (HullPoint p r) = if r1' ~~ r2' then d + r <= r1' else let (p2,r2,p1,r1) = if r1' < r2' then (p2',r2',p1',r1') else (p1',r1',p2',r2') sc = similarityCenter p2 r2 p1 r1 coneSine = r1 / distance p1 sc sc' = sc + ((p1 - sc) `scaleTo` (r / coneSine)) testSine = (norm ((p2 - p) * (p1 - p)) / (distance p2 p1 * distance p sc')) in testSine <= coneSine where d = norm ((p2' - p) * (p1' - p)) / (distance p2' p1') coplanarHullPoints :: HullPoint -> HullPoint -> Plane -> [HullPoint] -> Bool -> (HullFace, [HullFace]) coplanarHullPoints hp1@(HullPoint p1 r1) hp2 pl@(Plane n _) hps starter = let hpAll = hp1:hp2:hps cen = centroid (map hullPosition hpAll) v = hullPosition hp2 - p1 u = v * (v - n) (an, Plane sn _) = if u `dot` (p1 - cen) > 0 then let an' = n in (an', threeSpheresTangentPlane hp1 (HullPoint (p1 + an') r1) hp2 u ) else let an' = -n in (an', threeSpheresTangentPlane hp1 (HullPoint (p1 + an') r1) hp2 (-u)) sorted@(x:xs) = wrap2D hp1 cen an hp1 hp2 sn hpAll hfs = if starter then getHullFaces (sorted ++ [x, head xs]) else removeEdge (hp1,hp2) (getHullFaces (sorted ++ [x, head xs])) in (HullFace sorted pl, hfs) where sortRing v@(Vector x y z) hps = let i = unit (v * Vector x y (2 * maximum [x,y,z])) j = v * i pairs = map (projectPairup i j) hps in map snd (sortBy (\(a,_) (b,_) -> compare a b) pairs) where projectPairup i j hp@(HullPoint p _) = (atan3 (p `dot` j) (p `dot` i), hp) getHullFaces (a:xs@(b:c:_)) = HullFace [a,b,c] pl : getHullFaces xs getHullFaces _ = [] removeEdge (a,b) = removeBy ((\x -> x == [a,b] || x == [b,a]) . (take 2) . hullFacePolygon) wrap2D hp0 cen an hp1 hp2@(HullPoint p2 r2) sn hps = let p2' = p2 + an pairs = mapMaybe (pairWithAng p2 p2' sn hp2 (HullPoint p2' r2)) (hps \\ [hp1,hp2]) (_,(n,hp)) = minimumBy (\(a,_) (b,_) -> compare a b) pairs in if hp == hp0 then [hp1,hp2] else hp1 : wrap2D hp0 cen an hp2 hp n hps where pairWithAng p1 p2 v hp1 hp2 hp@(HullPoint p _) = if inConeOf hp1 hp2 hp then Nothing else let Plane nv _ = threeSpheresTangentPlane hp1 hp2 hp ((p1 - p) * (p2 - p)) in Just (angleBetween v nv, (nv,hp)) removeBy f (x:xs) = if f x then xs else x : removeBy f xs removeBy _ _ = [] convexHull :: [HullPoint] -> ConvexHull convexHull [hp] = ConvexHull [hp] [] [] convexHull [hp1,hp2] = ConvexHull [hp1,hp2] [(hp1,hp2)] [] convexHull hps' = let hps = nub hps' xPairs = map pairWithXR hps (_,hp1) = minimumBy (\(a,_) (b,_) -> compare a b) xPairs HullPoint p1@(Vector x y z) r1 = hp1 tp2 = Vector x y (z + 2*r1) hps1 = delete hp1 hps angPairs = mapMaybe (pairWithAng p1 tp2 (Vector (-1) 0 0) hp1 (HullPoint tp2 r1)) hps1 (_,(nv,hp2)) = minimumBy (\(a,_) (b,_) -> compare a b) angPairs p2 = hullPosition hp2 hps2 = delete hp2 hps1 plPairs = mapMaybe (pairWithPlanes p2 p1 nv hp2 hp1) hps2 sorted = sortBy (\(a,_) (b,_) -> compare a b) plPairs (ang,(pl,_)) = head sorted cohps = map (snd . snd) (takeWhile ((~= ang) . fst) sorted) (hf0,hfs) = coplanarHullPoints hp1 hp2 pl cohps True in giftWrapping (hullFacePolygon hf0) [] [hf0] hfs hps where pairWithXR hp@(HullPoint (Vector x _ _) r) = (x - r, hp) pairWithAng p1 p2 xv hp1 hp2 hp@(HullPoint p _) = if inConeOf hp1 hp2 hp then Nothing else let pl@(Plane nv _) = threeSpheresTangentPlane hp1 hp2 hp ((p - p2) * (p - p1)) in Just (angleBetween xv nv, (nv,hp)) pairWithPlanes p1 p2 v hp1 hp2 hp@(HullPoint p _) = if inConeOf hp1 hp2 hp then Nothing else let pl@(Plane nv _) = threeSpheresTangentPlane hp1 hp2 hp ((p - p2) * (p - p1)) in Just (angleBetween v nv, (pl,hp)) giftWrapping :: [HullPoint] -> [HullSegment] -> [HullFace] -> [HullFace] -> [HullPoint] -> ConvexHull giftWrapping hps hss hfs (HullFace [hp1,hp2,hp3] (Plane n _) : hsfs) points = let HullPoint p1 r1 = hp1 HullPoint p2 r2 = hp2 p3 = hullPosition hp3 tn = (p1 - p3) * (p2 - p3) k = unit (p2 + (n `scaleTo` r2) - p1 - (n `scaleTo` r1)) rest = points \\ [hp1,hp2] pairs = if tn `dot` n > 0 then mapMaybe (pairWithPlanes p2 p1 n ( k * n)) rest else mapMaybe (pairWithPlanes p1 p2 n (-k * n)) rest sorted = sortBy (\(a,_) (b,_) -> compare a b) pairs (ang,(pl@(Plane nn _),ppp)) = head sorted cohps = map (snd . snd) (takeWhile ((~= ang) . fst) sorted) (hf1,hfs1) = coplanarHullPoints hp1 hp2 pl cohps False in if any (doneBefore (hp1,hp2) nn) hsfs then giftWrapping hps ((hp1,hp2):hss) hfs (removeBy (doneBefore (hp1,hp2) nn) hsfs) points else giftWrapping (hullFacePolygon hf1 ++ hps) ((hp1,hp2):hss) (hf1:hfs) (hfs1 ++ hsfs) points where pairWithPlanes p1 p2 i j hp@(HullPoint p _) = if inConeOf hp1 hp2 hp then Nothing else let pl@(Plane nv _) = threeSpheresTangentPlane hp1 hp2 hp ((p1 - p) * (p2 - p)) ang' = atan3 (nv `dot` j) (nv `dot` i) ang = if ang' ~= (2*pi) then 0 else ang' in Just (ang, (pl,hp)) getNormal (HullFace _ (Plane n _)) = n doneBefore (a,b) nn (HullFace [c,d,_] (Plane n _)) = (n == nn) && ((a == c && b == d) || (a == d && b == c)) giftWrapping hps hss hfs _ _ = ConvexHull (nub hps) hss hfs
herngyi/hmol
Geometry.hs
gpl-3.0
14,575
0
18
5,265
6,660
3,524
3,136
294
6
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DLP.Projects.Locations.InspectTemplates.Patch -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the InspectTemplate. See -- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more. -- -- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.projects.locations.inspectTemplates.patch@. module Network.Google.Resource.DLP.Projects.Locations.InspectTemplates.Patch ( -- * REST Resource ProjectsLocationsInspectTemplatesPatchResource -- * Creating a Request , projectsLocationsInspectTemplatesPatch , ProjectsLocationsInspectTemplatesPatch -- * Request Lenses , plitpXgafv , plitpUploadProtocol , plitpAccessToken , plitpUploadType , plitpPayload , plitpName , plitpCallback ) where import Network.Google.DLP.Types import Network.Google.Prelude -- | A resource alias for @dlp.projects.locations.inspectTemplates.patch@ method which the -- 'ProjectsLocationsInspectTemplatesPatch' request conforms to. type ProjectsLocationsInspectTemplatesPatchResource = "v2" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] GooglePrivacyDlpV2UpdateInspectTemplateRequest :> Patch '[JSON] GooglePrivacyDlpV2InspectTemplate -- | Updates the InspectTemplate. See -- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more. -- -- /See:/ 'projectsLocationsInspectTemplatesPatch' smart constructor. data ProjectsLocationsInspectTemplatesPatch = ProjectsLocationsInspectTemplatesPatch' { _plitpXgafv :: !(Maybe Xgafv) , _plitpUploadProtocol :: !(Maybe Text) , _plitpAccessToken :: !(Maybe Text) , _plitpUploadType :: !(Maybe Text) , _plitpPayload :: !GooglePrivacyDlpV2UpdateInspectTemplateRequest , _plitpName :: !Text , _plitpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsInspectTemplatesPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plitpXgafv' -- -- * 'plitpUploadProtocol' -- -- * 'plitpAccessToken' -- -- * 'plitpUploadType' -- -- * 'plitpPayload' -- -- * 'plitpName' -- -- * 'plitpCallback' projectsLocationsInspectTemplatesPatch :: GooglePrivacyDlpV2UpdateInspectTemplateRequest -- ^ 'plitpPayload' -> Text -- ^ 'plitpName' -> ProjectsLocationsInspectTemplatesPatch projectsLocationsInspectTemplatesPatch pPlitpPayload_ pPlitpName_ = ProjectsLocationsInspectTemplatesPatch' { _plitpXgafv = Nothing , _plitpUploadProtocol = Nothing , _plitpAccessToken = Nothing , _plitpUploadType = Nothing , _plitpPayload = pPlitpPayload_ , _plitpName = pPlitpName_ , _plitpCallback = Nothing } -- | V1 error format. plitpXgafv :: Lens' ProjectsLocationsInspectTemplatesPatch (Maybe Xgafv) plitpXgafv = lens _plitpXgafv (\ s a -> s{_plitpXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plitpUploadProtocol :: Lens' ProjectsLocationsInspectTemplatesPatch (Maybe Text) plitpUploadProtocol = lens _plitpUploadProtocol (\ s a -> s{_plitpUploadProtocol = a}) -- | OAuth access token. plitpAccessToken :: Lens' ProjectsLocationsInspectTemplatesPatch (Maybe Text) plitpAccessToken = lens _plitpAccessToken (\ s a -> s{_plitpAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plitpUploadType :: Lens' ProjectsLocationsInspectTemplatesPatch (Maybe Text) plitpUploadType = lens _plitpUploadType (\ s a -> s{_plitpUploadType = a}) -- | Multipart request metadata. plitpPayload :: Lens' ProjectsLocationsInspectTemplatesPatch GooglePrivacyDlpV2UpdateInspectTemplateRequest plitpPayload = lens _plitpPayload (\ s a -> s{_plitpPayload = a}) -- | Required. Resource name of organization and inspectTemplate to be -- updated, for example -- \`organizations\/433245324\/inspectTemplates\/432452342\` or -- projects\/project-id\/inspectTemplates\/432452342. plitpName :: Lens' ProjectsLocationsInspectTemplatesPatch Text plitpName = lens _plitpName (\ s a -> s{_plitpName = a}) -- | JSONP plitpCallback :: Lens' ProjectsLocationsInspectTemplatesPatch (Maybe Text) plitpCallback = lens _plitpCallback (\ s a -> s{_plitpCallback = a}) instance GoogleRequest ProjectsLocationsInspectTemplatesPatch where type Rs ProjectsLocationsInspectTemplatesPatch = GooglePrivacyDlpV2InspectTemplate type Scopes ProjectsLocationsInspectTemplatesPatch = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsInspectTemplatesPatch'{..} = go _plitpName _plitpXgafv _plitpUploadProtocol _plitpAccessToken _plitpUploadType _plitpCallback (Just AltJSON) _plitpPayload dLPService where go = buildClient (Proxy :: Proxy ProjectsLocationsInspectTemplatesPatchResource) mempty
brendanhay/gogol
gogol-dlp/gen/Network/Google/Resource/DLP/Projects/Locations/InspectTemplates/Patch.hs
mpl-2.0
6,156
0
16
1,269
781
458
323
120
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Plus.Activities.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Shut down. See https:\/\/developers.google.com\/+\/api-shutdown for more -- details. -- -- /See:/ <https://developers.google.com/+/api/ Google+ API Reference> for @plus.activities.get@. module Network.Google.Resource.Plus.Activities.Get ( -- * REST Resource ActivitiesGetResource -- * Creating a Request , activitiesGet , ActivitiesGet -- * Request Lenses , agActivityId ) where import Network.Google.Plus.Types import Network.Google.Prelude -- | A resource alias for @plus.activities.get@ method which the -- 'ActivitiesGet' request conforms to. type ActivitiesGetResource = "plus" :> "v1" :> "activities" :> Capture "activityId" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Activity -- | Shut down. See https:\/\/developers.google.com\/+\/api-shutdown for more -- details. -- -- /See:/ 'activitiesGet' smart constructor. newtype ActivitiesGet = ActivitiesGet' { _agActivityId :: Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ActivitiesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'agActivityId' activitiesGet :: Text -- ^ 'agActivityId' -> ActivitiesGet activitiesGet pAgActivityId_ = ActivitiesGet' {_agActivityId = pAgActivityId_} -- | The ID of the activity to get. agActivityId :: Lens' ActivitiesGet Text agActivityId = lens _agActivityId (\ s a -> s{_agActivityId = a}) instance GoogleRequest ActivitiesGet where type Rs ActivitiesGet = Activity type Scopes ActivitiesGet = '["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me"] requestClient ActivitiesGet'{..} = go _agActivityId (Just AltJSON) plusService where go = buildClient (Proxy :: Proxy ActivitiesGetResource) mempty
brendanhay/gogol
gogol-plus/gen/Network/Google/Resource/Plus/Activities/Get.hs
mpl-2.0
2,743
0
12
587
304
188
116
47
1
{- Copyright (C) 2014 Albert Krewinkel <tarleb+metropolis@moltkeplatz.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} {- | Module : Text.Rundoc Copyright : © 2014 Albert Krewinkel <tarleb+metropolis@moltkeplatz.de> License : GNU AGPL, version 3 or above Evaluate code in Rundoc code blocks and re-insert the results. -} module Text.Rundoc ( rundoc , runBlocks , runInlineCode , rundocBlockClass ) where import Metropolis.Types ( MetropolisResult(..) , MetropolisParameter(..) , Language(..) ) import Metropolis.Worker (runCode) import Text.Pandoc ( Attr, Inline( Code, Space, Span ) , Block ( Para, CodeBlock, Null, Div ) , nullAttr ) import Text.Pandoc.Walk (walkM) import Text.Pandoc.Builder (Inlines, Blocks) import qualified Text.Pandoc.Builder as B import Control.Applicative ((<$>)) import Data.Bifunctor (bimap) import Data.Default (Default(..)) import Data.List (foldl', isPrefixOf) import Data.Maybe (fromMaybe) import Data.Monoid (mconcat, mempty) -- | Run code and return the result if a rundoc code block is supplied; -- otherwise return the argument unaltered. rundoc :: Block -> IO Block rundoc x = runBlocks x >>= walkM runInlineCode -- | Run inline code blocks. runInlineCode :: Inline -> IO Inline runInlineCode inline = case inline of (Code attr code) | isRundocBlock attr -> evalInlineCode attr code _ -> return inline where evalInlineCode :: Attr -- ^ Old block attributes -> String -- ^ Code to evaluate -> IO Inline -- ^ Resulting inline evalInlineCode attr@(_,_,opts) code = let attr' = stripRundocAttrs attr rdOpts = rundocOptions opts in (setCodeAttr attr' . singularizeInlines . resultToInlines rdOpts) <$> evalCode rdOpts code -- | Run code blocks. runBlocks :: Block -> IO Block runBlocks block = case block of (CodeBlock attr code) | isRundocBlock attr -> evalBlock attr code _ -> return block where evalBlock :: Attr -> String -> IO Block evalBlock attr@(_,_,opts) code = let attr' = stripRundocAttrs attr rdOpts = rundocOptions opts in (setBlockCodeAttr attr' . singularizeBlocks . inlinesToBlocks . resultToInlines rdOpts) <$> evalCode rdOpts code isRundocBlock :: Attr -> Bool isRundocBlock (_,cls,_) = rundocBlockClass `elem` cls isRundocOption :: (String, String) -> Bool isRundocOption (key, _) = rundocPrefix `isPrefixOf` key -- | Prefix used for rundoc classes and parameters. rundocPrefix :: String rundocPrefix = "rundoc-" -- | Class-name used to mark rundoc blocks. rundocBlockClass :: String rundocBlockClass = rundocPrefix ++ "block" -- Options data RundocOptions = RundocOptions { rundocLanguage :: Language , rundocResultType :: RundocResultType , rundocExports :: RundocExports , rundocOutfile :: Maybe FilePath } deriving (Eq, Show) instance Default RundocOptions where def = RundocOptions { rundocLanguage = UnknownLanguage "" , rundocResultType = Replace , rundocExports = [ExportSource] , rundocOutfile = Nothing } optionsToMetropolisParameters :: RundocOptions -> MetropolisParameter optionsToMetropolisParameters opts = MetropolisParameter { parameterVariables = [] , parameterOutfile = rundocOutfile opts , parameterLanguage = rundocLanguage opts } data RundocResultType = Replace | Silent deriving (Eq, Show) data Export = ExportSource | ExportOutput | ExportError | ExportFile deriving (Eq, Show) type RundocExports = [Export] rundocOptions :: [(String, String)] -> RundocOptions rundocOptions = foldl' parseOption def . map rmPrefix . filter isRundocOption where rmPrefix (k,v) = (drop (length rundocPrefix) k, v) parseOption :: RundocOptions -> (String, String) -> RundocOptions parseOption opts (key, value) = case key of "language" -> opts{ rundocLanguage = parseLanguage value } "exports" -> opts{ rundocExports = parseExport value } "results" -> opts{ rundocResultType = parseResult value } "file" -> opts{ rundocOutfile = Just value } _ -> opts parseLanguage :: String -> Language parseLanguage lang = case lang of "sh" -> Shell "haskell" -> Haskell "ditaa" -> Ditaa "R" -> R x -> UnknownLanguage x parseExport :: String -> RundocExports parseExport exportType = case exportType of "result" -> [ExportOutput] "output" -> [ExportOutput] "code" -> [ExportSource] "both" -> [ExportSource, ExportOutput] "file" -> [ExportFile] _ -> [] parseResult :: String -> RundocResultType parseResult "silent" = Silent parseResult _ = Replace setCodeAttr :: Attr -> Inline -> Inline setCodeAttr attr x = case x of Code _ code -> Code attr code _ -> x setBlockCodeAttr :: Attr -> Block -> Block setBlockCodeAttr attr x = case x of CodeBlock _ code -> CodeBlock attr code _ -> x stripRundocAttrs :: Attr -> Attr stripRundocAttrs = bimap (filter (/= rundocBlockClass)) (filter (not . isRundocOption)) evalCode :: RundocOptions -> String -> IO MetropolisResult evalCode opts = runCode (optionsToMetropolisParameters opts) resultToInlines :: RundocOptions -> MetropolisResult -> Inlines resultToInlines opts res = if Silent == rundocResultType opts then mempty else mconcat . map (`exporter` res) $ rundocExports opts singularizeInlines :: Inlines -> Inline singularizeInlines inlines = case B.toList inlines of [] -> Space (x:[]) -> x xs -> Span nullAttr xs inlinesToBlocks :: Inlines -> Blocks inlinesToBlocks = fmap inlineToBlock inlineToBlock :: Inline -> Block inlineToBlock = Para . (:[]) singularizeBlocks :: Blocks -> Block singularizeBlocks blocks = case B.toList blocks of [] -> Null (x:[]) -> x xs -> Div nullAttr xs exporter :: Export -> MetropolisResult -> Inlines exporter e = case e of ExportSource -> exportSource ExportOutput -> exportOutput ExportFile -> exportFile _ -> error "Not implemented yet" exportOutput :: MetropolisResult -> Inlines exportOutput = B.codeWith nullAttr . resultOutput exportSource :: MetropolisResult -> Inlines exportSource = B.codeWith nullAttr . resultSource exportFile :: MetropolisResult -> Inlines exportFile = (\url -> B.image url "" mempty) . fromMaybe "" . resultFile
tarleb/rundoc
src/Text/Rundoc.hs
agpl-3.0
7,594
0
14
2,084
1,706
930
776
168
6
{-# LANGUAGE NoImplicitPrelude #-} module Except (ExceptT(..), throwE, runExceptT) where import GHC.Base ((.), ($)) import Functor import Monad import Applicative import Either import Trans data ExceptT e m a = ExceptT (m (Either e a)) runExceptT :: ExceptT e m a -> m (Either e a) runExceptT (ExceptT m) = m instance Functor m => Functor (ExceptT e m) where fmap f = ExceptT . fmap (fmap f) . runExceptT instance Monad m => Applicative (ExceptT e m) where pure = ExceptT . pure . Right (ExceptT f) <*> (ExceptT v) = ExceptT $ (f >>= \mf -> v >>= \m -> return (mf <*> m)) instance Monad m => Monad (ExceptT e m) where return = ExceptT . return . Right m >>= k = ExceptT $ runExceptT m >>= \a -> case a of Left e -> return (Left e) Right x -> runExceptT (k x) fail = ExceptT . fail -- fmap will promote function `Right` to monad `m` instance MonadTrans (ExceptT e) where lift = ExceptT . fmap Right throwE :: Monad m => e -> ExceptT e m a throwE = ExceptT . return . Left
seckcoder/lang-learn
haskell/lambda-calculus/src/Except.hs
unlicense
1,203
0
14
423
436
228
208
29
1
--{-# LANGUAGE BangPatterns #-} -- -- Copyright : (c) T.Mishima 2014 -- License : Apache-2.0 -- module Hinecraft.Types where version :: String version = "0.3.0" data ChunkParam = ChunkParam { blockSize :: Int , blockNum :: Int } chunkParam :: ChunkParam chunkParam = ChunkParam { blockSize = 16 , blockNum = 8 } type BlockIDNum = Int data Shape = Cube | Half Bool | Stairs | Cross deriving (Eq,Show,Ord) type BlockCatalog = [BlockIDNum] data InventoryParam = InventoryParam { dlgTexturePath :: FilePath , tabTexturePath :: FilePath , iconSize :: Double , projectionRate :: Double , rectDotSize :: (Int,Int) , uvOrg :: (Double,Double) , uvRectSize :: (Double,Double) , iconListOrg :: (Double,Double) , iconListItvl :: Double , palletOrg :: (Double,Double) } inventoryParam :: InventoryParam inventoryParam = InventoryParam { dlgTexturePath = "/.Hinecraft/textures/gui/container/creative_inventory/tab_items.png" , tabTexturePath = "/.Hinecraft/textures/gui/container/creative_inventory/tabs.png" , iconSize = 16.0 , projectionRate = 2.5 , rectDotSize = (w,h) , uvOrg = (0,0) , uvRectSize = (fromIntegral w / 256,fromIntegral h / 256) , iconListOrg = (9, fromIntegral h - 35) , iconListItvl = 18 , palletOrg = (9,fromIntegral h - 129) } where (w,h) = (196,136) data UserStatus = UserStatus { userPos :: Pos' , userRot :: Rot' , palletIndex :: Int , userVel :: (Double,Double,Double) } deriving (Eq,Show) data TitleModeState = TitleModeState { rotW :: Double , isModeChgBtnEntr :: Bool , isExitBtnEntr :: Bool , isQuit :: Bool } deriving (Eq,Show) data InitModeState = InitModeState Double deriving (Eq,Show) type DragDropMode = Maybe BlockIDNum type DragDropState = Maybe ((Double,Double),BlockIDNum) data PlayModeState = PlayModeState { usrStat :: UserStatus , drgdrpMd :: DragDropMode , drgSta :: DragDropState , curPos :: Maybe (WorldIndex,Surface) , pallet :: [BlockIDNum] } deriving (Show) type ChunkIdx = (Int,Int) type ChunkID = Int type BlockID = Int type Index = Int type WorldIndex = (Int,Int,Int) type Pos' = (Double,Double,Double) type Rot' = Pos' type Vel' = Pos' type SurfacePos = [(WorldIndex,BlockIDNum,[Surface])] data Surface = STop | SBottom | SRight | SLeft | SFront | SBack deriving (Ord,Show,Eq,Read) type BlockNo = Int type ChunkNo = Int type LightNo = Int type Bright = Int
tmishima/Hinecraft
Hinecraft/Types.hs
apache-2.0
2,439
0
10
485
726
455
271
78
1
-- -- Copyright 2017 Warlock <internalmike@gmail.com> -- -- 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. -- #define TESTS #include <haskell> import qualified Solid.Solver.Spec main :: IO () main = void $ runTestTT tests tests :: Test tests = TestList [ Solid.Solver.Spec.tests ]
A1-Triard/solid
test/Spec.hs
apache-2.0
793
0
7
134
67
45
22
6
1
{-# LANGUAGE GeneralizedNewtypeDeriving, ScopedTypeVariables #-} module Language.Gamma.Parser.Commented where import Control.Applicative import Control.Monad import Control.Monad.Trans import Data.Proxy import Text.Trifecta import Text.Parser.Token.Style -- a way to decide comment style based on a phantom type class CommentedStyle t where commentedStyle :: Proxy t -> CommentStyle -- a parser transformer that skips comments as whitespace newtype Commented sty m a = Commented { runCommented :: m a } deriving (Functor, Applicative, Alternative, Monad, MonadPlus, Parsing, CharParsing, DeltaParsing, Errable, Monoid) instance MonadTrans (Commented sty) where lift = Commented instance (TokenParsing m, CommentedStyle sty) => TokenParsing (Commented sty m) where nesting (Commented m) = Commented (nesting m) semi = Commented semi highlight h (Commented m) = Commented (highlight h m) someSpace = Commented (buildSomeSpaceParser someSpace style) where style = commentedStyle (Proxy :: Proxy sty)
agrif/gammac
src/Language/Gamma/Parser/Commented.hs
apache-2.0
1,034
0
10
165
270
147
123
20
0
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE BangPatterns #-} {-| Module : Marvin.API.Table.Column Description : Statically and dynamically typed columns that represent machine learning attributes. -} module Marvin.API.Table.Column where import Data.Vector (Vector) import qualified Data.Vector as Vec import qualified Data.Vector.Unboxed as UVec import qualified Data.Set as Set import qualified Data.ByteString as BS import Data.ByteString (ByteString) import Data.ByteString.Internal (c2w, w2c) import Data.Typeable import Control.Arrow import Control.Monad.Reader import Control.Monad.Except import Text.PrettyPrint.Boxes (Box) import Marvin.API.Table.DataType import Marvin.API.Fallible type ColumnName = String -- * ColumnClass -- | Class for general columns. class Eq c => ColumnClass c where -- | Number of elements in column. columnSize :: c -> Int -- | Name of column. columnName :: c -> Fallible ColumnName -- | Names a column without checking name validity. nameColumn' :: ColumnName -> c -> c -- | Splits a column by 'Bool' flags. -- Useful for random splitting tables to training and test data. splitByFlags :: [Bool] -> c -> Fallible (c, c) -- * Concrete column types -- ** RawColumn -- | Type for column before parsing. Contains Strings. newtype RawColumn = RawColumn (Maybe ColumnName, Vector ByteString) instance ColumnClass RawColumn where columnSize (RawColumn (_, vals)) = Vec.length vals columnName (RawColumn (name, _)) = maybe (Left NoColumnName) Right name nameColumn' name (RawColumn (_, vals)) = RawColumn (Just name, vals) splitByFlags = splitByFlagsRaw instance Show RawColumn where show (RawColumn (_, vals)) = show $ Vec.cons (Vec.last vals) (Vec.take 10 vals) instance Eq RawColumn where a == b = valuesRaw a == valuesRaw b -- | Creating 'RawColumn' from list. fromListToRaw :: [String] -> Fallible RawColumn fromListToRaw xs = do -- checking whether the column is empty checkNonEmptyColumn xs -- creating a ByteStrings from Strings, and Vector from the list. return $ fromVectorToRaw $ Vec.fromList $ fmap stringToBS xs -- | Creating 'RawColumn' from list. rawToList :: RawColumn -> [String] rawToList = valuesRaw >>> Vec.toList >>> fmap bsToString -- *** Helper methods bsToString :: ByteString -> String bsToString = BS.unpack >>> fmap w2c stringToBS :: String -> ByteString stringToBS = fmap c2w >>> BS.pack valuesRaw :: RawColumn -> Vector ByteString valuesRaw (RawColumn (_, vals)) = vals setValuesRaw :: Vector ByteString -> RawColumn -> RawColumn setValuesRaw vals (RawColumn (name, _)) = RawColumn (name, vals) fromVectorToRaw :: Vector ByteString -> RawColumn fromVectorToRaw vals = RawColumn (Nothing, vals) columnNameRaw :: RawColumn -> Maybe ColumnName columnNameRaw (RawColumn (name, _)) = name -- ** Generic columns -- *** Type class -- | Type class for statically typed, parsed column. -- The type is represented by the attribute type. class (DataTypeClass a, Typeable a, UVec.Unbox (ColumnRepr a), Typeable (ColumnRepr a), Typeable (ColumnExposed a), Eq (ColumnExposed a)) => ColumnDataType a where -- | Type family assigning a data representation type to the attribute type. type ColumnRepr a -- | Injective type family assigning a display type for the attribute type. type ColumnExposed a = e | e -> a -- | Creates a column from a list of the displayed types without checks. unsafeFromList :: [ColumnExposed a] -> Column a -- | A column invariant that's checked before creating the column. -- E.g. 'Natural Column' must not contain negative integers. columnInvariant :: ColumnExposed a -> Fallible () -- *** GenericColumn data GenericColumn dtype repr exposed = GC { values :: UVec.Vector repr, exposure :: repr -> exposed, columnNameGen :: Maybe ColumnName } genColType :: DataTypeClass dtype => GenericColumn dtype repr exposed -> dtype genColType col = staticType instance (Eq exposed, UVec.Unbox repr) => Eq (GenericColumn dtype repr exposed) where a == b = (eqPrep a) == (eqPrep b) where eqPrep x = fmap (exposure x) $ UVec.toList (values x) instance (ColumnDataType a, UVec.Unbox r, Eq e) => ColumnClass (GenericColumn a r e) where columnSize = values >>> UVec.length columnName = maybe (Left NoColumnName) Right . columnNameGen nameColumn' name c = c { columnNameGen = Just name } splitByFlags = splitByFlagsGen instance ColumnDataType Numeric where type ColumnRepr Numeric = Double type ColumnExposed Numeric = Double unsafeFromList = unsafeFromVector . UVec.fromList columnInvariant _ = return () instance ColumnDataType Nominal where type ColumnRepr Nominal = Int type ColumnExposed Nominal = String unsafeFromList = unsafeNominalColumn columnInvariant _ = return () instance ColumnDataType Binary where type ColumnRepr Binary = Bool type ColumnExposed Binary = Bool unsafeFromList = unsafeFromVector . UVec.fromList columnInvariant _ = return () instance ColumnDataType Natural where type ColumnRepr Natural = Int type ColumnExposed Natural = Int unsafeFromList = unsafeFromVector . UVec.fromList columnInvariant x = if x >= 0 then return () else throwError $ BrokenInvariant $ "Negative element while constructing NaturalColumn: " ++ show x -- *** Column aliases type Column a = GenericColumn a (ColumnRepr a) (ColumnExposed a) type NumericColumn = GenericColumn Numeric Double Double type NominalColumn = GenericColumn Nominal Int String type BinaryColumn = GenericColumn Binary Bool Bool type NaturalColumn = GenericColumn Natural Int Int -- | Creates a column from a list of the displayed type. -- E.g. a 'Column Numeric' can be created from a '[Double]'. fromList :: (ColumnDataType dtype) => [ColumnExposed dtype] -> Fallible (Column dtype) fromList xs = do -- checking whether the column is empty if null xs then throwError EmptyColumn else return () -- checking the column invariant traverse columnInvariant xs return $ unsafeFromList xs -- | Creates a list of the displayed types from a column. -- E.g. a '[Double]' can be created from a 'Column Numeric'. toList :: (ColumnDataType a) => Column a -> [ColumnExposed a] toList col = fmap (exposure col) $ UVec.toList $ values col -- | Creates a column from a 'Data.Vector.Unboxed.Vector' of the representation type -- without checks. unsafeFromVector :: (Eq (ColumnExposed dtype), Eq (ColumnRepr dtype), UVec.Unbox repr) => UVec.Vector repr -> GenericColumn dtype repr repr unsafeFromVector !vec = GC { values = vec, exposure = id, columnNameGen = Nothing } -- | Creates a nominal column from a list of 'String's -- without checks. unsafeNominalColumn :: [String] -> Column Nominal unsafeNominalColumn xs = nominalColumnFromCategories catsVec vals where vals = UVec.fromList $ fmap (\x -> Set.findIndex x cats) xs catsVec = Vec.fromList $ Set.toAscList cats -- creating a list cats = Set.fromList xs -- | Creates a nominal column from a 'Vector' of nominal values and indexes marking that category -- without checks. nominalColumnFromCategories :: Vector String -> UVec.Vector Int -> Column Nominal nominalColumnFromCategories cats v = GC { values = v, exposure = \i -> cats Vec.! i, columnNameGen = Nothing } -- | Creates the distinct representation values in a nominal column. distinctValues :: NominalColumn -> [Int] distinctValues = Set.toList . Set.fromList . UVec.toList . values -- | Throws 'EmptyColumn' error when list is empty. checkNonEmptyColumn :: [a] -> Fallible () checkNonEmptyColumn xs = if null xs then throwError EmptyColumn else return () -- ** DataColumn -- | Dynamically typed column. -- The column type could be numeric, nominal, binary, or natural. data DataColumn = forall dtype repr exposed . (DataTypeClass dtype, ColumnDataType dtype, Typeable (GenericColumn dtype repr exposed), (ColumnExposed dtype) ~ exposed, (ColumnRepr dtype) ~ repr, PrettyPrintable exposed) => DC (GenericColumn dtype repr exposed) instance Eq DataColumn where (DC col1) == (DC col2) = case cast col1 of Just castedCol1 -> castedCol1 == col2 Nothing -> False instance ColumnClass DataColumn where columnSize (DC col) = columnSize col columnName (DC col) = columnName col nameColumn' name (DC col) = DC $ nameColumn' name col splitByFlags flags (DC col) = do (c1, c2) <- splitByFlags flags col return (DC c1, DC c2) -- | The type of the dynamic 'DataColumn'. columnType :: DataColumn -> DataType columnType (DC col) = atRuntime $ genColType col -- | Creates dynamically typed column from statically typed. asDataColumn :: (DataTypeClass dtype, ColumnDataType dtype, Typeable (GenericColumn dtype repr exposed), (ColumnExposed dtype) ~ exposed, (ColumnRepr dtype) ~ repr, PrettyPrintable exposed) => GenericColumn dtype repr exposed -> DataColumn asDataColumn = DC -- | Tries to creates statically typed column from dynamically typed. asColumn :: (ColumnDataType dtype) => DataColumn -> Fallible (Column dtype) asColumn (DC col) = maybe (Left CannotCast) Right (cast col) -- * Splitting by flags splitByFlagsRaw :: [Bool] -> RawColumn -> Fallible (RawColumn, RawColumn) splitByFlagsRaw flags col = do (c1, c2) <- splitByFlagsVec flags $ valuesRaw col return (setValuesRaw c1 col, setValuesRaw c2 col) splitByFlagsGen :: UVec.Unbox r => [Bool] -> GenericColumn a r e -> Fallible (GenericColumn a r e, GenericColumn a r e) splitByFlagsGen flags col = do (c1, c2) <- splitByFlagsUVec flags $ values col return $ (col { values = c1 }, col { values = c2 }) -- | Helper for column splitting. splitByFlagsVec :: [Bool] -> Vector a -> Fallible (Vector a, Vector a) splitByFlagsVec flags xs = if Vec.length xs1 /= 0 && Vec.length xs2 /= 0 then Right (xs1, xs2) else Left EmptyColumn where (xs1, xs2) = (Vec.map snd *** Vec.map snd) $ Vec.partition (\(flag, x) -> flag) $ Vec.zip vecFlags xs vecFlags = Vec.fromList $ take (Vec.length xs) flags -- | Helper for column splitting. splitByFlagsUVec :: UVec.Unbox a => [Bool] -> UVec.Vector a -> Fallible (UVec.Vector a, UVec.Vector a) splitByFlagsUVec flags xs = if UVec.length xs1 /= 0 && UVec.length xs2 /= 0 then Right (xs1, xs2) else Left EmptyColumn where (xs1, xs2) = (UVec.map snd *** UVec.map snd) $ UVec.partition (\(flag, x) -> flag) $ UVec.zip vecFlags xs vecFlags = UVec.fromList $ take (UVec.length xs) flags -- * Naming -- | Names a column. nameColumn :: ColumnClass c => ColumnName -> c -> Fallible c nameColumn name c = do validName <- validateName name return $ nameColumn' validName c -- | Validates a column name. validateName :: ColumnName -> Fallible ColumnName validateName name = if (Prelude.elem '_' name) then Left $ InvalidName $ "\"" ++ name ++ "\". Name cannot contain _" else (Right name) -- | Assigns the name to the column. copyName :: ColumnDataType b => Maybe ColumnName -> Column b -> Column b copyName colName to = to { columnNameGen = colName } -- * Transforming -- | Mapping to columns by the exposed type. mapColumnAtoB :: (ColumnDataType a, ColumnDataType b, ColumnExposed b ~ ColumnRepr b) => (ColumnExposed a -> ColumnExposed b) -> Column a -> Column b mapColumnAtoB f col = col { values = UVec.map (f . exposure col) (values col), exposure = id } -- * Helpers for pretty printing data PrettyPrintParams = PrettyPrintParams { numberOfDecimals :: Int , maxNumberOfLinesToShow :: Int , maxNumberOfColumnsInWindow :: Int } class PrettyPrintable a where prettyPrint :: a -> Reader PrettyPrintParams String data PrettyPrintableData = forall a. (PrettyPrintable a) => PPData a mkPrettyPrintable :: PrettyPrintable a => a -> PrettyPrintableData mkPrettyPrintable = PPData instance PrettyPrintable PrettyPrintableData where prettyPrint (PPData x) = prettyPrint x dataColumnToPrettyPrintables :: DataColumn -> Vector PrettyPrintableData dataColumnToPrettyPrintables (DC col) = columnToPrettyPrintables col columnToPrettyPrintables :: (ColumnDataType a, PrettyPrintable e, UVec.Unbox r) => GenericColumn a r e -> Vector PrettyPrintableData columnToPrettyPrintables col = Vec.map (mkPrettyPrintable . exposure col) $ UVec.convert (values col)
gaborhermann/marvin
src/Marvin/API/Table/Column.hs
apache-2.0
12,346
14
12
2,205
3,393
1,777
1,616
214
2
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RankNTypes #-} module Main (main) where import Control.Applicative import Control.Exception (catch) import Control.Lens import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Resource (runResourceT) import Data.List.NonEmpty (NonEmpty, nonEmpty) import Data.Conduit (Conduit, ($$)) import qualified Data.Conduit as C import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as Text import Data.Version (showVersion) import Options.Applicative import Prelude hiding (init, lines) import System.Exit (exitFailure) import qualified System.IO as IO import Text.Printf (printf) import Wybor (TTYException, selections, fromTexts, HasWybor(..)) import Paths_wybor_bin (version) main :: IO () main = do opts <- options ins <- inputs output opts ins data Options = Options { _visible, _height :: Maybe Int , _query, _prompt :: Maybe Text , _mode :: Mode , _endWith :: EndWith } newtype Mode = Mode (forall i m o. MonadIO m => (i -> Conduit i m o) -> Conduit i m o) newtype EndWith = EndWith (forall m. MonadIO m => Text -> m ()) options :: IO Options options = customExecParser (prefs showHelpOnError) parser where parser = info (helper <*> go) (fullDesc <> progDesc "CLI fuzzy text selector" <> header (printf "wybor - %s" (showVersion version))) go = Options <$> optional (option auto (long "visible" <> help "Choices to show")) <*> optional (option auto (long "height" <> help "Choice height in lines")) <*> optional (textOption (long "query" <> help "Initial query string")) <*> optional (textOption (long "prompt" <> help "Prompt string")) <*> flag single multi (long "multi" <> help "Multiple selections mode") <*> flag ln _0 (short '0' <> help "End the choice with the \\0 symbol and not a newline") single, multi :: Mode single = Mode (\f -> C.await >>= \case Nothing -> liftIO exitFailure; Just x -> f x) multi = Mode C.awaitForever ln = EndWith println _0 = EndWith print0 textOption :: Mod OptionFields String -> Parser Text textOption = fmap Text.pack . strOption inputs :: IO (NonEmpty Text) inputs = maybe exitFailure return . nonEmpty . Text.lines =<< Text.getContents output :: Options -> NonEmpty Text -> IO () output Options { _visible, _height, _query, _prompt, _mode = Mode f, _endWith = EndWith g } ins = do IO.hSetBuffering IO.stdout IO.LineBuffering runResourceT (selections alternatives $$ f g) `catchTTYException` \_ -> exitFailure where alternatives = fromTexts ins & visible %~ maybe id const _visible & height %~ maybe id const _height & prefix %~ maybe id const _prompt & initial %~ maybe id const _query catchTTYException :: IO a -> (TTYException -> IO a) -> IO a catchTTYException = catch println :: MonadIO m => Text -> m () println = liftIO . Text.putStrLn print0 :: MonadIO m => Text -> m () print0 m = liftIO $ do Text.putStr m; Text.putStr (Text.singleton '\0')
supki/wybor
example/wybor-bin/src/Main.hs
bsd-2-clause
3,223
0
18
767
1,057
562
495
73
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QTextCharFormat.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:35 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QTextCharFormat ( VerticalAlignment, eAlignNormal, eAlignSuperScript, eAlignSubScript, eAlignMiddle , UnderlineStyle, eNoUnderline, eSingleUnderline, eDashUnderline, eWaveUnderline, eSpellCheckUnderline ) where import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CVerticalAlignment a = CVerticalAlignment a type VerticalAlignment = QEnum(CVerticalAlignment Int) ieVerticalAlignment :: Int -> VerticalAlignment ieVerticalAlignment x = QEnum (CVerticalAlignment x) instance QEnumC (CVerticalAlignment Int) where qEnum_toInt (QEnum (CVerticalAlignment x)) = x qEnum_fromInt x = QEnum (CVerticalAlignment x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> VerticalAlignment -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eAlignNormal :: VerticalAlignment eAlignNormal = ieVerticalAlignment $ 0 eAlignSuperScript :: VerticalAlignment eAlignSuperScript = ieVerticalAlignment $ 1 eAlignSubScript :: VerticalAlignment eAlignSubScript = ieVerticalAlignment $ 2 eAlignMiddle :: VerticalAlignment eAlignMiddle = ieVerticalAlignment $ 3 instance QeAlignTop VerticalAlignment where eAlignTop = ieVerticalAlignment $ 4 instance QeAlignBottom VerticalAlignment where eAlignBottom = ieVerticalAlignment $ 5 data CUnderlineStyle a = CUnderlineStyle a type UnderlineStyle = QEnum(CUnderlineStyle Int) ieUnderlineStyle :: Int -> UnderlineStyle ieUnderlineStyle x = QEnum (CUnderlineStyle x) instance QEnumC (CUnderlineStyle Int) where qEnum_toInt (QEnum (CUnderlineStyle x)) = x qEnum_fromInt x = QEnum (CUnderlineStyle x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> UnderlineStyle -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eNoUnderline :: UnderlineStyle eNoUnderline = ieUnderlineStyle $ 0 eSingleUnderline :: UnderlineStyle eSingleUnderline = ieUnderlineStyle $ 1 eDashUnderline :: UnderlineStyle eDashUnderline = ieUnderlineStyle $ 2 instance QeDotLine UnderlineStyle where eDotLine = ieUnderlineStyle $ 3 instance QeDashDotLine UnderlineStyle where eDashDotLine = ieUnderlineStyle $ 4 instance QeDashDotDotLine UnderlineStyle where eDashDotDotLine = ieUnderlineStyle $ 5 eWaveUnderline :: UnderlineStyle eWaveUnderline = ieUnderlineStyle $ 6 eSpellCheckUnderline :: UnderlineStyle eSpellCheckUnderline = ieUnderlineStyle $ 7
uduki/hsQt
Qtc/Enums/Gui/QTextCharFormat.hs
bsd-2-clause
5,149
0
18
1,054
1,278
645
633
125
1
module Hyper.TreesExtra where import Hyper.Canvas import Hyper.Trees data EditTree a = EditTree { etTree :: (ZTree a) } deriving Show data Ord a => Heap a = Heap { hTree :: (BiTree a) } deriving Show newHeap :: Ord a => Heap a newHeap = Heap EmptyTree insert :: Ord a => Bool -> a -> Heap a -> Heap a insert b a (Heap t) = Heap (i a t) where i a (BiNode l v r) = if compare' a v then i v (BiNode l a r) else if shallow l > shallow r then BiNode l v (i a r) else BiNode (i a l) v r i a EmptyTree = leaf a compare' = if b then (<) else (>=) bottom' :: Ord a => (a -> b) -> (b -> b) -> Heap a -> ZTree b bottom' m f (Heap EmptyTree) = (fmap m . zTop) EmptyTree bottom' m f (Heap t) = recr (fmap m (zTop t)) where recr (ZTree t c) = case t of BiNode l _ r -> if shallow l > shallow r then (recr . ztRight . ztModify f) (ZTree t c) else (recr . ztLeft . ztModify f) (ZTree t c) _ -> ztModify f (ZTree t c) bottomBy :: (a -> Bool) -> BiTree a -> ZTree a bottomBy base EmptyTree = zTop EmptyTree bottomBy base t = recr (zTop t) where recr (ZTree t c) = case t of BiNode l v r -> if base v then ZTree t c else if shallowBy base l > shallowBy base r then (recr . ztRight) (ZTree t c) else (recr . ztLeft) (ZTree t c) _ -> ztUp (ZTree t c) bottom :: Ord a => Heap a -> ZTree a bottom h = bottom' id id h shallowBy :: (a -> Bool) -> BiTree a -> Int shallowBy _ EmptyTree = 0 shallowBy base (BiNode l v r) = if base v then 0 else (min (shallowBy base l) (shallowBy base r)) + 1 depthBy :: (a -> Bool) -> BiTree a -> Int depthBy _ EmptyTree = 0 depthBy base (BiNode l v r) = if base v then 0 else (max (depthBy base l) (depthBy base r)) + 1 lastElemBy :: (a -> Bool) -> BiTree a -> ZTree a lastElemBy base t = recr (zTop t) where recr (ZTree t c) = case t of BiNode l v r -> if base v then ztUp (ZTree t c) else if depthBy base r >= depthBy base l then (recr . ztRight) (ZTree t c) else (recr . ztLeft) (ZTree t c) _ -> ztUp (ZTree t c) lastElem :: Ord a => Heap a -> ZTree a lastElem (Heap t) = recr (zTop t) where recr (ZTree t c) = case t of BiNode l _ r -> if depth r >= depth l then (recr . ztRight) (ZTree t c) else (recr . ztLeft) (ZTree t c) _ -> ztUp (ZTree t c) upHeap :: (a -> a) -> EditTree a -> EditTree a upHeap mark (EditTree (ZTree (BiNode l v r) c)) = case c of L u k p -> (EditTree . ztUp) (ZTree (BiNode l (mark u) r) (L v k p)) R s u k -> (EditTree . ztUp) (ZTree (BiNode l (mark u) r) (R s v k)) Top -> EditTree (ZTree (BiNode l v r) Top) upHeap _ et = et -- Nothing happens if you try to upHeap an EmptyTree upHeapZ :: (a -> a) -> ZTree a -> ZTree a upHeapZ mark (ZTree (BiNode l v r) c) = case c of L u k p -> (ztUp) (ZTree (BiNode l (mark u) r) (L v k p)) R s u k -> (ztUp) (ZTree (BiNode l (mark u) r) (R s v k)) Top -> ZTree (BiNode l v r) Top upHeapZ _ et = et -- Nothing happens if you try to upHeap an EmptyTree downHeapL :: (a -> a) -> EditTree a -> EditTree a downHeapL mark (EditTree (ZTree (BiNode (BiNode l u p) v r) c)) = (EditTree . ztLeft) (ZTree (BiNode (BiNode l v p) (mark u) r) c) downHeapL _ et = et downHeapLZ :: (a -> a) -> ZTree a -> ZTree a downHeapLZ mark (ZTree (BiNode (BiNode l u p) v r) c) = ztLeft (ZTree (BiNode (BiNode l v p) (mark u) r) c) downHeapLZ _ et = et downHeapR :: (a -> a) -> EditTree a -> EditTree a downHeapR mark (EditTree (ZTree (BiNode l v (BiNode s u r)) c)) = (EditTree . ztRight) (ZTree (BiNode l (mark u) (BiNode s v r)) c) downHeapR _ et = et downHeapRZ :: (a -> a) -> ZTree a -> ZTree a downHeapRZ mark (ZTree (BiNode l v (BiNode s u r)) c) = ztRight (ZTree (BiNode l (mark u) (BiNode s v r)) c) downHeapRZ _ et = et type NodeForm a = (ZTree a -> (HyperForm, LineForm)) type LineForm = (Location -> HyperForm) type Embedding a = (ZTree a -> Location) toForm :: BoundingBox -> Embedding a -> NodeForm a -> BiTree a -> HyperForm toForm bb a b c = nextNode bb a b (zTop c) nextNode :: BoundingBox -> Embedding a -> NodeForm a -> ZTree a -> HyperForm nextNode bb findLoc nodeForm zt = case zt of ZTree (BiNode _ _ _) _ -> let loc = bb * findLoc zt lineDest = bb * findLoc (ztUp zt) - loc (node,lineF) = nodeForm zt line = lineF lineDest next = nextNode bb findLoc nodeForm in combine [translate loc line ,next (ztLeft zt) ,next (ztRight zt) ,fit loc ((0.7,0.7) * bb) node] _ -> blank class DrawableNode n where nodeForm :: n -> (HyperForm, LineForm) instance DrawableNode a => DrawableNode (ZTree a) where nodeForm (ZTree (BiNode _ v _) _) = nodeForm v nodeForm _ = (blank, const blank) zDepthOf :: ZTree a -> Int zDepthOf (ZTree _ Top) = 1 zDepthOf t = ((+1) . zDepthOf . ztUp) t zFindLoc :: ZTree a -> Location zFindLoc tree = (fromIntegral (findX tree) ,fromIntegral (zDepthOf tree - 1)) findX :: ZTree a -> Int findX zt = case zt of ZTree (BiNode l _ r) Top -> let lsubtree = (zTree . ztLeft) zt initXIndex = 0 in nextX initXIndex lsubtree ZTree (BiNode l _ r) (L _ _ _) -> let rsubtree = (zTree . ztRight) zt initXIndex = 0 in findX (ztUp zt) - nextX initXIndex rsubtree - 1 ZTree (BiNode l _ r) (R _ _ _) -> let lsubtree = (zTree . ztLeft) zt initXIndex = 0 in findX (ztUp zt) + nextX initXIndex lsubtree + 1 where nextX :: Int -> BiTree a -> Int nextX x (BiNode EmptyTree _ EmptyTree) = x + 1 -- leaf node case nextX x EmptyTree = x -- absent child case nextX x (BiNode l _ r) = let x' = nextX x l in nextX (x' + 1) r
RoboNickBot/interactive-tree-demos
src/Hyper/TreesExtra.hs
bsd-2-clause
6,404
0
16
2,292
2,979
1,485
1,494
159
5
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} module Models where import Control.Monad.Reader.Class import Control.Monad.IO.Class import Data.Aeson import Database.Persist.Sql import Database.Persist.TH (share, mkPersist, sqlSettings, mkMigrate, persistLowerCase) import Data.Text (Text) import Config share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User json name Text password Text UniqueUser name ApiKey json userId UserId accessKey Text secretKey Text UniqueApiKey accessKey |] doMigrations :: SqlPersistT IO () doMigrations = runMigration migrateAll runDB :: (MonadReader Config m, MonadIO m) => SqlPersistT IO b -> m b runDB query = do pool <- asks getPool liftIO $ runSqlPool query pool
tlaitinen/servant-cookie-hmac-auth-example
src/Models.hs
bsd-3-clause
1,273
0
8
390
183
106
77
26
1
module Kendo.Lexer where import Control.Monad.State import Text.Parsec hiding (State) import Text.Parsec.Indent import Text.Parsec.Pos (SourcePos) import qualified Text.Parsec.Token as P type Parser a = IndentParser String () a reservedNames = [ "true" , "false" , "data" , "type" , "import" , "infixl" , "infixr" , "infix" , "class" , "instance" , "module" , "case" , "of" , "if" , "then" , "else" , "do" , "let" , "in" , "where" , "infixl" , "infixr" , "infix" ] reservedOps = [ "::" , ".." , "=" , "\\" , "|" , "<-" , "->" , "@" , "~" , "=>" ] identLetter, identStart, opLetter :: Parser Char identLetter = alphaNum <|> oneOf "_'" identStart = letter <|> char '_' opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~" lexerConfig :: P.GenLanguageDef String () (State SourcePos) lexerConfig = P.LanguageDef { P.commentStart = "" , P.commentEnd = "" , P.commentLine = "--" , P.nestedComments = False , P.identStart = identStart , P.identLetter = identLetter , P.opStart = P.opLetter lexerConfig , P.opLetter = opLetter , P.reservedOpNames = reservedOps , P.reservedNames = reservedNames , P.caseSensitive = True } lexer :: P.GenTokenParser String () (State SourcePos) lexer = P.makeTokenParser lexerConfig reserved = P.reserved lexer reservedOp = P.reservedOp lexer parens = P.parens lexer brackets = P.brackets lexer braces = P.braces lexer commaSep = P.commaSep lexer commaSep1 = P.commaSep1 lexer semi = P.semi lexer integer = P.integer lexer chr = P.charLiteral lexer str = P.stringLiteral lexer operator = P.operator lexer dot = P.dot lexer whiteSpace = P.whiteSpace lexer lexeme = P.lexeme lexer underscore :: Parser () underscore = reserved "_" ident :: Parser Char -> Parser String ident start = lexeme ((:) <$> start <*> many identLetter) upperIdent :: Parser String upperIdent = ident upper identifier :: Parser String identifier = do name <- ident $ lower <|> (oneOf "_" <* notFollowedBy whiteSpace) if name `elem` reservedNames then unexpected $ "reserved word " ++ show name else return name
jetho/kendo
src/Kendo/Lexer.hs
bsd-3-clause
2,329
0
11
651
672
376
296
88
2
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell import Prelude hiding (gcd, mod) import Language.Haskell.Liquid.Prelude [lq| mod :: a:Nat -> b:{v:Nat| ((v < a) && (v > 0))} -> {v:Nat | v < b} |] mod :: Int -> Int -> Int mod a b | a - b > b = mod (a - b) b | a - b < b = a - b | a - b == b = 0 [lq| gcd :: a:Nat -> b:{v:Nat | v < a} -> Int |] gcd :: Int -> Int -> Int gcd a 0 = a gcd a b = gcd b (a `mod` b) [lq| gcd' :: a:Nat -> b:Nat -> Nat / [a, b] |] gcd' :: Int -> Int -> Int gcd' a b | a == 0 = b | b == 0 = a | a == b = a | a > b = gcd' (a - b) b | a < b = gcd' a (b - a)
spinda/liquidhaskell
tests/gsoc15/unknown/pos/GCD.hs
bsd-3-clause
645
5
9
232
311
155
156
20
1
module Test ( A(..) , B(C) , z , x , y ) where
hecrj/haskell-format
test/specs/module-export/output.hs
bsd-3-clause
71
0
5
38
29
20
9
8
0
{-# LANGUAGE GADTs #-} -- | -- Module : Data.Array.Accelerate.Trafo.Normalise -- Copyright : [2012] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module Data.Array.Accelerate.Trafo.Normalise ( anormalise ) where import Prelude hiding ( exp ) import Data.Array.Accelerate.AST import Data.Array.Accelerate.Tuple import Data.Array.Accelerate.Trafo.Substitution -- Convert to Administrative Normal (a-normal) Form, where lets-within-lets of -- an expression are flattened. -- -- let x = -- let y = e1 in e2 -- in e3 -- -- ==> -- -- let y = e1 in -- let x = e2 -- in e3 -- anormalise :: OpenExp env aenv t -> OpenExp env aenv t anormalise = cvt where split1 :: Idx (env, a) t -> Idx ((env, s), a) t split1 ZeroIdx = ZeroIdx split1 (SuccIdx ix) = SuccIdx (SuccIdx ix) cvtA :: OpenAcc aenv a -> OpenAcc aenv a cvtA = id cvtT :: Tuple (OpenExp env aenv) t -> Tuple (OpenExp env aenv) t cvtT NilTup = NilTup cvtT (SnocTup t e) = cvtT t `SnocTup` cvt e cvtF :: OpenFun env aenv f -> OpenFun env aenv f cvtF (Body e) = Body (cvt e) cvtF (Lam f) = Lam (cvtF f) cvt :: OpenExp env aenv e -> OpenExp env aenv e cvt exp = case exp of Let bnd body -> let bnd' = cvt bnd body' = cvt body in case bnd' of Let bnd'' body'' -> Let bnd'' $ Let body'' (weakenByE split1 body') _ -> Let bnd' body' -- Var ix -> Var ix Const c -> Const c Tuple tup -> Tuple (cvtT tup) Prj tup ix -> Prj tup (cvt ix) IndexNil -> IndexNil IndexCons sh sz -> IndexCons (cvt sh) (cvt sz) IndexHead sh -> IndexHead (cvt sh) IndexTail sh -> IndexTail (cvt sh) IndexAny -> IndexAny IndexSlice x ix sh -> IndexSlice x (cvt ix) (cvt sh) IndexFull x ix sl -> IndexFull x (cvt ix) (cvt sl) ToIndex sh ix -> ToIndex (cvt sh) (cvt ix) FromIndex sh ix -> FromIndex (cvt sh) (cvt ix) Cond p t e -> Cond (cvt p) (cvt t) (cvt e) Iterate n f x -> Iterate n (cvtF f) (cvt x) PrimConst c -> PrimConst c PrimApp f x -> PrimApp f (cvt x) Index a sh -> Index (cvtA a) (cvt sh) LinearIndex a i -> LinearIndex (cvtA a) (cvt i) Shape a -> Shape (cvtA a) ShapeSize sh -> ShapeSize (cvt sh) Intersect s t -> Intersect (cvt s) (cvt t)
robeverest/accelerate
Data/Array/Accelerate/Trafo/Normalise.hs
bsd-3-clause
2,957
0
18
1,151
929
462
467
51
27
module App.Roster.RosterGeneration (generateInitialRoster, generateNextRoster, generatePreviousRoster) where import App.Helper.Lists(splitInHalf, replaceIndex, rotate) -- Roster generation algorthm based on: -- https://en.wikipedia.org/wiki/Round-robin_tournament#Scheduling_algorithm -- http://stackoverflow.com/questions/41896889/algorithm-to-schedule-people-to-an-activity-that-should-be-done-in-pairs -- Empty value is provided in case of an odd number of elements. generateInitialRoster :: [a] -> a -> [(a,a)] generateInitialRoster list emptyValue | isOdd $ length list = getRosterFromList $ list ++ [emptyValue] | otherwise = getRosterFromList list -- Given the current roster, generates another permutation. generateNextRoster :: [(a,a)] -> [(a,a)] -- given (1,4)(2,5)(3,6) generateNextRoster roster = let (l1, l2) = unzip roster -- [1,2,3][4,5,6] head:xs = l1 ++ (reverse l2) -- 1 : [2,3,6,5,4] rotatedList = head:(rotate 1 xs) -- [1,3,6,5,4,2] (newL1, newL2) = splitInHalf rotatedList -- ([1,3,6],[5,4,2]) in zip newL1 (reverse newL2) -- (1,2)(3,4)(6,5) -- Given the current roster, generates the previous permutation. generatePreviousRoster :: [(a,a)] -> [(a,a)] -- given (1,2)(3,4)(6,5) generatePreviousRoster roster = let (l1, l2) = unzip roster -- [1,3,6][2,4,5] head:xs = l1 ++ (reverse l2) -- 1 : [3,6,5,4,2] rotatedList = head:(rotate (-1) xs) -- [1,2,3,6,5,4] (newL1, newL2) = splitInHalf rotatedList -- ([1,2,3],[6,5,4]) in zip newL1 (reverse newL2) -- (1,4)(2,5)(3,6) -- private functions getRosterFromList :: [a] -> [(a,a)] getRosterFromList list = let (l1, l2) = splitInHalf list in zip l1 l2 isOdd :: Int -> Bool isOdd n = n `mod` 2 == 1
afcastano/cafe-duty
src/App/Roster/RosterGeneration.hs
bsd-3-clause
2,178
0
13
728
450
251
199
23
1
-- | 'IntPSQ' fixes the key type to 'Int'. It is generally much faster than -- an 'OrdPSQ'. -- -- Many operations have a worst-case complexity of O(min(n,W)). This means that -- the operation can -- become linear in the number of elements with a maximum -- of W -- the number of bits in an Int (32 or 64). {-# LANGUAGE CPP #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE UnboxedTuples #-} module Data.IntPSQ ( -- * Type IntPSQ -- * Query , null , size , member , lookup , findMin -- * Construction , empty , singleton -- * Insertion , insert -- * Delete/update , delete , deleteMin , alter , alterMin -- * Lists , fromList , toList , keys -- * Views , insertView , deleteView , minView , atMostView -- * Traversal , map , unsafeMapMonotonic , fold' -- * Unsafe operations , unsafeInsertNew , unsafeInsertIncreasePriority , unsafeInsertIncreasePriorityView , unsafeInsertWithIncreasePriority , unsafeInsertWithIncreasePriorityView , unsafeLookupIncreasePriority -- * Validity check , valid ) where import Prelude hiding (lookup, map, filter, foldr, foldl, null) import Data.IntPSQ.Internal
bttr/psqueues
src/Data/IntPSQ.hs
bsd-3-clause
1,314
0
5
405
147
104
43
37
0
{-# LANGUAGE BangPatterns #-} module Y2017.Day10 (answer1, answer2, knotHash, showHex, toBytes) where import GHC.Word import qualified Numeric import Data.List.Split (chunksOf) import Data.Bits import Data.Char import qualified Data.Vector as V import Data.Monoid answer1 :: IO () answer1 = let (_, _, v) = foldl hashStep (0, 0, V.fromList [0 .. 255]) input in print $ (v V.! 0) * (v V.! 1) answer2 :: IO () answer2 = putStrLn $ knotHash input2 hashStep :: (Int, Int, V.Vector Int) -> Int -> (Int, Int, V.Vector Int) hashStep (!skip, pos, !v) l = let n = V.length v (v1, v2) = V.splitAt pos v v' = V.reverse $ V.take l $ v2 <> v1 us = [ ((i + pos) `mod` n, v' V.! i) | i <- [0 .. l - 1] ] in (skip + 1, (pos + skip + l) `mod` n, v V.// us) hash :: V.Vector Int -> [Int] -> V.Vector Int hash v l = third $ foldl round (0, 0, v) [0 .. 63] where round r _ = foldl hashStep r l third (_, _, x) = x densify :: [Word8] -> [Word8] densify l = foldl1 xor <$> chunksOf 16 l knotHash :: String -> String knotHash s = let bytesIn = toBytes s ++ [17, 31, 73, 47, 23] bytesOut = map fromIntegral $ V.toList $ hash (V.fromList [0 .. 255]) (map fromIntegral bytesIn) dense = densify bytesOut in concatMap showHex dense showHex :: (Integral a, Show a) => a -> String showHex w = case Numeric.showHex w "" of [x] -> '0' : [x] x -> x toBytes :: String -> [Word8] toBytes = map (fromIntegral . ord) input :: [Int] input = [199, 0, 255, 136, 174, 254, 227, 16, 51, 85, 1, 2, 22, 17, 7, 192] input2 :: String input2 = "199,0,255,136,174,254,227,16,51,85,1,2,22,17,7,192" test :: [Int] test = [3, 4, 1, 5]
geekingfrog/advent-of-code
src/Y2017/Day10.hs
bsd-3-clause
1,728
0
13
456
815
454
361
48
2
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, UndecidableInstances, TypeOperators #-} module Numeric.Algebra.Class ( -- * Multiplicative Semigroups Multiplicative(..) , pow1pIntegral , product1 -- * Semirings , Semiring -- * Left and Right Modules , LeftModule(..) , RightModule(..) , Module -- * Additive Monoids , Monoidal(..) , sum , sinnumIdempotent -- * Associative algebras , Algebra(..) -- * Coassociative coalgebras , Coalgebra(..) ) where import Data.Foldable hiding (sum, concat) import Data.Int import Data.IntMap (IntMap) import Data.IntSet (IntSet) import Data.Map (Map) import Data.Monoid (mappend) -- import Data.Semigroup.Foldable import Data.Sequence hiding (reverse,index) import Data.Semigroup.Foldable import Data.Set (Set) import Data.Word import Numeric.Additive.Class import Numeric.Natural import Prelude hiding ((*), (+), negate, subtract,(-), recip, (/), foldr, sum, product, replicate, concat) import qualified Data.IntMap as IntMap import qualified Data.IntSet as IntSet import qualified Data.Map as Map import qualified Data.Sequence as Seq import qualified Data.Set as Set import qualified Prelude infixr 8 `pow1p` infixl 7 *, .*, *. -- | A multiplicative semigroup class Multiplicative r where (*) :: r -> r -> r -- class Multiplicative r => PowerAssociative r where -- pow1p x n = pow x (1 + n) pow1p :: r -> Natural -> r pow1p x0 y0 = f x0 (y0 Prelude.+ 1) where f x y | even y = f (x * x) (y `quot` 2) | y == 1 = x | otherwise = g (x * x) ((y Prelude.- 1) `quot` 2) x g x y z | even y = g (x * x) (y `quot` 2) z | y == 1 = x * z | otherwise = g (x * x) ((y Prelude.- 1) `quot` 2) (x * z) -- class PowerAssociative r => Assocative r where productWith1 :: Foldable1 f => (a -> r) -> f a -> r productWith1 f = maybe (error "Numeric.Multiplicative.Semigroup.productWith1: empty structure") id . foldl' mf Nothing where mf Nothing y = Just $! f y mf (Just x) y = Just $! x * f y product1 :: (Foldable1 f, Multiplicative r) => f r -> r product1 = productWith1 id pow1pIntegral :: (Integral r, Integral n) => r -> n -> r pow1pIntegral r n = r ^ (1 Prelude.+ n) instance Multiplicative Bool where (*) = (&&) pow1p m _ = m instance Multiplicative Natural where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Integer where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Int where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Int8 where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Int16 where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Int32 where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Int64 where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Word where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Word8 where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Word16 where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Word32 where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative Word64 where (*) = (Prelude.*) pow1p = pow1pIntegral instance Multiplicative () where _ * _ = () pow1p _ _ = () instance (Multiplicative a, Multiplicative b) => Multiplicative (a,b) where (a,b) * (c,d) = (a * c, b * d) instance (Multiplicative a, Multiplicative b, Multiplicative c) => Multiplicative (a,b,c) where (a,b,c) * (i,j,k) = (a * i, b * j, c * k) instance (Multiplicative a, Multiplicative b, Multiplicative c, Multiplicative d) => Multiplicative (a,b,c,d) where (a,b,c,d) * (i,j,k,l) = (a * i, b * j, c * k, d * l) instance (Multiplicative a, Multiplicative b, Multiplicative c, Multiplicative d, Multiplicative e) => Multiplicative (a,b,c,d,e) where (a,b,c,d,e) * (i,j,k,l,m) = (a * i, b * j, c * k, d * l, e * m) instance Algebra r a => Multiplicative (a -> r) where f * g = mult $ \a b -> f a * g b -- | A pair of an additive abelian semigroup, and a multiplicative semigroup, with the distributive laws: -- -- > a(b + c) = ab + ac -- left distribution (we are a LeftNearSemiring) -- > (a + b)c = ac + bc -- right distribution (we are a [Right]NearSemiring) -- -- Common notation includes the laws for additive and multiplicative identity in semiring. -- -- If you want that, look at 'Rig' instead. -- -- Ideally we'd use the cyclic definition: -- -- > class (LeftModule r r, RightModule r r, Additive r, Abelian r, Multiplicative r) => Semiring r -- -- to enforce that every semiring r is an r-module over itself, but Haskell doesn't like that. class (Additive r, Abelian r, Multiplicative r) => Semiring r instance Semiring Integer instance Semiring Natural instance Semiring Bool instance Semiring Int instance Semiring Int8 instance Semiring Int16 instance Semiring Int32 instance Semiring Int64 instance Semiring Word instance Semiring Word8 instance Semiring Word16 instance Semiring Word32 instance Semiring Word64 instance Semiring () instance (Semiring a, Semiring b) => Semiring (a, b) instance (Semiring a, Semiring b, Semiring c) => Semiring (a, b, c) instance (Semiring a, Semiring b, Semiring c, Semiring d) => Semiring (a, b, c, d) instance (Semiring a, Semiring b, Semiring c, Semiring d, Semiring e) => Semiring (a, b, c, d, e) instance Algebra r a => Semiring (a -> r) -- | An associative algebra built with a free module over a semiring class Semiring r => Algebra r a where mult :: (a -> a -> r) -> a -> r instance Algebra () a where mult _ _ = () -- | The tensor algebra instance Semiring r => Algebra r [a] where mult f = go [] where go ls rrs@(r:rs) = f (reverse ls) rrs + go (r:ls) rs go ls [] = f (reverse ls) [] -- | The tensor algebra instance Semiring r => Algebra r (Seq a) where mult f = go Seq.empty where go ls s = case viewl s of EmptyL -> f ls s r :< rs -> f ls s + go (ls |> r) rs instance Semiring r => Algebra r () where mult f = f () instance (Semiring r, Ord a) => Algebra r (Set a) where mult f = go Set.empty where go ls s = case Set.minView s of Nothing -> f ls s Just (r, rs) -> f ls s + go (Set.insert r ls) rs instance Semiring r => Algebra r IntSet where mult f = go IntSet.empty where go ls s = case IntSet.minView s of Nothing -> f ls s Just (r, rs) -> f ls s + go (IntSet.insert r ls) rs instance (Semiring r, Monoidal r, Ord a, Partitionable b) => Algebra r (Map a b) -- where -- mult f xs = case minViewWithKey xs of -- Nothing -> zero -- Just ((k, r), rs) -> ... instance (Semiring r, Monoidal r, Partitionable a) => Algebra r (IntMap a) instance (Algebra r a, Algebra r b) => Algebra r (a,b) where mult f (a,b) = mult (\a1 a2 -> mult (\b1 b2 -> f (a1,b1) (a2,b2)) b) a instance (Algebra r a, Algebra r b, Algebra r c) => Algebra r (a,b,c) where mult f (a,b,c) = mult (\a1 a2 -> mult (\b1 b2 -> mult (\c1 c2 -> f (a1,b1,c1) (a2,b2,c2)) c) b) a instance (Algebra r a, Algebra r b, Algebra r c, Algebra r d) => Algebra r (a,b,c,d) where mult f (a,b,c,d) = mult (\a1 a2 -> mult (\b1 b2 -> mult (\c1 c2 -> mult (\d1 d2 -> f (a1,b1,c1,d1) (a2,b2,c2,d2)) d) c) b) a instance (Algebra r a, Algebra r b, Algebra r c, Algebra r d, Algebra r e) => Algebra r (a,b,c,d,e) where mult f (a,b,c,d,e) = mult (\a1 a2 -> mult (\b1 b2 -> mult (\c1 c2 -> mult (\d1 d2 -> mult (\e1 e2 -> f (a1,b1,c1,d1,e1) (a2,b2,c2,d2,e2)) e) d) c) b) a -- incoherent -- instance (Algebra r b, Algebra r a) => Algebra (b -> r) a where mult f a b = mult (\a1 a2 -> f a1 a2 b) a -- A coassociative coalgebra over a semiring using class Semiring r => Coalgebra r c where comult :: (c -> r) -> c -> c -> r -- | Every coalgebra gives rise to an algebra by vector space duality classically. -- Sadly, it requires vector space duality, which we cannot use constructively. -- The dual argument only relies in the fact that any constructive coalgebra can only inspect a finite number of coefficients, -- which we CAN exploit. instance Algebra r m => Coalgebra r (m -> r) where comult k f g = k (f * g) -- instance Coalgebra () c where comult _ _ _ = () -- instance (Algebra r b, Coalgebra r c) => Coalgebra (b -> r) c where comult f c1 c2 b = comult (`f` b) c1 c2 instance Semiring r => Coalgebra r () where comult = const instance (Coalgebra r a, Coalgebra r b) => Coalgebra r (a, b) where comult f (a1,b1) (a2,b2) = comult (\a -> comult (\b -> f (a,b)) b1 b2) a1 a2 instance (Coalgebra r a, Coalgebra r b, Coalgebra r c) => Coalgebra r (a, b, c) where comult f (a1,b1,c1) (a2,b2,c2) = comult (\a -> comult (\b -> comult (\c -> f (a,b,c)) c1 c2) b1 b2) a1 a2 instance (Coalgebra r a, Coalgebra r b, Coalgebra r c, Coalgebra r d) => Coalgebra r (a, b, c, d) where comult f (a1,b1,c1,d1) (a2,b2,c2,d2) = comult (\a -> comult (\b -> comult (\c -> comult (\d -> f (a,b,c,d)) d1 d2) c1 c2) b1 b2) a1 a2 instance (Coalgebra r a, Coalgebra r b, Coalgebra r c, Coalgebra r d, Coalgebra r e) => Coalgebra r (a, b, c, d, e) where comult f (a1,b1,c1,d1,e1) (a2,b2,c2,d2,e2) = comult (\a -> comult (\b -> comult (\c -> comult (\d -> comult (\e -> f (a,b,c,d,e)) e1 e2) d1 d2) c1 c2) b1 b2) a1 a2 -- | The tensor Hopf algebra instance Semiring r => Coalgebra r [a] where comult f as bs = f (mappend as bs) -- | The tensor Hopf algebra instance Semiring r => Coalgebra r (Seq a) where comult f as bs = f (mappend as bs) -- | the free commutative band coalgebra instance (Semiring r, Ord a) => Coalgebra r (Set a) where comult f as bs = f (Set.union as bs) -- | the free commutative band coalgebra over Int instance Semiring r => Coalgebra r IntSet where comult f as bs = f (IntSet.union as bs) -- | the free commutative coalgebra over a set and a given semigroup instance (Semiring r, Ord a, Additive b) => Coalgebra r (Map a b) where comult f as bs = f (Map.unionWith (+) as bs) -- | the free commutative coalgebra over a set and Int instance (Semiring r, Additive b) => Coalgebra r (IntMap b) where comult f as bs = f (IntMap.unionWith (+) as bs) class (Semiring r, Additive m) => LeftModule r m where (.*) :: r -> m -> m instance LeftModule Natural Bool where 0 .* _ = False _ .* a = a instance LeftModule Natural Natural where (.*) = (*) instance LeftModule Natural Integer where n .* m = toInteger n * m instance LeftModule Integer Integer where (.*) = (*) instance LeftModule Natural Int where (.*) = (*) . fromIntegral instance LeftModule Integer Int where (.*) = (*) . fromInteger instance LeftModule Natural Int8 where (.*) = (*) . fromIntegral instance LeftModule Integer Int8 where (.*) = (*) . fromInteger instance LeftModule Natural Int16 where (.*) = (*) . fromIntegral instance LeftModule Integer Int16 where (.*) = (*) . fromInteger instance LeftModule Natural Int32 where (.*) = (*) . fromIntegral instance LeftModule Integer Int32 where (.*) = (*) . fromInteger instance LeftModule Natural Int64 where (.*) = (*) . fromIntegral instance LeftModule Integer Int64 where (.*) = (*) . fromInteger instance LeftModule Natural Word where (.*) = (*) . fromIntegral instance LeftModule Integer Word where (.*) = (*) . fromInteger instance LeftModule Natural Word8 where (.*) = (*) . fromIntegral instance LeftModule Integer Word8 where (.*) = (*) . fromInteger instance LeftModule Natural Word16 where (.*) = (*) . fromIntegral instance LeftModule Integer Word16 where (.*) = (*) . fromInteger instance LeftModule Natural Word32 where (.*) = (*) . fromIntegral instance LeftModule Integer Word32 where (.*) = (*) . fromInteger instance LeftModule Natural Word64 where (.*) = (*) . fromIntegral instance LeftModule Integer Word64 where (.*) = (*) . fromInteger instance Semiring r => LeftModule r () where _ .* _ = () instance LeftModule r m => LeftModule r (e -> m) where (.*) m f e = m .* f e instance Additive m => LeftModule () m where _ .* a = a instance (LeftModule r a, LeftModule r b) => LeftModule r (a, b) where n .* (a, b) = (n .* a, n .* b) instance (LeftModule r a, LeftModule r b, LeftModule r c) => LeftModule r (a, b, c) where n .* (a, b, c) = (n .* a, n .* b, n .* c) instance (LeftModule r a, LeftModule r b, LeftModule r c, LeftModule r d) => LeftModule r (a, b, c, d) where n .* (a, b, c, d) = (n .* a, n .* b, n .* c, n .* d) instance (LeftModule r a, LeftModule r b, LeftModule r c, LeftModule r d, LeftModule r e) => LeftModule r (a, b, c, d, e) where n .* (a, b, c, d, e) = (n .* a, n .* b, n .* c, n .* d, n .* e) class (Semiring r, Additive m) => RightModule r m where (*.) :: m -> r -> m instance RightModule Natural Bool where _ *. 0 = False a *. _ = a instance RightModule Natural Natural where (*.) = (*) instance RightModule Natural Integer where n *. m = n * fromIntegral m instance RightModule Integer Integer where (*.) = (*) instance RightModule Natural Int where m *. n = m * fromIntegral n instance RightModule Integer Int where m *. n = m * fromInteger n instance RightModule Natural Int8 where m *. n = m * fromIntegral n instance RightModule Integer Int8 where m *. n = m * fromInteger n instance RightModule Natural Int16 where m *. n = m * fromIntegral n instance RightModule Integer Int16 where m *. n = m * fromInteger n instance RightModule Natural Int32 where m *. n = m * fromIntegral n instance RightModule Integer Int32 where m *. n = m * fromInteger n instance RightModule Natural Int64 where m *. n = m * fromIntegral n instance RightModule Integer Int64 where m *. n = m * fromInteger n instance RightModule Natural Word where m *. n = m * fromIntegral n instance RightModule Integer Word where m *. n = m * fromInteger n instance RightModule Natural Word8 where m *. n = m * fromIntegral n instance RightModule Integer Word8 where m *. n = m * fromInteger n instance RightModule Natural Word16 where m *. n = m * fromIntegral n instance RightModule Integer Word16 where m *. n = m * fromInteger n instance RightModule Natural Word32 where m *. n = m * fromIntegral n instance RightModule Integer Word32 where m *. n = m * fromInteger n instance RightModule Natural Word64 where m *. n = m * fromIntegral n instance RightModule Integer Word64 where m *. n = m * fromInteger n instance Semiring r => RightModule r () where _ *. _ = () instance RightModule r m => RightModule r (e -> m) where (*.) f m e = f e *. m instance Additive m => RightModule () m where (*.) = const instance (RightModule r a, RightModule r b) => RightModule r (a, b) where (a, b) *. n = (a *. n, b *. n) instance (RightModule r a, RightModule r b, RightModule r c) => RightModule r (a, b, c) where (a, b, c) *. n = (a *. n, b *. n, c *. n) instance (RightModule r a, RightModule r b, RightModule r c, RightModule r d) => RightModule r (a, b, c, d) where (a, b, c, d) *. n = (a *. n, b *. n, c *. n, d *. n) instance (RightModule r a, RightModule r b, RightModule r c, RightModule r d, RightModule r e) => RightModule r (a, b, c, d, e) where (a, b, c, d, e) *. n = (a *. n, b *. n, c *. n, d *. n, e *. n) class (LeftModule r m, RightModule r m) => Module r m instance (LeftModule r m, RightModule r m) => Module r m -- | An additive monoid -- -- > zero + a = a = a + zero class (LeftModule Natural m, RightModule Natural m) => Monoidal m where zero :: m sinnum :: Natural -> m -> m sinnum 0 _ = zero sinnum n x0 = f x0 n where f x y | even y = f (x + x) (y `quot` 2) | y == 1 = x | otherwise = g (x + x) (pred y `quot` 2) x g x y z | even y = g (x + x) (y `quot` 2) z | y == 1 = x + z | otherwise = g (x + x) (pred y `quot` 2) (x + z) sumWith :: Foldable f => (a -> m) -> f a -> m sumWith f = foldl' (\b a -> b + f a) zero sum :: (Foldable f, Monoidal m) => f m -> m sum = sumWith id sinnumIdempotent :: (Integral n, Idempotent r, Monoidal r) => n -> r -> r sinnumIdempotent 0 _ = zero sinnumIdempotent _ x = x instance Monoidal Bool where zero = False sinnum 0 _ = False sinnum _ r = r instance Monoidal Natural where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Integer where zero = 0 sinnum n r = toInteger n * r instance Monoidal Int where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Int8 where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Int16 where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Int32 where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Int64 where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Word where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Word8 where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Word16 where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Word32 where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal Word64 where zero = 0 sinnum n r = fromIntegral n * r instance Monoidal r => Monoidal (e -> r) where zero = const zero sumWith f xs e = sumWith (`f` e) xs sinnum n r e = sinnum n (r e) instance Monoidal () where zero = () sinnum _ () = () sumWith _ _ = () instance (Monoidal a, Monoidal b) => Monoidal (a,b) where zero = (zero,zero) sinnum n (a,b) = (sinnum n a, sinnum n b) instance (Monoidal a, Monoidal b, Monoidal c) => Monoidal (a,b,c) where zero = (zero,zero,zero) sinnum n (a,b,c) = (sinnum n a, sinnum n b, sinnum n c) instance (Monoidal a, Monoidal b, Monoidal c, Monoidal d) => Monoidal (a,b,c,d) where zero = (zero,zero,zero,zero) sinnum n (a,b,c,d) = (sinnum n a, sinnum n b, sinnum n c, sinnum n d) instance (Monoidal a, Monoidal b, Monoidal c, Monoidal d, Monoidal e) => Monoidal (a,b,c,d,e) where zero = (zero,zero,zero,zero,zero) sinnum n (a,b,c,d,e) = (sinnum n a, sinnum n b, sinnum n c, sinnum n d, sinnum n e)
athanclark/algebra
src/Numeric/Algebra/Class.hs
bsd-3-clause
18,022
2
22
4,087
7,842
4,237
3,605
-1
-1
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-} {-# OPTIONS_GHC -fcontext-stack42 #-} module Games.Chaos2010.Database.Base_relvar_key_attributes where import Games.Chaos2010.Database.Fields import Database.HaskellDB.DBLayout type Base_relvar_key_attributes = Record (HCons (LVPair Constraint_name (Expr (Maybe String))) (HCons (LVPair Attribute_name (Expr (Maybe String))) HNil)) base_relvar_key_attributes :: Table Base_relvar_key_attributes base_relvar_key_attributes = baseTable "base_relvar_key_attributes"
JakeWheat/Chaos-2010
Games/Chaos2010/Database/Base_relvar_key_attributes.hs
bsd-3-clause
543
0
15
67
104
58
46
11
1
module PCREHeavyExampleSpec where import PCREHeavyExample (mediaRegex) import Test.Hspec (Spec, hspec, describe, it, shouldSatisfy) import Text.Regex.PCRE.Heavy ((=~)) -- | Required for auto-discovery. spec :: Spec spec = describePredicate "pcre-heavy" ("match", (=~ mediaRegex)) (matchExamples, nonMatchExamples) describePredicate :: Show a => String -- ^ description -> (String, a -> Bool) -- ^ (base description, predicate) -> ( [(String, a)], [(String, a)] ) -- ^ positive and negative examples -> Spec describePredicate description (baseDescription, predicate) (positiveExamples, negativeExamples) = describe description $ do describe baseDescription $ do mapM_ (predSpec predicate) positiveExamples describe ("not " ++ baseDescription) $ do mapM_ (predSpec (not . predicate)) negativeExamples predSpec :: Show a => (a -> Bool) -> (String, a) -> Spec predSpec predicate (description, a) = it description $ do a `shouldSatisfy` predicate matchExamples :: [(String, String)] matchExamples = [ ( "has audio" , "@Media:\thas-audio, audio" ) , ( "has video" , "@Media:\thas-video,video" ) , ( "has audio but missing" , "@Media:\thas-audio-but-missing, audio, missing" ) , ( "has video but unlinked" , "@Media:\thas-video-but-unlinked , video, unlinked" ) ] nonMatchExamples :: [(String, String)] nonMatchExamples = [ ( "no audio or video" , "@Media:\tno-audio-or-video" ) , ( "missing media field" , "@Media:\tmissing-media-field, unlinked" ) ] -- | Just for our convenience to manually run just this module's tests. main :: IO () main = hspec spec
FranklinChen/twenty-four-days2015-of-hackage
test/PCREHeavyExampleSpec.hs
bsd-3-clause
1,753
0
15
419
412
240
172
44
1
-- | Functions for dealing with TPFS blocks. -- -- This is not a high level interface; it only provides a few utility functions -- for dealing with the blocks on disk themselves. It does not deal with -- extents or anything like that. See 'System.TPFS.Extent'. -- -- If you are looking for a high level interface, check out the modules for the -- the objects you are trying to access, as TPFS blocks simply contain these -- objects. module System.TPFS.Block ( -- * Indexing BlockIndex, blockIndexToAddress, addressToBlockIndex, addressToBlockIndexAndOffset, divBlocks, -- * Reading and writing readBlock, writeBlock ) where import Data.Binary import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy as B import System.TPFS.Device import System.TPFS.Filesystem import System.TPFS.Header --- Indexing --- type BlockIndex = Word64 -- | Converts a 'BlockIndex' to an 'Address' in the context of a filesystem. blockIndexToAddress :: Header -> BlockIndex -> Address blockIndexToAddress hdr idx = blockOffset hdr + fromIntegral (blockSize hdr) * fromIntegral (idx - 1) -- | Converts an 'Address' to a 'Blockindex' in the context of a filesystem. -- -- Note: This function will floor any addresses to the block boundary; it does -- not preserve offsets. See 'addressToBlockIndexAndOffset'. addressToBlockIndex :: Header -> Address -> BlockIndex addressToBlockIndex hdr a = toZero $ fromIntegral (quot (a - blockOffset hdr) (fromIntegral $ blockSize hdr)) + 1 where toZero x | x < 1 = 0 | otherwise = x -- | Converts an 'Address' to a 'BlockIndex' and byte offset within the block -- in the context of a filesystem. -- -- Note: Undefined when the 'Address' points to somewhere before the beginning -- of the block space. addressToBlockIndexAndOffset :: Header -> Address -> (BlockIndex, Word64) addressToBlockIndexAndOffset hdr a | a >= blockOffset hdr = (fromIntegral q + 1, fromIntegral r) | otherwise = undefined where (q, r) = quotRem (a - blockOffset hdr) (fromIntegral $ blockSize hdr) -- | Divides a number of bytes into the required number of blocks -- according to a filesystem header. divBlocks :: Integral i => i -> Header -> i i `divBlocks` hdr | r == 0 = q | otherwise = q + 1 where (q, r) = i `quotRem` fromIntegral (blockSize hdr - 16) --- Reading and writing --- -- | Reads an entire block into memory. readBlock :: Device m h => Filesystem m h -> BlockIndex -> m ByteString readBlock fs idx = dGet (fsHandle fs) (blockIndexToAddress (fsHeader fs) idx) (blockSize (fsHeader fs)) -- | Reads a section of a block into memory. Use sparingly: it is often faster -- (especially on hard drives) to read an entire block and store it if you -- think you'll be needing the same block shortly after. -- -- This function does verify that the region that is to be read is indeed -- within the block. The real offset is @offset `mod` 'blockSize' ('fsHeader' -- fs)@, and the length will simply be truncated to the block boundary if it is -- found to read outside of it. readBlockSection :: Device m h => Filesystem m h -> BlockIndex -> Word64 -- ^ The offset to start reading from. -> Word64 -- ^ The length (in bytes) to read. -> m ByteString readBlockSection fs idx ofs len = dGet (fsHandle fs) (blockIndexToAddress (fsHeader fs) idx + ofs') len' where ofs' = ofs `mod` blockSize (fsHeader fs) len' | ofs' + len > blockSize (fsHeader fs) = blockSize (fsHeader fs) - ofs' | otherwise = len -- | Replaces a block with the given string. The string is truncated/padded -- with NULs to fit the filesystem's block size. writeBlock :: Device m h => Filesystem m h -> BlockIndex -> ByteString -> m () writeBlock fs idx str = dPut (fsHandle fs) (blockIndexToAddress (fsHeader fs) idx) padstr where padstr | fromIntegral (B.length str) > blockSize (fsHeader fs) = B.take (fromIntegral . blockSize $ fsHeader fs) str | fromIntegral (B.length str) < blockSize (fsHeader fs) = B.append str . flip B.replicate 0 $ fromIntegral (blockSize $ fsHeader fs) - B.length str | otherwise = str -- | Writes a string within a block at a given offset. The string will be -- truncated if it does not fit within the block boundaries, but it will never -- be padded. writeBlockSection :: Device m h => Filesystem m h -> BlockIndex -> Word64 -> ByteString -> m () writeBlockSection fs idx ofs str = dPut (fsHandle fs) (blockIndexToAddress (fsHeader fs) idx + ofs') str' where ofs' = ofs `mod` blockSize (fsHeader fs) str' = flip B.take str . fromIntegral $ blockSize (fsHeader fs) - ofs'
devyn/TPFS
System/TPFS/Block.hs
bsd-3-clause
5,217
0
14
1,501
1,050
545
505
76
1
-- | LYAH Chapter 2 - Starting Out -- <http://learnyouahaskell.com/starting-out> module Week01.Lyah02 where doubleMe :: Num a => a -> a doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y -- double numbers smaller than 100 doubleSmallNumber x = if x > 100 then x else x*2 boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x] lc2 = [x*y | x <- [2,5,10], y <- [8,10,11]] length' xs = sum [1 | _ <- xs] removeNonUppercase str = [c | c <- str, c `elem` ['A'..'Z']] -- triangles triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ] rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2] rightTriangles' = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == 24]
emaphis/Haskell-Practice
cis194/src/week01/Lyah02.hs
bsd-3-clause
810
0
11
216
454
249
205
14
2
module Config ( Provider(..) , ProviderName , RoutesName , Route(..) , Routes , Config(..) , readConfig ) where import Control.Applicative import Data.Monoid import Data.List import Data.Char (isDigit) import Network.Socket hiding (recv, sendAll) type ProviderName = String type RoutesName = String data Provider = ProviderExternal String PortNumber | ProviderDirect | ProviderNone deriving (Show,Eq) data Route = Route String ProviderName | Inherit RoutesName | CatchAll ProviderName deriving (Show,Eq) type Routes = [Route] data Config = Config { configProviders :: [(ProviderName, Provider)] , configRoutes :: [(RoutesName, Routes)] } deriving (Show,Eq) configOneRoute r = mempty { configRoutes = [r] } configOneProvider p = mempty { configProviders = [p] } instance Monoid Config where mempty = Config [] [] mappend c1 c2 = Config { configProviders = configProviders c1 ++ configProviders c2 , configRoutes = configRoutes c1 ++ configRoutes c2 } parseConfig allLines = let (g, ls) = skipUntilGroup allLines in parseRoutes g [] ls where getGroupLine s | isPrefixOf "[" s && isSuffixOf "]" s = Just $ strip $ init $ tail s | otherwise = Nothing getNormalAssignment s | null s2 = Nothing | otherwise = Just (strip s1, strip $ tail s2) where (s1,s2) = break (== '=') s strip = reverse . stripForward . reverse . stripForward stripForward = dropWhile (\c -> c == ' ' || c == '\t') skipUntilGroup (l:ls) = case getGroupLine l of Nothing -> skipUntilGroup ls Just g -> (g, ls) parseRoutes name acc [] = [(name, reverse acc)] parseRoutes name acc (l:ls) = case getGroupLine l of Nothing -> case getNormalAssignment l of Nothing -> parseRoutes name acc ls Just (k,v) | k == "inherit" -> parseNext (Inherit v) ls | k == "*" -> parseNext (CatchAll v) ls | otherwise -> parseNext (Route k v) ls Just grp -> (name, reverse acc) : parseRoutes grp [] ls where parseNext val ls = parseRoutes name (val:acc) ls structureConfig cfg (gname, kvs) | gname == "providers" = cfg `mappend` (Config (map toProvider kvs) []) | otherwise = cfg `mappend` (Config [] [(gname, kvs)]) where toProvider (Inherit _) = error "inherit in providers section not allowed" toProvider (CatchAll _) = error "default in providers section not allowed" toProvider (Route name pr) | pr == "none" = (name, ProviderNone) | pr == "direct" = (name, ProviderDirect) | "external:" `isPrefixOf` pr = let externalS = drop (length "external:") pr (e1, e2) = break (== ':') externalS in case e2 of _ | null e2 -> error "missing a port number" | otherwise -> let port = tail e2 in if isNumber port then (name, ProviderExternal e1 (fromIntegral $ read port)) else error ("external not a valid port: " ++ show port) | otherwise = error ("unknown provider: " ++ name ++ "=" ++ pr) isNumber = and . map isDigit readConfig path = foldl structureConfig mempty . parseConfig . lines <$> readFile path
vincenthz/socksmaster
Src/Config.hs
bsd-3-clause
4,011
0
21
1,644
1,167
604
563
79
5
#define IncludedshiftNewIndicesLeft #ifdef IncludedmapCastId #else #include "../Proofs/mapCastId.hs" #endif #ifdef IncludedconcatMakeIndices #else #include "../Proofs/concatMakeIndices.hs" #endif {-@ shiftNewIndicesLeft :: xi:RString -> yi:RString -> zi:RString -> tg:{RString | stringLen tg <= stringLen yi } -> { makeNewIndices xi (yi <+> zi) tg == map (castGoodIndexRight tg (xi <+> yi) zi) (makeNewIndices xi yi tg)} @-} shiftNewIndicesLeft :: RString -> RString -> RString -> RString -> Proof shiftNewIndicesLeft xi yi zi tg | stringLen tg < 2 = makeNewIndices xi (yi <+> zi) tg ==. N ==. makeNewIndices xi yi tg ==. map (castGoodIndexRight tg (xi <+> yi) zi) (makeNewIndices xi yi tg) ?mapCastId tg (xi <+> yi) zi (makeNewIndices xi yi tg) *** QED | otherwise = makeNewIndices xi (yi <+> zi) tg ==. makeIndices (xi <+> (yi <+> zi)) tg (maxInt (stringLen xi - (stringLen tg-1)) 0) (stringLen xi - 1) ==. makeIndices ((xi <+> yi) <+> zi) tg (maxInt (stringLen xi - (stringLen tg-1)) 0) (stringLen xi - 1) ?stringAssoc xi yi zi ==. makeIndices (xi <+> yi) tg (maxInt (stringLen xi - (stringLen tg-1)) 0) (stringLen xi - 1) ?concatMakeIndices (maxInt (stringLen xi - (stringLen tg-1)) 0) (stringLen xi - 1) tg (xi <+> yi) zi ==. makeNewIndices xi yi tg ==. map (castGoodIndexRight tg (xi <+> yi) zi) (makeNewIndices xi yi tg) ?mapCastId tg (xi <+> yi) zi (makeNewIndices xi yi tg) *** QED
nikivazou/verified_string_matching
src/Proofs/shiftNewIndicesLeft.hs
bsd-3-clause
1,614
6
17
448
512
260
252
26
1
module Chapter3 where hello :: IO () hello = putStrLn "hello" helloThere :: IO () helloThere = putStrLn s where s = "hello "++"there" helloThere' :: IO () helloThere' = let s = "hello "++"there" in putStrLn s -- helloThere'' :: IO () -- helloThere'' = do -- putStrLn "hello "++"there" -- where unused = 1+1 ht = (++) "hello " "there" ht' = "hello " ++ "there" two = tail [1..10] printTwoToTen = putStrLn $ show two
peterbecich/haskell-programming-first-principles
src/Chapter3.hs
bsd-3-clause
429
0
9
92
134
72
62
13
1
module Code16 where import Data.Array (accumArray,(!)) import Data.List (inits,isSuffixOf,isPrefixOf) import Code15 matches0 :: Eq a => [a] -> [a] -> [Int] matches0 ws = map length . filter (endswith0 ws) . inits endswith0 :: Eq a => [a] -> [a] -> Bool endswith0 = isSuffixOf {- scan lemma map (foldl op e) . inits = scanl op e -} matches1 :: Eq a => [a] -> [a] -> [Int] matches1 ws = map fst . filter ((sw `isPrefixOf`) . snd) . scanl step (0,[]) where sw = reverse ws step :: (Int,[a]) -> a -> (Int,[a]) step (n,sx) x = (n+1, x:sx) matches ws = test m . scanl step (0,[]) where test j [] = [] test j ((n,sx):nxs) | i == m = n : test k (drop (k-1) nxs) | m-k <= i = test k (drop (k-1) nxs) | otherwise = test m (drop (k-1) nxs) where i' = llcp sw (take j sx) i = if i'== j then m else i' k = a ! i a = accumArray min m (0,m) (vks ++ vks') sw = reverse ws m = length sw vks = zip (allcp' sw) [1..m] vks' = zip [m,m-1..1] (foldr op [] vks) op (v,k) ks = if v+k==m then k:ks else head ks:ks llcp :: Eq a => [a] -> [a] -> Int llcp = llcp1 allcp' xs = tail (allcp xs) ++ [0] spat = "aabaaabaa" srpat = reverse spat stxt = "aaababcabcabcc" srtxt = reverse stxt f k = llcp srpat (drop k srpat) op (v,k) ks = if v+k==9 then k:ks else head ks:ks vks = [(f k,k)|k <- [1..9]] vks' = zip [9,8..1] (foldr op [] vks)
sampou-org/pfad
Code/Code16.hs
bsd-3-clause
1,463
0
13
441
834
447
387
39
4
module Main where import Test.Bakers12.System.Enumerators import Test.Bakers12.Tokenizer import Test.Bakers12.Tokenizer.Minimal import Test.Bakers12.Tokenizer.PennTreebank import Test.Framework (Test, defaultMain, testGroup) main :: IO () main = defaultMain tests tests :: [Test] tests = [ testGroup "tokenizer" tokenizerTests , testGroup "minimal filter" minimalFilterTests , testGroup "penn treebank" pennTreebankTests , testGroup "system.enumerators" systemEnumeratorTests ]
erochest/bakers12
tests/TestBakers12.hs
bsd-3-clause
504
0
6
74
110
65
45
14
1
module Turbinado.Database.ORM.Generator ( generateModels ) where import Control.Monad import Data.List import qualified Data.Map as M import Data.Maybe import Database.HDBC import Config.Database import Turbinado.Database.ORM.Types import Turbinado.Database.ORM.Output import Turbinado.Database.ORM.PostgreSQL -- | Outputs ORM models to App/Models. User configurable files -- are in App/Models. Machine generated files are in App/Models/Bases. generateModels :: IO () generateModels = do conn <- fromJust databaseConnection ts <- getTables conn -- TODO: Pull in indices tcs <- foldM (buildTable conn) (M.empty) ts writeModels tcs buildTable conn tcs t = do ds <- describeTable conn t let tcs' = combineDescription t ds tcs pks <- getPrimaryKeys conn t let tcs'' = combinePrimaryKeys t pks tcs' fks <- getForeignKeyReferences conn t let tcs''' = combineForeignKeyReferences t fks tcs'' hds <- getDefaultColumns conn t return $ combineDefaultColumns t hds tcs''' combineDescription t ds tcs = M.insert t (cols, []) tcs where cols = M.fromList $ map (\(columnName, columnDescription) -> (columnName, (columnDescription,[], False))) ds combinePrimaryKeys :: TableName -> [ColumnName] -> Tables -> Tables combinePrimaryKeys t pks tcs = M.adjust (\(c, _) -> (c,pks)) t tcs combineForeignKeyReferences :: TableName -> [(ColumnName, TableName, ColumnName)] -> Tables -> Tables combineForeignKeyReferences t fks tcs = M.adjust (\(cs, pks) -> (foldl (worker) cs fks, pks)) t tcs where worker cs (c, tt, tc) = M.adjust (\(cd, deps, hd) -> (cd, [(tt, tc)] `union` deps, hd)) c cs combineDefaultColumns :: TableName -> [ColumnName] -> Tables -> Tables combineDefaultColumns t hds tcs = M.adjust (\(cs, pks) -> (foldl (worker) cs hds, pks)) t tcs where worker cs hd = M.adjust (\(cd, deps, _) -> (cd, deps, True)) hd cs
abuiles/turbinado-blog
Turbinado/Database/ORM/Generator.hs
bsd-3-clause
2,259
0
13
713
666
363
303
41
1
module Azure.Storage.Protocol.HttpHelpers ( httpRequest ) where import Control.Monad (unless) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Reader.Class (MonadReader) import Control.Monad.Trans.Resource (MonadResource) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.Conduit as C import qualified Network.HTTP.Client as HTTP httpRequest :: MonadResource m => HTTP.Request -> HTTP.Manager -> C.Source m BS.ByteString httpRequest r m = C.bracketP (liftIO $ HTTP.responseOpen r m) (liftIO . HTTP.responseClose) (produce . HTTP.responseBody) where produce resp = loop where loop = do chunk <- liftIO $ HTTP.brRead resp unless (BS.null chunk) $ C.yield chunk >> loop
Porges/azure-storage-haskell
src/Azure/Storage/Protocol/HttpHelpers.hs
bsd-3-clause
887
0
16
241
241
136
105
21
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( makeApplication , getApplicationDev , makeFoundation ) where import Import import Settings import Yesod.Default.Config import Yesod.Default.Main import Yesod.Default.Handlers import Network.Wai.Middleware.RequestLogger ( mkRequestLogger, outputFormat, OutputFormat (..), IPAddrSource (..), destination ) import qualified Network.Wai.Middleware.RequestLogger as RequestLogger import qualified Database.Persist import Database.Persist.Sql (runMigration) import Network.HTTP.Client.Conduit (newManager) import Control.Monad.Logger (runLoggingT) import Control.Concurrent (forkIO, threadDelay) import System.Log.FastLogger (newStdoutLoggerSet, defaultBufSize) import Network.Wai.Logger (clockDateCacher) import Data.Default (def) import Yesod.Core.Types (loggerSet, Logger (Logger)) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Home -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- This function allocates resources (such as a database connection pool), -- performs initialization and creates a WAI application. This is also the -- place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeApplication :: AppConfig DefaultEnv Extra -> IO (Application, LogFunc) makeApplication conf = do foundation <- makeFoundation conf -- Initialize the logging middleware logWare <- mkRequestLogger def { outputFormat = if development then Detailed True else Apache FromSocket , destination = RequestLogger.Logger $ loggerSet $ appLogger foundation } -- Create the WAI application and apply middlewares app <- toWaiAppPlain foundation let logFunc = messageLoggerSource foundation (appLogger foundation) return (logWare app, logFunc) -- | Loads up any necessary settings, creates your foundation datatype, and -- performs some initialization. makeFoundation :: AppConfig DefaultEnv Extra -> IO App makeFoundation conf = do manager <- newManager s <- staticSite dbconf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf) Database.Persist.loadConfig >>= Database.Persist.applyEnv p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf) loggerSet' <- newStdoutLoggerSet defaultBufSize (getter, updater) <- clockDateCacher -- If the Yesod logger (as opposed to the request logger middleware) is -- used less than once a second on average, you may prefer to omit this -- thread and use "(updater >> getter)" in place of "getter" below. That -- would update the cache every time it is used, instead of every second. let updateLoop = do threadDelay 1000000 updater updateLoop _ <- forkIO updateLoop let logger = Yesod.Core.Types.Logger loggerSet' getter foundation = App conf s p manager dbconf logger -- Perform database migration using our application's logging settings. runLoggingT (Database.Persist.runPool dbconf (runMigration migrateAll) p) (messageLoggerSource foundation logger) return foundation -- for yesod devel getApplicationDev :: IO (Int, Application) getApplicationDev = defaultDevelApp loader (fmap fst . makeApplication) where loader = Yesod.Default.Config.loadConfig (configSettings Development) { csParseExtra = parseExtra }
pirapira/hashprice
Application.hs
bsd-3-clause
3,705
0
13
734
640
354
286
-1
-1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : YARN.Client_r2_7_3 -- Copyright : (c) Stanislav Chernichkin 2017 -- License : BSD3 -- -- Maintainer : schernichkin@gmail.com -- Stability : experimental -- Portability : portable -- -- ResourceManager REST API client version r2.7.3. -- -- This code was generated by a tool. -- Changes to this file will be lost if the code is regenerated. ----------------------------------------------------------------------------- module YARN.Client_r2_7_3 ( getClusterInformation , getClusterMetrics , getClusterScheduler , getClusterApplications , getClusterApplicationStatistics , getClusterApplication , getClusterApplicationAttempts , getClusterNodes , getClusterNode , postClusterNewApplication , submitClusterApplication , getClusterApplicationState , putClusterApplicationState , getClusterApplicationQueue , putClusterApplicationQueue , postClusterDelegationTokens , deleteClusterDelegationTokens , ClusterInfo (..) , ClusterMetrics (..) , SchedulerInfo (..) , Apps (..) , AppStatInfo (..) , App (..) , AppAttempts (..) , Nodes (..) , Node (..) , Appstate (..) , Appqueue (..) , DelegationToken (..) ) where import Data.Aeson import qualified Data.ByteString as B import Data.Int import Data.Text (Text) import Network.HTTP.Client data ClusterInfo = ClusterInfo { clusterInfoId :: Int64 -- ^ The cluster id , clusterInfoStartedOn :: Int64 -- ^ The time the cluster started (in ms since epoch) , clusterInfoState :: Text -- ^ The ResourceManager state - valid values are: NOTINITED, INITED, STARTED, STOPPED , clusterInfoHaState :: Text -- ^ The ResourceManager HA state - valid values are: INITIALIZING, ACTIVE, STANDBY, STOPPED , clusterInfoResourceManagerVersion :: Text -- ^ Version of the ResourceManager , clusterInfoResourceManagerBuildVersion :: Text -- ^ ResourceManager build string with build version, user, and checksum , clusterInfoResourceManagerVersionBuiltOn :: Text -- ^ Timestamp when ResourceManager was built (in ms since epoch) , clusterInfoHadoopVersion :: Text -- ^ Version of hadoop common , clusterInfoHadoopBuildVersion :: Text -- ^ Hadoop common build string with build version, user, and checksum , clusterInfoHadoopVersionBuiltOn :: Text -- ^ Timestamp when hadoop common was built(in ms since epoch) } deriving ( Show, Eq ) instance FromJSON ClusterInfo where parseJSON = withObject "ClusterInfo" $ \v -> ClusterInfo <$> v .: "id" <*> v .: "startedOn" <*> v .: "state" <*> v .: "haState" <*> v .: "resourceManagerVersion" <*> v .: "resourceManagerBuildVersion" <*> v .: "resourceManagerVersionBuiltOn" <*> v .: "hadoopVersion" <*> v .: "hadoopBuildVersion" <*> v .: "hadoopVersionBuiltOn" data ClusterMetrics = ClusterMetrics { clusterMetricsAppsSubmitted :: Int32 -- ^ The number of applications submitted , clusterMetricsAppsCompleted :: Int32 -- ^ The number of applications completed , clusterMetricsAppsPending :: Int32 -- ^ The number of applications pending , clusterMetricsAppsRunning :: Int32 -- ^ The number of applications running , clusterMetricsAppsFailed :: Int32 -- ^ The number of applications failed , clusterMetricsAppsKilled :: Int32 -- ^ The number of applications killed , clusterMetricsReservedMB :: Int64 -- ^ The amount of memory reserved in MB , clusterMetricsAvailableMB :: Int64 -- ^ The amount of memory available in MB , clusterMetricsAllocatedMB :: Int64 -- ^ The amount of memory allocated in MB , clusterMetricsTotalMB :: Int64 -- ^ The amount of total memory in MB , clusterMetricsReservedVirtualCores :: Int64 -- ^ The number of reserved virtual cores , clusterMetricsAvailableVirtualCores :: Int64 -- ^ The number of available virtual cores , clusterMetricsAllocatedVirtualCores :: Int64 -- ^ The number of allocated virtual cores , clusterMetricsTotalVirtualCores :: Int64 -- ^ The total number of virtual cores , clusterMetricsContainersAllocated :: Int32 -- ^ The number of containers allocated , clusterMetricsContainersReserved :: Int32 -- ^ The number of containers reserved , clusterMetricsContainersPending :: Int32 -- ^ The number of containers pending , clusterMetricsTotalNodes :: Int32 -- ^ The total number of nodes , clusterMetricsActiveNodes :: Int32 -- ^ The number of active nodes , clusterMetricsLostNodes :: Int32 -- ^ The number of lost nodes , clusterMetricsUnhealthyNodes :: Int32 -- ^ The number of unhealthy nodes , clusterMetricsDecommissionedNodes :: Int32 -- ^ The number of nodes decommissioned , clusterMetricsRebootedNodes :: Int32 -- ^ The number of nodes rebooted } deriving ( Show, Eq ) instance FromJSON ClusterMetrics where parseJSON = withObject "ClusterMetrics" $ \v -> ClusterMetrics <$> v .: "appsSubmitted" <*> v .: "appsCompleted" <*> v .: "appsPending" <*> v .: "appsRunning" <*> v .: "appsFailed" <*> v .: "appsKilled" <*> v .: "reservedMB" <*> v .: "availableMB" <*> v .: "allocatedMB" <*> v .: "totalMB" <*> v .: "reservedVirtualCores" <*> v .: "availableVirtualCores" <*> v .: "allocatedVirtualCores" <*> v .: "totalVirtualCores" <*> v .: "containersAllocated" <*> v .: "containersReserved" <*> v .: "containersPending" <*> v .: "totalNodes" <*> v .: "activeNodes" <*> v .: "lostNodes" <*> v .: "unhealthyNodes" <*> v .: "decommissionedNodes" <*> v .: "rebootedNodes" data SchedulerInfo = SchedulerInfo { schedulerInfoType :: Text -- ^ Scheduler type - capacityScheduler , schedulerInfoCapacity :: Float -- ^ Configured queue capacity in percentage relative to its parent queue , schedulerInfoUsedCapacity :: Float -- ^ Used queue capacity in percentage , schedulerInfoMaxCapacity :: Float -- ^ Configured maximum queue capacity in percentage relative to its parent queue , schedulerInfoQueueName :: Text -- ^ Name of the queue , schedulerInfoQueues :: () -- ^ A collection of queue resources } deriving ( Show, Eq ) instance FromJSON SchedulerInfo where parseJSON = withObject "SchedulerInfo" $ \v -> SchedulerInfo <$> v .: "type" <*> v .: "capacity" <*> v .: "usedCapacity" <*> v .: "maxCapacity" <*> v .: "queueName" <*> v .: "queues" -- | When you make a request for the list of applications, the information will be returned as a collection of app objects. See also Application API for syntax of the app object. data Apps = Apps { appsApp :: () -- ^ The collection of application objects } deriving ( Show, Eq ) instance FromJSON Apps where parseJSON = withObject "Apps" $ \v -> Apps <$> v .: "app" -- | When you make a request for the list of statistics items, the information will be returned as a collection of statItem objects data AppStatInfo = AppStatInfo { appStatInfoStatItem :: () -- ^ The collection of statItem objects } deriving ( Show, Eq ) instance FromJSON AppStatInfo where parseJSON = withObject "AppStatInfo" $ \v -> AppStatInfo <$> v .: "statItem" -- | Note that depending on security settings a user might not be able to see all the fields. data App = App { appId :: Text -- ^ The application id , appUser :: Text -- ^ The user who started the application , appName :: Text -- ^ The application name , appApplication :: Text -- ^ The application type , appQueue :: Text -- ^ The queue the application was submitted to , appState :: Text -- ^ The application state according to the ResourceManager - valid values are members of the YarnApplicationState enum: NEW, NEW_SAVING, SUBMITTED, ACCEPTED, RUNNING, FINISHED, FAILED, KILLED , appFinalStatus :: Text -- ^ The final status of the application if finished - reported by the application itself - valid values are: UNDEFINED, SUCCEEDED, FAILED, KILLED , appProgress :: Float -- ^ The progress of the application as a percent , appTrackingUI :: Text -- ^ Where the tracking url is currently pointing - History (for history server) or ApplicationMaster , appTrackingUrl :: Text -- ^ The web URL that can be used to track the application , appDiagnostics :: Text -- ^ Detailed diagnostics information , appClusterId :: Int64 -- ^ The cluster id , appStartedTime :: Int64 -- ^ The time in which application started (in ms since epoch) , appFinishedTime :: Int64 -- ^ The time in which the application finished (in ms since epoch) , appElapsedTime :: Int64 -- ^ The elapsed time since the application started (in ms) , appAmContainerLogs :: Text -- ^ The URL of the application master container logs , appAmHostHttpAddress :: Text -- ^ The nodes http address of the application master , appAllocatedMB :: Int32 -- ^ The sum of memory in MB allocated to the application’s running containers , appAllocatedVCores :: Int32 -- ^ The sum of virtual cores allocated to the application’s running containers , appRunningContainers :: Int32 -- ^ The number of containers currently running for the application , appMemorySeconds :: Int64 -- ^ The amount of memory the application has allocated (megabyte-seconds) , appVcoreSeconds :: Int64 -- ^ The amount of CPU resources the application has allocated (virtual core-seconds) } deriving ( Show, Eq ) instance FromJSON App where parseJSON = withObject "App" $ \v -> App <$> v .: "id" <*> v .: "user" <*> v .: "name" <*> v .: "Application" <*> v .: "queue" <*> v .: "state" <*> v .: "finalStatus" <*> v .: "progress" <*> v .: "trackingUI" <*> v .: "trackingUrl" <*> v .: "diagnostics" <*> v .: "clusterId" <*> v .: "startedTime" <*> v .: "finishedTime" <*> v .: "elapsedTime" <*> v .: "amContainerLogs" <*> v .: "amHostHttpAddress" <*> v .: "allocatedMB" <*> v .: "allocatedVCores" <*> v .: "runningContainers" <*> v .: "memorySeconds" <*> v .: "vcoreSeconds" -- | When you make a request for the list of app attempts, the information will be returned as an array of app attempt objects. -- appAttempts: data AppAttempts = AppAttempts { appAttemptsAppAttempt :: () -- ^ The collection of app attempt objects } deriving ( Show, Eq ) instance FromJSON AppAttempts where parseJSON = withObject "AppAttempts" $ \v -> AppAttempts <$> v .: "appAttempt" -- | When you make a request for the list of nodes, the information will be returned as a collection of node objects. See also Node API for syntax of the node object. data Nodes = Nodes { nodesNode :: () -- ^ A collection of node objects } deriving ( Show, Eq ) instance FromJSON Nodes where parseJSON = withObject "Nodes" $ \v -> Nodes <$> v .: "node" data Node = Node { nodeRack :: Text -- ^ The rack location of this node , nodeState :: Text -- ^ State of the node - valid values are: NEW, RUNNING, UNHEALTHY, DECOMMISSIONED, LOST, REBOOTED , nodeId :: Text -- ^ The node id , nodeNodeHostName :: Text -- ^ The host name of the node , nodeNodeHTTPAddress :: Text -- ^ The nodes HTTP address , nodeHealthStatus :: Text -- ^ The health status of the node - Healthy or Unhealthy , nodeHealthReport :: Text -- ^ A detailed health report , nodeLastHealthUpdate :: Int64 -- ^ The last time the node reported its health (in ms since epoch) , nodeUsedMemoryMB :: Int64 -- ^ The total amount of memory currently used on the node (in MB) , nodeAvailMemoryMB :: Int64 -- ^ The total amount of memory currently available on the node (in MB) , nodeUsedVirtualCores :: Int64 -- ^ The total number of vCores currently used on the node , nodeAvailableVirtualCores :: Int64 -- ^ The total number of vCores available on the node , nodeNumContainers :: Int32 -- ^ The total number of containers currently running on the node } deriving ( Show, Eq ) instance FromJSON Node where parseJSON = withObject "Node" $ \v -> Node <$> v .: "rack" <*> v .: "state" <*> v .: "id" <*> v .: "nodeHostName" <*> v .: "nodeHTTPAddress" <*> v .: "healthStatus" <*> v .: "healthReport" <*> v .: "lastHealthUpdate" <*> v .: "usedMemoryMB" <*> v .: "availMemoryMB" <*> v .: "usedVirtualCores" <*> v .: "availableVirtualCores" <*> v .: "numContainers" -- | When you make a request for the state of an app, the information returned has the following fields data Appstate = Appstate { appstateState :: Text -- ^ The application state - can be one of “NEW”, “NEW_SAVING”, “SUBMITTED”, “ACCEPTED”, “RUNNING”, “FINISHED”, “FAILED”, “KILLED” } deriving ( Show, Eq ) instance FromJSON Appstate where parseJSON = withObject "Appstate" $ \v -> Appstate <$> v .: "state" -- | When you make a request for the state of an app, the information returned has the following fields data Appqueue = Appqueue { appqueueQueue :: Text -- ^ The application queue } deriving ( Show, Eq ) instance FromJSON Appqueue where parseJSON = withObject "Appqueue" $ \v -> Appqueue <$> v .: "queue" -- | The response from the delegation tokens API contains one of the fields listed below. data DelegationToken = DelegationToken { delegationTokenToken :: Text -- ^ The delegation token , delegationTokenRenewer :: Text -- ^ The user who is allowed to renew the delegation token , delegationTokenOwner :: Text -- ^ The owner of the delegation token , delegationTokenKind :: Text -- ^ The kind of delegation token , delegationTokenExpiration :: Int64 -- ^ The expiration time of the token , delegationTokenMax :: Int64 -- ^ The maximum validity of the token } deriving ( Show, Eq ) instance FromJSON DelegationToken where parseJSON = withObject "DelegationToken" $ \v -> DelegationToken <$> v .: "token" <*> v .: "renewer" <*> v .: "owner" <*> v .: "kind" <*> v .: "expiration" <*> v .: "max" -- | Cluster Information API -- http://<rm http address:port>/ws/v1/cluster -- The cluster information resource provides overall information about the cluster. getClusterInformation :: B.ByteString -> Int -> Manager -> IO ClusterInfo getClusterInformation h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster Metrics API -- http://<rm http address:port>/ws/v1/cluster/metrics -- The cluster metrics resource provides some overall metrics about the cluster. More detailed metrics should be retrieved from the jmx interface. getClusterMetrics :: B.ByteString -> Int -> Manager -> IO ClusterMetrics getClusterMetrics h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/metrics", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster Scheduler API -- http://<rm http address:port>/ws/v1/cluster/scheduler -- A scheduler resource contains information about the current scheduler configured in a cluster. It currently supports both the Fifo and Capacity Scheduler. You will get different information depending on which scheduler is configured so be sure to look at the type information. getClusterScheduler :: B.ByteString -> Int -> Manager -> IO SchedulerInfo getClusterScheduler h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/scheduler", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster Applications API -- http://<rm http address:port>/ws/v1/cluster/apps -- With the Applications API, you can obtain a collection of resources, each of which represents an application. When you run a GET operation on this resource, you obtain a collection of Application Objects. getClusterApplications :: B.ByteString -> Int -> Manager -> IO Apps getClusterApplications h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster Application Statistics API -- http://<rm http address:port>/ws/v1/cluster/appstatistics -- With the Application Statistics API, you can obtain a collection of triples, each of which contains the application type, the application state and the number of applications of this type and this state in ResourceManager context. Note that with the performance concern, we currently only support at most one applicationType per query. We may support multiple applicationTypes per query as well as more statistics in the future. When you run a GET operation on this resource, you obtain a collection of statItem objects. getClusterApplicationStatistics :: B.ByteString -> Int -> Manager -> IO AppStatInfo getClusterApplicationStatistics h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/appstatistics", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster Application API -- http://<rm http address:port>/ws/v1/cluster/apps/{appid} -- An application resource contains information about a particular application that was submitted to a cluster. getClusterApplication :: B.ByteString -> Int -> Manager -> IO App getClusterApplication h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps/{appid}", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster Application Attempts API -- http://<rm http address:port>/ws/v1/cluster/apps/{appid}/appattempts -- With the application attempts API, you can obtain a collection of resources that represent an application attempt. When you run a GET operation on this resource, you obtain a collection of App Attempt Objects. getClusterApplicationAttempts :: B.ByteString -> Int -> Manager -> IO AppAttempts getClusterApplicationAttempts h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps/{appid}/appattempts", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster Nodes API -- http://<rm http address:port>/ws/v1/cluster/nodes -- With the Nodes API, you can obtain a collection of resources, each of which represents a node. When you run a GET operation on this resource, you obtain a collection of Node Objects. getClusterNodes :: B.ByteString -> Int -> Manager -> IO Nodes getClusterNodes h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/nodes", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster Node API -- http://<rm http address:port>/ws/v1/cluster/nodes/{nodeid} -- A node resource contains information about a node in the cluster. getClusterNode :: B.ByteString -> Int -> Manager -> IO Node getClusterNode h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/nodes/{nodeid}", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e -- | Cluster New Application API -- http://<rm http address:port>/ws/v1/cluster/apps/new-application -- With the New Application API, you can obtain an application-id which can then be used as part of the Cluster Submit Applications API to submit applications. The response also includes the maximum resource capabilities available on the cluster. -- This feature is currently in the alpha stage and may change in the future. postClusterNewApplication :: B.ByteString -> Int -> Manager -> IO () postClusterNewApplication h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps/new-application", method = "POST" } return undefined -- | Cluster Applications API(Submit Application) -- http://<rm http address:port>/ws/v1/cluster/apps -- The Submit Applications API can be used to submit applications. In case of submitting applications, you must first obtain an application-id using the Cluster New Application API. The application-id must be part of the request body. The response contains a URL to the application page which can be used to track the state and progress of your application. submitClusterApplication :: B.ByteString -> Int -> Manager -> IO () submitClusterApplication h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps", method = "POST" } return undefined -- | Cluster Application State API -- http://<rm http address:port>/ws/v1/cluster/apps/{appid}/state -- With the application state API, you can query the state of a submitted app as well kill a running app by modifying the state of a running app using a PUT request with the state set to “KILLED”. To perform the PUT operation, authentication has to be setup for the RM web services. In addition, you must be authorized to kill the app. Currently you can only change the state to “KILLED”; an attempt to change the state to any other results in a 400 error response. Examples of the unauthorized and bad request errors are below. When you carry out a successful PUT, the iniital response may be a 202. You can confirm that the app is killed by repeating the PUT request until you get a 200, querying the state using the GET method or querying for app information and checking the state. In the examples below, we repeat the PUT request and get a 200 response. -- Please note that in order to kill an app, you must have an authentication filter setup for the HTTP interface. The functionality requires that a username is set in the HttpServletRequest. If no filter is setup, the response will be an “UNAUTHORIZED” response. -- This feature is currently in the alpha stage and may change in the future. getClusterApplicationState :: B.ByteString -> Int -> Manager -> IO Appstate getClusterApplicationState h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps/{appid}/state", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e putClusterApplicationState :: B.ByteString -> Int -> Manager -> IO () putClusterApplicationState h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps/{appid}/state", method = "PUT" } return undefined -- | Cluster Application Queue API -- http://<rm http address:port>/ws/v1/cluster/apps/{appid}/queue -- With the application queue API, you can query the queue of a submitted app as well move a running app to another queue using a PUT request specifying the target queue. To perform the PUT operation, authentication has to be setup for the RM web services. In addition, you must be authorized to move the app. Currently you can only move the app if you’re using the Capacity scheduler or the Fair scheduler. -- Please note that in order to move an app, you must have an authentication filter setup for the HTTP interface. The functionality requires that a username is set in the HttpServletRequest. If no filter is setup, the response will be an “UNAUTHORIZED” response. -- This feature is currently in the alpha stage and may change in the future. getClusterApplicationQueue :: B.ByteString -> Int -> Manager -> IO Appqueue getClusterApplicationQueue h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps/{appid}/queue", method = "GET" } b <- responseBody <$> httpLbs request m return $ case eitherDecode' b of Right r -> r Left e -> error e putClusterApplicationQueue :: B.ByteString -> Int -> Manager -> IO () putClusterApplicationQueue h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/apps/{appid}/queue", method = "PUT" } return undefined -- | Cluster Delegation Tokens API -- http://<rm http address:port>/ws/v1/cluster/delegation-token -- http://<rm http address:port>/ws/v1/cluster/delegation-token/expiration -- The Delegation Tokens API can be used to create, renew and cancel YARN ResourceManager delegation tokens. All delegation token requests must be carried out on a Kerberos authenticated connection(using SPNEGO). Carrying out operations on a non-kerberos connection will result in a FORBIDDEN response. In case of renewing a token, only the renewer specified when creating the token can renew the token. Other users(including the owner) are forbidden from renewing tokens. It should be noted that when cancelling or renewing a token, the token to be cancelled or renewed is specified by setting a header. -- This feature is currently in the alpha stage and may change in the future. postClusterDelegationTokens :: B.ByteString -> Int -> Manager -> IO () postClusterDelegationTokens h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/delegation-token", method = "POST" } return undefined deleteClusterDelegationTokens :: B.ByteString -> Int -> Manager -> IO () deleteClusterDelegationTokens h p m = do let request = defaultRequest { host = h, port = p, path = "/ws/v1/cluster/delegation-token", method = "DELETE" } return undefined
schernichkin/yarn-client
src/YARN/Client_r2_7_3.hs
bsd-3-clause
30,302
0
53
9,601
3,873
2,168
1,705
395
2
----------------------------------------------------------------------------- -- | -- Module : XMonad.Util.Minimize -- Description : Common utilities for window minimizing\/maximizing. -- Copyright : (c) Bogdan Sinitsyn (2016) -- License : BSD3-style (see LICENSE) -- -- Maintainer : bogdan.sinitsyn@gmail.com -- Stability : unstable -- Portability : not portable -- -- Stores some common utilities for modules used for window minimizing/maximizing -- ----------------------------------------------------------------------------- module XMonad.Util.Minimize ( RectMap , Minimized(..) ) where import XMonad import qualified XMonad.StackSet as W import qualified Data.Map as M type RectMap = M.Map Window (Maybe W.RationalRect) data Minimized = Minimized { rectMap :: RectMap , minimizedStack :: [Window] } deriving (Eq, Read, Show) instance ExtensionClass Minimized where initialValue = Minimized { rectMap = M.empty , minimizedStack = [] } extensionType = PersistentExtension
xmonad/xmonad-contrib
XMonad/Util/Minimize.hs
bsd-3-clause
1,082
0
9
225
148
96
52
15
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {- | Module : Control.Arrow.CCA Description : ArrowDelay Copyright : (c) 2015 Thomas Bereknyei License : BSD3 Maintainer : Thomas Bereknyei <tomberek@gmail.com> Stability : unstable Portability : MultiParamTypeClasses Originally from CCA package: <https://hackage.haskell.org/package/CCA-0.1.5.2> Added ArrowEffect in order to model effectful arrows. Adding Swap,Id,Dup,Diag for CCC normalization -} module Control.Arrow.CCA.NoQ where import Control.Arrow import Control.Category (Category) import Control.Concurrent.Async import Control.Monad.Identity import Language.Haskell.TH import Control.Categorical.Bifunctor (Bifunctor,(***),PFunctor,QFunctor) import Control.Category.Structural (Weaken) import qualified Control.Category.Structural (Weaken(..)) -- | An @'ArrowCCA'@ is a typeclass that captures causual commutative arrows. -- Any instance must also be an instance of 'ArrowLoop'. -- Merged at the moment with an @'ArrowEffect'@ typeclass that captures monadic -- causual commutative arrows. -- Laws: -- `first f >>> second g == second g >>> first f` -- `init i *** init j == init (i,j)` instance ArrowCCA (->) where delay = error "undefined delay for -> " class (ArrowLoop a,Weaken (,) a) => ArrowCCA a where {-# NOINLINE arr' #-} arr' :: Exp -> (b->c) -> a b c arr' _ = arr delay :: b -> a b b delay' :: Exp -> b -> a b b delay' _ = delay loopD :: e -> ((b, e) -> (c, e)) -> a b c loopD i f = loop (arr f >>> second (delay i)) type M a :: * -> * type M a = Identity arrM :: (b -> (M a) c) -> a b c default arrM :: (b -> Identity c) -> a b c arrM f = arr $ \a -> runIdentity $ f a arrM' :: Exp -> (b -> (M a) c) -> a b c arrM' _ = arrM class Category k => HasTerminal k where terminate :: i -> k a i terminate' :: Exp -> i -> k a i terminate' _ = terminate instance HasTerminal (->) where terminate = const instance Monad m => Weaken (,) (Kleisli m) where fst = Kleisli $ return . fst snd = Kleisli $ return . snd instance Monad m => Bifunctor (,) (Kleisli m) where (***) (Kleisli f) (Kleisli g) = Kleisli $ \(a,b) -> do a' <- f a b' <- g b return (a',b') instance Monad m => PFunctor (,) (Kleisli m) instance Monad m => QFunctor (,) (Kleisli m) newtype PKleisli a b = PKleisli {runPKleisli :: Kleisli IO a b} deriving (Category,ArrowLoop,Weaken (,),Bifunctor (,),PFunctor (,),QFunctor (,)) rr :: PKleisli a b -> a -> IO b rr = runKleisli . runPKleisli instance Arrow (PKleisli) where arr = PKleisli . arr first (PKleisli f) = PKleisli $ first f a1 *** a2 = PKleisli $ Kleisli $ \(x1, x2) -> do ( y1, y2 ) <- concurrently (rr a1 x1) (rr a2 x2) return (y1, y2) instance ArrowCCA (PKleisli) where delay = error "delay for PKleisli not defined" type M PKleisli = IO arrM f = PKleisli $ Kleisli f instance MonadFix m => ArrowCCA (Kleisli m) where delay = error "delay for PKleisli not defined" type M (Kleisli m) = m arrM f = Kleisli f
tomberek/rulestesting
src/Control/Arrow/CCA/NoQ.hs
bsd-3-clause
3,457
0
13
893
1,023
547
476
67
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} module Bench where import Control.Applicative ((<$>)) import Control.Concurrent (threadDelay) import Control.Monad (void,forever) import Data.Maybe import Data.Serialize import qualified Data.Text as T import Data.Traversable (traverse) import SimpleStore import System.Random (getStdGen, randoms) import TestImport main :: IO () main = do sc <- initializeSampleSC "benchTestCell" stdGen <- getStdGen let sis = take 500 $ Sample <$> randoms stdGen void $ traverse (insertSampleSC sc) sis samples <- traverse (storeState sc) sis forever $ do print "restart" void $ traverse checkpointWithoutReGet (catMaybes samples) storeState sc sample = do putStrLn "running" threadDelay $ 3*1000 msimpleStoreSample <- getSampleSC sc sample return (msimpleStoreSample >>= \simpleStoreSample -> return (simpleStoreSample, sample) ) checkpointWithoutReGet :: Data.Serialize.Serialize st => (SimpleStore st, t) -> IO (SimpleStore st) checkpointWithoutReGet (simpleStoreSample,sample) = do eT' <- createCheckpoint simpleStoreSample a <- either (\e -> fail (T.unpack $ T.concat [T.pack.show $ e," modify failure"] ) ) (const $ return simpleStoreSample) eT' -- (eT >> eT') return simpleStoreSample
plow-technologies/simple-cell
bench/Bench.hs
bsd-3-clause
1,351
0
18
267
407
208
199
36
1
module CRF.Model.Internal ( Model , fromList , toList --, Student (..) , makeModel --, makeStudent -- , showModel -- , readModel , modelSize , onOFeat , onTFeat , featToIx , consumeWith , mapModel , mapModel' -- , updateWithNumbers --, gradientInternal --, applyGradients ) where import Data.Maybe (fromJust) import Control.Monad (forM_) import qualified Data.Array.IO as A import qualified Data.Array.MArray as A import qualified Data.Array.Unboxed as A import qualified Data.IntMap as IM import qualified Data.Set as Set import Data.List (foldl', zip3, zip4, zip5) import Data.Binary import Control.Concurrent (newEmptyMVar, putMVar, takeMVar, forkIO) import qualified CRF.Data.MarkedArray as MA import CRF.Base import CRF.Feature import CRF.LogMath import CRF.Util (partition) import Debug.Trace (trace) type Level = Int type Observation = Int data Model = Model { observationIxs :: IM.IntMap (IM.IntMap Int) , transitionIxs :: IM.IntMap Int , values :: A.UArray Int Double , labelMax :: Int } instance Binary Model where put crf = put ( observationIxs crf , transitionIxs crf , values crf , labelMax crf ) get = do (observationIxs, transitionIxs, values, labelMax) <- get return Model { observationIxs = observationIxs , transitionIxs = transitionIxs , values = values , labelMax = labelMax } instance Show Model where show = unlines . map show . toList -- instance Read Model where -- read = fromList . map read' . lines where -- read' s = -- let (feat, val) = read s -- in feat `seq` val `seq` (feat, val) toList :: Model -> [(Feature, Double)] toList crf = [ (TFeature k x y z, v) | ((k, x, y, z), v) <- map dcdT $ IM.toList $ transitionIxs crf ] ++ [ (OFeature k o x, v) | (o, om) <- IM.toList $ observationIxs crf , ((k, x), v) <- map dcdO $ IM.toList om ] where dcdT = dcd decodeTFeat dcdO = dcd decodeOFeat dcd with (key, ix) = (with (labelMax crf) key, values crf A.! ix) fromList :: [(Feature, Double)] -> Model fromList fs = {-# SCC "modelFromList" #-} let featSublabels (OFeature _ _ x) = [x] featSublabels (TFeature _ x y z) = [x, y, z] featObvs (OFeature _ o _) = [o] featObvs _ = [] lmax = maximum $ concat $ map featSublabels $ map fst fs omax = maximum $ concat $ map featObvs $ map fst fs trsFeats = [feat | (feat, val) <- fs, isTransFeat feat] obsFeats = [feat | (feat, val) <- fs, isObsFeat feat] transitionIxs = IM.fromList $ zip [encodeTFeat lmax k x y z | TFeature k x y z <- trsFeats] [0 ..] observationIxs = IM.fromList [ (o, IM.fromList [ (encodeOFeat lmax k x, ix) | (OFeature k _ x, ix) <- fs ]) | (o, fs) <- groupObsFeatures obsFeats' ] where obsFeats' = zip obsFeats [ length trsFeats .. ] groupObsFeatures fs = IM.toList $ IM.fromListWith (++) [ (o, [(feat, ix)]) | (feat@(OFeature _ o _), ix) <- fs ] values = A.array (0, length fs - 1) [(i, 0.0) | i <- [0 .. length fs - 1]] A.// [(featToIx feat model, val) | (feat, val) <- fs] model = Model { labelMax = lmax , values = values , transitionIxs = transitionIxs , observationIxs = observationIxs } in model modelSize :: Model -> Int modelSize crf = -- snd $ A.bounds $ values crf (IM.size $ transitionIxs crf) + (sum $ map IM.size $ IM.elems $ observationIxs crf) -- type Student = (Model, MA.MarkedArray) --data Student = Student -- { learned :: Model -- , gradBufs :: [Gradient] } makeModel :: [Feature] -> Model makeModel fs = fromList [(feat, 0.0) | feat <- fs'] where fs' = Set.toList $ Set.fromList fs --makeStudent :: Model -> Int -> Student --makeStudent crf k = Student -- { learned = crf -- , gradBufs = replicate k -- $ MA.new -- $ modelSize crf } -- !TODO!: rozwazyc, co gdy numer etykiety wykracza -- poza zakres !! dodac Maybe ? Wczesniej rozwiazaniem -- bylo m = lmax + 3 !! -- return (k, xs); should satisfy: -- (k, xs) = decode lmax $ encode lmax k xs -- encode :: Int -> Int -> [Int] -> Int -- encode lmax k xs = -- foldl' (\acc x -> acc * m + x) k xs' -- where -- xs' = take 3 $ [x + 1 | x <- xs] ++ [0, 0 ..] -- m = lmax + 2 -- ASSUMPTION: 0 <= x, y, z <= lmax encodeTFeat :: Int -> Level -> Int -> Int -> Int -> Int encodeTFeat lmax k x y z = if any (== unknown) [x, y, z] then -1 else foldl' (\acc x -> acc * m + x) k [x, y, z] where m = lmax + 1 encodeOFeat :: Int -> Level -> Int -> Int encodeOFeat lmax k x = if x == unknown then -1 else k * m + x where m = lmax + 1 decodeTFeat :: Int -> Int -> (Int, Int, Int, Int) decodeTFeat lmax n = (k, x, y, z) where (k, [x, y, z]) = it !! 3 it = iterate f (n, []) f (n, acc) = (n `div` m, (n `mod` m):acc) m = lmax + 1 decodeOFeat :: Int -> Int -> (Int, Int) decodeOFeat lmax n = (n `div` m, n `mod` m) where m = lmax + 1 oFeatToIx :: Level -> Observation -> Int -> Model -> Maybe Int oFeatToIx k o x crf = do obsMap <- IM.lookup o $ observationIxs crf IM.lookup (encodeOFeat lmax k x) obsMap where lmax = labelMax crf tFeatToIx :: Level -> Int -> Int -> Int -> Model -> Maybe Int tFeatToIx k x y z crf = IM.lookup (encodeTFeat lmax k x y z) $ transitionIxs crf where lmax = labelMax crf featToIx :: Feature -> Model -> Int featToIx feat crf = fromJust $ case feat of TFeature k x y z -> tFeatToIx k x y z crf OFeature k o x -> oFeatToIx k o x crf consumeWith :: (Double -> Double -> Double) -> [(Int, Double)] -> Model -> IO Model consumeWith f xs crf = do arr <- A.unsafeThaw $ values crf :: IO (A.IOUArray Int Double) forM_ xs $ \(i, v) -> do w <- A.readArray arr i A.writeArray arr i $! f w v arr' <- A.unsafeFreeze arr return Model { labelMax = labelMax crf , values = arr' , transitionIxs = transitionIxs crf , observationIxs = observationIxs crf } onOFeat :: Level -> Observation -> Int -> Model -> Double onOFeat k o x crf = case oFeatToIx k o x crf of Just ix -> values crf A.! ix Nothing -> 0.0 onTFeat :: Level -> Int -> Int -> Int -> Model -> Double onTFeat k x y z crf = case tFeatToIx k x y z crf of Just ix -> values crf A.! ix Nothing -> 0.0 mapModel :: (Double -> Double) -> Model -> IO Model mapModel f crf = do arr <- A.unsafeThaw $ values crf :: IO (A.IOUArray Int Double) n <- return $ snd $ A.bounds $ values crf forM_ [0 .. n - 1] $ \i -> A.writeArray arr i . f =<< A.readArray arr i arr' <- A.unsafeFreeze arr return Model { labelMax = labelMax crf , transitionIxs = transitionIxs crf , observationIxs = observationIxs crf , values = arr' } -- parallel version mapModel' :: Int -> (Double -> Double) -> Model -> IO Model mapModel' k f crf = do let n = snd $ A.bounds $ values crf ps = (n `div` k) + 1 uppers = [i * ps | i <- [1 .. k - 1]] ++ [n] bounds = zip (0 : uppers) uppers arr <- A.unsafeThaw $ values crf :: IO (A.IOUArray Int Double) com <- newEmptyMVar forM_ bounds $ \(p, q) -> forkIO $ do forM_ [p .. q - 1] $ \i -> A.writeArray arr i . f =<< A.readArray arr i putMVar com () sequence [takeMVar com | _ <- bounds] -- forM_ [0 .. n - 1] $ -- \i -> A.writeArray arr i . f =<< A.readArray arr i arr' <- A.unsafeFreeze arr return Model { labelMax = labelMax crf , transitionIxs = transitionIxs crf , observationIxs = observationIxs crf , values = arr' }
kawu/tagger
src/CRF/Model/Internal.hs
bsd-3-clause
8,088
0
17
2,538
2,797
1,512
1,285
192
3
-- Copyright 2013 Thomas Szczarkowski module Ciphers where import Data.Bits import Data.Word import Data.List import Text.Printf import Control.Monad import Control.Arrow import Control.Exception import OpenSSL.Symmetric import OpenSSL.Random import Bytes -- OpenSSL block ciphers (128 bit only) -- Hacked from OpenSSL's ECB mode by stripping padding -- 'cipher' is an OpenSSL EVP_CIPHER* for the corresponding ECB mode, e.g.: aes = c_EVP_aes_128_ecb -- AES-128 blockCipher Encrypt cipher key input = do check (length input == 16) "Block cipher given an invalid input: block is not 16 bytes long" paddedOutput <- sslSymmetric Encrypt cipher (encode key) (encode $ 16 # 0) (encode input) return $ take 16 $ decode paddedOutput blockCipher Decrypt cipher key input = do check (length input == 16) "Block cipher given an invalid input: block is not 16 bytes long" padding <- blockCipher Encrypt cipher key (16 # 16) output <- sslSymmetric Decrypt cipher (encode key) (encode $ 16 # 0) (encode $ input ++ padding) return $ decode output -- modes of operation data Mode = ECB | CBC | CTR deriving Eq encrypt ECB cipher key iv input = liftM unblocks $ mapM (blockCipher Encrypt cipher key) (blocks $ pad 16 input) encrypt CBC cipher key iv input = liftM unblocks $ sequence $ scanl f (return iv) (blocks $ pad 16 input) where f chain plaintext = blockCipher Encrypt cipher key =<< liftM (xorBuffers plaintext) chain decrypt ECB cipher key input = liftM (unpad . unblocks) $ mapM (blockCipher Decrypt cipher key) (blocks input) decrypt CBC cipher key input = liftM (unpad . unblocks . zipWith xorBuffers (blocks input)) $ mapM (blockCipher Decrypt cipher key) (drop 1 $ blocks input) -- group bytes into 128-bit blocks blocks [] = [] blocks text = let (b,bs) = splitAt 16 text in b : blocks bs unblocks = concat -- PKCS #7 padding pad n input = let slack = n - length input `mod` n in input ++ slack # (fromIntegral slack :: Word8) unpad input = let slack = fromIntegral $ last input in take (length input - slack) input unpadStrict n input = if input == (pad n . unpad) input then Just $ unpad input else Nothing check cond err = if cond then return () else throw $ userError err n # x = replicate n x -- 4 # 'A' == "AAAA" infixl 8 # each xs f = sequence $ map f xs infixl 1 `each` xorBuffers a b = zipWith xor a b
tom-szczarkowski/matasano-crypto-puzzles-solutions
set6/Ciphers.hs
mit
2,501
0
11
604
822
412
410
53
2
{-# LANGUAGE ExistentialQuantification #-} module Zeno ( Bool (..), Equals (..), Prop, prove, proveBool, given, givenBool, ($), otherwise ) where import Prelude ( Bool (..) ) infix 1 :=: infixr 0 $ ($) :: (a -> b) -> a -> b f $ x = f x otherwise :: Bool otherwise = True data Equals = forall a . (:=:) a a data Prop = Given Equals Prop | Prove Equals prove :: Equals -> Prop prove = Prove given :: Equals -> Prop -> Prop given = Given proveBool :: Bool -> Prop proveBool p = Prove (p :=: True) givenBool :: Bool -> Prop -> Prop givenBool p = Given (p :=: True)
Gurmeet-Singh/Zeno
test/Zeno.hs
mit
584
17
8
138
241
138
103
25
1
{- | Module : ./Propositional/Conversions.hs Description : Helper functions for proofs in propositional logic Copyright : (c) Dominik Luecke, Uni Bremen 2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : luecke@informatik.uni-bremen.de Stability : experimental Portability : portable Helper functions for printing of Theories in DIMACS-CNF Format -} module Propositional.Conversions ( showDIMACSProblem , goalDIMACSProblem , createSignMap , mapClause ) where import qualified Common.AS_Annotation as AS_Anno import qualified Common.Id as Id import Common.DocUtils import Data.Maybe import qualified Data.Map as Map import qualified Data.Set as Set import qualified Propositional.AS_BASIC_Propositional as AS import qualified Propositional.ProverState as PState import qualified Propositional.Sign as Sig import Propositional.Fold -- | make a DIMACS Problem for SAT-Solvers goalDIMACSProblem :: String -- ^ name of the theory -> PState.PropProverState -- ^ initial Prover state -> AS_Anno.Named AS.FORMULA -- ^ goal to prove -> [String] -- ^ Options (ignored) -> IO String goalDIMACSProblem thName pState conjec _ = do let sign = PState.initialSignature pState axs = PState.initialAxioms pState showDIMACSProblem thName sign axs $ Just conjec -- | Translation of a Propositional Formula to a String in DIMACS Format showDIMACSProblem :: String -- ^ name of the theory -> Sig.Sign -- ^ Signature -> [AS_Anno.Named AS.FORMULA] -- ^ Axioms -> Maybe (AS_Anno.Named AS.FORMULA) -- ^ Conjectures -> IO String -- ^ Output showDIMACSProblem name fSig axs mcons = do let negatedCons = case mcons of Nothing -> [] Just cons -> [AS_Anno.mapNamed (negForm Id.nullRange) cons] tAxs = map (AS_Anno.mapNamed cnf) axs tCon = fmap (AS_Anno.mapNamed cnf) negatedCons flatSens = getConj . flip mkConj Id.nullRange . map AS_Anno.sentence tfAxs = flatSens tAxs tfCon = flatSens tCon numVars = Set.size $ Sig.items fSig numClauses = length tfAxs + length tfCon sigMap = createSignMap fSig 1 Map.empty fct = map (++ " 0") . concatMap (`mapClauseAux` sigMap) return $ unlines $ [ "c " ++ name, "p cnf " ++ show numVars ++ " " ++ show numClauses] ++ (if null tfAxs then [] else "c Axioms" : fct tfAxs) ++ if null tfCon || isNothing mcons then [] else "c Conjectures" : fct tfCon -- | Create signature map createSignMap :: Sig.Sign -> Integer -- ^ Starting number of the variables -> Map.Map Id.Token Integer -> Map.Map Id.Token Integer createSignMap sig inNum inMap = let it = Sig.items sig minL = Set.findMin it nSig = Sig.Sign {Sig.items = Set.deleteMin it} in if Set.null it then inMap else createSignMap nSig (inNum + 1) (Map.insert (Sig.id2SimpleId minL) inNum inMap) -- | Mapping of a single Clause mapClause :: AS.FORMULA -> Map.Map Id.Token Integer -> String mapClause form = unlines . map (++ " 0") . mapClauseAux form -- | Mapping of a single Clause mapClauseAux :: AS.FORMULA -> Map.Map Id.Token Integer -> [String] mapClauseAux form mapL = case form of -- unused case: AS.Conjunction ts _ -> map (`mapLiteral` mapL) ts AS.True_atom _ -> [] AS.False_atom _ -> ["-1", "1"] _ -> [mapLiteral form mapL] -- | Mapping of a single literal mapLiteral :: AS.FORMULA -> Map.Map Id.Token Integer -> String mapLiteral f mapL = case f of AS.Disjunction ts _ -> unwords $ map (`mapLiteral` mapL) ts AS.Negation n _ -> '-' : mapLiteral n mapL AS.Predication tok -> show (Map.findWithDefault 0 tok mapL) _ -> error $ "Impossible clause case: " ++ showDoc f ""
spechub/Hets
Propositional/Conversions.hs
gpl-2.0
4,084
0
17
1,186
967
507
460
78
4
{-# LANGUAGE ExistentialQuantification #-} module TestRunner(main) where import System.Environment (getArgs) import Control.Arrow ((>>>)) import Test import Test.QuickCheck import RewriteRules import Bag data Test = forall a. (Testable a) => Test String String a tests :: [Test] tests = [ Test "Simplify" "Idempotent" prop_simplify_idempotent, Test "Dedual" "Only negative atoms" prop_dedual_onlyNegativeAtoms, Test "Unexpt" "In Exponential Lattice" prop_unexpt_inExponentialLattice1, Test "Unexpt" "In Exponential Lattice" prop_unexpt_inExponentialLattice2, Test "Subbag" "Reflexive" prop_subbag_reflexive, Test "Subbag" "Less" prop_subbag_less, Test "Subbag" "More" prop_subbag_more, Test "Parser" "Print and Parse is Identity" prop_printParse_ident ] runTest :: Test -> IO () runTest (Test mod name prop) = do let title = concat [mod, " -- ", name] putStrLn title quickCheckWith (stdArgs {maxSuccess = 10000}) prop runTests :: [Test] -> IO () runTests tests = mapM_ runTest tests modname :: Test -> String modname (Test mod _ _) = mod main = do args <- getArgs case args of [m] -> runTests $ filter (modname >>> (== m)) tests _ -> runTests tests
jff/TeLLer
tests/TestRunner.hs
gpl-3.0
1,266
0
14
276
358
190
168
37
2
import GHC.Unicode import Data.Ix ( index ) main :: IO () main = do putStrLn "\xFFFF" putStrLn "\x10000" putStrLn "\x1F600" putStrLn "\x10FFFF" putStrLn "7" putStrLn "S" putStrLn "△" putStrLn "☃" putStrLn "¥" putStrLn "n̂" print $ UppercaseLetter == UppercaseLetter print $ UppercaseLetter == LowercaseLetter print $ NonSpacingMark <= MathSymbol print $ enumFromTo ModifierLetter SpacingCombiningMark print (read "DashPunctuation" :: GeneralCategory) print $ show EnclosingMark print (minBound :: GeneralCategory) print (maxBound :: GeneralCategory) print $ index (OtherLetter,Control) FinalQuote print $ generalCategory 'a' print $ generalCategory 'A' print $ generalCategory '0' print $ generalCategory '%' print $ generalCategory '♥' print $ generalCategory '\31' print $ generalCategory ' ' print $ isPunctuation 'a' print $ isPunctuation '7' print $ isPunctuation '♥' print $ isPunctuation '"' print $ isPunctuation '?' print $ isPunctuation '—' print $ isSymbol 'a' print $ isSymbol '6' print $ isSymbol '=' print $ isSymbol '+' print $ isSymbol '-' print $ isSymbol '<'
rahulmutt/ghcvm
tests/suite/basic/run/Unicode.hs
bsd-3-clause
1,166
0
9
230
393
165
228
42
1
module PTS.Syntax ( -- * Abstract syntax -- ** Names Name , Names , freshvarl , LanguageName , ModuleName (..) , parts -- ** Constants , C (C) , int , star , box , triangle , circle -- ** Arithmetic operators , BinOp (Add, Sub, Mul, Div) , evalOp -- ** Term structure , TermStructure (..) , Structure (structure) , structure' -- ** Folding , PreAlgebra , Algebra , fold , depZip -- ** Plain terms , Term , strip , mkInt , mkIntOp , mkIfZero , mkVar , mkConst , mkApp , mkLam , mkPi , mkSortedPi , mkPos , mkUnquote , mkInfer , handlePos -- ** Annotated terms , AnnotatedTerm , annotation , annotatedHandlePos -- ** Typed terms , TypedTerm , typeOf , sortOf , typedHandlePos -- ** Telescopes , Telescope , foldTelescope -- ** Statements , Stmt (..) -- ** Files , File (..) -- * Concrete syntax -- ** Parser , parseFile , parseStmt , parseStmts , parseTerm , parseTermAtPos -- ** Printer , Pretty (pretty) , singleLine , multiLine , showPretty , showCtx , showAssertion -- * Operations , allvars , freevars , freshvar , Diff , diff , showDiff , subst -- , typedSubst -- * Algebras , allvarsAlgebra , freevarsAlgebra , prettyAlgebra ) where import PTS.Syntax.Algebra import PTS.Syntax.Constants import PTS.Syntax.Diff import PTS.Syntax.File import PTS.Syntax.Names import PTS.Syntax.Parser import PTS.Syntax.Pretty import PTS.Syntax.Statement import PTS.Syntax.Substitution import PTS.Syntax.Telescope import PTS.Syntax.Term import PTS.Dynamics.TypedTerm
Toxaris/pts
src-lib/PTS/Syntax.hs
bsd-3-clause
1,662
0
5
446
340
237
103
90
0
-- | Provides the configurable prototype implementation of the supermonad -- plugin. This can essentially be used with any type classes when configured -- correctly. module Control.Super.Plugin.Prototype ( pluginPrototype ) where import Data.Maybe ( isJust, isNothing, fromJust, catMaybes ) import Data.Foldable ( foldrM ) import Control.Monad ( forM ) import Plugins ( Plugin(tcPlugin), defaultPlugin ) import TcRnTypes ( Ct(..) , TcPlugin(..), TcPluginResult(..) ) import TcPluginM ( TcPluginM ) import Outputable ( hang, text, vcat ) import qualified Outputable as O import Control.Super.Plugin.Utils ( errIndent ) --import qualified Control.Super.Plugin.Log as L import Control.Super.Plugin.InstanceDict ( InstanceDict ) import Control.Super.Plugin.ClassDict ( ClassDict ) import Control.Super.Plugin.Solving ( solveConstraints ) import Control.Super.Plugin.Environment ( SupermonadPluginM , runSupermonadPluginAndReturn, runTcPlugin , getWantedConstraints , getClass, getClassDictionary , isOptionalClass , throwPluginErrorSDoc , printMsg -- , printObj, printConstraints ) import Control.Super.Plugin.Environment.Lift ( findClassesAndInstancesInScope ) import Control.Super.Plugin.Detect ( ModuleQuery(..) , ClassQuery(..) , moduleQueryOf, isOptionalClassQuery , InstanceImplication , checkInstances , findModuleByQuery , findMonoTopTyConInstances ) import Control.Super.Plugin.Names ( PluginClassName ) -- ----------------------------------------------------------------------------- -- The Plugin -- ----------------------------------------------------------------------------- -- | Type of the state used in the supermonad plugin. type SupermonadState = () -- | The supermonad type checker plugin for GHC. pluginPrototype :: [ClassQuery] -- ^ The classes that the plugin will solve for. -> [[PluginClassName]] -- ^ The sets of class names that require being solved together. -> (ClassDict -> [InstanceImplication]) -- ^ The depedencies between different class instances, that -- cannot be implemented using the Haskell type class definitiisOptionalClassQueryons. -> Plugin pluginPrototype clsQueries solvingGroups instImps = defaultPlugin { tcPlugin = \_clOpts -> Just plugin } where plugin :: TcPlugin plugin = TcPlugin { tcPluginInit = pluginInit , tcPluginSolve = pluginSolve , tcPluginStop = pluginStop } -- | No initialization needs takes place. pluginInit :: TcPluginM SupermonadState pluginInit = return () -- | No clean up needs to take place. pluginStop :: SupermonadState -> TcPluginM () pluginStop _s = return () -- | The plugin code wrapper. Handles execution of the monad stack. pluginSolve :: SupermonadState -> [Ct] -> [Ct] -> [Ct] -> TcPluginM TcPluginResult pluginSolve _s given derived wanted = do runSupermonadPluginAndReturn (given ++ derived) wanted initSupermonadPlugin $ do printMsg "Invoke (super) plugin..." forM solvingGroups $ \solvingGroup -> do -- Find the classes in the solving group. mClss <- fmap catMaybes $ forM solvingGroup $ \clsName -> do mCls <- getClass clsName opt <- isOptionalClass clsName -- Optional classes that are not available, can be ignored while solving return $ if opt && isNothing mCls then Nothing else Just (clsName, mCls) -- If we found all of the classes in the solving group -- (except the optional ones), we can try to solve the constraints. if all (isJust . snd) mClss then do wantedCts <- getWantedConstraints solveConstraints (fmap (fromJust . snd) mClss) wantedCts -- We could not find all of the classes in the solving group: -- Throw an error listing the missing classes. else do throwPluginErrorSDoc $ O.hang (O.text "Missing classes:") errIndent $ O.hcat $ O.punctuate (O.text ", ") $ fmap (O.quotes . O.text . fst) $ filter (isNothing . snd) mClss -- | Initialize the plugin environment. initSupermonadPlugin :: SupermonadPluginM () (ClassDict, InstanceDict) initSupermonadPlugin = do -- Determine which modules are mandatory: let getMandMdlQ :: ClassQuery -> Maybe ModuleQuery getMandMdlQ clsQ = if isOptionalClassQuery clsQ then Nothing else Just (moduleQueryOf clsQ) let mandMdlQs = catMaybes $ fmap getMandMdlQ clsQueries -- Determine if the mandatory modules are available. _foundMandMdls <- forM mandMdlQs $ \mdlQ -> do eMandMdl <- runTcPlugin $ findModuleByQuery mdlQ case eMandMdl of Right mandMdl -> return mandMdl Left mdlErrMsg -> throwPluginErrorSDoc mdlErrMsg -- Find the classes and instances and add the to the class dictionary. oldClsDict <- getClassDictionary newClsDict <- foldrM findClassesAndInstancesInScope oldClsDict clsQueries -- Calculate the mono-top-tycon instances in scope and check for rogue poly-top-tycon instances. let smInsts = findMonoTopTyConInstances newClsDict let smErrors = fmap snd $ checkInstances newClsDict smInsts (instImps newClsDict) -- Try to construct the environment or throw errors case smErrors of [] -> return (newClsDict, smInsts) _ -> do throwPluginErrorSDoc $ hang (text "Problems when finding instances:") errIndent $ vcat smErrors
jbracker/supermonad-plugin
src/Control/Super/Plugin/Prototype.hs
bsd-3-clause
5,841
0
27
1,541
1,017
562
455
89
6
{-| Module : IRTS.Portable Description : Serialise Idris' IR to JSON. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE FlexibleInstances, OverloadedStrings, TypeSynonymInstances #-} module IRTS.Portable (writePortable) where import Idris.Core.CaseTree import Idris.Core.Evaluate import Idris.Core.TT import IRTS.Bytecode import IRTS.CodegenCommon import IRTS.Defunctionalise import IRTS.Lang import IRTS.Simplified import Data.Aeson import qualified Data.ByteString.Lazy as B import qualified Data.Text as T import System.IO data CodegenFile = CGFile { fileType :: String, version :: Int, cgInfo :: CodegenInfo } -- Update the version when the format changes formatVersion :: Int formatVersion = 3 writePortable :: Handle -> CodegenInfo -> IO () writePortable file ci = do let json = encode $ CGFile "idris-codegen" formatVersion ci B.hPut file json instance ToJSON CodegenFile where toJSON (CGFile ft v ci) = object ["file-type" .= ft, "version" .= v, "codegen-info" .= toJSON ci] instance ToJSON CodegenInfo where toJSON ci = object ["output-file" .= (outputFile ci), "includes" .= (includes ci), "import-dirs" .= (importDirs ci), "compile-objs" .= (compileObjs ci), "compile-libs" .= (compileLibs ci), "compiler-flags" .= (compilerFlags ci), "interfaces" .= (interfaces ci), "exports" .= (exportDecls ci), "lift-decls" .= (liftDecls ci), "defun-decls" .= (defunDecls ci), "simple-decls" .= (simpleDecls ci), "bytecode" .= (map toBC (simpleDecls ci)), "tt-decls" .= (ttDecls ci)] instance ToJSON Name where toJSON n = toJSON $ showCG n instance ToJSON ExportIFace where toJSON (Export n f xs) = object ["ffi-desc" .= n, "interface-file" .= f, "exports" .= xs] instance ToJSON FDesc where toJSON (FCon n) = object ["FCon" .= n] toJSON (FStr s) = object ["FStr" .= s] toJSON (FUnknown) = object ["FUnknown" .= Null] toJSON (FIO fd) = object ["FIO" .= fd] toJSON (FApp n xs) = object ["FApp" .= (n, xs)] instance ToJSON Export where toJSON (ExportData fd) = object ["ExportData" .= fd] toJSON (ExportFun n dsc ret args) = object ["ExportFun" .= (n, dsc, ret, args)] instance ToJSON LDecl where toJSON (LFun opts name args def) = object ["LFun" .= (opts, name, args, def)] toJSON (LConstructor name tag ar) = object ["LConstructor" .= (name, tag, ar)] instance ToJSON LOpt where toJSON Inline = String "Inline" toJSON NoInline = String "NoInline" instance ToJSON LExp where toJSON (LV lv) = object ["LV" .= lv] toJSON (LApp tail exp args) = object ["LApp" .= (tail, exp, args)] toJSON (LLazyApp name exps) = object ["LLazyApp" .= (name, exps)] toJSON (LLazyExp exp) = object ["LLazyExp" .= exp] toJSON (LForce exp) = object ["LForce" .= exp] toJSON (LLet name a b) = object ["LLet" .= (name, a, b)] toJSON (LLam args exp) = object ["LLam" .= (args, exp)] toJSON (LProj exp i) = object ["LProj" .= (exp, i)] toJSON (LCon lv i n exps) = object ["LCon" .= (lv, i, n, exps)] toJSON (LCase ct exp alts) = object ["LCase" .= (ct, exp, alts)] toJSON (LConst c) = object ["LConst" .= c] toJSON (LForeign fd ret exps) = object ["LForeign" .= (fd, ret, exps)] toJSON (LOp prim exps) = object ["LOp" .= (prim, exps)] toJSON LNothing = object ["LNothing" .= Null] toJSON (LError s) = object ["LError" .= s] instance ToJSON LVar where toJSON (Loc i) = object ["Loc" .= i] toJSON (Glob n) = object ["Glob" .= n] instance ToJSON CaseType where toJSON Updatable = String "Updatable" toJSON Shared = String "Shared" instance ToJSON LAlt where toJSON (LConCase i n ns exp) = object ["LConCase" .= (i, n, ns, exp)] toJSON (LConstCase c exp) = object ["LConstCase" .= (c, exp)] toJSON (LDefaultCase exp) = object ["LDefaultCase" .= exp] instance ToJSON Const where toJSON (I i) = object ["int" .= i] toJSON (BI i) = object ["bigint" .= (show i)] toJSON (Fl d) = object ["double" .= d] toJSON (Ch c) = object ["char" .= (show c)] toJSON (Str s) = object ["string" .= s] toJSON (B8 b) = object ["bits8" .= b] toJSON (B16 b) = object ["bits16" .= b] toJSON (B32 b) = object ["bits32" .= b] toJSON (B64 b) = object ["bits64" .= b] toJSON (AType at) = object ["atype" .= at] toJSON StrType = object ["strtype" .= Null] toJSON WorldType = object ["worldtype" .= Null] toJSON TheWorld = object ["theworld" .= Null] toJSON VoidType = object ["voidtype" .= Null] toJSON Forgot = object ["forgot" .= Null] instance ToJSON ArithTy where toJSON (ATInt it) = object ["ATInt" .= it] toJSON ATFloat = object ["ATFloat" .= Null] instance ToJSON IntTy where toJSON it = toJSON $ intTyName it instance ToJSON PrimFn where toJSON (LPlus aty) = object ["LPlus" .= aty] toJSON (LMinus aty) = object ["LMinus" .= aty] toJSON (LTimes aty) = object ["LTimes" .= aty] toJSON (LUDiv aty) = object ["LUDiv" .= aty] toJSON (LSDiv aty) = object ["LSDiv" .= aty] toJSON (LURem ity) = object ["LURem" .= ity] toJSON (LSRem aty) = object ["LSRem" .= aty] toJSON (LAnd ity) = object ["LAnd" .= ity] toJSON (LOr ity) = object ["LOr" .= ity] toJSON (LXOr ity) = object ["LXOr" .= ity] toJSON (LCompl ity) = object ["LCompl" .= ity] toJSON (LSHL ity) = object ["LSHL" .= ity] toJSON (LLSHR ity) = object ["LLSHR" .= ity] toJSON (LASHR ity) = object ["LASHR" .= ity] toJSON (LEq aty) = object ["LEq" .= aty] toJSON (LLt ity) = object ["LLt" .= ity] toJSON (LLe ity) = object ["LLe" .= ity] toJSON (LGt ity) = object ["LGt" .= ity] toJSON (LGe ity) = object ["LGe" .= ity] toJSON (LSLt aty) = object ["LSLt" .= aty] toJSON (LSLe aty) = object ["LSLe" .= aty] toJSON (LSGt aty) = object ["LSGt" .= aty] toJSON (LSGe aty) = object ["LSGe" .= aty] toJSON (LZExt from to) = object ["LZExt" .= (from, to)] toJSON (LSExt from to) = object ["LSExt" .= (from, to)] toJSON (LTrunc from to) = object ["LTrunc" .= (from, to)] toJSON LStrConcat = object ["LStrConcat" .= Null] toJSON LStrLt = object ["LStrLt" .= Null] toJSON LStrEq = object ["LStrEq" .= Null] toJSON LStrLen = object ["LStrLen" .= Null] toJSON (LIntFloat ity) = object ["LIntFloat" .= ity] toJSON (LFloatInt ity) = object ["LFloatInt" .= ity] toJSON (LIntStr ity) = object ["LIntStr" .= ity] toJSON (LStrInt ity) = object ["LStrInt" .= ity] toJSON (LIntCh ity) = object ["LIntCh" .= ity] toJSON (LChInt ity) = object ["LChInt" .= ity] toJSON LFloatStr = object ["LFloatStr" .= Null] toJSON LStrFloat = object ["LStrFloat" .= Null] toJSON (LBitCast from to) = object ["LBitCast" .= (from, to)] toJSON LFExp = object ["LFExp" .= Null] toJSON LFLog = object ["LFLog" .= Null] toJSON LFSin = object ["LFSin" .= Null] toJSON LFCos = object ["LFCos" .= Null] toJSON LFTan = object ["LFTan" .= Null] toJSON LFASin = object ["LFASin" .= Null] toJSON LFACos = object ["LFACos" .= Null] toJSON LFATan = object ["LFATan" .= Null] toJSON LFSqrt = object ["LFSqrt" .= Null] toJSON LFFloor = object ["LFFloor" .= Null] toJSON LFCeil = object ["LFCeil" .= Null] toJSON LFNegate = object ["LFNegate" .= Null] toJSON LStrHead = object ["LStrHead" .= Null] toJSON LStrTail = object ["LStrTail" .= Null] toJSON LStrCons = object ["LStrCons" .= Null] toJSON LStrIndex = object ["LStrIndex" .= Null] toJSON LStrRev = object ["LStrRev" .= Null] toJSON LStrSubstr = object ["LStrSubstr" .= Null] toJSON LReadStr = object ["LReadStr" .= Null] toJSON LWriteStr = object ["LWriteStr" .= Null] toJSON LSystemInfo = object ["LSystemInfo" .= Null] toJSON LFork = object ["LFork" .= Null] toJSON LPar = object ["LPar" .= Null] toJSON (LExternal name) = object ["LExternal" .= name] toJSON LCrash = object ["LCrash" .= Null] toJSON LNoOp = object ["LNoOp" .= Null] instance ToJSON DDecl where toJSON (DFun name args exp) = object ["DFun" .= (name, args, exp)] toJSON (DConstructor name tag arity) = object ["DConstructor" .= (name, tag, arity)] instance ToJSON DExp where toJSON (DV lv) = object ["DV" .= lv] toJSON (DApp tail name exps) = object ["DApp" .= (tail, name, exps)] toJSON (DLet name a b) = object ["DLet" .= (name, a, b)] toJSON (DUpdate name exp) = object ["DUpdate" .= (name,exp)] toJSON (DProj exp i) = object ["DProj" .= (exp, i)] toJSON (DC lv i name exp) = object ["DC" .= (lv, i, name, exp)] toJSON (DCase ct exp alts) = object ["DCase" .= (ct, exp, alts)] toJSON (DChkCase exp alts) = object ["DChkCase" .= (exp, alts)] toJSON (DConst c) = object ["DConst" .= c] toJSON (DForeign fd ret exps) = object ["DForeign" .= (fd, ret, exps)] toJSON (DOp prim exps) = object ["DOp" .= (prim, exps)] toJSON DNothing = object ["DNothing" .= Null] toJSON (DError s) = object ["DError" .= s] instance ToJSON DAlt where toJSON (DConCase i n ns exp) = object ["DConCase" .= (i, n, ns, exp)] toJSON (DConstCase c exp) = object ["DConstCase" .= (c, exp)] toJSON (DDefaultCase exp) = object ["DDefaultCase" .= exp] instance ToJSON SDecl where toJSON (SFun name args i exp) = object ["SFun" .= (name, args, i, exp)] instance ToJSON SExp where toJSON (SV lv) = object ["SV" .= lv] toJSON (SApp tail name exps) = object ["SApp" .= (tail, name, exps)] toJSON (SLet lv a b) = object ["SLet" .= (lv, a, b)] toJSON (SUpdate lv exp) = object ["SUpdate" .= (lv, exp)] toJSON (SProj lv i) = object ["SProj" .= (lv, i)] toJSON (SCon lv i name vars) = object ["SCon" .= (lv, i, name, vars)] toJSON (SCase ct lv alts) = object ["SCase" .= (ct, lv, alts)] toJSON (SChkCase lv alts) = object ["SChkCase" .= (lv, alts)] toJSON (SConst c) = object ["SConst" .= c] toJSON (SForeign fd ret exps) = object ["SForeign" .= (fd, ret, exps)] toJSON (SOp prim vars) = object ["SOp" .= (prim, vars)] toJSON SNothing = object ["SNothing" .= Null] toJSON (SError s) = object ["SError" .= s] instance ToJSON SAlt where toJSON (SConCase i j n ns exp) = object ["SConCase" .= (i, j, n, ns, exp)] toJSON (SConstCase c exp) = object ["SConstCase" .= (c, exp)] toJSON (SDefaultCase exp) = object ["SDefaultCase" .= exp] instance ToJSON BC where toJSON (ASSIGN r1 r2) = object ["ASSIGN" .= (r1, r2)] toJSON (ASSIGNCONST r c) = object ["ASSIGNCONST" .= (r, c)] toJSON (UPDATE r1 r2) = object ["UPDATE" .= (r1, r2)] toJSON (MKCON con mr i regs) = object ["MKCON" .= (con, mr, i, regs)] toJSON (CASE b r alts def) = object ["CASE" .= (b, r, alts, def)] toJSON (PROJECT r loc arity) = object ["PROJECT" .= (r, loc, arity)] toJSON (PROJECTINTO r1 r2 loc) = object ["PROJECTINTO" .= (r1, r2, loc)] toJSON (CONSTCASE r alts def) = object ["CONSTCASE" .= (r, alts, def)] toJSON (CALL name) = object ["CALL" .= name] toJSON (TAILCALL name) = object ["TAILCALL" .= name] toJSON (FOREIGNCALL r fd ret exps) = object ["FOREIGNCALL" .= (r, fd, ret, exps)] toJSON (SLIDE i) = object ["SLIDE" .= i] toJSON (RESERVE i) = object ["RESERVE" .= i] toJSON (ADDTOP i) = object ["ADDTOP" .= i] toJSON (TOPBASE i) = object ["TOPBASE" .= i] toJSON (BASETOP i) = object ["BASETOP" .= i] toJSON REBASE = object ["REBASE" .= Null] toJSON STOREOLD = object ["STOREOLD" .= Null] toJSON (OP r prim args) = object ["OP" .= (r, prim, args)] toJSON (NULL r) = object ["NULL" .= r] toJSON (ERROR s) = object ["ERROR" .= s] instance ToJSON Reg where toJSON RVal = object ["RVal" .= Null] toJSON (T i) = object ["T" .= i] toJSON (L i) = object ["L" .= i] toJSON Tmp = object ["Tmp" .= Null] instance ToJSON RigCount where toJSON r = object ["RigCount" .= show r] instance ToJSON Totality where toJSON t = object ["Totality" .= show t] instance ToJSON MetaInformation where toJSON m = object ["MetaInformation" .= show m] instance ToJSON Def where toJSON (Function ty tm) = object ["Function" .= (ty, tm)] toJSON (TyDecl nm ty) = object ["TyDecl" .= (nm, ty)] toJSON (Operator ty n f) = Null -- Operator and CaseOp omits same values as in IBC.hs toJSON (CaseOp info ty argTy _ _ cdefs) = object ["CaseOp" .= (info, ty, argTy, cdefs)] instance (ToJSON t) => ToJSON (TT t) where toJSON (P nt name term) = object ["P" .= (nt, name, term)] toJSON (V n) = object ["V" .= n] toJSON (Bind n b tt) = object ["Bind" .= (n, b, tt)] toJSON (App s t1 t2) = object ["App" .= (s, t1, t2)] toJSON (Constant c) = object ["Constant" .= c] toJSON (Proj tt n) = object ["Proj" .= (tt, n)] toJSON Erased = object ["Erased" .= Null] toJSON Impossible = object ["Impossible" .= Null] toJSON (Inferred tt) = object ["Inferred" .= tt] toJSON (TType u) = object ["TType" .= u] toJSON (UType u) = object ["UType" .= (show u)] instance ToJSON UExp where toJSON (UVar src n) = object ["UVar" .= (src, n)] toJSON (UVal n) = object ["UVal" .= n] instance (ToJSON t) => ToJSON (AppStatus t) where toJSON Complete = object ["Complete" .= Null] toJSON MaybeHoles = object ["MaybeHoles" .= Null] toJSON (Holes ns) = object ["Holes" .= ns] instance (ToJSON t) => ToJSON (Binder t) where toJSON (Lam rc bty) = object ["Lam" .= (rc, bty)] toJSON (Pi c i t k) = object ["Pi" .= (c, i, t, k)] toJSON (Let t v) = object ["Let" .= (t, v)] toJSON (NLet t v) = object ["NLet" .= (t, v)] toJSON (Hole t) = object ["Hole" .= (t)] toJSON (GHole l ns t) = object ["GHole" .= (l, ns, t)] toJSON (Guess t v) = object ["Guess" .= (t, v)] toJSON (PVar rc t) = object ["PVar" .= (rc, t)] toJSON (PVTy t) = object ["PVTy" .= (t)] instance ToJSON ImplicitInfo where toJSON (Impl a b c) = object ["Impl" .= (a, b, c)] instance ToJSON NameType where toJSON Bound = object ["Bound" .= Null] toJSON Ref = object ["Ref" .= Null] toJSON (DCon a b c) = object ["DCon" .= (a, b, c)] toJSON (TCon a b) = object ["TCon" .= (a, b)] instance ToJSON CaseDefs where toJSON (CaseDefs rt ct) = object ["Runtime" .= rt, "Compiletime" .= ct] instance (ToJSON t) => ToJSON (SC' t) where toJSON (Case ct n alts) = object ["Case" .= (ct, n, alts)] toJSON (ProjCase t alts) = object ["ProjCase" .= (t, alts)] toJSON (STerm t) = object ["STerm" .= t] toJSON (UnmatchedCase s) = object ["UnmatchedCase" .= s] toJSON ImpossibleCase = object ["ImpossibleCase" .= Null] instance (ToJSON t) => ToJSON (CaseAlt' t) where toJSON (ConCase n c ns sc) = object ["ConCase" .= (n, c, ns, sc)] toJSON (FnCase n ns sc) = object ["FnCase" .= (n, ns, sc)] toJSON (ConstCase c sc) = object ["ConstCase" .= (c, sc)] toJSON (SucCase n sc) = object ["SucCase" .= (n, sc)] toJSON (DefaultCase sc) = object ["DefaultCase" .= sc] instance ToJSON CaseInfo where toJSON (CaseInfo a b c) = object ["CaseInfo" .= (a, b, c)] instance ToJSON Accessibility where toJSON a = object ["Accessibility" .= show a]
Heather/Idris-dev
src/IRTS/Portable.hs
bsd-3-clause
15,562
0
12
3,862
6,857
3,561
3,296
309
1
module WASHExpression where import Monad import WASHFlags import qualified WASHUtil import WASHData import WASHOut code :: FLAGS -> [CodeFrag] -> ShowS code flags [] = id code flags (x:xs) = code' flags x . code flags xs code' :: FLAGS -> CodeFrag -> ShowS code' flags (HFrag h) = showString h code' flags (EFrag e) = runOut $ element flags e code' flags (CFrag cnts) = showChar '(' . runOut (contents flags [] cnts) . showChar ')' code' flags (AFrag attrs) = showChar '(' . WASHUtil.itemList (attribute flags) "CGI.empty" " >> " attrs . showChar ')' code' flags (VFrag var) = id code' flags _ = error "Unknown type: code" outMode :: Mode -> Out () outMode = outShowS . showMode showMode :: Mode -> ShowS showMode V = id showMode S = showString "_T" showMode F = showString "_S" element :: FLAGS -> Element -> Out [String] element flags (Element mode nm ats cnt et) = do outChar '(' outString "CGI." outString nm when (generateBT flags) $ outMode mode outChar '(' outShowS $ attributes flags ats rvs <- contents flags [] cnt outString "))" return rvs outRVS :: [String] -> Out () outRVS [] = outString "()" outRVS (x:xs) = do outChar '(' outString x mapM_ g xs outChar ')' where g x = do { outChar ','; outString x; } outRVSpat :: [String] -> Out () outRVSpat [] = outString "(_)" outRVSpat xs = outRVS xs contents :: FLAGS -> [String] -> [Content] -> Out [String] contents flags inRVS cts = case cts of [] -> do outString "return" outRVS inRVS return inRVS ct:cts -> do rvs <- content flags ct case rvs of [] -> case (cts, inRVS) of ([],[]) -> return [] _ -> do outString " >> " contents flags inRVS cts _ -> case (cts, inRVS) of ([],[]) -> return rvs _ -> do outString " >>= \\ " outRVSpat rvs outString " -> " contents flags (rvs ++ inRVS) cts content :: FLAGS -> Content -> Out [String] content flags (CElement elem) = element flags elem content flags (CText txt) = do text flags txt return [] content flags (CCode (VFrag var:c)) = do outShowS $ (showChar '(' . code flags c . showChar ')') return [var] content flags (CCode c) = do outShowS $ (showChar '(' . code flags c . showChar ')') return [] content flags (CComment cc) = do outShowS $ (showString "return (const () " . shows cc . showChar ')') return [] content flags (CReference txt) = do text flags txt return [] content flags c = error $ "Unknown type: content -- " ++ (show c) text :: FLAGS -> Text -> Out [String] text flags txt = do outString "CGI.rawtext" when (generateBT flags) $ outMode (textMode txt) outChar ' ' outs (textString txt) return [] attributes :: FLAGS -> [Attribute] -> ShowS attributes flags atts = f atts where f [] = id f (att:atts) = attribute flags att . showString " >> " . f atts attribute :: FLAGS -> Attribute -> ShowS attribute flags (Attribute m n v) = showString "(CGI.attr" . (if generateBT flags then (attrvalueBT m v) else id) . showChar ' ' . shows n . showString " " . attrvalue v . showString ")" attribute flags (AttrPattern pat) = showString "( " . showString pat . showString " )" attribute flags a = error $ "Unknown type: attribute -- " ++ (show a) attrvalue :: AttrValue -> ShowS attrvalue (AText t) = shows t attrvalue (ACode c) = showString "( " . showString c . showString " )" attrvalue a = error $ "Unknown type: attrvalue -- " ++ (show a) attrvalueBT :: Mode -> AttrValue -> ShowS attrvalueBT V _ = id attrvalueBT m (AText _) = showMode m . showChar 'S' attrvalueBT m (ACode _) = showMode m . showChar 'D' attrvalueBT m a = error $ "Unknown type: attrvalueBT -- " ++ (show a)
dcreager/cabal
tests/systemTests/wash2hs/hs/WASHExpression.hs
bsd-3-clause
3,844
20
17
1,009
1,611
767
844
141
5
{-# LANGUAGE MagicHash, NoImplicitPrelude, TypeFamilies, UnboxedTuples, MultiParamTypeClasses, RoleAnnotations #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Types -- Copyright : (c) The University of Glasgow 2009 -- License : see libraries/ghc-prim/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- GHC type definitions. -- Use GHC.Exts from the base package instead of importing this -- module directly. -- ----------------------------------------------------------------------------- module GHC.Types ( Bool(..), Char(..), Int(..), Word(..), Float(..), Double(..), Ordering(..), IO(..), isTrue#, SPEC(..), Nat, Symbol, Coercible, ) where import GHC.Prim infixr 5 : -- | (Kind) This is the kind of type-level natural numbers. data Nat -- | (Kind) This is the kind of type-level symbols. -- Declared here because class IP needs it data Symbol data [] a = [] | a : [a] data {-# CTYPE "HsBool" #-} Bool = False | True {- | The character type 'Char' is an enumeration whose values represent Unicode (or equivalently ISO\/IEC 10646) characters (see <http://www.unicode.org/> for details). This set extends the ISO 8859-1 (Latin-1) character set (the first 256 characters), which is itself an extension of the ASCII character set (the first 128 characters). A character literal in Haskell has type 'Char'. To convert a 'Char' to or from the corresponding 'Int' value defined by Unicode, use 'Prelude.toEnum' and 'Prelude.fromEnum' from the 'Prelude.Enum' class respectively (or equivalently 'ord' and 'chr'). -} data {-# CTYPE "HsChar" #-} Char = C# Char# -- | A fixed-precision integer type with at least the range @[-2^29 .. 2^29-1]@. -- The exact range for a given implementation can be determined by using -- 'Prelude.minBound' and 'Prelude.maxBound' from the 'Prelude.Bounded' class. data {-# CTYPE "HsInt" #-} Int = I# Int# -- |A 'Word' is an unsigned integral type, with the same size as 'Int'. data {-# CTYPE "HsWord" #-} Word = W# Word# -- | Single-precision floating point numbers. -- It is desirable that this type be at least equal in range and precision -- to the IEEE single-precision type. data {-# CTYPE "HsFloat" #-} Float = F# Float# -- | Double-precision floating point numbers. -- It is desirable that this type be at least equal in range and precision -- to the IEEE double-precision type. data {-# CTYPE "HsDouble" #-} Double = D# Double# data Ordering = LT | EQ | GT {- | A value of type @'IO' a@ is a computation which, when performed, does some I\/O before returning a value of type @a@. There is really only one way to \"perform\" an I\/O action: bind it to @Main.main@ in your program. When your program is run, the I\/O will be performed. It isn't possible to perform I\/O from an arbitrary function, unless that function is itself in the 'IO' monad and called at some point, directly or indirectly, from @Main.main@. 'IO' is a monad, so 'IO' actions can be combined using either the do-notation or the '>>' and '>>=' operations from the 'Monad' class. -} newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #)) type role IO representational {- The above role annotation is redundant but is included because this role is significant in the normalisation of FFI types. Specifically, if this role were to become nominal (which would be very strange, indeed!), changes elsewhere in GHC would be necessary. See [FFI type roles] in TcForeign. -} {- Note [Kind-changing of (~) and Coercible] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (~) and Coercible are tricky to define. To the user, they must appear as constraints, but we cannot define them as such in Haskell. But we also cannot just define them only in GHC.Prim (like (->)), because we need a real module for them, e.g. to compile the constructor's info table. Furthermore the type of MkCoercible cannot be written in Haskell (no syntax for ~#R). So we define them as regular data types in GHC.Types, and do magic in TysWiredIn, inside GHC, to change the kind and type. -} -- | A data constructor used to box up all unlifted equalities -- -- The type constructor is special in that GHC pretends that it -- has kind (? -> ? -> Fact) rather than (* -> * -> *) data (~) a b = Eq# ((~#) a b) -- | This two-parameter class has instances for types @a@ and @b@ if -- the compiler can infer that they have the same representation. This class -- does not have regular instances; instead they are created on-the-fly during -- type-checking. Trying to manually declare an instance of @Coercible@ -- is an error. -- -- Nevertheless one can pretend that the following three kinds of instances -- exist. First, as a trivial base-case: -- -- @instance a a@ -- -- Furthermore, for every type constructor there is -- an instance that allows to coerce under the type constructor. For -- example, let @D@ be a prototypical type constructor (@data@ or -- @newtype@) with three type arguments, which have roles @nominal@, -- @representational@ resp. @phantom@. Then there is an instance of -- the form -- -- @instance Coercible b b\' => Coercible (D a b c) (D a b\' c\')@ -- -- Note that the @nominal@ type arguments are equal, the -- @representational@ type arguments can differ, but need to have a -- @Coercible@ instance themself, and the @phantom@ type arguments can be -- changed arbitrarily. -- -- The third kind of instance exists for every @newtype NT = MkNT T@ and -- comes in two variants, namely -- -- @instance Coercible a T => Coercible a NT@ -- -- @instance Coercible T b => Coercible NT b@ -- -- This instance is only usable if the constructor @MkNT@ is in scope. -- -- If, as a library author of a type constructor like @Set a@, you -- want to prevent a user of your module to write -- @coerce :: Set T -> Set NT@, -- you need to set the role of @Set@\'s type parameter to @nominal@, -- by writing -- -- @type role Set nominal@ -- -- For more details about this feature, please refer to -- <http://www.cis.upenn.edu/~eir/papers/2014/coercible/coercible.pdf Safe Coercions> -- by Joachim Breitner, Richard A. Eisenberg, Simon Peyton Jones and Stephanie Weirich. -- -- @since 4.7.0.0 data Coercible a b = MkCoercible ((~#) a b) -- It's really ~R# (representational equality), not ~#, -- but * we don't yet have syntax for ~R#, -- * the compiled code is the same either way -- * TysWiredIn has the truthful types -- Also see Note [Kind-changing of (~) and Coercible] -- | Alias for 'tagToEnum#'. Returns True if its parameter is 1# and False -- if it is 0#. {-# INLINE isTrue# #-} isTrue# :: Int# -> Bool -- See Note [Optimizing isTrue#] isTrue# x = tagToEnum# x -- Note [Optimizing isTrue#] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- Current definition of isTrue# is a temporary workaround. We would like to -- have functions isTrue# and isFalse# defined like this: -- -- isTrue# :: Int# -> Bool -- isTrue# 1# = True -- isTrue# _ = False -- -- isFalse# :: Int# -> Bool -- isFalse# 0# = True -- isFalse# _ = False -- -- These functions would allow us to safely check if a tag can represent True -- or False. Using isTrue# and isFalse# as defined above will not introduce -- additional case into the code. When we scrutinize return value of isTrue# -- or isFalse#, either explicitly in a case expression or implicitly in a guard, -- the result will always be a single case expression (given that optimizations -- are turned on). This results from case-of-case transformation. Consider this -- code (this is both valid Haskell and Core): -- -- case isTrue# (a ># b) of -- True -> e1 -- False -> e2 -- -- Inlining isTrue# gives: -- -- case (case (a ># b) of { 1# -> True; _ -> False } ) of -- True -> e1 -- False -> e2 -- -- Case-of-case transforms that to: -- -- case (a ># b) of -- 1# -> case True of -- True -> e1 -- False -> e2 -- _ -> case False of -- True -> e1 -- False -> e2 -- -- Which is then simplified by case-of-known-constructor: -- -- case (a ># b) of -- 1# -> e1 -- _ -> e2 -- -- While we get good Core here, the code generator will generate very bad Cmm -- if e1 or e2 do allocation. It will push heap checks into case alternatives -- which results in about 2.5% increase in code size. Until this is improved we -- just make isTrue# an alias to tagToEnum#. This is a temporary solution (if -- you're reading this in 2023 then things went wrong). See #8326. -- -- | 'SPEC' is used by GHC in the @SpecConstr@ pass in order to inform -- the compiler when to be particularly aggressive. In particular, it -- tells GHC to specialize regardless of size or the number of -- specializations. However, not all loops fall into this category. -- -- Libraries can specify this by using 'SPEC' data type to inform which -- loops should be aggressively specialized. data SPEC = SPEC | SPEC2
urbanslug/ghc
libraries/ghc-prim/GHC/Types.hs
bsd-3-clause
9,206
3
10
1,933
464
344
120
-1
-1
foldM_ f a xs = foldM f a xs >> return ()
mpickering/hlint-refactor
tests/examples/Monad17.hs
bsd-3-clause
41
0
7
11
31
13
18
1
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hr-HR"> <title>Front-End Scanner | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/frontendscanner/src/main/javahelp/org/zaproxy/zap/extension/frontendscanner/resources/help_hr_HR/helpset_hr_HR.hs
apache-2.0
978
88
29
159
402
214
188
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Magic -- Copyright : (c) The University of Glasgow 2009 -- License : see libraries/ghc-prim/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- GHC magic. -- -- Use GHC.Exts from the base package instead of importing this -- module directly. -- ----------------------------------------------------------------------------- module GHC.Magic ( inline, noinline, lazy, oneShot, runRW# ) where import GHC.Prim import GHC.CString () import GHC.Types (RuntimeRep, TYPE) -- | The call @inline f@ arranges that 'f' is inlined, regardless of -- its size. More precisely, the call @inline f@ rewrites to the -- right-hand side of @f@'s definition. This allows the programmer to -- control inlining from a particular call site rather than the -- definition site of the function (c.f. 'INLINE' pragmas). -- -- This inlining occurs regardless of the argument to the call or the -- size of @f@'s definition; it is unconditional. The main caveat is -- that @f@'s definition must be visible to the compiler; it is -- therefore recommended to mark the function with an 'INLINABLE' -- pragma at its definition so that GHC guarantees to record its -- unfolding regardless of size. -- -- If no inlining takes place, the 'inline' function expands to the -- identity function in Phase zero, so its use imposes no overhead. {-# NOINLINE[0] inline #-} inline :: a -> a inline x = x -- | The call @noinline f@ arranges that 'f' will not be inlined. -- It is removed during CorePrep so that its use imposes no overhead -- (besides the fact that it blocks inlining.) {-# NOINLINE noinline #-} noinline :: a -> a noinline x = x -- | The 'lazy' function restrains strictness analysis a little. The -- call @lazy e@ means the same as 'e', but 'lazy' has a magical -- property so far as strictness analysis is concerned: it is lazy in -- its first argument, even though its semantics is strict. After -- strictness analysis has run, calls to 'lazy' are inlined to be the -- identity function. -- -- This behaviour is occasionally useful when controlling evaluation -- order. Notably, 'lazy' is used in the library definition of -- 'Control.Parallel.par': -- -- > par :: a -> b -> b -- > par x y = case (par# x) of _ -> lazy y -- -- If 'lazy' were not lazy, 'par' would look strict in 'y' which -- would defeat the whole purpose of 'par'. -- -- Like 'seq', the argument of 'lazy' can have an unboxed type. lazy :: a -> a lazy x = x -- Implementation note: its strictness and unfolding are over-ridden -- by the definition in MkId.hs; in both cases to nothing at all. -- That way, 'lazy' does not get inlined, and the strictness analyser -- sees it as lazy. Then the worker/wrapper phase inlines it. -- Result: happiness -- | The 'oneShot' function can be used to give a hint to the compiler that its -- argument will be called at most once, which may (or may not) enable certain -- optimizations. It can be useful to improve the performance of code in continuation -- passing style. -- -- If 'oneShot' is used wrongly, then it may be that computations whose result -- that would otherwise be shared are re-evaluated every time they are used. Otherwise, -- the use of `oneShot` is safe. -- -- 'oneShot' is representation polymorphic: the type variables may refer to lifted -- or unlifted types. oneShot :: forall (q :: RuntimeRep) (r :: RuntimeRep) (a :: TYPE q) (b :: TYPE r). (a -> b) -> a -> b oneShot f = f -- Implementation note: This is wired in in MkId.hs, so the code here is -- mostly there to have a place for the documentation. -- | Apply a function to a 'State# RealWorld' token. When manually applying -- a function to `realWorld#`, it is necessary to use `NOINLINE` to prevent -- semantically undesirable floating. `runRW#` is inlined, but only very late -- in compilation after all floating is complete. -- 'runRW#' is representation polymorphic: the result may have a lifted or -- unlifted type. runRW# :: forall (r :: RuntimeRep) (o :: TYPE r). (State# RealWorld -> o) -> o -- See Note [runRW magic] in MkId #if !defined(__HADDOCK_VERSION__) runRW# m = m realWorld# #else runRW# = runRW# -- The realWorld# is too much for haddock #endif {-# NOINLINE runRW# #-} -- This is inlined manually in CorePrep
ezyang/ghc
libraries/ghc-prim/GHC/Magic.hs
bsd-3-clause
4,637
0
9
855
308
216
92
-1
-1
module UnitTests.Distribution.Client.Dependency.Modular.PSQ ( tests ) where import Distribution.Client.Dependency.Modular.PSQ import Test.Framework as TF (Test) import Test.Framework.Providers.QuickCheck2 tests :: [TF.Test] tests = [ testProperty "splitsAltImplementation" splitsTest ] -- | Original splits implementation splits' :: PSQ k a -> PSQ k (a, PSQ k a) splits' xs = casePSQ xs (PSQ []) (\ k v ys -> cons k (v, ys) (fmap (\ (w, zs) -> (w, cons k v zs)) (splits' ys))) splitsTest :: [(Int, Int)] -> Bool splitsTest psq = splits' (PSQ psq) == splits (PSQ psq)
DavidAlphaFox/ghc
libraries/Cabal/cabal-install/tests/UnitTests/Distribution/Client/Dependency/Modular/PSQ.hs
bsd-3-clause
594
0
14
113
233
132
101
14
1
{-# LANGUAGE TypeSynonymInstances, MultiParamTypeClasses, DeriveDataTypeable #-} {-# LANGUAGE PatternGuards, FlexibleContexts, FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.BoringWindows -- Copyright : (c) 2008 David Roundy <droundy@darcs.net> -- License : BSD3-style (see LICENSE) -- -- Maintainer : Adam Vogt <vogt.adam@gmail.com> -- Stability : unstable -- Portability : unportable -- -- BoringWindows is an extension to allow windows to be marked boring -- ----------------------------------------------------------------------------- module XMonad.Layout.BoringWindows ( -- * Usage -- $usage boringWindows, boringAuto, markBoring, clearBoring, focusUp, focusDown, focusMaster, UpdateBoring(UpdateBoring), BoringMessage(Replace,Merge), BoringWindows() -- * Tips -- ** variant of 'Full' -- $simplest ) where import XMonad.Layout.LayoutModifier(ModifiedLayout(..), LayoutModifier(handleMessOrMaybeModifyIt, redoLayout)) import XMonad(Typeable, LayoutClass, Message, X, fromMessage, sendMessage, windows, withFocused, Window) import Control.Applicative((<$>)) import Data.List((\\), union) import Data.Maybe(fromMaybe, listToMaybe, maybeToList) import qualified Data.Map as M import qualified XMonad.StackSet as W -- $usage -- You can use this module with the following in your -- @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.BoringWindows -- -- Then edit your @layoutHook@ by adding the layout modifier: -- -- > myLayout = boringWindows (Full ||| etc..) -- > main = xmonad def { layoutHook = myLayout } -- -- Then to your keybindings, add: -- -- > , ((modm, xK_j), focusUp) -- > , ((modm, xK_k), focusDown) -- > , ((modm, xK_m), focusMaster) -- -- For more detailed instructions on editing the layoutHook see: -- -- "XMonad.Doc.Extending#Editing_the_layout_hook" data BoringMessage = FocusUp | FocusDown | FocusMaster | IsBoring Window | ClearBoring | Replace String [Window] | Merge String [Window] deriving ( Read, Show, Typeable ) instance Message BoringMessage -- | UpdateBoring is sent before attempting to view another boring window, so -- that layouts have a chance to mark boring windows. data UpdateBoring = UpdateBoring deriving (Typeable) instance Message UpdateBoring markBoring, clearBoring, focusUp, focusDown, focusMaster :: X () markBoring = withFocused (sendMessage . IsBoring) clearBoring = sendMessage ClearBoring focusUp = sendMessage UpdateBoring >> sendMessage FocusUp focusDown = sendMessage UpdateBoring >> sendMessage FocusDown focusMaster = sendMessage UpdateBoring >> sendMessage FocusMaster data BoringWindows a = BoringWindows { namedBoring :: M.Map String [a] -- ^ store borings with a specific source , chosenBoring :: [a] -- ^ user-chosen borings , hiddenBoring :: Maybe [a] -- ^ maybe mark hidden windows } deriving (Show,Read,Typeable) boringWindows :: (LayoutClass l a, Eq a) => l a -> ModifiedLayout BoringWindows l a boringWindows = ModifiedLayout (BoringWindows M.empty [] Nothing) -- | Mark windows that are not given rectangles as boring boringAuto :: (LayoutClass l a, Eq a) => l a -> ModifiedLayout BoringWindows l a boringAuto = ModifiedLayout (BoringWindows M.empty [] (Just [])) instance LayoutModifier BoringWindows Window where redoLayout (b@BoringWindows { hiddenBoring = bs }) _r mst arrs = do let bs' = W.integrate' mst \\ map fst arrs return (arrs, Just $ b { hiddenBoring = const bs' <$> bs } ) handleMessOrMaybeModifyIt bst@(BoringWindows nbs cbs lbs) m | Just (Replace k ws) <- fromMessage m , maybe True (ws/=) (M.lookup k nbs) = let nnb = if null ws then M.delete k nbs else M.insert k ws nbs in rjl bst { namedBoring = nnb } | Just (Merge k ws) <- fromMessage m , maybe True (not . null . (ws \\)) (M.lookup k nbs) = rjl bst { namedBoring = M.insertWith union k ws nbs } | Just (IsBoring w) <- fromMessage m , w `notElem` cbs = rjl bst { chosenBoring = w:cbs } | Just ClearBoring <- fromMessage m, not (null cbs) = rjl bst { namedBoring = M.empty, chosenBoring = []} | Just FocusUp <- fromMessage m = do windows $ W.modify' $ skipBoring W.focusUp' return Nothing | Just FocusDown <- fromMessage m = do windows $ W.modify' $ skipBoring W.focusDown' return Nothing | Just FocusMaster <- fromMessage m = do windows $ W.modify' $ skipBoring W.focusDown' -- wiggle focus to make sure . skipBoring W.focusUp' -- no boring window gets the focus . focusMaster' return Nothing where skipBoring f st = fromMaybe st $ listToMaybe $ filter ((`notElem` W.focus st:bs) . W.focus) $ take (length $ W.integrate st) $ iterate f st bs = concat $ cbs:maybeToList lbs ++ M.elems nbs rjl = return . Just . Left handleMessOrMaybeModifyIt _ _ = return Nothing -- | Variant of 'focusMaster' that works on a -- 'Stack' rather than an entire 'StackSet'. focusMaster' :: W.Stack a -> W.Stack a focusMaster' c@(W.Stack _ [] _) = c focusMaster' (W.Stack t ls rs) = W.Stack x [] (xs ++ t : rs) where (x:xs) = reverse ls {- $simplest An alternative to 'Full' is "XMonad.Layout.Simplest". Less windows are ignored by 'focusUp' and 'focusDown'. This may be helpful when you want windows to be uninteresting by some other layout modifier (ex. "XMonad.Layout.Minimize") -}
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Layout/BoringWindows.hs
bsd-2-clause
6,431
0
17
2,008
1,351
731
620
87
1
module T5884Other where data Pair a = Pair a a
urbanslug/ghc
testsuite/tests/generics/T5884Other.hs
bsd-3-clause
48
0
6
11
16
10
6
2
0
{-# LANGUAGE DataKinds #-} module Main where import Control.Lens import Data.Monoid import System.Environment import System.IO import qualified Text.PrettyPrint.ANSI.Leijen as Ppr import qualified Text.Trifecta as P import Formura.Interpreter.Eval import qualified Formura.Parser as P import Formura.Syntax main :: IO () main = do argv <- getArgs mapM_ process argv process :: FilePath -> IO () process fn = do mprog <- P.parseFromFileEx (P.runP $ P.program <* P.eof) fn case mprog of P.Failure doc -> Ppr.displayIO stdout $ Ppr.renderPretty 0.8 80 $ doc <> Ppr.linebreak P.Success prog -> do let BindingF stmts = prog ^. programBinding mapM_ evalStmt stmts evalStmt :: StatementF RExpr -> IO () evalStmt (TypeDecl _ _) = return () evalStmt (Subst l r) = do putStrLn $ show l ++ " = " ++ show r rv <- runIM $ eval r case rv of Left doc -> Ppr.displayIO stdout $ Ppr.renderPretty 0.8 80 $ doc <> Ppr.linebreak Right vt -> print vt putStrLn ""
nushio3/formura
exe-src/formura-eval.hs
mit
1,059
0
15
273
374
185
189
32
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.StringCallback (newStringCallback, newStringCallbackSync, newStringCallbackAsync, StringCallback) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/StringCallback Mozilla StringCallback documentation> newStringCallback :: (MonadIO m, FromJSString data') => (data' -> IO ()) -> m (StringCallback data') newStringCallback callback = liftIO (syncCallback1 ThrowWouldBlock (\ data' -> fromJSRefUnchecked data' >>= \ data'' -> callback data'')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StringCallback Mozilla StringCallback documentation> newStringCallbackSync :: (MonadIO m, FromJSString data') => (data' -> IO ()) -> m (StringCallback data') newStringCallbackSync callback = liftIO (syncCallback1 ContinueAsync (\ data' -> fromJSRefUnchecked data' >>= \ data'' -> callback data'')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StringCallback Mozilla StringCallback documentation> newStringCallbackAsync :: (MonadIO m, FromJSString data') => (data' -> IO ()) -> m (StringCallback data') newStringCallbackAsync callback = liftIO (asyncCallback1 (\ data' -> fromJSRefUnchecked data' >>= \ data'' -> callback data''))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/StringCallback.hs
mit
2,240
0
12
441
548
325
223
42
1
module Jaml.Parser.Tag ( tag ) where import Text.ParserCombinators.Parsec import Control.Monad (liftM) import Data.List (partition) import Jaml.Types import Jaml.Parser.Util (optSpaces, identifier) import Jaml.Parser.Attribute (cssSelector, attrs) tag :: Parser Node tag = do n <- try name <|> return "div" ss <- many cssSelector <|> return [] as <- attrs <|> return [] gs <- gators c <- if isSelfClosing n then return SelfClosing else content optSpaces return (Tag n (unifyClassSelectors $ ss ++ as) gs c) unifyClassSelectors :: [Attr] -> [Attr] unifyClassSelectors selectors = (combine classes) : others where (classes, others) = partition isClass selectors combine cs = Attr ("class", concat $ map vals cs) vals (Attr (_, vs)) = vs isClass (Attr ("class", _)) = True isClass _ = False isSelfClosing :: String -> Bool isSelfClosing n = n `elem` selfClosingTagNames selfClosingTagNames :: [String] = ["meta", "img", "link", "script", "br", "hr"] -- First InGator, then OutGator. (Or NoGator in either spot.) gators :: Parser (Gator,Gator) gators = do a <- outGator <|> inGator <|> return NoGator b <- case a of NoGator -> return NoGator OutGator -> inGator <|> return NoGator InGator -> outGator <|> return NoGator return $ case a of InGator -> (b,a) _ -> (a,b) where outGator = char '>' >> return OutGator inGator = char '<' >> return InGator content :: Parser TagContent content = selfClose <|> try noisyCode <|> try plainText <|> return EmptyContent selfClose :: Parser TagContent selfClose = do char '/' -- there shouldn't be anything else here until Eol return SelfClosing noisyCode :: Parser TagContent noisyCode = do optSpaces >> char '=' >> optSpaces liftM NoisyCode beforeEol plainText :: Parser TagContent plainText = do optSpaces liftM content beforeEol where content "" = EmptyContent content s = PlainText s name :: Parser String name = char '%' >> identifier beforeEol :: Parser String beforeEol = many1 (noneOf "\n")
marklar/jaml
Jaml/Parser/Tag.hs
mit
2,201
0
12
573
709
362
347
-1
-1
module Mycont_01 where import Control.Monad.Cont fact :: Int -> Cont r Int -- Your own code: -- Cont ($ (fact 0)) = return 1 fact 0 = return 1 -- Cont ($ (fact n)) = Cont ($ (fact (n-1))) >>= (\x -> Cont ($ (n*x))) fact n = fact (n-1) >>= \x -> return (n*x) -- the "real" factorial function, without monads factorial :: Int -> Int factorial n = runCont (fact n) id
Muzietto/transformerz
haskell/cont/mycont.hs
mit
390
0
9
99
104
56
48
7
1
module Redirect where import Network.HTTP.Types import Network.Wai import Servant.Server.Internal import Servant.API import Servant.Server import Protolude -- TODO: use responseServantErr data IndexRedirect instance HasServer IndexRedirect config where type ServerT IndexRedirect m = m () route Proxy _ action = leafRouter route' where route_uri () = Route $ responseLBS seeOther303 [(hLocation, "/" )] "" route' env req resp = runAction action env req resp route_uri
mreider/kinda-might-work
src/Redirect.hs
mit
660
0
11
255
134
73
61
-1
-1
module Budget.Debt where import Budget (Person,BudgetRecord,Budget,brOwners,brPurchaser,brAmount) import Data.List (nub) data DebtRecord = DebtRecord { drCreditor :: Person , drDebtor :: Person , drAmount :: Double } deriving (Show,Eq) type Debt = [DebtRecord] -- | Analyze debt from budget report debt :: Budget -> Debt debt = debt' [] -- | Accumulator version of debt debt' :: Debt -> Budget -> Debt debt' d [] = d debt' d (x:xs) | length o == 1 && (head o) == p = debt' d xs --No debt here | otherwise = debt' d' xs where o = brOwners x ol = fromIntegral (length o) p = brPurchaser x a = brAmount x o' = filter (/= p) o -- Debtors d' = d ++ [ DebtRecord p dtor (a / ol) | dtor <- o' ] -- | Sum records of debt with same creditor/debtor into single record compress :: Debt -> Debt compress dl = [ DebtRecord c d (sum' c d) | c <- creds, d <- dbts, c /= d ] where creds = nub [ drCreditor x | x <- dl ] dbts = nub [ drDebtor x | x <- dl ] sum' c d = Budget.Debt.sum [ dr | dr <- dl, c == drCreditor dr, d == drDebtor dr ] -- | Sum debt records sum :: Debt -> Double sum d = foldr ((+).drAmount) 0.0 d -- | Extract debts with specific debtor creditors :: Person -> Debt -> Debt creditors p d = [ x | x <- d, p == drDebtor x ] -- | Extract debts with specific creditor debtors :: Person -> Debt -> Debt debtors p d = [ x | x <- d, p == drCreditor x ] -- | Extract all people involved in debts people :: Debt -> [Person] people dl = nub (creds ++ dbts) where creds = nub [ drCreditor x | x <- dl ] dbts = nub [ drDebtor x | x <- dl ] -- | Sum amount owed by one person to another owed :: Person -> Person -> Debt -> DebtRecord owed d c dbt = foldl f (DebtRecord c d 0) dbt where f t (DebtRecord c' d' a) | c == c' && d == d' = t { drAmount = tot + a } | c == d' && d == c' = t { drAmount = tot - a } --Inverse | otherwise = t where tot = drAmount t
pmlt/budget
src/Budget/Debt.hs
mit
1,951
0
12
519
793
417
376
44
1
module LuciansLusciousLasagna (elapsedTimeInMinutes, expectedMinutesInOven, preparationTimeInMinutes) where -- TODO: define the expectedMinutesInOven constant -- TODO: define the preparationTimeInMinutes function -- TODO: define the elapsedTimeInMinutes function
exercism/xhaskell
exercises/concept/lucians-luscious-lasagna/src/LuciansLusciousLasagna.hs
mit
266
0
4
27
18
13
5
1
0
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Data.List.NonEmpty.Compat" -- from a globally unique namespace. module Data.List.NonEmpty.Compat.Repl ( module Data.List.NonEmpty.Compat ) where import "this" Data.List.NonEmpty.Compat
haskell-compat/base-compat
base-compat/src/Data/List/NonEmpty/Compat/Repl.hs
mit
304
0
5
31
31
24
7
5
0
{-# LANGUAGE DataKinds, FlexibleContexts, FlexibleInstances, GADTs, MultiParamTypeClasses, ScopedTypeVariables, TypeFamilies, TypeOperators, UndecidableInstances #-} module Data.Nested.List (module Data.Nested.List, module Data.Nested.Functor) where import qualified Data.Function as F import qualified Data.List as L import Data.Nested.Naturals import Data.Nested.Functor type NList = MkNested [] sortByKey' :: (Ord b) => (a -> b) -> [a] -> [a] sortByKey' key = L.sortBy (compare `F.on` key) groupByKey' :: (Ord b) => (a -> b) -> [a] -> [[a]] groupByKey' key = L.groupBy ((==) `F.on` key) sortAndGroupByKey' :: (Ord b) => (a -> b) -> [a] -> [[a]] sortAndGroupByKey' key = groupByKey' key . sortByKey' key select = nlift :: (a -> b) -> NList Zero a -> NList Zero b produce = nlift :: (a -> [b]) -> NList Zero a -> NList (Succ Zero) b reduce = nlift :: ([a] -> b) -> NList (Succ Zero) a -> NList Zero b select' = nlift :: ([a] -> [b]) -> NList (Succ Zero) a -> NList (Succ Zero) b produce' = nlift :: ([a] -> [[b]]) -> NList (Succ Zero) a -> NList (Succ (Succ Zero)) b reduce' = nlift :: ([[a]] -> [b]) -> NList (Succ (Succ Zero)) a -> NList (Succ Zero) b filterBy :: (a -> Bool) -> NList (Succ Zero) a -> NList (Succ Zero) a filterBy f = select' (filter f) orderBy :: (Ord b) => (a -> b) -> NList (Succ Zero) a -> NList (Succ Zero) a orderBy f = select' (sortByKey' f) groupBy :: (Ord b) => (a -> b) -> NList (Succ Zero) a -> NList (Succ (Succ Zero)) a groupBy f = produce' (sortAndGroupByKey' f) ungroup = reduce' (foldl (++) [])
filonik/nfunctors
src/Data/Nested/List.hs
mit
1,546
0
12
287
751
406
345
26
1
import Data.Ord import Data.List type Name = String type Size = Int type Item = (Name,Size) type Bin = (Name,Size,[Item]) -- CONTRACT --pack :: [Item] -> [Bin] -> [Bin] -- PURPOSE -- Given a set of empty bins with fixed sizes and a set of items, return (one of the) -- optimal solution(s) where the least space is wasted in used bins. -- The basic idea is that at each level of recursion we filter out alternatives with -- the same total waste and keep only the best waste at each recursion branch. -- We also always take the biggest remaining item and only recurse through options where it fits -- TO DO: -- * optimal algorithm: http://aaaipress.org/Papers/AAAI/2002/AAAI02-110.pdf -- Korf assumes a uniform bin size in his bin-completion algorithm though. -- The general idea is similar to Best-Fit-Decreasing (BFD). But instead of always -- taking the biggest remaining item, for each recursion step it is evaluated which -- so called "feasible set" of remaining items (and if I understood correctly, this includes -- all the items which are alone in some bin) "dominates" the other feasible sets and then adding -- each undominated set to this bin in a separate recursion branch. A feasible set of items can be -- placed in the bin worked on. Set A dominates set B if all items from B can be placed into bins from A -- (implying to use items from A as bins). This means each creation of undominated sets is another -- bin-packing problem and is solved recursively by Korf. -- It seems that this step uses most of the total time of the algorithm and might be somewhat -- improved by better implementation. -- Each recursion branch is checked against a lower bound on numbers of bins used and discarded if appropriate. -- I'm not sure how to convert this figure to varying bin sizes and the lower bound of wasted space. -- As an optimization, the first run is BFD and the bin-completion algorithm is then fed with its -- results to reduce the search space and discard branches early on. -- * display results more prettily -- EXAMPLES -- pack [("TooBigItem",100)] [("TooSmallBin",50,[])] : [] -- pack [("Item1",50),("Item2",50)] [("Bin",100,[])] : [("Bin",0,[("Item1",50),("Item2",50)])] -- DEFINITION -- filter redundancy before and after recursing, but only by waste pack [] bins = bins -- assume items are sorted descending pack (i:is) bins = head $ nubBy compareWaste $ sortBy (comparing meanWaste) $ map (pack is) unique where -- produce a list of alternatives where the biggest remaining item fits in -- somewhere at the end of this line should be the place to find dominant feasible sets to branch on permutations = [ addItem i b : filter (/= b) bins | b <- bins, spaceOf b >= sizeOf i] -- filter variants with same waste unique = nubBy compareWaste permutations -- compare two alternatives by total waaste compareWaste x y = totalWaste x == totalWaste y-- && meanWaste x == meanWaste y -- HELPER FUNCTIONS -- get size of item sizeOf :: Item -> Size sizeOf = snd -- get free space of bin spaceOf :: Bin -> Size spaceOf (_,space,_) = space -- get name of bin nameOf :: Bin -> Name nameOf (name,_,_) = name -- get items from bin contentOf :: Bin -> [Item] contentOf (_,_,items) = items -- sum of bins' free space sumBinSpace bins = sum [spaceOf a | a <- bins] -- sum of items' sizes sumItemSize items = sum [sizeOf a | a <- items] -- sort bins by free space sortBins bins = sortBy (comparing spaceOf) bins -- sort items by size descending, then name ascending -- assumes unique item names sortItems items = sortBy compareItems items where compareItems (a1, b1) (a2, b2) | b1 < b2 = GT | b1 > b2 = LT | b1 == b2 = compare a1 a2 -- add item to bin addItem item (name,space,items) = (name,space - (sizeOf item),item:items) -- find out total waste totalWaste bins = sumBinSpace $ filter (not.null.contentOf) bins -- calculate mean waste of a set of bins meanWaste bins = sum wastes-- / (fromIntegral $ length wastes) where wastes = map (sqrt.fromIntegral.spaceOf) $ filter (not.null.contentOf) bins {- -- Check if given system could be solvable solvable :: [Item] -> [Bin] -> Either Bool Size -- Return `False` when definitely not solvable, otherwise returns sum of all bin sizes solvable items bins | sumItemSize items > sumBinSpace bins || sizeOf (last (sortItems items)) > spaceOf(last (sortBins bins)) = Left False | otherwise = Right (sumBinSpace bins) -} -- SHOW FUNCTIONS itemToString :: Item -> Name itemToString (name,size) = name ++ " (" ++ show size ++ ")" itemListToString :: [Item] -> Name itemListToString (i:is) = itemToString i ++ next where next | null is = "" | otherwise = " | " ++ itemListToString is binToString :: Bin -> Name binToString bin@(name,size,items) = name ++ " " ++ show (spaceOf bin) ++ "/" ++ show (spaceOf bin + sumItemSize items) ++ itemString ++ "\n" where itemString | null items = "" | otherwise = "\n " ++ itemListToString items binListToString :: [Bin] -> Name binListToString (b:bs) = binToString b ++ next where next | null bs = "\n" | otherwise = "\n" ++ binListToString bs alternativesToString :: [[Bin]] -> Name alternativesToString (bs:bss) = binListToString bs ++ next where next | null bss = "\n" | otherwise = "----\n\n" ++ alternativesToString bss -- TEST DATA bin = sortBins [ ("A",30,[]), ("C",15,[]), ("D",100,[]), ("B",110,[])] :: [Bin] item = sortItems [ ("x",5), ("y",6), ("z",1), ("a",2), ("b",3), ("k",4), ("l",7), ("j",8)] :: [Item] main = do let res = pack item bin putStrLn $ show res putStr "\n" putStrLn $ "Total Waste: " ++ (show $ totalWaste res)
frickler01/pack
pack.hs
mit
5,704
26
12
1,148
1,190
652
538
78
1
module TetrisAttack.Board.Types where -------------------------------------------------------------------------------- import TetrisAttack.Tile import TetrisAttack.Grid -------------------------------------------------------------------------------- type Board a = Grid2D (TileLogic a) type BoardState = Grid2D Tile boardState2Board :: TileMap -> BoardState -> Board a boardState2Board m = mapGrid convertTile where convertTile :: Tile -> TileLogic a convertTile (Stationary c) = stationary m c convertTile _ = blank
Mokosha/HsTetrisAttack
TetrisAttack/Board/Types.hs
mit
534
0
9
69
112
60
52
10
2
import System.MIDI import System.IO import System.Process import Control.Monad import Control.Concurrent import Safe comment :: String -> IO () comment s = hPutStrLn stderr ( "# " ++ s ) main :: IO () main = do hSetBuffering stdout LineBuffering sources <- enumerateSources names <- mapM getName sources comment "What source do you want?" mapM_ (comment . \(a,b) -> show a ++ " - " ++ b) (zip [1 :: Int ..] names) choiceID <- readMay `fmap` getLine :: IO (Maybe Int) run choiceID $ do cid <- choiceID lookup cid (zip [1..] sources) run :: Maybe Int -> Maybe Source -> IO () run (Just choiceID) (Just choice) = print choiceID >> setup choice run _ _ = comment "Invalid Option" >> main setup :: Source -> IO () setup choice = do buttonIDs <- newChan buttonStrings <- mapMChan createButton buttonIDs keys <- newChan events <- mergeChans buttonStrings keys conn <- openSource choice (Just (maybeWriteChan buttonIDs . getID)) start conn comment "Processing Events" void $ forkIO $ do getContents >>= writeList2Chan keys . map Keyboard . lines writeChan keys (Keyboard "exit") updateCommands events stop conn getID :: MidiEvent -> Maybe Int getID (MidiEvent _ (MidiMessage _ (NoteOn x _))) = Just x getID _ = Nothing maybeWriteChan :: Chan a -> Maybe a -> IO () maybeWriteChan c (Just e) = writeChan c e maybeWriteChan _ Nothing = return () createButton :: Show a => a -> IO Event createButton b = do comment $ show b return (Button (show b)) mapMChan :: (x -> IO y) -> Chan x -> IO (Chan y) mapMChan f c1 = do c2 <- dupChan c1 c3 <- newChan void $ forkIO $ getChanContents c2 >>= mapM_ (writeChan c3 <=< f) return c3 mergeChans :: Chan a -> Chan a -> IO (Chan a) mergeChans a b = do a' <- dupChan a b' <- dupChan b c <- newChan void $ forkIO $ getChanContents a' >>= writeList2Chan c void $ forkIO $ getChanContents b' >>= writeList2Chan c return c respondCommand :: Command -> IO () -- respondCommand (Run s ) = void $ forkIO $ callCommand s respondCommand (Run s ) = void $ forkIO $ void $ createProcess ((shell s) { delegate_ctlc = True , std_out = UseHandle stderr }) respondCommand (Log a b) = putStrLn a >> putStrLn b updateCommands :: Chan Event -> IO () updateCommands events = getChanContents events >>= mapM_ respondCommand . behave [] . filter (not . isComment) . filter (/= Keyboard "") . takeWhile (/= Keyboard "exit") isComment :: Event -> Bool isComment (Keyboard x) = and $ zipWith (==) x "#" isComment _ = False -- Event definition and processing data Event = Keyboard String | Button String deriving (Eq, Show) data Command = Run String | Log String String deriving (Eq, Show) behave :: [(String,String)] -> [Event] -> [Command] behave l (Button b1 : xs) | Just c <- lookup b1 l = Run c : behave l (Keyboard b1 : xs) behave l (Button b1 : Keyboard k1 : xs) = Log b1 k1 : behave ((b1,k1):l) xs behave l (Keyboard __ : Button b1 : xs) = behave l (Button b1 : xs) behave l (Button __ : Button b2 : xs) = behave l (Button b2 : xs) behave l (Keyboard k1 : Keyboard k2 : xs) = Log k1 k2 : behave ((k1,k2):l) xs behave _ _ = []
sordina/ScriptMidi
src/scriptMidi.hs
mit
3,700
0
13
1,236
1,408
675
733
83
1
module HunitTest (module HunitTest) where import Test.HUnit import HspInterpreter import Phonemizer import Soundgluer htest :: IO () htest = do phones1 <- (phonemize "pol" "przewięźlikowski") phones2 <- (phonemize "pol" "Litwo, ojczyzno moja, ty jesteś jak zdrowie") phones3 <- (phonemize "pol" "Jeżu klątw, spuść Finom część gry hańb!") let res1 = [["p","rz","e","w","i","en","zi","l","i","k","o","w","s","k","i"]] let res2 = [["l","i","t","w","o","-"],["o","j","cz","y","z","n","o"],["m","o","j","a","-"],["t","y"],["j","e","s","t","e","si"],["j","a","k"],["z","d","r","o","w","j","e"]] let res3 = [["j","e","rz","u"],["k","l","on","t","w","-"],["s","p","u","si","ci"],["f","i","n","o","m"],["cz","en","si","ci"],["g","r","y"],["h","a","ni","b","-"]] runTestTT $ TestList [ -- Phonemizer.phonemize assertEqual' "przewięźlikowski" res1 phones1, assertEqual' "Litwo, ojczyzno..." res2 phones2, assertEqual' "Jeżu klątw, spuść Finom część gry hańb!" res3 phones3, -- HspInterpreter.strToLangRule assertEqual' "a -> a" (MkLangRule "a" ["a"]) (strToLangRule "a -> a"), assertEqual' "żółćęśąźń -> rz,u,ll,ci,en,si,on,zi,ni" (MkLangRule "żółćęśąźń" ["rz","u","ll","ci","en","si","on","zi","ni"]) (strToLangRule "żółćęśąźń -> rz,u,ll,ci,en,si,on,zi,ni"), -- HspInterpreter.despace assertEqual' "" "" (despace ""), assertEqual' " " "" (despace " "), assertEqual' " " "" (despace " "), assertEqual' "qwerty" "qwerty" (despace "qwerty"), assertEqual' " qwerty" "qwerty" (despace " qwerty"), assertEqual' "qwerty " "qwerty" (despace "qwerty "), assertEqual' " with Out Spaces " "withOutSpaces" (despace " with Out Spaces "), -- Soundgluer.isWave assertBool' ".wav" (isWave ".wav"), assertBool' "wav." (not $ isWave "wav."), assertBool' "" (not $ isWave ""), assertBool' "wav" (not $ isWave "wav"), -- Soundgluer.phoneName assertEqual' ".wav" "" (phoneName ".wav"), assertEqual' "a.wav" "a" (phoneName "a.wav"), assertEqual' "" "" (phoneName ""), assertEqual' "asdf.wav" "asdf" (phoneName "asdf.wav"), assertEqual' "żółćęśąźń.wav" "żółćęśąźń" (phoneName "żółćęśąźń.wav"), -- Soundgluer.getLangPath assertEqual' "pol" (langsDirectory ++ pathSeparator ++ "pol") (getLangPath "pol") ] putStrLn "Test suite not yet implemented" assertEqual' :: (Eq a, Show a) => String -> a -> a -> Test assertEqual' msg x y = TestCase $ assertEqual msg x y assertBool' :: String -> Bool -> Test assertBool' msg b = TestCase $ assertBool msg b
mprzewie/haspell
test/HunitTest.hs
mit
3,006
0
13
790
909
512
397
41
1
{-# LANGUAGE CPP, OverloadedStrings, BangPatterns #-} #define COLON 58 #define SPACE 32 #define TAB 9 #define A_UPPER 65 #define A_LOWER 97 #define Z_UPPER 90 #define Z_LOWER 122 #define ZERO 48 #define NINE 57 #define PERIOD 46 #define UNDERSCORE 95 module Data.Array.Repa.Distributed.Config where import Data.Attoparsec.ByteString as A import qualified Data.ByteString as B import qualified Data.Map as M import Data.Word (Word8) import Control.Applicative data Id = Id !B.ByteString !B.ByteString !Int deriving (Eq, Show, Ord) data Node = Node !Id deriving (Eq, Show) data NodeRegistry = NodeRegistry { registry :: M.Map Id Node } deriving (Show) parseConfig :: String -> IO (Either String NodeRegistry) parseConfig conf = do bytes <- B.readFile conf return $ A.parseOnly config bytes config :: Parser NodeRegistry config = do n @ (Node id) <- configLine return $ NodeRegistry $ M.fromList [(id, n)] eatHSpace :: Parser () eatHSpace = skipMany wspace where wspace = satisfy $ \c -> c == SPACE || c == TAB configLine :: Parser Node configLine = do name <- nodeName <* eatHSpace string "=>" <* eatHSpace ip' <- (hostname <|> ip) <* colon p <- port return $ Node (Id name ip' p) {-# INLINE colon #-} colon = A.word8 COLON letter_ascii :: Parser Word8 letter_ascii = satisfy $ \w -> (w >= A_LOWER && w <= Z_LOWER) || (w >= A_UPPER && w <= Z_UPPER) digit :: Parser Word8 digit = satisfy $ \w -> w >= ZERO && w <= NINE nodeName :: Parser B.ByteString nodeName = B.pack <$> many1 (letter_ascii <|> digit <|> A.word8 UNDERSCORE) hostname :: Parser B.ByteString hostname = B.pack <$> many (letter_ascii <|> digit <|> A.word8 PERIOD) ip :: Parser B.ByteString ip = takeWhile1 ipChar where ipChar w = (w >= ZERO && w <= NINE) || w == PERIOD port :: Parser Int port = return 10
jroesch/dda
src/Data/Array/Repa/Distributed/Config.hs
mit
1,867
1
12
398
628
332
296
54
1
module SModel (module SModel, module SModel.Nucleotides, module SModel.Doublets, module SModel.Codons, module SModel.ReversibleMarkov, module SModel.Likelihood, frequencies_from_dict) where import Probability import Bio.Alphabet import Bio.Sequence import Tree import Parameters import SModel.Nucleotides import SModel.Doublets import SModel.Codons import SModel.ReversibleMarkov import SModel.Likelihood import Data.Matrix builtin builtin_average_frequency 1 "average_frequency" "SModel" builtin builtin_empirical 2 "empirical" "SModel" builtin pam 1 "pam" "SModel" builtin jtt 1 "jtt" "SModel" builtin wag 1 "wag" "SModel" builtin builtin_wag_frequencies 1 "wag_frequencies" "SModel" builtin builtin_lg_frequencies 1 "lg_frequencies" "SModel" builtin lg 1 "lg" "SModel" builtin builtin_weighted_frequency_matrix 2 "weighted_frequency_matrix" "SModel" builtin builtin_frequency_matrix 1 "frequency_matrix" "SModel" builtin mut_sel_q 2 "mut_sel_q" "SModel" builtin mut_sel_pi 2 "mut_sel_pi" "SModel" builtin builtin_modulated_markov_rates 2 "modulated_markov_rates" "SModel" builtin builtin_modulated_markov_pi 2 "modulated_markov_pi" "SModel" builtin builtin_modulated_markov_smap 1 "modulated_markov_smap" "SModel" data F81 = F81 Alphabet (EVector Int) () (EVector Double) data MixtureModel a = MixtureModel [(Double,a)] -- Currently we are weirdly duplicating the mixture probabilities for each component. -- Probably the actual data-type is something like [(Double,\Int->a)] or [(Double,[a])] where all the [a] should have the same length. -- This would be a branch-dependent mixture data MixtureModels a = MixtureModels [Int] [MixtureModel a] branch_categories (MixtureModels categories _) = categories -- We need to combine branch lengths and rate matrices to get transition probability matrices. -- We need to combine mixtures of rate matrices. -- We need to combine mixtures of transition probability matrices. -- Should we combine mixture only at one of the levels? -- Should we select branch-specific models at the level of rate matrices, or the level of transition probability matrices, or both? rate (ReversibleMarkov a s q pi l t r) = r rate (MixtureModel d) = average [(p,rate m) | (p,m) <- d] scale x (ReversibleMarkov a s q pi l t r) = ReversibleMarkov a s q pi l (x*t) (x*r) scale x (MixtureModel dist ) = MixtureModel [(p, scale x m) | (p, m) <- dist] rescale r q = scale (r/rate q) q mixMM fs ms = MixtureModel $ mix fs [m | MixtureModel m <- ms] scale_MMs rs ms = [scale r m | (r,m) <- zip' rs ms] -- For mixtures like mixture([hky85,tn93,gtr]), we probably need to mix on the Matrix level, to avoid shared scaling. mixture ms fs = mixMM fs ms -- Note that this scales the models BY rs instead of TO rs. scaled_mixture ms rs fs = mixMM fs (scale_MMs rs ms) parameter_mixture :: (a -> MixtureModel b) -> [a] -> MixtureModel b parameter_mixture values model_fn = MixtureModel [ (f*p, m) |(p,x) <- values, let MixtureModel dist = model_fn x, (f,m) <- dist] parameter_mixture_unit :: (a -> ReversibleMarkov b) -> [a] -> MixtureModel b parameter_mixture_unit values model_fn = parameter_mixture values (unit_mixture . model_fn) rate_mixture m d = parameter_mixture d (\x->scale x m) average_frequency (MixtureModel ms) = list_from_vector $ builtin_average_frequency $ weighted_frequency_matrix $ MixtureModel ms extend_mixture (MixtureModel ms) (p,x) = MixtureModel $ mix [p, 1.0-p] [certainly x, ms] plus_inv p_inv mm = extend_mixture mm (p_inv, scale 0.0 $ f81 pi a) where a = getAlphabet mm pi = average_frequency mm rate_mixture_unif_bins base dist n_bins = rate_mixture base $ uniformDiscretize dist n_bins -- In theory we could take just (a,q) since we could compute smap from a (if states are simple) and pi from q. baseModel (MixtureModel l) i = snd (l !! i) nStates m = vector_size (stateLetters m) frequencies (ReversibleMarkov _ _ _ pi _ _ _) = pi frequencies (F81 _ _ _ pi) = pi unwrapMM (MixtureModel dd) = dd mixMixtureModels l dd = MixtureModel (mix l (map unwrapMM dd)) -- m1a_omega_dist f1 w1 = [(f1,w1), (1.0-f1,1.0)] m2a_omega_dist f1 w1 posP posW = extendDiscreteDistribution (m1a_omega_dist f1 w1) posP posW m2a_test_omega_dist f1 w1 posP posW 0 = m2a_omega_dist f1 w1 posP 1.0 m2a_test_omega_dist f1 w1 posP posW _ = m2a_omega_dist f1 w1 posP posW m3_omega_dist ps omegas = zip' ps omegas m3p_omega_dist ps omegas posP posW = extendDiscreteDistribution (m3_omega_dist ps omegas) posP posW m3_test_omega_dist ps omegas posP posW 0 = m3p_omega_dist ps omegas posP 1.0 m3_test_omega_dist ps omegas posP posW _ = m3p_omega_dist ps omegas posP posW -- The M7 is just a beta distribution -- gamma' = var(x)/(mu*(1-mu)) = 1/(a+b+1) = 1/(n+1) m7_omega_dist mu gamma n_bins = uniformDiscretize (beta a b) n_bins where cap = min (mu/(1.0+mu)) ((1.0-mu)/(2.0-mu)) gamma' = gamma*cap n = (1.0/gamma')-1.0 a = n*mu b = n*(1.0 - mu) -- The M8 is a beta distribution, where a fraction posP of sites have omega posW m8_omega_dist mu gamma n_bins posP posW = extendDiscreteDistribution (m7_omega_dist mu gamma n_bins) posP posW m8a_omega_dist mu gamma n_bins posP = m8_omega_dist mu gamma n_bins posP 1.0 m8a_test_omega_dist mu gamma n_bins posP posW 0 = m8_omega_dist mu gamma n_bins posP 1.0 m8a_test_omega_dist mu gamma n_bins posP posW _ = m8_omega_dist mu gamma n_bins posP posW -- w1 <- uniform 0.0 1.0 -- [f1, f2] <- symmetric_dirichlet 2 1.0 m1a w1 f1 model_func = parameter_mixture_unit (m1a_omega_dist f1 w1) model_func m2a w1 f1 posP posW model_func = parameter_mixture_unit (m2a_omega_dist f1 w1 posP posW) model_func m2a_test w1 f1 posP posW posSelection model_func = parameter_mixture_unit (m2a_test_omega_dist f1 w1 posP posW posSelection) model_func m3 ps omegas model_func = parameter_mixture_unit (m3_omega_dist ps omegas) model_func m3_test ps omegas posP posW posSelection model_func = parameter_mixture_unit (m3_test_omega_dist ps omegas posP posW posSelection) model_func m7 mu gamma n_bins model_func = parameter_mixture_unit (m7_omega_dist mu gamma n_bins) model_func m8 mu gamma n_bins posP posW model_func = parameter_mixture_unit (m8_omega_dist mu gamma n_bins posP posW) model_func m8a mu gamma n_bins posP model_func = parameter_mixture_unit (m8a_omega_dist mu gamma n_bins posP) model_func m8a_test mu gamma n_bins posP posW posSelection model_func = parameter_mixture_unit (m8a_test_omega_dist mu gamma n_bins posP posW posSelection) model_func -- OK, so if I change this from [Mixture Omega] to Mixture [Omega] or Mixture (\Int -> Omega), how do I apply the function model_func to all the omegas? branch_site fs ws posP posW branch_cats model_func = MixtureModels branch_cats [bg_mixture,fg_mixture] -- background omega distribution -- where the last omega is 1.0 (neutral) where bg_dist = zip fs (ws ++ [1.0]) -- accelerated omega distribution -- posW for all categories accel_dist = zip fs (repeat posW) -- background branches always use the background omega distribution bg_mixture = parameter_mixture_unit (mix [1.0-posP, posP] [bg_dist, bg_dist]) model_func -- foreground branches use the foreground omega distribution with probability posP fg_mixture = parameter_mixture_unit (mix [1.0-posP, posP] [bg_dist, accel_dist]) model_func branch_site_test fs ws posP posW posSelection branch_cats model_func = branch_site fs ws posP posW' branch_cats model_func where posW' = if (posSelection == 1) then posW else 1.0 mut_sel w' (ReversibleMarkov a smap q0 pi0 _ _ _) = reversible_markov a smap q pi where w = list_to_vector w' q = mut_sel_q q0 w pi = mut_sel_pi pi0 w mut_sel' w' q0 = mut_sel w q0 where w = get_ordered_elements (letters a) w' "fitnesses" a = getAlphabet q0 mut_sel_aa ws q@(ReversibleMarkov codon_a _ _ _ _ _ _) = mut_sel (aa_to_codon codon_a ws) q mut_sel_aa' ws' q0 = mut_sel_aa ws q0 where ws = get_ordered_elements (letters amino_alphabet) ws' "fitnesses" codon_alphabet = getAlphabet q0 amino_alphabet = getAminoAcids codon_alphabet fMutSel codon_a codon_w omega nuc_model = nuc_model & x3 codon_a & dNdS omega & mut_sel codon_w fMutSel' codon_a codon_ws' omega nuc_model = fMutSel codon_a codon_ws omega nuc_model where codon_ws = get_ordered_elements (letters codon_a) codon_ws' "fitnesses" aa_to_codon codon_a xs = [xs_array!aa | codon <- codons, let aa = translate codon_a codon] where xs_array = listArray' xs codons = take n_letters [0..] n_letters = alphabetSize codon_a -- \#1->let {w' = listAray' #1} in \#2 #3->fMutSel #0 codon_w #2 #3 -- The whole body of the function is let-floated up in round 2, and w' is eliminated. fMutSel0 codon_a aa_w omega nuc_q = fMutSel codon_a codon_w omega nuc_q where codon_w = aa_to_codon codon_a aa_w fMutSel0' codon_a amino_ws' omega nuc_model = fMutSel0 codon_a amino_ws omega nuc_model where amino_ws = get_ordered_elements (letters amino_a) amino_ws' "fitnesses" amino_a = getAminoAcids codon_a -- Issue: bad mixing on fMutSel model modulated_markov_rates qs rates_between = builtin_modulated_markov_rates (list_to_vector qs) rates_between modulated_markov_pi pis level_probs = builtin_modulated_markov_pi (list_to_vector pis) (list_to_vector level_probs) modulated_markov_smap smaps = builtin_modulated_markov_smap (list_to_vector smaps) -- This could get renamed, after I look at the paper that uses the term "modulated markov" modulated_markov models rates_between level_probs = reversible_markov a smap q pi where a = getAlphabet $ head models qs = map get_q models pis = map get_pi models smaps = map get_smap models q = modulated_markov_rates qs rates_between pi = modulated_markov_pi pis level_probs smap = modulated_markov_smap smaps markov_modulate_mixture nu (MixtureModel dist) = modulated_markov models rates_between level_probs where (level_probs,models) = unzip dist rates_between = generic_equ (length models) nu -- We need to rescale submodels to have substitution rate `1.0`. -- Otherwise class-switching rates are not relative to the substitution rate. tuffley_steel_98_unscaled s01 s10 q = modulated_markov [scale 0.0 q, q] rates_between level_probs where level_probs = [s10/total, s01/total] where total = s10 + s01 rates_between = fromLists [[-s01,s01],[s10,-s10]] tuffley_steel_98 s01 s10 q = tuffley_steel_98_unscaled s01 s10 (rescale 1.0 q) huelsenbeck_02 s01 s10 model = MixtureModel [(p, tuffley_steel_98_unscaled s01 s10 q) | (p,q) <- dist] where MixtureModel dist = rescale 1.0 model galtier_01_ssrv :: Double -> MixtureModel a -> ReversibleMarkov a galtier_01_ssrv nu model = modulated_markov models rates_between level_probs where MixtureModel dist = rescale 1.0 model level_probs = map fst dist models = map snd dist n_levels = length dist -- This is really a generic gtr... We should be able to get this with f81 rates_between = (generic_equ n_levels nu) %*% (plus_f_matrix $ list_to_vector level_probs) galtier_01 :: Double -> Double -> MixtureModel a -> MixtureModel a galtier_01 nu pi model = parameter_mixture_unit [(1.0-pi, 0.0), (pi, nu)] (\nu' -> galtier_01_ssrv nu' model) wssr07_ssrv :: Double -> Double -> Double -> MixtureModel a -> ReversibleMarkov a wssr07_ssrv s01 s10 nu model = tuffley_steel_98 s01 s10 $ galtier_01_ssrv nu model wssr07 :: Double -> Double -> Double -> Double -> MixtureModel a -> MixtureModel a wssr07 s01 s10 nu pi model = parameter_mixture_unit [(1.0-pi, 0.0), (pi, nu)] (\nu' -> wssr07_ssrv s01 s10 nu' model) gamma_rates_dist alpha = gamma alpha (1.0/alpha) gamma_rates alpha n base = rate_mixture_unif_bins base (gamma_rates_dist alpha) n log_normal_rates_dist sigmaOverMu = log_normal lmu lsigma where x = log(1.0+sigmaOverMu^2) lmu = -0.5*x lsigma = sqrt x log_normal_rates sigmaOverMu n base = rate_mixture_unif_bins base (log_normal_rates_dist sigmaOverMu) n --dp base rates fraction = rate_mixture base dist where dist = zip fraction rates free_rates rates fractions base = scaled_mixture (replicate (length fractions) base) rates fractions transition_p_index smodel_on_tree = mkArray n_branches (list_to_vector . branch_transition_p smodel_on_tree) where tree = get_tree' smodel_on_tree n_branches = numBranches tree -- * OK... so a mixture of rate matrices is NOT the same as a mixture of exponentiated matrices, because the rate matrices are scaled relative to each other. -- ** Hmm... THAT might explain why the mixtures aren't working well! We need to scale each of THOSE components separately. -- * In theory, we should allow each mixture component to have a different number of states. This would require -- that we either split the condition likelihoods into per-component objects, or reserve sum(i,smap(i)) spots per cell. -- Probably the latter one would be fine. -- * The model from Sergei Kosakovsky-Pond is a SModelOnTreeMixture, since it is a mixture at the matrix level. -- * The MBR models are also SModelOnTree Mixtures, since they are also mixtures at the matrix level. -- + We should be able to get them by combining SingleBranchLengthModels. -- OK... so a mixture of rate matrices is NOT the same as a mixture of exponentiated matrices, because the rate matrices are scale with respect to each other. -- So, we can have -- ReversibleMarkov -- rate matrix -- MixtureModel ReversibleMarkov -- mixture of rate matrices -- MixtureModels branch_cats MixtureModel -- per-branch mixture of rate matrices, where component i always has the same frequencies. -- We can construct mixtures of these things with e.g. gamma rate models. -- Gamma rate models SHOULD be able to construct unit_mixtures WITHOUT the use of mmm or unit_mixture now. -- We should also be able to constructing mixtures of mixtures of rate matrices -> mixtures of rate matrices. This sounds like the join operation. -- class SModelOnTree a where -- branch_transition_p :: (SingleBranchLengthModel a) Int -> EVector (Matrix Double) -- distribution :: a -> [Double] -- weighted_frequency_matrix :: a -> Matrix Double -- weighted_matrix :: a -> Matrix Double -- nBaseModels :: a -> Int -- stateLetters :: a -> EVector -- getAlphabet :: a -> b -- componentFrequencies :: a -> Int -> EVector -- How about -- scale :: a -> a ? -- qExp :: a -> Matrix Double? -- What kind of things can be scaled? Things built on rate matrices, I guess? -- If a mixture of mixture can be flattened, Mixture (Mixture) -> Mixture, isn't that like the monadic operation "join"? -- Instances: -- * ReversibleMarkovModel -- * MixtureModel -- * MixtureModels -- * SModelOnTree a => SModelOnTreeMixture [(Double,a)] -- So, the question is, can we avoid distribution on things like mixtures of Rates. -- So, how are we going to handle rate scaling? That should be part of the model! data SingleBranchLengthModel a = SingleBranchLengthModel BranchLengthTree a get_tree' (SingleBranchLengthModel t _) = t -- Avoid aliasing with get_tree from DataPartition get_smap (ReversibleMarkov _ s _ _ _ _ _) = s get_smap (MixtureModel ((_,m):_)) = get_smap m get_smap (MixtureModels branch_cat_list mms) = get_smap $ head mms -- branch_transition_p :: Tree -> a -> Array Int Double -> Int -> EVector branch_transition_p (SingleBranchLengthModel tree smodel@(MixtureModels branch_cat_list mms)) b = branch_transition_p (SingleBranchLengthModel tree mx) b where mx = mms!!(branch_cat_list!!b) branch_transition_p (SingleBranchLengthModel tree smodel@(MixtureModel cs )) b = [qExp $ scale (branch_length tree b/r) component | (_,component) <- cs] where r = rate smodel branch_transition_p (SingleBranchLengthModel tree smodel@(ReversibleMarkov _ _ _ _ _ _ _ )) b = [qExp $ scale (branch_length tree b/r) smodel] where r = rate smodel -- distribution :: a -> [Double] distribution (MixtureModel l) = map fst l distribution (MixtureModels _ (m:ms)) = distribution m distribution (ReversibleMarkov _ _ _ _ _ _ _) = [1.0] -- weighted_frequency_matrix :: a -> Matrix Double weighted_frequency_matrix (MixtureModels _ (m:ms)) = weighted_frequency_matrix m weighted_frequency_matrix (MixtureModel d) = let model = MixtureModel d dist = list_to_vector $ distribution model freqs = list_to_vector $ map (componentFrequencies model) [0..nBaseModels model-1] in builtin_weighted_frequency_matrix dist freqs weighted_frequency_matrix smodel@(ReversibleMarkov _ _ _ pi _ _ _) = builtin_weighted_frequency_matrix (list_to_vector [1.0]) (list_to_vector [pi]) -- frequency_matrix :: a -> Matrix Double frequency_matrix (MixtureModels _ (m:ms)) = frequency_matrix m frequency_matrix (MixtureModel d) = let model = MixtureModel d in builtin_frequency_matrix $ list_to_vector $ map (componentFrequencies model) [0..nBaseModels model-1] frequency_matrix smodel@(ReversibleMarkov _ _ _ pi _ _ _) = builtin_frequency_matrix (list_to_vector [pi]) -- nBaseModels :: a -> Int nBaseModels (MixtureModel l) = length l nBaseModels (MixtureModels _ (m:ms)) = nBaseModels m nBaseModels (ReversibleMarkov _ _ _ _ _ _ _) = 1 -- stateLetters :: a -> EVector stateLetters (ReversibleMarkov _ smap _ _ _ _ _) = smap stateLetters (F81 _ smap _ _ ) = smap stateLetters (MixtureModel l) = stateLetters (baseModel (MixtureModel l) 0) stateLetters (MixtureModels _ (m:ms)) = stateLetters m -- getAlphabet :: a -> Alphabet getAlphabet (ReversibleMarkov a _ _ _ _ _ _) = a getAlphabet (F81 a _ _ _) = a getAlphabet (MixtureModel l) = getAlphabet (baseModel (MixtureModel l) 0) getAlphabet (MixtureModels _ (m:ms)) = getAlphabet m -- componentFrequencies :: a -> Int -> EVector componentFrequencies smodel@(ReversibleMarkov _ _ _ _ _ _ _) i = [frequencies smodel]!!i componentFrequencies (MixtureModel d) i = frequencies (baseModel (MixtureModel d) i) componentFrequencies (MixtureModels _ (m:ms)) i = componentFrequencies m i --- unit_mixture m = MixtureModel (certainly m) mmm branch_cats m = MixtureModels branch_cats [m] empirical a filename = builtin_empirical a (list_to_string filename) wag_frequencies a = zip (letters a) (list_from_vector $ builtin_wag_frequencies a) lg_frequencies a = zip (letters a) (list_from_vector $ builtin_lg_frequencies a)
bredelings/BAli-Phy
haskell/SModel.hs
gpl-2.0
19,342
0
13
4,092
4,659
2,378
2,281
-1
-1
module ParserSpec (spec) where import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck import qualified Test.QuickCheck.Property as QP import Control.Monad import Language.Inference.Syntax import Language.Inference.Parser import Language.Inference.Pretty import Text.PrettyPrint (render) import Arbitrary spec :: Spec spec = do describe "printing" $ do prop "should be a right inverse of parsing" $ \x -> let printed = showTerm x in either (\x -> QP.property $ QP.failed { QP.reason = show x ++ "\n" ++ printed }) (\y -> x === y) $ readTerm printed
robertclancy/tapl
inference/tests/ParserSpec.hs
gpl-2.0
621
0
23
137
180
101
79
17
1
{-# LANGUAGE OverloadedStrings #-} import Network.HTTP.Types import Network.Wai import Network.Wai.Handler.Warp main :: IO () main = do putStrLn "Server running at http://127.0.0.1:9000" run 9000 app app :: Application app _req respond = respond $ responseLBS status200 headers body where headers = [ ("Content-Type", "text/plan")] body = "Hello World"
yamadapc/simple-warp-server
bin/Main.hs
gpl-2.0
370
0
8
65
96
52
44
12
1
module X86 where import Data.Int (Int64(..)) -- this represents the level of indirection of a value data I a = Concrete a | Pointer a deriving (Eq, Show) data Register = RAX | RBX | RCX | RDX | RSI | RDI | RSP | RBP | R8 | R9 | R10 | R11 | R12 | R13 | R14 | R15 deriving (Eq, Show) data Operand = Register (I Register) | Memory (I Int64) | Stack (I Int64) | Immediate (I Int64) | Label_R String deriving (Eq, Show) data Instruction = Label String | ADD Operand Operand | CMP Operand Operand | DIV Operand | JE Operand | JMP Operand | JNE Operand | MOV Operand Operand | MUL Operand Operand | NOP | PUSH Operand | POP Operand | SUB Operand Operand deriving (Eq, Show)
orchid-hybrid/WHILE
X86.hs
gpl-2.0
1,037
0
8
507
260
154
106
28
0
{-# LANGUAGE Rank2Types, OverloadedStrings, DeriveGeneric, TemplateHaskell, GeneralizedNewtypeDeriving #-} module Lamdu.Data.Anchors ( Code(..), onCode , Revision(..), onRevision , Pane, makePane , CodeProps, RevisionProps , assocNameRef , assocScopeRef , PresentationMode(..) , assocPresentationMode , assocTagOrder , ParamList , assocFieldParamList , BinderParamScopeId(..), bParamScopeId ) where import qualified Control.Lens as Lens import Data.Binary (Binary) import Data.ByteString.Char8 () import Data.Set (Set) import Data.Store.Rev.Branch (Branch) import Data.Store.Rev.Version (Version) import Data.Store.Rev.View (View) import Data.Store.Transaction (MkProperty(..)) import qualified Data.Store.Transaction as Transaction import GHC.Generics (Generic) import qualified Graphics.UI.Bottle.WidgetId as WidgetId import qualified Lamdu.Calc.Type as T import Lamdu.Eval.Results (ScopeId) import Lamdu.Expr.IRef (DefI, ValI) import qualified Lamdu.Expr.UniqueId as UniqueId type Pane m = DefI m data Code f m = Code { repl :: f (ValI m) , panes :: f [Pane m] , globals :: f (Set (DefI m)) , preJumps :: f [WidgetId.Id] , preCursor :: f WidgetId.Id , postCursor :: f WidgetId.Id , tags :: f (Set (T.Tag)) , tids :: f (Set (T.NominalId)) } onCode :: (forall a. Binary a => f a -> g a) -> Code f m -> Code g m onCode f (Code x0 x1 x2 x3 x4 x5 x6 x7) = Code (f x0) (f x1) (f x2) (f x3) (f x4) (f x5) (f x6) (f x7) data Revision f m = Revision { branches :: f [Branch m] , currentBranch :: f (Branch m) , cursor :: f WidgetId.Id , redos :: f [Version m] , view :: f (View m) } onRevision :: (forall a. Binary a => f a -> g a) -> Revision f m -> Revision g m onRevision f (Revision x0 x1 x2 x3 x4) = Revision (f x0) (f x1) (f x2) (f x3) (f x4) newtype BinderParamScopeId = BinderParamScopeId { _bParamScopeId :: ScopeId } deriving (Eq, Ord, Binary) type CodeProps m = Code (MkProperty m) m type RevisionProps m = Revision (MkProperty m) m makePane :: DefI m -> Pane m makePane = id assocNameRef :: (UniqueId.ToUUID a, Monad m) => a -> MkProperty m String assocNameRef = Transaction.assocDataRefDef "" "Name" . UniqueId.toUUID assocScopeRef :: (UniqueId.ToUUID a, Monad m) => a -> MkProperty m (Maybe BinderParamScopeId) assocScopeRef = Transaction.assocDataRef "ScopeId" . UniqueId.toUUID assocTagOrder :: Monad m => T.Tag -> MkProperty m Int assocTagOrder = Transaction.assocDataRefDef 0 "Order" . UniqueId.toUUID type ParamList = [T.Tag] assocFieldParamList :: Monad m => ValI m -> Transaction.MkProperty m (Maybe ParamList) assocFieldParamList lambdaI = Transaction.assocDataRef "field param list" $ UniqueId.toUUID lambdaI data PresentationMode = OO | Verbose | Infix Int deriving (Eq, Ord, Show, Generic) instance Binary PresentationMode assocPresentationMode :: (UniqueId.ToUUID a, Monad m) => a -> Transaction.MkProperty m PresentationMode assocPresentationMode = Transaction.assocDataRefDef Verbose "PresentationMode" . UniqueId.toUUID Lens.makeLenses ''BinderParamScopeId
da-x/lamdu
Lamdu/Data/Anchors.hs
gpl-3.0
3,251
0
13
710
1,117
617
500
79
1
{---------------------------------------------------------------------} {- Copyright 2015, 2016 Nathan Bloomfield -} {- -} {- This file is part of Feivel. -} {- -} {- Feivel is free software: you can redistribute it and/or modify -} {- it under the terms of the GNU General Public License version 3, -} {- as published by the Free Software Foundation. -} {- -} {- Feivel is distributed in the hope that it will be useful, but -} {- WITHOUT ANY WARRANTY; without even the implied warranty of -} {- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -} {- GNU General Public License for more details. -} {- -} {- You should have received a copy of the GNU General Public License -} {- along with Feivel. If not, see <http://www.gnu.org/licenses/>. -} {---------------------------------------------------------------------} module Feivel.Parse.ParseM ( ParseM, runParseM, reportParseErr, pAtLocus, stringParseM, -- Constants pNatural, pInteger, pRatInteger, pRat, pBool, pString, pVar, pFormat, pPath, pPaths, pText, -- Fences pParens, pBrack, pBrace, -- Lists pBraceList, pBrackList ) where import Feivel.Error import Feivel.Store import Carl.String (Format(..), Text(..)) import Carl.Data.Rat (Rat((:/:))) import Carl.Struct.Polynomial (Variable(..), VarString(..)) import Text.Parsec.Prim (ParsecT, runParserT, try, (<|>), (<?>), many, getPosition) import Text.ParserCombinators.Parsec (digit, many1, char, string, choice, option, noneOf, spaces, sepBy, oneOf, sepBy1) import Control.Monad.Trans.Class (lift) {-----------} {- :ParseM -} {-----------} type ParseM = ParsecT String () (Either Goof) stringParseM :: ParseM a -> String -> Either Goof a stringParseM p str = runParseM p "" str runParseM :: ParseM a -> String -> String -> Either Goof a runParseM p name str = case runParserT p () name str of Left goof -> Left goof Right (Left err) -> Left (parseGoof err) Right (Right x) -> Right x reportParseErr :: (PromoteError err) => Locus -> err -> ParseM a reportParseErr loc err = lift $ Left $ Goof loc (promote err) pAtLocus :: ParseM a -> ParseM (AtLocus a) pAtLocus p = do start <- getPosition x <- p end <- getPosition return (x :@ (locus start end)) {--------------} {- :Constants -} {--------------} pNatural :: ParseM Integer pNatural = do ds <- many1 digit return $ rd ds where rd = read :: String -> Integer pInteger :: ParseM Integer pInteger = pNegative <|> pNatural <?> "integer constant" where pNegative = do _ <- char '-' n <- pNatural return (-n) pRatInteger :: ParseM Rat pRatInteger = do k <- pInteger return $ k :/:1 pRat :: ParseM Rat pRat = do a <- pInteger b <- option 1 (char '/' >> pInteger) return (a:/:b) pBool :: ParseM Bool pBool = choice [ try $ string "#t" >> return True , try $ string "#f" >> return False ] <?> "boolean constant" pText :: ParseM Text pText = fmap Text pString pString :: ParseM String pString = do _ <- char '"' t <- many $ choice [ try $ noneOf ['\\', '"', '\n'] , try $ string "\\n" >> return '\n' , try $ string "\\\"" >> return '"' , try $ string "\\" >> return '\\' ] _ <- char '"' return t pShellArg :: ParseM String pShellArg = many1 $ noneOf [' ','\t','\n',')'] pPath :: ParseM FilePath pPath = many1 $ oneOf allowed where allowed = "abcdefghijklmnopqrstuvwxyz" ++ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ++ "_+-.0123456789/<>=:;@#$%^&" pPaths :: ParseM [FilePath] pPaths = sepBy1 pPath spaces pVar :: ParseM (Variable VarString) pVar = fmap (Var . VarString) $ many1 $ oneOf allowed where allowed = "abcdefghijklmnopqrstuvwxyz" ++ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ++ "_[]" pFormat :: ParseM Format pFormat = pLaTeX where pLaTeX = do _ <- try $ string "latex" return LaTeX {-----------} {- :Fences -} {-----------} pParens :: ParseM a -> ParseM a pParens p = do try $ char '(' >> spaces x <- p char ')' >> spaces return x pBrack :: ParseM a -> ParseM a pBrack p = do try $ char '[' >> spaces x <- p char ']' >> spaces return x pBrace :: ParseM a -> ParseM a pBrace p = do try $ char '{' >> spaces x <- p char '}' >> spaces return x {---------} {- :List -} {---------} pBraceList :: ParseM a -> ParseM [a] pBraceList p = do try $ char '{' >> spaces xs <- p `sepBy` (char ';' >> spaces) char '}' >> spaces return xs pBrackList :: ParseM a -> ParseM [a] pBrackList p = do try $ char '[' >> spaces xs <- p `sepBy` (char ';' >> spaces) char ']' >> spaces return xs
nbloomf/feivel
src/Feivel/Parse/ParseM.hs
gpl-3.0
4,996
0
13
1,410
1,449
749
700
119
3
module Language.Mulang.Inspector.Query ( inspect, select, selectCount, Query) where import Control.Monad (guard) import Language.Mulang.Ast (Expression) type Query a = [a] inspect :: Query () -> Bool inspect = not.null select :: Bool -> Query () select = guard selectCount :: (Int -> Bool) -> Query Expression -> Query () selectCount condition list = select (condition . length $ list)
mumuki/mulang
src/Language/Mulang/Inspector/Query.hs
gpl-3.0
400
0
8
72
145
82
63
14
1
{-| Module : Css.Constants Description : Defines the constants for the other CSS modules. -} module Css.Constants (margin0, padding0, width100, height100, -- * Node and Rectangle Constants fill, stroke, alignCenter, wideStroke, faded, semiVisible, fullyVisible, strokeRed, strokeDashed, roundCorners, -- * Colors theoryDark, coreDark, seDark, systemsDark, graphicsDark, dbwebDark, numDark, aiDark, hciDark, mathDark, introDark, titleColour, lightGrey, -- * Background Colors purple1, purple2, purple3, purple4, purple5, purple6, purple7, purple8, purple9, purple10, pink1, pink2, borderNone, borderPink, -- * More Node Colors! teal1, orange1, blue1, blue2, blue3, blue4, blue5, blue6, blueFb, red1, red2, red3, red4, red5, green1, green2, dRed, dGreen, dBlue, dPurple, grey1, grey2, grey3, grey4, grey5, grey6, beige1, -- * Color Palette Colors pastelRed, pastelOrange, pastelYellow, pastelGreen, pastelBlue, pastelPink, pastelPurple, pastelBrown, pastelGrey, -- * FCE Count Color fceCountColor, -- * Graph Styles nodeFontSize, hybridFontSize, boolFontSize, regionFontSize ) where import Clay import Prelude hiding ((**)) import Data.Text as T -- |Defines CSS for empty margins. margin0 :: Css margin0 = margin nil nil nil nil -- |Defines CSS for empty padding. padding0 :: Css padding0 = padding nil nil nil nil -- |Defines default rectangle width, which is 100%. width100 :: Css width100 = width $ pct 100 -- |Defines default rectangle height, which is 100%. height100 :: Css height100 = height $ pct 100 {- Node and rectangle constants, - including sizes, strokes, fills, - opacities, colors and alignments. -} -- |Defines "fill" as text for CSS. fill :: Text -> Css fill = (-:) "fill" -- |Defines "stroke" as text for CSS. stroke :: Text -> Css stroke = (-:) "stroke" -- |Defines the CSS for center alignment for a node or rectangle. alignCenter :: Css alignCenter = textAlign $ alignSide sideCenter -- |Defines the CSS for a wide stroke. wideStroke :: Css wideStroke = "stroke-width" -: "3" -- |Defines the CSS for a lower opacity, called faded. faded :: Css faded = opacity 0.4 -- |Defines the CSS for a mid-high opacity, but not quite opaque. semiVisible :: Css semiVisible = opacity 0.7 -- |Defines the CSS for something that is opaque. fullyVisible :: Css fullyVisible = opacity 1.0 -- |Defines the CSS for a strong red stroke. strokeRed :: Css strokeRed = do "stroke" -: "#CC0011" "stroke-width" -: "2px" {-| Defines the CSS for a dashed stroke, with the width between dashes being a bit smaller than the dash itself. -} strokeDashed :: Css strokeDashed = do "stroke-dasharray" -: "8,5" "stroke-width" -: "2px" -- |Defines the CSS for the rounded corners of a border. roundCorners :: Css roundCorners = "border-radius" -: "8px" {- Colors -} -- |Defines the color of a grayish blue. theoryDark :: T.Text theoryDark = "#B1C8D1" -- |Defines the color of a light gray. coreDark :: T.Text coreDark = "#C9C9C9" -- |Defines the color of a soft red. seDark :: T.Text seDark = "#E68080" -- |Defines the color of a light violet. systemsDark :: T.Text systemsDark = "#C285FF" -- |Defines the color of a mostly desaturated dark lime green. graphicsDark :: T.Text graphicsDark = "#66A366" -- |Defines the color of a strong pink. dbwebDark :: T.Text dbwebDark = "#C42B97" -- |Defines the color of a very light green. numDark :: T.Text numDark = "#B8FF70" -- |Defines the color of a very light blue. aiDark :: T.Text aiDark = "#80B2FF" -- |Defines the color of a soft lime green. hciDark :: T.Text hciDark = "#91F27A" -- |Defines the color of a slightly desaturated violet. mathDark :: T.Text mathDark = "#8A67BE" -- |Defines the color of a moderate cyan. introDark :: T.Text introDark = "#5DD5B8" -- |Defines the color of a very dark blue. titleColour :: T.Text titleColour = "#072D68" -- |Defines the color of a light gray. lightGrey :: T.Text lightGrey = "#CCCCCC" {- Background colors. -} -- |Defines the color of a dark grayish magenta, intended for the background. purple1 :: Color purple1 = parse "#46364A" -- |Defines the color of a mostly desaturated dark pink, intended for the -- background. purple2 :: Color purple2 = parse "#7E4D66" -- |Defines the color of a slightly desaturated magenta, intended for the -- background. purple3 :: Color purple3 = parse "#CD96CD" -- |Defines the color of a mostly desaturated dark magenta, intended for the -- background. purple4 :: Color purple4 = parse "#9C6B98" -- |Defines the color of a dark magenta, intended for the background. purple5 :: Color purple5 = parse "#800080" -- |Defines the color of a grayish violet, intended for the background. purple6 :: Color purple6 = parse "#CAC4D4" -- |Defines the color of a dark grayish violet, intended for the background. purple7 :: Color purple7 = parse "#9C91B0" -- |Defines the color of a mostly desaturated dark violet, intended for the -- background. purple8 :: Color purple8 = parse "#7A6A96" -- |Defines the color of a very dark desaturated violet, intended for the -- background. purple9 :: Color purple9 = parse "#433063" -- |Defines the color of a mostly desaturated dark violet, intended for the -- background. purple10 :: Color purple10 = parse "#5C497E" -- |Defines the color of a very soft pink, intended for the background. pink1 :: Color pink1 = parse "#DB94B8" -- |Defines the color of a light grayish pink, intended for the background. pink2 :: Color pink2 = rgb 236 189 210 -- |Defines an empty border, making for a flat look. borderNone :: Css borderNone = border solid (px 0) white -- |Defines a border with a color of pink1, intended for the timetable. borderPink :: (Stroke -> Size LengthUnit -> Color -> Css) -> Css borderPink borderStroke = borderStroke solid (px 2) pink1 {- More node colours! -} -- |Defines the color of a dark grayish blue, intended for nodes. teal1 :: Color teal1 = parse "#737A99" -- |Defines the color of a strong blue, intended for nodes. orange1 :: Color orange1 = parse "#1E7FCC" -- |Defines the color of a very dark, mostly black, violet intended for nodes. blue1 :: Color blue1 = parse "#261B2A" -- |Defines the color of a dark moderate blue, intended for nodes. blue2 :: Color blue2 = parse "#336685" -- |Defines the color of a slightly lighter than blue2 dark moderate blue, -- intended for nodes. blue3 :: Color blue3 = parse "#437699" -- |Defines the color of a soft blue, intended for nodes. blue4 :: Color blue4 = parse "#5566F5" -- |Defines the color of a very soft blue, intended for nodes. blue5 :: Color blue5 = parse "#A5A6F5" -- |Defines the color of a slightly lighter than blue5 very soft blue, -- intended for nodes. blue6 :: Color blue6 = rgb 184 231 249 -- |Defines the color of a slightly more virbrant than blue2 dark moderate -- blue, intended for nodes. blueFb :: Color blueFb = rgb 59 89 152 -- |Defines the color of a strong red, intended for nodes. red1 :: Color red1 = parse "#C92343" -- |Defines the color of a darker than red1 strong red, intended for nodes. red2 :: Color red2 = parse "#B91333" -- |Defines the color of a moderate orange, intended for nodes. red3 :: Color red3 = rgb 215 117 70 -- |Defines the color of a slightly darker than red3 moderate orange, intended -- for nodes. red4 :: Color red4 = rgb 195 97 50 -- |Defines the color of a light grayish red, intended for nodes. red5 :: Color red5 = rgb 221 189 189 -- |Defines the color of a very soft lime green, intended for nodes. green1 :: Color green1 = rgb 170 228 164 -- |Defines the color of a moderate cyan - lime green, intended for nodes. green2 :: Color green2 = parse "#3Cb371" -- |Defines the color of a slightly darker than red4 moderate orange, intended -- for nodes dRed :: T.Text dRed = "#D77546" -- |Defines the color of a dark moderate cyan - lime green, intended for -- nodes. dGreen :: T.Text dGreen = "#2E8B57" -- |Defines the color of a dark moderate blue, intended for nodes. dBlue :: T.Text dBlue = "#437699" -- |Defines the color of a very dark grayish magenta, intended for nodes. dPurple :: T.Text dPurple = "#46364A" -- |Defines the color of a very dark gray, mostly black, intended for nodes. grey1 :: Color grey1 = parse "#222" -- |Defines the color of a very light gray, intended for nodes. grey2 :: Color grey2 = parse "#dedede" -- |Defines the color of a dark gray, intended for nodes. grey3 :: Color grey3 = parse "#949494" -- |Defines the color of a gray, intended for nodes. grey4 :: Color grey4 = parse "#BABABA" -- |Defines the color of a slightly darker grey2 very light gray, intended for -- nodes. grey5 :: Color grey5 = parse "#DCDCDC" -- |Defines the color of a slightly lighter than grey3 dark gray, intended for -- nodes. grey6 :: Color grey6 = parse "#9C9C9C" -- |Defines the color of a light grayish orange, intended for nodes. beige1 :: Color beige1 = parse "#EBE8E4" {-Color palette colors-} -- |Defines the color of a very light red. pastelRed :: Color pastelRed = parse "#FF7878" -- |Defines the color of a very light orange. pastelOrange :: Color pastelOrange = parse "#FFC48C" -- |Defines the color of a very soft yellow. pastelYellow :: Color pastelYellow = parse "#EEDD99" -- |Defines the color of a very soft lime green. pastelGreen :: Color pastelGreen = parse "#BDECB6" -- |Defines the color of a very soft blue. pastelBlue :: Color pastelBlue = parse "#9BD1FA" -- |Defines the color of a very pale red. pastelPink :: Color pastelPink = parse "#FFD1DC" -- |Defines the color of a very soft magenta. pastelPurple :: Color pastelPurple = parse "#E3AAD6" -- |Defines the color of a mostly desaturated dark orange. pastelBrown :: Color pastelBrown = parse "#AD876E" -- |Defines the color of a dark grayish blue. pastelGrey :: Color pastelGrey = parse "#A2A9AF" {- FCE count color. Currently unused. -} -- |Defines the color of a light blue, intended for FCE count, and currently -- unused. fceCountColor :: Color fceCountColor = parse "#66C2FF" {- Graph styles -} -- |Defines node font size, 12 in pixels. nodeFontSize :: Num a => a nodeFontSize = 12 -- |Defines hybrid font size, 7 in pixels. hybridFontSize :: Double hybridFontSize = 7 -- |Defines bool font size, 6 in pixels. boolFontSize :: Num a => a boolFontSize = 6 -- |Defines region font size, 14 in pixels. regionFontSize :: Num a => a regionFontSize = 14
hermish/courseography
app/Css/Constants.hs
gpl-3.0
10,781
0
9
2,310
1,578
943
635
254
1
module Neural ( NNet, Layer, feedforward, backprop, backpropSome, randomNNet ) where import Data.Array.Unboxed import Data.List import Control.DeepSeq import Control.Parallel.Strategies import System.Random newtype Layer = Layer (UArray (Int,Int) Double) deriving (Eq) type NNet = [Layer] instance Read Layer where readsPrec p s = map (\ ~(a,r) -> let x = ul a in x `deepseq` (x, r)) $ readsPrec p s where ul l = let w = minimum (map length l) - 1 h = length l - 1 in Layer $ array ((0,0),(w,h)) $ do (y,r) <- zip [0 .. h] l (x,v) <- zip [0 .. w] r return ((x,y),v) instance Show Layer where showsPrec p (Layer l) = let ((x0,y0),(xn,yn)) = bounds l in showsPrec p $ map (\y -> map (\x -> l ! (x,y)) [x0 .. xn]) [y0 .. yn] instance NFData Layer where rnf (Layer l) = l `seq` () sigmoid :: Double -> Double sigmoid t = 1 / (1 + exp (-t)) -- This is the derivative given the sigmoid value. -- For the derivative given x: use sigmoidDerivative . sigmoid sigmoidDerivative :: Double -> Double sigmoidDerivative fx = fx * (1 - fx) feedforward :: NNet -> [Double] -> [Double] feedforward = flip (foldl' feedlayer) feedlayer :: [Double] -> Layer -> [Double] feedlayer i (Layer l) = let ((x0,y0),(xn,yn)) = bounds l in withStrategy (parList rdeepseq) $ map (\y -> sigmoid $ sum $ zipWith (\x i' -> (l ! (x,y)) * i') [x0 .. xn] (1:i)) [y0 .. yn] {- What was causing the bug ======================== When an error signal reaches a node, this should happen: -->Multiply by weights-->Propagate to earlier nodes / error \ -->Update weights. What was happening before I fixed the bug: -->Propagate to earlier nodes / error-->Multiply by weights \ -->Update weights -} backprop :: Double -> [Double] -> [Double] -> NNet -> NNet backprop rate i t = backpropSome rate i (map Just t) backpropSome :: Double -> [Double] -> [Maybe Double] -> NNet -> NNet backpropSome rate i t n = fst $ backprop' i t n where backprop' i t (l@(Layer la):n) = (nw:r,be) where ab@((x0,y0),(xn,yn)) = bounds la -- hs: output of this layer hs = feedlayer i l -- r: the next layer updated -- e: the error of this layer's output (r,e) = case n of [] -> ([], zipWith (\o m -> case m of Nothing -> 0 Just v -> v - o ) hs t) x -> backprop' hs t n -- we: Error divided among weights we :: UArray (Int,Int) Double we = array ab $ withStrategy (parList rdeepseq) $ do (oe,y) <- zip e [y0 .. yn] x <- [x0 .. xn] return ((x,y), oe * (la ! (x,y))) -- nw: New weights for this layer -- wl: weights leading to current node -- h: this node's output nw = Layer $ array ab $ withStrategy (parList rdeepseq) $ do (y,d,h) <- zip3 [y0 .. yn] e hs let sdh = sigmoidDerivative h (x,i') <- zip [x0 .. xn] (1 : i) return ((x,y), (la ! (x,y)) + rate * d * sdh * i') -- be: Errors to propagate back to earlier nodes be = map (\x -> sum $ map (\y -> we ! (x,y)) [y0 .. yn]) [x0 .. xn] randomNNet :: RandomGen g => g -> [Int] -> NNet randomNNet _ [_] = [] randomNNet gen (i:r@(n:_)) = let i' = i + 1 (gen',l1) = mapAccumL (const . uncurry (flip (,)) . randomR (-0.05, 0.05)) gen $ replicate ((i + 1) * n) () ar = ((0,0),(i, n - 1)) l1' = Layer $ array ar $ zip (range ar) l1 in l1' : randomNNet gen' r
quickdudley/varroa
Neural.hs
agpl-3.0
3,535
0
20
1,019
1,521
828
693
76
3
module PprDFG where import DFG import Outputable import qualified Data.Map.Strict as Map import qualified Data.Set as Set instance Outputable Graph where ppr g = hang head 2 (outputs $$ signals $$ nodes) where head = text "graph" <+> text (graphName g) outputs = text "outputs:" <+> (vcat $ map ppr $ Set.toAscList $ graphOutputs g) signals = text "signals:" <+> (vcat $ map ppr $ Map.toAscList $ graphSignals g) nodes = text "nodes:" <+> (vcat $ map ppr $ Map.toAscList $ graphNodes g) instance Outputable Signal where ppr s | SimpleSigType b <- signalType s = text "signal" <+> pprSignalName s <+> (ppr b) pprSignalName :: Signal -> SDoc pprSignalName s = case signalID s of Left str -> doubleQuotes $ text str Right id -> ppr '\\' <> ppr id instance Outputable Node where ppr (CaseNode o cond dflt branches) = hang head 2 body where head = pprSignalName o <+> equals <+> text "case" <+> pprSignalName cond <+> text "of" body = (vcat $ map (\ (v, s) -> integer v <+> arrow <+> ppr s) branches) $$ text "else" <+> arrow <+> ppr dflt ppr (BinNode o op l r) = pprSignalName o <+> equals <+> ppr op <+> pprSignalName l <+> pprSignalName r instance Outputable BinOp where ppr LessThan = parens $ char '<' ppr GreaterThan = parens $ char '>' ppr Minus = parens $ char '-' ppr Plus = parens $ char '+'
yjwen/hada
src/PprDFG.hs
lgpl-3.0
1,517
0
18
459
549
268
281
30
2
module RandomGeneration where import Types import System.Random (randomRIO) randomElement :: [a] -> IO a randomElement [] = fail "randomElement: empty list" randomElement [x] = return x randomElement xs = (xs !!) `fmap` randomRIO (0, length xs - 1) -- Implementations for GenerationBias. -- The basic functionality is shifting the odds between randomly -- choosing the horizontal or vertical neighbour of some given -- maze cell; different odds result in the desired visual pattern. randomBias :: GenerationBias -> (Int, Int) -> MazeIx -> [MazeIx] -> IO MazeIx randomBias NoBias _ _ xs = randomElement xs randomBias CheckerBoard dims@(mazeW, mazeH) ix@(x, y) xs = let sqX = 2*x `div` mazeW sqY = 2*y `div` mazeH bias = bool HorizBias VertBias $ (odd sqY && even sqX) || (odd sqX && even sqY) in randomBias bias dims ix xs randomBias DiagonalSplit dims@(mazeW, mazeH) ix@(x, y) xs = let bias = bool VertBias HorizBias $ x > (y * mazeW) `div` mazeH in randomBias bias dims ix xs randomBias bias _ (x, y) xs = let biased = filter filterFunc xs in randomElement $ concat $ xs : replicate 3 biased where filterFunc = case bias of VertBias -> (== x) . fst _ -> (== y) . snd -- other biases than HorizBias matched beforehand
mgmeier/MazeGenerator
RandomGeneration.hs
unlicense
1,411
0
13
405
439
236
203
26
2
main = do let a = [1,2,3,4] print (a !! 0) print (head a) let b = [1,2,4,4] print (a > b) let a = [2,1,1,1] print (a > b) print (tail a) print (init a)
Trickness/pl_learning
Haskell/list/list_simple.hs
unlicense
232
0
10
116
144
72
72
10
1