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
{-# LANGUAGE RecordWildCards #-} module GCommon.Objects.Transforms ( addPlayer , changePlayerSettings , changePlayerSettingsReset , removePlayer , getPlayer , updatePlayer , moveVehicle , setOrientation , addBullet , addBulletsFromPlayer , addToHealth ) where import Control.Monad.State ( execState , modify , get , put , StateT(..) ) import Data.Functor.Identity ( Identity ) import Control.Monad.Trans ( lift ) import qualified Data.Map as Map import Data.Map ( insert ) import Control.Lens ( (^.) , uses , (%=) , (.=) , use , view , zoom , set ) import qualified Linear as L import Linear ( V2(..) ) import Graphics.Rendering.OpenGL ( GLfloat ) import GCommon.Objects.Objects as GO import GCommon.Types.Generic ( ClientKey , PlayerSettings , PlayerSettingsReset , Direction(..) ) import GCommon.Geometry ( Angle , translate , rotate , scale , Rectangle , insideRectangle ) addPlayer :: Player -> WorldS () addPlayer ply = players %= (Map.insert (ply ^. pClientKey) ply) changePlayerSettings :: ClientKey -> PlayerSettings -> WorldS () changePlayerSettings key settings = getPlayer key >>= \plyM -> case plyM of Nothing -> return () Just ply -> players %= Map.insert (ply ^. pClientKey) (newPlayer key settings) changePlayerSettingsReset :: ClientKey -> PlayerSettingsReset -> WorldS () changePlayerSettingsReset key settings = getPlayer key >>= \plyM -> case plyM of Nothing -> return () Just ply -> players %= Map.insert (ply ^. pClientKey) (playerReset key (ply ^. pName) settings) removePlayer :: ClientKey -> WorldS () removePlayer key = players %= Map.delete key getPlayer :: ClientKey -> WorldS (Maybe Player) getPlayer key = uses players (Map.lookup key) addToHealth :: Float -> PlayerS () addToHealth h = (pVehicle . vHealth) %= (max 0 . min 100 . (+ h)) updatePlayer :: ClientKey -> PlayerS () -> WorldS () updatePlayer key comp = getPlayer key >>= \plyM -> case plyM of Nothing -> return () Just ply -> players %= Map.insert (ply ^. pClientKey) (execState comp ply) moveVehicle :: Rectangle -> Direction -> VehicleS () moveVehicle bounds dir = use vSpeed >>= \s -> use vPosition >>= \p -> vPosition %= const (newPos p s) where newPos (L.V2 x y) s = let (ofx, ofy) = help s inside = insideRectangle bounds (L.V2 (x + ofx) (y + ofy)) in if inside then L.V2 (x + ofx) (y + ofy) else L.V2 x y help s' = case dir of DUp -> (0.0, s') DLeft -> (-s', 0.0) DDown -> (0.0, -s') DRight -> (s', 0.0) setOrientation :: Angle -> VehicleS () setOrientation angle = vOrientation .= angle addBullet :: Bullet -> WorldS () addBullet bullet = bullets %= (bullet :) upVectorDim :: L.V2 GLfloat -> L.V3 GLfloat upVectorDim (L.V2 x y) = L.V3 x y 1 downVectorDim :: L.V3 GLfloat -> L.V2 GLfloat downVectorDim (L.V3 x y z) = L.V2 x y addBulletsFromPlayer :: ClientKey -> WorldS () addBulletsFromPlayer key = getPlayer key >>= \plyM -> case plyM of Nothing -> return () Just ply -> do let vehicleTrans = rotate $ ply ^. pVehicle . vOrientation - (pi / 2) mapM_ (\w -> do let bulletPos = (ply ^. pVehicle . vPosition) L.^+^ downVectorDim (vehicleTrans L.!* upVectorDim (w ^. wPosition)) bulletAngle = ply ^. pVehicle . vOrientation + w ^. wOrientation bullet = (w ^. wBullet) { _bPosition = bulletPos , _bOrientation = bulletAngle , _bTeam = ply ^. pTeam } addBullet bullet ) (ply ^. pVehicle . vWeapons)
cernat-catalin/haskellGame
src/GCommon/Objects/Transforms.hs
bsd-3-clause
5,020
0
26
2,275
1,304
697
607
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Main where import Web.Scotty.Trans (scottyT, ScottyT, ActionT, get, post, json, param, status, middleware, jsonData) import Network.Wai.Middleware.Cors (simpleCors) import Network.HTTP.Types (status200) import Network.URI (URI, parseURI) import Data.Text.Lazy (Text) import Control.Monad.Trans (liftIO) import Control.Monad.Reader (asks, runReaderT) import qualified Config import Config (ConfigReader, runConfigReader, port) import qualified Store import Store (FileType) import qualified Upload import Upload (Status(Ready), Actions(..), Method(Get, Put)) import User (token) type Error = Text type Action = ActionT Error ConfigReader () type App = ScottyT Error ConfigReader () main :: IO () main = do config <- Config.get let reader monad = runReaderT (runConfigReader monad) config scottyT (port config) reader app app :: App app = do middleware simpleCors get "/" $ status status200 post "/uploads/" createUpload get "/uploads/:id" findUpload createUpload :: Action createUpload = do request <- jsonData id <- liftIO Store.genId let domain = "scrub" -- TODO config asks put <- liftIO $ Store.genPut domain request let get = mkGet domain id let upload = Upload.Upload (token request) Ready (mkActions get put) liftIO $ Store.put domain id upload json upload findUpload :: Action findUpload = do id <- read <$> param "id" let domain = "scrub" -- TODO config asks upload <- liftIO (Store.get domain id :: IO Upload.Upload) json upload mkActions :: Store.Url -> Store.Url -> Actions mkActions get put = Actions [("check", Get, get), ("start", Put, put)] mkGet :: Config.Domain -> Store.Id -> Store.Url mkGet domain id = "http://" ++ domain ++ "/uploads/" ++ show id
svanderbleek/media-server
src/Main.hs
bsd-3-clause
1,844
0
12
379
620
333
287
69
1
main = mapM_ (putStrLn . fizzbuzz) [1..100] fizzbuzz x | x `mod` 15 == 0 = "FizzBuzz" | x `mod` 3 == 0 = "Fizz" | x `mod` 5 == 0 = "Buzz" | otherwise = show x
askl56/Challenges
Maths/02-FizzBuzz/solutions/askl56-fizzbuzz.hs
mit
178
0
9
57
97
49
48
6
1
module Main where import IRTS.CodegenBash import IRTS.Compiler import Idris.AbsSyntax import Idris.ElabDecls import Idris.REPL import System.Environment import System.Exit data Opts = Opts { inputs :: [FilePath] , output :: FilePath } showUsage :: IO () showUsage = do putStrLn "Usage: idris-bash <ibc-files> [-o <output-file>]" exitWith ExitSuccess getOpts :: IO Opts getOpts = do xs <- getArgs return $ reduce (Opts [] "a.sh") xs where reduce opts ("-o" : o : xs) = reduce (opts { output = o }) xs reduce opts (i : xs) = reduce (opts { inputs = i : inputs opts }) xs reduce opts [] = opts compileMain :: Opts -> Idris () compileMain opts = do elabPrims _ <- loadInputs (inputs opts) Nothing mainProg <- elabMain compileInfo <- compile (Via "bash") (output opts) (Just mainProg) runIO $ codegenBash compileInfo main :: IO () main = do opts <- getOpts if (null (inputs opts)) then showUsage else runMain (compileMain opts)
wskplho/idris-bash
src/Main.hs
mit
1,025
0
12
256
369
188
181
35
3
{- Copyright 2012-2013 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Plush.Utilities ( isBlank, readMaybe, readUtf8File, displayVersion, OutputVerbosity(..) ) where import Data.Maybe (listToMaybe) import Data.Version (Version(..), showVersion) import System.IO import qualified Paths_plush as CabalPaths -- | In the spec, <blank> is defined by the class current locale (§3.74). -- In plush, which is always UTF-8 based, it is simply <space> or <tab>. On many -- UTF-8 locales have <blank> include a few other (but not all) space chars. isBlank :: Char -> Bool isBlank ' ' = True isBlank '\t' = True isBlank _ = False -- | The missing read function. The string must parse entirely for this to -- return a value. readMaybe :: (Read a) => String -> Maybe a readMaybe = listToMaybe . map fst . filter (null . snd) . reads -- | Lazily get a text file's contents as with 'readFile', but assume its -- contents are encoded with UTF-8 regardless of the user's current locale. readUtf8File :: FilePath -> IO String readUtf8File path = do h <- openFile path ReadMode hSetEncoding h utf8 hGetContents h displayVersion :: String displayVersion = headOr (showVersion v) $ reverse $ versionTags v where v = CabalPaths.version headOr def [] = def headOr _ (a:_) = a -- | Level of output requested from a plush mode. data OutputVerbosity = OutputQuiet | OutputNormal | OutputJson
kustomzone/plush
src/Plush/Utilities.hs
apache-2.0
1,951
0
9
375
285
158
127
27
2
{-# LANGUAGE OverloadedLists #-} module Main (main) where import Data.Int (Int32) import Data.Maybe (isJust) import Control.Monad (when) import Control.Monad.IO.Class (liftIO) import qualified Data.Vector.Storable as V import TensorFlow.Core ( unScalar , render , run_ , runSession , run , withControlDependencies) import qualified TensorFlow.Ops as Ops import TensorFlow.Variable ( Variable , readValue , initializedValue , initializedVariable , assign , assignAdd , variable ) import Test.Framework (defaultMain, Test) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit ((@=?), assertFailure) main :: IO () main = defaultMain [ testInitializedVariable , testInitializedVariableShape , testInitializedValue , testDependency , testRereadRef , testAssignAdd ] testInitializedVariable :: Test testInitializedVariable = testCase "testInitializedVariable" $ runSession $ do (formula, reset) <- do v <- initializedVariable 42 r <- assign v 24 return (1 + readValue v, r) result <- run formula liftIO $ 43 @=? (unScalar result :: Float) run_ reset -- Updates v to a different value rerunResult <- run formula liftIO $ 25 @=? (unScalar rerunResult :: Float) testInitializedVariableShape :: Test testInitializedVariableShape = testCase "testInitializedVariableShape" $ runSession $ do vector <- initializedVariable (Ops.constant [1] [42 :: Float]) result <- run (readValue vector) liftIO $ [42] @=? (result :: V.Vector Float) s <- run (Ops.shape (readValue vector)) liftIO $ [1] @=? (s :: V.Vector Int32) testInitializedValue :: Test testInitializedValue = testCase "testInitializedValue" $ runSession $ do initialized <- initializedVariable (Ops.constant [1] [42 :: Float]) result <- run (initializedValue initialized) liftIO $ Just [42] @=? (result :: Maybe (V.Vector Float)) uninitialized <- variable [1] -- Can't use @=? because there is no Show instance for Tensor. when (isJust (initializedValue (uninitialized :: Variable Float))) $ liftIO $ assertFailure "initializedValue should be Nothing, got Just" testDependency :: Test testDependency = testCase "testDependency" $ runSession $ do v <- variable [] a <- assign v 24 r <- withControlDependencies a $ render (readValue v + 18) result <- run r liftIO $ (42 :: Float) @=? unScalar result -- | See https://github.com/tensorflow/haskell/issues/92. -- Even though we're not explicitly evaluating `f0` until the end, -- it should hold the earlier value of the variable. testRereadRef :: Test testRereadRef = testCase "testReRunAssign" $ runSession $ do w <- initializedVariable 0 f0 <- run (readValue w) run_ =<< assign w (Ops.scalar (0.1 :: Float)) f1 <- run (readValue w) liftIO $ (0.0, 0.1) @=? (unScalar f0, unScalar f1) testAssignAdd :: Test testAssignAdd = testCase "testAssignAdd" $ runSession $ do w <- initializedVariable 42 run_ =<< assignAdd w 17 f1 <- run (readValue w) liftIO $ (42 + 17 :: Float) @=? unScalar f1
tensorflow/haskell
tensorflow-ops/tests/VariableTest.hs
apache-2.0
3,314
0
16
838
938
485
453
84
1
-- Solution to Simultaneous Linear Equations using Matrices import Matrix solveEqns (Matrix coeff) (Matrix const) = (inverse (Matrix coeff)) |><| (Matrix const) main = do putStrLn "\nEnter the coefficient matrix -" mat <- getLine putStrLn "\nEnter the constant matrix -" con <- getLine putStrLn ("\n\nSolution matrix -\n" ++ show (solveEqns (Matrix $ read mat) (Matrix $ read con))) {- Output - 2 equations and 2 variables ------------------------------------ [rohitjha@rohitjha Implementation]$ runhaskell lineq.hs Enter the coefficient matrix - [[1,2],[1,1]] Enter the constant matrix - [[4],[1]] Solution matrix - -2.0 3.0 -} {- Output - 2 equations and 2 variables ------------------------------------ [rohitjha@rohitjha Implementation]$ runhaskell lineq.hs Enter the coefficient matrix - [[4,3],[5,12]] Enter the constant matrix - [[7],[13]] Solution matrix - 1.3636363636363635 0.5151515151515151 -} {- Output - 3 equations and 2 variables (No Solution) -------------------------------------------------- [rohitjha@rohitjha Implementation]$ runhaskell lineq.hs Enter the coefficient matrix - [[1,1],[2,2],[3,3]] Enter the constant matrix - [[2],[4],[6]] Solution matrix - lineq.hs: Prelude.head: empty list -}
rohitjha/DiMPL
examples/lineq.hs
bsd-2-clause
1,268
0
15
207
127
62
65
8
1
{-# LANGUAGE TemplateHaskellQuotes #-} module TH_bracket2 where d_show = [d| data A = A instance Show A where show _ = "A" |]
mpickering/ghc-exactprint
tests/examples/ghc8/TH_bracket2.hs
bsd-3-clause
168
0
4
65
14
11
3
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} module Bookstore ( Bug(..) , prop_bookstore , cleanup , setup ) where import Control.Concurrent (threadDelay) import Control.Monad.Reader (ReaderT, ask, runReaderT) import Data.Int (Int64) import Data.Kind (Type) import Data.List (dropWhileEnd, group, inits, isInfixOf, sort, tails) import Data.Maybe (fromJust) import Database.PostgreSQL.Simple as PS (ConnectInfo, Connection, Query, close, connect, connectDatabase, connectHost, connectPassword, connectPort, connectUser, defaultConnectInfo, execute, execute_, query) import Database.PostgreSQL.Simple.Errors (ConstraintViolation(..), catchViolation) import Database.PostgreSQL.Simple.FromRow (FromRow(fromRow), field) import GHC.Generics (Generic, Generic1) import Network.Socket as Sock (AddrInfoFlag(AI_NUMERICHOST, AI_NUMERICSERV), Socket, SocketType(Stream), addrAddress, addrFamily, addrFlags, addrProtocol, addrSocketType, close, connect, defaultHints, getAddrInfo, socket) import Prelude import System.Process (callProcess, readProcess) import Test.QuickCheck (Arbitrary(arbitrary), Gen, Property, arbitraryPrintableChar, choose, elements, frequency, ioProperty, listOf, oneof, shrink, suchThat, vectorOf, (===)) import Test.QuickCheck.Monadic (monadic) import UnliftIO (IOException, bracket, catch, liftIO, onException, throwIO) import Test.StateMachine import qualified Test.StateMachine.Types.Rank2 as Rank2 import Test.StateMachine.Z (codomain, domain) ------------------------------------------------------------------------ -- Based on Bookstore case study from: -- https://propertesting.com/book_case_study_stateful_properties_with_a_bookstore.html -- System under test: Parametrized SQL statements data Book = Book { isbn :: String , title :: String , author :: String , owned :: Int , avail :: Int } deriving stock (Eq, Show, Generic) instance ToExpr Book where instance FromRow Book where fromRow = Book <$> field <*> field <*> field <*> field <*> field handleViolations :: (Connection -> IO a) -> Connection -> IO (Maybe a) handleViolations fn cn = catchViolation catcher (Just <$> fn cn) where catcher _ (UniqueViolation _) = return Nothing catcher e _ = throwIO e setupTable :: Connection -> IO (Maybe Int64) setupTable = handleViolations $ \cn -> execute_ cn "CREATE TABLE books (\ \ isbn varchar(20) PRIMARY KEY,\ \ title varchar(256) NOT NULL,\ \ author varchar(256) NOT NULL,\ \ owned smallint DEFAULT 0,\ \ available smallint DEFAULT 0\ \ )" teardown :: Connection -> IO (Maybe Int64) teardown = handleViolations $ \cn -> execute_ cn "DROP TABLE books" addBook :: String -> String -> String -> Connection -> IO (Maybe Int64) addBook isbn_ title_ auth = handleViolations $ \cn -> execute cn templ (isbn_, title_, auth) where templ = "INSERT INTO books (isbn, title, author, owned, available)\ \ VALUES ( ?, ?, ?, 0, 0 )" update :: Query -> String -> Connection -> IO Int64 update prepStmt param cn = execute cn prepStmt [param] addCopy :: String -> Connection -> IO (Maybe Int64) addCopy isbn_ = handleViolations $ update templ isbn_ where templ = "UPDATE books SET\ \ owned = owned + 1,\ \ available = available + 1\ \ WHERE isbn = ?" borrowCopy :: String -> Connection -> IO (Maybe Int64) borrowCopy isbn_ = handleViolations (update templ isbn_) where templ = "UPDATE books SET available = available - 1 \ \ WHERE isbn = ? AND available > 0" returnCopy :: Bug -> String -> Connection -> IO (Maybe Int64) returnCopy bug isbn_ = handleViolations (update templ isbn_) where templ = if bug == Bug then "UPDATE books SET available = available + 1 WHERE isbn = ?;" else "UPDATE books SET available = available + 1\ \ WHERE isbn = ? AND available < owned;" select :: Query -> String -> Connection -> IO [Book] select prepStmt param cn = query cn prepStmt [param] findByAuthor, findByTitle :: Bug -> String -> Connection -> IO (Maybe [Book]) findByAuthor bug s = case bug of Injection -> handleViolations (select templ $ "%"++s++"%") _ -> handleViolations (select templ $ "%"++(sanitize s)++"%") where templ = "SELECT * FROM books WHERE author LIKE ?" findByTitle bug s = case bug of Injection -> handleViolations (select templ $ "%"++s++"%") _ -> handleViolations (select templ $ "%"++(sanitize s)++"%") where templ = "SELECT * FROM books WHERE title LIKE ?" findByIsbn :: String -> Connection -> IO (Maybe [Book]) findByIsbn s = handleViolations $ select "SELECT * FROM books WHERE isbn = ?" s -- XXX sanitize :: String -> String sanitize = concatMap (\c -> if c `elem` ['_', '%', '\\'] then '\\':[c] else [c]) withConnection :: ConnectInfo -> (Connection -> IO a) -> IO a withConnection connInfo = bracket (PS.connect connInfo) PS.close -- Modeling newtype Model r = Model [(Isbn, Book)] deriving stock (Generic, Show) instance ToExpr (Model Concrete) where initModel :: Model v initModel = Model [] newtype Isbn = Isbn { getString :: String } deriving stock (Eq, Show) instance ToExpr Isbn where toExpr = toExpr . show instance Arbitrary Isbn where arbitrary = oneof [isbn10, isbn13] where isbn10 = do gr <- isbnGroup t <- pubTitle (9 - length gr) c <- elements ('X':['0'..'9']) return $ Isbn (gr ++ "-" ++ t ++ "-" ++ [c]) isbn13 = do code <- elements ["978", "979"] Isbn x <- isbn10 return $ Isbn (code ++ "-" ++ x) isbnGroup :: Gen String isbnGroup = elements $ show <$> concat [ [0..5] :: [Integer] , [7] , [80..94] , [600..621] , [950..989] , [9926..9989] , [99901..99976] ] pubTitle :: Int -> Gen String pubTitle size = do i <- choose (1, size - 1) v1 <- vectorOf i $ choose ('0', '9') v2 <- vectorOf (size - i) $ choose ('0', '9') return $ v1 ++ "-" ++ v2 data Tag = New | Exist | Invalid | Avail | Unavail | Taken | Full deriving stock (Eq, Show) data Command (r :: Type -> Type) = NewBook Tag Isbn String String | AddCopy Tag Isbn | Borrow Tag Isbn | Return Tag Isbn | FindByAuthor Tag String | FindByTitle Tag String | FindByIsbn Tag Isbn deriving stock (Show, Generic1) instance Rank2.Foldable Command where instance Rank2.Functor Command where instance Rank2.Traversable Command where data Response (r :: Type -> Type) = Rows [Book] | Updated | Inserted | NotFound | UniqueError | OtherError deriving stock (Eq, Show, Generic1) instance Rank2.Foldable Response where generator :: Model Symbolic -> Maybe (Gen (Command Symbolic)) generator (Model m) = Just $ oneof $ [ NewBook New <$> newIsbn <*> stringGen <*> stringGen , AddCopy Invalid <$> newIsbn , Borrow Invalid <$> newIsbn , Return Invalid <$> newIsbn , FindByIsbn Invalid <$> newIsbn , FindByTitle Invalid <$> searchStringGen , FindByAuthor Invalid <$> searchStringGen ] ++ if null m then [] else [ NewBook Exist <$> existIsbn <*> stringGen <*> stringGen , AddCopy Exist <$> existIsbn , Borrow Avail <$> existIsbn , Borrow Unavail <$> existIsbn , Return Taken <$> existIsbn , Return Full <$> existIsbn , FindByIsbn Exist <$> existIsbn , FindByTitle Exist <$> genTitle , FindByAuthor Exist <$> genAuthor ] where newIsbn = arbitrary `suchThat` \x -> x `notElem` domain m existIsbn = elements $ domain m genTitle = elements $ (title <$> codomain m) >>= infixes genAuthor = elements $ (author <$> codomain m) >>= infixes stringGen :: Gen String stringGen = listOf arbitraryPrintableChar searchStringGen :: Gen String searchStringGen = listOf $ frequency [ (7, arbitraryPrintableChar) , (3, elements ['_', '%']) ] infixes :: Ord a => [a] -> [[a]] infixes l = map head . group . sort $ inits l >>= tails -- How to shrink Commands shrinker :: Model Symbolic -> Command Symbolic -> [Command Symbolic] shrinker _ (NewBook tag key x y) = [ NewBook tag key x y' | y' <- shrink y ] ++ [ NewBook tag key x' y | x' <- shrink x ] shrinker _ (FindByAuthor tag a) = [ FindByAuthor tag a' | a' <- shrink a ] shrinker _ (FindByTitle tag t) = [ FindByTitle tag t' | t' <- shrink t ] shrinker _ _ = [] -- Pre-requisites and invariants preconditions :: Model Symbolic -> Command Symbolic -> Logic preconditions (Model m) cmd = case cmd of AddCopy Invalid key -> Not $ hasKey key Borrow Invalid key -> Not $ hasKey key Return Invalid key -> Not $ hasKey key FindByIsbn Invalid key -> Not $ hasKey key NewBook New key _ _ -> Not $ hasKey key NewBook Exist key _ _ -> hasKey key AddCopy Exist key -> hasKey key FindByIsbn Exist key -> hasKey key Borrow Avail key -> keyPred key (\b -> avail b .> 0) Borrow Unavail key -> keyPred key (\b -> avail b .== 0) Return Taken key -> keyPred key (\b -> owned b .> avail b) Return Full key -> keyPred key (\b -> owned b .== avail b) FindByAuthor Invalid x -> Not $ Exists values (Boolean . isInfixOf x . author) FindByTitle Invalid x -> Not $ Exists values (Boolean . isInfixOf x . title) FindByTitle Exist x -> Exists values (Boolean . isInfixOf x . title) _ -> Top where values = codomain m hasKey key = key `member` (domain m) keyPred key p = maybe Bot p (lookup key m) postconditions :: Model Concrete -> Command Concrete -> Response Concrete -> Logic postconditions (Model m) cmd resp = case cmd of NewBook Exist _ _ _ -> resp .== UniqueError NewBook New _ _ _ -> resp .== Inserted AddCopy Invalid _ -> resp .== NotFound Return Invalid _ -> resp .== NotFound Borrow Invalid _ -> resp .== NotFound Return Full _ -> resp .== NotFound Borrow Unavail _ -> resp .== NotFound Borrow Avail _ -> resp .== Updated AddCopy Exist _ -> resp .== Updated Return Taken _ -> resp .== Updated FindByIsbn Invalid _ -> resp .== Rows [] FindByAuthor Invalid _ -> resp .== Rows [] FindByTitle Invalid _ -> resp .== Rows [] FindByIsbn Exist key -> case lookup key m of Just x -> Rows [x] .== resp _ -> error "Should not happen" FindByAuthor Exist x -> case resp of Rows rs -> Forall rs (Boolean . isInfixOf x . author) .&& Forall rs (\b -> Just b .== lookup (Isbn $ isbn b) m) _ -> Bot .// "findByAuthor returned " ++ (show resp) FindByTitle Exist x -> case resp of Rows rs -> Forall rs (Boolean . isInfixOf x . title) .&& Forall rs (\b -> Just b .== lookup (Isbn $ isbn b) m) _ -> Bot .// "findByTitle returned " ++ (show resp) _ -> Bot -- Transitions of the state machine that models SUT transitions :: Model r -> Command r -> Response r -> Model r transitions (Model m) cmd _ = Model $ case cmd of NewBook New key t a -> (key, Book (getString key) t a 0 0):m AddCopy Exist key -> map (applyForKey key $ incOwned . incAvail) m Borrow Avail key -> map (applyForKey key decAvail) m Return Taken key -> map (applyForKey key incAvail) m _ -> m where applyForKey key fn (k, v) = (k, if k == key then fn v else v) incOwned row = row { owned = 1 + owned row } incAvail row = row { avail = 1 + avail row } decAvail row = row { avail = (avail row) - 1 } -- Semantics data Bug = Bug | NoBug | Injection deriving stock Eq semantics :: Bug -> Command Concrete -> ReaderT ConnectInfo IO (Response Concrete) semantics bug cmd = do connInfo <- ask liftIO $ withConnection connInfo $ \cn -> case cmd of NewBook _ (Isbn key) t a -> toResp insertRes <$> addBook key t a cn AddCopy _ (Isbn key) -> toResp updateRes <$> addCopy key cn Borrow _ (Isbn key) -> toResp updateRes <$> borrowCopy key cn Return _ (Isbn key) -> toResp updateRes <$> returnCopy bug key cn FindByAuthor _ x -> toResp Rows <$> findByAuthor bug x cn FindByTitle _ x -> toResp Rows <$> findByTitle bug x cn FindByIsbn _ (Isbn key) -> toResp Rows <$> findByIsbn key cn where toResp = maybe UniqueError updateRes 0 = NotFound updateRes 1 = Updated updateRes _ = OtherError insertRes 1 = Inserted insertRes _ = OtherError -- Mock is currently not used by the library mock :: Model Symbolic -> Command Symbolic -> GenSym (Response Symbolic) mock (Model m) cmd = return $ case cmd of NewBook New _ _ _ -> Inserted NewBook Exist _ _ _ -> UniqueError AddCopy Invalid _ -> NotFound AddCopy Exist _ -> Updated Borrow Invalid _ -> NotFound Borrow Avail _ -> Updated Borrow Unavail _ -> NotFound Return Invalid _ -> NotFound Return Taken _ -> Updated Return Full _ -> NotFound FindByTitle Exist x -> Rows $ filter (isInfixOf x . title) (codomain m) FindByAuthor Exist x -> Rows $ filter (isInfixOf x . author) (codomain m) FindByIsbn Exist key -> Rows [fromJust (lookup key m)] FindByTitle Invalid _ -> Rows [] FindByIsbn Invalid _ -> Rows [] FindByAuthor Invalid _ -> Rows [] _ -> error $ (show cmd) ++ " should not happen" -- Property sm :: Bug -> StateMachine Model Command (ReaderT ConnectInfo IO) Response sm bug = StateMachine initModel transitions preconditions postconditions Nothing generator shrinker (semantics bug) mock noCleanup runner :: IO String -> ReaderT ConnectInfo IO Property -> IO Property runner io p = do dbIp <- io let connInfo = defaultConnectInfo { connectUser = "postgres" , connectPassword = "mysecretpassword" , connectDatabase = "postgres" , connectPort = 5432 , connectHost = dbIp } bracket (withConnection connInfo setupTable) (const (withConnection connInfo teardown)) (const (runReaderT p connInfo)) prop_bookstore :: Bug -> IO String -> Property prop_bookstore bug io = forAllCommands sm' Nothing $ \cmds -> monadic (ioProperty . runner io) $ do (hist, _, res) <- runCommands sm' cmds prettyCommands sm' hist $ res === Ok where sm' = sm bug -- Setup PostgreSQL db in Docker setup :: IO (String, String) setup = do pid <- trim <$> readProcess "docker" [ "run" , "-d" , "-e", "POSTGRES_PASSWORD=mysecretpassword" , "postgres:10.2" ] "" ip <- trim <$> readProcess "docker" [ "inspect" , pid , "--format" , "'{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'" ] "" healthyDb pid ip `onException` callProcess "docker" [ "rm", "-f", "-v", pid ] return (pid, ip) where trim :: String -> String trim = dropWhileEnd isGarbage . dropWhile isGarbage where isGarbage = flip elem ['\'', '\n'] healthyDb :: String -> String -> IO () healthyDb pid ip = do sock <- go 10 Sock.close sock where go :: Int -> IO Socket go 0 = error "healthyDb: db isn't healthy" go n = do let hints = defaultHints { addrFlags = [AI_NUMERICHOST , AI_NUMERICSERV] , addrSocketType = Stream } addr : _ <- getAddrInfo (Just hints) (Just ip) (Just "5432") sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr) (Sock.connect sock (addrAddress addr) >> readProcess "docker" [ "exec" , "-u", "postgres" , pid , "psql", "-U", "postgres", "-d", "postgres", "-c", "SELECT 1 + 1" ] "" >> return sock) `catch` (\(_ :: IOException) -> do threadDelay 1000000 go (n - 1)) cleanup :: (String, String) -> IO () cleanup (pid, _) = callProcess "docker" [ "rm", "-f", "-v", pid ]
advancedtelematic/quickcheck-state-machine-model
test/Bookstore.hs
bsd-3-clause
16,931
0
19
4,856
5,414
2,793
2,621
-1
-1
{-# LANGUAGE GADTs #-} -- | -- Module : Data.Array.Accelerate.Trafo.Normalise -- Copyright : [2012..2014] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module Data.Array.Accelerate.Trafo.Normalise ( anormalise ) where import Prelude hiding ( exp ) import Data.Array.Accelerate.AST import Data.Array.Accelerate.Product import Data.Array.Accelerate.Trafo.Substitution -- Convert to Administrative Normal (a-normal) Form, where lets-within-lets of -- an expression are flattened. -- -- let x = -- let y = e1 in e2 -- in e3 -- -- ==> -- -- let y = e1 in -- let x = e2 -- in e3 -- anormalise :: PreOpenExp acc env aenv t -> PreOpenExp acc env aenv t anormalise = cvt where split1 :: Idx (env, a) t -> Idx ((env, s), a) t split1 ZeroIdx = ZeroIdx split1 (SuccIdx ix) = SuccIdx (SuccIdx ix) cvtA :: acc aenv a -> acc aenv a cvtA = id cvtT :: Tuple (PreOpenExp acc env aenv) t -> Tuple (PreOpenExp acc env aenv) t cvtT NilTup = NilTup cvtT (SnocTup t e) = cvtT t `SnocTup` cvt e cvtF :: PreOpenFun acc env aenv f -> PreOpenFun acc env aenv f cvtF (Body e) = Body (cvt e) cvtF (Lam f) = Lam (cvtF f) cvt :: PreOpenExp acc env aenv e -> PreOpenExp acc env aenv e cvt exp = case exp of Let bnd body -> let bnd' = cvt bnd body' = cvt body in case bnd' of Let bnd'' body'' -> Let bnd'' $ Let body'' (weakenE split1 body') _ -> Let bnd' body' -- Var ix -> Var ix Const c -> Const c Tuple tup -> Tuple (cvtT tup) Prj tup ix -> Prj tup (cvt ix) IndexNil -> IndexNil IndexCons sh sz -> IndexCons (cvt sh) (cvt sz) IndexHead sh -> IndexHead (cvt sh) IndexTail sh -> IndexTail (cvt sh) IndexAny -> IndexAny IndexSlice x ix sh -> IndexSlice x (cvt ix) (cvt sh) IndexFull x ix sl -> IndexFull x (cvt ix) (cvt sl) ToIndex sh ix -> ToIndex (cvt sh) (cvt ix) FromIndex sh ix -> FromIndex (cvt sh) (cvt ix) Cond p t e -> Cond (cvt p) (cvt t) (cvt e) Iterate n f x -> Iterate n (cvt f) (cvt x) PrimConst c -> PrimConst c PrimApp f x -> PrimApp f (cvt x) Index a sh -> Index (cvtA a) (cvt sh) LinearIndex a i -> LinearIndex (cvtA a) (cvt i) Shape a -> Shape (cvtA a) ShapeSize sh -> ShapeSize (cvt sh) Intersect s t -> Intersect (cvt s) (cvt t) Foreign ff f e -> Foreign ff (cvtF f) (cvt e)
rrnewton/accelerate
Data/Array/Accelerate/Trafo/Normalise.hs
bsd-3-clause
3,073
0
18
1,187
977
485
492
52
28
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} -------------------------------------------------------------------------------- -- | -- Module : Data.Comp.Multi.Variables -- Copyright : (c) 2011 Patrick Bahr -- License : BSD3 -- Maintainer : Patrick Bahr <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC Extensions) -- -- This module defines an abstract notion of (bound) variables in compositional -- data types, and scoped substitution. Capture-avoidance is /not/ taken into -- account. All definitions are generalised versions of those in -- "Data.Comp.Variables". -- -------------------------------------------------------------------------------- module Data.Comp.Multi.Variables ( HasVars(..), GSubst, CxtSubst, Subst, varsToHoles, containsVar, variables, variableList, variables', appSubst, compSubst, getBoundVars, (&), (|->), empty ) where import Data.Comp.Multi.Algebra import Data.Comp.Multi.Derive import Data.Comp.Multi.HFoldable import Data.Comp.Multi.HFunctor import Data.Comp.Multi.Mapping import Data.Comp.Multi.Ops import Data.Comp.Multi.Term import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set type GSubst v a = Map v (A a) type CxtSubst h a f v = GSubst v (Cxt h f a) type Subst f v = CxtSubst NoHole (K ()) f v type SubstFun v a = NatM Maybe (K v) a substFun :: Ord v => GSubst v a -> SubstFun v a substFun s (K v) = fmap unA $ Map.lookup v s {-| This multiparameter class defines functors with variables. An instance @HasVar f v@ denotes that values over @f@ might contain and bind variables of type @v@. -} class HasVars (f :: (* -> *) -> * -> *) v where -- | Indicates whether the @f@ constructor is a variable. The -- default implementation returns @Nothing@. isVar :: f a :=> Maybe v isVar _ = Nothing -- | Indicates the set of variables bound by the @f@ constructor -- for each argument of the constructor. For example for a -- non-recursive let binding: -- -- @ -- data Let i e = Let Var (e i) (e i) -- instance HasVars Let Var where -- bindsVars (Let v x y) = y |-> Set.singleton v -- @ -- -- If, instead, the let binding is recursive, the methods has to -- be implemented like this: -- -- @ -- bindsVars (Let v x y) = x |-> Set.singleton v & -- y |-> Set.singleton v -- @ -- -- This indicates that the scope of the bound variable also -- extends to the right-hand side of the variable binding. -- -- The default implementation returns the empty map. bindsVars :: Mapping m a => f a :=> m (Set v) bindsVars _ = empty $(derive [liftSum] [''HasVars]) -- | Same as 'isVar' but it returns Nothing@ instead of @Just v@ if -- @v@ is contained in the given set of variables. isVar' :: (HasVars f v, Ord v) => Set v -> f a :=> Maybe v isVar' b t = do v <- isVar t if v `Set.member` b then Nothing else return v -- | This combinator pairs every argument of a given constructor with -- the set of (newly) bound variables according to the corresponding -- 'HasVars' type class instance. getBoundVars :: forall f a v i . (HasVars f v, HTraversable f) => f a i -> f (a :*: K (Set v)) i getBoundVars t = let n :: f (Numbered a) i n = number t m = bindsVars n trans :: Numbered a :-> (a :*: K (Set v)) trans (Numbered i x) = x :*: K (lookupNumMap Set.empty i m) in hfmap trans n -- | This combinator combines 'getBoundVars' with the 'mfmap' function. hfmapBoundVars :: forall f a b v i . (HasVars f v, HTraversable f) => (Set v -> a :-> b) -> f a i -> f b i hfmapBoundVars f t = let n :: f (Numbered a) i n = number t m = bindsVars n trans :: Numbered a :-> b trans (Numbered i x) = f (lookupNumMap Set.empty i m) x in hfmap trans n -- | This combinator combines 'getBoundVars' with the generic 'hfoldl' function. hfoldlBoundVars :: forall f a b v i . (HasVars f v, HTraversable f) => (b -> Set v -> a :=> b) -> b -> f a i -> b hfoldlBoundVars f e t = let n :: f (Numbered a) i n = number t m = bindsVars n trans :: b -> Numbered a :=> b trans x (Numbered i y) = f x (lookupNumMap Set.empty i m) y in hfoldl trans e n -- Auxiliary data type, used only to define varsToHoles newtype C a b i = C{ unC :: a -> b i } varsToHoles :: forall f v. (HTraversable f, HasVars f v, Ord v) => Term f :-> Context f (K v) varsToHoles t = unC (cata alg t) Set.empty where alg :: (HTraversable f, HasVars f v, Ord v) => Alg f (C (Set v) (Context f (K v))) alg t = C $ \vars -> case isVar t of Just v | not (v `Set.member` vars) -> Hole $ K v _ -> Term $ hfmapBoundVars run t where run :: Set v -> C (Set v) (Context f (K v)) :-> Context f (K v) run newVars f = f `unC` (newVars `Set.union` vars) -- | Convert variables to holes, except those that are bound. containsVarAlg :: forall v f . (Ord v, HasVars f v, HTraversable f) => v -> Alg f (K Bool) containsVarAlg v t = K $ hfoldlBoundVars run local t where local = case isVar t of Just v' -> v == v' Nothing -> False run :: Bool -> Set v -> K Bool i -> Bool run acc vars (K b) = acc || (not (v `Set.member` vars) && b) {-| This function checks whether a variable is contained in a context. -} containsVar :: (Ord v, HasVars f v, HTraversable f, HFunctor f) => v -> Cxt h f a :=> Bool containsVar v = unK . free (containsVarAlg v) (const $ K False) {-| This function computes the list of variables occurring in a context. -} variableList :: (HasVars f v, HTraversable f, HFunctor f, Ord v) => Cxt h f a :=> [v] variableList = Set.toList . variables -- |Algebra for checking whether a variable is contained in a term, except those -- that are bound. variablesAlg :: (Ord v, HasVars f v, HTraversable f) => Alg f (K (Set v)) variablesAlg t = K $ hfoldlBoundVars run local t where local = case isVar t of Just v -> Set.singleton v Nothing -> Set.empty run acc bvars (K vars) = acc `Set.union` (vars `Set.difference` bvars) {-| This function computes the set of variables occurring in a context. -} variables :: (Ord v, HasVars f v, HTraversable f, HFunctor f) => Cxt h f a :=> Set v variables = unK . free variablesAlg (const $ K Set.empty) {-| This function computes the set of variables occurring in a context. -} variables' :: (Ord v, HasVars f v, HFoldable f, HFunctor f) => Const f :=> Set v variables' c = case isVar c of Nothing -> Set.empty Just v -> Set.singleton v {-| This function substitutes variables in a context according to a partial mapping from variables to contexts.-} class SubstVars v t a where substVars :: SubstFun v t -> a :-> a appSubst :: (Ord v, SubstVars v t a) => GSubst v t -> a :-> a appSubst subst = substVars (substFun subst) instance (Ord v, HasVars f v, HTraversable f) => SubstVars v (Cxt h f a) (Cxt h f a) where -- have to use explicit GADT pattern matching!! substVars subst = doSubst Set.empty where doSubst :: Set v -> Cxt h f a :-> Cxt h f a doSubst _ (Hole a) = Hole a doSubst b (Term t) = case isVar' b t >>= subst . K of Just new -> new Nothing -> Term $ hfmapBoundVars run t where run :: Set v -> Cxt h f a :-> Cxt h f a run vars = doSubst (b `Set.union` vars) instance (SubstVars v t a, HFunctor f) => SubstVars v t (f a) where substVars subst = hfmap (substVars subst) {-| This function composes two substitutions @s1@ and @s2@. That is, applying the resulting substitution is equivalent to first applying @s2@ and then @s1@. -} compSubst :: (Ord v, HasVars f v, HTraversable f) => CxtSubst h a f v -> CxtSubst h a f v -> CxtSubst h a f v compSubst s1 = Map.map (\ (A t) -> A (appSubst s1 t))
spacekitteh/compdata
src/Data/Comp/Multi/Variables.hs
bsd-3-clause
8,880
0
20
2,679
2,458
1,301
1,157
133
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Bits -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This module defines bitwise operations for signed and unsigned -- integers. Instances of the class 'Bits' for the 'Int' and -- 'Integer' types are available from this module, and instances for -- explicitly sized integral types are available from the -- "Data.Int" and "Data.Word" modules. -- ----------------------------------------------------------------------------- module Data.Bits ( Bits( (.&.), (.|.), xor, complement, shift, rotate, zeroBits, bit, setBit, clearBit, complementBit, testBit, bitSizeMaybe, bitSize, isSigned, shiftL, shiftR, unsafeShiftL, unsafeShiftR, rotateL, rotateR, popCount ), FiniteBits( finiteBitSize, countLeadingZeros, countTrailingZeros ), bitDefault, testBitDefault, popCountDefault, toIntegralSized ) where -- Defines the @Bits@ class containing bit-based operations. -- See library document for details on the semantics of the -- individual operations. #define WORD_SIZE_IN_BITS 32 -- import GHC.Integer.BigInteger.Internals (bitInteger, popCountInteger) import Data.Maybe import GHC.Enum import GHC.Num import GHC.Base import GHC.Real infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR` infixl 7 .&. infixl 6 `xor` infixl 5 .|. {-# DEPRECATED bitSize "Use 'bitSizeMaybe' or 'finiteBitSize' instead" #-} -- deprecated in 7.8 -- | The 'Bits' class defines bitwise operations over integral types. -- -- * Bits are numbered from 0 with bit 0 being the least -- significant bit. class Eq a => Bits a where {-# MINIMAL (.&.), (.|.), xor, complement, (shift | (shiftL, shiftR)), (rotate | (rotateL, rotateR)), bitSize, bitSizeMaybe, isSigned, testBit, bit, popCount #-} -- | Bitwise \"and\" (.&.) :: a -> a -> a -- | Bitwise \"or\" (.|.) :: a -> a -> a -- | Bitwise \"xor\" xor :: a -> a -> a {-| Reverse all the bits in the argument -} complement :: a -> a {-| @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive, or right by @-i@ bits otherwise. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. An instance can define either this unified 'shift' or 'shiftL' and 'shiftR', depending on which is more convenient for the type in question. -} shift :: a -> Int -> a x `shift` i | i<0 = x `shiftR` (-i) | i>0 = x `shiftL` i | otherwise = x {-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive, or right by @-i@ bits otherwise. For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'. An instance can define either this unified 'rotate' or 'rotateL' and 'rotateR', depending on which is more convenient for the type in question. -} rotate :: a -> Int -> a x `rotate` i | i<0 = x `rotateR` (-i) | i>0 = x `rotateL` i | otherwise = x {- -- Rotation can be implemented in terms of two shifts, but care is -- needed for negative values. This suggested implementation assumes -- 2's-complement arithmetic. It is commented out because it would -- require an extra context (Ord a) on the signature of 'rotate'. x `rotate` i | i<0 && isSigned x && x<0 = let left = i+bitSize x in ((x `shift` i) .&. complement ((-1) `shift` left)) .|. (x `shift` left) | i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x)) | i==0 = x | i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x)) -} -- | 'zeroBits' is the value with all bits unset. -- -- The following laws ought to hold (for all valid bit indices @/n/@): -- -- * @'clearBit' 'zeroBits' /n/ == 'zeroBits'@ -- * @'setBit' 'zeroBits' /n/ == 'bit' /n/@ -- * @'testBit' 'zeroBits' /n/ == False@ -- * @'popCount' 'zeroBits' == 0@ -- -- This method uses @'clearBit' ('bit' 0) 0@ as its default -- implementation (which ought to be equivalent to 'zeroBits' for -- types which possess a 0th bit). -- -- @since 4.7.0.0 zeroBits :: a zeroBits = clearBit (bit 0) 0 -- | @bit /i/@ is a value with the @/i/@th bit set and all other bits clear. -- -- Can be implemented using `bitDefault' if @a@ is also an -- instance of 'Num'. -- -- See also 'zeroBits'. bit :: Int -> a -- | @x \`setBit\` i@ is the same as @x .|. bit i@ setBit :: a -> Int -> a -- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@ clearBit :: a -> Int -> a -- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@ complementBit :: a -> Int -> a -- | Return 'True' if the @n@th bit of the argument is 1 -- -- Can be implemented using `testBitDefault' if @a@ is also an -- instance of 'Num'. testBit :: a -> Int -> Bool {-| Return the number of bits in the type of the argument. The actual value of the argument is ignored. Returns Nothing for types that do not have a fixed bitsize, like 'Integer'. @since 4.7.0.0 -} bitSizeMaybe :: a -> Maybe Int {-| Return the number of bits in the type of the argument. The actual value of the argument is ignored. The function 'bitSize' is undefined for types that do not have a fixed bitsize, like 'Integer'. -} bitSize :: a -> Int {-| Return 'True' if the argument is a signed type. The actual value of the argument is ignored -} isSigned :: a -> Bool {-# INLINE setBit #-} {-# INLINE clearBit #-} {-# INLINE complementBit #-} x `setBit` i = x .|. bit i x `clearBit` i = x .&. complement (bit i) x `complementBit` i = x `xor` bit i {-| Shift the argument left by the specified number of bits (which must be non-negative). An instance can define either this and 'shiftR' or the unified 'shift', depending on which is more convenient for the type in question. -} shiftL :: a -> Int -> a {-# INLINE shiftL #-} x `shiftL` i = x `shift` i {-| Shift the argument left by the specified number of bits. The result is undefined for negative shift amounts and shift amounts greater or equal to the 'bitSize'. Defaults to 'shiftL' unless defined explicitly by an instance. @since 4.5.0.0 -} unsafeShiftL :: a -> Int -> a {-# INLINE unsafeShiftL #-} x `unsafeShiftL` i = x `shiftL` i {-| Shift the first argument right by the specified number of bits. The result is undefined for negative shift amounts and shift amounts greater or equal to the 'bitSize'. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. An instance can define either this and 'shiftL' or the unified 'shift', depending on which is more convenient for the type in question. -} shiftR :: a -> Int -> a {-# INLINE shiftR #-} x `shiftR` i = x `shift` (-i) {-| Shift the first argument right by the specified number of bits, which must be non-negative and smaller than the number of bits in the type. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. Defaults to 'shiftR' unless defined explicitly by an instance. @since 4.5.0.0 -} unsafeShiftR :: a -> Int -> a {-# INLINE unsafeShiftR #-} x `unsafeShiftR` i = x `shiftR` i {-| Rotate the argument left by the specified number of bits (which must be non-negative). An instance can define either this and 'rotateR' or the unified 'rotate', depending on which is more convenient for the type in question. -} rotateL :: a -> Int -> a {-# INLINE rotateL #-} x `rotateL` i = x `rotate` i {-| Rotate the argument right by the specified number of bits (which must be non-negative). An instance can define either this and 'rotateL' or the unified 'rotate', depending on which is more convenient for the type in question. -} rotateR :: a -> Int -> a {-# INLINE rotateR #-} x `rotateR` i = x `rotate` (-i) {-| Return the number of set bits in the argument. This number is known as the population count or the Hamming weight. Can be implemented using `popCountDefault' if @a@ is also an instance of 'Num'. @since 4.5.0.0 -} popCount :: a -> Int -- |The 'FiniteBits' class denotes types with a finite, fixed number of bits. -- -- @since 4.7.0.0 class Bits b => FiniteBits b where -- | Return the number of bits in the type of the argument. -- The actual value of the argument is ignored. Moreover, 'finiteBitSize' -- is total, in contrast to the deprecated 'bitSize' function it replaces. -- -- @ -- 'finiteBitSize' = 'bitSize' -- 'bitSizeMaybe' = 'Just' . 'finiteBitSize' -- @ -- -- @since 4.7.0.0 finiteBitSize :: b -> Int -- | Count number of zero bits preceding the most significant set bit. -- -- @ -- 'countLeadingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a) -- @ -- -- 'countLeadingZeros' can be used to compute log base 2 via -- -- @ -- logBase2 x = 'finiteBitSize' x - 1 - 'countLeadingZeros' x -- @ -- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive -- integral types are implemented using CPU specific machine -- instructions. -- -- @since 4.8.0.0 countLeadingZeros :: b -> Int countLeadingZeros x = (w-1) - go (w-1) where go i | i < 0 = i -- no bit set | testBit x i = i | otherwise = go (i-1) w = finiteBitSize x -- | Count number of zero bits following the least significant set bit. -- -- @ -- 'countTrailingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a) -- 'countTrailingZeros' . 'negate' = 'countTrailingZeros' -- @ -- -- The related -- <http://en.wikipedia.org/wiki/Find_first_set find-first-set operation> -- can be expressed in terms of 'countTrailingZeros' as follows -- -- @ -- findFirstSet x = 1 + 'countTrailingZeros' x -- @ -- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive -- integral types are implemented using CPU specific machine -- instructions. -- -- @since 4.8.0.0 countTrailingZeros :: b -> Int countTrailingZeros x = go 0 where go i | i >= w = i | testBit x i = i | otherwise = go (i+1) w = finiteBitSize x -- The defaults below are written with lambdas so that e.g. -- bit = bitDefault -- is fully applied, so inlining will happen -- | Default implementation for 'bit'. -- -- Note that: @bitDefault i = 1 `shiftL` i@ -- -- @since 4.6.0.0 bitDefault :: (Bits a, Num a) => Int -> a bitDefault = \i -> 1 `shiftL` i {-# INLINE bitDefault #-} -- | Default implementation for 'testBit'. -- -- Note that: @testBitDefault x i = (x .&. bit i) /= 0@ -- -- @since 4.6.0.0 testBitDefault :: (Bits a, Num a) => a -> Int -> Bool testBitDefault = \x i -> (x .&. bit i) /= 0 {-# INLINE testBitDefault #-} -- | Default implementation for 'popCount'. -- -- This implementation is intentionally naive. Instances are expected to provide -- an optimized implementation for their size. -- -- @since 4.6.0.0 popCountDefault :: (Bits a, Num a) => a -> Int popCountDefault = go 0 where go !c 0 = c go c w = go (c+1) (w .&. (w - 1)) -- clear the least significant {-# INLINABLE popCountDefault #-} -- Interpret 'Bool' as 1-bit bit-field; @since 4.7.0.0 instance Bits Bool where (.&.) = (&&) (.|.) = (||) xor = (/=) complement = not shift x 0 = x shift _ _ = False rotate x _ = x bit 0 = True bit _ = False testBit x 0 = x testBit _ _ = False bitSizeMaybe _ = Just 1 bitSize _ = 1 isSigned _ = False popCount False = 0 popCount True = 1 -- | @since 4.7.0.0 instance FiniteBits Bool where finiteBitSize _ = 1 countTrailingZeros x = if x then 0 else 1 countLeadingZeros x = if x then 0 else 1 -- | @since 2.01 instance Bits Int where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} zeroBits = 0 bit = bitDefault testBit = testBitDefault (I# x#) .&. (I# y#) = I# (x# `andI#` y#) (I# x#) .|. (I# y#) = I# (x# `orI#` y#) (I# x#) `xor` (I# y#) = I# (x# `xorI#` y#) complement (I# x#) = I# (notI# x#) (I# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = I# (x# `iShiftL#` i#) | otherwise = I# (x# `iShiftRA#` negateInt# i#) (I# x#) `shiftL` (I# i#) = I# (x# `iShiftL#` i#) (I# x#) `unsafeShiftL` (I# i#) = I# (x# `uncheckedIShiftL#` i#) (I# x#) `shiftR` (I# i#) = I# (x# `iShiftRA#` i#) (I# x#) `unsafeShiftR` (I# i#) = I# (x# `uncheckedIShiftRA#` i#) {-# INLINE rotate #-} -- See Note [Constant folding for rotate] (I# x#) `rotate` (I# i#) = I# ((x# `uncheckedIShiftL#` i'#) `orI#` (x# `uncheckedIShiftRL#` (wsib -# i'#))) where !i'# = i# `andI#` (wsib -# 1#) !wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -} bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i popCount (I# x#) = I# (word2Int# (popCnt# (int2Word# x#))) isSigned _ = True -- | @since 4.6.0.0 instance FiniteBits Int where finiteBitSize _ = WORD_SIZE_IN_BITS countLeadingZeros (I# x#) = I# (word2Int# (clz# (int2Word# x#))) countTrailingZeros (I# x#) = I# (word2Int# (ctz# (int2Word# x#))) -- | @since 2.01 instance Bits Word where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W# x#) .&. (W# y#) = W# (x# `and#` y#) (W# x#) .|. (W# y#) = W# (x# `or#` y#) (W# x#) `xor` (W# y#) = W# (x# `xor#` y#) complement (W# x#) = W# (x# `xor#` mb#) where !(W# mb#) = maxBound (W# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W# (x# `shiftL#` i#) | otherwise = W# (x# `shiftRL#` negateInt# i#) (W# x#) `shiftL` (I# i#) = W# (x# `shiftL#` i#) (W# x#) `unsafeShiftL` (I# i#) = W# (x# `uncheckedShiftL#` i#) (W# x#) `shiftR` (I# i#) = W# (x# `shiftRL#` i#) (W# x#) `unsafeShiftR` (I# i#) = W# (x# `uncheckedShiftRL#` i#) (W# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W# x# | otherwise = W# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (wsib -# i'#))) where !i'# = i# `andI#` (wsib -# 1#) !wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -} bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = False popCount (W# x#) = I# (word2Int# (popCnt# x#)) bit = bitDefault testBit = testBitDefault -- | @since 4.6.0.0 instance FiniteBits Word where finiteBitSize _ = WORD_SIZE_IN_BITS countLeadingZeros (W# x#) = I# (word2Int# (clz# x#)) countTrailingZeros (W# x#) = I# (word2Int# (ctz# x#)) -- | @since 2.01 instance Bits Integer where (.&.) = andInteger (.|.) = orInteger xor = xorInteger complement = complementInteger shift x i@(I# i#) | i >= 0 = shiftLInteger x i# | otherwise = shiftRInteger x (negateInt# i#) testBit x (I# i) = testBitInteger x i zeroBits = 0 bit = bitDefault popCount = popCountDefault rotate x i = shift x i -- since an Integer never wraps around bitSizeMaybe _ = Nothing bitSize _ = errorWithoutStackTrace "Data.Bits.bitSize(Integer)" isSigned _ = True ----------------------------------------------------------------------------- -- | Attempt to convert an 'Integral' type @a@ to an 'Integral' type @b@ using -- the size of the types as measured by 'Bits' methods. -- -- A simpler version of this function is: -- -- > toIntegral :: (Integral a, Integral b) => a -> Maybe b -- > toIntegral x -- > | toInteger x == y = Just (fromInteger y) -- > | otherwise = Nothing -- > where -- > y = toInteger x -- -- This version requires going through 'Integer', which can be inefficient. -- However, @toIntegralSized@ is optimized to allow GHC to statically determine -- the relative type sizes (as measured by 'bitSizeMaybe' and 'isSigned') and -- avoid going through 'Integer' for many types. (The implementation uses -- 'fromIntegral', which is itself optimized with rules for @base@ types but may -- go through 'Integer' for some type pairs.) -- -- @since 4.8.0.0 toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b toIntegralSized x -- See Note [toIntegralSized optimization] | maybe True (<= x) yMinBound , maybe True (x <=) yMaxBound = Just y | otherwise = Nothing where y = fromIntegral x xWidth = bitSizeMaybe x yWidth = bitSizeMaybe y yMinBound | isBitSubType x y = Nothing | isSigned x, not (isSigned y) = Just 0 | isSigned x, isSigned y , Just yW <- yWidth = Just (negate $ bit (yW-1)) -- Assumes sub-type | otherwise = Nothing yMaxBound | isBitSubType x y = Nothing | isSigned x, not (isSigned y) , Just xW <- xWidth, Just yW <- yWidth , xW <= yW+1 = Nothing -- Max bound beyond a's domain | Just yW <- yWidth = if isSigned y then Just (bit (yW-1)-1) else Just (bit yW-1) | otherwise = Nothing {-# INLINABLE toIntegralSized #-} -- | 'True' if the size of @a@ is @<=@ the size of @b@, where size is measured -- by 'bitSizeMaybe' and 'isSigned'. isBitSubType :: (Bits a, Bits b) => a -> b -> Bool isBitSubType x y -- Reflexive | xWidth == yWidth, xSigned == ySigned = True -- Every integer is a subset of 'Integer' | ySigned, Nothing == yWidth = True | not xSigned, not ySigned, Nothing == yWidth = True -- Sub-type relations between fixed-with types | xSigned == ySigned, Just xW <- xWidth, Just yW <- yWidth = xW <= yW | not xSigned, ySigned, Just xW <- xWidth, Just yW <- yWidth = xW < yW | otherwise = False where xWidth = bitSizeMaybe x xSigned = isSigned x yWidth = bitSizeMaybe y ySigned = isSigned y {-# INLINE isBitSubType #-} {- Note [Constant folding for rotate] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The INLINE on the Int instance of rotate enables it to be constant folded. For example: sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int) goes to: Main.$wfold = \ (ww_sO7 :: Int#) (ww1_sOb :: Int#) -> case ww1_sOb of wild_XM { __DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1); 10000000 -> ww_sO7 whereas before it was left as a call to $wrotate. All other Bits instances seem to inline well enough on their own to enable constant folding; for example 'shift': sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int) goes to: Main.$wfold = \ (ww_sOb :: Int#) (ww1_sOf :: Int#) -> case ww1_sOf of wild_XM { __DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1); 10000000 -> ww_sOb } -} -- Note [toIntegralSized optimization] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- The code in 'toIntegralSized' relies on GHC optimizing away statically -- decidable branches. -- -- If both integral types are statically known, GHC will be able optimize the -- code significantly (for @-O1@ and better). -- -- For instance (as of GHC 7.8.1) the following definitions: -- -- > w16_to_i32 = toIntegralSized :: Word16 -> Maybe Int32 -- > -- > i16_to_w16 = toIntegralSized :: Int16 -> Maybe Word16 -- -- are translated into the following (simplified) /GHC Core/ language: -- -- > w16_to_i32 = \x -> Just (case x of _ { W16# x# -> I32# (word2Int# x#) }) -- > -- > i16_to_w16 = \x -> case eta of _ -- > { I16# b1 -> case tagToEnum# (<=# 0 b1) of _ -- > { False -> Nothing -- > ; True -> Just (W16# (narrow16Word# (int2Word# b1))) -- > } -- > }
rahulmutt/ghcvm
libraries/base/Data/Bits.hs
bsd-3-clause
21,536
0
14
6,304
3,603
2,008
1,595
254
2
{-# LANGUAGE PatternGuards #-} module Idris.DataOpts where -- Forcing, detagging and collapsing import Idris.AbsSyntax import Core.TT import Data.List import Data.Maybe import Debug.Trace -- Calculate the forceable arguments to a constructor and update the set of -- optimisations forceArgs :: Name -> Type -> Idris () forceArgs n t = do i <- getIState let fargs = force i 0 t copt <- case lookupCtxt n (idris_optimisation i) of [] -> return $ Optimise False [] [] (op:_) -> return op let opts = addDef n (copt { forceable = fargs }) (idris_optimisation i) putIState (i { idris_optimisation = opts }) addIBC (IBCOpt n) iLOG $ "Forced: " ++ show n ++ " " ++ show fargs ++ "\n from " ++ show t where force :: IState -> Int -> Term -> [Int] force ist i (Bind _ (Pi ty) sc) | collapsibleIn ist ty = nub $ i : (force ist (i + 1) $ instantiate (P Bound (MN i "?") Erased) sc) | otherwise = force ist (i + 1) $ instantiate (P Bound (MN i "?") Erased) sc force _ _ sc@(App f a) | (_, args) <- unApply sc = nub $ concatMap guarded args force _ _ _ = [] collapsibleIn i t | (P _ tn _, _) <- unApply t = case lookupCtxt tn (idris_optimisation i) of [oi] -> collapsible oi _ -> False | otherwise = False isF (P _ (MN force "?") _) = Just force isF _ = Nothing guarded :: Term -> [Int] guarded t@(App f a) -- | (P (TCon _ _) _ _, args) <- unApply t -- = mapMaybe isF args ++ concatMap guarded args | (P (DCon _ _) _ _, args) <- unApply t = mapMaybe isF args ++ concatMap guarded args guarded t = mapMaybe isF [t] -- Calculate whether a collection of constructors is collapsible collapseCons :: Name -> [(Name, Type)] -> Idris () collapseCons ty cons = do i <- getIState let cons' = map (\ (n, t) -> (n, map snd (getArgTys t))) cons allFR <- mapM (forceRec i) cons' if and allFR then detaggable (map getRetTy (map snd cons)) else return () -- not collapsible as not detaggable where setCollapsible :: Name -> Idris () setCollapsible n = do i <- getIState iLOG $ show n ++ " collapsible" case lookupCtxt n (idris_optimisation i) of (oi:_) -> do let oi' = oi { collapsible = True } let opts = addDef n oi' (idris_optimisation i) putIState (i { idris_optimisation = opts }) [] -> do let oi = Optimise True [] [] let opts = addDef n oi (idris_optimisation i) putIState (i { idris_optimisation = opts }) addIBC (IBCOpt n) forceRec :: IState -> (Name, [Type]) -> Idris Bool forceRec i (n, ts) = case lookupCtxt n (idris_optimisation i) of (oi:_) -> checkFR (forceable oi) 0 ts _ -> return False checkFR fs i [] = return True checkFR fs i (_ : xs) | i `elem` fs = checkFR fs (i + 1) xs checkFR fs i (t : xs) -- must be recursive or type is not collapsible = do let (rtf, rta) = unApply $ getRetTy t if (ty `elem` freeNames rtf) then checkFR fs (i+1) xs else return False detaggable :: [Type] -> Idris () detaggable rtys = do let rtyArgs = map (snd . unApply) rtys -- if every rtyArgs is disjoint with every other, it's detaggable, -- therefore also collapsible given forceable/recursive check if disjoint rtyArgs then mapM_ setCollapsible (ty : map fst cons) else return () disjoint :: [[Term]] -> Bool disjoint [] = True disjoint [x] = True disjoint (x : xs) = anyDisjoint x xs && disjoint xs anyDisjoint x [] = True anyDisjoint x (y : ys) = disjointCons x y disjointCons [] [] = False disjointCons [] y = False disjointCons x [] = False disjointCons (x : xs) (y : ys) = disjointCon x y || disjointCons xs ys disjointCon x y = let (cx, _) = unApply x (cy, _) = unApply y in case (cx, cy) of (P (DCon _ _) nx _, P (DCon _ _) ny _) -> nx /= ny _ -> False class Optimisable term where applyOpts :: term -> Idris term stripCollapsed :: term -> Idris term instance (Optimisable a, Optimisable b) => Optimisable (a, b) where applyOpts (x, y) = do x' <- applyOpts x y' <- applyOpts y return (x', y') stripCollapsed (x, y) = do x' <- stripCollapsed x y' <- stripCollapsed y return (x', y') instance (Optimisable a, Optimisable b) => Optimisable (vs, a, b) where applyOpts (v, x, y) = do x' <- applyOpts x y' <- applyOpts y return (v, x', y') stripCollapsed (v, x, y) = do x' <- stripCollapsed x y' <- stripCollapsed y return (v, x', y') instance Optimisable a => Optimisable [a] where applyOpts = mapM applyOpts stripCollapsed = mapM stripCollapsed instance Optimisable a => Optimisable (Either a (a, a)) where applyOpts (Left t) = do t' <- applyOpts t; return $ Left t' applyOpts (Right t) = do t' <- applyOpts t; return $ Right t' stripCollapsed (Left t) = do t' <- stripCollapsed t; return $ Left t' stripCollapsed (Right t) = do t' <- stripCollapsed t; return $ Right t' -- Raw is for compile time optimisation (before type checking) -- Term is for run time optimisation (after type checking, collapsing allowed) -- Compile time: no collapsing instance Optimisable Raw where applyOpts t@(RApp f a) | (Var n, args) <- raw_unapply t -- MAGIC HERE = do args' <- mapM applyOpts args i <- getIState case lookupCtxt n (idris_optimisation i) of (oi:_) -> return $ applyDataOpt oi n args' _ -> return (raw_apply (Var n) args') | otherwise = do f' <- applyOpts f a' <- applyOpts a return (RApp f' a') applyOpts (RBind n b t) = do b' <- applyOpts b t' <- applyOpts t return (RBind n b' t') applyOpts (RForce t) = applyOpts t applyOpts t = return t stripCollapsed t = return t instance Optimisable t => Optimisable (Binder t) where applyOpts (Let t v) = do t' <- applyOpts t v' <- applyOpts v return (Let t' v') applyOpts b = do t' <- applyOpts (binderTy b) return (b { binderTy = t' }) stripCollapsed (Let t v) = do t' <- stripCollapsed t v' <- stripCollapsed v return (Let t' v') stripCollapsed b = do t' <- stripCollapsed (binderTy b) return (b { binderTy = t' }) applyDataOpt :: OptInfo -> Name -> [Raw] -> Raw applyDataOpt oi n args = let args' = zipWith doForce (map (\x -> x `elem` (forceable oi)) [0..]) args in raw_apply (Var n) args' where doForce True a = RForce a doForce False a = a -- Run-time: do everything instance Optimisable (TT Name) where applyOpts c@(P (DCon t arity) n _) = do i <- getIState case lookupCtxt n (idris_optimisation i) of (oi:_) -> return $ applyDataOptRT oi n t arity [] _ -> return c applyOpts t@(App f a) | (c@(P (DCon t arity) n _), args) <- unApply t -- MAGIC HERE = do args' <- mapM applyOpts args i <- getIState case lookupCtxt n (idris_optimisation i) of (oi:_) -> do return $ applyDataOptRT oi n t arity args' _ -> return (mkApp c args') | otherwise = do f' <- applyOpts f a' <- applyOpts a return (App f' a') applyOpts (Bind n b t) = do b' <- applyOpts b t' <- applyOpts t return (Bind n b' t') applyOpts (Proj t i) = do t' <- applyOpts t return (Proj t' i) applyOpts t = return t stripCollapsed (Bind n (PVar x) t) | (P _ ty _, _) <- unApply x = do i <- getIState case lookupCtxt ty (idris_optimisation i) of [oi] -> if collapsible oi then do t' <- stripCollapsed t return (Bind n (PVar x) (instantiate Erased t')) else do t' <- stripCollapsed t return (Bind n (PVar x) t') _ -> do t' <- stripCollapsed t return (Bind n (PVar x) t') stripCollapsed (Bind n (PVar x) t) = do t' <- stripCollapsed t return (Bind n (PVar x) t') stripCollapsed t = return t -- Need to saturate arguments first to ensure that erasure happens uniformly applyDataOptRT :: OptInfo -> Name -> Int -> Int -> [Term] -> Term applyDataOptRT oi n tag arity args | length args == arity = doOpts n args (collapsible oi) (forceable oi) | otherwise = let extra = satArgs (arity - length args) tm = doOpts n (args ++ map (\n -> P Bound n Erased) extra) (collapsible oi) (forceable oi) in bind extra tm where satArgs n = map (\i -> MN i "sat") [1..n] bind [] tm = tm bind (n:ns) tm = Bind n (Lam Erased) (pToV n (bind ns tm)) doOpts n args True f = Erased doOpts n args _ forced = let args' = filter keep (zip (map (\x -> x `elem` forced) [0..]) args) in mkApp (P (DCon tag (arity - length forced)) n Erased) (map snd args') keep (forced, _) = not forced
byorgey/Idris-dev
src/Idris/DataOpts.hs
bsd-3-clause
10,452
0
19
4,147
3,795
1,854
1,941
205
15
{-# LANGUAGE OverloadedStrings #-} module VForth.LocationBench where import Criterion.Main import qualified Data.Text as T import TextShow import VForth benchmarks :: [Benchmark] benchmarks = [ bench "length.show" (whnf (T.length . showt) l) , bench "show" (whnf showt l) ] where l = Location { locTitle = "Your Bedroom" , locDescription = T.pack $ unlines [ "You're in your bedroom. It's an utterly disgusting tip of a place. ", "Dirty coffee mugs everywhere, bits of computer and motorbike all ", "over the floor. It's an outrage. You can leave by going north, and ", "maybe you should." ] , locItems = [] }
budgefeeney/ventureforth
chap6/bench/VForth/LocationBench.hs
bsd-3-clause
700
0
11
191
130
77
53
18
1
{-# LANGUAGE CPP #-} {-# LANGUAGE InterruptibleFFI #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE NoImplicitPrelude #-} module GHC.IO.Handle.Lock ( FileLockingNotSupported(..) , LockMode(..) , hLock , hTryLock , hUnlock ) where #include "HsBaseConfig.h" import Data.Functor (void) import GHC.Base import GHC.IO.Handle.Lock.Common (LockMode(..), FileLockingNotSupported(..)) import GHC.IO.Handle.Types (Handle) #if defined(mingw32_HOST_OS) import GHC.IO.Handle.Lock.Windows #elif HAVE_OFD_LOCKING import GHC.IO.Handle.Lock.LinuxOFD #elif HAVE_FLOCK import GHC.IO.Handle.Lock.Flock #else import GHC.IO.Handle.Lock.NoOp #endif -- | If a 'Handle' references a file descriptor, attempt to lock contents of the -- underlying file in appropriate mode. If the file is already locked in -- incompatible mode, this function blocks until the lock is established. The -- lock is automatically released upon closing a 'Handle'. -- -- Things to be aware of: -- -- 1) This function may block inside a C call. If it does, in order to be able -- to interrupt it with asynchronous exceptions and/or for other threads to -- continue working, you MUST use threaded version of the runtime system. -- -- 2) The implementation uses 'LockFileEx' on Windows and 'flock' otherwise, -- hence all of their caveats also apply here. -- -- 3) On non-Windows platforms that don't support 'flock' (e.g. Solaris) this -- function throws 'FileLockingNotImplemented'. We deliberately choose to not -- provide fcntl based locking instead because of its broken semantics. -- -- @since 4.10.0.0 hLock :: Handle -> LockMode -> IO () hLock h mode = void $ lockImpl h "hLock" mode True -- | Non-blocking version of 'hLock'. -- -- @since 4.10.0.0 hTryLock :: Handle -> LockMode -> IO Bool hTryLock h mode = lockImpl h "hTryLock" mode False -- | Release a lock taken with 'hLock' or 'hTryLock'. -- -- @since 4.11.0.0 hUnlock :: Handle -> IO () hUnlock = unlockImpl ----------------------------------------
sdiehl/ghc
libraries/base/GHC/IO/Handle/Lock.hs
bsd-3-clause
2,012
0
8
315
222
145
77
22
1
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE DeriveFunctor #-} module Hans.Lens ( -- * Lenses Lens, Lens', lens, -- ** Getters Getting, Getter, view, to, -- ** Setters ASetter, ASetter', set, over, modify, -- * Utility Lenses bit, byte, ) where import qualified Control.Applicative as A import qualified Data.Bits as B import Data.Word (Word8) import MonadLib (Id,runId) -- Lenses ---------------------------------------------------------------------- -- | General lenses that allow for the type of the inner field to change. type Lens s t a b = forall f. Functor f => (a -> f b) -> (s -> f t) -- | Lenses that don't change type. type Lens' s a = Lens s s a a lens :: (s -> a) -> (s -> b -> t) -> Lens s t a b lens get upd = \ f s -> upd s `fmap` f (get s) {-# INLINE lens #-} -- Getters --------------------------------------------------------------------- type Getting r s a = (a -> Const r a) -> (s -> Const r s) type Getter s a = forall r. Getting r s a newtype Const r a = Const { runConst :: r } deriving Functor -- | This is just a handy way of not exposing a Contrafunctor class, as we only -- really need it for the definition of `to`. castConst' :: (b -> a) -> Const r a -> Const r b castConst' _ (Const r) = Const r {-# INLINE castConst' #-} -- NOTE: the @(s -> a)@ part could be generalized to @ReaderM m s@. view :: Getting a s a -> s -> a view l = \ s -> runConst (l Const s) {-# INLINE view #-} to :: (s -> a) -> Getting r s a to f = \ l s -> castConst' f (l (f s)) {-# INLINE to #-} -- Setters --------------------------------------------------------------------- type ASetter s t a b = (a -> Id b) -> (s -> Id t) type ASetter' s a = ASetter s s a a set :: Lens s t a b -> b -> s -> t set l b = \ s -> runId (l (\ _ -> A.pure b) s) {-# INLINE set #-} over :: ASetter s t a b -> (a -> b) -> (s -> t) over l f = \ s -> runId (l (A.pure . f) s) {-# INLINE over #-} newtype Modify r a = Modify { runModify :: (a,r) } instance Functor (Modify r) where fmap f = \ (Modify (a,r)) -> Modify (f a, r) {-# INLINE fmap #-} modify :: Lens s t a b -> (a -> (b,r)) -> (s -> (t,r)) modify l f = \ s -> runModify (l (\ a -> Modify (f a)) s) {-# INLINE modify #-} -- Utility Lenses -------------------------------------------------------------- -- NOTE: successive uses of 'bit' with 'set' will cause terms like this to build -- up: -- -- > or# (or# .. (or# val (__word m1)) .. (__word mi)) (__word mj) -- -- This can be fixed with a rewrite rule that associates all uses of or# to the -- right, but this seems like it might block other simplifications that would -- have fired if it was associated to the left. -- -- The real problem here is that GHC isn't reorganizing the uses of or# to group -- together constants, which would allow only one final use of or# after -- simplification. bit :: B.Bits a => Int -> Lens' a Bool bit n = lens get upd where get a = B.testBit a n upd a True = B.setBit a n upd a False = B.clearBit a n byte :: (Integral a, B.Bits a) => Int -> Lens' a Word8 byte n = lens get upd where sh = n * 8 get a = fromIntegral (a `B.shiftR` sh) upd a b = a B..|. (fromIntegral b `B.shiftL` sh)
GaloisInc/HaNS
src/Hans/Lens.hs
bsd-3-clause
3,267
0
13
810
1,028
577
451
61
2
module Game.Menus where import Data.IORef import Control.Monad.State (get) import Physics.Chipmunk (freeSpace) import Graphics.Qt import Utils import Base import Base.Renderable.Layered import Base.Renderable.StickToBottom import Base.Renderable.Centered import Base.Renderable.CenterHorizontally import Base.Renderable.VBox import Base.Renderable.Spacer import Game.Scene import Game.BackgroundScene as BackgroundScene freeGameState :: GameState -> AppState -> AppState freeGameState gameState follower = NoGUIAppState $ io $ do stopGameBackgroundMusic postGUI $ fmapM_ freeObject (scene gameState ^. objects) freeSpace $ cmSpace gameState return follower pauseMenu :: Application -> Parent -> AppState -> GameState -> Int -> AppState pauseMenu app parent continueLevel gameState = menuAppState app PauseMenu (Just continueLevel) ( MenuItem (p "continue") (const continueLevel) : -- (p "rewind to last save point", todo) : MenuItem (p "retry from beginning") (const $ freeGameState gameState (retryLevel gameState)) : MenuItem (p "options") (generalOptions app 0 . this) : MenuItem (p "help") (playHelp app . this) : MenuItem (p "quit level") (const $ freeGameState gameState parent) : []) where this = pauseMenu app parent continueLevel gameState playHelp :: Application -> Parent -> AppState playHelp app parent = NoGUIAppState $ do file <- rm2m $ getDataFileName "manual/playHelp.txt" controls_ <- gets (^. controls) text <- (fmap (substitute (keysContext controls_))) <$> io (pFile file) return $ scrollingAppState app text parent failureMenu :: Application -> Parent -> RenderStateRefs -> GameState -> AppState failureMenu app parent sceneRenderState gameState = AppStateLooped (renderable waitFailureScreen) $ do config <- get triggerSound config $ failureSound $ applicationSounds app gameStateRef <- io $ newIORef gameState ignore $ waitForPressedButtonBackgroundScene app gameStateRef (sceneMVar sceneRenderState) (const False) (Just $ realToFrac afterLevelWaitTime) return $ menuAppStateSpecialized app (poller gameStateRef) (renderable backGround) AppStateLooped FailureMenu Nothing menuItems 0 where menuItems = -- (p "rewind to last savepoint", todo) : MenuItem (p "retry from beginning") (const $ freeGameState gameState (retryLevel gameState)) : MenuItem (p "quit level") (const $ freeGameState gameState parent) : [] poller gameStateRef = waitForPressedButtonBackgroundScene app gameStateRef (sceneMVar sceneRenderState) (const True) Nothing backGround = sceneRenderState |:> MenuBackgroundTransparent waitFailureScreen = backGround |:> (addBottomLineSpacer $ centered $ vBox (length lines) $ lines) lines = renderable (failurePixmap (applicationPixmaps app)) : replicate (length menuItems + 1) lineSpacer ++ [] -- | show a textual message and wait for a keypress -- PRE: score /= Score_1_Tried successMessage :: Application -> Parent -> RenderStateRefs -> GameState -> Score -> (Maybe Score, Record, Record) -> AppState successMessage app parent sceneRenderState gameState score@Score_1_Passed{} (mHighScore, timeRecord, batteryRecord) = AppStateLooped (renderable $ renderableInstance False) $ do config <- get triggerSound config $ successSound $ applicationSounds app ref <- io $ newIORef gameState waitForEvent ref (const False) (Just $ realToFrac afterLevelWaitTime) return $ AppStateLooped (renderable $ renderableInstance True) $ do waitForEvent ref (const True) Nothing return $ freeGameState gameState parent where waitForEvent ref p to = ignore $ waitForPressedButtonBackgroundScene app ref (sceneMVar sceneRenderState) p to renderableInstance showKeyHint = sceneRenderState |:> MenuBackgroundTransparent |:> (if showKeyHint then addKeysHint (menuConfirmationKeysHint (Base.p "ok")) else addBottomLineSpacer) (centered $ vBox (length lines) $ fmap centerHorizontally lines) lines :: [RenderableInstance] lines = renderable (successPixmap (applicationPixmaps app)) : lineSpacer : renderable batteryLine : renderable timeLine : [] batteryLine :: [Glyph] batteryLine = currentBattery ++ batteryRecordGlyphs currentBattery :: [Glyph] currentBattery = pvdWhite $ (batteryChar : " " ++ batteryFormat (score ^. scoreBatteryPowerA)) batteryRecordGlyphs :: [Glyph] batteryRecordGlyphs = bracket $ case batteryRecord of NoNewRecord -> maybe (pv "no record") (\ hs -> p "record" ++ pv ": " ++ pvd (batteryFormat hs)) (batteryHighScore mHighScore) NewRecord -> p "new record!" ++ maybe (pv "") (\ hs -> pv " " ++ p "before" ++ pv ": " ++ pvd (batteryFormat hs)) (batteryHighScore mHighScore) RecordTied -> p "tie record" batteryHighScore :: Maybe Score -> Maybe Integer batteryHighScore (Just (Score_1_Passed _ bp)) | bp /= 0 = Just bp batteryHighScore _ = Nothing timeLine :: [Glyph] timeLine = currentTime ++ timeRecordGlyphs currentTime = pvdWhite $ (watchChar : " " ++ timeFormat (score ^. scoreTimeA)) timeRecordGlyphs = bracket $ case timeRecord of NoNewRecord -> case mHighScore of Just (Score_1_Passed oldTime _) -> p "record" ++ pv ": " ++ pvd (timeFormat oldTime) _ -> pv "" NewRecord -> p "new record!" ++ case mHighScore of Just (Score_1_Passed oldTime _) -> pv " " ++ p "before" ++ pv ": " ++ pvd (timeFormat oldTime) _ -> pv "" RecordTied -> p "tie record" -- String to [Glyph] -- | normal font p :: String -> [Glyph] p = proseToGlyphs (standardFont app) . capitalizeProse . Base.p pv :: String -> [Glyph] pv = proseToGlyphs (standardFont app) . capitalizeProse . Base.pv -- | digits font pvd :: String -> [Glyph] pvd = proseToGlyphs (digitFont app) . capitalizeProse . Base.pv -- | white pvdWhite :: String -> [Glyph] pvdWhite = proseToGlyphs (digitFont app) . colorizeProse white . capitalizeProse . Base.pv -- | Encloses in standard font brackets and adds spaces as a prefix, -- if the string is not null. bracket :: [Glyph] -> [Glyph] bracket [] = [] bracket x = pv " [" ++ x ++ pv "]"
geocurnoff/nikki
src/Game/Menus.hs
lgpl-3.0
6,867
0
18
1,851
1,874
938
936
150
10
-- The lambda-calculus part of the language, which can be shared module Language.Hakaru.Lambda(lit, dbl, lam, app, fix, ifThenElse) where lit :: (Eq a) => a -> a lit = id -- raw lit is a pain to use. These are nicer dbl :: Double -> Double dbl = lit lam :: (a -> b) -> (a -> b) lam f = f app :: (a -> b) -> a -> b app f x = f x fix :: ((a -> b) -> (a -> b)) -> (a -> b) fix g = f where f = g f ifThenElse :: Bool -> a -> a -> a ifThenElse True t _ = t ifThenElse False _ f = f
bitemyapp/hakaru
Language/Hakaru/Lambda.hs
bsd-3-clause
485
0
9
128
226
126
100
14
1
------------------------------------------------------------------------------- -- | -- Module : System.Hardware.Haskino.Test.ExprBool -- Copyright : (c) University of Kansas -- License : BSD3 -- Stability : experimental -- -- Quick Check tests for Expressions returning a Expr Bool ------------------------------------------------------------------------------- {-# LANGUAGE GADTs #-} module System.Hardware.Haskino.Test.ExprBool where import Prelude hiding ( quotRem, divMod, quot, rem, div, mod, properFraction, fromInteger, toInteger, (<*) ) import qualified Prelude as P import System.Hardware.Haskino import Data.Boolean import Data.Boolean.Numbers import Data.Boolean.Bits import Data.Word import qualified Data.Bits as DB import Test.QuickCheck hiding ((.&.)) import Test.QuickCheck.Monadic litEvalB :: Expr Bool -> Bool litEvalB (LitB w) = w prop_not :: ArduinoConnection -> RemoteRef Bool -> Bool -> Property prop_not c r x = monadicIO $ do let local = not x remote <- run $ send c $ do writeRemoteRef r $ notB (lit x) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_and :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Property prop_and c r x y = monadicIO $ do let local = x && y remote <- run $ send c $ do writeRemoteRef r $ (lit x) &&* (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_or :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Property prop_or c r x y = monadicIO $ do let local = x || y remote <- run $ send c $ do writeRemoteRef r $ (lit x) ||* (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_ifb :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Bool -> Property prop_ifb c r b x y = monadicIO $ do let local = if b then x else y remote <- run $ send c $ do writeRemoteRef r $ ifB (lit b) (lit x) (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_eq :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Property prop_eq c r x y = monadicIO $ do let local = x == y remote <- run $ send c $ do writeRemoteRef r $ (lit x) ==* (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_neq :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Property prop_neq c r x y = monadicIO $ do let local = x /= y remote <- run $ send c $ do writeRemoteRef r $ (lit x) /=* (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_lt :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Property prop_lt c r x y = monadicIO $ do let local = x < y remote <- run $ send c $ do writeRemoteRef r $ (lit x) <* (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_gt :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Property prop_gt c r x y = monadicIO $ do let local = x > y remote <- run $ send c $ do writeRemoteRef r $ (lit x) >* (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_lte :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Property prop_lte c r x y = monadicIO $ do let local = x <= y remote <- run $ send c $ do writeRemoteRef r $ (lit x) <=* (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) prop_gte :: ArduinoConnection -> RemoteRef Bool -> Bool -> Bool -> Property prop_gte c r x y = monadicIO $ do let local = x >= y remote <- run $ send c $ do writeRemoteRef r $ (lit x) >=* (lit y) v <- readRemoteRef r return v assert (local == litEvalB remote) main :: IO () main = do conn <- openArduino False "/dev/cu.usbmodem1421" refB <- send conn $ newRemoteRef (lit False) print "Not Tests:" quickCheck (prop_not conn refB) print "And Tests:" quickCheck (prop_and conn refB) print "Or Tests:" quickCheck (prop_or conn refB) print "ifB Tests:" quickCheck (prop_ifb conn refB) print "Equal Tests:" quickCheck (prop_eq conn refB) print "Not Equal Tests:" quickCheck (prop_neq conn refB) print "Less Than Tests:" quickCheck (prop_lt conn refB) print "Greater Than Tests:" quickCheck (prop_gt conn refB) print "Less Than Equal Tests:" quickCheck (prop_lte conn refB) print "Greater Than Equal Tests:" quickCheck (prop_gte conn refB) closeArduino conn
ku-fpg/kansas-amber
tests/ExprTests/ExprBool.hs
bsd-3-clause
4,629
0
15
1,221
1,715
805
910
120
2
{- foo bar -} {- module class X where yyy -}
itchyny/vim-haskell-indent
test/comment/double_block_comments.out.hs
mit
45
0
2
11
4
3
1
1
0
-- Unpack a tarball containing a Cabal package {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module Distribution.Server.Packages.Unpack ( CombinedTarErrs(..), checkEntries, checkUselessPermissions, unpackPackage, unpackPackageRaw, ) where import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Archive.Tar.Check as Tar import Distribution.Version ( Version(..) ) import Distribution.Package ( PackageIdentifier, packageVersion, packageName, PackageName(..) ) import Distribution.PackageDescription ( GenericPackageDescription(..), PackageDescription(..) , exposedModules ) import Distribution.PackageDescription.Parse ( parsePackageDescription ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.PackageDescription.Check ( PackageCheck(..), checkPackage ) import Distribution.ParseUtils ( ParseResult(..), locatedErrorMsg, showPWarning ) import Distribution.Text ( display, simpleParse ) import Distribution.ModuleName ( components ) import Distribution.Server.Util.Parse ( unpackUTF8 ) import Distribution.License ( License(..) ) import Control.Applicative import Control.Monad ( unless, when ) import Control.Monad.Except ( ExceptT, runExceptT, MonadError, throwError ) import Control.Monad.Identity ( Identity(..) ) import Control.Monad.Writer ( WriterT(..), MonadWriter, tell ) import Data.Bits ( (.&.) ) import Data.ByteString.Lazy ( ByteString ) import qualified Data.ByteString.Lazy as LBS import Data.List ( nub, (\\), partition, intercalate ) import Data.Maybe ( isJust ) import Data.Time ( UTCTime(..), fromGregorian, addUTCTime ) import Data.Time.Clock.POSIX ( posixSecondsToUTCTime ) import qualified Distribution.Server.Util.GZip as GZip import System.FilePath ( (</>), (<.>), splitDirectories, splitExtension, normalise ) import qualified System.FilePath.Windows ( takeFileName ) import Text.Printf ( printf ) -- Whether to allow upload of "all rights reserved" packages allowAllRightsReserved :: Bool allowAllRightsReserved = True -- | Upload or check a tarball containing a Cabal package. -- Returns either an fatal error or a package description and a list -- of warnings. unpackPackage :: UTCTime -> FilePath -> ByteString -> Either String ((GenericPackageDescription, ByteString), [String]) unpackPackage now tarGzFile contents = runUploadMonad $ do (pkgDesc, warnings, cabalEntry) <- basicChecks False now tarGzFile contents mapM_ throwError warnings extraChecks pkgDesc return (pkgDesc, cabalEntry) unpackPackageRaw :: FilePath -> ByteString -> Either String ((GenericPackageDescription, ByteString), [String]) unpackPackageRaw tarGzFile contents = runUploadMonad $ do (pkgDesc, _warnings, cabalEntry) <- basicChecks True noTime tarGzFile contents return (pkgDesc, cabalEntry) where noTime = UTCTime (fromGregorian 1970 1 1) 0 basicChecks :: Bool -> UTCTime -> FilePath -> ByteString -> UploadMonad (GenericPackageDescription, [String], ByteString) basicChecks lax now tarGzFile contents = do let (pkgidStr, ext) = (base, tar ++ gz) where (tarFile, gz) = splitExtension (portableTakeFileName tarGzFile) (base, tar) = splitExtension tarFile unless (ext == ".tar.gz") $ throwError $ tarGzFile ++ " is not a gzipped tar file, it must have the .tar.gz extension" pkgid <- case simpleParse pkgidStr of Just pkgid | null . versionBranch . packageVersion $ pkgid -> throwError $ "Invalid package id " ++ quote pkgidStr ++ ". It must include the package version number, and not just " ++ "the package name, e.g. 'foo-1.0'." | display pkgid == pkgidStr -> return (pkgid :: PackageIdentifier) | not . null . versionTags . packageVersion $ pkgid -> throwError $ "Hackage no longer accepts packages with version tags: " ++ intercalate ", " (versionTags (packageVersion pkgid)) _ -> throwError $ "Invalid package id " ++ quote pkgidStr ++ ". The tarball must use the name of the package." -- Extract entries and check the tar format / portability let entries = tarballChecks lax now expectedDir $ Tar.read (GZip.decompressNamed tarGzFile contents) expectedDir = display pkgid -- Extract the .cabal file from the tarball let selectEntry entry = case Tar.entryContent entry of Tar.NormalFile bs _ | cabalFileName == normalise (Tar.entryPath entry) -> Just bs _ -> Nothing PackageName name = packageName pkgid cabalFileName = display pkgid </> name <.> "cabal" cabalEntries <- selectEntries explainTarError selectEntry entries cabalEntry <- case cabalEntries of -- NB: tar files *can* contain more than one entry for the same filename. -- (This was observed in practice with the package CoreErlang-0.0.1). -- In this case, after extracting the tar the *last* file in the archive -- wins. Since selectEntries returns results in reverse order we use the head: cabalEntry:_ -> -- We tend to keep hold of the .cabal file, but -- cabalEntry itself is part of a much larger -- ByteString (the whole tar file), so we make a -- copy of it return $ LBS.copy cabalEntry [] -> throwError $ "The " ++ quote cabalFileName ++ " file is missing from the package tarball." when (startsWithBOM cabalEntry) $ throwError $ "The cabal file starts with a Unicode byte order mark (BOM), " ++ "which causes problems for older versions of cabal. Please " ++ "save the package's cabal file as UTF8 without the BOM." -- Parse the Cabal file let cabalFileContent = unpackUTF8 cabalEntry (pkgDesc, warnings) <- case parsePackageDescription cabalFileContent of ParseFailed err -> throwError $ showError (locatedErrorMsg err) ParseOk warnings pkgDesc -> return (pkgDesc, map (showPWarning cabalFileName) warnings) -- Check that the name and version in Cabal file match when (packageName pkgDesc /= packageName pkgid) $ throwError "Package name in the cabal file does not match the file name." when (packageVersion pkgDesc /= packageVersion pkgid) $ throwError "Package version in the cabal file does not match the file name." return (pkgDesc, warnings, cabalEntry) where showError (Nothing, msg) = msg showError (Just n, msg) = "line " ++ show n ++ ": " ++ msg -- | The issue is that browsers can upload the file name using either unix -- or windows convention, so we need to take the basename using either -- convention. Since windows allows the unix '/' as a separator then we can -- use the Windows.takeFileName as a portable solution. -- portableTakeFileName :: FilePath -> String portableTakeFileName = System.FilePath.Windows.takeFileName -- Miscellaneous checks on package description extraChecks :: GenericPackageDescription -> UploadMonad () extraChecks genPkgDesc = do let pkgDesc = flattenPackageDescription genPkgDesc -- various checks --FIXME: do the content checks. The dev version of Cabal generalises -- checkPackageContent to work in any monad, we just need to provide -- a record of ops that will do checks inside the tarball. We should -- gather a map of files and dirs and have these just to map lookups: -- -- > checkTarballContents = CheckPackageContentOps { -- > doesFileExist = Set.member fileMap, -- > doesDirectoryExist = Set.member dirsMap -- > } -- > fileChecks <- checkPackageContent checkTarballContents pkgDesc let pureChecks = checkPackage genPkgDesc (Just pkgDesc) checks = pureChecks -- ++ fileChecks isDistError (PackageDistSuspicious {}) = False -- warn without refusing isDistError _ = True (errors, warnings) = partition isDistError checks mapM_ (throwError . explanation) errors mapM_ (warn . explanation) warnings -- Proprietary License check (only active in central-server branch) when (not allowAllRightsReserved && license pkgDesc == AllRightsReserved) $ throwError $ "This server does not accept packages with 'license' " ++ "field set to AllRightsReserved." -- Check for an existing x-revision when (isJust (lookup "x-revision" (customFieldsPD pkgDesc))) $ throwError $ "Newly uploaded packages must not specify the 'x-revision' " ++ "field in their .cabal file. This is only used for " ++ "post-release revisions." -- Check reasonableness of names of exposed modules let topLevel = case library pkgDesc of Nothing -> [] Just l -> nub $ map head $ filter (not . null) $ map components $ exposedModules l badTopLevel = topLevel \\ allocatedTopLevelNodes unless (null badTopLevel) $ warn $ "Exposed modules use unallocated top-level names: " ++ unwords badTopLevel -- Monad for uploading packages: -- WriterT for warning messages -- Either for fatal errors newtype UploadMonad a = UploadMonad (WriterT [String] (ExceptT String Identity) a) deriving (Functor, Applicative, Monad, MonadWriter [String], MonadError String) warn :: String -> UploadMonad () warn msg = tell [msg] runUploadMonad :: UploadMonad a -> Either String (a, [String]) runUploadMonad (UploadMonad m) = runIdentity . runExceptT . runWriterT $ m -- | Registered top-level nodes in the class hierarchy. allocatedTopLevelNodes :: [String] allocatedTopLevelNodes = [ "Algebra", "Codec", "Control", "Data", "Database", "Debug", "Distribution", "DotNet", "Foreign", "Graphics", "Language", "Network", "Numeric", "Prelude", "Sound", "System", "Test", "Text"] selectEntries :: forall err a. (err -> String) -> (Tar.Entry -> Maybe a) -> Tar.Entries err -> UploadMonad [a] selectEntries formatErr select = extract [] where extract :: [a] -> Tar.Entries err -> UploadMonad [a] extract _ (Tar.Fail err) = throwError (formatErr err) extract selected Tar.Done = return selected extract selected (Tar.Next entry entries) = case select entry of Nothing -> extract selected entries Just saved -> extract (saved : selected) entries data CombinedTarErrs = FormatError Tar.FormatError | PortabilityError Tar.PortabilityError | TarBombError FilePath FilePath | FutureTimeError FilePath UTCTime | PermissionsError FilePath Tar.Permissions tarballChecks :: Bool -> UTCTime -> FilePath -> Tar.Entries Tar.FormatError -> Tar.Entries CombinedTarErrs tarballChecks lax now expectedDir = (if not lax then checkFutureTimes now else id) . checkTarbomb expectedDir . checkUselessPermissions . (if lax then ignoreShortTrailer else fmapTarError (either id PortabilityError) . Tar.checkPortability) . fmapTarError FormatError where ignoreShortTrailer = Tar.foldEntries Tar.Next Tar.Done (\e -> case e of FormatError Tar.ShortTrailer -> Tar.Done _ -> Tar.Fail e) fmapTarError f = Tar.foldEntries Tar.Next Tar.Done (Tar.Fail . f) checkFutureTimes :: UTCTime -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkFutureTimes now = checkEntries checkEntry where -- Allow 30s for client clock skew now' = addUTCTime 30 now checkEntry entry | entryUTCTime > now' = Just (FutureTimeError posixPath entryUTCTime) where entryUTCTime = posixSecondsToUTCTime (realToFrac (Tar.entryTime entry)) posixPath = Tar.fromTarPathToPosixPath (Tar.entryTarPath entry) checkEntry _ = Nothing checkTarbomb :: FilePath -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkTarbomb expectedTopDir = checkEntries checkEntry where checkEntry entry = case splitDirectories (Tar.entryPath entry) of (topDir:_) | topDir == expectedTopDir -> Nothing _ -> Just $ TarBombError (Tar.entryPath entry) expectedTopDir checkUselessPermissions :: Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkUselessPermissions = checkEntries checkEntry where checkEntry entry = case Tar.entryContent entry of (Tar.NormalFile _ _) -> checkPermissions 0o644 (Tar.entryPermissions entry) (Tar.Directory) -> checkPermissions 0o755 (Tar.entryPermissions entry) _ -> Nothing where checkPermissions expected actual = if expected .&. actual /= expected then Just $ PermissionsError (Tar.entryPath entry) actual else Nothing checkEntries :: (Tar.Entry -> Maybe e) -> Tar.Entries e -> Tar.Entries e checkEntries checkEntry = Tar.foldEntries (\entry rest -> maybe (Tar.Next entry rest) Tar.Fail (checkEntry entry)) Tar.Done Tar.Fail explainTarError :: CombinedTarErrs -> String explainTarError (TarBombError filename expectedDir) = "Bad file name in package tarball: " ++ quote filename ++ "\nAll the file in the package tarball must be in the subdirectory " ++ quote expectedDir ++ "." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.GnuFormat)) = "This tarball is in the non-standard GNU tar format. " ++ "For portability and long-term data preservation, hackage requires that " ++ "package tarballs use the standard 'ustar' format. If you are using GNU " ++ "tar, use --format=ustar to get the standard portable format." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.V7Format)) = "This tarball is in the old Unix V7 tar format. " ++ "For portability and long-term data preservation, hackage requires that " ++ "package tarballs use the standard 'ustar' format. Virtually all tar " ++ "programs can now produce ustar format (POSIX 1988). For example if you " ++ "are using GNU tar, use --format=ustar to get the standard portable format." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.UstarFormat)) = error "explainTarError: impossible UstarFormat" explainTarError (PortabilityError Tar.NonPortableFileType) = "The package tarball contains a non-portable entry type. " ++ "For portability, package tarballs should use the 'ustar' format " ++ "and only contain normal files, directories and file links." explainTarError (PortabilityError (Tar.NonPortableEntryNameChar _)) = "The package tarball contains an entry with a non-ASCII file name. " ++ "For portability, package tarballs should contain only ASCII file names " ++ "(e.g. not UTF8 encoded Unicode)." explainTarError (PortabilityError ([email protected] {})) = show err ++ ". For portability, hackage requires that file names be valid on both Unix " ++ "and Windows systems, and not refer outside of the tarball." explainTarError (FormatError formateror) = "There is an error in the format of the tar file: " ++ show formateror ++ ". Check that it is a valid tar file (e.g. 'tar -xtf thefile.tar'). " ++ "You may need to re-create the package tarball and try again." explainTarError (FutureTimeError entryname time) = "The tarball entry " ++ quote entryname ++ " has a file timestamp that is " ++ "in the future (" ++ show time ++ "). This tends to cause problems " ++ "for build systems and other tools, so hackage does not allow it. This " ++ "problem can be caused by having a misconfigured system time, or by bugs " ++ "in the tools (tarballs created by 'cabal sdist' on Windows with " ++ "cabal-install-1.18.0.2 or older have this problem)." explainTarError (PermissionsError entryname mode) = "The tarball entry " ++ quote entryname ++ " has file permissions that are " ++ "broken: " ++ (showMode mode) ++ ". Permissions must be 644 at a minimum " ++ "for files and 755 for directories." where showMode :: Tar.Permissions -> String showMode m = printf "%.3o" (fromIntegral m :: Int) quote :: String -> String quote s = "'" ++ s ++ "'" -- | Whether a UTF8 BOM is at the beginning of the input startsWithBOM :: ByteString -> Bool startsWithBOM bs = LBS.take 3 bs == LBS.pack [0xEF, 0xBB, 0xBF]
ocharles/hackage-server
Distribution/Server/Packages/Unpack.hs
bsd-3-clause
16,941
0
20
4,005
3,372
1,779
1,593
296
6
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Dependency -- Copyright : (c) David Himmelstrup 2005, -- Bjorn Bringert 2007 -- Duncan Coutts 2008 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Top level interface to dependency resolution. ----------------------------------------------------------------------------- module Distribution.Client.Dependency ( -- * The main package dependency resolver chooseSolver, resolveDependencies, Progress(..), foldProgress, -- * Alternate, simple resolver that does not do dependencies recursively resolveWithoutDependencies, -- * Constructing resolver policies DepResolverParams(..), PackageConstraint(..), PackagesPreferenceDefault(..), PackagePreference(..), InstalledPreference(..), -- ** Standard policy standardInstallPolicy, PackageSpecifier(..), -- ** Sandbox policy applySandboxInstallPolicy, -- ** Extra policy options dontUpgradeNonUpgradeablePackages, hideBrokenInstalledPackages, upgradeDependencies, reinstallTargets, -- ** Policy utils addConstraints, addPreferences, setPreferenceDefault, setReorderGoals, setIndependentGoals, setAvoidReinstalls, setShadowPkgs, setStrongFlags, setMaxBackjumps, addSourcePackages, hideInstalledPackagesSpecificByComponentId, hideInstalledPackagesSpecificBySourcePackageId, hideInstalledPackagesAllVersions, removeUpperBounds ) where import Distribution.Client.Dependency.TopDown ( topDownResolver ) import Distribution.Client.Dependency.Modular ( modularResolver, SolverConfig(..) ) import qualified Distribution.Client.PackageIndex as PackageIndex import Distribution.Simple.PackageIndex (InstalledPackageIndex) import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Client.InstallPlan (InstallPlan) import Distribution.Client.Types ( SourcePackageDb(SourcePackageDb), SourcePackage(..) , ConfiguredPackage(..), ConfiguredId(..), enableStanzas ) import Distribution.Client.Dependency.Types ( PreSolver(..), Solver(..), DependencyResolver, ResolverPackage(..) , PackageConstraint(..), showPackageConstraint , LabeledPackageConstraint(..), unlabelPackageConstraint , ConstraintSource(..), showConstraintSource , AllowNewer(..), PackagePreferences(..), InstalledPreference(..) , PackagesPreferenceDefault(..) , Progress(..), foldProgress ) import Distribution.Client.Sandbox.Types ( SandboxPackageInfo(..) ) import Distribution.Client.Targets import Distribution.Client.ComponentDeps (ComponentDeps) import qualified Distribution.Client.ComponentDeps as CD import qualified Distribution.InstalledPackageInfo as Installed import Distribution.Package ( PackageName(..), PackageIdentifier(PackageIdentifier), PackageId , Package(..), packageName, packageVersion , ComponentId, Dependency(Dependency)) import qualified Distribution.PackageDescription as PD ( PackageDescription(..), Library(..), Executable(..) , TestSuite(..), Benchmark(..), SetupBuildInfo(..) , GenericPackageDescription(..), CondTree , Flag(flagName), FlagName(..) ) import Distribution.PackageDescription (BuildInfo(targetBuildDepends)) import Distribution.PackageDescription.Configuration ( mapCondTree, finalizePackageDescription ) import Distribution.Client.PackageUtils ( externalBuildDepends ) import Distribution.Version ( VersionRange, anyVersion, thisVersion, withinRange , removeUpperBound, simplifyVersionRange ) import Distribution.Compiler ( CompilerInfo(..) ) import Distribution.System ( Platform ) import Distribution.Client.Utils ( duplicates, duplicatesBy, mergeBy, MergeResult(..) ) import Distribution.Simple.Utils ( comparing, warn, info ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity ) import Data.List ( foldl', sort, sortBy, nubBy, maximumBy, intercalate ) import Data.Function (on) import Data.Maybe (fromMaybe) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Set (Set) import Control.Exception ( assert ) -- ------------------------------------------------------------ -- * High level planner policy -- ------------------------------------------------------------ -- | The set of parameters to the dependency resolver. These parameters are -- relatively low level but many kinds of high level policies can be -- implemented in terms of adjustments to the parameters. -- data DepResolverParams = DepResolverParams { depResolverTargets :: [PackageName], depResolverConstraints :: [LabeledPackageConstraint], depResolverPreferences :: [PackagePreference], depResolverPreferenceDefault :: PackagesPreferenceDefault, depResolverInstalledPkgIndex :: InstalledPackageIndex, depResolverSourcePkgIndex :: PackageIndex.PackageIndex SourcePackage, depResolverReorderGoals :: Bool, depResolverIndependentGoals :: Bool, depResolverAvoidReinstalls :: Bool, depResolverShadowPkgs :: Bool, depResolverStrongFlags :: Bool, depResolverMaxBackjumps :: Maybe Int } showDepResolverParams :: DepResolverParams -> String showDepResolverParams p = "targets: " ++ intercalate ", " (map display (depResolverTargets p)) ++ "\nconstraints: " ++ concatMap (("\n " ++) . showLabeledConstraint) (depResolverConstraints p) ++ "\npreferences: " ++ concatMap (("\n " ++) . showPackagePreference) (depResolverPreferences p) ++ "\nstrategy: " ++ show (depResolverPreferenceDefault p) where showLabeledConstraint :: LabeledPackageConstraint -> String showLabeledConstraint (LabeledPackageConstraint pc src) = showPackageConstraint pc ++ " (" ++ showConstraintSource src ++ ")" -- | A package selection preference for a particular package. -- -- Preferences are soft constraints that the dependency resolver should try to -- respect where possible. It is not specified if preferences on some packages -- are more important than others. -- data PackagePreference = -- | A suggested constraint on the version number. PackageVersionPreference PackageName VersionRange -- | If we prefer versions of packages that are already installed. | PackageInstalledPreference PackageName InstalledPreference -- | Provide a textual representation of a package preference -- for debugging purposes. -- showPackagePreference :: PackagePreference -> String showPackagePreference (PackageVersionPreference pn vr) = display pn ++ " " ++ display (simplifyVersionRange vr) showPackagePreference (PackageInstalledPreference pn ip) = display pn ++ " " ++ show ip basicDepResolverParams :: InstalledPackageIndex -> PackageIndex.PackageIndex SourcePackage -> DepResolverParams basicDepResolverParams installedPkgIndex sourcePkgIndex = DepResolverParams { depResolverTargets = [], depResolverConstraints = [], depResolverPreferences = [], depResolverPreferenceDefault = PreferLatestForSelected, depResolverInstalledPkgIndex = installedPkgIndex, depResolverSourcePkgIndex = sourcePkgIndex, depResolverReorderGoals = False, depResolverIndependentGoals = False, depResolverAvoidReinstalls = False, depResolverShadowPkgs = False, depResolverStrongFlags = False, depResolverMaxBackjumps = Nothing } addTargets :: [PackageName] -> DepResolverParams -> DepResolverParams addTargets extraTargets params = params { depResolverTargets = extraTargets ++ depResolverTargets params } addConstraints :: [LabeledPackageConstraint] -> DepResolverParams -> DepResolverParams addConstraints extraConstraints params = params { depResolverConstraints = extraConstraints ++ depResolverConstraints params } addPreferences :: [PackagePreference] -> DepResolverParams -> DepResolverParams addPreferences extraPreferences params = params { depResolverPreferences = extraPreferences ++ depResolverPreferences params } setPreferenceDefault :: PackagesPreferenceDefault -> DepResolverParams -> DepResolverParams setPreferenceDefault preferenceDefault params = params { depResolverPreferenceDefault = preferenceDefault } setReorderGoals :: Bool -> DepResolverParams -> DepResolverParams setReorderGoals b params = params { depResolverReorderGoals = b } setIndependentGoals :: Bool -> DepResolverParams -> DepResolverParams setIndependentGoals b params = params { depResolverIndependentGoals = b } setAvoidReinstalls :: Bool -> DepResolverParams -> DepResolverParams setAvoidReinstalls b params = params { depResolverAvoidReinstalls = b } setShadowPkgs :: Bool -> DepResolverParams -> DepResolverParams setShadowPkgs b params = params { depResolverShadowPkgs = b } setStrongFlags :: Bool -> DepResolverParams -> DepResolverParams setStrongFlags b params = params { depResolverStrongFlags = b } setMaxBackjumps :: Maybe Int -> DepResolverParams -> DepResolverParams setMaxBackjumps n params = params { depResolverMaxBackjumps = n } -- | Some packages are specific to a given compiler version and should never be -- upgraded. dontUpgradeNonUpgradeablePackages :: DepResolverParams -> DepResolverParams dontUpgradeNonUpgradeablePackages params = addConstraints extraConstraints params where extraConstraints = [ LabeledPackageConstraint (PackageConstraintInstalled pkgname) ConstraintSourceNonUpgradeablePackage | all (/=PackageName "base") (depResolverTargets params) , pkgname <- map PackageName [ "base", "ghc-prim", "integer-gmp" , "integer-simple" ] , isInstalled pkgname ] -- TODO: the top down resolver chokes on the base constraints -- below when there are no targets and thus no dep on base. -- Need to refactor constraints separate from needing packages. isInstalled = not . null . InstalledPackageIndex.lookupPackageName (depResolverInstalledPkgIndex params) addSourcePackages :: [SourcePackage] -> DepResolverParams -> DepResolverParams addSourcePackages pkgs params = params { depResolverSourcePkgIndex = foldl (flip PackageIndex.insert) (depResolverSourcePkgIndex params) pkgs } hideInstalledPackagesSpecificByComponentId :: [ComponentId] -> DepResolverParams -> DepResolverParams hideInstalledPackagesSpecificByComponentId pkgids params = --TODO: this should work using exclude constraints instead params { depResolverInstalledPkgIndex = foldl' (flip InstalledPackageIndex.deleteComponentId) (depResolverInstalledPkgIndex params) pkgids } hideInstalledPackagesSpecificBySourcePackageId :: [PackageId] -> DepResolverParams -> DepResolverParams hideInstalledPackagesSpecificBySourcePackageId pkgids params = --TODO: this should work using exclude constraints instead params { depResolverInstalledPkgIndex = foldl' (flip InstalledPackageIndex.deleteSourcePackageId) (depResolverInstalledPkgIndex params) pkgids } hideInstalledPackagesAllVersions :: [PackageName] -> DepResolverParams -> DepResolverParams hideInstalledPackagesAllVersions pkgnames params = --TODO: this should work using exclude constraints instead params { depResolverInstalledPkgIndex = foldl' (flip InstalledPackageIndex.deletePackageName) (depResolverInstalledPkgIndex params) pkgnames } hideBrokenInstalledPackages :: DepResolverParams -> DepResolverParams hideBrokenInstalledPackages params = hideInstalledPackagesSpecificByComponentId pkgids params where pkgids = map Installed.installedComponentId . InstalledPackageIndex.reverseDependencyClosure (depResolverInstalledPkgIndex params) . map (Installed.installedComponentId . fst) . InstalledPackageIndex.brokenPackages $ depResolverInstalledPkgIndex params -- | Remove upper bounds in dependencies using the policy specified by the -- 'AllowNewer' argument (all/some/none). removeUpperBounds :: AllowNewer -> DepResolverParams -> DepResolverParams removeUpperBounds allowNewer params = params { -- NB: It's important to apply 'removeUpperBounds' after -- 'addSourcePackages'. Otherwise, the packages inserted by -- 'addSourcePackages' won't have upper bounds in dependencies relaxed. depResolverSourcePkgIndex = sourcePkgIndex' } where sourcePkgIndex = depResolverSourcePkgIndex params sourcePkgIndex' = case allowNewer of AllowNewerNone -> sourcePkgIndex AllowNewerAll -> fmap relaxAllPackageDeps sourcePkgIndex AllowNewerSome pkgs -> fmap (relaxSomePackageDeps pkgs) sourcePkgIndex relaxAllPackageDeps :: SourcePackage -> SourcePackage relaxAllPackageDeps = onAllBuildDepends doRelax where doRelax (Dependency pkgName verRange) = Dependency pkgName (removeUpperBound verRange) relaxSomePackageDeps :: [PackageName] -> SourcePackage -> SourcePackage relaxSomePackageDeps pkgNames = onAllBuildDepends doRelax where doRelax d@(Dependency pkgName verRange) | pkgName `elem` pkgNames = Dependency pkgName (removeUpperBound verRange) | otherwise = d -- Walk a 'GenericPackageDescription' and apply 'f' to all 'build-depends' -- fields. onAllBuildDepends :: (Dependency -> Dependency) -> SourcePackage -> SourcePackage onAllBuildDepends f srcPkg = srcPkg' where gpd = packageDescription srcPkg pd = PD.packageDescription gpd condLib = PD.condLibrary gpd condExes = PD.condExecutables gpd condTests = PD.condTestSuites gpd condBenchs = PD.condBenchmarks gpd f' = onBuildInfo f onBuildInfo g bi = bi { targetBuildDepends = map g (targetBuildDepends bi) } onLibrary lib = lib { PD.libBuildInfo = f' $ PD.libBuildInfo lib } onExecutable exe = exe { PD.buildInfo = f' $ PD.buildInfo exe } onTestSuite tst = tst { PD.testBuildInfo = f' $ PD.testBuildInfo tst } onBenchmark bmk = bmk { PD.benchmarkBuildInfo = f' $ PD.benchmarkBuildInfo bmk } srcPkg' = srcPkg { packageDescription = gpd' } gpd' = gpd { PD.packageDescription = pd', PD.condLibrary = condLib', PD.condExecutables = condExes', PD.condTestSuites = condTests', PD.condBenchmarks = condBenchs' } pd' = pd { PD.buildDepends = map f (PD.buildDepends pd), PD.library = fmap onLibrary (PD.library pd), PD.executables = map onExecutable (PD.executables pd), PD.testSuites = map onTestSuite (PD.testSuites pd), PD.benchmarks = map onBenchmark (PD.benchmarks pd) } condLib' = fmap (onCondTree onLibrary) condLib condExes' = map (mapSnd $ onCondTree onExecutable) condExes condTests' = map (mapSnd $ onCondTree onTestSuite) condTests condBenchs' = map (mapSnd $ onCondTree onBenchmark) condBenchs mapSnd :: (a -> b) -> (c,a) -> (c,b) mapSnd = fmap onCondTree :: (a -> b) -> PD.CondTree v [Dependency] a -> PD.CondTree v [Dependency] b onCondTree g = mapCondTree g (map f) id upgradeDependencies :: DepResolverParams -> DepResolverParams upgradeDependencies = setPreferenceDefault PreferAllLatest reinstallTargets :: DepResolverParams -> DepResolverParams reinstallTargets params = hideInstalledPackagesAllVersions (depResolverTargets params) params standardInstallPolicy :: InstalledPackageIndex -> SourcePackageDb -> [PackageSpecifier SourcePackage] -> DepResolverParams standardInstallPolicy installedPkgIndex (SourcePackageDb sourcePkgIndex sourcePkgPrefs) pkgSpecifiers = addPreferences [ PackageVersionPreference name ver | (name, ver) <- Map.toList sourcePkgPrefs ] . addConstraints (concatMap pkgSpecifierConstraints pkgSpecifiers) . addTargets (map pkgSpecifierTarget pkgSpecifiers) . hideInstalledPackagesSpecificBySourcePackageId [ packageId pkg | SpecificSourcePackage pkg <- pkgSpecifiers ] . addSourcePackages [ pkg | SpecificSourcePackage pkg <- pkgSpecifiers ] $ basicDepResolverParams installedPkgIndex sourcePkgIndex applySandboxInstallPolicy :: SandboxPackageInfo -> DepResolverParams -> DepResolverParams applySandboxInstallPolicy (SandboxPackageInfo modifiedDeps otherDeps allSandboxPkgs _allDeps) params = addPreferences [ PackageInstalledPreference n PreferInstalled | n <- installedNotModified ] . addTargets installedNotModified . addPreferences [ PackageVersionPreference (packageName pkg) (thisVersion (packageVersion pkg)) | pkg <- otherDeps ] . addConstraints [ let pc = PackageConstraintVersion (packageName pkg) (thisVersion (packageVersion pkg)) in LabeledPackageConstraint pc ConstraintSourceModifiedAddSourceDep | pkg <- modifiedDeps ] . addTargets [ packageName pkg | pkg <- modifiedDeps ] . hideInstalledPackagesSpecificBySourcePackageId [ packageId pkg | pkg <- modifiedDeps ] -- We don't need to add source packages for add-source deps to the -- 'installedPkgIndex' since 'getSourcePackages' did that for us. $ params where installedPkgIds = map fst . InstalledPackageIndex.allPackagesBySourcePackageId $ allSandboxPkgs modifiedPkgIds = map packageId modifiedDeps installedNotModified = [ packageName pkg | pkg <- installedPkgIds, pkg `notElem` modifiedPkgIds ] -- ------------------------------------------------------------ -- * Interface to the standard resolver -- ------------------------------------------------------------ chooseSolver :: Verbosity -> PreSolver -> CompilerInfo -> IO Solver chooseSolver verbosity preSolver _cinfo = case preSolver of AlwaysTopDown -> do warn verbosity "Topdown solver is deprecated" return TopDown AlwaysModular -> do return Modular Choose -> do info verbosity "Choosing modular solver." return Modular runSolver :: Solver -> SolverConfig -> DependencyResolver runSolver TopDown = const topDownResolver -- TODO: warn about unsupported options runSolver Modular = modularResolver -- | Run the dependency solver. -- -- Since this is potentially an expensive operation, the result is wrapped in a -- a 'Progress' structure that can be unfolded to provide progress information, -- logging messages and the final result or an error. -- resolveDependencies :: Platform -> CompilerInfo -> Solver -> DepResolverParams -> Progress String String InstallPlan --TODO: is this needed here? see dontUpgradeNonUpgradeablePackages resolveDependencies platform comp _solver params | null (depResolverTargets params) = return (validateSolverResult platform comp indGoals []) where indGoals = depResolverIndependentGoals params resolveDependencies platform comp solver params = Step (showDepResolverParams finalparams) $ fmap (validateSolverResult platform comp indGoals) $ runSolver solver (SolverConfig reorderGoals indGoals noReinstalls shadowing strFlags maxBkjumps) platform comp installedPkgIndex sourcePkgIndex preferences constraints targets where finalparams @ (DepResolverParams targets constraints prefs defpref installedPkgIndex sourcePkgIndex reorderGoals indGoals noReinstalls shadowing strFlags maxBkjumps) = dontUpgradeNonUpgradeablePackages -- TODO: -- The modular solver can properly deal with broken -- packages and won't select them. So the -- 'hideBrokenInstalledPackages' function should be moved -- into a module that is specific to the top-down solver. . (if solver /= Modular then hideBrokenInstalledPackages else id) $ params preferences = interpretPackagesPreference (Set.fromList targets) defpref prefs -- | Give an interpretation to the global 'PackagesPreference' as -- specific per-package 'PackageVersionPreference'. -- interpretPackagesPreference :: Set PackageName -> PackagesPreferenceDefault -> [PackagePreference] -> (PackageName -> PackagePreferences) interpretPackagesPreference selected defaultPref prefs = \pkgname -> PackagePreferences (versionPref pkgname) (installPref pkgname) where versionPref pkgname = fromMaybe anyVersion (Map.lookup pkgname versionPrefs) versionPrefs = Map.fromList [ (pkgname, pref) | PackageVersionPreference pkgname pref <- prefs ] installPref pkgname = fromMaybe (installPrefDefault pkgname) (Map.lookup pkgname installPrefs) installPrefs = Map.fromList [ (pkgname, pref) | PackageInstalledPreference pkgname pref <- prefs ] installPrefDefault = case defaultPref of PreferAllLatest -> \_ -> PreferLatest PreferAllInstalled -> \_ -> PreferInstalled PreferLatestForSelected -> \pkgname -> -- When you say cabal install foo, what you really mean is, prefer the -- latest version of foo, but the installed version of everything else if pkgname `Set.member` selected then PreferLatest else PreferInstalled -- ------------------------------------------------------------ -- * Checking the result of the solver -- ------------------------------------------------------------ -- | Make an install plan from the output of the dep resolver. -- It checks that the plan is valid, or it's an error in the dep resolver. -- validateSolverResult :: Platform -> CompilerInfo -> Bool -> [ResolverPackage] -> InstallPlan validateSolverResult platform comp indepGoals pkgs = case planPackagesProblems platform comp pkgs of [] -> case InstallPlan.new indepGoals index of Right plan -> plan Left problems -> error (formatPlanProblems problems) problems -> error (formatPkgProblems problems) where index = InstalledPackageIndex.fromList (map toPlanPackage pkgs) toPlanPackage (PreExisting pkg) = InstallPlan.PreExisting pkg toPlanPackage (Configured pkg) = InstallPlan.Configured pkg formatPkgProblems = formatProblemMessage . map showPlanPackageProblem formatPlanProblems = formatProblemMessage . map InstallPlan.showPlanProblem formatProblemMessage problems = unlines $ "internal error: could not construct a valid install plan." : "The proposed (invalid) plan contained the following problems:" : problems ++ "Proposed plan:" : [InstallPlan.showPlanIndex index] data PlanPackageProblem = InvalidConfiguredPackage ConfiguredPackage [PackageProblem] showPlanPackageProblem :: PlanPackageProblem -> String showPlanPackageProblem (InvalidConfiguredPackage pkg packageProblems) = "Package " ++ display (packageId pkg) ++ " has an invalid configuration, in particular:\n" ++ unlines [ " " ++ showPackageProblem problem | problem <- packageProblems ] planPackagesProblems :: Platform -> CompilerInfo -> [ResolverPackage] -> [PlanPackageProblem] planPackagesProblems platform cinfo pkgs = [ InvalidConfiguredPackage pkg packageProblems | Configured pkg <- pkgs , let packageProblems = configuredPackageProblems platform cinfo pkg , not (null packageProblems) ] data PackageProblem = DuplicateFlag PD.FlagName | MissingFlag PD.FlagName | ExtraFlag PD.FlagName | DuplicateDeps [PackageId] | MissingDep Dependency | ExtraDep PackageId | InvalidDep Dependency PackageId showPackageProblem :: PackageProblem -> String showPackageProblem (DuplicateFlag (PD.FlagName flag)) = "duplicate flag in the flag assignment: " ++ flag showPackageProblem (MissingFlag (PD.FlagName flag)) = "missing an assignment for the flag: " ++ flag showPackageProblem (ExtraFlag (PD.FlagName flag)) = "extra flag given that is not used by the package: " ++ flag showPackageProblem (DuplicateDeps pkgids) = "duplicate packages specified as selected dependencies: " ++ intercalate ", " (map display pkgids) showPackageProblem (MissingDep dep) = "the package has a dependency " ++ display dep ++ " but no package has been selected to satisfy it." showPackageProblem (ExtraDep pkgid) = "the package configuration specifies " ++ display pkgid ++ " but (with the given flag assignment) the package does not actually" ++ " depend on any version of that package." showPackageProblem (InvalidDep dep pkgid) = "the package depends on " ++ display dep ++ " but the configuration specifies " ++ display pkgid ++ " which does not satisfy the dependency." -- | A 'ConfiguredPackage' is valid if the flag assignment is total and if -- in the configuration given by the flag assignment, all the package -- dependencies are satisfied by the specified packages. -- configuredPackageProblems :: Platform -> CompilerInfo -> ConfiguredPackage -> [PackageProblem] configuredPackageProblems platform cinfo (ConfiguredPackage pkg specifiedFlags stanzas specifiedDeps') = [ DuplicateFlag flag | ((flag,_):_) <- duplicates specifiedFlags ] ++ [ MissingFlag flag | OnlyInLeft flag <- mergedFlags ] ++ [ ExtraFlag flag | OnlyInRight flag <- mergedFlags ] ++ [ DuplicateDeps pkgs | pkgs <- CD.nonSetupDeps (fmap (duplicatesBy (comparing packageName)) specifiedDeps) ] ++ [ MissingDep dep | OnlyInLeft dep <- mergedDeps ] ++ [ ExtraDep pkgid | OnlyInRight pkgid <- mergedDeps ] ++ [ InvalidDep dep pkgid | InBoth dep pkgid <- mergedDeps , not (packageSatisfiesDependency pkgid dep) ] where specifiedDeps :: ComponentDeps [PackageId] specifiedDeps = fmap (map confSrcId) specifiedDeps' mergedFlags = mergeBy compare (sort $ map PD.flagName (PD.genPackageFlags (packageDescription pkg))) (sort $ map fst specifiedFlags) packageSatisfiesDependency (PackageIdentifier name version) (Dependency name' versionRange) = assert (name == name') $ version `withinRange` versionRange dependencyName (Dependency name _) = name mergedDeps :: [MergeResult Dependency PackageId] mergedDeps = mergeDeps requiredDeps (CD.flatDeps specifiedDeps) mergeDeps :: [Dependency] -> [PackageId] -> [MergeResult Dependency PackageId] mergeDeps required specified = let sortNubOn f = nubBy ((==) `on` f) . sortBy (compare `on` f) in mergeBy (\dep pkgid -> dependencyName dep `compare` packageName pkgid) (sortNubOn dependencyName required) (sortNubOn packageName specified) -- TODO: It would be nicer to use ComponentDeps here so we can be more -- precise in our checks. That's a bit tricky though, as this currently -- relies on the 'buildDepends' field of 'PackageDescription'. (OTOH, that -- field is deprecated and should be removed anyway.) As long as we _do_ -- use a flat list here, we have to allow for duplicates when we fold -- specifiedDeps; once we have proper ComponentDeps here we should get rid -- of the `nubOn` in `mergeDeps`. requiredDeps :: [Dependency] requiredDeps = --TODO: use something lower level than finalizePackageDescription case finalizePackageDescription specifiedFlags (const True) platform cinfo [] (enableStanzas stanzas $ packageDescription pkg) of Right (resolvedPkg, _) -> externalBuildDepends resolvedPkg ++ maybe [] PD.setupDepends (PD.setupBuildInfo resolvedPkg) Left _ -> error "configuredPackageInvalidDeps internal error" -- ------------------------------------------------------------ -- * Simple resolver that ignores dependencies -- ------------------------------------------------------------ -- | A simplistic method of resolving a list of target package names to -- available packages. -- -- Specifically, it does not consider package dependencies at all. Unlike -- 'resolveDependencies', no attempt is made to ensure that the selected -- packages have dependencies that are satisfiable or consistent with -- each other. -- -- It is suitable for tasks such as selecting packages to download for user -- inspection. It is not suitable for selecting packages to install. -- -- Note: if no installed package index is available, it is OK to pass 'mempty'. -- It simply means preferences for installed packages will be ignored. -- resolveWithoutDependencies :: DepResolverParams -> Either [ResolveNoDepsError] [SourcePackage] resolveWithoutDependencies (DepResolverParams targets constraints prefs defpref installedPkgIndex sourcePkgIndex _reorderGoals _indGoals _avoidReinstalls _shadowing _strFlags _maxBjumps) = collectEithers (map selectPackage targets) where selectPackage :: PackageName -> Either ResolveNoDepsError SourcePackage selectPackage pkgname | null choices = Left $! ResolveUnsatisfiable pkgname requiredVersions | otherwise = Right $! maximumBy bestByPrefs choices where -- Constraints requiredVersions = packageConstraints pkgname pkgDependency = Dependency pkgname requiredVersions choices = PackageIndex.lookupDependency sourcePkgIndex pkgDependency -- Preferences PackagePreferences preferredVersions preferInstalled = packagePreferences pkgname bestByPrefs = comparing $ \pkg -> (installPref pkg, versionPref pkg, packageVersion pkg) installPref = case preferInstalled of PreferLatest -> const False PreferInstalled -> not . null . InstalledPackageIndex.lookupSourcePackageId installedPkgIndex . packageId versionPref pkg = packageVersion pkg `withinRange` preferredVersions packageConstraints :: PackageName -> VersionRange packageConstraints pkgname = Map.findWithDefault anyVersion pkgname packageVersionConstraintMap packageVersionConstraintMap = let pcs = map unlabelPackageConstraint constraints in Map.fromList [ (name, range) | PackageConstraintVersion name range <- pcs ] packagePreferences :: PackageName -> PackagePreferences packagePreferences = interpretPackagesPreference (Set.fromList targets) defpref prefs collectEithers :: [Either a b] -> Either [a] [b] collectEithers = collect . partitionEithers where collect ([], xs) = Right xs collect (errs,_) = Left errs partitionEithers :: [Either a b] -> ([a],[b]) partitionEithers = foldr (either left right) ([],[]) where left a (l, r) = (a:l, r) right a (l, r) = (l, a:r) -- | Errors for 'resolveWithoutDependencies'. -- data ResolveNoDepsError = -- | A package name which cannot be resolved to a specific package. -- Also gives the constraint on the version and whether there was -- a constraint on the package being installed. ResolveUnsatisfiable PackageName VersionRange instance Show ResolveNoDepsError where show (ResolveUnsatisfiable name ver) = "There is no available version of " ++ display name ++ " that satisfies " ++ display (simplifyVersionRange ver)
trskop/cabal
cabal-install/Distribution/Client/Dependency.hs
bsd-3-clause
33,988
1
19
8,585
5,876
3,202
2,674
587
4
foo :: (() -> () -> [()] -> [()]) -> () -> [()] -> [()] foo k = \_ xs -> concatMap ($ [head xs]) [bar] where bar = let k' = k undefined undefined in \xs -> let k'' = [k' xs] in (() : (foldr1 (>>) k'')) k :: () -> [()] -> [()] k = foo (\_ -> k) --k a = foo (\_ -> k) a -- all the work should happen in r r :: () r = k undefined [] !! 4000 main = print r
urbanslug/ghc
testsuite/tests/profiling/should_run/T680.hs
bsd-3-clause
392
0
15
131
230
124
106
13
1
f i = if ?flag then i*2 else i g i = let ?flag=False in f i
ghc-android/ghc
testsuite/tests/ghci.debugger/scripts/break015.hs
bsd-3-clause
61
0
8
18
43
21
22
-1
-1
{- HAAP: Haskell Automated Assessment Platform This module provides a miscellaneous utility functions. -} module HAAP.Utils where import Data.Map (Map(..)) import qualified Data.Map as Map import Data.Time.LocalTime import Data.Time.Calendar import Data.Time.Format import Data.Csv import Data.Char import Data.List import Data.String import qualified Data.Vector as Vector import qualified Data.HashMap.Strict as HashMap import qualified Data.ByteString as ByteString import System.FilePath import System.FilePath.Find import System.Directory import System.IO.Unsafe import Control.Monad import Text.Printf import Text.Parsec as Parsec addPrefixHeader :: String -> Header -> Header addPrefixHeader n xs = Vector.map (ByteString.append (fromString n)) xs addPrefixNamedRecord :: String -> NamedRecord -> NamedRecord addPrefixNamedRecord n xs = HashMap.fromList $ map (\(k,v) -> (ByteString.append (fromString n) k,v)) $ HashMap.toList xs remPrefixNamedRecord :: String -> NamedRecord -> NamedRecord remPrefixNamedRecord n xs = HashMap.fromList $ aux $ HashMap.toList xs where aux [] = [] aux ((k,v):xs) = case stripPrefix n (show k) of Nothing -> aux xs Just k' -> (fromString k',v) : aux xs instance Eq ZonedTime where x == y = zonedTimeToUTC x == zonedTimeToUTC y instance Ord ZonedTime where compare x y = compare (zonedTimeToUTC x) (zonedTimeToUTC y) sameJust :: Eq a => Maybe a -> Maybe a -> Bool sameJust (Just x) (Just y) = x == y sameJust _ _ = False printFloat :: Float -> Int -> String printFloat f i = printf ("%."++show i++"f") f printDouble :: Double -> Int -> String printDouble f i = printf ("%."++show i++"f") f mapFst :: (a -> c) -> (a,b) -> (c,b) mapFst f (x,y) = (f x,y) mapSnd :: (b -> c) -> (a,b) -> (a,c) mapSnd f (x,y) = (x,f y) mapFst3 :: (a -> a') -> (a,b,c) -> (a',b,c) mapFst3 f (x,y,z) = (f x,y,z) mapSnd3 :: (b -> b') -> (a,b,c) -> (a,b',c) mapSnd3 f (x,y,z) = (x,f y,z) mapThr3 :: (c -> c') -> (a,b,c) -> (a,b,c') mapThr3 f (x,y,z) = (x,y,f z) mapFstM :: Monad m => (a -> m c) -> (a,b) -> m (c,b) mapFstM f (x,y) = f x >>= \x' -> return (x',y) mapSndM :: Monad m => (b -> m c) -> (a,b) -> m (a,c) mapSndM f (x,y) = f y >>= \y' -> return (x,y') fst3 :: (a,b,c) -> a fst3 (x,y,z) = x snd3 :: (a,b,c) -> b snd3 (x,y,z) = y thr3 :: (a,b,c) -> c thr3 (x,y,z) = z fst4 :: (a,b,c,d) -> a fst4 (x,y,z,w) = x snd4 :: (a,b,c,d) -> b snd4 (x,y,z,w) = y thr4 :: (a,b,c,d) -> c thr4 (x,y,z,w) = z fou4 :: (a,b,c,d) -> d fou4 (x,y,z,w) = w averageList :: Fractional a => [a] -> a averageList xs | length xs == 0 = 0 | otherwise = sum xs / realToFrac (length xs) zipLeft :: [a] -> [b] -> [(a,Maybe b)] zipLeft [] [] = [] zipLeft (x:xs) [] = (x,Nothing) : zipLeft xs [] zipLeft [] (y:ys) = [] zipLeft (x:xs) (y:ys) = (x,Just y) : zipLeft xs ys groupN :: Int -> [a] -> [[a]] groupN n [] = [] groupN n xs = case splitAt n xs of (ys,zs) -> ys : groupN n zs snoc :: [x] -> x -> [x] snoc xs x = xs ++ [x] foldr0 :: (a -> a -> a) -> [a] -> a -> a foldr0 f [] x = x foldr0 f xs x = foldr1 f xs lookupMap :: Ord a => a -> Map a b -> b lookupMap x xs = case Map.lookup x xs of Just y -> y Nothing -> error $ "lookupMap can't find key" pathDepth :: [FilePath] -> Int pathDepth [] = 0 pathDepth ("":xs) = pathDepth xs pathDepth (".":xs) = pathDepth xs pathDepth ("..":xs) = pred $ pathDepth xs pathDepth ("/":xs) = pathDepth xs pathDepth ("./":xs) = pathDepth xs pathDepth ("../":xs) = pred $ pathDepth xs pathDepth (x:xs) = succ $ pathDepth xs dirToRoot :: FilePath -> FilePath dirToRoot p = case joinPath $ replicate (pathDepth $ splitPath p) ".." of "" -> "." x -> x fileToRoot :: FilePath -> FilePath fileToRoot p = case joinPath $ replicate (pred $ pathDepth $ splitPath p) ".." of "" -> "." x -> x anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool anyM f [] = return False anyM f (x:xs) = f x >>= \b -> if b then return b else anyM f xs concatPaths [] = [] concatPaths [x] = x concatPaths (x:xs) = x ++ ":" ++ concatPaths xs unSplitOn :: [a] -> [[a]] -> [a] unSplitOn tok [] = [] unSplitOn tok [x] = x unSplitOn tok (x:xs) = x ++ tok ++ unSplitOn tok xs compareSnd x y = compare (snd x) (snd y) readDay :: String -> Day readDay str = readTime defaultTimeLocale (iso8601DateFormat Nothing) str canonicalFilePath :: FilePath -> IO FilePath canonicalFilePath fp = do exists <- liftM2 (||) (doesFileExist fp) (doesDirectoryExist fp) if exists then canonicalizePath fp else fmap (</> fp) getCurrentDirectory canonicalFilePath' :: FilePath -> FilePath canonicalFilePath' = unsafePerformIO . canonicalFilePath singleton x = [x] appendMaybe :: Maybe a -> Maybe a -> Maybe a appendMaybe Nothing y = y appendMaybe x y = x infixl 0 <||> x <||> y = Parsec.try x <|> y isEmptyLine :: String -> Bool isEmptyLine = all isSpace sepByStr :: String -> [String] -> String sepByStr s [] = [] sepByStr s [x] = x sepByStr s (x:xs) = x ++ s ++ sepByStr s xs divNote :: String -> Int -> Int -> Int divNote str 0 y = 0 divNote str x 0 = error $ "divideByZero " ++ str ++ " " ++ show x divNote str x y = div x y
hpacheco/HAAP
src/HAAP/Utils.hs
mit
5,134
0
13
1,081
2,671
1,432
1,239
144
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module System.ImportGraph.ModuleCluster where import Avail import ClassyPrelude import Data.GraphViz import Data.GraphViz.Attributes.Complete import Data.GraphViz.Types.Monadic import qualified Data.Text.Lazy as TL import HscTypes import Module import Name moduleCluster :: ModIface -> Dot TL.Text moduleCluster iface@ModIface{..} = do cluster (Str (ifaceName iface)) $ do graphAttrs [textLabel (ifaceName iface)] node (ifaceDummyNodeName iface) [Style [SItem Invisible []]] mapM node' exports mapM_ (ifaceUsageEdges iface) mi_usages where exports = map (pack . getOccString . availName) mi_exports ifaceName :: ModIface -> TL.Text ifaceName = moduleText . mi_module moduleText :: Module -> TL.Text moduleText = pack . moduleNameString . moduleName ifaceDummyNodeName :: ModIface -> TL.Text ifaceDummyNodeName iface = ifaceName iface <> "_dummy_node" ifaceClusterName :: ModIface -> TL.Text ifaceClusterName iface = "cluster_" <> ifaceName iface ifaceUsageEdges :: ModIface -> Usage -> Dot TL.Text ifaceUsageEdges iface UsagePackageModule{..} = do ifaceEdge iface (moduleText usg_mod) node (moduleText usg_mod) [Shape Component] ifaceUsageEdges iface UsageHomeModule{..} = mapM_ (ifaceEdge iface . pack . occNameString . fst) usg_entities ifaceUsageEdges iface UsageFile{..} = ifaceEdge iface (pack usg_file_path) ifaceUsageEdges _ _ = mempty ifaceEdge :: ModIface -> TL.Text -> Dot TL.Text ifaceEdge iface edgeTo = edge (ifaceDummyNodeName iface) edgeTo [LTail (ifaceClusterName iface)]
ncaq/haskell-import-graph
lib/System/ImportGraph/ModuleCluster.hs
mit
1,721
0
15
324
494
253
241
38
1
{-# LANGUAGE StandaloneDeriving, FlexibleInstances #-} module Derivation where import qualified Prelude as P import Lib c2hl :: List a -> [a] c2hl Nil = [] c2hl (Cons x xs) = x : (c2hl xs) deriving instance (P.Eq Cand) deriving instance (P.Ord Cand) deriving instance (P.Show Cand) deriving instance (P.Show Bool) deriving instance (P.Eq Bool) deriving instance (P.Show Nat) deriving instance (P.Eq Nat) deriving instance (P.Ord Nat) deriving instance (P.Show a, P.Show b) => P.Show (Sum a b) deriving instance (P.Show a, P.Show b) => P.Show (Prod a b) -- show (Pair a b) = "(" P.++ P.show a P.++ ", " P.++ P.show b ")" deriving instance (P.Show a) => P.Show (List a) deriving instance (P.Show Comparison) deriving instance (P.Show Sumbool) deriving instance (P.Show a) => P.Show (Sumor a) deriving instance (P.Show Positive) deriving instance (P.Show Z) haskInt :: Nat -> P.Int haskInt O = 0 haskInt (S p) = 1 P.+ haskInt p haskPos :: Positive -> P.Int haskPos XH = 1 haskPos p = haskHelp p 1 where haskHelp XH p2 = p2 haskHelp (XO r) p2 = haskHelp r (2 P.* p2) haskHelp (XI r) p2 = p2 P.+ haskHelp r (2 P.* p2) haskZ :: Z -> P.Int haskZ Z0 = 0 haskZ (Zpos p) = haskPos p haskZ (Zneg p) = -1 P.* haskPos p instance P.Show PathT where show (UnitT x y) = P.show x P.++ " --> " P.++ P.show y show (ConsT x _ _ p) = P.show x P.++ " --> " P.++ P.show p -- deriving instance (P.Show PathT) instance P.Show (SigT (Cand -> Bool) (SigT Count ())) where show (ExistT f (ExistT v _)) = P.show v show_winner :: Wins_type -> Cand -> [Cand] -> P.String show_winner g x [] = "" show_winner g x (y : ys) = case (g y) of (ExistT u (Pair v (ExistT f _))) -> " for " P.++ P.show y P.++ ": " P.++ "path " P.++ P.show v P.++ " of strenght " P.++ P.show (haskZ u) P.++ ", " P.++ P.show (1 P.+ haskZ u) P.++ "-" P.++ "coclosed set: " P.++ P.show (P.filter (\(xx, yy) -> f (Pair xx yy) P.== True) [(a, b) | a <- (c2hl cand_all), b <- (c2hl cand_all), a P./= b]) P.++ "\n" P.++ show_winner g x ys show_loser :: Loses_type -> Cand -> P.String show_loser g x = case g of (ExistT u (ExistT c (Pair p (ExistT f _)))) -> " for " P.++ P.show c P.++ ": " P.++ "path " P.++ P.show p P.++ " of strength >= " P.++ P.show (haskZ u) P.++ ", " P.++ P.show (haskZ u) P.++ "-" P.++ "coclosed set: " P.++ P.show (P.filter (\(xx, yy) -> f (Pair xx yy) P.== True) [(a, b) | a <- (c2hl cand_all), b <- (c2hl cand_all), a P./= b]) show_cand :: (Cand -> Sum Wins_type Loses_type) -> Cand -> P.String show_cand f x = case (f x) of Inl g -> "winning: " P.++ P.show x P.++ "\n" P.++ show_winner g x (P.filter (\y -> y P./= x) (c2hl cand_all)) Inr h -> "losing: " P.++ P.show x P.++ "\n" P.++ show_loser h x show_ballot :: Ballot -> P.String show_ballot f = P.unwords (P.map (\x -> P.show x P.++ P.show (haskInt (f x))) (c2hl cand_all)) show_list_ballot :: List Ballot -> P.String show_list_ballot ls = P.show (P.map show_ballot (c2hl ls)) show_marg :: (Cand -> Cand -> Z) -> P.String show_marg m = "[" P.++ P.unwords (P.map (\(x, y) -> P.show x P.++ P.show y P.++ ":" P.++ P.show (haskZ (m x y))) [(a, b) | a <- (c2hl cand_all), b <- (c2hl cand_all), b P.> a]) P.++ "]" instance P.Show Count where show (Ax ls m) = "" show (Cvalid u us m nm inbs c) = P.show c P.++ "V = [" P.++ show_ballot u P.++ ",....]" P.++ ", I = " P.++ show_list_ballot inbs P.++ ", M = " P.++ show_marg m P.++ "\n----------------------------------------------------------------------------------------------------------------------------------------------------\n" show (Cinvalid u us m inbs c) = P.show c P.++ "I = [" P.++ show_ballot u P.++ ",....], I = " P.++ show_list_ballot inbs P.++ ", M = " P.++ show_marg m P.++ "\n----------------------------------------------------------------------------------------------------------------------------------------------------\n" show (Fin m ls p f c) = P.show c P.++ "V = [], I = " P.++ show_list_ballot ls P.++ ", M = " P.++ show_marg m P.++ "\n----------------------------------------------------------------------------------------------------------------------------------------------------\n" P.++ (P.unlines P.$ P.map (show_cand f) (c2hl cand_all))
mukeshtiwari/formalized-voting
paper-code/schulze-voting/src/Derivation.hs
mit
4,381
0
22
985
2,031
1,021
1,010
75
3
-- {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE DeriveDataTypeable #-} module Main where -- import Data.Word import qualified EdaxProtocol import System.IO import System.Environment(getArgs, getProgName) import System.Console.GetOpt import Text.Printf -- foreign export ccall search :: Word64 -> Word64 -> Int -> Int -> IO Int -- -- search :: Word64 -> Word64 -> Int -> Int -> IO Int -- search black white pnsLessThan searchDepth = do -- putStrLn "Called!" -- return $ 10 + 10 data HamletOptions = EvalOptions String | HashOptions String deriving Show defaultOptions = EvalOptions "" options :: [OptDescr HamletOptions] options = [ Option ['e'] ["eval"] (ReqArg EvalOptions "SFEN") "Eval given board and turn in SFEN", Option ['h'] ["hash"] (ReqArg HashOptions "SFEN") "Show hash of given board factors" ] compilerOpts :: [String] -> String -> IO ([HamletOptions], [String]) compilerOpts argv progName = case getOpt Permute options argv of (o,n,[] ) -> return (o,n) (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) where header = printf "Usage: %s [OPTION...]\n SFEN exmple: %s" progName "\"----O-X------X-----XXXO-OXXXXXOO-XXOOXOOXXOXXXOO--OOOO-O----OO-- O\"" main :: IO () main = do argv <- getArgs progName <- getProgName (options, _) <- compilerOpts argv progName case length options of 0 -> startEdaxLoop _ -> case head options of EvalOptions s -> printf "%s\n" $ show $ EdaxProtocol.evalHelper s HashOptions s -> printf "%s\n" $ show $ EdaxProtocol.hashHelper s _ -> startEdaxLoop startEdaxLoop = do hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering EdaxProtocol.commandLoop (EdaxProtocol.Search EdaxProtocol.AlphaBeta) undefined
ysnrkdm/Hamlet
src/Main.hs
mit
1,877
0
15
425
443
233
210
40
4
module Graphics.Urho3D.Graphics.Internal.Camera( Camera , ViewOverride(..) , ViewOverrideFlags , cameraCntx ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import Data.Word import GHC.Generics import Graphics.Urho3D.Container.FlagSet import qualified Data.Map as Map data Camera data ViewOverride = ViewOverrideNone | ViewOverrideLowMaterialQuality | ViewOverrideDisableShadows | ViewOverrideDisableOcclusion deriving (Eq, Ord, Show, Read, Bounded, Generic) instance Enum ViewOverride where toEnum v = case v of 0 -> ViewOverrideNone 1 -> ViewOverrideLowMaterialQuality 2 -> ViewOverrideDisableShadows 4 -> ViewOverrideDisableOcclusion _ -> ViewOverrideNone {-# INLINE toEnum #-} fromEnum v = case v of ViewOverrideNone -> 0 ViewOverrideLowMaterialQuality -> 1 ViewOverrideDisableShadows -> 2 ViewOverrideDisableOcclusion -> 4 {-# INLINE fromEnum #-} type ViewOverrideFlags = FlagSet Word32 ViewOverride cameraCntx :: C.Context cameraCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "Camera", [t| Camera |]) ] }
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Graphics/Internal/Camera.hs
mit
1,204
0
11
224
270
162
108
-1
-1
module Main where sortTuple (l, []) lt = (l, []) sortTuple (s, h:t) lt = sortTuple ((filter (fixed_lt) s) ++ [h] ++ (filter (not . fixed_lt) s), t) lt where fixed_lt = (\x -> (lt x) h) sortBy l lt = fst (sortTuple ([], l) lt) sort l = sortBy l (<)
henryaddison/7-lang-7-weeks
week7-haskell/2/sort.hs
mit
262
0
11
66
166
91
75
6
1
module ListTransformations (dropItem, dropDouble) where -- deletes the item from the list -- dropItem '/' "/home/i/test/" -> "homeitest" dropItem :: (Eq a) => a -> [a] -> [a] dropItem i = foldr (\x y -> if x == i then y else x : y) [] -- cuts the list from the start to front until end and drops everything else -- doubleDrop 2 3 "Haskell is fun!" -> "skell is fu" dropDouble :: Int -> Int -> [a] -> [a] dropDouble front end l = reverse (e f) where f = drop front l e f = drop end (reverse f)
cirquit/Personal-Repository
Haskell/RWH/Lists/ListTransformations.hs
mit
553
0
9
162
160
88
72
7
2
module Distribution.Compat.Filesystem.Posix (pathSeparator, pathSeparators, pathCoerceToDirectory, pathCoerceToFile, pathIsAbsolute, pathIsRelative, pathIsDirectory, pathIsFile, (</>), removeFileSilently, removeDirectorySilently, removeDirectoryRecursiveSilently, listDirectory) where import Control.Exception import Data.List import Distribution.Compat.Filesystem.Portable import qualified System.Posix.Directory as Posix import qualified System.Posix.Files as Posix pathSeparator :: Char pathSeparator = '/' pathSeparators :: [Char] pathSeparators = ['/'] removeFileSilently :: FilePath -> IO () removeFileSilently path = do Posix.removeLink $ pathCoerceToFile path removeDirectorySilently :: FilePath -> IO () removeDirectorySilently path = do Posix.removeLink $ pathCoerceToFile path removeDirectoryRecursiveSilently :: FilePath -> IO () removeDirectoryRecursiveSilently path = do let visit path = do exists <- Posix.fileExist path if exists then do fileStatus <- Posix.getSymbolicLinkStatus path if Posix.isSymbolicLink fileStatus then visitFile path else do if Posix.isDirectory fileStatus then visitDirectory path else visitFile path else return () visitFile path = do removeFileSilently path visitDirectory path = do itemPaths <- listDirectory path mapM_ visit $ map (path </>) $ itemPaths \\ [".", ".."] removeDirectorySilently path visit path listDirectory :: FilePath -> IO [FilePath] listDirectory path = do bracket (Posix.openDirStream path) (Posix.closeDirStream) (\dirStream -> do let loop accumulator = do itemPath <- Posix.readDirStream dirStream if itemPath == "" then return accumulator else loop $ accumulator ++ [itemPath] loop [])
IreneKnapp/cabal-app
Distribution/Compat/Filesystem/Posix.hs
mit
2,040
0
20
576
485
251
234
62
4
module Web.Kirstie.Hook ( afterSaveHooks , beforeSaveHooks ) where import Web.Kirstie.Model import Web.Kirstie.Hooks.RelatedPosts import Web.Kirstie.Hooks.AtomFeed import Web.Kirstie.Hooks.XmlSitemap import Web.Kirstie.Hooks.AmazonAssociates import Web.Kirstie.Hooks.TagArchives import Web.Kirstie.Hooks.ArchivePage beforeSaveHooks :: [Configure -> [Article] -> IO [Article]] beforeSaveHooks = [ amazonAssociates ] afterSaveHooks :: [Configure -> [Article] -> IO ()] afterSaveHooks = [ relatedPosts , atomFeed , xmlSitemap , tagArchives , archivePage ]
hekt/blog-system
src/Web/Kirstie/Hook.hs
mit
671
0
9
174
140
89
51
18
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.CharacterData (js_substringData, substringData, js_appendData, appendData, js_insertData, insertData, js_deleteData, deleteData, js_replaceData, replaceData, js_setData, setData, js_getData, getData, js_getLength, getLength, CharacterData, castToCharacterData, gTypeCharacterData, IsCharacterData, toCharacterData) 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[\"substringData\"]($2, $3)" js_substringData :: CharacterData -> Word -> Word -> IO (Nullable JSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.substringData Mozilla CharacterData.substringData documentation> substringData :: (MonadIO m, IsCharacterData self, FromJSString result) => self -> Word -> Word -> m (Maybe result) substringData self offset length = liftIO (fromMaybeJSString <$> (js_substringData (toCharacterData self) offset length)) foreign import javascript unsafe "$1[\"appendData\"]($2)" js_appendData :: CharacterData -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.appendData Mozilla CharacterData.appendData documentation> appendData :: (MonadIO m, IsCharacterData self, ToJSString data') => self -> data' -> m () appendData self data' = liftIO (js_appendData (toCharacterData self) (toJSString data')) foreign import javascript unsafe "$1[\"insertData\"]($2, $3)" js_insertData :: CharacterData -> Word -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.insertData Mozilla CharacterData.insertData documentation> insertData :: (MonadIO m, IsCharacterData self, ToJSString data') => self -> Word -> data' -> m () insertData self offset data' = liftIO (js_insertData (toCharacterData self) offset (toJSString data')) foreign import javascript unsafe "$1[\"deleteData\"]($2, $3)" js_deleteData :: CharacterData -> Word -> Word -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.deleteData Mozilla CharacterData.deleteData documentation> deleteData :: (MonadIO m, IsCharacterData self) => self -> Word -> Word -> m () deleteData self offset length = liftIO (js_deleteData (toCharacterData self) offset length) foreign import javascript unsafe "$1[\"replaceData\"]($2, $3, $4)" js_replaceData :: CharacterData -> Word -> Word -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.replaceData Mozilla CharacterData.replaceData documentation> replaceData :: (MonadIO m, IsCharacterData self, ToJSString data') => self -> Word -> Word -> data' -> m () replaceData self offset length data' = liftIO (js_replaceData (toCharacterData self) offset length (toJSString data')) foreign import javascript unsafe "$1[\"data\"] = $2;" js_setData :: CharacterData -> Nullable JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.data Mozilla CharacterData.data documentation> setData :: (MonadIO m, IsCharacterData self, ToJSString val) => self -> Maybe val -> m () setData self val = liftIO (js_setData (toCharacterData self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"data\"]" js_getData :: CharacterData -> IO (Nullable JSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.data Mozilla CharacterData.data documentation> getData :: (MonadIO m, IsCharacterData self, FromJSString result) => self -> m (Maybe result) getData self = liftIO (fromMaybeJSString <$> (js_getData (toCharacterData self))) foreign import javascript unsafe "$1[\"length\"]" js_getLength :: CharacterData -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/CharacterData.length Mozilla CharacterData.length documentation> getLength :: (MonadIO m, IsCharacterData self) => self -> m Word getLength self = liftIO (js_getLength (toCharacterData self))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/CharacterData.hs
mit
4,976
70
11
849
1,174
649
525
82
1
{- ================================================================================ The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number. Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair. Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers: 12496 -> 14288 -> 15472 -> 14536 -> 14264 (-> 12496 -> ...) Since this chain returns to its starting point, it is called an amicable chain. Find the smallest member of the longest amicable chain with no element exceeding one million. ================================================================================ -} import Data.List import Data.Numbers.Primes (primes) import qualified Data.Set as Set import Data.Array.Unboxed type FactorExp = (Int, Int) -- (b,e) represents b^e type Prime = Int -- Returns the prime factorisation of a number primeFactors :: Int -- Number to factor -> [FactorExp] -- prime factors of the number primeFactors n = primeFactors' n (map fromIntegral primes) [] where primeFactors' :: Int -- number to factor -> [Prime] -- primes -> [FactorExp] -- accumulator -> [FactorExp] -- prime factors of the number primeFactors' n (p:ps) acc | n == 1 = acc | n < p*p = (n, 1):acc | rem n p == 0 = primeFactors' n' ps ((p, exp):acc) | otherwise = primeFactors' n ps acc where (n', exp) = reduce (n, 0) {- reduce (n, a) -> (m, b) Reduces the value n*p^a with regards to the current prime p, i.e. that n * p^a = m * p^b, with b the greatest possible value. As a pecial case: reduce (n, 0) = (m, b) => n = m * p^b -} reduce :: (Int, Int) -> (Int, Int) reduce arg@(n, a) | rem n p == 0 = reduce (quot n p, a+1) | otherwise = arg -- Returns the divisors of a number divisors :: Int -> [Int] divisors n = combine $ primeFactors n expand :: FactorExp -> [Int] expand (base, exp) = expand' base exp base [1] expand' base 0 cur acc = acc expand' base exp cur acc = expand' base (exp-1) (cur*base) (cur:acc) combine :: [FactorExp] -> [Int] combine factors = combine' factors [1] combine' :: [FactorExp] -> [Int] -> [Int] combine' [] acc = acc combine' (factor:factors) acc = combine' factors (combine'' (expand factor) acc) combine'' :: [Int] -> [Int] -> [Int] combine'' factors values = concat $ map (\f -> map (f*) values) factors -- Trajectory data Trajectory = Trajectory [Int] -- Trajectory (Set.Set Int) -- nodes deriving (Show) data Accum = Accum { length_ :: Int , nodes_ :: [Int] , isNodesVisited_ :: (UArray Int Bool) -- visited } deriving (Show) data TrajectoryOutcome = Cycle [Int] -- nodes | NoCycle [Int] -- nodes deriving (Show) emptyTrajectory = Trajectory [] Set.empty emptyAccum :: Int -> Accum emptyAccum dim = Accum 0 -- length [] -- cycles (array (1, dim) ((1, True) : [(i, False) | i <- [2..dim]])) -- visited step = sum . tail . divisors trajectory :: Int -> Int -> Accum -> TrajectoryOutcome trajectory n dim (Accum len cycle nodeArray) = trajectory_ n emptyTrajectory where trajectory_ :: Int -> Trajectory -> TrajectoryOutcome trajectory_ n (Trajectory trajectory nodes) | dim < n = NoCycle trajectory | nodeArray ! n = NoCycle trajectory | Set.member n nodes = Cycle (n:trajectory) | otherwise = trajectory_ (step n) (Trajectory (n:trajectory) (Set.insert n nodes)) getCycle :: [Int] -> [Int] getCycle nodes = getCycle' (tail nodes) [] where firstNode = head nodes getCycle' :: [Int] -> [Int] -> [Int] getCycle' (node:nodes) acc | firstNode == node = node:acc | otherwise = getCycle' nodes (node:acc) run dim = nodes_ $ foldl' iter (emptyAccum dim) [1..dim] where iter :: Accum -> Int -> Accum iter acc@(Accum len cycle isNodeVisited) n = let trajectoryOutcome = trajectory n dim acc in case trajectoryOutcome of NoCycle nodes -> acc {isNodesVisited_ = isNodeVisited // [(i,True) | i <- nodes]} Cycle nodes -> let cycle' = getCycle nodes len' = length cycle' isNodeVisited' = (isNodesVisited_ acc) // [(i,True) | i <- nodes] in if len < len' then Accum len' cycle' isNodeVisited' else acc {isNodesVisited_ = isNodeVisited'} main = do let result = run 1000000 print result print $minimum result
dpieroux/euler
0/0095.hs
mit
5,396
0
19
1,799
1,379
735
644
-1
-1
module CommandLineParser ( Command (..) , parseCommandLine ) where import Control.Applicative ((<$>), (*>), (<*), (<*>)) import Control.Monad (void) import Network.Traffic.Object ( EnumerationTarget (..) , FilterFunc (..) , filterFunc , maybeRead ) import Text.Parsec import Text.Parsec.String data Command = EmptyLine | Enumerate !EnumerationTarget !(Maybe FilterFunc) | File !FilePath | Playtime | LastObjectTime | Help | Quit deriving Show parseCommandLine :: String -> Either ParseError Command parseCommandLine = parse commandLine "" commandLine :: Parser Command commandLine = spaces *> ( emptyLine <|> enumerate <* eof' <|> file <* eof' <|> playtime <* eof' <|> lastObjectTime <* eof' <|> quit <* eof' <|> help <* eof' ) eof' :: Parser () eof' = spaces >> eof emptyLine :: Parser Command emptyLine = eof *> return EmptyLine enumerate :: Parser Command enumerate = string "enumerate" *> many1 space *> (Enumerate <$> enumerationTarget <*> optionMaybe filterSpec) file :: Parser Command file = string "file" *> spaces *> (File <$> filePath) playtime :: Parser Command playtime = string "playtime" *> return Playtime lastObjectTime :: Parser Command lastObjectTime = string "lastobjecttime" *> return LastObjectTime help :: Parser Command help = string "help" *> return Help quit :: Parser Command quit = string "quit" *> return Quit enumerationTarget :: Parser EnumerationTarget enumerationTarget = do s <- many1 letter case maybeRead s of Just target -> return target Nothing -> let expect = "Expected oneof: " ++ show [ minBound :: EnumerationTarget .. ] in parserFail expect filterSpec :: Parser FilterFunc filterSpec = many1 space *> string "where" *> filterSpec' where filterSpec' :: Parser FilterFunc filterSpec' = do void $ many1 space target <- many1 letter void $ many1 space void $ string "is" void $ many1 space value <- many1 letter case filterFunc target value of Left err -> parserFail err Right f -> return f filePath :: Parser FilePath filePath = many1 ( letter <|> digit <|> choice [char '.', char '-', char '_', char '/'] <?> "file name" )
kosmoskatten/traffic-analysis
src/CommandLineParser.hs
mit
2,636
0
18
896
705
360
345
78
2
-- expandiendo_un_circulo.hs -- Expandiendo un círculo. -- José A. Alonso Jiménez <[email protected]> -- Sevilla, 21 de Mayo de 2013 -- --------------------------------------------------------------------- import Graphics.Gloss main :: IO () main = animate (InWindow "Expandiendo un circulo" (1800,820) (90,90)) green animacion animacion :: Float -> Picture animacion t = circle (800 * sin (t / 4)) -- Nota: La variable t toma como valor el tiempo transcurrido. Sus -- valores son [0,0.5..]. Por tanto, los radios son [0,10,..].
jaalonso/I1M-Cod-Temas
src/Tema_27/expandiendo_un_circulo.hs
gpl-2.0
547
0
10
94
94
53
41
6
1
module Cluster (Cluster, emptyCluster, createCluster, blocksInCluster, isClusterEmpty, doClustersClash, isClusterWithinArea, moveClusterInDirection, joinClusters, rotateCluster, centerClusterAtLocation) where import Data.Map (Map) import qualified Data.Map as Map import Data data Cluster = Cluster { blocks :: Map Location Coloring } createCluster :: [Block] -> Cluster createCluster blocks = Cluster $ Map.fromList [(location, coloring) | (Block location coloring) <- blocks] emptyCluster :: Cluster emptyCluster = Cluster Map.empty blocksInCluster :: Cluster -> [Block] blocksInCluster = (map $ uncurry Block) . Map.toList . blocks isClusterEmpty :: Cluster -> Bool isClusterEmpty = Map.null . blocks doClustersClash :: Cluster -> Cluster -> Bool doClustersClash (Cluster a) (Cluster b) = not $ Map.null $ Map.intersection a b isClusterWithinArea :: Area -> Cluster -> Bool isClusterWithinArea area = (all $ isLocationWithinArea area) . Map.keys . blocks moveClusterInDirection :: Direction -> Cluster -> Cluster moveClusterInDirection direction = Cluster . (Map.mapKeys $ moveLocationInDirection direction) . blocks joinClusters :: Cluster -> Cluster -> Cluster joinClusters (Cluster a) (Cluster b) = Cluster $ Map.union a b rotateCluster :: Cluster -> Cluster rotateCluster cluster@(Cluster blocks) = let tranformation = \(Location x y) -> Location (y) (- x) rotatedCluster = Cluster $ Map.mapKeys tranformation blocks in centerClusterAtLocation (centerLocationOfCluster cluster) rotatedCluster centerClusterAtLocation :: Location -> Cluster -> Cluster centerClusterAtLocation (Location x0 y0) cluster@(Cluster blocks) = let (Location x1 y1) = centerLocationOfCluster cluster dx = x1 - x0 dy = y1 - y0 transformation = \(Location x y) -> Location (x - dx) (y - dy) in Cluster $ Map.mapKeys transformation blocks centerLocationOfCluster :: Cluster -> Location centerLocationOfCluster (Cluster blocks) = let (xs, ys) = unzip $ map (\(Location x y) -> (x, y)) (Map.keys blocks) average ns = (div (sum ns) (length ns)) in Location (average xs) (average ys)
pavelfatin/haskell-blocks
src/Cluster.hs
gpl-3.0
2,303
0
14
525
730
386
344
48
1
#!/usr/bin/env runhaskell {-# LANGUAGE UnicodeSyntax #-} import Prelude.Unicode import Data.Bool (bool) import Data.Monoid.Unicode ((⊕)) import Data.Char (isSpace) import Data.List (dropWhileEnd) import Control.Applicative (liftA2) modifyLines ∷ Bool → [String] → [String] modifyLines False [] = [] modifyLines True [] = ["```"] modifyLines _ ("Available options:":ys) = ["### Available options ###", "```"] ⧺ modifyLines True ys modifyLines _ (('U':'s':'a':'g':'e':':':' ':xs):ys) = ["```", xs, "```"] ⧺ modifyLines False ys modifyLines inCode (xs:ys) | lastElm ≡ Just ':' = endCodeLines ⧺ ["#### " ⊕ init xs' ⊕ " ####", "```"] ⧺ modifyLines True ys | all isSpace' xs = endCodeLines ⧺ [""] ⧺ modifyLines False ys | otherwise = [drop 2 xs] ⧺ modifyLines inCode ys where xs' = dropWhileEnd isSpace' (dropWhile isSpace' xs) isSpace' = liftA2 (∨) isSpace (≡'\b') lastElm = if null xs' then Nothing else Just (last xs') endCodeLines = bool [] ["```"] inCode addSubTitles ∷ [String] → [String] addSubTitles [] = [] addSubTitles (x:x'@('#':_):xs) | all isSpace x = x : x' : addSubTitles xs | otherwise = x : ("#" ⊕ x' ⊕ "#") : addSubTitles xs addSubTitles (x:xs) = x : addSubTitles xs main ∷ IO () main = getContents >>= mapM_ putStrLn ∘ addSubTitles ∘ (modifyLines False) ∘ drop 1 ∘ lines
39aldo39/klfc
scripts/Usage.hs
gpl-3.0
1,366
0
15
237
581
303
278
28
2
module Test where import Data.List {- Syntax -} -- redundant f :: Int f = if True then 1 else 2 f' :: Int f' = if True then 1 else 1 f1 :: Int f1 = (1 + 2) -- error g :: Int g = "aaa"
mumuxme/vim-config
test/test.hs
gpl-3.0
222
0
6
86
75
47
28
14
2
{-# 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.FireStore.Projects.Databases.Documents.PartitionQuery -- 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) -- -- Partitions a query by returning partition cursors that can be used to -- run the query in parallel. The returned partition cursors are split -- points that can be used by RunQuery as starting\/end points for the -- query results. -- -- /See:/ <https://cloud.google.com/firestore Cloud Firestore API Reference> for @firestore.projects.databases.documents.partitionQuery@. module Network.Google.Resource.FireStore.Projects.Databases.Documents.PartitionQuery ( -- * REST Resource ProjectsDatabasesDocumentsPartitionQueryResource -- * Creating a Request , projectsDatabasesDocumentsPartitionQuery , ProjectsDatabasesDocumentsPartitionQuery -- * Request Lenses , pddpqParent , pddpqXgafv , pddpqUploadProtocol , pddpqAccessToken , pddpqUploadType , pddpqPayload , pddpqCallback ) where import Network.Google.FireStore.Types import Network.Google.Prelude -- | A resource alias for @firestore.projects.databases.documents.partitionQuery@ method which the -- 'ProjectsDatabasesDocumentsPartitionQuery' request conforms to. type ProjectsDatabasesDocumentsPartitionQueryResource = "v1" :> CaptureMode "parent" "partitionQuery" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] PartitionQueryRequest :> Post '[JSON] PartitionQueryResponse -- | Partitions a query by returning partition cursors that can be used to -- run the query in parallel. The returned partition cursors are split -- points that can be used by RunQuery as starting\/end points for the -- query results. -- -- /See:/ 'projectsDatabasesDocumentsPartitionQuery' smart constructor. data ProjectsDatabasesDocumentsPartitionQuery = ProjectsDatabasesDocumentsPartitionQuery' { _pddpqParent :: !Text , _pddpqXgafv :: !(Maybe Xgafv) , _pddpqUploadProtocol :: !(Maybe Text) , _pddpqAccessToken :: !(Maybe Text) , _pddpqUploadType :: !(Maybe Text) , _pddpqPayload :: !PartitionQueryRequest , _pddpqCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsDatabasesDocumentsPartitionQuery' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pddpqParent' -- -- * 'pddpqXgafv' -- -- * 'pddpqUploadProtocol' -- -- * 'pddpqAccessToken' -- -- * 'pddpqUploadType' -- -- * 'pddpqPayload' -- -- * 'pddpqCallback' projectsDatabasesDocumentsPartitionQuery :: Text -- ^ 'pddpqParent' -> PartitionQueryRequest -- ^ 'pddpqPayload' -> ProjectsDatabasesDocumentsPartitionQuery projectsDatabasesDocumentsPartitionQuery pPddpqParent_ pPddpqPayload_ = ProjectsDatabasesDocumentsPartitionQuery' { _pddpqParent = pPddpqParent_ , _pddpqXgafv = Nothing , _pddpqUploadProtocol = Nothing , _pddpqAccessToken = Nothing , _pddpqUploadType = Nothing , _pddpqPayload = pPddpqPayload_ , _pddpqCallback = Nothing } -- | Required. The parent resource name. In the format: -- \`projects\/{project_id}\/databases\/{database_id}\/documents\`. -- Document resource names are not supported; only database resource names -- can be specified. pddpqParent :: Lens' ProjectsDatabasesDocumentsPartitionQuery Text pddpqParent = lens _pddpqParent (\ s a -> s{_pddpqParent = a}) -- | V1 error format. pddpqXgafv :: Lens' ProjectsDatabasesDocumentsPartitionQuery (Maybe Xgafv) pddpqXgafv = lens _pddpqXgafv (\ s a -> s{_pddpqXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pddpqUploadProtocol :: Lens' ProjectsDatabasesDocumentsPartitionQuery (Maybe Text) pddpqUploadProtocol = lens _pddpqUploadProtocol (\ s a -> s{_pddpqUploadProtocol = a}) -- | OAuth access token. pddpqAccessToken :: Lens' ProjectsDatabasesDocumentsPartitionQuery (Maybe Text) pddpqAccessToken = lens _pddpqAccessToken (\ s a -> s{_pddpqAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pddpqUploadType :: Lens' ProjectsDatabasesDocumentsPartitionQuery (Maybe Text) pddpqUploadType = lens _pddpqUploadType (\ s a -> s{_pddpqUploadType = a}) -- | Multipart request metadata. pddpqPayload :: Lens' ProjectsDatabasesDocumentsPartitionQuery PartitionQueryRequest pddpqPayload = lens _pddpqPayload (\ s a -> s{_pddpqPayload = a}) -- | JSONP pddpqCallback :: Lens' ProjectsDatabasesDocumentsPartitionQuery (Maybe Text) pddpqCallback = lens _pddpqCallback (\ s a -> s{_pddpqCallback = a}) instance GoogleRequest ProjectsDatabasesDocumentsPartitionQuery where type Rs ProjectsDatabasesDocumentsPartitionQuery = PartitionQueryResponse type Scopes ProjectsDatabasesDocumentsPartitionQuery = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/datastore"] requestClient ProjectsDatabasesDocumentsPartitionQuery'{..} = go _pddpqParent _pddpqXgafv _pddpqUploadProtocol _pddpqAccessToken _pddpqUploadType _pddpqCallback (Just AltJSON) _pddpqPayload fireStoreService where go = buildClient (Proxy :: Proxy ProjectsDatabasesDocumentsPartitionQueryResource) mempty
brendanhay/gogol
gogol-firestore/gen/Network/Google/Resource/FireStore/Projects/Databases/Documents/PartitionQuery.hs
mpl-2.0
6,488
0
16
1,374
790
465
325
121
1
-- brittany { lconfig_indentAmount: 8, lconfig_indentPolicy: IndentPolicyMultiple } foo = do let aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa foo foo = do let aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa foo
lspitzner/brittany
data/Test356.hs
agpl-3.0
457
0
11
142
48
23
25
10
1
-- The real Setup file for a Gtk2Hs package (invoked via the SetupWrapper). -- It contains only adjustments specific to this package, -- all Gtk2Hs-specific boilerplate is kept in Gtk2HsSetup.hs -- which should be kept identical across all packages. -- import Gtk2HsSetup ( gtk2hsUserHooks, checkGtk2hsBuildtools ) import Distribution.Simple ( defaultMainWithHooks ) main = do checkGtk2hsBuildtools ["gtk2hsC2hs", "gtk2hsTypeGen", "gtk2hsHookGenerator"] defaultMainWithHooks gtk2hsUserHooks
haasn/haskell-vte
SetupMain.hs
lgpl-2.1
499
0
8
68
53
31
22
5
1
{- Copyright 2015 Tristan Aubrey-Jones 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. -} {-| Copyright : (c) Tristan Aubrey-Jones, 2015 License : Apache-2 Maintainer : [email protected] Stability : experimental For more information please see <http://www.flocc.net/> -} module Compiler.Types.Variables (VarsIn(..), VarSubsts, applyVarSubst, fromList, fromDisjointList, composeVarSubsts, newVars, emptyVarSubsts) where import Compiler.Front.Indices (Idx, IdxSet, newidST) import Data.Maybe (Maybe(..)) import Data.Set (Set) import qualified Data.Set (toList) --import Data.Map.Strict (Map, mapWithKey, union, empty) --import qualified Data.Map.Strict as Data.Map (map, fromList, lookup, empty) import Data.IntMap.Strict (IntMap, mapWithKey, union) import qualified Data.IntMap.Strict as IM import Control.Monad.State.Strict ( StateT ) -- |A type that contains variables class VarsIn a where isVar :: a -> Maybe Idx getVars :: a -> Set Idx newVar :: Idx -> a applyVarSubsts :: VarSubsts a -> a -> a -- |Substs is a Map of substitutions from var ids -- |to terms. type VarSubsts a = IntMap a -- |emptyVarSubsts is an empty set of substitutions emptyVarSubsts :: IntMap a emptyVarSubsts = IM.empty -- |applyVarSubst takes a map of substitutions and a var id -- |and returns the substituted value if there is one, or -- |Var i if there isn't. applyVarSubst :: VarsIn a => VarSubsts a -> Idx -> a applyVarSubst subs i = case IM.lookup i subs of Just b -> b Nothing -> newVar i -- |fromList takes a list of (var id, VarsIn) pairs -- |and returns a VarSubsts for that list such that -- |subs are applied from left to right (left first...) fromList :: VarsIn a => [(Idx, a)] -> VarSubsts a fromList (h:t) = foldl (\a -> \b -> composeVarSubsts (fromDisjointList [b]) a) (fromDisjointList [h]) t fromList [] = emptyVarSubsts -- |fromDisjointList takes a list of disjoint (Var id, VarsIn) pairs -- |and returns a VarSubsts. fromDisjointList :: VarsIn a => [(Idx, a)] -> VarSubsts a fromDisjointList l = IM.fromList l -- |composeSubsts a b sequentially composes a and b -- |such that a is applied after b. composeVarSubsts :: VarsIn a => VarSubsts a -> VarSubsts a -> VarSubsts a composeVarSubsts a b = (IM.map (\bv -> applyVarSubsts a bv) b) `union` a -- |newVars varsToChange a, takes -- |a list of var ids to change, and an instance of VarsIn and returns -- |the same VarsIn a with the var ids to change replaced with new ones -- |from the newids in the state monad. newVars :: (Monad m, VarsIn a) => Set Idx -> a -> StateT IdxSet m a newVars varsToChange a = do subList <- mapM (\i -> do i' <- newidST 0; return (i, newVar i')) (Data.Set.toList varsToChange) return $ applyVarSubsts (fromDisjointList subList) a
flocc-net/flocc
v0.1/Compiler/Types/Variables.hs
apache-2.0
3,231
0
15
562
620
343
277
33
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="pt-BR"> <title>Technology detection | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Localizar</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>
0xkasun/security-tools
src/org/zaproxy/zap/extension/wappalyzer/resources/help_pt_BR/helpset_pt_BR.hs
apache-2.0
985
80
66
160
415
210
205
-1
-1
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ScopedTypeVariables #-} module Data.Container.Poly where --import Prologue hiding (Ixed, Indexed, Simple) --import Data.TypeLevel.List (In) --import Data.Typeable --import GHC.Prim --import Type.Bool import qualified Data.Container.Opts as Mods --import Data.Container.Mods (FilterMutable, filterMutable) --type family AppendLst a lst where AppendLst a '[] = '[a] -- AppendLst a (l ': ls) = l ': AppendLst a ls -------------------- --type family CmpLst (lst :: [k]) (lst' :: [k']) :: [Bool] where -- CmpLst (l ': ls) (l ': ls') = (True ': CmpLst ls ls') -- CmpLst (l ': ls) (l' ': ls') = (False ': CmpLst ls ls') -- CmpLst '[] '[] = '[] --type family LstIn (lst :: [*]) (lst' :: [*]) :: [Bool] where -- LstIn (l ': ls) lst = In l lst ': LstIn ls (Remove l lst) -- LstIn ls '[] = '[] -- LstIn '[] lst = '[] --type family Remove (a :: k) (cont :: c) :: c --type instance Remove (a :: k) ((t ': ts) :: [k]) = If (a :== t) ts (t ': Remove a ts) --type instance Remove (a :: k) '[] = '[] --type family ModsOf (inst :: k) cont :: [*] --data InstMods (inst :: k) (mods :: [Bool]) = InstMods --data InstMods2 (inst :: k) (mods :: [Bool]) (cont :: *) = InstMods2 --data InstModsX (inst :: k) (query :: [*]) (mods :: [Bool]) (cont :: *) = InstModsX --newtype Tagged t a = Tagged { fromTag :: a } deriving (Show) --tagged :: Proxy t -> a -> Tagged t a --tagged _ = Tagged --type family FillData (layout :: [*]) datas where FillData (t ': ts) datas = (GetData t datas, FillData ts datas) -- FillData '[] datas = () --type family GetData (tag :: *) datas where GetData tag (Tagged tag a, ds) = a -- GetData tag (Tagged tag' a, ds) = GetData tag ds --type family TaggedCont (tags :: [*]) a --type instance TaggedCont '[] () = () --type instance TaggedCont (t ': ts) (a,as) = (Tagged t a, TaggedCont ts as) --class Taggable tags cont where -- taggedCont :: Proxy tags -> cont -> TaggedCont tags cont --instance {-# OVERLAPPABLE #-} Taggable '[] () where taggedCont _ _ = () --instance {-# OVERLAPPABLE #-} Taggable ts as => Taggable (t ': ts) (a,as) where taggedCont _ (a,as) = (Tagged a, taggedCont (Proxy :: Proxy ts) as) --class DataFillable (layout :: [*]) datas where fillData :: Proxy layout -> datas -> FillData layout datas --instance {-# OVERLAPPABLE #-} (DataGettable t datas, DataFillable ts datas) => DataFillable (t ': ts) datas where fillData _ ds = (getData (Proxy :: Proxy t) ds, fillData (Proxy :: Proxy ts) ds) --instance {-# OVERLAPPABLE #-} DataFillable '[] datas where fillData _ _ = () --class DataGettable tag datas where getData :: Proxy tag -> datas -> GetData tag datas --instance {-# OVERLAPPABLE #-} DataGettable tag (Tagged tag a, ds) where getData _ = fromTag . fst --instance {-# OVERLAPPABLE #-} (DataGettable tag ds, GetData tag (Tagged tag' a, ds) ~ GetData tag ds) => DataGettable tag (Tagged tag' a, ds) where getData t = getData t . snd --type family MappedByTag tag a l --type instance MappedByTag t a () = () --type instance MappedByTag t a (Tagged t' a', ls) = If (t :== t') (Tagged t a , MappedByTag t a ls) -- (Tagged t' a', MappedByTag t a ls) --class MapByTag t a b l | t l -> a where mapByTag :: Proxy t -> (a -> b) -> l -> MappedByTag t b l --class MapByTag' t a b l where mapByTag' :: Proxy t -> (a -> b) -> l -> MappedByTag t b l --instance {-# OVERLAPPABLE #-} (MapByTag' t a b l, a ~ a') => MapByTag t a b (Tagged t a', l ) where mapByTag t f (Tagged a, l) = (Tagged $ f a, mapByTag' t f l) --instance {-# OVERLAPPABLE #-} (MapByTag t a b l, MappedByTag t b (Tagged t' a', l) ~ (Tagged t' a', MappedByTag t b l)) => MapByTag t a b (Tagged t' a', l ) where mapByTag t f (ta , l) = (ta , mapByTag t f l) --instance {-# OVERLAPPABLE #-} (MapByTag' t a b l, a ~ a') => MapByTag' t a b (Tagged t a', l ) where mapByTag' t f (Tagged a, l) = (Tagged $ f a, mapByTag' t f l) --instance {-# OVERLAPPABLE #-} (MapByTag' t a b l, MappedByTag t b (Tagged t' a', l) ~ (Tagged t' a', MappedByTag t b l)) => MapByTag' t a b (Tagged t' a', l ) where mapByTag' t f (ta , l) = (ta , mapByTag' t f l) --instance MapByTag' t a b () where mapByTag' _ _ _ = () --type I = InstMods2 --type I2X = InstModsX --type family UpdateQuery instMods guery where -- UpdateQuery (InstModsX inst q m cont) q'= InstModsX inst q' (LstIn (ModsOf inst cont) q') cont --rebaseSpecX :: InstModsX inst q mods cont -> InstModsX inst' q (LstIn (ModsOf inst' cont) q) cont --rebaseSpecX _ = InstModsX --polySpecX :: InstModsX inst q mods cont -> InstModsX inst q (LstIn (ModsOf inst cont') q) cont' --polySpecX _ = InstModsX ----type family Rebase mods base where Rebase (InstMods2 inst mods old) new = InstMods2 inst mods new --type family InstQuery (inst :: * -> Constraint) :: [*] --query :: InstModsX inst q mods cont -> Proxy q --query _ = Proxy --optBuilder :: a -> OptBuilderBase a --optBuilder = OptBuilder --type OptBuilderBase = OptBuilder '[] --newtype OptBuilder (opts :: [*]) a = OptBuilder a deriving (Functor) --class FuncBuilder f a | a -> f where -- buildFunc :: f -> a --class FuncTrans opts f a | a opts -> f where -- transFunc :: OptBuilder opts f -> a --instance {-# OVERLAPPABLE #-} (f ~ a, g ~ b) => FuncBuilder (f -> g) (a -> b) where buildFunc = id --instance {-# OVERLAPPABLE #-} (t ~ (f -> g), opts ~ '[]) => FuncBuilder (f -> g) (OptBuilder opts t) where buildFunc = OptBuilder --instance (opts ~ opts', f ~ f') => FuncTrans opts f (OptBuilder opts' f') where transFunc = id --instance (f ~ (Proxy opts -> a -> b)) => FuncTrans opts f (a -> b) where transFunc (OptBuilder f) = f Proxy --extendOptBuilder :: Proxy opt -> Proxy opts' -> OptBuilder opts a -> OptBuilder (opt ': (Concat opts' opts)) a --extendOptBuilder _ _ (OptBuilder a) = OptBuilder a ---------------- --type family Selected (b :: [Bool]) (lst :: [*]) :: [*] where -- Selected ('True ': b) (l ': ls) = l ': Selected b ls -- Selected ('False ': b) (l ': ls) = Selected b ls -- Selected '[] lst = '[] -- Selected s lst = '[] --data Query (q :: [*]) (m :: [Bool]) = Query --data NA = NA --data Info (idx :: *) (el :: *) (cls :: k) (cont :: *) = Info --type family InfoIdx i where InfoIdx (Info idx el cls cont) = idx --type family InfoEl i where InfoEl (Info idx el cls cont) = el --type family InfoCls i where InfoCls (Info idx el cls cont) = cls --type family InfoCont i where InfoCont (Info idx el cls cont) = cont --type RawInfo = Info NA NA --type IxedInfo idx = Info idx NA --type ElInfo el = Info NA el --type IxedElInfo idx el = Info idx el --type family ElementOf cont --type family IndexOf el cont --type family HomoIndexOf (m :: * -> *) :: * --type family ElementByIx idx cont --type family IxType idx --type IndexOf' cont = IndexOf (ElementOf cont) cont ---- === Results === --type family SelTags (info :: *) (s :: [Bool]) where SelTags (Info idx el cls cont) s = QueryData (Info idx el cls (DataStoreOf cont)) (Selected s (FilterMutable (ModsOf cls cont))) --type IxedData cls idx = If (IxedMode cls :== Single) idx [idx] --type family QueryData (info :: *) (query :: [*]) :: * where -- QueryData info '[] = () -- QueryData info (q ': qs) = (ModData q info, QueryData info qs) --type family ModData mod info --type instance ModData Mods.Ixed (Info idx el cls cont) = IxedData cls ( -- If (idx :== NA) ( -- --If (el :== NA) -- (IndexOf' cont) -- -- (IndexOf el cont) -- ) idx -- ) --type ComputeSelection (cls :: k) (cont :: *) (q :: [*]) = LstIn (ModsOf cls cont) q --type AssumeQuery i q s = QueryData (DataStoreInfo i) (FilterMutable q) ~ SelTags i s --runModsF :: ComputeSelection cls cont q ~ s => (Proxy (q :: [*])) -> (Query q s -> Info idx el cls cont -> sig) -> sig --runModsF _ f = f Query Info --runModsF' = flip runModsF --type family ContainerOf a --class HasContainer a where -- container :: Lens' a (ContainerOf a) --type family DataStoreOf a --class HasDataStore a where -- dataStore :: Lens' a (DataStoreOf a) --class HasDataStore a => IsDataStore a where -- fromDataStore :: DataStoreOf a -> a --type family InfoSelection i q where InfoSelection (Info idx el cls cont) q = ComputeSelection cls cont q --type family DataStoreInfo i where DataStoreInfo (Info idx el cls cont) = Info idx el cls (DataStoreOf cont) --type family InfoInst info q m :: Constraint where -- InfoInst (Info NA NA cls cont) q m = cls cont m q (ComputeSelection cls cont q) -- InfoInst (Info NA el cls cont) q m = cls el cont m q (ComputeSelection cls cont q) -- InfoInst (Info idx NA cls cont) q m = cls idx cont m q (ComputeSelection cls cont q) -- InfoInst (Info idx el cls cont) q m = cls idx el cont m q (ComputeSelection cls cont q) ------ --type family Ixed (op :: k) :: k where Ixed (cls q (m :: * -> *) :: * -> Constraint) = cls (AppendLst Mods.Ixed q) m -- Ixed (cls q :: (* -> *) -> * -> Constraint) = cls (AppendLst Mods.Ixed q) --type family Unchecked (op :: k) :: k where Unchecked (cls q (m :: * -> *) :: * -> Constraint) = cls (AppendLst Mods.Unchecked q) m -- Unchecked (cls q :: (* -> *) -> * -> Constraint) = cls (AppendLst Mods.Unchecked q) type family Ixed (op :: k) :: k where Ixed (op (ms :: [*]) (ps :: [*])) = op (Mods.Ixed ': ms) ps Ixed (op (ms :: [*]) (ps :: [*]) (m :: * -> *)) = op (Mods.Ixed ': ms) ps m ---- === Concatenation === --type family IxedMode (a :: k) :: IxedType --data IxedType = Multi -- | Single -- deriving (Show) ----type family ClassOf (a :: *) :: k ---------------------------------- --newtype NestedFunctor m n a = NestedFunctor { fromNestedFunctor :: m (n a)} deriving (Show) --instance (Functor m, Functor n) => Functor (NestedFunctor m n) where fmap f = NestedFunctor . (fmap $ fmap f) . fromNestedFunctor --nested :: (Functor m, Functor n) => Lens a b c d -> (c -> m (n d)) -> (a -> m (n b)) --nested l f = fromNestedFunctor . l (fmap NestedFunctor f) --data Result d r = Result d r deriving (Show, Functor) ---- Result utils --simple' = Result () --res = Result . (,()) --resM = return .: res --simpleM = return . simple' --withResData :: (d -> (out, d')) -> Result d r -> (out, Result d' r) --withResData f (Result d r) = (out, Result d' r) where -- (out, d') = f d --withResData_ :: (d -> d') -> Result d r -> Result d' r --withResData_ = flattenMod withResData --splitResData :: Result (d,ds) r -> (d, Result ds r) --splitResData = withResData id --flattenMod :: Functor f => (f ((), a) -> b -> (x, c)) -> f a -> b -> c --flattenMod f = snd .: (f . fmap ((),)) ----type Unique lst = Reverse (Unique' lst '[]) --type Unique lst = (Unique2' lst) --type family Unique' (lst :: [*]) (reg :: [*]) where -- Unique' '[] reg = reg -- Unique' (l ': ls) reg = Unique' ls (If (l `In` reg) reg (l ': reg)) --type family Unique2' (lst :: [*]) where -- Unique2' '[] = '[] -- Unique2' (l ': ls) = l ': Unique2' (Remove l ls) --uniqueProxy :: Proxy a -> Proxy (Unique a) --uniqueProxy _ = Proxy --newtype Flipped t a b = Flipped { fromFlipped :: t b a } deriving Show --instance Functor (Flipped Result r) where fmap f (Flipped (Result d r)) = Flipped (Result (f d) r) --withFlipped f = fromFlipped . f . Flipped --foo f (info :: Proxy (cls :: k)) (q :: Proxy (q :: [*])) (tc :: cont) = out where -- tc2 = runModsF' f (uniqueProxy q) tc -- tc3 = withFlipped (fmap $ taggedCont (Proxy :: Proxy (Selected (ComputeSelection cls cont q) (FilterMutable (ModsOf cls cont))) )) <$> tc2 -- out = tc3 ----bar :: OpCtx ExpandableInfo2 q m t => Proxy q -> t -> m (Result (MyResult ExpandableInfo2 q t) t) --bar f info q t = out where -- q' = filterMutable q -- cont = view container t -- tgdr = foo f info q cont -- tgdr' = (fmap . fmap) (\c -> t & container .~ c) tgdr -- out = withFlipped (fmap (fillData q')) <$> tgdr' --barTx f (cls :: Proxy (cls :: k)) (q :: Proxy (q :: [*])) (t :: t) = withFlipped (fmap (fillData (filterMutable q))) <$> nested container tgdr t where -- tgdr c = withFlipped (fmap $ taggedCont (Proxy :: Proxy (Selected (ComputeSelection cls (ContainerOf t) q) (FilterMutable (ModsOf cls (ContainerOf t)))) )) <$> f (uniqueProxy q) c --barTy f (cls :: Proxy (cls :: k)) (q :: Proxy (q :: [*])) (t :: t) = withFlipped (fmap (fillData (filterMutable q))) <$> tgdr (view container t) where -- tgdr c = withFlipped (fmap $ taggedCont (Proxy :: Proxy (Selected (ComputeSelection cls (ContainerOf t) q) (FilterMutable (ModsOf cls (ContainerOf t)))) )) <$> f (uniqueProxy q) c ----bar2z f (cls :: Proxy (cls :: k)) (q :: Proxy (q :: [*])) (t :: t) = withFlipped (fmap (fillData (filterMutable q))) <$> tgdr (view container t) where ---- tgdr c = withFlipped (fmap $ taggedCont (Proxy :: Proxy (Selected (ComputeSelection cls (ContainerOf t) q) (FilterMutable (ModsOf cls (ContainerOf t)))) )) <$> f (uniqueProxy q) c --type family AssumeRtupConv q t :: Constraint where AssumeRtupConv q t = If' (Mods.FilterMutable q :== '[]) (AsRTup t ~ (t,())) () --type family OpCtx info q m t where OpCtx (Info idx el cls) q m t = ((Functor m, -- HasContainer t, -- DataFillable -- (FilterMutable q) -- (TaggedCont -- (Selected -- (LstIn -- (ModsOf cls (ContainerOf t)) q) -- (FilterMutable -- (ModsOf cls (ContainerOf t)))) -- (QueryData -- (Info idx el cls (DataStoreOf t)) -- (Selected -- (LstIn -- (ModsOf cls (ContainerOf t)) -- (Unique q)) -- (FilterMutable -- (ModsOf -- cls (ContainerOf t)))))), -- Taggable -- (Selected -- (LstIn -- (ModsOf cls (ContainerOf t)) q) -- (FilterMutable -- (ModsOf cls (ContainerOf t)))) -- (QueryData -- (Info idx el cls (DataStoreOf t)) -- (Selected -- (LstIn -- (ModsOf cls (ContainerOf t)) -- (Unique q)) -- (FilterMutable -- (ModsOf -- cls (ContainerOf t))))), -- QueryData -- (Info idx el cls (DataStoreOf t)) -- (FilterMutable (Unique q)) -- ~ QueryData -- (Info idx el cls (DataStoreOf t)) -- (Selected -- (LstIn -- (ModsOf cls (ContainerOf t)) -- (Unique q)) -- (FilterMutable -- (ModsOf cls (ContainerOf t)))), -- QueryData -- (Info idx el cls (DataStoreOf t)) -- (FilterMutable q) -- ~ FillData -- (FilterMutable q) -- (TaggedCont -- (Selected -- (LstIn -- (ModsOf cls (ContainerOf t)) -- q) -- (FilterMutable -- (ModsOf -- cls (ContainerOf t)))) -- (QueryData -- (Info idx el cls (DataStoreOf t)) -- (Selected -- (LstIn -- (ModsOf -- cls (ContainerOf t)) -- (Unique q)) -- (FilterMutable -- (ModsOf -- cls -- (ContainerOf t))))))), -- -- manual -- Functor m, -- AssumeRtupConv q t, -- IsContainer t, -- InfoInst (Info idx el cls (ContainerOf t)) (Unique q) m, -- DataStoreOf (ContainerOf t) ~ DataStoreOf t, -- (QueryData (Info idx el cls (DataStoreOf t)) (FilterMutable q) ~ QueryData (Info idx el cls (DataStoreOf t)) (FilterMutable q))) --type family TransCheck q info info' t where -- TransCheck q (Info idx el cls) info' t = (FillData -- (FilterMutable q) -- (TaggedCont -- (Selected -- (LstIn (ModsOf cls (ContainerOf t)) q) -- (FilterMutable (ModsOf cls (ContainerOf t)))) -- (QueryData -- (Info idx el cls (DataStoreOf t)) -- (Selected -- (LstIn -- (ModsOf cls (ContainerOf t)) -- (Unique q)) -- (FilterMutable (ModsOf cls (ContainerOf t)))))) -- ~ QueryData -- (info' (DataStoreOf t)) (FilterMutable q)) ----type family Test (a :: k) where Test a = (If a :== (t1,t2)) True True ----type family Match --class IsTuple a (is :: Bool) | a -> is --instance {-# OVERLAPPABLE #-} is ~ False => IsTuple a is --instance IsTuple () True --instance IsTuple (t1,t2) True --instance IsTuple (t1,t2,t3) True --instance IsTuple (t1,t2,t3,t4) True --instance IsTuple (t1,t2,t3,t4,t5) True --instance IsTuple (t1,t2,t3,t4,t5,t6) True --instance IsTuple (t1,t2,t3,t4,t5,t6,t7) True --instance IsTuple (t1,t2,t3,t4,t5,t6,t7,t8) True --instance IsTuple (t1,t2,t3,t4,t5,t6,t7,t8,t9) True ---- FIXME [WD]: below ToTupCtx* refer to need of AssumeRtupConv function, which adds special case context when we are returning only single value from Rtuple (t,()) ---- It is not seen properly byGHC though ----type family ToTupCtx a :: Constraint where ---- ToTupCtx (t,()) = (AsRTup t ~ (t,())) ---- ToTupCtx t = () ----type family ToTupCtx2 a :: Constraint where ---- ToTupCtx2 (t1,t2) = () ---- ToTupCtx2 (t1,t2,t3) = () ---- ToTupCtx2 (t1,t2,t3,t4) = () ---- ToTupCtx2 (t1,t2,t3,t4,t5) = () ---- ToTupCtx2 (t1,t2,t3,t4,t5,t6) = () ---- ToTupCtx2 (t1,t2,t3,t4,t5,t6,t7) = () ---- ToTupCtx2 (t1,t2,t3,t4,t5,t6,t7,t8) = () ---- ToTupCtx2 (t1,t2,t3,t4,t5,t6,t7,t8,t9) = () ---- ToTupCtx2 t = (AsRTup t ~ (t,())) -- ---- Utils --type family AsTup a --type instance AsTup () = () --type instance AsTup (t1,()) = t1 --type instance AsTup (t1,(t2,())) = (t1,t2) --type instance AsTup (t1,(t2,(t3,()))) = (t1,t2,t3) --type instance AsTup (t1,(t2,(t3,(t4,())))) = (t1,t2,t3,t4) --type instance AsTup (t1,(t2,(t3,(t4,(t5,()))))) = (t1,t2,t3,t4,t5) --type instance AsTup (t1,(t2,(t3,(t4,(t5,(t6,())))))) = (t1,t2,t3,t4,t5,t6) --type instance AsTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,()))))))) = (t1,t2,t3,t4,t5,t6,t7) --type instance AsTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,(t8,())))))))) = (t1,t2,t3,t4,t5,t6,t7,t8) --type instance AsTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,(t8,(t9,()))))))))) = (t1,t2,t3,t4,t5,t6,t7,t8,t9) --type family AsRTup a where -- AsRTup () = () -- AsRTup (t1,t2) = (t1,(t2,())) -- AsRTup (t1,t2,t3) = (t1,(t2,(t3,()))) -- AsRTup (t1,t2,t3,t4) = (t1,(t2,(t3,(t4,())))) -- AsRTup (t1,t2,t3,t4,t5) = (t1,(t2,(t3,(t4,(t5,()))))) -- AsRTup (t1,t2,t3,t4,t5,t6) = (t1,(t2,(t3,(t4,(t5,(t6,())))))) -- AsRTup (t1,t2,t3,t4,t5,t6,t7) = (t1,(t2,(t3,(t4,(t5,(t6,(t7,()))))))) -- AsRTup (t1,t2,t3,t4,t5,t6,t7,t8) = (t1,(t2,(t3,(t4,(t5,(t6,(t7,(t8,())))))))) -- AsRTup (t1,t2,t3,t4,t5,t6,t7,t8,t9) = (t1,(t2,(t3,(t4,(t5,(t6,(t7,(t8,(t9,()))))))))) -- AsRTup a = (a,()) --class a ~ AsRTup (AsTup a) => ToTup a where toTup :: a -> AsTup a --instance ToTup () where toTup _ = () --instance AsRTup t1 ~ (t1,()) => ToTup (t1,()) where toTup (t1,()) = t1 --instance ToTup (t1,(t2,())) where toTup (t1,(t2,())) = (t1,t2) --instance ToTup (t1,(t2,(t3,()))) where toTup (t1,(t2,(t3,()))) = (t1,t2,t3) --instance ToTup (t1,(t2,(t3,(t4,())))) where toTup (t1,(t2,(t3,(t4,())))) = (t1,t2,t3,t4) --instance ToTup (t1,(t2,(t3,(t4,(t5,()))))) where toTup (t1,(t2,(t3,(t4,(t5,()))))) = (t1,t2,t3,t4,t5) --instance ToTup (t1,(t2,(t3,(t4,(t5,(t6,())))))) where toTup (t1,(t2,(t3,(t4,(t5,(t6,())))))) = (t1,t2,t3,t4,t5,t6) --instance ToTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,()))))))) where toTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,()))))))) = (t1,t2,t3,t4,t5,t6,t7) --instance ToTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,(t8,())))))))) where toTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,(t8,())))))))) = (t1,t2,t3,t4,t5,t6,t7,t8) --instance ToTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,(t8,(t9,()))))))))) where toTup (t1,(t2,(t3,(t4,(t5,(t6,(t7,(t8,(t9,()))))))))) = (t1,t2,t3,t4,t5,t6,t7,t8,t9) --type SimpleRes a = AsRTup a ~ (a, ()) type Simple (t :: [*] -> [*] -> k) = t '[] '[]
wdanilo/container
src/Data/Container/Poly.hs
apache-2.0
25,747
0
11
10,231
548
472
76
-1
-1
{- Copyright 2016-2017 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} -- | -- Module : Data.MultiMap -- Copyright : (c) CodeWorld Authors 2017 -- License : Apache-2.0 -- -- Maintainer : [email protected] -- -- A simple MultiMap. -- -- This differs from the one in the @multimap@ package by using -- 'Data.Sequence.Seq' for efficient insert-at-end and other improved speeds. -- -- Also only supports the operations required by CodeWorld for now. {-# LANGUAGE TupleSections #-} module Data.MultiMap (MultiMap, empty, null, insertL, insertR, toList, spanAntitone, union, keys) where import Prelude hiding (null) import qualified Data.Sequence as S import qualified Data.Map as M import qualified Data.Foldable (toList) import Data.Bifunctor import Data.Coerce newtype MultiMap k v = MM (M.Map k (S.Seq v)) deriving (Show, Eq) empty :: MultiMap k v empty = MM M.empty null :: MultiMap k v -> Bool null (MM m) = M.null m insertL :: Ord k => k -> v -> MultiMap k v -> MultiMap k v insertL k v (MM m) = MM (M.alter (Just . maybe (S.singleton v) (v S.<|)) k m) insertR :: Ord k => k -> v -> MultiMap k v -> MultiMap k v insertR k v (MM m) = MM (M.alter (Just . maybe (S.singleton v) (S.|> v)) k m) toList :: MultiMap k v -> [(k,v)] toList (MM m) = [ (k,v) | (k,vs) <- M.toList m , v <- Data.Foldable.toList vs ] -- TODO: replace with M.spanAntitone once containers is updated mapSpanAntitone :: (k -> Bool) -> M.Map k a -> (M.Map k a, M.Map k a) mapSpanAntitone p = bimap M.fromDistinctAscList M.fromDistinctAscList . span (p.fst) . M.toList spanAntitone :: (k -> Bool) -> MultiMap k v -> (MultiMap k v, MultiMap k v) spanAntitone p (MM m) = coerce (mapSpanAntitone p m) union :: Ord k => MultiMap k v -> MultiMap k v -> MultiMap k v union (MM m1) (MM m2) = MM (M.unionWith (S.><) m1 m2) keys :: MultiMap k v -> [k] keys (MM m) = M.keys m
nomeata/codeworld
codeworld-prediction/src/Data/MultiMap.hs
apache-2.0
2,412
0
13
469
716
383
333
27
1
import Data.List g n = [n, n+1, n+2,n+9,n+10,n+11,n+18,n+19,n+20] h n = map (\i -> i * 9 + n) [0..8] gp = [ [ 0.. 8], [ 9..17], [18..26], [27..35], [36..44], [45..53], [54..62], [63..71], [72..80], (g 0), (g 3), (g 6), (g 27), (g 30), (g 33), (g 54), (g 57), (g 60), (h 0), (h 1), (h 2), (h 3), (h 4), (h 5), (h 6), (h 7), (h 8)] chk g = let m = concat $ filter (\f -> length(f) > 1) $ map (\ n -> filter (\(i,v) -> v == n) g) [1..9] in m to_s' :: [Int] -> (Int,Int) -> String to_s' p (i,v) = if elem i p then '*':(show v) else ' ':(show v) to_s :: [Int] -> [(Int,Int)] -> String to_s _ [] = [] to_s p x = let d = concat $ map (to_s' p) $ take 9 x r = drop 9 x in d ++ "\n" ++ (to_s p r) ans' x = let z = zip [0..] x gs = map (\g -> filter (\(i,v) -> elem i g) z ) gp gr = map fst $ concat $ map chk gs in to_s gr z ans [] = [] ans x = let i = concat $ take 9 x r = drop 9 x in (ans' i):(ans r) pr (l:[]) = do putStr l pr (l:ls) = do putStrLn l pr ls main = do _ <- getLine c <- getContents let i = map (map read) $ map words $ lines c :: [[Int]] o = ans i pr o
a143753/AOJ
0126.hs
apache-2.0
1,168
0
16
373
899
476
423
41
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QFont.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:20 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QFont ( QqFont(..) ,QqFont_nf(..) ,qFontCacheStatistics ,qFontCleanup ,defaultFamily ,fromString ,qFontInitialize ,qFontInsertSubstitution ,qFontInsertSubstitutions ,kerning ,lastResortFamily ,lastResortFont ,rawName ,qFontRemoveSubstitution ,setBold ,setFamily ,setFixedPitch ,setItalic ,setKerning ,setOverline ,setPixelSize ,setPointSize ,setPointSizeF ,setRawMode ,setRawName ,setStretch ,setStrikeOut ,QsetStyleHint(..) ,setStyleStrategy ,setUnderline ,setWeight ,stretch ,styleStrategy ,qFontSubstitute ,qFontSubstitutes ,qFontSubstitutions ,qFont_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QFont import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqFont x1 where qFont :: x1 -> IO (QFont ()) instance QqFont (()) where qFont () = withQFontResult $ qtc_QFont foreign import ccall "qtc_QFont" qtc_QFont :: IO (Ptr (TQFont ())) instance QqFont ((QFont t1)) where qFont (x1) = withQFontResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QFont1 cobj_x1 foreign import ccall "qtc_QFont1" qtc_QFont1 :: Ptr (TQFont t1) -> IO (Ptr (TQFont ())) instance QqFont ((String)) where qFont (x1) = withQFontResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont2 cstr_x1 foreign import ccall "qtc_QFont2" qtc_QFont2 :: CWString -> IO (Ptr (TQFont ())) instance QqFont ((String, Int)) where qFont (x1, x2) = withQFontResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont3 cstr_x1 (toCInt x2) foreign import ccall "qtc_QFont3" qtc_QFont3 :: CWString -> CInt -> IO (Ptr (TQFont ())) instance QqFont ((QFont t1, QPaintDevice t2)) where qFont (x1, x2) = withQFontResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QFont4 cobj_x1 cobj_x2 foreign import ccall "qtc_QFont4" qtc_QFont4 :: Ptr (TQFont t1) -> Ptr (TQPaintDevice t2) -> IO (Ptr (TQFont ())) instance QqFont ((QFont t1, QWidget t2)) where qFont (x1, x2) = withQFontResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QFont4_widget cobj_x1 cobj_x2 foreign import ccall "qtc_QFont4_widget" qtc_QFont4_widget :: Ptr (TQFont t1) -> Ptr (TQWidget t2) -> IO (Ptr (TQFont ())) instance QqFont ((String, Int, Int)) where qFont (x1, x2, x3) = withQFontResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont5 cstr_x1 (toCInt x2) (toCInt x3) foreign import ccall "qtc_QFont5" qtc_QFont5 :: CWString -> CInt -> CInt -> IO (Ptr (TQFont ())) instance QqFont ((String, Int, Int, Bool)) where qFont (x1, x2, x3, x4) = withQFontResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont6 cstr_x1 (toCInt x2) (toCInt x3) (toCBool x4) foreign import ccall "qtc_QFont6" qtc_QFont6 :: CWString -> CInt -> CInt -> CBool -> IO (Ptr (TQFont ())) class QqFont_nf x1 where qFont_nf :: x1 -> IO (QFont ()) instance QqFont_nf (()) where qFont_nf () = withObjectRefResult $ qtc_QFont instance QqFont_nf ((QFont t1)) where qFont_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QFont1 cobj_x1 instance QqFont_nf ((String)) where qFont_nf (x1) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont2 cstr_x1 instance QqFont_nf ((String, Int)) where qFont_nf (x1, x2) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont3 cstr_x1 (toCInt x2) instance QqFont_nf ((QFont t1, QPaintDevice t2)) where qFont_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QFont4 cobj_x1 cobj_x2 instance QqFont_nf ((QFont t1, QWidget t2)) where qFont_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QFont4_widget cobj_x1 cobj_x2 instance QqFont_nf ((String, Int, Int)) where qFont_nf (x1, x2, x3) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont5 cstr_x1 (toCInt x2) (toCInt x3) instance QqFont_nf ((String, Int, Int, Bool)) where qFont_nf (x1, x2, x3, x4) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont6 cstr_x1 (toCInt x2) (toCInt x3) (toCBool x4) instance Qbold (QFont a) (()) where bold x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_bold cobj_x0 foreign import ccall "qtc_QFont_bold" qtc_QFont_bold :: Ptr (TQFont a) -> IO CBool qFontCacheStatistics :: (()) -> IO () qFontCacheStatistics () = qtc_QFont_cacheStatistics foreign import ccall "qtc_QFont_cacheStatistics" qtc_QFont_cacheStatistics :: IO () qFontCleanup :: (()) -> IO () qFontCleanup () = qtc_QFont_cleanup foreign import ccall "qtc_QFont_cleanup" qtc_QFont_cleanup :: IO () defaultFamily :: QFont a -> (()) -> IO (String) defaultFamily x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_defaultFamily cobj_x0 foreign import ccall "qtc_QFont_defaultFamily" qtc_QFont_defaultFamily :: Ptr (TQFont a) -> IO (Ptr (TQString ())) instance QexactMatch (QFont a) (()) where exactMatch x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_exactMatch cobj_x0 foreign import ccall "qtc_QFont_exactMatch" qtc_QFont_exactMatch :: Ptr (TQFont a) -> IO CBool instance Qfamily (QFont a) (()) where family x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_family cobj_x0 foreign import ccall "qtc_QFont_family" qtc_QFont_family :: Ptr (TQFont a) -> IO (Ptr (TQString ())) instance QfixedPitch (QFont a) (()) where fixedPitch x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_fixedPitch cobj_x0 foreign import ccall "qtc_QFont_fixedPitch" qtc_QFont_fixedPitch :: Ptr (TQFont a) -> IO CBool fromString :: QFont a -> ((String)) -> IO (Bool) fromString x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFont_fromString cobj_x0 cstr_x1 foreign import ccall "qtc_QFont_fromString" qtc_QFont_fromString :: Ptr (TQFont a) -> CWString -> IO CBool qFontInitialize :: (()) -> IO () qFontInitialize () = qtc_QFont_initialize foreign import ccall "qtc_QFont_initialize" qtc_QFont_initialize :: IO () qFontInsertSubstitution :: ((String, String)) -> IO () qFontInsertSubstitution (x1, x2) = withCWString x1 $ \cstr_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QFont_insertSubstitution cstr_x1 cstr_x2 foreign import ccall "qtc_QFont_insertSubstitution" qtc_QFont_insertSubstitution :: CWString -> CWString -> IO () qFontInsertSubstitutions :: ((String, [String])) -> IO () qFontInsertSubstitutions (x1, x2) = withCWString x1 $ \cstr_x1 -> withQListString x2 $ \cqlistlen_x2 cqliststr_x2 -> qtc_QFont_insertSubstitutions cstr_x1 cqlistlen_x2 cqliststr_x2 foreign import ccall "qtc_QFont_insertSubstitutions" qtc_QFont_insertSubstitutions :: CWString -> CInt -> Ptr (Ptr CWchar) -> IO () instance QisCopyOf (QFont a) ((QFont t1)) where isCopyOf x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFont_isCopyOf cobj_x0 cobj_x1 foreign import ccall "qtc_QFont_isCopyOf" qtc_QFont_isCopyOf :: Ptr (TQFont a) -> Ptr (TQFont t1) -> IO CBool instance Qitalic (QFont a) (()) where italic x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_italic cobj_x0 foreign import ccall "qtc_QFont_italic" qtc_QFont_italic :: Ptr (TQFont a) -> IO CBool kerning :: QFont a -> (()) -> IO (Bool) kerning x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_kerning cobj_x0 foreign import ccall "qtc_QFont_kerning" qtc_QFont_kerning :: Ptr (TQFont a) -> IO CBool instance Qkey (QFont a) (()) (IO (String)) where key x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_key cobj_x0 foreign import ccall "qtc_QFont_key" qtc_QFont_key :: Ptr (TQFont a) -> IO (Ptr (TQString ())) lastResortFamily :: QFont a -> (()) -> IO (String) lastResortFamily x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_lastResortFamily cobj_x0 foreign import ccall "qtc_QFont_lastResortFamily" qtc_QFont_lastResortFamily :: Ptr (TQFont a) -> IO (Ptr (TQString ())) lastResortFont :: QFont a -> (()) -> IO (String) lastResortFont x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_lastResortFont cobj_x0 foreign import ccall "qtc_QFont_lastResortFont" qtc_QFont_lastResortFont :: Ptr (TQFont a) -> IO (Ptr (TQString ())) instance Qoverline (QFont a) (()) where overline x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_overline cobj_x0 foreign import ccall "qtc_QFont_overline" qtc_QFont_overline :: Ptr (TQFont a) -> IO CBool instance QpixelSize (QFont a) (()) where pixelSize x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_pixelSize cobj_x0 foreign import ccall "qtc_QFont_pixelSize" qtc_QFont_pixelSize :: Ptr (TQFont a) -> IO CInt instance QpointSize (QFont a) (()) where pointSize x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_pointSize cobj_x0 foreign import ccall "qtc_QFont_pointSize" qtc_QFont_pointSize :: Ptr (TQFont a) -> IO CInt instance QpointSizeF (QFont a) (()) where pointSizeF x0 () = withDoubleResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_pointSizeF cobj_x0 foreign import ccall "qtc_QFont_pointSizeF" qtc_QFont_pointSizeF :: Ptr (TQFont a) -> IO CDouble instance QrawMode (QFont a) (()) where rawMode x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_rawMode cobj_x0 foreign import ccall "qtc_QFont_rawMode" qtc_QFont_rawMode :: Ptr (TQFont a) -> IO CBool rawName :: QFont a -> (()) -> IO (String) rawName x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_rawName cobj_x0 foreign import ccall "qtc_QFont_rawName" qtc_QFont_rawName :: Ptr (TQFont a) -> IO (Ptr (TQString ())) qFontRemoveSubstitution :: ((String)) -> IO () qFontRemoveSubstitution (x1) = withCWString x1 $ \cstr_x1 -> qtc_QFont_removeSubstitution cstr_x1 foreign import ccall "qtc_QFont_removeSubstitution" qtc_QFont_removeSubstitution :: CWString -> IO () instance Qresolve (QFont a) ((Int)) (IO ()) where resolve x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_resolve1 cobj_x0 (toCUInt x1) foreign import ccall "qtc_QFont_resolve1" qtc_QFont_resolve1 :: Ptr (TQFont a) -> CUInt -> IO () instance Qresolve (QFont a) (()) (IO (Int)) where resolve x0 () = withUnsignedIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_resolve cobj_x0 foreign import ccall "qtc_QFont_resolve" qtc_QFont_resolve :: Ptr (TQFont a) -> IO CUInt instance Qresolve (QFont a) ((QFont t1)) (IO (QFont ())) where resolve x0 (x1) = withQFontResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFont_resolve2 cobj_x0 cobj_x1 foreign import ccall "qtc_QFont_resolve2" qtc_QFont_resolve2 :: Ptr (TQFont a) -> Ptr (TQFont t1) -> IO (Ptr (TQFont ())) setBold :: QFont a -> ((Bool)) -> IO () setBold x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setBold cobj_x0 (toCBool x1) foreign import ccall "qtc_QFont_setBold" qtc_QFont_setBold :: Ptr (TQFont a) -> CBool -> IO () setFamily :: QFont a -> ((String)) -> IO () setFamily x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFont_setFamily cobj_x0 cstr_x1 foreign import ccall "qtc_QFont_setFamily" qtc_QFont_setFamily :: Ptr (TQFont a) -> CWString -> IO () setFixedPitch :: QFont a -> ((Bool)) -> IO () setFixedPitch x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setFixedPitch cobj_x0 (toCBool x1) foreign import ccall "qtc_QFont_setFixedPitch" qtc_QFont_setFixedPitch :: Ptr (TQFont a) -> CBool -> IO () setItalic :: QFont a -> ((Bool)) -> IO () setItalic x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setItalic cobj_x0 (toCBool x1) foreign import ccall "qtc_QFont_setItalic" qtc_QFont_setItalic :: Ptr (TQFont a) -> CBool -> IO () setKerning :: QFont a -> ((Bool)) -> IO () setKerning x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setKerning cobj_x0 (toCBool x1) foreign import ccall "qtc_QFont_setKerning" qtc_QFont_setKerning :: Ptr (TQFont a) -> CBool -> IO () setOverline :: QFont a -> ((Bool)) -> IO () setOverline x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setOverline cobj_x0 (toCBool x1) foreign import ccall "qtc_QFont_setOverline" qtc_QFont_setOverline :: Ptr (TQFont a) -> CBool -> IO () setPixelSize :: QFont a -> ((Int)) -> IO () setPixelSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setPixelSize cobj_x0 (toCInt x1) foreign import ccall "qtc_QFont_setPixelSize" qtc_QFont_setPixelSize :: Ptr (TQFont a) -> CInt -> IO () setPointSize :: QFont a -> ((Int)) -> IO () setPointSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setPointSize cobj_x0 (toCInt x1) foreign import ccall "qtc_QFont_setPointSize" qtc_QFont_setPointSize :: Ptr (TQFont a) -> CInt -> IO () setPointSizeF :: QFont a -> ((Double)) -> IO () setPointSizeF x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setPointSizeF cobj_x0 (toCDouble x1) foreign import ccall "qtc_QFont_setPointSizeF" qtc_QFont_setPointSizeF :: Ptr (TQFont a) -> CDouble -> IO () setRawMode :: QFont a -> ((Bool)) -> IO () setRawMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setRawMode cobj_x0 (toCBool x1) foreign import ccall "qtc_QFont_setRawMode" qtc_QFont_setRawMode :: Ptr (TQFont a) -> CBool -> IO () setRawName :: QFont a -> ((String)) -> IO () setRawName x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFont_setRawName cobj_x0 cstr_x1 foreign import ccall "qtc_QFont_setRawName" qtc_QFont_setRawName :: Ptr (TQFont a) -> CWString -> IO () setStretch :: QFont a -> ((Int)) -> IO () setStretch x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setStretch cobj_x0 (toCInt x1) foreign import ccall "qtc_QFont_setStretch" qtc_QFont_setStretch :: Ptr (TQFont a) -> CInt -> IO () setStrikeOut :: QFont a -> ((Bool)) -> IO () setStrikeOut x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setStrikeOut cobj_x0 (toCBool x1) foreign import ccall "qtc_QFont_setStrikeOut" qtc_QFont_setStrikeOut :: Ptr (TQFont a) -> CBool -> IO () instance QsetStyle (QFont a) ((QFontStyle)) where setStyle x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setStyle cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QFont_setStyle" qtc_QFont_setStyle :: Ptr (TQFont a) -> CLong -> IO () class QsetStyleHint x1 where setStyleHint :: QFont a -> x1 -> IO () instance QsetStyleHint ((QFontStyleHint)) where setStyleHint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setStyleHint cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QFont_setStyleHint" qtc_QFont_setStyleHint :: Ptr (TQFont a) -> CLong -> IO () instance QsetStyleHint ((QFontStyleHint, StyleStrategy)) where setStyleHint x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setStyleHint1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QFont_setStyleHint1" qtc_QFont_setStyleHint1 :: Ptr (TQFont a) -> CLong -> CLong -> IO () setStyleStrategy :: QFont a -> ((StyleStrategy)) -> IO () setStyleStrategy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setStyleStrategy cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QFont_setStyleStrategy" qtc_QFont_setStyleStrategy :: Ptr (TQFont a) -> CLong -> IO () setUnderline :: QFont a -> ((Bool)) -> IO () setUnderline x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setUnderline cobj_x0 (toCBool x1) foreign import ccall "qtc_QFont_setUnderline" qtc_QFont_setUnderline :: Ptr (TQFont a) -> CBool -> IO () setWeight :: QFont a -> ((Int)) -> IO () setWeight x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_setWeight cobj_x0 (toCInt x1) foreign import ccall "qtc_QFont_setWeight" qtc_QFont_setWeight :: Ptr (TQFont a) -> CInt -> IO () stretch :: QFont a -> (()) -> IO (Int) stretch x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_stretch cobj_x0 foreign import ccall "qtc_QFont_stretch" qtc_QFont_stretch :: Ptr (TQFont a) -> IO CInt instance QstrikeOut (QFont a) (()) where strikeOut x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_strikeOut cobj_x0 foreign import ccall "qtc_QFont_strikeOut" qtc_QFont_strikeOut :: Ptr (TQFont a) -> IO CBool instance Qstyle (QFont a) (()) (IO (QFontStyle)) where style x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_style cobj_x0 foreign import ccall "qtc_QFont_style" qtc_QFont_style :: Ptr (TQFont a) -> IO CLong instance QstyleHint (QFont a) (()) (IO (QFontStyleHint)) where styleHint x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_styleHint cobj_x0 foreign import ccall "qtc_QFont_styleHint" qtc_QFont_styleHint :: Ptr (TQFont a) -> IO CLong styleStrategy :: QFont a -> (()) -> IO (StyleStrategy) styleStrategy x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_styleStrategy cobj_x0 foreign import ccall "qtc_QFont_styleStrategy" qtc_QFont_styleStrategy :: Ptr (TQFont a) -> IO CLong qFontSubstitute :: ((String)) -> IO (String) qFontSubstitute (x1) = withStringResult $ withCWString x1 $ \cstr_x1 -> qtc_QFont_substitute cstr_x1 foreign import ccall "qtc_QFont_substitute" qtc_QFont_substitute :: CWString -> IO (Ptr (TQString ())) qFontSubstitutes :: ((String)) -> IO ([String]) qFontSubstitutes (x1) = withQListStringResult $ \arr -> withCWString x1 $ \cstr_x1 -> qtc_QFont_substitutes cstr_x1 arr foreign import ccall "qtc_QFont_substitutes" qtc_QFont_substitutes :: CWString -> Ptr (Ptr (TQString ())) -> IO CInt qFontSubstitutions :: (()) -> IO ([String]) qFontSubstitutions () = withQListStringResult $ \arr -> qtc_QFont_substitutions arr foreign import ccall "qtc_QFont_substitutions" qtc_QFont_substitutions :: Ptr (Ptr (TQString ())) -> IO CInt instance QtoString (QFont a) (()) where toString x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_toString cobj_x0 foreign import ccall "qtc_QFont_toString" qtc_QFont_toString :: Ptr (TQFont a) -> IO (Ptr (TQString ())) instance Qunderline (QFont a) (()) where underline x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_underline cobj_x0 foreign import ccall "qtc_QFont_underline" qtc_QFont_underline :: Ptr (TQFont a) -> IO CBool instance Qweight (QFont a) (()) where weight x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_weight cobj_x0 foreign import ccall "qtc_QFont_weight" qtc_QFont_weight :: Ptr (TQFont a) -> IO CInt qFont_delete :: QFont a -> IO () qFont_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QFont_delete cobj_x0 foreign import ccall "qtc_QFont_delete" qtc_QFont_delete :: Ptr (TQFont a) -> IO ()
uduki/hsQt
Qtc/Gui/QFont.hs
bsd-2-clause
19,540
0
15
3,506
6,821
3,502
3,319
-1
-1
module Blinker where import CLaSH.Prelude {-# ANN topEntity (defTop { t_name = "blinker" , t_inputs = ["KEY1"] , t_outputs = ["LED"] , t_extraIn = [ ("CLOCK_50", 1) , ("KEY0" , 1) ] , t_clocks = [ altpll "altpll50" "CLOCK_50(0)" "not KEY0(0)" ] }) #-} topEntity :: Signal Bit -> Signal (BitVector 8) topEntity key1 = leds where key1R = isRising 1 key1 leds = mealy blinkerT (1,False,0) key1R blinkerT (leds,mode,cntr) key1R = ((leds',mode',cntr'),leds) where -- clock frequency = 50e6 (50 MHz) -- led update rate = 333e-3 (every 333ms) cnt_max = 16650000 -- 50e6 * 333e-3 cntr' | cntr == cnt_max = 0 | otherwise = cntr + 1 mode' | key1R = not mode | otherwise = mode leds' | cntr == 0 = if mode then complement leds else rotateL leds 1 | otherwise = leds
ggreif/clash-compiler
examples/Blinker.hs
bsd-2-clause
948
0
10
331
207
109
98
-1
-1
module Main ( main ) where import qualified Iron.Executables.Ironc main :: IO () main = Iron.Executables.Ironc.main
iron-codegen/iron
executables/ironc/Main.hs
bsd-3-clause
122
0
6
22
35
22
13
5
1
{- | Allow monad transformers to be run/eval/exec in a section of conduit rather then needing to run across the whole conduit. The circumvents many of the problems with breaking the monad transformer laws. Read more about when the monad transformer laws are broken: <https://github.com/snoyberg/conduit/wiki/Dealing-with-monad-transformers> This method has a considerable number of advantages over the other two recommended methods. * Run the monad transformer outisde of the conduit * Use a mutable varible inside a readerT to retain side effects. This functionality has existed for awhile in the pipes ecosystem and my recent improvement to the Pipes.Lift module has allowed it to almost mechanically translated for conduit. -} module Data.Conduit.Lift ( -- * ErrorT errorC, runErrorC, catchError, -- liftCatchError, -- * MaybeT maybeC, runMaybeC, -- * ReaderT readerC, runReaderC, -- * StateT stateC, runStateC, evalStateC, execStateC, -- * WriterT -- $writert writerC, runWriterC, execWriterC, -- * RWST rwsC, runRWSC, evalRWSC, execRWSC, distribute ) where import Data.Conduit import Control.Monad.Morph (hoist, lift, MFunctor(..), ) import Control.Monad.Trans.Class (MonadTrans(..)) import Data.Monoid (Monoid(..)) import qualified Control.Monad.Trans.Error as E import qualified Control.Monad.Trans.Maybe as M import qualified Control.Monad.Trans.Reader as R import qualified Control.Monad.Trans.State.Strict as S import qualified Control.Monad.Trans.Writer.Strict as W import qualified Control.Monad.Trans.RWS.Strict as RWS catAwaitLifted :: (Monad (t (ConduitM o1 o m)), Monad m, MonadTrans t) => ConduitM i o1 (t (ConduitM o1 o m)) () catAwaitLifted = go where go = do x <- lift . lift $ await case x of Nothing -> return () Just x2 -> do yield x2 go catYieldLifted :: (Monad (t (ConduitM i o1 m)), Monad m, MonadTrans t) => ConduitM o1 o (t (ConduitM i o1 m)) () catYieldLifted = go where go = do x <- await case x of Nothing -> return () Just x2 -> do lift . lift $ yield x2 go distribute :: (Monad (t (ConduitM b o m)), Monad m, Monad (t m), MonadTrans t, MFunctor t) => ConduitM b o (t m) () -> t (ConduitM b o m) () distribute p = catAwaitLifted =$= hoist (hoist lift) p $$ catYieldLifted -- | Run 'E.ErrorT' in the base monad errorC :: (Monad m, Monad (t (E.ErrorT e m)), MonadTrans t, E.Error e, MFunctor t) => t m (Either e b) -> t (E.ErrorT e m) b errorC p = do x <- hoist lift p lift $ E.ErrorT (return x) -- | Run 'E.ErrorT' in the base monad runErrorC :: (Monad m, E.Error e) => ConduitM b o (E.ErrorT e m) () -> ConduitM b o m (Either e ()) runErrorC = E.runErrorT . distribute {-# INLINABLE runErrorC #-} -- | Catch an error in the base monad catchError :: (Monad m, E.Error e) => ConduitM i o (E.ErrorT e m) () -> (e -> ConduitM i o (E.ErrorT e m) ()) -> ConduitM i o (E.ErrorT e m) () catchError e h = errorC $ E.runErrorT $ E.catchError (distribute e) (distribute . h) {-# INLINABLE catchError #-} -- | Wrap the base monad in 'M.MaybeT' maybeC :: (Monad m, Monad (t (M.MaybeT m)), MonadTrans t, MFunctor t) => t m (Maybe b) -> t (M.MaybeT m) b maybeC p = do x <- hoist lift p lift $ M.MaybeT (return x) {-# INLINABLE maybeC #-} -- | Run 'M.MaybeT' in the base monad runMaybeC :: Monad m => ConduitM b o (M.MaybeT m) () -> ConduitM b o m (Maybe ()) runMaybeC p = M.runMaybeT $ distribute p {-# INLINABLE runMaybeC #-} -- | Wrap the base monad in 'R.ReaderT' readerC :: (Monad m, Monad (t1 (R.ReaderT t m)), MonadTrans t1, MFunctor t1) => (t -> t1 m b) -> t1 (R.ReaderT t m) b readerC k = do i <- lift R.ask hoist lift (k i) {-# INLINABLE readerC #-} -- | Run 'R.ReaderT' in the base monad runReaderC :: Monad m => r -> ConduitM b o (R.ReaderT r m) () -> ConduitM b o m () runReaderC r p = (`R.runReaderT` r) $ distribute p {-# INLINABLE runReaderC #-} -- | Wrap the base monad in 'S.StateT' stateC :: (Monad m, Monad (t1 (S.StateT t m)), MonadTrans t1, MFunctor t1) => (t -> t1 m (b, t)) -> t1 (S.StateT t m) b stateC k = do s <- lift S.get (r, s') <- hoist lift (k s) lift (S.put s') return r {-# INLINABLE stateC #-} -- | Run 'S.StateT' in the base monad runStateC :: Monad m => s -> ConduitM b o (S.StateT s m) () -> ConduitM b o m ((), s) runStateC s p = (`S.runStateT` s) $ distribute p {-# INLINABLE runStateC #-} -- | Evaluate 'S.StateT' in the base monad evalStateC :: Monad m => b -> ConduitM b1 o (S.StateT b m) () -> ConduitM b1 o m () evalStateC s p = fmap fst $ runStateC s p {-# INLINABLE evalStateC #-} -- | Execute 'S.StateT' in the base monad execStateC :: Monad m => b -> ConduitM b1 o (S.StateT b m) () -> ConduitM b1 o m b execStateC s p = fmap snd $ runStateC s p {-# INLINABLE execStateC #-} -- | Wrap the base monad in 'W.WriterT' writerC :: (Monad m, Monad (t (W.WriterT w m)), MonadTrans t, Monoid w, MFunctor t) => t m (b, w) -> t (W.WriterT w m) b writerC p = do (r, w) <- hoist lift p lift $ W.tell w return r {-# INLINABLE writerC #-} -- | Run 'W.WriterT' in the base monad runWriterC :: (Monad m, Monoid w) => ConduitM b o (W.WriterT w m) () -> ConduitM b o m ((), w) runWriterC p = W.runWriterT $ distribute p {-# INLINABLE runWriterC #-} -- | Execute 'W.WriterT' in the base monad execWriterC :: (Monad m, Monoid b) => ConduitM b1 o (W.WriterT b m) () -> ConduitM b1 o m b execWriterC p = fmap snd $ runWriterC p {-# INLINABLE execWriterC #-} -- | Wrap the base monad in 'RWS.RWST' rwsC :: (Monad m, Monad (t1 (RWS.RWST t w t2 m)), MonadTrans t1, Monoid w, MFunctor t1) => (t -> t2 -> t1 m (b, t2, w)) -> t1 (RWS.RWST t w t2 m) b rwsC k = do i <- lift RWS.ask s <- lift RWS.get (r, s', w) <- hoist lift (k i s) lift $ do RWS.put s' RWS.tell w return r {-# INLINABLE rwsC #-} -- | Run 'RWS.RWST' in the base monad runRWSC :: (Monad m, Monoid w) => r -> s -> ConduitM b o (RWS.RWST r w s m) () -> ConduitM b o m ((), s, w) runRWSC i s p = (\b -> RWS.runRWST b i s) $ distribute p {-# INLINABLE runRWSC #-} -- | Evaluate 'RWS.RWST' in the base monad evalRWSC :: (Monad m, Monoid t1) => r -> t -> ConduitM b o (RWS.RWST r t1 t m) () -> ConduitM b o m ((), t1) evalRWSC i s p = fmap f $ runRWSC i s p where f x = let (r, _, w) = x in (r, w) {-# INLINABLE evalRWSC #-} -- | Execute 'RWS.RWST' in the base monad execRWSC :: (Monad m, Monoid t1) => r -> t -> ConduitM b o (RWS.RWST r t1 t m) () -> ConduitM b o m (t, t1) execRWSC i s p = fmap f $ runRWSC i s p where f x = let (_, s2, w2) = x in (s2, w2) {-# INLINABLE execRWSC #-}
Davorak/conduit-lift
src/Data/Conduit/Lift.hs
bsd-3-clause
7,058
0
15
1,915
2,571
1,333
1,238
172
2
{-# LANGUAGE ForeignFunctionInterface #-} module Send ( bsSend , rawSend ) where import Control.Monad (when) import Data.ByteString.Internal import Foreign.C.Error (eAGAIN, getErrno, throwErrno) import Foreign.C.Types import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr (Ptr, plusPtr, castPtr) import GHC.Conc (threadWaitWrite) import Network.Socket (Socket(..)) import qualified Network.Socket.ByteString as SB (sendAll) import System.Posix.Types (Fd(..)) import Types ---------------------------------------------------------------- bsSend :: Socket -> ByteString -> Sender bsSend = SB.sendAll ---------------------------------------------------------------- rawSend :: Socket -> ByteString -> Sender rawSend sock bs = withForeignPtr fptr $ \ptr -> do let buf = castPtr (ptr `plusPtr` off) sendloop s buf siz where MkSocket s _ _ _ _ = sock PS fptr off len = bs siz = fromIntegral len sendloop :: CInt -> Ptr CChar -> CSize -> IO () sendloop s buf len = do bytes <- c_send s buf len 0 if bytes == -1 then do errno <- getErrno if errno == eAGAIN then do threadWaitWrite (Fd s) sendloop s buf len else throwErrno "sendloop" else do let sent = fromIntegral bytes when (sent /= len) $ do let left = len - sent ptr = buf `plusPtr` fromIntegral bytes sendloop s ptr left foreign import ccall unsafe "send" c_send :: CInt -> Ptr a -> CSize -> CInt -> IO CInt
kazu-yamamoto/witty
src/Send.hs
bsd-3-clause
1,539
0
17
379
481
256
225
41
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Text.RE.LineNo where newtype LineNo = ZeroBasedLineNo { getZeroBasedLineNo :: Int } deriving (Show,Enum) firstLine :: LineNo firstLine = ZeroBasedLineNo 0 getLineNo :: LineNo -> Int getLineNo = (+1) . getZeroBasedLineNo lineNo :: Int -> LineNo lineNo = ZeroBasedLineNo . (\x->x-1)
cdornan/idiot
Text/RE/LineNo.hs
bsd-3-clause
345
0
8
58
97
58
39
11
1
module ExceptionLang.Parser ( expression , program , parseProgram ) where import Control.Monad (void) import Data.Maybe (fromMaybe) import ExceptionLang.Data import Text.Megaparsec import Text.Megaparsec.Expr import qualified Text.Megaparsec.Lexer as L import Text.Megaparsec.String parseProgram :: String -> Try Program parseProgram input = case runParser program "Program Parser" input of Left err -> Left $ show err Right p -> Right p spaceConsumer :: Parser () spaceConsumer = L.space (void spaceChar) lineCmnt blockCmnt where lineCmnt = L.skipLineComment "//" blockCmnt = L.skipBlockComment "/*" "*/" symbol = L.symbol spaceConsumer parens = between (symbol "(") (symbol ")") minus = symbol "-" equal = symbol "=" comma = symbol "," lexeme :: Parser a -> Parser a lexeme = L.lexeme spaceConsumer keyWord :: String -> Parser () keyWord w = string w *> notFollowedBy alphaNumChar *> spaceConsumer reservedWords :: [String] reservedWords = [ "let", "in", "if", "then", "else", "zero?", "minus" , "equal?", "greater?", "less?", "proc", "letrec" , "try", "catch", "raise" ] binOpsMap :: [(String, BinOp)] binOpsMap = [ ("+", Add), ("-", Sub), ("*", Mul), ("/", Div), ("equal?", Eq) , ("greater?", Gt), ("less?", Le) ] binOp :: Parser BinOp binOp = do opStr <- foldl1 (<|>) (fmap (try . symbol . fst) binOpsMap) return $ fromMaybe (error ("Unknown operator '" `mappend` opStr `mappend` "'")) (lookup opStr binOpsMap) unaryOpsMap :: [(String, UnaryOp)] unaryOpsMap = [ ("minus", Minus), ("zero?", IsZero) ] unaryOp :: Parser UnaryOp unaryOp = do opStr <- foldl1 (<|>) (fmap (try . symbol . fst) unaryOpsMap) return $ fromMaybe (error ("Unknown operator '" `mappend` opStr `mappend` "'")) (lookup opStr unaryOpsMap) -- | Identifier ::= String (without reserved words) identifier :: Parser String identifier = lexeme (p >>= check) where p = (:) <$> letterChar <*> many alphaNumChar check x = if x `elem` reservedWords then fail $ concat ["keyword ", show x, " cannot be an identifier"] else return x integer :: Parser Integer integer = lexeme L.integer signedInteger :: Parser Integer signedInteger = L.signed spaceConsumer integer -- expressionPair ::= (Expression, Expression) expressionPair :: Parser (Expression, Expression) expressionPair = parens $ do expr1 <- expression comma expr2 <- expression return (expr1, expr2) -- | ConstExpr ::= Number constExpr :: Parser Expression constExpr = ConstExpr . ExprNum <$> signedInteger -- | BinOpExpr ::= BinOp (Expression, Expression) binOpExpr :: Parser Expression binOpExpr = do op <- binOp exprPair <- expressionPair return $ uncurry (BinOpExpr op) exprPair -- | UnaryOpExpr ::= UnaryOp (Expression) unaryOpExpr :: Parser Expression unaryOpExpr = do op <- unaryOp expr <- parens expression return $ UnaryOpExpr op expr -- | IfExpr ::= if Expression then Expression ifExpr :: Parser Expression ifExpr = do keyWord "if" ifE <- expression keyWord "then" thenE <- expression keyWord "else" elseE <- expression return $ IfExpr ifE thenE elseE -- | VarExpr ::= Identifier varExpr :: Parser Expression varExpr = VarExpr <$> identifier -- | LetExpr ::= let {Identifier = Expression}* in Expression letExpr :: Parser Expression letExpr = letFamilyExpr "let" LetExpr letFamilyExpr :: String -> ([(String, Expression)] -> Expression -> Expression) -> Parser Expression letFamilyExpr letType builder = do keyWord letType bindings <- many binding keyWord "in" body <- expression return $ builder bindings body where binding = try $ do var <- identifier equal val <- expression return (var, val) -- | LetrecExpr ::= letrec {Identifier (Identifier) = Expression} in Expression letRecExpr :: Parser Expression letRecExpr = do keyWord "letrec" procBindings <- many procBinding keyWord "in" recBody <- expression return $ LetRecExpr procBindings recBody where procBinding = try $ do procName <- identifier params <- parens (sepBy identifier comma) equal procBody <- expression return (procName, params, procBody) -- | ManyExprs ::= <empty> -- ::= Many1Exprs manyExprs :: Parser [Expression] manyExprs = sepBy expression comma -- | Many1Exprs ::= Expression -- ::= Expression , Many1Exprs many1Exprs :: Parser [Expression] many1Exprs = sepBy1 expression comma -- | ProcExpr ::= proc ({Identifier}*) Expression procExpr :: Parser Expression procExpr = do keyWord "proc" params <- parens . many $ identifier body <- expression return $ ProcExpr params body -- | CallExpr ::= (Expression {Expression}*) callExpr :: Parser Expression callExpr = parens $ do rator <- expression rand <- many expression return $ CallExpr rator rand -- | TryExpr ::= try Expression catch (Identifier) Expression tryExpr :: Parser Expression tryExpr = do keyWord "try" body <- expression keyWord "catch" exception <- parens identifier handler <- expression return $ TryExpr body exception handler -- | RaiseExpr ::= raise Expression raiseExpr :: Parser Expression raiseExpr = do keyWord "raise" RaiseExpr <$> expression -- | Expression ::= ConstExpr -- ::= BinOpExpr -- ::= UnaryOpExpr -- ::= IfExpr -- ::= VarExpr -- ::= LetExpr -- ::= ProcExpr -- ::= CallExpr -- ::= TryExpr -- ::= LetRecExpr -- ::= RaiseExpr expression :: Parser Expression expression = foldl1 (<|>) (fmap try expressionList) where expressionList = [ constExpr , binOpExpr , unaryOpExpr , ifExpr , varExpr , letExpr , procExpr , callExpr , letRecExpr , tryExpr , raiseExpr ] program :: Parser Program program = do spaceConsumer expr <- expression eof return $ Prog expr
li-zhirui/EoplLangs
src/ExceptionLang/Parser.hs
bsd-3-clause
6,098
0
13
1,477
1,639
855
784
168
2
{-# LANGUAGE OverloadedStrings #-} -- | -- Module : Network.TLS.Handshake.Signature -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : unknown -- module Network.TLS.Handshake.Signature ( certificateVerifyCreate , certificateVerifyCheck , digitallySignDHParams , digitallySignECDHParams , digitallySignDHParamsVerify , digitallySignECDHParamsVerify ) where import Network.TLS.Crypto import Network.TLS.Context.Internal import Network.TLS.Struct import Network.TLS.Packet (generateCertificateVerify_SSL, encodeSignedDHParams, encodeSignedECDHParams) import Network.TLS.Parameters (supportedHashSignatures) import Network.TLS.State import Network.TLS.Handshake.State import Network.TLS.Handshake.Key import Network.TLS.Util import Control.Applicative import Control.Monad.State certificateVerifyCheck :: Context -> Version -> Maybe HashAndSignatureAlgorithm -> Bytes -> DigitallySigned -> IO Bool certificateVerifyCheck ctx usedVersion malg msgs dsig = prepareCertificateVerifySignatureData ctx usedVersion malg msgs >>= signatureVerifyWithHashDescr ctx SignatureRSA dsig certificateVerifyCreate :: Context -> Version -> Maybe HashAndSignatureAlgorithm -> Bytes -> IO DigitallySigned certificateVerifyCreate ctx usedVersion malg msgs = prepareCertificateVerifySignatureData ctx usedVersion malg msgs >>= signatureCreate ctx malg getHashAndASN1 :: MonadIO m => (HashAlgorithm, SignatureAlgorithm) -> m Hash getHashAndASN1 hashSig = case hashSig of (HashSHA1, SignatureRSA) -> return SHA1 (HashSHA224, SignatureRSA) -> return SHA224 (HashSHA256, SignatureRSA) -> return SHA256 (HashSHA384, SignatureRSA) -> return SHA384 (HashSHA512, SignatureRSA) -> return SHA512 _ -> throwCore $ Error_Misc "unsupported hash/sig algorithm" type CertVerifyData = (Hash, Bytes) prepareCertificateVerifySignatureData :: Context -> Version -> Maybe HashAndSignatureAlgorithm -> Bytes -> IO CertVerifyData prepareCertificateVerifySignatureData ctx usedVersion malg msgs | usedVersion == SSL3 = do Just masterSecret <- usingHState ctx $ gets hstMasterSecret return (SHA1_MD5, generateCertificateVerify_SSL masterSecret (hashUpdate (hashInit SHA1_MD5) msgs)) | usedVersion == TLS10 || usedVersion == TLS11 = do return (SHA1_MD5, hashFinal $ hashUpdate (hashInit SHA1_MD5) msgs) | otherwise = do let Just hashSig = malg hsh <- getHashAndASN1 hashSig return (hsh, msgs) signatureHashData :: SignatureAlgorithm -> Maybe HashAlgorithm -> Hash signatureHashData SignatureRSA mhash = case mhash of Just HashSHA512 -> SHA512 Just HashSHA256 -> SHA256 Just HashSHA1 -> SHA1 Nothing -> SHA1_MD5 _ -> error ("unimplemented signature hash type") signatureHashData SignatureDSS mhash = case mhash of Nothing -> SHA1 Just HashSHA1 -> SHA1 Just _ -> error "invalid DSA hash choice, only SHA1 allowed" signatureHashData sig _ = error ("unimplemented signature type: " ++ show sig) --signatureCreate :: Context -> Maybe HashAndSignatureAlgorithm -> HashDescr -> Bytes -> IO DigitallySigned signatureCreate :: Context -> Maybe HashAndSignatureAlgorithm -> CertVerifyData -> IO DigitallySigned signatureCreate ctx malg (hashAlg, toSign) = do cc <- usingState_ ctx $ isClientContext let signData = case (malg, hashAlg) of (Nothing, SHA1_MD5) -> hashFinal $ hashUpdate (hashInit SHA1_MD5) toSign _ -> toSign DigitallySigned malg <$> signRSA ctx cc hashAlg signData signatureVerify :: Context -> DigitallySigned -> SignatureAlgorithm -> Bytes -> IO Bool signatureVerify ctx digSig@(DigitallySigned hashSigAlg _) sigAlgExpected toVerifyData = do usedVersion <- usingState_ ctx getVersion -- in the case of TLS < 1.2, RSA signing, then the data need to be hashed first, as -- the SHA_MD5 algorithm expect an already digested data let (hashDescr, toVerify) = case (usedVersion, hashSigAlg) of (TLS12, Nothing) -> error "expecting hash and signature algorithm in a TLS12 digitally signed structure" (TLS12, Just (h,s)) | s == sigAlgExpected -> (signatureHashData sigAlgExpected (Just h), toVerifyData) | otherwise -> error "expecting different signature algorithm" (_, Nothing) -> case signatureHashData sigAlgExpected Nothing of SHA1_MD5 -> (SHA1_MD5, hashFinal $ hashUpdate (hashInit SHA1_MD5) toVerifyData) alg -> (alg, toVerifyData) (_, Just _) -> error "not expecting hash and signature algorithm in a < TLS12 digitially signed structure" signatureVerifyWithHashDescr ctx sigAlgExpected digSig (hashDescr, toVerify) signatureVerifyWithHashDescr :: Context -> SignatureAlgorithm -> DigitallySigned -> CertVerifyData -> IO Bool signatureVerifyWithHashDescr ctx sigAlgExpected (DigitallySigned _ bs) (hashDescr, toVerify) = do cc <- usingState_ ctx $ isClientContext case sigAlgExpected of SignatureRSA -> verifyRSA ctx cc hashDescr toVerify bs SignatureDSS -> verifyRSA ctx cc hashDescr toVerify bs _ -> error "not implemented yet" digitallySignParams :: Context -> Bytes -> SignatureAlgorithm -> IO DigitallySigned digitallySignParams ctx signatureData sigAlg = do usedVersion <- usingState_ ctx getVersion let mhash = case usedVersion of TLS12 -> case filter ((==) sigAlg . snd) $ supportedHashSignatures $ ctxSupported ctx of [] -> error ("no hash signature for " ++ show sigAlg) x:_ -> Just (fst x) _ -> Nothing let hashDescr = signatureHashData sigAlg mhash signatureCreate ctx (fmap (\h -> (h, sigAlg)) mhash) (hashDescr, signatureData) digitallySignDHParams :: Context -> ServerDHParams -> SignatureAlgorithm -> IO DigitallySigned digitallySignDHParams ctx serverParams sigAlg = do dhParamsData <- withClientAndServerRandom ctx $ encodeSignedDHParams serverParams digitallySignParams ctx dhParamsData sigAlg digitallySignECDHParams :: Context -> ServerECDHParams -> SignatureAlgorithm -> IO DigitallySigned digitallySignECDHParams ctx serverParams sigAlg = do ecdhParamsData <- withClientAndServerRandom ctx $ encodeSignedECDHParams serverParams digitallySignParams ctx ecdhParamsData sigAlg digitallySignDHParamsVerify :: Context -> ServerDHParams -> SignatureAlgorithm -> DigitallySigned -> IO Bool digitallySignDHParamsVerify ctx dhparams sigAlg signature = do expectedData <- withClientAndServerRandom ctx $ encodeSignedDHParams dhparams signatureVerify ctx signature sigAlg expectedData digitallySignECDHParamsVerify :: Context -> ServerECDHParams -> SignatureAlgorithm -> DigitallySigned -> IO Bool digitallySignECDHParamsVerify ctx dhparams sigAlg signature = do expectedData <- withClientAndServerRandom ctx $ encodeSignedECDHParams dhparams signatureVerify ctx signature sigAlg expectedData withClientAndServerRandom :: Context -> (ClientRandom -> ServerRandom -> b) -> IO b withClientAndServerRandom ctx f = do (cran, sran) <- usingHState ctx $ (,) <$> gets hstClientRandom <*> (fromJust "withClientAndServer : server random" <$> gets hstServerRandom) return $ f cran sran
AaronFriel/hs-tls
core/Network/TLS/Handshake/Signature.hs
bsd-3-clause
8,536
0
20
2,551
1,758
881
877
152
7
{-# LANGUAGE OverloadedStrings #-} module JKF.Parser.Kif.Internal where import Control.Applicative ((<$>), (<*>)) import Data.Char (digitToInt) import Data.Maybe (isNothing) import Data.Text (Text) import JKF.Type import Text.Parsec import Text.Parsec.Char import Text.Parsec.String import Text.ParserCombinators.Parsec.Language import qualified Text.ParserCombinators.Parsec.Token as P kifu :: Parser JKF kifu = do many skipLine comment_ <- many $ try comment headers1 <- many $ try header movemoves <- many $ try sashite let moves = map (\mm -> MoveFormat Nothing (Just mm) Nothing Nothing Nothing) movemoves return $ JKF (Header "sente" "gote" "1/1 00:00" "1/1 10:00" "hirate") Nothing moves -- hs <- try headers -- kls <- try kifuLines -- return $ Kifu hs kls comment :: Parser String comment = do char '*' many space c <- many $ noneOf "\r\n" endOfLine return c -- header :: Parser String header = do k <- many $ noneOf "\r\n:" string ":" v <- many $ noneOf "\r\n:" endOfLine return (k, v) -- initialBoard = do -- c <- many $ noneOf "\r\n" -- endOfLine -- return c -- splitLine = return $ many $ string "手数----指手--" "-------消費時間--" sashite :: Parser MoveMoveFormat sashite = do spaces n <- many digit spaces toP <- toPos koma <- kanjiKoma nari <- (string "成" >> return (Just True)) <|> (string "" >> return (Just False)) spaces fromP <- optionMaybe fromPos endOfLine let color = if read n `mod` 2 == 1 then Black else White dou = if isNothing toP then Just True else Just False return $ MoveMoveFormat color fromP toP koma dou nari Nothing Nothing skipLine :: Parser String skipLine = do char '#' v <- many $ noneOf "\r\n" endOfLine return v toPos :: Parser (Maybe PlaceFormat) toPos = (do string "同" skipMany (string " ") return Nothing) <|> do x <- zenkakuNum y <- kanjiNum return $ Just $ PlaceFormat x y fromPos :: Parser PlaceFormat fromPos = do char '(' x <- digitToInt <$> digit y <- digitToInt <$> digit char ')' return $ PlaceFormat x y zenkakuNum = (string "1" >> return 1) <|> (string "2" >> return 2) <|> (string "3" >> return 3) <|> (string "4" >> return 4) <|> (string "5" >> return 5) <|> (string "6" >> return 6) <|> (string "7" >> return 7) <|> (string "8" >> return 8) <|> (string "9" >> return 9) kanjiNum = (string "一" >> return 1) <|> (string "二" >> return 2) <|> (string "三" >> return 3) <|> (string "四" >> return 4) <|> (string "五" >> return 5) <|> (string "六" >> return 6) <|> (string "七" >> return 7) <|> (string "八" >> return 8) <|> (string "九" >> return 9) kanjiKoma = (string "歩" >> return FU) <|> (string "香" >> return KY) <|> (string "桂" >> return KE) <|> (string "銀" >> return GI) <|> (string "金" >> return KI) <|> (string "角" >> return KA) <|> (string "飛" >> return HI) <|> (string "玉" >> return OU) <|> (string "王" >> return OU) <|> (string "と" >> return TO) <|> (string "杏" >> return NY) <|> (string "圭" >> return NK) <|> (string "全" >> return NG) <|> (string "竜" >> return RY) <|> (string "龍" >> return RY)
suzuki-shin/jkf-hs
src/JKF/Parser/Kif/Internal.hs
bsd-3-clause
3,457
0
21
945
1,263
609
654
108
3
{-# OPTIONS_GHC -F -pgmF htfpp #-} {- haskell-librsync - an attempt to write a Haskell library to read/write /apply rdiff patches etc. Presently lives inside the source code for rdifffs and only implements the minimum necessary to support that program: namely parsing and applying rdiff patches. This file: tests for Rdiff.hs Copyright © 2016 Jonathan Dowland See "LICENSE" for copyright information. -} module Main where import Test.Framework import Data.Either -- isLeft, isRight import Data.Either.Utils -- fromRight (missingh) import Data.Char -- chr import Text.ParserCombinators.Parsec -- parse import Rdiff testWrap x = assertBool $ (isRight . p) x test_goodpatch_empty = testWrap $ magic ++ "\0" test_goodpatch_short = testWrap $ magic ++ (chr 0x02):"hi\0" test_goodpatch_longer = testWrap $ magic ++ (chr 0x41):"\5hello\0" test_goodpatch_dunno = testWrap $ magic ++ (chr 0x45):"\0\0\0" badWrap x = assertBool $ (isLeft . p) x test_badpatch_nomagic = badWrap $ "no magic\0" test_badpatch_nonull = badWrap $ magic test_badpatch_command = badWrap $ magic ++ "\256not a command\0" test_badpatch_missing_arg1 = badWrap $ magic ++ [chr 0x41, '\0'] test_badpatch_missing_arg2 = badWrap $ magic ++ [chr 0x45, '\0'] test_badpatch_missing_arg3 = badWrap $ magic ++ (chr 0x45):"\0\0" test_badpatch_missing_data = badWrap $ magic ++ (chr 0x41):"\6\0" prop_literal str = [LiteralCommand str] == fromRight (p $ magic ++ [chr 0x41, chr $ length str] ++ str ++ "\0") p x = parse rdiffPatch "" x -- real test data! patch = "rs\STX6A\GSThu Feb 4 18:18:18 GMT 2010\n\NUL" my_output = "Thu Feb 4 18:18:18 GMT 2010\n" prop_realpatch = applyPatch (fromRight $ p patch) "" == my_output main = htfMain htf_thisModulesTests
jmtd/rdifffs
Test.hs
bsd-3-clause
1,784
0
13
327
401
216
185
28
1
{-+ Type environments. For efficiency, a type environment is represented as a pair of an environment and the set of (nongeneric) type variables that occur free in the environment. The type checker needs this information when it generalizes a type, and traversing the whole environment every time is too costly. -} module TiTEnv(TEnv,extenv1,extenv,empty,TiTEnv.lookup,domain,range) where import HsIdent(HsIdentI) import TiTypes(Scheme,Types(..)) import TiNames(TypeVar) import qualified TiEnvFM as E import Set60204 #if __GLASGOW_HASKELL__ >= 604 import qualified Data.Set as S (Set) #else import qualified Sets as S (Set) #endif type TEnv' i = E.Env (HsIdentI i) (Scheme i) -- types of value identifiers data TEnv i = TEnv (TEnv' i) (S.Set i) extenv1 x t (TEnv env vs) = TEnv (E.extenv1 x t env) (vs `unionS` fromListS (tv t)) extenv bs1 (TEnv bs2 vs) = TEnv (E.extenv bs1 bs2) (vs `unionS` fromListS (tv (map snd bs1))) empty = TEnv E.empty emptyS lookup (TEnv env _) x = E.lookup env x domain (TEnv env _) = E.domain env range (TEnv env _) = E.range env --instance Functor TEnv where ... instance TypeVar i => Types i (TEnv i) where tv (TEnv env vs) = elemsS vs -- tmap -- of questionable use...
forste/haReFork
tools/base/TI/TiTEnv.hs
bsd-3-clause
1,212
0
12
210
376
206
170
-1
-1
{-| An encoding of the error function and plotting example enclosures. -} module TestSineCosine where -- Doubles as interval endpoints: import Numeric.AERN.RealArithmetic.Basis.Double () -- intervals generic in the type of its endpoints: import Numeric.AERN.Basics.Interval (Interval(..)) -- interval-coefficient polynomials: import Numeric.AERN.Poly.IntPoly (IntPoly, IntPolySizeLimits(..), IntPolyEffort(..), defaultIntPolySizeLimits) import Numeric.AERN.Poly.IntPoly.Interval () import Numeric.AERN.Poly.IntPoly.Plot () -- abstract approximate real arithmetic operations: import Numeric.AERN.RealArithmetic.RefinementOrderRounding (piOut, sqrtOut, expOutEff, expDefaultEffort, sincosDefaultEffort, sinOutEff, cosOutEff) import Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators ((+|), (|*)) import Numeric.AERN.RealArithmetic.ExactOps (one) -- ability to control the effort for elementary operations: import Numeric.AERN.RealArithmetic.Interval (SineCosineThinEffortIndicator(..)) -- abstract function processing operations: import Numeric.AERN.RmToRn (newProjection, newConstFn, primitiveFunctionOut) import Numeric.AERN.RefinementOrder ((/\)) import qualified Numeric.AERN.RmToRn.Plot.FnView as FV {----- type definitions -----} type DI = Interval Double type V = String -- names of variables type Poly = IntPoly V DI type PI = Interval Poly {----- using interval polynomials -----} plotSineCosine :: IO () plotSineCosine = FV.plotFns [ -- ("sin^2(x) + cos^2(x) = 1", -- [ -- (("sin(x)", FV.blue, False), sineX), -- (("cos(x)", FV.blue, False), cosineX) -- , -- (("sin^2(x)", FV.blue, False), sineX * sineX), -- (("cos^2(x)", FV.blue, False), cosineX * cosineX), -- (("sin^2(x) + cos^2(x)", FV.blue, False), sineX * sineX + cosineX * cosineX) -- ] -- ) -- , ("over thick argument", [ (("x", FV.black, False), x), (("x+1", FV.black, False), xp1), (("x+(y\\in[0,1])", FV.black, False), xThickParam), (("[x,x+1]", FV.black, False), xThick), (("sin(x)", FV.black, False), sineX), (("sin(x+1)", FV.black, False), sinOutEff effSinCos xp1), (("sin(x+(y\\in[0,1]))", FV.red, False), sinOutEff effSinCos xThickParam), (("sin([x,x+1])", FV.green, False), sinOutEff effSinCos xThick), (("cos(x)", FV.black, False), cosineX), (("cos(x+1)", FV.black, False), cosOutEff effSinCos xp1), (("cos([x+(y\\in[0,1])])", FV.red, False), cosOutEff effSinCos xThickParam) ] ) -- , -- ("sin(x^2)", -- [ -- (("x*x", FV.black, False), x * x), -- (("sin(x*x)", FV.red, False), sineXSqr) -- ] -- ) ] where maxdeg = 20 taylorDeg = 10 sineX = sinOutEff effSinCos x cosineX = cosOutEff effSinCos x sineXSqr = sinOutEff effSinCos (x * x) xp1 = x + (one x) xThickParam = x + y xThick = x +| (Interval 0 1 :: DI) x :: Poly x = newProjection sizeLimits doms "x" y = newProjection sizeLimits doms "y" doms = [ ("x", Interval (0) 2) , ("y", Interval (0) 1) ] -- indicators controlling the approximation effort: effSinCos = (sincosDefaultEffort sampleFn) { sincoseff_taylorDeg = taylorDeg -- Taylor approximation degree } sizeLimits = -- restrictions on the size of the polynomials defaultSizeLimits { ipolylimits_maxdeg = maxdeg, -- maximum degree ipolylimits_maxsize = 1000, -- maximum number of terms ipolylimits_effort = (ipolylimits_effort defaultSizeLimits) { ipolyeff_evalMaxSplitSize = 2000 } } where defaultSizeLimits = (defaultIntPolySizeLimits sampleCoeff () 1) sampleCoeff = 0 sampleFn = x plotSineOfCosine :: IO () plotSineOfCosine = FV.plotFns [ ("sin(cos(x))", [ -- (("x", FV.black, False), x), (("cos(x)", FV.black, False), cosX) , (("sin(cos(x))", FV.black, False), sinOutEff effSinCos2 cosX) -- , -- (("1+eps1DI", FV.black, False), eps1DIp1) -- , -- (("(1+ePI)cos(x)", FV.red, True), eps1PIcosX) , (("(1+eDI)cos(x)", FV.green, True), eps1DIcosX) -- , -- (("sin((1+ePI)cos(x))", FV.red, True), Interval poly_sinEps1CosX poly_sinEps1CosX) , (("sin((1+eDI)cos(x))", FV.blue, True), sinEps1CosX) ] ) ] where maxdeg = 12 maxsize = 100 taylorDeg1 = 15 taylorDeg2 = 20 bernsteinDeg = 2 evalMaxSplitSize = 2000 -- best so far: -- maxdeg = 12 -- maxsize = 100 -- taylorDeg1 = 15 -- taylorDeg2 = 20 -- bernsteinDeg = 2 -- evalMaxSplitSize = 2000 sinEps1CosX = sinOutEff effSinCos2 eps1DIcosX poly_sinEps1CosX = sinOutEff poly_effSinCos2 poly_eps1cosX poly_eps1cosX = poly_eps1p1 * poly_cosX poly_eps1p1 = poly_eps1 +| (1 :: Int) eps1DIcosX = eps1DIp1 * cosX eps1DIp1 = newConstFn sizeLimits doms (eps1DI +| (1 :: Int)) cosX = cosOutEff effSinCos1 x poly_cosX = cosOutEff poly_effSinCos1 poly_x poly_eps1 = newProjection sizeLimits doms "eps1" :: Poly poly_x = newProjection sizeLimits doms "x" :: Poly x = newProjection sizeLimits doms "x" :: PI doms = [ ("x", 0 /\ 2) , ("eps1", eps1DI) -- , -- ("eps2", eps2DI) ] eps1DI = (-eps1) /\ eps1 eps2DI = (-eps2) /\ eps2 eps1 = 0.125 :: DI eps2 = 0.125 :: DI -- indicators controlling the approximation effort: effSinCos1 = (sincosDefaultEffort x) { sincoseff_taylorDeg = taylorDeg1 -- Taylor approximation degree } poly_effSinCos1 = (sincosDefaultEffort poly_x) { sincoseff_taylorDeg = taylorDeg1 -- Taylor approximation degree } effSinCos2 = (sincosDefaultEffort x) { sincoseff_taylorDeg = taylorDeg2 -- Taylor approximation degree } poly_effSinCos2 = (sincosDefaultEffort poly_x) { sincoseff_taylorDeg = taylorDeg2 -- Taylor approximation degree } sizeLimits = -- restrictions on the size of the polynomials defaultSizeLimits { ipolylimits_maxdeg = maxdeg, -- maximum degree ipolylimits_maxsize = maxsize, -- maximum number of terms ipolylimits_effort = (ipolylimits_effort defaultSizeLimits) { ipolyeff_evalMaxSplitSize = evalMaxSplitSize, ipolyeff_minmaxBernsteinDegree = bernsteinDeg } } where defaultSizeLimits = (defaultIntPolySizeLimits sampleCoeff () 1) sampleCoeff = 0 sampleFn = x {----- using polynomial intervals -----} plotSineCosinePI :: IO () plotSineCosinePI = FV.plotFns [ -- ("sin^2(x) + cos^2(x) = 1", -- [ -- (("sin(x)", FV.blue, False), sineX), -- (("cos(x)", FV.blue, False), cosineX), -- (("sin^2(x)", FV.blue, False), sineX * sineX), -- (("cos^2(x)", FV.blue, False), cosineX * cosineX), -- (("sin^2(x) + cos^2(x)", FV.blue, False), sineX * sineX + cosineX * cosineX) -- ] -- ) -- , ("over thick argument", [ (("x", FV.black, False), x), (("x+1", FV.black, False), x + 1), (("[x,x+1]", FV.black, False), xThick), (("sin(x)", FV.black, False), sineX), (("sin(x+1)", FV.black, False), sinOutEff effSinCos xp1), (("sin([x,x+1])", FV.red, False), sinOutEff effSinCos xThick) ] ) -- , -- ("sin(x^2)", -- [ -- (("x*x", FV.black, False), x * x), -- (("sin(x*x)", FV.red, False), sineXSqr) -- ] -- ) ] where maxdeg = 20 taylorDeg = 20 sineX = sinOutEff effSinCos x cosineX = cosOutEff effSinCos x sineXSqr = sinOutEff effSinCos (x * x) xThick = x /\ (x + 1) xp1 = x + 1 x :: PI x = -- ie the identity function \x:[0,1] -> x newProjection sizeLimits [("x", Interval (0) 2)] "x" -- indicators controlling the approximation effort: effSinCos = (sincosDefaultEffort sampleFn) { sincoseff_taylorDeg = taylorDeg -- Taylor approximation degree } sizeLimits = -- restrictions on the size of the polynomials defaultSizeLimits { ipolylimits_maxdeg = maxdeg, -- maximum degree ipolylimits_maxsize = 100, -- maximum number of terms ipolylimits_effort = (ipolylimits_effort defaultSizeLimits) { ipolyeff_evalMaxSplitSize = 20000 } } where defaultSizeLimits = (defaultIntPolySizeLimits sampleCoeff () 1) sampleCoeff = 0 sampleFn = x
michalkonecny/aern
aern-poly-plot-gtk/demos/TestSineCosine.hs
bsd-3-clause
9,562
0
11
3,188
1,707
1,057
650
169
1
module Main(main) where import System.Environment import TagSoup.Sample import TagSoup.Test import TagSoup.Benchmark import Data.Char(toLower) helpMsg :: IO () helpMsg = putStr $ unlines $ ["TagSoup, (C) Neil Mitchell 2006-2009" ,"" ," tagsoup arguments" ,"" ,"<url> may either be a local file, or a http[s]:// page" ,"" ] ++ map f res where width = maximum $ map (length . fst) res res = map g actions g (nam,msg,Left _) = (nam,msg) g (nam,msg,Right _) = (nam ++ " <url>",msg) f (lhs,rhs) = " " ++ lhs ++ replicate (4 + width - length lhs) ' ' ++ rhs actions :: [(String, String, Either (IO ()) (String -> IO ()))] actions = [("test","Run the test suite",Left test) ,("grab","Grab a web page",Right grab) ,("parse","Parse a web page",Right parse) ,("bench","Benchmark the parsing",Left time) ,("benchfile","Benchmark the parsing of a file",Right timefile) ,("validate","Validate a page",Right validate) ,("lastmodifieddate","Get the wiki.haskell.org last modified date",Left haskellLastModifiedDateTime) ,("spj","Simon Peyton Jones' papers",Left spjPapers) ,("ndm","Neil Mitchell's papers",Left ndmPapers) ,("time","Current time",Left currentTime) ,("google","Google Tech News",Left googleTechNews) ,("sequence","Creators on sequence.complete.org",Left rssCreators) ,("table","Parse a table",Left $ print parseTable) ,("help","This help message",Left helpMsg) ] main :: IO () main = do args <- getArgs case (args, lookup (map toLower $ head args) $ map (\(a,_,c) -> (a,c)) actions) of ([],_) -> do putStrLn "No arguments specifying, defaulting to test" helpMsg putStrLn $ replicate 70 '-' test (x:_,Nothing) -> putStrLn ("Error: unknown command " ++ x) >> helpMsg ([_],Just (Left a)) -> a (x:xs,Just (Left a)) -> do putStrLn $ "Warning: expected no arguments to " ++ x ++ " but got: " ++ unwords xs a ([_,y],Just (Right a)) -> a y (x:xs,Just (Right _)) -> do putStrLn $ "Error: expected exactly one argument to " ++ x ++ " but got: " ++ unwords xs helpMsg
ndmitchell/tagsoup
test/Main.hs
bsd-3-clause
2,333
0
15
667
789
432
357
53
6
-- ----------------------------------------------------------------------------- -- Syntax.hs, part of Luthor -- -- (c) Edward Kmett 2010 -- Based on AbsSyn.hs from 'alex' (c) Chris Dornan 1995-2000, Simon Marlow 2003 -- ----------------------------------------------------------------------------} module Text.Luthor.Syntax ( Scanner(..) , Rule(..) , Code(..) , RegExp(..) , Post(..) , mapPostCode , assignStartCodes ) where import Data.CharSet (CharSet) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Text.Luthor.Bifunctor import Data.Maybe (fromJust) infixl 4 :| infixl 5 :%% data Scanner sc -- ^ start code format c -- ^ code type = Scanner { scannerName :: String , scannerRules :: [Rule sc c] } deriving (Show) instance Functor Scanner where fmap f (Scanner n rules) = Scanner n (map (fmap f) rules) instance Bifunctor Scanner where bimap f g (Scanner n rules) = Scanner n (map (bimap f g) rules) type StartCode = Int data Rule sc -- ^ start code format c -- ^ code type = Rule { ruleStartCodes :: [sc] , rulePre :: Maybe CharSet , ruleRegExp :: RegExp , rulePost :: Post RegExp c , ruleCode :: Maybe c } deriving (Show) instance Functor Rule where fmap f (Rule as pre r post code) = Rule (fmap f as) pre r post (fmap f code) instance Bifunctor Rule where bimap f g (Rule as pre r post code) = Rule (fmap g as) pre r (first f post) (fmap f code) data Post re -- ^ regexp format c -- ^ code type = NoPost | Post re | PostCode c deriving (Show) instance Functor (Post re) where fmap _ NoPost = NoPost fmap _ (Post re) = Post re fmap f (PostCode c) = PostCode (f c) instance Bifunctor Post where bimap _ _ NoPost = NoPost bimap f _ (Post re) = Post (f re) bimap _ g (PostCode c) = PostCode (g c) data RegExp = Eps | Ch CharSet | RegExp :%% RegExp | RegExp :| RegExp | Star RegExp | Plus RegExp | Ques RegExp deriving (Show) -- | Takes a 'Scanner' with startCodes identified by 'String' -- and recodes it to one with startCodes @[0 .. n - 1]@, -- returning the new 'Scanner', the mapping, and @n@. assignStartCodes :: Scanner String c -> (Scanner Int c, Map String Int, Int) assignStartCodes scanner = (first startCode scanner, codeMap, numStartCodes) where startCode name = fromJust $ Map.lookup name codeMap next a _ = let a' = a + 1 in a' `seq` (a', a') (numStartCodes, codeMap) = second (insert "0" 0) $ Traversable.mapAccumL next 1 $ Map.fromList [ (name, ()) | Rule { ruleStartCodes = names } <- scannerRules scanner , name <- names , name /= "0" ]
ekmett/luthor
Text/Luthor/Syntax.hs
bsd-3-clause
2,890
0
14
809
882
487
395
77
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} #if MIN_VERSION_base(4,9,0) {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Text.CSL.Eval.Common -- Copyright : (c) Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Andrea Rossato <[email protected]> -- Stability : unstable -- Portability : unportable -- -- The CSL implementation -- ----------------------------------------------------------------------------- module Text.CSL.Eval.Common where import Prelude import Control.Arrow ((&&&), (>>>)) import Control.Monad.State import Data.Char (toLower) import Data.List (elemIndex) import qualified Data.Map as M import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import Text.CSL.Reference import Text.CSL.Style import Text.Pandoc.Shared (stringify) import Debug.Trace data EvalState = EvalState { ref :: ReferenceMap , env :: Environment , debug :: [Text] , mode :: EvalMode , disamb :: Bool , consume :: Bool , authSub :: [Text] , consumed :: [Text] , edtrans :: Bool , etal :: [[Output]] , contNum :: [Agent] , lastName :: [Output] } deriving ( Show ) data Environment = Env { cite :: Cite , terms :: [CslTerm] , macros :: [MacroMap] , dates :: [Element] , options :: [Option] , names :: [Element] , abbrevs :: Abbreviations } deriving ( Show ) data EvalMode = EvalSorting Cite | EvalCite Cite | EvalBiblio Cite -- for the reference position deriving ( Show, Eq ) isSorting :: EvalMode -> Bool isSorting m = case m of EvalSorting _ -> True; _ -> False -- | With the variable name and the variable value search for an -- abbreviation or return an empty string. getAbbreviation :: Abbreviations -> Text -> Text -> Text getAbbreviation (Abbreviations as) s v = fromMaybe "" $ M.lookup "default" as >>= M.lookup (if s `elem` numericVars then "number" else s) >>= M.lookup v -- | If the first parameter is 'True' the plural form will be retrieved. getTerm :: Bool -> Form -> Text -> State EvalState Text getTerm b f s = maybe "" g . findTerm s f' <$> gets (terms . env) -- FIXME: vedere i fallback where g = if b then termPlural else termSingular f' = case f of NotSet -> Long; _ -> f getStringVar :: Text -> State EvalState Text getStringVar = getVar "" getStringValue getDateVar :: Text -> State EvalState [RefDate] getDateVar = getVar [] getDateValue where getDateValue = maybe [] id . fromValue getLocVar :: State EvalState (Text,Text) getLocVar = gets (env >>> cite >>> citeLabel &&& citeLocator) getVar :: a -> (Value -> a) -> Text -> State EvalState a getVar a f s = withRefMap $ maybe a f . lookup (formatVariable s) getAgents :: Text -> State EvalState [Agent] getAgents s = do mv <- withRefMap (lookup s) case mv of Just v -> case fromValue v of Just x -> consumeVariable s >> return x _ -> return [] _ -> return [] getAgents' :: Text -> State EvalState [Agent] getAgents' s = do mv <- withRefMap (lookup s) case mv of Just v -> case fromValue v of Just x -> return x _ -> return [] _ -> return [] getStringValue :: Value -> Text getStringValue val = -- The second clause handles the case where we have a Formatted -- but need a String. This is currently needed for "page". It's a bit -- hackish; we should probably change the type in Reference for -- page to String. case fromValue val `mplus` ((stringify . unFormatted) `fmap` fromValue val) `mplus` (unLiteral `fmap` fromValue val) of Just v -> v Nothing -> Debug.Trace.trace ("Expecting string value, got " ++ show val) T.empty getOptionVal :: Text -> [Option] -> Text getOptionVal s = fromMaybe "" . lookup s getOptionValWithDefault :: Text -> Text -> [Option] -> Text getOptionValWithDefault s defvalue = fromMaybe defvalue . lookup s isOptionSet :: Text -> [Option] -> Bool isOptionSet s = maybe False (not . T.null) . lookup s isTitleVar, isTitleShortVar :: Text -> Bool isTitleVar = flip elem ["title", "container-title", "collection-title"] isTitleShortVar = flip elem ["title-short", "container-title-short"] getTitleShort :: Text -> State EvalState Text getTitleShort s = do let s' = T.dropEnd 6 s -- drop '-short' v <- getStringVar s' abbrs <- gets (abbrevs . env) return $ getAbbreviation abbrs s' v isVarSet :: Text -> State EvalState Bool isVarSet s | isTitleShortVar s = do r <- getVar False isValueSet s if r then return r else fmap (not . T.null) (getTitleShort s) | otherwise = if s /= "locator" then getVar False isValueSet s else getLocVar >>= return . (/=) "" . snd withRefMap :: (ReferenceMap -> a) -> State EvalState a withRefMap f = return . f =<< gets ref -- | Convert variable to lower case, translating underscores ("_") to dashes ("-") formatVariable :: Text -> Text formatVariable = T.foldr f T.empty where f x xs = if x == '_' then '-' `T.cons` xs else toLower x `T.cons` xs consumeVariable :: Text -> State EvalState () consumeVariable s = do b <- gets consume when b $ modify $ \st -> st { consumed = s : consumed st } consuming :: State EvalState a -> State EvalState a consuming f = setConsume >> f >>= \a -> doConsume >> unsetConsume >> return a where setConsume = modify $ \s -> s {consume = True, consumed = [] } unsetConsume = modify $ \s -> s {consume = False } doConsume = do sl <- gets consumed modify $ \st -> st { ref = remove (ref st) sl } doRemove s (k,v) = if isValueSet v then [(formatVariable s,Value Empty)] else [(k,v)] remove rm sl | (s:ss) <- sl = case elemIndex (formatVariable s) (map fst rm) of Just i -> let nrm = take i rm ++ doRemove s (rm !! i) ++ drop (i + 1) rm in remove nrm ss Nothing -> remove rm ss | otherwise = rm when' :: Monad m => m Bool -> m [a] -> m [a] when' p f = whenElse p f (return []) whenElse :: Monad m => m Bool -> m a -> m a -> m a whenElse b f g = b >>= \ bool -> if bool then f else g concatMapM :: (Monad m, Functor m, Eq b) => (a -> m [b]) -> [a] -> m [b] concatMapM f l = concat . filter (/=[]) <$> mapM f l {- trace :: String -> State EvalState () trace d = modify $ \s -> s { debug = d : debug s } -}
jgm/pandoc-citeproc
src/Text/CSL/Eval/Common.hs
bsd-3-clause
7,320
0
19
2,346
2,143
1,140
1,003
148
3
{-| Module : Utils.Test.EnforceRange Description : squash generated numbers to a given range Copyright : (c) Michal Konecny License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable Utility for squashing randomly generated numbers to a given range. -} module Utils.Test.EnforceRange (enforceRange, CanEnforceRange) where import Numeric.MixedTypes.PreludeHiding -- import qualified Prelude as P -- import Numeric.CollectErrors import Numeric.MixedTypes.Literals import Numeric.MixedTypes.Bool -- import Numeric.MixedTypes.Eq import Numeric.MixedTypes.Ord import Numeric.MixedTypes.MinMaxAbs import Numeric.MixedTypes.AddSub import Numeric.MixedTypes.Mul import Numeric.MixedTypes.Field import Numeric.MixedTypes.Round type CanEnforceRange t b = (CanAddSubMulDivBy t Integer , CanAddSameType t, CanSubSameType t, CanAbsSameType t , CanDivIModIntegerSameType t , ConvertibleExactly b t , HasOrderCertainly t t) {-| @enforceRange (Just l, Just u) a@ where @l < u@ returns an arbitrary value @b@ with @u < b < l@. Moreover, the returned values are distributed roughly evenly if the input values @a@ are distributed roughly evenly in a large neighbourhood of the interval @[l,r]@. In most cases, when @l<a<u@, then @b=a@. -} enforceRange :: (CanEnforceRange t b) => (Maybe b, Maybe b) -> t -> t enforceRange (Just l_, Just u_) (a::t) | not (l !<! u) = error "enforceRange: inconsistent range" | l !<! a && a !<! u = a | l !<! b && b !<! u = b | otherwise = (u+l)/2 where l = convertExactly l_ :: t u = convertExactly u_ :: t b = l + ((abs a) `mod` (u-l)) enforceRange (Just l_, _) (a::t) | l !<! a = a | otherwise = (2*l-a+1) where l = convertExactly l_ :: t enforceRange (_, Just u_) (a::t) | a !<! u = a | otherwise = (2*u-a-1) where u = convertExactly u_ :: t enforceRange _ a = a
michalkonecny/mixed-types-num
src/Utils/Test/EnforceRange.hs
bsd-3-clause
1,989
0
11
453
487
263
224
-1
-1
{-# LANGUAGE FlexibleContexts #-} module OfficeClimate.Connection ( connect , run , runI ) where import Database.HDBC.PostgreSQL (connectPostgreSQL, Connection) import Database.HDBC (IConnection, SqlValue) import Database.Record (FromSql, ToSql) import Database.HDBC.Record.Query (runQuery) import Database.HDBC.Record.Insert (runInsert) import Database.Relational.Query (Insert) import Database.Relational.Query (Relation, relationalQuery) connect :: IO Connection connect = connectPostgreSQL "dbname='office_climate'" run :: (Show a, IConnection conn, FromSql SqlValue a, ToSql SqlValue p) => conn -> p -> Relation p a -> IO () run conn param rel = do putStrLn $ "SQL: " ++ show rel records <- runQuery conn (relationalQuery rel) param mapM_ print records putStrLn "" runI :: (IConnection conn, ToSql SqlValue p) => conn -> p -> Insert p -> IO () runI conn param ins = do putStrLn $ "SQL: " ++ show ins num <- runInsert conn ins param print num putStrLn ""
igrep/office-climate
src/OfficeClimate/Connection.hs
bsd-3-clause
1,000
0
10
176
335
175
160
28
1
{-# LANGUAGE CPP #-} module React.Flux.Mui.Util where import Protolude import Data.Aeson import qualified Data.HashMap.Strict as HashMap import React.Flux #ifdef __GHCJS__ import Data.JSString.Text import Data.JSString (JSString) #else import Data.String (String) #endif #ifdef __GHCJS__ toKey :: Text -> JSString toKey = textToJSString #else toKey :: Text -> String toKey = toS #endif toProps :: (ToJSON a) => a -> Maybe [PropertyOrHandler handler] toProps j = case toJSON j of Object o -> Just . map (\(k, v) -> toKey k &= v) . HashMap.toList $ o _ -> Nothing
pbogdan/react-flux-mui
gen/templates/Util.hs
bsd-3-clause
642
0
15
167
162
94
68
16
2
{- Originally from: http://5outh.blogspot.com/2013/05/symbolic-calculus-in-haskell.html -} module Data.Expression where import Prelude (Eq, Show, String, error, id, otherwise, show, undefined, ($), (++), (==)) import Domains.Applicable import Domains.Exponentiative import Domains.Field import Domains.Trigonometric --import Debug.Trace infixl 1 ~> {-# ANN module "HLint: ignore Redundant bracket" #-} {-# ANN module "HLint: ignore Eta reduce" #-} {-# ANN module "HLint: ignore Avoid lambda" #-} {-# ANN module "HLint: ignore Unused matches" #-} data Fn a = Fn { name_ :: String , fun_ :: a -> a } fnValue :: Expression a -> a -> a fnValue (Fun f) = fun_ f fnValue _ = undefined instance Eq (Fn a) where Fn name1 _ == Fn name2 _ = name1 == name2 instance Show (Fn a) where show (Fn name1 _) = name1 data Expression a = Const !a | Var !String | Fun !(Fn a) | Lambda !(Expression a) !(Expression a) | App !(Expression a) !(Expression a) | Sum !(Expression a) !(Expression a) | Neg !(Expression a) | Prd !(Expression a) !(Expression a) | Rcp !(Expression a) | Pow !(Expression a) !(Expression a) | Log !(Expression a) !(Expression a) deriving (Eq) (~>) :: Expression a -> Expression a -> Expression a x ~> body = Lambda x body varName :: Expression a -> String varName (Var s) = s varName _ = error "Formal parameter to Lambda wasn't a symbol!" instance (Show a) => Show (Expression a) where show (Const a) = show a show (Var a) = a show (Fun f) = name_ f show (Lambda var body) = "(" ++ show var ++ " ~> " ++ show body ++ ")" show (App f a) = "(" ++ show f ++ " " ++ show a ++ ")" show (Sum a b) = "(" ++ show a ++ " + " ++ show b ++ ")" show (Neg a) = "(" ++ "-" ++ show a ++ ")" show (Prd a b) = "(" ++ show a ++ "*" ++ show b ++ ")" show (Pow a b) = "(" ++ show a ++ "^" ++ show b ++ ")" show (Log a b) = "(log (base " ++ show a ++ ") " ++ show b ++ ")" show (Rcp a) = "(" ++ "/" ++ show a ++ ")" instance (Eq a, Additive a) => Additive (Expression a) where Const a + Const b = Const (a + b) Const a + b | a == zero = b | otherwise = Sum (Const a) b a + Const b | b == zero = a | otherwise = Sum a (Const b) a + b = Sum a b zero = Const zero instance (Negatable a) => Negatable (Expression a) where neg (Const a) = Const (neg a) neg (Neg a) = a neg a = Neg a instance (Eq a, Subtractive a) => Subtractive (Expression a) instance (Eq a, Additive a, Multiplicative a) => Multiplicative (Expression a) where Const a * Const b = Const (a * b) a * Const b | b == zero = zero | b == one = a | otherwise = Prd (Const b) a -- move the constants to the front; todo -- check for commutativity. Const a * (Prd (Const b) c) = Prd (Const (a * b)) c -- gather constants; todo -- check for associativity. Const a * b | a == zero = zero | a == one = b | otherwise = Prd (Const a) b (Rcp a) * (Rcp b) = Rcp (a * b) a * (Prd b (Rcp c)) = Prd (a * b) (Rcp c) a * (Rcp b) | a == b = one | otherwise = Prd a (Rcp b) a * b | a == b = Pow a (Const one + Const one) | otherwise = Prd a b one = Const one instance (Eq a, Ring a) => Ring (Expression a) instance (Eq a, Field a) => Reciprocative (Expression a) where reciprocal (Const a) = Const (reciprocal a) reciprocal a = Rcp a instance (Eq a, Field a) => Field (Expression a) where a / b = a * reciprocal b instance (Eq a, Field a, Exponentiative a) => Exponentiative (Expression a) where Const a ^ Const b = Const (a ^ b) a ^ Const b | b == zero = one | b == one = a | otherwise = Pow a (Const b) Const a ^ b | a == zero = zero | a == one = one | otherwise = Pow (Const a) b a ^ b = Pow a b log a b | b == one = zero | otherwise = Log a b ln (Const a) = Const (ln a) ln a = App (Fun (Fn "ln" ln)) a exp (Const a) = Const (exp a) exp a = App (Fun (Fn "exp" exp)) a sqrt = App (Fun (Fn "sqrt" sqrt)) two = Const two -- https://en.wikipedia.org/wiki/Differentiation_of_trigonometric_functions instance (Eq a, Field a, Exponentiative a, Trigonometric a) => Trigonometric (Expression a) where sin = App (Fun (Fn "sin" sin)) cos = App (Fun (Fn "cos" cos)) tan = App (Fun (Fn "tan" tan)) asin = App (Fun (Fn "asin" asin)) acos = App (Fun (Fn "acos" acos)) atan = App (Fun (Fn "atan" atan)) instance (Show a, Eq a, Field a, Exponentiative a, Applicable a) => Applicable (Expression a) where apply (Lambda x body) arg = substitute (varName x) arg body apply f x = App f x map0 :: (Show b, Eq b, Field b, Exponentiative b) => (String -> b) -> (a -> b) -> (Fn a -> b) -> (Expression a -> b -> b) -> Expression a -> b map0 mapVar mapConst mapFun mapApplyFun e0 = rec e0 where rec e = case e of Const a -> mapConst a Var a -> mapVar a Fun f -> mapFun f App f a -> mapApplyFun f (rec a) Neg a -> neg (rec a) Sum a b -> rec a + rec b Prd a b -> rec a * rec b Rcp a -> reciprocal (rec a) Pow a b -> rec a ^ rec b Log a b -> log (rec a) (rec b) -- trace ("evalExpr: " ++ nm ++ " -> " ++ show val ++ " in " ++ show exp) $ eval1 :: (Show a, Eq a, Field a, Exponentiative a, Applicable a) => String -> a -> Expression a -> a eval1 name value exp0 = map0 (\vName -> if name == vName then value else undefined) id undefined fnValue exp0 substitute :: (Applicable a, Exponentiative a, Field a, Eq a, Show a) => String -> Expression a -> Expression a -> Expression a substitute name val exp0 = map0 (\nm -> if nm == name then val else Var nm) Const Fun (\f -> apply (substitute name val f)) exp0
pmilne/algebra
src/Data/Expression.hs
bsd-3-clause
6,038
0
12
1,888
2,807
1,365
1,442
206
10
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE StandaloneDeriving #-} -- | Experimenting with a data structure to define a plugin. -- -- The general idea is that a given plugin returns this structure during the -- initial load/registration process, when- or however this eventually happens. -- -- It should define the following things -- 1. What features the plugin should expose into the IDE -- (this one may not be needed initially) -- -- This may include a requirement to store private data of a particular -- form. -- -- It may be interesting to look at the Android model wrt Intents and -- shared resource management, e.g. default Calendar app, default SMS app, -- all making use of Contacts service. module Haskell.Ide.Engine.PluginDescriptor ( PluginDescriptor(..) , Service(..) -- * Commands , Command(..) , TaggedCommand , UntaggedCommand , CommandFunc(..), SyncCommandFunc, AsyncCommandFunc , buildCommand -- * Plugins , Plugins -- * The IDE monad , IdeM , IdeState(..) , ExtensionClass(..) , getPlugins , untagPluginDescriptor , TaggedPluginDescriptor , UntaggedPluginDescriptor , NamedCommand(..) , CommandType(..) , Rec(..) , Proxy(..) , recordToList' -- * All the good types , module Haskell.Ide.Engine.PluginTypes ) where import Control.Applicative import Control.Monad.State.Strict import Data.Aeson import Data.Dynamic import qualified Data.Map as Map import Data.Singletons import qualified Data.Text as T import Data.Vinyl import qualified Data.Vinyl.Functor as Vinyl import GHC.Generics import GHC.TypeLits import Haskell.Ide.Engine.PluginTypes import qualified Language.Haskell.GhcMod.Monad as GM -- --------------------------------------------------------------------- data PluginDescriptor cmds = PluginDescriptor { pdUIShortName :: !T.Text , pdUIOverview :: !T.Text , pdCommands :: cmds , pdExposedServices :: [Service] , pdUsedServices :: [Service] } type TaggedPluginDescriptor cmds = PluginDescriptor (Rec NamedCommand cmds) type UntaggedPluginDescriptor = PluginDescriptor [UntaggedCommand] instance Show UntaggedPluginDescriptor where showsPrec p (PluginDescriptor name oview cmds svcs used) = showParen (p > 10) $ showString "PluginDescriptor " . showString (T.unpack name) . showString (T.unpack oview) . showList cmds . showString " " . showList svcs . showString " " . showList used data Service = Service { svcName :: T.Text -- , svcXXX :: undefined } deriving (Show,Eq,Ord,Generic) recordToList' :: (forall a. f a -> b) -> Rec f as -> [b] recordToList' f = recordToList . rmap (Vinyl.Const . f) untagPluginDescriptor :: TaggedPluginDescriptor cmds -> UntaggedPluginDescriptor untagPluginDescriptor pluginDescriptor = pluginDescriptor {pdCommands = recordToList' untagCommand (pdCommands pluginDescriptor)} type Plugins = Map.Map PluginId UntaggedPluginDescriptor untagCommand :: NamedCommand t -> UntaggedCommand untagCommand (NamedCommand _ (Command desc func)) = Command (desc {cmdContexts = recordToList' fromSing (cmdContexts desc) ,cmdAdditionalParams = recordToList' untagParamDesc (cmdAdditionalParams desc)}) func -- | Ideally a Command is defined in such a way that its CommandDescriptor -- can be exposed via the native CLI for the tool being exposed as well. -- Perhaps use Options.Applicative for this in some way. data Command desc = forall a. (ValidResponse a) => Command { cmdDesc :: !desc , cmdFunc :: !(CommandFunc a) } type TaggedCommand cxts tags = Command (TaggedCommandDescriptor cxts tags) type UntaggedCommand = Command UntaggedCommandDescriptor instance Show desc => Show (Command desc) where show (Command desc _func) = "(Command " ++ show desc ++ ")" data NamedCommand (t :: CommandType) where NamedCommand :: KnownSymbol s => Proxy s -> TaggedCommand cxts tags -> NamedCommand ('CommandType s cxts tags) data CommandType = CommandType Symbol [AcceptedContext] [ParamDescType] -- | Build a command, ensuring the command response type name and the command -- function match buildCommand :: forall a s cxts tags. (ValidResponse a, KnownSymbol s) => CommandFunc a -> Proxy s -> T.Text -> [T.Text] -> Rec SAcceptedContext cxts -> Rec SParamDescription tags -> NamedCommand ( 'CommandType s cxts tags ) buildCommand fun n d exts ctxs parm = NamedCommand n $ Command {cmdDesc = CommandDesc {cmdName = T.pack $ symbolVal n ,cmdUiDescription = d ,cmdFileExtensions = exts ,cmdContexts = ctxs ,cmdAdditionalParams = parm ,cmdReturnType = T.pack $ show $ typeOf (undefined :: a)} ,cmdFunc = fun} -- --------------------------------------------------------------------- -- | The 'CommandFunc' is called once the dispatcher has checked that it -- satisfies at least one of the `AcceptedContext` values for the command -- descriptor, and has all the required parameters. Where a command has only one -- allowed context the supplied context list does not add much value, but allows -- easy case checking when multiple contexts are supported. data CommandFunc resp = CmdSync (SyncCommandFunc resp) | CmdAsync (AsyncCommandFunc resp) -- ^ Note: does not forkIO, the command must decide when -- to do this. type SyncCommandFunc resp = [AcceptedContext] -> IdeRequest -> IdeM (IdeResponse resp) type AsyncCommandFunc resp = (IdeResponse resp -> IO ()) -> [AcceptedContext] -> IdeRequest -> IdeM () -- ------------------------------------- -- JSON instances instance ToJSON Service where toJSON service = object [ "name" .= svcName service ] instance FromJSON Service where parseJSON (Object v) = Service <$> v .: "name" parseJSON _ = empty -- --------------------------------------------------------------------- type IdeM = IdeT IO type IdeT m = GM.GhcModT (StateT IdeState m) data IdeState = IdeState { idePlugins :: Plugins , extensibleState :: !(Map.Map TypeRep Dynamic) -- ^ stores custom state information. } deriving (Show) getPlugins :: IdeM Plugins getPlugins = lift $ lift $ idePlugins <$> get -- --------------------------------------------------------------------- -- Extensible state, based on -- http://xmonad.org/xmonad-docs/xmonad/XMonad-Core.html#t:ExtensionClass -- -- | Every module must make the data it wants to store -- an instance of this class. -- -- Minimal complete definition: initialValue class Typeable a => ExtensionClass a where -- | Defines an initial value for the state extension initialValue :: a
JPMoresmau/haskell-ide-engine
hie-plugin-api/Haskell/Ide/Engine/PluginDescriptor.hs
bsd-3-clause
7,470
0
16
1,798
1,356
780
576
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DataKinds #-} -------------------------------------------------------------------------------- -- | -- Module : Database.EventStore.Internal.Operation.Identify -- Copyright : (C) 2017 Yorick Laupa -- License : (see the file LICENSE) -- Maintainer: Yorick Laupa <[email protected]> -- Stability : experimental -- Portability: non-portable -- -------------------------------------------------------------------------------- module Database.EventStore.Internal.Operation.Identify ( newIdentifyPkg ) where -------------------------------------------------------------------------------- import Data.ProtocolBuffers import Data.Serialize (runPut) -------------------------------------------------------------------------------- import Database.EventStore.Internal.Command import Database.EventStore.Internal.Prelude import Database.EventStore.Internal.Types -------------------------------------------------------------------------------- data Request = Request { _version :: Required 1 (Value Int32) , _name :: Optional 2 (Value Text) } deriving (Generic, Show) -------------------------------------------------------------------------------- newRequest :: Int32 -> Text -> Request newRequest ver name = Request { _version = putField ver , _name = putField $ Just name } -------------------------------------------------------------------------------- newIdentifyPkg :: MonadBase IO m => Int32 -> Text -> m Package newIdentifyPkg version name = do uuid <- newUUID let msg = newRequest version name pkg = Package { packageCmd = identifyClientCmd , packageCorrelation = uuid , packageData = runPut $ encodeMessage msg , packageCred = Nothing } pure pkg -------------------------------------------------------------------------------- instance Encode Request
YoEight/eventstore
Database/EventStore/Internal/Operation/Identify.hs
bsd-3-clause
1,983
0
13
353
276
160
116
-1
-1
main :: IO Int main = return (42)
alanz/haskell-lsp
lsp-test/test/data/refactor/Main.hs
mit
34
0
6
8
20
10
10
2
1
module Evict where data EvictionState = LRU eviction_init :: EvictionState eviction_init = LRU eviction_update :: EvictionState -> Integer -> EvictionState eviction_update s _ = s eviction_choose :: EvictionState -> (Integer, EvictionState) eviction_choose s = (0, s)
mit-pdos/fscq-impl
src/hslib/Evict.hs
mit
274
0
6
42
73
42
31
9
1
{-# LANGUAGE DeriveDataTypeable #-} module InnerEar.Exercises.FiveBandBoostCut (fiveBandBoostCutExercise) where import Reflex import Reflex.Dom import Data.Map import Data.List (elemIndex,findIndices) import System.Random import Text.JSON import Text.JSON.Generic import InnerEar.Widgets.Config import InnerEar.Widgets.SpecEval import InnerEar.Types.Data hiding (Time) import InnerEar.Types.Sound import InnerEar.Types.Score import InnerEar.Types.MultipleChoiceStore import Sound.MusicW hiding (Frequency) import InnerEar.Types.Exercise import InnerEar.Types.ExerciseId import InnerEar.Types.Frequency import InnerEar.Exercises.MultipleChoice import InnerEar.Widgets.AnswerButton type Config = Double configs :: [Double] configs = [10,6,3,2,1,-1,-2,-3,-6,-10] -- configMap::Map String Config -- configMap = fromList $ fmap (\x-> (show x ++ " dB",x)) configs configMap::Map Int (String,Config) configMap = fromList $ zip [0::Int,1..] $ fmap (\x-> (show x ++ " dB",x)) configs newtype Answer = Answer { frequency :: Frequency } deriving (Eq,Ord,Data,Typeable) instance Buttonable Answer where makeButton = showAnswerButton instance Show Answer where show a = freqAsString $ frequency a answers :: [Answer] answers = [Answer $ F 155 "Bass (155 Hz)",Answer $ F 1125 "Low Mids (1125 Hz)",Answer $ F 3000 "High Mids (3 kHz)", Answer $ F 5000 "Presence (5 kHz)",Answer $ F 13000 "Brilliance (13 kHz)"] renderAnswer :: Map String AudioBuffer -> Config -> (SourceNodeSpec,Maybe Time) -> Maybe Answer -> Synth () renderAnswer _ db (src, dur) (Just freq) = buildSynth $ do let env = maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur synthSource src >> gain (Db $ -10) biquadFilter $ Peaking (Hz $ freqAsDouble $ frequency freq) 1.4 (Db db) env destination maybeDelete (fmap (+Sec 0.2) dur) renderAnswer _ db (src, dur) _ = buildSynth $ do let env = maybe (return EmptyGraph) (unitRectEnv (Millis 1)) dur synthSource src >> gain (Db $ -10) >> env >> destination maybeDelete (fmap (+Sec 0.2) dur) instructions :: MonadWidget t m => m () instructions = el "div" $ do elClass "div" "instructionsText" $ text "In this exercise, a filter is applied to a specific region of the spectrum, either boosting or cutting the energy in that part of the spectrum by a specified amount. Your task is to identify which part of the spectrum has been boosted or cut. Challenge yourself and explore additional possibilities by trying cuts (instead of boosts) to the spectrum, and by trying more subtle boosts/cuts (dB values progressively closer to 0)." displayEval :: MonadWidget t m => Dynamic t (Map Answer Score) -> Dynamic t (MultipleChoiceStore Config Answer) -> m () displayEval e _ = displayMultipleChoiceEvaluationGraph ("scoreBarWrapperFiveBars","svgBarContainerFiveBars","svgFaintedLineFiveBars", "xLabelFiveBars") "Session performance" "Hz" answers e generateQ :: Config -> [ExerciseDatum] -> IO ([Answer],Answer) generateQ _ _ = randomMultipleChoiceQuestion answers sourcesMap:: Map Int (String,SoundSourceConfigOption) sourcesMap = fromList $ [ (0, ("Pink noise", Resource "pinknoise.wav" (Just $ Sec 2))), (1, ("White noise", Resource "whitenoise.wav" (Just $ Sec 2))), (2, ("Load a sound file", UserProvidedResource)) ] fiveBandBoostCutExercise :: MonadWidget t m => Exercise t m Config [Answer] Answer (Map Answer Score) (MultipleChoiceStore Config Answer) fiveBandBoostCutExercise = multipleChoiceExercise 3 answers instructions (configWidget "fiveBandBoostCutExercise" sourcesMap 0 "Boost amount: " configMap) -- (dynRadioConfigWidget "fiveBandBoostCutExercise" sourcesMap 0 configMap) renderAnswer FiveBandBoostCut (configs!!0) displayEval generateQ (const (0,2))
JamieBeverley/InnerEar
src/InnerEar/Exercises/FiveBandBoostCut.hs
gpl-3.0
3,738
0
15
559
1,087
585
502
70
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CodePipeline.EnableStageTransition -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Enables artifacts in a pipeline to transition to a stage in a pipeline. -- -- /See:/ <http://docs.aws.amazon.com/codepipeline/latest/APIReference/API_EnableStageTransition.html AWS API Reference> for EnableStageTransition. module Network.AWS.CodePipeline.EnableStageTransition ( -- * Creating a Request enableStageTransition , EnableStageTransition -- * Request Lenses , estPipelineName , estStageName , estTransitionType -- * Destructuring the Response , enableStageTransitionResponse , EnableStageTransitionResponse ) where import Network.AWS.CodePipeline.Types import Network.AWS.CodePipeline.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Represents the input of an enable stage transition action. -- -- /See:/ 'enableStageTransition' smart constructor. data EnableStageTransition = EnableStageTransition' { _estPipelineName :: !Text , _estStageName :: !Text , _estTransitionType :: !StageTransitionType } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'EnableStageTransition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'estPipelineName' -- -- * 'estStageName' -- -- * 'estTransitionType' enableStageTransition :: Text -- ^ 'estPipelineName' -> Text -- ^ 'estStageName' -> StageTransitionType -- ^ 'estTransitionType' -> EnableStageTransition enableStageTransition pPipelineName_ pStageName_ pTransitionType_ = EnableStageTransition' { _estPipelineName = pPipelineName_ , _estStageName = pStageName_ , _estTransitionType = pTransitionType_ } -- | The name of the pipeline in which you want to enable the flow of -- artifacts from one stage to another. estPipelineName :: Lens' EnableStageTransition Text estPipelineName = lens _estPipelineName (\ s a -> s{_estPipelineName = a}); -- | The name of the stage where you want to enable the transition of -- artifacts, either into the stage (inbound) or from that stage to the -- next stage (outbound). estStageName :: Lens' EnableStageTransition Text estStageName = lens _estStageName (\ s a -> s{_estStageName = a}); -- | Specifies whether artifacts will be allowed to enter the stage and be -- processed by the actions in that stage (inbound) or whether -- already-processed artifacts will be allowed to transition to the next -- stage (outbound). estTransitionType :: Lens' EnableStageTransition StageTransitionType estTransitionType = lens _estTransitionType (\ s a -> s{_estTransitionType = a}); instance AWSRequest EnableStageTransition where type Rs EnableStageTransition = EnableStageTransitionResponse request = postJSON codePipeline response = receiveNull EnableStageTransitionResponse' instance ToHeaders EnableStageTransition where toHeaders = const (mconcat ["X-Amz-Target" =# ("CodePipeline_20150709.EnableStageTransition" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON EnableStageTransition where toJSON EnableStageTransition'{..} = object (catMaybes [Just ("pipelineName" .= _estPipelineName), Just ("stageName" .= _estStageName), Just ("transitionType" .= _estTransitionType)]) instance ToPath EnableStageTransition where toPath = const "/" instance ToQuery EnableStageTransition where toQuery = const mempty -- | /See:/ 'enableStageTransitionResponse' smart constructor. data EnableStageTransitionResponse = EnableStageTransitionResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'EnableStageTransitionResponse' with the minimum fields required to make a request. -- enableStageTransitionResponse :: EnableStageTransitionResponse enableStageTransitionResponse = EnableStageTransitionResponse'
fmapfmapfmap/amazonka
amazonka-codepipeline/gen/Network/AWS/CodePipeline/EnableStageTransition.hs
mpl-2.0
4,848
0
12
996
564
339
225
80
1
{-# LANGUAGE OverloadedStrings #-} -- Module : Test.AWS.Lambda -- Copyright : (c) 2013-2015 Brendan Hay -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Test.AWS.Lambda ( tests , fixtures ) where import Network.AWS.Lambda import Test.AWS.Gen.Lambda import Test.Tasty tests :: [TestTree] tests = [] fixtures :: [TestTree] fixtures = []
fmapfmapfmap/amazonka
amazonka-lambda/test/Test/AWS/Lambda.hs
mpl-2.0
736
0
5
201
73
50
23
11
1
module Main where import System.Console.GetOpt import System.Environment import System.Exit import System.IO import Data.Aeson import Data.ByteString.Lazy.Char8 (pack) import qualified Data.IntMap as M import Data.Maybe import Database.Algebra.Dag import Database.DSH.VSL.Dot import Database.DSH.VSL.Lang data Options = Options { optInput :: IO String , optReuse :: Bool , optRootNodes :: Maybe [Int] , optProperties :: Bool } startOptions :: Options startOptions = Options { optInput = getContents , optReuse = False , optRootNodes = Nothing , optProperties = False } options :: [OptDescr (Options -> IO Options)] options = [ Option "i" ["input"] (ReqArg (\arg opt -> return opt { optInput = readFile arg }) "FILE") "Input file" , Option "n" ["rootnodes"] (ReqArg (\arg opt -> return opt { optRootNodes = Just $ read arg }) "ROOTNODES") "List of root nodes to use (must be in Haskell list syntax)" , Option "p" ["properties"] (NoArg (\opt -> return opt { optProperties = True })) "Infer properties and display them" , Option "h" ["help"] (NoArg (\_ -> do prg <- getProgName hPutStrLn stderr (usageInfo prg options) exitWith ExitSuccess)) "Show help" ] main :: IO () main = do args <- getArgs let (actions, _, _) = getOpt RequireOrder options args opts <- foldl (>>=) (return startOptions) actions let Options { optInput = input , optRootNodes = mRootNodes } = opts plan <- pack <$> input case eitherDecode plan of Left msg -> putStrLn msg >> exitFailure Right dag -> do let rs' = fromMaybe (rootNodes dag) mRootNodes putStr $ renderVSLDot M.empty rs' (nodeMap (dag :: AlgebraDag TVSL))
ulricha/dsh
src/Database/DSH/Tools/VSLDotGen.hs
bsd-3-clause
2,143
0
17
806
567
306
261
54
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.S3.GetBucketVersioning -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns the versioning state of a bucket. -- -- <http://docs.aws.amazon.com/AmazonS3/latest/API/GetBucketVersioning.html> module Network.AWS.S3.GetBucketVersioning ( -- * Request GetBucketVersioning -- ** Request constructor , getBucketVersioning -- ** Request lenses , gbvBucket -- * Response , GetBucketVersioningResponse -- ** Response constructor , getBucketVersioningResponse -- ** Response lenses , gbvrMFADelete , gbvrStatus ) where import Network.AWS.Prelude import Network.AWS.Request.S3 import Network.AWS.S3.Types import qualified GHC.Exts newtype GetBucketVersioning = GetBucketVersioning { _gbvBucket :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'GetBucketVersioning' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gbvBucket' @::@ 'Text' -- getBucketVersioning :: Text -- ^ 'gbvBucket' -> GetBucketVersioning getBucketVersioning p1 = GetBucketVersioning { _gbvBucket = p1 } gbvBucket :: Lens' GetBucketVersioning Text gbvBucket = lens _gbvBucket (\s a -> s { _gbvBucket = a }) data GetBucketVersioningResponse = GetBucketVersioningResponse { _gbvrMFADelete :: Maybe MFADeleteStatus , _gbvrStatus :: Maybe BucketVersioningStatus } deriving (Eq, Read, Show) -- | 'GetBucketVersioningResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gbvrMFADelete' @::@ 'Maybe' 'MFADeleteStatus' -- -- * 'gbvrStatus' @::@ 'Maybe' 'BucketVersioningStatus' -- getBucketVersioningResponse :: GetBucketVersioningResponse getBucketVersioningResponse = GetBucketVersioningResponse { _gbvrStatus = Nothing , _gbvrMFADelete = Nothing } -- | Specifies whether MFA delete is enabled in the bucket versioning -- configuration. This element is only returned if the bucket has been -- configured with MFA delete. If the bucket has never been so configured, this -- element is not returned. gbvrMFADelete :: Lens' GetBucketVersioningResponse (Maybe MFADeleteStatus) gbvrMFADelete = lens _gbvrMFADelete (\s a -> s { _gbvrMFADelete = a }) -- | The versioning state of the bucket. gbvrStatus :: Lens' GetBucketVersioningResponse (Maybe BucketVersioningStatus) gbvrStatus = lens _gbvrStatus (\s a -> s { _gbvrStatus = a }) instance ToPath GetBucketVersioning where toPath GetBucketVersioning{..} = mconcat [ "/" , toText _gbvBucket ] instance ToQuery GetBucketVersioning where toQuery = const "versioning" instance ToHeaders GetBucketVersioning instance ToXMLRoot GetBucketVersioning where toXMLRoot = const (namespaced ns "GetBucketVersioning" []) instance ToXML GetBucketVersioning instance AWSRequest GetBucketVersioning where type Sv GetBucketVersioning = S3 type Rs GetBucketVersioning = GetBucketVersioningResponse request = get response = xmlResponse instance FromXML GetBucketVersioningResponse where parseXML x = GetBucketVersioningResponse <$> x .@? "MfaDelete" <*> x .@? "Status"
romanb/amazonka
amazonka-s3/gen/Network/AWS/S3/GetBucketVersioning.hs
mpl-2.0
4,125
0
9
862
524
314
210
63
1
import System.Plugins import System.Directory a = "Foo.hs" -- user code b = "Bar.hs" -- more user code z = "Stub.hs" -- and a stub main = do status <- makeWith a z [] s <- case status of MakeFailure e -> mapM_ putStrLn e >> error "failed" MakeSuccess n s -> print n >> return s status <- makeWith b z [] s' <- case status of MakeFailure e -> mapM_ putStrLn e >> error "failed" MakeSuccess n s -> print n >> return s -- shouldn't need to remerge (a,z) status <- makeWith a z [] t <- case status of MakeFailure e -> mapM_ putStrLn e >> error "failed" MakeSuccess n s -> print n >> return s -- shouldn't need to remerge (b,z) status <- makeWith b z [] t' <- case status of MakeFailure e -> mapM_ putStrLn e >> error "failed" MakeSuccess n s -> print n >> return s print $ s /= s' -- test we got unique modules print $ t /= t' -- test we got unique modules mapM_ makeCleaner [s,s']
abuiles/turbinado-blog
tmp/dependencies/hs-plugins-1.3.1/testsuite/makewith/multi_make/Main.hs
bsd-3-clause
1,137
0
12
439
350
162
188
25
5
main f g xs = map f (map g xs) map f xs = case xs of [] -> [] y:ys -> f y : map f ys
ndmitchell/tagsoup
test/TagSoup/Generate/programs/MapMap.hs
bsd-3-clause
97
0
9
40
72
34
38
4
2
module LayoutIn3a where --Layout rule applies after 'where','let','do' and 'of' --In this Example: rename 'x' after 'let' to 'anotherX'. foo x = let x = 12 in ( x ) where y = 2 --there is a comment. w = x where x = let y = 5 in y + 3
mpickering/ghc-exactprint
tests/examples/transform/LayoutIn3a.hs
bsd-3-clause
530
0
12
348
63
35
28
5
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Data.Conduit.Process.Unix ( -- * Process tracking -- $processTracker -- ** Types ProcessTracker -- ** Functions , initProcessTracker -- * Monitored process , MonitoredProcess , monitorProcess , terminateMonitoredProcess ) where import Control.Applicative ((<$>), (<*>)) import Control.Arrow ((***)) import Control.Concurrent (forkIO) import Control.Concurrent (threadDelay) import Control.Concurrent.MVar (MVar, modifyMVar, modifyMVar_, newEmptyMVar, newMVar, putMVar, readMVar, swapMVar, takeMVar) import Control.Exception (Exception, SomeException, bracketOnError, finally, handle, mask_, throwIO, try) import Control.Monad (void) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Conduit (Source, ($$)) import Data.Conduit.Binary (sinkHandle, sourceHandle) import qualified Data.Conduit.List as CL import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.Time (getCurrentTime) import Data.Time (diffUTCTime) import Data.Typeable (Typeable) import Foreign.C.Types import Prelude (Bool (..), Either (..), IO, Maybe (..), Monad (..), Show, const, error, map, maybe, show, ($), ($!), (*), (<), (==)) import System.Exit (ExitCode) import System.IO (hClose) import System.Posix.IO.ByteString ( closeFd, createPipe, fdToHandle) import System.Posix.Signals (sigKILL, signalProcess) import System.Posix.Types (CPid (..)) import System.Process (CmdSpec (..), CreateProcess (..), StdStream (..), createProcess, terminateProcess, waitForProcess) import System.Process.Internals (ProcessHandle (..), ProcessHandle__ (..)) processHandleMVar :: ProcessHandle -> MVar ProcessHandle__ #if MIN_VERSION_process(1, 2, 0) processHandleMVar (ProcessHandle m _) = m #else processHandleMVar (ProcessHandle m) = m #endif withProcessHandle_ :: ProcessHandle -> (ProcessHandle__ -> IO ProcessHandle__) -> IO () withProcessHandle_ ph io = modifyMVar_ (processHandleMVar ph) io -- | Kill a process by sending it the KILL (9) signal. -- -- Since 0.1.0 killProcess :: ProcessHandle -> IO () killProcess ph = withProcessHandle_ ph $ \p_ -> case p_ of ClosedHandle _ -> return p_ OpenHandle h -> do signalProcess sigKILL h return p_ ignoreExceptions :: IO () -> IO () ignoreExceptions = handle (\(_ :: SomeException) -> return ()) -- $processTracker -- -- Ensure that child processes are killed, regardless of how the parent process exits. -- -- The technique used here is: -- -- * Create a pipe. -- -- * Fork a new child process that listens on the pipe. -- -- * In the current process, send updates about processes that should be auto-killed. -- -- * When the parent process dies, listening on the pipe in the child process will get an EOF. -- -- * When the child process receives that EOF, it kills all processes it was told to auto-kill. -- -- This code was originally written for Keter, but was moved to unix-process -- conduit in the 0.2.1 release. foreign import ccall unsafe "launch_process_tracker" c_launch_process_tracker :: IO CInt foreign import ccall unsafe "track_process" c_track_process :: ProcessTracker -> CPid -> CInt -> IO () -- | Represents the child process which handles process cleanup. -- -- Since 0.2.1 newtype ProcessTracker = ProcessTracker CInt -- | Represents a child process which is currently being tracked by the cleanup -- child process. -- -- Since 0.2.1 data TrackedProcess = TrackedProcess !ProcessTracker !(IORef MaybePid) !(IO ExitCode) data MaybePid = NoPid | Pid !CPid -- | Fork off the child cleanup process. -- -- This will ideally only be run once for your entire application. -- -- Since 0.2.1 initProcessTracker :: IO ProcessTracker initProcessTracker = do i <- c_launch_process_tracker if i == -1 then throwIO CannotLaunchProcessTracker else return $! ProcessTracker i -- | Since 0.2.1 data ProcessTrackerException = CannotLaunchProcessTracker deriving (Show, Typeable) instance Exception ProcessTrackerException -- | Begin tracking the given process. If the 'ProcessHandle' refers to a -- closed process, no tracking will occur. If the process is closed, then it -- will be untracked automatically. -- -- Note that you /must/ compile your program with @-threaded@; see -- 'waitForProcess'. -- -- Since 0.2.1 trackProcess :: ProcessTracker -> ProcessHandle -> IO TrackedProcess trackProcess pt ph = mask_ $ do mpid <- readMVar $ processHandleMVar ph mpid' <- case mpid of ClosedHandle{} -> return NoPid OpenHandle pid -> do c_track_process pt pid 1 return $ Pid pid ipid <- newIORef mpid' baton <- newEmptyMVar let tp = TrackedProcess pt ipid (takeMVar baton) case mpid' of NoPid -> return () Pid _ -> void $ forkIO $ do waitForProcess ph >>= putMVar baton untrackProcess tp return $! tp -- | Explicitly remove the given process from the tracked process list in the -- cleanup process. -- -- Since 0.2.1 untrackProcess :: TrackedProcess -> IO () untrackProcess (TrackedProcess pt ipid _) = mask_ $ do mpid <- readIORef ipid case mpid of NoPid -> return () Pid pid -> do c_track_process pt pid 0 writeIORef ipid NoPid -- | Fork and execute a subprocess, sending stdout and stderr to the specified -- rotating log. -- -- Since 0.2.1 forkExecuteLog :: ByteString -- ^ command -> [ByteString] -- ^ args -> Maybe [(ByteString, ByteString)] -- ^ environment -> Maybe ByteString -- ^ working directory -> Maybe (Source IO ByteString) -- ^ stdin -> (ByteString -> IO ()) -- ^ both stdout and stderr will be sent to this location -> IO ProcessHandle forkExecuteLog cmd args menv mwdir mstdin rlog = bracketOnError setupPipe cleanupPipes usePipes where setupPipe = bracketOnError createPipe (\(x, y) -> closeFd x `finally` closeFd y) (\(x, y) -> (,) <$> fdToHandle x <*> fdToHandle y) cleanupPipes (x, y) = hClose x `finally` hClose y usePipes pipes@(readerH, writerH) = do (min, _, _, ph) <- createProcess CreateProcess { cmdspec = RawCommand (S8.unpack cmd) (map S8.unpack args) , cwd = S8.unpack <$> mwdir , env = map (S8.unpack *** S8.unpack) <$> menv , std_in = maybe Inherit (const CreatePipe) mstdin , std_out = UseHandle writerH , std_err = UseHandle writerH , close_fds = True , create_group = True #if MIN_VERSION_process(1, 2, 0) , delegate_ctlc = False #endif } ignoreExceptions $ addAttachMessage pipes ph void $ forkIO $ ignoreExceptions $ (sourceHandle readerH $$ CL.mapM_ rlog) `finally` hClose readerH case (min, mstdin) of (Just h, Just source) -> void $ forkIO $ ignoreExceptions $ (source $$ sinkHandle h) `finally` hClose h (Nothing, Nothing) -> return () _ -> error $ "Invariant violated: Data.Conduit.Process.Unix.forkExecuteLog" return ph addAttachMessage pipes ph = withProcessHandle_ ph $ \p_ -> do now <- getCurrentTime case p_ of ClosedHandle ec -> do rlog $ S8.concat [ "\n\n" , S8.pack $ show now , ": Process immediately died with exit code " , S8.pack $ show ec , "\n\n" ] cleanupPipes pipes OpenHandle h -> do rlog $ S8.concat [ "\n\n" , S8.pack $ show now , ": Attached new process " , S8.pack $ show h , "\n\n" ] return p_ data Status = NeedsRestart | NoRestart | Running ProcessHandle -- | Run the given command, restarting if the process dies. monitorProcess :: (ByteString -> IO ()) -- ^ log -> ProcessTracker -> Maybe S8.ByteString -- ^ setuid -> S8.ByteString -- ^ executable -> S8.ByteString -- ^ working directory -> [S8.ByteString] -- ^ command line parameter -> [(S8.ByteString, S8.ByteString)] -- ^ environment -> (ByteString -> IO ()) -> (ExitCode -> IO Bool) -- ^ should we restart? -> IO MonitoredProcess monitorProcess log processTracker msetuid exec dir args env' rlog shouldRestart = do mstatus <- newMVar NeedsRestart let loop mlast = do next <- modifyMVar mstatus $ \status -> case status of NoRestart -> return (NoRestart, return ()) _ -> do now <- getCurrentTime case mlast of Just last | diffUTCTime now last < 5 -> do log $ "Process restarting too quickly, waiting before trying again: " `S8.append` exec threadDelay $ 5 * 1000 * 1000 _ -> return () let (cmd, args') = case msetuid of Nothing -> (exec, args) Just setuid -> ("sudo", "-E" : "-u" : setuid : "--" : exec : args) res <- try $ forkExecuteLog cmd args' (Just env') (Just dir) (Just $ return ()) rlog case res of Left e -> do log $ "Data.Conduit.Process.Unix.monitorProcess: " `S8.append` S8.pack (show (e :: SomeException)) return (NeedsRestart, return ()) Right pid -> do log $ "Process created: " `S8.append` exec return (Running pid, do TrackedProcess _ _ wait <- trackProcess processTracker pid ec <- wait shouldRestart' <- shouldRestart ec if shouldRestart' then loop (Just now) else return ()) next _ <- forkIO $ loop Nothing return $ MonitoredProcess mstatus -- | Abstract type containing information on a process which will be restarted. newtype MonitoredProcess = MonitoredProcess (MVar Status) -- | Terminate the process and prevent it from being restarted. terminateMonitoredProcess :: MonitoredProcess -> IO () terminateMonitoredProcess (MonitoredProcess mstatus) = do status <- swapMVar mstatus NoRestart case status of Running pid -> do terminateProcess pid threadDelay 1000000 killProcess pid _ -> return ()
telser/keter
Data/Conduit/Process/Unix.hs
mit
12,780
2
32
4,992
2,560
1,376
1,184
234
6
module Sum where import Prelude hiding (sum) fun1 = x + x sum c [] = 0 sum c ((h : t)) = c h (sum c t) main = sum (+) [1 .. 4]
kmate/HaRe
old/testing/generaliseDef/Sum_AstOut.hs
bsd-3-clause
132
0
8
40
85
48
37
6
1
import StackTest main :: IO () main = do stackErr ["build", "files-3"] stackErr ["build", "files-0.1.0.0"] stack ["build", "files"] stack ["build", "."]
AndreasPK/stack
test/integration/tests/606-local-version-not-exist/Main.hs
bsd-3-clause
170
0
8
38
67
34
33
7
1
{-# LANGUAGE RoleAnnotations #-} module T10285a (N, coercion) where import Data.Type.Coercion newtype N a = MkN Int type role N representational coercion :: Coercion (N a) (N b) coercion = Coercion
urbanslug/ghc
testsuite/tests/typecheck/should_fail/T10285a.hs
bsd-3-clause
202
0
7
35
61
37
24
7
1
import Control.Exception as E import Data.IORef import System.Mem.Weak import Control.Concurrent main :: IO () main = do ref <- newIORef 'x' weak <- mkWeakIORef ref $ putStrLn "IORef finalized" let check = deRefWeak weak >>= \m -> case m of Nothing -> putStrLn "IORef was GCed" Just ref' -> do x <- readIORef ref' putStrLn $ "IORef still alive, and contains " ++ show x m <- newEmptyMVar check takeMVar m `catch` \ex -> do putStrLn $ "caught exception: " ++ show (ex :: SomeException) check readIORef ref >>= print
urbanslug/ghc
testsuite/tests/concurrent/should_run/T7970.hs
bsd-3-clause
616
0
18
191
193
92
101
19
2
module Main where fizzbuzz :: (Show a, Integral a) => a -> String fizzbuzz n | fizz == 0 && buzz == 0 = "FizzBuzz" | fizz == 0 = "Fizz" | buzz == 0 = "Buzz" | otherwise = show n where fizz = n `mod` 3 buzz = n `mod` 5 main = do putStrLn "Fizzbuzz 3:" putStrLn $ fizzbuzz 3 putStrLn "Fizzbuzz 5:" putStrLn $ fizzbuzz 5 putStrLn "Fizzbuzz 15:" putStrLn $ fizzbuzz 15 putStrLn "Fizzbuzz 50:" putStrLn $ fizzbuzz 50 putStrLn "Fizzbuzz 113:" putStrLn $ fizzbuzz 113
archdragon/haskell_exercises
fizz_buzz/fizz_buzz.hs
mit
500
0
10
130
201
93
108
20
1
{-# LANGUAGE ForeignFunctionInterface #-} module System.Environment.FindBin ( __Bin__ , getProgPath ) where import Foreign (Ptr, alloca, peek, peekElemOff) import Foreign.C (CInt, CString, peekCString) import System.Directory (canonicalizePath, findExecutable) import System.FilePath (takeDirectory, takeBaseName) import System.IO.Unsafe (unsafePerformIO) {-# NOINLINE __Bin__ #-} -- | Unsafe (/constant/) version of 'getProgPath'. __Bin__ :: String __Bin__ = let path = unsafePerformIO getProgPath in length path `seq` path -- | Get the full directory to the running program. getProgPath :: IO String getProgPath = alloca $ \p_argc -> alloca $ \p_argv -> do getProgArgv p_argc p_argv argv <- peek p_argv arg0 <- peekCString =<< peekElemOff argv 0 case arg0 of "<interactive>" -> alloca $ \p_argc' -> alloca $ \p_argv' -> do getFullProgArgv p_argc' p_argv' argc' <- peek p_argc' argv' <- peek p_argv' findBin =<< peekCString =<< peekElemOff argv' (pred $ fromEnum argc') _ -> do findBin arg0 where directoryOf "" = directoryOf "." directoryOf x = do x' <- canonicalizePath x let path = takeDirectory x' return (length path `seq` path) findBin s = case takeDirectory s of "" -> do -- This should work for ghci as well, as long as nobody name -- their executable file "<interactive>"... rv <- findExecutable s case rv of Just fullName -> directoryOf fullName _ -> alloca $ \p_argc' -> alloca $ \p_argv' -> do -- Here we are in the "runghc"/"runhaskell" land. Fun! getFullProgArgv p_argc' p_argv' argc' <- peek p_argc' argv' <- peek p_argv' prog <- peekCString =<< peekElemOff argv' 0 s' <- case takeBaseName prog of "runghc" -> peekCString =<< peekElemOff argv' (fromEnum argc'-1) "runhaskell" -> peekCString =<< peekElemOff argv' (fromEnum argc'-1) _ -> return prog canon <- canonicalizePath s canon' <- canonicalizePath s' if canon == canon' then findBin canon else findBin s' _ -> directoryOf s foreign import ccall unsafe "getFullProgArgv" getFullProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO () foreign import ccall unsafe "getProgArgv" getProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()
audreyt/findbin
src/System/Environment/FindBin.hs
mit
2,686
0
29
911
667
328
339
55
8
{-# htermination realToFrac :: Int -> Float #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_realToFrac_2.hs
mit
48
0
2
8
3
2
1
1
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeSynonymInstances #-} module Gate where import BigGate import Data.Bits import NotGate import Types -- type GateCounter = [Int] andGate :: SecureGate andGate = bigGate AND orGate :: SecureGate orGate = bigGate OR xorGate :: SecureGate xorGate = bigGate XOR instance Eq Literal where (==) = undefined (/=) = undefined instance Bits SecureNum where (.&.) = zipWith andGate (.|.) = zipWith orGate xor = zipWith xorGate complement = map notGate shiftL xs num = drop num xs ++ map ( const $ Constant False) [0 .. num -1] shiftR xs num = map ( const $ Constant False) [0 .. num -1] ++ take num xs rotate = undefined -- rotate x st = take ( length st) $ drop ( negate x ` mod` length st) $ cycle st isSigned _ = False testBit = undefined bit _ = undefined popCount = undefined bitSize = length bitSizeMaybe a = Just $ length a
ur-crypto/sec-lib
library/Gate.hs
mit
1,049
0
10
313
267
147
120
31
1
{-# htermination denominator :: Ratio Int -> Int #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_denominator_1.hs
mit
53
0
2
9
3
2
1
1
0
module Paradox.Instantiate where {- Paradox -- Copyright (c) 2003-2007, Koen Claessen, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} import Form hiding ( Form(..) ) import Name import Flags import qualified Data.Set as S import Data.List hiding ( insert, delete, union ) ------------------------------------------------------------------------- -- clause sets data ClauseSet = ForAll [Clause] | ForAllNew Int [Clause] deriving (Show, Eq) elt :: Int -> Symbol elt = \i -> (el % i) ::: ([] :-> top) isElt :: Symbol -> Bool isElt (c ::: _) = isEltName c ------------------------------------------------------------------------- -- instantiate instantiate :: Flags -> [(Type,Int)] -> [Clause] -> [QClause] -> [(Symbol,[ClauseSet])] instantiate flags predefs cs qcs = [ (assump, ForAll symcs : cs) | ((assump,cs),symcs) <- parts 1 [] patterns nonGroundCs `zip` symmetries ] where (groundCs, nonGroundCs) = partition isGround (sortBy siz cs) where c1 `siz` c2 = length c1 `compare` length c2 iqcs = [1..] `zip` qcs syms = symbols cs isGround c = S.size (free c) == 0 con k = Fun (elt k) [] symmetries :: [[Clause]] symmetries = transp [ symmForType tp predef | (tp,predef) <- predefs ] where transp [] = repeat [] transp xss = concat [ x | x:_ <- xss ] : transp [ xs | _:xs <- xss ] symmForType tp predef = zipWith (\k f -> f k) [1..] -- do not use symmetries before predef size $ replicate predef (\_ -> []) -- constant-triangle ++ [ \k -> [ [ Pos (t :=: con i) | i <- [1..k] ] ] | t <- allCons ] -- predicate-symmetries ++ [ \k -> if k <= predef then error "predef???" else [] | not (null allUnitPreds)] ++ concat [ repeat $ \k -> [ [ Neg (p `prd` [con k]) , Pos (p `prd` [con (k-1)]) ] ] | (p:_) <- [allUnitPreds] ] -- function-symmetries ++ concat [ repeat $ \k -> [ c | k > n , c <- [ [ Pos ((Fun f [con (k-j) | j <- [1..n]]) :=: con i) | i <- [1..k] ] ] ++ [ Neg ((Fun f [con (k-1)]) :=: con k) : Neg ((Fun f [con (k-2)]) :=: con (k-1)) : [ Pos (Fun f [con j] :=: con (k-2)) | j <- [numCons..k-2] , j > 0 ] | k > ((numCons + 2) `max` 3) , n == 1 ] ] | ((f,n):_) <- [allFuns] , n > 0 ] where numCons = predef + length allCons allCons = [ t | Uniq (Bind v c) <- qcs , [Pos (t@(Fun f []) :=: Var v')] <- [c] , v == v' , typ t == tp ] allFuns = sortBy cmp [ (f,length xs) | Uniq (Bind v c) <- qcs , [Pos (t@(Fun f (xs@(_:_))) :=: Var v')] <- [c] , v == v' , typ t == tp ] where (_,x) `cmp` (_,y) = x `compare` y allUnitPreds = [ p | p@(_ ::: ([tp'] :-> b)) <- S.toList syms , b == bool , tp' == tp ] parts :: Int -> [Term] -> [[Bool]] -> [Clause] -> [(Symbol,[ClauseSet])] parts k oldCons (pat:pats) cs = (dom, clauses) : parts (k+1) allCons pats (extra ++ cs) where dom = (dm % k) ::: ([] :-> bool) domk = dom `prd` [] newCon = con k allCons = newCon : oldCons qclauses = [ c | (i,qc) <- iqcs , c <- atMostOne i qc ] extra = [ c | c <- qclauses , not (isGround c) ] clauses = [ ForAll ( -- constant equalities [ [ Pos (newCon :=: newCon) ] ] ++ concat [ [ [ Neg (c :=: newCon) ] , [ Neg (newCon :=: c) ] ] | c <- oldCons ] -- ground clauses (only if k == 1) ++ [ c | k == 1 , c <- groundCs ] ) , ForAllNew k ( -- instantiate clauses cs ) , ForAll ( -- uniqueness clauses [ c | qc <- qcs , c <- atLeastOne qc ] ++ qclauses ) ] atLeastOne :: QClause -> [Clause] atLeastOne (Uniq (Bind v@(_ ::: V tp) c)) = [ pre [ l | a <- allCons , l <- subst (v |=> a) c ] | pre <- case tdomain tp of Just k' | k' == k -> [id] | k > k' -> [] _ -> [(Neg domk :)] ] atMostOne :: Int -> QClause -> [Clause] atMostOne i (Uniq (Bind v@(_ ::: V tp) c)) = [ [negat l, a] | case tdomain tp of Just k' | k > k' -> False _ -> True , l <- ls , a <- pattern i ] where ls = subst (v |=> newCon) c vs = S.toList (v `S.delete` free c) uni i j = (un % i % j ::: (map typ xs :-> bool)) `prd` xs xs = map Var vs pattern i = [ sgn (uni i j) | (j,b) <- [0..] `zip` pat , let sgn = if b then Pos else Neg ] -- unique non-empty non-overlapping infinite list of 0/1 patterns patterns :: [[Bool]] patterns = pats 4 where pats n = init base ++ map (last base ++) (pats (n+1)) where base = bits n bits 0 = [[]] bits k = [ False : bs | bs <- bits (k-1) ] ++ [ True : bs | bs <- bits (k-1) ] ------------------------------------------------------------------------- -- the end.
msakai/folkung
Haskell/Paradox/Instantiate.hs
mit
6,877
0
29
2,715
2,303
1,242
1,061
148
6
{-# LANGUAGE ViewPatterns #-} module FunctorLaws ( functorCompose' ) where import Test.QuickCheck import Test.QuickCheck.Function functorCompose'::(Eq (f c), Functor f) => f a -> Fun a b -> Fun b c -> Bool functorCompose' x (Fun _ f) (Fun _ g) = (fmap (g . f) x) == (fmap g . fmap f $ x)
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/Chapter16.hsproj/FunctorLaws.hs
mit
296
0
9
62
136
71
65
7
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Lib where import Control.Applicative import Database.SQLite.Simple import qualified Data.Text as T import Web.Scotty import Network.Wai.Middleware.RequestLogger import Control.Monad.IO.Class import Data.Aeson hiding(json) import GHC.Generics import Prelude hiding (id) data Todo = Todo { id :: Maybe Int , task :: T.Text , done :: Bool } deriving (Show,Generic) instance FromRow Todo where fromRow = Todo <$> field <*> field <*> field instance ToRow Todo where toRow (Todo a b c) = toRow (a, b, c) instance ToJSON Todo where toEncoding = genericToEncoding defaultOptions instance FromJSON Todo setCssHeader :: ActionM () setCssHeader = setHeader "Content-Type" "text/css" --run :: IO () main = do conn <- open "todo.db" execute_ conn "create table if not exists TODOS (id integer primary key not null, task text not null, done integer not null)" execute conn "delete from TODOS where id = ?" (Only (1::Int)) executeNamed conn "update TODOS set task = :task" [":task" := ("teste" ::T.Text)] scotty 3000 $ do middleware logStdoutDev get "/" $ file "src/index.html" get "/w3.css" $ setCssHeader >> file "src/w3.css" get "/w3-theme-teal.css" $ setCssHeader >> file "src/w3-theme-teal.css" get "/style.css" $ setCssHeader >> file "src/style.css" get "/jquery-2.2.4.min.js" $ file "src/jquery-2.2.4.min.js" get "/angular.min.js" $ file "src/angular.min.js" get "/todo.js" $ file "src/todo.js" --windows: --curl -H "Content-Type: application/json" -X POST -d "{\"todo\": {\"id\":null, \"task\": \"teste\", \"done\": 1}}" http://localhost:3000/todos --linux: --curl -H "Content-Type: application/json" -X POST -d '{"id":null, "task": "teste", "done": 1}' http://localhost:3000/todos post "/todos" $ do todo <- jsonData :: ActionM Todo liftIO $ execute conn "insert into TODOS(id, task, done) values(?, ?, ?)" todo newId <- liftIO $ lastInsertRowId conn >>= return . fromIntegral json (newId :: Int) --curl -H "Content-Type: application/json" -X PUT -d "{\"id\":1, \"task\": \"teste\", \"done\": true}" http://localhost:3000/todos/1 put "/todos/:id" $ do a <- param "id" :: ActionM Int todo <- jsonData :: ActionM Todo let b = task todo c = done todo ns = [":id" := a, ":task" := b, ":done" := c] liftIO $ executeNamed conn "update TODOS set task = :task, done = :done where id = :id" ns json todo get "/todos/:id" $ do id <- param "id" html $ id delete "/todo" $ do id <- param "id" :: ActionM Int liftIO $ execute conn "delete from TODOS where id = ?" (Only id) return ()
jean-lopes/todo
src/Lib.hs
mit
3,075
0
17
915
670
328
342
59
1
-- file ch03/ex06.hs -- Create a function that sorts a list of lists based on the length of each -- sublist. (You may want to look at the sortBy function from the Data.List -- module.) import Data.List longer :: [a] -> [b] -> Ordering longer a b | length(a) > length(b) = GT | length(a) < length(b) = LT | length(a) == length(b) = EQ listsort :: (Ord a) => [[a]] -> [[a]] listsort [] = [] listsort list = sortBy longer list
imrehg/rwhaskell
ch03/ex06.hs
mit
451
0
10
110
166
87
79
8
1
{-# OPTIONS_HADDOCK hide, prune #-} {-# Language CPP #-} module Foundation ( module Foundation , parseSqlKey ) where #if DEVELOPMENT import qualified Prelude import qualified Language.Haskell.TH as TH import qualified Language.Haskell.TH.Quote as TH #endif import Control.Concurrent.STM.TChan import qualified Data.Text as Text import qualified Data.Map as Map import Yesod.Auth.LdapNative import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool, toSqlKey, fromSqlKey, Single (..), rawSql) import qualified Network.Mail.Mime as Mail import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Text.Shakespeare.Text (stext) import Yesod.Auth.Email import Yesod.Auth.Message (AuthMessage (..)) import Yesod.Default.Util (addStaticContentExternal) import Yesod.Core.Types (Logger) import qualified Yesod.Core.Unsafe as Unsafe import Data.Text.Read (decimal) import System.Directory (createDirectoryIfMissing) import Text.Blaze (Markup) import Handler.Mooc.EdxLogin import Model.Session import Application.Edx -- | The foundation datatype for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { appSettings :: AppSettings , appStatic :: Static -- ^ Settings for static file serving. , appConnPool :: ConnectionPool -- ^ Database connection pool. , appHttpManager :: Manager , appLogger :: Logger , appWSChan :: TChan Text } -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the following documentation -- for an explanation for this split: -- http://www.yesodweb.com/book/scaffolding-and-the-site-template#scaffolding-and-the-site-template_foundation_and_application_modules -- -- This function also generates the following type synonyms: -- type Handler = HandlerT App IO -- type Widget = WidgetT App IO () #if DEVELOPMENT mkYesodData "App" $(do routes <- TH.runIO $ do a <- Prelude.readFile "config/routes" b <- Prelude.readFile "config/routes.dev" return $ Prelude.unlines [a,b] TH.quoteExp parseRoutes routes ) #else mkYesodData "App" $(parseRoutesFile "config/routes") #endif -- | A convenient synonym for creating forms. type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where -- Controls the base of generated URLs. For more information on modifying, -- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot approot = ApprootRequest $ \app req -> fromMaybe (getApprootText guessApproot app req) (appRoot $ appSettings app) -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = do liftIO $ createDirectoryIfMissing True "config" Just <$> defaultClientSessionBackend 43200 -- timeout in minutes "config/client_session_key.aes" -- Yesod Middleware allows you to run code before and after each handler function. -- The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks. -- Some users may also want to add the defaultCsrfMiddleware, which: -- a) Sets a cookie with a CSRF token in it. -- b) Validates that incoming write requests include that token in either a header or POST parameter. -- For details, see the CSRF documentation in the Yesod.Core.Handler module of the yesod-core package. yesodMiddleware = defaultYesodMiddleware defaultLayout widget = do -- master <- getYesod mmsg <- getMessage muser <- fmap entityVal <$> maybeAuth siteMenu <- pageBody <$> widgetToPageContent $(widgetFile "site-menu") -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent widget -- pc <- widgetToPageContent $ do -- addStylesheet $ StaticR css_bootstrap_css -- (widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/site-layout.hamlet") -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR -- Routes not requiring authentication. isAuthorized (AuthR _) _ = return Authorized isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized isAuthorized AdminR _ = do role <- muserRole <$> maybeAuth return $ if role == UR_ADMIN then Authorized else Unauthorized "You need admin rights to access this page." isAuthorized CompareProposalsR _ = do iAmHere <- (Nothing /=) <$> maybeAuthId return $ if iAmHere then Authorized else Unauthorized "Only logged-in users can access this page" -- Default to Authorized for now. isAuthorized _ _ = return Authorized -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger maximumContentLength _ _ = Just 4000000 fullLayout :: Maybe Markup -> Text -> Widget -> Handler Html fullLayout mmsgIcon defaultMsg widget = do mmsg <- getMessage muser <- fmap entityVal <$> maybeAuth siteMenu <- pageBody <$> widgetToPageContent $(widgetFile "site-menu") pc <- widgetToPageContent widget withUrlRenderer $(hamletFile "templates/site-layout-full.hamlet") adminLayout :: Text -> Widget -> Handler Html adminLayout defaultMsg widget = do mmsg <- getMessage muser <- fmap entityVal <$> maybeAuth siteMenu <- pageBody <$> widgetToPageContent $(widgetFile "site-menu") pc <- widgetToPageContent widget withUrlRenderer $(hamletFile "templates/site-layout-admin.hamlet") minimalLayout :: Widget -> Handler Html minimalLayout widget = do muser <- fmap entityVal <$> maybeAuth siteMenu <- pageBody <$> widgetToPageContent $(widgetFile "site-menu") pc <- widgetToPageContent widget withUrlRenderer $(hamletFile "templates/site-layout-minimal.hamlet") -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = MoocHomeR -- Where to send a user after logout logoutDest _ = MoocHomeR onLogout = clearSession -- Override the above two destinations when a Referer: header is present redirectToReferer _ = True -- authenticatin using ldap plugin authenticate creds@Creds{credsPlugin = "ldap"} = runDB $ do x <- getBy . ETHUserName . Just $ credsIdent creds case x of Just (Entity uid _) -> return $ Authenticated uid Nothing -> Authenticated <$> insert User { userName = credsIdent creds , userRole = UR_LOCAL , userEthUserName = Just $ credsIdent creds , userEdxUserId = Nothing , userEmail = Nothing , userPassword = Nothing , userVerified = True } authenticate creds@Creds{credsPlugin = "lti"} = do uid <- runDB $ do x <- getBy . EdxUserId . Just $ credsIdent creds case x of Just (Entity uid _) -> return uid Nothing -> insert User { userName = "anonymous edX student" , userRole = UR_STUDENT , userEthUserName = Nothing , userEdxUserId = Just $ credsIdent creds , userEmail = Nothing , userPassword = Nothing , userVerified = True } setupEdxGrading uid (credsExtra creds) case Map.lookup "custom_exercise_type" (Map.fromList $ credsExtra creds) of Just "design" -> setUltDest RedirectToQuaViewEditR Just "compare" -> setUltDest CompareProposalsR _ -> return () return $ Authenticated uid authenticate Creds{credsPlugin = "temporary"} = do uid <- runDB $ insert User { userName = "Anonymous user" , userRole = UR_STUDENT , userEthUserName = Nothing , userEdxUserId = Nothing , userEmail = Nothing , userPassword = Nothing , userVerified = False } return $ Authenticated uid -- use Yesod.Auth.Email plugin, -- also for legacy usernames that are stored in the email column: -- Look at https://hackage.haskell.org/package/yesod-auth-1.4.19/docs/src/Yesod-Auth-Email.html#postLoginR -- according to that page, 'credsPlugin' record of creds can be one of -- "email", "email-verified", "username", or who knows what else. -- That is why we need this weird check below. authenticate creds@(Creds cPlugin _ _) | "email" `isPrefixOf` cPlugin || "username" == cPlugin = runDB $ do x <- getBy . UserEmailId . Just $ credsIdent creds return $ case x of Just (Entity uid _) -> Authenticated uid Nothing -> UserError AuthError authenticate _ = do return $ UserError AuthError -- You can add other plugins like Google Email, email or OAuth here authPlugins ye = [ authLdapWithForm ldapConf $ \ldapLoginR -> $(widgetFile "login-ethz") , authLtiPlugin (appLTICredentials $ appSettings ye) , authEmail] authHttpManager = getHttpManager ldapConf :: LdapAuthConf ldapConf = setHost (Secure "isla.ethz.ch") $ setPort 636 $ mkLdapConf Nothing "cn=users,dc=isla,dc=ethz,dc=ch" instance YesodAuthPersist App instance YesodAuthEmail App where type AuthEmailId App = UserId afterPasswordRoute _ = RedirectToQuaViewEditR confirmationEmailSentResponse email = do setMessage $ "A confirmain email has been sent. Please, check your mailbox." setCreds False $ Creds "email" email [] mscId <- maybeEnroll redirect $ case mscId of Nothing -> MoocHomeR Just _ -> RedirectToQuaViewEditR addUnverified email verkey = do uid <- runDB $ do uid <- insert User { userName = takeWhile (/= '@') email , userRole = UR_NOBODY , userEthUserName = Nothing , userEdxUserId = Nothing , userEmail = Just email , userPassword = Nothing , userVerified = False } _ <- insert $ UserProp uid "verkey" verkey return uid maybeSetRoleBasedOnParams uid pure uid -- this function must not log-in user, -- because it is actually used by admin user too! -- (it would lead to admin being re-logged-in as as the new user) sendVerifyEmail email _ verurl = do -- Print out to the console the verification email, for easier -- debugging. $(logDebug) $ "Copy/ Paste this URL in your browser: " <> verurl -- Send email. mailFrom <- appMailFrom _ <- fork $ catch (liftIO . Mail.renderSendMail $ Mail.simpleMail' (Mail.Address Nothing email) -- To address mailFrom "Please validate your email address" -- Subject [stext| Please confirm your email address by clicking on the link below. #{verurl} Thank you |] ) (\e -> $(logWarn) $ "[EMAIL REGISTRATION] Could not send an email: " <> Text.pack (show (e :: SomeException))) pure () -- setCreds False $ Creds "email" email [] -- mscId <- maybeEnroll -- setUltDest $ case mscId of -- Nothing -> MoocHomeR -- Just _ -> RedirectToQuaViewEditR getVerifyKey uid = runDB $ do mup <- getBy $ UserProperty uid "verkey" return $ case mup of (Just (Entity _ u)) -> Just $ userPropValue u _ -> Nothing setVerifyKey uid key = runDB $ do _ <- upsertBy (UserProperty uid "verkey") (UserProp uid "verkey" key) [UserPropValue =. key] return () verifyAccount uid = runDB $ do mu <- get uid case mu of Nothing -> return Nothing Just _ -> do update uid [UserVerified =. True] return $ Just uid getPassword = runDB . fmap (join . fmap userPassword) . get setPassword uid pass = runDB $ do update uid [UserPassword =. Just pass] -- set verkey to empty string to prevent reuse void $ upsertBy (UserProperty uid "verkey") (UserProp uid "verkey" "") [UserPropValue =. ""] getEmailCreds email = runDB $ do mu <- getBy $ UserEmailId (Just email) case mu of Nothing -> return Nothing Just (Entity uid u) -> do mup <- getBy $ UserProperty uid "verkey" return $ Just $ EmailCreds { emailCredsId = uid , emailCredsAuthId = Just uid , emailCredsStatus = isJust $ userPassword u , emailCredsVerkey = fmap (userPropValue . entityVal) mup , emailCredsEmail = email } getEmail = runDB . fmap (join . fmap userEmail) . get emailLoginHandler toParent = $(widgetFile "login-local") registerHandler = do let extraParam key = do mr <- lookupGetParam key pure $ (,) key <$> mr extraParams <- mapM extraParam ["exercise", "invitation-secret"] toParRt <- getRouteToParent let allowTempUserOption = all isJust extraParams (widget, _) <- lift $ generateFormPost $ registrationForm (catMaybes extraParams) toParRt allowTempUserOption lift $ authLayout widget where registrationForm extraFields toParentRoute allowTempUserOption extra = do let emailSettings = FieldSettings { fsLabel = SomeMessage ("E-Mail"::Text), fsTooltip = Nothing, fsId = Just "email", fsName = Just "email", fsAttrs = [("autofocus", ""), ("class", "form-control")] } (emailRes, emailView) <- mreq emailField emailSettings Nothing let widget = $(widgetFile "register-local") return (emailRes, widget) setPasswordHandler needOldPw = do messageRender <- lift getMessageRender toParent <- getRouteToParent selectRep $ do provideJsonMessage $ messageRender ("Set password"::Text) provideRep $ lift $ authLayout $ do (widget, _) <- liftWidgetT $ generateFormPost (setPasswordForm toParent needOldPw) widget where setPasswordForm toParent needOld extra = do (currentPasswordRes, currentPasswordView) <- mreq passwordField currentPasswordSettings Nothing (newPasswordRes, newPasswordView) <- mreq passwordField newPasswordSettings Nothing (confirmPasswordRes, confirmPasswordView) <- mreq passwordField confirmPasswordSettings Nothing let passwordFormRes = PasswordForm <$> currentPasswordRes <*> newPasswordRes <*> confirmPasswordRes let widget = $(widgetFile "set-password-local") return (passwordFormRes, widget) currentPasswordSettings = FieldSettings { fsLabel = SomeMessage ("Current password"::Text), fsTooltip = Nothing, fsId = Just "currentPassword", fsName = Just "current", fsAttrs = [("autofocus", ""), ("class", "form-control")] } newPasswordSettings = FieldSettings { fsLabel = SomeMessage ("New password"::Text), fsTooltip = Nothing, fsId = Just "newPassword", fsName = Just "new", fsAttrs = [ ("autofocus", "") , (":not", ""), ("needOld:autofocus", "") , ("class", "form-control") ] } confirmPasswordSettings = FieldSettings { fsLabel = SomeMessage ("Confirm password"::Text), fsTooltip = Nothing, fsId = Just "confirmPassword", fsName = Just "confirm", fsAttrs = [("autofocus", ""), ("class", "form-control")] } data PasswordForm = PasswordForm { _passwordCurrent :: Text, _passwordNew :: Text, _passwordConfirm :: Text } -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage -- Useful when writing code that is re-usable outside of the Handler context. -- An example is background jobs that send email. -- This can also be useful for writing code that works across multiple Yesod applications. instance HasHttpManager App where getHttpManager = appHttpManager unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger -- Note: Some functionality previously present in the scaffolding has been -- moved to documentation in the Wiki. Following are some hopefully helpful -- links: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email -- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain -- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding muserRole :: Maybe (Entity User) -> UserRole muserRole Nothing = UR_NOBODY muserRole (Just (Entity _ u)) = userRole u -- | Get two capital characters out of a name twoCharsName :: Text -> Text twoCharsName s = case filter (not . null) $ Text.words s of [name] -> Text.toUpper $ Text.take 2 name n1:n2:_ -> Text.toUpper $ Text.take 1 n1 <> Text.take 1 n2 _ -> "??" requireSession :: Text -> Text -> Handler Text requireSession pam errstr = lookupSession pam >>= \mv -> case mv of Nothing -> invalidArgsI [errstr] Just v -> return v requirePostParam :: Text -> Text -> Handler Text requirePostParam pam errstr = lookupPostParam pam >>= \mv -> case mv of Nothing -> invalidArgsI [errstr] Just v -> return v getCurrentExercise :: Handler ExerciseId getCurrentExercise = do mtExId <- lookupSession "custom_exercise_id" maxExId <- runDB lastExerciseId return $ case decimal <$> mtExId of Just (Right (i, _)) -> toSqlKey i _ -> maxExId submissionR :: CurrentScenario -> Route App submissionR cSc = SubmissionR (currentScenarioExerciseId cSc) (currentScenarioAuthorId cSc) submissionPreviewR :: CurrentScenario -> Route App submissionPreviewR cSc = ProposalPreviewR (currentScenarioExerciseId cSc) (currentScenarioAuthorId cSc) lastExerciseId :: ReaderT SqlBackend Handler ExerciseId lastExerciseId = getVal <$> rawSql query [] where getVal (Single c:_) = c getVal [] = toSqlKey 0 query = unlines ["SELECT max(id) FROM exercise;" ] maybeSetRoleBasedOnParams :: UserId -> Handler () maybeSetRoleBasedOnParams userId = do runDB $ update userId [UserRole =. UR_STUDENT] maybeEnroll :: Handler (Maybe ExerciseId) maybeEnroll = do mExId <- checkInvitationParams musrId <- maybeAuthId -- This is Nothing! $(logDebug) $ "New user: " <> tshow (mExId, musrId) case (mExId, musrId) of (Just exId, Just usrId) -> do $(logDebug) $ "Enrolling new user in exercise " <> tshow (fromSqlKey exId) setSafeSession userSessionCurrentExerciseId exId time <- liftIO getCurrentTime void $ runDB $ upsert (UserExercise usrId exId time) [ UserExerciseUserId =. usrId , UserExerciseExerciseId =. exId , UserExerciseEnrolled =. time] _ -> pure () return mExId invitationParams :: ExerciseId -> Handler [(Text, Text)] invitationParams spId = do sp <- runDB $ get404 spId pure [("exercise", tshow $ fromSqlKey spId), ("invitation-secret", exerciseInvitationSecret sp)] checkInvitationParams :: Handler (Maybe ExerciseId) checkInvitationParams = do mid <- (>>= parseSqlKey) <$> lookupPostParam "exercise" case mid of Nothing -> pure Nothing Just spId -> do sp <- runDB $ get404 spId is <- lookupPostParam "invitation-secret" pure $ if Just (exerciseInvitationSecret sp) == is then Just spId else Nothing postTempUserR :: Handler Html postTempUserR = do setCreds False $ Creds "temporary" "Anonymous user" [] _ <- maybeEnroll redirect RedirectToQuaViewEditR -- | default mail from-address appMailFrom :: Handler Mail.Address appMailFrom = do domain <- appDomainName return $ Mail.Address (Just "Qua-kit") ("noreply@" <> domain) -- | returns domain name of server appDomainName :: Handler Text appDomainName = do app <- getYesod req <- waiRequest let domainStr = getApprootText guessApproot app req (pref, ds) = Text.breakOn "//" domainStr dsClean = if Text.length ds >= 2 then Text.drop 2 ds else pref return . fst $ Text.breakOn "/" dsClean
achirkin/qua-kit
apps/hs/qua-server/src/Foundation.hs
mit
22,747
0
19
5,952
4,790
2,464
2,326
-1
-1
-- Set Comprehensions -- To create a list comprehension we define a rule for every X and then the group from which we'll pick our Xs firstTenEvens = [x * 2 | x <- [1..10]] -- Now let's get all elements that doubled are greater than or equal to 12 -- This time we will also need a condition after the input group greaterOrEqualTwelve = [x * 2 | x <- [1..10], x >= 12] -- The output function can be basically anything, for example -- PS.: `odd` returns true for odd numbers boomsAndBangs listOfNumbers = [if x < 10 then "BOOM!" else "BANG!" | x <- listOfNumbers, odd x] -- We can also draw from several lists, for example allPossibleProducts firstList secondList = [x * y | x <- firstList, y <- secondList] allPossibleProductsAboveFifty firstList secondList = [x * y | x <- firstList, y <- secondList, x * y > 50] -- Now let's create our own version of `length` -- `_` means that we are not interested in the value we're drawing from the list, so we won't assign it to a variable length' list = sum [1 | _ <- list]
lucasfcosta/haskell-experiences
Chapter 2/setComprehensions.hs
mit
1,018
0
8
200
206
112
94
6
2
{-# htermination notElem :: Eq a => (Maybe a) -> [(Maybe a)] -> Bool #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_notElem_10.hs
mit
73
0
2
15
3
2
1
1
0
{-# LANGUAGE OverloadedStrings #-} module Proxy where import qualified Logger as L import qualified Data.ByteString.Char8 as B import qualified Network.BSD as NBSD import Network.Wai import Network.HTTP.Types import Network.HTTP.Types.Header import Network.Wai.Handler.Warp (run) import qualified Network.HTTP.Client as Client import qualified Network.HTTP.Client.OpenSSL as ClientSSL import Data.Time.LocalTime import Control.Concurrent (ThreadId,forkIO) import Control.Concurrent.Chan import Data.ByteString.Lazy import qualified Data.List.Split as Split import Data.Streaming.Network import Control.Exception (finally) import Control.Monad (forever,when) import Control.Concurrent (forkFinally) import Control.Concurrent.MVar (MVar(..),takeMVar,putMVar,newEmptyMVar,isEmptyMVar) import System.Posix.Unistd (usleep) import Network.Socket (isConnected) import Control.Exception (try) import qualified OpenSSL.Session as SSL splitHostAndPort :: String -> Maybe (String, Int) splitHostAndPort hostport = case Split.splitOn ":" hostport of [host,port] -> Just (host, read port :: Int) _ -> Nothing removeHeaders headers headersToRemove = Prelude.filter (\(h,_) -> not (inlist h headersToRemove)) headers where inlist h (x:l) = h == x || inlist h l inlist h [] = False getRequest :: Client.Manager -> Request -> String -> IO (Client.Response ByteString) getRequest man req url = do initialRequest <- Client.parseUrl url requestBody <- requestBody req let requestWithQS = Client.setQueryString (queryString req) initialRequest let request = requestWithQS { Client.method=methodGet, Client.redirectCount=0, Client.requestHeaders=(if url == paranoiaUrl then [] else (removeHeaders (requestHeaders req) [hContentLength])), Client.requestBody=Client.RequestBodyBS requestBody } Client.httpLbs request man postRequest :: Client.Manager -> Request -> String -> IO (Client.Response ByteString) postRequest man req url = do initialRequest <- Client.parseUrl url requestBody <- requestBody req let request = initialRequest { Client.method=methodPost, Client.redirectCount=0, Client.requestHeaders=(removeHeaders (requestHeaders req) [hContentLength]), Client.requestBody = Client.RequestBodyBS requestBody } Client.httpLbs request man startLogger :: (L.Logger l) => l -> Chan (LocalTime,Request) -> IO ThreadId startLogger l c = forkIO logData where logData = do (t,r) <- readChan c L.log l t r logData paranoiaUrl = "http://i.imgur.com/zXMBlV0.jpg" isLocalHost :: String -> String -> Int -> Bool isLocalHost host hostname port = host == (hostname ++ ":" ++ (show port)) || host == ("localhost:"++(show port)) || host == hostname || host == "localhost" buildRequestUrl :: Request -> String -> Int -> String buildRequestUrl request hostname port = let unpackedpath = (B.unpack $ rawPathInfo request) in let path = if unpackedpath == "/" then "" else unpackedpath in case (requestHeaderHost request) of Just u -> let uu = (B.unpack u) in if isLocalHost uu hostname port then paranoiaUrl else "http://"++uu++unpackedpath Nothing -> paranoiaUrl forkThread :: IO () -> IO (MVar ()) forkThread proc = do handle <- newEmptyMVar _ <- forkFinally proc (\_ -> putMVar handle ()) return handle foreverUntil :: IO Bool -> IO a -> IO () foreverUntil cond act = do tf <- cond if tf then act >> foreverUntil cond act else return () doUntil :: IO Bool -> IO a -> IO () doUntil cond act = do act tf <- cond if tf then doUntil cond act else return () isAppDataSocketConnected appData = case appRawSocket appData of Just s -> isConnected s Nothing -> return False tunnel (Just host) = case (splitHostAndPort (B.unpack host)) of Just (host,port) -> flip responseRaw (tunnel Nothing) $ \clientBody response -> do runTCPClient (clientSettingsTCP port (B.pack host)) $ \remoteData -> do response "HTTP/1.1 200 Connection Established\r\nProxy-agent: paranoia\r\n\r\n" connClosed <- newEmptyMVar reader <- forkThread $ foreverUntil (isEmptyMVar connClosed) (do inp <- clientBody if (not $ B.null inp) then appWrite remoteData inp else usleep 100000 ) doUntil (isAppDataSocketConnected remoteData) (do d <- appRead remoteData if (B.null d) then usleep 100000 else response d) `finally` putMVar connClosed () takeMVar reader Nothing -> (tunnel Nothing) tunnel Nothing = responseLBS status404 [("Content-Type", "text/plain")] "404 Not found" fixResponseHeaders hs = ("Proxy-Agent","paranoia"):(removeHeaders hs [hContentEncoding,hContentLength]) processResponse respond req = do res <- try req case res of Left ex -> processResponseEx ex Right clientResponse -> respond $ responseLBS (Client.responseStatus clientResponse) (fixResponseHeaders (Client.responseHeaders clientResponse)) (Client.responseBody clientResponse) where processResponseEx (Client.StatusCodeException s hs _) = case lookup "X-Response-Body-Start" hs of Just body -> respond $ responseLBS s (fixResponseHeaders hs) (fromStrict body) Nothing -> respond $ responseLBS s (fixResponseHeaders hs) "" processResponseEx (Client.FailedConnectionException host port) = do Prelude.putStrLn ("Timeout while connecting to " ++ host ++ ":" ++ (show port)) respond $ responseLBS status502 [("Proxy-Agent","paranoia")] "Ohh nouz something went wrong" processResponseEx (Client.FailedConnectionException2 host port secure ex) = do Prelude.putStrLn ("Failure while connecting to " ++ host ++ ":" ++ (show port) ++ " secure: "++(show secure) ++ " "++(show ex)) respond $ responseLBS status502 [("Proxy-Agent","paranoia")] "Ohh nouz something went wrong" processResponseEx ex = do Prelude.putStrLn (show ex) respond $ responseLBS status502 [("Proxy-Agent","paranoia")] "Ohh nouz something went wrong" app :: Client.Manager -> Chan (LocalTime,Request) -> String -> Int -> Application app man logChan hostname port = \request respond -> do t <- getZonedTime writeChan logChan (zonedTimeToLocalTime t, request) case requestMethod request of "GET" -> processResponse respond $ getRequest man request (buildRequestUrl request hostname port) "POST" -> processResponse respond $ postRequest man request (buildRequestUrl request hostname port) "CONNECT" -> respond $ tunnel (requestHeaderHost request) _ -> respond $ responseLBS status405 [("Content-Type", "text/plain")] "405 Method not supported" runProxy :: (L.Logger l) => Int -> l -> IO () runProxy port logger = do man <- Client.newManager (ClientSSL.opensslManagerSettings SSL.context) --Client.defaultManagerSettings hostname <- NBSD.getHostName logChan <- newChan startLogger logger logChan Prelude.putStrLn $ "paranoia started on http://0.0.0.0:" ++ (show port) ++ "/" run port (app man logChan hostname port)
troydm/paranoia
src/Proxy.hs
mit
10,093
0
26
4,365
2,284
1,165
1,119
137
6
import Data.Array.Unboxed improve :: Array (Int, Int) Int -> Array (Int, Int) Int -> Array (Int, Int) Int improve path cost = array (bounds path) ( ((i0, j0), cost!(i0, j0)) : ((i0, j1), path!(i0, j1) `min` (cost!(i0,j1) + minTopRight)) : ((i1, j0), path!(i1, j0) `min` (cost!(i1,j0) + minBottomLeft)) : ((i1, j1), path!(i1, j1) `min` (cost!(i1,j1) + minBottomRight)) : [((i,j), path!(i,j) `min` (cost!(i,j) + minCenter i j)) | i <- [i0+1..i1-1], j <- [j0+1..j1-1]] ++ [((i0,j), path!(i0,j) `min` (cost!(i0,j) + minTop j)) | j <- [j0+1..j1-1]] ++ [((i1,j), path!(i1,j) `min` (cost!(i1,j) + minBottom j)) | j <- [j0+1..j1-1]] ++ [((i,j0), path!(i,j0) `min` (cost!(i,j0) + minLeft i)) | i <- [i0+1..i1-1]] ++ [((i,j1), path!(i,j1) `min` (cost!(i,j1) + minRight i)) | i <- [i0+1..i1-1]] ) where ((i0, j0), (i1, j1)) = bounds path minCenter i j = (path!(i-1,j)) `min` (path!(i+1,j)) `min` (path!(i,j-1)) `min` (path!(i,j+1)) minTop j = (path!(i0+1,j)) `min` (path!(i0,j-1)) `min` (path!(i0,j+1)) minBottom j = (path!(i1-1,j)) `min` (path!(i1,j-1)) `min` (path!(i1,j+1)) minLeft i = (path!(i+1,j0)) `min` (path!(i-1,j0)) `min` (path!(i,j0+1)) minRight i = (path!(i+1,j1)) `min` (path!(i-1,j1)) `min` (path!(i,j1-1)) minTopRight = (path!(i0+1,j1)) `min` (path!(i0,j1-1)) minBottomLeft = (path!(i1-1,j0)) `min` (path!(i1,j0+1)) minBottomRight = (path!(i1-1,j1)) `min` (path!(i1,j1-1)) initPath :: Array (Int, Int) Int -> Array (Int, Int) Int initPath cost = listArray (bounds cost) $ repeat maxItem where items = elems cost maxItem = length items * maximum items sampleCost :: Array (Int, Int) Int sampleCost = listArray ((1,1), (5,5)) [ 131, 673, 234, 103, 18, 201, 96, 342, 965, 150, 630, 803, 746, 422, 111, 537, 699, 497, 121, 956, 805, 732, 524, 37, 331] euler cost = (iter $ initPath cost) ! snd (bounds cost) where iter path = if (path == path') then path else iter path' where path' = improve path cost main = do src <- readFile "z:/euler/euler_0083.dat" let rows = map (\r -> (read ("[" ++ r ++ "]"))::[Int]) $ lines src let i1 = length rows let j1 = length (head rows) let cost = listArray ((1, 1), (i1, j1)) $ concat rows putStrLn $ "test: " ++ show (euler sampleCost) putStrLn $ "actual: " ++ show (euler cost)
dpieroux/euler
0/0083.hs
mit
2,446
0
20
577
1,635
936
699
43
2
{-# LANGUAGE GeneralizedNewtypeDeriving, PatternGuards, DeriveDataTypeable #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} module Test.Tasty.Silver.Interactive.Run ( wrapRunTest ) where import Data.Tagged import Data.Typeable import Test.Tasty hiding (defaultMain) import Test.Tasty.Options import Test.Tasty.Providers import Test.Tasty.Runners import Test.Tasty.Silver.Filter ( TestPath ) data CustomTestExec t = IsTest t => CustomTestExec t (OptionSet -> t -> (Progress -> IO ()) -> IO Result) deriving (Typeable) instance IsTest t => IsTest (CustomTestExec t) where run opts (CustomTestExec t r) cb = r opts t cb testOptions = retag $ (testOptions :: Tagged t [OptionDescription]) -- | Provide new test run function wrapping the existing tests. wrapRunTest :: (forall t . IsTest t => TestPath -> TestName -> OptionSet -> t -> (Progress -> IO ()) -> IO Result) -> TestTree -> TestTree wrapRunTest = wrapRunTest' "/" wrapRunTest' :: TestPath -> (forall t . IsTest t => TestPath -> TestName -> OptionSet -> t -> (Progress -> IO ()) -> IO Result) -> TestTree -> TestTree wrapRunTest' tp f (SingleTest n t) = SingleTest n (CustomTestExec t (f (tp <//> n) n)) wrapRunTest' tp f (TestGroup n ts) = TestGroup n (fmap (wrapRunTest' (tp <//> n) f) ts) wrapRunTest' tp f (PlusTestOptions o t) = PlusTestOptions o (wrapRunTest' tp f t) wrapRunTest' tp f (WithResource r t) = WithResource r (\x -> wrapRunTest' tp f (t x)) wrapRunTest' tp f (AskOptions t) = AskOptions (\o -> wrapRunTest' tp f (t o)) (<//>) :: TestPath -> TestPath -> TestPath a <//> b = a ++ "/" ++ b
phile314/tasty-silver
Test/Tasty/Silver/Interactive/Run.hs
mit
1,666
0
18
298
588
310
278
34
1
{-# LANGUAGE DerivingVia #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE RecordWildCards #-} module Unison.Codebase.FileCodebase.Branch.Dependencies where import Data.Set (Set) import Data.Foldable (toList) import qualified Data.Set as Set import qualified Data.Map as Map import Unison.Codebase.Branch (Branch(Branch), Branch0, EditHash) import qualified Unison.Codebase.Causal as Causal import qualified Unison.Codebase.Branch as Branch import qualified Unison.Reference as Reference import qualified Unison.Referent as Referent import GHC.Generics (Generic) import Data.Monoid.Generic import Data.Map (Map) import Unison.NameSegment (NameSegment) import Unison.Referent (Referent) import Unison.Codebase.Patch (Patch) import qualified Unison.Util.Star3 as Star3 import qualified Unison.Util.Relation as R import Unison.Reference (Reference(DerivedId)) type Branches m = [(Branch.Hash, Maybe (m (Branch m)))] data Dependencies = Dependencies { patches :: Set EditHash , terms :: Set Reference.Id , decls :: Set Reference.Id } deriving Show deriving Generic deriving Semigroup via GenericSemigroup Dependencies deriving Monoid via GenericMonoid Dependencies data Dependencies' = Dependencies' { patches' :: [EditHash] , terms' :: [Reference.Id] , decls' :: [Reference.Id] } deriving Show deriving Generic deriving Semigroup via GenericSemigroup Dependencies' deriving Monoid via GenericMonoid Dependencies' to' :: Dependencies -> Dependencies' to' Dependencies{..} = Dependencies' (toList patches) (toList terms) (toList decls) fromBranch :: Applicative m => Branch m -> (Branches m, Dependencies) fromBranch (Branch c) = case c of Causal.One _hh e -> fromBranch0 e Causal.Cons _hh e (h, m) -> fromBranch0 e <> fromTails (Map.singleton h m) Causal.Merge _hh e tails -> fromBranch0 e <> fromTails tails where fromTails m = ([(h, Just (Branch <$> mc)) | (h, mc) <- Map.toList m], mempty) fromRawCausal :: Causal.Raw Branch.Raw (Branches m, Dependencies) -> (Branches m, Dependencies) fromRawCausal = \case Causal.RawOne e -> e Causal.RawCons e h -> e <> fromTails [h] Causal.RawMerge e hs -> e <> fromTails (toList hs) where fromTails ts = (fmap (,Nothing) ts, mempty) fromBranch0 :: Applicative m => Branch0 m -> (Branches m, Dependencies) fromBranch0 b = ( fromChildren (Branch._children b) , fromTermsStar (Branch._terms b) <> fromTypesStar (Branch._types b) <> fromEdits (Branch._edits b) ) where fromChildren :: Applicative m => Map NameSegment (Branch m) -> Branches m fromChildren m = [ (Branch.headHash b, Just (pure b)) | b <- toList m ] references :: Branch.Star r NameSegment -> [r] references = toList . R.dom . Star3.d1 mdValues :: Branch.Star r NameSegment -> [Reference] mdValues = fmap snd . toList . R.ran . Star3.d3 fromTermsStar :: Branch.Star Referent NameSegment -> Dependencies fromTermsStar s = Dependencies mempty terms decls where terms = Set.fromList $ [ i | Referent.Ref (DerivedId i) <- references s] ++ [ i | DerivedId i <- mdValues s] decls = Set.fromList $ [ i | Referent.Con (DerivedId i) _ _ <- references s ] fromTypesStar :: Branch.Star Reference NameSegment -> Dependencies fromTypesStar s = Dependencies mempty terms decls where terms = Set.fromList [ i | DerivedId i <- mdValues s ] decls = Set.fromList [ i | DerivedId i <- references s ] fromEdits :: Map NameSegment (EditHash, m Patch) -> Dependencies fromEdits m = Dependencies (Set.fromList . fmap fst $ toList m) mempty mempty
unisonweb/platform
parser-typechecker/src/Unison/Codebase/FileCodebase/Branch/Dependencies.hs
mit
3,576
0
16
641
1,236
663
573
-1
-1