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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- | Support for command-line completion at the REPL and in the prover
module Idris.Completion (replCompletion, proverCompletion) where
import Idris.Core.Evaluate (ctxtAlist)
import Idris.Core.TT
import Idris.AbsSyntax (runIO)
import Idris.AbsSyntaxTree
import Idris.Help
import Idris.Imports (installedPackages)
import Idris.Colours
import Idris.ParseHelpers(opChars)
import qualified Idris.ParseExpr (constants, tactics)
import Idris.ParseExpr (TacticArg (..))
import Idris.REPLParser (allHelp, setOptions)
import Control.Monad.State.Strict
import Data.List
import Data.Maybe
import Data.Char(toLower)
import System.Console.Haskeline
import System.Console.ANSI (Color)
commands = [ n | (names, _, _) <- allHelp ++ extraHelp, n <- names ]
tacticArgs :: [(String, Maybe TacticArg)]
tacticArgs = [ (name, args) | (names, args, _) <- Idris.ParseExpr.tactics
, name <- names ]
tactics = map fst tacticArgs
-- | Convert a name into a string usable for completion. Filters out names
-- that users probably don't want to see.
nameString :: Name -> Maybe String
nameString (UN nm)
| not (tnull nm) && (thead nm == '@' || thead nm == '#') = Nothing
nameString (UN n) = Just (str n)
nameString (NS n _) = nameString n
nameString _ = Nothing
-- FIXME: Respect module imports
-- Issue #1767 in the issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1767
-- | Get the user-visible names from the current interpreter state.
names :: Idris [String]
names = do i <- get
let ctxt = tt_ctxt i
return . nub $
mapMaybe (nameString . fst) (ctxtAlist ctxt) ++
"Type" : map fst Idris.ParseExpr.constants
metavars :: Idris [String]
metavars = do i <- get
return . map (show . nsroot) $ map fst (filter (\(_, (_,_,_,t)) -> not t) (idris_metavars i)) \\ primDefs
modules :: Idris [String]
modules = do i <- get
return $ map show $ imported i
completeWith :: [String] -> String -> [Completion]
completeWith ns n = if uniqueExists
then [simpleCompletion n]
else map simpleCompletion prefixMatches
where prefixMatches = filter (isPrefixOf n) ns
uniqueExists = [n] == prefixMatches
completeName :: [String] -> String -> Idris [Completion]
completeName extra n = do ns <- names
return $ completeWith (extra ++ ns) n
completeExpr :: [String] -> CompletionFunc Idris
completeExpr extra = completeWord Nothing (" \t(){}:" ++ opChars) (completeName extra)
completeMetaVar :: CompletionFunc Idris
completeMetaVar = completeWord Nothing (" \t(){}:" ++ opChars) completeM
where completeM m = do mvs <- metavars
return $ completeWith mvs m
completeOption :: CompletionFunc Idris
completeOption = completeWord Nothing " \t" completeOpt
where completeOpt = return . completeWith (map fst setOptions)
completeConsoleWidth :: CompletionFunc Idris
completeConsoleWidth = completeWord Nothing " \t" completeW
where completeW = return . completeWith ["auto", "infinite", "80", "120"]
isWhitespace :: Char -> Bool
isWhitespace = (flip elem) " \t\n"
lookupInHelp :: String -> Maybe CmdArg
lookupInHelp cmd = lookupInHelp' cmd allHelp
where lookupInHelp' cmd ((cmds, arg, _):xs) | elem cmd cmds = Just arg
| otherwise = lookupInHelp' cmd xs
lookupInHelp' cmd [] = Nothing
completeColour :: CompletionFunc Idris
completeColour (prev, next) = case words (reverse prev) of
[c] | isCmd c -> do cmpls <- completeColourOpt next
return (reverse $ c ++ " ", cmpls)
[c, o] | o `elem` opts -> let correct = (c ++ " " ++ o) in
return (reverse correct, [simpleCompletion ""])
| o `elem` colourTypes -> completeColourFormat (prev, next)
| otherwise -> let cmpls = completeWith (opts ++ colourTypes) o in
let sofar = (c ++ " ") in
return (reverse sofar, cmpls)
cmd@(c:o:_) | isCmd c && o `elem` colourTypes ->
completeColourFormat (prev, next)
_ -> noCompletion (prev, next)
where completeColourOpt :: String -> Idris [Completion]
completeColourOpt = return . completeWith (opts ++ colourTypes)
opts = ["on", "off"]
colourTypes = map (map toLower . reverse . drop 6 . reverse . show) $
enumFromTo (minBound::ColourType) maxBound
isCmd ":colour" = True
isCmd ":color" = True
isCmd _ = False
colours = map (map toLower . show) $ enumFromTo (minBound::Color) maxBound
formats = ["vivid", "dull", "underline", "nounderline", "bold", "nobold", "italic", "noitalic"]
completeColourFormat = let getCmpl = completeWith (colours ++ formats) in
completeWord Nothing " \t" (return . getCmpl)
-- The FIXMEs are Issue #1768 on the issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1768
-- | Get the completion function for a particular command
completeCmd :: String -> CompletionFunc Idris
completeCmd cmd (prev, next) = fromMaybe completeCmdName $ fmap completeArg $ lookupInHelp cmd
where completeArg FileArg = completeFilename (prev, next)
completeArg NameArg = completeExpr [] (prev, next) -- FIXME only complete one name
completeArg OptionArg = completeOption (prev, next)
completeArg ModuleArg = noCompletion (prev, next) -- FIXME do later
completeArg NamespaceArg = noCompletion (prev, next) -- FIXME do later
completeArg ExprArg = completeExpr [] (prev, next)
completeArg MetaVarArg = completeMetaVar (prev, next) -- FIXME only complete one name
completeArg ColourArg = completeColour (prev, next)
completeArg NoArg = noCompletion (prev, next)
completeArg ConsoleWidthArg = completeConsoleWidth (prev, next)
completeArg DeclArg = completeExpr [] (prev, next)
completeArg PkgArgs = completePkg (prev, next)
completeArg (ManyArgs a) = completeArg a
completeArg (OptionalArg a) = completeArg a
completeArg (SeqArgs a b) = completeArg a
completeArg _ = noCompletion (prev, next)
completeCmdName = return $ ("", completeWith commands cmd)
-- | Complete REPL commands and defined identifiers
replCompletion :: CompletionFunc Idris
replCompletion (prev, next) = case firstWord of
':':cmdName -> completeCmd (':':cmdName) (prev, next)
_ -> completeExpr [] (prev, next)
where firstWord = fst $ break isWhitespace $ dropWhile isWhitespace $ reverse prev
completePkg :: CompletionFunc Idris
completePkg = completeWord Nothing " \t()" completeP
where completeP p = do pkgs <- runIO installedPackages
return $ completeWith pkgs p
-- The TODOs are Issue #1769 on the issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1769
completeTactic :: [String] -> String -> CompletionFunc Idris
completeTactic as tac (prev, next) = fromMaybe completeTacName . fmap completeArg $
lookup tac tacticArgs
where completeTacName = return $ ("", completeWith tactics tac)
completeArg Nothing = noCompletion (prev, next)
completeArg (Just NameTArg) = noCompletion (prev, next) -- this is for binding new names!
completeArg (Just ExprTArg) = completeExpr as (prev, next)
completeArg (Just StringLitTArg) = noCompletion (prev, next)
completeArg (Just AltsTArg) = noCompletion (prev, next) -- TODO
-- | Complete tactics and their arguments
proverCompletion :: [String] -- ^ The names of current local assumptions
-> CompletionFunc Idris
proverCompletion assumptions (prev, next) = completeTactic assumptions firstWord (prev, next)
where firstWord = fst $ break isWhitespace $ dropWhile isWhitespace $ reverse prev
|
TimRichter/Idris-dev
|
src/Idris/Completion.hs
|
bsd-3-clause
| 8,441
| 0
| 16
| 2,405
| 2,343
| 1,230
| 1,113
| 135
| 16
|
module D2 where
sumSquares ((x : xs)) = (sq x) + (sumSquares xs)
sumSquares [] = 0
sq x = x ^ pow
pow = 2
|
kmate/HaRe
|
old/testing/rmOneParameter/D2_AstOut.hs
|
bsd-3-clause
| 111
| 0
| 8
| 31
| 65
| 35
| 30
| 5
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Builtin
-- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- The module defines all the known built-in 'Program's.
--
-- Where possible we try to find their version numbers.
--
module Distribution.Simple.Program.Builtin (
-- * The collection of unconfigured and configured programs
builtinPrograms,
-- * Programs that Cabal knows about
ghcProgram,
ghcPkgProgram,
ghcjsProgram,
ghcjsPkgProgram,
lhcProgram,
lhcPkgProgram,
hmakeProgram,
jhcProgram,
haskellSuiteProgram,
haskellSuitePkgProgram,
uhcProgram,
gccProgram,
arProgram,
stripProgram,
happyProgram,
alexProgram,
hsc2hsProgram,
c2hsProgram,
cpphsProgram,
hscolourProgram,
haddockProgram,
greencardProgram,
ldProgram,
tarProgram,
cppProgram,
pkgConfigProgram,
hpcProgram,
) where
import Distribution.Simple.Program.Find
( findProgramOnSearchPath )
import Distribution.Simple.Program.Internal
( stripExtractVersion )
import Distribution.Simple.Program.Run
( getProgramInvocationOutput, programInvocation )
import Distribution.Simple.Program.Types
( Program(..), ConfiguredProgram(..), simpleProgram )
import Distribution.Simple.Utils
( findProgramVersion )
import Distribution.Compat.Exception
( catchIO )
import Distribution.Verbosity
( lessVerbose )
import Distribution.Version
( Version(..), withinRange, earlierVersion, laterVersion
, intersectVersionRanges )
import Data.Char
( isDigit )
import Data.List
( isInfixOf )
import qualified Data.Map as Map
-- ------------------------------------------------------------
-- * Known programs
-- ------------------------------------------------------------
-- | The default list of programs.
-- These programs are typically used internally to Cabal.
builtinPrograms :: [Program]
builtinPrograms =
[
-- compilers and related progs
ghcProgram
, ghcPkgProgram
, ghcjsProgram
, ghcjsPkgProgram
, haskellSuiteProgram
, haskellSuitePkgProgram
, hmakeProgram
, jhcProgram
, lhcProgram
, lhcPkgProgram
, uhcProgram
, hpcProgram
-- preprocessors
, hscolourProgram
, haddockProgram
, happyProgram
, alexProgram
, hsc2hsProgram
, c2hsProgram
, cpphsProgram
, greencardProgram
-- platform toolchain
, gccProgram
, arProgram
, stripProgram
, ldProgram
, tarProgram
-- configuration tools
, pkgConfigProgram
]
ghcProgram :: Program
ghcProgram = (simpleProgram "ghc") {
programFindVersion = findProgramVersion "--numeric-version" id,
-- Workaround for https://ghc.haskell.org/trac/ghc/ticket/8825
-- (spurious warning on non-english locales)
programPostConf = \_verbosity ghcProg ->
do let ghcProg' = ghcProg {
programOverrideEnv = ("LANGUAGE", Just "en")
: programOverrideEnv ghcProg
}
-- Only the 7.8 branch seems to be affected. Fixed in 7.8.4.
affectedVersionRange = intersectVersionRanges
(laterVersion $ Version [7,8,0] [])
(earlierVersion $ Version [7,8,4] [])
return $ maybe ghcProg
(\v -> if withinRange v affectedVersionRange
then ghcProg' else ghcProg)
(programVersion ghcProg)
}
ghcPkgProgram :: Program
ghcPkgProgram = (simpleProgram "ghc-pkg") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- Invoking "ghc-pkg --version" gives a string like
-- "GHC package manager version 6.4.1"
case words str of
(_:_:_:_:ver:_) -> ver
_ -> ""
}
ghcjsProgram :: Program
ghcjsProgram = (simpleProgram "ghcjs") {
programFindVersion = findProgramVersion "--numeric-ghcjs-version" id
}
-- note: version is the version number of the GHC version that ghcjs-pkg was built with
ghcjsPkgProgram :: Program
ghcjsPkgProgram = (simpleProgram "ghcjs-pkg") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- Invoking "ghcjs-pkg --version" gives a string like
-- "GHCJS package manager version 6.4.1"
case words str of
(_:_:_:_:ver:_) -> ver
_ -> ""
}
lhcProgram :: Program
lhcProgram = (simpleProgram "lhc") {
programFindVersion = findProgramVersion "--numeric-version" id
}
lhcPkgProgram :: Program
lhcPkgProgram = (simpleProgram "lhc-pkg") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- Invoking "lhc-pkg --version" gives a string like
-- "LHC package manager version 0.7"
case words str of
(_:_:_:_:ver:_) -> ver
_ -> ""
}
hmakeProgram :: Program
hmakeProgram = (simpleProgram "hmake") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- Invoking "hmake --version" gives a string line
-- "/usr/local/bin/hmake: 3.13 (2006-11-01)"
case words str of
(_:ver:_) -> ver
_ -> ""
}
jhcProgram :: Program
jhcProgram = (simpleProgram "jhc") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- invoking "jhc --version" gives a string like
-- "jhc 0.3.20080208 (wubgipkamcep-2)
-- compiled by ghc-6.8 on a x86_64 running linux"
case words str of
(_:ver:_) -> ver
_ -> ""
}
uhcProgram :: Program
uhcProgram = (simpleProgram "uhc") {
programFindVersion = findProgramVersion "--version-dotted" id
}
hpcProgram :: Program
hpcProgram = (simpleProgram "hpc")
{
programFindVersion = findProgramVersion "version" $ \str ->
case words str of
(_ : _ : _ : ver : _) -> ver
_ -> ""
}
-- This represents a haskell-suite compiler. Of course, the compiler
-- itself probably is not called "haskell-suite", so this is not a real
-- program. (But we don't know statically the name of the actual compiler,
-- so this is the best we can do.)
--
-- Having this Program value serves two purposes:
--
-- 1. We can accept options for the compiler in the form of
--
-- --haskell-suite-option(s)=...
--
-- 2. We can find a program later using this static id (with
-- requireProgram).
--
-- The path to the real compiler is found and recorded in the ProgramDb
-- during the configure phase.
haskellSuiteProgram :: Program
haskellSuiteProgram = (simpleProgram "haskell-suite") {
-- pretend that the program exists, otherwise it won't be in the
-- "configured" state
programFindLocation =
\_verbosity _searchPath -> return $ Just "haskell-suite-dummy-location"
}
-- This represent a haskell-suite package manager. See the comments for
-- haskellSuiteProgram.
haskellSuitePkgProgram :: Program
haskellSuitePkgProgram = (simpleProgram "haskell-suite-pkg") {
programFindLocation =
\_verbosity _searchPath -> return $ Just "haskell-suite-pkg-dummy-location"
}
happyProgram :: Program
happyProgram = (simpleProgram "happy") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- Invoking "happy --version" gives a string like
-- "Happy Version 1.16 Copyright (c) ...."
case words str of
(_:_:ver:_) -> ver
_ -> ""
}
alexProgram :: Program
alexProgram = (simpleProgram "alex") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- Invoking "alex --version" gives a string like
-- "Alex version 2.1.0, (c) 2003 Chris Dornan and Simon Marlow"
case words str of
(_:_:ver:_) -> takeWhile (\x -> isDigit x || x == '.') ver
_ -> ""
}
gccProgram :: Program
gccProgram = (simpleProgram "gcc") {
programFindVersion = findProgramVersion "-dumpversion" id
}
arProgram :: Program
arProgram = simpleProgram "ar"
stripProgram :: Program
stripProgram = (simpleProgram "strip") {
programFindVersion = \verbosity ->
findProgramVersion "--version" stripExtractVersion (lessVerbose verbosity)
}
hsc2hsProgram :: Program
hsc2hsProgram = (simpleProgram "hsc2hs") {
programFindVersion =
findProgramVersion "--version" $ \str ->
-- Invoking "hsc2hs --version" gives a string like "hsc2hs version 0.66"
case words str of
(_:_:ver:_) -> ver
_ -> ""
}
c2hsProgram :: Program
c2hsProgram = (simpleProgram "c2hs") {
programFindVersion = findProgramVersion "--numeric-version" id
}
cpphsProgram :: Program
cpphsProgram = (simpleProgram "cpphs") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- Invoking "cpphs --version" gives a string like "cpphs 1.3"
case words str of
(_:ver:_) -> ver
_ -> ""
}
hscolourProgram :: Program
hscolourProgram = (simpleProgram "hscolour") {
programFindLocation = \v p -> findProgramOnSearchPath v p "HsColour",
programFindVersion = findProgramVersion "-version" $ \str ->
-- Invoking "HsColour -version" gives a string like "HsColour 1.7"
case words str of
(_:ver:_) -> ver
_ -> ""
}
haddockProgram :: Program
haddockProgram = (simpleProgram "haddock") {
programFindVersion = findProgramVersion "--version" $ \str ->
-- Invoking "haddock --version" gives a string like
-- "Haddock version 0.8, (c) Simon Marlow 2006"
case words str of
(_:_:ver:_) -> takeWhile (`elem` ('.':['0'..'9'])) ver
_ -> ""
}
greencardProgram :: Program
greencardProgram = simpleProgram "greencard"
ldProgram :: Program
ldProgram = simpleProgram "ld"
tarProgram :: Program
tarProgram = (simpleProgram "tar") {
-- See #1901. Some versions of 'tar' (OpenBSD, NetBSD, ...) don't support the
-- '--format' option.
programPostConf = \verbosity tarProg -> do
tarHelpOutput <- getProgramInvocationOutput
verbosity (programInvocation tarProg ["--help"])
-- Some versions of tar don't support '--help'.
`catchIO` (\_ -> return "")
let k = "Supports --format"
v = if ("--format" `isInfixOf` tarHelpOutput) then "YES" else "NO"
m = Map.insert k v (programProperties tarProg)
return $ tarProg { programProperties = m }
}
cppProgram :: Program
cppProgram = simpleProgram "cpp"
pkgConfigProgram :: Program
pkgConfigProgram = (simpleProgram "pkg-config") {
programFindVersion = findProgramVersion "--version" id
}
|
enolan/cabal
|
Cabal/Distribution/Simple/Program/Builtin.hs
|
bsd-3-clause
| 10,750
| 0
| 17
| 2,650
| 1,979
| 1,137
| 842
| 216
| 2
|
import Data.Ratio
-- !!! Test that (%) has the right fixity
main = print (2^3%5)
|
seereason/ghcjs
|
test/pkg/base/ratio001.hs
|
mit
| 82
| 1
| 8
| 16
| 29
| 14
| 15
| 2
| 1
|
{-# htermination (minFloat :: Float -> Float -> Float) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Float = Float MyInt MyInt ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ordering = LT | EQ | GT ;
primCmpNat :: Nat -> Nat -> Ordering;
primCmpNat Zero Zero = EQ;
primCmpNat Zero (Succ y) = LT;
primCmpNat (Succ x) Zero = GT;
primCmpNat (Succ x) (Succ y) = primCmpNat x y;
primCmpInt :: MyInt -> MyInt -> Ordering;
primCmpInt (Pos Zero) (Pos Zero) = EQ;
primCmpInt (Pos Zero) (Neg Zero) = EQ;
primCmpInt (Neg Zero) (Pos Zero) = EQ;
primCmpInt (Neg Zero) (Neg Zero) = EQ;
primCmpInt (Pos x) (Pos y) = primCmpNat x y;
primCmpInt (Pos x) (Neg y) = GT;
primCmpInt (Neg x) (Pos y) = LT;
primCmpInt (Neg x) (Neg y) = primCmpNat y x;
compareMyInt :: MyInt -> MyInt -> Ordering
compareMyInt = primCmpInt;
primPlusNat :: Nat -> Nat -> Nat;
primPlusNat Zero Zero = Zero;
primPlusNat Zero (Succ y) = Succ y;
primPlusNat (Succ x) Zero = Succ x;
primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y));
primMulNat :: Nat -> Nat -> Nat;
primMulNat Zero Zero = Zero;
primMulNat Zero (Succ y) = Zero;
primMulNat (Succ x) Zero = Zero;
primMulNat (Succ x) (Succ y) = primPlusNat (primMulNat x (Succ y)) (Succ y);
primMulInt :: MyInt -> MyInt -> MyInt;
primMulInt (Pos x) (Pos y) = Pos (primMulNat x y);
primMulInt (Pos x) (Neg y) = Neg (primMulNat x y);
primMulInt (Neg x) (Pos y) = Neg (primMulNat x y);
primMulInt (Neg x) (Neg y) = Pos (primMulNat x y);
srMyInt :: MyInt -> MyInt -> MyInt
srMyInt = primMulInt;
primCmpFloat :: Float -> Float -> Ordering;
primCmpFloat (Float x1 x2) (Float y1 y2) = compareMyInt (srMyInt x1 y1) (srMyInt x2 y2);
compareFloat :: Float -> Float -> Ordering
compareFloat = primCmpFloat;
esEsOrdering :: Ordering -> Ordering -> MyBool
esEsOrdering LT LT = MyTrue;
esEsOrdering LT EQ = MyFalse;
esEsOrdering LT GT = MyFalse;
esEsOrdering EQ LT = MyFalse;
esEsOrdering EQ EQ = MyTrue;
esEsOrdering EQ GT = MyFalse;
esEsOrdering GT LT = MyFalse;
esEsOrdering GT EQ = MyFalse;
esEsOrdering GT GT = MyTrue;
not :: MyBool -> MyBool;
not MyTrue = MyFalse;
not MyFalse = MyTrue;
fsEsOrdering :: Ordering -> Ordering -> MyBool
fsEsOrdering x y = not (esEsOrdering x y);
ltEsFloat :: Float -> Float -> MyBool
ltEsFloat x y = fsEsOrdering (compareFloat x y) GT;
min0 x y MyTrue = y;
otherwise :: MyBool;
otherwise = MyTrue;
min1 x y MyTrue = x;
min1 x y MyFalse = min0 x y otherwise;
min2 x y = min1 x y (ltEsFloat x y);
minFloat :: Float -> Float -> Float
minFloat x y = min2 x y;
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/min_4.hs
|
mit
| 2,655
| 5
| 9
| 570
| 1,232
| 638
| 594
| 69
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -freduction-depth=50 #-}
module CoqLNOutputThmOpenClose where
import Text.Printf ( printf )
import AST
import ASTAnalysis
import ComputationMonad
import CoqLNOutputCommon
import CoqLNOutputCombinators
openCloseThms :: ASTAnalysis -> [[NtRoot]] -> M String
openCloseThms aa nts =
do { close_inj_recs <- mapM (local . close_inj_rec aa) nts
; close_injs <- mapM (local . close_inj aa) nts
; close_open_recs <- mapM (local . close_open_rec aa) nts
; close_opens <- mapM (local . close_open aa) nts
; open_close_recs <- mapM (local . open_close_rec aa) nts
; open_closes <- mapM (local . open_close aa) nts
; open_inj_recs <- mapM (local . open_inj_rec aa) nts
; open_injs <- mapM (local . open_inj aa) nts
; return $ printf "Ltac %s ::= auto with %s %s; tauto.\n\
\Ltac %s ::= fail.\n\
\\n"
defaultAuto hintDb bruteDb
defaultAutoRewr ++
concat close_inj_recs ++
concat close_injs ++
concat close_open_recs ++
concat close_opens ++
concat open_close_recs ++
concat open_closes ++
concat open_inj_recs ++
concat open_injs ++ "\n"
}
{- | @close_rec k x e1 = close_rec k x e2@ implies @e1 = e2@. -}
close_inj_rec :: ASTAnalysis -> [NtRoot] -> M String
close_inj_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = mutPfStart Prop types ++
"intros; match goal with\n\
\ | |- _ = ?term => destruct term\n\
\ end;\n" ++
defaultSimp ++ printf "; eauto with %s." hintDb
; mutualLemmaText2 Immediate NoRewrite Hide [hintDb] Prop names thms (repeat proof)
}
where
name aa nt1 _ mv2 =
do { close_fn <- closeRecName aa nt1 mv2
; return $ close_fn ++ "_inj"
}
thm aa nt1 _ mv2 =
do { close_fn <- closeRecName aa nt1 mv2
; e1 <- newName nt1
; e2 <- newName nt1
; x <- newName mv2
; k <- newName bvarRoot
; return $ printf "forall %s %s %s %s,\n\
\ %s %s %s %s = %s %s %s %s ->\n\
\ %s = %s"
e1 e2 x k
close_fn k x e1 close_fn k x e2
e1 e2
}
{- | @close x e1 = close x e2@ implies @e1 = e2@. -}
close_inj :: ASTAnalysis -> [NtRoot] -> M String
close_inj aaa nt1s =
do { gens <- processNt1Nt2Mv2 aaa nt1s gen
; names <- processNt1Nt2Mv2 aaa nt1s name
; lemmaText2 Immediate NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 =
do { close_fn <- closeName aa nt1 mv2
; return $ close_fn ++ "_inj"
}
gen aa nt1 _ mv2 =
do { close_fn <- closeName aa nt1 mv2
; e1 <- newName nt1
; e2 <- newName nt1
; x <- newName mv2
; let stmt = printf "forall %s %s %s,\n\
\ %s %s %s = %s %s %s ->\n\
\ %s = %s"
e1 e2 x
close_fn x e1 close_fn x e2
e1 e2
; let proof = printf "unfold %s; eauto with %s." close_fn hintDb
; return (stmt, proof)
}
{- | @close_rec k x (open_rec k x e) = e@ when @x `notin` fv e@. -}
close_open_rec :: ASTAnalysis -> [NtRoot] -> M String
close_open_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve Rewrite Hide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 =
do { close_fn <- closeRecName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2
; return $ close_fn ++ "_" ++ open_fn
}
thm aa nt1 nt2 mv2 =
do { close_fn <- closeRecName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; e <- newName nt1
; x <- newName mv2
; k <- newName bvarRoot
; constr <- getFreeVarConstr aa nt2 mv2
; return $ printf "forall %s %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s %s (%s %s (%s %s) %s) = %s"
e x k
x mvSetNotin fv_fn e
close_fn k x open_fn k (toName constr) x e e
}
{- | @close x (open x e) = e@ when @x `notin` fv e@. -}
close_open :: ASTAnalysis -> [NtRoot] -> M String
close_open aaa nt1s =
do { gens <- processNt1Nt2Mv2 aaa nt1s gen
; names <- processNt1Nt2Mv2 aaa nt1s name
; lemmaText2 Resolve Rewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 =
do { close_fn <- closeName aa nt1 mv2
; open_fn <- openName aa nt1 mv2
; return $ close_fn ++ "_" ++ open_fn
}
gen aa nt1 nt2 mv2 =
do { close_fn <- closeName aa nt1 mv2
; open_fn <- openName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; e <- newName nt1
; x <- newName mv2
; constr <- getFreeVarConstr aa nt2 mv2
-- ORDER TO OPEN
; let stmt = printf "forall %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s (%s %s (%s %s)) = %s"
e x
x mvSetNotin fv_fn e
close_fn x open_fn e (toName constr) x e
; let proof = printf "unfold %s; unfold %s; %s." close_fn open_fn defaultSimp
; return (stmt, proof)
}
{- | @open_rec k x (close_rec k x e) = e@ -}
open_close_rec :: ASTAnalysis -> [NtRoot] -> M String
open_close_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve Rewrite Hide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 =
do { close_fn <- closeRecName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2
; return $ open_fn ++ "_" ++ close_fn
}
thm aa nt1 nt2 mv2 =
do { k <- newName bvarRoot
; x <- newName mv2
; e <- newName nt1
; close_fn <- closeRecName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2
; constr <- getFreeVarConstr aa nt2 mv2
; return $ printf
"forall %s %s %s,\n\
\ %s %s (%s %s) (%s %s %s %s) = %s"
e x k
open_fn k (toName constr) x close_fn k x e e
}
{- | @open x (close x e) = e@ -}
open_close :: ASTAnalysis -> [NtRoot] -> M String
open_close aaa nt1s =
do { gens <- processNt1Nt2Mv2 aaa nt1s gen
; names <- processNt1Nt2Mv2 aaa nt1s name
; lemmaText2 Resolve Rewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 =
do { close_fn <- closeName aa nt1 mv2
; open_fn <- openName aa nt1 mv2
; return $ open_fn ++ "_" ++ close_fn
}
gen aa nt1 nt2 mv2 =
do { x <- newName mv2
; e <- newName nt1
; close_fn <- closeName aa nt1 mv2
; open_fn <- openName aa nt1 mv2
; constr <- getFreeVarConstr aa nt2 mv2
-- ORDER TO OPEN
; let stmt = printf "forall %s %s,\n\
\ %s (%s %s %s) (%s %s) = %s"
e x
open_fn close_fn x e (toName constr) x e
; let proof = printf "unfold %s; unfold %s; %s."
close_fn open_fn defaultSimp
; return (stmt, proof)
}
{- | @open_rec k x e1 = open_rec k x e2@ implies @e1 = e2@ when
@x `notin` fv e1 `union` fv e2@. -}
open_inj_rec :: ASTAnalysis -> [NtRoot] -> M String
open_inj_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = mutPfStart Prop types ++
"intros; match goal with\n\
\ | |- _ = ?term => destruct term\n\
\ end;\n" ++
printf "%s; eauto with %s." defaultSimp hintDb
; mutualLemmaText2 Immediate NoRewrite Hide [hintDb] Prop names thms (repeat proof)
}
where
name aa nt1 _ mv2 =
do { open_fn <- openRecName aa nt1 mv2
; return $ open_fn ++ "_inj"
}
thm aa nt1 nt2 mv2 =
do { e2 <- newName nt1
; e1 <- newName nt1
; k <- newName bvarRoot
; x <- newName mv2
; open_fn <- openRecName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; constr <- getFreeVarConstr aa nt2 mv2
; return $ printf "forall %s %s %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s %s %s ->\n\
\ %s %s (%s %s) %s = %s %s (%s %s) %s ->\n\
\ %s = %s"
e1 e2 x k
x mvSetNotin fv_fn e1
x mvSetNotin fv_fn e2
open_fn k (toName constr) x e1 open_fn k (toName constr) x e2
e1 e2
}
{- | @open e1 x = open e2 x@ implies @e1 = e2@ when
@x `notin` fv e1 `union` fv e2@. -}
open_inj :: ASTAnalysis -> [NtRoot] -> M String
open_inj aaa nt1s =
do { gens <- processNt1Nt2Mv2 aaa nt1s gen
; names <- processNt1Nt2Mv2 aaa nt1s name
; lemmaText2 Immediate NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 =
do { open_fn <- openName aa nt1 mv2
; return $ open_fn ++ "_inj"
}
gen aa nt1 nt2 mv2 =
do { e2 <- newName nt1
; e1 <- newName nt1
; x <- newName mv2
; open_fn <- openName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; constr <- getFreeVarConstr aa nt2 mv2
-- ORDER TO OPEN
; let stmt = printf"forall %s %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s %s %s ->\n\
\ %s %s (%s %s) = %s %s (%s %s) ->\n\
\ %s = %s"
e1 e2 x
x mvSetNotin fv_fn e1
x mvSetNotin fv_fn e2
open_fn e1 (toName constr) x open_fn e2 (toName constr) x
e1 e2
; let proof = printf "unfold %s; eauto with %s." open_fn hintDb
; return (stmt, proof)
}
|
plclub/lngen
|
src/CoqLNOutputThmOpenClose.hs
|
mit
| 12,036
| 0
| 17
| 5,501
| 2,836
| 1,392
| 1,444
| 210
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
module Goolosh.Game.State where
import Prelude(Show(..),Eq(..),Ord(..),Int)
import qualified Data.Map as M
import qualified Data.Sequence as S
import Data.Sequence((|>))
import Goolosh.Geom.Transform
data PlayerState
= Halted
| PlayerDeath
| Invincible
| Normal
deriving (Show,Eq,Ord)
data SceneState
= LevelStart
| LevelEnd
| GameDeath
| Transition
deriving (Show,Eq,Ord)
data MobState
= MobMoving
| MobDeath
| Hiding
| MobStill
| Revealing
deriving (Show,Eq,Ord)
data TileState
= Immutable
| Ivisible
| Visible
| Breaking
| Destroyed
deriving (Show,Eq,Ord)
data ItemState
= Spawnable
| ItemStill
| ItemMoving
| Consumed
deriving (Show,Eq,Ord)
data MusicState
= OneTrack
| Silence
| LevelLoop
| TemporaryTrack
deriving (Show,Eq,Ord)
data MobExtra
= ExtraFire
| ExtraWater
data GamePlayer = GamePlayer
{ playerPosition :: GV2D
, playerState :: PlayerState
}
data GameMob = GameMob
{ mobPosition :: GV2D
, mobState :: MobState
, mobExtras :: S.Seq MobExtra
}
data GameTile = GameTile
{ tilePosition :: GV2D
, tileState :: TileState
}
data GameState = GameState
{ gamePlayer :: GamePlayer
, gameMobs :: S.Seq GameMob
, gameTiles :: S.Seq GameTile
}
dummyState :: GameState
dummyState = GameState
{ gamePlayer = GamePlayer
{ playerPosition = make2DPoint 1 1
, playerState = Normal
}
, gameMobs = S.empty
|> GameMob
{ mobPosition = make2DPoint 5 5
, mobState = MobStill
, mobExtras = S.empty
}
, gameTiles = S.empty
|> GameTile
{ tilePosition = make2DPoint 0 6
, tileState = Immutable
}
|> GameTile
{ tilePosition = make2DPoint 1 6
, tileState = Immutable
}
|> GameTile
{ tilePosition = make2DPoint 2 6
, tileState = Immutable
}
|> GameTile
{ tilePosition = make2DPoint 3 6
, tileState = Immutable
}
|> GameTile
{ tilePosition = make2DPoint 4 6
, tileState = Immutable
}
|> GameTile
{ tilePosition = make2DPoint 5 6
, tileState = Immutable
}
|> GameTile
{ tilePosition = make2DPoint 6 6
, tileState = Immutable
}
}
--
|
LeviSchuck/Goolosh
|
src/Goolosh/Game/State.hs
|
mit
| 2,560
| 0
| 16
| 918
| 630
| 376
| 254
| 94
| 1
|
-- |
-- Module: Math.NumberTheory.GCD
-- Copyright: (c) 2011 Daniel Fischer
-- Licence: MIT
-- Maintainer: Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability: Provisional
-- Portability: Non-portable (GHC extensions)
--
-- This module exports GCD and coprimality test using the binary gcd algorithm
-- and GCD with the extended Euclidean algorithm.
--
-- Efficiently counting the number of trailing zeros, the binary gcd algorithm
-- can perform considerably faster than the Euclidean algorithm on average.
-- For 'Int', GHC has a rewrite rule to use GMP's fast gcd, depending on
-- hardware and\/or GMP version, that can be faster or slower than the binary
-- algorithm (on my 32-bit box, binary is faster, on my 64-bit box, GMP).
-- For 'Word' and the sized @IntN\/WordN@ types, there is no rewrite rule (yet)
-- in GHC, and the binary algorithm performs consistently (so far as my tests go)
-- much better (if this module's rewrite rules fire).
--
-- When using this module, always compile with optimisations turned on to
-- benefit from GHC's primops and the rewrite rules.
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
module Math.NumberTheory.GCD
( binaryGCD
, extendedGCD
, coprime
, splitIntoCoprimes
) where
import Data.Bits
import GHC.Word
import GHC.Int
import Math.NumberTheory.GCD.LowLevel
import Math.NumberTheory.Utils
#include "MachDeps.h"
{-# RULES
"binaryGCD/Int" binaryGCD = gcdInt
"binaryGCD/Word" binaryGCD = gcdWord
"binaryGCD/Int8" binaryGCD = gi8
"binaryGCD/Int16" binaryGCD = gi16
"binaryGCD/Int32" binaryGCD = gi32
"binaryGCD/Word8" binaryGCD = gw8
"binaryGCD/Word16" binaryGCD = gw16
"binaryGCD/Word32" binaryGCD = gw32
#-}
#if WORD_SIZE_IN_BITS == 64
gi64 :: Int64 -> Int64 -> Int64
gi64 (I64# x#) (I64# y#) = I64# (gcdInt# x# y#)
gw64 :: Word64 -> Word64 -> Word64
gw64 (W64# x#) (W64# y#) = W64# (gcdWord# x# y#)
{-# RULES
"binaryGCD/Int64" binaryGCD = gi64
"binaryGCD/Word64" binaryGCD = gw64
#-}
#endif
{-# INLINE [1] binaryGCD #-}
-- | Calculate the greatest common divisor using the binary gcd algorithm.
-- Depending on type and hardware, that can be considerably faster than
-- @'Prelude.gcd'@ but it may also be significantly slower.
--
-- There are specialised functions for @'Int'@ and @'Word'@ and rewrite rules
-- for those and @IntN@ and @WordN@, @N <= WORD_SIZE_IN_BITS@, to use the
-- specialised variants. These types are worth benchmarking, others probably not.
--
-- It is very slow for 'Integer' (and probably every type except the abovementioned),
-- I recommend not using it for those.
--
-- Relies on twos complement or sign and magnitude representaion for signed types.
binaryGCD :: (Integral a, Bits a) => a -> a -> a
binaryGCD = binaryGCDImpl
#if WORD_SIZE_IN_BITS < 64
{-# SPECIALISE binaryGCDImpl :: Word64 -> Word64 -> Word64,
Int64 -> Int64 -> Int64 #-}
#endif
{-# SPECIALISE binaryGCDImpl :: Integer -> Integer -> Integer #-}
binaryGCDImpl :: (Integral a, Bits a) => a -> a -> a
binaryGCDImpl a 0 = abs a
binaryGCDImpl 0 b = abs b
binaryGCDImpl a b =
case shiftToOddCount a' of
(!za, !oa) ->
case shiftToOddCount b' of
(!zb, !ob) -> gcdOdd (abs oa) (abs ob) `shiftL` min za zb
where
a' = abs a
b' = abs b
{-# SPECIALISE extendedGCD :: Int -> Int -> (Int, Int, Int),
Word -> Word -> (Word, Word, Word),
Integer -> Integer -> (Integer, Integer, Integer)
#-}
-- | Calculate the greatest common divisor of two numbers and coefficients
-- for the linear combination.
--
-- For signed types satisfies:
--
-- > case extendedGCD a b of
-- > (d, u, v) -> u*a + v*b == d
-- > && d == gcd a b
--
-- For unsigned and bounded types the property above holds, but since @u@ and @v@ must also be unsigned,
-- the result may look weird. E. g., on 64-bit architecture
--
-- > extendedGCD (2 :: Word) (3 :: Word) == (1, 2^64-1, 1)
--
-- For unsigned and unbounded types (like 'Numeric.Natural.Natural') the result is undefined.
--
-- For signed types we also have
--
-- > abs u < abs b || abs b <= 1
-- >
-- > abs v < abs a || abs a <= 1
--
-- (except if one of @a@ and @b@ is 'minBound' of a signed type).
extendedGCD :: Integral a => a -> a -> (a, a, a)
extendedGCD a b = (d, u, v)
where
(d, x, y) = eGCD 0 1 1 0 (abs a) (abs b)
u | a < 0 = negate x
| otherwise = x
v | b < 0 = negate y
| otherwise = y
eGCD !n1 o1 !n2 o2 r s
| s == 0 = (r, o1, o2)
| otherwise = case r `quotRem` s of
(q, t) -> eGCD (o1 - q*n1) n1 (o2 - q*n2) n2 s t
{-# RULES
"coprime/Int" coprime = coprimeInt
"coprime/Word" coprime = coprimeWord
"coprime/Int8" coprime = ci8
"coprime/Int16" coprime = ci16
"coprime/Int32" coprime = ci32
"coprime/Word8" coprime = cw8
"coprime/Word16" coprime = cw16
"coprime/Word32" coprime = cw32
#-}
#if WORD_SIZE_IN_BITS == 64
ci64 :: Int64 -> Int64 -> Bool
ci64 (I64# x#) (I64# y#) = coprimeInt# x# y#
cw64 :: Word64 -> Word64 -> Bool
cw64 (W64# x#) (W64# y#) = coprimeWord# x# y#
{-# RULES
"coprime/Int64" coprime = ci64
"coprime/Word64" coprime = cw64
#-}
#endif
{-# INLINE [1] coprime #-}
-- | Test whether two numbers are coprime using an abbreviated binary gcd algorithm.
-- A little bit faster than checking @binaryGCD a b == 1@ if one of the arguments
-- is even, much faster if both are even.
--
-- The remarks about performance at 'binaryGCD' apply here too, use this function
-- only at the types with rewrite rules.
--
-- Relies on twos complement or sign and magnitude representaion for signed types.
coprime :: (Integral a, Bits a) => a -> a -> Bool
coprime = coprimeImpl
-- Separate implementation to give the rules a chance to fire by not inlining
-- before phase 1, and yet have a specialisation for the types without rules
#if WORD_SIZE_IN_BITS < 64
{-# SPECIALISE coprimeImpl :: Word64 -> Word64 -> Bool,
Int64 -> Int64 -> Bool #-}
#endif
{-# SPECIALISE coprimeImpl :: Integer -> Integer -> Bool #-}
coprimeImpl :: (Integral a, Bits a) => a -> a -> Bool
coprimeImpl a b =
(a' == 1 || b' == 1)
|| (a' /= 0 && b' /= 0 && ((a .|. b) .&. 1) == 1
&& gcdOdd (abs (shiftToOdd a')) (abs (shiftToOdd b')) == 1)
where
a' = abs a
b' = abs b
-- Auxiliaries
-- gcd of two odd numbers
{-# INLINE gcdOdd #-}
gcdOdd :: (Integral a, Bits a) => a -> a -> a
gcdOdd a b
| a == 1 || b == 1 = 1
| a < b = oddGCD b a
| a > b = oddGCD a b
| otherwise = a
{-# SPECIALISE oddGCD :: Integer -> Integer -> Integer #-}
#if WORD_SIZE_IN_BITS < 64
{-# SPECIALISE oddGCD :: Int64 -> Int64 -> Int64,
Word64 -> Word64 -> Word64
#-}
#endif
oddGCD :: (Integral a, Bits a) => a -> a -> a
oddGCD a b =
case shiftToOdd (a-b) of
1 -> 1
c | c < b -> oddGCD b c
| c > b -> oddGCD c b
| otherwise -> c
-------------------------------------------------------------------------------
-- Blech! Getting the rules to fire isn't easy. --
-------------------------------------------------------------------------------
gi8 :: Int8 -> Int8 -> Int8
gi8 (I8# x#) (I8# y#) = I8# (gcdInt# x# y#)
gi16 :: Int16 -> Int16 -> Int16
gi16 (I16# x#) (I16# y#) = I16# (gcdInt# x# y#)
gi32 :: Int32 -> Int32 -> Int32
gi32 (I32# x#) (I32# y#) = I32# (gcdInt# x# y#)
gw8 :: Word8 -> Word8 -> Word8
gw8 (W8# x#) (W8# y#) = W8# (gcdWord# x# y#)
gw16 :: Word16 -> Word16 -> Word16
gw16 (W16# x#) (W16# y#) = W16# (gcdWord# x# y#)
gw32 :: Word32 -> Word32 -> Word32
gw32 (W32# x#) (W32# y#) = W32# (gcdWord# x# y#)
ci8 :: Int8 -> Int8 -> Bool
ci8 (I8# x#) (I8# y#) = coprimeInt# x# y#
ci16 :: Int16 -> Int16 -> Bool
ci16 (I16# x#) (I16# y#) = coprimeInt# x# y#
ci32 :: Int32 -> Int32 -> Bool
ci32 (I32# x#) (I32# y#) = coprimeInt# x# y#
cw8 :: Word8 -> Word8 -> Bool
cw8 (W8# x#) (W8# y#) = coprimeWord# x# y#
cw16 :: Word16 -> Word16 -> Bool
cw16 (W16# x#) (W16# y#) = coprimeWord# x# y#
cw32 :: Word32 -> Word32 -> Bool
cw32 (W32# x#) (W32# y#) = coprimeWord# x# y#
-- | The input list is assumed to be a factorisation of some number
-- into a list of powers of (possibly, composite) non-zero factors. The output
-- list is a factorisation of the same number such that all factors
-- are coprime. Such transformation is crucial to continue factorisation
-- (lazily, in parallel or concurrent fashion) without
-- having to merge multiplicities of primes, which occurs more than in one
-- composite factor.
--
-- > > splitIntoCoprimes [(140, 1), (165, 1)]
-- > [(5,2),(28,1),(33,1)]
-- > > splitIntoCoprimes [(360, 1), (210, 1)]
-- > [(2,4),(3,3),(5,2),(7,1)]
splitIntoCoprimes :: (Integral a, Num b) => [(a, b)] -> [(a, b)]
splitIntoCoprimes = \case
[] -> []
((1, _) : rest) -> splitIntoCoprimes rest
((x, xm) : rest) -> case popSuchThat (\(r, _) -> gcd x r /= 1) rest of
Nothing -> (x, xm) : splitIntoCoprimes rest
Just ((y, ym), zs) -> let g = gcd x y in splitIntoCoprimes
((g, xm + ym) : (x `quot` g, xm) : (y `quot` g, ym) : zs)
popSuchThat :: (a -> Bool) -> [a] -> Maybe (a, [a])
popSuchThat predicate = go
where
go = \case
[] -> Nothing
(x : xs)
| predicate x -> Just (x, xs)
| otherwise -> fmap (fmap (x :)) (go xs)
|
cfredric/arithmoi
|
Math/NumberTheory/GCD.hs
|
mit
| 9,583
| 0
| 19
| 2,337
| 2,034
| 1,100
| 934
| 131
| 4
|
-- Number of trailing zeros of N!
-- http://www.codewars.com/kata/52f787eb172a8b4ae1000a34/
module Zeros where
zeros :: Int -> Int
zeros 0 = 0
zeros n = sum . tail . takeWhile (/=0) . iterate (`div` 5) $ n
|
gafiatulin/codewars
|
src/5 kyu/Zeros.hs
|
mit
| 208
| 0
| 9
| 38
| 63
| 36
| 27
| 4
| 1
|
import Data.List(foldl')
import Math.NumberTheory.Primes.Sieve (primes)
-- The result is given by mutliplying the highest exponent of each prime not
-- greater than the range upper bound
euler ubound = foldl' (*) 1 $ map (greatestFactor 1) $ takeWhile (<=ubound) primes
where
greatestFactor acc n
= let acc' = n*acc in
if ubound < acc' then acc else greatestFactor acc' n
main = do
print $ euler 10
print $ euler 20
|
dpieroux/euler
|
0/0005.hs
|
mit
| 451
| 1
| 9
| 106
| 140
| 70
| 70
| 9
| 2
|
module Handler.About where
import Import
getAboutR :: Handler Html
getAboutR = defaultLayout $(widgetFile "about")
-- getAboutR = error "Not yet implemented: getAboutR"
|
silky/super-reference
|
Handler/About.hs
|
mit
| 171
| 0
| 8
| 24
| 33
| 18
| 15
| 4
| 1
|
-- | Provides a monad transformer that has a local def table.
-- An instance of 'CM.MonadSymtab' and 'H.HasDefTable'
{-# language GeneralizedNewtypeDeriving,
UndecidableInstances,
StandaloneDeriving
#-}
module Centrinel.Control.Monad.LocalSymtab (
LocalSymtabT(..)
, evalLocalSymtabT
) where
import Control.Monad.Reader.Class
import Control.Monad.Writer.Class
import Control.Monad.State.Class
import Control.Monad.State.Strict (StateT (..), evalStateT)
import qualified Control.Monad.Trans.State.Strict as State
import Control.Monad.Trans (MonadTrans (..))
import Centrinel.Control.Monad.Class.RegionResult
import qualified Language.C.Analysis.DefTable as CDT
import qualified Language.C.Analysis.TravMonad as CM
-- TODO: move this to a separate file
newtype LocalSymtabT m a = LocalSymtabT { unLocalSymtabT :: StateT CDT.DefTable m a }
deriving (Functor, Applicative, Monad, MonadTrans)
deriving instance MonadReader r m => MonadReader r (LocalSymtabT m)
deriving instance MonadWriter w m => MonadWriter w (LocalSymtabT m)
deriving instance RegionResultMonad m => RegionResultMonad (LocalSymtabT m)
instance Monad m => CM.MonadSymtab (LocalSymtabT m) where
getDefTable = LocalSymtabT get
withDefTable f = LocalSymtabT $ do
x <- get
let ~(a, y) = f x
put y
return a
instance CM.MonadName m => CM.MonadName (LocalSymtabT m) where
genName = lift CM.genName
instance CM.MonadCError m => CM.MonadCError (LocalSymtabT m) where
throwTravError = lift . CM.throwTravError
catchTravError (LocalSymtabT c) handler = LocalSymtabT (State.liftCatch CM.catchTravError c (unLocalSymtabT . handler))
recordError = lift . CM.recordError
getErrors = lift CM.getErrors
-- | Note that global handlers will be invoked with a copy of the local DefTable in the global DefTable which
-- is then copied back into the local DefTable after the handlers return, and the global DefTable is restored.
instance CM.MonadTrav m => CM.MonadTrav (LocalSymtabT m) where
handleDecl evt = do
-- snapshot global def table
snapshotGlobal <- lift CM.getDefTable
lcl <- CM.getDefTable
-- set global def table to current local
final <- lift $ do
setDefTable lcl
CM.handleDecl evt -- XXX catch and restore?
CM.getDefTable
-- set local def table to final global
setDefTable final
-- restore global to the snapshot
lift (setDefTable snapshotGlobal)
setDefTable :: CM.MonadSymtab m => CDT.DefTable -> m ()
setDefTable t = CM.withDefTable (const ((), t))
evalLocalSymtabT :: Monad m => CDT.DefTable -> LocalSymtabT m a -> m a
evalLocalSymtabT st0 comp = evalStateT (unLocalSymtabT comp) st0
|
lambdageek/use-c
|
src/Centrinel/Control/Monad/LocalSymtab.hs
|
mit
| 2,663
| 0
| 13
| 460
| 658
| 350
| 308
| -1
| -1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE CPP #-}
module Database.Sql.Simple.PostgreSQL
( PostgreSQL(..)
, ConnectInfo(..)
, postgreSQL
, psql
, module Data.Default.Class
) where
import Control.Applicative
import Control.Monad
import qualified Data.Text.Encoding as T
import Data.Typeable
import Data.Word
import Database.Sql.Simple.Internal
import qualified Database.PostgreSQL.Simple as PSql
import qualified Database.PostgreSQL.Simple.ToRow as PSql
import qualified Database.PostgreSQL.Simple.FromRow as PSql
import qualified Database.PostgreSQL.Simple.ToField as PSql
import qualified Database.PostgreSQL.Simple.FromField as PSql
import qualified Database.PostgreSQL.Simple.Types as PSql
import Data.Default.Class
#if !MIN_VERSION_base(4,7,0)
import Data.Proxy
#endif
data PostgreSQL = PostgreSQL PSql.Connection
deriving Typeable
instance PSql.ToField a => PSql.ToRow (Only a) where
toRow (Only v) = PSql.toRow $ PSql.Only v
instance PSql.FromField a => PSql.FromRow (Only a) where
fromRow = Only . PSql.fromOnly <$> PSql.fromRow
instance (PSql.ToRow a, PSql.ToRow b) => PSql.ToRow (a :. b) where
toRow (a :. b) = PSql.toRow $ a PSql.:. b
instance (PSql.FromRow a, PSql.FromRow b) => PSql.FromRow (a :. b) where
fromRow = (\(a PSql.:. b) -> a :. b) <$> PSql.fromRow
instance Backend PostgreSQL where
data ConnectInfo PostgreSQL = ConnectInfo
{ connectHost :: String
, connectPort :: Word16
, connectUser :: String
, connectPassword :: String
, connectDatabase :: String
} deriving (Eq, Read, Show)
type ToRow PostgreSQL = PSql.ToRow
type FromRow PostgreSQL = PSql.FromRow
connect (ConnectInfo h p u w d) =
PostgreSQL <$> PSql.connect (PSql.ConnectInfo h p u w d)
close (PostgreSQL c) = PSql.close c
execute (PostgreSQL c) t q = void . Sql $ PSql.execute c (psqlQuery t) q
execute_ (PostgreSQL c) t = void . Sql $ PSql.execute_ c (psqlQuery t)
query (PostgreSQL c) t q = Sql $ PSql.query c (psqlQuery t) q
query_ (PostgreSQL c) t = Sql $ PSql.query_ c (psqlQuery t)
fold (PostgreSQL c) q = PSql.fold c (psqlQuery q)
fold_ (PostgreSQL c) q = PSql.fold_ c (psqlQuery q)
instance Transaction PostgreSQL where
begin (PostgreSQL c) = Sql $ PSql.begin c
commit (PostgreSQL c) = Sql $ PSql.commit c
rollback (PostgreSQL c) = Sql $ PSql.rollback c
instance Default (ConnectInfo PostgreSQL) where
def = ConnectInfo h p u w d
where
PSql.ConnectInfo h p u w d = PSql.defaultConnectInfo
psqlQuery :: Query -> PSql.Query
psqlQuery = PSql.Query . T.encodeUtf8 . getQuery (typeOf (undefined :: PostgreSQL))
postgreSQL :: Proxy '[PostgreSQL]
postgreSQL = Proxy
psql :: Proxy '[PostgreSQL]
psql = postgreSQL
|
philopon/sql-simple
|
sql-simple-postgresql/Database/Sql/Simple/PostgreSQL.hs
|
mit
| 2,994
| 0
| 10
| 624
| 958
| 524
| 434
| 69
| 1
|
-----------------------------------------------------------
-- |
-- copyright: (c) 2016-2017 Tao He
-- license: MIT
-- maintainer: sighingnow@gmail.com
--
-- Test suite for mxnet package.
--
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE TypeApplications #-}
import qualified Data.Vector.Storable as V
import Test.Tasty
import Test.Tasty.HUnit
import MXNet.Core.Base
main :: IO ()
main = mxListAllOpNames >> defaultMain mxnetTest
mxnetTest :: TestTree
mxnetTest = testGroup "MXNet Test Suite"
[ hmapTest
, ndarrayTest
, symbolTest
]
hmapTest :: TestTree
hmapTest = testGroup "HMap"
[ testCase "Get after add" $ do
let expected = 1
got = get @"a" (add @"a" (1 :: Int) nil)
assertEqual "get after add" expected got
]
ndarrayTest :: TestTree
ndarrayTest = testGroup "NDArray"
[ testCaseSteps "NDArray basic operation" $ \step -> do
step "preparing ndarray"
let sh = [2, 3, 4, 5]
p = product sh
arr <- array sh [1 .. fromIntegral $ product sh] :: IO (NDArray Float)
step "shape and size"
(d, sh') <- ndshape arr
assertEqual "dimension should coincide" 4 d
assertEqual "shape should coincide" sh sh'
s <- ndsize arr
assertEqual "size should coincide" p s
step "arithmetic operators"
b <- (arr + arr) .* 3 >>= (./ 2)
r <- V.sum <$> items b
let expected = 3 * (p * (p+1) `div` 2)
assertEqual "sum of elements should be as expected" expected (round r)
step "comparison with scalar"
b <- _Maximum' arr 1000
r <- V.sum <$> items b
let expected = 1000 * p
assertEqual "_Maximum' should set the whole ndarray" expected (round r)
, testCaseSteps "NDArray linear algebra" $ \step -> do
step "preparing ndarray"
a <- array [2, 3] [1 .. 6]
step "ndarray dot product"
b <- (a `dot`) =<< transpose a
expected1 <- array [2, 2] [14, 32, 32, 77] :: IO (NDArray Float)
assertEqual "a `dot` transpose a" expected1 b
c <- transpose a >>= (`dot` a)
expected2 <- array [3, 3] [17, 22, 27, 22, 29, 36, 27, 36, 45] :: IO (NDArray Float)
assertEqual "transpose a `dot` a" expected2 c
, testCaseSteps "NDArray activation" $ \step -> do
step "preparing ndarray"
a <- array [4] [-0.5, -0.1, 0.1, 0.5]
step "relu activation"
r <- activation a "relu"
expected <- array [4] [0.0, 0.0, 0.1, 0.5] :: IO (NDArray Float)
assertEqual "relu activation" expected r
step "sigmoid activation"
r <- activation a "sigmoid"
expected <- array [4] [0.37754068, 0.4750208, 0.52497917, 0.62245935] :: IO (NDArray Float)
assertEqual "sigmoid activation" expected r
step "softrelu activation"
r <- activation a "softrelu"
expected <- array [4] [0.47407699, 0.64439672, 0.74439669, 0.97407699] :: IO (NDArray Float)
assertEqual "softrelu activation" expected r
step "tanh activation"
r <- activation a "tanh"
expected <- array [4] [-0.46211717, -0.099667996, 0.099667996, 0.46211717] :: IO (NDArray Float)
assertEqual "tanh activation" expected r
step "softmax activation"
r <- softmaxActivation a
expected <- array [4] [0.1422025, 0.21214119, 0.25910985, 0.38654646] :: IO (NDArray Float)
assertEqual "softmax activation" expected r
step "leakyReLU activation" -- for leakyReLU, input must be a multiple dimensions ndarray.
a' <- array [1, 4] [-0.5, -0.1, 0.1, 0.5]
r <- leakyReLU a' "leaky"
expected <- array [1, 4] [-0.125, -0.025, 0.1, 0.5] :: IO (NDArray Float)
assertEqual "leakyReLU activation" expected r
]
symbolTest :: TestTree
symbolTest = testGroup "Symbol"
[ testCaseSteps "Symbol basic operation" $ \step -> do
step "preparing symbol"
a <- variable "a" :: IO (Symbol Float)
step "get name"
a' <- getName a
assertEqual "get symbol name" "a" a'
, testCaseSteps "Symbol bind ndarray data" $ \step -> do
step "preparing symbol and ndarray"
a <- variable "a" :: IO (Symbol Float)
b <- variable "b" :: IO (Symbol Float)
arr1 <- array [2, 3] [1 .. 6]
arr2 <- array [2, 3] [5 .. 10]
step "bind and arithmetic operators"
c <- a + b .+ 2 >>= (./ 2)
expected <- array [2, 3] [4 .. 9]
exec <- bind c contextCPU [ ("a", arr1)
, ("b", arr2) ]
forward exec False
[r] <- getOutputs exec
assertEqual "bind and arithmetics with scalar" expected r
step "bind and linear algebra"
c <- (a `dot`) =<< transpose b
expected <- array [2, 2] [38, 56, 92, 137]
exec <- bind c contextCPU [ ("a", arr1)
, ("b", arr2) ]
forward exec False
[r] <- getOutputs exec
assertEqual "bind and a `dot` transpose b" expected r
c <- transpose a >>= (`dot` b)
expected <- array [3, 3] [ 37, 42, 47
, 50, 57, 64
, 63, 72, 81 ]
exec <- bind c contextCPU [ ("a", arr1)
, ("b", arr2) ]
forward exec False
[r] <- getOutputs exec
assertEqual "bind and transpose a `dot` b" expected r
step "bind and activation"
c <- softmaxActivation a
expected <- array [2, 3] [ 0.09003057, 0.24472848, 0.66524094
, 0.09003057, 0.24472848, 0.66524094 ]
exec <- bind c contextCPU [ ("a", arr1) ]
forward exec False
[r] <- getOutputs exec
assertEqual "bind and softmax activation" expected r
c <- leakyReLU a "leaky"
expected <- array [2, 3] [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 ]
exec <- bind c contextCPU [ ("a", arr1) ]
forward exec False
[r] <- getOutputs exec
assertEqual "bind and leakyReLU activation" expected r
]
|
sighingnow/mxnet-haskell
|
mxnet/tests/mxnet-test.hs
|
mit
| 6,273
| 1
| 18
| 2,053
| 1,978
| 987
| 991
| 135
| 1
|
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
sampleBytes :: B.ByteString
sampleBytes = "Hello!" -- OverloadedStrings work with any string type!
bcInt :: B.ByteString
bcInt = "6"
convertToString :: B.ByteString -> String
convertToString bytes = BC.unpack bytes
convertToInt :: B.ByteString -> Int
convertToInt = read . convertToString
|
raventid/coursera_learning
|
haskell/will_kurt/25_bytestring_worksheet.hs
|
mit
| 412
| 0
| 7
| 58
| 94
| 53
| 41
| 11
| 1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
module Letter.Core where
import qualified Data.Map as M
import Control.Applicative ((<|>))
import Data.Maybe
import Control.Error
import Control.Monad.IO.Class
import Control.Monad.Trans
type LetterResult = ExceptT String IO
addGlobals (Env !fs !gs) !vars = Env fs (M.union (M.fromList vars) gs)
addFuns (Env !fs !gs) !funs = Env (M.union (M.fromList funs) fs) gs
addFun (Env !fs !gs) id f = Env (M.insert id f fs) gs
addGlobal (Env !fs !gs) id e = Env fs (M.insert id e gs)
findGlobal (Env !_ !gs) id = M.lookup id gs
findFun (Env !fs !_) id = M.lookup id fs
data Exp = NExp !Integer
| Var !String
| Let !String !Exp
| FunCall !String ![Exp]
deriving (Show, Eq)
data Env = Env
{ functions :: M.Map String FunDef
, globals :: M.Map String Exp
} deriving Show
data FunDef = UserFun ![String] !Exp
| BuiltinFun (Maybe Int) (Env -> [Exp] -> LetterResult Exp)
instance Show FunDef where
show (UserFun args e) = "<UserFun:" ++ show (length args) ++ ">"
show (BuiltinFun a f) = "<BuiltinFun:" ++ showArity a ++ ">"
where showArity Nothing = "∞"
showArity (Just a) = show a
call :: Env -> String -> FunDef -> [Exp] -> LetterResult Exp
call env n (BuiltinFun Nothing f) !args = f env args
call env n (BuiltinFun (Just arity) f) !args
| length args == arity = f env args
| otherwise = argsError n arity (length args)
call env n (UserFun !ns !e) !args
| length args == length ns = do
vals <- mapM (reduce env) args
let formals = zip ns vals
reduce (addGlobals env formals) e
| otherwise = argsError n (length ns) (length args)
argsError :: String -> Int -> Int -> LetterResult Exp
argsError id f a = throwE $
"Invalid number of arguments to function \""
++ id ++ "\". Expected " ++ show f
++ ", got " ++ show a ++ "."
eval :: Env -> Exp -> LetterResult Integer
eval _ (NExp n) = return n
eval env e = reduce env e >>= eval env
reduce :: Env -> Exp -> LetterResult Exp
reduce env n@(NExp _) = liftIO $ return n
reduce env (Var !id) =
case findGlobal env id of
Nothing -> throwE $ "Use of undeclared identifier \"" ++ id ++ "\""
(Just e) -> reduce env e
reduce env (FunCall !id !args) =
case findFun env id of
Nothing -> throwE $ "Use of undeclared function \"" ++ id ++ "\""
(Just f) -> call env id f args
|
harlanhaskins/Letter
|
Haskell/src/Letter/Core.hs
|
mit
| 2,540
| 0
| 11
| 708
| 1,044
| 506
| 538
| 77
| 3
|
module Solar.Dial.Wait where
import System.Timeout
import Control.Concurrent
import Control.Concurrent.STM
import Data.Maybe
type WaitOn = MVar ()
sleepOn :: ()
=> WaitOn -- ^ Waiting variable
-> Int -- ^ Time to sleep in microseconds
-> IO () -- ^ Blocking action
sleepOn w i = do
_ <- tryTakeMVar w -- Clear the state
_ <- timeout i $ takeMVar w
return ()
-- | Does similar to compare and swap
sleepOnSTM :: (Eq a)
=> Int -- ^ Time to sleep in microseconds
-> a -- ^ Original
-> TVar b -- ^ Some structure
-> (TVar b -> STM a)
-> IO ()
sleepOnSTM i original s f = do
_ <- sleepOnSTM' i original s f
return ()
sleepOnSTM' :: (Eq a)
=> Int -- ^ Time to sleep in microseconds
-> a -- ^ Original
-> TVar b -- ^ Some structure
-> (TVar b -> STM a)
-> IO Bool
sleepOnSTM' i original s f = do
timed <- timeout i $ atomically $ do
current <- f s
check $ current /= original
-- Only let the transaction pass through
-- if things HAVE changed!
return $ isJust timed
|
Cordite-Studios/solar-dial
|
Solar/Dial/Wait.hs
|
mit
| 1,168
| 0
| 12
| 405
| 320
| 162
| 158
| 34
| 1
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.MessageEvent
(js_initMessageEvent, initMessageEvent, js_webkitInitMessageEvent,
webkitInitMessageEvent, js_getOrigin, getOrigin, js_getLastEventId,
getLastEventId, js_getSource, getSource, js_getData, getData,
js_getPorts, getPorts, MessageEvent, castToMessageEvent,
gTypeMessageEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"$1[\"initMessageEvent\"]($2, $3,\n$4, $5, $6, $7, $8, $9)"
js_initMessageEvent ::
MessageEvent ->
JSString ->
Bool ->
Bool ->
JSVal ->
JSString -> JSString -> Nullable Window -> Nullable Array -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent.initMessageEvent Mozilla MessageEvent.initMessageEvent documentation>
initMessageEvent ::
(MonadIO m, ToJSString typeArg, ToJSString originArg,
ToJSString lastEventIdArg, IsArray messagePorts) =>
MessageEvent ->
typeArg ->
Bool ->
Bool ->
JSVal ->
originArg ->
lastEventIdArg -> Maybe Window -> Maybe messagePorts -> m ()
initMessageEvent self typeArg canBubbleArg cancelableArg dataArg
originArg lastEventIdArg sourceArg messagePorts
= liftIO
(js_initMessageEvent (self) (toJSString typeArg) canBubbleArg
cancelableArg
dataArg
(toJSString originArg)
(toJSString lastEventIdArg)
(maybeToNullable sourceArg)
(maybeToNullable (fmap toArray messagePorts)))
foreign import javascript unsafe
"$1[\"webkitInitMessageEvent\"]($2,\n$3, $4, $5, $6, $7, $8, $9)"
js_webkitInitMessageEvent ::
MessageEvent ->
JSString ->
Bool ->
Bool ->
JSVal ->
JSString -> JSString -> Nullable Window -> Nullable Array -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent.webkitInitMessageEvent Mozilla MessageEvent.webkitInitMessageEvent documentation>
webkitInitMessageEvent ::
(MonadIO m, ToJSString typeArg, ToJSString originArg,
ToJSString lastEventIdArg, IsArray transferables) =>
MessageEvent ->
typeArg ->
Bool ->
Bool ->
JSVal ->
originArg ->
lastEventIdArg -> Maybe Window -> Maybe transferables -> m ()
webkitInitMessageEvent self typeArg canBubbleArg cancelableArg
dataArg originArg lastEventIdArg sourceArg transferables
= liftIO
(js_webkitInitMessageEvent (self) (toJSString typeArg) canBubbleArg
cancelableArg
dataArg
(toJSString originArg)
(toJSString lastEventIdArg)
(maybeToNullable sourceArg)
(maybeToNullable (fmap toArray transferables)))
foreign import javascript unsafe "$1[\"origin\"]" js_getOrigin ::
MessageEvent -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent.origin Mozilla MessageEvent.origin documentation>
getOrigin ::
(MonadIO m, FromJSString result) => MessageEvent -> m result
getOrigin self = liftIO (fromJSString <$> (js_getOrigin (self)))
foreign import javascript unsafe "$1[\"lastEventId\"]"
js_getLastEventId :: MessageEvent -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent.lastEventId Mozilla MessageEvent.lastEventId documentation>
getLastEventId ::
(MonadIO m, FromJSString result) => MessageEvent -> m result
getLastEventId self
= liftIO (fromJSString <$> (js_getLastEventId (self)))
foreign import javascript unsafe "$1[\"source\"]" js_getSource ::
MessageEvent -> IO (Nullable EventTarget)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent.source Mozilla MessageEvent.source documentation>
getSource :: (MonadIO m) => MessageEvent -> m (Maybe EventTarget)
getSource self = liftIO (nullableToMaybe <$> (js_getSource (self)))
foreign import javascript unsafe "$1[\"data\"]" js_getData ::
MessageEvent -> IO JSVal
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent.data Mozilla MessageEvent.data documentation>
getData :: (MonadIO m) => MessageEvent -> m JSVal
getData self = liftIO (js_getData (self))
foreign import javascript unsafe "$1[\"ports\"]" js_getPorts ::
MessageEvent -> IO JSVal
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent.ports Mozilla MessageEvent.ports documentation>
getPorts :: (MonadIO m) => MessageEvent -> m [Maybe MessagePort]
getPorts self
= liftIO ((js_getPorts (self)) >>= fromJSValUnchecked)
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MessageEvent.hs
|
mit
| 5,770
| 74
| 11
| 1,411
| 1,170
| 649
| 521
| 101
| 1
|
{-# LANGUAGE BangPatterns #-}
{-|
Copyright (c) 2014 Maciej Bendkowski
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-}
module SI where
import Memo
import Types
import CommonUtils
{-|
SI calculus (subset of CLI calculus)
-}
data Term = S | I
| App Term Term deriving (Eq)
{-|
String representation following common term notations, i.e.
outermost parentheses are omitted, application is binding to the left.
-}
instance Show Term where
show t = show' t "" where
show' :: Term -> ShowS
show' S = ("S" ++)
show' I = ("I" ++)
show' (App x p @ (App _ _)) = show' x . ("(" ++) . show' p . (")" ++)
show' (App x y) = show' x . show' y
{-|
Infinite binary tree of SI combinatorial classes, i.e.
lists of terms grouped by size.
-}
terms :: Tree [Term]
terms = fmap (terms' g) nats where
g :: Int -> [Term]
g n = idx terms n
terms' :: (Int -> [Term]) -> Int -> [Term]
terms' _ 0 = [S, I]
terms' f n = concat $ map f' $ partitions (n-1) where
f' :: (Int, Int) -> [Term]
f' (p, p') = [App t t' | t <- f p, t' <- f p']
partitions :: Int -> [(Int, Int)]
partitions k = [(x, y) | x <- [0..k], y <- [0..k], x + y == k]
{-|
Computes the number of terms of size n.
-}
termsOfSize :: Integer -> Integer
termsOfSize n = (2 ^ (n + 1)) * catalan n
{-|
Common measurable SI term functions inherited
from the Measurable typeclass.
-}
instance Measurable Term where
{-|
Number of applications in the term structure.
-}
size (App x y) = (size x) + (size y) + 1
size _ = 0
{-|
Retrieves the k-th combinatorial class in O(log k) time.
-}
ofSize k = idx terms k
{-|
Computes the relative density of terms of size k, satisfying
the predicate f in the overall terms of size k.
-}
density f k = (fromIntegral t) / (fromIntegral $ termsOfSize $ toInteger k) where
t = length . filter (\x -> x == True) $ map f $ ofSize k
{-|
Checks if the given term is a
primitive combinator or not.
-}
isCombinator :: Term -> Bool
isCombinator S = True
isCombinator I = True
isCombinator _ = False
{-|
Performs a single reduction step
to the given term if possible. Returns
a pair (reduct, performed reduction?)
-}
reduct :: Term -> (Term, Bool)
reduct (App I x) = (x, True)
reduct (App (App (App S x) y) z) = ((App (App x z) (App y z)), True)
reduct t' = (t', False)
{-|
Performs a single head position reduction step
to the given term if possible. Returns
(reduct, redex term, performed reduction?)
-}
headReduction :: Term -> (Term, Term, Bool)
headReduction t @ (App x y) = case reduct t of
(r, True) -> (r, t, True)
(_, False) -> case headReduction x of
(r, _, True) -> (App r y, x, True)
(_, _, False) -> case headReduction y of
(r, _, True) -> (App x r, y, True)
(_, _, False) -> (t, t, False)
headReduction x = (x, x, False)
{-|
Finds the normal form a given term if possible.
Note, this function may not terminate.
-}
normalForm :: Term -> Term
normalForm t = case headReduction t of
(r, _, True) -> normalForm r
(_, _, False) -> t
{-|
Returns a (possibly infinite) list of intermediate
reduction terms resulting from applying the head
position reduction.
-}
normalFormReductionList :: Term -> [Term]
normalFormReductionList t = case headReduction t of
(r, _, True) -> r : normalFormReductionList r
(_, _, False) -> [t]
{-|
Returns a list of the first k intermediate
reduction terms resulting from applying the head
position reduction.
-}
boundNormalForm :: Int -> Term -> [Term]
boundNormalForm k t = take k $ normalFormReductionList t
{-|
Returns a (possibly infinite) list of intermediate
reduction redexes resulting from applying the head
position reduction.
-}
normalFormRedexList :: Term -> [Term]
normalFormRedexList t = case headReduction t of
(r, x, True) -> x : normalFormRedexList r
(_, x, False) -> [x]
{-|
Returns a list of the first k intermediate
reduction redexes resulting from applying the head
position reduction.
-}
boundNormalFormRedex :: Int -> Term -> [Term]
boundNormalFormRedex k t = take k $ normalFormRedexList t
{-|
Checks if e is a subterm of t.
-}
isSubterm :: Term -> Term -> Bool
isSubterm e t @ (App t' t'')
| e == t = True
| otherwise = (left || right) where
left = e `isSubterm` t'
right = e `isSubterm` t''
isSubterm e t = e == t
{-|
Checks if the given term has a redex.
-}
hasRedex :: Term -> Bool
hasRedex I = False
hasRedex S = False
hasRedex (App I _) = True
hasRedex (App (App (App S _) _) _) = True
hasRedex (App t' t'') = hasRedex t' || hasRedex t''
{-|
Checks if the given term is in normal form.
-}
isInNormalForm :: Term -> Bool
isInNormalForm t = not $ hasRedex t
{-|
Checks if t reduces to r in finite reduction steps.
Note, that this function may not terminate.
-}
reducesTo :: Term -> Term -> Bool
reducesTo t r = any (r ==) $ normalFormReductionList t
|
maciej-bendkowski/LCCLUtils
|
src/SI.hs
|
mit
| 6,960
| 17
| 18
| 2,376
| 1,477
| 801
| 676
| 83
| 4
|
{-# LANGUAGE RecordWildCards #-}
module UART.Rx (rxInit, rxRun) where
import CLaSH.Prelude
import Control.Lens
import Control.Monad
import Control.Monad.Trans.State
import Data.Tuple
import Types
data RxState = RxState
{ _rx_done_tick :: Bool
, _rx_dout :: Byte -- byte register (same as _b_reg in Tx)
, _rx_state :: Unsigned 2
, _s_reg :: Unsigned 4 -- sampling counter
, _n_reg :: Unsigned 3 -- number of bits received
}
makeLenses ''RxState
rxInit :: RxState
rxInit = RxState False 0 0 0 0
rxRun :: RxState -> (Bit, Bit) -> (RxState, (Byte, Bool))
rxRun s@(RxState {..}) (rx, s_tick) = swap $ flip runState s $ do
rx_done_tick .= False
case _rx_state of
0 -> idle
1 -> start
2 -> rdata
3 -> stop
done_tick <- use rx_done_tick
return (_rx_dout, done_tick)
where
idle = when (rx == 0) $ do
rx_state .= 1
s_reg .= 0
start = when (s_tick == 1) $
if _s_reg == 7 then do
rx_state .= 2
s_reg .= 0
n_reg .= 0
else
s_reg += 1
rdata = when (s_tick == 1) $
if _s_reg == 15 then do
s_reg .= 0
rx_dout %= replaceBit _n_reg rx
if _n_reg == 7 then -- 8 bits
rx_state .= 3
else
n_reg += 1
else
s_reg += 1
stop = when (s_tick == 1) $
if _s_reg == 15 then do
rx_state .= 0
rx_done_tick .= True
else
s_reg += 1
|
aufheben/Y86
|
SEQ/UART/Rx.hs
|
mit
| 1,581
| 0
| 12
| 616
| 475
| 253
| 222
| -1
| -1
|
{-# LANGUAGE TemplateHaskell #-}
module McCarthy91 where
import Test.QuickCheck
import Test.QuickCheck.All
--------------------------------------------------------------------------------
m :: Integer -> Integer
m n | n > 100 = n-10
| otherwise = m (m (n+11))
--------------------------------------------------------------------------------
prop_M1 n =
n <= 100 ==> m n == 91
prop_M2 n =
n >= 101 ==> m n == n-10
--------------------------------------------------------------------------------
return []
testAll = $(quickCheckAll)
--------------------------------------------------------------------------------
|
koengit/induction-examples
|
McCarthy91.hs
|
mit
| 632
| 0
| 10
| 81
| 143
| 74
| 69
| -1
| -1
|
module Qy.Room where
import Data.Aeson
import GHC.Generics hiding (from)
import Servant
import Control.Monad.Trans.Either
import Control.Monad.Reader
import Control.Applicative ((<$>), (<*>), empty)
import qualified Control.Applicative as A
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Control.Monad.Trans (lift)
import Control.Monad.IO.Class (liftIO)
import Database.Esqueleto
import qualified Database.Persist as P
import Qy.Types
import qualified Qy.Model as M
import Qy.Error (raiseHTTPError)
import Qy.Error.Room ( roomNotExists
, roomAlreadyExists
, roomNameNotMatchBody)
import Qy.Error.Auth (userNotExists)
import Qy.User (checkToken, Token)
type RoomAPI = "room" :> Capture "roomname" Text :> "join" :> Post '[JSON] RoomInfo -- join in
:<|> "room" :> Capture "roomname" Text :> "info" :> Get '[JSON] RoomInfo -- get room info
:<|> "room" :> Capture "roomname" Text :> ReqBody '[JSON] RoomReq :> Post '[JSON] RoomInfo -- update room info
:<|> "room" :> Capture "roomname" Text :> Delete '[JSON] RoomInfo -- delete room
:<|> "rooms" :> ReqBody '[JSON] RoomReq :> Post '[JSON] RoomInfo -- create new room
:<|> "rooms" :> QueryFlag "all" :> Get '[JSON] [RoomInfo] -- get all room info user joinded in
data RoomInfo = RoomInfo { name :: Text
, description :: Maybe Text
} deriving (Show, Generic)
instance ToJSON RoomInfo
data RoomReq = RoomReq Text (Maybe Text)
instance FromJSON RoomReq where
parseJSON (Object v) = RoomReq
<$> v .: "name"
<*> v .: "description"
roomServer :: Maybe Token -> ServerT RoomAPI AppM
roomServer mt = joinRoom mt
:<|> getRoomInfo mt
:<|> updateRoom mt
:<|> leaveRoom mt
:<|> createRoom mt
:<|> listRooms mt
getRoomInfo :: Maybe Token -> Text -> AppM RoomInfo
getRoomInfo mt rname = do
uname <- checkToken mt
maybeRoom <- M.runDb $ getBy $ M.UniqueRoom rname
case maybeRoom of
Nothing -> raiseHTTPError roomNotExists
Just (Entity _ room) -> return $ RoomInfo rname (M.roomDescription room)
joinRoom :: Maybe Token -> Text -> AppM RoomInfo
joinRoom mt rname = do
uname <- checkToken mt
maybeUser <- M.runDb $ getBy $ M.UniqueUser uname
maybeRoom <- M.runDb $ getBy $ M.UniqueRoom rname
case (maybeUser, maybeRoom) of
(Just (Entity uid _) , Just (Entity rid room))-> do
M.runDb $ insertBy $ M.UserRoom uid rid
return $ RoomInfo rname (M.roomDescription room)
(Nothing, _) -> raiseHTTPError userNotExists
(_, Nothing) -> raiseHTTPError roomNotExists
leaveRoom :: Maybe Token -> Text -> AppM RoomInfo
leaveRoom mt rname = do
uname <- checkToken mt
maybeUser <- M.runDb $ getBy $ M.UniqueUser uname
maybeRoom <- M.runDb $ getBy $ M.UniqueRoom rname
case (maybeUser, maybeRoom) of
(Just (Entity uid _) , Just (Entity rid room))-> do
M.runDb $ deleteBy $ M.UniqueUserRoom uid rid
return $ RoomInfo rname (M.roomDescription room)
(Nothing, _) -> raiseHTTPError userNotExists
(_, Nothing) -> raiseHTTPError roomNotExists
createRoom :: Maybe Token -> RoomReq -> AppM RoomInfo
createRoom mt (RoomReq name desc) = do
uname <- checkToken mt
maybeUser <- M.runDb $ getBy $ M.UniqueUser uname
case maybeUser of
Just (Entity uid _) -> do
maybeRoom <- M.runDb $ insertBy $ M.Room name desc uid
case maybeRoom of
Left _ -> raiseHTTPError roomAlreadyExists
Right _ -> return $ RoomInfo name desc
Nothing -> raiseHTTPError userNotExists
updateRoom :: Maybe Token -> Text -> RoomReq -> AppM RoomInfo
updateRoom mt rname (RoomReq name desc) = do
uname <- checkToken mt
if rname /= name
then raiseHTTPError roomNameNotMatchBody
else do
M.runDb $ P.updateWhere
[M.RoomName P.==. rname]
[M.RoomDescription P.=. desc]
return $ RoomInfo rname desc
listRooms :: Maybe Token -> Bool -> AppM [RoomInfo]
listRooms mt listAll = do
uname <- checkToken mt
rooms <- M.runDb $ select $
from $ \(u, re, r) -> do
where_ (if listAll
then (u^. M.UserId ==. re^. M.UserRoomUserId
&&. re^. M.UserRoomRoomId ==. r^. M.RoomId)
else (u^. M.UserId ==. re^. M.UserRoomUserId
&&. re^. M.UserRoomRoomId ==. r^. M.RoomId
&&. u ^. M.UserName ==. val uname))
return r
return $ map roomsToInfo rooms
where roomsToInfo (Entity _ room) = RoomInfo (M.roomName room) (M.roomDescription room)
|
realli/chatqy
|
src/Qy/Room.hs
|
mit
| 4,746
| 0
| 27
| 1,244
| 1,596
| 807
| 789
| -1
| -1
|
module Data.ListZipper where
import Control.Applicative(liftA3)
data Zipper a = Z [a] a [a]
left :: Zipper a -> Zipper a
left (Z [] c rs) = Z [] c rs
left (Z (l:ls) c rs) = Z ls l (c:rs)
right :: Zipper a -> Zipper a
right (Z ls c []) = Z ls c []
right (Z ls c (r:rs)) = Z (c:ls) r rs
instance Functor Zipper where
fmap f (Z xs y zs) = Z (map f xs) (f y) (map f zs)
instance Foldable Zipper where
foldr f w (Z xs y zs) = foldr f (f y (foldr f w zs)) $ reverse xs
instance Traversable Zipper where
traverse f (Z xs y zs) = liftA3 Z (traverse f xs) (f y) (traverse f zs)
|
rueshyna/sdl2-examples
|
src/Data/ListZipper.hs
|
mit
| 585
| 0
| 11
| 147
| 378
| 190
| 188
| 15
| 1
|
-- 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 3 of the License, or
-- (at your option) any later version.
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
-- Authors: Elvio Martinelli
-- Segio Candeas
module Main where
import Data.List
import Data.Char
import System.IO.Unsafe
import System.Random
-- Cria uma lista de listas que possuem todas as combinações possiveis de 4 elementos de 1 à 7 sem repetição
genLsts:: [[Int]]
genLsts = [[w, x, y, z] | w <- [1..7], x <- [1..7], y <- [1..7], z <- [1..7], w /= x, w /= y, w /= z, x /= y, x /= z, y /= z]
-- Função que pega uma combinação
getTheSecret :: Int -> [Int]
getTheSecret index = genLsts !! index
-- Função que retorna o numero de pinos que o usuario acertou nao importando se foi na posicao correta
nLstOcurrences :: [Int] -> [Int] -> Int
aux :: [Int] -> [Int] -> Int -> Int
nLstOcurrences lst lst2 = aux lst lst2 0
aux _ [] ac = ac
aux lst (a:x) ac
|elem a lst = aux lst x (ac + 1)
|otherwise = aux lst x ac
-- Função que retorna o numero de pinos que o usuario acertou importando se foi na posicao correta
nLstOcurrencesAtSamePos :: [Int] -> [Int] -> Int
aux2 :: [Int] -> [Int] -> [Int] -> Int -> Int
nLstOcurrencesAtSamePos lst lst2 = aux2 lst lst2 lst2 0
aux2 _ _ [] ac = ac
aux2 lst lst2 (a:x) ac
|elemIndices a lst == elemIndices a lst2 = aux2 lst lst2 x (ac + 1)
|otherwise = aux2 lst lst2 x ac
-- Retorna uma string com os pinos pretos, brancos e vazios, nao mostra na ordem que estao os pinos na senha correta
returnPins :: Int -> Int -> String
returnPins 0 0 = "vvvv"
returnPins blacks blacksPlusWhites = createString blacks 'p' ++
createString (blacksPlusWhites - blacks) 'b' ++
createString (4 - blacksPlusWhites) 'v'
-- Cria uma String com caracteres iguais
createString :: Int -> Char -> String
createString 0 _ = []
createString n _ |n < 0 = []
createString n s = s : createString (n - 1) s
-- Compara o segredo e a entrada do usuário. Retorna os pinos correspondentes
putPins :: [Int] -> [Int] -> String
putPins _ [] = []
putPins secret input
|input == secret = "pppp"
|otherwise = returnPins (nLstOcurrencesAtSamePos secret input) (nLstOcurrences secret input)
-- Tratamento de entrada
maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
[(x,"")] -> Just x
_ -> Nothing
-- Tratamento de entrada
getListFromString :: String -> Maybe [Int]
getListFromString str = maybeRead $ "[" ++ str ++ "]"
welcome :: String
welcome = "Let's play a game!"
instructions :: String
instructions = "Enter with a sequence of 4 distinct numbers from 1 to 7 (separated by comma). Let's try!"
formatError :: String
formatError = "Bad format. Good Bye."
loserMessage :: String
loserMessage = "You lose! :/"
winnerMessage :: String
winnerMessage = "You win! \\o/"
game :: [Int] -> IO ()
game ran = do
gameInput ran 10
-- Verifica se o usuario acertou a combinação ou não, e se não acertou mostra quantas tentativas faltam
gameTest :: [Int] -> [Int] -> Int -> IO ()
gameTest secret input count =
let pins = putPins secret input in
if count < 2 then
print loserMessage
else if pins == "pppp" then
print winnerMessage
else
do
print ("Try again! You have more "++ [intToDigit (count-1)] ++ " tries. Tip: "++ pins)
gameInput secret (count-1)
-- Tratamento de entrada
gameInput :: [Int] -> Int -> IO ()
gameInput rand count = do
input <- getLine
let maybeList = getListFromString input in
case maybeList of
Just l -> (gameTest rand l count)
Nothing -> error formatError
-- Função Principal
main :: IO ()
main = do
putStrLn welcome
putStrLn instructions
game (getTheSecret (unsafePerformIO (getStdRandom (randomR (0, length genLsts)))))
|
emartinelli/mastermind
|
src/Main.hs
|
gpl-2.0
| 5,026
| 0
| 19
| 1,664
| 1,186
| 617
| 569
| 78
| 3
|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
{-
Copyright (C) 2006-2014 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.LaTeX
Copyright : Copyright (C) 2006-2014 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' format into LaTeX.
-}
module Text.Pandoc.Writers.LaTeX ( writeLaTeX ) where
import Text.Pandoc.Definition
import Text.Pandoc.Walk
import Text.Pandoc.Shared
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Options
import Text.Pandoc.Templates
import Text.Printf ( printf )
import Network.URI ( isURI, unEscapeString )
import Data.List ( (\\), isSuffixOf, isInfixOf,
isPrefixOf, intercalate, intersperse )
import Data.Char ( toLower, isPunctuation, isAscii, isLetter, isDigit, ord )
import Data.Maybe ( fromMaybe )
import Control.Applicative ((<|>))
import Control.Monad.State
import Text.Pandoc.Pretty
import Text.Pandoc.Slides
import Text.Pandoc.Highlighting (highlight, styleToLaTeX,
formatLaTeXInline, formatLaTeXBlock,
toListingsLanguage)
data WriterState =
WriterState { stInNote :: Bool -- true if we're in a note
, stInQuote :: Bool -- true if in a blockquote
, stInMinipage :: Bool -- true if in minipage
, stNotes :: [Doc] -- notes in a minipage
, stOLLevel :: Int -- level of ordered list nesting
, stOptions :: WriterOptions -- writer options, so they don't have to be parameter
, stVerbInNote :: Bool -- true if document has verbatim text in note
, stTable :: Bool -- true if document has a table
, stStrikeout :: Bool -- true if document has strikeout
, stUrl :: Bool -- true if document has visible URL link
, stGraphics :: Bool -- true if document contains images
, stLHS :: Bool -- true if document has literate haskell code
, stBook :: Bool -- true if document uses book or memoir class
, stCsquotes :: Bool -- true if document uses csquotes
, stHighlighting :: Bool -- true if document has highlighted code
, stIncremental :: Bool -- true if beamer lists should be displayed bit by bit
, stInternalLinks :: [String] -- list of internal link targets
, stUsesEuro :: Bool -- true if euro symbol used
}
-- | Convert Pandoc to LaTeX.
writeLaTeX :: WriterOptions -> Pandoc -> String
writeLaTeX options document =
evalState (pandocToLaTeX options document) $
WriterState { stInNote = False, stInQuote = False,
stInMinipage = False, stNotes = [],
stOLLevel = 1, stOptions = options,
stVerbInNote = False,
stTable = False, stStrikeout = False,
stUrl = False, stGraphics = False,
stLHS = False, stBook = writerChapters options,
stCsquotes = False, stHighlighting = False,
stIncremental = writerIncremental options,
stInternalLinks = [], stUsesEuro = False }
pandocToLaTeX :: WriterOptions -> Pandoc -> State WriterState String
pandocToLaTeX options (Pandoc meta blocks) = do
-- Strip off final 'references' header if --natbib or --biblatex
let method = writerCiteMethod options
let blocks' = if method == Biblatex || method == Natbib
then case reverse blocks of
(Div (_,["references"],_) _):xs -> reverse xs
_ -> blocks
else blocks
-- see if there are internal links
let isInternalLink (Link _ ('#':xs,_)) = [xs]
isInternalLink _ = []
modify $ \s -> s{ stInternalLinks = query isInternalLink blocks' }
let template = writerTemplate options
-- set stBook depending on documentclass
let bookClasses = ["memoir","book","report","scrreprt","scrbook"]
case lookup "documentclass" (writerVariables options) of
Just x | x `elem` bookClasses -> modify $ \s -> s{stBook = True}
| otherwise -> return ()
Nothing | any (\x -> "\\documentclass" `isPrefixOf` x &&
(any (`isSuffixOf` x) bookClasses))
(lines template) -> modify $ \s -> s{stBook = True}
| otherwise -> return ()
-- check for \usepackage...{csquotes}; if present, we'll use
-- \enquote{...} for smart quotes:
when ("{csquotes}" `isInfixOf` template) $
modify $ \s -> s{stCsquotes = True}
let colwidth = if writerWrapText options
then Just $ writerColumns options
else Nothing
metadata <- metaToJSON options
(fmap (render colwidth) . blockListToLaTeX)
(fmap (render colwidth) . inlineListToLaTeX)
meta
let (blocks'', lastHeader) = if writerCiteMethod options == Citeproc then
(blocks', [])
else case last blocks' of
Header 1 _ il -> (init blocks', il)
_ -> (blocks', [])
blocks''' <- if writerBeamer options
then toSlides blocks''
else return blocks''
body <- mapM (elementToLaTeX options) $ hierarchicalize blocks'''
(biblioTitle :: String) <- liftM (render colwidth) $ inlineListToLaTeX lastHeader
let main = render colwidth $ vsep body
st <- get
titleMeta <- stringToLaTeX TextString $ stringify $ docTitle meta
authorsMeta <- mapM (stringToLaTeX TextString . stringify) $ docAuthors meta
let context = defField "toc" (writerTableOfContents options) $
defField "toc-depth" (show (writerTOCDepth options -
if stBook st
then 1
else 0)) $
defField "body" main $
defField "title-meta" titleMeta $
defField "author-meta" (intercalate "; " authorsMeta) $
defField "documentclass" (if writerBeamer options
then ("beamer" :: String)
else if stBook st
then "book"
else "article") $
defField "verbatim-in-note" (stVerbInNote st) $
defField "tables" (stTable st) $
defField "strikeout" (stStrikeout st) $
defField "url" (stUrl st) $
defField "numbersections" (writerNumberSections options) $
defField "lhs" (stLHS st) $
defField "graphics" (stGraphics st) $
defField "book-class" (stBook st) $
defField "euro" (stUsesEuro st) $
defField "listings" (writerListings options || stLHS st) $
defField "beamer" (writerBeamer options) $
defField "mainlang" (maybe "" (reverse . takeWhile (/=',') . reverse)
(lookup "lang" $ writerVariables options)) $
(if stHighlighting st
then defField "highlighting-macros" (styleToLaTeX
$ writerHighlightStyle options )
else id) $
(case writerCiteMethod options of
Natbib -> defField "biblio-title" biblioTitle .
defField "natbib" True
Biblatex -> defField "biblio-title" biblioTitle .
defField "biblatex" True
_ -> id) $
metadata
return $ if writerStandalone options
then renderTemplate' template context
else main
-- | Convert Elements to LaTeX
elementToLaTeX :: WriterOptions -> Element -> State WriterState Doc
elementToLaTeX _ (Blk block) = blockToLaTeX block
elementToLaTeX opts (Sec level _ (id',classes,_) title' elements) = do
header' <- sectionHeader ("unnumbered" `elem` classes) id' level title'
innerContents <- mapM (elementToLaTeX opts) elements
return $ vsep (header' : innerContents)
data StringContext = TextString
| URLString
| CodeString
deriving (Eq)
-- escape things as needed for LaTeX
stringToLaTeX :: StringContext -> String -> State WriterState String
stringToLaTeX _ [] = return ""
stringToLaTeX ctx (x:xs) = do
opts <- gets stOptions
rest <- stringToLaTeX ctx xs
let ligatures = writerTeXLigatures opts && ctx == TextString
let isUrl = ctx == URLString
when (x == '€') $
modify $ \st -> st{ stUsesEuro = True }
return $
case x of
'€' -> "\\euro{}" ++ rest
'{' -> "\\{" ++ rest
'}' -> "\\}" ++ rest
'$' -> "\\$" ++ rest
'%' -> "\\%" ++ rest
'&' -> "\\&" ++ rest
'_' | not isUrl -> "\\_" ++ rest
'#' -> "\\#" ++ rest
'-' | not isUrl -> case xs of
-- prevent adjacent hyphens from forming ligatures
('-':_) -> "-\\/" ++ rest
_ -> '-' : rest
'~' | not isUrl -> "\\textasciitilde{}" ++ rest
'^' -> "\\^{}" ++ rest
'\\'| isUrl -> '/' : rest -- NB. / works as path sep even on Windows
| otherwise -> "\\textbackslash{}" ++ rest
'|' -> "\\textbar{}" ++ rest
'<' -> "\\textless{}" ++ rest
'>' -> "\\textgreater{}" ++ rest
'[' -> "{[}" ++ rest -- to avoid interpretation as
']' -> "{]}" ++ rest -- optional arguments
'\160' -> "~" ++ rest
'\x2026' -> "\\ldots{}" ++ rest
'\x2018' | ligatures -> "`" ++ rest
'\x2019' | ligatures -> "'" ++ rest
'\x201C' | ligatures -> "``" ++ rest
'\x201D' | ligatures -> "''" ++ rest
'\x2014' | ligatures -> "---" ++ rest
'\x2013' | ligatures -> "--" ++ rest
_ -> x : rest
toLabel :: String -> State WriterState String
toLabel z = go `fmap` stringToLaTeX URLString z
where go [] = ""
go (x:xs)
| (isLetter x || isDigit x) && isAscii x = x:go xs
| elem x "-+=:;." = x:go xs
| otherwise = "ux" ++ printf "%x" (ord x) ++ go xs
-- | Puts contents into LaTeX command.
inCmd :: String -> Doc -> Doc
inCmd cmd contents = char '\\' <> text cmd <> braces contents
toSlides :: [Block] -> State WriterState [Block]
toSlides bs = do
opts <- gets stOptions
let slideLevel = fromMaybe (getSlideLevel bs) $ writerSlideLevel opts
let bs' = prepSlides slideLevel bs
concat `fmap` (mapM (elementToBeamer slideLevel) $ hierarchicalize bs')
elementToBeamer :: Int -> Element -> State WriterState [Block]
elementToBeamer _slideLevel (Blk b) = return [b]
elementToBeamer slideLevel (Sec lvl _num (ident,classes,kvs) tit elts)
| lvl > slideLevel = do
bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts
return $ Para ( RawInline "latex" "\\begin{block}{"
: tit ++ [RawInline "latex" "}"] )
: bs ++ [RawBlock "latex" "\\end{block}"]
| lvl < slideLevel = do
bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts
return $ (Header lvl (ident,classes,kvs) tit) : bs
| otherwise = do -- lvl == slideLevel
-- note: [fragile] is required or verbatim breaks
let hasCodeBlock (CodeBlock _ _) = [True]
hasCodeBlock _ = []
let hasCode (Code _ _) = [True]
hasCode _ = []
opts <- gets stOptions
let fragile = not $ null $ query hasCodeBlock elts ++
if writerListings opts
then query hasCode elts
else []
let allowframebreaks = "allowframebreaks" `elem` classes
let optionslist = ["fragile" | fragile] ++
["allowframebreaks" | allowframebreaks]
let options = if null optionslist
then ""
else "[" ++ intercalate "," optionslist ++ "]"
let slideStart = Para $ RawInline "latex" ("\\begin{frame}" ++ options) :
if tit == [Str "\0"] -- marker for hrule
then []
else (RawInline "latex" "{") : tit ++ [RawInline "latex" "}"]
let slideEnd = RawBlock "latex" "\\end{frame}"
-- now carve up slide into blocks if there are sections inside
bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts
return $ slideStart : bs ++ [slideEnd]
isListBlock :: Block -> Bool
isListBlock (BulletList _) = True
isListBlock (OrderedList _ _) = True
isListBlock (DefinitionList _) = True
isListBlock _ = False
isLineBreakOrSpace :: Inline -> Bool
isLineBreakOrSpace LineBreak = True
isLineBreakOrSpace Space = True
isLineBreakOrSpace _ = False
-- | Convert Pandoc block element to LaTeX.
blockToLaTeX :: Block -- ^ Block to convert
-> State WriterState Doc
blockToLaTeX Null = return empty
blockToLaTeX (Div (_,classes,_) bs) = do
beamer <- writerBeamer `fmap` gets stOptions
contents <- blockListToLaTeX bs
if beamer && "notes" `elem` classes -- speaker notes
then return $ "\\note" <> braces contents
else return contents
blockToLaTeX (Plain lst) =
inlineListToLaTeX $ dropWhile isLineBreakOrSpace lst
-- title beginning with fig: indicates that the image is a figure
blockToLaTeX (Para [Image txt (src,'f':'i':'g':':':tit)]) = do
capt <- if null txt
then return empty
else (\c -> "\\caption" <> braces c) `fmap` inlineListToLaTeX txt
img <- inlineToLaTeX (Image txt (src,tit))
return $ "\\begin{figure}[htbp]" $$ "\\centering" $$ img $$
capt $$ "\\end{figure}"
-- . . . indicates pause in beamer slides
blockToLaTeX (Para [Str ".",Space,Str ".",Space,Str "."]) = do
beamer <- writerBeamer `fmap` gets stOptions
if beamer
then blockToLaTeX (RawBlock "latex" "\\pause")
else inlineListToLaTeX [Str ".",Space,Str ".",Space,Str "."]
blockToLaTeX (Para lst) =
inlineListToLaTeX $ dropWhile isLineBreakOrSpace lst
blockToLaTeX (BlockQuote lst) = do
beamer <- writerBeamer `fmap` gets stOptions
case lst of
[b] | beamer && isListBlock b -> do
oldIncremental <- gets stIncremental
modify $ \s -> s{ stIncremental = not oldIncremental }
result <- blockToLaTeX b
modify $ \s -> s{ stIncremental = oldIncremental }
return result
_ -> do
oldInQuote <- gets stInQuote
modify (\s -> s{stInQuote = True})
contents <- blockListToLaTeX lst
modify (\s -> s{stInQuote = oldInQuote})
return $ "\\begin{quote}" $$ contents $$ "\\end{quote}"
blockToLaTeX (CodeBlock (identifier,classes,keyvalAttr) str) = do
opts <- gets stOptions
ref <- toLabel identifier
let linkAnchor = if null identifier
then empty
else "\\hyperdef{}" <> braces (text ref) <>
braces ("\\label" <> braces (text ref))
let lhsCodeBlock = do
modify $ \s -> s{ stLHS = True }
return $ flush (linkAnchor $$ "\\begin{code}" $$ text str $$
"\\end{code}") $$ cr
let rawCodeBlock = do
st <- get
env <- if stInNote st
then modify (\s -> s{ stVerbInNote = True }) >>
return "Verbatim"
else return "verbatim"
return $ flush (linkAnchor $$ text ("\\begin{" ++ env ++ "}") $$
text str $$ text ("\\end{" ++ env ++ "}")) <> cr
let listingsCodeBlock = do
st <- get
let params = if writerListings (stOptions st)
then (case getListingsLanguage classes of
Just l -> [ "language=" ++ l ]
Nothing -> []) ++
[ "numbers=left" | "numberLines" `elem` classes
|| "number" `elem` classes
|| "number-lines" `elem` classes ] ++
[ (if key == "startFrom"
then "firstnumber"
else key) ++ "=" ++ attr |
(key,attr) <- keyvalAttr ] ++
(if identifier == ""
then []
else [ "label=" ++ ref ])
else []
printParams
| null params = empty
| otherwise = brackets $ hcat (intersperse ", " (map text params))
return $ flush ("\\begin{lstlisting}" <> printParams $$ text str $$
"\\end{lstlisting}") $$ cr
let highlightedCodeBlock =
case highlight formatLaTeXBlock ("",classes,keyvalAttr) str of
Nothing -> rawCodeBlock
Just h -> modify (\st -> st{ stHighlighting = True }) >>
return (flush $ linkAnchor $$ text h)
case () of
_ | isEnabled Ext_literate_haskell opts && "haskell" `elem` classes &&
"literate" `elem` classes -> lhsCodeBlock
| writerListings opts -> listingsCodeBlock
| writerHighlight opts && not (null classes) -> highlightedCodeBlock
| otherwise -> rawCodeBlock
blockToLaTeX (RawBlock f x)
| f == Format "latex" || f == Format "tex"
= return $ text x
| otherwise = return empty
blockToLaTeX (BulletList []) = return empty -- otherwise latex error
blockToLaTeX (BulletList lst) = do
incremental <- gets stIncremental
let inc = if incremental then "[<+->]" else ""
items <- mapM listItemToLaTeX lst
let spacing = if isTightList lst
then text "\\itemsep1pt\\parskip0pt\\parsep0pt"
else empty
return $ text ("\\begin{itemize}" ++ inc) $$ spacing $$ vcat items $$
"\\end{itemize}"
blockToLaTeX (OrderedList _ []) = return empty -- otherwise latex error
blockToLaTeX (OrderedList (start, numstyle, numdelim) lst) = do
st <- get
let inc = if stIncremental st then "[<+->]" else ""
let oldlevel = stOLLevel st
put $ st {stOLLevel = oldlevel + 1}
items <- mapM listItemToLaTeX lst
modify (\s -> s {stOLLevel = oldlevel})
let tostyle x = case numstyle of
Decimal -> "\\arabic" <> braces x
UpperRoman -> "\\Roman" <> braces x
LowerRoman -> "\\roman" <> braces x
UpperAlpha -> "\\Alph" <> braces x
LowerAlpha -> "\\alph" <> braces x
Example -> "\\arabic" <> braces x
DefaultStyle -> "\\arabic" <> braces x
let todelim x = case numdelim of
OneParen -> x <> ")"
TwoParens -> parens x
Period -> x <> "."
_ -> x <> "."
let enum = text $ "enum" ++ map toLower (toRomanNumeral oldlevel)
let stylecommand = if numstyle == DefaultStyle && numdelim == DefaultDelim
then empty
else "\\def" <> "\\label" <> enum <>
braces (todelim $ tostyle enum)
let resetcounter = if start == 1 || oldlevel > 4
then empty
else "\\setcounter" <> braces enum <>
braces (text $ show $ start - 1)
let spacing = if isTightList lst
then text "\\itemsep1pt\\parskip0pt\\parsep0pt"
else empty
return $ text ("\\begin{enumerate}" ++ inc)
$$ stylecommand
$$ resetcounter
$$ spacing
$$ vcat items
$$ "\\end{enumerate}"
blockToLaTeX (DefinitionList []) = return empty
blockToLaTeX (DefinitionList lst) = do
incremental <- gets stIncremental
let inc = if incremental then "[<+->]" else ""
items <- mapM defListItemToLaTeX lst
let spacing = if all isTightList (map snd lst)
then text "\\itemsep1pt\\parskip0pt\\parsep0pt"
else empty
return $ text ("\\begin{description}" ++ inc) $$ spacing $$ vcat items $$
"\\end{description}"
blockToLaTeX HorizontalRule = return $
"\\begin{center}\\rule{3in}{0.4pt}\\end{center}"
blockToLaTeX (Header level (id',classes,_) lst) =
sectionHeader ("unnumbered" `elem` classes) id' level lst
blockToLaTeX (Table caption aligns widths heads rows) = do
headers <- if all null heads
then return empty
else ($$ "\\midrule\\endhead") `fmap`
(tableRowToLaTeX True aligns widths) heads
captionText <- inlineListToLaTeX caption
let capt = if isEmpty captionText
then empty
else text "\\addlinespace"
$$ text "\\caption" <> braces captionText
rows' <- mapM (tableRowToLaTeX False aligns widths) rows
let colDescriptors = text $ concat $ map toColDescriptor aligns
modify $ \s -> s{ stTable = True }
return $ "\\begin{longtable}[c]" <>
braces ("@{}" <> colDescriptors <> "@{}")
-- the @{} removes extra space at beginning and end
$$ "\\toprule\\addlinespace"
$$ headers
$$ vcat rows'
$$ "\\bottomrule"
$$ capt
$$ "\\end{longtable}"
toColDescriptor :: Alignment -> String
toColDescriptor align =
case align of
AlignLeft -> "l"
AlignRight -> "r"
AlignCenter -> "c"
AlignDefault -> "l"
blockListToLaTeX :: [Block] -> State WriterState Doc
blockListToLaTeX lst = vsep `fmap` mapM blockToLaTeX lst
tableRowToLaTeX :: Bool
-> [Alignment]
-> [Double]
-> [[Block]]
-> State WriterState Doc
tableRowToLaTeX header aligns widths cols = do
-- scale factor compensates for extra space between columns
-- so the whole table isn't larger than columnwidth
let scaleFactor = 0.97 ** fromIntegral (length aligns)
let widths' = map (scaleFactor *) widths
cells <- mapM (tableCellToLaTeX header) $ zip3 widths' aligns cols
return $ hsep (intersperse "&" cells) $$ "\\\\\\addlinespace"
-- For simple latex tables (without minipages or parboxes),
-- we need to go to some lengths to get line breaks working:
-- as LineBreak bs = \vtop{\hbox{\strut as}\hbox{\strut bs}}.
fixLineBreaks :: Block -> Block
fixLineBreaks (Para ils) = Para $ fixLineBreaks' ils
fixLineBreaks (Plain ils) = Plain $ fixLineBreaks' ils
fixLineBreaks x = x
fixLineBreaks' :: [Inline] -> [Inline]
fixLineBreaks' ils = case splitBy (== LineBreak) ils of
[] -> []
[xs] -> xs
chunks -> RawInline "tex" "\\vtop{" :
concatMap tohbox chunks ++
[RawInline "tex" "}"]
where tohbox ys = RawInline "tex" "\\hbox{\\strut " : ys ++
[RawInline "tex" "}"]
tableCellToLaTeX :: Bool -> (Double, Alignment, [Block])
-> State WriterState Doc
tableCellToLaTeX _ (0, _, blocks) =
blockListToLaTeX $ walk fixLineBreaks blocks
tableCellToLaTeX header (width, align, blocks) = do
modify $ \st -> st{ stInMinipage = True, stNotes = [] }
cellContents <- blockListToLaTeX blocks
notes <- gets stNotes
modify $ \st -> st{ stInMinipage = False, stNotes = [] }
let valign = text $ if header then "[b]" else "[t]"
let halign = case align of
AlignLeft -> "\\raggedright"
AlignRight -> "\\raggedleft"
AlignCenter -> "\\centering"
AlignDefault -> "\\raggedright"
return $ ("\\begin{minipage}" <> valign <>
braces (text (printf "%.2f\\columnwidth" width)) <>
(halign <> cr <> cellContents <> cr) <> "\\end{minipage}")
$$ case notes of
[] -> empty
ns -> (case length ns of
n | n > 1 -> "\\addtocounter" <>
braces "footnote" <>
braces (text $ show $ 1 - n)
| otherwise -> empty)
$$
vcat (intersperse
("\\addtocounter" <> braces "footnote" <> braces "1")
$ map (\x -> "\\footnotetext" <> braces x)
$ reverse ns)
listItemToLaTeX :: [Block] -> State WriterState Doc
listItemToLaTeX lst = blockListToLaTeX lst >>= return . (text "\\item" $$) .
(nest 2)
defListItemToLaTeX :: ([Inline], [[Block]]) -> State WriterState Doc
defListItemToLaTeX (term, defs) = do
term' <- inlineListToLaTeX term
-- put braces around term if it contains an internal link,
-- since otherwise we get bad bracket interactions: \item[\hyperref[..]
let isInternalLink (Link _ ('#':_,_)) = True
isInternalLink _ = False
let term'' = if any isInternalLink term
then braces term'
else term'
def' <- liftM vsep $ mapM blockListToLaTeX defs
return $ "\\item" <> brackets term'' $$ def'
-- | Craft the section header, inserting the secton reference, if supplied.
sectionHeader :: Bool -- True for unnumbered
-> [Char]
-> Int
-> [Inline]
-> State WriterState Doc
sectionHeader unnumbered ref level lst = do
txt <- inlineListToLaTeX lst
lab <- text `fmap` toLabel ref
let noNote (Note _) = Str ""
noNote x = x
let lstNoNotes = walk noNote lst
txtNoNotes <- inlineListToLaTeX lstNoNotes
let star = if unnumbered then text "*" else empty
-- footnotes in sections don't work (except for starred variants)
-- unless you specify an optional argument:
-- \section[mysec]{mysec\footnote{blah}}
optional <- if unnumbered || lstNoNotes == lst
then return empty
else do
return $ brackets txtNoNotes
let stuffing = star <> optional <> braces txt
book <- gets stBook
opts <- gets stOptions
let level' = if book || writerChapters opts then level - 1 else level
internalLinks <- gets stInternalLinks
let refLabel x = (if ref `elem` internalLinks
then text "\\hyperdef"
<> braces empty
<> braces lab
<> braces x
else x)
let headerWith x y = refLabel $ text x <> y <>
if null ref
then empty
else text "\\label" <> braces lab
let sectionType = case level' of
0 | writerBeamer opts -> "part"
| otherwise -> "chapter"
1 -> "section"
2 -> "subsection"
3 -> "subsubsection"
4 -> "paragraph"
5 -> "subparagraph"
_ -> ""
inQuote <- gets stInQuote
let prefix = if inQuote && level' >= 4
then text "\\mbox{}%"
-- needed for \paragraph, \subparagraph in quote environment
-- see http://tex.stackexchange.com/questions/169830/
else empty
return $ if level' > 5
then txt
else prefix $$
headerWith ('\\':sectionType) stuffing
$$ if unnumbered
then "\\addcontentsline{toc}" <>
braces (text sectionType) <>
braces txtNoNotes
else empty
-- | Convert list of inline elements to LaTeX.
inlineListToLaTeX :: [Inline] -- ^ Inlines to convert
-> State WriterState Doc
inlineListToLaTeX lst =
mapM inlineToLaTeX (fixLineInitialSpaces lst)
>>= return . hcat
-- nonbreaking spaces (~) in LaTeX don't work after line breaks,
-- so we turn nbsps after hard breaks to \hspace commands.
-- this is mostly used in verse.
where fixLineInitialSpaces [] = []
fixLineInitialSpaces (LineBreak : Str s@('\160':_) : xs) =
LineBreak : fixNbsps s ++ fixLineInitialSpaces xs
fixLineInitialSpaces (x:xs) = x : fixLineInitialSpaces xs
fixNbsps s = let (ys,zs) = span (=='\160') s
in replicate (length ys) hspace ++ [Str zs]
hspace = RawInline "latex" "\\hspace*{0.333em}"
isQuoted :: Inline -> Bool
isQuoted (Quoted _ _) = True
isQuoted _ = False
-- | Convert inline element to LaTeX
inlineToLaTeX :: Inline -- ^ Inline to convert
-> State WriterState Doc
inlineToLaTeX (Span (id',classes,_) ils) = do
let noEmph = "csl-no-emph" `elem` classes
let noStrong = "csl-no-strong" `elem` classes
let noSmallCaps = "csl-no-smallcaps" `elem` classes
label' <- if null id'
then return empty
else toLabel id' >>= \x ->
return (text "\\label" <> braces (text x))
fmap (label' <>)
((if noEmph then inCmd "textup" else id) .
(if noStrong then inCmd "textnormal" else id) .
(if noSmallCaps then inCmd "textnormal" else id) .
(if not (noEmph || noStrong || noSmallCaps)
then braces
else id)) `fmap` inlineListToLaTeX ils
inlineToLaTeX (Emph lst) =
inlineListToLaTeX lst >>= return . inCmd "emph"
inlineToLaTeX (Strong lst) =
inlineListToLaTeX lst >>= return . inCmd "textbf"
inlineToLaTeX (Strikeout lst) = do
contents <- inlineListToLaTeX lst
modify $ \s -> s{ stStrikeout = True }
return $ inCmd "sout" contents
inlineToLaTeX (Superscript lst) =
inlineListToLaTeX lst >>= return . inCmd "textsuperscript"
inlineToLaTeX (Subscript lst) = do
inlineListToLaTeX lst >>= return . inCmd "textsubscript"
inlineToLaTeX (SmallCaps lst) =
inlineListToLaTeX lst >>= return . inCmd "textsc"
inlineToLaTeX (Cite cits lst) = do
st <- get
let opts = stOptions st
case writerCiteMethod opts of
Natbib -> citationsToNatbib cits
Biblatex -> citationsToBiblatex cits
_ -> inlineListToLaTeX lst
inlineToLaTeX (Code (_,classes,_) str) = do
opts <- gets stOptions
case () of
_ | writerListings opts -> listingsCode
| writerHighlight opts && not (null classes) -> highlightCode
| otherwise -> rawCode
where listingsCode = do
inNote <- gets stInNote
when inNote $ modify $ \s -> s{ stVerbInNote = True }
let chr = ((enumFromTo '!' '~') \\ str) !! 0
return $ text $ "\\lstinline" ++ [chr] ++ str ++ [chr]
highlightCode = do
case highlight formatLaTeXInline ("",classes,[]) str of
Nothing -> rawCode
Just h -> modify (\st -> st{ stHighlighting = True }) >>
return (text h)
rawCode = liftM (text . (\s -> "\\texttt{" ++ s ++ "}"))
$ stringToLaTeX CodeString str
inlineToLaTeX (Quoted qt lst) = do
contents <- inlineListToLaTeX lst
csquotes <- liftM stCsquotes get
opts <- gets stOptions
if csquotes
then return $ "\\enquote" <> braces contents
else do
let s1 = if (not (null lst)) && (isQuoted (head lst))
then "\\,"
else empty
let s2 = if (not (null lst)) && (isQuoted (last lst))
then "\\,"
else empty
let inner = s1 <> contents <> s2
return $ case qt of
DoubleQuote ->
if writerTeXLigatures opts
then text "``" <> inner <> text "''"
else char '\x201C' <> inner <> char '\x201D'
SingleQuote ->
if writerTeXLigatures opts
then char '`' <> inner <> char '\''
else char '\x2018' <> inner <> char '\x2019'
inlineToLaTeX (Str str) = liftM text $ stringToLaTeX TextString str
inlineToLaTeX (Math InlineMath str) =
return $ char '$' <> text str <> char '$'
inlineToLaTeX (Math DisplayMath str) =
return $ "\\[" <> text str <> "\\]"
inlineToLaTeX (RawInline f str)
| f == Format "latex" || f == Format "tex"
= return $ text str
| otherwise = return empty
inlineToLaTeX (LineBreak) = return "\\\\"
inlineToLaTeX Space = return space
inlineToLaTeX (Link txt ('#':ident, _)) = do
contents <- inlineListToLaTeX txt
lab <- toLabel ident
return $ text "\\hyperref" <> brackets (text lab) <> braces contents
inlineToLaTeX (Link txt (src, _)) =
case txt of
[Str x] | x == src -> -- autolink
do modify $ \s -> s{ stUrl = True }
src' <- stringToLaTeX URLString x
return $ text $ "\\url{" ++ src' ++ "}"
_ -> do contents <- inlineListToLaTeX txt
src' <- stringToLaTeX URLString src
return $ text ("\\href{" ++ src' ++ "}{") <>
contents <> char '}'
inlineToLaTeX (Image _ (source, _)) = do
modify $ \s -> s{ stGraphics = True }
let source' = if isURI source
then source
else unEscapeString source
source'' <- stringToLaTeX URLString source'
return $ "\\includegraphics" <> braces (text source'')
inlineToLaTeX (Note contents) = do
inMinipage <- gets stInMinipage
modify (\s -> s{stInNote = True})
contents' <- blockListToLaTeX contents
modify (\s -> s {stInNote = False})
let optnl = case reverse contents of
(CodeBlock _ _ : _) -> cr
_ -> empty
let noteContents = nest 2 contents' <> optnl
modify $ \st -> st{ stNotes = noteContents : stNotes st }
return $
if inMinipage
then "\\footnotemark{}"
-- note: a \n before } needed when note ends with a Verbatim environment
else "\\footnote" <> braces noteContents
citationsToNatbib :: [Citation] -> State WriterState Doc
citationsToNatbib (one:[])
= citeCommand c p s k
where
Citation { citationId = k
, citationPrefix = p
, citationSuffix = s
, citationMode = m
}
= one
c = case m of
AuthorInText -> "citet"
SuppressAuthor -> "citeyearpar"
NormalCitation -> "citep"
citationsToNatbib cits
| noPrefix (tail cits) && noSuffix (init cits) && ismode NormalCitation cits
= citeCommand "citep" p s ks
where
noPrefix = all (null . citationPrefix)
noSuffix = all (null . citationSuffix)
ismode m = all (((==) m) . citationMode)
p = citationPrefix $ head $ cits
s = citationSuffix $ last $ cits
ks = intercalate ", " $ map citationId cits
citationsToNatbib (c:cs) | citationMode c == AuthorInText = do
author <- citeCommand "citeauthor" [] [] (citationId c)
cits <- citationsToNatbib (c { citationMode = SuppressAuthor } : cs)
return $ author <+> cits
citationsToNatbib cits = do
cits' <- mapM convertOne cits
return $ text "\\citetext{" <> foldl combineTwo empty cits' <> text "}"
where
combineTwo a b | isEmpty a = b
| otherwise = a <> text "; " <> b
convertOne Citation { citationId = k
, citationPrefix = p
, citationSuffix = s
, citationMode = m
}
= case m of
AuthorInText -> citeCommand "citealt" p s k
SuppressAuthor -> citeCommand "citeyear" p s k
NormalCitation -> citeCommand "citealp" p s k
citeCommand :: String -> [Inline] -> [Inline] -> String -> State WriterState Doc
citeCommand c p s k = do
args <- citeArguments p s k
return $ text ("\\" ++ c) <> args
citeArguments :: [Inline] -> [Inline] -> String -> State WriterState Doc
citeArguments p s k = do
let s' = case s of
(Str (x:[]) : r) | isPunctuation x -> dropWhile (== Space) r
(Str (x:xs) : r) | isPunctuation x -> Str xs : r
_ -> s
pdoc <- inlineListToLaTeX p
sdoc <- inlineListToLaTeX s'
let optargs = case (isEmpty pdoc, isEmpty sdoc) of
(True, True ) -> empty
(True, False) -> brackets sdoc
(_ , _ ) -> brackets pdoc <> brackets sdoc
return $ optargs <> braces (text k)
citationsToBiblatex :: [Citation] -> State WriterState Doc
citationsToBiblatex (one:[])
= citeCommand cmd p s k
where
Citation { citationId = k
, citationPrefix = p
, citationSuffix = s
, citationMode = m
} = one
cmd = case m of
SuppressAuthor -> "autocite*"
AuthorInText -> "textcite"
NormalCitation -> "autocite"
citationsToBiblatex (c:cs) = do
args <- mapM convertOne (c:cs)
return $ text cmd <> foldl (<>) empty args
where
cmd = case citationMode c of
AuthorInText -> "\\textcites"
_ -> "\\autocites"
convertOne Citation { citationId = k
, citationPrefix = p
, citationSuffix = s
}
= citeArguments p s k
citationsToBiblatex _ = return empty
-- Determine listings language from list of class attributes.
getListingsLanguage :: [String] -> Maybe String
getListingsLanguage [] = Nothing
getListingsLanguage (x:xs) = toListingsLanguage x <|> getListingsLanguage xs
|
nickbart1980/pandoc
|
src/Text/Pandoc/Writers/LaTeX.hs
|
gpl-2.0
| 39,265
| 0
| 36
| 13,801
| 10,526
| 5,273
| 5,253
| 774
| 31
|
module Handler.Home where
import Import
import Yesod.Form.Bootstrap3
import Yesod.Text.Markdown
blurbForm :: Maybe Blurb -> AForm Handler Blurb
blurbForm mblurb = Blurb
<$> areq markdownField (bfs ("Blurb" :: Text)) (blurbBlurb <$> mblurb)
<*> areq markdownField (bfs ("Social" :: Text)) (blurbSocial <$> mblurb)
getHomeR :: Handler Html
getHomeR = do
uid <- maybeAuthId
(widget, enctype) <- generateFormPost . renderBootstrap3 BootstrapBasicForm $ blurbForm Nothing
currentPost <- runDB $ selectFirst [] [Desc BlogId]
currentBlurb <- runDB $ selectFirst [] [Desc BlurbId]
defaultLayout $ do
setTitle "I like when it works | The adventures of a programming autodidact"
addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"
addScriptRemote "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/highlight.min.js"
addScriptRemote "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/collapse.js"
addStylesheetRemote "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/styles/zenburn.min.css"
$(widgetFile "homepage")
postHomeR :: Handler Html
postHomeR = do
uid <- maybeAuthId
((res, widget), enctype) <- runFormPost . renderBootstrap3 BootstrapBasicForm $ blurbForm Nothing
currentPost <- runDB $ selectFirst [] [Desc BlogId]
currentBlurb <- runDB $ selectFirst [] [Desc BlurbId]
case res of
FormSuccess blurb -> do
_ <- runDB $ insert blurb
redirect $ HomeR
_ -> defaultLayout $(widgetFile "homepage")
|
garry-cairns/ILikeWhenItWorks
|
ILikeWhenItWorks/Handler/Home.hs
|
gpl-3.0
| 1,623
| 0
| 14
| 331
| 402
| 192
| 210
| 32
| 2
|
module ReductionRules where
import Control.Monad.State
import Data.List ((\\), intersect, nub)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import ProverState
import Syntax
import Printer (showTerm, showAction)
import Term (detensor, linearizeTensorProducts, isSimple, isEnabledAction)
import UserIO (choose, chooseRandom, tellerWarning, tellerDebug, readStringFromUser)
import CGraph (getResourceNodeList, partitionResourceNodeList)
import Util (third)
type StateReduction = (Term, Environment) -> ProverStateIO (Maybe Environment)
reduceLollyStateIO :: StateReduction
reduceLollyStateIO (t@((:-@:) a b _), ts) =
removeProductGiving' (\ts' -> b:ts') t ts
reduceLollyStateIO (t@(OfCourse ((:-@:) a b d)), ts) = do
reduceLollyStateIO ((:-@:) a b d, t:ts)
reduceLollyStateIO _ = return $ Nothing
removeProductGiving' ::
([Term] -> [Term]) ->
Term -> [Term] ->
ProverStateIO (Maybe [Term])
removeProductGiving' f ((:-@:) a b actionDesc) ts
| isSimple a =
--case removeProduct' a ts of
-- TODO: make sure that myRemoveFunction is correct! and change its name to resourcesAreAvailable
case myRemoveFunction a ts of
Nothing -> return Nothing
Just ts' -> do
-- PROPERTY (RES_AVAILABLE): the action can execute, hence the map originOfResources has to contain all the needed resources
state <- get
-- Show message
lift $ reduceMessage a b actionDesc
g <- gets granularity
fr <- gets focusedReductions
-- Terms b were just introduced. If b enables unfocused actions,
-- bring them to the environment.
actionsToFocus <- focusActionsEnabledBy b
-- TODO: change the following to modify
state <- get
put $ state { env = (f ts')++actionsToFocus}
-- Increase number of reductions *and* the graph node count
increaseNumberOfReductionsBy 1 -- TODO: change this to modify
modify incrementGraphNodeCount
-- change trace and map
state <- get
nodeCount <- gets _cGraphNode
originRes <- gets originOfResources
let needs = linearizeTensorProducts [a]
let nodeList = getResourceNodeList state needs
let flatNodeList = nub $ concatMap (\(_,_,c)->c) nodeList
let (multipleNodes, oneNode) = partitionResourceNodeList nodeList
let nodeLabel = fromMaybe (showTerm ((:-@:) a b Nothing)) actionDesc
if(multipleNodes==[]) then modify (addActionToTrace (nodeCount,flatNodeList,nodeLabel))
else do
let multipleNodesNonDup = nub (concatMap third multipleNodes)
modify (addActionToTrace (nodeCount,multipleNodesNonDup ,"OR"))
modify incrementGraphNodeCount
nodeCount <- gets _cGraphNode
-- If this action also depends of resources that originate from a single node, we need
-- to establish those connections in the causality graph
let oneNodeNonDup = nub (concatMap third oneNode)
if (oneNodeNonDup == []) then modify (addActionToTrace (nodeCount,[nodeCount-1],nodeLabel))
else modify (addActionToTrace (nodeCount,(nodeCount-1):oneNodeNonDup,nodeLabel))
nodeCount <- gets _cGraphNode
-- The map is changed if oneNode is /= from []
modify (changeMapNonOR oneNode)
-- The map is changed if multipleNodes is /= from []
modify (changeMapOR multipleNodes (nodeCount-1))
-- Change map with the newly introduced resources
let introduces = linearizeTensorProducts [b]
omap <- gets originOfResources
let newMap = foldr (\k -> Map.insertWith (++) k [nodeCount]) omap introduces
-- TODO: use modify
state <- get
put $ state {originOfResources = newMap}
return $ Just ((f ts') ++ actionsToFocus)
| otherwise = lift $ lollyTensorWarning
-- | 'reduceWithStateIO' applies the reduction rule for &.
-- The reduction only happens if both arguments of & are enabled.
reduceWithStateIO :: StateReduction
reduceWithStateIO (term@(a :&: b), ts)
-- Perform only if the choice is enabled (i.e., both actions are enabled)
| isEnabledAction ts term =
do
t <- lift $ choose (term:ts) a b -- ask the user what action to choose
-- There was a choice, so add this state to choicePoints
state <- get
let lastActionName = (\(f,s,t) -> t) $ last $ actionTrace state
let currentChoicePoints = choicePoints state
put (state {choicePoints = (length currentChoicePoints, lastActionName, map showAction [a,b], state): currentChoicePoints})
savedState <- get
let alternative = savedState {env = ([a,b]\\[t])++ts }
modify (changeEnvTo (t:ts))
tellAllStories <- gets tellAllStories
when tellAllStories $ do
state <- get
-- lift $ putStrLn $ "STACK: " ++ show (env alternative)
put (state {btStack = alternative:(btStack state)})
return $ Just (t:ts)
| otherwise = return Nothing
reduceWithStateIO _ = return Nothing
-- | 'reduceWithPlusStateIO' applies the reduction rule for +.
-- If both arguments are enabled, TeLLer chooses one randomly.
-- If only one of the arguments is enabled, that argument is chosen.
-- Otherwise, the state is not changed.
reducePlusStateIO :: StateReduction
reducePlusStateIO (term@(a :+: b), ts)
-- Perform only if one of the choices is enabled. If both are available, choose randomly.
| (isEnabledAction ts a) && (isEnabledAction ts b) =
do t <- lift $ chooseRandom a b
savedState <- get
let alternative = savedState {env = ([a,b]\\[t])++ts }
lift $ putStrLn $ "Alt:" ++ show (env alternative)
modify (changeEnvTo (t:ts))
tellAllStories <- gets tellAllStories
when tellAllStories $ do
state <- get
put (state {btStack = alternative:(btStack state)})
return $ Just (t:ts)
| (isEnabledAction ts a) && (not (isEnabledAction ts b)) =
do savedState <- get
let alternative = savedState {env = (b:ts) }
modify (changeEnvTo (a:ts))
tellAllStories <- gets tellAllStories
when tellAllStories $ do
state <- get
put (state {btStack = alternative:(btStack state)})
return $ Just (a:ts)
| (not (isEnabledAction ts a)) && (isEnabledAction ts b) =
do savedState <- get
let alternative = savedState {env = (a:ts) }
modify (changeEnvTo (b:ts))
tellAllStories <- gets tellAllStories
when tellAllStories $ do
state <- get
put (state {btStack = alternative:(btStack state)})
return $ Just (b:ts)
| otherwise = return Nothing
reducePlusStateIO _ = return Nothing
-- | 'reduceOneStateIO' removes any occurence of One from the environment.
reduceOneStateIO :: StateReduction
reduceOneStateIO (One, ts) = do
modify (changeEnvTo ts)
return $ Just ts
reduceOneStateIO _ = return Nothing
-- | 'reduceOfCourseAtom' introduces an atom in case it isn't already there
{--
reduceOfCourseAtomStateIO :: StateReduction
reduceOfCourseAtomStateIO (OfCourse t@(Atom a), ts) = do
if t `elem` ts then return Nothing
else do modify (changeEnvTo (t:(OfCourse t):ts))
return $ Just (t:(OfCourse t):ts)
reduceOfCourseAtomStateIO _ = return Nothing
--}
{--
reduceOfCourseLollyIO :: IOReduction
reduceOfCourseLollyIO (OfCourse (a :-@: b), ts) =
if (a :-@: b) `elem` ts
then return $ Nothing
else return $ Just ((a :-@: b):OfCourse (a :-@: b):ts)
reduceOfCourseLollyIO _ = return Nothing
--}
{--
removeProduct' :: Term -> [Term] -> Maybe [Term]
removeProduct :: [String] -> [String] -> Maybe [String]
removeProduct' t ts =
let deatom (Atom s) = s
used = map deatom (detensor t)
(atoms, rest) = partition isAtom ts
have = map deatom atoms
left = removeProduct (sort used) (sort have)
in do atoms' <- left
return (rest ++ map Atom atoms')
removeProduct (x:xs) (t:ts)
| x == t = removeProduct xs ts
| otherwise = do ts' <- removeProduct (x:xs) ts
Just (t:ts')
removeProduct [] ts = Just ts
removeProduct _ [] = Nothing
--}
-- The following function replaces removeProductGiving'.
-- Its complexity is still quadratic, but it is much easier
-- to read!
-- FIXME, TODO: REVIEW, BECAUSE BECAUSE INTERSECT DOES NOT WORK AS EXPECTED! IT IS NOT COMMUTATIVE.
myRemoveFunction :: Term -> [Term] -> Maybe [Term]
myRemoveFunction atoms env =
let need = linearizeTensorProducts [atoms] -- what we need
available = linearizeTensorProducts env -- what we have
int = intersect available need
intPersistent = intersect available (map OfCourse need) -- check for persistent resources
simpleNotAvailable = need \\ int
persistentNeeded = map OfCourse simpleNotAvailable
nonExistent = persistentNeeded \\ (concat . replicate (length persistentNeeded)) intPersistent -- nonExistent = map ! (need\\int)\\intPersistent
in
--if (need \\ int) == [])
if (nonExistent == []) -- then, we have all that we need!
then Just $ available \\ need
else Nothing
-- TODO: change this to CLI?
-- If action is named, shows the name; otherwise it shows reduction
reduceMessage :: Term -> Term -> Maybe String -> IO ()
reduceMessage a b Nothing = tellerWarning $ concat ["reducing: ", showTerm ((:-@:) a b Nothing),
", removing: ", showTerm a,
", adding: ", showTerm b]
reduceMessage a b (Just name) = do
tellerWarning (concat ["Action performed: ", name])
readStringFromUser "" -- TODO: this was requested by Cindy, but it's not great when interacting with CLI
return ()
lollyTensorWarning :: IO (Maybe a)
lollyTensorWarning = do
tellerWarning "Warning: lolly LHSs must be simple tensor products"
return $ Nothing
|
jff/TeLLer
|
src/ReductionRules.hs
|
gpl-3.0
| 10,181
| 0
| 21
| 2,676
| 2,272
| 1,166
| 1,106
| 145
| 4
|
module Lab5 where
import Control.Monad
data Concurrent a = Concurrent ((a -> Action) -> Action)
data Action
= Atom (IO Action)
| Fork Action Action
| Stop
instance Show Action where
show (Atom x) = "atom"
show (Fork x y) = "fork " ++ show x ++ " " ++ show y
show Stop = "stop"
-- ===================================
-- Ex. 0
-- ===================================
action :: Concurrent a -> Action
action (Concurrent f) = f (\_-> Stop)
-- ===================================
-- Ex. 1
-- ===================================
stop :: Concurrent a
stop = Concurrent (\f -> Stop)
-- ===================================
-- Ex. 2
-- ===================================
atom :: IO a -> Concurrent a
atom x = Concurrent (\f -> Atom (x >>= return . f))
-- ===================================
-- Ex. 3
-- ===================================
fork :: Concurrent a -> Concurrent ()
fork c = Concurrent (\f -> Fork (action c) (f ()))
par :: Concurrent a -> Concurrent a -> Concurrent a
par (Concurrent c1) (Concurrent c2) = Concurrent (\f -> Fork (c1 f) (c2 f))
-- ===================================
-- Ex. 4
-- ===================================
instance Monad Concurrent where
(Concurrent f) >>= g = Concurrent (\c -> f (\a -> let (Concurrent h) = g a in h c))
return x = Concurrent (\c -> c x)
-- ===================================
-- Ex. 5
-- ===================================
roundRobin :: [Action] -> IO ()
roundRobin [] = return ()
roundRobin (x:xs) = case x of
Atom x -> x >>= \y -> roundRobin (xs ++[y])
Fork a1 a2 -> roundRobin (xs ++ [a1,a2])
Stop -> roundRobin xs
-- ===================================
-- Tests
-- ===================================
ex0 :: Concurrent ()
ex0 = par (loop (genRandom 1337)) (loop (genRandom 2600) >> atom (putStrLn ""))
ex1 :: Concurrent ()
ex1 = do atom (putStr "Haskell")
fork (loop $ genRandom 7331)
loop $ genRandom 42
atom (putStrLn "")
-- ===================================
-- Helper Functions
-- ===================================
run :: Concurrent a -> IO ()
run x = roundRobin [action x]
genRandom :: Int -> [Int]
genRandom 1337 = [1, 96, 36, 11, 42, 47, 9, 1, 62, 73]
genRandom 7331 = [17, 73, 92, 36, 22, 72, 19, 35, 6, 74]
genRandom 2600 = [83, 98, 35, 84, 44, 61, 54, 35, 83, 9]
genRandom 42 = [71, 71, 17, 14, 16, 91, 18, 71, 58, 75]
loop :: [Int] -> Concurrent ()
loop xs = mapM_ (atom . putStr . show) xs
|
zhensydow/ljcsandbox
|
edx/fp101x/pmctemplate.hs
|
gpl-3.0
| 2,514
| 0
| 17
| 549
| 954
| 509
| 445
| 46
| 3
|
{-# 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.Books.CloudLoading.AddBook
-- 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)
--
-- Add a user-upload volume and triggers processing.
--
-- /See:/ <https://code.google.com/apis/books/docs/v1/getting_started.html Books API Reference> for @books.cloudloading.addBook@.
module Network.Google.Resource.Books.CloudLoading.AddBook
(
-- * REST Resource
CloudLoadingAddBookResource
-- * Creating a Request
, cloudLoadingAddBook
, CloudLoadingAddBook
-- * Request Lenses
, clabXgafv
, clabUploadProtocol
, clabAccessToken
, clabUploadType
, clabMimeType
, clabUploadClientToken
, clabName
, clabDriveDocumentId
, clabCallback
) where
import Network.Google.Books.Types
import Network.Google.Prelude
-- | A resource alias for @books.cloudloading.addBook@ method which the
-- 'CloudLoadingAddBook' request conforms to.
type CloudLoadingAddBookResource =
"books" :>
"v1" :>
"cloudloading" :>
"addBook" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "mime_type" Text :>
QueryParam "upload_client_token" Text :>
QueryParam "name" Text :>
QueryParam "drive_document_id" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Post '[JSON] BooksCloudLoadingResource
-- | Add a user-upload volume and triggers processing.
--
-- /See:/ 'cloudLoadingAddBook' smart constructor.
data CloudLoadingAddBook =
CloudLoadingAddBook'
{ _clabXgafv :: !(Maybe Xgafv)
, _clabUploadProtocol :: !(Maybe Text)
, _clabAccessToken :: !(Maybe Text)
, _clabUploadType :: !(Maybe Text)
, _clabMimeType :: !(Maybe Text)
, _clabUploadClientToken :: !(Maybe Text)
, _clabName :: !(Maybe Text)
, _clabDriveDocumentId :: !(Maybe Text)
, _clabCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CloudLoadingAddBook' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clabXgafv'
--
-- * 'clabUploadProtocol'
--
-- * 'clabAccessToken'
--
-- * 'clabUploadType'
--
-- * 'clabMimeType'
--
-- * 'clabUploadClientToken'
--
-- * 'clabName'
--
-- * 'clabDriveDocumentId'
--
-- * 'clabCallback'
cloudLoadingAddBook
:: CloudLoadingAddBook
cloudLoadingAddBook =
CloudLoadingAddBook'
{ _clabXgafv = Nothing
, _clabUploadProtocol = Nothing
, _clabAccessToken = Nothing
, _clabUploadType = Nothing
, _clabMimeType = Nothing
, _clabUploadClientToken = Nothing
, _clabName = Nothing
, _clabDriveDocumentId = Nothing
, _clabCallback = Nothing
}
-- | V1 error format.
clabXgafv :: Lens' CloudLoadingAddBook (Maybe Xgafv)
clabXgafv
= lens _clabXgafv (\ s a -> s{_clabXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
clabUploadProtocol :: Lens' CloudLoadingAddBook (Maybe Text)
clabUploadProtocol
= lens _clabUploadProtocol
(\ s a -> s{_clabUploadProtocol = a})
-- | OAuth access token.
clabAccessToken :: Lens' CloudLoadingAddBook (Maybe Text)
clabAccessToken
= lens _clabAccessToken
(\ s a -> s{_clabAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
clabUploadType :: Lens' CloudLoadingAddBook (Maybe Text)
clabUploadType
= lens _clabUploadType
(\ s a -> s{_clabUploadType = a})
-- | The document MIME type. It can be set only if the drive_document_id is
-- set.
clabMimeType :: Lens' CloudLoadingAddBook (Maybe Text)
clabMimeType
= lens _clabMimeType (\ s a -> s{_clabMimeType = a})
-- | Scotty upload token.
clabUploadClientToken :: Lens' CloudLoadingAddBook (Maybe Text)
clabUploadClientToken
= lens _clabUploadClientToken
(\ s a -> s{_clabUploadClientToken = a})
-- | The document name. It can be set only if the drive_document_id is set.
clabName :: Lens' CloudLoadingAddBook (Maybe Text)
clabName = lens _clabName (\ s a -> s{_clabName = a})
-- | A drive document id. The upload_client_token must not be set.
clabDriveDocumentId :: Lens' CloudLoadingAddBook (Maybe Text)
clabDriveDocumentId
= lens _clabDriveDocumentId
(\ s a -> s{_clabDriveDocumentId = a})
-- | JSONP
clabCallback :: Lens' CloudLoadingAddBook (Maybe Text)
clabCallback
= lens _clabCallback (\ s a -> s{_clabCallback = a})
instance GoogleRequest CloudLoadingAddBook where
type Rs CloudLoadingAddBook =
BooksCloudLoadingResource
type Scopes CloudLoadingAddBook =
'["https://www.googleapis.com/auth/books"]
requestClient CloudLoadingAddBook'{..}
= go _clabXgafv _clabUploadProtocol _clabAccessToken
_clabUploadType
_clabMimeType
_clabUploadClientToken
_clabName
_clabDriveDocumentId
_clabCallback
(Just AltJSON)
booksService
where go
= buildClient
(Proxy :: Proxy CloudLoadingAddBookResource)
mempty
|
brendanhay/gogol
|
gogol-books/gen/Network/Google/Resource/Books/CloudLoading/AddBook.hs
|
mpl-2.0
| 6,054
| 0
| 21
| 1,478
| 951
| 549
| 402
| 137
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Plus.Comments.List
-- 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)
--
-- List all of the comments for an activity.
--
-- /See:/ <https://developers.google.com/+/api/ Google+ API Reference> for @plus.comments.list@.
module Network.Google.Resource.Plus.Comments.List
(
-- * REST Resource
CommentsListResource
-- * Creating a Request
, commentsList
, CommentsList
-- * Request Lenses
, clActivityId
, clSortOrder
, clPageToken
, clMaxResults
) where
import Network.Google.Plus.Types
import Network.Google.Prelude
-- | A resource alias for @plus.comments.list@ method which the
-- 'CommentsList' request conforms to.
type CommentsListResource =
"plus" :>
"v1" :>
"activities" :>
Capture "activityId" Text :>
"comments" :>
QueryParam "sortOrder" CommentsListSortOrder :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :> Get '[JSON] CommentFeed
-- | List all of the comments for an activity.
--
-- /See:/ 'commentsList' smart constructor.
data CommentsList = CommentsList'
{ _clActivityId :: !Text
, _clSortOrder :: !CommentsListSortOrder
, _clPageToken :: !(Maybe Text)
, _clMaxResults :: !(Textual Word32)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'CommentsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clActivityId'
--
-- * 'clSortOrder'
--
-- * 'clPageToken'
--
-- * 'clMaxResults'
commentsList
:: Text -- ^ 'clActivityId'
-> CommentsList
commentsList pClActivityId_ =
CommentsList'
{ _clActivityId = pClActivityId_
, _clSortOrder = Ascending
, _clPageToken = Nothing
, _clMaxResults = 20
}
-- | The ID of the activity to get comments for.
clActivityId :: Lens' CommentsList Text
clActivityId
= lens _clActivityId (\ s a -> s{_clActivityId = a})
-- | The order in which to sort the list of comments.
clSortOrder :: Lens' CommentsList CommentsListSortOrder
clSortOrder
= lens _clSortOrder (\ s a -> s{_clSortOrder = a})
-- | The continuation token, which is used to page through large result sets.
-- To get the next page of results, set this parameter to the value of
-- \"nextPageToken\" from the previous response.
clPageToken :: Lens' CommentsList (Maybe Text)
clPageToken
= lens _clPageToken (\ s a -> s{_clPageToken = a})
-- | The maximum number of comments to include in the response, which is used
-- for paging. For any response, the actual number returned might be less
-- than the specified maxResults.
clMaxResults :: Lens' CommentsList Word32
clMaxResults
= lens _clMaxResults (\ s a -> s{_clMaxResults = a})
. _Coerce
instance GoogleRequest CommentsList where
type Rs CommentsList = CommentFeed
type Scopes CommentsList =
'["https://www.googleapis.com/auth/plus.login",
"https://www.googleapis.com/auth/plus.me"]
requestClient CommentsList'{..}
= go _clActivityId (Just _clSortOrder) _clPageToken
(Just _clMaxResults)
(Just AltJSON)
plusService
where go
= buildClient (Proxy :: Proxy CommentsListResource)
mempty
|
rueshyna/gogol
|
gogol-plus/gen/Network/Google/Resource/Plus/Comments/List.hs
|
mpl-2.0
| 4,111
| 0
| 16
| 975
| 557
| 329
| 228
| 82
| 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.YouTube.Videos.Rate
-- 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)
--
-- Adds a like or dislike rating to a video or removes a rating from a
-- video.
--
-- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.videos.rate@.
module Network.Google.Resource.YouTube.Videos.Rate
(
-- * REST Resource
VideosRateResource
-- * Creating a Request
, videosRate
, VideosRate
-- * Request Lenses
, vrXgafv
, vrRating
, vrUploadProtocol
, vrAccessToken
, vrUploadType
, vrId
, vrCallback
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.videos.rate@ method which the
-- 'VideosRate' request conforms to.
type VideosRateResource =
"youtube" :>
"v3" :>
"videos" :>
"rate" :>
QueryParam "id" Text :>
QueryParam "rating" VideosRateRating :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] ()
-- | Adds a like or dislike rating to a video or removes a rating from a
-- video.
--
-- /See:/ 'videosRate' smart constructor.
data VideosRate =
VideosRate'
{ _vrXgafv :: !(Maybe Xgafv)
, _vrRating :: !VideosRateRating
, _vrUploadProtocol :: !(Maybe Text)
, _vrAccessToken :: !(Maybe Text)
, _vrUploadType :: !(Maybe Text)
, _vrId :: !Text
, _vrCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideosRate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vrXgafv'
--
-- * 'vrRating'
--
-- * 'vrUploadProtocol'
--
-- * 'vrAccessToken'
--
-- * 'vrUploadType'
--
-- * 'vrId'
--
-- * 'vrCallback'
videosRate
:: VideosRateRating -- ^ 'vrRating'
-> Text -- ^ 'vrId'
-> VideosRate
videosRate pVrRating_ pVrId_ =
VideosRate'
{ _vrXgafv = Nothing
, _vrRating = pVrRating_
, _vrUploadProtocol = Nothing
, _vrAccessToken = Nothing
, _vrUploadType = Nothing
, _vrId = pVrId_
, _vrCallback = Nothing
}
-- | V1 error format.
vrXgafv :: Lens' VideosRate (Maybe Xgafv)
vrXgafv = lens _vrXgafv (\ s a -> s{_vrXgafv = a})
vrRating :: Lens' VideosRate VideosRateRating
vrRating = lens _vrRating (\ s a -> s{_vrRating = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
vrUploadProtocol :: Lens' VideosRate (Maybe Text)
vrUploadProtocol
= lens _vrUploadProtocol
(\ s a -> s{_vrUploadProtocol = a})
-- | OAuth access token.
vrAccessToken :: Lens' VideosRate (Maybe Text)
vrAccessToken
= lens _vrAccessToken
(\ s a -> s{_vrAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
vrUploadType :: Lens' VideosRate (Maybe Text)
vrUploadType
= lens _vrUploadType (\ s a -> s{_vrUploadType = a})
vrId :: Lens' VideosRate Text
vrId = lens _vrId (\ s a -> s{_vrId = a})
-- | JSONP
vrCallback :: Lens' VideosRate (Maybe Text)
vrCallback
= lens _vrCallback (\ s a -> s{_vrCallback = a})
instance GoogleRequest VideosRate where
type Rs VideosRate = ()
type Scopes VideosRate =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtubepartner"]
requestClient VideosRate'{..}
= go (Just _vrId) (Just _vrRating) _vrXgafv
_vrUploadProtocol
_vrAccessToken
_vrUploadType
_vrCallback
(Just AltJSON)
youTubeService
where go
= buildClient (Proxy :: Proxy VideosRateResource)
mempty
|
brendanhay/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/Videos/Rate.hs
|
mpl-2.0
| 4,714
| 0
| 19
| 1,219
| 803
| 466
| 337
| 113
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.PubSub.Types.Sum
-- 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)
--
module Network.Google.PubSub.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | The set of fields to return in the response. If not set, returns a
-- Schema with \`name\` and \`type\`, but not \`definition\`. Set to
-- \`FULL\` to retrieve all fields.
data ProjectsSchemasGetView
= SchemaViewUnspecified
-- ^ @SCHEMA_VIEW_UNSPECIFIED@
-- The default \/ unset value. The API will default to the BASIC view.
| Basic
-- ^ @BASIC@
-- Include the name and type of the schema, but not the definition.
| Full
-- ^ @FULL@
-- Include all Schema object fields.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsSchemasGetView
instance FromHttpApiData ProjectsSchemasGetView where
parseQueryParam = \case
"SCHEMA_VIEW_UNSPECIFIED" -> Right SchemaViewUnspecified
"BASIC" -> Right Basic
"FULL" -> Right Full
x -> Left ("Unable to parse ProjectsSchemasGetView from: " <> x)
instance ToHttpApiData ProjectsSchemasGetView where
toQueryParam = \case
SchemaViewUnspecified -> "SCHEMA_VIEW_UNSPECIFIED"
Basic -> "BASIC"
Full -> "FULL"
instance FromJSON ProjectsSchemasGetView where
parseJSON = parseJSONText "ProjectsSchemasGetView"
instance ToJSON ProjectsSchemasGetView where
toJSON = toJSONText
-- | The encoding expected for messages
data ValidateMessageRequestEncoding
= EncodingUnspecified
-- ^ @ENCODING_UNSPECIFIED@
-- Unspecified
| JSON
-- ^ @JSON@
-- JSON encoding
| Binary
-- ^ @BINARY@
-- Binary encoding, as defined by the schema type. For some schema types,
-- binary encoding may not be available.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ValidateMessageRequestEncoding
instance FromHttpApiData ValidateMessageRequestEncoding where
parseQueryParam = \case
"ENCODING_UNSPECIFIED" -> Right EncodingUnspecified
"JSON" -> Right JSON
"BINARY" -> Right Binary
x -> Left ("Unable to parse ValidateMessageRequestEncoding from: " <> x)
instance ToHttpApiData ValidateMessageRequestEncoding where
toQueryParam = \case
EncodingUnspecified -> "ENCODING_UNSPECIFIED"
JSON -> "JSON"
Binary -> "BINARY"
instance FromJSON ValidateMessageRequestEncoding where
parseJSON = parseJSONText "ValidateMessageRequestEncoding"
instance ToJSON ValidateMessageRequestEncoding where
toJSON = toJSONText
-- | The encoding of messages validated against \`schema\`.
data SchemaSettingsEncoding
= SSEEncodingUnspecified
-- ^ @ENCODING_UNSPECIFIED@
-- Unspecified
| SSEJSON
-- ^ @JSON@
-- JSON encoding
| SSEBinary
-- ^ @BINARY@
-- Binary encoding, as defined by the schema type. For some schema types,
-- binary encoding may not be available.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SchemaSettingsEncoding
instance FromHttpApiData SchemaSettingsEncoding where
parseQueryParam = \case
"ENCODING_UNSPECIFIED" -> Right SSEEncodingUnspecified
"JSON" -> Right SSEJSON
"BINARY" -> Right SSEBinary
x -> Left ("Unable to parse SchemaSettingsEncoding from: " <> x)
instance ToHttpApiData SchemaSettingsEncoding where
toQueryParam = \case
SSEEncodingUnspecified -> "ENCODING_UNSPECIFIED"
SSEJSON -> "JSON"
SSEBinary -> "BINARY"
instance FromJSON SchemaSettingsEncoding where
parseJSON = parseJSONText "SchemaSettingsEncoding"
instance ToJSON SchemaSettingsEncoding where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | The set of Schema fields to return in the response. If not set, returns
-- Schemas with \`name\` and \`type\`, but not \`definition\`. Set to
-- \`FULL\` to retrieve all fields.
data ProjectsSchemasListView
= PSLVSchemaViewUnspecified
-- ^ @SCHEMA_VIEW_UNSPECIFIED@
-- The default \/ unset value. The API will default to the BASIC view.
| PSLVBasic
-- ^ @BASIC@
-- Include the name and type of the schema, but not the definition.
| PSLVFull
-- ^ @FULL@
-- Include all Schema object fields.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsSchemasListView
instance FromHttpApiData ProjectsSchemasListView where
parseQueryParam = \case
"SCHEMA_VIEW_UNSPECIFIED" -> Right PSLVSchemaViewUnspecified
"BASIC" -> Right PSLVBasic
"FULL" -> Right PSLVFull
x -> Left ("Unable to parse ProjectsSchemasListView from: " <> x)
instance ToHttpApiData ProjectsSchemasListView where
toQueryParam = \case
PSLVSchemaViewUnspecified -> "SCHEMA_VIEW_UNSPECIFIED"
PSLVBasic -> "BASIC"
PSLVFull -> "FULL"
instance FromJSON ProjectsSchemasListView where
parseJSON = parseJSONText "ProjectsSchemasListView"
instance ToJSON ProjectsSchemasListView where
toJSON = toJSONText
-- | The type of the schema definition.
data SchemaType
= TypeUnspecified
-- ^ @TYPE_UNSPECIFIED@
-- Default value. This value is unused.
| ProtocolBuffer
-- ^ @PROTOCOL_BUFFER@
-- A Protocol Buffer schema definition.
| Avro
-- ^ @AVRO@
-- An Avro schema definition.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SchemaType
instance FromHttpApiData SchemaType where
parseQueryParam = \case
"TYPE_UNSPECIFIED" -> Right TypeUnspecified
"PROTOCOL_BUFFER" -> Right ProtocolBuffer
"AVRO" -> Right Avro
x -> Left ("Unable to parse SchemaType from: " <> x)
instance ToHttpApiData SchemaType where
toQueryParam = \case
TypeUnspecified -> "TYPE_UNSPECIFIED"
ProtocolBuffer -> "PROTOCOL_BUFFER"
Avro -> "AVRO"
instance FromJSON SchemaType where
parseJSON = parseJSONText "SchemaType"
instance ToJSON SchemaType where
toJSON = toJSONText
|
brendanhay/gogol
|
gogol-pubsub/gen/Network/Google/PubSub/Types/Sum.hs
|
mpl-2.0
| 7,127
| 0
| 11
| 1,638
| 1,113
| 600
| 513
| 131
| 0
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Redis.Types.Sum
-- 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)
--
module Network.Google.Redis.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | Optional. Available data protection modes that the user can choose. If
-- it\'s unspecified, data protection mode will be LIMITED_DATA_LOSS by
-- default.
data FailoverInstanceRequestDataProtectionMode
= DataProtectionModeUnspecified
-- ^ @DATA_PROTECTION_MODE_UNSPECIFIED@
-- Defaults to LIMITED_DATA_LOSS if a data protection mode is not
-- specified.
| LimitedDataLoss
-- ^ @LIMITED_DATA_LOSS@
-- Instance failover will be protected with data loss control. More
-- specifically, the failover will only be performed if the current
-- replication offset diff between primary and replica is under a certain
-- threshold.
| ForceDataLoss
-- ^ @FORCE_DATA_LOSS@
-- Instance failover will be performed without data loss control.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable FailoverInstanceRequestDataProtectionMode
instance FromHttpApiData FailoverInstanceRequestDataProtectionMode where
parseQueryParam = \case
"DATA_PROTECTION_MODE_UNSPECIFIED" -> Right DataProtectionModeUnspecified
"LIMITED_DATA_LOSS" -> Right LimitedDataLoss
"FORCE_DATA_LOSS" -> Right ForceDataLoss
x -> Left ("Unable to parse FailoverInstanceRequestDataProtectionMode from: " <> x)
instance ToHttpApiData FailoverInstanceRequestDataProtectionMode where
toQueryParam = \case
DataProtectionModeUnspecified -> "DATA_PROTECTION_MODE_UNSPECIFIED"
LimitedDataLoss -> "LIMITED_DATA_LOSS"
ForceDataLoss -> "FORCE_DATA_LOSS"
instance FromJSON FailoverInstanceRequestDataProtectionMode where
parseJSON = parseJSONText "FailoverInstanceRequestDataProtectionMode"
instance ToJSON FailoverInstanceRequestDataProtectionMode where
toJSON = toJSONText
-- | Optional. The TLS mode of the Redis instance. If not provided, TLS is
-- disabled for the instance.
data InstanceTransitEncryptionMode
= TransitEncryptionModeUnspecified
-- ^ @TRANSIT_ENCRYPTION_MODE_UNSPECIFIED@
-- Not set.
| ServerAuthentication
-- ^ @SERVER_AUTHENTICATION@
-- Client to Server traffic encryption enabled with server authentication.
| Disabled
-- ^ @DISABLED@
-- TLS is disabled for the instance.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InstanceTransitEncryptionMode
instance FromHttpApiData InstanceTransitEncryptionMode where
parseQueryParam = \case
"TRANSIT_ENCRYPTION_MODE_UNSPECIFIED" -> Right TransitEncryptionModeUnspecified
"SERVER_AUTHENTICATION" -> Right ServerAuthentication
"DISABLED" -> Right Disabled
x -> Left ("Unable to parse InstanceTransitEncryptionMode from: " <> x)
instance ToHttpApiData InstanceTransitEncryptionMode where
toQueryParam = \case
TransitEncryptionModeUnspecified -> "TRANSIT_ENCRYPTION_MODE_UNSPECIFIED"
ServerAuthentication -> "SERVER_AUTHENTICATION"
Disabled -> "DISABLED"
instance FromJSON InstanceTransitEncryptionMode where
parseJSON = parseJSONText "InstanceTransitEncryptionMode"
instance ToJSON InstanceTransitEncryptionMode where
toJSON = toJSONText
-- | Required. The service tier of the instance.
data InstanceTier
= TierUnspecified
-- ^ @TIER_UNSPECIFIED@
-- Not set.
| Basic
-- ^ @BASIC@
-- BASIC tier: standalone instance
| StandardHa
-- ^ @STANDARD_HA@
-- STANDARD_HA tier: highly available primary\/replica instances
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InstanceTier
instance FromHttpApiData InstanceTier where
parseQueryParam = \case
"TIER_UNSPECIFIED" -> Right TierUnspecified
"BASIC" -> Right Basic
"STANDARD_HA" -> Right StandardHa
x -> Left ("Unable to parse InstanceTier from: " <> x)
instance ToHttpApiData InstanceTier where
toQueryParam = \case
TierUnspecified -> "TIER_UNSPECIFIED"
Basic -> "BASIC"
StandardHa -> "STANDARD_HA"
instance FromJSON InstanceTier where
parseJSON = parseJSONText "InstanceTier"
instance ToJSON InstanceTier where
toJSON = toJSONText
-- | Optional. The network connect mode of the Redis instance. If not
-- provided, the connect mode defaults to DIRECT_PEERING.
data InstanceConnectMode
= ConnectModeUnspecified
-- ^ @CONNECT_MODE_UNSPECIFIED@
-- Not set.
| DirectPeering
-- ^ @DIRECT_PEERING@
-- Connect via direct peering to the Memorystore for Redis hosted service.
| PrivateServiceAccess
-- ^ @PRIVATE_SERVICE_ACCESS@
-- Connect your Memorystore for Redis instance using Private Service
-- Access. Private services access provides an IP address range for
-- multiple Google Cloud services, including Memorystore.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InstanceConnectMode
instance FromHttpApiData InstanceConnectMode where
parseQueryParam = \case
"CONNECT_MODE_UNSPECIFIED" -> Right ConnectModeUnspecified
"DIRECT_PEERING" -> Right DirectPeering
"PRIVATE_SERVICE_ACCESS" -> Right PrivateServiceAccess
x -> Left ("Unable to parse InstanceConnectMode from: " <> x)
instance ToHttpApiData InstanceConnectMode where
toQueryParam = \case
ConnectModeUnspecified -> "CONNECT_MODE_UNSPECIFIED"
DirectPeering -> "DIRECT_PEERING"
PrivateServiceAccess -> "PRIVATE_SERVICE_ACCESS"
instance FromJSON InstanceConnectMode where
parseJSON = parseJSONText "InstanceConnectMode"
instance ToJSON InstanceConnectMode where
toJSON = toJSONText
-- | Required. If reschedule type is SPECIFIC_TIME, must set up schedule_time
-- as well.
data RescheduleMaintenanceRequestRescheduleType
= RescheduleTypeUnspecified
-- ^ @RESCHEDULE_TYPE_UNSPECIFIED@
-- Not set.
| Immediate
-- ^ @IMMEDIATE@
-- If the user wants to schedule the maintenance to happen now.
| NextAvailableWindow
-- ^ @NEXT_AVAILABLE_WINDOW@
-- If the user wants to use the existing maintenance policy to find the
-- next available window.
| SpecificTime
-- ^ @SPECIFIC_TIME@
-- If the user wants to reschedule the maintenance to a specific time.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RescheduleMaintenanceRequestRescheduleType
instance FromHttpApiData RescheduleMaintenanceRequestRescheduleType where
parseQueryParam = \case
"RESCHEDULE_TYPE_UNSPECIFIED" -> Right RescheduleTypeUnspecified
"IMMEDIATE" -> Right Immediate
"NEXT_AVAILABLE_WINDOW" -> Right NextAvailableWindow
"SPECIFIC_TIME" -> Right SpecificTime
x -> Left ("Unable to parse RescheduleMaintenanceRequestRescheduleType from: " <> x)
instance ToHttpApiData RescheduleMaintenanceRequestRescheduleType where
toQueryParam = \case
RescheduleTypeUnspecified -> "RESCHEDULE_TYPE_UNSPECIFIED"
Immediate -> "IMMEDIATE"
NextAvailableWindow -> "NEXT_AVAILABLE_WINDOW"
SpecificTime -> "SPECIFIC_TIME"
instance FromJSON RescheduleMaintenanceRequestRescheduleType where
parseJSON = parseJSONText "RescheduleMaintenanceRequestRescheduleType"
instance ToJSON RescheduleMaintenanceRequestRescheduleType where
toJSON = toJSONText
-- | Required. The day of week that maintenance updates occur.
data WeeklyMaintenanceWindowDay
= DayOfWeekUnspecified
-- ^ @DAY_OF_WEEK_UNSPECIFIED@
-- The day of the week is unspecified.
| Monday
-- ^ @MONDAY@
-- Monday
| Tuesday
-- ^ @TUESDAY@
-- Tuesday
| Wednesday
-- ^ @WEDNESDAY@
-- Wednesday
| Thursday
-- ^ @THURSDAY@
-- Thursday
| Friday
-- ^ @FRIDAY@
-- Friday
| Saturday
-- ^ @SATURDAY@
-- Saturday
| Sunday
-- ^ @SUNDAY@
-- Sunday
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable WeeklyMaintenanceWindowDay
instance FromHttpApiData WeeklyMaintenanceWindowDay where
parseQueryParam = \case
"DAY_OF_WEEK_UNSPECIFIED" -> Right DayOfWeekUnspecified
"MONDAY" -> Right Monday
"TUESDAY" -> Right Tuesday
"WEDNESDAY" -> Right Wednesday
"THURSDAY" -> Right Thursday
"FRIDAY" -> Right Friday
"SATURDAY" -> Right Saturday
"SUNDAY" -> Right Sunday
x -> Left ("Unable to parse WeeklyMaintenanceWindowDay from: " <> x)
instance ToHttpApiData WeeklyMaintenanceWindowDay where
toQueryParam = \case
DayOfWeekUnspecified -> "DAY_OF_WEEK_UNSPECIFIED"
Monday -> "MONDAY"
Tuesday -> "TUESDAY"
Wednesday -> "WEDNESDAY"
Thursday -> "THURSDAY"
Friday -> "FRIDAY"
Saturday -> "SATURDAY"
Sunday -> "SUNDAY"
instance FromJSON WeeklyMaintenanceWindowDay where
parseJSON = parseJSONText "WeeklyMaintenanceWindowDay"
instance ToJSON WeeklyMaintenanceWindowDay where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | Output only. The current state of this instance.
data InstanceState
= StateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Not set.
| Creating
-- ^ @CREATING@
-- Redis instance is being created.
| Ready
-- ^ @READY@
-- Redis instance has been created and is fully usable.
| Updating
-- ^ @UPDATING@
-- Redis instance configuration is being updated. Certain kinds of updates
-- may cause the instance to become unusable while the update is in
-- progress.
| Deleting
-- ^ @DELETING@
-- Redis instance is being deleted.
| Repairing
-- ^ @REPAIRING@
-- Redis instance is being repaired and may be unusable.
| Maintenance
-- ^ @MAINTENANCE@
-- Maintenance is being performed on this Redis instance.
| Importing
-- ^ @IMPORTING@
-- Redis instance is importing data (availability may be affected).
| FailingOver
-- ^ @FAILING_OVER@
-- Redis instance is failing over (availability may be affected).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InstanceState
instance FromHttpApiData InstanceState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right StateUnspecified
"CREATING" -> Right Creating
"READY" -> Right Ready
"UPDATING" -> Right Updating
"DELETING" -> Right Deleting
"REPAIRING" -> Right Repairing
"MAINTENANCE" -> Right Maintenance
"IMPORTING" -> Right Importing
"FAILING_OVER" -> Right FailingOver
x -> Left ("Unable to parse InstanceState from: " <> x)
instance ToHttpApiData InstanceState where
toQueryParam = \case
StateUnspecified -> "STATE_UNSPECIFIED"
Creating -> "CREATING"
Ready -> "READY"
Updating -> "UPDATING"
Deleting -> "DELETING"
Repairing -> "REPAIRING"
Maintenance -> "MAINTENANCE"
Importing -> "IMPORTING"
FailingOver -> "FAILING_OVER"
instance FromJSON InstanceState where
parseJSON = parseJSONText "InstanceState"
instance ToJSON InstanceState where
toJSON = toJSONText
|
brendanhay/gogol
|
gogol-redis/gen/Network/Google/Redis/Types/Sum.hs
|
mpl-2.0
| 12,452
| 0
| 11
| 2,834
| 1,725
| 932
| 793
| 209
| 0
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.ListVirtualMFADevices
-- Copyright : (c) 2013-2015 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)
--
-- Lists the virtual MFA devices under the AWS account by assignment
-- status. If you do not specify an assignment status, the action returns a
-- list of all virtual MFA devices. Assignment status can be 'Assigned',
-- 'Unassigned', or 'Any'.
--
-- You can paginate the results using the 'MaxItems' and 'Marker'
-- parameters.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListVirtualMFADevices.html AWS API Reference> for ListVirtualMFADevices.
--
-- This operation returns paginated results.
module Network.AWS.IAM.ListVirtualMFADevices
(
-- * Creating a Request
listVirtualMFADevices
, ListVirtualMFADevices
-- * Request Lenses
, lvmdAssignmentStatus
, lvmdMarker
, lvmdMaxItems
-- * Destructuring the Response
, listVirtualMFADevicesResponse
, ListVirtualMFADevicesResponse
-- * Response Lenses
, lvmdrsMarker
, lvmdrsIsTruncated
, lvmdrsResponseStatus
, lvmdrsVirtualMFADevices
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'listVirtualMFADevices' smart constructor.
data ListVirtualMFADevices = ListVirtualMFADevices'
{ _lvmdAssignmentStatus :: !(Maybe AssignmentStatusType)
, _lvmdMarker :: !(Maybe Text)
, _lvmdMaxItems :: !(Maybe Nat)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListVirtualMFADevices' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lvmdAssignmentStatus'
--
-- * 'lvmdMarker'
--
-- * 'lvmdMaxItems'
listVirtualMFADevices
:: ListVirtualMFADevices
listVirtualMFADevices =
ListVirtualMFADevices'
{ _lvmdAssignmentStatus = Nothing
, _lvmdMarker = Nothing
, _lvmdMaxItems = Nothing
}
-- | The status (unassigned or assigned) of the devices to list. If you do
-- not specify an 'AssignmentStatus', the action defaults to 'Any' which
-- lists both assigned and unassigned virtual MFA devices.
lvmdAssignmentStatus :: Lens' ListVirtualMFADevices (Maybe AssignmentStatusType)
lvmdAssignmentStatus = lens _lvmdAssignmentStatus (\ s a -> s{_lvmdAssignmentStatus = a});
-- | Use this parameter only when paginating results and only after you
-- receive a response indicating that the results are truncated. Set it to
-- the value of the 'Marker' element in the response you received to inform
-- the next call about where to start.
lvmdMarker :: Lens' ListVirtualMFADevices (Maybe Text)
lvmdMarker = lens _lvmdMarker (\ s a -> s{_lvmdMarker = a});
-- | Use this only when paginating results to indicate the maximum number of
-- items you want in the response. If there are additional items beyond the
-- maximum you specify, the 'IsTruncated' response element is 'true'.
--
-- This parameter is optional. If you do not include it, it defaults to
-- 100. Note that IAM might return fewer results, even when there are more
-- results available. If this is the case, the 'IsTruncated' response
-- element returns 'true' and 'Marker' contains a value to include in the
-- subsequent call that tells the service where to continue from.
lvmdMaxItems :: Lens' ListVirtualMFADevices (Maybe Natural)
lvmdMaxItems = lens _lvmdMaxItems (\ s a -> s{_lvmdMaxItems = a}) . mapping _Nat;
instance AWSPager ListVirtualMFADevices where
page rq rs
| stop (rs ^. lvmdrsIsTruncated) = Nothing
| isNothing (rs ^. lvmdrsMarker) = Nothing
| otherwise =
Just $ rq & lvmdMarker .~ rs ^. lvmdrsMarker
instance AWSRequest ListVirtualMFADevices where
type Rs ListVirtualMFADevices =
ListVirtualMFADevicesResponse
request = postQuery iAM
response
= receiveXMLWrapper "ListVirtualMFADevicesResult"
(\ s h x ->
ListVirtualMFADevicesResponse' <$>
(x .@? "Marker") <*> (x .@? "IsTruncated") <*>
(pure (fromEnum s))
<*>
(x .@? "VirtualMFADevices" .!@ mempty >>=
parseXMLList "member"))
instance ToHeaders ListVirtualMFADevices where
toHeaders = const mempty
instance ToPath ListVirtualMFADevices where
toPath = const "/"
instance ToQuery ListVirtualMFADevices where
toQuery ListVirtualMFADevices'{..}
= mconcat
["Action" =: ("ListVirtualMFADevices" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"AssignmentStatus" =: _lvmdAssignmentStatus,
"Marker" =: _lvmdMarker, "MaxItems" =: _lvmdMaxItems]
-- | Contains the response to a successful ListVirtualMFADevices request.
--
-- /See:/ 'listVirtualMFADevicesResponse' smart constructor.
data ListVirtualMFADevicesResponse = ListVirtualMFADevicesResponse'
{ _lvmdrsMarker :: !(Maybe Text)
, _lvmdrsIsTruncated :: !(Maybe Bool)
, _lvmdrsResponseStatus :: !Int
, _lvmdrsVirtualMFADevices :: ![VirtualMFADevice]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListVirtualMFADevicesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lvmdrsMarker'
--
-- * 'lvmdrsIsTruncated'
--
-- * 'lvmdrsResponseStatus'
--
-- * 'lvmdrsVirtualMFADevices'
listVirtualMFADevicesResponse
:: Int -- ^ 'lvmdrsResponseStatus'
-> ListVirtualMFADevicesResponse
listVirtualMFADevicesResponse pResponseStatus_ =
ListVirtualMFADevicesResponse'
{ _lvmdrsMarker = Nothing
, _lvmdrsIsTruncated = Nothing
, _lvmdrsResponseStatus = pResponseStatus_
, _lvmdrsVirtualMFADevices = mempty
}
-- | When 'IsTruncated' is 'true', this element is present and contains the
-- value to use for the 'Marker' parameter in a subsequent pagination
-- request.
lvmdrsMarker :: Lens' ListVirtualMFADevicesResponse (Maybe Text)
lvmdrsMarker = lens _lvmdrsMarker (\ s a -> s{_lvmdrsMarker = a});
-- | A flag that indicates whether there are more items to return. If your
-- results were truncated, you can make a subsequent pagination request
-- using the 'Marker' request parameter to retrieve more items. Note that
-- IAM might return fewer than the 'MaxItems' number of results even when
-- there are more results available. We recommend that you check
-- 'IsTruncated' after every call to ensure that you receive all of your
-- results.
lvmdrsIsTruncated :: Lens' ListVirtualMFADevicesResponse (Maybe Bool)
lvmdrsIsTruncated = lens _lvmdrsIsTruncated (\ s a -> s{_lvmdrsIsTruncated = a});
-- | The response status code.
lvmdrsResponseStatus :: Lens' ListVirtualMFADevicesResponse Int
lvmdrsResponseStatus = lens _lvmdrsResponseStatus (\ s a -> s{_lvmdrsResponseStatus = a});
-- | The list of virtual MFA devices in the current account that match the
-- 'AssignmentStatus' value that was passed in the request.
lvmdrsVirtualMFADevices :: Lens' ListVirtualMFADevicesResponse [VirtualMFADevice]
lvmdrsVirtualMFADevices = lens _lvmdrsVirtualMFADevices (\ s a -> s{_lvmdrsVirtualMFADevices = a}) . _Coerce;
|
olorin/amazonka
|
amazonka-iam/gen/Network/AWS/IAM/ListVirtualMFADevices.hs
|
mpl-2.0
| 7,975
| 0
| 14
| 1,613
| 1,001
| 595
| 406
| 112
| 1
|
{-|
Module : Data.Patent.Citation.Parse
Description : Parses different representations of patent document numbers, particular US formats, into standardized format.
Copyright : (c) Martin Galese, 2017
License : AGPL-3
Maintainer : martin@galese.net
Stability : experimental
Portability : POSIX
-}
module Data.Patent.Citation.Parse
( parseCitation
) where
import Data.Patent.Types
import Data.Text (pack, unpack)
import Protolude
import qualified Text.Parsec as Parsec
usPubAppFormat :: Parsec.Parsec Text () Citation
usPubAppFormat = do
void $ Parsec.string "US"
year <- Parsec.count 4 Parsec.digit
Parsec.optional $ Parsec.char '/'
serialNo <- Parsec.count 7 Parsec.digit
let trimLeadZero = dropWhile (== '0') serialNo -- For some reason, EPO data drops these zeros
serialPart = year <> trimLeadZero
kindPart <- Parsec.optionMaybe (Parsec.many1 Parsec.anyChar)
return $
Citation
{ _citationCountry = "US"
, _citationSerial = pack serialPart
, _citationKind = pack <$> kindPart
, _citationPubDate = Nothing
, _citationSpecialCase = Just $ EPO_US_Pub_App . pack $ (year <> serialNo)
}
epodocFormat :: Parsec.Parsec Text () Citation
epodocFormat = do
countryPart <- Parsec.count 2 Parsec.letter
serialPart <- Parsec.many1 Parsec.digit
kindPart <- Parsec.optionMaybe (Parsec.many1 Parsec.anyChar)
return $
Citation
{ _citationCountry = pack countryPart
, _citationSerial = pack serialPart
, _citationKind = pack <$> kindPart
, _citationPubDate = Nothing
, _citationSpecialCase = Nothing
}
messyUSPatent :: Parsec.Parsec Text () Citation
messyUSPatent = do
Parsec.optional $ do
_ <- countryPhrase
_ <- Parsec.spaces
_ <- patentPhrase
_ <- Parsec.spaces
return ()
serialNo <- commaSepPatNumber
return $
Citation
{ _citationCountry = "US"
, _citationSerial = serialNo
, _citationKind = Nothing
, _citationPubDate = Nothing
, _citationSpecialCase = Nothing
}
lensLikeFormat :: Parsec.Parsec Text () Citation
lensLikeFormat = do
countryPart <- Parsec.count 2 Parsec.letter
_ <- Parsec.char '_'
serialPart <- Parsec.many1 Parsec.digit
_ <- Parsec.char '_'
kindPart <- Parsec.many1 Parsec.anyChar
return $
Citation
{ _citationCountry = pack countryPart
, _citationSerial = pack serialPart
, _citationKind = Just $ pack kindPart
, _citationPubDate = Nothing
, _citationSpecialCase = Nothing
}
countryPhrase :: Parsec.Parsec Text () ()
countryPhrase =
void $
Parsec.choice
[ Parsec.try $ Parsec.string "United States"
, Parsec.try $ Parsec.string "U.S."
, Parsec.string "US"
]
patentPhrase :: Parsec.Parsec Text () ()
patentPhrase = do
_ <- typePhrase
_ <- Parsec.optional $ Parsec.char '.'
_ <- Parsec.spaces
_ <- Parsec.optional numberSignalPhrase
_ <- Parsec.optional $ Parsec.char '.'
_ <- Parsec.spaces
return ()
typePhrase :: Parsec.ParsecT Text u Identity ()
typePhrase =
void $
Parsec.choice
[Parsec.try $ Parsec.string "Pat", Parsec.try $ Parsec.string "Patent"]
numberSignalPhrase :: Parsec.ParsecT Text u Identity ()
numberSignalPhrase =
void $
Parsec.choice
[Parsec.try $ Parsec.string "No", Parsec.try $ Parsec.string "Number"]
jpxNumber :: Parsec.Parsec Text () Citation
jpxNumber = do
_ <- Parsec.string "JP"
emperor <-
Parsec.choice
[Parsec.try $ Parsec.string "S", Parsec.try $ Parsec.string "H"]
serialPart <- Parsec.many1 Parsec.digit
kindPart <- Parsec.optionMaybe (Parsec.many1 Parsec.anyChar)
-- http://www.epo.org/searching-for-patents/helpful-resources/asian/japan/numbering.html
return $
Citation
{ _citationCountry = "JP"
, _citationSerial = pack $ emperor <> serialPart
, _citationKind = pack <$> kindPart
, _citationPubDate = Nothing
, _citationSpecialCase = Just JPX
}
triplet :: Parsec.ParsecT Text u Identity [Char]
triplet = Parsec.optional (Parsec.char ',') >> Parsec.count 3 Parsec.digit
-- only matching "modern" 7 digit series patents
commaSepPatNumber :: Parsec.Parsec Text () Text
commaSepPatNumber = do
firstPart <- Parsec.digit
rest <- Parsec.count 2 triplet
return $ pack (firstPart : concat rest)
patentFormats :: Parsec.Parsec Text () Citation
patentFormats =
Parsec.choice
[ Parsec.try usPubAppFormat
, Parsec.try jpxNumber
, Parsec.try epodocFormat
, Parsec.try messyUSPatent
, Parsec.try lensLikeFormat
]
-- | Parses a variety of textual formats into a normalized Citation structure.
--
-- Formats such as US1234567 or EP1234567 are understood, as are messier variations on "U.S. Pat. No. 1,234,567"
-- For some countries, notably JP, a kind code will basically be required to get any results in Citation. In other cases,
-- like U.S. patents, it is not required.
--
-- Other formats, like US_1234567_A, or US2016/1234567, are also supported.
-- For more information, check out
-- http://www.hawkip.com/advice/variations-of-publication-number-formatting-by-country
-- http://documents.epo.org/projects/babylon/eponet.nsf/0/94AA7EF4AAB18DDEC125806500367F15/$FILE/publ1_20161102_en.pdf
parseCitation :: Text -> Either Parsec.ParseError Citation
parseCitation input = Parsec.parse patentFormats (unpack input) input
|
fros1y/patent-api
|
src/Data/Patent/Citation/Parse.hs
|
agpl-3.0
| 5,332
| 0
| 12
| 1,033
| 1,303
| 660
| 643
| 122
| 1
|
{-
Copyright (C) 2009 Andrejs Sisojevs <andrejs.sisojevs@nextmail.ru>
All rights reserved.
For license and copyright information, see the file COPYRIGHT
-}
--------------------------------------------------------------------------
--------------------------------------------------------------------------
module Text.PCLT.Catalog where
import qualified Data.ByteString.Lazy.UTF8.Unified as Lazy (ByteString)
import qualified Data.ByteString.Lazy.UTF8.Unified as B hiding (ByteString)
import Data.Int
import qualified Data.Map as M
import Data.Map (Map, (!))
import Data.MyHelpers
import Data.Typeable
import Text.PCLT.Config
import Text.PCLT.Template
import Text.PCLT.CommonTypes
type PCLT_CatalogID = Int
data PCLT_Catalog = PCLT_Catalog {
pcltcCatalogID :: PCLT_CatalogID
, pcltcCatalogMap :: PCLT_CatalogMap
-- | It is highly recommended not to change this param
-- values after catalog is formed, since it's easy to
-- spoil catalog content that way.
, pcltcInnerConfig :: PCLT_InnerConfig
}
deriving (Show, Typeable)
catInstMaxLen :: PCLT_Catalog -> Int64
catInstMaxLen = pcsInstaniationResultMaxSize . pcltcInnerConfig
catDfltLng :: PCLT_Catalog -> LanguageName
catDfltLng = pcsDefaultLanguage . pcltcInnerConfig
catStrictOrient :: PCLT_Catalog -> StrictOrient_ofParamsAndCmpsts_onDfltLngTplsSets
catStrictOrient = pcsStrictOrient_ofParamsAndCmpsts_onDfltLngTplsSets . pcltcInnerConfig
catSize :: PCLT_Catalog -> Int
catSize c = M.size $ pcltcCatalogMap c
-----------------------------------------
-- * Common errors related to catalog, used by diffent functions
data TplDefaultLngIsMissing_PCLTE = TplDefaultLngIsMissing_PCLTE PCLT_CompositeKey deriving (Show, Typeable)
data DefaultLngTplComponentsParamsSetsDiffersFromOnesOfNondefault_PCLTE
= DefaultLngTplComponentsParamsSetsDiffersFromOnesOfNondefault_PCLTE PCLT_CompositeKey LanguageName
deriving (Show, Typeable)
data RequiredCompositeIsMissing_PCLTE = RequiredCompositeIsMissing_PCLTE RequiredCompositeKey deriving (Show, Typeable)
data RequiredByRequirerCompositeIsMissing_PCLTE
= RequiredByRequirerCompositeIsMissing_PCLTE RequirerCompositeKey RequiredCompositeIsMissing_PCLTE
deriving (Show, Typeable)
data CompositionCycle_PCLTE = CompositionCycle_PCLTE PCLT_CompositeKey [PCLT_CompositeKey] deriving (Show, Typeable)
data TplUniquenessViol_PCLTE = TplUniquenessViol_PCLTE PCLT_ID [LanguageName] deriving (Show, Typeable)
type MainUnit_SDL = PCLT_ShowDetalizationLevel
type AddedUnit_SDL = PCLT_ShowDetalizationLevel
data DifferentSDLs_PCLTE = DifferentSDLs_PCLTE PCLT_ID (MainUnit_SDL, AddedUnit_SDL) deriving (Show, Typeable)
----
data ErrorWithPCSCatalog a = ErrorWithPCSCatalog PCLT_CatalogID a deriving (Show, Typeable)
-----------------------------------------------------------------
|
Andrey-Sisoyev/haskell-PCLT
|
Text/PCLT/Catalog.hs
|
lgpl-2.1
| 3,286
| 0
| 8
| 772
| 427
| 258
| 169
| 39
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
module Cont( ContT(..), Cont, callCC, cont, runCont ) where
import Prelude (($), (.))
import Base
import Functor
import Applicative
import Monad
import Trans
-- newtype Cont r a = Cont { runCont :: (a -> r) -> r}
-- `a` is intermediate return value in continuation monad. It will be passed
-- to continuation.
-- Note that for Monad, we always "focus" on `a`.
newtype ContT r m a = ContT { runContT :: (a -> m r) -> m r }
type Cont r = ContT r Identity
cont :: ((a -> r) -> r) -> Cont r a
cont f = ContT $ \ c -> Identity (f (runIdentity . c))
runCont :: Cont r a -> (a -> r) -> r
runCont m k = runIdentity $ runContT m (Identity . k)
instance Functor (ContT r m) where
fmap f m = ContT $ \c -> runContT m (c . f)
instance Applicative (ContT r m) where
-- $ x is the simplest suspended computation. The computation does nothing
-- but return the value `x`.
pure x = ContT ($ x)
-- First extract the function and value in the Applicative Context, then
-- return the final value through continuation:c
f <*> v = ContT $ \c -> runContT f $ \g -> runContT v $ (c . g)
instance Monad m => Monad (ContT r m) where
return x = ContT ($ x)
-- For a continuation monad, the final return value `r` is the return value of
-- continuation :`a -> r`. So `c` is always called in the last.
m >>= f = ContT $ \c -> runContT m $ \x -> runContT (f x) c
callCC :: ((a -> ContT r m a1) -> ContT r m a) -> ContT r m a
callCC f = ContT $ \ c -> runContT (f (\ x -> ContT $ \ _ -> c x)) c
|
seckcoder/lang-learn
|
haskell/lambda-calculus/src/Cont.hs
|
unlicense
| 1,580
| 0
| 14
| 405
| 520
| 284
| 236
| 24
| 1
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-
Copyright 2020 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Model where
import Control.Applicative
import Control.Monad
import Data.Aeson
import Data.ByteString (ByteString)
import Data.Text (Text)
import GHC.Generics (Generic)
import System.FilePath (FilePath)
data Project = Project
{ projectName :: Text,
projectSource :: Text,
projectHistory :: Value
}
instance FromJSON Project where
parseJSON (Object v) =
Project <$> v .: "name" <*> v .: "source" <*> v .: "history"
parseJSON _ = mzero
instance ToJSON Project where
toJSON p =
object
[ "name" .= projectName p,
"source" .= projectSource p,
"history" .= projectHistory p,
"type" .= ("project" :: Text)
]
data FileSystemEntryType = Dir | Proj deriving (Eq, Ord, Show)
instance ToJSON FileSystemEntryType where
toJSON Dir = Data.Aeson.String "directory"
toJSON Proj = Data.Aeson.String "project"
instance FromJSON FileSystemEntryType where
parseJSON (Data.Aeson.String "directory") = return $ Dir
parseJSON (Data.Aeson.String "project") = return $ Proj
parseJSON _ = mzero
data FileSystemEntry = FSEntry
{ fsEntryIndex :: Int,
fsEntryName :: Text,
fsEntryType :: FileSystemEntryType,
fsEntryChildren :: Maybe [FileSystemEntry]
}
deriving (Generic, Eq, Ord, Show)
fsEntryJSONOptions :: Options
fsEntryJSONOptions =
defaultOptions
{ fieldLabelModifier = \f -> case f of
"fsEntryIndex" -> "index"
"fsEntryName" -> "name"
"fsEntryType" -> "type"
"fsEntryChildren" -> "children"
_ -> f,
omitNothingFields = True
}
instance ToJSON FileSystemEntry where
toJSON = genericToJSON fsEntryJSONOptions
instance FromJSON FileSystemEntry where
parseJSON = genericParseJSON fsEntryJSONOptions
data CompileResult = CompileResult
{ compileHash :: Text,
compileDeployHash :: Text
}
instance ToJSON CompileResult where
toJSON cr =
object ["hash" .= compileHash cr, "dhash" .= compileDeployHash cr]
data Gallery = Gallery {galleryItems :: [GalleryItem]}
data GalleryItem = GalleryItem
{ galleryItemName :: Text,
galleryItemURL :: Text,
galleryItemCode :: Maybe Text
}
instance ToJSON Gallery where
toJSON g = object ["items" .= galleryItems g]
instance ToJSON GalleryItem where
toJSON item = case galleryItemCode item of
Nothing -> object base
Just code -> object (("code" .= code) : base)
where
base =
[ "name" .= galleryItemName item,
"url" .= galleryItemURL item
]
|
google/codeworld
|
codeworld-server/src/Model.hs
|
apache-2.0
| 3,211
| 0
| 13
| 676
| 700
| 380
| 320
| 74
| 5
|
{-# LANGUAGE OverloadedStrings #-}
module Web.Twitter.Enumerator.Api
( api
, endpoint
, endpointSearch
, UserParam(..)
, ListParam(..)
, mkUserParam
, mkListParam
) where
import Web.Twitter.Enumerator.Types
import Web.Twitter.Enumerator.Monad
import Web.Twitter.Enumerator.Utils
import Network.HTTP.Enumerator
import qualified Network.HTTP.Types as HT
import Data.Enumerator (Iteratee, throwError, liftTrans)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B8
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Class
import Control.Monad.IO.Class (MonadIO (liftIO))
endpoint :: String
endpoint = "https://api.twitter.com/1/"
endpointSearch :: String
endpointSearch = "http://search.twitter.com/"
api :: RequireAuth -- ^ OAuth required?
-> ByteString -- ^ HTTP request method (GET or POST)
-> String -- ^ API Resource URL
-> HT.Query -- ^ Query
-> Iteratee ByteString IO a
-> Iteratee ByteString TW a
api authp m url query iter = do
req <- lift $ apiRequest authp m url query
httpMgr req (handleError iter)
where
handleError iter' st@(HT.Status sc _) _ =
if 200 <= sc && sc < 300
then iter'
else throwError $ HTTPStatusCodeException st
httpMgr :: Request IO
-> (HT.Status
-> HT.ResponseHeaders
-> Iteratee ByteString IO a)
-> Iteratee ByteString TW a
httpMgr req iterf = do
mgr <- lift getManager
liftTrans $ http req iterf mgr
apiRequest :: RequireAuth -> ByteString -> String -> HT.Query -> TW (Request IO)
apiRequest authp m uri query = do
p <- asks twProxy
req <- liftIO $ parseUrl uri >>= \r ->
return $ r { method = m, queryString = query, proxy = p }
signOAuthTW authp req
data UserParam = UserIdParam UserId | ScreenNameParam String
deriving (Show, Eq)
data ListParam = ListIdParam Integer | ListNameParam String
deriving (Show, Eq)
mkUserParam :: UserParam -> HT.Query
mkUserParam (UserIdParam uid) = [("user_id", toMaybeByteString uid)]
mkUserParam (ScreenNameParam sn) = [("screen_name", Just . B8.pack $ sn)]
mkListParam :: ListParam -> HT.Query
mkListParam (ListIdParam lid) = [("list_id", toMaybeByteString lid)]
mkListParam (ListNameParam listname) =
[("slug", Just . B8.pack $ lstName),
("owner_screen_name", Just . B8.pack $ screenName)]
where
(screenName, ln) = span (/= '/') listname
lstName = drop 1 ln
|
himura/twitter-enumerator
|
Web/Twitter/Enumerator/Api.hs
|
bsd-2-clause
| 2,480
| 0
| 12
| 537
| 742
| 411
| 331
| 65
| 2
|
module Propellor.Property.Tor where
import Propellor.Base
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Apt as Apt
import qualified Propellor.Property.Service as Service
import qualified Propellor.Property.ConfFile as ConfFile
import Utility.FileMode
import Utility.DataUnits
import System.Posix.Files
import Data.Char
import Data.List
type HiddenServiceName = String
type NodeName = String
-- | Sets up a tor bridge. (Not a relay or exit node.)
--
-- Uses port 443
isBridge :: Property NoInfo
isBridge = configured
[ ("BridgeRelay", "1")
, ("Exitpolicy", "reject *:*")
, ("ORPort", "443")
]
`describe` "tor bridge"
`requires` server
-- | Sets up a tor relay.
--
-- Uses port 443
isRelay :: Property NoInfo
isRelay = configured
[ ("BridgeRelay", "0")
, ("Exitpolicy", "reject *:*")
, ("ORPort", "443")
]
`describe` "tor relay"
`requires` server
-- | Makes the tor node be named, with a known private key.
--
-- This can be moved to a different IP without needing to wait to
-- accumulate trust.
named :: NodeName -> Property HasInfo
named n = configured [("Nickname", n')]
`describe` ("tor node named " ++ n')
`requires` torPrivKey (Context ("tor " ++ n))
where
n' = saneNickname n
torPrivKey :: Context -> Property HasInfo
torPrivKey context = f `File.hasPrivContent` context
`onChange` File.ownerGroup f user (userGroup user)
-- install tor first, so the directory exists with right perms
`requires` Apt.installed ["tor"]
where
f = "/var/lib/tor/keys/secret_id_key"
-- | A tor server (bridge, relay, or exit)
-- Don't use if you just want to run tor for personal use.
server :: Property NoInfo
server = configured [("SocksPort", "0")]
`requires` Apt.installed ["tor", "ntp"]
`describe` "tor server"
-- | Specifies configuration settings. Any lines in the config file
-- that set other values for the specified settings will be removed,
-- while other settings are left as-is. Tor is restarted when
-- configuration is changed.
configured :: [(String, String)] -> Property NoInfo
configured settings = File.fileProperty "tor configured" go mainConfig
`onChange` restarted
where
ks = map fst settings
go ls = sort $ map toconfig $
filter (\(k, _) -> k `notElem` ks) (map fromconfig ls)
++ settings
toconfig (k, v) = k ++ " " ++ v
fromconfig = separate (== ' ')
data BwLimit
= PerSecond String
| PerDay String
| PerMonth String
-- | Limit incoming and outgoing traffic to the specified
-- amount each.
--
-- For example, PerSecond "30 kibibytes" is the minimum limit
-- for a useful relay.
bandwidthRate :: BwLimit -> Property NoInfo
bandwidthRate (PerSecond s) = bandwidthRate' s 1
bandwidthRate (PerDay s) = bandwidthRate' s (24*60*60)
bandwidthRate (PerMonth s) = bandwidthRate' s (31*24*60*60)
bandwidthRate' :: String -> Integer -> Property NoInfo
bandwidthRate' s divby = case readSize dataUnits s of
Just sz -> let v = show (sz `div` divby) ++ " bytes"
in configured [("BandwidthRate", v)]
`describe` ("tor BandwidthRate " ++ v)
Nothing -> property ("unable to parse " ++ s) noChange
hiddenServiceAvailable :: HiddenServiceName -> Int -> Property NoInfo
hiddenServiceAvailable hn port = hiddenServiceHostName $ hiddenService hn port
where
hiddenServiceHostName p = adjustPropertySatisfy p $ \satisfy -> do
r <- satisfy
h <- liftIO $ readFile (varLib </> hn </> "hostname")
warningMessage $ unwords ["hidden service hostname:", h]
return r
hiddenService :: HiddenServiceName -> Int -> Property NoInfo
hiddenService hn port = ConfFile.adjustSection
(unwords ["hidden service", hn, "available on port", show port])
(== oniondir)
(not . isPrefixOf "HiddenServicePort")
(const [oniondir, onionport])
(++ [oniondir, onionport])
mainConfig
`onChange` restarted
where
oniondir = unwords ["HiddenServiceDir", varLib </> hn]
onionport = unwords ["HiddenServicePort", show port, "127.0.0.1:" ++ show port]
hiddenServiceData :: IsContext c => HiddenServiceName -> c -> Property HasInfo
hiddenServiceData hn context = combineProperties desc
[ installonion "hostname"
, installonion "private_key"
]
where
desc = unwords ["hidden service data available in", varLib </> hn]
installonion f = withPrivData (PrivFile $ varLib </> hn </> f) context $ \getcontent ->
property desc $ getcontent $ install $ varLib </> hn </> f
install f privcontent = ifM (liftIO $ doesFileExist f)
( noChange
, ensureProperties
[ property desc $ makeChange $ do
createDirectoryIfMissing True (takeDirectory f)
writeFileProtected f (unlines (privDataLines privcontent))
, File.mode (takeDirectory f) $ combineModes
[ownerReadMode, ownerWriteMode, ownerExecuteMode]
, File.ownerGroup (takeDirectory f) user (userGroup user)
, File.ownerGroup f user (userGroup user)
]
)
restarted :: Property NoInfo
restarted = Service.restarted "tor"
mainConfig :: FilePath
mainConfig = "/etc/tor/torrc"
varLib :: FilePath
varLib = "/var/lib/tor"
varRun :: FilePath
varRun = "/var/run/tor"
user :: User
user = User "debian-tor"
type NickName = String
-- | Convert String to a valid tor NickName.
saneNickname :: String -> NickName
saneNickname s
| null n = "unnamed"
| otherwise = n
where
legal c = isNumber c || isAsciiUpper c || isAsciiLower c
n = take 19 $ filter legal s
|
np/propellor
|
src/Propellor/Property/Tor.hs
|
bsd-2-clause
| 5,305
| 66
| 18
| 912
| 1,546
| 839
| 707
| 116
| 2
|
{-# LANGUAGE DataKinds, ScopedTypeVariables #-}
module Codes.ICFP_Paper where
import Haskell.ArraySig (M)
import Data.Sized.Fin
import Data.ListMatrix
import System.Directory (doesFileExist)
import Codec.Compression.BZip (decompress)
import qualified Data.ByteString.Lazy as L
import Data.List (intercalate)
import Control.Arrow (second)
import GHC.TypeLits
import Data.Binary (decode)
import System.IO.Unsafe (unsafePerformIO)
h_4096_7168 :: ListMatrix Bool
h_4096_7168 = expand h_4096_7168_compact
-- this g has a lot more ones in it than h does
g_4096_7168 :: M Bool
g_4096_7168 =
-- prefer loading from the decompressed version
let srcs = concatMap (\(f,p) -> [(f,p),(f,"src/"++p)]) $
map (second ("Codes/"++)) $
[(id,"g_4096_7168.bin")
,(decompress,"g_4096_7168.bin.bz2")
]
go [] = error $ "hacky load of g_4096_7168 failed, could find none of " ++ intercalate " " (map snd srcs)
go ((f,path):srcs) = doesFileExist path >>= \b -> if b
then (decode.f) `fmap` L.readFile path
else go srcs
in unsafePerformIO $ go srcs
h_4096_7168_compact :: ListMatrix (Maybe (Fin 256))
h_4096_7168_compact = fmap cleanup $ listMatrix
[ [ nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, 0 , nul, nul, nul, nul, nul, nul, nul, 0 , nul, nul, 160 ]
, [ nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, 0 , nul, nul, nul, nul, nul, nul, 0 , 0 , nul, nul ]
, [ nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, 0 , nul, nul, nul, nul, nul, nul, 0 , 0 , nul ]
, [ nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, 0 , nul, nul, nul, nul, nul, nul, 0 , 0 ]
, [ 248, 12 , 111, nul, 0 , nul, nul, nul, 0 , nul, nul, nul, 0 , nul, nul, nul, nul, nul, nul, nul, 0 , nul, nul, nul, 241, 185, 251, nul ]
, [ nul, 55 , 12 , 227, nul, 0 , nul, nul, nul, 0 , nul, nul, nul, 0 , nul, nul, nul, nul, nul, nul, nul, 0 , nul, nul, nul, 182, 249, 65 ]
, [ 23 , nul, 147, 54 , nul, nul, 0 , nul, nul, nul, 0 , nul, nul, nul, 0 , nul, nul, nul, nul, nul, nul, nul, 0 , nul, 214, nul, 35 , 167 ]
, [ 99 , 105, nul, 133, nul, nul, nul, 0 , nul, nul, nul, 0 , nul, nul, nul, 0 , nul, nul, nul, nul, nul, nul, nul, 0 , 7 , 31 , nul, 162 ]
, [ 0 , nul, nul, nul, 66 , nul, 173, 42 , 0 , nul, nul, nul, nul, nul, 209, 103, nul, nul, nul, nul, 90 , 184, nul, nul, 0 , nul, nul, nul ]
, [ nul, 0 , nul, nul, 243, 42 , nul, 52 , nul, 0 , nul, nul, 141, nul, nul, 70 , nul, nul, nul, nul, nul, 237, 77 , nul, nul, 0 , nul, nul ]
, [ nul, nul, 0 , nul, 20 , 197, 93 , nul, nul, nul, 0 , nul, 84 , 206, nul, nul, nul, nul, nul, nul, nul, nul, 122, 67 , nul, nul, 0 , nul ]
, [ nul, nul, nul, 0 , nul, 97 , 91 , 17 , nul, nul, nul, 0 , nul, 164, 11 , nul, nul, nul, nul, nul, 125, nul, nul, 237, nul, nul, nul, 0 ]
]
where nul = negate 1
cleanup :: Int -> Maybe (Fin 256)
cleanup i | i < 0 = Nothing
| otherwise = Just $ toEnum $ fromEnum i
expand :: forall n. SingI n => ListMatrix (Maybe (Fin n)) -> ListMatrix Bool
expand = ListMatrix
. concatMap (foldr (zipWith (++)) (replicate size []))
. unListMatrix
. fmap (unListMatrix . rotated) where
size :: Int
size = fromEnum $ fromNat (sing :: TNat n)
rotated :: Maybe (Fin n) -> ListMatrix Bool
rotated e = case e of
Nothing -> zeroes
Just fin -> case fromEnum fin of
0 -> ones -- memoize a common case
i -> rotateMatrix i (size,ones)
zeroes,ones :: ListMatrix Bool
zeroes = ListMatrix $ replicate size $ replicate size False
ones = fmap (==1) $ identity size
rotateMatrix :: Int -> (Int,ListMatrix a) -> ListMatrix a
rotateMatrix by (width,ListMatrix rows) =
ListMatrix $ map rotateList rows where
rotateList :: [a] -> [a]
rotateList l = let (a,b) = splitAt (width - (by `mod` width)) l in b ++ a
h_7_20 =fmap (/=0) $ listMatrix
[ [1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
, [1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
, [1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
, [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
, [1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
, [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
, [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
, [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
, [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
, [1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
, [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
, [0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
, [1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
]
g_7_20 = fmap (/=0) $ listMatrix
[ [1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1]
, [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1]
, [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]
, [0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1]
, [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1]
, [0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1]
, [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0]
]
|
ku-fpg/ldpc-blob
|
src/Codes/ICFP_Paper.hs
|
bsd-2-clause
| 5,409
| 0
| 16
| 1,516
| 3,138
| 1,982
| 1,156
| 87
| 3
|
{-# LANGUAGE CPP #-}
#ifndef MIN_VERSION_base
#define MIN_VERSION_base(x,y,z) 0
#endif
#ifndef MIN_VERSION_bytestring
#define MIN_VERSION_bytestring(x,y,z) 0
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Data.Serialize.Put
-- Copyright : Lennart Kolmodin, Galois Inc. 2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Trevor Elliott <trevor@galois.com>
-- Stability :
-- Portability :
--
-- The Put monad. A monad for efficiently constructing bytestrings.
--
-----------------------------------------------------------------------------
module Data.Serialize.Put (
-- * The Put type
Put
, PutM(..)
, Putter
, runPut
, runPutM
, runPutLazy
, runPutMLazy
, putBuilder
, execPut
-- * Flushing the implicit parse state
, flush
-- * Primitives
, putWord8
, putByteString
, putLazyByteString
#if MIN_VERSION_bytestring(0,10,4)
, putShortByteString
#endif
-- * Big-endian primitives
, putWord16be
, putWord32be
, putWord64be
-- * Little-endian primitives
, putWord16le
, putWord32le
, putWord64le
-- * Host-endian, unaligned writes
, putWordhost
, putWord16host
, putWord32host
, putWord64host
-- * Containers
, putTwoOf
, putListOf
, putIArrayOf
, putSeqOf
, putTreeOf
, putMapOf
, putIntMapOf
, putSetOf
, putIntSetOf
, putMaybeOf
, putEitherOf
, putNested
) where
#if MIN_VERSION_bytestring(0,10,2)
import Data.ByteString.Builder (Builder, toLazyByteString)
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Builder.Extra as B
#elif MIN_VERSION_bytestring(0,10,0)
import Data.ByteString.Lazy.Builder (Builder, toLazyByteString)
import qualified Data.ByteString.Lazy.Builder as B
import qualified Data.ByteString.Lazy.Builder.Extras as B
#else
#error "cereal requires bytestring >= 0.10.0.0"
#endif
#if MIN_VERSION_bytestring(0,10,4)
import qualified Data.ByteString.Short as BS
#endif
import qualified Control.Applicative as A
import Data.Array.Unboxed
import qualified Data.Monoid as M
import qualified Data.Foldable as F
import Data.Word
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IntSet
import qualified Data.Map as Map
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import qualified Data.Tree as T
#if !(MIN_VERSION_base(4,8,0))
import Control.Applicative
import Data.Foldable (foldMap)
import Data.Monoid
#endif
------------------------------------------------------------------------
-- XXX Strict in builder only.
data PairS a = PairS a !Builder
sndS :: PairS a -> Builder
sndS (PairS _ b) = b
-- | The PutM type. A Writer monad over the efficient Builder monoid.
newtype PutM a = Put { unPut :: PairS a }
-- | Put merely lifts Builder into a Writer monad, applied to ().
type Put = PutM ()
type Putter a = a -> Put
instance Functor PutM where
fmap f m = Put $ let PairS a w = unPut m in PairS (f a) w
{-# INLINE fmap #-}
instance A.Applicative PutM where
pure a = Put (PairS a M.mempty)
{-# INLINE pure #-}
m <*> k = Put $
let PairS f w = unPut m
PairS x w' = unPut k
in PairS (f x) (w `M.mappend` w')
{-# INLINE (<*>) #-}
m *> k = Put $
let PairS _ w = unPut m
PairS b w' = unPut k
in PairS b (w `M.mappend` w')
{-# INLINE (*>) #-}
instance Monad PutM where
return = pure
{-# INLINE return #-}
m >>= k = Put $
let PairS a w = unPut m
PairS b w' = unPut (k a)
in PairS b (w `M.mappend` w')
{-# INLINE (>>=) #-}
(>>) = (*>)
{-# INLINE (>>) #-}
tell :: Putter Builder
tell b = Put $! PairS () b
{-# INLINE tell #-}
putBuilder :: Putter Builder
putBuilder = tell
{-# INLINE putBuilder #-}
-- | Run the 'Put' monad
execPut :: PutM a -> Builder
execPut = sndS . unPut
{-# INLINE execPut #-}
-- | Run the 'Put' monad with a serialiser
runPut :: Put -> S.ByteString
runPut = L.toStrict . runPutLazy
{-# INLINE runPut #-}
-- | Run the 'Put' monad with a serialiser and get its result
runPutM :: PutM a -> (a, S.ByteString)
runPutM (Put (PairS f s)) = (f, L.toStrict (toLazyByteString s))
{-# INLINE runPutM #-}
-- | Run the 'Put' monad with a serialiser
runPutLazy :: Put -> L.ByteString
runPutLazy = toLazyByteString . sndS . unPut
{-# INLINE runPutLazy #-}
-- | Run the 'Put' monad with a serialiser
runPutMLazy :: PutM a -> (a, L.ByteString)
runPutMLazy (Put (PairS f s)) = (f, toLazyByteString s)
{-# INLINE runPutMLazy #-}
------------------------------------------------------------------------
-- | Pop the ByteString we have constructed so far, if any, yielding a
-- new chunk in the result ByteString.
flush :: Put
flush = tell B.flush
{-# INLINE flush #-}
-- | Efficiently write a byte into the output buffer
putWord8 :: Putter Word8
putWord8 = tell . B.word8
{-# INLINE putWord8 #-}
-- | An efficient primitive to write a strict ByteString into the output buffer.
-- It flushes the current buffer, and writes the argument into a new chunk.
putByteString :: Putter S.ByteString
putByteString = tell . B.byteString
{-# INLINE putByteString #-}
#if MIN_VERSION_bytestring(0,10,4)
putShortByteString :: Putter BS.ShortByteString
putShortByteString = tell . B.shortByteString
#endif
-- | Write a lazy ByteString efficiently, simply appending the lazy
-- ByteString chunks to the output buffer
putLazyByteString :: Putter L.ByteString
putLazyByteString = tell . B.lazyByteString
{-# INLINE putLazyByteString #-}
-- | Write a Word16 in big endian format
putWord16be :: Putter Word16
putWord16be = tell . B.word16BE
{-# INLINE putWord16be #-}
-- | Write a Word16 in little endian format
putWord16le :: Putter Word16
putWord16le = tell . B.word16LE
{-# INLINE putWord16le #-}
-- | Write a Word32 in big endian format
putWord32be :: Putter Word32
putWord32be = tell . B.word32BE
{-# INLINE putWord32be #-}
-- | Write a Word32 in little endian format
putWord32le :: Putter Word32
putWord32le = tell . B.word32LE
{-# INLINE putWord32le #-}
-- | Write a Word64 in big endian format
putWord64be :: Putter Word64
putWord64be = tell . B.word64BE
{-# INLINE putWord64be #-}
-- | Write a Word64 in little endian format
putWord64le :: Putter Word64
putWord64le = tell . B.word64LE
{-# INLINE putWord64le #-}
------------------------------------------------------------------------
-- | /O(1)./ Write a single native machine word. The word is
-- written in host order, host endian form, for the machine you're on.
-- On a 64 bit machine the Word is an 8 byte value, on a 32 bit machine,
-- 4 bytes. Values written this way are not portable to
-- different endian or word sized machines, without conversion.
--
putWordhost :: Putter Word
putWordhost = tell . B.wordHost
{-# INLINE putWordhost #-}
-- | /O(1)./ Write a Word16 in native host order and host endianness.
-- For portability issues see @putWordhost@.
putWord16host :: Putter Word16
putWord16host = tell . B.word16Host
{-# INLINE putWord16host #-}
-- | /O(1)./ Write a Word32 in native host order and host endianness.
-- For portability issues see @putWordhost@.
putWord32host :: Putter Word32
putWord32host = tell . B.word32Host
{-# INLINE putWord32host #-}
-- | /O(1)./ Write a Word64 in native host order
-- On a 32 bit machine we write two host order Word32s, in big endian form.
-- For portability issues see @putWordhost@.
putWord64host :: Putter Word64
putWord64host = tell . B.word64Host
{-# INLINE putWord64host #-}
-- Containers ------------------------------------------------------------------
encodeListOf :: (a -> Builder) -> [a] -> Builder
encodeListOf f = -- allow inlining with just a single argument
\xs -> execPut (putWord64be (fromIntegral $ length xs)) `M.mappend`
F.foldMap f xs
{-# INLINE encodeListOf #-}
putTwoOf :: Putter a -> Putter b -> Putter (a,b)
putTwoOf pa pb (a,b) = pa a >> pb b
{-# INLINE putTwoOf #-}
putListOf :: Putter a -> Putter [a]
putListOf pa = \l -> do
putWord64be (fromIntegral (length l))
mapM_ pa l
{-# INLINE putListOf #-}
putIArrayOf :: (Ix i, IArray a e) => Putter i -> Putter e -> Putter (a i e)
putIArrayOf pix pe a = do
putTwoOf pix pix (bounds a)
putListOf pe (elems a)
{-# INLINE putIArrayOf #-}
putSeqOf :: Putter a -> Putter (Seq.Seq a)
putSeqOf pa = \s -> do
putWord64be (fromIntegral $ Seq.length s)
F.mapM_ pa s
{-# INLINE putSeqOf #-}
putTreeOf :: Putter a -> Putter (T.Tree a)
putTreeOf pa =
tell . go
where
go (T.Node x cs) = execPut (pa x) `M.mappend` encodeListOf go cs
{-# INLINE putTreeOf #-}
putMapOf :: Ord k => Putter k -> Putter a -> Putter (Map.Map k a)
putMapOf pk pa = putListOf (putTwoOf pk pa) . Map.toAscList
{-# INLINE putMapOf #-}
putIntMapOf :: Putter Int -> Putter a -> Putter (IntMap.IntMap a)
putIntMapOf pix pa = putListOf (putTwoOf pix pa) . IntMap.toAscList
{-# INLINE putIntMapOf #-}
putSetOf :: Putter a -> Putter (Set.Set a)
putSetOf pa = putListOf pa . Set.toAscList
{-# INLINE putSetOf #-}
putIntSetOf :: Putter Int -> Putter IntSet.IntSet
putIntSetOf pix = putListOf pix . IntSet.toAscList
{-# INLINE putIntSetOf #-}
putMaybeOf :: Putter a -> Putter (Maybe a)
putMaybeOf _ Nothing = putWord8 0
putMaybeOf pa (Just a) = putWord8 1 >> pa a
{-# INLINE putMaybeOf #-}
putEitherOf :: Putter a -> Putter b -> Putter (Either a b)
putEitherOf pa _ (Left a) = putWord8 0 >> pa a
putEitherOf _ pb (Right b) = putWord8 1 >> pb b
{-# INLINE putEitherOf #-}
-- | Put a nested structure by first putting a length
-- field and then putting the encoded value.
putNested :: Putter Int -> Put -> Put
putNested putLen putVal = do
let bs = runPut putVal
putLen (S.length bs)
putByteString bs
|
fpco/fpco-cereal
|
src/Data/Serialize/Put.hs
|
bsd-3-clause
| 10,288
| 0
| 13
| 2,358
| 2,113
| 1,165
| 948
| -1
| -1
|
{-# LANGUAGE RecordWildCards #-}
--------------------------------------------------------------------------------
-- |
-- Module : HEP.Data.LHEF
-- Copyright : (c) 2014 - 2015 Chan Beom Park
-- License : BSD-style
-- Maintainer : Chan Beom Park <cbpark@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-- Helper functions to use in analyses of LHEF data files.
--
--------------------------------------------------------------------------------
module HEP.Data.LHEF
(
module LT
, module LP
, module HK
, module LV
, module TV
, module PI
, energyOf
, idOf
, is
, finalStates
, initialStates
, getDaughters
, particlesFrom
) where
import Control.Monad.Trans.Reader
import qualified Data.IntMap as M
import HEP.Kinematics as HK
import HEP.Kinematics.Vector.LorentzTVector as TV (setXYM)
import HEP.Kinematics.Vector.LorentzVector as LV (setEtaPhiPtM,
setXYZT)
import HEP.Particle.ID as PI
import HEP.Data.LHEF.Parser as LP
import HEP.Data.LHEF.Type as LT
energyOf :: Particle -> Double
energyOf Particle { pup = (_, _, _, e, _) } = e
idOf :: Particle -> Int
idOf Particle { .. } = idup
is :: Particle -> ParticleType -> Bool
p `is` pid = ((`elem` getParType pid) . abs . idup) p
initialStates :: Reader EventEntry [Particle]
initialStates = M.elems <$> asks (M.filter (\Particle { .. } -> fst mothup == 1))
finalStates :: Reader EventEntry [Particle]
finalStates = M.elems <$> asks (M.filter (\Particle { .. } -> istup == 1))
particlesFrom :: ParticleType -> Reader EventEntry [[Particle]]
particlesFrom pid = asks (M.keys . M.filter (`is` pid)) >>= mapM getDaughters
getDaughters :: Int -> Reader EventEntry [Particle]
getDaughters i = do
pm <- ask
daughters <- asks $ M.filter (\Particle { .. } -> fst mothup == i)
return $ M.foldrWithKey
(\k p acc -> case istup p of
1 -> p : acc
_ -> runReader (getDaughters k) pm ++ acc) []
daughters
|
cbpark/lhef-tools
|
src/HEP/Data/LHEF.hs
|
bsd-3-clause
| 2,239
| 0
| 17
| 673
| 563
| 327
| 236
| 46
| 2
|
{-# LANGUAGE DataKinds #-}
module Web.Spock.Routing where
import Control.Monad.Trans
import Data.HVect hiding (head)
import qualified Data.Text as T
import qualified Network.Wai as Wai
import Web.Routing.Combinators
import Web.Spock.Action
import Web.Spock.Internal.Wire (SpockMethod (..))
class RouteM t where
addMiddleware :: Monad m => Wai.Middleware -> t ctx m ()
withPrehook :: MonadIO m => ActionCtxT ctx m ctx' -> t ctx' m () -> t ctx m ()
wireAny :: Monad m => SpockMethod -> ([T.Text] -> ActionCtxT ctx m ()) -> t ctx m ()
wireRoute ::
(Monad m, HasRep xs) =>
SpockMethod ->
Path xs ps ->
HVectElim xs (ActionCtxT ctx m ()) ->
t ctx m ()
|
agrafix/Spock
|
Spock-core/src/Web/Spock/Routing.hs
|
bsd-3-clause
| 678
| 0
| 14
| 138
| 263
| 142
| 121
| 19
| 0
|
{-# LANGUAGE OverloadedStrings #-}
-- ^
-- Common functionality for the persistence layer
module Persistence.Common where
import Control.Monad (join, (>=>))
import Control.Monad.IO.Class
import Data.Aeson as AESON
import Data.Bifunctor
import Data.Bson as BSON
import Data.Digest.Pure.SHA
import Data.List (find, findIndex, foldl, nub)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time (getCurrentTime)
import Types.Common
import Util.Constants
-- ^
-- Extract the record fields
getDocument :: Record -> Document
getDocument (Record xs) = xs
-- ^
-- Case analysis for the @ApiItem@ type
apiItem :: (e -> c) -> (a -> c) -> ApiItem e a -> c
apiItem f _ (Fail e) = f e
apiItem _ g (Succ a) = g a
-- ^
-- Create a field definition
mkFieldDef
:: Val a
=> Label -> Bool -> Bool -> Bool -> Maybe a -> (Label, FieldDefinition)
mkFieldDef name required isId isDate defaultValue =
(name, FieldDefinition name required (val <$> defaultValue) isId isDate)
-- ^
-- Create a definition for an id field used as a foreign key
mkIdDef :: Label -> (Label, FieldDefinition)
mkIdDef name = mkFieldDef name True True False (Nothing :: Maybe String)
-- ^
-- Create a definition for a required field without a default value
mkReqDef' :: Label -> (Label, FieldDefinition)
mkReqDef' name = mkFieldDef name True False False (Nothing :: Maybe String)
-- ^
-- Create a definition for a required field
mkReqDef :: Val a => Label -> a -> (Label, FieldDefinition)
mkReqDef name v = mkFieldDef name True False False (Just v)
-- ^
-- Create a definition for an optional field without a default value
mkOptDef' :: Label -> (Label, FieldDefinition)
mkOptDef' name = mkFieldDef name False False False (Nothing :: Maybe String)
-- ^
-- Create a definition for an optional field
mkOptDef :: Val a => Label -> a -> (Label, FieldDefinition)
mkOptDef name v = mkFieldDef name False False False (Just v)
-- ^
-- Create a definition for a date optional field
mkDateDef' :: Label -> (Label, FieldDefinition)
mkDateDef' name = mkFieldDef name False False True (Nothing :: Maybe String)
-- ^
-- Validate a record against it's definition
validateRecord :: RecordDefinition -> Record -> (Record, ValidationResult)
validateRecord def r = (r, ValidationErrors $ catMaybes results)
where
names = nub $ Map.keys (recordFields def) ++ recordLabels r
results = validateField True def r <$> names
validateField :: Bool -> RecordDefinition -> Record -> Label -> Maybe Field
validateField ignoreId def r name
| ignoreId && name == idLabel = Nothing
| name `elem` ignore = Nothing
| not (Map.member name fields) = Just (mkField "Field is not allowed")
| isRequired && not (hasValue name r) && noDefault =
Just (mkField "Field is required")
| otherwise = Nothing
where
fields = recordFields def
ignore = [updatedAtLabel, createdAtLabel]
fieldDef = fromJust $ Map.lookup name fields
isRequired = fieldRequired fieldDef
noDefault = isNothing (fieldDefault fieldDef)
mkField :: String -> Field
mkField msg = name =: msg
-- ^
-- Populate defaults for all missing fields that have a default value
populateDefaults :: RecordDefinition -> Record -> Record
populateDefaults def r = Map.foldl populate r defaults
where
defaults = Map.filter (isJust . fieldDefault) (recordFields def)
populate acc field = modField (fieldLabel field) (set field) acc
set field = fromMaybe (fieldDefault field)
-- ^
-- Get the names of all fields in a record
recordLabels :: Record -> [Label]
recordLabels (Record xs) = label <$> xs
-- ^
-- Set the value of the id field
setIdValue
:: Val a
=> a -> Record -> Record
setIdValue = setValue idLabel
-- ^
-- Get the value of the id field
getIdValue :: Record -> Maybe RecordId
getIdValue = getValue idLabel
-- ^
-- Get the value of the id field
getIdValue' :: Record -> RecordId
getIdValue' = fromJust . getValue idLabel
-- ^
-- Return true if the value of a field is a 'True' value
isValueOn :: Label -> Record -> Bool
isValueOn name record = isJust bval && fromJust bval
where
bval :: Maybe Bool
bval = getValue name record
-- ^
-- Set the value of a field to the current time
setTimestamp'
:: MonadIO m
=> Text -> Record -> m Record
setTimestamp' name r = do
time <- liftIO getCurrentTime
return (setValue name time r)
-- ^
-- Set the value of the updatedAt field
setUpdatedAt
:: MonadIO m
=> Record -> m Record
setUpdatedAt = setTimestamp' updatedAtLabel
-- ^
-- Set the value of the createdAt field
setCreatedAt
:: MonadIO m
=> Record -> m Record
setCreatedAt = setTimestamp' createdAtLabel
-- ^
-- Set the updatedAt field. For new records also set a createdAt field.
setTimestamp
:: MonadIO m
=> Bool -> Record -> m Record
setTimestamp isNew =
if isNew
then setUpdatedAt >=> setCreatedAt
else setUpdatedAt
-- ^
-- Modify the value of a field or remove it
modField
:: (Val a, Val b)
=> Label -> (Maybe a -> Maybe b) -> Record -> Record
modField name f r =
case f (getValue name r) of
Nothing -> delField name r
Just v -> setValue name v r
-- ^
-- Change the name of a field if it exists
renameField :: Label -> Label -> Record -> Record
renameField old new (Record doc) = withField old doc Record rename
where
rename :: ([Field], Field, [Field]) -> (Int, Document) -> Record
rename (xs, _ := v, ys) _ = Record $ xs ++ [new := v] ++ ys
-- ^
-- Get a field by name. Nested fields are supported.
--
-- >>> getField "inner.email" (Record [ inner : [ email : "bson@email.com" ]])
-- Just ("email" : "bson@email.com")
--
-- >>> getField "_id" (Record [_id : "123"])
-- Just (_id : "123")
--
-- >>> getField "email" (Record [_id : "123"])
-- Nothing
--
getField :: Label -> Record -> Maybe Field
getField name (Record d) = findField d (splitAtDot name)
where
findField _ [] = error "no field specified"
findField doc [fname] = find ((fname ==) . label) doc
findField doc (fname:ns) = withField fname doc (const Nothing) (process ns)
process ns (_, y, _) _ = findNested y (head ns)
findNested f@(k := v) fname
| valIsDoc v = getField fname (docToRec k f)
| otherwise = Nothing
-- ^
-- Get the value of a field by name. Nested fields are supported.
--
-- >>> getValue "inner.email" (Record [ inner : [ email : "bson@email.com" ]])
-- Just "bson@email.com"
--
-- >>> getValue "_id" (Record [_id : "123"])
-- Just "123"
--
-- >>> getValue "email" (Record [_id : "123"])
-- Nothing
--
-- >>> getValue "email" (Record [email : Null])
-- Nothing
--
getValue
:: Val a
=> Label -> Record -> Maybe a
getValue name r = join $ get <$> getField name r
where
get
:: Val a
=> Field -> Maybe a
get (_ := v) = cast v
-- ^
-- Get the value of a field by name. Nested fields are supported.
getValue' :: Val a => Label -> Record -> a
getValue' name = fromJust . getValue name
-- ^
-- Set a field in a record. Overwrite the existing value if any.
setField :: Field -> Record -> Record
setField field = flip mergeRecords (Record [field])
-- ^
-- Set the value of a field in a record. Create the field if necessary.
setValue
:: Val a
=> Label -> a -> Record -> Record
setValue fname fvalue = setField (mkField $ T.split (== '.') fname)
where
mkField [] = error "no field name specified"
mkField [name] = name =: fvalue
mkField (name:ns) = name =: mkField ns
-- ^
-- Delete a field by name
delField :: Label -> Record -> Record
delField = excludeFields . (: [])
-- ^
-- Set the value of a field to @Null@.
-- If the field does not exist it will be created.
delValue :: Label -> Record -> Record
delValue = flip setValue BSON.Null
-- ^
-- Determine whether a field exists within a record
hasField :: Label -> Record -> Bool
hasField name = isJust . getField name
-- ^
-- Determine whether a field exists within a record
-- and it has a non-null value
hasValue :: Label -> Record -> Bool
hasValue name r = hasField name r && has (getValue name r)
where
has Nothing = False
has (Just BSON.Null) = False
has _ = True
-- ^
-- Merge two records with the record on the right overwriting any
-- existing fields in the left record. Nested records are supported.
mergeRecords :: Record -> Record -> Record
mergeRecords (Record d1) (Record d2) = Record $ foldl add d1 d2
where
add doc field@(k := _) = withField k doc (++ [field]) (process field)
process field (xs, _, ys) (i, d) = xs ++ [new (d !! i) field] ++ ys
new lf@(lk := lv) rf@(rk := rv)
| valIsDoc lv && valIsDoc rv =
rk := recToDoc (mergeRecords (docToRec lk lf) (docToRec rk rf))
| otherwise = rk := rv
-- ^
-- Replace one record with another keeping some fields unmodified
replaceRecords :: [Label] -> Record -> Record -> Record
replaceRecords preserveFields r1 r2 =
mergeRecords
(excludeFields preserveFields r2)
(includeFields preserveFields r1)
-- ^
-- Exclude all specified fields from a record
excludeFields :: [Label] -> Record -> Record
excludeFields keys (Record d) =
Record $ foldl remove d (splitAtDot <$> keys)
where
remove _ [] = error "excludeFields: no field name specified"
remove doc [name] = filter (\(k := _) -> k /= name) doc
remove doc (name:ns) = withField name doc id (process ns)
process ns (xs, y, ys) _ = xs ++ [removeNested y ns] ++ ys
removeNested f@(k := v) names
| valIsDoc v = k := recToDoc (excludeFields names (docToRec k f))
| otherwise = k := v
-- ^
-- Return a record containing only the specified fields
includeFields :: [Label] -> Record -> Record
includeFields keys (Record doc) = Record fields
where
fields = toField . snd <$> Map.toList (Map.fromListWith mergeRecords tuples)
tuples = second toRecord <$> mapMaybe add (splitAtDot <$> keys)
toRecord = Record . (: [])
toField = head . getDocument
add [] = error "includeFields: no field specified"
add [name] = (,) name <$> find (\(k := _) -> k == name) doc
add (name:ns) = (,) name <$> withField name doc (const Nothing) (process ns)
process ns (_, y, _) _ = addNested y ns
addNested f@(k := v) names
| valIsDoc v = Just (k := recToDoc (includeFields names (docToRec k f)))
| otherwise = Nothing
-- ^
-- Prepare the labels of the fields to be included in an object
-- which will contain the input fields and the id. Empty input fields
-- will result in all fields being returned.
mkIncludeLabels :: [Label] -> [Label]
mkIncludeLabels [] = []
mkIncludeLabels xs = idLabel : xs
-- ^
-- Extract the field names from a record
getLabels :: Record -> [Label]
getLabels = fmap label . getDocument
-- ^
-- Find the field with @name@ in @doc@ and do a case analysis
-- based on whether the field is found or not
withField
:: Text
-> Document
-> (Document -> a)
-> (([Field], Field, [Field]) -> (Int, Document) -> a)
-> a
withField name doc f g =
case findIndex ((name ==) . label) doc of
Nothing -> f doc
Just i ->
let (xs, y:ys) = splitAt i doc
in g (xs, y, ys) (i, doc)
-- ^
-- Split a nested label at the first dot
--
-- >>> splitAtDot "a.b.c"
-- ["a", "b.c"]
--
-- >>> splitAtDot "a"
-- ["a"]
--
splitAtDot :: Text -> [Text]
splitAtDot name =
case T.findIndex ('.' ==) name of
Nothing -> [name]
Just i ->
let (x, y) = T.splitAt i name
in [x, T.tail y]
-- ^
-- Determine whether a bson value is of type @Document@
valIsDoc :: BSON.Value -> Bool
valIsDoc (Doc _) = True
valIsDoc _ = False
-- ^
-- Convert a record to a document value
recToDoc :: Record -> BSON.Value
recToDoc = Doc . getDocument
-- ^
-- Extract the document from a field value and convert it to a record
docToRec :: Label -> Field -> Record
docToRec name field = Record (at name [field])
-- ^
-- Compute the sha-1 hash of a record
recToSha' :: Record -> Digest SHA1State
recToSha' = sha1 . encode
-- ^
-- Compute the sha-1 hash of a record as a string
recToSha :: Record -> String
recToSha = showDigest . recToSha'
-- ^
-- Compute the pagination data given a current page,
-- the page size, and the total number of records
paginate :: Int -> Int -> Int -> Pagination
paginate page' size' total' =
Pagination
{ paginationTotal = total
, paginationPage = page
, paginationSize = size
, paginationNext = next
, paginationPrev = prev
, paginationFirst = first'
, paginationLast = last'
, paginationStart = start
, paginationLimit = limit
}
where
total = max total' 0
size = max size' 1
first' = 1
last' = max 1 (div total size + min 1 (mod total size))
page = min (max page' first') last'
next = min (page + 1) last'
prev = max first' (page - 1)
start = max 0 ((page - 1) * size)
limit = size
-- ^
-- Make a sort expression
--
-- >>> mkSortExpr "+title"
-- Just (SortExpr "title" SortAscending)
--
-- >>> mkSortExpr "-title"
-- Just (SortExpr "title" SortDescending)
--
-- >>> mkSortExpr ""
-- Nothing
--
mkSortExpr :: Text -> Maybe SortExpr
mkSortExpr name
| T.null name = Nothing
| T.head name == '-' = Just $ SortExpr (getName name) SortDescending
| otherwise = Just $ SortExpr (getName name) SortAscending
where
getName xs
| T.head xs == '+' || T.head xs == '-' = T.tail xs
| otherwise = xs
-- ^
-- A record definition that contains only a required id field
idDefinition :: RecordDefinition
idDefinition =
RecordDefinition mempty mempty mempty $ Map.fromList [mkReqDef' idLabel]
|
gabesoft/kapi
|
src/Persistence/Common.hs
|
bsd-3-clause
| 13,449
| 0
| 15
| 2,901
| 3,975
| 2,120
| 1,855
| 250
| 3
|
module Zero.KeyFetchToken.Internal
(
KeyFetchToken
, KeyFetchState(..)
, defaultKeyFetchState
) where
import Data.Aeson
import Data.Text (Text)
import Zero.Swagger
import Servant.API.Experimental.Auth (AuthProtect)
------------------------------------------------------------------------------
-- Types
------------------------------------------------------------------------------
-- | Type used which requires an auth token with hawk
type KeyFetchToken = AuthProtect "KeyFetchToken"
------------------------------------------------------------------------------
data KeyFetchState = KeyFetchState {
ks_kA :: Text
, ks_wrap_kB :: Text
} deriving (Show, Generic)
instance ToJSON KeyFetchState where
toJSON (KeyFetchState kA wrap_kB) =
object [
"kA" .= kA
, "wrap_kB" .= wrap_kB
]
instance FromJSON KeyFetchState where
parseJSON = withObject "KeyFetchState" $ \v -> KeyFetchState
<$> v .: "kA"
<*> v .: "wrap_kB"
instance ToSchema KeyFetchState where
declareNamedSchema proxy = genericDeclareNamedSchema defaultSchemaOptions proxy
& mapped.schema.description ?~ "The public / private master key of this account. These keys are the base of future client-side key derivations. "
& mapped.schema.example ?~ toJSON defaultKeyFetchState
------------------------------------------------------------------------------
-- Constructors
------------------------------------------------------------------------------
defaultKeyFetchState =
KeyFetchState "<bytestring>" "<bytestring>"
|
et4te/zero
|
src-shared/Zero/KeyFetchToken/Internal.hs
|
bsd-3-clause
| 1,587
| 0
| 11
| 258
| 243
| 137
| 106
| -1
| -1
|
module Ui.Commands where
import Ptui.Types
import qualified Graphics.X11.Xlib as X
import qualified Graphics.X11.Xlib.Extras as XE
import Control.Concurrent.STM (atomically,TQueue,writeTQueue,readTQueue)
import Control.Monad (when)
import Data.Bits ((.|.))
import Lens.Simple
import Control.Monad.Trans (liftIO)
process :: Ptui ()
process = do
d <- use $ x11.display
w <- use $ x11.window
q <- use channel
liftIO $ do
X.selectInput d w (X.exposureMask .|. X.buttonPressMask)
X.allocaXEvent $ \e -> do
evs <- X.pending d
when (evs > 0) $ do
X.nextEvent d e
ev <- XE.getEvent e
atomically $ writeTQueue q $ X11Event $ XE.eventName ev
|
mrak/ptui
|
src/Ui/Commands.hs
|
bsd-3-clause
| 738
| 0
| 20
| 196
| 257
| 136
| 121
| 22
| 1
|
module CodeGen.RightSide.Infer(
buildRightInfer,
populateForalls,
genCheckMetaEq
) where
import Control.Monad.State
import Control.Monad.Except (throwError, lift)
import Control.Lens
import Language.Haskell.Exts.Simple
import qualified Data.Map as Map
import AST hiding (Var, name, Name)
import qualified AST (Term(Var), Name)
import AST.Axiom hiding (name)
import CodeGen.Common hiding (count)
import CodeGen.RightSide.Common
import CodeGen.RightSide.Helpers
import CodeGen.RightSide.Exprs
buildRightInfer :: (Map.Map AST.Name FunctionalSymbol) -> FunctionalSymbol -> Axiom -> ErrorM Exp
buildRightInfer fss fs ax = -- pure ExprHole
runBM fss (buildRight' fs ax)
buildRight' :: FunctionalSymbol -> Axiom -> BldRM Exp
buildRight' fs ax = do
genCheckStability $ stab ax
-- populate foralls
populateForalls (forallVars ax)
-- write all metas given as args + add |- A judgements to be inferred
correctFresh ax
-- check metas for equality and leave only one in map if many
genCheckMetaEq
-- find all used Metavars + check for equality where needed
-- First check all guys of the smth : T - build up the map (metavars : Term)
mapM_ labelJudgement (premise ax)
-- returns checks for contexts and infers the part after |-
-- equality goes like this "checkEq a b >> infer (consCtx v) a"
-- [[Exp]]
-- [MetaVar]
metaJs <- use (juds.metaTyDefs)
expsMeta <- mapM (buildInferExps . snd) metaJs
stmtsMeta <- mapM stmtsAndMetaLast $ zipWith
(\(a,jud) c -> (a, judCtx jud,c))
metaJs expsMeta
mapM_ appendStmt (concat stmtsMeta)
-- check metas for equality after all of them are added
genCheckMetaEq
------------------------------------------------------------------------------
ctTerms <- use (juds.notDefsTy)
expsTyTms <- mapM (buildInferExps . snd) ctTerms
stmtsTyTms <- mapM stmtsAndTmEqLast $ zipWith
(\(a,jud) c -> (a, judCtx jud,c))
ctTerms expsTyTms
mapM_ appendStmt (concat stmtsTyTms)
------------------------------------------------------------------------------
-- a = b >> check ctx TyDef expr
expsDef <- join $ uses (juds.otherJuds) (mapM buildCheckExps)
mapM_ appendExp (concat expsDef)
genReturnSt fs (conclusion ax)
uses doStmts doExp
-- >>= \t -> remvars (Metavar) this
stmtsAndMetaLast :: (MetaVar, Ctx, [Exp]) -> BldRM [Stmt]
stmtsAndMetaLast (_, _, []) = throwError "stmtsAndMetaLast must be called with at least one expr"
-- this is a metaVar def
stmtsAndMetaLast (m, ct, x:[]) = do
-- v_i <- x
vn <- fresh
let vname = var (name vn)
-- trim ctx of metavar given in here and put it into the metamap
-- v_i+1 <- trim v_i
(mct, mvarExp) <- trimMeta (mContext m) (ct, nf 0 vname)
vm <- fresh
metas %= updateMap m (mct, var (name vm))
-- return first v <- infer ..., then m <- trimmed
-- the benefit of using remove here is that it's in TC too,
-- every other place we just use Identity monad!
return [generator vn x, generator vm mvarExp]
stmtsAndMetaLast (m, ct, x:xs) = do
xs' <- stmtsAndMetaLast (m, ct, xs)
return $ Qualifier x : xs'
-- >>= \t -> remvars (Metavar) this
stmtsAndTmEqLast :: (Term, Ctx, [Exp]) -> BldRM [Stmt]
stmtsAndTmEqLast (_,_,[]) = throwError "stmtsAndTmEqLast must be called with at least one expr"
-- this is a ": Exp" situation so we check it for equality
stmtsAndTmEqLast (tm, ct, x:[]) = do
vn <- fresh
let vExp = var (name vn)
tmExp <- buildTermExp ct tm
return [generator vn x, Qualifier $ eqCheckExp tmExp vExp]
stmtsAndTmEqLast (tm, ct, x:xs) = do
xs' <- stmtsAndTmEqLast (tm, ct, xs)
return $ Qualifier x : xs'
--------------------------------------------------------------------------------
-- first vars are already used
-- also axioms are always of the form like this
correctFresh :: Axiom -> BldRM ()
correctFresh (Axiom _ _ _ prems (Statement _ (FunApp _ lst) _)) = populateSt lst
where
populateSt ((ct, Meta mv):xs) = do
v <- fresh
metas %= updateMap mv (ct, fromScope (length ct) $ var (name v))
populateSt xs
-- user may have not added these
when (null ct && not (elem mv (concat $ ctMetas <$> prems))) $
juds.otherJuds %= (Statement [] (Meta mv) Nothing : )
populateSt [] = return ()
populateSt _ = throwError "Can't have a non metavariable in an axiom concl"
correctFresh _ = throwError $ "error: Only axioms with funsym intro are allowed"
populateForalls :: [(MetaVar, Sort)] -> BldRM ()
populateForalls [] = return ()
populateForalls ((m, sort):xs) = do
foralls %= Map.insert m sort
populateForalls xs
--------------------------------------------------------------------------------
-- Check terms for equality
genCheckMetaEq :: BldRM ()
genCheckMetaEq = do
ms <- gets _metas
metas <~ sequence (genMetaEq <$> ms)
-- metas .= res
-- generate code for meta equality checking
genMetaEq :: [(Ctx, Exp)] -> BldRM [(Ctx, Exp)]
genMetaEq [] = return []
genMetaEq (x : []) = return [x]
genMetaEq (tm : y'@(ct2, y) : xs) = do
ex <- conniveMeta ct2 tm
let ex' = eqCheckExp ex y
appendExp ex'
genMetaEq (y' : xs)
--------------------------------------------------------------------------------
genReturnSt :: FunctionalSymbol -> Judgement -> BldRM ()
genReturnSt (FunSym _ _ res) (Statement _ _ Nothing) = do
appendExp $ retExp (tyCtor $ sortToTyCtor $ getSortName res)
genReturnSt _ (Statement _ _ (Just ty)) = do
ret <- buildTermExp [] ty
appendExp $ retExp ret
genReturnSt _ _ = throwError "Can't have anything but Statement in conclusion"
---
|
esengie/fpl-exploration-tool
|
src/langGenerator/CodeGen/RightSide/Infer.hs
|
bsd-3-clause
| 5,555
| 0
| 19
| 1,084
| 1,620
| 838
| 782
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module ClientSpec where
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.STM.TVar
import Control.Exception.Base
import Control.Monad.STM
import Crypto.Hash.SHA1
import Data.Binary
import Data.Binary.Get
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Char8 as BC
import Data.Functor
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import qualified Network.BitTorrent.BitField as BF
import Network.BitTorrent.Bencoding
import Network.BitTorrent.Client
import qualified Network.BitTorrent.FileWriter as FW
import Network.BitTorrent.MetaInfo
import Network.BitTorrent.PWP
import Network.BitTorrent.Types
import Network.Socket
import SpecHelper
import System.Directory
import System.FilePath
import System.IO
import System.Random
import System.Timeout
import Test.Hspec
withSetup f = do
tmpdir <- getTemporaryDirectory
salt <- randomIO :: IO Word16
let outDir = tmpdir </> show salt
createDirectory outDir
bracket (do
generated <- getStdGen >>= pure . randomRs (6882 :: Word16, 15000)
let ports = fromIntegral <$> generated
bf = BF.newBitField pieceCount
peer = newPeer bf (testAddr [1, 0, 0, 127] $ ports !! 0) "12345678901234567890"
peer2 = newPeer bf (testAddr [1, 0, 0, 127] $ ports !! 1) "98765432109876543210"
globalState <- newGlobalState (fromIntegral $ ports !! 2)
state <- newTorrentState outDir testMeta
addActiveTorrent globalState state
return (peer, peer2, (globalState, state), testMeta)) (\_ -> do
removeDirectoryRecursive outDir
)
f
data TestMessage = ReadHandshake BHandshake | ReadPWP PWP | WriteHandshake BHandshake | WritePWP PWP deriving(Show)
setupSocket :: PeerData -> [TestMessage] -> IO (Async Bool)
setupSocket peer messages = do
let SockAddrInet port _ = address peer
sock <- socket AF_INET Stream defaultProtocol
setSocketOption sock NoDelay 1 -- Helps greatly on localhost
bind sock (address peer)
listen sock 10
async $ do
(sock', addr) <- accept sock
handle <- socketToHandle sock' ReadWriteMode
let evaluator previous [] = do
return True
evaluator previous all@(ReadHandshake expected : xs) = do
input <- B.hGetSome handle (1024*1024)
let parsed = runGetIncremental get `pushChunk` previous `pushChunk` input
case parsed of
Partial _ -> do
evaluator (previous <> input) all
Done unused _ handshake | handshake == expected -> do
evaluator unused xs
Done unused _ msg -> do
putStrLn $ show msg <> " DOES NOT MATCH " <> show expected
return False
_ -> return False
evaluator previous all@(WriteHandshake handshake : xs) = do
BL.hPut handle $ encode handshake
evaluator previous xs
evaluator previous all@(WritePWP msg : xs) = do
BL.hPut handle $ encode msg
evaluator previous xs
evaluator previous all@(ReadPWP expected : xs) = do
input <- B.hGetSome handle (1024*1024)
let parsed = runGetIncremental get `pushChunk` previous `pushChunk` input
case parsed of
Partial _ -> do
evaluator (previous <> input) all
Done unused _ msg | msg == expected -> do
evaluator unused xs
Done unused _ msg -> do
putStrLn $ "EXPECTED " <> show expected <> " BUT GOT " <> show msg
return False
_ -> return False
evaluator "" messages
spec :: SpecWith ()
spec = do
{-
it "updates the peer's bitfield" $ withSetup $ \(peer, peer2, state, meta) -> do
let someData = BL.toStrict $ BL.take pieceCount $ BL.cycle $ BL.pack $
fromIntegral <$> [readBinary "11011010", readBinary "00101000"]
let bitField = BF.BitField someData pieceCount
promise <- setupSocket peer
[ ReadHandshake $ BHandshake (infoHash meta) $ myPeerId state
, WriteHandshake $ BHandshake (infoHash meta) "12345678901234567890"
, WritePWP $ Bitfield someData
]
forkIO $ reachOutToPeer state (address peer)
wait promise
res <- timeout 10000 $ atomically $ do
map <- readTVar (statePeers state)
case Map.lookup (peerId peer) map of
Just res | peerBitField res == bitField -> return True
_ -> retry
r <- atomically $ do
map <- readTVar (statePeers state)
return $ peerBitField <$> Map.lookup (peerId peer) map
print r
print bitField
print pieceCount
res `shouldBe` Just True
-}
it "handshakes properly" $ withSetup $ \(peer, peer2, (globalState, state), meta) -> do
promise <- setupSocket peer
[ WriteHandshake $ BHandshake (infoHash meta) "12345678901234567890"
, ReadHandshake $ BHandshake (infoHash meta) $ globalStatePeerId globalState
]
forkIO $ reachOutToPeer globalState state (address peer)
result <- wait promise
result `shouldBe` True
{-
it "handles HAVE messages properly" $ withSetup $ \(peer, peer2, state, meta) -> do
let newBitField = BF.set fullBitField 7 False
promise <- setupSocket peer
[ WriteHandshake $ BHandshake (infoHash meta) "12345678901234567890"
, ReadHandshake $ BHandshake (infoHash meta) $ myPeerId state
, WritePWP $ Bitfield $ BF.raw fullBitField
, WritePWP $ Have 7
]
forkIO $ reachOutToPeer state (address peer)
res1 <- timeout 10000 $ wait promise
res2 <- timeout 10000 $ atomically $ do
peers <- readTVar (statePeers state)
case Map.lookup "12345678901234567890" peers of
Just p | BF.get (peerBitField p) 7 -> return True
_ -> retry
(res1, res2) `shouldBe` (Just True, Just True)
-}
it "can seed itself" $
withSetup $ \(_, _, (globalState, state), _) -> do
withSetup $ \(_, _, (globalState2, state2), _) -> do
bracket (do
tmpdir <- getTemporaryDirectory
openTempFile tmpdir "torrent") (\(path, handle) -> do
hClose handle
removeFile path) (\(path, handle) -> do
B.hPut handle testData
atomically $
writeTVar (torrentStateBitField state) fullBitField
let state' = state { torrentStateOutputHandles = (\(lo, hi, _) -> (lo, hi, handle)) <$> torrentStateOutputHandles state }
addr = testAddr [1, 0, 0, 127] $ fromIntegral $ globalStateListenPort globalState
void $ btListen globalState
promise <- async $ reachOutToPeer globalState2 state2 addr
res <- timeout 1000000 $ atomically $ do
bitField <- readTVar (torrentStateBitField state2)
if bitField == fullBitField
then return True
else retry
r <- atomically $ readTVar (torrentStateBitField state2)
print r
print fullBitField
res `shouldBe` Just True)
|
farnoy/torrent
|
test/ClientSpec.hs
|
bsd-3-clause
| 7,113
| 0
| 28
| 1,919
| 1,620
| 823
| 797
| 126
| 11
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Berp.Interpreter.Repl
-- Copyright : (c) 2010 Bernie Pope
-- License : BSD-style
-- Maintainer : florbitous@gmail.com
-- Stability : experimental
-- Portability : ghc
--
-- The Read Eval Print Loop (REPL) of the interpreter.
--
-----------------------------------------------------------------------------
module Berp.Interpreter.Repl (repl) where
import Data.Typeable (Typeable (..), mkTyConApp, mkTyCon)
import Control.Monad.Trans (lift, liftIO)
import Control.Monad (when)
import System.IO (hSetBuffering, stdout, BufferMode (..))
import Language.Python.Version3.Parser (parseStmt)
import Language.Python.Common.Pretty (prettyText)
import Language.Python.Common.AST (StatementSpan)
import Language.Haskell.Exts.Pretty
( prettyPrintStyleMode, defaultMode, style, Style (..), PPHsMode (..)
, Mode (..), PPLayout (PPSemiColon))
import Language.Haskell.Exts.Build (app, qualStmt)
import Language.Haskell.Exts.Syntax (Exp)
import Language.Haskell.Interpreter (setImportsQ, as, interpret)
import Berp.Version (versionString)
import Berp.Compile.Compile (compile)
import Berp.Compile.PrimName as Prim (init)
import Berp.Compile.PySyntaxUtils (InterpreterStmt (..))
import Berp.Interpreter.Monad (Repl, runRepl, getGlobalScope)
import Berp.Interpreter.Input (getInputLines)
import Berp.Base.SemanticTypes (Eval, Object (None), HashTable)
import Berp.Base (runWithGlobals)
import Berp.Base.Prims (printObject)
repl :: IO ()
repl = do
hSetBuffering stdout NoBuffering
greeting
runRepl $ do
setImportsQ [ ("Data.IntMap", Nothing)
, ("Data.IORef", Nothing)
, ("Berp.Base", Nothing)
, ("Berp.Base.SemanticTypes", Nothing)
]
replLoop
greeting :: IO ()
greeting = putStrLn $ "Berp version " ++ versionString ++ ", type control-d to exit."
replLoop :: Repl ()
replLoop = do
maybeInput <- getInputLines
case maybeInput of
Nothing -> return ()
Just input -> evalInput input >> replLoop
evalInput :: String -> Repl ()
evalInput input =
when (not $ null input) $ do
pyStmts <- liftIO $ parseAndCheckErrors (input ++ "\n")
when (not $ null pyStmts) $ do
exp <- lift $ lift $ compile $ InterpreterStmt pyStmts
let expStr = oneLinePrinter exp
comp <- interpret expStr (as :: HashTable -> Eval Object)
globals <- getGlobalScope
liftIO $ runWithGlobals globals $ runAndPrint comp
runAndPrint :: (HashTable -> Eval Object) -> HashTable -> Eval Object
runAndPrint comp globals = do
-- XXX should catch exceptions here?
result <- comp globals
printObjectNotNone result
return result
oneLinePrinter :: Exp -> String
oneLinePrinter =
prettyPrintStyleMode newStyle newMode
where
newStyle = style { mode = OneLineMode }
newMode = defaultMode { layout = PPSemiColon }
parseAndCheckErrors :: String -> IO [StatementSpan]
parseAndCheckErrors fileContents =
case parseStmt fileContents "<stdin>" of
Left e -> (putStrLn $ prettyText e) >> return []
Right (pyStmt, _comments) -> return pyStmt
printObjectNotNone :: Object -> Eval ()
printObjectNotNone obj@None = return ()
printObjectNotNone object = printObject object >> liftIO (putStr "\n")
-- these Typeable instances are needed by the Hint interpret function.
instance Typeable Object where
typeOf _ = mkTyConApp (mkTyCon "Object") []
instance Typeable (Eval Object) where
typeOf _ = mkTyConApp (mkTyCon "Eval") [typeOf (undefined :: Object)]
|
bjpop/berp
|
interpreter/src/Berp/Interpreter/Repl.hs
|
bsd-3-clause
| 3,672
| 0
| 15
| 681
| 971
| 537
| 434
| 74
| 2
|
module Data.Char.Properties.Misc
(
module Data.Char.Properties.MiscData,
module Data.Char.Properties.Derivation,
module Data.Char.Properties.Misc
) where
{
import Data.Char.Properties.MiscData;
import Data.Char.Properties.GeneralCategory;
import Data.Char.Properties.Derivation;
import Prelude;
-- | Returns true if the general category is Lt.
;
isTitlecase :: Char -> Bool;
isTitlecase c = getGeneralCategory c == GcLt;
-- Note: this is not defined by Unicode.
-- Also, a single line break can be an 0D 0A sequence.
isLineBreak :: Char -> Bool;
isLineBreak '\x000A' = True; -- LINE FEED
isLineBreak '\x000B' = True; -- VERTICAL TABULATION ?
isLineBreak '\x000C' = True; -- FORM FEED
isLineBreak '\x000D' = True; -- CARRIAGE RETURN
isLineBreak '\x2028' = True; -- LINE SEPARATOR
isLineBreak '\x2029' = True; -- PARAGRAPH SEPARATOR
isLineBreak _ = False;
}
|
seereason/unicode-properties
|
Data/Char/Properties/Misc.hs
|
bsd-3-clause
| 1,044
| 1
| 6
| 304
| 174
| 113
| 61
| 19
| 1
|
{-#LANGUAGE MultiParamTypeClasses #-}
{-#LANGUAGE OverloadedStrings #-}
module Twilio.AvailablePhoneNumber
( -- * Resource
AvailablePhoneNumber(..)
) where
import Control.Applicative
import Control.Error.Safe
import Control.Monad
import Data.Aeson
import Data.Text (Text)
import Twilio.Types
import Twilio.Internal.Parser
{- Resource -}
data AvailablePhoneNumber = AvailablePhoneNumber
{ friendlyName :: !Text
, phoneNumber :: !Text
, lata :: !(Maybe Integer)
, rateCenter :: !(Maybe Text)
, latitude :: !(Maybe Double)
, longitude :: !(Maybe Double)
, region :: !Text
, postalCode :: !(Maybe Integer)
, isoCountry :: !ISOCountryCode
, addressRequirements :: !(Maybe AddressRequirement)
, capabilities :: !Capabilities
} deriving (Eq, Show)
instance FromJSON AvailablePhoneNumber where
parseJSON (Object v) = AvailablePhoneNumber
<$> v .: "friendly_name"
<*> v .: "phone_number"
<*> (v .: "lata" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "rate_center"
<*> (v .: "latitude" <&> (=<<) readZ
>>= maybeReturn')
<*> (v .: "longitude" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "region"
<*> (v .: "postal_code" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "iso_country"
<*> v .: "address_requirements"
<*> (v .: "capabilities" >>= parseJSON)
parseJSON _ = mzero
|
seagreen/twilio-haskell
|
src/Twilio/AvailablePhoneNumber.hs
|
bsd-3-clause
| 1,514
| 0
| 22
| 429
| 383
| 212
| 171
| 65
| 0
|
module Perceptron where
import qualified Prelude
import Data.Ratio
andb :: Prelude.Bool -> Prelude.Bool -> Prelude.Bool
andb b1 b2 =
case b1 of {
Prelude.True -> b2;
Prelude.False -> Prelude.False}
negb :: Prelude.Bool -> Prelude.Bool
negb = (Prelude.not)
data Nat =
O
| S Nat
data Option a =
Some a
| None
data Comparison =
Eq
| Lt
| Gt
compOpp :: Comparison -> Comparison
compOpp r =
case r of {
Eq -> Eq;
Lt -> Gt;
Gt -> Lt}
add :: Nat -> Nat -> Nat
add n m =
case n of {
O -> m;
S p -> S (add p m)}
eqb :: Prelude.Bool -> Prelude.Bool -> Prelude.Bool
eqb = (Prelude.==)
succ :: Prelude.Integer -> Prelude.Integer
succ x =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p -> (\x -> (Prelude.*) 2 x)
(succ p))
(\p -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
p)
(\_ -> (\x -> (Prelude.*) 2 x)
1)
x
add0 :: Prelude.Integer -> Prelude.Integer -> Prelude.Integer
add0 x y =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q -> (\x -> (Prelude.*) 2 x)
(add_carry p q))
(\q -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
(add0 p q))
(\_ -> (\x -> (Prelude.*) 2 x)
(succ p))
y)
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
(add0 p q))
(\q -> (\x -> (Prelude.*) 2 x)
(add0 p q))
(\_ -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
p)
y)
(\_ ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q -> (\x -> (Prelude.*) 2 x)
(succ q))
(\q -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
q)
(\_ -> (\x -> (Prelude.*) 2 x)
1)
y)
x
add_carry :: Prelude.Integer -> Prelude.Integer -> Prelude.Integer
add_carry x y =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
(add_carry p q))
(\q -> (\x -> (Prelude.*) 2 x)
(add_carry p q))
(\_ -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
(succ p))
y)
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q -> (\x -> (Prelude.*) 2 x)
(add_carry p q))
(\q -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
(add0 p q))
(\_ -> (\x -> (Prelude.*) 2 x)
(succ p))
y)
(\_ ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
(succ q))
(\q -> (\x -> (Prelude.*) 2 x)
(succ q))
(\_ -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
1)
y)
x
pred_double :: Prelude.Integer -> Prelude.Integer
pred_double x =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1) ((\x -> (Prelude.*) 2 x)
p))
(\p -> (\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
(pred_double p))
(\_ ->
1)
x
data Mask =
IsNul
| IsPos Prelude.Integer
| IsNeg
succ_double_mask :: Mask -> Mask
succ_double_mask x =
case x of {
IsNul -> IsPos 1;
IsPos p -> IsPos ((\x -> (Prelude.+) ((Prelude.*) 2 x) 1) p);
IsNeg -> IsNeg}
double_mask :: Mask -> Mask
double_mask x =
case x of {
IsPos p -> IsPos ((\x -> (Prelude.*) 2 x) p);
x0 -> x0}
double_pred_mask :: Prelude.Integer -> Mask
double_pred_mask x =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p -> IsPos ((\x -> (Prelude.*) 2 x) ((\x -> (Prelude.*) 2 x)
p)))
(\p -> IsPos ((\x -> (Prelude.*) 2 x)
(pred_double p)))
(\_ ->
IsNul)
x
sub_mask :: Prelude.Integer -> Prelude.Integer -> Mask
sub_mask x y =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q ->
double_mask (sub_mask p q))
(\q ->
succ_double_mask (sub_mask p q))
(\_ -> IsPos ((\x -> (Prelude.*) 2 x)
p))
y)
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q ->
succ_double_mask (sub_mask_carry p q))
(\q ->
double_mask (sub_mask p q))
(\_ -> IsPos
(pred_double p))
y)
(\_ ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\_ ->
IsNeg)
(\_ ->
IsNeg)
(\_ ->
IsNul)
y)
x
sub_mask_carry :: Prelude.Integer -> Prelude.Integer -> Mask
sub_mask_carry x y =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q ->
succ_double_mask (sub_mask_carry p q))
(\q ->
double_mask (sub_mask p q))
(\_ -> IsPos
(pred_double p))
y)
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q ->
double_mask (sub_mask_carry p q))
(\q ->
succ_double_mask (sub_mask_carry p q))
(\_ ->
double_pred_mask p)
y)
(\_ ->
IsNeg)
x
sub :: Prelude.Integer -> Prelude.Integer -> Prelude.Integer
sub x y =
case sub_mask x y of {
IsPos z -> z;
_ -> 1}
mul :: Prelude.Integer -> Prelude.Integer -> Prelude.Integer
mul x y =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p ->
add0 y ((\x -> (Prelude.*) 2 x) (mul p y)))
(\p -> (\x -> (Prelude.*) 2 x)
(mul p y))
(\_ ->
y)
x
size_nat :: Prelude.Integer -> Nat
size_nat p =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p0 -> S
(size_nat p0))
(\p0 -> S
(size_nat p0))
(\_ -> S
O)
p
compare_cont :: Comparison -> Prelude.Integer -> Prelude.Integer ->
Comparison
compare_cont r x y =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q ->
compare_cont r p q)
(\q ->
compare_cont Gt p q)
(\_ ->
Gt)
y)
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q ->
compare_cont Lt p q)
(\q ->
compare_cont r p q)
(\_ ->
Gt)
y)
(\_ ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\_ ->
Lt)
(\_ ->
Lt)
(\_ ->
r)
y)
x
compare :: Prelude.Integer -> Prelude.Integer -> Comparison
compare =
compare_cont Eq
ggcdn :: Nat -> Prelude.Integer -> Prelude.Integer -> (,) Prelude.Integer
((,) Prelude.Integer Prelude.Integer)
ggcdn n a b =
case n of {
O -> (,) 1 ((,) a b);
S n0 ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\a' ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\b' ->
case compare a' b' of {
Eq -> (,) a ((,) 1 1);
Lt ->
case ggcdn n0 (sub b' a') a of {
(,) g p ->
case p of {
(,) ba aa -> (,) g ((,) aa
(add0 aa ((\x -> (Prelude.*) 2 x) ba)))}};
Gt ->
case ggcdn n0 (sub a' b') b of {
(,) g p ->
case p of {
(,) ab bb -> (,) g ((,) (add0 bb ((\x -> (Prelude.*) 2 x) ab))
bb)}}})
(\b0 ->
case ggcdn n0 a b0 of {
(,) g p ->
case p of {
(,) aa bb -> (,) g ((,) aa ((\x -> (Prelude.*) 2 x) bb))}})
(\_ -> (,) 1 ((,) a
1))
b)
(\a0 ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\_ ->
case ggcdn n0 a0 b of {
(,) g p ->
case p of {
(,) aa bb -> (,) g ((,) ((\x -> (Prelude.*) 2 x) aa) bb)}})
(\b0 ->
case ggcdn n0 a0 b0 of {
(,) g p -> (,) ((\x -> (Prelude.*) 2 x) g) p})
(\_ -> (,) 1 ((,) a
1))
b)
(\_ -> (,) 1 ((,) 1
b))
a}
ggcd :: Prelude.Integer -> Prelude.Integer -> (,) Prelude.Integer
((,) Prelude.Integer Prelude.Integer)
ggcd a b =
ggcdn (add (size_nat a) (size_nat b)) a b
double :: Prelude.Integer -> Prelude.Integer
double x =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
0)
(\p -> ((\x -> (Prelude.*) 2 x)
p))
(\p -> (\x -> (Prelude.*) x (-1)) ((\x -> (Prelude.*) 2 x)
p))
x
succ_double :: Prelude.Integer -> Prelude.Integer
succ_double x =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
1)
(\p -> ((\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
p))
(\p -> (\x -> (Prelude.*) x (-1))
(pred_double p))
x
pred_double0 :: Prelude.Integer -> Prelude.Integer
pred_double0 x =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ -> (\x -> (Prelude.*) x (-1))
1)
(\p ->
(pred_double p))
(\p -> (\x -> (Prelude.*) x (-1))
((\x -> (Prelude.+) ((Prelude.*) 2 x) 1)
p))
x
pos_sub :: Prelude.Integer -> Prelude.Integer -> Prelude.Integer
pos_sub x y =
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q ->
double (pos_sub p q))
(\q ->
succ_double (pos_sub p q))
(\_ -> ((\x -> (Prelude.*) 2 x)
p))
y)
(\p ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q ->
pred_double0 (pos_sub p q))
(\q ->
double (pos_sub p q))
(\_ ->
(pred_double p))
y)
(\_ ->
(\xI xO xH p ->
if (Prelude.==) p 1 then xH ()
else if Prelude.even p then xO (Prelude.quot p 2)
else xI (Prelude.quot p 2))
(\q -> (\x -> (Prelude.*) x (-1)) ((\x -> (Prelude.*) 2 x)
q))
(\q -> (\x -> (Prelude.*) x (-1))
(pred_double q))
(\_ ->
0)
y)
x
add1 :: Prelude.Integer -> Prelude.Integer -> Prelude.Integer
add1 = (Prelude.+)
opp :: Prelude.Integer -> Prelude.Integer
opp x =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
0)
(\x0 -> (\x -> (Prelude.*) x (-1))
x0)
(\x0 ->
x0)
x
mul0 :: Prelude.Integer -> Prelude.Integer -> Prelude.Integer
mul0 = (Prelude.*)
compare0 :: Prelude.Integer -> Prelude.Integer -> Comparison
compare0 x y =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
Eq)
(\_ ->
Lt)
(\_ ->
Gt)
y)
(\x' ->
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
Gt)
(\y' ->
compare x' y')
(\_ ->
Gt)
y)
(\x' ->
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
Lt)
(\_ ->
Lt)
(\y' ->
compOpp (compare x' y'))
y)
x
sgn :: Prelude.Integer -> Prelude.Integer
sgn z =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
0)
(\_ ->
1)
(\_ -> (\x -> (Prelude.*) x (-1))
1)
z
leb :: Prelude.Integer -> Prelude.Integer -> Prelude.Bool
leb x y =
case compare0 x y of {
Gt -> Prelude.False;
_ -> Prelude.True}
abs :: Prelude.Integer -> Prelude.Integer
abs z =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
0)
(\p ->
p)
(\p ->
p)
z
to_pos :: Prelude.Integer -> Prelude.Integer
to_pos z =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ ->
1)
(\p ->
p)
(\_ ->
1)
z
ggcd0 :: Prelude.Integer -> Prelude.Integer -> (,) Prelude.Integer
((,) Prelude.Integer Prelude.Integer)
ggcd0 a b =
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ -> (,) (abs b) ((,) 0
(sgn b)))
(\a0 ->
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ -> (,) (abs a) ((,) (sgn a)
0))
(\b0 ->
case ggcd a0 b0 of {
(,) g p ->
case p of {
(,) aa bb -> (,) ( g) ((,) ( aa) ( bb))}})
(\b0 ->
case ggcd a0 b0 of {
(,) g p ->
case p of {
(,) aa bb -> (,) ( g) ((,) ( aa) ((\x -> (Prelude.*) x (-1)) bb))}})
b)
(\a0 ->
(\fO fPos fNeg z ->
if (Prelude.==) z 0 then fO ()
else if (Prelude.>) z 0 then fPos z
else fNeg ((Prelude.*) z (-1)))
(\_ -> (,) (abs a) ((,) (sgn a)
0))
(\b0 ->
case ggcd a0 b0 of {
(,) g p ->
case p of {
(,) aa bb -> (,) ( g) ((,) ((\x -> (Prelude.*) x (-1)) aa) ( bb))}})
(\b0 ->
case ggcd a0 b0 of {
(,) g p ->
case p of {
(,) aa bb -> (,) ( g) ((,) ((\x -> (Prelude.*) x (-1)) aa)
((\x -> (Prelude.*) x (-1)) bb))}})
b)
a
qeq_bool :: Rational -> Rational -> Prelude.Bool
qeq_bool = (Prelude.==)
qle_bool :: Rational -> Rational -> Prelude.Bool
qle_bool = (Prelude.<=)
map :: (a1 -> a2) -> Nat -> (([]) a1) -> ([]) a2
map = (\g _ l -> Prelude.map g l)
map2 :: (a1 -> a2 -> a3) -> Nat -> (([]) a1) -> (([]) a2) -> ([]) a3
map2 = (\g _ l1 l2 -> Prelude.map (\(x,y) -> g x y) (Prelude.zip l1 l2))
fold_left :: (a2 -> a1 -> a2) -> a2 -> Nat -> (([]) a1) -> a2
fold_left = (\g a _ l -> Prelude.foldl g a l)
qplus :: Rational -> Rational -> Rational
qplus = (Prelude.+)
qmult :: Rational -> Rational -> Rational
qmult = (Prelude.*)
type Qvec = ([]) Rational
qvec_plus :: Nat -> Qvec -> Qvec -> ([]) Rational
qvec_plus n v1 v2 =
map2 qplus n v1 v2
qvec_dot :: Nat -> Qvec -> Qvec -> Rational
qvec_dot n v1 v2 =
fold_left qplus ((\n d -> (Data.Ratio.%) n d) 0 1) n (map2 qmult n v1 v2)
class0 :: Rational -> Prelude.Bool
class0 i =
qle_bool ((\n d -> (Data.Ratio.%) n d) 0 1) i
correct_class :: Rational -> Prelude.Bool -> Prelude.Bool
correct_class i l =
andb (eqb l (class0 i))
(negb (qeq_bool i ((\n d -> (Data.Ratio.%) n d) 0 1)))
qvec_mult_class :: Nat -> Prelude.Bool -> Qvec -> Qvec
qvec_mult_class n l f =
case l of {
Prelude.True -> f;
Prelude.False ->
map (qmult ((\n d -> (Data.Ratio.%) n d) (opp ( 1)) 1)) n f}
consb :: Nat -> Qvec -> ([]) Rational
consb n v =
(\a _ v -> a : v) ((\n d -> (Data.Ratio.%) n d) ( 1) 1) n v
inner_perceptron :: Nat -> (([]) ((,) Qvec Prelude.Bool)) -> Qvec -> Option
Qvec
inner_perceptron n t w =
case t of {
[] -> None;
(:) p t' ->
case p of {
(,) f l ->
case correct_class (qvec_dot (S n) w (consb n f)) l of {
Prelude.True -> inner_perceptron n t' w;
Prelude.False ->
case inner_perceptron n t'
(qvec_plus (S n) w (qvec_mult_class (S n) l (consb n f))) of {
Some w' -> Some w';
None -> Some
(qvec_plus (S n) w (qvec_mult_class (S n) l (consb n f)))}}}}
perceptron :: Nat -> Nat -> (([]) ((,) Qvec Prelude.Bool)) -> Qvec -> Option
Qvec
perceptron n e t w =
case e of {
O -> None;
S e' ->
case inner_perceptron n t w of {
Some w' -> perceptron n e' t w';
None -> Some w}}
inner_perceptron_MCE :: Nat -> (([]) ((,) Qvec Prelude.Bool)) -> Qvec ->
Option ((,) (([]) ((,) Qvec Prelude.Bool)) Qvec)
inner_perceptron_MCE n t w =
case t of {
[] -> None;
(:) p t' ->
case p of {
(,) f l ->
case correct_class (qvec_dot (S n) w (consb n f)) l of {
Prelude.True -> inner_perceptron_MCE n t' w;
Prelude.False ->
case inner_perceptron_MCE n t'
(qvec_plus (S n) w (qvec_mult_class (S n) l (consb n f))) of {
Some p0 ->
case p0 of {
(,) l0 w' -> Some ((,) ((:) ((,) f l) l0) w')};
None -> Some ((,) ((:) ((,) f l) [])
(qvec_plus (S n) w (qvec_mult_class (S n) l (consb n f))))}}}}
gas :: (Nat -> a1) -> a1
gas = (\f -> let infiniteGas = S infiniteGas in f infiniteGas)
fueled_perceptron :: Nat -> Nat -> (([]) ((,) Qvec Prelude.Bool)) -> Qvec ->
Option Qvec
fueled_perceptron n _ t w =
gas (\fuel -> perceptron n fuel t w)
|
tm507211/CoqPerceptron
|
Benchmarks/hsopt/Perceptron.hs
|
bsd-3-clause
| 21,592
| 20
| 33
| 8,667
| 10,395
| 5,621
| 4,774
| 708
| 10
|
{-# LANGUAGE OverloadedStrings
, ScopedTypeVariables
, LambdaCase
, BangPatterns
, ViewPatterns
#-}
module PrepGhcJS.Network.Utils where
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import qualified Data.Conduit.List as CL
import Network.HTTP.Simple as Si
import Data.Time.Format
import Data.Time.Clock
import Data.Monoid
import qualified Data.Text as T
import Network.HTTP.Client
import System.Directory
import System.IO (stdout, hClose, openFile, IOMode(..))
import Turtle
import Prelude hiding (FilePath)
import PrepGhcJS.Types
work80 :: FilePath -> FilePath -> IO (String, Bool)
work80 (T.unpack . fromPath->cacheDir) (T.unpack . fromPath->f1) = do
let f = cacheDir <> "/" <> f1
createDirectoryIfMissing True cacheDir
let etagFile = f <> ".etag"
!oldEtag <- doesFileExist etagFile >>= \case
True -> S.readFile etagFile
False -> return ""
initReq <- parseRequest $ "http://ghcjs.luite.com/"<> f1
-- let req = "HEAD" `setRequestMethod` initReq
let req = "GET" `setRequestMethod` initReq
(ret, mat, etag) <- httpSink req $ \response -> do
let [tim] :: [UTCTime] = map (parseTimeOrError True defaultTimeLocale "%a, %d %b %Y %T %Z" . S8.unpack) (getResponseHeader "Last-Modified" response)
[etag] = getResponseHeader "ETag" response
ret = formatTime defaultTimeLocale "%F" tim
mat = etag == oldEtag
liftIO $ putStrLn
$ "The status code was: "
++ show (getResponseStatusCode response)
++ show (getResponseHeader "Content-Type" response)
++ show (getResponseHeader "Content-Length" response)
++ show tim
++ show mat
if mat
then do
liftIO $ print "cached"
return (ret, False, etag)
else do
h <- liftIO $ openFile ( f <> "~") WriteMode
liftIO $ print $ "kope" ++ (show etag) ++ (show oldEtag)
CL.mapM_ (S.hPut h)
liftIO $ hClose h
return (ret, True, etag)
fin <- if mat
then
shell ("tar tf " <> T.pack f <> "~") empty >>= \case
ExitFailure _ -> echo "Update failing" >> return False
ExitSuccess -> do
-- liftIO $ print a
liftIO $! S.writeFile etagFile etag
mv ( fromString (f <> "~")) (fromString f)
return True
else
return False
return (ret, fin)
nightly :: IO T.Text
nightly = redirLocation "https://www.stackage.org/nightly"
lts :: IO T.Text
lts = redirLocation "https://www.stackage.org/lts"
lts1 :: T.Text -> IO T.Text
lts1 r = return $ "lts-" <> r
redirLocation url = do
initReq <- parseRequest url
let req = Si.setRequestIgnoreStatus $ ("GET" `setRequestMethod` initReq){redirectCount=0}
httpSink req $ \response ->
return $ head $ T.pack . S8.unpack . S.drop 1 <$> getResponseHeader "Location" response
|
tolysz/prepare-ghcjs
|
lib/PrepGhcJS/Network/Utils.hs
|
bsd-3-clause
| 3,164
| 0
| 19
| 956
| 902
| 465
| 437
| 73
| 5
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Rules.HR
( rules
) where
import Duckling.Dimensions.Types
import Duckling.Types
import qualified Duckling.AmountOfMoney.HR.Rules as AmountOfMoney
import qualified Duckling.Distance.HR.Rules as Distance
import qualified Duckling.Duration.HR.Rules as Duration
import qualified Duckling.Numeral.HR.Rules as Numeral
import qualified Duckling.Ordinal.HR.Rules as Ordinal
import qualified Duckling.Quantity.HR.Rules as Quantity
import qualified Duckling.Temperature.HR.Rules as Temperature
import qualified Duckling.Time.HR.Rules as Time
import qualified Duckling.TimeGrain.HR.Rules as TimeGrain
import qualified Duckling.Volume.HR.Rules as Volume
rules :: Some Dimension -> [Rule]
rules (This Distance) = Distance.rules
rules (This Duration) = Duration.rules
rules (This Numeral) = Numeral.rules
rules (This Email) = []
rules (This AmountOfMoney) = AmountOfMoney.rules
rules (This Ordinal) = Ordinal.rules
rules (This PhoneNumber) = []
rules (This Quantity) = Quantity.rules
rules (This RegexMatch) = []
rules (This Temperature) = Temperature.rules
rules (This Time) = Time.rules
rules (This TimeGrain) = TimeGrain.rules
rules (This Url) = []
rules (This Volume) = Volume.rules
|
rfranek/duckling
|
Duckling/Rules/HR.hs
|
bsd-3-clause
| 1,557
| 0
| 7
| 206
| 370
| 223
| 147
| 31
| 1
|
-- |This library contains (incomplete) bindings to the SDL Primitive Generator (SPriG) written by
-- Jonny D.
module Graphics.UI.SDL.Sprig (module Graphics.UI.SDL.Sprig.Primitives,
module Graphics.UI.SDL.Sprig.Transform ,
module Graphics.UI.SDL.Sprig.Control ,
module Graphics.UI.SDL.Sprig.Drawing ) where
import Graphics.UI.SDL.Sprig.Primitives
import Graphics.UI.SDL.Sprig.Transform
import Graphics.UI.SDL.Sprig.Control
import Graphics.UI.SDL.Sprig.Drawing
|
liamoc/sprig-hs
|
Graphics/UI/SDL/Sprig.hs
|
bsd-3-clause
| 556
| 0
| 5
| 136
| 80
| 61
| 19
| 8
| 0
|
-- | Simple module for producing Graphviz diagrams of Petri Nets
module NPNTool.Graphviz (drawPT, drawWithLab,drawBP) where
import NPNTool.PetriNet
import NPNTool.NPNet
import NPNTool.Unfoldings
import Data.Set (Set)
import qualified Data.Set as S
import Data.Foldable (Foldable)
import qualified Data.Foldable as F
showSet :: Show a => Set a -> String
showSet = concatMap ((++ "; ") . show) . S.toList
showPre :: (Show p, Foldable n) => Net p Trans n m -> Trans -> String
showPre (Net {pre=pre}) t =
F.concatMap ((++ " -> \"" ++ show t ++ "\"; ") . show) (pre t)
showPost :: (Show p, Foldable n) => Net p Trans n m -> Trans -> String
showPost (Net {post=post}) t =
F.concatMap (\x -> "\"" ++ show t ++ "\" -> " ++ show x ++ "; ") (post t)
-- | Draw a P/T-net
drawPT :: (Show p, Foldable n) => Net p Trans n m -> String
drawPT net =
unlines
[ "digraph PT {"
, " subgraph place {"
, " graph [shape=circle,color=gray];"
, " node [shape=circle,fixedsize=true,width=1];"
, " " ++ showSet (places net)
, " }"
, " subgraph transitions {"
, " node [shape=rect,height=0.2,width=1];"
, " " ++ showSet (trans net)
, " }"
, " " ++ concatMap (showPre net) (S.toList (trans net))
, " " ++ concatMap (showPost net) (S.toList (trans net))
, "}"]
showLab :: (Show a1, Show a) => (a, a1) -> String
showLab (t, l) = filter (not . (`elem` "\"'")) $ show t ++ "_" ++ show l
showSetLab :: (Show a, Show b) => Set (a,b) -> String
showSetLab = concatMap ((++ "\"; ") . ("\"" ++ ) . showLab) . S.toList
showPreLab :: (Show p, Foldable n, Show l) => Net p Trans n m -> (Trans, Maybe l) -> String
showPreLab (Net {pre=pre}) tr@(t,l) =
F.concatMap ((++ " -> \"" ++ showLab tr ++ "\"; ") . show) (pre t)
showPostLab :: (Show p, Foldable n, Show l) => Net p Trans n m -> (Trans, Maybe l) -> String
showPostLab (Net {post=post}) tr@(t,l) =
F.concatMap (\x -> "\"" ++ showLab tr ++ "\" -> " ++ show x ++ "; ") (post t)
-- | Draws a net using the labelling for transitions
drawWithLab :: (Show p, Foldable n, Show l, Ord l) => Net p Trans n m -> Labelling l -> String
drawWithLab net lab =
unlines
[ "digraph PT {"
, " subgraph place {"
, " graph [shape=circle,color=gray];"
, " node [shape=circle,fixedsize=true,width=1];"
, " " ++ showSet (places net)
, " }"
, " subgraph transitions {"
, " node [shape=rect,height=0.2,width=1];"
, " " ++ showSetLab tr
, " }"
, " " ++ concatMap (showPreLab net) (S.toList tr)
, " " ++ concatMap (showPostLab net) (S.toList tr)
, "}"]
where tr = S.map (\x -> (x, lab x)) (trans net)
-- | Draws a branching process
drawBP :: BProc -> String
drawBP bp@(net,(hp,ht)) = unlines
[ "digraph PT {"
, " subgraph place {"
, " graph [shape=circle,color=gray];"
, " node [shape=circle,fixedsize=true,width=1];"
, " " ++ showSetLab ps
, " }"
, " subgraph transitions {"
, " node [shape=rect,height=0.2,width=1];"
, " " ++ showSetLab tr
, " }"
, " " ++ concatMap (showPreBP bp) (S.toList tr)
, " " ++ concatMap (showPostBP bp) (S.toList tr)
, "}"]
where tr = S.map (\x -> (x, ht x)) (trans net)
ps = S.map (\p -> (p, hp p)) (places net)
showPreBP :: BProc -> (PTTrans, PTTrans) -> String
showPreBP (Net {pre=pre},(hp,ht)) tr@(t,tl) =
F.concatMap (\p -> "\"" ++ showLab (p, hp p) ++ "\" -> \"" ++ showLab tr ++ "\"; ") (pre t)
showPostBP :: BProc -> (PTTrans, PTTrans) -> String
showPostBP (Net {post=post},(hp,ht)) tr@(t,tl) =
F.concatMap (\x -> "\"" ++ showLab tr ++ "\" -> \"" ++ showLab (x, hp x) ++ "\"; ") (post t)
|
co-dan/NPNTool
|
src/NPNTool/Graphviz.hs
|
bsd-3-clause
| 3,801
| 0
| 14
| 1,032
| 1,502
| 813
| 689
| 82
| 1
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Test.Hspec.Control where
import Control.Monad.Base
import Control.Monad.Trans.Control
import Control.Monad.Trans.Writer
import Data.Functor (($>))
import Test.Hspec.Core.Spec
instance MonadBase IO (SpecM a) where
liftBase = runIO
instance MonadBaseControl IO (SpecM a) where
type StM (SpecM a) r = (r, [SpecTree a])
liftBaseWith f = runIO (f runSpecM')
where runSpecM' (SpecM specs) = runWriterT specs
restoreM (r, specs) = fromSpecList specs $> r
|
bmjames/hspec-monad-control
|
Test/Hspec/Control.hs
|
bsd-3-clause
| 539
| 0
| 10
| 82
| 171
| 97
| 74
| 15
| 0
|
module HPage.Utils.Log where
import Control.Monad.Trans
import Data.Time()
import Data.Time.Clock
data LogLevel = Trace | Debug | Info | Warning | Error | Fatal
deriving (Show, Eq)
logIO :: Show a => LogLevel -> a -> IO ()
logIO lvl msg = getCurrentTime >>= \ts -> putStrLn $ (show ts) ++ " (" ++ (show lvl) ++ "): " ++ (show msg)
liftLogIO :: (MonadIO m, Show a) => LogLevel -> a -> m ()
liftLogIO _ _ = return () -- lvl = liftIO . (logIO lvl)
traceIO, debugIO, infoIO, warnIO, errorIO, fatalIO :: Show a => a -> IO ()
liftTraceIO, liftDebugIO, liftInfoIO, liftWarnIO, liftErrorIO, liftFatalIO :: (MonadIO m, Show a) => a -> m ()
{- with(out) log...
traceIO = logIO Trace
debugIO _ = return ()
-}
traceIO _ = return ()
debugIO = logIO Debug
infoIO = logIO Info
warnIO = logIO Warning
errorIO = logIO Error
fatalIO = logIO Fatal
{- without log...
liftTraceIO _ = return ()
liftDebugIO _ = return ()
-}
liftTraceIO = liftLogIO Trace
liftDebugIO = liftLogIO Debug
liftInfoIO = liftLogIO Info
liftWarnIO = liftLogIO Warning
liftErrorIO = liftLogIO Error
liftFatalIO = liftLogIO Fatal
|
elbrujohalcon/hPage
|
src/HPage/Utils/Log.hs
|
bsd-3-clause
| 1,094
| 0
| 13
| 206
| 364
| 201
| 163
| 24
| 1
|
module Data.Astro.SunTest
(
tests
)
where
import Test.Framework (testGroup)
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit
import Test.HUnit.Approx
import Test.QuickCheck
import Control.Monad (unless)
import Data.Astro.TypesTest (testDecimalDegrees, testDecimalHours)
import Data.Astro.CoordinateTest (testEC1)
import Data.Astro.Types (DecimalDegrees(..), DecimalHours(..), GeographicCoordinates(..), fromDMS, fromHMS)
import Data.Astro.Time.JulianDate (JulianDate(..), LocalCivilTime(..), lctFromYMDHMS, LocalCivilDate(..), lcdFromYMD)
import Data.Astro.Time.Epoch (j2010)
import Data.Astro.Coordinate (EquatorialCoordinates1(..))
import Data.Astro.Sun
tests = [testGroup "sunDetails" [
testSunDetails "J2010.0"
0.000001
(SunDetails j2010 (DD 279.557208) (DD 283.112438) 0.016705)
(sunDetails j2010)
]
, testGroup "the Sun's coordinates" [
-- The Astronomycal Almanach gives (EC1 (fromDMS 19 21 16) (fromHMS 8 23 33))
testEC1 "(1) at 2003-07-27 00:00:00"
0.000001
(EC1 (fromDMS 19 21 17.4394) (fromHMS 8 23 32.8286))
(sunPosition1 j2010SunDetails (JD 2452847.5))
, testEC1 "(1) at 2016-08-11 13:30:00"
0.000001
(EC1 (fromDMS 15 2 5.1480) (fromHMS 9 26 49.9629))
(sunPosition1 j2010SunDetails (JD 2457612.0625))
-- The Astronomycal Almanach gives (EC1 (fromDMS 19 12 52) (fromHMS 8 26 3))
, testEC1 "(1) at 1988-07-27 00:00:00"
0.000001
(EC1 (fromDMS 19 12 50.6369) (fromHMS 8 26 3.6147))
(sunPosition1 j2010SunDetails (JD 2447369.5))
-- The Astronomycal Almanach gives (EC1 (fromDMS 19 12 52) (fromHMS 8 26 3))
, testEC1 "(2) at 1988-07-27 00:00:00"
0.000001
(EC1 (fromDMS 19 12 48.9604) (fromHMS 8 26 4.1004))
(sunPosition2 (JD 2447369.5))
-- The Astronomycal Almanach gives (EC1 (fromDMS 19 21 16) (fromHMS 8 23 33))
, testEC1 "(2) at 2003-07-27 00:00:00"
0.000001
(EC1 (fromDMS 19 21 9.2633) (fromHMS 8 23 35.2376))
(sunPosition2 (JD 2452847.5))
]
, testGroup "distance" [
testCase "at 1988-07-27 00:00:00" $ assertApproxEqual ""
1
151920130
(sunDistance (JD 2447369.5))
, testCase "at 2016-08-12 13:30:00" $ assertApproxEqual ""
1
151577454
(sunDistance (JD 2457613.0625))
, testCase "at 2010-10-10 18:00:00" $ assertApproxEqual ""
1
149373939
(sunDistance (JD 2455480.25))
]
, testGroup "angular size" [
testDecimalDegrees "at 1988-07-27 00:00:00"
0.000001
(fromDMS 0 31 29.9308)
(sunAngularSize (JD 2447369.5))
, testDecimalDegrees "at 2016-08-12 13:30:00"
0.000001
(fromDMS 0 31 34.2034)
(sunAngularSize (JD 2457613.0625))
, testDecimalDegrees "at 2010-10-10 18:00:00"
0.000001
(fromDMS 0 32 2.1461)
(sunAngularSize (JD 2455480.25))
]
, testGroup "Sun's rise and set" [
-- sunrise/set times are from http://timeanddate.com
-- coordinates are from http://dateandtime.info
testRiseSet "Venice at 2016-08-12; Rise: 06:08, DD 68; Set: 20:22, DD 292"
0.000001
(RiseSet
(Just (lctFromYMDHMS 2 2016 8 12 6 8 1.2955, DD 67.6609383))
(Just (lctFromYMDHMS 2 2016 8 12 20 22 17.5593, DD 292.0714064)))
(sunRiseAndSet (GeoC (DD 45.43713) (12.33265)) 0.833333 (lcdFromYMD 2 2016 8 12))
, testRiseSet "Ulaanbaatar at 2016-08-13; Rise: 06:45, DD 67; Set: 21:09, DD 293"
0.000001
(RiseSet
(Just (lctFromYMDHMS 9 2016 8 13 6 44 43.1358, DD 66.8644763))
(Just (lctFromYMDHMS 9 2016 8 13 21 8 49.7896, DD 292.8475000)))
(sunRiseAndSet (GeoC (DD 47.90771) (106.88324)) 0.833333 (lcdFromYMD 9 2016 8 13))
, testRiseSet "Lima at 2016-08-12; Rise: 06:22, DD 75; Set: 18:04, DD 285"
0.000001
(RiseSet
(Just (lctFromYMDHMS (-5) 2016 8 12 6 22 22.2308, DD 75.0822853))
(Just (lctFromYMDHMS (-5) 2016 8 12 18 3 41.7631, DD 284.7661756)))
(sunRiseAndSet (GeoC (DD $ -12.04318) (DD $ -77.02824)) 0.833333 (lcdFromYMD (-5) 2016 8 12))
, testRiseSet "Longyearbyen at 2016-08-12; Circumpolar"
0.000001
Circumpolar
(sunRiseAndSet (GeoC (DD 78.22) (DD 15.65)) 0.833333 (lcdFromYMD 2 2016 8 12))
, testRiseSet "Longyearbyen at 2017-01-12; Down all day"
0.000001
NeverRises
(sunRiseAndSet (GeoC (DD 78.22) (DD 15.65)) 0.833333 (lcdFromYMD 2 2017 1 12))
, testRiseSet "Anchorage at 2016-08-13; Rise: 06:05, DD 57; Set: 22:02, DD 302"
0.000001
(RiseSet
(Just (lctFromYMDHMS (-8) 2016 8 13 6 4 29.3945, DD 57.0595036))
(Just (lctFromYMDHMS (-8) 2016 8 13 22 2 8.3067, DD 302.4495529)))
(sunRiseAndSet (GeoC (DD 61.21806) (-149.90028)) 0.833333 (lcdFromYMD (-8) 2016 8 13))
, testRiseSet "Kazan at 2016-08-18; Rise: 04:21, DD 65; Set: 19:12, DD 295"
0.000001
(RiseSet
(Just (lctFromYMDHMS 3 2016 8 18 4 21 19.3153, DD 65.0507218))
(Just (lctFromYMDHMS 3 2016 8 18 19 11 46.7175,DD 294.5658995)))
(sunRiseAndSet (GeoC 55.78874 49.1221400) 0.833333 $ lcdFromYMD 3 2016 8 18)
],
testGroup "equationOfTime" [
testDecimalHours "zero at June"
(1/3600)
(-(fromHMS 0 0 1))
(equationOfTime $ JD 2457551.5)
, testDecimalHours "minimum at February"
(1/3600)
(-(fromHMS 0 14 7))
(equationOfTime $ JD 2457429.5)
, testDecimalHours "maximum at November"
(1/3600)
(fromHMS 0 16 18)
(equationOfTime $ JD 2457694.5)
]
, testGroup "solarElongation" [
testDecimalDegrees "Mars at 2010-07-27 20:00:00 UT"
0.0000001
(DD 24.7905087)
(solarElongation (EC1 (fromDMS 11 57 27) (fromHMS 10 6 45)) (JD 2455405.3333333335))
]
]
testSunDetails msg eps expected actual =
testCase msg $ assertSunDetails eps expected actual
assertSunDetails eps expected@(SunDetails (JD eJd) (DD eEps) (DD eOm) eE) actual@(SunDetails (JD aJd) (DD aEps) (DD aOm) aE) =
unless (abs(eJd-aJd) <= eps && abs(eEps-aEps) <= eps
&& abs(eOm-aOm) <= eps && abs(eE-aE) <= eps) (assertFailure msg)
where msg = "expected: " ++ show expected ++ "\n but got: " ++ show actual ++
"\n (maximum margin of error: " ++ show eps ++ ")"
testRiseSet msg eps expected actual =
testCase msg $ assertRiseSet eps expected actual
assertRiseSet eps expected@(RiseSet er es) actual@(RiseSet ar as) =
unless (eqMaybeRS eps er ar && eqMaybeRS eps es as) (assertFailure msg)
where msg = "expected: " ++ show expected ++ "\n but got: " ++ show actual ++
"\n (maximum margin of error: " ++ show eps ++ ")"
assertRiseSet _ Circumpolar Circumpolar = assertString ""
assertRiseSet _ Circumpolar actual = assertString msg
where msg = "expected: Circumpolar\n but got: " ++ show actual
assertRiseSet _ NeverRises NeverRises = assertString ""
assertRiseSet _ NeverRises actual = assertString msg
where msg = "expected: NeverRises\n but got: " ++ show actual
eqMaybeRS eps (Just rs1) (Just rs2) = eqRS eps rs1 rs2
eqMaybeRS _ Nothing Nothing = True
eqMaybeRS _ _ _ = False
eqRS eps (LCT (DH tz1) (JD j1), DD d1) (LCT (DH tz2) (JD j2), DD d2) = abs (j1-j2) < eps && abs (tz1-tz2) < eps && abs (d1-d2) < eps
|
Alexander-Ignatyev/astro
|
test/Data/Astro/SunTest.hs
|
bsd-3-clause
| 8,710
| 0
| 16
| 3,093
| 2,306
| 1,189
| 1,117
| 149
| 1
|
{-# LANGUAGE RecordWildCards #-}
module Pos.Chain.Genesis.ProtocolConstants
( GenesisProtocolConstants (..)
, genesisProtocolConstantsToProtocolConstants
, genesisProtocolConstantsFromProtocolConstants
) where
import Universum
import Control.Monad.Except (MonadError)
import Data.Aeson.Options (defaultOptions)
import Data.Aeson.TH (deriveJSON)
import Text.JSON.Canonical (FromJSON (..), Int54, JSValue (..),
ToJSON (..), fromJSField, mkObject)
import Pos.Core.ProtocolConstants (ProtocolConstants (..),
VssMaxTTL (..), VssMinTTL (..))
import Pos.Crypto.Configuration (ProtocolMagic)
import Pos.Util.Json.Canonical (SchemaError)
-- | 'GensisProtocolConstants' are not really part of genesis global state,
-- but they affect consensus, so they are part of 'GenesisSpec' and
-- 'GenesisData'.
data GenesisProtocolConstants = GenesisProtocolConstants
{ -- | Security parameter from the paper.
gpcK :: !Int
-- | Magic constant for separating real/testnet.
, gpcProtocolMagic :: !ProtocolMagic
-- | VSS certificates max timeout to live (number of epochs).
, gpcVssMaxTTL :: !VssMaxTTL
-- | VSS certificates min timeout to live (number of epochs).
, gpcVssMinTTL :: !VssMinTTL
} deriving (Show, Eq, Generic)
instance Monad m => ToJSON m GenesisProtocolConstants where
toJSON GenesisProtocolConstants {..} =
mkObject
-- 'k' definitely won't exceed the limit
[ ("k", pure . JSNum . fromIntegral $ gpcK)
, ("protocolMagic", toJSON gpcProtocolMagic)
, ("vssMaxTTL", toJSON gpcVssMaxTTL)
, ("vssMinTTL", toJSON gpcVssMinTTL)
]
instance MonadError SchemaError m => FromJSON m GenesisProtocolConstants where
fromJSON obj = do
gpcK <- fromIntegral @Int54 <$> fromJSField obj "k"
gpcProtocolMagic <- fromJSField obj "protocolMagic"
gpcVssMaxTTL <- fromJSField obj "vssMaxTTL"
gpcVssMinTTL <- fromJSField obj "vssMinTTL"
return GenesisProtocolConstants {..}
deriveJSON defaultOptions ''GenesisProtocolConstants
genesisProtocolConstantsToProtocolConstants
:: GenesisProtocolConstants
-> ProtocolConstants
genesisProtocolConstantsToProtocolConstants GenesisProtocolConstants {..} =
ProtocolConstants
{ pcK = gpcK
, pcVssMinTTL = gpcVssMinTTL
, pcVssMaxTTL = gpcVssMaxTTL
}
genesisProtocolConstantsFromProtocolConstants
:: ProtocolConstants
-> ProtocolMagic
-> GenesisProtocolConstants
genesisProtocolConstantsFromProtocolConstants ProtocolConstants {..} pm =
GenesisProtocolConstants
{ gpcK = pcK
, gpcProtocolMagic = pm
, gpcVssMinTTL = pcVssMinTTL
, gpcVssMaxTTL = pcVssMaxTTL
}
|
input-output-hk/pos-haskell-prototype
|
chain/src/Pos/Chain/Genesis/ProtocolConstants.hs
|
mit
| 2,915
| 0
| 11
| 726
| 504
| 290
| 214
| -1
| -1
|
{- DATX02-17-26, automated assessment of imperative programs.
- Copyright, 2017, see AUTHORS.md.
-
- 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
-- | Test for eliminating redundant blocks and statements
module Norm.SOPTest (
allTests
) where
import Norm.NormTestUtil
import Norm.SumsOfProducts
normalizers :: NormalizerCU
normalizers = [ normSOP ]
allTests :: TestTree
allTests = testGroup "Norm.SumsOfProducts tests"
[ normTestDir "sop_unittest_1" "sop" 1 normalizers
]
|
Centril/DATX02-17-26
|
Test/Norm/SOPTest.hs
|
gpl-2.0
| 1,165
| 0
| 7
| 214
| 63
| 37
| 26
| 9
| 1
|
{- |
Module : ./CASL/OMDocImport.hs
Description : OMDoc-to-CASL conversion
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : ewaryst.schulz@dfki.de
Stability : provisional
Portability : portable
CASL implementation of the interface functions omdocToSym, omdocToSen
, addOMadtToTheory, addOmdocToTheory from class Logic. The actual
instantiation can be found in module "CASL.Logic_CASL".
-}
module CASL.OMDocImport
( omdocToSym
, omdocToSen
, addOMadtToTheory
, addOmdocToTheory
) where
import OMDoc.DataTypes
import Common.Id
import Common.Result
import Common.AS_Annotation
import qualified Common.Lib.Rel as Rel
import CASL.AS_Basic_CASL
import CASL.Sign
import CASL.OMDoc
import Control.Monad
import qualified Data.Map as Map
import Data.List
import Data.Function (on)
-- * Environment Interface
type Env = SigMapI Symbol
symbolToSort :: Symbol -> SORT
symbolToSort (Symbol n SortAsItemType) = n
symbolToSort s = error $ "symbolToSort: Nonsort encountered: " ++ show s
symbolToOp :: Symbol -> (Id, OpType)
symbolToOp (Symbol n (OpAsItemType ot)) = (n, ot)
symbolToOp s = error $ "symbolToOp: Nonop encountered: " ++ show s
symbolToPred :: Symbol -> (Id, PredType)
symbolToPred (Symbol n (PredAsItemType pt)) = (n, pt)
symbolToPred s = error $ "symbolToPred: Nonpred encountered: " ++ show s
lookupSymbol :: Env -> OMName -> Symbol
lookupSymbol e omn =
Map.findWithDefault
(error $ concat [ "lookupSymbol failed for: "
, show omn, "\nmap: ", show $ sigMapISymbs e])
omn $ sigMapISymbs e
lookupSort :: Env -> OMName -> SORT
lookupSort e = symbolToSort . lookupSymbol e
lookupSortOMS :: String -> Env -> OMElement -> SORT
lookupSortOMS msg = lookupOMS lookupSort $ msg ++ "(SORT)"
lookupPred :: Env -> OMName -> (Id, PredType)
lookupPred e = symbolToPred . lookupSymbol e
lookupPredOMS :: String -> Env -> OMElement -> (Id, PredType)
lookupPredOMS msg = lookupOMS lookupPred $ msg ++ "(PRED)"
lookupOp :: Env -> OMName -> (Id, OpType)
lookupOp e = symbolToOp . lookupSymbol e
lookupOpOMS :: String -> Env -> OMElement -> (Id, OpType)
lookupOpOMS msg = lookupOMS lookupOp $ msg ++ "(Op)"
lookupOMS :: (Env -> OMName -> a) -> String -> Env -> OMElement -> a
lookupOMS f msg e oms@(OMS (cd, omn)) =
if cdIsEmpty cd then f e omn
else error $ concat [ msg, ": lookupOMS: Nonempty cd in const: "
, show oms]
lookupOMS _ msg _ ome =
error $ concat [msg, ": lookupOMS: Nonsymbol: ", show ome]
toOpSymb :: (Id, OpType) -> OP_SYMB
toOpSymb (i, t) = Qual_op_name i (toOP_TYPE t) nullRange
toPredSymb :: (Id, PredType) -> PRED_SYMB
toPredSymb (i, t) = Qual_pred_name i (toPRED_TYPE t) nullRange
-- * TOPLEVEL Interface
-- | A TCSymbols is transformed to a CASL symbol with given name.
omdocToSym :: Env -> TCElement -> String -> Result Symbol
omdocToSym e sym@(TCSymbol _ ctp srole _) n =
case srole of
Typ | ctp == const_sort -> return $ idToSortSymbol $ nameToId n
| otherwise -> fail $ "omdocToSym: No sorttype for " ++ show sym
Obj -> return $
case omdocToType e ctp of
Left ot -> idToOpSymbol (nameToId n) ot
Right pt -> idToPredSymbol (nameToId n) pt
_ -> fail $ concat [ "omdocToSym: only type or object are allowed as"
, " symbol roles, but found: ", show srole ]
omdocToSym _ sym _ = fail $ concat [ "omdocToSym: only TCSymbol is allowed,"
, " but found: ", show sym ]
omdocToSen :: Env -> TCElement -> String
-> Result (Maybe (Named (FORMULA f)))
omdocToSen e (TCSymbol _ t sr _) n =
case nameDecode n of
Just _ ->
return Nothing -- don't translate encoded names here
Nothing ->
let ns = makeNamed n $ omdocToFormula e t
res b = return $ Just $ ns { isAxiom = b }
in case sr of
Axiom -> res True
Theorem -> res False
_ -> return Nothing
omdocToSen _ sym _ = fail $ concat [ "omdocToSen: only TCSymbol is allowed,"
, " but found: ", show sym ]
-- | Sort generation constraints are added as named formulas.
addOMadtToTheory :: Env
-> (Sign f e, [Named (FORMULA f)]) -> [[OmdADT]]
-> Result (Sign f e, [Named (FORMULA f)])
addOMadtToTheory e (sig, nsens) adts = do
sgcs <- mapR (omdocToSortGenConstraint e) adts
return (sig, nsens ++ sgcs)
-- | The subsort relation is recovered from exported sentences.
addOmdocToTheory :: Env -> (Sign f e, [Named (FORMULA f)]) -> [TCElement]
-> Result (Sign f e, [Named (FORMULA f)])
addOmdocToTheory e (sig, nsens) tcs = do
srel <- omdocToSortRel e tcs
return (sig { sortRel = Rel.transClosure srel }, nsens)
-- * Algebraic Data Types
omdocToSortGenConstraint :: Env -> [OmdADT] -> Result (Named (FORMULA f))
omdocToSortGenConstraint e sortdefs = do
-- take the last type as the type of all constraints
let (t, cs) = mapAccumL (const $ mkConstraint e) Generated sortdefs
-- TODO: do we take newSort or origSort?
return $ toSortGenNamed (mkSort_gen_ax cs $ t == Free) $ map newSort cs
mkConstraint :: Env -> OmdADT -> (ADTType, Constraint)
mkConstraint e (ADTSortDef nm t constrs) =
let s = lookupSort e $ mkSimpleName nm
l = map (mkConstructor e s) constrs
in (t, Constraint s l s)
mkConstraint _ _ = error "mkConstraint: Malformed ADT expression"
mkConstructor :: Env -> SORT -> OmdADT -> (OP_SYMB, [Int])
mkConstructor e s (ADTConstr nm args) =
let opn = nameToId $ lookupNotation e $ mkSimpleName nm
l = map (mkArg e) args
in (Qual_op_name opn (Op_type Total l s nullRange) nullRange, [0])
{- we have to create the name of this injection because we throw it away
during the export -}
mkConstructor e s (ADTInsort (_, omn)) =
let argsort = lookupSort e omn
opn = mkUniqueInjName argsort s
in (Qual_op_name opn (Op_type Total [argsort] s nullRange) nullRange, [0])
mkConstructor _ _ _ = error "mkConstructor: Malformed ADT expression"
mkArg :: Env -> OmdADT -> SORT
mkArg e (ADTArg oms _) = lookupSortOMS "mkArg" e oms
mkArg _ _ = error "mkArg: Malformed ADT expression"
-- * Subsort Relation
omdocToSortRel :: Env -> [TCElement] -> Result (Rel.Rel SORT)
omdocToSortRel e = foldM (addMaybeToSortRel e) Rel.empty
addMaybeToSortRel :: Env -> Rel.Rel SORT -> TCElement -> Result (Rel.Rel SORT)
addMaybeToSortRel e r (TCSymbol n (OMA [sof, oms1, oms2]) Axiom _) =
case nameDecode n of
Just ("ST", _)
| sof == const_subsortof ->
let s1 = lookupSortOMS "addMaybeToSortRel: s1" e oms1
s2 = lookupSortOMS "addMaybeToSortRel: s2" e oms2
in return $ Rel.insertKeyOrPair s1 s2 r
| otherwise ->
do
warning () ("Use of subsortof in a non ST Statement: " ++ n)
nullRange
return r
_ -> return r
addMaybeToSortRel _ r _ = return r
-- * Types
omdocToType :: Env -> OMElement -> Either OpType PredType
omdocToType e (OMA (c : args)) =
let sorts = map (lookupSortOMS "omdocToType" e) args
opargs = init sorts
oprange = last sorts
res | c == const_predtype = Right $ PredType sorts
| c == const_partialfuntype = Left $ OpType Partial opargs oprange
| c == const_funtype = Left $ OpType Total opargs oprange
| otherwise = error $ "omdocToType: unknown type constructor: "
++ show c
in res
omdocToType e oms@(OMS _)
| oms == const_predtype = Right $ PredType []
| otherwise = Left $ OpType Total [] $ lookupSortOMS "omdocToType" e oms
omdocToType _ ome = error $ "omdocToType: Non-supported element: " ++ show ome
-- * Terms and Formulas
type VarMap = Map.Map VAR SORT
type TermEnv = (Env, VarMap)
mkImplication, mkImplied, mkEquivalence
, mkNegation :: [FORMULA f] -> FORMULA f
mkImplication [x, y] = mkImpl x y
mkImplication _ = error "Malformed implication"
mkImplied [x, y] = mkRel RevImpl x y
mkImplied _ = error "Malformed if"
mkEquivalence [x, y] = mkEqv x y
mkEquivalence _ = error "Malformed equivalence"
mkNegation [x] = mkNeg x
mkNegation _ = error "Malformed negation"
mkDefinedness, mkExistl_equation, mkStrong_equation
:: [TERM f] -> FORMULA f
mkDefinedness [x] = Definedness x nullRange
mkDefinedness _ = error "Malformed definedness"
mkExistl_equation [x, y] = mkExEq x y
mkExistl_equation _ = error "Malformed existl equation"
mkStrong_equation [x, y] = mkStEq x y
mkStrong_equation _ = error "Malformed strong equation"
-- Quantification, Predication and Membership are handled inside omdocToFormula
-- Term construction functions
mkT2 :: (OMElement -> a) -> (OMElement -> b) -> (a -> b -> Range -> TERM f)
-> [OMElement] -> TERM f
mkT2 f g c l = case l of
[x, y] -> c (f x) (g y) nullRange
_ -> error "mkT2: 2 arguments expected"
mkT3 :: (OMElement -> a) -> (OMElement -> b) -> (OMElement -> c)
-> (a -> b -> c -> Range -> TERM f) -> [OMElement] -> TERM f
mkT3 f g h c l = case l of
[x, y, z] -> c (f x) (g y) (h z) nullRange
_ -> error "mkT3: 3 arguments expected"
-- Formula construction functions
mkFF :: TermEnv -> ([FORMULA f] -> FORMULA f) -> [OMElement] -> FORMULA f
mkFF e f l = f $ map (omdocToFormula' e) l
mkTF :: TermEnv -> ([TERM f] -> FORMULA f) -> [OMElement] -> FORMULA f
mkTF e f l = f $ map (omdocToTerm' e) l
getQuantifier :: OMElement -> QUANTIFIER
getQuantifier oms
| oms == const_forall = Universal
| oms == const_exists = Existential
| oms == const_existsunique = Unique_existential
| otherwise = error $ "getQuantifier: unrecognized quantifier " ++ show oms
mkBinder :: TermEnv -> QUANTIFIER -> [OMElement] -> OMElement -> FORMULA f
mkBinder te@(e, _) q vars body =
let (vm', vardecls) = toVarDecls te vars
bd = omdocToFormula' (e, vm') body
in Quantification q vardecls bd nullRange
toVarDecls :: TermEnv -> [OMElement] -> (VarMap, [VAR_DECL])
toVarDecls (e, vm) l =
let f acc x = let (v, s) = toVarDecl e x
acc' = Map.insert v s acc
in (acc', (v, s))
(vm', l') = mapAccumL f vm l
-- group by same sort
l'' = groupBy ((==) `Data.Function.on` snd) l'
-- the lists returned by groupBy are never empty, so head will succeed
g vsl = Var_decl (map fst vsl) (snd $ head vsl) nullRange
in (vm', map g l'')
-- in CASL we expect all bound vars to be attributed (typed)
toVarDecl :: Env -> OMElement -> (VAR, SORT)
toVarDecl e (OMATTT (OMV v) (OMAttr ct t))
| ct == const_type = (nameToToken $ name v, lookupSortOMS "toVarDecl" e t)
| otherwise = error $ "toVarDecl: unrecognized attribution " ++ show ct
toVarDecl _ _ = error "toVarDecl: bound variables should be attributed."
-- Toplevel entry point
omdocToFormula :: Env -> OMElement -> FORMULA f
omdocToFormula e = omdocToFormula' (e, Map.empty)
-- Functions with given VarMap
-- omdocToTerm has no toplevel entry point
omdocToTerm' :: TermEnv -> OMElement -> TERM f
omdocToTerm' e@(ie, vm) f =
case f of
OMA (h : args)
| h == const_cast ->
mkT2 (omdocToTerm' e) (lookupSortOMS "omdocToTerm: Cast" ie)
Cast args
| h == const_if ->
mkT3 (omdocToTerm' e) (omdocToFormula' e) (omdocToTerm' e)
Conditional args
-- all other heads mean application
| otherwise ->
let os = toOpSymb $ lookupOpOMS "omdocToTerm" ie h
args' = map (omdocToTerm' e) args
in Application os args' nullRange
OMS _ -> let os = toOpSymb $ lookupOpOMS "omdocToTerm-OMS:" ie f
in Application os [] nullRange
OMV omn -> let var = nameToToken $ name omn
-- lookup the type of the variable in the varmap
s = Map.findWithDefault
(error $ concat [ "omdocToTerm': Variable not in "
, "varmap: ", show var ]) var vm
in Qual_var var s nullRange
OMATTT ome (OMAttr ct t)
| ct == const_type ->
-- same as cast
mkT2 (omdocToTerm' e) (lookupSortOMS "omdocToTerm: Sorted" ie)
Sorted_term [ome, t]
| otherwise -> error $ "omdocToTerm: unrecognized attribution "
++ show ct
_ -> error $ "omdocToTerm: no valid term " ++ show f
omdocToFormula' :: TermEnv -> OMElement -> FORMULA f
omdocToFormula' e@(ie, _) f =
case f of
OMA (h : args)
| h == const_in ->
case args of
[x, s] ->
Membership (omdocToTerm' e x) (lookupSortOMS
"omdocToFormula"
ie s) nullRange
_ -> error "Malformed membership"
| h == const_and ->
mkFF e conjunct args
| h == const_or ->
mkFF e disjunct args
| h == const_implies ->
mkFF e mkImplication args
| h == const_implied ->
mkFF e mkImplied args
| h == const_equivalent ->
mkFF e mkEquivalence args
| h == const_not ->
mkFF e mkNegation args
| h == const_def ->
mkTF e mkDefinedness args
| h == const_eeq ->
mkTF e mkExistl_equation args
| h == const_eq ->
mkTF e mkStrong_equation args
-- all other heads mean predication
| otherwise ->
let ps = toPredSymb $ lookupPredOMS "omdocToFormula" ie h
g l = Predication ps l nullRange in
mkTF e g args
OMBIND binder args body ->
mkBinder e (getQuantifier binder) args body
OMS _ | f == const_true -> trueForm
| f == const_false -> falseForm
-- Propositional Constants (0-ary predicates):
| otherwise ->
Predication (toPredSymb
$ lookupPredOMS
("omdocToFormula: can't handle constant "
++ show f) ie f) [] nullRange
_ -> error $ "omdocToFormula: no valid formula " ++ show f
|
spechub/Hets
|
CASL/OMDocImport.hs
|
gpl-2.0
| 14,606
| 0
| 17
| 4,325
| 4,477
| 2,261
| 2,216
| 282
| 5
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.MachineLearning.UpdateMLModel
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the 'MLModelName' and the 'ScoreThreshold' of an 'MLModel'.
--
-- You can use the GetMLModel operation to view the contents of the updated
-- data element.
--
-- /See:/ <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_UpdateMLModel.html AWS API Reference> for UpdateMLModel.
module Network.AWS.MachineLearning.UpdateMLModel
(
-- * Creating a Request
updateMLModel
, UpdateMLModel
-- * Request Lenses
, umlmMLModelName
, umlmScoreThreshold
, umlmMLModelId
-- * Destructuring the Response
, updateMLModelResponse
, UpdateMLModelResponse
-- * Response Lenses
, umlmrsMLModelId
, umlmrsResponseStatus
) where
import Network.AWS.MachineLearning.Types
import Network.AWS.MachineLearning.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'updateMLModel' smart constructor.
data UpdateMLModel = UpdateMLModel'
{ _umlmMLModelName :: !(Maybe Text)
, _umlmScoreThreshold :: !(Maybe Double)
, _umlmMLModelId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateMLModel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'umlmMLModelName'
--
-- * 'umlmScoreThreshold'
--
-- * 'umlmMLModelId'
updateMLModel
:: Text -- ^ 'umlmMLModelId'
-> UpdateMLModel
updateMLModel pMLModelId_ =
UpdateMLModel'
{ _umlmMLModelName = Nothing
, _umlmScoreThreshold = Nothing
, _umlmMLModelId = pMLModelId_
}
-- | A user-supplied name or description of the 'MLModel'.
umlmMLModelName :: Lens' UpdateMLModel (Maybe Text)
umlmMLModelName = lens _umlmMLModelName (\ s a -> s{_umlmMLModelName = a});
-- | The 'ScoreThreshold' used in binary classification 'MLModel' that marks
-- the boundary between a positive prediction and a negative prediction.
--
-- Output values greater than or equal to the 'ScoreThreshold' receive a
-- positive result from the 'MLModel', such as 'true'. Output values less
-- than the 'ScoreThreshold' receive a negative response from the
-- 'MLModel', such as 'false'.
umlmScoreThreshold :: Lens' UpdateMLModel (Maybe Double)
umlmScoreThreshold = lens _umlmScoreThreshold (\ s a -> s{_umlmScoreThreshold = a});
-- | The ID assigned to the 'MLModel' during creation.
umlmMLModelId :: Lens' UpdateMLModel Text
umlmMLModelId = lens _umlmMLModelId (\ s a -> s{_umlmMLModelId = a});
instance AWSRequest UpdateMLModel where
type Rs UpdateMLModel = UpdateMLModelResponse
request = postJSON machineLearning
response
= receiveJSON
(\ s h x ->
UpdateMLModelResponse' <$>
(x .?> "MLModelId") <*> (pure (fromEnum s)))
instance ToHeaders UpdateMLModel where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("AmazonML_20141212.UpdateMLModel" :: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON UpdateMLModel where
toJSON UpdateMLModel'{..}
= object
(catMaybes
[("MLModelName" .=) <$> _umlmMLModelName,
("ScoreThreshold" .=) <$> _umlmScoreThreshold,
Just ("MLModelId" .= _umlmMLModelId)])
instance ToPath UpdateMLModel where
toPath = const "/"
instance ToQuery UpdateMLModel where
toQuery = const mempty
-- | Represents the output of an UpdateMLModel operation.
--
-- You can see the updated content by using the GetMLModel operation.
--
-- /See:/ 'updateMLModelResponse' smart constructor.
data UpdateMLModelResponse = UpdateMLModelResponse'
{ _umlmrsMLModelId :: !(Maybe Text)
, _umlmrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateMLModelResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'umlmrsMLModelId'
--
-- * 'umlmrsResponseStatus'
updateMLModelResponse
:: Int -- ^ 'umlmrsResponseStatus'
-> UpdateMLModelResponse
updateMLModelResponse pResponseStatus_ =
UpdateMLModelResponse'
{ _umlmrsMLModelId = Nothing
, _umlmrsResponseStatus = pResponseStatus_
}
-- | The ID assigned to the 'MLModel' during creation. This value should be
-- identical to the value of the 'MLModelID' in the request.
umlmrsMLModelId :: Lens' UpdateMLModelResponse (Maybe Text)
umlmrsMLModelId = lens _umlmrsMLModelId (\ s a -> s{_umlmrsMLModelId = a});
-- | The response status code.
umlmrsResponseStatus :: Lens' UpdateMLModelResponse Int
umlmrsResponseStatus = lens _umlmrsResponseStatus (\ s a -> s{_umlmrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-ml/gen/Network/AWS/MachineLearning/UpdateMLModel.hs
|
mpl-2.0
| 5,586
| 0
| 13
| 1,192
| 757
| 454
| 303
| 95
| 1
|
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Main
-- Copyright : (c) 2013-2015 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)
--
module Main (main) where
import Test.Tasty
import Test.AWS.Glacier
import Test.AWS.Glacier.Internal
main :: IO ()
main = defaultMain $ testGroup "Glacier"
[ testGroup "tests" tests
, testGroup "fixtures" fixtures
]
|
fmapfmapfmap/amazonka
|
amazonka-glacier/test/Main.hs
|
mpl-2.0
| 534
| 0
| 8
| 103
| 76
| 47
| 29
| 9
| 1
|
module BrownPLT.JavaScript.Contracts.Parser
( interface
, parseInterface
) where
import Control.Monad
import qualified Data.List as L
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Pos
import BrownPLT.JavaScript.Lexer
import BrownPLT.JavaScript.Parser (parseSimpleExpr', ParsedExpression,
parseBlockStmt)
import BrownPLT.JavaScript.Contracts.Types
{-
interface = interfaceItem *
interfaceItem = identifier :: contract;
| instance identifier object;
| identifier = contract;
| blockStmt
function = nonFunction * -> function
| nonFunction + ... -> function
| nonFunction
nonFunction = :flat
| contractLabel
| customConstructor(contract ,*)
| object
| ( function )
| [ contract ,* ] -- fixed length array
| [ contract , ... ] -- arbitrary length array
flat = jsExpr
object = { identifier : contract ,* }
-}
jsExpr = parseSimpleExpr'
contract :: CharParser st Contract
contract = function
function :: CharParser st Contract
function = do
pos <- getPosition
args <- nonFunction `sepBy` whiteSpace
case args of
[] -> do
reserved "->"
result <- function
return (FunctionContract pos [] Nothing result)
[arg] -> (do reserved "->"
result <- function
return (FunctionContract pos [arg] Nothing result)) <|>
(do reserved "..."
reserved "->"
result <- function
return (FunctionContract pos [] (Just arg) result)) <|>
return arg -- nonfunction
args' -> (do reserved "->"
result <- function
return (FunctionContract pos args' Nothing result)) <|>
(do reserved "..."
reserved "->" <?> "-> after ..."
result <- function
let (fixedArgs,[restArg]) = L.splitAt (length args' - 1) args'
return (FunctionContract pos fixedArgs (Just restArg) result))
namedContract :: CharParser st Contract
namedContract = do
idFirst <- letter <|> oneOf "$_"
pos <- getPosition
-- same as JavaScript (from WebBits' lexer)
idRest <- many1 (alphaNum <|> oneOf "$_")
let name = idFirst:idRest
let constr = do
args <- parens $ contract `sepBy1` comma
return (ConstructorContract pos name args)
let named = do
whiteSpace
return (NamedContract pos name)
constr <|> named
nonFunction = parens function <|> object <|> namedContract <|> array <|> flat
array :: CharParser st Contract
array = do
pos <- getPosition
reservedOp "["
elt1 <- contract
comma
let arbitrary = do
reservedOp "..."
reservedOp "]"
return (ArrayContract pos elt1)
let fixed = do
elts <- contract `sepBy` comma <?> "elements in an array contract"
reservedOp "]"
return (FixedArrayContract pos (elt1:elts))
arbitrary <|> fixed
field :: CharParser st (String,Contract)
field = do
id <- identifier
reservedOp ":"
ctc <- contract
return (id,ctc)
object :: CharParser st Contract
object = do
pos <- getPosition
fields <- braces $ field `sepBy1` (reservedOp ",")
return (ObjectContract pos fields)
flat :: CharParser st Contract
flat = do
pos <- getPosition
reservedOp ":"
expr <- jsExpr <?> "JavaScript expression"
return (FlatContract pos expr)
interfaceExport = do
reservedOp "::"
return $ \id ->
liftM2 (InterfaceExport id) getPosition contract
interfaceAlias = do
reservedOp "=" >> (return $ \id -> liftM (InterfaceAlias id) contract)
interfaceInstance = do
reserved "instance"
id <- identifier
pos <- getPosition
contract <- object
reservedOp ";"
return (InterfaceInstance id pos contract)
interfaceElement = interfaceExport <|> interfaceAlias
interface :: CharParser st [InterfaceItem]
interface = many $ interfaceInstance <|>
(stmt $ interfaceElement `fap` identifier) <|>
(liftM InterfaceStatement parseBlockStmt)
where stmt p = do { e <- p; reservedOp ";"; return e }
fap k m = do { e <- m; f <- k; f e }
parseInterface :: String -> IO [InterfaceItem]
parseInterface filename = do
chars <- readFile filename
let parser = do
whiteSpace
r <- interface
eof
return r
case parse parser filename chars of
Left err -> fail (show err)
Right exports -> return exports
|
brownplt/javascript-contracts
|
src/BrownPLT/JavaScript/Contracts/Parser.hs
|
bsd-3-clause
| 4,574
| 0
| 20
| 1,286
| 1,246
| 602
| 644
| 117
| 3
|
{-# LANGUAGE FlexibleInstances #-}
module Control.Search.Language where
import Text.PrettyPrint
import Data.Monoid hiding ((<>))
import Data.Int
import qualified Data.Map as Map
import Data.Map (Map)
spacetype ModeFZ = "FlatZincSpace"
spacetype ModeGecode = "State"
spacetype ModeMCP = "MCPProgram"
xsspace fl@(PrettyFlags ModeFZ) x str = prettyX fl (PField x str)
xsspace fl@(PrettyFlags ModeMCP) x str = prettyX fl (PField x str)
xsspace fl@(PrettyFlags ModeGecode) x str = text "((VarAccessorSpace*)msg.space(" <> prettyX fl x <> text "))->" <> text str
instance Monoid Statement where
mempty = Skip
mappend = (>>>)
data GenMode = ModeUnk | ModeGecode | ModeFZ | ModeMCP
deriving Eq
data PrettyFlags = PrettyFlags { genMode :: GenMode }
deriving Eq
renderVar :: PrettyFlags -> Value -> Doc
renderVar f@(PrettyFlags { genMode = ModeFZ }) x = case x of
(AVarElem vs s i) -> xsspace f s "iv" <> brackets (text "VAR_" <> text vs <> brackets (pr_ i))
(AVarSize vs s) -> text "VAR_" <> text vs <> text ".size()"
(BAVarElem vs s i) -> xsspace f s "bv" <> brackets (text "VAR_" <> text vs <> brackets (pr_ i))
(BAVarSize vs s) -> text "VAR_" <> text vs <> text ".size()"
(IVar vs s) -> xsspace f s "iv" <> brackets (text "VAR_" <> text vs)
where pr_ :: Value -> Doc
pr_ = prettyX f
renderVar f@(PrettyFlags { genMode = ModeGecode }) x = case x of
(AVarElem vs s i) -> xsspace f s "va.iv" <> parens (text "idx" <> parens (xsspace f s "va.map()" <> text ",\"" <> text vs <> text "\"") <> text "+" <> pr_ i)
(AVarSize vs s) -> text "size" <> parens (xsspace f s "va.map()" <> text ",\"" <> text vs <> text "\"")
(BAVarElem vs s i) -> xsspace f s "va.bv" <> parens (text "idx" <> parens (xsspace f s "va.map()" <> text ",\"" <> text vs <> text "\"") <> text "+" <> pr_ i)
(BAVarSize vs s) -> text "size" <> parens (xsspace f s "va.map()" <> text ",\"" <> text vs <> text "\"")
(IVar vs s) -> xsspace f s "va.iv" <> parens (text "idx" <> parens (xsspace f s "va.map()" <> text ",\"" <> text vs <> text "\""))
where pr_ :: Value -> Doc
pr_ = prettyX f
renderVar f@(PrettyFlags { genMode = ModeMCP }) x = case x of
(AVarElem vs s i) -> xsspace f s vs <> brackets (pretty i)
(AVarSize vs s) -> xsspace f s vs <> text ".size()"
(BAVarElem vs s i) -> xsspace f s vs <> brackets (pretty i)
(BAVarSize vs s) -> xsspace f s vs <> text ".size()"
(IVar vs s) -> xsspace f s vs
renderVar f@(PrettyFlags { genMode = ModeUnk }) _ = error "Cannot generate variable without render mode!"
class Pretty x where
prettyX :: PrettyFlags -> x -> Doc
pretty :: x -> Doc
prettyX _ = pretty
pretty = prettyX (PrettyFlags { genMode = ModeUnk })
data Struct = Struct String [(Type,String)] deriving (Show, Eq, Ord)
instance Pretty Struct where
prettyX x (Struct name fields) =
text "struct" <+> text name <+> text "{"
$+$ nest 2 (vcat [prettyX x ty <+> text f <> text ";" | (ty,f) <- fields])
$+$ text "};"
data Type = Pointer Type
| SpaceType
| Int
| Bool
| Union [(Type,String)]
| SType Struct
| THook String
deriving (Show, Eq, Ord)
data Value = IVal Int32
| BVal Bool
| RootSpace
| Minus Value Value
| Plus Value Value
| Mult Value Value
| Div Value Value
| Mod Value Value
| Abs Value
| Var String
| Ref Value
| Deref Value
| Clone Value
| Field String String
| Field' Value String
| PField Value String
| Lt Value Value
| Gq Value Value
| Gt Value Value
| Eq Value Value
| BaseContinue
| And Value Value
| Or Value Value
| Not Value
| VHook String
| Max Value Value
| AVarElem String Value Value
| AVarSize String Value
| BAVarElem String Value Value
| BAVarSize String Value
| IVar String Value
| MinDom Value
| MaxDom Value
| Degree Value
| WDegree Value
| UbRegret Value
| LbRegret Value
| Median Value
| Random
| Null
| New Struct
| Base
| Cond Value Value Value
| Assigned Value
| Dummy Int
| MaxVal
| MinVal
deriving (Show, Eq, Ord)
instance Num Value where
(-) = Minus
fromInteger = IVal . fromInteger
(+) = Plus
(*) = Mult
abs = Abs
signum = error "signum is not defined for Value"
divValue (IVal x) (IVal y) = IVal (x `div` y)
divValue x y = Div x y
true = BVal True
false = BVal False
(&&&) = And
(|||) = Or
(@>) = Gt
(@>=) = Gq
x @<= y = y `Gq` x
(@==) = Eq
(@->) = Field'
(@=>) = PField
(@<) = Lt
lex cmps l1 l2 = foldr (\(x,y,cmp) r -> (x `cmp` y) ||| ((x @== y) &&& r)) false (zip3 l1 l2 cmps)
simplValue :: Value -> Value
simplValue (Cond c t e) =
let c' = simplValue c
t' = simplValue t
e' = simplValue e
in case (c',t',e') of
(BVal True, _, _) -> t'
(BVal False, _, _) -> e'
_ | t' == e' -> t'
_ -> Cond c' t' e'
simplValue (Minus (IVal x) (IVal y)) = IVal (x - y)
simplValue (Lt x y) = Lt (simplValue x) (simplValue y)
simplValue (Gq x y) = Gq (simplValue x) (simplValue y)
simplValue (And x y) =
let x' = simplValue x
y' = simplValue y
in case (x',y') of
(x, (BVal True)) -> x
(x, (BVal False)) -> BVal False
_ -> And x' y'
simplValue (Not x) =
let x' = simplValue x
in case x' of
(BVal True) -> BVal False
(BVal False) -> BVal True
_ -> Not x'
simplValue (PField (Ref x) f) = Field' (simplValue x) f
simplValue v = v
instance Pretty Type where
prettyX x (Pointer t) = prettyX x t <> text "*"
prettyX x SpaceType = text $ spacetype (genMode x)
prettyX x Int = text "int"
prettyX x Bool = text "bool"
prettyX x (Union fields) =
text "union" <+> text "{"
$+$ nest 2 (vcat [prettyX x ty <+> text f <> text ";" | (ty,f) <- fields])
$+$ text "}"
prettyX x (SType (Struct name fields)) =
text name
prettyX x (THook str) =
text str
instance Pretty Value where
prettyX x = prettyX_ x . simplValue
where
prettyX_ :: PrettyFlags -> Value -> Doc
prettyX_ _ (Cond c t e) = pr_ c <+> text "?" <+> pr_ t <+> text ":" <+> pr_ e
prettyX_ _ Base = text "<BASE>"
prettyX_ _ Null = text "NULL"
prettyX_ _ (IVal i) = int $ fromInteger $ toInteger i
prettyX_ _ (BVal True) = text "true"
prettyX_ _ (BVal False) = text "false"
prettyX_ _ (Abs x) = text "abs" <> parens (pr_ x)
prettyX_ fl RootSpace = case (genMode fl) of
ModeFZ -> text "root"
ModeGecode -> text "mgr.root()"
ModeMCP -> text "root"
prettyX_ _ (Minus v1 v2) = pr_ v1 <+> text "-" <+> pr_ v2
prettyX_ _ (Plus v1 v2) = pr_ v1 <+> text "+" <+> pr_ v2
prettyX_ _ (Mult v1 v2) = pr_ v1 <+> text "*" <+> pr_ v2
prettyX_ _ (Div v1 v2) = parens (pr_ v1) <+> text "/" <+> parens (pr_ v2)
prettyX_ _ (Mod v1 v2) = parens (pr_ v1) <+> text "%" <+> parens (pr_ v2)
prettyX_ _ (Ref x) = parens $ text "&" <> parens (pr_ x)
prettyX_ _ (Deref x) = parens $ text "*" <> parens (pr_ x)
prettyX_ _ (Var x) = text x
prettyX_ f (Clone x) = text ("static_cast<" ++ spacetype (genMode f) ++ "*>(") <> pr_ x <> text "->clone(true))"
-- prettyX_ (Clone x) = text ("static_cast<" ++ spacetype ++ "*>(") <> pretty_ x <> text "->clone(false))"
prettyX_ _ (Field r f) = text r <> text "." <> text f
prettyX_ _ (Field' r f) = pr_ r <> text "." <> text f
-- prettyX_ (PField (Field' (Var "estate") "evalState") f) = text f
-- prettyX_ (PField (Field' (Var "nstate") "evalState") f) = text f
-- prettyX_ (PField (Field' (Var _) "evalState") f) = text f
prettyX_ _ (PField r f) = pr_ r <> text "->" <> text f
prettyX_ _ (Lt x y) = parens (pr_ x) <+> text "<" <+> parens (pr_ y)
prettyX_ _ (Gq x y) = parens (pr_ x) <+> text ">=" <+> parens (pr_ y)
prettyX_ _ (Gt x y) = parens (pr_ x) <+> text ">" <+> parens (pr_ y)
prettyX_ _ (Eq x y) = parens (pr_ x) <+> text "==" <+> parens (pr_ y)
prettyX_ _ BaseContinue = text "!st->queue->empty()"
prettyX_ _ (And x y) = parens (pr_ x) <+> text "&&" <+> parens (pr_ y)
prettyX_ _ (Or x y) = parens (pr_ x) <+> text "||" <+> parens (pr_ y)
prettyX_ _ (Not x) = text "!" <> parens (pr_ x)
prettyX_ _ (VHook s) = text s
prettyX_ _ (Max x y) = text "max" <> parens (pr_ x <> text "," <> pr_ y)
prettyX_ e v@(AVarElem _ _ _) = renderVar e v
prettyX_ e v@(AVarSize _ _) = renderVar e v
prettyX_ e v@(BAVarElem _ _ _) = renderVar e v
prettyX_ e v@(BAVarSize _ _) = renderVar e v
prettyX_ e v@(IVar _ _) = renderVar e v
prettyX_ _ (MinDom v) = pr_ v <> text ".min()"
prettyX_ _ (MaxDom v) = pr_ v <> text ".max()"
prettyX_ _ (Degree v) = pr_ v <> text ".degree()"
prettyX_ _ (WDegree v) = pr_ v <> text ".afc()" -- aka accumulated failure count
prettyX_ _ (UbRegret v) = pr_ v <> text ".regret_max()"
prettyX_ _ (LbRegret v) = pr_ v <> text ".regret_min()"
prettyX_ _ (Median v) = pr_ v <> text ".med()"
prettyX_ _ MaxVal = text "Gecode::Int::Limits::max"
prettyX_ _ MinVal = text "Gecode::Int::Limits::min"
prettyX_ _ Random = text "rand()"
prettyX_ _ (New (Struct name _)) = text "new" <+> text name
prettyX_ _ (Assigned var) = pr_ var <> text ".assigned()"
pr :: Value -> Doc
pr = prettyX x
pr_ :: Value -> Doc
pr_ = prettyX_ x
data Constraint = EqC Value Value
| NqC Value Value
| LtC Value Value
| LqC Value Value
| GtC Value Value
| GqC Value Value
| TrueC
| FalseC
deriving (Eq, Ord, Show)
($==) = EqC
($/=) = NqC
($<) = LtC
($<=) = LqC
($>) = GtC
($>=) = GqC
neg (EqC x y) = NqC x y
neg (NqC x y) = EqC x y
neg (LtC x y) = GqC x y
neg (LqC x y) = GtC x y
neg (GtC x y) = LqC x y
neg (GqC x y) = LtC x y
instance Pretty Constraint where
prettyX f (EqC x y) =
prettyX f x <> text "," <> text "IRT_EQ" <> text "," <> prettyX f y
prettyX f (NqC x y) =
prettyX f x <> text "," <> text "IRT_NQ" <> text "," <> prettyX f y
prettyX f (LtC x y) =
prettyX f x <> text "," <> text "IRT_LE" <> text "," <> prettyX f y
prettyX f (LqC x y) =
prettyX f x <> text "," <> text "IRT_LQ" <> text "," <> prettyX f y
prettyX f (GtC x y) =
prettyX f x <> text "," <> text "IRT_GR" <> text "," <> prettyX f y
prettyX f (GqC x y) =
prettyX f x <> text "," <> text "IRT_GQ" <> text "," <> prettyX f y
prettyX f TrueC = error "true constraint can't be posted directly"
prettyX f FalseC = error "false constraint can't be posted directly"
data Statement = IfThenElse Value Statement Statement
| Push Value
| Skip
| Seq Statement Statement
| Assign Value Value
| Abort
| Print Value [String]
| SHook String
| Post Value Constraint
| Fold String Value Value Value (Value -> Value) (Value -> Value -> Value)
| IFold String Value Value Value (Value -> Value) (Value -> Value -> Value)
| BFold String Value Value Value (Value -> Value) (Value -> Value -> Value)
| BIFold String Value Value Value (Value -> Value) (Value -> Value -> Value)
-- | MFold String [(Value, Value->Value)] ([Value] -> [Value] -> Value)
| Delete Value
| Block Statement Statement
| DebugOutput String
| DebugValue String Value
deriving (Eq,Ord,Show)
inliner :: (Statement -> Maybe Statement) -> Statement -> Statement
inliner f s =
case f s of
Just x -> inliner f x
Nothing -> case s of
IfThenElse v s1 s2 -> IfThenElse v (inliner f s1) (inliner f s2)
Seq s1 s2 -> Seq (inliner f s1) (inliner f s2)
Block s1 s2 -> Block s1 (inliner f s2)
_ -> s
instance Ord (Value -> Value) where
compare a b = compare (a (Dummy 0)) (b (Dummy 0))
instance Eq (Value -> Value) where
a == b = (a (Dummy 1)) == (b (Dummy 1))
instance Show (Value -> Value) where
show a = show (a (Dummy 1))
instance Ord (Value -> Value -> Value) where
compare a b = compare (a (Dummy 2) (Dummy 3)) (b (Dummy 2) (Dummy 3))
instance Eq (Value -> Value -> Value) where
a == b = (a (Dummy 4) (Dummy 5)) == (b (Dummy 4) (Dummy 5))
instance Show (Value -> Value -> Value) where
show a = show (a (Dummy 1) (Dummy 2))
comment str = SHook ("// " ++ str)
dec var = Assign var (var - 1)
inc var = Assign var (var + 1)
(>>>) = Seq
(<==) = Assign
assign = flip Assign
ifthen c t = IfThenElse c t Skip
seqs = foldr (>>>) Skip
simplStmt :: Statement -> Statement
simplStmt (IfThenElse c t e)
= let c' = simplValue c
t' = simplStmt t
e' = simplStmt e
in go c' t' e'
where go (BVal True) t e = t
go (BVal False) t e = e
go c t e | t == e = t
go c Skip e = simplStmt $ IfThenElse (Not c) e t
go c1 (IfThenElse c2 t2 e2) e1
| e1 == e2 = simplStmt $ IfThenElse (c1 &&& c2) t2 e1
go c t e = IfThenElse c t e
simplStmt (Assign x y) | x==y = Skip
simplStmt (Seq Skip a) = simplStmt a
simplStmt (Seq a Skip) = simplStmt a
simplStmt s = s
instance Pretty Statement where
prettyX x = prettyX_ . simplStmt
where
prettyX_ (Push tstate) =
text "st->queue->push_back" <> parens (pr tstate) <> text ";"
prettyX_ (IfThenElse c t Skip) = text "if" <+> parens (pr c) <+> text "{" $+$ nest 2 (pr t) $+$ text "}"
prettyX_ (IfThenElse c t e) = text "if" <+> parens (pr c) <+> text "{" $+$ nest 2 (pr t) $+$ text "} else {" $+$ nest 2 (pr_ e) $+$ text "}"
prettyX_ Skip =
empty
prettyX_ (Assign var (Minus val 1))
| var == val
= pr var <> text "--;"
prettyX_ (Assign var (Plus val 1))
| var == val
= pr var <> text "++;"
prettyX_ (Block s1 s2) = pr s1 <+> text "{" $+$ nest 2 (pr s2) $+$ text "}"
prettyX_ (Seq s1 s2) =
pr s1 $+$ pr s2
prettyX_ (Assign x Null) = pr x <> text ";"
prettyX_ (Assign x y) = let y' = simplValue y
in if x == y'
then pr Skip
else pr x <+> text "=" <+> pr y' <> text ";"
prettyX_ Abort =
text "break;"
prettyX_ (Print space vs) =
(vcat $ map (\s -> text "std::cout << \"[\"; for (int i=0; i<" <> pr (AVarSize s space) <> text "; i++) { std::cout << " <> pr (AVarElem s space (Var "i")) <> text " << \" \"; }; std::cout << \"] \";") vs) <> text "std::cout << std::endl;"
prettyX_ (DebugOutput str) =
text "cout << " <> text (show str) <> text " << endl;"
prettyX_ (DebugValue str val) =
text "cout << " <> text (show $ str ++ ": ") <> text " << " <> pr val <> text " << endl;"
prettyX_ (SHook s) =
text s
prettyX_ (Post space FalseC) = pr space <> text "->fail();"
prettyX_ (Post space TrueC) = empty
prettyX_ (Post space c) =
text "rel(*" <> parens (pr space) <> text "," <> pr c <> text ");"
prettyX_ (Fold vars state space m0 metric better) =
let
pos = Field' state "pos"
size = AVarSize vars space
in
text "int best_pos = -1;"
$+$ pr (Assign pos 0)
$+$ text "for (int metric = " <> pr m0 <> text "; " <> pr (pos @< size ) <> text "; " <> pr pos <> text "++) {"
$+$ nest 2 (text "if" <+> parens (text "!" <> pr (AVarElem vars space pos) <> text ".assigned()") <+> text "{"
$+$ nest 2 ( text "int current_metric = " <> pr (metric (AVarElem vars space pos)) <> text ";"
$+$ pr (IfThenElse (Var "current_metric" `better` Var "metric")
(Assign (Var "metric") (Var "current_metric") >>> (Assign (Var "best_pos") pos))
Skip
)
)
$+$ text "}"
)
$+$ text "}"
$+$ pr (Assign pos (Var "best_pos"))
prettyX_ (IFold vars state space m0 metric better) =
let
pos = Field' state "pos"
size = AVarSize vars state
in
text "int best_pos = -1;"
$+$ pr (Assign pos 0)
$+$ text "for (int metric = " <> pr m0 <> text "; " <> pr (pos @< size ) <> text "; " <> pr pos <> text "++) {"
$+$ nest 2 (text "if" <+> parens (text "!" <> pr (AVarElem vars space pos) <> text ".assigned()") <+> text "{"
$+$ nest 2 ( text "int current_metric = " <> pr (metric pos) <> text ";"
$+$ pr (IfThenElse (Var "current_metric" `better` Var "metric")
(Assign (Var "metric") (Var "current_metric") >>> (Assign (Var "best_pos") pos))
Skip
)
)
$+$ text "}"
)
$+$ text "}"
$+$ pr (Assign pos (Var "best_pos"))
prettyX_ (BFold vars state space m0 metric better) =
let
pos = Field' state "pos"
size = BAVarSize vars space
in
text "int best_pos = -1;"
$+$ pr (Assign pos 0)
$+$ text "for (int metric = " <> pr m0 <> text "; " <> pr (pos @< size ) <> text "; " <> pr pos <> text "++) {"
$+$ nest 2 (text "if" <+> parens (text "!" <> pr (BAVarElem vars space pos) <> text ".assigned()") <+> text "{"
$+$ nest 2 ( text "int current_metric = " <> pr (metric (BAVarElem vars space pos)) <> text ";"
$+$ pr (IfThenElse (Var "current_metric" `better` Var "metric")
(Assign (Var "metric") (Var "current_metric") >>> (Assign (Var "best_pos") pos))
Skip
)
)
$+$ text "}"
)
$+$ text "}"
$+$ pr (Assign pos (Var "best_pos"))
prettyX_ (BIFold vars state space m0 metric better) =
let
pos = Field' state "pos"
size = BAVarSize vars space
in
text "int best_pos = -1;"
$+$ pr (Assign pos 0)
$+$ text "for (int metric = " <> pr m0 <> text "; " <> pr (pos @< size ) <> text "; " <> pr pos <> text "++) {"
$+$ nest 2 (text "if" <+> parens (text "!" <> pr (BAVarElem vars space pos) <> text ".assigned()") <+> text "{"
$+$ nest 2 ( text "int current_metric = " <> pr (metric pos) <> text ";"
$+$ pr (IfThenElse (Var "current_metric" `better` Var "metric")
(Assign (Var "metric") (Var "current_metric") >>> (Assign (Var "best_pos") pos))
Skip
)
)
$+$ text "}"
)
$+$ text "}"
$+$ pr (Assign pos (Var "best_pos"))
{- prettyX_ (MFold state metrics better) =
let
space = Field "estate" "space"
pos = Field state "pos"
cvar = CVar "get" space pos
size = VHook $ render $ pr space <> text "->" <> text "get" <> text "().size()"
acc_vars = [Var $ "metric" ++ show i | i <- [1..length metrics]]
cur_vars = [Var $ "current_metric" ++ show i | i <- [1..length metrics]]
init_list = hcat $ punctuate comma [pr v <+> text "=" <+> pretty z | (v,(z,_)) <- zip acc_vars metrics]
computations = vcat $ [text "int" <+> pr (Update var (f cvar))| (var,(_,f)) <- zip cur_vars metrics]
updates = foldl (>>>) Skip [Update v1 v2 | (v1,v2) <- zip acc_vars cur_vars]
in
text "int best_pos = -1;"
$+$ pr (Update pos 0)
$+$ text "for (int " <> init_list <> text "; " <> pr (pos @< size ) <> text "; " <> pr pos <> text "++) {"
$+$ nest 2 (text "if" <+> parens (text "!" <> pr cvar <> text ".assigned()") <+> text "{"
$+$ nest 2 ( computations
$+$ pr (IfThenElse (cur_vars `better` acc_vars)
(updates >>> (Update (Var "best_pos") pos))
Skip
)
)
$+$ text "}"
)
$+$ text "}"
$+$ pr (Update pos (Var "best_pos")) -}
prettyX_ (Delete value) =
text "delete" <+> pr value <> text ";"
pr :: Pretty x => x -> Doc
pr = prettyX x
pr_ :: Statement -> Doc
pr_ = prettyX_
class Simplifiable a where
simplify :: a -> a
instance Simplifiable Statement where
simplify = simplStmt
instance Simplifiable Value where
simplify = simplValue
|
FranklinChen/monadiccp
|
Control/Search/Language.hs
|
bsd-3-clause
| 22,646
| 42
| 24
| 8,656
| 7,734
| 3,873
| 3,861
| 438
| 13
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
--------------------------------------------------------------------------------
-- |
-- Module : Data.Comp.Desugar
-- Copyright : (c) 2011 Patrick Bahr, Tom Hvitved
-- License : BSD3
-- Maintainer : Tom Hvitved <hvitved@diku.dk>
-- Stability : experimental
-- Portability : non-portable (GHC Extensions)
--
-- This modules defines the 'Desugar' type class for desugaring of terms.
--
--------------------------------------------------------------------------------
module Data.Comp.Desugar where
import Data.Comp
-- |The desugaring term homomorphism.
class (Functor f, Functor g) => Desugar f g where
desugHom :: Hom f g
desugHom = desugHom' . fmap Hole
desugHom' :: Alg f (Context g a)
desugHom' x = appCxt (desugHom x)
-- We make the lifting to sums explicit in order to make the Desugar
-- class work with the default instance declaration further below.
instance (Desugar f h, Desugar g h) => Desugar (f :+: g) h where
desugHom = caseF desugHom desugHom
-- |Desugar a term.
desugar :: Desugar f g => Term f -> Term g
{-# INLINE desugar #-}
desugar = appHom desugHom
-- |Lift desugaring to annotated terms.
desugarA :: (Functor f', Functor g', DistAnn f p f', DistAnn g p g',
Desugar f g) => Term f' -> Term g'
desugarA = appHom (propAnn desugHom)
-- |Default desugaring instance.
instance (Functor f, Functor g, f :<: g) => Desugar f g where
desugHom = simpCxt . inj
|
spacekitteh/compdata
|
src/Data/Comp/Desugar.hs
|
bsd-3-clause
| 1,669
| 0
| 9
| 325
| 312
| 171
| 141
| 23
| 1
|
{-# LANGUAGE DeriveGeneric, DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
-- | Handling project configuration, types.
--
module Distribution.Client.ProjectConfig.Types (
-- * Types for project config
ProjectConfig(..),
ProjectConfigBuildOnly(..),
ProjectConfigShared(..),
PackageConfig(..),
-- * Resolving configuration
SolverSettings(..),
BuildTimeSettings(..),
-- * Extra useful Monoids
MapLast(..),
MapMappend(..),
) where
import Distribution.Client.Types
( RemoteRepo )
import Distribution.Client.Dependency.Types
( PreSolver )
import Distribution.Client.Targets
( UserConstraint )
import Distribution.Client.BuildReports.Types
( ReportLevel(..) )
import Distribution.Solver.Types.Settings
import Distribution.Solver.Types.ConstraintSource
import Distribution.Package
( PackageName, PackageId, UnitId, Dependency )
import Distribution.Version
( Version )
import Distribution.System
( Platform )
import Distribution.PackageDescription
( FlagAssignment, SourceRepo(..) )
import Distribution.Simple.Compiler
( Compiler, CompilerFlavor
, OptimisationLevel(..), ProfDetailLevel, DebugInfoLevel(..) )
import Distribution.Simple.Setup
( Flag, AllowNewer(..) )
import Distribution.Simple.InstallDirs
( PathTemplate )
import Distribution.Utils.NubList
( NubList )
import Distribution.Verbosity
( Verbosity )
import Data.Map (Map)
import qualified Data.Map as Map
import Distribution.Compat.Binary (Binary)
import Distribution.Compat.Semigroup
import GHC.Generics (Generic)
-------------------------------
-- Project config types
--
-- | This type corresponds directly to what can be written in the
-- @cabal.project@ file. Other sources of configuration can also be injected
-- into this type, such as the user-wide @~/.cabal/config@ file and the
-- command line of @cabal configure@ or @cabal build@.
--
-- Since it corresponds to the external project file it is an instance of
-- 'Monoid' and all the fields can be empty. This also means there has to
-- be a step where we resolve configuration. At a minimum resolving means
-- applying defaults but it can also mean merging information from multiple
-- sources. For example for package-specific configuration the project file
-- can specify configuration that applies to all local packages, and then
-- additional configuration for a specific package.
--
-- Future directions: multiple profiles, conditionals. If we add these
-- features then the gap between configuration as written in the config file
-- and resolved settings we actually use will become even bigger.
--
data ProjectConfig
= ProjectConfig {
-- | Packages in this project, including local dirs, local .cabal files
-- local and remote tarballs. Where these are file globs, they must
-- match something.
projectPackages :: [String],
-- | Like 'projectConfigPackageGlobs' but /optional/ in the sense that
-- file globs are allowed to match nothing. The primary use case for
-- this is to be able to say @optional-packages: */@ to automagically
-- pick up deps that we unpack locally.
projectPackagesOptional :: [String],
-- | Packages in this project from remote source repositories.
projectPackagesRepo :: [SourceRepo],
-- | Packages in this project from hackage repositories.
projectPackagesNamed :: [Dependency],
projectConfigBuildOnly :: ProjectConfigBuildOnly,
projectConfigShared :: ProjectConfigShared,
projectConfigLocalPackages :: PackageConfig,
projectConfigSpecificPackage :: MapMappend PackageName PackageConfig
}
deriving (Eq, Show, Generic)
-- | That part of the project configuration that only affects /how/ we build
-- and not the /value/ of the things we build. This means this information
-- does not need to be tracked for changes since it does not affect the
-- outcome.
--
data ProjectConfigBuildOnly
= ProjectConfigBuildOnly {
projectConfigVerbosity :: Flag Verbosity,
projectConfigDryRun :: Flag Bool,
projectConfigOnlyDeps :: Flag Bool,
projectConfigSummaryFile :: NubList PathTemplate,
projectConfigLogFile :: Flag PathTemplate,
projectConfigBuildReports :: Flag ReportLevel,
projectConfigReportPlanningFailure :: Flag Bool,
projectConfigSymlinkBinDir :: Flag FilePath,
projectConfigOneShot :: Flag Bool,
projectConfigNumJobs :: Flag (Maybe Int),
projectConfigKeepGoing :: Flag Bool,
projectConfigOfflineMode :: Flag Bool,
projectConfigKeepTempFiles :: Flag Bool,
projectConfigHttpTransport :: Flag String,
projectConfigIgnoreExpiry :: Flag Bool,
projectConfigCacheDir :: Flag FilePath,
projectConfigLogsDir :: Flag FilePath,
projectConfigWorldFile :: Flag FilePath
}
deriving (Eq, Show, Generic)
-- | Project configuration that is shared between all packages in the project.
-- In particular this includes configuration that affects the solver.
--
data ProjectConfigShared
= ProjectConfigShared {
projectConfigHcFlavor :: Flag CompilerFlavor,
projectConfigHcPath :: Flag FilePath,
projectConfigHcPkg :: Flag FilePath,
projectConfigHaddockIndex :: Flag PathTemplate,
-- Things that only make sense for manual mode, not --local mode
-- too much control!
--projectConfigUserInstall :: Flag Bool,
--projectConfigInstallDirs :: InstallDirs (Flag PathTemplate),
--TODO: [required eventually] decide what to do with InstallDirs
-- currently we don't allow it to be specified in the config file
--projectConfigPackageDBs :: [Maybe PackageDB],
-- configuration used both by the solver and other phases
projectConfigRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers.
projectConfigLocalRepos :: NubList FilePath,
-- solver configuration
projectConfigConstraints :: [(UserConstraint, ConstraintSource)],
projectConfigPreferences :: [Dependency],
projectConfigCabalVersion :: Flag Version, --TODO: [required eventually] unused
projectConfigSolver :: Flag PreSolver,
projectConfigAllowNewer :: Maybe AllowNewer,
projectConfigMaxBackjumps :: Flag Int,
projectConfigReorderGoals :: Flag ReorderGoals,
projectConfigCountConflicts :: Flag CountConflicts,
projectConfigStrongFlags :: Flag StrongFlags
-- More things that only make sense for manual mode, not --local mode
-- too much control!
--projectConfigIndependentGoals :: Flag Bool,
--projectConfigShadowPkgs :: Flag Bool,
--projectConfigReinstall :: Flag Bool,
--projectConfigAvoidReinstalls :: Flag Bool,
--projectConfigOverrideReinstall :: Flag Bool,
--projectConfigUpgradeDeps :: Flag Bool
}
deriving (Eq, Show, Generic)
-- | Project configuration that is specific to each package, that is where we
-- can in principle have different values for different packages in the same
-- project.
--
data PackageConfig
= PackageConfig {
packageConfigProgramPaths :: MapLast String FilePath,
packageConfigProgramArgs :: MapMappend String [String],
packageConfigProgramPathExtra :: NubList FilePath,
packageConfigFlagAssignment :: FlagAssignment,
packageConfigVanillaLib :: Flag Bool,
packageConfigSharedLib :: Flag Bool,
packageConfigDynExe :: Flag Bool,
packageConfigProf :: Flag Bool, --TODO: [code cleanup] sort out
packageConfigProfLib :: Flag Bool, -- this duplication
packageConfigProfExe :: Flag Bool, -- and consistency
packageConfigProfDetail :: Flag ProfDetailLevel,
packageConfigProfLibDetail :: Flag ProfDetailLevel,
packageConfigConfigureArgs :: [String],
packageConfigOptimization :: Flag OptimisationLevel,
packageConfigProgPrefix :: Flag PathTemplate,
packageConfigProgSuffix :: Flag PathTemplate,
packageConfigExtraLibDirs :: [FilePath],
packageConfigExtraFrameworkDirs :: [FilePath],
packageConfigExtraIncludeDirs :: [FilePath],
packageConfigGHCiLib :: Flag Bool,
packageConfigSplitObjs :: Flag Bool,
packageConfigStripExes :: Flag Bool,
packageConfigStripLibs :: Flag Bool,
packageConfigTests :: Flag Bool,
packageConfigBenchmarks :: Flag Bool,
packageConfigCoverage :: Flag Bool,
packageConfigRelocatable :: Flag Bool,
packageConfigDebugInfo :: Flag DebugInfoLevel,
packageConfigRunTests :: Flag Bool, --TODO: [required eventually] use this
packageConfigDocumentation :: Flag Bool, --TODO: [required eventually] use this
packageConfigHaddockHoogle :: Flag Bool, --TODO: [required eventually] use this
packageConfigHaddockHtml :: Flag Bool, --TODO: [required eventually] use this
packageConfigHaddockHtmlLocation :: Flag String, --TODO: [required eventually] use this
packageConfigHaddockExecutables :: Flag Bool, --TODO: [required eventually] use this
packageConfigHaddockTestSuites :: Flag Bool, --TODO: [required eventually] use this
packageConfigHaddockBenchmarks :: Flag Bool, --TODO: [required eventually] use this
packageConfigHaddockInternal :: Flag Bool, --TODO: [required eventually] use this
packageConfigHaddockCss :: Flag FilePath, --TODO: [required eventually] use this
packageConfigHaddockHscolour :: Flag Bool, --TODO: [required eventually] use this
packageConfigHaddockHscolourCss :: Flag FilePath, --TODO: [required eventually] use this
packageConfigHaddockContents :: Flag PathTemplate --TODO: [required eventually] use this
}
deriving (Eq, Show, Generic)
instance Binary ProjectConfig
instance Binary ProjectConfigBuildOnly
instance Binary ProjectConfigShared
instance Binary PackageConfig
-- | Newtype wrapper for 'Map' that provides a 'Monoid' instance that takes
-- the last value rather than the first value for overlapping keys.
newtype MapLast k v = MapLast { getMapLast :: Map k v }
deriving (Eq, Show, Functor, Generic, Binary)
instance Ord k => Monoid (MapLast k v) where
mempty = MapLast Map.empty
mappend = (<>)
instance Ord k => Semigroup (MapLast k v) where
MapLast a <> MapLast b = MapLast (flip Map.union a b)
-- rather than Map.union which is the normal Map monoid instance
-- | Newtype wrapper for 'Map' that provides a 'Monoid' instance that
-- 'mappend's values of overlapping keys rather than taking the first.
newtype MapMappend k v = MapMappend { getMapMappend :: Map k v }
deriving (Eq, Show, Functor, Generic, Binary)
instance (Semigroup v, Ord k) => Monoid (MapMappend k v) where
mempty = MapMappend Map.empty
mappend = (<>)
instance (Semigroup v, Ord k) => Semigroup (MapMappend k v) where
MapMappend a <> MapMappend b = MapMappend (Map.unionWith (<>) a b)
-- rather than Map.union which is the normal Map monoid instance
instance Monoid ProjectConfig where
mempty = gmempty
mappend = (<>)
instance Semigroup ProjectConfig where
(<>) = gmappend
instance Monoid ProjectConfigBuildOnly where
mempty = gmempty
mappend = (<>)
instance Semigroup ProjectConfigBuildOnly where
(<>) = gmappend
instance Monoid ProjectConfigShared where
mempty = gmempty
mappend = (<>)
instance Semigroup ProjectConfigShared where
(<>) = gmappend
instance Monoid PackageConfig where
mempty = gmempty
mappend = (<>)
instance Semigroup PackageConfig where
(<>) = gmappend
----------------------------------------
-- Resolving configuration to settings
--
-- | Resolved configuration for the solver. The idea is that this is easier to
-- use than the raw configuration because in the raw configuration everything
-- is optional (monoidial). In the 'BuildTimeSettings' every field is filled
-- in, if only with the defaults.
--
-- Use 'resolveSolverSettings' to make one from the project config (by
-- applying defaults etc).
--
data SolverSettings
= SolverSettings {
solverSettingRemoteRepos :: [RemoteRepo], -- ^ Available Hackage servers.
solverSettingLocalRepos :: [FilePath],
solverSettingConstraints :: [(UserConstraint, ConstraintSource)],
solverSettingPreferences :: [Dependency],
solverSettingFlagAssignment :: FlagAssignment, -- ^ For all local packages
solverSettingFlagAssignments :: Map PackageName FlagAssignment,
solverSettingCabalVersion :: Maybe Version, --TODO: [required eventually] unused
solverSettingSolver :: PreSolver,
solverSettingAllowNewer :: AllowNewer,
solverSettingMaxBackjumps :: Maybe Int,
solverSettingReorderGoals :: ReorderGoals,
solverSettingCountConflicts :: CountConflicts,
solverSettingStrongFlags :: StrongFlags
-- Things that only make sense for manual mode, not --local mode
-- too much control!
--solverSettingIndependentGoals :: Bool,
--solverSettingShadowPkgs :: Bool,
--solverSettingReinstall :: Bool,
--solverSettingAvoidReinstalls :: Bool,
--solverSettingOverrideReinstall :: Bool,
--solverSettingUpgradeDeps :: Bool
}
deriving (Eq, Show, Generic)
instance Binary SolverSettings
-- | Resolved configuration for things that affect how we build and not the
-- value of the things we build. The idea is that this is easier to use than
-- the raw configuration because in the raw configuration everything is
-- optional (monoidial). In the 'BuildTimeSettings' every field is filled in,
-- if only with the defaults.
--
-- Use 'resolveBuildTimeSettings' to make one from the project config (by
-- applying defaults etc).
--
data BuildTimeSettings
= BuildTimeSettings {
buildSettingDryRun :: Bool,
buildSettingOnlyDeps :: Bool,
buildSettingSummaryFile :: [PathTemplate],
buildSettingLogFile :: Maybe (Compiler -> Platform
-> PackageId -> UnitId
-> FilePath),
buildSettingLogVerbosity :: Verbosity,
buildSettingBuildReports :: ReportLevel,
buildSettingReportPlanningFailure :: Bool,
buildSettingSymlinkBinDir :: [FilePath],
buildSettingOneShot :: Bool,
buildSettingNumJobs :: Int,
buildSettingKeepGoing :: Bool,
buildSettingOfflineMode :: Bool,
buildSettingKeepTempFiles :: Bool,
buildSettingRemoteRepos :: [RemoteRepo],
buildSettingLocalRepos :: [FilePath],
buildSettingCacheDir :: FilePath,
buildSettingHttpTransport :: Maybe String,
buildSettingIgnoreExpiry :: Bool
}
|
kolmodin/cabal
|
cabal-install/Distribution/Client/ProjectConfig/Types.hs
|
bsd-3-clause
| 15,769
| 0
| 14
| 4,063
| 2,029
| 1,238
| 791
| 215
| 0
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.NormalMap
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
module Yi.Keymap.Vim.NormalMap (defNormalMap) where
import Prelude hiding (lookup)
import Control.Applicative ((<$>))
import Control.Lens (assign, use, (.=))
import Control.Monad (replicateM_, unless, void, when)
import Data.Char (ord)
import Data.HashMap.Strict (lookup, singleton)
import Data.List (group)
import Data.Maybe (fromMaybe)
import Data.Monoid (Monoid (mempty), (<>))
import qualified Data.Text as T (drop, empty, pack, replicate, unpack)
import System.Directory (doesFileExist)
import System.FriendlyPath (expandTilda)
import Yi.Buffer.Adjusted hiding (Insert)
import Yi.Core (closeWindow, quitEditor)
import Yi.Editor
import Yi.Event (Event (Event), Key (KASCII, KEnter, KEsc, KTab), Modifier (MCtrl))
import Yi.File (fwriteE, openNewFile)
import Yi.History (historyPrefixSet, historyStart)
import Yi.Keymap (YiM)
import Yi.Keymap.Keys (char, ctrlCh, spec)
import Yi.Keymap.Vim.Common
import Yi.Keymap.Vim.Eval (scheduleActionStringForEval)
import Yi.Keymap.Vim.Motion (CountedMove (CountedMove), regionOfMoveB, stringToMove)
import Yi.Keymap.Vim.Operator (VimOperator (..), opChange, opDelete, opYank)
import Yi.Keymap.Vim.Search (doVimSearch)
import Yi.Keymap.Vim.StateUtils
import Yi.Keymap.Vim.StyledRegion (StyledRegion (StyledRegion), transformCharactersInLineN)
import Yi.Keymap.Vim.Tag (gotoTag, popTag)
import Yi.Keymap.Vim.Utils
import Yi.MiniBuffer (spawnMinibufferE)
import Yi.Misc (printFileInfoE)
import Yi.Monad (maybeM, whenM)
import Yi.Regex (makeSearchOptsM, seInput)
import qualified Yi.Rope as R (fromText, null, toString, toText)
import Yi.Search (getRegexE, isearchInitE, makeSimpleSearch, setRegexE)
import Yi.String (showT)
import Yi.Tag (Tag (..))
import Yi.Utils (io)
data EOLStickiness = Sticky | NonSticky deriving Eq
mkDigitBinding :: Char -> VimBinding
mkDigitBinding c = mkBindingE Normal Continue (char c, return (), mutate)
where
mutate vs@(VimState {vsCount = Nothing}) = vs { vsCount = Just d }
mutate vs@(VimState {vsCount = Just count}) =
vs { vsCount = Just $ count * 10 + d }
d = ord c - ord '0'
defNormalMap :: [VimOperator] -> [VimBinding]
defNormalMap operators =
[recordMacroBinding, finishRecordingMacroBinding, playMacroBinding] <>
[zeroBinding, repeatBinding, motionBinding, searchBinding] <>
[chooseRegisterBinding, setMarkBinding] <>
fmap mkDigitBinding ['1' .. '9'] <>
operatorBindings operators <>
finishingBingings <>
continuingBindings <>
nonrepeatableBindings <>
jumpBindings <>
fileEditBindings <>
[tabTraversalBinding] <>
[tagJumpBinding, tagPopBinding]
tagJumpBinding :: VimBinding
tagJumpBinding = mkBindingY Normal (Event (KASCII ']') [MCtrl], f, id)
where f = withCurrentBuffer readCurrentWordB >>= g . Tag . R.toText
g tag = gotoTag tag 0 Nothing
tagPopBinding :: VimBinding
tagPopBinding = mkBindingY Normal (Event (KASCII 't') [MCtrl], f, id)
where f = popTag
motionBinding :: VimBinding
motionBinding = mkMotionBinding Drop $
\m -> case m of
Normal -> True
_ -> False
chooseRegisterBinding :: VimBinding
chooseRegisterBinding = mkChooseRegisterBinding ((== Normal) . vsMode)
zeroBinding :: VimBinding
zeroBinding = VimBindingE f
where f "0" (VimState {vsMode = Normal}) = WholeMatch $ do
currentState <- getEditorDyn
case vsCount currentState of
Just c -> do
setCountE (10 * c)
return Continue
Nothing -> do
withCurrentBuffer moveToSol
resetCountE
setStickyEolE False
return Drop
f _ _ = NoMatch
repeatBinding :: VimBinding
repeatBinding = VimBindingE (f . T.unpack . _unEv)
where
f "." (VimState {vsMode = Normal}) = WholeMatch $ do
currentState <- getEditorDyn
case vsRepeatableAction currentState of
Nothing -> return ()
Just (RepeatableAction prevCount (Ev actionString)) -> do
let count = showT $ fromMaybe prevCount (vsCount currentState)
scheduleActionStringForEval . Ev $ count <> actionString
resetCountE
return Drop
f _ _ = NoMatch
jumpBindings :: [VimBinding]
jumpBindings = fmap (mkBindingE Normal Drop)
[ (ctrlCh 'o', jumpBackE, id)
, (spec KTab, jumpForwardE, id)
, (ctrlCh '^', controlCarrot, resetCount)
, (ctrlCh '6', controlCarrot, resetCount)
]
where
controlCarrot = alternateBufferE . (+ (-1)) =<< getCountE
finishingBingings :: [VimBinding]
finishingBingings = fmap (mkStringBindingE Normal Finish)
[ ("x", cutCharE Forward NonSticky =<< getCountE, resetCount)
, ("<Del>", cutCharE Forward NonSticky =<< getCountE, resetCount)
, ("X", cutCharE Backward NonSticky =<< getCountE, resetCount)
, ("D",
do region <- withCurrentBuffer $ regionWithTwoMovesB (return ()) moveToEol
void $ operatorApplyToRegionE opDelete 1 $ StyledRegion Exclusive region
, id)
-- Pasting
, ("p", pasteAfter, id)
, ("P", pasteBefore, id)
-- Miscellaneous.
, ("~", do
count <- getCountE
withCurrentBuffer $ do
transformCharactersInLineN count switchCaseChar
leftOnEol
, resetCount)
, ("J", do
count <- fmap (flip (-) 1 . max 2) getCountE
withCurrentBuffer $ do
(StyledRegion s r) <- case stringToMove "j" of
WholeMatch m -> regionOfMoveB $ CountedMove (Just count) m
_ -> error "can't happen"
void $ lineMoveRel $ count - 1
moveToEol
joinLinesB =<< convertRegionToStyleB r s
, resetCount)
]
pasteBefore :: EditorM ()
pasteBefore = do
-- TODO: use count
register <- getRegisterE . vsActiveRegister =<< getEditorDyn
case register of
Nothing -> return ()
Just (Register LineWise rope) -> withCurrentBuffer $ unless (R.null rope) $
-- Beware of edge cases ahead
insertRopeWithStyleB (addNewLineIfNecessary rope) LineWise
Just (Register style rope) -> withCurrentBuffer $ pasteInclusiveB rope style
pasteAfter :: EditorM ()
pasteAfter = do
-- TODO: use count
register <- getRegisterE . vsActiveRegister =<< getEditorDyn
case register of
Nothing -> return ()
Just (Register LineWise rope) -> withCurrentBuffer $ do
-- Beware of edge cases ahead
moveToEol
eof <- atEof
when eof $ insertB '\n'
rightB
insertRopeWithStyleB (addNewLineIfNecessary rope) LineWise
when eof $ savingPointB $ do
newSize <- sizeB
moveTo (newSize - 1)
curChar <- readB
when (curChar == '\n') $ deleteN 1
Just (Register style rope) -> withCurrentBuffer $ do
whenM (fmap not atEol) rightB
pasteInclusiveB rope style
operatorBindings :: [VimOperator] -> [VimBinding]
operatorBindings = fmap mkOperatorBinding
where
mkT (Op o) = (Ev o, return (), switchMode . NormalOperatorPending $ Op o)
mkOperatorBinding (VimOperator {operatorName = opName}) =
mkStringBindingE Normal Continue $ mkT opName
continuingBindings :: [VimBinding]
continuingBindings = fmap (mkStringBindingE Normal Continue)
[ ("r", return (), switchMode ReplaceSingleChar) -- TODO make it just a binding
-- Transition to insert mode
, ("i", return (), switchMode $ Insert 'i')
, ("<Ins>", return (), switchMode $ Insert 'i')
, ("I", withCurrentBuffer firstNonSpaceB, switchMode $ Insert 'I')
, ("a", withCurrentBuffer $ moveXorEol 1, switchMode $ Insert 'a')
, ("A", withCurrentBuffer moveToEol, switchMode $ Insert 'A')
, ("o", withCurrentBuffer $ do
moveToEol
newlineB
indentAsTheMostIndentedNeighborLineB
, switchMode $ Insert 'o')
, ("O", withCurrentBuffer $ do
moveToSol
newlineB
leftB
indentAsNextB
, switchMode $ Insert 'O')
-- Transition to visual
, ("v", enableVisualE Inclusive, resetCount . switchMode (Visual Inclusive))
, ("V", enableVisualE LineWise, resetCount . switchMode (Visual LineWise))
, ("<C-v>", enableVisualE Block, resetCount . switchMode (Visual Block))
]
nonrepeatableBindings :: [VimBinding]
nonrepeatableBindings = fmap (mkBindingE Normal Drop)
[ (spec KEsc, return (), resetCount)
, (ctrlCh 'c', return (), resetCount)
-- Changing
, (char 'C',
do region <- withCurrentBuffer $ regionWithTwoMovesB (return ()) moveToEol
void $ operatorApplyToRegionE opChange 1 $ StyledRegion Exclusive region
, switchMode $ Insert 'C')
, (char 's', cutCharE Forward Sticky =<< getCountE, switchMode $ Insert 's')
, (char 'S',
do region <- withCurrentBuffer $ regionWithTwoMovesB firstNonSpaceB moveToEol
void $ operatorApplyToRegionE opDelete 1 $ StyledRegion Exclusive region
, switchMode $ Insert 'S')
-- Replacing
, (char 'R', return (), switchMode Replace)
-- Yanking
, ( char 'Y'
, do region <- withCurrentBuffer $ regionWithTwoMovesB (return ()) moveToEol
void $ operatorApplyToRegionE opYank 1 $ StyledRegion Exclusive region
, id
)
-- Search
, (char '*', addVimJumpHereE >> searchWordE True Forward, resetCount)
, (char '#', addVimJumpHereE >> searchWordE True Backward, resetCount)
, (char 'n', addVimJumpHereE >> withCount (continueSearching id), resetCount)
, (char 'N', addVimJumpHereE >> withCount (continueSearching reverseDir), resetCount)
, (char ';', repeatGotoCharE id, id)
, (char ',', repeatGotoCharE reverseDir, id)
-- Repeat
, (char '&', return (), id) -- TODO
-- Transition to ex
, (char ':', do
void (spawnMinibufferE ":" id)
historyStart
historyPrefixSet ""
, switchMode Ex)
-- Undo
, (char 'u', withCountOnBuffer undoB >> withCurrentBuffer leftOnEol, id)
, (char 'U', withCountOnBuffer undoB >> withCurrentBuffer leftOnEol, id) -- TODO
, (ctrlCh 'r', withCountOnBuffer redoB >> withCurrentBuffer leftOnEol, id)
-- scrolling
,(ctrlCh 'b', getCountE >>= withCurrentBuffer . upScreensB, id)
,(ctrlCh 'f', getCountE >>= withCurrentBuffer . downScreensB, id)
,(ctrlCh 'u', getCountE >>= withCurrentBuffer . vimScrollByB (negate . (`div` 2)), id)
,(ctrlCh 'd', getCountE >>= withCurrentBuffer . vimScrollByB (`div` 2), id)
,(ctrlCh 'y', getCountE >>= withCurrentBuffer . vimScrollB . negate, id)
,(ctrlCh 'e', getCountE >>= withCurrentBuffer . vimScrollB, id)
-- unsorted TODO
, (char '-', return (), id)
, (char '+', return (), id)
, (spec KEnter, return (), id)
] <> fmap (mkStringBindingE Normal Drop)
[ ("g*", searchWordE False Forward, resetCount)
, ("g#", searchWordE False Backward, resetCount)
, ("gd", withCurrentBuffer $ withModeB modeGotoDeclaration, resetCount)
, ("gD", withCurrentBuffer $ withModeB modeGotoDeclaration, resetCount)
, ("<C-g>", printFileInfoE, resetCount)
, ("<C-w>c", tryCloseE, resetCount)
, ("<C-w>o", closeOtherE, resetCount)
, ("<C-w>s", splitE, resetCount)
, ("<C-w>w", nextWinE, resetCount)
, ("<C-w><Down>", nextWinE, resetCount) -- TODO: please implement downWinE
, ("<C-w><Right>", nextWinE, resetCount) -- TODO: please implement rightWinE
, ("<C-w><C-w>", nextWinE, resetCount)
, ("<C-w>W", prevWinE, resetCount)
, ("<C-w>p", prevWinE, resetCount)
, ("<C-w><Up>", prevWinE, resetCount) -- TODO: please implement upWinE
, ("<C-w><Left>", prevWinE, resetCount) -- TODO: please implement leftWinE
, ("<C-w>l", layoutManagersNextE, resetCount)
, ("<C-w>L", layoutManagersPreviousE, resetCount)
--, ("<C-w> ", layoutManagersNextE, resetCount)
, ("<C-w>v", layoutManagerNextVariantE, resetCount)
, ("<C-w>V", layoutManagerPreviousVariantE, resetCount)
, ("<C-a>", getCountE >>= withCurrentBuffer . incrementNextNumberByB, resetCount)
, ("<C-x>", getCountE >>= withCurrentBuffer . incrementNextNumberByB . negate, resetCount)
-- z commands
-- TODO Add prefix count
, ("zt", withCurrentBuffer scrollCursorToTopB, resetCount)
, ("zb", withCurrentBuffer scrollCursorToBottomB, resetCount)
, ("zz", withCurrentBuffer scrollToCursorB, resetCount)
{- -- TODO Horizantal scrolling
, ("ze", withCurrentBuffer .., resetCount)
, ("zs", withCurrentBuffer .., resetCount)
, ("zH", withCurrentBuffer .., resetCount)
, ("zL", withCurrentBuffer .., resetCount)
, ("zh", withCurrentBuffer .., resetCount)
, ("zl", withCurrentBuffer .., resetCount)
-}
, ("z.", withCurrentBuffer $ scrollToCursorB >> moveToSol, resetCount)
, ("z+", withCurrentBuffer scrollToLineBelowWindowB, resetCount)
, ("z-", withCurrentBuffer $ scrollCursorToBottomB >> moveToSol, resetCount)
, ("z^", withCurrentBuffer scrollToLineAboveWindowB, resetCount)
{- -- TODO Code folding
, ("zf", .., resetCount)
, ("zc", .., resetCount)
, ("zo", .., resetCount)
, ("za", .., resetCount)
, ("zC", .., resetCount)
, ("zO", .., resetCount)
, ("zA", .., resetCount)
, ("zr", .., resetCount)
, ("zR", .., resetCount)
, ("zm", .., resetCount)
, ("zM", .., resetCount)
-}
-- Z commands
] <> fmap (mkStringBindingY Normal)
[ ("ZQ", quitEditor, id)
-- TODO ZZ should replicate :x not :wq
, ("ZZ", fwriteE >> closeWindow, id)
]
fileEditBindings :: [VimBinding]
fileEditBindings = fmap (mkStringBindingY Normal)
[ ("gf", openFileUnderCursor Nothing, resetCount)
, ("<C-w>gf", openFileUnderCursor $ Just newTabE, resetCount)
, ("<C-w>f", openFileUnderCursor $ Just (splitE >> prevWinE), resetCount)
]
setMarkBinding :: VimBinding
setMarkBinding = VimBindingE (f . T.unpack . _unEv)
where f _ s | vsMode s /= Normal = NoMatch
f "m" _ = PartialMatch
f ('m':c:[]) _ = WholeMatch $ do
withCurrentBuffer $ setNamedMarkHereB [c]
return Drop
f _ _ = NoMatch
searchWordE :: Bool -> Direction -> EditorM ()
searchWordE wholeWord dir = do
word <- withCurrentBuffer readCurrentWordB
let search re = do
setRegexE re
assign searchDirectionA dir
withCount $ continueSearching (const dir)
if wholeWord
then case makeSearchOptsM [] $ "\\<" <> R.toString word <> "\\>" of
Right re -> search re
Left _ -> return ()
else search $ makeSimpleSearch word
searchBinding :: VimBinding
searchBinding = VimBindingE (f . T.unpack . _unEv)
where f evs (VimState { vsMode = Normal }) | evs `elem` group ['/', '?']
= WholeMatch $ do
state <- fmap vsMode getEditorDyn
let dir = if evs == "/" then Forward else Backward
switchModeE $ Search state dir
isearchInitE dir
historyStart
historyPrefixSet T.empty
return Continue
f _ _ = NoMatch
continueSearching :: (Direction -> Direction) -> EditorM ()
continueSearching fdir =
getRegexE >>= \case
Just regex -> do
dir <- fdir <$> use searchDirectionA
printMsg . T.pack $ (if dir == Forward then '/' else '?') : seInput regex
void $ doVimSearch Nothing [] dir
Nothing -> printMsg "No previous search pattern"
repeatGotoCharE :: (Direction -> Direction) -> EditorM ()
repeatGotoCharE mutateDir = do
prevCommand <- fmap vsLastGotoCharCommand getEditorDyn
count <- getCountE
withCurrentBuffer $ case prevCommand of
Just (GotoCharCommand c dir style) -> do
let newDir = mutateDir dir
let move = gotoCharacterB c newDir style True
p0 <- pointB
replicateM_ (count - 1) $ do
move
when (style == Exclusive) $ moveB Character newDir
p1 <- pointB
move
p2 <- pointB
when (p1 == p2) $ moveTo p0
Nothing -> return ()
enableVisualE :: RegionStyle -> EditorM ()
enableVisualE style = withCurrentBuffer $ do
putRegionStyle style
rectangleSelectionA .= (Block == style)
setVisibleSelection True
pointB >>= setSelectionMarkPointB
cutCharE :: Direction -> EOLStickiness -> Int -> EditorM ()
cutCharE dir stickiness count = do
r <- withCurrentBuffer $ do
p0 <- pointB
(if dir == Forward then moveXorEol else moveXorSol) count
p1 <- pointB
let region = mkRegion p0 p1
rope <- readRegionB region
deleteRegionB $ mkRegion p0 p1
when (stickiness == NonSticky) leftOnEol
return rope
regName <- fmap vsActiveRegister getEditorDyn
setRegisterE regName Inclusive r
tabTraversalBinding :: VimBinding
tabTraversalBinding = VimBindingE (f . T.unpack . _unEv)
where f "g" (VimState { vsMode = Normal }) = PartialMatch
f ('g':c:[]) (VimState { vsMode = Normal }) | c `elem` ['t', 'T'] = WholeMatch $ do
count <- getCountE
replicateM_ count $ if c == 'T' then previousTabE else nextTabE
resetCountE
return Drop
f _ _ = NoMatch
openFileUnderCursor :: Maybe (EditorM ()) -> YiM ()
openFileUnderCursor editorAction = do
fileName <- fmap R.toString . withCurrentBuffer $ readUnitB unitViWORD
fileExists <- io $ doesFileExist =<< expandTilda fileName
if fileExists then do
maybeM withEditor editorAction
openNewFile $ fileName
else
withEditor . fail $ "Can't find file \"" <> fileName <> "\""
recordMacroBinding :: VimBinding
recordMacroBinding = VimBindingE (f . T.unpack . _unEv)
where f "q" (VimState { vsMode = Normal
, vsCurrentMacroRecording = Nothing })
= PartialMatch
f ['q', c] (VimState { vsMode = Normal })
= WholeMatch $ do
modifyStateE $ \s ->
s { vsCurrentMacroRecording = Just (c, mempty) }
return Finish
f _ _ = NoMatch
finishRecordingMacroBinding :: VimBinding
finishRecordingMacroBinding = VimBindingE (f . T.unpack . _unEv)
where f "q" (VimState { vsMode = Normal
, vsCurrentMacroRecording = Just (macroName, Ev macroBody) })
= WholeMatch $ do
let reg = Register Exclusive (R.fromText (T.drop 2 macroBody))
modifyStateE $ \s ->
s { vsCurrentMacroRecording = Nothing
, vsRegisterMap = singleton macroName reg
<> vsRegisterMap s
}
return Finish
f _ _ = NoMatch
playMacroBinding :: VimBinding
playMacroBinding = VimBindingE (f . T.unpack . _unEv)
where f "@" (VimState { vsMode = Normal }) = PartialMatch
f ['@', c] (VimState { vsMode = Normal
, vsRegisterMap = registers
, vsCount = mbCount }) = WholeMatch $ do
resetCountE
case lookup c registers of
Just (Register _ evs) -> do
let count = fromMaybe 1 mbCount
mkAct = Ev . T.replicate count . R.toText
scheduleActionStringForEval . mkAct $ evs
return Finish
Nothing -> return Drop
f _ _ = NoMatch
-- TODO: withCount name implies that parameter has type (Int -> EditorM ())
-- Is there a better name for this function?
withCount :: EditorM () -> EditorM ()
withCount action = flip replicateM_ action =<< getCountE
withCountOnBuffer :: BufferM () -> EditorM ()
withCountOnBuffer action = withCount $ withCurrentBuffer action
|
TOSPIO/yi
|
src/library/Yi/Keymap/Vim/NormalMap.hs
|
gpl-2.0
| 21,171
| 0
| 21
| 6,233
| 5,688
| 3,026
| 2,662
| 406
| 4
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.Ex.Commands.Substitute
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
module Yi.Keymap.Vim.Ex.Commands.Substitute (parse) where
import Control.Applicative (Alternative)
import Control.Monad (void)
import qualified Data.Attoparsec.Text as P (char, inClass, many', match,
satisfy, string, option,
(<?>), Parser)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import qualified Data.Text as T (Text, cons, snoc)
import Lens.Micro.Platform (over, _2)
import Yi.Buffer
import Yi.Keymap (Action (EditorA))
import Yi.Keymap.Vim.Common (EventString, Substitution(..))
import qualified Yi.Keymap.Vim.Ex.Commands.Common as Common (parse, pureExCommand, parseRange)
import Yi.Keymap.Vim.Ex.Types (ExCommand (cmdAction, cmdShow))
import qualified Yi.Rope as R (fromString, toText)
import Yi.Keymap.Vim.Substitution
-- | Skip one or no occurrences of a given parser.
skipOptional :: Alternative f => f a -> f ()
skipOptional p = P.option () (() <$ p)
{-# SPECIALIZE skipOptional :: P.Parser a -> P.Parser () #-}
parse :: EventString -> Maybe ExCommand
parse = Common.parse $ do
(rangeText, rangeB) <- over _2 (fromMaybe $ regionOfB Line) <$> P.match Common.parseRange
P.char 's' *>
skipOptional (P.string "ub" *> skipOptional (P.string "stitute"))
P.<?> "substitute"
delimiter <- P.satisfy (`elem` ("!@#$%^&*()[]{}<>/.,~';:?-=" :: String))
from <- R.fromString <$> P.many' (P.satisfy (/= delimiter))
void $ P.char delimiter
to <- R.fromString <$> P.many' (P.satisfy (/= delimiter))
flagChars <- P.option "" $
P.char delimiter *> P.many' (P.satisfy $ P.inClass "gic")
return $! substitute
(Substitution
from
to
('g' `elem` flagChars)
('i' `elem` flagChars)
('c' `elem` flagChars))
delimiter
rangeText
rangeB
substitute :: Substitution -> Char -> T.Text -> BufferM Region -> ExCommand
substitute s@(Substitution from to global caseInsensitive confirm) delimiter regionText regionB = Common.pureExCommand
{ cmdShow = regionText
<> "s"
<> (delimiter `T.cons` R.toText from)
<> (delimiter `T.cons` R.toText to)
`T.snoc` delimiter
<> (if confirm then "c" else "")
<> (if caseInsensitive then "i" else "")
<> (if global then "g" else "")
, cmdAction = EditorA $ substituteE s regionB
}
|
noughtmare/yi
|
yi-keymap-vim/src/Yi/Keymap/Vim/Ex/Commands/Substitute.hs
|
gpl-2.0
| 3,094
| 0
| 16
| 1,030
| 776
| 445
| 331
| 56
| 4
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hi-IN">
<title>Revisit | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
0xkasun/security-tools
|
src/org/zaproxy/zap/extension/revisit/resources/help_hi_IN/helpset_hi_IN.hs
|
apache-2.0
| 969
| 80
| 66
| 159
| 413
| 209
| 204
| -1
| -1
|
-------------------------------------------------------------------------------
-- |
-- Module : System.Hardware.Haskino.Test.ExprList8
-- Copyright : (c) University of Kansas
-- License : BSD3
-- Stability : experimental
--
-- Quick Check tests for Expressions returning a Expr List8
-------------------------------------------------------------------------------
{-# LANGUAGE GADTs, ScopedTypeVariables, DataKinds #-}
module System.Hardware.Haskino.Test.ExprList8 where
import Prelude hiding
( quotRem, divMod, quot, rem, div, mod, properFraction, fromInteger, toInteger, (<*) )
import qualified Prelude as P
import System.Hardware.Haskino
import Data.Boolean
import Data.Boolean.Numbers
import Data.Boolean.Bits
import Data.Char
import Data.Int
import Data.Word
import Numeric
import qualified Data.Bits as DB
import Test.QuickCheck hiding ((.&.))
import Test.QuickCheck.Monadic
litEvalL :: Expr [Word8] -> [Word8]
litEvalL (LitList8 l) = l
litEval8 :: Expr Word8 -> Word8
litEval8 (LitW8 w) = w
litEvalB :: Expr Bool -> Bool
litEvalB (LitB b) = b
litEvalI :: Expr Int -> Int
litEvalI (LitI i) = i
stringToBytes :: String -> [Word8]
stringToBytes s = map (\d -> fromIntegral $ ord d) s
bytesToString :: [Word8] -> String
bytesToString bs = map (\d -> chr $ fromIntegral d) bs
prop_cons :: ArduinoConnection -> RemoteRef [Word8] -> Word8 -> [Word8] -> Property
prop_cons c r x xs = monadicIO $ do
let local = x : xs
remote <- run $ send c $ do
writeRemoteRefE r $ (lit x) *: (lit xs)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_app :: ArduinoConnection -> RemoteRef [Word8] -> [Word8] -> [Word8] -> Property
prop_app c r xs ys = monadicIO $ do
let local = xs ++ ys
remote <- run $ send c $ do
writeRemoteRefE r $ (lit xs) ++* (lit ys)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_tail :: ArduinoConnection -> RemoteRef [Word8] -> NonEmptyList Word8 -> Property
prop_tail c r (NonEmpty xs) = monadicIO $ do
let local = tail xs
remote <- run $ send c $ do
writeRemoteRefE r $ tailE (lit xs)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_len :: ArduinoConnection -> RemoteRef Int -> [Word8] -> Property
prop_len c ri xs = monadicIO $ do
let local = length xs
remote <- run $ send c $ do
writeRemoteRefE ri $ len (lit xs)
v <- readRemoteRefE ri
return v
assert (local == (fromIntegral $ litEvalI remote))
prop_elem :: ArduinoConnection -> RemoteRef Word8 -> NonEmptyList Word8 -> Property
prop_elem c r (NonEmpty xs) =
forAll (choose (0::Int, fromIntegral $ length xs - 1)) $ \e ->
monadicIO $ do
let local = xs !! (fromIntegral e)
remote <- run $ send c $ do
writeRemoteRefE r $ (lit xs) !!* (lit e)
v <- readRemoteRefE r
return v
assert (local == (fromIntegral $ litEval8 remote))
prop_head :: ArduinoConnection -> RemoteRef Word8 -> NonEmptyList Word8 -> Property
prop_head c r (NonEmpty xs) = monadicIO $ do
let local = head xs
remote <- run $ send c $ do
writeRemoteRefE r $ headE (lit xs)
v <- readRemoteRefE r
return v
assert (local == (fromIntegral $ litEval8 remote))
-- ToDo: generate prop_elem_out_of_bounds
prop_ifb :: ArduinoConnection -> RemoteRef [Word8] -> Bool -> Word8 -> Word8 ->
[Word8] -> [Word8] -> Property
prop_ifb c r b x y xs ys = monadicIO $ do
let local = if b then x : xs else y : ys
remote <- run $ send c $ do
writeRemoteRefE r $ ifB (lit b) (lit x *: lit xs) (lit y *: lit ys)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_eq :: ArduinoConnection -> RemoteRef Bool -> [Word8] -> [Word8] -> Property
prop_eq c r x y = monadicIO $ do
let local = x == y
remote <- run $ send c $ do
writeRemoteRefE r $ (lit x) ==* (lit y)
v <- readRemoteRefE r
return v
assert (local == litEvalB remote)
prop_neq :: ArduinoConnection -> RemoteRef Bool -> [Word8] -> [Word8] -> Property
prop_neq c r x y = monadicIO $ do
let local = x /= y
remote <- run $ send c $ do
writeRemoteRefE r $ (lit x) /=* (lit y)
v <- readRemoteRefE r
return v
assert (local == litEvalB remote)
prop_lt :: ArduinoConnection -> RemoteRef Bool -> [Word8] -> [Word8] -> Property
prop_lt c r x y = monadicIO $ do
let local = x < y
remote <- run $ send c $ do
writeRemoteRefE r $ (lit x) <* (lit y)
v <- readRemoteRefE r
return v
assert (local == litEvalB remote)
prop_gt :: ArduinoConnection -> RemoteRef Bool -> [Word8] -> [Word8] -> Property
prop_gt c r x y = monadicIO $ do
let local = x > y
remote <- run $ send c $ do
writeRemoteRefE r $ (lit x) >* (lit y)
v <- readRemoteRefE r
return v
assert (local == litEvalB remote)
prop_lte :: ArduinoConnection -> RemoteRef Bool -> [Word8] -> [Word8] -> Property
prop_lte c r x y = monadicIO $ do
let local = x <= y
remote <- run $ send c $ do
writeRemoteRefE r $ (lit x) <=* (lit y)
v <- readRemoteRefE r
return v
assert (local == litEvalB remote)
prop_gte :: ArduinoConnection -> RemoteRef Bool -> [Word8] -> [Word8] -> Property
prop_gte c r x y = monadicIO $ do
let local = x >= y
remote <- run $ send c $ do
writeRemoteRefE r $ (lit x) >=* (lit y)
v <- readRemoteRefE r
return v
assert (local == litEvalB remote)
prop_showW8 :: ArduinoConnection -> RemoteRef [Word8] -> Word8 -> Property
prop_showW8 c r x = monadicIO $ do
let local = stringToBytes $ show x
remote <- run $ send c $ do
writeRemoteRefE r $ showE (lit x)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_showW16 :: ArduinoConnection -> RemoteRef [Word8] -> Word16 -> Property
prop_showW16 c r x = monadicIO $ do
let local = stringToBytes $ show x
remote <- run $ send c $ do
writeRemoteRefE r $ showE (lit x)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_showW32 :: ArduinoConnection -> RemoteRef [Word8] -> Word32 -> Property
prop_showW32 c r x = monadicIO $ do
let local = stringToBytes $ show x
remote <- run $ send c $ do
writeRemoteRefE r $ showE (lit x)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_showI8 :: ArduinoConnection -> RemoteRef [Word8] -> Int8 -> Property
prop_showI8 c r x = monadicIO $ do
let local = stringToBytes $ show x
remote <- run $ send c $ do
writeRemoteRefE r $ showE (lit x)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_showI16 :: ArduinoConnection -> RemoteRef [Word8] -> Int16 -> Property
prop_showI16 c r x = monadicIO $ do
let local = stringToBytes $ show x
remote <- run $ send c $ do
writeRemoteRefE r $ showE (lit x)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_showI32 :: ArduinoConnection -> RemoteRef [Word8] -> Int32 -> Property
prop_showI32 c r x = monadicIO $ do
let local = stringToBytes $ show x
remote <- run $ send c $ do
writeRemoteRefE r $ showE (lit x)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
prop_showFloat :: ArduinoConnection -> RemoteRef [Word8] -> Float -> Property
prop_showFloat c r x = monadicIO $ do
let local = showFFloat (Just 2) x ""
remote <- run $ send c $ do
writeRemoteRefE r $ showFFloatE (Just (lit 2)) (lit x)
v <- readRemoteRefE r
return v
assert (local == (bytesToString $ litEvalL remote))
prop_showBool :: ArduinoConnection -> RemoteRef [Word8] -> Bool -> Property
prop_showBool c r x = monadicIO $ do
let local = stringToBytes $ show x
remote <- run $ send c $ do
writeRemoteRefE r $ showE (lit x)
v <- readRemoteRefE r
return v
assert (local == litEvalL remote)
main :: IO ()
main = do
conn <- openArduino False "/dev/cu.usbmodem1421"
refL <- send conn $ newRemoteRefE (lit [])
refW8 <- send conn $ newRemoteRefE (lit 0)
refI <- send conn $ newRemoteRefE (lit 0)
refB <- send conn $ newRemoteRefE (lit False)
print "Cons Tests:"
quickCheck (prop_cons conn refL)
print "Apppend Tests:"
quickCheck (prop_app conn refL)
print "Length Tests:"
quickCheck (prop_len conn refI)
print "Element Tests:"
quickCheck (prop_elem conn refW8)
print "Head Tests:"
quickCheck (prop_head conn refW8)
print "Tail Tests:"
quickCheck (prop_tail conn refL)
print "ifB Tests:"
quickCheck (prop_ifb conn refL)
print "Equal Tests:"
quickCheck (prop_eq conn refB)
print "Not Equal Tests:"
quickCheck (prop_neq conn refB)
print "Less Than Tests:"
quickCheck (prop_lt conn refB)
print "Greater Than Tests:"
quickCheck (prop_gt conn refB)
print "Less Than Equal Tests:"
quickCheck (prop_lte conn refB)
print "Greater Than Equal Tests:"
quickCheck (prop_gte conn refB)
print "Show Word8 Tests:"
quickCheck (prop_showW8 conn refL)
print "Show Word16 Tests:"
quickCheck (prop_showW16 conn refL)
print "Show Word32 Tests:"
quickCheck (prop_showW32 conn refL)
print "Show Int8 Tests:"
quickCheck (prop_showI8 conn refL)
print "Show Int16 Tests:"
quickCheck (prop_showI16 conn refL)
print "Show Int32 Tests:"
quickCheck (prop_showI32 conn refL)
print "Show Bool Tests:"
quickCheck (prop_showBool conn refL)
print "Show Float Tests:"
quickCheck (prop_showFloat conn refL)
closeArduino conn
|
ku-fpg/kansas-amber
|
tests/ExprTests/ExprList8.hs
|
bsd-3-clause
| 9,847
| 0
| 17
| 2,589
| 3,754
| 1,748
| 2,006
| 249
| 2
|
module T16569 where
main :: IO ()
main = putStrLn (case (undefined :: Int) of _ -> undefined)
|
sdiehl/ghc
|
testsuite/tests/ghci/scripts/T16569.hs
|
bsd-3-clause
| 95
| 0
| 9
| 19
| 41
| 23
| 18
| 3
| 1
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>Advanced SQLInjection Scanner</title>
<maps>
<homeID>sqliplugin</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/sqliplugin/src/main/javahelp/help_sq_AL/helpset_sq_AL.hs
|
apache-2.0
| 981
| 77
| 66
| 157
| 409
| 207
| 202
| -1
| -1
|
module A1 where
import Control.Parallel.Strategies
fib t n
| n <= 1 = 1
| otherwise = n1_2 + n2_2 + 1
where
n1 = fib 20 (n-1)
n2 = fib 20 (n-2)
(n1_2, n2_2)
=
runEval
(do n1_2 <- rpar_abs_1 n1
n2_2 <- rpar_abs_1 n2
return (n1_2, n2_2))
where
rpar_abs_1
| n > t = rpar
| otherwise = rseq
n1_2 = fib 20 42
|
RefactoringTools/HaRe
|
old/testing/introDeepSeq/A1.hs
|
bsd-3-clause
| 492
| 0
| 12
| 254
| 169
| 84
| 85
| 17
| 1
|
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving, PatternGuards #-}
-- | Haste.App startup monad and configuration.
module Haste.App.Monad (
Remotable,
App, Server, Sessions, SessionID, Remote (..), Done (..),
AppCfg, defaultConfig, mkConfig, cfgHost, cfgPort,
liftServerIO, forkServerIO, remote, getAppConfig,
runApp, (<.>), getSessionID, getActiveSessions, onSessionEnd
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Monad (ap)
import Control.Monad.IO.Class
import Haste.Binary
import qualified Data.Map as M
import qualified Data.Set as S
import Haste.App.Protocol
import Data.Word
import Control.Concurrent (ThreadId)
import Data.IORef
import System.IO.Unsafe
#ifndef __HASTE__
import Haste.Binary.Types
import Control.Concurrent (forkIO)
import Network.WebSockets as WS
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.UTF8 as BU
import Control.Exception
import System.Random hiding (next)
import Data.List (foldl')
import Data.String
#endif
data AppCfg = AppCfg {
cfgHost :: String,
cfgPort :: Int,
cfgSessionEndHandlers :: [SessionID -> Server ()]
}
defaultConfig :: AppCfg
defaultConfig = mkConfig "localhost" 24601
-- | Create a default configuration from a host name and a port number.
mkConfig :: String -> Int -> AppCfg
mkConfig host port = AppCfg {
cfgHost = host,
cfgPort = port,
cfgSessionEndHandlers = []
}
type SessionID = Word64
type Sessions = S.Set SessionID
type Method = [Blob] -> SessionID -> IORef Sessions -> IO Blob
type Exports = M.Map CallID Method
newtype Done = Done (IO ())
#ifdef __HASTE__
data Remote a = Remote CallID [Blob]
#else
data Remote a = Remote
#endif
-- | Has 'runApp' already been invoked?
hasteAppRunning :: IORef Bool
hasteAppRunning = unsafePerformIO $ newIORef False
-- | Apply an exported function to an argument.
-- TODO: look into making this Applicative.
(<.>) :: Binary a => Remote (a -> b) -> a -> Remote b
#ifdef __HASTE__
(Remote cid args) <.> arg = Remote cid (encode arg:args)
#else
_ <.> _ = Remote
#endif
-- | Application monad; allows for exporting functions, limited liftIO,
-- forkIO and launching the client.
newtype App a = App {
unA :: AppCfg
-> IORef Sessions
-> CallID
-> Exports
-> IO (a, CallID, Exports, AppCfg)
}
instance Monad App where
return x = App $ \c _ cid exports -> return (x, cid, exports, c)
(App m) >>= f = App $ \cfg sessions cid exports -> do
res <- m cfg sessions cid exports
case res of
(x, cid', exports', cfg') -> unA (f x) cfg' sessions cid' exports'
instance Functor App where
fmap f m = m >>= return . f
instance Applicative App where
(<*>) = ap
pure = return
-- | Lift an IO action into the Server monad, the result of which can only be
-- used server-side.
liftServerIO :: IO a -> App (Server a)
#ifdef __HASTE__
liftServerIO _ = return Server
#else
liftServerIO m = App $ \cfg _ cid exports -> do
x <- m
return (return x, cid, exports, cfg)
#endif
-- | Fork off a Server computation not bound an API call.
-- This may be useful for any tasks that will keep running for as long as
-- the server is running.
--
-- Calling @getSessionID@ inside this computation will return 0, which will
-- never be generated for an actual session. @getActiveSessions@ works as
-- expected.
forkServerIO :: Server () -> App (Server ThreadId)
#ifdef __HASTE__
forkServerIO _ = return Server
#else
forkServerIO (Server m) = App $ \cfg sessions cid exports -> do
tid <- forkIO $ m 0 sessions
return (return tid, cid, exports, cfg)
#endif
-- | An exportable function is of the type
-- (Serialize a, ..., Serialize result) => a -> ... -> IO result
class Remotable a where
serializify :: a -> [Blob] -> (SessionID -> IORef Sessions -> IO Blob)
instance Binary a => Remotable (Server a) where
#ifdef __HASTE__
serializify _ _ = undefined
#else
serializify (Server m) _ = \sid ss -> fmap encode (m sid ss)
#endif
instance (Binary a, Remotable b) => Remotable (a -> b) where
#ifdef __HASTE__
serializify _ _ = undefined
#else
serializify f (x:xs) = serializify (f $! fromEither $ decode (toBD x)) xs
where
toBD (Blob x') = BlobData x'
fromEither (Right val) = val
fromEither (Left e) = error $ "Unable to deserialize data: " ++ e
serializify _ _ = error "The impossible happened in serializify!"
#endif
-- | Make a function available to the client as an API call.
remote :: Remotable a => a -> App (Remote a)
#ifdef __HASTE__
remote _ = App $ \c _ cid _ ->
return (Remote cid [], cid+1, undefined, c)
#else
remote s = App $ \c _ cid exports ->
return (Remote, cid+1, M.insert cid (serializify s) exports, c)
#endif
-- | Register a handler to be run whenever a session terminates.
-- Several handlers can be registered at the same time; they will be run in
-- the order they were registered.
onSessionEnd :: (SessionID -> Server ()) -> App ()
#ifdef __HASTE__
onSessionEnd _ = return ()
#else
onSessionEnd s = App $ \cfg _ cid exports -> return $
((), cid, exports, cfg {cfgSessionEndHandlers = s:cfgSessionEndHandlers cfg})
#endif
-- | Returns the application configuration.
getAppConfig :: App AppCfg
getAppConfig = App $ \cfg _ cid exports -> return (cfg, cid, exports, cfg)
-- | Run a Haste.App application. runApp never returns before the program
-- terminates.
--
-- Note that @runApp@ is single-entry, and that its argument must not
-- depend on any external IO. It is *strongly* recommended that the main
-- function of any Haste.App program *only* consists of a single call to
-- @runApp@.
runApp :: AppCfg -> App Done -> IO ()
runApp cfg (App s) = do
running <- atomicModifyIORef hasteAppRunning $ \r -> (True, r)
if running
then do
error "runApp is single-entry!"
else do
#ifdef __HASTE__
(Done client, _, _, _) <- s cfg undefined 0 undefined
client
#else
sessions <- newIORef S.empty
(_, _, exports, cfg') <- s cfg sessions 0 M.empty
serverEventLoop cfg' sessions exports
#endif
#ifndef __HASTE__
-- | Server's communication event loop. Handles dispatching API calls.
-- TODO: we could consider terminating a client who gets bad data, as that is
-- a sure side of outside interference.
serverEventLoop :: AppCfg -> IORef Sessions -> Exports -> IO ()
serverEventLoop cfg sessions exports = do
WS.runServer "0.0.0.0" (cfgPort cfg) $ \pending -> do
conn <- acceptRequest pending
sid <- randomRIO (1, 0xFFFFFFFFFFFFFFFF)
atomicModifyIORef sessions $ \s -> (S.insert sid s, ())
clientLoop sid sessions conn
where
cleanup :: Connection -> SessionID -> IORef Sessions -> IO ()
cleanup conn deadsession sref = do
let f next m = unS (m deadsession) deadsession sref >> next
foldl' f (return ()) (cfgSessionEndHandlers cfg)
atomicModifyIORef sref $ \cs -> (S.delete deadsession cs, ())
let Blob bs = encode $ ServerException "Session ended"
sendTextData conn bs
clientLoop :: SessionID -> IORef Sessions -> Connection -> IO ()
clientLoop sid sref c = finally go (cleanup c sid sref)
where
go = do
msg <- receiveData c
_ <- forkIO $ do
case decode (BlobData msg) of
Right (ServerCall nonce method args)
| Just m <- M.lookup method exports -> do
result <- m args sid sref
let Blob bs = encode $ ServerReply {
srNonce = nonce,
srResult = result
}
sendBinaryData c bs
_ -> do
error $ "Got bad method call: " ++ show msg
go
#endif
-- | Server monad for Haste.App. Allows redeeming remote values, lifting IO
-- actions, and not much more.
#ifdef __HASTE__
data Server a = Server
#else
newtype Server a = Server {unS :: SessionID -> IORef Sessions -> IO a}
#endif
instance Functor Server where
#ifdef __HASTE__
fmap _ _ = Server
#else
fmap f (Server m) = Server $ \sid ss -> f <$> m sid ss
#endif
instance Applicative Server where
(<*>) = ap
pure = return
instance Monad Server where
#ifdef __HASTE__
return _ = Server
_ >>= _ = Server
#else
return x = Server $ \_ _ -> return x
(Server m) >>= f = Server $ \sid ss -> do
Server m' <- f <$> m sid ss
m' sid ss
#endif
instance MonadIO Server where
#ifdef __HASTE__
liftIO _ = Server
#else
liftIO m = Server $ \_ _ -> m
#endif
instance MonadBlob Server where
#ifndef __HASTE__
getBlobData (Blob bd) = return $ BlobData bd
getBlobText' (Blob bd) = return $ fromString $ BU.toString $ BS.concat $ BSL.toChunks bd
#else
getBlobData _ = Server
getBlobText' _ = Server
#endif
-- | Returns the ID of the current session.
getSessionID :: Server SessionID
#ifdef __HASTE__
getSessionID = Server
#else
getSessionID = Server $ \sid _ -> return sid
#endif
-- | Return all currently active sessions.
getActiveSessions :: Server Sessions
#ifdef __HASTE__
getActiveSessions = Server
#else
getActiveSessions = Server $ \_ ss -> readIORef ss
#endif
|
beni55/haste-compiler
|
libraries/haste-lib/src/Haste/App/Monad.hs
|
bsd-3-clause
| 9,244
| 0
| 26
| 2,148
| 1,958
| 1,072
| 886
| 152
| 2
|
{-# LANGUAGE ConstraintKinds, GADTs, RankNTypes #-}
{-# LANGUAGE TypeOperators, KindSignatures #-}
module CatEntail where
import Prelude hiding (id, (.))
import Data.Kind
import Control.Category
-- One dictionary to rule them all.
data Dict :: Constraint -> Type where
Dict :: ctx => Dict ctx
-- Entailment.
-- Note the kind 'Constraint -> Constraint -> *'
newtype (|-) a b = Sub (a => Dict b)
(\\) :: a => (b => r) -> (a |- b) -> r
r \\ Sub Dict = r
reflexive :: a |- a
reflexive = Sub Dict
transitive :: (b |- c) -> (a |- b) -> a |- c
transitive f g = Sub $ Dict \\ f \\ g
instance Category (|-) where
id = reflexive
(.) = transitive
|
sdiehl/ghc
|
libraries/base/tests/CatEntail.hs
|
bsd-3-clause
| 649
| 0
| 9
| 139
| 221
| 127
| 94
| -1
| -1
|
{-# LANGUAGE PolyKinds, DataKinds, KindSignatures, RankNTypes,
TypeFamilies, FlexibleInstances, UndecidableInstances #-}
module T6118 where
import GHC.Exts
data Nat = Zero | Succ Nat
data List a = Nil | Cons a (List a)
class SingE (a :: k) where
type Demote a :: *
instance SingE (a :: Bool) where
type Demote a = Bool
instance SingE (a :: Nat) where
type Demote a = Nat
instance SingE (a :: Maybe k) where
type Demote a = Maybe (Demote (Any :: k))
instance SingE (a :: List k) where
type Demote (a :: List k) = List (Demote (Any :: k))
|
frantisekfarka/ghc-dsi
|
testsuite/tests/polykinds/T6118.hs
|
bsd-3-clause
| 566
| 2
| 10
| 129
| 206
| 114
| 92
| 16
| 0
|
module Identifiers where
foo, bar, baz :: Int -> Int -> Int
foo x y = x + x * bar y x * y + y
bar x y = y + x - baz x y - x + y
baz x y = x * y * y * y * x
quux :: Int -> Int
quux x = foo (bar x x) (bar x x)
norf :: Int -> Int -> Int -> Int
norf x y z
| x < 0 = quux x
| y < 0 = quux y
| z < 0 = quux z
| otherwise = norf (-x) (-y) (-z)
main :: IO ()
main = do
putStrLn . show $ foo x y
putStrLn . show $ quux z
putStrLn . show $ Identifiers.norf x y z
where
x = 10
y = 20
z = 30
|
sdiehl/ghc
|
testsuite/tests/hiefile/should_compile/hie004.hs
|
bsd-3-clause
| 528
| 0
| 9
| 197
| 334
| 166
| 168
| 21
| 1
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, BangPatterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Device
-- Copyright : (c) The University of Glasgow, 1994-2008
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- Type classes for I/O providers.
--
-----------------------------------------------------------------------------
module GHC.IO.Device (
RawIO(..),
IODevice(..),
IODeviceType(..),
SeekMode(..)
) where
import GHC.Base
import GHC.Word
import GHC.Arr
import GHC.Enum
import GHC.Read
import GHC.Show
import GHC.Ptr
import GHC.Num
import GHC.IO
import {-# SOURCE #-} GHC.IO.Exception ( unsupportedOperation )
-- | A low-level I/O provider where the data is bytes in memory.
class RawIO a where
-- | Read up to the specified number of bytes, returning the number
-- of bytes actually read. This function should only block if there
-- is no data available. If there is not enough data available,
-- then the function should just return the available data. A return
-- value of zero indicates that the end of the data stream (e.g. end
-- of file) has been reached.
read :: a -> Ptr Word8 -> Int -> IO Int
-- | Read up to the specified number of bytes, returning the number
-- of bytes actually read, or 'Nothing' if the end of the stream has
-- been reached.
readNonBlocking :: a -> Ptr Word8 -> Int -> IO (Maybe Int)
-- | Write the specified number of bytes.
write :: a -> Ptr Word8 -> Int -> IO ()
-- | Write up to the specified number of bytes without blocking. Returns
-- the actual number of bytes written.
writeNonBlocking :: a -> Ptr Word8 -> Int -> IO Int
-- | I/O operations required for implementing a 'Handle'.
class IODevice a where
-- | @ready dev write msecs@ returns 'True' if the device has data
-- to read (if @write@ is 'False') or space to write new data (if
-- @write@ is 'True'). @msecs@ specifies how long to wait, in
-- milliseconds.
--
ready :: a -> Bool -> Int -> IO Bool
-- | closes the device. Further operations on the device should
-- produce exceptions.
close :: a -> IO ()
-- | returns 'True' if the device is a terminal or console.
isTerminal :: a -> IO Bool
isTerminal _ = return False
-- | returns 'True' if the device supports 'seek' operations.
isSeekable :: a -> IO Bool
isSeekable _ = return False
-- | seek to the specified position in the data.
seek :: a -> SeekMode -> Integer -> IO ()
seek _ _ _ = ioe_unsupportedOperation
-- | return the current position in the data.
tell :: a -> IO Integer
tell _ = ioe_unsupportedOperation
-- | return the size of the data.
getSize :: a -> IO Integer
getSize _ = ioe_unsupportedOperation
-- | change the size of the data.
setSize :: a -> Integer -> IO ()
setSize _ _ = ioe_unsupportedOperation
-- | for terminal devices, changes whether characters are echoed on
-- the device.
setEcho :: a -> Bool -> IO ()
setEcho _ _ = ioe_unsupportedOperation
-- | returns the current echoing status.
getEcho :: a -> IO Bool
getEcho _ = ioe_unsupportedOperation
-- | some devices (e.g. terminals) support a "raw" mode where
-- characters entered are immediately made available to the program.
-- If available, this operations enables raw mode.
setRaw :: a -> Bool -> IO ()
setRaw _ _ = ioe_unsupportedOperation
-- | returns the 'IODeviceType' corresponding to this device.
devType :: a -> IO IODeviceType
-- | duplicates the device, if possible. The new device is expected
-- to share a file pointer with the original device (like Unix @dup@).
dup :: a -> IO a
dup _ = ioe_unsupportedOperation
-- | @dup2 source target@ replaces the target device with the source
-- device. The target device is closed first, if necessary, and then
-- it is made into a duplicate of the first device (like Unix @dup2@).
dup2 :: a -> a -> IO a
dup2 _ _ = ioe_unsupportedOperation
ioe_unsupportedOperation :: IO a
ioe_unsupportedOperation = throwIO unsupportedOperation
-- | Type of a device that can be used to back a
-- 'GHC.IO.Handle.Handle' (see also 'GHC.IO.Handle.mkFileHandle'). The
-- standard libraries provide creation of 'GHC.IO.Handle.Handle's via
-- Posix file operations with file descriptors (see
-- 'GHC.IO.Handle.FD.mkHandleFromFD') with FD being the underlying
-- 'GHC.IO.Device.IODevice' instance.
--
-- Users may provide custom instances of 'GHC.IO.Device.IODevice'
-- which are expected to conform the following rules:
data IODeviceType
= Directory -- ^ The standard libraries do not have direct support
-- for this device type, but a user implementation is
-- expected to provide a list of file names in
-- the directory, in any order, separated by @'\0'@
-- characters, excluding the @"."@ and @".."@ names. See
-- also 'System.Directory.getDirectoryContents'. Seek
-- operations are not supported on directories (other
-- than to the zero position).
| Stream -- ^ A duplex communications channel (results in
-- creation of a duplex 'GHC.IO.Handle.Handle'). The
-- standard libraries use this device type when
-- creating 'GHC.IO.Handle.Handle's for open sockets.
| RegularFile -- ^ A file that may be read or written, and also
-- may be seekable.
| RawDevice -- ^ A "raw" (disk) device which supports block binary
-- read and write operations and may be seekable only
-- to positions of certain granularity (block-
-- aligned).
deriving (Eq)
-- -----------------------------------------------------------------------------
-- SeekMode type
-- | A mode that determines the effect of 'hSeek' @hdl mode i@.
data SeekMode
= AbsoluteSeek -- ^ the position of @hdl@ is set to @i@.
| RelativeSeek -- ^ the position of @hdl@ is set to offset @i@
-- from the current position.
| SeekFromEnd -- ^ the position of @hdl@ is set to offset @i@
-- from the end of the file.
deriving (Eq, Ord, Ix, Enum, Read, Show)
|
tolysz/prepare-ghcjs
|
spec-lts8/base/GHC/IO/Device.hs
|
bsd-3-clause
| 6,396
| 0
| 12
| 1,526
| 696
| 407
| 289
| 61
| 1
|
module SafeLang15_A (IsoInt, h, showH, P, p, showP) where
newtype IsoInt = I Int
h :: IsoInt
h = I 2
showH :: String
showH = let I n = h
in show n
data P = P Int
p :: P
p = P 3
showP :: P -> String
showP (P n) = "Should be 3 := " ++ show n
|
siddhanathan/ghc
|
testsuite/tests/safeHaskell/safeLanguage/SafeLang15_A.hs
|
bsd-3-clause
| 255
| 0
| 9
| 78
| 125
| 68
| 57
| 12
| 1
|
{-# LANGUAGE TypeFamilies #-}
module Overlap4 where
type family F a b where
F Int Int = Bool
F Bool = Maybe
|
urbanslug/ghc
|
testsuite/tests/indexed-types/should_fail/Overlap4.hs
|
bsd-3-clause
| 115
| 0
| 6
| 29
| 31
| 19
| 12
| 5
| 0
|
-- #4444: We shouldn't warn about SPECIALISE INLINE pragmas on
-- non-overloaded functions
{-# LANGUAGE GADTs, MagicHash #-}
module Q where
import GHC.Exts
data Arr e where
ArrInt :: !Int -> ByteArray# -> Arr Int
ArrPair :: !Int -> Arr e1 -> Arr e2 -> Arr (e1, e2)
(!:) :: Arr e -> Int -> e
{-# SPECIALISE INLINE (!:) :: Arr Int -> Int -> Int #-}
{-# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #-}
(ArrInt _ ba) !: (I# i) = I# (indexIntArray# ba i)
(ArrPair _ a1 a2) !: i = (a1 !: i, a2 !: i)
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_compile/T4444.hs
|
bsd-3-clause
| 529
| 0
| 10
| 130
| 158
| 84
| 74
| 15
| 1
|
import Data.List (sort)
quads n = sort [(quad a b c d, (a,b,c,d))
| a <- [1..n], b <- [a..n], c <- [a+1..n], d <- [c..n],
cube a + cube b == cube c + cube d]
where
cube x = x^3
quad a b c d = cube a + cube b
|
dirkz/Thinking_Functionally_With_Haskell
|
4/Quads.hs
|
isc
| 235
| 0
| 11
| 80
| 174
| 89
| 85
| 6
| 1
|
{-# LANGUAGE MultiWayIf,LambdaCase,TupleSections,DeriveFunctor #-}
module LatexNodes where
import Text.ParserCombinators.Parsec
import System.Process
import Text.Printf (printf)
import Control.Parallel.Strategies
import Control.DeepSeq
import AST
import Parser (parseLText)
--wrap for simple latex expressions
(\>) :: String -> String -> String
str \> s = printf "\\%s{%s}\n" str s
(\\>) :: String -> String -> String
str \\> s = printf "\\%s{%s}" str s
stringOfDocElt :: DocElts -> IO String
stringOfDocElt = \case
Section s -> return $ "section*" \> s
SubSection s -> return $ "subsection*" \> s
SubSubSection s -> return $ "subsubsection*" \> s
Paragraph s -> do
lt <- case parse parseLText "" s of
Left e -> error $ "This paragraph:\n" ++
s ++ "\ncontains the following error:\n" ++ (show e)
Right r -> return r
mapM stringOfLText lt >>= return . (++ "\n\n") . concat
stringOfLText :: LText -> IO String
stringOfLText = \case
Bold s -> return $ "textbf" \\> s
Underline s -> return $ "underline" \\> s
IText s -> return $ "textit" \\> s
Normal s -> return s
IVShell s ls -> readProcess s ls "" >>=
(\r -> return $ "\\begin{verbatim}" ++ r ++ "\\end{verbatim}")
IShell s ls -> readProcess s ls ""
LBlock cmd body -> (mapM stringOfLText body) >>= return . concat
>>= return . (++ "end" \> cmd) . ("begin" \\> cmd ++)
Code lang source -> return $ ("begin" \\> "minted") ++
"[frame=single,mathescape]" ++ "{" ++ lang ++ "}" ++
source ++ "\n" ++ ("end" \> "minted") ++ "\n"
-- declare header-specific variables based on title and author
-- TODO: don't hardcode author/title variables
varDecs :: Doc -> String
varDecs (Doc title author _ ) = printf "\\newcommand{\\mytitle}{%s}\
\ \n\\newcommand{\\myauthor}{%s}\n" title author
-- emit laTex from a document
-- TODO: have it return either rather than ad-hoc error throwing
emitDoc :: Doc -> IO String
emitDoc (Doc title author bullets) = do
title' <- return $ "title" \> title
author' <- return $ "author" \> author
rest' <- concatmapM getEltPair bullets
return $ title' ++ "\n" ++ author' ++ "\n\\begin{document}\n" -- deleted \maketitle
++ rest' ++ "\n\\end{document}"
where concatmapM f l = mapM f l >>= return . concat
getEltPair :: ([DocElts],[Bullet]) -> IO String
getEltPair (d,b) = do
docElts' <- concatmapM stringOfDocElt d
bullets' <- (emitBT True . conv) $ map lTextofBullet b
return $ docElts' ++ bullets'
lTextofBullet :: Bullet -> (Int,[LText])
lTextofBullet (n,tex) = (n,rightOf tex $ parse parseLText "" tex)
rightOf t = \case Right a -> Normal "\\item " : a
Left err -> error $ "parse error on input:\n" ++ (t) ++
"\nyielded the following error:\n" ++ show err
-- convert an assoc-list into a BT,
-- the assoc-list has the semantics of 'Indentation Levels' for bullets
conv :: (Eq a,NFData a) => [(Int,a)] -> BT a
conv = \case
[] -> Node [] Nothing Nothing
xs@((n,_):_) -> Node (map snd curr)
(if (child == []) || (fst $ head child) < n
then Nothing else Just $ conv child)
(if (next == []) then Nothing else Just $ conv next)
where (curr,child,next) = split3' ((== n).fst) xs
split3' f ls = runEval $ do
mid' <- rpar $ force (dropWhile f ls)
a' <- rpar $ force (takeWhile f ls)
rseq mid'
b' <- rpar $ force (takeWhile (not.f) mid')
c' <- rpar $ force (dropWhile (not.f) mid')
rseq a'; rseq b'; rseq c';
return (a',b',c')
-- convert BT [LText] to well-itemized Latex;
-- Boolean flag indicates whether or not to begin with a \begin{itemize}
emitBT :: Bool -> BT [LText] -> IO String
emitBT b (Node ls next cont) = do
bullets <- (mapM (mapM stringOfLText) ls) >>= return . (concat . concat) -- convert to string, flatten
children <- case next of {Nothing -> return ""; Just s -> emitBT True s}
continue <- case cont of {Nothing -> return "\\end{itemize}\n"; Just s -> emitBT False s}
return $ (if b then "\\begin{itemize}\n" else "") ++ bullets ++ children ++ continue
|
ezrosent/latexnodes
|
LatexNodes.hs
|
mit
| 4,401
| 0
| 19
| 1,228
| 1,437
| 730
| 707
| 81
| 8
|
-- This file is covered by an MIT license. See 'LICENSE' for details.
-- Author: Bertram Felgenhauer
module Confluence.Types (
Problem,
) where
import Data.Rewriting.Rule (Rule)
type Problem f v = [Rule f v]
|
haskell-rewriting/confluence-tool
|
src/Confluence/Types.hs
|
mit
| 215
| 0
| 6
| 41
| 41
| 27
| 14
| 4
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Prelude hiding (id)
import System.Environment (getArgs)
import Network.Wai
import Network.Wai.Middleware.RequestLogger (logStdoutDev)
import Network.Wai.Middleware.Gzip (gzip, def)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, setPort)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Web.Scotty
(scottyApp, get, middleware, setHeader, html, file)
import Network.Wai.Handler.WebSockets (websocketsOr)
import Network.WebSockets
(receiveData, sendTextData,
PendingConnection, acceptRequest, Connection, ConnectionException(..),
defaultConnectionOptions)
import Control.Monad (when, forever)
import Control.Exception (handle, fromException)
import Control.Concurrent.STM
(STM, TVar, newTVar, readTVar, writeTVar, atomically)
import qualified Data.Map as M
import Data.Aeson (encode, decode)
import Fay.Convert (showToFay, readFromFay)
import Types
import Pages.Index
main :: IO ()
main = do
graphV <- newGraph
clientsV <- newClients
port <- fmap (read . head) getArgs
home <- site
let settings = setPort port defaultSettings
app = websocketsOr
defaultConnectionOptions
(handleConnection clientsV graphV)
home
putStrLn "Serving on http://localhost:8000"
runSettings settings app
site :: IO Application
site = scottyApp $ do
middleware logStdoutDev
middleware (gzip def)
get "/js/app.js" $ js "js/app.js"
get "/" $ blaze Pages.Index.render
where
blaze = html . renderHtml
js f = file f >> setHeader "content-type" "text/javascript"
--css f = file f >> setHeader "content-type" "text/css"
{- WebSockets connection handler -}
handleConnection :: TVar Clients -> TVar Graph -> PendingConnection -> IO ()
handleConnection clientsV graphV pending = do
connection <- acceptRequest pending
client <- atomically $ addClient clientsV connection
putStrLn $ "Client " ++ show client ++ " connected"
handle (catchDisconnect client) $ forever $ do
msg <- receiveData connection
case fromFay msg of
Just edit -> handleClientEvent clientsV graphV client edit
Nothing -> return ()
where
fromFay x = case decode x of
Just x' -> readFromFay x'
Nothing -> Nothing
catchDisconnect client e = case fromException e of
-- This is backwards and needs to be fixed.
Just ConnectionClosed -> return ()
_otherwise -> do
putStrLn $ "Client " ++ show client ++ " disconnected"
atomically $ removeClient clientsV client
{- Edit event handlers -}
handleClientEvent :: TVar Clients -> TVar Graph -> ID -> Edit -> IO ()
-- Handle an event that creates a new node.
handleClientEvent clientsV graphV client (Create node@(Node id _)) = do
node'@(Node id' _) <- atomically $ insertNode graphV node
when (id' /= id) $ do
conn <- atomically $ getConnection clientsV client
case conn of
Nothing -> return ()
Just c -> sendTo c (UpdateID id id')
broadcast clientsV (Create node')
-- Handle node content update events.
handleClientEvent clientsV graphV _client edit@(UpdateContent id old new) = do
updated <- atomically $ updateNodeContent graphV id old new
when updated $ broadcast clientsV edit
-- All other events are just multiplexed to all clients.
handleClientEvent clientsV _ _ edit = broadcast clientsV edit
-- Convenience: send an object to a client.
sendTo :: Connection -> Edit -> IO ()
sendTo conn e = sendTextData conn . encode . showToFay $ e
-- Convenience: send an object to all clients.
broadcast :: TVar Clients -> Edit -> IO ()
broadcast clientsV e = do
conns <- atomically $ getConnections clientsV
mapM_ (flip sendTo e) conns
{- Graph data structure and modification -}
type Graph = M.Map ID Node
newGraph :: IO (TVar Graph)
newGraph = atomically $ newTVar M.empty
insertNode :: TVar Graph -> Node -> STM Node
insertNode graphV node@(Node id content) = do
graph <- readTVar graphV
-- Obtain a new node, which is either identical to 'node' if its 'id' does
-- not already exist in the graph, or modified with a new id if it does.
node' <- case M.lookup id graph of
Nothing -> return node
Just _ -> let id' = (fst . M.findMax $ graph) + 1
in return (Node id' content)
writeTVar graphV $ M.insert (nodeId node') node' graph
-- Return the new node so the user can inspect whether its ID was changed.
return node'
updateNodeContent :: TVar Graph -> ID -> String -> String -> STM Bool
updateNodeContent graphV id old new = do
graph <- readTVar graphV
-- Maybe modify the node, if it exists in the graph and its content matches
-- 'old'. If the content doesn't match, the edit is outdated.
node' <- case M.lookup id graph of
Nothing -> return (Node id old)
Just (Node _ content) ->
if content == old
then return (Node id new)
else return (Node id old)
-- Update the graph if the node was modified, and return status either way.
if nodeContent node' /= old
then writeTVar graphV (M.insert id node' graph) >> return True
else return False
{- Connected client registry -}
type Clients = M.Map ID Connection
newClients :: IO (TVar Clients)
newClients = atomically $ newTVar M.empty
addClient :: TVar Clients -> Connection -> STM ID
addClient clientsV connection = do
clients <- readTVar clientsV
let id = if M.null clients
then 0
else (fst . M.findMax $ clients) + 1
writeTVar clientsV $ M.insert id connection clients
return id
removeClient :: TVar Clients -> ID -> STM ()
removeClient clientsV client = do
clients <- readTVar clientsV
writeTVar clientsV $ M.delete client clients
getConnection :: TVar Clients -> ID -> STM (Maybe Connection)
getConnection clientsV client = do
clients <- readTVar clientsV
return $ M.lookup client clients
getConnections :: TVar Clients -> STM [Connection]
getConnections clientsV = do
clients <- readTVar clientsV
return (M.elems clients)
|
knowledge-map/graph-rtce
|
src/Server.hs
|
mit
| 6,283
| 0
| 19
| 1,528
| 1,772
| 878
| 894
| 131
| 4
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Dispatch where
import Foundation
import Handlers
import Yesod
mkYesodDispatch "Intranet" resourcesIntranet
|
lhoghu/intranet
|
app/Dispatch.hs
|
mit
| 196
| 0
| 5
| 34
| 23
| 14
| 9
| 7
| 0
|
{-# htermination (enumFromThenRatio :: Ratio MyInt -> Ratio MyInt -> (List (Ratio MyInt))) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ordering = LT | EQ | GT ;
data Ratio a = CnPc a a;
iterate :: (a -> a) -> a -> (List a);
iterate f x = Cons x (iterate f (f x));
primNegInt :: MyInt -> MyInt;
primNegInt (Pos x) = Neg x;
primNegInt (Neg x) = Pos x;
negateMyInt :: MyInt -> MyInt
negateMyInt = primNegInt;
negateRatio :: Ratio MyInt -> Ratio MyInt
negateRatio (CnPc x y) = CnPc (negateMyInt x) y;
primMinusNat :: Nat -> Nat -> MyInt;
primMinusNat Zero Zero = Pos Zero;
primMinusNat Zero (Succ y) = Neg (Succ y);
primMinusNat (Succ x) Zero = Pos (Succ x);
primMinusNat (Succ x) (Succ y) = primMinusNat x y;
primPlusNat :: Nat -> Nat -> Nat;
primPlusNat Zero Zero = Zero;
primPlusNat Zero (Succ y) = Succ y;
primPlusNat (Succ x) Zero = Succ x;
primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y));
primPlusInt :: MyInt -> MyInt -> MyInt;
primPlusInt (Pos x) (Neg y) = primMinusNat x y;
primPlusInt (Neg x) (Pos y) = primMinusNat y x;
primPlusInt (Neg x) (Neg y) = Neg (primPlusNat x y);
primPlusInt (Pos x) (Pos y) = Pos (primPlusNat x y);
psMyInt :: MyInt -> MyInt -> MyInt
psMyInt = primPlusInt;
primEqNat :: Nat -> Nat -> MyBool;
primEqNat Zero Zero = MyTrue;
primEqNat Zero (Succ y) = MyFalse;
primEqNat (Succ x) Zero = MyFalse;
primEqNat (Succ x) (Succ y) = primEqNat x y;
primEqInt :: MyInt -> MyInt -> MyBool;
primEqInt (Pos (Succ x)) (Pos (Succ y)) = primEqNat x y;
primEqInt (Neg (Succ x)) (Neg (Succ y)) = primEqNat x y;
primEqInt (Pos Zero) (Neg Zero) = MyTrue;
primEqInt (Neg Zero) (Pos Zero) = MyTrue;
primEqInt (Neg Zero) (Neg Zero) = MyTrue;
primEqInt (Pos Zero) (Pos Zero) = MyTrue;
primEqInt xv xw = MyFalse;
esEsMyInt :: MyInt -> MyInt -> MyBool
esEsMyInt = primEqInt;
fromIntMyInt :: MyInt -> MyInt
fromIntMyInt x = x;
stop :: MyBool -> a;
stop MyFalse = stop MyFalse;
error :: a;
error = stop MyTrue;
otherwise :: MyBool;
otherwise = MyTrue;
primMinusNatS :: Nat -> Nat -> Nat;
primMinusNatS (Succ x) (Succ y) = primMinusNatS x y;
primMinusNatS Zero (Succ y) = Zero;
primMinusNatS x Zero = x;
primDivNatS0 x y MyTrue = Succ (primDivNatS (primMinusNatS x y) (Succ y));
primDivNatS0 x y MyFalse = Zero;
primGEqNatS :: Nat -> Nat -> MyBool;
primGEqNatS (Succ x) Zero = MyTrue;
primGEqNatS (Succ x) (Succ y) = primGEqNatS x y;
primGEqNatS Zero (Succ x) = MyFalse;
primGEqNatS Zero Zero = MyTrue;
primDivNatS :: Nat -> Nat -> Nat;
primDivNatS Zero Zero = error;
primDivNatS (Succ x) Zero = error;
primDivNatS (Succ x) (Succ y) = primDivNatS0 x y (primGEqNatS x y);
primDivNatS Zero (Succ x) = Zero;
primQuotInt :: MyInt -> MyInt -> MyInt;
primQuotInt (Pos x) (Pos (Succ y)) = Pos (primDivNatS x (Succ y));
primQuotInt (Pos x) (Neg (Succ y)) = Neg (primDivNatS x (Succ y));
primQuotInt (Neg x) (Pos (Succ y)) = Neg (primDivNatS x (Succ y));
primQuotInt (Neg x) (Neg (Succ y)) = Pos (primDivNatS x (Succ y));
primQuotInt wz xu = error;
quotMyInt :: MyInt -> MyInt -> MyInt
quotMyInt = primQuotInt;
absReal0 x MyTrue = negateMyInt x;
absReal1 x MyTrue = x;
absReal1 x MyFalse = absReal0 x otherwise;
primCmpNat :: Nat -> Nat -> Ordering;
primCmpNat Zero Zero = EQ;
primCmpNat Zero (Succ y) = LT;
primCmpNat (Succ x) Zero = GT;
primCmpNat (Succ x) (Succ y) = primCmpNat x y;
primCmpInt :: MyInt -> MyInt -> Ordering;
primCmpInt (Pos Zero) (Pos Zero) = EQ;
primCmpInt (Pos Zero) (Neg Zero) = EQ;
primCmpInt (Neg Zero) (Pos Zero) = EQ;
primCmpInt (Neg Zero) (Neg Zero) = EQ;
primCmpInt (Pos x) (Pos y) = primCmpNat x y;
primCmpInt (Pos x) (Neg y) = GT;
primCmpInt (Neg x) (Pos y) = LT;
primCmpInt (Neg x) (Neg y) = primCmpNat y x;
compareMyInt :: MyInt -> MyInt -> Ordering
compareMyInt = primCmpInt;
esEsOrdering :: Ordering -> Ordering -> MyBool
esEsOrdering LT LT = MyTrue;
esEsOrdering LT EQ = MyFalse;
esEsOrdering LT GT = MyFalse;
esEsOrdering EQ LT = MyFalse;
esEsOrdering EQ EQ = MyTrue;
esEsOrdering EQ GT = MyFalse;
esEsOrdering GT LT = MyFalse;
esEsOrdering GT EQ = MyFalse;
esEsOrdering GT GT = MyTrue;
not :: MyBool -> MyBool;
not MyTrue = MyFalse;
not MyFalse = MyTrue;
fsEsOrdering :: Ordering -> Ordering -> MyBool
fsEsOrdering x y = not (esEsOrdering x y);
gtEsMyInt :: MyInt -> MyInt -> MyBool
gtEsMyInt x y = fsEsOrdering (compareMyInt x y) LT;
absReal2 x = absReal1 x (gtEsMyInt x (fromIntMyInt (Pos Zero)));
absReal x = absReal2 x;
absMyInt :: MyInt -> MyInt
absMyInt = absReal;
primModNatS0 x y MyTrue = primModNatS (primMinusNatS x (Succ y)) (Succ (Succ y));
primModNatS0 x y MyFalse = Succ x;
primModNatS :: Nat -> Nat -> Nat;
primModNatS Zero Zero = error;
primModNatS Zero (Succ x) = Zero;
primModNatS (Succ x) Zero = error;
primModNatS (Succ x) (Succ Zero) = Zero;
primModNatS (Succ x) (Succ (Succ y)) = primModNatS0 x y (primGEqNatS x (Succ y));
primRemInt :: MyInt -> MyInt -> MyInt;
primRemInt (Pos x) (Pos (Succ y)) = Pos (primModNatS x (Succ y));
primRemInt (Pos x) (Neg (Succ y)) = Pos (primModNatS x (Succ y));
primRemInt (Neg x) (Pos (Succ y)) = Neg (primModNatS x (Succ y));
primRemInt (Neg x) (Neg (Succ y)) = Neg (primModNatS x (Succ y));
primRemInt wx wy = error;
remMyInt :: MyInt -> MyInt -> MyInt
remMyInt = primRemInt;
gcd0Gcd'0 x y = gcd0Gcd' y (remMyInt x y);
gcd0Gcd'1 MyTrue x xx = x;
gcd0Gcd'1 xy xz yu = gcd0Gcd'0 xz yu;
gcd0Gcd'2 x xx = gcd0Gcd'1 (esEsMyInt xx (fromIntMyInt (Pos Zero))) x xx;
gcd0Gcd'2 yv yw = gcd0Gcd'0 yv yw;
gcd0Gcd' x xx = gcd0Gcd'2 x xx;
gcd0Gcd' x y = gcd0Gcd'0 x y;
gcd0 x y = gcd0Gcd' (absMyInt x) (absMyInt y);
gcd1 MyTrue yx yy = error;
gcd1 yz zu zv = gcd0 zu zv;
gcd2 MyTrue yx yy = gcd1 (esEsMyInt yy (fromIntMyInt (Pos Zero))) yx yy;
gcd2 zw zx zy = gcd0 zx zy;
gcd3 yx yy = gcd2 (esEsMyInt yx (fromIntMyInt (Pos Zero))) yx yy;
gcd3 zz vuu = gcd0 zz vuu;
gcd yx yy = gcd3 yx yy;
gcd x y = gcd0 x y;
reduce2D vuv vuw = gcd vuv vuw;
reduce2Reduce0 vuv vuw x y MyTrue = CnPc (quotMyInt x (reduce2D vuv vuw)) (quotMyInt y (reduce2D vuv vuw));
reduce2Reduce1 vuv vuw x y MyTrue = error;
reduce2Reduce1 vuv vuw x y MyFalse = reduce2Reduce0 vuv vuw x y otherwise;
reduce2 x y = reduce2Reduce1 x y x y (esEsMyInt y (fromIntMyInt (Pos Zero)));
reduce x y = reduce2 x y;
primMulNat :: Nat -> Nat -> Nat;
primMulNat Zero Zero = Zero;
primMulNat Zero (Succ y) = Zero;
primMulNat (Succ x) Zero = Zero;
primMulNat (Succ x) (Succ y) = primPlusNat (primMulNat x (Succ y)) (Succ y);
primMulInt :: MyInt -> MyInt -> MyInt;
primMulInt (Pos x) (Pos y) = Pos (primMulNat x y);
primMulInt (Pos x) (Neg y) = Neg (primMulNat x y);
primMulInt (Neg x) (Pos y) = Neg (primMulNat x y);
primMulInt (Neg x) (Neg y) = Pos (primMulNat x y);
srMyInt :: MyInt -> MyInt -> MyInt
srMyInt = primMulInt;
psRatio :: Ratio MyInt -> Ratio MyInt -> Ratio MyInt
psRatio (CnPc x y) (CnPc x' y') = reduce (psMyInt (srMyInt x y') (srMyInt x' y)) (srMyInt y y');
msRatio :: Ratio MyInt -> Ratio MyInt -> Ratio MyInt
msRatio x y = psRatio x (negateRatio y);
numericEnumFromThen n m = iterate (psRatio (msRatio m n)) n;
enumFromThenRatio :: Ratio MyInt -> Ratio MyInt -> (List (Ratio MyInt))
enumFromThenRatio = numericEnumFromThen;
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/enumFromThen_2.hs
|
mit
| 7,404
| 0
| 11
| 1,528
| 3,564
| 1,853
| 1,711
| 177
| 1
|
{-# INCLUDE "benchmark.h" #-}
{-# LANGUAGE ForeignFunctionInterface #-}
module Main where
import Foreign.C -- get the C types
import Criterion.Main
-- "unsafe" means it's slightly faster but can't callback to haskell
foreign import ccall unsafe "benchmark_parseURL" benchmark :: CInt -> CInt
main = defaultMain [
bgroup "parseURL" [bench title $ whnf (benchmark) n]
]
where
n = 1000000
title = "benchmark " ++ (show n)
|
nathanwiegand/urlparser
|
criterion-benchmark.hs
|
mit
| 455
| 0
| 11
| 101
| 92
| 52
| 40
| 9
| 1
|
module Algebra.CAS (
module Algebra.CAS.Base
, module Algebra.CAS.Diff
, module Algebra.CAS.GrobnerBasis
, module Algebra.CAS.Integrate
, module Algebra.CAS.Solve
) where
import Algebra.CAS.Base
import Algebra.CAS.Diff
import Algebra.CAS.GrobnerBasis
import Algebra.CAS.Integrate
import Algebra.CAS.Solve
|
junjihashimoto/th-cas
|
Algebra/CAS.hs
|
mit
| 310
| 0
| 5
| 34
| 73
| 50
| 23
| 11
| 0
|
{-# LANGUAGE OverloadedStrings,
InstanceSigs,
DeriveGeneric,
DeriveAnyClass #-}
module Communication where
import Data.Aeson (ToJSON)
import Data.Text as T
import GHC.Generics (Generic)
import Servant (FromHttpApiData(..))
import Safe (readEitherSafe)
data QueueName = UrlQueue
| StoreQueue
| ErrorQueue
deriving (Generic, Read)
instance FromHttpApiData QueueName where
parseQueryParam :: Text -> Either Text QueueName
parseQueryParam text =
case readEitherSafe (T.unpack text) of
Left _ -> Left $ T.concat ["Unknown queueName: ", text]
Right queueName -> Right queueName
data CrawlerStatus = RunningStatus
| HaltingStatus
| Halted
deriving (Generic, Eq, Show, ToJSON)
|
jahaynes/crawler
|
src/Communication.hs
|
mit
| 917
| 0
| 11
| 332
| 189
| 105
| 84
| 24
| 0
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-retainrule.html
module Stratosphere.ResourceProperties.DLMLifecyclePolicyRetainRule where
import Stratosphere.ResourceImports
-- | Full data type definition for DLMLifecyclePolicyRetainRule. See
-- 'dlmLifecyclePolicyRetainRule' for a more convenient constructor.
data DLMLifecyclePolicyRetainRule =
DLMLifecyclePolicyRetainRule
{ _dLMLifecyclePolicyRetainRuleCount :: Val Integer
} deriving (Show, Eq)
instance ToJSON DLMLifecyclePolicyRetainRule where
toJSON DLMLifecyclePolicyRetainRule{..} =
object $
catMaybes
[ (Just . ("Count",) . toJSON) _dLMLifecyclePolicyRetainRuleCount
]
-- | Constructor for 'DLMLifecyclePolicyRetainRule' containing required fields
-- as arguments.
dlmLifecyclePolicyRetainRule
:: Val Integer -- ^ 'dlmlprrCount'
-> DLMLifecyclePolicyRetainRule
dlmLifecyclePolicyRetainRule countarg =
DLMLifecyclePolicyRetainRule
{ _dLMLifecyclePolicyRetainRuleCount = countarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-retainrule.html#cfn-dlm-lifecyclepolicy-retainrule-count
dlmlprrCount :: Lens' DLMLifecyclePolicyRetainRule (Val Integer)
dlmlprrCount = lens _dLMLifecyclePolicyRetainRuleCount (\s a -> s { _dLMLifecyclePolicyRetainRuleCount = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/DLMLifecyclePolicyRetainRule.hs
|
mit
| 1,499
| 0
| 13
| 164
| 174
| 100
| 74
| 23
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module MinionsApi.Middlewares where
import Network.Wai (Middleware)
import Network.Wai.Middleware.AddHeaders (addHeaders)
import Network.Wai.Middleware.Cors (CorsResourcePolicy(..), cors)
-- | @x-csrf-token@ allowence.
-- The following header will be set: @Access-Control-Allow-Headers: x-csrf-token@.
allowCsrf :: Middleware
allowCsrf = addHeaders [("Access-Control-Allow-Headers", "x-csrf-token")]
-- | CORS middleware configured with 'appCorsResourcePolicy'.
corsified :: Middleware
corsified = cors (const $ Just appCorsResourcePolicy)
-- | Cors resource policy to be used with 'corsified' middleware.
--
-- This policy will set the following:
--
-- * RequestHeaders: @Content-Type@
-- * MethodsAllowed: @OPTIONS, GET, PUT, POST@
appCorsResourcePolicy :: CorsResourcePolicy
appCorsResourcePolicy = CorsResourcePolicy {
corsOrigins = Nothing
, corsMethods = ["OPTIONS", "GET", "PUT", "POST"]
, corsRequestHeaders = ["Content-Type"]
, corsExposedHeaders = Nothing
, corsMaxAge = Nothing
, corsVaryOrigin = False
, corsRequireOrigin = False
, corsIgnoreFailures = False
}
|
dzotokan/minions-api
|
src/lib/MinionsApi/Middlewares.hs
|
mit
| 1,186
| 0
| 8
| 206
| 177
| 115
| 62
| 19
| 1
|
module ChaCha20Poly1305Bench (benchChaCha20Poly1305, chaCha20Poly1305Env) where
import Criterion.Main
import Control.Monad
import Control.DeepSeq
import Control.Exception
import Data.ByteString as BS
import Crypto.Saltine.Core.AEAD.ChaCha20Poly1305 as C
import BenchUtils
chaCha20Poly1305Env :: IO Key
chaCha20Poly1305Env = newKey
benchChaCha20Poly1305 :: Key -> Benchmark
benchChaCha20Poly1305 k = do
let encrypt :: ByteString -> ByteString -> IO ByteString
encrypt msg aad = newNonce >>= \n -> pure $ C.aead k n msg aad
decrypt :: ByteString -> ByteString -> IO (Maybe ByteString)
decrypt msg aad = do
n <- newNonce
let ciphertext = C.aead k n msg aad
return $ C.aeadOpen k n ciphertext aad
encryptDetached msg aad = newNonce >>= \n -> pure $ C.aeadDetached k n msg aad
decryptDetached msg aad = do
n <- newNonce
let (t,c) = C.aeadDetached k n msg aad
pure $ C.aeadOpenDetached k n t c aad
bgroup "ChaCha20Poly1305"
[ bench "newKey" $ nfIO newKey
, bgroup "aead"
[ bench "128 B + 128 B" $ nfIO $ encrypt bs128 bs128
, bench "128 B + 5 MB" $ nfIO $ encrypt bs128 mb5
, bench "1 MB + 128 B" $ nfIO $ encrypt mb1 bs128
, bench "1 MB + 5 B" $ nfIO $ encrypt mb1 mb5
, bench "5 MB + 128 B" $ nfIO $ encrypt mb5 bs128
, bench "5 MB + 5 MB" $ nfIO $ encrypt mb5 mb5
]
, bgroup "aead + open"
[ bench "128 B + 128 B" $ nfIO $ decrypt bs128 bs128
, bench "128 B + 5 MB" $ nfIO $ decrypt bs128 mb5
, bench "1 MB + 128 B" $ nfIO $ decrypt mb1 bs128
, bench "1 MB + 5 B" $ nfIO $ decrypt mb1 mb5
, bench "5 MB + 128 B" $ nfIO $ decrypt mb5 bs128
, bench "5 MB + 5 MB" $ nfIO $ decrypt mb5 mb5
]
, bgroup "aeadDetached"
[ bench "128 B + 128 B" $ nfIO $ encryptDetached bs128 bs128
, bench "128 B + 5 MB" $ nfIO $ encryptDetached bs128 mb5
, bench "1 MB + 128 B" $ nfIO $ encryptDetached mb1 bs128
, bench "1 MB + 5 B" $ nfIO $ encryptDetached mb1 mb5
, bench "5 MB + 128 B" $ nfIO $ encryptDetached mb5 bs128
, bench "5 MB + 5 MB" $ nfIO $ encryptDetached mb5 mb5
]
, bgroup "aeadDetached + openDetached"
[ bench "128 B + 128 B" $ nfIO $ decryptDetached bs128 bs128
, bench "128 B + 5 MB" $ nfIO $ decryptDetached bs128 mb5
, bench "1 MB + 128 B" $ nfIO $ decryptDetached mb1 bs128
, bench "1 MB + 5 B" $ nfIO $ decryptDetached mb1 mb5
, bench "5 MB + 128 B" $ nfIO $ decryptDetached mb5 bs128
, bench "5 MB + 5 MB" $ nfIO $ decryptDetached mb5 mb5
]
]
|
tel/saltine
|
bench/ChaCha20Poly1305Bench.hs
|
mit
| 2,688
| 0
| 16
| 822
| 820
| 401
| 419
| 54
| 1
|
module Hash (runInteractive, runScript) where
import Control.Exception
import Control.Monad
import Data.Maybe
import Language.Exec
import Language.Expressions
import Parsing.HashParser
import Network.BSD
import System.IO
import System.Directory
import System.Environment
executeHashRc :: IO VarTable
executeHashRc = do
homeDir <- getHomeDirectory
exists <- doesFileExist (homeDir ++ "/.hashrc")
if exists
then runScriptWithRet emptyState (homeDir ++ "/.hashrc")
else return emptyState
runInteractive :: IO ()
runInteractive = do
sState <- executeHashRc
mainLoop sState
runScript :: FilePath -> IO ()
runScript script = do
vTable <- executeHashRc
runScriptWithRet vTable script
return ()
runScriptWithRet :: VarTable -> FilePath -> IO VarTable
runScriptWithRet vTable script = do
src <- readFile script
lineByLine (lines src) vTable
lineByLine :: [String] -> VarTable -> IO VarTable
lineByLine [] vTable = return vTable
lineByLine (l:ls) sState = do
let stmt = parseLine (l ++ ";")
nextState <- case stmt of
Left _ -> return sState
Right x -> do
result <- try (execStmt x sState) :: IO (Either SomeException VarTable)
case result of
Left ex -> do
putStrLn $ show ex
return sState
Right res -> return res
lineByLine ls nextState
mainLoop sState = do
wkDir <- getCurrentDirectory
hmDir <- getHomeDirectory
username <- getEnv "USERNAME"
hostname <- getHostName
putStr $ "\027[1;34m" ++ username ++ "@" ++ hostname
putStr $ " \027[1;35m" ++ wkDir ++ " "
putStr "λ \027[0m"
hFlush stdout
line <- getLine
let stmt = parseLine (line ++ ";")
nextState <- case stmt of
Left _ -> return sState
Right x -> do
result <- try (execStmt x sState) :: IO (Either SomeException VarTable)
case result of
Left ex -> do
putStrLn $ show ex
return sState
Right res -> return res
mainLoop nextState
|
tomicm/puh-hash
|
Hash.hs
|
gpl-2.0
| 2,006
| 0
| 19
| 501
| 659
| 308
| 351
| 66
| 3
|
{-# OPTIONS -fallow-overlapping-instances #-}
{- arch-tag: Python interpreter module
Copyright (C) 2005 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 : Python.Interpreter
Copyright : Copyright (C) 2005 John Goerzen
License : GNU GPL, version 2 or above
Maintainer : John Goerzen,
Maintainer : jgoerzen\@complete.org
Stability : provisional
Portability: portable
Interface to Python interpreter
Written by John Goerzen, jgoerzen\@complete.org
-}
module Python.Interpreter (
py_initialize,
-- * Intrepreting Code
pyRun_SimpleString,
pyRun_String,
pyRun_StringHs,
StartFrom(..),
-- * Calling Code
callByName,
callByNameHs,
noParms,
noKwParms,
-- * Imports
pyImport,
pyImport_ImportModule,
pyImport_AddModule,
pyModule_GetDict,
)
where
import Python.Utils
import Python.Objects
import Python.Types
import Python.ForeignImports
import Foreign
import Foreign.C.String
import Foreign.C
import System.IO.Unsafe
{- | Initialize the Python interpreter environment.
MUST BE DONE BEFORE DOING ANYTHING ELSE! -}
py_initialize :: IO ()
py_initialize = do cpy_initialize
pyImport "traceback"
pyRun_SimpleString :: String -> IO ()
pyRun_SimpleString x = withCString x (\cs ->
do cpyRun_SimpleString cs >>= checkCInt
return ()
)
-- | Like 'pyRun_String', but take more Haskellish args and results.
pyRun_StringHs :: (ToPyObject b, FromPyObject c) =>
String -- ^ Command to run
-> StartFrom -- ^ Start token
-- -> [(String, a)] -- ^ Globals (may be empty)
-> [(String, b)] -- ^ Locals (may be empty)
-> IO c
pyRun_StringHs cmd start locals =
let conv (k, v) = do v1 <- toPyObject v
return (k, v1)
in do
--rglobals <- mapM conv globals
rlocals <- mapM conv locals
pyRun_String cmd start rlocals >>= fromPyObject
-- | Run some code in Python.
pyRun_String :: String -- ^ Command to run
-> StartFrom -- ^ Start Token
-- -> [(String, PyObject)] -- ^ Globals (may be empty)
-> [(String, PyObject)] -- ^ Locals (may be empty)
-> IO PyObject -- ^ Result
pyRun_String command startfrom xlocals =
let cstart = sf2c startfrom
in do dobj <- getDefaultGlobals
rlocals <- toPyObject xlocals
withCString command (\ccommand ->
withPyObject dobj (\cglobals ->
withPyObject rlocals (\clocals ->
cpyRun_String ccommand cstart cglobals clocals >>= fromCPyObject
)))
{- | Call a function or callable object by name. -}
callByName :: String -- ^ Object\/function name
-> [PyObject] -- ^ List of non-keyword parameters
-> [(String, PyObject)] -- ^ List of keyword parameters
-> IO PyObject
callByName fname sparms kwparms =
do func <- pyRun_String fname Py_eval_input []
pyObject_Call func sparms kwparms
{- | Call a function or callable object by namem using Haskell args
and return values..
You can use 'noParms' and 'noKwParms' if you have no simple or
keyword parameters to pass, respectively. -}
callByNameHs :: (ToPyObject a, ToPyObject b, FromPyObject c) =>
String -- ^ Object\/function name
-> [a] -- ^ List of non-keyword parameters
-> [(String, b)] -- ^ List of keyword parameters
-> IO c
callByNameHs fname sparms kwparms =
do func <- pyRun_String fname Py_eval_input []
pyObject_CallHs func sparms kwparms
{- | Import a module into the current environment in the normal sense
(similar to \"import\" in Python).
-}
pyImport :: String -> IO ()
pyImport x =
do pyImport_ImportModule x
globals <- getDefaultGlobals
cdict <- pyImport_GetModuleDict
py_incref cdict
pyo2 <- fromCPyObject cdict
dict <- fromPyObject pyo2
case lookup x dict of
Nothing -> return ()
Just pyo -> do withPyObject globals (\cglobals ->
withPyObject pyo (\cmodule ->
withCString x (\cstr ->
pyDict_SetItemString cglobals cstr cmodule >>= checkCInt)))
return ()
{- | Wrapper around C PyImport_ImportModule, which imports a module.
You may want the higher-level 'pyImport' instead. -}
pyImport_ImportModule :: String -> IO PyObject
pyImport_ImportModule x =
do globals <- getDefaultGlobals
fromlist <- toPyObject ['*']
cr <- withPyObject globals (\cglobals ->
withPyObject fromlist (\cfromlist ->
withCString x (\cstr ->
cpyImport_ImportModuleEx cstr cglobals cglobals cfromlist)))
fromCPyObject cr
|
jgoerzen/missingpy
|
Python/Interpreter.hs
|
gpl-2.0
| 6,107
| 0
| 22
| 2,101
| 872
| 452
| 420
| 92
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Lamdu.Builtins.Anchors where
import Lamdu.Expr.Type (Tag)
import qualified Lamdu.Expr.Type as T
import qualified Lamdu.Expr.Val as V
recurseVar :: V.Var
recurseVar = "RECURSE"
objTag :: Tag
objTag = "BI:object"
infixlTag :: Tag
infixlTag = "BI:infixl"
infixrTag :: Tag
infixrTag = "BI:infixr"
listTid :: T.Id
listTid = "BI:list"
headTag :: Tag
headTag = "BI:head"
tailTag :: Tag
tailTag = "BI:tail"
consTag :: Tag
consTag = "BI:cons"
nilTag :: Tag
nilTag = "BI:nil"
trueTag :: Tag
trueTag = "BI:true"
falseTag :: Tag
falseTag = "BI:false"
justTag :: Tag
justTag = "BI:just"
nothingTag :: Tag
nothingTag = "BI:nothing"
infiniteStreamTag :: Tag
infiniteStreamTag = "BI:just"
type Order = Int
anchorTags :: [(Order, Tag, String)]
anchorTags =
[ (0, objTag, "object")
, (0, infixlTag, "infixl")
, (1, infixrTag, "infixr")
, (0, headTag, "head")
, (1, tailTag, "tail")
, (0, nilTag, "Empty")
, (1, consTag, "NonEmpty")
, (0, trueTag, "True")
, (1, falseTag, "False")
, (0, nothingTag, "Nothing")
, (1, justTag, "Just")
]
|
rvion/lamdu
|
Lamdu/Builtins/Anchors.hs
|
gpl-3.0
| 1,133
| 0
| 6
| 235
| 341
| 219
| 122
| 47
| 1
|
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Monad (forever)
import Control.Concurrent.Async
import Control.Monad.IO.Class (liftIO)
import qualified Data.List as L
import Data.Traversable
import qualified Data.Vector as V
import Options.Applicative
import GHC.Word
import Control.Concurrent.STM
import System.Arte.Decode.Types
import Data.Ephys.EphysDefs
import Network.Socket
import qualified Data.Map as Map
import Pipes
import Pipes.RealTime
import Data.Ephys.Position
import Data.Ephys.TrackPosition
import System.Arte.Net (udpSocketProducer)
import System.Arte.Decode.Config (pos0, field0)
import System.Arte.Decode.Algorithm (normalize)
data Opts = Opts {
estPort :: Word16
, posPort :: Word16
, rTau :: Double
} deriving (Eq, Show)
optStruct :: Parser Opts
optStruct = Opts
<$> option auto
(long "estPort"
<> short 'e'
<> help "Port to listen for position estimates")
<*> option auto
(long "posPort"
<> short 'p'
<> help "Port to listen for rat position")
<*> option auto
(long "rTau"
<> short 'r'
<> help "Decoding interval rTau (seconds)")
masterOpts = info (helper <*> optStruct)
(fullDesc
<> progDesc "Decoder matser"
<> header "master-decoder")
------------------------------------------------------------------------------
main :: IO ()
main = do
masterState <- newMasterState
opts <- execParser masterOpts
print opts
(estSock,posSock) <- setupSockets opts
posThread <- async . runEffect $ udpSocketProducer 9000 posSock >->
(forever $ await >>= \p -> liftIO $
atomically $ writeTVar (ratPos masterState) p)
slavesThread <- async . runEffect $ udpSocketProducer 9090 estSock >->
(forever $ await >>= \est -> liftIO (acceptEstimate masterState est))
combineThread <- async . runEffect $ forever (yield ())
>-> steadyCat 100
>-> forever (await >> liftIO (updateMasterEstimate masterState))
let runMasterGui = undefined
runMasterGui undefined
data MasterState = MasterState {
tetrodeEstimate :: TVar (Map.Map TrodeName Field)
, ratPos :: TVar Position
, masterEstimate :: TVar Field
}
type Estimate = Int
acceptEstimate :: MasterState -> Estimate -> IO ()
acceptEstimate = undefined
-- TODO: ? Profile and decide: switch to Rational (infinite precision)
updateMasterEstimate :: MasterState -> IO ()
updateMasterEstimate MasterState{..} = do
fields <- Map.elems <$> readTVarIO tetrodeEstimate
let fieldLogs = V.map log <$> fields
logSums = V.map (L.foldl' (+) 0) (sequenceA fieldLogs)
fieldPDF = normalize (V.map exp logSums)
atomically . writeTVar masterEstimate $ fieldPDF
setupSockets :: Opts -> IO (Socket,Socket)
setupSockets Opts{..} = do
estSock <- socket AF_INET Datagram defaultProtocol
bind estSock $ SockAddrInet (fromIntegral estPort) iNADDR_ANY
posSock <- socket AF_INET Datagram defaultProtocol
bind posSock $ SockAddrInet (fromIntegral posPort) iNADDR_ANY
return (estSock,posSock)
newMasterState :: IO MasterState
newMasterState = do
ests <- newTVarIO Map.empty
p <- newTVarIO pos0
est0 <- newTVarIO field0
return $ MasterState ests p est0
|
imalsogreg/arte-ephys
|
arte-decoder/exec/MasterDecoder.hs
|
gpl-3.0
| 3,272
| 0
| 15
| 680
| 935
| 482
| 453
| 88
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.