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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module Physics.Integrator
( Integrator(..)
, runIntegratorPos
, euler
, verlet
) where
import Control.Wire
import FRP.Netwire
import Linear.Vector
import Prelude hiding ((.), id)
-- | Integrator newtype, wrapping around integrator functions. Integrator
-- functions in general take an acceleration vector and return a position
-- vector and velocity vector integrated from the given initial position
-- and velocity.
--
newtype Integrator =
Integrator { runIntegrator :: forall v t e a m s.
(Monad m, Monoid e, HasTime t s, Additive v, Fractional (v a), Fractional a)
=> v a -- Initial position
-> v a -- Initial velocity
-> Wire s e m (v a) (v a, v a)
}
runIntegratorPos ::
(Monad m, Monoid e, HasTime t s, Additive v, Fractional (v a), Fractional a)
=> Integrator
-> v a
-> v a
-> Wire s e m (v a) (v a)
runIntegratorPos igr x0 v0 = fst <$> runIntegrator igr x0 v0
-- | Euler integrator
--
euler :: Integrator
euler = Integrator $
\x0 v0 -> proc acc -> do
vel <- integral v0 -< acc
pos <- integral x0 -< vel
returnA -< (pos, vel)
-- | Verlet integrator
--
verlet :: Integrator
verlet = Integrator vVel
where
vVel x0 v0 = snd <$> vInt
where
vInt = mkSF wpure
wpure ds _ = (tup, loop' ds tup)
where
tup = (x0 ^-^ (v0 ^* dt), (x0, v0))
dt = realToFrac $ dtime ds
loop' ds1 (x1, (x2, _)) = mkSF $ \ds2 a ->
let dt1 = realToFrac $ dtime ds1
dt2 = realToFrac $ dtime ds2
dtr = dt2 / dt1
x3 = (x2 ^+^ (x2 ^-^ x1) ^* dtr) ^+^ (a ^* (dt2 * dt2))
v = x3 ^-^ x2
tup' = (x2, (x3, v))
in (tup', loop' ds1 tup')
-- -- | Runge-Kutta (RK4) integrator
-- --
-- rk4 :: Integrator
-- rk4 = undefined
|
mstksg/netwire-experiments
|
src/Physics/Integrator.hs
|
gpl-3.0
| 1,886
| 1
| 20
| 617
| 618
| 340
| 278
| -1
| -1
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module Types where
import Data.Bits(shiftL, shiftR, (.&.), (.|.))
import Data.List(intercalate, transpose, foldl', unfoldr)
import Control.Applicative((<$>), (<*))
import Text.ParserCombinators.Parsec(GenParser, (<|>), many, many1, oneOf, newline, digit, eof, char, (<?>))
-- The following are the basic datatypes for the grid
data Cell = U | O | X deriving Eq
type Row = [Cell]
type Grid = [Row]
-- Show instances for our basic types
instance {-# OVERLAPPING #-} Show Cell where
show c =
case c of
O -> "O"
X -> "X"
U -> "_"
instance {-# OVERLAPPING #-} Show Row where
show = concatMap show
instance {-# OVERLAPPING #-} Show Grid where
show = intercalate "\n" . map show
-- Parser for the grid
parseCell :: GenParser Char st Cell
parseCell =
(oneOf "xX" >> return X)
<|> (oneOf "oO" >> return O)
<|> (char '_' >> return U)
<?> "x, X, o, O, _"
parseRow :: GenParser Char st Row
parseRow =
concat <$> many ((:[]) <$> parseCell <|> flip replicate U . read <$> many1 digit) <* newline
parseGrid :: GenParser Char st Grid
parseGrid = do
r1 <- parseRow
(r1:) <$> many (do r <- parseRow; return $ r ++ replicate (length r1 - length r) U) <* eof
-- For efficiency, we use a binary representation of the grid when solving.
-- The QRow contains two bit sets: the first is the X/O pattern, the second is the unknown mask.
data QRow = QRow {xbits :: Int, umask :: Int}
data QGrid = QGrid {rowlen :: Int, qrows :: [QRow]}
rowToQRow :: Row -> QRow
rowToQRow =
foldl' r2qr (QRow 0 0)
where
r2qr (QRow xbits umask) x =
let xbits' = xbits `shiftL` 1
umask' = umask `shiftL` 1
in case x of
U -> QRow xbits' umask'
O -> QRow xbits' (umask' .|. 1)
X -> QRow (xbits' .|. 1) (umask' .|. 1)
gridToQGrid :: Grid -> QGrid
gridToQGrid g =
case g of
[] -> QGrid 0 []
r:_ -> QGrid (length r) (map rowToQRow g)
qRowToRow :: Int -> QRow -> Row
qRowToRow len (QRow xbits umask) =
unfoldr qr2r (1 `shiftL` (len-1))
where
qr2r n =
case n of
0 -> Nothing
_ -> let n' = (n `shiftR` 1)
in case umask .&. n of
0 -> Just (U, n')
_ -> case xbits .&. n of
0 -> Just (O, n')
_ -> Just (X, n')
qGridToGrid :: QGrid -> Grid
qGridToGrid (QGrid len g) =
map (qRowToRow len) g
transposeQGrid :: QGrid -> QGrid
transposeQGrid =
gridToQGrid . transpose . qGridToGrid
|
peteryland/binoxxo
|
src/Types.hs
|
gpl-3.0
| 2,520
| 0
| 19
| 671
| 902
| 491
| 411
| -1
| -1
|
{-#LANGUAGE DeriveGeneric #-}
module Handler.Review (getReviewR, putReviewR, deleteReviewR) where
import Import
import Util.Data
import Util.Database
import Data.Map as M (fromList)
import Data.Tree
import Data.List (nub)
import Filter.Util (sanatizeHtml)
import Text.Read (readMaybe)
import Yesod.Form.Bootstrap3
import Carnap.Languages.PurePropositional.Syntax
import Carnap.Languages.PureFirstOrder.Syntax
import Carnap.Languages.PurePropositional.Logic (ofPropSys)
import Carnap.Languages.PureFirstOrder.Logic (ofFOLSys)
import Carnap.Calculi.NaturalDeduction.Syntax (NaturalDeductionCalc(..))
import Carnap.GHCJS.SharedTypes
import Carnap.GHCJS.SharedFunctions (simpleCipher,simpleHash)
deleteReviewR :: Text -> Text -> Handler Value
deleteReviewR coursetitle filename = do
msg <- requireJsonBody :: Handler ReviewDelete
case msg of
DeleteProblem key -> do
runDB $ delete key
returnJson ("Problem deleted." :: Text)
putReviewR :: Text -> Text -> Handler Value
putReviewR coursetitle filename =
do (Entity key val, _) <- getAssignmentByCourse coursetitle filename
((theUpdate,_),_) <- runFormPost (identifyForm "updateSubmission" $ updateSubmissionForm Nothing "" "")
case theUpdate of
FormSuccess (ident, serializeduid, extra) -> do
success <- runDB $ do case readMaybe serializeduid of
Just uid -> do msub <- getBy (UniqueProblemSubmission ident uid (Assignment (show key)))
case msub of
Just (Entity k _) -> update k [ProblemSubmissionExtra =. Just extra] >> return True
Nothing -> return False
Nothing -> return False
if success then returnJson ("success" :: Text) else returnJson ("error: no submission record" :: Text)
FormMissing -> returnJson ("no form" :: Text)
(FormFailure s) -> returnJson ("error:" <> concat s :: Text)
getReviewR :: Text -> Text -> Handler Html
getReviewR coursetitle filename =
do (Entity key val, _) <- getAssignmentByCourse coursetitle filename
unsortedProblems <- runDB $ selectList [ProblemSubmissionAssignmentId ==. Just key] []
(uidAndData, uidAndUser) <- runDB $ do
let uids = nub $ map (problemSubmissionUserId . entityVal) unsortedProblems
muserdata <- mapM (getBy . UniqueUserData) uids
musers <- mapM get uids
return (sortBy maybeLnSort $ zip muserdata uids, zip uids musers)
let problems = sortBy theSorting unsortedProblems
defaultLayout $ do
addScript $ StaticR js_popper_min_js
addScript $ StaticR js_proof_js
addScript $ StaticR ghcjs_rts_js
addScript $ StaticR ghcjs_allactions_lib_js
addScript $ StaticR ghcjs_allactions_out_js
addStylesheet $ StaticR css_proof_css
addStylesheet $ StaticR css_exercises_css
$(widgetFile "review")
addScript $ StaticR ghcjs_allactions_runmain_js
where maybeLnSort (Nothing,_) (Nothing,_) = EQ
maybeLnSort (Nothing,_) _ = LT
maybeLnSort _ (Nothing,_) = GT
maybeLnSort (Just ud,_) (Just ud',_) = compare (userDataLastName $ entityVal ud)
(userDataLastName $ entityVal ud')
theSorting p p' = scompare s s'
where s = unpack . problemSubmissionIdent . entityVal $ p
s' = unpack . problemSubmissionIdent . entityVal $ p'
scompare a a' = case (break (== '.') a, break (== '.') a') of
((h,[]),(h',[])) | compare (length h) (length h') /= EQ -> compare (length h) (length h')
| compare h h' /= EQ -> compare h h'
| otherwise -> EQ
((h,t), (h',t')) | compare (length h) (length h') /= EQ -> compare (length h) (length h')
| compare h h' /= EQ -> compare h h'
| otherwise -> scompare (drop 1 t) (drop 1 t')
selectUser list =
[whamlet|
<select#selectStudent class="form-control">
<option value="all">All Students
$forall (k,v) <- list
$maybe k' <- k
<option value="#{show v}">
#{userDataLastName (entityVal k')}, #
#{userDataFirstName (entityVal k')}
$nothing
<option value="#{show v}">unknown
|]
renderProblem uidanduser (Entity key val) = do
let ident = problemSubmissionIdent val
uid = problemSubmissionUserId val
extra = problemSubmissionExtra val
correct = problemSubmissionCorrect val
Just user = lookup uid uidanduser
(updateSubmissionWidget,enctypeUpdateSubmission) <- generateFormPost (identifyForm "updateSubmission" $ updateSubmissionForm extra ident (show uid))
let isGraded = if correct then "graded"
else case extra of Just _ -> "graded"; _ -> "ungraded" :: String
howGraded = if correct then "automatically graded"
else case extra of Just _ -> "manually graded"; _ -> "ungraded" :: String
credit = case problemSubmissionCredit val of Just n -> n; _ -> 5
score = if correct then credit else 0
awarded = case extra of Just n -> show n; _ -> "0" :: String
mailto theuser = sanatizeHtml (userIdent theuser) ++ "?subject=[Carnap-" ++ sanatizeHtml ident ++ "]"
template display =
[whamlet|
<div.card.mb-3.#{isGraded} data-submission-uid="#{show uid}">
<div.card-body style="padding:20px">
<div.d-flex.flex-wrap-reverse>
<div.col-sm-8>
<h4.card-title>#{ident}
<div style="overflow-x:scroll">
^{display}
<div.col-sm-4>
<h6.review-status>#{howGraded}
<h6.point-value>point value: #{credit}
<h6.points-score>submission score: #{score}
<h6.points-awarded>points added: #{awarded}
<hr>
<form.updateSubmission enctype=#{enctypeUpdateSubmission}>
^{updateSubmissionWidget}
<div.form-group>
<input.btn.btn-primary type=submit value="update" disabled>
<hr>
$maybe user' <- user
<a href="mailto:#{mailto user'}">
<i.fa.fa-envelope-o>
email student
<br>
<a href="#" onclick="tryDeleteProblem(event,'#{jsonSerialize $ DeleteProblem key}')">
<i.fa.fa-trash-o>
delete problem
|]
case (problemSubmissionType val, problemSubmissionData val) of
(Derivation, DerivationData goal der) -> template
[whamlet|
<div data-carnap-system="prop"
data-carnap-options="resize"
data-carnap-type="proofchecker"
data-carnap-goal="#{goal}"
data-carnap-submission="none">
#{der}
|]
(Derivation, DerivationDataOpts goal der opts) -> template
[whamlet|
<div data-carnap-type="proofchecker"
data-carnap-system="#{sys}"
data-carnap-options="resize"
data-carnap-goal="#{goal}"
data-carnap-submission="none">
#{der}
|]
where sys = case lookup "system" (M.fromList opts) of Just s -> s; Nothing -> "prop"
(TruthTable, TruthTableData goal tt) -> template
[whamlet|
<div data-carnap-type="truthtable"
data-carnap-tabletype="#{checkvalidity goal}"
data-carnap-submission="none"
data-carnap-goal="#{goal}">
#{renderTT tt}
|]
(TruthTable, TruthTableDataOpts goal tt opts) -> template
[whamlet|
<div data-carnap-type="truthtable"
data-carnap-tabletype="#{tabletype}"
data-carnap-system="#{ttsystem}"
data-carnap-submission="none"
data-carnap-options="immutable nocheck nocounterexample"
data-carnap-goal="#{formatContent (unpack goal)}">
#{renderTT tt}
|]
where tabletype = case lookup "tabletype" (M.fromList opts) of Just s -> s; Nothing -> checkvalidity goal
ttsystem = case lookup "system" (M.fromList opts) of Just s -> s; Nothing -> "prop"
formatContent c = case (ndNotation `ofPropSys` ttsystem) <*> maybeString of Just s -> s; Nothing -> ""
where maybeString = (show <$> (readMaybe c :: Maybe PureForm))
`mplus` (intercalate "," . map show <$> (readMaybe c :: Maybe [PureForm]))
`mplus` case readMaybe c :: Maybe ([PureForm],[PureForm]) of
Just (fs,gs) -> Just $ intercalate "," (map show fs) ++ ":" ++ intercalate "," (map show gs)
Nothing -> Just c --If it's a sequent, it'll show properly anyway.
(CounterModel, CounterModelDataOpts goal cm opts) -> template
[whamlet|
<div data-carnap-type="countermodeler"
data-carnap-countermodelertype="#{cmtype}"
data-carnap-submission="none"
data-carnap-system="#{cmsystem}"
data-carnap-goal="#{formatContent (unpack goal)}">
#{renderCM cm}
|]
where cmtype = case lookup "countermodelertype" (M.fromList opts) of Just s -> s; Nothing -> checkvalidity goal
cmsystem = case lookup "system" (M.fromList opts) of Just s -> s; Nothing -> "firstOrder"
formatContent c = case (ndNotation `ofFOLSys` cmsystem) <*> maybeString of Just s -> s; Nothing -> ""
where maybeString = (show <$> (readMaybe c :: Maybe PureForm))
`mplus` (intercalate "," . map show <$> (readMaybe c :: Maybe [PureFOLForm]))
`mplus` Just c --If it's a sequent, it'll show properly anyway.
(Translation, TranslationData goal trans) -> template
[whamlet|
<div data-carnap-type="translate"
data-carnap-transtype="prop"
data-carnap-goal="#{show (simpleCipher (unpack goal))}"
data-carnap-submission="none"
data-carnap-problem="#{goal}">
#{trans}
|]
(Translation, TranslationDataOpts goal trans opts) -> template
[whamlet|
<div data-carnap-type="translate"
data-carnap-transtype="#{transtype}"
data-carnap-system="#{sys}"
$nothing
data-carnap-goal="#{show (simpleCipher (unpack goal))}"
data-carnap-submission="none"
data-carnap-problem="#{problem}">
#{trans}
|]
where transtype = case lookup "transtype" (M.fromList opts) of Just s -> s; Nothing -> "prop"
problem = case lookup "problem" (M.fromList opts) of Just s -> s ++ " : " ++ (unpack goal)
sys = case lookup "system" (M.fromList opts) of
Just s -> s;
Nothing -> if transtype == "prop" then "prop" else "firstOrder"
(SequentCalc, SequentCalcData goal tree opts) -> template
[whamlet|
<div data-carnap-type="sequentchecker"
data-carnap-system="#{sys}"
data-carnap-options="resize"
data-carnap-goal="#{goal}"
data-carnap-submission="none">
#{treeJSON tree}
|]
where sys = case lookup "system" (M.fromList opts) of Just s -> s; Nothing -> "propLK"
(DeductionTree, DeductionTreeData goal tree opts) -> template
[whamlet|
<div data-carnap-type="treedeductionchecker"
data-carnap-system="#{sys}"
data-carnap-options="resize"
data-carnap-goal="#{goal}"
data-carnap-submission="none">
#{treeJSON tree}
|]
where sys = case lookup "system" (M.fromList opts) of Just s -> s; Nothing -> "propNK"
(Qualitative, QualitativeProblemDataOpts goal answer opts) -> template
[whamlet|
<div data-carnap-type="qualitative"
data-carnap-qualitativetype="#{qualtype}"
data-carnap-goal="#{unpack goal}"
data-carnap-submission="none">
#{content}
|]
where qualtype = case lookup "qualitativetype" (M.fromList opts) of Just s -> s; Nothing -> "shortanswer"
content = case qualtype of
"shortanswer" -> unpack answer
"multiplechoice" -> withChecked
withChecked = case lookup "content" (M.fromList opts) of
Nothing -> "Error no content"
Just cnt -> unlines . map processEntry . lines . unpack $ cnt
processEntry l = case readMaybe l :: Maybe (Int, String) of
Just (h,s) | s == unpack answer -> show (simpleHash ('-':s), s)
Just (h,s) | h == simpleHash ('-':s) -> show (simpleHash s, s)
Just (h,s) | h == simpleHash ('+':s) -> show (simpleHash ('*':s), s)
Just (h,s) -> show (h, s)
Nothing -> "indeciperable entry"
(Qualitative, QualitativeNumericalData problem answer opts) -> template
[whamlet|
<div data-carnap-type="qualitative"
data-carnap-qualitativetype="#{qualtype}"
data-carnap-problem="#{unpack problem}"
data-carnap-goal="#{goal}"
data-carnap-submission="none">
#{show answer}
|]
where qualtype = case lookup "qualitativetype" (M.fromList opts) of Just s -> s; Nothing -> "shortanswer"
goal = case lookup "goal" (M.fromList opts) of Just s -> s; Nothing -> "no goal?"
(_, ProblemContent txt) -> template
[whamlet|
<div>
<p>Submission: #{txt}
<p>Autograded, no data for review
|]
_ -> return ()
where renderTT tt = concat $ map renderRow tt
renderRow row = map toval row ++ "\n"
toval (Just True) = 'T'
toval (Just False) = 'F'
toval Nothing = '-'
checkvalidity ct = if '⊢' `elem` ct then "validity" :: String else "simple" :: String
renderCMPair (l,v) = l ++ ":" ++ v
renderCM cm = unlines . map renderCMPair $ cm
treeJSON (Node (l,r) f) = "{\"label\":\"" ++ l
++ "\",\"rule\":\"" ++ r
++ "\",\"forest\":[" ++ concatMap treeJSON f
++ "]}"
updateSubmissionForm extra ident uid = renderBootstrap3 BootstrapBasicForm $ (,,)
<$> areq hiddenField "" (Just ident)
<*> areq hiddenField "" (Just uid)
<*> areq scoreField scoreInput {fsAttrs = ("autocomplete","off") : fsAttrs scoreInput}
(maybe (Just 0) Just extra)
where scoreField = check validateScore intField
validateScore s | s < 0 = Left ("Added credit must be a positive number." :: Text)
| otherwise = Right s
scoreInput = bfs ("Partial Credit Points"::Text)
data ReviewDelete = DeleteProblem ProblemSubmissionId
deriving Generic
instance ToJSON ReviewDelete
instance FromJSON ReviewDelete
|
gleachkr/Carnap
|
Carnap-Server/Handler/Review.hs
|
gpl-3.0
| 18,362
| 0
| 28
| 7,838
| 3,424
| 1,760
| 1,664
| -1
| -1
|
-- Try to eventually arrive at a solution that uses foldr, even if
-- earlier versions don’t use foldr.
lefts' :: [Either a b] -> [a]
lefts' ls = foldr f [] ls
where f k acc = case k of
(Left l) -> l:acc
_ -> acc
rights' :: [Either a b] -> [b]
rights' ls = foldr f [] ls
where f k acc = case k of
(Right r) -> r:acc
_ -> acc
partitionEithers' :: [Either a b] -> ([a], [b])
partitionEithers' ls = (lefts' ls, rights' ls)
eitherMaybe' :: (b -> c) -> Either a b -> Maybe c
eitherMaybe' f (Right r) = Just $ f r
eitherMaybe' _ _ = Nothing
-- This is a general catamorphism for Either values.
either' :: (a -> c) -> (b -> c) -> Either a b -> c
either' f _ (Left l) = f l
either' _ f (Right r) = f r
-- Same as before, but use the either' function you just wrote.
eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c
eitherMaybe'' f k = Just $ either' undefined f k
|
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
|
Signaling_Adversity/EitherLib.hs
|
gpl-3.0
| 1,020
| 0
| 11
| 352
| 392
| 200
| 192
| 20
| 2
|
module HEP.Automation.MadGraph.Dataset.Set20110704set2 where
import HEP.Storage.WebDAV.Type
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.SM
import HEP.Automation.MadGraph.Dataset.Processes
import HEP.Automation.JobQueue.JobType
import qualified Data.ByteString as B
psetup_sm_eebardijet :: ProcessSetup SM
psetup_sm_eebardijet = PS {
mversion = MadGraph5
, model = SM
, process = preDefProcess EEDijet
, processBrief = "EEDijet"
, workname = "704SM_EEDijet"
}
psetuplist :: [ProcessSetup SM]
psetuplist = [ psetup_sm_eebardijet ]
sets :: [Int]
sets = [1..10]
eventsets :: [EventSet]
eventsets =
[ EventSet (psetup_sm_eebardijet)
(RS { param = SMParam
, numevent = 10000
, machine = Parton energy ATLAS
, rgrun = Fixed
, rgscale = 200.0
, match = NoMatch
, cut = DefCut
, pythia = RunPYTHIA
, usercut = NoUserCutDef
, pgs = RunPGS
, jetalgo = AntiKTJet 0.4
, uploadhep = NoUploadHEP
, setnum = num
})
| energy <- [ 100,200..1500], num <- sets ]
webdavdir :: WebDAVRemoteDir
webdavdir = WebDAVRemoteDir "paper3/jetenergy"
|
wavewave/madgraph-auto-dataset
|
src/HEP/Automation/MadGraph/Dataset/Set20110704set2.hs
|
gpl-3.0
| 1,461
| 0
| 10
| 442
| 312
| 198
| 114
| 40
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Glacier.ListJobs
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation lists jobs for a vault, including jobs that are in-progress
-- and jobs that have recently finished.
--
-- Amazon Glacier retains recently completed jobs for a period before deleting
-- them; however, it eventually removes completed jobs. The output of completed
-- jobs can be retrieved. Retaining completed jobs for a period of time after
-- they have completed enables you to get a job output in the event you miss the
-- job completion notification or your first attempt to download it fails. For
-- example, suppose you start an archive retrieval job to download an archive.
-- After the job completes, you start to download the archive but encounter a
-- network error. In this scenario, you can retry and download the archive while
-- the job exists.
--
-- To retrieve an archive or retrieve a vault inventory from Amazon Glacier,
-- you first initiate a job, and after the job completes, you download the data.
-- For an archive retrieval, the output is the archive data, and for an
-- inventory retrieval, it is the inventory list. The List Job operation returns
-- a list of these jobs sorted by job initiation time.
--
-- This List Jobs operation supports pagination. By default, this operation
-- returns up to 1,000 jobs in the response. You should always check the
-- response for a 'marker' at which to continue the list; if there are no more
-- items the 'marker' is 'null'. To return a list of jobs that begins at a specific
-- job, set the 'marker' request parameter to the value you obtained from a
-- previous List Jobs request. You can also limit the number of jobs returned in
-- the response by specifying the 'limit' parameter in the request.
--
-- Additionally, you can filter the jobs list returned by specifying an
-- optional 'statuscode' (InProgress, Succeeded, or Failed) and 'completed' (true,
-- false) parameter. The 'statuscode' allows you to specify that only jobs that
-- match a specified status are returned. The 'completed' parameter allows you to
-- specify that only jobs in a specific completion state are returned.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don't have any
-- permissions by default. You must grant them explicit permission to perform
-- specific actions. For more information, see <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identityand Access Management (IAM)>.
--
-- For the underlying REST API, go to <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-jobs-get.html List Jobs >
--
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-ListJobs.html>
module Network.AWS.Glacier.ListJobs
(
-- * Request
ListJobs
-- ** Request constructor
, listJobs
-- ** Request lenses
, ljAccountId
, ljCompleted
, ljLimit
, ljMarker
, ljStatuscode
, ljVaultName
-- * Response
, ListJobsResponse
-- ** Response constructor
, listJobsResponse
-- ** Response lenses
, ljrJobList
, ljrMarker
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.RestJSON
import Network.AWS.Glacier.Types
import qualified GHC.Exts
data ListJobs = ListJobs
{ _ljAccountId :: Text
, _ljCompleted :: Maybe Text
, _ljLimit :: Maybe Text
, _ljMarker :: Maybe Text
, _ljStatuscode :: Maybe Text
, _ljVaultName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListJobs' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ljAccountId' @::@ 'Text'
--
-- * 'ljCompleted' @::@ 'Maybe' 'Text'
--
-- * 'ljLimit' @::@ 'Maybe' 'Text'
--
-- * 'ljMarker' @::@ 'Maybe' 'Text'
--
-- * 'ljStatuscode' @::@ 'Maybe' 'Text'
--
-- * 'ljVaultName' @::@ 'Text'
--
listJobs :: Text -- ^ 'ljAccountId'
-> Text -- ^ 'ljVaultName'
-> ListJobs
listJobs p1 p2 = ListJobs
{ _ljAccountId = p1
, _ljVaultName = p2
, _ljLimit = Nothing
, _ljMarker = Nothing
, _ljStatuscode = Nothing
, _ljCompleted = Nothing
}
-- | The 'AccountId' value is the AWS account ID of the account that owns the vault.
-- You can either specify an AWS account ID or optionally a single apos'-'apos
-- (hyphen), in which case Amazon Glacier uses the AWS account ID associated
-- with the credentials used to sign the request. If you use an account ID, do
-- not include any hyphens (apos-apos) in the ID.
ljAccountId :: Lens' ListJobs Text
ljAccountId = lens _ljAccountId (\s a -> s { _ljAccountId = a })
-- | Specifies the state of the jobs to return. You can specify 'true' or 'false'.
ljCompleted :: Lens' ListJobs (Maybe Text)
ljCompleted = lens _ljCompleted (\s a -> s { _ljCompleted = a })
-- | Specifies that the response be limited to the specified number of items or
-- fewer. If not specified, the List Jobs operation returns up to 1,000 jobs.
ljLimit :: Lens' ListJobs (Maybe Text)
ljLimit = lens _ljLimit (\s a -> s { _ljLimit = a })
-- | An opaque string used for pagination. This value specifies the job at which
-- the listing of jobs should begin. Get the marker value from a previous List
-- Jobs response. You need only include the marker if you are continuing the
-- pagination of results started in a previous List Jobs request.
ljMarker :: Lens' ListJobs (Maybe Text)
ljMarker = lens _ljMarker (\s a -> s { _ljMarker = a })
-- | Specifies the type of job status to return. You can specify the following
-- values: "InProgress", "Succeeded", or "Failed".
ljStatuscode :: Lens' ListJobs (Maybe Text)
ljStatuscode = lens _ljStatuscode (\s a -> s { _ljStatuscode = a })
-- | The name of the vault.
ljVaultName :: Lens' ListJobs Text
ljVaultName = lens _ljVaultName (\s a -> s { _ljVaultName = a })
data ListJobsResponse = ListJobsResponse
{ _ljrJobList :: List "JobList" GlacierJobDescription
, _ljrMarker :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'ListJobsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ljrJobList' @::@ ['GlacierJobDescription']
--
-- * 'ljrMarker' @::@ 'Maybe' 'Text'
--
listJobsResponse :: ListJobsResponse
listJobsResponse = ListJobsResponse
{ _ljrJobList = mempty
, _ljrMarker = Nothing
}
-- | A list of job objects. Each job object contains metadata describing the job.
ljrJobList :: Lens' ListJobsResponse [GlacierJobDescription]
ljrJobList = lens _ljrJobList (\s a -> s { _ljrJobList = a }) . _List
-- | An opaque string that represents where to continue pagination of the results.
-- You use this value in a new List Jobs request to obtain more jobs in the
-- list. If there are no more jobs, this value is 'null'.
ljrMarker :: Lens' ListJobsResponse (Maybe Text)
ljrMarker = lens _ljrMarker (\s a -> s { _ljrMarker = a })
instance ToPath ListJobs where
toPath ListJobs{..} = mconcat
[ "/"
, toText _ljAccountId
, "/vaults/"
, toText _ljVaultName
, "/jobs"
]
instance ToQuery ListJobs where
toQuery ListJobs{..} = mconcat
[ "limit" =? _ljLimit
, "marker" =? _ljMarker
, "statuscode" =? _ljStatuscode
, "completed" =? _ljCompleted
]
instance ToHeaders ListJobs
instance ToJSON ListJobs where
toJSON = const (toJSON Empty)
instance AWSRequest ListJobs where
type Sv ListJobs = Glacier
type Rs ListJobs = ListJobsResponse
request = get
response = jsonResponse
instance FromJSON ListJobsResponse where
parseJSON = withObject "ListJobsResponse" $ \o -> ListJobsResponse
<$> o .:? "JobList" .!= mempty
<*> o .:? "Marker"
|
romanb/amazonka
|
amazonka-glacier/gen/Network/AWS/Glacier/ListJobs.hs
|
mpl-2.0
| 8,746
| 0
| 12
| 1,856
| 951
| 584
| 367
| 96
| 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.Dataflow.Projects.Jobs.GetMetrics
-- 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)
--
-- Request the job status. To request the status of a job, we recommend
-- using \`projects.locations.jobs.getMetrics\` with a [regional endpoint]
-- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints).
-- Using \`projects.jobs.getMetrics\` is not recommended, as you can only
-- request the status of jobs that are running in \`us-central1\`.
--
-- /See:/ <https://cloud.google.com/dataflow Dataflow API Reference> for @dataflow.projects.jobs.getMetrics@.
module Network.Google.Resource.Dataflow.Projects.Jobs.GetMetrics
(
-- * REST Resource
ProjectsJobsGetMetricsResource
-- * Creating a Request
, projectsJobsGetMetrics
, ProjectsJobsGetMetrics
-- * Request Lenses
, pjgmXgafv
, pjgmJobId
, pjgmUploadProtocol
, pjgmLocation
, pjgmStartTime
, pjgmAccessToken
, pjgmUploadType
, pjgmProjectId
, pjgmCallback
) where
import Network.Google.Dataflow.Types
import Network.Google.Prelude
-- | A resource alias for @dataflow.projects.jobs.getMetrics@ method which the
-- 'ProjectsJobsGetMetrics' request conforms to.
type ProjectsJobsGetMetricsResource =
"v1b3" :>
"projects" :>
Capture "projectId" Text :>
"jobs" :>
Capture "jobId" Text :>
"metrics" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "location" Text :>
QueryParam "startTime" DateTime' :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] JobMetrics
-- | Request the job status. To request the status of a job, we recommend
-- using \`projects.locations.jobs.getMetrics\` with a [regional endpoint]
-- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints).
-- Using \`projects.jobs.getMetrics\` is not recommended, as you can only
-- request the status of jobs that are running in \`us-central1\`.
--
-- /See:/ 'projectsJobsGetMetrics' smart constructor.
data ProjectsJobsGetMetrics =
ProjectsJobsGetMetrics'
{ _pjgmXgafv :: !(Maybe Xgafv)
, _pjgmJobId :: !Text
, _pjgmUploadProtocol :: !(Maybe Text)
, _pjgmLocation :: !(Maybe Text)
, _pjgmStartTime :: !(Maybe DateTime')
, _pjgmAccessToken :: !(Maybe Text)
, _pjgmUploadType :: !(Maybe Text)
, _pjgmProjectId :: !Text
, _pjgmCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsJobsGetMetrics' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pjgmXgafv'
--
-- * 'pjgmJobId'
--
-- * 'pjgmUploadProtocol'
--
-- * 'pjgmLocation'
--
-- * 'pjgmStartTime'
--
-- * 'pjgmAccessToken'
--
-- * 'pjgmUploadType'
--
-- * 'pjgmProjectId'
--
-- * 'pjgmCallback'
projectsJobsGetMetrics
:: Text -- ^ 'pjgmJobId'
-> Text -- ^ 'pjgmProjectId'
-> ProjectsJobsGetMetrics
projectsJobsGetMetrics pPjgmJobId_ pPjgmProjectId_ =
ProjectsJobsGetMetrics'
{ _pjgmXgafv = Nothing
, _pjgmJobId = pPjgmJobId_
, _pjgmUploadProtocol = Nothing
, _pjgmLocation = Nothing
, _pjgmStartTime = Nothing
, _pjgmAccessToken = Nothing
, _pjgmUploadType = Nothing
, _pjgmProjectId = pPjgmProjectId_
, _pjgmCallback = Nothing
}
-- | V1 error format.
pjgmXgafv :: Lens' ProjectsJobsGetMetrics (Maybe Xgafv)
pjgmXgafv
= lens _pjgmXgafv (\ s a -> s{_pjgmXgafv = a})
-- | The job to get metrics for.
pjgmJobId :: Lens' ProjectsJobsGetMetrics Text
pjgmJobId
= lens _pjgmJobId (\ s a -> s{_pjgmJobId = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pjgmUploadProtocol :: Lens' ProjectsJobsGetMetrics (Maybe Text)
pjgmUploadProtocol
= lens _pjgmUploadProtocol
(\ s a -> s{_pjgmUploadProtocol = a})
-- | The [regional endpoint]
-- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints)
-- that contains the job specified by job_id.
pjgmLocation :: Lens' ProjectsJobsGetMetrics (Maybe Text)
pjgmLocation
= lens _pjgmLocation (\ s a -> s{_pjgmLocation = a})
-- | Return only metric data that has changed since this time. Default is to
-- return all information about all metrics for the job.
pjgmStartTime :: Lens' ProjectsJobsGetMetrics (Maybe UTCTime)
pjgmStartTime
= lens _pjgmStartTime
(\ s a -> s{_pjgmStartTime = a})
. mapping _DateTime
-- | OAuth access token.
pjgmAccessToken :: Lens' ProjectsJobsGetMetrics (Maybe Text)
pjgmAccessToken
= lens _pjgmAccessToken
(\ s a -> s{_pjgmAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pjgmUploadType :: Lens' ProjectsJobsGetMetrics (Maybe Text)
pjgmUploadType
= lens _pjgmUploadType
(\ s a -> s{_pjgmUploadType = a})
-- | A project id.
pjgmProjectId :: Lens' ProjectsJobsGetMetrics Text
pjgmProjectId
= lens _pjgmProjectId
(\ s a -> s{_pjgmProjectId = a})
-- | JSONP
pjgmCallback :: Lens' ProjectsJobsGetMetrics (Maybe Text)
pjgmCallback
= lens _pjgmCallback (\ s a -> s{_pjgmCallback = a})
instance GoogleRequest ProjectsJobsGetMetrics where
type Rs ProjectsJobsGetMetrics = JobMetrics
type Scopes ProjectsJobsGetMetrics =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/userinfo.email"]
requestClient ProjectsJobsGetMetrics'{..}
= go _pjgmProjectId _pjgmJobId _pjgmXgafv
_pjgmUploadProtocol
_pjgmLocation
_pjgmStartTime
_pjgmAccessToken
_pjgmUploadType
_pjgmCallback
(Just AltJSON)
dataflowService
where go
= buildClient
(Proxy :: Proxy ProjectsJobsGetMetricsResource)
mempty
|
brendanhay/gogol
|
gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Jobs/GetMetrics.hs
|
mpl-2.0
| 6,978
| 0
| 21
| 1,616
| 969
| 565
| 404
| 143
| 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.DFAReporting.Advertisers.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Inserts a new advertiser.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.advertisers.insert@.
module Network.Google.Resource.DFAReporting.Advertisers.Insert
(
-- * REST Resource
AdvertisersInsertResource
-- * Creating a Request
, advertisersInsert
, AdvertisersInsert
-- * Request Lenses
, aiiProFileId
, aiiPayload
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.advertisers.insert@ method which the
-- 'AdvertisersInsert' request conforms to.
type AdvertisersInsertResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"advertisers" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Advertiser :> Post '[JSON] Advertiser
-- | Inserts a new advertiser.
--
-- /See:/ 'advertisersInsert' smart constructor.
data AdvertisersInsert = AdvertisersInsert'
{ _aiiProFileId :: !(Textual Int64)
, _aiiPayload :: !Advertiser
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AdvertisersInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aiiProFileId'
--
-- * 'aiiPayload'
advertisersInsert
:: Int64 -- ^ 'aiiProFileId'
-> Advertiser -- ^ 'aiiPayload'
-> AdvertisersInsert
advertisersInsert pAiiProFileId_ pAiiPayload_ =
AdvertisersInsert'
{ _aiiProFileId = _Coerce # pAiiProFileId_
, _aiiPayload = pAiiPayload_
}
-- | User profile ID associated with this request.
aiiProFileId :: Lens' AdvertisersInsert Int64
aiiProFileId
= lens _aiiProFileId (\ s a -> s{_aiiProFileId = a})
. _Coerce
-- | Multipart request metadata.
aiiPayload :: Lens' AdvertisersInsert Advertiser
aiiPayload
= lens _aiiPayload (\ s a -> s{_aiiPayload = a})
instance GoogleRequest AdvertisersInsert where
type Rs AdvertisersInsert = Advertiser
type Scopes AdvertisersInsert =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient AdvertisersInsert'{..}
= go _aiiProFileId (Just AltJSON) _aiiPayload
dFAReportingService
where go
= buildClient
(Proxy :: Proxy AdvertisersInsertResource)
mempty
|
rueshyna/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Advertisers/Insert.hs
|
mpl-2.0
| 3,285
| 0
| 14
| 739
| 406
| 242
| 164
| 63
| 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.MapsEngine.RasterCollections.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Return metadata for a particular raster collection.
--
-- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.rasterCollections.get@.
module Network.Google.Resource.MapsEngine.RasterCollections.Get
(
-- * REST Resource
RasterCollectionsGetResource
-- * Creating a Request
, rasterCollectionsGet
, RasterCollectionsGet
-- * Request Lenses
, rcgId
) where
import Network.Google.MapsEngine.Types
import Network.Google.Prelude
-- | A resource alias for @mapsengine.rasterCollections.get@ method which the
-- 'RasterCollectionsGet' request conforms to.
type RasterCollectionsGetResource =
"mapsengine" :>
"v1" :>
"rasterCollections" :>
Capture "id" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] RasterCollection
-- | Return metadata for a particular raster collection.
--
-- /See:/ 'rasterCollectionsGet' smart constructor.
newtype RasterCollectionsGet = RasterCollectionsGet'
{ _rcgId :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'RasterCollectionsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rcgId'
rasterCollectionsGet
:: Text -- ^ 'rcgId'
-> RasterCollectionsGet
rasterCollectionsGet pRcgId_ =
RasterCollectionsGet'
{ _rcgId = pRcgId_
}
-- | The ID of the raster collection.
rcgId :: Lens' RasterCollectionsGet Text
rcgId = lens _rcgId (\ s a -> s{_rcgId = a})
instance GoogleRequest RasterCollectionsGet where
type Rs RasterCollectionsGet = RasterCollection
type Scopes RasterCollectionsGet =
'["https://www.googleapis.com/auth/mapsengine",
"https://www.googleapis.com/auth/mapsengine.readonly"]
requestClient RasterCollectionsGet'{..}
= go _rcgId (Just AltJSON) mapsEngineService
where go
= buildClient
(Proxy :: Proxy RasterCollectionsGetResource)
mempty
|
rueshyna/gogol
|
gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/RasterCollections/Get.hs
|
mpl-2.0
| 2,901
| 0
| 12
| 645
| 302
| 186
| 116
| 49
| 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.Games.Applications.Played
-- 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)
--
-- Indicate that the the currently authenticated user is playing your
-- application.
--
-- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.applications.played@.
module Network.Google.Resource.Games.Applications.Played
(
-- * REST Resource
ApplicationsPlayedResource
-- * Creating a Request
, applicationsPlayed
, ApplicationsPlayed
-- * Request Lenses
, apConsistencyToken
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.applications.played@ method which the
-- 'ApplicationsPlayed' request conforms to.
type ApplicationsPlayedResource =
"games" :>
"v1" :>
"applications" :>
"played" :>
QueryParam "consistencyToken" (Textual Int64) :>
QueryParam "alt" AltJSON :> Post '[JSON] ()
-- | Indicate that the the currently authenticated user is playing your
-- application.
--
-- /See:/ 'applicationsPlayed' smart constructor.
newtype ApplicationsPlayed = ApplicationsPlayed'
{ _apConsistencyToken :: Maybe (Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ApplicationsPlayed' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'apConsistencyToken'
applicationsPlayed
:: ApplicationsPlayed
applicationsPlayed =
ApplicationsPlayed'
{ _apConsistencyToken = Nothing
}
-- | The last-seen mutation timestamp.
apConsistencyToken :: Lens' ApplicationsPlayed (Maybe Int64)
apConsistencyToken
= lens _apConsistencyToken
(\ s a -> s{_apConsistencyToken = a})
. mapping _Coerce
instance GoogleRequest ApplicationsPlayed where
type Rs ApplicationsPlayed = ()
type Scopes ApplicationsPlayed =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.login"]
requestClient ApplicationsPlayed'{..}
= go _apConsistencyToken (Just AltJSON) gamesService
where go
= buildClient
(Proxy :: Proxy ApplicationsPlayedResource)
mempty
|
rueshyna/gogol
|
gogol-games/gen/Network/Google/Resource/Games/Applications/Played.hs
|
mpl-2.0
| 3,029
| 0
| 13
| 667
| 332
| 201
| 131
| 51
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Directory.RoleAssignments.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a role assignment.
--
-- /See:/ <https://developers.google.com/admin-sdk/ Admin SDK API Reference> for @directory.roleAssignments.get@.
module Network.Google.Resource.Directory.RoleAssignments.Get
(
-- * REST Resource
RoleAssignmentsGetResource
-- * Creating a Request
, roleAssignmentsGet
, RoleAssignmentsGet
-- * Request Lenses
, ragXgafv
, ragUploadProtocol
, ragAccessToken
, ragUploadType
, ragCustomer
, ragRoleAssignmentId
, ragCallback
) where
import Network.Google.Directory.Types
import Network.Google.Prelude
-- | A resource alias for @directory.roleAssignments.get@ method which the
-- 'RoleAssignmentsGet' request conforms to.
type RoleAssignmentsGetResource =
"admin" :>
"directory" :>
"v1" :>
"customer" :>
Capture "customer" Text :>
"roleassignments" :>
Capture "roleAssignmentId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] RoleAssignment
-- | Retrieves a role assignment.
--
-- /See:/ 'roleAssignmentsGet' smart constructor.
data RoleAssignmentsGet =
RoleAssignmentsGet'
{ _ragXgafv :: !(Maybe Xgafv)
, _ragUploadProtocol :: !(Maybe Text)
, _ragAccessToken :: !(Maybe Text)
, _ragUploadType :: !(Maybe Text)
, _ragCustomer :: !Text
, _ragRoleAssignmentId :: !Text
, _ragCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RoleAssignmentsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ragXgafv'
--
-- * 'ragUploadProtocol'
--
-- * 'ragAccessToken'
--
-- * 'ragUploadType'
--
-- * 'ragCustomer'
--
-- * 'ragRoleAssignmentId'
--
-- * 'ragCallback'
roleAssignmentsGet
:: Text -- ^ 'ragCustomer'
-> Text -- ^ 'ragRoleAssignmentId'
-> RoleAssignmentsGet
roleAssignmentsGet pRagCustomer_ pRagRoleAssignmentId_ =
RoleAssignmentsGet'
{ _ragXgafv = Nothing
, _ragUploadProtocol = Nothing
, _ragAccessToken = Nothing
, _ragUploadType = Nothing
, _ragCustomer = pRagCustomer_
, _ragRoleAssignmentId = pRagRoleAssignmentId_
, _ragCallback = Nothing
}
-- | V1 error format.
ragXgafv :: Lens' RoleAssignmentsGet (Maybe Xgafv)
ragXgafv = lens _ragXgafv (\ s a -> s{_ragXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ragUploadProtocol :: Lens' RoleAssignmentsGet (Maybe Text)
ragUploadProtocol
= lens _ragUploadProtocol
(\ s a -> s{_ragUploadProtocol = a})
-- | OAuth access token.
ragAccessToken :: Lens' RoleAssignmentsGet (Maybe Text)
ragAccessToken
= lens _ragAccessToken
(\ s a -> s{_ragAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ragUploadType :: Lens' RoleAssignmentsGet (Maybe Text)
ragUploadType
= lens _ragUploadType
(\ s a -> s{_ragUploadType = a})
-- | Immutable ID of the Google Workspace account.
ragCustomer :: Lens' RoleAssignmentsGet Text
ragCustomer
= lens _ragCustomer (\ s a -> s{_ragCustomer = a})
-- | Immutable ID of the role assignment.
ragRoleAssignmentId :: Lens' RoleAssignmentsGet Text
ragRoleAssignmentId
= lens _ragRoleAssignmentId
(\ s a -> s{_ragRoleAssignmentId = a})
-- | JSONP
ragCallback :: Lens' RoleAssignmentsGet (Maybe Text)
ragCallback
= lens _ragCallback (\ s a -> s{_ragCallback = a})
instance GoogleRequest RoleAssignmentsGet where
type Rs RoleAssignmentsGet = RoleAssignment
type Scopes RoleAssignmentsGet =
'["https://www.googleapis.com/auth/admin.directory.rolemanagement",
"https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly"]
requestClient RoleAssignmentsGet'{..}
= go _ragCustomer _ragRoleAssignmentId _ragXgafv
_ragUploadProtocol
_ragAccessToken
_ragUploadType
_ragCallback
(Just AltJSON)
directoryService
where go
= buildClient
(Proxy :: Proxy RoleAssignmentsGetResource)
mempty
|
brendanhay/gogol
|
gogol-admin-directory/gen/Network/Google/Resource/Directory/RoleAssignments/Get.hs
|
mpl-2.0
| 5,285
| 0
| 20
| 1,291
| 788
| 458
| 330
| 119
| 1
|
-- | A @`Maker` a@ is wrapper around a function from @`Tree`@'s to @a@s. They are
-- built up using various combinators, then invoked with @`runMaker`@.
module Maker (
Maker(),runMaker,
(@@),(@?),(@@@),(@@#),(/@@),(/@#),(<?>),
(~@),(~?),
firstChild,secondChild,mapSubForest,tryMap,filterSubForest,singleChild,
checkKey,checkKeys,excludeKeys,checkValue,checkValues,key,
fetchString,label,except,optional,defaultingTo,oneOf,
Maker.number,fetchId, fetchBool,position
) where
import Tree(Tree(..))
import Scoped (Error,Label,Atom(..),eventId)
import qualified Data.Text as T(pack,Text)
import Text.Parsec(parse)
import Control.Applicative(Alternative(empty),(<|>))
import Data.Monoid((<>))
import Data.Foldable(find)
import Data.Either(rights)
import Prelude hiding (concat,lookup)
show' :: Show a ⇒ a → T.Text
show' = T.pack . show
-- | Describes how to make an @a@ from a @`Tree` Atom@.
-- If there is an error, the integer is flags how likely it is that the error
-- message will be useful. For instance, if a key doesn't match, we are likely
-- to backtrack out of a wrong branch of an alternative, but if the structure
-- is wrong, this is probably an error.
newtype Maker a = Maker (Tree Atom -> Either (Error,Reason) a)
data Reason = KeyNotFound
| BadConversion
| MissingChild
deriving (Eq,Ord,Show)
-- | @runMaker maker t@ uses the description provided by @maker@ to construct an
-- @a@.
runMaker :: Maker a → Tree Atom → Either Error a
runMaker (Maker f) t = case f t of
Left (e,_) -> Left e
Right r -> Right r
instance Functor Maker where
fmap f (Maker a) = Maker ((f<$>) <$> a)
instance Applicative Maker where
pure m = Maker $ const (Right m)
Maker mf <*> Maker ma = Maker $ \t -> case mf t of
Right f → case ma t of
Right a → Right $ f a
Left l → Left l
Left l → Left l
instance Alternative Maker where
empty = Maker $ \Node { source } -> Left (("Empty Maker",source), MissingChild)
Maker mx <|> Maker my = Maker $ \t -> case (mx t, my t) of
(x@(Left (_,ix)), y@(Left (_,iy))) → if ix > iy then x else y
(Right x, _) -> Right x
(_, Right y) -> Right y
optional :: Maker a -> Maker (Maybe a)
optional (Maker f) = Maker $ \t -> case f t of
Right r -> Right $ Just r
Left _ -> Right Nothing
instance Monad Maker where
return x = Maker $ \_ → Right x
(Maker f1) >>= f = Maker $ \t → case f1 t of
Left l → Left l
Right a → case f a of
Maker f2 -> f2 t
-- | @maker \<?\> err@ behaves the same as @maker@, but if @maker@ fails, the error
-- message is prefixed by "@err@ =>"
infix 0 <?>
(Maker f) <?> msg = Maker $ \t → case f t of
r@(Right _) → r
Left ((eMsg, source),prio) → Left ((msg <> " => " <> eMsg, source),prio)
-- | Get the source position this tree was created from.
position = Maker $ Right . source
-- | @firstChild m@ applies @m@ to the first child node.
firstChild :: Maker a → Maker a
firstChild (Maker f) = Maker $ \t → case subForest t of
[] → Left (("No children: "<> show' (rootLabel t),source t), MissingChild)
(x:_) → f x
-- | @secondChild m@ applies @m@ to the second child node.
secondChild :: Maker a → Maker a
secondChild (Maker f) = Maker $ \t → case subForest t of
[] → Left (("No children",source t), MissingChild)
[_] → Left (("Only one child", source t), MissingChild)
(_:x:_) → f x
oneOf :: Maker a → Maker b → Maker (Either a b)
oneOf m1 m2 = (Left <$> m1) <|> (Right <$> m2)
-- | @mapSubForest m@ applies @m@ to every child node.
mapSubForest (Maker f) = Maker $ \t -> mapM f $ subForest t
-- | @tryMap m@ applies @m@ to every child node for which it succeeds
tryMap :: Maker a → Maker [a]
tryMap (Maker f) = Maker $ \t -> Right $ rights $ map f $ subForest t
-- | @filterSubForest p m@ removes any subtree that @o@ doesn't match, then
-- applies @m@ to the entire result.
filterSubForest p (Maker f) = Maker $ f . (\Node { subForest = s,
rootLabel,
source } ->
Node { subForest = filter p s,
rootLabel,
source })
-- | Fail unless there is exactly one child.
singleChild = Maker $ \t → if length (subForest t) == 1
then Right ()
else Left (("Not one child",source t), MissingChild)
-- | @m \@\@ key@ makes @m@ by using only a subtree with rootLabel @key@. If no such
-- subtree exists (or if @m@ fails) the entire @`Maker`@ fails.
infixl 5 @@
(@@) :: Maker a → Label → Maker a
(Maker f) @@ k = Maker $ \t → case find ((==Label k) . rootLabel) $ subForest t of
Nothing → Left (("No child: " <> k <> " in block with root: " <> show' (rootLabel t), source t)
, MissingChild)
Just t' → f t'
-- | @m \@? key@: As @\@\@@, but if no child is found, return @Nothing@.
infixl 5 @?
(@?) :: Maker a → Label → Maker (Maybe a)
(Maker f) @? k = Maker $ \t → case find ((==Label k) . rootLabel) $ subForest t of
Nothing → Right Nothing
Just t' → Just <$> f t'
-- | @m \~\@ key@ makes @m@ by using only the first child of the subtree with
-- rootLabel @key@. If no such subtree exists (or if @m@ fails) the entire
-- @`Maker`@ fails.
infixl 5 ~@
(~@) :: Maker a → Label → Maker a
m ~@ k = firstChild m @@ k
-- | @m \~? key@: As @\~\@@, but if no child is found, return @Nothing@.
infixl 5 ~?
(~?) :: Maker a → Label → Maker (Maybe a)
m ~? k = firstChild m @? k
-- | @checkKey key@ succeeds if the root label is key
checkKey k = Maker $ \t -> case rootLabel t of
Label l → if l == k
then Right l
else Left (("Check for "<>show' k<>" failed. Found: "<>show' (rootLabel t)
,source t)
, KeyNotFound)
Number _ → Left (("Check for key "<>show' k<>" failed. Found number",source t)
, KeyNotFound)
-- | @checkKeys keys@ succeeds if the root label is an element of keys.
checkKeys keys = Maker $ \t → if rootLabel t `elem` map Label keys
then Right $ rootLabel t
else Left (("Check for keys failed. Found: " <> show' (rootLabel t), source t)
, KeyNotFound)
-- | @except m1 m2@ is equivalent to `m2` if `m1` fails, and fails if `m1` succeeds
except (Maker f1) (Maker f2) = Maker $ \t -> case f1 t of
Right _ -> Left (("Excepted maker succeeded: " <> show' (rootLabel t), source t)
, KeyNotFound)
Left _ -> f2 t
-- | @excludeKeys keys@ succeeds with the root label provided the label is not in `keys`.
excludeKeys keys = Maker $ \t → if rootLabel t `notElem` map Label keys
then Right $ rootLabel t
else Left (("Root label excluded: " <> show' (rootLabel t), source t)
, KeyNotFound)
-- | @checkValue v@ succeeds if the root label of the first child is @v@.
checkValue = firstChild . checkKey
-- | @checkValue vs@ succeeds if the root label of the first child is in @vs@.
checkValues = firstChild . checkKeys
-- | Succeed with the root label of the tree
key :: Maker Atom
key = Maker $ \ t → Right $ rootLabel t
-- | If the root label is a number, succeed with it.
number = Maker $ \t → case rootLabel t of
Scoped.Label l → Left (("Not a number: "<> show' l, source t), BadConversion)
Scoped.Number n → Right n
-- | Get the label of the tree
label :: Maker Atom → Maker Label
label (Maker f) = Maker $ \t → case f t of
Left l → Left l
Right (Label l) → Right l
Right (Number n) → Left (("Encountered number when expecting a label: " <> show' n, source t), BadConversion)
-- | @m `defaultingTo` v@ makes `m`, but if it fails, it returns `v`
defaultingTo :: Maker a → a → Maker a
(Maker f) `defaultingTo` value = Maker $ \t → case f t of
Left _ → Right value
r@(Right _) → r
-- | @m \@\@\@ key@: As @\@\@@, but return make a list with every matching subTree
infixl 5 @@@
(@@@) :: Maker a -> Label -> Maker [a]
f @@@ k = filterSubForest ((== Label k) . rootLabel) (mapSubForest f)
-- | @m /\@\@ key@: As @\@\@\@@, but use all subtrees that don't match
infixl 5 /@@
(/@@) :: Maker a → Label → Maker [a]
f /@@ k = filterSubForest ((/= Label k) . rootLabel) $ mapSubForest f
-- | @m \@\@# keys@: As @@@, but use any subtree whose label is in @keys@.
infixl 5 @@#
(@@#) :: Maker a → [Label] → Maker [a]
f @@# keys = filterSubForest ((`elem` (Label <$> keys)) . rootLabel) $ mapSubForest f
-- | m \/\@# keys: As /\@\@, but with any subtree whose label is not in @keys@.
infixl 5 /@#
(/@#) :: Maker a → [Label] → Maker [a]
f /@# keys = filterSubForest (not . (`elem` (Label <$> keys)) . rootLabel) $ mapSubForest f
-- | Get the root label of the single child. If the label is a number, fail.
fetchString = Maker $ \t → case subForest t of
[] → Left (("Can't take a value at " <> show' (rootLabel t),source t), BadConversion)
[Node { rootLabel = Number n}] →
Left (("Expected string for value of "<> show' (rootLabel t) <>", got: "<> show' n
, source t)
, BadConversion)
[Node { rootLabel = Label l}] → Right l
_ → Left (("Expected a string for value of "<> show' (rootLabel t) <> ", got a block."
, source t)
, BadConversion)
-- | Get an event id from the label of the single child. This can either be of
-- the form @Number id@ or @Label $ namespace <> "." <> number@.
fetchId = Maker $ \t → case firstChild key of
Maker f -> case f t of
Left e → Left e
Right (Label k) → case parse eventId "fetchID parse" k of
Left _ → Left (("Not a valid eventId: "<>k, source t), BadConversion)
Right (t,Number n) → Right (t,n)
Right (n,Label x) → Left (("Ill-formed eventId: "<>n<>"."<>x, source t)
, BadConversion)
Right (Number n) → Right ("",n)
-- | Get a boolean from the label of the single child. The label must be one of
-- "yes", "no", "true", "false".
fetchBool = Maker $ \t → case firstChild key of
Maker f -> case f t of
Left e → Left e
Right (Label k) → case k of
"false" → Right False
"no" → Right False
"true" → Right True
"yes" → Right True
_ → Left ((k <> " is not a boolean value.", source t), BadConversion)
Right (Number n) → Left (("Expected boolean, got: " <> show' n, source t)
, BadConversion)
|
joelwilliamson/validator
|
Maker.hs
|
agpl-3.0
| 10,737
| 0
| 21
| 2,913
| 3,444
| 1,807
| 1,637
| -1
| -1
|
{- |
Module : $Header$
Description : Types used by tempuhs.
Copyright : (c) plaimi 2014
License : AGPL-3
Maintainer : tempuhs@plaimi.net
-} module Tempuhs.Types where
-- | A 'ProperTime' is time measured by a 'Clock'.
type ProperTime = Double
-- | A 'TimeRange' represents a range between two 'ProperTime' endpoints.
type TimeRange = (ProperTime, ProperTime)
-- | A 'Weight' is used to signify the relative significance of a 'Timespan'.
type Weight = Double
|
plaimi/tempuhs
|
src/Tempuhs/Types.hs
|
agpl-3.0
| 477
| 0
| 5
| 93
| 34
| 24
| 10
| 4
| 0
|
-- type templated haskell
-- http://ghc-devs.haskell.narkive.com/cCdTaqot/new-branch-implementing-typed-untyped-template-haskell
-- https://mail.haskell.org/pipermail/ghc-devs/2013-May/001255.html
|
egaburov/funstuff
|
Haskell/thsk/tths02.hs
|
apache-2.0
| 197
| 0
| 2
| 8
| 5
| 4
| 1
| 1
| 0
|
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
module World.Statistics where
import Control.Lens
import qualified Data.Foldable as F
import Data.List (intercalate)
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Sequence as S
import Numeric (showFFloat)
import Types
import World.Utils
instance Monoid WorldStats where
mempty = WS (M.fromList $ map (,0) index) 0 0 0 (M.fromList $ map (,0) r) 0 0 S.empty
where
r :: (Bounded t, Enum t) => [t]
r = [minBound..maxBound]
index = (,,,,) <$> r <*> r <*> r <*> r <*> r
mappend (WS a w h m i g p as) (WS a' w' h' m' i' g' p' as') =
WS (M.unionWith (+) a a') (w+w') (h+h') (m + m') (M.unionWith (+) i i') (g+g') (p+p') (as S.>< as')
agentDied :: AgentIndex -> WorldStats -> WorldStats
agentDied i = numAgents . ix i -~ 1
wumpusDied :: WorldStats -> WorldStats
wumpusDied = numWumpuses -~ 1
plantHarvested :: WorldStats -> WorldStats
plantHarvested = numHarvests +~ 1
mealEaten :: WorldStats -> WorldStats
mealEaten = numMeals +~ 1
itemGiven :: Item -> WorldStats -> WorldStats
itemGiven item = numItemsGiven . ix item +~ 1
gestureSent :: WorldStats -> WorldStats
gestureSent = numGesturesSent +~ 1
attackPerformed :: WorldStats -> WorldStats
attackPerformed = numAttacksPerformed +~ 1
-- |Records that an agent performed a given action. No target is specified.
did :: EntityName -> CellInd -> Action -> WorldStats -> WorldStats
did x i a = actions %~ (S.|> (x,i,a,Nothing))
-- |Records that an agent performed a given action with another entity as the target.
didT :: EntityName -> CellInd -> Action -> EntityName -> WorldStats -> WorldStats
didT x i a t = actions %~ (S.|> (x,i,a,Just t))
-- |Creates statistics from a world. The number of living agents and Wumpuses will
-- be filled in. Everything else will be 0.
mkStats :: WorldMetaInfo -> World -> WorldStats
mkStats wmi w = M.foldr recordEntity mempty $ w ^. cellData
where
recordEntity CD{_cellDataEntity=Nothing} w = w
recordEntity CD{_cellDataEntity=Just (Wu _)} w = w & numWumpuses +~ 1
recordEntity CD{_cellDataEntity=Just (Ag a)} w = w & numAgents . ix ind +~ 1
where ind = wmi ^. agentPersonalities . at' (a ^. name)
showStats :: Int -> WorldStats -> String
showStats initialNumAgents ws =
"agents: " ++ show curAgents ++ " (" ++ percAgents ++ "%)\n"
++ concat (printAgents $ ws ^. numAgents)
++ "wumpuses: " ++ show (ws ^. numWumpuses) ++ "\n"
++ "harvests: " ++ show (ws ^. numHarvests) ++ "\n"
++ "meals eaten: " ++ show (ws ^. numMeals) ++ "\n"
++ "items given: " ++ show (F.sum $ ws ^. numItemsGiven) ++ "\n"
++ " gold: " ++ show (ws ^. numItemsGiven . at' Gold) ++ "\n"
++ " meat: " ++ show (ws ^. numItemsGiven . at' Meat) ++ "\n"
++ " fruit: " ++ show (ws ^. numItemsGiven . at' Fruit) ++ "\n"
++ "gestures: " ++ show (ws ^. numGesturesSent) ++ "\n"
++ "attacks: " ++ show (ws ^. numAttacksPerformed) ++ "\n"
++ "actions:\n"
++ (concat . map (\x -> " " ++ x ++ "\n") . map showAction . F.toList . view actions $ ws)
where
showFT Weak = "w"
showFT Strong = "s"
showST Friendly = "f"
showST Hostile = "h"
curAgents = F.sum $ ws ^. numAgents
percAgents :: String
percAgents = flip (showFFloat (Just 3)) ""
$ (((fromIntegral curAgents / fromIntegral initialNumAgents) :: Float) * 100)
showInd :: AgentIndex -> String
showInd (a,f,e,c,s) = "(" ++ intercalate "," (map showFT [a,f,e,c]) ++ ";" ++ showST s ++ ")"
printAgents :: M.Map AgentIndex Int -> [String]
printAgents = map (\(k,v) -> " " ++ showInd k ++ ": " ++ show v ++ "\n") . M.toList
-- |Prints an action as a pretty string.
-- The result will contain more information than 'showAction''.
showAction :: ActionRecord -> String
showAction (n, i, a, t) = mconcat [n, " at ", show i, " ", go a]
where
t' = fromMaybe "<UNKNOWN>" t
go NoOp = "did nothing."
go (Rotate d) = mconcat ["turned ", show d, "."]
go (Move d) = mconcat ["moved ", show d, " to ", show (inDirection i d), "."]
go (Attack d) = mconcat ["attacked ", t', " to its ", show d, "."]
go (Give d it) = mconcat ["gave ", show it, " to ", t', " to its ", show d, "." ]
go (Gather) = mconcat ["harvested a plant."]
go (Collect it) = mconcat ["picked up ", show it, "."]
go (Drop it) = mconcat ["dropped ", show it, "."]
go (Eat it) = mconcat ["ate ", show it, "."]
go (Gesture d g) = mconcat ["gestured '", g, "' to ", t', " to its ", show d, "."]
-- |Prints an action as a pretty string.
showAction' :: Action -> String
showAction' = go
where
go NoOp = "Do nothing."
go (Rotate d) = mconcat ["Turn to ", show d, "."]
go (Move d) = mconcat ["Move to ", show d, "."]
go (Attack d) = mconcat ["Attack to the ", show d, "."]
go (Give d it) = mconcat ["Give ", show it, " to the ", show d, "." ]
go (Gather) = mconcat ["Harvest a plant."]
go (Collect it) = mconcat ["Pick up ", show it, "."]
go (Drop it) = mconcat ["Drop ", show it, "."]
go (Eat it) = mconcat ["Eat ", show it, "."]
go (Gesture d g) = mconcat ["Gesture '", g, "' to the ", show d, "."]
|
jtapolczai/wumpus
|
World/Statistics.hs
|
apache-2.0
| 5,319
| 0
| 39
| 1,300
| 2,047
| 1,089
| 958
| -1
| -1
|
-- Copyright 1999-2011 The Text.XHtml Authors.
--
-- 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.
-- #hide
module Text.XHtml.Transitional.Attributes where
import Text.XHtml.Internals
-- * Extra attributes in XHTML Transitional
{-# DEPRECATED alink "This attribute is deprecated in XHTML 1.0" #-}
alink :: String -> HtmlAttr
alink = strAttr "alink"
{-# DEPRECATED background "This attribute is deprecated in XHTML 1.0" #-}
background :: String -> HtmlAttr
background = strAttr "background"
{-# DEPRECATED bgcolor "This attribute is deprecated in XHTML 1.0" #-}
bgcolor :: String -> HtmlAttr
bgcolor = strAttr "bgcolor"
{-# DEPRECATED clear "This attribute is deprecated in XHTML 1.0" #-}
clear :: String -> HtmlAttr
clear = strAttr "clear"
{-# DEPRECATED code "This attribute is deprecated in XHTML 1.0" #-}
code :: String -> HtmlAttr
code = strAttr "code"
{-# DEPRECATED color "This attribute is deprecated in XHTML 1.0" #-}
color :: String -> HtmlAttr
color = strAttr "color"
{-# DEPRECATED compact "This attribute is deprecated in XHTML 1.0" #-}
compact :: HtmlAttr
compact = emptyAttr "compact"
{-# DEPRECATED face "This attribute is deprecated in XHTML 1.0" #-}
face :: String -> HtmlAttr
face = strAttr "face"
{-# DEPRECATED hspace "This attribute is deprecated in XHTML 1.0" #-}
hspace :: Int -> HtmlAttr
hspace = intAttr "hspace"
{-# DEPRECATED link "This attribute is deprecated in XHTML 1.0" #-}
link :: String -> HtmlAttr
link = strAttr "link"
{-# DEPRECATED noshade "This attribute is deprecated in XHTML 1.0" #-}
noshade :: HtmlAttr
noshade = emptyAttr "noshade"
{-# DEPRECATED nowrap "This attribute is deprecated in XHTML 1.0" #-}
nowrap :: HtmlAttr
nowrap = emptyAttr "nowrap"
{-# DEPRECATED start "This attribute is deprecated in XHTML 1.0" #-}
start :: Int -> HtmlAttr
start = intAttr "start"
target :: String -> HtmlAttr
target = strAttr "target"
{-# DEPRECATED text "This attribute is deprecated in XHTML 1.0" #-}
text :: String -> HtmlAttr
text = strAttr "text"
{-# DEPRECATED version "This attribute is deprecated in XHTML 1.0" #-}
version :: String -> HtmlAttr
version = strAttr "version"
{-# DEPRECATED vlink "This attribute is deprecated in XHTML 1.0" #-}
vlink :: String -> HtmlAttr
vlink = strAttr "vlink"
{-# DEPRECATED vspace "This attribute is deprecated in XHTML 1.0" #-}
vspace :: Int -> HtmlAttr
vspace = intAttr "vspace"
--
-- * Html colors
--
{-# DEPRECATED aqua,black,blue,fuchsia,gray,green,lime,maroon,navy,olive,purple,red,silver,teal,yellow,white "The use of color attibutes is deprecated in XHTML 1.0" #-}
aqua :: String
black :: String
blue :: String
fuchsia :: String
gray :: String
green :: String
lime :: String
maroon :: String
navy :: String
olive :: String
purple :: String
red :: String
silver :: String
teal :: String
yellow :: String
white :: String
aqua = "aqua"
black = "black"
blue = "blue"
fuchsia = "fuchsia"
gray = "gray"
green = "green"
lime = "lime"
maroon = "maroon"
navy = "navy"
olive = "olive"
purple = "purple"
red = "red"
silver = "silver"
teal = "teal"
yellow = "yellow"
white = "white"
|
robinbb/hs-text-xhtml
|
Text/XHtml/Transitional/Attributes.hs
|
apache-2.0
| 4,398
| 0
| 5
| 1,412
| 504
| 298
| 206
| 88
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | A datatype representing the request attributes Airbrake wants to hear
-- about. Conversion functions are provided for:
--
-- * wai
module Airbrake.WebRequest (
WebRequest (..), waiRequestToRequest
) where
import Data.ByteString.UTF8 (toString)
import Data.Maybe
import Network.URI
import qualified Network.Wai as Wai
data WebRequest = WebRequest
{
-- | The request URL.
requestUrl :: URI
-- | Current route.
-- This is a carryover from Rails-style MVC and is optional.
, requestRoute :: Maybe String
-- | Controller action being used.
-- This is a carryover from Rails-style MVC and is optional.
, requestAction :: Maybe String
-- | Any other request metadata that you would like to include
-- (server name, user agent, etc.)
, requestOtherVars :: [(String, String)]
} deriving (Eq, Ord, Show)
waiRequestToRequest :: Wai.Request -> WebRequest
waiRequestToRequest req = WebRequest{..} where
requestUrl = fromMaybe
(error "Failure producing URI from wai request.")
(parseURI uriS)
uriS = (if Wai.isSecure req then "https://" else "http://")
++ show (Wai.remoteHost req)
++ toString (Wai.rawPathInfo req)
++ toString (Wai.rawQueryString req)
requestRoute = Nothing
requestAction = Nothing
requestOtherVars = catMaybes
[ k "Host" "HTTP_HOST"
, k "User-Agent" "HTTP_USER_AGENT"
, k "Referer" "HTTP_REFERER"
, k "Cookie" "HTTP_COOKIE"
, if Wai.isSecure req then Just ("HTTPS", "on") else Nothing]
where k hdr key = fmap (\ v -> (key, toString v))
(lookup hdr (Wai.requestHeaders req))
|
pikajude/hs-airbrake
|
src/Airbrake/WebRequest.hs
|
bsd-2-clause
| 1,963
| 0
| 14
| 639
| 362
| 205
| 157
| 33
| 3
|
module Physics.Sloth2D.Stepper
( Stepper
, stepper, advance
, lerpFactor, timeStep
) where
-- | A time step manager entity to fix the time steps of the
-- simulation.
data Stepper = Stepper
{ tstep :: Float
, tstep' :: Float
, dtmax :: Float
, tfrac :: Float
}
-- | Constructing a stepper.
stepper :: Float -- ^ Physics time step.
-> Float -- ^ Maximum time of physics simulated in one step.
-> Stepper -- ^ The stepper with the above parameters fixed.
stepper tstep dtmax = Stepper
{ tstep = tstep
, tstep' = recip tstep
, dtmax = dtmax
, tfrac = 0
}
-- | Advancing a stepper.
advance :: Float -- ^ The amount of time elapsed since the last sampling.
-> Stepper -- ^ The stepper to advance.
-> (Int, Stepper) -- ^ The number of physics steps to take and the updated stepper.
advance dt s = (n,s')
where
tf = tfrac s+min dt (dtmax s)
n = floor (tf*tstep' s)
s' = s { tfrac = tf-fromIntegral n*tstep s}
-- | The interpolation factor of a stepper: the time fraction of the
-- frame to render between 0 and 1. If 1, the current state of the
-- simulation must be rendered, otherwise it needs to be interpolated
-- with the previous state.
lerpFactor :: Stepper -> Float
lerpFactor s = tfrac s*tstep' s
-- | The time step associated with a stepper.
timeStep :: Stepper -> Float
timeStep = tstep
|
cobbpg/sloth2d
|
Physics/Sloth2D/Stepper.hs
|
bsd-3-clause
| 1,425
| 0
| 11
| 384
| 270
| 158
| 112
| 28
| 1
|
module Zero.Account.Client
(
Credentials(..)
) where
import GHC.Generics (Generic)
import Data.Text (Text)
import Data.Aeson
------------------------------------------------------------------------------
-- Types
------------------------------------------------------------------------------
data Credentials = Credentials
{ c_email :: Text
, c_salt :: Text
, c_pass :: Text
, c_unwrapKey :: Text
} deriving (Show, Generic)
instance ToJSON Credentials where
toJSON (Credentials email salt pass unwrapKey) =
object [
"email" .= email
, "salt" .= salt
, "pass" .= pass
, "unwrapKey" .= unwrapKey
]
|
et4te/zero
|
src/Zero/Account/Client.hs
|
bsd-3-clause
| 692
| 0
| 8
| 167
| 147
| 87
| 60
| 19
| 0
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RebindableSyntax #-}
module Nifty (main) where
import Prelude
import FFI
import Fay.Text
import Cinder.SVG
main :: Fay ()
main = addEventListener "load" nifty False
nifty :: Fay ()
nifty = root >>= byTag "path" >>= mapM (tracePath 1 1)
>>= stagger "begin" 0 1 >> return ()
addEventListener :: Text -> Fay () -> Bool -> Fay ()
addEventListener = ffi "window['addEventListener'](%1,%2,%3)"
|
crooney/cinder
|
examples/Nifty.hs
|
bsd-3-clause
| 449
| 0
| 10
| 81
| 141
| 73
| 68
| 14
| 1
|
--
-- Copyright © 2014-2015 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
-- | Description: Configuration for the system.
module Synchronise.Configuration where
import Control.Applicative
import Control.Monad.Error.Class
import Control.Monad.IO.Class
import Control.Monad.Trans.Except
import Data.ByteString
import qualified Data.ByteString.Char8 as BS
import Data.Configurator as C
import Data.Configurator.Types
import qualified Data.List as L
import Data.Map (Map)
import qualified Data.Map as M
import Data.Monoid
import Data.String
import Data.Text (Text)
import qualified Data.Text as T
import System.Log.Logger
import Synchronise.Diff
import Synchronise.Identifier
-- | Command template.
newtype Command = Command { unCommand :: Text }
deriving (Eq, Show, Ord)
instance IsString Command where
fromString = Command . T.pack
--------------------------------------------------------------------------------
-- | Record describing an external data source and how we interact with it.
data DataSource = DataSource
{ sourceEntity :: EntityName -- ^ Unique name for entity.
, sourceName :: SourceName -- ^ Unique name for this data source.
, sourceDescription :: Maybe Text -- ^ Description for this data source.
, commandCreate :: Command -- ^ Command template: create object.
, commandRead :: Command -- ^ Command template: read object.
, commandUpdate :: Command -- ^ Command template: update object.
, commandDelete :: Command -- ^ Command template: delete object.
}
deriving (Eq, Ord, Show)
instance Synchronisable DataSource where
getEntityName = sourceEntity
getSourceName = sourceName
--------------------------------------------------------------------------------
data Entity = Entity
{ entityName :: EntityName
, entityDescription :: Maybe Text
, entitySchema :: Maybe FilePath
, entityPolicy :: MergePolicy
, entitySources :: Map SourceName DataSource
}
instance Eq Entity where
(==) (Entity n1 d1 s1 _ c1) (Entity n2 d2 s2 _ c2)
= n1 == n2 && d1 == d2 && s1 == s2 && c1 == c2
instance Show Entity where
show (Entity n d s _ c)
= L.intercalate "," [show n, show d, show s, show c]
-- | Construct an 'Entity' with only a name.
emptyEntity
:: Text
-> Entity
emptyEntity name = Entity (EntityName name) mempty mempty doNothing mempty
--------------------------------------------------------------------------------
-- | Configuration of entities and data sources.
data Configuration = Configuration
{ configEntities :: Map EntityName Entity
, configServer :: (String, Priority, ByteString)
}
deriving (Eq, Show)
-- | An \"empty\" configuration.
emptyConfiguration :: Configuration
emptyConfiguration = Configuration
mempty
("tcp://127.0.0.1:9999", EMERGENCY, "")
type Parser a = Config -> ExceptT Text IO a
-- | Parse a configurator 'Config' value into a 'Configuration'.
parseConfiguration
:: Parser Configuration
parseConfiguration cfg = Configuration
<$> entities cfg
<*> server cfg
where
entities :: Parser (Map EntityName Entity)
entities _ = do
enabled <- liftIO $ C.lookup cfg "entities.enabled"
ents <- case enabled of
Nothing -> throwError "No entities enabled in configuration."
Just [] -> throwError "No entities enabled in configuration."
Just es -> mapM (`parseEntity` cfg) es
return . M.fromList . fmap (\e -> (entityName e, e)) $ ents
server :: Parser (String, Priority, ByteString)
server _ =
(,,) <$> liftIO (C.require cfg "server.listen")
<*> liftIO (read <$> C.require cfg "server.log-level")
<*> liftIO (BS.pack <$> C.require cfg "server.database")
-- | Parse an entity from a configuration.
parseEntity
:: Text -- ^ Entity name.
-> Parser Entity
parseEntity name cfg' = do
let cfg = C.subconfig ("entities." <> name) cfg'
Entity
<$> parseName cfg
<*> parseDescription cfg
<*> parseSchema cfg
<*> (parsePolicy cfg >>= mkPolicy)
<*> parseSources cfg
where
parseName :: Parser EntityName
parseName _ = EntityName <$> pure name
parseDescription cfg = liftIO $ C.lookup cfg "description"
parseSchema cfg = liftIO $ C.lookup cfg "schema"
parsePolicy cfg = liftIO $ C.lookup cfg "merge-policy"
mkPolicy n
| n == Just "accept-all" = return acceptAll
| n == Just "reject-all" = return rejectAll
| n == Just "ignore-conflicts" = return ignoreConflicts
| Just thing <- n
, Just trusted <- L.stripPrefix "trust-only:" thing
= return (trustOnlySource $ SourceName $ T.pack trusted)
| otherwise = throwError $ "Unrecognised merge policy " <> T.pack (show n)
parseSources :: Parser (Map SourceName DataSource)
parseSources cfg = do
enabled <- liftIO $ C.lookup cfg "enabled"
sources <- case enabled of
Nothing -> throwError $ "No sources enabled in " <> name
Just [] -> throwError $ "No sources enabled in " <> name
Just ss -> mapM (`parseDataSource` cfg) . fmap (name,) $ ss
return . M.fromList $ sources
-- | Parse a data source from a configuration.
parseDataSource
:: (Text, Text)
-> Parser (SourceName, DataSource)
parseDataSource (entity_name, source_name) cfg' = do
let name = source_name
let cfg = C.subconfig name cfg'
let en = EntityName entity_name
let sn = SourceName source_name
desc <- liftIO $ C.lookup cfg "description"
c_cmd <- get_cmd cfg "create"
r_cmd <- get_cmd cfg "read"
u_cmd <- get_cmd cfg "update"
d_cmd <- get_cmd cfg "delete"
return (sn, DataSource en sn desc c_cmd r_cmd u_cmd d_cmd)
where
get_cmd cfg name = do
cmd <- liftIO $ C.lookup cfg name
case cmd of
Nothing -> throwError $ "No " <> name <> " command for " <>
entity_name <> "." <> source_name
Just c -> return $ Command c
-- | Get a 'DataSource' from a 'Configuration'.
getDataSource
:: Configuration
-> EntityName
-> SourceName
-> Either String DataSource
getDataSource Configuration{configEntities = es} en sn =
case M.lookup en es of
Nothing -> Left $ "No configuration for entity: " <> show en
Just ss -> case M.lookup sn (entitySources ss) of
Nothing -> Left $ "No configuration for entity and data source: "
<> n
Just ds -> Right ds
where
n = T.unpack $ ename en <> "/" <> sname sn
|
anchor/synchronise
|
lib/Synchronise/Configuration.hs
|
bsd-3-clause
| 7,157
| 0
| 17
| 1,931
| 1,720
| 894
| 826
| 145
| 3
|
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Geometry.ThreeD.Types
-- Copyright : (c) 2011-2017 diagrams team (see LICENSE)
-- License : BSD-style (see LICENSE)
-- Maintainer : diagrams-discuss@googlegroups.com
--
-- Basic types for three-dimensional Euclidean space.
--
-----------------------------------------------------------------------------
module Geometry.ThreeD.Types
( -- * 3D Euclidean space
r3, unr3, mkR3
, p3, unp3, mkP3
, r3Iso, p3Iso, project
, r3SphericalIso, r3CylindricalIso
, V3 (..), P3, T3
, R1 (..), R2 (..), R3 (..)
) where
import Control.Lens (Iso', iso, _1, _2, _3)
import Geometry.Angle
import Geometry.Points
import Geometry.Space
import Geometry.Transform
import Geometry.TwoD.Types
import Linear.Metric
import Linear.V3 as V
------------------------------------------------------------
-- 3D Euclidean space
-- Basic R3 types
type T3 = Transformation V3
r3Iso :: Iso' (V3 n) (n, n, n)
r3Iso = iso unr3 r3
-- | Construct a 3D vector from a triple of components.
r3 :: (n, n, n) -> V3 n
r3 (x,y,z) = V3 x y z
-- | Curried version of `r3`.
mkR3 :: n -> n -> n -> V3 n
mkR3 = V3
-- | Convert a 3D vector back into a triple of components.
unr3 :: V3 n -> (n, n, n)
unr3 (V3 x y z) = (x,y,z)
-- | Construct a 3D point from a triple of coordinates.
p3 :: (n, n, n) -> P3 n
p3 = P . r3
-- | Convert a 3D point back into a triple of coordinates.
unp3 :: P3 n -> (n, n, n)
unp3 (P (V3 x y z)) = (x,y,z)
p3Iso :: Iso' (P3 n) (n, n, n)
p3Iso = iso unp3 p3
-- | Curried version of `p3`.
mkP3 :: n -> n -> n -> P3 n
mkP3 x y z = p3 (x, y, z)
type instance V (V3 n) = V3
type instance N (V3 n) = n
instance Num n => Transformable (V3 n) where
transform = apply
-- | An isomorphism between 3D vectors and their representation in
-- spherical coordinates.
r3SphericalIso :: RealFloat n => Iso' (V3 n) (n, Angle n, Angle n)
r3SphericalIso = iso
(\v@(V3 x y z) -> (norm v, atan2A y x, acosA (z / norm v)))
(\(r,θ,φ) -> V3 (r * cosA θ * sinA φ) (r * sinA θ * sinA φ) (r * cosA φ))
-- | An isomorphism between 3D vectors and their representation in
-- cylindrical coordinates.
r3CylindricalIso :: RealFloat n => Iso' (V3 n) (n, Angle n, n)
r3CylindricalIso = iso
(\(V3 x y z) -> (sqrt $ x*x + y*y, atan2A y x, z))
(\(r,θ,z) -> V3 (r*cosA θ) (r*sinA θ) z)
instance HasR V3 where
_r = r3SphericalIso . _1
instance HasTheta V3 where
_theta = r3CylindricalIso . _2
instance HasPhi V3 where
_phi = r3SphericalIso . _3
|
cchalmers/geometry
|
src/Geometry/ThreeD/Types.hs
|
bsd-3-clause
| 2,737
| 0
| 12
| 647
| 900
| 511
| 389
| 53
| 1
|
module Main where
import InteractivePrompt
import System.Environment
main :: IO()
main = do
args <- getArgs
opts <- (if length args /= 2 then withArgs ["--help"] else id) getOpts
optionHandler opts
|
shaurya0/GPWebCrawler
|
src/Main.hs
|
bsd-3-clause
| 212
| 0
| 12
| 45
| 74
| 38
| 36
| 8
| 2
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.ProvokingVertex
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.ProvokingVertex (
-- * Extension Support
glGetARBProvokingVertex,
gl_ARB_provoking_vertex,
-- * Enums
pattern GL_FIRST_VERTEX_CONVENTION,
pattern GL_LAST_VERTEX_CONVENTION,
pattern GL_PROVOKING_VERTEX,
pattern GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION,
-- * Functions
glProvokingVertex
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/ProvokingVertex.hs
|
bsd-3-clause
| 855
| 0
| 5
| 113
| 72
| 52
| 20
| 12
| 0
|
module Data.Text.Lazy
( module ListBased
, Text
) where
import ListBased
import Types
|
Soostone/string-compat
|
src/Data/Text/Lazy.hs
|
bsd-3-clause
| 120
| 0
| 4
| 47
| 22
| 15
| 7
| 5
| 0
|
{-# LANGUAGE PatternGuards, ExistentialQuantification, CPP #-}
module Idris.Core.Execute (execute) where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import IRTS.Lang(FType(..))
import Idris.Primitives(Prim(..), primitives)
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.CaseTree
import Idris.Error
import Debug.Trace
import Util.DynamicLinker
import Util.System
import Control.Applicative hiding (Const)
import Control.Exception
import Control.Monad.Trans
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Error
import Control.Monad hiding (forM)
import Data.Maybe
import Data.Bits
import Data.Traversable (forM)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Data.Map as M
#ifdef IDRIS_FFI
import Foreign.LibFFI
import Foreign.C.String
import Foreign.Marshal.Alloc (free)
import Foreign.Ptr
#endif
import System.IO
#ifndef IDRIS_FFI
execute :: Term -> Idris Term
execute tm = fail "libffi not supported, rebuild Idris with -f FFI"
#else
-- else is rest of file
readMay :: (Read a) => String -> Maybe a
readMay s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
data Lazy = Delayed ExecEnv Context Term | Forced ExecVal deriving Show
data ExecState = ExecState { exec_dynamic_libs :: [DynamicLib] -- ^ Dynamic libs from idris monad
, binderNames :: [Name] -- ^ Used to uniquify binders when converting to TT
}
data ExecVal = EP NameType Name ExecVal
| EV Int
| EBind Name (Binder ExecVal) (ExecVal -> Exec ExecVal)
| EApp ExecVal ExecVal
| EType UExp
| EUType Universe
| EErased
| EConstant Const
| forall a. EPtr (Ptr a)
| EThunk Context ExecEnv Term
| EHandle Handle
instance Show ExecVal where
show (EP _ n _) = show n
show (EV i) = "!!V" ++ show i ++ "!!"
show (EBind n b body) = "EBind " ++ show b ++ " <<fn>>"
show (EApp e1 e2) = show e1 ++ " (" ++ show e2 ++ ")"
show (EType _) = "Type"
show (EUType _) = "UType"
show EErased = "[__]"
show (EConstant c) = show c
show (EPtr p) = "<<ptr " ++ show p ++ ">>"
show (EThunk _ env tm) = "<<thunk " ++ show env ++ "||||" ++ show tm ++ ">>"
show (EHandle h) = "<<handle " ++ show h ++ ">>"
toTT :: ExecVal -> Exec Term
toTT (EP nt n ty) = (P nt n) <$> (toTT ty)
toTT (EV i) = return $ V i
toTT (EBind n b body) = do n' <- newN n
body' <- body $ EP Bound n' EErased
b' <- fixBinder b
Bind n' b' <$> toTT body'
where fixBinder (Lam t) = Lam <$> toTT t
fixBinder (Pi t k) = Pi <$> toTT t <*> toTT k
fixBinder (Let t1 t2) = Let <$> toTT t1 <*> toTT t2
fixBinder (NLet t1 t2) = NLet <$> toTT t1 <*> toTT t2
fixBinder (Hole t) = Hole <$> toTT t
fixBinder (GHole i t) = GHole i <$> toTT t
fixBinder (Guess t1 t2) = Guess <$> toTT t1 <*> toTT t2
fixBinder (PVar t) = PVar <$> toTT t
fixBinder (PVTy t) = PVTy <$> toTT t
newN n = do (ExecState hs ns) <- lift get
let n' = uniqueName n ns
lift (put (ExecState hs (n':ns)))
return n'
toTT (EApp e1 e2) = do e1' <- toTT e1
e2' <- toTT e2
return $ App e1' e2'
toTT (EType u) = return $ TType u
toTT (EUType u) = return $ UType u
toTT EErased = return Erased
toTT (EConstant c) = return (Constant c)
toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env
return $ normalise ctxt env' tm
where toBinder (n, v) = do v' <- toTT v
return (n, Let Erased v')
toTT (EHandle _) = return Erased
unApplyV :: ExecVal -> (ExecVal, [ExecVal])
unApplyV tm = ua [] tm
where ua args (EApp f a) = ua (a:args) f
ua args t = (t, args)
mkEApp :: ExecVal -> [ExecVal] -> ExecVal
mkEApp f [] = f
mkEApp f (a:args) = mkEApp (EApp f a) args
initState :: Idris ExecState
initState = do ist <- getIState
return $ ExecState (idris_dynamic_libs ist) []
type Exec = ErrorT Err (StateT ExecState IO)
runExec :: Exec a -> ExecState -> IO (Either Err a)
runExec ex st = fst <$> runStateT (runErrorT ex) st
getExecState :: Exec ExecState
getExecState = lift get
putExecState :: ExecState -> Exec ()
putExecState = lift . put
execFail :: Err -> Exec a
execFail = throwError
execIO :: IO a -> Exec a
execIO = lift . lift
execute :: Term -> Idris Term
execute tm = do est <- initState
ctxt <- getContext
res <- lift . lift . flip runExec est $
do res <- doExec [] ctxt tm
toTT res
case res of
Left err -> ierror err
Right tm' -> return tm'
ioWrap :: ExecVal -> ExecVal
ioWrap tm = mkEApp (EP (DCon 0 2 False) (sUN "prim__IO") EErased) [EErased, tm]
ioUnit :: ExecVal
ioUnit = ioWrap (EP Ref unitCon EErased)
type ExecEnv = [(Name, ExecVal)]
doExec :: ExecEnv -> Context -> Term -> Exec ExecVal
doExec env ctxt p@(P Ref n ty) | Just v <- lookup n env = return v
doExec env ctxt p@(P Ref n ty) =
do let val = lookupDef n ctxt
case val of
[Function _ tm] -> doExec env ctxt tm
[TyDecl _ _] -> return (EP Ref n EErased) -- abstract def
[Operator tp arity op] -> return (EP Ref n EErased) -- will be special-cased later
[CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
doExec env ctxt tm
[CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> return (EP Ref n EErased)
[] -> execFail . Msg $ "Could not find " ++ show n ++ " in definitions."
other | length other > 1 -> execFail . Msg $ "Multiple definitions found for " ++ show n
| otherwise -> execFail . Msg . take 500 $ "got to " ++ show other ++ " lookup up " ++ show n
doExec env ctxt p@(P Bound n ty) =
case lookup n env of
Nothing -> execFail . Msg $ "not found"
Just tm -> return tm
doExec env ctxt (P (DCon a b u) n _) = return (EP (DCon a b u) n EErased)
doExec env ctxt (P (TCon a b) n _) = return (EP (TCon a b) n EErased)
doExec env ctxt v@(V i) | i < length env = return (snd (env !! i))
| otherwise = execFail . Msg $ "env too small"
doExec env ctxt (Bind n (Let t v) body) = do v' <- doExec env ctxt v
doExec ((n, v'):env) ctxt body
doExec env ctxt (Bind n (NLet t v) body) = trace "NLet" $ undefined
doExec env ctxt tm@(Bind n b body) = do b' <- forM b (doExec env ctxt)
return $
EBind n b' (\arg -> doExec ((n, arg):env) ctxt body)
doExec env ctxt a@(App _ _) =
do let (f, args) = unApply a
f' <- doExec env ctxt f
args' <- case f' of
(EP _ d _) | d == delay ->
case args of
[t,a,tm] -> do t' <- doExec env ctxt t
a' <- doExec env ctxt a
return [t', a', EThunk ctxt env tm]
_ -> mapM (doExec env ctxt) args -- partial applications are fine to evaluate
fun' -> do mapM (doExec env ctxt) args
execApp env ctxt f' args'
doExec env ctxt (Constant c) = return (EConstant c)
doExec env ctxt (Proj tm i) = let (x, xs) = unApply tm in
doExec env ctxt ((x:xs) !! i)
doExec env ctxt Erased = return EErased
doExec env ctxt Impossible = fail "Tried to execute an impossible case"
doExec env ctxt (TType u) = return (EType u)
doExec env ctxt (UType u) = return (EUType u)
execApp :: ExecEnv -> Context -> ExecVal -> [ExecVal] -> Exec ExecVal
execApp env ctxt v [] = return v -- no args is just a constant! can result from function calls
execApp env ctxt (EP _ f _) (t:a:delayed:rest)
| f == force
, (_, [_, _, EThunk tmCtxt tmEnv tm]) <- unApplyV delayed =
do tm' <- doExec tmEnv tmCtxt tm
execApp env ctxt tm' rest
execApp env ctxt (EP _ fp _) (ty:action:rest)
| fp == upio,
(prim__IO, [_, v]) <- unApplyV action
= execApp env ctxt v rest
execApp env ctxt (EP _ fp _) args@(_:_:v:k:rest)
| fp == piobind,
(prim__IO, [_, v']) <- unApplyV v =
do res <- execApp env ctxt k [v']
execApp env ctxt res rest
execApp env ctxt con@(EP _ fp _) args@(tp:v:rest)
| fp == pioret = execApp env ctxt (mkEApp con [tp, v]) rest
-- Special cases arising from not having access to the C RTS in the interpreter
execApp env ctxt (EP _ fp _) (_:fn:str:_:rest)
| fp == mkfprim,
Just (FFun "putStr" _ _) <- foreignFromTT fn
= case str of
EConstant (Str arg) -> do execIO (putStr arg)
execApp env ctxt ioUnit rest
_ -> execFail . Msg $
"The argument to putStr should be a constant string, but it was " ++
show str ++
". Are all cases covered?"
execApp env ctxt (EP _ fp _) (_:fn:ch:_:rest)
| fp == mkfprim,
Just (FFun "putchar" _ _) <- foreignFromTT fn
= case ch of
EConstant (Ch c) -> do execIO (putChar c)
execApp env ctxt ioUnit rest
EConstant (I i) -> do execIO (putChar (toEnum i))
execApp env ctxt ioUnit rest
_ -> execFail . Msg $
"The argument to putchar should be a constant character, but it was " ++
show str ++
". Are all cases covered?"
execApp env ctxt (EP _ fp _) (_:fn:_:handle:_:rest)
| fp == mkfprim,
Just (FFun "idris_readStr" _ _) <- foreignFromTT fn
= case handle of
EHandle h -> do contents <- execIO $ hGetLine h
execApp env ctxt (EConstant (Str (contents ++ "\n"))) rest
_ -> execFail . Msg $
"The argument to idris_readStr should be a handle, but it was " ++
show handle ++
". Are all cases covered?"
execApp env ctxt (EP _ fp _) (_:fn:rest)
| fp == mkfprim,
Just (FFun "idris_time" _ _) <- foreignFromTT fn
= do execIO $ fmap (ioWrap . EConstant . I . round) getPOSIXTime
execApp env ctxt (EP _ fp _) (_:fn:fileStr:modeStr:rest)
| fp == mkfprim,
Just (FFun "fileOpen" _ _) <- foreignFromTT fn
= case (fileStr, modeStr) of
(EConstant (Str f), EConstant (Str mode)) ->
do f <- execIO $
catch (do let m = case mode of
"r" -> Right ReadMode
"w" -> Right WriteMode
"a" -> Right AppendMode
"rw" -> Right ReadWriteMode
"wr" -> Right ReadWriteMode
"r+" -> Right ReadWriteMode
_ -> Left ("Invalid mode for " ++ f ++ ": " ++ mode)
case fmap (openFile f) m of
Right h -> do h' <- h
hSetBinaryMode h' True
return $ Right (ioWrap (EHandle h'), tail rest)
Left err -> return $ Left err)
(\e -> let _ = ( e::SomeException)
in return $ Right (ioWrap (EPtr nullPtr), tail rest))
case f of
Left err -> execFail . Msg $ err
Right (res, rest) -> execApp env ctxt res rest
_ -> execFail . Msg $
"The arguments to fileOpen should be constant strings, but they were " ++
show fileStr ++ " and " ++ show modeStr ++
". Are all cases covered?"
execApp env ctxt (EP _ fp _) (_:fn:handle:rest)
| fp == mkfprim,
Just (FFun "fileEOF" _ _) <- foreignFromTT fn
= case handle of
EHandle h -> do eofp <- execIO $ hIsEOF h
let res = ioWrap (EConstant (I $ if eofp then 1 else 0))
execApp env ctxt res (tail rest)
_ -> execFail . Msg $
"The argument to fileEOF should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
execApp env ctxt (EP _ fp _) (_:fn:handle:rest)
| fp == mkfprim,
Just (FFun "fileClose" _ _) <- foreignFromTT fn
= case handle of
EHandle h -> do execIO $ hClose h
execApp env ctxt ioUnit (tail rest)
_ -> execFail . Msg $
"The argument to fileClose should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
execApp env ctxt (EP _ fp _) (_:fn:ptr:rest)
| fp == mkfprim,
Just (FFun "isNull" _ _) <- foreignFromTT fn
= case ptr of
EPtr p -> let res = ioWrap . EConstant . I $
if p == nullPtr then 1 else 0
in execApp env ctxt res (tail rest)
-- Handles will be checked as null pointers sometimes - but if we got a
-- real Handle, then it's valid, so just return 1.
EHandle h -> let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (tail rest)
-- A foreign-returned char* has to be tested for NULL sometimes
EConstant (Str s) -> let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (tail rest)
_ -> execFail . Msg $
"The argument to isNull should be a pointer or file handle or string, but it was " ++
show ptr ++
". Are all cases covered?"
-- Right now, there's no way to send command-line arguments to the executor,
-- so just return 0.
execApp env ctxt (EP _ fp _) (_:fn:rest)
| fp == mkfprim,
Just (FFun "idris_numArgs" _ _) <- foreignFromTT fn
= let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (tail rest)
execApp env ctxt f@(EP _ fp _) args@(ty:fn:xs) | fp == mkfprim
= case foreignFromTT fn of
Just (FFun f argTs retT) | length xs >= length argTs ->
do let (args', xs') = (take (length argTs) xs, -- foreign args
drop (length argTs + 1) xs) -- rest
res <- stepForeign (ty:fn:args')
case res of
Nothing -> fail $ "Could not call foreign function \"" ++ f ++
"\" with args " ++ show args
Just r -> return (mkEApp r xs')
Nothing -> return (mkEApp f args)
execApp env ctxt c@(EP (DCon _ arity _) n _) args =
do let args' = take arity args
let restArgs = drop arity args
execApp env ctxt (mkEApp c args') restArgs
execApp env ctxt c@(EP (TCon _ arity) n _) args =
do let args' = take arity args
let restArgs = drop arity args
execApp env ctxt (mkEApp c args') restArgs
execApp env ctxt f@(EP _ n _) args =
do let val = lookupDef n ctxt
case val of
[Function _ tm] -> fail "should already have been eval'd"
[TyDecl nt ty] -> return $ mkEApp f args
[Operator tp arity op] ->
if length args >= arity
then let args' = take arity args in
case getOp n args' of
Just res -> do r <- res
execApp env ctxt r (drop arity args)
Nothing -> return (mkEApp f args)
else return (mkEApp f args)
[CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
do rhs <- doExec env ctxt tm
execApp env ctxt rhs args
[CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] ->
do res <- execCase env ctxt ns sc args
return $ fromMaybe (mkEApp f args) res
thing -> return $ mkEApp f args
execApp env ctxt bnd@(EBind n b body) (arg:args) = do ret <- body arg
let (f', as) = unApplyV ret
execApp env ctxt f' (as ++ args)
execApp env ctxt app@(EApp _ _) args2 | (f, args1) <- unApplyV app = execApp env ctxt f (args1 ++ args2)
execApp env ctxt f args = return (mkEApp f args)
prs = sUN "prim__readString"
pbm = sUN "prim__believe_me"
pstd = sUN "prim__stdin"
mkfprim = sUN "mkForeignPrim"
pioret = sUN "prim_io_return"
piobind = sUN "prim_io_bind"
upio = sUN "unsafePerformPrimIO"
delay = sUN "Delay"
force = sUN "Force"
-- | Look up primitive operations in the global table and transform them into ExecVal functions
getOp :: Name -> [ExecVal] -> Maybe (Exec ExecVal)
getOp fn [_, _, x] | fn == pbm = Just (return x)
getOp fn [EP _ fn' _]
| fn == prs && fn' == pstd =
Just $ do line <- execIO getLine
return (EConstant (Str line))
getOp fn [EHandle h]
| fn == prs =
Just $ do contents <- execIO $ hGetLine h
return (EConstant (Str (contents ++ "\n")))
getOp n args = getPrim n primitives >>= flip applyPrim args
where getPrim :: Name -> [Prim] -> Maybe ([ExecVal] -> Maybe ExecVal)
getPrim n [] = Nothing
getPrim n ((Prim pn _ arity def _ _) : prims) | n == pn = Just $ execPrim def
| otherwise = getPrim n prims
execPrim :: ([Const] -> Maybe Const) -> [ExecVal] -> Maybe ExecVal
execPrim f args = EConstant <$> (mapM getConst args >>= f)
getConst (EConstant c) = Just c
getConst _ = Nothing
applyPrim :: ([ExecVal] -> Maybe ExecVal) -> [ExecVal] -> Maybe (Exec ExecVal)
applyPrim fn args = return <$> fn args
-- | Overall wrapper for case tree execution. If there are enough arguments, it takes them,
-- evaluates them, then begins the checks for matching cases.
execCase :: ExecEnv -> Context -> [Name] -> SC -> [ExecVal] -> Exec (Maybe ExecVal)
execCase env ctxt ns sc args =
let arity = length ns in
if arity <= length args
then do let amap = zip ns args
-- trace ("Case " ++ show sc ++ "\n in " ++ show amap ++"\n in env " ++ show env ++ "\n\n" ) $ return ()
caseRes <- execCase' env ctxt amap sc
case caseRes of
Just res -> Just <$> execApp (map (\(n, tm) -> (n, tm)) amap ++ env) ctxt res (drop arity args)
Nothing -> return Nothing
else return Nothing
-- | Take bindings and a case tree and examines them, executing the matching case if possible.
execCase' :: ExecEnv -> Context -> [(Name, ExecVal)] -> SC -> Exec (Maybe ExecVal)
execCase' env ctxt amap (UnmatchedCase _) = return Nothing
execCase' env ctxt amap (STerm tm) =
Just <$> doExec (map (\(n, v) -> (n, v)) amap ++ env) ctxt tm
execCase' env ctxt amap (Case sh n alts) | Just tm <- lookup n amap =
case chooseAlt tm alts of
Just (newCase, newBindings) ->
let amap' = newBindings ++ (filter (\(x,_) -> not (elem x (map fst newBindings))) amap) in
execCase' env ctxt amap' newCase
Nothing -> return Nothing
chooseAlt :: ExecVal -> [CaseAlt] -> Maybe (SC, [(Name, ExecVal)])
chooseAlt tm (DefaultCase sc : alts) | ok tm = Just (sc, [])
| otherwise = Nothing
where -- Default cases should only work on applications of constructors or on constants
ok (EApp f x) = ok f
ok (EP Bound _ _) = False
ok (EP Ref _ _) = False
ok _ = True
chooseAlt (EConstant c) (ConstCase c' sc : alts) | c == c' = Just (sc, [])
chooseAlt tm (ConCase n i ns sc : alts) | ((EP _ cn _), args) <- unApplyV tm
, cn == n = Just (sc, zip ns args)
| otherwise = chooseAlt tm alts
chooseAlt tm (_:alts) = chooseAlt tm alts
chooseAlt _ [] = Nothing
idrisType :: FType -> ExecVal
idrisType FUnit = EP Ref unitTy EErased
idrisType ft = EConstant (idr ft)
where idr (FArith ty) = AType ty
idr FString = StrType
idr FPtr = PtrType
data Foreign = FFun String [FType] FType deriving Show
call :: Foreign -> [ExecVal] -> Exec (Maybe ExecVal)
call (FFun name argTypes retType) args =
do fn <- findForeign name
maybe (return Nothing) (\f -> Just . ioWrap <$> call' f args retType) fn
where call' :: ForeignFun -> [ExecVal] -> FType -> Exec ExecVal
call' (Fun _ h) args (FArith (ATInt ITNative)) = do
res <- execIO $ callFFI h retCInt (prepArgs args)
return (EConstant (I (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT8))) = do
res <- execIO $ callFFI h retCChar (prepArgs args)
return (EConstant (B8 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT16))) = do
res <- execIO $ callFFI h retCWchar (prepArgs args)
return (EConstant (B16 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT32))) = do
res <- execIO $ callFFI h retCInt (prepArgs args)
return (EConstant (B32 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT64))) = do
res <- execIO $ callFFI h retCLong (prepArgs args)
return (EConstant (B64 (fromIntegral res)))
call' (Fun _ h) args (FArith ATFloat) = do
res <- execIO $ callFFI h retCDouble (prepArgs args)
return (EConstant (Fl (realToFrac res)))
call' (Fun _ h) args (FArith (ATInt ITChar)) = do
res <- execIO $ callFFI h retCChar (prepArgs args)
return (EConstant (Ch (castCCharToChar res)))
call' (Fun _ h) args FString = do res <- execIO $ callFFI h retCString (prepArgs args)
if res == nullPtr
then return (EPtr res)
else do hStr <- execIO $ peekCString res
return (EConstant (Str hStr))
call' (Fun _ h) args FPtr = EPtr <$> (execIO $ callFFI h (retPtr retVoid) (prepArgs args))
call' (Fun _ h) args FUnit = do _ <- execIO $ callFFI h retVoid (prepArgs args)
return $ EP Ref unitCon EErased
prepArgs = map prepArg
prepArg (EConstant (I i)) = argCInt (fromIntegral i)
prepArg (EConstant (B8 i)) = argCChar (fromIntegral i)
prepArg (EConstant (B16 i)) = argCWchar (fromIntegral i)
prepArg (EConstant (B32 i)) = argCInt (fromIntegral i)
prepArg (EConstant (B64 i)) = argCLong (fromIntegral i)
prepArg (EConstant (Fl f)) = argCDouble (realToFrac f)
prepArg (EConstant (Ch c)) = argCChar (castCharToCChar c) -- FIXME - castCharToCChar only safe for first 256 chars
-- Issue #1720 on the issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1720
prepArg (EConstant (Str s)) = argString s
prepArg (EPtr p) = argPtr p
prepArg other = trace ("Could not use " ++ take 100 (show other) ++ " as FFI arg.") undefined
foreignFromTT :: ExecVal -> Maybe Foreign
foreignFromTT t = case (unApplyV t) of
(_, [(EConstant (Str name)), args, ret]) ->
do argTy <- unEList args
argFTy <- sequence $ map getFTy argTy
retFTy <- getFTy ret
return $ FFun name argFTy retFTy
_ -> trace ("failed to construct ffun") Nothing
getFTy :: ExecVal -> Maybe FType
getFTy (EApp (EP _ (UN fi) _) (EP _ (UN intTy) _))
| fi == txt "FIntT" =
case str intTy of
"ITNative" -> Just (FArith (ATInt ITNative))
"ITChar" -> Just (FArith (ATInt ITChar))
"IT8" -> Just (FArith (ATInt (ITFixed IT8)))
"IT16" -> Just (FArith (ATInt (ITFixed IT16)))
"IT32" -> Just (FArith (ATInt (ITFixed IT32)))
"IT64" -> Just (FArith (ATInt (ITFixed IT64)))
_ -> Nothing
getFTy (EP _ (UN t) _) =
case str t of
"FFloat" -> Just (FArith ATFloat)
"FString" -> Just FString
"FPtr" -> Just FPtr
"FUnit" -> Just FUnit
_ -> Nothing
getFTy _ = Nothing
unEList :: ExecVal -> Maybe [ExecVal]
unEList tm = case unApplyV tm of
(nil, [_]) -> Just []
(cons, ([_, x, xs])) ->
do rest <- unEList xs
return $ x:rest
(f, args) -> Nothing
toConst :: Term -> Maybe Const
toConst (Constant c) = Just c
toConst _ = Nothing
stepForeign :: [ExecVal] -> Exec (Maybe ExecVal)
stepForeign (ty:fn:args) = let ffun = foreignFromTT fn
in case (call <$> ffun) of
Just f -> f args
Nothing -> return Nothing
stepForeign _ = fail "Tried to call foreign function that wasn't mkForeignPrim"
mapMaybeM :: (Functor m, Monad m) => (a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM f [] = return []
mapMaybeM f (x:xs) = do rest <- mapMaybeM f xs
maybe rest (:rest) <$> f x
findForeign :: String -> Exec (Maybe ForeignFun)
findForeign fn = do est <- getExecState
let libs = exec_dynamic_libs est
fns <- mapMaybeM getFn libs
case fns of
[f] -> return (Just f)
[] -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" not found"
return Nothing
fs -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" is ambiguous. Found " ++
show (length fs) ++ " occurrences."
return Nothing
where getFn lib = execIO $ catchIO (tryLoadFn fn lib) (\_ -> return Nothing)
#endif
|
andyarvanitis/Idris-dev
|
src/Idris/Core/Execute.hs
|
bsd-3-clause
| 26,978
| 0
| 6
| 10,127
| 240
| 153
| 87
| 27
| 1
|
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Contains monads which provide environment for references counting and
-- remembering.
module Toy.Exp.RefEnv
( MRef
, MRefId (..)
, MonadRefEnv (..)
, NoGcEnv (..)
) where
import Control.Monad.Error.Class (MonadError)
import qualified Control.Monad.State.Strict as St
import Control.Monad.Trans (MonadTrans)
import Control.Monad.Writer (MonadWriter, WriterT)
import Data.Conduit (ConduitM)
import Data.IORef (IORef)
import qualified Prelude
import Universum
-- | Innard beyond reference type.
type MRef = IORef
-- | Allows to destinguish different 'MRef's.
newtype MRefId = MRefId Int
deriving (Eq, Ord)
instance Show MRefId where
show (MRefId id) = "#" <> show id
-- | Defines how (and whether) to perform references counting and remember
-- allocated values.
class Monad m =>
MonadRefEnv exp m where
newMRef :: (MRefId -> IO exp) -> m exp
default newMRef
:: (MonadRefEnv exp n, MonadTrans t, t n ~ m)
=> (MRefId -> IO exp) -> m exp
newMRef = lift . newMRef
changeRefCounter
:: (forall a. Num a =>
a -> a -> a)
-> exp
-> m ()
default changeRefCounter
:: ( MonadRefEnv exp n
, MonadTrans t
, t n ~ m
) =>
(forall a. Num a =>
a -> a -> a) -> exp -> m ()
changeRefCounter e = lift . changeRefCounter e
checkNoRefs :: Proxy exp -> m ()
default checkNoRefs
:: (MonadRefEnv exp n, MonadTrans t, t n ~ m) => Proxy exp -> m ()
checkNoRefs = lift . checkNoRefs
instance MonadRefEnv e m => MonadRefEnv e (ReaderT __ m) where
instance MonadRefEnv e m => MonadRefEnv e (StateT __ m) where
instance MonadRefEnv e m => MonadRefEnv e (St.StateT __ m)
instance (MonadRefEnv e m, Monoid w) => MonadRefEnv e (WriterT w m)
instance MonadRefEnv e m => MonadRefEnv e (ExceptT __ m)
instance MonadRefEnv e m => MonadRefEnv e (MaybeT m)
instance MonadRefEnv e m => MonadRefEnv e (ConduitM __ __ m)
-- | Implementation which doesn't perform any garbage collection.
newtype NoGcEnv m a = NoGcEnv
{ getNoGcEnv :: m a
} deriving ( Functor
, Applicative
, Monad
, MonadIO
, MonadReader __
, MonadState __
, MonadWriter __
, MonadError __
)
instance MonadTrans NoGcEnv where
lift = NoGcEnv
instance MonadIO m => MonadRefEnv exp (NoGcEnv m) where
newMRef = liftIO . ($ MRefId 0)
changeRefCounter _ _ = return ()
checkNoRefs _ = return ()
|
Martoon-00/toy-compiler
|
src/Toy/Exp/RefEnv.hs
|
bsd-3-clause
| 2,914
| 0
| 14
| 938
| 809
| 429
| 380
| -1
| -1
|
module Module5.Task6 where
import Module5.Task5 (Log(..))
returnLog :: a -> Log a
returnLog = Log []
|
dstarcev/stepic-haskell
|
src/Module5/Task6.hs
|
bsd-3-clause
| 102
| 0
| 6
| 17
| 42
| 24
| 18
| 4
| 1
|
{-# LANGUAGE Arrows, OverloadedStrings #-}
module Main where
import FRP.Yampa
import FRP.Yampa.Utilities
import Data.Colour.SRGB
import Graphics
import Shapes
import Input
import System.Random (mkStdGen)
cubeX, cubeWidth, cubeHeight :: Double
cubeX = 100
cubeWidth = 30
cubeHeight = 30
pipeWidth, pipeGap :: Double
pipeWidth = 60
pipeGap = 200
cubeColour, pipeColour, skyColour, groundColour :: Colour Double
cubeColour = sRGB24 0xED 0xBA 0x00
pipeColour = sRGB24 0x1A 0xAF 0x5D
skyColour = sRGB24 0xAD 0xD4 0xF4
groundColour = sRGB24 0xCE 0xB1 0x71
winHeight, winWidth :: Double
winHeight = 600
winWidth = 300
groundHeight :: Double
groundHeight = winHeight / 8
tap :: SF AppInput (Event ())
tap = lbp
-- << State datatypes >> -------------------------------------------------------
data Game = Game { gameCube :: Cube
, gamePipe :: Pipe
}
initGame :: Game
initGame = Game initCube initPipe
data Cube = Cube { cubePosY :: Double -- ^ Cube's vertical position
, cubeVelY :: Double -- ^ Cube's vertical velocity
}
initCube :: Cube
initCube = Cube (winHeight / 2) 0
data Pipe = Pipe { positionX :: Double
, height :: Double
}
initPipe :: Pipe
initPipe = Pipe winWidth 300
-- < Cube signal functions > ---------------------------------------------------
-- | Falling Cube just falls down. Doesn't react to anything as can be seen from type.
fallingCube :: Cube -> SF a Cube
fallingCube (Cube p0 v0) = lift2 Cube pos vel
where vel = constant (-200) >>> imIntegral v0
pos = vel >>> imIntegral p0
-- | Yampy Cube flaps on a command received from AppInput
yampyCube :: Cube -> SF AppInput Cube
yampyCube cube0 = switch update (\(Cube p v) -> yampyCube (Cube p (v + 400)))
where update = proc inp -> do
cube <- fallingCube cube0 -< ()
tapEv <- tap -< inp
returnA -< (cube, tapEv `tag` cube)
-- < Pipe signal functions > ---------------------------------------------------
-- | Just a pipe. Moves from right to left.
pipe :: Pipe -> SF a Pipe
pipe (Pipe p0 h0) = pipeHeightGen >>> switch initial (\h -> pipe $ Pipe p0 h)
where initial = proc h -> do
p <- imIntegral p0 -< -100
ev <- edge -< (p < -pipeWidth)
returnA -< (Pipe p h0, ev `tag` h)
pipeHeightGen :: SF a Double
pipeHeightGen = noiseR (0 + groundHeight + 20, winHeight - pipeGap - 20)
(mkStdGen 3) -- FIXME: Make truly random
-- < The whole game > ----------------------------------------------------------
-- Demo consists of three stages:
-- 1. Intro -- Cube is freezed at initial position
intro :: SF a Game
intro = constant initGame
-- 2. Game -- Pipes appear, cube falls down flapping when user taps
game :: SF AppInput Game
game = lift2 Game (yampyCube initCube) (pipe initPipe)
-- 3. GameOver -- The screen is freezed displaying the state at the moment of
-- collision
gameOver :: Game -> SF AppInput Game
gameOver collisionState = constant collisionState
-- | We then switch between these stages
demo :: SF AppInput Game
demo = switch (intro &&& tap) $
\_ -> switch (game >>> isGameOver) $
\g -> switch (gameOver g &&& tap) $
\_ -> demo
where isGameOver = proc g -> do
collisionEvent <- edge <<< arr checkCollision -< g
returnA -< (g, collisionEvent `tag` g)
checkCollision :: Game -> Bool
checkCollision (Game (Cube cubeY _) (Pipe pipeX pipeHeight)) =
or [ collide (pipeHeight, pipeHeight)
, collide (winHeight, winHeight - pipeHeight - pipeGap)
, cubeY <= groundHeight + cubeHeight ]
where collide (y2, h2) = and [ cubeX + cubeWidth > pipeX
, cubeX < pipeX + pipeWidth
, cubeY > y2 - h2
, cubeY - cubeHeight < y2 ]
main :: IO ()
main = animate "Yampy cube" (round winWidth) (round winHeight)
(parseWinInput >>> ((demo >>^ render) &&& handleExit))
render :: Game -> Object
render (Game (Cube y _) (Pipe p h)) = scene ! colour_ skyColour
where scene = scene_ [ground, cube, bottomPipe, upperPipe]
cube = rectangle_ cubeWidth cubeHeight ! pos_ (cubeX, y)
! colour_ cubeColour
bottomPipe = rectangle_ pipeWidth h ! pos_ (p, h)
! colour_ pipeColour
upperPipe = rectangle_ pipeWidth (winHeight - h - pipeGap)
! pos_ (p, winHeight)
! colour_ pipeColour
ground = rectangle_ winWidth groundHeight ! pos_ (0, groundHeight)
! colour_ groundColour
handleExit :: SF AppInput Bool
handleExit = quitEvent >>> arr isEvent
|
pyrtsa/yampa-demos-template
|
src/Cube.hs
|
bsd-3-clause
| 4,989
| 3
| 14
| 1,532
| 1,332
| 715
| 617
| 99
| 1
|
module Main where
import D14Lib
import System.Environment (getArgs)
main :: IO ()
main = do
input <- head <$> getArgs
let g = grid input
putStrLn $ showGroups g
|
wfleming/advent-of-code-2016
|
2017/D14/app/PrintGroups.hs
|
bsd-3-clause
| 169
| 0
| 10
| 37
| 65
| 33
| 32
| 8
| 1
|
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2014 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE PatternGuards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module REPL.Haskeline where
import REPL.Command
import REPL.Monad
import REPL.Trie
import Control.Monad (when)
import Data.Char (isAlphaNum, isSpace)
import Data.Function (on)
import Data.List (isPrefixOf,sortBy)
import System.Console.Haskeline
import System.Directory(getAppUserDataDirectory,createDirectoryIfMissing)
import System.FilePath((</>))
import qualified Control.Monad.IO.Class as MTL
import qualified Control.Monad.Trans.Class as MTL
import qualified Control.Exception as X
-- | Haskeline-specific repl implementation.
--
-- XXX this needs to handle Ctrl-C, which at the moment will just cause
-- haskeline to exit. See the function 'withInterrupt' for more info on how to
-- handle this.
repl :: Maybe FilePath -> REPL () -> IO ()
repl mbBatch begin =
do settings <- setHistoryFile replSettings
runREPL isBatch (runInputTBehavior style settings body)
where
body = withInterrupt $ do
MTL.lift begin
loop
(isBatch,style) = case mbBatch of
Nothing -> (False,defaultBehavior)
Just path -> (True,useFile path)
loop = do
prompt <- MTL.lift getPrompt
mb <- handleInterrupt (return (Just "")) (getInputLines prompt [])
case mb of
Just line
| Just cmd <- parseCommand findCommand line -> do
continue <- MTL.lift $ do
handleInterrupt handleCtrlC (runCommand cmd)
shouldContinue
when continue loop
| otherwise -> loop
Nothing -> return ()
getInputLines prompt ls =
do mb <- getInputLine prompt
let newPropmpt = map (\_ -> ' ') prompt
case mb of
Nothing -> return Nothing
Just l | not (null l) && last l == '\\' ->
getInputLines newPropmpt (init l : ls)
| otherwise -> return $ Just $ unlines $ reverse $ l : ls
-- | Try to set the history file.
setHistoryFile :: Settings REPL -> IO (Settings REPL)
setHistoryFile ss =
do dir <- getAppUserDataDirectory "cryptol"
createDirectoryIfMissing True dir
return ss { historyFile = Just (dir </> "history") }
`X.catch` \(SomeException {}) -> return ss
-- | Haskeline settings for the REPL.
replSettings :: Settings REPL
replSettings = Settings
{ complete = cryptolCommand
, historyFile = Nothing
, autoAddHistory = True
}
-- Utilities -------------------------------------------------------------------
instance MTL.MonadIO REPL where
liftIO = io
instance MonadException REPL where
controlIO branchIO = REPL $ \ ref -> do
runBody <- branchIO $ RunIO $ \ m -> do
a <- unREPL m ref
return (return a)
unREPL runBody ref
-- Completion ------------------------------------------------------------------
-- | Completion for cryptol commands.
cryptolCommand :: CompletionFunc REPL
cryptolCommand cursor@(l,r)
| ":" `isPrefixOf` l'
, Just (cmd,rest) <- splitCommand l' = case findCommand cmd of
[c] | null rest && not (any isSpace l') -> do
return (l, [cmdComp cmd c])
| otherwise -> do
(rest',cs) <- cmdArgument (cBody c) (reverse (sanitize rest),r)
return (unwords [rest', reverse cmd],cs)
cmds ->
return (l, [ cmdComp l' c | c <- cmds ])
| otherwise = completeExpr cursor
where
l' = sanitize (reverse l)
-- | Generate a completion from a REPL command definition.
cmdComp :: String -> CommandDescr -> Completion
cmdComp prefix c = Completion
{ replacement = drop (length prefix) (cName c)
, display = cName c
, isFinished = True
}
-- | Dispatch to a completion function based on the kind of completion the
-- command is expecting.
cmdArgument :: CommandBody -> CompletionFunc REPL
cmdArgument ct cursor@(l,_) = case ct of
ExprArg _ -> completeExpr cursor
DeclsArg _ -> (completeExpr +++ completeType) cursor
ExprTypeArg _ -> (completeExpr +++ completeType) cursor
FilenameArg _ -> completeFilename cursor
ShellArg _ -> completeFilename cursor
OptionArg _ -> completeOption cursor
NoArg _ -> return (l,[])
-- | Complete a name from the expression environment.
completeExpr :: CompletionFunc REPL
completeExpr (l,_) = do
ns <- getExprNames
let n = reverse (takeWhile isIdentChar l)
vars = filter (n `isPrefixOf`) ns
return (l,map (nameComp n) vars)
-- | Complete a name from the type synonym environment.
completeType :: CompletionFunc REPL
completeType (l,_) = do
ns <- getTypeNames
let n = reverse (takeWhile isIdentChar l)
vars = filter (n `isPrefixOf`) ns
return (l,map (nameComp n) vars)
-- | Generate a completion from a prefix and a name.
nameComp :: String -> String -> Completion
nameComp prefix c = Completion
{ replacement = drop (length prefix) c
, display = c
, isFinished = True
}
isIdentChar :: Char -> Bool
isIdentChar c = isAlphaNum c || c `elem` "_\'"
-- | Join two completion functions together, merging and sorting their results.
(+++) :: CompletionFunc REPL -> CompletionFunc REPL -> CompletionFunc REPL
(as +++ bs) cursor = do
(_,acs) <- as cursor
(_,bcs) <- bs cursor
return (fst cursor, sortBy (compare `on` replacement) (acs ++ bcs))
-- | Complete an option from the options environment.
--
-- XXX this can do better, as it has access to the expected form of the value
completeOption :: CompletionFunc REPL
completeOption cursor@(l,_) = return (fst cursor, map comp opts)
where
n = reverse l
opts = lookupTrie n userOptions
comp opt = Completion
{ replacement = drop (length n) (optName opt)
, display = optName opt
, isFinished = False
}
|
TomMD/cryptol
|
cryptol/REPL/Haskeline.hs
|
bsd-3-clause
| 5,881
| 0
| 21
| 1,370
| 1,716
| 885
| 831
| 124
| 7
|
{-|
Module: Data.Astro.Utils
Description: Utility functions
Copyright: Alexander Ignatyev, 2016
Utility functions.
-}
module Data.Astro.Utils
(
fromFixed
, trunc
, fraction
, reduceToZeroRange
, toRadians
, fromRadians
, roundToN
, tropicalYearLen
)
where
import Data.Fixed(Fixed(MkFixed), HasResolution(resolution))
-- | Convert From Fixed to Fractional
fromFixed :: (Fractional a, HasResolution b) => Fixed b -> a
fromFixed fv@(MkFixed v) = (fromIntegral v) / (fromIntegral $ resolution fv)
-- | return the integral part of a number
-- almost the same as truncate but result type is Real
trunc :: RealFrac a => a -> a
trunc = fromIntegral . truncate
-- | Almost the same the properFraction function but result type
fraction :: (RealFrac a, Num b) => a -> (b, a)
fraction v = let (i, f) = (properFraction v)
in (fromIntegral i, f)
-- | Reduce to range from 0 to n
reduceToZeroRange :: RealFrac a => a -> a -> a
reduceToZeroRange r n =
let b = n - (trunc (n / r)) * r
in if b < 0 then b + r else b
-- | Convert from degrees to radians
toRadians :: Floating a => a -> a
toRadians deg = deg*pi/180
-- | Convert from radians to degrees
fromRadians :: Floating a => a -> a
fromRadians rad = rad*180/pi
-- | Round to a specified number of digits
roundToN :: RealFrac a => Int -> a -> a
roundToN n f = (fromInteger $ round $ f * factor) / factor
where factor = 10.0^^n
-- | Length of a tropical year in days
tropicalYearLen :: Double
tropicalYearLen = 365.242191
|
Alexander-Ignatyev/astro
|
src/Data/Astro/Utils.hs
|
bsd-3-clause
| 1,512
| 0
| 14
| 322
| 436
| 239
| 197
| 31
| 2
|
{-# LANGUAGE ViewPatterns, TupleSections, RecordWildCards, ScopedTypeVariables, PatternGuards #-}
module Action.Generate(actionGenerate) where
import Data.List.Extra
import System.FilePath
import System.Directory.Extra
import System.Time.Extra
import Data.Tuple.Extra
import Control.Exception.Extra
import Data.IORef
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.Text as T
import Control.Monad.Extra
import System.Console.CmdArgs.Verbosity
import Prelude
import Output.Items
import Output.Tags
import Output.Names
import Output.Types
import Input.Cabal
import Input.Haddock
import Input.Download
import Input.Reorder
import Input.Set
import Input.Item
import General.Util
import General.Store
import General.Str
import System.Mem
import System.IO
import GHC.Stats
import Action.CmdLine
import General.Conduit
{-
data GenList
= GenList_Package String -- a literally named package
| GenList_GhcPkg String -- command to run, or "" for @ghc-pkg list@
| GenList_Stackage String -- URL of stackage file, defaults to @http://www.stackage.org/lts/cabal.config@
| GenList_Dependencies String -- dependencies in a named .cabal file
| GenList_Sort String -- URL of file to sort by, defaults to @http://packdeps.haskellers.com/reverse@
data GenTags
= GenTags_GhcPkg String -- command to run, or "" for @ghc-pkg dump@
| GenTags_Diff FilePath -- a diff to apply to previous metadata
| GenTags_Tarball String -- tarball of Cabal files, defaults to http://hackage.haskell.org/packages/index.tar.gz
| GetTags_Cabal FilePath -- tarball to get tag information from
data GenData
= GenData_File FilePath -- a file containing package data
| GenData_Tarball String -- URL where a tarball of data files resides
* `hoogle generate` - generate for all things in Stackage based on Hackage information.
* `hoogle generate --source=file1.txt --source=local --source=stackage --source=hackage --source=tarball.tar.gz`
Which files you want to index. Currently the list on stackage, could be those locally installed, those in a .cabal file etc. A `--list` flag, defaults to `stackage=url`. Can also be `ghc-pkg`, `ghc-pkg=user` `ghc-pkg=global`. `name=p1`.
Extra metadata you want to apply. Could be a file. `+shake author:Neil-Mitchell`, `-shake author:Neil-Mitchel`. Can be sucked out of .cabal files. A `--tags` flag, defaults to `tarball=url` and `diff=renamings.txt`.
Where the haddock files are. Defaults to `tarball=hackage-url`. Can also be `file=p1.txt`. Use `--data` flag.
Defaults to: `hoogle generate --list=ghc-pkg --list=constrain=stackage-url`.
Three pieces of data:
* Which packages to index, in order.
* Metadata.
generate :: Maybe Int -> [GenList] -> [GenTags] -> [GenData] -> IO ()
-- how often to redownload, where to put the files
generate :: FilePath -> [(String, [(String, String)])] -> [(String, LBS.ByteString)] -> IO ()
generate output metadata = undefined
-}
-- -- generate all
-- @tagsoup -- generate tagsoup
-- @tagsoup filter -- search the tagsoup package
-- filter -- search all
actionGenerate :: CmdLine -> IO ()
actionGenerate Generate{..} = do
putStrLn "Starting generate"
createDirectoryIfMissing True $ takeDirectory database
downloadInputs $ takeDirectory database
(n,_) <- duration $ generate database debug include
putStrLn $ "Took " ++ showDuration n
generate :: FilePath -> Bool -> [String] -> IO ()
generate database debug args = do
-- fix up people using Hoogle 4 instructions
args <- if "all" `notElem` args then return args else do
putStrLn $ "Warning: 'all' argument is no longer required, and has been ignored."
return $ delete "all" args
-- peakMegabytesAllocated = 2
let input x = takeDirectory database </> "input-" ++ x
setStackage <- setStackage $ input "stackage.txt"
setPlatform <- setPlatform $ input "platform.txt"
setGHC <- setGHC $ input "platform.txt"
let want = if args /= [] then Set.fromList args else Set.unions [setStackage, setPlatform, setGHC]
-- peakMegabytesAllocated = 2
(cblErrs,cbl) <- timed "Reading Cabal" $ parseCabalTarball $ input "cabal.tar.gz"
let packageTags pkg =
[("set","included-with-ghc") | pkg `Set.member` setGHC] ++
[("set","haskell-platform") | pkg `Set.member` setPlatform] ++
[("set","stackage") | pkg `Set.member` setStackage] ++
maybe [] (map (both T.unpack) . cabalTags) (Map.lookup pkg cbl)
-- peakMegabytesAllocated = 21, currentBytesUsed = 6.5Mb
storeWriteFile database $ \store -> do
xs <- withBinaryFile (database `replaceExtension` "warn") WriteMode $ \warnings -> do
hSetEncoding warnings utf8
hPutStr warnings $ unlines cblErrs
nCblErrs <- evaluate $ length cblErrs
itemWarn <- newIORef 0
let warning msg = do modifyIORef itemWarn succ; hPutStrLn warnings msg
let consume :: Conduit (Int, (String, LStr)) IO (Maybe Target, Item)
consume = awaitForever $ \(i, (pkg, body)) -> do
timed ("[" ++ show i ++ "/" ++ show (Set.size want) ++ "] " ++ pkg) $
parseHoogle warning pkg body
writeItems store $ \items -> do
let packages = [ fakePackage name $ "Not in Stackage, so not searched.\n" ++ T.unpack cabalSynopsis
| (name,Cabal{..}) <- Map.toList cbl, name `Set.notMember` want]
(seen, xs) <- runConduit $
(sourceList =<< liftIO (tarballReadFiles $ input "hoogle.tar.gz")) =$=
mapC (first takeBaseName) =$=
filterC (flip Set.member want . fst) =$=
((fmap Set.fromList $ mapC fst =$= sinkList) |$|
(((zipFromC 1 =$= consume) >> when (null args) (sourceList packages))
=$= pipelineC 10 (items =$= sinkList)))
putStrLn $ "Packages not found: " ++ unwords (Set.toList $ want `Set.difference` seen)
when (Set.null seen) $
exitFail "No packages were found, aborting (use no arguments to index all of Stackage)"
itemWarn <- readIORef itemWarn
when (itemWarn > 0) $
putStrLn $ "Found " ++ show itemWarn ++ " warnings when processing items"
return xs
xs <- timed "Reodering items" $ reorderItems (\s -> maybe 1 (negate . cabalPopularity) $ Map.lookup s cbl) xs
timed "Writing tags" $ writeTags store (`Set.member` want) packageTags xs
timed "Writing names" $ writeNames store xs
timed "Writing types" $ writeTypes store (if debug then Just $ dropExtension database else Nothing) xs
whenM getGCStatsEnabled $ do
performGC
stats@GCStats{..} <- getGCStats
x <- getVerbosity
if x >= Loud then
print stats
else if x >= Normal then
putStrLn $ "Required " ++ show peakMegabytesAllocated ++ "Mb, " ++ show (currentBytesUsed `div` (1024*1024)) ++ "Mb currently used"
else
return ()
void $ evaluate xs
|
BartAdv/hoogle
|
src/Action/Generate.hs
|
bsd-3-clause
| 7,255
| 0
| 32
| 1,770
| 1,444
| 738
| 706
| 98
| 6
|
-- This module is necessary to avoid cyclic imports in some cases.
-- Unfortunately it leaks more than is necessary.
{-# LANGUAGE DeriveGeneric, OverloadedStrings, DeriveDataTypeable, TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module CommonTypes
( PendingActionsTrackerHandle(..)
, PendingActionsState(..)
, PendingOrder(..)
, BridgewalkerAccount(..)
, BridgewalkerAction(..)
, ClientHubHandle(..)
, ClientHubCommand(..)
, ClientStatus(..)
, ClientPendingTransaction(..)
, ClientPendingReason(..)
, ClientHubAnswer(..)
, LoggingHandle(..)
, Logger
, LoggingCmd(..)
, LogContent(..)
, LogEntry(..)
, QuoteData(..)
, PureQuoteData(..)
, ExchangeStatus(..)
, AmountType(..)
, confsNeededForSending
, SnapApp(..)
, SnapAppHandler
, heist
) where
import Control.Applicative
import Control.Concurrent
import Control.Lens hiding ((.=))
import Control.Monad
import Data.Aeson
import Data.Serialize
import Data.Time
import Data.Typeable
import GHC.Generics
import Snap.Snaplet
import Snap.Snaplet.Heist
import qualified Data.Sequence as S
import qualified Data.Text as T
import qualified Network.BitcoinRPC as RPC
newtype PendingActionsTrackerHandle = PendingActionsTrackerHandle
{ unPATH :: Chan () }
data PendingActionsState = PendingActionsState
{ pasSequence :: S.Seq BridgewalkerAction
, pasStatus :: String
, pasBTCImbalance :: Integer
, pasLastOrder :: Maybe PendingOrder
}
deriving (Show, Generic)
data PendingOrder = PendingOrder { poOpCount :: Integer
, poAdjustment :: Integer
}
deriving (Show, Generic)
data BridgewalkerAccount = BridgewalkerAccount { bAccount :: Integer }
deriving (Generic, Show, Eq, Ord, Typeable)
data BridgewalkerAction = DepositAction { baAmount :: Integer
, baAddress :: RPC.BitcoinAddress
}
| ConvertBTCAcount { baAmount :: Integer
, baAccount :: BridgewalkerAccount
}
| MarketAction
| SendPaymentAction { baAccount :: BridgewalkerAccount
, baRequestID :: Integer
, baAddress :: RPC.BitcoinAddress
, baAmountType :: AmountType
, baExpiration :: UTCTime
}
| PauseAction { baExpiration :: UTCTime }
| HeartbeatAction
deriving (Show, Generic)
data ClientHubAnswer = ForwardStatusToClient ClientStatus
| ForwardQuoteToClient Integer (Maybe QuoteData)
| ForwardSuccessfulSend
Integer (Maybe RPC.SerializedTransaction)
| ForwardFailedSend Integer T.Text
| SendPongToClient Integer
| CloseConnectionWithClient
data ExchangeStatus = ExchangeAvailable { esExchangeRate :: Integer }
| ExchangeUnavailable
data ClientHubCommand = RegisterClient { chcAccount :: BridgewalkerAccount
, chcAnswerChan :: Chan ClientHubAnswer
}
| RequestClientStatus { chcAccount ::
BridgewalkerAccount }
| RequestQuote { chcAccount :: BridgewalkerAccount
, chcRequestID :: Integer
, chcAddressM :: Maybe T.Text
, chcAmountType :: AmountType
}
| SendPayment { chcAccount :: BridgewalkerAccount
, chcRequestID :: Integer
, chcAddress :: T.Text
, chcAmountType :: AmountType
}
| ReceivedPing { chcAccount :: BridgewalkerAccount }
| CheckTimeouts
| ExchangeUpdate { chcExchangeStatus :: ExchangeStatus }
| SignalPossibleBitcoinEvents
| SignalAccountUpdates { chcAccounts ::
[BridgewalkerAccount] }
| SignalSuccessfulSend
{ chcAccount :: BridgewalkerAccount
, chcRequestID :: Integer
, chcSerializedTransactionM
:: Maybe RPC.SerializedTransaction
}
| SignalFailedSend
{ chcAccount :: BridgewalkerAccount
, chcRequestID :: Integer
, chcReason :: T.Text
}
newtype ClientHubHandle = ClientHubHandle { unCHH :: Chan ClientHubCommand }
data ClientStatus = ClientStatus { csUSDBalance :: Integer
, csBTCIn :: Integer
, csPrimaryBTCAddress :: T.Text
, csPendingTxs :: [ClientPendingTransaction]
, csExchangeAvailable :: Bool
, csExchangeRate :: Integer
}
deriving (Show)
data AmountType = AmountBasedOnBTC Integer
| AmountBasedOnUSDBeforeFees Integer
| AmountBasedOnUSDAfterFees Integer
deriving (Generic, Show)
instance Serialize AmountType
data QuoteData = QuoteData { qdBTC :: Integer
, qdUSDRecipient :: Integer
, qdUSDAccount :: Integer
, qdSufficientBalance :: Bool
}
deriving (Show)
data PureQuoteData = PureQuoteData { pqdBTC :: Integer
, pqdUSDRecipient :: Integer
, pqdUSDAccount :: Integer
}
deriving (Show)
data ClientPendingTransaction = ClientPendingTransaction
{ cptAmount :: Integer
, cptReason :: ClientPendingReason
}
deriving (Show, Eq)
data ClientPendingReason = TooFewConfirmations { cprConfs :: Integer }
| MarkerAddressLimitReached
{ cprMarkerAddress :: T.Text }
deriving (Show, Eq)
data LoggingCmd = PerformLogging LogContent
newtype LoggingHandle = LoggingHandle { unLH :: Chan LoggingCmd }
type Logger = LogContent -> IO ()
data LogContent = RebalancerFailure { lcInfo :: String }
| RebalancerStatus { lcRLevel :: Integer
, lcRWillAct :: Bool
, lcInfo :: String
}
| RebalancerAction { lcInfo :: String }
| DepositProcessed { lcAccount :: Integer
, lcInfo :: String
}
| SystemDepositProcessed { lcInfo :: String }
| LargeDeposit { lcAccount :: Integer
, lcInfo :: String
}
| BTCConvertedToFiat { lcAccount :: Integer
, lcInfo :: String
, lcImbalance :: Integer
}
| FiatConvertedToBTC { lcAccount :: Integer
, lcInfo :: String
}
| ImbalanceAdjustedAfterSending { lcInfo :: String
, lcImbalance :: Integer
}
| OneShotSellOrderPlaced { lcInfo :: String
, lcOpCount :: Integer
, lcAmount :: Integer
, lcImbalance :: Integer
}
| OneShotBuyOrderPlaced { lcInfo :: String
, lcOpCount :: Integer
, lcAmount :: Integer
, lcImbalance :: Integer
}
| OneShotOrderProbablySuccessful { lcInfo :: String
, lcAdjustment :: Integer
, lcImbalance :: Integer
}
| MtGoxLowBTCBalance { lcInfo :: String }
| MtGoxLowUSDBalance { lcInfo :: String }
| MtGoxError { lcInfo :: String }
| MtGoxStillOpenOrders { lcInfo :: String }
| MtGoxOrderBookUnavailable { lcInfo :: String }
| MtGoxOrderBookInsufficient { lcInfo :: String }
| BitcoindLowBTCBalance { lcInfo :: String }
| BTCSent { lcAccount :: Integer
, lcInfo :: String
}
| BTCSendNetworkOrParseError
{ lcAccount :: Integer
, lcAddress :: String
, lcAmount :: Integer
, lcInfo :: String
}
| BTCSendError { lcAccount :: Integer
, lcAddress :: String
, lcAmount :: Integer
, lcInfo :: String
}
| SendPaymentFailedCheck { lcAccount :: Integer
, lcAddress :: String
, lcInfo :: String
}
| InternalTransfer { lcAccount :: Integer
, lcOtherAccount :: Integer
, lcAmount :: Integer
, lcInfo :: String
}
| GuestAccountCreated { lcAccountName :: String }
| UserLoggedIn { lcAccount :: Integer }
| DisconnectedStaleClient
{ lcClientsDisconnected :: Integer
, lcClientsRemaining :: Integer
, lcInfo :: String
}
| WatchdogError { lcInfo :: String }
| LogMisc { lcInfo :: String }
deriving (Generic, Show)
data LogEntry = LogEntry { _leTimestamp :: UTCTime
, _leContent :: LogContent
}
deriving (Generic, Show)
instance Serialize LogContent
instance Serialize LogEntry
instance ToJSON ClientPendingReason where
toJSON (TooFewConfirmations confs) =
object [ "type" .= ("too_few_confirmations" :: T.Text)
, "confirmations" .= confs
]
toJSON (MarkerAddressLimitReached markerAddress) =
object [ "type" .= ("marker_address_limit_reached" :: T.Text)
, "marker_address" .= markerAddress
]
instance ToJSON ClientPendingTransaction where
toJSON cpt@ClientPendingTransaction{} =
let amount = cptAmount cpt
reason = cptReason cpt
in object [ "amount" .= amount
, "reason" .= reason
]
instance ToJSON ClientStatus where
toJSON cs@ClientStatus{} =
let usdBalance = csUSDBalance cs
btcIn = csBTCIn cs
pendingTxs = csPendingTxs cs
primaryBTCAddress = csPrimaryBTCAddress cs
exchangeAvailable = csExchangeAvailable cs
exchangeRate = csExchangeRate cs
in object [ "usd_balance" .= usdBalance
, "btc_in" .= btcIn
, "primary_btc_address" .= primaryBTCAddress
, "pending_txs" .= pendingTxs
, "exchange_available" .= exchangeAvailable
, "exchange_rate" .= exchangeRate
]
instance Serialize Day where
put = put . toModifiedJulianDay
get = ModifiedJulianDay <$> get
instance Serialize DiffTime where
put = put . toRational
get = fromRational <$> get
instance Serialize UTCTime where
put timestamp = put (utctDay timestamp) >> put (utctDayTime timestamp)
get = liftM2 UTCTime get get
instance Serialize BridgewalkerAccount
instance Serialize BridgewalkerAction
instance Serialize PendingOrder
instance Serialize PendingActionsState
data SnapApp = SnapApp
{ _heist :: Snaplet (Heist SnapApp)
}
makeLenses ''SnapApp
instance HasHeist SnapApp where
heistLens = subSnaplet heist
type SnapAppHandler = Handler SnapApp SnapApp
confsNeededForSending :: Integer
confsNeededForSending = 3
|
javgh/bridgewalker
|
src/CommonTypes.hs
|
bsd-3-clause
| 13,764
| 0
| 11
| 6,489
| 2,086
| 1,257
| 829
| 251
| 1
|
{-# LANGUAGE DeriveGeneric #-}
module HipChat.Types.ExternalPage where
import Data.Aeson
import Data.Aeson.Casing
import Data.Text (Text)
import GHC.Generics
import HipChat.Types.Name
data ExternalPage = ExternalPage
{ externalPageKey :: Text
, externalPageName :: Name
, externalPageUrl :: Text
} deriving (Eq, Generic, Show)
instance ToJSON ExternalPage where
toJSON = genericToJSON $ aesonDrop 12 camelCase
instance FromJSON ExternalPage where
parseJSON = genericParseJSON $ aesonDrop 12 camelCase
|
oswynb/hipchat-hs
|
lib/HipChat/Types/ExternalPage.hs
|
bsd-3-clause
| 582
| 0
| 8
| 142
| 126
| 73
| 53
| 16
| 0
|
-------------------------------------------------------------------------------
--
-- | Main API for compiling plain Haskell source code.
--
-- This module implements compilation of a Haskell source. It is
-- /not/ concerned with preprocessing of source files; this is handled
-- in "DriverPipeline".
--
-- There are various entry points depending on what mode we're in:
-- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and
-- "interactive" mode (GHCi). There are also entry points for
-- individual passes: parsing, typechecking/renaming, desugaring, and
-- simplification.
--
-- All the functions here take an 'HscEnv' as a parameter, but none of
-- them return a new one: 'HscEnv' is treated as an immutable value
-- from here on in (although it has mutable components, for the
-- caches).
--
-- Warning messages are dealt with consistently throughout this API:
-- during compilation warnings are collected, and before any function
-- in @HscMain@ returns, the warnings are either printed, or turned
-- into a real compialtion error if the @-Werror@ flag is enabled.
--
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
--
-------------------------------------------------------------------------------
module Language.Haskell.Liquid.Desugar710.HscMain (hscDesugarWithLoc) where
import Language.Haskell.Liquid.Desugar710.Desugar (deSugarWithLoc)
import Prelude hiding (error)
import Module
import Lexer
import TcRnMonad
import ErrUtils
import HscTypes
import Bag
import Exception
-- -----------------------------------------------------------------------------
getWarnings :: Hsc WarningMessages
getWarnings = Hsc $ \_ w -> return (w, w)
clearWarnings :: Hsc ()
clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
logWarnings :: WarningMessages -> Hsc ()
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
--
-- | Convert a typechecked module to Core
hscDesugarWithLoc :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
hscDesugarWithLoc hsc_env mod_summary tc_result =
runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
hsc_env <- getHscEnv
r <- ioMsgMaybe $
{-# SCC "deSugar" #-}
deSugarWithLoc hsc_env mod_location tc_result
-- always check -Werror after desugaring, this is the last opportunity for
-- warnings to arise before the backend.
handleWarnings
return r
getHscEnv :: Hsc HscEnv
getHscEnv = Hsc $ \e w -> return (e, w)
handleWarnings :: Hsc ()
handleWarnings = do
dflags <- getDynFlags
w <- getWarnings
liftIO $ printOrThrowWarnings dflags w
clearWarnings
ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
ioMsgMaybe ioA = do
((warns,errs), mb_r) <- liftIO ioA
logWarnings warns
case mb_r of
Nothing -> throwErrors errs
Just r -> return r
|
ssaavedra/liquidhaskell
|
src/Language/Haskell/Liquid/Desugar710/HscMain.hs
|
bsd-3-clause
| 3,000
| 0
| 10
| 518
| 511
| 282
| 229
| 44
| 2
|
module Main where
import Test.DocTest
--import Test.QuickCheck
main :: IO ()
main = doctest [ "src/Lambda/DataType.hs"
]
|
ocean0yohsuke/Simply-Typed-Lambda
|
test/doctests.hs
|
bsd-3-clause
| 138
| 0
| 6
| 34
| 31
| 18
| 13
| 4
| 1
|
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances #-}
{- |
Module : ./THF/StaticAnalysisTHF.hs
Description : Static analysis for THF
Copyright : (c) A. Tsogias, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Alexis.Tsogias@dfki.de
Stability : provisional
Portability : portable
Static analysis for THF.
NOTE: This implementation covers only THF0!
-}
module THF.StaticAnalysisTHF (basicAnalysis) where
import THF.As as As
import THF.Cons
import THF.Print ()
import THF.Sign
import THF.Poly (type_check)
import THF.Utils (thfTopLevelTypeToType)
import Common.AS_Annotation
import Common.GlobalAnnotations
import Common.Result
import Common.ExtSign
import Common.Lib.State
import Common.DocUtils
import Control.Monad
import qualified Data.Map as Map
import qualified Data.Set as Set
{- -----------------------------------------------------------------------------
Questions:
how to handle SysType in isTypeConsistent?
Todo:
find out what fi_domain, fi_predicates and fi_functors are and try
to somehow support them
----------------------------------------------------------------------------- -}
-- The main method for the static analysis
basicAnalysis :: (BasicSpecTHF, SignTHF, GlobalAnnos) ->
Result (BasicSpecTHF, ExtSign SignTHF SymbolTHF, [Named THFFormula])
basicAnalysis (bs@(BasicSpecTHF bs1), sig1, _) =
let (diag1, bs2) = filterBS [] bs1
(diag2, sig2, syms) = execState (fillSig bs2) (diag1, sig1, Set.empty)
(diag3, ns) = getSentences bs2 (diag2, [])
in do
type_check (types sig2) (consts sig2) ns
Result (reverse diag3) $ Just (bs, ExtSign sig2 syms, ns)
{- This functions delets all Comments and Includes because they are not needed
for the static analysis
The diagnosis list has a reverted order! -}
filterBS :: [Diagnosis] -> [TPTP_THF] -> ([Diagnosis], [TPTP_THF])
filterBS d [] = (d, [])
filterBS d (t : rt) = case t of
TPTP_Include i -> let ds = mkDiag Warning "Include will be ignored." i
in filterBS (ds : d) rt
TPTP_Comment _ -> filterBS d rt
TPTP_Defined_Comment _ -> filterBS d rt
TPTP_System_Comment _ -> filterBS d rt
TPTP_Header _ -> filterBS d rt
_ -> let (diag, thf) = filterBS d rt
in (diag, t : thf)
-- Append the Signature by the Types and Constants given inside the basic spec
fillSig :: [TPTP_THF] -> State ([Diagnosis], SignTHF, Set.Set SymbolTHF) ()
fillSig [] = return ()
fillSig bs = mapM_ fillSingleType bs >> mapM_ fillSingleConst bs
where
fillSingleType t = case t of
TPTP_THF_Annotated_Formula n fr tf a -> case fr of
Type ->
when (isKind tf) $ case makeKind tf of
Right d -> appandDiag d
Left (k, c) -> insertType c n k a
_ -> return ()
_ -> return ()
fillSingleConst t = case t of
TPTP_THF_Annotated_Formula n fr tf a -> case fr of
Type ->
unless (isKind tf) $ case makeType tf of
Right d -> appandDiag d
Left (ty, c) -> insertConst c n ty a
_ -> return ()
_ -> return ()
{- Append the Diagnosis-List by the given Diagnosis
The new diag will be put on top of the existing list. -}
appandDiag :: Diagnosis -> State ([Diagnosis], SignTHF, Set.Set SymbolTHF) ()
appandDiag d = modify (\ (diag, s, syms) -> (d : diag, s, syms))
-- insert the given type into the Signature
insertType :: Constant -> As.Name -> Kind -> Annotations
-> State ([Diagnosis], SignTHF, Set.Set SymbolTHF) ()
insertType c n k a = do
(diag, sig, syms) <- get
if sigHasConstSymbol c sig then appandDiag $ mkDiag Error
"Duplicate definition of a symbol as a type constant. Symbol: " c
else
if sigHasTypeSymbol c sig then
unless (sigHasSameKind c k sig) $ appandDiag $
mkDiag Error ("A type with the same identifier"
++ "but another Kind is already inside the signature") c
else do -- everythign is fine
let ti = TypeInfo { typeId = c, typeName = n, typeKind = k
, typeAnno = a }
sym = Symbol { symId = c, symName = n, symType = ST_Type k }
put (diag, sig { types = Map.insert c ti (types sig)
, symbols = Map.insert c sym (symbols sig) }
, Set.insert sym syms)
-- insert the given constant into the Signature
insertConst :: Constant -> As.Name -> Type -> Annotations
-> State ([Diagnosis], SignTHF, Set.Set SymbolTHF) ()
insertConst c n t a = do
(_, sig, _) <- get
if sigHasTypeSymbol c sig then (appandDiag $ mkDiag Error
"Duplicate definition of a symbol as a type constant. Symbol: " c)
else do
isTypeConsistent t
if sigHasConstSymbol c sig then
unless (sigHasSameType c t sig) $ appandDiag $ mkDiag Error
("A constant with the same identifier but another " ++
"type is already inside the signature") c
else -- everything is fine
let ci = ConstInfo { constId = c, constName = n, constType = t
, constAnno = a }
sym = Symbol { symId = c, symName = n
, symType = ST_Const t }
in do
(diag', sig', syms') <- get
put (diag', sig' { consts = Map.insert c ci (consts sig')
, symbols = Map.insert c sym (symbols sig') }
, Set.insert sym syms')
-- Check if a type symbol is already inside the sig
sigHasTypeSymbol :: Constant -> SignTHF -> Bool
sigHasTypeSymbol c sig = Map.member c (types sig)
{- This Method is ment to be used after sigHasTypeSymbol
Check if a type symbol with the same kind is inside the Sig
If this is not the case me have a problem! -}
sigHasSameKind :: Constant -> Kind -> SignTHF -> Bool
sigHasSameKind c k sig = typeKind (types sig Map.! c) == k
-- Check if a const symbol is already inside the sig
sigHasConstSymbol :: Constant -> SignTHF -> Bool
sigHasConstSymbol c sig = Map.member c (consts sig)
{- This Method is ment to be used after sigHasConstSymbol
Check if a const symbol with the same type is inside the Sig
If this is not the case me have a problem! -}
sigHasSameType :: Constant -> Type -> SignTHF -> Bool
sigHasSameType c t sig = constType (consts sig Map.! c) == t
{- check if all cTypes inside the given Type are elements of the signaure.
Nothing means that everything is fine, otherwise Just diag will be returned. -}
isTypeConsistent :: Type -> State ([Diagnosis], SignTHF, Set.Set SymbolTHF) ()
isTypeConsistent t = do
(_, sig, _) <- get
case t of
MapType t1 t2 -> do
isTypeConsistent t1
isTypeConsistent t2
ParType t1 -> isTypeConsistent t1
CType c -> when (not (sigHasTypeSymbol c sig))
(do
insertType c (N_Atomic_Word c) Kind Null
appandDiag $ mkDiag Warning "Unknown type: " c)
ProdType ts -> mapM_ isTypeConsistent ts
_ -> return ()
-- SType _ -> ... -- how to handle these?
{- -----------------------------------------------------------------------------
Extract the sentences from the basic spec
----------------------------------------------------------------------------- -}
{- Get all sentences from the content of the BasicSpecTH
The diag list has a reverted order. -}
getSentences :: [TPTP_THF] -> ([Diagnosis], [Named THFFormula])
-> ([Diagnosis], [Named THFFormula])
getSentences [] dn = dn
getSentences (t : rt) dn@(d, ns) = case t of
TPTP_THF_Annotated_Formula _ fr _ _ -> case fr of
Type -> getSentences rt dn
Unknown ->
let diag = mkDiag Warning
"THFFormula with role \'unknown\' will be ignored." t
in getSentences rt (diag : d, ns)
Plain ->
let diag = mkDiag Warning
"THFFormula with role \'plain\' will be ignored." t
in getSentences rt (diag : d, ns)
Fi_Domain ->
let diag = mkDiag Warning
"THFFormula with role \'fi_domain\' will be ignored." t
in getSentences rt (diag : d, ns)
Fi_Functors ->
let diag = mkDiag Warning
"THFFormula with role \'fi_functors\' will be ignored." t
in getSentences rt (diag : d, ns)
Fi_Predicates ->
let diag = mkDiag Warning
"THFFormula with role \'fi_predicates\' will be ignored." t
in getSentences rt (diag : d, ns)
Assumption ->
let diag = mkDiag Warning
"THFFormula with role \'assumption\' will be ignored." t
in getSentences rt (diag : d, ns)
_ ->
let (d1, ns1) = getSentences rt dn
in (d1, tptpthfToNS t : ns1)
_ -> getSentences rt dn
{- Precondition: The formulaRole must not be Type, Unknown, Plain, Fi_Domain
Fi_Functors, Fi_Predicates or Assumption
(They are filtered out in getSentences) -}
tptpthfToNS :: TPTP_THF -> Named THFFormula
tptpthfToNS f =
let s = makeNamed (show $ pretty $ nameAF f) (thfFormulaAF f)
t = s { isAxiom = False }
w = s { wasTheorem = True }
in case formulaRoleAF f of
Definition -> s { isDef = True }
Conjecture -> t
Negated_Conjecture -> t
Theorem -> w
Lemma -> w
Hypothesis -> t
_ -> s -- { isAxiom = True, isDef = False, wasTheorem = False }
{- -----------------------------------------------------------------------------
Get the Kind of a type
----------------------------------------------------------------------------- -}
makeKind :: THFFormula -> Either (Kind, Constant) Diagnosis
makeKind t = maybe (Right $ mkDiag Error "Error while parsing the kind of:" t)
Left (thfFormulaToKind t)
thfFormulaToKind :: THFFormula -> Maybe (Kind, Constant)
thfFormulaToKind (T0F_THF_Typed_Const tc) = thfTypedConstToKind tc
thfFormulaToKind _ = Nothing
thfTypedConstToKind :: THFTypedConst -> Maybe (Kind, Constant)
thfTypedConstToKind (T0TC_THF_TypedConst_Par tcp) = thfTypedConstToKind tcp
thfTypedConstToKind (T0TC_Typed_Const c tlt) =
maybe Nothing (\ k -> Just (k, c))
(thfTopLevelTypeToKind tlt)
thfTopLevelTypeToKind :: THFTopLevelType -> Maybe Kind
thfTopLevelTypeToKind tlt = case tlt of
T0TLT_THF_Binary_Type bt -> thfBinaryTypeToKind bt
T0TLT_Defined_Type _ -> Just Kind
_ -> Nothing
thfBinaryTypeToKind :: THFBinaryType -> Maybe Kind
thfBinaryTypeToKind bt = case bt of
T0BT_THF_Binary_Type_Par btp -> thfBinaryTypeToKind btp
_ -> Nothing
{- -----------------------------------------------------------------------------
Get the Type of a constant
----------------------------------------------------------------------------- -}
makeType :: THFFormula -> Either (Type, Constant) Diagnosis
makeType t = maybe (Right $ mkDiag Error "Error while parsing the type of:" t)
Left (thfFormulaToType t)
thfFormulaToType :: THFFormula -> Maybe (Type, Constant)
thfFormulaToType (T0F_THF_Typed_Const tc) = thfTypedConstToType tc
thfFormulaToType _ = Nothing
thfTypedConstToType :: THFTypedConst -> Maybe (Type, Constant)
thfTypedConstToType (T0TC_THF_TypedConst_Par tcp) = thfTypedConstToType tcp
thfTypedConstToType (T0TC_Typed_Const c tlt) =
maybe Nothing (\ t -> Just (t, c))
(thfTopLevelTypeToType tlt)
{- -----------------------------------------------------------------------------
Check if a THFFormula is a Type definition
----------------------------------------------------------------------------- -}
isKind :: THFFormula -> Bool
isKind tf = case tf of
T0F_THF_Typed_Const tc -> thfTypedConstIsKind tc
_ -> False
thfTypedConstIsKind :: THFTypedConst -> Bool
thfTypedConstIsKind tc = case tc of
T0TC_THF_TypedConst_Par tcp -> thfTypedConstIsKind tcp
T0TC_Typed_Const _ tlt -> thfTopLevelTypeIsKind tlt
thfTopLevelTypeIsKind :: THFTopLevelType -> Bool
thfTopLevelTypeIsKind tlt = case tlt of
T0TLT_THF_Binary_Type bt -> thfBinaryTypeIsKind bt
T0TLT_Defined_Type dt -> thfDefinedTypeIsKind dt
_ -> False
thfDefinedTypeIsKind :: DefinedType -> Bool
thfDefinedTypeIsKind dt = case dt of
DT_tType -> True
_ -> False
thfBinaryTypeIsKind :: THFBinaryType -> Bool
thfBinaryTypeIsKind bt = case bt of
T0BT_THF_Binary_Type_Par btp -> thfBinaryTypeIsKind btp
_ -> False
|
spechub/Hets
|
THF/StaticAnalysisTHF.hs
|
gpl-2.0
| 12,733
| 0
| 21
| 3,401
| 3,080
| 1,588
| 1,492
| 217
| 9
|
{-# LANGUAGE CPP, MultiParamTypeClasses, TypeSynonymInstances
, FlexibleInstances #-}
{- |
Module : ./CASL/Logic_CASL.hs
Description : Instance of class Logic for the CASL logic
Copyright : (c) Klaus Luettich, Uni Bremen 2002-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : till@informatik.uni-bremen.de
Stability : provisional
Portability : non-portable (imports Logic.Logic)
Instance of class Logic for the CASL logic
Also the instances for Syntax and Category.
-}
module CASL.Logic_CASL where
import ATC.ProofTree ()
import CASL.AS_Basic_CASL
import CASL.Parse_AS_Basic
import CASL.Kif
import CASL.Kif2CASL
import CASL.Fold
import CASL.ToDoc
import CASL.ToItem (bsToItem)
import CASL.SymbolParser
import CASL.MapSentence
import CASL.Amalgamability
import CASL.ATC_CASL ()
import CASL.Sublogic as SL
import CASL.Sign
import CASL.StaticAna
import CASL.ColimSign
import CASL.Morphism
import CASL.SymbolMapAnalysis
import CASL.Taxonomy
import CASL.Simplify
import CASL.SimplifySen
import CASL.CCC.FreeTypes
import CASL.CCC.OnePoint () -- currently unused
import CASL.Qualify
import CASL.Quantification
import qualified CASL.OMDocImport as OMI
import CASL.OMDocExport
import CASL.Freeness
-- test
import CASL.Formula (formula)
#ifdef UNI_PACKAGE
import CASL.QuickCheck
#endif
import Common.ProofTree
import Common.Consistency
import Common.DocUtils
import Data.Monoid
import qualified Data.Set as Set
import Logic.Logic
data CASL = CASL deriving Show
instance Language CASL where
description _ = unlines
[ "CASL - the Common algebraic specification language"
, "This logic is subsorted partial first-order logic"
, " with sort generation constraints"
, "See the CASL User Manual, LNCS 2900, Springer Verlag"
, "and the CASL Reference Manual, LNCS 2960, Springer Verlag"
, "See also http://www.cofi.info/CASL.html"
, ""
, "Abbreviations of sublogic names indicate the following feature:"
, " Sub -> with subsorting"
, " Sul -> with a locally filtered subsort relation"
, " P -> with partial functions"
, " C -> with sort generation constraints"
, " eC -> C without renamings"
, " sC -> C with injective constructors"
, " seC -> sC and eC"
, " FOL -> first order logic"
, " FOAlg -> FOL without predicates"
, " Horn -> positive conditional logic"
, " GHorn -> generalized Horn"
, " GCond -> GHorn without predicates"
, " Cond -> Horn without predicates"
, " Atom -> atomic logic"
, " Eq -> Atom without predicates"
, " = -> with equality"
, ""
, "Examples:"
, " SubPCFOL= -> the CASL logic itself"
, " FOAlg= -> first order algebra (without predicates)"
, " SubPHorn= -> the positive conditional fragement of CASL"
, " SubPAtom -> the atomic subset of CASL"
, " SubPCAtom -> SubPAtom with sort generation constraints"
, " Eq= -> classical equational logic" ]
type CASLBasicSpec = BASIC_SPEC () () ()
trueC :: a -> b -> Bool
trueC _ _ = True
instance (Ord f, Ord e, Ord m, MorphismExtension e m) =>
Category (Sign f e) (Morphism f e m) where
ide sig = idMor (ideMorphismExtension $ extendedInfo sig) sig
inverse = inverseMorphism inverseMorphismExtension
composeMorphisms = composeM composeMorphismExtension
dom = msource
cod = mtarget
isInclusion = isInclusionMorphism isInclusionMorphismExtension
legal_mor = legalMor
instance Monoid (BASIC_SPEC b s f) where
mempty = Basic_spec []
mappend (Basic_spec l1) (Basic_spec l2) = Basic_spec $ l1 ++ l2
-- abstract syntax, parsing (and printing)
instance Syntax CASL CASLBasicSpec
Symbol SYMB_ITEMS SYMB_MAP_ITEMS
where
parsersAndPrinters CASL = addSyntax "KIF"
(const $ fmap kif2CASL kifBasic, pretty)
$ makeDefault (basicSpec [], pretty)
parseSingleSymbItem CASL = Just $ symbItem []
parse_symb_items CASL = Just $ symbItems []
parse_symb_map_items CASL = Just $ symbMapItems []
toItem CASL = bsToItem
symb_items_name CASL = symbItemsName
-- lattices (for sublogics)
instance Lattice a => SemiLatticeWithTop (CASL_SL a) where
lub = sublogics_max
top = SL.top
class Lattice a => MinSL a f where
minSL :: f -> CASL_SL a
instance MinSL () () where
minSL () = bottom
class NameSL a where
nameSL :: a -> String
instance NameSL () where
nameSL _ = ""
class Lattice a => ProjForm a f where
projForm :: CASL_SL a -> f -> Maybe (FORMULA f)
instance Lattice a => ProjForm a () where
projForm _ = Just . ExtFORMULA
class (Lattice a, ProjForm a f) => ProjSigItem a s f where
projSigItems :: CASL_SL a -> s -> (Maybe (SIG_ITEMS s f), [SORT])
instance (Lattice a, ProjForm a f) => ProjSigItem a () f where
projSigItems _ s = (Just $ Ext_SIG_ITEMS s, [])
class (Lattice a, ProjForm a f) => ProjBasic a b s f where
projBasicItems :: CASL_SL a -> b -> (Maybe (BASIC_ITEMS b s f), [SORT])
instance (Lattice a, ProjForm a f, ProjSigItem a s f)
=> ProjBasic a () s f where
projBasicItems _ b = (Just $ Ext_BASIC_ITEMS b, [])
instance (NameSL a) => SublogicName (CASL_SL a) where
sublogicName = sublogics_name nameSL
instance (MinSL a f, MinSL a s, MinSL a b) =>
MinSublogic (CASL_SL a) (BASIC_SPEC b s f) where
minSublogic = sl_basic_spec minSL minSL minSL
instance MinSL a f => MinSublogic (CASL_SL a) (FORMULA f) where
minSublogic = sl_sentence minSL
instance Lattice a => MinSublogic (CASL_SL a) SYMB_ITEMS where
minSublogic = sl_symb_items
instance Lattice a => MinSublogic (CASL_SL a) SYMB_MAP_ITEMS where
minSublogic = sl_symb_map_items
instance MinSL a e => MinSublogic (CASL_SL a) (Sign f e) where
minSublogic = sl_sign minSL
instance MinSL a e => MinSublogic (CASL_SL a) (Morphism f e m) where
minSublogic = sl_morphism minSL
instance Lattice a => MinSublogic (CASL_SL a) Symbol where
minSublogic = sl_symbol
instance (MinSL a f, MinSL a s, MinSL a b, ProjForm a f,
ProjSigItem a s f, ProjBasic a b s f) =>
ProjectSublogic (CASL_SL a) (BASIC_SPEC b s f) where
projectSublogic = pr_basic_spec projBasicItems projSigItems projForm
instance Lattice a => ProjectSublogicM (CASL_SL a) SYMB_ITEMS where
projectSublogicM = pr_symb_items
instance Lattice a => ProjectSublogicM (CASL_SL a) SYMB_MAP_ITEMS where
projectSublogicM = pr_symb_map_items
instance MinSL a e => ProjectSublogic (CASL_SL a) (Sign f e) where
projectSublogic = pr_sign
instance MinSL a e => ProjectSublogic (CASL_SL a) (Morphism f e m) where
projectSublogic = pr_morphism
instance Lattice a => ProjectSublogicM (CASL_SL a) Symbol where
projectSublogicM = pr_symbol
-- CASL logic
instance Sentences CASL CASLFORMULA CASLSign CASLMor Symbol where
map_sen CASL m = return . mapSen (const id) m
negation CASL = negateFormula
sym_of CASL = symOf
mostSymsOf CASL = sigSymsOf
symmap_of CASL = morphismToSymbMap
sym_name CASL = symName
symKind CASL = show . pretty . symbolKind . symbType
symsOfSen CASL _ = Set.toList
. foldFormula (symbolsRecord $ const Set.empty)
simplify_sen CASL = simplifyCASLSen
print_named CASL = printTheoryFormula
instance StaticAnalysis CASL CASLBasicSpec CASLFORMULA
SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol where
basic_analysis CASL = Just basicCASLAnalysis
sen_analysis CASL = Just cASLsen_analysis
stat_symb_map_items CASL = statSymbMapItems
stat_symb_items CASL = statSymbItems
signature_colimit CASL diag = return $ signColimit diag extCASLColimit
quotient_term_algebra CASL = quotientTermAlgebra
ensures_amalgamability CASL (opts, diag, sink, desc) =
ensuresAmalgamability opts diag sink desc
qualify CASL = qualifySig
symbol_to_raw CASL = symbolToRaw
id_to_raw CASL = idToRaw
matches CASL = CASL.Morphism.matches
is_transportable CASL = isSortInjective
is_injective CASL = isInjective
empty_signature CASL = emptySign ()
add_symb_to_sign CASL = addSymbToSign
signature_union CASL s = return . addSig const s
signatureDiff CASL s = return . diffSig const s
intersection CASL s = return . interSig const s
morphism_union CASL = plainMorphismUnion const
final_union CASL = finalUnion const
is_subsig CASL = isSubSig trueC
subsig_inclusion CASL = sigInclusion ()
cogenerated_sign CASL = cogeneratedSign ()
generated_sign CASL = generatedSign ()
induced_from_morphism CASL = inducedFromMorphism ()
induced_from_to_morphism CASL = inducedFromToMorphism () trueC const
theory_to_taxonomy CASL = convTaxo
instance Logic CASL CASL_Sublogics
CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol ProofTree where
stability CASL = Stable
-- for Hybridization
parse_basic_sen CASL = Just $ \ _ -> formula []
proj_sublogic_epsilon CASL = pr_epsilon ()
all_sublogics CASL = sublogics_all []
sublogicDimensions CASL = sDims []
parseSublogic CASL = parseSL (\ s -> Just ((), s))
conservativityCheck CASL =
[ConservativityChecker "CCC" (return Nothing) checkFreeType]
empty_proof_tree CASL = emptyProofTree
omdoc_metatheory CASL = Just caslMetaTheory
export_senToOmdoc CASL = exportSenToOmdoc
export_symToOmdoc CASL = exportSymToOmdoc
export_theoryToOmdoc CASL = exportTheoryToOmdoc
omdocToSen CASL = OMI.omdocToSen
omdocToSym CASL = OMI.omdocToSym
addOMadtToTheory CASL = OMI.addOMadtToTheory
addOmdocToTheory CASL = OMI.addOmdocToTheory
syntaxTable CASL = Just . getSyntaxTable
#ifdef UNI_PACKAGE
provers CASL = [quickCheckProver]
#endif
|
spechub/Hets
|
CASL/Logic_CASL.hs
|
gpl-2.0
| 10,136
| 0
| 12
| 2,437
| 2,481
| 1,285
| 1,196
| 221
| 1
|
-- Copyright : Daan Leijen (c) 1999, daan@cs.uu.nl
-- HWT Group (c) 2003, haskelldb-users@lists.sourceforge.net
-- License : BSD-style
module Opaleye.Internal.HaskellDB.Sql.Generate (SqlGenerator(..)) where
import Opaleye.Internal.HaskellDB.PrimQuery
import Opaleye.Internal.HaskellDB.Sql
import qualified Data.List.NonEmpty as NEL
data SqlGenerator = SqlGenerator
{
sqlUpdate :: SqlTable -> [PrimExpr] -> Assoc -> SqlUpdate,
sqlDelete :: SqlTable -> [PrimExpr] -> SqlDelete,
sqlInsert :: SqlTable -> [Attribute] -> NEL.NonEmpty [PrimExpr] -> Maybe OnConflict -> SqlInsert,
sqlExpr :: PrimExpr -> SqlExpr,
sqlLiteral :: Literal -> String,
-- | Turn a string into a quoted string. Quote characters
-- and any escaping are handled by this function.
sqlQuote :: String -> String
}
|
WraithM/haskell-opaleye
|
src/Opaleye/Internal/HaskellDB/Sql/Generate.hs
|
bsd-3-clause
| 885
| 0
| 13
| 208
| 159
| 99
| 60
| 11
| 0
|
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.HGL.Draw.Monad
-- Copyright : (c) Alastair Reid, 1999-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : non-portable (requires concurrency)
--
-- The 'Draw' monad, with graphical objects as a special case.
--
-----------------------------------------------------------------------------
module Graphics.HGL.Draw.Monad
( Graphic -- = Draw ()
, Draw
, ioToDraw -- :: IO a -> Draw a
, bracket -- :: Draw a -> (a -> Draw b) -> (a -> Draw c) -> Draw c
, bracket_ -- :: Draw a -> (a -> Draw b) -> Draw c -> Draw c
) where
import Graphics.HGL.Internals.Draw
|
FranklinChen/hugs98-plus-Sep2006
|
packages/HGL/Graphics/HGL/Draw/Monad.hs
|
bsd-3-clause
| 785
| 4
| 4
| 139
| 53
| 41
| 12
| 7
| 0
|
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "src/Foreign/Marshal/Unsafe/Compat.hs" #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
module Foreign.Marshal.Unsafe.Compat (
-- * Unsafe functions
unsafeLocalState
) where
import Foreign.Marshal.Unsafe (unsafeLocalState)
|
phischu/fragnix
|
tests/packages/scotty/Foreign.Marshal.Unsafe.Compat.hs
|
bsd-3-clause
| 310
| 0
| 5
| 81
| 28
| 20
| 8
| 6
| 0
|
module Nitpick.PatternMatches (patternMatches) where
import Control.Applicative ((<$>), (<*))
import Control.Arrow (second)
import qualified Data.Foldable as F
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import qualified AST.Expression.General as E
import qualified AST.Expression.Canonical as Canonical
import qualified AST.Helpers as Help
import qualified AST.Module as Module
import qualified AST.Module.Name as ModuleName
import qualified AST.Pattern as Pattern
import qualified AST.Variable as Var
import Elm.Utils ((|>))
import Nitpick.Pattern (Pattern(..), fromCanonicalPattern)
import qualified Optimize.Patterns.DecisionTree as Opt
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Pattern as Error
import qualified Reporting.Region as Region
import qualified Reporting.Result as Result
patternMatches
:: Module.Interfaces
-> Module.CanonicalModule
-> Result.Result w Error.Error Opt.VariantDict
patternMatches interfaces modul =
let
name = Module.name modul
body = Module.body modul
tagDict =
toTagDict interfaces name (Module.datatypes body)
in
const (Map.map (Map.map length) tagDict)
<$> checkExpression tagDict (Module.program body)
-- TAG DICT
type TagDict =
Map.Map Var.Home (Map.Map Tag [TagInfo])
type Tag = String
data TagInfo = TagInfo
{ _tag :: Tag
, _arity :: Int
}
toTagDict :: Module.Interfaces -> ModuleName.Canonical -> Module.ADTs -> TagDict
toTagDict interfaces localName localAdts =
let
listTags =
[ TagInfo "::" 2
, TagInfo "[]" 0
]
builtinDict =
Map.singleton Var.BuiltIn $
Map.fromList
[ ("::", listTags)
, ("[]", listTags)
]
interfaceDict =
interfaces
|> Map.map (toTagMapping . Module.iAdts)
|> Map.mapKeysMonotonic Var.Module
|> Map.insert (Var.Module localName) (toTagMapping localAdts)
in
Map.union builtinDict interfaceDict
toTagMapping :: Module.ADTs -> Map.Map Tag [TagInfo]
toTagMapping adts =
let
toTagAndArity (_tvars, tagInfoList) =
let
info = map (\(tag, args) -> TagInfo tag (length args)) tagInfoList
in
map (second (const info)) tagInfoList
in
Map.elems adts
|> concatMap toTagAndArity
|> Map.fromList
lookupOtherTags :: Var.Canonical -> TagDict -> [TagInfo]
lookupOtherTags (Var.Canonical home name) tagDict =
case Map.lookup name =<< Map.lookup home tagDict of
Just otherTags ->
otherTags
Nothing ->
if Help.isTuple name then
[ TagInfo name (read (drop 6 name)) ]
else
error
"Since the Nitpick phase happens after canonicalization and type \
\inference, it is impossible that a pattern in a case cannot be \
\found."
-- CHECK EXPRESSIONS
checkExpression
:: TagDict
-> Canonical.Expr
-> Result.Result w Error.Error ()
checkExpression tagDict (A.A region expression) =
let
go =
checkExpression tagDict
go2 a b =
go a <* go b
goPattern =
checkPatterns tagDict region
in
case expression of
E.Literal _ ->
Result.ok ()
E.Var _ ->
Result.ok ()
E.Range low high ->
go2 low high
E.ExplicitList listExprs ->
F.traverse_ go listExprs
E.Binop _ leftExpr rightExpr ->
go2 leftExpr rightExpr
E.Lambda pattern body ->
goPattern [pattern]
<* go body
E.App func arg ->
go2 func arg
E.If branches finally ->
F.traverse_ (uncurry go2) branches
<* go finally
E.Let defs body ->
go body
<* F.traverse_ goDef defs
where
goDef (Canonical.Definition _ pattern expr _) =
goPattern [pattern]
<* go expr
E.Case expr branches ->
go expr
<* goPattern (map fst branches)
<* F.traverse_ (go . snd) branches
E.Data _ctor exprs ->
F.traverse_ go exprs
E.Access record _field ->
go record
E.Update record fields ->
go record
<* F.traverse_ (go . snd) fields
E.Record fields ->
F.traverse_ (go . snd) fields
E.Port impl ->
case impl of
E.In _ _ ->
Result.ok ()
E.Out _ expr _ ->
go expr
E.Task _ expr _ ->
go expr
E.GLShader _ _ _ ->
Result.ok ()
-- CHECK PATTERNS
checkPatterns
:: TagDict
-> Region.Region
-> [Pattern.CanonicalPattern]
-> Result.Result w Error.Error ()
checkPatterns tagDict region patterns =
checkPatternsHelp tagDict region [Anything] patterns
checkPatternsHelp
:: TagDict
-> Region.Region
-> [Pattern]
-> [Pattern.CanonicalPattern]
-> Result.Result w Error.Error ()
checkPatternsHelp tagDict region unhandled patterns =
case (unhandled, patterns) of
([], []) ->
return ()
(_:_, []) ->
Result.throw region (Error.Incomplete unhandled)
(_, pattern@(A.A localRegion _) : remainingPatterns) ->
do newUnhandled <- filterPatterns tagDict localRegion pattern unhandled
checkPatternsHelp tagDict region newUnhandled remainingPatterns
filterPatterns
:: TagDict
-> Region.Region
-> Pattern.CanonicalPattern
-> [Pattern]
-> Result.Result w Error.Error [Pattern]
filterPatterns tagDict region pattern unhandled =
let
nitPattern =
fromCanonicalPattern pattern
noIntersection pat =
intersection pat nitPattern == Nothing
in
if all noIntersection unhandled then
Result.throw region Error.Redundant
else
do let complementPatterns = complement tagDict nitPattern
return $
concatMap
(\p -> Maybe.mapMaybe (intersection p) complementPatterns)
unhandled
-- PATTERN INTERSECTION
intersection :: Pattern -> Pattern -> Maybe Pattern
intersection pattern1 pattern2 =
case (pattern1, pattern2) of
(Alias _ pattern1', _) ->
intersection pattern1' pattern2
(_, Alias _ pattern2') ->
intersection pattern1 pattern2'
(Anything, _) ->
Just pattern2
(Var _, _) ->
Just pattern2
(_, Anything) ->
Just pattern1
(_, Var _) ->
Just pattern1
(Data ctor1 args1, Data ctor2 args2) ->
if ctor1 /= ctor2 then
Nothing
else
Data ctor1 <$> sequence (zipWith intersection args1 args2)
(Record _, Record _) ->
Just pattern1
(Literal lit1, Literal lit2) ->
if lit1 == lit2 then
Just pattern1
else
Nothing
(AnythingBut literals, Literal lit) ->
if Set.member lit literals then
Nothing
else
Just pattern2
(Literal lit, AnythingBut literals) ->
if Set.member lit literals then
Nothing
else
Just pattern1
(AnythingBut literals1, AnythingBut literals2) ->
Just (AnythingBut (Set.union literals1 literals2))
_ ->
Nothing
-- PATTERN COMPLEMENT
complement :: TagDict -> Pattern -> [Pattern]
complement tagDict nitPattern =
case nitPattern of
Record _fields ->
[]
Alias _name pattern ->
complement tagDict pattern
Var _name ->
[]
Anything ->
[]
Literal lit ->
[AnythingBut (Set.singleton lit)]
AnythingBut literals ->
map Literal (Set.toList literals)
Data ctor patterns ->
complementData tagDict ctor patterns
complementData :: TagDict -> Var.Canonical -> [Pattern] -> [Pattern]
complementData tagDict tag patterns =
let
otherTags =
lookupOtherTags tag tagDict
tagComplements =
Maybe.mapMaybe (tagToPattern tag) otherTags
arity =
length patterns
argComplements =
concat (zipWith (makeArgComplements tagDict tag arity) [0..] patterns)
in
tagComplements ++ argComplements
tagToPattern :: Var.Canonical -> TagInfo -> Maybe Pattern
tagToPattern (Var.Canonical home rootTag) (TagInfo tag arity) =
if rootTag == tag then
Nothing
else
Just (Data (Var.Canonical home tag) (replicate arity Anything))
makeArgComplements :: TagDict -> Var.Canonical -> Int -> Int -> Pattern -> [Pattern]
makeArgComplements tagDict tag arity index argPattern =
let
complementList =
complement tagDict argPattern
padArgs pattern =
replicate index Anything
++ pattern
: replicate (arity - index - 1) Anything
in
map (Data tag . padArgs) complementList
|
pairyo/elm-compiler
|
src/Nitpick/PatternMatches.hs
|
bsd-3-clause
| 8,684
| 0
| 18
| 2,495
| 2,572
| 1,314
| 1,258
| 258
| 18
|
module Viewers (
viewCPU
, viewStack
, viewMem
, viewMem16
) where
import qualified CPU.Instructions as Ops
import CPU.FrozenEnvironment (FrozenCPUEnvironment(..), readFrzMemory)
import CPU.Types (Address)
import BitTwiddling (joinBytes)
import Text.Printf (printf)
import Data.Word (Word8, Word16)
import Data.Bits (testBit)
-- A basic view showing the registers, flags and the next instruction:
--
-- A F B C D E H L SP
-- 01B0 0013 00D8 014D FFFE
--
-- IME : ENABLED
-- Flags ZNHC
-- 1011
--
-- PC = 0x0100 (0x00)
--
viewCPU :: FrozenCPUEnvironment -> String
viewCPU cpu =
"A F B C D E H L SP \n" ++
(printf "%02X%02X %02X%02X %02X%02X %02X%02X %04X\n\n"
(frz_a cpu) (frz_f cpu) (frz_b cpu) (frz_c cpu) (frz_d cpu) (frz_e cpu) (frz_h cpu) (frz_l cpu) (frz_sp cpu)) ++
(" IME: " ++ (if frz_ime cpu then "ENABLED" else "DISABLED")) ++ "\n" ++
(viewFlags $ frz_f cpu) ++
"\n" ++
(peekInstruction cpu)
peekInstruction :: FrozenCPUEnvironment -> String
peekInstruction cpu =
let pointer = frz_pc cpu
opcode = readFrzMemory pointer cpu
arg1 = readFrzMemory (pointer+1) cpu
arg2 = readFrzMemory (pointer+2) cpu
op = Ops.opTable opcode
template = Ops.label op
label = case (Ops.instruction op) of
(Ops.Ary0 _) -> template
(Ops.Ary1 _) -> printf template arg1
(Ops.Ary2 _) -> printf template (arg1 `joinBytes` arg2)
(Ops.Unimplemented) -> printf "Unimplemented instruction: 0x%02X (%s)" opcode template
in
printf "PC = 0x%04X (%s)\n" pointer label
viewFlags :: Word8 -> String
viewFlags f =
"Flags ZNHC \n" ++
" " ++ (b 7) ++ (b 6) ++ (b 5) ++ (b 4) ++ "\n"
where
b n = if (testBit f n) then "1" else "0"
readMem16 :: Address -> FrozenCPUEnvironment -> Word16
readMem16 address cpu =
let
low = readFrzMemory address cpu
high = readFrzMemory (address + 1) cpu
in
joinBytes low high
viewMem16 :: Address -> FrozenCPUEnvironment -> String
viewMem16 address cpu =
printf "0x%04X" $ readMem16 address cpu
viewMem :: Address -> FrozenCPUEnvironment -> String
viewMem address cpu =
printf "0x%02X" $ readFrzMemory address cpu
-- Might be able to trace up the stack a bit,
-- but there's no way to tell where the base of the stack is.
viewStack :: FrozenCPUEnvironment -> String
viewStack cpu =
printf "[0x%04X] <- 0x%04X\n" value pointer
where
pointer = frz_sp cpu
value = readMem16 pointer cpu
|
ChaosCabbage/my-haskell-flailing
|
src/Viewers.hs
|
bsd-3-clause
| 2,733
| 0
| 14
| 829
| 727
| 386
| 341
| 57
| 4
|
{-# LANGUAGE OverloadedStrings #-}
-- | Description : Easy IPython kernels = Overview This module provides automation for writing
-- simple IPython kernels. In particular, it provides a record type that defines configurations and
-- a function that interprets a configuration as an action in some monad that can do IO.
--
-- The configuration consists primarily of functions that implement the various features of a
-- kernel, such as running code, looking up documentation, and performing completion. An example for
-- a simple language that nevertheless has side effects, global state, and timing effects is
-- included in the examples directory.
--
-- = Kernel Specs
--
-- To run your kernel, you will need to install the kernelspec into the Jupyter namespace. If your
-- kernel name is `kernel`, you will need to run the command:
--
-- > kernel install
--
-- This will inform Jupyter of the kernel so that it may be used.
--
-- == Further profile improvements Consult the IPython documentation along with the generated
-- profile source code for further configuration of the frontend, including syntax highlighting,
-- logos, help text, and so forth.
module IHaskell.IPython.EasyKernel (easyKernel, installKernelspec, KernelConfig(..)) where
import Data.Aeson (decode, encode)
import qualified Data.ByteString.Lazy as BL
import System.IO.Temp (withTempDirectory)
import System.Process (rawSystem)
import Control.Concurrent (MVar, readChan, writeChan, newMVar, readMVar, modifyMVar_)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad (forever, when, unless, void)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import IHaskell.IPython.Kernel
import IHaskell.IPython.Message.UUID as UUID
import IHaskell.IPython.Types
import System.Directory (createDirectoryIfMissing, doesDirectoryExist, doesFileExist,
getHomeDirectory, getTemporaryDirectory)
import System.FilePath ((</>))
import System.Exit (exitSuccess)
import System.IO (openFile, IOMode(ReadMode))
-- | The kernel configuration specifies the behavior that is specific to your language. The type
-- parameters provide the monad in which your kernel will run, the type of intermediate outputs from
-- running cells, and the type of final results of cells, respectively.
data KernelConfig m output result =
KernelConfig
{
-- | Info on the language of the kernel.
kernelLanguageInfo :: LanguageInfo
-- | Write all the files into the kernel directory, including `kernel.js`, `logo-64x64.png`, and any
-- other required files. The directory to write to will be passed to this function, and the return
-- value should be the kernelspec to be written to `kernel.json`.
, writeKernelspec :: FilePath -> IO KernelSpec
-- | How to render intermediate output
, displayOutput :: output -> [DisplayData]
-- | How to render final cell results
, displayResult :: result -> [DisplayData]
-- | Perform completion. The returned tuple consists of the matched text and completions. The
-- arguments are the code in the cell and the position of the cursor in the cell.
, completion :: T.Text -> Int -> m (T.Text, [T.Text])
-- | Return the information or documentation for its argument, described by the cell contents and
-- cursor position. The returned value is simply the data to display.
, inspectInfo :: T.Text -> Int -> m (Maybe [DisplayData])
-- | Execute a cell. The arguments are the contents of the cell, an IO action that will clear the
-- current intermediate output, and an IO action that will add a new item to the intermediate
-- output. The result consists of the actual result, the status to be sent to IPython, and the
-- contents of the pager. Return the empty string to indicate that there is no pager output. Errors
-- should be handled by defining an appropriate error constructor in your result type.
, run :: T.Text -> IO () -> (output -> IO ()) -> m (result, ExecuteReplyStatus, String)
, debug :: Bool -- ^ Whether to print extra debugging information to
}
-- Install the kernelspec, using the `writeKernelspec` field of the kernel configuration.
installKernelspec :: MonadIO m
=> KernelConfig m output result -- ^ Kernel configuration to install
-> Bool -- ^ Whether to use Jupyter `--replace`
-> Maybe FilePath -- ^ (Optional) prefix to install into for Jupyter `--prefix`
-> m ()
installKernelspec config replace installPrefixMay =
liftIO $ withTmpDir $ \tmp -> do
let kernelDir = tmp </> languageName (kernelLanguageInfo config)
createDirectoryIfMissing True kernelDir
kernelSpec <- writeKernelspec config kernelDir
let filename = kernelDir </> "kernel.json"
BL.writeFile filename $ encode $ toJSON kernelSpec
let replaceFlag = ["--replace" | replace]
installPrefixFlag = maybe ["--user"] (\prefix -> ["--prefix", prefix]) installPrefixMay
cmd = concat [["kernelspec", "install"], installPrefixFlag, [kernelDir], replaceFlag]
void $ rawSystem "ipython" cmd
where
withTmpDir act = do
tmp <- getTemporaryDirectory
withTempDirectory tmp "easyKernel" act
getProfile :: FilePath -> IO Profile
getProfile fn = do
profData <- openFile fn ReadMode >>= BL.hGetContents
case decode profData of
Just prof -> return prof
Nothing -> error "Invalid profile data"
createReplyHeader :: MonadIO m => MessageHeader -> m MessageHeader
createReplyHeader parent = do
-- Generate a new message UUID.
newMessageId <- liftIO UUID.random
let repType = fromMaybe err (replyType $ msgType parent)
err = error $ "No reply for message " ++ show (msgType parent)
return
MessageHeader
{ identifiers = identifiers parent
, parentHeader = Just parent
, metadata = Map.fromList []
, messageId = newMessageId
, sessionId = sessionId parent
, username = username parent
, msgType = repType
}
-- | Execute an IPython kernel for a config. Your 'main' action should call this as the last thing
-- it does.
easyKernel :: MonadIO m
=> FilePath -- ^ The connection file provided by the IPython frontend
-> KernelConfig m output result -- ^ The kernel configuration specifying how to react to
-- messages
-> m ()
easyKernel profileFile config = do
prof <- liftIO $ getProfile profileFile
zmq@(Channels shellReqChan shellRepChan ctrlReqChan ctrlRepChan iopubChan _) <- liftIO $ serveProfile
prof
False
execCount <- liftIO $ newMVar 0
forever $ do
req <- liftIO $ readChan shellReqChan
repHeader <- createReplyHeader (header req)
when (debug config) . liftIO $ print req
reply <- replyTo config execCount zmq req repHeader
liftIO $ writeChan shellRepChan reply
replyTo :: MonadIO m
=> KernelConfig m output result
-> MVar Integer
-> ZeroMQInterface
-> Message
-> MessageHeader
-> m Message
replyTo config _ _ KernelInfoRequest{} replyHeader =
return
KernelInfoReply
{ header = replyHeader
, languageInfo = kernelLanguageInfo config
, implementation = "ipython-kernel.EasyKernel"
, implementationVersion = "0.0"
}
replyTo config _ interface ShutdownRequest { restartPending = pending } replyHeader = do
liftIO $ writeChan (shellReplyChannel interface) $ ShutdownReply replyHeader pending
liftIO exitSuccess
replyTo config execCount interface req@ExecuteRequest { getCode = code } replyHeader = do
let send = writeChan (iopubChannel interface)
busyHeader <- dupHeader replyHeader StatusMessage
liftIO . send $ PublishStatus busyHeader Busy
outputHeader <- dupHeader replyHeader DisplayDataMessage
(res, replyStatus, pagerOut) <- let clearOutput = do
clearHeader <- dupHeader replyHeader
ClearOutputMessage
send $ ClearOutput clearHeader False
sendOutput x =
send $ PublishDisplayData
outputHeader
(languageName $ kernelLanguageInfo
config)
(displayOutput config x)
in run config code clearOutput sendOutput
liftIO . send $ PublishDisplayData outputHeader (languageName $ kernelLanguageInfo config)
(displayResult config res)
idleHeader <- dupHeader replyHeader StatusMessage
liftIO . send $ PublishStatus idleHeader Idle
liftIO $ modifyMVar_ execCount (return . (+ 1))
counter <- liftIO $ readMVar execCount
return
ExecuteReply
{ header = replyHeader
, pagerOutput = [DisplayData PlainText $ T.pack pagerOut]
, executionCounter = fromIntegral counter
, status = replyStatus
}
replyTo config _ _ req@CompleteRequest{} replyHeader = do
let code = getCode req
pos = getCursorPos req
(matchedText, completions) <- completion config code pos
let start = pos - T.length matchedText
end = pos
reply = CompleteReply replyHeader completions start end Map.empty True
return reply
replyTo config _ _ req@InspectRequest{} replyHeader = do
result <- inspectInfo config (inspectCode req) (inspectCursorPos req)
let reply =
case result of
Just datas -> InspectReply
{ header = replyHeader
, inspectStatus = True
, inspectData = datas
}
_ -> InspectReply { header = replyHeader, inspectStatus = False, inspectData = [] }
return reply
replyTo _ _ _ msg _ = do
liftIO $ putStrLn "Unknown message: "
liftIO $ print msg
return msg
dupHeader :: MonadIO m => MessageHeader -> MessageType -> m MessageHeader
dupHeader hdr mtype =
do
uuid <- liftIO UUID.random
return hdr { messageId = uuid, msgType = mtype }
|
artuuge/IHaskell
|
ipython-kernel/src/IHaskell/IPython/EasyKernel.hs
|
mit
| 10,812
| 0
| 16
| 3,181
| 1,956
| 1,029
| 927
| 157
| 2
|
module RenamingSpec (main, spec) where
import Test.Hspec
import Language.Haskell.Refact.Refactoring.Renaming
import TestUtils
import System.Directory
-- ---------------------------------------------------------------------
main :: IO ()
main = do
hspec spec
spec :: Spec
spec = do
describe "Renaming" $ do
it "renames in D1 B1 C1 A1 6 6" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/D1.hs" "AnotherTree" (6,6)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/D1.hs" "AnotherTree" (6,6)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/D1.hs"
, "Renaming/A1.hs"
, "Renaming/B1.hs"
, "Renaming/C1.hs"
]
diffD <- ct $ compareFiles "./Renaming/D1.hs.expected"
"./Renaming/D1.refactored.hs"
diffD `shouldBe` []
diffC <- ct $ compareFiles "./Renaming/C1.hs.expected"
"./Renaming/C1.refactored.hs"
diffC `shouldBe` []
diffB <- ct $ compareFiles "./Renaming/B1.hs.expected"
"./Renaming/B1.refactored.hs"
diffB `shouldBe` []
diffA <- ct $ compareFiles "./Renaming/A1.hs.expected"
"./Renaming/A1.refactored.hs"
diffA `shouldBe` []
-- ---------------------------------
it "renames in D2 B2 C2 A2 6 24" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/D2.hs" "SubTree" (6,24)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/D2.hs" "SubTree" (6,24)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/D2.hs"
, "Renaming/B2.hs"
, "Renaming/C2.hs"
]
diffD <- ct $ compareFiles "./Renaming/D2.hs.expected"
"./Renaming/D2.refactored.hs"
diffD `shouldBe` []
diffC <- ct $ compareFiles "./Renaming/C2.hs.expected"
"./Renaming/C2.refactored.hs"
diffC `shouldBe` []
diffB <- ct $ compareFiles "./Renaming/B2.hs.expected"
"./Renaming/B2.refactored.hs"
diffB `shouldBe` []
-- ---------------------------------
it "renames in D3 B3 C3 A3 12 7" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/D3.hs" "Same" (12,7)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/D3.hs" "Same" (12,7)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/D3.hs"
, "Renaming/B3.hs"
, "Renaming/C3.hs"
]
diffD <- ct $ compareFiles "./Renaming/D3.hs.expected"
"./Renaming/D3.refactored.hs"
diffD `shouldBe` []
diffC <- ct $ compareFiles "./Renaming/C3.hs.expected"
"./Renaming/C3.refactored.hs"
diffC `shouldBe` []
diffB <- ct $ compareFiles "./Renaming/B3.hs.expected"
"./Renaming/B3.refactored.hs"
diffB `shouldBe` []
-- ---------------------------------
it "renames in D4 B4 C4 A4 13 4" $ do
-- (["D4.hs","B4.hs","C4.hs","A4.hs"],["isSameOrNot","13","4"]),
r <- ct $ rename defaultTestSettings testOptions "./Renaming/D4.hs" "isSameOrNot" (13,4)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/D4.hs" "isSameOrNot" (13,4)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/D4.hs"
, "Renaming/A4.hs"
, "Renaming/B4.hs"
, "Renaming/C4.hs"
]
diffD <- ct $ compareFiles "./Renaming/D4.hs.expected"
"./Renaming/D4.refactored.hs"
diffD `shouldBe` []
diffC <- ct $ compareFiles "./Renaming/C4.hs.expected"
"./Renaming/C4.refactored.hs"
diffC `shouldBe` []
diffB <- ct $ compareFiles "./Renaming/B4.hs.expected"
"./Renaming/B4.refactored.hs"
diffB `shouldBe` []
diffA <- ct $ compareFiles "./Renaming/A4.hs.expected"
"./Renaming/A4.refactored.hs"
diffA `shouldBe` []
-- ---------------------------------
it "renames in D5 B5 C5 A5 24 1" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/D5.hs" "sum" (24,1)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/D5.hs" "sum" (24,1)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/D5.hs"
, "Renaming/A5.hs"
, "Renaming/B5.hs"
, "Renaming/C5.hs"
]
diffD <- ct $ compareFiles "./Renaming/D5.hs.expected"
"./Renaming/D5.refactored.hs"
diffD `shouldBe` []
diffC <- ct $ compareFiles "./Renaming/C5.hs.expected"
"./Renaming/C5.refactored.hs"
diffC `shouldBe` []
diffB <- ct $ compareFiles "./Renaming/B5.hs.expected"
"./Renaming/B5.refactored.hs"
diffB `shouldBe` []
diffA <- ct $ compareFiles "./Renaming/A5.hs.expected"
"./Renaming/A5.refactored.hs"
diffA `shouldBe` []
-- ---------------------------------
it "renames in D7 C7 10 1" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/D7.hs" "myFringe" (10,1)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/D7.hs" "myFringe" (10,1)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/D7.hs"
, "Renaming/C7.hs"
]
diffD <- ct $ compareFiles "./Renaming/D7.hs.expected"
"./Renaming/D7.refactored.hs"
diffD `shouldBe` []
diffC <- ct $ compareFiles "./Renaming/C7.hs.expected"
"./Renaming/C7.refactored.hs"
diffC `shouldBe` []
-- ---------------------------------
it "renames in Field1 5 18" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/Field1.hs" "pointx1" (5,18)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/Field1.hs" "pointx1" (5,18)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/Field1.hs"
]
diff <- ct $ compareFiles "./Renaming/Field1.hs.expected"
"./Renaming/Field1.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in Field3 9 1" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/Field3.hs" "abs" (9,1)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/Field3.hs" "abs" (9,1)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/Field3.hs"
]
diff <- ct $ compareFiles "./Renaming/Field3.hs.expected"
"./Renaming/Field3.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in Field4 5 23" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/Field4.hs" "value2" (5,23)
-- ct $ rename logTestSettings testOptions "./Renaming/Field4.hs" "value2" (5,23)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/Field4.hs"
]
diff <- ct $ compareFiles "./Renaming/Field4.hs.expected"
"./Renaming/Field4.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in IdIn1 11 1" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/IdIn1.hs" "x1" (11,1)
-- ct $ rename logTestSettings testOptions "./Renaming/IdIn1.hs" "x1" (11,1)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/IdIn1.hs"
]
diff <- ct $ compareFiles "./Renaming/IdIn1.hs.expected"
"./Renaming/IdIn1.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in IdIn2 15 7" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/IdIn2.hs" "x1" (15,7)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/IdIn2.hs" "x1" (15,7)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/IdIn2.hs"
]
diff <- ct $ compareFiles "./Renaming/IdIn2.hs.expected"
"./Renaming/IdIn2.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in ClassIn1 7 7" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/ClassIn1.hs" "MyReversable" (7,7)
-- ct $ rename logTestSettings testOptions Nothing "./Renaming/ClassIn1.hs" "MyReversable" (7,7)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/ClassIn1.hs"
]
diff <- ct $ compareFiles "./Renaming/ClassIn1.hs.expected"
"./Renaming/ClassIn1.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in ClassIn2 8 3" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/ClassIn2.hs" "reversable" (8,3)
-- ct $ rename logTestSettings testOptions Nothing "./Renaming/ClassIn2.hs" "reversable" (8,3)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/ClassIn2.hs"
]
diff <- ct $ compareFiles "./Renaming/ClassIn2.hs.expected"
"./Renaming/ClassIn2.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in ConstructorIn1 8 6" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/ConstructorIn1.hs" "MyBTree" (8,6)
-- ct $ rename logTestSettings testOptions "./Renaming/ConstructorIn1.hs" "MyBTree" (8,6)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/ConstructorIn1.hs"
]
diff <- ct $ compareFiles "./Renaming/ConstructorIn1.hs.expected"
"./Renaming/ConstructorIn1.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in ConstructorIn2 8 6" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/ConstructorIn2.hs" "Tree" (8,24)
-- ct $ rename logTestSettings testOptions Nothing "./Renaming/ConstructorIn2.hs" "Tree" (8,24)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/ConstructorIn2.hs"
]
diff <- ct $ compareFiles "./Renaming/ConstructorIn2.hs.expected"
"./Renaming/ConstructorIn2.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in ConstructorIn3 9 12" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/ConstructorIn3.hs" "b" (9,13)
-- ct $ rename logTestSettings testOptions "./Renaming/ConstructorIn3.hs" "b" (9,13)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/ConstructorIn3.hs"
]
diff <- ct $ compareFiles "./Renaming/ConstructorIn3.hs.expected"
"./Renaming/ConstructorIn3.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in Constructor 5 16" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/Constructor.hs" "MyType" (5,16)
-- ct $ rename logTestSettings testOptions "./Renaming/Constructor.hs" "MyType" (5,16)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/Constructor.hs"
]
diff <- ct $ compareFiles "./Renaming/Constructor.expected.hs"
"./Renaming/Constructor.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in LayoutIn1 7 17" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/LayoutIn1.hs" "square" (7,17)
-- ct $ rename logTestSettings testOptions "./Renaming/LayoutIn1.hs" "square" (7,17)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/LayoutIn1.hs"
]
diff <- ct $ compareFiles "./Renaming/LayoutIn1.hs.expected"
"./Renaming/LayoutIn1.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in LayoutIn2 8 7" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/LayoutIn2.hs" "ls" (8,7)
-- ct $ rename logTestSettings testOptions "./Renaming/LayoutIn2.hs" "ls" (8,7)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/LayoutIn2.hs"
]
diff <- ct $ compareFiles "./Renaming/LayoutIn2.hs.expected"
"./Renaming/LayoutIn2.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in LayoutIn3 7 13" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/LayoutIn3.hs" "anotherX" (7,13)
-- ct $ rename logTestSettings testOptions "./Renaming/LayoutIn3.hs" "anotherX" (7,13)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/LayoutIn3.hs"
]
diff <- ct $ compareFiles "./Renaming/LayoutIn3.hs.expected"
"./Renaming/LayoutIn3.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in LayoutIn4 7 8" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/LayoutIn4.hs" "io" (7,8)
-- ct $ rename logTestSettings testOptions "./Renaming/LayoutIn4.hs" "io" (7,8)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/LayoutIn4.hs"
]
diff <- ct $ compareFiles "./Renaming/LayoutIn4.hs.expected"
"./Renaming/LayoutIn4.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
-- Negative tests
-- ---------------------------------
it "naming clash at top level IdIn3" $ do
-- rename logTestSettings testOptions Nothing "./Renaming/IdIn3.hs" "foo" (10,1)
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/IdIn3.hs" "foo" (10,1))
(show res) `shouldBe` "Just \"Name 'foo' already exists in this module\\n\""
-- ---------------------------------
it "upper case name for fn fails IdIn4" $ do
-- rename logTestSettings testOptions Nothing "./Renaming/IdIn4.hs" "Foo" (12,1)
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/IdIn4.hs" "Foo" (12,1))
(show res) `shouldBe` "Just \"The new name should be an identifier!\""
-- ---------------------------------
it "naming clash IdIn5" $ do
-- ct $ rename logTestSettings testOptions "./Renaming/IdIn5.hs" "y" (13,1)
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/IdIn5.hs" "y" (13,1))
(show res) `shouldBe` "Just \"Name 'y' already exists, or renaming 'IdIn5.x' to 'y' will change the program's semantics!\\n\""
-- ---------------------------------
it "must rename in home module ClassIn3" $ do
-- rename logTestSettings testOptions Nothing "./Renaming/ClassIn3.hs" "Eq1" (16,10)
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/ClassIn3.hs" "Eq1" (16,10))
(show res) `shouldBe` "Just \"This identifier is defined in module GHC.Classes, please do renaming in that module!\""
-- ---------------------------------
it "will not rename existing name Field2" $ do
-- rename logTestSettings testOptions Nothing "./Renaming/Field2.hs" "absPoint" (5,18)
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/Field2.hs" "absPoint" (5,18))
(show res) `shouldBe` "Just \"Name 'absPoint' already exists in this module\\n\""
-- ---------------------------------
it "must qualify clashes Qualifier" $ do
-- rename logTestSettings testOptions "./Renaming/Qualifier.hs" "sum" (13,1)
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/Qualifier.hs" "sum" (13,1))
(show res) `shouldBe` "Just \"The new name will cause an ambiguous occurrence problem, please select another new name or qualify the use of 'sum' before renaming!\\n\""
-- ---------------------------------
it "cannot rename main Main" $ do
-- rename logTestSettings testOptions "./Renaming/Main.hs" "main1" (11,1)
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/Main.hs" "main1" (11,1))
(show res) `shouldBe` "Just \"The 'main' function defined in a 'Main' module should not be renamed!\""
-- ---------------------------------
it "cannot rename main Main2" $ do
-- res <- catchException (ct $ rename logTestSettings testOptions "./Renaming/Main2.hs" "main1" (4,1))
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/Main2.hs" "main1" (4,1))
(show res) `shouldBe` "Just \"The 'main' function defined in a 'Main' module should not be renamed!\""
-- ---------------------------------
it "cannot rename x InScopes 1" $ do
-- res <- catchException (ct $ rename logTestSettings testOptions "./Renaming/InScopes.hs" "g" (6,22))
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/InScopes.hs" "g" (6,22))
show res `shouldBe` "Just \"The new name will cause name capture!\""
-- ---------------------------------
it "cannot rename x InScopes 2" $ do
-- res <- catchException (ct $ rename logTestSettings testOptions "./Renaming/InScopes.hs" "g" (10,10))
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/InScopes.hs" "g" (10,10))
show res `shouldBe` "Just \"The new name will cause name capture!\""
-- ---------------------------------
it "cannot rename x InScopes 3" $ do
-- res <- catchException (ct $ rename logTestSettings testOptions "./Renaming/InScopes.hs" "g" (12,8))
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/InScopes.hs" "g" (12,8))
show res `shouldBe` "Just \"The new name will cause name capture!\""
-- ---------------------------------
it "cannot rename x InScopes 4" $ do
-- res <- catchException (ct $ rename logTestSettings testOptions "./Renaming/InScopes.hs" "g" (21,12))
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/InScopes.hs" "g" (21,12))
show res `shouldBe` "Just \"The new name will cause name capture!\""
-- ---------------------------------
it "rename with default main Main2" $ do
-- ct $ rename logTestSettings testOptions "./Renaming/Main2.hs" "baz" (6,1)
r <- ct $ rename defaultTestSettings testOptions "./Renaming/Main2.hs" "baz" (6,1)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/Main2.hs"
]
diff <- ct $ compareFiles "./Renaming/Main2.hs.expected"
"./Renaming/Main2.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "rename in a do statement" $ do
-- ct $ rename logTestSettings testOptions "./Layout/Do1.hs" "g2" (10,3)
r <- ct $ rename defaultTestSettings testOptions "./Layout/Do1.hs" "g2" (10,3)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Layout/Do1.hs"
]
diff <- ct $ compareFiles "./Layout/Do1.hs.expected"
"./Layout/Do1.refactored.hs"
diff `shouldBe` []
-- ---------------------------------
it "renames in QualServer QualClient" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/QualServer.hs" "foo1" (11,1)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/QualServer.hs" "foo1" (11,1)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` ["Renaming/QualServer.hs",
"Renaming/QualClient.hs"
]
diffD <- ct $ compareFiles "./Renaming/QualServer.expected.hs"
"./Renaming/QualServer.refactored.hs"
diffD `shouldBe` []
diffC <- ct $ compareFiles "./Renaming/QualClient.expected.hs"
"./Renaming/QualClient.refactored.hs"
diffC `shouldBe` []
-- ---------------------------------
it "renames in lib and in main 1" $ do
let ct4 = cdAndDo "./test/testdata/cabal/cabal4"
r <- ct4 $ rename defaultTestSettings testOptions "./src/Foo/Bar.hs" "baz1" (3,1)
-- r <- cdAndDo "./test/testdata/cabal/cabal4" $ rename logTestSettings testOptions "./src/Foo/Bar.hs" "baz1" (3,1)
r' <- ct4 $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` ["src/Foo/Bar.hs",
"src/main4.hs"
]
diffD <- ct4 $ compareFiles "./src/Foo/Bar.expected.hs"
"./src/Foo/Bar.refactored.hs"
diffD `shouldBe` []
diffC <- ct4 $ compareFiles "./src/main4.expected.hs"
"./src/main4.refactored.hs"
diffC `shouldBe` []
-- ---------------------------------
it "renames in lib and in main 2" $ do
let ctf = cdAndDo "./test/testdata/cabal/foo"
r <- ctf $ rename defaultTestSettings testOptions "./src/Foo/Bar.hs" "bar1" (3,1)
-- r <- cdAndDo "./test/testdata/cabal/foo" $ rename logTestSettings testOptions "./src/Foo/Bar.hs" "bar1" (3,1)
r' <- ctf $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` ["src/Foo/Bar.hs",
"src/Main.hs"
]
diffD <- ctf $ compareFiles "./src/Foo/Bar.expected.hs"
"./src/Foo/Bar.refactored.hs"
diffD `shouldBe` []
diffC <- ctf $ compareFiles "./src/Main.expected.hs"
"./src/Main.refactored.hs"
diffC `shouldBe` []
-- ---------------------------------
{-
it "rename gives noRebindableInfo MoveDef" $ do
-- ct $ rename logTestSettings testOptions "./src/Language/Haskell/Refact/MoveDef.hs" "t2" (1105,20)
r <- ct $ rename defaultTestSettings (testOptions { cradleCabalDir = Just ".", cradleCabalFile = Just "HaRe.cabal"}) "./src/Language/Haskell/Refact/MoveDef.hs" "t2" (1105,20)
r `shouldBe` [ "Renaming/Main2.hs"
]
diff <- ct $ compareFiles "./Renaming/Main2.hs.expected"
"./Renaming/Main2.refactored.hs"
diff `shouldBe` []
-}
-- ---------------------------------
it "ConflictExports" $ do
-- rename (logTestSettingsMainfile "./Renaming/ConflictExport.hs") testOptions "./Renaming/ConflictExport.hs" "fringe" (7,1)
res <- catchException (ct $ rename defaultTestSettings testOptions "./Renaming/ConflictExport.hs" "fringe" (7,1))
-- res <- catchException (ct $ rename (testSettingsMainfile "./Renaming/ConflictExport.hs") testOptions "./Renaming/ConflictExport.hs" "fringe" (7,1))
(show res) `shouldBe` "Just \"The new name will cause conflicting exports, please select another new name!\""
{-
TestCases{refactorCmd="rename",
positive=[
(["D1.hs","B1.hs","C1.hs","A1.hs"],["AnotherTree", "6", "6"]),
(["D2.hs","B2.hs","C2.hs","A2.hs"],["SubTree" , "6", "24"]),
(["D3.hs","B3.hs","C3.hs","A3.hs"],["Same","12","7"]),
(["D4.hs","B4.hs","C4.hs","A4.hs"],["isSameOrNot","13","4"]),
(["D5.hs","B5.hs","C5.hs","A5.hs"],["sum","24","1"]),
(["D7.hs","C7.hs"],["myFringe","10","1"]),
(["Field1.hs"],["pointx1","5","18"]),
(["Field3.hs"],["abs", "9","1"]),
(["Field4.hs"],["value2","5","23"]),
(["IdIn1.hs"],["x1","11","1"]),
(["IdIn2.hs"],["x1","15","7"]),
(["ClassIn1.hs"],["MyReversable","7","7"]),
(["ClassIn2.hs"],["reversable","8","3"]),
(["ConstructorIn1.hs"],["MyBTree","8","6"]),
(["ConstructorIn2.hs"],["Tree","8","24"]),
(["ConstructorIn3.hs"],["b","9","12"]),
(["LayoutIn1.hs"],["square","7","17"]),
(["LayoutIn2.hs"],["ls","8","7"]),
(["LayoutIn3.hs"],["anotherX","7","13"]),
(["LayoutIn4.hs"],["io","7","8"])],
negative=[(["IdIn3.hs"],["foo","10","1"]),
(["IdIn4.hs"],["Foo","12","1"]),
(["IdIn5.hs"],["y","10","1"]),
(["ClassIn3.hs"],["Eq1","16","10"]),
(["Field2.hs"], ["absPoint", "5", "18"]),
(["Qualifier.hs"],["sum","13","1"]),
(["Main.hs"],["main1", "11","1"]),
(["ConflictExport.hs","D6.hs"],["fringe","7","1"])]
}
-}
-- ---------------------------------
it "rename preserving layout Utils.hs" $ do
-- ct $ rename logTestSettings testOptions "./Renaming/Utils.hs" "parsed1" (5,11)
r <- ct $ rename defaultTestSettings testOptions "./Renaming/Utils.hs" "parsed1" (5,11)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
r' `shouldBe` [ "Renaming/Utils.hs"
]
diff <- ct $ compareFiles "./Renaming/Utils.expected.hs"
"./Renaming/Utils.refactored.hs"
diff `shouldBe` []
-- -----------------------------------------------------------------
it "passes RenameInExportedType.hs 1" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/RenameInExportedType.hs" "NewType" (6,6)
-- ct $ rename logTestSettings testOptions "./Renaming/RenameInExportedType.hs" "NewType" (6,6)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
(show r') `shouldBe` "[\"Renaming/RenameInExportedType.hs\"]"
diff <- ct $ compareFiles "./Renaming/RenameInExportedType.refactored.hs"
"./Renaming/RenameInExportedType.expected.hs"
diff `shouldBe` []
-- -----------------------------------------------------------------
it "passes RenameInExportedType2.hs" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/RenameInExportedType2.hs" "NewType" (6,24)
-- ct $ rename logTestSettings testOptions "./Renaming/RenameInExportedType2.hs" "NewType" (6,24)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
(show r') `shouldBe` "[\"Renaming/RenameInExportedType2.hs\"]"
diff <- ct $ compareFiles "./Renaming/RenameInExportedType2.refactored.hs"
"./Renaming/RenameInExportedType2.expected.hs"
diff `shouldBe` []
-- -----------------------------------------------------------------
it "passes ExportedType.hs for type name" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/ExportedType.hs" "NewType" (4,7)
-- ct $ rename logTestSettings testOptions "./Renaming/ExportedType.hs" "NewType" (4,7)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
(show r') `shouldBe` "[\"Renaming/ExportedType.hs\",\"Renaming/ExportedTypeClient.hs\"]"
diff <- ct $ compareFiles "./Renaming/ExportedType.refactored.hs"
"./Renaming/ExportedType.expected.hs"
diff `shouldBe` []
diff2 <- ct $ compareFiles "./Renaming/ExportedTypeClient.refactored.hs"
"./Renaming/ExportedTypeClient.expected.hs"
diff2 `shouldBe` []
-- -----------------------------------------------------------------
it "passes ExportedType.hs for type constructor" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/ExportedType.hs" "NewType" (4,16)
-- ct $ rename logTestSettings testOptions "./Renaming/ExportedType.hs" "NewType" (4,16)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
(show r') `shouldBe` "[\"Renaming/ExportedType.hs\",\"Renaming/ExportedTypeClient.hs\"]"
diff <- ct $ compareFiles "./Renaming/ExportedType.refactored.hs"
"./Renaming/ExportedType.expected2.hs"
diff `shouldBe` []
diff2 <- ct $ compareFiles "./Renaming/ExportedTypeClient.refactored.hs"
"./Renaming/ExportedTypeClient.expected2.hs"
diff2 `shouldBe` []
-- -----------------------------------------------------------------
it "passes WildCard.hs" $ do
r <- ct $ rename defaultTestSettings testOptions "./Renaming/WildCard.hs" "taggedPlugins2" (7,1)
-- r <- ct $ rename logTestSettings testOptions "./Renaming/WildCard.hs" "taggedPlugins2" (7,1)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
(show r') `shouldBe` "[\"Renaming/WildCard.hs\"]"
diff <- ct $ compareFiles "./Renaming/WildCard.refactored.hs"
"./Renaming/WildCard.expected.hs"
diff `shouldBe` []
-- -----------------------------------------------------------------
{-
it "renames in slack-api" $ do
let cts = cdAndDo "/home/alanz/tmp/hackage/slack-api-0.6"
r <- cts $ rename defaultTestSettings testOptions "./src/Web/Slack/Utils.hs" "anyName" (14,1)
-- cdAndDo "/home/alanz/tmp/hackage/slack-api-0.6" $ rename logTestSettings testOptions "./src/Web/Slack/Utils.hs" "anyName" (14,1)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
(show r') `shouldBe` "[\"Renaming/RenameInExportedType2.hs\"]"
-}
-- -----------------------------------------------------------------
it "renames in ghc-mod with CPP" $ do
pendingWith "get to the bottom of this"
{-
let cts = cdAndDo "/home/alanz/tmp/hackage/ghc-mod-5.4.0.0"
r <- cts $ rename defaultTestSettings testOptions "Language/Haskell/GhcMod/Target.hs" "putNewSession2" (81,6)
-- cdAndDo "/home/alanz/tmp/hackage/ghc-mod-5.4.0.0" $ rename logTestSettings testOptions "Language/Haskell/GhcMod/Target.hs" "putNewSession2" (81,6)
r' <- ct $ mapM makeRelativeToCurrentDirectory r
(show r') `shouldBe` "[\"Renaming/RenameInExportedType2.hs\"]"
-}
-- ---------------------------------------------------------------------
-- Helper functions
|
RefactoringTools/HaRe
|
test/RenamingSpec.hs
|
bsd-3-clause
| 30,397
| 0
| 18
| 7,509
| 4,527
| 2,256
| 2,271
| 352
| 1
|
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE QuasiQuotes, OverloadedStrings, RecordWildCards #-}
module Language.Bond.Codegen.Cpp.Enum_h (enum_h) where
import Data.Monoid
import Prelude
import Data.Text.Lazy (Text)
import Text.Shakespeare.Text
import Language.Bond.Syntax.Types
import Language.Bond.Codegen.TypeMapping
import Language.Bond.Codegen.Util
import qualified Language.Bond.Codegen.Cpp.Util as CPP
-- | Codegen template for generating /base_name/_enum.h containing definitions
-- of enums. Generated by <https://microsoft.github.io/bond/manual/compiler.html gbc> with @--enum-header@ flag.
enum_h :: MappingContext -> String -> [Import] -> [Declaration] -> (String, Text)
enum_h cpp _file _imports declarations = ("_enum.h", [lt|
#pragma once
#include <stdint.h>
#{CPP.openNamespace cpp}
namespace _bond_enumerators
{
#{newlineSep 1 typeDeclaration declarations}
} // namespace _bond_enumerators
#{newlineSep 0 usingDeclaration declarations}
#{CPP.closeNamespace cpp}
|])
where
-- enum definition
typeDeclaration e@Enum {..} = [lt|
namespace #{declName}
{
#{CPP.enumDefinition e}
} // namespace #{declName}
|]
typeDeclaration _ = mempty
usingDeclaration Enum {..} = [lt|using namespace _bond_enumerators::#{declName};|]
usingDeclaration _ = mempty
|
chwarr/bond
|
compiler/src/Language/Bond/Codegen/Cpp/Enum_h.hs
|
mit
| 1,431
| 0
| 10
| 205
| 191
| 123
| 68
| 16
| 3
|
module C3 (sumTree, myFringe, SameOrNot(..)) where
data Tree a = Leaf a | Branch (Tree a) (Tree a)
sumTree :: Num a => (Tree a) -> a
sumTree (Leaf x) = x
sumTree (Branch left right)
= (sumTree left) + (sumTree right)
myFringe :: (Tree a) -> [a]
myFringe (Leaf x) = [x]
myFringe (Branch left right) = myFringe left
class SameOrNot a
where
isSame :: a -> a -> Bool
isNotSame :: a -> a -> Bool
instance SameOrNot Int
where
isSame a b = a == b
isNotSame a b = a /= b
|
kmate/HaRe
|
old/testing/rmFromExport/C3_AstOut.hs
|
bsd-3-clause
| 531
| 0
| 8
| 164
| 241
| 127
| 114
| 15
| 1
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Database.Persist.Class.DeleteCascade
( DeleteCascade (..)
, deleteCascadeWhere
) where
import Database.Persist.Class.PersistStore
import Database.Persist.Class.PersistQuery
import Database.Persist.Class.PersistEntity
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader (ReaderT, ask, runReaderT)
import Data.Acquire (with)
class (PersistStore backend, PersistEntity record, backend ~ PersistEntityBackend record)
=> DeleteCascade record backend where
deleteCascade :: MonadIO m => Key record -> ReaderT backend m ()
deleteCascadeWhere :: (MonadIO m, DeleteCascade record backend, PersistQuery backend)
=> [Filter record] -> ReaderT backend m ()
deleteCascadeWhere filts = do
srcRes <- selectKeysRes filts []
conn <- ask
liftIO $ with srcRes (C.$$ CL.mapM_ (flip runReaderT conn . deleteCascade))
|
jasonzoladz/persistent
|
persistent/Database/Persist/Class/DeleteCascade.hs
|
mit
| 1,025
| 0
| 13
| 164
| 278
| 156
| 122
| 22
| 1
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for "Ganeti.Errors".
-}
{-
Copyright (C) 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.Errors (testErrors) where
import Test.QuickCheck
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import qualified Ganeti.Errors as Errors
$(genArbitrary ''Errors.ErrorCode)
$(genArbitrary ''Errors.GanetiException)
-- | Tests error serialisation.
prop_GenericError_serialisation :: Errors.GanetiException -> Property
prop_GenericError_serialisation = testSerialisation
testSuite "Errors"
[ 'prop_GenericError_serialisation
]
|
apyrgio/snf-ganeti
|
test/hs/Test/Ganeti/Errors.hs
|
bsd-2-clause
| 1,892
| 0
| 9
| 282
| 98
| 57
| 41
| 13
| 1
|
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Exit
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Exiting the program.
--
-----------------------------------------------------------------------------
module System.Exit
(
ExitCode(ExitSuccess,ExitFailure)
, exitWith
, exitFailure
, exitSuccess
, die
) where
import System.IO
import GHC.IO
import GHC.IO.Exception
-- ---------------------------------------------------------------------------
-- exitWith
-- | Computation 'exitWith' @code@ throws 'ExitCode' @code@.
-- Normally this terminates the program, returning @code@ to the
-- program's caller.
--
-- On program termination, the standard 'Handle's 'stdout' and
-- 'stderr' are flushed automatically; any other buffered 'Handle's
-- need to be flushed manually, otherwise the buffered data will be
-- discarded.
--
-- A program that fails in any other way is treated as if it had
-- called 'exitFailure'.
-- A program that terminates successfully without calling 'exitWith'
-- explicitly is treated as if it had called 'exitWith' 'ExitSuccess'.
--
-- As an 'ExitCode' is not an 'IOError', 'exitWith' bypasses
-- the error handling in the 'IO' monad and cannot be intercepted by
-- 'catch' from the "Prelude". However it is a 'SomeException', and can
-- be caught using the functions of "Control.Exception". This means
-- that cleanup computations added with 'Control.Exception.bracket'
-- (from "Control.Exception") are also executed properly on 'exitWith'.
--
-- Note: in GHC, 'exitWith' should be called from the main program
-- thread in order to exit the process. When called from another
-- thread, 'exitWith' will throw an 'ExitException' as normal, but the
-- exception will not cause the process itself to exit.
--
exitWith :: ExitCode -> IO a
exitWith ExitSuccess = throwIO ExitSuccess
exitWith code@(ExitFailure n)
| n /= 0 = throwIO code
| otherwise = ioError (IOError Nothing InvalidArgument "exitWith" "ExitFailure 0" Nothing Nothing)
-- | The computation 'exitFailure' is equivalent to
-- 'exitWith' @(@'ExitFailure' /exitfail/@)@,
-- where /exitfail/ is implementation-dependent.
exitFailure :: IO a
exitFailure = exitWith (ExitFailure 1)
-- | The computation 'exitSuccess' is equivalent to
-- 'exitWith' 'ExitSuccess', It terminates the program
-- successfully.
exitSuccess :: IO a
exitSuccess = exitWith ExitSuccess
-- | Write given error message to `stderr` and terminate with `exitFailure`.
--
-- @since 4.8.0.0
die :: String -> IO a
die err = hPutStrLn stderr err >> exitFailure
|
rahulmutt/ghcvm
|
libraries/base/System/Exit.hs
|
bsd-3-clause
| 2,817
| 0
| 8
| 452
| 244
| 152
| 92
| 25
| 1
|
module DoExp1 where
f x = do
(x:y) <- getLine
putStrLn x
g x = do
x <- getLine
putStrLn x
|
kmate/HaRe
|
old/testing/foldDef/DoExpr1_TokOut.hs
|
bsd-3-clause
| 129
| 0
| 9
| 60
| 53
| 25
| 28
| 7
| 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="ar-SA">
<title>WebSockets | 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>بحث</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>
|
msrader/zap-extensions
|
src/org/zaproxy/zap/extension/websocket/resources/help_ar_SA/helpset_ar_SA.hs
|
apache-2.0
| 972
| 82
| 65
| 159
| 411
| 208
| 203
| -1
| -1
|
{-# LANGUAGE PatternSynonyms #-}
module T12108 where
type Endo a = a -> a
pattern Id :: Endo a
pattern Id x = x
|
ezyang/ghc
|
testsuite/tests/patsyn/should_compile/T12108.hs
|
bsd-3-clause
| 115
| 0
| 6
| 27
| 37
| 21
| 16
| 5
| 0
|
{-# LANGUAGE CPP #-}
module Vectorise.Monad.InstEnv
( existsInst
, lookupInst
, lookupFamInst
)
where
import Vectorise.Monad.Global
import Vectorise.Monad.Base
import Vectorise.Env
import DynFlags
import FamInstEnv
import InstEnv
import Class
import Type
import TyCon
import Outputable
import Util
#include "HsVersions.h"
-- Check whether a unique class instance for a given class and type arguments exists.
--
existsInst :: Class -> [Type] -> VM Bool
existsInst cls tys
= do { instEnv <- readGEnv global_inst_env
; return $ either (const False) (const True) (lookupUniqueInstEnv instEnv cls tys)
}
-- Look up the dfun of a class instance.
--
-- The match must be unique —i.e., match exactly one instance— but the
-- type arguments used for matching may be more specific than those of
-- the class instance declaration. The found class instances must not have
-- any type variables in the instance context that do not appear in the
-- instances head (i.e., no flexi vars); for details for what this means,
-- see the docs at InstEnv.lookupInstEnv.
--
lookupInst :: Class -> [Type] -> VM (DFunId, [Type])
lookupInst cls tys
= do { instEnv <- readGEnv global_inst_env
; case lookupUniqueInstEnv instEnv cls tys of
Right (inst, inst_tys) -> return (instanceDFunId inst, inst_tys)
Left err ->
do dflags <- getDynFlags
cantVectorise dflags "Vectorise.Monad.InstEnv.lookupInst:" err
}
-- Look up a family instance.
--
-- The match must be unique - ie, match exactly one instance - but the
-- type arguments used for matching may be more specific than those of
-- the family instance declaration.
--
-- Return the family instance and its type instance. For example, if we have
--
-- lookupFamInst 'T' '[Int]' yields (':R42T', 'Int')
--
-- then we have a coercion (ie, type instance of family instance coercion)
--
-- :Co:R42T Int :: T [Int] ~ :R42T Int
--
-- which implies that :R42T was declared as 'data instance T [a]'.
--
lookupFamInst :: TyCon -> [Type] -> VM FamInstMatch
lookupFamInst tycon tys
= ASSERT( isOpenFamilyTyCon tycon )
do { instEnv <- readGEnv global_fam_inst_env
; case lookupFamInstEnv instEnv tycon tys of
[match] -> return match
_other ->
do dflags <- getDynFlags
cantVectorise dflags "Vectorise.Monad.InstEnv.lookupFamInst: not found: "
(ppr $ mkTyConApp tycon tys)
}
|
urbanslug/ghc
|
compiler/vectorise/Vectorise/Monad/InstEnv.hs
|
bsd-3-clause
| 2,531
| 0
| 16
| 607
| 398
| 221
| 177
| -1
| -1
|
{-# LANGUAGE RankNTypes, MultiParamTypeClasses #-}
{-# LANGUAGE AllowAmbiguousTypes #-} -- c3 is ambiguous!
module T where
import qualified Prelude as T(length,Monad,Integer)
import qualified Data.ByteString as T(length)
import Prelude(length,(+),(=<<),Monad(..),Maybe(..),Eq)
import Data.Maybe
import Control.Monad(Monad(..),MonadPlus(..))
length :: T.Integer
length = 0
class N a
class S a
class C a b where
c1 :: N b => a -> b
c2 :: (N b,S b) => a -> b
c3 :: forall a. a -> b
c4 :: a1 -> b
|
urbanslug/ghc
|
testsuite/tests/ghci/scripts/ghci025.hs
|
bsd-3-clause
| 507
| 0
| 8
| 92
| 198
| 121
| 77
| -1
| -1
|
-- | Data types representing responses from the API.
module Strive.Types
( module Strive.Types.Activities
, module Strive.Types.Athletes
, module Strive.Types.Authentication
, module Strive.Types.Clubs
, module Strive.Types.Comments
, module Strive.Types.Efforts
, module Strive.Types.Gear
, module Strive.Types.Photos
, module Strive.Types.Polylines
, module Strive.Types.Segments
, module Strive.Types.Streams
, module Strive.Types.Uploads
) where
import Strive.Types.Activities
import Strive.Types.Athletes
import Strive.Types.Authentication
import Strive.Types.Clubs
import Strive.Types.Comments
import Strive.Types.Efforts
import Strive.Types.Gear
import Strive.Types.Photos
import Strive.Types.Polylines
import Strive.Types.Segments
import Strive.Types.Streams
import Strive.Types.Uploads
|
bitemyapp/strive
|
library/Strive/Types.hs
|
mit
| 822
| 0
| 5
| 100
| 165
| 114
| 51
| 25
| 0
|
module Main where
import Control.Monad.Reader
import Control.Monad.Except
import Control.Exception (try)
import Data.List
import Data.Time
import System.Directory
import System.FilePath
import System.Environment
import System.Console.GetOpt
import System.Console.Haskeline
import System.Console.Haskeline.History
import Text.Printf
import Exp.Lex
import Exp.Par
import Exp.Print
import Exp.Abs hiding (NoArg)
import Exp.Layout
import Exp.ErrM
import CTT
import Resolver
import qualified TypeChecker as TC
import qualified Eval as E
type Interpreter a = InputT IO a
-- Flag handling
data Flag = Debug | Batch | Help | Version | Time
deriving (Eq,Show)
options :: [OptDescr Flag]
options = [ Option "d" ["debug"] (NoArg Debug) "run in debugging mode"
, Option "b" ["batch"] (NoArg Batch) "run in batch mode"
, Option "" ["help"] (NoArg Help) "print help"
, Option "-t" ["time"] (NoArg Time) "measure time spent computing"
, Option "" ["version"] (NoArg Version) "print version number" ]
-- Version number, welcome message, usage and prompt strings
version, welcome, usage, prompt :: String
version = "1.0"
welcome = "cubical, version: " ++ version ++ " (:h for help)\n"
usage = "Usage: cubical [options] <file.ctt>\nOptions:"
prompt = "> "
lexer :: String -> [Token]
lexer = resolveLayout True . myLexer
showTree :: (Show a, Print a) => a -> IO ()
showTree tree = do
putStrLn $ "\n[Abstract Syntax]\n\n" ++ show tree
putStrLn $ "\n[Linearized tree]\n\n" ++ printTree tree
-- Used for auto completion
searchFunc :: [String] -> String -> [Completion]
searchFunc ns str = map simpleCompletion $ filter (str `isPrefixOf`) ns
settings :: [String] -> Settings IO
settings ns = Settings
{ historyFile = Nothing
, complete = completeWord Nothing " \t" $ return . searchFunc ns
, autoAddHistory = True }
main :: IO ()
main = do
args <- getArgs
case getOpt Permute options args of
(flags,files,[])
| Help `elem` flags -> putStrLn $ usageInfo usage options
| Version `elem` flags -> putStrLn version
| otherwise -> case files of
[] -> do
putStrLn welcome
runInputT (settings []) (loop flags [] [] TC.verboseEnv)
[f] -> do
putStrLn welcome
putStrLn $ "Loading " ++ show f
initLoop flags f emptyHistory
_ -> putStrLn $ "Input error: zero or one file expected\n\n" ++
usageInfo usage options
(_,_,errs) -> putStrLn $ "Input error: " ++ concat errs ++ "\n" ++
usageInfo usage options
shrink :: String -> String
shrink s = s -- if length s > 1000 then take 1000 s ++ "..." else s
-- Initialize the main loop
initLoop :: [Flag] -> FilePath -> History -> IO ()
initLoop flags f hist = do
-- Parse and type check files
(_,_,mods) <- imports True ([],[],[]) f
-- Translate to TT
let res = runResolver $ resolveModules mods
case res of
Left err -> do
putStrLn $ "Resolver failed: " ++ err
runInputT (settings []) (putHistory hist >> loop flags f [] TC.verboseEnv)
Right (adefs,names) -> do
(merr,tenv) <- TC.runDeclss TC.verboseEnv adefs
case merr of
Just err -> putStrLn $ "Type checking failed: " ++ shrink err
Nothing -> putStrLn "File loaded."
if Batch `elem` flags
then return ()
else -- Compute names for auto completion
runInputT (settings [n | (n,_) <- names])
(putHistory hist >> loop flags f names tenv)
-- The main loop
loop :: [Flag] -> FilePath -> [(CTT.Ident,SymKind)] -> TC.TEnv -> Interpreter ()
loop flags f names tenv = do
input <- getInputLine prompt
case input of
Nothing -> outputStrLn help >> loop flags f names tenv
Just ":q" -> return ()
Just ":r" -> getHistory >>= lift . initLoop flags f
Just (':':'l':' ':str)
| ' ' `elem` str -> do outputStrLn "Only one file allowed after :l"
loop flags f names tenv
| otherwise -> getHistory >>= lift . initLoop flags str
Just (':':'c':'d':' ':str) -> do lift (setCurrentDirectory str)
loop flags f names tenv
Just ":h" -> outputStrLn help >> loop flags f names tenv
Just str' ->
let (msg,str,mod) = case str' of
(':':'n':' ':str) ->
("NORMEVAL: ",str,E.normal [])
str -> ("EVAL: ",str,id)
in case pExp (lexer str) of
Bad err -> outputStrLn ("Parse error: " ++ err) >> loop flags f names tenv
Ok exp ->
case runResolver $ local (insertIdents names) $ resolveExp exp of
Left err -> do outputStrLn ("Resolver failed: " ++ err)
loop flags f names tenv
Right body -> do
x <- liftIO $ TC.runInfer tenv body
case x of
Left err -> do outputStrLn ("Could not type-check: " ++ err)
loop flags f names tenv
Right _ -> do
start <- liftIO getCurrentTime
let e = mod $ E.eval (TC.env tenv) body
-- Let's not crash if the evaluation raises an error:
liftIO $ catch (putStrLn (msg ++ shrink (show e)))
-- (writeFile "examples/nunivalence3.ctt" (show e))
(\e -> putStrLn ("Exception: " ++
show (e :: SomeException)))
stop <- liftIO getCurrentTime
-- Compute time and print nicely
let time = diffUTCTime stop start
secs = read (takeWhile (/='.') (init (show time)))
rest = read ('0':dropWhile (/='.') (init (show time)))
mins = secs `quot` 60
sec = printf "%.3f" (fromInteger (secs `rem` 60) + rest :: Float)
when (Time `elem` flags) $
outputStrLn $ "Time: " ++ show mins ++ "m" ++ sec ++ "s"
-- Only print in seconds:
-- when (Time `elem` flags) $ outputStrLn $ "Time: " ++ show time
loop flags f names tenv
-- (not ok,loaded,already loaded defs) -> to load ->
-- (new not ok, new loaded, new defs)
-- the bool determines if it should be verbose or not
imports :: Bool -> ([String],[String],[Module]) -> String ->
IO ([String],[String],[Module])
imports v st@(notok,loaded,mods) f
| f `elem` notok = putStrLn ("Looping imports in " ++ f) >> return ([],[],[])
| f `elem` loaded = return st
| otherwise = do
b <- doesFileExist f
let prefix = dropFileName f
if not b
then putStrLn (f ++ " does not exist") >> return ([],[],[])
else do
s <- readFile f
let ts = lexer s
case pModule ts of
Bad s -> do
putStrLn $ "Parse failed in " ++ show f ++ "\n" ++ show s
return ([],[],[])
Ok mod@(Module (AIdent (_,name)) imp decls) ->
let imp_ctt = [prefix ++ i ++ ".ctt" | Import (AIdent (_,i)) <- imp]
in do
when (name /= dropExtension (takeFileName f)) $
error $ "Module name mismatch " ++ show (f,name)
(notok1,loaded1,mods1) <-
foldM (imports v) (f:notok,loaded,mods) imp_ctt
when v $ putStrLn $ "Parsed " ++ show f ++ " successfully!"
return (notok,f:loaded1,mods1 ++ [mod])
help :: String
help = "\nAvailable commands:\n" ++
" <statement> infer type and evaluate statement\n" ++
" :n <statement> normalize statement\n" ++
" :q quit\n" ++
" :l <filename> loads filename (and resets environment before)\n" ++
" :cd <path> change directory to path\n" ++
" :r reload\n" ++
" :h display this message\n"
|
linuborj/cubicaltt
|
Main.hs
|
mit
| 7,938
| 0
| 35
| 2,535
| 2,515
| 1,289
| 1,226
| 168
| 11
|
module Ast where
data Ast a = Value a | Operation Op (Ast a) (Ast a)
data Op = Add | Subtract | Multiply | Divide deriving (Show)
evaluate :: (Integral a) => (Ast a) -> a
evaluate (Value a) = a
evaluate (Operation Add a b) = evaluate a + evaluate b
evaluate (Operation Subtract a b) = evaluate a - evaluate b
evaluate (Operation Multiply a b) = evaluate a * evaluate b
evaluate (Operation Divide a b) = evaluate a `div` evaluate b
|
Agrosis/haxpr
|
src/Ast.hs
|
mit
| 456
| 0
| 8
| 111
| 210
| 108
| 102
| 9
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{- |
Module : Database.Couch.Explicit.Doc
Description : Document-oriented requests to CouchDB, with explicit parameters
Copyright : Copyright (c) 2015, Michael Alan Dorman
License : MIT
Maintainer : mdorman@jaunder.io
Stability : experimental
Portability : POSIX
This module is intended to be @import qualified@. /No attempt/ has been made to keep names of types or functions from clashing with obvious or otherwise commonly-used names, or even other modules within this package.
The functions here are derived from (and presented in the same order as) the <http://docs.couchdb.org/en/1.6.1/api/document/common.html Document API documentation>. For each function, we attempt to link back to the original documentation, as well as make a notation as to how complete and correct we feel our implementation is.
Each function takes a 'Database.Couch.Types.Context'---which, among other things, holds the name of the database---as its final parameter, and returns a 'Database.Couch.Types.Result'.
-}
module Database.Couch.Explicit.Doc where
import Control.Monad.IO.Class (MonadIO)
import Data.Aeson (FromJSON, ToJSON)
import Data.Maybe (Maybe)
import Data.Monoid (mempty)
import qualified Database.Couch.Explicit.DocBase as Base (copy, delete, get,
put)
import Database.Couch.Types (Context, DocId, DocRev,
ModifyDoc, Result,
RetrieveDoc)
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#head--db-docid Get the size and revision of the specified document>
The return value is an object that should only contain the keys "rev" and "size", that can be easily parsed into a pair of (DocRev, Int):
>>> (,) <$> (getKey "rev" >>= toOutputType) <*> (getKey "size" >>= toOutputType)
If the specified DocRev matches, returns a JSON Null, otherwise a JSON value for the document.
Status: __Complete__ -}
meta :: (FromJSON a, MonadIO m)
=> RetrieveDoc -- ^ Parameters for document retrieval
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> Context
-> m (Result a)
meta = Base.get mempty
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#get--db-docid Get the specified document>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Doc.get "pandas" Nothing ctx
If the specified DocRev matches, returns a JSON Null, otherwise a JSON value for the document.
Status: __Complete__ -}
get :: (FromJSON a, MonadIO m)
=> RetrieveDoc -- ^ Parameters for document retrieval
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> Context
-> m (Result a)
get = Base.get mempty
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#put--db-docid Create or replace the specified document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- DocBase.put modifyDoc "pandas" Nothing SomeValue ctx >>= asBool
Status: __Complete__ -}
put :: (FromJSON a, MonadIO m, ToJSON b)
=> ModifyDoc -- ^ Parameters for modifying document
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> b -- ^ The document
-> Context
-> m (Result a)
put = Base.put mempty
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#delete--db-docid Delete the specified document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- DocBase.delete "prefix" modifyDoc "pandas" Nothing ctx >>= asBool
Status: __Complete__ -}
delete :: (FromJSON a, MonadIO m)
=> ModifyDoc -- ^ Parameters for modifying document
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> Context
-> m (Result a)
delete = Base.delete mempty
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#copy--db-docid Copy the specified document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- DocBase.delete "prefix" modifyDoc "pandas" Nothing ctx >>= asBool
Status: __Complete__ -}
copy :: (FromJSON a, MonadIO m)
=> ModifyDoc -- ^ Parameters for modifying document
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> DocId -- ^ The destination document Id
-> Context
-> m (Result a)
copy = Base.copy mempty
|
mdorman/couch-simple
|
src/lib/Database/Couch/Explicit/Doc.hs
|
mit
| 5,149
| 0
| 13
| 1,164
| 433
| 246
| 187
| 50
| 1
|
{-# LANGUAGE TemplateHaskell #-}
module Example where
import Hs2Ps
data Array a = Array a
data Tuple a b = Tuple a b
data Example = A [[Int]] | B [(Maybe Int, Maybe Bool, [Maybe Float])]
hs2Ps "Example"
{-
Result from -ddump-splices
data Example
= A (Array (Array Int)) |
B (Array (Tuple (Maybe Int) (Tuple (Maybe Bool) (Array (Maybe Float)))))
-}
|
izgzhen/purescript-purescript
|
utils-hs/Example.hs
|
mit
| 382
| 0
| 10
| 96
| 82
| 48
| 34
| 7
| 0
|
-- | Strict alternatives to the functions in
-- Control.Monad.Conc.CVar. Specifically, values are evaluated to
-- normal form before being put into a @CVar@.
module Control.Concurrent.CVar.Strict
( -- *@CVar@s
CVar
, newEmptyCVar
, newCVar
, takeCVar
, putCVar
, readCVar
, swapCVar
, tryTakeCVar
, tryPutCVar
, isEmptyCVar
, withCVar
, withCVarMasked
, modifyCVar_
, modifyCVar
, modifyCVarMasked_
, modifyCVarMasked
-- * Binary semaphores
-- | A common use of @CVar@s is in making binary semaphores to
-- control mutual exclusion over a resource, so a couple of helper
-- functions are provided.
, lock
, unlock
) where
import Control.Concurrent.CVar (isEmptyCVar, withCVar, withCVarMasked, lock, unlock)
import Control.DeepSeq (NFData, force)
import Control.Monad (liftM)
import Control.Monad.Catch (mask_, onException)
import Control.Monad.Conc.Class hiding (newEmptyCVar, putCVar, tryPutCVar)
import qualified Control.Concurrent.CVar as V
import qualified Control.Monad.Conc.Class as C
-- | Create a new empty @CVar@.
newEmptyCVar :: (MonadConc m, NFData a) => m (CVar m a)
newEmptyCVar = C.newEmptyCVar
-- | Create a new @CVar@ containing a value.
newCVar :: (MonadConc m, NFData a) => a -> m (CVar m a)
newCVar = V.newCVar . force
-- | Swap the contents of a @CVar@, and return the value taken.
swapCVar :: (MonadConc m, NFData a) => CVar m a -> a -> m a
swapCVar cvar = V.swapCVar cvar . force
-- | Put a value into a @CVar@. If there is already a value there,
-- this will block until that value has been taken, at which point the
-- value will be stored.
putCVar :: (MonadConc m, NFData a) => CVar m a -> a -> m ()
putCVar cvar = C.putCVar cvar . force
-- | Attempt to put a value in a @CVar@, returning 'True' (and filling
-- the @CVar@) if there was nothing there, otherwise returning
-- 'False'.
tryPutCVar :: (MonadConc m, NFData a) => CVar m a -> a -> m Bool
tryPutCVar cvar = C.tryPutCVar cvar . force
-- | An exception-safe wrapper for modifying the contents of a @CVar@.
-- Like 'withCVar', 'modifyCVar' will replace the original contents of
-- the @CVar@ if an exception is raised during the operation. This
-- function is only atomic if there are no other producers for this
-- @CVar@.
{-# INLINE modifyCVar_ #-}
modifyCVar_ :: (MonadConc m, NFData a) => CVar m a -> (a -> m a) -> m ()
modifyCVar_ cvar f = modifyCVar cvar $ liftM (\a -> (a,())) . f
-- | A slight variation on 'modifyCVar_' that allows a value to be
-- returned (@b@) in addition to the modified value of the @CVar@.
{-# INLINE modifyCVar #-}
modifyCVar :: (MonadConc m, NFData a) => CVar m a -> (a -> m (a, b)) -> m b
modifyCVar cvar f = mask $ \restore -> do
val <- takeCVar cvar
(val', out) <- restore (f val) `onException` putCVar cvar val
putCVar cvar val'
return out
-- | Like 'modifyCVar_', but the @IO@ action in the second argument is
-- executed with asynchronous exceptions masked.
{-# INLINE modifyCVarMasked_ #-}
modifyCVarMasked_ :: (MonadConc m, NFData a) => CVar m a -> (a -> m a) -> m ()
modifyCVarMasked_ cvar f = modifyCVarMasked cvar $ liftM (\a -> (a,())) . f
-- | Like 'modifyCVar', but the @IO@ action in the second argument is
-- executed with asynchronous exceptions masked.
{-# INLINE modifyCVarMasked #-}
modifyCVarMasked :: (MonadConc m, NFData a) => CVar m a -> (a -> m (a, b)) -> m b
modifyCVarMasked cvar f = mask_ $ do
val <- takeCVar cvar
(val', out) <- f val `onException` putCVar cvar val
putCVar cvar val'
return out
|
bitemyapp/dejafu
|
Control/Concurrent/CVar/Strict.hs
|
mit
| 3,494
| 0
| 13
| 655
| 860
| 474
| 386
| 57
| 1
|
{-# LANGUAGE StandaloneDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Data.String.Interpolate.ParseSpec (main, spec) where
import Test.Hspec
import Data.String.Interpolate.Parse
deriving instance Eq a => Eq (Node a)
deriving instance Show a => Show (Node a)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "parseNodes" $ do
it "parses string literals" $ do
parseNodes "foo" `shouldBe` [Literal "foo"]
it "parses abstractions" $ do
parseNodes "#{}" `shouldBe` [Abstraction ()]
it "parses expressions" $ do
parseNodes "#{foo}" `shouldBe` [Expression "foo"]
it "parses embedded expressions" $ do
parseNodes "foo #{bar} baz" `shouldBe` [Literal "foo ", Expression "bar", Literal " baz"]
context "when given an unterminated expression" $ do
it "parses it as a string literal" $ do
parseNodes "foo #{bar" `shouldBe` [Literal "foo #{bar"]
|
sol/interpolate
|
test/Data/String/Interpolate/ParseSpec.hs
|
mit
| 948
| 0
| 18
| 214
| 274
| 136
| 138
| 23
| 1
|
{-# LANGUAGE DoAndIfThenElse, DeriveDataTypeable #-}
module Assets.FileSystem(
FileSystemArchive
, newFileSystemArchive
) where
import Prelude hiding (readFile, writeFile)
import Control.Monad.Trans (liftIO)
import Control.Monad.Trans.Either
import Data.Typeable
import Data.ByteString.Lazy (readFile, writeFile)
import System.Directory
import System.FilePath
import Assets.Archive
import Util.Monad (liftExceptions)
import Data.Text (Text)
newtype FileSystemArchive = FileSystemArchive FilePath
deriving (Typeable)
instance Archive FileSystemArchive where
openArchive path = do
ex <- liftIO $ doesDirectoryExist path
if ex then do
p <- liftIO $ getPermissions path
if readable p && writable p
then right $ FileSystemArchive path
else left "Doesn't have permissions"
else left "Directory doesn't exist"
closeArchive _ = return ()
listArchive (FileSystemArchive path) = getDirectoryContents path
readArchiveFile (FileSystemArchive path) file = liftExceptions $ liftIO $ readFile $ path </> file
writeArchiveFile (FileSystemArchive path) file ds = liftExceptions $ liftIO $ writeFile (path </> file) ds
archivePath (FileSystemArchive path) = path
newFileSystemArchive :: FilePath -> EitherT Text IO FileSystemArchive
newFileSystemArchive path = do
liftExceptions $ liftIO $ createDirectoryIfMissing True path
openArchive path
|
NCrashed/sinister
|
src/client/Assets/FileSystem.hs
|
mit
| 1,405
| 0
| 13
| 239
| 363
| 190
| 173
| 34
| 1
|
-- https://www.hackerrank.com/challenges/fp-update-list
f = map abs
-- This section handles the Input/Output and can be used as it is. Do not modify it.
main = do
inputdata <- getContents
mapM_ putStrLn $ map show $ f $ map (read :: String -> Int) $ lines inputdata
|
Seblink/HackerRank
|
functional-programming/introduction/fp-update-list.hs
|
mit
| 274
| 0
| 11
| 54
| 64
| 31
| 33
| 4
| 1
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.Database
(js_changeVersion, changeVersion, js_transaction, transaction,
js_readTransaction, readTransaction, js_getVersion, getVersion,
Database, castToDatabase, gTypeDatabase)
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[\"changeVersion\"]($2, $3, $4,\n$5, $6)" js_changeVersion ::
Database ->
JSString ->
JSString ->
Nullable SQLTransactionCallback ->
Nullable SQLTransactionErrorCallback ->
Nullable VoidCallback -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.changeVersion Mozilla Database.changeVersion documentation>
changeVersion ::
(MonadIO m, ToJSString oldVersion, ToJSString newVersion) =>
Database ->
oldVersion ->
newVersion ->
Maybe SQLTransactionCallback ->
Maybe SQLTransactionErrorCallback -> Maybe VoidCallback -> m ()
changeVersion self oldVersion newVersion callback errorCallback
successCallback
= liftIO
(js_changeVersion (self) (toJSString oldVersion)
(toJSString newVersion)
(maybeToNullable callback)
(maybeToNullable errorCallback)
(maybeToNullable successCallback))
foreign import javascript unsafe "$1[\"transaction\"]($2, $3, $4)"
js_transaction ::
Database ->
Nullable SQLTransactionCallback ->
Nullable SQLTransactionErrorCallback ->
Nullable VoidCallback -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.transaction Mozilla Database.transaction documentation>
transaction ::
(MonadIO m) =>
Database ->
Maybe SQLTransactionCallback ->
Maybe SQLTransactionErrorCallback -> Maybe VoidCallback -> m ()
transaction self callback errorCallback successCallback
= liftIO
(js_transaction (self) (maybeToNullable callback)
(maybeToNullable errorCallback)
(maybeToNullable successCallback))
foreign import javascript unsafe
"$1[\"readTransaction\"]($2, $3,\n$4)" js_readTransaction ::
Database ->
Nullable SQLTransactionCallback ->
Nullable SQLTransactionErrorCallback ->
Nullable VoidCallback -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.readTransaction Mozilla Database.readTransaction documentation>
readTransaction ::
(MonadIO m) =>
Database ->
Maybe SQLTransactionCallback ->
Maybe SQLTransactionErrorCallback -> Maybe VoidCallback -> m ()
readTransaction self callback errorCallback successCallback
= liftIO
(js_readTransaction (self) (maybeToNullable callback)
(maybeToNullable errorCallback)
(maybeToNullable successCallback))
foreign import javascript unsafe "$1[\"version\"]" js_getVersion ::
Database -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.version Mozilla Database.version documentation>
getVersion ::
(MonadIO m, FromJSString result) => Database -> m result
getVersion self = liftIO (fromJSString <$> (js_getVersion (self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Database.hs
|
mit
| 4,131
| 46
| 10
| 927
| 833
| 473
| 360
| 79
| 1
|
module Chart.Backend.Chart
( renderChart
) where
import Control.Lens
import Control.Monad (void)
import Data.Default (def)
import Data.List.NonEmpty (nonEmpty)
import qualified Data.List.NonEmpty as NonEmpty
import Data.Maybe (catMaybes)
import Data.Text (unpack)
import qualified Graphics.Rendering.Cairo as Cairo
import qualified Graphics.Rendering.Chart as Chart
import Graphics.Rendering.Chart.Backend.Cairo (defaultEnv, runBackend)
import qualified Dataset
import Chart.Types
-- | This type allows you to package all 'Renderable' (in the Chart backend sense)
-- values as a single type by hiding all information about that type, besides
-- the fact that it can be rendered.
data Renderable = forall r. Chart.ToRenderable r => MkRenderable r
-- | Given a cplot home-rolled 'Chart', produce a cairo rendered object, which
-- we can then paint to any canvas that supports such objects.
renderChart :: Chart -> Chart.RectSize -> Cairo.Render ()
renderChart chart rect =
void $ runBackend (defaultEnv Chart.vectorAlignmentFns)
(Chart.render renderable rect)
where
-- Unwrap the Renderable wrapper and actually make the object renderable.
render :: Renderable -> Chart.Renderable ()
render (MkRenderable r) = Chart.toRenderable r
renderable :: Chart.Renderable ()
renderable = render layout
listOfSubcharts = NonEmpty.toList (chart^.subcharts)
layout =
case chart^.axisScaling of
LinearScaling -> MkRenderable
$ Chart.layout_title .~ unpack (chart^.title)
$ Chart.layout_plots .~ map makeLinearPlottable listOfSubcharts
$ Chart.layout_x_axis .~ customLinAxis minX maxX
$ Chart.layout_y_axis .~ customLinAxis minY maxY
$ def
LogScaling -> MkRenderable
$ Chart.layout_title .~ unpack (chart^.title)
$ Chart.layout_plots .~ map makeLogPlottable listOfSubcharts
$ Chart.layout_x_axis .~ customLinAxis minX maxX
$ Chart.layout_y_axis .~ customLogAxis minY maxY
$ def
-- The rest of the functions in here are mostly for computing axis bounds.
-- It is annoyingly convoluted.
customLinAxis (Just mn) (Just mx) | mn /= mx =
Chart.laxis_override .~
(\axisData -> Chart.axis_viewport .~ Chart.vmap (mn, mx)
$ Chart.axis_tropweiv .~ Chart.invmap (mn, mx)
$ axisData) $ def
customLinAxis _ _ = def
customLogAxis (Just mn) (Just mx) | mn /= mx =
Chart.laxis_override .~
(\axisData -> Chart.axis_viewport .~ Chart.vmap (Chart.LogValue mn, Chart.LogValue mx)
$ Chart.axis_tropweiv .~ Chart.invmap (Chart.LogValue mn, Chart.LogValue mx)
$ axisData) $ def
customLogAxis _ _ = def
xbounds = catMaybes
[ Dataset.xbounds (subchart^.dataset) | subchart <- listOfSubcharts ]
ybounds = catMaybes
[ Dataset.ybounds (subchart^.dataset) | subchart <- listOfSubcharts ]
(minX, maxX) = mins xbounds
(minY, maxY) = mins ybounds
mins bounds = (safeMinimum (map fst bounds), safeMaximum (map snd bounds))
safeMinimum = fmap minimum . nonEmpty
safeMaximum = fmap maximum . nonEmpty
-- | For linear axes, convert a 'Subchart' to a 'Plot'.
makeLinearPlottable :: Subchart -> Chart.Plot Double Double
makeLinearPlottable subchart =
case subchart^.style of
LinePlot -> Chart.toPlot
$ Chart.plot_lines_title .~ l
$ Chart.plot_lines_values .~ [ unwrapPoints (Dataset.toList d) ]
$ def
ScatterPlot -> Chart.toPlot
$ Chart.plot_points_title .~ l
$ Chart.plot_points_values .~ unwrapPoints (Dataset.toList d)
$ def
Histogram -> Chart.histToPlot
$ Chart.plot_hist_title .~ l
$ Chart.plot_hist_bins .~ 16
$ Chart.plot_hist_values .~ unwrapSingles (Dataset.toList d)
$ Chart.plot_hist_no_zeros .~ False
$ Chart.defaultNormedPlotHist
where
d = subchart^.dataset
l = unpack (subchart^.label)
unwrapSingles xs = [ x | Dataset.P1 x <- xs ]
unwrapPoints ps = [ (x, y) | Dataset.P2 x y <- ps ]
-- | For a logarithmic axis, convert a 'Subchart' to a 'Plot'.
makeLogPlottable :: Subchart -> Chart.Plot Double Chart.LogValue
makeLogPlottable subchart =
case subchart^.style of
LinePlot -> Chart.toPlot
$ Chart.plot_lines_title .~ l
$ Chart.plot_lines_values .~ [ unwrapPoints (Dataset.toList d) ]
$ def
ScatterPlot -> Chart.toPlot
$ Chart.plot_points_title .~ l
$ Chart.plot_points_values .~ unwrapPoints (Dataset.toList d)
$ def
Histogram -> Chart.histToPlot
$ Chart.plot_hist_title .~ l
$ Chart.plot_hist_bins .~ 16
$ Chart.plot_hist_values .~ unwrapSingles (Dataset.toList d)
$ Chart.plot_hist_no_zeros .~ False
$ Chart.plot_hist_norm_func .~ norm
$ Chart.defaultNormedPlotHist
where
d = subchart^.dataset
l = unpack (subchart^.label)
norm n y = Chart.LogValue (realToFrac y) / realToFrac n
-- Yes, you read that correctly, whether the axis is linear or log, which
-- really should be a property of the *axes*, is in fact a property of *each
-- individual data point*. I cannot understand why this is the case.
unwrapSingles xs = [ x | Dataset.P1 x <- xs ]
unwrapPoints ps = [ (x, Chart.LogValue y) | Dataset.P2 x y <- ps ]
|
SilverSylvester/cplot
|
src/Chart/Backend/Chart.hs
|
mit
| 5,672
| 0
| 20
| 1,561
| 1,409
| 731
| 678
| -1
| -1
|
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Control.Concurrent.Compat"
-- from a globally unique namespace.
module Control.Concurrent.Compat.Repl (
module Control.Concurrent.Compat
) where
import "this" Control.Concurrent.Compat
|
haskell-compat/base-compat
|
base-compat/src/Control/Concurrent/Compat/Repl.hs
|
mit
| 304
| 0
| 5
| 31
| 28
| 21
| 7
| 5
| 0
|
module Jakway.Blackjack.Interface.Config where
import Jakway.Blackjack.AI
import Jakway.Blackjack.IO.TableNames
data Config = Config
{ verbose :: Bool,
whichDealer :: AI,
playerAIs :: [AI],
numGames :: Integer,
tableNames :: TableNames,
psqlConnString :: Maybe String
}
|
tjakway/blackjack-simulator
|
src/Jakway/Blackjack/Interface/Config.hs
|
mit
| 367
| 0
| 9
| 129
| 72
| 47
| 25
| 10
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Canteven.Url(
URL,
(</>)
) where
import Data.Monoid ((<>))
import Data.Text (Text, dropWhileEnd)
import qualified Data.Text as T (dropWhile)
type URL = Text
-- |Concatenates a URL and a string of text, and puts a `/` between them. Strips
-- away any `/` characters from the end of the first parameter and the start of
-- the second parameter. Doesn't do any URL-parsing or URL-validation.
(</>) :: URL -> Text -> URL
a </> b = a' <> "/" <> b'
where
a' = dropWhileEnd (== '/') a
b' = T.dropWhile (== '/') b
|
SumAll/haskell-canteven-url
|
src/Canteven/Url.hs
|
mit
| 573
| 0
| 8
| 123
| 130
| 80
| 50
| 12
| 1
|
{-
Copyright (C) 2012-2017 Jimmy Liang, Michal Antkiewicz <http://gsd.uwaterloo.ca>
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 Language.Clafer.IG.Sugarer (sugarClaferModel) where
import Language.Clafer.Common
import Language.Clafer.IG.ClaferModel
import Data.Maybe (fromJust)
import Data.List as List hiding (map)
import Data.Map as Map hiding (map, foldr, foldl)
import Prelude hiding (id)
-- | Sample: maps the id to the its simple name and the number of times its simple name appeared in the census before it
-- | Count: maps the simple name to the total count of the simple name
data Census = Census
(Map Id (Int, String)) -- Sample
(Map String Int) -- Counts
deriving Show
-- | Adds the full name to the census
poll :: Id -> Census -> Census
poll id (Census sample' counts') =
Census sample'' counts''
where
fullName = i_name id
name = makeSimpleName fullName
counts'' = insertWith (+) name 1 counts'
ordinal' = findWithDefault (error $ "Did not find " ++ name ++ " in counts.") name counts''
sample'' = insertWith (error $ "Polled " ++ fullName ++ " twice in the census.") id (ordinal', name) sample'
-- Transforms c2_name -> name
makeSimpleName :: String -> String
makeSimpleName name' = case dropWhile (/='_') name' of
"" -> error "Unexpected Clafer name " ++ name'
x -> tail x
-- | Count the number of each clafer
claferModelCensus :: ClaferModel -> Census
claferModelCensus (ClaferModel topLevelClafers) =
clafersCensus (Census Map.empty Map.empty) topLevelClafers
where
clafersCensus = foldl claferCensus
claferCensus census Clafer{c_id=id, c_children=children} = poll id (clafersCensus census children)
-- | Rewrite the model into a human-friendlier format
sugarClaferModel:: Bool -> Bool -> UIDIClaferMap -> ClaferModel -> (Map Int String) -> ClaferModel
sugarClaferModel useUids addTypes uidIClaferMap' model@(ClaferModel topLevelClafers) sMap =
ClaferModel $ map sugarClafer topLevelClafers
where
sugarClafer (Clafer id value children) =
Clafer (sugarId useUids addTypes True id) (sugarValue (Clafer id value children)) (map sugarClafer children)
sugarValue (Clafer _ (Just (AliasValue alias)) _) = Just $ AliasValue $ sugarId useUids addTypes False alias
sugarValue (Clafer _ Nothing _) = Nothing
sugarValue c = if (cType c) == "string" then (Just ((StringValue) (getString c))) else (c_value c)
cType (Clafer id _ _) = cTypeSolve $ getReference iclafer
where
iclafer = fromJust $ findIClafer uidIClaferMap' $ i_name id
cTypeSolve ["string"] = "string"
cTypeSolve ["integer"] = "integer"
cTypeSolve ["int"] = "integer"
cTypeSolve ["real"] = "real"
cTypeSolve _ = ""
getString c = case (Map.lookup strNumber sMap) of
Nothing -> "\"<text " ++ show strNumber ++ ">\""
Just s -> s
where strNumber = v_value $ fromJust $ c_value c
Census sample' counts' = claferModelCensus model
sugarId :: Bool -> Bool -> Bool -> Id -> Id
sugarId useUids' addTypes' addRefDecl id =
Id (finalName ++ ordinalDisplay ++ (refDecl addTypes' addRefDecl uidIClaferMap')) 0
where
fullName = i_name id
ordinalDisplay = if (useUids || count > 1)
then "$" ++ show ordinal
else ""
refDecl :: Bool -> Bool -> UIDIClaferMap -> String
refDecl True True uidIClaferMap'' = retrieveSuper useUids' uidIClaferMap'' $ i_name id
refDecl _ _ _ = ""
(ordinal, simpleName) = findWithDefault (error $ "Sample lookup " ++ show id ++ " failed.") id sample'
count = findWithDefault (error $ "Count lookup " ++ simpleName ++ " failed.") simpleName counts'
finalName = if useUids' then fullName else simpleName
retrieveSuper :: Bool -> UIDIClaferMap -> String -> String
retrieveSuper useUids' uidIClaferMap' uid =
sugarSuper (getSuper iclafer)
-- ++
-- sugarReference (getReference iclafer)
where
iclafer = fromJust $ findIClafer uidIClaferMap' uid
sugarSuper :: [String] -> String
sugarSuper [s] = " : " ++ if useUids' then s else makeSimpleName s
sugarSuper _ = ""
-- sugarReference :: [String] -> String
-- sugarReference [s] = " -> " ++ s
-- sugarReference _ = ""
|
gsdlab/claferIG
|
src/Language/Clafer/IG/Sugarer.hs
|
mit
| 5,461
| 0
| 13
| 1,303
| 1,157
| 611
| 546
| 68
| 12
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Commander.S3 where
import Data.Conduit.Binary (sourceFile)
import Data.Monoid
import Data.List
import Control.Lens
import Control.Monad.Reader
import Control.Monad.State
import Network.AWS
import Network.AWS.Data.Body
import Network.AWS.S3
import Katip
import Data.Text (Text)
import qualified Data.Text as Text
import System.IO
import System.Posix
import Commander.Types
getLocalFileSize :: FilePath -> IO Integer
getLocalFileSize = fmap (fromIntegral . fileSize) . getFileStatus
uploadScript :: (MonadAWS m, MonadReader AppConfig m, MonadState AppState m) => Text -> FilePath -> m ()
uploadScript name path = do
bucket <- view $ configFile . awsBucket
body <- makeRequestBody path
let getLastElementOfPath :: FilePath -> Text
getLastElementOfPath = Text.concat . take 1 . reverse . Text.splitOn "/" . Text.pack
objectKey :: Text
objectKey = name <> "-" <> (getLastElementOfPath path)
send $ putObject (BucketName bucket) (ObjectKey objectKey) body
scriptsToRun <>= objectKey:[]
where
makeRequestBody :: MonadIO m => FilePath -> m RqBody
makeRequestBody path = do
fsize <- liftIO $ getLocalFileSize path
return $ Chunked (ChunkedBody defaultChunkSize fsize $ sourceFile path)
uploadScripts :: ( MonadAWS m
, MonadState AppState m
, MonadReader AppConfig m
, KatipContext m ) => Text -> [FilePath] -> m ()
uploadScripts name = mapM_ (uploadScript name)
|
Flogistix/aws-commander
|
src/Commander/S3.hs
|
mit
| 1,550
| 0
| 14
| 314
| 455
| 238
| 217
| 39
| 1
|
import Ohua.Prelude
import Control.Exception (evaluate)
import Test.Hspec
import Test.Hspec.QuickCheck
import Ohua.Test
import Ohua.DFLang.Parser
import Ohua.DFLang.Lang
import Ohua.ALang.PPrint
import Ohua.DFLang.PPrint ()
import Ohua.Types.Arbitrary
dfLangParserPPrinterSpec :: Spec
dfLangParserPPrinterSpec =
describe "let-expression pretty printing is parseable" $
prop "it works" $ \randExpr ->
randExpr `shouldBe`
parseExp (encodeUtf8 $ quickRender (randExpr :: DFExpr))
dflangParseSpec :: Spec
dflangParseSpec =
describe "dflang parsing" $ do
let op = DFFnRef OperatorNode
sf = DFFnRef FunctionNode
num = DFEnvVar . NumericLit
env = DFEnvVar . EnvRefLit
it "parses a simple let expression" $
parseExp "let (a) = b/c<0>() in d" `shouldBe`
DFExpr [LetExpr 0 ["a"] (sf "b/c") Nothing []] "d"
it "parses a let expression with variable arguments" $ do
parseExp "let (a) = some.ns/func<2>(a) in var" `shouldBe`
DFExpr [LetExpr 2 ["a"] (sf "some.ns/func") Nothing ["a"]] "var"
parseExp "let (a) = some.other.ns/func2<2>(a, b_d, ugI) in var" `shouldBe`
DFExpr
[ LetExpr
2
["a"]
(sf "some.other.ns/func2")
Nothing
["a", "b_d", "ugI"]
]
"var"
it "parses let expressions with multiple returns" $
parseExp "let (a, f_po0, _8) = b/c<0>() in d" `shouldBe`
DFExpr [LetExpr 0 ["a", "f_po0", "_8"] (sf "b/c") Nothing []] "d"
it "parses let expressions with numeric literal arguments" $
parseExp "let (a) = some.ns/func<2>(0, -80, 1000) in var" `shouldBe`
DFExpr
[ LetExpr
2
["a"]
(sf "some.ns/func")
Nothing
[num 0, num (-80), num 1000]
]
"var"
it "parses let expressions with env literal arguments" $
parseExp "let (a) = some.ns/func<2>($0, $80, $1000) in var" `shouldBe`
DFExpr
[ LetExpr
2
["a"]
(sf "some.ns/func")
Nothing
[env 0, env 80, env 1000]
]
"var"
it "fails to parse negative env literals" $
evaluate (parseExp "let (a) = a/b<5>($-9) in b") `shouldThrow` anyErrorCall
main :: IO ()
main
-- This test should work (and kinda does, but it sometimes seems to get stuck
-- in an infinite loop and I do not have the time to figure out why).
= hspec $ do
dflangParseSpec
unless True dfLangParserPPrinterSpec
|
ohua-dev/ohua-core
|
test-tools/test/Spec.hs
|
epl-1.0
| 2,987
| 0
| 16
| 1,197
| 572
| 297
| 275
| 68
| 1
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN"
"http://java.sun.com/products/javahelp/helpset_1_0.dtd">
<helpset version="1.0">
<!-- title -->
<title>Hilfe zum Modul Heapsort</title>
<!-- maps -->
<maps>
<homeID>heapsort</homeID>
<mapref location="map.jhm"/>
</maps>
<!-- presentations -->
<presentation default="true">
<name>main window</name>
<size width="920" height="450" />
<location x="150" y="150" />
<image>mainicon</image>
<toolbar>
<helpaction>javax.help.BackAction</helpaction>
<helpaction>javax.help.ForwardAction</helpaction>
<helpaction>javax.help.ReloadAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction image="Startseite">javax.help.HomeAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction>javax.help.PrintAction</helpaction>
<helpaction>javax.help.PrintSetupAction</helpaction>
</toolbar>
</presentation>
<!-- views -->
<view mergetype="javax.help.UniteAppendMerge">
<name>TOC</name>
<label>Inhaltsverzeichnis</label>
<type>javax.help.TOCView</type>
<data>heapsortTOC.xml</data>
</view>
<view mergetype="javax.help.SortMerge">
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>heapsortIndex.xml</data>
</view>
<!--
<view xml:lang="de">
<name>Search</name>
<label>Suche</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
-->
</helpset>
|
jurkov/j-algo-mod
|
res/module/heapsort/help/jhelp/heapsort_help.hs
|
gpl-2.0
| 1,644
| 126
| 89
| 221
| 651
| 326
| 325
| -1
| -1
|
--Copyright 2017 by John F. Miller
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
module Test.Parameters
( module Eval.Parameters
, module Test.Parameters
, module Name
, module Object
, quickCheck
)
where
import Control.Monad.State
import Control.Monad.Except
import Data.String
import qualified Data.Map.Strict as M
import Test.QuickCheck
import Name
import String
import Object hiding (State)
import Eval.Parameters
import Scope
import qualified Array as A
newtype S a= S{ uns :: StateT (Namespace Object) (Except Object) a}
deriving (Functor, Applicative, Monad,
MonadState (Namespace Object), MonadError Object)
instance Scope S where
readVar Local n = do
m <- gets (M.lookup n)
return $ fmap (\m ->MV m (\_->return ())) m
readVar _ _ = error "Not included in test setup"
setVar Local n o = do
modify (M.insert n o)
setVar _ _ _ = error "Not included in test setup"
call _ "kind_of" [Prim (VString s)] = if (string s) == "FooClass"
then return $ RO TrueClass
else return $ RO FalseClass
send = undefined
tailCall = undefined
spawn = undefined
presidenceTable = undefined
run :: S a -> Either Object (Namespace Object)
run x = runExcept $ execStateT (uns x) (M.empty)
runMatch p xs = run $ match p xs
instance Arbitrary Object where
arbitrary = Prim <$> arbitrary
instance Arbitrary Primitive where
arbitrary = oneof [
VInt <$> arbitrary
, VString . fromString <$> arbitrary
, VFloat <$> arbitrary
, VAtom <$> arbitrary
, VArray . A.fromList <$> arbitrary
]
prop_Empty xs = --Empty only matches the empty list
if (length xs) == 0
then
case r of
Right _ -> True
Left _ -> False
else
case r of
Right _ -> False
Left _ -> True
where r = runMatch Empty xs
prop_Asterisk xs = -- an Astrisk should match everything
let r = runMatch (Asterisk "foo") xs in
case r of
Left _ -> False
Right m -> maybe False (\_ -> True) (M.lookup "foo" m)
|
antarestrader/sapphire
|
Test/Parameters.hs
|
gpl-3.0
| 2,049
| 0
| 16
| 510
| 674
| 357
| 317
| 62
| 4
|
{-# LANGUAGE ExistentialQuantification, RankNTypes #-}
module SymLens.Database where
import SymLens
import Database.Memory
import qualified Data.Map as Map
import qualified Data.Bimap as Bimap
import Data.Maybe (fromMaybe,fromJust,maybe)
import qualified Data.Tuple as T
type TableLens = SymLens Table Table
type DatabaseLens = SymLens Database Database
liftTableLens :: Name -> TableLens -> DatabaseLens
liftTableLens n (SymLens s pr pl) = SymLens s (doit pr) (doit pl)
where doit put d c = T.swap $ Map.mapAccumWithKey onT c d
where onT c n' t | n == n' = T.swap $ put t c
| otherwise = (c,t)
rename :: Name -> Name -> DatabaseLens
rename n1 n2 = SymLens () put put
where sigma n | n == n1 = n2
| n == n2 = n1
| otherwise = n
put d () = (Map.mapKeys sigma d, ())
drop :: Name -> DatabaseLens
drop n = SymLens Nothing pr pl
where pr d c = maybe (d,c) trans $ Map.lookup n d
where trans t' = (Map.delete n d, Just t')
pl d Nothing = (d, Nothing)
pl d c@(Just v) = (Map.insert n v d,c)
-- Can this be implemented using drop ??
-- Keep track of added and deleted records while coming from right to left.
insert :: Name -> Table -> DatabaseLens
insert n t@(Table _ m) = SymLens Nothing pr pl
where pr d Nothing = (Map.insert n t d, Just t)
pr d c@(Just t') = (Map.insert n t' d, c)
pl d c = maybe (d,c) trans $ Map.lookup n d
where trans t' = (Map.delete n d, Just t')
-- Take a pred depending on which the new records will go to n1 or n2.
-- putr :: Database with (n1,n2) and without n -> Database with n and without (n1,n2)
-- putl :: Database with n and without (n1,n2) -> Database with (n1,n2) and without n
-- Compelement is a pair of maps mapping keys from the the two initial tables to the appended table
append :: (Id -> Fields -> Bool)
-> Name
-> Name
-> Name
-> DatabaseLens
append on n1 n2 n = SymLens (Bimap.empty, Bimap.empty) pr pl
where pr d c@(lc,rc) = case (Map.lookup n1 d, Map.lookup n2 d) of
(Just (Table h1 m1), Just (Table h2 m2)) | h1 == h2 -> (Map.insert n (Table h1 m') $ Map.delete n1 $ Map.delete n2 d, (lc', rc'))
where (m', rc', _) = Map.foldlWithKey combine (m, rc, newkey') m2
(m, lc', newkey') = Map.foldlWithKey combine (Map.empty, lc, newkey) m1
combine (m, c, nextkey) k v =
case Bimap.lookup k c of
Just k' -> (Map.insert k' v m, c, nextkey)
Nothing -> (Map.insert nextkey v m, Bimap.insert k nextkey c, nextkey + 1)
newkey = (maxR lc `max` maxR rc) + 1
maxR bm = if Bimap.null bm then -1 else fst $ Bimap.findMaxR bm
_ -> (d,c)
pl d c@(lc, rc) = case Map.lookup n d of
Just (Table h m) -> (Map.insert n1 (Table h m1) $ Map.insert n2 (Table h m2) $ Map.delete n d, (lc', rc'))
where m1' = Map.mapKeys (fromJust . flip Bimap.lookupR lc) $ Map.intersection m lcmap
m2' = Map.mapKeys (fromJust . flip Bimap.lookupR rc) $ Map.intersection m rcmap
(m1,m2,(lc',rc'),_) = Map.foldlWithKey combine (m1',m2',(lc,rc),(next1,next2)) rest
rest = Map.difference (Map.difference m lcmap) rcmap
combine (m1,m2,(lc',rc'),(next1,next2)) k v
| on k v = (Map.insert next1 v m1, m2, (Bimap.insert next1 k lc', rc'), (next1 + 1, next2))
| otherwise = (m1, Map.insert next2 v m2, (lc', Bimap.insert next2 k rc'), (next1, next2 + 1))
next1 = maybe 0 ((+1) . fst . fst) $ Map.maxViewWithKey m1'
next2 = maybe 0 ((+1) . fst . fst) $ Map.maxViewWithKey m2'
lcmap = Bimap.toMapR lc
rcmap = Bimap.toMapR rc
_ -> (d,c)
{- pl d c@(lc, rc) = case Map.lookup n d of
Just (Table h m) -> (Map.insert n1 (Table h m1) $ Map.insert n2 (Table h m2) $ Map.delete n d, (lc', rc'))
where m1' = Map.mapKeys (fromJust . flip Map.lookup lc) $ Map.intersection m lc
m2' = Map.mapKeys (fromJust . flip Map.lookup rc) $ Map.intersection m rc
(m1,m2,(lc',rc'),_)
= Map.foldlWithKey combine (m1',m2',(lc,rc),(next1,next2))
$ rest
rest = Map.difference (Map.difference m lc) rc
combine (m1,m2,(lc',rc'),(next1,next2)) k v
| on k v = (Map.insert next1 v m1, m2, (Map.insert k next1 lc', rc'), (next1 + 1, next2))
| otherwise = (m1, Map.insert next2 v m2, (lc', Map.insert k next2 rc'), (next1, next2 + 1))
next1 = maybe 0 ((+1) . fst . fst) $ Map.maxViewWithKey m1'
next2 = maybe 0 ((+1) . fst . fst) $ Map.maxViewWithKey m2'
_ -> (d,c)
-}
-- | Takes a function to filter the table on and then splits the table
-- into two tables, first satisfying the predicate and other the rest.
-- I doubt this is not a lens. Consider t split on f to t1 and t2. Now
-- we insert a record r to t1 satisying ~f. Then the lens laws will be
-- broken. Maintain two tables of additional records added and apply
-- f if r is not in these table otherwise just split based on r
-- belongs to which table.
split :: (Id -> Fields -> Bool) -> Name -> Name -> Name -> DatabaseLens
split on n n1 n2 = inv $ append on n1 n2 n
|
cornell-pl/evolution
|
SymLens/Database.hs
|
gpl-3.0
| 5,713
| 0
| 17
| 1,913
| 1,615
| 856
| 759
| 66
| 5
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module Qlogic.SatSolver
(
SatSolver(..)
, Solver(..)
, Clause(..)
, Decoder(..)
, (:&:) (..)
, addFormula
, fix
, value
, freshLit
, getAssign
, runSolver
, liftS
, liftIO
)
where
import System.IO.Unsafe (unsafePerformIO)
import Control.Monad
import Control.Monad.Trans (lift, liftIO, MonadIO)
import qualified Control.Monad.State.Lazy as State
import qualified Data.HashTable as Hash
import qualified Qlogic.Assign as Assign
import Qlogic.Assign (Assign, (|->))
import Data.Typeable
import qualified Control.Monad.State.Class as StateClass
import Prelude hiding (negate)
import Qlogic.Formula
import Qlogic.PropositionalFormula
newtype Clause l = Clause {clauseToList :: [l]}
class Monad s => Solver s l | s -> l where
solve :: s Bool
run :: s a -> IO a
newLit :: s l
negate :: l -> s l
addClause :: Clause l -> s Bool
getModelValue :: l -> s Bool
class Solver s l => IncrementalSolver s l where
okay :: s () -> s Bool
data ExtLit l = Lit !l | TopLit | BotLit deriving (Eq, Show)
data Polarity = PosPol | NegPol
newtype SatSolver s l r = SatSolver (State.StateT (Hash.HashTable PA l) s r)
deriving (Monad, StateClass.MonadState (Hash.HashTable PA l), MonadIO)
liftS :: Solver s l => s r -> SatSolver s l r
liftS = SatSolver . lift
freshLit :: Solver s l => SatSolver s l l
freshLit = liftS newLit
freshELit :: Solver s l => SatSolver s l (ExtLit l)
freshELit = Lit `liftM` freshLit
atomToELit :: (MonadIO s, Solver s l) => PA -> SatSolver s l (ExtLit l)
atomToELit a = do litMap <- State.get
lu <- liftIO $ Hash.lookup litMap a
case lu of
Just oldLit -> return $ Lit oldLit
Nothing -> do l <- freshLit
liftIO $ Hash.insert litMap a l
return (Lit l)
negateELit :: (Solver s l) => ExtLit l -> SatSolver s l (ExtLit l)
negateELit (Lit x) = Lit `liftM` liftS (negate x)
negateELit TopLit = return BotLit
negateELit BotLit = return TopLit
plit :: (MonadIO s, Solver s l) => PropFormula l -> SatSolver s l (ExtLit l)
plit (A x) = atomToELit x
plit (SL x) = return $ Lit x
plit Top = return TopLit
plit Bot = return BotLit
plit (Neg x) = nlit x
plit fm = freshELit
nlit :: (MonadIO s, Solver s l) => PropFormula l -> SatSolver s l (ExtLit l)
nlit fm = plit fm >>= negateELit
freshELits :: (Monad s, Solver s l) => SatSolver s l (ExtLit l, ExtLit l)
freshELits = do p <- freshELit
n <- negateELit p
return (p,n)
addLitClause :: (Eq l, Solver s l) => Clause (ExtLit l) -> SatSolver s l Bool
addLitClause (Clause ls) = case foldr f (Just []) ls of
Nothing -> return True
Just lits -> liftS $ addClause $ Clause lits
where f (Lit x) (Just xs) = Just $ x:xs
f BotLit xs = xs
f TopLit xs = Nothing
f _ Nothing = Nothing
addPositively :: (Eq l, MonadIO s, Solver s l) => PropFormula l -> SatSolver s l (ExtLit l)
addPositively fm@(Neg a) = addNegatively a >>= negateELit
addPositively fm@(A _) = plit fm
addPositively fm@(SL l) = plit fm
addPositively Top = return TopLit
addPositively Bot = return BotLit
addPositively fm = do (p,n) <- freshELits
addPositively' (p,n) fm
addPositively' :: (Eq l, MonadIO s, Solver s l) => (ExtLit l,ExtLit l) -> PropFormula l -> SatSolver s l (ExtLit l)
addPositively' (p,n) fm@(And as) =
do plits <- mapM addPositively as
mapM_ (\l -> addLitClause $ Clause [n, l]) plits
return p
addPositively' (p,n) fm@(Or as) =
do plits <- mapM addPositively as
addLitClause $ Clause $ n:plits
return p
addPositively' (p,n) fm@(a `Iff` b) =
do apos <- addPositively a
aneg <- addNegatively a >>= negateELit
bpos <- addPositively b
bneg <- addNegatively b >>= negateELit
addLitClause $ Clause [n, aneg, bpos]
addLitClause $ Clause [n, apos, bneg]
return p
addPositively' (p,n) fm@(Ite g t e) =
do gpos <- addPositively g
gneg <- addNegatively g >>= negateELit
tpos <- addPositively t
epos <- addPositively e
addLitClause $ Clause [n, gneg, tpos]
addLitClause $ Clause [n, gpos, epos]
return p
addPositively' (p,n) fm@(a `Imp` b) =
do aneg <- addNegatively a >>= negateELit
bpos <- addPositively b
addLitClause $ Clause [n, aneg, bpos]
return p
addPositively' (p,n) fm@(Neg a) = do addNegatively' (n,p) a
return p
addPositively' (p,n) fm@(A _) = do l <- plit fm
addLitClause $ Clause [n, l]
return l
addPositively' (_,n) fm@(SL l) = do l <- plit fm
addLitClause $ Clause [n, l]
return l
addPositively' (_,_) Top = return TopLit
addPositively' (_,n) Bot = addLitClause (Clause [n]) >> return BotLit
addNegatively :: (Eq l, MonadIO s, Solver s l) => PropFormula l -> SatSolver s l (ExtLit l)
addNegatively fm@(Neg a) = addPositively a >>= negateELit
addNegatively fm@(A _) = plit fm
addNegatively fm@(SL l) = plit fm
addNegatively Top = return TopLit
addNegatively Bot = return BotLit
addNegatively fm = do (p,n) <- freshELits
addNegatively' (p,n) fm
addNegatively' :: (Eq l, MonadIO s, Solver s l) => (ExtLit l, ExtLit l) -> PropFormula l -> SatSolver s l (ExtLit l)
addNegatively' (p,n) fm@(And as) =
do nlits <- mapM (\l -> addNegatively l >>= negateELit) as
addLitClause $ Clause $ p:nlits
return p
addNegatively' (p,n) fm@(Or as) =
do nlits <- mapM (\l -> addNegatively l >>= negateELit) as
mapM_ (\l -> addLitClause $ Clause [p, l]) nlits
return p
addNegatively' (p,n) fm@(a `Iff` b) =
do apos <- addPositively a
aneg <- addNegatively a >>= negateELit
bpos <- addPositively b
bneg <- addNegatively b >>= negateELit
addLitClause $ Clause [p, apos, bpos]
addLitClause $ Clause [p, aneg, bneg]
return p
addNegatively' (p,n) fm@(Ite g t e) =
do gpos <- addPositively g
gneg <- addNegatively g >>= negateELit
tneg <- addNegatively t >>= negateELit
eneg <- addNegatively e >>= negateELit
addLitClause $ Clause [p, gneg, tneg]
addLitClause $ Clause [p, gpos, eneg]
return p
addNegatively' (p,n) fm@(a `Imp` b) =
do apos <- addPositively a
bneg <- addNegatively b >>= negateELit
addLitClause $ Clause [p, apos]
addLitClause $ Clause [p, bneg]
return p
addNegatively' (p,n) fm@(Neg a) = do addPositively' (n,p) a
return p
addNegatively' (p,n) fm@(A _) = do l' <- plit fm >>= negateELit
addLitClause $ Clause [l',p]
return n
addNegatively' (p,n) fm@(SL l) = do l' <- plit fm >>= negateELit
addLitClause $ Clause [l',p]
return n
addNegatively' (p,_) Top = addLitClause (Clause [p]) >> return TopLit
addNegatively' (_,n) Bot = return BotLit
addFormula :: (Show l, Eq l, MonadIO s, Solver s l) => PropFormula l -> SatSolver s l ()
addFormula fm =
-- unsafePerformIO $ do putStrLn $ show fm
-- return $
do p <- addPositively fm
addLitClause $ Clause [p]
return ()
fix :: (Eq l, MonadIO s, Solver s l) => l -> PropFormula l -> SatSolver s l ()
fix l fm = do n <- negateELit elit
addPositively' (elit,n) fm
addNegatively' (elit,n) fm
return ()
-- unsafePerformIO ((putStrLn $ show l ++ " := " ++ show fm) >> (return $ return ()))
where elit = Lit l
class Typeable a => Decoder e a | e -> a, a -> e where
extract :: PA -> Maybe a
extract (PA a) = cast a
add :: a -> e -> e
data a :&: b = a :&: b
data OneOf a b = Foo a | Bar b deriving Typeable
instance (Decoder e1 a1, Decoder e2 a2) => Decoder (e1 :&: e2) (OneOf a1 a2) where
extract a = case extract a of
Just a' -> Just $ Foo a'
Nothing -> case extract a of
Just a' -> Just $ Bar a'
Nothing -> Nothing
add (Foo a) (e1 :&: e2) = add a e1 :&: e2
add (Bar b) (e1 :&: e2) = e1 :&: (add b e2)
constructValue :: (Decoder e a, MonadIO s, Solver s l) => e -> SatSolver s l e
constructValue e = do s <- State.get >>= liftIO . Hash.toList
foldl f (return e) s
where f m (atm, v) = case extract atm of
Just a -> (liftS $ getModelValue v) >>= \ val -> if val then add a `liftM` m else m
Nothing -> m
getAssign :: (Ord l, MonadIO s, Solver s l) => SatSolver s l (Assign l)
getAssign = do s <- State.get >>= liftIO . Hash.toList
foldl f (return Assign.empty) s
where f m (k, l) = do assign <- m
v <- liftS $ getModelValue l
return $ Assign.add [Right k |-> v] assign
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM mc mt me = do c <- mc
if c then mt else me
runSolver :: (Solver s l) => SatSolver s l r -> IO r
runSolver (SatSolver m) = do s <- Hash.new (==) (Hash.hashString . take 20 . show)
run $ State.evalStateT m s
value :: (Decoder e a, MonadIO s, Solver s l) => SatSolver s l () -> e -> IO (Maybe e)
value m p = runSolver $ m >> ifM (liftS solve) (Just `liftM` constructValue p) (return Nothing)
|
mzini/qlogic
|
Qlogic/SatSolverHash.hs
|
gpl-3.0
| 10,044
| 0
| 14
| 3,173
| 4,080
| 2,063
| 2,017
| 232
| 5
|
{-
This file is part of HNH.
HNH 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.
HNH 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 HNH. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010 Francisco Ferreira
-}
module ProgToLet
(
progToLet
)
where
import Syntax
import TransformMonad(TransformM, transformOk, transformError)
import ErrorMonad(ErrorM(..))
import TypeUtils(getType, isVarDecl)
import Data.List(find, partition)
progToLet :: Program -> TransformM Program
progToLet (Program decls) =
case findMain decls of
Error msg -> transformError msg
Success main -> transformOk
"progToLet"
(Program
(dataDecls
++ [mainToLet
main (filter (not . isMain) varDecls)]))
where
(varDecls, dataDecls) = partition isVarDecl decls
findMain :: Monad m => [Declaration] -> m Declaration
findMain decls =
case find isMain decls of Just d -> return d
Nothing -> fail "main symbol not found"
isMain (PatBindDcl p e) = case p of (IdVarPat (Id "main"_) _) -> True
_ -> False
isMain d = False
mainToLet :: Declaration -> [Declaration] -> Declaration
mainToLet d@(PatBindDcl p e) decls =
if length decls > 0 then
(PatBindDcl p (LetExp decls e (getType e)))
else
d
|
fferreira/hnh
|
ProgToLet.hs
|
gpl-3.0
| 1,903
| 0
| 18
| 567
| 369
| 193
| 176
| 31
| 2
|
{-
Assembly Language Monad
Part of Aex
Copyright (C) 2015 Jeffrey Sharp
-}
{-# LANGUAGE OverloadedStrings #-}
module Asm where
import Control.Monad.State.Lazy
import Data.Monoid (mconcat, (<>))
import Data.Text.Lazy (Text)
import Data.Text.Lazy.Builder (Builder, fromLazyText, toLazyText)
data AsmState = AsmState
{ asmOut :: Builder -- accumulated output
}
initState :: AsmState
initState = AsmState { asmOut = "" }
append :: Builder -> AsmState -> AsmState
append b AsmState { asmOut = o }
= AsmState { asmOut = o <> b }
type Asm a = State AsmState a
assemble :: Asm a -> Text
assemble asm = toLazyText . asmOut . execAsm asm $ initState
runAsm :: Asm a -> AsmState -> (a, AsmState)
runAsm = runState
evalAsm :: Asm a -> AsmState -> a
evalAsm = evalState
execAsm :: Asm a -> AsmState -> AsmState
execAsm = execState
write :: Builder -> Asm ()
write = modify . append
section :: Text -> Asm ()
section t = write
$ ".section "
<> fromLazyText t
<> eol
directive :: Text -> [Text] -> Asm ()
directive op args = write
$ indent
<> fromLazyText op
<> " "
<> mconcat (fromLazyText <$> args)
<> eol
indent :: Builder
indent = "\t"
eol :: Builder
eol = "\n"
|
sharpjs/haskell-learning
|
before-stack/Asm.hs
|
gpl-3.0
| 1,260
| 0
| 9
| 317
| 395
| 219
| 176
| 40
| 1
|
{-# language FlexibleContexts, TypeFamilies #-}
module Data.Sparse.Internal.SVector.Mutable where
import Data.Foldable
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Generic as VG
import Control.Arrow ((&&&))
import Control.Monad.Primitive
data SMVector m a = SMV { smvDim :: {-# UNPACK #-} !Int,
smvIx :: VM.MVector (PrimState m) Int,
smvVal :: VM.MVector (PrimState m) a }
fromList :: (PrimMonad m) => Int -> [(Int, a)] -> m (SMVector m a)
fromList n ixv = do
let ns = length ixv
vm <- VM.new ns
ixm <- VM.new ns
fromListOverwrite ixm vm n ixv
fromListOverwrite :: PrimMonad m =>
VM.MVector (PrimState m) Int
-> VM.MVector (PrimState m) a
-> Int
-> [(Int, a)]
-> m (SMVector m a)
fromListOverwrite ixm vm n ixv = go ixm vm ixv 0
where
go ixm_ vm_ [] _ = return $ SMV n ixm_ vm_
go ixm_ vm_ ((i, x) : xs) iwrite = do
VM.write vm_ iwrite x
VM.write ixm_ iwrite i
go ixm_ vm_ xs (iwrite + 1)
-- instance Foldable (SMVector m) where
-- foldr f z (SMV _ _ v) = foldr f z v
-- instance Traversable (SMVector m) where
-- traverse f (SMV n ix v) = SMV n ix <$> traverse f v
-- | traverse the sparse mutable vector and operate on the union set between the indices of the immutable vector `v` and those of the mutable one `vm`, _overwriting_ the values in vm.
-- Invariant: the index set of `v` is a strict subset of that of `vm` (i.e. we assume that `vm` is preallocated properly, or, we assume there won't be any out-of-bound writes attempted)
unionWithM_prealloc g z v vm@(SMV nvm vmix vmv) = undefined
-- -- | unionWithSMV takes the union of two sparse mutable vectors given a binary function and a neutral element.
-- -- unionWithSMV :: PrimMonad m =>
-- -- (a -> a -> b)
-- -- -> a
-- -- -> SMVector m a
-- -- -> SMVector m a
-- -- -> m (VM.MVector (PrimState m) (Int, b))
-- unionWithSMV g z (SMV n1 ixu uu) (SMV n2 ixv vv) = do
-- vm0 <- VM.new n
-- (vm, nfin) <- go ixu uu ixv vv 0 vm0 -- populate
-- -- let (ixm, vm') = VG.unzip (VM.take nfin vm')
-- let vm_trim = VM.take nfin vm
-- (ixm, vm') = VG.unzip $ VG.convert vm_trim
-- vOut <- V.freeze ixm
-- return (vOut, vm')
-- where
-- headTail = V.head &&& V.tail
-- n = min n1 n2
-- go iu u_ iv v_ i vm
-- | (VM.null u_ && VM.null v_) || i == n = return (vm , i)
-- | VM.null u_ = do
-- v0 <- VM.read v_ 0
-- VM.write vm i (V.head iv, g z v0)
-- go iu u_ (V.tail iv) (VM.tail v_) (i + 1) vm
-- | VM.null v_ = do
-- u0 <- VM.read u_ 0
-- VM.write vm i (V.head iu, g u0 z)
-- go (V.tail iu) (VM.tail u_) iv v_ (i + 1) vm
-- | otherwise = do
-- u <- VM.read u_ 0
-- v <- VM.read v_ 0
-- let us = VM.tail u_
-- vs = VM.tail v_
-- let (iu1, ius) = headTail iu
-- (iv1, ivs) = headTail iv
-- if iu1 == iv1 then do VM.write vm i (iu1, g u v)
-- go ius us ivs vs (i + 1) vm
-- else if iu1 < iv1 then do VM.write vm i (iu1, g u z)
-- go ius us iv v_ (i + 1) vm
-- else do VM.write vm i (iv1, g z v)
-- go iu u_ ivs vs (i + 1) vm
-- -- * helpers
-- -- both :: Arrow arr => arr b c -> arr (b, b) (c, c)
-- -- both f = f *** f
|
ocramz/sparse-linear-algebra
|
src/Data/Sparse/Internal/SVector/Mutable.hs
|
gpl-3.0
| 3,698
| 0
| 12
| 1,320
| 489
| 283
| 206
| 30
| 2
|
{- |
Module : Data.Grib.Raw.ContextSpec
Copyright : (c) Mattias Jakobsson 2015
License : GPL-3
Maintainer : mjakob422@gmail.com
Stability : unstable
Portability : portable
Unit and regression tests for Data.Grib.Raw.Context.
-}
module Data.Grib.Raw.ContextSpec ( main, spec ) where
import Control.Exception ( bracket )
import Test.Hspec
import Data.Grib.Raw
main :: IO ()
main = hspec spec
withGribexMode :: GribContext -> IO () -> IO ()
withGribexMode ctx action =
bracket saveMode restoreMode (const action)
where saveMode = gribGetGribexMode ctx
restoreMode True = gribGribexModeOn ctx
restoreMode False = gribGribexModeOff ctx
spec :: Spec
spec = do
let ctx = defaultGribContext
describe "gribContextGetDefault" $
it "should not return a null context" $
gribContextGetDefault `shouldNotReturn` defaultGribContext
describe "gribContextNew" $ do
it "should not return a null context" $
gribContextNew ctx `shouldNotReturn` defaultGribContext
it "should not return the default context" $
gribContextGetDefault >>= (gribContextNew ctx `shouldNotReturn`)
describe "gribGtsHeaderOff" $
it "should return nothing" $
gribGtsHeaderOff ctx `shouldReturn` ()
describe "gribGtsHeaderOn" $ after_ (gribGtsHeaderOff ctx) $
it "should return nothing" $
gribGtsHeaderOn ctx `shouldReturn` ()
describe "gribGribexModeOn" $ around_ (withGribexMode ctx) $
it "should enable gribex mode" $ do
gribGribexModeOn ctx `shouldReturn` ()
gribGetGribexMode ctx `shouldReturn` True
describe "gribGribexModeOff" $ around_ (withGribexMode ctx) $
it "should disable gribex mode" $ do
gribGribexModeOff ctx `shouldReturn` ()
gribGetGribexMode ctx `shouldReturn` False
describe "gribMultiSupportOff" $
it "should return nothing" $
gribMultiSupportOff ctx `shouldReturn` ()
describe "gribMultiSupportOn" $ after_ (gribMultiSupportOff ctx) $
it "should return nothing" $
gribMultiSupportOn ctx `shouldReturn` ()
|
mjakob/hgrib
|
test/Data/Grib/Raw/ContextSpec.hs
|
gpl-3.0
| 2,071
| 0
| 13
| 430
| 478
| 233
| 245
| 43
| 2
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Dataflow.Projects.Locations.Jobs.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 the jobs of a project. To list the jobs of a project in a region,
-- we recommend using \`projects.locations.jobs.list\` with a [regional
-- endpoint]
-- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints).
-- To list the all jobs across all regions, use
-- \`projects.jobs.aggregated\`. Using \`projects.jobs.list\` is not
-- recommended, as you can only get the list of jobs that are running in
-- \`us-central1\`.
--
-- /See:/ <https://cloud.google.com/dataflow Dataflow API Reference> for @dataflow.projects.locations.jobs.list@.
module Network.Google.Resource.Dataflow.Projects.Locations.Jobs.List
(
-- * REST Resource
ProjectsLocationsJobsListResource
-- * Creating a Request
, projectsLocationsJobsList
, ProjectsLocationsJobsList
-- * Request Lenses
, pljlXgafv
, pljlUploadProtocol
, pljlLocation
, pljlAccessToken
, pljlUploadType
, pljlView
, pljlFilter
, pljlPageToken
, pljlProjectId
, pljlPageSize
, pljlCallback
) where
import Network.Google.Dataflow.Types
import Network.Google.Prelude
-- | A resource alias for @dataflow.projects.locations.jobs.list@ method which the
-- 'ProjectsLocationsJobsList' request conforms to.
type ProjectsLocationsJobsListResource =
"v1b3" :>
"projects" :>
Capture "projectId" Text :>
"locations" :>
Capture "location" Text :>
"jobs" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "view" ProjectsLocationsJobsListView :>
QueryParam "filter" ProjectsLocationsJobsListFilter
:>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListJobsResponse
-- | List the jobs of a project. To list the jobs of a project in a region,
-- we recommend using \`projects.locations.jobs.list\` with a [regional
-- endpoint]
-- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints).
-- To list the all jobs across all regions, use
-- \`projects.jobs.aggregated\`. Using \`projects.jobs.list\` is not
-- recommended, as you can only get the list of jobs that are running in
-- \`us-central1\`.
--
-- /See:/ 'projectsLocationsJobsList' smart constructor.
data ProjectsLocationsJobsList =
ProjectsLocationsJobsList'
{ _pljlXgafv :: !(Maybe Xgafv)
, _pljlUploadProtocol :: !(Maybe Text)
, _pljlLocation :: !Text
, _pljlAccessToken :: !(Maybe Text)
, _pljlUploadType :: !(Maybe Text)
, _pljlView :: !(Maybe ProjectsLocationsJobsListView)
, _pljlFilter :: !(Maybe ProjectsLocationsJobsListFilter)
, _pljlPageToken :: !(Maybe Text)
, _pljlProjectId :: !Text
, _pljlPageSize :: !(Maybe (Textual Int32))
, _pljlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsJobsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pljlXgafv'
--
-- * 'pljlUploadProtocol'
--
-- * 'pljlLocation'
--
-- * 'pljlAccessToken'
--
-- * 'pljlUploadType'
--
-- * 'pljlView'
--
-- * 'pljlFilter'
--
-- * 'pljlPageToken'
--
-- * 'pljlProjectId'
--
-- * 'pljlPageSize'
--
-- * 'pljlCallback'
projectsLocationsJobsList
:: Text -- ^ 'pljlLocation'
-> Text -- ^ 'pljlProjectId'
-> ProjectsLocationsJobsList
projectsLocationsJobsList pPljlLocation_ pPljlProjectId_ =
ProjectsLocationsJobsList'
{ _pljlXgafv = Nothing
, _pljlUploadProtocol = Nothing
, _pljlLocation = pPljlLocation_
, _pljlAccessToken = Nothing
, _pljlUploadType = Nothing
, _pljlView = Nothing
, _pljlFilter = Nothing
, _pljlPageToken = Nothing
, _pljlProjectId = pPljlProjectId_
, _pljlPageSize = Nothing
, _pljlCallback = Nothing
}
-- | V1 error format.
pljlXgafv :: Lens' ProjectsLocationsJobsList (Maybe Xgafv)
pljlXgafv
= lens _pljlXgafv (\ s a -> s{_pljlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pljlUploadProtocol :: Lens' ProjectsLocationsJobsList (Maybe Text)
pljlUploadProtocol
= lens _pljlUploadProtocol
(\ s a -> s{_pljlUploadProtocol = a})
-- | The [regional endpoint]
-- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints)
-- that contains this job.
pljlLocation :: Lens' ProjectsLocationsJobsList Text
pljlLocation
= lens _pljlLocation (\ s a -> s{_pljlLocation = a})
-- | OAuth access token.
pljlAccessToken :: Lens' ProjectsLocationsJobsList (Maybe Text)
pljlAccessToken
= lens _pljlAccessToken
(\ s a -> s{_pljlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pljlUploadType :: Lens' ProjectsLocationsJobsList (Maybe Text)
pljlUploadType
= lens _pljlUploadType
(\ s a -> s{_pljlUploadType = a})
-- | Deprecated. ListJobs always returns summaries now. Use GetJob for other
-- JobViews.
pljlView :: Lens' ProjectsLocationsJobsList (Maybe ProjectsLocationsJobsListView)
pljlView = lens _pljlView (\ s a -> s{_pljlView = a})
-- | The kind of filter to use.
pljlFilter :: Lens' ProjectsLocationsJobsList (Maybe ProjectsLocationsJobsListFilter)
pljlFilter
= lens _pljlFilter (\ s a -> s{_pljlFilter = a})
-- | Set this to the \'next_page_token\' field of a previous response to
-- request additional results in a long list.
pljlPageToken :: Lens' ProjectsLocationsJobsList (Maybe Text)
pljlPageToken
= lens _pljlPageToken
(\ s a -> s{_pljlPageToken = a})
-- | The project which owns the jobs.
pljlProjectId :: Lens' ProjectsLocationsJobsList Text
pljlProjectId
= lens _pljlProjectId
(\ s a -> s{_pljlProjectId = a})
-- | If there are many jobs, limit response to at most this many. The actual
-- number of jobs returned will be the lesser of max_responses and an
-- unspecified server-defined limit.
pljlPageSize :: Lens' ProjectsLocationsJobsList (Maybe Int32)
pljlPageSize
= lens _pljlPageSize (\ s a -> s{_pljlPageSize = a})
. mapping _Coerce
-- | JSONP
pljlCallback :: Lens' ProjectsLocationsJobsList (Maybe Text)
pljlCallback
= lens _pljlCallback (\ s a -> s{_pljlCallback = a})
instance GoogleRequest ProjectsLocationsJobsList
where
type Rs ProjectsLocationsJobsList = ListJobsResponse
type Scopes ProjectsLocationsJobsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/userinfo.email"]
requestClient ProjectsLocationsJobsList'{..}
= go _pljlProjectId _pljlLocation _pljlXgafv
_pljlUploadProtocol
_pljlAccessToken
_pljlUploadType
_pljlView
_pljlFilter
_pljlPageToken
_pljlPageSize
_pljlCallback
(Just AltJSON)
dataflowService
where go
= buildClient
(Proxy :: Proxy ProjectsLocationsJobsListResource)
mempty
|
brendanhay/gogol
|
gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Locations/Jobs/List.hs
|
mpl-2.0
| 8,354
| 0
| 23
| 1,937
| 1,151
| 671
| 480
| 163
| 1
|
{-
This file is part of Tractor.
Tractor is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Tractor 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Tractor. If not, see <http://www.gnu.org/licenses/>.
-}
{- |
Module : SBIsecCoJp.Scraper
Description : Scraping a web page
Copyright : (c) 2016 Akihiro Yamamoto
License : AGPLv3
Maintainer : https://github.com/ak1211
Stability : unstable
Portability : POSIX
スクレイピングするモジュールです。
>>> :set -XOverloadedStrings
-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TypeFamilies #-}
module SBIsecCoJp.Scraper
( MarketInfo(..)
, MarketInfoPage(..)
, TopPage(..)
, AccMenuPage(..)
, PurchaseMarginListPage(..)
, PurchaseMarginDetailPage(..)
, HoldStockDetailLink(..)
, HoldStockListPage(..)
, HoldStockDetailPage(..)
, topPage
, accMenuPage
, purchaseMarginListPage
, purchaseMarginDetailPage
, formLoginPage
, holdStockListPage
, holdStockDetailPage
, marketInfoPage
) where
import Control.Exception.Safe
import Control.Monad as M
import Control.Monad ((>=>))
import qualified Data.Char as C
import Data.Int (Int32)
import qualified Data.Maybe as Mb
import Data.Monoid (mempty, (<>))
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import qualified Data.Text.Lazy.Builder.Int as TLB
import qualified Data.Text.Lazy.Builder.RealFloat as TLB
import System.IO (Newline (..), nativeNewline)
import qualified Text.HTML.DOM as DOM
import Text.XML.Cursor (($/), ($//), (&/), (&//),
(&|))
import qualified Text.XML.Cursor as X
import qualified GenScraper as GS
import ModelDef (TickerSymbol (..))
-- |
-- マーケット情報
data MarketInfo = MarketInfo
{ miPrice :: Double -- ^ 現在値
, miMonth :: Int -- ^ 月
, miDay :: Int -- ^ 日
, miHour :: Int -- ^ 時間
, miMin :: Int -- ^ 時間
, miDifference :: Double -- ^ 前日比
, miDiffPercent :: Double -- ^ 前日比(%)
, miOpen :: Double -- ^ 始値
, miHigh :: Double -- ^ 高値
, miLow :: Double -- ^ 安値
} deriving Eq
-- |
-- マーケット情報ページの内容
data MarketInfoPage
= MInikkei225 (Maybe MarketInfo)
| MInikkei225future (Maybe MarketInfo)
| MItopix (Maybe MarketInfo)
deriving Eq
-- |
-- MarketInfoのshow
instance Show MarketInfo where
show MarketInfo{..} =
TL.unpack . TLB.toLazyText $ mempty
<> "現在値: " <> frf miPrice
<> " (" <> md <> " " <> time <> ")" <> newline
<> "前日比: " <> frf miDifference <> " " <> frf miDiffPercent <> "%" <> newline
<> "open " <> frf miOpen <> newline
<> "high " <> frf miHigh <> newline
<> "low " <> frf miLow
where
frf = TLB.formatRealFloat TLB.Fixed (Just 2)
md = TLB.decimal miMonth <> "/" <> TLB.decimal miDay
time = TLB.decimal miHour <> ":" <> TLB.decimal miMin
-- |
-- MarketInfoPageのshow
instance Show MarketInfoPage where
show mip =
let (t,v) = case mip of
(MInikkei225 info) -> ("日経平均", info)
(MInikkei225future info) -> ("日経平均先物", info)
(MItopix info) -> ("TOPIX", info)
in
TL.unpack . TLB.toLazyText $
TLB.fromText t <> newline <>
maybe "マーケット情報ありません" (TLB.fromString . show) v
<> newline
-- |
-- 改行文字
newline :: TLB.Builder
newline =
TLB.fromString $
case nativeNewline of
LF -> "\n"
CRLF -> "\r\n"
-- |
-- トップページの内容
newtype TopPage = TopPage
{ unTopPage :: [GS.AnchorTag]
} deriving (Eq, Show)
-- |
-- 口座管理ページの内容
newtype AccMenuPage = AccMenuPage
{ unAccMenuPage :: [GS.AnchorTag]
} deriving (Eq, Show)
-- |
-- 買付余力ページの内容
newtype PurchaseMarginListPage = PurchaseMarginListPage
{ unPurchaseMarginListPage :: [GS.AnchorTag]
} deriving (Eq, Show)
-- |
-- 買付余力詳細ページの内容
data PurchaseMarginDetailPage = PurchaseMarginDetailPage
{ pmdUserid :: T.Text -- ^ ユーザーID
, pmdDay :: T.Text -- ^ 受渡日
, pmdMoneyToSpare :: Int32 -- ^ 買付余力
, pmdCashBalance :: Int32 -- ^ 残高(保証金現金)
} deriving (Eq, Show)
-- |
-- 保有証券詳細ページの内容
data HoldStockDetailPage = HoldStockDetailPage
{ hsdUserid :: T.Text -- ^ ユーザーID
, hsdMDHourMin :: Maybe (Int,Int,Int,Int) -- ^ 時間(取引がない場合はNothing)
, hsdTicker :: TickerSymbol -- ^ ティッカーシンボル
, hsdCaption :: T.Text -- ^ 名前
, hsdDiff :: Maybe Double -- ^ 前日比(取引がない場合はNothing)
, hsdCount :: Int32 -- ^ 保有数
, hsdPurchasePrice :: Double -- ^ 取得単価
, hsdPrice :: Double -- ^ 現在値
} deriving (Eq, Show)
-- |
-- 保有証券詳細ページへのリンク
newtype HoldStockDetailLink = HoldStockDetailLink
{ unHoldStockDetailLink :: [GS.AnchorTag]
} deriving (Eq, Show)
-- |
-- 保有証券一覧ページの内容
data HoldStockListPage = HoldStockListPage
{ hslUserid :: T.Text -- ^ ユーザーID
, hslNthPages :: T.Text -- ^ 1~2件(2件中)等
, hslEvaluation :: Double -- ^ 評価合計
, hslProfit :: Double -- ^ 損益合計
, hslLinks :: HoldStockDetailLink -- ^ 保有証券詳細ページへのリンク
} deriving (Eq, Show)
-- |
-- ログインページをスクレイピングする関数
formLoginPage :: MonadThrow m => TL.Text -> m GS.FormTag
formLoginPage html =
let tag = X.fromDocument (DOM.parseLT html)
$// X.element "form" >=> X.attributeIs "name" "form1"
&| GS.takeFormTag
in
case concat tag of
[] -> GS.throwScrapingEx "\"form1\" form or \"action\" attribute is not present."
x:_ -> pure x
-- |
-- トップページをスクレイピングする関数
topPage :: TL.Text -> TopPage
topPage =
TopPage . GS.takeAnchorTag . X.fromDocument . DOM.parseLT
-- |
-- 口座管理ページをスクレイピングする関数
accMenuPage :: TL.Text -> AccMenuPage
accMenuPage =
AccMenuPage . GS.takeAnchorTag . X.fromDocument . DOM.parseLT
-- |
-- 買付余力ページをスクレイピングする関数
purchaseMarginListPage :: TL.Text -> PurchaseMarginListPage
purchaseMarginListPage html =
PurchaseMarginListPage (concatMap GS.takeAnchorTag table)
where
--
-- <div class="titletext">買付余力</div> 以下のtable
table :: [X.Cursor]
table =
X.fromDocument (DOM.parseLT html)
$// X.attributeIs "class" "titletext"
>=> X.followingSibling >=> X.laxElement "div"
&/ X.laxElement "table"
-- |
-- 買付余力詳細ページをスクレイピングする関数
purchaseMarginDetailPage :: TL.Text -> Maybe PurchaseMarginDetailPage
purchaseMarginDetailPage html =
pack =<< Mb.listToMaybe table
where
--
-- <div class="titletext">買付余力詳細</div> 以下のtable
table :: [X.Cursor]
table =
X.fromDocument (DOM.parseLT html)
$// X.attributeIs "class" "titletext"
>=> X.followingSibling >=> X.element "div"
&/ X.element "table" &/ X.element "tr" &/ X.element "td"
--
--
userid :: X.Cursor -> Maybe T.Text
userid cursor =
Just . T.strip =<< Mb.listToMaybe . drop 1 =<< pure (cursor $/ X.content)
--
--
pack :: X.Cursor -> Maybe PurchaseMarginDetailPage
pack cursor =
let xs = cursor
$/ X.element "table" &/ X.element "tr" &/ X.element "td"
&// X.content
in do
uid <- userid cursor
day <- Just . T.strip =<< Mb.listToMaybe . drop 1 =<< pure xs
mts <- GS.toDecimal . T.strip =<< Mb.listToMaybe . drop 3 =<< pure xs
cb <- GS.toDecimal . T.strip =<< Mb.listToMaybe . drop 24 =<< pure xs
Just PurchaseMarginDetailPage
{ pmdUserid = uid
, pmdDay = day
, pmdMoneyToSpare = mts
, pmdCashBalance = cb
}
-- |
-- 保有証券一覧ページをスクレイピングする関数
holdStockListPage :: TL.Text -> Maybe HoldStockListPage
holdStockListPage html =
pack =<< Mb.listToMaybe table
where
--
-- <div class="titletext">保有証券一覧</div> 以下のtable
table :: [X.Cursor]
table =
X.fromDocument (DOM.parseLT html)
$// X.attributeIs "class" "titletext"
>=> X.followingSibling >=> X.element "table" &/ X.element "tr" &/ X.element "td"
--
--
userid :: X.Cursor -> Maybe T.Text
userid cursor =
Just . T.strip =<< Mb.listToMaybe . drop 1 =<< pure (cursor $/ X.content)
--
--
nthPages :: X.Cursor -> Maybe T.Text
nthPages cursor =
let xs = cursor
$/ X.element "table" &/ X.element "tr"
&/ X.element "form" &/ X.element "td"
&// X.content
in
case xs of
[] -> Nothing
_ -> Just . T.concat $ map T.strip xs
--
--
summary :: X.Cursor -> Maybe (T.Text, T.Text)
summary cursor =
let xs = cursor
$/ X.element "table" &/ X.element "tr" &/ X.element "td"
&/ X.element "table" &/ X.element "tr" &/ X.element "td"
>=> X.descendant
ys = concatMap X.content xs
in do
a <- Mb.listToMaybe $ drop 1 ys
b <- Mb.listToMaybe $ drop 4 ys
Just (T.strip a, T.strip b)
--
--
links cursor =
let xs = cursor
$/ X.element "table" &/ X.element "tr" &/ X.element "td"
&/ X.element "table" &/ X.element "tr" &/ X.element "td"
ys = concatMap GS.takeAnchorTag xs
dropKehai = filter ((/=) "気配" . GS.aText)
in
HoldStockDetailLink $ dropKehai ys -- 気配リンクは不要
--
--
pack :: X.Cursor -> Maybe HoldStockListPage
pack cursor = do
uid <- userid cursor
nth <- nthPages cursor
sm <- summary cursor
ev <- GS.toDouble $ fst sm
pf <- GS.toDouble $ snd sm
Just HoldStockListPage
{ hslUserid = uid
, hslNthPages = nth
, hslEvaluation = ev
, hslProfit = pf
, hslLinks = links cursor
}
-- |
-- 保有証券詳細ページをスクレイピングする関数
holdStockDetailPage :: TL.Text -> Maybe HoldStockDetailPage
holdStockDetailPage html =
pack =<< Mb.listToMaybe table
where
--
-- <div class="titletext">保有証券詳細</div> 以下のtable
table :: [X.Cursor]
table =
X.fromDocument (DOM.parseLT html)
$// X.attributeIs "class" "titletext"
>=> X.followingSibling >=> X.element "div"
&/ X.element "table"
--
--
userid :: X.Cursor -> Maybe T.Text
userid cursor =
let
xs = filter (/= T.empty) . map T.strip $
cursor
$/ X.element "tr" &/ X.element "td"
&// X.content
in
Mb.listToMaybe xs
--
--
tickerCaption :: X.Cursor -> Maybe (TickerSymbol, T.Text)
tickerCaption cursor =
let xs = cursor
$/ X.element "tr" &/ X.element "td"
&/ X.element "table" &/ X.element "tr" &/ X.element "td"
&/ X.content
in
case xs of
[] -> Nothing
_ ->
let
spaceSeparated = T.concat $ map T.strip xs
(t,c) = T.break C.isSpace spaceSeparated
in do
code <- GS.toDecimal t
Just (TSTYO code, T.strip c)
--
-- (現在値, 時間)
priceMDHourMin :: X.Cursor -> Maybe (Double, Maybe (Int,Int,Int,Int))
priceMDHourMin cursor =
let
xs = filter (/= T.empty) . map T.strip $
cursor
$/ X.element "tr" &/ X.element "td"
&// X.content
in do
-- 現在値
pr <- GS.toDouble =<< Mb.listToMaybe . drop 4 =<< pure xs
-- 時間
chunk <- T.init . T.tail . T.dropWhile (/= '(')
<$> (Mb.listToMaybe . drop 5 $ xs)
case M.mapM GS.toDecimal . T.split (`elem` ['/',' ',':']) . T.strip $ chunk of
Just [month,day,hour,minute] -> Just (pr, Just (month,day,hour,minute))
_ -> Just (pr, Nothing)
--
--
diffCountGain :: X.Cursor -> Maybe (Maybe Double, Int32, Double)
diffCountGain cursor =
let
xs = cursor
$/ X.element "tr" &/ X.element "td"
&/ X.element "table" &/ X.element "tr" &/ X.element "td"
ys = filter (/= T.empty)
. map T.strip
. concatMap ($// X.content)
. take 1 $ drop 2 xs
in do
-- "-" は現在取引無し
d <- \case{"-"->Nothing; x->GS.toDouble x} <$> (Mb.listToMaybe . drop 1 $ ys)
c <- GS.toDecimal =<< Mb.listToMaybe . drop 3 =<< pure ys
g <- GS.toDouble =<< Mb.listToMaybe . drop 5 =<< pure ys
Just (d, c, g)
--
--
pack :: X.Cursor -> Maybe HoldStockDetailPage
pack cursor = do
uid <- userid cursor
(ts,ca) <- tickerCaption cursor
(pr,at) <- priceMDHourMin cursor
(d,c,g) <- diffCountGain cursor
Just HoldStockDetailPage
{ hsdUserid = uid
, hsdMDHourMin = at
, hsdTicker = ts
, hsdCaption = ca
, hsdDiff = d
, hsdCount = c
, hsdPurchasePrice = pr - g / realToFrac c
, hsdPrice = pr
}
-- |
-- マーケット情報ページをスクレイピングする関数
marketInfoPage :: TL.Text -> Maybe MarketInfoPage
marketInfoPage html =
let table = [("国内指標", MInikkei225)
,("日経平均", MInikkei225)
,("日経平均先物", MInikkei225future)
,("TOPIX", MItopix)
]
in do
cap <- caption
fn <- lookup cap table
Just $ fn marketInfo
where
--
--
marketInfo :: Maybe MarketInfo
marketInfo = do
(pr,month,day,hour,minute,df,dp) <- priceMonthDayHourMinDiffPercent =<< Mb.listToMaybe . drop 1 =<< pure tables
(o,h,l) <- openHighLow =<< Mb.listToMaybe . drop 2 =<< pure tables
Just MarketInfo
{ miPrice = pr
, miMonth = month
, miDay = day
, miHour = hour
, miMin = minute
, miDifference = df
, miDiffPercent = dp
, miOpen = o
, miHigh = h
, miLow = l
}
--
--
root = X.fromDocument (DOM.parseLT html)
--
-- <div class="titletext"></div> 以下の
-- <table><tr><td><form><table>
tables :: [X.Cursor]
tables =
X.fromDocument (DOM.parseLT html)
$// X.attributeIs "class" "titletext"
>=> X.followingSibling >=> X.element "table" &/ X.element "tr" &/ X.element "td"
&/ X.element "form" &/ X.element "table"
--
--
caption :: Maybe T.Text
caption =
Mb.listToMaybe $
root $// X.attributeIs "class" "titletext" &// X.content
--
--
priceMonthDayHourMinDiffPercent :: X.Cursor -> Maybe (Double, Int, Int, Int, Int, Double, Double)
priceMonthDayHourMinDiffPercent cursor = do
let tds = map T.strip $
cursor
$/ X.element "tr" &/ X.element "td" &// X.content
-- 現在値
pr <- GS.toDouble =<< Mb.listToMaybe . drop 1 =<< pure tds
-- 時間
chunk <- T.init . T.tail . T.strip <$> (Mb.listToMaybe . drop 2 $ tds)
parts <- M.mapM GS.toDecimal . T.split (`elem` ['/',' ',':']) . T.strip $ chunk
M.guard (length parts == 4)
let [month, day, hour, minute] = parts
-- 前日比
df <- GS.toDouble =<< Mb.listToMaybe . drop 4 =<< pure tds
-- 前日比(%)
dp <- GS.toDouble =<< Mb.listToMaybe . drop 6 =<< pure tds
Just (pr, month, day, hour, minute, df, dp)
--
--
openHighLow :: X.Cursor -> Maybe (Double, Double, Double)
openHighLow cursor = do
let tds = map T.strip $
cursor
$/ X.element "tr" &/ X.element "td" &// X.content
-- 始値
open <- GS.toDouble =<< Mb.listToMaybe . drop 1 =<< pure tds
-- 高値
high <- GS.toDouble =<< Mb.listToMaybe . drop 3 =<< pure tds
-- 安値
low <- GS.toDouble =<< Mb.listToMaybe . drop 5 =<< pure tds
Just (open, high, low)
|
ak1211/tractor
|
src/SBIsecCoJp/Scraper.hs
|
agpl-3.0
| 18,403
| 0
| 30
| 6,002
| 4,562
| 2,445
| 2,117
| 361
| 4
|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
-- {-# LANGUAGE Impredicative #-}
import Control.Monad.State
myID :: forall a . a -> a
myID = id
pairwiseAutomorphism :: forall a b . (forall c . c -> c) -> (a, b) -> (a, b)
pairwiseAutomorphism f (a, b) = (f a, f b)
pairwiseTerminalMorphism :: forall a b d . (forall c . c -> d) -> (a, b) -> (d, d)
pairwiseTerminalMorphism f (a, b) = (f a, f b)
pairwiseFunctor :: forall a b f . (forall c . c ->f c) -> (a, b) -> (f a, f b)
pairwiseFunctor f (a, b) = (f a, f b)
{-
type Nat a b = forall c . a c -> b c
listToMaybe :: Nat [] Maybe
listToMaybe [] = Nothing
listToMaybe (a:as) = Just a
maybeToList :: Nat Maybe []
maybeToList Nothing = []
maybeToList (Just a) = [a]
newtype Predicate = (a -> Bool)
double = \x->x*2
-}
newtype ShowBox = SB (forall b . (forall a . (Show a) => a -> b) -> b)
makeShowBox :: (Show a) => a -> ShowBox
makeShowBox showable = SB (\f -> f showable)
applyShowBox :: ShowBox -> (forall a . (Show a) => a -> b) -> b
applyShowBox (SB showbox) f = showbox f
instance Show ShowBox where
show sb = applyShowBox sb show
newtype PureShowBox = PSB (forall b . (forall a . (a, a -> String) -> b) -> b)
makePureShowBoxFromShowable :: (Show a) => a -> PureShowBox
makePureShowBoxFromShowable showable = PSB (\f -> f (showable, show))
applyPureShowBox :: PureShowBox -> (forall a . (a, a -> String) -> b) -> b
applyPureShowBox (PSB showbox) f = showbox f
instance Show PureShowBox where
show psb = applyPureShowBox psb (\(a, showfunc) -> showfunc a)
data SQueue = SQ (forall t r . (forall a . (Queue a) => a t -> r) -> r)
newSQueueList :: SQueue
newSQueueList = SQ (\f -> f [])
newSQueueTS :: SQueue
newSQueueTS = SQ (\f -> f (empty :: TwoStacks t))
runOnSQ :: SQueue -> (forall a . (Queue a) => a t -> r) -> r
runOnSQ (SQ cont) f = cont f
church :: Int -> (a -> a) -> a -> a
church 0 _ x = x
church n f x = f (church (n-1) f x)
-- f:: forall a . (Queue a) => a -> t
-- empty :: (Queue a) => a
-- f empty :: t
class (Queue a) where
enqueue :: a t -> t -> a t
dequeue :: a t -> (t, a t)
empty :: a t
len :: a t -> Int
instance Queue [] where
enqueue l t = l ++ [t]
dequeue l = (head l, tail l)
empty = []
len = Prelude.length
data TwoStacks t = TS [t] [t]
instance Queue TwoStacks where
enqueue (TS a b) t = TS b (t:a)
dequeue (TS [] b) = let newa = reverse b in (head newa, TS (tail newa) [])
dequeue (TS a b) = (head a, TS (tail a) b)
empty = TS [] []
len (TS a b) = Prelude.length a + Prelude.length b
--Object is defined as a type with
-- a) underlying representation
-- tuple of data
-- b) instance methods
-- way to create the type of all instance methods given the underlying representation
newtype Object instancemethods = Object (forall result . ((forall underlyingrep . (underlyingrep, instancemethods underlyingrep) -> result) -> result))
objLift :: forall instancemethods result . (forall underlyingrep . (underlyingrep, instancemethods underlyingrep) -> result) -> (Object instancemethods) -> result
objLift f (Object o) = o f
makeConstructorFromInstanceMethods :: instancemethods a -> a -> Object instancemethods
makeConstructorFromInstanceMethods instancemethods = \a -> Object (\f -> f (a, instancemethods))
newtype PrintableInstanceMethods a = PIM (a -> String)
newtype Printable = Printable (Object PrintableInstanceMethods)
makePrintableFromShowable :: (Show a) => a -> Printable
makePrintableFromShowable a = Printable $ makeConstructorFromInstanceMethods (PIM show) a
instance Show Printable where
show (Printable obj) = objLift (\(rep, PIM toShow) -> toShow rep) obj
{- Equivalent Java code
interface Printable {
String toString();
}
class FromShowable : Printable {
Object underlyingRep; //Using Object here because Java object implements toString, like Show
FromShowable(Object o) {
underlyingRep = o;
}
String toString() {
return underlyingRep.toString();
}
}
-}
|
Crazycolorz5/Haskell-Code
|
rankntypes.hs
|
unlicense
| 4,105
| 1
| 14
| 923
| 1,448
| 778
| 670
| 64
| 1
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module PPrelude
( Word4, word4to8, packWord8, fstWord4, sndWord4, word4toInt, unpackWord4s
, ByteString, Word8, Map
, DB, insertDB, lookupDB, runDB
, encodeInt, decodeInt
, module X
)
where
import Control.Applicative as X
import Control.Monad.Free
import Data.Bits
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Char (intToDigit)
import Data.Functor as X
import Data.Map (Map)
import Data.Maybe as X
import Data.Monoid as X
import Data.Word (Word8)
encodeInt :: Integral n => n -> ByteString
encodeInt = BS.reverse <$> BS.unfoldr nextByte
where
nextByte 0 = Nothing
nextByte n = Just (fromIntegral n, n `quot` 256)
decodeInt :: Integral n => ByteString -> Maybe n
decodeInt bs
| not (BS.null bs) && BS.head bs == 0 = Nothing
| otherwise = Just $ BS.foldl addByte 0 bs
where
addByte n b = (n * 256) + fromIntegral b
newtype Word4 = Word4 { word4to8 :: Word8 }
deriving (Eq)
instance Show Word4 where
show = (:[]) . intToDigit . word4toInt
packWord8 :: Word4 -> Word4 -> Word8
packWord8 (Word4 a) (Word4 b) = (a `shift` 4) .|. b
fstWord4, sndWord4 :: Word8 -> Word4
fstWord4 b = Word4 $ b `shiftR` 4
sndWord4 b = Word4 $ b .&. 0x0f
word4toInt :: Word4 -> Int
word4toInt = fromIntegral . word4to8
unpackWord4s :: ByteString -> [Word4]
unpackWord4s bs = BS.unpack bs >>= unpackByte
where unpackByte b = [fstWord4 b, sndWord4 b]
data KV k v a
= Put k v a
| Get k (v -> a)
deriving (Functor)
newtype DB k v a = DB (Free (KV k v) a)
deriving (Functor, Applicative, Monad)
insertDB :: k -> v -> DB k v ()
insertDB k v = DB $ liftF $ Put k v ()
lookupDB :: k -> DB k v v
lookupDB k = DB $ liftF $ Get k id
-- Collapses a series of puts and gets down to the monad of your choice
runDB :: Monad m
=> (k -> v -> m ()) -- ^ The 'put' function for our desired monad
-> (k -> m v) -- ^ The 'get' function for the same monad
-> DB k v a -- ^ The puts and gets to execute
-> m a
runDB put get (DB ops) = go ops
where
go (Pure a) = return a
go (Free (Put k v next)) = put k v >> go next
go (Free (Get k handler)) = get k >>= go . handler
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/playpen/blockchain/ben-kirwin-merkle/src/PPrelude.hs
|
unlicense
| 2,439
| 0
| 13
| 717
| 867
| 470
| 397
| 61
| 3
|
-- |Assorted REPL (read-eval-print-loop) functionality for console UIs.
module Console.REPL (
repl',
repl,
askFor,
askForBy',
askForBy,
putPrompt) where
import Control.Monad
import System.IO
import Text.Read
-- |Executes a REP loop until a given condition is met.
-- Variant of @repl'@ which performs the same input and output action
-- over and over again.
repl' :: Monad m => (a -> Bool) -> m a -> (a -> m b) -> m ()
repl' check f g = repl check (repeat f) (repeat g)
-- |Executes a REP loop until a given condition is met.
repl :: Monad m
=> (a -> Bool) -- |The check which, when true, terminates the loop.
-> [m a] -- |The list of inputs.
-> [a -> m b] -- |The list of functions operating on the input.
-> m ()
repl check i o = sequenceWhile check $ zip i o
where sequenceWhile _ [] = return ()
sequenceWhile f ((inp,out):xs) =
do inp' <- inp
unless (f inp') $ do out inp'
sequenceWhile f xs
-- |Asks for a value of a given type.
-- The prompt is printed and the user is asked to enter
-- a line. If the input cannot be parsed, the error text
-- is printed and the process repeats.
askFor :: Read a => String -> String -> IO a
askFor prompt err = askForBy' prompt err (const (return True))
-- |Variant of @askFor@, with an additional predicate which the
-- input must satisify.
askForBy' :: Read a => String -> String -> (a -> IO Bool) -> IO a
askForBy' prompt err check = do
x <- putPrompt prompt
case readMaybe x of
Just x' -> do isValid <- check x'
if isValid then return x'
else putStrLn err >> askForBy' prompt err check
Nothing -> putStrLn err >> askForBy' prompt err check
-- |Variant of @askFor@, with an additional predicate which the
-- input must satisify.
askForBy :: String -> String -> (String -> IO Bool) -> IO String
askForBy prompt err check = do
x <- putPrompt prompt
isValid <- check x
if isValid then return x
else putStrLn err >> askForBy prompt err check
-- |Puts a prompt onto the console without starting a new line.
putPrompt :: String -> IO String
putPrompt prompt = putStr prompt >> hFlush stdout >> getLine
|
ombocomp/Renaming
|
Console/REPL.hs
|
apache-2.0
| 2,233
| 0
| 14
| 582
| 605
| 301
| 304
| 41
| 3
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Conduit
import Data.Hashable
import Control.Exception
import Control.Lens
import Control.Monad
import Data.Aeson
import qualified Data.Aeson as A
import Data.Aeson.Lens
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.Csv
import qualified Data.Csv as Csv
import Data.Csv.Conduit
import Data.Foldable
import qualified Data.HashMap.Strict as M
import qualified Data.List as L
import Data.Maybe
import Data.Ord
import Data.Semigroup
import qualified Data.Text as T
import Data.Text.Format
import qualified Data.Text.Format as F
import Data.Text.Lazy (toStrict)
import Data
import Opts
import Parsing
import Utils hiding (info)
main :: IO ()
main = parseOpts >>= yorkScripts
yorkScripts :: Options -> IO ()
yorkScripts BillId =
runResourceT $ stdinC
$= fromCsvLiftError liftError defaultDecodeOptions NoHeader
$= mapC line
$$ toCsv defaultEncodeOptions
=$ stdoutC
yorkScripts RollCall{..} =
BL.writeFile outputFile
. Csv.encodeDefaultOrderedByName
. map (summarizeCall . getMax)
. M.elems
. getLastRollCall
. indexByBill
. filterCategories
=<< readDecodeDir verbose inputDir
yorkScripts CallData{..} =
mapM_ (F.print "{} {}\n" . bimap (F.left 20 ' ') (F.right 5 ' '))
. L.sortBy (comparing (Down . snd))
. M.toList
. frequencies
. mapMaybe (join . fmap category . A.decode . BL.fromStrict)
=<< mapM B.readFile
=<< walk inputDir
-- key id
-- bill id
-- >>> bill id 2 <<<
-- cong
-- bill type
-- bill no
-- name full
-- description
-- intr date
-- intr month
-- year
-- major topic
-- sub topic code
-- cap major topic
-- cap sub topic
-- plaw
-- plaw date
-- plaw no
-- pass h
-- pass s
-- majority
-- party
-- chamber
-- commem
-- congress
line :: [T.Text] -> [T.Text]
line ("KeyID":"BillID":hdr) = "KeyID" : "BillID" : "BillID2" : hdr
line (keyId:billId:row) = keyId : billId : field billId : row
line row = row
field :: T.Text -> T.Text
field = toStrict . format "{}{} ({})" . parseBillId . T.split (== '-')
parseBillId :: [T.Text] -> (T.Text, T.Text, T.Text)
parseBillId (session:house:bill:_) = (T.take 1 house, bill, session)
parseBillId _ = ("ERROR", "", "")
liftError :: CsvParseError -> IOException
liftError (CsvParseError _ _) = undefined
liftError (IncrementalError _) = undefined
category :: Value -> Maybe T.Text
category = preview (key "category" . _String)
frequencies :: (Hashable k, Eq k, Traversable t) => t k -> M.HashMap k Int
frequencies = foldl' step M.empty
where
step m k = M.insertWith (+) k 1 m
|
erochest/york-scripts
|
src/Main.hs
|
apache-2.0
| 3,080
| 0
| 17
| 918
| 836
| 468
| 368
| 73
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Codec.Sarsi.Spec where
import Data.Attoparsec.Text (Parser)
import Data.Attoparsec.Text.Machine (streamParser)
import Data.Machine (ProcessT, runT, source, (<~))
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as TextIO
import Sarsi.Tools.Trace (appendLF)
parseFile :: Parser a -> FilePath -> IO [Either String a]
parseFile parser = parsingFile $ streamParser parser <~ appendLF
parsingFile :: ProcessT IO Text (Either String a) -> FilePath -> IO [Either String a]
parsingFile p fp = do
txts <- Text.lines <$> TextIO.readFile fp
parsingText p txts
parseText :: Parser a -> [Text] -> IO [Either String a]
parseText parser = parsingText $ streamParser parser <~ appendLF
parsingText :: ProcessT IO Text (Either String a) -> [Text] -> IO [Either String a]
parsingText p txts =
runT $ p <~ source txts
|
aloiscochard/sarsi
|
tests/Codec/Sarsi/Spec.hs
|
apache-2.0
| 893
| 0
| 10
| 141
| 323
| 173
| 150
| 20
| 1
|
{- GPC lexer -}
{-# LANGUAGE NoMonomorphismRestriction #-}
module GPC.Lexer
( ident
, reserved
, reservedOp
, parens
, int
, ch
, str
, float
, bool
, semi
, whiteSpace
, braces
, typeT
, commaSep
, parseCh
, brackets
) where
import Control.Applicative hiding (empty, many,optional, (<|>))
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Language
import qualified Text.ParserCombinators.Parsec.Token as Token
reservedTypes = ["int", "double", "bool","void"] :: [String]
otherReserved = ["if", "else", "true", "false", "seq", "par","return", "for"] :: [String]
-- Define the tokens used in our language
languageDef = emptyDef {
Token.commentStart = "/*"
, Token.commentEnd = "*/"
, Token.commentLine = "//"
, Token.nestedComments = True
, Token.identStart = letter
, Token.identLetter = alphaNum <|> oneOf "'_"
, Token.reservedNames = otherReserved ++ reservedTypes
, Token.caseSensitive = True
}
lexer = Token.makeTokenParser languageDef
-- Setup parsers for language
ident = Token.identifier lexer
reserved = Token.reserved lexer
reservedOp = Token.reservedOp lexer
parens = Token.parens lexer
semi = Token.semi lexer
whiteSpace = Token.whiteSpace lexer
--comma = Token.comma lexer
braces = Token.braces lexer
commaSep = Token.commaSep lexer
--semiSep = Token.semiSep lexer
brackets = Token.brackets lexer
-- Parse specific character
parseCh c = reserved [c]
-- Parse specific string
parseStr = reserved
-- Setup parsers for literal values
ch = Token.charLiteral lexer
int = Token.hexadecimal lexer <|> Token.octal lexer <|> Token.integer lexer
float = Token.float lexer
str = Token.stringLiteral lexer
bool = parseStr "true" *> pure True
<|> parseStr "false" *> pure False
-- |When we need to use built in types
typeT = Token.identifier typeLexer
where typeLexer = Token.makeTokenParser languageDef
{Token.reservedNames = otherReserved}
|
RossMeikleham/GPC
|
src/GPC/Lexer.hs
|
bsd-2-clause
| 2,059
| 0
| 9
| 451
| 489
| 284
| 205
| 54
| 1
|
{-# LANGUAGE CPP, NamedFieldPuns, RecordWildCards #-}
-- | cabal-install CLI command: freeze
--
module Distribution.Client.CmdFreeze (
freezeCommand,
freezeAction,
) where
import Distribution.Client.ProjectOrchestration
import Distribution.Client.ProjectPlanning
import Distribution.Client.ProjectConfig
( ProjectConfig(..), ProjectConfigShared(..)
, writeProjectLocalFreezeConfig )
import Distribution.Client.Targets
( UserQualifier(..), UserConstraintScope(..), UserConstraint(..) )
import Distribution.Solver.Types.PackageConstraint
( PackageProperty(..) )
import Distribution.Solver.Types.ConstraintSource
( ConstraintSource(..) )
import Distribution.Client.DistDirLayout
( DistDirLayout(distProjectFile) )
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Package
( PackageName, packageName, packageVersion )
import Distribution.Version
( VersionRange, thisVersion
, unionVersionRanges, simplifyVersionRange )
import Distribution.PackageDescription
( FlagAssignment )
import Distribution.Client.Setup
( GlobalFlags, ConfigFlags(..), ConfigExFlags, InstallFlags )
import Distribution.Simple.Setup
( HaddockFlags, fromFlagOrDefault )
import Distribution.Simple.Utils
( die', notice, wrapText )
import Distribution.Verbosity
( normal )
import Data.Monoid as Monoid
import qualified Data.Map as Map
import Data.Map (Map)
import Control.Monad (unless)
import Distribution.Simple.Command
( CommandUI(..), usageAlternatives )
import qualified Distribution.Client.Setup as Client
freezeCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
freezeCommand = Client.installCommand {
commandName = "new-freeze",
commandSynopsis = "Freeze dependencies.",
commandUsage = usageAlternatives "new-freeze" [ "[FLAGS]" ],
commandDescription = Just $ \_ -> wrapText $
"The project configuration is frozen so that it will be reproducible "
++ "in future.\n\n"
++ "The precise dependency configuration for the project is written to "
++ "the 'cabal.project.freeze' file (or '$project_file.freeze' if "
++ "'--project-file' is specified). This file extends the configuration "
++ "from the 'cabal.project' file and thus is used as the project "
++ "configuration for all other commands (such as 'new-build', "
++ "'new-repl' etc).\n\n"
++ "The freeze file can be kept in source control. To make small "
++ "adjustments it may be edited manually, or to make bigger changes "
++ "you may wish to delete the file and re-freeze. For more control, "
++ "one approach is to try variations using 'new-build --dry-run' with "
++ "solver flags such as '--constraint=\"pkg < 1.2\"' and once you have "
++ "a satisfactory solution to freeze it using the 'new-freeze' command "
++ "with the same set of flags.",
commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " new-freeze\n"
++ " Freeze the configuration of the current project\n\n"
++ " " ++ pname ++ " new-build --dry-run --constraint=\"aeson < 1\"\n"
++ " Check what a solution with the given constraints would look like\n"
++ " " ++ pname ++ " new-freeze --constraint=\"aeson < 1\"\n"
++ " Freeze a solution using the given constraints\n\n"
++ "Note: this command is part of the new project-based system (aka "
++ "nix-style\nlocal builds). These features are currently in beta. "
++ "Please see\n"
++ "http://cabal.readthedocs.io/en/latest/nix-local-build-overview.html "
++ "for\ndetails and advice on what you can expect to work. If you "
++ "encounter problems\nplease file issues at "
++ "https://github.com/haskell/cabal/issues and if you\nhave any time "
++ "to get involved and help with testing, fixing bugs etc then\nthat "
++ "is very much appreciated.\n"
}
-- | To a first approximation, the @freeze@ command runs the first phase of
-- the @build@ command where we bring the install plan up to date, and then
-- based on the install plan we write out a @cabal.project.freeze@ config file.
--
-- For more details on how this works, see the module
-- "Distribution.Client.ProjectOrchestration"
--
freezeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
freezeAction (configFlags, configExFlags, installFlags, haddockFlags)
extraArgs globalFlags = do
unless (null extraArgs) $
die' verbosity $ "'freeze' doesn't take any extra arguments: "
++ unwords extraArgs
ProjectBaseContext {
distDirLayout,
cabalDirLayout,
projectConfig,
localPackages
} <- establishProjectBaseContext verbosity cliConfig
(_, elaboratedPlan, _) <-
rebuildInstallPlan verbosity
distDirLayout cabalDirLayout
projectConfig
localPackages
let freezeConfig = projectFreezeConfig elaboratedPlan
writeProjectLocalFreezeConfig distDirLayout freezeConfig
notice verbosity $
"Wrote freeze file: " ++ distProjectFile distDirLayout "freeze"
where
verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
cliConfig = commandLineFlagsToProjectConfig
globalFlags configFlags configExFlags
installFlags haddockFlags
-- | Given the install plan, produce a config value with constraints that
-- freezes the versions of packages used in the plan.
--
projectFreezeConfig :: ElaboratedInstallPlan -> ProjectConfig
projectFreezeConfig elaboratedPlan =
Monoid.mempty {
projectConfigShared = Monoid.mempty {
projectConfigConstraints =
concat (Map.elems (projectFreezeConstraints elaboratedPlan))
}
}
-- | Given the install plan, produce solver constraints that will ensure the
-- solver picks the same solution again in future in different environments.
--
projectFreezeConstraints :: ElaboratedInstallPlan
-> Map PackageName [(UserConstraint, ConstraintSource)]
projectFreezeConstraints plan =
--
-- TODO: [required eventually] this is currently an underapproximation
-- since the constraints language is not expressive enough to specify the
-- precise solution. See https://github.com/haskell/cabal/issues/3502.
--
-- For the moment we deal with multiple versions in the solution by using
-- constraints that allow either version. Also, we do not include any
-- /version/ constraints for packages that are local to the project (e.g.
-- if the solution has two instances of Cabal, one from the local project
-- and one pulled in as a setup deps then we exclude all constraints on
-- Cabal, not just the constraint for the local instance since any
-- constraint would apply to both instances). We do however keep flag
-- constraints of local packages.
--
deleteLocalPackagesVersionConstraints
(Map.unionWith (++) versionConstraints flagConstraints)
where
versionConstraints :: Map PackageName [(UserConstraint, ConstraintSource)]
versionConstraints =
Map.mapWithKey
(\p v -> [(UserConstraint (UserQualified UserQualToplevel p) (PackagePropertyVersion v),
ConstraintSourceFreeze)])
versionRanges
versionRanges :: Map PackageName VersionRange
versionRanges =
Map.map simplifyVersionRange $
Map.fromListWith unionVersionRanges $
[ (packageName pkg, thisVersion (packageVersion pkg))
| InstallPlan.PreExisting pkg <- InstallPlan.toList plan
]
++ [ (packageName pkg, thisVersion (packageVersion pkg))
| InstallPlan.Configured pkg <- InstallPlan.toList plan
]
flagConstraints :: Map PackageName [(UserConstraint, ConstraintSource)]
flagConstraints =
Map.mapWithKey
(\p f -> [(UserConstraint (UserQualified UserQualToplevel p) (PackagePropertyFlags f),
ConstraintSourceFreeze)])
flagAssignments
flagAssignments :: Map PackageName FlagAssignment
flagAssignments =
Map.fromList
[ (pkgname, flags)
| InstallPlan.Configured elab <- InstallPlan.toList plan
, let flags = elabFlagAssignment elab
pkgname = packageName elab
, not (null flags) ]
-- As described above, remove the version constraints on local packages,
-- but leave any flag constraints.
deleteLocalPackagesVersionConstraints
:: Map PackageName [(UserConstraint, ConstraintSource)]
-> Map PackageName [(UserConstraint, ConstraintSource)]
deleteLocalPackagesVersionConstraints =
#if MIN_VERSION_containers(0,5,0)
Map.mergeWithKey
(\_pkgname () constraints ->
case filter (not . isVersionConstraint . fst) constraints of
[] -> Nothing
constraints' -> Just constraints')
(const Map.empty) id
localPackages
#else
Map.mapMaybeWithKey
(\pkgname constraints ->
if pkgname `Map.member` localPackages
then case filter (not . isVersionConstraint . fst) constraints of
[] -> Nothing
constraints' -> Just constraints'
else Just constraints)
#endif
isVersionConstraint (UserConstraint _ (PackagePropertyVersion _)) = True
isVersionConstraint _ = False
localPackages :: Map PackageName ()
localPackages =
Map.fromList
[ (packageName elab, ())
| InstallPlan.Configured elab <- InstallPlan.toList plan
, elabLocalToProject elab
]
|
mydaum/cabal
|
cabal-install/Distribution/Client/CmdFreeze.hs
|
bsd-3-clause
| 9,877
| 0
| 29
| 2,356
| 1,433
| 806
| 627
| 162
| 4
|
module Problem265 where
import Data.Array
n :: Int
n = 5
type Seq = [Int]
type State = (Seq, Array Int Bool)
main :: IO ()
main =
print
$ sum
$ map (sum . (zipWith (*) (iterate (* 2) 1) . drop (n - 1)) . fst)
$ (!! (2 ^ n - 1))
$ iterate
(concatMap go)
[ ( [0, 0, 0]
, array (0, 2 ^ n - 1) ((0, True) : [ (x, False) | x <- [1 .. 2 ^ n - 1] ])
)
]
go :: State -> [State]
go (s, arr) =
map (\x' -> (x', arr // [(getVal x', True)]))
$ filter (\x' -> not $ arr ! getVal x')
$ map (: s) [0, 1]
getVal :: Seq -> Int
getVal xs = sum $ zipWith (*) (take n xs) (iterate (* 2) 1)
|
adityagupta1089/Project-Euler-Haskell
|
src/problems/Problem265.hs
|
bsd-3-clause
| 696
| 0
| 17
| 270
| 387
| 218
| 169
| -1
| -1
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
module Cayley where
import Data.Profunctor
import Data.Functor.Contravariant
import Control.Category
import Prelude hiding (id, (.))
newtype Cayley a b = Cayley (forall x. (x -> a) -> x -> b)
instance Category Cayley where
id = Cayley id
Cayley f . Cayley g = Cayley $ f . g
instance Functor (Cayley a) where
fmap f (Cayley g) = Cayley $ (fmap . fmap) f g
instance Profunctor Cayley where
dimap f g c = liftCayley g . c . liftCayley f
liftCayley :: (a -> b) -> Cayley a b
liftCayley f = Cayley (f .)
lowerCayley :: Cayley a b -> (a -> b)
lowerCayley (Cayley f) = f id
toCayley :: x -> Cayley () x
toCayley x = liftCayley $ const x
fromCayley :: Cayley () a -> a
fromCayley c = lowerCayley c ()
|
isovector/category-theory
|
Cayley.hs
|
bsd-3-clause
| 837
| 0
| 10
| 184
| 328
| 173
| 155
| 25
| 1
|
{-# LANGUAGE FlexibleInstances
, BangPatterns
, MagicHash
, ScopedTypeVariables
, TypeFamilies
, UndecidableInstances
, OverlappingInstances
, DeriveDataTypeable
, MultiParamTypeClasses
, NamedFieldPuns
#-}
-- State monad transformer is needed for both step & graph:
#ifndef MODNAME
#define MODNAME Intel.Cnc7
#endif
#define CNC_SCHEDULER 7
#define STEPLIFT S.lift$
#define GRAPHLIFT S.lift$
#define SUPPRESS_runGraph
#define DEFINED_free_items
#include "Cnc.Header.hs"
------------------------------------------------------------
-- Version 7: Now with healing -- bring back worker threads that died
-- prematurely. Specifically, in this version we use a global work
-- queue but we heal workers when we put into an empty queue.
#define SUPPRESS_HiddenState5
#include "shared_5_6.hs"
-- We extend the type with the "deadset" field:
data HiddenState5 =
HiddenState5 { stack :: HotVar [StepCode ()],
numworkers :: HotVar Int,
makeworker :: Int -> IO (),
mortal :: HotVar (Set.Set ThreadId),
myid :: Int,
deadset :: HotVar [Int]
}
deriving Show
defaultState =
do hv <- newHotVar []
hv2 <- newHotVar 0
hv3 <- newHotVar Set.empty
hv4 <- newHotVar []
let msg = "Intel.Cnc"++ show CNC_SCHEDULER ++" internal error: makeworker thunk used before initalized"
return$ HiddenState5 { stack = hv, numworkers = hv2, makeworker= error msg,
mortal = hv3, myid = -1,
deadset = hv4 }
-- A push that also wakes the dead.
stepcode_push :: HotVar [a] -> a -> StepCode ()
stepcode_push stack val =
-- If push onto an empty stack, wake up deadset.
do old <- STEPLIFT modifyHotVar stack (\ls -> (val:ls, ls))
if null old
-- Wake up the dead:
then do (HiddenState5 { numworkers, makeworker, deadset }) <- S.get
dead <- STEPLIFT modifyHotVar deadset (\old -> ([], old))
let len = length dead
--STEPLIFT putStrLn$ " ********** Waking the dead: " ++ show dead
if len > 0
then do STEPLIFT modifyHotVar_ numworkers (+ len)
STEPLIFT forM_ dead (forkIO . makeworker)
else return ()
else return ()
putt = proto_putt
(\ steps tag ->
do (HiddenState5 { stack }) <- S.get
foldM (\ () step -> stepcode_push stack (step tag))
() steps)
-- New, more dynamic API:
forkStep s =
do (HiddenState5 { stack }) <- S.get
stepcode_push stack s
get col tag = ver5_6_core_get (return ()) col tag
-- At finalize time we set up the workers and run them.
finalize userFinalAction =
do (HiddenState5 { stack, deadset }) <- S.get
joiner <- GRAPHLIFT newChan
let worker id =
do x <- STEPLIFT tryPop stack
case x of
Nothing -> STEPLIFT writeChan joiner id
Just action -> do action
worker id
let joinerHook id = modifyHotVar_ deadset (id:)
ver5_6_core_finalize joiner userFinalAction worker True numCapabilities joinerHook
------------------------------------------------------------
quiescence_support = True
|
rrnewton/Haskell-CnC
|
Intel/Cnc7.hs
|
bsd-3-clause
| 3,099
| 57
| 15
| 771
| 715
| 377
| 338
| 60
| 3
|
{-# LANGUAGE RankNTypes #-}
-- | Creation of clatch-like types.
module Penny.Clatch.Create where
import Penny.Balance
import Penny.Clatch.Types
import Penny.Clatch.Access.Converted
import Penny.Converter
import Penny.Core
import Penny.Ents (Balanced, balancedToSeqEnt)
import Penny.SeqUtil
import Penny.Serial
import Penny.Tranche (Postline, TopLine)
import Penny.Transaction (Transaction(Transaction))
import Penny.Troika
import Control.Lens hiding (index)
import Control.Monad (join)
import Data.Bifunctor
import Data.Bifunctor.Flip
import Data.Monoid
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Traversable as T
import Data.Functor.Compose
createViewposts :: TransactionX l -> Seq (Sliced l ())
createViewposts txn = fmap (\vw -> (txn, (vw, ())))
(allSlices . snd . snd $ txn)
-- | Applies a 'Converter' to convert a posting.
createConverted
:: Converter
-> Sliced l a
-> Converted l ()
createConverted (Converter f) clatch = set (_2._2) (conv, ()) clatch
where
conv = f $ view amount clatch
amount = _2._1.onSlice. Penny.Core.core. Penny.Core.troika . to c'Amount'Troika
createPrefilt
:: (Converted l a -> Bool)
-- ^ Predicate
-> Seq (Converted l a)
-> Seq (Prefilt l ())
createPrefilt pd
= fmap arrange
. serialNumbers
. Seq.filter pd
where
arrange ((t, (v, (a, _))), s) = (t, (v, (a, (s, ()))))
createSortset
:: (Prefilt l a -> Prefilt l a -> Ordering)
-- ^ Sorter
-> Seq (Prefilt l a)
-> Seq (Sorted l ())
createSortset pd
= fmap arrange
. serialNumbers
. Seq.sortBy pd
where
arrange ((t, (v, (a, (e, _)))), s) = (t, (v, (a, (e, (s, ())))))
addTotals
:: forall l a. Seq (Sorted l a)
-> Seq (Totaled l ())
addTotals = snd . T.mapAccumL f mempty
where
f bal clatch@(txn, (vw, (conv, (pf, (ss, _))))) =
(bal', (txn, (vw, (conv, (pf, (ss, (bal', ())))))))
where
bal' = bal <> c'Balance'Amount (best clatch)
createClatch
:: (Totaled l() -> Bool)
-- ^ Predicate
-> Seq (Sorted l a)
-> Seq (Clatch l)
createClatch pd
= fmap arrange
. serialNumbers
. Seq.filter pd
. addTotals
where
arrange ((t, (v, (a, (e, (s, (b, _)))))), o)
= (t, (v, (a, (e, (s, (b, (o, ())))))))
--
-- # Adding serials
--
addSersets
:: Seq (a, Seq b)
-> Seq ((a, Serset), Seq (b, Serset))
addSersets
= addTxn
. addPstg
where
addTxn = fmap runFlip . getCompose . serialNumbers . Compose . fmap Flip
addPstg = getCompose . getCompose . serialNumbers . Compose . Compose
addIndexes
:: Balanced a
-> Seq (Troika, a, Serset)
addIndexes
= fmap (\((tm, trees), srst) -> (tm, trees, srst))
. serialNumbers
. balancedToSeqEnt
arrangeTransaction
:: (((TopLine l, Serset), Serset),
Seq (((Troika, Postline l, Serset), Serset), Serset))
-> TransactionX l
arrangeTransaction (((txnMeta, txnLcl), txnGlbl), sq)
= (Serpack txnLcl txnGlbl, (txnMeta, pstgs))
where
pstgs = fmap mkPstg sq
mkPstg (((tm, trees, pstgIdx), pstgLcl), pstgGbl)
= (Serpack pstgLcl pstgGbl, (trees, Core tm pstgIdx))
addSerials
:: Seq (Seq (Transaction l))
-> Seq (TransactionX l)
addSerials
= fmap arrangeTransaction
. addSersets
. join
. fmap (addSersets . fmap (second addIndexes))
. fmap (fmap (\(Transaction tl pstgs) -> (tl, pstgs)))
--
-- Creator
--
clatchesFromTransactions
:: Converter
-- ^ Converts amounts
-> (Converted l () -> Bool)
-- ^ Filters 'Converted'
-> (Prefilt l () -> Prefilt l () -> Ordering)
-- ^ Sorts 'Prefilt'
-> (Totaled l () -> Bool)
-- ^ Filters 'Totaled'
-> Seq (TransactionX l)
-> Seq (Clatch l)
clatchesFromTransactions converter pConverted sorter pTotaled
= createClatch pTotaled
. createSortset sorter
. createPrefilt pConverted
. fmap (createConverted converter)
. join
. fmap createViewposts
|
massysett/penny
|
penny/lib/Penny/Clatch/Create.hs
|
bsd-3-clause
| 3,835
| 0
| 14
| 790
| 1,576
| 882
| 694
| 115
| 1
|
{-# language DeriveFunctor #-}
{-# language QuasiQuotes #-}
{-# language RankNTypes #-}
{-# language TemplateHaskell #-}
module OpenCV.Internal.Exception
( -- * Exception type
CvException(..)
, CoerceMatError(..)
, ExpectationError(..)
, CvCppException
-- * Handling C++ exceptions
, handleCvException
-- * Quasi quoters
, cvExcept
, cvExceptU
-- * Monadic interface
, CvExcept
, CvExceptT
, pureExcept
-- * Promoting exceptions to errors
, exceptError
, exceptErrorIO
, exceptErrorM
, runCvExceptST
-- * Unsafe stuff
, unsafeCvExcept
, unsafeWrapException
) where
import "base" Control.Monad.ST ( ST, runST )
import "base" Control.Exception ( Exception, mask_, throw, throwIO )
import "base" Control.Monad ( (<=<) )
import "base" Data.Functor.Identity
import "base" Data.Monoid ( (<>) )
import "base" Foreign.C.String ( peekCString )
import "base" Foreign.ForeignPtr ( ForeignPtr, withForeignPtr )
import "base" Foreign.Ptr ( Ptr, nullPtr )
import "base" System.IO.Unsafe ( unsafePerformIO )
import qualified "inline-c" Language.C.Inline as C
import qualified "inline-c" Language.C.Inline.Unsafe as CU
import qualified "inline-c-cpp" Language.C.Inline.Cpp as C
import "template-haskell" Language.Haskell.TH.Quote ( QuasiQuoter, quoteExp )
import "this" OpenCV.Internal.C.Inline ( openCvCtx )
import "this" OpenCV.Internal.C.Types
import "this" OpenCV.Internal.Core.Types.Mat.Depth
import "this" OpenCV.Internal ( objFromPtr )
import "transformers" Control.Monad.Trans.Except
--------------------------------------------------------------------------------
C.context openCvCtx
C.include "opencv2/core.hpp"
C.using "namespace cv"
--------------------------------------------------------------------------------
-- Exceptions
--------------------------------------------------------------------------------
data CvException
= BindingException !CvCppException
| CoerceMatError ![CoerceMatError]
deriving Show
data CoerceMatError
= ShapeError !(ExpectationError Int)
| SizeError !Int !(ExpectationError Int)
| ChannelError !(ExpectationError Int)
| DepthError !(ExpectationError Depth)
deriving Show
data ExpectationError a
= ExpectationError
{ expectedValue :: !a
, actualValue :: !a
} deriving (Show, Functor)
instance Exception CvException
newtype CvCppException = CvCppException { unCvCppException :: ForeignPtr (C CvCppException) }
type instance C CvCppException = C'CvCppException
instance WithPtr CvCppException where
withPtr = withForeignPtr . unCvCppException
instance FromPtr CvCppException where
fromPtr = objFromPtr CvCppException $ \ptr ->
[CU.exp| void { delete $(Exception * ptr) }|]
instance Show CvCppException where
show cvException = unsafePerformIO $
withPtr cvException $ \cvExceptionPtr -> do
charPtr <- [CU.exp| const char * { $(Exception * cvExceptionPtr)->what() } |]
peekCString charPtr
handleCvException
:: IO a
-> IO (Ptr (C CvCppException))
-> IO (Either CvException a)
handleCvException okAct act = mask_ $ do
exceptionPtr <- act
if exceptionPtr /= nullPtr
then do cppErr <- fromPtr (pure exceptionPtr)
pure $ Left $ BindingException cppErr
else Right <$> okAct
cvExcept :: QuasiQuoter
cvExcept = C.block {quoteExp = \s -> quoteExp C.block $ cvExceptWrap s}
cvExceptU :: QuasiQuoter
cvExceptU = CU.block {quoteExp = \s -> quoteExp CU.block $ cvExceptWrap s}
cvExceptWrap :: String -> String
cvExceptWrap s =
"Exception * {\n\
\ try\n\
\ {\n " <> s <> "\n\
\ return NULL;\n\
\ }\n\
\ catch (const cv::Exception & e)\n\
\ {\n\
\ return new cv::Exception(e);\n\
\ }\n\
\}"
type CvExcept a = Except CvException a
type CvExceptT m a = ExceptT CvException m a
pureExcept :: (Applicative m) => CvExcept a -> CvExceptT m a
pureExcept = mapExceptT (pure . runIdentity)
exceptError :: CvExcept a -> a
exceptError = either throw id . runExcept
exceptErrorIO :: CvExceptT IO a -> IO a
exceptErrorIO = either throwIO pure <=< runExceptT
exceptErrorM :: (Monad m) => CvExceptT m a -> m a
exceptErrorM = either throw pure <=< runExceptT
runCvExceptST :: (forall s. CvExceptT (ST s) a) -> CvExcept a
runCvExceptST act = except $ runST $ runExceptT act
unsafeCvExcept :: CvExceptT IO a -> CvExcept a
unsafeCvExcept = mapExceptT (Identity . unsafePerformIO)
unsafeWrapException :: IO (Either CvException a) -> CvExcept a
unsafeWrapException = unsafeCvExcept . ExceptT
|
Cortlandd/haskell-opencv
|
src/OpenCV/Internal/Exception.hs
|
bsd-3-clause
| 4,645
| 0
| 14
| 930
| 1,068
| 607
| 461
| -1
| -1
|
module Ygit.LsFiles (
lsFiles
) where
import qualified Data.ByteString.Lazy as BS
import System.Directory
import System.FilePath.Posix
import Data.Binary.Get
import Data.Word
lsFiles :: [String] -> IO ()
lsFiles args = do
indexFileContent <- indexFile
print $ runGet readHeader indexFileContent
indexFile :: IO BS.ByteString
indexFile = do
cwd <- getCurrentDirectory
let filePath = (cwd </> ".git" </> "index")
BS.readFile filePath
readHeader :: Get Word32
readHeader = do
dirc <- getWord32be
version <- getWord32be
numberOfFiles <- getWord32be
return $ numberOfFiles
|
jmpak/ygit
|
src/Ygit/LsFiles.hs
|
bsd-3-clause
| 601
| 0
| 12
| 109
| 177
| 92
| 85
| 22
| 1
|
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
module Fragment.KiBase.Helpers (
kiBase
) where
import Control.Lens (review)
import Ast.Kind
import Fragment.KiBase.Ast.Kind
kiBase :: AsKiBase k => Kind k a
kiBase = review _KiBase ()
|
dalaing/type-systems
|
src/Fragment/KiBase/Helpers.hs
|
bsd-3-clause
| 348
| 0
| 6
| 65
| 64
| 37
| 27
| 7
| 1
|
module Lambdasim.NMEA (
FixQuality(..),
gga,
) where
import Data.Bits (xor)
import Data.Char (ord)
import Data.List
import Data.Time.Clock
import Data.Time.Format (formatTime)
import System.Locale (defaultTimeLocale)
import Text.Printf (printf)
import qualified Prelude as P ((+))
import Lambdasim.Prelude
import Lambdasim.Geographical
data FixQuality
= Invalid | GPS | DGPS | PPS | RTK | FloatRTK
| DeadReckoning | Manual | Simulation
deriving (Enum, Show)
gga :: UTCTime -> Geog -> FixQuality -> String
gga time (Geog lat lon elh) quality = nmea
[ "GPGGA"
, take 9 $ formatTime defaultTimeLocale "%H%M%S%Q" time -- time of fix
, latDecimalMinutes lat -- latitude
, latHemisphere lat -- latitude hemisphere
, lonDecimalMinutes lon -- longitude
, lonHemisphere lon -- longitude hemisphere
, show $ fromEnum quality
, "08" -- number of satellites being tracked
, "0.0" -- horizontal dilution of position
, printf "%.1f" (elh /~ metre) -- altitude, metres above mean sea level
, "M" -- units for altitude
, "0.0" -- height of geoid (mean sea level) above WGS84
, "M" -- units for height
, "" -- time in seconds since last DGPS update
, "" -- DGPS station ID number
]
latHemisphere :: Angle -> String
latHemisphere x = hemisphere "N" "S" (x /~ degree)
lonHemisphere :: Angle -> String
lonHemisphere x = hemisphere "E" "W" (x /~ degree)
hemisphere :: (Num b, Ord b) => a -> a -> b -> a
hemisphere pos neg x | x > 0 = pos
| otherwise = neg
latDecimalMinutes :: Angle -> String
latDecimalMinutes = decimalMinutes 2 6
lonDecimalMinutes :: Angle -> String
lonDecimalMinutes = decimalMinutes 3 6
decimalMinutes :: Int -> Int -> Angle -> String
decimalMinutes degreeDigits minuteDecimals angle =
printf format degrees minutes
where
angle' = abs angle
degrees = truncate (angle' /~ degree)
minutes = remainder /~ arcminute
remainder = angle' - (fromInteger degrees *~ degree)
format = "%0" ++ dWidth ++ "d" ++
"%0" ++ mWidth ++ "." ++ mPrec ++ "f"
dWidth = show degreeDigits
mWidth = show (minuteDecimals P.+ 3)
mPrec = show minuteDecimals
nmea :: [String] -> String
nmea fields = "$" ++ sentence ++ "*" ++ checksum sentence ++ "\r\n"
where
sentence = intercalate "," fields
checksum :: String -> String
checksum xs = printf "%2X" $ foldl' xor 0 (map ord xs)
|
jystic/lambdasim
|
src/Lambdasim/NMEA.hs
|
bsd-3-clause
| 2,560
| 0
| 13
| 689
| 699
| 384
| 315
| 62
| 1
|
module Mandelbrot.Coloring (diverseColoring
, greenColoring
, grayColoring
, maxDepth
, Coloring) where
import Data.Word
-- 1 byte per color channel
maxDepth :: Integral a => a
maxDepth = fromIntegral (maxBound :: Word8) + 1
type Coloring = Int -> (Word8, Word8, Word8)
diverseColoring :: Coloring
diverseColoring num = (valBy 8, valBy 16, valBy 32)
where valBy = wrapNum . (* num)
greenColoring :: Coloring
greenColoring num = (0, wrapNum num, 0)
grayColoring :: Coloring
grayColoring num = (wrappedNum, wrappedNum, wrappedNum)
where wrappedNum = wrapNum num
wrapNum :: Int -> Word8
wrapNum = fromIntegral . (`mod` maxDepth)
|
matt-keibler/mandelbrot
|
src/Mandelbrot/Coloring.hs
|
bsd-3-clause
| 745
| 0
| 8
| 215
| 205
| 119
| 86
| 19
| 1
|
{-# LANGUAGE OverloadedStrings #-}
-------------------------------------------------------------------------------
-- |
-- Module : Generator.Printer.Section.Decode
-- Copyright : (c) 2016 Michael Carpenter
-- License : BSD3
-- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------
module Generator.Printer.Section.Decode
( docPacketGetter
, docGetFields
) where
import qualified Data.Text.Lazy as TL
import Generator.Types
import Generator.Printer.Types
import Text.PrettyPrint.Leijen.Text
docPacketGetter :: Packet -> Doc
docPacketGetter packet = vsep
[ indent 6 ((string . TL.fromStrict . pId $ packet)
<+> "-> do")
, docGetFields (pFields packet)
, indent 8 (string "return $"
<+> (string . pName $ packet)
<+> (docFieldNames . pFields $ packet))
]
docGetFields :: Maybe [Field] -> Doc
docGetFields maybeFields = undefined
{-
case maybeFields of
Just fields -> vsep $
fmap (\x -> do
case fieldType x of
SwitchType _ -> vsep $
[ indent 8 (string "let"
<+> string (TL.fromStrict (fieldName x))
<+> equals)
, indent 10 (string "case"
<+> string (TL.fromStrict (fieldCompareTo x))
<+> string "of")
, indent 12 (vsep $
fmap
(\(a,_) -> string (TL.fromStrict a) <+> string "->")
(fieldSwitches x))
, indent 12 (string "_" <+> string "->")
]
_ -> do
indent 8 (string (TL.fromStrict (fieldName x))
<+> "<-"
<+> docFieldGetter (fieldType x))
) fields
Nothing -> empty
-}
docFieldNames :: Maybe [Field] -> Doc
docFieldNames maybeFields =
case maybeFields of
Just fields -> hsep (fmap (text . fieldName) fields)
Nothing -> empty
|
oldmanmike/hs-minecraft-protocol
|
generate/src/Generator/Printer/Section/Decode.hs
|
bsd-3-clause
| 2,194
| 0
| 14
| 761
| 246
| 140
| 106
| 23
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.