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
<?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="sk-SK"> <title>Call Graph</title> <maps> <homeID>callgraph</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/callgraph/src/main/javahelp/help_sk_SK/helpset_sk_SK.hs
apache-2.0
961
82
52
156
390
206
184
-1
-1
module A(A(..),akeybc,akeycb) where import B(B) import B(bkeyac) import C(C) import C(ckeyab) data A = A { name :: String } akeybc :: Either B (Maybe C) akeybc = Right Nothing akeycb :: Either C (Maybe B) akeycb = Right Nothing instance Show A where show a = [name a,show bkeyac,show ckeyab]
timjb/protocol-buffers
tests/recursive/test-case/a.hs
apache-2.0
299
0
8
58
148
83
65
12
1
{-# OPTIONS_JHC -fno-prelude #-} module Foreign.Marshal.Array ( -- * Marshalling arrays -- ** Allocation -- mallocArray, -- :: Storable a => Int -> IO (Ptr a) mallocArray0, -- :: Storable a => Int -> IO (Ptr a) allocaArray, -- :: Storable a => Int -> (Ptr a -> IO b) -> IO b allocaArray0, -- :: Storable a => Int -> (Ptr a -> IO b) -> IO b reallocArray, -- :: Storable a => Ptr a -> Int -> IO (Ptr a) reallocArray0, -- :: Storable a => Ptr a -> Int -> IO (Ptr a) -- ** Marshalling -- peekArray, -- :: Storable a => Int -> Ptr a -> IO [a] peekArray0, -- :: (Storable a, Eq a) => a -> Ptr a -> IO [a] pokeArray, -- :: Storable a => Ptr a -> [a] -> IO () pokeArray0, -- :: Storable a => a -> Ptr a -> [a] -> IO () -- ** Combined allocation and marshalling -- newArray, -- :: Storable a => [a] -> IO (Ptr a) newArray0, -- :: Storable a => a -> [a] -> IO (Ptr a) withArray, -- :: Storable a => [a] -> (Ptr a -> IO b) -> IO b withArray0, -- :: Storable a => a -> [a] -> (Ptr a -> IO b) -> IO b withArrayLen, -- :: Storable a => [a] -> (Int -> Ptr a -> IO b) -> IO b withArrayLen0, -- :: Storable a => a -> [a] -> (Int -> Ptr a -> IO b) -> IO b -- ** Copying -- | (argument order: destination, source) copyArray, -- :: Storable a => Ptr a -> Ptr a -> Int -> IO () moveArray, -- :: Storable a => Ptr a -> Ptr a -> Int -> IO () -- ** Finding the length -- lengthArray0, -- :: (Storable a, Eq a) => a -> Ptr a -> IO Int -- ** Indexing -- advancePtr, -- :: Storable a => Ptr a -> Int -> Ptr a ) where import Foreign.Marshal.Alloc import Foreign.Marshal.Utils import Foreign.Ptr import Foreign.Storable import Jhc.Basics import Jhc.IO import Jhc.List import Jhc.Monad import Jhc.Num import Jhc.Order -- allocation -- ---------- -- |Allocate storage for the given number of elements of a storable type -- (like 'Foreign.Marshal.Alloc.malloc', but for multiple elements). -- mallocArray :: Storable a => Int -> IO (Ptr a) mallocArray = doMalloc undefined doMalloc :: Storable a' => a' -> Int -> IO (Ptr a') doMalloc dummy size = mallocBytes (size * sizeOf dummy) -- |Like 'mallocArray', but add an extra position to hold a special -- termination element. -- mallocArray0 :: Storable a => Int -> IO (Ptr a) mallocArray0 size = mallocArray (size + 1) -- |Temporarily allocate space for the given number of elements -- (like 'Foreign.Marshal.Alloc.alloca', but for multiple elements). -- allocaArray :: Storable a => Int -> (Ptr a -> IO b) -> IO b allocaArray size fn = etaIO $ doAlloca undefined fn where doAlloca :: Storable a' => a' -> (Ptr a' -> IO b') -> IO b' doAlloca dummy fn = allocaBytes (size * sizeOf dummy) fn -- |Like 'allocaArray', but add an extra position to hold a special -- termination element. -- allocaArray0 :: Storable a => Int -> (Ptr a -> IO b) -> IO b allocaArray0 size = allocaArray (size + 1) -- |Adjust the size of an array -- reallocArray :: Storable a => Ptr a -> Int -> IO (Ptr a) reallocArray = doRealloc undefined where doRealloc :: Storable a' => a' -> Ptr a' -> Int -> IO (Ptr a') doRealloc dummy ptr size = reallocBytes ptr (size * sizeOf dummy) -- |Adjust the size of an array including an extra position for the end marker. -- reallocArray0 :: Storable a => Ptr a -> Int -> IO (Ptr a) reallocArray0 ptr size = reallocArray ptr (size + 1) -- |Convert an array of given length into a Haskell list. This version -- traverses the array backwards using an accumulating parameter, -- which uses constant stack space. The previous version using mapM -- needed linear stack space. -- peekArray :: Storable a => Int -> Ptr a -> IO [a] peekArray size ptr | ptr `seq` (size <= 0) = return [] | otherwise = f (size-1) [] where f 0 acc = do e <- peekElemOff ptr 0; return (e:acc) f n acc = do e <- peekElemOff ptr n; f (n-1) (e:acc) -- |Convert an array terminated by the given end marker into a Haskell list -- peekArray0 :: (Storable a, Eq a) => a -> Ptr a -> IO [a] peekArray0 marker ptr = do size <- lengthArray0 marker ptr peekArray size ptr -- finding the length -- ------------------ -- |Write the list elements consecutive into memory -- --pokeArray :: Storable a => Ptr a -> [a] -> IO () --pokeArray ptr vals = zipWithM_ (pokeElemOff ptr) [0..] vals where -- zipWithM_ :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m () -- zipWithM_ f xs ys = sequence_ (zipWith f xs ys) pokeArray :: Storable a => Ptr a -> [a] -> IO () pokeArray ptr vals = pokeArray' ptr vals >> return () pokeArray' :: Storable a => Ptr a -> [a] -> IO Int pokeArray' ptr vals = etaIO $ f 0 vals where f n [] | n `seq` True = return n f n (x:xs) = pokeElemOff ptr n x >> f (n + 1) xs -- |Write the list elements consecutive into memory and terminate them with the -- given marker element -- pokeArray0 :: Storable a => a -> Ptr a -> [a] -> IO () pokeArray0 marker ptr vals = do lv <- pokeArray' ptr vals pokeElemOff ptr lv marker -- combined allocation and marshalling -- ----------------------------------- -- |Write a list of storable elements into a newly allocated, consecutive -- sequence of storable values -- (like 'Foreign.Marshal.Utils.new', but for multiple elements). -- newArray :: Storable a => [a] -> IO (Ptr a) newArray vals = do ptr <- mallocArray (length vals) pokeArray ptr vals return ptr -- |Write a list of storable elements into a newly allocated, consecutive -- sequence of storable values, where the end is fixed by the given end marker -- newArray0 :: Storable a => a -> [a] -> IO (Ptr a) newArray0 marker vals = do ptr <- mallocArray0 (length vals) pokeArray0 marker ptr vals return ptr -- |Temporarily store a list of storable values in memory -- (like 'Foreign.Marshal.Utils.with', but for multiple elements). -- withArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b withArray vals = withArrayLen vals . const -- |Like 'withArray', but the action gets the number of values -- as an additional parameter -- withArrayLen :: Storable a => [a] -> (Int -> Ptr a -> IO b) -> IO b withArrayLen vals f = etaIO $ len `seq` allocaArray len $ \ptr -> do pokeArray ptr vals res <- f len ptr return res where len = length vals -- |Like 'withArray', but a terminator indicates where the array ends -- withArray0 :: Storable a => a -> [a] -> (Ptr a -> IO b) -> IO b withArray0 marker vals = withArrayLen0 marker vals . const -- |Like 'withArrayLen', but a terminator indicates where the array ends -- withArrayLen0 :: Storable a => a -> [a] -> (Int -> Ptr a -> IO b) -> IO b withArrayLen0 marker vals f = etaIO $ len `seq` allocaArray0 len $ \ptr -> do pokeArray0 marker ptr vals res <- f len ptr return res where len = length vals -- copying (argument order: destination, source) -- ------- -- |Copy the given number of elements from the second array (source) into the -- first array (destination); the copied areas may /not/ overlap -- copyArray :: Storable a => Ptr a -> Ptr a -> Int -> IO () copyArray = doCopy undefined where doCopy :: Storable a' => a' -> Ptr a' -> Ptr a' -> Int -> IO () doCopy dummy dest src size = copyBytes dest src (size * sizeOf dummy) -- |Copy the given number of elements from the second array (source) into the -- first array (destination); the copied areas /may/ overlap -- moveArray :: Storable a => Ptr a -> Ptr a -> Int -> IO () moveArray = doMove undefined where doMove :: Storable a' => a' -> Ptr a' -> Ptr a' -> Int -> IO () doMove dummy dest src size = moveBytes dest src (size * sizeOf dummy) -- finding the length -- ------------------ -- |Return the number of elements in an array, excluding the terminator -- lengthArray0 :: (Storable a, Eq a) => a -> Ptr a -> IO Int lengthArray0 marker ptr | ptr `seq` True = etaIO $ loop 0 where loop i | i `seq` True = do val <- peekElemOff ptr i if val == marker then return i else loop (i+1) -- indexing -- -------- -- |Advance a pointer into an array by the given number of elements -- advancePtr :: Storable a => Ptr a -> Int -> Ptr a advancePtr = doAdvance undefined where doAdvance :: Storable a' => a' -> Ptr a' -> Int -> Ptr a' doAdvance dummy ptr i = ptr `plusPtr` (i * sizeOf dummy)
m-alvarez/jhc
lib/jhc/Foreign/Marshal/Array.hs
mit
8,565
0
13
2,154
2,098
1,078
1,020
114
2
module Invariant where data F a = F {fx :: a, fy :: a, fzz :: a} | G {fx :: a} {-@ data F a = F {fxx :: a, fy :: a, fz :: a} | G {fxx :: a} @-} {-@ fooG :: x:a -> {v : F a | (fxx v) > x} @-} fooG :: a -> F a fooG x = G x {-@ foo :: x:a -> {v : F a | (fxx v) > x} @-} foo :: a -> F a foo x = F x x x
mightymoose/liquidhaskell
tests/neg/RecSelector.hs
bsd-3-clause
320
0
8
118
96
55
41
6
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="pl-PL"> <title>Quick Start | 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>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Szukaj</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>
ccgreen13/zap-extensions
src/org/zaproxy/zap/extension/quickstart/resources/help_pl_PL/helpset_pl_PL.hs
apache-2.0
974
85
52
160
398
210
188
-1
-1
{-# LANGUAGE GADTs, TypeFamilies, EmptyDataDecls #-} module T2627b where data R a b data W a b data Z type family Dual a type instance Dual Z = Z type instance Dual (R a b) = W a (Dual b) type instance Dual (W a b) = R a (Dual b) data Comm a where Rd :: (a -> Comm b) -> Comm (R a b) Wr :: a -> Comm b -> Comm (W a b) Fin :: Int -> Comm Z conn :: (Dual a ~ b, Dual b ~ a) => Comm a -> Comm b -> (Int, Int) conn (Rd k) (Wr a r) = conn undefined undefined
frantisekfarka/ghc-dsi
testsuite/tests/indexed-types/should_fail/T2627b.hs
bsd-3-clause
473
0
10
131
245
131
114
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-| Module : Npm.Latest Description : Fetch the latest version of an npm module. Copyright : (c) Pascal Hartig, 2014 License : MIT Maintainer : phartig@rdrei.net Stability : experimental Portability : POSIX This is just an experiment of me porting a node module to Haskell and learning about Lenses and Pipes along the way. Use on your own risk. -} module Npm.Latest ( fetchLatestVersion, extractVersion, GenericNpmException(..) ) where import Control.Exception (SomeException) import Data.Text.Format (Format) import Npm.Latest.Internal (buildRequest, makeVersionRequest, extractVersion, GenericNpmException(..)) import qualified Data.Text as T latestUrl :: Format latestUrl = "https://registry.npmjs.org/{}/latest" -- |Fetch the latest version for the given module name. fetchLatestVersion :: String -> IO (Either SomeException T.Text) fetchLatestVersion name = do req <- buildRequest name latestUrl resp <- makeVersionRequest req return $ extractVersion resp
passy/latest-npm-version
Npm/Latest.hs
mit
1,039
0
9
172
149
86
63
16
1
{-# LANGUAGE OverloadedStrings #-} {-| Module: Web.OIDC.Client.Settings Maintainer: krdlab@gmail.com Stability: experimental -} module Web.OIDC.Client.Settings ( OIDC(..) , def , newOIDC , setCredentials ) where import Data.ByteString (ByteString) import Data.Text (Text) import Web.OIDC.Client.Discovery.Provider (Provider) import qualified Web.OIDC.Client.Discovery.Provider as P -- | This data type represents information needed in the OpenID flow. data OIDC = OIDC { oidcAuthorizationServerUrl :: Text , oidcTokenEndpoint :: Text , oidcClientId :: ByteString , oidcClientSecret :: ByteString , oidcRedirectUri :: ByteString , oidcProvider :: Provider } def :: OIDC def = OIDC { oidcAuthorizationServerUrl = error "You must specify authorizationServerUrl" , oidcTokenEndpoint = error "You must specify tokenEndpoint" , oidcClientId = error "You must specify clientId" , oidcClientSecret = error "You must specify clientSecret" , oidcRedirectUri = error "You must specify redirectUri" , oidcProvider = error "You must specify provider" } newOIDC :: Provider -- ^ OP's information (obtained by 'Web.OIDC.Client.Discovery.discover') -> OIDC newOIDC p = def { oidcAuthorizationServerUrl = P.authorizationEndpoint . P.configuration $ p , oidcTokenEndpoint = P.tokenEndpoint . P.configuration $ p , oidcProvider = p } setCredentials :: ByteString -- ^ client ID -> ByteString -- ^ client secret -> ByteString -- ^ redirect URI (the HTTP endpont on your server that will receive a response from OP) -> OIDC -> OIDC setCredentials cid secret redirect oidc = oidc { oidcClientId = cid , oidcClientSecret = secret , oidcRedirectUri = redirect }
krdlab/haskell-oidc-client
src/Web/OIDC/Client/Settings.hs
mit
2,053
0
9
642
304
186
118
43
1
-- | provides methods to see what types of attacks are effective -- against what and what defenses are good against what module TypeComparison (weakDefenseAgainst, strongDefenseAgainst, against, getTypesAccordingTo, typeMap, DamageMult) where import Pokemon import Data.List (union) import qualified Data.Map as M (Map, fromList, lookup, mapMaybeWithKey, elems) type DamageMult = Double -- | What types have a weak defense against the given type? weakDefenseAgainst :: Type -> [Type] weakDefenseAgainst t = getTypesAccordingTo (\(a, d) v -> if (t == a) && (v > 1) then Just d else Nothing) -- | What types have a strong defense against the given type? strongDefenseAgainst :: Type -> [Type] strongDefenseAgainst t = getTypesAccordingTo (\(a, d) v -> if (t == a) && (v < 1) then Just d else Nothing) -- | Higher order function for getting info on types getTypesAccordingTo :: ((Type, Type) -> Double -> Maybe Type) -> [Type] getTypesAccordingTo fun = M.elems $ M.mapMaybeWithKey fun typeMap -- | Return the effectiveness of @t1@ 'against' @t2@ against :: Type -> Type -> Double t1 `against` t2 = maybe 1 id $ M.lookup (t1, t2) typeMap -- | What types will do poor against the given type? weakOffenseAgainst :: Type -> [Type] weakOffenseAgainst t = getTypesAccordingTo (\(a, d) v -> if (t == d) && (v < 1) then Just a else Nothing) -- | What types will to well against the given type? strongOffenseAgainst :: Type -> [Type] strongOffenseAgainst t = getTypesAccordingTo (\(a, d) v -> if (t == d) && (v > 1) then Just a else Nothing) describeDefender :: Pokemon -> [Type] describeDefender = foldr union [] . map strongDefenseAgainst . types -- | A map containing the multipliers for attack types. -- If it's not in the map, the multiplier is 1. -- Structure: ((Attacker, Defender), multiplier) typeMap :: M.Map (Type, Type) DamageMult typeMap = M.fromList [((Normal, Rock), 0.5) ,((Normal, Ghost), 0) ,((Normal, Steel), 0.5) ,((Fighting, Normal), 2) ,((Fighting, Flying), 0.5) ,((Fighting, Poison), 0.5) ,((Fighting, Rock), 2) ,((Fighting, Bug), 0.5) ,((Fighting, Ghost), 0) ,((Fighting, Steel), 2) ,((Fighting, Psychic), 0.5) ,((Fighting, Ice), 2) ,((Fighting, Dark), 2) ,((Flying, Fighting), 2) ,((Flying, Rock), 0.5) ,((Flying, Bug), 2) ,((Flying, Steel), 0.5) ,((Flying, Grass), 2) ,((Flying, Electric), 0.5) ,((Poison, Poison), 0.5) ,((Poison, Ground), 0.5) ,((Poison, Rock), 0.5) ,((Poison, Ghost), 0.5) ,((Poison, Steel), 0) ,((Poison, Grass), 2) ,((Ground, Flying), 0) ,((Ground, Poison), 2) ,((Ground, Rock), 2) ,((Ground, Bug), 0.5) ,((Ground, Steel), 2) ,((Ground, Fire), 2) ,((Ground, Grass), 0.5) ,((Ground, Electric), 2) ,((Rock, Fighting), 0.5) ,((Rock, Flying), 2) ,((Rock, Ground), 0.5) ,((Rock, Bug), 2) ,((Rock, Steel), 0.5) ,((Rock, Fire), 2) ,((Rock, Ice), 2) ,((Bug, Fighting), 0.5) ,((Bug, Flying), 0.5) ,((Bug, Poison), 0.5) ,((Bug, Ghost), 0.5) ,((Bug, Steel), 0.5) ,((Bug, Fire), 0.5) ,((Bug, Grass), 2) ,((Bug, Psychic), 2) ,((Bug, Dark), 2) ,((Ghost, Normal), 0) ,((Ghost, Ghost), 2) ,((Ghost, Steel), 0.5) ,((Ghost, Psychic), 2) ,((Ghost, Dark), 0.5) ,((Steel, Rock), 2) ,((Steel, Steel), 0.5) ,((Steel, Fire), 0.5) ,((Steel, Water), 0.5) ,((Steel, Electric), 0.5) ,((Steel, Ice), 2) ,((Fire, Rock), 0.5) ,((Fire, Bug), 2) ,((Fire, Steel), 2) ,((Fire, Fire), 0.5) ,((Fire, Water), 0.5) ,((Fire, Grass), 2) ,((Fire, Ice), 2) ,((Fire, Dragon), 0.5) ,((Water, Ground), 2) ,((Water, Rock), 2) ,((Water, Fire), 2) ,((Water, Water), 0.5) ,((Water, Grass), 0.5) ,((Water, Dragon), 0.5) ,((Grass, Flying), 0.5) ,((Grass, Poison), 0.5) ,((Grass, Ground), 2) ,((Grass, Rock), 2) ,((Grass, Bug), 0.5) ,((Grass, Steel), 0.5) ,((Grass, Fire), 0.5) ,((Grass, Water), 2) ,((Grass, Grass), 0.5) ,((Grass, Dragon), 0.5) ,((Electric, Flying), 2) ,((Electric, Ground), 0) ,((Electric, Water), 2) ,((Electric, Grass), 0.5) ,((Electric, Electric), 0.5) ,((Electric, Dragon), 0.5) ,((Psychic, Fighting), 2) ,((Psychic, Poison), 2) ,((Psychic, Steel), 0.5) ,((Psychic, Psychic), 0.5) ,((Psychic, Dark), 0) ,((Ice, Flying), 2) ,((Ice, Ground), 2) ,((Ice, Steel), 0.5) ,((Ice, Fire), 0.5) ,((Ice, Water), 0.5) ,((Ice, Grass), 2) ,((Ice, Ice), 0.5) ,((Ice, Dragon), 2) ,((Dragon, Steel), 0.5) ,((Dragon, Dragon), 2) ,((Dark, Fighting), 0.5) ,((Dark, Ghost), 2) ,((Dark, Steel), 0.5) ,((Dark, Psychic), 2) ,((Dark, Dark), 0.5)]
apella/pokedex
TypeComparison.hs
mit
6,417
0
11
2,728
2,165
1,394
771
131
2
{-| Http Client Driver TODO When making a request, handle the case where the request id is already in use. -} module Urbit.Vere.Http.Client where import Urbit.Prelude hiding (Builder, finally) import Urbit.Vere.Http import Urbit.Vere.Pier.Types import Urbit.King.App import Urbit.Arvo (BlipEv(..), Ev(..), HttpClientEf(..), HttpClientEv(..), HttpClientReq(..), HttpEvent(..), KingId, ResponseHeader(..)) import RIO.Orphans () import Control.Monad.Catch (finally) import qualified Data.Map.Strict as M import qualified Network.HTTP.Client as H import qualified Network.HTTP.Client.TLS as TLS import qualified Network.HTTP.Types as HT -- Types ----------------------------------------------------------------------- type ReqId = Word data HttpClientDrv = HttpClientDrv { hcdManager :: H.Manager , hcdLive :: TVar (Map ReqId (Async ())) } -------------------------------------------------------------------------------- cvtReq :: HttpClientReq -> Maybe H.Request cvtReq r = H.parseRequest (unpack (unCord $ url r)) <&> \init -> init { H.method = encodeUtf8 $ tshow (method r) , H.requestHeaders = unconvertHeaders (headerList r) , H.requestBody = H.RequestBodyBS $ case body r of Nothing -> "" Just (Octs bs) -> bs } cvtRespHeaders :: H.Response a -> ResponseHeader cvtRespHeaders resp = ResponseHeader (fromIntegral $ HT.statusCode (H.responseStatus resp)) heads where heads = convertHeaders (H.responseHeaders resp) bornEv :: KingId -> Ev bornEv king = EvBlip $ BlipEvHttpClient $ HttpClientEvBorn (king, ()) () -------------------------------------------------------------------------------- _bornFailed :: e -> WorkError -> IO () _bornFailed env _ = runRIO env $ do pure () -- TODO What to do in this case? client' :: HasPierEnv e => RIO e ([Ev], RAcquire e (DriverApi HttpClientEf)) client' = do ventQ :: TQueue EvErr <- newTQueueIO env <- ask let (bornEvs, startDriver) = client env (writeTQueue ventQ) let runDriver = do diOnEffect <- startDriver let diEventSource = fmap RRWork <$> tryReadTQueue ventQ pure (DriverApi {..}) pure (bornEvs, runDriver) {-| Iris -- HTTP Client Driver Until born events succeeds, ignore effects. Wait until born event callbacks invoked. If success, signal success. If failure, try again several times. If still failure, bring down ship. Once born event succeeds, hold on to effects. Once all other drivers have booted: - Execute stashed effects. - Begin normal operation (start accepting requests) -} client :: forall e . (HasLogFunc e, HasKingId e) => e -> (EvErr -> STM ()) -> ([Ev], RAcquire e (HttpClientEf -> IO ())) client env plan = (initialEvents, runHttpClient) where kingId = view (kingIdL . to fromIntegral) env initialEvents :: [Ev] initialEvents = [bornEv kingId] runHttpClient :: RAcquire e (HttpClientEf -> IO ()) runHttpClient = handleEffect <$> mkRAcquire start stop start :: RIO e (HttpClientDrv) start = HttpClientDrv <$> (io $ H.newManager TLS.tlsManagerSettings) <*> newTVarIO M.empty stop :: HttpClientDrv -> RIO e () stop HttpClientDrv{..} = do -- Cancel all the outstanding asyncs, ignoring any exceptions. liveThreads <- atomically $ readTVar hcdLive mapM_ cancel liveThreads handleEffect :: HttpClientDrv -> HttpClientEf -> IO () handleEffect drv = \case HCERequest _ id req -> runRIO env (newReq drv id req) HCECancelRequest _ id -> runRIO env (cancelReq drv id) newReq :: HttpClientDrv -> ReqId -> HttpClientReq -> RIO e () newReq drv id req = do async <- runReq drv id req -- If the async has somehow already completed, don't put it in the map, -- because then it might never get out. atomically $ pollSTM async >>= \case Nothing -> modifyTVar' (hcdLive drv) (insertMap id async) Just _ -> pure () -- The problem with the original http client code was that it was written -- to the idea of what the events "should have" been instead of what they -- actually were. This means that this driver doesn't run like the vere -- http client driver. The vere driver was written assuming that parts of -- events could be compressed together: a Start might contain the only -- chunk of data and immediately complete, where here the Start event, the -- Continue (with File) event, and the Continue (completed) event are three -- separate things. runReq :: HttpClientDrv -> ReqId -> HttpClientReq -> RIO e (Async ()) runReq HttpClientDrv{..} id req = async $ flip finally aftr $ case cvtReq req of Nothing -> do logInfo $ displayShow ("(malformed http client request)", id, req) planEvent id (Cancel ()) Just r -> do logDebug $ displayShow ("(http client request)", id, req) withRunInIO $ \run -> H.withResponse r hcdManager $ \x -> run (exec x) where -- Make sure to remove our entry from hcdLive after we're done so the -- map doesn't grow without bound. aftr :: RIO e () aftr = atomically $ modifyTVar' hcdLive (deleteMap id) recv :: H.BodyReader -> RIO e (Maybe ByteString) recv read = io $ read <&> \case chunk | null chunk -> Nothing | otherwise -> Just chunk exec :: H.Response H.BodyReader -> RIO e () exec resp = do let headers = cvtRespHeaders resp getChunk = recv (H.responseBody resp) loop = getChunk >>= \case Nothing -> planEvent id (Continue Nothing True) Just bs -> do planEvent id $ Continue (Just $ File $ Octs bs) False loop planEvent id (Start headers Nothing False) loop planEvent :: ReqId -> HttpEvent -> RIO e () planEvent id ev = do logDebug $ displayShow ("(http client response)", id, (describe ev)) let recvEv = EvBlip $ BlipEvHttpClient $ HttpClientEvReceive (kingId, ()) (fromIntegral id) ev let recvFailed _ = pure () atomically $ plan (EvErr recvEv recvFailed) -- show an HttpEvent with byte count instead of raw data describe :: HttpEvent -> String describe (Start header Nothing final) = "(Start " ++ (show header) ++ " ~ " ++ (show final) describe (Start header (Just (File (Octs bs))) final) = "(Start " ++ (show header) ++ " (" ++ (show $ length bs) ++ " bytes) " ++ (show final) describe (Continue Nothing final) = "(Continue ~ " ++ (show final) describe (Continue (Just (File (Octs bs))) final) = "(Continue (" ++ (show $ length bs) ++ " bytes) " ++ (show final) describe (Cancel ()) = "(Cancel ())" waitCancel :: Async a -> RIO e (Either SomeException a) waitCancel async = cancel async >> waitCatch async cancelThread :: ReqId -> Async a -> RIO e () cancelThread id = waitCancel >=> \case Left _ -> planEvent id $ Cancel () Right _ -> pure () cancelReq :: HttpClientDrv -> ReqId -> RIO e () cancelReq drv id = join $ atomically $ do tbl <- readTVar (hcdLive drv) case lookup id tbl of Nothing -> pure (pure ()) Just async -> do writeTVar (hcdLive drv) (deleteMap id tbl) pure (cancelThread id async)
urbit/urbit
pkg/hs/urbit-king/lib/Urbit/Vere/Http/Client.hs
mit
7,706
0
24
2,168
2,133
1,085
1,048
-1
-1
module Foundation where import Import.NoFoundation hiding (ByteString) import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Yesod.Auth.Simple import Yesod.Default.Util (addStaticContentExternal) import Yesod.Core.Types (Logger) import qualified Yesod.Core.Unsafe as Unsafe import Util.Shakespare (stextFile) import Util.Slug (mkSlug) import Util.Hash (sha1Text) import Util.User (newToken) import Util.Alert (successHtml) import Settings.Environment (mailgunDomain, mailgunApiKey, emailFromAddress, analyticsId) import Data.Text.Lazy.Builder (toLazyText) import Data.ByteString (ByteString) import Mail.Hailgun ( sendEmail, hailgunMessage, emptyMessageRecipients, UnverifiedEmailAddress, HailgunContext(..), MessageContent(..), HailgunErrorResponse(..), MessageRecipients(..)) import qualified Model.Snippet.Api as SnippetApi import qualified Model.Run.Api as RunApi -- | The foundation datatype for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { appSettings :: AppSettings , appStatic :: Static -- ^ Settings for static file serving. , appConnPool :: ConnectionPool -- ^ Database connection pool. , appHttpManager :: Manager , appLogger :: Logger } instance HasHttpManager App where getHttpManager = appHttpManager -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the linked documentation for an -- explanation for this split. mkYesodData "App" $(parseRoutesFile "config/routes") -- | A convenient synonym for creating forms. type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where -- Controls the base of generated URLs. For more information on modifying, -- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot approot = ApprootMaster $ appRoot . appSettings -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = fmap Just $ defaultClientSessionBackend 525600 -- timeout in minutes "config/client_session_key.aes" defaultLayout widget = do mmsg <- getMessage mAnalytics <- liftIO analyticsId -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent $ do addStylesheet $ StaticR lib_font_awesome_css_font_awesome_min_css $(combineStylesheets 'StaticR [ lib_bootstrap_bootstrap_min_css, css_glot_css]) $(combineScripts 'StaticR [ lib_jquery_jquery_min_js, lib_bootstrap_bootstrap_min_js, js_location_js, js_xhr_js]) $(widgetFile "default-layout") $(widgetFile "widgets/alert") case mAnalytics of Just aId -> $(widgetFile "widgets/analytics") Nothing -> return () withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR -- Routes not requiring authentication. isAuthorized (AuthR _) _ = return Authorized isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized -- Default to Authorized for now. isAuthorized _ _ = return Authorized -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = AccountProfileR -- Where to send a user after logout logoutDest _ = HomeR -- Override the above two destinations when a Referer: header is present redirectToReferer _ = True onLogin = setMessage $ successHtml "You are now logged in" getAuthId = return . fromPathPiece . credsIdent -- You can add other plugins like BrowserID, email or OAuth here authPlugins _ = [authSimple] authHttpManager = getHttpManager instance YesodAuthPersist App instance YesodAuthSimple App where type AuthSimpleId App = UserId afterPasswordRoute _ = HomeR onPasswordUpdated = setMessage $ successHtml "Password has been updated" insertUser email password = do let name = takeWhile (/= '@') email username <- mkUsername email name token <- liftIO newToken snippetsId <- liftIO $ SnippetApi.addUser token runId <- liftIO $ RunApi.addUser token now <- liftIO getCurrentTime runDB $ do mUserId <- insertUnique $ User email password now now case mUserId of Just userId -> do _ <- insertUnique $ Profile userId snippetsId username name now now _ <- insertUnique $ ApiUser userId snippetsId runId token now now return mUserId Nothing -> do return mUserId updateUserPassword uid pass = do now <- liftIO getCurrentTime runDB $ update uid [UserPassword =. pass, UserModified =. now] getUserId email = runDB $ do res <- getBy $ UniqueUser email return $ case res of Just (Entity uid _) -> Just uid _ -> Nothing getUserPassword = runDB . fmap userPassword . get404 getUserModified = runDB . fmap userModified . get404 loginTemplate mErr = $(widgetFile "auth/login") registerTemplate mErr = $(widgetFile "auth/register") confirmationEmailSentTemplate = $(widgetFile "auth/confirmation-email-sent") confirmTemplate confirmUrl email mErr = $(widgetFile "auth/confirm") registerSuccessTemplate = $(widgetFile "auth/register-success") setPasswordTemplate setPasswordUrl mErr = $(widgetFile "auth/set-password") resetPasswordTemplate mErr = $(widgetFile "auth/reset-password") resetPasswordEmailSentTemplate = $(widgetFile "auth/reset-password-email-sent") invalidTokenTemplate msg = $(widgetFile "auth/invalid-token") userExistsTemplate = $(widgetFile "auth/user-exists") sendVerifyEmail email url = do let toAddress = encodeUtf8 email let subject = "Registration Link" let msg = registerEmailMsg url liftIO $ sendEmail' [toAddress] subject msg sendResetPasswordEmail email url = do let toAddress = encodeUtf8 email let subject = "Reset password link" let msg = resetPasswordEmailMsg url liftIO $ sendEmail' [toAddress] subject msg sendEmail' :: [UnverifiedEmailAddress] -> Text -> ByteString -> IO () sendEmail' toAddrs subject msg = do fromAddr <- encodeUtf8 <$> emailFromAddress domain <- mailgunDomain apiKey <- mailgunApiKey let context = HailgunContext{ hailgunDomain = domain, hailgunApiKey = apiKey, hailgunProxy = Nothing} let recipients = emptyMessageRecipients {recipientsTo = toAddrs} case hailgunMessage subject (TextOnly msg) fromAddr recipients [] of Left _ -> error "Failed to compose email" Right mail -> do res <- sendEmail context mail case res of Left errorResponse -> do liftIO $ print $ herMessage errorResponse error "Failed to send email" Right _ -> return () registerEmailMsg :: Text -> ByteString registerEmailMsg url = encodeUtf8 $ toStrict $ toLazyText $(stextFile "templates/email/register.txt") resetPasswordEmailMsg :: Text -> ByteString resetPasswordEmailMsg url = encodeUtf8 $ toStrict $ toLazyText $(stextFile "templates/email/reset-password.txt") -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger -- Note: Some functionality previously present in the scaffolding has been -- moved to documentation in the Wiki. Following are some hopefully helpful -- links: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email -- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain -- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding mkUsername :: Text -> Text -> HandlerT App IO Text mkUsername email name = do let slug = mkSlug name mUser <- runDB $ getBy $ UniqueUsername slug return $ case mUser of Just _ -> sha1Text email Nothing -> slug navbarWidget :: Widget navbarWidget = do auth <- handlerToWidget $ maybeAuth mProfile <- case auth of Just (Entity userId _) -> do Entity _ p <- handlerToWidget $ runDB $ getBy404 $ UniqueProfile userId return $ Just p Nothing -> return Nothing currentPage <- getCurrentPage mProfile <$> getCurrentRoute $(widgetFile "widgets/navbar") data Page = HomePage | ComposeLanguagesPage | SnippetsPage | MySnippetsPage | UserSnippetsPage | AccountPage | MetaPage | None deriving Eq getCurrentPage :: Maybe Profile -> Maybe (Route App) -> Page getCurrentPage _ (Just HomeR) = HomePage getCurrentPage _ (Just ComposeLanguagesR) = ComposeLanguagesPage getCurrentPage _ (Just SnippetsR) = SnippetsPage getCurrentPage _ (Just MetaApiDocsR) = MetaPage getCurrentPage _ (Just MetaAboutR) = MetaPage getCurrentPage (Just profile) (Just (UserSnippetsR username)) | profileUsername profile == username = MySnippetsPage getCurrentPage _ (Just (UserSnippetsR _)) = UserSnippetsPage getCurrentPage _ (Just AccountProfileR) = AccountPage getCurrentPage _ (Just r) | r == AuthR loginR = AccountPage | r == AuthR registerR = AccountPage | r == AuthR setPasswordR = AccountPage | r == AuthR resetPasswordR = AccountPage | r == AuthR resetPasswordEmailSentR = AccountPage | r == AuthR resetPasswordR = AccountPage | r == AuthR userExistsR = AccountPage | r == AuthR registerSuccessR = AccountPage | r == AuthR confirmationEmailSentR = AccountPage getCurrentPage _ _ = None
vinnymac/glot-www
Foundation.hs
mit
12,452
0
18
3,068
2,512
1,265
1,247
-1
-1
{- Copyright 2012-2015 Vidar Holen This file is part of ShellCheck. http://www.vidarholen.net/contents/shellcheck ShellCheck is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ShellCheck is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} import ShellCheck.Data import ShellCheck.Checker import ShellCheck.Interface import ShellCheck.Regex import ShellCheck.Formatter.Format import qualified ShellCheck.Formatter.CheckStyle import qualified ShellCheck.Formatter.GCC import qualified ShellCheck.Formatter.JSON import qualified ShellCheck.Formatter.TTY import Control.Exception import Control.Monad import Control.Monad.Except import Data.Char import Data.Functor import Data.Either import qualified Data.Map as Map import Data.Maybe import Data.Monoid import Prelude hiding (catch) import System.Console.GetOpt import System.Directory import System.Environment import System.Exit import System.IO data Flag = Flag String String data Status = NoProblems | SomeProblems | SupportFailure | SyntaxFailure | RuntimeException deriving (Ord, Eq, Show) instance Monoid Status where mempty = NoProblems mappend = max data Options = Options { checkSpec :: CheckSpec, externalSources :: Bool, formatterOptions :: FormatterOptions } defaultOptions = Options { checkSpec = emptyCheckSpec, externalSources = False, formatterOptions = FormatterOptions { foColorOption = ColorAuto } } usageHeader = "Usage: shellcheck [OPTIONS...] FILES..." options = [ Option "e" ["exclude"] (ReqArg (Flag "exclude") "CODE1,CODE2..") "exclude types of warnings", Option "f" ["format"] (ReqArg (Flag "format") "FORMAT") "output format", Option "C" ["color"] (OptArg (maybe (Flag "color" "always") (Flag "color")) "WHEN") "Use color (auto, always, never)", Option "s" ["shell"] (ReqArg (Flag "shell") "SHELLNAME") "Specify dialect (sh,bash,dash,ksh)", Option "x" ["external-sources"] (NoArg $ Flag "externals" "true") "Allow 'source' outside of FILES.", Option "V" ["version"] (NoArg $ Flag "version" "true") "Print version information" ] printErr = lift . hPutStrLn stderr parseArguments :: [String] -> ExceptT Status IO ([Flag], [FilePath]) parseArguments argv = case getOpt Permute options argv of (opts, files, []) -> return (opts, files) (_, _, errors) -> do printErr $ concat errors ++ "\n" ++ usageInfo usageHeader options throwError SyntaxFailure formats :: FormatterOptions -> Map.Map String (IO Formatter) formats options = Map.fromList [ ("checkstyle", ShellCheck.Formatter.CheckStyle.format), ("gcc", ShellCheck.Formatter.GCC.format), ("json", ShellCheck.Formatter.JSON.format), ("tty", ShellCheck.Formatter.TTY.format options) ] getOption [] _ = Nothing getOption (Flag var val:_) name | name == var = return val getOption (_:rest) flag = getOption rest flag getOptions options name = map (\(Flag _ val) -> val) . filter (\(Flag var _) -> var == name) $ options split char str = split' str [] where split' (a:rest) element = if a == char then reverse element : split' rest [] else split' rest (a:element) split' [] element = [reverse element] getExclusions options = let elements = concatMap (split ',') $ getOptions options "exclude" clean = dropWhile (not . isDigit) in map (Prelude.read . clean) elements :: [Int] toStatus = liftM (either id id) . runExceptT getEnvArgs = do opts <- getEnv "SHELLCHECK_OPTS" `catch` cantWaitForLookupEnv return . filter (not . null) $ opts `splitOn` mkRegex " +" where cantWaitForLookupEnv :: IOException -> IO String cantWaitForLookupEnv = const $ return "" main = do params <- getArgs envOpts <- getEnvArgs let args = envOpts ++ params status <- toStatus $ do (flags, files) <- parseArguments args process flags files exitWith $ statusToCode status statusToCode status = case status of NoProblems -> ExitSuccess SomeProblems -> ExitFailure 1 SyntaxFailure -> ExitFailure 3 SupportFailure -> ExitFailure 4 RuntimeException -> ExitFailure 2 process :: [Flag] -> [FilePath] -> ExceptT Status IO Status process flags files = do options <- foldM (flip parseOption) defaultOptions flags verifyFiles files let format = fromMaybe "tty" $ getOption flags "format" let formatters = formats $ formatterOptions options formatter <- case Map.lookup format formatters of Nothing -> do printErr $ "Unknown format " ++ format printErr "Supported formats:" mapM_ (printErr . write) $ Map.keys formatters throwError SupportFailure where write s = " " ++ s Just f -> ExceptT $ fmap Right f sys <- lift $ ioInterface options files lift $ runFormatter sys formatter options files runFormatter :: SystemInterface IO -> Formatter -> Options -> [FilePath] -> IO Status runFormatter sys format options files = do header format result <- foldM f NoProblems files footer format return result where f :: Status -> FilePath -> IO Status f status file = do newStatus <- process file `catch` handler file return $ status `mappend` newStatus handler :: FilePath -> IOException -> IO Status handler file e = do onFailure format file (show e) return RuntimeException process :: FilePath -> IO Status process filename = do contents <- inputFile filename let checkspec = (checkSpec options) { csFilename = filename, csScript = contents } result <- checkScript sys checkspec onResult format result contents return $ if null (crComments result) then NoProblems else SomeProblems parseColorOption colorOption = case colorOption of "auto" -> ColorAuto "always" -> ColorAlways "never" -> ColorNever _ -> error $ "Bad value for --color `" ++ colorOption ++ "'" parseOption flag options = case flag of Flag "shell" str -> fromMaybe (die $ "Unknown shell: " ++ str) $ do shell <- shellForExecutable str return $ return options { checkSpec = (checkSpec options) { csShellTypeOverride = Just shell } } Flag "exclude" str -> do new <- mapM parseNum $ split ',' str let old = csExcludedWarnings . checkSpec $ options return options { checkSpec = (checkSpec options) { csExcludedWarnings = new ++ old } } Flag "version" _ -> do liftIO printVersion throwError NoProblems Flag "externals" _ -> return options { externalSources = True } Flag "color" color -> return options { formatterOptions = (formatterOptions options) { foColorOption = parseColorOption color } } _ -> return options where die s = do printErr s throwError SupportFailure parseNum ('S':'C':str) = parseNum str parseNum num = do unless (all isDigit num) $ do printErr $ "Bad exclusion: " ++ num throwError SyntaxFailure return (Prelude.read num :: Integer) ioInterface options files = do inputs <- mapM normalize files return SystemInterface { siReadFile = get inputs } where get inputs file = do ok <- allowable inputs file if ok then (Right <$> inputFile file) `catch` handler else return $ Left (file ++ " was not specified as input (see shellcheck -x).") where handler :: IOException -> IO (Either ErrorMessage String) handler ex = return . Left $ show ex allowable inputs x = if externalSources options then return True else do path <- normalize x return $ path `elem` inputs normalize x = canonicalizePath x `catch` fallback x where fallback :: FilePath -> IOException -> IO FilePath fallback path _ = return path inputFile file = do contents <- if file == "-" then getContents else readFile file seq (length contents) $ return contents verifyFiles files = when (null files) $ do printErr "No files specified.\n" printErr $ usageInfo usageHeader options throwError SyntaxFailure printVersion = do putStrLn "ShellCheck - shell script analysis tool" putStrLn $ "version: " ++ shellcheckVersion putStrLn "license: GNU General Public License, version 3" putStrLn "website: http://www.shellcheck.net"
coolhacks/scripts-hacks
examples/shellcheck-master/shellcheck.hs
mit
9,650
0
17
2,812
2,506
1,257
1,249
232
7
module Foundation where import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Yesod.Default.Util (addStaticContentExternal) import Yesod.Core.Types (Logger) import qualified Yesod.Core.Unsafe as Unsafe import Model.User import Yesod.Auth.Dummy import Yesod.Auth.GoogleEmail2 hiding (Token) import Yesod.Auth.OAuth2.Github -- | The foundation datatype for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { appSettings :: AppSettings , appStatic :: Static -- ^ Settings for static file serving. , appConnPool :: ConnectionPool -- ^ Database connection pool. , appHttpManager :: Manager , appLogger :: Logger , appGithubOAuthKeys :: OAuthKeys , appGoogleOAuthKeys :: OAuthKeys , appStripeKeys :: StripeKeys } instance HasHttpManager App where getHttpManager = appHttpManager -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the linked documentation for an -- explanation for this split. mkYesodData "App" $(parseRoutesFile "config/routes") -- | A convenient synonym for creating forms. type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where -- Controls the base of generated URLs. For more information on modifying, -- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot approot = ApprootMaster $ appRoot . appSettings -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = whenSSL sslOnlySessions $ Just <$> envClientSessionBackend sessionTimeout "SESSION_KEY" defaultLayout widget = do master <- getYesod mmsg <- getMessage muser <- maybeAuth route <- getCurrentRoute let isRoute r = route == Just r -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent $ do addScript $ StaticR js_highlight_js addStylesheet $ StaticR css_normalize_css addStylesheet $ StaticR css_highlight_css when (maybe False includeBootstrap route) $ addStylesheet $ StaticR css_bootstrap_css addStylesheet $ StaticR css_screen_css addStylesheetRemote $ "//fonts.googleapis.com/css?family=Lato:300,400,900" $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR -- Routes not requiring authentication. -- isAuthorized (AuthR _) _ = return Authorized -- isAuthorized FaviconR _ = return Authorized -- isAuthorized RobotsR _ = return Authorized -- -- Default to Authorized for now. -- isAuthorized _ _ = return Authorized -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger yesodMiddleware = whenSSL (sslOnlyMiddleware sessionTimeout) . defaultYesodMiddleware whenSSL :: (a -> a) -> (a -> a) whenSSL f = if (appForceSSL compileTimeAppSettings) then f else id sessionTimeout :: Int sessionTimeout = 120 embedLayout :: Widget -> Handler Html embedLayout widget = do pc <- widgetToPageContent widget withUrlRenderer $(hamletFile "templates/embed-layout-wrapper.hamlet") analytics :: App -> Maybe (Entity User) -> a -> Html analytics app muser = $(hamletFile "templates/analytics.hamlet") includeBootstrap :: Route App -> Bool includeBootstrap RootR = False includeBootstrap _ = True -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = RootR -- Where to send a user after logout logoutDest _ = RootR -- Override the above two destinations when a Referer: header is present redirectToReferer _ = True authenticate = runDB . authenticateUser -- You can add other plugins like BrowserID, email or OAuth here authPlugins m = addAuthBackDoor m [ oauth2Github (oauthKeysClientId $ appGithubOAuthKeys m) (oauthKeysClientSecret $ appGithubOAuthKeys m) , authGoogleEmail (oauthKeysClientId $ appGoogleOAuthKeys m) (oauthKeysClientSecret $ appGoogleOAuthKeys m) ] authHttpManager = getHttpManager loginHandler = lift $ do app <- getYesod murl <- runInputGet $ iopt textField "dest" mapM_ setUltDest murl defaultLayout $ do setTitle "Carnival - Login" $(widgetFile "login") addAuthBackDoor :: App -> [AuthPlugin App] -> [AuthPlugin App] addAuthBackDoor app = if appAllowDummyAuth (appSettings app) then (authDummy :) else id instance YesodAuthPersist App -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger -- Note: Some functionality previously present in the scaffolding has been -- moved to documentation in the Wiki. Following are some hopefully helpful -- links: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email -- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain -- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding getAppRoot :: Handler Text getAppRoot = fmap (appRoot . appSettings) getYesod
thoughtbot/carnival
Foundation.hs
mit
7,735
0
16
1,759
1,198
631
567
-1
-1
module Rebase.System.Console.GetOpt ( module System.Console.GetOpt ) where import System.Console.GetOpt
nikita-volkov/rebase
library/Rebase/System/Console/GetOpt.hs
mit
107
0
5
12
23
16
7
4
0
import Text.Printf import Control.Monad import Algorithms.MDP import Algorithms.MDP.CTMDP import Algorithms.MDP.ValueIteration import Algorithms.MDP.Examples.MM1 printErrors :: MDP State Action Double -> Double -> IO () printErrors mdp tol = case verifyStochastic mdp tol of Left er -> do mapM_ (putStrLn . show) (_negativeProbability er) mapM_ (putStrLn . show) (_notOneProbability er) Right _ -> return () names :: [String] names = [ "Scenario 1" , "Scenario 2" , "Scenario 3" ] scenarios :: [MDP State Action Double] scenarios = [ uniformize (mkInstance scenario1) , uniformize (mkInstance scenario2) , uniformize (mkInstance scenario3) ] costs :: [Double] costs = [ 8.475 , 21.091 , 21.091 ] gap :: (Num t) => CFBounds a b t -> t gap (CFBounds _ lb ub) = ub - lb solution :: Double -> MDP State Action Double -> CFBounds State Action Double solution tol = head . dropWhile ((> tol) . gap) . undiscountedRelativeValueIteration printSolution :: MDP State Action Double -> Double -> Double -> IO () printSolution scenario tol c = let (CFBounds _ lb ub) = solution tol scenario result = if lb <= c && c <= ub then printf " %.3f in [%.3f, %.3f]" c lb ub else printf " %.3f not in [%.3f, %.3f]" c lb ub in putStrLn result main :: IO () main = do forM_ (zip3 names scenarios costs) $ \(name, scenario, c) -> do putStrLn name printErrors scenario 1e-5 printSolution scenario 1e-3 c
prsteele/mdp
src/run-mm1.hs
mit
1,494
0
12
350
535
273
262
47
2
import qualified Data.ByteString.Lazy as L import qualified Data.ByteString as S import Data.Digest.Pure.MD4 import System.Environment import Numeric import Control.Monad import Control.Arrow main = getArgs >>= \ args -> forM_ args $ \ path -> do bs <- L.readFile path putStr path putChar '\t' S.foldl (\m w -> m >> putStr (showHex w "")) (return ()) (md4 bs) putStrLn ""
mfeyg/md4
md4.hs
mit
445
0
17
131
150
79
71
15
1
-- |Netrium is Copyright Anthony Waite, Dave Hewett, Shaun Laurens & Contributors 2009-2018, and files herein are licensed -- |under the MIT license, the text of which can be found in license.txt -- -- Module for common types and functions module Common where import Prelude hiding (and, or, min, max, abs, negate, not, read, until) import Contract import Data.List (transpose) import Data.Time import Data.Monoid import Data.Maybe -- * Common types -- | A price is modelled as an observable double type Price = Obs Double -- | A volume is modelled as an observable double type Volume = Obs Double -- | A price curve is a list of prices type PriceCurve = [Price] -- | Markets, e.g. UK Power (Electricity MWh UK), NBP Gas (Gas TH UK) data Market = Market Commodity Unit Location -- | Index, e.g. SPX type Index = Obs Double -- | Basic schedule, defined as a ist of date times type Schedule = [DateTime] -- | Advanced schedule, defined as a list of time ranges type SegmentedSchedule = [[DateTime]] -- | Amortisation table, defined as a list of amortisation rates and -- observation rates type AmortisationTable = [(Double, Double)] -- | Day count conventions, e.g. 90/360 type DayCountConvention = Double -- | Underlying assets type Underlying = Contract -- * Dates and times -- | Use the UTC format type DateTime = UTCTime -- | Midnight on a given day date :: Integer -> Int -> Int -> DateTime date year month day = UTCTime (fromGregorian year month day) 0 -- | A point in time on a given day datetime :: Integer -> Int -> Int -> Int -> Int -> DateTime datetime year month day hours minutes = UTCTime (fromGregorian year month day) (timeOfDayToTime (TimeOfDay hours minutes 0)) -- | The difference between 2 date times newtype DiffDateTime = DiffDateTime (DateTime -> DateTime) infixr 5 <> -- | Used to combine various things. -- -- For example for 'DiffDateTime' it combines date/time differences, -- e.g. @daysEarlier 3 <> atTimeOfDay 15 00@ means 3 days earlier at 3pm. (<>) :: Monoid a => a -> a -> a a <> b = mappend a b instance Monoid DiffDateTime where mempty = DiffDateTime id mappend (DiffDateTime a) (DiffDateTime b) = DiffDateTime (b . a) -- | Adjust a date time by a given date time difference adjustDateTime :: DateTime -> DiffDateTime -> DateTime adjustDateTime d (DiffDateTime adj) = adj d modifyDate adj = DiffDateTime (\(UTCTime day tod) -> UTCTime (adj day) tod) modifyTime adj = DiffDateTime (\(UTCTime day tod) -> UTCTime day (adj tod)) -- | Return a positive time difference of a given number of days daysLater :: Int -> DiffDateTime daysLater n = modifyDate (addDays (fromIntegral n)) -- | Return a negative time difference of a given number of days daysEarlier :: Int -> DiffDateTime daysEarlier = daysLater . negate -- | Return a positive time difference of a given number of months monthsEarlier :: Int -> DiffDateTime monthsEarlier n = modifyDate (addGregorianMonthsClip (fromIntegral n)) -- | Return a negative time difference of a given number of months monthsLater :: Int -> DiffDateTime monthsLater = monthsEarlier . negate -- | Return a negative time difference of a given number of quarters quartersLater :: Int -> DiffDateTime quartersLater n = monthsEarlier (n*3) -- | Return a positive time difference of a given number of quarters quartersEarlier :: Int -> DiffDateTime quartersEarlier = quartersEarlier . negate -- | Return a positive time difference of a given number of years yearsEarlier :: Int -> DiffDateTime yearsEarlier n = modifyDate (addGregorianYearsClip (fromIntegral n)) -- | Return a negative time difference of a given number of years yearsLater :: Int -> DiffDateTime yearsLater = yearsEarlier . negate -- | Return a time difference of a given number of seasons -- -- Not implemented yet seasons :: Int -> DiffDateTime seasons n = error "TODO: definition for seasons" -- | Return the time difference between midnight and a given time atTimeOfDay :: Int -- ^Hours -> Int -- ^Minutes -> DiffDateTime atTimeOfDay h m = modifyTime $ \_ -> timeOfDayToTime (TimeOfDay h m 0) -- | A date difference that sets the day of the month -- (offset from the begining of the month, starting with 1). onDayOfMonth :: Int -> DiffDateTime onDayOfMonth d = modifyDate $ \day -> let (y, m, _) = toGregorian day in fromGregorian y m d -- | A date difference that sets the month of the year -- (offset from the begining of the month, starting with 1). inMonth :: Int -> DiffDateTime inMonth m = modifyDate $ \day -> let (y, _, d) = toGregorian day in fromGregorian y m d -- | Define a time duration, in terms of hours, minutes and seconds. duration :: Int -- ^Hours -> Int -- ^Minutes -> Int -- ^Seconds -> Duration duration h m s = Duration ((h * 60 + m) * 60 + s) -- | Double conversion - e.g. FX, unit conversion convertDouble :: Obs Double -- ^Double to convert -> Obs Double -- ^Conversion factor -> Obs Double convertDouble toConvert factor = toConvert * factor -- * Extra combinators -- | Combine a list of contract into a contract allOf :: [Contract] -> Contract allOf [] = zero allOf xs = foldr1 and xs --anyOneOf :: [(ChoiceLabel, Contract)] -> Contract --anyOneOf -- | Choice between a contract and a zero contract (used for options) orZero :: ChoiceId -> Contract -> Contract orZero cid c = or cid c zero -- | Like 'give' but to a named third party rather than the implicit -- counterparty. -- giveTo :: PartyName -> Contract -> Contract giveTo p = party p . give -- | Acquire a sub-contract where the counterparty is a named third party -- rather than the usual implicit counterparty. -- recieveFrom :: PartyName -> Contract -> Contract recieveFrom p = party p -- * Simple contract templates -- | Basic physical leg physical :: Volume -> Market -> Contract physical vol (Market comod unit loc) = scale vol (one (Physical comod unit loc Nothing Nothing)) -- | Basic financial leg financial :: Price -> Currency -> CashFlowType -> Contract financial pr cur cft = scale pr (one (Financial cur cft Nothing)) -- | A physical leg with additional trade attributes. -- -- Example -- -- > physicalWith vol market (withDuration duration <> withPortfolio "example") -- physicalWith :: Volume -> Market -> TradeAttrs -> Contract physicalWith vol (Market comod unit loc) (TradeAttr modifyAttrs) = scale vol . one . modifyAttrs $ Physical comod unit loc Nothing Nothing -- | A physical leg with additional trade attributes. -- -- Example -- -- > financialWith vol market (withPortfolio "example") -- financialWith :: Price -> Currency -> CashFlowType -> TradeAttrs -> Contract financialWith pr cur cft (TradeAttr modifyAttrs) = scale pr . one . modifyAttrs $ Financial cur cft Nothing -- | Additional optional attributes of a trade. -- See 'physicalWith' and 'financialWith'. -- newtype TradeAttrs = TradeAttr (Tradeable -> Tradeable) instance Monoid TradeAttrs where mempty = TradeAttr id mappend (TradeAttr a) (TradeAttr b) = TradeAttr (b . a) withPortfolio :: String -> TradeAttrs withPortfolio portfolio = TradeAttr setPortfolio where setPortfolio (Physical comod unit loc dur _) = Physical comod unit loc dur (Just (Portfolio portfolio)) setPortfolio (Financial cur cft _) = Financial cur cft (Just (Portfolio portfolio)) withDuration :: Duration -> TradeAttrs withDuration duration = TradeAttr setDuration where setDuration (Physical comod unit loc _ portfolio) = Physical comod unit loc (Just duration) portfolio setDuration (Financial {}) = error "withDuration only applies to physical trades" -- | A physical leg with a duration physicalWithDuration :: Volume -> Market -> Duration -> Contract physicalWithDuration vol (Market comod unit loc) dur = scale vol (one (Physical comod unit loc (Just dur) Nothing)) {-# DEPRECATED physicalWithDuration "Use physicalWith vol market (withDuration d)" #-} {- TODO: not used, will it ever be used or can we delete it? -- A physical contract with a delivery/settlement schedule physicalWithSchedule :: Volume -> Market -> Maybe Schedule -> Maybe Duration -> Contract physicalWithSchedule vol m sch dur = if (isNothing sch) then (physicalWithDuration vol m dur) else (allOf [when (at t) $ (physicalWithDuration vol m dur) | t <- (fromJust sch)]) -} {- TODO: not used, will it ever be used or can we delete it? -- A financial contract with a delivery/settlement schedule financialWithSchedule :: Price -> Currency -> CashFlowType -> Maybe Schedule -> Contract financialWithSchedule pr cur cft sch = if (isNothing sch) then (financial pr cur cft) else (allOf [when (at t) $ (financial pr cur cft) | t <- (fromJust sch)]) -} -- | A fixed price: transform a double into an observable fixedPrice :: Double -> Price fixedPrice pr = konst pr -- | A floating price floatingPrice :: Obs Double -> Price floatingPrice pr = pr -- | Aquire a contract multiple times according to a schedule. -- -- For example this can be used to apply a settlement/delivery schedule. -- scheduled :: Contract -> Schedule -> Contract scheduled c sch = allOf [ when (at t) $ c | t <- sch ] scheduledContract :: Contract -> Schedule -> Contract scheduledContract = scheduled {-# DEPRECATED scheduledContract "Use simply 'scheduled' instead." #-} -- * More complex trades -- | A zero coupon bond: delivery of a notional amount at a given time zcb :: DateTime -- ^Delivery date time -> Price -- ^Notional amount -> Currency -- ^Payment currency -> CashFlowType -- ^Cashflow type -> Contract zcb t pr cur cft = when (at t) (financial pr cur cft) -- More 'advanced' bonds -- | Chooser Range -- -- The note pays a coupon based on the number of days that e.g. 6-month LIBOR -- sits within an e.g. [80bps] range. -- The range is chosen by the buyer at the beginning of each coupon period. chooserLeg :: Int -- ^Range for observation period -> Int -- ^Index strike for observation period -> Time -- ^Coupon settlement date -> Schedule -- ^Dates for observation period -> Currency -- ^Payment currency -> Index -- ^Coupon rate -> CashFlowType -- ^Cashflow type -> Contract chooserLeg range strike setD sch cur cRate cft = foldr daily settlementDate sch (konst 0) where daily (day) next daysWithinRange = when (at day) $ letin "daysWithinRange" (daysWithinRange %+ indexInRange strike range) (\daysWithinRange -> next daysWithinRange) settlementDate couponAmount = when (at setD) $ financial paymentDue cur cft where -- bit of a cheat here. should be a count of actual business days, not total -- number of days paymentDue = cRate %* var "daysWithinRange" %/ konst (fromIntegral(length sch)) -- If the coupon rate is within strike +/- range then increase days within -- range otherwise don't increase days within range indexInRange strike range = ifthen (cRate %<= konst (fromIntegral(strike + range)) %&& cRate %> konst (fromIntegral(strike - range))) (konst 1) (konst 0) -- | A chooser note has a set of 'chooserLeg' chooserNote :: [Contract] -> Contract chooserNote c = allOf c -- | Forward: agreement to buy or sell an asset at a pre-agreed future point forward :: FeeCalc -- ^Fees -> Market -- ^Market, e.g. NBP Gas -> Volume -- ^Notional volume -> Price -- ^Price -> Currency -- ^Payment currency -> CashFlowType -- ^Cashflow type -> Schedule -- ^Schedule for physical settlement -> Schedule -- ^Schedule for financial settlement -> Contract forward fee market vol pr cur cft pSch fSch = give (calcFee fee vol pr cur fSch) `and` (scheduled (physical vol market) pSch) `and` (scheduled (give (financial (vol * pr) cur cft)) fSch) -- | Commodity swing: a contract guaranteeing one of two parties periodic -- delivery of a certain amount of commodity (the nominated amount) -- on certain dates in the future, within a given delivery period, at a -- stipulated constant price (the strike price). -- -- The party can also change ("swing") the amount delivered from the nominated -- amount to a new amount on a short notice, for a limited number of times commoditySwing :: FeeCalc -- ^Fees -> Market -- ^Market, e.g. NBP Gas -> Price -- ^Price -> Currency -- ^Payment currency -> CashFlowType -- ^Cashflow type -> (Volume, Volume, Volume) -- ^(low, normal, high) delivery volumes -> Int -- ^Number of exercise times -> DiffDateTime -- ^How far the option is in advance -> SegmentedSchedule -- ^Delivery schedule -> Contract commoditySwing fee market pr cur cft (lowVol,normalVol, highVol) exerciseCount optionDiffTime sched = allOf [ give (calcFee fee normalVol pr cur sched) , letin "count" (konst (fromIntegral exerciseCount)) $ \count0 -> foldr leg (\_ -> zero) sched count0 ] where leg deliverySegment remainder count = when (at optionTime) $ cond (count %<= 0) normal (or "normal" normal (or "low-high" low high)) where optionTime = firstDeliveryTime `adjustDateTime` optionDiffTime firstDeliveryTime = head deliverySegment normal = and (delivery deliverySegment normalVol) (remainder count) low = and (delivery deliverySegment lowVol) (letin "count" (count - 1) (\count' -> remainder count')) high = and (delivery deliverySegment highVol) (letin "count" (count - 1) (\count' -> remainder count')) delivery sch vol = scheduledContract (and (physical vol market) (give (financial (vol * pr) cur cft))) sch -- * Trade metadata -- | Counterparty newtype CounterParty = CounterParty String deriving (Show, Eq) -- | Trader newtype Trader = Trader String deriving (Show, Eq) -- | Book newtype Book = Book String deriving (Show, Eq) -- * Types for margining, fixing, netting, settlement -- | Margining schedule type MarginingSchedule = Schedule -- | Fixing schedule type FixingSchedule = Schedule -- | Settlement schedule type SettlementSchedule = Schedule -- | Settlement volume variance (for actuals) type SettlementVolumeVariance = Obs Double -- | Settlement agreement data SettlementAgreement = SettlementAgreement Market SettlementSchedule -- | Market netting agreement data MarketNettingAgreement = MarketNettingAgreement CounterParty Market -- | Cross-market netting agreement data CrossMarketNettingAgreement = CrossMarketNettingAgreement CounterParty -- * Fee calculations -- | Type for fee calculations newtype FeeCalc = FeeCalc (Volume -> Price -> Currency -> Int -> Contract) instance Monoid FeeCalc where mempty = zeroFee mappend = andFee -- | Function to calculate fees calcFee :: FeeCalc -- ^Function to apply to calculate the fees -> Volume -- ^Contract notional volume -> Price -- ^Contract price -> Currency -- ^Contract currency -> [a] -- ^The schedule -> Contract calcFee (FeeCalc fc) vol pr cur sch = fc vol pr cur (length sch) -- | No fee zeroFee :: FeeCalc zeroFee = FeeCalc $ \_ _ _ _ -> zero -- | Fees for initial margin initialMarginFee :: FeeCalc initialMarginFee = FeeCalc $ \vol pr cur numDeliveries -> financial (vol * pr * konst (fromIntegral (numDeliveries))) cur cft where cft = CashFlowType "initialMargin" -- | Basic calculated fees computedFee :: CashFlowType -> Price -> FeeCalc computedFee cft pr = FeeCalc $ \_ _ cur _ -> financial pr cur cft -- | Fixed fees fixedFee :: CashFlowType -> Double -> FeeCalc fixedFee cft = computedFee cft . konst -- | Exchange fees exchangeFee :: Price -> FeeCalc exchangeFee = computedFee cft where cft = CashFlowType "exchange" -- | Append 2 fee calculations andFee :: FeeCalc -> FeeCalc -> FeeCalc andFee (FeeCalc fc1) (FeeCalc fc2) = FeeCalc $ \vol pr cur sch -> fc1 vol pr cur sch `and` fc2 vol pr cur sch -- Not used yet -- | Traded date type TradedDate = Obs DateTime -- | Contract direction (give or take) data Direction = DGive | DTake -- * Utilities -- | Function to determine amortisation rate from an amortisation table and an -- observable rate getAmRate :: Obs Double -> AmortisationTable -> Obs Double getAmRate rate [] = konst 0 getAmRate rate ((x1,x2):xs) = ifthen (rate %< konst x1) (konst x2) $ getAmRate rate xs -- * List helper functions -- | Extract n last elements from a list lastn :: Int -> [a] -> [a] lastn n l = reverse (take n (reverse l)) -- * Basic math functions -- | Square a double square :: Num n => n -> n square x = x * x
netrium/Netrium
share/Common.hs
mit
17,551
0
16
4,354
3,473
1,883
1,590
252
2
module Accumulate where accumulate :: (a -> a1) -> [a] -> [a1] accumulate _ [] = [] accumulate f (x:xs) = f x : accumulate f xs
tonyfischetti/exercism
haskell/accumulate/Accumulate.hs
mit
129
0
7
28
73
39
34
4
1
{-# LANGUAGE JavaScriptFFI #-} -- | FIXME: doc module GHCJS.Electron.WebFrame where
taktoa/ghcjs-electron
src/GHCJS/Electron/WebFrame.hs
mit
85
0
3
12
9
7
2
2
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UnicodeSyntax #-} import Data.ByteString (readFile) import Data.List (intercalate) import Data.Map.Strict hiding (map) import qualified Data.Set as S import Debug.Trace import qualified Lambdas as Λ import Prelude hiding (lookup, readFile) import TT5.Unification hiding (main, myshow) import Utils data Type = AtomType String | Type :→: Type deriving (Eq, Ord) arrow = Function "" instance Show Type where show (AtomType s) = s show (t :→: t') = "(" ++ (show t) ++ ")" ++ "→" ++ show t' instance Show (Term Type) where show (Function s xs) = s ++ "(" ++ intercalate "," (show <$> xs) ++ ")" show (Var s) = show s nameType :: Int → Type nameType n = AtomType $ "t" ++ (show n) getType :: (Show (Term Type)) ⇒ Λ.Lambda → Int → Map String Type → [Equation Type] → (Type, Int, Map String Type, [Equation Type]) getType (Λ.Var x) n m eqs = (newType, newN, insert x newType m, eqs) where (newType, newN) = case lookup x m of Nothing → (nameType n, n + 1) Just s → (s, n) getType (Λ.Lambda x λ) n m eqs = (newType, rn + 1, delete x rmap, newEq:reqs) where (ltype, ln, lmap, leqs) = getType (Λ.Var x) n (delete x m) eqs (rtype, rn, rmap, reqs) = getType λ ln lmap leqs newType = nameType rn -- ltype :→: rtype newEq = (Var newType, arrow [Var ltype, Var rtype]) getType (Λ.Application lhs rhs) n m eqs = (newType, ln, rmap, newEq:leqs) where newType = nameType n (rtype, rn, rmap, reqs) = getType rhs (n + 1) m eqs (ltype, ln, lmap, leqs) = getType lhs rn rmap reqs newEq = (Var ltype, arrow [Var rtype, Var newType]) myshow :: Term Type → String myshow (Function _ [lhs, rhs]) = "(" ++ (myshow lhs) ++ "->" ++ myshow rhs ++ ")" myshow (Var (AtomType t)) = t main :: (Show (Term Type)) ⇒ IO () main = do input ← readFile "task6.in" let λ = parseBS Λ.parseLambda input print λ let (atype, n, m, eqs) = getType λ 0 empty [] print eqs print ("---------------------------------") return () let unified = unify S.empty eqs print eqs print unified let ans = case unified of Nothing → "Can not infer type" -- Just a | trace (show (n-1)) False -> undefined Just a → myshow $ a ! (AtomType $ "t" ++ (show 0)) writeFile "task6.out" $ ans ++ "\n"
loskutov/logic-hw
TT6/Main.hs
mit
2,516
5
17
672
1,050
551
499
56
2
import System.Environment(getArgs) placeQueens :: [Integer] -> [Integer] -> [[Integer]] placeQueens placed [] = [placed] placeQueens placed remaining = let f placed choice remaining | illegalChoice placed choice = [] | otherwise = (placeQueens (choice:placed) remaining) in foldl1 (++) $ zipWith (f placed) remaining (without remaining) -- Returns a list of lists without one of the elements without xs = map (\el -> filter (/= el) xs) xs properPlaceQueens list = map (take 4) (placeQueens [] list) illegalChoice placed choice = (any (==choice) $ zipWith (+) placed [1..]) || (any (==choice) $ zipWith (+) placed [-1,-2..]) kQueens :: Integer -> [[Integer]] kQueens n = placeQueens [] [1..n] -- Finds the number of solutions for each board solutions = map (length . kQueens) [1..] main = do args <- getArgs putStrLn $ show $ kQueens (read $ head args)
teodorlu/ballmer
queens.hs
gpl-2.0
877
6
13
162
375
196
179
19
1
{-# LANGUAGE OverloadedStrings #-} module Process (readProcess, readProcess', readProcess'') where ------------------------------------------------------------------------------------ import qualified Control.Exception.Lifted as E import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Text (Text, unpack) import Data.Typeable (Typeable) import System.Exit (ExitCode (..)) import qualified System.Process.Text as SP ------------------------------------------------------------------------------------ data ReadProcessFailed = ReadProcessFailed String deriving (Typeable) instance E.Exception ReadProcessFailed instance Show ReadProcessFailed where show (ReadProcessFailed msgstr) = "ReadProcessFailed: " ++ msgstr readProcess :: MonadIO m => FilePath -> [Text] -> m Text readProcess fp params = readProcess' fp params "" readProcess' :: MonadIO m => FilePath -> [Text] -> Text -> m Text readProcess' fp params input = do (exitcode, stdout, stderr) <- readProcess'' fp params input case exitcode of ExitSuccess -> return stdout _ -> E.throw $ ReadProcessFailed $ (show (exitcode, stderr)) readProcess'' :: MonadIO m => FilePath -> [Text] -> Text -> m (ExitCode, Text, Text) readProcess'' fp params input = do liftIO $ SP.readProcessWithExitCode fp (map unpack params) input
da-x/autofix-ghc
lib/Process.hs
gpl-2.0
1,399
0
13
271
366
200
166
23
2
{-# OPTIONS_GHC -Wall -fwarn-tabs -Werror #-} ------------------------------------------------------------------------------- -- | -- Module : Window.GLUT -- Copyright : Copyright (c) 2014 Michael R. Shannon -- License : GPLv2 or Later -- Maintainer : mrshannon.aerospace@gmail.com -- Stability : unstable -- Portability : portable -- -- Window module (GLUT adapter). ------------------------------------------------------------------------------- module Window.GLUT ( reshape ) where import Data.IORef import qualified Graphics.UI.GLUT as GLUT import qualified Graphics.Rendering.OpenGL as GL import Graphics.Rendering.OpenGL(($=)) import Window.Types -- type ReshapeCallback = Size -> IO () reshape :: IORef Window -> GLUT.ReshapeCallback reshape winRef s@(GLUT.Size w h) = do GL.viewport $= (GL.Position 0 0, s) modifyIORef winRef (\win -> win { width = fromIntegral w , height = fromIntegral h }) GLUT.postRedisplay Nothing
mrshannon/trees
src/Window/GLUT.hs
gpl-2.0
1,017
0
12
203
168
101
67
14
1
module Command.Monad ( MonadCommand(..) , CSTM , runCSTM , throwSTM , CM , runCM , log , setPaused , setSpeed , atomically , newStdGen , module Control.Concurrent.STM , module Control.Monad.STM.Class , module System.Random ) where import Control.Concurrent.STM hiding (atomically, throwSTM) import qualified Control.Concurrent.STM as STM import Control.Exception import Control.Monad.Operational import Control.Monad.STM.Class import Data.IORef import Data.Time.Clock import H.IO import H.Prelude import System.Random hiding (getStdRandom, getStdGen, setStdGen, newStdGen, randomRIO, randomIO) import qualified System.Random as R import Simulation import Types (Game()) class (Monad m) => MonadCommand m where getGame :: m Game data CommandSTMInstruction a where CSLift :: STM a -> CommandSTMInstruction a CSThrow :: (Exception e) => e -> CommandSTMInstruction a CSGetGame :: CommandSTMInstruction Game newtype CSTM a = CSTM { unCSTM :: Program CommandSTMInstruction a } deriving (Functor, Applicative, Monad) instance MonadCommand CSTM where getGame = CSTM $ singleton CSGetGame instance MonadSTM CSTM where liftSTM = CSTM . singleton . CSLift runCSTM :: CSTM a -> Game -> STM a runCSTM m game = case view $ unCSTM m of Return x -> pure x m' :>>= k -> case m' of CSLift stm -> stm >>= continue k CSThrow e -> STM.throwSTM e >>= continue k CSGetGame -> continue k game where continue :: (a -> Program CommandSTMInstruction b) -> a -> STM b continue k b = runCSTM (CSTM $ k b) game throwSTM :: (Exception e) => e -> CSTM a throwSTM = CSTM . singleton . CSThrow data CommandInstruction a where CILog :: Text -> CommandInstruction () CISetPaused :: Bool -> CommandInstruction () CISetSpeed :: NominalDiffTime -> CommandInstruction () CIAtomically :: CSTM a -> CommandInstruction a CINewStdGen :: CommandInstruction StdGen CIGetGame :: CommandInstruction Game type CM = Program CommandInstruction instance MonadCommand CM where getGame = singleton CIGetGame runCM :: CM a -> MasterHandle -> Game -> IO a runCM m mh game = case view m of Return x -> pure x m' :>>= k -> case m' of CILog xs -> putStrLn xs >>= continue k CISetPaused paused -> writeIORef (mhPaused mh) paused >>= continue k CISetSpeed speed -> writeIORef (mhSpeed mh) speed >>= continue k CIAtomically cstm -> STM.atomically (runCSTM cstm game) >>= continue k CINewStdGen -> R.newStdGen >>= continue k CIGetGame -> continue k game where continue :: (a -> Program CommandInstruction b) -> a -> IO b continue k b = runCM (k b) mh game log :: Text -> CM () log = singleton . CILog setPaused :: Bool -> CM () setPaused = singleton . CISetPaused setSpeed :: NominalDiffTime -> CM () setSpeed = singleton . CISetSpeed atomically :: CSTM a -> CM a atomically = singleton . CIAtomically newStdGen :: CM StdGen newStdGen = singleton CINewStdGen
ktvoelker/airline
src/Command/Monad.hs
gpl-3.0
2,959
0
14
609
991
520
471
-1
-1
-- Hshuf, a haskell implementation of GNU shuf. module Main where import System.Environment import System.Console.Terminfo.Base --import Data.List import GnUtils main :: IO () main = do term <- setupTermFromEnv args <- getArgs let shuf = ProgramData { appName = "Hshuf" , appHelp = (shufAppHelpPre,shufAppHelpPost) , appVersion = shufAppVersion , argumentStrings = args , configuration = defaultConfig , longParser = shufLongParser , longOptionParser = shufLongOptionParser , shortParser = shufShortParser } let parsedShuf = parseArguments shuf args output <- showOutput parsedShuf runTermOutput term (termText (output)) if doHelp parsedShuf then runTermOutput term (termText (getHelp parsedShuf)) else return () if doVersion parsedShuf then runTermOutput term (termText (getVersion parsedShuf)) else return () runTermOutput term (termText ("\n"++(show parsedShuf)++"\n")) --debug opts return () showOutput :: ProgramData -> IO String showOutput _opts = return "<<>>\n" -- <do-stuff-Here> defaultShuf :: ShufOptions defaultShuf = ShufOptions data ShufOptions = ShufOptions { } deriving (Show, Eq) defaultBools :: [ProgramOption Bool] defaultBools = zeroOption : repeatOption : echoOption : defaultOptions dafaultStrings :: [ProgramOption String] dafaultStrings = [sourceOption, outputOption] defaultIntegers :: [ProgramOption Integer] defaultIntegers = [countOption, rangeOption] defaultConfig :: ConfigurationData defaultConfig = ConfigurationData defaultBools dafaultStrings defaultIntegers [] shufAppHelpPre :: String shufAppHelpPre = "Usage: /home/bminerds/x/coreutils/src/shuf [OPTION]... [FILE]" ++" or: /home/bminerds/x/coreutils/src/shuf -e [OPTION]... [ARG]..." ++" or: /home/bminerds/x/coreutils/src/shuf -i LO-HI [OPTION]..." ++ "Write a random permutation of the input lines to standard output." ++ "Mandatory arguments to long options are mandatory for short options too." shufAppHelpPost :: String shufAppHelpPost = "With no FILE, or when FILE is -, read standard input." ++"GNU coreutils online help: <http://www.gnu.org/software/coreutils/>" ++"Full documentation at: <http://www.gnu.org/software/coreutils/shuf>" ++"or available locally via: info '(coreutils) shuf invocation'\n" shufAppVersion :: String shufAppVersion = "shuffle\n version\n" --helpText = [" -e, --echo treat each ARG as an input line" -- , "-i, --input-range=LO-HI treat each number LO through HI as an input line" -- , " -n, --head-count=COUNT output at most COUNT lines" -- , " -o, --output=FILE write result to FILE instead of standard output" -- , " --random-source=FILE get random bytes from FILE" -- , " -r, --repeat output lines can be repeated" -- , " -z, --zero-terminated line delimiter is NUL, not newline" -- , " --help display this help and exit" -- , " --version output version information and exit" shufLongParser :: ProgramData -> String -> ProgramData shufLongParser dat "zero-terminated" = addOption dat True zeroOption shufLongParser dat "repeat" = addOption dat True repeatOption --shufLongParser dat "random-source" = addOption dat "FILE" sourceOption -- =FILE --shufLongParser dat "output" = addOption dat True repeatOption -- =FILE --shufLongParser dat "head-count" = addOption dat True repeatOption -- =COUNT --shufLongParser dat "input-range" = addOption dat True repeatOption -- =LO-HI shufLongParser dat "echo" = addOption dat True echoOption shufLongParser dat _ = dat shufLongOptionParser :: ProgramData -> String -> String -> ProgramData shufLongOptionParser dat "random-source" tgt = addOption dat tgt sourceOption -- =FILE shufLongOptionParser dat _ _ = dat shufShortParser :: ProgramData -> String -> ProgramData shufShortParser cfg [] = cfg shufShortParser dat "z" = addOption dat True zeroOption shufShortParser dat "r" = addOption dat True repeatOption shufShortParser dat "e" = addOption dat True echoOption shufShortParser cfg _ = cfg --shufShortParser cfg (flag:others) = -- where thiseffect = head (filter () ) --shufShortParser = (\x y -> x) -- z r o=FILE n=COUNT i=LO-HI e zeroOption :: ProgramOption Bool zeroOption = ProgramOption "zero-terminated text" ["z"] ["zero-terminated"] [] (\x->x{boolData = setOption (boolData x) "z" True}) False repeatOption :: ProgramOption Bool repeatOption = ProgramOption "repeat text" ["r"] ["repeat"] [] (\x->x{boolData = setOption (boolData x) "r" True}) False sourceOption :: ProgramOption String sourceOption = ProgramOption "random-source text" [] ["random-source"] [] (\x->x{stringData = setOption (stringData x) "random-source" "<IN>"}) "" outputOption :: ProgramOption String outputOption = ProgramOption "output text" ["o"] ["output"] [] (\x->x{stringData = setOption (stringData x) "o" "<INPUT>"}) "" countOption :: ProgramOption Integer countOption = ProgramOption "head-count text" ["n"] ["head-count"] [] (\x->x{integerData = setOption (integerData x) "n" 666}) 0 rangeOption :: ProgramOption Integer rangeOption = ProgramOption "input-range text" ["i"] ["input-range"] [] (\x->x{integerData = setOption (integerData x) "i" 666}) 0 echoOption :: ProgramOption Bool echoOption = ProgramOption "echo text" ["e"] ["echo"] [] (\x->x{boolData = setOption (boolData x) "e" True}) False
PuZZleDucK/Hls
Hshuf.hs
gpl-3.0
5,486
1
14
1,002
1,139
611
528
120
3
{-# LANGUAGE DeriveAnyClass , UndecidableInstances , FlexibleInstances , MultiParamTypeClasses #-} module Text.Shaun.Sweeper ( SweeperT , Sweeper , to , getTo , at , getAt , back , get , set , withSweeperT , withSweeper , path , getPath , top , peek , modify ) where import Text.Shaun.Types import Control.Monad.Identity import Data.List.Split (splitOn) import Data.Maybe import Data.Map as Map hiding (lookup, foldl, map) import Data.Array as Arr import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Catch import Control.Monad.Except data SwCrumb = FromObject String ShaunValue | FromList Int ShaunValue deriving (Eq) type SwPath = (ShaunValue, [SwCrumb]) data SweeperT m a = SweeperT { runSweeperT :: SwPath -> m (a, SwPath) } type Sweeper = SweeperT (Either ShaunException) instance (MonadThrow m) => MonadThrow (SweeperT m) where throwM = lift . throwM instance (MonadCatch m) => MonadCatch (SweeperT m) where catch m h = SweeperT $ \sv -> (runSweeperT m sv) `catch` (\e -> runSweeperT (h e) sv) instance MonadError e m => MonadError e (SweeperT m) where throwError = lift . throwError catchError m h = SweeperT $ \sv -> (runSweeperT m sv) `catchError` (\e -> runSweeperT (h e) sv) instance Functor m => Functor (SweeperT m) where fmap f (SweeperT { runSweeperT = s }) = SweeperT (\sv0 -> fmap (\(a,sv) -> (f a,sv)) $ s sv0) instance (Functor m, Monad m) => Applicative (SweeperT m) where pure a = SweeperT (\sv0 -> return (a, sv0)) (SweeperT s0) <*> (SweeperT s1) = SweeperT $ \sv0 -> do { (f, sv1) <- s0 sv0 ; (x, sv2) <- s1 sv1 ; return (f x, sv2) } instance Monad m => Monad (SweeperT m) where return v = SweeperT (\sv -> return (v, sv)) (>>=) (SweeperT f) g = SweeperT $ \sv0 -> do { (a, sv1) <- f sv0 ; runSweeperT (g a) sv1} instance MonadTrans SweeperT where lift m = SweeperT $ \sv -> do ret <- m return (ret, sv) instance MonadIO m => MonadIO (SweeperT m) where liftIO = lift . liftIO getSwObject :: (MonadThrow m) => String -> SwPath -> m ShaunValue getSwObject s (o, _) = getObject s o getObject s (SObject o) = case lookup s o of Nothing -> throwM AttributeNotFound Just r -> return r getObject s _ = throwM NotAnObject swat :: (MonadThrow m) => Int -> SwPath -> m ShaunValue swat i ((SList l), _) = if length l > i then return (l !! i) else throwM OutOfRange swat _ _ = throwM NotAList -- | Go to an @SObject@'s attribute to :: (MonadThrow m) => String -> SweeperT m () to s = SweeperT $ \(sv0, crumb) -> do sv1 <- getSwObject s (sv0, crumb) return ((), (sv1, (FromObject s sv0):crumb)) -- | Go at a @SList@'s index at :: (MonadThrow m) => Int -> SweeperT m () at i = SweeperT $ \(sv0, crumb) -> do sv1 <- swat i (sv0, crumb) return ((), (sv1, (FromList i sv0):crumb)) -- | Perform a @to@ action and returns the current @ShaunValue@ -- @getTo attr = to attr >> get@ getTo :: (MonadThrow m) => String -> SweeperT m ShaunValue getTo s = to s >> get -- | Perform an @at@ action and returns the current @ShaunValue@ -- @getAt i = at i >> get@ getAt :: (MonadThrow m) => Int -> SweeperT m ShaunValue getAt i = at i >> get -- | Walk through a path composed of the successive objects' attributes names or -- list indices separated by @':'@. (@path "attr1:[2]:attr2"@) -- The resulting path action is just a composition of @to@ and @at@. path :: (MonadThrow m) => String -> SweeperT m () path s = foldl (>>) (return ()) $ map act (splitOn ":" s) where act ('[':rest) = (at . read . init) rest act s = to s -- | Perform an @path@ action and returns the current @ShaunValue@ -- @getPath p = path p >> get@ getPath :: (MonadThrow m) => String -> SweeperT m ShaunValue getPath p = path p >> get -- | Moves backward in the tree back :: (Monad m) => SweeperT m () back = SweeperT $ \(sv0, crumb) -> case crumb of (FromObject s b : crumb') -> return ((), (setObjectAttribute s sv0 b, crumb')) (FromList i b : crumb') -> return ((), (setListIndex i sv0 b, crumb')) _ -> return ((), (sv0, [])) setObjectAttribute str val (SObject m) = SObject $ Map.toList $ Map.insert str val $ Map.fromList m setListIndex id val (SList l) = SList $ Arr.elems ((Arr.listArray (0, length l) l) Arr.// [(id,val)]) -- | Returns the current @ShaunValue@ the sweeper is at. get :: (Monad m) => SweeperT m ShaunValue get = SweeperT $ \(sv0, crumb) -> return (sv0, (sv0, crumb)) -- | Changes the current @ShaunValue@ with a new one. set :: (Monad m) => ShaunValue -> SweeperT m () set sv = SweeperT $ \(sv0, crumb) -> return ((), (sv, crumb)) -- | Runs a @SweeperT@ with any monad @m@ and returns the computed value wrapped into @m@ withSweeperT :: (Monad m) => SweeperT m a -> ShaunValue -> m a withSweeperT s v = fmap fst $ runSweeperT s (v, []) -- | Runs a @Sweeper@ and returns a computed value withSweeper :: Sweeper a -> ShaunValue -> Either ShaunException a withSweeper s v = withSweeperT s v -- | Performs a @Sweeper@ action without changing the position in the tree peek :: (Monad m) => SweeperT m a -> SweeperT m a peek sw = SweeperT $ \(sv, crumb) -> do (ret, (sv', [])) <- runSweeperT (do a <- sw; top; return a) (sv, []) return (ret, (sv', crumb)) -- | Gets to the root @ShaunValue@ top :: (Monad m) => SweeperT m () top = do cr <- getCrumbs case cr of [] -> return () _ -> back >> top getCrumbs :: (Monad m) => SweeperT m [SwCrumb] getCrumbs = SweeperT $ \(a, b) -> return (b, (a,b)) -- | Apply a function to the current @ShaunValue@ modify :: (Monad m) => (ShaunValue -> ShaunValue) -> SweeperT m () modify f = get >>= set . f
Shumush/SNIHs
src/Text/Shaun/Sweeper.hs
gpl-3.0
5,731
0
14
1,297
2,224
1,195
1,029
123
3
module Carbon.Backend.User where import Control.Monad import Control.Monad.IO.Class (liftIO) import qualified Data.Maybe as Maybe import Carbon.Backend.DSL import Carbon.Data import qualified Carbon.Data.Hash as Hash import qualified Carbon.Data.Salt as Salt {-| This function ensures that an admin user and Nobody exist. |-} init :: BackendDSL () init = do -- Making sure Nobody exists: GetNobody -- Making sure we've got an admin user: mAdmin <- HasUser "admin" when (Maybe.isNothing mAdmin) $ do liftIO $ putStrLn "Adding user admin:admin…" salt <- liftIO Salt.mkSalt let hash = Hash.hash salt "admin" no = error . ("Could not create admin user in Carbon.Backend.User:init:\n"++) go = const $ return () either no go =<< AddUser "admin" (hash, salt) True
runjak/carbon-adf
Carbon/Backend/User.hs
gpl-3.0
806
0
15
158
200
110
90
19
1
start = "sibling" : -- comment ["commented"]
evolutics/haskell-formatter
testsuite/resources/source/comments/indentation/inherits_indentation_of_merged_line/actual_code_between_start_and_commented/Input.hs
gpl-3.0
59
1
6
21
17
8
9
3
1
module Database.Design.Ampersand.Prototype.Installer (installerDBstruct,installerDefPop, createTablesPHP,populateTablesPHP) where import Database.Design.Ampersand import Database.Design.Ampersand.Prototype.ProtoUtil import Database.Design.Ampersand.Prototype.PHP installerDBstruct :: FSpec -> String installerDBstruct fSpec = unlines $ ["<?php" , "// Try to connect to the database" , "" , "include \"dbSettings.php\";" , "" , "$DB_name='"++addSlashes (dbName (getOpts fSpec))++"';" , "$DB_link = mysqli_connect($DB_host,$DB_user,$DB_pass);" , "// Check connection" , "if (mysqli_connect_errno()) {" , " die(\"Failed to connect to MySQL: \" . mysqli_connect_error());" , "}" , "" ]++setSqlModePHP++ [ "// Drop the database if it exists" , "$sql=\"DROP DATABASE $DB_name\";" , "mysqli_query($DB_link,$sql);" , "// Don't bother about the error if the database didn't exist..." , "" , "// Create the database" , "$sql=\"CREATE DATABASE $DB_name DEFAULT CHARACTER SET UTF8 DEFAULT COLLATE UTF8_BIN\";" , "if (!mysqli_query($DB_link,$sql)) {" , " die(\"Error creating the database: \" . mysqli_error($DB_link));" , " }" , "" , "// Connect to the freshly created database" , "$DB_link = mysqli_connect($DB_host,$DB_user,$DB_pass,$DB_name);" , "// Check connection" , "if (mysqli_connect_errno()) {" , " die(\"Failed to connect to the database: \" . mysqli_connect_error());" , " }" , "" ]++setSqlModePHP++ createTablesPHP fSpec ++ [ "mysqli_query($DB_link,'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');" , "?>" ] --installerTriggers :: FSpec -> String --installerTriggers _ = unlines $ -- [ "<?php" -- , "" -- , "" -- , "// Array for trigger queries that need to be installed" -- , "$queries = array();" -- , "" -- , "" -- ] ++ [] -- something like: map unlines [ trigger tablename query | ] -- ++ -- [ "$queries[] = \"CREATE TRIGGER etc\";" -- , "" -- , "" -- , "" -- , "" -- , "// Execute queries" -- , "foreach ($queries as $query){" -- , " print $query.\"<br/>\";" -- , " // $db->Exe($query); " -- , " // print($db->error());" -- , "" -- , "}" -- , "?>" -- ] -- where -- trigger tablename query -- = [ "// Trigger for DELETE Atom or Pair in function in Concept table" -- , "$queries['delete_"++tablename++"']" -- , " = \"CREATE TRIGGER `delete_"++tablename++"` BEFORE DELETE ON `"++tablename++"`" -- , " FOR EACH ROW" -- , " BEGIN " -- , " DELETE FROM <other table> WHERE <other table>.<column name> = OLD.<column name>; " -- , " END\";" -- ] installerDefPop :: FSpec -> String installerDefPop fSpec = unlines $ ["<?php" , "// Connect to the database" , "include \"dbSettings.php\";" , "" , "$DB_link = mysqli_connect($DB_host,$DB_user,$DB_pass,$DB_name);" , "// Check connection" , "if (mysqli_connect_errno()) {" , " die(\"Failed to connect to the database: \" . mysqli_connect_error());" , " }" , "$error=false;" ] ++setSqlModePHP++ populateTablesPHP fSpec ++ ["?>" ]
4ZP6Capstone2015/ampersand
src/Database/Design/Ampersand/Prototype/Installer.hs
gpl-3.0
3,391
0
18
940
312
204
108
58
1
module Main where import System.Environment main :: IO () main = do putStrLn "please a name: " line <- getLine putStrLn ("the name is: " ++ line)
lifengsun/haskell-exercise
scheme/01/ex-3.hs
gpl-3.0
153
0
9
34
50
25
25
7
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CodeDeploy.BatchGetApplications -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Gets information about one or more applications. -- -- <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetApplications.html> module Network.AWS.CodeDeploy.BatchGetApplications ( -- * Request BatchGetApplications -- ** Request constructor , batchGetApplications -- ** Request lenses , bgaApplicationNames -- * Response , BatchGetApplicationsResponse -- ** Response constructor , batchGetApplicationsResponse -- ** Response lenses , bgarApplicationsInfo ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CodeDeploy.Types import qualified GHC.Exts newtype BatchGetApplications = BatchGetApplications { _bgaApplicationNames :: List "applicationNames" Text } deriving (Eq, Ord, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList BatchGetApplications where type Item BatchGetApplications = Text fromList = BatchGetApplications . GHC.Exts.fromList toList = GHC.Exts.toList . _bgaApplicationNames -- | 'BatchGetApplications' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'bgaApplicationNames' @::@ ['Text'] -- batchGetApplications :: BatchGetApplications batchGetApplications = BatchGetApplications { _bgaApplicationNames = mempty } -- | A list of application names, with multiple application names separated by -- spaces. bgaApplicationNames :: Lens' BatchGetApplications [Text] bgaApplicationNames = lens _bgaApplicationNames (\s a -> s { _bgaApplicationNames = a }) . _List newtype BatchGetApplicationsResponse = BatchGetApplicationsResponse { _bgarApplicationsInfo :: List "applicationsInfo" ApplicationInfo } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList BatchGetApplicationsResponse where type Item BatchGetApplicationsResponse = ApplicationInfo fromList = BatchGetApplicationsResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _bgarApplicationsInfo -- | 'BatchGetApplicationsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'bgarApplicationsInfo' @::@ ['ApplicationInfo'] -- batchGetApplicationsResponse :: BatchGetApplicationsResponse batchGetApplicationsResponse = BatchGetApplicationsResponse { _bgarApplicationsInfo = mempty } -- | Information about the applications. bgarApplicationsInfo :: Lens' BatchGetApplicationsResponse [ApplicationInfo] bgarApplicationsInfo = lens _bgarApplicationsInfo (\s a -> s { _bgarApplicationsInfo = a }) . _List instance ToPath BatchGetApplications where toPath = const "/" instance ToQuery BatchGetApplications where toQuery = const mempty instance ToHeaders BatchGetApplications instance ToJSON BatchGetApplications where toJSON BatchGetApplications{..} = object [ "applicationNames" .= _bgaApplicationNames ] instance AWSRequest BatchGetApplications where type Sv BatchGetApplications = CodeDeploy type Rs BatchGetApplications = BatchGetApplicationsResponse request = post "BatchGetApplications" response = jsonResponse instance FromJSON BatchGetApplicationsResponse where parseJSON = withObject "BatchGetApplicationsResponse" $ \o -> BatchGetApplicationsResponse <$> o .:? "applicationsInfo" .!= mempty
dysinger/amazonka
amazonka-codedeploy/gen/Network/AWS/CodeDeploy/BatchGetApplications.hs
mpl-2.0
4,381
6
11
830
557
326
231
66
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.Directory.Schemas.Insert -- 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) -- -- Create schema. -- -- /See:/ <https://developers.google.com/admin-sdk/directory/ Admin Directory API Reference> for @directory.schemas.insert@. module Network.Google.Resource.Directory.Schemas.Insert ( -- * REST Resource SchemasInsertResource -- * Creating a Request , schemasInsert , SchemasInsert -- * Request Lenses , siPayload , siCustomerId ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.schemas.insert@ method which the -- 'SchemasInsert' request conforms to. type SchemasInsertResource = "admin" :> "directory" :> "v1" :> "customer" :> Capture "customerId" Text :> "schemas" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Schema :> Post '[JSON] Schema -- | Create schema. -- -- /See:/ 'schemasInsert' smart constructor. data SchemasInsert = SchemasInsert' { _siPayload :: !Schema , _siCustomerId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'SchemasInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'siPayload' -- -- * 'siCustomerId' schemasInsert :: Schema -- ^ 'siPayload' -> Text -- ^ 'siCustomerId' -> SchemasInsert schemasInsert pSiPayload_ pSiCustomerId_ = SchemasInsert' { _siPayload = pSiPayload_ , _siCustomerId = pSiCustomerId_ } -- | Multipart request metadata. siPayload :: Lens' SchemasInsert Schema siPayload = lens _siPayload (\ s a -> s{_siPayload = a}) -- | Immutable id of the Google Apps account siCustomerId :: Lens' SchemasInsert Text siCustomerId = lens _siCustomerId (\ s a -> s{_siCustomerId = a}) instance GoogleRequest SchemasInsert where type Rs SchemasInsert = Schema type Scopes SchemasInsert = '["https://www.googleapis.com/auth/admin.directory.userschema"] requestClient SchemasInsert'{..} = go _siCustomerId (Just AltJSON) _siPayload directoryService where go = buildClient (Proxy :: Proxy SchemasInsertResource) mempty
rueshyna/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/Schemas/Insert.hs
mpl-2.0
3,044
0
15
721
390
234
156
62
1
{- Copyright (C) 2009 Andrejs Sisojevs <andrejs.sisojevs@nextmail.ru> All rights reserved. For license and copyright information, see the file COPYRIGHT -} -------------------------------------------------------------------------- -------------------------------------------------------------------------- {-# LANGUAGE FlexibleInstances, FlexibleContexts #-} -- Without extending HelloWorld application with PCLT catalog, it would look like the code in "HelloWorld.NoPCLT.hs" file module HelloWorld where ----------------------------------------------------- -- Modules necessary for our PCLTCatalog import Prelude hiding (putStrLn) -- Prelude putStrLn doesn't work properly with utf8 import Data.ByteString.Lazy.UTF8 import qualified Data.ByteString.Lazy.UTF8.Unified as Lazy (ByteString) -- all catalog business is done using lazy ByteStrings import qualified Data.ByteString.Lazy.UTF8.Unified as B hiding (ByteString) -- since ByteStrings (and System.IO) is not very friendly to unicode symbols "utf8-string" package us used import qualified Data.Map as M import Data.Map (Map, (!)) import System.IO.UTF8 hiding (readLn) import Text.PCLT -- this module exports most important PCLT modules - there (in Text.PCLT) are some comments about exported modules import qualified Text.ConstraintedLBS as CB -- a constrainting (the constraint here is on it's size) wrapper for a lazy ByteString (LBS) - this container is used for messages generated from PCLT templates ----------------------------------------------------- ----------------------------------------------------- -- Application specific modules import Control.Exception ----------------------------------------------------- ----------------------------------------------------- -- Application specific data structures -- \/ data data HelloWorld = HelloWorld -- \/ errors type WorldName = String type WorldIndex = Int data HelloWorldError = NoWorld_HWE | AmbiguousChoiceOfWorlds_HWE (WorldName, WorldIndex) (WorldName, WorldIndex) [(WorldName, WorldIndex)] | SomeVeryStrangeError_HWE Int String Bool (Maybe Bool) (Maybe Bool) SomeException | FailedDueToErrorInSubsystem_HWE ErrorInSubsystem data ErrorInSubsystem = ErrorType1_EIS | ErrorType2_EIS | FailedDueToErrorInSub_sub_system_EIS ErrorInSub_sub_system data ErrorInSub_sub_system = ErrorType1_EISS | ErrorType2_EISS ----------------------------------------------------- ----------------------------------------------------- -- Functional part of app type SayHelloWorld_Mode = Int sayHelloWorld :: SayHelloWorld_Mode -> Either HelloWorldError HelloWorld sayHelloWorld mode = case mode of 0 -> Right HelloWorld 1 -> Left NoWorld_HWE 2 -> Left $ AmbiguousChoiceOfWorlds_HWE ("RealWorld", 1) ("VirtualWorld", 2) [("OtherWorld1", 3), ("OtherWorld2", 4), ("OtherWorld3", 5)] 3 -> Left $ SomeVeryStrangeError_HWE 5789 "Noise..." True (Just True) Nothing (SomeException DivideByZero) 4 -> Left $ FailedDueToErrorInSubsystem_HWE ErrorType1_EIS 5 -> Left $ FailedDueToErrorInSubsystem_HWE ErrorType2_EIS 6 -> Left $ FailedDueToErrorInSubsystem_HWE $ FailedDueToErrorInSub_sub_system_EIS ErrorType1_EISS 7 -> Left $ FailedDueToErrorInSubsystem_HWE $ FailedDueToErrorInSub_sub_system_EIS ErrorType2_EISS acquireCatalog :: StdErr_CLBS -> (ShowDetalizationLevel, LanguageName) -> (PCLT_Catalog, StdErr_CLBS) acquireCatalog stderr_clbs (stderr_sdl, stderr_lng) = let catalog_id = 777 catalog_config = defaultPCLTInnerConfig { -- config, that influences catalog formation and messages generation -- a catalog always hasa default language (primary) -- by default a strict orientation of other languages on this primary language is turned on - for every nonprimary language template, it's sets of parameters and composites must be equal to the sets in primary language -- this stricness is easy to turn off or to add exclusions to (when not to be strict on composites and parameters sets) -- (but one can't turn off (or make exclusions for) the constraint, according to which, a template can't be added to a catalog if it's version for primary language is nowhere (in catalog, in added template) to be found) pcsStrictOrient_ofParamsAndCmpsts_onDfltLngTplsSets = -- let's add one such exclusion: we don't want catalogto be strict on a parameter "__row_idx" in template "E_HWE_AMBWRLDCH_OW" (pcsStrictOrient_ofParamsAndCmpsts_onDfltLngTplsSets defaultPCLTInnerConfig) { soExcludingCompParameters = soExcludingCompParameters (pcsStrictOrient_ofParamsAndCmpsts_onDfltLngTplsSets defaultPCLTInnerConfig) ++ [("E_HWE_AMBWRLDCH_OW", "__row_idx")] } } -- \/ these here aren't to be believed to be lightweight operations - don't use them too often, just intitialize catalog once when program starts (catalog1, stderr_clbs2) = initDefaultCatalog_2 -- it contains temlates of messages used by PCLT pacakage itself (error messages and some shows) catalog_config catalog_id (stderr_clbs, stderr_sdl, stderr_lng) -- collect error messages if any (catalog2, stderr_clbs3) = addFromHSRTToCatalog_2 PCLTRawCatalog__HelloWorld -- an instance of HasStaticRawPCLTs, a data type to which we bind all the application specifc templates catalog1 -- we add it to the initial version of catalog (stderr_clbs2, stderr_sdl, stderr_lng) -- collect error messages if any in (catalog2, stderr_clbs3) showHelloWorld :: SayHelloWorld_Mode -> (StdOut_CLBS, StdErr_CLBS) -> (ShowDetalizationLevel, LanguageName, PCLT_Catalog) -> (StdOut_CLBS, StdErr_CLBS) -- first CLBS - result; second - representation of catalog errors list showHelloWorld mode (stdout_clbs, stderr_clbs) (sdl, lng, catalog) = let err_or_HelloWorld = sayHelloWorld mode (new_stdout_clbs, new_stderr_clbs) = -- note: here in stderr_clbs goes only catalog-works errors, HelloWorldError (if any) goes into stdout_clbs pcsi2text_plus_errs_2 (stdout_clbs, stderr_clbs) (showAsPCSI err_or_HelloWorld) -- this means, thet err_or_HelloWorld is of ShowAsPCSI class - the according instance is declared in the bottom of this example (sdl, lng) catalog in (new_stdout_clbs, new_stderr_clbs) -- these are showable, and one may print them "CB.putStrLn stdout_clbs" main = run_test "rus" (SDL 15000) -- possible values here: ["rus", "eng", "hs_"] x [Zero_SDL, One_SDL, SDL <Int>, InfinitelyBig_SDL] run_test _lng _sdl = let my_lng = _lng my_sdl = _sdl my_stderr_clbs_size = 50000 my_stdout_clbs_size = 50000 stderr_clbs0 = newCLBS my_stderr_clbs_size stdout_clbs0 = newCLBS my_stdout_clbs_size (catalogue, stderr_clbs1) = acquireCatalog stderr_clbs0 (my_sdl, my_lng) iterate_ = do putStrLn "----New-iteration:---------------" putStrLn "Input sayHelloWorld mode (0-7; '-1' to exit): " mode <- readLn case mode >= 0 && mode <= 7 of True -> do let (stdout_clbs1, stderr_clbs1) = showHelloWorld mode (stdout_clbs0, stderr_clbs0) (my_sdl, my_lng, catalogue) putStrLn "----Errors:----------------------" putStrLn $ toString $ clbsLBS stderr_clbs1 putStrLn "----Output:----------------------" putStrLn $ toString $ clbsLBS stdout_clbs1 --putStrLn $ show $ toString $ clbsLBS stdout_clbs1 iterate_ False -> case mode == (-1) of True -> return () False -> iterate_ in do putStrLn ("Language, SDL (detailization level): " ++ show (_lng, _sdl)) putStrLn "----Init-errors:-----------------" putStrLn $ show stderr_clbs1 putStrLn "----Cycle-start:-----------------" iterate_ ----------------------------------------------------- ----------------------------------------------------- -- Representations -- Note: it's a recommended practice to put these declarations below into a separate file... -- IMPORTANT!!! : It is highly recommended to use ISO 639(3) standard for language names, since PCLT-DB package that addons a DBMS powers to PCLT catalogs management is oriented on 3 letters (not bigger) language names. Without modifications PCLT-DB won't work for bigger (then 3-letters) names. instance (ShowAsPCSI HelloWorldError, ShowAsPCSI HelloWorld) => ShowAsPCSI (Either HelloWorldError HelloWorld) where showAsPCSI err_or_hw = case err_or_hw of Right hw -> showAsPCSI hw Left hwe -> showAsPCSI hwe instance ShowAsPCSI HelloWorld where showAsPCSI hw = empPCSI "HW" instance HasStaticRawPCLTs HelloWorld where getStaticRawPCLTs inner_cfg _ = flip (,) [] $ PCLT_RawCatalogData $ M.fromList [ ( "HW" , ( M.fromList [ ("rus", B.pack "Привет, Мир!") , ("eng", B.pack "Hello world!") , ("hs_", B.pack "HelloWorld") ] , str2PCLT_SDL Required_SDLM "0" inner_cfg ) ) ] instance ShowAsPCSI HelloWorldError where showAsPCSI hwe = thePCSI "E_HWE" [ ("hwe_details_pcsi", PCSI_PV hwe_details_pcsi) ] where hwe_details_pcsi = case hwe of NoWorld_HWE -> empPCSI "E_HWE_NOWRLD" AmbiguousChoiceOfWorlds_HWE (wn1, wi1) (wn2, wi2) other_worlds -> thePCSI "E_HWE_AMBWRLDCH" [ ("w_name_1", PlainText_PV wn1) , ("w_idx_1" , PlainText_PV $ show wi1) , ("w_name_2", PlainTextLBS_PV $ B.pack wn1) -- lazy ByteString is also welcome , ("w_idx_2" , PlainTextLBS_PV $ B.pack $ show wi2) , ("other_worlds", case null other_worlds of -- this is a #1 way to include templates in a template - through parameters using PCSI_PV and/or PCSIList_PV parameter value types True -> PCSI_PV $ empPCSI "E_HWE_AMBWRLDCH_NOMORE" False -> Indented_PV 3 $ -- a way to insert 3 whitespaces after each '\n' in a string that results from what's wrapped in PCSIList_PV (map (\ (w_name, w_idx) -> thePCSI "E_HWE_AMBWRLDCH_OW" [ ("w_name", PlainText_PV w_name) , ("w_idx" , PlainText_PV $ show w_idx) ] ) other_worlds ) (PCSI_PV $ empPCSI "E_HWE_AMBWRLDCH_OW_SEP") -- this is a separator between rows in representation (put Nothing_PV here, if you want to omit separator) ) ] SomeVeryStrangeError_HWE i s b mb_b1 mb_b2 sm_excpt -> thePCSI "E_HWE_STRNGERR" [ ("int" , PlainText_PV $ show i) , ("str" , PlainText_PV s) , ("bool" , PCSI_PV $ showAsPCSI b) -- Text.PCLT.ShowAsPCSI__ module conains ShowAsPCSI instances for some basic general types (Bool, ShowAsPCSI a => Maybe a, SomeException) , ("mb_bool1", PCSI_PV $ showAsPCSI mb_b1) -- such treatment is possible only if type under Maybe is of ShowAsPCSI class , ("mb_bool2", PCSI_PV $ showAsPCSI mb_b2) , ("sm_excpt", PCSI_PV $ showAsPCSI sm_excpt) -- uses SomeException instaniation from Text.PCLT.ShowAsPCSI__ ] FailedDueToErrorInSubsystem_HWE eis -> [showAsPCSI eis] `addToPCSI` empPCSI "E_HWE_EIS" -- if summed PCSIs parameters names happen coincide, the walue is kept from first parameter, from earliest PCSI from list -- E_HWE_STRNGERR template refers to some predefined standard templates, assumming, that Bool, (Maybe a) and SomeException already are instances of ShowAsPCSI class. -- And they really are instaniated in Text.PCLT.ShowAsPCLT__ module. However, HasStaticRawPCLTs instances of Bool, (Maybe a) and SomeException support only 2 languages: eng, rus. -- But we use 3 languages here: eng, rus and haskell! -- So, in order to make this example complete, we also need to add representations for Bool, (Maybe a) and SomeException types in a 'haskell' language: data PCLTRawCatalog__Text_PCLT_ShowAsPCSI_GeneralCommons__addon_for_haskell_lng = PCLTRawCatalog__Text_PCLT_ShowAsPCSI_GeneralCommons__addon_for_haskell_lng instance HasStaticRawPCLTs PCLTRawCatalog__Text_PCLT_ShowAsPCSI_GeneralCommons__addon_for_haskell_lng where getStaticRawPCLTs inner_cfg _ = flip (,) [] $ PCLT_RawCatalogData $ M.fromList [ ("TRUE", (M.fromList [("hs_", B.pack "True")], str2PCLT_SDL Required_SDLM "one" inner_cfg)) , ("FALSE", (M.fromList [("hs_", B.pack "False")], str2PCLT_SDL Required_SDLM "##|TRUE##|" inner_cfg)) , ("MAYBE_A", (M.fromList [("hs_", B.pack "@@|maybe_cnstr@@|")], str2PCLT_SDL Required_SDLM "##|TRUE##|" inner_cfg)) , ("MAYBE_JUST", (M.fromList [("hs_", B.pack "Just @@|a@@|")], str2PCLT_SDL Required_SDLM "##|MAYBE_A##|" inner_cfg)) , ("MAYBE_NOTHING", (M.fromList [("hs_", B.pack "Nothing")], str2PCLT_SDL Required_SDLM "##|MAYBE_A##|" inner_cfg)) , ("LLEXCPT", (M.fromList [("hs_", B.pack "SomeException (ErrorCall \"@@|excpt_msg@@|\")")], str2PCLT_SDL Required_SDLM "1000" inner_cfg)) ] instance HasStaticRawPCLTs HelloWorldError where getStaticRawPCLTs inner_cfg _ = flip (,) [] $ PCLT_RawCatalogData $ M.fromList [ ( "E_HWE" , ( let same_tpl = B.pack "##|E_HWE_PREFIX##|@@|hwe_details_pcsi@@|" -- the E_HWE_PREFIX is a composite; the hwe_details_pcsi is a parameter in M.fromList [ ("rus", same_tpl) , ("eng", same_tpl) , ("hs_", same_tpl) ] , str2PCLT_SDL Required_SDLM "10" inner_cfg -- == PCLT_SDL $ SDL 10 ) ) , ( "E_HWE_PREFIX" , ( M.fromList [ ("rus", B.pack "Приветствие мира не удалось!\nПричина: ") , ("eng", B.pack "Hello world failure!\nReason: ") , ("hs_", B.empty) ] , str2PCLT_SDL Required_SDLM "##|E_HWE##|" inner_cfg -- the SDL must be the same as specified for E_HWE template -- == PCLT_SDL_ToTemplateLink "E_HWE" ) ) , ( "E_HWE_NOWRLD" , ( M.fromList [ ("rus", B.pack "некого приветствовать (нет мира)!") , ("eng", B.pack "no world!") , ("hs_", B.pack "NoWorld_HWE") ] , str2PCLT_SDL Required_SDLM "##|E_HWE##|" inner_cfg ) ) , ( "E_HWE_AMBWRLDCH" , ( M.fromList [ ("rus", B.pack "неясно, какой из миров приветствовать - их несколько!\nПервый мир: [имя: '@@|w_name_1@@|', индекс: @@|w_idx_1@@|].\nВторой мир: [имя: '@@|w_name_2@@|', индекс: @@|w_idx_2@@|].\nА так же эти миры: \n @@|other_worlds@@|.") , ("eng", B.pack "ambiguous choice of worlds!\nFirst world: [name: '@@|w_name_1@@|', index: @@|w_idx_1@@|].\nSecond world: [name: '@@|w_name_2@@|', index: @@|w_idx_2@@|].\nAnd also these worlds: \n @@|other_worlds@@|.") , ("hs_", B.pack "AmbiguousChoiceOfWorlds_HWE\n (\"@@|w_name_1@@|\", @@|w_idx_1@@|)\n (\"@@|w_name_2@@|\", @@|w_idx_2@@|)\n [ @@|other_worlds@@|\n ]") ] , str2PCLT_SDL Required_SDLM "##|E_HWE##|" inner_cfg ) ) , ( "E_HWE_AMBWRLDCH_OW" , ( M.fromList [ ("rus", B.pack "@@|__row_idx@@|) мир [имя: '@@|w_name@@|', индекс: @@|w_idx@@|]") -- __row_idx is an implicit parameter, that can be used by templates that are guaranteed to be wrapped in a PCSIList_PV (not PVList_PV !!!) parameter value wrapper , ("eng", B.pack "@@|__row_idx@@|) world [name: '@@|w_name@@|', index: @@|w_idx@@|]") , ("hs_", B.pack "(\"@@|w_name@@|\", @@|w_idx@@|)") ] , str2PCLT_SDL Required_SDLM "##|E_HWE_AMBWRLDCH##|" inner_cfg ) ) , ( "E_HWE_AMBWRLDCH_OW_SEP" , ( M.fromList [ ("rus", B.pack "\n") , ("eng", B.pack "\n") , ("hs_", B.pack "\n, ") ] , str2PCLT_SDL Required_SDLM "##|E_HWE_AMBWRLDCH_OW##|" inner_cfg ) ) , ( "E_HWE_AMBWRLDCH_NOMORE" , ( M.fromList [ ("rus", B.pack "список пуст.") , ("eng", B.pack "empty list.") , ("hs_", B.empty) ] , str2PCLT_SDL Required_SDLM "##|E_HWE_AMBWRLDCH_OW##|" inner_cfg ) ) , ( "E_HWE_STRNGERR" , ( M.fromList [ ("rus", B.pack "какая-то странная непонятная ошибка! Данные: @@|int@@| \"@@|str@@|\" @@|bool@@| (@@|mb_bool1@@|) (@@|mb_bool2@@|) { @@|sm_excpt@@| }") , ("eng", B.pack "some very strange error! Data: @@|int@@| \"@@|str@@|\" @@|bool@@| (@@|mb_bool1@@|) (@@|mb_bool2@@|) { @@|sm_excpt@@| }") , ("hs_", B.pack "SomeVeryStrangeError_HWE @@|int@@| \"@@|str@@|\" @@|bool@@| (@@|mb_bool1@@|) (@@|mb_bool2@@|) (@@|sm_excpt@@|)") ] , str2PCLT_SDL Required_SDLM "##|E_HWE##|" inner_cfg ) ) , ( "E_HWE_EIS" , ( M.fromList [ ("rus", B.pack "ошибка в подсистеме!\nТекст исключения уровнем ниже:\n##|E_EIS##|") , ("eng", B.pack "failed due to error(s) in subsystem!\nLower level exception message:\n##|E_EIS##|") , ("hs_", B.pack "FailedDueToErrorInSubsystem_HWE (##|E_EIS##|)") -- include a template E_EIS here (note: it's representation together with E_HWE_EIS will share one parameters values map) -- this is a #2 way to include templates in a template - as composites -- the difference from #1 way is such, that in #2 template and it's composites share one same parameters map, but in #1 each inclusion has it's own parameters map ] , str2PCLT_SDL Required_SDLM "##|E_HWE##|" inner_cfg ) ) ] instance ShowAsPCSI ErrorInSubsystem where showAsPCSI eis = thePCSI "E_EIS" [ ("eis_details_pcsi", PCSI_PV eis_details_pcsi) ] where eis_details_pcsi = case eis of ErrorType1_EIS -> empPCSI "E_EIS_ET1" ErrorType2_EIS -> empPCSI "E_EIS_ET2" FailedDueToErrorInSub_sub_system_EIS eiss -> thePCSI "E_EIS_EISS" [("e_eiss", PCSI_PV $ showAsPCSI eiss)] instance HasStaticRawPCLTs ErrorInSubsystem where getStaticRawPCLTs inner_cfg _ = flip (,) [] $ PCLT_RawCatalogData $ M.fromList [ ( "E_EIS" , ( let same_tpl = B.pack "##|E_EIS_PREFIX##|@@|eis_details_pcsi@@|" in M.fromList [ ("rus", same_tpl) , ("eng", same_tpl) , ("hs_", same_tpl) ] , str2PCLT_SDL Required_SDLM "20" inner_cfg ) ) , ( "E_EIS_PREFIX" , ( M.fromList [ ("rus", B.pack "Сбой в подсистеме!\nПричина: ") , ("eng", B.pack "Subsystem failure!\nReason: ") , ("hs_", B.empty) ] , str2PCLT_SDL Required_SDLM "##|E_EIS##|" inner_cfg ) ) , ( "E_EIS_ET1" , ( M.fromList [ ("rus", B.pack "ошибка типа #1!") , ("eng", B.pack "error of type #1!") , ("hs_", B.pack "ErrorType1_EIS") ] , str2PCLT_SDL Required_SDLM "##|E_EIS##|" inner_cfg ) ) , ( "E_EIS_ET2" , ( M.fromList [ ("rus", B.pack "ошибка типа #2!") , ("eng", B.pack "error of type #2!") , ("hs_", B.pack "ErrorType2_EIS") ] , str2PCLT_SDL Required_SDLM "##|E_EIS##|" inner_cfg ) ) , ( "E_EIS_EISS" , ( M.fromList [ ("rus", B.pack "сбой в подПОДсистеме! Текст исключения уровнем ниже: @@|e_eiss@@|") , ("eng", B.pack "failed due to error(s) in subSUBsystem!\nLower level exception message:\n@@|e_eiss@@|") , ("hs_", B.pack "FailedDueToErrorInSub_sub_system_EIS (@@|e_eiss@@|)") -- i could have included representation of ErrorInSub_sub_system as a composite here ##|E_EISS##| (the same as we did in E_HWE_EIS template) -- but for example purpose i do the same work in a different way through @@|e_eiss@@| parameter -- this way is less strict because user may choose not to (forget to) put under a parameter "e_eiss" the template "E_EISS" ] , str2PCLT_SDL Required_SDLM "@@|e_eiss@@|" inner_cfg -- == PCLT_SDL_ToParamCompositeLink "e_eiss" -- now if user forgets to put a PCSI_PV in the value of param "e_eiss", the engine will complain with an error -- because here we specify, that SDL requirement must be the same as for TEMPLATE that is under "e_eiss" parameter ) ) ] instance ShowAsPCSI ErrorInSub_sub_system where showAsPCSI eiss = thePCSI "E_EISS" [ ("eiss_details_pcsi", PCSI_PV eiss_details_pcsi) ] where eiss_details_pcsi = case eiss of ErrorType1_EISS -> empPCSI "E_EISS_ET1" ErrorType2_EISS -> empPCSI "E_EISS_ET2" instance HasStaticRawPCLTs ErrorInSub_sub_system where getStaticRawPCLTs inner_cfg _ = flip (,) [] $ PCLT_RawCatalogData $ M.fromList [ ( "E_EISS" , ( let same_tpl = B.pack "##|E_EISS_PREFIX##|@@|eiss_details_pcsi@@|" in M.fromList [ ("rus", same_tpl) , ("eng", same_tpl) , ("hs_", same_tpl) ] , str2PCLT_SDL Required_SDLM "30" inner_cfg ) ) , ( "E_EISS_PREFIX" , ( M.fromList [ ("rus", B.pack "Сбой в подПОДсистеме!\nПричина: ") , ("eng", B.pack "SubSUBsystem failure!\nReason: ") , ("hs_", B.empty) ] , str2PCLT_SDL Required_SDLM "##|E_EISS##|" inner_cfg ) ) , ( "E_EISS_ET1" , ( M.fromList [ ("rus", B.pack "ошибка типа #1!") , ("eng", B.pack "error of type #1!") , ("hs_", B.pack "ErrorType1_EISS") ] , str2PCLT_SDL Required_SDLM "##|E_EISS##|" inner_cfg ) ) , ( "E_EISS_ET2" , ( M.fromList [ ("rus", B.pack "ошибка типа #2!") , ("eng", B.pack "error of type #2!") , ("hs_", B.pack "ErrorType2_EISS") ] , str2PCLT_SDL Required_SDLM "##|E_EISS##|" inner_cfg ) ) ] ------------------------------------ -- Gathering all HasStaticRawPCLTs insances and sticking them to one data type. This way we may scope all our templates, for example, when we need a single reference on catalog input data (as in addFromHSRTToCatalog) data PCLTRawCatalog__HelloWorld = PCLTRawCatalog__HelloWorld instance HasStaticRawPCLTs PCLTRawCatalog__HelloWorld where -- here we gather all the local to module HasStaticRawPCLTs instances, so tha it's easy to mention them by one word widenessOfStaticRawPCLTsSet _ = Module_RPSW -- this is apurely informative declaration, no functions make use of it so far getStaticRawPCLTs inner_cfg _ = mergeRawCatalogDataSets2 True [ getStaticRawPCLTs inner_cfg (undefined :: HelloWorld) , getStaticRawPCLTs inner_cfg (undefined :: HelloWorldError) , getStaticRawPCLTs inner_cfg (undefined :: ErrorInSubsystem) , getStaticRawPCLTs inner_cfg (undefined :: ErrorInSub_sub_system) , getStaticRawPCLTs inner_cfg (undefined :: PCLTRawCatalog__Text_PCLT_ShowAsPCSI_GeneralCommons__addon_for_haskell_lng) ] -- if we also add (undefined :: PCLTRawCatalog__PCLT_InitialDefaultCatalog) in this list, -- then instead of using "initDefaultCatalog_2" and "addFromHSRTToCatalog_2" we can use just single "initCatalogFromHSRT_2" {- ------------------------------------------------------------------------- -- CONCLUSION One may see here, that adding a multilinguality to a system is not a task for a lazy guy. While developing this (PCLT engine) package a recomended practice was explicated: 1) Separate program and representations - put all ShowAsPCSI and HasStaticRawPCLTs instances to a separate files. For example, author would make his file into two: "HelloWorld.hs" and "HelloWorld__.hs". The HelloWorld__ should have imported at least "Text.PCLT.SH__" and HelloWorld 2) Keep all templates in tables in OpenOffice Calc file (or Excel's analogue). An example of such file is provided in package folder, in [initial_data/PCLT.InitialCatalog.ods] - it is filled with templates data actually used by PCLT engine. This package comes before another one - "PCLT-DB", where all templates are kept in a PostgreSQL v8.4.(not less) data base, and it is possible to run a thread, that regularly checks, if a catalog in operative memory is up tu date, and if not, rereads it from DB. Check it in Hackage. Best regards, Belka -}
Andrey-Sisoyev/haskell-PCLT
examples/HelloWorld/HelloWorld.hs
lgpl-2.1
32,257
0
27
13,076
3,601
2,009
1,592
307
8
{-# LANGUAGE OverloadedStrings #-} module Graphics.Model.MikuMikuDance.Loader where import Control.Applicative import Control.Monad import Data.Int import Data.Bits import Data.Pack import Data.Packer import qualified Data.ByteString as B import Graphics.Model.MikuMikuDance.Types import Linear import Unsafe.Coerce import System.IO.Unsafe getFloat :: Unpacking Float -- Performance hack (may not work on your devices!) getFloat = unsafeCoerce <$> getWord32LE get2 :: Unpacking a -> Unpacking (V2 a) get2 get = V2 <$> get <*> get get3 :: Unpacking a -> Unpacking (V3 a) get3 get = V3 <$> get <*> get <*> get get4 :: Unpacking a -> Unpacking (V4 a) get4 get = V4 <$> get <*> get <*> get <*> get getV2 :: Unpacking (V2 Float) getV2 = get2 getFloat getV3 :: Unpacking (V3 Float) getV3 = get3 getFloat getV4 :: Unpacking (V4 Float) getV4 = get4 getFloat getWord8Int, getWord16Int, getWord32Int :: Unpacking Int getWord8Int = fromIntegral <$> getWord8 getWord16Int = fromIntegral <$> getWord16LE getWord32Int = fromIntegral <$> getWord32LE -- Left handed system -> Right handed system ltrTrans (V3 x y z) = V3 x y (-z) ltrEular (V3 x y z) = V3 (-x) (-y) z ltrQuat (V4 t i j k) = V4 (-t) i j k getPos = fmap ltrTrans getV3 getEular = fmap ltrEular getV3 getQuat = fmap ltrQuat getV4 -- * PMX loadMMD :: FilePath -> IO MMD loadMMD path = decodeMMD <$> B.readFile path decodeMMD :: B.ByteString -> MMD decodeMMD bs = runUnpacking unpackMMD bs unpackMMD :: Unpacking MMD unpackMMD = do magic <- getWord32BE case magic of 0x506d6400 -> unpackPMD 0x504d5820 -> unpackPMX _ -> fail "Not a MMD Model" getUnsignedIndexUnpacker :: Unpacking (Unpacking Int32) getUnsignedIndexUnpacker = do size <- getWord8 return $ case size of 1 -> fromIntegral <$> getWord8 2 -> fromIntegral <$> getWord16LE 4 -> fromIntegral <$> getWord32LE getIndexUnpacker :: Unpacking (Unpacking Int32) getIndexUnpacker = do size <- getWord8 return $ case size of 1 -> ((fromIntegral :: Int8 -> Int32) . fromIntegral) <$> getWord8 2 -> ((fromIntegral :: Int16 -> Int32) . fromIntegral) <$> getWord16LE 4 -> fromIntegral <$> getWord32LE getTextBuf :: Unpacking B.ByteString getTextBuf = getWord32Int >>= getBytesCopy -- Polygon Model Extended unpackPMX :: Unpacking MMD unpackPMX = do version <- getFloat size <- getWord8 when ((version /= 2.0 && version /= 2.1) || size /= 8) $ fail "Not PMX 2.0/2.1" -- PMX Header -- 0: UTF-16, 1: UTF-8 isUTF16 <- getWord8 let charset 0 = "UTF-16" charset 1 = "UTF-8" numExtUVs <- getWord8 getVertexIndex <- getUnsignedIndexUnpacker getTextureIndex <- getIndexUnpacker getMaterialndex <- getIndexUnpacker getBoneIndex <- getIndexUnpacker getMorphIndex <- getIndexUnpacker getBodyIndex <- getIndexUnpacker modelName <- getTextBuf modelNameEn <- getTextBuf comment <- getTextBuf commentEn <- getTextBuf -- Vertex numVertices <- getWord32Int vertices <- replicateM numVertices $ do pos <- getPos normal <- getPos uv <- getV2 extV4s <- replicateM (fromIntegral numExtUVs) getV4 weightFormat <- getWord8 w <- case weightFormat of 0 -> BDEF1 <$> getBoneIndex 1 -> BDEF2 <$> get2 getBoneIndex <*> getFloat 2 -> BDEF4 <$> get4 getBoneIndex <*> getV4 -- SDEF need left<->right handed system transformation? 3 -> SDEF <$> get2 getBoneIndex <*> getFloat <*> get3 getPos 4 -> QDEF <$> get4 getBoneIndex <*> getV4 -- edgeScalingFactor esf <- getFloat return $ MMDVertex pos normal uv extV4s w esf -- Plane numPlanes <- getWord32Int planes <- replicateM (numPlanes `div` 3) $ do V3 p q r <- get3 getVertexIndex return $ V3 q p r -- from left to right -- Texture numTextures <- getWord32Int textures <- replicateM numTextures getTextBuf -- Material numMaterials <- getWord32Int materials <- replicateM numMaterials $ do name <- getTextBuf nameEn <- getTextBuf diffuse <- getV4 specular <- getV3 shininess <- getFloat ambient <- getV3 renderFlags <- getWord8 edgeColor <- getV4 edgeSize <- getFloat tex <- getTextureIndex sphereTex <- getTextureIndex sphereMode <- getWord8 toonFlag <- getWord8 toon <- case toonFlag of 0 -> getTextureIndex 1 -> (\x -> fromIntegral x - 10) <$> getWord8 script <- getTextBuf verticesCount <- getWord32LE return $ MMDMaterial name nameEn diffuse specular shininess ambient renderFlags edgeColor edgeSize tex sphereTex sphereMode toon script verticesCount -- Bone numBones <- getWord32Int bones <- replicateM numBones $ do name <- getTextBuf nameEn <- getTextBuf pos <- getPos parent <- getBoneIndex transDepth <- getWord32Int flags <- getWord16LE link <- if flags .&. 1 == 0 then Left <$> getV3 else Right <$> getBoneIndex following <- if flags .&. 0x300 /= 0 then Just <$> ((,) <$> getBoneIndex <*> getFloat) else return Nothing axis <- if flags .&. 0x400 /= 0 then Just <$> getV3 else return Nothing local <- if flags .&. 0x800 /= 0 then Just <$> ((,) <$> getPos <*> getPos) else return Nothing external <- if flags .&. 0x2000 /= 0 then Just <$> getWord32Int else return Nothing ik <- if flags .&. 0x20 /= 0 then do ix <- getBoneIndex lc <- getWord32Int maxRot <- getFloat numlink <- getWord32Int links <- replicateM numlink $ do ix <- getBoneIndex ranged <- getWord8 limit <- if ranged == 1 then Just <$> ((,) <$> getEular <*> getEular) else return Nothing return (ix, limit) return . Just $ MMDIK ix lc maxRot links else return Nothing return $ MMDBone name nameEn pos parent transDepth flags link following axis local external ik -- Morph numMorphs <- getWord32Int morphs <- replicateM numMorphs $ do name <- getTextBuf nameEn <- getTextBuf facial <- getWord8 morphType <- getWord8 let getMorphOffset = case morphType of 0 -> GroupMorph <$> getMorphIndex <*> getFloat 1 -> VertexMorph <$> getVertexIndex <*> getPos 2 -> BoneMorph <$> getBoneIndex <*> getPos <*> getQuat 3 -> UVMorph <$> getVertexIndex <*> getV4 4 -> UV1Morph <$> getVertexIndex <*> getV4 5 -> UV2Morph <$> getVertexIndex <*> getV4 6 -> UV3Morph <$> getVertexIndex <*> getV4 7 -> UV4Morph <$> getVertexIndex <*> getV4 8 -> MaterialMorph <$> getMaterialndex <*> getWord8 <*> getV4 <*> getV3 <*> getFloat <*> getV3 <*> getV4 <*> getFloat <*> getV4 <*> getV4 <*> getV4 9 -> FlipMorph <$> getMorphIndex <*> getFloat 10 -> ImpulseMorph <$> getBodyIndex <*> ((/= 0) <$> getWord8) <*> getPos <*> getEular numOffsets <- getWord32Int offsets <- replicateM numOffsets getMorphOffset return $ MMDMorph name nameEn facial offsets -- Group numGroups <- getWord32Int groups <- replicateM numGroups $ do name <- getTextBuf nameEn <- getTextBuf isSpecial <- getWord8 count <- getWord32Int elements <- replicateM count $ do kind <- getWord8 case kind of 0 -> Left <$> getBoneIndex 1 -> Right <$> getMorphIndex return $ MMDGroup name nameEn (isSpecial /= 0) elements -- Rigid Body numRigidBodies <- getWord32Int bodies <- replicateM numRigidBodies $ MMDRigidBody <$> getTextBuf <*> getTextBuf <*> getBoneIndex <*> getWord8 <*> getWord16LE <*> getWord8 <*> getV3 <*> getPos <*> getEular <*> getFloat <*> getFloat <*> getFloat <*> getFloat <*> getFloat <*> getWord8 -- Joint numJoints <- getWord32Int joints <- replicateM numJoints $ MMDJoint <$> getTextBuf <*> getTextBuf <*> getWord8 <*> getBodyIndex <*> getBodyIndex <*> getPos <*> getEular <*> getPos <*> getPos <*> getEular <*> getEular <*> getPos <*> getEular -- Soft Body numSoftBodies <- getWord32Int softBodies <- replicateM numSoftBodies $ MMDSoftBody <$> getTextBuf <*> getTextBuf <*> getWord8 <*> getMaterialndex <*> getWord8 <*> getWord16LE <*> getWord8 <*> getWord32Int <*> getWord32Int <*> getFloat <*> getFloat <*> getWord32Int <*> get3 getV4 <*> get2 getV3 <*> get4 getWord32Int <*> getV3 <*> (getWord32Int >>= flip replicateM ( (,,) <$> getBodyIndex <*> getVertexIndex <*> ((== 1) <$> getWord8))) <*> (getWord32Int >>= flip replicateM getVertexIndex) -- Sums up! return $ MMD version (charset isUTF16) numExtUVs modelName modelNameEn comment commentEn vertices planes textures [] materials bones morphs groups bodies joints softBodies -- get fixed length C string terminating NUL byte getFixedStr :: Int -> Unpacking B.ByteString getFixedStr l = B.takeWhile (/= 0) <$> getBytesCopy l -- Polygon Model Data unpackPMD :: Unpacking MMD unpackPMD = do unpackSetPosition 3 version <- getFloat when (version /= 1.0) $ fail "Not PMD 1.0" -- PMD Header name <- getFixedStr 20 comment <- getFixedStr 256 -- Vertex numVertices <- getWord32Int vertices <- replicateM numVertices $ do v <- MMDVertex <$> getPos <*> getPos <*> getV2 weight <- BDEF2 <$> get2 getBoneIndex <*> getPercent edgeFlag <- getWord8 let edgeScale = fromIntegral (1 - edgeFlag) return $ v [] weight edgeScale -- Plane numPlanesX3 <- getWord32Int planes <- replicateM (numPlanesX3 `div` 3) $ do V3 p q r <- get3 getVertexIndex return $ V3 q p r -- Material numMaterials <- getWord32Int materials <- forM [0 .. numMaterials - 1] $ \i -> do diffuse <- getV4 specularity <- getFloat specular <- getV3 ambient <- getV3 toonIx <- fromIntegral <$> getWord8 -- -1:0.bmp, 0..9:[1..10].bmp edgeFlag <- getWord8 -- 1 to disable numVertices <- getWord32LE texturePath <- getFixedStr 20 let sphereMode = -- "tex.bmp*sphere.sph" => Multiply (MMD 5.12-) -- "tex.bmp*sphere.spa" => Plus (MMD 5.12-) -- "tex.bmp/sphere.sph" => Multiply (MMD 5.11) -- "tex.bmp" or "sphere.sph" => None (MMD 5.09-) if 42 `B.elem` texturePath -- or 47 `elem` texturePath then if ".spa" `B.isSuffixOf` texturePath then 2 -- Add else 1 -- Mul else 0 -- None let i' = fromIntegral i return $ MMDMaterial texturePath "" diffuse specular specularity ambient ((1 - edgeFlag) * 16) -- draw edge (V4 0 0 0 1) 1.0 (i' * 2) (i' * 2 + 1) sphereMode (toonIx - 10) B.empty numVertices -- Texture let split x y | mSphereMode x == 0 = mNameJa x : mNameJa x : y split x y = t1 : B.tail t2 : y where (t1,t2) = B.break (== 42) (mNameJa x) let textures = foldr split [] materials -- Bone numBones <- getWord16Int bones <- replicateM numBones $ do name <- getFixedStr 20 parent <- getBoneIndex tailBone <- getBoneIndex -- 0:回転 1:回転と移動 2:IK 3:不明 4:IK影響下 -- 5:回転影響下 6:IK接続先 7:非表示 8:捻り 9:回転運動 typ <- getWord8 ik <- getBoneIndex headPos <- getPos return $ MMDBone name "" headPos parent 0 0 -- XXX ? (Right 0) Nothing --XXX follow link Nothing Nothing Nothing Nothing -- IK numIKBones <- getWord16Int ikbones <- replicateM numIKBones $ do bone <- getBoneIndex target <- getBoneIndex ikLen <- getWord8Int iter <- getWord16Int rotLimit <- (* 4) <$> getFloat links <- replicateM ikLen $ (\x -> (x, Nothing)) <$> getBoneIndex return $ (bone, MMDIK target iter rotLimit links) let bones' = zipWith (\ i bone -> bone { bIK = lookup i ikbones }) [0..] bones -- Face numFaces <- getWord16Int faces <- replicateM numFaces $ do name <- getFixedStr 20 numVertices <- getWord32Int facial <- getWord8 -- 0:Base, 1:Brow, 2: Eye, 3: Lip, 4:Other -- XXX 'base' should be ignored (0,0,0)??? vMorph <- replicateM numVertices $ VertexMorph <$> fmap fromIntegral getWord32LE <*> getPos return $ MMDMorph name "" facial vMorph faceListLen <- getWord8Int faceList <- replicateM faceListLen getMorphIndex -- Group boneGroupsLen <- getWord8Int boneGroups <- replicateM boneGroupsLen (getFixedStr 50) let bGsEn = replicate boneGroupsLen "" numGroupedBones <- getWord32Int groupedBones <- replicateM numGroupedBones $ (,) <$> getBoneIndex <*> getWord8 -- Ext - English support since MMD 4.03 empty <- isEmpty haveEnNames <- if empty then return False else (== 1) <$> getWord8 (nameEn, commentEn, bones, faces, bGsEn) <- if not haveEnNames then return ("", "", bones, faces, bGsEn) else do name' <- getFixedStr 20 comment' <- getFixedStr 256 bones' <- forM bones $ \bone -> do nameEn <- getFixedStr 20 return bone { bName = nameEn } faces' <- forM (tail faces) $ \morph -> do nameEn <- getFixedStr 20 return morph { mphName = nameEn } let faces'' = (head faces) { mphName = "base" } : faces' bGsEn' <- replicateM boneGroupsLen (getFixedStr 50) return (name', comment', bones', faces'', bGsEn') -- UTF-16 let root = "R\NULo\NULo\NULt\NUL" let rootGroup = MMDGroup root root True [Left 0] let faceGroup = MMDGroup "h\136\197`" "E\NULx\NULp\NUL" True (map Right faceList) let groups = rootGroup : faceGroup : zipWith3 (\i j e -> MMDGroup j e False $ map (Left . fst) $ filter ((== i).snd) groupedBones ) [1..] boneGroups bGsEn -- group 0 ('center') is reserved for the root bone -- toon texture list since MMD 4.03 toonTexList <- if empty then return [] else replicateM 10 (getFixedStr 100) -- Ext - Bullet Physics -- Rigid Body numRigidBodies <- getWord32Int bodies <- replicateM numRigidBodies $ MMDRigidBody <$> getFixedStr 20 <*> pure "" <*> getBoneIndex <*> getWord8 <*> getWord16LE <*> getWord8 <*> getV3 <*> getPos <*> getEular <*> getFloat <*> getFloat <*> getFloat <*> getFloat <*> getFloat <*> getWord8 -- Joint numJoints <- getWord32Int joints <- replicateM numJoints $ MMDJoint <$> getFixedStr 20 <*> pure "" <*> pure 0 <*> getBodyIndex <*> getBodyIndex <*> getPos <*> getEular <*> getPos <*> getPos <*> getEular <*> getEular <*> getPos <*> getEular -- Sums up! return $ MMD 1 "Shift-JIS" 0 name nameEn comment commentEn vertices planes textures toonTexList materials bones' faces groups bodies joints [] where toInt16 = fromIntegral toInt32 = fromIntegral :: Int16 -> Int32 getBoneIndex = toInt32 . toInt16 <$> getWord16LE getPercent = (/100) . fromIntegral <$> getWord8 getVertexIndex = fromIntegral <$> getWord16LE getMorphIndex = getVertexIndex getBodyIndex = fromIntegral <$> getWord32LE -- * VMD loadVMD :: FilePath -> IO VMD loadVMD path = decodeVMD <$> B.readFile path decodeVMD :: B.ByteString -> VMD decodeVMD bs = runUnpacking unpackVMD bs unpackVMD :: Unpacking VMD unpackVMD = do magic <- getBytes 30 when (magic /= "Vocaloid Motion Data 0002\0\0\0\0\0") $ -- MMD 3.0+ required. fail "Not Vocaloid Motion Data" -- If the content is camera, light, and self shadow, -- model name should be "カメラ・照明\0on Data" name <- getFixedStr 20 numBoneKeyframes <- getWord32Int boneM <- replicateM numBoneKeyframes $ BoneKeyframe <$> getFixedStr 15 <*> getWord32LE <*> getPos <*> getQuat <*> replicateM 64 (fromIntegral <$> getWord8) numMorphKeyframes <- getWord32Int morphM <- replicateM numMorphKeyframes $ MorphKeyframe <$> getFixedStr 15 <*> getWord32LE <*> getFloat numCameraKeyframes <- getWord32Int cameraM <- replicateM numCameraKeyframes $ CameraKeyframe <$> getWord32LE <*> getFloat <*> getPos <*> getEular <*> replicateM 24 (fromIntegral <$> getWord8) <*> getWord32LE <*> ((== 0) <$> getWord8) numLightKeyframes <- getWord32Int lightM <- replicateM numLightKeyframes $ LightKeyframe <$> getWord32LE <*> getV3 <*> getPos -- After MMDv6.19 -- empty <- isEmpty shadowM <- if empty then return [] else do numSelfShadowKeyframes <- getWord32Int replicateM numSelfShadowKeyframes $ ShadowKeyframe <$> getWord32LE <*> (fromIntegral <$> getWord8) <*> getFloat -- Since MMDv7.40 -- empty <- isEmpty ctrlM <- if empty then return [] else do numCtrlKeyframes <- getWord32Int replicateM numCtrlKeyframes $ ControlKeyframe <$> getWord32LE <*> ((== 1) <$> getWord8) <*> (getWord32Int >>= \count -> replicateM count ((,) <$> getFixedStr 20 <*> ((== 1) <$> getWord8))) -- Sums up! return $ VMD name boneM morphM cameraM lightM shadowM ctrlM packetVMD :: Packet VMD packetVMD (VMD name bone morph camera light shadow control) = do magic <- bytes 30 when (magic /= "Vocaloid Motion Data 0002\0\0\0\0\0") $ -- MMD 3.0+ required. fail "Not Vocaloid Motion Data" -- If the content is camera, light, and self shadow, -- model name should be "カメラ・照明\0on Data" nameM <- varchar 20 name let p >< s = fromIntegral <$> p (fromIntegral s) numBoneKeyframes <- i32 >< V.length bone boneM <- array numBoneKeyframes bone -- boneM <- replicateM numBoneKeyframes $ -- BoneKeyframe <$> getFixedStr 15 <*> getWord32LE <*> getPos -- <*> getQuat <*> replicateM 64 (fromIntegral <$> getWord8) numMorphKeyframes <- i32 >< V.length morph morphM <- array numMorphKeyframes morph -- morphM <- replicateM numMorphKeyframes $ -- MorphKeyframe <$> getFixedStr 15 <*> getWord32LE <*> getFloat numCameraKeyframes <- i32 >< V.length camera cameraM <- array numCameraKeyframes camera -- numCameraKeyframes <- getWord32Int -- cameraM <- replicateM numCameraKeyframes $ -- CameraKeyframe <$> getWord32LE <*> getFloat -- <*> getPos <*> getEular -- <*> replicateM 24 (fromIntegral <$> getWord8) -- <*> getWord32LE <*> ((== 0) <$> getWord8) numLightKeyframes <- i32 >< V.length light lightM <- array numLightKeyframes light -- numLightKeyframes <- getWord32Int -- lightM <- replicateM numLightKeyframes $ -- LightKeyframe <$> getWord32LE <*> getV3 <*> getPos -- After MMDv6.19 -- empty <- isEmpty numSelfShadowKeyframes <- dicase (if empty then return V.empty else i32 >< V.length shadow) (i32 >< V.length shadow) shadowM <- array numSelfShadowKeyframes shadow -- numSelfShadowKeyframes <- getWord32Int -- replicateM numSelfShadowKeyframes $ -- ShadowKeyframe <$> getWord32LE -- <*> (fromIntegral <$> getWord8) <*> getFloat -- Since MMDv7.40 -- empty <- isEmpty ctrlM <- if empty then return [] else do numCtrlKeyframes <- getWord32Int replicateM numCtrlKeyframes $ ControlKeyframe <$> getWord32LE <*> ((== 1) <$> getWord8) <*> (getWord32Int >>= \count -> replicateM count ((,) <$> getFixedStr 20 <*> ((== 1) <$> getWord8))) -- Sums up! return $ VMD nameM boneM morphM cameraM lightM shadowM ctrlM
capsjac/3dmodels
Graphics/Model/MikuMikuDance/Loader.hs
lgpl-3.0
18,276
260
28
3,717
5,589
2,775
2,814
446
25
{-# LANGUAGE InstanceSigs #-} module Twinplicative where import Prelude hiding (Either, Left, Right) newtype Compose f g a = Compose { getCompose :: f (g a) } deriving (Eq, Show) instance (Functor f, Functor g) => Functor (Compose f g) where fmap f (Compose fga) = Compose $ (fmap . fmap) f fga instance (Applicative f, Applicative g) => Applicative (Compose f g) where pure :: a -> Compose f g a pure x = Compose $ (pure . pure) x (<*>) :: Compose f g (a -> b) -> Compose f g a -> Compose f g b (Compose f) <*> (Compose a) = Compose $ ((<*>) <$> f) <*> a instance (Foldable f, Foldable g) => Foldable (Compose f g) where foldMap f (Compose fga) = (foldMap . foldMap) f fga instance (Traversable f, Traversable g) => Traversable (Compose f g) where traverse :: Applicative f1 => (a -> f1 b) -> Compose f g a -> f1 (Compose f g b) traverse f (Compose fga) = Compose <$> (traverse . traverse) f fga class Bifunctor p where {-# MINIMAL bimap | first, second #-} bimap :: (a -> b) -> (c -> d) -> p a c -> p b d bimap f g = first f . second g first :: (a -> b) -> p a c -> p b c first f = bimap f id second :: (b -> c) -> p a b -> p a c second = bimap id data Deux a b = Deux a b instance Bifunctor Deux where bimap f g (Deux a b) = Deux (f a) (g b) first f (Deux a b) = Deux (f a) b second f (Deux a b) = Deux a (f b) data Const a b = Const a instance Bifunctor Const where bimap f _ (Const a) = Const (f a) first f (Const a) = Const (f a) second _ (Const a) = Const a data Drei a b c = Drei a b c instance Bifunctor (Drei a) where bimap f g (Drei a b c) = Drei a (f b) (g c) first f (Drei a b c) = Drei a (f b) c second g (Drei a b c) = Drei a b (g c) data SuperDrei a b c = SuperDrei a b instance Bifunctor (SuperDrei a) where bimap f _ (SuperDrei a b) = SuperDrei a (f b) first f (SuperDrei a b) = SuperDrei a (f b) second _ (SuperDrei a b) = SuperDrei a b data SemiDrei a b c = SemiDrei a instance Bifunctor (SemiDrei a) where bimap _ _ (SemiDrei a) = SemiDrei a first _ (SemiDrei a) = SemiDrei a second _ (SemiDrei a) = SemiDrei a data Quadriceps a b c d = Quadzzz a b c d instance Bifunctor (Quadriceps a b) where bimap f g (Quadzzz a b c d) = Quadzzz a b (f c) (g d) first f (Quadzzz a b c d) = Quadzzz a b (f c) d second g (Quadzzz a b c d) = Quadzzz a b c (g d) data Either a b = Left a | Right b instance Bifunctor Either where bimap f _ (Left a) = Left (f a) bimap _ g (Right b) = Right (g b) first f (Left a) = Left (f a) first _ (Right b) = Right b second _ (Left a) = Left a second g (Right b) = Right (g b)
dmvianna/haskellbook
src/Ch25-Twinplicative.hs
unlicense
2,877
0
11
943
1,454
738
716
77
0
module Problem001 where main = print $ sum' 1000 sum' :: (Integral a) => a -> a sum' m = f 3 + f 5 - f 15 where f x = x * n * (n + 1) `quot` 2 where n = (m - 1) `quot` x
vasily-kartashov/playground
euler/problem-001.hs
apache-2.0
207
0
11
86
110
59
51
7
1
-- Copyright 2018 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- https://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module Google.Utils.Monad where import Control.Monad bind2 :: Monad m => m a -> m b -> (a -> b -> m c) -> m c bind2 m_x m_y f = join $ liftM2 f m_x m_y
google/cabal2bazel
src/Google/Utils/Monad.hs
apache-2.0
742
0
12
137
95
54
41
4
1
module Handler.Image where import Import import Data.Text (unpack) getImageR :: FilePath' -> Handler RepHtml getImageR (FilePath' fp) = sendFile "image/jpeg" $ unpack fp
snoyberg/photosorter
Handler/Image.hs
bsd-2-clause
172
0
7
25
55
29
26
5
1
{-# LANGUAGE CPP #-} module Text.PrettyPrint.Leijen {-# DEPRECATED "Compatibility module for users of wl-pprint - use \"Prettyprinter\" instead" #-} ( Doc, putDoc, hPutDoc, empty, char, text, (<>), nest, line, linebreak, group, softline, softbreak, align, hang, indent, encloseSep, list, tupled, semiBraces, (<+>), (<$>), (</>), (<$$>), (<//>), hsep, vsep, fillSep, sep, hcat, vcat, fillCat, cat, punctuate, fill, fillBreak, enclose, squotes, dquotes, parens, angles, braces, brackets, lparen, rparen, langle, rangle, lbrace, rbrace, lbracket, rbracket, squote, dquote, semi, colon, comma, space, dot, backslash, equals, string, int, integer, float, double, rational, Pretty(..), SimpleDoc, renderPretty, renderCompact, displayS, displayIO, bool, column, nesting, width ) where #if MIN_VERSION_base(4,8,0) import Prelude hiding ((<$>)) #else import Prelude #endif import qualified Data.Text.Lazy as TL import System.IO import Prettyprinter (Pretty (..)) import qualified Prettyprinter as New import qualified Prettyprinter.Render.Text as NewT #if !(MIN_VERSION_base(4,11,0)) import Data.Semigroup #endif type Doc = New.Doc () type SimpleDoc = New.SimpleDocStream () putDoc :: Doc -> IO () putDoc = NewT.putDoc hPutDoc :: Handle -> Doc -> IO () hPutDoc = NewT.hPutDoc empty :: Doc empty = New.emptyDoc char :: Char -> Doc char = New.pretty text :: String -> Doc text = New.pretty nest :: Int -> Doc -> Doc nest = New.nest line :: Doc line = New.line linebreak :: Doc linebreak = New.flatAlt New.line mempty group :: Doc -> Doc group = New.group softline :: Doc softline = New.softline softbreak :: Doc softbreak = New.group linebreak align :: Doc -> Doc align = New.align hang :: Int -> Doc -> Doc hang = New.hang indent :: Int -> Doc -> Doc indent = New.indent encloseSep :: Doc -> Doc -> Doc -> [Doc] -> Doc encloseSep = New.encloseSep list :: [Doc] -> Doc list = New.list tupled :: [Doc] -> Doc tupled = New.tupled semiBraces :: [Doc] -> Doc semiBraces = New.encloseSep New.lbrace New.rbrace New.semi (<+>), (<$>), (</>), (<$$>), (<//>) :: Doc -> Doc -> Doc (<+>) = (New.<+>) (<$>) = \x y -> x <> New.line <> y (</>) = \x y -> x <> softline <> y (<$$>) = \x y -> x <> linebreak <> y (<//>) = \x y -> x <> softbreak <> y hsep, vsep, fillSep, sep, hcat, vcat, fillCat, cat :: [Doc] -> Doc hsep = New.hsep vsep = New.vsep fillSep = New.fillSep sep = New.sep hcat = New.hcat vcat = New.vcat fillCat = New.fillCat cat = New.cat punctuate :: Doc -> [Doc] -> [Doc] punctuate = New.punctuate fill :: Int -> Doc -> Doc fill = New.fill fillBreak :: Int -> Doc -> Doc fillBreak = New.fillBreak enclose :: Doc -> Doc -> Doc -> Doc enclose = New.enclose squotes, dquotes, parens, angles, braces, brackets :: Doc -> Doc squotes = New.squotes dquotes = New.dquotes parens = New.parens angles = New.angles braces = New.braces brackets = New.brackets lparen, rparen, langle, rangle, lbrace, rbrace, lbracket, rbracket, squote, dquote, semi, colon, comma, space, dot, backslash, equals :: Doc lparen = New.lparen rparen = New.rparen langle = New.langle rangle = New.rangle lbrace = New.lbrace rbrace = New.rbrace lbracket = New.lbracket rbracket = New.rbracket squote = New.squote dquote = New.dquote semi = New.semi colon = New.colon comma = New.comma space = New.space dot = New.dot backslash = New.backslash equals = New.equals string :: String -> Doc string = New.pretty int :: Int -> Doc int = New.pretty integer :: Integer -> Doc integer = New.pretty float :: Float -> Doc float = New.pretty double :: Double -> Doc double = New.pretty rational :: Rational -> Doc rational = New.pretty . show renderPretty :: Float -> Int -> Doc -> SimpleDoc renderPretty ribbonFraction pageWidth = New.layoutPretty New.LayoutOptions { New.layoutPageWidth = New.AvailablePerLine pageWidth (realToFrac ribbonFraction) } renderCompact :: Doc -> SimpleDoc renderCompact = New.layoutCompact displayS :: SimpleDoc -> ShowS displayS sdoc = let rendered = NewT.renderLazy sdoc in (TL.unpack rendered ++) displayIO :: Handle -> SimpleDoc -> IO () displayIO = NewT.renderIO bool :: Bool -> Doc bool = New.pretty column :: (Int -> Doc) -> Doc column = New.column nesting :: (Int -> Doc) -> Doc nesting = New.nesting width :: Doc -> (Int -> Doc) -> Doc width = New.width
quchen/prettyprinter
prettyprinter-compat-wl-pprint/src/Text/PrettyPrint/Leijen.hs
bsd-2-clause
4,391
0
10
837
1,534
932
602
137
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QColormap.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QColormap ( QColormapMode, eDirect, eIndexed, eGray ) where import Foreign.C.Types 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 CQColormapMode a = CQColormapMode a type QColormapMode = QEnum(CQColormapMode Int) ieQColormapMode :: Int -> QColormapMode ieQColormapMode x = QEnum (CQColormapMode x) instance QEnumC (CQColormapMode Int) where qEnum_toInt (QEnum (CQColormapMode x)) = x qEnum_fromInt x = QEnum (CQColormapMode 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 -> QColormapMode -> 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 () eDirect :: QColormapMode eDirect = ieQColormapMode $ 0 eIndexed :: QColormapMode eIndexed = ieQColormapMode $ 1 eGray :: QColormapMode eGray = ieQColormapMode $ 2
keera-studios/hsQt
Qtc/Enums/Gui/QColormap.hs
bsd-2-clause
2,461
0
18
532
612
313
299
55
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE StandaloneDeriving #-} module Math.CF.Internal where import Data.Maybe (fromMaybe, listToMaybe) import Data.List (intersperse) import Data.Ratio import Data.Semigroup data CF a = Integral a => CF [a] deriving instance Eq (CF a) instance Show a => Show (CF a) where show (CF xs) = "[" ++ show (fromMaybe 0 (listToMaybe xs)) ++ "; " ++ concat (intersperse ", " (map show (drop 1 xs))) ++ "]" toCF' :: Integral a => (a, a) -> [a] -> [a] toCF' (n, d) acc = if d == 0 then acc else let q = n `div` d s = (n - (q * d)) in toCF' (d, s) (q:acc) toCF :: Integral a => (a, a) -> CF a toCF n = CF (reverse $ toCF' n []) -- | Convert from a 'CF' to a different representation, potentially subject to -- rounding errors and other evilness. unsafeFromCF :: (Integral a, Fractional b) => CF a -> b unsafeFromCF (CF []) = 0 unsafeFromCF (CF (x:xs)) = fromIntegral x + (1/unsafeFromCF (CF xs)) -- | For any invertable 2x2 matrix, we can obtain a Mobius transformation -- (specifically a homographic function) of the form @h(z) = (az + b)/(cz + d)@. data Mobius a = Mobius a a a a deriving (Eq, Functor, Show) instance Num a => Semigroup (Mobius a) where Mobius x1 x2 x3 x4 <> Mobius y1 y2 y3 y4 = Mobius (x1 * y1 + x2 * y3) (x2 * y1 + x2 * y3) (x3 * y2 + x3 * y4) (x4 * y2 + x4 * y4) instance Num a => Monoid (Mobius a) where mappend = (<>) mempty = Mobius 1 0 0 1 -- Identity 2x2 matrix -- | Determinant of a 'Mobius' representation determinant :: Num a => Mobius a -> a determinant (Mobius x1 x2 x3 x4) = x1 * x4 - x2 * x3
relrod/cfplayground
src/Math/CF/Internal.hs
bsd-2-clause
1,717
0
14
432
673
355
318
-1
-1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( makeApplication , getApplicationDev , makeFoundation ) where import Import import Settings import Yesod.Auth import Yesod.Default.Config import Yesod.Default.Main import Yesod.Default.Handlers import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev) import qualified Database.Persist.Store import Database.Persist.GenericSql (runMigration) import Network.HTTP.Conduit (newManager, def) -- 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 makeApplication conf = do foundation <- makeFoundation conf app <- toWaiAppPlain foundation return $ logWare app where logWare = if development then logStdoutDev else logStdout makeFoundation :: AppConfig DefaultEnv Extra -> IO App makeFoundation conf = do manager <- newManager def s <- staticSite dbconf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf) Database.Persist.Store.loadConfig >>= Database.Persist.Store.applyEnv p <- Database.Persist.Store.createPoolConfig (dbconf :: Settings.PersistConfig) Database.Persist.Store.runPool dbconf (runMigration migrateAll) p return $ App conf s p manager dbconf -- for yesod devel getApplicationDev :: IO (Int, Application) getApplicationDev = defaultDevelApp loader makeApplication where loader = loadConfig (configSettings Development) { csParseExtra = parseExtra }
tlaitinen/yesod-datatables
example/Application.hs
bsd-2-clause
2,094
0
11
393
367
202
165
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} -- | -- -- Utility for formatting @'Idea'@ data in accordance with the Code Climate -- spec: <https://github.com/codeclimate/spec> -- module CC ( printIssue , fromIdea ) where import Data.Aeson (ToJSON(..), (.=), encode, object) import Data.Char (toUpper) import Data.Text (Text) import qualified Data.Text as T import qualified Data.ByteString.Lazy.Char8 as C8 import Idea (Idea(..), Severity(..)) import qualified GHC.Types.SrcLoc as GHC import qualified GHC.Util as GHC data Issue = Issue { issueType :: Text , issueCheckName :: Text , issueDescription :: Text , issueContent :: Text , issueCategories :: [Text] , issueLocation :: Location , issueRemediationPoints :: Int } data Location = Location FilePath Position Position data Position = Position Int Int instance ToJSON Issue where toJSON Issue{..} = object [ "type" .= issueType , "check_name" .= issueCheckName , "description" .= issueDescription , "content" .= object [ "body" .= issueContent ] , "categories" .= issueCategories , "location" .= issueLocation , "remediation_points" .= issueRemediationPoints ] instance ToJSON Location where toJSON (Location path begin end) = object [ "path" .= path , "positions" .= object [ "begin" .= begin , "end" .= end ] ] instance ToJSON Position where toJSON (Position line column) = object [ "line" .= line , "column" .= column ] -- | Print an @'Issue'@ with trailing null-terminator and newline -- -- The trailing newline will be ignored, but makes the output more readable -- printIssue :: Issue -> IO () printIssue = C8.putStrLn . (<> "\0") . encode -- | Convert an hlint @'Idea'@ to a datatype more easily serialized for CC fromIdea :: Idea -> Issue fromIdea Idea{..} = Issue { issueType = "issue" , issueCheckName = "HLint/" <> T.pack (camelize ideaHint) , issueDescription = T.pack ideaHint , issueContent = content ideaFrom ideaTo <> listNotes ideaNote , issueCategories = categories ideaHint , issueLocation = fromSrcSpan ideaSpan , issueRemediationPoints = points ideaSeverity } where content from Nothing = T.unlines [ "Found" , "" , "```" , T.pack from , "```" , "" , "remove it." ] content from (Just to) = T.unlines [ "Found" , "" , "```" , T.pack from , "```" , "" , "Perhaps" , "" , "```" , T.pack to , "```" ] listNotes [] = "" listNotes notes = T.unlines $ [ "" , "Applying this change:" , "" ] ++ map (("* " <>) . T.pack . show) notes categories _ = ["Style"] points Ignore = 0 points Suggestion = basePoints points Warning = 5 * basePoints points Error = 10 * basePoints fromSrcSpan :: GHC.SrcSpan -> Location fromSrcSpan GHC.SrcSpan{..} = Location (locationFileName srcSpanFilename) (Position srcSpanStartLine' srcSpanStartColumn) (Position srcSpanEndLine' srcSpanEndColumn) where locationFileName ('.':'/':x) = x locationFileName x = x camelize :: String -> String camelize = concatMap capitalize . words capitalize :: String -> String capitalize [] = [] capitalize (c:rest) = toUpper c : rest -- "The baseline remediation points value is 50,000, which is the time it takes -- to fix a trivial code style issue like a missing semicolon on a single line, -- including the time for the developer to open the code, make the change, and -- confidently commit the fix. All other remediation points values are expressed -- in multiples of that Basic Remediation Point Value." basePoints :: Int basePoints = 50000
ndmitchell/hlint
src/CC.hs
bsd-3-clause
3,931
0
12
1,074
908
515
393
99
6
module Distribution.MacOSX.Common where import Data.List import System.FilePath import System.Directory -- | Mac OSX application information. data MacApp = MacApp { -- | Application name. This should be the name of the executable -- produced by Cabal's build stage. The app bundle produced will be -- @dist\/build\//appName/.app@, and the executable /appName/ will -- be copied to @Contents\/MacOSX\/@ in the bundle. appName :: String, -- | additional compiled executables that will be placed in the same -- directory as the main executable. Dependency chasing will also be -- done for these. (The difference to otherBins is just the location -- in the app bundle.) otherCompiledBins :: [String], -- | Path to icon file, to be copied to @Contents\/Resources\/@ in -- the app bundle. If omitted, no icon will be used. appIcon :: Maybe FilePath, -- | Path to /plist/ file ('property-list' of application metadata), -- to be copied to @Contents\/Info.plist@ in the app bundle. If -- omitted, and if 'appIcon' is specified, a basic default plist -- will be used. appPlist :: Maybe FilePath, -- | Other resources to bundle in the application, e.g. image files, -- etc. Each will be copied to @Contents\/Resources\/@, with the -- proviso that if the resource path begins with @resources\/@, it -- will go to a /relative/ subdirectory of @Contents\/Resources\/@. -- For example, @images/splash.png@ will be copied to -- @Contents\/Resources\/splash.png@, whereas -- @resources\/images\/splash.png@ will be copied to -- @Contents\/Resources\/resources\/images\/splash.png@. -- -- Bundled resources may be referred to from your program relative -- to your executable's path (which may be computed, e.g., using -- Audrey Tang's FindBin package). resources :: [FilePath], -- | Other binaries to bundle in the application, e.g. other -- executables from your project, or third-party programs. Each -- will be copied to a relative sub-directory of -- @Contents\/Resources\/@ in the bundle. For example, -- @\/usr\/bin\/ftp@ would be copied to -- @Contents\/Resources\/usr\/bin\/ftp@ in the app. -- -- Like 'resources', bundled binaries may be referred to from your -- program relative to your executable's path (which may be -- computed, e.g., using Audrey Tang's FindBin package). otherBins :: [FilePath], -- | Controls inclusion of library dependencies for executable and -- 'otherBins'; see below. appDeps :: ChaseDeps } -- | Application bundles may carry their own copies of shared -- libraries, which enables distribution of applications which 'just -- work, out of the box' in the absence of static linking. For -- example, a wxHaskell app can include the wx library (and /its/ -- dependencies, recursively), meaning end users do not need to -- install wxWidgets in order to use the app. -- -- This data type controls this process: if dependency chasing is -- activated, then the app's executable and any 'otherBins' are -- examined for their dependencies, recursively (usually with some -- exceptions - see below), the dependencies are copied into the app -- bundle, and any references to each library are updated to point to -- the copy. -- -- (The process is transparent to the programmer, i.e. requires no -- modification to code. In case anyone is interested: @otool@ is -- used to discover a binary's library dependencies; each library is -- copied to a relative sub-directory of @Contents\/Frameworks\/@ in -- the app bundle (e.g. @\/usr\/lib\/libFoo.a@ becomes -- @Contents\/Frameworks\/usr\/lib\/libFoo.a@); finally, -- @install_name_tool@ is used to update dependency references to -- point to the new version.) data ChaseDeps = -- | Do not include any dependencies - a sensible default if not -- distributing your app. DoNotChase -- | Include any libraries which the executable and 'otherBins' -- depend on, excluding a default set which we would expect to be -- present on any machine running the same version of OSX on which -- the executable was built. (n.b.: Creation of application -- bundles which work transparently across different versions of -- OSX is currently beyond the scope of this package.) | ChaseWithDefaults -- | Include any libraries which the executable and 'otherBins' -- depend on, excluding a user-defined set. If you specify an -- empty exclusion list, then /all/ dependencies will be included, -- recursively, including various OSX Frameworks; /this/ -- /probably/ /isn't/ /ever/ /sensible/. The intended use, -- rather, is to allow extension of the default list, which can be -- accessed via 'defaultExclusions'. | ChaseWith Exclusions -- | Filter the dependencies by the given function. Includes dependencies -- (and follows them recursively), if the given function returns True -- when given the FilePath of the dependency. -- Implemented to give you full control over dependecy chasing. | FilterDeps DepsFilter -- | A list of exclusions to dependency chasing. Any library whose -- path contains any exclusion string /as a substring/ will be -- excluded when chasing dependencies. type Exclusions = [String] -- | Filtering function for dependency chasing. type DepsFilter = FilePath -> Bool -- | Default list of exclusions; excludes OSX standard frameworks, -- libgcc, etc. - basically things which we would expect to be present -- on any functioning OSX installation. defaultExclusions :: Exclusions defaultExclusions = ["/System/Library/Frameworks/", "/libSystem.", "/libgcc_s.", "/libobjc." ] isRoot :: MacApp -> FilePath -> Bool isRoot app path = path == appName app || path `elem` otherCompiledBins app -- | Compute item's path relative to app bundle root. pathInApp :: MacApp -> FilePath -> FilePath pathInApp app p | isRoot app p = "Contents/MacOS" </> p | p `elem` otherBins app = "Contents/Resources" </> relP | p `elem` resources app = let p' = if "resources/" `isPrefixOf` p then makeRelative "resources/" p else takeFileName p in "Contents/Resources" </> p' | otherwise = "Contents/Frameworks" </> relP where relP = makeRelative "/" p -- | looks up a library, if the given path is not already absolute. lookupLibrary :: FilePath -> IO FilePath lookupLibrary p = if isAbsolute p then return p else do mAbsPath <- searchInPaths macLibraryPaths p return $ case mAbsPath of Nothing -> error ("cannot find dependency: " ++ p) Just absPath -> absPath where searchInPaths :: [FilePath] -> FilePath -> IO (Maybe FilePath) searchInPaths [] _ = return Nothing searchInPaths (a : r) file = do exists <- doesFileExist (a </> file) if exists then return $ Just (a </> file) else searchInPaths r file -- | standard paths where libraries are looked up macLibraryPaths :: [FilePath] macLibraryPaths = "/Library/Frameworks" : "/System/Frameworks" : []
soenkehahn/cabal-macosx
Distribution/MacOSX/Common.hs
bsd-3-clause
7,077
0
14
1,438
633
379
254
59
5
module Main where import Data.Monoid import Options.Applicative.Simple import Statistics import Convert -- | Helper for lifting pure parsing functions into ReadM monad readMPure :: String -- ^ Name of argument for pretty error message -> (String -> Maybe a) -- ^ Function that parses the argument -> ReadM a -- ^ Optparse parser monad readMPure desc f = do s <- str case f s of Nothing -> fail $ "Unknown " ++ desc ++ " " ++ s Just v -> return v -- | How to parse ConvertFormat convertFormatR :: ReadM ConvertFormat convertFormatR = readMPure "format" readConvertFormat -- | How to parse BlpFormat blpFormatR :: ReadM BlpFormat blpFormatR = readMPure "blp format" readBlpFormat main :: IO () main = do (_,runCmd) <- simpleOptions ver headerDesc desc (pure ()) $ do addCommand "convert" "Converts given blp or folder with blps to PNG" convertFiles $ (<*>) helper $ ConvertOptions <$> strArgument (metavar "INPUT_PATH" <> help "input file or directory (batch mode)") <*> strArgument (metavar "OUTPUT_PATH" <> help "output file name or directory (need explicit format option)") <*> option convertFormatR (long "input-format" <> short 'i' <> value UnspecifiedFormat <> help "Input file format, if not specified tries to infer from input file name. Values: blp png jpg tiff gif bmp.") <*> option convertFormatR (long "format" <> short 'f' <> value UnspecifiedFormat <> help "Output file format, if not specified tries to infer from output file name. Values: blp png jpg tiff gif bmp.") <*> option auto (long "quality" <> short 'q' <> value 90 <> help "Quality level for formats with lossy compression (default 90)") <*> fmap not (switch (long "notPreserveStructure" <> short 'p' <> help "Will not produce subfolders while batch converting" )) <*> switch (long "shallow" <> short 's' <> help "Not look into subfolders while batch converting") <*> option blpFormatR (long "blpFormat" <> short 'b' <> value BlpJpeg <> help "Specifies what BLP internal format to use when converting to BLP. Values: jpg uncompressedWithAlpha uncompressedWithoutAlpha") <*> option auto (long "min-mipmap-size" <> value 1 <> help "Minimum size of mimmap side to include in resulted BLP file") addCommand "stats" "Collects statistics about BLP images in folder and saves examples of BLP's for each sample" (uncurry collectStatistics) $ (<*>) helper $ (,) <$> strArgument (metavar "DIRECTORY" <> help "Input folder that stores blps (subfolders are processed)") <*> strArgument (metavar "OUTPUT_PATH" <> help "Here blp samples would be stored") runCmd where ver = "0.1.0.0" headerDesc = "" desc = "Converting BLP1 Warcraft III format to/from PNG, JPEG, TGA, TIFF, BMP, GIF"
NCrashed/JuicyPixels-blp
blp2any/Main.hs
bsd-3-clause
2,757
0
23
534
589
283
306
37
2
module Data.Interface.Module ( -- * ModuleInterface ModuleInterface(..) , ModuleName , ExportName , ClassInstance(..) , makeModuleInterface , isLocal , findExport , unsafeFindExport -- , lookupOrigin , filterInterfaceNames -- ** Exports , Export , ExportElem , compileModuleExports , splitExports , module Data.Interface.Module.Diff , module Data.Interface.Module.Entity ) where import Data.Interface.Module.Interface import Data.Interface.Name ( ModuleName ) import Data.Interface.Module.Export ( ExportName, Export, ExportElem, splitExports ) import Data.Interface.Module.Diff import Data.Interface.Module.Entity
cdxr/haskell-interface
src/Data/Interface/Module.hs
bsd-3-clause
658
0
5
107
128
89
39
23
0
-- Run tests using the TCP transport. module Main where import TEST_SUITE_MODULE (tests) import Network.Transport.Test (TestTransport(..)) import Network.Transport.InMemory import Test.Framework (defaultMainWithArgs) import System.Environment (getArgs) main :: IO () main = do (transport, internals) <- createTransportExposeInternals ts <- tests TestTransport { testTransport = transport , testBreakConnection = \addr1 addr2 -> breakConnection internals addr1 addr2 "user error" } args <- getArgs -- Tests are time sensitive. Running the tests concurrently can slow them -- down enough that threads using threadDelay would wake up later than -- expected, thus changing the order in which messages were expected. -- Therefore we run the tests sequentially by passing "-j 1" to -- test-framework. This does not solve the issue but makes it less likely. -- -- The problem was first detected with -- 'Control.Distributed.Process.Tests.CH.testMergeChannels' -- in particular. defaultMainWithArgs ts ("-j" : "1" : args)
haskell-distributed/distributed-process
distributed-process-tests/tests/runInMemory.hs
bsd-3-clause
1,089
0
12
214
157
92
65
14
1
{-# LANGUAGE FlexibleContexts, QuasiQuotes #-} module Main where import Control.Applicative ((<$>)) import Control.Monad (forM_, when) import Data.Word import Data.Sequence (iterateN) import Data.Array.Repa (computeP, traverse, Z(..), (:.)(..), Array, U, DIM0, DIM1, DIM2, DIM3, (!), sumAllP, Source(..)) import Data.Array.Repa.Eval (Target(..)) import qualified Data.Array.Repa as R import qualified Data.Array.Repa.Eval as RE import Data.Array.Repa.Repr.ForeignPtr (fromForeignPtr, F) import Data.Array.Repa.IO.DevIL import Data.Array.Repa.Stencil import Data.Array.Repa.Stencil.Dim2 import qualified Data.Vector.Unboxed as U import Data.List (sort) import Data.Minc import Data.Minc.Raw import Data.Minc.Raw.Base import Data.Minc.Utils import Data.Minc.Types import System.IO (IOMode (..)) import Foreign.C.String (peekCString) import Foreign.Marshal.Alloc (free, mallocBytes) import Foreign.Marshal.Array import Foreign.Ptr (castPtr, Ptr(..)) import Foreign.C.Types (CDouble(..)) import Foreign.Storable (sizeOf) import qualified Foreign.ForeignPtr as FP import qualified Data.HashSet as HS import Text.Printf (printf) type RepaRet3 a = Array F DIM3 a -- | Take a slice in the first dimension of a 3D array. slice0 :: (Monad m, Source r e, Target r e) => Array r DIM3 e -> Int -> m (Array r DIM2 e) slice0 a i = computeP $ traverse a (\(e0 :. e1 :. _) -> (e0 :. e1)) (\f (Z :. j :. k) -> f (Z :. i :. j :. k)) -- | Take a slice in the second dimension of a 3D array. slice1 :: (Monad m, Source r e, Target r e) => Array r DIM3 e -> Int -> m (Array r DIM2 e) slice1 a j = computeP $ traverse a (\(e0 :. _ :. e2) -> (e0 :. e2)) (\f (Z :. i :. k) -> f (Z :. i :. j :. k)) -- | Take a slice in the third dimension of a 3D array. slice2 :: (Monad m, Source r e, Target r e) => Array r DIM3 e -> Int -> m (Array r DIM2 e) slice2 a k = computeP $ traverse a (\(e0 :. e1 :. _) -> (e0 :. e1)) (\f (Z :. i :. j) -> f (Z :. i :. j :. k)) writeSlice :: Source r Word8 => Array r DIM2 Word8 -> FilePath -> IO () writeSlice a f = do grey <- Grey <$> RE.copyP a :: IO Image runIL $ writeImage f grey cross4 = [stencil2| 0 1 0 1 1 1 0 1 0 |] dilate :: Source r Word8 => Array r DIM2 Word8 -> Array PC5 DIM2 Word8 dilate a = mapStencil2 (BoundConst 0) cross4 a {- dilateN n a = if n > 0 then do a' <- dilate a -- a'' <- dilateN (n-1) a' return undefined else return a -} main :: IO () main = do let small = "/scratch/small.mnc" (_, volumePtr) <- miopen_volume small (mincIOMode ReadMode) print volumePtr dimensionCount <- runAccess "miget_volume_dimension_count " small $ chk $ miget_volume_dimension_count volumePtr Minc_Dim_Class_Any Minc_Dim_Attr_All print ("dimensionCount", dimensionCount) let Right dimensionCount' = dimensionCount Right dimensionPtrs <- runAccess "miget_volume_dimensions " small $ chk $ miget_volume_dimensions volumePtr Minc_Dim_Class_Any Minc_Dim_Attr_All Minc_Dim_Order_File dimensionCount' print $ take dimensionCount' dimensionPtrs Right dimensionSizes <- runAccess "miget_dimension_sizes " small $ chk $ miget_dimension_sizes dimensionPtrs dimensionCount' print $ take dimensionCount' dimensionSizes Right separations <- runAccess "miget_dimension_separations" small $ chk $ miget_dimension_separations dimensionPtrs Minc_Voxel_Order_File dimensionCount' print $ take dimensionCount' separations Right starts <- runAccess "miget_dimension_starts" small $ chk $ miget_dimension_starts dimensionPtrs Minc_Voxel_Order_File dimensionCount' print $ take dimensionCount' starts forM_ [0..(dimensionCount'-1)] $ \dimIdx -> do Right z <- runAccess "miget_dimension_name" small $ chk $ miget_dimension_name (dimensionPtrs !! dimIdx) name <- peekCString z print $ ("miget_dimension_name", dimIdx, name) free z -- FIXME We need to free this ourselves? Right mtype <- runAccess "miget_data_type" small $ chk $ miget_data_type volumePtr print $ ("mtype", mtype) Right nrBytes <- runAccess "miget_hyperslab_size" small $ chk $ miget_hyperslab_size Minc_Double dimensionCount' (take dimensionCount' dimensionSizes) print $ ("nrBytes", nrBytes) d <- mallocBytes (fromIntegral nrBytes) blah <- miget_real_value_hyperslab volumePtr Minc_Double -- we want doubles to be returned [0, 0, 0] (take dimensionCount' dimensionSizes) d -- Manual here, we know that it will be a let d_double = castPtr d :: Ptr CDouble let nrVoxels = foldl (*) 1 $ take dimensionCount' dimensionSizes asArray <- peekArray nrVoxels d_double -- Check a few non-zero values: print $ take 40 $ filter (> 0) asArray -- Find the unique set of non-zero values: let values = sort . HS.toList . HS.fromList . filter (> 0) . map realToFrac $ asArray :: [Double] print ("values", values) -- Cast ??? to Repa? fptr <- FP.newForeignPtr_ d_double :: IO (FP.ForeignPtr CDouble) let [i, j, k] = take dimensionCount' dimensionSizes repa = fromForeignPtr (Z :. i :. j :. k) fptr :: RepaRet3 CDouble -- Look at a value: print $ repa ! (Z :. 0 :. 0 :. 0) let v0 = realToFrac (values !! 21) :: CDouble print ("v0", v0) let flabert :: CDouble -> Word8 flabert x = if x > v0 - (0.05 :: CDouble) && x < v0 + (0.05 :: CDouble) then 255 else 0 -- Extract to Word8.... zzz <- computeP $ traverse repa id (\f (Z :. i :. j :. k) -> flabert $ f (Z :. i :. j :. k)) :: IO (Array U DIM3 Word8) -- This is probably overflowing! zzzsum <- sumAllP zzz print ("zzzsum", zzzsum) -- From the tutorial: https://wiki.haskell.org/Numeric_Haskell:_A_Repa_Tutorial#Building_shapes let nrI = dimensionSizes !! 0 nrJ = dimensionSizes !! 1 nrK = dimensionSizes !! 2 forM_ [0..(nrJ - 1)] $ \j -> do -- The change-of-shape function ((\e0 :. _ :. e2) -> ...) has to be right, otherwise we get rubbish. -- I had blindly copied the example which had (\(e0 :. _ :. e2) -> (e0 :. e2)) and all the sums below -- ended up being zero. blah <- slice1 zzz j blahSum <- sumAllP blah :: IO Word8 print (j, blahSum) -- Dump a greyscale image. The slice is a 'U' (Unboxed) but we need an 'F' (foreign) for the Grey function. grey <- Grey <$> RE.copyP blah :: IO Image runIL $ writeImage (printf "grey_%03d.png" j) grey -- Try out some stencils. oneSlice <- slice1 zzz 7 let oneSliceDilated = dilate oneSlice -- oneSliceDilatedAFewTimes = dilateN 20 oneSlice oneSliceDilated' <- computeP oneSliceDilated :: IO (Array U DIM2 Word8) -- writeSlice oneSliceDilated' "oneSliceDilated.png" -- Volume properties? Need more tests. volProp <- runAccess "minew_volume_props" "(none)" $ chk minew_volume_props case volProp of Left err -> print err Right volProp' -> do x <- runAccess "mifree_volume_props" "(none)" $ chk $ mifree_volume_props volProp' print x -- {#fun mifree_volume_props{ `()' } -> `Int' #} free d y <- miclose_volume volumePtr print y
carlohamalainen/hminc
examples/example1.hs
bsd-3-clause
8,808
0
17
3,222
2,194
1,141
1,053
134
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LiberalTypeSynonyms #-} module LuaObjects(module LuaObjects) where import qualified Data.Map.Strict as Map import qualified Data.IntMap.Strict as IntMap import qualified Data.Vector.Mutable as MV import qualified Data.Vector as V import qualified Data.Vector.Unboxed as UV import qualified Data.Vector.Generic as GV import qualified Data.Foldable as F import Control.Monad.ST as ST --import Control.Monad.ST.Lazy import Data.Primitive.Array import Data.Maybe import Data.IORef import System.IO.Unsafe import qualified Data.Sequence as Sequence import Control.Monad as Monad import LuaLoader import Parser as P import Debug.Trace import Control.Exception.Base data LuaObject = LONil | LONumber { lvNumber :: {-# UNPACK #-} !Double} | LOString { loString :: !String} | LOTable {-# UNPACK #-} !(IORef LTable) | LOFunction { loFunction :: !LuaFunctionInstance} | LOBool !Bool | LOUserData {-TODO-} | LOThread {-TODO-} deriving (Eq, Show, Ord) type LuaRef = IORef LuaObject instance Show (IORef LuaObject) where show o = show (unsafePerformIO $ readLR o) instance Ord (IORef LuaObject) where (<=) a b = error "Order not defined for LuaRef" instance Show (IORef LTable) where show r = "Some LuaTable" instance Ord (IORef LTable) where (<=) = error "Can't compare table references" readLR :: LuaRef -> IO LuaObject readLR = readIORef updateLR :: LuaRef -> (LuaObject -> LuaObject) -> IO () updateLR = modifyIORef' writeLR :: LuaRef -> LuaObject -> IO () writeLR = writeIORef getConst :: LuaConstList -> Int -> LuaObject getConst (LuaConstList size constants) pos = let constant = constants V.! pos in luaConstToObject constant luaConstToObject :: LuaConst -> LuaObject luaConstToObject LuaNil = LONil luaConstToObject (LuaConstNumber value) = LONumber value luaConstToObject (LuaConstBool bool) = LOBool bool luaConstToObject (LuaConstString (LuaString l s)) = LOString s -- | Associates each Key with a Lua Object. newtype LTable = LTable (Map.Map LuaObject LuaObject) deriving (Eq, Show, Ord) -- | getTableElement table key -> value getTableElement :: LTable -> LuaObject -> LuaObject getTableElement (LTable m) k | k == LONil = LONil | Map.member k m = m Map.! k | otherwise = LONil -- | setTableElement table key value -> changed table -- If the key is nil ignore the operation -- If the value is nil remove the element from the map -- Otherwise update/add the entry setTableElement :: LTable -> LuaObject -> LuaObject -> LTable setTableElement table@(LTable m) k v | isNil k = table | isNil v = LTable $ Map.delete k m | otherwise = LTable $ Map.insert k v m createTable = LTable Map.empty :: LTable ppLuaInstruction :: LuaInstruction -> String ppLuaInstruction inst = let attributes = show (op inst) : map show [ ra inst :: Int, rb inst, rc inst, rsbx inst, rsbx inst + 131070, rbx inst] :: [String] namedAtt = flip zip attributes $ fmap (++":") ["op", "ra", "rb", "rc", "rsbx", "csbx" , "rbx"] :: [(String, String)] in foldl (\a b -> a ++ " " ++ uncurry (++) b) "" namedAtt isNil :: LuaObject -> Bool isNil o | o == LONil = True | otherwise = False ltoNumber :: LuaObject -> LuaObject ltoNumber n@(LONumber _) = n ltoNumber (LOString s) = LONumber $ read s ltoNumber x = error $ unsafePerformIO $ do print "ltoNumber: Can't convert to number" print x return "toNumber conversion error" ltoBool :: LuaObject -> LuaObject ltoBool LONil = LOBool True ltoBool (LOBool False) = LOBool False ltoBool _ = LOBool True lLen :: LuaObject -> LuaObject lLen (LOString s) = LONumber $ fromIntegral $ length s lLen _ = error "Length of objects other than String not implemented" ltoString :: LuaObject -> LuaObject ltoString LONil = LOString "nil" ltoString (LOBool True) = LOString "true" ltoString (LOBool False) = LOString "false" ltoString (LONumber x) = LOString $ show x ltoString x@(LOString s) = x ltoString x = error $ unsafePerformIO $ do putStrLn "Error:Can't convert type to string" print x return "Conversion error" lgetFunctionHeader :: LuaObject -> LuaFunctionHeader lgetFunctionHeader = funcHeader . loFunction --functionInstance -> FunctionIndex -> FunctionHeader lgetPrototype :: LuaObject -> Int -> LuaFunctionHeader lgetPrototype = --let LuaFunctionHeader name startLine endLine upvalueCount parameterCount varargFlag stackSize instructions constList functionList instPosList localList upvalueList = functionHeader --in (!!) . P.fhFunctions . funcHeader . loFunction --functionList !! pos -- | Create a function instance based on prototype, doesn't set up passed parameters/upvalues/varargs linstantiateFunction :: LuaFunctionHeader -> IO LuaObject linstantiateFunction functionHeader@(LuaFunctionHeader name startLine endLine upvalueCount parameterCount varargFlag stackSize instructions constList functionList instPosList localList upvalueList) = do stack <- createStack $ fromIntegral stackSize :: IO LVStack upvalues <- newIORef $ FuncUpvalueStack stack [] let functionInstance = LuaFunctionInstance upvalues (lilInstructions instructions) constList functionHeader V.empty return $ LOFunction functionInstance -- | Set the variable argument list based on the given list of values -- lsetvarargs function arguments -> updatedFunction lsetvarargs :: LuaObject -> [LuaObject] -> LuaObject lsetvarargs (LOFunction func) parameters = let varargs = V.fromList parameters in LOFunction (func {funcVarargs = varargs}) -- upvalues closure) lgetArgCount :: LuaObject -> Int lgetArgCount (LOFunction func) = let (LuaFunctionHeader _ _ _ upvalCount parCount varargFlags _ _ _ _ _ _ _) = funcHeader func in fromIntegral parCount --varargFlag != 0 represents a variable argument function lisVarArg :: LuaObject -> Bool lisVarArg (LOFunction func) = 0 /= (P.fhVarargFlag . funcHeader) func lgetMaxStackSize :: LuaObject -> Int lgetMaxStackSize = fromIntegral . fhMaxStacksize . funcHeader . loFunction --lgetMaxStackSize (LOFunction (LuaFunctionInstance _ _ _ fh _ _)) = -- let (LuaFunctionHeader _ _ _ upvalCount parCount varargFlags stackSize _ _ _ _ _ _) = fh -- in fromIntegral stackSize ladd :: LuaObject -> LuaObject -> LuaObject ladd (LONumber x) (LONumber y) = LONumber $ x + y -- | sub a b = a - b lsub :: LuaObject -> LuaObject -> LuaObject lsub (LONumber x) (LONumber y) = LONumber $ x - y lmul :: LuaObject -> LuaObject -> LuaObject lmul (LONumber x) (LONumber y) = LONumber $ x * y ldiv :: LuaObject -> LuaObject -> LuaObject ldiv (LONumber x) (LONumber y) = LONumber $ x / y -- | a % b == a - math.floor(a/b)*b lmod :: LuaObject -> LuaObject -> LuaObject lmod (LONumber a) (LONumber b) = LONumber $ a - b * (fromIntegral $ floor (a/b) :: Double) lpow :: LuaObject -> LuaObject -> LuaObject lpow (LONumber x) (LONumber y) = LONumber $ (**) x y -- | Lua Stack wrapper TODO: Performance optimization class LuaStack l where createStack :: Int -> IO l setElement :: l -> Int -> LuaObject -> IO l getElement :: l -> Int -> IO LuaObject getRange :: l -> Int -> Int -> IO [LuaObject]--get elements stack[a..b] setRange :: l -> Int -> [LuaObject] -> IO l --place given objects in stack starting at position p stackSize :: l -> IO Int setStackSize :: l -> Int -> IO l pushObjects :: l -> [LuaObject] -> IO l fromList :: [LuaObject] -> IO l fromList objs = do s <- createStack 0; pushObjects s objs shrink :: l -> Int -> IO l --shrink stack by x elements if possible shrink s x = do currentSize <- stackSize s; setStackSize s (currentSize - x) toList :: l -> IO [LuaObject] toList l = do count <- stackSize l; mapM (getElement l) [0..count -1] setRange stack n objects = foldM (\s (k, v) -> setElement s k v) stack $ zip [n..] objects --requires stack to be at least (n - 1) in size type LVStack = IORef (MV.IOVector LuaObject) showLVStack :: LVStack -> IO () showLVStack stack = do size <- stackSize stack let f = getElement stack mapM_ (f >=> print) [0..size - 1] instance Show LVStack where show x = "LVStack (Show Not implemented)" --unsafePerformIO $ do ss <- stackSize x; show <$> mapM (getElement x) [0 .. ss] --"LVStack [not implemented]" instance LuaStack LVStack where createStack size = newIORef =<< MV.replicate size LONil setElement stack i v = do s <- readIORef stack :: IO (MV.IOVector LuaObject) MV.unsafeWrite s i v return stack getElement s i = readIORef s >>= flip MV.unsafeRead i getRange s from to = do stack <- readIORef s; mapM (MV.read stack) [from..to] setRange s start objects = do stack <- readIORef s; zipWithM_ (MV.write stack) [start..] objects; return s stackSize s = MV.length <$> readIORef s :: IO Int setStackSize sref size = do stack <- readIORef sref; case compare (MV.length stack) size of Prelude.EQ -> return sref Prelude.LT -> do let ss = MV.length stack writeIORef sref =<< MV.grow stack (size - ss) return sref; Prelude.GT -> do writeIORef sref $ MV.slice 0 (size-1) stack return sref --grows stack accordingly pushObjects sref objects = do --grow the vector by the number of elements, then put them into the vector let l = length objects --s <- stack :: IO LVStack stack <- readIORef sref let ss = MV.length stack writeIORef sref =<< MV.grow stack l setRange sref ss objects fromList objects = do stack <- createStack $ length objects setRange stack 0 objects shrink sref by = do stack <- readIORef sref let newSize = MV.length stack - by writeIORef sref $ MV.slice 0 newSize stack return sref toList sref = do stack <- readIORef sref mapM (MV.read stack) [0.. MV.length stack -1] instance Show (IO LVStack) where show s = unsafePerformIO $ do s <- s; return $ show s type LuaParameterList = [LuaObject] data FuncUpvalueList = FuncUpvalueStack { uvStack :: LVStack , uvUpvalues :: [UVRef] } deriving (Eq, Show)-- Stack, list of indixed data UVRef = UVRef { uvrStack :: LVStack , uvrOffset :: !Int } deriving (Eq, Show) type LuaFunctionUpvalues = IORef FuncUpvalueList instance Show LuaFunctionUpvalues where show x = unsafePerformIO $ do uv <- readIORef x return $ "(IORef (" ++ show uv ++ ") )" setUVStack :: LuaFunctionUpvalues -> LVStack -> IO () setUVStack uvr stack = do uv <- readIORef uvr :: IO FuncUpvalueList writeIORef uvr $ uv { uvStack = stack } getUpvalue :: FuncUpvalueList -> Int -> UVRef getUpvalue (FuncUpvalueStack stack upvalues) index = upvalues !! index readUpvalue :: LuaFunctionUpvalues -> Int -> IO LuaObject readUpvalue funcUpval index = do uv <- (`getUpvalue` index) <$> readIORef funcUpval :: IO UVRef getElement (uvrStack uv) (uvrOffset uv) :: IO LuaObject setUpvalues :: Traversable t => LuaFunctionUpvalues -> t UVRef -> IO LuaFunctionUpvalues setUpvalues uvref upvalues = do modifyIORef' uvref $ \x -> x { uvUpvalues = F.toList upvalues } return uvref -- | Update the value of the upvalue at the specific index writeUpvalue :: LuaFunctionUpvalues -> Int -> LuaObject -> IO LuaFunctionUpvalues writeUpvalue uvref index value = do upvalues <- readIORef uvref let uv = getUpvalue upvalues index setElement (uvrStack uv :: LVStack) (uvrOffset uv :: Int) (value :: LuaObject) return uvref -- | Instance of an executable function -- LuaFunctionInstance stack instructions constants funcPrototypes upvalues arguments data LuaFunctionInstance = LuaFunctionInstance { funcUpvalues :: LuaFunctionUpvalues , funcInstructions :: !(UV.Vector LuaInstruction) --List of op codes , funcConstants :: !LuaConstList --List of constants , funcHeader :: !LuaFunctionHeader --Function prototypes , funcVarargs :: !(V.Vector LuaObject) --ArgumentList for varargs, starting with index 0 } | HaskellFunctionInstance { funcName :: !String --name , funcFunc :: LVStack -> IO LVStack } deriving () instance Eq LuaFunctionInstance where (==) a b = error "Broken typeclass for function instances" instance Ord LuaFunctionInstance where (<=) a b = error "Broken typeclass for function instances" instance Show LuaFunctionInstance where show (HaskellFunctionInstance name _) = "(HaskellFunction: " ++ name ++ ")" show (LuaFunctionInstance upvalues _ constList fh varargs ) = "(Lua Function: " ++ show ( uvStack (unsafePerformIO $ readIORef upvalues) , constList, fh, varargs, "upvalues not shown") ++ ")" -- | Get line at which instruction was defined -- function pc -> line getLine :: LuaFunctionInstance -> Int -> Int getLine = (!!) . fhInstPos . funcHeader data LuaExecutionState = LuaStateSuspended | LuaStateRunning | LuaStateDead deriving (Eq, Show, Ord, Enum) -- | LuaExecutionThread currentInstance prevInstance position state -- Wraps a function AND execution frame, so jumping into another function also means replacing the current executin thread as well -- LuaExecutionThread func precThread pc state callInfo data LuaExecutionThread = LuaExecutionThread { execFunctionInstance :: !LuaFunctionInstance, execPrevInst :: LuaExecutionThread, execCurrentPC :: !Int, execRunningState :: !LuaExecutionState, execCallInfo :: !LuaCallInfo, execStop :: {-# UNPACK #-} !Int } -- | 1: Stop VM, 0: Continue running deriving (Eq, Ord) instance Show LuaExecutionThread where show x = if execStop x == 0 then "(LuaExecutionThread (" ++ show (execFunctionInstance x, execCurrentPC x, execRunningState x, execCallInfo x, execStop x) ++ "))" else "(LuaExecutionThread_Top " ++ (show . execFunctionInstance) x ++ ")" -- | Contains information about arguments passed to the function data LuaCallInfo = LuaCallInfo { lciParams :: ![LuaObject] } deriving(Show, Eq, Ord) callInfo :: [LuaObject] -> LuaCallInfo callInfo = LuaCallInfo callInfoEmpty = LuaCallInfo [] getContainedFunctionHeader :: LuaExecutionThread -> Int -> LuaFunctionHeader getContainedFunctionHeader = getIndexedFunction . funcHeader . execFunctionInstance
AndreasPK/yalvm
src/LuaObjects.hs
bsd-3-clause
14,075
0
17
2,672
4,059
2,086
1,973
308
1
{-# LANGUAGE OverloadedStrings #-} module Data.Aeson.Forms.Combinators ( -- * Working with forms Form , Result (..) , runForm , withForm , runAction -- * Form fields , (.:) , (.:!) , (.:?) , (>->) -- * Validators , text , string , int , integer , integral , float , double , realFloat , bool , object , array , opt -- * Lower level helpers , success , failed , errors ) where import Control.Applicative ((<$>)) import Control.Lens.Fold ((^?)) import Data.Aeson (Value (..)) import Data.Aeson.Lens (key) import qualified Data.HashMap.Strict as HashMap import Data.Scientific (floatingOrInteger) import Data.Text (Text) ------------------------------------------------------------------------------ import Data.Aeson.Forms.Internal.Types ------------------------------------------------------------------------------ -- | Runs the form against the provided JSON 'Value'. runForm :: Maybe Value -> Form m a -> m (Result a) runForm json (Form action) = action json ------------------------------------------------------------------------------ -- | Takes a function that extracts a field from a JSON 'Value' and turns it -- into a 'Form'. withForm :: Monad m => (Maybe Value -> m (Result a)) -> Form m a withForm = Form ------------------------------------------------------------------------------ -- | Runs the action from a form against the given JSON 'Value', yielding a -- result. runAction :: Form m a -> Maybe Value -> m (Result a) runAction (Form action) = action ------------------------------------------------------------------------------ -- | Combines a 'Field' validator and a function from a -> b to be (>->) :: Monad m => (Field -> Form m a) -> (a -> b) -> Field -> Form m b (>->) validator f field = fmap f (validator field) {-# INLINE (>->) #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Text'. If field is not a string validation -- fails with the message "Must be a string". See also `string`. text :: Monad m => Field -- ^ The name of the field to extract -> Form m Text text field = withForm go where go (Just (String t)) = success t go _ = failed $ errors field ["Must be a string"] {-# INLINE text #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'String'. If field is not a string validation -- fails with the message "Must be a string". See also `text`. string :: Monad m => Field -- ^ The name of the field to extract -> Form m String string field = withForm go where go (Just (String t)) = success $ show t go _ = failed $ errors field ["Must be a string"] {-# INLINE string #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Int'. If field is not an integer validation -- fails with the message "Must be an integer". See also `integer` and -- `integral`. int :: Monad m => Field -- ^ The name of the field to extract -> Form m Int int = integral {-# INLINE int #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Integer'. If field is not an integer validation -- fails with the message "Must be an integer". See also `int` and -- `integral`. integer :: Monad m => Field -- ^ The name of the field to extract -> Form m Integer integer = integral {-# INLINE integer #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Integral i => i'. If field is not an integer -- validation fails with the message "Must be an integer". See also `int` -- and `integer`. integral :: (Monad m, Integral i) => Field -- ^ The name of the field to extract -> Form m i integral field = withForm go where go (Just (Number scientific)) = convert scientific go _ = wrongType convert scientific = case (floatingOrInteger scientific :: Integral i => Either Double i) of Left _ -> wrongType Right num -> success num wrongType = failed $ errors field ["Must be an integer"] {-# INLINE integral #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Double'. If field is not a number validation -- fails with the message "Must be an number". See also `float` and -- `realFloat`. double :: Monad m => Field -- ^ The name of the field to extract -> Form m Double double = realFloat {-# INLINE double #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Double'. If field is not a number validation -- fails with the message "Must be an number". See also `double` and -- `realFloat`. float :: Monad m => Field -- ^ The name of the field to extract -> Form m Float float = realFloat {-# INLINE float #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'RealFloat r => r'. If field is not a number -- validation fails with the message "Must be a number ". See also `float` -- and `double`. realFloat :: (Monad m, RealFloat r) => Field -- ^ The name of the field to extract -> Form m r realFloat field = withForm go where go (Just (Number scientific)) = convert scientific go _ = wrongType convert scientific = case (floatingOrInteger scientific :: RealFloat r => Either r Integer) of Left num -> success num Right num -> success $ fromIntegral num wrongType = failed $ errors field ["Must be a number"] {-# INLINE realFloat #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Bool'. If field is not a boolean validation -- fails with the message "Must be a boolean". bool :: Monad m => Field -- ^ The name of the field to extract -> Form m Bool bool field = withForm go where go (Just (Bool t)) = success t go _ = failed $ errors field ["Must be a boolean"] {-# INLINE bool #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Object'. If field is not an object validation -- fails with the message "Must be an object". object :: Monad m => Field -- ^ The name of the field to extract -> Form m Value object field = withForm go where go (Just obj@(Object _)) = success obj go _ = failed $ errors field ["Must be an object"] {-# INLINE object #-} ------------------------------------------------------------------------------ -- | Extracts a field of type 'Object'. If field is not an object validation -- fails with the message "Must be an array". array :: Monad m => Field -- ^ The name of the field to extract -> Form m Value array field = withForm go where go (Just ary@(Array _)) = success ary go _ = failed $ errors field ["Must be an array"] {-# INLINE array #-} ------------------------------------------------------------------------------ -- | Converts a validator that returns 'a' into one that returns 'Maybe' a. If -- the value is not present 'Nothing' will be returned. opt :: Monad m => (Field -> Form m a) -- ^ The validator to run if field is present -> Field -- ^ The name of the field to extract -> Form m (Maybe a) opt validate field = withForm go where go (Just Null) = success Nothing go json@(Just _) = do result <- runAction (validate field) json return $ Just <$> result go (Nothing) = success Nothing {-# INLINE opt #-} ------------------------------------------------------------------------------ -- | Extracts a required field and runs the given validator against it. If the -- field is absent validation fails with the message "Is required". (.:) :: Monad m => Field -- ^ The name of the field to extract -> (Field -> Form m a) -- ^ Validation function to run against the field -> Form m a (.:) field validate = withForm go where go (Just json) = case json ^? key field of Just value -> runAction (validate field) $ Just value Nothing -> missing go Nothing = missing missing = failed $ errors field ["Is required"] infixr 5 .: {-# INLINE (.:) #-} ------------------------------------------------------------------------------ -- | Extracts a field and runs the given validator against it. The validator -- is responsible for handling the field being 'Nothing'. (.:!) :: Monad m => Field -- ^ The name of the field to extract -> (Field -> Form m a) -- ^ Validation function to run against the field -> Form m a (.:!) field validate = withForm go where go (Just json) = go' $ json ^? key field go Nothing = go' Nothing go' = runAction (validate field) infixr 5 .:! {-# INLINE (.:!) #-} ------------------------------------------------------------------------------ -- | Extracts a field and runs the given validator against it. If the field is -- absent it returns nothing. (.:?) :: Monad m => Field -- ^ The name of the field to extract -> (Field -> Form m (Maybe a)) -- ^ Validation function to run against the field -> Form m (Maybe a) (.:?) field validate = withForm go where go (Just json) | Just value <- json ^? key field = runAction (validate field) (Just value) go _ = success Nothing infixr 5 .:? {-# INLINE (.:?) #-} ------------------------------------------------------------------------------ -- | Return parsed value from a successful parse. success :: Monad m => a -> m (Result a) success = return . Success {-# INLINE success #-} ------------------------------------------------------------------------------ -- | Return validation errors for a failed parse. failed :: Monad m => Errors -> m (Result a) failed = return . Failed {-# INLINE failed #-} ------------------------------------------------------------------------------ -- | Return 'Errors' for the given field and validation error messages. errors :: Field -- ^ Field that failed validation -> [Text] -- ^ List of validation error messages -> Errors errors field errs = Errors $ HashMap.singleton field errs {-# INLINE errors #-}
lukerandall/aeson-forms
src/Data/Aeson/Forms/Combinators.hs
bsd-3-clause
10,634
0
13
2,459
1,929
1,039
890
177
3
module Main where import Ivory.Tower.Config import Ivory.OS.FreeRTOS.Tower.STM32 import LDrive.Platforms import LDrive.Tests.PWM (app) main :: IO () main = compileTowerSTM32FreeRTOS testplatform_stm32 p $ app (stm32config_clock . testplatform_stm32) testplatform_pwm testplatform_leds where p topts = getConfig topts testPlatformParser
sorki/odrive
test/PWMTest.hs
bsd-3-clause
376
0
8
75
87
49
38
11
1
{-# Language PolyKinds, DataKinds, TemplateHaskell, TypeFamilies, GADTs, TypeOperators, RankNTypes, FlexibleContexts, UndecidableInstances, FlexibleInstances, ScopedTypeVariables, MultiParamTypeClasses, OverlappingInstances, KindSignatures, DeriveDataTypeable #-} module Oxymoron.Description.Symbol where import Data.Singletons import Language.Haskell.TH import Data.Data singletons [d| data Nat = Zero | Succ Nat deriving (Show, Eq, Ord) data AChar = CA | CB | CC | CD | CE | CF | CG | CH | CI | CJ | CK | CL | CM | CN | CO | CP | CQ | CR | CS | CT | CU | CV | CW | CX | CY | CZ deriving (Read, Show, Eq, Enum, Ord) data Symbol = Symbol [AChar] deriving (Read, Show, Eq) data SymbolList = SymbolList [Symbol] proj :: Bool -> Bool -> Bool proj True True = True proj True False = True proj False True = False proj False False = False leqNat :: Nat -> Nat -> Bool leqNat Zero _ = True leqNat (Succ _) Zero = False leqNat (Succ a) (Succ b) = leqNat a b leqAChar :: AChar -> AChar -> Bool leqAChar CA CA = False leqAChar CA CB = True leqAChar CA CC = True leqAChar CA CD = True leqAChar CA CE = True leqAChar CA CF = True leqAChar CA CG = True leqAChar CA CH = True leqAChar CA CI = True leqAChar CA CJ = True leqAChar CA CK = True leqAChar CA CL = True leqAChar CA CM = True leqAChar CA CN = True leqAChar CA CO = True leqAChar CA CP = True leqAChar CA CQ = True leqAChar CA CR = True leqAChar CA CS = True leqAChar CA CT = True leqAChar CA CU = True leqAChar CA CV = True leqAChar CA CW = True leqAChar CA CX = True leqAChar CA CY = True leqAChar CA CZ = True leqAChar CB CA = False leqAChar CB CB = False leqAChar CB CC = True leqAChar CB CD = True leqAChar CB CE = True leqAChar CB CF = True leqAChar CB CG = True leqAChar CB CH = True leqAChar CB CI = True leqAChar CB CJ = True leqAChar CB CK = True leqAChar CB CL = True leqAChar CB CM = True leqAChar CB CN = True leqAChar CB CO = True leqAChar CB CP = True leqAChar CB CQ = True leqAChar CB CR = True leqAChar CB CS = True leqAChar CB CT = True leqAChar CB CU = True leqAChar CB CV = True leqAChar CB CW = True leqAChar CB CX = True leqAChar CB CY = True leqAChar CB CZ = True leqAChar CC CA = False leqAChar CC CB = False leqAChar CC CC = False leqAChar CC CD = True leqAChar CC CE = True leqAChar CC CF = True leqAChar CC CG = True leqAChar CC CH = True leqAChar CC CI = True leqAChar CC CJ = True leqAChar CC CK = True leqAChar CC CL = True leqAChar CC CM = True leqAChar CC CN = True leqAChar CC CO = True leqAChar CC CP = True leqAChar CC CQ = True leqAChar CC CR = True leqAChar CC CS = True leqAChar CC CT = True leqAChar CC CU = True leqAChar CC CV = True leqAChar CC CW = True leqAChar CC CX = True leqAChar CC CY = True leqAChar CC CZ = True leqAChar CD CA = False leqAChar CD CB = False leqAChar CD CC = False leqAChar CD CD = False leqAChar CD CE = True leqAChar CD CF = True leqAChar CD CG = True leqAChar CD CH = True leqAChar CD CI = True leqAChar CD CJ = True leqAChar CD CK = True leqAChar CD CL = True leqAChar CD CM = True leqAChar CD CN = True leqAChar CD CO = True leqAChar CD CP = True leqAChar CD CQ = True leqAChar CD CR = True leqAChar CD CS = True leqAChar CD CT = True leqAChar CD CU = True leqAChar CD CV = True leqAChar CD CW = True leqAChar CD CX = True leqAChar CD CY = True leqAChar CD CZ = True leqAChar CE CA = False leqAChar CE CB = False leqAChar CE CC = False leqAChar CE CD = False leqAChar CE CE = False leqAChar CE CF = True leqAChar CE CG = True leqAChar CE CH = True leqAChar CE CI = True leqAChar CE CJ = True leqAChar CE CK = True leqAChar CE CL = True leqAChar CE CM = True leqAChar CE CN = True leqAChar CE CO = True leqAChar CE CP = True leqAChar CE CQ = True leqAChar CE CR = True leqAChar CE CS = True leqAChar CE CT = True leqAChar CE CU = True leqAChar CE CV = True leqAChar CE CW = True leqAChar CE CX = True leqAChar CE CY = True leqAChar CE CZ = True leqAChar CF CA = False leqAChar CF CB = False leqAChar CF CC = False leqAChar CF CD = False leqAChar CF CE = False leqAChar CF CF = False leqAChar CF CG = True leqAChar CF CH = True leqAChar CF CI = True leqAChar CF CJ = True leqAChar CF CK = True leqAChar CF CL = True leqAChar CF CM = True leqAChar CF CN = True leqAChar CF CO = True leqAChar CF CP = True leqAChar CF CQ = True leqAChar CF CR = True leqAChar CF CS = True leqAChar CF CT = True leqAChar CF CU = True leqAChar CF CV = True leqAChar CF CW = True leqAChar CF CX = True leqAChar CF CY = True leqAChar CF CZ = True leqAChar CG CA = False leqAChar CG CB = False leqAChar CG CC = False leqAChar CG CD = False leqAChar CG CE = False leqAChar CG CF = False leqAChar CG CG = False leqAChar CG CH = True leqAChar CG CI = True leqAChar CG CJ = True leqAChar CG CK = True leqAChar CG CL = True leqAChar CG CM = True leqAChar CG CN = True leqAChar CG CO = True leqAChar CG CP = True leqAChar CG CQ = True leqAChar CG CR = True leqAChar CG CS = True leqAChar CG CT = True leqAChar CG CU = True leqAChar CG CV = True leqAChar CG CW = True leqAChar CG CX = True leqAChar CG CY = True leqAChar CG CZ = True leqAChar CH CA = False leqAChar CH CB = False leqAChar CH CC = False leqAChar CH CD = False leqAChar CH CE = False leqAChar CH CF = False leqAChar CH CG = False leqAChar CH CH = False leqAChar CH CI = True leqAChar CH CJ = True leqAChar CH CK = True leqAChar CH CL = True leqAChar CH CM = True leqAChar CH CN = True leqAChar CH CO = True leqAChar CH CP = True leqAChar CH CQ = True leqAChar CH CR = True leqAChar CH CS = True leqAChar CH CT = True leqAChar CH CU = True leqAChar CH CV = True leqAChar CH CW = True leqAChar CH CX = True leqAChar CH CY = True leqAChar CH CZ = True leqAChar CI CA = False leqAChar CI CB = False leqAChar CI CC = False leqAChar CI CD = False leqAChar CI CE = False leqAChar CI CF = False leqAChar CI CG = False leqAChar CI CH = False leqAChar CI CI = False leqAChar CI CJ = True leqAChar CI CK = True leqAChar CI CL = True leqAChar CI CM = True leqAChar CI CN = True leqAChar CI CO = True leqAChar CI CP = True leqAChar CI CQ = True leqAChar CI CR = True leqAChar CI CS = True leqAChar CI CT = True leqAChar CI CU = True leqAChar CI CV = True leqAChar CI CW = True leqAChar CI CX = True leqAChar CI CY = True leqAChar CI CZ = True leqAChar CJ CA = False leqAChar CJ CB = False leqAChar CJ CC = False leqAChar CJ CD = False leqAChar CJ CE = False leqAChar CJ CF = False leqAChar CJ CG = False leqAChar CJ CH = False leqAChar CJ CI = False leqAChar CJ CJ = False leqAChar CJ CK = True leqAChar CJ CL = True leqAChar CJ CM = True leqAChar CJ CN = True leqAChar CJ CO = True leqAChar CJ CP = True leqAChar CJ CQ = True leqAChar CJ CR = True leqAChar CJ CS = True leqAChar CJ CT = True leqAChar CJ CU = True leqAChar CJ CV = True leqAChar CJ CW = True leqAChar CJ CX = True leqAChar CJ CY = True leqAChar CJ CZ = True leqAChar CK CA = False leqAChar CK CB = False leqAChar CK CC = False leqAChar CK CD = False leqAChar CK CE = False leqAChar CK CF = False leqAChar CK CG = False leqAChar CK CH = False leqAChar CK CI = False leqAChar CK CJ = False leqAChar CK CK = False leqAChar CK CL = True leqAChar CK CM = True leqAChar CK CN = True leqAChar CK CO = True leqAChar CK CP = True leqAChar CK CQ = True leqAChar CK CR = True leqAChar CK CS = True leqAChar CK CT = True leqAChar CK CU = True leqAChar CK CV = True leqAChar CK CW = True leqAChar CK CX = True leqAChar CK CY = True leqAChar CK CZ = True leqAChar CL CA = False leqAChar CL CB = False leqAChar CL CC = False leqAChar CL CD = False leqAChar CL CE = False leqAChar CL CF = False leqAChar CL CG = False leqAChar CL CH = False leqAChar CL CI = False leqAChar CL CJ = False leqAChar CL CK = False leqAChar CL CL = False leqAChar CL CM = True leqAChar CL CN = True leqAChar CL CO = True leqAChar CL CP = True leqAChar CL CQ = True leqAChar CL CR = True leqAChar CL CS = True leqAChar CL CT = True leqAChar CL CU = True leqAChar CL CV = True leqAChar CL CW = True leqAChar CL CX = True leqAChar CL CY = True leqAChar CL CZ = True leqAChar CM CA = False leqAChar CM CB = False leqAChar CM CC = False leqAChar CM CD = False leqAChar CM CE = False leqAChar CM CF = False leqAChar CM CG = False leqAChar CM CH = False leqAChar CM CI = False leqAChar CM CJ = False leqAChar CM CK = False leqAChar CM CL = False leqAChar CM CM = False leqAChar CM CN = True leqAChar CM CO = True leqAChar CM CP = True leqAChar CM CQ = True leqAChar CM CR = True leqAChar CM CS = True leqAChar CM CT = True leqAChar CM CU = True leqAChar CM CV = True leqAChar CM CW = True leqAChar CM CX = True leqAChar CM CY = True leqAChar CM CZ = True leqAChar CN CA = False leqAChar CN CB = False leqAChar CN CC = False leqAChar CN CD = False leqAChar CN CE = False leqAChar CN CF = False leqAChar CN CG = False leqAChar CN CH = False leqAChar CN CI = False leqAChar CN CJ = False leqAChar CN CK = False leqAChar CN CL = False leqAChar CN CM = False leqAChar CN CN = False leqAChar CN CO = True leqAChar CN CP = True leqAChar CN CQ = True leqAChar CN CR = True leqAChar CN CS = True leqAChar CN CT = True leqAChar CN CU = True leqAChar CN CV = True leqAChar CN CW = True leqAChar CN CX = True leqAChar CN CY = True leqAChar CN CZ = True leqAChar CO CA = False leqAChar CO CB = False leqAChar CO CC = False leqAChar CO CD = False leqAChar CO CE = False leqAChar CO CF = False leqAChar CO CG = False leqAChar CO CH = False leqAChar CO CI = False leqAChar CO CJ = False leqAChar CO CK = False leqAChar CO CL = False leqAChar CO CM = False leqAChar CO CN = False leqAChar CO CO = False leqAChar CO CP = True leqAChar CO CQ = True leqAChar CO CR = True leqAChar CO CS = True leqAChar CO CT = True leqAChar CO CU = True leqAChar CO CV = True leqAChar CO CW = True leqAChar CO CX = True leqAChar CO CY = True leqAChar CO CZ = True leqAChar CP CA = False leqAChar CP CB = False leqAChar CP CC = False leqAChar CP CD = False leqAChar CP CE = False leqAChar CP CF = False leqAChar CP CG = False leqAChar CP CH = False leqAChar CP CI = False leqAChar CP CJ = False leqAChar CP CK = False leqAChar CP CL = False leqAChar CP CM = False leqAChar CP CN = False leqAChar CP CO = False leqAChar CP CP = False leqAChar CP CQ = True leqAChar CP CR = True leqAChar CP CS = True leqAChar CP CT = True leqAChar CP CU = True leqAChar CP CV = True leqAChar CP CW = True leqAChar CP CX = True leqAChar CP CY = True leqAChar CP CZ = True leqAChar CQ CA = False leqAChar CQ CB = False leqAChar CQ CC = False leqAChar CQ CD = False leqAChar CQ CE = False leqAChar CQ CF = False leqAChar CQ CG = False leqAChar CQ CH = False leqAChar CQ CI = False leqAChar CQ CJ = False leqAChar CQ CK = False leqAChar CQ CL = False leqAChar CQ CM = False leqAChar CQ CN = False leqAChar CQ CO = False leqAChar CQ CP = False leqAChar CQ CQ = False leqAChar CQ CR = True leqAChar CQ CS = True leqAChar CQ CT = True leqAChar CQ CU = True leqAChar CQ CV = True leqAChar CQ CW = True leqAChar CQ CX = True leqAChar CQ CY = True leqAChar CQ CZ = True leqAChar CR CA = False leqAChar CR CB = False leqAChar CR CC = False leqAChar CR CD = False leqAChar CR CE = False leqAChar CR CF = False leqAChar CR CG = False leqAChar CR CH = False leqAChar CR CI = False leqAChar CR CJ = False leqAChar CR CK = False leqAChar CR CL = False leqAChar CR CM = False leqAChar CR CN = False leqAChar CR CO = False leqAChar CR CP = False leqAChar CR CQ = False leqAChar CR CR = False leqAChar CR CS = True leqAChar CR CT = True leqAChar CR CU = True leqAChar CR CV = True leqAChar CR CW = True leqAChar CR CX = True leqAChar CR CY = True leqAChar CR CZ = True leqAChar CS CA = False leqAChar CS CB = False leqAChar CS CC = False leqAChar CS CD = False leqAChar CS CE = False leqAChar CS CF = False leqAChar CS CG = False leqAChar CS CH = False leqAChar CS CI = False leqAChar CS CJ = False leqAChar CS CK = False leqAChar CS CL = False leqAChar CS CM = False leqAChar CS CN = False leqAChar CS CO = False leqAChar CS CP = False leqAChar CS CQ = False leqAChar CS CR = False leqAChar CS CS = False leqAChar CS CT = True leqAChar CS CU = True leqAChar CS CV = True leqAChar CS CW = True leqAChar CS CX = True leqAChar CS CY = True leqAChar CS CZ = True leqAChar CT CA = False leqAChar CT CB = False leqAChar CT CC = False leqAChar CT CD = False leqAChar CT CE = False leqAChar CT CF = False leqAChar CT CG = False leqAChar CT CH = False leqAChar CT CI = False leqAChar CT CJ = False leqAChar CT CK = False leqAChar CT CL = False leqAChar CT CM = False leqAChar CT CN = False leqAChar CT CO = False leqAChar CT CP = False leqAChar CT CQ = False leqAChar CT CR = False leqAChar CT CS = False leqAChar CT CT = False leqAChar CT CU = True leqAChar CT CV = True leqAChar CT CW = True leqAChar CT CX = True leqAChar CT CY = True leqAChar CT CZ = True leqAChar CU CA = False leqAChar CU CB = False leqAChar CU CC = False leqAChar CU CD = False leqAChar CU CE = False leqAChar CU CF = False leqAChar CU CG = False leqAChar CU CH = False leqAChar CU CI = False leqAChar CU CJ = False leqAChar CU CK = False leqAChar CU CL = False leqAChar CU CM = False leqAChar CU CN = False leqAChar CU CO = False leqAChar CU CP = False leqAChar CU CQ = False leqAChar CU CR = False leqAChar CU CS = False leqAChar CU CT = False leqAChar CU CU = False leqAChar CU CV = True leqAChar CU CW = True leqAChar CU CX = True leqAChar CU CY = True leqAChar CU CZ = True leqAChar CV CA = False leqAChar CV CB = False leqAChar CV CC = False leqAChar CV CD = False leqAChar CV CE = False leqAChar CV CF = False leqAChar CV CG = False leqAChar CV CH = False leqAChar CV CI = False leqAChar CV CJ = False leqAChar CV CK = False leqAChar CV CL = False leqAChar CV CM = False leqAChar CV CN = False leqAChar CV CO = False leqAChar CV CP = False leqAChar CV CQ = False leqAChar CV CR = False leqAChar CV CS = False leqAChar CV CT = False leqAChar CV CU = False leqAChar CV CV = False leqAChar CV CW = True leqAChar CV CX = True leqAChar CV CY = True leqAChar CV CZ = True leqAChar CW CA = False leqAChar CW CB = False leqAChar CW CC = False leqAChar CW CD = False leqAChar CW CE = False leqAChar CW CF = False leqAChar CW CG = False leqAChar CW CH = False leqAChar CW CI = False leqAChar CW CJ = False leqAChar CW CK = False leqAChar CW CL = False leqAChar CW CM = False leqAChar CW CN = False leqAChar CW CO = False leqAChar CW CP = False leqAChar CW CQ = False leqAChar CW CR = False leqAChar CW CS = False leqAChar CW CT = False leqAChar CW CU = False leqAChar CW CV = False leqAChar CW CW = False leqAChar CW CX = True leqAChar CW CY = True leqAChar CW CZ = True leqAChar CX CA = False leqAChar CX CB = False leqAChar CX CC = False leqAChar CX CD = False leqAChar CX CE = False leqAChar CX CF = False leqAChar CX CG = False leqAChar CX CH = False leqAChar CX CI = False leqAChar CX CJ = False leqAChar CX CK = False leqAChar CX CL = False leqAChar CX CM = False leqAChar CX CN = False leqAChar CX CO = False leqAChar CX CP = False leqAChar CX CQ = False leqAChar CX CR = False leqAChar CX CS = False leqAChar CX CT = False leqAChar CX CU = False leqAChar CX CV = False leqAChar CX CW = False leqAChar CX CX = False leqAChar CX CY = True leqAChar CX CZ = True leqAChar CY CA = False leqAChar CY CB = False leqAChar CY CC = False leqAChar CY CD = False leqAChar CY CE = False leqAChar CY CF = False leqAChar CY CG = False leqAChar CY CH = False leqAChar CY CI = False leqAChar CY CJ = False leqAChar CY CK = False leqAChar CY CL = False leqAChar CY CM = False leqAChar CY CN = False leqAChar CY CO = False leqAChar CY CP = False leqAChar CY CQ = False leqAChar CY CR = False leqAChar CY CS = False leqAChar CY CT = False leqAChar CY CU = False leqAChar CY CV = False leqAChar CY CW = False leqAChar CY CX = False leqAChar CY CY = False leqAChar CY CZ = True leqAChar CZ CA = False leqAChar CZ CB = False leqAChar CZ CC = False leqAChar CZ CD = False leqAChar CZ CE = False leqAChar CZ CF = False leqAChar CZ CG = False leqAChar CZ CH = False leqAChar CZ CI = False leqAChar CZ CJ = False leqAChar CZ CK = False leqAChar CZ CL = False leqAChar CZ CM = False leqAChar CZ CN = False leqAChar CZ CO = False leqAChar CZ CP = False leqAChar CZ CQ = False leqAChar CZ CR = False leqAChar CZ CS = False leqAChar CZ CT = False leqAChar CZ CU = False leqAChar CZ CV = False leqAChar CZ CW = False leqAChar CZ CX = False leqAChar CZ CY = False leqAChar CZ CZ = False leqSymbol :: Symbol -> Symbol -> Bool leqSymbol (Symbol []) (Symbol _) = False leqSymbol (Symbol (x:_)) (Symbol []) = True leqSymbol (Symbol (x:xs)) (Symbol (y:ys)) = proj (leqAChar x y) (leqSymbol (Symbol xs) (Symbol ys)) --write the one for symbol insert :: Symbol -> [Symbol] -> [Symbol] insert n [] = [n] insert n (h:t) = if leqSymbol n h then (n:h:t) else h:(insert n t) insertionSort :: [Symbol] -> [Symbol] insertionSort [] = [] insertionSort (h:t) = insert h (insertionSort t) --prefined symbols until I get a quasiquoter or something color = Symbol [CC, CO, CL, CO, CR] position = Symbol [CP, CO, CS, CI, CT, CI, CO, CN] |] -- Conversions to any from Integers fromNat :: Nat -> Integer fromNat Zero = 0 fromNat (Succ n) = (fromNat n) + 1 toNat :: Integer -> Nat toNat 0 = Zero toNat n | n > 0 = Succ (toNat (n - 1)) toNat _ = error "Converting negative to Nat"
jfischoff/oxymoron
src/Oxymoron/Description/Symbol.hs
bsd-3-clause
20,139
0
10
6,780
138
74
64
723
1
{-# LANGUAGE OverloadedStrings #-} import Control.Applicative ((<$>)) import Control.Monad (mzero) import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as L import Data.Text (Text) import Network.Riak import Snap.Core import Snap.Http.Server -- create a new datatype which is a message data Msg = Msg Text deriving (Show) -- Make it an instance which can be converted from JSON, with the possibility -- of failure. instance FromJSON Msg where parseJSON (Object v) = Msg <$> v .: "message" parseJSON _ = mzero -- Also make it an instance which can be converted to JSON. instance ToJSON Msg where toJSON (Msg s) = object [ "message" .= s] -- Make it an instance of resolvable instance Resolvable Msg -- create a new msg msg = Msg "Welcome to a brave new world." serve :: Config Snap a -> IO () serve config = httpServe config $ route [ ("/", writeBS "Hello") ] myClient :: Client myClient = Client { host = "127.0.0.1" , port = "8081" , clientID = L.empty } main :: IO () main = do -- connect to riak conn <- connect myClient -- add a msg to the database new_msg <- put conn "messages" "abc" Nothing msg One One serve defaultConfig
hdgarrood/snugio
examples/RiakResource.hs
bsd-3-clause
1,345
0
9
404
308
169
139
30
1
{-# OPTIONS_GHC -Wall #-} module Homework.C.Golf where -- Exercise 1 Hopscotch skips :: [a] -> [[a]] skips xs = let indexed = zip [1..length xs] xs build (i, _) = filter (\(j, _) -> j `mod` i == 0) indexed extract built = map snd built in map (extract . build) indexed -- Exercise 2 Local maxima localMaxima :: [Integer] -> [Integer] localMaxima xs@(x:y:z:_) = (if y > x && y > z then [y] else []) ++ (localMaxima (drop 1 xs)) localMaxima _ = [] -- Exercise 3 Histogram histogram :: [Integer] -> String histogram xs = let buckets = [0,1,2,3,4,5,6,7,8,9] -- List with the number of occurences for each integer (0-9) frequences = map (\i -> length (filter ((==) i) xs)) buckets -- List of tuples (integer, frequence) representing the histogram pairs = zip buckets frequences -- "Height" of the histogram is 2 lines (for the integers and "="s) -- plus the maximum frequence height = 2 + (foldl max 0 frequences) -- Start by building a "flipped" version of the histogram, i.e.: -- ["0=* ", "1=**", etc.] visualize (i, n) = show i ++ "=" ++ replicate n '*' ++ replicate (height - n) ' ' flipped = map visualize pairs -- "Expand" the flipped version to an intermediate representation: -- [["0=* ", "1=**"], ["=* ", "=**"], ["* ", "**"], etc.] expanded = take height (iterate (map (drop 1)) flipped) -- ..so we can take the first item of each sublist and create the lines: -- ["01", "==", "**", etc.] concatFirsts l = foldl (++) "" (map (take 1) l) reversed = map concatFirsts expanded -- Which we reverse and join with "\n" in unlines (reverse reversed)
nicolashery/cis194
src/Homework/C/Golf.hs
bsd-3-clause
1,701
0
16
433
500
275
225
25
2
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.AmountOfMoney.CA.Corpus ( corpus ) where import Data.String import Prelude import Duckling.AmountOfMoney.Types import Duckling.Locale import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale CA Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (simple Dollar 10) [ "$10" , "10$" , "deu dolars" , "deu dòlars" ] , examples (simple Dollar 10000) [ "$10.000" , "10K$" , "$10k" ] , examples (simple USD 1.23) [ "USD1,23" ] , examples (simple EUR 20) [ "20€" , "20 euros" , "20 Euro" , "20 Euros" , "EUR 20" , "vint euros" ] , examples (simple EUR 29.99) [ "EUR29,99" , "29,99 euros" , "29,99 €" , "29,99€" ] , examples (simple Pound 9) [ "£9" , "nou lliures" , "9 lliures" ] ,examples (simple Pound 1) [ "£1" , "una lliura" , "1 lliura" ] , examples (simple GBP 3.01) [ "GBP3,01" , "GBP 3,01" , "3 gbp 1 cèntims" , "3 gbp i 1 cèntims" ] , examples (simple PTS 15) [ "15 Pt" , "15pta" , "15Ptas" ] , examples (between Dollar (10, 20)) [ "entre 10 i 20 dòlars" , "des de $10 fins a $20" , "10$ - 20 dolars" , "10 - 20 $" ] , examples (under Dollar 10) [ "menys de 10 dolars" , "no més de 10$" ] , examples (above Dollar 10) [ "no menys de 10 dòlars" , "més de 10$" ] ]
facebookincubator/duckling
Duckling/AmountOfMoney/CA/Corpus.hs
bsd-3-clause
2,234
0
10
976
412
240
172
64
1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-orphans #-} module ChainedModelTests where import TestHarness () import Test.Tasty.TH --import Test.Tasty.QuickCheck as QC import Test.Tasty.HUnit import Model import Evidence import Observations chained_model_test_group = $(testGroupGenerator) raining = fact "rain" :: Evidence String Bool wet = fact "wet" :: Evidence String Bool slippery = fact "slippery" :: Evidence String Bool rain_causes_wet = Causally raining wet wet_causes_slippery = Causally wet slippery rain_causes_wet_causes_slippery = Multiple [rain_causes_wet, wet_causes_slippery] case_given_wet_causing_spillery_we_cant_conclude_slippery_from_rain = eval_causalmodel [raining] wet_causes_slippery @?= (conclude $ [raining]) case_rain_causes_wet_causes_slippery_manually_iterated = eval_causalmodel (observations_toList (eval_causalmodel [raining] model)) model @?= (conclude $ [raining, wet, slippery]) where model = rain_causes_wet_causes_slippery case_rain_causes_wet_causes_slippery = eval_causalmodel [raining] model @?= (conclude $ [raining, wet, slippery]) where model = rain_causes_wet_causes_slippery
jcberentsen/causality
tests/ChainedModelTests.hs
bsd-3-clause
1,208
0
11
156
246
139
107
25
1
module Cloud.AWS.EC2.Types.AvailabilityZone ( AvailabilityZone(..) , AvailabilityZoneMessage ) where import Data.Text (Text) data AvailabilityZone = AvailabilityZone { zoneName :: Text , zoneState :: Text , zoneRegionName :: Text , zoneMessageSet :: [AvailabilityZoneMessage] } deriving (Show, Read, Eq) type AvailabilityZoneMessage = Text
worksap-ate/aws-sdk
Cloud/AWS/EC2/Types/AvailabilityZone.hs
bsd-3-clause
377
0
9
77
88
56
32
11
0
{-# LANGUAGE RecursiveDo #-} module Main where import Reflex import Reflex.Gloss.Scene import Reflex.Monad.Time import Reflex.Animation import Reflex.Monad import Graphics.Gloss import Widgets renderCanvas :: Vector -> [Picture] -> Picture renderCanvas (sx, sy) drawings = mconcat [ color black $ rectangleWire sx sy , mconcat drawings ] canvas :: Reflex t => Vector -> Scene t () canvas size = do drawings <- hold [] never target <- targetRect (constant size) render $ renderCanvas <$> pure size <*> drawings widget :: Reflex t => Scene t () widget = canvas (300, 300) main = playSceneGraph display background frequency widget where display = InWindow "Scribble1" (600, 600) (0, 0) background = white frequency = 30
Saulzar/scribble
src/Scribble1.hs
bsd-3-clause
774
0
10
169
256
135
121
24
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-} module Data.ECS.Entity where import Control.Lens.Extra import Control.Monad.State import Control.Monad.Reader import Control.Monad.Trans.Control import System.Random import Data.ECS.Types import qualified Data.HashSet as Set data Persistence = Transient | Persistent deriving (Eq, Show) newEntityID :: MonadIO m => m EntityID newEntityID = liftIO randomIO spawnEntity :: (MonadBaseControl IO m, MonadState ECS m, MonadIO m) => ReaderT EntityID m () -> m EntityID spawnEntity = spawnTransientEntity spawnEntity_ :: (MonadBaseControl IO m, MonadState ECS m, MonadIO m) => ReaderT EntityID m () -> m () spawnEntity_ = void . spawnEntity spawnPersistentEntity :: (MonadBaseControl IO m, MonadState ECS m, MonadIO m) => ReaderT EntityID m () -> m EntityID spawnPersistentEntity = spawnEntityWithPersistence Persistent spawnTransientEntity :: (MonadBaseControl IO m, MonadState ECS m, MonadIO m) => ReaderT EntityID m () -> m EntityID spawnTransientEntity = spawnEntityWithPersistence Transient spawnEntityWithPersistence :: (MonadBaseControl IO m, MonadState ECS m, MonadIO m) => Persistence -> ReaderT EntityID m () -> m EntityID spawnEntityWithPersistence persistence entityDef = do entityID <- newEntityID runReaderT entityDef entityID activateEntity persistence entityID return entityID isEntityPersistent :: MonadState ECS m => EntityID -> m Bool isEntityPersistent entityID = Set.member entityID <$> use wldPersistentEntities makeEntityPersistent :: MonadState ECS m => EntityID -> m () makeEntityPersistent entityID = wldPersistentEntities %= (Set.insert entityID) removeEntity :: (MonadState ECS m, MonadIO m) => EntityID -> m () removeEntity entityID = do library <- use wldComponentLibrary forM_ library (\ComponentInterface{..} -> inEntity entityID ciRemoveComponent) wldPersistentEntities %= Set.delete entityID deriveComponents :: (MonadIO m, MonadState ECS m, MonadBaseControl IO m) => EntityID -> m () deriveComponents entityID = use wldComponentLibrary >>= mapM_ (\ComponentInterface{..} -> forM_ ciDeriveComponent (inEntity entityID)) -- | Registers an entity in the list of all entities, and -- converts inert properties into live ones activateEntity :: (MonadIO m, MonadBaseControl IO m, MonadState ECS m) => Persistence -> EntityID -> m () activateEntity persistence entityID = do when (persistence == Persistent) $ do makeEntityPersistent entityID deriveComponents entityID
lukexi/extensible-ecs
src/Data/ECS/Entity.hs
bsd-3-clause
2,681
0
11
488
742
376
366
51
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Distribution.OSX.InstallerScript ( installerScript , writeInstallerScript , installerScriptToString , InstallerScript ) where import Data.Maybe import Distribution.PackageDescription.Configuration import Text.XML.HXT.Arrow ------------------------------------------------------------------------ -- exports ------------------------------------------------------------------------ data InstallerScript = InstallerScript { is_title :: String , is_background :: Maybe String , is_welcome :: Maybe String , is_readme :: Maybe String , is_license :: Maybe String , is_conclusion :: Maybe String , is_pkgFileNames :: [(String,Int)] } ------------------------------------------------------------------------ -- | Populate an InstallerScript object with the given values. installerScript :: String -- ^ package title -> Maybe String -- ^ background image to use in the installer -- (FIXME: currently ignored) -> Maybe String -- ^ welcome blurb -> Maybe String -- ^ readme blurb -> Maybe String -- ^ license blurb -> Maybe String -- ^ conclusion blurb -> [(String,Int)] -- ^ list of .pkg files to -- include, along with their -- installed sizes -> InstallerScript installerScript = InstallerScript ------------------------------------------------------------------------ -- | Write a populated installer script to a file. writeInstallerScript :: String -- ^ file to write the output to -> InstallerScript -- ^ the values for the installer script -> IO () writeInstallerScript file is = runX ( mkInstallerScript is >>> writeDocument [(a_indent, v_1)] file ) >> return () ------------------------------------------------------------------------ -- | Render a populated installer script into a string. installerScriptToString :: InstallerScript -> IO String installerScriptToString is = runX ( mkInstallerScript is >>> writeDocumentToString [(a_indent, v_1)] ) >>= return . concat ------------------------------------------------------------------------ -- local functions ------------------------------------------------------------------------ ------------------------------------------------------------------------ simpleTag :: (ArrowXml a) => String -> String -> a n XmlTree simpleTag tagName text = mkelem tagName [] [txt text] ------------------------------------------------------------------------ mkTitle :: ArrowXml a => String -> a n XmlTree mkTitle = simpleTag "title" ------------------------------------------------------------------------ mkOptions :: (ArrowXml a) => a n XmlTree mkOptions = mkelem "options" [ sattr "customize" "never" , sattr "allow-external-scripts" "no" , sattr "rootVolumeOnly" "false"] [] ------------------------------------------------------------------------ blurbAttrs :: (ArrowXml a) => [a n XmlTree] blurbAttrs = [ sattr "language" "en" , sattr "mime-type" "text/plain" ] ------------------------------------------------------------------------ blurb :: (ArrowXml a) => String -> String -> a n XmlTree blurb tagName s = mkelem tagName blurbAttrs [cdata s] ------------------------------------------------------------------------ mkReadme :: (ArrowXml a) => String -> a n XmlTree mkReadme = blurb "readme" ------------------------------------------------------------------------ mkWelcome :: (ArrowXml a) => String -> a n XmlTree mkWelcome = blurb "welcome" ------------------------------------------------------------------------ mkLicense :: (ArrowXml a) => String -> a n XmlTree mkLicense = blurb "license" ------------------------------------------------------------------------ mkConclusion :: (ArrowXml a) => String -> a n XmlTree mkConclusion = blurb "conclusion" ------------------------------------------------------------------------ cdata :: (ArrowXml cat) => String -> cat a XmlTree cdata = (>>> mkCdata) . arr . const ------------------------------------------------------------------------ mkLine :: (ArrowXml a) => String -> a n XmlTree mkLine choiceId = mkelem "line" [sattr "choice" choiceId] [] ------------------------------------------------------------------------ mkChoicesOutline :: (ArrowXml a) => [String] -> a n XmlTree mkChoicesOutline choiceIds = mkelem "choices-outline" [] (map mkLine choiceIds) ------------------------------------------------------------------------ mkChoice :: (ArrowXml a) => String -> String -> String -> a n XmlTree mkChoice iD title pkgref = mkelem "choice" [ sattr "id" iD , sattr "title" title , sattr "start_visible" "false" ] [ mkelem "pkg-ref" [sattr "id" pkgref] [] ] ------------------------------------------------------------------------ mkPkgRef :: (ArrowXml a) => String -> String -> [Char] -> a n XmlTree mkPkgRef iD installKBytes pkgFileName = mkelem "pkg-ref" [ sattr "id" iD , sattr "installKBytes" installKBytes , sattr "version" "" , sattr "auth" "Root" ] [ txt $ "#" ++ pkgFileName ] ------------------------------------------------------------------------ installerScriptHead :: (ArrowXml a) => [a n XmlTree] -> a n XmlTree installerScriptHead body = root [] [ mkelem "installer-script" [ sattr "minSpecVersion" "1.000000" ] body ] ------------------------------------------------------------------------ mkInstallerScript :: (ArrowXml a) => InstallerScript -> a n XmlTree mkInstallerScript is = installerScriptHead $ concat [ [ mkTitle (is_title is) ] , catMaybes [ (is_welcome is) >>= Just . mkWelcome , (is_readme is) >>= Just . mkReadme , (is_license is) >>= Just . mkLicense , (is_conclusion is) >>= Just . mkConclusion ] , [ choicesOutline ] , choices , pkgRefs ] where pkgFiles = is_pkgFileNames is n = length pkgFiles choiceIds = [ "choice" ++ (show i) | i <- [0..(n-1)] ] pkgRefIds = [ "pkg" ++ (show i) | i <- [0..(n-1)] ] choicesOutline = mkChoicesOutline choiceIds choices = map (\(x,y) -> mkChoice x x y) (choiceIds `zip` pkgRefIds) -- FIXME: installKBytes should not be "0"! pkgRefs = map (\(x,(f,sz)) -> mkPkgRef x (show sz) f) (pkgRefIds `zip` pkgFiles)
gregorycollins/cabal2macpkg
Distribution/OSX/InstallerScript.hs
bsd-3-clause
7,179
0
13
1,965
1,416
765
651
105
1
{-# LANGUAGE CPP #-} #ifdef MainCall #else {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE CPP #-} {-@ LIQUID "--higherorder" @-} {-@ LIQUID "--totality" @-} {-@ LIQUID "--exactdc" @-} {-@ LIQUID "--no-measure-fields" @-} {-@ LIQUID "--trust-internals" @-} {-@ LIQUID "--automatic-instances=liquidinstanceslocal" @-} {-@ infix <+> @-} {-@ infix <> @-} import Data.RString.RString import Language.Haskell.Liquid.ProofCombinators import Data.Proxy import GHC.TypeLits import Prelude hiding ( mempty, mappend, id, mconcat, map , take, drop , error, undefined ) #define MainCall #include "../Data/List/RList.hs" #include "../Data/StringMatching/StringMatching.hs" #include "../AutoProofs/ListMonoidLemmata.hs" #define CheckMonoidEmptyLeft #endif #ifdef IncludedmakeNewIndicesNullLeft #else #include "../AutoProofs/makeNewIndicesNullLeft.hs" #endif #ifdef IncludedmapCastId #else #include "../AutoProofs/mapCastId.hs" #endif #define IncludedMonoidEmptyLeft #ifdef CheckMonoidEmptyLeft {-@ automatic-instances smLeftId @-} smLeftId :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof {-@ smLeftId :: xs:SM target -> {xs <> mempty == xs } @-} smLeftId (SM i is) = let tg = fromString (symbolVal (Proxy :: Proxy target)) in stringLeftId i &&& mapCastId tg i stringEmp is &&& makeNewIndicesNullLeft i tg &&& listLeftId is mempty_left :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof {-@ mempty_left :: xs:SM target -> {xs <> mempty == xs } @-} mempty_left = smLeftId #else mempty_left :: forall (target :: Symbol). (KnownSymbol target) => SM target -> Proof {-@ mempty_left :: xs:SM target -> {xs <> mempty == xs } @-} mempty_left _ = trivial #endif
nikivazou/verified_string_matching
src/AutoProofs/MonoidEmptyLeft.hs
bsd-3-clause
2,102
0
13
477
164
92
72
25
1
module Data.Generics.Bifixplate ( module Data.Generics.Bifixplate.Base ) where import Data.Generics.Bifixplate.Base
hyPiRion/bifixplate
src/Data/Generics/Bifixplate.hs
bsd-3-clause
138
0
5
31
24
17
7
3
0
----------------------------------------------------------------------------- -- -- Argument representations used in GHC.StgToCmm.Layout. -- -- (c) The University of Glasgow 2013 -- ----------------------------------------------------------------------------- module GHC.StgToCmm.ArgRep ( ArgRep(..), toArgRep, argRepSizeW, argRepString, isNonV, idArgRep, slowCallPattern, ) where import GhcPrelude import GHC.StgToCmm.Closure ( idPrimRep ) import GHC.Runtime.Layout ( WordOff ) import Id ( Id ) import TyCon ( PrimRep(..), primElemRepSizeB ) import BasicTypes ( RepArity ) import Constants ( wORD64_SIZE ) import DynFlags import Outputable import FastString -- I extricated this code as this new module in order to avoid a -- cyclic dependency between GHC.StgToCmm.Layout and GHC.StgToCmm.Ticky. -- -- NSF 18 Feb 2013 ------------------------------------------------------------------------- -- Classifying arguments: ArgRep ------------------------------------------------------------------------- -- ArgRep is re-exported by GHC.StgToCmm.Layout, but only for use in the -- byte-code generator which also needs to know about the -- classification of arguments. data ArgRep = P -- GC Ptr | N -- Word-sized non-ptr | L -- 64-bit non-ptr (long) | V -- Void | F -- Float | D -- Double | V16 -- 16-byte (128-bit) vectors of Float/Double/Int8/Word32/etc. | V32 -- 32-byte (256-bit) vectors of Float/Double/Int8/Word32/etc. | V64 -- 64-byte (512-bit) vectors of Float/Double/Int8/Word32/etc. instance Outputable ArgRep where ppr = text . argRepString argRepString :: ArgRep -> String argRepString P = "P" argRepString N = "N" argRepString L = "L" argRepString V = "V" argRepString F = "F" argRepString D = "D" argRepString V16 = "V16" argRepString V32 = "V32" argRepString V64 = "V64" toArgRep :: PrimRep -> ArgRep toArgRep VoidRep = V toArgRep LiftedRep = P toArgRep UnliftedRep = P toArgRep IntRep = N toArgRep WordRep = N toArgRep Int8Rep = N -- Gets widened to native word width for calls toArgRep Word8Rep = N -- Gets widened to native word width for calls toArgRep Int16Rep = N -- Gets widened to native word width for calls toArgRep Word16Rep = N -- Gets widened to native word width for calls toArgRep Int32Rep = N -- Gets widened to native word width for calls toArgRep Word32Rep = N -- Gets widened to native word width for calls toArgRep AddrRep = N toArgRep Int64Rep = L toArgRep Word64Rep = L toArgRep FloatRep = F toArgRep DoubleRep = D toArgRep (VecRep len elem) = case len*primElemRepSizeB elem of 16 -> V16 32 -> V32 64 -> V64 _ -> error "toArgRep: bad vector primrep" isNonV :: ArgRep -> Bool isNonV V = False isNonV _ = True argRepSizeW :: DynFlags -> ArgRep -> WordOff -- Size in words argRepSizeW _ N = 1 argRepSizeW _ P = 1 argRepSizeW _ F = 1 argRepSizeW dflags L = wORD64_SIZE `quot` wORD_SIZE dflags argRepSizeW dflags D = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags argRepSizeW _ V = 0 argRepSizeW dflags V16 = 16 `quot` wORD_SIZE dflags argRepSizeW dflags V32 = 32 `quot` wORD_SIZE dflags argRepSizeW dflags V64 = 64 `quot` wORD_SIZE dflags idArgRep :: Id -> ArgRep idArgRep = toArgRep . idPrimRep -- This list of argument patterns should be kept in sync with at least -- the following: -- -- * GHC.StgToCmm.Layout.stdPattern maybe to some degree? -- -- * the RTS_RET(stg_ap_*) and RTS_FUN_DECL(stg_ap_*_fast) -- declarations in includes/stg/MiscClosures.h -- -- * the SLOW_CALL_*_ctr declarations in includes/stg/Ticky.h, -- -- * the TICK_SLOW_CALL_*() #defines in includes/Cmm.h, -- -- * the PR_CTR(SLOW_CALL_*_ctr) calls in rts/Ticky.c, -- -- * and the SymI_HasProto(stg_ap_*_{ret,info,fast}) calls and -- SymI_HasProto(SLOW_CALL_*_ctr) calls in rts/Linker.c -- -- There may be more places that I haven't found; I merely igrep'd for -- pppppp and excluded things that seemed ghci-specific. -- -- Also, it seems at the moment that ticky counters with void -- arguments will never be bumped, but I'm still declaring those -- counters, defensively. -- -- NSF 6 Mar 2013 slowCallPattern :: [ArgRep] -> (FastString, RepArity) -- Returns the generic apply function and arity -- -- The first batch of cases match (some) specialised entries -- The last group deals exhaustively with the cases for the first argument -- (and the zero-argument case) -- -- In 99% of cases this function will match *all* the arguments in one batch slowCallPattern (P: P: P: P: P: P: _) = (fsLit "stg_ap_pppppp", 6) slowCallPattern (P: P: P: P: P: _) = (fsLit "stg_ap_ppppp", 5) slowCallPattern (P: P: P: P: _) = (fsLit "stg_ap_pppp", 4) slowCallPattern (P: P: P: V: _) = (fsLit "stg_ap_pppv", 4) slowCallPattern (P: P: P: _) = (fsLit "stg_ap_ppp", 3) slowCallPattern (P: P: V: _) = (fsLit "stg_ap_ppv", 3) slowCallPattern (P: P: _) = (fsLit "stg_ap_pp", 2) slowCallPattern (P: V: _) = (fsLit "stg_ap_pv", 2) slowCallPattern (P: _) = (fsLit "stg_ap_p", 1) slowCallPattern (V: _) = (fsLit "stg_ap_v", 1) slowCallPattern (N: _) = (fsLit "stg_ap_n", 1) slowCallPattern (F: _) = (fsLit "stg_ap_f", 1) slowCallPattern (D: _) = (fsLit "stg_ap_d", 1) slowCallPattern (L: _) = (fsLit "stg_ap_l", 1) slowCallPattern (V16: _) = (fsLit "stg_ap_v16", 1) slowCallPattern (V32: _) = (fsLit "stg_ap_v32", 1) slowCallPattern (V64: _) = (fsLit "stg_ap_v64", 1) slowCallPattern [] = (fsLit "stg_ap_0", 0)
sdiehl/ghc
compiler/GHC/StgToCmm/ArgRep.hs
bsd-3-clause
6,086
0
12
1,613
1,216
686
530
90
4
{-# LANGUAGE RecordWildCards #-} module Utils( fromRight , substr , toStrict , toLazy , diff , debug , formatTable , maxDuplicate , xattrRaw , xattr ) where import Blaze.ByteString.Builder.Char.Utf8 import Control.Monad import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.Function import Data.List import Data.Text () import qualified Data.Text as T import Debug.Trace import Text.Printf import qualified Text.XML.Generator as X fromRight :: (Either String t2, t) -> t2 fromRight (Right x, _) = x fromRight (Left y, _) = error y substr :: Int -> Int -> B.ByteString -> B.ByteString substr s l = B.take l . B.drop s toStrict :: BL.ByteString -> B.ByteString toStrict = B.concat . BL.toChunks toLazy :: B.ByteString -> BL.ByteString toLazy str = BL.fromChunks [str] diff :: Num b => [b] -> [b] diff l = zipWith (-) l $ tail l formatTable :: [[String]] -> String formatTable table = line ++ unlines (map formatRow table) ++ line where maxSize = map maximum $ transpose $ map (map length) table line = concat (replicate (sum maxSize + (length maxSize - 1) * 3) "-") ++ "\n" formatRow row = intercalate " | " $ zipWith formatCell row maxSize formatCell :: String -> Int -> String formatCell field size = printf ("%-" ++ show size ++ "s") field maxDuplicate :: [Int] -> Int maxDuplicate = head . minimumBy (compare `on` (negate . length)) . group . sort debug :: Monad m => String -> m () debug str = when True $ trace str $ return () xattrRaw :: String -> String -> X.Xml X.Attr xattrRaw name attr = X.xattrQRaw X.defaultNamespace (T.pack name) (fromString attr) xattr :: String -> T.Text -> X.Xml X.Attr xattr name = X.xattr (T.pack name)
guilt/webify
src/Utils.hs
mit
1,917
0
16
524
686
367
319
51
1
-- | Web-related part of cardano-sl. module Pos.Web ( module Pos.Web.Api , module Pos.Web.Mode , module Pos.Web.Server , module Pos.Web.Types ) where import Pos.Web.Api import Pos.Web.Mode import Pos.Web.Server import Pos.Web.Types
input-output-hk/pos-haskell-prototype
lib/src/Pos/Web.hs
mit
309
0
5
107
61
42
19
9
0
module Fun.Check where -- $Id$ import Condition import qualified Autolib.Reporter.Checker as C import Fun.Type import qualified RAM.Builtin import qualified Machine.Numerical.Config as NC import Autolib.Reporter import Autolib.ToDoc import Autolib.Set instance NC.Check Property Fun where check ( Builtins allowed ) f = check_builtins ( mkSet allowed ) f check :: Property -> C.Type Fun check ( Builtins bs ) = C.Make { C.nametag = "" , C.condition = text "Nur diese builtin-Funktionen sind gestattet:" </> toDoc bs , C.investigate = \ f -> check_builtins ( mkSet bs ) f } instance Condition Property Fun where condition p f = C.run ( check p ) f instance Explain Property where explain p = C.condition ( check p ) check_builtins :: Set Builtin -> Fun -> Reporter () check_builtins allowed f = do inform $ text "erlaubt sind diese Builtin-Funktionen:" inform $ nest 4 $ toDoc allowed let you = mkSet $ do Builtin i b <- subtrees f return b inform $ text "Sie benutzen:" <+> toDoc you let wrong = minusSet you allowed assert ( isEmptySet wrong ) $ text "sind alle zugelassen?" subtrees :: Fun -> [ Fun ] subtrees f = f : case f of Sub f gs -> concat $ map subtrees gs PR f gs -> concat $ map subtrees gs Min f gs -> concat $ map subtrees gs _ -> [] --------------------------------------------------------------------------- check_arity :: Int -> Fun -> Reporter () check_arity soll f = case f of -- Funktionen Zero ist -> do diff f soll ist Succ ist -> do when (1 /= ist) $ do complain f reject $ fsep [ text "Diese Funktion ist einstellig." ] diff f soll ist Decr ist -> do when (1 /= ist) $ do complain f reject $ fsep [ text "Diese Funktion ist einstellig." ] diff f soll ist Proj ist unten -> do when ( ist < 0 ) $ do complain f reject $ fsep [ text "Es gibt keine", tupel ist ] when ( unten < 1 || unten > ist ) $ do complain f reject $ fsep [ text "Ein", tupel ist , text "besitzt keine" , komponente unten ] diff f soll ist Builtin ist b -> do let ( arity, _ ) = RAM.Builtin.get b when ( arity /= ist ) $ do complain f reject $ fsep [ text "Diese Funktion ist" , toDoc arity, text "-stellig." ] diff f soll ist -- Operatoren Sub ist [ ] -> do complain f reject $ fsep [ text "Der Sub-Operator benötigt wenigstens" , text "ein Argument." ] Sub ist (g : hs) -> do diff f soll ist let n = length hs check_arity n g mapM_ (check_arity soll) hs PR ist gh | 2 /= length gh -> do complain f reject $ fsep [ text "Der PR-Operator benötigt genau" , text "zwei Argumente." ] PR ist [ g, h ] -> do diff f soll ist check_arity (pred soll) g check_arity (succ soll) h Min ist gs | 1 /= length gs -> reject $ fsep [ text "Der Min-Operator benötigt genau" , text "ein Argument." ] Min ist [ g ] -> do diff f soll ist check_arity (succ soll) g complain :: Fun -> Reporter () complain f = do inform $ text "Fehler im Ausdruck:" inform $ nest 4 $ toDoc f ste i = text "eine" <+> text ( show i ++ "-stellige" ) <+> text "Funktion" diff f soll ist = when ( soll /= ist ) $ do complain f reject $ fsep [ text "Dieser Ausdruck beschreibt", ste ist, text "," , text "verlangt ist hier", ste soll, text "." ] tupel i = text $ show i ++ "-Tupel" komponente i = text $ show i ++ "-te Komponente"
florianpilz/autotool
src/Fun/Check.hs
gpl-2.0
3,675
32
19
1,126
1,216
602
614
-1
-1
{-# LANGUAGE Safe #-} -- | A vector clock implementation. -- -- This module re-exports "Data.VectorClock.Simple", which is the -- fully-featured vector clock library. If you wish to use -- approximate vector clocks, which are significantly smaller and have -- bounded size, but are not exact, use "Data.VectorClock.Approximate" -- instead. -- -- See @Fundamentals of Distributed Computing: A Practical Tour of -- Vector Clock Systems@ by R. Baldoni and M. Raynal for an overview -- of vector clocks. module Data.VectorClock ( module Data.VectorClock.Simple ) where import Data.VectorClock.Simple
tkonolige/vector-clock
src/Data/VectorClock.hs
gpl-3.0
612
0
5
103
33
26
7
4
0
{-#LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} module Carnap.Languages.PureFirstOrder.Logic.Carnap (FOLogic(..), parseFOLogic, folCalc) where import Data.Map as M (lookup, Map,empty) import Text.Parsec import Carnap.Core.Unification.Unification (applySub) import Carnap.Core.Data.Types (Form) import Carnap.Languages.PureFirstOrder.Syntax import Carnap.Languages.PureFirstOrder.Parser import Carnap.Languages.PurePropositional.Logic.Carnap import Carnap.Calculi.NaturalDeduction.Syntax import Carnap.Calculi.NaturalDeduction.Parser import Carnap.Calculi.NaturalDeduction.Checker (hoProcessLineMontague, hoProcessLineMontagueMemo) import Carnap.Languages.ClassicalSequent.Syntax import Carnap.Languages.ClassicalSequent.Parser import Carnap.Languages.Util.LanguageClasses import Carnap.Languages.Util.GenericConstructors import Carnap.Languages.PurePropositional.Logic.Rules (axiom,premConstraint) import Carnap.Languages.PureFirstOrder.Logic.Rules -------------------------------------------------------- --2. Classical First-Order Logic -------------------------------------------------------- data FOLogic = SL PropLogic | UD | UI | EG | ED1 | ED2 | QN1 | QN2 | QN3 | QN4 | LL1 | LL2 | EL1 | EL2 | ID | SM | ALL1 | ALL2 | DER (ClassicalSequentOver PureLexiconFOL (Sequent (Form Bool))) | PR (Maybe [(ClassicalSequentOver PureLexiconFOL (Sequent (Form Bool)))]) deriving (Eq) instance Show FOLogic where show (PR _) = "PR" show UD = "UD" show UI = "UI" show EG = "EG" show ED1 = "ED" show ED2 = "ED" show (DER _) = "Derived" show QN1 = "QN" show QN2 = "QN" show QN3 = "QN" show QN4 = "QN" show ID = "Id" show LL1 = "LL" show LL2 = "LL" show ALL1 = "LL" show ALL2 = "LL" show EL1 = "EL" show EL2 = "EL" show SM = "Sm" show (SL x) = show x instance Inference FOLogic PureLexiconFOL (Form Bool) where ruleOf (PR _) = axiom ruleOf UI = universalInstantiation ruleOf EG = existentialGeneralization ruleOf UD = universalGeneralization ruleOf ED1 = existentialDerivation !! 0 ruleOf ED2 = existentialDerivation !! 1 ruleOf QN1 = quantifierNegation !! 0 ruleOf QN2 = quantifierNegation !! 1 ruleOf QN3 = quantifierNegation !! 2 ruleOf QN4 = quantifierNegation !! 3 ruleOf LL1 = leibnizLawVariations !! 0 ruleOf LL2 = leibnizLawVariations !! 1 ruleOf ALL1 = antiLeibnizLawVariations !! 0 ruleOf ALL2 = antiLeibnizLawVariations !! 1 ruleOf EL1 = euclidsLawVariations !! 0 ruleOf EL2 = euclidsLawVariations !! 1 ruleOf ID = eqReflexivity ruleOf SM = eqSymmetry premisesOf (SL x) = map liftSequent (premisesOf x) premisesOf (DER r) = multiCutLeft r premisesOf x = upperSequents (ruleOf x) conclusionOf (SL x) = liftSequent (conclusionOf x) conclusionOf (DER r) = multiCutRight r conclusionOf x = lowerSequent (ruleOf x) restriction UD = Just (eigenConstraint tau (SS (lall "v" $ phi' 1)) (fogamma 1)) restriction ED1 = Just (eigenConstraint tau (SS (lsome "v" $ phi' 1) :-: SS (phin 1)) (fogamma 1 :+: fogamma 2)) restriction ED2 = Just (eigenConstraint tau (SS (lsome "v" $ phi' 1) :-: SS (phin 1)) (fogamma 1 :+: fogamma 2)) restriction (PR prems) = Just (premConstraint prems) restriction _ = Nothing indirectInference (SL x) = indirectInference x indirectInference x | x `elem` [ ED1,ED2,UD ] = Just PolyProof | otherwise = Nothing parseFOLogic :: RuntimeNaturalDeductionConfig PureLexiconFOL (Form Bool) -> Parsec String u [FOLogic] parseFOLogic rtc = try quantRule <|> liftProp where liftProp = map SL <$> parsePropLogic (RuntimeNaturalDeductionConfig mempty mempty) quantRule = do r <- choice (map (try . string) ["PR", "UI", "UD", "EG", "ED", "QN","LL","EL","Id","Sm","D-"]) case r of r | r == "PR" -> return [PR $ problemPremises rtc] | r == "UI" -> return [UI] | r == "UD" -> return [UD] | r == "EG" -> return [EG] | r == "ED" -> return [ED1,ED2] | r == "QN" -> return [QN1,QN2,QN3,QN4] | r == "LL" -> return [LL1,LL2,ALL1,ALL2] | r == "Sm" -> return [SM] | r == "EL" -> return [EL1,EL2] | r == "Id" -> return [ID] | r == "D-" -> do rn <- many1 upper case M.lookup rn (derivedRules rtc) of Just r -> return [DER r] Nothing -> parserFail "Looks like you're citing a derived rule that doesn't exist" parseFOLProof :: RuntimeNaturalDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine FOLogic PureLexiconFOL (Form Bool)] parseFOLProof ders = toDeductionMontague (parseFOLogic ders) folFormulaParser folCalc = mkNDCalc { ndRenderer = MontagueStyle , ndParseProof = parseFOLProof , ndProcessLine = hoProcessLineMontague , ndProcessLineMemo = Just hoProcessLineMontagueMemo }
opentower/carnap
Carnap/src/Carnap/Languages/PureFirstOrder/Logic/Carnap.hs
gpl-3.0
5,724
0
20
1,840
1,619
849
770
106
2
module Llvm.Asm (module Llvm.Asm.Data ,module Llvm.Asm.Parser ,module Llvm.Asm.Simplification )where import Llvm.Asm.Data import Llvm.Asm.Parser import Llvm.Asm.Printer.LlvmPrint import Llvm.Asm.Simplification
mlite/hLLVM
src/Llvm/Asm.hs
bsd-3-clause
258
0
5
65
54
37
17
7
0
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This provides an abstraction which deals with configuring and running -- programs. A 'Program' is a static notion of a known program. A -- 'ConfiguredProgram' is a 'Program' that has been found on the current -- machine and is ready to be run (possibly with some user-supplied default -- args). Configuring a program involves finding its location and if necessary -- finding its version. There is also a 'ProgramConfiguration' type which holds -- configured and not-yet configured programs. It is the parameter to lots of -- actions elsewhere in Cabal that need to look up and run programs. If we had -- a Cabal monad, the 'ProgramConfiguration' would probably be a reader or -- state component of it. -- -- The module also defines all the known built-in 'Program's and the -- 'defaultProgramConfiguration' which contains them all. -- -- One nice thing about using it is that any program that is -- registered with Cabal will get some \"configure\" and \".cabal\" -- helpers like --with-foo-args --foo-path= and extra-foo-args. -- -- There's also good default behavior for trying to find \"foo\" in -- PATH, being able to override its location, etc. -- -- There's also a hook for adding programs in a Setup.lhs script. See -- hookedPrograms in 'Distribution.Simple.UserHooks'. This gives a -- hook user the ability to get the above flags and such so that they -- don't have to write all the PATH logic inside Setup.lhs. module Distribution.Simple.Program ( -- * Program and functions for constructing them Program(..) , ProgramSearchPath , ProgramSearchPathEntry(..) , simpleProgram , findProgramOnSearchPath , defaultProgramSearchPath , findProgramVersion -- * Configured program and related functions , ConfiguredProgram(..) , programPath , ProgArg , ProgramLocation(..) , runProgram , getProgramOutput , suppressOverrideArgs -- * Program invocations , ProgramInvocation(..) , emptyProgramInvocation , simpleProgramInvocation , programInvocation , runProgramInvocation , getProgramInvocationOutput -- * The collection of unconfigured and configured programs , builtinPrograms -- * The collection of configured programs we can run , ProgramConfiguration , emptyProgramConfiguration , defaultProgramConfiguration , restoreProgramConfiguration , addKnownProgram , addKnownPrograms , lookupKnownProgram , knownPrograms , getProgramSearchPath , setProgramSearchPath , userSpecifyPath , userSpecifyPaths , userMaybeSpecifyPath , userSpecifyArgs , userSpecifyArgss , userSpecifiedArgs , lookupProgram , lookupProgramVersion , updateProgram , configureProgram , configureAllKnownPrograms , reconfigurePrograms , requireProgram , requireProgramVersion , runDbProgram , getDbProgramOutput -- * Programs that Cabal knows about , ghcProgram , ghcPkgProgram , ghcjsProgram , ghcjsPkgProgram , lhcProgram , lhcPkgProgram , hmakeProgram , jhcProgram , uhcProgram , gccProgram , arProgram , stripProgram , happyProgram , alexProgram , hsc2hsProgram , c2hsProgram , cpphsProgram , hscolourProgram , haddockProgram , greencardProgram , ldProgram , tarProgram , cppProgram , pkgConfigProgram , hpcProgram -- * deprecated , rawSystemProgram , rawSystemProgramStdout , rawSystemProgramConf , rawSystemProgramStdoutConf , findProgramOnPath , findProgramLocation ) where import Distribution.Simple.Program.Types import Distribution.Simple.Program.Run import Distribution.Simple.Program.Db import Distribution.Simple.Program.Builtin import Distribution.Simple.Program.Find import Distribution.Simple.Utils ( die, findProgramLocation, findProgramVersion ) import Distribution.Verbosity ( Verbosity ) -- | Runs the given configured program. -- runProgram :: Verbosity -- ^Verbosity -> ConfiguredProgram -- ^The program to run -> [ProgArg] -- ^Any /extra/ arguments to add -> IO () runProgram verbosity prog args = runProgramInvocation verbosity (programInvocation prog args) -- | Runs the given configured program and gets the output. -- getProgramOutput :: Verbosity -- ^Verbosity -> ConfiguredProgram -- ^The program to run -> [ProgArg] -- ^Any /extra/ arguments to add -> IO String getProgramOutput verbosity prog args = getProgramInvocationOutput verbosity (programInvocation prog args) -- | Looks up the given program in the program database and runs it. -- runDbProgram :: Verbosity -- ^verbosity -> Program -- ^The program to run -> ProgramDb -- ^look up the program here -> [ProgArg] -- ^Any /extra/ arguments to add -> IO () runDbProgram verbosity prog programDb args = case lookupProgram prog programDb of Nothing -> die notFound Just configuredProg -> runProgram verbosity configuredProg args where notFound = "The program '" ++ programName prog ++ "' is required but it could not be found" -- | Looks up the given program in the program database and runs it. -- getDbProgramOutput :: Verbosity -- ^verbosity -> Program -- ^The program to run -> ProgramDb -- ^look up the program here -> [ProgArg] -- ^Any /extra/ arguments to add -> IO String getDbProgramOutput verbosity prog programDb args = case lookupProgram prog programDb of Nothing -> die notFound Just configuredProg -> getProgramOutput verbosity configuredProg args where notFound = "The program '" ++ programName prog ++ "' is required but it could not be found" --------------------- -- Deprecated aliases -- rawSystemProgram :: Verbosity -> ConfiguredProgram -> [ProgArg] -> IO () rawSystemProgram = runProgram rawSystemProgramStdout :: Verbosity -> ConfiguredProgram -> [ProgArg] -> IO String rawSystemProgramStdout = getProgramOutput rawSystemProgramConf :: Verbosity -> Program -> ProgramConfiguration -> [ProgArg] -> IO () rawSystemProgramConf = runDbProgram rawSystemProgramStdoutConf :: Verbosity -> Program -> ProgramConfiguration -> [ProgArg] -> IO String rawSystemProgramStdoutConf = getDbProgramOutput type ProgramConfiguration = ProgramDb emptyProgramConfiguration, defaultProgramConfiguration :: ProgramConfiguration emptyProgramConfiguration = emptyProgramDb defaultProgramConfiguration = defaultProgramDb restoreProgramConfiguration :: [Program] -> ProgramConfiguration -> ProgramConfiguration restoreProgramConfiguration = restoreProgramDb {-# DEPRECATED findProgramOnPath "use findProgramOnSearchPath instead" #-} findProgramOnPath :: String -> Verbosity -> IO (Maybe FilePath) findProgramOnPath name verbosity = fmap (fmap fst) $ findProgramOnSearchPath verbosity defaultProgramSearchPath name
randen/cabal
Cabal/Distribution/Simple/Program.hs
bsd-3-clause
7,502
0
10
1,753
897
543
354
146
2
module Type.Constrain.Expression where import Control.Applicative ((<$>)) import qualified Control.Monad as Monad import Control.Monad.Error import qualified Data.List as List import qualified Data.Map as Map import qualified Text.PrettyPrint as PP import AST.Literal as Lit import AST.Annotation as Ann import AST.Expression.General import qualified AST.Expression.Canonical as Canonical import qualified AST.Pattern as P import qualified AST.Type as ST import qualified AST.Variable as V import Type.Type hiding (Descriptor(..)) import Type.Fragment import qualified Type.Environment as Env import qualified Type.Constrain.Literal as Literal import qualified Type.Constrain.Pattern as Pattern constrain :: Env.Environment -> Canonical.Expr -> Type -> ErrorT [PP.Doc] IO TypeConstraint constrain env (A region expr) tipe = let list t = Env.get env Env.types "List" <| t and = A region . CAnd true = A region CTrue t1 === t2 = A region (CEqual t1 t2) x <? t = A region (CInstance x t) clet schemes c = A region (CLet schemes c) in case expr of Literal lit -> liftIO $ Literal.constrain env region lit tipe GLShader _uid _src gltipe -> exists $ \attr -> exists $ \unif -> let shaderTipe a u v = Env.get env Env.types "WebGL.Shader" <| a <| u <| v glTipe = Env.get env Env.types . Lit.glTipeName makeRec accessor baseRec = let decls = accessor gltipe in if Map.size decls == 0 then baseRec else record (Map.map (\t -> [glTipe t]) decls) baseRec attribute = makeRec Lit.attribute attr uniform = makeRec Lit.uniform unif varying = makeRec Lit.varying (termN EmptyRecord1) in return . A region $ CEqual tipe (shaderTipe attribute uniform varying) Var var | name == saveEnvName -> return (A region CSaveEnv) | otherwise -> return (name <? tipe) where name = V.toString var Range lo hi -> existsNumber $ \n -> do clo <- constrain env lo n chi <- constrain env hi n return $ and [clo, chi, list n === tipe] ExplicitList exprs -> exists $ \x -> do cs <- mapM (\e -> constrain env e x) exprs return . and $ list x === tipe : cs Binop op e1 e2 -> exists $ \t1 -> exists $ \t2 -> do c1 <- constrain env e1 t1 c2 <- constrain env e2 t2 return $ and [ c1, c2, V.toString op <? (t1 ==> t2 ==> tipe) ] Lambda p e -> exists $ \t1 -> exists $ \t2 -> do fragment <- try region $ Pattern.constrain env p t1 c2 <- constrain env e t2 let c = ex (vars fragment) (clet [monoscheme (typeEnv fragment)] (typeConstraint fragment /\ c2 )) return $ c /\ tipe === (t1 ==> t2) App e1 e2 -> exists $ \t -> do c1 <- constrain env e1 (t ==> tipe) c2 <- constrain env e2 t return $ c1 /\ c2 MultiIf branches -> and <$> mapM constrain' branches where bool = Env.get env Env.types "Bool" constrain' (b,e) = do cb <- constrain env b bool ce <- constrain env e tipe return (cb /\ ce) Case exp branches -> exists $ \t -> do ce <- constrain env exp t let branch (p,e) = do fragment <- try region $ Pattern.constrain env p t clet [toScheme fragment] <$> constrain env e tipe and . (:) ce <$> mapM branch branches Data name exprs -> do vars <- forM exprs $ \_ -> liftIO (variable Flexible) let pairs = zip exprs (map varN vars) (ctipe, cs) <- Monad.foldM step (tipe,true) (reverse pairs) return $ ex vars (cs /\ name <? ctipe) where step (t,c) (e,x) = do c' <- constrain env e x return (x ==> t, c /\ c') Access e label -> exists $ \t -> constrain env e (record (Map.singleton label [tipe]) t) Remove e label -> exists $ \t -> constrain env e (record (Map.singleton label [t]) tipe) Insert e label value -> exists $ \tVal -> exists $ \tRec -> do cVal <- constrain env value tVal cRec <- constrain env e tRec let c = tipe === record (Map.singleton label [tVal]) tRec return (and [cVal, cRec, c]) Modify e fields -> exists $ \t -> do oldVars <- forM fields $ \_ -> liftIO (variable Flexible) let oldFields = ST.fieldMap (zip (map fst fields) (map varN oldVars)) cOld <- ex oldVars <$> constrain env e (record oldFields t) newVars <- forM fields $ \_ -> liftIO (variable Flexible) let newFields = ST.fieldMap (zip (map fst fields) (map varN newVars)) let cNew = tipe === record newFields t cs <- zipWithM (constrain env) (map snd fields) (map varN newVars) return $ cOld /\ ex newVars (and (cNew : cs)) Record fields -> do vars <- forM fields $ \_ -> liftIO (variable Flexible) cs <- zipWithM (constrain env) (map snd fields) (map varN vars) let fields' = ST.fieldMap (zip (map fst fields) (map varN vars)) recordType = record fields' (termN EmptyRecord1) return . ex vars . and $ tipe === recordType : cs Let defs body -> do c <- constrain env body tipe (schemes, rqs, fqs, header, c2, c1) <- Monad.foldM (constrainDef env) ([], [], [], Map.empty, true, true) (concatMap expandPattern defs) return $ clet schemes (clet [Scheme rqs fqs (clet [monoscheme header] c2) header ] (c1 /\ c)) PortIn _ _ -> return true PortOut _ _ signal -> constrain env signal tipe constrainDef env info (Canonical.Definition pattern expr maybeTipe) = let qs = [] -- should come from the def, but I'm not sure what would live there... (schemes, rigidQuantifiers, flexibleQuantifiers, headers, c2, c1) = info in do rigidVars <- forM qs (\_ -> liftIO $ variable Rigid) -- Some mistake may be happening here. -- Currently, qs is always []. case (pattern, maybeTipe) of (P.Var name, Just tipe) -> do flexiVars <- forM qs (\_ -> liftIO $ variable Flexible) let inserts = zipWith (\arg typ -> Map.insert arg (varN typ)) qs flexiVars env' = env { Env.value = List.foldl' (\x f -> f x) (Env.value env) inserts } (vars, typ) <- Env.instantiateType env tipe Map.empty let scheme = Scheme { rigidQuantifiers = [], flexibleQuantifiers = flexiVars ++ vars, constraint = Ann.noneNoDocs CTrue, header = Map.singleton name typ } c <- constrain env' expr typ return ( scheme : schemes , rigidQuantifiers , flexibleQuantifiers , headers , c2 , fl rigidVars c /\ c1 ) (P.Var name, Nothing) -> do v <- liftIO $ variable Flexible let tipe = varN v inserts = zipWith (\arg typ -> Map.insert arg (varN typ)) qs rigidVars env' = env { Env.value = List.foldl' (\x f -> f x) (Env.value env) inserts } c <- constrain env' expr tipe return ( schemes , rigidVars ++ rigidQuantifiers , v : flexibleQuantifiers , Map.insert name tipe headers , c /\ c2 , c1 ) _ -> error ("problem in constrainDef with " ++ show pattern) expandPattern :: Canonical.Def -> [Canonical.Def] expandPattern def@(Canonical.Definition pattern lexpr@(A r _) maybeType) = case pattern of P.Var _ -> [def] _ -> Canonical.Definition (P.Var x) lexpr maybeType : map toDef vars where vars = P.boundVarList pattern x = "$" ++ concat vars mkVar = A r . localVar toDef y = Canonical.Definition (P.Var y) (A r $ Case (mkVar x) [(pattern, mkVar y)]) Nothing try :: Region -> ErrorT (Region -> PP.Doc) IO a -> ErrorT [PP.Doc] IO a try region computation = do result <- liftIO $ runErrorT computation case result of Left err -> throwError [err region] Right value -> return value
JoeyEremondi/utrecht-apa-p1
src/Type/Constrain/Expression.hs
bsd-3-clause
9,071
0
27
3,451
3,149
1,576
1,573
191
20
import Graphics.UI.Gtk import Graphics.Rendering.Cairo main :: IO () main= do initGUI window <- windowNew set window [windowTitle := "Hello Cairo", windowDefaultWidth := 300, windowDefaultHeight := 200, containerBorderWidth := 30 ] frame <- frameNew containerAdd window frame canvas <- drawingAreaNew containerAdd frame canvas widgetModifyBg canvas StateNormal (Color 65535 65535 65535) widgetShowAll window drawin <- widgetGetDrawWindow canvas onExpose canvas (\x -> do renderWithDrawable drawin myDraw return (eventSent x)) onDestroy window mainQuit mainGUI myDraw :: Render () myDraw = do setSourceRGB 1 1 0 setLineWidth 5 moveTo 120 60 lineTo 60 110 lineTo 180 110 closePath stroke
k0001/gtk2hs
docs/tutorial/Tutorial_Port/Example_Code/GtkApp1a.hs
gpl-3.0
851
1
14
259
251
111
140
29
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} -- From http://www.reddit.com/r/haskell/comments/8ereh/a_here_document_syntax/ -- copyright unknown? module HereDoc (heredoc) where import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax import Language.Haskell.TH.Lib heredoc :: QuasiQuoter heredoc = QuasiQuoter (litE . stringL) (litP . stringL) undefined undefined
jtdaugherty/vty
test/HereDoc.hs
bsd-3-clause
393
0
7
40
67
43
24
8
1
--------------------------------------------------------- -- The main program for the hpc-report tool, part of HPC. -- Colin Runciman and Andy Gill, June 2006 --------------------------------------------------------- module HpcReport (report_plugin) where import Prelude hiding (exp) import Data.List(sort,intersperse,sortBy) import HpcFlags import Trace.Hpc.Mix import Trace.Hpc.Tix import Control.Monad hiding (guard) import qualified Data.Set as Set notExpecting :: String -> a notExpecting s = error ("not expecting "++s) data BoxTixCounts = BT {boxCount, tixCount :: !Int} btZero :: BoxTixCounts btZero = BT {boxCount=0, tixCount=0} btPlus :: BoxTixCounts -> BoxTixCounts -> BoxTixCounts btPlus (BT b1 t1) (BT b2 t2) = BT (b1+b2) (t1+t2) btPercentage :: String -> BoxTixCounts -> String btPercentage s (BT b t) = showPercentage s t b showPercentage :: String -> Int -> Int -> String showPercentage s 0 0 = "100% "++s++" (0/0)" showPercentage s n d = showWidth 3 p++"% "++ s++ " ("++show n++"/"++show d++")" where p = (n*100) `div` d showWidth w x0 = replicate (shortOf w (length sx)) ' ' ++ sx where sx = show x0 shortOf x y = if y < x then x-y else 0 data BinBoxTixCounts = BBT { binBoxCount , onlyTrueTixCount , onlyFalseTixCount , bothTixCount :: !Int} bbtzero :: BinBoxTixCounts bbtzero = BBT { binBoxCount=0 , onlyTrueTixCount=0 , onlyFalseTixCount=0 , bothTixCount=0} bbtPlus :: BinBoxTixCounts -> BinBoxTixCounts -> BinBoxTixCounts bbtPlus (BBT b1 tt1 ft1 bt1) (BBT b2 tt2 ft2 bt2) = BBT (b1+b2) (tt1+tt2) (ft1+ft2) (bt1+bt2) bbtPercentage :: String -> Bool -> BinBoxTixCounts -> String bbtPercentage s withdetail (BBT b tt ft bt) = showPercentage s bt b ++ if withdetail && bt/=b then detailFor tt "always True"++ detailFor ft "always False"++ detailFor (b-(tt+ft+bt)) "unevaluated" else "" where detailFor n txt = if n>0 then ", "++show n++" "++txt else "" data ModInfo = MI { exp,alt,top,loc :: !BoxTixCounts , guard,cond,qual :: !BinBoxTixCounts , decPaths :: [[String]]} miZero :: ModInfo miZero = MI { exp=btZero , alt=btZero , top=btZero , loc=btZero , guard=bbtzero , cond=bbtzero , qual=bbtzero , decPaths = []} miPlus :: ModInfo -> ModInfo -> ModInfo miPlus mi1 mi2 = MI { exp = exp mi1 `btPlus` exp mi2 , alt = alt mi1 `btPlus` alt mi2 , top = top mi1 `btPlus` top mi2 , loc = loc mi1 `btPlus` loc mi2 , guard = guard mi1 `bbtPlus` guard mi2 , cond = cond mi1 `bbtPlus` cond mi2 , qual = qual mi1 `bbtPlus` qual mi2 , decPaths = decPaths mi1 ++ decPaths mi2 } allBinCounts :: ModInfo -> BinBoxTixCounts allBinCounts mi = BBT { binBoxCount = sumAll binBoxCount , onlyTrueTixCount = sumAll onlyTrueTixCount , onlyFalseTixCount = sumAll onlyFalseTixCount , bothTixCount = sumAll bothTixCount } where sumAll f = f (guard mi) + f (cond mi) + f (qual mi) accumCounts :: [(BoxLabel,Integer)] -> ModInfo -> ModInfo accumCounts [] mi = mi accumCounts ((bl,btc):etc) mi | single bl = accumCounts etc mi' where mi' = case bl of ExpBox False -> mi{exp = inc (exp mi)} ExpBox True -> mi{exp = inc (exp mi), alt = inc (alt mi)} TopLevelBox dp -> mi{top = inc (top mi) ,decPaths = upd dp (decPaths mi)} LocalBox dp -> mi{loc = inc (loc mi) ,decPaths = upd dp (decPaths mi)} _other -> notExpecting "BoxLabel in accumcounts" inc (BT {boxCount=bc,tixCount=tc}) = BT { boxCount = bc+1 , tixCount = tc + bit (btc>0) } upd dp dps = if btc>0 then dps else dp:dps accumCounts [_] _ = error "accumCounts: Unhandled case: [_] _" accumCounts ((bl0,btc0):(bl1,btc1):etc) mi = accumCounts etc mi' where mi' = case (bl0,bl1) of (BinBox GuardBinBox True, BinBox GuardBinBox False) -> mi{guard = inc (guard mi)} (BinBox CondBinBox True, BinBox CondBinBox False) -> mi{cond = inc (cond mi)} (BinBox QualBinBox True, BinBox QualBinBox False) -> mi{qual = inc (qual mi)} _other -> notExpecting "BoxLabel pair in accumcounts" inc (BBT { binBoxCount=bbc , onlyTrueTixCount=ttc , onlyFalseTixCount=ftc , bothTixCount=btc}) = BBT { binBoxCount = bbc+1 , onlyTrueTixCount = ttc + bit (btc0 >0 && btc1==0) , onlyFalseTixCount = ftc + bit (btc0==0 && btc1 >0) , bothTixCount = btc + bit (btc0 >0 && btc1 >0) } bit :: Bool -> Int bit True = 1 bit False = 0 single :: BoxLabel -> Bool single (ExpBox {}) = True single (TopLevelBox _) = True single (LocalBox _) = True single (BinBox {}) = False modInfo :: Flags -> Bool -> TixModule -> IO ModInfo modInfo hpcflags qualDecList tix@(TixModule moduleName _ _ tickCounts) = do Mix _ _ _ _ mes <- readMixWithFlags hpcflags (Right tix) return (q (accumCounts (zip (map snd mes) tickCounts) miZero)) where q mi = if qualDecList then mi{decPaths = map (moduleName:) (decPaths mi)} else mi modReport :: Flags -> TixModule -> IO () modReport hpcflags tix@(TixModule moduleName _ _ _) = do mi <- modInfo hpcflags False tix if xmlOutput hpcflags then putStrLn $ " <module name = " ++ show moduleName ++ ">" else putStrLn ("-----<module "++moduleName++">-----") printModInfo hpcflags mi if xmlOutput hpcflags then putStrLn $ " </module>" else return () printModInfo :: Flags -> ModInfo -> IO () printModInfo hpcflags mi | xmlOutput hpcflags = do element "exprs" (xmlBT $ exp mi) element "booleans" (xmlBBT $ allBinCounts mi) element "guards" (xmlBBT $ guard mi) element "conditionals" (xmlBBT $ cond mi) element "qualifiers" (xmlBBT $ qual mi) element "alts" (xmlBT $ alt mi) element "local" (xmlBT $ loc mi) element "toplevel" (xmlBT $ top mi) printModInfo hpcflags mi = do putStrLn (btPercentage "expressions used" (exp mi)) putStrLn (bbtPercentage "boolean coverage" False (allBinCounts mi)) putStrLn (" "++bbtPercentage "guards" True (guard mi)) putStrLn (" "++bbtPercentage "'if' conditions" True (cond mi)) putStrLn (" "++bbtPercentage "qualifiers" True (qual mi)) putStrLn (btPercentage "alternatives used" (alt mi)) putStrLn (btPercentage "local declarations used" (loc mi)) putStrLn (btPercentage "top-level declarations used" (top mi)) modDecList hpcflags mi modDecList :: Flags -> ModInfo -> IO () modDecList hpcflags mi0 = when (decList hpcflags && someDecsUnused mi0) $ do putStrLn "unused declarations:" mapM_ showDecPath (sort (decPaths mi0)) where someDecsUnused mi = tixCount (top mi) < boxCount (top mi) || tixCount (loc mi) < boxCount (loc mi) showDecPath dp = putStrLn (" "++ concat (intersperse "." dp)) report_plugin :: Plugin report_plugin = Plugin { name = "report" , usage = "[OPTION] .. <TIX_FILE> [<MODULE> [<MODULE> ..]]" , options = report_options , summary = "Output textual report about program coverage" , implementation = report_main , init_flags = default_flags , final_flags = default_final_flags } report_main :: Flags -> [String] -> IO () report_main hpcflags (progName:mods) = do let hpcflags1 = hpcflags { includeMods = Set.fromList mods `Set.union` includeMods hpcflags } let prog = getTixFileName $ progName tix <- readTix prog case tix of Just (Tix tickCounts) -> makeReport hpcflags1 progName $ sortBy (\ mod1 mod2 -> tixModuleName mod1 `compare` tixModuleName mod2) $ [ tix' | tix'@(TixModule m _ _ _) <- tickCounts , allowModule hpcflags1 m ] Nothing -> hpcError report_plugin $ "unable to find tix file for:" ++ progName report_main _ [] = hpcError report_plugin $ "no .tix file or executable name specified" makeReport :: Flags -> String -> [TixModule] -> IO () makeReport hpcflags progName modTcs | xmlOutput hpcflags = do putStrLn $ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" putStrLn $ "<coverage name=" ++ show progName ++ ">" if perModule hpcflags then mapM_ (modReport hpcflags) modTcs else return () mis <- mapM (modInfo hpcflags True) modTcs putStrLn $ " <summary>" printModInfo hpcflags (foldr miPlus miZero mis) putStrLn $ " </summary>" putStrLn $ "</coverage>" makeReport hpcflags _ modTcs = if perModule hpcflags then mapM_ (modReport hpcflags) modTcs else do mis <- mapM (modInfo hpcflags True) modTcs printModInfo hpcflags (foldr miPlus miZero mis) element :: String -> [(String,String)] -> IO () element tag attrs = putStrLn $ " <" ++ tag ++ " " ++ unwords [ x ++ "=" ++ show y | (x,y) <- attrs ] ++ "/>" xmlBT :: BoxTixCounts -> [(String, String)] xmlBT (BT b t) = [("boxes",show b),("count",show t)] xmlBBT :: BinBoxTixCounts -> [(String, String)] xmlBBT (BBT b tt tf bt) = [("boxes",show b),("true",show tt),("false",show tf),("count",show (tt + tf + bt))] ------------------------------------------------------------------------------ report_options :: FlagOptSeq report_options = perModuleOpt . decListOpt . excludeOpt . includeOpt . srcDirOpt . hpcDirOpt . xmlOutputOpt
nomeata/ghc
utils/hpc/HpcReport.hs
bsd-3-clause
9,744
16
16
2,623
3,458
1,796
1,662
237
9
{-# LANGUAGE OverloadedStrings, RecordWildCards #-} import qualified Data.Map as M import Data.Map ((!)) import Control.Monad import Data.Yaml import Data.Aeson.Types (withObject) import System.FilePath import ConvertAeson import Examples import Entry main = do Examples {..} <- readExamples "../examples" analyses <- readDirectoryOfYamlFiles "../examples/results" forM_ (M.keys analyses) $ \name -> do let proof = exampleProofs ! name let task = exampleTasks ! (proof !!! "task") let logic = exampleLogics ! (task !!! "logic") let res = incredibleLogic (fromJSON' logic) (fromJSON' task) (fromJSON' proof) case res of Left e -> putStrLn $ "Skippping " ++ name ++ ":\n" ++ e Right r -> encodeFile ("../examples/results" </> name <.> "yaml") r where value !!! field = either error id $ parseEither (withObject "" (.: field)) value fromJSON' :: FromJSON a => Value -> a fromJSON' = either error id . parseEither parseJSON
psibi/incredible
logic/tests/update-tests.hs
mit
1,009
1
17
225
331
166
165
24
2
<?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="ro-RO"> <title>Active Scan Rules | 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/ascanrules/src/main/javahelp/org/zaproxy/zap/extension/ascanrules/resources/help_ro_RO/helpset_ro_RO.hs
apache-2.0
978
83
52
160
398
210
188
-1
-1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.WorkspaceNames -- Copyright : (c) Tomas Janousek <tomi@nomi.cz> -- License : BSD3-style (see LICENSE) -- -- Maintainer : Tomas Janousek <tomi@nomi.cz> -- Stability : experimental -- Portability : unportable -- -- Provides bindings to rename workspaces, show these names in DynamicLog and -- swap workspaces along with their names. These names survive restart. -- Together with "XMonad.Layout.WorkspaceDir" this provides for a fully -- dynamic topic space workflow. -- ----------------------------------------------------------------------------- {-# LANGUAGE DeriveDataTypeable #-} module XMonad.Actions.WorkspaceNames ( -- * Usage -- $usage -- * Workspace naming renameWorkspace, workspaceNamesPP, getWorkspaceNames, setWorkspaceName, setCurrentWorkspaceName, -- * Workspace swapping swapTo, swapTo', swapWithCurrent, -- * Workspace prompt workspaceNamePrompt ) where import XMonad import qualified XMonad.StackSet as W import qualified XMonad.Util.ExtensibleState as XS import XMonad.Actions.CycleWS (findWorkspace, WSType(..), Direction1D(..)) import qualified XMonad.Actions.SwapWorkspaces as Swap import XMonad.Hooks.DynamicLog (PP(..)) import XMonad.Prompt (mkXPrompt, XPConfig) import XMonad.Prompt.Workspace (Wor(Wor)) import XMonad.Util.WorkspaceCompare (getSortByIndex) import qualified Data.Map as M import Data.Maybe (fromMaybe) import Data.List (isInfixOf) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@ file: -- -- > import XMonad.Actions.WorkspaceNames -- -- Then add keybindings like the following: -- -- > , ((modm .|. shiftMask, xK_r ), renameWorkspace def) -- -- and apply workspaceNamesPP to your DynamicLog pretty-printer: -- -- > myLogHook = -- > workspaceNamesPP xmobarPP >>= dynamicLogString >>= xmonadPropLog -- -- We also provide a modification of "XMonad.Actions.SwapWorkspaces"\'s -- functionality, which may be used this way: -- -- > , ((modMask .|. shiftMask, xK_Left ), swapTo Prev) -- > , ((modMask .|. shiftMask, xK_Right ), swapTo Next) -- -- > [((modm .|. controlMask, k), swapWithCurrent i) -- > | (i, k) <- zip workspaces [xK_1 ..]] -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". -- | Workspace names container. newtype WorkspaceNames = WorkspaceNames (M.Map WorkspaceId String) deriving (Typeable, Read, Show) instance ExtensionClass WorkspaceNames where initialValue = WorkspaceNames M.empty extensionType = PersistentExtension -- | Returns a function that maps workspace tag @\"t\"@ to @\"t:name\"@ for -- workspaces with a name, and to @\"t\"@ otherwise. getWorkspaceNames :: X (WorkspaceId -> String) getWorkspaceNames = do WorkspaceNames m <- XS.get return $ \wks -> case M.lookup wks m of Nothing -> wks Just s -> wks ++ ":" ++ s -- | Sets the name of a workspace. Empty string makes the workspace unnamed -- again. setWorkspaceName :: WorkspaceId -> String -> X () setWorkspaceName w name = do WorkspaceNames m <- XS.get XS.put $ WorkspaceNames $ if null name then M.delete w m else M.insert w name m refresh -- | Sets the name of the current workspace. See 'setWorkspaceName'. setCurrentWorkspaceName :: String -> X () setCurrentWorkspaceName name = do current <- gets (W.currentTag . windowset) setWorkspaceName current name -- | Prompt for a new name for the current workspace and set it. renameWorkspace :: XPConfig -> X () renameWorkspace conf = do mkXPrompt pr conf (const (return [])) setCurrentWorkspaceName where pr = Wor "Workspace name: " -- | Modify "XMonad.Hooks.DynamicLog"\'s pretty-printing format to show -- workspace names as well. workspaceNamesPP :: PP -> X PP workspaceNamesPP pp = do names <- getWorkspaceNames return $ pp { ppCurrent = ppCurrent pp . names, ppVisible = ppVisible pp . names, ppHidden = ppHidden pp . names, ppHiddenNoWindows = ppHiddenNoWindows pp . names, ppUrgent = ppUrgent pp . names } -- | See 'XMonad.Actions.SwapWorkspaces.swapTo'. This is the same with names. swapTo :: Direction1D -> X () swapTo dir = swapTo' dir AnyWS -- | Swap with the previous or next workspace of the given type. swapTo' :: Direction1D -> WSType -> X () swapTo' dir which = findWorkspace getSortByIndex dir which 1 >>= swapWithCurrent -- | See 'XMonad.Actions.SwapWorkspaces.swapWithCurrent'. This is almost the -- same with names. swapWithCurrent :: WorkspaceId -> X () swapWithCurrent t = do current <- gets (W.currentTag . windowset) swapNames t current windows $ Swap.swapWorkspaces t current -- | Swap names of the two workspaces. swapNames :: WorkspaceId -> WorkspaceId -> X () swapNames w1 w2 = do WorkspaceNames m <- XS.get let getname w = fromMaybe "" $ M.lookup w m set w name m' = if null name then M.delete w m' else M.insert w name m' XS.put $ WorkspaceNames $ set w1 (getname w2) $ set w2 (getname w1) $ m -- | Same behavior than 'XMonad.Prompt.Workspace.workspacePrompt' excepted it acts on the workspace name provided by this module. workspaceNamePrompt :: XPConfig -> (String -> X ()) -> X () workspaceNamePrompt conf job = do myWorkspaces <- gets $ map W.tag . W.workspaces . windowset myWorkspacesName <- getWorkspaceNames >>= \f -> return $ map f myWorkspaces let pairs = zip myWorkspacesName myWorkspaces mkXPrompt (Wor "Select workspace: ") conf (contains myWorkspacesName) (job . toWsId pairs) where toWsId pairs name = case lookup name pairs of Nothing -> "" Just i -> i contains completions input = return $ filter (Data.List.isInfixOf input) completions
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Actions/WorkspaceNames.hs
bsd-2-clause
6,064
0
13
1,304
1,141
616
525
85
2
{-# LANGUAGE PatternGuards #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} -- | Reduction to Weak Head Normal Form module Idris.Core.WHNF(whnf, WEnv) where import Idris.Core.TT import Idris.Core.CaseTree import Idris.Core.Evaluate hiding (quote) import qualified Idris.Core.Evaluate as Evaluate import Debug.Trace -- | A stack entry consists of a term and the environment it is to be -- evaluated in (i.e. it's a thunk) type StackEntry = (Term, WEnv) data WEnv = WEnv Int -- number of free variables [(Term, WEnv)] deriving Show type Stack = [StackEntry] -- | A WHNF is a top level term evaluated in the empty environment. It is -- always headed by either an irreducible expression, i.e. a constructor, -- a lambda, a constant, or a postulate -- -- Every 'Term' or 'Type' in this structure is associated with the -- environment it was encountered in, so that when we quote back to a term -- we get the substitutions right. data WHNF = WDCon Int Int Bool Name (Type, WEnv) -- ^ data constructor | WTCon Int Int Name (Type, WEnv) -- ^ type constructor | WPRef Name (Type, WEnv) -- ^irreducible global (e.g. a postulate) | WBind Name (Binder Term) (Term, WEnv) | WApp WHNF (Term, WEnv) | WConstant Const | WProj WHNF Int | WType UExp | WUType Universe | WErased | WImpossible -- | Reduce a *closed* term to weak head normal form. whnf :: Context -> Term -> Term whnf ctxt tm = quote (do_whnf ctxt (WEnv 0 []) tm) do_whnf :: Context -> WEnv -> Term -> WHNF do_whnf ctxt env tm = eval env [] tm where eval :: WEnv -> Stack -> Term -> WHNF eval wenv@(WEnv d env) stk (V i) | i < length env = let (tm, env') = env !! i in eval env' stk tm | otherwise = error "Can't happen: WHNF scope error" eval wenv@(WEnv d env) stk (Bind n (Let t v) sc) = eval (WEnv d ((v, wenv) : env)) stk sc eval (WEnv d env) [] (Bind n b sc) = WBind n b (sc, WEnv (d + 1) env) eval (WEnv d env) ((tm, tenv) : stk) (Bind n b sc) = eval (WEnv d ((tm, tenv) : env)) stk sc eval env stk (P nt n ty) = apply env nt n ty stk eval env stk (App _ f a) = eval env ((a, env) : stk) f eval env stk (Constant c) = unload (WConstant c) stk -- Should never happen in compile time code (for now...) eval env stk (Proj tm i) = unload (WProj (eval env [] tm) i) stk eval env stk Erased = unload WErased stk eval env stk Impossible = unload WImpossible stk eval env stk (TType u) = unload (WType u) stk eval env stk (UType u) = unload (WUType u) stk apply :: WEnv -> NameType -> Name -> Type -> Stack -> WHNF apply env nt n ty stk = let wp = case nt of DCon t a u -> WDCon t a u n (ty, env) TCon t a -> WTCon t a n (ty, env) _ -> WPRef n (ty, env) in case lookupDefExact n ctxt of Just (CaseOp ci _ _ _ _ cd) -> let (ns, tree) = cases_compiletime cd in case evalCase env ns tree stk of Just w -> w Nothing -> unload wp stk Just (Operator _ i op) -> if i <= length stk then case runOp env op (take i stk) (drop i stk) of Just v -> v Nothing -> unload wp stk else unload wp stk _ -> unload wp stk unload :: WHNF -> Stack -> WHNF unload f [] = f unload f (a : as) = unload (WApp f a) as runOp :: WEnv -> ([Value] -> Maybe Value) -> Stack -> Stack -> Maybe WHNF runOp env op stk rest = do vals <- mapM tmtoValue stk case op vals of Just (VConstant c) -> Just $ unload (WConstant c) rest -- Operators run on values, so we have to convert back -- and forth. This is pretty ugly, but operators that -- aren't run on constants are themselves pretty ugly -- (it's prim__believe_me and prim__syntacticEq, for -- example) so let's not worry too much... Just val -> Just $ eval env rest (quoteTerm val) _ -> Nothing tmtoValue :: (Term, WEnv) -> Maybe Value tmtoValue (tm, tenv) = case eval tenv [] tm of WConstant c -> Just (VConstant c) _ -> let tm' = quoteEnv tenv tm in Just (toValue ctxt [] tm') evalCase :: WEnv -> [Name] -> SC -> Stack -> Maybe WHNF evalCase wenv@(WEnv d env) ns tree args | length ns > length args = Nothing | otherwise = let args' = take (length ns) args rest = drop (length ns) args in do (tm, amap) <- evalTree wenv (zip ns args') tree let wtm = pToVs (map fst amap) tm Just $ eval (WEnv d (map snd amap)) rest wtm evalTree :: WEnv -> [(Name, (Term, WEnv))] -> SC -> Maybe (Term, [(Name, (Term, WEnv))]) evalTree env amap (STerm tm) = Just (tm, amap) evalTree env amap (Case _ n alts) = case lookup n amap of Just (tm, tenv) -> findAlt env amap (deconstruct (eval tenv [] tm) []) alts _ -> Nothing evalTree _ _ _ = Nothing deconstruct :: WHNF -> Stack -> (WHNF, Stack) deconstruct (WApp f arg) stk = deconstruct f (arg : stk) deconstruct t stk = (t, stk) findAlt :: WEnv -> [(Name, (Term, WEnv))] -> (WHNF, Stack) -> [CaseAlt] -> Maybe (Term, [(Name, (Term, WEnv))]) findAlt env amap (WDCon tag _ _ _ _, args) alts | Just (ns, sc) <- findTag tag alts = let amap' = updateAmap (zip ns args) amap in evalTree env amap' sc | Just sc <- findDefault alts = evalTree env amap sc findAlt env amap (WConstant c, []) alts | Just sc <- findConst c alts = evalTree env amap sc | Just sc <- findDefault alts = evalTree env amap sc findAlt _ _ _ _ = Nothing findTag :: Int -> [CaseAlt] -> Maybe ([Name], SC) findTag i [] = Nothing findTag i (ConCase n j ns sc : xs) | i == j = Just (ns, sc) findTag i (_ : xs) = findTag i xs findDefault :: [CaseAlt] -> Maybe SC findDefault [] = Nothing findDefault (DefaultCase sc : xs) = Just sc findDefault (_ : xs) = findDefault xs findConst c [] = Nothing findConst c (ConstCase c' v : xs) | c == c' = Just v findConst (AType (ATInt ITNative)) (ConCase n 1 [] v : xs) = Just v findConst (AType ATFloat) (ConCase n 2 [] v : xs) = Just v findConst (AType (ATInt ITChar)) (ConCase n 3 [] v : xs) = Just v findConst StrType (ConCase n 4 [] v : xs) = Just v findConst (AType (ATInt ITBig)) (ConCase n 6 [] v : xs) = Just v findConst (AType (ATInt (ITFixed ity))) (ConCase n tag [] v : xs) | tag == 7 + fromEnum ity = Just v findConst c (_ : xs) = findConst c xs updateAmap newm amap = newm ++ filter (\ (x, _) -> not (elem x (map fst newm))) amap quote :: WHNF -> Term quote (WDCon t a u n (ty, env)) = P (DCon t a u) n (quoteEnv env ty) quote (WTCon t a n (ty, env)) = P (TCon t a) n (quoteEnv env ty) quote (WPRef n (ty, env)) = P Ref n (quoteEnv env ty) quote (WBind n ty (sc, env)) = Bind n ty (quoteEnv env sc) quote (WApp f (a, env)) = App Complete (quote f) (quoteEnv env a) quote (WConstant c) = Constant c quote (WProj t i) = Proj (quote t) i quote (WType u) = TType u quote (WUType u) = UType u quote WErased = Erased quote WImpossible = Impossible quoteEnv :: WEnv -> Term -> Term quoteEnv (WEnv d ws) tm = qe' d ws tm where qe' d ts (V i) | i < d = V i | otherwise = let (tm, env) = ts !! (i - d) in quoteEnv env tm qe' d ts (Bind n b sc) = Bind n (fmap (qe' d ts) b) (qe' (d + 1) ts sc) qe' d ts (App c f a) = App c (qe' d ts f) (qe' d ts a) qe' d ts (P nt n ty) = P nt n (qe' d ts ty) qe' d ts (Proj tm i) = Proj (qe' d ts tm) i qe' d ts tm = tm
adnelson/Idris-dev
src/Idris/Core/WHNF.hs
bsd-3-clause
8,413
0
17
3,011
3,364
1,708
1,656
161
41
import System.Process (readProcessWithExitCode) import System.Exit (ExitCode(ExitSuccess)) import System.IO.Unsafe (unsafeInterleaveIO) import Utils (stringsFromStatus, Hash(MkHash)) import Data.Maybe (fromMaybe) {- Git commands -} successOrNothing :: (ExitCode, a, b) -> Maybe a successOrNothing (exitCode, output, _) = if exitCode == ExitSuccess then Just output else Nothing safeRun :: String -> [String] -> IO (Maybe String) safeRun command arguments = do -- IO output <- readProcessWithExitCode command arguments "" return (successOrNothing output) gitrevparse :: IO (Maybe Hash) gitrevparse = do -- IO mresult <- safeRun "git" ["rev-parse", "--short", "HEAD"] let rev = do -- Maybe result <- mresult return (MkHash (init result)) return rev {- main -} main :: IO () main = do -- IO status <- getContents mhash <- unsafeInterleaveIO gitrevparse -- defer the execution until we know we need the hash let result = do -- Maybe strings <- stringsFromStatus mhash status return (unwords strings) putStr (fromMaybe "" result)
Bryan792/dotfiles
zsh/zsh-git-prompt/src/app/Main.hs
mit
1,058
5
16
180
349
180
169
28
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude , RecordWildCards , BangPatterns , PatternGuards , NondecreasingIndentation , Rank2Types #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Handle.Internals -- Copyright : (c) The University of Glasgow, 1994-2001 -- License : see libraries/base/LICENSE -- -- Maintainer : libraries@haskell.org -- Stability : internal -- Portability : non-portable -- -- This module defines the basic operations on I\/O \"handles\". All -- of the operations defined here are independent of the underlying -- device. -- ----------------------------------------------------------------------------- -- #hide module GHC.IO.Handle.Internals ( withHandle, withHandle', withHandle_, withHandle__', withHandle_', withAllHandles__, wantWritableHandle, wantReadableHandle, wantReadableHandle_, wantSeekableHandle, mkHandle, mkFileHandle, mkDuplexHandle, openTextEncoding, closeTextCodecs, initBufferState, dEFAULT_CHAR_BUFFER_SIZE, flushBuffer, flushWriteBuffer, flushCharReadBuffer, flushCharBuffer, flushByteReadBuffer, flushByteWriteBuffer, readTextDevice, writeCharBuffer, readTextDeviceNonBlocking, decodeByteBuf, augmentIOError, ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable, ioe_finalizedHandle, ioe_bufsiz, hClose_help, hLookAhead_, HandleFinalizer, handleFinalizer, debugIO, ) where import GHC.IO import GHC.IO.IOMode import GHC.IO.Encoding as Encoding import GHC.IO.Handle.Types import GHC.IO.Buffer import GHC.IO.BufferedIO (BufferedIO) import GHC.IO.Exception import GHC.IO.Device (IODevice, SeekMode(..)) import qualified GHC.IO.Device as IODevice import qualified GHC.IO.BufferedIO as Buffered import GHC.Conc.Sync import GHC.Real import GHC.Base import GHC.Exception import GHC.Num ( Num(..) ) import GHC.Show import GHC.IORef import GHC.MVar import Data.Typeable import Control.Monad import Data.Maybe import Foreign.Safe import System.Posix.Internals hiding (FD) import Foreign.C c_DEBUG_DUMP :: Bool c_DEBUG_DUMP = False -- --------------------------------------------------------------------------- -- Creating a new handle type HandleFinalizer = FilePath -> MVar Handle__ -> IO () newFileHandle :: FilePath -> Maybe HandleFinalizer -> Handle__ -> IO Handle newFileHandle filepath mb_finalizer hc = do m <- newMVar hc case mb_finalizer of Just finalizer -> addMVarFinalizer m (finalizer filepath m) Nothing -> return () return (FileHandle filepath m) -- --------------------------------------------------------------------------- -- Working with Handles {- In the concurrent world, handles are locked during use. This is done by wrapping an MVar around the handle which acts as a mutex over operations on the handle. To avoid races, we use the following bracketing operations. The idea is to obtain the lock, do some operation and replace the lock again, whether the operation succeeded or failed. We also want to handle the case where the thread receives an exception while processing the IO operation: in these cases we also want to relinquish the lock. There are three versions of @withHandle@: corresponding to the three possible combinations of: - the operation may side-effect the handle - the operation may return a result If the operation generates an error or an exception is raised, the original handle is always replaced. -} {-# INLINE withHandle #-} withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a withHandle fun h@(FileHandle _ m) act = withHandle' fun h m act withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act withHandle' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO (Handle__,a)) -> IO a withHandle' fun h m act = mask_ $ do (h',v) <- do_operation fun h act m checkHandleInvariants h' putMVar m h' return v {-# INLINE withHandle_ #-} withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a withHandle_ fun h@(FileHandle _ m) act = withHandle_' fun h m act withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a withHandle_' fun h m act = withHandle' fun h m $ \h_ -> do a <- act h_ return (h_,a) withAllHandles__ :: String -> Handle -> (Handle__ -> IO Handle__) -> IO () withAllHandles__ fun h@(FileHandle _ m) act = withHandle__' fun h m act withAllHandles__ fun h@(DuplexHandle _ r w) act = do withHandle__' fun h r act withHandle__' fun h w act withHandle__' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO Handle__) -> IO () withHandle__' fun h m act = mask_ $ do h' <- do_operation fun h act m checkHandleInvariants h' putMVar m h' return () do_operation :: String -> Handle -> (Handle__ -> IO a) -> MVar Handle__ -> IO a do_operation fun h act m = do h_ <- takeMVar m checkHandleInvariants h_ act h_ `catchException` handler h_ where handler h_ e = do putMVar m h_ case () of _ | Just ioe <- fromException e -> ioError (augmentIOError ioe fun h) _ | Just async_ex <- fromException e -> do -- see Note [async] let _ = async_ex :: AsyncException t <- myThreadId throwTo t e do_operation fun h act m _otherwise -> throwIO e -- Note [async] -- -- If an asynchronous exception is raised during an I/O operation, -- normally it is fine to just re-throw the exception synchronously. -- However, if we are inside an unsafePerformIO or an -- unsafeInterleaveIO, this would replace the enclosing thunk with the -- exception raised, which is wrong (#3997). We have to release the -- lock on the Handle, but what do we replace the thunk with? What -- should happen when the thunk is subsequently demanded again? -- -- The only sensible choice we have is to re-do the IO operation on -- resumption, but then we have to be careful in the IO library that -- this is always safe to do. In particular we should -- -- never perform any side-effects before an interruptible operation -- -- because the interruptible operation may raise an asynchronous -- exception, which may cause the operation and its side effects to be -- subsequently performed again. -- -- Re-doing the IO operation is achieved by: -- - using throwTo to re-throw the asynchronous exception asynchronously -- in the current thread -- - on resumption, it will be as if throwTo returns. In that case, we -- recursively invoke the original operation (see do_operation above). -- -- Interruptible operations in the I/O library are: -- - threadWaitRead/threadWaitWrite -- - fillReadBuffer/flushWriteBuffer -- - readTextDevice/writeTextDevice augmentIOError :: IOException -> String -> Handle -> IOException augmentIOError ioe@IOError{ ioe_filename = fp } fun h = ioe { ioe_handle = Just h, ioe_location = fun, ioe_filename = filepath } where filepath | Just _ <- fp = fp | otherwise = case h of FileHandle path _ -> Just path DuplexHandle path _ _ -> Just path -- --------------------------------------------------------------------------- -- Wrapper for write operations. wantWritableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a wantWritableHandle fun h@(FileHandle _ m) act = wantWritableHandle' fun h m act wantWritableHandle fun h@(DuplexHandle _ _ m) act = wantWritableHandle' fun h m act -- we know it's not a ReadHandle or ReadWriteHandle, but we have to -- check for ClosedHandle/SemiClosedHandle. (#4808) wantWritableHandle' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a wantWritableHandle' fun h m act = withHandle_' fun h m (checkWritableHandle act) checkWritableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a checkWritableHandle act h_@Handle__{..} = case haType of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle ReadHandle -> ioe_notWritable ReadWriteHandle -> do buf <- readIORef haCharBuffer when (not (isWriteBuffer buf)) $ do flushCharReadBuffer h_ flushByteReadBuffer h_ buf <- readIORef haCharBuffer writeIORef haCharBuffer buf{ bufState = WriteBuffer } buf <- readIORef haByteBuffer buf' <- Buffered.emptyWriteBuffer haDevice buf writeIORef haByteBuffer buf' act h_ _other -> act h_ -- --------------------------------------------------------------------------- -- Wrapper for read operations. wantReadableHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a wantReadableHandle fun h act = withHandle fun h (checkReadableHandle act) wantReadableHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a wantReadableHandle_ fun h@(FileHandle _ m) act = wantReadableHandle' fun h m act wantReadableHandle_ fun h@(DuplexHandle _ m _) act = wantReadableHandle' fun h m act -- we know it's not a WriteHandle or ReadWriteHandle, but we have to -- check for ClosedHandle/SemiClosedHandle. (#4808) wantReadableHandle' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a wantReadableHandle' fun h m act = withHandle_' fun h m (checkReadableHandle act) checkReadableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a checkReadableHandle act h_@Handle__{..} = case haType of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle AppendHandle -> ioe_notReadable WriteHandle -> ioe_notReadable ReadWriteHandle -> do -- a read/write handle and we want to read from it. We must -- flush all buffered write data first. bbuf <- readIORef haByteBuffer when (isWriteBuffer bbuf) $ do when (not (isEmptyBuffer bbuf)) $ flushByteWriteBuffer h_ cbuf' <- readIORef haCharBuffer writeIORef haCharBuffer cbuf'{ bufState = ReadBuffer } bbuf <- readIORef haByteBuffer writeIORef haByteBuffer bbuf{ bufState = ReadBuffer } act h_ _other -> act h_ -- --------------------------------------------------------------------------- -- Wrapper for seek operations. wantSeekableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a wantSeekableHandle fun h@(DuplexHandle _ _ _) _act = ioException (IOError (Just h) IllegalOperation fun "handle is not seekable" Nothing Nothing) wantSeekableHandle fun h@(FileHandle _ m) act = withHandle_' fun h m (checkSeekableHandle act) checkSeekableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a checkSeekableHandle act handle_@Handle__{haDevice=dev} = case haType handle_ of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle AppendHandle -> ioe_notSeekable _ -> do b <- IODevice.isSeekable dev if b then act handle_ else ioe_notSeekable -- ----------------------------------------------------------------------------- -- Handy IOErrors ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable, ioe_cannotFlushNotSeekable, ioe_notSeekable :: IO a ioe_closedHandle = ioException (IOError Nothing IllegalOperation "" "handle is closed" Nothing Nothing) ioe_EOF = ioException (IOError Nothing EOF "" "" Nothing Nothing) ioe_notReadable = ioException (IOError Nothing IllegalOperation "" "handle is not open for reading" Nothing Nothing) ioe_notWritable = ioException (IOError Nothing IllegalOperation "" "handle is not open for writing" Nothing Nothing) ioe_notSeekable = ioException (IOError Nothing IllegalOperation "" "handle is not seekable" Nothing Nothing) ioe_cannotFlushNotSeekable = ioException (IOError Nothing IllegalOperation "" "cannot flush the read buffer: underlying device is not seekable" Nothing Nothing) ioe_finalizedHandle :: FilePath -> Handle__ ioe_finalizedHandle fp = throw (IOError Nothing IllegalOperation "" "handle is finalized" Nothing (Just fp)) ioe_bufsiz :: Int -> IO a ioe_bufsiz n = ioException (IOError Nothing InvalidArgument "hSetBuffering" ("illegal buffer size " ++ showsPrec 9 n []) Nothing Nothing) -- 9 => should be parens'ified. -- --------------------------------------------------------------------------- -- Wrapper for Handle encoding/decoding. -- The interface for TextEncoding changed so that a TextEncoding doesn't raise -- an exception if it encounters an invalid sequnce. Furthermore, encoding -- returns a reason as to why encoding stopped, letting us know if it was due -- to input/output underflow or an invalid sequence. -- -- This code adapts this elaborated interface back to the original TextEncoding -- interface. -- -- FIXME: it is possible that Handle code using the haDecoder/haEncoder fields -- could be made clearer by using the 'encode' interface directly. I have not -- looked into this. streamEncode :: BufferCodec from to state -> Buffer from -> Buffer to -> IO (Buffer from, Buffer to) streamEncode codec from to = go (from, to) where go (from, to) = do (why, from', to') <- encode codec from to -- When we are dealing with Handles, we don't care about input/output -- underflow particularly, and we want to delay errors about invalid -- sequences as far as possible. case why of Encoding.InvalidSequence | bufL from == bufL from' -> recover codec from' to' >>= go _ -> return (from', to') -- ----------------------------------------------------------------------------- -- Handle Finalizers -- For a duplex handle, we arrange that the read side points to the write side -- (and hence keeps it alive if the read side is alive). This is done by -- having the haOtherSide field of the read side point to the read side. -- The finalizer is then placed on the write side, and the handle only gets -- finalized once, when both sides are no longer required. -- NOTE about finalized handles: It's possible that a handle can be -- finalized and then we try to use it later, for example if the -- handle is referenced from another finalizer, or from a thread that -- has become unreferenced and then resurrected (arguably in the -- latter case we shouldn't finalize the Handle...). Anyway, -- we try to emit a helpful message which is better than nothing. -- -- [later; 8/2010] However, a program like this can yield a strange -- error message: -- -- main = writeFile "out" loop -- loop = let x = x in x -- -- because the main thread and the Handle are both unreachable at the -- same time, the Handle may get finalized before the main thread -- receives the NonTermination exception, and the exception handler -- will then report an error. We'd rather this was not an error and -- the program just prints "<<loop>>". handleFinalizer :: FilePath -> MVar Handle__ -> IO () handleFinalizer fp m = do handle_ <- takeMVar m (handle_', _) <- hClose_help handle_ putMVar m handle_' return () -- --------------------------------------------------------------------------- -- Allocating buffers -- using an 8k char buffer instead of 32k improved performance for a -- basic "cat" program by ~30% for me. --SDM dEFAULT_CHAR_BUFFER_SIZE :: Int dEFAULT_CHAR_BUFFER_SIZE = 2048 -- 8k/sizeof(HsChar) getCharBuffer :: IODevice dev => dev -> BufferState -> IO (IORef CharBuffer, BufferMode) getCharBuffer dev state = do buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state ioref <- newIORef buffer is_tty <- IODevice.isTerminal dev let buffer_mode | is_tty = LineBuffering | otherwise = BlockBuffering Nothing return (ioref, buffer_mode) mkUnBuffer :: BufferState -> IO (IORef CharBuffer, BufferMode) mkUnBuffer state = do buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state -- See [note Buffer Sizing], GHC.IO.Handle.Types ref <- newIORef buffer return (ref, NoBuffering) -- ----------------------------------------------------------------------------- -- Flushing buffers -- | syncs the file with the buffer, including moving the -- file pointer backwards in the case of a read buffer. This can fail -- on a non-seekable read Handle. flushBuffer :: Handle__ -> IO () flushBuffer h_@Handle__{..} = do buf <- readIORef haCharBuffer case bufState buf of ReadBuffer -> do flushCharReadBuffer h_ flushByteReadBuffer h_ WriteBuffer -> do flushByteWriteBuffer h_ -- | flushes the Char buffer only. Works on all Handles. flushCharBuffer :: Handle__ -> IO () flushCharBuffer h_@Handle__{..} = do cbuf <- readIORef haCharBuffer case bufState cbuf of ReadBuffer -> do flushCharReadBuffer h_ WriteBuffer -> when (not (isEmptyBuffer cbuf)) $ error "internal IO library error: Char buffer non-empty" -- ----------------------------------------------------------------------------- -- Writing data (flushing write buffers) -- flushWriteBuffer flushes the buffer iff it contains pending write -- data. Flushes both the Char and the byte buffer, leaving both -- empty. flushWriteBuffer :: Handle__ -> IO () flushWriteBuffer h_@Handle__{..} = do buf <- readIORef haByteBuffer when (isWriteBuffer buf) $ flushByteWriteBuffer h_ flushByteWriteBuffer :: Handle__ -> IO () flushByteWriteBuffer h_@Handle__{..} = do bbuf <- readIORef haByteBuffer when (not (isEmptyBuffer bbuf)) $ do bbuf' <- Buffered.flushWriteBuffer haDevice bbuf writeIORef haByteBuffer bbuf' -- write the contents of the CharBuffer to the Handle__. -- The data will be encoded and pushed to the byte buffer, -- flushing if the buffer becomes full. writeCharBuffer :: Handle__ -> CharBuffer -> IO () writeCharBuffer h_@Handle__{..} !cbuf = do -- bbuf <- readIORef haByteBuffer debugIO ("writeCharBuffer: cbuf=" ++ summaryBuffer cbuf ++ " bbuf=" ++ summaryBuffer bbuf) (cbuf',bbuf') <- case haEncoder of Nothing -> latin1_encode cbuf bbuf Just encoder -> (streamEncode encoder) cbuf bbuf debugIO ("writeCharBuffer after encoding: cbuf=" ++ summaryBuffer cbuf' ++ " bbuf=" ++ summaryBuffer bbuf') -- flush if the write buffer is full if isFullBuffer bbuf' -- or we made no progress || not (isEmptyBuffer cbuf') && bufL cbuf' == bufL cbuf -- or the byte buffer has more elements than the user wanted buffered || (case haBufferMode of BlockBuffering (Just s) -> bufferElems bbuf' >= s NoBuffering -> True _other -> False) then do bbuf'' <- Buffered.flushWriteBuffer haDevice bbuf' writeIORef haByteBuffer bbuf'' else writeIORef haByteBuffer bbuf' if not (isEmptyBuffer cbuf') then writeCharBuffer h_ cbuf' else return () -- ----------------------------------------------------------------------------- -- Flushing read buffers -- It is always possible to flush the Char buffer back to the byte buffer. flushCharReadBuffer :: Handle__ -> IO () flushCharReadBuffer Handle__{..} = do cbuf <- readIORef haCharBuffer if isWriteBuffer cbuf || isEmptyBuffer cbuf then return () else do -- haLastDecode is the byte buffer just before we did our last batch of -- decoding. We're going to re-decode the bytes up to the current char, -- to find out where we should revert the byte buffer to. (codec_state, bbuf0) <- readIORef haLastDecode cbuf0 <- readIORef haCharBuffer writeIORef haCharBuffer cbuf0{ bufL=0, bufR=0 } -- if we haven't used any characters from the char buffer, then just -- re-install the old byte buffer. if bufL cbuf0 == 0 then do writeIORef haByteBuffer bbuf0 return () else do case haDecoder of Nothing -> do writeIORef haByteBuffer bbuf0 { bufL = bufL bbuf0 + bufL cbuf0 } -- no decoder: the number of bytes to decode is the same as the -- number of chars we have used up. Just decoder -> do debugIO ("flushCharReadBuffer re-decode, bbuf=" ++ summaryBuffer bbuf0 ++ " cbuf=" ++ summaryBuffer cbuf0) -- restore the codec state setState decoder codec_state (bbuf1,cbuf1) <- (streamEncode decoder) bbuf0 cbuf0{ bufL=0, bufR=0, bufSize = bufL cbuf0 } debugIO ("finished, bbuf=" ++ summaryBuffer bbuf1 ++ " cbuf=" ++ summaryBuffer cbuf1) writeIORef haByteBuffer bbuf1 -- When flushing the byte read buffer, we seek backwards by the number -- of characters in the buffer. The file descriptor must therefore be -- seekable: attempting to flush the read buffer on an unseekable -- handle is not allowed. flushByteReadBuffer :: Handle__ -> IO () flushByteReadBuffer h_@Handle__{..} = do bbuf <- readIORef haByteBuffer if isEmptyBuffer bbuf then return () else do seekable <- IODevice.isSeekable haDevice when (not seekable) $ ioe_cannotFlushNotSeekable let seek = negate (bufR bbuf - bufL bbuf) debugIO ("flushByteReadBuffer: new file offset = " ++ show seek) IODevice.seek haDevice RelativeSeek (fromIntegral seek) writeIORef haByteBuffer bbuf{ bufL=0, bufR=0 } -- ---------------------------------------------------------------------------- -- Making Handles mkHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -> FilePath -> HandleType -> Bool -- buffered? -> Maybe TextEncoding -> NewlineMode -> Maybe HandleFinalizer -> Maybe (MVar Handle__) -> IO Handle mkHandle dev filepath ha_type buffered mb_codec nl finalizer other_side = do openTextEncoding mb_codec ha_type $ \ mb_encoder mb_decoder -> do let buf_state = initBufferState ha_type bbuf <- Buffered.newBuffer dev buf_state bbufref <- newIORef bbuf last_decode <- newIORef (error "codec_state", bbuf) (cbufref,bmode) <- if buffered then getCharBuffer dev buf_state else mkUnBuffer buf_state spares <- newIORef BufferListNil newFileHandle filepath finalizer (Handle__ { haDevice = dev, haType = ha_type, haBufferMode = bmode, haByteBuffer = bbufref, haLastDecode = last_decode, haCharBuffer = cbufref, haBuffers = spares, haEncoder = mb_encoder, haDecoder = mb_decoder, haCodec = mb_codec, haInputNL = inputNL nl, haOutputNL = outputNL nl, haOtherSide = other_side }) -- | makes a new 'Handle' mkFileHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -- ^ the underlying IO device, which must support -- 'IODevice', 'BufferedIO' and 'Typeable' -> FilePath -- ^ a string describing the 'Handle', e.g. the file -- path for a file. Used in error messages. -> IOMode -- The mode in which the 'Handle' is to be used -> Maybe TextEncoding -- Create the 'Handle' with no text encoding? -> NewlineMode -- Translate newlines? -> IO Handle mkFileHandle dev filepath iomode mb_codec tr_newlines = do mkHandle dev filepath (ioModeToHandleType iomode) True{-buffered-} mb_codec tr_newlines (Just handleFinalizer) Nothing{-other_side-} -- | like 'mkFileHandle', except that a 'Handle' is created with two -- independent buffers, one for reading and one for writing. Used for -- full-duplex streams, such as network sockets. mkDuplexHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -> FilePath -> Maybe TextEncoding -> NewlineMode -> IO Handle mkDuplexHandle dev filepath mb_codec tr_newlines = do write_side@(FileHandle _ write_m) <- mkHandle dev filepath WriteHandle True mb_codec tr_newlines (Just handleFinalizer) Nothing -- no othersie read_side@(FileHandle _ read_m) <- mkHandle dev filepath ReadHandle True mb_codec tr_newlines Nothing -- no finalizer (Just write_m) return (DuplexHandle filepath read_m write_m) ioModeToHandleType :: IOMode -> HandleType ioModeToHandleType ReadMode = ReadHandle ioModeToHandleType WriteMode = WriteHandle ioModeToHandleType ReadWriteMode = ReadWriteHandle ioModeToHandleType AppendMode = AppendHandle initBufferState :: HandleType -> BufferState initBufferState ReadHandle = ReadBuffer initBufferState _ = WriteBuffer openTextEncoding :: Maybe TextEncoding -> HandleType -> (forall es ds . Maybe (TextEncoder es) -> Maybe (TextDecoder ds) -> IO a) -> IO a openTextEncoding Nothing ha_type cont = cont Nothing Nothing openTextEncoding (Just TextEncoding{..}) ha_type cont = do mb_decoder <- if isReadableHandleType ha_type then do decoder <- mkTextDecoder return (Just decoder) else return Nothing mb_encoder <- if isWritableHandleType ha_type then do encoder <- mkTextEncoder return (Just encoder) else return Nothing cont mb_encoder mb_decoder closeTextCodecs :: Handle__ -> IO () closeTextCodecs Handle__{..} = do case haDecoder of Nothing -> return (); Just d -> Encoding.close d case haEncoder of Nothing -> return (); Just d -> Encoding.close d -- --------------------------------------------------------------------------- -- closing Handles -- hClose_help is also called by lazyRead (in GHC.IO.Handle.Text) when -- EOF is read or an IO error occurs on a lazy stream. The -- semi-closed Handle is then closed immediately. We have to be -- careful with DuplexHandles though: we have to leave the closing to -- the finalizer in that case, because the write side may still be in -- use. hClose_help :: Handle__ -> IO (Handle__, Maybe SomeException) hClose_help handle_ = case haType handle_ of ClosedHandle -> return (handle_,Nothing) _ -> do mb_exc1 <- trymaybe $ flushWriteBuffer handle_ -- interruptible -- it is important that hClose doesn't fail and -- leave the Handle open (#3128), so we catch -- exceptions when flushing the buffer. (h_, mb_exc2) <- hClose_handle_ handle_ return (h_, if isJust mb_exc1 then mb_exc1 else mb_exc2) trymaybe :: IO () -> IO (Maybe SomeException) trymaybe io = (do io; return Nothing) `catchException` \e -> return (Just e) hClose_handle_ :: Handle__ -> IO (Handle__, Maybe SomeException) hClose_handle_ h_@Handle__{..} = do -- close the file descriptor, but not when this is the read -- side of a duplex handle. -- If an exception is raised by the close(), we want to continue -- to close the handle and release the lock if it has one, then -- we return the exception to the caller of hClose_help which can -- raise it if necessary. maybe_exception <- case haOtherSide of Nothing -> trymaybe $ IODevice.close haDevice Just _ -> return Nothing -- free the spare buffers writeIORef haBuffers BufferListNil writeIORef haCharBuffer noCharBuffer writeIORef haByteBuffer noByteBuffer -- release our encoder/decoder closeTextCodecs h_ -- we must set the fd to -1, because the finalizer is going -- to run eventually and try to close/unlock it. -- ToDo: necessary? the handle will be marked ClosedHandle -- XXX GHC won't let us use record update here, hence wildcards return (Handle__{ haType = ClosedHandle, .. }, maybe_exception) {-# NOINLINE noCharBuffer #-} noCharBuffer :: CharBuffer noCharBuffer = unsafePerformIO $ newCharBuffer 1 ReadBuffer {-# NOINLINE noByteBuffer #-} noByteBuffer :: Buffer Word8 noByteBuffer = unsafePerformIO $ newByteBuffer 1 ReadBuffer -- --------------------------------------------------------------------------- -- Looking ahead hLookAhead_ :: Handle__ -> IO Char hLookAhead_ handle_@Handle__{..} = do buf <- readIORef haCharBuffer -- fill up the read buffer if necessary new_buf <- if isEmptyBuffer buf then readTextDevice handle_ buf else return buf writeIORef haCharBuffer new_buf peekCharBuf (bufRaw buf) (bufL buf) -- --------------------------------------------------------------------------- -- debugging debugIO :: String -> IO () debugIO s | c_DEBUG_DUMP = do _ <- withCStringLen (s ++ "\n") $ \(p, len) -> c_write 1 (castPtr p) (fromIntegral len) return () | otherwise = return () -- ---------------------------------------------------------------------------- -- Text input/output -- Read characters into the provided buffer. Return when any -- characters are available; raise an exception if the end of -- file is reached. readTextDevice :: Handle__ -> CharBuffer -> IO CharBuffer readTextDevice h_@Handle__{..} cbuf = do -- bbuf0 <- readIORef haByteBuffer debugIO ("readTextDevice: cbuf=" ++ summaryBuffer cbuf ++ " bbuf=" ++ summaryBuffer bbuf0) bbuf1 <- if not (isEmptyBuffer bbuf0) then return bbuf0 else do (r,bbuf1) <- Buffered.fillReadBuffer haDevice bbuf0 if r == 0 then ioe_EOF else do -- raise EOF return bbuf1 debugIO ("readTextDevice after reading: bbuf=" ++ summaryBuffer bbuf1) (bbuf2,cbuf') <- case haDecoder of Nothing -> do writeIORef haLastDecode (error "codec_state", bbuf1) latin1_decode bbuf1 cbuf Just decoder -> do state <- getState decoder writeIORef haLastDecode (state, bbuf1) (streamEncode decoder) bbuf1 cbuf debugIO ("readTextDevice after decoding: cbuf=" ++ summaryBuffer cbuf' ++ " bbuf=" ++ summaryBuffer bbuf2) writeIORef haByteBuffer bbuf2 if bufR cbuf' == bufR cbuf -- no new characters then readTextDevice' h_ bbuf2 cbuf -- we need more bytes to make a Char else return cbuf' -- we have an incomplete byte sequence at the end of the buffer: try to -- read more bytes. readTextDevice' :: Handle__ -> Buffer Word8 -> CharBuffer -> IO CharBuffer readTextDevice' h_@Handle__{..} bbuf0 cbuf0 = do -- -- copy the partial sequence to the beginning of the buffer, so we have -- room to read more bytes. bbuf1 <- slideContents bbuf0 -- readTextDevice only calls us if we got some bytes but not some characters. -- This can't occur if haDecoder is Nothing because latin1_decode accepts all bytes. let Just decoder = haDecoder (r,bbuf2) <- Buffered.fillReadBuffer haDevice bbuf1 if r == 0 then do (bbuf3, cbuf1) <- recover decoder bbuf2 cbuf0 writeIORef haByteBuffer bbuf3 -- We should recursively invoke readTextDevice after recovery, -- if recovery did not add at least one new character to the buffer: -- 1. If we were using IgnoreCodingFailure it might be the case that -- cbuf1 is the same length as cbuf0 and we need to raise ioe_EOF -- 2. If we were using TransliterateCodingFailure we might have *mutated* -- the byte buffer without changing the pointers into either buffer. -- We need to try and decode it again - it might just go through this time. if bufR cbuf1 == bufR cbuf0 then readTextDevice h_ cbuf1 else return cbuf1 else do debugIO ("readTextDevice' after reading: bbuf=" ++ summaryBuffer bbuf2) (bbuf3,cbuf1) <- do state <- getState decoder writeIORef haLastDecode (state, bbuf2) (streamEncode decoder) bbuf2 cbuf0 debugIO ("readTextDevice' after decoding: cbuf=" ++ summaryBuffer cbuf1 ++ " bbuf=" ++ summaryBuffer bbuf3) writeIORef haByteBuffer bbuf3 if bufR cbuf0 == bufR cbuf1 then readTextDevice' h_ bbuf3 cbuf1 else return cbuf1 -- Read characters into the provided buffer. Do not block; -- return zero characters instead. Raises an exception on end-of-file. readTextDeviceNonBlocking :: Handle__ -> CharBuffer -> IO CharBuffer readTextDeviceNonBlocking h_@Handle__{..} cbuf = do -- bbuf0 <- readIORef haByteBuffer when (isEmptyBuffer bbuf0) $ do (r,bbuf1) <- Buffered.fillReadBuffer0 haDevice bbuf0 if isNothing r then ioe_EOF else do -- raise EOF writeIORef haByteBuffer bbuf1 decodeByteBuf h_ cbuf -- Decode bytes from the byte buffer into the supplied CharBuffer. decodeByteBuf :: Handle__ -> CharBuffer -> IO CharBuffer decodeByteBuf h_@Handle__{..} cbuf = do -- bbuf0 <- readIORef haByteBuffer (bbuf2,cbuf') <- case haDecoder of Nothing -> do writeIORef haLastDecode (error "codec_state", bbuf0) latin1_decode bbuf0 cbuf Just decoder -> do state <- getState decoder writeIORef haLastDecode (state, bbuf0) (streamEncode decoder) bbuf0 cbuf writeIORef haByteBuffer bbuf2 return cbuf'
mightymoose/liquidhaskell
benchmarks/ghc-7.4.1/IO/Handle/Internals.hs
bsd-3-clause
34,050
0
23
8,279
6,704
3,384
3,320
537
6
{-# LANGUAGE OverloadedStrings #-} -- | <http://strava.github.io/api/v3/efforts/> module Strive.Types.Efforts ( EffortDetailed (..) ) where import Control.Applicative (empty) import Data.Aeson (FromJSON, Value (Object), parseJSON, (.:), (.:?)) import Data.Text (Text) import Data.Time.Clock (UTCTime) import Strive.Enums (ResourceState) import Strive.Types.Segments (SegmentSummary) -- | <http://strava.github.io/api/v3/efforts/#detailed> data EffortDetailed = EffortDetailed { effortDetailed_activityId :: Integer , effortDetailed_athleteId :: Integer , effortDetailed_averageCadence :: Maybe Double , effortDetailed_averageHeartrate :: Maybe Double , effortDetailed_averageWatts :: Maybe Double , effortDetailed_distance :: Double , effortDetailed_elapsedTime :: Integer , effortDetailed_endIndex :: Integer , effortDetailed_hidden :: Maybe Bool , effortDetailed_id :: Integer , effortDetailed_komRank :: Maybe Integer , effortDetailed_maxHeartrate :: Maybe Integer , effortDetailed_movingTime :: Integer , effortDetailed_name :: Text , effortDetailed_prRank :: Maybe Integer , effortDetailed_resourceState :: ResourceState , effortDetailed_segment :: SegmentSummary , effortDetailed_startDate :: UTCTime , effortDetailed_startDateLocal :: UTCTime , effortDetailed_startIndex :: Integer } deriving Show instance FromJSON EffortDetailed where parseJSON (Object o) = EffortDetailed <$> ((o .: "activity") >>= (.: "id")) <*> ((o .: "athlete") >>= (.: "id")) <*> o .:? "average_cadence" <*> o .:? "average_heartrate" <*> o .:? "average_watts" <*> o .: "distance" <*> o .: "elapsed_time" <*> o .: "end_index" <*> o .:? "hidden" <*> o .: "id" <*> o .:? "kom_rank" <*> o .:? "max_heartrate" <*> o .: "moving_time" <*> o .: "name" <*> o .:? "pr_rank" <*> o .: "resource_state" <*> o .: "segment" <*> o .: "start_date" <*> o .: "start_date_local" <*> o .: "start_index" parseJSON _ = empty
liskin/strive
library/Strive/Types/Efforts.hs
mit
2,149
0
47
499
472
274
198
54
0
{-# LANGUAGE ScopedTypeVariables #-} import Control.Monad (mapM_) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as IO import Text.Parsec import Text.Parsec.Text data CompressedText = Uncompressed Int | Compressed Text Int deriving (Eq) main = do input <- Compressed <$> (Text.strip <$> IO.getContents) <*> return 1 print $ measureLength input measureLength :: CompressedText -> Int measureLength (Uncompressed length) = length measureLength compressed@(Compressed text repetitions) = repetitions * sum (map measureLength (parseCompressed text)) parseCompressed :: Text -> [CompressedText] parseCompressed text = either (error . show) id $ parse parser "" text where parser = many $ try uncompressed <|> compressed uncompressed = Uncompressed <$> length <$> many1 alphaNum compressed = do char '(' segmentLength :: Int <- read <$> many1 digit char 'x' repetitions :: Int <- read <$> many1 digit char ')' compressedText <- Text.pack <$> count segmentLength anyChar return $ Compressed compressedText repetitions
SamirTalwar/advent-of-code
2016/AOC_09_2.hs
mit
1,124
1
13
217
353
176
177
29
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} module Cenary.Codegen.CodegenM where import Cenary.Codegen.CodegenError import Cenary.Codegen.CodegenState import Cenary.Codegen.ContextM import Cenary.Codegen.Memory import Cenary.Codegen.TcM import Cenary.EvmAPI.OpcodeM import Control.Monad.Except import Control.Monad.State -- | This type alias will be used for top-level codegen, since -- at top level we use all contexts type CodegenM m = (OpcodeM m, MonadState CodegenState m, MemoryM m, MonadError CodegenError m, ContextM m, TcM m, MonadFix m)
yigitozkavci/ivy
src/Cenary/Codegen/CodegenM.hs
mit
687
0
6
158
113
70
43
13
0
module TruthTable.Printing (PrintConfig(..), printM, printTruthTable, printWithDefaultConfig, printResultOrErrorWithDefaultConfig ) where import TruthTable.Types -- there's no reason to be Lazy when printing (we discard results right -- after anyway) and String generates a lot of thunks import Control.Monad.State.Strict data PrintConfig = PrintConfig { delimiter :: String, trueString :: String, falseString :: String, resultColumnName :: String } type Printer = State (PrintConfig, TruthTable) defaultConfig :: PrintConfig defaultConfig = PrintConfig { delimiter= "\t", trueString = "T", falseString = "F", resultColumnName = "Result" } -- | take a row from the TruthTable, return it, and update state to reflect -- this takeRow :: Printer (TruthSet, Bool) takeRow = do (conf, truthTable) <- get let split [] = error "Cannot split an empty list" split (x:xs) = (x, xs) (thisTruthSet, remTruthSets) <- split . truthSets <$> getTruthTable (thisResult, remResults) <- split . rs <$> getTruthTable let newTruthTable = truthTable { truthSets = remTruthSets, rs = remResults } put (conf, newTruthTable) return (thisTruthSet, thisResult) getConfig :: Printer PrintConfig getConfig = fst <$> get getTruthTable :: Printer TruthTable getTruthTable = snd <$> get getVariables :: Printer [Variable] getVariables = variables . snd <$> get printBool :: PrintConfig -> Bool -> String printBool conf True = trueString conf printBool conf False = falseString conf printRow :: Printer String printRow = do truthTable <- getTruthTable -- make sure a row exists before we take one if (not . null . truthSets $ truthTable) && (not . null . rs $ truthTable) then printRow' --if there are no rows left to print return an empty string else return "" where printRow' = do conf <- getConfig (truthSet, result) <- takeRow let pBool = printBool conf delim = delimiter conf -- TODO: consider printing the first item separately so the line -- doesn't start with a delimiter let rowStr = foldr (\thisTruthValue acc -> acc ++ delim ++ pBool thisTruthValue) "" truthSet -- don't forget to print the result as the last column return $ rowStr ++ delim ++ pBool result printHeader :: Printer String printHeader = do conf <- getConfig vars <- getVariables let delim = delimiter conf -- TODO: consider printing the first item separately so the line -- doesn't start with a delimiter let header = foldr (\(Variable varName) acc -> acc ++ delim ++ varName) "" vars resColName = resultColumnName conf -- have to add the result column header explicitly return $ header ++ delim ++ resColName printRows :: Printer (Either String String) printRows = do truthTable <- getTruthTable let truthSetsLength = length . truthSets $ truthTable resultsLength = length . rs $ truthTable printedRow <- printRow if truthSetsLength /= resultsLength then return . Left $ "Number of TruthSets does not match number of results! " ++ (show . truthSets $ truthTable) ++ (show . rs $ truthTable) else if (truthSetsLength == 0) && (resultsLength == 0) -- if we're out of rows to print we're done then return . Right $ printedRow -- recurse to print the next row -- we have to bind twice: once to unwrap the state -- monad, again to unwrap the Either type else (fmap ((printedRow ++ "\n") ++)) <$> printRows printM :: Printer (Either String String) printM = do header <- printHeader rowsR <- printRows --prepend the header if the message is valid case rowsR of (Left e) -> return . Left $ e (Right printedRows) -> return . Right $ header ++ "\n" ++ printedRows printTruthTable :: PrintConfig -> TruthTable -> Either String String printTruthTable conf truthTable = evalState printM (conf, truthTable) printWithDefaultConfig :: TruthTable -> Either String String printWithDefaultConfig = printTruthTable defaultConfig printResultOrErrorWithDefaultConfig :: Either [Variable] TruthTable -> String printResultOrErrorWithDefaultConfig (Left vars) = "Error: " ++ (show vars) printResultOrErrorWithDefaultConfig (Right truthTable) = case printWithDefaultConfig truthTable of Right result -> result Left err -> "Error: " ++ err
tjakway/truth-table-generator
src/TruthTable/Printing.hs
mit
4,957
0
16
1,528
1,076
570
506
88
3
{- | Module : Xcode.CompilerSpec License : MIT Maintainer : shea@shealevy.com Stability : unstable Portability : portable A compiler specification -} module Xcode.CompilerSpec ( CompilerSpec( .. ) ) where -- | A compiler specification -- Compilers will be added as they are found data CompilerSpec = Clang1.0
shlevy/xcode-types
src/Xcode/CompilerSpec.hs
mit
340
1
5
78
23
17
6
-1
-1
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Control.Monad.ST.Unsafe.Compat" -- from a globally unique namespace. module Control.Monad.ST.Unsafe.Compat.Repl ( module Control.Monad.ST.Unsafe.Compat ) where import "this" Control.Monad.ST.Unsafe.Compat
haskell-compat/base-compat
base-compat/src/Control/Monad/ST/Unsafe/Compat/Repl.hs
mit
324
0
5
31
34
27
7
5
0
{- 1000-digit Fibonacci number Problem 25 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the first term in the Fibonacci sequence to contain 1000 digits? -} import Data.List fibs = 1 : 1 : [ a + b | (a,b) <- zip fibs (tail fibs) ] -- 1) My first attempt euler25 = fst $ head $ dropWhile (\(n,x) -> length (show x) < 1000) $ zip [1..] fibs -- (0.14 secs, 91924848 bytes) -- 2) Based on a forum answer euler25' = elemIndex 1000 $ map (length . show) fibs -- (0.14 secs, 91890352 bytes) -- 3) From http://projecteuler.net/thread=25 -- Using the property that fib n ~= phi * fib (n-1) and fib n ~= phi ^ n phi = (1 + sqrt 5) / 2 log10 = logBase 10 euler25log = ( 999 + log10 (sqrt 5) ) / (log10 phi) + 1
feliposz/project-euler-solutions
haskell/euler25.hs
mit
970
0
13
225
199
107
92
7
1
{-| Module : FRP.AST.Construct Description : Helper functions to construct ASTs by hand -} module FRP.AST.Construct where import FRP.AST tmfst :: EvalTerm -> EvalTerm tmfst = TmFst () tmsnd :: EvalTerm -> EvalTerm tmsnd = TmSnd () tmtup :: EvalTerm -> EvalTerm -> EvalTerm tmtup = TmTup () tminl :: EvalTerm -> EvalTerm tminl = TmInl () tminr :: EvalTerm -> EvalTerm tminr = TmInr () tmcase :: EvalTerm -> (Name, EvalTerm) -> (Name, EvalTerm) -> EvalTerm tmcase = TmCase () tmlam :: Name -> EvalTerm -> EvalTerm tmlam n t = TmLam () n Nothing t tmlamty :: Name -> Type () -> EvalTerm -> EvalTerm tmlamty n ty t = TmLam () n (Just ty) t tmvar :: Name -> EvalTerm tmvar = TmVar () tmapp :: EvalTerm -> EvalTerm -> EvalTerm tmapp = TmApp () tmcons :: EvalTerm -> EvalTerm -> EvalTerm tmcons = TmCons () tmout :: Type () -> EvalTerm -> EvalTerm tmout = TmOut () tminto :: Type () -> EvalTerm -> EvalTerm tminto = TmInto () tmstable :: EvalTerm -> EvalTerm tmstable = TmStable () tmdelay :: EvalTerm -> EvalTerm -> EvalTerm tmdelay = TmDelay () tmpromote :: EvalTerm -> EvalTerm tmpromote = TmPromote () tmlet :: Pattern -> EvalTerm -> EvalTerm -> EvalTerm tmlet = TmLet () tmlit :: Lit -> EvalTerm tmlit = TmLit () tmint = tmlit . LNat tmunit = tmlit $ LUnit tmbool = tmlit . LBool tmbinop :: BinOp -> EvalTerm -> EvalTerm -> EvalTerm tmbinop = TmBinOp () tmite :: EvalTerm -> EvalTerm -> EvalTerm -> EvalTerm tmite = TmITE () tmpntr :: Label -> EvalTerm tmpntr = TmPntr () tmpntrderef :: Label -> EvalTerm tmpntrderef = TmPntrDeref () tmalloc :: EvalTerm tmalloc = TmAlloc () tmfix :: Name -> Type () -> EvalTerm -> EvalTerm tmfix n ty t = TmFix () n (Just ty) t infixr 0 --> (-->) :: Name -> EvalTerm -> EvalTerm (-->) = tmlam infixr 0 -:> (-:>) :: (Name, Type ()) -> EvalTerm -> EvalTerm (nm, ty) -:> trm = tmlamty nm ty trm infixl 9 <| (<|) :: EvalTerm -> EvalTerm -> EvalTerm (<|) = tmapp eq :: EvalTerm -> EvalTerm -> EvalTerm eq = tmbinop Eq (<==) :: EvalTerm -> EvalTerm -> EvalTerm (<==) = tmbinop Leq (>==) :: EvalTerm -> EvalTerm -> EvalTerm (>==) = tmbinop Geq (>.) :: EvalTerm -> EvalTerm -> EvalTerm (>.) = tmbinop Gt (<.) :: EvalTerm -> EvalTerm -> EvalTerm (<.) = tmbinop Lt tyvar = TyVar () typrod = TyProd () tysum = TySum () tyarr = TyArr () tylater = TyLater () tystable = TyStable () tystream = TyStream () tyrec = TyRec () tyalloc = TyAlloc () tynat = TyPrim () TyNat tybool = TyPrim () TyBool tyunit = TyPrim () TyUnit (.*.) :: Type () -> Type () -> Type () (.*.) = TyProd () (.+.) :: Type () -> Type () -> Type () (.+.) = TySum () infixr 1 |-> (|->) :: Type () -> Type () -> Type () (|->) = TyArr ()
adamschoenemann/simple-frp
src/FRP/AST/Construct.hs
mit
2,677
0
8
566
1,136
606
530
91
1
module Network.JSONApi.ResourceSpec where import qualified Data.Aeson as AE import qualified Data.ByteString.Lazy.Char8 as BS import Data.Maybe (isJust, fromJust) import Data.Text (Text, pack) import GHC.Generics (Generic) import Network.JSONApi import Network.URL (URL, importURL) import TestHelpers (prettyEncode) import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = describe "JSON serialization" $ it "can be encoded and decoded from JSON" $ do let encodedJson = BS.unpack . prettyEncode $ toResource testObject let decodedJson = AE.decode (BS.pack encodedJson) :: Maybe (Resource TestObject) isJust decodedJson `shouldBe` True {- putStrLn encodedJson -} {- putStrLn $ show . fromJust $ decodedJson -} data TestObject = TestObject { myId :: Int , myName :: Text , myAge :: Int , myFavoriteFood :: Text } deriving (Show, Generic) instance AE.ToJSON TestObject instance AE.FromJSON TestObject instance ResourcefulEntity TestObject where resourceIdentifier = pack . show . myId resourceType _ = "TestObject" resourceLinks _ = Just myResourceLinks resourceMetaData _ = Just myResourceMetaData resourceRelationships _ = Just myRelationshipss data PaginationMetaObject = PaginationMetaObject { currentPage :: Int , totalPages :: Int } deriving (Show, Generic) instance AE.ToJSON PaginationMetaObject instance AE.FromJSON PaginationMetaObject instance MetaObject PaginationMetaObject where typeName _ = "pagination" myRelationshipss :: Relationships myRelationshipss = mkRelationships relationship <> mkRelationships otherRelationship relationship :: Relationship relationship = fromJust $ mkRelationship (Just $ Identifier "42" "FriendOfTestObject" Nothing) (Just myResourceLinks) otherRelationship :: Relationship otherRelationship = fromJust $ mkRelationship (Just $ Identifier "49" "CousinOfTestObject" Nothing) (Just myResourceLinks) myResourceLinks :: Links myResourceLinks = mkLinks [ ("self", toURL "/me") , ("related", toURL "/tacos/4") ] myResourceMetaData :: Meta myResourceMetaData = mkMeta (PaginationMetaObject 1 14) toURL :: String -> URL toURL = fromJust . importURL testObject :: TestObject testObject = TestObject 1 "Fred Armisen" 49 "Pizza"
toddmohney/json-api
test/Network/JSONApi/ResourceSpec.hs
mit
2,296
0
14
398
587
317
270
64
1
module Main where import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy as B (readFile) import Data.List (maximumBy) import qualified Data.Map.Strict as Map import Prelude hiding (read) import System.Environment (getArgs) import Turing getMove :: Transition -> Bool -> String getMove t isFinal | isFinal && tAction == "RIGHT" = "!RSH_HALT" | isFinal && tAction == "LEFT" = "!LSH_HALT" | tAction == "RIGHT" = "!RSH" | otherwise = "!LSH" where tAction = action t -- Escape the ! mark because the shell wants to run something when it sees it esc :: String -> String esc s | head s == '!' = "\\" ++ s | otherwise = s encodeTransitions :: Map.Map String [Transition] -> [String] -> Bool -> String encodeTransitions transMap finalStates True = let encodeTransLst state ts acc = foldr (\x y -> y ++ "&TRANS" ++ esc state ++ esc (read x) ++ esc (to_state x) ++ esc (write x) ++ esc (getMove x $ to_state x `elem` finalStates)) acc ts in Map.foldrWithKey encodeTransLst "" transMap encodeTransitions transMap finalStates False = let encodeTransLst state ts acc = foldr (\x y -> y ++ "&TRANS" ++ state ++ read x ++ to_state x ++ write x ++ getMove x (to_state x `elem` finalStates)) acc ts in Map.foldrWithKey encodeTransLst "" transMap encodeMachine :: Machine -> String -> Bool -> String encodeMachine m input e = "&TAPE_START" ++ encodeTransitions (transitions m) (finals m) e ++ "&INIT" ++ initial m ++ "&INPUT" ++ input ++ "&EOI" legitElements :: [String] -> String -> [(String, Int)] -> [(String, Int)] legitElements [] _ tokens = tokens legitElements (x:xs) input legitTokens | x == take len input = legitElements xs input $ (x, len) : legitTokens | otherwise = legitElements xs input legitTokens where len = length x isGoodInput :: [String] -> String -> Bool isGoodInput _ "" = True isGoodInput symbols input = not (null legitToks) && isGoodInput symbols (drop (snd goodSym) input) where legitToks = legitElements symbols input [] goodSym = maximumBy (\ (_, x) (_, y) -> compare x y) legitToks showResult :: Machine -> String -> Bool -> String showResult m input isEscaped | isGoodInput symbols input = encodeMachine m input isEscaped | otherwise = "Wrong input" where symbols = filter (\y -> y /= blank m) $ alphabet m readJsonFile :: FilePath -> String -> Bool -> IO () readJsonFile file input isEscaped = do myJson <- B.readFile file let parsed = Aeson.eitherDecode myJson :: Either String Machine case parsed of Right x -> putStrLn $ showResult x input isEscaped Left y -> putStrLn y main :: IO () main = do args <- getArgs let isEscaped = "-e" `elem` args case filter (/= "-e") args of (x:(y:_)) -> readJsonFile x y isEscaped _ -> do putStrLn "Error: parameters" putStrLn "Usage: ./program ex.json \"input\" [-e]" putStrLn "-e: Escape the '!'. Use this option if your shell needs it."
range12/there-is-no-B-side
tools/encoder/Encoder.hs
mit
3,228
0
18
896
1,091
547
544
67
2
{-# htermination (^^) :: Fractional a => a -> Int -> a #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_CARETCARET_1.hs
mit
59
0
2
13
3
2
1
1
0
module PrettyJSON ( renderJValue ) where import Numeric (showHex) import Data.Char (ord) import Data.Bits (shiftR, (.&.)) import Prettify(Doc, (<>), char, double, fsep, hcat, punctuate, text, compact, pretty) import SimpleJSON(JValue(..)) renderJValue :: JValue -> Doc renderJValue (JBool True) = text "true" renderJValue (JBool False) = text "false" renderJValue JNull = text "null" renderJValue (JNumber num) = double num renderJValue (JString str) = string str renderJValue (JArray array) = series '[' ']' renderJValue array renderJValue (JObject obj) = series '{' '}' field obj where field (name, val) = string name <> text ": " <> renderJValue val string :: String -> Doc string = enclose '"' '"' . hcat . map oneChar enclose :: Char -> Char -> Doc -> Doc enclose left right x = char left <> x <> char right oneChar :: Char -> Doc oneChar c = case lookup c simpleEscapes of Just r -> text r Nothing | mustEscape c -> hexEscape c | otherwise -> char c where mustEscape c = c < ' ' || c == '\x7f' || c > '\xff' simpleEscapes :: [(Char, String)] simpleEscapes = zipWith ch "\b\n\f\r\t\\\"/" "bnfrt\\\"/" where ch a b = (a, ['\\',b]) smallHex :: Int -> Doc smallHex x = text "\\u" <> text (replicate (4 - length h) '0') <> text h where h = showHex x "" astral :: Int -> Doc astral n = smallHex (a + 0xd800) <> smallHex (b + 0xdc00) where a = (n `shiftR` 10) .&. 0x3ff b = n .&. 0x3ff hexEscape :: Char -> Doc hexEscape c | d < 0x10000 = smallHex d | otherwise = astral (d - 0x10000) where d = ord c series :: Char -> Char -> (a -> Doc) -> [a] -> Doc series open close item = enclose open close . fsep . punctuate (char ',') . map item
Bolt64/my_code
haskell/myprecious/PrettyJSON.hs
mit
1,869
0
12
540
744
383
361
49
2
module Test.Framework.Providers.QuickCheck2 where import Test.QuickCheck import Test.Hspec.Core.Spec import Test.Framework.Providers.API testProperty :: Testable a => TestName -> a -> Test testProperty name = specItem name . property
sol/hspec-test-framework
src/Test/Framework/Providers/QuickCheck2.hs
mit
267
0
7
59
62
36
26
6
1
-- Make a spiral -- http://www.codewars.com/kata/534e01fbbb17187c7e0000c6/ module Spiral where spiralize :: Int -> [[Int]] spiralize n | n == 5 = [[1,1,1,1,1],[0,0,0,0,1],[1,1,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] | n == 6 = [[1,1,1,1,1,1],[0,0,0,0,0,1],[1,1,1,1,0,1],[1,0,0,1,0,1],[1,0,0,0,0,1],[1,1,1,1,1,1]] | otherwise = fl:sl:rest where fl = replicate n 1 sl = replicate (n-1) 0 ++ [1] rest = zipWith (++) (map reverse . reverse .spiralize $ (n-2)) (replicate (n-3) [0, 1] ++ [[1, 1]])
gafiatulin/codewars
src/3 kyu/Spiral.hs
mit
559
1
12
137
395
240
155
8
1
{- applyinhg Key and copy texture without scaling -} {-# LANGUAGE OverloadedStrings #-} module Lesson10 where -- import qualified SDL -- import Data.Word (Word8(..)) import Linear.Affine (Point(..)) import Linear.V2 (V2(..)) import Linear.V4 (V4(..)) import Foreign.C.Types (CInt) -- import Control.Monad (unless) -- import qualified Config -- -- definition of LTextureexture data LTexture = LTexture {getTx :: SDL.Texture, getWH :: (V2 CInt)} -- class Renderable a where renderQuad :: a -> CInt -> CInt -> Maybe (SDL.Rectangle CInt) render :: SDL.Renderer -> a -> CInt -> CInt -> IO () free :: a -> IO () -- instance Renderable LTexture where renderQuad ltx x y = Just $ SDL.Rectangle (P $ V2 x y) $ getWH ltx render rdr ltx x y = do SDL.copy rdr (getTx ltx) Nothing (renderQuad ltx x y) free ltx = SDL.destroyTexture (getTx ltx) -- definition of key yellowKey :: Maybe (V4 Word8) yellowKey = Just $ V4 maxBound maxBound 0 maxBound -- definition of loading function loadFromFile :: SDL.Renderer -> FilePath -> IO LTexture loadFromFile rdr path = do tempSf <- SDL.loadBMP path wh <- SDL.surfaceDimensions tempSf -- ************ -- SDL.surfaceColorKey tempSf SDL.$= yellowKey -- ************ -- tx <- SDL.createTextureFromSurface rdr tempSf SDL.freeSurface tempSf return (LTexture tx wh) -- note: in lazyfoo's tutorial, the function mapRGB is called -- however, in sdl2 haskell binding, -- mapRGB is not needed and thus flagged as deprecated -- lesson10 :: IO () lesson10 = do -- initialize SDL SDL.initialize [SDL.InitVideo] -- create window window <- SDL.createWindow "Lesson10" Config.winConfig SDL.HintRenderScaleQuality SDL.$= SDL.ScaleLinear renderer <- SDL.createRenderer window (-1) Config.rdrConfig SDL.rendererDrawColor renderer SDL.$= V4 maxBound maxBound minBound maxBound imgBg <- loadFromFile renderer "./img/10/bg.bmp" imgHumanish <- loadFromFile renderer "./img/10/humanish.bmp" let loop = do events <- SDL.pollEvents let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events -- *** beginning of drawing region *** SDL.rendererDrawColor renderer SDL.$= V4 minBound minBound maxBound maxBound SDL.clear renderer -- render with our own function render renderer imgBg 0 0 render renderer imgHumanish 240 190 -- SDL.present renderer -- *** end of drawing region *** unless quit loop loop free imgBg free imgHumanish SDL.destroyRenderer renderer SDL.destroyWindow window SDL.quit
rueshyna/sdl2-examples
src/Lesson10.hs
mit
2,648
0
18
601
747
374
373
58
1
{-# LANGUAGE OverloadedStrings #-} -- | Start up screen. Very brief. module View.Starting where import React import React.Lucid import View.Template -- | Start up screen. starting :: Monad m => ReactT state m () starting = div_ (do class_ "starting" centered_ (do img_ (src_ "/static/img/starting.png") p_ (do class_ "screen-info" "Starting ...")))
fpco/stackage-view
client/View/Starting.hs
mit
432
0
17
134
99
49
50
12
1
module CornerPoints.Transpose ( transposeZ, transposeX, transposeY ) where import CornerPoints.CornerPoints import CornerPoints.Points(Point(..), transposeZ) import CornerPoints.Transposable(TransposePoint, transposeX, transposeY, transposeZ) ------------------------------------- transposing cubes/points ---------------------------------------------- {- Used for: changing points by adding values, as opposed to mulipling with the scalePoints -} instance TransposePoint CornerPoints where ---------------- z-axis ---------------------- transposeZ _ (CornerPointsError err) = CornerPointsError err transposeZ f (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) = CubePoints {f1=(transposeZ f f1), f2=(transposeZ f f2), f3=(transposeZ f f3), f4=(transposeZ f f4), b1=(transposeZ f b1), b2=(transposeZ f b2), b3=(transposeZ f b3), b4=(transposeZ f b4)} transposeZ f (TopFace b2 f2 b3 f3 ) = TopFace { f2=(transposeZ f f2), f3=(transposeZ f f3), b2=(transposeZ f b2), b3=(transposeZ f b3)} transposeZ f (BottomFace b1 f1 b4 f4) = BottomFace {f1=(transposeZ f f1), f4=(transposeZ f f4 ), b1=(transposeZ f b1 ), b4=(transposeZ f b4 )} transposeZ f (RightFace b3 b4 f3 f4) = RightFace {b3=(transposeZ f b3), b4=(transposeZ f b4), f3=(transposeZ f f3), f4=(transposeZ f f4)} transposeZ f (LeftFace b1 b2 f1 f2)= LeftFace {b1=(transposeZ f b1), b2=(transposeZ f b2), f1=(transposeZ f f1), f2=(transposeZ f f2) } transposeZ f (BottomFrontLine f1 f4) = BottomFrontLine {f1=(transposeZ f f1), f4=(transposeZ f f4)} transposeZ f (BackTopLine b2 b3) = BackTopLine {b2=(transposeZ f b2), b3=(transposeZ f b3)} transposeZ f (FrontTopLine f2 f3) = FrontTopLine {f2=(transposeZ f f2), f3=(transposeZ f f3)} --------------- x-axis --------------------- transposeX _ (CornerPointsError err) = CornerPointsError err transposeX f (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) = CubePoints {f1=(transposeX f f1), f2=(transposeX f f2), f3=(transposeX f f3), f4=(transposeX f f4), b1=(transposeX f b1), b2=(transposeX f b2), b3=(transposeX f b3), b4=(transposeX f b4)} transposeX f (TopFace b2 f2 b3 f3)= TopFace { f2=(transposeX f f2), f3=(transposeX f f3), b2=(transposeX f b2), b3=(transposeX f b3)} transposeX f (BottomFace b1 f1 b4 f4)= BottomFace {f1=(transposeX f f1), f4=(transposeX f f4), b1=(transposeX f b1), b4=(transposeX f b4)} transposeX f (F1 f1 ) = F1 {f1=(transposeX f f1)} transposeX f (F4 f4 ) = F4 {f4=(transposeX f f4)} transposeX f (B1 b1 ) = B1 {b1=(transposeX f b1)} transposeX f (B4 b4 ) = B4 {b4=(transposeX f b4)} ------------- y-axis ----------------- transposeY _ (CornerPointsError err) = CornerPointsError err transposeY f (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) = CubePoints {f1=(transposeY f f1), f2=(transposeY f f2), f3=(transposeY f f3), f4=(transposeY f f4), b1=(transposeY f b1), b2=(transposeY f b2), b3=(transposeY f b3), b4=(transposeY f b4)} transposeY f (BottomFace b1 f1 b4 f4)= BottomFace {f1=(transposeY f f1), f4=(transposeY f f4), b1=(transposeY f b1), b4=(transposeY f b4)} transposeY f (TopFace b2 f2 b3 f3)= TopFace {f2=(transposeY f f2), f3=(transposeY f f3), b2=(transposeY f b2), b3=(transposeY f b3)} transposeY f (B1 b1 ) = B1 {b1=(transposeY f b1)} transposeY f (B4 b4 ) = B4 {b4=(transposeY f b4)} transposeY f (F1 f1 ) = F1 {f1=(transposeY f f1)} transposeY f (F4 f4 ) = F4 {f4=(transposeY f f4)} {- get rid of all this, replaces with Transposable class. ----------------------------- z-axis --------------------------------------- transposeCornerPointsZ :: (Double -> Double) -> CornerPoints -> CornerPoints transposeCornerPointsZ transposeFactor (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) = CubePoints {f1=(transposeZ transposeFactor f1), f2=(transposeZ transposeFactor f2), f3=(transposeZ transposeFactor f3), f4=(transposeZ transposeFactor f4), b1=(transposeZ transposeFactor b1), b2=(transposeZ transposeFactor b2), b3=(transposeZ transposeFactor b3), b4=(transposeZ transposeFactor b4)} transposeCornerPointsZ transposeFactor (TopFace b2 f2 b3 f3)= TopFace {f2=(transposeZ transposeFactor f2), f3=(transposeZ transposeFactor f3), b2=(transposeZ transposeFactor b2), b3=(transposeZ transposeFactor b3)} transposeCornerPointsZ transposeFactor (BottomFace b1 f1 b4 f4) = BottomFace {f1=(transposeZ transposeFactor f1), f4=(transposeZ transposeFactor f4 ), b1=(transposeZ transposeFactor b1 ), b4=(transposeZ transposeFactor b4 )} transposeCornerPointsZ transposeFactor (BottomFrontLine f1 f4) = BottomFrontLine {f1=(transposeZ transposeFactor f1), f4=(transposeZ transposeFactor f4) } --untested transposeCornerPointsZ transposeFactor (BackTopLine b2 b3) = BackTopLine {b2=(transposeZ transposeFactor b2), b3=(transposeZ transposeFactor b3) } transposeCornerPointsZ transposeFactor (FrontTopLine f2 f3) = FrontTopLine {f2=(transposeZ transposeFactor f2), f3=(transposeZ transposeFactor f3) } -} {- Should be able to get rid of this. Replaces by Transposable class. transposePointZ :: (Double -> Double)-> Point -> Point transposePointZ transposeFactor (Point x y z) = Point {x_axis=x, y_axis=y, z_axis=(transposeFactor z)} transposePointX :: (Double -> Double)-> Point -> Point transposePointX transposeFactor (Point x y z) = Point {x_axis=(transposeFactor x), y_axis=y, z_axis=z} transposeCornerPointsX transposeFactor (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) = CubePoints {f1=(transposePointX transposeFactor f1), f2=(transposePointX transposeFactor f2), f3=(transposePointX transposeFactor f3), f4=(transposePointX transposeFactor f4), b1=(transposePointX transposeFactor b1), b2=(transposePointX transposeFactor b2), b3=(transposePointX transposeFactor b3), b4=(transposePointX transposeFactor b4)} transposeCornerPointsX transposeFactor (TopFace b2 f2 b3 f3)= TopFace { f2=(transposePointX transposeFactor f2), f3=(transposePointX transposeFactor f3), b2=(transposePointX transposeFactor b2), b3=(transposePointX transposeFactor b3)} transposeCornerPointsX transposeFactor (BottomFace b1 f1 b4 f4)= BottomFace {f1=(transposePointX transposeFactor f1), f4=(transposePointX transposeFactor f4), b1=(transposePointX transposeFactor b1), b4=(transposePointX transposeFactor b4)} ------------------------------------ y-axis --------------------------------- transposePointY :: (Double -> Double)-> Point -> Point transposePointY transposeFactor (Point x y z) = Point {x_axis=(x), y_axis=(transposeFactor y), z_axis=z} transposeCornerPointsY transposeFactor (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) = CubePoints {f1=(transposePointY transposeFactor f1), f2=(transposePointY transposeFactor f2), f3=(transposePointY transposeFactor f3), f4=(transposePointY transposeFactor f4), b1=(transposePointY transposeFactor b1), b2=(transposePointY transposeFactor b2), b3=(transposePointY transposeFactor b3), b4=(transposePointY transposeFactor b4)} transposeCornerPointsY transposeFactor (TopFace b2 f2 b3 f3)= TopFace { f2=(transposePointY transposeFactor f2), f3=(transposePointY transposeFactor f3), b2=(transposePointY transposeFactor b2), b3=(transposePointY transposeFactor b3)} transposeCornerPointsY transposeFactor (BottomFace b1 f1 b4 f4)= BottomFace {f1=(transposePointY transposeFactor f1), f4=(transposePointY transposeFactor f4), b1=(transposePointY transposeFactor b1), b4=(transposePointY transposeFactor b4)} -}
heathweiss/Tricad
src/CornerPoints/Transpose.hs
gpl-2.0
8,988
0
9
2,619
1,602
881
721
103
0
-- GenI surface realiser -- Copyright (C) 2005 Carlos Areces and Eric Kow -- -- 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. {-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module NLP.GenI.GraphvizShowPolarity where import Data.List (intercalate) import qualified Data.Map as Map import Data.Maybe ( catMaybes ) import Data.GraphViz import Data.GraphViz.Attributes.Complete import qualified Data.Text.Lazy as TL import NLP.GenI.General(showInterval) import NLP.GenI.Polarity(PolAut, PolState(PolSt), NFA(states, transitions), finalSt) import NLP.GenI.Pretty import NLP.GenI.Graphviz(GraphvizShow(..), gvUnlines) import NLP.GenI.Tag (idname) instance GraphvizShow PolAut where -- we want a directed graph (arrows) graphvizShowGraph aut = DotGraph False True Nothing $ DotStmts [ GraphAttrs [RankDir FromLeft, RankSep [0.02], Pack (PackMargin 1)] , NodeAttrs [FontSize 10] , EdgeAttrs [FontSize 10] ] (graphvizShowAsSubgraph "aut" aut) [] -- all nodes are in the subgraph [] -- graphvizShowAsSubgraph prefix aut = [ DotSG False Nothing $ DotStmts [ NodeAttrs [ Shape Ellipse, Peripheries 1 ] ] [] (zipWith (gvShowState fin) ids st) (concat $ zipWith (gvShowTrans aut stmap) ids st) ] where st = (concat.states) aut fin = finalSt aut ids = map (\x -> prefix `TL.append` TL.pack (show x)) ([0..] :: [Int]) -- map which permits us to assign an id to a state stmap = Map.fromList $ zip st ids gvShowState :: [PolState] -> TL.Text -> PolState -> DotNode TL.Text gvShowState fin stId st = DotNode stId $ decorate [ Label . StrLabel . showSt $ st ] where showSt (PolSt _ ex po) = gvUnlines . catMaybes $ [ Nothing -- Just (snd3 pr) , if null ex then Nothing else Just (TL.fromChunks [pretty ex]) , Just . TL.pack . intercalate "," $ map showInterval po ] decorate = if st `elem` fin then (Peripheries 2 :) else id gvShowTrans :: PolAut -> Map.Map PolState TL.Text -> TL.Text -> PolState -> [DotEdge TL.Text] gvShowTrans aut stmap idFrom st = let -- outgoing transition labels from st trans = Map.findWithDefault Map.empty st $ transitions aut -- returns the graphviz dot command to draw a labeled transition drawTrans (stTo,x) = case Map.lookup stTo stmap of Nothing -> drawTrans' ("id_error_" `TL.append` (TL.pack (sem_ stTo))) x Just idTo -> drawTrans' idTo x where sem_ (PolSt i _ _) = show i --showSem (PolSt (_,pred,_) _ _) = pred drawTrans' idTo x = DotEdge idFrom idTo [Label (drawLabel x)] drawLabel labels = StrLabel . gvUnlines $ labs where lablen = length labels maxlabs = 6 excess = TL.pack $ "...and " ++ show (lablen - maxlabs) ++ " more" -- name t = TL.fromChunks [ idname t ] labstrs = map (maybe "EMPTY" name) labels labs = if lablen > maxlabs then take maxlabs labstrs ++ [ excess ] else labstrs in map drawTrans (Map.toList trans)
kowey/GenI
geni-gui/src/NLP/GenI/GraphvizShowPolarity.hs
gpl-2.0
4,111
0
18
1,164
966
526
440
65
3
module Data.Set.Infix( (∪) , (∩) , (\\) , (∊) , (⊆), (∅), disjointFrom, intersects ) where import Data.Set as Set (∪) :: Ord a => Set a -> Set a -> Set a (∪) = Set.union (∩) :: Ord a => Set a -> Set a -> Set a (∩) = Set.intersection (∊) :: Ord a => a -> Set a -> Bool (∊) = Set.member (⊆) :: Ord a => Set a -> Set a -> Bool (⊆) = Set.isSubsetOf (∅) = Set.empty disjointFrom :: Ord a => Set a -> Set a -> Bool disjointFrom a b = Set.null $ a ∩ b intersects :: Ord a => Set a -> Set a -> Bool intersects a b = not $ a `disjointFrom` b
bordaigorl/jamesbound
src/Data/Set/Infix.hs
gpl-2.0
571
0
8
134
304
171
133
15
1
module CyclicListFlat where import Prelude hiding (cycle, reverse, take, splitAt, zipWith, and, or, null, repeat) import Control.Applicative import qualified Data.List as List import qualified Control.Monad as Monad data CList a = CList { prfx :: [ a ] , cycl :: [ a ] } data View a = CNil | Cons a (CList a) rewind :: Eq a => CList a -> CList a rewind xs = go (List.reverse $ prfx xs) cs [] where cs = List.reverse $ cycl xs go [] cs ds = unsafeCycle (ds ++ List.reverse cs) go ps [] ds = go ps cs [] go (p : ps) (c : cs) ds | p == c = go ps cs (c : ds) | otherwise = CList (List.reverse $ p : ps) (ds ++ List.reverse (c : cs)) cyclic :: Eq a => Int -> [ a ] -> Maybe [ a ] cyclic n xs = let cyc = List.take n xs l = List.length xs xss = xs ++ List.take (n * (l `div` n) - l) xs in if xss == Monad.join (List.replicate (l `div` n) cyc) then Just cyc else Nothing factor :: Eq a => CList a -> CList a factor xs = let l = List.length $ cycl xs in case Monad.msum $ flip cyclic (cycl xs) <$> [1..l-1] of Nothing -> xs Just cyc -> xs { cycl = cyc } minimise :: Eq a => CList a -> CList a minimise = factor . rewind null :: CList a -> Bool null xs = List.null (prfx xs) && List.null (cycl xs) repeat :: a -> CList a repeat x = CList [] [x] join :: CList (CList a) -> CList a join = cfold append cnil crec where crec x ih = let res = x `append` ih cnil in if isFinite res && not (null res) then unsafeCycle $ prfx res else res observe :: CList a -> View a observe xs = case (prfx xs, cycl xs) of (y : ys, zs) -> Cons y $ xs { prfx = ys } ([], z : zs) -> Cons z $ xs { prfx = zs } ([], [] ) -> CNil splitAt :: Int -> CList a -> Maybe ([ a ], CList a) splitAt 0 xs = Just ([], xs) splitAt n xs | 0 < n = case observe xs of CNil -> Nothing Cons y ys -> (uncurry $ (,) . (y :)) <$> splitAt (n - 1) ys splitAt n xs | otherwise = Nothing unfoldCycleBy :: Int -> [ a ] -> CList a unfoldCycleBy n xs = let l = List.length xs ps = Monad.join $ List.replicate (n `div` l) xs (ys, zs) = List.splitAt (n `mod` l) xs in CList { prfx = ps ++ ys, cycl = zs ++ ys } take :: Int -> CList a -> Maybe [ a ] take n = (fst <$>) . splitAt n drop :: Int -> CList a -> Maybe (CList a) drop n = (snd <$>) . splitAt n zipWith :: (a -> b -> c) -> CList a -> CList b -> CList c zipWith f xs ys = go (prfx xs) (prfx ys) (cycl xs) (cycl ys) where go [] [] [] _ = cnil go [] [] _ [] = cnil go [] [] ss ts = let m = List.length ss n = List.length ts l = lcm m n ms = Monad.join $ List.replicate (l `div` m) ss ns = Monad.join $ List.replicate (l `div` n) ts in unsafeCycle $ List.zipWith f ms ns go ps [] ss ts = let ts' = unfoldCycleBy (List.length ps) ts pqs = fromList $ List.zipWith f ps (prfx ts') in fromList (prfx pqs) `append` go [] [] ss (cycl ts') go [] qs ss ts = let ss' = unfoldCycleBy (List.length qs) ss pqs = fromList $ List.zipWith f (prfx ss') qs in fromList (prfx pqs) `append` go [] [] (cycl ss') ts go (p : ps) (q : qs) ss ts = cons (f p q) $ go ps qs ss ts instance Functor CList where fmap f xs = CList { prfx = fmap f $ prfx xs , cycl = fmap f $ cycl xs } instance Functor View where fmap _ CNil = CNil fmap f (Cons x xs) = Cons (f x) $ fmap f xs cnil :: CList a cnil = CList [] [] cons :: a -> CList a -> CList a cons x xs = xs { prfx = x : prfx xs } singleton :: a -> CList a singleton x = cons x cnil fromList :: [ a ] -> CList a fromList xs = CList { prfx = xs, cycl = [] } cycle :: a -> [a] -> CList a cycle x xs = CList { prfx = [], cycl = x : xs } unsafeCycle :: [ a ] -> CList a unsafeCycle xs@(_ : _) = CList [] xs isFinite :: CList a -> Bool isFinite = List.null . cycl isCyclic :: CList a -> Bool isCyclic = not . isFinite getCycle :: CList a -> [ a ] getCycle = cycl getPrefix :: CList a -> [ a ] getPrefix = prfx getSupport :: CList a -> [ a ] getSupport xs = prfx xs ++ cycl xs cfold :: (a -> b -> b) -> b -> (a -> (b -> b) -> b) -> CList a -> b cfold c n r xs = foldr c (aux n $ cycl xs) $ prfx xs where aux p [] = p aux p (y : ys) = r y (\ b -> foldr c b ys) cfold' :: (a -> b -> b) -> b -> CList a -> b cfold' c n = cfold c n r where r a ih = c a $ ih $ r a ih cfoldFinite :: (a -> b -> b) -> b -> CList a -> Maybe b cfoldFinite c n xs | isFinite xs = Just $ foldr c n $ prfx xs cfoldFinite c n xs | otherwise = Nothing append :: CList a -> CList a -> CList a append xs ys | isFinite xs = ys { prfx = prfx xs ++ prfx ys } append xs ys | otherwise = xs length :: Num b => CList a -> Maybe b length = cfoldFinite (const (+1)) 0 reverse :: CList a -> Maybe (CList a) reverse = cfoldFinite (flip append . singleton) cnil toList :: CList a -> Maybe [ a ] toList xs | isFinite xs = Just $ prfx xs toList xs | otherwise = Nothing head :: CList a -> Maybe a head = cfold (const . Just) Nothing (const . Just) and :: CList Bool -> Bool and = cfold (&&) True (const $ const True) all :: (a -> Bool) -> CList a -> Bool all p = and . fmap p or :: CList Bool -> Bool or = cfold (||) False (const $ const False) any :: (a -> Bool) -> CList a -> Bool any p = or . fmap p intersperse :: a -> CList a -> CList a intersperse x xs = CList { prfx = List.intersperse x $ prfx xs , cycl = List.intersperse x $ cycl xs } unzip :: CList (a, b) -> (CList a, CList b) unzip xs = let (ps, qs) = List.unzip $ prfx xs (ss, ts) = List.unzip $ cycl xs in (CList ps ss, CList qs ts) instance Show a => Show (CList a) where show = cfold (\ a -> (++) (show a ++ " : ")) "[]" (\ a ih -> "rec X. " ++ show a ++ " : " ++ ih "X") instance Show a => Show (View a) where show CNil = [] show (Cons x xs) = show x ++ " : " ++ show xs instance Eq a => Eq (CList a) where xs == ys = and $ zipWith (==) xs ys instance Eq a => Eq (View a) where CNil == CNil = True Cons x xs == Cons y ys = x == y && xs == ys _ == _ = False instance Monad CList where return = singleton m >>= f = join $ fmap f m toStream :: CList a -> [ a ] toStream = cfold' (:) []
gallais/potpourri
haskell/cyclic/CyclicListFlat.hs
gpl-3.0
6,365
0
15
1,972
3,389
1,711
1,678
171
6