Datasets:
				
			
			
	
			
			
	
		
		Dataset Viewer
	| 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 | 
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 
	answer = sum [1..100] ^ 2 - foldl (\x y -> y^2 + x) 0 [1..100]
 | 
	tamasgal/haskell_exercises | 
	ProjectEuler/p006.hs | 
	mit | 63 | 0 | 10 | 16 | 52 | 27 | 25 | 1 | 1 | 
| 
	{-# LANGUAGE DataKinds     #-}
{-# LANGUAGE TypeOperators #-}
module DirectoryAPI.API
  ( directoryAPIProxy
  , DirectoryAPI
  ) where
import Servant
import AuthAPI.API (AuthToken)
import Models (File, Node, NodeId)
type DirectoryAPI = "ls" :> -- List all files
                    AuthToken :>
                    Get '[JSON] [File] -- Listing of all files
               :<|> "whereis" :> -- Lookup the node for a given file path
                    AuthToken :>
                    ReqBody '[JSON] FilePath :> -- Path of file being looked up
                    Post '[JSON] Node -- Node where the file is kept
               :<|> "roundRobinNode" :> -- Next node to use as a file primary
                    AuthToken :>
                    ReqBody '[JSON] FilePath :> -- Path of file that will be written
                    Get '[JSON] Node -- Primary node of the file being stored
               :<|> "registerFileServer" :> -- Register a node with the directory service
                    ReqBody '[JSON] Int :> -- Port file server node is running on
                    Post '[JSON] NodeId -- Id of the newly created node record
directoryAPIProxy :: Proxy DirectoryAPI
directoryAPIProxy = Proxy
 | 
	houli/distributed-file-system | 
	dfs-shared/src/DirectoryAPI/API.hs | 
	mit | 1,213 | 0 | 20 | 421 | 198 | 113 | 85 | 24 | 1 | 
| 
	module BlocVoting.Tally.Resolution where
import qualified Data.ByteString as BS
data Resolution = Resolution {
    rCategories :: Int
  , rEndTimestamp :: Int
  , rName :: BS.ByteString
  , rUrl :: BS.ByteString
  , rVotesFor :: Integer
  , rVotesTotal :: Integer
  , rResolved :: Bool
}
  deriving (Show, Eq)
updateResolution :: Resolution -> Integer -> Integer -> Resolution
updateResolution (Resolution cats endT name url for total resolved) newForVotes newTotalVotes =
    Resolution cats endT name url (for +  newForVotes) (total + newTotalVotes) resolved
 | 
	XertroV/blocvoting | 
	src/BlocVoting/Tally/Resolution.hs | 
	mit | 565 | 0 | 9 | 104 | 157 | 91 | 66 | 14 | 1 | 
| 
	{-# LANGUAGE CPP #-}
module Database.Orville.PostgreSQL.Plan.Explanation
  ( Explanation
  , noExplanation
  , explainStep
  , explanationSteps
  ) where
newtype Explanation =
  Explanation ([String] -> [String])
#if MIN_VERSION_base(4,11,0)
instance Semigroup Explanation where
  (<>) = appendExplanation
#endif
instance Monoid Explanation where
  mempty = noExplanation
  mappend = appendExplanation
appendExplanation :: Explanation -> Explanation -> Explanation
appendExplanation (Explanation front) (Explanation back) =
  Explanation (front . back)
noExplanation :: Explanation
noExplanation =
  Explanation id
explainStep :: String -> Explanation
explainStep str =
  Explanation (str:)
explanationSteps :: Explanation -> [String]
explanationSteps (Explanation prependTo) =
  prependTo []
 | 
	flipstone/orville | 
	orville-postgresql/src/Database/Orville/PostgreSQL/Plan/Explanation.hs | 
	mit | 800 | 0 | 8 | 121 | 193 | 110 | 83 | 23 | 1 | 
| 
	import Data.List (permutations, sort)
solve :: String
solve = (sort $ permutations "0123456789") !! 999999
main = putStrLn $ solve
 | 
	pshendry/project-euler-solutions | 
	0024/solution.hs | 
	mit | 133 | 0 | 8 | 22 | 47 | 26 | 21 | 4 | 1 | 
| 
	module Lesson08 where
-- Now let's have some real fun: a two player, online five card stud game,
-- with a full betting system. The betting system is actually the biggest
-- addition versus what we've done previously, so most of our attention
-- will be focused on that. Most of the other code will be very similar
-- to what we had in lesson 7.
import Helper
import Helper.Multiplayer
import Helper.Pretty
import Helper.Winning
import System.Random.Shuffle
import Data.List
import Safe
-- We're going to want to keep track of multiple information per player.
-- A common way to do that is to create a record data type, where each
-- piece of data has its own name. We'll want to have the player and
-- how much money he/she has.
data PokerPlayer = PokerPlayer
    { player :: Player
    , chips :: Int
    , cards :: [Card]
    , hand :: PokerHand
    }
data Action = Call | Raise Int | Fold
askAction p allowedRaise = do
    str <- askPlayer (player p) "call, raise, or fold?"
    case str of
        "call" -> return Call
        "raise" ->  askRaise p allowedRaise
        "fold" -> return Fold
        _ -> do
            tellPlayer (player p) "That was not a valid answer"
            askAction p allowedRaise
askRaise p allowedRaise = do
    str <- askPlayer (player p) ("Enter amount to raise, up to " ++ show allowedRaise)
    case readMay str of
        Nothing -> do
            tellPlayer (player p) "That was an invalid raise amount"
            askRaise p allowedRaise
        Just amount
            | amount < 0 -> do
                tellPlayer (player p) "You cannot raise by a negative value"
                askRaise p allowedRaise
            | otherwise -> return (Raise amount)
wager p1 p2 pot owed = do
    tellAllPlayers $ show (player p1) ++ " has " ++ show (chips p1) ++ " chips"
    tellAllPlayers $ show (player p2) ++ " has " ++ show (chips p2) ++ " chips"
    tellAllPlayers $ "The pot currently has " ++ show pot ++ " chips"
    tellAllPlayers $ "Betting is to " ++ show (player p1) ++ ", who owes " ++ show owed
    let allowedRaise = min (chips p2) (chips p1 - owed)
    action <- askAction p1 allowedRaise
    case action of
        Call -> do
            tellAllPlayers $ show (player p1) ++ " calls"
            let p1' = p1 { chips = chips p1 - owed }
                pot' = pot + owed
            finishHand p1' p2 pot'
        Fold -> do
            tellAllPlayers $ show (player p1) ++ " folds"
            startGame (player p1) (chips p1) (player p2) (chips p2 + pot)
        Raise raise -> do
            tellAllPlayers $ show (player p1) ++ " raises " ++ show raise
            let p1' = p1 { chips = chips p1 - owed - raise }
            wager p2 p1' (pot + owed + raise) raise
finishHand p1 p2 pot = do
    tellAllPlayers ("All bets are in, the pot is at: " ++ show pot)
    tellAllPlayers (show (player p1) ++ " has " ++ prettyHand (cards p1) ++ ", " ++ show (hand p1))
    tellAllPlayers (show (player p2) ++ " has " ++ prettyHand (cards p2) ++ ", " ++ show (hand p2))
    (winnings1, winnings2) <-
        case compare (hand p1) (hand p2) of
            LT -> do
                tellAllPlayers (show (player p2) ++ " wins!")
                return (0, pot)
            EQ -> do
                tellAllPlayers "Tied game"
                let winnings1 = pot `div` 2
                    winnings2 = pot - winnings1
                return (winnings1, winnings2)
            GT -> do
                tellAllPlayers (show (player p1) ++ " wins!")
                return (pot, 0)
    startGame (player p1) (chips p1 + winnings1) (player p2) (chips p2 + winnings2)
startGame player1 0 player2 chips2 = do
    tellAllPlayers (show player1 ++ " is out of chips")
    tellAllPlayers (show player2 ++ " wins with a total of: " ++ show chips2)
startGame player1 chips1 player2 0 = do
    tellAllPlayers (show player2 ++ " is out of chips")
    tellAllPlayers (show player1 ++ " wins with a total of: " ++ show chips1)
startGame player1 chips1 player2 chips2 = do
    tellAllPlayers "Dealing..."
    shuffled <- shuffleM deck
    let (cards1, rest) = splitAt 5 shuffled
        hand1 = pokerHand cards1
        cards2 = take 5 rest
        hand2 = pokerHand cards2
        p1 = PokerPlayer
            { player = player1
            , chips = chips1
            , cards = cards1
            , hand = hand1
            }
        -- Always start with a 1 chip ante from player 2
        pot = 1
        owed = 1
        p2 = PokerPlayer
            { player = player2
            , chips = chips2 - 1
            , cards = cards2
            , hand = hand2
            }
    tellPlayer player1 ("You have " ++ prettyHand cards1 ++ ", " ++ show hand1)
    tellPlayer player2 ("You have " ++ prettyHand cards2 ++ ", " ++ show hand2)
    wager p1 p2 pot owed
main = playMultiplayerGame "two player five card stud" 2 $ do
    tellAllPlayers "Welcome to two player five card stud!"
    [player1, player2] <- getPlayers
    startGame player1 20 player2 20
-- Let's talk about the betting phase. We'll be alternating between each
-- player. At each player's betting turn, he/she will be allowed to:
--
-- 1. Call, which would be to match whatever bet is on the table.
-- 2. Raise, which would match the current bet and add a little more.
-- 3. Fold
 | 
	snoyberg/haskell-impatient-poker-players | 
	src/Lesson08.hs | 
	mit | 5,286 | 0 | 19 | 1,643 | 1,450 | 706 | 744 | 104 | 4 | 
| 
	{- hpodder component
Copyright (C) 2006 John Goerzen <jgoerzen@complete.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-}
{- |
   Module     : FeedParser
   Copyright  : Copyright (C) 2006 John Goerzen
   License    : GNU GPL, version 2 or above
   Maintainer : John Goerzen <jgoerzen@complete.org>
   Stability  : provisional
   Portability: portable
Written by John Goerzen, jgoerzen\@complete.org
-}
module FeedParser where
import Types
import Text.XML.HaXml
import Text.XML.HaXml.Parse
import Text.XML.HaXml.Posn
import Utils
import Data.Maybe.Utils
import Data.Char
import Data.Either.Utils
import Data.List
import System.IO
data Item = Item {itemtitle :: String,
                  itemguid :: Maybe String,
                  enclosureurl :: String,
                  enclosuretype :: String,
                  enclosurelength :: String
                  }
          deriving (Eq, Show, Read)
data Feed = Feed {channeltitle :: String,
                  items :: [Item]}
            deriving (Eq, Show, Read)
item2ep pc item =
    Episode {podcast = pc, epid = 0,
             eptitle = sanitize_basic (itemtitle item), 
             epurl = sanitize_basic (enclosureurl item),
             epguid = fmap sanitize_basic (itemguid item),
             eptype = sanitize_basic (enclosuretype item), epstatus = Pending,
             eplength = case reads . sanitize_basic . enclosurelength $ item of
                          [] -> 0
                          [(x, [])] -> x
                          _ -> 0,
             epfirstattempt = Nothing,
             eplastattempt = Nothing,
             epfailedattempts = 0}
parse :: FilePath -> String -> IO (Either String Feed)
parse fp name = 
    do h <- openBinaryFile fp ReadMode
       c <- hGetContents h
       case xmlParse' name (unifrob c) of
         Left x -> return (Left x)
         Right y ->
             do let doc = getContent y
                let title = getTitle doc
                let feeditems = getEnclosures doc
                return $ Right $
                           (Feed {channeltitle = title, items = feeditems})
       where getContent (Document _ _ e _) = CElem e noPos
unifrob ('\xfeff':x) = x -- Strip off unicode BOM
unifrob x = x
unesc = xmlUnEscape stdXmlEscaper
getTitle doc = forceEither $ strofm "title" (channel doc)
getEnclosures doc =
    concat . map procitem $ item doc
    where procitem i = map (procenclosure title guid) enclosure
              where title = case strofm "title" [i] of
                              Left x -> "Untitled"
                              Right x -> x
                    guid = case strofm "guid" [i] of
                              Left _ -> Nothing
                              Right x -> Just x
                    enclosure = tag "enclosure" `o` children $ i
          procenclosure title guid e =
              Item {itemtitle = title,
                    itemguid = guid,
                    enclosureurl = head0 $ forceMaybe $ stratt "url" e,
                    enclosuretype = head0 $ case stratt "type" e of
                                              Nothing -> ["application/octet-stream"]
                                              Just x -> x,
                    enclosurelength = head $ case stratt "length" e of
                                                Nothing -> ["0"]
                                                Just [] -> ["0"]
                                                Just x -> x
                                                }
          head0 [] = ""
          head0 (x:xs) = x
              
item = tag "item" `o` children `o` channel
channel =
    tag "channel" `o` children `o` tag "rss"
--------------------------------------------------
-- Utilities
--------------------------------------------------
attrofelem :: String -> Content Posn -> Maybe AttValue
attrofelem attrname (CElem inelem _) =
    case unesc inelem of
      Elem name al _ -> lookup attrname al
attrofelem _ _ =
    error "attrofelem: called on something other than a CElem"
stratt :: String -> Content Posn -> Maybe [String]
stratt attrname content =
    case attrofelem attrname content of
      Just (AttValue x) -> Just (concat . map mapfunc $ x)
      Nothing -> Nothing
    where mapfunc (Left x) = [x]
          mapfunc (Right _) = []
-- Finds the literal children of the named tag, and returns it/them
tagof :: String -> CFilter Posn
tagof x = keep /> tag x -- /> txt
-- Retruns the literal string that tagof would find
strof :: String -> Content Posn -> String
strof x y = forceEither $ strof_either x y
strof_either :: String -> Content Posn -> Either String String
strof_either x y =
    case tagof x $ y of
      [CElem elem pos] -> Right $ verbatim $ tag x /> txt
           $ CElem (unesc elem) pos
      z -> Left $ "strof: expecting CElem in " ++ x ++ ", got "
           ++ verbatim z ++ " at " ++ verbatim y
strofm x y = 
    if length errors /= 0
       then Left errors
       else Right (concat plainlist)
    where mapped = map (strof_either x) $ y
          (errors, plainlist) = conveithers mapped
          isright (Left _) = False
          isright (Right _) = True
conveithers :: [Either a b] -> ([a], [b])
conveithers inp =  worker inp ([], [])
    where worker [] y = y
          worker (Left x:xs) (lefts, rights) =
              worker xs (x:lefts, rights)
          worker (Right x:xs) (lefts, rights) =
              worker xs (lefts, x:rights)
 | 
	jgoerzen/hpodder | 
	FeedParser.hs | 
	gpl-2.0 | 6,088 | 1 | 16 | 2,117 | 1,532 | 797 | 735 | 115 | 7 | 
| 
	{- |
Module      :  $EmptyHeader$
Description :  <optional short description entry>
Copyright   :  (c) <Authors or Affiliations>
License     :  GPLv2 or higher, see LICENSE.txt
Maintainer  :  <email>
Stability   :  unstable | experimental | provisional | stable | frozen
Portability :  portable | non-portable (<reason>)
<optional description>
-}
-------------------------------------------------------------------------------
-- GMP
-- Copyright 2007, Lutz Schroeder and Georgel Calin
-------------------------------------------------------------------------------
module Main where
import Text.ParserCombinators.Parsec
import System.Environment
import IO
import GMP.GMPAS
import GMP.GMPSAT
import GMP.GMPParser
import GMP.ModalLogic
import GMP.ModalK()
import GMP.ModalKD()
import GMP.GradedML()
import GMP.CoalitionL()
import GMP.MajorityL()
import GMP.GenericML()
import GMP.Lexer
-------------------------------------------------------------------------------
-- Funtion to run parser & print
-------------------------------------------------------------------------------
runLex :: (Ord a, Show a, ModalLogic a b) => Parser (Formula a) -> String -> IO ()
runLex p input = run (do
    whiteSpace
    ; x <- p
    ; eof
    ; return x
    ) input
run :: (Ord a, Show a, ModalLogic a b) => Parser (Formula a) -> String -> IO ()
run p input
        = case (parse p "" input) of
                Left err -> do putStr "parse error at "
                               print err
                Right x ->  do putStrLn ("Input Formula: "{- ++ show x ++ " ..."-})
                               let sat = checkSAT x
                               if sat then putStrLn "x ... is Satisfiable"
                                      else putStrLn "x ... is not Satisfiable"
                               let nsat = checkSAT $ Neg x
                               if nsat then putStrLn "~x ... is Satisfiable"
                                       else putStrLn "~x ... is not Satisfiable"
                               let prov = not $ checkSAT $ Neg x
                               if prov then putStrLn "x ... is Provable"
                                       else putStrLn "x ... is not Provable"
-------------------------------------------------------------------------------
-- For Testing
-------------------------------------------------------------------------------
runTest :: Int -> FilePath -> IO ()
runTest ml p = do
    input <- readFile (p)
    case ml of
     1 -> runLex ((par5er parseIndex) :: Parser (Formula ModalK)) input
     2 -> runLex ((par5er parseIndex) :: Parser (Formula ModalKD)) input
     3 -> runLex ((par5er parseIndex) :: Parser (Formula CL)) input
     4 -> runLex ((par5er parseIndex) :: Parser (Formula GML)) input
     5 -> runLex ((par5er parseIndex) :: Parser (Formula ML)) input
     _ -> runLex ((par5er parseIndex) :: Parser (Formula Kars)) input
    return ()
help :: IO()
help = do
    putStrLn ( "Usage:\n" ++
               "    ./main <ML> <path>\n\n" ++
               "<ML>:    1 for K ML\n" ++
               "         2 for KD ML\n" ++
               "         3 for Coalition L\n" ++
               "         4 for Graded ML\n" ++
               "         5 for Majority L\n" ++
               "         _ for Generic ML\n" ++
               "<path>:  path to input file\n" )
-------------------------------------------------------------------------------
main :: IO()
main = do
    args <- getArgs
    if (args == [])||(head args == "--help")||(length args < 2)
     then help
     else let ml = head args
              p = head (tail args)
          in runTest (read ml) p
 | 
	nevrenato/Hets_Fork | 
	GMP/versioning/gmp-0.0.1/GMP/Main.hs | 
	gpl-2.0 | 3,633 | 3 | 16 | 1,112 | 822 | 416 | 406 | 67 | 6 | 
| 
	{-# LANGUAGE ScopedTypeVariables #-}
import Bench
import Bench.Triangulations
main = print (qVertexSolBench trs)
 | 
	DanielSchuessler/hstri | 
	scratch6.hs | 
	gpl-3.0 | 115 | 0 | 7 | 15 | 24 | 13 | 11 | 4 | 1 | 
| 
	{-# LANGUAGE OverloadedStrings #-}
module Response.Export 
    (pdfResponse) where
import Happstack.Server
import qualified Data.ByteString.Lazy as BS
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString.Base64.Lazy as BEnc
import ImageConversion
import TimetableImageCreator (renderTable)
import System.Random
import Latex
-- | Returns a PDF containing the image of the timetable
-- requested by the user.
pdfResponse :: String -> String -> ServerPart Response
pdfResponse courses session =
    liftIO $ getPdf courses session
getPdf :: String -> String -> IO Response
getPdf courses session = do
    gen <- newStdGen
    let (rand, _) = next gen
        svgFilename = (show rand ++ ".svg")
        imageFilename = (show rand ++ ".png")
        texFilename = (show rand ++ ".tex")
        pdfFilename = (drop 4 texFilename) ++ ".pdf"
    renderTable svgFilename courses session
    returnPdfData svgFilename imageFilename pdfFilename texFilename
returnPdfData :: String -> String -> String -> String -> IO Response
returnPdfData svgFilename imageFilename pdfFilename texFilename = do
    createImageFile svgFilename imageFilename
    compileTex texFilename imageFilename
    _ <- compileTexToPdf texFilename
    pdfData <- BS.readFile texFilename
    _ <- removeImage svgFilename
    _ <- removeImage imageFilename
    _ <- removeImage pdfFilename
    _ <- removeImage texFilename
    let encodedData = BEnc.encode pdfData
    return $ toResponse encodedData
 
 | 
	pkukulak/courseography | 
	hs/Response/Export.hs | 
	gpl-3.0 | 1,487 | 0 | 12 | 284 | 380 | 192 | 188 | 36 | 1 | 
| 
	module Hazel.StringWriter where
import Control.Monad.State
------------- StringState -------------
type StringState = State String (Maybe Bool)
eval :: StringState -> String
eval s = execState s ""
newLine :: StringState
append  :: String -> StringState
apply   :: (String -> String) -> StringState
newLine  = append "\n"
append s = apply (++s)
apply f  = get >>= put.(f$) >> return (Just True)
--newLine :: StringState
--newLine = do
--            t <- get
--            put $ t++"\n"
--            return True
-- get >>= put.(++"\n") >>= return True
--append :: String -> StringState
--append s = do
--           t <- get
--           put $ t++s
--           return True
-- get >>= put.(++s) >>= return True
--modify :: (String -> String) -> StringState
--modify f = do
--             t <- get
--             put $ f t
--             return True
 | 
	hazel-el/hazel | 
	Hazel/StringWriter.hs | 
	gpl-3.0 | 860 | 1 | 8 | 250 | 155 | 92 | 63 | 11 | 1 | 
| 
	{-# LANGUAGE FlexibleContexts, CPP, JavaScriptFFI #-}
module Carnap.GHCJS.Action.TreeDeductionCheck (treeDeductionCheckAction) where
import Lib hiding (content)
import Data.Tree
import Data.Either
import Data.Map as M (lookup,Map, toList)
import Data.IORef (IORef, readIORef, newIORef, writeIORef)
import Data.Typeable (Typeable)
import Data.Aeson.Types
import Data.Text (pack)
import qualified Text.Parsec as P (parse) 
import Control.Monad.State (modify,get,execState,State)
import Control.Lens
import Control.Concurrent
import Control.Monad (mplus, (>=>))
import Control.Monad.IO.Class (liftIO)
import Carnap.Core.Unification.Unification (MonadVar,FirstOrder, applySub)
import Carnap.Core.Unification.ACUI (ACUI)
import Carnap.Core.Data.Types
import Carnap.Core.Data.Classes
import Carnap.Core.Data.Optics
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser
import Carnap.Languages.PurePropositional.Syntax
import Carnap.Languages.Util.LanguageClasses
import Carnap.Calculi.Util
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Checker
import Carnap.Calculi.Tableau.Data
import Carnap.Languages.PurePropositional.Logic (ofPropTreeSys)
import Carnap.Languages.PureFirstOrder.Logic (ofFOLTreeSys)
import Carnap.GHCJS.Util.ProofJS
import Carnap.GHCJS.SharedTypes
import GHCJS.DOM.HTMLElement (getInnerText, castToHTMLElement)
import GHCJS.DOM.Element (setInnerHTML, click, keyDown, input, setAttribute )
import GHCJS.DOM.Node (appendChild, removeChild, getParentNode, insertBefore, getParentElement)
import GHCJS.DOM.Types (Element, Document, IsElement)
import GHCJS.DOM.Document (createElement, getActiveElement)
import GHCJS.DOM.KeyboardEvent
import GHCJS.DOM.EventM
import GHCJS.DOM
import GHCJS.Types
treeDeductionCheckAction ::  IO ()
treeDeductionCheckAction = 
            do initializeCallback "checkProofTreeInfo" njCheck
               initElements getCheckers activateChecker
               return ()
    where njCheck = maybe (error "can't find PropNJ") id $ (\calc -> checkProofTree calc Nothing >=> return . fst) `ofPropTreeSys` "PropNJ" 
getCheckers :: IsElement self => Document -> self -> IO [Maybe (Element, Element, Map String String)]
getCheckers w = genInOutElts w "div" "div" "treedeductionchecker"
activateChecker :: Document -> Maybe (Element, Element, Map String String) -> IO ()
activateChecker _ Nothing  = return ()
activateChecker w (Just (i, o, opts)) = case (setupWith `ofPropTreeSys` sys) 
                                              `mplus` (setupWith `ofFOLTreeSys` sys)
                                        of Just io -> io
                                           Nothing -> error $ "couldn't parse tree system: " ++ sys
        where sys = case M.lookup "system" opts of
                        Just s -> s
                        Nothing -> "propNK"
              setupWith calc = do
                  mgoal <- parseGoal calc
                  let content = M.lookup "content" opts
                  root <- case (content >>= decodeJSON, mgoal) of
                              (Just val,_) -> let Just c = content in initRoot c o
                              (_, Just seq) | "prepopulate" `inOpts` opts -> 
                                                initRoot ("{\"label\": \"" ++ show (view rhs seq) 
                                                          ++ "\", \"rule\":\"\", \"forest\": []}") o
                              _ -> initRoot "{\"label\": \"\", \"rule\":\"\", \"forest\": []}" o
                  memo <- newIORef mempty
                  threadRef <- newIORef (Nothing :: Maybe ThreadId)
                  bw <- createButtonWrapper w o
                  let submit = submitTree w memo opts calc root mgoal
                  btStatus <- createSubmitButton w bw submit opts
                  if "displayJSON" `inOpts` opts 
                      then do
                          Just displayDiv <- createElement w (Just "div")
                          setAttribute displayDiv "class" "jsonDisplay"
                          setAttribute displayDiv "contenteditable" "true"
                          val <- toCleanVal root
                          setInnerHTML displayDiv . Just $ toJSONString val
                          toggleDisplay <- newListener $ do
                              kbe <- event
                              isCtrl <- getCtrlKey kbe
                              code <- liftIO $ keyString kbe
                              liftIO $ print code
                              if isCtrl && code == "?" 
                                  then do
                                      preventDefault
                                      mparent <- getParentNode displayDiv
                                      case mparent of
                                          Just p -> removeChild o (Just displayDiv)
                                          _ -> appendChild o (Just displayDiv)
                                      return ()
                                  else return ()
                          addListener o keyDown toggleDisplay False
                          updateRoot <- newListener $ liftIO $ do 
                                Just json <- getInnerText (castToHTMLElement displayDiv)
                                replaceRoot root json
                          addListener displayDiv input updateRoot False
                          root `onChange` (\_ -> do
                                   mfocus <- getActiveElement w
                                   --don't update when the display is
                                   --focussed, to avoid cursor jumping
                                   if Just displayDiv /= mfocus then do
                                       val <- toCleanVal root
                                       setInnerHTML displayDiv . Just $ toJSONString val
                                   else return ())
                          return ()
                      else return ()
                  initialCheck <- newListener $ liftIO $  do 
                                    forkIO $ do
                                        threadDelay 500000
                                        mr <- toCleanVal root
                                        case mr of
                                            Just r -> do (info,mseq) <- checkProofTree calc (Just memo) r 
                                                         decorate root info
                                                         Just wrap <- getParentElement i
                                                         updateInfo calc mgoal mseq wrap
                                            Nothing -> return ()
                                    return ()
                  addListener i initialize initialCheck False --initial check in case we preload a tableau
                  doOnce i mutate False $ liftIO $ btStatus Edited
                  case M.lookup "init" opts of Just "now" -> dispatchCustom w i "initialize"; _ -> return ()
                  root `onChange` (\_ -> dispatchCustom w i "mutate")
                  root `onChange` (\_ -> checkOnChange memo threadRef calc mgoal i root)
              parseGoal calc = do 
                  let seqParse = parseSeqOver $ tbParseForm calc
                  case M.lookup "goal" opts of
                      Just s -> case P.parse seqParse "" s of
                          Left e -> do setInnerHTML i (Just $ "Couldn't Parse This Goal:" ++ s)
                                       error "couldn't parse goal"
                          Right seq -> do setInnerHTML i (Just . tbNotation calc . show $ seq)
                                          return $ Just seq
                      Nothing -> do setInnerHTML i (Just "Awaiting a proof")
                                    return Nothing
updateInfo _ (Just goal) (Just seq) wrap | seq `seqSubsetUnify` goal = setAttribute wrap "class" "success"
updateInfo _ (Just goal) (Just seq) wrap = setAttribute wrap "class" "failure"
updateInfo calc Nothing (Just seq) wrap = setInnerHTML wrap (Just . tbNotation calc . show $ seq)
updateInfo _ Nothing Nothing wrap  = setInnerHTML wrap (Just "Awaiting a proof")
updateInfo _ _ _ wrap = setAttribute wrap "class" ""
submitTree w memo opts calc root (Just seq) l = 
        do Just val <- liftIO $ toCleanVal root
           case parse parseTreeJSON val of
               Error s -> message $ "Something has gone wrong. Here's the error:" ++ s
               Success tree -> case toProofTree calc tree of
                     Left _ | "exam" `inOpts` opts -> trySubmit w DeductionTree opts l (DeductionTreeData (pack (show seq)) tree (toList opts)) False
                     Left _ -> message "Something is wrong with the proof... Try again?"
                     Right prooftree -> do 
                          validation <- liftIO $ hoReduceProofTreeMemo memo (structuralRestriction prooftree) prooftree 
                          case validation of
                              Right seq' | "exam" `inOpts` opts || (seq' `seqSubsetUnify` seq) 
                                -> trySubmit w DeductionTree opts l (DeductionTreeData (pack (show seq)) tree (toList opts)) (seq' `seqSubsetUnify` seq)
                              _ -> message "Something is wrong with the proof... Try again?"
checkOnChange :: ( ReLex lex
                 , Sequentable lex
                 , Inference rule lex sem
                 , FirstOrder (ClassicalSequentOver lex)
                 , ACUI (ClassicalSequentOver lex)
                 , MonadVar (ClassicalSequentOver lex) (State Int)
                 , StaticVar (ClassicalSequentOver lex)
                 , Schematizable (lex (ClassicalSequentOver lex))
                 , CopulaSchema (ClassicalSequentOver lex)
                 , Typeable sem
                 , Show rule
                 , PrismSubstitutionalVariable lex
                 , FirstOrderLex (lex (ClassicalSequentOver lex))
                 , StructuralOverride rule (ProofTree rule lex sem)
                 , StructuralInference rule lex (ProofTree rule lex sem)
                 ) => ProofMemoRef lex sem rule -> IORef (Maybe ThreadId) -> TableauCalc lex sem rule 
                                                -> Maybe (ClassicalSequentOver lex (Sequent sem)) -> Element -> JSVal -> IO ()
checkOnChange memo threadRef calc mgoal i root = do
        mt <- readIORef threadRef
        case mt of Just t -> killThread t
                   Nothing -> return ()
        t' <- forkIO $ do
            threadDelay 500000
            Just changedVal <- toCleanVal root
            (theInfo, mseq) <- checkProofTree calc (Just memo) changedVal 
            decorate root theInfo
            Just wrap <- getParentElement i
            updateInfo calc mgoal mseq wrap
        writeIORef threadRef (Just t')
toProofTree :: ( Typeable sem
               , ReLex lex
               , Sequentable lex
               , StructuralOverride rule (ProofTree rule lex sem)
               , Inference rule lex sem
               ) => TableauCalc lex sem rule -> Tree (String,String) -> Either (TreeFeedback lex) (ProofTree rule lex sem)
toProofTree calc (Node (l,r) f) 
    | all isRight parsedForest && isRight newNode = handleOverride <$> (Node <$> newNode <*> sequence parsedForest)
    | isRight newNode = Left $ Node Waiting (map cleanTree parsedForest)
    | Left n <- newNode = Left n
    where parsedLabel = (SS . liftToSequent) <$> P.parse (tbParseForm calc) "" l
          parsedRules = P.parse (tbParseRule calc) "" r
          parsedForest = map (toProofTree calc) f
          cleanTree (Left fs) = fs
          cleanTree (Right fs) = fmap (const Waiting) fs
          newNode = case ProofLine 0 <$> parsedLabel <*> parsedRules of
                        Right l -> Right l
                        Left e -> Left (Node (ProofError $ NoParse e 0) (map cleanTree parsedForest))
          handleOverride f@(Node l fs) = case structuralOverride f (head (rule l)) of
                                               Nothing -> f
                                               Just rs -> Node (l {rule = rs}) fs
checkProofTree :: ( ReLex lex
                  , Sequentable lex
                  , Inference rule lex sem
                  , FirstOrder (ClassicalSequentOver lex)
                  , ACUI (ClassicalSequentOver lex)
                  , MonadVar (ClassicalSequentOver lex) (State Int)
                  , StaticVar (ClassicalSequentOver lex)
                  , Schematizable (lex (ClassicalSequentOver lex))
                  , CopulaSchema (ClassicalSequentOver lex)
                  , Typeable sem
                  , Show rule
                  , StructuralOverride rule (ProofTree rule lex sem)
                  , StructuralInference rule lex (ProofTree rule lex sem)
                  ) => TableauCalc lex sem rule -> Maybe (ProofMemoRef lex sem rule) -> Value -> IO (Value, Maybe (ClassicalSequentOver lex (Sequent sem)))
checkProofTree calc mmemo v = case parse parseTreeJSON v of
                           Success t -> case toProofTree calc t of 
                                  Left feedback -> return (toInfo feedback, Nothing)
                                  Right tree -> do (val,mseq) <- validateProofTree calc mmemo tree
                                                   return (toInfo val, mseq)
                           Error s -> do print (show v)
                                         error s
validateProofTree :: ( ReLex lex
                     , Sequentable lex
                     , Inference rule lex sem
                     , FirstOrder (ClassicalSequentOver lex)
                     , ACUI (ClassicalSequentOver lex)
                     , MonadVar (ClassicalSequentOver lex) (State Int)
                     , StaticVar (ClassicalSequentOver lex)
                     , Schematizable (lex (ClassicalSequentOver lex))
                     , CopulaSchema (ClassicalSequentOver lex)
                     , Typeable sem
                     , Show rule
                     , StructuralInference rule lex (ProofTree rule lex sem)
                     ) => TableauCalc lex sem rule -> Maybe (ProofMemoRef lex sem rule) 
                       -> ProofTree rule lex sem -> IO (TreeFeedback lex, Maybe (ClassicalSequentOver lex (Sequent sem)))
validateProofTree calc mmemo t@(Node _ fs) = do rslt <- case mmemo of 
                                                     Nothing -> return $ hoReduceProofTree (structuralRestriction t) t
                                                     Just memo -> hoReduceProofTreeMemo memo (structuralRestriction t) t
                                                case rslt of
                                                     Left msg -> (,) <$> (Node <$> pure (ProofError msg) <*> mapM (validateProofTree calc mmemo >=> return . fst) fs) 
                                                                     <*> pure Nothing
                                                     Right seq ->  (,) <$> (Node <$> pure (ProofData (tbNotation calc . show $ seq)) <*> mapM (validateProofTree calc mmemo >=> return . fst) fs) 
                                                                    <*> pure (Just seq)
 | 
	gleachkr/Carnap | 
	Carnap-GHCJS/src/Carnap/GHCJS/Action/TreeDeductionCheck.hs | 
	gpl-3.0 | 15,280 | 0 | 25 | 6,177 | 3,919 | 1,946 | 1,973 | -1 | -1 | 
| 
	-- Move generator logic
module Kurt.GoEngine ( genMove
                     , simulatePlayout
                     , EngineState(..)
                     , newEngineState
                     , updateEngineState
                     , newUctTree
                     ) where
import           Control.Arrow               (second)
import           Control.Monad               (liftM)
import           Control.Monad.Primitive     (PrimState)
import           Control.Monad.ST            (ST, runST, stToIO)
import           Control.Parallel.Strategies (parMap, rdeepseq)
import           Data.List                   ((\\))
import qualified Data.Map                    as M (map)
import           Data.Maybe                  (fromMaybe)
import           Data.Time.Clock             (UTCTime (..), getCurrentTime,
                                              picosecondsToDiffTime)
import           Data.Tree                   (rootLabel)
import           Data.Tree.Zipper            (findChild, fromTree, hasChildren,
                                              tree)
import           System.Random.MWC           (Gen, Seed, restore, save, uniform,
                                              withSystemRandom)
import           Data.Goban.GameState
import           Data.Goban.Types            (Color (..), Move (..), Score,
                                              Stone (..), Vertex)
import           Data.Goban.Utils            (rateScore, winningScore)
import           Kurt.Config
import           Data.Tree.UCT
import           Data.Tree.UCT.GameTree      (MoveNode (..), RaveMap,
                                              UCTTreeLoc, newMoveNode,
                                              newRaveMap)
import           Debug.TraceOrId             (trace)
-- import Data.Tree (drawTree)
data EngineState = EngineState {
      getGameState :: !GameState
    , getUctTree   :: !(UCTTreeLoc Move)
    , getRaveMap   :: !(RaveMap Move)
    , boardSize    :: !Int
    , getKomi      :: !Score
    , getConfig    :: !KurtConfig
    }
type LoopState = (UCTTreeLoc Move, RaveMap Move)
-- result from playout: score, playedMoves, path to startnode in tree
type Result = (Score, [Move], [Move])
-- request for playout: gamestate, path to startnode in tree, seed
type Request = (GameState, [Move], Seed)
newEngineState :: KurtConfig -> EngineState
newEngineState config =
  EngineState { getGameState =
                   newGameState (initialBoardsize config) (initialKomi config)
              , getUctTree = newUctTree
              , getRaveMap = newRaveMap
              , boardSize = initialBoardsize config
              , getKomi = initialKomi config
              , getConfig = config
              }
newUctTree :: UCTTreeLoc Move
newUctTree =
    fromTree $ newMoveNode
            (trace "UCT tree root move accessed"
             (Move (Stone (25,25) White)))
            (0.5, 1)
updateEngineState :: EngineState -> Move -> EngineState
updateEngineState eState move =
    eState { getGameState = gState', getUctTree = loc' }
    where
      gState' = updateGameState gState move
      gState = getGameState eState
      loc' = case move of
               (Resign _) -> loc
               _otherwise ->
                   if hasChildren loc
                   then selectSubtree loc move
                   else newUctTree
      loc = getUctTree eState
selectSubtree :: UCTTreeLoc Move -> Move -> UCTTreeLoc Move
selectSubtree loc move =
    loc''
    where
      loc'' = fromTree $ tree loc'
      loc' =
          fromMaybe newUctTree
          $ findChild ((move ==) . nodeMove . rootLabel) loc
genMove :: EngineState -> Color -> IO (Move, EngineState)
genMove eState color = do
  now <- getCurrentTime
  let deadline = UTCTime { utctDay = utctDay now
                         , utctDayTime = thinkPicosecs + utctDayTime now }
  let moves = nextMoves gState color
  let score = scoreGameState gState
  (if null moves
   then
       if winningScore color score
       then return (Pass color, eState)
       else return (Resign color, eState)
   else (do
          seed <- withSystemRandom (save :: Gen (PrimState IO) -> IO Seed)
          (loc', raveMap') <- runUCT loc gState raveMap config deadline seed
          let eState' = eState { getUctTree = loc', getRaveMap = raveMap' }
          return (bestMoveFromLoc loc' (getState gState) score, eState')))
    where
      config = getConfig eState
      gState = getGameState eState
      loc = getUctTree eState
      raveMap = M.map (second ((1 +) . (`div` 2))) $ getRaveMap eState
      thinkPicosecs =
          picosecondsToDiffTime
          $ fromIntegral (maxTime config) * 1000000000
bestMoveFromLoc :: UCTTreeLoc Move -> GameStateStuff -> Score -> Move
bestMoveFromLoc loc state score =
    case principalVariation loc of
      [] ->
          error "bestMoveFromLoc: principalVariation is empty"
      (node : _) ->
          if value < 0.1
          then
              if winningScore color score
              then
                  trace ("bestMoveFromLoc pass " ++ show node)
                  Pass color
              else
                  trace ("bestMoveFromLoc resign " ++ show node)
                  Resign color
          else
              trace ("total sims: " ++ show (nodeVisits$rootLabel$tree$loc)
                     ++ " best: " ++ show node
                     ++ "\n")
                     -- ++ (drawTree $ fmap show $ tree loc)
              move
          where
            move = nodeMove node
            value = nodeValue node
            color = nextMoveColor state
runUCT :: UCTTreeLoc Move
       -> GameState
       -> RaveMap Move
       -> KurtConfig
       -> UTCTime
       -> Seed
       -> IO LoopState
runUCT initLoc rootGameState initRaveMap config deadline seed00 = do
  uctLoop stateStream0 0
    where
      uctLoop :: [LoopState] -> Int -> IO LoopState
      uctLoop [] _ = return (initLoc, initRaveMap)
      uctLoop (st : stateStream) !n = do
        _ <- return $! st
        let maxRuns = n >= (maxPlayouts config)
        now <- getCurrentTime
        let timeIsUp = (now > deadline)
        (if maxRuns || timeIsUp
         then return st
         else uctLoop stateStream (n + 1))
      stateStream0 = loop0 seed00 (initLoc, initRaveMap)
      loop0 :: Seed -> LoopState -> [LoopState]
      loop0 seed0 st0 =
          map (\(_, st, _) -> st) $ iterate loop (seed0, st0, [])
          where
            loop (seed, st, results0) =
                (seed', st'', results)
                where
                  st'' = updater st' r
                  r : results = results0 ++ (parMap rdeepseq runOne requests)
                  (st', seed', requests) = requestor st seed reqNeeded
                  reqNeeded = max 2 $ maxThreads config - length results0
      updater :: LoopState -> Result -> LoopState
      updater !st !res =
          updateTreeResult st res
      requestor :: LoopState -> Seed -> Int -> (LoopState, Seed, [Request])
      requestor !st0 seed0 !n =
          last $ take n $ iterate r (st0, seed0, [])
          where
            r :: (LoopState, Seed, [Request]) -> (LoopState, Seed, [Request])
            r (!st, seed, rs) = (st', seed', request : rs)
                where
                  seed' = incrSeed seed
                  st' = (loc, raveMap)
                  (_, raveMap) = st
                  request = (leafGameState, path, seed)
                  (loc, (leafGameState, path)) = nextNode st
      nextNode :: LoopState -> (UCTTreeLoc Move, (GameState, [Move]))
      nextNode (!loc, !raveMap) =
          (loc'', (leafGameState, path))
              where
                loc'' = backpropagate (\_x -> 0) updateNodeVisits $ expandNode loc' slHeu moves
                moves = nextMoves leafGameState $ nextMoveColor $ getState leafGameState
                leafGameState = getLeafGameState rootGameState path
                (loc', path) = selectLeafPath policy loc
                policy = policyRaveUCB1 (uctExplorationPercent config) (raveWeight config) raveMap
                slHeu = makeStonesAndLibertyHeuristic leafGameState config
updateTreeResult :: LoopState -> Result -> LoopState
updateTreeResult (!loc, !raveMap) (!score, !playedMoves, !path) =
    (loc', raveMap')
    where
      raveMap' = updateRaveMap raveMap (rateScore score) $ drop (length playedMoves `div` 3) playedMoves
      loc' = backpropagate (rateScore score) updateNodeValue $ getLeaf loc path
simulatePlayout :: GameState -> IO [Move]
simulatePlayout gState = do
  seed <- withSystemRandom (save :: Gen (PrimState IO) -> IO Seed)
  let gState' = getLeafGameState gState []
  (oneState, playedMoves) <- stToIO $ runOneRandom gState' seed
  let score = scoreGameState oneState
  trace ("simulatePlayout " ++ show score) $ return ()
  return $ reverse playedMoves
runOne :: Request -> Result
runOne (gameState, path, seed) =
    (score, playedMoves, path)
    where
      score = scoreGameState endState
      (endState, playedMoves) = runST $ runOneRandom gameState seed
runOneRandom :: GameState -> Seed -> ST s (GameState, [Move])
runOneRandom initState seed = do
  rGen <- restore seed
  run initState 0 rGen []
    where
      run :: GameState -> Int -> Gen s -> [Move] -> ST s (GameState, [Move])
      run state 1000 _ moves = return (trace ("runOneRandom not done after 1000 moves " ++ show moves) state, [])
      run state runCount rGen moves = do
        move <- genMoveRand state rGen
        let state' = updateGameState state move
        case move of
          (Pass passColor) -> do
                    move' <- genMoveRand state' rGen
                    let state'' = updateGameState state' move'
                    case move' of
                      (Pass _) ->
                          return (state'', moves)
                      sm@(Move _) ->
                          run state'' (runCount + 1) rGen (sm : Pass passColor : moves)
                      (Resign _) ->
                          error "runOneRandom encountered Resign"
          sm@(Move _) ->
              run state' (runCount + 1) rGen (sm : moves)
          (Resign _) ->
              error "runOneRandom encountered Resign"
genMoveRand :: GameState -> Gen s -> ST s Move
genMoveRand state rGen =
    pickSane $ freeVertices $ getState state
    where
      pickSane [] =
           return $ Pass color
      pickSane [p] = do
        let stone = Stone p color
        let sane = isSaneMove state stone
        return (if sane
                then Move stone
                else Pass color)
      pickSane ps = do
        p <- pick ps rGen
        let stone = Stone p color
        let sane = isSaneMove state stone
        (if sane
         then return $ Move stone
         else pickSane (ps \\ [p]))
      color = nextMoveColor $ getState state
pick :: [Vertex] -> Gen s -> ST s Vertex
pick as rGen = do
  i <- liftM (`mod` length as) $ uniform rGen
  return $ as !! i
incrSeed :: Seed -> Seed
incrSeed !seed =
    runST $ do
      gen <- restore seed
      x <- uniform gen
      _ <- return $ x + (1 :: Int)
      seed' <- save gen
      return $! seed'
 | 
	lefant/kurt | 
	src/Kurt/GoEngine.hs | 
	gpl-3.0 | 11,157 | 0 | 21 | 4,063 | 3,147 | 1,659 | 1,488 | -1 | -1 | 
| 
	{-# LANGUAGE DataKinds                   #-}
{-# LANGUAGE DeriveGeneric               #-}
{-# LANGUAGE FlexibleInstances           #-}
{-# LANGUAGE GeneralizedNewtypeDeriving  #-}
{-# LANGUAGE LambdaCase                  #-}
{-# LANGUAGE NoImplicitPrelude           #-}
{-# LANGUAGE OverloadedStrings           #-}
{-# LANGUAGE RecordWildCards             #-}
{-# LANGUAGE TypeFamilies                #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module      : Network.AWS.CloudWatchLogs.PutLogEvents
-- Copyright   : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License     : This Source Code Form is subject to the terms of
--               the Mozilla Public License, v. 2.0.
--               A copy of the MPL can be found in the LICENSE file or
--               you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer  : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability   : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Uploads a batch of log events to the specified log stream.
--
-- Every PutLogEvents request must include the 'sequenceToken' obtained from the
-- response of the previous request. An upload in a newly created log stream
-- does not require a 'sequenceToken'.
--
-- The batch of events must satisfy the following constraints:  The maximum
-- batch size is 32,768 bytes, and this size is calculated as the sum of all
-- event messages in UTF-8, plus 26 bytes for each log event. None of the log
-- events in the batch can be more than 2 hours in the future. None of the log
-- events in the batch can be older than 14 days or the retention period of the
-- log group. The log events in the batch must be in chronological ordered by
-- their 'timestamp'. The maximum number of log events in a batch is 1,000.
--
-- <http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html>
module Network.AWS.CloudWatchLogs.PutLogEvents
    (
    -- * Request
      PutLogEvents
    -- ** Request constructor
    , putLogEvents
    -- ** Request lenses
    , pleLogEvents
    , pleLogGroupName
    , pleLogStreamName
    , pleSequenceToken
    -- * Response
    , PutLogEventsResponse
    -- ** Response constructor
    , putLogEventsResponse
    -- ** Response lenses
    , plerNextSequenceToken
    ) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CloudWatchLogs.Types
import qualified GHC.Exts
data PutLogEvents = PutLogEvents
    { _pleLogEvents     :: List1 "logEvents" InputLogEvent
    , _pleLogGroupName  :: Text
    , _pleLogStreamName :: Text
    , _pleSequenceToken :: Maybe Text
    } deriving (Eq, Read, Show)
-- | 'PutLogEvents' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pleLogEvents' @::@ 'NonEmpty' 'InputLogEvent'
--
-- * 'pleLogGroupName' @::@ 'Text'
--
-- * 'pleLogStreamName' @::@ 'Text'
--
-- * 'pleSequenceToken' @::@ 'Maybe' 'Text'
--
putLogEvents :: Text -- ^ 'pleLogGroupName'
             -> Text -- ^ 'pleLogStreamName'
             -> NonEmpty InputLogEvent -- ^ 'pleLogEvents'
             -> PutLogEvents
putLogEvents p1 p2 p3 = PutLogEvents
    { _pleLogGroupName  = p1
    , _pleLogStreamName = p2
    , _pleLogEvents     = withIso _List1 (const id) p3
    , _pleSequenceToken = Nothing
    }
pleLogEvents :: Lens' PutLogEvents (NonEmpty InputLogEvent)
pleLogEvents = lens _pleLogEvents (\s a -> s { _pleLogEvents = a }) . _List1
pleLogGroupName :: Lens' PutLogEvents Text
pleLogGroupName = lens _pleLogGroupName (\s a -> s { _pleLogGroupName = a })
pleLogStreamName :: Lens' PutLogEvents Text
pleLogStreamName = lens _pleLogStreamName (\s a -> s { _pleLogStreamName = a })
-- | A string token that must be obtained from the response of the previous 'PutLogEvents' request.
pleSequenceToken :: Lens' PutLogEvents (Maybe Text)
pleSequenceToken = lens _pleSequenceToken (\s a -> s { _pleSequenceToken = a })
newtype PutLogEventsResponse = PutLogEventsResponse
    { _plerNextSequenceToken :: Maybe Text
    } deriving (Eq, Ord, Read, Show, Monoid)
-- | 'PutLogEventsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'plerNextSequenceToken' @::@ 'Maybe' 'Text'
--
putLogEventsResponse :: PutLogEventsResponse
putLogEventsResponse = PutLogEventsResponse
    { _plerNextSequenceToken = Nothing
    }
plerNextSequenceToken :: Lens' PutLogEventsResponse (Maybe Text)
plerNextSequenceToken =
    lens _plerNextSequenceToken (\s a -> s { _plerNextSequenceToken = a })
instance ToPath PutLogEvents where
    toPath = const "/"
instance ToQuery PutLogEvents where
    toQuery = const mempty
instance ToHeaders PutLogEvents
instance ToJSON PutLogEvents where
    toJSON PutLogEvents{..} = object
        [ "logGroupName"  .= _pleLogGroupName
        , "logStreamName" .= _pleLogStreamName
        , "logEvents"     .= _pleLogEvents
        , "sequenceToken" .= _pleSequenceToken
        ]
instance AWSRequest PutLogEvents where
    type Sv PutLogEvents = CloudWatchLogs
    type Rs PutLogEvents = PutLogEventsResponse
    request  = post "PutLogEvents"
    response = jsonResponse
instance FromJSON PutLogEventsResponse where
    parseJSON = withObject "PutLogEventsResponse" $ \o -> PutLogEventsResponse
        <$> o .:? "nextSequenceToken"
 | 
	dysinger/amazonka | 
	amazonka-cloudwatch-logs/gen/Network/AWS/CloudWatchLogs/PutLogEvents.hs | 
	mpl-2.0 | 5,362 | 0 | 10 | 1,135 | 687 | 412 | 275 | 76 | 1 | 
| 
	{-# LANGUAGE DataKinds          #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric      #-}
{-# LANGUAGE FlexibleInstances  #-}
{-# LANGUAGE NoImplicitPrelude  #-}
{-# LANGUAGE OverloadedStrings  #-}
{-# LANGUAGE RecordWildCards    #-}
{-# LANGUAGE TypeFamilies       #-}
{-# LANGUAGE TypeOperators      #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds      #-}
{-# OPTIONS_GHC -fno-warn-unused-imports    #-}
-- |
-- Module      : Network.Google.Resource.GamesConfiguration.AchievementConfigurations.Get
-- Copyright   : (c) 2015-2016 Brendan Hay
-- License     : Mozilla Public License, v. 2.0.
-- Maintainer  : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability   : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the metadata of the achievement configuration with the given
-- ID.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Publishing API Reference> for @gamesConfiguration.achievementConfigurations.get@.
module Network.Google.Resource.GamesConfiguration.AchievementConfigurations.Get
    (
    -- * REST Resource
      AchievementConfigurationsGetResource
    -- * Creating a Request
    , achievementConfigurationsGet
    , AchievementConfigurationsGet
    -- * Request Lenses
    , acgXgafv
    , acgUploadProtocol
    , acgAchievementId
    , acgAccessToken
    , acgUploadType
    , acgCallback
    ) where
import Network.Google.GamesConfiguration.Types
import Network.Google.Prelude
-- | A resource alias for @gamesConfiguration.achievementConfigurations.get@ method which the
-- 'AchievementConfigurationsGet' request conforms to.
type AchievementConfigurationsGetResource =
     "games" :>
       "v1configuration" :>
         "achievements" :>
           Capture "achievementId" Text :>
             QueryParam "$.xgafv" Xgafv :>
               QueryParam "upload_protocol" Text :>
                 QueryParam "access_token" Text :>
                   QueryParam "uploadType" Text :>
                     QueryParam "callback" Text :>
                       QueryParam "alt" AltJSON :>
                         Get '[JSON] AchievementConfiguration
-- | Retrieves the metadata of the achievement configuration with the given
-- ID.
--
-- /See:/ 'achievementConfigurationsGet' smart constructor.
data AchievementConfigurationsGet =
  AchievementConfigurationsGet'
    { _acgXgafv :: !(Maybe Xgafv)
    , _acgUploadProtocol :: !(Maybe Text)
    , _acgAchievementId :: !Text
    , _acgAccessToken :: !(Maybe Text)
    , _acgUploadType :: !(Maybe Text)
    , _acgCallback :: !(Maybe Text)
    }
  deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AchievementConfigurationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acgXgafv'
--
-- * 'acgUploadProtocol'
--
-- * 'acgAchievementId'
--
-- * 'acgAccessToken'
--
-- * 'acgUploadType'
--
-- * 'acgCallback'
achievementConfigurationsGet
    :: Text -- ^ 'acgAchievementId'
    -> AchievementConfigurationsGet
achievementConfigurationsGet pAcgAchievementId_ =
  AchievementConfigurationsGet'
    { _acgXgafv = Nothing
    , _acgUploadProtocol = Nothing
    , _acgAchievementId = pAcgAchievementId_
    , _acgAccessToken = Nothing
    , _acgUploadType = Nothing
    , _acgCallback = Nothing
    }
-- | V1 error format.
acgXgafv :: Lens' AchievementConfigurationsGet (Maybe Xgafv)
acgXgafv = lens _acgXgafv (\ s a -> s{_acgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
acgUploadProtocol :: Lens' AchievementConfigurationsGet (Maybe Text)
acgUploadProtocol
  = lens _acgUploadProtocol
      (\ s a -> s{_acgUploadProtocol = a})
-- | The ID of the achievement used by this method.
acgAchievementId :: Lens' AchievementConfigurationsGet Text
acgAchievementId
  = lens _acgAchievementId
      (\ s a -> s{_acgAchievementId = a})
-- | OAuth access token.
acgAccessToken :: Lens' AchievementConfigurationsGet (Maybe Text)
acgAccessToken
  = lens _acgAccessToken
      (\ s a -> s{_acgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
acgUploadType :: Lens' AchievementConfigurationsGet (Maybe Text)
acgUploadType
  = lens _acgUploadType
      (\ s a -> s{_acgUploadType = a})
-- | JSONP
acgCallback :: Lens' AchievementConfigurationsGet (Maybe Text)
acgCallback
  = lens _acgCallback (\ s a -> s{_acgCallback = a})
instance GoogleRequest AchievementConfigurationsGet
         where
        type Rs AchievementConfigurationsGet =
             AchievementConfiguration
        type Scopes AchievementConfigurationsGet =
             '["https://www.googleapis.com/auth/androidpublisher"]
        requestClient AchievementConfigurationsGet'{..}
          = go _acgAchievementId _acgXgafv _acgUploadProtocol
              _acgAccessToken
              _acgUploadType
              _acgCallback
              (Just AltJSON)
              gamesConfigurationService
          where go
                  = buildClient
                      (Proxy :: Proxy AchievementConfigurationsGetResource)
                      mempty
 | 
	brendanhay/gogol | 
	gogol-games-configuration/gen/Network/Google/Resource/GamesConfiguration/AchievementConfigurations/Get.hs | 
	mpl-2.0 | 5,179 | 0 | 17 | 1,145 | 704 | 411 | 293 | 106 | 1 | 
| 
	{-# LANGUAGE DataKinds          #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric      #-}
{-# LANGUAGE FlexibleInstances  #-}
{-# LANGUAGE NoImplicitPrelude  #-}
{-# LANGUAGE OverloadedStrings  #-}
{-# LANGUAGE RecordWildCards    #-}
{-# LANGUAGE TypeFamilies       #-}
{-# LANGUAGE TypeOperators      #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds      #-}
{-# OPTIONS_GHC -fno-warn-unused-imports    #-}
-- |
-- Module      : Network.Google.Resource.Storage.Objects.Update
-- Copyright   : (c) 2015-2016 Brendan Hay
-- License     : Mozilla Public License, v. 2.0.
-- Maintainer  : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability   : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an object\'s metadata.
--
-- /See:/ <https://developers.google.com/storage/docs/json_api/ Cloud Storage JSON API Reference> for @storage.objects.update@.
module Network.Google.Resource.Storage.Objects.Update
    (
    -- * REST Resource
      ObjectsUpdateResource
    -- * Creating a Request
    , objectsUpdate
    , ObjectsUpdate
    -- * Request Lenses
    , ouIfMetagenerationMatch
    , ouIfGenerationNotMatch
    , ouIfGenerationMatch
    , ouPredefinedACL
    , ouBucket
    , ouPayload
    , ouUserProject
    , ouIfMetagenerationNotMatch
    , ouObject
    , ouProjection
    , ouProvisionalUserProject
    , ouGeneration
    ) where
import Network.Google.Prelude
import Network.Google.Storage.Types
-- | A resource alias for @storage.objects.update@ method which the
-- 'ObjectsUpdate' request conforms to.
type ObjectsUpdateResource =
     "storage" :>
       "v1" :>
         "b" :>
           Capture "bucket" Text :>
             "o" :>
               Capture "object" Text :>
                 QueryParam "ifMetagenerationMatch" (Textual Int64) :>
                   QueryParam "ifGenerationNotMatch" (Textual Int64) :>
                     QueryParam "ifGenerationMatch" (Textual Int64) :>
                       QueryParam "predefinedAcl" ObjectsUpdatePredefinedACL
                         :>
                         QueryParam "userProject" Text :>
                           QueryParam "ifMetagenerationNotMatch" (Textual Int64)
                             :>
                             QueryParam "projection" ObjectsUpdateProjection :>
                               QueryParam "provisionalUserProject" Text :>
                                 QueryParam "generation" (Textual Int64) :>
                                   QueryParam "alt" AltJSON :>
                                     ReqBody '[JSON] Object :>
                                       Put '[JSON] Object
-- | Updates an object\'s metadata.
--
-- /See:/ 'objectsUpdate' smart constructor.
data ObjectsUpdate =
  ObjectsUpdate'
    { _ouIfMetagenerationMatch :: !(Maybe (Textual Int64))
    , _ouIfGenerationNotMatch :: !(Maybe (Textual Int64))
    , _ouIfGenerationMatch :: !(Maybe (Textual Int64))
    , _ouPredefinedACL :: !(Maybe ObjectsUpdatePredefinedACL)
    , _ouBucket :: !Text
    , _ouPayload :: !Object
    , _ouUserProject :: !(Maybe Text)
    , _ouIfMetagenerationNotMatch :: !(Maybe (Textual Int64))
    , _ouObject :: !Text
    , _ouProjection :: !(Maybe ObjectsUpdateProjection)
    , _ouProvisionalUserProject :: !(Maybe Text)
    , _ouGeneration :: !(Maybe (Textual Int64))
    }
  deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ObjectsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ouIfMetagenerationMatch'
--
-- * 'ouIfGenerationNotMatch'
--
-- * 'ouIfGenerationMatch'
--
-- * 'ouPredefinedACL'
--
-- * 'ouBucket'
--
-- * 'ouPayload'
--
-- * 'ouUserProject'
--
-- * 'ouIfMetagenerationNotMatch'
--
-- * 'ouObject'
--
-- * 'ouProjection'
--
-- * 'ouProvisionalUserProject'
--
-- * 'ouGeneration'
objectsUpdate
    :: Text -- ^ 'ouBucket'
    -> Object -- ^ 'ouPayload'
    -> Text -- ^ 'ouObject'
    -> ObjectsUpdate
objectsUpdate pOuBucket_ pOuPayload_ pOuObject_ =
  ObjectsUpdate'
    { _ouIfMetagenerationMatch = Nothing
    , _ouIfGenerationNotMatch = Nothing
    , _ouIfGenerationMatch = Nothing
    , _ouPredefinedACL = Nothing
    , _ouBucket = pOuBucket_
    , _ouPayload = pOuPayload_
    , _ouUserProject = Nothing
    , _ouIfMetagenerationNotMatch = Nothing
    , _ouObject = pOuObject_
    , _ouProjection = Nothing
    , _ouProvisionalUserProject = Nothing
    , _ouGeneration = Nothing
    }
-- | Makes the operation conditional on whether the object\'s current
-- metageneration matches the given value.
ouIfMetagenerationMatch :: Lens' ObjectsUpdate (Maybe Int64)
ouIfMetagenerationMatch
  = lens _ouIfMetagenerationMatch
      (\ s a -> s{_ouIfMetagenerationMatch = a})
      . mapping _Coerce
-- | Makes the operation conditional on whether the object\'s current
-- generation does not match the given value. If no live object exists, the
-- precondition fails. Setting to 0 makes the operation succeed only if
-- there is a live version of the object.
ouIfGenerationNotMatch :: Lens' ObjectsUpdate (Maybe Int64)
ouIfGenerationNotMatch
  = lens _ouIfGenerationNotMatch
      (\ s a -> s{_ouIfGenerationNotMatch = a})
      . mapping _Coerce
-- | Makes the operation conditional on whether the object\'s current
-- generation matches the given value. Setting to 0 makes the operation
-- succeed only if there are no live versions of the object.
ouIfGenerationMatch :: Lens' ObjectsUpdate (Maybe Int64)
ouIfGenerationMatch
  = lens _ouIfGenerationMatch
      (\ s a -> s{_ouIfGenerationMatch = a})
      . mapping _Coerce
-- | Apply a predefined set of access controls to this object.
ouPredefinedACL :: Lens' ObjectsUpdate (Maybe ObjectsUpdatePredefinedACL)
ouPredefinedACL
  = lens _ouPredefinedACL
      (\ s a -> s{_ouPredefinedACL = a})
-- | Name of the bucket in which the object resides.
ouBucket :: Lens' ObjectsUpdate Text
ouBucket = lens _ouBucket (\ s a -> s{_ouBucket = a})
-- | Multipart request metadata.
ouPayload :: Lens' ObjectsUpdate Object
ouPayload
  = lens _ouPayload (\ s a -> s{_ouPayload = a})
-- | The project to be billed for this request. Required for Requester Pays
-- buckets.
ouUserProject :: Lens' ObjectsUpdate (Maybe Text)
ouUserProject
  = lens _ouUserProject
      (\ s a -> s{_ouUserProject = a})
-- | Makes the operation conditional on whether the object\'s current
-- metageneration does not match the given value.
ouIfMetagenerationNotMatch :: Lens' ObjectsUpdate (Maybe Int64)
ouIfMetagenerationNotMatch
  = lens _ouIfMetagenerationNotMatch
      (\ s a -> s{_ouIfMetagenerationNotMatch = a})
      . mapping _Coerce
-- | Name of the object. For information about how to URL encode object names
-- to be path safe, see Encoding URI Path Parts.
ouObject :: Lens' ObjectsUpdate Text
ouObject = lens _ouObject (\ s a -> s{_ouObject = a})
-- | Set of properties to return. Defaults to full.
ouProjection :: Lens' ObjectsUpdate (Maybe ObjectsUpdateProjection)
ouProjection
  = lens _ouProjection (\ s a -> s{_ouProjection = a})
-- | The project to be billed for this request if the target bucket is
-- requester-pays bucket.
ouProvisionalUserProject :: Lens' ObjectsUpdate (Maybe Text)
ouProvisionalUserProject
  = lens _ouProvisionalUserProject
      (\ s a -> s{_ouProvisionalUserProject = a})
-- | If present, selects a specific revision of this object (as opposed to
-- the latest version, the default).
ouGeneration :: Lens' ObjectsUpdate (Maybe Int64)
ouGeneration
  = lens _ouGeneration (\ s a -> s{_ouGeneration = a})
      . mapping _Coerce
instance GoogleRequest ObjectsUpdate where
        type Rs ObjectsUpdate = Object
        type Scopes ObjectsUpdate =
             '["https://www.googleapis.com/auth/cloud-platform",
               "https://www.googleapis.com/auth/devstorage.full_control"]
        requestClient ObjectsUpdate'{..}
          = go _ouBucket _ouObject _ouIfMetagenerationMatch
              _ouIfGenerationNotMatch
              _ouIfGenerationMatch
              _ouPredefinedACL
              _ouUserProject
              _ouIfMetagenerationNotMatch
              _ouProjection
              _ouProvisionalUserProject
              _ouGeneration
              (Just AltJSON)
              _ouPayload
              storageService
          where go
                  = buildClient (Proxy :: Proxy ObjectsUpdateResource)
                      mempty
 | 
	brendanhay/gogol | 
	gogol-storage/gen/Network/Google/Resource/Storage/Objects/Update.hs | 
	mpl-2.0 | 8,463 | 0 | 24 | 2,060 | 1,290 | 738 | 552 | 177 | 1 | 
| 
	{-# LANGUAGE DataKinds          #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric      #-}
{-# LANGUAGE FlexibleInstances  #-}
{-# LANGUAGE NoImplicitPrelude  #-}
{-# LANGUAGE OverloadedStrings  #-}
{-# LANGUAGE RecordWildCards    #-}
{-# LANGUAGE TypeFamilies       #-}
{-# LANGUAGE TypeOperators      #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds      #-}
{-# OPTIONS_GHC -fno-warn-unused-imports    #-}
-- |
-- Module      : Network.Google.Resource.Analytics.Management.WebProperties.Update
-- Copyright   : (c) 2015-2016 Brendan Hay
-- License     : Mozilla Public License, v. 2.0.
-- Maintainer  : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability   : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an existing web property.
--
-- /See:/ <https://developers.google.com/analytics/ Google Analytics API Reference> for @analytics.management.webproperties.update@.
module Network.Google.Resource.Analytics.Management.WebProperties.Update
    (
    -- * REST Resource
      ManagementWebPropertiesUpdateResource
    -- * Creating a Request
    , managementWebPropertiesUpdate
    , ManagementWebPropertiesUpdate
    -- * Request Lenses
    , mwpuWebPropertyId
    , mwpuPayload
    , mwpuAccountId
    ) where
import           Network.Google.Analytics.Types
import           Network.Google.Prelude
-- | A resource alias for @analytics.management.webproperties.update@ method which the
-- 'ManagementWebPropertiesUpdate' request conforms to.
type ManagementWebPropertiesUpdateResource =
     "analytics" :>
       "v3" :>
         "management" :>
           "accounts" :>
             Capture "accountId" Text :>
               "webproperties" :>
                 Capture "webPropertyId" Text :>
                   QueryParam "alt" AltJSON :>
                     ReqBody '[JSON] WebProperty :>
                       Put '[JSON] WebProperty
-- | Updates an existing web property.
--
-- /See:/ 'managementWebPropertiesUpdate' smart constructor.
data ManagementWebPropertiesUpdate = ManagementWebPropertiesUpdate'
    { _mwpuWebPropertyId :: !Text
    , _mwpuPayload       :: !WebProperty
    , _mwpuAccountId     :: !Text
    } deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ManagementWebPropertiesUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mwpuWebPropertyId'
--
-- * 'mwpuPayload'
--
-- * 'mwpuAccountId'
managementWebPropertiesUpdate
    :: Text -- ^ 'mwpuWebPropertyId'
    -> WebProperty -- ^ 'mwpuPayload'
    -> Text -- ^ 'mwpuAccountId'
    -> ManagementWebPropertiesUpdate
managementWebPropertiesUpdate pMwpuWebPropertyId_ pMwpuPayload_ pMwpuAccountId_ =
    ManagementWebPropertiesUpdate'
    { _mwpuWebPropertyId = pMwpuWebPropertyId_
    , _mwpuPayload = pMwpuPayload_
    , _mwpuAccountId = pMwpuAccountId_
    }
-- | Web property ID
mwpuWebPropertyId :: Lens' ManagementWebPropertiesUpdate Text
mwpuWebPropertyId
  = lens _mwpuWebPropertyId
      (\ s a -> s{_mwpuWebPropertyId = a})
-- | Multipart request metadata.
mwpuPayload :: Lens' ManagementWebPropertiesUpdate WebProperty
mwpuPayload
  = lens _mwpuPayload (\ s a -> s{_mwpuPayload = a})
-- | Account ID to which the web property belongs
mwpuAccountId :: Lens' ManagementWebPropertiesUpdate Text
mwpuAccountId
  = lens _mwpuAccountId
      (\ s a -> s{_mwpuAccountId = a})
instance GoogleRequest ManagementWebPropertiesUpdate
         where
        type Rs ManagementWebPropertiesUpdate = WebProperty
        type Scopes ManagementWebPropertiesUpdate =
             '["https://www.googleapis.com/auth/analytics.edit"]
        requestClient ManagementWebPropertiesUpdate'{..}
          = go _mwpuAccountId _mwpuWebPropertyId (Just AltJSON)
              _mwpuPayload
              analyticsService
          where go
                  = buildClient
                      (Proxy ::
                         Proxy ManagementWebPropertiesUpdateResource)
                      mempty
 | 
	rueshyna/gogol | 
	gogol-analytics/gen/Network/Google/Resource/Analytics/Management/WebProperties/Update.hs | 
	mpl-2.0 | 4,070 | 0 | 16 | 926 | 466 | 278 | 188 | 78 | 1 | 
| 
	{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC  -fno-warn-incomplete-patterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module PontariusService.Types where
import           Control.Applicative
import           Control.Lens
import           Control.Monad.Reader
import           DBus
import           DBus.Signal
import           DBus.Types
import           Data.ByteString (ByteString)
import           Data.Set (Set)
import qualified Data.Set as Set
import           Data.Text (Text)
import qualified Data.Text as Text
import           Data.Time.Clock (UTCTime)
import           Data.Time.Clock.POSIX as Time
import           Data.Typeable
import           Data.UUID (UUID)
import qualified Data.UUID as UUID
import           Data.Word
import qualified Network.Xmpp as Xmpp
type SSID = ByteString
data BatchLink = BatchLinkIgnore
               | BatchLinkExisting UUID
               | BatchLinkNewContact Text
instance Representable BatchLink where
  type RepType BatchLink = 'TypeStruct '[ 'DBusSimpleType 'TypeByte
                                        , 'DBusSimpleType 'TypeString]
  toRep BatchLinkIgnore = DBVStruct (StructCons
                                    (DBVByte 0) (StructSingleton (DBVString "")))
  toRep (BatchLinkExisting uuid)
    = DBVStruct (StructCons (DBVByte 1) (StructSingleton (toRep uuid)))
  toRep (BatchLinkNewContact name)
    = DBVStruct (StructCons (DBVByte 2) (StructSingleton (toRep name)))
  fromRep
    (DBVStruct (StructCons (DBVByte 0) (StructSingleton _)))
    = Just BatchLinkIgnore
  fromRep (DBVStruct (StructCons (DBVByte 1) (StructSingleton uuid)))
    = BatchLinkExisting <$> (fromRep uuid)
  fromRep (DBVStruct (StructCons (DBVByte 2) (StructSingleton (DBVString name))))
    = Just $ BatchLinkNewContact name
data PontariusState = CredentialsUnset
                    | IdentityNotFound
                    | IdentitiesAvailable
                    | CreatingIdentity
                    | Disabled
                    | Authenticating
                    | Authenticated
                    | AuthenticationDenied
                      deriving (Show, Eq)
data AccountState = AccountEnabled
                  | AccountDisabled
                    deriving (Show, Eq)
data PeerStatus = Unavailable
                | Available
                  deriving (Show, Eq)
instance Representable UTCTime where
    type RepType UTCTime = 'DBusSimpleType 'TypeUInt32
    toRep = DBVUInt32 . round . utcTimeToPOSIXSeconds
    fromRep (DBVUInt32 x) = Just . posixSecondsToUTCTime $ fromIntegral x
instance DBus.Representable Xmpp.Jid where
    type RepType Xmpp.Jid = 'DBusSimpleType 'TypeString
    toRep = DBus.DBVString . Xmpp.jidToText
    fromRep (DBus.DBVString s) = Xmpp.jidFromText s
instance (Ord a, DBus.Representable a) => DBus.Representable (Set a) where
    type RepType (Set a) = RepType [a]
    toRep = toRep . Set.toList
    fromRep = fmap Set.fromList . fromRep
instance Representable (Maybe KeyID) where
    type RepType (Maybe KeyID) = RepType KeyID
    toRep Nothing = toRep Text.empty
    toRep (Just k) = toRep k
    fromRep v = case fromRep v of
        Nothing -> Nothing
        Just v' | Text.null v' -> Just Nothing
                | otherwise -> Just (Just v')
instance Representable (Maybe UTCTime) where
    type RepType (Maybe UTCTime) = RepType UTCTime
    toRep Nothing = toRep (0 :: Word32)
    toRep (Just t) = toRep t
    fromRep v = case fromRep v of
        Nothing -> Nothing
        Just t' | t' == (0 :: Word32) -> Just Nothing
                | otherwise -> Just . Just $ posixSecondsToUTCTime
                               $ fromIntegral t'
type KeyID = Text
type SessionID = ByteString
data ConnectionStatus = Connected
                      | Disconnected
                      deriving (Show, Eq, Ord)
data InitResponse = KeyOK
                  | SelectKey
data Ent = Ent { entityJid :: Xmpp.Jid
               , entityDisplayName :: Text
               , entityDescription :: Text
               } deriving (Show, Typeable)
data AkeEvent = AkeEvent { akeEventStart :: UTCTime
                         , akeEventSuccessfull :: Bool
                         , akeEventPeerJid :: Xmpp.Jid
                         , akeEventOurJid :: Xmpp.Jid
                         , akeEventPeerkeyID :: KeyID
                         , akeEventOurkeyID :: KeyID
                         } deriving (Show, Eq)
data ChallengeEvent =
    ChallengeEvent { challengeEventChallengeOutgoing :: Bool
                   , challengeEventStarted :: UTCTime
                   , challengeEventCompleted :: UTCTime
                   , challengeEventQuestion :: Text
                   , challengeEventResult :: Text
                   } deriving (Show, Eq)
data RevocationEvent =
    RevocationEvent { revocationEventKeyID :: KeyID
                    , revocationEventTime :: UTCTime
                    }
data RevocationSignalEvent =
    RevocationlEvent { revocationSignalEventKeyID :: KeyID
                          , revocationSignalEventTime :: UTCTime
                          }
makePrisms ''PontariusState
makeRepresentable ''PontariusState
makePrisms ''AccountState
makeRepresentable ''AccountState
makeRepresentable ''RevocationSignalEvent
makeRepresentable ''ConnectionStatus
makeRepresentable ''InitResponse
makeRepresentable ''Ent
makeRepresentable ''AkeEvent
makeRepresentable ''ChallengeEvent
makeRepresentable ''RevocationEvent
makeRepresentable ''PeerStatus
instance DBus.Representable UUID where
    type RepType UUID = RepType Text
    toRep = toRep . Text.pack . UUID.toString
    fromRep = UUID.fromString . Text.unpack <=< fromRep
data AddPeerFailed =
    AddPeerFailed { addPeerFailedPeer :: !Xmpp.Jid
                  , addPeerFailedReason :: !Text
                  } deriving (Show)
makeRepresentable ''AddPeerFailed
makeLensesWith camelCaseFields ''AddPeerFailed
data RemovePeerFailed =
    RemovePeerFailed { removePeerFailedPeer :: !Xmpp.Jid
                     , removePeerFailedReason :: !Text
                     } deriving (Show)
makeRepresentable ''RemovePeerFailed
makeLensesWith camelCaseFields ''RemovePeerFailed
 | 
	pontarius/pontarius-service | 
	source/PontariusService/Types.hs | 
	agpl-3.0 | 6,475 | 0 | 14 | 1,907 | 1,507 | 798 | 709 | -1 | -1 | 
| 
	-- | This module provides the data type and parser for a trait file
module Trait (
  Trait(..)
  , defaultTrait
  , trait
  ) where
import Maker
import Modifier
import Scoped(Label)
data Trait = Trait {
  trait_name :: Label
  , agnatic :: Bool
  , birth :: Double -- ^ Chance of being assigned on birth. Default 0
  , cached :: Bool
  , cannot_inherit :: Bool
  , cannot_marry :: Bool
  , caste_tier :: Maybe Int -- ^ The trait is a caste trait, and this
                  -- defines the order of the castes.
  , customizer :: Bool -- ^ Blocks the trait from being available in the Designer
  , education :: Bool
  , immortal :: Bool
  , in_hiding :: Bool
  , inbred :: Bool
  , incapacitating :: Bool
  , inherit_chance :: Double
  , is_epidemic :: Bool
  , is_health :: Bool
  , is_illness :: Bool
  , leader :: Bool
  , leadership_traits :: Maybe Int
  , lifestyle :: Bool
  , opposites :: [Label]
  , personality :: Bool
  , prevent_decadence :: Bool
  , priest :: Bool
  , pilgrimage :: Bool
  , random :: Bool
  , rebel_inherited :: Bool -- ^ Unknown purpose
  , religious :: Bool
  , religious_branch :: Maybe Label
  , ruler_designer_cost :: Maybe Int -- ^ The postive cost in the Ruler Designer
  , tolerates :: [Label] -- ^ A list of the religion groups tolerated by this character
  , modifiers :: [Modifier]
  } deriving (Eq, Ord, Show)
trait :: Maker Trait
trait = Trait
        <$> label key
        <*> boolProp "agnatic"
        <*> ((number ~@ "birth") `defaultingTo` 0)
        <*> boolProp "cached"
        <*> boolProp "cannot_inherit"
        <*> boolProp "cannot_marry"
        <*> intProp "caste_tier"
        <*> boolProp "customizer"
        <*> boolProp "education"
        <*> boolProp "immortal"
        <*> boolProp "in_hiding"
        <*> boolProp "inbred"
        <*> boolProp "incapacitating"
        <*> (number ~@ "inherit_chance") `defaultingTo` 0
        <*> boolProp "is_epidemic"
        <*> boolProp "is_health"
        <*> boolProp "is_illness"
        <*> boolProp "leader"
        <*> intProp "leadership_traits"
        <*> boolProp "lifestyle"
        <*> (opposites @@ "opposites") `defaultingTo` []
        <*> boolProp "personality"
        <*> boolProp "prevent_decadence"
        <*> boolProp "priest"
        <*> boolProp "pilgrimage"
        <*> boolProp "random"
        <*> boolProp "rebel_inherited"
        <*> boolProp "religious"
        <*> fetchString @? "religious_branch"
        <*> intProp "ruler_designer_cost"
        <*> tolerations
        <*> tryMap modifier
  where boolProp key = ((fetchBool @@ key) `defaultingTo` False) <?> key
        intProp :: Label → Maker (Maybe Int)
        intProp key = fmap round <$> number ~? key <?> key
        opposites = error "opposite traits are not implemented"
        tolerations = return []
defaultTrait :: Trait
defaultTrait =
  Trait { trait_name = undefined, agnatic = False, birth = 0, cached = False
        , cannot_inherit = False, cannot_marry = False, caste_tier = Nothing
        , customizer = False, education = False, immortal = False
        , in_hiding = False, inbred = False, incapacitating = False
        , inherit_chance = 0, is_epidemic = False, is_health = False
        , is_illness = False, leader = False, leadership_traits = Nothing
        , lifestyle = False, opposites = [], personality = False
        , prevent_decadence = False, priest = False, pilgrimage = False
        , random = False, rebel_inherited = False, religious = False
        , religious_branch = Nothing, ruler_designer_cost = Nothing
        , tolerates = [], modifiers = [] }
 | 
	joelwilliamson/validator | 
	Trait.hs | 
	agpl-3.0 | 3,593 | 0 | 41 | 970 | 847 | 492 | 355 | -1 | -1 | 
| 
	-- Copyright (C) 2016-2017 Red Hat, Inc.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE OverloadedStrings #-}
module BDCS.RPM.Sources(mkSource)
 where
import           Database.Esqueleto(Key)
import qualified Data.Text as T
import BDCS.DB(Projects, Sources(..))
import BDCS.Exceptions(DBException(..), throwIfNothing)
import RPM.Tags(Tag, findStringTag)
mkSource :: [Tag] -> Key Projects -> Sources
mkSource tags projectId = let
    license = T.pack $ findStringTag "License" tags `throwIfNothing` MissingRPMTag "License"
    version = T.pack $ findStringTag "Version" tags `throwIfNothing` MissingRPMTag "Version"
    -- FIXME:  Where to get this from?
    source_ref = "SOURCE_REF"
 in
    Sources projectId license version source_ref
 | 
	dashea/bdcs | 
	importer/BDCS/RPM/Sources.hs | 
	lgpl-2.1 | 1,380 | 0 | 11 | 234 | 192 | 116 | 76 | 13 | 1 | 
| 
	{-|
Module      : Main-nowx
Description : Модуль с точкой входа для консольной версии приложения
License     : LGPLv3
-}
module Main where
import Kernel
import PlayerConsole
import DrawingConsole
import Controller
import AIPlayer
-- | Точка входа для консольной версии программы
main :: IO ()
main = do
    winner <- run cfg player1 player2 [drawing]
    case winner of
      Winner color -> putStrLn $ (show color) ++ " player wins!"
      DrawBy color -> putStrLn $ "It's a trap for " ++ (show color) ++ " player!"
    return ()
  where
    cfg = russianConfig
    game = createGame cfg
    player1 = createAIPlayer 1 2
    player2 = createPlayerConsole
    drawing = createDrawingConsole
 | 
	cmc-haskell-2015/checkers | 
	src/Main-nowx.hs | 
	lgpl-3.0 | 805 | 0 | 13 | 188 | 155 | 81 | 74 | 18 | 2 | 
| 
	
{-# LANGUAGE OverloadedStrings #-}
module Mdb.Status ( doStatus ) where
import           Control.Monad ( when )
import           Control.Monad.Catch (MonadMask)
import           Control.Monad.IO.Class ( MonadIO, liftIO )
import           Control.Monad.Logger ( logWarnN, logDebugN, logInfoN )
import           Control.Monad.Reader ( ask )
import qualified Database.SQLite.Simple as SQL
import           Data.Monoid ( (<>) )
import qualified Data.Text as T
import           System.IO.Error ( tryIOError )
import           System.Posix.Files ( getFileStatus, modificationTimeHiRes )
import           Mdb.CmdLine ( OptStatus(..) )
import           Mdb.Database ( MDB, dbExecute, runMDB', withConnection )
import           Mdb.Types ( FileId )
doStatus :: (MonadMask m, MonadIO m) => OptStatus -> MDB m ()
doStatus = withFilesSeq . checkFile
type FileInfo = (FileId, FilePath)
withFilesSeq :: (MonadIO m, MonadMask m) => (FileInfo -> MDB IO ()) -> MDB m ()
withFilesSeq f = withConnection $ \c -> do
    mdb <- ask
    liftIO $ SQL.withStatement c "SELECT file_id, file_name FROM file ORDER BY file_id" $ \stmt ->
        let
            go = SQL.nextRow stmt >>= \mfi -> case mfi of
                Nothing -> return ()
                Just fi -> (runMDB' mdb $ f fi) >> go
        in go
checkFile :: (MonadIO m, MonadMask m) => OptStatus -> FileInfo -> MDB m ()
checkFile op (fid, fp) = do
    efs <- liftIO $ tryIOError $ getFileStatus fp
    case efs of
        Left ioe    -> do
            logWarnN $ T.pack ( show ioe )
            when (removeMissing op) $ do
                logInfoN $ "removing file with ID " <> (T.pack $ show fid)
                dbExecute "DELETE FROM file WHERE file_id = ?" (SQL.Only fid)
        Right fs    -> logDebugN $ T.pack (show $ modificationTimeHiRes fs)
 | 
	waldheinz/mdb | 
	src/lib/Mdb/Status.hs | 
	apache-2.0 | 1,802 | 0 | 23 | 523 | 569 | 307 | 262 | 37 | 2 | 
| 
	module Serf.Event where
import Serf.Member
import Control.Applicative
import Control.Monad.IO.Class
import System.Environment
import System.Exit
import System.IO
import Text.Parsec
type SerfError = String
data SerfEvent = MemberJoin Member
               | MemberLeave Member
               | MemberFailed Member
               | MemberUpdate Member
               | MemberReap Member
               | User
               | Query
               | Unknown String
getSerfEvent :: IO (Either SerfError SerfEvent)
getSerfEvent = getEnv "SERF_EVENT" >>= fromString
  where
    fromString :: String -> IO (Either SerfError SerfEvent)
    fromString "member-join" = readMemberEvent MemberJoin
    fromString "member-leave" = readMemberEvent MemberLeave
    fromString "member-failed" = readMemberEvent MemberFailed
    fromString "member-update" = readMemberEvent MemberUpdate
    fromString "member-reap" = readMemberEvent MemberReap
    fromString "user"  = return $ Right User
    fromString "query" = return $ Right Query
    fromString unk     = return . Right $ Unknown unk
    readMemberEvent :: (Member -> SerfEvent) -> IO (Either SerfError SerfEvent)
    readMemberEvent f = addMember f <$> readMember
    addMember :: (Member -> SerfEvent)
              -> Either ParseError Member
              -> Either SerfError SerfEvent
    addMember _ (Left err) = Left $ show err
    addMember f (Right m)  = Right $ f m
    readMember :: IO (Either ParseError Member)
    readMember = memberFromString <$> getLine
isMemberEvent :: SerfEvent -> Bool
isMemberEvent (MemberJoin _)   = True
isMemberEvent (MemberLeave _)  = True
isMemberEvent (MemberFailed _) = True
isMemberEvent (MemberUpdate _) = True
isMemberEvent (MemberReap _)   = True
isMemberEvent _                = False
type EventHandler m = SerfEvent -> m ()
handleEventWith :: MonadIO m => EventHandler m -> m ()
handleEventWith hdlr = do
  evt <- liftIO getSerfEvent
  case evt of
    Left err -> liftIO $ hPutStrLn stderr err >> exitFailure
    Right ev -> hdlr ev
 | 
	lstephen/box | 
	src/main/ansible/roles/serf/files/Serf/Event.hs | 
	apache-2.0 | 2,110 | 0 | 12 | 576 | 572 | 289 | 283 | 51 | 9 | 
| 
	{-# LANGUAGE ExplicitForAll, Rank2Types #-} 
-- | An implementation of Reagents (http://www.mpi-sws.org/~turon/reagents.pdf)
-- NOTE: currently this is just a very tiny core of the Reagent design.  Needs
-- lots of work.
module Data.Concurrent.Internal.Reagent where
  
import Data.IORef  
import Data.Atomics
import Prelude hiding (succ, fail)
type Reagent a = forall b. (a -> IO b) -> IO b -> IO b
-- | Execute a Reagent.
{-# INLINE react #-}
react :: Reagent a -> IO a
react r = try where 
  try      = r finish try
  finish x = return x
  
-- | Like atomicModifyIORef, but uses CAS and permits the update action to force
-- a retry by returning Nothing  
  
{-# INLINE atomicUpdate #-}
atomicUpdate :: IORef a -> (a -> Maybe (a, b)) -> Reagent b  
atomicUpdate r f succ fail = do
  curTicket <- readForCAS r
  let cur = peekTicket curTicket
  case f cur of
    Just (new, out) -> do
      (done, _) <- casIORef r curTicket new
      if done then succ out else fail
    Nothing -> fail
atomicUpdate_ :: IORef a -> (a -> a) -> Reagent ()
atomicUpdate_ r f = atomicUpdate r (\x -> Just (f x, ()))
    
postCommit :: Reagent a -> (a -> IO b) -> Reagent b
postCommit r f succ fail = r (\x -> f x >>= succ) fail
choice :: Reagent a -> Reagent a -> Reagent a
choice _ _ = error "TODO"
 | 
	rrnewton/concurrent-skiplist | 
	src/Data/Concurrent/Internal/Reagent.hs | 
	apache-2.0 | 1,287 | 0 | 13 | 297 | 420 | 216 | 204 | 27 | 3 | 
| 
	{-# LANGUAGE TemplateHaskell #-}
-- Copyright (C) 2010-2012 John Millikin <john@john-millikin.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module DBusTests.Signature (test_Signature) where
import           Test.Chell
import           Test.Chell.QuickCheck
import           Test.QuickCheck hiding ((.&.), property)
import           DBus
import           DBusTests.Util
test_Signature :: Suite
test_Signature = suite "Signature"
	[ test_BuildSignature
	, test_ParseSignature
	, test_ParseInvalid
	, test_FormatSignature
	, test_IsAtom
	, test_ShowType
	]
test_BuildSignature :: Test
test_BuildSignature = property "signature" prop where
	prop = forAll gen_SignatureTypes check
	check types = case signature types of
		Nothing -> False
		Just sig -> signatureTypes sig == types
test_ParseSignature :: Test
test_ParseSignature = property "parseSignature" prop where
	prop = forAll gen_SignatureString check
	check (s, types) = case parseSignature s of
		Nothing -> False
		Just sig -> signatureTypes sig == types
test_ParseInvalid :: Test
test_ParseInvalid = assertions "parse-invalid" $ do
	-- at most 255 characters
	$expect (just (parseSignature (replicate 254 'y')))
	$expect (just (parseSignature (replicate 255 'y')))
	$expect (nothing (parseSignature (replicate 256 'y')))
	
	-- length also enforced by 'signature'
	$expect (just (signature (replicate 255 TypeWord8)))
	$expect (nothing (signature (replicate 256 TypeWord8)))
	
	-- struct code
	$expect (nothing (parseSignature "r"))
	
	-- empty struct
	$expect (nothing (parseSignature "()"))
	$expect (nothing (signature [TypeStructure []]))
	
	-- dict code
	$expect (nothing (parseSignature "e"))
	
	-- non-atomic dict key
	$expect (nothing (parseSignature "a{vy}"))
	$expect (nothing (signature [TypeDictionary TypeVariant TypeVariant]))
test_FormatSignature :: Test
test_FormatSignature = property "formatSignature" prop where
	prop = forAll gen_SignatureString check
	check (s, _) = let
		Just sig = parseSignature s
		in formatSignature sig == s
test_IsAtom :: Test
test_IsAtom = assertions "IsAtom" $ do
	let Just sig = signature []
	assertAtom TypeSignature sig
test_ShowType :: Test
test_ShowType = assertions "show-type" $ do
	$expect (equal "Bool" (show TypeBoolean))
	$expect (equal "Bool" (show TypeBoolean))
	$expect (equal "Word8" (show TypeWord8))
	$expect (equal "Word16" (show TypeWord16))
	$expect (equal "Word32" (show TypeWord32))
	$expect (equal "Word64" (show TypeWord64))
	$expect (equal "Int16" (show TypeInt16))
	$expect (equal "Int32" (show TypeInt32))
	$expect (equal "Int64" (show TypeInt64))
	$expect (equal "Double" (show TypeDouble))
	$expect (equal "UnixFd" (show TypeUnixFd))
	$expect (equal "String" (show TypeString))
	$expect (equal "Signature" (show TypeSignature))
	$expect (equal "ObjectPath" (show TypeObjectPath))
	$expect (equal "Variant" (show TypeVariant))
	$expect (equal "[Word8]" (show (TypeArray TypeWord8)))
	$expect (equal "Dict Word8 (Dict Word8 Word8)" (show (TypeDictionary TypeWord8 (TypeDictionary TypeWord8 TypeWord8))))
	$expect (equal "(Word8, Word16)" (show (TypeStructure [TypeWord8, TypeWord16])))
gen_SignatureTypes :: Gen [Type]
gen_SignatureTypes = do
	(_, ts) <- gen_SignatureString
	return ts
gen_SignatureString :: Gen (String, [Type])
gen_SignatureString = gen where
	anyType = oneof [atom, container]
	atom = elements
		[ ("b", TypeBoolean)
		, ("y", TypeWord8)
		, ("q", TypeWord16)
		, ("u", TypeWord32)
		, ("t", TypeWord64)
		, ("n", TypeInt16)
		, ("i", TypeInt32)
		, ("x", TypeInt64)
		, ("d", TypeDouble)
		, ("h", TypeUnixFd)
		, ("s", TypeString)
		, ("o", TypeObjectPath)
		, ("g", TypeSignature)
		]
	container = oneof
		[ return ("v", TypeVariant)
		, array
		, dict
		, struct
		]
	array = do
		(tCode, tEnum) <- anyType
		return ('a':tCode, TypeArray tEnum)
	dict = do
		(kCode, kEnum) <- atom
		(vCode, vEnum) <- anyType
		return (concat ["a{", kCode, vCode, "}"], TypeDictionary kEnum vEnum)
	struct = do
		ts <- listOf1 (halfSized anyType)
		let (codes, enums) = unzip ts
		return ("(" ++ concat codes ++ ")", TypeStructure enums)
	gen = do
		types <- listOf anyType
		let (codes, enums) = unzip types
		let chars = concat codes
		if length chars > 255
			then halfSized gen
			else return (chars, enums)
instance Arbitrary Signature where
	arbitrary = do
		ts <- gen_SignatureTypes
		let Just sig = signature ts
		return sig
 | 
	jmillikin/haskell-dbus | 
	tests/DBusTests/Signature.hs | 
	apache-2.0 | 4,901 | 16 | 16 | 860 | 1,580 | 786 | 794 | 119 | 2 | 
| 
	{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE DeriveDataTypeable         #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures             #-}
{-# LANGUAGE LambdaCase                 #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE PolyKinds                  #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# OPTIONS_GHC -Wall #-}
-- TODO: Complex Numbers
{-|
Embeds Fortran's type system in Haskell via the 'D' GADT.
== Note: Phantom Types and GADTs
Lots of the data types in this module are parameterised by phantom types. These
are types which appear at the type-level, but not at the value level. They are
there to make things more type-safe.
In addition, a lot of the data types are GADTs. In a phantom-type-indexed GADT,
the phantom type often restricts which GADT constructors a particular value may
be an instance of. This is very useful for restricting value-level terms based
on type-level information.
-}
module Language.Fortran.Model.Types where
import           Data.Int                              (Int16, Int32, Int64,
                                                        Int8)
import           Data.List                             (intersperse)
import           Data.Monoid                           (Endo (..))
import           Data.Typeable                         (Typeable)
import           Data.Word                             (Word8)
import           Data.Singletons.TypeLits
import           Data.Vinyl                            hiding (Field)
import           Data.Vinyl.Functor
import           Language.Expression.Pretty
import           Language.Fortran.Model.Singletons
--------------------------------------------------------------------------------
-- * Fortran Types
{-|
This is the main embedding of Fortran types. A value of type @D a@ represents
the Fortran type which corresponds to the Haskell type @a@. @a@ is a phantom
type parameter. There is at most one instance of @D a@ for each @a@. This means
that a value of type @D a@ acts as a kind of proof that it possible to have a
Fortran type corresponding to the Haskell type @a@ -- and that when you match on
@D a@ knowing the particular @a@ you have, you know which constructor you will
get. This is a nice property because it means that GHC (with
@-fwarn-incomplete-patterns@) will not warn when you match on an impossible
case. It eliminates situations where you'd otherwise write @error "impossible:
..."@.
* @'DPrim' p :: D ('PrimS' a)@ is for primitive types. It contains a value @p@
  of type @'Prim' p k a@ for some @p@, @k@, @a@. When matching on something of
  type @D ('PrimS' a)@, you know it can only contain a primitive type.
* @'DArray' i v :: D ('Array' i v)@ is for arrays. It contains instances of @'Index'
  i@ and @'ArrValue' a@. @'Index' i@ is a proof that @i@ can be used as an index,
  and @'ArrValue' a@ is a proof that @a@ can be stored in arrays.
* @'DData' s xs :: D ('Record' name fs)@ is for user-defined data types. The
  type has a name, represented at the type level by the type parameter @name@ of
  kind 'Symbol'. The constructor contains @s :: 'SSymbol' name@, which acts as a
  sort of value-level representation of the name. 'SSymbol' is from the
  @singletons@ library. It also contains @xs :: 'Rec' ('Field' D) fs@. @fs@ is a
  type-level list of pairs, pairing field names with field types. @'Field' D
  '(fname, b)@ is a value-level pair of @'SSymbol' fname@ and @D b@. The vinyl
  record is a list of fields, one for each pair in @fs@.
-}
data D a where
  DPrim :: Prim p k a -> D (PrimS a)
  DArray :: Index i -> ArrValue a -> D (Array i a)
  DData :: SSymbol name -> Rec (Field D) fs -> D (Record name fs)
--------------------------------------------------------------------------------
-- * Semantic Types
newtype Bool8  = Bool8 { getBool8 :: Int8 } deriving (Show, Num, Eq, Typeable)
newtype Bool16 = Bool16 { getBool16 :: Int16 } deriving (Show, Num, Eq, Typeable)
newtype Bool32 = Bool32 { getBool32 :: Int32 } deriving (Show, Num, Eq, Typeable)
newtype Bool64 = Bool64 { getBool64 :: Int64 } deriving (Show, Num, Eq, Typeable)
newtype Char8  = Char8 { getChar8 :: Word8 } deriving (Show, Num, Eq, Typeable)
{-|
This newtype wrapper is used in 'DPrim' for semantic primitive types. This means
that when matching on something of type @'D' ('PrimS' a)@, we know it can't be
an array or a record.
-}
newtype PrimS a = PrimS { getPrimS :: a }
  deriving (Show, Eq, Typeable)
--------------------------------------------------------------------------------
-- * Primitive Types
{-|
Lists the allowed primitive Fortran types. For example, @'PInt8' :: 'Prim' 'P8
''BTInt' 'Int8'@ represents 8-bit integers. 'Prim' has three phantom type
parameters: precision, base type and semantic Haskell type. Precision is the
number of bits used to store values of that type. The base type represents the
corresponding Fortran base type, e.g. @integer@ or @real@. Constructors are only
provided for those Fortran types which are semantically valid, so for example no
constructor is provided for a 16-bit real. A value of type @'Prim' p k a@ can be
seen as a proof that there is some Fortran primitive type with those parameters.
-}
data Prim p k a where
  PInt8          :: Prim 'P8   'BTInt     Int8
  PInt16         :: Prim 'P16  'BTInt     Int16
  PInt32         :: Prim 'P32  'BTInt     Int32
  PInt64         :: Prim 'P64  'BTInt     Int64
  PBool8         :: Prim 'P8   'BTLogical Bool8
  PBool16        :: Prim 'P16  'BTLogical Bool16
  PBool32        :: Prim 'P32  'BTLogical Bool32
  PBool64        :: Prim 'P64  'BTLogical Bool64
  PFloat         :: Prim 'P32  'BTReal    Float
  PDouble        :: Prim 'P64  'BTReal    Double
  PChar          :: Prim 'P8   'BTChar    Char8
--------------------------------------------------------------------------------
-- * Arrays
-- | Specifies which types can be used as array indices.
data Index a where
  Index :: Prim p 'BTInt a -> Index (PrimS a)
-- | Specifies which types can be stored in arrays. Currently arrays of arrays
-- are not supported.
data ArrValue a where
  ArrPrim :: Prim p k a -> ArrValue (PrimS a)
  ArrData :: SSymbol name -> Rec (Field ArrValue) fs -> ArrValue (Record name fs)
-- | An array with a phantom index type. Mostly used at the type-level to
-- constrain instances of @'D' (Array i a)@ etc.
newtype Array i a = Array [a]
--------------------------------------------------------------------------------
-- * Records
-- | A field over a pair of name and value type.
data Field f field where
  Field :: SSymbol name -> f a -> Field f '(name, a)
-- | A type of records with the given @name@ and @fields@. Mostly used at the
-- type level to constrain instances of @'D' (Record name fields)@ etc.
data Record name fields where
  Record :: SSymbol name -> Rec (Field Identity) fields -> Record name fields
--------------------------------------------------------------------------------
-- * Combinators
-- | Any Fortran index type is a valid Fortran type.
dIndex :: Index i -> D i
dIndex (Index p) = DPrim p
-- | Anything that can be stored in Fortran arrays is a valid Fortran type.
dArrValue :: ArrValue a -> D a
dArrValue (ArrPrim p) = DPrim p
dArrValue (ArrData nameSym fieldArrValues) =
  DData nameSym (rmap (overField' dArrValue) fieldArrValues)
-- | Given a field with known contents, we can change the functor and value
-- type.
overField :: (f a -> g b) -> Field f '(name, a) -> Field g '(name, b)
overField f (Field n x) = Field n (f x)
-- | Given a field with unknown contents, we can change the functor but not the
-- value type.
overField' :: (forall a. f a -> g a) -> Field f nv -> Field g nv
overField' f (Field n x) = Field n (f x)
traverseField' :: (Functor t) => (forall a. f a -> t (g a)) -> Field f nv -> t (Field g nv)
traverseField' f (Field n x) = Field n <$> f x
-- | Combine two fields over the same name-value pair but (potentially)
-- different functors.
zipFieldsWith :: (forall a. f a -> g a -> h a) -> Field f nv -> Field g nv -> Field h nv
zipFieldsWith f (Field _ x) (Field n y) = Field n (f x y)
zip3FieldsWith
  :: (forall a. f a -> g a -> h a -> i a)
  -> Field f nv
  -> Field g nv
  -> Field h nv
  -> Field i nv
zip3FieldsWith f (Field _ x) (Field _ y) (Field n z) = Field n (f x y z)
--------------------------------------------------------------------------------
--  Pretty Printing
instance Pretty1 (Prim p k) where
  prettys1Prec p = \case
    PInt8   -> showString "integer8"
    PInt16  -> showString "integer16"
    PInt32  -> showString "integer32"
    PInt64  -> showString "integer64"
    PFloat  -> showString "real"
    PDouble -> showParen (p > 8) $ showString "double precision"
    PBool8  -> showString "logical8"
    PBool16 -> showString "logical16"
    PBool32 -> showString "logical32"
    PBool64 -> showString "logical64"
    PChar   -> showString "character"
instance Pretty1 ArrValue where
  prettys1Prec p = prettys1Prec p . dArrValue
instance (Pretty1 f) => Pretty1 (Field f) where
  prettys1Prec _ = \case
    Field fname x ->
      prettys1Prec 0 x .
      showString " " .
      withKnownSymbol fname (showString (symbolVal fname))
-- | e.g. "type custom_type { character a, integer array b }"
instance Pretty1 D where
  prettys1Prec p = \case
    DPrim px -> prettys1Prec p px
    DArray _ pv -> prettys1Prec p pv . showString " array"
    DData rname fields ->
        showParen (p > 8)
      $ showString "type "
      . withKnownSymbol rname (showString (symbolVal rname))
      . showString "{ "
      . appEndo ( mconcat
              . intersperse (Endo $ showString ", ")
              . recordToList
              . rmap (Const . Endo . prettys1Prec 0)
              $ fields)
      . showString " }"
 | 
	dorchard/camfort | 
	src/Language/Fortran/Model/Types.hs | 
	apache-2.0 | 9,913 | 0 | 20 | 2,416 | 1,791 | 939 | 852 | 114 | 1 | 
| 
	{-# LANGUAGE TupleSections #-}
module Arbitrary.TestModule where
import Data.Integrated.TestModule
import Test.QuickCheck
import Data.ModulePath
import Control.Applicative
import Arbitrary.Properties
import Test.Util
import Filesystem.Path.CurrentOS
import Prelude hiding (FilePath)
import qualified Arbitrary.ModulePath as MP
import qualified Data.Set as S
testModulePath :: Gen Char -> S.Set ModulePath -> Gen ModulePath
testModulePath subpath avoided =
  suchThat
    (fromModPath <$> MP.toModulePath subpath)
    (not . flip S.member avoided)
  where
    fromModPath :: ModulePath -> ModulePath
    fromModPath (ModulePath pth) =
      ModulePath $ take (length pth - 1) pth ++ [testFormat $ last pth]
toTestModule :: ModulePath -> Gen TestModule
toTestModule mp = do
  props <- arbitrary :: Gen Properties
  return $ TestModule mp (list props)
-- Generate a random test file, care must be taken to avoid generating
-- the same path twice
toGenerated :: Gen Char -> S.Set ModulePath -> Gen (FilePath, TestModule)
toGenerated subpath avoided = do
  mp <- testModulePath subpath avoided
  (relPath mp,) <$> toTestModule mp
 | 
	jfeltz/tasty-integrate | 
	tests/Arbitrary/TestModule.hs | 
	bsd-2-clause | 1,129 | 0 | 12 | 186 | 314 | 165 | 149 | 28 | 1 | 
| 
	{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Root where
import Foundation
-- This is a handler function for the GET request method on the RootR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getRootR :: Handler RepHtml
getRootR = do
    defaultLayout $ do
        h2id <- lift newIdent
        setTitle "TierList homepage"
        $(widgetFile "homepage") | 
	periodic/Simple-Yesod-ToDo | 
	Handler/Root.hs | 
	bsd-2-clause | 625 | 0 | 12 | 123 | 63 | 34 | 29 | 9 | 1 | 
| 
	{--
Copyright (c) 2014-2020, Clockwork Dev Studio
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: 
1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer. 
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution. 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--}
{-# LANGUAGE CPP #-}
module Arguments where
import Prelude hiding (catch)
import LexerData
import Common
import Options
import Data.Char
import System.FilePath.Posix
import System.Directory
import System.IO
import Control.Exception
import System.Exit
import Control.Monad.State
import Control.Monad.Except
import Control.Monad.Identity
import Debug.Trace
import qualified Data.Sequence as Seq
data ConfigFile =
  ConfigFile
  {
    configFileVariableList :: [ConfigFileVariable]
  } deriving (Show,Eq)
data ConfigFileVariable =
  ConfigFileVariable
  {
    configFileVariableName :: String,
    configFileVariableValue :: String
  } deriving (Show, Eq)
loadConfigFile :: Handle -> ConfigFile -> IO ConfigFile
loadConfigFile handle (ConfigFile variables) =
  do let endOfFile :: IOError -> IO String
         endOfFile e = do return "EOF"
                          
     line <- catch (hGetLine handle) endOfFile
     
     if line == "EOF"
     then return (ConfigFile variables)
     else do let (variable,rest) = span (isAlpha) line
             if variable == [] || rest == [] || head rest /= '='
             then loadConfigFile handle (ConfigFile variables)
             else do loadConfigFile handle (ConfigFile (variables ++ [(ConfigFileVariable variable (tail rest))]))
adjustOptionsBasedOnConfigFile :: Options -> [ConfigFileVariable] -> Options
adjustOptionsBasedOnConfigFile originalOptions (configFileVariable:rest) =
  case configFileVariableName configFileVariable of
       "backend" -> adjustOptionsBasedOnConfigFile (originalOptions {optionAssembler = configFileVariableValue configFileVariable}) rest
       
adjustOptionsBasedOnConfigFile originalOptions _ = originalOptions
  
processArguments :: CodeTransformation ()
processArguments = 
  
  do homeDirectory <- liftIO $ getHomeDirectory
     let writeDefaultConfigFile :: IOError -> IO Handle
         writeDefaultConfigFile _ =
           do newConfHandle <- openFile (homeDirectory ++ "/.idlewild-lang.conf") WriteMode
              hPutStrLn newConfHandle "backend=nasm"
              hClose newConfHandle
              newConfHandle <- openFile (homeDirectory ++ "/.idlewild-lang.conf") ReadMode
              return newConfHandle
     
     confHandle <- liftIO $ (catch (openFile (homeDirectory ++ "/.idlewild-lang.conf") ReadMode) writeDefaultConfigFile)
     configFile <- liftIO $ loadConfigFile confHandle (ConfigFile [])
     let customisedOptions = adjustOptionsBasedOnConfigFile defaultOptions (configFileVariableList configFile)
     
     liftIO $ hClose confHandle
     
     arguments <- gets argumentStateArguments
     (options, nonOptions) <- liftIO $ processOptions customisedOptions arguments
     if optionShowVersion options == True
     then do liftIO $ putStrLn "Idlewild-Lang version 0.0.5."
             liftIO $ exitSuccess
     else return ()
     if length nonOptions /= 1
     then do liftIO $ putStrLn "Please specify one (and only one) source file name."
             liftIO $ exitSuccess
     else return ()
     let sourceFileName = head nonOptions
         asmFileName = replaceExtension sourceFileName ".asm"
#if LINUX==1 || MAC_OS==1
         objectFileName = replaceExtension sourceFileName ".o"
#elif WINDOWS==1
         objectFileName = replaceExtension sourceFileName ".obj"
#endif
         verbose = optionVerbose options
     
     fromHandle <- liftIO $ openFile sourceFileName ReadMode
     toHandle <- liftIO $ openFile asmFileName WriteMode
     code <- liftIO $  hGetContents fromHandle
     put LexState
         {lexStateID = LEX_PENDING,
          lexStateIncludeFileDepth = 0,
          lexStateIncludeFileNameStack = [sourceFileName],
          lexStateIncludeFileNames = [],
          lexStateCurrentToken = emptyToken,
          lexStatePendingTokens = Seq.empty,
          lexStateTokens = Seq.singleton (createBOFToken sourceFileName),
          lexStateLineNumber = 1,
          lexStateLineOffset = 0,
          lexStateCharacters = code,
          lexStateCompoundTokens = allCompoundTokens,
          lexStateConfig = Config {configInputFile = fromHandle,
                                   configOutputFile = toHandle,
                                   configSourceFileName = sourceFileName,
                                   configAsmFileName = asmFileName,
                                   configObjectFileName = objectFileName,
                                   configOptions = options}}
     verboseCommentary ("Program arguments okay...\n") verbose
     verboseCommentary ("Source file '" ++ sourceFileName ++ "'...\n") verbose
 | 
	clockworkdevstudio/Idlewild-Lang | 
	Arguments.hs | 
	bsd-2-clause | 5,916 | 0 | 22 | 1,368 | 1,000 | 518 | 482 | 92 | 3 | 
| 
	module Convert.LRChirotope where
-- standard modules
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as Set
-- local modules
import Basics
import Calculus.FlipFlop
import Helpful.General
--import Debug.Trace
{------------------------------------------------------------------------------
 - FlipFlop to Chirotope
------------------------------------------------------------------------------}
flipflopsToChirotope :: Network [String] (ARel FlipFlop)
                     -> Maybe (Network [Int] Int)
flipflopsToChirotope net
    | isNothing net5 || isNothing net3  = Nothing
    | otherwise  = Just $ (fromJust net3)
        { nCons = fst $ Map.foldlWithKey
                                collectOneCon
                                (Map.empty, Map.empty)
                                cons
        }
    where
        collectOneCon (consAcc, mapAcc) nodes rel =
            let
                (newMap, convertedNodes) = mapAccumL
                    (\ m node -> let mappedNode = Map.lookup node m in
                        case mappedNode of
                            Nothing   -> let n = (Map.size m) + 1 in
                                         (Map.insert node n m, n)
                            otherwise -> (m, fromJust mappedNode)
                    )
                    mapAcc
                    nodes
                newRel = case aRel rel of
                    R -> (-1)
                    I -> 0
                    L -> 1
            in
            ( foldl (flip $ uncurry Map.insert) consAcc $
                [(x, newRel * y)
                | (x,y) <- kPermutationsWithParity 3 convertedNodes
                ]
            , newMap
            )
        net5 = ffsToFF5s net
        net3 = ff5sToFF3s $ fromJust net5
        cons = nCons $ fromJust net3
 | 
	spatial-reasoning/zeno | 
	src/Convert/LRChirotope.hs | 
	bsd-2-clause | 1,839 | 0 | 26 | 767 | 422 | 224 | 198 | 38 | 4 | 
| 
	{-# LANGUAGE FlexibleContexts #-}
module BRC.Solver.Error where
import Control.Monad.Error (Error(..), MonadError(..))
-- | Solver errors, really just a container for a possibly useful error message.
data SolverError = SolverError String deriving (Eq, Ord)
instance Show (SolverError) where
  show (SolverError msg) = "Solver error: " ++ msg
  
instance Error SolverError where
  strMsg = SolverError
  
-- | Throws an error with a given message in a solver error monad.
solverError :: MonadError SolverError m => String -> m a
solverError = throwError . strMsg | 
	kcharter/brc-solver | 
	BRC/Solver/Error.hs | 
	bsd-2-clause | 565 | 0 | 8 | 95 | 124 | 71 | 53 | 10 | 1 | 
| 
	{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module NW.Monster where
import NW.Stats
data MonsterClass
	= MCFighter
	| MCMage
	deriving (Eq, Show)
data Monster = Monster
	{ mClass :: MonsterClass
	, mName :: String
	, mStatsBase :: [Stat]
	, mLootBonus :: Int
	} deriving (Eq, Show)
type MonsterDB = [Monster]
 | 
	listx/netherworld | 
	src/NW/Monster.hs | 
	bsd-2-clause | 338 | 8 | 9 | 63 | 98 | 60 | 38 | 15 | 0 | 
| 
	{-# LANGUAGE TemplateHaskell #-}
{-| Contains TemplateHaskell stuff I don't want to recompile every time I make
    changes to other files, a pre-compiled header, so to say. Don't know if that
    even works.
-}
module FeedGipeda.THGenerated
  ( benchmarkClosure
  , stringDict
  , __remoteTable
  ) where
import           Control.Distributed.Process         (Closure, Process, Static,
                                                      liftIO)
import           Control.Distributed.Process.Closure (SerializableDict,
                                                      functionTDict, mkClosure,
                                                      remotable)
import           FeedGipeda.GitShell                 (SHA)
import           FeedGipeda.Repo                     (Repo)
import qualified FeedGipeda.Slave                    as Slave
import           FeedGipeda.Types                    (Timeout)
benchmarkProcess :: (String, Repo, SHA, Rational) -> Process String
benchmarkProcess (benchmarkScript, repo, sha, timeout) =
  liftIO (Slave.benchmark benchmarkScript repo sha (fromRational timeout))
remotable ['benchmarkProcess]
benchmarkClosure :: String -> Repo -> SHA -> Timeout -> Closure (Process String)
benchmarkClosure benchmarkScript repo commit timeout =
  $(mkClosure 'benchmarkProcess) (benchmarkScript, repo, commit, toRational timeout)
stringDict :: Static (SerializableDict String)
stringDict =
  $(functionTDict 'benchmarkProcess)
 | 
	sgraf812/feed-gipeda | 
	src/FeedGipeda/THGenerated.hs | 
	bsd-3-clause | 1,466 | 0 | 11 | 454 | 272 | 156 | 116 | 24 | 1 | 
| 
	{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Test.PGConstant (
    TestPGConstant(..)
  , spec
  ) where
import Data.Proxy (Proxy(..))
import Database.PostgreSQL.Simple.Bind.Parser
import Test.Hspec (Spec, describe)
import Test.QuickCheck (Arbitrary(..), oneof)
import Test.Common (PGSql(..))
import Test.Utils (propParsingWorks)
import Test.PGString (TestPGString(..))
data TestPGConstant
  = TPGCString TestPGString
  | TPGCNumeric Double
  deriving (Show, Eq)
instance Arbitrary TestPGConstant where
  arbitrary = oneof [
      TPGCString <$> arbitrary
    , TPGCNumeric <$> arbitrary]
instance PGSql TestPGConstant where
  render (TPGCString s) = render s
  render (TPGCNumeric c) = show c
spec :: Spec
spec = do
  describe "pgConstant" $ do
    propParsingWorks pgConstant (Proxy :: Proxy TestPGConstant)
 | 
	zohl/postgresql-simple-bind | 
	tests/Test/PGConstant.hs | 
	bsd-3-clause | 1,133 | 0 | 12 | 177 | 253 | 149 | 104 | 36 | 1 | 
| 
	{-# LANGUAGE OverloadedStrings #-}
module WildBind.SeqSpec (main,spec) where
import Control.Applicative ((<*>))
import Control.Monad (forM_)
import Control.Monad.IO.Class (liftIO)
import qualified Control.Monad.Trans.State as State
import Data.Monoid ((<>))
import Data.IORef (modifyIORef, newIORef, readIORef)
import Test.Hspec
import WildBind.Binding
  ( binds, on, run, as,
    boundActions, actDescription,
    boundInputs,
    Binding,
    justBefore
  )
import WildBind.Description (ActionDescription)
import WildBind.Seq
  ( prefix,
    toSeq, fromSeq,
    withPrefix, withCancel,
    reviseSeq
  )
import WildBind.ForTest
  ( SampleInput(..), SampleState(..),
    evalStateEmpty, execAll,
    boundDescs, curBoundInputs, curBoundDescs, curBoundDesc,
    checkBoundInputs,
    checkBoundDescs,
    checkBoundDesc,
    withRefChecker
  )
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
  spec_prefix
  spec_SeqBinding
  spec_reviseSeq
spec_prefix :: Spec
spec_prefix = describe "prefix" $ do
  let base_b = binds $ do
        on SIa `as` "a" `run` return ()
        on SIb `as` "b" `run` return ()
  specify "no prefix" $ do
    let b = prefix [] [] base_b
    boundDescs b (SS "") `shouldMatchList`
      [ (SIa, "a"),
        (SIb, "b")
      ]
  specify "one prefix" $ evalStateEmpty $ do
    State.put $ prefix [] [SIc] base_b
    checkBoundInputs (SS "") [SIc]
    execAll (SS "") [SIc] 
    checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
    execAll (SS "") [SIc]
    checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
    execAll (SS "") [SIa]
    checkBoundInputs (SS "") [SIc]
  specify "two prefixes" $ evalStateEmpty $ do
    State.put $ prefix [] [SIc, SIb] base_b
    checkBoundInputs (SS "") [SIc]
    execAll (SS "") [SIc]
    checkBoundInputs (SS "") [SIb]
    execAll (SS "") [SIb]
    checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
    execAll (SS "") [SIa]
    checkBoundInputs (SS "") [SIc]
  specify "cancel binding" $ evalStateEmpty $ do
    State.put $ prefix [SIa] [SIc, SIb] base_b
    checkBoundInputs (SS "") [SIc]
    execAll (SS "") [SIc] -- there is no cancel binding at the top level.
    checkBoundInputs (SS "") [SIa, SIb]
    checkBoundDesc (SS "") SIa "cancel"
    execAll (SS "") [SIa]
    checkBoundInputs (SS "") [SIc]
    execAll (SS "") [SIc, SIb]
    checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]  -- cancel binding should be weak and overridden.
    execAll (SS "") [SIb]
    checkBoundInputs (SS "") [SIc]
    execAll (SS "") [SIc, SIb]
    checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
    execAll (SS "") [SIa]
    checkBoundInputs (SS "") [SIc]
spec_SeqBinding :: Spec
spec_SeqBinding = describe "SeqBinding" $ do
  let b_a = binds $ on SIa `as` "a" `run` return ()
      b_b = binds $ on SIb `as` "b" `run` return ()
  describe "withPrefix" $ do
    it "should allow nesting" $ evalStateEmpty $ do
      State.put $ fromSeq $ withPrefix [SIb] $ withPrefix [SIc] $ withPrefix [SIa] $ toSeq (b_a <> b_b)
      checkBoundInputs (SS "") [SIb]
      execAll (SS "") [SIb]
      checkBoundInputs (SS "") [SIc]
      execAll (SS "") [SIc]
      checkBoundInputs (SS "") [SIa]
      execAll (SS "") [SIa]
      checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")]
      execAll (SS "") [SIa]
      checkBoundInputs (SS "") [SIb]
  describe "mappend" $ do
    it "should be able to combine SeqBindings with different prefixes." $ evalStateEmpty $ do
      State.put $ fromSeq $ withPrefix [SIc] $ ( (withPrefix [SIa, SIc] $ toSeq $ b_a)
                                                 <> (withPrefix [SIa] $ toSeq $ b_b)
                                               )
      checkBoundInputs (SS "") [SIc]
      execAll (SS "") [SIc]
      checkBoundInputs (SS "") [SIa]
      execAll (SS "") [SIa]
      checkBoundInputs (SS "") [SIc, SIb]
      checkBoundDesc (SS "") SIb "b"
      execAll (SS "") [SIb]
      checkBoundInputs (SS "") [SIc]
      execAll (SS "") [SIc, SIa]
      checkBoundInputs (SS "") [SIc, SIb]
      execAll (SS "") [SIc]
      checkBoundDescs (SS "") [(SIa, "a")]
      execAll (SS "") [SIa]
      checkBoundInputs (SS "") [SIc]
  describe "withCancel" $ do
    it "should weakly add 'cancel' binding when at least one prefix is kept in the state." $ evalStateEmpty $ do
      State.put $ fromSeq $ withPrefix [SIa, SIc] $ withCancel [SIa, SIb, SIc] $ ( toSeq b_a
                                                                                   <> (withPrefix [SIc] $ toSeq b_b)
                                                                                 )
      let checkPrefixOne = do
            checkBoundInputs (SS "") [SIa]
            execAll (SS "") [SIa]
            checkBoundInputs (SS "") [SIa, SIb, SIc]
            forM_ [SIa, SIb] $ \c -> checkBoundDesc (SS "") c "cancel"
      checkPrefixOne
      execAll (SS "") [SIa]
      checkPrefixOne
      execAll (SS "") [SIc]
      checkBoundInputs (SS "") [SIa, SIb, SIc]
      checkBoundDesc (SS "") SIa "a"
      checkBoundDesc (SS "") SIb "cancel"
      execAll (SS "") [SIa]
      checkPrefixOne
      execAll (SS "") [SIc, SIb]
      checkPrefixOne
      execAll (SS "") [SIc, SIc]
      checkBoundDescs (SS "") [(SIa, "cancel"), (SIb, "b"), (SIc, "cancel")]
      execAll (SS "") [SIb]
      checkPrefixOne
      
spec_reviseSeq :: Spec
spec_reviseSeq = describe "reviseSeq" $ do
  it "should allow access to prefix keys input so far" $ evalStateEmpty $ withRefChecker [] $ \out checkOut -> do
    act_out <- liftIO $ newIORef ("" :: String)
    let sb = withCancel [SIa] $ withPrefix [SIa, SIb, SIc] $ toSeq $ base_b
        base_b = binds $ on SIb `as` "B" `run` modifyIORef act_out (++ "B executed")
        rev ps _ _ = justBefore $ modifyIORef out (++ [ps])
    State.put $ fromSeq $ reviseSeq rev sb
    execAll (SS "") [SIa, SIa]
    checkOut [[], [SIa]]
    execAll (SS "") [SIa, SIb, SIc]
    checkOut [[], [SIa], [], [SIa], [SIa, SIb]]
    liftIO $ readIORef act_out `shouldReturn` ""
    execAll (SS "") [SIb]
    checkOut [[], [SIa], [], [SIa], [SIa, SIb], [SIa, SIb, SIc]]
    liftIO $ readIORef act_out `shouldReturn` "B executed"
  it "should allow unbinding" $ evalStateEmpty $ do
    let sb = withPrefix [SIa]
             ( toSeq ba
               <> (withPrefix [SIb] $ toSeq bab)
               <> (withPrefix [SIa] $ toSeq baa)
             )
        ba  = binds $ on SIc `as` "c on a" `run` return ()
        bab = binds $ on SIc `as` "c on ab" `run` return ()
        baa = binds $ do
          on SIc `as` "c on aa" `run` return ()
          on SIb `as` "b on aa" `run` return ()
        rev ps _ i act = if (ps == [SIa] && i == SIb) || (ps == [SIa,SIa] && i == SIc)
                         then Nothing
                         else Just act
    State.put $ fromSeq $ reviseSeq rev sb
    checkBoundInputs (SS "") [SIa]
    execAll (SS "") [SIa]
    checkBoundInputs (SS "") [SIa, SIc] -- SIb should be canceled
    execAll (SS "") [SIa]
    checkBoundDescs (SS "") [(SIb, "b on aa")] -- SIc should be canceled
    execAll (SS "") [SIb]
    checkBoundInputs (SS "") [SIa]
    
    
 | 
	debug-ito/wild-bind | 
	wild-bind/test/WildBind/SeqSpec.hs | 
	bsd-3-clause | 7,072 | 0 | 23 | 2,072 | 2,930 | 1,501 | 1,429 | 175 | 2 | 
| 
	{-# LANGUAGE TemplateHaskell #-}
module Data.Comp.Trans.DeriveUntrans (
    deriveUntrans
  ) where
import Control.Lens ( view ,(^.))
import Control.Monad ( liftM )
import Control.Monad.Trans ( lift )
import Data.Comp.Multi ( Alg, cata, (:&:)(..) )
import Language.Haskell.TH
import Data.Comp.Trans.Util
--------------------------------------------------------------------------------
-- |
-- Creates an @untranslate@ function inverting the @translate@ function
-- created by @deriveTrans@.
-- 
-- @
-- import qualified Foo as F
-- type ArithTerm = Term (Arith :+: Atom :+: Lit)
-- deriveUntrans [''F.Arith, ''F.Atom, ''F.Lit] (TH.ConT ''ArithTerm)
-- @
-- 
-- will create
-- 
-- @
-- type family Targ l
-- newtype T l = T {t :: Targ l}
-- 
-- class Untrans f where
--   untrans :: Alg f t
-- 
-- untranslate :: ArithTerm l -> Targ l
-- untranslate = t . cata untrans
-- 
-- type instance Targ ArithL = F.Arith
-- instance Untrans Arith where
--   untrans (Add x y) = T $ F.Add (t x) (t y)
-- 
-- type instance Targ AtomL = F.Atom
-- instance Untrans Atom where
--   untrans (Var s)   = T $ F.Var s
--   untrans (Const x) = T $ F.Const (t x)
-- 
-- type instance Targ LitL = F.Lit
-- instance Untrans Lit where
--   untrans (Lit n) = T $ F.Lit n
-- @
-- 
-- Note that you will need to manually provide an instance @(Untrans f, Untrans g) => Untrans (f :+: g)@
-- due to phase issues. (Or @(Untrans (f :&: p), Untrans (g :&: p)) => Untrans ((f :+: g) :&: p)@, if you
-- are propagating annotations.)
--
-- With annotation propagation on, it will instead produce
-- `untranslate :: Term (Arith :&: Ann) l -> Targ l Ann`
deriveUntrans :: [Name] -> Type -> CompTrans [Dec]
deriveUntrans names term = do targDec <- mkTarg targNm
                              wrapperDec <- mkWrapper wrapNm unwrapNm targNm
                              fnDec <- mkFn untranslateNm term targNm unwrapNm fnNm
                              classDec <- mkClass classNm fnNm wrapNm
                              instances <- liftM concat $ mapM (mkInstance classNm fnNm wrapNm unwrapNm targNm) names
                              return $ concat [ targDec
                                              , wrapperDec
                                              , fnDec
                                              , classDec
                                              , instances
                                              ]
  where
    targNm = mkName "Targ"
    wrapNm = mkName "T"
    unwrapNm = mkName "t"
    untranslateNm = mkName "untranslate"
    classNm = mkName "Untrans"
    fnNm = mkName "untrans"
{- type family Targ l -}
mkTarg :: Name -> CompTrans [Dec]
mkTarg targNm = do i <- lift $ newName "i"
                   return [FamilyD TypeFam targNm [PlainTV i] Nothing]
{- newtype T l = T { t :: Targ l } -}
mkWrapper :: Name -> Name -> Name -> CompTrans [Dec]
mkWrapper tpNm fNm targNm = do i <- lift $ newName "i"
                               let con = RecC tpNm [(fNm, NotStrict, AppT (ConT targNm) (VarT i))]
                               return [NewtypeD [] tpNm [PlainTV i] con []]
{-
  untranslate :: JavaTerm l -> Targ l
  untranslate = t . cata untrans
-}
mkFn :: Name -> Type -> Name -> Name -> Name -> CompTrans [Dec]
mkFn fnNm term targNm fldNm untransNm = sequence [sig, def]
  where
    sig = do i <- lift $ newName "i"
             lift $ sigD fnNm (forallT [PlainTV i] (return []) (typ $ varT i))
    typ :: Q Type -> Q Type
    typ i = [t| $term' $i -> $targ $i |]
    term' = return term
    targ = conT targNm
    def = lift $ valD (varP fnNm) (normalB body) []
    body = [| $fld . cata $untrans |]
    fld = varE fldNm
    untrans = varE untransNm
{-
  class Untrans f where
    untrans :: Alg f T
-}
mkClass :: Name -> Name -> Name -> CompTrans [Dec]
mkClass classNm funNm newtpNm = do f <- lift $ newName "f"
                                   let funDec = SigD funNm (AppT (AppT (ConT ''Alg) (VarT f)) (ConT newtpNm))
                                   return [ClassD [] classNm [PlainTV f] [] [funDec]]
                      
{-
  type instance Targ CompilationUnitL = J.CompilationUnit
  instance Untrans CompilationUnit where
    untrans (CompilationUnit x y z) = T $ J.CompilationUnit (t x) (t y) (t z)
-}
mkInstance :: Name -> Name -> Name -> Name -> Name -> Name -> CompTrans [Dec]
mkInstance classNm funNm wrap unwrap targNm typNm = do inf <- lift $ reify typNm
                                                       targTyp <- getFullyAppliedType typNm
                                                       let nmTyps = simplifyDataInf inf
                                                       clauses <- mapM (uncurry $ mkClause wrap unwrap) nmTyps
                                                       let conTyp = ConT (transName typNm)
                                                       annPropInf <- view annotationProp
                                                       let instTyp = case annPropInf of
                                                                       Nothing  -> conTyp
                                                                       Just api -> foldl AppT (ConT ''(:&:)) [conTyp, api ^. annTyp]
                                                       return [ famInst targTyp
                                                              , inst clauses instTyp
                                                              ]
  where
    famInst targTyp = TySynInstD targNm (TySynEqn [ConT $ nameLab typNm] targTyp)
    inst clauses instTyp =  InstanceD []
                                      (AppT (ConT classNm) instTyp)
                                      [FunD funNm clauses]
mapConditionallyReplacing :: [a] -> (a -> b) -> (a -> Bool) -> [b] -> [b]
mapConditionallyReplacing src f p reps = go src reps
  where
    go [] _                      = []
    go (x:xs) (y:ys) | p x       = y   : go xs ys
    go (x:xs) l      | not (p x) = f x : go xs l
    go (_:_ ) []                 = error "mapConditionallyReplacing: Insufficiently many replacements"
mkClause :: Name -> Name -> Name -> [Type] -> CompTrans Clause
mkClause wrap unwrap con tps = do isAnn <- getIsAnn
                                  nms <- mapM (const $ lift $ newName "x") tps
                                  nmAnn <- lift $ newName "a"
                                  tps' <- applyCurSubstitutions tps
                                  let nmTps = zip nms tps'
                                  Clause <$> (sequence [pat isAnn nmTps nmAnn]) <*> (body nmTps nmAnn) <*> pure []
  where
    pat :: (Type -> Bool) -> [(Name, Type)] -> Name -> CompTrans Pat
    pat isAnn nmTps nmAnn = do isProp <- isPropagatingAnns
                               if isProp then
                                 return $ ConP '(:&:) [nodeP, VarP nmAnn]
                                else
                                 return nodeP
      where
        nonAnnNms = map fst $ filter (not.isAnn.snd) nmTps
        nodeP = ConP (transName con) (map VarP nonAnnNms)
    body :: [(Name, Type)] -> Name -> CompTrans Body
    body nmTps nmAnn = do annPropInf <- view annotationProp
                          args <- case annPropInf of
                                    Nothing  -> return $ map atom nmTps
                                    Just api -> do isAnn <- getIsAnn
                                                   let unProp = api ^. unpropAnn
                                                   let annVars = filter (isAnn.snd) nmTps
                                                   let annExps = unProp (VarE nmAnn) (length annVars)
                                                   return $ mapConditionallyReplacing nmTps atom (isAnn.snd) annExps
                          return $ makeRhs args
      where
        makeRhs :: [Exp] -> Body
        makeRhs args = NormalB $ AppE (ConE wrap) $ foldl AppE (ConE con) args
    atom :: (Name, Type) -> Exp
    atom (x, t) | elem t baseTypes = VarE x
    atom (x, _)                    = AppE (VarE unwrap) (VarE x)
 | 
	jkoppel/comptrans | 
	Data/Comp/Trans/DeriveUntrans.hs | 
	bsd-3-clause | 8,030 | 0 | 20 | 3,281 | 1,942 | 992 | 950 | 100 | 4 | 
| 
	module Mistral.Schedule.Value (
    Env
  , groupEnv
  , lookupEnv
  , bindType
  , bindValue
  , bindParam
  , NodeTags
  , bindNode
  , lookupTag, lookupTags
  , Value(..)
  , SNetwork(..), mapWhen, modifyNode
  , SNode(..), addTask
  , STask(..), hasConstraints
  , SConstraint(..), target
  ) where
import Mistral.TypeCheck.AST
import Mistral.Utils.PP
import Mistral.Utils.Panic ( panic )
import Mistral.Utils.SCC ( Group )
import qualified Data.Foldable as Fold
import qualified Data.Map as Map
import           Data.Monoid ( Monoid(..) )
import qualified Data.Set as Set
sPanic :: [String] -> a
sPanic  = panic "Mistral.Schedule.Value"
-- Environments ----------------------------------------------------------------
data Env = Env { envValues :: Map.Map Name Value
               , envTypes  :: Map.Map TParam Type
               }
instance Monoid Env where
  mempty       = Env { envValues = mempty, envTypes = mempty }
  mappend l r  = mconcat [l,r]
  -- merge the two environments, preferring things from the left
  mconcat envs = Env { envValues = Map.unions (map envValues envs)
                     , envTypes  = Map.unions (map envTypes  envs) }
lookupEnv :: Name -> Env -> Value
lookupEnv n env =
  case Map.lookup n (envValues env) of
    Just v  -> v
    Nothing -> sPanic [ "no value for: " ++ pretty n ]
bindType :: TParam -> Type -> Env -> Env
bindType p ty env = env { envTypes = Map.insert p ty (envTypes env) }
bindValue :: Name -> Value -> Env -> Env
bindValue n v env = env { envValues = Map.insert n v (envValues env) }
bindParam :: Param -> Value -> Env -> Env
bindParam p v env = bindValue (pName p) v env
groupEnv :: (a -> Env) -> (Group a -> Env)
groupEnv  = Fold.foldMap
-- Node Tags -------------------------------------------------------------------
newtype NodeTags = NodeTags { getNodeTags :: Map.Map Atom (Set.Set Name) }
instance Monoid NodeTags where
  mempty      = NodeTags mempty
  mappend l r = mconcat [l,r]
  mconcat nts = NodeTags (Map.unionsWith Set.union (map getNodeTags nts))
bindNode :: SNode -> NodeTags
bindNode sn = mempty { getNodeTags = foldl add mempty allTags }
  where
  name               = snName sn
  allTags            = [ (tag, Set.singleton name) | tag <- snTags sn ]
  add nodes (tag, s) = Map.insertWith Set.union tag s nodes
-- | Try to resolve a single tag to set of Node names.
lookupTag :: Atom -> NodeTags -> Set.Set Name
lookupTag tag env = case Map.lookup tag (getNodeTags env) of
  Just nodes -> nodes
  Nothing    -> Set.empty
-- | Lookup the nodes that have all of the tags given.
lookupTags :: [Atom] -> NodeTags -> [Name]
lookupTags tags env
  | null tags = [] -- XXX maybe all nodes?
  | otherwise = Set.toList (foldl1 Set.intersection (map (`lookupTag` env) tags))
-- Values ----------------------------------------------------------------------
data Value = VTFun (Type -> Value)
             -- ^ Type abstractions
           | VFun (Value -> Value)
             -- ^ Value abstractions
           | VCon Name [Value]
             -- ^ Constructor use
           | VLit Literal
             -- ^ Literals
           | VSched [SNetwork]
             -- ^ Evaluted schedules
           | VTopo SNetwork
             -- ^ Nodes and links
           | VNode SNode
             -- ^ Nodes
           | VLink Link
             -- ^ Links
           | VTasks (NodeTags -> [STask])
           | VTask STask
instance Show Value where
  show val = case val of
    VTFun _     -> "<function>"
    VFun _      -> "<type-function>"
    VCon n vs   -> "(" ++ unwords (pretty n : map show vs) ++ ")"
    VLit lit    -> "(VLit " ++ show lit ++ ")"
    VSched nets -> show nets
    VTopo net   -> show net
    VNode n     -> show n
    VLink l     -> show l
    VTasks _    -> "<tasks>"
    VTask t     -> show t
-- | Scheduling network.
data SNetwork = SNetwork { snNodes :: [SNode]
                         , snLinks :: [Link]
                         } deriving (Show)
instance Monoid SNetwork where
  mempty      = SNetwork { snNodes = []
                         , snLinks = [] }
  mappend l r = SNetwork { snNodes = Fold.foldMap snNodes [l,r]
                         , snLinks = Fold.foldMap snLinks [l,r] }
mapWhen :: (a -> Bool) -> (a -> a) -> [a] -> [a]
mapWhen p f = go
  where
  go as = case as of
    a:rest | p a       -> f a :    rest
           | otherwise ->   a : go rest
    []                 -> []
-- | Modify the first occurrence of node n.
--
-- INVARIANT: This relies on the assumption that the renamer has given fresh
-- names to all nodes.
modifyNode :: Name -> (SNode -> SNode) -> (SNetwork -> SNetwork)
modifyNode n f net = net { snNodes = mapWhen nameMatches f (snNodes net) }
  where
  nameMatches sn = snName sn == n
data SNode = SNode { snName  :: Name
                   , snSpec  :: Expr
                   , snType  :: Type
                   , snTags  :: [Atom]
                   , snTasks :: [STask]
                   } deriving (Show)
addTask :: STask -> (SNode -> SNode)
addTask task sn = sn { snTasks = task : snTasks sn }
data STask = STask { stName        :: Name
                   , stTask        :: Task
                   , stTags        :: [Atom]
                   , stConstraints :: [SConstraint]
                   } deriving (Show)
hasConstraints :: STask -> Bool
hasConstraints t = not (null (stConstraints t))
data SConstraint = SCOn Name -- ^ On this node
                   deriving (Show)
-- XXX This won't work for constraints that specify relative information like:
-- "I need to be able to communicate with X"
target :: SConstraint -> Name
target (SCOn n) = n
 | 
	GaloisInc/mistral | 
	src/Mistral/Schedule/Value.hs | 
	bsd-3-clause | 5,624 | 0 | 14 | 1,727 | 1,680 | 920 | 760 | 121 | 2 | 
| 
	{-# LANGUAGE ParallelListComp #-}
module OldHMM
    (Prob, HMM(..), train, bestSequence, sequenceProb)
    where
import qualified Data.Map as M
import Data.List (sort, groupBy, maximumBy, foldl')
import Data.Maybe (fromMaybe, fromJust)
import Data.Ord (comparing)
import Data.Function (on)
import Control.Monad
import Data.Number.LogFloat
type Prob = LogFloat
-- | The type of Hidden Markov Models.
data HMM state observation = HMM [state] [Prob] [[Prob]] (observation -> [Prob])
instance (Show state, Show observation) => Show (HMM state observation) where
    show (HMM states probs tpm _) = "HMM " ++ show states ++ " "
                                           ++ show probs ++ " " ++ show tpm ++ " <func>"
-- | Perform a single step in the Viterbi algorithm.
--  
--   Takes a list of path probabilities, and an observation, and returns the updated
--   list of (surviving) paths with probabilities.
viterbi ::     HMM state observation
            -> [(Prob, [state])]
            -> observation
            -> [(Prob, [state])]
viterbi (HMM states _ state_transitions observations) prev x =
    deepSeq prev `seq`
    [maximumBy (comparing fst)
            [(transition_prob * prev_prob * observation_prob,
               new_state:path)
                    | transition_prob <- transition_probs
                    | (prev_prob, path) <- prev
                    | observation_prob <- observation_probs]
        | transition_probs <- state_transitions
        | new_state <- states]
    where
        observation_probs = observations x
        deepSeq ((x, y:ys):xs) = x `seq` y `seq` (deepSeq xs)
        deepSeq ((x, _):xs) = x `seq` (deepSeq xs)
        deepSeq [] = []
-- | The initial value for the Viterbi algorithm
viterbi_init :: HMM state observation -> [(Prob, [state])]
viterbi_init (HMM states state_probs _ _) = zip state_probs (map (:[]) states)
-- | Perform a single step of the forward algorithm
-- 
--   Each item in the input and output list is the probability that the system
--   ended in the respective state.
forward ::     HMM state observation
            -> [Prob]
            -> observation
            -> [Prob]
forward (HMM _ _ state_transitions observations) prev x =
    last prev `seq`
    [sum [transition_prob * prev_prob * observation_prob
                | transition_prob <- transition_probs
                | prev_prob <- prev
                | observation_prob <- observation_probs]
        | transition_probs <- state_transitions]
    where
        observation_probs = observations x
-- | The initial value for the forward algorithm
forward_init :: HMM state observation -> [Prob]
forward_init (HMM _ state_probs _ _) = state_probs
learn_states :: (Ord state, Fractional prob) => [(observation, state)] -> M.Map state prob
learn_states xs = histogram $ map snd xs
learn_transitions :: (Ord state, Fractional prob) => [(observation, state)] -> M.Map (state, state) prob
learn_transitions xs = let xs' = map snd xs in
                        histogram $ zip xs' (tail xs')
learn_observations ::  (Ord state, Ord observation, Fractional prob) =>
                       M.Map state prob
                    -> [(observation, state)]
                    -> M.Map (observation, state) prob
learn_observations state_prob = M.mapWithKey (\ (observation, state) prob -> prob / (fromJust $ M.lookup state state_prob))
                            . histogram
histogram :: (Ord a, Fractional prob) => [a] -> M.Map a prob
histogram xs = let hist = foldl' (flip $ flip (M.insertWith (+)) 1) M.empty xs in
                M.map (/ M.fold (+) 0 hist) hist
-- | Calculate the parameters of an HMM from a list of observations
--   and the corresponding states.
train :: (Ord observation, Ord state) =>
            [(observation, state)]
         -> HMM state observation
train sample = model
    where
        states = learn_states sample
        state_list = M.keys states
        
        transitions = learn_transitions sample
        trans_prob_mtx = [[fromMaybe 1e-10 $ M.lookup (old_state, new_state) transitions
                                | old_state <- state_list]
                                | new_state <- state_list]
        observations = learn_observations states sample
        observation_probs = fromMaybe (fill state_list []) . (flip M.lookup $
                            M.fromList $ map (\ (e, xs) -> (e, fill state_list xs)) $
                                map (\ xs -> (fst $ head xs, map snd xs)) $
                                groupBy     ((==) `on` fst)
                                            [(observation, (state, prob))
                                                | ((observation, state), prob) <- M.toAscList observations])
        initial = map (\ state -> (fromJust $ M.lookup state states, [state])) state_list
        model = HMM state_list (fill state_list $ M.toAscList states) trans_prob_mtx observation_probs
        fill :: Eq state => [state] -> [(state, Prob)] -> [Prob]
        fill states [] = map (const 1e-10) states
        fill (s:states) xs@((s', p):xs') = if s /= s' then
                                            1e-10 : fill states xs
                                           else
                                            p : fill states xs'
-- | Calculate the most likely sequence of states for a given sequence of observations
--   using Viterbi's algorithm
bestSequence :: (Ord observation) => HMM state observation -> [observation] -> [state]
bestSequence hmm = (reverse . tail . snd . (maximumBy (comparing fst))) . (foldl' (viterbi hmm) (viterbi_init hmm))
-- | Calculate the probability of a given sequence of observations
--    using the forward algorithm.
sequenceProb :: (Ord observation) => HMM state observation -> [observation] -> Prob
sequenceProb hmm = sum . (foldl' (forward hmm) (forward_init hmm)) | 
	mikeizbicki/hmm | 
	OldHMM.hs | 
	bsd-3-clause | 5,845 | 8 | 16 | 1,773 | 1,640 | 907 | 733 | 91 | 3 | 
| 
	{-# LANGUAGE DataKinds              #-}
{-# LANGUAGE FlexibleContexts       #-}
{-# LANGUAGE FlexibleInstances      #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses  #-}
{-# LANGUAGE OverloadedStrings      #-}
{-# LANGUAGE ScopedTypeVariables    #-}
{-# LANGUAGE TupleSections          #-}
{-# LANGUAGE TypeFamilies           #-}
{-# LANGUAGE TypeSynonymInstances   #-}
module Test.Hspec.Snap (
  -- * Running blocks of hspec-snap tests
    snap
  , modifySite
  , modifySite'
  , afterEval
  , beforeEval
  -- * Core data types
  , TestResponse(..)
  , SnapHspecM
  -- * Factory style test data generation
  , Factory(..)
  -- * Requests
  , delete
  , get
  , get'
  , post
  , postJson
  , put
  , put'
  , params
  -- * Helpers for dealing with TestResponses
  , restrictResponse
  -- * Dealing with session state (EXPERIMENTAL)
  , recordSession
  , HasSession(..)
  , sessionShouldContain
  , sessionShouldNotContain
  -- * Evaluating application code
  , eval
  -- * Unit test assertions
  , shouldChange
  , shouldEqual
  , shouldNotEqual
  , shouldBeTrue
  , shouldNotBeTrue
  -- * Response assertions
  , should200
  , shouldNot200
  , should404
  , shouldNot404
  , should300
  , shouldNot300
  , should300To
  , shouldNot300To
  , shouldHaveSelector
  , shouldNotHaveSelector
  , shouldHaveText
  , shouldNotHaveText
  -- * Form tests
  , FormExpectations(..)
  , form
  -- * Internal types and helpers
  , SnapHspecState(..)
  , setResult
  , runRequest
  , runHandlerSafe
  , evalHandlerSafe
  ) where
import           Control.Applicative     ((<$>))
import           Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar
                                         ,putMVar, readMVar, takeMVar)
import           Control.Exception       (SomeException, catch)
import           Control.Monad           (void)
import           Control.Monad.State     (StateT (..), runStateT)
import qualified Control.Monad.State     as S (get, put)
import           Control.Monad.Trans     (liftIO)
import           Data.Aeson              (encode, ToJSON)
import           Data.ByteString         (ByteString)
import qualified Data.ByteString.Lazy    as LBS (ByteString)
import           Data.ByteString.Lazy    (fromStrict, toStrict)
import qualified Data.Map                as M
import           Data.Maybe              (fromMaybe)
import           Data.Text               (Text)
import qualified Data.Text               as T
import qualified Data.Text.Encoding      as T
import           Snap.Core               (Response (..), getHeader)
import qualified Snap.Core               as Snap
import           Snap.Snaplet            (Handler, Snaplet, SnapletInit,
                                          SnapletLens, with)
import           Snap.Snaplet.Session    (SessionManager, commitSession,
                                          sessionToList, setInSession)
import           Snap.Snaplet.Test       (InitializerState, closeSnaplet,
                                          evalHandler', getSnaplet, runHandler')
import           Snap.Test               (RequestBuilder, getResponseBody)
import qualified Snap.Test               as Test
import           Test.Hspec
import           Test.Hspec.Core.Spec
import qualified Text.Digestive          as DF
import qualified Text.HandsomeSoup       as HS
import qualified Text.XML.HXT.Core       as HXT
-- | The result of making requests against your application. Most
-- assertions act against these types (for example, `should200`,
-- `shouldHaveSelector`, etc).
data TestResponse = Html Text
                  | Json LBS.ByteString
                  | NotFound
                  | Redirect Int Text
                  | Other Int
                  | Empty
                  deriving (Show, Eq)
-- | The main monad that tests run inside of. This allows both access
-- to the application (via requests and `eval`) and to running
-- assertions (like `should404` or `shouldHaveText`).
type SnapHspecM b = StateT (SnapHspecState b) IO
-- | Internal state used to share site initialization across tests, and to propogate failures.
-- Understanding it is completely unnecessary to use the library.
--
-- The fields it contains, in order, are:
--
-- > Result
-- > Main handler
-- > Startup state
-- > Startup state
-- > Session state
-- > Before handler (runs before each eval)
-- > After handler (runs after each eval).
data SnapHspecState b = SnapHspecState Result
                                       (Handler b b ())
                                       (Snaplet b)
                                       (InitializerState b)
                                       (MVar [(Text, Text)])
                                       (Handler b b ())
                                       (Handler b b ())
instance Example (SnapHspecM b ()) where
  type Arg (SnapHspecM b ()) = SnapHspecState b
  evaluateExample s _ cb _ =
    do mv <- newEmptyMVar
       cb $ \st -> do ((),SnapHspecState r' _ _ _ _ _ _) <- runStateT s st
                      putMVar mv r'
       takeMVar mv
-- | Factory instances allow you to easily generate test data.
--
-- Essentially, you specify a default way of constructing a
-- data type, and allow certain parts of it to be modified (via
-- the 'fields' data structure).
--
-- An example follows:
--
-- > data Foo = Foo Int
-- > newtype FooFields = FooFields (IO Int)
-- > instance Factory App Foo FooFields where
-- >   fields = FooFields randomIO
-- >   save f = liftIO f >>= saveFoo . Foo1
-- >
-- > main = do create id :: SnapHspecM App Foo
-- >           create (const $ FooFields (return 1)) :: SnapHspecM App Foo
class Factory b a d | a -> b, a -> d, d -> a where
  fields :: d
  save :: d -> SnapHspecM b a
  create :: (d -> d) -> SnapHspecM b a
  create transform = save $ transform fields
  reload :: a -> SnapHspecM b a
  reload = return
-- | The way to run a block of `SnapHspecM` tests within an `hspec`
-- test suite. This takes both the top level handler (usually `route
-- routes`, where `routes` are all the routes for your site) and the
-- site initializer (often named `app`), and a block of tests. A test
-- suite can have multiple calls to `snap`, though each one will cause
-- the site initializer to run, which is often a slow operation (and
-- will slow down test suites).
snap :: Handler b b () -> SnapletInit b b -> SpecWith (SnapHspecState b) -> Spec
snap site app spec = do
  snapinit <- runIO $ getSnaplet (Just "test") app
  mv <- runIO (newMVar [])
  case snapinit of
    Left err -> error $ show err
    Right (snaplet, initstate) ->
      afterAll (const $ closeSnaplet initstate) $
        before (return (SnapHspecState Success site snaplet initstate mv (return ()) (return ()))) spec
-- | This allows you to change the default handler you are running
-- requests against within a block. This is most likely useful for
-- setting request state (for example, logging a user in).
modifySite :: (Handler b b () -> Handler b b ())
           -> SpecWith (SnapHspecState b)
           -> SpecWith (SnapHspecState b)
modifySite f = beforeWith (\(SnapHspecState r site snaplet initst sess bef aft) ->
                             return (SnapHspecState r (f site) snaplet initst sess bef aft))
-- | This performs a similar operation to `modifySite` but in the context
-- of `SnapHspecM` (which is needed if you need to `eval`, produce values, and
-- hand them somewhere else (so they can't be created within `f`).
modifySite' :: (Handler b b () -> Handler b b ())
            -> SnapHspecM b a
            -> SnapHspecM b a
modifySite' f a = do (SnapHspecState r site s i sess bef aft) <- S.get
                     S.put (SnapHspecState r (f site) s i sess bef aft)
                     a
-- | Evaluate a Handler action after each test.
afterEval :: Handler b b () -> SpecWith (SnapHspecState b) -> SpecWith (SnapHspecState b)
afterEval h = after (\(SnapHspecState _r _site s i _ _ _) ->
                       do res <- evalHandlerSafe h s i
                          case res of
                            Right _ -> return ()
                            Left msg -> liftIO $ print msg)
-- | Evaluate a Handler action before each test.
beforeEval :: Handler b b () -> SpecWith (SnapHspecState b) -> SpecWith (SnapHspecState b)
beforeEval h = beforeWith (\state@(SnapHspecState _r _site s i _ _ _) -> do void $ evalHandlerSafe h s i
                                                                            return state)
class HasSession b where
  getSessionLens :: SnapletLens b SessionManager
recordSession :: HasSession b => SnapHspecM b a -> SnapHspecM b a
recordSession a =
  do (SnapHspecState r site s i mv bef aft) <- S.get
     S.put (SnapHspecState r site s i mv
                             (do ps <- liftIO $ readMVar mv
                                 with getSessionLens $ mapM_ (uncurry setInSession) ps
                                 with getSessionLens commitSession)
                             (do ps' <- with getSessionLens sessionToList
                                 void . liftIO $ takeMVar mv
                                 liftIO $ putMVar mv ps'))
     res <- a
     (SnapHspecState r' _ _ _ _ _ _) <- S.get
     void . liftIO $ takeMVar mv
     liftIO $ putMVar mv []
     S.put (SnapHspecState r' site s i mv bef aft)
     return res
sessContents :: SnapHspecM b Text
sessContents = do
  (SnapHspecState _ _ _ _ mv _ _) <- S.get
  ps <- liftIO $ readMVar mv
  return $ T.concat (map (uncurry T.append) ps)
sessionShouldContain :: Text -> SnapHspecM b ()
sessionShouldContain t =
  do contents <- sessContents
     if t `T.isInfixOf` contents
       then setResult Success
       else setResult (Fail $ "Session did not contain: " ++ T.unpack t
                            ++ "\n\nSession was:\n" ++ T.unpack contents)
sessionShouldNotContain :: Text -> SnapHspecM b ()
sessionShouldNotContain t =
  do contents <- sessContents
     if t `T.isInfixOf` contents
       then setResult (Fail $ "Session should not have contained: " ++ T.unpack t
                            ++ "\n\nSession was:\n" ++ T.unpack contents)
       else setResult Success
-- | Runs a DELETE request
delete :: Text -> SnapHspecM b TestResponse
delete path = runRequest (Test.delete (T.encodeUtf8 path) M.empty)
-- | Runs a GET request.
get :: Text -> SnapHspecM b TestResponse
get path = get' path M.empty
-- | Runs a GET request, with a set of parameters.
get' :: Text -> Snap.Params -> SnapHspecM b TestResponse
get' path ps = runRequest (Test.get (T.encodeUtf8 path) ps)
-- | A helper to construct parameters.
params :: [(ByteString, ByteString)] -- ^ Pairs of parameter and value.
       -> Snap.Params
params = M.fromList . map (\x -> (fst x, [snd x]))
-- | Creates a new POST request, with a set of parameters.
post :: Text -> Snap.Params -> SnapHspecM b TestResponse
post path ps = runRequest (Test.postUrlEncoded (T.encodeUtf8 path) ps)
-- | Creates a new POST request with a given JSON value as the request body.
postJson :: ToJSON tj => Text -> tj -> SnapHspecM b TestResponse
postJson path json = runRequest $ Test.postRaw (T.encodeUtf8 path)
                                               "application/json"
                                               (toStrict $ encode json)
-- | Creates a new PUT request, with a set of parameters, with a default type of "application/x-www-form-urlencoded"
put :: Text -> Snap.Params -> SnapHspecM b TestResponse
put path params' = put' path "application/x-www-form-urlencoded" params'
-- | Creates a new PUT request with a configurable MIME/type
put' :: Text -> Text -> Snap.Params -> SnapHspecM b TestResponse
put' path mime params' = runRequest $ do
  Test.put (T.encodeUtf8 path) (T.encodeUtf8 mime) ""
  Test.setQueryString params'
-- | Restricts a response to matches for a given CSS selector.
-- Does nothing to non-Html responses.
restrictResponse :: Text -> TestResponse -> TestResponse
restrictResponse selector (Html body) =
  case HXT.runLA (HXT.xshow $ HXT.hread HXT.>>> HS.css (T.unpack selector)) (T.unpack body) of
    [] -> Html ""
    matches -> Html (T.concat (map T.pack matches))
restrictResponse _ r = r
-- | Runs an arbitrary stateful action from your application.
eval :: Handler b b a -> SnapHspecM b a
eval act = do (SnapHspecState _ _site app is _mv bef aft) <- S.get
              liftIO $ either (error . T.unpack) id <$> evalHandlerSafe (do bef
                                                                            r <- act
                                                                            aft
                                                                            return r) app is
-- | Records a test Success or Fail. Only the first Fail will be
-- recorded (and will cause the whole block to Fail).
setResult :: Result -> SnapHspecM b ()
setResult r = do (SnapHspecState r' s a i sess bef aft) <- S.get
                 case r' of
                   Success -> S.put (SnapHspecState r s a i sess bef aft)
                   _ -> return ()
-- | Asserts that a given stateful action will produce a specific different result after
-- an action has been run.
shouldChange :: (Show a, Eq a)
             => (a -> a)
             -> Handler b b a
             -> SnapHspecM b c
             -> SnapHspecM b ()
shouldChange f v act = do before' <- eval v
                          void act
                          after' <- eval v
                          shouldEqual (f before') after'
-- | Asserts that two values are equal.
shouldEqual :: (Show a, Eq a)
            => a
            -> a
            -> SnapHspecM b ()
shouldEqual a b = if a == b
                      then setResult Success
                      else setResult (Fail ("Should have held: " ++ show a ++ " == " ++ show b))
-- | Asserts that two values are not equal.
shouldNotEqual :: (Show a, Eq a)
               => a
               -> a
               -> SnapHspecM b ()
shouldNotEqual a b = if a == b
                         then setResult (Fail ("Should not have held: " ++ show a ++ " == " ++ show b))
                         else setResult Success
-- | Asserts that the value is True.
shouldBeTrue :: Bool
             -> SnapHspecM b ()
shouldBeTrue True = setResult Success
shouldBeTrue False = setResult (Fail "Value should have been True.")
-- | Asserts that the value is not True (otherwise known as False).
shouldNotBeTrue :: Bool
                 -> SnapHspecM b ()
shouldNotBeTrue False = setResult Success
shouldNotBeTrue True = setResult (Fail "Value should have been True.")
-- | Asserts that the response is a success (either Html, or Other with status 200).
should200 :: TestResponse -> SnapHspecM b ()
should200 (Html _) = setResult Success
should200 (Other 200) = setResult Success
should200 r = setResult (Fail (show r))
-- | Asserts that the response is not a normal 200.
shouldNot200 :: TestResponse -> SnapHspecM b ()
shouldNot200 (Html _) = setResult (Fail "Got Html back.")
shouldNot200 (Other 200) = setResult (Fail "Got Other with 200 back.")
shouldNot200 _ = setResult Success
-- | Asserts that the response is a NotFound.
should404 :: TestResponse -> SnapHspecM b ()
should404 NotFound = setResult Success
should404 r = setResult (Fail (show r))
-- | Asserts that the response is not a NotFound.
shouldNot404 :: TestResponse -> SnapHspecM b ()
shouldNot404 NotFound = setResult (Fail "Got NotFound back.")
shouldNot404 _ = setResult Success
-- | Asserts that the response is a redirect.
should300 :: TestResponse -> SnapHspecM b ()
should300 (Redirect _ _) = setResult Success
should300 r = setResult (Fail (show r))
-- | Asserts that the response is not a redirect.
shouldNot300 :: TestResponse -> SnapHspecM b ()
shouldNot300 (Redirect _ _) = setResult (Fail "Got Redirect back.")
shouldNot300 _ = setResult Success
-- | Asserts that the response is a redirect, and thet the url it
-- redirects to starts with the given path.
should300To :: Text -> TestResponse -> SnapHspecM b ()
should300To pth (Redirect _ to) | pth `T.isPrefixOf` to = setResult Success
should300To _ r = setResult (Fail (show r))
-- | Asserts that the response is not a redirect to a given path. Note
-- that it can still be a redirect for this assertion to succeed, the
-- path it redirects to just can't start with the given path.
shouldNot300To :: Text -> TestResponse -> SnapHspecM b ()
shouldNot300To pth (Redirect _ to) | pth `T.isPrefixOf` to = setResult (Fail "Got Redirect back.")
shouldNot300To _ _ = setResult Success
-- | Assert that a response (which should be Html) has a given selector.
shouldHaveSelector :: Text -> TestResponse -> SnapHspecM b ()
shouldHaveSelector selector r@(Html body) =
  setResult $ if haveSelector' selector r
                then Success
                else Fail msg
  where msg = T.unpack $ T.concat ["Html should have contained selector: ", selector, "\n\n", body]
shouldHaveSelector match _ = setResult (Fail (T.unpack $ T.concat ["Non-HTML body should have contained css selector: ", match]))
-- | Assert that a response (which should be Html) doesn't have a given selector.
shouldNotHaveSelector :: Text -> TestResponse -> SnapHspecM b ()
shouldNotHaveSelector selector r@(Html body) =
  setResult $ if haveSelector' selector r
                then Fail msg
                else Success
  where msg = T.unpack $ T.concat ["Html should not have contained selector: ", selector, "\n\n", body]
shouldNotHaveSelector _ _ = setResult Success
haveSelector' :: Text -> TestResponse -> Bool
haveSelector' selector (Html body) =
  case HXT.runLA (HXT.hread HXT.>>> HS.css (T.unpack selector)) (T.unpack body)  of
    [] -> False
    _ -> True
haveSelector' _ _ = False
-- | Asserts that the response (which should be Html) contains the given text.
shouldHaveText :: Text -> TestResponse -> SnapHspecM b ()
shouldHaveText match (Html body) =
  if T.isInfixOf match body
  then setResult Success
  else setResult (Fail $ T.unpack $ T.concat [body, "' contains '", match, "'."])
shouldHaveText match _ = setResult (Fail (T.unpack $ T.concat ["Body contains: ", match]))
-- | Asserts that the response (which should be Html) does not contain the given text.
shouldNotHaveText :: Text -> TestResponse -> SnapHspecM b ()
shouldNotHaveText match (Html body) =
  if T.isInfixOf match body
  then setResult (Fail $ T.unpack $ T.concat [body, "' contains '", match, "'."])
  else setResult Success
shouldNotHaveText _ _ = setResult Success
-- | A data type for tests against forms.
data FormExpectations a = Value a           -- ^ The value the form should take (and should be valid)
                        | Predicate (a -> Bool)
                        | ErrorPaths [Text] -- ^ The error paths that should be populated
-- | Tests against digestive-functors forms.
form :: (Eq a, Show a)
     => FormExpectations a           -- ^ If the form should succeed, Value a is what it should produce.
                                     --   If failing, ErrorPaths should be all the errors that are triggered.
     -> DF.Form Text (Handler b b) a -- ^ The form to run
     -> M.Map Text Text                -- ^ The parameters to pass
     -> SnapHspecM b ()
form expected theForm theParams =
  do r <- eval $ DF.postForm "form" theForm (const $ return lookupParam)
     case expected of
       Value a -> shouldEqual (snd r) (Just a)
       Predicate f ->
         case snd r of
           Nothing -> setResult (Fail $ T.unpack $
                                 T.append "Expected form to validate. Resulted in errors: "
                                          (T.pack (show $ DF.viewErrors $ fst r)))
           Just v -> if f v
                       then setResult Success
                       else setResult (Fail $ T.unpack $
                                       T.append "Expected predicate to pass on value: "
                                                (T.pack (show v)))
       ErrorPaths expectedPaths ->
         do let viewErrorPaths = map (DF.fromPath . fst) $ DF.viewErrors $ fst r
            if all (`elem` viewErrorPaths) expectedPaths
               then if length viewErrorPaths == length expectedPaths
                       then setResult Success
                       else setResult (Fail $ "Number of errors did not match test. Got:\n\n "
                                            ++ show viewErrorPaths
                                            ++ "\n\nBut expected:\n\n"
                                            ++ show expectedPaths)
               else setResult (Fail $ "Did not have all errors specified. Got:\n\n"
                                    ++ show viewErrorPaths
                                    ++ "\n\nBut expected:\n\n"
                                    ++ show expectedPaths)
  where lookupParam pth = case M.lookup (DF.fromPath pth) fixedParams of
                            Nothing -> return []
                            Just v -> return [DF.TextInput v]
        fixedParams = M.mapKeys (T.append "form.") theParams
-- | Runs a request (built with helpers from Snap.Test), resulting in a response.
runRequest :: RequestBuilder IO () -> SnapHspecM b TestResponse
runRequest req = do
  (SnapHspecState _ site app is _ bef aft) <- S.get
  res <- liftIO $ runHandlerSafe req (bef >> site >> aft) app is
  case res of
    Left err ->
      error $ T.unpack err
    Right response ->
      case rspStatus response of
        404 -> return NotFound
        200 ->
          liftIO $ parse200 response
        _ -> if rspStatus response >= 300 && rspStatus response < 400
                then do let url = fromMaybe "" $ getHeader "Location" response
                        return (Redirect (rspStatus response) (T.decodeUtf8 url))
                else return (Other (rspStatus response))
parse200 :: Response -> IO TestResponse
parse200 resp =
    let body        = getResponseBody resp
        contentType = getHeader "content-type" resp in
    case contentType of
      Just "application/json" -> Json . fromStrict <$> body
      _                       -> Html . T.decodeUtf8 <$> body
-- | Runs a request against a given handler (often the whole site),
-- with the given state. Returns any triggered exception, or the response.
runHandlerSafe :: RequestBuilder IO ()
               -> Handler b b v
               -> Snaplet b
               -> InitializerState b
               -> IO (Either Text Response)
runHandlerSafe req site s is =
  catch (runHandler' s is req site) (\(e::SomeException) -> return $ Left (T.pack $ show e))
-- | Evaluates a given handler with the given state. Returns any
-- triggered exception, or the value produced.
evalHandlerSafe :: Handler b b v
                -> Snaplet b
                -> InitializerState b
                -> IO (Either Text v)
evalHandlerSafe act s is =
  catch (evalHandler' s is (Test.get "" M.empty) act) (\(e::SomeException) -> return $ Left (T.pack $ show e))
{-# ANN put ("HLint: ignore Eta reduce"::String)                            #-}
 | 
	bitemyapp/hspec-snap | 
	src/Test/Hspec/Snap.hs | 
	bsd-3-clause | 22,986 | 0 | 22 | 7,031 | 5,474 | 2,827 | 2,647 | 387 | 8 | 
| 
	{-# LANGUAGE TypeOperators, MultiParamTypeClasses, FunctionalDependencies
           , UndecidableInstances
  #-}
-- For ghc 6.6 compatibility
-- {-# OPTIONS -fglasgow-exts -fallow-undecidable-instances #-}
----------------------------------------------------------------------
-- |
-- Module      :  Data.FunArr
-- Copyright   :  (c) Conal Elliott 2007-2013
-- License     :  BSD3
-- 
-- Maintainer  :  conal@conal.net
-- Stability   :  experimental
-- Portability :  portable
-- 
-- Conversion between arrow values and wrapped functions.
----------------------------------------------------------------------
module Data.FunArr
  (
  FunArr(..) -- , wapl
  ) where
-- import Control.Monad.Identity
import Control.Compose
infixr 0  $$  -- FunArr application
-- | Convert between an arrow value and a \"wrapped function\".  The \"arrow\"
-- doesn't really have to be an arrow.  I'd appreciate ideas for names &
-- uses.
class FunArr ar w | ar->w , w->ar where
  -- | Convert a @w@-wrapped function to an arrow value
  toArr :: w (a->b) -> (a `ar` b)
  -- | Apply an arrow to a @w@-wrapped value
  ($$)  :: (a `ar` b) -> w a -> w b
-- -- | Apply a wrapped function to a wrapped value
-- wapl :: FunArr ar w => w (a->b) -> w a -> w b
-- wapl f a = toArr f $$ a
-- The type of wapl matches <*> from Control.Applicative.  What about
-- "pure" from the Applicative class, with type a -> w a?
-- Function/Id instance
instance FunArr (->) Id where
  toArr (Id f) = f
  f $$ Id a    = Id (f a)
-- -- Oops!  This instance can't work with the mutual functional
-- dependencies.  Instead, instantiate it per @h@.
-- 
-- instance FunArr (FunA h) h where
--   toArr = error "toArr: undefined for FunArr" --  Add FunArrable class & delegate
--   FunA f $$ ha = f ha
-- The following instance violates the "coverage condition" and so
-- requires -fallow-undecidable-instances.
instance (FunArr ar w, FunArr ar' w')
    => FunArr (ar ::*:: ar') (w :*: w') where
  toArr (Prod (f,f'))         = Prodd (toArr f, toArr f')
  Prodd (f,f') $$ Prod (w,w') = Prod (f $$ w, f' $$ w')
 | 
	conal/DeepArrow | 
	src/Data/FunArr.hs | 
	bsd-3-clause | 2,075 | 2 | 10 | 435 | 310 | 184 | 126 | 17 | 0 | 
| 
	module Main where
import Build_doctests (flags, pkgs, module_sources)
import Data.Foldable (traverse_)
import Test.DocTest (doctest)
main :: IO ()
main = do
    traverse_ putStrLn args
    doctest args
  where
    args = ["-XOverloadedStrings"] ++ flags ++ pkgs ++ module_sources
 | 
	kazu-yamamoto/unix-time | 
	test/doctests.hs | 
	bsd-3-clause | 282 | 0 | 10 | 52 | 89 | 49 | 40 | 9 | 1 | 
| 
	-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.Client.Configure
-- Copyright   :  (c) David Himmelstrup 2005,
--                    Duncan Coutts 2005
-- License     :  BSD-like
--
-- Maintainer  :  cabal-devel@haskell.org
-- Portability :  portable
--
-- High level interface to configuring a package.
-----------------------------------------------------------------------------
module Distribution.Client.Configure (
    configure,
  ) where
import Distribution.Client.Dependency
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.InstallPlan (InstallPlan)
import Distribution.Client.IndexUtils as IndexUtils
         ( getSourcePackages, getInstalledPackages )
import Distribution.Client.Setup
         ( ConfigExFlags(..), configureCommand, filterConfigureFlags )
import Distribution.Client.Types as Source
import Distribution.Client.SetupWrapper
         ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.Targets
         ( userToPackageConstraint )
import Distribution.Simple.Compiler
         ( CompilerId(..), Compiler(compilerId)
         , PackageDB(..), PackageDBStack )
import Distribution.Simple.Program (ProgramConfiguration )
import Distribution.Simple.Setup
         ( ConfigFlags(..), fromFlag, toFlag, flagToMaybe, fromFlagOrDefault )
import Distribution.Simple.PackageIndex (PackageIndex)
import Distribution.Simple.Utils
         ( defaultPackageDesc )
import Distribution.Package
         ( Package(..), packageName, Dependency(..), thisPackageVersion )
import Distribution.PackageDescription.Parse
         ( readPackageDescription )
import Distribution.PackageDescription.Configuration
         ( finalizePackageDescription )
import Distribution.Version
         ( anyVersion, thisVersion )
import Distribution.Simple.Utils as Utils
         ( notice, info, debug, die )
import Distribution.System
         ( Platform, buildPlatform )
import Distribution.Verbosity as Verbosity
         ( Verbosity )
import Data.Monoid (Monoid(..))
-- | Configure the package found in the local directory
configure :: Verbosity
          -> PackageDBStack
          -> [Repo]
          -> Compiler
          -> ProgramConfiguration
          -> ConfigFlags
          -> ConfigExFlags
          -> [String]
          -> IO ()
configure verbosity packageDBs repos comp conf
  configFlags configExFlags extraArgs = do
  installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf
  sourcePkgDb       <- getSourcePackages    verbosity repos
  progress <- planLocalPackage verbosity comp configFlags configExFlags
                               installedPkgIndex sourcePkgDb
  notice verbosity "Resolving dependencies..."
  maybePlan <- foldProgress logMsg (return . Left) (return . Right)
                            progress
  case maybePlan of
    Left message -> do
      info verbosity message
      setupWrapper verbosity (setupScriptOptions installedPkgIndex) Nothing
        configureCommand (const configFlags) extraArgs
    Right installPlan -> case InstallPlan.ready installPlan of
      [pkg@(ConfiguredPackage (SourcePackage _ _ (LocalUnpackedPackage _)) _ _ _)] ->
        configurePackage verbosity
          (InstallPlan.planPlatform installPlan)
          (InstallPlan.planCompiler installPlan)
          (setupScriptOptions installedPkgIndex)
          configFlags pkg extraArgs
      _ -> die $ "internal error: configure install plan should have exactly "
              ++ "one local ready package."
  where
    setupScriptOptions index = SetupScriptOptions {
      useCabalVersion  = maybe anyVersion thisVersion
                         (flagToMaybe (configCabalVersion configExFlags)),
      useCompiler      = Just comp,
      -- Hack: we typically want to allow the UserPackageDB for finding the
      -- Cabal lib when compiling any Setup.hs even if we're doing a global
      -- install. However we also allow looking in a specific package db.
      usePackageDB     = if UserPackageDB `elem` packageDBs
                           then packageDBs
                           else packageDBs ++ [UserPackageDB],
      usePackageIndex  = if UserPackageDB `elem` packageDBs
                           then Just index
                           else Nothing,
      useProgramConfig = conf,
      useDistPref      = fromFlagOrDefault
                           (useDistPref defaultSetupScriptOptions)
                           (configDistPref configFlags),
      useLoggingHandle = Nothing,
      useWorkingDir    = Nothing
    }
    logMsg message rest = debug verbosity message >> rest
-- | Make an 'InstallPlan' for the unpacked package in the current directory,
-- and all its dependencies.
--
planLocalPackage :: Verbosity -> Compiler
                 -> ConfigFlags -> ConfigExFlags
                 -> PackageIndex
                 -> SourcePackageDb
                 -> IO (Progress String String InstallPlan)
planLocalPackage verbosity comp configFlags configExFlags installedPkgIndex
  (SourcePackageDb _ packagePrefs) = do
  pkg <- readPackageDescription verbosity =<< defaultPackageDesc verbosity
  let -- We create a local package and ask to resolve a dependency on it
      localPkg = SourcePackage {
        packageInfoId             = packageId pkg,
        Source.packageDescription = pkg,
        packageSource             = LocalUnpackedPackage "."
      }
      solver = fromFlag $ configSolver configExFlags
      testsEnabled = fromFlagOrDefault False $ configTests configFlags
      benchmarksEnabled =
        fromFlagOrDefault False $ configBenchmarks configFlags
      resolverParams =
          addPreferences
            -- preferences from the config file or command line
            [ PackageVersionPreference name ver
            | Dependency name ver <- configPreferences configExFlags ]
        . addConstraints
            -- version constraints from the config file or command line
            -- TODO: should warn or error on constraints that are not on direct deps
            -- or flag constraints not on the package in question.
            (map userToPackageConstraint (configExConstraints configExFlags))
        . addConstraints
            -- package flags from the config file or command line
            [ PackageConstraintFlags (packageName pkg)
                                     (configConfigurationsFlags configFlags) ]
        . addConstraints
            -- '--enable-tests' and '--enable-benchmarks' constraints from
            -- command line
            [ PackageConstraintStanzas (packageName pkg) $ concat
                [ if testsEnabled then [TestStanzas] else []
                , if benchmarksEnabled then [BenchStanzas] else []
                ]
            ]
        $ standardInstallPolicy
            installedPkgIndex
            (SourcePackageDb mempty packagePrefs)
            [SpecificSourcePackage localPkg]
  return (resolveDependencies buildPlatform (compilerId comp) solver resolverParams)
-- | Call an installer for an 'SourcePackage' but override the configure
-- flags with the ones given by the 'ConfiguredPackage'. In particular the
-- 'ConfiguredPackage' specifies an exact 'FlagAssignment' and exactly
-- versioned package dependencies. So we ignore any previous partial flag
-- assignment or dependency constraints and use the new ones.
--
configurePackage :: Verbosity
                 -> Platform -> CompilerId
                 -> SetupScriptOptions
                 -> ConfigFlags
                 -> ConfiguredPackage
                 -> [String]
                 -> IO ()
configurePackage verbosity platform comp scriptOptions configFlags
  (ConfiguredPackage (SourcePackage _ gpkg _) flags stanzas deps) extraArgs =
  setupWrapper verbosity
    scriptOptions (Just pkg) configureCommand configureFlags extraArgs
  where
    configureFlags   = filterConfigureFlags configFlags {
      configConfigurationsFlags = flags,
      configConstraints         = map thisPackageVersion deps,
      configVerbosity           = toFlag verbosity,
      configBenchmarks          = toFlag (BenchStanzas `elem` stanzas),
      configTests               = toFlag (TestStanzas `elem` stanzas)
    }
    pkg = case finalizePackageDescription flags
           (const True)
           platform comp [] (enableStanzas stanzas gpkg) of
      Left _ -> error "finalizePackageDescription ConfiguredPackage failed"
      Right (desc, _) -> desc
 | 
	alphaHeavy/cabal | 
	cabal-install/Distribution/Client/Configure.hs | 
	bsd-3-clause | 8,529 | 0 | 20 | 2,277 | 1,429 | 793 | 636 | 144 | 5 | 
| 
	module Text.OpenGL.Xml.ReadRegistry (
    readRegistry,
    parseRegistry,
    PreProcess
) where
import Prelude hiding ((.), id)
import Control.Category
import Text.OpenGL.Types
import Text.OpenGL.Xml.Pickle()
import Text.OpenGL.Xml.PreProcess
import Text.XML.HXT.Core
type PreProcess = Bool
-- TODO RelaxNG validation
readRegistry :: FilePath -> PreProcess -> IO (Either String Registry)
readRegistry fp pp = do
    results <- runX (
            readDocument readOpts fp >>> preProcess pp >>> parseRegistryArrow
        ) -- TODO: error handling
    return $ handleResults results
  where
    readOpts :: [SysConfig]
    readOpts = [withValidate no, withPreserveComment no]
preProcess :: (ArrowChoice a, ArrowXml a) => PreProcess -> a XmlTree XmlTree
preProcess pp = if pp then preProcessRegistry else id
-- | TODO: make it work (doesn't work with the <?xml ?> header.
parseRegistry :: String -> PreProcess -> Either String Registry
parseRegistry str pp = handleResults $ runLA (
        xread >>> preProcess pp >>> parseRegistryArrow
    ) str
handleResults :: [Either String Registry] -> Either String Registry
handleResults rs = case rs of
    []      -> Left "No parse"
    (_:_:_) -> Left "Multiple parse"
    [rc]    -> rc
parseRegistryArrow :: ArrowXml a => a XmlTree (Either String Registry)
parseRegistryArrow =
    removeAllWhiteSpace >>> -- This processing is needed for the non IO case.
    removeAllComment >>>
    arr (unpickleDoc' xpickle)
 | 
	Laar/opengl-xmlspec | 
	src/Text/OpenGL/Xml/ReadRegistry.hs | 
	bsd-3-clause | 1,468 | 0 | 12 | 298 | 395 | 213 | 182 | 34 | 3 | 
| 
	{-# Language OverloadedStrings #-}
module XMonad.Actions.XHints.Render where
import XMonad hiding (drawString)
import Data.Text (Text)
import qualified Data.Text as T
import Foreign.C
import Graphics.X11.Xlib.Types
import qualified Data.Text.Foreign as TF
import qualified Data.ByteString as BS
import Codec.Binary.UTF8.String
mkUnmanagedWindow :: Display -> Screen -> Window -> Position
                  -> Position -> Dimension -> Dimension -> IO Window
mkUnmanagedWindow d s rw x y w h = do
  let visual = defaultVisualOfScreen s
      attrmask = cWOverrideRedirect
  allocaSetWindowAttributes $
         \attributes -> do
           set_override_redirect attributes True
           createWindow d rw x y w h 0 (defaultDepthOfScreen s)
                        inputOutput visual attrmask attributes
newHintWindow :: Display  -> IO (Window,GC)
newHintWindow dpy = do
  let win = defaultRootWindow dpy
      blk = blackPixel dpy $ defaultScreen dpy
      wht = whitePixel dpy $ defaultScreen dpy
      scn = defaultScreenOfDisplay dpy
  (_,_,_,_,_,x,y,_) <- queryPointer dpy win
  nw <- createSimpleWindow dpy win (fromIntegral x) (fromIntegral y) 2 2 1 blk wht
  mapWindow dpy nw
  gc <- createGC dpy nw
  return (nw,gc)
 | 
	netogallo/XHints | 
	src/XMonad/Actions/XHints/Render.hs | 
	bsd-3-clause | 1,227 | 0 | 13 | 272 | 381 | 202 | 179 | 31 | 1 | 
End of preview. Expand
						in Data Studio
					
Dataset Card for "github-code-haskell-file"
Rows: 339k Download Size: 806M
This dataset is extracted from github-code-clean.
Each row also contains attribute values for my personal analysis project.
12.6% (43k) of the rows have cyclomatic complexity and LOC valued at -1 because homplexity failed in parsing the row's uncommented_code.
- Downloads last month
- 30
