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
-- Problem 7 -- (0.94 secs, 458,377,840 bytes) primes = 2 : filter (null . tail . primeFactors) [3,5..] primeFactors n = factor n primes where factor n (p:ps) | p*p > n = [n] | n `mod` p == 0 = p : factor (n `div` p) (p:ps) | otherwise = factor n ps e007 = primes !! 10000 -- Sources -- Primes generator, prime factorization algorithm -- https://wiki.haskell.org/Euler_problems/1_to_10
synndicate/euler
solutions/e007.hs
gpl-3.0
447
0
11
131
153
81
72
7
1
{-# LANGUAGE Rank2Types, FlexibleContexts #-} -- 3. Continue the previous exercise with Reader Bool and Maybe. -- that is Define at least two different natural transformations between Reader Bool and the Maybe functor. -- newtype Reader e a = Reader {runReader :: (e -> a) } instance Functor (Reader e) where fmap f (Reader g) = Reader (\x -> f (g x)) -- First natural transformation ==> obvious reader_to_maybe :: Reader Bool a -> Maybe a reader_to_maybe m = Just $ runReader m True -- Second natural transformation ==> dumb reader_to_maybe' :: Reader Bool a -> Maybe a reader_to_maybe' m = Nothing reader_func :: Bool -> Int reader_func False = 0 reader_func True = 1 reader_func' :: Bool -> Int reader_func' False = 1 reader_func' True = 0 test_func :: Num a => a -> (a, a) test_func x = (x, x + 1) type NatTran f f' a = (Functor f, Functor f') => f a -> f' a to_assert :: (Functor f, Functor f', Eq (f' b)) => (a -> b) -> NatTran f f' a -> NatTran f f' b -> f a -> Bool to_assert g h h' f = (fmap g . h) f == (h' . fmap g) f success = (all (to_assert test_func reader_to_maybe reader_to_maybe) [Reader reader_func, Reader reader_func']) && (all (to_assert test_func reader_to_maybe' reader_to_maybe') [Reader reader_func, Reader reader_func']) main :: IO () main = do if success then putStrLn "Success!" else putStrLn "Failure."
sujeet4github/MyLangUtils
CategoryTheory_BartoszMilewsky/PI_10_Natural_Transformations/Ex_3.hs
gpl-3.0
1,375
0
11
283
479
249
230
24
2
module HidingClass where import ClassA hiding (A) instance A Int where id2 = id
Helium4Haskell/helium
test/classesQualified/HidingClass.hs
gpl-3.0
84
0
5
18
26
16
10
4
0
{-# LANGUAGE CPP, ScopedTypeVariables #-} -- -- Copyright (C) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library 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 -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -- USA -- module System.Plugins.Utils ( Arg, hWrite, mkUnique, hMkUnique, mkUniqueIn, hMkUniqueIn, findFile, mkTemp, mkTempIn, {- internal -} replaceSuffix, outFilePath, dropSuffix, mkModid, changeFileExt, joinFileExt, splitFileExt, isSublistOf, -- :: Eq a => [a] -> [a] -> Bool dirname, basename, (</>), (<.>), (<+>), (<>), newer, encode, decode, EncodedString, panic ) where #include "../../../config.h" import System.Plugins.Env ( isLoaded ) import System.Plugins.Consts ( objSuf, hiSuf, tmpDir ) -- import qualified System.MkTemp ( mkstemps ) import Control.Exception (IOException, catch) import Data.Char import Data.List import Prelude hiding (catch) import System.IO import System.Environment ( getEnv ) import System.Directory ( doesFileExist, getModificationTime, removeFile ) -- --------------------------------------------------------------------- -- some misc types we use type Arg = String -- --------------------------------------------------------------------- -- | useful -- panic s = ioError ( userError s ) -- --------------------------------------------------------------------- -- | writeFile for Handles -- hWrite :: Handle -> String -> IO () hWrite hdl src = hPutStr hdl src >> hClose hdl >> return () -- --------------------------------------------------------------------- -- | mkstemps. -- -- We use the Haskell version now... it is faster than calling into -- mkstemps(3). -- -- mkstemps :: String -> Int -> IO (String,Handle) -- mkstemps path slen = do -- m_v <- System.MkTemp.mkstemps path slen -- case m_v of Nothing -> error "mkstemps : couldn't create temp file" -- Just v' -> return v' {- mkstemps path slen = do withCString path $ \ ptr -> do let c_slen = fromIntegral $ slen+1 fd <- throwErrnoIfMinus1 "mkstemps" $ c_mkstemps ptr c_slen name <- peekCString ptr hdl <- fdToHandle fd return (name, hdl) foreign import ccall unsafe "mkstemps" c_mkstemps :: CString -> CInt -> IO Fd -} -- --------------------------------------------------------------------- -- | create a new temp file, returning name and handle. -- bit like the mktemp shell utility -- mkTemp :: IO (String,Handle) mkTemp = do tmpd <- catch (getEnv "TMPDIR") (\ (_ :: IOException) -> return tmpDir) mkTempIn tmpd mkTempIn :: String -> IO (String, Handle) mkTempIn tmpd = do -- XXX (tmpf,hdl) <- mkstemps (tmpd++"/MXXXXXXXXX.hs") 3 (tmpf, hdl) <- openTempFile tmpd "MXXXXX.hs" let modname = mkModid $ dropSuffix tmpf if and $ map (\c -> isAlphaNum c && c /= '_') modname then return (tmpf,hdl) else panic $ "Illegal characters in temp file: `"++tmpf++"'" -- --------------------------------------------------------------------- -- | Get a new temp file, unique from those in /tmp, and from those -- modules already loaded. Very nice for merge/eval uses. -- -- Will run for a long time if we can't create a temp file, luckily -- mkstemps gives us a pretty big search space -- mkUnique :: IO FilePath mkUnique = do (t,h) <- hMkUnique hClose h >> return t hMkUnique :: IO (FilePath,Handle) hMkUnique = do (t,h) <- mkTemp alreadyLoaded <- isLoaded t -- not unique! if alreadyLoaded then hClose h >> removeFile t >> hMkUnique else return (t,h) mkUniqueIn :: FilePath -> IO FilePath mkUniqueIn dir = do (t,h) <- hMkUniqueIn dir hClose h >> return t hMkUniqueIn :: FilePath -> IO (FilePath,Handle) hMkUniqueIn dir = do (t,h) <- mkTempIn dir alreadyLoaded <- isLoaded t -- not unique! if alreadyLoaded then hClose h >> removeFile t >> hMkUniqueIn dir else return (t,h) findFile :: [String] -> FilePath -> IO (Maybe FilePath) findFile [] _ = return Nothing findFile (ext:exts) file = do let l = changeFileExt file ext b <- doesFileExist l if b then return $ Just l else findFile exts file -- --------------------------------------------------------------------- -- some filename manipulation stuff -- -- | </>, <.> : join two path components -- infixr 6 </> infixr 6 <.> (</>), (<.>), (<+>), (<>) :: FilePath -> FilePath -> FilePath [] </> b = b a </> b = a ++ "/" ++ b [] <.> b = b a <.> b = a ++ "." ++ b [] <+> b = b a <+> b = a ++ " " ++ b [] <> b = b a <> b = a ++ b -- -- | dirname : return the directory portion of a file path -- if null, return "." -- dirname :: FilePath -> FilePath dirname p = let x = findIndices (== '\\') p y = findIndices (== '/') p in if not $ null x then if not $ null y then if (maximum x) > (maximum y) then dirname' '\\' p else dirname' '/' p else dirname' '\\' p else dirname' '/' p where dirname' chara pa = case reverse $ dropWhile (/= chara) $ reverse pa of [] -> "." pa' -> pa' -- -- | basename : return the filename portion of a path -- basename :: FilePath -> FilePath basename p = let x = findIndices (== '\\') p y = findIndices (== '/') p in if not $ null x then if not $ null y then if (maximum x) > (maximum y) then basename' '\\' p else basename' '/' p else basename' '\\' p else basename' '/' p where basename' chara pa = reverse $ takeWhile (/= chara) $ reverse pa -- -- drop suffix -- dropSuffix :: FilePath -> FilePath dropSuffix f = reverse . tail . dropWhile (/= '.') $ reverse f -- -- | work out the mod name from a filepath mkModid :: String -> String mkModid = (takeWhile (/= '.')) . reverse . (takeWhile (\x -> ('/'/= x) && ('\\' /= x))) . reverse ----------------------------------------------------------- -- Code from Cabal ---------------------------------------- -- | Changes the extension of a file path. changeFileExt :: FilePath -- ^ The path information to modify. -> String -- ^ The new extension (without a leading period). -- Specify an empty string to remove an existing -- extension from path. -> FilePath -- ^ A string containing the modified path information. changeFileExt fpath ext = joinFileExt name ext where (name,_) = splitFileExt fpath -- | The 'joinFileExt' function is the opposite of 'splitFileExt'. -- It joins a file name and an extension to form a complete file path. -- -- The general rule is: -- -- > filename `joinFileExt` ext == path -- > where -- > (filename,ext) = splitFileExt path joinFileExt :: String -> String -> FilePath joinFileExt fpath "" = fpath joinFileExt fpath ext = fpath ++ '.':ext -- | Split the path into file name and extension. If the file doesn\'t have extension, -- the function will return empty string. The extension doesn\'t include a leading period. -- -- Examples: -- -- > splitFileExt "foo.ext" == ("foo", "ext") -- > splitFileExt "foo" == ("foo", "") -- > splitFileExt "." == (".", "") -- > splitFileExt ".." == ("..", "") -- > splitFileExt "foo.bar."== ("foo.bar.", "") splitFileExt :: FilePath -> (String, String) splitFileExt p = case break (== '.') fname of (suf@(_:_),_:pre) -> (reverse (pre++fpath), reverse suf) _ -> (p, []) where (fname,fpath) = break isPathSeparator (reverse p) -- | Checks whether the character is a valid path separator for the host -- platform. The valid character is a 'pathSeparator' but since the Windows -- operating system also accepts a slash (\"\/\") since DOS 2, the function -- checks for it on this platform, too. isPathSeparator :: Char -> Bool isPathSeparator ch = #if defined(CYGWIN) || defined(__MINGW32__) ch == '/' || ch == '\\' #else ch == '/' #endif -- Code from Cabal end ------------------------------------ ----------------------------------------------------------- -- | return the object file, given the .conf file -- i.e. /home/dons/foo.rc -> /home/dons/foo.o -- -- we depend on the suffix we are given having a lead '.' -- replaceSuffix :: FilePath -> String -> FilePath replaceSuffix [] _ = [] -- ? replaceSuffix f suf = case reverse $ dropWhile (/= '.') $ reverse f of [] -> f ++ suf -- no '.' in file name f' -> f' ++ tail suf -- -- Normally we create the .hi and .o files next to the .hs files. -- For some uses this is annoying (i.e. true EDSL users don't actually -- want to know that their code is compiled at all), and for hmake-like -- applications. -- -- This code checks if "-o foo" or "-odir foodir" are supplied as args -- to make(), and if so returns a modified file path, otherwise it -- uses the source file to determing the path to where the object and -- .hi file will be put. -- outFilePath :: FilePath -> [Arg] -> (FilePath,FilePath) outFilePath src args = let objs = find_o args -- user sets explicit object path paths = find_p args -- user sets a directory to put stuff in in case () of { _ | not (null objs) -> let obj = last objs in (obj, mk_hi obj) | not (null paths) -> let obj = last paths </> mk_o (basename src) in (obj, mk_hi obj) | otherwise -> (mk_o src, mk_hi src) } where outpath = "-o" outdir = "-odir" mk_hi s = replaceSuffix s hiSuf mk_o s = replaceSuffix s objSuf find_o [] = [] find_o (f:f':fs) | f == outpath = [f'] | otherwise = find_o $! f':fs find_o _ = [] find_p [] = [] find_p (f:f':fs) | f == outdir = [f'] | otherwise = find_p $! f':fs find_p _ = [] ------------------------------------------------------------------------ -- -- | is file1 newer than file2? -- -- needs some fixing to work with 6.0.x series. (is this true?) -- -- fileExist still seems to throw exceptions on some platforms: ia64 in -- particular. -- -- invarient : we already assume the first file, 'a', exists -- newer :: FilePath -> FilePath -> IO Bool newer a b = do a_t <- getModificationTime a b_exists <- doesFileExist b if not b_exists then return True -- needs compiling else do b_t <- getModificationTime b return ( a_t > b_t ) -- maybe need recompiling ------------------------------------------------------------------------ -- -- | return the Z-Encoding of the string. -- -- Stolen from GHC. Use -package ghc as soon as possible -- type EncodedString = String encode :: String -> EncodedString encode [] = [] encode (c:cs) = encode_ch c ++ encode cs unencodedChar :: Char -> Bool -- True for chars that don't need encoding unencodedChar 'Z' = False unencodedChar 'z' = False unencodedChar c = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' -- -- Decode is used for user printing. -- decode :: EncodedString -> String decode [] = [] decode ('Z' : d : rest) | isDigit d = decode_tuple d rest | otherwise = decode_upper d : decode rest decode ('z' : d : rest) | isDigit d = decode_num_esc d rest | otherwise = decode_lower d : decode rest decode (c : rest) = c : decode rest decode_upper, decode_lower :: Char -> Char decode_upper 'L' = '(' decode_upper 'R' = ')' decode_upper 'M' = '[' decode_upper 'N' = ']' decode_upper 'C' = ':' decode_upper 'Z' = 'Z' decode_upper ch = error $ "decode_upper can't handle this char `"++[ch]++"'" decode_lower 'z' = 'z' decode_lower 'a' = '&' decode_lower 'b' = '|' decode_lower 'c' = '^' decode_lower 'd' = '$' decode_lower 'e' = '=' decode_lower 'g' = '>' decode_lower 'h' = '#' decode_lower 'i' = '.' decode_lower 'l' = '<' decode_lower 'm' = '-' decode_lower 'n' = '!' decode_lower 'p' = '+' decode_lower 'q' = '\'' decode_lower 'r' = '\\' decode_lower 's' = '/' decode_lower 't' = '*' decode_lower 'u' = '_' decode_lower 'v' = '%' decode_lower ch = error $ "decode_lower can't handle this char `"++[ch]++"'" -- Characters not having a specific code are coded as z224U decode_num_esc :: Char -> [Char] -> String decode_num_esc d cs = go (digitToInt d) cs where go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest go n ('U' : rest) = chr n : decode rest go _ other = error $ "decode_num_esc can't handle this: \""++other++"\"" encode_ch :: Char -> EncodedString encode_ch c | unencodedChar c = [c] -- Common case first -- Constructors encode_ch '(' = "ZL" -- Needed for things like (,), and (->) encode_ch ')' = "ZR" -- For symmetry with ( encode_ch '[' = "ZM" encode_ch ']' = "ZN" encode_ch ':' = "ZC" encode_ch 'Z' = "ZZ" -- Variables encode_ch 'z' = "zz" encode_ch '&' = "za" encode_ch '|' = "zb" encode_ch '^' = "zc" encode_ch '$' = "zd" encode_ch '=' = "ze" encode_ch '>' = "zg" encode_ch '#' = "zh" encode_ch '.' = "zi" encode_ch '<' = "zl" encode_ch '-' = "zm" encode_ch '!' = "zn" encode_ch '+' = "zp" encode_ch '\'' = "zq" encode_ch '\\' = "zr" encode_ch '/' = "zs" encode_ch '*' = "zt" encode_ch '_' = "zu" encode_ch '%' = "zv" encode_ch c = 'z' : shows (ord c) "U" decode_tuple :: Char -> EncodedString -> String decode_tuple d cs = go (digitToInt d) cs where go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest go 0 ['T'] = "()" go n ['T'] = '(' : replicate (n-1) ',' ++ ")" go 1 ['H'] = "(# #)" go n ['H'] = '(' : '#' : replicate (n-1) ',' ++ "#)" go _ other = error $ "decode_tuple \'"++other++"'" -- --------------------------------------------------------------------- -- -- 'isSublistOf' takes two arguments and returns 'True' iff the first -- list is a sublist of the second list. This means that the first list -- is wholly contained within the second list. Both lists must be -- finite. isSublistOf :: Eq a => [a] -> [a] -> Bool isSublistOf [] _ = True isSublistOf _ [] = False isSublistOf x y@(_:ys) | isPrefixOf x y = True | otherwise = isSublistOf x ys
sheganinans/plugins
src/System/Plugins/Utils.hs
lgpl-2.1
15,334
0
18
4,042
3,539
1,888
1,651
261
6
--main = do putStrLn $ show $ p55 merge [] = 0 merge (x:xs) = x + (merge (map (\ a -> a*10) xs)) makeList 0 = [] makeList a = (makeList (div a 10)) ++ [(mod a 10)] isPalindrome a = a == merge (makeList a) reverseAdd a = a + (merge (makeList a)) worker f v tr fr |( tr == 50) = True |( fr v') = False | otherwise = worker f v' (tr + 1) fr where v' = f v isLychrel a = worker reverseAdd a 0 isPalindrome --p55 = length $ filter isLychrel [ 100 .. 999] --p55 = filter isLychrel [ 100 .. 999] p55 = length $ filter isLychrel [ 5 .. 9999]
nmarshall23/Programming-Challenges
project-euler/055/55.hs
unlicense
553
0
12
139
265
134
131
13
1
module Akarui.FOL.BinT where import Akarui.ShowTxt -- | Supported binary connectives (in order of precedence). data BinT = -- | Conjunction. Returns true only if both sides are true. And -- | Disjunction. Returns true if at least one operand is true. | Or -- | Implication is... messed up. It returns true except if the -- left operand is true and the right one is false, e.g. True implies False -- is the only situation where implication returns false. | Implies -- | Exclusive disjunction. Returns true if one and only one operand is true. | Xor -- | Equivalence. Returns true is both operand have the same value, i.e. both -- true or both are false. | Iff deriving (Eq, Ord, Show) instance ShowTxt BinT where showTxt And = "And" showTxt Or = "Or" showTxt Implies = "Implies" showTxt Xor = "Xor" showTxt Iff = "Iff"
PhDP/Manticore
Akarui/FOL/BinT.hs
apache-2.0
861
0
6
190
103
61
42
15
0
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} ------------------------------------------------------------------------------ -- | This module is where all the routes and handlers are defined for your -- site. The 'app' function is the initializer that combines everything -- together and is exported by this module. module Site ( app ) where ------------------------------------------------------------------------------ import Control.Applicative import Control.Lens ((^#)) import Control.Concurrent (withMVar) import Control.Monad.Trans (liftIO, lift) import Control.Monad.Trans.Either import Control.Error.Safe (tryJust) import Lens.Family ((&), (.~)) import Data.ByteString as B import qualified Data.Text as T import qualified Data.Text.Read as T import Data.Monoid ------------------------------------------------------------------------------ import Database.SQLite.Simple as S import Snap.Core import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Auth.Backends.SqliteSimple import Snap.Snaplet.Heist import Snap.Snaplet.Session.Backends.CookieSession import Snap.Snaplet.SqliteSimple import Snap.Util.FileServe import Heist import qualified Heist.Interpreted as I ------------------------------------------------------------------------------ import Community import Application import Stock import qualified Db import Util import Login ------------------------------------------------------------------------------ -- | Handle posts handlePost :: H () handlePost = do -- infoLog ["handler" <=> "postHandler"] (Just c) <- getParam "cat" (Just k) <- getParam "key" --cRender $ B.append (B.intercalate "/" ["posts", c, k]) ".md" cRender $ (B.intercalate "/" ["posts", c,k]) ------------------------------------------------------------------------------ -- | The application's routes. routes :: [(B.ByteString, Handler App App ())] routes = [ ("/about", cRender "about") , ("/install", cRender "install") , ("/posts/", cRender "post") , ("/posts/:cat", cRender "post") , ("/posts/:cat/:key", handlePost) , ("/new_user", handleNewUser) , ("/login", handleLoginSubmit) , ("/logout", handleLogout) , ("/community", handleCommunity) , ("", serveDirectory "static") ] ------------------------------------------------------------------------------ -- | The application initializer. app :: SnapletInit App App app = makeSnaplet "app" "A snaplet example application." Nothing initProcess initProcess :: Initializer App App App initProcess = do h <- nestSnaplet "" heist $ heistInit "templates" addRoutes routes addConfig h (mempty & scCompiledSplices .~ allCommentSplices) s <- nestSnaplet "sess" sess $ initCookieSessionManager "site_key.txt" "sess" (Just 3600) d <- nestSnaplet "db" db sqliteInit a <- nestSnaplet "auth" auth $ initSqliteAuth sess d -- Grab the DB connection pool from the sqlite snaplet and call -- into the Model to create all the DB tables if necessary. let conn = sqliteConn $ d ^# snapletValue liftIO $ withMVar conn $ Db.createTables addAuthSplices h auth wrapSite (\site -> site <|> cRender "404") return $ App h s d a
santolucito/Peers
src/Site.hs
apache-2.0
3,530
0
11
813
655
377
278
63
1
{- Copyright 2015 Rafał Nowak Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE OverloadedStrings#-} module RaytracaH.Math where import Test.QuickCheck (Gen, Arbitrary(..), choose) import Control.Applicative import Data.Aeson import Data.Vec type Vector2D = Packed (Vec2 Float) type Vector3D = Packed (Vec3 Float) deg2rad :: Float -> Float deg2rad deg = deg * pi / 180.0 rad2deg :: Float -> Float rad2deg rad = 180.0 * rad / pi multvs :: Vector3D -> Float -> Vector3D multvs v scalar = v * Vec3F scalar scalar scalar comparisonEpsilon :: Fractional a => a comparisonEpsilon = 1e-5 equalsWithEpsilon :: Float -> Float -> Bool equalsWithEpsilon = equalsCustomEpsilon comparisonEpsilon equalsCustomEpsilon :: Float -> Float -> Float -> Bool equalsCustomEpsilon epsilon a b = abs (a - b) < epsilon clampedToPositive :: Float -> Float clampedToPositive = max 0.0 limitedToOne :: Float -> Float limitedToOne = min 1.0 reflect :: Vector3D -> Vector3D -> Vector3D reflect i n = i - multvs n (2 * dot i n) instance ToJSON Vector3D where toJSON (Vec3F x y z) = object [ "x" .= x , "y" .= y , "z" .= z] instance FromJSON Vector3D where parseJSON (Object o) = Vec3F <$> o .: "x" <*> o .: "y" <*> o .: "z" parseJSON _ = empty -- TODO: remove this new type and use type synonim instances and flexible instances as in Aeson typeclasses newtype AnyVector3D = AnyVector3D { v3d :: Vector3D } deriving (Eq, Show) instance Arbitrary AnyVector3D where arbitrary = vectorWithTermsInRange (-100.0) 100.0 vectorWithTermsInRange :: Float -> Float -> Gen AnyVector3D vectorWithTermsInRange a b = AnyVector3D <$> v where v = Vec3F <$> choose (a, b) <*> choose (a, b) <*> choose (a, b)
rafalnowak/RaytracaH
src/RaytracaH/Math.hs
apache-2.0
2,336
0
11
479
546
292
254
46
1
{-# LANGUAGE RecordWildCards #-} ----------------------------------------------------------------------------- -- | -- Module : HEP.Parser.LHE.Formatter -- Copyright : (c) 2010-2013 Ian-Woo Kim -- -- License : GPL-3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- -- Formatting back to LHE format. Currently this uses Text.Printf and String, so it's slow. -- Later, when text-format library becomes mature, I will switch to Data.Text. -- ----------------------------------------------------------------------------- module HEP.Parser.LHE.Formatter ( printPtlInfo , formatLHEvent , formatEventInfo -- , formatEventInfoOld , formatParticleInfo -- , formatParticleInfoOld ) where import Control.Applicative import Data.List -- import Foreign.C -- import Foreign.Marshal.Array -- import System.IO.Unsafe import Text.Printf -- import HEP.Util.Formatter.Fortran -- import HEP.Parser.LHE.Type -- import HEP.Parser.LHE.Formatter.Internal px :: PtlInfo -> Double px pinfo = case pup pinfo of (x,_,_,_,_) -> x py :: PtlInfo -> Double py pinfo = case pup pinfo of (_,y,_,_,_) -> y pz :: PtlInfo -> Double pz pinfo = case pup pinfo of (_,_,z,_,_) -> z p0 :: PtlInfo -> Double p0 pinfo = case pup pinfo of (_,_,_,t,_) -> t mass :: PtlInfo -> Double mass pinfo = case pup pinfo of (_,_,_,_,m) -> m printPtlInfo :: PtlInfo -> String printPtlInfo pinfo = printf " %5d %5d %5d %5d %5d %5d %1.10E %18.11e %18.11E %18.11E %18.11E %f %f" <$> idup <*> istup <*> fst.mothup <*> snd.mothup <*> fst.icolup <*> snd.icolup <*> px <*> py <*> pz <*> p0 <*> mass <*> vtimup <*> spinup $ pinfo formatLHEvent :: LHEvent -> String formatLHEvent (LHEvent einfo pinfos) = let estr = formatEventInfo einfo pstrs = map formatParticleInfo pinfos in intercalate "\n" (estr:pstrs) formatEventInfo :: EventInfo -> String formatEventInfo EvInfo {..} = fformats [ P (I 2) nup , P (I 4) idprup , P (E 15 7) xwgtup , P (E 15 7) scalup , P (E 15 7) aqedup , P (E 15 7) aqcdup ] -- | using old fortran formatParticleInfo :: PtlInfo -> String formatParticleInfo PtlInfo {..} = let fmt2 f (a,b) = [P f a,P f b] fmt5 f (a,b,c,d,e) = [P f a,P f b,P f c,P f d,P f e] in fformats $ [ P (I 9) idup , P (I 5) istup ] ++ fmt2 (I 5) mothup ++ fmt2 (I 5) icolup ++ fmt5 (E 19 11) pup ++ [ P (F 3 0) vtimup , P (F 4 0) spinup ] {- -- | using old fortran formatEventInfoOld :: EventInfo -> String formatEventInfoOld einfo = let cstr = c_formatEventInfo <$> fromIntegral.nup <*> fromIntegral.idprup <*> realToFrac.xwgtup <*> realToFrac.scalup <*> realToFrac.aqedup <*> realToFrac.aqcdup $ einfo in unsafePerformIO $ peekCString cstr -- | using old fortran formatParticleInfoOld :: PtlInfo -> String formatParticleInfoOld pinfo = let tuple2lst (a,b) = [a,b] tuple5lst (a,b,c,d,e) = [a,b,c,d,e] lstToCPtr f = unsafePerformIO . newArray . (map f) cstr = c_formatParticleInfo <$> fromIntegral.idup <*> fromIntegral.istup <*> lstToCPtr fromIntegral . tuple2lst . mothup <*> lstToCPtr fromIntegral . tuple2lst . icolup <*> lstToCPtr realToFrac . tuple5lst . pup <*> realToFrac . vtimup <*> realToFrac . spinup $ pinfo in unsafePerformIO $ peekCString cstr -}
wavewave/LHEParser
src/HEP/Parser/LHE/Formatter.hs
bsd-2-clause
3,780
0
19
1,132
805
437
368
55
1
module Database.SqlServer.Create.Queue ( Queue ) where import Database.SqlServer.Create.Identifier hiding (unwrap) import Database.SqlServer.Create.Procedure import Database.SqlServer.Create.Entity import Test.QuickCheck import Data.Word (Word16) import Text.PrettyPrint hiding (render) import Data.Maybe (isJust) -- TODO username support data ExecuteAs = Self | Owner -- Activation procedures can not have any parameters newtype ZeroParamProc = ZeroParamProc { unwrap :: Procedure } instance Arbitrary ZeroParamProc where arbitrary = do proc <- arbitrary :: Gen Procedure return $ ZeroParamProc (proc { parameters = [] }) data Activation = Activation { maxQueueReaders :: Word16 , executeAs :: ExecuteAs , procedure :: ZeroParamProc } data Queue = Queue { queueName :: RegularIdentifier , queueStatus :: Maybe Bool , retention :: Maybe Bool , activation :: Maybe Activation , poisonMessageHandling :: Maybe Bool } instance Arbitrary ExecuteAs where arbitrary = elements [Self, Owner] instance Arbitrary Queue where arbitrary = Queue <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary Activation where arbitrary = do r <- choose (0, 32767) x <- arbitrary y <- arbitrary return $ Activation r x y anySpecified :: Queue -> Bool anySpecified q = isJust (queueStatus q) || isJust (retention q) || isJust (activation q) || isJust (poisonMessageHandling q) renderStatus :: Bool -> Doc renderStatus True = text "STATUS = ON" renderStatus False = text "STATUS = OFF" renderRetention :: Bool -> Doc renderRetention True = text "RETENTION = ON" renderRetention False = text "RETENTION = OFF" renderPoisonMessageHandling :: Bool -> Doc renderPoisonMessageHandling True = text "POISON_MESSAGE_HANDLING(STATUS = ON)" renderPoisonMessageHandling False = text "POISON_MESSAGE_HANDLING(STATUS = OFF)" renderMaxQueueReaders :: Word16 -> Doc renderMaxQueueReaders t = text "MAX_QUEUE_READERS = " <> int (fromIntegral t) renderExecuteAs :: ExecuteAs -> Doc renderExecuteAs Self = text "EXECUTE AS SELF" renderExecuteAs Owner = text "EXECUTE AS OWNER" renderProc :: Activation -> Doc renderProc a = render (unwrap $ procedure a) renderProcedureName :: Procedure -> Doc renderProcedureName a = text "PROCEDURE_NAME =" <+> renderRegularIdentifier (procedureName a) renderActivation :: Activation -> Doc renderActivation a = text "ACTIVATION(" <+> hcat (punctuate comma $ filter (/= empty) [ renderMaxQueueReaders (maxQueueReaders a) , renderExecuteAs (executeAs a) , renderProcedureName (unwrap $ procedure a) ]) <+> text ")" instance Entity Queue where name = queueName render q = maybe empty renderProc (activation q) $+$ text "CREATE QUEUE" <+> renderRegularIdentifier (queueName q) <+> options $+$ text "GO\n" where options | not $ anySpecified q = empty | otherwise = text "WITH" <+> hcat (punctuate comma $ filter (/= empty) [ maybe empty renderStatus (queueStatus q) , maybe empty renderRetention (retention q) , maybe empty renderActivation (activation q) , maybe empty renderPoisonMessageHandling (poisonMessageHandling q)])
fffej/sql-server-gen
src/Database/SqlServer/Create/Queue.hs
bsd-2-clause
3,588
0
17
962
905
468
437
86
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QRegExpValidator_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QRegExpValidator_h where import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QRegExpValidator ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QRegExpValidator_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QRegExpValidator_unSetUserMethod" qtc_QRegExpValidator_unSetUserMethod :: Ptr (TQRegExpValidator a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QRegExpValidatorSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QRegExpValidator_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QRegExpValidator ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QRegExpValidator_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QRegExpValidatorSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QRegExpValidator_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QRegExpValidator ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QRegExpValidator_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QRegExpValidatorSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QRegExpValidator_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QRegExpValidator ()) (QRegExpValidator x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QRegExpValidator setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QRegExpValidator_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QRegExpValidator_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQRegExpValidator x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QRegExpValidator_setUserMethod" qtc_QRegExpValidator_setUserMethod :: Ptr (TQRegExpValidator a) -> CInt -> Ptr (Ptr (TQRegExpValidator x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QRegExpValidator :: (Ptr (TQRegExpValidator x0) -> IO ()) -> IO (FunPtr (Ptr (TQRegExpValidator x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QRegExpValidator_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QRegExpValidatorSc a) (QRegExpValidator x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QRegExpValidator setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QRegExpValidator_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QRegExpValidator_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQRegExpValidator x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QRegExpValidator ()) (QRegExpValidator x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QRegExpValidator setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QRegExpValidator_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QRegExpValidator_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQRegExpValidator x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QRegExpValidator_setUserMethodVariant" qtc_QRegExpValidator_setUserMethodVariant :: Ptr (TQRegExpValidator a) -> CInt -> Ptr (Ptr (TQRegExpValidator x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QRegExpValidator :: (Ptr (TQRegExpValidator x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQRegExpValidator x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QRegExpValidator_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QRegExpValidatorSc a) (QRegExpValidator x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QRegExpValidator setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QRegExpValidator_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QRegExpValidator_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQRegExpValidator x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QRegExpValidator ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QRegExpValidator_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QRegExpValidator_unSetHandler" qtc_QRegExpValidator_unSetHandler :: Ptr (TQRegExpValidator a) -> CWString -> IO (CBool) instance QunSetHandler (QRegExpValidatorSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QRegExpValidator_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QRegExpValidator ()) (QRegExpValidator x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QRegExpValidator1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QRegExpValidator1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QRegExpValidator_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQRegExpValidator x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qRegExpValidatorFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QRegExpValidator_setHandler1" qtc_QRegExpValidator_setHandler1 :: Ptr (TQRegExpValidator a) -> CWString -> Ptr (Ptr (TQRegExpValidator x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QRegExpValidator1 :: (Ptr (TQRegExpValidator x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQRegExpValidator x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QRegExpValidator1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QRegExpValidatorSc a) (QRegExpValidator x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QRegExpValidator1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QRegExpValidator1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QRegExpValidator_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQRegExpValidator x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qRegExpValidatorFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QRegExpValidator ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QRegExpValidator_event cobj_x0 cobj_x1 foreign import ccall "qtc_QRegExpValidator_event" qtc_QRegExpValidator_event :: Ptr (TQRegExpValidator a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QRegExpValidatorSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QRegExpValidator_event cobj_x0 cobj_x1 instance QsetHandler (QRegExpValidator ()) (QRegExpValidator x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QRegExpValidator2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QRegExpValidator2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QRegExpValidator_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQRegExpValidator x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qRegExpValidatorFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QRegExpValidator_setHandler2" qtc_QRegExpValidator_setHandler2 :: Ptr (TQRegExpValidator a) -> CWString -> Ptr (Ptr (TQRegExpValidator x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QRegExpValidator2 :: (Ptr (TQRegExpValidator x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQRegExpValidator x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QRegExpValidator2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QRegExpValidatorSc a) (QRegExpValidator x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QRegExpValidator2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QRegExpValidator2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QRegExpValidator_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQRegExpValidator x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qRegExpValidatorFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QRegExpValidator ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QRegExpValidator_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QRegExpValidator_eventFilter" qtc_QRegExpValidator_eventFilter :: Ptr (TQRegExpValidator a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QRegExpValidatorSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QRegExpValidator_eventFilter cobj_x0 cobj_x1 cobj_x2
uduki/hsQt
Qtc/Gui/QRegExpValidator_h.hs
bsd-2-clause
17,400
0
18
3,804
5,484
2,612
2,872
-1
-1
-- Exercise 4 of chapter 4 in "Real World Haskell" splitWith :: (a -> Bool) -> [a] -> [[a]] splitWith _ [] = [[]] splitWith p (x:xs)
ploverlake/practice_of_haskell
src/splitWith.hs
bsd-2-clause
134
0
8
28
63
34
29
-1
-1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE OverloadedStrings #-} module Quiz.Web.Prelude ( module Quiz.Web.Prelude.External ) where import Quiz.Web.Prelude.External import Control.Monad.Catch import Data.Text.Lazy.Encoding -- getPath :: Web [Text] -- getPath = pathInfo . wsRequest <$> ask -- renderPage :: Html -> Html -> ByteString -- renderPage = renderPage' Nothing -- -- renderPage' :: Maybe Text -> Html -> Html -> ByteString -- renderPage' title header body = renderHtml $ layoutHtml title header body -- -- layoutHtml :: Maybe Text -> Html -> Html -> Html -- layoutHtml maybeTitle header content = [shamlet| -- $doctype 5 -- <html> -- <head> -- $maybe title <- maybeTitle -- <title>Quick Quiz | #{title} -- $nothing -- <title>Quick Quiz -- <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,700" rel="stylesheet" type="text/css"> -- <link rel="stylesheet" type="text/css" href="/style.css"> -- <script type="text/x-mathjax-config"> -- MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}}); -- <script type="text/javascript" async src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML"> -- <body> -- <div id="page"> -- <h1>#{header} -- <div id="content">#{content} -- |] -- throwWebError :: ByteString -> Status -> Web a -- throwWebError msg status = throwError $ WebError msg [] status -- infixl 3 <|> -- onGet :: Web a -> Web a -- onGet = isMethod methodGet -- -- onPost :: Web a -> Web a -- onPost = isMethod methodPost -- -- onDelete :: Web a -> Web a -- onDelete = isMethod methodDelete -- -- isMethod :: Method -> Web a -> Web a -- isMethod methodMatch m = do -- method <- requestMethod . wsRequest <$> ask -- if method == methodMatch then -- m -- else -- throwError $ WebError "Invalid method." [] status400 -- getRequestBody :: Web ByteString -- getRequestBody = liftIO . lazyRequestBody . wsRequest =<< ask
michael-swan/quick-quiz
src/Quiz/Web/Prelude.hs
bsd-3-clause
2,132
0
5
522
87
76
11
6
0
{-# LANGUAGE PackageImports, OverloadedStrings #-} module Network.PeyoTLS.Codec.Alert (Alert(..), AlertLevel(..), AlertDesc(..)) where import Control.Applicative import "monads-tf" Control.Monad.Error.Class (Error(..)) import Data.Word (Word8) import qualified Data.ByteString as BS import qualified Codec.Bytable.BigEndian as B modNm :: String modNm = "Network.PeyoTLS.Codec.Alert" -- | RFC 5246 7.2. Alert Protocol -- -- @ -- struct { -- AlertLevel level; -- AlertDescription description; -- } Alert; -- @ data Alert = Alert AlertLevel AlertDesc String | ExternalAlert String | NotDetected String deriving Show instance B.Bytable Alert where encode (Alert al ad _) = B.encode al `BS.append` B.encode ad encode _ = error "Alert.encode" decode alad = let (al, ad) = BS.splitAt 1 alad in Alert <$> B.decode al <*> B.decode ad <*> return "" -- | RFC 5246 7.2. Alert Protocol -- -- @ -- enum { warning(1), fatal(2), (255) } AlertLevel; -- @ data AlertLevel = ALWarning | ALFtl | ALRaw Word8 deriving Show instance B.Bytable AlertLevel where encode ALWarning = "\x01" encode ALFtl = "\x02" encode (ALRaw w) = BS.pack [w] decode bs = case BS.unpack bs of [al] -> Right $ case al of 1 -> ALWarning; 2 -> ALFtl; _ -> ALRaw al _ -> Left $ modNm ++ ": AlertLevel.decode" -- | RFC 5246 7.2. Alert Protocol -- -- @ -- enum { -- close_notify(0), -- unexpected_message(10), -- bad_record_mac(20), -- decryption_failed_RESERVED(21), -- record_overflow(22), -- decompression_failure(30), -- handshake_failure(40), -- no_certificate_RESERVED(41), -- bad_certificate(42), -- unsupported_certificate(43), -- certificate_revoked(44), -- certificate_expired(45), -- certificate_unknown(46), -- illegal_parameter(47), -- unknown_ca(48), -- access_denied(49), -- decode_error(50), -- decrypt_error(51), -- export_restriction_RESERVED(60), -- protocol_version(70), -- insufficient_security(71), -- internal_error(80), -- user_canceled(90), -- no_renegotiation(100), -- unsupported_extension(110), -- (255) -- } AlertDescription; -- @ data AlertDesc = ADCloseNotify | ADUnexMsg | ADBadRecMac | ADRecOverflow | ADDecFail | ADHsFailure | ADUnsCert | ADCertEx | ADCertUnk | ADIllParam | ADUnkCa | ADDecodeErr | ADDecryptErr | ADProtoVer | ADInsSec | ADInternalErr | ADUnk | ADRaw Word8 deriving Show instance B.Bytable AlertDesc where encode ADCloseNotify = "\0" encode ADUnexMsg = "\10" encode ADBadRecMac = "\20" encode ADRecOverflow = "\22" encode ADDecFail = "\30" encode ADHsFailure = "\40" encode ADUnsCert = "\43" encode ADCertEx = "\45" encode ADCertUnk = "\46" encode ADIllParam = "\47" encode ADUnkCa = "\48" encode ADDecodeErr = "\50" encode ADDecryptErr = "\51" encode ADProtoVer = "\70" encode ADInsSec = "\71" encode ADInternalErr = "\80" encode ADUnk = error $ modNm ++ ": AlertDesc,encode" encode (ADRaw w) = BS.pack [w] decode bs = case BS.unpack bs of [ad] -> Right $ case ad of 0 -> ADCloseNotify 10 -> ADUnexMsg 20 -> ADBadRecMac 22 -> ADRecOverflow 30 -> ADDecFail 40 -> ADHsFailure 43 -> ADUnsCert 45 -> ADCertEx 46 -> ADCertUnk 47 -> ADIllParam 48 -> ADUnkCa 50 -> ADDecodeErr 51 -> ADDecryptErr 70 -> ADProtoVer 71 -> ADInsSec 80 -> ADInternalErr w -> ADRaw w _ -> Left $ modNm ++ ": AlertDesc.decode" instance Error Alert where strMsg = NotDetected
YoshikuniJujo/peyotls
peyotls-codec/src/Network/PeyoTLS/Codec/Alert.hs
bsd-3-clause
3,408
8
13
633
827
465
362
73
1
{-| Module : Types.Unique Description : Type family for testing type list uniqueness. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Types.Unique ( Unique ) where import Types.BooleanLogic import Types.Member -- | 'True if and only if the list contains no duplicate elements. type family Unique (ts :: [k]) :: Bool where Unique '[] = 'True Unique (x ': xs) = And (Not (Member x xs)) (Unique xs)
avieth/Relational
Types/Unique.hs
bsd-3-clause
764
0
10
148
105
63
42
14
0
module Main where import Language import PrettyPrint import Parser import TiState import Utils main :: IO () main = do --program <- getContents --(putStrLn . show) (clex 0 program) --(putStrLn . show) (parse program) --let coreProgram = parse program --let states@(stack, dump, (_, _, heap), globals, stats) = step $ step $ step $ step $ compile coreProgram --(putStrLn . show) $ (stack, heap, globals, stats) getContents >>= (putStrLn . runProg)
caasi/spj-book-student-1992
app/Main.hs
bsd-3-clause
465
0
9
89
54
34
20
9
1
{-# LANGUAGE CPP #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE FlexibleContexts #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif {- | Module : Control.Concurrent.SampleVar.Lifted Copyright : Liyang HU, Bas van Dijk License : BSD-style Maintainer : Bas van Dijk <[email protected]> Stability : experimental This is a wrapped version of "Control.Concurrent.SampleVar" with types generalised from 'IO' to all monads in 'MonadBase'. -} module Control.Concurrent.SampleVar.Lifted ( SampleVar , newEmptySampleVar , newSampleVar , emptySampleVar , readSampleVar , writeSampleVar , isEmptySampleVar ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- -- from base: import Control.Concurrent.SampleVar ( SampleVar ) import qualified Control.Concurrent.SampleVar as SampleVar import Data.Bool ( Bool ) import System.IO ( IO ) import Prelude ( (.) ) -- from transformers-base: import Control.Monad.Base ( MonadBase, liftBase ) #include "inlinable.h" -------------------------------------------------------------------------------- -- * SampleVars -------------------------------------------------------------------------------- -- | Generalized version of 'SampleVar.newEmptySampleVar'. newEmptySampleVar :: MonadBase IO m => m (SampleVar a) newEmptySampleVar = liftBase SampleVar.newEmptySampleVar {-# INLINABLE newEmptySampleVar #-} -- | Generalized version of 'SampleVar.newSampleVar'. newSampleVar :: MonadBase IO m => a -> m (SampleVar a) newSampleVar = liftBase . SampleVar.newSampleVar {-# INLINABLE newSampleVar #-} -- | Generalized version of 'SampleVar.emptySampleVar'. emptySampleVar :: MonadBase IO m => SampleVar a -> m () emptySampleVar = liftBase . SampleVar.emptySampleVar {-# INLINABLE emptySampleVar #-} -- | Generalized version of 'SampleVar.readSampleVar'. readSampleVar :: MonadBase IO m => SampleVar a -> m a readSampleVar = liftBase . SampleVar.readSampleVar {-# INLINABLE readSampleVar #-} -- | Generalized version of 'SampleVar.writeSampleVar'. writeSampleVar :: MonadBase IO m => SampleVar a -> a -> m () writeSampleVar sv = liftBase . SampleVar.writeSampleVar sv {-# INLINABLE writeSampleVar #-} -- | Generalized version of 'SampleVar.isEmptySampleVar'. isEmptySampleVar :: MonadBase IO m => SampleVar a -> m Bool isEmptySampleVar = liftBase . SampleVar.isEmptySampleVar {-# INLINABLE isEmptySampleVar #-}
basvandijk/lifted-base
Control/Concurrent/SampleVar/Lifted.hs
bsd-3-clause
2,549
0
9
353
348
200
148
29
1
module Email where import Prelude import Data.Text import Network.Mail.Mime adminAddr, noreplyAddr :: Address adminAddr = Address (Just "Bannerstalker") "[email protected]" noreplyAddr = Address (Just "Bannerstalker") "[email protected]" mySendmail :: Mail -> IO () mySendmail message = do let Address mName email = mailFrom message flags = ["-tf", unpack email] ++ case mName of Just name -> ["-F", unpack name] _ -> [] renderSendMailCustom "/usr/sbin/sendmail" flags message
nejstastnejsistene/bannerstalker-yesod
src/Email.hs
bsd-3-clause
554
0
15
127
155
80
75
15
2
module Experiments.MonadT.ExceptWriterStateT where import Control.Monad.Except import Control.Monad.State.Strict import Control.Monad.Writer.Strict data Token = OpenParen | CloseParen | Letter Char deriving (Eq, Show) data AST = Group [AST] | Expression [Char] deriving (Eq, Show) type ParserState = State [Token] type ParserLog = WriterT [String] ParserState type ParserMonad a = ExceptT String ParserLog a type Parser = ParserMonad AST type ParserOutput = Either String AST charLex :: Char -> Token charLex c = case c of '(' -> OpenParen ')' -> CloseParen _ -> Letter c myLex :: String -> [Token] myLex text = fmap charLex text myParse :: Parser myParse = do tokens <- get case tokens of OpenParen:rest -> do put rest lift $ tell ["open paren"] myParse CloseParen:rest -> do put rest lift $ tell ["close paren"] return $ Expression [] (Letter c):rest -> do put rest parsed <- myParse case parsed of Expression chars -> return $ Expression (c : chars) Group _ -> throwError "shouldn'g get an AST here" [] -> throwError "shouldn't hit this" parse :: String -> (Either String AST, [String]) parse input = evalState (runWriterT $ runExceptT myParse) (myLex input)
rumblesan/haskell-experiments
src/Experiments/MonadT/ExceptWriterStateT.hs
bsd-3-clause
1,333
0
18
356
442
228
214
47
5
{- Binary serialization for .hie files. -} {-# LANGUAGE ScopedTypeVariables #-} module GHC.Iface.Ext.Binary ( readHieFile , readHieFileWithVersion , HieHeader , writeHieFile , HieName(..) , toHieName , HieFileResult(..) , hieMagic , hieNameOcc ) where import GHC.Settings ( maybeRead ) import Config ( cProjectVersion ) import GhcPrelude import Binary import GHC.Iface.Binary ( getDictFastString ) import FastMutInt import FastString ( FastString ) import Module ( Module ) import Name import NameCache import Outputable import PrelInfo import SrcLoc import UniqSupply ( takeUniqFromSupply ) import Unique import UniqFM import qualified Data.Array as A import Data.IORef import Data.ByteString ( ByteString ) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import Data.List ( mapAccumR ) import Data.Word ( Word8, Word32 ) import Control.Monad ( replicateM, when ) import System.Directory ( createDirectoryIfMissing ) import System.FilePath ( takeDirectory ) import GHC.Iface.Ext.Types -- | `Name`'s get converted into `HieName`'s before being written into @.hie@ -- files. See 'toHieName' and 'fromHieName' for logic on how to convert between -- these two types. data HieName = ExternalName !Module !OccName !SrcSpan | LocalName !OccName !SrcSpan | KnownKeyName !Unique deriving (Eq) instance Ord HieName where compare (ExternalName a b c) (ExternalName d e f) = compare (a,b,c) (d,e,f) compare (LocalName a b) (LocalName c d) = compare (a,b) (c,d) compare (KnownKeyName a) (KnownKeyName b) = nonDetCmpUnique a b -- Not actually non deterministic as it is a KnownKey compare ExternalName{} _ = LT compare LocalName{} ExternalName{} = GT compare LocalName{} _ = LT compare KnownKeyName{} _ = GT instance Outputable HieName where ppr (ExternalName m n sp) = text "ExternalName" <+> ppr m <+> ppr n <+> ppr sp ppr (LocalName n sp) = text "LocalName" <+> ppr n <+> ppr sp ppr (KnownKeyName u) = text "KnownKeyName" <+> ppr u hieNameOcc :: HieName -> OccName hieNameOcc (ExternalName _ occ _) = occ hieNameOcc (LocalName occ _) = occ hieNameOcc (KnownKeyName u) = case lookupKnownKeyName u of Just n -> nameOccName n Nothing -> pprPanic "hieNameOcc:unknown known-key unique" (ppr (unpkUnique u)) data HieSymbolTable = HieSymbolTable { hie_symtab_next :: !FastMutInt , hie_symtab_map :: !(IORef (UniqFM (Int, HieName))) } data HieDictionary = HieDictionary { hie_dict_next :: !FastMutInt -- The next index to use , hie_dict_map :: !(IORef (UniqFM (Int,FastString))) -- indexed by FastString } initBinMemSize :: Int initBinMemSize = 1024*1024 -- | The header for HIE files - Capital ASCII letters "HIE". hieMagic :: [Word8] hieMagic = [72,73,69] hieMagicLen :: Int hieMagicLen = length hieMagic ghcVersion :: ByteString ghcVersion = BSC.pack cProjectVersion putBinLine :: BinHandle -> ByteString -> IO () putBinLine bh xs = do mapM_ (putByte bh) $ BS.unpack xs putByte bh 10 -- newline char -- | Write a `HieFile` to the given `FilePath`, with a proper header and -- symbol tables for `Name`s and `FastString`s writeHieFile :: FilePath -> HieFile -> IO () writeHieFile hie_file_path hiefile = do bh0 <- openBinMem initBinMemSize -- Write the header: hieHeader followed by the -- hieVersion and the GHC version used to generate this file mapM_ (putByte bh0) hieMagic putBinLine bh0 $ BSC.pack $ show hieVersion putBinLine bh0 $ ghcVersion -- remember where the dictionary pointer will go dict_p_p <- tellBin bh0 put_ bh0 dict_p_p -- remember where the symbol table pointer will go symtab_p_p <- tellBin bh0 put_ bh0 symtab_p_p -- Make some initial state symtab_next <- newFastMutInt writeFastMutInt symtab_next 0 symtab_map <- newIORef emptyUFM let hie_symtab = HieSymbolTable { hie_symtab_next = symtab_next, hie_symtab_map = symtab_map } dict_next_ref <- newFastMutInt writeFastMutInt dict_next_ref 0 dict_map_ref <- newIORef emptyUFM let hie_dict = HieDictionary { hie_dict_next = dict_next_ref, hie_dict_map = dict_map_ref } -- put the main thing let bh = setUserData bh0 $ newWriteState (putName hie_symtab) (putName hie_symtab) (putFastString hie_dict) put_ bh hiefile -- write the symtab pointer at the front of the file symtab_p <- tellBin bh putAt bh symtab_p_p symtab_p seekBin bh symtab_p -- write the symbol table itself symtab_next' <- readFastMutInt symtab_next symtab_map' <- readIORef symtab_map putSymbolTable bh symtab_next' symtab_map' -- write the dictionary pointer at the front of the file dict_p <- tellBin bh putAt bh dict_p_p dict_p seekBin bh dict_p -- write the dictionary itself dict_next <- readFastMutInt dict_next_ref dict_map <- readIORef dict_map_ref putDictionary bh dict_next dict_map -- and send the result to the file createDirectoryIfMissing True (takeDirectory hie_file_path) writeBinMem bh hie_file_path return () data HieFileResult = HieFileResult { hie_file_result_version :: Integer , hie_file_result_ghc_version :: ByteString , hie_file_result :: HieFile } type HieHeader = (Integer, ByteString) -- | Read a `HieFile` from a `FilePath`. Can use -- an existing `NameCache`. Allows you to specify -- which versions of hieFile to attempt to read. -- `Left` case returns the failing header versions. readHieFileWithVersion :: (HieHeader -> Bool) -> NameCache -> FilePath -> IO (Either HieHeader (HieFileResult, NameCache)) readHieFileWithVersion readVersion nc file = do bh0 <- readBinMem file (hieVersion, ghcVersion) <- readHieFileHeader file bh0 if readVersion (hieVersion, ghcVersion) then do (hieFile, nc') <- readHieFileContents bh0 nc return $ Right (HieFileResult hieVersion ghcVersion hieFile, nc') else return $ Left (hieVersion, ghcVersion) -- | Read a `HieFile` from a `FilePath`. Can use -- an existing `NameCache`. readHieFile :: NameCache -> FilePath -> IO (HieFileResult, NameCache) readHieFile nc file = do bh0 <- readBinMem file (readHieVersion, ghcVersion) <- readHieFileHeader file bh0 -- Check if the versions match when (readHieVersion /= hieVersion) $ panic $ unwords ["readHieFile: hie file versions don't match for file:" , file , "Expected" , show hieVersion , "but got", show readHieVersion ] (hieFile, nc') <- readHieFileContents bh0 nc return $ (HieFileResult hieVersion ghcVersion hieFile, nc') readBinLine :: BinHandle -> IO ByteString readBinLine bh = BS.pack . reverse <$> loop [] where loop acc = do char <- get bh :: IO Word8 if char == 10 -- ASCII newline '\n' then return acc else loop (char : acc) readHieFileHeader :: FilePath -> BinHandle -> IO HieHeader readHieFileHeader file bh0 = do -- Read the header magic <- replicateM hieMagicLen (get bh0) version <- BSC.unpack <$> readBinLine bh0 case maybeRead version of Nothing -> panic $ unwords ["readHieFileHeader: hieVersion isn't an Integer:" , show version ] Just readHieVersion -> do ghcVersion <- readBinLine bh0 -- Check if the header is valid when (magic /= hieMagic) $ panic $ unwords ["readHieFileHeader: headers don't match for file:" , file , "Expected" , show hieMagic , "but got", show magic ] return (readHieVersion, ghcVersion) readHieFileContents :: BinHandle -> NameCache -> IO (HieFile, NameCache) readHieFileContents bh0 nc = do dict <- get_dictionary bh0 -- read the symbol table so we are capable of reading the actual data (bh1, nc') <- do let bh1 = setUserData bh0 $ newReadState (error "getSymtabName") (getDictFastString dict) (nc', symtab) <- get_symbol_table bh1 let bh1' = setUserData bh1 $ newReadState (getSymTabName symtab) (getDictFastString dict) return (bh1', nc') -- load the actual data hiefile <- get bh1 return (hiefile, nc') where get_dictionary bin_handle = do dict_p <- get bin_handle data_p <- tellBin bin_handle seekBin bin_handle dict_p dict <- getDictionary bin_handle seekBin bin_handle data_p return dict get_symbol_table bh1 = do symtab_p <- get bh1 data_p' <- tellBin bh1 seekBin bh1 symtab_p (nc', symtab) <- getSymbolTable bh1 nc seekBin bh1 data_p' return (nc', symtab) putFastString :: HieDictionary -> BinHandle -> FastString -> IO () putFastString HieDictionary { hie_dict_next = j_r, hie_dict_map = out_r} bh f = do out <- readIORef out_r let unique = getUnique f case lookupUFM out unique of Just (j, _) -> put_ bh (fromIntegral j :: Word32) Nothing -> do j <- readFastMutInt j_r put_ bh (fromIntegral j :: Word32) writeFastMutInt j_r (j + 1) writeIORef out_r $! addToUFM out unique (j, f) putSymbolTable :: BinHandle -> Int -> UniqFM (Int,HieName) -> IO () putSymbolTable bh next_off symtab = do put_ bh next_off let names = A.elems (A.array (0,next_off-1) (nonDetEltsUFM symtab)) mapM_ (putHieName bh) names getSymbolTable :: BinHandle -> NameCache -> IO (NameCache, SymbolTable) getSymbolTable bh namecache = do sz <- get bh od_names <- replicateM sz (getHieName bh) let arr = A.listArray (0,sz-1) names (namecache', names) = mapAccumR fromHieName namecache od_names return (namecache', arr) getSymTabName :: SymbolTable -> BinHandle -> IO Name getSymTabName st bh = do i :: Word32 <- get bh return $ st A.! (fromIntegral i) putName :: HieSymbolTable -> BinHandle -> Name -> IO () putName (HieSymbolTable next ref) bh name = do symmap <- readIORef ref case lookupUFM symmap name of Just (off, ExternalName mod occ (UnhelpfulSpan _)) | isGoodSrcSpan (nameSrcSpan name) -> do let hieName = ExternalName mod occ (nameSrcSpan name) writeIORef ref $! addToUFM symmap name (off, hieName) put_ bh (fromIntegral off :: Word32) Just (off, LocalName _occ span) | notLocal (toHieName name) || nameSrcSpan name /= span -> do writeIORef ref $! addToUFM symmap name (off, toHieName name) put_ bh (fromIntegral off :: Word32) Just (off, _) -> put_ bh (fromIntegral off :: Word32) Nothing -> do off <- readFastMutInt next writeFastMutInt next (off+1) writeIORef ref $! addToUFM symmap name (off, toHieName name) put_ bh (fromIntegral off :: Word32) where notLocal :: HieName -> Bool notLocal LocalName{} = False notLocal _ = True -- ** Converting to and from `HieName`'s toHieName :: Name -> HieName toHieName name | isKnownKeyName name = KnownKeyName (nameUnique name) | isExternalName name = ExternalName (nameModule name) (nameOccName name) (nameSrcSpan name) | otherwise = LocalName (nameOccName name) (nameSrcSpan name) fromHieName :: NameCache -> HieName -> (NameCache, Name) fromHieName nc (ExternalName mod occ span) = let cache = nsNames nc in case lookupOrigNameCache cache mod occ of Just name -> (nc, name) Nothing -> let (uniq, us) = takeUniqFromSupply (nsUniqs nc) name = mkExternalName uniq mod occ span new_cache = extendNameCache cache mod occ name in ( nc{ nsUniqs = us, nsNames = new_cache }, name ) fromHieName nc (LocalName occ span) = let (uniq, us) = takeUniqFromSupply (nsUniqs nc) name = mkInternalName uniq occ span in ( nc{ nsUniqs = us }, name ) fromHieName nc (KnownKeyName u) = case lookupKnownKeyName u of Nothing -> pprPanic "fromHieName:unknown known-key unique" (ppr (unpkUnique u)) Just n -> (nc, n) -- ** Reading and writing `HieName`'s putHieName :: BinHandle -> HieName -> IO () putHieName bh (ExternalName mod occ span) = do putByte bh 0 put_ bh (mod, occ, span) putHieName bh (LocalName occName span) = do putByte bh 1 put_ bh (occName, span) putHieName bh (KnownKeyName uniq) = do putByte bh 2 put_ bh $ unpkUnique uniq getHieName :: BinHandle -> IO HieName getHieName bh = do t <- getByte bh case t of 0 -> do (modu, occ, span) <- get bh return $ ExternalName modu occ span 1 -> do (occ, span) <- get bh return $ LocalName occ span 2 -> do (c,i) <- get bh return $ KnownKeyName $ mkUnique c i _ -> panic "GHC.Iface.Ext.Binary.getHieName: invalid tag"
sdiehl/ghc
compiler/GHC/Iface/Ext/Binary.hs
bsd-3-clause
13,244
0
18
3,508
3,764
1,875
1,889
320
5
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module Main where import Control.Concurrent (threadDelay) import Control.Exception import Control.Monad import Control.Monad.IO.Class import Data.Default import Data.Time import System.IO (stdout) import System.Log.Formatter (simpleLogFormatter) import System.Log.Handler (setFormatter) import System.Log.Handler.Simple (streamHandler) import System.Log.Logger import API.IB -- ----------------------------------------------------------------------------- -- Reference data conES :: IBContract conES = future "ES" "ESZ5" (Just $ fromGregorian 2015 12 18) GLOBEX "USD" conES' :: IBContract conES' = future "ES" "" Nothing GLOBEX "USD" -- ----------------------------------------------------------------------------- -- Requests requests :: IB () requests = do display "Starting" displayStatus connect --reqConData reqMktData recvP 50 displayStatus disconnect delay 5 connect reqMktData recvP 30 delay 10 stop displayStatus display "Finished" where --reqConData = requestContractData conES' reqMktData = requestMarketData conES [] False displayStatus = status >>= display . show recvP n = replicateM_ n $ recv >>= display . show delay t = liftIO $ threadDelay (t*1000000) display = liftIO . putStrLn -- ----------------------------------------------------------------------------- -- Main main :: IO () main = do handler <- streamHandler stdout DEBUG >>= \h -> return $ setFormatter h $ simpleLogFormatter "$time $loggername $prio: $msg" updateGlobalLogger rootLoggerName (setLevel DEBUG . setHandlers [handler]) finally (runIB def requests) (threadDelay 1000000)
teuffy/interactive-brokers
executable/Requests-Simple.hs
bsd-3-clause
1,876
0
12
422
419
216
203
47
1
module GHC.VacuumTube where import Control.Applicative import Data.Binary import GHC.VacuumTube.Limbo import GHC.VacuumTube.Morgue newtype VacuumTube a = VacuumTube{unVacuumTube :: a} instance Binary (VacuumTube a) where put = vacuumPut . unVacuumTube get = VacuumTube <$> vacuumGet
alphaHeavy/vacuum-tube
GHC/VacuumTube.hs
bsd-3-clause
291
0
7
41
74
45
29
9
0
{-# LANGUAGE CPP #-} #define LAZY Strict #define BANG ! #include "base.inc"
liyang/enumfun
Data/EnumFun/Strict/Base.hs
bsd-3-clause
76
0
2
12
6
5
1
1
0
{-# OPTIONS_GHC -Wall #-} module Elm.Project.Flags ( Options(..) , Output(..) , safeCustomPath ) where import qualified System.Directory as Dir import System.FilePath ((</>)) import qualified Elm.Compiler.Objects as Obj data Options = Options { _mode :: Obj.Mode , _target :: Obj.Target , _output :: Maybe Output } data Output = None | Custom (Maybe FilePath) FilePath safeCustomPath :: Maybe FilePath -> FilePath -> IO FilePath safeCustomPath maybeDirectory fileName = case maybeDirectory of Nothing -> do return fileName Just dir -> do Dir.createDirectoryIfMissing True dir return (dir </> fileName)
evancz/builder
src/Elm/Project/Flags.hs
bsd-3-clause
679
0
12
163
187
106
81
24
2
{-| Module : Idris.CaseSplit Description : Module to provide case split functionality. Copyright : License : BSD3 Maintainer : The Idris Community. Given a pattern clause and a variable 'n', elaborate the clause and find the type of 'n'. Make new pattern clauses by replacing 'n' with all the possibly constructors applied to '_', and replacing all other variables with '_' in order to resolve other dependencies. Finally, merge the generated patterns with the original, by matching. Always take the "more specific" argument when there is a discrepancy, i.e. names over '_', patterns over names, etc. -} {-# LANGUAGE PatternGuards #-} module Idris.CaseSplit( splitOnLine, replaceSplits , getClause, getProofClause , mkWith , nameMissing , getUniq, nameRoot ) where import Idris.AbsSyntax import Idris.AbsSyntaxTree (IState, Idris, PTerm) import Idris.Core.Evaluate import Idris.Core.TT import Idris.Core.Typecheck import Idris.Delaborate import Idris.Elab.Term import Idris.Elab.Value import Idris.ElabDecls import Idris.Error import Idris.Output import Idris.Parser import Idris.Parser.Helpers import Control.Monad import Control.Monad.State.Strict import Data.Char import Data.List (isPrefixOf, isSuffixOf) import Data.Maybe import Debug.Trace import Text.Parser.Char (anyChar) import Text.Parser.Combinators import Text.Trifecta (Result(..), parseString) import Text.Trifecta.Delta -- | Given a variable to split, and a term application, return a list -- of variable updates, paired with a flag to say whether the given -- update typechecks (False = impossible) if the flag is 'False' the -- splits should be output with the 'impossible' flag, otherwise they -- should be output as normal split :: Name -> PTerm -> Idris (Bool, [[(Name, PTerm)]]) split n t' = do ist <- getIState -- Make sure all the names in the term are accessible mapM_ (\n -> setAccessibility n Public) (allNamesIn t') -- ETyDecl rather then ELHS because there'll be explicit type -- matching (tm, ty, pats) <- elabValBind (recinfo (fileFC "casesplit")) ETyDecl True (addImplPat ist t') -- ASSUMPTION: tm is in normal form after elabValBind, so we don't -- need to do anything special to find out what family each argument -- is in logElab 4 ("Elaborated:\n" ++ show tm ++ " : " ++ show ty ++ "\n" ++ show pats) -- iputStrLn (show (delab ist tm) ++ " : " ++ show (delab ist ty)) -- iputStrLn (show pats) let t = mergeUserImpl (addImplPat ist t') (delabDirect ist tm) let ctxt = tt_ctxt ist case lookup n pats of Nothing -> ifail $ show n ++ " is not a pattern variable" Just ty -> do let splits = findPats ist ty logElab 1 ("New patterns " ++ showSep ", " (map showTmImpls splits)) let newPats_in = zipWith (replaceVar ctxt n) splits (repeat t) logElab 4 ("Working from " ++ showTmImpls t) logElab 4 ("Trying " ++ showSep "\n" (map (showTmImpls) newPats_in)) newPats_in <- mapM elabNewPat newPats_in case anyValid [] [] newPats_in of Left fails -> do let fails' = mergeAllPats ist n t fails return (False, (map snd fails')) Right newPats -> do logElab 3 ("Original:\n" ++ show t) logElab 3 ("Split:\n" ++ (showSep "\n" (map show newPats))) logElab 3 "----" let newPats' = mergeAllPats ist n t newPats logElab 1 ("Name updates " ++ showSep "\n" (map (\ (p, u) -> show u ++ " " ++ show p) newPats')) return (True, (map snd newPats')) where anyValid ok bad [] = if null ok then Left (reverse bad) else Right (reverse ok) anyValid ok bad ((tc, p) : ps) | tc = anyValid (p : ok) bad ps | otherwise = anyValid ok (p : bad) ps data MergeState = MS { namemap :: [(Name, Name)], invented :: [(Name, Name)], explicit :: [Name], updates :: [(Name, PTerm)] } addUpdate :: Name -> Idris.AbsSyntaxTree.PTerm -> State MergeState () addUpdate n tm = do ms <- get put (ms { updates = ((n, stripNS tm) : updates ms) } ) inventName :: Idris.AbsSyntaxTree.IState -> Maybe Name -> Name -> State MergeState Name inventName ist ty n = do ms <- get let supp = case ty of Nothing -> [] Just t -> getNameHints ist t let nsupp = case n of MN i n | not (tnull n) && thead n == '_' -> mkSupply (supp ++ varlist) MN i n -> mkSupply (UN n : supp ++ varlist) UN n | thead n == '_' -> mkSupply (supp ++ varlist) x -> mkSupply (x : supp) let badnames = map snd (namemap ms) ++ map snd (invented ms) ++ explicit ms case lookup n (invented ms) of Just n' -> return n' Nothing -> do let n' = uniqueNameFrom nsupp badnames put (ms { invented = (n, n') : invented ms }) return n' mkSupply :: [Name] -> [Name] mkSupply ns = mkSupply' ns (map nextName ns) where mkSupply' xs ns' = xs ++ mkSupply ns' varlist :: [Name] varlist = map (sUN . (:[])) "xyzwstuv" -- EB's personal preference :) stripNS :: Idris.AbsSyntaxTree.PTerm -> Idris.AbsSyntaxTree.PTerm stripNS tm = mapPT dens tm where dens (PRef fc hls n) = PRef fc hls (nsroot n) dens t = t mergeAllPats :: IState -> Name -> PTerm -> [PTerm] -> [(PTerm, [(Name, PTerm)])] mergeAllPats ist cv t [] = [] mergeAllPats ist cv t (p : ps) = let (p', MS _ _ _ u) = runState (mergePat ist t p Nothing) (MS [] [] (filter (/=cv) (patvars t)) []) ps' = mergeAllPats ist cv t ps in ((p', u) : ps') where patvars (PRef _ _ n) = [n] patvars (PApp _ _ as) = concatMap (patvars . getTm) as patvars (PPatvar _ n) = [n] patvars _ = [] mergePat :: IState -> PTerm -> PTerm -> Maybe Name -> State MergeState PTerm mergePat ist orig new t = do -- collect user names for name map, by matching user pattern against -- the generated pattern case matchClause ist orig new of Left _ -> return () Right ns -> mapM_ addNameMap ns mergePat' ist orig new t where addNameMap (n, PRef fc _ n') = do ms <- get put (ms { namemap = ((n', n) : namemap ms) }) addNameMap _ = return () -- | If any names are unified, make sure they stay unified. Always -- prefer user provided name (first pattern) mergePat' ist (PPatvar fc n) new t = mergePat' ist (PRef fc [] n) new t mergePat' ist old (PPatvar fc n) t = mergePat' ist old (PRef fc [] n) t mergePat' ist orig@(PRef fc _ n) new@(PRef _ _ n') t | isDConName n' (tt_ctxt ist) = do addUpdate n new return new | otherwise = do ms <- get case lookup n' (namemap ms) of Just x -> do addUpdate n (PRef fc [] x) return (PRef fc [] x) Nothing -> do put (ms { namemap = ((n', n) : namemap ms) }) return (PRef fc [] n) mergePat' ist (PApp _ _ args) (PApp fc f args') t = do newArgs <- zipWithM mergeArg args (zip args' (argTys ist f)) return (PApp fc f newArgs) where mergeArg x (y, t) = do tm' <- mergePat' ist (getTm x) (getTm y) t case x of (PImp _ _ _ _ _) -> return (y { machine_inf = machine_inf x, getTm = tm' }) _ -> return (y { getTm = tm' }) mergePat' ist (PRef fc _ n) tm ty = do tm <- tidy ist tm ty addUpdate n tm return tm mergePat' ist x y t = return y mergeUserImpl :: PTerm -> PTerm -> PTerm mergeUserImpl x y = x argTys :: IState -> PTerm -> [Maybe Name] argTys ist (PRef fc hls n) = case lookupTy n (tt_ctxt ist) of [ty] -> let ty' = normalise (tt_ctxt ist) [] ty in map (tyName . snd) (getArgTys ty') ++ repeat Nothing _ -> repeat Nothing where tyName (Bind _ (Pi _ _ _ _) _) = Just (sUN "->") tyName t | (P _ d _, [_, ty]) <- unApply t, d == sUN "Delayed" = tyName ty | (P _ n _, _) <- unApply t = Just n | otherwise = Nothing argTys _ _ = repeat Nothing tidy :: IState -> PTerm -> Maybe Name -> State MergeState PTerm tidy ist orig@(PRef fc hls n) ty = do ms <- get case lookup n (namemap ms) of Just x -> return (PRef fc [] x) Nothing -> case n of (UN _) -> return orig _ -> do n' <- inventName ist ty n return (PRef fc [] n') tidy ist (PApp fc f args) ty = do args' <- zipWithM tidyArg args (argTys ist f) return (PApp fc f args') where tidyArg x ty' = do tm' <- tidy ist (getTm x) ty' return (x { getTm = tm' }) tidy ist tm ty = return tm -- mapPT tidyVar tm -- where tidyVar (PRef _ _) = Placeholder -- tidyVar t = t elabNewPat :: PTerm -> Idris (Bool, PTerm) elabNewPat t = idrisCatch (do (tm, ty) <- elabVal (recinfo (fileFC "casesplit")) ELHS t i <- getIState return (True, delabDirect i tm)) (\e -> do i <- getIState logElab 5 $ "Not a valid split:\n" ++ showTmImpls t ++ "\n" ++ pshow i e return (False, t)) findPats :: IState -> Type -> [PTerm] findPats ist t | (P _ n _, _) <- unApply t = case lookupCtxt n (idris_datatypes ist) of [ti] -> map genPat (con_names ti) _ -> [Placeholder] where genPat n = case lookupCtxt n (idris_implicits ist) of [args] -> PApp emptyFC (PRef emptyFC [] n) (map toPlaceholder args) _ -> error $ "Can't happen (genPat) " ++ show n toPlaceholder tm = tm { getTm = Placeholder } findPats ist t = [Placeholder] replaceVar :: Context -> Name -> PTerm -> PTerm -> PTerm replaceVar ctxt n t (PApp fc f pats) = PApp fc f (map substArg pats) where subst :: PTerm -> PTerm subst orig@(PPatvar _ v) | v == n = t | otherwise = Placeholder subst orig@(PRef _ _ v) | v == n = t | isDConName v ctxt = orig subst (PRef _ _ _) = Placeholder subst (PApp fc (PRef _ _ t) pats) | isTConName t ctxt = Placeholder -- infer types subst (PApp fc f pats) = PApp fc f (map substArg pats) subst x = x substArg arg = arg { getTm = subst (getTm arg) } replaceVar ctxt n t pat = pat splitOnLine :: Int -- ^ line number -> Name -- ^ variable -> FilePath -- ^ name of file -> Idris (Bool, [[(Name, PTerm)]]) splitOnLine l n fn = do cl <- getInternalApp fn l logElab 3 ("Working with " ++ showTmImpls cl) tms <- split n cl return tms replaceSplits :: String -> [[(Name, PTerm)]] -> Bool -> Idris [String] replaceSplits l ups impossible = do ist <- getIState updateRHSs 1 (map (rep ist (expandBraces l)) ups) where rep ist str [] = str ++ "\n" rep ist str ((n, tm) : ups) = rep ist (updatePat False (show n) (nshow (resugar ist tm)) str) ups updateRHSs i [] = return [] updateRHSs i (x : xs) | impossible = do xs' <- updateRHSs i xs return (setImpossible False x : xs') | otherwise = do (x', i') <- updateRHS (null xs) i x xs' <- updateRHSs i' xs return (x' : xs') updateRHS last i ('?':'=':xs) = do (xs', i') <- updateRHS last i xs return ("?=" ++ xs', i') updateRHS last i ('?':xs) = do let (nm, rest_in) = span (not . (\x -> isSpace x || x == ')' || x == '(')) xs let rest = if last then rest_in else case span (not . (=='\n')) rest_in of (_, restnl) -> restnl (nm', i') <- getUniq nm i return ('?':nm' ++ rest, i') updateRHS last i (x : xs) = do (xs', i') <- updateRHS last i xs return (x : xs', i') updateRHS last i [] = return ("", i) setImpossible brace ('}':xs) = '}' : setImpossible False xs setImpossible brace ('{':xs) = '{' : setImpossible True xs setImpossible False ('=':xs) = "impossible\n" setImpossible brace (x : xs) = x : setImpossible brace xs setImpossible brace [] = "" -- TMP HACK: If there are Nats, we don't want to show as numerals since -- this isn't supported in a pattern, so special case here nshow (PRef _ _ (UN z)) | z == txt "Z" = "Z" nshow (PApp _ (PRef _ _ (UN s)) [x]) | s == txt "S" = "(S " ++ addBrackets (nshow (getTm x)) ++ ")" nshow t = show t -- if there's any {n} replace with {n=n} -- but don't replace it in comments expandBraces ('{' : '-' : xs) = '{' : '-' : xs expandBraces ('{' : xs) = let (brace, (_:rest)) = span (/= '}') xs in if (not ('=' `elem` brace)) then ('{' : brace ++ " = " ++ brace ++ "}") ++ expandBraces rest else ('{' : brace ++ "}") ++ expandBraces rest expandBraces (x : xs) = x : expandBraces xs expandBraces [] = [] updatePat start n tm [] = [] updatePat start n tm ('{':rest) = let (space, rest') = span isSpace rest in '{' : space ++ updatePat False n tm rest' updatePat start n tm done@('?':rest) = done updatePat True n tm xs@(c:rest) | length xs > length n = let (before, after@(next:_)) = splitAt (length n) xs in if (before == n && not (isAlphaNum next)) then addBrackets tm ++ updatePat False n tm after else c : updatePat (not (isAlphaNum c)) n tm rest updatePat start n tm (c:rest) = c : updatePat (not ((isAlphaNum c) || c == '_')) n tm rest addBrackets tm | ' ' `elem` tm , not (isPrefixOf "(" tm && isSuffixOf ")" tm) = "(" ++ tm ++ ")" | otherwise = tm getUniq :: (Show t, Num t) => [Char] -> t -> Idris ([Char], t) getUniq nm i = do ist <- getIState let n = nameRoot [] nm ++ "_" ++ show i case lookupTy (sUN n) (tt_ctxt ist) of [] -> return (n, i+1) _ -> getUniq nm (i+1) nameRoot acc nm | all isDigit nm = showSep "_" acc nameRoot acc nm = case span (/='_') nm of (before, ('_' : after)) -> nameRoot (acc ++ [before]) after _ -> showSep "_" (acc ++ [nm]) -- Show a name for use in pattern definitions on the lhs showLHSName :: Name -> String showLHSName n = let fn = show n in if any (flip elem opChars) fn then "(" ++ fn ++ ")" else fn -- Show a name for the purpose of generating a metavariable name on the rhs showRHSName :: Name -> String showRHSName n = let fn = show n in if any (flip elem opChars) fn then "op" else fn getClause :: Int -- ^ line number that the type is declared on -> Name -- ^ Function name -> Name -- ^ User given name -> FilePath -- ^ Source file name -> Idris String getClause l fn un fp = do i <- getIState case lookupCtxt un (idris_interfaces i) of [c] -> return (mkInterfaceBodies i (interface_methods c)) _ -> do ty_in <- getInternalApp fp l let ty = case ty_in of PTyped n t -> t x -> x ist <- get let ap = mkApp ist ty [] return (showLHSName un ++ " " ++ ap ++ "= ?" ++ showRHSName un ++ "_rhs") where mkApp :: IState -> PTerm -> [Name] -> String mkApp i (PPi (Exp _ _ False _) (MN _ _) _ ty sc) used = let n = getNameFrom i used ty in show n ++ " " ++ mkApp i sc (n : used) mkApp i (PPi (Exp _ _ False _) (UN n) _ ty sc) used | thead n == '_' = let n = getNameFrom i used ty in show n ++ " " ++ mkApp i sc (n : used) mkApp i (PPi (Exp _ _ False _) n _ _ sc) used = show n ++ " " ++ mkApp i sc (n : used) mkApp i (PPi _ _ _ _ sc) used = mkApp i sc used mkApp i _ _ = "" getNameFrom i used (PPi _ _ _ _ _) = uniqueNameFrom (mkSupply [sUN "f", sUN "g"]) used getNameFrom i used (PApp fc f as) = getNameFrom i used f getNameFrom i used (PRef fc _ f) = case getNameHints i f of [] -> uniqueNameFrom (mkSupply [sUN "x", sUN "y", sUN "z"]) used ns -> uniqueNameFrom (mkSupply ns) used getNameFrom i used _ = uniqueNameFrom (mkSupply [sUN "x", sUN "y", sUN "z"]) used -- write method declarations, indent with 4 spaces mkInterfaceBodies :: IState -> [(Name, (Bool, FnOpts, PTerm))] -> String mkInterfaceBodies i ns = showSep "\n" (zipWith (\(n, (_, _, ty)) m -> " " ++ def (show (nsroot n)) ++ " " ++ mkApp i ty [] ++ "= ?" ++ showRHSName un ++ "_rhs_" ++ show m) ns [1..]) def n@(x:xs) | not (isAlphaNum x) = "(" ++ n ++ ")" def n = n getProofClause :: Int -- ^ line number that the type is declared -> Name -- ^ Function name -> FilePath -- ^ Source file name -> Idris String getProofClause l fn fp = do ty_in <- getInternalApp fp l let ty = case ty_in of PTyped n t -> t x -> x return (mkApp ty ++ " = ?" ++ showRHSName fn ++ "_rhs") where mkApp (PPi _ _ _ _ sc) = mkApp sc mkApp rt = "(" ++ show rt ++ ") <== " ++ show fn -- Purely syntactic - turn a pattern match clause into a with and a new -- match clause mkWith :: String -> Name -> String mkWith str n = let str' = replaceRHS str "with (_)" in str' ++ "\n" ++ newpat str where replaceRHS [] str = str replaceRHS ('?':'=': rest) str = str replaceRHS ('=': rest) str | not ('=' `elem` rest) = str replaceRHS (x : rest) str = x : replaceRHS rest str newpat ('>':patstr) = '>':newpat patstr newpat patstr = " " ++ replaceRHS patstr "| with_pat = ?" ++ showRHSName n ++ "_rhs" -- Replace _ with names in missing clauses nameMissing :: [PTerm] -> Idris [PTerm] nameMissing ps = do ist <- get newPats <- mapM nm ps let newPats' = mergeAllPats ist (sUN "_") (base (head ps)) newPats return (map fst newPats') where base (PApp fc f args) = PApp fc f (map (fmap (const (PRef fc [] (sUN "_")))) args) base t = t nm ptm = do mptm <- elabNewPat ptm case mptm of (False, _) -> return ptm (True, ptm') -> return ptm'
bravit/Idris-dev
src/Idris/CaseSplit.hs
bsd-3-clause
20,633
0
27
8,058
7,135
3,560
3,575
391
22
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE DeriveGeneric #-} module Scripts.FCCForm471 ( module Scripts.FCCForm471 , module Scripts.FCCForm471Types ) where import ClassyPrelude hiding (take, takeWhile) import Control.Lens hiding (index, cons, snoc) import Data.Aeson import Data.Aeson.Lens import Appian import Appian.Types import Appian.Instances import Appian.Lens import Appian.Client import Appian.Internal.Updates import Data.Attoparsec.Text hiding (Result) import Data.Time (addDays) import Appian.Internal.Arbitrary import qualified Test.QuickCheck as QC import Control.Lens.Action import Control.Lens.Action.Reified import Scripts.Common import qualified Data.Foldable as F import qualified Data.Csv as Csv import Control.Monad.Logger import Control.Monad.Time import Scripts.FCCForm471Types import Scripts.FCCForm471Common (Form471Num(..)) import Data.Random (MonadRandom) import Control.Retry import Control.Monad.Except hiding (foldM, mapM_) form471Intake :: (RapidFire m, MonadGen m, MonadIO m) => Form471Conf -> AppianT m Form471Num form471Intake conf = do v <- reportsTab rid <- getReportId "My Landing Page" v v' <- editReport rid form471Link <- handleMissing "FCC Form 471" v' $ v' ^? landingPageLink "FCC Form 471" aid <- handleMissing "Action ID" v' $ parseActionId form471Link pid <- landingPageAction aid v'' <- ( do v <- landingPageActionEx pid v' <- handleMultipleEntitiesOld checkMultipleOrgs "Apply for Funding Now" "Organization ID" (conf ^. selectOrgMethod) v case v' ^? isWindowClose of Nothing -> return v' Just False -> return v' Just True -> sendUpdates "Window Close" (buttonUpdateNoCheckF "Continue") v' ) membersPage <- sendUpdates "Nickname" ( MonadicFold (textFieldArbitrary "Please enter an application nickname here." 255) <|> buttonUpdateNoCheckF "Save & Continue" ) v'' >>= sendUpdates "Contact Info" ( buttonUpdateNoCheckF "Yes" <|> paragraphArbitraryUpdate "Enter Holiday Contact Information" 4000 <|> buttonUpdateNoCheckF "Save & Continue" ) >>= sendUpdates "Choose Category" ( buttonUpdateNoCheckF (conf ^. category . to tshow) <|> buttonUpdateNoCheckF "Save & Continue" ) entityInformation <- case membersCompleted membersPage of True -> sendUpdates "Entity Members" (buttonUpdateNoCheckF "Save & Continue") membersPage False -> selectMembers membersPage frnList <- sendUpdates "View Entity Types" (buttonUpdateNoCheckF "Save & Continue") entityInformation >>= sendUpdates "View Discount Rates" (buttonUpdateNoCheckF "Save & Continue") >>= createFRN conf (conf ^. nFRNs) (conf ^. spin) val <- case conf ^. createFRNType of NewFRN -> forLineItems conf frnList CopyFRN _ -> clickThroughAllFRNLineItems frnList let asDynamicLink = id :: DynamicLink -> DynamicLink val' <- case conf ^. category of Cat2 -> sendUpdates "Click Cat2 Budget Link" (componentUpdateWithF "Could not find 'Cat2 Budget Link'" $ hasKeyValue "testLabel" ">> Click to View" . _JSON . to asDynamicLink) val Cat1 -> return val val'' <- case val ^? getButton "Continue" of Just _ -> sendUpdates "Click 'Continue'" (buttonUpdateF "Continue") val' Nothing -> return val' ifContinueToCertification val'' isMultipleEntities :: (Plated s, AsValue s) => Text -> Fold s Text isMultipleEntities buttonLabel = hasKeyValue "label" buttonLabel . key "#t" . _String checkMultipleOrgs :: Value -> MultiOrgStatus checkMultipleOrgs v = case v ^? isMultipleEntities "Apply For Funding Now" of Nothing -> IsSingle Just "FormLayout" -> IsMultiple Just _ -> Failure "There seems to be some change in the 'Select Organization' page or perhaps it is different for this operation?" selectMembers :: (RapidFire m, MonadGen m) => Value -> AppianT m Value selectMembers = selectMembers' -- selectMembers v = do -- (v', rGridField) <- validMemberCheckboxes v -- case rGridField of -- Error msg -> throwError $ MissingComponentError ("selectMembers: " <> pack msg, v') -- Success gridField -> do -- taskId <- getTaskId v' -- let updates = toUpdate gridField -- checked <- sendUpdate (taskUpdate taskId) $ mkUiUpdate [updates] v' -- sendUpdates "Add Members" (buttonUpdateNoCheckF "Add") checked -- >>= sendUpdates "Click Save & Continue" (buttonUpdateNoCheckF "Save & Continue") validMemberCheckboxes :: (RapidFire m, MonadGen m) => Value -> AppianT m (Value, Result (GridField GridFieldCell)) validMemberCheckboxes v = do logDebugN "Getting valid member checkboxes." let mRefs = v ^.. getGridFieldRecordRefs "BEN Name" . traverse case mRefs of [] -> throwError $ BadUpdateError "There are no entity members!" (Just v) refs -> do discountRates <- mapM (\r -> (,) <$> pure r <*> viewDiscountRates r) refs taskId <- getTaskId v let validRefs = discountRates ^.. traverse . filtered (has $ _2 . to insufficientDiscountRate . only False) . _1 updates = v ^.. to (buttonUpdate "No") . traverse v' <- sendUpdate (taskUpdate taskId) $ mkUiUpdate updates v let gf = v' ^. getGridField refs' = gf ^.. traverse . gfColumns . at "BEN Name" . traverse . _TextCellLink . _2 . traverse idents = gf ^.. traverse . gfIdentifiers . traverse . ifolded . ifiltered (\i _ -> i `elem` indices) indices = refs ^.. ifolded . filtered (\r -> r `elem` validRefs) . withIndex . _1 return (v', _Success . gfSelection . _Just . _Selectable . gslSelected .~ idents $ gf) selectMembers' :: (RapidFire m, MonadGen m) => Value -> AppianT m Value selectMembers' v = do assign appianValue v sendUpdates1 "Select 'No' for 'Is every member in this consortium included on this FCC Form 471?'" (buttonUpdateF "No") validMemberCheckboxes' sendUpdates1 "Click 'Add' to add members" (buttonUpdateF "Add") sendUpdates1 "Click 'Save & Continue' to 'Entity Information'" (buttonUpdateF "Save & Continue") use appianValue validMemberCheckboxes' :: (RapidFire m, MonadGen m) => AppianT m () validMemberCheckboxes' = do forGridRows1_ sendUpdates (^. runFold ((,) <$> Fold getGridFieldIdfs <*> Fold getGridFieldRefs) . to (uncurry zip)) (MonadicFold $ getGridField . traverse) viewDiscountRates' pure () getGridFieldRefs :: Traversal' (GridField GridFieldCell) (Vector RecordRef) getGridFieldRefs = gfColumns . at "BEN Name" . traverse . _TextCellLink . _2 getGridFieldIdfs :: Traversal' (GridField GridFieldCell) (Vector GridFieldIdent) getGridFieldIdfs = gfIdentifiers . traverse viewDiscountRates :: (RapidFire m, MonadGen m) => RecordRef -> AppianT m Value viewDiscountRates rref = do dashState <- runDashboardByName rref "Discount Rate" execDashboardFormT (pure ()) dashState use appianValue viewDiscountRates' :: (RapidFire m, MonadGen m) => (GridFieldIdent, RecordRef) -> GridField GridFieldCell -> AppianT m () viewDiscountRates' (identifier, rref) gf = do v <- use appianValue eDashState <- runDashboardByName' rref "Discount Rate" case eDashState of Left _ -> return () Right dashState -> do discountRates <- execDashboardFormT (usesValue' (^.. getDiscountRate)) dashState assign appianValue v case discountRates of [] -> return () discounts -> do mapM_ (logDebugN . tshow) $ discounts sendUpdates1 "Selecting Member Entity" (componentUpdateWithF "The impossible happened! Check the viewDiscountRates function in 471 intake." (to (const $ gridFieldSelect identifier gf)) ) gridFieldSelect :: GridFieldIdent -> GridField GridFieldCell -> GridField GridFieldCell gridFieldSelect ident = gfSelection . traverse . _Selectable . gslSelected %~ (cons ident) usesValue' :: Monad m => (Value -> a) -> DashboardFormT m a usesValue' f = mkDashboardFormT $ \dashState -> do a <- usesValue f pure (a, dashState) -- viewDiscountRates :: (RapidFire m, MonadGen m) => RecordRef -> AppianT m Value -- viewDiscountRates rref = do -- v <- viewRecordDashboard rref (Dashboard "summary") -- dashboard <- handleMissing "Discount Rate" v $ v ^? getRecordDashboard "Discount Rate" -- viewRecordDashboard rref dashboard hasDiscountRate :: Value -> Bool hasDiscountRate = has getDiscountRate insufficientDiscountRate :: Value -> Bool insufficientDiscountRate v = any (checkResult . parseResult) msgs where msgs = v ^.. hasKeyValue "name" "x-embedded-summary" . key "children" . plate . _String . _JSON . asValue . cosmos . key "validations" . plate . key "message" . _String parseResult = parseOnly (manyTill anyChar (string "not sufficient") *> manyTill anyChar (string "Discount Rate") *> pure True) checkResult (Left _) = False checkResult (Right b) = b isWindowClose :: (Contravariant f, Applicative f, AsValue t) => (Bool -> f Bool) -> t -> f t isWindowClose = key "title" . _String . to (=="FCC Form 471 Funding Year Window is Closed") selectFirst :: Applicative f => (GridFieldIdent -> f GridFieldIdent) -> GridField a0 -> f (GridField a0) selectFirst = gfIdentifiers . traverse . taking 1 traverse arbTextInt :: MonadGen m => LineItemSize -> m Text arbTextInt Small = genArbitrary (resize 1 $ QC.arbitrarySizedNatural :: Gen Int) >>= pure . tshow . (+1) arbTextInt Regular = genArbitrary (QC.arbitrarySizedNatural :: Gen Int) >>= pure . tshow . (+1) arbTextInt Large = genArbitrary (resize 1000000 $ QC.arbitrarySizedNatural :: Gen Int) >>= pure . tshow . (+1) arbTextInt (Range low high) = genArbitrary (QC.choose (low, high) :: Gen Int) >>= pure . tshow membersCompleted :: Value -> Bool membersCompleted v = case v ^? deep (filtered $ has $ key "value" . _String . prefixed "We've completed this section of the form based on information from your applicant entity's profile.") of Nothing -> False Just _ -> True selectConsortiumMembers :: Value -> Bool selectConsortiumMembers v = case v ^? getButton "Select an Entity by Consortium Members" of Nothing -> False Just _ -> True selectEntities :: (RapidFire m, MonadGen m) => Value -> AppianT m Value selectEntities v = do v' <- case v ^? getButton "Manage Recipients of Service" of Nothing -> return v Just _ -> sendUpdates "Click 'Manage Recipients of Service'" (buttonUpdateF "Manage Recipients of Service") v case selectConsortiumMembers v' of True -> selectEntitiesReceivingService v' False -> sendUpdates "Manage Recipients of Service" (MonadicFold (getButtonWith (== "Yes") . to toUpdate . to Right) <|> buttonUpdateNoCheckF "Save & Continue" ) v' selectEntitiesReceivingService :: (RapidFire m, MonadGen m) => Value -> AppianT m Value selectEntitiesReceivingService v = sendUpdates "Select Consortia Members" (buttonUpdateNoCheckF "Select an Entity by Consortium Members") v >>= foldDropdown "Select Consortium Member Entity Type" (\v -> case v ^? _JSON . to isEmpty470Grid of Just False -> sendUpdates "Add All Button" addAllButtonUpdate v _ -> return v ) "Search for Consortium Member by Entity Type" >>= isShared -- >>= sendUpdates "Select Consortium Member Entity Type" (MonadicFold (to (dropdownUpdate "Search for Consortium Member by Entity Type" 3))) -- >>= sendUpdates "Add All Dependent Schools and NIFs" (buttonUpdateNoCheckF "Add All Dependent Schools And NIFs "))) -- >>= sendUpdates "Manage Recipients of Service" (buttonUpdateNoCheckF "Save & Continue"))) >>= sendUpdates "Manage Recipients of Service" (buttonUpdateWithF (\label -> label == "Save & Continue" || label == "Continue") "Could not locate 'Continue' button") isShared :: (RapidFire m, MonadGen m) => Value -> AppianT m Value isShared v = case has (getTextField "Are the costs shared equally among all of the entities?") v of True -> sendUpdates "Select Yes (Equally Shared Costs)" (buttonUpdateNoCheckF "Yes" <|> buttonUpdateNoCheckF "Save & Continue" ) v False -> return v isEmpty470Grid :: Value -> Bool isEmpty470Grid v = case v ^? hasType "GridField" . key "numRowsToDisplay" . _Number . only 0.0 of Just _ -> True Nothing -> False search470 :: (RapidFire m, MonadGen m) => Form470SearchType -> Value -> AppianT m Value search470 (ByBEN ben) = sendUpdates "Search for 470 by BEN" (MonadicFold (to $ textUpdate "Search by BEN" ben) <|> buttonUpdateNoCheckF "Search" ) >=> select470 search470 (By470 form470ID) = sendUpdates "Search for 470 by 470 ID" (MonadicFold (to $ textUpdate "Search by FCC Form 470 Number" form470ID) <|> MonadicFold (to $ textUpdate "Search by BEN" mempty) <|> buttonUpdateNoCheckF "Search" ) >=> sendUpdates "Select 470 and Continue" (MonadicFold (to (gridFieldUpdate 0)) <|> buttonUpdateNoCheckF "Continue" ) search470 No470 = sendUpdates "Click Search" (MonadicFold (to $ buttonUpdate "Search")) >=> select470 select470 :: (RapidFire m, MonadGen m) => Value -> AppianT m Value select470 v = case isEmpty470Grid v of True -> sendUpdates "No Form 470" (buttonUpdateNoCheckF "No" <|> buttonUpdateNoCheckF "Continue" ) v False -> sendUpdates "Select 470 and Continue" (MonadicFold (to (gridFieldUpdate 0)) <|> buttonUpdateNoCheckF "Continue" ) v ifContinueToCertification :: (RapidFire m, MonadGen m) => Value -> AppianT m Form471Num ifContinueToCertification v = do formNum <- handleMissing "Could not find 471 number!" v $ v ^? deep (key "title" . _String . to (parseOnly parse471Number) . traverse) case has (key "ui" . key "#t" . _String . only "FormLayout") v of True -> pure formNum False -> case v ^? getButton "Review FCC Form 471" of Just _ -> sendUpdates "Click Review FCC Form 471" (buttonUpdateNoCheckF "Review FCC Form 471") v >> pure formNum Nothing -> do v' <- sendUpdates "Click Continue to Certification" (buttonUpdateNoCheckF "Continue to Certification") v case v' ^? getButton "Review FCC Form 471" of Nothing -> pure formNum Just _ -> sendUpdates "Click Review FCC Form 471" (buttonUpdateNoCheckF "Review FCC Form 471") v' >> pure formNum -- Discards the result of f foldDropdown :: (RapidFire m, MonadGen m) => Text -> (Value -> AppianT m Value) -> Text -> Value -> AppianT m Value foldDropdown label f dfLabel val = foldM go Null indices where go _ n = do v <- sendUpdates (label <> ": Dropdown choice: " <> tshow n) (dfUpdate n) val _ <- f v return val indices :: [Int] indices = case val ^? getDropdown dfLabel of Just df -> [2.. (df ^. dfChoices . to length)] Nothing -> [] dfUpdate n = MonadicFold (to (dropdownUpdate dfLabel n)) addAllButtonUpdate :: (Plated s, AsValue s, AsJSON s) => ReifiedMonadicFold m s (Either Text Update) addAllButtonUpdate = MonadicFold (failing (getButtonWith getAddAllButton . to toUpdate . to Right) (to (const $ Left "Could not find the Add All button!"))) getAddAllButton :: Text -> Bool getAddAllButton label = label == "Add All Dependent Schools And NIFs " || label == "Add All Schools and Dependent NIFs " || label == "Add All Libraries and Dependent NIFs " || label == "Add All Dependent Libraries and NIFs " || label == "Add All Schools " || label == "Add All Libraries " createFRN :: (RapidFire m, MonadGen m, MonadIO m) => Form471Conf -> Int -> Text -> Value -> AppianT m Value createFRN _ 0 _ val = return val createFRN conf n spin val = do logDebugN $ "Creating FRN with " <> tshow (n - 1) <> " to go." val' <- sendUpdates "Create new FRN" (MonadicFold $ to (buttonUpdate "Add FRN")) val frnList <- case conf ^. createFRNType of NewFRN -> createNewFRN conf spin val' CopyFRN method -> sendUpdates "Funding Request Key Information" (MonadicFold (textFieldArbitrary "Please enter a Funding Request Nickname here" 255) <|> MonadicFold (to $ buttonUpdate "No") <|> MonadicFold (to $ buttonUpdate "Copy FRN") ) val' >>= copyFRN conf method >>= sendUpdates "Select an FRN & Continue" (gridFieldArbitrarySelect <|> MonadicFold (to $ buttonUpdate "Continue") ) >>= (\v -> do assign appianValue v retrying refreshRetryPolicy retryRefresh (const $ do sendUpdates1 "Select refresh" (MonadicFold $ to $ buttonUpdate "Refresh" ) use appianValue ) ) >>= sendUpdates "Continue to Key Information" (MonadicFold $ to $ buttonUpdate "Continue") >>= sendUpdates "Continue to Contract" (MonadicFold $ to $ buttonUpdate "Continue") >>= sendUpdates "Continue to Contract Dates" (MonadicFold $ to $ buttonUpdate "Continue") -- The below may change based on contract type >>= setDates >>= sendUpdates "Save Narrative & Continue" (MonadicFold (to $ buttonUpdate "Save & Continue")) createFRN conf (n - 1) spin frnList refreshRetryPolicy :: RetryPolicy refreshRetryPolicy = exponentialBackoff 8000000 `mappend` limitRetries 5 retryRefresh :: MonadIO m => RetryStatus -> Value -> m Bool retryRefresh _ v = pure $ not $ has (deep $ hasKeyValue "#v" "FRN has been successfully copied.") v copyFRN :: (RapidFire m, MonadGen m) => Form471Conf -> SearchFRNMethod -> Value -> AppianT m Value copyFRN conf (ByFRNNumber num) = sendUpdates "Search by FRN Number" (MonadicFold (to $ textUpdate "Search by FRN Number" $ tshow num) <|> MonadicFold (to $ buttonUpdate "Search") ) copyFRN conf (ByFCCForm471 num) = sendUpdates "Search by FCC Form 471" (MonadicFold (to $ textUpdate "Search by FCC Form 471" $ tshow num) <|> MonadicFold (to $ buttonUpdate "Search") ) createNewFRN :: (RapidFire m, MonadGen m) => Form471Conf -> Text -> Value -> AppianT m Value createNewFRN conf spin val = do dates <- sendUpdates "Funding Request Key Information" ( MonadicFold (textFieldArbitrary "Please enter a Funding Request Nickname here" 255) <|> buttonUpdateNoCheckF "No" <|> MonadicFold (to (dropdownUpdate "Category 1 Service Types" 2)) <|> buttonUpdateNoCheckF "Continue" ) val >>= sendUpdates "Select Purchase Type" (buttonUpdateNoCheckF "Tariff" <|> buttonUpdateNoCheckF "Continue" ) >>= sendUpdates "Enter number of Bids" ( MonadicFold (intFieldArbitrary "How many bids were received?") -- (to (textUpdate "How many bids were received?" "3")) <|> buttonUpdateNoCheckF "Yes" ) >>= search470 (conf ^. form470Search) -- >>= select470 >>= sendUpdates "SPIN Search" ( MonadicFold (to (textUpdate "Search by SPIN" spin)) <|> buttonUpdateNoCheckF "Search" ) >>= sendUpdates "Select SPIN and Continue" ( MonadicFold (to (gridFieldUpdate 0)) <|> buttonUpdateNoCheckF "Continue" ) startDate <- handleMissing "Start Date" dates $ dates ^? hasLabel "What is the service start date?" . dpwValue . appianDate . traverse pricing <- sendUpdates "Enter funding dates and Continue" (MonadicFold (to (datePickerUpdate "When will the services end? " (AppianDate $ Just $ addDays 360 startDate))) <|> buttonUpdateNoCheckF "Continue" ) dates res <- sendUpdates "Price Confidentiality and Continue" (buttonUpdateNoCheckF "No" <|> buttonUpdateNoCheckF "Continue" ) pricing narrative <- case res ^? hasKeyValue "label" "Fiber Request Key Information" of Nothing -> return res Just _ -> sendUpdates "Fiber Request Key Information" (MonadicFold (to $ buttonUpdate "No") <|> MonadicFold (to $ buttonUpdate "Continue") ) res sendUpdates "Enter narrative and Continue" (paragraphArbitraryUpdate "Provide a brief explanation of the products and services that you are requesting, or provide any other relevant information regarding this Funding Request. You should also use this field to describe any updates to your entity data, such as revised student counts, entity relationships, etc, that you were unable to make after the close of the Administrative filing window for profile updates. These changes will be addressed during the application review process." 4000 <|> buttonUpdateNoCheckF "Save & Continue" ) narrative setDates :: (RapidFire m, MonadGen m) => Value -> AppianT m Value setDates v = do today <- utctDay <$> currentTime sendUpdates "Enter funding dates and Continue" (MonadicFold (to (datePickerUpdate "What is the service start date?" (AppianDate $ Just today))) <|> MonadicFold (to (datePickerUpdate "What is the date your contract expires for the current term of the contract?" (AppianDate $ Just $ addDays 360 today))) <|> buttonUpdateNoCheckF "Continue" ) v forLineItems :: (RapidFire m, MonadGen m) => Form471Conf -> Value -> AppianT m Value forLineItems conf = forGridRows_ sendUpdates (^. gfColumns . at "FRN" . traverse . _TextCellDynLink . _2) (MonadicFold $ getGridFieldCell . traverse) (\dyl _ v -> addLineItem' conf dyl v) addLineItem' :: (RapidFire m, MonadGen m) => Form471Conf -> DynamicLink -> Value -> AppianT m Value addLineItem' conf dyl v = sendUpdates "Click FRN Link" (MonadicFold (to (const dyl) . to toUpdate . to Right)) v >>= addLineItem'' (conf ^. nLineItems) -- >>= sendUpdates "Review FRN Line Items" (buttonUpdateWithF (\label -> label == "Continue" || label == "Review FCC Form 471") "Could not locate 'Continue' or 'Review 471 Button'") >>= toFRNGrid where addLineItem'' 0 val = return val addLineItem'' n val = do logDebugN $ "Creating line item " <> tshow (conf ^. nLineItems - n + 1) sendUpdates "Add New FRN Line Item" (buttonUpdateNoCheckF "Add New FRN Line Item") val >>= selectFunction >>= handleDataQuestions >>= enterCosts conf >>= selectEntities >>= sendUpdates "Review Recpients" (buttonUpdateNoCheckF "Continue") -- >>= sendUpdates "Select the sub-category" (dropdownUpdateF1 "Select the sub-category you want to modify" "Funding Request Details") -- >>= sendUpdates "Click FRN Link" (MonadicFold (to (const dyl) . to toUpdate . to Right)) >>= (\v -> addLineItem'' (n - 1) v) toFRNGrid val = case val ^? getDropdown "Select the sub-category you want to modify" of Nothing -> sendUpdates "Review FRN Line Items" (buttonUpdateWithF (\label -> label == "Continue") "Could not locate 'Continue' Button") val Just _ -> sendUpdates "Select 'Funding Request Details'" (dropdownUpdateF1 "Select the sub-category you want to modify" "Funding Request Details") val data ProductType = Connection | InternalConnection | Multiple | Unknown deriving (Show, Eq) getProductType :: Value -> ProductType getProductType v = maybe Unknown id mProductType where mProductType = v ^? runFold ( Fold (getDropdown "Function" . to (const Connection)) <|> Fold (getDropdown "Type of Internal Connection" . to (const InternalConnection)) <|> Fold (to $ const Multiple) ) selectFunction :: (RapidFire m, MonadGen m) => Value -> AppianT m Value selectFunction v = do assign appianValue v hasFunction <- usesValue getProductType -- (has $ getDropdown "Function") case hasFunction of Connection -> do selectPurpose sendUpdates1 "Select Function" (dropdownArbitraryUpdateF "Function") sendUpdates1 "Select 'Type of Connection'" (dropdownArbitraryUpdateF "Type of Connection") enterOther sendUpdates1 "Click 'Continue' from Function Details" (buttonUpdateF "Continue") InternalConnection -> do sendUpdates1 "Type of Internal Connection" (dropdownArbitraryUpdateF "Type of Internal Connection") isEditable <- usesValue (has $ getTextField "Type of Product" . tfReadOnly . _Just . only True) case isEditable of True -> return () False -> sendUpdates1 "Type of Product" (dropdownArbitraryUpdateF "Type of Product") sendUpdates1 "Select 'Make'" (dropdownArbitraryUpdateF "Make") makeInput <- usesValue (has $ getTextField "Enter the Make") case makeInput of True -> sendUpdates1 "Enter the Make" (textFieldArbitraryF "Enter the Make" 255) False -> sendUpdates1 "Enter the 'Model'" (textFieldArbitraryF "Model" 255) -- let asButtons = to (id :: [ButtonWidget] -> [ButtonWidget]) -- firstYesNoButtons <- usesValue (^? _JSON . asValue . deep (key "secondaryButtons") . _JSON . asButtons) -- secondYesNoButtons <- usesValue (^? _JSON . asValue . dropping 1 (deep (key "secondaryButtons")) . _JSON . asButtons) -- firstYesNoChoice <- QC.elements $ maybe mempty firstYesNoButtons sendUpdates1 "Select Yes/No Buttons" (buttonArbitraryUpdateF $ deep (key "secondaryButtons") . _JSON) sendUpdates1 "Click 'Continue' from Product Type" (buttonUpdateF "Continue") Multiple -> do sendUpdates1 "Total Quantity of Equipment Maintained" (intFieldArbitraryUpdateF "Total Quantity of Equipment Maintained") sendUpdates1 "Click 'Continue' from Function Details" (buttonUpdateF "Continue") Unknown -> logErrorN "Unknown product type?!" use appianValue -- case has (getDropdown "Function") v of -- True -> sendUpdates "Select Function" (dropdownArbitraryUpdateF "Function") v -- >>= sendUpdates "Select Type of Connection and Continue" (dropdownArbitraryUpdateF "Type of Connection" -- MonadicFold (to (dropdownUpdate "Type of Connection" 13)) -- <|> MonadicFold (radioButtonUpdate "Purpose" 1) -- <|> buttonUpdateNoCheckF "Continue" -- ) -- -- False -> sendUpdates "Select Type of Connection" (MonadicFold (to $ dropdownUpdate "Type of Internal Connection" 2)) v -- -- >>= sendUpdates "Select Type, Make, Model, and Continue" (MonadicFold (to $ dropdownUpdate "Type of Product" 2) -- -- <|> dropdownArbitraryUpdateF "Make" -- -- <|> MonadicFold (textFieldArbitrary "Enter the Make" 255) -- -- <|> MonadicFold (textFieldArbitrary "Model" 255) -- -- <|> MonadicFold (getButtonWith (== "Yes") . to toUpdate . to Right) -- -- <|> MonadicFold (to $ buttonUpdate "Continue") -- -- ) -- False -> sendUpdates "Total Quantity of Equipment Maintained" (MonadicFold (to $ textUpdate "Total Quantity of Equipment Maintained" "2") -- <|> buttonUpdateNoCheckF "Continue" -- ) v data YesNoButtons = YesNoButtons { yesButton :: ButtonWidget , noButton :: ButtonWidget } deriving (Show, Generic) instance FromJSON YesNoButtons where parseJSON val = do mButtons <- val ^!? runMonadicFold (YesNoButtons <$> MonadicFold (hasLabel "Yes" . act parseJSON) <*> MonadicFold (hasLabel"No" . act parseJSON)) case mButtons of Nothing -> fail "Could not find YES/NO buttons" Just buttons -> pure buttons instance ToJSON YesNoButtons buttonArbitraryUpdateF :: MonadGen m => Fold Value YesNoButtons -> ReifiedMonadicFold m Value (Either Text Update) buttonArbitraryUpdateF getButtons = MonadicFold $ failing (getButtons . to Right) (to (const $ Left "Failed to find Yes/No buttons")) . act (mapM (genArbitrary . sampleButton)) . to (fmap toUpdate) where sampleButton (YesNoButtons yes no) = QC.elements [yes, no] checkEmpty :: [a] -> Either Text (NonNull [a]) checkEmpty = maybe (Left "Empty list!") Right . fromNullable selectPurpose :: (RapidFire m, MonadGen m) => AppianT m () selectPurpose = do hasPurpose <- usesValue (has $ getRadioButtonField "Purpose") case hasPurpose of True -> sendUpdates1 "Select 'Purpose'" (radioArbitraryF "Purpose") False -> return () enterOther :: (RapidFire m, MonadGen m) => AppianT m () enterOther = do hasOther <- usesValue (has $ getTextField "Enter Type of Connection, if Other was selected") case hasOther of True -> sendUpdates1 "Enter 'Other'" (textFieldArbitraryF "Enter Type of Connection, if Other was selected" 255) False -> return () handleDataQuestions :: (RapidFire m, MonadGen m) => Value -> AppianT m Value handleDataQuestions v = do case v ^? hasKeyValue "value" "Please enter Bandwidth Speed Information for this Data Transmission and/or Internet Access Line Item" of Nothing -> return $ trace "No bandwidth questions" v Just _ -> do assign appianValue v bdw <- genArbitrary arbitrary enterBandwidthSpeeds bdw -- burstable <- genArbitrary arbitrary -- enterInput (burstable :: Burstable) sendUpdates1 "Click 'Continue'" (buttonUpdateF "Continue") use appianValue >>= handleConnections -- handleDataQuestions v = do -- logDebugN "Handling Data Questions" -- case v ^? hasKeyValue "value" "Please enter Bandwidth Speed Information for this Data Transmission and/or Internet Access Line Item" of -- Nothing -> return $ trace "No bandwidth questions" v -- Just _ -> sendUpdates "Not Burstable & Continue" (buttonUpdateNoCheckF "No" -- <|> buttonUpdateNoCheckF "Continue" -- ) v -- >>= handleConnections enterBandwidthSpeeds :: RapidFire m => BandwidthSpeeds -> AppianT m () enterBandwidthSpeeds bdw = enterInput bdw handleConnections :: (RapidFire m, MonadGen m) => Value -> AppianT m Value handleConnections v = do case has (getDropdown "Connection used by") v of True -> sendUpdates "Select All No & Continue" (MonadicFold (getButtonWith (\l -> l == "No" || l == "No ✓") . to toUpdate . to Right) <|> MonadicFold (to (dropdownUpdate "Connection used by" 2)) <|> buttonUpdateNoCheckF "Continue" ) v False -> sendUpdates "Select All No & Continue" (MonadicFold (getButtonWith (\l -> l == "No" || l == "No ✓") . to toUpdate . to Right) <|> buttonUpdateNoCheckF "Continue" ) v arbLineItemCost :: LineItemSize -> QC.Gen LineItemCost arbLineItemCost Small = resize 1 QC.arbitrary arbLineItemCost Regular = QC.arbitrary arbLineItemCost Large = resize 1000000 QC.arbitrary arbLineItemCost (Range low high) = QC.scale (const high) QC.arbitrary enterCosts :: (RapidFire m, MonadGen m) => Form471Conf -> Value -> AppianT m Value enterCosts conf v = do assign appianValue v lineItemCost <- genArbitrary $ arbLineItemCost $ conf ^. lineItemSize enterLineItemCost lineItemCost differentUnits <- usesValue (has $ deep $ filtered $ has $ key "_cId" . _String . only "c7124e2e127c533cfb4479122a135aa3") case differentUnits of True -> sendUpdates1 "Select 'Units'" (dropdownArbitraryCidUpdateF "c7124e2e127c533cfb4479122a135aa3") False -> return () sendUpdates1 "Click 'Save & Continue'" (buttonUpdateF "Save & Continue") use appianValue -- enterCosts conf v = -- case conf ^. category of -- Cat1 -> case has (hasKeyValue "_cId" "d2d5fc7028c296c76a2a9698ed79bd69") v of -- False -> sendUpdates "Enter Cost Calculations and Continue" (MonadicFold (act (\v -> textFieldCidUpdate "ee957a1e3a2ca52198084739fbb47ba3" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "caeb5787e0d7c381e182e53631fb57ab" <$> pure "0" <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "962c6b0f58a1bddff3b0d629742c983c" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "a20962004cc39b76be3d841b402ed5cc" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "3664d88f53b3b462acdfebcb53c93b1e" <$> pure "0" <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "b7c76bf218e1350b13fb987094288670" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> buttonUpdateNoCheckF "Save & Continue" -- ) v -- True -> sendUpdates "Enter Cost Calculations and Continue" (MonadicFold (act (\v -> textFieldCidUpdate "ee957a1e3a2ca52198084739fbb47ba3" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "caeb5787e0d7c381e182e53631fb57ab" <$> pure "0" <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "962c6b0f58a1bddff3b0d629742c983c" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "a20962004cc39b76be3d841b402ed5cc" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "3664d88f53b3b462acdfebcb53c93b1e" <$> pure "0" <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "b7c76bf218e1350b13fb987094288670" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> dropdownCidArbitraryUpdateF "d2d5fc7028c296c76a2a9698ed79bd69" -- <|> buttonUpdateNoCheckF "Save & Continue" -- ) v -- Cat2 -> sendUpdates "Enter Costs Calutations and Continue" (MonadicFold (act (\v -> textFieldCidUpdate "ee957a1e3a2ca52198084739fbb47ba3" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "caeb5787e0d7c381e182e53631fb57ab" <$> pure "0" <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "a20962004cc39b76be3d841b402ed5cc" <$> arbTextInt (conf ^. lineItemSize) <*> pure v)) -- <|> MonadicFold (act (\v -> textFieldCidUpdate "3664d88f53b3b462acdfebcb53c93b1e" <$> pure "0" <*> pure v)) -- <|> buttonUpdateNoCheckF "Save & Continue" -- ) v enterLineItemCost :: RapidFire m => LineItemCost -> AppianT m () enterLineItemCost = enterInput parse471Number :: Parser Form471Num parse471Number = string "Create FCC Form 471 - " *> (Form471Num <$> decimal) -- parse471Number = manyTill anyChar (string " - Form # ") *> (Form471Num <$> decimal) clickThroughAllFRNLineItems :: (RapidFire m, MonadGen m) => Value -> AppianT m Value clickThroughAllFRNLineItems val = forGridRows_ sendUpdates (^. gfColumns . at "FRN" . traverse . _TextCellDynLink . _2) (MonadicFold $ getGridFieldCell . traverse) (\dyl _ v -> clickThroughFRNLineItems dyl v) val clickThroughFRNLineItems :: (RapidFire m, MonadGen m) => DynamicLink -> Value -> AppianT m Value clickThroughFRNLineItems dyl v = sendUpdates "Click FRN Link" (MonadicFold (to (const dyl) . to toUpdate . to Right)) v >>= forGridRows_ sendUpdates (^. gfColumns . at "FRN Line Item Number" . traverse . _TextCellDynLink . _2) (MonadicFold $ getGridFieldCell . traverse) (\dyl _ v -> clickThroughLineItem dyl v) >>= sendUpdates "Continue to FRN Summary" (MonadicFold $ to $ buttonUpdate "Continue") clickThroughLineItem :: (RapidFire m, MonadGen m) => DynamicLink -> Value -> AppianT m Value clickThroughLineItem dyl v = sendUpdates "Click Line Item" (MonadicFold (to (const dyl) . to toUpdate . to Right)) v >>= sendUpdates "Continue to Cost Calculation" (MonadicFold $ to $ buttonUpdate "Continue") >>= sendUpdates "Continue to Recipients of Service" (MonadicFold $ to $ buttonUpdate "Save & Continue") >>= sendUpdates "Continue to Line Item Summary" (MonadicFold $ to $ buttonUpdate "Continue")
limaner2002/EPC-tools
USACScripts/src/Scripts/FCCForm471.hs
bsd-3-clause
39,977
0
29
11,904
7,982
3,922
4,060
-1
-1
module Language.Promela.Tokens where data Token = Key KeyWord | Identifier String | Uname String | Number Integer | Bracket BracketType Bool | Comma | Semicolon | Plus | Dot | Equals | DoubleColon | EOF deriving Show data KeyWord = KeyActive | KeyBit | KeyBool | KeyByte | KeyChan | KeyDo | KeyFi | KeyHidden | KeyIf | KeyInit | KeyInt | KeyMType | KeyNever | KeyOd | KeyOf | KeyPriority | KeyProctype | KeyProvided | KeyShort | KeyShow | KeyTrace | KeyTypedef | KeyUnless deriving Show data BracketType = Parentheses | Square | Curly deriving Show
hguenther/language-promela
Language/Promela/Tokens.hs
bsd-3-clause
1,034
0
6
582
154
99
55
42
0
module Fib where -- | Calculate Fibonacci number of given 'Num'. -- -- First let's set `n` to ten: -- -- >>> let n = 10 -- -- And now calculate the 10th Fibonacci number: -- -- >>> fib n -- 55 fib :: Integer -> Integer fib 0 = 0 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2)
beni55/doctest-haskell
tests/integration/testCombinedExample/Fib.hs
mit
274
0
8
68
71
42
29
5
1
import List nums = Cons 1 $ Cons 2 $ Cons 3 Nil -- Should print "1 2 3 2 4 6 3 6 9" main = print $ do x <- nums y <- nums return (x * y)
raimohanska/Monads
examples/challenges/List/CartesianProduct.hs
mit
148
0
10
50
65
31
34
6
1
{-# LANGUAGE TypeFamilies #-} module Test.Pos.Block.Logic.Event ( -- * Running events and scenarios runBlockEvent , runBlockScenario , BlockScenarioResult(..) -- * Exceptions , SnapshotMissingEx(..) , DbNotEquivalentToSnapshot(..) ) where import Universum import Control.Exception.Safe (fromException) import qualified Data.Map as Map import qualified Data.Text as T import qualified GHC.Exts as IL import Pos.Chain.Block (Blund, HeaderHash) import Pos.Chain.Genesis as Genesis (Config (..)) import Pos.Chain.Txp (TxpConfiguration) import Pos.Core.Chrono (NE, NewestFirst, OldestFirst) import Pos.Core.Exception (CardanoFatalError (..)) import Pos.Core.Slotting (EpochOrSlot (..), SlotId, getEpochOrSlot) import Pos.DB.Block (BlockLrcMode, rollbackBlocks, verifyAndApplyBlocks) import Pos.DB.Pure (DBPureDiff, MonadPureDB, dbPureDiff, dbPureDump, dbPureReset) import Pos.DB.Txp (MonadTxpLocal) import Pos.Generator.BlockEvent (BlockApplyResult (..), BlockEvent, BlockEvent' (..), BlockRollbackFailure (..), BlockRollbackResult (..), BlockScenario, BlockScenario' (..), SnapshotId, SnapshotOperation (..), beaInput, beaOutValid, berInput, berOutValid) import Pos.Util.Util (eitherToThrow, lensOf) import Test.Pos.Block.Logic.Mode (BlockTestContext, PureDBSnapshotsVar (..)) import Test.Pos.Block.Logic.Util (satisfySlotCheck) data SnapshotMissingEx = SnapshotMissingEx SnapshotId deriving (Show) instance Exception SnapshotMissingEx data DbNotEquivalentToSnapshot = DbNotEquivalentToSnapshot SnapshotId DBPureDiff deriving (Show) instance Exception DbNotEquivalentToSnapshot newtype IsExpected = IsExpected Bool data BlockEventResult = BlockEventSuccess IsExpected | BlockEventFailure IsExpected SomeException | BlockEventDbChanged DbNotEquivalentToSnapshot verifyAndApplyBlocks' :: ( BlockLrcMode BlockTestContext m , MonadTxpLocal m ) => Genesis.Config -> TxpConfiguration -> OldestFirst NE Blund -> m () verifyAndApplyBlocks' genesisConfig txpConfig blunds = do let -- We cannot simply take `getCurrentSlot` since blocks are generated in --`MonadBlockGen` which locally changes its current slot. We just take -- the last slot of all generated blocks. curSlot :: Maybe SlotId curSlot = case mapMaybe (either (const Nothing) Just . unEpochOrSlot . getEpochOrSlot . fst) . IL.toList $ blunds of [] -> Nothing ss -> Just $ maximum ss satisfySlotCheck blocks $ do _ :: (HeaderHash, NewestFirst [] Blund) <- eitherToThrow =<< verifyAndApplyBlocks genesisConfig txpConfig curSlot True blocks return () where blocks = fst <$> blunds -- | Execute a single block event. runBlockEvent :: ( BlockLrcMode BlockTestContext m , MonadTxpLocal m ) => Genesis.Config -> TxpConfiguration -> BlockEvent -> m BlockEventResult runBlockEvent genesisConfig txpConfig (BlkEvApply ev) = (onSuccess <$ verifyAndApplyBlocks' genesisConfig txpConfig (ev ^. beaInput)) `catch` (return . onFailure) where onSuccess = case ev ^. beaOutValid of BlockApplySuccess -> BlockEventSuccess (IsExpected True) BlockApplyFailure -> BlockEventSuccess (IsExpected False) onFailure (e :: SomeException) = case ev ^. beaOutValid of BlockApplySuccess -> BlockEventFailure (IsExpected False) e BlockApplyFailure -> BlockEventFailure (IsExpected True) e runBlockEvent genesisConfig _ (BlkEvRollback ev) = (onSuccess <$ rollbackBlocks genesisConfig (ev ^. berInput)) `catch` (return . onFailure) where onSuccess = case ev ^. berOutValid of BlockRollbackSuccess -> BlockEventSuccess (IsExpected True) BlockRollbackFailure _ -> BlockEventSuccess (IsExpected False) onFailure (e :: SomeException) = case ev ^. berOutValid of BlockRollbackSuccess -> BlockEventFailure (IsExpected False) e BlockRollbackFailure brf -> let isExpected = case brf of BlkRbSecurityLimitExceeded | Just cfe <- fromException e , CardanoFatalError msg <- cfe , "security risk" `T.isInfixOf` msg -> True | otherwise -> False in BlockEventFailure (IsExpected isExpected) e runBlockEvent _ _ (BlkEvSnap ev) = (onSuccess <$ runSnapshotOperation ev) `catch` (return . onFailure) where onSuccess = BlockEventSuccess (IsExpected True) onFailure = BlockEventDbChanged -- | Execute a snapshot operation. runSnapshotOperation :: MonadPureDB BlockTestContext m => SnapshotOperation -> m () runSnapshotOperation snapOp = do PureDBSnapshotsVar snapsRef <- view (lensOf @PureDBSnapshotsVar) case snapOp of SnapshotSave snapId -> do currentDbState <- dbPureDump modifyIORef snapsRef $ Map.insert snapId currentDbState SnapshotLoad snapId -> do snap <- getSnap snapsRef snapId dbPureReset snap SnapshotEq snapId -> do currentDbState <- dbPureDump snap <- getSnap snapsRef snapId whenJust (dbPureDiff snap currentDbState) $ \dbDiff -> throwM $ DbNotEquivalentToSnapshot snapId dbDiff where getSnap snapsRef snapId = do mSnap <- Map.lookup snapId <$> readIORef snapsRef maybe (throwM $ SnapshotMissingEx snapId) return mSnap data BlockScenarioResult = BlockScenarioFinishedOk | BlockScenarioUnexpectedSuccess | BlockScenarioUnexpectedFailure SomeException | BlockScenarioDbChanged DbNotEquivalentToSnapshot -- | Execute a block scenario: a sequence of block events that either ends with -- an expected failure or with a rollback to the initial state. runBlockScenario :: ( MonadPureDB ctx m , ctx ~ BlockTestContext , BlockLrcMode BlockTestContext m , MonadTxpLocal m ) => Genesis.Config -> TxpConfiguration -> BlockScenario -> m BlockScenarioResult runBlockScenario _ _ (BlockScenario []) = return BlockScenarioFinishedOk runBlockScenario genesisConfig txpConfig (BlockScenario (ev:evs)) = do runBlockEvent genesisConfig txpConfig ev >>= \case BlockEventSuccess (IsExpected isExp) -> if isExp then runBlockScenario genesisConfig txpConfig (BlockScenario evs) else return BlockScenarioUnexpectedSuccess BlockEventFailure (IsExpected isExp) e -> return $ if isExp then BlockScenarioFinishedOk else BlockScenarioUnexpectedFailure e BlockEventDbChanged d -> return $ BlockScenarioDbChanged d
input-output-hk/pos-haskell-prototype
generator/src/Test/Pos/Block/Logic/Event.hs
mit
7,271
0
21
2,070
1,572
840
732
-1
-1
module Char where ord :: Char -> Int ord = primOrd chr :: Int -> Char chr = primChr isSpace :: Char -> Bool isSpace c = i == ord ' ' || i == ord '\t' || i == ord '\n' || i == ord '\r' || i == ord '\f' || i == ord '\v' where i = ord c isUpper :: Char -> Bool isUpper c = ord c >= ord 'A' && ord c <= ord 'Z' isLower :: Char -> Bool isLower c = ord c >= ord 'a' && ord c <= ord 'z' isDigit :: Char -> Bool isDigit c = ord c >= ord '0' && ord c <= ord '9' isAlpha :: Char -> Bool isAlpha c = isUpper c || isLower c isAlphaNum :: Char -> Bool isAlphaNum c = isAlpha c || isDigit c toUpper :: Char -> Char toUpper c | isLower c = chr ( ord c - ord 'a' + ord 'A' ) | otherwise = c toLower :: Char -> Char toLower c | isUpper c = chr ( ord c - ord 'A' + ord 'a' ) | otherwise = c
roberth/uu-helium
lib/Char.hs
gpl-3.0
824
0
16
248
414
196
218
28
1
-- BasicIML V01 -- Edgar F.A. Lederer, FHNW and Uni Basel, 2015 module CheckedArithmetic ( euclidDM, euclidQR, divE, modE, ArithError(DivisionByZero, Overflow), CheckedInt(negExcla, (+!), (-!), (*!), divEexcla, modEexcla, divFexcla, modFexcla, divTexcla, modTexcla), checkIntImplementation, Int32(), Int64(), Int1024(), fromInttoInt32, fromInt32toInt, fromInt32toInt64, fromInt32toInt1024, fromInt64toInt1024, fromInt64toInt32, fromInt1024toInt32, fromInt1024toInt64, fromIntegerToInt32, fromIntegerToInt64, fromIntegerToInt1024 ) {- ( negChecked, addChecked, subChecked, multChecked, divEuclidChecked, divFloorChecked, divTruncChecked, modEuclidChecked, modFloorChecked, modTruncChecked ) -} where euclidDM, euclidQR :: Integral a => a -> a -> (a, a) -- Euclidean division defined via divMod euclidDM a b | b > 0 || r == 0 = qr | otherwise = (q+1, r-b) where qr@(q, r) = divMod a b -- Euclidean division defined via quotRem euclidQR a b | a >= 0 || r == 0 = qr | b > 0 = (q-1, r+b) | otherwise = (q+1, r-b) where qr@(q, r) = quotRem a b divE, modE :: Integral a => a -> a -> a divE a b = fst (euclidDM a b) modE a b = snd (euclidDM a b) data ArithError = DivisionByZero | Overflow deriving (Eq, Show) class (Eq a, Ord a) => UncheckedInt a where negQuest :: a -> a (+?), (-?), (*?) :: a -> a -> a divEquest, modEquest, quotQuest, remQuest, divQuest, modQuest :: a -> a -> a fromIntegerQuest :: Integer -> a class (Bounded a, UncheckedInt a) => CheckedInt a where negExcla :: a -> Either ArithError a (+!), (-!), (*!) :: a -> a -> Either ArithError a divEexcla, modEexcla :: a -> a -> Either ArithError a divFexcla, modFexcla :: a -> a -> Either ArithError a divTexcla, modTexcla :: a -> a -> Either ArithError a negExcla a | a == minBound = Left Overflow | otherwise = Right (negQuest a) a +! b | isAddOk a b = Right (a +? b) | otherwise = Left Overflow where isAddOk a b = b == fromIntegerQuest 0 || (b > fromIntegerQuest 0 && a <= (maxBound -? b)) || (b < fromIntegerQuest 0 && a >= (minBound -? b)) a -! b | isSubOk a b = Right (a -? b) | otherwise = Left Overflow where isSubOk a b = b == fromIntegerQuest 0 || (b > fromIntegerQuest 0 && a >= (minBound +? b)) || (b < fromIntegerQuest 0 && a <= (maxBound +? b)) a *! b | isMultOk a b = Right (a *? b) | otherwise = Left Overflow where isMultOk a b | a == fromIntegerQuest 0 = True | a > fromIntegerQuest 0 = if b >= fromIntegerQuest 0 then b <= quotQuest maxBound a else b >= quotQuest minBound a | otherwise = if b >= fromIntegerQuest 0 then a == fromIntegerQuest (-1) || b <= quotQuest minBound a else b >= quotQuest maxBound a divEexcla = divGenericExcla divEquest modEexcla = modGenericExcla modEquest divFexcla = divGenericExcla divQuest modFexcla = modGenericExcla modQuest divTexcla = divGenericExcla quotQuest modTexcla = modGenericExcla remQuest divGenericExcla :: CheckedInt a => (a -> a -> a) -> a -> a -> Either ArithError a divGenericExcla divConcreteQuest a b | b == fromIntegerQuest 0 = Left DivisionByZero | a == minBound && b == fromIntegerQuest (-1) = Left Overflow | otherwise = Right (a `divConcreteQuest` b) modGenericExcla :: CheckedInt a => (a -> a -> a) -> a -> a -> Either ArithError a modGenericExcla modConcreteQuest a b | b == fromIntegerQuest 0 = Left DivisionByZero | a == minBound && b == fromIntegerQuest (-1) = Right (fromIntegerQuest 0) | otherwise = Right (a `modConcreteQuest` b) checkIntImplementation :: String checkIntImplementation = if (minBound :: Int) == -(2^31) && (maxBound :: Int) == (2^31)-1 then "Int has minBound and maxBound of 32 bit two's complement." else if (minBound :: Int) == -(2^63) && (maxBound :: Int) == (2^63)-1 then "Int has minBound and maxBound of 64 bit two's complement." else "Int has minBound and maxBound of unknown kind." -- check whether Int suffices; otherwise, take Integer newtype Int32 = Int32 { val32 :: Int } deriving (Eq, Ord, Show) instance Bounded Int32 where minBound = Int32 (-(2^31)) maxBound = Int32 ((2^31)-1) -- check whether Int suffices; otherwise, take Integer newtype Int64 = Int64 { val64 :: Int } deriving (Eq, Ord, Show) instance Bounded Int64 where minBound = Int64 (-(2^63)) maxBound = Int64 ((2^63)-1) newtype Int1024 = Int1024 { val1024 :: Integer } deriving (Eq, Ord, Show) instance Bounded Int1024 where minBound = Int1024 (-(2^1023)) maxBound = Int1024 ((2^1023)-1) instance UncheckedInt Int32 where negQuest (Int32 a) = Int32 (-a) Int32 a +? Int32 b = Int32 (a + b) Int32 a -? Int32 b = Int32 (a - b) Int32 a *? Int32 b = Int32 (a * b) Int32 a `divEquest` Int32 b = Int32 (a `divE` b) Int32 a `modEquest` Int32 b = Int32 (a `modE` b) Int32 a `quotQuest` Int32 b = Int32 (a `quot` b) Int32 a `remQuest` Int32 b = Int32 (a `rem` b) Int32 a `divQuest` Int32 b = Int32 (a `div` b) Int32 a `modQuest` Int32 b = Int32 (a `mod` b) fromIntegerQuest a = Int32 (fromInteger a) instance UncheckedInt Int64 where negQuest (Int64 a) = Int64 (-a) Int64 a +? Int64 b = Int64 (a + b) Int64 a -? Int64 b = Int64 (a - b) Int64 a *? Int64 b = Int64 (a * b) Int64 a `divEquest` Int64 b = Int64 (a `divE` b) Int64 a `modEquest` Int64 b = Int64 (a `modE` b) Int64 a `quotQuest` Int64 b = Int64 (a `quot` b) Int64 a `remQuest` Int64 b = Int64 (a `rem` b) Int64 a `divQuest` Int64 b = Int64 (a `div` b) Int64 a `modQuest` Int64 b = Int64 (a `mod` b) fromIntegerQuest a = Int64 (fromInteger a) instance UncheckedInt Int1024 where negQuest (Int1024 a) = Int1024 (-a) Int1024 a +? Int1024 b = Int1024 (a + b) Int1024 a -? Int1024 b = Int1024 (a - b) Int1024 a *? Int1024 b = Int1024 (a * b) Int1024 a `divEquest` Int1024 b = Int1024 (a `divE` b) Int1024 a `modEquest` Int1024 b = Int1024 (a `modE` b) Int1024 a `quotQuest` Int1024 b = Int1024 (a `quot` b) Int1024 a `remQuest` Int1024 b = Int1024 (a `rem` b) Int1024 a `divQuest` Int1024 b = Int1024 (a `div` b) Int1024 a `modQuest` Int1024 b = Int1024 (a `mod` b) fromIntegerQuest a = Int1024 (fromInteger a) instance CheckedInt Int32 instance CheckedInt Int64 instance CheckedInt Int1024 fromInttoInt32 :: Int -> Int32 fromInttoInt32 a = (Int32 a) fromInt32toInt :: Int32 -> Int fromInt32toInt (Int32 a) = a fromInt32toInt64 :: Int32 -> Int64 fromInt32toInt64 (Int32 a) = Int64 a fromInt32toInt1024 :: Int32 -> Int1024 fromInt32toInt1024 (Int32 a) = Int1024 (toInteger a) fromInt64toInt1024 :: Int64 -> Int1024 fromInt64toInt1024 (Int64 a) = Int1024 (toInteger a) fromInt64toInt32 :: Int64 -> Either ArithError Int32 fromInt64toInt32 (Int64 a) | minBound32 <= a && a <= maxBound32 = Right (Int32 a) | otherwise = Left Overflow where minBound32 = val32 minBound maxBound32 = val32 maxBound fromInt1024toInt32 :: Int1024 -> Either ArithError Int32 fromInt1024toInt32 (Int1024 a) | minBound32 <= a && a <= maxBound32 = Right (Int32 (fromInteger a)) | otherwise = Left Overflow where minBound32 = toInteger (val32 minBound) maxBound32 = toInteger (val32 maxBound) fromInt1024toInt64 :: Int1024 -> Either ArithError Int64 fromInt1024toInt64 (Int1024 a) | minBound64 <= a && a <= maxBound64 = Right (Int64 (fromInteger a)) | otherwise = Left Overflow where minBound64 = toInteger (val64 minBound) maxBound64 = toInteger (val64 maxBound) fromIntegerToInt32 :: Integer -> Either ArithError Int32 fromIntegerToInt32 a | minBound32 <= a && a <= maxBound32 = Right (Int32 (fromInteger a)) | otherwise = Left Overflow where minBound32 = toInteger (val32 minBound) maxBound32 = toInteger (val32 maxBound) fromIntegerToInt64 :: Integer -> Either ArithError Int64 fromIntegerToInt64 a | minBound64 <= a && a <= maxBound64 = Right (Int64 (fromInteger a)) | otherwise = Left Overflow where minBound64 = toInteger (val64 minBound) maxBound64 = toInteger (val64 maxBound) fromIntegerToInt1024 :: Integer -> Either ArithError Int1024 fromIntegerToInt1024 a | minBound1024 <= a && a <= maxBound1024 = Right (Int1024 a) | otherwise = Left Overflow where minBound1024 = val1024 minBound maxBound1024 = val1024 maxBound
chrisjpn/CPIB_ILMCompiler
src/VM/CheckedArithmetic.hs
bsd-3-clause
8,598
0
16
2,066
3,383
1,731
1,652
207
3
{-# LANGUAGE OverloadedStrings #-} import Data.Monoid import Data.Foldable import Data.List import Data.Function (on) import Options.Applicative import qualified Data.Map as M import qualified Data.Set as S import qualified Data.ByteString as BS import qualified Data.Text.Lazy.IO as TL import qualified Data.Text.Lazy.Builder as TB import Data.Text.Lazy.Builder.Int import Data.Text.Lazy.Builder.RealFloat import Data.Binary import System.FilePath ((</>)) import Text.Printf import BayesStack.Models.Topic.CitationInfluence import FormatMultinom import Numeric.Log import ReadData import SerializeText data Opts = Opts { nElems :: Maybe Int , dumper :: Dumper , sweepDir :: FilePath , sweepNum :: Maybe Int } type Dumper = Opts -> NetData -> MState -> (Item -> TB.Builder) -> (Node -> TB.Builder) -> TB.Builder showB :: Show a => a -> TB.Builder showB = TB.fromString . show showTopic :: Topic -> TB.Builder showTopic (Topic n) = "Topic "<>decimal n formatProb = formatRealFloat Exponent (Just 3) . realToFrac readDumper :: String -> Maybe Dumper readDumper "phis" = Just $ \opts nd m showItem showNode -> formatMultinoms showTopic showItem (nElems opts) (stPhis m) readDumper "psis" = Just $ \opts nd m showItem showNode -> formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stPsis m) readDumper "lambdas"= Just $ \opts nd m showItem showNode -> formatMultinoms (\(Cited n)->showNode n) showB (nElems opts) (stLambdas m) readDumper "omegas" = Just $ \opts nd m showItem showNode -> formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stOmegas m) readDumper "gammas" = Just $ \opts nd m showItem showNode -> formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stGammas m) readDumper "influences" = Just $ \opts nd m showItem showNode -> let formatInfluences u = foldMap (\(Cited n,p)->"\t" <> showNode n <> "\t" <> formatProb p <> "\n") $ sortBy (flip (compare `on` snd)) $ M.assocs $ influence nd m u in foldMap (\u@(Citing u')->"\n" <> showNode u' <> "\n" <> formatInfluences u) $ M.keys $ stGammas m readDumper "edge-mixtures" = Just $ \opts nd m showItem showNode -> let showArc (Arc (Citing d) (Cited c)) = showNode d <> " -> " <> showNode c formatMixture a = let ps = sortBy (flip compare `on` snd) $ map (\t->(t, arcTopicMixture nd m a t)) $ S.toList $ dTopics nd norm = Numeric.Log.sum $ map snd ps in foldMap (\(t,p)->"\t" <> showTopic t <> "\t" <> formatProb p <> "\n") $ maybe id take (nElems opts) $ map (\(t,p)->(t, p / norm)) ps in foldMap (\a->"\n" <> showArc a <> "\n" <> formatMixture a) $ S.toList $ dArcs nd readDumper _ = Nothing opts = Opts <$> nullOption ( long "top" <> short 'n' <> value Nothing <> reader (pure . auto) <> metavar "N" <> help "Number of elements to output from each distribution" ) <*> argument readDumper ( metavar "STR" <> help "One of: phis, psis, lambdas, omegas, gammas, influences, edge-mixtures" ) <*> strOption ( long "sweeps" <> short 's' <> value "sweeps" <> metavar "DIR" <> help "The directory of sweeps to dump" ) <*> option ( long "sweep-n" <> short 'N' <> reader (pure . auto) <> value Nothing <> metavar "N" <> help "The sweep number to dump" ) readSweep :: FilePath -> IO MState readSweep = decodeFile readNetData :: FilePath -> IO NetData readNetData = decodeFile main = do args <- execParser $ info (helper <*> opts) ( fullDesc <> progDesc "Dump distributions from an citation influence model sweep" <> header "dump-ci - Dump distributions from an citation influence model sweep" ) nd <- readNetData $ sweepDir args </> "data" itemMap <- readItemMap $ sweepDir args nodeMap <- readNodeMap $ sweepDir args m <- case sweepNum args of Nothing -> readSweep =<< getLastSweep (sweepDir args) Just n -> readSweep $ sweepDir args </> printf "%05d.state" n let showItem = showB . (itemMap M.!) showNode = showB . (nodeMap M.!) TL.putStr $ TB.toLazyText $ dumper args args nd m showItem showNode
beni55/bayes-stack
network-topic-models/DumpCI.hs
bsd-3-clause
4,897
11
22
1,640
1,521
783
738
103
2
module Chap12 where import Data.List import Data.Char type Name = String type Age = Integer data Person = Person Name Age deriving (Show, Eq) data PersonInvalid = NameBlank | AgeTooLow deriving (Show, Eq) -- mkPerson :: Name -> Age -> Either PersonInvalid Person -- mkPerson name age -- | name /= "" && age >=0 = Right $ Person name age -- | name == "" = Left NameBlank -- | age < 0 = Left AgeTooLow type ValidatePerson a = Either [PersonInvalid] a ageOkay :: Age -> Either [PersonInvalid] Age ageOkay age = case age >=0 of True -> Right age False -> Left [AgeTooLow] nameOkay :: Name -> Either [PersonInvalid] Name nameOkay name = case name /= "" of True -> Right name False -> Left [NameBlank] mkPerson :: Name -> Age -> ValidatePerson Person mkPerson name age = mkPerson' (nameOkay name) (ageOkay age) mkPerson' :: ValidatePerson Name -> ValidatePerson Age -> ValidatePerson Person mkPerson' (Right name) (Right age) = Right (Person name age) mkPerson' (Left badName) (Left badAge) = Left (badName ++ badAge) mkPerson' (Left badName) _ = Left badName mkPerson' _ (Left badAge) = Left badAge notThe :: String -> Maybe String notThe "the" = Nothing notThe w = Just w replaceThe' :: [String] -> [String] replaceThe' [] = [] replaceThe' (w:ws) = case notThe w of Just w' -> [w'] ++ replaceThe' ws Nothing -> ["a"] ++ replaceThe' ws replaceThe:: String -> String replaceThe s = unwords $ replaceThe' (words s) vowelStr = "aeiou" countTheBeforeVowel' :: [String] -> Integer countTheBeforeVowel' [] = 0 countTheBeforeVowel' (w:ws) = case notThe w of Just _ -> countTheBeforeVowel' ws Nothing -> case (elem (head $ head ws) vowelStr) of True -> 1 + countTheBeforeVowel' ws False -> countTheBeforeVowel' ws countTheBeforeVowel :: String -> Integer countTheBeforeVowel s = countTheBeforeVowel' $ words s countVowels :: String -> Integer countVowels [] = 0 countVowels (l:ls) = case (elem (toLower l) vowelStr) of True -> 1 + countVowels ls False -> countVowels ls countConsonents :: String -> Integer countConsonents [] = 0 countConsonents (l:ls) = case (elem (toLower l) vowelStr) of True -> countConsonents ls False -> 1 + countConsonents ls newtype Word' = Word' String deriving (Eq, Show) isWord :: String -> Bool isWord w = case (countVowels w > countConsonents w) of True -> False False -> True mkWord :: String -> Maybe Word' mkWord w = case isWord w of True -> Just (Word' w) False -> Nothing data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 natToInteger (Succ n) = 1 + (natToInteger n) integerToNat' :: Integer -> Nat integerToNat' 0 = Zero integerToNat' n = Succ (integerToNat' (n -1)) integerToNat :: Integer -> Maybe Nat integerToNat n = Just (integerToNat' n) isJust :: Maybe a -> Bool isJust Nothing = False isJust (Just _) = True isNothing :: Maybe a -> Bool isNothing Nothing = True isNothing _ = False mayybee :: b -> (a -> b) -> Maybe a -> b mayybee init _ Nothing = init mayybee _ f (Just a) = f a fromMaybe :: a -> Maybe a -> a fromMaybe a Nothing = a fromMaybe _ (Just v) = v listToMaybe :: [a] -> Maybe a listToMaybe [] = Nothing listToMaybe [a] = Just a listToMaybe _ = Nothing catMaybes :: [Maybe a] -> [a] catMaybes [] = [] catMaybes (Nothing:xs) = catMaybes xs catMaybes ((Just x):xs) = x:(catMaybes xs) flipMaybe :: [Maybe a] -> Maybe [a] flipMaybe = foldr f (Just []) where f (Just x) (Just xs) = Just(x:xs) f _ _ = Nothing lefts' :: [Either a b] -> [a] lefts' = foldr f [] where f (Right a) y = y f (Left a) y = a:y rights' :: [Either a b] -> [b] rights' = foldr f [] where f (Right a) y = a:y f (Left a) y = y partitionEithers' :: [Either a b] -> ([a], [b]) partitionEithers' e = foldr f ([],[]) e where f (Left a) (xs, ys) = (a:xs, ys) f (Right a) (xs, ys) = (xs, a:ys) either' :: (a -> c) -> (b -> c) -> Either a b -> c either' f1 _ (Left a) = f1 a either' _ f2 (Right b) = f2 b eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c eitherMaybe'' f e@(Left a) = either' (\x -> Nothing) (\x -> Just (f x)) e eitherMaybe'' f e@(Right a) = either' (\x -> Nothing) (\x -> Just (f x)) e -- take 10 $ iterate (+1) 0 myIterate :: (a -> a) -> a -> [a] myIterate f init = init:(myIterate f v) where v = f init -- take 10 $ unfoldr (\b -> Just (b, b+1)) 0 myUnfoldr :: (b -> Maybe (a, b)) -> b -> [a] myUnfoldr f init = a:(myUnfoldr f b) where (Just (a, b)) = f init betterIterate :: (a -> a) -> a -> [a] betterIterate f x = myUnfoldr (\a -> Just(a, f a)) x data BinaryTree a = Leaf | Node (BinaryTree a) a (BinaryTree a) deriving (Eq, Ord, Show) -- Leaf 0 Leaf unfold:: (a -> Maybe (a,b,a)) -> a -> BinaryTree b unfold f a = case f a of (Just (lt, x, rt)) -> Node (unfold f lt) x (unfold f rt) Nothing -> Leaf treeBuild :: Int -> BinaryTree Int treeBuild n = unfold (\b -> if b < 2^n - 1 then Just (2*b+1, b, 2*b+2) else Nothing) 0 -- treeBuild 0 -- => unfold (\b -> if b < 0 -- then Just(2*b+1, b, 2*b+2) -- else Nothing) 0 -- => Leaf -- treeBuild 1 -- => unfold (\b -> if b < 1 -- then Just(2*b+1, b, 2*b+2) -- else Nothing) 0 -- => Node( Leaf, 0 , Leaf)
punitrathore/haskell-first-principles
src/Chap12.hs
bsd-3-clause
5,375
0
13
1,328
2,311
1,199
1,112
133
3
{-# LANGUAGE OverloadedStrings #-} module TestImport ( module Yesod.Test , Specs ) where import Yesod.Test type Specs = SpecsConn ()
Tener/deeplearning-thesis
yesod/abaloney/tests/TestImport.hs
bsd-3-clause
147
0
6
34
32
20
12
6
0
{-| Cluster space sizing -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Program.Hspace (main , options , arguments ) where import Control.Monad import Data.Char (toUpper, toLower) import Data.Function (on) import qualified Data.IntMap as IntMap import Data.List import Data.Maybe (fromMaybe) import Data.Ord (comparing) import System.IO import Text.Printf (printf, hPrintf) import qualified Ganeti.HTools.AlgorithmParams as Alg import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Cluster as Cluster import qualified Ganeti.HTools.Cluster.Metrics as Metrics import qualified Ganeti.HTools.Group as Group import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Instance as Instance import Ganeti.BasicTypes import Ganeti.Common import Ganeti.HTools.AlgorithmParams (AlgorithmOptions(algCapacityIgnoreGroups)) import Ganeti.HTools.GlobalN1 (redundantGrp) import Ganeti.HTools.Types import Ganeti.HTools.CLI import Ganeti.HTools.ExtLoader import Ganeti.HTools.Loader import Ganeti.Utils -- | Options list and functions. options :: IO [OptType] options = do luxi <- oLuxiSocket return [ oPrintNodes , oDataFile , oDiskTemplate , oSpindleUse , oNodeSim , oRapiMaster , luxi , oSoR , oIAllocSrc , oVerbose , oQuiet , oIndependentGroups , oAcceptExisting , oOfflineNode , oNoCapacityChecks , oMachineReadable , oMaxCpu , oMaxSolLength , oMinDisk , oStdSpec , oTieredSpec , oSaveCluster ] -- | The list of arguments supported by the program. arguments :: [ArgCompletion] arguments = [] -- | The allocation phase we're in (initial, after tiered allocs, or -- after regular allocation). data Phase = PInitial | PFinal | PTiered -- | The kind of instance spec we print. data SpecType = SpecNormal | SpecTiered -- | Prefix for machine readable names htsPrefix :: String htsPrefix = "HTS" -- | What we prefix a spec with. specPrefix :: SpecType -> String specPrefix SpecNormal = "SPEC" specPrefix SpecTiered = "TSPEC_INI" -- | The description of a spec. specDescription :: SpecType -> String specDescription SpecNormal = "Standard (fixed-size)" specDescription SpecTiered = "Tiered (initial size)" -- | The \"name\" of a 'SpecType'. specName :: SpecType -> String specName SpecNormal = "Standard" specName SpecTiered = "Tiered" -- | Efficiency generic function. effFn :: (Cluster.CStats -> Integer) -> (Cluster.CStats -> Double) -> Cluster.CStats -> Double effFn fi ft cs = fromIntegral (fi cs) / ft cs -- | Memory efficiency. memEff :: Cluster.CStats -> Double memEff = effFn Cluster.csImem Cluster.csTmem -- | Disk efficiency. dskEff :: Cluster.CStats -> Double dskEff = effFn Cluster.csIdsk Cluster.csTdsk -- | Cpu efficiency. cpuEff :: Cluster.CStats -> Double cpuEff = effFn Cluster.csIcpu (fromIntegral . Cluster.csVcpu) -- | Spindles efficiency. spnEff :: Cluster.CStats -> Double spnEff = effFn Cluster.csIspn Cluster.csTspn -- | Holds data for converting a 'Cluster.CStats' structure into -- detailed statistics. statsData :: [(String, Cluster.CStats -> String)] statsData = [ ("SCORE", printf "%.8f" . Cluster.csScore) , ("INST_CNT", printf "%d" . Cluster.csNinst) , ("MEM_FREE", printf "%d" . Cluster.csFmem) , ("MEM_AVAIL", printf "%d" . Cluster.csAmem) , ("MEM_RESVD", \cs -> printf "%d" (Cluster.csFmem cs - Cluster.csAmem cs)) , ("MEM_INST", printf "%d" . Cluster.csImem) , ("MEM_OVERHEAD", \cs -> printf "%d" (Cluster.csXmem cs + Cluster.csNmem cs)) , ("MEM_EFF", printf "%.8f" . memEff) , ("DSK_FREE", printf "%d" . Cluster.csFdsk) , ("DSK_AVAIL", printf "%d". Cluster.csAdsk) , ("DSK_RESVD", \cs -> printf "%d" (Cluster.csFdsk cs - Cluster.csAdsk cs)) , ("DSK_INST", printf "%d" . Cluster.csIdsk) , ("DSK_EFF", printf "%.8f" . dskEff) , ("SPN_FREE", printf "%d" . Cluster.csFspn) , ("SPN_INST", printf "%d" . Cluster.csIspn) , ("SPN_EFF", printf "%.8f" . spnEff) , ("CPU_INST", printf "%d" . Cluster.csIcpu) , ("CPU_EFF", printf "%.8f" . cpuEff) , ("MNODE_MEM_AVAIL", printf "%d" . Cluster.csMmem) , ("MNODE_DSK_AVAIL", printf "%d" . Cluster.csMdsk) ] -- | List holding 'RSpec' formatting information. specData :: [(String, RSpec -> String)] specData = [ ("MEM", printf "%d" . rspecMem) , ("DSK", printf "%d" . rspecDsk) , ("CPU", printf "%d" . rspecCpu) ] -- | 'RSpec' formatting information including spindles. specDataSpn :: [(String, RSpec -> String)] specDataSpn = specData ++ [("SPN", printf "%d" . rspecSpn)] -- | List holding 'Cluster.CStats' formatting information. clusterData :: [(String, Cluster.CStats -> String)] clusterData = [ ("MEM", printf "%.0f" . Cluster.csTmem) , ("DSK", printf "%.0f" . Cluster.csTdsk) , ("CPU", printf "%.0f" . Cluster.csTcpu) , ("VCPU", printf "%d" . Cluster.csVcpu) ] -- | 'Cluster.CStats' formatting information including spindles clusterDataSpn :: [(String, Cluster.CStats -> String)] clusterDataSpn = clusterData ++ [("SPN", printf "%.0f" . Cluster.csTspn)] -- | Function to print stats for a given phase. printStats :: Phase -> Cluster.CStats -> [(String, String)] printStats ph cs = map (\(s, fn) -> (printf "%s_%s" kind s, fn cs)) statsData where kind = case ph of PInitial -> "INI" PFinal -> "FIN" PTiered -> "TRL" -- | Print failure reason and scores printFRScores :: Node.List -> Node.List -> [(FailMode, Int)] -> IO () printFRScores ini_nl fin_nl sreason = do printf " - most likely failure reason: %s\n" $ failureReason sreason::IO () printClusterScores ini_nl fin_nl printClusterEff (Cluster.totalResources fin_nl) (Node.haveExclStorage fin_nl) -- | Print final stats and related metrics. printResults :: Bool -> Node.List -> Node.List -> Int -> Int -> [(FailMode, Int)] -> IO () printResults True _ fin_nl num_instances allocs sreason = do let fin_stats = Cluster.totalResources fin_nl fin_instances = num_instances + allocs exitWhen (num_instances + allocs /= Cluster.csNinst fin_stats) $ printf "internal inconsistency, allocated (%d)\ \ != counted (%d)\n" (num_instances + allocs) (Cluster.csNinst fin_stats) main_reason <- exitIfEmpty "Internal error, no failure reasons?!" sreason printKeysHTS $ printStats PFinal fin_stats printKeysHTS [ ("ALLOC_USAGE", printf "%.8f" ((fromIntegral num_instances::Double) / fromIntegral fin_instances)) , ("ALLOC_INSTANCES", printf "%d" allocs) , ("ALLOC_FAIL_REASON", map toUpper . show . fst $ main_reason) ] printKeysHTS $ map (\(x, y) -> (printf "ALLOC_%s_CNT" (show x), printf "%d" y)) sreason printResults False ini_nl fin_nl _ allocs sreason = do putStrLn "Normal (fixed-size) allocation results:" printf " - %3d instances allocated\n" allocs :: IO () printFRScores ini_nl fin_nl sreason -- | Prints the final @OK@ marker in machine readable output. printFinalHTS :: Bool -> IO () printFinalHTS = printFinal htsPrefix {-# ANN tieredSpecMap "HLint: ignore Use alternative" #-} -- | Compute the tiered spec counts from a list of allocated -- instances. tieredSpecMap :: [Instance.Instance] -> [(RSpec, Int)] tieredSpecMap trl_ixes = let fin_trl_ixes = reverse trl_ixes ix_byspec = groupBy ((==) `on` Instance.specOf) fin_trl_ixes -- head is "safe" here, as groupBy returns list of non-empty lists spec_map = map (\ixs -> (Instance.specOf $ head ixs, length ixs)) ix_byspec in spec_map -- | Formats a spec map to strings. formatSpecMap :: [(RSpec, Int)] -> [String] formatSpecMap = map (\(spec, cnt) -> printf "%d,%d,%d,%d=%d" (rspecMem spec) (rspecDsk spec) (rspecCpu spec) (rspecSpn spec) cnt) -- | Formats \"key-metrics\" values. formatRSpec :: String -> AllocInfo -> [(String, String)] formatRSpec s r = [ ("KM_" ++ s ++ "_CPU", show $ allocInfoVCpus r) , ("KM_" ++ s ++ "_NPU", show $ allocInfoNCpus r) , ("KM_" ++ s ++ "_MEM", show $ allocInfoMem r) , ("KM_" ++ s ++ "_DSK", show $ allocInfoDisk r) , ("KM_" ++ s ++ "_SPN", show $ allocInfoSpn r) ] -- | Shows allocations stats. printAllocationStats :: Node.List -> Node.List -> IO () printAllocationStats ini_nl fin_nl = do let ini_stats = Cluster.totalResources ini_nl fin_stats = Cluster.totalResources fin_nl (rini, ralo, runa) = Cluster.computeAllocationDelta ini_stats fin_stats printKeysHTS $ formatRSpec "USED" rini printKeysHTS $ formatRSpec "POOL" ralo printKeysHTS $ formatRSpec "UNAV" runa -- | Format a list of key\/values as a shell fragment. printKeysHTS :: [(String, String)] -> IO () printKeysHTS = printKeys htsPrefix -- | Converts instance data to a list of strings. printInstance :: Node.List -> Instance.Instance -> [String] printInstance nl i = [ Instance.name i , Container.nameOf nl $ Instance.pNode i , let sdx = Instance.sNode i in if sdx == Node.noSecondary then "" else Container.nameOf nl sdx , show (Instance.mem i) , show (Instance.dsk i) , show (Instance.vcpus i) , if Node.haveExclStorage nl then case Instance.getTotalSpindles i of Nothing -> "?" Just sp -> show sp else "" ] -- | Optionally print the allocation map. printAllocationMap :: Int -> String -> Node.List -> [Instance.Instance] -> IO () printAllocationMap verbose msg nl ixes = when (verbose > 1) $ do hPutStrLn stderr (msg ++ " map") hPutStr stderr . unlines . map ((:) ' ' . unwords) $ formatTable (map (printInstance nl) (reverse ixes)) -- This is the numberic-or-not field -- specification; the first three fields are -- strings, whereas the rest are numeric [False, False, False, True, True, True, True] -- | Formats nicely a list of resources. formatResources :: a -> [(String, a->String)] -> String formatResources res = intercalate ", " . map (\(a, fn) -> a ++ " " ++ fn res) -- | Print the cluster resources. printCluster :: Bool -> Cluster.CStats -> Int -> Bool -> IO () printCluster True ini_stats node_count _ = do printKeysHTS $ map (\(a, fn) -> ("CLUSTER_" ++ a, fn ini_stats)) clusterDataSpn printKeysHTS [("CLUSTER_NODES", printf "%d" node_count)] printKeysHTS $ printStats PInitial ini_stats printCluster False ini_stats node_count print_spn = do let cldata = if print_spn then clusterDataSpn else clusterData printf "The cluster has %d nodes and the following resources:\n %s.\n" node_count (formatResources ini_stats cldata)::IO () printf "There are %s initial instances on the cluster.\n" (if inst_count > 0 then show inst_count else "no" ) where inst_count = Cluster.csNinst ini_stats -- | Prints the normal instance spec. printISpec :: Bool -> RSpec -> SpecType -> DiskTemplate -> Bool -> IO () printISpec True ispec spec disk_template _ = do printKeysHTS $ map (\(a, fn) -> (prefix ++ "_" ++ a, fn ispec)) specDataSpn printKeysHTS [ (prefix ++ "_RQN", printf "%d" req_nodes) ] printKeysHTS [ (prefix ++ "_DISK_TEMPLATE", diskTemplateToRaw disk_template) ] where req_nodes = Instance.requiredNodes disk_template prefix = specPrefix spec printISpec False ispec spec disk_template print_spn = let spdata = if print_spn then specDataSpn else specData in printf "%s instance spec is:\n %s, using disk\ \ template '%s'.\n" (specDescription spec) (formatResources ispec spdata) (diskTemplateToRaw disk_template) -- | Prints the tiered results. printTiered :: Bool -> [(RSpec, Int)] -> Node.List -> Node.List -> [(FailMode, Int)] -> IO () printTiered True spec_map nl trl_nl _ = do printKeysHTS $ printStats PTiered (Cluster.totalResources trl_nl) printKeysHTS [("TSPEC", unwords (formatSpecMap spec_map))] printAllocationStats nl trl_nl printTiered False spec_map ini_nl fin_nl sreason = do _ <- printf "Tiered allocation results:\n" let spdata = if Node.haveExclStorage ini_nl then specDataSpn else specData if null spec_map then putStrLn " - no instances allocated" else mapM_ (\(ispec, cnt) -> printf " - %3d instances of spec %s\n" cnt (formatResources ispec spdata)) spec_map printFRScores ini_nl fin_nl sreason -- | Displays the initial/final cluster scores. printClusterScores :: Node.List -> Node.List -> IO () printClusterScores ini_nl fin_nl = do printf " - initial cluster score: %.8f\n" $ Metrics.compCV ini_nl::IO () printf " - final cluster score: %.8f\n" $ Metrics.compCV fin_nl -- | Displays the cluster efficiency. printClusterEff :: Cluster.CStats -> Bool -> IO () printClusterEff cs print_spn = do let format = [("memory", memEff), ("disk", dskEff), ("vcpu", cpuEff)] ++ [("spindles", spnEff) | print_spn] len = maximum $ map (length . fst) format mapM_ (\(s, fn) -> printf " - %*s usage efficiency: %5.2f%%\n" len s (fn cs * 100)) format -- | Computes the most likely failure reason. failureReason :: [(FailMode, Int)] -> String failureReason = show . fst . head -- | Sorts the failure reasons. sortReasons :: [(FailMode, Int)] -> [(FailMode, Int)] sortReasons = sortBy (flip $ comparing snd) -- | Runs an allocation algorithm and saves cluster state. runAllocation :: ClusterData -- ^ Cluster data -> Maybe Cluster.AllocResult -- ^ Optional stop-allocation -> Result Cluster.AllocResult -- ^ Allocation result -> RSpec -- ^ Requested instance spec -> DiskTemplate -- ^ Requested disk template -> SpecType -- ^ Allocation type -> Options -- ^ CLI options -> IO (FailStats, Node.List, Int, [(RSpec, Int)]) runAllocation cdata stop_allocation actual_result spec dt mode opts = do (reasons, new_nl, new_il, new_ixes, _) <- case stop_allocation of Just result_noalloc -> return result_noalloc Nothing -> exitIfBad "failure during allocation" actual_result let name = specName mode descr = name ++ " allocation" ldescr = "after " ++ map toLower descr excstor = Node.haveExclStorage new_nl printISpec (optMachineReadable opts) spec mode dt excstor printAllocationMap (optVerbose opts) descr new_nl new_ixes maybePrintNodes (optShowNodes opts) descr (Cluster.printNodes new_nl) maybeSaveData (optSaveCluster opts) (map toLower name) ldescr (cdata { cdNodes = new_nl, cdInstances = new_il}) return (sortReasons reasons, new_nl, length new_ixes, tieredSpecMap new_ixes) -- | Create an instance from a given spec. -- For values not implied by the resorce specification (like distribution of -- of the disk space to individual disks), sensible defaults are guessed (e.g., -- having a single disk). instFromSpec :: RSpec -> DiskTemplate -> Int -> Instance.Instance instFromSpec spx dt su = Instance.create "new" (rspecMem spx) (rspecDsk spx) [Instance.Disk (rspecDsk spx) (Just $ rspecSpn spx)] (rspecCpu spx) Running [] True (-1) (-1) dt su [] False combineTiered :: AlgorithmOptions -> Maybe Int -> Cluster.AllocNodes -> Cluster.AllocResult -> Instance.Instance -> Result Cluster.AllocResult combineTiered algOpts limit allocnodes result inst = do let (_, nl, il, ixes, cstats) = result ixes_cnt = length ixes (stop, newlimit) = case limit of Nothing -> (False, Nothing) Just n -> (n <= ixes_cnt, Just (n - ixes_cnt)) if stop then return result else Cluster.tieredAlloc algOpts nl il newlimit inst allocnodes ixes cstats -- | Main function. main :: Options -> [String] -> IO () main opts args = do exitUnless (null args) "This program doesn't take any arguments." let verbose = optVerbose opts machine_r = optMachineReadable opts independent_grps = optIndependentGroups opts accept_existing = optAcceptExisting opts algOpts = Alg.fromCLIOptions opts orig_cdata@(ClusterData gl fixed_nl il _ ipol) <- loadExternalData opts nl <- setNodeStatus opts fixed_nl cluster_disk_template <- case iPolicyDiskTemplates ipol of first_templ:_ -> return first_templ _ -> exitErr "null list of disk templates received from cluster" let num_instances = Container.size il all_nodes = Container.elems fixed_nl cdata = orig_cdata { cdNodes = fixed_nl } disk_template = fromMaybe cluster_disk_template (optDiskTemplate opts) req_nodes = Instance.requiredNodes disk_template csf = commonSuffix fixed_nl il su = fromMaybe (iSpecSpindleUse $ iPolicyStdSpec ipol) (optSpindleUse opts) when (not (null csf) && verbose > 1) $ hPrintf stderr "Note: Stripping common suffix of '%s' from names\n" csf maybePrintNodes (optShowNodes opts) "Initial cluster" (Cluster.printNodes nl) when (verbose > 2) $ hPrintf stderr "Initial coefficients: overall %.8f\n%s" (Metrics.compCV nl) (Metrics.printStats " " nl) printCluster machine_r (Cluster.totalResources nl) (length all_nodes) (Node.haveExclStorage nl) let (bad_nodes, _) = Cluster.computeBadItems nl il bad_grp_idxs = filter (not . redundantGrp algOpts nl il) $ Container.keys gl when ((verbose > 3) && (not . null $ bad_nodes)) . hPrintf stderr "Bad nodes: %s\n" . show . map Node.name $ bad_nodes when ((verbose > 3) && not (null bad_grp_idxs)) . hPrintf stderr "Bad groups: %s\n" . show $ map (Group.name . flip Container.find gl) bad_grp_idxs let markGrpsUnalloc = foldl (flip $ IntMap.adjust Group.setUnallocable) gl' = if accept_existing then gl else markGrpsUnalloc gl $ map Node.group bad_nodes (gl'', algOpts') = if independent_grps then ( markGrpsUnalloc gl' bad_grp_idxs , algOpts { algCapacityIgnoreGroups = bad_grp_idxs } ) else (gl', algOpts) grps_remaining = any Group.isAllocable $ IntMap.elems gl'' stop_allocation = case () of _ | accept_existing-> Nothing _ | independent_grps && grps_remaining -> Nothing _ | null bad_nodes -> Nothing _ -> Just ([(FailN1, 1)]::FailStats, nl, il, [], []) alloclimit = if optMaxLength opts == -1 then Nothing else Just (optMaxLength opts) allocnodes <- exitIfBad "failure during allocation" $ Cluster.genAllocNodes algOpts' gl'' nl req_nodes True when (verbose > 3) . hPrintf stderr "Allocatable nodes: %s\n" $ show allocnodes -- Run the tiered allocation let minmaxes = iPolicyMinMaxISpecs ipol tspecs = case optTieredSpec opts of Nothing -> map (rspecFromISpec . minMaxISpecsMaxSpec) minmaxes Just t -> [t] tinsts = map (\ts -> instFromSpec ts disk_template su) tspecs tspec <- case tspecs of [] -> exitErr "Empty list of specs received from the cluster" t:_ -> return t (treason, trl_nl, _, spec_map) <- runAllocation cdata stop_allocation (foldM (combineTiered algOpts' alloclimit allocnodes) ([], nl, il, [], []) tinsts ) tspec disk_template SpecTiered opts printTiered machine_r spec_map nl trl_nl treason -- Run the standard (avg-mode) allocation let ispec = fromMaybe (rspecFromISpec (iPolicyStdSpec ipol)) (optStdSpec opts) (sreason, fin_nl, allocs, _) <- runAllocation cdata stop_allocation (Cluster.iterateAlloc algOpts' nl il alloclimit (instFromSpec ispec disk_template su) allocnodes [] []) ispec disk_template SpecNormal opts printResults machine_r nl fin_nl num_instances allocs sreason -- Print final result printFinalHTS machine_r
andir/ganeti
src/Ganeti/HTools/Program/Hspace.hs
bsd-2-clause
22,378
0
16
5,735
5,576
2,945
2,631
400
10
module Trit (Trit, rationalToTrit, getIntegral, getFraction, getFraction', neg, addTrits, subTrits, shiftLeft, shiftRight, multiply ) where import Stream import Utilities import Data.Ratio type Mantissa = Stream type Fraction = Stream type Trit = (Mantissa, Fraction) -- Convert from a Rational number to its Trit representation (Integral, Fraction) rationalToTrit :: Rational -> Trit rationalToTrit x |x<1 = ([0], rationalToStream x) |otherwise = (u', rationalToStream v) where u = n `div` d u' = toBinary u v = x - (toRational u) n = numerator x d = denominator x -- Get the integral part of Trit getIntegral :: Trit -> Mantissa getIntegral = fst -- Get the fraction part of Trit, with n digit of the stream getFraction :: Int -> Trit -> Stream getFraction n = take n. snd -- Get the fraction part of Trit getFraction' :: Trit -> Stream getFraction' = snd -- Negate a Trit neg :: Trit -> Trit neg (a, b) = (negate' a, negate' b) -- Add two Trits addTrits :: Trit -> Trit -> Trit addTrits (m1, (x1:x2:xs)) (m2, (y1:y2:ys)) = (u,addStream (x1:x2:xs) (y1:y2:ys)) where u' = addFiniteStream m1 m2 c = [carry x1 x2 y1 y2] u = addFiniteStream u' c -- Subtraction of 2 Trits subTrits :: Trit -> Trit -> Trit subTrits x y = addTrits x (neg y) -- Shift left = *2 operation with Trit shiftLeft :: Trit -> Trit shiftLeft (x, (y:ys)) = (x++ [y], ys) -- Shift right = /2 operation with Trit shiftRight :: Trit -> Integer -> Trit shiftRight (x, xs) 1 = (init x, (u:xs)) where u = last x shiftRight (x, xs) n = shiftRight (init x, (u:xs)) (n-1) where u = last x -- Multiply a Trit stream by 1,0 or -1, simply return the stream mulOneDigit :: Integer -> Stream -> Stream mulOneDigit x xs |x==1 = xs |x==0 = zero' |otherwise = negate' xs where zero' = (0:zero') -- Multiplication of two streams multiply :: Stream -> Stream -> Stream multiply (a0:a1:x) (b0:b1:y) = average p q where p = average (a1*b0: (average (mulOneDigit b1 x) (mulOneDigit a1 y))) (average (mulOneDigit b0 x) (mulOneDigit a0 y)) q = (a0*b0:a0*b1:a1*b1:(multiply x y)) start0 = take 30 (multiply (rationalToStream (1%2)) zo) zo :: Stream zo = 1:(-1):zero where zero = 0:zero start1 = take 30 (average (rationalToStream (1%2)) (negate' (rationalToStream (1%4))))
sdiehl/ghc
testsuite/tests/concurrent/prog001/Trit.hs
bsd-3-clause
2,950
0
13
1,122
948
516
432
57
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GLU.Matrix -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- This module corresponds to chapter 4 (Matrix Manipulation) of the GLU specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GLU.Matrix ( ortho2D, perspective, lookAt, pickMatrix, project, unProject, unProject4 ) where import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import Graphics.Rendering.GLU.Raw import Graphics.Rendering.OpenGL.GL.CoordTrans import Graphics.Rendering.OpenGL.GL.GLboolean import Graphics.Rendering.OpenGL.GL.Tensor import Graphics.Rendering.OpenGL.GLU.ErrorsInternal import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- -- matrix setup ortho2D :: GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO () ortho2D = gluOrtho2D perspective :: GLdouble -> GLdouble -> GLdouble -> GLdouble -> IO () perspective = gluPerspective lookAt :: Vertex3 GLdouble -> Vertex3 GLdouble -> Vector3 GLdouble -> IO () lookAt (Vertex3 eyeX eyeY eyeZ) (Vertex3 centerX centerY centerZ) (Vector3 upX upY upZ) = gluLookAt eyeX eyeY eyeZ centerX centerY centerZ upX upY upZ pickMatrix :: (GLdouble, GLdouble) -> (GLdouble, GLdouble) -> (Position, Size) -> IO () pickMatrix (x, y) (w, h) viewPort = withViewport viewPort $ gluPickMatrix x y w h -------------------------------------------------------------------------------- -- coordinate projection project :: Matrix m => Vertex3 GLdouble -> m GLdouble -> m GLdouble -> (Position, Size) -> IO (Vertex3 GLdouble) project (Vertex3 objX objY objZ) model proj viewPort = withColumnMajor model $ \modelBuf -> withColumnMajor proj $ \projBuf -> withViewport viewPort $ \viewBuf -> getVertex3 $ gluProject objX objY objZ modelBuf projBuf viewBuf unProject :: Matrix m => Vertex3 GLdouble -> m GLdouble -> m GLdouble -> (Position, Size) -> IO (Vertex3 GLdouble) unProject (Vertex3 objX objY objZ) model proj viewPort = withColumnMajor model $ \modelBuf -> withColumnMajor proj $ \projBuf -> withViewport viewPort $ \viewBuf -> getVertex3 $ gluUnProject objX objY objZ modelBuf projBuf viewBuf unProject4 :: Matrix m => Vertex4 GLdouble -> m GLdouble -> m GLdouble -> (Position, Size) -> GLclampd -> GLclampd -> IO (Vertex4 GLdouble) unProject4 (Vertex4 objX objY objZ clipW) model proj viewPort near far = withColumnMajor model $ \modelBuf -> withColumnMajor proj $ \projBuf -> withViewport viewPort $ \viewBuf -> getVertex4 $ gluUnProject4 objX objY objZ clipW modelBuf projBuf viewBuf near far -------------------------------------------------------------------------------- withViewport :: (Position, Size) -> (Ptr GLint -> IO a ) -> IO a withViewport (Position x y, Size w h) = withArray [ x, y, fromIntegral w, fromIntegral h ] withColumnMajor :: (Matrix m, MatrixComponent c) => m c -> (Ptr c -> IO b) -> IO b withColumnMajor mat act = withMatrix mat juggle where juggle ColumnMajor p = act p juggle RowMajor p = do transposedElems <- mapM (peekElemOff p) [ 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 ] withArray transposedElems act getVertex3 :: (Ptr GLdouble -> Ptr GLdouble -> Ptr GLdouble -> IO GLint) -> IO (Vertex3 GLdouble) getVertex3 act = alloca $ \xBuf -> alloca $ \yBuf -> alloca $ \zBuf -> do ok <- act xBuf yBuf zBuf if unmarshalGLboolean ok then do x <- peek xBuf y <- peek yBuf z <- peek zBuf return $ Vertex3 x y z else do recordInvalidValue return $ Vertex3 0 0 0 getVertex4 :: (Ptr GLdouble -> Ptr GLdouble -> Ptr GLdouble -> Ptr GLdouble -> IO GLint) -> IO (Vertex4 GLdouble) getVertex4 act = alloca $ \xBuf -> alloca $ \yBuf -> alloca $ \zBuf -> alloca $ \wBuf -> do ok <- act xBuf yBuf zBuf wBuf if unmarshalGLboolean ok then do x <- peek xBuf y <- peek yBuf z <- peek zBuf w <- peek wBuf return $ Vertex4 x y z w else do recordInvalidValue return $ Vertex4 0 0 0 0
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GLU/Matrix.hs
bsd-3-clause
4,696
0
19
1,173
1,370
704
666
99
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="ja-JP"> <title>OpenAPI Support Add-on</title> <maps> <homeID>openapi</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/openapi/src/main/javahelp/org/zaproxy/zap/extension/openapi/resources/help_ja_JP/helpset_ja_JP.hs
apache-2.0
971
77
67
157
413
209
204
-1
-1
import Test.Cabal.Prelude main = cabalTest $ do workdir <- fmap testWorkDir getTestEnv let conf = workdir </> "cabal-config" cabalG ["--config-file", conf] "user-config" ["init"] shouldExist conf fails $ cabalG ["--config-file", workdir </> "cabal-config"] "user-config" ["init"] cabalG ["--config-file", conf] "user-config" ["-f", "init"] shouldExist conf let conf2 = workdir </> "cabal-config2" withEnv [("CABAL_CONFIG", Just conf2)] $ do cabal "user-config" ["init"] shouldExist conf2
themoritz/cabal
cabal-testsuite/PackageTests/UserConfig/cabal.test.hs
bsd-3-clause
540
0
12
111
173
84
89
13
1
{-# LANGUAGE TemplateHaskell #-} {-| Lenses for OpCodes -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.OpCodes.Lens where import Ganeti.Lens (makeCustomLenses) import Ganeti.OpCodes $(makeCustomLenses ''MetaOpCode) $(makeCustomLenses ''CommonOpParams)
leshchevds/ganeti
src/Ganeti/OpCodes/Lens.hs
bsd-2-clause
1,526
0
8
229
49
27
22
6
0
-- | Take/drop tools. module Data.Conduit.List.TakeDrop where takeWhile :: Monad m => (a -> Bool) -> Conduit a m a takeWhile p = do m <- await case m of Nothing -> return () Just x | p x -> do yield x takeWhile p | otherwise -> return () dropWhile :: Monad m => (a -> Bool) -> Conduit a m a dropWhile p = do m <- await case m of Nothing -> return () Just x | p x -> dropWhile p | otherwise -> awaitForever yield
josefs/hl
src/Data/Conduit/TakeDrop.hs
bsd-3-clause
512
0
13
190
212
97
115
16
2
{-# LANGUAGE RankNTypes #-} module Main where import Parallel import qualified Memo import qualified Data.Map.Lazy as M import Control.DeepSeq import Control.Monad.ST import Data.STRef fight :: Int -> Int -> [Int] fight i a = map fst $ fightVanillaM i a fightVanillaM :: Int -> Int -> [(Int, Int)] fightVanillaM = Memo.memo2 Memo.bits Memo.bits fightVanilla fightVanilla :: Int -> Int -> [(Int, Int)] fightVanilla php ohp | php <= 0 || ohp <= 0 = [(max 0 php, max 0 ohp)] | otherwise = regroup $ do (odmg, pdmg) <- [(9,3),(10,2),(11,2),(12,2),(14,1),(16,1),(18,0),(100,0),(100,0),(100,0)] fightVanillaM (php - pdmg) (ohp - odmg) update :: Int -> Int -> [(Int, Int)] update i outcome = (,) outcome <$> fight i outcome memoState :: Memo.Memo (Int, Int) memoState = Memo.pair Memo.bits Memo.bits fibFight :: Int -> [Int] fibFight 0 = [] fibFight 1 = [] fibFight x = [(x - 1), (x - 2)] ----------------------------------------------------------------------------------- regroup :: (NFData a, Show a, Eq a, Ord a) => [(a, Int)] -> [(a, Int)] regroup xs = let xs' = M.toList $ M.fromListWith (+) xs s' = addTheNumbers (map (\(_,x) -> x) xs) -- sum (map snd xs') s = sum (map snd xs) in if s' /= s then if show s' == show s then error "WAT????" else error $ "Those are expected to be equal" ++ show (s', s) else xs' ---------------------------------------------------------------------------------- addTheNumbers :: [Int] -> Int addTheNumbers xs0 = runST $ do y <- newSTRef 0 let go [] = readSTRef y go (x : xs) = do modifySTRef y (+x) go xs go xs0 main :: IO () main = rnf (go (80, 250)) `seq` return () where go = memoState (rnf . parMap rdeepseq (map go) . step) step (cid, hp) = map (update hp) (fibFight cid)
ezyang/ghc
testsuite/tests/concurrent/T13615/T13615.hs
bsd-3-clause
1,865
0
14
451
842
460
382
48
3
{-# LANGUAGE TypeFamilies, DeriveFunctor #-} module T5686 where data U a = U (G a) deriving Functor class A a where type G a
urbanslug/ghc
testsuite/tests/deriving/should_fail/T5686.hs
bsd-3-clause
130
0
8
29
37
22
15
5
0
{-# LANGUAGE PartialTypeSignatures #-} module WildcardInDeriving where data Foo a = Foo a deriving (_)
urbanslug/ghc
testsuite/tests/partial-sigs/should_fail/WildcardInDeriving.hs
bsd-3-clause
115
0
6
27
22
14
8
-1
-1
module Main where data Hash = Hash{ (#) :: Int } deriving (Show, Read) main = do print s print (read s :: Hash) where s = show (Hash 3)
siddhanathan/ghc
testsuite/tests/deriving/should_run/drvrun004.hs
bsd-3-clause
149
3
9
43
76
40
36
7
1
digits :: Int -> [Int] digits 0 = [] digits x = (x `mod` 10):(digits (x `div` 10)) answer = sum $ filter (\x -> x == (sum $ map (^5) (digits x))) [2..999999] main = do putStrLn (show answer)
tamasgal/haskell_exercises
ProjectEuler/p030.hs
mit
193
0
14
42
129
70
59
5
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} -- | The Unison language typechecker, based on: -- "Complete and Easy Bidirectional Typechecking for Higher-Rank Polymorphism", -- by Dunfield and Krishnaswami -- -- PDF at: https://www.mpi-sws.org/~neelk/bidir.pdf module Unison.Typechecker.Context1 where -- import Unison.Term (Term) -- trace (msg ++ ":\n" ++ show (Var.shortName a, Var.shortName b, Var.shortName c)) t --watchVar msg a = trace (msg ++ ": " ++ Text.unpack (Var.shortName a)) a --watchVars msg t@(a,b,c) = import Control.Monad import Control.Monad.Loops (anyM, allM) import Control.Monad.State import qualified Data.Foldable as Foldable import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import Debug.Trace import qualified Unison.ABT as ABT import Unison.DataDeclaration (DataDeclaration) import qualified Unison.DataDeclaration as DataDeclaration import Unison.Note (Note,Noted(..)) import qualified Unison.Note as Note import Unison.Pattern (Pattern) import qualified Unison.Pattern as Pattern import Unison.Reference (Reference) import qualified Unison.Term as Term import qualified Unison.Type as Type import Unison.TypeVar (TypeVar) import qualified Unison.TypeVar as TypeVar import Unison.Typechecker.Components (minimize') import Unison.Var (Var) import qualified Unison.Var as Var -- uncomment for debugging watch :: Show a => String -> a -> a watch msg a = let !r = trace (msg ++ ": " ++ show a) a in r -- | We deal with type variables annotated with whether they are universal or existential type Type v = Type.Type (TypeVar v) type Term v = Term.Term' (TypeVar v) v type Monotype v = Type.Monotype (TypeVar v) () pattern Universal v <- Var (TypeVar.Universal v) where Universal v = Var (TypeVar.Universal v) pattern Existential v <- Var (TypeVar.Existential v) where Existential v = Var (TypeVar.Existential v) -- | Elements of an ordered algorithmic context data Element v = Var (TypeVar v) -- A variable declaration | Solved v (Monotype v) -- `v` is solved to some monotype | Ann v (Type v) -- `v` has type `a`, which may be quantified | Marker v deriving (Eq) -- used for scoping instance Var v => Show (Element v) where show (Var v) = case v of TypeVar.Universal x -> "@" <> show x TypeVar.Existential x -> "'" ++ show x show (Solved v t) = "'"++Text.unpack (Var.shortName v)++" = "++show t show (Ann v t) = Text.unpack (Var.shortName v) ++ " : " ++ show t show (Marker v) = "|"++Text.unpack (Var.shortName v)++"|" (===) :: Eq v => Element v -> Element v -> Bool Existential v === Existential v2 | v == v2 = True Universal v === Universal v2 | v == v2 = True Marker v === Marker v2 | v == v2 = True _ === _ = False {- An ordered algorithmic context, stored as a snoc list of elements (the first element of the list represents the last element of the context). The `Info` value stored along with each element is a summary of all values up to and including that element of the context. With this representation, any suffix of the `Context` element list is also a valid context, and a fresh name can be obtained just by inspecting the first `Info` in the list. -} newtype Context v = Context [(Element v, Info v)] data Info v = Info { existentialVars :: Set v -- set of existentials seen so far , universalVars :: Set v -- set of universals seen so far , allVars :: Set v -- all variables seen so far , isWellformed :: Bool -- whether the context so far is well-formed } -- | The empty context context0 :: Context v context0 = Context [] env0 :: Env v env0 = Env 0 context0 instance Var v => Show (Context v) where show (Context es) = "Γ\n " ++ (intercalate "\n " . map (show . fst)) (reverse es) debugEnabled :: Bool debugEnabled = False logContext :: Var v => String -> M v () logContext msg = when debugEnabled $ do ctx <- getContext let !_ = trace ("\n"++msg ++ ": " ++ show ctx) () setContext ctx -- ctxOK :: Context -> Context -- ctxOK ctx = if wellformed ctx then ctx else error $ "not ok: " ++ show ctx usedVars :: Context v -> Set v usedVars = allVars . info -- | Return the `Info` associated with the last element of the context, or the zero `Info`. info :: Context v -> Info v info (Context []) = Info Set.empty Set.empty Set.empty True info (Context ((_,i):_)) = i -- | Add an element onto the end of this `Context`. Takes `O(log N)` time, -- including updates to the accumulated `Info` value. extend :: Var v => Element v -> Context v -> Context v extend e c@(Context ctx) = Context ((e,i'):ctx) where i' = addInfo e (info c) -- see figure 7 addInfo e (Info es us vs ok) = case e of Var v -> case v of -- UvarCtx - ensure no duplicates TypeVar.Universal v -> Info es (Set.insert v us) (Set.insert v vs) (ok && Set.notMember v us) -- EvarCtx - ensure no duplicates, and that this existential is not solved earlier in context TypeVar.Existential v -> Info (Set.insert v es) us (Set.insert v vs) (ok && Set.notMember v es) -- SolvedEvarCtx - ensure `v` is fresh, and the solution is well-formed wrt the context Solved v sa -> Info (Set.insert v es) us (Set.insert v vs) (ok && Set.notMember v es && wellformedType c (Type.getPolytype sa)) -- VarCtx - ensure `v` is fresh, and annotation is well-formed wrt the context Ann v t -> Info es us (Set.insert v vs) (ok && Set.notMember v vs && wellformedType c t) -- MarkerCtx - note that since a Marker is always the first mention of a variable, suffices to -- just check that `v` is not previously mentioned Marker v -> Info es us (Set.insert v vs) (ok && Set.notMember v vs) data Env v = Env { freshId :: Word, ctx :: Context v } type DataDeclarations v = Map Reference (DataDeclaration v) -- | Typechecking monad newtype M v a = M { runM :: MEnv v -> Either Note (a, Env v) } -- | The typechecking environment data MEnv v = MEnv { env :: Env v, -- The typechecking state abilities :: [Type v], -- Allowed ambient abilities dataDecls :: DataDeclarations v, -- Data declarations in scope abilityChecks :: Bool -- Whether to perform ability checks. -- It's here so we can disable it during -- effect inference. } orElse :: M v a -> M v a -> M v a orElse m1 m2 = M (\menv -> either (const $ runM m2 menv) Right $ runM m1 menv) fromMEnv :: (MEnv v -> a) -> MEnv v -> Either Note (a, Env v) fromMEnv f m = Right (f m, env m) getContext :: M v (Context v) getContext = M . fromMEnv $ ctx . env getDataDeclarations :: M v (DataDeclarations v) getDataDeclarations = M $ fromMEnv dataDecls getAbilities :: M v [Type v] getAbilities = M $ fromMEnv abilities abilityCheckEnabled :: M v Bool abilityCheckEnabled = M $ fromMEnv abilityChecks withoutAbilityCheck :: M v a -> M v a withoutAbilityCheck m = M (\menv -> runM m $ menv { abilityChecks = False }) abilityCheck' :: Var v => [Type v] -> [Type v] -> M v () abilityCheck' ambient requested = do success <- flip allM requested $ \req -> flip anyM ambient $ \amb -> (True <$ subtype amb req) `orElse` pure False when (not success) $ fail $ "Ability check failed. Requested abilities " <> show requested <> " but ambient abilities only included " <> show ambient <> "." abilityCheck :: Var v => [Type v] -> M v () abilityCheck requested = do enabled <- abilityCheckEnabled when enabled $ do ambient <- getAbilities abilityCheck' ambient requested getFromTypeEnv :: (Ord r, Show r) => String -> M v (Map r (f v ())) -> r -> M v (f v ()) getFromTypeEnv what get r = get >>= \decls -> case Map.lookup r decls of Nothing -> fail $ "unknown " ++ what ++ " reference: " ++ show r ++ " " ++ show (Map.keys decls) Just decl -> pure decl getDataDeclaration :: Reference -> M v (DataDeclaration v) getDataDeclaration = getFromTypeEnv "data type" getDataDeclarations getConstructorType :: Var v => Reference -> Int -> M v (Type v) getConstructorType = getConstructorType' getDataDeclaration getConstructorType' :: (Var v, Show r) => (r -> M v (DataDeclaration v)) -> r -> Int -> M v (Type v) getConstructorType' get r cid = do decl <- get r case drop cid (DataDeclaration.constructors decl) of [] -> fail $ "invalid constructor id: " ++ show cid ++ " in " ++ show r (_v, typ) : _ -> pure $ ABT.vmap TypeVar.Universal typ setContext :: Context v -> M v () setContext ctx = M (\menv -> let e = env menv in Right ((), e {ctx = ctx})) modifyContext :: (Context v -> M v (Context v)) -> M v () modifyContext f = do c <- getContext; c <- f c; setContext c modifyContext' :: (Context v -> Context v) -> M v () modifyContext' f = modifyContext (pure . f) appendContext :: Var v => Context v -> M v () appendContext tl = modifyContext' (\ctx -> ctx `append` tl) scope :: Var v => String -> M v a -> M v a scope msg (M m) = do ambient <- getAbilities M (\menv -> Note.scope (show ambient ++ " " ++ msg) $ m menv) freshenVar :: Var v => v -> M v v freshenVar v = M (\menv -> let e = env menv id = freshId e in Right (Var.freshenId id v, e {freshId = id+1})) freshenTypeVar :: Var v => TypeVar v -> M v v freshenTypeVar v = M (\menv -> let e = env menv id = freshId e in Right (Var.freshenId id (TypeVar.underlying v), e {freshId = id+1})) freshNamed :: Var v => Text -> M v v freshNamed = freshenVar . Var.named freshVar :: Var v => M v v freshVar = freshNamed "v" -- then have check, subtype, etc, take a Fresh (Term v), Fresh (Type v) -- | Build a context from a list of elements. context :: Var v => [Element v] -> Context v context xs = foldl' (flip extend) context0 xs -- | `append c1 c2` adds the elements of `c2` onto the end of `c1`. append :: Var v => Context v -> Context v -> Context v append ctxL (Context es) = -- since `es` is a snoc list, we add it to `ctxL` in reverse order foldl' f ctxL (reverse es) where f ctx (e,_) = extend e ctx -- | Delete from the end of this context up to and including -- the given `Element`. Returns `Left` if the element is not found. retract :: (Monad m, Var v) => Element v -> Context v -> m (Context v) retract m (Context ctx) = let maybeTail [] = fail ("unable to retract: " ++ show m) maybeTail (_:t) = pure t -- note: no need to recompute used variables; any suffix of the -- context snoc list is also a valid context in Context <$> maybeTail (dropWhile (\(e,_) -> e /= m) ctx) -- | Like `retract`, but returns the empty context if retracting would remove all elements. retract' :: Var v => Element v -> Context v -> Context v retract' e ctx = case retract e ctx of Left _ -> context [] Right ctx -> ctx universals :: Context v -> Set v universals = universalVars . info existentials :: Context v -> Set v existentials = existentialVars . info solved :: Context v -> [(v, Monotype v)] solved (Context ctx) = [(v, sa) | (Solved v sa,_) <- ctx] unsolved :: Context v -> [v] unsolved (Context ctx) = [v | (Existential v,_) <- ctx] -- | Apply the context to the input type, then convert any unsolved existentials -- to universals. generalizeExistentials :: Var v => Context v -> Type v -> Type v generalizeExistentials ctx t = foldr gen (apply ctx t) (unsolved ctx) where gen e t = if TypeVar.Existential e `ABT.isFreeIn` t then Type.forall() (TypeVar.Universal e) (ABT.subst (TypeVar.Existential e) (Type.universal e) t) else t -- don't bother introducing a forall if type variable is unused replace :: Var v => Element v -> Context v -> Context v -> Context v replace e focus ctx = let (l,r) = breakAt e ctx in l `append` focus `append` r breakAt :: Var v => Element v -> Context v -> (Context v, Context v) breakAt m (Context xs) = let (r, l) = break (\(e,_) -> e === m) xs -- l is a suffix of xs and is already a valid context; -- r needs to be rebuilt in (Context (drop 1 l), context . map fst $ reverse r) -- | ordered Γ α β = True <=> Γ[α^][β^] ordered :: Var v => Context v -> v -> v -> Bool ordered ctx v v2 = Set.member v (existentials (retract' (Existential v2) ctx)) -- | Check that the context is well formed, see Figure 7 of paper -- Since contexts are 'monotonic', we can compute an cache this efficiently -- as the context is built up, see implementation of `extend`. wellformed :: Context v -> Bool wellformed ctx = isWellformed (info ctx) -- | Check that the type is well formed wrt the given `Context`, see Figure 7 of paper wellformedType :: Var v => Context v -> Type v -> Bool wellformedType c t = wellformed c && case t of Type.Existential' v -> Set.member v (existentials c) Type.Universal' v -> Set.member v (universals c) Type.Ref' _ -> True Type.Arrow' i o -> wellformedType c i && wellformedType c o Type.Ann' t' _ -> wellformedType c t' Type.App' x y -> wellformedType c x && wellformedType c y Type.Effect' es a -> all (wellformedType c) es && wellformedType c a Type.Forall' t -> let (v,ctx2) = extendUniversal c in wellformedType ctx2 (ABT.bind t (Type.universal v)) _ -> error $ "Match failure in wellformedType: " ++ show t where -- | Extend this `Context` with a single variable, guaranteed fresh extendUniversal ctx = case Var.freshIn (usedVars ctx) (Var.named "var") of v -> (v, extend (Universal v) ctx) bindings :: Context v -> [(v, Type v)] bindings (Context ctx) = [(v,a) | (Ann v a,_) <- ctx] lookupType :: Eq v => Context v -> v -> Maybe (Type v) lookupType ctx v = lookup v (bindings ctx) -- | Replace any existentials with their solution in the context apply :: Var v => Context v -> Type v -> Type v apply ctx t = case t of Type.Universal' _ -> t Type.Ref' _ -> t Type.Existential' v -> maybe t (\(Type.Monotype t') -> apply ctx t') (lookup v (solved ctx)) Type.Arrow' i o -> Type.arrow() (apply ctx i) (apply ctx o) Type.App' x y -> Type.app() (apply ctx x) (apply ctx y) Type.Ann' v k -> Type.ann() (apply ctx v) k Type.Effect' es t -> Type.effect() (map (apply ctx) es) (apply ctx t) Type.ForallNamed' v t' -> Type.forall() v (apply ctx t') _ -> error $ "Context.apply ill formed type - " ++ show t -- | solve (ΓL,α^,ΓR) α τ = (ΓL,α^ = τ,ΓR) -- If the given existential variable exists in the context, -- we solve it to the given monotype, otherwise return `Nothing` solve :: Var v => Context v -> v -> Monotype v -> Maybe (Context v) solve ctx v t -- okay to solve something again if it's to an identical type | v `elem` (map fst (solved ctx)) = same =<< lookup v (solved ctx) where same t2 | apply ctx (Type.getPolytype t) == apply ctx (Type.getPolytype t2) = Just ctx | otherwise = Nothing solve ctx v t | wellformedType ctxL (Type.getPolytype t) = Just ctx' | otherwise = Nothing where (ctxL,ctxR) = breakAt (Existential v) ctx ctx' = ctxL `append` context [Solved v t] `append` ctxR extendUniversal :: Var v => v -> M v v extendUniversal v = do v' <- freshenVar v modifyContext (pure . extend (Universal v')) pure v' extendMarker :: Var v => v -> M v v extendMarker v = do v' <- freshenVar v modifyContext (\ctx -> pure $ ctx `append` (context [Marker v', Existential v'])) pure v' notMember :: Var v => v -> Set (TypeVar v) -> Bool notMember v s = Set.notMember (TypeVar.Universal v) s && Set.notMember (TypeVar.Existential v) s -- | `subtype ctx t1 t2` returns successfully if `t1` is a subtype of `t2`. -- This may have the effect of altering the context. subtype :: Var v => Type v -> Type v -> M v () subtype tx ty | debugEnabled && traceShow ("subtype"::String, tx, ty) False = undefined subtype tx ty = scope (show tx++" <: "++show ty) $ do ctx <- getContext; go ctx tx ty where -- Rules from figure 9 go _ (Type.Ref' r) (Type.Ref' r2) | r == r2 = pure () -- `Unit` go ctx t1@(Type.Universal' v1) t2@(Type.Universal' v2) -- `Var` | v1 == v2 && wellformedType ctx t1 && wellformedType ctx t2 = pure () go ctx t1@(Type.Existential' v1) t2@(Type.Existential' v2) -- `Exvar` | v1 == v2 && wellformedType ctx t1 && wellformedType ctx t2 = pure () go _ (Type.Arrow' i1 o1) (Type.Arrow' i2 o2) = do -- `-->` subtype i1 i2; ctx' <- getContext subtype (apply ctx' o1) (apply ctx' o2) go _ (Type.App' x1 y1) (Type.App' x2 y2) = do -- analogue of `-->` subtype x1 x2; ctx' <- getContext subtype (apply ctx' y1) (apply ctx' y2) go _ t (Type.Forall' t2) = scope "forall (R)" $ do v' <- extendUniversal =<< ABT.freshen t2 freshenTypeVar t2 <- pure $ ABT.bind t2 (Type.universal v') subtype t t2 modifyContext (retract (Universal v')) go _ (Type.Forall' t) t2 = scope "forall (L)" $ do v <- extendMarker =<< ABT.freshen t freshenTypeVar t <- pure $ ABT.bind t (Type.existential v) ctx' <- getContext subtype (apply ctx' t) t2 modifyContext (retract (Marker v)) go _ (Type.Effect' [] a1) a2 = subtype a1 a2 go _ a1 (Type.Effect' [] a2) = subtype a1 a2 go ctx (Type.Existential' v) t -- `InstantiateL` | Set.member v (existentials ctx) && notMember v (Type.freeVars t) = instantiateL v t go ctx t (Type.Existential' v) -- `InstantiateR` | Set.member v (existentials ctx) && notMember v (Type.freeVars t) = instantiateR t v go _ (Type.Effect'' es1 a1) (Type.Effect' es2 a2) = do subtype a1 a2 ctx <- getContext let es1' = map (apply ctx) es1 es2' = map (apply ctx) es2 abilityCheck' es2' es1' go _ _ _ = fail "not a subtype" -- | Instantiate the given existential such that it is -- a subtype of the given type, updating the context -- in the process. instantiateL :: Var v => v -> Type v -> M v () instantiateL v t | debugEnabled && traceShow ("instantiateL"::String, v, t) False = undefined instantiateL v t = getContext >>= \ctx -> case Type.monotype t >>= (solve ctx v) of Just ctx -> setContext ctx -- InstLSolve Nothing -> case t of Type.Existential' v2 | ordered ctx v v2 -> -- InstLReach (both are existential, set v2 = v) maybe (fail "InstLReach failed") setContext $ solve ctx v2 (Type.Monotype (Type.existential v)) Type.Arrow' i o -> do -- InstLArr [i',o'] <- traverse freshenVar [ABT.v' "i", ABT.v' "o"] let s = Solved v (Type.Monotype (Type.arrow() (Type.existential i') (Type.existential o'))) modifyContext' $ replace (Existential v) (context [Existential o', Existential i', s]) instantiateR i i' ctx <- getContext instantiateL o' (apply ctx o) Type.App' x y -> do -- analogue of InstLArr [x', y'] <- traverse freshenVar [ABT.v' "x", ABT.v' "y"] let s = Solved v (Type.Monotype (Type.app() (Type.existential x') (Type.existential y'))) modifyContext' $ replace (Existential v) (context [Existential y', Existential x', s]) ctx0 <- getContext ctx' <- instantiateL x' (apply ctx0 x) >> getContext instantiateL y' (apply ctx' y) Type.Effect' es vt -> do es' <- replicateM (length es) (freshNamed "eeee") vt' <- freshNamed "vt" let s = Solved v (Type.Monotype (Type.effect() (Type.existential <$> es') (Type.existential vt'))) modifyContext' $ replace (Existential v) (context $ (Existential <$> es') ++ [Existential vt', s]) Foldable.for_ (es' `zip` es) $ \(e',e) -> do ctx <- getContext instantiateL e' (apply ctx e) ctx <- getContext instantiateL vt' (apply ctx vt) Type.Forall' body -> do -- InstLIIL v <- extendUniversal =<< ABT.freshen body freshenTypeVar instantiateL v (ABT.bind body (Type.universal v)) modifyContext (retract (Universal v)) _ -> do let msg = "could not instantiate left: '" ++ show v ++ " <: " ++ show t logContext msg fail msg -- | Instantiate the given existential such that it is -- a supertype of the given type, updating the context -- in the process. instantiateR :: Var v => Type v -> v -> M v () instantiateR t v | debugEnabled && traceShow ("instantiateR"::String, t, v) False = undefined instantiateR t v = getContext >>= \ctx -> case Type.monotype t >>= solve ctx v of Just ctx -> setContext ctx -- InstRSolve Nothing -> case t of Type.Existential' v2 | ordered ctx v v2 -> -- InstRReach (both are existential, set v2 = v) maybe (fail "InstRReach failed") setContext $ solve ctx v2 (Type.Monotype (Type.existential v)) Type.Arrow' i o -> do -- InstRArrow [i', o'] <- traverse freshenVar [ABT.v' "i", ABT.v' "o"] let s = Solved v (Type.Monotype (Type.arrow() (Type.existential i') (Type.existential o'))) setContext (replace (Existential v) (context [Existential o', Existential i', s]) ctx) ctx <- instantiateL i' i >> getContext instantiateR (apply ctx o) o' Type.App' x y -> do -- analogue of InstRArr -- example foo a <: v' will -- 1. create foo', a', add these to the context -- 2. add v' = foo' a' to the context -- 3. recurse to refine the types of foo' and a' [x', y'] <- traverse freshenVar [ABT.v' "x", ABT.v' "y"] let s = Solved v (Type.Monotype (Type.app() (Type.existential x') (Type.existential y'))) setContext $ replace (Existential v) (context [Existential y', Existential x', s]) ctx ctx <- getContext instantiateR (apply ctx x) x' ctx <- getContext instantiateR (apply ctx y) y' Type.Effect' es vt -> do es' <- replicateM (length es) (freshNamed "e") vt' <- freshNamed "vt" let s = Solved v (Type.Monotype (Type.effect() (Type.existential <$> es') (Type.existential vt'))) modifyContext' $ replace (Existential v) (context $ (Existential <$> es') ++ [Existential vt', s]) Foldable.for_ (es `zip` es') $ \(e, e') -> do ctx <- getContext instantiateR (apply ctx e) e' ctx <- getContext instantiateR (apply ctx vt) vt' Type.Forall' body -> do -- InstRAIIL x' <- ABT.freshen body freshenTypeVar setContext $ ctx `append` context [Marker x', Existential x'] instantiateR (ABT.bind body (Type.existential x')) v modifyContext (retract (Marker x')) _ -> do logContext ("failed: instantiateR " <> show t <> " " <> show v) fail $ "could not instantiate right " ++ show t withEffects :: [Type v] -> M v a -> M v a withEffects abilities' m = M (\menv -> runM m (menv { abilities = abilities' ++ abilities menv })) withEffects0 :: [Type v] -> M v a -> M v a withEffects0 abilities' m = M (\menv -> runM m (menv { abilities = abilities' })) -- | Check that under the given context, `e` has type `t`, -- updating the context in the process. check :: Var v => Term v -> Type v -> M v () check e t | debugEnabled && traceShow ("check"::String, e, t) False = undefined check e t = getContext >>= \ctx -> if wellformedType ctx t then let go (Term.Int64' _) _ = subtype (Type.int64()) t -- 1I go (Term.UInt64' _) _ = subtype (Type.uint64()) t -- 1I go (Term.Float' _) _ = subtype (Type.float()) t -- 1I go (Term.Boolean' _) _ = subtype (Type.boolean()) t -- 1I go (Term.Text' _) _ = subtype (Type.text()) t -- 1I go Term.Blank' _ = pure () -- somewhat hacky short circuit; blank checks successfully against all types go _ (Type.Forall' body) = do -- ForallI x <- extendUniversal =<< ABT.freshen body freshenTypeVar check e (ABT.bind body (Type.universal x)) modifyContext $ retract (Universal x) go (Term.Lam' body) (Type.Arrow' i o) = do -- =>I x <- ABT.freshen body freshenVar modifyContext' (extend (Ann x i)) let Type.Effect'' es _ = o scope ("pushing effects: " ++ show es) . withEffects0 es $ check (ABT.bind body (Term.var() x)) o modifyContext (retract (Ann x i)) go (Term.Let1' binding e) t = do v <- ABT.freshen e freshenVar tbinding <- scope "let1.synthesize binding" $ synthesize binding modifyContext' (extend (Ann v tbinding)) scope "let1.checking body" $ check (ABT.bind e (Term.var() v)) t modifyContext (retract (Ann v tbinding)) go (Term.LetRecNamed' [] e) t = check e t go (Term.LetRec' letrec) t = do (marker, e) <- annotateLetRecBindings letrec check e t modifyContext (retract marker) go (Term.Handle' h body) t = do -- `h` should check against `Effect e i -> t` (for new existentials `e` and `i`) -- `body` should check against `i` [e, i] <- sequence [freshNamed "e", freshNamed "i"] appendContext $ context [Existential e, Existential i] check h $ Type.arrow() (Type.effectV() ((), Type.existential e) ((), Type.existential i)) t ctx <- getContext let Type.Effect'' requested _ = apply ctx t abilityCheck requested withEffects [apply ctx $ Type.existential e] $ do ambient <- getAbilities let (_, i') = Type.stripEffect (apply ctx (Type.existential i)) check body (Type.effect() ambient i') pure () go _ _ = do -- Sub a <- synthesize e; ctx <- getContext subtype (apply ctx a) (apply ctx t) e' = minimize' e in scope ("check: " ++ show e' ++ ": " ++ show t) $ case t of -- expand existentials before checking t@(Type.Existential' _) -> go e' (apply ctx t) t -> go e' t else scope ("context: " ++ show ctx) . scope ("term: " ++ show e) . scope ("type: " ++ show t) . scope ("context well formed: " ++ show (wellformed ctx)) . scope ("type well formed wrt context: " ++ show (wellformedType ctx t)) $ fail "check failed" -- | Synthesize and generalize the type of each binding in a let rec -- and return the new context in which all bindings are annotated with -- their type. Also returns the freshened version of `body` and a marker -- which should be used to retract the context after checking/synthesis -- of `body` is complete. See usage in `synthesize` and `check` for `LetRec'` case. annotateLetRecBindings :: Var v => ((v -> M v v) -> M v ([(v, Term v)], Term v)) -> M v (Element v, Term v) annotateLetRecBindings letrec = do (bindings, body) <- letrec freshenVar let vs = map fst bindings -- generate a fresh existential variable `e1, e2 ...` for each binding es <- traverse freshenVar vs ctx <- getContext e1 <- if null vs then fail "impossible" else pure $ head es -- Introduce these existentials into the context and -- annotate each term variable w/ corresponding existential -- [marker e1, 'e1, 'e2, ... v1 : 'e1, v2 : 'e2 ...] let f e (_,binding) = case binding of -- TODO: Think about whether `apply` here is always correct -- Used to have a guard that would only do this if t had no free vars Term.Ann' _ t -> apply ctx t _ -> Type.existential e let bindingTypes = zipWith f es bindings appendContext $ context (Marker e1 : map Existential es ++ zipWith Ann vs bindingTypes) -- check each `bi` against `ei`; sequencing resulting contexts Foldable.for_ (zip bindings bindingTypes) $ \((_,b), t) -> check b t -- compute generalized types `gt1, gt2 ...` for each binding `b1, b2...`; -- add annotations `v1 : gt1, v2 : gt2 ...` to the context (ctx1, ctx2) <- breakAt (Marker e1) <$> getContext let gen e = generalizeExistentials ctx2 (Type.existential e) let annotations = zipWith Ann vs (map gen es) marker <- Marker <$> freshenVar (ABT.v' "let-rec-marker") setContext (ctx1 `append` context (marker : annotations)) pure $ (marker, body) -- | Synthesize the type of the given term, updating the context in the process. -- | Figure 11 from the paper synthesize :: Var v => Term v -> M v (Type v) synthesize e | debugEnabled && traceShow ("synthesize"::String, e) False = undefined synthesize e = scope ("synth: " ++ show e) $ go (minimize' e) where go :: Var v => Term v -> M v (Type v) go (Term.Var' v) = getContext >>= \ctx -> case lookupType ctx v of -- Var Nothing -> fail $ "type not known for term var: " ++ Text.unpack (Var.name v) Just t -> pure t go Term.Blank' = do v <- freshNamed "_" appendContext $ context [Existential v] pure $ Type.existential v -- forall (TypeVar.Universal v) (Type.universal v) go (Term.Ann' (Term.Ref' _) t) = case ABT.freeVars t of s | Set.null s -> -- innermost Ref annotation assumed to be correctly provided by `synthesizeClosed` pure t s | otherwise -> fail $ "type annotation contains free variables " ++ show (map Var.name (Set.toList s)) go (Term.Ref' h) = fail $ "unannotated reference: " ++ show h go (Term.Constructor' r cid) = do t <- getConstructorType r cid if Type.arity t == 0 then do a <- freshNamed "a" appendContext $ context [Marker a, Existential a] ambient <- getAbilities subtype t (Type.effect() ambient (Type.existential a)) -- modifyContext $ retract [Marker a] pure t else pure t -- todo: Term.Request' go (Term.Ann' e' t) = t <$ check e' t go (Term.Float' _) = pure (Type.float()) -- 1I=> go (Term.Int64' _) = pure (Type.int64()) -- 1I=> go (Term.UInt64' _) = pure (Type.uint64())-- 1I=> go (Term.Boolean' _) = pure (Type.boolean()) go (Term.Text' _) = pure (Type.text()) go (Term.App' f arg) = do -- ->E ft <- synthesize f ctx <- getContext synthesizeApp (apply ctx ft) arg go (Term.Vector' v) = synthesize (desugarVector (Foldable.toList v)) go (Term.Let1' binding e) | Set.null (ABT.freeVars binding) = do -- special case when it is definitely safe to generalize - binding contains -- no free variables, i.e. `let id x = x in ...` decls <- getDataDeclarations abilities <- getAbilities t <- scope "let1 closed" $ synthesizeClosed' abilities decls binding v' <- ABT.freshen e freshenVar e <- pure $ ABT.bind e (Term.builtin() (Var.name v') `Term.ann_` t) synthesize e --go (Term.Let1' binding e) = do -- -- literally just convert to a lambda application and call synthesize! -- -- NB: this misses out on let generalization -- -- let x = blah p q in foo y <=> (x -> foo y) (blah p q) -- v' <- ABT.freshen e freshenVar -- e <- pure $ ABT.bind e (Term.var v') -- synthesize (Term.lam v' e `Term.app` binding) go (Term.Let1' binding e) = do -- note: no need to freshen binding, it can't refer to v tbinding <- synthesize binding v' <- ABT.freshen e freshenVar appendContext (context [Ann v' tbinding]) t <- synthesize (ABT.bind e (Term.var() v')) modifyContext (retract (Ann v' tbinding)) pure t -- -- TODO: figure out why this retract sometimes generates invalid contexts, -- -- (ctx, ctx2) <- breakAt (Ann v' tbinding) <$> getContext -- -- as in (f -> let x = (let saved = f in 42) in 1) -- -- removing the retract and generalize 'works' for this example -- -- generalizeExistentials ctx2 t <$ setContext ctx go (Term.Lam' body) = do -- ->I=> (Full Damas Milner rule) [arg, i, o] <- sequence [ABT.freshen body freshenVar, freshVar, freshVar] appendContext $ context [Marker i, Existential i, Existential o, Ann arg (Type.existential i)] body <- pure $ ABT.bind body (Term.var() arg) check body (Type.existential o) (ctx1, ctx2) <- breakAt (Marker i) <$> getContext -- unsolved existentials get generalized to universals setContext ctx1 pure $ generalizeExistentials ctx2 (Type.arrow() (Type.existential i) (Type.existential o)) go (Term.LetRecNamed' [] body) = synthesize body go (Term.LetRec' letrec) = do (marker, e) <- annotateLetRecBindings letrec t <- synthesize e (ctx, ctx2) <- breakAt marker <$> getContext generalizeExistentials ctx2 t <$ setContext ctx go (Term.If' cond t f) = foldM synthesizeApp Type.iff [cond, t, f] go (Term.And' a b) = foldM synthesizeApp Type.andor [a, b] go (Term.Or' a b) = foldM synthesizeApp Type.andor [a, b] -- { 42 } go (Term.EffectPure' a) = do e <- freshenVar (Var.named "e") Type.Effect'' _ at <- synthesize a pure . Type.forall() (TypeVar.Universal e) $ Type.effectV() ((), Type.universal e) ((), at) go (Term.EffectBind' r cid args k) = do cType <- getConstructorType r cid let arity = Type.arity cType -- TODO: error message algebra when (length args /= arity) . fail $ "Effect constructor wanted " <> show arity <> " arguments " <> "but got " <> show (length args) ([eType], iType) <- Type.stripEffect <$> withoutAbilityCheck (foldM synthesizeApp cType args) rTypev <- freshNamed "result" let rType = Type.existential rTypev appendContext $ context [Existential rTypev] check k (Type.arrow() iType (Type.effect() [eType] rType)) ctx <- getContext pure $ apply ctx (Type.effectV() ((), eType) ((), rType)) go (Term.Match' scrutinee cases) = scope ("match " ++ show scrutinee) $ do scrutineeType <- synthesize scrutinee outputTypev <- freshenVar (Var.named "match-output") let outputType = Type.existential outputTypev appendContext $ context [Existential outputTypev] Foldable.traverse_ (checkCase scrutineeType outputType) cases ctx <- getContext pure $ apply ctx outputType go h@(Term.Handle' _ _) = do o <- freshNamed "o" appendContext $ context [Existential o] check h (Type.existential o) ctx <- getContext pure (apply ctx (Type.existential o)) go e = fail $ "unknown case in synthesize " ++ show e -- data MatchCase a = MatchCase Pattern (Maybe a) a {- type Optional b c = None | Some b c let blah : Optional Int64 Int64 blah = ... case blah of Some x (Some y z) | x < 10 -> x + y + z --becomes-- let x = _ y = _ z = _ pat : Optional Int64 Int64 pat = Optional.Some x (Some y z) -- from here on is rhs' guard : Boolean guard = x <_Int64 +10 x +_Int64 y -} checkCase :: Var v => Type v -> Type v -> Term.MatchCase () (Term v) -> M v () checkCase scrutineeType outputType (Term.MatchCase pat guard rhs) = -- Get the variables bound in the pattern let (vs, body) = case rhs of ABT.AbsN' vars bod -> (vars, bod) _ -> ([], rhs) -- Make up a term that involves the guard if present rhs' = case guard of Just g -> Term.let1_ [(Var.named "_", g `Term.ann_` Type.boolean())] body Nothing -> body -- Convert pattern to a Term patTerm = evalState (patternToTerm pat) vs newBody = Term.let1_ [(Var.named "_", patTerm `Term.ann_` scrutineeType)] rhs' entireCase = foldr (\v t -> Term.let1_ [(v, Term.blank())] t) newBody vs in check entireCase outputType -- Make up a fake term for the pattern, that we can typecheck patternToTerm :: Var v => Pattern -> State [v] (Term v) patternToTerm pat = case pat of Pattern.Boolean b -> pure $ Term.boolean() b Pattern.Int64 n -> pure $ Term.int64() n Pattern.UInt64 n -> pure $ Term.uint64() n Pattern.Float n -> pure $ Term.float() n -- similar for other literals Pattern.Constructor r cid pats -> do outputTerms <- traverse patternToTerm pats pure $ Term.apps (Term.constructor() r cid) (((),) <$> outputTerms) Pattern.Var -> do (h : t) <- get put t pure $ Term.var() h Pattern.Unbound -> pure $ Term.blank() Pattern.As p -> do (h : t) <- get put t tm <- patternToTerm p pure . Term.let1_ [(h, tm)] $ Term.var() h Pattern.EffectPure p -> Term.effectPure() <$> patternToTerm p Pattern.EffectBind r cid pats kpat -> do outputTerms <- traverse patternToTerm pats kTerm <- patternToTerm kpat pure $ Term.effectBind() r cid outputTerms kTerm _ -> error "todo: delete me after deleting PatternP - patternToTerm match failure" -- | Synthesize the type of the given term, `arg` given that a function of -- the given type `ft` is being applied to `arg`. Update the context in -- the process. -- e.g. in `(f:t) x` -- finds the type of (f x) given t and x. synthesizeApp :: Var v => Type v -> Term v -> M v (Type v) synthesizeApp ft arg | debugEnabled && traceShow ("synthesizeApp"::String, ft, arg) False = undefined synthesizeApp ft arg = scope ("synthesizeApp: " ++ show ft ++ ", " ++ show arg) $ go ft where go (Type.Forall' body) = do -- Forall1App v <- ABT.freshen body freshenTypeVar appendContext (context [Existential v]) synthesizeApp (ABT.bind body (Type.existential v)) arg go (Type.Arrow' i o) = do -- ->App let (es, _) = Type.stripEffect o abilityCheck es ambientEs <- getAbilities o <$ check arg (Type.effect() ambientEs i) go (Type.Existential' a) = do -- a^App [i,o] <- traverse freshenVar [ABT.v' "i", ABT.v' "o"] let soln = Type.Monotype (Type.arrow() (Type.existential i) (Type.existential o)) let ctxMid = context [Existential o, Existential i, Solved a soln] modifyContext' $ replace (Existential a) ctxMid scope "a^App" $ (Type.existential o <$ check arg (Type.existential i)) go _ = scope "unable to synthesize type of application" $ scope ("function type: " ++ show ft) $ fail ("arg: " ++ show arg) -- | For purposes of typechecking, we translate `[x,y,z]` to the term -- `Vector.prepend x (Vector.prepend y (Vector.prepend z Vector.empty))`, -- where `Vector.prepend : forall a. a -> Vector a -> a` and -- `Vector.empty : forall a. Vector a` -- todo: easiest to desugar as a variadic function forall a . a -> a -> a -> a -> Vector a -- of the appropriate arity -- also rename Vector -> Sequence desugarVector :: Var v => [Term v] -> Term v desugarVector ts = case ts of [] -> Term.ann() (Term.builtin() "Vector.empty") (Type.forall'() ["a"] va) hd : tl -> (Term.builtin() "Vector.prepend" `Term.ann_` prependT) `Term.app_` hd `Term.app_` desugarVector tl where prependT = Type.forall'() ["a"] (Type.arrow() (Type.v' "a") (Type.arrow() va va)) va = Type.app() (Type.vector()) (Type.v' "a") annotateRefs :: (Applicative f, Ord v) => (Reference -> Noted f (Type.Type v)) -> Term v -> Noted f (Term v) annotateRefs synth term = ABT.visit f term where f (Term.Ref' h) = Just (Term.ann() (Term.ref() h) <$> (ABT.vmap TypeVar.Universal <$> synth h)) f _ = Nothing synthesizeClosed :: (Monad f, Var v) => [Type v] -> Type.Env f v -> (Reference -> Noted f (DataDeclaration v)) -> Term v -> Noted f (Type v) synthesizeClosed abilities synthRef lookupDecl term = do let declRefs = Set.toList $ Term.referencedDataDeclarations term term <- annotateRefs synthRef term decls <- Map.fromList <$> traverse (\r -> (r,) <$> lookupDecl r) declRefs synthesizeClosedAnnotated abilities decls term synthesizeClosed' :: Var v => [Type v] -> DataDeclarations v -> Term v -> M v (Type v) synthesizeClosed' abilities decls term | Set.null (ABT.freeVars term) = verifyDataDeclarations decls *> case runM (synthesize term) (MEnv env0 abilities decls True) of Left err -> M $ \_ -> Left err Right (t,env) -> pure $ generalizeExistentials (ctx env) t synthesizeClosed' _abilities _decls term = fail $ "Unknown symbols: " ++ show (Set.toList . ABT.freeVars $ term) checkClosed :: (Monad f, Var v) => Term v -> Noted f () checkClosed t = let fvs = Set.toList $ Term.freeVars t fvts = Set.toList $ Term.freeTypeVars t in if null fvs && null fvts then pure () else fail $ "Unknown symbols: " ++ intercalate ", " (Set.toList . Set.fromList $ map show fvs ++ map show fvts) synthesizeClosedAnnotated :: (Monad f, Var v) => [Type v] -> DataDeclarations v -> Term v -> Noted f (Type v) synthesizeClosedAnnotated abilities decls term = do checkClosed term Note.fromEither $ runM (verifyDataDeclarations decls *> synthesize term) (MEnv env0 abilities decls True) >>= \(t,env) -> -- we generalize over any remaining unsolved existentials pure $ generalizeExistentials (ctx env) t verifyDataDeclarations :: Var v => DataDeclarations v -> M v () verifyDataDeclarations decls = forM_ (Map.toList decls) $ \(r, decl) -> do let ctors = DataDeclaration.constructors decl forM_ ctors $ \(ctorName,typ) -> if Set.null $ ABT.freeVars typ then pure () else fail $ "encountered free vars " ++ show (Var.qualifiedName <$> Set.toList (ABT.freeVars typ)) ++ " in " ++ show r ++ "#" ++ show (Var.qualifiedName ctorName) -- boring instances instance Applicative (M v) where pure = return (<*>) = ap instance Functor (M v) where fmap = liftM instance Monad (M v) where return a = M (\menv -> Right (a, env menv)) M f >>= g = M (\menv -> f menv >>= (\(a,env') -> runM (g a) (menv {env = env'}))) fail msg = M (\_ -> Left (Note.note msg))
paulp/unison
parser-typechecker/src/Unison/Typechecker/Context1.hs
mit
41,680
126
25
10,107
14,697
7,261
7,436
722
29
module Util.Multiline( multiline ) where import Language.Haskell.TH import Language.Haskell.TH.Quote multiline :: QuasiQuoter multiline = QuasiQuoter { quoteExp = stringE }
vinnymac/glot-www
Util/Multiline.hs
mit
179
0
6
26
42
27
15
6
1
module Main where import Queens main = print $ length (queens 12)
dmoverton/finite-domain
test/testQueens.hs
mit
68
0
8
14
25
14
11
3
1
{-# LANGUAGE DataKinds, FlexibleContexts, FlexibleInstances, TypeOperators, TypeSynonymInstances #-} module Formura.Type where import Algebra.Lattice import qualified Data.Set as S import Data.Tuple(swap) import Formura.Language.Combinator import Formura.Syntax unitType :: (ElemTypeF ∈ fs) => Lang fs unitType = ElemType "void" type ElementalType = Lang '[TopTypeF, ElemTypeF] instance MeetSemiLattice ElementalType where (ElemType ea) /\ (ElemType eb) = case elementTypenameDecode(max (elementTypenameEncode ea) (elementTypenameEncode eb)) of "top" -> TopType str -> ElemType str _ /\ _ = TopType elementTypenames :: S.Set IdentName elementTypenames = S.fromList $ map fst elementTypenameTable elementTypenameTable :: [(IdentName,Int)] elementTypenameTable = flip zip [0..] ["void" ,"bool" ,"int" ,"Rational" ,"float" ,"double" ,"real" ,"Real"] elementTypenameEncode :: String -> Int elementTypenameEncode str = case lookup str elementTypenameTable of Just i -> i Nothing -> maxBound elementTypenameDecode :: Int -> String elementTypenameDecode i = case lookup i (map swap elementTypenameTable) of Just n -> n Nothing -> "top"
nushio3/formura
src/Formura/Type.hs
mit
1,352
0
11
361
338
181
157
36
2
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Data.Maybe as Maybe import qualified Data.Function as Function import qualified Data.List as List import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified Data.Text.Format.Strict as Format import System.FilePath ((</>), (<.>)) import qualified System.FilePath.Find as FilePath import System.FilePath.Find ((~~?)) import qualified System.Directory as Directory import qualified Text.Greek.IO.Paths as Paths import qualified Text.Greek.Source.Perseus.Catalog as Catalog import qualified Text.Greek.Source.Perseus.TEI as TEI import qualified Text.Greek.Xml.Parse as Parse import qualified Text.Greek.Xml.Common as Xml main :: IO () main = do paths <- greekFilePaths documents <- mapM tryLoadDocument paths mapM_ (printResult (\_ -> putStrLn "Success")) documents printResult :: Show e => (a -> IO ()) -> Either [e] a -> IO () printResult _ (Left es) = mapM_ (Text.putStrLn . Text.pack . show) es printResult f (Right x) = f x tryLoadDocument :: FilePath -> IO (Either [Xml.XmlError] TEI.Document) tryLoadDocument = Parse.readParseEvents TEI.documentParser greekFilePaths :: IO [FilePath] greekFilePaths = FilePath.find FilePath.always (FilePath.fileName ~~? "*-grc?.xml") Paths.perseusGreekData loadCatalog :: IO () loadCatalog = do perseusCatalog <- Parse.readParseEvents Catalog.inventoryParser Paths.perseusInventoryXml printResult getMessage perseusCatalog where getMessage inventory = do infos <- editionInfos let sortedInfos = List.sortBy (compare `Function.on` snd) infos mapM_ (Text.putStrLn . printEditionInfo) sortedInfos where works = getWorks inventory editions = concatMap workEditions works editionFiles = fmap editionPath editions editionInfos = traverse getEditionInfo editionFiles getEditionInfo x = do fileExists <- Directory.doesFileExist x return (x, fileExists) printEditionInfo (x, fileExists) = Format.format' "{}-{}" (existsMessage, x) where existsMessage = if fileExists then "Ok" else "Missing" :: Text.Text data Work = Work { workTitle :: Text.Text , workEditions :: [Edition] } data Edition = Edition { editionLabel :: Text.Text , editionDescription :: Text.Text , editionPath :: FilePath } makeWork :: Catalog.Work -> Work makeWork (Catalog.Work _ _ _ t es) = Work t $ Maybe.catMaybes $ fmap makeOpenEdition es makeOpenEdition :: Catalog.Edition -> Maybe Edition makeOpenEdition (Catalog.Edition _ u l d m) | m /= protectedGroup = Edition l d <$> (makeRelativePath u) makeOpenEdition _ = Nothing greekLitUrnPrefix :: Text.Text greekLitUrnPrefix = "greekLit" protectedGroup :: Text.Text protectedGroup = "Perseus:collection:Greco-Roman-protected" makeRelativePath :: Catalog.CtsUrn -> Maybe FilePath makeRelativePath (Catalog.CtsUrn [p, f]) | p == greekLitUrnPrefix = (Paths.perseusGreekData </>) <$> (convertPath $ fmap Text.unpack $ Text.splitOn "." f) where convertPath :: [String] -> Maybe FilePath convertPath [x,y,_] = Just $ x </> y </> (Text.unpack f <.> ".xml") convertPath _ = Nothing makeRelativePath _ = Nothing isValidWork :: Work -> Bool isValidWork = (/= 0) . length . workEditions getWorks :: Catalog.Inventory -> [Work] getWorks inventory = presentGreekWorks where textGroups = Catalog.inventoryTextGroups inventory flatWorks = concatMap Catalog.textGroupWorks textGroups greekWorks = filter ((== "grc") . Catalog.workLang) flatWorks greekWorkEditionCount = fmap makeWork greekWorks presentGreekWorks = filter isValidWork greekWorkEditionCount
scott-fleischman/greek-grammar
haskell/greek-grammar/executables/Perseus.hs
mit
3,713
0
14
665
1,085
597
488
78
2
----------------------------------------------------------- -- | -- module: MXNet.Core.Base.DType -- copyright: (c) 2016-2017 Tao He -- license: MIT -- maintainer: [email protected] -- -- DType corresponding between Haskell's data type and numpy's data type. -- {-# OPTIONS_GHC -Wno-missing-signatures #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE KindSignatures #-} module MXNet.Core.Base.DType ( DType (..) , pattern FLOAT32 , pattern FLOAT64 , pattern FLOAT16 , pattern UINT8 , pattern INT32 , Tensor (..) , Neural (..) , Context (..) , contextCPU , contextGPU ) where import Data.Int import Foreign.Storable (Storable) -- | DType class, used to quantify types that can be passed to mxnet. class (Storable a, Show a, Eq a, Ord a, Num a, Real a) => DType a where typeid :: a -> Int typename :: a -> String pattern FLOAT32 = 0 pattern FLOAT64 = 1 pattern FLOAT16 = 2 pattern UINT8 = 3 pattern INT32 = 4 instance DType Float where typeid _ = FLOAT32 {-# INLINE typeid #-} typename _ = "float32" {-# INLINE typename #-} instance DType Double where typeid _ = FLOAT64 {-# INLINE typeid #-} typename _ = "float64" {-# INLINE typename #-} instance DType Int8 where typeid _ = UINT8 {-# INLINE typeid #-} typename _ = "uint8" {-# INLINE typename #-} instance DType Int32 where typeid _ = INT32 {-# INLINE typeid #-} typename _ = "int32" {-# INLINE typename #-} -- | Tensor operations. class Tensor (tensor :: * -> *) where -- | Dot product. dot :: DType a => tensor a -> tensor a -> IO (tensor a) -- | Reshape a tensor value. reshape :: DType a => tensor a -> [Int] -> IO (tensor a) -- | Transpose a tensor value. transpose :: DType a => tensor a -> IO (tensor a) -- | Add, subtract, multiply, divide and power with IO action. (+.), (-.), (*.), (/.), (^.) :: DType a => tensor a -> tensor a -> IO (tensor a) -- | Ordinary arithmetic operators with scalar value. (.+), (.-), (.*), (./), (.^) :: DType a => tensor a -> a -> IO (tensor a) -- | Flip version of ordinary arithmetic operators with scalar value. (..-), (../), (..^) :: DType a => a -> tensor a -> IO (tensor a) -- | Mutable ordinary arithmetic operators with scalar value. (.+=), (.-=), (.*=), (./=), (.^=) :: DType a => tensor a -> a -> IO () -- | Compare two tensor values, after comparison, all cell may be set as a same value, or /0/, or /1/. _Maximum, _Minimum, equal, notEqual, greater, greaterEqual, lesser, lesserEqual :: DType a => tensor a -> tensor a -> IO (tensor a) -- | Compare a tensor value with a scalar value, after comparison, all cell may be set as a same value, or /0/, or /1/. _Maximum', _Minimum', equal', notEqual', greater', greaterEqual', lesser', lesserEqual' :: DType a => tensor a -> a -> IO (tensor a) infixl 6 .+, .-, ..- infixl 7 .*, ./, ../ infixr 8 .^, ..^ -- | Neural network combinators. class Tensor tensor => Neural tensor where -- | Apply a linear transformation: /Y = X W^T + b/. fullyConnected :: DType a => tensor a -- ^ Input data. -> tensor a -- ^ Weight matrix. -> tensor a -- ^ Bias parameter. -> Int -- ^ Number of hidden nodes of the output. -> IO (tensor a) -- | Apply correlation to inputs correlation :: DType a => tensor a -- ^ Input data1 to the correlation. -> tensor a -- ^ Input data2 to the correlation. -> IO (tensor a) -- | ElementWise activation function. activation :: DType a => tensor a -- ^ Input data to activation function. -> String -- ^ Activation function to be applied, one of {'relu', 'sigmoid', 'softrelu', 'tanh'}. -> IO (tensor a) -- | Leaky ReLu activation -- -- The following types are supported: -- -- 1. elu: /y = x > 0 ? x : slop * (exp(x)-1)/ -- 2. leaky: /y = x > 0 ? x : slope * x/ -- 3. prelu: same as leaky but the slope is learnable. -- 4. rrelu: same as leaky but the slope is uniformly randomly chosen from [lower_bound, upper_bound) for -- training, while fixed to be (lower_bound+upper_bound)/2 for inference. leakyReLU :: DType a => tensor a -- ^ Input data to activation function. -> String -- ^ Activation function to be applied, one of {'elu', 'leaky', 'prelu', 'rrelu'}, default is 'leaky'. -> IO (tensor a) -- | Apply softmax activation to input. softmaxActivation :: DType a => tensor a -- ^ Input data to activation function. -> IO (tensor a) -- | Apply dropout to input. dropout :: DType a => tensor a -- ^ Input data to dropout. -> Float -- ^ Fraction of the input that gets dropped out at training time, default is 0.5. -> IO (tensor a) -- | Batch normalization. batchNorm :: DType a => tensor a -- ^ Input data to batch normalization. -> tensor a -- ^ Gamma -> tensor a -- ^ Beta -> tensor a -- ^ Moving mean -> tensor a -- ^ Moving var -> IO (tensor a) -- | An operator taking in a n-dimensional input tensor (n > 2), and normalizing the input by subtracting the mean -- and variance calculated over the spatial dimensions. instanceNorm :: DType a => tensor a -- ^ A n-dimensional tensor (n > 2) of the form [batch, channel, spatial_dim1, spatial_dim2, ...]. -> tensor a -- ^ Gamma, a vector of length 'channel', which multiplies the normalized input. -> tensor a -- ^ Beta, a vector of length 'channel', which is added to the product of the normalized input and the weight. -> Float -- ^ Epsilon to prevent division by 0. -> IO (tensor a) -- | Set the l2 norm of each instance to a constant. l2Normalization :: DType a => tensor a -- ^ Input data to the L2NormalizationOp. -> Float -- ^ Epsilon to prevent div 0, default is /1e-10/. -> String -- ^ Normalization Mode, one of {'channel', 'instance', 'spatial'}, default is 'instance'. -> IO (tensor a) -- | Convolution Compute N-D convolution on (N+2)-D input. convolution :: DType a => tensor a -- ^ Input data. -> tensor a -- ^ Weight matrix. -> tensor a -- ^ Bias parameter. -> String -- ^ Convolution kernel size: (h, w) or (d, h, w). -> Int -- ^ Convolution filter(channel) number. -> IO (tensor a) -- | Apply convolution to input then add a bias. lrn :: DType a => tensor a -- ^ Input data to the ConvolutionOp. -> Float -- ^ Alpha, value of the alpha variance scaling parameter in the normalization formula, default is 0.0001. -> Float -- ^ Beta, value of the beta power parameter in the normalization formula, default is 0.75. -> Float -- ^ Value of the k parameter in normalization formula, default is 2. -> Int -- ^ Normalization window width in elements. -> IO (tensor a) -- | Apply deconvolution to input then add a bias. deconvolution :: DType a => tensor a -- ^ Input data to the DeconvolutionOp. -> tensor a -- ^ Weight matrix. -> tensor a -- ^ Bias parameter. -> String -- ^ Convolution kernel size: (h, w) or (d, h, w). -> Int -- ^ Convolution filter(channel) number. -> IO (tensor a) -- | Perform pooling on the input. pooling :: DType a => tensor a -- ^ Input data to the pooling operator. -> String -- ^ Pooling kernel size: (y, x) or (d, y, x). -> String -- ^ Pooling type to be applied, one of {'avg', 'max', 'sum'}. -> IO (tensor a) -- | Performs region-of-interest pooling on inputs. roiPooling :: DType a => tensor a -- ^ Input data to the pooling operator, a 4D Feature maps. -> tensor a -- ^ Bounding box coordinates. -> String -- ^ Fix pooled size: (h, w). -> Int -- ^ Ratio of input feature map height (or w) to raw image height (or w). -> IO (tensor a) -- | Apply a recurrent layer to input. rnn :: DType a => tensor a -- ^ Input data to RNN. -> tensor a -- ^ Vector of all RNN trainable parameters concatenated. -> tensor a -- ^ Initial hidden state of the RNN. -> tensor a -- ^ Initial cell state for LSTM networks (only for LSTM). -> Int -- ^ Size of the state for each layer. -> Int -- ^ Number of stacked layers. -> String -- ^ The type of RNN to compute, one of {'gru', 'lstm', 'rnn_relu', 'rnn_tanh'}. -> IO (tensor a) -- | Map integer index to vector representations (embeddings). embedding :: DType a => tensor a -- ^ Input data to the EmbeddingOp. -> tensor a -- ^ Embedding weight matrix. -> Int -- ^ Vocabulary size of the input indices. -> Int -- ^ Dimension of the embedding vectors. -> IO (tensor a) -- | Apply bilinear sampling to input feature map, which is the key of “[NIPS2015] Spatial Transformer Networks” output[batch, channel, y_dst, x_dst] = G(data[batch, channel, y_src, x_src) x_dst, y_dst enumerate all spatial locations in output x_src = grid[batch, 0, y_dst, x_dst] y_src = grid[batch, 1, y_dst, x_dst] G() denotes the bilinear interpolation kernel The out-boundary points will be padded as zeros. bilinearSampler :: DType a => tensor a -- ^ Input data to the BilinearsamplerOp. -> tensor a -- ^ Input grid to the BilinearsamplerOp.grid has two channels: x_src, y_src. -> IO (tensor a) -- | generate sampling grid for bilinear sampling. gridGenerator :: DType a => tensor a -- ^ Input data to the BilinearsamplerOp. -> tensor a -- ^ Input grid to the BilinearsamplerOp.grid has two channels: x_src, y_src. -> IO (tensor a) -- | Perform nearest neighboor/bilinear up sampling to inputs upSampling :: DType a => [tensor a] -- ^ Array of tensors to upsample. -> Int -- ^ Up sampling scale. -> String -- ^ Upsampling method, one of {'bilinear', 'nearest'}. -> IO (tensor a) -- | Apply spatial transformer to input feature map. spatialTransformer :: DType a => tensor a -- ^ Input data to the SpatialTransformerOp. -> tensor a -- ^ Localisation net, the output dim should be 6 when transform_type is affine. -> IO (tensor a) -- | Use linear regression for final output, this is used on final output of a net. linearRegressionOutput :: DType a => tensor a -- ^ Input data to function. -> tensor a -- ^ Input label to function. -> IO (tensor a) -- | Use Logistic regression for final output, this is used on final output of a net. logisticRegressionOutput :: DType a => tensor a -- ^ Input data to function. -> tensor a -- ^ Input label to function. -> IO (tensor a) -- | Softmax with logit loss. softmaxOutput :: DType a => tensor a -- ^ Input data. -> tensor a -- ^ Ground truth label. -> IO (tensor a) -- | Use mean absolute error regression for final output, this is used on final output of a net. maeRegressionOutput :: DType a => tensor a -- ^ Input data to function. -> tensor a -- ^ Input label to function. -> IO (tensor a) -- | Support Vector Machine based transformation on input, backprop L2-SVM svmOutput :: DType a => tensor a -- ^ Input data to svm. -> tensor a -- ^ Label data. -> Int -- ^ Margin, scale the DType(param_.margin) for activation size, default is 1. -> Float -- ^ Regularization coefficient, Scale the coefficient responsible for balacing coefficient size and error -- tradeoff, default is 1. -> Bool -- ^ Use linear, if set true, uses L1-SVM objective function. Default uses L2-SVM objective, default is False. -> IO (tensor a) -- | Calculate cross_entropy(data, one_hot(label)) softmaxCrossEntropy :: DType a => tensor a -- ^ Input data. -> tensor a -- ^ Input label. -> IO (tensor a) -- | Calculate Smooth L1 Loss(lhs, scalar) smoothL1 :: DType a => tensor a -- ^ Source input -> Float -- ^ Scalar input. -> IO (tensor a) -- | Apply a sparse regularization to the output a sigmoid activation function. identityAttachKLSparsereg :: DType a => tensor a -- ^ Input data. -> IO (tensor a) -- | Get output from a symbol and pass 1 gradient back. makeLoss :: DType a => tensor a -- ^ Input data. -> Float -- ^ Gradient scale as a supplement to unary and binary operators, default is 1. -> Float -- ^ Valid thresh, default is 0. Regard element valid when x > valid_thresh, this is used only -- in valid normalization mode. -> String -- ^ Normalization, one of {'batch', 'null', 'valid'}, default is 'null'. -> IO (tensor a) -- | Get output from a symbol and pass 0 gradient back blockGrad :: DType a => tensor a -- ^ The input. -> IO (tensor a) -- | Custom operator implemented in frontend. custom :: DType a => [tensor a] -- ^ Input of custom operator -> String -- ^ Type of custom operator, must be registered first. -> IO (tensor a) -- | Context definition. -- -- * DeviceType -- -- 1. cpu -- 2. gpu -- 3. cpu_pinned data Context = Context { deviceType :: Int , deviceId :: Int } deriving (Eq, Show) -- | Context for CPU 0. contextCPU :: Context contextCPU = Context 1 0 -- | Context for GPU 0. contextGPU :: Context contextGPU = Context 2 0
sighingnow/mxnet-haskell
mxnet/src/MXNet/Core/Base/DType.hs
mit
14,596
0
17
4,717
2,171
1,187
984
251
1
import Test.HUnit fizzbuzz n = [condition x | x <- [1 .. n]] condition x | rem x 3 == 0 && rem x 5 == 0 = "fizzbuzz" | rem x 3 == 0 = "fizz" | rem x 5 == 0 = "buzz" | otherwise = show x testFizz = TestCase (assertEqual "Should return until Fizz]" ["1", "2", "fizz"] (fizzbuzz 3)) testBuzz = TestCase (assertEqual "Should return until Buzz" ["1", "2", "fizz", "4", "buzz"] (fizzbuzz 5)) testFizzBuzz = TestCase (assertEqual "Should return until FizzBuzz" ["1", "2", "fizz", "4", "buzz", "fizz", "7", "8", "fizz", "buzz", "11", "fizz", "13", "14", "fizzbuzz"] (fizzbuzz 15)) myTests = TestList [testFizz, testBuzz, testFizzBuzz]
jefersonm/sandbox
languages/haskell/fizzbuzz.hs
mit
660
18
11
142
294
156
138
11
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeOperators #-} -- |Module : Numeric.Optimization.Algorithms.DifferentialEvolution -- Copyright : (c) 2011 Ville Tirronen -- License : MIT -- -- Maintainer : [email protected] -- -- This module implements basic version of Differential Evolution algorithm -- for finding minimum of possibly multimodal and non-differentiable real valued -- functions. -- module Numeric.Optimization.Algorithms.DifferentialEvolution ( -- * Basic Types Vector , Bounds , Fitness , Budget , DEParams(..) , -- * Control Parameters DEArgs(..) , Strategy(..) , strategy , defaultParams , -- * Executing the algorithm de , deStep ) where import qualified Data.Vector as V import qualified Data.Vector.Unboxed as VUB import qualified Data.Vector.Unboxed.Mutable as MUB import Control.Applicative import Control.Monad import Control.Monad.Base import Control.Monad.Primitive import Control.Monad.Reader import Control.Monad.ST import Data.Label as L import Data.Ord import Data.Tuple (swap) import System.Random.MWC -- Essential Types -- | -- Vector type for storing trial points type Vector = VUB.Vector Double -- | -- Type for storing function domain orthope. (Structure of arrays seems -- more efficient than array of structures) type Bounds = (Vector, Vector) -- | -- Fitness function type type Fitness i m o = V.Vector Vector -> m (V.Vector (o, Vector)) -- | -- Termination condition type. (Currently just a hard limit on evaluation count) type Budget = Int -- * Optimizer State data DEParams o = DEParams { _ec :: {-# UNPACK #-} !Int , _pop :: V.Vector (o, Vector) } $(mkLabels [''DEParams]) -- | -- Population Size sPop :: DEParams o -> Int sPop = V.length . get pop -- | -- Problem dimension dimension :: DEParams o -> Int dimension = VUB.length . snd . V.head . get pop -- * Context monad type Generator b = Gen (PrimState b) selectRandom :: (MonadBase b m, PrimMonad b) => Generator b -> Int -> V.Vector a -> m [a] selectRandom gen n vec = do idx <- randomIndexes (V.length vec) n gen return $! map (V.unsafeIndex vec) idx randomIndex :: (Integral a, Integral r, MonadBase b m, PrimMonad b) => a -> Generator b -> m r {-# INLINE randomIndex #-} randomIndex ub gen = do uni <- liftBase $ uniform gen return $! floor (fromIntegral ub * (uni :: Float)) randomIndexes :: (MonadBase b m, PrimMonad b) => Int -> Int -> Generator b -> m [Int] {-# INLINE randomIndexes #-} randomIndexes ub n gen = let sel 0 ss = return ss sel n ss = do x <- randomIndex ub gen if x `elem` ss then sel n ss else sel (n-1) (x:ss) in sel n [] expVariate :: (Integral r, MonadBase b m, PrimMonad b) => Float -> Generator b -> m r expVariate lambda gen = do uni <- liftBase $ uniform gen return $! round $ (- log uni)/(1-lambda) -- -- -- These should also have their own Vector - module (<+>), (<->) :: Vector -> Vector -> Vector a <+> b = VUB.zipWith (+) a b a <-> b = VUB.zipWith (-) a b (*|) :: Double -> Vector -> Vector a *| b = VUB.map (a*) b -- | -- Different strategies for optimization data Strategy = Rand1Bin {cr ::{-# UNPACK #-} !Float, f ::{-# UNPACK #-} !Double} | Prox1Bin {cr ::{-# UNPACK #-} !Float, f ::{-# UNPACK #-} !Double} | Rand2Bin {cr ::{-# UNPACK #-} !Float, f ::{-# UNPACK #-} !Double} | Rand1Exp {cr ::{-# UNPACK #-} !Float, f ::{-# UNPACK #-} !Double} | Rand2Exp {cr ::{-# UNPACK #-} !Float, f ::{-# UNPACK #-} !Double} deriving (Show) -- | -- Convert a Showable strategy into executable one strategy :: (MonadBase b m, PrimMonad b) => Int -> V.Vector (o, Vector) -> Strategy -> Vector -> Generator b -> m Vector {-# INLINE strategy #-} strategy l pop Rand1Bin{..} = strat' l pop (rand1 f) (binCrossover cr) strategy l pop Rand2Bin{..} = strat' l pop (rand2 f) (binCrossover cr) strategy l pop Rand1Exp{..} = strat' l pop (rand1 f) (expCrossover cr) strategy l pop Rand2Exp{..} = strat' l pop (rand2 f) (expCrossover cr) strategy l pop Prox1Bin{..} = \ parent gen -> do c <- rand2 f pop gen expCrossover cr l parent c gen strat' :: MonadBase b m => Int -> V.Vector (o, Vector) -> (V.Vector (o, Vector) -> Generator b -> m Vector) -> (Int -> Vector -> Vector -> Generator b -> m Vector) -> Vector -> Generator b -> m Vector strat' l pop m co parent gen = do x <- m pop gen co l parent x gen rand1 :: (MonadBase b m, PrimMonad b) => Double -> V.Vector (o, Vector) -> Generator b -> m Vector rand1 f pop gen = do [x1, x2, x3] <- selectRandom gen 3 $ V.map snd pop return $! x1 <+> (f *| (x2 <-> x3)) rand2 :: (MonadBase b m, PrimMonad b) => Double -> V.Vector (o, Vector) -> Generator b -> m Vector rand2 f pop gen = do [x1, x2, x3, x4, x5] <- selectRandom gen 5 $ V.map snd pop return $! x1 <+> (f *| (x2 <-> x3)) <+> (f *| (x4 <-> x5)) expCrossover :: (MonadBase b m, PrimMonad b, VUB.Unbox a) => Float -> Int -> VUB.Vector a -> VUB.Vector a -> Generator b -> m (VUB.Vector a) expCrossover cr l a b gen = do n' :: Int <- expVariate cr gen index <- randomIndex l gen let n = min n' (l-1) return $! moduloReplacement1 index n l a b moduloReplacement1 :: forall a . MUB.Unbox a => Int -> Int -> Int -> VUB.Vector a -> VUB.Vector a -> VUB.Vector a moduloReplacement1 start length dim a b = VUB.modify step a where overflow = start+length-dim end = min dim $ start+length step :: MUB.MVector s a -> ST s () step v = do MUB.write v start (b VUB.! start) forM_ ([0..overflow-1] ++ [start..end-1]) $ \ i -> MUB.write v i (b VUB.! i) binCrossover :: (MonadBase b m, PrimMonad b, VUB.Unbox a) => Float -> Int -> VUB.Vector a -> VUB.Vector a -> Generator b -> m (VUB.Vector a) binCrossover cr l a b gen = do randoms <- liftBase $ VUB.replicateM l (uniform gen) index :: Int <- randomIndex l gen return $! VUB.map (\ (x, e1, e2, i) -> if x < cr || i == index then e2 else e1) $ VUB.zip4 randoms a b (VUB.enumFromN 0 l) -- | -- Parameters for algorithm execution data DEArgs i m o = DEArgs { -- | Mutation strategy destrategy :: Strategy -- | N-dimensional function to be minimized , fitness :: Fitness i m o -- | N-orthope describing the domain of the fitness function , bounds :: Bounds -- | N, this should work well with dimension from 2-100 , dim :: Int -- | Number of individuals to use in optimization (60 is good) , spop :: Int -- | Number of fitness function evaluations until termination , budget :: Budget -- | Seed value for random number generation. (You often wish -- to replicate results without storing) , seed :: Seed } -- | -- Generate a parameter setting for DE. defaultParams :: Fitness i m o -> Bounds -> DEArgs i m o defaultParams fitness bounds = let dimension = VUB.length . fst $ bounds in DEArgs { destrategy = Rand1Exp 0.9 0.70 , fitness = fitness , bounds = bounds , dim = dimension , spop = 60 , budget = 5000 * dimension , seed = runST (create >>= save) } saturateVector :: Bounds -> Vector -> Vector saturateVector (mn, mx) x = let (!) = (VUB.!) d = VUB.length x in VUB.generate d $ \ i -> min (mx!i) (max (mn!i) (x!i)) -- | -- Run DE algorithm over a 'PrimMonad' such as 'IO' or 'ST'. de :: (Functor m, MonadBase b m, Ord o, PrimMonad b) => DEArgs i m o -> m [(Vector, o)] de DEArgs{..} = do let (lb, ub) = bounds scale x = VUB.zipWith3 (\ l u x -> l+x*(u-l)) lb ub x work gen state | get ec state > budget = return $! fmap swap . V.toList $ get pop state | otherwise = deStep destrategy bounds fitness gen state >>= work gen gen <- liftBase $ restore seed init <- liftBase $ V.replicateM spop (scale <$> uniformVector gen dim) population <- fitness init work gen $ DEParams (V.length population) population -- | -- Single iteration of Differential Evolution. Could be an useful building block -- for other algorithms as well. deStep :: (Functor m, MonadBase b m, Ord o, PrimMonad b) => Strategy -> Bounds -> Fitness i m o -> Generator b -> DEParams o -> m (DEParams o) deStep strate bounds fitness gen params = do let l = dimension params strat = strategy l (get pop params) strate update gen orig = do val <- V.forM orig $ \ (_, a) -> saturateVector bounds <$> strat a gen fitnessVal <- fitness val return $! V.zipWith (minBy fst) orig fitnessVal newPop <- update gen . get pop $ params return $! modify ec (+ sPop params) . set pop newPop $ params minBy :: Ord x => (a -> x) -> a -> a -> a minBy f a b | f a <= f b = a | otherwise = b
alphaHeavy/differential-evolution
Numeric/Optimization/Algorithms/DifferentialEvolution.hs
mit
8,983
4
16
2,218
3,214
1,683
1,531
259
3
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.ClientRect (js_getTop, getTop, js_getRight, getRight, js_getBottom, getBottom, js_getLeft, getLeft, js_getWidth, getWidth, js_getHeight, getHeight, ClientRect, castToClientRect, gTypeClientRect) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"top\"]" js_getTop :: ClientRect -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/ClientRect.top Mozilla ClientRect.top documentation> getTop :: (MonadIO m) => ClientRect -> m Float getTop self = liftIO (js_getTop (self)) foreign import javascript unsafe "$1[\"right\"]" js_getRight :: ClientRect -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/ClientRect.right Mozilla ClientRect.right documentation> getRight :: (MonadIO m) => ClientRect -> m Float getRight self = liftIO (js_getRight (self)) foreign import javascript unsafe "$1[\"bottom\"]" js_getBottom :: ClientRect -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/ClientRect.bottom Mozilla ClientRect.bottom documentation> getBottom :: (MonadIO m) => ClientRect -> m Float getBottom self = liftIO (js_getBottom (self)) foreign import javascript unsafe "$1[\"left\"]" js_getLeft :: ClientRect -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/ClientRect.left Mozilla ClientRect.left documentation> getLeft :: (MonadIO m) => ClientRect -> m Float getLeft self = liftIO (js_getLeft (self)) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: ClientRect -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/ClientRect.width Mozilla ClientRect.width documentation> getWidth :: (MonadIO m) => ClientRect -> m Float getWidth self = liftIO (js_getWidth (self)) foreign import javascript unsafe "$1[\"height\"]" js_getHeight :: ClientRect -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/ClientRect.height Mozilla ClientRect.height documentation> getHeight :: (MonadIO m) => ClientRect -> m Float getHeight self = liftIO (js_getHeight (self))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/ClientRect.hs
mit
2,902
36
8
385
702
411
291
43
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes, ViewPatterns, DeriveGeneric, TemplateHaskell, LambdaCase #-} module Ical where import Data.Time.Clock import Data.Time.LocalTime import Data.Time.Calendar import Data.List import Network.Http.Client import qualified Data.Text.Encoding as TE import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import Text.Parsec.Text import Text.Parsec hiding ((<|>)) import qualified Data.ByteString.Char8 as B import System.IO import qualified System.Directory as Dir import qualified System.IO.Error as IOEx import Data.Map as Map hiding (filter, map, foldl) import Data.Time.Format import Data.Aeson.TH (deriveJSON, defaultOptions) import Control.Applicative ((<|>)) import Data.Maybe import Control.Error import Control.Monad.Trans import TsEvent import Util import EventProvider import EventProviderSettings deriveConfigRecord icalConfigDataType deriveJSON defaultOptions ''IcalConfigRecord getIcalProvider :: EventProvider IcalConfigRecord () getIcalProvider = EventProvider { getModuleName = "Ical", getEvents = getCalendarEvents, getConfigType = members icalConfigDataType, getExtraData = Nothing, fetchFieldCts = Nothing } -- we can have components or objects, which are between BEGIN and END blocks, -- and can be recursive: -- -- BEGIN:VTIMEZONE -- TZID:US-Eastern -- BEGIN:STANDARD -- DTSTART:19971026T020000 -- TZOFFSETFROM:-0400 -- END:STANDARD -- BEGIN:DAYLIGHT -- DTSTART:19971026T02000 -- TZOFFSETFROM:-0500 -- TZNAME:EDT -- END:DAYLIGHT -- END:VTIMEZONE0 -- -- I map those with a tree structure. -- -- And also: http://tools.ietf.org/html/rfc2445#section-4.1.1 -- -- Some properties allow a list of parameters. Each property parameter -- in a list of property parameters MUST be separated by a SEMICOLON -- character (US-ASCII decimal 59). -- -- Property parameters with values containing a COLON, a SEMICOLON or a -- COMMA character MUST be placed in quoted text. -- -- For example, in the following properties a SEMICOLON is used to -- separate property parameters from each other, and a COMMA is used to -- separate property values in a value list. -- -- ATTENDEE;RSVP=TRUE;ROLE=REQ-PARTICIPANT:MAILTO: -- [email protected] -- -- RDATE;VALUE=DATE:19970304,19970504,19970704,19970904 -- -- Due to that, I have propParams (property parameters) and a list for the property values. data CalendarLeaf = CalendarLeaf { propParams :: Map String String, propValues :: [String] } deriving (Show, Eq) data CalendarValue = Leaf CalendarLeaf | SubLevel (Map String CalendarValue) deriving (Show, Eq) leafText :: CalendarLeaf -> String leafText = intercalate ", " . propValues fromLeaf :: CalendarValue -> Maybe CalendarLeaf fromLeaf (Leaf x) = Just x fromLeaf _ = Nothing getCalendarEvents :: IcalConfigRecord -> GlobalSettings -> Day -> (() -> Url) -> ExceptT String IO [TsEvent] getCalendarEvents (IcalConfigRecord icalAddress) settings day _ = do timezone <- lift $ getTimeZone (UTCTime day 8) let settingsFolder = getSettingsFolder settings icalText <- lift $ do hasCached <- hasCachedVersionForDay settingsFolder day if hasCached then readFromCache settingsFolder else readFromWWW (TE.encodeUtf8 icalAddress) settingsFolder calendarData <- hoistEither $ fmapL show $ parse parseEvents "" icalText return $ convertToEvents timezone day calendarData convertToEvents :: TimeZone -> Day -> [Map String CalendarValue] -> [TsEvent] convertToEvents tz day keyValues = filterDate tz day $ concatMap (keyValuesToEvents tz) keyValues readFromWWW :: B.ByteString -> String -> IO Text readFromWWW icalAddress settingsFolder = do putStrLn "reading from WWW" icalData <- Util.http GET icalAddress "" concatHandler requestDefaults putStrLn "read from WWW" let icalText = TE.decodeUtf8 icalData putInCache settingsFolder icalText return icalText filterDate :: TimeZone -> Day -> [TsEvent] -> [TsEvent] filterDate tz day = filter (eventInDateRange tz day) eventInDateRange :: TimeZone -> Day -> TsEvent -> Bool eventInDateRange tz day event = eventDay >= day && eventDay <= day where eventDay = localDay $ utcToLocalTime tz (TsEvent.eventDate event) parseEvents :: GenParser st [Map String CalendarValue] parseEvents = do manyTill anyChar (try $ lookAhead parseBegin) many parseEvent parseEvent :: GenParser st (Map String CalendarValue) parseEvent = do parseBegin keyValues <- manyTill (try parseSubLevel <|> try parseKeyValue) (try parseEnd) return $ Map.fromList keyValues makeEvents :: TimeZone -> TsEvent -> LocalTime -> LocalTime -> [TsEvent] makeEvents tz base start end | localDay end == localDay start = [base { eventDate = startUtc, extraInfo = T.concat["End: ", T.pack $ formatTime defaultTimeLocale "%R" end, "; duration: ", Util.formatDurationSec $ diffUTCTime endUtc startUtc] }] | otherwise = makeEvents tz base start (start {localTimeOfDay = TimeOfDay 23 59 0}) ++ makeEvents tz base (LocalTime (addDays 1 (localDay start)) (TimeOfDay 0 0 0)) end where startUtc = localTimeToUTC tz start endUtc = localTimeToUTC tz end keyValuesToEvents :: TimeZone -> Map String CalendarValue -> [TsEvent] keyValuesToEvents tz records = makeEvents tz baseEvent startDate endDate where baseEvent = buildBasicEvent descV (localTimeToUTC tz startDate) descV = T.concat $ (T.pack . leafValue records) <$> ["DESCRIPTION", "SUMMARY"] startDate = fromMaybe (error "No DTSTART!?") $ parseDateNode "DTSTART" records endDate = fromMaybe startDate $ parseDateNode "DTEND" records leafValue :: Map String CalendarValue -> String -> String leafValue records name = fromMaybe (error $ "No leaf of name " ++ name ++ " " ++ show records) $ leafText <$> (Map.lookup name records >>= fromLeaf) buildBasicEvent :: Text -> UTCTime -> TsEvent buildBasicEvent descV date = TsEvent { pluginName = getModuleName getIcalProvider, eventIcon = "glyphicons-46-calendar", eventDate = date, desc = descV, extraInfo = "", fullContents = Nothing } parseBegin :: GenParser st () parseBegin = string "BEGIN:VEVENT" >> eol parseKeyValue :: GenParser st (String, CalendarValue) parseKeyValue = do key <- many $ noneOf ":;" propertyParameters <- Map.fromList <$> many parsePropertyParameters string ":" values <- parseSingleValue `sepBy` string "," eol return (key, Leaf $ CalendarLeaf propertyParameters values) isMatch :: GenParser st a -> GenParser st Bool isMatch parser = isJust <$> optionMaybe (try parser) singleValueParserMatches :: [(GenParser st String, GenParser st String)] singleValueParserMatches = [ (string "\\n", ("\n" ++) <$> parseSingleValue), (string "\\", (:) <$> anyChar <*> parseSingleValue), (eol >> string " ", parseSingleValue)] parseSingleValue :: GenParser st String parseSingleValue = do text <- many $ noneOf "\\,\r\n" match <- Util.findM (isMatch . fst) singleValueParserMatches case match of Just matchInfo -> (text ++) <$> snd matchInfo Nothing -> return text parsePropertyParameters :: GenParser st (String, String) parsePropertyParameters = do string ";" key <- many $ noneOf "=" string "=" value <- many $ noneOf ";:" return (key, value) parseSubLevel :: GenParser st (String, CalendarValue) parseSubLevel = do string "BEGIN:" value <- many $ noneOf "\r\n" eol subcontents <- manyTill parseKeyValue (try (do string $ "END:" ++ value; eol)) return (value, SubLevel $ Map.fromList subcontents) parseDateNode :: String -> Map String CalendarValue -> Maybe LocalTime parseDateNode key records = do dateInfo <- Map.lookup key records >>= fromLeaf case Map.lookup "VALUE" $ propParams dateInfo of Just "DATE" -> parseDateOnlyNode key $ leafText dateInfo _ -> parseMaybe parseDateTime $ T.pack $ leafText dateInfo parseDateOnlyNode :: String -> String -> Maybe LocalTime parseDateOnlyNode key (T.pack -> nodeText) = dayTime <$> parseMaybe parseDate nodeText where dayTime time = case key of "DTSTART" -> time "DTEND" -> time { localTimeOfDay = TimeOfDay 23 59 59 } -- end of the day _ -> error $ "parseDateOnlyNode: " ++ show key parseDate :: GenParser st LocalTime parseDate = do date <- fromGregorian <$> parseNum 4 <*> parseNum 2 <*> parseNum 2 return $ LocalTime date (TimeOfDay 0 0 0) parseDateTime :: GenParser st LocalTime parseDateTime = do date <- parseDate char 'T' timeOfDay <- TimeOfDay <$> parseNum 2 <*> parseNum 2 <*> parseNum 2 return $ date { localTimeOfDay = timeOfDay } -- at the end of the file there may not be a carriage return. parseEnd :: GenParser st () parseEnd = string "END:VEVENT" >> optional eol hasCachedVersionForDay :: String -> Day -> IO Bool hasCachedVersionForDay settingsFolder day = cachedVersionDate settingsFolder >>= \case Nothing -> return False Just cachedDate -> return $ day < cachedDate cacheFilename :: String -> String cacheFilename settingsFolder = settingsFolder ++ "cached-calendar.ical" cachedVersionDate :: String -> IO (Maybe Day) cachedVersionDate settingsFolder = do modifTime <- IOEx.tryIOError $ Dir.getModificationTime $ cacheFilename settingsFolder return $ utctDay <$> hush modifTime readFromCache :: String -> IO Text readFromCache settingsFolder = do putStrLn "reading calendar from cache!" T.pack <$> readFile (cacheFilename settingsFolder) putInCache :: String -> Text -> IO () putInCache settingsFolder text = withFile (cacheFilename settingsFolder) WriteMode (`T.hPutStr` text)
emmanueltouzery/cigale-timesheet
src/EventProviders/Ical.hs
mit
9,976
0
15
2,050
2,599
1,339
1,260
191
3
-- -- Chapter 13, definitions from the book. -- module B'C'13 where -- Note: Chapter 5> cabal install import E'5''5 ( Shape ( Circle , Rectangle ) ) import E'5''7 ( area ) class Info a where examples :: [a] size :: a -> Int instance Info Char where examples = [ 'a' , 'A' , 'z' , 'Z' , '0' , '9' ] size _ = 1 -- GHCi> putStr (examples !! 0) -- -- GHCi> putStr (examples !! 1) -- a -- GHCi> examples :: [Char] -- "aAzZ09" instance Info Bool where examples = [ True , False ] size _ = 1 instance Info Int where examples = [ -100 .. 100 ] size _ = 1 -- instance Info Shape where -- -- examples = [ Circle 3.0 , Rectangle 45.9 87.6 ] -- size _ = round . area instance Info a => Info [a] where examples = [ [] ] ++ [ [x] | x <- examples ] ++ [ [x,y] | x <- examples , y <- examples ] size = foldr (+) 1 . map size instance (Info a , Info b) => Info (a , b) where examples = [ (x , y) | x <- examples , y <- examples ] size (x , y) = size x + size y + 1 -- class Checkable b where infoCheck :: (Info a) => (a -> b) -> Bool instance Checkable Bool where infoCheck property = and (map property examples) instance (Info a, Checkable b) => Checkable (a -> b) where infoCheck property = and (map (infoCheck . property) examples) test0 = infoCheck ( \x -> ( x <= (0::Int) || x > 0 ) ) test1 = infoCheck ( \x y -> ( x <= (0::Int) || y <= 0 || x*y >= x ) ) test2 = infoCheck ( \x y -> ( x <= (0::Int) || y <= 0 || x*y > x ) )
pascal-knodel/haskell-craft
Chapter 13/B'C'13.hs
mit
1,596
0
15
511
599
336
263
38
1
{-# LANGUAGE BangPatterns, OverloadedStrings#-} module Smutt.HTTP.Server.Request where import Prelude hiding (read) import Smutt.HTTP.Method as Method import Smutt.Util.URL.Simple as URL import Smutt.HTTP.URI as URI import Smutt.HTTP.Version as Version import Smutt.HTTP.Header (Header) import qualified Smutt.HTTP.Header as Header import Smutt.HTTP.Server.Settings as EXPORT import Smutt.HTTP.Server.Request.Content.Error import Network.BufferedSocket (BufferedSocket) import Control.Concurrent.MVar import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import Data.ByteString.Lazy (ByteString) import Data.Maybe import Data.Monoid -- | The server applies a Request to the handler thunk for every requst data Request = Request{ method :: !Method , uriStr :: !ByteString , uri :: URI , version :: !Version , headers :: !Header , contentLength :: !(Maybe Int) , bodyType :: !(Maybe BodyType) , bufferedSocket :: !BufferedSocket , settings :: !ServerSettings , readStateMVar :: !(Maybe (MVar ReadState)) -- | Thest functions are for reading the request. May not allways be the same function depending on the request , readAll :: IO (Either ContentError ByteString) , readMax :: Int -> IO (Either ContentError (Int, ByteString)) } -- | Only shows the request header instance Show Request where show req = show (method req) <> " " <> " " <> show (uriStr req) <> " " <> show (version req) <> show (headers req) blankRequest :: ServerSettings -> BufferedSocket -> Request blankRequest set bSock = Request { method = GET, uriStr = "", uri = fromJust $ URI.fromString "/", version = HTTP 1 0, headers = mempty, contentLength = Nothing, bodyType = Nothing, settings = set, bufferedSocket = bSock, readStateMVar = Nothing, readAll = return $ Left EOF, readMax = \_ -> return $ Left EOF } data BodyType = Chunked | Exact deriving (Eq, Show,Read) {-| The read state is in use when a request has a body that should be read. -} data ReadState = ExactState { exactBytesLeft :: Int } | ChunkedState { chunkedTotalRead :: Int, chunkBytesLeft :: Int, chunkedEOF :: Bool, trailer :: Maybe Header } deriving (Show,Eq) -- | Return the ammount of bytes read. If the request doesn't have a body it will still return 0 bytesRead:: Request -> IO Int bytesRead req = case readStateMVar req of Nothing -> return 0 Just mvarReadState -> do readState <- readMVar mvarReadState return $ readStateBytesRead readState where readStateBytesRead :: ReadState -> Int readStateBytesRead (ExactState n) = n readStateBytesRead (ChunkedState n _ _ _) = n -- | Checks wether the body is transfered through chunked encoding hasChunkedBody :: Request -> Bool hasChunkedBody = maybe False (==Chunked) . bodyType -- | Checks wether the body length is known hasExactBody :: Request -> Bool hasExactBody = isJust . contentLength hasBody :: Request -> Bool hasBody = isJust . bodyType reachedEOF :: Request -> IO Bool reachedEOF req | isNothing maybeRS || isNothing mLength = return True | otherwise = do rs <- readMVar (fromJust maybeRS) case rs of ExactState 0 -> return True (ChunkedState _ _ True _) -> return True _ -> return False where maybeRS = readStateMVar req mLength = contentLength req -- | Wrapper for a hashmap lookup, this is needed since field names Must be case-insesitive headerLookup :: Request -> Text -> Maybe Text headerLookup req fieldName = Header.lookup fieldName (headers req) hasHeaderKey :: Request -> Text -> Bool hasHeaderKey req key = Header.member key (headers req) headerSize :: Request -> Int headerSize = Header.size . headers hasConnectionClose :: Request -> Bool hasConnectionClose req = case headerLookup req "connection" >>= Just . T.toCaseFold of Just "close" -> True _ -> False
black0range/Smutt
src/Smutt/HTTP/Server/Request.hs
mit
4,139
0
14
1,026
1,039
572
467
111
3
{-#LANGUAGE DeriveDataTypeable #-} module Crystal.RecursiveType (solveLetrec) where import Control.Arrow (second) import Control.Lens (_1, _2, _3, mapped, (^.), (.~), (&), view, to, (%~)) import Control.Lens.TH import Data.List import Data.Function import Debug.Trace import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S import Data.Generics import Data.Generics.Uniplate.Operations import Control.Monad import Control.Monad.Trans import Control.Monad.Reader import Control.Monad.Writer import Control.Monad.State import Control.Applicative import Test.QuickCheck import Text.Show import Text.PrettyPrint import Crystal.Tuple import Crystal.Type debugging = False traced f x | debugging = trace (f x) x traced f x | otherwise = x solveLetrec :: [(TVar, Type)] -> [(TVar, Type)] solveLetrec tts' = traced (\_ -> "Input: " ++ show tts) $ traced (\out -> "Output: " ++ show out) $ go 0 [ (tv, TFun vars ef TError) | (tv, TFun vars ef _) <- tts ] where tts = map (second (simplifyPlus True . approximate allowed)) tts' allowed = S.fromList $ map fst tts go n expns = let expns' = [ (tv, simplifyPlus True ex') | (tv, tt) <- tts , let ex' = fillIn tt expns] in if expns == expns' then expns' else go (n+1) $ traced (\out -> "Iter " ++ show n ++ ": " ++ show out) expns' fillIn tt expns = replace (M.fromList [ (v, LSyn :*: t) | (v,t) <- expns]) tt approximate :: S.Set TVar -> Type -> Type approximate allowed = transform f where f (TChain (TAppl (TVar tv) args) res lab body) | tv `S.notMember` allowed = expand (TChain TAny res lab body) f x = x
Botje/crystal
Crystal/RecursiveType.hs
gpl-2.0
1,837
1
17
522
668
368
300
46
2
-- | A simple fight simulator for Sil 1.1.1; see the README for -- a more thorough introduction. module Main (fight, FightStats, summarize, damGiven, critsGiven, damGivenPercent, damTaken, player, opponent, readCharDump, parseMonsterFile, getMonster, main) where import System.Environment import Control.Monad import Control.Monad.State import Numeric import Data.List (concat) import qualified Numeric.Probability.Distribution as D import Numeric.Probability.Distribution((??)) import qualified Monster as M import Monster(getMonster) import qualified Player as P import qualified Data.Map as Map import qualified Types as T import Rdice import qualified CombatState as CS import MonsterParser import CharDumpParser import CommandLineArgs as CLA import qualified Numeric.Probability.Random as R import qualified Numeric.Probability.Transition as TR import qualified Numeric.Probability.Simulation as S -- | 'FightStats' contains all the statistics that fsil computes. data FightStats = FightStats { damGiven :: Dist, -- ^ Distribution of the damage inflicted by the player on the monster -- in a single turn (using all the attacks that the player has if -- they have several due to Two-Weapon Fighting or Rapid Attack.) critsGiven :: [Dist], -- ^ Distributions of the number of extra damage dice that the player -- gets due to a critical hit, separately for each of the player's -- attacks. confusionTurnsInflicted :: Dist, -- ^ Distribution of the number of turns of confusion inflicted on -- the monster due to a critical hit if the player has the -- Cruel Blow ability. damGivenPercent :: Dist, -- ^ Distribution of the damage inflicted by the player on the monster -- as a percentage of the monster's maximum hit points; monster max hp -- is a random number, so this cannot be computed directly from -- @damGiven@ above. damTaken :: [Dist], -- ^ Distributions of the damage inflicted on the player by the monster, -- separately for each of the monster's attacks if the monster has -- several. (Monsters that have several attacks don't attack with both -- attacks at the same time.) player :: P.Player, opponent :: M.Monster } --All the functions that follow use RInt as a monad, as defined in --Numeric.Probability.Random; --http://web.engr.oregonstate.edu/~erwig/papers/PFP_JFP06.pdf is a good --explanation of the idea and implementation. --Returns the net to-hit roll, i.e. the difference between the attacker's --to-hit roll and the defender's evasion roll netToHitDist :: Int -> Int -> RInt netToHitDist accuracy evasion = do toHitRoll <- (+accuracy) `fmap` (dist $ 1 `d` 20) evasionRoll <- (+evasion) `fmap` (dist $ 1 `d` 20) return $ toHitRoll - evasionRoll --Calculate the number of critical hits based on the base threshold --and the net to-hit score. nCrits :: Double -> Int -> Int nCrits criticalThreshold toHitRoll | toHitRoll < 1 = 0 | otherwise = floor $ (fromIntegral toHitRoll + 0.4) / criticalThreshold --Roll damage and subtract protection roll (modified by sharpness). netDamageDist :: Dice -> Double -> [Dice] -> RInt netDamageDist damDice sharpness protDiceList = do damage <- dist damDice protection <- sumDice protDiceList let modifiedProt = floor $ fromIntegral protection * sharpness return $ max 0 (damage - modifiedProt) --Take an Attack and the defender's evasion score and return the --net damage distribution for that attack. attackDamDist :: T.Attack -> Int -> [Dice] -> RInt attackDamDist attack evasion protDice = do toHit <- if (T.alwaysHits attack) then return 1 else netToHitDist (T.accuracy attack) evasion if toHit < 1 then return 0 else do let damDice = addDice nCritDice (T.damage attack) sharpness = T.sharpness attack nCritDice = if (T.canCrit attack) then nCrits (T.critThreshold attack) toHit else 0 netDamageDist damDice sharpness protDice --Take a list of attacks and the defender's evasion score and protection --dice, and return the net damage distribution for the attacks being applied --one after another (e.g. the player attacks the monster with two attacks --from Rapid Attack or Two-Weapon Fighting) attackSeqDamDist :: [T.Attack] -> Int -> [Dice] -> RInt attackSeqDamDist [] _ _ = return 0 attackSeqDamDist (a:as) evasion protDice = do damRest <- attackSeqDamDist as evasion protDice dam <- attackDamDist a evasion protDice return $ dam + damRest --Take an attack and the defender's evasion score and return the distribution --of the number of critical dice that the attacker gets. attackNCritsDist :: T.Attack -> Int -> RInt attackNCritsDist attack evasion = do toHit <- netToHitDist (T.accuracy attack) evasion let nCritDice = if (T.canCrit attack) then nCrits (T.critThreshold attack) toHit else 0 return nCritDice --Take a list of attacks and the defender's evasion score and return the --distributions of the number of critical dice that the attacker gets, --separately for each attack in the list. attackSeqNCritsDist :: [T.Attack] -> Int -> [RInt] attackSeqNCritsDist [] _ = [] attackSeqNCritsDist (a:as) evasion = (attackNCritsDist a evasion) : attackSeqNCritsDist as evasion --Number of turns of confusion inflicted with cruel blow. --If multiple player attacks inflict confusion, the maximum of --the confusion turn counts inflicted by the individual attacks --will be used. cruelBlowTurns :: [RInt] -> M.Monster -> RInt cruelBlowTurns nCritsDists monster = fmap maximum $ sequence $ map (cBTurnsForOneAttack monster) nCritsDists where cBTurnsForOneAttack monster nCritsDist = do nCrits <- nCritsDist check <- skillCheck (4 * nCrits) (M.will monster) if check > 0 then return nCrits else return 0 --Roll a skill check. skillCheck :: Int -> Int -> RInt skillCheck skill difficulty = do skillRoll <- (+ skill) `fmap` (dist $ 1 `d` 10) diffRoll <- (+ difficulty) `fmap` (dist $ 1 `d` 10) return $ skillRoll - diffRoll --Take a net damage distribution and return a distribution --of the damage as a percentage of the monster's max hp. damDistPercent :: RInt -> M.Monster -> RInt damDistPercent damDist m = do maxHP <- dist $ (M.health m) damage <- damDist return $ 100 - (100 * (maxHP - damage)) `quot` maxHP --Take a player, a monster and a number of samples to simulate, --and produce a FightStats. The distributions in FightStats are --empirical distributions simulated using nSamples samples. fight :: P.Player -> M.Monster -> Int -> IO FightStats fight player monster nSamples = let (_,(p,m)) = runState CS.applyCombatModifiers (player,monster) pAttacks = P.attacks p pEv = P.evasion p pProt = P.protDice p mAttacks = M.attacks m mEv = M.evasion m mProt = M.protDice m damGiven' = attackSeqDamDist pAttacks mEv [mProt] damGivenPercent' = damDistPercent damGiven' monster critsGiven' = attackSeqNCritsDist pAttacks mEv confusionTurnsInflicted' = cruelBlowTurns critsGiven' monster --When a monster has several attacks, they're mutually exclusive --alternatives, so compute separate distributions for each damTaken' = map distForOneAttack mAttacks distForOneAttack a = attackDamDist a pEv pProt in do damGiven <- simulate nSamples $! damGiven' damGivenPercent <- simulate nSamples $! damGivenPercent' critsGiven <- mapM (simulate nSamples) $! critsGiven' confusionTurnsInflicted <- simulate nSamples $! confusionTurnsInflicted' damTaken <- mapM (simulate nSamples) $! damTaken' return $ FightStats { damGiven = damGiven, damGivenPercent = damGivenPercent, critsGiven = critsGiven, confusionTurnsInflicted = confusionTurnsInflicted, damTaken = damTaken, player = p, opponent = m} -- | Pretty-print a FightStats summarize :: FightStats -> String summarize fs = "SUMMARY AND MISC INFORMATION\n\n" ++ P.name (player fs) ++ " vs " ++ M.name (opponent fs) ++ "\nDamage dealt by monster: mean " ++ show ( map mean (damTaken fs)) ++ ", standard deviation " ++ show ( map std (damTaken fs)) ++ "\nDamage dealt by player: mean " ++ show (mean (damGiven fs)) ++ ", standard deviation " ++ show (std (damGiven fs)) ++ "\nPlayer dark resistance: " ++ show ( (P.resistances $ player fs) Map.! T.Dark) ++ "\nPlayer singing: " ++ show (P.activeSongs $ player fs) ++ "\nMonster alertness: " ++ show (M.alertness $ opponent fs) ++ "\nMonster will: " ++ show (M.will $ opponent fs) ++ "\nPlayer sees monster: " ++ show ( M.seenByPlayer $ opponent fs ) ++ "\n\n\nMONSTER ATTACKING PLAYER\n" ++ "\nProbability of dealing at least x damage: \n\n" ++ unlines (map (printCDF 0) $ map (ccdf 1) (damTaken fs)) ++ "\n\nPLAYER ATTACKING MONSTER\n" ++ "\nProbability of getting at least n critical hits:\n" ++ unlines ( map (printCDF 3) $ map (ccdf 1) (critsGiven fs) ) ++ "\nProbability of inflicting at least n turns of confusion \ \with Cruel Blow:\n" ++ (printCDF 3 $ ccdf 1 (confusionTurnsInflicted fs)) ++ "\nProbability of dealing at least X% (of max hp) damage:\n" ++ (printCDF 3 $ takeWhile ((<= 100) . fst) $ ccdf 10 $ damGivenPercent fs ) ++ "\nProbability of dealing at least x damage: \n" ++ (printCDF 3 $ ccdf 1 (damGiven fs) ) where main = do fsilOptions <- CLA.parseArgs player <- readCharDump (CLA.charDumpFile fsilOptions) let singing' = CLA.singing fsilOptions meleeBonus = CLA.meleeBonus fsilOptions evBonus = CLA.evBonus fsilOptions nSamples = CLA.nSamples fsilOptions player' = (P.modifyAccuracyWith (+ meleeBonus)) . (P.modifyEvasionWith (+ evBonus)) . (P.singing singing') $ player {P.onLitSquare = CLA.playerOnLitSquare fsilOptions} monsterName = CLA.monsterName fsilOptions alertness = CLA.alertness fsilOptions monsters <- parseMonsterFile "monster.txt" let monster = (M.getMonster monsterName monsters) {M.alertness = alertness, M.onLitSquare = CLA.monsterOnLitSquare fsilOptions, M.seenByPlayer = not $ CLA.invisibleMonster fsilOptions} fightStats <- fight player' monster nSamples putStr . summarize $ fightStats
kryft/fsil
Fsil.hs
gpl-2.0
10,628
0
40
2,394
2,318
1,234
1,084
191
4
module Database.Design.Ampersand.Input.ADL1.LexerBinaryTrees ( BinSearchTree(..) , tab2tree , btFind , btLocateIn ) where data BinSearchTree av = Node (BinSearchTree av) av (BinSearchTree av) | Nil tab2tree :: [av] -> BinSearchTree av tab2tree tab = tree where (tree,[]) = sl2bst (length tab) tab sl2bst 0 list = (Nil , list) sl2bst n list = let ll = (n - 1) `div` 2 ; rl = n - 1 - ll (lt,a:list1) = sl2bst ll list (rt, list2) = sl2bst rl list1 in (Node lt a rt, list2) btFind :: (a -> b -> Ordering) -> BinSearchTree (a, c) -> b -> Maybe c btLocateIn :: (a -> b -> Ordering) -> BinSearchTree a -> b -> Maybe a btFind = btLookup fst snd btLocateIn = btLookup id id btLookup :: (d -> a) -> (d -> c) -> (a -> b -> Ordering) -> BinSearchTree d -> b -> Maybe c btLookup key val cmp (Node Nil kv Nil) = let comp = cmp (key kv) r = val kv in \i -> case comp i of LT -> Nothing EQ -> Just r GT -> Nothing btLookup key val cmp (Node left kv Nil) = let comp = cmp (key kv) findleft = btLookup key val cmp left r = val kv in \i -> case comp i of LT -> Nothing EQ -> Just r GT -> findleft i btLookup key val cmp (Node Nil kv right ) = let comp = cmp (key kv) findright = btLookup key val cmp right r = val kv in \i -> case comp i of LT -> findright i EQ -> Just r GT -> Nothing btLookup key val cmp (Node left kv right) = let comp = cmp (key kv) findleft = btLookup key val cmp left findright = btLookup key val cmp right r = val kv in \i -> case comp i of LT -> findright i EQ -> Just r GT -> findleft i btLookup _ _ _ Nil = const Nothing
DanielSchiavini/ampersand
src/Database/Design/Ampersand/Input/ADL1/LexerBinaryTrees.hs
gpl-3.0
2,078
0
13
883
797
405
392
56
9
-- Cryptography examples -- URL: http://www.macs.hw.ac.uk/~hwloidl/Courses/F21CN/index.html -- This file: http://www.macs.hw.ac.uk/~hwloidl/Courses/F21CN/Labs/caesar.hs -- Exercises for the Cryptography part of the above course F21CN -- -- Run the exercises on the Linux lab machines after doing the installation: -- # wget http://www.macs.hw.ac.uk/~hwloidl/Courses/F21CN/Labs/f21cn.sh -- # source f21cn.sh -- # install_ghc_pkgs -- Installation is successful, if you see these lines at the end: -- You should now find 'QuickCheck' and 'HaskellForMaths' in the list below: -- QuickCheck-2.4.1.1 -- HaskellForMaths-0.1.9 -- After that, start the GHCi interpreter like this: -- # ghci -package HaskellForMaths -package QuickCheck caesar.hs -- Now, go through this file and test code snippets, by cut-and-paste of lines -- starting with (#> represents the GHCi prompt): -- #> -- eg, -- #> test ----------------------------------------------------------------------------- module Caesar where import Data.Char import Data.List ----------------------------------------------------------------------------- -- Caesar Cipher Example -- from Hutton "Programming in Haskell", p42ff -- The code below implements a simple (rotation-bsaed) Caesar cipher. -- It is very easy to crack, which is done by the function crack. -- See the exercise below ----------------------------------------------------------------------------- let2int :: Char -> Int let2int c = ord c - ord 'a' int2let :: Int -> Char int2let n = chr (ord 'a' + n) -- shift a character c by n slots to the right shift :: Int -> Char -> Char shift n c | isLower c = int2let (((let2int c) + n) `mod` 26) | otherwise = c -- top-level string encoding function encode :: Int -> String -> String encode n cs = [ shift n c | c <- cs ] -- table of frequencies of letters 'a'..'z' table :: [Float] table = [8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0, 0.2, 0.8, 4.0, 2.4, 6.7, 7.5, 1.9, 0.1, 6.0, 6.3, 9.1, 2.8, 1.0, 2.4, 0.2, 2.0, 0.1] percent :: Int -> Int -> Float percent n m = (fromIntegral n / fromIntegral m)*100 -- compute frequencies of letters 'a'..'z' in a given string freqs :: String -> [Float] freqs cs = [percent (count c cs) n | c <- ['a'..'z'] ] where n = lowers cs -- chi-square function for computing distance between 2 frequency lists chisqr :: [Float] -> [Float] -> Float chisqr os es = sum [((o-e)^2)/e | (o,e) <- zip os es] -- rotate a list by n slots to the left; take, drop are Prelude functions rotate :: Int -> [a] -> [a] rotate n xs = drop n xs ++ take n xs -- the number of lower case letters in a given string lowers :: String -> Int lowers cs = length [ c | c <- cs, isLower c] -- count the number of occurrences of c in cs count :: Char -> String -> Int count c cs = length [ c' | c' <- cs, c==c'] -- find list of positions of x in the list xs positions :: Eq a => a -> [a] -> [Int] positions x xs = [ i' | (x', i') <- zip xs [0..n], x==x' ] where n = length xs - 1 -- top-level decoding function crack :: String -> String crack cs = encode (-factor) cs where factor = head (positions (minimum chitab) chitab) chitab = [ chisqr (rotate n table') table | n <- [0..25] ] table' = freqs cs -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- Exercise: -- encrypting a simple text string -- #> let s1 = "a completely random text string" -- #> let c1 = encode 3 s1 -- #> c1 -- now, let's try to crack it -- #> let d1 = crack c1 -- Q: is it the same as s1? -- #> d1 -- there are no 'e's in the string below -- Q: do you believe we can still crack this string? -- #> let s2 = "unusal random string" -- #> let c2 = encode 7 s2 -- #> c2 -- #> let d2 = crack c2 -- #> d2 -- Now, let's try the string below -- #> let s3 = "an apple fell off" -- #> let c3 = encode 13 s3 -- #> c3 -- #> let d3 = crack c3 -- #> d3 -- Q: why do you think cracking failed in the above example? -- Test your hypothesis by devising another input, encode and try to crack it -- Now, let's try some randomly generated text as input -- We read in words from a dictionary (in words.txt) -- #> str <- readFile "words.txt" -- #> let words = lines str -- Now we define a function to build text by selecting words from the list -- #> let mkStr = \ (n:xs) -> map toLower (foldl1 (\ x ys -> x ++ " " ++ ys) (map (\ i -> words!!i) (take n (filter (<(length words)) (nub xs))))) -- Test this by generating text consisting of 4 (first number in the list) words -- #> mkStr [4,23349,98422,52321,1942,453,8777] -- and try to crack it -- #> crack (encode 6 (mkStr [4,23349,98422,52321,1942,453,8777])) -- We can use this function together with quickcheck to test random texts, containing 5 to 9 words from the dictionary -- #> quickCheck ( \ ys -> length ys > 66 ==> let (n:xs) = ys in (n>5 && n<9 ) ==> let str = mkStr (n:xs) in crack (encode 13 str) == str ) -- It will fail for a degenerate case, such as picking [16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] -- Check the string, which triggers the failed check like this -- #> mkStr [16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] -- You can also use quickcheck to encode some random string str (btw 10 and 50 characters long) -- and then trying to crack the encoded string; it will report the first failed crack -- #> quickCheck (\str -> length str < 10 || length str > 50 || crack (encode 7 str) == str) -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- Vernam cipher (using a sequence of shift values as key) vernam = zipWith shift -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- Exercise: -- encrypting a simple text string using a vernam cipher -- #> vernam [1..] "some message" -- "tqpi slabkrq" -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- ----------------------------------------------------------------------------- -- Modular arithmetic using Math.Algebra.Field.Base -- ----------------------------------------------------------------------------- showtab' n str [] = str showtab' n str ([]:xss) = showtab' (n+1) (str++"\n"++" "++(if not (null xss) then show (n+1) ++ ":" else "")) xss showtab' n str ((x:xs):xss) = showtab' n (str++" "++(show x)) (xs:xss) -- show a multiplication table showtab n = showtab' 0 (" "++(concat (intersperse " " (map show [0..n-1])))++"\n 0:") (mkTab n) -- build a multiplication table mkTab n = [ [ i*j `mod` n | j <- [0..n-1] ] | i <- [0..n-1] ] -- Example: -- #> putStrLn (showtab 5) -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- Exercise: -- In the examples below, try to answer each question -- yourself before you execute the line following it. -- multiplication in the modular domain, mod 5 -- (2 :: F5) means, 2 is a number in the modular domain mod 5 -- Q: what's the result? -- #> (2 :: F5)*(3 :: F5) -- try more examples, using +, -, * -- use variables like this: -- #> let x = (2 :: F5) -- #> x*x*x -- the notation x^n means x to the power of n; -- Q: can you calculate the result below, using pen and paper, -- or even in your head? Explain how you can compute it. -- #> x^10 -- here is the multiplication table, mod 5 -- #> putStrLn (showtab 5) -- exponentiation in the modular domain, mod 5 -- Q: Using the table above, what's the result? -- #> (2 :: F5)^3 -- inverse mod 5 -- Q: how do you use the multiplication table to find an inverse? eg: -- #> recip (3::F5) -- how to you read-off the inverse from the table -- #> putStrLn (showtab 5) -- let's test it -- #> recip (4::F5) -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- ----------------------------------------------------------------------------- -- RSA encryption -- ----------------------------------------------------------------------------- -- Auxiliary functions -- modular inverse, i.e. mod_inv n e = head [ x | x <-[1..n-1], e*x `mod` n == 1 ] -- (naive) Euler totient function euler :: Integer -> Integer euler n = fromIntegral (length [ x | x <- [(1::Integer)..n], gcd x n == 1]) -- relatively prime rel_prime :: Integer -> Integer -> Bool rel_prime x y = gcd x y == 1 -- all prime numbers (infinite list) primes :: [Integer] primes = 2:[ p | p <- [3,5..], isprime primes p ] where isprime (x:xs) p = if p>=x^2 then not (p `mod` x == 0) && isprime xs p else True -- test is_prime :: Integer -> Bool is_prime n = n == head (dropWhile (<n) primes) -- naive integer factorisation factors :: Integer -> [Integer] factors x = [ p | p <- takeWhile (<x) primes, x `mod` p == 0 ] pick_e (p,q) = head [ x | x <- primes, not (x `elem` ps) ] where ps = factors ((p-1)*(q-1)) -- ----------------------------------------------------------------------------- -- RSA encryption -- ----------------------------------------------------------------------------- -- main functions -- RSA encryption is simple: you just compute the exponential encrypt (e,n) m = m^e `mod` n -- RSA decryption is almost the same: decrypt (d,n) m = m^d `mod` n -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- RSA Exercise:: -- we first need to pick 2 prime numbers; to do that we -- select the 7-th and 8-th element of the infinite list -- prime numbes, 'primes' -- #> let p = primes!!7 -- #> let q = primes!!8 -- #> let n = p*q -- #> let phi = (p-1)*(q-1) -- we need to select a (public) encryption key 'e', which is not -- a factor of the 'phi' computed above -- #> factors phi -- we see that the value 7 is a valid choice -- #> let e = 7 -- we double check that it is a valid choice by computing the gcd -- #> gcd e phi -- the result must be 1 -- now, we can compute the (secret) decryption key as follows: -- #> let d = mod_inv phi e -- we check that 'd' works as a decryption key, by computing: -- #> e*d `mod` phi -- the result must be 1 -- now, that we have both encryption and decryption keys, we can encode 'm' -- #> let enc m = m^e `mod` n -- and decode the encrypted message 'c' like this -- #> let dec c = c^d `mod` n -- let's test this, using the integer 99 as message -- #> let m=99 -- we encode the message like this -- #> let c = enc m -- #> c -- and decode it like this -- #> dec c -- the result should be the original message, 99 -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- Exercise: testing properties -- The following property states correctness of encryption: -- for any random integer m, encryting and then decrypting -- gives you the original message: -- #> quickCheck (\ m -> dec (enc (abs m)) == (abs m)) -- This property states that the Euler totient of a prime m is m-1 -- #> quickCheck (\ m -> m<0 || not (is_prime m) || euler m == m-1) -- This is the Euler Theorem: -- #> quickCheck (\ m n -> m<2 || n<2 || not (gcd m n == 1) || m^(euler n) `mod` n == 1) -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ test = do let p = primes!!7 putStrLn $ "We pick p = "++(show p) let q = primes!!8 putStrLn $ "We pick q = "++(show q) let n = p*q putStrLn $ "We have n = p*q = "++(show n) let phi = (p-1)*(q-1) putStrLn $ "We have phi = (p-1)*(q-1) = "++(show phi) putStrLn $ "Factors of "++(show phi)++" = "++(show (factors phi)) let ps = factors ((p-1)*(q-1)) let e = head [ x | x <- primes, not (x `elem` ps) ] putStrLn $ "We pick e (relatively prime to phi) = "++(show e) putStrLn $ "gcd e phi (expect 1) = "++(show (gcd e phi)) let d = mod_inv phi e putStrLn $ "e*d `mod` phi (expect 1) = " ++ (show ( e*d `mod` phi)) let enc m = m^e `mod` n let dec c = c^d `mod` n let m = 99 putStrLn $ "Message = "++(show m) let c = enc m putStrLn $ "Ciphertext = "++(show c) let m' = dec c putStrLn $ "Decrypted ciphertext = "++(show m') -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- a test wrapper; run it like this -- #> test -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++
jack793/Haskell-examples
Flipped/ceaser.hs
gpl-3.0
11,846
15
16
2,290
2,088
1,201
887
82
2
-- | -- Copyright : © 2009 CNRS - École Polytechnique - INRIA -- License : GPL -- -- A representation of module names and associated functions to map module -- names to source files and vice-versa. Qualified names, as required in the -- presence of modules, are also defined here. module Dedukti.Module ( -- * Data types Hierarchy(..), MName -- * Exceptions , InvalidModuleName(..) -- * Functions , hierarchy, toList , pathFromModule, moduleFromPath , srcPathFromModule, objPathFromModule, ifacePathFromModule -- * Qualified names , Qid, qid_qualifier, qid_stem, qid_suffix , qid, (.$), provenance, qualify, unqualify -- * Atoms , Atom , fromAtom, toAtom ) where import Dedukti.DkM import System.FilePath import Data.Char (isAlpha, isAlphaNum) import qualified Data.ByteString.Lazy.Char8 as B import qualified Data.ByteString as BS (concat) import Text.PrettyPrint.Leijen import qualified StringTable.Atom as Atom import StringTable.Atom (Atom) -- | A generic stack-like datatype for representing hierarchical -- names. Names components are hash consed (or "interned") for -- equality test in constant time and a smaller memory footprint. data Hierarchy = !Hierarchy :. {-# UNPACK #-} !Atom | Root deriving (Eq, Ord, Show) type MName = Hierarchy newtype InvalidModuleName = InvalidModuleName String deriving (Eq, Ord, Typeable) instance Show InvalidModuleName where show (InvalidModuleName name) = "invalid character in " ++ name instance Exception InvalidModuleName instance Pretty MName where pretty (Root :. x) = text (B.unpack (fromAtom x)) pretty (xs :. x) = pretty xs <> char '.' <> text (B.unpack (fromAtom x)) fromAtom :: Atom -> B.ByteString fromAtom = B.fromChunks . return . Atom.fromAtom toAtom :: B.ByteString -> Atom toAtom = Atom.toAtom . BS.concat . B.toChunks hierarchy :: [B.ByteString] -> Hierarchy hierarchy = f . reverse where f [] = Root f (x:xs) = f xs :. toAtom x toList :: Hierarchy -> [B.ByteString] toList = reverse . f where f Root = [] f (xs :. x) = fromAtom x : f xs -- | Raise an exception if module name component is a valid identifier. check :: String -> String check cmpt@(x:xs) | isAlpha x, and (map (\x -> isAlphaNum x || elem x "_-+~") xs) = cmpt | otherwise = throw $ InvalidModuleName cmpt pathFromModule :: String -> MName -> FilePath pathFromModule ext mod = addExtension (joinPath $ map B.unpack $ toList mod) ext moduleFromPath :: FilePath -> MName moduleFromPath = hierarchy . map (B.pack . check) . splitDirectories . dropExtension srcPathFromModule :: MName -> FilePath srcPathFromModule = pathFromModule ".dk" objPathFromModule :: MName -> FilePath objPathFromModule = pathFromModule ".dko" ifacePathFromModule :: MName -> FilePath ifacePathFromModule = pathFromModule ".dki" -- | The datatype of qualified names. data Qid = Qid !Hierarchy !Atom !Hierarchy deriving (Eq, Show, Ord) qid_qualifier (Qid qual _ _) = qual qid_stem (Qid _ stem _) = stem qid_suffix (Qid _ _ suf) = suf -- | Shorthand qid introduction. qid :: B.ByteString -> Qid qid x = Qid Root (toAtom x) Root -- | Append suffix. (.$) :: Qid -> B.ByteString -> Qid (Qid qual x sufs) .$ suf = Qid qual x (sufs :. (toAtom suf)) -- | Get the module where the qid is defined, based on its qualifier. provenance :: Qid -> Maybe MName provenance (Qid Root _ _) = Nothing provenance (Qid qual _ _) = Just qual -- | Set the qualifier. qualify :: Hierarchy -> Qid -> Qid qualify qual (Qid _ stem suf) = Qid qual stem suf -- | Remove any qualifier. unqualify :: Qid -> Qid unqualify (Qid _ stem suf) = Qid Root stem suf
mboes/dedukti
Dedukti/Module.hs
gpl-3.0
3,699
1
15
751
1,048
569
479
81
2
{-# LANGUAGE ExistentialQuantification #-} module Mudblood.Trigger ( module Control.Trigger -- * The trigger event type , TriggerEvent (..) -- * Trigger functions -- ** Guards , guardLine, guardSend, guardTime, guardTelneg, guardGMCP , guardBlock, joinBlock -- ** Yielding , yieldLine, yieldSend, yieldTime -- ** Returning , returnLine, returnSend, returnTime -- ** Trigger combinators , gag, keep, keep1, pass , loopT -- * Common triggers , on -- ** Coloring , colorize ) where import Control.Trigger import Control.Monad import Data.Dynamic import Data.Monoid import Mudblood.Telnet import Mudblood.UI import Mudblood.Text import Mudblood.Mapper.Map import Data.GMCP data TriggerEvent = LineTEvent AttrString -- ^ Emitted when a line was received from the host | SendTEvent String -- ^ Emitted when the user wants to send a line of input | TelnetTEvent TelnetNeg -- ^ Emitted when a telnet negotiation is received | GMCPTEvent GMCP -- ^ Emitted when a GMCP telneg is received | TimeTEvent Int -- ^ Emitted every second. Argument is current POSIX timestamp. | BellTEvent -- ^ Emitted on bell character. | NilTEvent -- ^ Dummy event type | CustomTEvent String -- ^ User defined events deriving (Eq, Show) guardLine :: (MonadPlus m) => TriggerEvent -> m AttrString guardLine ev = case ev of LineTEvent s -> return s _ -> mzero guardSend :: (MonadPlus m) => TriggerEvent -> m String guardSend ev = case ev of SendTEvent s -> return s _ -> mzero guardTime :: (MonadPlus m) => TriggerEvent -> m Int guardTime ev = case ev of TimeTEvent s -> return s _ -> mzero guardTelneg :: (MonadPlus m) => TriggerEvent -> m TelnetNeg guardTelneg ev = case ev of TelnetTEvent s -> return s _ -> mzero guardGMCP :: (MonadPlus m) => TriggerEvent -> m GMCP guardGMCP ev = case ev of GMCPTEvent gmcp -> return gmcp _ -> mzero guardBlock :: (Monad m) => TriggerEvent -> TriggerM m [TriggerEvent] TriggerEvent [AttrString] guardBlock ev = readBlock [] ev where readBlock acc ev = case ev of TelnetTEvent (TelnetNeg (Just CMD_EOR) Nothing []) -> return acc LineTEvent s -> yieldT [ev] >>= readBlock (acc ++ [s]) _ -> failT joinBlock :: [AttrString] -> AttrString joinBlock [] = mempty joinBlock [a] = a joinBlock (x:xs) = foldr joinBlock' x xs where joinBlock' x a = a <> (toAS " ") <> x -- | Yield a line event yieldLine :: (Monad m) => AttrString -> TriggerM m [TriggerEvent] r r yieldLine x = yieldT [LineTEvent x] -- | Yield a send event yieldSend :: (Monad m) => String -> TriggerM m [TriggerEvent] r r yieldSend x = yieldT [SendTEvent x] -- | Yield a timer event yieldTime :: (Monad m) => Int -> TriggerM m [TriggerEvent] r r yieldTime x = yieldT [TimeTEvent x] -- | Return a line event returnLine :: (Monad m) => AttrString -> m [TriggerEvent] returnLine x = return [LineTEvent x] -- | Return a send event returnSend :: (Monad m) => String -> m [TriggerEvent] returnSend x = return [SendTEvent x] -- | Return a timer event returnTime :: (Monad m) => Int -> m [TriggerEvent] returnTime x = return [TimeTEvent x] -- | Discard the result of a trigger gag :: (Monad m) => (a -> m b) -> (a -> m [c]) gag a ev = a ev >> return [] -- | Discard the result of a trigger and return its input as a list keep :: (Monad m) => (a -> m b) -> (a -> m [a]) keep a ev = a ev >> return [ev] -- | Discard the result of a trigger and return its input keep1 :: (Monad m) => (a -> m b) -> (a -> m a) keep1 a ev = a ev >> return ev pass :: (Monad m) => m () -> a -> m a pass m x = m >> return x -- | If the first trigger succeeds, subsequent events will run the second trigger -- until one of these fails. loopT :: (Monad m) => (a -> TriggerM m [a] a [a]) -> (a -> TriggerM m [a] a [a]) -> (a -> TriggerM m [a] a [a]) loopT startt nextt = startt >=> yieldT >=> loop where loop x = ((nextt >=> yieldT >=> loop) x) `mplus` (return [x]) -- | Colorize an AttrString colorize :: (Monad m) => Color -> AttrString -> TriggerM m i y [TriggerEvent] colorize c x = returnLine $ setFg c x on :: (Monad m) => (a -> m b) -> m c -> a -> m [a] on trig action ev = do trig ev action return [ev]
talanis85/mudblood
src/Mudblood/Trigger.hs
gpl-3.0
4,527
0
14
1,255
1,447
769
678
94
3
-- | Raw SQL insert commands module Tweet.Store.Raw.Insert where token :: String token = "insert into Token (access_token, token_type) values (?, ?);" user :: String user = "insert into User (id, name, screen_name, spammer) values (?, ?, ?, ?);" tweet :: String tweet = "insert into Tweet (text, user_id, spam) values (?, ?, ?);"
cbowdon/TweetFilter
Tweet/Store/Raw/Insert.hs
gpl-3.0
333
0
4
57
39
25
14
7
1
-- | StatusBar texts {-# OPTIONS -O0 #-} {-# LANGUAGE TemplateHaskell, DerivingVia #-} module Lamdu.I18N.StatusBar where import qualified Control.Lens as Lens import qualified Data.Aeson.TH.Extended as JsonTH import GUI.Momentu.Animation.Id (ElemIds) import Lamdu.Prelude data StatusBar a = StatusBar { _sbStatusBar :: a , _sbAnnotations :: a , _sbTypes :: a , _sbNone :: a , _sbSwitchAnnotations :: a , _sbBranch :: a , _sbSwitchHelp :: a , _sbHelp :: a , _sbSwitchLanguage :: a , _sbTheme :: a , _sbSwitchTheme :: a , _sbExtraOptions :: a } deriving stock (Generic, Generic1, Eq, Functor, Foldable, Traversable) deriving anyclass ElemIds deriving Applicative via (Generically1 StatusBar) Lens.makeLenses ''StatusBar JsonTH.derivePrefixed "_sb" ''StatusBar
lamdu/lamdu
src/Lamdu/I18N/StatusBar.hs
gpl-3.0
845
0
8
193
196
121
75
-1
-1
module Examples.CRC.QDSL where import Prelude hiding (Int,div,foldl) import QFeldspar.QDSL import Examples.Prelude.QDSL crcVec :: Qt (Vec Word32 -> Word32) crcVec = [|| $$foldl $$updCrc 0 ||] updCrc :: Qt (Word32 -> Word32 -> Word32) updCrc = [|| \ cc -> \ ch -> xor (xor ($$tbl ((xor (xor cc 0xFFFFFFFF) ch) .&. 0xff)) (shfRgt (xor cc 0xFFFFFFFF) 8)) 0xFFFFFFFF ||] tbl :: Qt (Word32 -> Word32) tbl = [|| \ i -> ixArr hashTable i ||] crc :: Qt (Ary Word32 -> Word32) crc = [|| \ a -> $$crcVec ($$fromArr a) ||]
shayan-najd/QFeldspar
Examples/CRC/QDSL.hs
gpl-3.0
599
6
21
179
257
141
116
-1
-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.Ml.Projects.Locations.Studies.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a study. -- -- /See:/ <https://cloud.google.com/ml/ AI Platform Training & Prediction API Reference> for @ml.projects.locations.studies.get@. module Network.Google.Resource.Ml.Projects.Locations.Studies.Get ( -- * REST Resource ProjectsLocationsStudiesGetResource -- * Creating a Request , projectsLocationsStudiesGet , ProjectsLocationsStudiesGet -- * Request Lenses , plsgXgafv , plsgUploadProtocol , plsgAccessToken , plsgUploadType , plsgName , plsgCallback ) where import Network.Google.MachineLearning.Types import Network.Google.Prelude -- | A resource alias for @ml.projects.locations.studies.get@ method which the -- 'ProjectsLocationsStudiesGet' request conforms to. type ProjectsLocationsStudiesGetResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GoogleCloudMlV1__Study -- | Gets a study. -- -- /See:/ 'projectsLocationsStudiesGet' smart constructor. data ProjectsLocationsStudiesGet = ProjectsLocationsStudiesGet' { _plsgXgafv :: !(Maybe Xgafv) , _plsgUploadProtocol :: !(Maybe Text) , _plsgAccessToken :: !(Maybe Text) , _plsgUploadType :: !(Maybe Text) , _plsgName :: !Text , _plsgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsStudiesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plsgXgafv' -- -- * 'plsgUploadProtocol' -- -- * 'plsgAccessToken' -- -- * 'plsgUploadType' -- -- * 'plsgName' -- -- * 'plsgCallback' projectsLocationsStudiesGet :: Text -- ^ 'plsgName' -> ProjectsLocationsStudiesGet projectsLocationsStudiesGet pPlsgName_ = ProjectsLocationsStudiesGet' { _plsgXgafv = Nothing , _plsgUploadProtocol = Nothing , _plsgAccessToken = Nothing , _plsgUploadType = Nothing , _plsgName = pPlsgName_ , _plsgCallback = Nothing } -- | V1 error format. plsgXgafv :: Lens' ProjectsLocationsStudiesGet (Maybe Xgafv) plsgXgafv = lens _plsgXgafv (\ s a -> s{_plsgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plsgUploadProtocol :: Lens' ProjectsLocationsStudiesGet (Maybe Text) plsgUploadProtocol = lens _plsgUploadProtocol (\ s a -> s{_plsgUploadProtocol = a}) -- | OAuth access token. plsgAccessToken :: Lens' ProjectsLocationsStudiesGet (Maybe Text) plsgAccessToken = lens _plsgAccessToken (\ s a -> s{_plsgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plsgUploadType :: Lens' ProjectsLocationsStudiesGet (Maybe Text) plsgUploadType = lens _plsgUploadType (\ s a -> s{_plsgUploadType = a}) -- | Required. The study name. plsgName :: Lens' ProjectsLocationsStudiesGet Text plsgName = lens _plsgName (\ s a -> s{_plsgName = a}) -- | JSONP plsgCallback :: Lens' ProjectsLocationsStudiesGet (Maybe Text) plsgCallback = lens _plsgCallback (\ s a -> s{_plsgCallback = a}) instance GoogleRequest ProjectsLocationsStudiesGet where type Rs ProjectsLocationsStudiesGet = GoogleCloudMlV1__Study type Scopes ProjectsLocationsStudiesGet = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsStudiesGet'{..} = go _plsgName _plsgXgafv _plsgUploadProtocol _plsgAccessToken _plsgUploadType _plsgCallback (Just AltJSON) machineLearningService where go = buildClient (Proxy :: Proxy ProjectsLocationsStudiesGetResource) mempty
brendanhay/gogol
gogol-ml/gen/Network/Google/Resource/Ml/Projects/Locations/Studies/Get.hs
mpl-2.0
4,767
5
16
1,064
694
407
287
103
1
{-# LANGUAGE FlexibleContexts #-} {- Welcome to your custom Prelude Export here everything that should always be in your library scope For more info on what is exported by Protolude check: https://github.com/sdiehl/protolude/blob/master/Symbols.md -} module Lib.Prelude ( readDef ) where import Data.String.Conversions (ConvertibleStrings, convertString) import Protolude as Exports import Text.Read (readMaybe) readDef :: (ConvertibleStrings s [Char], Read a) => a -> s -> a readDef defVal string = fromMaybe defVal $ readMaybe $ convertString string
fros1y/patent-api
src/Lib/Prelude.hs
agpl-3.0
563
0
7
85
99
57
42
10
1
type BString = [Bool] type Schema = [Maybe Bool] matchesSchema::Schema->BString->Bool matchesSchema [] [] = True matchesSchema (Nothing:schr) (str:strr) = matchesSchema schr strr matchesSchema ((Just sch):schr) (str:strr) | sch /= str = False | otherwise = matchesSchema schr strr orderSchema::Schema->Int orderSchema sch = orderSchema_rec sch 0 orderSchema_rec [] acc = acc orderSchema_rec (Nothing:schr) acc = orderSchema_rec schr acc orderSchema_rec (sch:schr) acc = orderSchema_rec schr (acc+1) mySchema = [Just True,Just False,Nothing,Just True,Nothing] myBString_1 = [True,False,False,True,True] myBString_2 = [True,False,False,False,True]
Crazycolorz5/Haskell-Code
schema.hs
unlicense
658
0
9
88
286
153
133
16
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Lib.Text ( showT , safeDecode , (+@) , removeTrailingNewLine , leadingZeros , lineSplit , lineSplitAfter ) where ------------------------------------------------------------------------------------ import Data.ByteString (ByteString) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) ------------------------------------------------------------------------------------ removeTrailingNewLine :: Text -> Text removeTrailingNewLine x = let n = T.length x - 1 in if n >= 0 && T.index x n == '\n' then T.take n x else x (+@) :: Text -> Text -> Text (+@) a b = T.concat [a, b] showT :: Show a => a -> Text showT = T.pack . show leadingZeros :: Int -> Text -> Text leadingZeros n t = T.concat [ T.pack(take (n - (T.length t)) $ repeat '0'), t ] safeDecode :: ByteString -> Text safeDecode = decodeUtf8With lenientDecode infixr 2 +@ -- | A line split function that preserves all character, unlike -- the standard 'lines' function, where `lines "foo\n" == lines "foo"`. lineSplit :: Text -> [Text] lineSplit t = reverse $ r $ reverse $ map f z where s = T.splitOn ("\n") t n = length s z = zip s (map (== n) [1..]) f (x, False) = T.concat [x, "\n"] f (x, True) = x r ("":xs) = xs r xs = xs -- | Another line split that preserves all characters, but this version -- | always puts the break after the newline. lineSplitAfter :: Text -> [Text] lineSplitAfter t = z where s = T.splitOn ("\n") t n = length s z = map (\(x, y) -> x +@ y) $ zip s (map (\x -> if x == n then "" else "\n") [1..n])
kernelim/gitomail
src/Lib/Text.hs
apache-2.0
1,926
0
15
553
577
321
256
42
3
{-# LANGUAGE OverloadedStrings #-} module Fs (getFullPath, Location(..)) where import Control.Monad (forM, msum) import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath ((</>), takeFileName) import Prelude data Location = Data | Vendor | Any deriving Show -- Link prefix syntax does not seem to follow the PCGen documentation -- (no extant samples use '&'), and futhermore there seem to be some -- links that don't have a location prefix. So screw it: let's just -- recursively look for the filename. getFullPath :: FilePath -> IO FilePath getFullPath x = do fullPath <- findFile "." $ takeFileName x case fullPath of Just f -> return f Nothing -> error $ "referenced file " ++ show x ++ " could not be found" findFile :: FilePath -> FilePath -> IO (Maybe FilePath) findFile location target = do names <- getDirectoryContents location let validFiles = filter (`notElem` [".", ".."]) names results <- forM validFiles $ \name -> do let path = location </> name isDirectory <- doesDirectoryExist path if isDirectory then findFile path target else return (if name == target then Just path else Nothing) return $ msum results
gamelost/pcgen-rules
src/Fs.hs
apache-2.0
1,209
0
16
237
315
166
149
24
3
module CoinsInARow.A276163Spec (main, spec) where import Test.Hspec import CoinsInARow.A276163 (a276163) main :: IO () main = hspec spec spec :: Spec spec = describe "A276163" $ it "correctly computes the first 5 elements" $ map a276163 [1..5] `shouldBe` expectedValue where expectedValue = [1, 1, 2, 4, 5]
peterokagey/haskellOEIS
test/CoinsInARow/A276163Spec.hs
apache-2.0
325
0
8
65
109
62
47
10
1
{-# LANGUAGE OverloadedStrings #-} module Model.Challenge where import Control.Applicative import Control.Monad import Data.Aeson import Data.ByteString (ByteString) import Data.Time (UTCTime) import qualified CouchDB.DBContract as DBContract import Model.UUID (UUID (..)) import Model.Contract (Contract (..)) data Challenge = Challenge { uuid :: Maybe UUID, revision :: Maybe ByteString, wasAnswered :: Bool, contractUUID :: UUID, answer :: ByteString, expiresAt :: UTCTime } deriving (Eq, Show) new :: UUID -> ByteString -> UTCTime -> Challenge new = Challenge Nothing Nothing False contract :: Challenge -> IO Contract contract = DBContract.findByUUID . contractUUID instance FromJSON Challenge where parseJSON (Object v) = Challenge <$> v .: "_id" <*> v .: "_rev" <*> v .: "wasAnswered" <*> v .: "contractUUID" <*> v .: "answer" <*> v .: "expiresAt" parseJSON _ = mzero instance ToJSON Challenge where toJSON (Challenge _ _ wa cu a ea) = object [ "type" .= ("challenge" :: ByteString) , "wasAnswered" .= wa , "contractUUID" .= cu , "answer" .= a , "expiresAt" .= ea ]
alexandrelucchesi/pfec
server-common/src/Model/Challenge.hs
apache-2.0
1,518
0
17
606
346
194
152
38
1
-- Copyright (c) 2014-2015 Jonathan M. Lange <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- The dreaded 'utils' module of death. {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Utils ( isSubListOf, ) where import BasicPrelude isSubListOf :: (Eq a, Ord a) => [a] -> [a] -> Bool isSubListOf xs ys = isSubListOf' (sort xs) (sort ys) isSubListOf' :: Eq a => [a] -> [a] -> Bool isSubListOf' (_:_) [] = False isSubListOf' [] _ = True isSubListOf' (x:xs) ys = (x `elem` ys) && isSubListOf' xs (delete x ys)
jml/haverer
tests/Utils.hs
apache-2.0
1,076
0
8
196
190
110
80
11
1
range :: [Integer] range = [1..100] -- cons operator onetwothree :: [Integer] onetwothree = 1 : 2 : 3 : [] hailstone :: Integer -> Integer hailstone n | n `mod` 2 == 0 = n `div` 2 | otherwise = 3*n + 1 hailstoneSeq :: Integer -> [Integer] hailstoneSeq 1 = [1] hailstoneSeq n = n : hailstoneSeq (hailstone n) -- pattern matching on lists intListLen :: [Integer] -> Integer intListLen [] = 0 -- similar pattern matchin gto tuples. Interesting! intListLen (x:xs) = 1 + intListLen xs -- pattern matching can be nested, which is super neat sumEveryTwo :: [Integer] -> [Integer] sumEveryTwo [] = [] -- who cares sumEveryTwo (x:[]) = [x] -- ignore single elements sumEveryTwo (x:(y:rest)) = x + y : sumEveryTwo rest
markmandel/cis194
src/week1/lecture/lists.hs
apache-2.0
726
1
9
145
274
150
124
18
1
module Permutations.A068424 (a068424, a068424T) where a068424T :: Integer -> Integer -> Integer a068424T n k | n < k = 0 | otherwise = product $ map (\i -> n - i) [0..k-1] a068424_row :: Integer -> [Integer] a068424_row n = map (a068424T n) [1..n] a068424_list :: [Integer] a068424_list = concatMap a068424_row [1..] a068424 :: Int -> Integer a068424 n = a068424_list !! (n - 1)
peterokagey/haskellOEIS
src/Permutations/A068424.hs
apache-2.0
391
0
10
78
171
91
80
11
1
import Data.Array md = 100000009 nmax = 5000 fact :: Array Int Integer fact = array (0, nmax) ((0, 1) : [(n, (fromIntegral n) * (fact ! (pred n))) | n <- [1 .. nmax]]) choose0 n k = (((fact ! n) `div` (fact ! k)) `div` (fact ! (n - k))) `mod` md choose n k = if k == 0 || k == n then 1 else (choo ! (pred n, pred k) + choo ! (pred n, k)) `mod` md choo = array ((0, 0), (nmax, nmax)) [((n, k), choose n k) | n <- [0 .. nmax], k <- [0 .. n]] choos n k = choo ! (n, k) nobst :: Array Int Integer nobst = array (0, nmax) ((0, 1) : (1, 1) : [(n, nobst' n) | n <- [2 .. nmax]]) nobst' n = foldl (\acc n -> (acc + n) `mod` md) 0 (map (\x -> ((nobst ! x) * (nobst ! ((n - 1) - x))) `mod` md) [0 .. (n - 1)]) nobst2 = array (0, nmax) ((0, 0) : [(ix, (sum $ map (\jx -> (nobst ! jx) * (choos ix jx)) [1 .. ix]) `mod` md) | ix <- [1 .. nmax]]) --main = putStrLn (show $ map (nobst2 !) [1 .. nmax]) main = putStrLn (show $ map (nobst !) [1 .. 50]) --tst = do -- nstr <- getLine -- (putStrLn . show . (nobst2 !) . read) nstr -- --main = do -- tstr <- getLine -- mapM_ (const tst) [1 .. (read tstr)]
pbl64k/HackerRank-Contests
2014-06-02-Weekly/LucyAndFlowers/laf.hs
bsd-2-clause
1,112
1
18
286
658
379
279
14
2
module Mewa.ProtocolSpec (spec) where import Mewa.Protocol import Test.Hspec spec :: Spec spec = do describe "Element by atomic number" $ it "Element by 12" $ length "ala" `shouldBe` 3
AnthillTech/mewa-sim
test-src/Mewa/ProtocolSpec.hs
bsd-2-clause
205
0
10
49
57
31
26
8
1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Database.HXournal.IDMap.Client.Communication.Multipart -- Copyright : (c) 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Database.HXournal.IDMap.Client.Communication.Multipart where import Blaze.ByteString.Builder -- import Blaze.ByteString.Builder.Char.Utf8 as BC import Data.ByteString.Lazy hiding (map) import Data.ByteString.Lazy.Char8 hiding (map) import Data.Monoid -- | -- -- class ToBuilder a where -- toBuilder :: a -> Builder -- toContentType :: a -> ContentType -- | infixl 4 <> (<>) :: Monoid a => a -> a -> a (<>) = mappend -- | startbdry :: ByteString -> Builder startbdry boundary = fromLazyByteString "--" <> fromLazyByteString boundary <> fromLazyByteString "\r\n" -- | endbdry :: ByteString -> Builder endbdry boundary = fromLazyByteString "--" <> fromLazyByteString boundary <> fromLazyByteString "--" <> fromLazyByteString "\r\n" -- | contentDisposition :: ByteString -> Builder contentDisposition name = fromLazyByteString "Content-Disposition: form-data; name=\"" <> fromLazyByteString (name `append` "\"") <> lineBreak contentDispositionFile :: ByteString -> ByteString -> Builder contentDispositionFile name fname = fromLazyByteString ("Content-Disposition: form-data; name=\"" <> name <> "\"; filename=\"" <> fname <> "\"") <> lineBreak -- | data ContentType = TextPlain | ImageGif | ApplicationXoj | ApplicationJson deriving (Show,Eq,Ord,Enum) -- | contentType :: ContentType -> Builder contentType typ = ctypeheader <> fromLazyByteString (ctype typ) <> lineBreak where ctypeheader = fromLazyByteString "Content-Type: " ctype TextPlain = "text/plain" ctype ImageGif = "image/gif" ctype ApplicationXoj = "application/xoj" ctype ApplicationJson = "application/json" -- | lineBreak :: Builder lineBreak = fromLazyByteString "\r\n" -- | data OnePart = OnePartTextFile { fieldName :: ByteString , fileName :: ByteString , fileeContent :: ByteString } | OnePartText ByteString ByteString | OnePartGif ByteString ByteString | OnePartJson ByteString ByteString -- | toBuilder :: OnePart -> Builder toBuilder opart = ctypedispos <> ctypeheader <> lineBreak <> fromLazyByteString cnt <> lineBreak where (ctypedispos,ctypeheader,cnt) = case opart of OnePartTextFile name fname bstr -> (contentDispositionFile name fname, contentType TextPlain, bstr) OnePartText name bstr -> (contentDisposition name,contentType TextPlain,bstr) OnePartGif name bstr -> (contentDisposition name,contentType ImageGif ,bstr) OnePartJson name bstr -> (contentDisposition name,contentType ApplicationJson,bstr) -- | onepart :: ByteString -> OnePart -> Builder onepart boundary content = startbdry boundary <> toBuilder content -- | multipart :: ByteString -> [OnePart] -> Builder multipart boundary xs = mconcat (map (onepart boundary) xs) <> endbdry boundary
wavewave/hxournal-idmap-client
lib/Database/HXournal/IDMap/Client/Communication/Multipart.hs
bsd-2-clause
3,686
0
11
999
693
381
312
71
4
module Prim where import Control.Applicative import Control.Monad import Data.List import Data.Ord import Graphics.UI.GLUT import System.Random import Text.Printf import Data.Bits((.|.),(.&.)) import qualified Data.Bits as DB type Val = Double type ID = Int data Vec = Vec { vX :: !Val , vY :: !Val } deriving (Show,Eq,Ord) -- a generic physical object -- the union type referenced by 'oType' contains -- specific info data Obj = Obj { oId :: !ID , oPos :: !Vec -- position , oOr :: !Val -- orientation (rotation) , oVel :: !Vec -- velocity , oDr :: !Val -- change in rotation , oMass :: !Val -- mass , oRadius :: !Val -- bounding box for collisions , oColor :: !(Color3 GLfloat) , oType :: !ObjType -- object-specific info } deriving Show data ObjType = OTRock | OTShip !Ship deriving Show data Ship = Ship { sHp :: !Val , sFuel :: !Val , sCargo :: !Val } deriving Show data GSt = GSt { gTick :: !Int , gExit :: !Bool -- , gLastTick :: !Int , gTickRate :: !Int -- in days , gOrders :: ![(ID,Input)] , gInpsDown :: !InputSet , gRunning :: !Bool , gSize :: (Val,Val) , gNextId :: !ID , gG :: StdGen , gSelected :: [ID] , gObjs :: ![Obj] } deriving Show oShipModifyFuel :: Obj -> (Val -> Val) -> Obj oShipModifyFuel o f = case oType o of OTShip s -> o { oType = OTShip (s { sFuel = clamp 0 100 (f (sFuel s)) }) } _ -> o oShipFuel :: Obj -> Val oShipFuel o = case oType o of OTShip s -> sFuel s _ -> 0 class HasPos p where pos :: p -> Vec instance HasPos Vec where pos = id instance HasPos Obj where pos = oPos oIntersect :: Obj -> Obj -> Bool oIntersect o1 o2 = dist2 o1 o2 < dr*dr where dr = oRadius o1 + oRadius o2 gConst :: Val gConst = 6.67384e-11 -- gConst = 0.00001 -- dScale :: Val -- 1 world unit is dScale miles -- dScale = 10 (xMIN,xMAX) = (-10,10) :: (Val,Val) (yMIN,yMAX) = (-10,10) :: (Val,Val) (vMIN,vMAX) = (-1,1) :: (Val,Val) clamp :: Ord a => a -> a -> a -> a clamp lo hi x | x < lo = lo | x > hi = hi | otherwise = x -- clamp a velocity vclamp :: Vec -> Vec vclamp = vmap (clamp vMIN vMAX) (clamp vMIN vMAX) -- clamp a position to world coordinates -- wclamp :: Vec -> Vec -- wclamp = vmap (clamp xMIN xMAX) (clamp yMIN yMAX) fmtGInfo :: GSt -> String fmtGInfo g = day_line ++ "\n" ++ tick_line ++ "\n" ++ sel_line where day_line = printf "tick: %10d" (gTick g) tick_line = printf "tick-rate: %10d ticks/fr %s" (gTickRate g) tstr where tstr = if gRunning g then "" else "(stepping)" sel_line = "selected: " ++ case gSelected g of [] -> "(nothing)" ids -> show ids color3f :: GLfloat -> GLfloat -> GLfloat -> IO () color3f r g b = color $ Color3 r g (b :: GLfloat) vertex3f :: GLfloat -> GLfloat -> GLfloat -> IO () vertex3f x y z = vertex $ Vertex3 x y z color3fv :: (GLfloat,GLfloat,GLfloat) -> IO () color3fv (r,g,b) = color $ Color3 r g b vertex3fv :: (GLfloat,GLfloat,GLfloat) -> IO () vertex3fv (x,y,z) = vertex $ Vertex3 x y z vecTrans :: Vec -> IO () vecTrans (Vec x y) = translate $ Vector3 (vToF x) (vToF y) 0 uscale :: Val -> IO () uscale n = scale (vToF n) (vToF n) 1 -- frV :: Val -> GLfloat frV :: Fractional b => Val -> b frV = realToFrac vToF :: Val -> GLfloat vToF = frV fmtObj :: Obj -> String fmtObj o = printf "#%d (m=%.3f),\np:(%.4f,%.4f) @%.2f\nv: <%.5f,%.5f> @%.2f" (oId o) (oMass o) px py (oOr o) vx vy (oDr o) ++ ship_info where (Vec px py) = oPos o (Vec vx vy) = oVel o ship_info = case oType o of OTShip s -> "\n" ++ printf "hp: %.1f, fuel %.1f, carg: %.1f" (sHp s) (sFuel s) (sCargo s) _ -> "" dist2 :: (HasPos a, HasPos b) => a -> b -> Val dist2 o1 o2 = dx * dx + dy * dy where (Vec p1x p1y,Vec p2x p2y) = (pos o1, pos o2) (dx,dy) = (p2x - p1x, p2y - p1y) vmap :: (Val -> Val) -> (Val -> Val) -> Vec -> Vec vmap f g (Vec x y) = Vec (f x) (g y) -- vec scale and add infixl 6 .+. (.+.) :: Vec -> Vec -> Vec (.+.) (Vec x1 y1) (Vec x2 y2) = Vec (x1+x2) (y1+y2) infixl 6 .-. (.-.) :: Vec -> Vec -> Vec (.-.) (Vec x1 y1) (Vec x2 y2) = Vec (x1-x2) (y1-y2) infixl 7 .*. (.*.) :: Val -> Vec -> Vec (.*.) s (Vec x y) = Vec (s*x) (s*y) vsum :: [Vec] -> Vec vsum vs = Vec (csum vX) (csum vY) where csum f = sum $ map f vs selectNearestIds :: GSt -> Vec -> [ID] selectNearestIds g = map oId . selectNearestObjs g selectNearestObjs :: GSt -> Vec -> [Obj] selectNearestObjs g v = map snd $ sortBy (comparing fst) $ filter (\(d2,o) -> d2 <= 0.1) $ map (\o -> (dist2 v o, o)) (gObjs g) data Input = ILeft | IRight | IThrust | IBrake | IShield | IShoot deriving (Eq,Show,Enum) newtype InputSet = IS Int deriving Eq ipEmpty :: InputSet ipEmpty = IS 0 ipAdd :: InputSet -> Input -> InputSet ipAdd (IS bits) i = IS (bits .|. bit) where bit = 1 `DB.shiftL` fromEnum i ipRemove :: InputSet -> Input -> InputSet ipRemove (IS bits) i = IS (bits .&. DB.complement bit) where bit = 1 `DB.shiftL` fromEnum i ipShow :: InputSet -> String ipShow = ("ipFromList "++) . show . ipToList ipToList :: InputSet -> [Input] ipToList (IS bits) = filter (DB.testBit bits . fromEnum) [ILeft ..] instance Show InputSet where show = ipShow orToV :: Val -> Vec orToV o = Vec (cos o) (sin o)
trbauer/gravity
src/Prim.hs
bsd-2-clause
5,383
0
18
1,419
2,274
1,227
1,047
214
3
module Noobing.Experimenting.List ( sortPermutations ) where import Data.List sortPermutations :: (Ord a) => [a] -> [a] sortPermutations l = sort $ concat $ permutations $ l
markmq/Noobing
src/Noobing/Experimenting/List.hs
bsd-3-clause
177
0
7
29
61
35
26
5
1
module Main where import Control.Applicative ((<$>), (<|>)) import Data.ByteString as B (readFile) import Data.Time.Calendar (Day, fromGregorian) import Data.Word (Word8) import System.Environment (getArgs) import qualified Data.Attoparsec.Binary as A (anyWord16le, anyWord32le) import qualified Data.Attoparsec.ByteString as A ( Parser , anyWord8 , parseOnly , take , word8 ) main :: IO () main = do args <- getArgs case args of (x:_) -> B.readFile x >>= print . A.parseOnly xbase _ -> error "Please supply a .dbf file as the first arg." data DBF = DBF { version :: Version , lastUpdate :: Day , numRecords :: Int , lengthHeader :: Int , lengthRecords :: Int , incompleteTransaction :: Bool , encrypted :: Bool , mdxFlag :: Word8 , languageDriver :: LanguageDriver } deriving (Show) xbase :: A.Parser DBF xbase = do version' <- versionParser lastUpdate' <- lastUpdateParser numRecords' <- numRecordsParser lengthHeader' <- lengthHeaderParser lengthRecords' <- lengthRecordsParser reservedParser incompleteTransaction' <- incompleteTransactionParser encrypted' <- encryptedParser freeRecordThreadParser multiUserParser mdxFlag' <- mdxFlagParser languageDriver' <- languageDriverParser return $ DBF version' lastUpdate' numRecords' lengthHeader' lengthRecords' incompleteTransaction' encrypted' mdxFlag' languageDriver' versionParser :: A.Parser Version versionParser = toEnum . fromIntegral <$> A.anyWord8 -- Little-endian; Year value has a range within 0x0-0xFF, and 1900 is added to -- that value. Therefore the date range is 1900-2155. lastUpdateParser :: A.Parser Day lastUpdateParser = do year <- (+ 1900) . fromIntegral <$> A.anyWord8 month <- fromIntegral <$> A.anyWord8 day <- fromIntegral <$> A.anyWord8 return $ fromGregorian year month day numRecordsParser :: A.Parser Int numRecordsParser = fromIntegral <$> A.anyWord32le lengthHeaderParser :: A.Parser Int lengthHeaderParser = fromIntegral <$> A.anyWord16le -- Sum of lengths of all fields + 1 (deletion flag), so - 1 from the field -- value. lengthRecordsParser :: A.Parser Int lengthRecordsParser = (subtract 1) . fromIntegral <$> A.anyWord16le -- Reserved for dBASE IV (value is 0x0000). Ignored. reservedParser :: A.Parser () reservedParser = A.anyWord16le >> return () -- For dBASE IV. incompleteTransactionParser :: A.Parser Bool incompleteTransactionParser = (A.word8 0x00 >> return False) <|> (A.word8 0x01 >> return True) -- For dBASE IV. encryptedParser :: A.Parser Bool encryptedParser = (A.word8 0x00 >> return False) <|> (A.word8 0x01 >> return True) -- Free record thread. (Reserved for LAN only). Ignored. freeRecordThreadParser :: A.Parser () freeRecordThreadParser = A.take 4 >> return () -- Reserved for multi-user dBASE; (dBASE III+ - ) multiUserParser :: A.Parser () multiUserParser = A.take 8 >> return () -- Little-endian; MDX flag (dBASE IV). mdxFlagParser :: A.Parser Word8 mdxFlagParser = A.anyWord8 languageDriverParser :: A.Parser LanguageDriver languageDriverParser = toEnum . fromIntegral <$> A.anyWord8 data Version = FoxBase -- FoxBase | NoDBT -- File without DBT | DBASEIVNoMemo -- dBASE IV w/o memo file | DBASEVNoMemo -- dBASE V w/o memo file | VISUALOBJECTSNoMemo -- VISUAL OBJECTS (first 1.0 versions) for -- the Dbase III files w/o memo file | VisualFoxPro | VisualFoxProDBC -- Visual FoxPro w. DBC | VisualFoxProAutoInc -- Visual FoxPro w. AutoIncrement field | DBVMemo -- .dbv memo var size (Flagship) | DBASEIVMemo -- dBASE IV with memo | DBT -- File with DBT | DBASEIIIMemo -- dBASE III+ with memo file | VISUALOBJECTSMemo -- VISUAL OBJECTS (first 1.0 versions) for -- the Dbase III files (NTX clipper driver) -- with memo file | DBASEIVSQL -- dBASE IV w. SQL table | DBVAndDBTMemo -- .dbv and .dbt memo (Flagship) | ClipperSIXSMTMemo -- Clipper SIX driver w. SMT memo file. Note! -- Clipper SIX driver sets lowest 3 bytes to -- 110 in descriptor of crypted databases. -- So, 3->6, 83h->86h, F5->F6, E5->E6 etc. | FoxProMemo -- FoxPro w. memo file | FoxProUnknown -- FoxPro ??? | UnknownVersion deriving (Show) instance Enum Version where toEnum 0x02 = FoxBase toEnum 0x03 = NoDBT toEnum 0x04 = DBASEIVNoMemo toEnum 0x05 = DBASEVNoMemo toEnum 0x07 = VISUALOBJECTSNoMemo toEnum 0x30 = VisualFoxPro -- 0x30 also == VisualFoxProDBC toEnum 0x31 = VisualFoxProAutoInc toEnum 0x43 = DBVMemo toEnum 0x7B = DBASEIVMemo toEnum 0x83 = DBT -- Matches the above, and there is no factor to discern between the two, so -- just assume every field that matches 83 is DBT: -- toEnum 0x83 = DBASEIIIMemo toEnum 0x87 = VISUALOBJECTSMemo toEnum 0x8B = DBASEIVMemo toEnum 0x8E = DBASEIVSQL toEnum 0xB3 = DBVAndDBTMemo toEnum 0xE5 = ClipperSIXSMTMemo toEnum 0xF5 = FoxProMemo toEnum 0xFB = FoxProUnknown toEnum _ = UnknownVersion fromEnum FoxBase = 0x02 fromEnum NoDBT = 0x03 fromEnum DBASEIVNoMemo = 0x04 fromEnum DBASEVNoMemo = 0x05 fromEnum VISUALOBJECTSNoMemo = 0x07 fromEnum VisualFoxPro = 0x30 fromEnum VisualFoxProDBC = 0x30 fromEnum VisualFoxProAutoInc = 0x31 fromEnum DBVMemo = 0x43 fromEnum DBASEIVMemo = 0x7B -- or 0x8B; what's the difference? fromEnum DBT = 0x83 fromEnum DBASEIIIMemo = 0x83 fromEnum VISUALOBJECTSMemo = 0x87 fromEnum DBASEIVSQL = 0x8E fromEnum DBVAndDBTMemo = 0xB3 fromEnum ClipperSIXSMTMemo = 0xE5 fromEnum FoxProMemo = 0xF5 fromEnum FoxProUnknown = 0xFB data LanguageDriver = DOSUSA -- DOS USA | DOSMultilingual -- DOS Multilingual | WindowsANSI -- Windows ANSI | StandardMacintosh -- Standard Macintosh | EEMSDOS -- EE MS-DOS | NordicMSDOS -- Nordic MS-DOS | RussianMSDOS -- Russian MS-DOS | IcelandicMSDOS -- Icelandic MS-DOS | KamenickyMSDOS -- Kamenicky (Cz0xec) MS-DOS | MazoviaMSDOS -- Mazovia (Polish) MS-DOS | GreekMSDOS -- Greek MS-DOS (437G) | TurkishMSDOS -- Turkish MS-DOS | RussianMacintosh -- Russian Macintosh | EasternEuropeanMacintosh -- Eastern European Macintosh | GreekMacintosh -- Greek Macintosh | WindowsEE -- Windows EE | RussianWindows -- Russian Windows | TurkishWindows -- Turkish Windows | GreekWindows -- Greek Windows | UnknownLanguageDriver deriving (Show) instance Enum LanguageDriver where toEnum 0x01 = DOSUSA toEnum 0x02 = DOSMultilingual toEnum 0x03 = WindowsANSI toEnum 0x04 = StandardMacintosh toEnum 0x64 = EEMSDOS toEnum 0x65 = NordicMSDOS toEnum 0x66 = RussianMSDOS toEnum 0x67 = IcelandicMSDOS toEnum 0x68 = KamenickyMSDOS toEnum 0x69 = MazoviaMSDOS toEnum 0x6A = GreekMSDOS toEnum 0x6B = TurkishMSDOS toEnum 0x96 = RussianMacintosh toEnum 0x97 = EasternEuropeanMacintosh toEnum 0x98 = GreekMacintosh toEnum 0xC8 = WindowsEE toEnum 0xC9 = RussianWindows toEnum 0xCA = TurkishWindows toEnum 0xCB = GreekWindows toEnum _ = UnknownLanguageDriver fromEnum DOSUSA = 0x01 fromEnum DOSMultilingual = 0x02 fromEnum WindowsANSI = 0x03 fromEnum StandardMacintosh = 0x04 fromEnum EEMSDOS = 0x64 fromEnum NordicMSDOS = 0x65 fromEnum RussianMSDOS = 0x66 fromEnum IcelandicMSDOS = 0x67 fromEnum KamenickyMSDOS = 0x68 fromEnum MazoviaMSDOS = 0x69 fromEnum GreekMSDOS = 0x6A fromEnum TurkishMSDOS = 0x6B fromEnum RussianMacintosh = 0x96 fromEnum EasternEuropeanMacintosh = 0x97 fromEnum GreekMacintosh = 0x98 fromEnum WindowsEE = 0xC8 fromEnum RussianWindows = 0xC9 fromEnum TurkishWindows = 0xCA fromEnum GreekWindows = 0xCB
chrisdotcode/antler
Main.hs
bsd-3-clause
9,451
0
13
3,327
1,578
859
719
202
2
module Data.MultiProto.Protobuf where
intolerable/multiproto
src/Data/MultiProto/Protobuf.hs
bsd-3-clause
39
0
3
4
7
5
2
1
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.Management -- Copyright : (c) Well-Typed / Tim Watson -- License : BSD3 (see the file LICENSE) -- -- Maintainer : Tim Watson <[email protected]> -- Stability : experimental -- Portability : non-portable (requires concurrency) -- -- [Management Extensions API] -- -- This module presents an API for creating /Management Agents/: -- special processes that are capable of receiving and responding to -- a node's internal system events. These /system events/ are delivered by -- the management event bus: An internal subsystem maintained for each -- running node, to which all agents are automatically subscribed. -- -- /Agents/ are defined in terms of /event sinks/, taking a particular -- @Serializable@ type and evaluating to an action in the 'MxAgent' monad in -- response. Each 'MxSink' evaluates to an 'MxAction' that specifies whether -- the agent should continue processing it's inputs or stop. If the type of a -- message cannot be matched to any of the agent's sinks, it will be discarded. -- A sink can also deliberately skip processing a message, deferring to the -- remaining handlers. This is the /only/ way that more than one event sink -- can handle the same data type, since otherwise the first /type match/ will -- /win/ every time a message arrives. See 'mxSkip' for details. -- -- Various events are published to the management event bus automatically, -- the full list of which can be found in the definition of the 'MxEvent' data -- type. Additionally, clients of the /Management API/ can publish arbitrary -- @Serializable@ data to the event bus using 'mxNotify'. All running agents -- receive all events (from the primary event bus to which they're subscribed). -- -- Agent processes are automatically registered on the local node, and can -- receive messages via their mailbox just like ordinary processes. Unlike -- ordinary @Process@ code however, it is unnecessary (though possible) for -- agents to use the base @expect@ and @receiveX@ primitives to do this, since -- the management infrastructure will continuously read from both the primary -- event bus /and/ the process' own mailbox. Messages are transparently passed -- to the agent's event sinks from both sources, so an agent need only concern -- itself with how to respond to its inputs. -- -- Some agents may wish to prioritise messages from their mailbox over traffic -- on the management event bus, or vice versa. The 'mxReceive' and -- 'mxReceiveChan' API calls do this for the mailbox and event bus, -- respectively. The /prioritisation/ these APIs offer is simply that the chosen -- data stream will be checked first. No blocking will occur if the chosen -- (prioritised) source is devoid of input messages, instead the agent handling -- code will revert to switching between the alternatives in /round-robin/ as -- usual. If messages exist in one or more channels, they will be consumed as -- soon as they're available, priority is effectively a hint about which -- channel to consume from, should messages be available in both. -- -- Prioritisation then, is a /hint/ about the preference of data source from -- which the next input should be chosen. No guarantee can be made that the -- chosen source will in fact be selected at runtime. -- -- [Management API Semantics] -- -- The management API provides /no guarantees whatsoever/, viz: -- -- * The ordering of messages delivered to the event bus. -- -- * The order in which agents will be executed. -- -- * Whether messages will be taken from the mailbox first, or the event bus. -- -- Since the event bus uses STM broadcast channels to communicate with agents, -- no message written to the bus successfully can be lost. -- -- Agents can also receive messages via their mailboxes - these are subject to -- the same guarantees as all inter-process message sending. -- -- Messages dispatched on an STM broadcast channel (i.e., management event bus) -- are guaranteed to be delivered with the same FIFO ordering guarantees that -- exist between two communicating processes, such that communication from the -- node controller's threads (i.e., MxEvent's) will never be re-ordered, but -- messages dispatched to the event bus by other processes (including, but not -- limited to agents) are only guaranteed to be ordered between one sender and -- one receiver. -- -- No guarantee exists for the ordering in which messages sent to an agent's -- mailbox will be delivered, vs messages dispatched via the event bus. -- -- Because of the above, there are no ordering guarantees for messages sent -- between agents, or for processes to agents, except for those that apply to -- messages sent between regular processes, since agents are -- implemented as such. -- -- The event bus is serial and single threaded. Anything that is published by -- the node controller will be seen in FIFO order. There are no ordering -- guarantees pertaining to entries published to the event bus by other -- processes or agents. -- -- It should not be possible to see, for example, an @MxReceived@ before the -- corresponding @MxSent@ event, since the places where we issue the @MxSent@ -- write directly to the event bus (using STM) in the calling (green) thread, -- before dispatching instructions to the node controller to perform the -- necessary routing to deliver the message to a process (or registered name, -- or typed channel) locally or remotely. -- -- [Management Data API] -- -- Both management agents and clients of the API have access to a variety of -- data storage capabilities, to facilitate publishing and consuming useful -- system information. Agents maintain their own internal state privately (via a -- state transformer - see 'mxGetLocal' et al), however it is possible for -- agents to share additional data with each other (and the outside world) -- using whatever mechanism the user wishes, e.g., acidstate, or shared memory -- primitives. -- -- [Defining Agents] -- -- New agents are defined with 'mxAgent' and require a unique 'MxAgentId', an -- initial state - 'MxAgent' runs in a state transformer - and a list of the -- agent's event sinks. Each 'MxSink' is defined in terms of a specific -- @Serializable@ type, via the 'mxSink' function, binding the event handler -- expression to inputs of only that type. -- -- Apart from modifying its own local state, an agent can execute arbitrary -- @Process a@ code via lifting (see 'liftMX') and even publish its own messages -- back to the primary event bus (see 'mxBroadcast'). -- -- Since messages are delivered to agents from both the management event bus and -- the agent processes mailbox, agents (i.e., event sinks) will generally have -- no idea as to their origin. An agent can, however, choose to prioritise the -- choice of input (source) each time one of its event sinks runs. The /standard/ -- way for an event sink to indicate that the agent is ready for its next input -- is to evaluate 'mxReady'. When this happens, the management infrastructure -- will obtain data from the event bus and process' mailbox in a round robbin -- fashion, i.e., one after the other, changing each time. -- -- [Example Code] -- -- What follows is a grossly over-simplified example of a management agent that -- provides a basic name monitoring facility. Whenever a process name is -- registered or unregistered, clients are informed of the fact. -- -- > -- simple notification data type -- > -- > data Registration = Reg { added :: Bool -- > , procId :: ProcessId -- > , name :: String -- > } -- > -- > -- start a /name monitoring agent/ -- > nameMonitorAgent = do -- > mxAgent (MxAgentId "name-monitor") Set.empty [ -- > (mxSink $ \(pid :: ProcessId) -> do -- > mxUpdateState $ Set.insert pid -- > mxReady) -- > , (mxSink $ -- > let act = -- > case ev of -- > (MxRegistered p n) -> notify True n p -- > (MxUnRegistered p n) -> notify False n p -- > _ -> return () -- > act >> mxReady) -- > ] -- > where -- > notify a n p = do -- > Foldable.mapM_ (liftMX . deliver (Reg a n p)) =<< mxGetLocal -- > -- -- The client interface (for sending their pid) can take one of two forms: -- -- > monitorNames = getSelfPid >>= nsend "name-monitor" -- > monitorNames2 = getSelfPid >>= mxNotify -- -- [Performance, Stablity and Scalability] -- -- /Management Agents/ offer numerous advantages over regular processes: -- broadcast communication with them can have a lower latency, they offer -- simplified messgage (i.e., input type) handling and they have access to -- internal system information that would be otherwise unobtainable. -- -- Do not be tempted to implement everything (e.g., the kitchen sink) using the -- management API though. There are overheads associated with management agents -- which is why they're presented as tools for consuming low level system -- information, instead of as /application level/ development tools. -- -- Agents that rely heavily on a busy mailbox can cause the management event -- bus to backlog un-GC'ed data, leading to increased heap space. Producers that -- do not take care to avoid passing unevaluated thunks to the API can crash -- /all/ the agents in the system. Agents are not monitored or managed in any -- way, and those that crash will not be restarted. -- -- The management event bus can receive a great deal of traffic. Every time -- a message is sent and/or received, an event is passed to the agent controller -- and broadcast to all agents (plus the trace controller, if tracing is enabled -- for the node). This is already a significant overhead - though profiling and -- benchmarks have demonstrated that it does not adversely affect performance -- if few agents are installed. Agents will typically use more cycles than plain -- processes, since they perform additional work: selecting input data from both -- the event bus /and/ their own mailboxes, plus searching through the set of -- event sinks (for each agent) to determine the right handler for the event. -- -- [Architecture Overview] -- -- The architecture of the management event bus is internal and subject to -- change without prior notice. The description that follows is provided for -- informational purposes only. -- -- When a node initially starts, two special, internal system processes are -- started to support the management infrastructure. The first, known as the -- /trace controller/, is responsible for consuming 'MxEvent's and forwarding -- them to the configured tracer - see "Control.Distributed.Process.Debug" for -- further details. The second is the /management agent controller/, and is the -- primary worker process underpinning the management infrastructure. All -- published management events are routed to this process, which places them -- onto a system wide /event bus/ and additionally passes them directly to the -- /trace controller/. -- -- There are several reasons for segregating the tracing and management control -- planes in this fashion. Tracing can be enabled or disabled by clients, whilst -- the management event bus cannot, since in addition to providing -- runtime instrumentation, its intended use-cases include node monitoring, peer -- discovery (via topology providing backends) and other essential system -- services that require knowledge of otherwise hidden system internals. Tracing -- is also subject to /trace flags/ that limit the specific 'MxEvent's delivered -- to trace clients - an overhead/complexity not shared by management agents. -- Finally, tracing and management agents are implemented using completely -- different signalling techniques - more on this later - which would introduce -- considerable complexity if the shared the same /event loop/. -- -- The management control plane is driven by a shared broadcast channel, which -- is written to by the agent controller and subscribed to by all agent -- processes. Agents are spawned as regular processes, whose primary -- implementation (i.e., /server loop/) is responsible for consuming -- messages from both the broadcast channel and their own mailbox. Once -- consumed, messages are applied to the agent's /event sinks/ until one -- matches the input, at which point it is applied and the loop continues. -- The implementation chooses from the event bus and the mailbox in a -- round-robin fashion, until a message is received. This polling activity would -- lead to management agents consuming considerable system resources if left -- unchecked, therefore the implementation will poll for a limitted number of -- retries, after which it will perform a blocking read on the event bus. -- ----------------------------------------------------------------------------- module Control.Distributed.Process.Management ( MxEvent(..) -- * Firing Arbitrary /Mx Events/ , mxNotify -- * Constructing Mx Agents , MxAction() , MxAgentId(..) , MxAgent() , mxAgent , mxAgentWithFinalize , MxSink() , mxSink , mxGetId , mxDeactivate , mxReady , mxSkip , mxReceive , mxReceiveChan , mxBroadcast , mxSetLocal , mxGetLocal , mxUpdateLocal , liftMX ) where import Control.Applicative import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TChan ( readTChan , writeTChan , TChan ) import Control.Distributed.Process.Internal.Primitives ( receiveWait , matchAny , matchSTM , unwrapMessage , register , whereis , die ) import Control.Distributed.Process.Internal.Types ( Process , ProcessId , Message , LocalProcess(..) , LocalNode(..) , MxEventBus(..) , unsafeCreateUnencodedMessage ) import Control.Distributed.Process.Management.Internal.Bus (publishEvent) import Control.Distributed.Process.Management.Internal.Types ( MxAgentId(..) , MxAgent(..) , MxAction(..) , ChannelSelector(..) , MxAgentState(..) , MxSink , MxEvent(..) ) import Control.Distributed.Process.Serializable (Serializable) import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader (ask) import Control.Monad.Catch (onException) import qualified Control.Monad.State as ST ( get , modify , lift , runStateT ) import Prelude -- | Publishes an arbitrary @Serializable@ message to the management event bus. -- Note that /no attempt is made to force the argument/, therefore it is very -- important that you do not pass unevaluated thunks that might crash the -- receiving process via this API, since /all/ registered agents will gain -- access to the data structure once it is broadcast by the agent controller. mxNotify :: (Serializable a) => a -> Process () mxNotify msg = do bus <- localEventBus . processNode <$> ask liftIO $ publishEvent bus $ unsafeCreateUnencodedMessage msg -------------------------------------------------------------------------------- -- API for writing user defined management extensions (i.e., agents) -- -------------------------------------------------------------------------------- -- | Return the 'MxAgentId' for the currently executing agent. -- mxGetId :: MxAgent s MxAgentId mxGetId = ST.get >>= return . mxAgentId -- | The 'MxAgent' version of 'mxNotify'. -- mxBroadcast :: (Serializable m) => m -> MxAgent s () mxBroadcast msg = do state <- ST.get liftMX $ liftIO $ atomically $ do writeTChan (mxBus state) (unsafeCreateUnencodedMessage msg) -- | Gracefully terminate an agent. -- mxDeactivate :: forall s. String -> MxAgent s MxAction mxDeactivate = return . MxAgentDeactivate -- | Continue executing (i.e., receiving and processing messages). -- mxReady :: forall s. MxAgent s MxAction mxReady = return MxAgentReady -- | Causes the currently executing /event sink/ to be skipped. -- The remaining declared event sinks will be evaluated to find -- a matching handler. Can be used to allow multiple event sinks -- to process data of the same type. -- mxSkip :: forall s. MxAgent s MxAction mxSkip = return MxAgentSkip -- | Continue exeucting, prioritising inputs from the process' own -- /mailbox/ ahead of data from the management event bus. -- mxReceive :: forall s. MxAgent s MxAction mxReceive = return $ MxAgentPrioritise Mailbox -- | Continue exeucting, prioritising inputs from the management event bus -- over the process' own /mailbox/. -- mxReceiveChan :: forall s. MxAgent s MxAction mxReceiveChan = return $ MxAgentPrioritise InputChan -- | Lift a @Process@ action. -- liftMX :: Process a -> MxAgent s a liftMX p = MxAgent $ ST.lift p -- | Set the agent's local state. -- mxSetLocal :: s -> MxAgent s () mxSetLocal s = ST.modify $ \st -> st { mxLocalState = s } -- | Update the agent's local state. -- mxUpdateLocal :: (s -> s) -> MxAgent s () mxUpdateLocal f = ST.modify $ \st -> st { mxLocalState = (f $ mxLocalState st) } -- | Fetch the agent's local state. -- mxGetLocal :: MxAgent s s mxGetLocal = ST.get >>= return . mxLocalState -- | Create an 'MxSink' from an expression taking a @Serializable@ type @m@, -- that yields an 'MxAction' in the 'MxAgent' monad. -- mxSink :: forall s m . (Serializable m) => (m -> MxAgent s MxAction) -> MxSink s mxSink act msg = do msg' <- liftMX $ (unwrapMessage msg :: Process (Maybe m)) case msg' of Nothing -> return Nothing Just m -> do r <- act m case r of MxAgentSkip -> return Nothing _ -> return $ Just r -- private ADT: a linked list of event sinks data MxPipeline s = MxPipeline { current :: !(MxSink s) , next :: !(MxPipeline s) } | MxStop -- | Activates a new agent. -- mxAgent :: MxAgentId -> s -> [MxSink s] -> Process ProcessId mxAgent mxId st hs = mxAgentWithFinalize mxId st hs $ return () -- | Activates a new agent. This variant takes a /finalizer/ expression, -- that is run once the agent shuts down (even in case of failure/exceptions). -- The /finalizer/ expression runs in the mx monad - @MxAgent s ()@ - such -- that the agent's internal state remains accessible to the shutdown/cleanup -- code. -- mxAgentWithFinalize :: MxAgentId -> s -> [MxSink s] -> MxAgent s () -> Process ProcessId mxAgentWithFinalize mxId initState handlers dtor = do let name = agentId mxId existing <- whereis name case existing of Just _ -> die "DuplicateAgentId" -- TODO: better error handling policy Nothing -> do node <- processNode <$> ask pid <- liftIO $ mxNew (localEventBus node) $ start register name pid return pid where start (sendTChan, recvTChan) = do let nState = MxAgentState mxId sendTChan initState runAgent dtor handlers InputChan recvTChan nState runAgent :: MxAgent s () -> [MxSink s] -> ChannelSelector -> TChan Message -> MxAgentState s -> Process () runAgent eh hs cs c s = runAgentWithFinalizer eh hs cs c s `onException` runAgentFinalizer eh s runAgentWithFinalizer :: MxAgent s () -> [MxSink s] -> ChannelSelector -> TChan Message -> MxAgentState s -> Process () runAgentWithFinalizer eh' hs' cs' c' s' = do msg <- getNextInput cs' c' (action, state) <- runPipeline msg s' $ pipeline hs' case action of MxAgentReady -> runAgent eh' hs' InputChan c' state MxAgentPrioritise priority -> runAgent eh' hs' priority c' state MxAgentDeactivate _ -> runAgentFinalizer eh' state MxAgentSkip -> error "IllegalState" -- MxAgentBecome h' -> runAgent h' c state getNextInput sel chan = let matches = case sel of Mailbox -> [ matchAny return , matchSTM (readTChan chan) return] InputChan -> [ matchSTM (readTChan chan) return , matchAny return] in receiveWait matches runAgentFinalizer :: MxAgent s () -> MxAgentState s -> Process () runAgentFinalizer f s = ST.runStateT (unAgent f) s >>= return . fst pipeline :: forall s . [MxSink s] -> MxPipeline s pipeline [] = MxStop pipeline (sink:sinks) = MxPipeline sink (pipeline sinks) runPipeline :: forall s . Message -> MxAgentState s -> MxPipeline s -> Process (MxAction, MxAgentState s) runPipeline _ state MxStop = return (MxAgentReady, state) runPipeline msg state MxPipeline{..} = do let act = current msg (pass, state') <- ST.runStateT (unAgent act) state case pass of Nothing -> runPipeline msg state next Just result -> return (result, state')
haskell-distributed/distributed-process
src/Control/Distributed/Process/Management.hs
bsd-3-clause
21,440
0
22
4,573
2,130
1,258
872
197
9
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} module BitD.Util.AMQP ( open , publishMsg , MsgBody(..) , declareQueuePersistent , bindQueue , Queue --, consumeMsgs , consumeMsgs' ) where #include <Imports.hs> import qualified Network.AMQP as Q import Control.Monad.Trans.Resource (ResourceT, allocate) bitdExchange :: T.Text bitdExchange = "bitd" newtype Queue = Queue T.Text open :: ResourceT IO Q.Channel open = do (_, conn) <- allocate (Q.openConnection "127.0.0.1" "/" "guest" "guest") Q.closeConnection chan <- lift $ Q.openChannel conn lift $ Q.declareExchange chan Q.newExchange { Q.exchangeName = bitdExchange , Q.exchangeType = "direct" , Q.exchangeDurable = True , Q.exchangeAutoDelete = False } return chan class MsgBody a where serialize :: SerP.Putter a deserialize :: SerG.Get a publishMsg :: (MsgBody msg) => Q.Channel -> T.Text -> msg -> IO () publishMsg chan routingKey msg = Q.publishMsg chan bitdExchange routingKey $ Q.newMsg { Q.msgBody = BSL.fromStrict $ serialize' msg , Q.msgDeliveryMode = Just Q.Persistent } declareQueuePersistent :: Q.Channel -> T.Text -> IO (Queue, Int, Int) declareQueuePersistent chan name = do (_, messageCount, consumerCount) <- Q.declareQueue chan $ Q.newQueue { Q.queueName = name , Q.queuePassive = False , Q.queueDurable = True , Q.queueExclusive = False , Q.queueAutoDelete = False } return (Queue name, messageCount, consumerCount) bindQueue :: Q.Channel -> Queue -> T.Text -> IO () bindQueue chan (Queue name) routingKey = Q.bindQueue chan name bitdExchange routingKey deserialize' :: MsgBody a => BS.ByteString -> a deserialize' = either error id . SerG.runGet deserialize serialize' :: MsgBody a => a -> BS.ByteString serialize' k = SerP.runPut (serialize k) --consumeMsgs :: Q.Channel -> T.Text -> IO consumeMsgs' :: (MsgBody msg) => Q.Channel -> Queue -> ((IO (), msg) -> out) -> PC.Output out -> IO () consumeMsgs' chan (Queue name) f output = M.void $ Q.consumeMsgs chan name Q.Ack (M.void . STM.atomically . PC.send output . f . extract) where extract (msg,env) = (Q.ackEnv env, deserialize' $ BSL.toStrict $ Q.msgBody msg) -- consumeMsgs :: (MsgBody msg) => Q.Channel -> Queue -> P.Producer (IO (), msg) IO () -- consumeMsgs chan queue = do -- --(output, input, seal) <- lift $ PC.spawn' PC.Unbounded -- (output, input) <- lift $ PC.spawn PC.Unbounded -- lift $ consumeMsgs' chan queue id output -- PC.fromInput input
benma/bitd
src/BitD/Util/AMQP.hs
bsd-3-clause
3,339
0
13
1,307
760
407
353
48
1
module Color ( Color, ) where import Data.Function (on) import Data.Interpolate (Interpolate(interpolate)) import Rgb (Rgb, RgbLike(fromRgb, toRgb)) newtype Color = RgbColor Rgb deriving (Eq, Ord) instance Interpolate Color where interpolate c1 c2 = fromRgb . (interpolate `on` toRgb) c1 c2 instance RgbLike Color where fromRgb = RgbColor toRgb (RgbColor rgb) = rgb
thomaseding/rows
src/Color.hs
bsd-3-clause
396
0
9
82
133
78
55
12
0
-- | -- Module : Crypto.Hash.SHA256 -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : unknown -- -- Module containing the binding functions to work with the -- SHA256 cryptographic hash. -- {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} module Crypto.Hash.SHA256 ( SHA256 (..) ) where import Crypto.Hash.Types import Foreign.Ptr (Ptr) import Data.Data import Data.Typeable import Data.Word (Word8, Word32) -- | SHA256 cryptographic hash algorithm data SHA256 = SHA256 deriving (Show,Data,Typeable) instance HashAlgorithm SHA256 where type HashBlockSize SHA256 = 64 type HashDigestSize SHA256 = 32 type HashInternalContextSize SHA256 = 192 hashBlockSize _ = 64 hashDigestSize _ = 32 hashInternalContextSize _ = 192 hashInternalInit = c_sha256_init hashInternalUpdate = c_sha256_update hashInternalFinalize = c_sha256_finalize foreign import ccall unsafe "cryptonite_sha256_init" c_sha256_init :: Ptr (Context a)-> IO () foreign import ccall "cryptonite_sha256_update" c_sha256_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO () foreign import ccall unsafe "cryptonite_sha256_finalize" c_sha256_finalize :: Ptr (Context a) -> Ptr (Digest a) -> IO ()
tekul/cryptonite
Crypto/Hash/SHA256.hs
bsd-3-clause
1,492
0
10
353
284
160
124
28
0
module Zero.KeyFetchToken.Handlers ( -- * Auth keyFetchTokenAuth , keyFetchTokenHandler -- * Routes , accountKeys ) where import Control.Monad.IO.Class (liftIO) import Data.Aeson import Data.Maybe import qualified Data.Text as T import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy.Char8 as L8 import Network.Wai (Request, lazyRequestBody) import qualified Network.Hawk.Server as Hawk import qualified Network.Hawk.Server.Nonce as Hawk import Network.Hawk.Internal.Types (HeaderArtifacts(..)) import Network.Hawk.Client (ClientId, Key(..), HawkAlgo(..), SHA256(..)) import Servant.Server.Experimental.Auth import Servant import Zero.Persistence import Zero.KeyFetchToken.Internal import Zero.KeyFetchToken.Model import Zero.KeyFetchToken.State import Zero.Token.Internal ------------------------------------------------------------------------------ -- Auth Handlers ------------------------------------------------------------------------------ -- | Verifies the provided keyfetch token (HAWK) keyFetchTokenAuth :: SessionId -> Connection -> ClientId -> IO (Either String (Hawk.Credentials, Text)) keyFetchTokenAuth sid conn tokenId = do putStrLn ("Fetching keyFetchToken where tokenId = " ++ show tokenId) maybeSessionToken <- getKeyFetchTokenById sid conn tokenId case maybeSessionToken of Just Token{..} -> do let key = B8.pack (T.unpack t_hmacKey) return $ Right (Hawk.Credentials (Key key) (HawkAlgo SHA256), t_user) Nothing -> return $ Left "No keyFetchToken was found where one was expected" -- | The server handler keyFetchTokenHandler :: SessionId -> Connection -> AuthHandler Request KeyFetchTokenState keyFetchTokenHandler sid conn = mkAuthHandler handler where handler req = liftIO $ handlerIO sid conn req handlerIO sid conn req = do opt <- Hawk.nonceOptsReq 60 res <- Hawk.authenticateRequest opt (keyFetchTokenAuth sid conn) req Nothing case res of Left err -> return $ KeyFetchTokenState (Left (Hawk.authFailMessage err)) Right (Hawk.AuthSuccess creds artifacts user) -> do token <- getKeyFetchTokenById sid conn (haId artifacts) return $ KeyFetchTokenState (Right (fromJust token, Nothing)) ------------------------------------------------------------------------------ -- Standard Handlers ------------------------------------------------------------------------------ -- | The accountKeys endpoint, returns kA and wrap_kB accountKeys :: SessionId -> Connection -> KeyFetchTokenState -> Handler KeyFetchState accountKeys sid conn (KeyFetchTokenState (Left err)) = throwError $ err403 { errBody = L8.pack err } accountKeys sid conn (KeyFetchTokenState (Right (Token{..}, Just payload))) = do keyFetchState <- liftIO $ getKeyFetchStateByEmail sid conn t_user return $ fromJust keyFetchState accountKeys sid conn (KeyFetchTokenState (Right (Token{..}, Nothing))) = do -- This is okay because we're not expecting a payload in GET /account/keys keyFetchState <- liftIO $ getKeyFetchStateByEmail sid conn t_user return $ fromJust keyFetchState
et4te/zero
server/src/Zero/KeyFetchToken/Handlers.hs
bsd-3-clause
3,285
0
19
634
765
412
353
-1
-1
{-# LANGUAGE TemplateHaskell #-} module Skeletons where import Data.FileEmbed (embedFile) import Data.ByteString.Char8 (unpack) import System.FilePath ((</>)) activateSkel :: String activateSkel = unpack $(embedFile $ "skeletons" </> "activate") cabalWrapperSkel :: String cabalWrapperSkel = unpack $(embedFile $ "skeletons" </> "cabal") cabalConfigSkel :: String cabalConfigSkel = unpack $(embedFile $ "skeletons" </> "cabal_config")
Paczesiowa/virthualenv
src/Skeletons.hs
bsd-3-clause
440
0
9
54
113
64
49
11
1
module Stage.Preprocessing ( posbval , negbval , posnegbval , posbvec , negbvec , posnegbvec , posNegVol , posb0s , negb0s , posnegb0s , posseries_txt , negseries_txt , index_txt , acqparams_txt , rules ) where import Data.Yaml (decodeFile) import Development.Shake import Development.Shake.Config import Development.Shake.FilePath import FSL (mergeVols, readbval, readbvec, tobval, tobvec, trimVol, writebval, writebvec) import qualified Stage.Normalize as Normalize import Text.Printf import Types (DWIInfo (..), DWIPair (..), PhaseDirection (..)) import Util (mkIndexList, readoutTime, writeB0s) outdir :: [Char] outdir = "hcp-output/1_preproc" posbval :: FilePath posbval = outdir </> "Pos.bval" negbval :: FilePath negbval = outdir </> "Neg.bval" posnegbval :: FilePath posnegbval = outdir </> "PosNeg.bval" posbvec :: FilePath posbvec = outdir </> "Pos.bvec" negbvec :: FilePath negbvec = outdir </> "Neg.bvec" posnegbvec :: FilePath posnegbvec = outdir </> "PosNeg.bvec" posNegVol :: FilePath posNegVol = outdir </> "PosNeg.nii.gz" posb0s :: FilePath posb0s = outdir </> "Pos_b0s.nii.gz" negb0s :: FilePath negb0s = outdir </> "Neg_b0s.nii.gz" posnegb0s :: FilePath posnegb0s = outdir </> "PosNeg_b0s.nii.gz" posseries_txt :: FilePath posseries_txt = outdir </> "Pos_SeriesVolNum.txt" negseries_txt :: FilePath negseries_txt = outdir </> "Neg_SeriesVolNum.txt" index_txt :: FilePath index_txt = outdir </> "index.txt" acqparams_txt :: FilePath acqparams_txt = outdir </> "acqparams.txt" rules :: Rules () rules = do [posbval, negbval, posnegbval] *>> \[posOut,negOut,posnegOut] -> do need [Normalize.dwipairs_yaml] Just dwipairs <- liftIO $ decodeFile Normalize.dwipairs_yaml let posbvals = map (tobval._dwi._pos) dwipairs negbvals = map (tobval._dwi._neg) dwipairs need $ posbvals ++ negbvals posbvalues <- concat <$> traverse readbval posbvals negbvalues <- concat <$> traverse readbval negbvals writebval posOut $ posbvalues writebval negOut $ negbvalues writebval posnegOut $ posbvalues ++ negbvalues [posbvec, negbvec, posnegbvec] *>> \[posOut,negOut,posnegOut] -> do need [Normalize.dwipairs_yaml] Just dwipairs <- liftIO $ decodeFile Normalize.dwipairs_yaml let posbvecs = map (tobvec._dwi._pos) dwipairs negbvecs = map (tobvec._dwi._neg) dwipairs need $ posbvecs ++ negbvecs posvectors <- concat <$> traverse readbvec posbvecs negvectors <- concat <$> traverse readbvec negbvecs writebvec posOut $ posvectors writebvec negOut $ negvectors writebvec posnegOut $ posvectors ++ negvectors posNegVol %> \out -> do need [Normalize.dwipairs_yaml] Just dwipairs <- liftIO $ decodeFile Normalize.dwipairs_yaml let dwis = map (_dwi._pos) dwipairs ++ map (_dwi._neg) dwipairs need dwis mergeVols out dwis trimVol out [posb0s, negb0s, posnegb0s] *>> \_ -> do need [Normalize.dwipairs_yaml] Just dwipairs <- liftIO $ decodeFile Normalize.dwipairs_yaml need $ map (_dwi._pos) dwipairs ++ map (_dwi._neg) dwipairs writeB0s posb0s (map _pos dwipairs) writeB0s negb0s (map _neg dwipairs) mergeVols posnegb0s [posb0s, negb0s] [posseries_txt, negseries_txt] *>> \[posseries, negseries] -> do need [Normalize.dwipairs_yaml] Just ps <- liftIO $ decodeFile Normalize.dwipairs_yaml let minsizes = zipWith min (map (_size._pos) $ ps) (map (_size._neg) $ ps) seriesPos = zipWith printline minsizes $ map (_size._pos) ps seriesNeg = zipWith printline minsizes $ map (_size._neg) ps printline x y = printf "%d %d" x y writeFile' posseries $ unlines seriesPos writeFile' negseries $ unlines seriesNeg index_txt %> \out -> do need [Normalize.dwipairs_yaml] Just dwipairs <- liftIO $ decodeFile Normalize.dwipairs_yaml writeFile' out (unlines $ map show $ mkIndexList dwipairs) acqparams_txt %> \out -> do need [Normalize.dwipairs_yaml] Just dwipairs <- liftIO $ decodeFile Normalize.dwipairs_yaml Just phasedir <- fmap read <$> getConfig "phasedir" Just echospacing <- fmap read <$> getConfig "echospacing" let dwi0 = _dwi._pos.head $ dwipairs need [dwi0] phaselength <- case phasedir of PA -> read . fromStdout <$> command [] "fslval" [dwi0, "dim1"] _ -> read . fromStdout <$> command [] "fslval" [dwi0, "dim2"] let readout = printf "%.6f" $ readoutTime phaselength echospacing numB0sToUse = length . concatMap _b0indicesToUse acqParamsPos = case phasedir of PA -> "0 1 0 " ++ readout RL -> "1 0 0 " ++ readout acqParamsNeg = case phasedir of PA -> "0 -1 0 " ++ readout RL -> "-1 0 0 " ++ readout acq = replicate (numB0sToUse $ map _pos dwipairs) acqParamsPos acq' = replicate (numB0sToUse $ map _neg dwipairs) acqParamsNeg writeFile' out $ unlines (acq ++ acq')
reckbo/hs-hcp-pipeline
src/Stage/Preprocessing.hs
bsd-3-clause
5,598
0
19
1,671
1,549
784
765
145
4
{-# LANGUAGE TemplateHaskell #-} module Pinchot.SyntaxTree.Optics where import Data.Data (Data) import Data.List.NonEmpty (NonEmpty, toList) import qualified Control.Lens as Lens import qualified Language.Haskell.TH as T import qualified Language.Haskell.TH.Syntax as Syntax import Pinchot.Names import Pinchot.Rules import Pinchot.Types -- | Creates optics declarations for a 'Rule', if optics can -- be made for the 'Rule': -- -- * 'Pinchot.terminal' gets a single 'Lens.Prism' -- -- * 'Pinchot.nonTerminal' gets a 'Lens.Prism' for each constructor -- -- * 'Pinchot.record' gets a single 'Lens.Lens' -- -- * 'Pinchot.wrap', 'Pinchot.opt', 'Pinchot.star', and 'Pinchot.plus' -- do not get optics. For those, you will typically want to use -- 'Pinchot.wrappedInstances'. -- -- Each rule in the sequence of 'Rule', as well as all ancestors of -- those 'Rule's, will be handled. -- -- Example: "Pinchot.Examples.RulesToOptics". rulesToOptics :: (Syntax.Lift t, Data t) => Qualifier -- ^ Qualifier for module containing the data types that will get -- optics -> T.Name -- ^ Type name for the terminal -> [Rule t] -> T.Q [T.Dec] rulesToOptics qual termName = fmap concat . traverse (ruleToOptics qual termName) . families -- | Creates optics declarations for a single 'Rule', if optics can -- be made for the 'Rule': -- -- * 'Terminal' gets a single 'Lens.Prism' -- -- * 'NonTerminal' gets a 'Lens.Prism' for each constructor -- -- * 'Series' gets a single 'Lens.Prism' -- -- * 'Record' gets a single 'Lens.Lens' -- -- * 'Wrap', 'Opt', 'Star', and 'Plus' do not get optics. ruleToOptics :: (Syntax.Lift t, Data t) => Qualifier -- ^ Qualifier for module containing the data type that will get -- optics -> T.Name -- ^ Type name for the terminal -> Rule t -> T.Q [T.Dec] ruleToOptics qual termName (Rule nm _ ty) = case ty of Terminal pdct -> terminalToOptics qual termName nm pdct NonTerminal bs -> sequence $ nonTerminalToOptics qual nm bs Record sq -> sequence $ recordsToOptics qual nm sq Series ne -> seriesToOptics qual termName nm ne _ -> return [] -- | Creates a prism for a terminal type. Although a newtype wraps -- each terminal, do not make a Wrapped or an Iso, because the -- relationship between the outer type and the type that it wraps -- typically is not isometric. Thus, use a Prism instead, which -- captures this relationship properly. terminalToOptics :: Syntax.Lift t => Qualifier -- ^ Qualifier for module containing the data type that will get -- optics -> T.Name -- ^ Terminal type name -> String -- ^ Rule name -> Predicate t -> T.Q [T.Dec] terminalToOptics qual termName nm (Predicate pdct) = do ctorName <- lookupTypeName (quald qual nm) e1 <- T.sigD (T.mkName ('_':nm)) $ T.forallT [ tyVarBndrA] (return []) [t| Lens.Prism' ( $(T.conT termName), $(typeA) ) ( $(T.conT ctorName) $(T.conT termName) $(typeA)) |] e2 <- T.valD prismName (T.normalB expn) [] return [e1, e2] where prismName = T.varP (T.mkName ('_' : nm)) expn = do x <- T.newName "_x" ctorName <- lookupValueName (quald qual nm) let fetchPat = T.conP ctorName [T.varP x] fetchName = T.varE x [| let fetch $fetchPat = $fetchName store (term, a) | $(fmap T.unType pdct) term = Just ($(T.conE ctorName) (term, a)) | otherwise = Nothing in Lens.prism' fetch store |] seriesToOptics :: (Data t, Syntax.Lift t) => Qualifier -- ^ Qualifier for module containing the data type that will get -- optics -> T.Name -- ^ Terminal type name -> String -- ^ Rule name -> NonEmpty t -> T.Q [T.Dec] seriesToOptics qual termName nm terminals = do ctorName <- lookupTypeName (quald qual nm) e1 <- T.sigD (T.mkName ('_':nm)) $ T.forallT [ tyVarBndrA] (return []) [t| Lens.Prism' (NonEmpty ( $(T.conT termName), $(typeA) )) ( $(T.conT ctorName) $(T.conT termName) $(typeA)) |] e2 <- T.valD prismName (T.normalB expn) [] return [e1, e2] where prismName = T.varP (T.mkName ('_' : nm)) expn = do x <- T.newName "_x" ctorName <- lookupValueName (quald qual nm) let fetchPat = T.conP ctorName [T.varP x] fetchName = T.varE x [| let fetch $fetchPat = $fetchName store terms | fmap fst terms == $(Syntax.liftData terminals) = Just ($(T.conE ctorName) terms ) | otherwise = Nothing in Lens.prism' fetch store |] prismSignature :: Qualifier -> String -- ^ Rule name -> Branch t -> T.DecQ prismSignature qual nm (Branch inner rules) = do ctorName <- lookupTypeName (quald qual nm) T.sigD prismName (forallA [t| Lens.Prism' ($(T.conT ctorName) $(typeT) $(typeA)) $(fieldsType) |]) where prismName = T.mkName ('_' : inner) fieldsType = case rules of [] -> T.tupleT 0 Rule r1 _ _ : [] -> do ctorName <- lookupTypeName (quald qual r1) [t| $(T.conT ctorName) $(typeT) $(typeA) |] rs -> foldl addType (T.tupleT (length rs)) rs where addType soFar (Rule r _ _) = do ctorName <- lookupTypeName (quald qual r) soFar `T.appT` [t| $(T.conT ctorName) $(typeT) $(typeA) |] setterPatAndExpn :: Qualifier -> BranchName -> [a] -- ^ List of rules -> T.Q (T.PatQ, T.ExpQ) setterPatAndExpn qual inner rules = do names <- sequence . flip replicate (T.newName "_setterPatAndExpn") . length $ rules let pat = T.tupP . fmap T.varP $ names expn = foldl addVar start names where start = do ctorName <- lookupValueName (quald qual inner) T.conE ctorName addVar acc nm = acc `T.appE` (T.varE nm) return (pat, expn) prismSetter :: Qualifier -> Branch t -> T.ExpQ prismSetter qual (Branch inner rules) = do (pat, expn) <- setterPatAndExpn qual inner rules T.lamE [pat] expn -- | Returns a pattern and expression to match a particular branch; if -- there is a match, the expression will return each field, in a tuple -- in a Right. rightPatternAndExpression :: Qualifier -> BranchName -> Int -- ^ Number of fields -> T.Q (T.PatQ, T.ExpQ) rightPatternAndExpression qual inner n = do names <- sequence . replicate n $ T.newName "_patternAndExpression" ctorName <- lookupValueName (quald qual inner) let pat = T.conP ctorName . fmap T.varP $ names expn = T.appE (T.conE 'Right) . T.tupE . fmap T.varE $ names return (pat, expn) -- | Returns a pattern and expression for branches that did not match. -- Does not return anything if there are no other branches. leftPatternAndExpression :: [a] -- ^ List of all other branches -> Maybe (T.Q (T.PatQ, T.ExpQ)) leftPatternAndExpression ls | null ls = Nothing | otherwise = Just $ do local <- T.newName "_leftPatternAndExpression" return (T.varP local, T.appE (T.conE 'Left) (T.varE local)) prismGetter :: Qualifier -> Branch t -- ^ Make prism for this branch -> [Branch t] -- ^ List of all branches -> T.ExpQ prismGetter qual (Branch inner rules) bs = do local <- T.newName "_prismGetter" (patCtor, bodyCtor) <- rightPatternAndExpression qual inner (length rules) let firstElem = T.match patCtor (T.normalB bodyCtor) [] lastElem <- case leftPatternAndExpression bs of Nothing -> return [] Just computation -> do (patLeft, expLeft) <- computation return [T.match patLeft (T.normalB expLeft) []] T.lamE [T.varP local] (T.caseE (T.varE local) $ firstElem : lastElem) -- | Creates prisms for each 'Branch'. nonTerminalToOptics :: Qualifier -- ^ Qualifier for module containing the data type that will get -- optics -> String -- ^ Rule name -> NonEmpty (Branch t) -> [T.Q T.Dec] nonTerminalToOptics qual nm bsSeq = concat $ fmap makePrism bs where bs = toList bsSeq makePrism branch@(Branch inner _) = [ prismSignature qual nm branch, binding ] where prismName = T.mkName ('_' : inner) binding = T.valD (T.varP prismName) body [] where body = T.normalB $ (T.varE 'Lens.prism) `T.appE` (prismSetter qual branch) `T.appE` (prismGetter qual branch bs) recordLensSignature :: Qualifier -> RuleName -- ^ Name of the main rule -> RuleName -- ^ Name of the rule for this lens -> Int -- ^ Index for this lens -> T.DecQ recordLensSignature qual nm inner idx = do ctorOuter <- lookupTypeName (quald qual nm) ctorInner <- lookupTypeName (quald qual inner) T.sigD lensName (forallA [t| Lens.Lens' ($(T.conT ctorOuter) $(typeT) $(typeA)) ($(T.conT ctorInner) $(typeT) $(typeA)) |]) where lensName = T.mkName $ recordFieldName idx nm inner recordLensGetter :: Qualifier -> String -- ^ Record field name -> T.ExpQ recordLensGetter qual fieldNm = do namedRec <- T.newName "_namedRec" fieldNm <- lookupValueName $ quald qual ('_' : fieldNm) let pat = T.varP namedRec expn = (T.varE fieldNm) `T.appE` (T.varE namedRec) T.lamE [pat] expn recordLensSetter :: Qualifier -> String -- ^ Record field name -> T.ExpQ recordLensSetter qual fieldNm = do namedRec <- T.newName "_namedRec" namedNewVal <- T.newName "_namedNewVal" fieldName <- lookupValueName (quald qual ('_' : fieldNm)) let patRec = T.varP namedRec patNewVal = T.varP namedNewVal expn = T.recUpdE (T.varE namedRec) [ return (fieldName , T.VarE namedNewVal) ] T.lamE [patRec, patNewVal] expn recordLensFunction :: Qualifier -> RuleName -- ^ Name of the main rule -> RuleName -- ^ Name of the rule for this lens -> Int -- ^ Index for this lens -> T.DecQ recordLensFunction qual nm inner idx = let fieldNm = recordFieldName idx nm inner lensName = T.mkName $ recordFieldName idx nm inner getter = recordLensGetter qual fieldNm setter = recordLensSetter qual fieldNm body = (T.varE 'Lens.lens) `T.appE` getter `T.appE` setter in T.funD lensName [T.clause [] (T.normalB body) []] recordsToOptics :: Qualifier -- ^ Qualifier for module containing the data type that will get -- optics -> String -- ^ Rule name -> [Rule t] -> [T.Q T.Dec] recordsToOptics qual nm rules = do let makeLens index (Rule inner _ _) = [ signature, function ] where signature = recordLensSignature qual nm inner index function = recordLensFunction qual nm inner index concat . zipWith makeLens [(0 :: Int) ..] $ rules forallA :: T.TypeQ -> T.TypeQ forallA = T.forallT [ tyVarBndrT, tyVarBndrA ] (return [])
massysett/pinchot
pinchot/lib/Pinchot/SyntaxTree/Optics.hs
bsd-3-clause
10,813
0
18
2,706
2,869
1,473
1,396
245
5
{-# LANGUAGE ScopedTypeVariables #-} module Distribution.Solver.Modular.Builder ( buildTree , splits -- for testing ) where -- Building the search tree. -- -- In this phase, we build a search tree that is too large, i.e, it contains -- invalid solutions. We keep track of the open goals at each point. We -- nondeterministically pick an open goal (via a goal choice node), create -- subtrees according to the index and the available solutions, and extend the -- set of open goals by superficially looking at the dependencies recorded in -- the index. -- -- For each goal, we keep track of all the *reasons* why it is being -- introduced. These are for debugging and error messages, mainly. A little bit -- of care has to be taken due to the way we treat flags. If a package has -- flag-guarded dependencies, we cannot introduce them immediately. Instead, we -- store the entire dependency. import Data.List as L import Data.Map as M import Prelude hiding (sequence, mapM) import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.Index import Distribution.Solver.Modular.Package import qualified Distribution.Solver.Modular.PSQ as P import Distribution.Solver.Modular.Tree import qualified Distribution.Solver.Modular.WeightedPSQ as W import Distribution.Solver.Types.PackagePath import Distribution.Solver.Types.Settings -- | All state needed to build and link the search tree. It has a type variable -- because the linking phase doesn't need to know about the state used to build -- the tree. data Linker a = Linker { buildState :: a, linkingState :: LinkingState } -- | The state needed to build the search tree without creating any linked nodes. data BuildState = BS { index :: Index, -- ^ information about packages and their dependencies rdeps :: RevDepMap, -- ^ set of all package goals, completed and open, with reverse dependencies open :: [OpenGoal], -- ^ set of still open goals (flag and package goals) next :: BuildType, -- ^ kind of node to generate next qualifyOptions :: QualifyOptions -- ^ qualification options } -- | Map of available linking targets. type LinkingState = Map (PN, I) [PackagePath] -- | Extend the set of open goals with the new goals listed. -- -- We also adjust the map of overall goals, and keep track of the -- reverse dependencies of each of the goals. extendOpen :: QPN -> [PotentialGoal] -> BuildState -> BuildState extendOpen qpn' gs s@(BS { rdeps = gs', open = o' }) = go gs' o' gs where go :: RevDepMap -> [OpenGoal] -> [PotentialGoal] -> BuildState go g o [] = s { rdeps = g, open = o } go g o ((PotentialGoal (Flagged fn fInfo t f) gr) : ngs) = go g (FlagGoal fn fInfo t f gr : o) ngs -- Note: for 'Flagged' goals, we always insert, so later additions win. -- This is important, because in general, if a goal is inserted twice, -- the later addition will have better dependency information. go g o ((PotentialGoal (Stanza sn t) gr) : ngs) = go g (StanzaGoal sn t gr : o) ngs go g o ((PotentialGoal (Simple (Dep _ qpn _) c) gr) : ngs) | qpn == qpn' = go g o ngs -- we ignore self-dependencies at this point; TODO: more care may be needed | qpn `M.member` g = go (M.adjust (addIfAbsent (c, qpn')) qpn g) o ngs | otherwise = go (M.insert qpn [(c, qpn')] g) (PkgGoal qpn gr : o) ngs -- code above is correct; insert/adjust have different arg order go g o ((PotentialGoal (Simple (Ext _ext ) _) _gr) : ngs) = go g o ngs go g o ((PotentialGoal (Simple (Lang _lang)_) _gr) : ngs) = go g o ngs go g o ((PotentialGoal (Simple (Pkg _pn _vr)_) _gr) : ngs) = go g o ngs addIfAbsent :: Eq a => a -> [a] -> [a] addIfAbsent x xs = if x `elem` xs then xs else x : xs -- | Given the current scope, qualify all the package names in the given set of -- dependencies and then extend the set of open goals accordingly. scopedExtendOpen :: QPN -> I -> QGoalReason -> FlaggedDeps PN -> FlagInfo -> BuildState -> BuildState scopedExtendOpen qpn i gr fdeps fdefs s = extendOpen qpn gs s where -- Qualify all package names qfdeps = qualifyDeps (qualifyOptions s) qpn fdeps -- Introduce all package flags qfdefs = L.map (\ (fn, b) -> Flagged (FN (PI qpn i) fn) b [] []) $ M.toList fdefs -- Combine new package and flag goals gs = L.map (flip PotentialGoal gr) (qfdefs ++ qfdeps) -- NOTE: -- -- In the expression @qfdefs ++ qfdeps@ above, flags occur potentially -- multiple times, both via the flag declaration and via dependencies. -- The order is potentially important, because the occurrences via -- dependencies may record flag-dependency information. After a number -- of bugs involving computing this information incorrectly, however, -- we're currently not using carefully computed inter-flag dependencies -- anymore, but instead use 'simplifyVar' when computing conflict sets -- to map all flags of one package to a single flag for conflict set -- purposes, thereby treating them all as interdependent. -- -- If we ever move to a more clever algorithm again, then the line above -- needs to be looked at very carefully, and probably be replaced by -- more systematically computed flag dependency information. -- | Datatype that encodes what to build next data BuildType = Goals -- ^ build a goal choice node | OneGoal OpenGoal -- ^ build a node for this goal | Instance QPN I PInfo QGoalReason -- ^ build a tree for a concrete instance build :: Linker BuildState -> Tree () QGoalReason build = ana go where go :: Linker BuildState -> TreeF () QGoalReason (Linker BuildState) go s = addLinking (linkingState s) $ addChildren (buildState s) addChildren :: BuildState -> TreeF () QGoalReason BuildState -- If we have a choice between many goals, we just record the choice in -- the tree. We select each open goal in turn, and before we descend, remove -- it from the queue of open goals. addChildren bs@(BS { rdeps = rdm, open = gs, next = Goals }) | L.null gs = DoneF rdm () | otherwise = GoalChoiceF rdm $ P.fromList $ L.map (\ (g, gs') -> (close g, bs { next = OneGoal g, open = gs' })) $ splits gs -- If we have already picked a goal, then the choice depends on the kind -- of goal. -- -- For a package, we look up the instances available in the global info, -- and then handle each instance in turn. addChildren bs@(BS { rdeps = rdm, index = idx, next = OneGoal (PkgGoal qpn@(Q _ pn) gr) }) = -- If the package does not exist in the index, we construct an emty PChoiceF node for it -- After all, we have no choices here. Alternatively, we could immediately construct -- a Fail node here, but that would complicate the construction of conflict sets. -- We will probably want to give this case special treatment when generating error -- messages though. case M.lookup pn idx of Nothing -> PChoiceF qpn rdm gr (W.fromList []) Just pis -> PChoiceF qpn rdm gr (W.fromList (L.map (\ (i, info) -> ([], POption i Nothing, bs { next = Instance qpn i info gr })) (M.toList pis))) -- TODO: data structure conversion is rather ugly here -- For a flag, we create only two subtrees, and we create them in the order -- that is indicated by the flag default. addChildren bs@(BS { rdeps = rdm, next = OneGoal (FlagGoal qfn@(FN (PI qpn _) _) (FInfo b m w) t f gr) }) = FChoiceF qfn rdm gr weak m b (W.fromList [([if b then 0 else 1], True, (extendOpen qpn (L.map (flip PotentialGoal (FDependency qfn True )) t) bs) { next = Goals }), ([if b then 1 else 0], False, (extendOpen qpn (L.map (flip PotentialGoal (FDependency qfn False)) f) bs) { next = Goals })]) where trivial = L.null t && L.null f weak = WeakOrTrivial $ unWeakOrTrivial w || trivial -- For a stanza, we also create only two subtrees. The order is initially -- False, True. This can be changed later by constraints (force enabling -- the stanza by replacing the False branch with failure) or preferences -- (try enabling the stanza if possible by moving the True branch first). addChildren bs@(BS { rdeps = rdm, next = OneGoal (StanzaGoal qsn@(SN (PI qpn _) _) t gr) }) = SChoiceF qsn rdm gr trivial (W.fromList [([0], False, bs { next = Goals }), ([1], True, (extendOpen qpn (L.map (flip PotentialGoal (SDependency qsn)) t) bs) { next = Goals })]) where trivial = WeakOrTrivial (L.null t) -- For a particular instance, we change the state: we update the scope, -- and furthermore we update the set of goals. -- -- TODO: We could inline this above. addChildren bs@(BS { next = Instance qpn i (PInfo fdeps fdefs _) _gr }) = addChildren ((scopedExtendOpen qpn i (PDependency (PI qpn i)) fdeps fdefs bs) { next = Goals }) {------------------------------------------------------------------------------- Add linking -------------------------------------------------------------------------------} -- | Introduce link nodes into the tree -- -- Linking is a phase that adapts package choice nodes and adds the option to -- link wherever appropriate: Package goals are called "related" if they are for -- the same instance of the same package (but have different prefixes). A link -- option is available in a package choice node whenever we can choose an -- instance that has already been chosen for a related goal at a higher position -- in the tree. We only create link options for related goals that are not -- themselves linked, because the choice to link to a linked goal is the same as -- the choice to link to the target of that goal's linking. -- -- The code here proceeds by maintaining a finite map recording choices that -- have been made at higher positions in the tree. For each pair of package name -- and instance, it stores the prefixes at which we have made a choice for this -- package instance. Whenever we make an unlinked choice, we extend the map. -- Whenever we find a choice, we look into the map in order to find out what -- link options we have to add. -- -- A separate tree traversal would be simpler. However, 'addLinking' creates -- linked nodes from existing unlinked nodes, which leads to sharing between the -- nodes. If we copied the nodes when they were full trees of type -- 'Tree () QGoalReason', then the sharing would cause a space leak during -- exploration of the tree. Instead, we only copy the 'BuildState', which is -- relatively small, while the tree is being constructed. See -- https://github.com/haskell/cabal/issues/2899 addLinking :: LinkingState -> TreeF () c a -> TreeF () c (Linker a) -- The only nodes of interest are package nodes addLinking ls (PChoiceF qpn@(Q pp pn) rdm gr cs) = let linkedCs = fmap (\bs -> Linker bs ls) $ W.fromList $ concatMap (linkChoices ls qpn) (W.toList cs) unlinkedCs = W.mapWithKey goP cs allCs = unlinkedCs `W.union` linkedCs -- Recurse underneath package choices. Here we just need to make sure -- that we record the package choice so that it is available below goP :: POption -> a -> Linker a goP (POption i Nothing) bs = Linker bs $ M.insertWith (++) (pn, i) [pp] ls goP _ _ = alreadyLinked in PChoiceF qpn rdm gr allCs addLinking ls t = fmap (\bs -> Linker bs ls) t linkChoices :: forall a w . LinkingState -> QPN -> (w, POption, a) -> [(w, POption, a)] linkChoices related (Q _pp pn) (weight, POption i Nothing, subtree) = L.map aux (M.findWithDefault [] (pn, i) related) where aux :: PackagePath -> (w, POption, a) aux pp = (weight, POption i (Just pp), subtree) linkChoices _ _ (_, POption _ (Just _), _) = alreadyLinked alreadyLinked :: a alreadyLinked = error "addLinking called on tree that already contains linked nodes" ------------------------------------------------------------------------------- -- | Interface to the tree builder. Just takes an index and a list of package names, -- and computes the initial state and then the tree from there. buildTree :: Index -> IndependentGoals -> [PN] -> Tree () QGoalReason buildTree idx (IndependentGoals ind) igs = build Linker { buildState = BS { index = idx , rdeps = M.fromList (L.map (\ qpn -> (qpn, [])) qpns) , open = L.map topLevelGoal qpns , next = Goals , qualifyOptions = defaultQualifyOptions idx } , linkingState = M.empty } where topLevelGoal qpn = PkgGoal qpn UserGoal qpns | ind = L.map makeIndependent igs | otherwise = L.map (Q (PackagePath DefaultNamespace QualToplevel)) igs {------------------------------------------------------------------------------- Goals -------------------------------------------------------------------------------} -- | Information needed about a dependency before it is converted into a Goal. -- Not all PotentialGoals correspond to Goals. For example, PotentialGoals can -- represent pkg-config or language extension dependencies. data PotentialGoal = PotentialGoal (FlaggedDep QPN) QGoalReason -- | Like a PotentialGoal, except that it always introduces a new Goal. data OpenGoal = FlagGoal (FN QPN) FInfo (FlaggedDeps QPN) (FlaggedDeps QPN) QGoalReason | StanzaGoal (SN QPN) (FlaggedDeps QPN) QGoalReason | PkgGoal QPN QGoalReason -- | Closes a goal, i.e., removes all the extraneous information that we -- need only during the build phase. close :: OpenGoal -> Goal QPN close (FlagGoal qfn _ _ _ gr) = Goal (F qfn) gr close (StanzaGoal qsn _ gr) = Goal (S qsn) gr close (PkgGoal qpn gr) = Goal (P qpn) gr {------------------------------------------------------------------------------- Auxiliary -------------------------------------------------------------------------------} -- | Pairs each element of a list with the list resulting from removal of that -- element from the original list. splits :: [a] -> [(a, [a])] splits = go id where go :: ([a] -> [a]) -> [a] -> [(a, [a])] go _ [] = [] go f (x : xs) = (x, f xs) : go (f . (x :)) xs
mydaum/cabal
cabal-install/Distribution/Solver/Modular/Builder.hs
bsd-3-clause
14,677
0
18
3,535
3,026
1,679
1,347
131
8
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DisambiguateRecordFields, RecordWildCards, NamedFieldPuns #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} module Narradar.Types.Problem.NarrowingGoal where import Control.Applicative import Control.Exception (assert) import Control.Monad.Free import Data.Foldable as F (Foldable(..), toList) import Data.Traversable as T (Traversable(..), mapM, fmapDefault, foldMapDefault) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Map as Map import Text.XHtml (theclass) import Data.Term import Data.Term.Rules import MuTerm.Framework.Problem import MuTerm.Framework.Proof import Narradar.Constraints.VariableCondition import Narradar.Types.ArgumentFiltering (AF_, ApplyAF(..), PolyHeuristic, MkHeu, mkHeu, bestHeu, fromAF) import qualified Narradar.Types.ArgumentFiltering as AF import Narradar.Types.DPIdentifiers import Narradar.Types.Goal import Narradar.Types.Problem import Narradar.Types.Problem.Rewriting import Narradar.Types.Term import Narradar.Framework import Narradar.Framework.Ppr import Narradar.Utils (chunks) import Prelude hiding (pi) type NarrowingGoal id = MkNarrowingGoal id Rewriting type CNarrowingGoal id = MkNarrowingGoal id IRewriting data MkNarrowingGoal id p = forall heu . PolyHeuristic heu id => NarrowingGoal (Goal id) (AF_ id) (MkHeu heu) p instance (Ord id, IsProblem p) => IsProblem (MkNarrowingGoal id p) where data Problem (MkNarrowingGoal id p) a = NarrowingGoalProblem {goal::Goal id, pi::AF_ id, baseProblem::Problem p a} getFramework (NarrowingGoalProblem g af p) = NarrowingGoal g af bestHeu (getFramework p) getR (NarrowingGoalProblem _ _ p) = getR p instance (Ord id, IsDPProblem p, MkProblem p trs, HasSignature trs, id ~ SignatureId (Problem p trs)) => MkProblem (MkNarrowingGoal id p) trs where mkProblem (NarrowingGoal g af _ base) rr = NarrowingGoalProblem g (af `mappend` AF.init p) p where p = mkProblem base rr mapR f (NarrowingGoalProblem g af p) = NarrowingGoalProblem g af (mapR f p) instance (Ord id, IsDPProblem p) => IsDPProblem (MkNarrowingGoal id p) where getP (NarrowingGoalProblem _ _ p) = getP p instance (id ~ SignatureId (Problem p trs), HasSignature trs, Ord id, MkDPProblem p trs) => MkDPProblem (MkNarrowingGoal id p) trs where mapP f (NarrowingGoalProblem g af p) = NarrowingGoalProblem g af (mapP f p) mkDPProblem (NarrowingGoal g af _ base) rr dp = NarrowingGoalProblem g (af `mappend` AF.init p) p where p = mkDPProblem base rr dp narrowingGoal g = narrowingGoal' g (mkGoalAF g) cnarrowingGoal g = NarrowingGoal g (mkGoalAF g) bestHeu irewriting narrowingGoal' g af = NarrowingGoal g af bestHeu rewriting mkDerivedNarrowingGoalProblem g mkH p = do let heu = mkHeu mkH p af = mkGoalAF g `mappend` AF.init p af' <- Set.toList $ invariantEV heu p af let p' = NarrowingGoalProblem g af' p -- $ (iUsableRules p (rhs <$> rules (getP p))) return p' -- Eq,Ord,Show deriving instance (Eq id, Eq (Problem p trs)) => Eq (Problem (MkNarrowingGoal id p) trs) deriving instance (Ord id, Ord (Problem p trs)) => Ord (Problem (MkNarrowingGoal id p) trs) deriving instance (Show id, Show (Problem p trs)) => Show (Problem (MkNarrowingGoal id p) trs) -- Functor instance Functor (MkNarrowingGoal id) where fmap = fmapDefault instance Foldable (MkNarrowingGoal id) where foldMap = foldMapDefault instance Traversable (MkNarrowingGoal id) where traverse f (NarrowingGoal g pi heu p) = NarrowingGoal g pi heu <$> f p instance Functor (Problem p) => Functor (Problem (MkNarrowingGoal id p)) where fmap f (NarrowingGoalProblem g af p) = NarrowingGoalProblem g af (fmap f p) instance Foldable (Problem p) => Foldable (Problem (MkNarrowingGoal id p)) where foldMap f (NarrowingGoalProblem g af p) = foldMap f p instance Traversable (Problem p) => Traversable (Problem (MkNarrowingGoal id p)) where traverse f (NarrowingGoalProblem g af p) = NarrowingGoalProblem g af <$> traverse f p -- Framework instance FrameworkExtension (MkNarrowingGoal id) where getBaseFramework (NarrowingGoal _ _ _ p) = p getBaseProblem = baseProblem liftProblem f p = f (baseProblem p) >>= \p0' -> return p{baseProblem = p0'} liftFramework f (NarrowingGoal g af heu p) = NarrowingGoal g af heu (f p) liftProcessorS = liftProcessorSdefault -- Output instance Pretty p => Pretty (MkNarrowingGoal id p) where pPrint (NarrowingGoal _ _ _ b) = text "NarrowingGoal" <+> pPrint b instance HTMLClass (MkNarrowingGoal id Rewriting) where htmlClass _ = theclass "NDP" instance HTMLClass (MkNarrowingGoal id IRewriting) where htmlClass _ = theclass "GNDP" instance (HasRules t v trs, GetVars v trs, Pretty v, Pretty (t(Term t v)) ,Pretty id, Pretty (Goal id) ,Foldable t, HasId t, id ~ TermId t ,PprTPDB (Problem base trs), HasMinimality base ) => PprTPDB (Problem (MkNarrowingGoal id base) trs) where pprTPDB (NarrowingGoalProblem g pi p) = pprTPDB (setMinimality A p) $$ parens (text "STRATEGY NARROWING") $$ parens (text "STRATEGY GOAL" <+> g) -- Icap instance (HasRules t v trs, Unify t, GetVars v trs, ICap t v (p,trs)) => ICap t v (MkNarrowingGoal id p, trs) where icap (NarrowingGoal _ _ _ p,trs) = icap (p,trs) -- Usable Rules instance (Enum v, Unify t, Ord (Term t v), IsTRS t v trs, GetVars v trs ,ApplyAF (Term t v), ApplyAF trs , id ~ AFId trs, AFId (Term t v) ~ id, Ord id, Ord (t(Term t v)) ,IUsableRules t v p trs, ICap t v (p,trs)) => IUsableRules t v (MkNarrowingGoal id p) trs where iUsableRulesM (NarrowingGoal _ pi _ b) trs dps tt = return trs iUsableRulesVarM (NarrowingGoal _ _ _ b) = iUsableRulesVarM b
pepeiborra/narradar
src/Narradar/Types/Problem/NarrowingGoal.hs
bsd-3-clause
6,019
0
12
1,070
2,151
1,121
1,030
103
1
module OuterInner where import Control.Monad import Control.Monad.Trans.Except import Control.Monad.Trans.Maybe import Control.Monad.Trans.Reader embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int embedded = return 1 -- we can consider this return as a type-composition maybeUnwrap :: ExceptT String (ReaderT () IO) (Maybe Int) maybeUnwrap = runMaybeT embedded eitherUnwrap :: ReaderT () IO (Either String (Maybe Int)) eitherUnwrap = runExceptT maybeUnwrap readerUnwrap :: () -> IO (Either String (Maybe Int)) readerUnwrap = runReaderT eitherUnwrap -- now if we want to evaluate the code, we can feed in a unit: -- readerUnwrap () -- alternatively, iw you consider the return composed of reader, either and maybe: {- instance Monad ((->) r) where return = const instance Monad (Either e) where return = Right instance Monad (Maybe) where return = Just -} -- then we can get the same result with: -- (const . Right . Just $ 1) () -- "Base Monad" is usually in reference to the outermost monad. -- type MyType a = IO [Maybe a] has a base monad of IO. given :: b -> Either String (Maybe Integer) given = const (Right (Just 1)) returnIO :: a -> IO a returnIO = return firstLayer :: ReaderT () IO (Either String (Maybe Integer)) firstLayer = ReaderT $ fn $ given where fn :: (() -> Either String (Maybe Integer)) -> () -> IO (Either String (Maybe Integer)) fn f _ = returnIO $ f () secondLayer :: MaybeT (ReaderT () IO) Integer secondLayer = MaybeT $ fn given where fn :: (() -> Either String (Maybe Integer)) -> ReaderT () IO (Maybe Integer) fn f = case f () of Right x -> ReaderT $ (const . returnIO) x Left _ -> ReaderT $ (const . returnIO) Nothing thirdLayer :: MaybeT (ExceptT String (ReaderT () IO)) Integer thirdLayer = MaybeT $ fn $ given where fn :: (() -> Either String (Maybe Integer)) -> ExceptT String (ReaderT () IO) (Maybe Integer) fn = (ExceptT . ReaderT . const . returnIO . (\f -> f ())) reembedded :: MaybeT (ExceptT String (ReaderT () IO)) Integer reembedded = MaybeT . ExceptT . ReaderT . const . returnIO . ($ ()) $ given
stites/composition
src/OuterInner.hs
bsd-3-clause
2,149
0
13
465
690
358
332
33
2
{-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} module Signal.Compiler.Cycles (cycles) where import Signal.Core import Signal.Core.Reify import Control.Monad.State import Control.Monad.Writer import Data.Ref import Data.Ref.Map (Map, Name) import qualified Data.Ref.Map as M import Prelude hiding (Left, Right, pred) import System.Mem.StableName (eqStableName, hashStableName) -- ! -------------------------------------------------------------------------------- -- * -------------------------------------------------------------------------------- -- | ... data Hide f where Hide :: f a -> Hide f -------------------------------------------------------------------------------- -- | A node can have three different states during cycle checking -- * Visited, no cycles detected in node or children -- * Visiting, node is being checked for cycles -- * Unvisited, node has not yet been checked for cycles data Status = Visited | Visiting | Unvisited deriving Eq data Tagged i a = Tagged Status Predecessor (Node i a) -- | A node's predecessor data Predecessor = Predecessor (Hide Name) | None -- | Cycle-checking monad type M i = WriterT [Hide (Key i)] (State (Map (Tagged i))) -------------------------------------------------------------------------------- -- ** untag :: Tagged i a -> Node i a untag (Tagged _ _ n) = n (=/=) :: Predecessor -> Predecessor -> Bool (=/=) (Predecessor (Hide n1)) (Predecessor (Hide n2)) = n1 `eqStableName` n2 (=/=) _ _ = False -- | Sets the status of a tagged node is :: Name a -> Status -> M i () is r s = modify $ flip M.adjust r $ \(Tagged _ p n) -> Tagged s p n -- | Sets the predecessor of a tagged node before :: Name a -> Predecessor -> M i () before r p = modify $ flip M.adjust r $ \(Tagged s _ n) -> Tagged s p n -- | Gets the status of a tagged node status :: Name a -> M i Status status r = do s <- get return $ case M.lookup r s of Nothing -> error $ "Sorter.status: lookup failed" ++ "\n\t i: " ++ show (hashStableName r) Just (Tagged s _ _) -> s -- | Gets the predecessor of a tagged node predecessor :: Name a -> M i Predecessor predecessor r = do s <- get return $ case M.lookup r s of Nothing -> error "Sorter.predecessor: lookup failed" Just (Tagged _ p _) -> p node :: Name (S Symbol i a) -> M i (S Key i a) node r = do s <- get return $ case M.lookup r s of Nothing -> error "Sorter.node: lookup failed" Just (Tagged _ _ (Node n)) -> n -------------------------------------------------------------------------------- -- * -------------------------------------------------------------------------------- -- ! Remove unsafe, It's not really needed. cycle' :: Key i a -> M i Bool cycle' key@(Key r) = do r `is` Visiting n <- node r b <- case n of (Var _) -> return False (Repeat _) -> return False (Map _ s) -> check s (Join l r) -> (&&) <$> check l <*> check r (Left l) -> check l (Right r) -> check r (Delay _ s) -> tell [Hide s] >> return False r `is` Visited return b where check :: Key i a -> M i Bool check key@(Key r') = do let q = Predecessor (Hide r) p <- predecessor r' s <- status r' case s of Unvisited -> r' `before` q >> cycle' key Visiting | p =/= q -> return False _ -> return True -------------------------------------------------------------------------------- -- | Checks if the given signal contains cycles cycles :: Key i a -> Nodes i -> Bool cycles key nodes = flip evalState (init nodes) $ go key where init :: Nodes i -> Map (Tagged i) init = M.hmap $ \node -> Tagged Unvisited None node go :: Key i a -> State (Map (Tagged i)) Bool go node = do (b, w) <- runWriterT $ cycle' node (bs) <- mapM add w return $ and (b : bs) where add :: Hide (Key i) -> State (Map (Tagged i)) Bool add (Hide key@(Key n)) = do s <- get case M.lookup n s of Nothing -> error "Cycles.cyles.add: lookup failed" Just (Tagged _ _ (Node (Delay _ k))) -> go k --------------------------------------------------------------------------------
markus-git/signal
src/Signal/Compiler/Cycles.hs
bsd-3-clause
4,550
0
20
1,251
1,425
726
699
88
9
module PA.Data where import Data.Serialize -- bytes -- import qualified Data.Bytes.Serial as S -- import qualified Data.Bytes.Get as G -- import qualified Data.Bytes.Put as P -- bits import qualified Data.Bits.Coded as B import qualified Data.Bits.Coding as B -- base import Data.Word import Data.Bits import Control.Monad (replicateM_, replicateM) import qualified Data.ByteString as BS (singleton, head) data MessageATS2PA = OperationalATSSession | NextThreeDeparture -- for revenue train StationCode [TrainInfo] | DeparturePlatform -- for revenue train StationCode TrainInfo | ArrivalPlatform StationCode ArrivalTrigger | ClearDisplay StationCode PlatformNumber deriving (Show) data MessagePA2ATS = ConnectionRequest deriving (Show) data ArrivalTrigger = NonStopping | NotInService | Terminated | NextEstimatedTrain TrainInfo Word8 deriving (Show) -- dwell time (not used) data TrainInfo = TrainInfo RollingStockProfile PlatformNumber Word8 Word8 Word8 StationCode deriving (Show) data RollingStockProfile = FourCar | SixCar | EightCar deriving (Show) data PlatformNumber = PL1 | PL2 | PL3 deriving (Show) data StationCode = JPW | DBMR | DSHP | PALM | SABR | IGDA | SKVR | VTVR | MIRK | RKPM | IIT | HKS | PSPK | CDLI | GKEI | NUEE | KJMD | OKNS | IWNR | JANR | OVA | JLA | KIKJ | OKBS | BTGD | KIKD | JSTB deriving (Show) instance Serialize MessageATS2PA where put OperationalATSSession = do putWord8 1 -- SrcID putWord8 1 -- MessageID put (NextThreeDeparture stNum trInfos) = do putWord8 1 -- SrcID putWord8 2 -- MessageID put stNum putWord8 (fromIntegral (length trInfos) :: Word8) mapM_ (\x -> put x >> replicateM_ 5 (putWord8 0xFF)) trInfos put (DeparturePlatform stNum trInfo) = do putWord8 1 -- SrcID putWord8 3 -- MessageID put stNum put trInfo replicateM_ 5 (putWord8 0xFF) put (ArrivalPlatform stNum arrTriger) = do putWord8 1 -- SrcID putWord8 4 -- MessageID put stNum put arrTriger put (ClearDisplay stNum plNum) = do putWord8 1 -- SrcID putWord8 5 -- MessageID put stNum B.runEncode $ do B.putBitsFrom 3 (zeroBits :: Word8) B.encode plNum :: B.Coding PutM () get = do 1 <- getWord8 msgID <- getWord8 case msgID of 1 -> return OperationalATSSession 2 -> do stCode <- get departures <- getWord8 let n = fromIntegral departures ts <- replicateM n $ do t <- get skip 5 return t skip ((3 - n) * 10) return $ NextThreeDeparture stCode ts 3 -> do stCode <- get trInfo <- get skip 5 return $ DeparturePlatform stCode trInfo 4 -> do stCode <- get arr <- get return $ ArrivalPlatform stCode arr 5 -> do stCode <- get plNum <- B.runDecode $ do B.getBitsFrom 3 (zeroBits :: Word8) B.decode :: B.Coding Get PlatformNumber return $ ClearDisplay stCode plNum _ -> fail "oh my god!" instance Serialize MessagePA2ATS where put ConnectionRequest = do putWord8 2 -- SrcID putWord8 11 -- MessageID get = do 2 <- getWord8 msgID <- getWord8 case msgID of 11 -> return ConnectionRequest _ -> fail "oh my god!" instance Serialize ArrivalTrigger where put NonStopping = do putWord8 0 -- Non Stopping replicateM_ 6 (putWord8 zeroBits) put NotInService = do putWord8 1 -- Not In Service replicateM_ 6 (putWord8 zeroBits) put Terminated = do putWord8 2 -- Terminated replicateM_ 6 (putWord8 zeroBits) put (NextEstimatedTrain trInfo dwell) = do putWord8 3 -- Next Estimated Train put trInfo putWord8 dwell get = do arrivalTrigger <- getWord8 case arrivalTrigger of 0 -> do replicateM_ 6 (skip 1) return NonStopping 1 -> do replicateM_ 6 (skip 1) return NotInService 2 -> do replicateM_ 6 (skip 1) return Terminated 3 -> do trInfo <- get dwell <- getWord8 return $ NextEstimatedTrain trInfo dwell instance Serialize TrainInfo where put (TrainInfo profile pl hh mm ss dst) = do B.runEncode $ do B.encode profile :: B.Coding PutM () B.encode pl :: B.Coding PutM () putWord8 hh putWord8 mm putWord8 ss put dst get = do (profile, pl) <- B.runDecode $ do profile <- B.decode :: B.Coding Get RollingStockProfile pl <- B.decode :: B.Coding Get PlatformNumber return (profile, pl) hh <- getWord8 mm <- getWord8 ss <- getWord8 sc <- get return $ TrainInfo profile pl hh mm ss sc instance B.Coded PlatformNumber where encode PL1 = B.putBitsFrom 3 (1 :: Word8) encode PL2 = B.putBitsFrom 3 (2 :: Word8) encode PL3 = B.putBitsFrom 3 (3 :: Word8) decode = do w <- B.getBitsFrom 3 (zeroBits :: Word8) case w of 1 -> return PL1 2 -> return PL2 3 -> return PL3 _ -> fail "oh my god!" instance B.Coded RollingStockProfile where encode FourCar = B.putBitsFrom 3 (1 :: Word8) encode SixCar = B.putBitsFrom 3 (2 :: Word8) encode EightCar = B.putBitsFrom 3 (2 :: Word8) decode = do w <- B.getBitsFrom 3 (zeroBits :: Word8) case w of 1 -> return FourCar 2 -> return SixCar 3 -> return EightCar _ -> fail "oh my god!" instance Serialize StationCode where put = putWord8 . enc where enc :: StationCode -> Word8 enc JPW = 31 enc DBMR = 32 enc DSHP = 33 enc PALM = 34 enc SABR = 35 enc IGDA = 36 enc SKVR = 37 enc VTVR = 38 enc MIRK = 39 enc RKPM = 40 enc IIT = 41 enc HKS = 42 enc PSPK = 43 enc CDLI = 44 enc GKEI = 45 enc NUEE = 46 enc KJMD = 47 enc OKNS = 48 enc IWNR = 49 enc JANR = 50 enc OVA = 51 enc JLA = 52 enc KIKJ = 53 enc OKBS = 54 enc BTGD = 55 enc KIKD = 56 enc JSTB = 57 get = do w <- getWord8 return $ dec w where dec :: Word8 -> StationCode dec 31 = JPW dec 32 = DBMR dec 33 = DSHP dec 34 = PALM dec 35 = SABR dec 36 = IGDA dec 37 = SKVR dec 38 = VTVR dec 39 = MIRK dec 40 = RKPM dec 41 = IIT dec 42 = HKS dec 43 = PSPK dec 44 = CDLI dec 45 = GKEI dec 46 = NUEE dec 47 = KJMD dec 48 = OKNS dec 49 = IWNR dec 50 = JANR dec 51 = OVA dec 52 = JLA dec 53 = KIKJ dec 54 = OKBS dec 55 = BTGD dec 56 = KIKD dec 57 = JSTB
wkoiking/simulator-for-PA-interface
src/PA/Data.hs
bsd-3-clause
7,889
0
18
3,328
2,236
1,101
1,135
275
0
module Prototype.Internal ( ) where
plow-technologies/template-service
src/Prototype/Internal.hs
bsd-3-clause
44
0
3
13
9
6
3
2
0
module Options where import Data.Json.Path import Options.Applicative data Options = Options { fileArg :: Maybe String } getOptions = execParser opts opts = info (helper <*> opts') fullDesc where opts' = Options <$> optional (argument str (metavar "FILE" <> help "Input file")) glob = do s <- readGlobPath <$> str case s of Left x -> error (show x) Right x -> pure x
Prillan/haskell-jsontools
app/jless/Options.hs
bsd-3-clause
425
0
14
122
146
74
72
12
2