code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE LiberalTypeSynonyms #-} {-# LANGUAGE RankNTypes #-} module Htn where import qualified Data.Map as M import Data.List (find, null, (\\)) class (Eq a, Ord a, Show a) => Term a class (Eq a, Ord a, Show a) => PrimitiveTask a class (Eq a, Ord a, Show a) => CompoundTask a data Task a b = Primitive a | Compound b | Invalid String deriving Show data Domain a b c = Domain { primitiveMap :: M.Map a [([c], [c])] , compoundMap :: M.Map b [([c], [Task a b])] } instance (Show a, Show b, Show c) => Show (Domain a b c) where show (Domain p c) = toStr p ++ toStr c where toStr :: (Show a, Show b) => M.Map a [b] -> String toStr = M.foldlWithKey (\str task list -> str ++ "-- " ++ show task ++ "\n" ++ unlines (map show list)) "" htn :: (PrimitiveTask a, CompoundTask b, Term c) => Domain a b c -> [c] -> [Task a b] -> ([Task a b], [c]) htn domain condition tasks = htn' domain condition tasks [] htn' :: (PrimitiveTask a, CompoundTask b, Term c) => Domain a b c -> [c] -> [Task a b] -> [Task a b] -> ([Task a b], [c]) htn' _ cond [] plan = (plan, cond) htn' domain [] _ plan = (plan ++ [Invalid "no condition"], []) htn' domain condition (task@(Invalid _):tasks) plan = (plan ++ [task, Invalid $ "current condition: " ++ show condition], condition) htn' domain condition (task@(Primitive pTask):tasks) plan = let newCondition = execute domain condition pTask in htn' domain newCondition tasks $ plan ++ [task] htn' domain condition (task@(Compound cTask):tasks) plan = let newTasks = breakdown domain condition cTask in htn' domain condition (newTasks ++ tasks) plan include :: (Ord a) => [a] -> [a] -> Bool include cond1 cond2 = null $ cond2 \\ cond1 breakdown :: (PrimitiveTask a, CompoundTask b, Term c) => Domain a b c -> [c] -> b -> [Task a b] breakdown domain condition task = case M.lookup task (compoundMap domain) of Nothing -> [Invalid $ "definition is not found for " ++ show task] Just list -> case find (\(pre, _) -> include condition pre) list of Just (_, tasks) -> tasks Nothing -> [Invalid $ "no condition is matched, current: " ++ show condition ++ ", task: " ++ show task] execute :: (PrimitiveTask a, Term c) => Domain a b c -> [c] -> a -> [c] execute domain condition task = case M.lookup task (primitiveMap domain) of Nothing -> [] Just list -> case find (\(pre, _) -> include condition pre) list of Just (pre, post) -> (condition \\ pre) ++ post Nothing -> []
y-kamiya/ai-samples
src/Htn.hs
bsd-3-clause
2,970
0
15
1,039
1,179
622
557
-1
-1
{-# LANGUAGE DefaultSignatures #-} module Mahjong.Class where import Foreign.C.Types -- | Tile describes the properties of a tile. class Tile a where suit :: a -> Bool suit = not . honor honor :: a -> Bool simple :: a -> Bool simple = not . terminal terminal :: a -> Bool default terminal :: (Eq a, Bounded a) => a -> Bool terminal a | suit a , a == minBound || a == maxBound = True | otherwise = False end :: a -> Bool end a | honor a || terminal a = True | otherwise = False -- | Enum and Bounded have a law that states that if succ a is equal to the -- maxBound return an error and thus it's never a good idea to abuse these laws -- for the type. Cycle on the other hand creates repeating infinite loops, which -- is useful in the game of Mahjong for things like determining the dora or next -- seat to be dealer. -- -- For the use of mahjong these laws must hold: -- If suit a == True -- - next (toEnum 9) = (toEnum 1) -- - prev (toEnum 1) = (toEnum 9) -- If honor a == True -- - next (toEnum 4) = (toEnum 1) -- - prev (toEnum 1) = (toEnum 4) class Cycle a where -- | The next tile in the cycle. next :: a -> a -- Eq, Enum, and Bounded already define the behavior that we are requesting -- without breaking the laws. default next :: (Eq a, Enum a, Bounded a) => a -> a next a | a == maxBound = minBound | otherwise = succ a -- | The previous tile in the cycle prev :: a -> a -- Eq, Enum, and Bounded already define the behavior that we are requesting -- without breaking the laws. default prev :: (Eq a, Enum a, Bounded a) => a -> a prev a | a == minBound = maxBound | otherwise = pred a -- | Properties of suited tiles. -- -- Since any suit tile is enumerated between 1-9 you can use type inference to -- get any suit that you need from. If you have an Enum instance for the type it -- can also be automatically derived for you. class Suit a where one, two, three, four, five, six, seven, eight, nine :: a default one :: Enum a => a one = toEnum 1 default two :: Enum a => a two = toEnum 2 default three :: Enum a => a three = toEnum 3 default four :: Enum a => a four = toEnum 4 default five :: Enum a => a five = toEnum 5 default six :: Enum a => a six = toEnum 6 default seven :: Enum a => a seven = toEnum 7 default eight :: Enum a => a eight = toEnum 8 default nine :: Enum a => a nine = toEnum 9 instance Suit Int instance Suit Integer instance Suit CInt
TakSuyu/mahjong
src/Mahjong/Class.hs
mit
2,511
0
12
659
611
325
286
51
0
{-# OPTIONS_HADDOCK hide, prune #-} module Handler.Mooc.FAQ ( getFAQR ) where import Import getFAQR :: Handler Html getFAQR = fullLayout Nothing "Frequently Asked Questions" $ do setTitle "Qua-kit: FAQ" toWidgetBody $ [hamlet| <div class="row"> <div class="col-lg-8 col-md-9 col-sm-10 col-xs-12"> <div.card.card-red> <div.card-main> <div.card-inner> In September-November 2016 we had the first run of our online course with qua-kit. At that time we received a number of questions from students regarding the work of the system. On this page you can find most common of them together with our answers. Please, try to find an answer to your question here before asking it by mail or via edX platform. <div class="col-lg-8 col-md-9 col-sm-10 col-xs-12"> <div.card> <div.card-main> <div.card-inner> <ol id="outlineList"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-1> I want other edX students to see and comment my design proposal! <div.card-inner> <p> This is hard to force unless they want to, right? <p> As the first step, we would suggest to de-anonymize yourself by changing your login name in qua-kit (upper right corner of the site pages). If you put the same nickname at qua-kit as you have at edX, it is easier for others to find you. <p> Second, try to write an interesting but concise description of your proposal when submitting/updating a design. Third, you can copy a direct link to your design submission and publish it in edX discussion (or somewhere else?). <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-2> I cannot move/rotate building blocks! <div.card-inner> <p> A. Make sure you get familiar with the controls. First, hold primary mouse button for panning, hold secondary mouse button (or primary + shift, or primary + ctrl) for rotating. These rules work for camera and for buildings. To move/rotate a block you first need to click on it (so it becomes red) to activate, and then drag using mouse to move/rotate. <p> B. Something may be wrong with your browser. Make sure you use the latest version of chrome/firefox/safari (chrome is reported to work best). If this does not work, we kindly ask you to submit an issue, so we could resolve it as soon as possible ( <a href="@{FeedbackR}">@{FeedbackR} ). When you report an issue, please specify following: <ul> <li>The browser you use (it will be very helpful if you can find out the version too). <li>The Operating System (Linux/Windows/Mac?) <li>Are you using mouse or touchpad? <li>Are you able to only move or only rotate buildings, or nothing at all? Can you select a building by clicking on it (so it turns red)? <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-3> I cannot use touchpad! <div.card-inner> <p> Due to the different nature of touchpads on different operating systems and browsers, it is difficult to make a touchpad behavior persistent across all of them. Touchpad may work to some extent, but we strongly advise you to use mouse controls. <p> On the other hand, if your screen supports multitouch, you can move camera and blocks using it - in a much more convenient manner! <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-4> I cannot see anything! <div.card-inner> <p> Something may be wrong with your browser. <p> Make sure you use the latest version of chrome/firefox/safari (chrome is reported to work best). <p> If this does not work, we kindly ask you to submit an issue, so we could resolve it as soon as possible ( <a href="@{FeedbackR}">@{FeedbackR} ). <p> When you report an issue, please specify following: <ul> <li> Which link do you use to start the exercise? Note, at least for a first time, you must use “Go!” button on the exercise 1 page. <li> The browser you use (it will be very helpful if you can find out the version too). <li> The Operating System (Linux/Windows/Mac?) <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-5> How do I submit a design solution? <div.card-inner> <p> When working on a design, in lower right corner you should see a red "tools" button. If you click on it, you should see a blue "submit" button. Click on it, and you will see a submit dialog. Enter your comments about the submission and press "submit" button. You will be redirected to the main site page, and your design will be saved. <p> You can come back and work on your design by using "menu -> Work on a design" entry in qua-kit site. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-6> I still cannot submit my design! <div.card-inner> <p> We kindly ask you to submit an issue, so we could resolve it as soon as possible ( <a href="@{FeedbackR}">@{FeedbackR} ). <p> Could you please clarify following points? This is important to find out exactly what your problem was. <ul> <li> Which link do you use to start the exercise? Note, at least for a first time, you must use “Go!” button on the exercise 1 page. <li> The browser you use (it will be very helpful if you can find out the version too). <li> The Operating System (Linux/Windows/Mac?) <li> Are you able to move/rotate buildings? <li> Do you have a blue submit button when you click on red tools button? <li> You do have a submit button, does the "submit design" dialog window appear on click? <li> What happens after you press "submit" in that window? <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-7> I can only view a design, but not edit or submit it! <div.card-inner> <p> This may happen if you use a wrong link to the editor (or you are not logged in the system). <p> Make sure you use either of two ways: <ul> <li> Use a button "Go!" on the exercise page at edX (it logs you in with edX credentials). <li> If you are logged in currently (check it at upper left corner of qua-kit site), you can use "menu" button (upper left corner) -> "Work on a design". <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-8> How do I find my submission after uploading it? <div.card-inner> <p> All submissions are listed in the gallery ("menu" -> "Explore submissions"), though it might be difficult to find your own submission, as there a lot of them. <p> On the other hand, you can always open your design in the editing mode. Just go to "menu" near top-left corner of any page at qua-kit and then click on "work on a design". Alternatively, you can use the same "Go!" button as the first time. Both ways redirect you to your last submission. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-9> Some of my building blocks overlap. Is that ok? <div.card-inner> <p> Yes. Although it is not an explicit feature, it is your decision to shrink the total area of buildings by overlapping them. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-10> What do orange lines mean? <div.card-inner> <p> Orange lines are meant as a guidance. They depict surrounding roads, zones, and buildings. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-11> Which area should I use for placing building blocks? <div.card-inner> <p> You should use an empty area in the center free of orange lines. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-12> How can I see rating of my proposal <div.card-inner> <p> You can look it up in the gallery ("menu" -> "Explore submissions"). <p> Icons and numbers show per-criterion rating on 0-100% scale (it is not a number of votes). <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-13> Can I comment others? <div.card-inner> <p> Yes. You can click "view" on a selected submission, then write a comment in the viewer windows. <p> You will also have to put up- or down-vote on a single criterion for this design. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-14> How can I see if anybody left a comment on my design? <div.card-inner> <p> Enter an editor mode ("menu" -> "Work on a design"), then open menu -> control panel (cogwheel icon). <p> You can only respond in a form of changing the description of your submission (when submitting a design update). <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-15> Do I need to use all blocks provided at qua-kit design template? <div.card-inner> <p> Yes, you do. There is no way to remove or add a block from the design. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-16> Can I update my design after submitting it? <div.card-inner> <p> Yes, you can. <p> Just go into an editor mode ("menu" -> "Work on a design") at qua-kit site and continue your work. <p> You can change it as many times as you want until the end of the course. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-17> How can I indicate that I have completed the task or I am still in progress? <div.card-inner> <p> You cannot do so. All submissions are visible to everybody right after you save them. Therefore we strongly recommend you to finish the exercise before the voting task starts (week 6). At that time, you will vote for submissions of others. <p> Nevertheless, you still can update your design until the very end of the course. That is, you can respond to comments of other students by addressing any issues they could have noticed. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-18> How do I get the grade for the first (design) exercise? <div.card-inner> <p> Right after you submit your design you get 60% of your grade automatically. <p> Then, your design is open for commenting and voting. In the second exercise other students vote for your designs and this make a peer-reviewed rating of all designs. Based on this rating, you get additional 0-40% (worst to best designs) of your grade. <p> Please note, voting is a long process so your grade will not change immediately. Instead, it will be updated once a day until the course ends (to take into account even latest user votes). <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-19> How do I get the grade for the second (compare-vote) exercise? <div.card-inner> <p> Right after you finish minimum number of comparisons, you get 60% of your grade automatically. <p> Remaning 0-40% you get while others vote: if your comparisons votes is similar to majority of other votes, your grade gets higher; if your votes contradict the majority, your grade gets lower. This is the essence of croud-sourcing approach and citizen science: majority decides! <p> Note, your grade is updated once a day as long as we receive other votes (to take into account even latest user votes). <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-20> I have not finished my design, but get (not good) grades! <div.card-inner> <p> This is a common situation. Look which criteria should you address more, and submit a new, revised version. <p> Your old votes get giscounted as new versions of your design appear. That is, if you submit a new version and get good responses, they count more than previous towards your final rating. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-21> Can I have multiple submissions? <div.card-inner> <p> No, only the last version of your design appears in qua-kit gallery and is available for voting/grading. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div.card> <div.card-main> <div.card-header> <div.card-inner> <h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-22> What happens if I change my nickname at qua-kit? <div.card-inner> <p> Nothing bad. Your design will still be connected to your account. <p> Your nickname appears in the submission gallery ("menu" -> "Explore submissions"). Hence, if you change your nickname to match the one at edX, it is easier to find and comment your design submission for others. So, do it! :) <script> var newLine, el, ToC = ""; \$("div h5").each(function() { el = $(this); ToC += "<li style='color: #ff6f00'>" + "<a href='#" + el.attr("id") + "'>" + el.text() + "</a>" + "</li>"; }); \$("#outlineList").html(ToC); |]
achirkin/qua-kit
apps/hs/qua-server/src/Handler/Mooc/FAQ.hs
mit
22,855
0
8
10,374
55
31
24
-1
-1
{-# LANGUAGE JavaScriptFFI #-} import qualified GHCJS.Foreign as F import GHCJS.Types import GHCJS.Marshal import GHCJS.Foreign (ToJSString(..), FromJSString(..), newObj, toJSBool, jsNull, jsFalse, jsTrue, mvarRef) import Control.Concurrent (threadDelay) import JavaScript.JQuery import JavaScript.JQuery.Internal import Data.Text (Text, pack, unpack) import Control.Applicative import Data.Maybe import Control.Monad import Data.Default import Protocol (Request (..), Response (..)) main = do setup loop setup = do playerNameInput <- getElement "#add-player-input" submitButton <- getElement "#add-player-submit" click (handleNewPlayerName playerNameInput) def submitButton handleNewPlayerName element _ = do name <- getVal element sendCommand $ AddPlayerRequest (unpack name) return () getElement = select . pack loop = do updatePlayerList threadDelay 1000000 loop sendCommand :: Request -> IO AjaxResult sendCommand command = do os <- toJSRef (def { asMethod = POST } :: AjaxSettings) jsCommand <- toJSRef $ show command F.setProp (pack "data") jsCommand os arr <- jq_ajax (toJSString "command") os dat <- F.getProp (pack "data") arr let d = if isNull dat then Nothing else Just (fromJSString dat) status <- fromMaybe 0 <$> (fromJSRef =<< F.getProp (pack "status") arr) return (AjaxResult status d) updatePlayerList = do result <- sendCommand PlayerListRequest case arData result of Nothing -> return () Just response -> do case read $ unpack response of (PlayerListResponse names) -> do let nameList = concat $ map wrapLi names element <- select $ pack "#current-players" setHtml (pack nameList) element return () _ -> putStrLn "Got an invalid response to command PlayerListRequest" wrapLi x = "<li>" ++ x ++ "</li>"
MichaelBaker/sartorial-client
vendor/sartorial-server/vendor/sartorial-client/src/Main.hs
mit
1,870
0
21
385
598
298
300
53
3
import X ( #if !defined(TESTING) X #else X(..) #endif -- f , f -- g , g , h ) import Y
itchyny/vim-haskell-indent
test/module/import_comma_first.in.hs
mit
100
0
5
35
26
18
8
-1
-1
import Criterion.Main import Control.Monad.MWC import Control.Monad.Reader main :: IO () main = do gen <- createSystemRandom let wrap name f size = bench name $ whnfIO $ replicateM_ 10000 $ runReaderT (f size) gen defaultMain $ flip map [10, 100, 1000, 10000] $ \size -> bgroup (show size) [ wrap "simple replicateM" uniformAsciiByteStringSimple size , wrap "complex Word64" uniformAsciiByteStringComplex64 size ]
bitemyapp/snoy-extra
bench/mwc-bytestring.hs
mit
475
0
13
122
149
75
74
12
1
{- DATX02-17-26, automated assessment of imperative programs. - Copyright, 2017, see AUTHORS.md. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} {-# LANGUAGE LambdaCase #-} module Norm.ForIndexConstLessThanEq (normForIndexCLTE) where import Norm.NormCS import CoreS.AST as AST stage :: Int stage = 1 normForIndexCLTE :: NormCUR normForIndexCLTE = makeRule' "for_index.stmt.for_index.clte" [stage] execForIndex --forIndex.stmt.for_index execForIndex :: NormCUA execForIndex = normEvery $ \case x@(SForB mForInit mExpr mExprs stmt) -> case mExpr of Just (ECmp LE left (ELit (Int i))) -> if left `isOk` mForInit then change $ SForB mForInit (Just (ECmp AST.LT left (ELit (Int (i+1))))) mExprs stmt else unique x _ -> unique x x -> unique x (EVar (LVName (Name [Ident ident]))) `isOk` (Just (FIVars (TypedVVDecl (VMType _ (PrimT IntT)) [VarDecl (VarDId (Ident ident')) _]))) = ident == ident' _ `isOk` _ = False
DATX02-17-26/DATX02-17-26
libsrc/Norm/ForIndexConstLessThanEq.hs
gpl-2.0
1,748
0
24
430
321
170
151
25
4
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hu-HU"> <title>Python Scripting</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>Keresés</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>
veggiespam/zap-extensions
addOns/jython/src/main/javahelp/org/zaproxy/zap/extension/jython/resources/help_hu_HU/helpset_hu_HU.hs
apache-2.0
964
79
66
157
412
208
204
-1
-1
{- | Module : Mongo.Pid.Removal Description : Get Pid from Name Copyright : (c) Plow Technology 2014 License : MIT Maintainer : brent.phillips@plowtech.net Stability : unstable Portability : portable <Uses a name to grab the pid to remove old pid alarms from mongo> -} {-# LANGUAGE OverloadedStrings, NoImplicitPrelude #-} import Mongo.Pid.Removal import BasicPrelude import Persist.Mongo.Settings lst :: [Int] lst = [111,122] main = do --conf <- readDBConf "mongoConfig.yml" --removeMissingAlarms conf lst
plow-technologies/mongo-pid-removal
src/RemovalMain_flymake.hs
bsd-3-clause
550
1
5
114
43
29
14
-1
-1
module Typed( typed, testPropertyI, testPropertyD, testPropertyZ, testPropertyDZ, immutableVector, immutableMatrix, ) where import Data.Complex( Complex ) import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck import Numeric.LinearAlgebra.Vector( Vector ) import Numeric.LinearAlgebra.Matrix( Matrix ) typed :: e -> a e -> a e typed _ = id immutableVector :: Vector e -> Vector e immutableVector = id immutableMatrix :: Matrix e -> Matrix e immutableMatrix = id testPropertyI :: (Testable a) => TestName -> (Int -> a) -> Test testPropertyI str prop = testProperty str $ prop undefined testPropertyDZ :: (Testable a, Testable b) => TestName -> (Double -> a) -> (Complex Double -> b) -> Test testPropertyDZ str propd propz = testGroup str [ testProperty "Double" $ propd undefined , testProperty "Complex Double" $ propz undefined ] testPropertyD :: (Testable a) => TestName -> (Double -> a) -> Test testPropertyD str prop = testProperty str $ prop undefined testPropertyZ :: (Testable a) => TestName -> (Complex Double -> a) -> Test testPropertyZ str prop = testProperty str $ prop undefined
patperry/hs-linear-algebra
tests/Typed.hs
bsd-3-clause
1,420
0
11
461
386
205
181
47
1
import Sound.Pd import Control.Concurrent import Control.Monad import Linear.Extra main :: IO () main = withPd $ \pd -> do p1 <- makePatch pd "test/world" forM_ (pdSources pd) $ \sourceID -> alSourcePosition sourceID ((V3 0 0 0) :: V3 Double) --_ <- forkIO $ forM_ [200,210..1500] $ \freq -> do -- send p1 "freq" $ Atom $ Float (freq) -- threadDelay 100000 _ <- forkIO $ forM_ (map ((*2) . sin) [0,0.01..]) $ \pos -> do --print $ "Listener now at " ++ show pos --alListenerPosition ((V3 0 0 (pos*5)) :: V3 Double) alListenerPosition (V3 0 0 (pos*5) :: V3 Double) alListenerOrientation ((axisAngle (V3 0 1 0) 0) :: Quaternion Double) threadDelay 10000 threadDelay 50000000
lukexi/pd-haskell
test/test-al.hs
bsd-3-clause
750
0
19
192
229
117
112
13
1
-------------------------------------------------------------------------------- -- | Provides URL shortening through the bit.ly API {-# LANGUAGE OverloadedStrings #-} module NumberSix.Util.BitLy ( shorten , textAndUrl ) where -------------------------------------------------------------------------------- import Data.Text (Text) import qualified Data.Text as T import Text.XmlHtml import Text.XmlHtml.Cursor -------------------------------------------------------------------------------- import NumberSix.Message import NumberSix.Util import NumberSix.Util.Http -------------------------------------------------------------------------------- shorten :: Text -> IO Text shorten query = do result <- httpScrape Xml url id $ fmap (nodeText . current) . findRec (byTagName "url") return $ case result of Just x -> x Nothing -> url where url = "http://api.bit.ly/v3/shorten?login=jaspervdj" <> "&apiKey=R_578fb5b17a40fa1f94669c6cba844df1" <> "&longUrl=" <> urlEncode (httpPrefix query) <> "&format=xml" -------------------------------------------------------------------------------- textAndUrl :: Text -> Text -> IO Text textAndUrl text url | T.length long <= maxLineLength = return long | otherwise = do shortUrl <- shorten url return $ join text shortUrl where join t u = if T.null t then u else t <> " >> " <> u long = join text url
itkovian/number-six
src/NumberSix/Util/BitLy.hs
bsd-3-clause
1,559
0
12
372
304
158
146
30
2
{-# LANGUAGE ScopedTypeVariables #-} -- You can set the following VERBOSE environment variable to control -- the verbosity of the output generated by this module. module PackageTests.PackageTester ( PackageSpec(..) , Success(..) , Result(..) -- * Running cabal commands , cabal_configure , cabal_build , cabal_haddock , cabal_test , cabal_bench , cabal_install , unregister , compileSetup , run -- * Test helpers , assertConfigureSucceeded , assertBuildSucceeded , assertBuildFailed , assertHaddockSucceeded , assertTestSucceeded , assertInstallSucceeded , assertOutputContains , assertOutputDoesNotContain ) where import qualified Control.Exception.Extensible as E import Control.Monad import qualified Data.ByteString.Char8 as C import Data.List import Data.Maybe import System.Directory (canonicalizePath, doesFileExist, getCurrentDirectory) import System.Environment (getEnv) import System.Exit (ExitCode(ExitSuccess)) import System.FilePath import System.IO (hIsEOF, hGetChar, hClose) import System.IO.Error (isDoesNotExistError) import System.Process (runProcess, waitForProcess) import Test.Tasty.HUnit (Assertion, assertFailure) import Distribution.Compat.CreatePipe (createPipe) import Distribution.Simple.BuildPaths (exeExtension) import Distribution.Simple.Program.Run (getEffectiveEnvironment) import Distribution.Simple.Utils (printRawCommandAndArgsAndEnv) import Distribution.ReadE (readEOrFail) import Distribution.Verbosity (Verbosity, flagToVerbosity, normal) data PackageSpec = PackageSpec { directory :: FilePath , distPref :: Maybe FilePath , configOpts :: [String] } data Success = Failure | ConfigureSuccess | BuildSuccess | HaddockSuccess | InstallSuccess | TestSuccess | BenchSuccess deriving (Eq, Show) data Result = Result { successful :: Bool , success :: Success , outputText :: String } deriving Show nullResult :: Result nullResult = Result True Failure "" ------------------------------------------------------------------------ -- * Running cabal commands recordRun :: (String, ExitCode, String) -> Success -> Result -> Result recordRun (cmd, exitCode, exeOutput) thisSucc res = res { successful = successful res && exitCode == ExitSuccess , success = if exitCode == ExitSuccess then thisSucc else success res , outputText = (if null $ outputText res then "" else outputText res ++ "\n") ++ cmd ++ "\n" ++ exeOutput } cabal_configure :: PackageSpec -> FilePath -> IO Result cabal_configure spec ghcPath = do res <- doCabalConfigure spec ghcPath record spec res return res doCabalConfigure :: PackageSpec -> FilePath -> IO Result doCabalConfigure spec ghcPath = do cleanResult@(_, _, _) <- cabal spec [] ["clean"] ghcPath requireSuccess cleanResult res <- cabal spec [] (["configure", "--user", "-w", ghcPath] ++ configOpts spec) ghcPath return $ recordRun res ConfigureSuccess nullResult doCabalBuild :: PackageSpec -> FilePath -> IO Result doCabalBuild spec ghcPath = do configResult <- doCabalConfigure spec ghcPath if successful configResult then do res <- cabal spec [] ["build", "-v"] ghcPath return $ recordRun res BuildSuccess configResult else return configResult cabal_build :: PackageSpec -> FilePath -> IO Result cabal_build spec ghcPath = do res <- doCabalBuild spec ghcPath record spec res return res cabal_haddock :: PackageSpec -> [String] -> FilePath -> IO Result cabal_haddock spec extraArgs ghcPath = do res <- doCabalHaddock spec extraArgs ghcPath record spec res return res doCabalHaddock :: PackageSpec -> [String] -> FilePath -> IO Result doCabalHaddock spec extraArgs ghcPath = do configResult <- doCabalConfigure spec ghcPath if successful configResult then do res <- cabal spec [] ("haddock" : extraArgs) ghcPath return $ recordRun res HaddockSuccess configResult else return configResult unregister :: String -> FilePath -> IO () unregister libraryName ghcPkgPath = do res@(_, _, output) <- run Nothing ghcPkgPath [] ["unregister", "--user", libraryName] if "cannot find package" `isInfixOf` output then return () else requireSuccess res -- | Install this library in the user area cabal_install :: PackageSpec -> FilePath -> IO Result cabal_install spec ghcPath = do buildResult <- doCabalBuild spec ghcPath res <- if successful buildResult then do res <- cabal spec [] ["install"] ghcPath return $ recordRun res InstallSuccess buildResult else return buildResult record spec res return res cabal_test :: PackageSpec -> [(String, Maybe String)] -> [String] -> FilePath -> IO Result cabal_test spec envOverrides extraArgs ghcPath = do res <- cabal spec envOverrides ("test" : extraArgs) ghcPath let r = recordRun res TestSuccess nullResult record spec r return r cabal_bench :: PackageSpec -> [String] -> FilePath -> IO Result cabal_bench spec extraArgs ghcPath = do res <- cabal spec [] ("bench" : extraArgs) ghcPath let r = recordRun res BenchSuccess nullResult record spec r return r compileSetup :: FilePath -> FilePath -> IO () compileSetup packageDir ghcPath = do wd <- getCurrentDirectory r <- run (Just $ packageDir) ghcPath [] [ "--make" -- HPC causes trouble -- see #1012 -- , "-fhpc" , "-package-conf " ++ wd </> "../dist/package.conf.inplace" , "Setup.hs" ] requireSuccess r -- | Returns the command that was issued, the return code, and the output text. cabal :: PackageSpec -> [(String, Maybe String)] -> [String] -> FilePath -> IO (String, ExitCode, String) cabal spec envOverrides cabalArgs_ ghcPath = do let cabalArgs = case distPref spec of Nothing -> cabalArgs_ Just dist -> ("--builddir=" ++ dist) : cabalArgs_ customSetup <- doesFileExist (directory spec </> "Setup.hs") if customSetup then do compileSetup (directory spec) ghcPath path <- canonicalizePath $ directory spec </> "Setup" run (Just $ directory spec) path envOverrides cabalArgs else do -- Use shared Setup executable (only for Simple build types). path <- canonicalizePath "Setup" run (Just $ directory spec) path envOverrides cabalArgs -- | Returns the command that was issued, the return code, and the output text run :: Maybe FilePath -> String -> [(String, Maybe String)] -> [String] -> IO (String, ExitCode, String) run cwd path envOverrides args = do verbosity <- getVerbosity -- path is relative to the current directory; canonicalizePath makes it -- absolute, so that runProcess will find it even when changing directory. path' <- do pathExists <- doesFileExist path canonicalizePath (if pathExists then path else path <.> exeExtension) menv <- getEffectiveEnvironment envOverrides printRawCommandAndArgsAndEnv verbosity path' args menv (readh, writeh) <- createPipe pid <- runProcess path' args cwd menv Nothing (Just writeh) (Just writeh) -- fork off a thread to start consuming the output out <- suckH [] readh hClose readh -- wait for the program to terminate exitcode <- waitForProcess pid let fullCmd = unwords (path' : args) return ("\"" ++ fullCmd ++ "\" in " ++ fromMaybe "" cwd, exitcode, out) where suckH output h = do eof <- hIsEOF h if eof then return (reverse output) else do c <- hGetChar h suckH (c:output) h requireSuccess :: (String, ExitCode, String) -> IO () requireSuccess (cmd, exitCode, output) = unless (exitCode == ExitSuccess) $ assertFailure $ "Command " ++ cmd ++ " failed.\n" ++ "output: " ++ output record :: PackageSpec -> Result -> IO () record spec res = do C.writeFile (directory spec </> "test-log.txt") (C.pack $ outputText res) ------------------------------------------------------------------------ -- * Test helpers assertConfigureSucceeded :: Result -> Assertion assertConfigureSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup configure\' should succeed\n" ++ " output: " ++ outputText result assertBuildSucceeded :: Result -> Assertion assertBuildSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup build\' should succeed\n" ++ " output: " ++ outputText result assertBuildFailed :: Result -> Assertion assertBuildFailed result = when (successful result) $ assertFailure $ "expected: \'setup build\' should fail\n" ++ " output: " ++ outputText result assertHaddockSucceeded :: Result -> Assertion assertHaddockSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup haddock\' should succeed\n" ++ " output: " ++ outputText result assertTestSucceeded :: Result -> Assertion assertTestSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup test\' should succeed\n" ++ " output: " ++ outputText result assertInstallSucceeded :: Result -> Assertion assertInstallSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup install\' should succeed\n" ++ " output: " ++ outputText result assertOutputContains :: String -> Result -> Assertion assertOutputContains needle result = unless (needle `isInfixOf` (concatOutput output)) $ assertFailure $ " expected: " ++ needle ++ "\n" ++ " in output: " ++ output ++ "" where output = outputText result assertOutputDoesNotContain :: String -> Result -> Assertion assertOutputDoesNotContain needle result = when (needle `isInfixOf` (concatOutput output)) $ assertFailure $ "unexpected: " ++ needle ++ " in output: " ++ output where output = outputText result -- | Replace line breaks with spaces, correctly handling "\r\n". concatOutput :: String -> String concatOutput = unwords . lines . filter ((/=) '\r') ------------------------------------------------------------------------ -- Verbosity lookupEnv :: String -> IO (Maybe String) lookupEnv name = (fmap Just $ getEnv name) `E.catch` \ (e :: IOError) -> if isDoesNotExistError e then return Nothing else E.throw e -- TODO: Convert to a "-v" flag instead. getVerbosity :: IO Verbosity getVerbosity = do maybe normal (readEOrFail flagToVerbosity) `fmap` lookupEnv "VERBOSE"
corngood/cabal
Cabal/tests/PackageTests/PackageTester.hs
bsd-3-clause
10,883
0
16
2,540
2,762
1,427
1,335
242
3
{-# LANGUAGE PackageImports #-} module Test17388 where import "base" Prelude import {-# Source #-} Foo.Bar import {-# SOURCE #-} "base" Data.Data import {-# SOURCE #-} qualified "base" Data.Data
sdiehl/ghc
testsuite/tests/ghc-api/annotations/Test17388.hs
bsd-3-clause
203
0
4
36
30
22
8
6
0
import System.Exit (ExitCode(..), exitWith) import System.Posix.Process import System.Posix.Signals main = do test1 test2 test3 test4 putStrLn "I'm happy." test1 = do -- Force SIGFPE exceptions to not be ignored. Under some -- circumstances this test will be run with SIGFPE -- ignored, see #7399 installHandler sigFPE Default Nothing forkProcess $ raiseSignal floatingPointException Just (pid, tc) <- getAnyProcessStatus True False case tc of Terminated sig _ | sig == floatingPointException -> return () _ -> error "unexpected termination cause" test2 = do forkProcess $ exitImmediately (ExitFailure 42) Just (pid, tc) <- getAnyProcessStatus True False case tc of Exited (ExitFailure 42) -> return () _ -> error "unexpected termination cause (2)" test3 = do forkProcess $ exitImmediately ExitSuccess Just (pid, tc) <- getAnyProcessStatus True False case tc of Exited ExitSuccess -> return () _ -> error "unexpected termination cause (3)" test4 = do forkProcess $ raiseSignal softwareStop Just (pid, tc) <- getAnyProcessStatus True True case tc of Stopped sig | sig == softwareStop -> do signalProcess killProcess pid Just (pid, tc) <- getAnyProcessStatus True True case tc of Terminated sig _ | sig == killProcess -> return () _ -> error "unexpected termination cause (5)" _ -> error "unexpected termination cause (4)"
jimenezrick/unix
tests/libposix/posix004.hs
bsd-3-clause
1,565
0
19
444
430
199
231
38
3
module Goo (poop) where class Zog a where zoom :: a -> Int -- Assume the relevant behavior for the method. {-@ zoom :: (Zog a) => a -> Nat @-} -- Uses the behavior of `zoom` {-@ poop :: (Zog a) => a -> Nat @-} poop x = zoom x
mightymoose/liquidhaskell
tests/pos/tyclass0.hs
bsd-3-clause
231
0
7
57
42
24
18
4
1
{-# LANGUAGE ScopedTypeVariables #-} -- !!! Error messages with scoped type variables module Foo where data Set a = Set a unionSetB :: Eq a => Set a -> Set a -> Set a unionSetB (s1 :: Set a) s2 = unionSets s1 s2 where unionSets :: Eq a => Set a -> Set a -> Set a unionSets a b = a {- In GHC 4.04 this gave the terrible message: None of the type variable(s) in the constraint `Eq a' appears in the type `Set a -> Set a -> Set a' In the type signature for `unionSets' -}
ryantm/ghc
testsuite/tests/rename/should_fail/rnfail020.hs
bsd-3-clause
492
0
10
124
112
56
56
7
1
-- !!! an example Simon made up -- module ShouldSucceed where f x = (x+1, x<3, g True, g 'c') where g y = if x>2 then [] else [y] {- Here the type-check of g will yield an LIE with an Ord dict for x. g still has type forall a. a -> [a]. The dictionary is free, bound by the x. It should be ok to add the signature: -} f2 x = (x+1, x<3, g2 True, g2 'c') where -- NB: this sig: g2 :: a -> [a] g2 y = if x>2 then [] else [y] {- or to write: -} f3 x = (x+1, x<3, g3 True, g3 'c') where -- NB: this line: g3 :: a -> [a] g3 = (\ y -> if x>2 then [] else [y])::(a -> [a])
urbanslug/ghc
testsuite/tests/typecheck/should_compile/tc081.hs
bsd-3-clause
588
1
9
160
236
134
102
9
2
{-# LANGUAGE ParallelArrays #-} {-# OPTIONS -fvectorise #-} module Types ( Point, Line, points, xsOf, ysOf) where import Data.Array.Parallel import Data.Array.Parallel.Prelude.Double type Point = (Double, Double) type Line = (Point, Point) points' :: [:Double:] -> [:Double:] -> [:Point:] points' = zipP points :: PArray Double -> PArray Double -> PArray Point {-# NOINLINE points #-} points xs ys = toPArrayP (points' (fromPArrayP xs) (fromPArrayP ys)) xsOf' :: [:Point:] -> [:Double:] xsOf' ps = [: x | (x, _) <- ps :] xsOf :: PArray Point -> PArray Double {-# NOINLINE xsOf #-} xsOf ps = toPArrayP (xsOf' (fromPArrayP ps)) ysOf' :: [:Point:] -> [:Double:] ysOf' ps = [: y | (_, y) <- ps :] ysOf :: PArray Point -> PArray Double {-# NOINLINE ysOf #-} ysOf ps = toPArrayP (ysOf' (fromPArrayP ps))
urbanslug/ghc
testsuite/tests/dph/quickhull/Types.hs
bsd-3-clause
810
27
9
145
338
187
151
22
1
module Main where import C main = print ("hello world" ++ show (f 42))
ghc-android/ghc
testsuite/tests/ghci/prog002/D.hs
bsd-3-clause
73
0
10
16
31
17
14
3
1
-- | -- Module: src-test/Main.hs -- Copyright: 2016 Michael Litchard -- License: BSD3 -- Maintainer: <Michael Litchard> <michael@schmong.org> -- A few tests for fizzbuzz demo module Main (main) where import BasicPrelude import Test.Hspec (hspec) import PropTests.Fibonacci import PropTests.FizzBuzz import UnitTests.Fibonacci import UnitTests.Input -- | -- Tests are first divided up into unit and property tests main :: IO () main = do hspec unitFib hspec unitInput hspec $ propFib upper_bound hspec $ propFizz upper_bound upper_bound :: Int upper_bound = 100000
mlitchard/swiftfizz
src-test/Main.hs
isc
588
0
8
104
107
60
47
15
1
{-# LANGUAGE LambdaCase #-} module Oden.Core.Expr where import Oden.Core.Foreign import Oden.Identifier import Oden.Metadata import Oden.SourceInfo data NameBinding = NameBinding (Metadata SourceInfo) Identifier deriving (Show, Eq, Ord) data FieldInitializer e = FieldInitializer (Metadata SourceInfo) Identifier e deriving (Show, Eq, Ord) data Literal = Int Integer | Float Double | Bool Bool | String String | Unit deriving (Show, Eq, Ord) data Range e = Range e e | RangeTo e | RangeFrom e deriving (Show, Eq, Ord) data Expr r t m = Symbol (Metadata SourceInfo) Identifier t | Subscript (Metadata SourceInfo) (Expr r t m) (Expr r t m) t | Subslice (Metadata SourceInfo) (Expr r t m) (Range (Expr r t m)) t | Application (Metadata SourceInfo) (Expr r t m) (Expr r t m) t | NoArgApplication (Metadata SourceInfo) (Expr r t m) t | ForeignFnApplication (Metadata SourceInfo) (Expr r t m) [Expr r t m] t | Fn (Metadata SourceInfo) NameBinding (Expr r t m) t | NoArgFn (Metadata SourceInfo) (Expr r t m) t | Let (Metadata SourceInfo) NameBinding (Expr r t m) (Expr r t m) t | Literal (Metadata SourceInfo) Literal t | Tuple (Metadata SourceInfo) (Expr r t m) (Expr r t m) [Expr r t m] t | If (Metadata SourceInfo) (Expr r t m) (Expr r t m) (Expr r t m) t | Slice (Metadata SourceInfo) [Expr r t m] t | Block (Metadata SourceInfo) [Expr r t m] t | RecordInitializer (Metadata SourceInfo) [FieldInitializer (Expr r t m)] t | MemberAccess (Metadata SourceInfo) m t | MethodReference (Metadata SourceInfo) r t | Foreign (Metadata SourceInfo) ForeignExpr t deriving (Show, Eq, Ord) typeOf :: Expr r t m -> t typeOf expr = case expr of Symbol _ _ t -> t Subscript _ _ _ t -> t Subslice _ _ _ t -> t Application _ _ _ t -> t NoArgApplication _ _ t -> t ForeignFnApplication _ _ _ t -> t Fn _ _ _ t -> t NoArgFn _ _ t -> t Let _ _ _ _ t -> t Literal _ _ t -> t If _ _ _ _ t -> t Tuple _ _ _ _ t -> t Slice _ _ t -> t Block _ _ t -> t RecordInitializer _ _ t -> t MemberAccess _ _ t -> t MethodReference _ _ t -> t Foreign _ _ t -> t -- | Applies a mapping function to the type of an expression. mapType :: (t -> t) -> Expr r t m -> Expr r t m mapType f = \case Symbol meta i t -> Symbol meta i (f t) Subscript meta s i t -> Subscript meta s i (f t) Subslice meta s r t -> Subslice meta s r (f t) Application meta func a t -> Application meta func a (f t) NoArgApplication meta func t -> NoArgApplication meta func (f t) ForeignFnApplication meta func a t -> ForeignFnApplication meta func a (f t) Fn meta n b t -> Fn meta n b (f t) NoArgFn meta b t -> NoArgFn meta b (f t) Let meta n v b t -> Let meta n v b (f t) Literal meta l t -> Literal meta l (f t) If meta c t e t' -> If meta c t e (f t') Slice meta e t -> Slice meta e (f t) Tuple meta f' s r t -> Tuple meta f' s r (f t) Block meta e t -> Block meta e (f t) RecordInitializer meta vs t -> RecordInitializer meta vs (f t) MemberAccess meta member t -> MemberAccess meta member (f t) MethodReference meta ref t -> MethodReference meta ref (f t) Foreign meta foreign' t -> Foreign meta foreign' (f t) instance HasSourceInfo (Expr r t m) where getSourceInfo expr = case expr of Symbol (Metadata si) _ _ -> si Subscript (Metadata si) _ _ _ -> si Subslice (Metadata si) _ _ _ -> si Application (Metadata si) _ _ _ -> si NoArgApplication (Metadata si) _ _ -> si ForeignFnApplication (Metadata si) _ _ _ -> si Fn (Metadata si) _ _ _ -> si NoArgFn (Metadata si) _ _ -> si Let (Metadata si) _ _ _ _ -> si Literal (Metadata si) _ _ -> si If (Metadata si) _ _ _ _ -> si Slice (Metadata si) _ _ -> si Tuple (Metadata si) _ _ _ _ -> si Block (Metadata si) _ _ -> si RecordInitializer (Metadata si) _ _ -> si MemberAccess (Metadata si) _ _ -> si MethodReference (Metadata si) _ _ -> si Foreign (Metadata si) _ _ -> si setSourceInfo si expr = case expr of Symbol _ i t -> Symbol (Metadata si) i t Subscript _ s i t -> Subscript (Metadata si) s i t Subslice _ s r t -> Subslice (Metadata si) s r t Application _ f a t -> Application (Metadata si) f a t NoArgApplication _ f t -> NoArgApplication (Metadata si) f t ForeignFnApplication _ f a t -> ForeignFnApplication (Metadata si) f a t Fn _ n b t -> Fn (Metadata si) n b t NoArgFn _ b t -> NoArgFn (Metadata si) b t Let _ n v b t -> Let (Metadata si) n v b t Literal _ l t -> Literal (Metadata si) l t If _ c t e t' -> If (Metadata si) c t e t' Slice _ e t -> Slice (Metadata si) e t Tuple _ f s r t -> Tuple (Metadata si) f s r t Block _ e t -> Block (Metadata si) e t RecordInitializer _ t vs -> RecordInitializer (Metadata si) t vs MemberAccess _ m t -> MemberAccess (Metadata si) m t MethodReference _ ref t -> MethodReference (Metadata si) ref t Foreign _ f t -> Foreign (Metadata si) f t
oden-lang/oden
src/Oden/Core/Expr.hs
mit
5,972
0
11
2,293
2,482
1,211
1,271
122
18
thousands = [y | z <- [1..1000], y <- [[x, yy, z] | yy <- [1..1000], let x = (1000 - yy - z), x > 0, x < yy, yy < z] ] isTriplet :: [Int] -> Bool isTriplet xs = a^2 + b^2 == c^2 where a = head xs b = xs !! 1 c = xs !! 2 problem9 = product $ head [x | x <- thousands, isTriplet x]
danhaller/euler-haskell
9.hs
mit
318
16
15
112
209
111
98
8
1
{-# LANGUAGE NoMonomorphismRestriction #-} import Diagrams.Prelude import Diagrams.Backend.SVG.CmdLine c1 = circle 0.5 # fc steelblue c2 = circle 1 # fc orange diagram :: Diagram B diagram = beside (1 ^& 1) c1 c2 # showOrigin main = mainWith $ frame 0.1 diagram
jeffreyrosenbluth/NYC-meetup
meetup/Atop6.hs
mit
268
0
8
49
89
46
43
8
1
mpow :: Int -> Float -> Float mpow 0 _ = 1 mpow n f = f * (mpow (n-1) f) main = print (mpow 50 0.5)
lucas8/MPSI
ipt/recursive/misc/pow.hs
mit
103
0
9
30
69
35
34
4
1
module ChatCore.ChatLog.File ( LogFileId (..) , logFileForDate , dayForLogFile , logFileForToday , logFileForLine , logFileName , parseLogFileId , logFilesInDir , ChatLogLine (..) ) where import Control.Applicative import Control.Error import Data.Time import System.Directory import System.FilePath import Text.Parsec import Text.Printf import ChatCore.ChatLog.Line -- | Identifier for log files. data LogFileId = LogFileId { lfDay :: Int , lfMonth :: Int , lfYear :: Integer } deriving (Show, Read, Eq) instance Ord LogFileId where a <= b = (lfYear a <= lfYear b) || (lfMonth a <= lfMonth b) || (lfDay a <= lfDay b) -- {{{ Date <-> ID conversions -- | Gets the log file ID for today. logFileForToday :: IO LogFileId logFileForToday = logFileForDate <$> getCurrentTime -- | Gets the log file ID for the given date. logFileForDate :: UTCTime -> LogFileId logFileForDate date = LogFileId day month year where (year, month, day) = toGregorian $ utctDay date -- | Gets the UTCTime day for the given log file. dayForLogFile :: LogFileId -> Day dayForLogFile (LogFileId day month year) = fromGregorian year month day -- | Gets the log file ID that the given line should be written to. logFileForLine :: ChatLogLine -> LogFileId logFileForLine = logFileForDate . logLineTime logFileName :: LogFileId -> String logFileName l = printf "%04i-%02i-%02i.log" (lfYear l) (lfMonth l) (lfDay l) -- | Parses a string to a `LogFileId` parseLogFileId :: String -> Maybe LogFileId parseLogFileId idStr = hush $ parse parser "Log File ID" idStr where parser = do year <- numSize 4 _ <- char '-' month <- numSize 2 _ <- char '-' day <- numSize 2 _ <- string ".log" return $ LogFileId day month year -- Read n many digits and parse them as an integer. numSize n = read <$> count n digit -- }}} -- {{{ Listing -- | Gets a list of log files at the given path. logFilesInDir :: FilePath -> IO [LogFileId] logFilesInDir dir = mapMaybe parseLogFileId <$> map takeFileName <$> getDirectoryContents dir -- }}}
Forkk/ChatCore
ChatCore/ChatLog/File.hs
mit
2,186
0
10
533
535
282
253
53
1
{-# LANGUAGE LambdaCase #-} module Main where import qualified $module$ import Control.Applicative import Control.Monad import Control.Concurrent.Timeout import Data.Time.Clock.POSIX import Data.Timeout import System.IO import Text.Printf import Language.Haskell.Liquid.Types (GhcSpec) import Test.Target import Test.Target.Monad import Test.Target.Util main :: IO () main = do spec <- getSpec "$file$" withFile "_results/$module$.tsv" WriteMode $ \h -> do hPutStrLn h "Function\tDepth\tTime(s)\tResult" mapM_ (checkMany spec h) funs putStrLn "done" putStrLn "" -- checkMany :: GhcSpec -> Handle -> IO [(Int, Double, Outcome)] checkMany spec h (T f,sp) = putStrNow (printf "Testing %s..\n" sp) >> go 2 where go 11 = return [] go n = checkAt n >>= \case (d,Nothing) -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show TimeOut) putStrLn s >> hFlush stdout hPutStrLn h s >> hFlush h return [(n,d,TimeOut)] --NOTE: ignore counter-examples for the sake of exploring coverage --(d,Just (Failed s)) -> return [(n,d,Completed (Failed s))] (d,Just r) -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show (Complete r)) putStrLn s >> hFlush stdout hPutStrLn h s >> hFlush h ((n,d,Complete r):) <$> go (n+1) checkAt n = timed $ timeout time $ runGen spec "$file$" $ testFunIgnoringFailure f sp n time = $timeout$ # Minute getTime :: IO Double getTime = realToFrac `fmap` getPOSIXTime timed x = do start <- getTime v <- x end <- getTime return (end-start, v) putStrNow s = putStr s >> hFlush stdout data Outcome = Complete Result | TimeOut deriving (Show) funs = [$funs$]
gridaphobe/target
bin/CheckFun.template.hs
mit
1,970
6
20
651
581
294
287
-1
-1
module Codecs.QuickCheck where import Data.Monoid ((<>)) import Test.Tasty import Test.QuickCheck import Test.QuickCheck.Arbitrary import Test.QuickCheck.Monadic import Data.Scientific as S import Data.Time import Text.Printf import Data.List as L import Data.UUID (UUID, fromWords) import Data.String (IsString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Database.PostgreSQL.Driver import Database.PostgreSQL.Protocol.DataRows import Database.PostgreSQL.Protocol.Types import Database.PostgreSQL.Protocol.Store.Encode import Database.PostgreSQL.Protocol.Store.Decode import qualified Database.PostgreSQL.Protocol.Codecs.Decoders as PD import qualified Database.PostgreSQL.Protocol.Codecs.Encoders as PE import qualified Database.PostgreSQL.Protocol.Codecs.PgTypes as PGT import Connection import Codecs.Runner -- | Makes property that if here is a value then encoding and sending it -- to PostgreSQL, and receiving back returns the same value. makeCodecProperty :: (Show a, Eq a, Arbitrary a) => Connection -> Oid -> (a -> Encode) -> PD.FieldDecoder a -> a -> Property makeCodecProperty c oid encoder fd v = monadicIO $ do let q = Query "SELECT $1" [(oid, Just $ encoder v)] Binary Binary AlwaysCache decoder = PD.dataRowHeader *> PD.getNonNullable fd r <- run $ do sendBatchAndSync c [q] dr <- readNextData c waitReadyForQuery c either (error . show) (pure . decodeOneRow decoder) dr assertQCEqual v r -- | Makes a property that encoded value is correctly parsed and printed -- by PostgreSQL. makeCodecEncodeProperty :: Arbitrary a => Connection -> Oid -> B.ByteString -> (a -> Encode) -> (a -> String) -> a -> Property makeCodecEncodeProperty c oid queryString encoder fPrint v = monadicIO $ do let q = Query queryString [(oid, Just $ encoder v)] Binary Text AlwaysCache decoder = PD.dataRowHeader *> PD.getNonNullable PD.bytea r <- run $ do sendBatchAndSync c [q] dr <- readNextData c waitReadyForQuery c either (error . show) (pure . BC.unpack . decodeOneRow decoder) dr assertQCEqual (fPrint v) r assertQCEqual :: (Eq a, Show a, Monad m) => a -> a -> PropertyM m () assertQCEqual a b | a == b = pure () | otherwise = fail $ "Equal assertion failed. Expected:\n" <> show a <> "\nbut got:\n" <> show b -- | Makes Tasty test tree. mkCodecTest :: (Eq a, Arbitrary a, Show a) => TestName -> PGT.Oids -> (a -> Encode) -> PD.FieldDecoder a -> TestTree mkCodecTest name oids encoder decoder = testPropertyConn name $ \c -> makeCodecProperty c (PGT.oidType oids) encoder decoder mkCodecEncodeTest :: (Arbitrary a, Show a) => TestName -> PGT.Oids -> B.ByteString -> (a -> Encode) -> (a -> String) -> TestTree mkCodecEncodeTest name oids queryString encoder fPrint = testPropertyConn name $ \c -> makeCodecEncodeProperty c (PGT.oidType oids) queryString encoder fPrint testCodecsEncodeDecode :: TestTree testCodecsEncodeDecode = testGroup "Codecs property 'encode . decode = id'" [ mkCodecTest "bool" PGT.bool PE.bool PD.bool , mkCodecTest "bytea" PGT.bytea PE.bytea PD.bytea , mkCodecTest "char" PGT.char (PE.char . unAsciiChar) (fmap AsciiChar <$> PD.char) , mkCodecTest "date" PGT.date PE.date PD.date , mkCodecTest "float4" PGT.float4 PE.float4 PD.float4 , mkCodecTest "float8" PGT.float8 PE.float8 PD.float8 , mkCodecTest "int2" PGT.int2 PE.int2 PD.int2 , mkCodecTest "int4" PGT.int4 PE.int4 PD.int4 , mkCodecTest "int8" PGT.int8 PE.int8 PD.int8 , mkCodecTest "interval" PGT.interval PE.interval PD.interval , mkCodecTest "json" PGT.json (PE.bsJsonText . unJsonString) (fmap JsonString <$> PD.bsJsonText) , mkCodecTest "jsonb" PGT.jsonb (PE.bsJsonBytes . unJsonString) (fmap JsonString <$> PD.bsJsonBytes) , mkCodecTest "numeric" PGT.numeric PE.numeric PD.numeric , mkCodecTest "text" PGT.text PE.bsText PD.bsText , mkCodecTest "time" PGT.time PE.time PD.time , mkCodecTest "timetz" PGT.timetz PE.timetz PD.timetz , mkCodecTest "timestamp" PGT.timestamp PE.timestamp PD.timestamp , mkCodecTest "timestamptz" PGT.timestamptz PE.timestamptz PD.timestamptz , mkCodecTest "uuid" PGT.uuid PE.uuid PD.uuid ] testCodecsEncodePrint :: TestTree testCodecsEncodePrint = testGroup "Codecs property 'Encoded value Postgres = value in Haskell'" [ mkCodecEncodeTest "bool" PGT.bool qBasic PE.bool displayBool , mkCodecEncodeTest "date" PGT.date qBasic PE.date show , mkCodecEncodeTest "float8" PGT.float8 "SELECT trim(to_char($1, '99999999999990.9999999999'))" PE.float8 (printf "%.10f") , mkCodecEncodeTest "int8" PGT.int8 qBasic PE.int8 show , mkCodecEncodeTest "interval" PGT.interval "SELECT extract(epoch from $1)||'s'" PE.interval show , mkCodecEncodeTest "numeric" PGT.numeric qBasic PE.numeric displayScientific , mkCodecEncodeTest "timestamp" PGT.timestamp qBasic PE.timestamp show , mkCodecEncodeTest "timestamptz" PGT.timestamptz "SELECT ($1 at time zone 'UTC')||' UTC'" PE.timestamptz show , mkCodecEncodeTest "uuid" PGT.uuid qBasic PE.uuid show ] where qBasic = "SELECT $1" displayScientific s | isInteger s = show $ ceiling s | otherwise = formatScientific S.Fixed Nothing s displayBool False = "f" displayBool True = "t" -- -- Orphan instances -- newtype AsciiChar = AsciiChar { unAsciiChar :: Char } deriving (Show, Eq) instance Arbitrary AsciiChar where arbitrary = AsciiChar <$> choose ('\0', '\127') -- Helper to generate valid json strings newtype JsonString = JsonString { unJsonString :: B.ByteString } deriving (Show, Eq, IsString) instance Arbitrary JsonString where arbitrary = oneof $ map pure [ "{}" , "{\"a\": 5}" , "{\"b\": [1, 2, 3]}" ] instance Arbitrary B.ByteString where arbitrary = do len <- choose (0, 1024) B.pack <$> vectorOf len (choose (1, 127)) instance Arbitrary Day where arbitrary = ModifiedJulianDay <$> choose (-100000, 100000) instance Arbitrary DiffTime where arbitrary = secondsToDiffTime <$> choose (0, 86400 - 1) instance Arbitrary TimeOfDay where arbitrary = timeToTimeOfDay <$> arbitrary instance Arbitrary LocalTime where arbitrary = LocalTime <$> arbitrary <*> fmap timeToTimeOfDay arbitrary instance Arbitrary UTCTime where arbitrary = UTCTime <$> arbitrary <*> arbitrary instance Arbitrary UUID where arbitrary = fromWords <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary Scientific where arbitrary = do c <- choose (-100000000, 100000000) e <- choose (-10, 10) pure . normalize $ scientific c e
postgres-haskell/postgres-wire
tests/Codecs/QuickCheck.hs
mit
7,070
0
16
1,608
1,947
1,019
928
155
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} -- | Defines an Postgresql event store. module Eventful.Store.Postgresql ( postgresqlEventStoreWriter , module Eventful.Store.Class , module Eventful.Store.Sql ) where import Control.Monad.Reader import Data.Monoid ((<>)) import Data.Text (Text) import Database.Persist import Database.Persist.Sql import Eventful.Store.Class import Eventful.Store.Sql -- | An 'EventStore' that uses a PostgreSQL database as a backend. Use -- 'SqlEventStoreConfig' to configure this event store. postgresqlEventStoreWriter :: (MonadIO m, PersistEntity entity, PersistEntityBackend entity ~ SqlBackend) => SqlEventStoreConfig entity serialized -> VersionedEventStoreWriter (SqlPersistT m) serialized postgresqlEventStoreWriter config = EventStoreWriter $ transactionalExpectedWriteHelper getLatestVersion storeEvents' where getLatestVersion = sqlMaxEventVersion config maxPostgresVersionSql storeEvents' = sqlStoreEvents config (Just tableLockFunc) maxPostgresVersionSql maxPostgresVersionSql :: DBName -> DBName -> DBName -> Text maxPostgresVersionSql (DBName tableName) (DBName uuidFieldName) (DBName versionFieldName) = "SELECT COALESCE(MAX(" <> versionFieldName <> "), -1) FROM " <> tableName <> " WHERE " <> uuidFieldName <> " = ?" -- | We need to lock the events table or else our global sequence number might -- not be monotonically increasing over time from the point of view of a -- reader. -- -- For example, say transaction A begins to write an event and the -- auto-increment key is 1. Then, transaction B starts to insert an event and -- gets an id of 2. If transaction B is quick and completes, then a listener -- might see the event from B and thinks it has all the events up to a sequence -- number of 2. However, once A finishes and the event with the id of 1 is -- done, then the listener won't know that event exists. tableLockFunc :: Text -> Text tableLockFunc tableName = "LOCK " <> tableName <> " IN EXCLUSIVE MODE"
jdreaver/eventful
eventful-postgresql/src/Eventful/Store/Postgresql.hs
mit
2,018
0
10
312
286
163
123
25
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.MediaError (pattern MEDIA_ERR_ABORTED, pattern MEDIA_ERR_NETWORK, pattern MEDIA_ERR_DECODE, pattern MEDIA_ERR_SRC_NOT_SUPPORTED, pattern MEDIA_ERR_ENCRYPTED, js_getCode, getCode, MediaError, castToMediaError, gTypeMediaError) 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 pattern MEDIA_ERR_ABORTED = 1 pattern MEDIA_ERR_NETWORK = 2 pattern MEDIA_ERR_DECODE = 3 pattern MEDIA_ERR_SRC_NOT_SUPPORTED = 4 pattern MEDIA_ERR_ENCRYPTED = 5 foreign import javascript unsafe "$1[\"code\"]" js_getCode :: MediaError -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaError.code Mozilla MediaError.code documentation> getCode :: (MonadIO m) => MediaError -> m Word getCode self = liftIO (js_getCode (self))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MediaError.hs
mit
1,580
6
8
193
417
261
156
29
1
import GHC.RTS.Events analyze path analysis = do logread <- readEventLogFromFile path print (do log <- logread return $ analysis log) isTrace (Event t i) = case i of (UserMessage x) -> True _ -> False dfilter f = foldr ((++) . rfilter) [] where rfilter e@(Event _ i) = case i of (EventBlock _ _ es) -> dfilter f es _ | f e -> [e] otherwise -> [] listTraces = (dfilter isTrace) . events . dat matchingMsg m = (filter mtch) . listTraces where mtch (Event t ei) = msg ei == m
patrickboe/artery
Analysis/Trace.hs
mit
603
0
13
224
249
122
127
17
3
module Rebase.Data.Text.IO ( module Data.Text.IO ) where import Data.Text.IO
nikita-volkov/rebase
library/Rebase/Data/Text/IO.hs
mit
80
0
5
12
23
16
7
4
0
module Eval where import Control.Monad.Error import Types eval :: LispVal -> ThrowsError LispVal eval val@(String _) = return val eval val@(Char _) = return val eval val@(Number _) = return val eval val@(Float _) = return val eval val@(Bool _) = return val eval (List [Atom "quote", val]) = return val eval (List (Atom func : args)) = mapM eval args >>= apply func eval badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm apply :: String -> [LispVal] -> ThrowsError LispVal apply func args = maybe (throwError $ NotFunction "Unrecognized primitive function args" func) ($ args) (lookup func primitives) primitives :: [(String, [LispVal] -> ThrowsError LispVal)] primitives = [("+", numericBinop (+)) ,("-", numericBinop (-)) ,("*", numericBinop (*)) ,("/", numericBinop div) ,("mod", numericBinop mod) ,("quotient", numericBinop quot) ,("remainder", numericBinop rem) ,("symbol?", return . Bool . isSymbol . head) ,("string?", return . Bool . isString . head) ,("number?", return . Bool . isNumber . head) ] numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op unpackNum :: LispVal -> ThrowsError Integer unpackNum (Number n) = return n unpackNum (Float f) = return $ round f unpackNum (String n) = let parsed = reads n in if null parsed then throwError $ TypeMismatch "number" $ String n else return $ fst $ head parsed unpackNum (List [n]) = unpackNum n unpackNum notNum = throwError $ TypeMismatch "number" notNum isSymbol :: LispVal -> Bool isSymbol (Atom _) = True isSymbol _ = False isString :: LispVal -> Bool isString (String _) = True isString _ = False isNumber :: LispVal -> Bool isNumber (Number _) = True isNumber (Float _) = True isNumber _ = False
dstruthers/WYAS
Eval.hs
mit
2,148
0
10
587
789
412
377
49
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ConstraintKinds #-} module App where import BasePrelude hiding (first) import Control.Lens import Control.Monad.Except (ExceptT, MonadError (..), runExceptT) import Control.Monad.Reader (MonadReader, ReaderT, runReaderT) import Control.Monad.Trans (MonadIO, liftIO) import Data.Bifunctor (first) import Csv import Db import Utils data AppEnv = AppEnv { _appEnvDb :: DbEnv } makeClassy ''AppEnv data AppError = AppCsvError CsvError | AppDbError DbError makeClassyPrisms ''AppError instance AsDbError AppError where _DbError = _AppDbError . _DbError instance AsCsvError AppError where _CsvError = _AppCsvError . _CsvError instance HasDbEnv AppEnv where dbEnv = appEnvDb . dbEnv type CanApp c e m = ( CanDb c e m , CanCsv e m , AsAppError e , HasAppEnv c ) loadAndInsert :: CanApp c e m => FilePath -> m [Int] loadAndInsert p = do xacts <- readTransactions p insertTransactions xacts
benkolera/talk-stacking-your-monads
code-classy/src/App.hs
mit
1,163
0
8
232
280
159
121
35
1
{-# LANGUAGE OverloadedStrings #-} module Jolly.Parser ( runParseModule ) where import qualified Data.Text.Lazy as TL import Text.Megaparsec import Text.Megaparsec.Char import qualified Text.Megaparsec.Char.Lexer as L import Text.Megaparsec.Expr import Jolly.Syntax type Parser = Parsec Decl TL.Text -- Lexer helpers {-# INLINE sc #-} sc :: Parser () sc = L.space space1 lineCmnt blockCmnt where lineCmnt = L.skipLineComment "--" blockCmnt = L.skipBlockComment "{-" "-}" {-# INLINE lexeme #-} lexeme :: Parser a -> Parser a lexeme = L.lexeme sc {-# INLINE symbol #-} symbol :: TL.Text -> Parser TL.Text symbol = L.symbol sc -- Combinators {-# INLINE parens #-} parens :: Parser a -> Parser a parens = between (symbol "(") (symbol ")") -- Primative data types {-# INLINE integer #-} integer :: Parser Int integer = lexeme L.decimal {-# INLINE boolean #-} boolean :: Parser Bool boolean = True <$ reserved "True" <|> False <$ reserved "False" -- Reserved tokens and identifiers {-# INLINE reserved #-} reserved :: TL.Text -> Parser () reserved w = string w *> notFollowedBy alphaNumChar *> sc {-# INLINE rws #-} rws :: [String] rws = ["True", "False", "let"] {-# INLINE identifier #-} identifier :: Parser Name identifier = (lexeme . try) (p >>= check) where p = (:) <$> letterChar <*> many alphaNumChar check x = if x `elem` rws then fail $ "keyword " ++ show x ++ " cannot be an identifier" else return x -- Expressions expr :: Parser Expr expr = makeExprParser term operators operators :: [[Operator Parser Expr]] operators = [ [InfixL (Op Mul <$ symbol "*")] , [InfixL (Op Add <$ symbol "+")] , [InfixL (Op Sub <$ symbol "-")] , [InfixL (Op Eql <$ symbol "==")] ] lambda :: Parser Expr lambda = do symbol "\\" arg <- identifier symbol "->" body <- expr return $ Lam arg body term :: Parser Expr term = aexp >>= \x -> (some aexp >>= \xs -> return (foldl App x xs)) <|> return x aexp :: Parser Expr aexp = parens expr <|> Var <$> identifier <|> lambda <|> Lit . LInt <$> integer <|> Lit . LBool <$> boolean type Binding = (String, Expr) signature :: Parser (Name, [Name], Expr) signature = do name <- identifier args <- many identifier symbol "=" body <- expr return (name, args, body) letdecl :: Parser Binding letdecl = do reserved "let" (name, args, body) <- signature return (name, foldr Lam body args) letrecdecl :: Parser Binding letrecdecl = do reserved "let" reserved "rec" (name, args, body) <- signature return (name, Fix $ foldr Lam body (name : args)) val :: Parser Binding val = do ex <- expr return ("it", ex) decl :: Parser Binding decl = try letrecdecl <|> letdecl <|> val top :: Parser Binding top = do x <- decl optional (symbol ";") return x modl :: Parser [Binding] modl = many top runParseModule :: String -> TL.Text -> Either (ParseError (Token TL.Text) Decl) [Binding] runParseModule = runParser modl
jchildren/jolly
src/Jolly/Parser.hs
mit
3,014
0
14
679
1,069
555
514
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} module Chapter14 where import Chapter8 (recMul) import Control.Monad (mapM_, return) import Data.Bool (Bool(False, True), (&&), (||)) import Data.Char (toUpper) import Data.Eq (Eq, (==), (/=)) import Data.Foldable (concat, foldr) import Data.Function (id) import Data.Functor (fmap) import Data.Int (Int) import Data.List ((++), length, reverse, sort, take) import Data.Maybe (Maybe(Nothing, Just)) import Data.Ord (Ord, (>=)) import Data.String (String) import Data.Tuple (snd) import Prelude (Double, Fractional, Integer, Num, (.), ($), (^), (*), (/), (+), div, mod, quot, rem) import System.IO (IO) import Test.Hspec (describe, hspec, it, shouldBe) import Test.QuickCheck (Arbitrary, Gen, Property, arbitrary, elements, forAll, frequency, maxSuccess, quickCheck, quickCheckWith, stdArgs, suchThat, verboseCheck) import Text.Read (read) import Text.Show (Show, show) import WordNumber (digits, digitToWord, wordNumber) --deepCheck = quickCheckWith (stdArgs {maxSuccess = 1000}) {- Intermission: Short Exercise In the Chapter Exercises at the end of Recursion, you were given this exercise: Write a function that multiplies two numbers using recursive sum- mation. The type should be (Eq a, Num a) => a -> a -> a although, depending on how you do it, you might also consider adding an Ord constraint. If you still have your answer, great! If not, rewrite it and then write Hspec tests for it. The above examples demonstrate the basics of writing individual tests to test particular values. If you’d like to see a more developed example, you could refer to Chris’s library, Bloodhound. 3 -} testRecMul :: IO () testRecMul = hspec $ describe "recMul" $ do it "recMul 5 1 is 5" $ recMul 5 1 `shouldBe` 5 it "recMul 5 4 is 20" $ recMul 5 4 `shouldBe` 20 {- Chapter Exercises Now it’s time to write some tests of your own. You could write tests for most of the exercises you’ve done in the book, but whether you’d want to use Hspec or QuickCheck depends on what you’re trying to test. We’ve tried to simplify things a bit by telling you which to use for these exercises, but, as always, we encourage you to experiment on your own. Validating numbers into words Remember the “numbers into words” exercise in Recursion? You’ll be writing tests to validate the functions you wrote. main :: IO () main = hspec $ do describe "digitToWord does what we want" $ do it "returns zero for 0" $ do digitToWord 0 `shouldBe` "zero" it "returns one for 1" $ do print "???" describe "digits does what we want" $ do it "returns [1] for 1" $ do digits 1 `shouldBe` [1] it "returns [1, 0, 0] for 100" $ do print "???" describe "wordNumber does what we want" $ do it "returns one-zero-zero for 100" $ do wordNumber 100 `shouldBe` "one-zero-zero" it "returns nine-zero-zero-one for 9001" $ do print "???" Fill in the test cases that print question marks. If you think of additional tests you could perform, add them. -} testHspec :: IO () testHspec = hspec $ do describe "digitToWord does what we want" $ do it "returns zero for 0" $ digitToWord 0 `shouldBe` "zero" it "returns one for 1" $ digitToWord 1 `shouldBe` "one" it "returns two for 2" $ digitToWord 2 `shouldBe` "two" it "returns three for 3" $ digitToWord 3 `shouldBe` "three" it "returns four for 4" $ digitToWord 4 `shouldBe` "four" it "returns five for 5" $ digitToWord 5 `shouldBe` "five" it "returns six for 6" $ digitToWord 6 `shouldBe` "six" it "returns seven for 7" $ digitToWord 7 `shouldBe` "seven" it "returns eight for 8" $ digitToWord 8 `shouldBe` "eight" it "returns nine for 9" $ digitToWord 9 `shouldBe` "nine" describe "digits does what we want" $ do it "returns [1] for 1" $ digits 1 `shouldBe` [1] it "returns [1, 0, 0] for 100" $ digits 100 `shouldBe` [1, 0, 0] it "returns [1, 2, 3] for 123" $ digits 123 `shouldBe` [1, 2, 3] describe "wordNumber does what we want" $ do it "returns one-zero-zero for 100" $ wordNumber 100 `shouldBe` "one-zero-zero" it "returns nine-zero-zero-one for 9001" $ wordNumber 9001 `shouldBe` "nine-zero-zero-one" it "returns one for 1" $ wordNumber 1 `shouldBe` "one" {- Using QuickCheck Test some simple arithmetic properties using QuickCheck. 1. -- for a function half x = x / 2 -- this property should hold halfIdentity = (*2) . half -} half :: Fractional a => a -> a half x = x / 2 genDouble :: Gen Double genDouble = arbitrary propHalfIdentity :: Property propHalfIdentity = forAll gen prop where gen = genDouble prop x = x == ((* 2) . half) x propHalfEqualToPointFive :: Property propHalfEqualToPointFive = forAll gen prop where gen = genDouble prop x = (x * 0.5) == half x propHalfOneFourth :: Property propHalfOneFourth = forAll gen prop where gen = genDouble prop x = (x * 0.25) == half (half x) testPropsHalf :: IO () testPropsHalf = mapM_ quickCheck [ propHalfIdentity , propHalfEqualToPointFive , propHalfOneFourth ] {- 2. import Data.List (sort) -- for any list you apply sort to -- this property should hold listOrdered :: (Ord a) => [a] -> Bool listOrdered xs = snd $ foldr go (Nothing, True) xs where go _ status@(_, False) = status go y (Nothing, t) = (Just y, t) go y (Just x, t) = (Just y, x >= y) -} listOrdered :: (Ord a) => [a] -> Bool listOrdered xs = snd $ foldr go (Nothing, True) xs where go _ status@(_, False) = status go y (Nothing, t) = (Just y, t) go y (Just x, _) = (Just y, x >= y) genIntList :: Gen [Int] genIntList = arbitrary genIntegerList :: Gen [Integer] genIntegerList = arbitrary genString :: Gen String genString = arbitrary propOrdered :: (Arbitrary a, Ord a, Show a) => Gen [a] -> Property propOrdered gen = forAll gen prop where prop xs = listOrdered $ sort xs testPropOrdered :: IO () testPropOrdered = mapM_ quickCheck [ propOrdered genIntList , propOrdered genIntegerList , propOrdered genString ] {- 3. Now we’ll test the associative and commutative properties of addition: plusAssociative x y z = x + (y + z) == (x + y) + z plusCommutative x y = x + y == y + x -} plusAssociative :: (Eq a, Num a) => a -> a -> a -> Bool plusAssociative x y z = x + (y + z) == (x + y) + z plusCommutative :: (Eq a, Num a) => a -> a -> Bool plusCommutative x y = x + y == y + x gen3Nums :: (Arbitrary a, Num a) => Gen (a, a, a) gen3Nums = do x <- arbitrary y <- arbitrary z <- arbitrary return (x, y, z) gen2Nums :: (Arbitrary a, Num a) => Gen (a, a) gen2Nums = do x <- arbitrary y <- arbitrary return (x, y) gen3Ints :: Gen (Int, Int, Int) gen3Ints = gen3Nums gen2Ints :: Gen (Int, Int) gen2Ints = gen2Nums propPlusAssociative :: Property propPlusAssociative = forAll gen prop where gen = gen3Ints prop (x, y, z) = plusAssociative x y z propPlusCommutative :: Property propPlusCommutative = forAll gen prop where gen = gen2Ints prop (x, y) = plusCommutative x y testAdditionProps :: IO () testAdditionProps = mapM_ quickCheck [ propPlusAssociative , propPlusCommutative ] {- 4. Now do the same for multiplication. -} multAssociative :: (Eq a, Num a) => a -> a -> a -> Bool multAssociative x y z = x + (y + z) == (x + y) + z multCommutative :: (Eq a, Num a) => a -> a -> Bool multCommutative x y = x + y == y + x propMultAssociative :: Property propMultAssociative = forAll gen prop where gen = gen3Ints prop (x, y, z) = multAssociative x y z propMultCommutative :: Property propMultCommutative = forAll gen prop where gen = gen2Ints prop (x, y) = multCommutative x y testMultProps :: IO () testMultProps = mapM_ quickCheck [propMultAssociative, propMultCommutative] {- 5. We mentioned in one of the first chapters that there are some laws involving the relationship of quot and rem and div and mod. Write QuickCheck tests to prove them. -- quot rem (quot x y) * y + (rem x y) == x (div x y) * y + (mod x y) == x -} genInt :: Gen Int genInt = arbitrary genIntGteOne :: Gen Int genIntGteOne = genInt `suchThat` (>= 1) genNoLessThanOneInt :: Gen (Int, Int) genNoLessThanOneInt = do x <- genIntGteOne y <- genIntGteOne return (x, y) propQuotRem :: Property propQuotRem = forAll gen prop where gen = genNoLessThanOneInt prop (x, y) = quot x y * y + rem x y == x propDivMod :: Property propDivMod = forAll gen prop where gen = genNoLessThanOneInt prop (x, y) = div x y * y + mod x y == x testPropQuotRemDivMod :: IO () testPropQuotRemDivMod = mapM_ quickCheck [ propQuotRem , propDivMod ] {- 6. Is (^) associative? Is it commutative? Use QuickCheck to see if the computer can contradict such an assertion. -} propExpAssociative :: Property propExpAssociative = forAll gen prop where gen = do x <- genInt y <- genIntGteOne z <- genIntGteOne return (x, y, z) prop (x, y, z) = x ^ (y ^ z) == (x ^ y) ^ z || x ^ (y ^ z) /= (x ^ y) ^ z propExpCommutative :: Property propExpCommutative = forAll gen prop where gen = do x <- genIntGteOne y <- genIntGteOne return (x, y) prop (x, y) = x ^ y == y ^ x || x ^ y /= y ^ x testPropExp :: IO () testPropExp = mapM_ verboseCheck [ propExpAssociative , propExpCommutative ] {- 7. Test that reversing a list twice is the same as the identity of the list: reverse . reverse == id -} propReverseIdentity :: Property propReverseIdentity = forAll gen prop where gen = genIntList prop xs = (reverse . reverse) xs == id xs testPropReverse :: IO () testPropReverse = mapM_ quickCheck [propReverseIdentity] {- 8. Write a property for the definition of ($) and (.). f $ a = f a f . g = \x -> f (g x) -} propApplyIdentity :: Property propApplyIdentity = forAll gen prop where gen = genInt prop x = id $ x == id x propComposeIdentity :: Property propComposeIdentity = forAll gen prop where gen = genInt prop x = (id . id) x == id (id x) testPropApplyAndCompose :: IO () testPropApplyAndCompose = mapM_ quickCheck [ propApplyIdentity , propComposeIdentity ] {- 9. See if these two functions are equal: foldr (:) == (++) foldr (++) [] == concat -} genListIntsInts :: Gen [[Int]] genListIntsInts = arbitrary genListInts :: Gen [Int] genListInts = arbitrary propFoldrEqual :: Property propFoldrEqual = forAll gen prop where gen = do xs <- genListIntsInts ys <- genListInts zs <- genListInts return (xs, ys, zs) prop (xs, ys, zs) = foldr (++) [] xs == concat xs && foldr (:) ys zs == ys ++ zs {- 10. Hm. Is that so? f n xs = length (take n xs) == n -} propLengthTake :: Property propLengthTake = forAll gen prop where gen = do n <- genInt xs <- genListInts return (n, xs) prop (n, xs) = length (take n xs) == n testPropLengthTake :: IO () testPropLengthTake = quickCheck propLengthTake {- 11. Finally, this is a fun one. You may remember we had you com- pose read and show one time to complete a “round trip.” Well, now you can test that it works: f x = (read (show x)) == x -} propReadShow :: Property propReadShow = forAll gen prop where gen = genInt prop n = read (show n) == n {- Failure Find out why this property fails. -- for a function square x = x * x -- why does this property not hold? Examine the type of sqrt. squareIdentity = square . sqrt Hint: Read about floating point arithmetic and precision if you’re unfamiliar with it. => because of high precision and the large number of decimal places Idempotence Idempotence refers to a property of some functions in which the result value does not change beyond the initial application. If you apply the function once, it returns a result, and applying the same function to that value won’t ever change it. You might think of a list that you sort: once you sort it, the sorted list will remain the same after applying the same sorting function to it. It’s already sorted, so new applications of the sort function won’t change it. Use QuickCheck and the following helper functions to demon- strate idempotence for the following: -} twice :: (a -> a) -> (a -> a) twice f = f . f fourTimes :: (a -> a) -> (a -> a) fourTimes = twice . twice {- 1. f x = capitalizeWord x == twice capitalizeWord x == fourTimes capitalizeWord x -} capitalize :: String -> String capitalize = fmap toUpper propCapitalizeIdempotence :: Property propCapitalizeIdempotence = forAll gen prop where gen = arbitrary :: Gen String prop s = c1 s && c2 s && c3 s c1 s = capitalize s == twice capitalize s c2 s = capitalize s == fourTimes capitalize s c3 s = twice capitalize s == fourTimes capitalize s {- 2. f x = sort x == twice sort x == fourTimes sort x -} propSortIdempotence :: Property propSortIdempotence = forAll gen prop where gen = arbitrary :: Gen String prop s = c1 s && c2 s && c3 s c1 s = sort s == twice sort s c2 s = sort s == fourTimes sort s c3 s = twice sort s == fourTimes sort s testPropTwice :: IO () testPropTwice = mapM_ verboseCheck [ propCapitalizeIdempotence , propSortIdempotence ] {- Make a Gen random generator for the datatype We demonstrated in the chapter how to make Gen generators for different datatypes. We are so certain you enjoyed that, we are going to ask you to do it for some new datatypes: 1. Equal probabilities for each. data Fool = Fulse | Frue deriving (Eq, Show) -} data Fool = Fulse | Frue deriving (Eq, Show) instance Arbitrary Fool where arbitrary = elements [Fulse, Frue] {- 2. 2/3s chance of Fulse, 1/3 chance of Frue. data Fool = Fulse | Frue deriving (Eq, Show) -} data Fool' = Fulse' | Frue' deriving (Eq, Show) instance Arbitrary Fool' where arbitrary = frequency [(2, return Fulse'), (1, return Frue')] {- Hangman testing Next, you should go back to the Hangman project from the pre- vious chapter and write tests. The kinds of tests you can write at this point will be limited due to the interactive nature of the game. However, you can test the functions. Focus your attention on testing the following: fillInCharacter :: Puzzle -> Char -> Puzzle fillInCharacter (Puzzle word filledInSoFar s) c = Puzzle word newFilledInSoFar (c : s) where zipper guessed wordChar guessChar = if wordChar == guessed then Just wordChar else guessChar newFilledInSoFar = zipWith (zipper c) word filledInSoFar and: handleGuess :: Puzzle -> Char -> IO Puzzle handleGuess puzzle guess = do putStrLn $ "Your guess was: " ++ [guess] case (charInWord puzzle guess, alreadyGuessed puzzle guess) of (_, True) -> do putStrLn "You already guessed that character, pick something else!" return puzzle (True, _) -> do putStrLn "This character was in the word, filling in the word accordingly" return (fillInCharacter puzzle guess) (False, _) -> do putStrLn "This character wasn't in the word, try again." return (fillInCharacter puzzle guess) Refresh your memory on what those are supposed to do and then test to make sure they do. -}
Numberartificial/workflow
haskell-first-principles/haskell-programming-from-first-principles-master/src/Chapter14.hs
mit
16,922
2
15
5,124
3,349
1,796
1,553
255
3
---------------------------------------------------- -- -- -- HyLoRes.Formula: -- -- Formula data type -- -- -- ---------------------------------------------------- {- Copyright (C) HyLoRes 2002-2007 - See AUTHORS file This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -} module HyLoRes.Formula( -- Signature Signature, NomSym, RelSym(..), PropSym(..), -- nominals NomId, spyU, evalPoint, inputNom, toNom, var, isVar, level, isSkolemNom, isInputNom, onInvToNom, nomId, varId, -- relation symbols invRel, -- Formula types Formula, AtFormula, Top, Prop, Nom, Neg, Conj, Disj, Diam, Box, At, Down, Opaque, -- formula construction nnfAtFormula, top, prop, nom, at, down, diam, box, neg, takeConj, takeDisj, opaque, asAtOpaque, replaceNom, killNom, instanceFreeVar, -- formula manipulation label, boundVar, subf, onSubf, subfs, relSym, symbol, unNNF, containsNom, flatten, specialize, -- Other HashOrd(..), CachedHash, cacheHash, fromCachedHash, -- Unit tests unit_tests ) where import Test.QuickCheck ( Arbitrary(..), Gen, Property, forAll, oneof, variant, sized, resize ) import Test.QuickCheck.Utils ( isTotalOrder ) import HyLo.Test ( UnitTest, runTest ) import Control.Monad ( liftM ) import Data.List ( sort, foldl1' ) import Data.Maybe ( mapMaybe, fromMaybe ) import Data.Set ( Set ) import qualified Data.Set as Set import Data.Hash import HyLoRes.Util.Ordering ( metap_trichotomy, metap_irreflexive, metap_antisymmetric, metap_transitive ) import qualified HyLo.Formula as F import HyLoRes.Formula.Internal hiding ( nnfAtFormula, unit_tests ) import qualified HyLoRes.Formula.Internal as I import HyLoRes.Formula.TypeLevel ( Top, Prop, Nom, Neg, Disj, Conj, Diam, Box, At, Down, Opaque, Specializable(..), Spec(..) ) import qualified HyLo.Signature as S import HyLo.Signature ( HasSignature(..), nomSymbols, merge, IsRelSym(..) ) import Text.Read ( Read(..) ) import qualified Text.ParserCombinators.ReadPrec as P ( lift ) import Text.ParserCombinators.ReadPrec ( get, choice ) import Text.ParserCombinators.ReadP ( string ) -- =============================== Signature ============================ -- -- (this ought to be in a separate module, but ghc's -- support for mutually recursive modules is quite poor) type Signature = S.Signature NomSym PropSym RelSym newtype PropSym = P Int deriving (Eq, Ord, Arbitrary) instance Show PropSym where show (P p) = 'P' : show p instance Read PropSym where readPrec = do 'P' <- get; P `liftM` readPrec instance Hashable PropSym where hash (P p) = hash p -- the order of the constructors guarantee -- Univ < Rel _ < RelInv _ data RelSym = Univ | Rel Int | RelInv Int deriving (Eq, Ord) instance Show RelSym where show (Rel r) = 'R' : show r show (RelInv r) = '-' : show (Rel r) show Univ = "U" instance Read RelSym where readPrec = choice [do 'R' <- get; Rel `liftM` readPrec, do '-' <- get; Rel r <- readPrec; return $ RelInv r, do 'U' <- get; return Univ] instance IsRelSym RelSym where invRel (Rel r) = Just (RelInv r) invRel (RelInv r) = Just (Rel r) invRel Univ = Nothing instance Hashable RelSym where hash (Rel r) = hash 'R' `combine` hash r hash (RelInv r) = hash 'r' `combine` hash r hash Univ = hash 'U' {- Nominals are split in "Input-Nominals" (N_i) and "Calculus-Nominals" (N_c) -} type Level = Int newtype NomId = NomId Int deriving(Eq, Ord, Show, Read, Enum, Num, Real, Integral, Hashable, Arbitrary) data NomSym = NspyU | Neval | Ni NomId | Nc Level (Formula (At (Diam Opaque))) | X NomId deriving (Eq) instance Ord NomSym where -- In order to guarantee termination, we must check that deeper nominals -- are always the greatest in the order. On the other hand, if we have -- two nominals on the same level, the greatest must be the one whose -- associated formula is the greatest (this is to guarantee i > j iff -- tonom(@_i<r>A) > tonom(@_j<r>A)) -- NspyU and Neval are given a low precedence with no real good reason compare NspyU NspyU = EQ compare NspyU _ = LT -- compare Neval Neval = EQ compare Neval NspyU = GT compare Neval _ = LT -- compare (Ni id1) (Ni id2) = compare id1 id2 compare (Ni _) (Nc _ _) = LT compare (Ni _) (X _) = LT compare (Ni _) _ = GT -- compare (Nc l1 f1) (Nc l2 f2) = case compare l1 l2 of EQ -> compare f1 f2 neq -> neq compare (Nc _ _) (X _) = LT compare (Nc _ _) _ = GT -- compare (X x) (X y) = compare x y compare (X _) _ = GT instance Show NomSym where showsPrec _ NspyU = showString "N_spy" showsPrec _ Neval = showString "N_eval" showsPrec _ (Ni (NomId i)) = showChar 'N' . shows i showsPrec _ (Nc l f) = showString "N_{" . shows l . showString ", " . shows f . showChar '}' showsPrec _ (X (NomId x)) = showChar 'X' . shows x instance Read NomSym where readPrec = choice [ do P.lift (string "N_spy"); return NspyU, -- do P.lift (string "N_eval"); return Neval, -- do 'N' <- get; (Ni . NomId) `liftM` readPrec, -- do P.lift (string "N_{") l <- readPrec; P.lift (string ", ") f <- asAtDiamF =<< readPrec '}' <- get return $ Nc l f, -- do 'X' <- get; (X . NomId) `liftM` readPrec ] instance Hashable NomSym where hash NspyU = hash 's' hash Neval = hash 'e' hash (Ni i) = hash 'i' `combine` hash i hash (Nc _ f) = hash 'c' `combine` hash f hash (X i) = hash 'x' `combine` hash i asAtDiamF :: Monad m => Formula Opaque -> m (Formula (At (Diam Opaque))) asAtDiamF (Opaque (At _ _ (Diam _ _ Nom{}))) = fail "Is a rel" asAtDiamF (Opaque f@(At _ _ Diam{})) = return$onSubf (onSubf opaque) f asAtDiamF _ = fail "Not an AtNomDiam formula" spyU :: NomSym spyU = NspyU evalPoint :: NomSym evalPoint = Neval inputNom :: NomId -> NomSym inputNom = Ni var :: NomId -> NomSym var = X isSkolemNom :: NomSym -> Bool isSkolemNom (Nc _ _) = True isSkolemNom _ = False isInputNom :: NomSym -> Bool isInputNom (Ni _) = True isInputNom _ = False nomId :: NomSym -> Maybe NomId nomId (Ni i) = Just i nomId _ = Nothing isVar :: NomSym -> Bool isVar (X _) = True isVar _ = False varId :: NomSym -> Maybe NomId varId (X x ) = Just x varId _ = Nothing level :: NomSym -> Level level NspyU = 0 level Neval = 0 level (Ni _) = 0 level (Nc l _) = l level (X _) = 0 toNom :: Formula (At (Diam f)) -> NomSym toNom f = Nc (succ . level . label $ f) (onSubf (onSubf opaque) f) onInvToNom :: NomSym -> (forall f . Formula (At (Diam f)) -> r) -> Maybe r onInvToNom (Nc _ f) g = Just $ g f onInvToNom _ _ = Nothing -- ============================== Formula ================================== -- type Formula f = Form NomSym PropSym RelSym Cached f data Cached = Cached { _phi :: Int, _hash :: Hash, _nomHashes :: Set Hash } instance Attrib Cached NomSym PropSym RelSym where computeAttrib f = Cached { _phi = computePhi f, _hash = computeHash f, _nomHashes = computeNomHashes f } nnfAtFormula :: F.Formula NomSym PropSym RelSym -> Formula (At Opaque) nnfAtFormula = I.nnfAtFormula evalPoint type AtFormula = Formula (At Opaque) asAtOpaque :: Formula (At f) -> AtFormula asAtOpaque = onSubf opaque instance Eq (Formula f) where f == g = (hash f == hash g) && (eqUnNNF f g) instance HasSignature (Formula f) where type NomsOf (Formula f) = NomSym type PropsOf (Formula f) = PropSym type RelsOf (Formula f) = RelSym getSignature f = foldl1' merge (sig_f:sig_sk_noms) where sig_f = getSignature $ unNNF f sig_sk_noms = mapMaybe skNomSig . Set.toList . nomSymbols $ sig_f skNomSig (Nc _ f') = Just (getSignature f') skNomSig _ = Nothing killNom :: NomSym -> NomSym -> Formula f -> Formula f killNom i i' f = mapSig killIt id id f where killIt j | j == i = i' killIt (Nc _ f') = toNom (killNom i i' f') killIt j = j -- =============== Public constructors for formulas ================= -- -- disjunctions and conjunctions are sorted to obtain a normal representation takeDisj :: [Formula f] -> Formula Disj takeDisj f@(_:_:_) = disj $ sort f takeDisj _ = error "takeDisj: not enough disjuncts" takeConj :: [Formula f] -> Formula Conj takeConj f@(_:_:_) = conj $ sort f takeConj _ = error "takeConj: not enough conjuncts" -- ================== Admissible ordering ============ args :: Formula a -> [Formula Opaque] args = nonOpaque args' where args' :: Formula f -> [Formula Opaque] args' Top{} = [] args' Nom{} = [] args' Prop{} = [] -- args' NegTop{} = [opaque top] args' a@NegNom{} = [opaque $ subf a] args' a@NegProp{} = [opaque $ subf a] -- -- observe that when turning @_aF to a term structure, -- the nominal (or var) must be the second argument args' f@Conj{} = map opaque (subfs f) args' f@Disj{} = map opaque (subfs f) -- args' f@At{} = [opaque (subf f), opaque $ nom (label f)] -- args' f@Down{} = [opaque $ nom (boundVar f), opaque (subf f)] -- args' f@Box{} = [opaque $ subf f] args' f@Diam{} = [opaque $ subf f] -- args' (Opaque _) = error "args': opaque!" instance Ord (Formula f) where compare f1 f2 = compareF f1 f2 compareF :: Formula f -> Formula g -> Ordering compareF = cmp_kbo cmp_kbo :: Formula a -> Formula b -> Ordering cmp_kbo f1 f2 = nonOpaque2 (\f g -> snd $ kbo f g 0) f1 f2 kbo :: Formula a -> Formula b -> Int -> (Int, Ordering) kbo s t wb_i = case compare wb_f 0 of EQ -> case cmp_head of EQ -> (wb_f, lex_res) res -> (wb_f, res) res -> (wb_f, res) where cmp_head = compareHead s t (wb_f, lex_res) = if cmp_head == EQ then let (wb_s, res) = kbolex s t wb_i in (wb_s + weightHead s - weightHead t, res) else (wb_i + phi s - phi t, error $ "lex_res shouldn't be used! ") kbolex :: Formula a -> Formula b -> Int -> (Int, Ordering) kbolex = nonOpaque2 kbolex' where kbolex' :: Formula a -> Formula b -> Int -> (Int, Ordering) kbolex' Top{} _ wb = (wb, EQ) kbolex' f@Nom{} g@Nom{} wb = (wb, compare (symbol f) (symbol g)) kbolex' f@Prop{} g@Prop{} wb = (wb, compare (symbol f) (symbol g)) -- kbolex' NegTop{} _ wb = (wb, EQ) kbolex' f@NegNom{} g@NegNom{} wb = (wb,compare (negSymbol f) (negSymbol g)) kbolex' f@NegProp{} g@NegProp{} wb = (wb,compare (negSymbol f) (negSymbol g)) -- kbolex' f@Conj{} g@Conj{} wb = kbolex_list (subfs f) (subfs g) wb kbolex' f@Disj{} g@Disj{} wb = kbolex_list (subfs f) (subfs g) wb -- -- observe that when turning @_aF to a term structure, -- the nominal (or var) must be the second argument kbolex' f@At{} g@At{} wb = case kbo (subf f) (subf g) wb of (wb',EQ) -> (wb',compare (label f) (label g)) res -> res -- kbolex' f@Down{} g@Down{} wb = case kbo (subf f) (subf g) wb of (wb',EQ) -> (wb',compare (boundVar f) (boundVar g)) res -> res -- kbolex' f@Box{} g@Box{} wb = kbo (subf f) (subf g) wb kbolex' f@Diam{} g@Diam{} wb = kbo (subf f) (subf g) wb -- kbolex' Opaque{} _ _ = error "kbolex': opaque l!" kbolex' _ Opaque{} _ = error "kbolex': opaque r!" -- kbolex' s t _ = error $ unlines ["kbolex' - non equal:", " s = " ++ show s, " t = " ++ show t] -- kbolex_list :: [Formula a]-> [Formula b]-> Int -> (Int,Ordering) kbolex_list [] [] wb = (wb, EQ) kbolex_list (f:fs) (g:gs) wb = case kbo f g wb of (wb', EQ) -> kbolex_list fs gs wb' (wb', res) -> (wb' + sum_phi fs - sum_phi gs,res) kbolex_list _ _ _ = error "kbolex_list: wrong arity" -- sum_phi :: [Formula a] -> Int sum_phi = sum . map phi phi :: Formula f -> Int phi = _phi . attrib computePhi :: Formula f -> Int computePhi = nonOpaque phi' where phi' :: Formula f -> Int phi' a@Top{} = weightHead a phi' a@Nom{} = weightHead a phi' a@Prop{} = weightHead a -- phi' a@NegTop{} = weightHead a phi' a@NegNom{} = weightHead a phi' a@NegProp{} = weightHead a -- phi' f@Conj{} = sum $ map phi (subfs f) phi' f@Disj{} = sum $ map phi (subfs f) -- phi' f@At{} = weightHead (nom $ label f) + phi (subf f) -- phi' f@Down{} = weightHead (nom $ boundVar f) + phi (subf f) -- phi' f@Box{} = weightHead f + phi (subf f) phi' f@Diam{} = weightHead f + phi (subf f) -- phi' (Opaque _) = error "phi: opaque!" compareHead :: Formula a -> Formula b -> Ordering compareHead = nonOpaque2 cmpHead where cmpHead :: Formula a -> Formula b -> Ordering cmpHead f@Nom{} g@Nom{} = compare (symbol f) (symbol g) cmpHead f@Prop{} g@Prop{} = compare (symbol f) (symbol g) -- cmpHead f@NegNom{} g@NegNom{} = compare(negSymbol f) (negSymbol g) cmpHead f@NegProp{} g@NegProp{} = compare(negSymbol f) (negSymbol g) -- cmpHead f@Diam{} g@Diam{} = compare (relSym f) (relSym g) cmpHead f@Box{} g@Box{} = compare (relSym f) (relSym g) -- cmpHead f@Conj{} g@Conj{} = cmpLen (subfs f) (subfs g) cmpHead f@Disj{} g@Disj{} = cmpLen (subfs f) (subfs g) -- cmpHead f g = case compare (weightHead f) (weightHead g) of EQ -> compare (linear f) (linear g) res -> res -- cmpLen :: [a] -> [a] -> Ordering cmpLen [] [] = EQ cmpLen [] _ = LT cmpLen _ [] = GT cmpLen (_:xs) (_:ys) = cmpLen xs ys -- linear :: Formula a -> Int linear Nom{} = 0 linear Top{} = 1 linear At{} = 2 linear Down{} = 5 linear Diam{} = 6 linear Box{} = 7 linear Prop{} = 8 linear Conj{} = 9 linear Disj{} = 10 linear NegNom{} = 11 linear NegTop{} = 12 linear NegProp{} = 14 linear Opaque{} = error "linear: opaque!" weightHead :: Formula f -> Int weightHead = nonOpaque weightHead' where {-# INLINE weightHead' #-} weightHead' :: Formula f -> Int -- all nominals weight the same, and less than the rest weightHead' Nom{} = 1 -- @ and top are unimportant, so they weight little weightHead' Top{} = 2 weightHead' At{} = 2 -- down weights little, so we try to postpone loop -- inducing formulas weightHead' Down{} = 2 -- weightHead' Diam{} = 4 -- boxes weight more than diamonds weightHead' Box{} = 5 -- we favor @ip over @i<>j, etc weightHead' Prop{} = 30 weightHead' f@Conj{} = 50 + length (subfs f) weightHead' f@Disj{} = 60 + length (subfs f) -- neg's like in @i-p, weight a lot, so we can favour resolution -- over other structural rules weightHead' NegNom{} = 201 weightHead' NegTop{} = 202 weightHead' NegProp{} = 230 weightHead' Opaque{} = error "weightHead': can't happen" instance Hashable (Formula f) where hash = _hash . attrib computeHash :: Formula f -> Hash computeHash Top{} = hash 'T' computeHash NegTop{} = hash 't' computeHash f@Nom{} = hash 'N' `combine` hash (symbol f) computeHash f@NegNom{} = hash 'n' `combine` hash (negSymbol f) computeHash f@Prop{} = hash 'P' `combine` hash (symbol f) computeHash f@NegProp{} = hash 'p' `combine` hash (negSymbol f) computeHash f@Conj{} = hash '&' `combine` hash (subfs f) computeHash f@Disj{} = hash '|' `combine` hash (subfs f) computeHash f@Diam{} = hash 'D' `combine` hash (relSym f) `combine` hash (subf f) computeHash f@Box{} = hash 'B' `combine` hash (relSym f) `combine` hash (subf f) computeHash f@At{} = hash '@' `combine` hash (label f) `combine` hash (subf f) computeHash f@Down{} = hash 'd' `combine` hash (boundVar f) `combine` hash (subf f) computeHash (Opaque f) = hash f newtype HashOrd a = HashOrd{fromHashOrd :: a} deriving ( Read, Show ) instance (Eq a, Hashable a) => Eq (HashOrd a) where (HashOrd a) == (HashOrd b) = hash a == hash b && a == b instance (Ord a, Hashable a) => Ord (HashOrd a) where compare (HashOrd a) (HashOrd b) = case compare (hash a) (hash b) of EQ -> compare a b res -> res data CachedHash a = CachedHash Hash a deriving ( Show ) cacheHash :: Hashable a => a -> CachedHash a cacheHash a = CachedHash (hash a) a fromCachedHash :: CachedHash a -> a fromCachedHash (CachedHash _ a) = a instance Hashable a => Hashable (CachedHash a) where hash (CachedHash h _) = h instance Eq a => Eq (CachedHash a) where (CachedHash _ l) == (CachedHash _ r) = l == r instance Ord a => Ord (CachedHash a) where compare (CachedHash _ l) (CachedHash _ r) = compare l r nomHashes :: Formula f -> Set Hash nomHashes = _nomHashes . attrib computeNomHashes :: Formula f -> Set Hash computeNomHashes form = comp form where comp :: Formula f -> Set Hash comp f@Nom{} = insertIfNotVar (symbol f) Set.empty comp f@NegNom{} = insertIfNotVar (negSymbol f) Set.empty comp f@At{} = insertIfNotVar (label f) (nomHashes $ subf f) comp f@Down{} = nomHashes $ subf f comp f@Box{} = nomHashes $ subf f comp f@Diam{} = nomHashes $ subf f comp f@Disj{} = foldl1' Set.union . map nomHashes $ subfs f comp f@Conj{} = foldl1' Set.union . map nomHashes $ subfs f comp (Opaque f) = nomHashes f comp _ = Set.empty -- insertIfNotVar n s | isVar n = s | otherwise = s `Set.union` (nomsIn n) nomsIn n = maybe (singleton n) (insert n) (onInvToNom n nomHashes) singleton = Set.singleton . hash insert = Set.insert . hash containsNom :: NomSym -> Formula f -> Bool containsNom i g = hash i `Set.member` nomHashes g && exactContainedIn g where exactContainedIn :: Formula f -> Bool exactContainedIn f@Nom{} = isHere (symbol f) exactContainedIn f@NegNom{} = isHere (negSymbol f) exactContainedIn f@At{} = isHere (label f) || containsNom i (subf f) exactContainedIn f@Down{} = containsNom i (subf f) exactContainedIn f@Box{} = containsNom i (subf f) exactContainedIn f@Diam{} = containsNom i (subf f) exactContainedIn f@Disj{} = any (containsNom i) (subfs f) exactContainedIn f@Conj{} = any (containsNom i) (subfs f) exactContainedIn (Opaque f) = exactContainedIn f exactContainedIn _ = False -- isHere n = i == n || fromMaybe False (onInvToNom n $ containsNom i) --------------------------------------- -- QuickCheck stuff -- --------------------------------------- instance Arbitrary RelSym where arbitrary = oneof [liftM Rel arbitrary, liftM RelInv arbitrary, return Univ] -- coarbitrary (Rel r) = variant 0 . coarbitrary r coarbitrary (RelInv r) = variant 1 . coarbitrary r coarbitrary Univ = variant 3 instance Arbitrary NomSym where arbitrary = sized arb where arb 0 = oneof [return NspyU, return Neval, liftM Ni arbitrary, liftM X arbitrary] arb n = oneof [return NspyU, return Neval, liftM Ni arbitrary, liftM X arbitrary, resize (n `div` 2) $ do a <- arbitrary let at_f = a :: AtFormula case specialize at_f of AtNom f -> mkNomC $ onSubf neg f _ -> mkNomC at_f ] -- coarbitrary NspyU = variant 0 . coarbitrary () coarbitrary Neval = variant 1 . coarbitrary () coarbitrary (Ni i) = variant 2 . coarbitrary i coarbitrary (Nc _ f) = variant 3 . coarbitrary (onSubf opaque f) coarbitrary (X x) = variant 4 . coarbitrary x mkNomC :: Formula (At f) -> Gen NomSym mkNomC f = do r <- arbitrary return (toNom $ onSubf (diam r) f) prop_read_PropSym :: PropSym -> Bool prop_read_PropSym p = p == (read . show $ p) prop_read_RelSym :: RelSym -> Bool prop_read_RelSym r = r == (read . show $ r) prop_read_NomSym :: NomSym -> Bool prop_read_NomSym i = i == (read . show $ i) prop_read_Opaque :: Formula Opaque -> Bool prop_read_Opaque f = f == (read . show $ f) prop_read_AtNomOpaque :: Formula (At Opaque) -> Bool prop_read_AtNomOpaque f = f == (read . show $ f) prop_ord_trichotomy_NomSym :: NomSym -> NomSym -> Bool prop_ord_trichotomy_NomSym = metap_trichotomy compare prop_ord_irreflexive_NomSym :: NomSym -> Bool prop_ord_irreflexive_NomSym = metap_irreflexive compare prop_ord_antisymmetric_NomSym :: NomSym -> NomSym -> Bool prop_ord_antisymmetric_NomSym = metap_antisymmetric compare prop_ord_transitive_NomSym :: NomSym -> NomSym -> NomSym -> Property prop_ord_transitive_NomSym = metap_transitive compare prop_ord_isTotalOrder_RelSym :: RelSym -> RelSym -> Property prop_ord_isTotalOrder_RelSym = isTotalOrder prop_ord_transitive_RelSym :: RelSym -> RelSym -> RelSym -> Property prop_ord_transitive_RelSym = metap_transitive compare prop_trichotomy_Opaque :: Formula Opaque -> Formula Opaque -> Bool prop_trichotomy_Opaque = metap_trichotomy compare prop_irreflexive_Opaque :: Formula Opaque -> Bool prop_irreflexive_Opaque = metap_irreflexive compare prop_antisymmetric_Opaque :: Formula Opaque -> Formula Opaque -> Bool prop_antisymmetric_Opaque = metap_antisymmetric compare prop_transitive_Opaque :: Formula Opaque -> Formula Opaque -> Formula Opaque -> Property prop_transitive_Opaque = metap_transitive compare prop_subformulaProperty :: Formula Opaque -> Bool prop_subformulaProperty f = all (f >) $ args f prop_rewriteOrd :: Int -> Formula Opaque -> Formula Opaque -> Formula Opaque -> Bool prop_rewriteOrd pos t s1 s2 = (s1 > s2) == (replace pos t s1 > replace pos t s2) replace :: Int -> Formula a -> Formula Opaque -> Formula Opaque replace 0 _ t = t replace _ Top{} t = t replace _ Nom{} t = t replace _ Prop{} t = t replace _ NegTop{} t = t replace _ NegNom{} t = t replace _ NegProp{} t = t -- replace n f@At{} t = Opaque $ at (label f) $ replace (n`div`2) (subf f) t replace n f@Diam{} t = Opaque $ diam (relSym f) $ replace (n`div`2) (subf f) t replace n f@Box{} t = Opaque $ box (relSym f) $ replace (n`div`2) (subf f) t replace n f@Down{} t = Opaque $ down (boundVar f) $ replace (n`div`2) (subf f) t -- replace n f@Disj{} t = Opaque $ disj $ rep_list n (subfs f) t replace n f@Conj{} t = Opaque $ conj $ rep_list n (subfs f) t -- replace n (Opaque s) t = replace n s t rep_list :: Int -> [Formula a] -> Formula Opaque -> [Formula Opaque] rep_list n fs t = concat [first, [replace n' t_p t], rest] where (n', p) = n `divMod` length fs (first,t_p:rest) = splitAt p $ map opaque fs prop_admOrd_A2 :: AtFormula -> Bool prop_admOrd_A2 f = case specialize f of AtNom{} -> True _ -> compareF (subf f) (nom $ label f) == GT prop_admOrd_A3 :: AtFormula -> AtFormula -> Bool prop_admOrd_A3 f1 f2 = case compareF (subf f1) (subf f2) of EQ -> True neq -> neq == compareF f1 f2 prop_admOrd_A4 :: Formula (Diam Nom) -> Property prop_admOrd_A4 dn = forAll containing_box_nom $ \f -> compareF f dn == GT where containing_box_nom :: Gen (Formula Opaque) containing_box_nom = try_size (100 :: Int) -- try_size t = do f <- arbitrary if contains_box_nom (unNNF f) then return f else if (t == 0) then sized $ \s -> resize (s+1) (try_size 100) else try_size (t-1) -- contains_box_nom (F.Box _ (F.Nom _)) = True contains_box_nom other = F.composeFold False (||) contains_box_nom other prop_admOrd_A5 :: Formula (Box Nom) -> Formula (Diam Nom) -> Bool prop_admOrd_A5 f1 f2 = compareF f1 f2 == GT prop_killNom_kills :: NomSym -> NomSym -> Formula Opaque -> Bool prop_killNom_kills i j f = (not $ i `Set.member` noms_f) || (j `Set.member` noms_f' && (i `Set.member` noms_j || (not $ i `Set.member` noms_f'))) where noms_f = nomSymbols . getSignature $ f noms_f' = nomSymbols . getSignature $ killNom i j f noms_j = nomSymbols . getSignature $ (nom j :: Formula Nom) unit_tests :: UnitTest unit_tests = [ ("read/show - PropSymbol", runTest prop_read_PropSym), ("read/show - NomSymbol", runTest prop_read_NomSym), ("read/show - RelSymbol", runTest prop_read_RelSym), ("read/show - F Opaque", runTest prop_read_Opaque), ("read/show - F (At Opaque)", runTest prop_read_AtNomOpaque), -- ("ord trichotomy - NomSymbol", runTest prop_ord_trichotomy_NomSym), ("ord irreflexive - NomSymbol", runTest prop_ord_irreflexive_NomSym), ("ord antisymmetric - NomSymbol", runTest prop_ord_antisymmetric_NomSym), ("ord transitive - NomSymbol", runTest prop_ord_transitive_NomSym), ("total order - RelSymbol", runTest prop_ord_isTotalOrder_RelSym), ("transitive - RelSymbol", runTest prop_ord_transitive_RelSym), -- ("trichotomy - Formula", runTest prop_trichotomy_Opaque), ("irreflexive - Formula", runTest prop_irreflexive_Opaque), ("antisymmetric - Formula", runTest prop_antisymmetric_Opaque), ("transitive - Formula", runTest prop_transitive_Opaque), ("subformula property", runTest prop_subformulaProperty), ("rewrite ordering", runTest prop_rewriteOrd), ("adm ord A2", runTest prop_admOrd_A2), ("adm ord A3", runTest prop_admOrd_A3), ("adm ord A4", runTest prop_admOrd_A4), ("adm ord A5", runTest prop_admOrd_A5), -- ("killNom removes in to_nom", runTest prop_killNom_kills) ]
nevrenato/HyLoRes_Source
2.4/src/HyLoRes/Formula.hs
gpl-2.0
30,229
3
17
10,481
9,804
5,121
4,683
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Mode.Compilation -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- A 'Mode' for working with buffers showing the results of compilations. module Yi.Mode.Compilation where import Control.Lens import Data.Text () import Yi.Buffer import Yi.Core (withSyntax) import Yi.Editor import Yi.File (openingNewFile) import Yi.Lexer.Alex (Tok(..), Posn(..)) import qualified Yi.Lexer.Compilation as Compilation import Yi.Keymap import Yi.Keymap.Keys import Yi.Modes (styleMode, TokenBasedMode) import qualified Yi.Syntax.OnlineTree as OnlineTree mode :: TokenBasedMode Compilation.Token mode = styleMode Compilation.lexer & modeAppliesA .~ modeNeverApplies & modeNameA .~ "compilation" & modeKeymapA .~ topKeymapA %~ ((spec KEnter ?>>! withSyntax modeFollow) <||) & modeFollowA .~ YiA . follow where follow errs = withCurrentBuffer pointB >>= \point -> case OnlineTree.tokAtOrBefore point errs of Just t@Tok {tokT = Compilation.Report filename line col _} -> do withCurrentBuffer . moveTo . posnOfs $ tokPosn t shiftOtherWindow openingNewFile filename $ gotoLn line >> rightN col _ -> return ()
atsukotakahashi/wi
src/library/Yi/Mode/Compilation.hs
gpl-2.0
1,435
0
18
348
318
178
140
-1
-1
-- | The "framework" provides all the core classes and types used ubiquitously by -- the machine learning algorithms. module Algorithms.MachineLearning.Framework where import Algorithms.MachineLearning.LinearAlgebra import Algorithms.MachineLearning.Utilities import Numeric.LinearAlgebra import Data.List import System.Random -- -- Ubiquitous synonyms for documentation purposes -- -- | The target is the variable you wish to predict with your machine learning algorithm. type Target = Double type Weight = Double -- | Commonly called the "average" of a set of data. type Mean = Double -- | Variance is the mean squared deviation from the mean. Must be positive. type Variance = Double -- | Precision is the inverse of variance. Must be positive. type Precision = Double -- | A positive coefficient indicating how strongly regularization should be applied. A good -- choice for this parameter might be your belief about the variance of the inherent noise -- in the samples (1/beta) divided by your belief about the variance of the weights that -- should be learnt by the model (1/alpha). -- -- Commonly written as lambda. -- -- See also equation 3.55 and 3.28 in Bishop. type RegularizationCoefficient = Double -- | A positive number that indicates the number of fully determined parameters in a learnt -- model. If all your parameters are determined, it will be equal to the number of parameters -- available, and if your data did not support any parameters it will be simply 0. -- -- See also section 3.5.3 of Bishop. type EffectiveNumberOfParameters = Double -- -- Injections to and from vectors -- class Vectorable a where toVector :: a -> Vector Double fromVector :: Vector Double -> a instance Vectorable Double where toVector = flip constant 1 fromVector = flip (@>) 0 instance Vectorable (Double, Double) where toVector (x, y) = 2 |> [x, y] fromVector vec = (vec @> 0, vec @> 1) instance Vectorable (Vector Double) where toVector = id fromVector = id -- -- Labelled data set -- data DataSet input target = DataSet { ds_inputs :: Matrix Double, -- One row per sample, one column per input variable ds_targets :: Matrix Target -- One row per sample, one column per target variable } fmapDataSetInput :: (Vectorable input, Vectorable input', Vectorable target) => (input -> input') -> DataSet input target -> DataSet input' target fmapDataSetInput f = dataSetFromSampleList . fmap (onLeft f) . dataSetToSampleList fmapDataSetTarget :: (Vectorable input, Vectorable target, Vectorable target') => (target -> target') -> DataSet input target -> DataSet input target' fmapDataSetTarget f = dataSetFromSampleList . fmap (onRight f) . dataSetToSampleList dataSetFromSampleList :: (Vectorable input, Vectorable target) => [(input, target)] -> DataSet input target dataSetFromSampleList elts | null elts = error "dataSetFromSampleList: no data supplied" | otherwise = DataSet { ds_inputs = fromRows $ map (toVector . fst) elts, ds_targets = fromRows $ map (toVector . snd) elts } dataSetToSampleList :: (Vectorable input, Vectorable target) => DataSet input target -> [(input, target)] dataSetToSampleList ds = zip (dataSetInputs ds) (dataSetTargets ds) dataSetInputs :: Vectorable input => DataSet input target -> [input] dataSetInputs ds = map fromVector $ toRows $ ds_inputs ds dataSetTargets :: Vectorable target => DataSet input target -> [target] dataSetTargets ds = map fromVector $ toRows $ ds_targets ds dataSetInputLength :: DataSet input target -> Int dataSetInputLength ds = cols (ds_inputs ds) dataSetSize :: DataSet input target -> Int dataSetSize ds = rows (ds_inputs ds) binDataSet :: StdGen -> Int -> DataSet input target -> [DataSet input target] binDataSet gen bins = transformDataSetAsVectors binDataSet' where binDataSet' ds = map dataSetFromSampleList $ chunk bin_size shuffled_samples where shuffled_samples = shuffle gen (dataSetToSampleList ds) bin_size = ceiling $ (fromIntegral $ dataSetSize ds :: Double) / (fromIntegral bins) sampleDataSet :: StdGen -> Int -> DataSet input target -> DataSet input target sampleDataSet gen n = unK . transformDataSetAsVectors (K . dataSetFromSampleList . sample gen n . dataSetToSampleList) transformDataSetAsVectors :: Functor f => (DataSet (Vector Double) (Vector Double) -> f (DataSet (Vector Double) (Vector Double))) -> DataSet input target -> f (DataSet input target) transformDataSetAsVectors transform input = fmap castDataSet (transform (castDataSet input)) where castDataSet :: DataSet input1 target1 -> DataSet input2 target2 castDataSet ds = DataSet { ds_inputs = ds_inputs ds, ds_targets = ds_targets ds } -- -- Metric spaces -- class MetricSpace a where distance :: a -> a -> Double instance MetricSpace Double where distance x y = abs (x - y) instance MetricSpace (Vector Double) where distance x y = vectorSumSquares (x - y) -- -- Models -- class Model model input target | model -> input target where predict :: model -> input -> target data AnyModel input output = forall model. Model model input output => AnyModel { theModel :: model } instance Model (AnyModel input output) input output where predict (AnyModel model) = predict model modelSumSquaredError :: (Model model input target, MetricSpace target, Vectorable input, Vectorable target) => model -> DataSet input target -> Double modelSumSquaredError model ds = sum [sample_error * sample_error | sample_error <- sample_errors] where sample_errors = zipWith (\x y -> x `distance` y) (dataSetTargets ds) (map (predict model) (dataSetInputs ds))
batterseapower/machine-learning
Algorithms/MachineLearning/Framework.hs
gpl-2.0
5,676
0
13
1,031
1,428
755
673
-1
-1
module CoreSVG (writeFullPolygon ,writeFullFigure_dep ,writeFullFigure ,colourizeFig ,findBBFigure ,findBBFullFigure ,findBBPolygon ) where import DataTypes import Data.Char (toUpper) import Numeric (showHex) import Constants (strokewidth) {- This function takes a Point and returns a string which is formatted as an svg point. -} writePoint :: Point -> String writePoint (x,y) = (show x)++","++(show y)++" " {- useage: writeFullPolygon FullPolygon => svg String This function takes a tuple of the (Fill, Outline, Polygon) and will recursively call writePoint on each Point in the Polygon, as Polygon is a list of Point. Since we will get a list of String from that result we need to 'flatten' the list into one big string. This could be done by concat $ map writePoint p But haskell combines the two into concatMap. Then it adds the Fill and Outline to the svg definition of the Polygon. -} writeFullPolygon :: FullPolygon -> String writeFullPolygon ((r1,r2,g1,g2,b1,b2),(r,g,b),p) = " <polygon points=\""++(concatMap writePoint p)++"\" style=\"fill:#"++(f)++";stroke:rgb("++(show r)++","++(show g)++","++(show b)++");stroke-width:"++(show strokewidth)++"\"/>\n" where f = (writeHex r1)++(writeHex r2)++(writeHex g1)++(writeHex g2)++(writeHex b1)++(writeHex b2) {- useage: writeFullFigure FullFigure => svg String This function takes a list of Full Polygons and maps writeFullPolygon to each one. Since we will get a list of String from that result we need to concatenate each element in the list to get the big String we actually need. Hence why we use concatMap to do so. It also crucially adds the svg tags and the basic meta data to the string -} writeFullFigure_dep :: FullFigure -> String writeFullFigure_dep p = "<svg xmlns=\"http://www.w3.org/2000/svg\">\n"++(concatMap writeFullPolygon p)++"</svg>" {- useage: writeFullFigurePublish FullFigure => svg String ready for viewing Since GitHub's markdown can't display svg unless the height and width is explicitly stated. This function is essentially writeFullFigure but also finds the height and width of the figure and writes that to the svg attributes tag. -} writeFullFigure :: FullFigure -> String writeFullFigure f = "<svg height=\""++height++"\" width=\""++width++"\" xmlns=\"http://www.w3.org/2000/svg\">\n"++(concatMap writeFullPolygon f)++"</svg>" where (x,y) = (findCanvasFull f) height = (show y) width = (show x) --This is the function which finds the height and width of a figure findCanvasFull :: FullFigure -> Point findCanvasFull fig = (findBBFigure $ fullFigtoFig fig) !! 2 --This function is helper function to strip all the colour out of a figure fullFigtoFig :: FullFigure -> Figure fullFigtoFig [] = [] fullFigtoFig ((_,_,poly):xs) = poly:(fullFigtoFig xs) --Also a helper function for writing the Fill in svg writeHex :: Int -> String writeHex x = map toUpper (showHex x []) {- useage: colourizeFig Fill Outline Figure => FullFigure this function takes a specified Fill and Outline and creates a list of tuples holding the (Fill,Outline,Polygon). Note: repeat x creates an infinite list of x. Haskell can do this becuase its lazy. So even though it has infinite colours to zip in theory, once it reaches the end the Figure list its too 'lazy' to continue. -} colourizeFig :: Fill -> Outline -> Figure -> FullFigure colourizeFig fill line fig = zip3 (repeat fill) (repeat line) fig {- useage: findBBFigure figure => boundingbox The boundingbox which is returned is always a rectangle. It is calculated by 'flattening' all the figures into one big Polygon, then finding the boundingbox of that shape. Hence it always a Polygon with 4 elements. [a,b,c,d] where: a-----d | | | | b-----c -} findBBFigure :: Figure -> Polygon findBBFigure = findBBPolygon . concat findBBFullFigure :: FullFigure -> Polygon findBBFullFigure = findBBFigure . fullFigtoFig {- useage: findBBPolygon Polygon => boundingbox Same properties as findBBFigure, execpt its only for one list of Points. Since a list of points is a list of Point which is a tuple we can unzip it into a pair of lists. -} findBBPolygon :: Polygon -> Polygon findBBPolygon = findBB_help . unzip {- The actual fromula for finding the boundingbox It works by receiving a pair of (all x's,all y's) and simply orders them correctly. -} findBB_help :: ([Float],[Float]) -> Polygon findBB_help (x,y) = [(minx, miny),(minx, maxy), (maxx, maxy),(maxx, miny)] where minx = minimum x maxx = maximum x miny = minimum y maxy = maximum y
Lexer747/Haskell-Fractals
Core/CoreSVG.hs
gpl-3.0
4,530
0
18
751
762
422
340
46
1
{-# LANGUAGE OverloadedStrings #-} module Ssh.HashMac ( HashMac(..) , noHashMac , sha1HashMac ) where import qualified Data.ByteString.Lazy as B import Data.ByteString.Lazy.Char8 () -- IsString instance for the above import Data.Word import Data.HMAC type SshString = B.ByteString data HashMac = HashMac { hashName :: SshString -- secret key -> message -> HMAC , hashFunction :: [Word8] -> [Word8] -> [Word8] , hashSize :: Int , hashKeySize :: Int } instance Show HashMac where show = show . hashName none _ _ = [] noHashMac = HashMac "none" none 0 0 -- for the initial KEX sha1HashMac = HashMac "hmac-sha1" hmac_sha1 20 20
bcoppens/HaskellSshClient
src/Ssh/HashMac.hs
gpl-3.0
673
0
11
150
169
103
66
20
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE DeriveGeneric #-} module Test.QuickFuzz.Gen.Image.Png where import Data.Default import qualified Data.Binary import Codec.Picture.Png import Codec.Picture.Png.Type import Codec.Picture.Png.Export import Codec.Picture.Metadata import Codec.Picture.ColorQuant import Test.QuickCheck import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.State import Data.List import Data.Monoid import Test.QuickFuzz.Derive.Arbitrary import Test.QuickFuzz.Derive.Show import Test.QuickFuzz.Gen.FormatInfo import Test.QuickFuzz.Gen.Base.ByteString import Test.QuickFuzz.Gen.Base.String import Test.QuickFuzz.Gen.Base.Image import qualified Data.ByteString.Lazy as L devArbitrary ''PngRawImage devShow ''PngRawImage pngencode :: PngRawImage -> L.ByteString pngencode = Data.Binary.encode pngInfo :: FormatInfo PngRawImage NoActions pngInfo = def { encode = pngencode , random = arbitrary , value = show , ext = "png" }
elopez/QuickFuzz
src/Test/QuickFuzz/Gen/Image/Png.hs
gpl-3.0
1,073
0
6
135
219
143
76
35
1
--------------------------------------------------------------------------- -- This file is part of grammata. -- -- grammata 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. -- -- grammata 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 grammata. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- | Module : Grammata.Language -- Description : Grammata Language Definition Module -- Maintainer : sascha.rechenberger@uni-ulm.de -- Stability : stable -- Portability : portable -- Copyright : (c) Sascha Rechenberger, 2014, 2015 -- License : GPL-3 --------------------------------------------------------------------------- module Grammata.Language ( -- * Grammata AST Program (..), Value (..), Expression (..), Returns (..), -- ** Subprograms Subprg (..), -- ** Functional Lambda (..), -- ** Imperative Statement (..), -- ** Logical Rule (..), Clause (..), Goal (..), Term (..), -- * Grammata Parser parseGrammata ) where import Grammata.Language.Program (Program (..), Returns (..), Subprg (..), parseProgram) import Grammata.Language.Functional (Lambda (..)) import Grammata.Language.Imperative (Statement (..)) import Grammata.Language.Logical (Term (..), Goal (..), Clause (..), Rule (..), Base) import Grammata.Language.Value (Value (..)) import Grammata.Language.Expression (Expression (..)) import Text.Parsec (parse) -- | Parses a grammata program. parseGrammata :: String -> Either String Program parseGrammata input = case parse parseProgram "" input of Left msg -> Left . show $ msg Right ast -> Right ast
SRechenberger/grammata
src/Grammata/Language.hs
gpl-3.0
2,237
0
9
398
323
218
105
19
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.IdentityToolkit.RelyingParty.SetAccountInfo -- 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) -- -- Set account info for a user. -- -- /See:/ <https://developers.google.com/identity-toolkit/v3/ Google Identity Toolkit API Reference> for @identitytoolkit.relyingparty.setAccountInfo@. module Network.Google.Resource.IdentityToolkit.RelyingParty.SetAccountInfo ( -- * REST Resource RelyingPartySetAccountInfoResource -- * Creating a Request , relyingPartySetAccountInfo , RelyingPartySetAccountInfo -- * Request Lenses , rpsaiPayload ) where import Network.Google.IdentityToolkit.Types import Network.Google.Prelude -- | A resource alias for @identitytoolkit.relyingparty.setAccountInfo@ method which the -- 'RelyingPartySetAccountInfo' request conforms to. type RelyingPartySetAccountInfoResource = "identitytoolkit" :> "v3" :> "relyingparty" :> "setAccountInfo" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] IdentitytoolkitRelyingPartySetAccountInfoRequest :> Post '[JSON] SetAccountInfoResponse -- | Set account info for a user. -- -- /See:/ 'relyingPartySetAccountInfo' smart constructor. newtype RelyingPartySetAccountInfo = RelyingPartySetAccountInfo' { _rpsaiPayload :: IdentitytoolkitRelyingPartySetAccountInfoRequest } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'RelyingPartySetAccountInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rpsaiPayload' relyingPartySetAccountInfo :: IdentitytoolkitRelyingPartySetAccountInfoRequest -- ^ 'rpsaiPayload' -> RelyingPartySetAccountInfo relyingPartySetAccountInfo pRpsaiPayload_ = RelyingPartySetAccountInfo' { _rpsaiPayload = pRpsaiPayload_ } -- | Multipart request metadata. rpsaiPayload :: Lens' RelyingPartySetAccountInfo IdentitytoolkitRelyingPartySetAccountInfoRequest rpsaiPayload = lens _rpsaiPayload (\ s a -> s{_rpsaiPayload = a}) instance GoogleRequest RelyingPartySetAccountInfo where type Rs RelyingPartySetAccountInfo = SetAccountInfoResponse type Scopes RelyingPartySetAccountInfo = '["https://www.googleapis.com/auth/cloud-platform"] requestClient RelyingPartySetAccountInfo'{..} = go (Just AltJSON) _rpsaiPayload identityToolkitService where go = buildClient (Proxy :: Proxy RelyingPartySetAccountInfoResource) mempty
rueshyna/gogol
gogol-identity-toolkit/gen/Network/Google/Resource/IdentityToolkit/RelyingParty/SetAccountInfo.hs
mpl-2.0
3,333
0
13
698
308
189
119
53
1
-- | Round 1C 2009 Problem A. All Your Base -- https://code.google.com/codejam/contest/189252/dashboard#s=p0 module AllYourBase where -- constant imports import Text.ParserCombinators.Parsec import Text.Parsec import System.IO (openFile, hClose, hGetContents, hPutStrLn, IOMode(ReadMode), stderr) import Debug.Trace (trace) -- variable imports import qualified Data.Set as S import Data.List (group, sort, sortBy, foldl') import Data.Char (ord) import qualified Data.Map as M -- variable Data data TestCase = TestCase String -- ^ The number as string deriving (Show, Eq, Ord) type Mults = M.Map Char Integer -- variable implementation solveCase c@(TestCase digits) = show $ solve c solve c@(TestCase digits) = fst $ interpret base mults digits where mults = allDigits digits base1 = fromIntegral $ M.size mults base = if base1 == 1 then 2 else base1 interpret :: Integer -> Mults -> String -> (Integer, Integer) interpret base mults = foldr fn (0, 1) where fn ch (total, b) = let m = M.lookup ch mults in case m of Nothing -> error "Could not lookup" Just n -> (total + n * b, b * base) digits :: [Integer] digits = 1 : 0 : [2..] emptyDigits = M.empty :: Mults allDigits :: String -> Mults allDigits = fst . foldl' trav (emptyDigits, digits) trav :: (Mults, [Integer]) -> Char -> (Mults, [Integer]) trav (ms, exps) ch = case M.lookup ch ms of Nothing -> (M.insert ch next ms, tail exps) Just _ -> (ms, exps) where next = head exps -- Parser (variable part) parseSingleCase = do s <- many1 (oneOf (concat [['a'..'z'], ['0'..'9']])) eol <|> eof return $ TestCase s eol :: GenParser Char st () eol = char '\n' >> return () parseIntegral :: Integral a => (String -> a) -> GenParser Char st a parseIntegral rd = rd <$> (plus <|> minus <|> number) where plus = char '+' *> number minus = (:) <$> char '-' <*> number number = many1 digit parseInteger :: GenParser Char st Integer parseInteger = parseIntegral (read :: String -> Integer) parseIntegers :: GenParser Char st [Integer] parseIntegers = parseInteger `sepBy` (char ' ') parseInt :: GenParser Char st Int parseInt = parseIntegral (read :: String -> Int) parseInts :: GenParser Char st [Int] parseInts = parseInt `sepBy` (char ' ') -- -- constant part -- -- Parsing (constant part) -- | First number is number of test cases data TestInput = TestInput Int -- ^ number of 'TestCase's [TestCase] deriving (Show, Ord, Eq) parseTestCases = do numCases <- parseInt eol cases <- count numCases parseSingleCase return $ TestInput numCases cases parseCases :: String -> Either ParseError TestInput parseCases contents = parse parseTestCases "(stdin)" contents -- main runOnContent :: String -> IO () runOnContent content = do let parsed = parseCases content case parsed of Right (TestInput _ cases) -> mapM_ putStrLn (output (solveCases cases)) Left err -> hPutStrLn stderr $ show err where solveCases xs = map solveCase xs consCase n s = "Case #" ++ (show n) ++ ": " ++ s output xs = zipWith consCase [1..] xs -- | command line implementation run = do cs <- getContents runOnContent cs main = run
dirkz/google-code-jam-haskell
practice/src/AllYourBase.hs
mpl-2.0
3,287
0
14
760
1,118
597
521
79
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.Glacier.Types -- 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. module Network.AWS.Glacier.Types ( -- * Service Glacier -- ** Error , JSONError -- * ArchiveCreationOutput , ArchiveCreationOutput , archiveCreationOutput , acoArchiveId , acoChecksum , acoLocation -- * UploadListElement , UploadListElement , uploadListElement , uleArchiveDescription , uleCreationDate , uleMultipartUploadId , ulePartSizeInBytes , uleVaultARN -- * InventoryRetrievalJobDescription , InventoryRetrievalJobDescription , inventoryRetrievalJobDescription , irjdEndDate , irjdFormat , irjdLimit , irjdMarker , irjdStartDate -- * JobParameters , JobParameters , jobParameters , jpArchiveId , jpDescription , jpFormat , jpInventoryRetrievalParameters , jpRetrievalByteRange , jpSNSTopic , jpType -- * DescribeVaultOutput , DescribeVaultOutput , describeVaultOutput , dvoCreationDate , dvoLastInventoryDate , dvoNumberOfArchives , dvoSizeInBytes , dvoVaultARN , dvoVaultName -- * DataRetrievalRule , DataRetrievalRule , dataRetrievalRule , drrBytesPerHour , drrStrategy -- * ActionCode , ActionCode (..) -- * VaultNotificationConfig , VaultNotificationConfig , vaultNotificationConfig , vncEvents , vncSNSTopic -- * InventoryRetrievalJobInput , InventoryRetrievalJobInput , inventoryRetrievalJobInput , irjiEndDate , irjiLimit , irjiMarker , irjiStartDate -- * PartListElement , PartListElement , partListElement , pleRangeInBytes , pleSHA256TreeHash -- * DataRetrievalPolicy , DataRetrievalPolicy , dataRetrievalPolicy , drpRules -- * GlacierJobDescription , GlacierJobDescription , glacierJobDescription , gjdAction , gjdArchiveId , gjdArchiveSHA256TreeHash , gjdArchiveSizeInBytes , gjdCompleted , gjdCompletionDate , gjdCreationDate , gjdInventoryRetrievalParameters , gjdInventorySizeInBytes , gjdJobDescription , gjdJobId , gjdRetrievalByteRange , gjdSHA256TreeHash , gjdSNSTopic , gjdStatusCode , gjdStatusMessage , gjdVaultARN -- * VaultAccessPolicy , VaultAccessPolicy , vaultAccessPolicy , vapPolicy -- * StatusCode , StatusCode (..) ) where import Network.AWS.Prelude import Network.AWS.Signing import qualified GHC.Exts -- | Version @2012-06-01@ of the Amazon Glacier service. data Glacier instance AWSService Glacier where type Sg Glacier = V4 type Er Glacier = JSONError service = service' where service' :: Service Glacier service' = Service { _svcAbbrev = "Glacier" , _svcPrefix = "glacier" , _svcVersion = "2012-06-01" , _svcTargetPrefix = Nothing , _svcJSONVersion = Nothing , _svcHandle = handle , _svcRetry = retry } handle :: Status -> Maybe (LazyByteString -> ServiceError JSONError) handle = jsonError statusSuccess service' retry :: Retry Glacier retry = Exponential { _retryBase = 0.05 , _retryGrowth = 2 , _retryAttempts = 5 , _retryCheck = check } check :: Status -> JSONError -> Bool check (statusCode -> s) (awsErrorCode -> e) | s == 400 && (Just "ThrottlingException") == e = True -- Throttling | s == 500 = True -- General Server Error | s == 509 = True -- Limit Exceeded | s == 503 = True -- Service Unavailable | otherwise = False data ArchiveCreationOutput = ArchiveCreationOutput { _acoArchiveId :: Maybe Text , _acoChecksum :: Maybe Text , _acoLocation :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'ArchiveCreationOutput' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'acoArchiveId' @::@ 'Maybe' 'Text' -- -- * 'acoChecksum' @::@ 'Maybe' 'Text' -- -- * 'acoLocation' @::@ 'Maybe' 'Text' -- archiveCreationOutput :: ArchiveCreationOutput archiveCreationOutput = ArchiveCreationOutput { _acoLocation = Nothing , _acoChecksum = Nothing , _acoArchiveId = Nothing } -- | The ID of the archive. This value is also included as part of the location. acoArchiveId :: Lens' ArchiveCreationOutput (Maybe Text) acoArchiveId = lens _acoArchiveId (\s a -> s { _acoArchiveId = a }) -- | The checksum of the archive computed by Amazon Glacier. acoChecksum :: Lens' ArchiveCreationOutput (Maybe Text) acoChecksum = lens _acoChecksum (\s a -> s { _acoChecksum = a }) -- | The relative URI path of the newly added archive resource. acoLocation :: Lens' ArchiveCreationOutput (Maybe Text) acoLocation = lens _acoLocation (\s a -> s { _acoLocation = a }) instance FromJSON ArchiveCreationOutput where parseJSON = withObject "ArchiveCreationOutput" $ \o -> ArchiveCreationOutput <$> o .:? "x-amz-archive-id" <*> o .:? "x-amz-sha256-tree-hash" <*> o .:? "Location" instance ToJSON ArchiveCreationOutput where toJSON = const (toJSON Empty) data UploadListElement = UploadListElement { _uleArchiveDescription :: Maybe Text , _uleCreationDate :: Maybe Text , _uleMultipartUploadId :: Maybe Text , _ulePartSizeInBytes :: Maybe Integer , _uleVaultARN :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'UploadListElement' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'uleArchiveDescription' @::@ 'Maybe' 'Text' -- -- * 'uleCreationDate' @::@ 'Maybe' 'Text' -- -- * 'uleMultipartUploadId' @::@ 'Maybe' 'Text' -- -- * 'ulePartSizeInBytes' @::@ 'Maybe' 'Integer' -- -- * 'uleVaultARN' @::@ 'Maybe' 'Text' -- uploadListElement :: UploadListElement uploadListElement = UploadListElement { _uleMultipartUploadId = Nothing , _uleVaultARN = Nothing , _uleArchiveDescription = Nothing , _ulePartSizeInBytes = Nothing , _uleCreationDate = Nothing } -- | The description of the archive that was specified in the Initiate Multipart -- Upload request. uleArchiveDescription :: Lens' UploadListElement (Maybe Text) uleArchiveDescription = lens _uleArchiveDescription (\s a -> s { _uleArchiveDescription = a }) -- | The UTC time at which the multipart upload was initiated. uleCreationDate :: Lens' UploadListElement (Maybe Text) uleCreationDate = lens _uleCreationDate (\s a -> s { _uleCreationDate = a }) -- | The ID of a multipart upload. uleMultipartUploadId :: Lens' UploadListElement (Maybe Text) uleMultipartUploadId = lens _uleMultipartUploadId (\s a -> s { _uleMultipartUploadId = a }) -- | The part size, in bytes, specified in the Initiate Multipart Upload request. -- This is the size of all the parts in the upload except the last part, which -- may be smaller than this size. ulePartSizeInBytes :: Lens' UploadListElement (Maybe Integer) ulePartSizeInBytes = lens _ulePartSizeInBytes (\s a -> s { _ulePartSizeInBytes = a }) -- | The Amazon Resource Name (ARN) of the vault that contains the archive. uleVaultARN :: Lens' UploadListElement (Maybe Text) uleVaultARN = lens _uleVaultARN (\s a -> s { _uleVaultARN = a }) instance FromJSON UploadListElement where parseJSON = withObject "UploadListElement" $ \o -> UploadListElement <$> o .:? "ArchiveDescription" <*> o .:? "CreationDate" <*> o .:? "MultipartUploadId" <*> o .:? "PartSizeInBytes" <*> o .:? "VaultARN" instance ToJSON UploadListElement where toJSON UploadListElement{..} = object [ "MultipartUploadId" .= _uleMultipartUploadId , "VaultARN" .= _uleVaultARN , "ArchiveDescription" .= _uleArchiveDescription , "PartSizeInBytes" .= _ulePartSizeInBytes , "CreationDate" .= _uleCreationDate ] data InventoryRetrievalJobDescription = InventoryRetrievalJobDescription { _irjdEndDate :: Maybe Text , _irjdFormat :: Maybe Text , _irjdLimit :: Maybe Text , _irjdMarker :: Maybe Text , _irjdStartDate :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'InventoryRetrievalJobDescription' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'irjdEndDate' @::@ 'Maybe' 'Text' -- -- * 'irjdFormat' @::@ 'Maybe' 'Text' -- -- * 'irjdLimit' @::@ 'Maybe' 'Text' -- -- * 'irjdMarker' @::@ 'Maybe' 'Text' -- -- * 'irjdStartDate' @::@ 'Maybe' 'Text' -- inventoryRetrievalJobDescription :: InventoryRetrievalJobDescription inventoryRetrievalJobDescription = InventoryRetrievalJobDescription { _irjdFormat = Nothing , _irjdStartDate = Nothing , _irjdEndDate = Nothing , _irjdLimit = Nothing , _irjdMarker = Nothing } -- | The end of the date range in UTC for vault inventory retrieval that includes -- archives created before this date. A string representation of ISO 8601 date -- format, for example, 2013-03-20T17:03:43Z. irjdEndDate :: Lens' InventoryRetrievalJobDescription (Maybe Text) irjdEndDate = lens _irjdEndDate (\s a -> s { _irjdEndDate = a }) -- | The output format for the vault inventory list, which is set by the InitiateJob -- request when initiating a job to retrieve a vault inventory. Valid values -- are "CSV" and "JSON". irjdFormat :: Lens' InventoryRetrievalJobDescription (Maybe Text) irjdFormat = lens _irjdFormat (\s a -> s { _irjdFormat = a }) -- | Specifies the maximum number of inventory items returned per vault inventory -- retrieval request. This limit is set when initiating the job with the a InitiateJob -- request. irjdLimit :: Lens' InventoryRetrievalJobDescription (Maybe Text) irjdLimit = lens _irjdLimit (\s a -> s { _irjdLimit = a }) -- | An opaque string that represents where to continue pagination of the vault -- inventory retrieval results. You use the marker in a new InitiateJob request -- to obtain additional inventory items. If there are no more inventory items, -- this value is 'null'. For more information, see <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-initiate-job-post.html#api-initiate-job-post-vault-inventory-list-filtering Range Inventory Retrieval>. irjdMarker :: Lens' InventoryRetrievalJobDescription (Maybe Text) irjdMarker = lens _irjdMarker (\s a -> s { _irjdMarker = a }) -- | The start of the date range in UTC for vault inventory retrieval that -- includes archives created on or after this date. A string representation of -- ISO 8601 date format, for example, 2013-03-20T17:03:43Z. irjdStartDate :: Lens' InventoryRetrievalJobDescription (Maybe Text) irjdStartDate = lens _irjdStartDate (\s a -> s { _irjdStartDate = a }) instance FromJSON InventoryRetrievalJobDescription where parseJSON = withObject "InventoryRetrievalJobDescription" $ \o -> InventoryRetrievalJobDescription <$> o .:? "EndDate" <*> o .:? "Format" <*> o .:? "Limit" <*> o .:? "Marker" <*> o .:? "StartDate" instance ToJSON InventoryRetrievalJobDescription where toJSON InventoryRetrievalJobDescription{..} = object [ "Format" .= _irjdFormat , "StartDate" .= _irjdStartDate , "EndDate" .= _irjdEndDate , "Limit" .= _irjdLimit , "Marker" .= _irjdMarker ] data JobParameters = JobParameters { _jpArchiveId :: Maybe Text , _jpDescription :: Maybe Text , _jpFormat :: Maybe Text , _jpInventoryRetrievalParameters :: Maybe InventoryRetrievalJobInput , _jpRetrievalByteRange :: Maybe Text , _jpSNSTopic :: Maybe Text , _jpType :: Maybe Text } deriving (Eq, Read, Show) -- | 'JobParameters' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'jpArchiveId' @::@ 'Maybe' 'Text' -- -- * 'jpDescription' @::@ 'Maybe' 'Text' -- -- * 'jpFormat' @::@ 'Maybe' 'Text' -- -- * 'jpInventoryRetrievalParameters' @::@ 'Maybe' 'InventoryRetrievalJobInput' -- -- * 'jpRetrievalByteRange' @::@ 'Maybe' 'Text' -- -- * 'jpSNSTopic' @::@ 'Maybe' 'Text' -- -- * 'jpType' @::@ 'Maybe' 'Text' -- jobParameters :: JobParameters jobParameters = JobParameters { _jpFormat = Nothing , _jpType = Nothing , _jpArchiveId = Nothing , _jpDescription = Nothing , _jpSNSTopic = Nothing , _jpRetrievalByteRange = Nothing , _jpInventoryRetrievalParameters = Nothing } -- | The ID of the archive that you want to retrieve. This field is required only -- if 'Type' is set to archive-retrieval. An error occurs if you specify this -- request parameter for an inventory retrieval job request. jpArchiveId :: Lens' JobParameters (Maybe Text) jpArchiveId = lens _jpArchiveId (\s a -> s { _jpArchiveId = a }) -- | The optional description for the job. The description must be less than or -- equal to 1,024 bytes. The allowable characters are 7-bit ASCII without -- control codes-specifically, ASCII values 32-126 decimal or 0x20-0x7E -- hexadecimal. jpDescription :: Lens' JobParameters (Maybe Text) jpDescription = lens _jpDescription (\s a -> s { _jpDescription = a }) -- | When initiating a job to retrieve a vault inventory, you can optionally add -- this parameter to your request to specify the output format. If you are -- initiating an inventory job and do not specify a Format field, JSON is the -- default format. Valid values are "CSV" and "JSON". jpFormat :: Lens' JobParameters (Maybe Text) jpFormat = lens _jpFormat (\s a -> s { _jpFormat = a }) -- | Input parameters used for range inventory retrieval. jpInventoryRetrievalParameters :: Lens' JobParameters (Maybe InventoryRetrievalJobInput) jpInventoryRetrievalParameters = lens _jpInventoryRetrievalParameters (\s a -> s { _jpInventoryRetrievalParameters = a }) -- | The byte range to retrieve for an archive retrieval. in the form "/StartByteValue/-/EndByteValue/" If not specified, the whole archive is retrieved. If -- specified, the byte range must be megabyte (1024*1024) aligned which means -- that /StartByteValue/ must be divisible by 1 MB and /EndByteValue/ plus 1 must be -- divisible by 1 MB or be the end of the archive specified as the archive byte -- size value minus 1. If RetrievalByteRange is not megabyte aligned, this -- operation returns a 400 response. -- -- An error occurs if you specify this field for an inventory retrieval job -- request. jpRetrievalByteRange :: Lens' JobParameters (Maybe Text) jpRetrievalByteRange = lens _jpRetrievalByteRange (\s a -> s { _jpRetrievalByteRange = a }) -- | The Amazon SNS topic ARN to which Amazon Glacier sends a notification when -- the job is completed and the output is ready for you to download. The -- specified topic publishes the notification to its subscribers. The SNS topic -- must exist. jpSNSTopic :: Lens' JobParameters (Maybe Text) jpSNSTopic = lens _jpSNSTopic (\s a -> s { _jpSNSTopic = a }) -- | The job type. You can initiate a job to retrieve an archive or get an -- inventory of a vault. Valid values are "archive-retrieval" and -- "inventory-retrieval". jpType :: Lens' JobParameters (Maybe Text) jpType = lens _jpType (\s a -> s { _jpType = a }) instance FromJSON JobParameters where parseJSON = withObject "JobParameters" $ \o -> JobParameters <$> o .:? "ArchiveId" <*> o .:? "Description" <*> o .:? "Format" <*> o .:? "InventoryRetrievalParameters" <*> o .:? "RetrievalByteRange" <*> o .:? "SNSTopic" <*> o .:? "Type" instance ToJSON JobParameters where toJSON JobParameters{..} = object [ "Format" .= _jpFormat , "Type" .= _jpType , "ArchiveId" .= _jpArchiveId , "Description" .= _jpDescription , "SNSTopic" .= _jpSNSTopic , "RetrievalByteRange" .= _jpRetrievalByteRange , "InventoryRetrievalParameters" .= _jpInventoryRetrievalParameters ] data DescribeVaultOutput = DescribeVaultOutput { _dvoCreationDate :: Maybe Text , _dvoLastInventoryDate :: Maybe Text , _dvoNumberOfArchives :: Maybe Integer , _dvoSizeInBytes :: Maybe Integer , _dvoVaultARN :: Maybe Text , _dvoVaultName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'DescribeVaultOutput' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dvoCreationDate' @::@ 'Maybe' 'Text' -- -- * 'dvoLastInventoryDate' @::@ 'Maybe' 'Text' -- -- * 'dvoNumberOfArchives' @::@ 'Maybe' 'Integer' -- -- * 'dvoSizeInBytes' @::@ 'Maybe' 'Integer' -- -- * 'dvoVaultARN' @::@ 'Maybe' 'Text' -- -- * 'dvoVaultName' @::@ 'Maybe' 'Text' -- describeVaultOutput :: DescribeVaultOutput describeVaultOutput = DescribeVaultOutput { _dvoVaultARN = Nothing , _dvoVaultName = Nothing , _dvoCreationDate = Nothing , _dvoLastInventoryDate = Nothing , _dvoNumberOfArchives = Nothing , _dvoSizeInBytes = Nothing } -- | The UTC date when the vault was created. A string representation of ISO 8601 -- date format, for example, "2012-03-20T17:03:43.221Z". dvoCreationDate :: Lens' DescribeVaultOutput (Maybe Text) dvoCreationDate = lens _dvoCreationDate (\s a -> s { _dvoCreationDate = a }) -- | The UTC date when Amazon Glacier completed the last vault inventory. A string -- representation of ISO 8601 date format, for example, -- "2012-03-20T17:03:43.221Z". dvoLastInventoryDate :: Lens' DescribeVaultOutput (Maybe Text) dvoLastInventoryDate = lens _dvoLastInventoryDate (\s a -> s { _dvoLastInventoryDate = a }) -- | The number of archives in the vault as of the last inventory date. This field -- will return 'null' if an inventory has not yet run on the vault, for example, -- if you just created the vault. dvoNumberOfArchives :: Lens' DescribeVaultOutput (Maybe Integer) dvoNumberOfArchives = lens _dvoNumberOfArchives (\s a -> s { _dvoNumberOfArchives = a }) -- | Total size, in bytes, of the archives in the vault as of the last inventory -- date. This field will return null if an inventory has not yet run on the -- vault, for example, if you just created the vault. dvoSizeInBytes :: Lens' DescribeVaultOutput (Maybe Integer) dvoSizeInBytes = lens _dvoSizeInBytes (\s a -> s { _dvoSizeInBytes = a }) -- | The Amazon Resource Name (ARN) of the vault. dvoVaultARN :: Lens' DescribeVaultOutput (Maybe Text) dvoVaultARN = lens _dvoVaultARN (\s a -> s { _dvoVaultARN = a }) -- | The name of the vault. dvoVaultName :: Lens' DescribeVaultOutput (Maybe Text) dvoVaultName = lens _dvoVaultName (\s a -> s { _dvoVaultName = a }) instance FromJSON DescribeVaultOutput where parseJSON = withObject "DescribeVaultOutput" $ \o -> DescribeVaultOutput <$> o .:? "CreationDate" <*> o .:? "LastInventoryDate" <*> o .:? "NumberOfArchives" <*> o .:? "SizeInBytes" <*> o .:? "VaultARN" <*> o .:? "VaultName" instance ToJSON DescribeVaultOutput where toJSON DescribeVaultOutput{..} = object [ "VaultARN" .= _dvoVaultARN , "VaultName" .= _dvoVaultName , "CreationDate" .= _dvoCreationDate , "LastInventoryDate" .= _dvoLastInventoryDate , "NumberOfArchives" .= _dvoNumberOfArchives , "SizeInBytes" .= _dvoSizeInBytes ] data DataRetrievalRule = DataRetrievalRule { _drrBytesPerHour :: Maybe Integer , _drrStrategy :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'DataRetrievalRule' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'drrBytesPerHour' @::@ 'Maybe' 'Integer' -- -- * 'drrStrategy' @::@ 'Maybe' 'Text' -- dataRetrievalRule :: DataRetrievalRule dataRetrievalRule = DataRetrievalRule { _drrStrategy = Nothing , _drrBytesPerHour = Nothing } -- | The maximum number of bytes that can be retrieved in an hour. -- -- This field is required only if the value of the Strategy field is 'BytesPerHour'. Your PUT operation will be rejected if the Strategy field is not set to 'BytesPerHour' and you set this field. drrBytesPerHour :: Lens' DataRetrievalRule (Maybe Integer) drrBytesPerHour = lens _drrBytesPerHour (\s a -> s { _drrBytesPerHour = a }) -- | The type of data retrieval policy to set. -- -- Valid values: BytesPerHour|FreeTier|None drrStrategy :: Lens' DataRetrievalRule (Maybe Text) drrStrategy = lens _drrStrategy (\s a -> s { _drrStrategy = a }) instance FromJSON DataRetrievalRule where parseJSON = withObject "DataRetrievalRule" $ \o -> DataRetrievalRule <$> o .:? "BytesPerHour" <*> o .:? "Strategy" instance ToJSON DataRetrievalRule where toJSON DataRetrievalRule{..} = object [ "Strategy" .= _drrStrategy , "BytesPerHour" .= _drrBytesPerHour ] data ActionCode = ArchiveRetrieval -- ^ ArchiveRetrieval | InventoryRetrieval -- ^ InventoryRetrieval deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ActionCode instance FromText ActionCode where parser = takeLowerText >>= \case "archiveretrieval" -> pure ArchiveRetrieval "inventoryretrieval" -> pure InventoryRetrieval e -> fail $ "Failure parsing ActionCode from " ++ show e instance ToText ActionCode where toText = \case ArchiveRetrieval -> "ArchiveRetrieval" InventoryRetrieval -> "InventoryRetrieval" instance ToByteString ActionCode instance ToHeader ActionCode instance ToQuery ActionCode instance FromJSON ActionCode where parseJSON = parseJSONText "ActionCode" instance ToJSON ActionCode where toJSON = toJSONText data VaultNotificationConfig = VaultNotificationConfig { _vncEvents :: List "Events" Text , _vncSNSTopic :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'VaultNotificationConfig' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vncEvents' @::@ ['Text'] -- -- * 'vncSNSTopic' @::@ 'Maybe' 'Text' -- vaultNotificationConfig :: VaultNotificationConfig vaultNotificationConfig = VaultNotificationConfig { _vncSNSTopic = Nothing , _vncEvents = mempty } -- | A list of one or more events for which Amazon Glacier will send a -- notification to the specified Amazon SNS topic. vncEvents :: Lens' VaultNotificationConfig [Text] vncEvents = lens _vncEvents (\s a -> s { _vncEvents = a }) . _List -- | The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource -- Name (ARN). vncSNSTopic :: Lens' VaultNotificationConfig (Maybe Text) vncSNSTopic = lens _vncSNSTopic (\s a -> s { _vncSNSTopic = a }) instance FromJSON VaultNotificationConfig where parseJSON = withObject "VaultNotificationConfig" $ \o -> VaultNotificationConfig <$> o .:? "Events" .!= mempty <*> o .:? "SNSTopic" instance ToJSON VaultNotificationConfig where toJSON VaultNotificationConfig{..} = object [ "SNSTopic" .= _vncSNSTopic , "Events" .= _vncEvents ] data InventoryRetrievalJobInput = InventoryRetrievalJobInput { _irjiEndDate :: Maybe Text , _irjiLimit :: Maybe Text , _irjiMarker :: Maybe Text , _irjiStartDate :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'InventoryRetrievalJobInput' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'irjiEndDate' @::@ 'Maybe' 'Text' -- -- * 'irjiLimit' @::@ 'Maybe' 'Text' -- -- * 'irjiMarker' @::@ 'Maybe' 'Text' -- -- * 'irjiStartDate' @::@ 'Maybe' 'Text' -- inventoryRetrievalJobInput :: InventoryRetrievalJobInput inventoryRetrievalJobInput = InventoryRetrievalJobInput { _irjiStartDate = Nothing , _irjiEndDate = Nothing , _irjiLimit = Nothing , _irjiMarker = Nothing } -- | The end of the date range in UTC for vault inventory retrieval that includes -- archives created before this date. A string representation of ISO 8601 date -- format, for example, 2013-03-20T17:03:43Z. irjiEndDate :: Lens' InventoryRetrievalJobInput (Maybe Text) irjiEndDate = lens _irjiEndDate (\s a -> s { _irjiEndDate = a }) -- | Specifies the maximum number of inventory items returned per vault inventory -- retrieval request. Valid values are greater than or equal to 1. irjiLimit :: Lens' InventoryRetrievalJobInput (Maybe Text) irjiLimit = lens _irjiLimit (\s a -> s { _irjiLimit = a }) -- | An opaque string that represents where to continue pagination of the vault -- inventory retrieval results. You use the marker in a new InitiateJob request -- to obtain additional inventory items. If there are no more inventory items, -- this value is 'null'. irjiMarker :: Lens' InventoryRetrievalJobInput (Maybe Text) irjiMarker = lens _irjiMarker (\s a -> s { _irjiMarker = a }) -- | The start of the date range in UTC for vault inventory retrieval that -- includes archives created on or after this date. A string representation of -- ISO 8601 date format, for example, 2013-03-20T17:03:43Z. irjiStartDate :: Lens' InventoryRetrievalJobInput (Maybe Text) irjiStartDate = lens _irjiStartDate (\s a -> s { _irjiStartDate = a }) instance FromJSON InventoryRetrievalJobInput where parseJSON = withObject "InventoryRetrievalJobInput" $ \o -> InventoryRetrievalJobInput <$> o .:? "EndDate" <*> o .:? "Limit" <*> o .:? "Marker" <*> o .:? "StartDate" instance ToJSON InventoryRetrievalJobInput where toJSON InventoryRetrievalJobInput{..} = object [ "StartDate" .= _irjiStartDate , "EndDate" .= _irjiEndDate , "Limit" .= _irjiLimit , "Marker" .= _irjiMarker ] data PartListElement = PartListElement { _pleRangeInBytes :: Maybe Text , _pleSHA256TreeHash :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'PartListElement' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pleRangeInBytes' @::@ 'Maybe' 'Text' -- -- * 'pleSHA256TreeHash' @::@ 'Maybe' 'Text' -- partListElement :: PartListElement partListElement = PartListElement { _pleRangeInBytes = Nothing , _pleSHA256TreeHash = Nothing } -- | The byte range of a part, inclusive of the upper value of the range. pleRangeInBytes :: Lens' PartListElement (Maybe Text) pleRangeInBytes = lens _pleRangeInBytes (\s a -> s { _pleRangeInBytes = a }) -- | The SHA256 tree hash value that Amazon Glacier calculated for the part. This -- field is never 'null'. pleSHA256TreeHash :: Lens' PartListElement (Maybe Text) pleSHA256TreeHash = lens _pleSHA256TreeHash (\s a -> s { _pleSHA256TreeHash = a }) instance FromJSON PartListElement where parseJSON = withObject "PartListElement" $ \o -> PartListElement <$> o .:? "RangeInBytes" <*> o .:? "SHA256TreeHash" instance ToJSON PartListElement where toJSON PartListElement{..} = object [ "RangeInBytes" .= _pleRangeInBytes , "SHA256TreeHash" .= _pleSHA256TreeHash ] newtype DataRetrievalPolicy = DataRetrievalPolicy { _drpRules :: List "Rules" DataRetrievalRule } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DataRetrievalPolicy where type Item DataRetrievalPolicy = DataRetrievalRule fromList = DataRetrievalPolicy . GHC.Exts.fromList toList = GHC.Exts.toList . _drpRules -- | 'DataRetrievalPolicy' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'drpRules' @::@ ['DataRetrievalRule'] -- dataRetrievalPolicy :: DataRetrievalPolicy dataRetrievalPolicy = DataRetrievalPolicy { _drpRules = mempty } -- | The policy rule. Although this is a list type, currently there must be only -- one rule, which contains a Strategy field and optionally a BytesPerHour field. drpRules :: Lens' DataRetrievalPolicy [DataRetrievalRule] drpRules = lens _drpRules (\s a -> s { _drpRules = a }) . _List instance FromJSON DataRetrievalPolicy where parseJSON = withObject "DataRetrievalPolicy" $ \o -> DataRetrievalPolicy <$> o .:? "Rules" .!= mempty instance ToJSON DataRetrievalPolicy where toJSON DataRetrievalPolicy{..} = object [ "Rules" .= _drpRules ] data GlacierJobDescription = GlacierJobDescription { _gjdAction :: Maybe ActionCode , _gjdArchiveId :: Maybe Text , _gjdArchiveSHA256TreeHash :: Maybe Text , _gjdArchiveSizeInBytes :: Maybe Integer , _gjdCompleted :: Maybe Bool , _gjdCompletionDate :: Maybe Text , _gjdCreationDate :: Maybe Text , _gjdInventoryRetrievalParameters :: Maybe InventoryRetrievalJobDescription , _gjdInventorySizeInBytes :: Maybe Integer , _gjdJobDescription :: Maybe Text , _gjdJobId :: Maybe Text , _gjdRetrievalByteRange :: Maybe Text , _gjdSHA256TreeHash :: Maybe Text , _gjdSNSTopic :: Maybe Text , _gjdStatusCode :: Maybe StatusCode , _gjdStatusMessage :: Maybe Text , _gjdVaultARN :: Maybe Text } deriving (Eq, Read, Show) -- | 'GlacierJobDescription' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gjdAction' @::@ 'Maybe' 'ActionCode' -- -- * 'gjdArchiveId' @::@ 'Maybe' 'Text' -- -- * 'gjdArchiveSHA256TreeHash' @::@ 'Maybe' 'Text' -- -- * 'gjdArchiveSizeInBytes' @::@ 'Maybe' 'Integer' -- -- * 'gjdCompleted' @::@ 'Maybe' 'Bool' -- -- * 'gjdCompletionDate' @::@ 'Maybe' 'Text' -- -- * 'gjdCreationDate' @::@ 'Maybe' 'Text' -- -- * 'gjdInventoryRetrievalParameters' @::@ 'Maybe' 'InventoryRetrievalJobDescription' -- -- * 'gjdInventorySizeInBytes' @::@ 'Maybe' 'Integer' -- -- * 'gjdJobDescription' @::@ 'Maybe' 'Text' -- -- * 'gjdJobId' @::@ 'Maybe' 'Text' -- -- * 'gjdRetrievalByteRange' @::@ 'Maybe' 'Text' -- -- * 'gjdSHA256TreeHash' @::@ 'Maybe' 'Text' -- -- * 'gjdSNSTopic' @::@ 'Maybe' 'Text' -- -- * 'gjdStatusCode' @::@ 'Maybe' 'StatusCode' -- -- * 'gjdStatusMessage' @::@ 'Maybe' 'Text' -- -- * 'gjdVaultARN' @::@ 'Maybe' 'Text' -- glacierJobDescription :: GlacierJobDescription glacierJobDescription = GlacierJobDescription { _gjdJobId = Nothing , _gjdJobDescription = Nothing , _gjdAction = Nothing , _gjdArchiveId = Nothing , _gjdVaultARN = Nothing , _gjdCreationDate = Nothing , _gjdCompleted = Nothing , _gjdStatusCode = Nothing , _gjdStatusMessage = Nothing , _gjdArchiveSizeInBytes = Nothing , _gjdInventorySizeInBytes = Nothing , _gjdSNSTopic = Nothing , _gjdCompletionDate = Nothing , _gjdSHA256TreeHash = Nothing , _gjdArchiveSHA256TreeHash = Nothing , _gjdRetrievalByteRange = Nothing , _gjdInventoryRetrievalParameters = Nothing } -- | The job type. It is either ArchiveRetrieval or InventoryRetrieval. gjdAction :: Lens' GlacierJobDescription (Maybe ActionCode) gjdAction = lens _gjdAction (\s a -> s { _gjdAction = a }) -- | For an ArchiveRetrieval job, this is the archive ID requested for download. -- Otherwise, this field is null. gjdArchiveId :: Lens' GlacierJobDescription (Maybe Text) gjdArchiveId = lens _gjdArchiveId (\s a -> s { _gjdArchiveId = a }) -- | The SHA256 tree hash of the entire archive for an archive retrieval. For -- inventory retrieval jobs, this field is null. gjdArchiveSHA256TreeHash :: Lens' GlacierJobDescription (Maybe Text) gjdArchiveSHA256TreeHash = lens _gjdArchiveSHA256TreeHash (\s a -> s { _gjdArchiveSHA256TreeHash = a }) -- | For an ArchiveRetrieval job, this is the size in bytes of the archive being -- requested for download. For the InventoryRetrieval job, the value is null. gjdArchiveSizeInBytes :: Lens' GlacierJobDescription (Maybe Integer) gjdArchiveSizeInBytes = lens _gjdArchiveSizeInBytes (\s a -> s { _gjdArchiveSizeInBytes = a }) -- | The job status. When a job is completed, you get the job's output. gjdCompleted :: Lens' GlacierJobDescription (Maybe Bool) gjdCompleted = lens _gjdCompleted (\s a -> s { _gjdCompleted = a }) -- | The UTC time that the archive retrieval request completed. While the job is -- in progress, the value will be null. gjdCompletionDate :: Lens' GlacierJobDescription (Maybe Text) gjdCompletionDate = lens _gjdCompletionDate (\s a -> s { _gjdCompletionDate = a }) -- | The UTC date when the job was created. A string representation of ISO 8601 -- date format, for example, "2012-03-20T17:03:43.221Z". gjdCreationDate :: Lens' GlacierJobDescription (Maybe Text) gjdCreationDate = lens _gjdCreationDate (\s a -> s { _gjdCreationDate = a }) -- | Parameters used for range inventory retrieval. gjdInventoryRetrievalParameters :: Lens' GlacierJobDescription (Maybe InventoryRetrievalJobDescription) gjdInventoryRetrievalParameters = lens _gjdInventoryRetrievalParameters (\s a -> s { _gjdInventoryRetrievalParameters = a }) -- | For an InventoryRetrieval job, this is the size in bytes of the inventory -- requested for download. For the ArchiveRetrieval job, the value is null. gjdInventorySizeInBytes :: Lens' GlacierJobDescription (Maybe Integer) gjdInventorySizeInBytes = lens _gjdInventorySizeInBytes (\s a -> s { _gjdInventorySizeInBytes = a }) -- | The job description you provided when you initiated the job. gjdJobDescription :: Lens' GlacierJobDescription (Maybe Text) gjdJobDescription = lens _gjdJobDescription (\s a -> s { _gjdJobDescription = a }) -- | An opaque string that identifies an Amazon Glacier job. gjdJobId :: Lens' GlacierJobDescription (Maybe Text) gjdJobId = lens _gjdJobId (\s a -> s { _gjdJobId = a }) -- | The retrieved byte range for archive retrieval jobs in the form "/StartByteValue/-/EndByteValue/" If no range was specified in the archive retrieval, then the -- whole archive is retrieved and /StartByteValue/ equals 0 and /EndByteValue/ -- equals the size of the archive minus 1. For inventory retrieval jobs this -- field is null. gjdRetrievalByteRange :: Lens' GlacierJobDescription (Maybe Text) gjdRetrievalByteRange = lens _gjdRetrievalByteRange (\s a -> s { _gjdRetrievalByteRange = a }) -- | For an ArchiveRetrieval job, it is the checksum of the archive. Otherwise, -- the value is null. -- -- The SHA256 tree hash value for the requested range of an archive. If the -- Initiate a Job request for an archive specified a tree-hash aligned range, -- then this field returns a value. -- -- For the specific case when the whole archive is retrieved, this value is -- the same as the ArchiveSHA256TreeHash value. -- -- This field is null in the following situations: Archive retrieval jobs -- that specify a range that is not tree-hash aligned. -- -- Archival jobs that specify a range that is equal to the whole archive and -- the job status is InProgress. -- -- Inventory jobs. -- -- gjdSHA256TreeHash :: Lens' GlacierJobDescription (Maybe Text) gjdSHA256TreeHash = lens _gjdSHA256TreeHash (\s a -> s { _gjdSHA256TreeHash = a }) -- | An Amazon Simple Notification Service (Amazon SNS) topic that receives -- notification. gjdSNSTopic :: Lens' GlacierJobDescription (Maybe Text) gjdSNSTopic = lens _gjdSNSTopic (\s a -> s { _gjdSNSTopic = a }) -- | The status code can be InProgress, Succeeded, or Failed, and indicates the -- status of the job. gjdStatusCode :: Lens' GlacierJobDescription (Maybe StatusCode) gjdStatusCode = lens _gjdStatusCode (\s a -> s { _gjdStatusCode = a }) -- | A friendly message that describes the job status. gjdStatusMessage :: Lens' GlacierJobDescription (Maybe Text) gjdStatusMessage = lens _gjdStatusMessage (\s a -> s { _gjdStatusMessage = a }) -- | The Amazon Resource Name (ARN) of the vault from which the archive retrieval -- was requested. gjdVaultARN :: Lens' GlacierJobDescription (Maybe Text) gjdVaultARN = lens _gjdVaultARN (\s a -> s { _gjdVaultARN = a }) instance FromJSON GlacierJobDescription where parseJSON = withObject "GlacierJobDescription" $ \o -> GlacierJobDescription <$> o .:? "Action" <*> o .:? "ArchiveId" <*> o .:? "ArchiveSHA256TreeHash" <*> o .:? "ArchiveSizeInBytes" <*> o .:? "Completed" <*> o .:? "CompletionDate" <*> o .:? "CreationDate" <*> o .:? "InventoryRetrievalParameters" <*> o .:? "InventorySizeInBytes" <*> o .:? "JobDescription" <*> o .:? "JobId" <*> o .:? "RetrievalByteRange" <*> o .:? "SHA256TreeHash" <*> o .:? "SNSTopic" <*> o .:? "StatusCode" <*> o .:? "StatusMessage" <*> o .:? "VaultARN" instance ToJSON GlacierJobDescription where toJSON GlacierJobDescription{..} = object [ "JobId" .= _gjdJobId , "JobDescription" .= _gjdJobDescription , "Action" .= _gjdAction , "ArchiveId" .= _gjdArchiveId , "VaultARN" .= _gjdVaultARN , "CreationDate" .= _gjdCreationDate , "Completed" .= _gjdCompleted , "StatusCode" .= _gjdStatusCode , "StatusMessage" .= _gjdStatusMessage , "ArchiveSizeInBytes" .= _gjdArchiveSizeInBytes , "InventorySizeInBytes" .= _gjdInventorySizeInBytes , "SNSTopic" .= _gjdSNSTopic , "CompletionDate" .= _gjdCompletionDate , "SHA256TreeHash" .= _gjdSHA256TreeHash , "ArchiveSHA256TreeHash" .= _gjdArchiveSHA256TreeHash , "RetrievalByteRange" .= _gjdRetrievalByteRange , "InventoryRetrievalParameters" .= _gjdInventoryRetrievalParameters ] newtype VaultAccessPolicy = VaultAccessPolicy { _vapPolicy :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'VaultAccessPolicy' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'vapPolicy' @::@ 'Maybe' 'Text' -- vaultAccessPolicy :: VaultAccessPolicy vaultAccessPolicy = VaultAccessPolicy { _vapPolicy = Nothing } -- | The vault access policy. vapPolicy :: Lens' VaultAccessPolicy (Maybe Text) vapPolicy = lens _vapPolicy (\s a -> s { _vapPolicy = a }) instance FromJSON VaultAccessPolicy where parseJSON = withObject "VaultAccessPolicy" $ \o -> VaultAccessPolicy <$> o .:? "Policy" instance ToJSON VaultAccessPolicy where toJSON VaultAccessPolicy{..} = object [ "Policy" .= _vapPolicy ] data StatusCode = Failed -- ^ Failed | InProgress -- ^ InProgress | Succeeded -- ^ Succeeded deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable StatusCode instance FromText StatusCode where parser = takeLowerText >>= \case "failed" -> pure Failed "inprogress" -> pure InProgress "succeeded" -> pure Succeeded e -> fail $ "Failure parsing StatusCode from " ++ show e instance ToText StatusCode where toText = \case Failed -> "Failed" InProgress -> "InProgress" Succeeded -> "Succeeded" instance ToByteString StatusCode instance ToHeader StatusCode instance ToQuery StatusCode instance FromJSON StatusCode where parseJSON = parseJSONText "StatusCode" instance ToJSON StatusCode where toJSON = toJSONText
romanb/amazonka
amazonka-glacier/gen/Network/AWS/Glacier/Types.hs
mpl-2.0
41,145
0
41
9,607
6,455
3,711
2,744
-1
-1
{-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} module X_3 where import Data.List import Data.Map.Strict as Map import Debug.Trace import Test.HUnit (Counts, Test (TestList), runTestTT) import qualified Test.HUnit.Util as U (tt) ------------------------------------------------------------------------------ -- Works with either import (one at a time, of course) -- import X_1 import X_2 -- | preserves names -- rewrites let bindings desugarTop :: ExpLet a -> ExpAnn a desugarTop = desugar Map.empty desugar :: Map.Map String Int -> ExpLet a -> ExpAnn a desugar env expr = case expr of LitLet a -> LitAnn a VarLet name -> VarAnn name (env Map.! name) AbsLet name expr' -> let env' = Map.map succ env env'' = Map.insert name 0 env' in AbsAnn name (desugar env'' expr') AppLet f x -> AppAnn (desugar env f) (desugar env x) LetLet n v expr' -> desugar env (AppLet (AbsLet n expr') v) _ -> error "impossible?" desugarTop' :: ExpLet a -> ExpAnn a desugarTop' = desugar' [] desugar' :: [String] -> ExpLet a -> ExpAnn a desugar' env expr = case expr of LitLet a -> LitAnn a VarLet name -> VarAnn name (fromJust (name `elemIndex` reverse env)) AbsLet name expr' -> AbsAnn name (desugar' (name:env) expr') AppLet f x -> AppAnn (desugar' env f) (desugar' env x) LetLet n v expr' -> desugar' env (AppLet (AbsLet n expr') v) _ -> error "impossible?" fromJust :: Num p => Maybe p -> p fromJust Nothing = -1 fromJust (Just i) = i -- | removes names anonymize :: ExpAnn a -> ExpUD a anonymize expr = case expr of LitAnn a -> LitUD a VarAnn _ i -> VarUD i AbsAnn _ e -> AbsUD (anonymize e) AppAnn f x -> AppUD (anonymize f) (anonymize x) _ -> error "impossible?" -- | operates on undecorated expressions eval :: Show a => [a] -> ExpUD a -> a eval env expr = case expr of LitUD a -> a VarUD i -> trace (show env ++ " " ++ show i) (env !! i) AbsUD f -> eval env f AppUD f x -> let x' = eval env x in eval (x':env) f _ -> error "impossible?" ------------------------------------------------------------------------------ -- summary -- - composable compiler passes : smaller, easier to write and to think about ------------------------------------------------------------------------------ tidentity :: [Test] tidentity = U.tt "tidentity" -- |identity | [ eval [] (anonymize (desugarTop (AppLet (AbsLet "i" (VarLet "i")) (LitLet 1)))) , eval [] (anonymize (AppAnn (AbsAnn "i" (VarAnn "i" 0)) (LitAnn 1))) , eval [] (AppUD (AbsUD (VarUD 0)) (LitUD 1)) -- wrapped with an ignored Let value , eval [] (anonymize (desugarTop (LetLet "x" (LitLet 1) (AppLet (AbsLet "i" (VarLet "i")) (VarLet "x"))))) -- wrapped with an ignored "desugared" Let value , eval [] (anonymize (desugarTop (ExpX ( "x" , LitLet 1 , AppLet (AbsLet "i" (VarLet "i")) (VarLet "x") )))) ] 1 {-# ANN konstH "HLint: ignore Use const" #-} {-# ANN konstH "HLint: ignore Redundant lambda" #-} {-# ANN konstH' "HLint: ignore Use id" #-} {-# ANN konstH' "HLint: ignore Redundant lambda" #-} konstH :: a -> b -> a konstH x = \_ -> x konstH' :: a -> b -> b konstH' _ = \y -> y konst :: ExpLet a konst = AbsLet "x" (AbsLet "y" (VarLet "x")) konst3Xyz,konst3xYz,konst3xyZ,konst3xyX :: ExpLet a konst3Xyz = AbsLet "x" (AbsLet "y" (AbsLet "z" (VarLet "x"))) konst3xYz = AbsLet "x" (AbsLet "y" (AbsLet "z" (VarLet "y"))) konst3xyZ = AbsLet "x" (AbsLet "y" (AbsLet "z" (VarLet "z"))) konst3xyX = AbsLet "x" (AbsLet "y" (AbsLet "x" (VarLet "x"))) konst' :: ExpLet a konst' = AbsLet "y" (AbsLet "x" (VarLet "x")) tkonst :: [Test] tkonst = U.tt "tkonst" [ eval [] (anonymize (desugarTop (AppLet (AppLet konst (LitLet 1)) (LitLet 2)))) , eval [] (anonymize (desugarTop (AppLet (AppLet (AbsLet "x" (AbsLet "y" (VarLet "x"))) (LitLet 1)) (LitLet 2)))) , eval [] (anonymize (AppAnn (AppAnn (AbsAnn "x" (AbsAnn "y" (VarAnn "x" 1))) (LitAnn 1)) (LitAnn 2))) , eval [] (AppUD (AppUD (AbsUD (AbsUD (VarUD 1))) (LitUD 1)) (LitUD 2)) ] 2 tkonst3 :: [Test] tkonst3 = U.tt "tkonst3" [ eval [] (anonymize (desugarTop' (AppLet (AppLet (AppLet konst3Xyz (LitLet 1)) (LitLet 2)) (LitLet 3)))) , eval [] (anonymize (desugarTop' (AppLet (AppLet (AppLet konst3xYz (LitLet 2)) (LitLet 1)) (LitLet 3)))) , eval [] (anonymize (desugarTop' (AppLet (AppLet (AppLet konst3xyZ (LitLet 3)) (LitLet 2)) (LitLet 1)))) -- not sure about this one: , eval [] (anonymize (desugarTop' (AppLet (AppLet (AppLet konst3xyX (LitLet 1)) (LitLet 2)) (LitLet 3)))) ] 1 test :: IO Counts test = runTestTT $ TestList $ tidentity ++ tkonst ++ tkonst3
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/trees-that-grow-and-shrink/2018-06-vaibhav-sagar-trees-that-shrink/X_3.hs
unlicense
5,978
0
21
2,221
1,944
981
963
138
6
ans :: [[Int]] -> [Int] ans ([0]:_) = [] ans ([k]:l:xs) = let d = k - 1 a = sum l in (a`div`d):ans xs main = do c <- getContents let i = map (map read) $ map words $ lines c :: [[Int]] o = ans i mapM_ print o
a143753/AOJ
1027.hs
apache-2.0
287
0
14
130
169
87
82
11
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QDial.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:15 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QDial ( QqDial(..) ,notchSize ,notchesVisible ,QsetNotchesVisible(..) ,qDial_delete ,qDial_deleteLater ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QAbstractSlider import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QDial ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QDial_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QDial_userMethod" qtc_QDial_userMethod :: Ptr (TQDial a) -> CInt -> IO () instance QuserMethod (QDialSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QDial_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QDial ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QDial_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QDial_userMethodVariant" qtc_QDial_userMethodVariant :: Ptr (TQDial a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QDialSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QDial_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqDial x1 where qDial :: x1 -> IO (QDial ()) instance QqDial (()) where qDial () = withQDialResult $ qtc_QDial foreign import ccall "qtc_QDial" qtc_QDial :: IO (Ptr (TQDial ())) instance QqDial ((QWidget t1)) where qDial (x1) = withQDialResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QDial1 cobj_x1 foreign import ccall "qtc_QDial1" qtc_QDial1 :: Ptr (TQWidget t1) -> IO (Ptr (TQDial ())) instance Qevent (QDial ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_event_h" qtc_QDial_event_h :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QDialSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_event_h cobj_x0 cobj_x1 instance QinitStyleOption (QDial ()) ((QStyleOptionSlider t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_initStyleOption cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_initStyleOption" qtc_QDial_initStyleOption :: Ptr (TQDial a) -> Ptr (TQStyleOptionSlider t1) -> IO () instance QinitStyleOption (QDialSc a) ((QStyleOptionSlider t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_initStyleOption cobj_x0 cobj_x1 instance QqminimumSizeHint (QDial ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QDial_minimumSizeHint_h" qtc_QDial_minimumSizeHint_h :: Ptr (TQDial a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QDialSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QDial ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDial_minimumSizeHint_qth_h" qtc_QDial_minimumSizeHint_qth_h :: Ptr (TQDial a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QDialSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QmouseMoveEvent (QDial ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_mouseMoveEvent_h" qtc_QDial_mouseMoveEvent_h :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QDialSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QDial ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_mousePressEvent_h" qtc_QDial_mousePressEvent_h :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QDialSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QDial ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_mouseReleaseEvent_h" qtc_QDial_mouseReleaseEvent_h :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QDialSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseReleaseEvent_h cobj_x0 cobj_x1 notchSize :: QDial a -> (()) -> IO (Int) notchSize x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_notchSize cobj_x0 foreign import ccall "qtc_QDial_notchSize" qtc_QDial_notchSize :: Ptr (TQDial a) -> IO CInt instance QnotchTarget (QDial a) (()) where notchTarget x0 () = withDoubleResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_notchTarget cobj_x0 foreign import ccall "qtc_QDial_notchTarget" qtc_QDial_notchTarget :: Ptr (TQDial a) -> IO CDouble notchesVisible :: QDial a -> (()) -> IO (Bool) notchesVisible x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_notchesVisible cobj_x0 foreign import ccall "qtc_QDial_notchesVisible" qtc_QDial_notchesVisible :: Ptr (TQDial a) -> IO CBool instance QpaintEvent (QDial ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_paintEvent_h" qtc_QDial_paintEvent_h :: Ptr (TQDial a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QDialSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_paintEvent_h cobj_x0 cobj_x1 instance QresizeEvent (QDial ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_resizeEvent_h" qtc_QDial_resizeEvent_h :: Ptr (TQDial a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QDialSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_resizeEvent_h cobj_x0 cobj_x1 instance QsetNotchTarget (QDial a) ((Double)) where setNotchTarget x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setNotchTarget cobj_x0 (toCDouble x1) foreign import ccall "qtc_QDial_setNotchTarget" qtc_QDial_setNotchTarget :: Ptr (TQDial a) -> CDouble -> IO () class QsetNotchesVisible x0 x1 where setNotchesVisible :: x0 -> x1 -> IO () instance QsetNotchesVisible (QDial ()) ((Bool)) where setNotchesVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setNotchesVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_setNotchesVisible_h" qtc_QDial_setNotchesVisible_h :: Ptr (TQDial a) -> CBool -> IO () instance QsetNotchesVisible (QDialSc a) ((Bool)) where setNotchesVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setNotchesVisible_h cobj_x0 (toCBool x1) instance QsetWrapping (QDial ()) ((Bool)) where setWrapping x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setWrapping_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_setWrapping_h" qtc_QDial_setWrapping_h :: Ptr (TQDial a) -> CBool -> IO () instance QsetWrapping (QDialSc a) ((Bool)) where setWrapping x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setWrapping_h cobj_x0 (toCBool x1) instance QqsizeHint (QDial ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sizeHint_h cobj_x0 foreign import ccall "qtc_QDial_sizeHint_h" qtc_QDial_sizeHint_h :: Ptr (TQDial a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QDialSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sizeHint_h cobj_x0 instance QsizeHint (QDial ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDial_sizeHint_qth_h" qtc_QDial_sizeHint_qth_h :: Ptr (TQDial a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QDialSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QsliderChange (QDial ()) ((SliderChange)) where sliderChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sliderChange_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDial_sliderChange_h" qtc_QDial_sliderChange_h :: Ptr (TQDial a) -> CLong -> IO () instance QsliderChange (QDialSc a) ((SliderChange)) where sliderChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sliderChange_h cobj_x0 (toCLong $ qEnum_toInt x1) instance Qwrapping (QDial a) (()) where wrapping x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_wrapping cobj_x0 foreign import ccall "qtc_QDial_wrapping" qtc_QDial_wrapping :: Ptr (TQDial a) -> IO CBool qDial_delete :: QDial a -> IO () qDial_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_delete cobj_x0 foreign import ccall "qtc_QDial_delete" qtc_QDial_delete :: Ptr (TQDial a) -> IO () qDial_deleteLater :: QDial a -> IO () qDial_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_deleteLater cobj_x0 foreign import ccall "qtc_QDial_deleteLater" qtc_QDial_deleteLater :: Ptr (TQDial a) -> IO () instance QchangeEvent (QDial ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_changeEvent_h" qtc_QDial_changeEvent_h :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QDialSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_changeEvent_h cobj_x0 cobj_x1 instance QkeyPressEvent (QDial ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_keyPressEvent_h" qtc_QDial_keyPressEvent_h :: Ptr (TQDial a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QDialSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_keyPressEvent_h cobj_x0 cobj_x1 instance QrepeatAction (QDial ()) (()) where repeatAction x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_repeatAction cobj_x0 foreign import ccall "qtc_QDial_repeatAction" qtc_QDial_repeatAction :: Ptr (TQDial a) -> IO CLong instance QrepeatAction (QDialSc a) (()) where repeatAction x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_repeatAction cobj_x0 instance QsetRepeatAction (QDial ()) ((SliderAction)) where setRepeatAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setRepeatAction cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDial_setRepeatAction" qtc_QDial_setRepeatAction :: Ptr (TQDial a) -> CLong -> IO () instance QsetRepeatAction (QDialSc a) ((SliderAction)) where setRepeatAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setRepeatAction cobj_x0 (toCLong $ qEnum_toInt x1) instance QsetRepeatAction (QDial ()) ((SliderAction, Int)) where setRepeatAction x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setRepeatAction1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2) foreign import ccall "qtc_QDial_setRepeatAction1" qtc_QDial_setRepeatAction1 :: Ptr (TQDial a) -> CLong -> CInt -> IO () instance QsetRepeatAction (QDialSc a) ((SliderAction, Int)) where setRepeatAction x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setRepeatAction1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2) instance QsetRepeatAction (QDial ()) ((SliderAction, Int, Int)) where setRepeatAction x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setRepeatAction2 cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2) (toCInt x3) foreign import ccall "qtc_QDial_setRepeatAction2" qtc_QDial_setRepeatAction2 :: Ptr (TQDial a) -> CLong -> CInt -> CInt -> IO () instance QsetRepeatAction (QDialSc a) ((SliderAction, Int, Int)) where setRepeatAction x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setRepeatAction2 cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2) (toCInt x3) instance QtimerEvent (QDial ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_timerEvent" qtc_QDial_timerEvent :: Ptr (TQDial a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QDialSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_timerEvent cobj_x0 cobj_x1 instance QwheelEvent (QDial ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_wheelEvent_h" qtc_QDial_wheelEvent_h :: Ptr (TQDial a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QDialSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_wheelEvent_h cobj_x0 cobj_x1 instance QactionEvent (QDial ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_actionEvent_h" qtc_QDial_actionEvent_h :: Ptr (TQDial a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QDialSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QDial ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_addAction" qtc_QDial_addAction :: Ptr (TQDial a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QDialSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_addAction cobj_x0 cobj_x1 instance QcloseEvent (QDial ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_closeEvent_h" qtc_QDial_closeEvent_h :: Ptr (TQDial a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QDialSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_closeEvent_h cobj_x0 cobj_x1 instance QcontextMenuEvent (QDial ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_contextMenuEvent_h" qtc_QDial_contextMenuEvent_h :: Ptr (TQDial a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QDialSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_contextMenuEvent_h cobj_x0 cobj_x1 instance Qcreate (QDial ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_create cobj_x0 foreign import ccall "qtc_QDial_create" qtc_QDial_create :: Ptr (TQDial a) -> IO () instance Qcreate (QDialSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_create cobj_x0 instance Qcreate (QDial ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_create1" qtc_QDial_create1 :: Ptr (TQDial a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QDialSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_create1 cobj_x0 cobj_x1 instance Qcreate (QDial ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QDial_create2" qtc_QDial_create2 :: Ptr (TQDial a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QDialSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QDial ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QDial_create3" qtc_QDial_create3 :: Ptr (TQDial a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QDialSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QDial ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_destroy cobj_x0 foreign import ccall "qtc_QDial_destroy" qtc_QDial_destroy :: Ptr (TQDial a) -> IO () instance Qdestroy (QDialSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_destroy cobj_x0 instance Qdestroy (QDial ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_destroy1" qtc_QDial_destroy1 :: Ptr (TQDial a) -> CBool -> IO () instance Qdestroy (QDialSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QDial ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QDial_destroy2" qtc_QDial_destroy2 :: Ptr (TQDial a) -> CBool -> CBool -> IO () instance Qdestroy (QDialSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QDial ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_devType_h cobj_x0 foreign import ccall "qtc_QDial_devType_h" qtc_QDial_devType_h :: Ptr (TQDial a) -> IO CInt instance QdevType (QDialSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_devType_h cobj_x0 instance QdragEnterEvent (QDial ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_dragEnterEvent_h" qtc_QDial_dragEnterEvent_h :: Ptr (TQDial a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QDialSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QDial ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_dragLeaveEvent_h" qtc_QDial_dragLeaveEvent_h :: Ptr (TQDial a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QDialSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QDial ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_dragMoveEvent_h" qtc_QDial_dragMoveEvent_h :: Ptr (TQDial a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QDialSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QDial ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_dropEvent_h" qtc_QDial_dropEvent_h :: Ptr (TQDial a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QDialSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dropEvent_h cobj_x0 cobj_x1 instance QenabledChange (QDial ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_enabledChange" qtc_QDial_enabledChange :: Ptr (TQDial a) -> CBool -> IO () instance QenabledChange (QDialSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QDial ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_enterEvent_h" qtc_QDial_enterEvent_h :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QDialSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_enterEvent_h cobj_x0 cobj_x1 instance QfocusInEvent (QDial ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_focusInEvent_h" qtc_QDial_focusInEvent_h :: Ptr (TQDial a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QDialSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_focusInEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QDial ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_focusNextChild cobj_x0 foreign import ccall "qtc_QDial_focusNextChild" qtc_QDial_focusNextChild :: Ptr (TQDial a) -> IO CBool instance QfocusNextChild (QDialSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_focusNextChild cobj_x0 instance QfocusNextPrevChild (QDial ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_focusNextPrevChild" qtc_QDial_focusNextPrevChild :: Ptr (TQDial a) -> CBool -> IO CBool instance QfocusNextPrevChild (QDialSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusOutEvent (QDial ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_focusOutEvent_h" qtc_QDial_focusOutEvent_h :: Ptr (TQDial a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QDialSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_focusOutEvent_h cobj_x0 cobj_x1 instance QfocusPreviousChild (QDial ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_focusPreviousChild cobj_x0 foreign import ccall "qtc_QDial_focusPreviousChild" qtc_QDial_focusPreviousChild :: Ptr (TQDial a) -> IO CBool instance QfocusPreviousChild (QDialSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_focusPreviousChild cobj_x0 instance QfontChange (QDial ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_fontChange" qtc_QDial_fontChange :: Ptr (TQDial a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QDialSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QDial ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QDial_heightForWidth_h" qtc_QDial_heightForWidth_h :: Ptr (TQDial a) -> CInt -> IO CInt instance QheightForWidth (QDialSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_heightForWidth_h cobj_x0 (toCInt x1) instance QhideEvent (QDial ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_hideEvent_h" qtc_QDial_hideEvent_h :: Ptr (TQDial a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QDialSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_hideEvent_h cobj_x0 cobj_x1 instance QinputMethodEvent (QDial ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_inputMethodEvent" qtc_QDial_inputMethodEvent :: Ptr (TQDial a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QDialSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QDial ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDial_inputMethodQuery_h" qtc_QDial_inputMethodQuery_h :: Ptr (TQDial a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QDialSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent (QDial ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_keyReleaseEvent_h" qtc_QDial_keyReleaseEvent_h :: Ptr (TQDial a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QDialSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_keyReleaseEvent_h cobj_x0 cobj_x1 instance QlanguageChange (QDial ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_languageChange cobj_x0 foreign import ccall "qtc_QDial_languageChange" qtc_QDial_languageChange :: Ptr (TQDial a) -> IO () instance QlanguageChange (QDialSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_languageChange cobj_x0 instance QleaveEvent (QDial ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_leaveEvent_h" qtc_QDial_leaveEvent_h :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QDialSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QDial ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDial_metric" qtc_QDial_metric :: Ptr (TQDial a) -> CLong -> IO CInt instance Qmetric (QDialSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance QmouseDoubleClickEvent (QDial ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_mouseDoubleClickEvent_h" qtc_QDial_mouseDoubleClickEvent_h :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QDialSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance Qmove (QDial ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDial_move1" qtc_QDial_move1 :: Ptr (TQDial a) -> CInt -> CInt -> IO () instance Qmove (QDialSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QDial ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QDial_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QDial_move_qth" qtc_QDial_move_qth :: Ptr (TQDial a) -> CInt -> CInt -> IO () instance Qmove (QDialSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QDial_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QDial ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_move cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_move" qtc_QDial_move :: Ptr (TQDial a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QDialSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_move cobj_x0 cobj_x1 instance QmoveEvent (QDial ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_moveEvent_h" qtc_QDial_moveEvent_h :: Ptr (TQDial a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QDialSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QDial ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_paintEngine_h cobj_x0 foreign import ccall "qtc_QDial_paintEngine_h" qtc_QDial_paintEngine_h :: Ptr (TQDial a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QDialSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_paintEngine_h cobj_x0 instance QpaletteChange (QDial ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_paletteChange" qtc_QDial_paletteChange :: Ptr (TQDial a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QDialSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QDial ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_repaint cobj_x0 foreign import ccall "qtc_QDial_repaint" qtc_QDial_repaint :: Ptr (TQDial a) -> IO () instance Qrepaint (QDialSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_repaint cobj_x0 instance Qrepaint (QDial ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QDial_repaint2" qtc_QDial_repaint2 :: Ptr (TQDial a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QDialSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QDial ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_repaint1" qtc_QDial_repaint1 :: Ptr (TQDial a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QDialSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QDial ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_resetInputContext cobj_x0 foreign import ccall "qtc_QDial_resetInputContext" qtc_QDial_resetInputContext :: Ptr (TQDial a) -> IO () instance QresetInputContext (QDialSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_resetInputContext cobj_x0 instance Qresize (QDial ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDial_resize1" qtc_QDial_resize1 :: Ptr (TQDial a) -> CInt -> CInt -> IO () instance Qresize (QDialSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QDial ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_resize" qtc_QDial_resize :: Ptr (TQDial a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QDialSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_resize cobj_x0 cobj_x1 instance Qresize (QDial ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QDial_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QDial_resize_qth" qtc_QDial_resize_qth :: Ptr (TQDial a) -> CInt -> CInt -> IO () instance Qresize (QDialSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QDial_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QsetGeometry (QDial ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QDial_setGeometry1" qtc_QDial_setGeometry1 :: Ptr (TQDial a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QDialSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QDial ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_setGeometry" qtc_QDial_setGeometry :: Ptr (TQDial a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QDialSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QDial ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QDial_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QDial_setGeometry_qth" qtc_QDial_setGeometry_qth :: Ptr (TQDial a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QDialSc a) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QDial_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QDial ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_setMouseTracking" qtc_QDial_setMouseTracking :: Ptr (TQDial a) -> CBool -> IO () instance QsetMouseTracking (QDialSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setMouseTracking cobj_x0 (toCBool x1) instance QsetVisible (QDial ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_setVisible_h" qtc_QDial_setVisible_h :: Ptr (TQDial a) -> CBool -> IO () instance QsetVisible (QDialSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setVisible_h cobj_x0 (toCBool x1) instance QshowEvent (QDial ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_showEvent_h" qtc_QDial_showEvent_h :: Ptr (TQDial a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QDialSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_showEvent_h cobj_x0 cobj_x1 instance QtabletEvent (QDial ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_tabletEvent_h" qtc_QDial_tabletEvent_h :: Ptr (TQDial a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QDialSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QDial ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_updateMicroFocus cobj_x0 foreign import ccall "qtc_QDial_updateMicroFocus" qtc_QDial_updateMicroFocus :: Ptr (TQDial a) -> IO () instance QupdateMicroFocus (QDialSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_updateMicroFocus cobj_x0 instance QwindowActivationChange (QDial ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_windowActivationChange" qtc_QDial_windowActivationChange :: Ptr (TQDial a) -> CBool -> IO () instance QwindowActivationChange (QDialSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QDial ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_childEvent" qtc_QDial_childEvent :: Ptr (TQDial a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QDialSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QDial ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDial_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QDial_connectNotify" qtc_QDial_connectNotify :: Ptr (TQDial a) -> CWString -> IO () instance QconnectNotify (QDialSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDial_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QDial ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_customEvent" qtc_QDial_customEvent :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QDialSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QDial ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDial_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QDial_disconnectNotify" qtc_QDial_disconnectNotify :: Ptr (TQDial a) -> CWString -> IO () instance QdisconnectNotify (QDialSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDial_disconnectNotify cobj_x0 cstr_x1 instance QeventFilter (QDial ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDial_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QDial_eventFilter_h" qtc_QDial_eventFilter_h :: Ptr (TQDial a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QDialSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDial_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QDial ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDial_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QDial_receivers" qtc_QDial_receivers :: Ptr (TQDial a) -> CWString -> IO CInt instance Qreceivers (QDialSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDial_receivers cobj_x0 cstr_x1 instance Qsender (QDial ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sender cobj_x0 foreign import ccall "qtc_QDial_sender" qtc_QDial_sender :: Ptr (TQDial a) -> IO (Ptr (TQObject ())) instance Qsender (QDialSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sender cobj_x0
uduki/hsQt
Qtc/Gui/QDial.hs
bsd-2-clause
45,334
0
14
7,876
15,927
8,087
7,840
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Config (AppConfig(..), config, defaultConfig) where import qualified Data.Configurator as C import Data.Configurator.Types import Control.Exception (catch) import Data.Text (unpack) import Options data AppOptions = AppOptions { configPath :: String } data AppConfig = AppConfig { repositoryPath :: String, repositoryBaseUrl :: String, rsyncBasePath :: String, snapshotSyncPeriod :: Int, oldDataRetainPeriod :: Int, appPort :: Int, rsyncRepoMap :: [(String, String)] } deriving (Show) defaultConfig :: AppConfig defaultConfig = AppConfig { repositoryPath = "./test-repo/rrdp", repositoryBaseUrl = "http://localhost:19999/test-repo", rsyncBasePath = "./test-repo", snapshotSyncPeriod = 10, oldDataRetainPeriod = 3600, appPort = 19999, rsyncRepoMap = [("rsync://test.url/", "test.url")] } config :: AppOptions -> IO (Either String AppConfig) config (AppOptions confPath) = readConfig `catch` catchError where readConfig = do conf <- C.load [C.Required confPath] port <- C.lookupDefault 19999 conf "port" repoPath <- C.require conf "repository.rrdpPath" repoBaseUrl <- C.require conf "repository.baseUrl" rsyncPath <- C.require conf "repository.rsync.basePath" urlMapping <- C.require conf "repository.rsync.urlMapping" syncPeriod <- C.lookupDefault 10 conf "snaphotSyncPeriod" retainPeriod <- C.lookupDefault 3600 conf "oldDataRetainPeriod" return $ Right AppConfig { repositoryPath = repoPath, repositoryBaseUrl = repoBaseUrl, rsyncBasePath = rsyncPath, snapshotSyncPeriod = syncPeriod, oldDataRetainPeriod = retainPeriod, appPort = port, rsyncRepoMap = urlMapping } catchError :: KeyError -> IO (Either String AppConfig) catchError (KeyError key) = return $ Left $ unpack key ++ " must be defined" instance Options AppOptions where defineOptions = pure AppOptions <*> simpleOption "config-path" "rpki-pub-server.conf" "Path to the config file"
lolepezy/rpki-pub-server
src/Config.hs
bsd-2-clause
2,204
0
13
542
503
280
223
51
1
module Raven.ParserSpec ( spec ) where import Test.Tasty.Hspec import Test.QuickCheck import Test.Hspec.Megaparsec import Text.Megaparsec hiding (parse, string) import Raven.Types import Raven.Parser spec :: Spec spec = describe "Parser" $ do describe "parsing bools" $ do it "should be able to parse true and false" $ do parse bool "true" `shouldParse` (RavenLiteral $ RavenBool True) parse bool "false" `shouldParse` (RavenLiteral $ RavenBool False) it "should fail to parse invalid input" $ do parse bool `shouldFailOn` "truf" parse bool `shouldFailOn` "fals" parse bool `shouldFailOn` "" parse bool `shouldFailOn` " " describe "parsing strings" $ do it "should be able to parse valid strings" $ do let checkStr a b = parse string a `shouldParse` (RavenLiteral $ RavenString b) checkStr "\"\"" "" checkStr "\"a\"" "a" checkStr "\"ab\"" "ab" checkStr "\"a b\"" "a b" checkStr "\"a b\"" "a b" it "should be able to parse escape characters" $ do let checkStr a b = parse string a `shouldParse` (RavenLiteral $ RavenString b) checkStr "\"a\r\n\t\b\v\\\'b\"" "a\r\n\t\b\v\\\'b" it "should fail to parse invalid input" $ do let checkFailStr a = parse string `shouldFailOn` a checkFailStr "" checkFailStr "\"" checkFailStr "\"a" checkFailStr "a\"" describe "parsing comments" $ do it "should be able to parse valid comments" $ do parse number "1 ; comment\n" `shouldParse` (RavenLiteral . RavenNumber $ RavenIntegral 1) parse define "(def a ; comment goes here\n 3)" `shouldParse` (RavenDefine "a" (RavenLiteral . RavenNumber $ RavenIntegral 3)) parse number "1 ;; more comments\n" `shouldParse` (RavenLiteral . RavenNumber $ RavenIntegral 1) describe "parsing identifiers" $ do it "should be able to parse valid identifiers" $ do let checkIdent a = parse identifier a `shouldParse` a checkIdent "lambda" checkIdent "list->vector" checkIdent "+" checkIdent "<=?" checkIdent "the-word-recursion-has-many-meanings" checkIdent "q" checkIdent "soup" checkIdent "V17a" checkIdent "a34kTMNs" checkIdent "-" checkIdent "..." checkIdent "a!$%&*+-./:<=>?@^_~" it "should fail to parse invalid identifiers" $ do let checkFailIdent a = parse identifier `shouldFailOn` a checkFailIdent "1" checkFailIdent "1.0a" checkFailIdent "." checkFailIdent ".." describe "parsing symbols" $ do it "should be able to parse valid symbols" $ do let checkSymbol a b = parse symbol a `shouldParse` (RavenLiteral $ RavenSymbol b) checkSymbol "'a" "a" checkSymbol "'ab" "ab" checkSymbol "'a1" "a1" checkSymbol "'a+-.*/<=>!?$%_&^~" "a+-.*/<=>!?$%_&^~" it "should fail to parse invalid symbols" $ do let checkFailSymbol a = parse symbol `shouldFailOn` a checkFailSymbol "1" checkFailSymbol "1a" checkFailSymbol "1\n" checkFailSymbol "!" describe "parsing variables" $ do it "should be able to parse valid variables" $ do let checkVar a b = parse variable a `shouldParse` (RavenVariable b) checkVar "a" "a" checkVar "a123" "a123" it "should fail to parse invalid variables" $ do let checkFailVar a = parse variable `shouldFailOn` a checkFailVar "lambda" checkFailVar "true" checkFailVar "def" -- TODO check remaining keywords describe "parsing numbers" $ do it "should be able to parse (positive) decimal numbers" $ do let checkInt a b = parse number a `shouldParse` (RavenLiteral . RavenNumber . RavenIntegral $ b) checkInt "0" 0 checkInt "1" 1 checkInt "2" 2 checkInt "11" 11 -- NOTE: negative integers are represented as (- X) -> handled with a different parser it "should fail to parse invalid decimal numbers" $ do let checkFailInt a = parse number `shouldFailOn` a checkFailInt "-0" checkFailInt "-1" checkFailInt "a1" it "should be able to parse hexadecimal numbers" $ do let checkHex a b = parse number a `shouldParse` (RavenLiteral . RavenNumber . RavenIntegral $ b) checkHex "0x0" 0 checkHex "0x1" 1 checkHex "0x2" 2 checkHex "0xa" 0x0A checkHex "0xf" 0x0F checkHex "0xA" 0x0A checkHex "0x0F" 0x0F checkHex "0xFF" 0xFF it "should fail to parse invalid hexadecimal numbers" $ do let checkFailHex a = parse number `shouldFailOn` a checkFailHex "0x" checkFailHex "0x 0" checkFailHex "0xG" checkFailHex "0x.1" --checkFailHex "0x1.0" --checkFailHex "0x0.1" it "should be able to parse binary numbers" $ do let checkBin a b = parse number a `shouldParse` (RavenLiteral . RavenNumber . RavenIntegral $ b) checkBin "0b0" 0 checkBin "0b1" 1 checkBin "0b01" 1 checkBin "0b10" 2 checkBin "0b11" 3 checkBin "0b1000" 8 it "should fail to parse invalid binary numbers" $ do let checkFailBin a = parse number `shouldFailOn` a checkFailBin "0b" checkFailBin "0b 0" checkFailBin "0b2" checkFailBin "0b.1" --checkFailBin "0b1.0" it "should be able to parse rational numbers" $ do let checkRat a b c = parse number a `shouldParse` (RavenLiteral . RavenNumber $ RavenRational b c) checkRat "0/1" 0 1 checkRat "1/1" 1 1 checkRat "1/2" 1 2 checkRat "3/2" 3 2 checkRat "-3/2" (negate 3) 2 --it "should fail to parse invalid rational numbers" $ do --let checkFailRat a = parse number `shouldFailOn` a --checkFailRat "0.1/1" --checkFailRat "1i/1" --checkFailRat "1 / 1" --checkFailRat "1/ 1" --checkFailRat "1 /1" it "should be able to parse real (floating point) numbers" $ do let checkDouble a b = parse number a `shouldParse` (RavenLiteral . RavenNumber . RavenReal $ b) checkDouble "0.0" 0.0 checkDouble "0.1" 0.1 checkDouble "1.1" 1.1 checkDouble "1e3" 1000 checkDouble "1e-3" 0.001 -- NOTE: negative floats not checked here, represented as (- F) it "should fail to parse invalid real (floating point) numbers" $ do let checkFailDouble a = parse number `shouldFailOn` a checkFailDouble ".1" checkFailDouble "a.1" checkFailDouble ".a1" checkFailDouble "-1e3" it "should be able to parse complex numbers" $ do let checkComplex a b c = parse number a `shouldParse` (RavenLiteral . RavenNumber $ RavenComplex b c) let checkComplexI a b = checkComplex a 0 b checkComplexI "0i" 0 checkComplexI "0.1i" 0.1 checkComplexI "1i" 1 checkComplex "1+1i" 1 1 checkComplex "1+0.1i" 1 0.1 checkComplex "0.1+0.1i" 0.1 0.1 checkComplex "0.1-0.1i" 0.1 (negate 0.1) checkComplex "-0.1-0.1i" (negate 0.1) (negate 0.1) it "should fail to parse invalid complex numbers" $ do let checkFailComplex a = parse number `shouldFailOn` a checkFailComplex "i" checkFailComplex "ai" checkFailComplex ".1i" --checkFailComplex "1*1i" --checkFailComplex "1/1i" --checkFailComplex "0.1e3i" describe "parsing defines" $ do it "should be able to parse a valid define expression (no procedure)" $ do let checkDefine a b c = parse define a `shouldParse` RavenDefine b c checkDefine "(def a 3)" "a" (RavenLiteral . RavenNumber . RavenIntegral $ 3) checkDefine "(def b \"test\")" "b" (RavenLiteral . RavenString $ "test") checkDefine "(def a true)" "a" (RavenLiteral . RavenBool $ True) it "should be able to parse funcions defined with 'def'" $ do let makeFuncDef b c d = RavenDefine b (RavenFunction $ Function c d) let checkDefine a b c d = parse define a `shouldParse` (makeFuncDef b c d) let int = RavenLiteral . RavenNumber . RavenIntegral let var = RavenVariable let func a b c = RavenFunctionCall (var a) [var b, var c] checkDefine "(def (test-func) 1)" "test-func" [] [int 1] checkDefine "(def (test-func a) a)" "test-func" ["a"] [var "a"] checkDefine "(def (test-func a b) a)" "test-func" ["a", "b"] [var "a"] checkDefine "(def (test-func a b) (+ a b))" "test-func" ["a", "b"] [func "+" "a" "b"] it "should fail to parse invalid define expression" $ do let checkFailDefine a = parse define `shouldFailOn` a checkFailDefine "def a 3" checkFailDefine "(ef a 3)" checkFailDefine "(def a)" checkFailDefine "(def 3)" checkFailDefine "(def true false)" checkFailDefine "(def (test-func 1)" checkFailDefine "(def test-func) 1)" checkFailDefine "(def () 1)" describe "parsing function calls" $ do it "should be able to parse valid function calls" $ do let checkFunc a b c = parse functionCall a `shouldParse` (RavenFunctionCall b c) let op = RavenVariable -- TODO this should return a procedure/function let int = RavenLiteral . RavenNumber . RavenIntegral checkFunc "(test-func)" (op "test-func") [] checkFunc "(print \"test123\")" (op "print") [RavenLiteral . RavenString $ "test123"] checkFunc "(+ 1 2)" (op "+") (map int [1, 2]) checkFunc "(- 1 2 3)" (op "-") (map int [1, 2, 3]) it "should fail to parse invalid function call syntax" $ do let checkFailFunc a = parse functionCall `shouldFailOn` a checkFailFunc "()" checkFailFunc "(test-func" checkFailFunc "test-func)" describe "parsing lambdas" $ do it "should be able to parse valid lambdas" $ do let checkFunc a b c = parse lambda a `shouldParse` (RavenFunction $ Function b c) let var = RavenVariable let int = RavenLiteral . RavenNumber . RavenIntegral let func a b = RavenFunctionCall (RavenVariable a) b -- TODO this should be a procedure checkFunc "(lambda () 1)" [] [int 1] checkFunc "(lambda (a) a)" ["a"] [var "a"] checkFunc "(lambda (a) (test-func) (test-func2))" ["a"] [ func "test-func" [] , func "test-func2" [] ] checkFunc "(lambda (a b) (+ a b))" ["a", "b"] [func "+" [var "a", var "b"]] it "should fail to parse invalid lambda syntax" $ do let checkFailFunc a = parse lambda `shouldFailOn` a checkFailFunc "(lambd () 1)" checkFailFunc "(lambda 1)" checkFailFunc "(lambda ( 1)" checkFailFunc "(lambda ())" describe "parsing and expressions" $ do it "should be able to parse valid and expressions" $ do let checkAnd a b = parse andExpr a `shouldParse` (RavenAnd $ And b) let boolean = RavenLiteral . RavenBool let int = RavenLiteral . RavenNumber . RavenIntegral let func a b = RavenFunctionCall (RavenVariable a) b -- TODO this should be a procedure checkAnd "(and)" [] checkAnd "(and true)" [boolean True] checkAnd "(and true true)" [boolean True, boolean True] checkAnd "(and true 1)" [boolean True, int 1] checkAnd "(and true (+ 1 2))" [boolean True, func "+" [int 1, int 2]] it "should fail to parse invalid and expressions" $ do let checkFailAnd a = parse andExpr `shouldFailOn` a checkFailAnd "(nd)" checkFailAnd "(and" checkFailAnd "and)" describe "parsing or expressions" $ do it "should be able to parse valid or expressions" $ do let checkAnd a b = parse orExpr a `shouldParse` (RavenOr $ Or b) let boolean = RavenLiteral . RavenBool let int = RavenLiteral . RavenNumber . RavenIntegral let func a b = RavenFunctionCall (RavenVariable a) b -- TODO this should be a procedure checkAnd "(or)" [] checkAnd "(or true)" [boolean True] checkAnd "(or true true)" [boolean True, boolean True] checkAnd "(or true 1)" [boolean True, int 1] checkAnd "(or true (+ 1 2))" [boolean True, func "+" [int 1, int 2]] it "should fail to parse invalid or expressions" $ do let checkFailAnd a = parse orExpr `shouldFailOn` a checkFailAnd "(r)" checkFailAnd "(or" checkFailAnd "or)" describe "parsing begin expressions" $ do it "should be able to parse valid begin expressions" $ do let checkBegin a b = parse begin a `shouldParse` (RavenBegin $ Begin b) let func a b = RavenFunctionCall (RavenVariable a) b let int = RavenLiteral . RavenNumber . RavenIntegral checkBegin "(begin (f1))" [func "f1" []] checkBegin "(begin (f1) (f2))" [func "f1" [], func "f2" []] checkBegin "(begin 1 (f1))" [int 1, func "f1" []] checkBegin "(begin (f1) 1)" [func "f1" [], int 1] it "should fail to parse invalid begin expressions" $ do let checkFailBegin a = parse begin `shouldFailOn` a checkFailBegin "(begi)" checkFailBegin "(begin)" checkFailBegin "(begin ())" describe "parsing assignments" $ do it "should be possible to parse valid assignment expressions" $ do let int = RavenLiteral . RavenNumber . RavenIntegral let str = RavenLiteral . RavenString let checkAssign a b c = parse assignment a `shouldParse` (RavenAssign $ Assign (b) c) checkAssign "(set! a 3)" "a" (int 3) checkAssign "(set! b \"123456789\")" "b" (str "123456789") it "should fail to parse invalid assignment expressions" $ do let checkFailAssign a = parse assignment `shouldFailOn` a checkFailAssign "(set!)" checkFailAssign "(set!x a 3)" checkFailAssign "(set! a)" checkFailAssign "(set! 3)" checkFailAssign "(set! 3 3)" describe "parsing if expressions" $ do it "should be possible to parse valid if expressions" $ do let checkIf a b = parse ifExpr a `shouldParse` b let int = RavenLiteral . RavenNumber . RavenIntegral let boolean = RavenLiteral . RavenBool let str = RavenLiteral . RavenString checkIf "(if true 1)" (RavenIf (If (boolean True) (int 1) Nothing)) checkIf "(if true 1 2)" (RavenIf (If (boolean True) (int 1) (Just (int 2)))) let func = RavenFunctionCall (RavenVariable "test-func") [] checkIf "(if \"test\" (test-func))" (RavenIf (If (str "test") func Nothing)) it "should fail to parse invalid if expressions" $ do let checkFailIf a = parse ifExpr `shouldFailOn` a checkFailIf "(if)" checkFailIf "(if () true)" checkFailIf "(if true)" checkFailIf "(iff true 1)" describe "parsing delay expressions" $ do it "should be able to parse valid delay expressions" $ do let checkDelay a b = parse delay a `shouldParse` b let int = RavenLiteral . RavenNumber . RavenIntegral let boolean = RavenLiteral . RavenBool checkDelay "(delay 1)" (RavenDelay (int 1)) checkDelay "(delay true)" (RavenDelay (boolean True)) it "should fail to parse invalid delay expressions" $ do let checkFailDelay a = parse delay `shouldFailOn` a checkFailDelay "(delay" checkFailDelay "delay)" checkFailDelay "(delay)" checkFailDelay "(delayy (+ 1 2))" describe "parsing cond expressions" $ do it "should be able to parse valid cond expressions" $ do let checkCond a b = parse cond a `shouldParse` b let condExpr a b = RavenCond $ Cond a b let boolean = RavenLiteral . RavenBool let int = RavenLiteral . RavenNumber . RavenIntegral let var = RavenVariable let func a b = RavenFunctionCall (var a) b let listFunc = func "list" [int 1, int 2] let lambdaFunc a = RavenFunctionCall (RavenFunction (Function ["x"] [var "x"])) a checkCond "(cond (true))" (condExpr [[boolean True]] []) checkCond "(cond (true 1))" (condExpr [[boolean True, int 1]] []) checkCond "(cond (else 1))" (condExpr [] [int 1]) checkCond "(cond (false 1) (true 2))" (condExpr [[boolean False, int 1], [boolean True, int 2]] []) checkCond "(cond (false 1) (false 2) (else 3))" (condExpr [[boolean False, int 1], [boolean False, int 2]] [int 3]) checkCond "(cond ((list 1 2) => car))" (condExpr [[listFunc, func "car" [listFunc]]] []) checkCond "(cond (1 => (lambda (x) x)))" (condExpr [[int 1, lambdaFunc [int 1]]] []) it "should fail to parse invalid cond expressions" $ do let checkFailCond a = parse cond `shouldFailOn` a checkFailCond "(cond)" checkFailCond "(cond ())" checkFailCond "(cnd (true))" checkFailCond "(cond (true)" checkFailCond "cond (true))" checkFailCond "cond (true))" checkFailCond "(cond ((list 1 2) =>)" checkFailCond "(cond (=> (list 1 2))" checkFailCond "(cond (else))" checkFailCond "(cond (else 1) (true))" describe "parsing case expressions" $ do it "should be able to parse valid case expressions" $ do let checkCase a b = parse caseExpr a `shouldParse` b let caseExpr' a b c = RavenCase $ Case a b c let boolean = RavenLiteral . RavenBool let int = RavenLiteral . RavenNumber . RavenIntegral checkCase "(case 1 ((1) 2))" (caseExpr' (int 1) [([int 1], [int 2])] []) checkCase "(case 1 ((1) 2 3))" (caseExpr' (int 1) [([int 1], [int 2, int 3])] []) checkCase "(case 1 ((1) 2) ((3) 4))" (caseExpr' (int 1) [([int 1], [int 2]), ([int 3], [int 4])] []) checkCase "(case 1 ((1) 2) ((3) 4) (else 5))" (caseExpr' (int 1) [([int 1], [int 2]), ([int 3], [int 4])] [int 5]) checkCase "(case 2 ((1 2) 3))" (caseExpr' (int 2) [([int 1, int 2], [int 3])] []) checkCase "(case 1 (else 2))" (caseExpr' (int 1) [] [int 2]) checkCase "(case 1 (else 2 3))" (caseExpr' (int 1) [] [int 2, int 3]) it "should fail to parse invalid case expressions" $ do let checkFailCase a = parse caseExpr `shouldFailOn` a checkFailCase "(case)" checkFailCase "(case 1)" checkFailCase "(case 1 ())" checkFailCase "(case 1 ((1) ))" checkFailCase "(cas 1 ((1) 2))" checkFailCase "(case 1 ((1) 1)" checkFailCase "case 1 ((1) 1))" checkFailCase "(case (else 1))" checkFailCase "(case 1 (else))" describe "parsing do expressions" $ do it "should be able to parse valid do expressions" $ do let checkDo a b = parse doExpr a `shouldParse` b let doExpr' a b c = RavenDo $ Do a b c let boolean = RavenLiteral . RavenBool let int = RavenLiteral . RavenNumber . RavenIntegral let var = RavenVariable let func a b = RavenFunctionCall (var a) b checkDo "(do () (true))" (doExpr' [] (boolean True, []) []) checkDo "(do () (true 1))" (doExpr' [] (boolean True, [int 1]) []) checkDo "(do () (true 1 2))" (doExpr' [] (boolean True, [int 1, int 2]) []) checkDo "(do ((a 1)) (true))" (doExpr' [(var "a", int 1, var "a")] (boolean True, []) []) checkDo "(do ((a 1 (+ a 1))) (true))" (doExpr' [(var "a", int 1, func "+" [var "a", int 1])] (boolean True, []) []) checkDo "(do ((a 1) (b 2)) (true))" (doExpr' [(var "a", int 1, var "a"), (var "b", int 2, var "b")] (boolean True, []) []) checkDo "(do () (true 1))" (doExpr' [] (boolean True, [int 1]) []) checkDo "(do () (true 1 2))" (doExpr' [] (boolean True, [int 1, int 2]) []) checkDo "(do () (true) 1)" (doExpr' [] (boolean True, []) [int 1]) checkDo "(do () (true) 1 2)" (doExpr' [] (boolean True, []) [int 1, int 2]) it "should fail to parse invalid do expressions" $ do let checkFailDo a = parse doExpr `shouldFailOn` a checkFailDo "(do)" checkFailDo "(do ())" checkFailDo "(do () ())" checkFailDo "(d () (true))" checkFailDo "(do () (true ()))" checkFailDo "(do (a) (true))" checkFailDo "(do (true))" checkFailDo "(do () true)" -- TODO fix failing test cases (mostly due to lack of end of number indicator: " " or ")")
luc-tielen/raven
test/Raven/ParserSpec.hs
bsd-3-clause
20,712
0
23
5,961
6,002
2,712
3,290
389
1
module Main where import qualified System.IO.Streams.Tests.Attoparsec.ByteString as AttoparsecByteString import qualified System.IO.Streams.Tests.Attoparsec.Text as AttoparsecText import qualified System.IO.Streams.Tests.Builder as Builder import qualified System.IO.Streams.Tests.ByteString as ByteString import qualified System.IO.Streams.Tests.Combinators as Combinators import qualified System.IO.Streams.Tests.Concurrent as Concurrent import qualified System.IO.Streams.Tests.Debug as Debug import qualified System.IO.Streams.Tests.File as File import qualified System.IO.Streams.Tests.Handle as Handle import qualified System.IO.Streams.Tests.Internal as Internal import qualified System.IO.Streams.Tests.List as List import qualified System.IO.Streams.Tests.Network as Network import qualified System.IO.Streams.Tests.Process as Process import qualified System.IO.Streams.Tests.Text as Text import qualified System.IO.Streams.Tests.Vector as Vector import qualified System.IO.Streams.Tests.Zlib as Zlib import Test.Framework (defaultMain, testGroup) ------------------------------------------------------------------------------ main :: IO () main = defaultMain tests where tests = [ testGroup "Tests.Attoparsec.ByteString" AttoparsecByteString.tests , testGroup "Tests.Attoparsec.Text" AttoparsecText.tests , testGroup "Tests.Builder" Builder.tests , testGroup "Tests.ByteString" ByteString.tests , testGroup "Tests.Debug" Debug.tests , testGroup "Tests.Combinators" Combinators.tests , testGroup "Tests.Concurrent" Concurrent.tests , testGroup "Tests.File" File.tests , testGroup "Tests.Handle" Handle.tests , testGroup "Tests.Internal" Internal.tests , testGroup "Tests.List" List.tests , testGroup "Tests.Network" Network.tests , testGroup "Tests.Process" Process.tests , testGroup "Tests.Text" Text.tests , testGroup "Tests.Vector" Vector.tests , testGroup "Tests.Zlib" Zlib.tests ]
LukeHoersten/io-streams
test/TestSuite.hs
bsd-3-clause
2,344
0
9
613
381
251
130
36
1
{-# LANGUAGE DataKinds, FlexibleContexts, TemplateHaskell #-} -- | Demonstration of streaming data processing. Try building with -- cabal (@cabal build benchdemo@), then running in bash with -- something like, -- -- @$ /usr/bin/time -l dist/build/benchdemo/benchdemo 2>&1 | head -n 4@ import qualified Control.Foldl as F import Frames import Pipes.Prelude (fold) tableTypes "Ins" "data/FL2.csv" main :: IO () main = do (lat,lng,n) <- F.purely fold f (readTable "data/FL2.csv") print $ lat / n print $ lng / n where f :: F.Fold Ins (Double,Double,Double) f = (,,) <$> F.handles pointLatitude F.sum <*> F.handles pointLongitude F.sum <*> F.genericLength
codygman/Frames
benchmarks/BenchDemo.hs
bsd-3-clause
718
0
11
162
168
91
77
13
1
{-# LANGUAGE TemplateHaskell, LambdaCase, FlexibleContexts, DeriveFunctor, DeriveFoldable, DeriveTraversable #-} module Jugendstil.Doc.Layout ( Layout(..) , matchLayout , computeStyle , Document , renderDocument , rows , columns , docs , margin -- * DoList , DoList , unDoList , (==>) , rowsDL , columnsDL) where import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Iter import Data.BoundingBox import Data.BoundingBox as Box import Data.Monoid import Graphics.Holz import Jugendstil.Doc import Linear data Layout a = Horizontal [(Maybe Float, a)] | Vertical [(Maybe Float, a)] | Stack [a] | Extend (Box V2 Float -> Box V2 Float) a deriving (Functor, Foldable, Traversable) matchLayout :: Applicative m => (Maybe a -> b -> m c) -> Layout a -> Layout b -> m (Layout c) matchLayout f (Horizontal xs) (Horizontal ys) = Horizontal <$> zipWithM (\m (s, b) -> (,) s <$> f (snd <$> m) b) (map Just xs ++ repeat Nothing) ys matchLayout f (Vertical xs) (Vertical ys) = Vertical <$> zipWithM (\m (s, b) -> (,) s <$> f (snd <$> m) b) (map Just xs ++ repeat Nothing) ys matchLayout f (Stack xs) (Stack ys) = Stack <$> zipWithM f (map Just xs ++ repeat Nothing) ys matchLayout f (Extend _ a) (Extend g b) = Extend g <$> f (Just a) b matchLayout f _ l = traverse (f Nothing) l renderDocument :: Document a -> ShaderT (HolzT IO) (Doc Layout (Box V2 Float, a)) renderDocument doc = do box <- getBoundingBox let doc' = computeStyle box doc renderDoc fst doc' return doc' computeStyle :: Box V2 Float -> Doc Layout a -> Doc Layout (Box V2 Float, a) computeStyle box (Prim a bg) = Prim (box, a) bg computeStyle box@(Box (V2 x0 y0) (V2 x1 y1)) (Docs a (Horizontal xs)) = Docs (box, a) $ Horizontal $ zip (map fst xs) $ boxes x0 $ sortLayout (x1 - x0) xs where boxes x ((w, d):ws) = computeStyle (Box (V2 x y0) (V2 (x + w) y1)) d : boxes (x + w) ws boxes _ [] = [] computeStyle box@(Box (V2 x0 y0) (V2 x1 y1)) (Docs a (Vertical xs)) = Docs (box, a) $ Vertical $ zip (map fst xs) $ boxes y0 $ sortLayout (y1 - y0) xs where boxes y ((h, d):hs) = computeStyle (Box (V2 x0 y) (V2 x1 (y + h))) d : boxes (y + h) hs boxes _ [] = [] computeStyle box (Docs a (Stack xs)) = Docs (box, a) $ Stack $ map (computeStyle box) xs computeStyle box (Docs a (Extend f d)) = Docs (box, a) $ Extend f $ computeStyle (f box) d computeStyle box (Viewport a d) = Viewport (box, a) (computeStyle box d) sortLayout :: Float -> [(Maybe Float, a)] -> [(Float, a)] sortLayout total xs0 = let (r, ys) = go total 0 xs0 in map ($ r) ys where go :: Float -> Int -> [(Maybe Float, a)] -> (Float, [Float -> (Float, a)]) go t n ((Just r, a) : xs) = let v = total * r in (const (v, a) :) <$> go (t - v) n xs go t n ((Nothing, a) : xs) = (:) (\r -> (r, a)) <$> go t (n + 1) xs go t n _ = (t / fromIntegral n, []) type Document = Doc Layout rows :: Monoid a => [(Maybe Float, Document a)] -> Document a rows xs = Docs mempty $ Vertical xs columns :: Monoid a => [(Maybe Float, Document a)] -> Document a columns xs = Docs mempty $ Horizontal xs docs :: Monoid a => [Document a] -> Document a docs xs = Docs mempty $ Stack xs margin :: Monoid a => V4 Float -> Document a -> Document a margin (V4 t r b l) = Docs mempty . Extend (\(V2 x0 y0 `Box` V2 x1 y1) -> V2 (x0 + l) (y0 + t) `Box` V2 (x1 - r) (y1 - b)) type DoList a = (,) (Endo [a]) unDoList :: DoList a x -> [a] unDoList (Endo f, _) = f [] (==>) :: a -> b -> DoList (a, b) () a ==> b = (Endo ((a, b):), ()) infix 0 ==> rowsDL :: Monoid a => DoList (Maybe Float, Document a) x -> Document a rowsDL = rows . unDoList columnsDL :: Monoid a => DoList (Maybe Float, Document a) x -> Document a columnsDL = columns . unDoList
fumieval/jugendstil
src/Jugendstil/Doc/Layout.hs
bsd-3-clause
3,806
0
14
865
2,030
1,055
975
88
3
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} module Aria.Pass where import Happstack.ClientSession import Control.Lens import Datat.Data import Data.SafeCopy (base, deriveSafeCopy) import Control.Monad.Catch import Control.Monad.IO.Class import GHC.Generics import qualified Data.Map as DM data LoginSessionData = LoginSessionData { _loginRName :: Text } deriving (Eq, Ord, Show, Read, Data, Typeable) data BadLoginError = BadLoginError Text deriving (Eq, Ord, Show, Read, Data, Typeable, Generic) data FailedLoginAttempt = FailedLoginAttempt Username Password deriving (Eq,Ord,Show,Read,Data,Typeable, Generic) type LoginApp = ClientSessionT LoginSessionData type Username = String type Password = String type UNamePassMap = DM.Map String String makeLenses ''LoginSessionData $(deriveSafeCopy 0 'base ''LoginSessionData) instance ClientSession LoginSessionData where emptySession = LoginSessionData { _loginRName = "" } instance Exception BadLoginError instance Exception FailedLoginAttempt guardLogin :: (MonadIO m, MonadThrow m) => Text -> m a -> LoginApp m a guardLogin login act = do loginName <- getSession case (loginName == login) of True -> act _ -> throwM $ BadLoginError loginName login :: (MonadIO m, MonadThrow m) => (Username,Password) -> LoginApp m () login upass@(uname,pass) = do unless (checkLogin upass) $ throwM FailedLoginAttempt uname pass
theNerd247/ariaRacer
arweb/app/Aria/Pass.hs
bsd-3-clause
1,507
2
11
237
447
241
206
42
2
-- | This module defines a sever-side handler that lets you serve static files. -- -- - 'serveDirectory' lets you serve anything that lives under a particular -- directory on your filesystem. module Servant.Utils.StaticFiles ( serveDirectory, ) where import Filesystem.Path.CurrentOS (decodeString) import Network.Wai.Application.Static import Servant.API.Raw import Servant.Server.Internal -- | Serve anything under the specified directory as a 'Raw' endpoint. -- -- @ -- type MyApi = "static" :> Raw -- -- server :: Server MyApi -- server = serveDirectory "\/var\/www" -- @ -- -- would capture any request to @\/static\/\<something>@ and look for -- @\<something>@ under @\/var\/www@. -- -- It will do its best to guess the MIME type for that file, based on the extension, -- and send an appropriate /Content-Type/ header if possible. -- -- If your goal is to serve HTML, CSS and Javascript files that use the rest of the API -- as a webapp backend, you will most likely not want the static files to be hidden -- behind a /\/static\// prefix. In that case, remember to put the 'serveDirectory' -- handler in the last position, because /servant/ will try to match the handlers -- in order. serveDirectory :: FilePath -> Server Raw serveDirectory documentRoot = staticApp (defaultFileServerSettings (decodeString (documentRoot ++ "/")))
derekelkins/servant-server
src/Servant/Utils/StaticFiles.hs
bsd-3-clause
1,346
0
11
216
109
74
35
9
1
import Image
YoshikuniJujo/markdown2svg
tests/testImage.hs
bsd-3-clause
13
0
3
2
4
2
2
1
0
module Opaleye.Internal.Order where import qualified Opaleye.Column as C import qualified Opaleye.Internal.Tag as T import qualified Opaleye.Internal.PrimQuery as PQ import qualified Database.HaskellDB.PrimQuery as HPQ import qualified Data.Functor.Contravariant as C import qualified Data.Profunctor as P import qualified Data.Monoid as M -- FIXME: make capitilisation of Specs consistent with UnpackSpec data SingleOrderSpec a = SingleOrderSpec HPQ.OrderOp (a -> HPQ.PrimExpr) instance C.Contravariant SingleOrderSpec where contramap f (SingleOrderSpec op g) = SingleOrderSpec op (P.lmap f g) newtype OrderSpec a = OrderSpec [SingleOrderSpec a] instance C.Contravariant OrderSpec where contramap f (OrderSpec xs) = OrderSpec (fmap (C.contramap f) xs) instance M.Monoid (OrderSpec a) where mempty = OrderSpec M.mempty OrderSpec o `mappend` OrderSpec o' = OrderSpec (o `M.mappend` o') orderSpec :: HPQ.OrderOp -> (a -> C.Column b) -> OrderSpec a orderSpec op f = C.contramap f (OrderSpec [SingleOrderSpec op C.unColumn]) orderByU :: OrderSpec a -> (a, PQ.PrimQuery, T.Tag) -> (a, PQ.PrimQuery, T.Tag) orderByU os (columns, primQ, t) = (columns, primQ', t) where primQ' = PQ.Order orderExprs primQ OrderSpec sos = os orderExprs = map (\(SingleOrderSpec op f) -> HPQ.OrderExpr op (f columns)) sos limit' :: Int -> (a, PQ.PrimQuery, T.Tag) -> (a, PQ.PrimQuery, T.Tag) limit' n (x, q, t) = (x, PQ.Limit (PQ.LimitOp n) q, t) offset' :: Int -> (a, PQ.PrimQuery, T.Tag) -> (a, PQ.PrimQuery, T.Tag) offset' n (x, q, t) = (x, PQ.Limit (PQ.OffsetOp n) q, t)
k0001/haskell-opaleye
Opaleye/Internal/Order.hs
bsd-3-clause
1,611
0
12
284
612
344
268
29
1
module Test6 where import qualified Data.HashMap.Strict as H import qualified Data.Text as T import qualified Data.Text.IO as T import Data.List import Debug.Trace import System.IO isAlpha ch = ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') wrds :: T.Text -> [ T.Text ] wrds bs = let (_, r1) = T.span (not . isAlpha) bs (w, r2) = T.span isAlpha r1 in if T.null w then [] else T.toLower w : wrds r2 readDict = do let add h w = let c = H.lookupDefault (0 :: Int) w h in H.insert w (c+1) h loop h fh = do b <- hIsEOF fh if b then return h else do cs <- T.hGetLine fh let h' = foldl' add h (wrds cs) loop h' fh h <- withFile "big.txt" ReadMode (loop H.empty) let member = \k -> H.member k h frequency = \k -> H.lookupDefault 0 k h return (member, frequency, T.pack)
erantapaa/test-spelling
src/Test6.hs
bsd-3-clause
942
0
20
333
405
209
196
26
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} module Development.Shake.Install.RequestResponse where import Development.Shake as Shake import Control.Applicative import Data.Data import Data.Binary import Control.DeepSeq import Data.Hashable data Request a = Request deriving (Show) deriving instance Typeable Request instance NFData (Request a) where rnf _ = () instance Eq (Request a) where _ == _ = True instance Hashable (Request a) where hashWithSalt _ _ = 1 instance Binary (Request a) where get = return Request put _ = return () data Response a = Response{unResponse :: a} deriving instance Show a => Show (Response a) deriving instance Read a => Read (Response a) deriving instance Eq a => Eq (Response a) deriving instance Ord a => Ord (Response a) deriving instance Typeable1 Response instance Hashable a => Hashable (Response a) where hashWithSalt s (Response x) = hashWithSalt s x instance Binary a => Binary (Response a) where get = fmap Response get put (Response x) = put x instance NFData a => NFData (Response a) where rnf (Response x) = rnf x `seq` () instance (Show a, Binary a, NFData a, Typeable a, Hashable a, Eq a) => Rule (Request a) (Response a) where storedValue _ = return Nothing requestOf :: forall a b . Rule (Request a) (Response a) => (a -> b) -- ^ record field selector -> Action b requestOf fun = fun . unResponse <$> apply1 (Request :: Request a)
alphaHeavy/shake-install
Development/Shake/Install/RequestResponse.hs
bsd-3-clause
1,597
0
9
299
568
293
275
47
1
{-# LANGUAGE Arrows #-} import Hatter import Hatter.Types import Hatter.Wires import Control.Wire as Wire hiding (id) import Control.Arrow import Control.Applicative import FRP.Netwire hiding (id) import Prelude hiding ((.), null, filter) import Data.Map as Map hiding (foldl) import Linear hiding (trace) import Debug.Trace initialGameState :: GameState String initialGameState = createInitialState (Map.fromList [(oid squareObject,squareObject)]) "" objectName :: String objectName = assetDirPath ++ "square.png" squareObject :: GameObject squareObject = GameObject "square1" (V2 2 2) Hatter.Types.None (Image $ Hatter.Types.Sprite objectName 100 100) myGameWire :: (Real t, HasTime t s) => Wire s e IO (GameState String) (Map String GameObject) myGameWire = proc state -> do let object = head $ Map.elems $ gameObjects state newposition <- positionWire identityCorrectionFunction (V2 0 0) (velocityWire identityCorrectionFunction $ V2 0 0) (constantAcceleration $ V2 0.1 0.03) -< state let newobject = GameObject {oid=oid object, position=newposition, boundingBox=boundingBox object, gameGraphic=gameGraphic object} returnA -< (Map.fromList [(oid newobject, newobject)]) --TODO: Provide function to form new game object with updated position myEventCheckers :: Map String (GameState String -> ()) myEventCheckers = Map.fromList [] assetDirPath :: String assetDirPath = "/Users/apple/Documents/Academics/sem9/FP/Hatter/examples/assets/" canvas :: Canvas canvas = Canvas 1000 1000 "Square" main = run myGameDefinition canvas initialGameState myGameDefinition = GameDefinition { gameWire=myGameWire , eventCheckers=myEventCheckers , frameRate=20 , externalState="" , assetDir=assetDirPath }
shivanshuag/Hatter
examples/square_using_wires.hs
bsd-3-clause
1,899
1
13
413
510
281
229
36
1
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} module Main where ------------------------------------------------------------------------------ import Control.Exception (SomeException, try) import qualified Data.Text as T import Site import Snap.Core import Snap.Http.Server import Snap.Snaplet import Snap.Snaplet.Config import System.IO #ifdef DEVELOPMENT import Snap.Loader.Dynamic #else import Snap.Loader.Static #endif ------------------------------------------------------------------------------ -- | This is the entry point for this web server application. It supports -- easily switching between interpreting source and running statically compiled -- code. -- -- In either mode, the generated program should be run from the root of the -- project tree. When it is run, it locates its templates, static content, and -- source files in development mode, relative to the current working directory. -- -- When compiled with the development flag, only changes to the libraries, your -- cabal file, or this file should require a recompile to be picked up. -- Everything else is interpreted at runtime. There are a few consequences of -- this. -- -- First, this is much slower. Running the interpreter takes a significant -- chunk of time (a couple tenths of a second on the author's machine, at this -- time), regardless of the simplicity of the loaded code. In order to -- recompile and re-load server state as infrequently as possible, the source -- directories are watched for updates, as are any extra directories specified -- below. -- -- Second, the generated server binary is MUCH larger, since it links in the -- GHC API (via the hint library). -- -- Third, and the reason you would ever want to actually compile with -- development mode, is that it enables a faster development cycle. You can -- simply edit a file, save your changes, and hit reload to see your changes -- reflected immediately. -- -- When this is compiled without the development flag, all the actions are -- statically compiled in. This results in faster execution, a smaller binary -- size, and having to recompile the server for any code change. -- main :: IO () main = do -- Depending on the version of loadSnapTH in scope, this either enables -- dynamic reloading, or compiles it without. The last argument to -- loadSnapTH is a list of additional directories to watch for changes to -- trigger reloads in development mode. It doesn't need to include source -- directories, those are picked up automatically by the splice. (conf, site, cleanup) <- $(loadSnapTH [| getConf |] 'getActions ["snaplets/heist/templates"]) _ <- try $ httpServe conf site :: IO (Either SomeException ()) cleanup ------------------------------------------------------------------------------ -- | This action loads the config used by this application. The loaded config -- is returned as the first element of the tuple produced by the loadSnapTH -- Splice. The type is not solidly fixed, though it must be an IO action that -- produces the same type as 'getActions' takes. It also must be an instance of -- Typeable. If the type of this is changed, a full recompile will be needed to -- pick up the change, even in development mode. -- -- This action is only run once, regardless of whether development or -- production mode is in use. getConf :: IO (Config Snap AppConfig) getConf = commandLineAppConfig defaultConfig ------------------------------------------------------------------------------ -- | This function generates the the site handler and cleanup action from the -- configuration. In production mode, this action is only run once. In -- development mode, this action is run whenever the application is reloaded. -- -- Development mode also makes sure that the cleanup actions are run -- appropriately before shutdown. The cleanup action returned from loadSnapTH -- should still be used after the server has stopped handling requests, as the -- cleanup actions are only automatically run when a reload is triggered. -- -- This sample doesn't actually use the config passed in, but more -- sophisticated code might. getActions :: Config Snap AppConfig -> IO (Snap (), IO ()) getActions conf = do (msgs, site, cleanup) <- runSnaplet (appEnvironment =<< getOther conf) app hPutStrLn stderr $ T.unpack msgs return (site, cleanup)
HaskellCNOrg/snaplet-oauth
example/src/Main.hs
bsd-3-clause
4,565
0
11
927
334
210
124
27
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} module MongoDbConnector where import Control.Monad (when) import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Data.Text (pack, unpack) import Data.Time.Clock (UTCTime, getCurrentTime) import Data.Time.Format (defaultTimeLocale, formatTime) import Database.MongoDB import System.Environment (getArgs, getProgName, lookupEnv) import System.Log.Logger connectToDatabase :: Action IO a -> IO a connectToDatabase act = do pipe <- connect (host "127.0.0.1") access pipe master "GluonDatabase" act drainCursor :: Cursor -> Action IO [Document] drainCursor cur = drainCursor' cur [] where drainCursor' cur res = do batch <- nextBatch cur if null batch then return res else drainCursor' cur (res ++ batch)
Coggroach/Gluon
src/MongoDbConnector.hs
bsd-3-clause
1,299
0
12
377
242
136
106
31
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} -- | <http://www.libtorrent.org/reference-Core.html#peer-info peer_info> structure for "Libtorrent" module Network.Libtorrent.PeerInfo (PeerFlags(..) , PeerSourceFlags(..) , ConnectionType(..) , BwState(..) , PeerInfo(..) , getClient , setClient , getPeerInfoPieces , setPeerInfoPieces , getPeerInfoTotalDownload , setPeerInfoTotalDownload , getPeerInfoTotalUpload , setPeerInfoTotalUpload , getLastRequest , setLastRequest , getLastActive , setLastActive , getDownloadQueueTime , setDownloadQueueTime , getPeerInfoFlags , setPeerInfoFlags , getPeerInfoSource , setPeerInfoSource , getUpSpeed , setUpSpeed , getDownSpeed , setDownSpeed , getPayloadUpSpeed , setPayloadUpSpeed , getPayloadDownSpeed , setPayloadDownSpeed , getPid , setPid , getQueueBytes , setQueueBytes , getPeerInfoRequestTimeout , setPeerInfoRequestTimeout , getSendBufferSize , setSendBufferSize , getUsedSendBuffer , setUsedSendBuffer , getReceiveBufferSize , setReceiveBufferSize , getUsedReceiveBuffer , setUsedReceiveBuffer , getNumHashfails , setNumHashfails , getDownloadQueueLength , setDownloadQueueLength , getTimedOutRequests , setTimedOutRequests , getBusyRequests , setBusyRequests , getRequestsInBuffer , setRequestsInBuffer , getTargetDlQueueLength , setTargetDlQueueLength , getUploadQueueLength , setUploadQueueLength , getFailcount , setFailcount , getDownloadingPieceIndex , setDownloadingPieceIndex , getDownloadingBlockIndex , setDownloadingBlockIndex , getDownloadingProgress , setDownloadingProgress , getDownloadingTotal , setDownloadingTotal , getConnectionType , setConnectionType , getRemoteDlRate , setRemoteDlRate , getPendingDiskBytes , setPendingDiskBytes , getSendQuota , setSendQuota , getReceiveQuota , setReceiveQuota , getRtt , setRtt , getPeerInfoNumPieces , setPeerInfoNumPieces , getDownloadRatePeak , setDownloadRatePeak , getUploadRatePeak , setUploadRatePeak , getPeerInfoProgressPpm , setPeerInfoProgressPpm , getEstimatedReciprocationRate , setEstimatedReciprocationRate , getIp , getLocalEndpoint , getReadState , setReadState , getWriteState , setWriteState ) where import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Array.BitArray (BitArray) import Data.Int (Int64) import Data.Text (Text) import qualified Data.Text.Foreign as TF import Data.Word (Word64) import Foreign.C.Types (CInt) import Foreign.ForeignPtr (ForeignPtr, withForeignPtr) import qualified Language.C.Inline as C import qualified Language.C.Inline.Cpp as C import qualified Language.C.Inline.Unsafe as CU import Network.Libtorrent.Bitfield import Network.Libtorrent.Inline import Network.Libtorrent.Internal import Network.Libtorrent.Sha1Hash import Network.Libtorrent.String import Network.Libtorrent.Types C.context libtorrentCtx C.include "<libtorrent/peer_info.hpp>" C.include "<libtorrent/torrent_handle.hpp>" C.include "torrent_handle.hpp" C.using "namespace libtorrent" C.using "namespace std" data PeerFlags = Interesting | Choked | RemoteInterested | RemoteChoked | SupportsExtensions | LocalConnection | Handshake | Connecting | Queued | OnParole | Seed | OptimisticUnchoke | Snubbed | UploadOnly | EndgameMode | Holepunched | I2pSocket | UtpSocket | SslSocket | Rc4Encrypted | PlaintextEncrypted deriving (Show, Enum, Bounded, Eq, Ord) data PeerSourceFlags = Tracker | Dht | Pex | Lsd | ResumeData | Incoming deriving (Show, Enum, Bounded, Eq, Ord) data ConnectionType = StandardBittorrent | WebSeed | HttpSeed deriving (Show, Enum, Bounded, Eq, Ord) data BwState = BwIdle | BwLimit | BwNetwork | BwDisk deriving (Show, Enum, Bounded, Eq, Ord) newtype PeerInfo = PeerInfo { unPeerInfo :: ForeignPtr (CType PeerInfo)} instance Show PeerInfo where show _ = "PeerInfo" instance Inlinable PeerInfo where type (CType PeerInfo) = C'PeerInfo instance FromPtr PeerInfo where fromPtr = objFromPtr PeerInfo $ \ptr -> [CU.exp| void { delete $(peer_info * ptr); } |] instance WithPtr PeerInfo where withPtr (PeerInfo fptr) = withForeignPtr fptr getClient :: MonadIO m => PeerInfo -> m Text getClient ho = liftIO . withPtr ho $ \hoPtr -> do res <- fromPtr [CU.exp| string * { new std::string($(peer_info * hoPtr)->client) } |] stdStringToText res setClient :: MonadIO m => PeerInfo -> Text -> m () setClient ho val = do liftIO . TF.withCStringLen val $ \(cstr, len) -> do let clen = fromIntegral len liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->client = std::string($(const char * cstr), $(size_t clen))} |] getPeerInfoPieces :: MonadIO m => PeerInfo -> m (BitArray Int) getPeerInfoPieces ho = liftIO . withPtr ho $ \hoPtr -> do bf <- fromPtr [CU.exp| bitfield * { new bitfield($(peer_info * hoPtr)->pieces) } |] bitfieldToBitArray bf setPeerInfoPieces :: MonadIO m => PeerInfo -> (BitArray Int) -> m () setPeerInfoPieces ho ba = liftIO $ do bf <- bitArrayToBitfield ba withPtr bf $ \bfPtr -> withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->pieces = bitfield(*$(bitfield * bfPtr))} |] getPeerInfoTotalDownload :: MonadIO m => PeerInfo -> m Int64 getPeerInfoTotalDownload ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int64_t { $(peer_info * hoPtr)->total_download } |] setPeerInfoTotalDownload :: MonadIO m => PeerInfo -> Int64 -> m () setPeerInfoTotalDownload ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->total_download = $(int64_t val)} |] getPeerInfoTotalUpload :: MonadIO m => PeerInfo -> m Int64 getPeerInfoTotalUpload ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int64_t { $(peer_info * hoPtr)->total_upload } |] setPeerInfoTotalUpload :: MonadIO m => PeerInfo -> Int64 -> m () setPeerInfoTotalUpload ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->total_upload = $(int64_t val)} |] getLastRequest :: MonadIO m => PeerInfo -> m Word64 getLastRequest ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| uint64_t { $(peer_info * hoPtr)->last_request.diff } |] setLastRequest :: MonadIO m => PeerInfo -> Word64 -> m () setLastRequest ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->last_request = time_duration($(uint64_t val))} |] getLastActive :: MonadIO m => PeerInfo -> m Word64 getLastActive ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| uint64_t { $(peer_info * hoPtr)->last_active.diff } |] setLastActive :: MonadIO m => PeerInfo -> Word64 -> m () setLastActive ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->last_active = time_duration($(uint64_t val))} |] getDownloadQueueTime :: MonadIO m => PeerInfo -> m Word64 getDownloadQueueTime ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| uint64_t { $(peer_info * hoPtr)->download_queue_time.diff } |] setDownloadQueueTime :: MonadIO m => PeerInfo -> Word64 -> m () setDownloadQueueTime ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->download_queue_time = time_duration($(uint64_t val))} |] getPeerInfoFlags :: MonadIO m => PeerInfo -> m (BitFlags PeerFlags) getPeerInfoFlags ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| int32_t{ $(peer_info * hoPtr)->flags } |] setPeerInfoFlags :: MonadIO m => PeerInfo -> BitFlags PeerFlags -> m () setPeerInfoFlags ho flags = do let val = fromIntegral $ fromEnum flags liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->flags = $(int32_t val)} |] getPeerInfoSource :: MonadIO m => PeerInfo -> m (BitFlags PeerSourceFlags) getPeerInfoSource ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| int32_t { $(peer_info * hoPtr)->source } |] setPeerInfoSource :: MonadIO m => PeerInfo -> BitFlags PeerSourceFlags -> m () setPeerInfoSource ho flags = do let val = fromIntegral $ fromEnum flags liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->source = $(int32_t val)} |] getUpSpeed :: MonadIO m => PeerInfo -> m CInt getUpSpeed ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->up_speed } |] setUpSpeed :: MonadIO m => PeerInfo -> CInt -> m () setUpSpeed ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->up_speed = $(int val)} |] getDownSpeed :: MonadIO m => PeerInfo -> m CInt getDownSpeed ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->down_speed } |] setDownSpeed :: MonadIO m => PeerInfo -> CInt -> m () setDownSpeed ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->down_speed = $(int val)} |] getPayloadUpSpeed :: MonadIO m => PeerInfo -> m CInt getPayloadUpSpeed ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->payload_up_speed } |] setPayloadUpSpeed :: MonadIO m => PeerInfo -> CInt -> m () setPayloadUpSpeed ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->payload_up_speed = $(int val)} |] getPayloadDownSpeed :: MonadIO m => PeerInfo -> m CInt getPayloadDownSpeed ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->payload_down_speed } |] setPayloadDownSpeed :: MonadIO m => PeerInfo -> CInt -> m () setPayloadDownSpeed ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->payload_down_speed = $(int val)} |] getPid :: MonadIO m => PeerInfo -> m Sha1Hash getPid ho = liftIO . withPtr ho $ \hoPtr -> do fromPtr [CU.exp| sha1_hash * { new sha1_hash($(peer_info * hoPtr)->pid) } |] setPid :: MonadIO m => PeerInfo -> Sha1Hash -> m () setPid ho val = liftIO . withPtr ho $ \hoPtr -> withPtr val $ \valPtr -> [CU.exp| void { $(peer_info * hoPtr)->pid = sha1_hash(*$(sha1_hash * valPtr)) } |] getQueueBytes :: MonadIO m => PeerInfo -> m CInt getQueueBytes ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->queue_bytes } |] setQueueBytes :: MonadIO m => PeerInfo -> CInt -> m () setQueueBytes ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->queue_bytes = $(int val)} |] getPeerInfoRequestTimeout :: MonadIO m => PeerInfo -> m CInt getPeerInfoRequestTimeout ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->request_timeout } |] setPeerInfoRequestTimeout :: MonadIO m => PeerInfo -> CInt -> m () setPeerInfoRequestTimeout ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->request_timeout = $(int val)} |] getSendBufferSize :: MonadIO m => PeerInfo -> m CInt getSendBufferSize ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->send_buffer_size } |] setSendBufferSize :: MonadIO m => PeerInfo -> CInt -> m () setSendBufferSize ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->send_buffer_size = $(int val)} |] getUsedSendBuffer :: MonadIO m => PeerInfo -> m CInt getUsedSendBuffer ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->used_send_buffer } |] setUsedSendBuffer :: MonadIO m => PeerInfo -> CInt -> m () setUsedSendBuffer ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->used_send_buffer = $(int val)} |] getReceiveBufferSize :: MonadIO m => PeerInfo -> m CInt getReceiveBufferSize ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->receive_buffer_size } |] setReceiveBufferSize :: MonadIO m => PeerInfo -> CInt -> m () setReceiveBufferSize ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->receive_buffer_size = $(int val)} |] getUsedReceiveBuffer :: MonadIO m => PeerInfo -> m CInt getUsedReceiveBuffer ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->used_receive_buffer } |] setUsedReceiveBuffer :: MonadIO m => PeerInfo -> CInt -> m () setUsedReceiveBuffer ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->used_receive_buffer = $(int val)} |] getNumHashfails :: MonadIO m => PeerInfo -> m CInt getNumHashfails ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->num_hashfails } |] setNumHashfails :: MonadIO m => PeerInfo -> CInt -> m () setNumHashfails ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->num_hashfails = $(int val)} |] getDownloadQueueLength :: MonadIO m => PeerInfo -> m CInt getDownloadQueueLength ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->download_queue_length } |] setDownloadQueueLength :: MonadIO m => PeerInfo -> CInt -> m () setDownloadQueueLength ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->download_queue_length = $(int val)} |] getTimedOutRequests :: MonadIO m => PeerInfo -> m CInt getTimedOutRequests ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->timed_out_requests } |] setTimedOutRequests :: MonadIO m => PeerInfo -> CInt -> m () setTimedOutRequests ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->timed_out_requests = $(int val)} |] getBusyRequests :: MonadIO m => PeerInfo -> m CInt getBusyRequests ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->busy_requests } |] setBusyRequests :: MonadIO m => PeerInfo -> CInt -> m () setBusyRequests ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->busy_requests = $(int val)} |] getRequestsInBuffer :: MonadIO m => PeerInfo -> m CInt getRequestsInBuffer ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->requests_in_buffer } |] setRequestsInBuffer :: MonadIO m => PeerInfo -> CInt -> m () setRequestsInBuffer ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->requests_in_buffer = $(int val)} |] getTargetDlQueueLength :: MonadIO m => PeerInfo -> m CInt getTargetDlQueueLength ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->target_dl_queue_length } |] setTargetDlQueueLength :: MonadIO m => PeerInfo -> CInt -> m () setTargetDlQueueLength ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->target_dl_queue_length = $(int val)} |] getUploadQueueLength :: MonadIO m => PeerInfo -> m CInt getUploadQueueLength ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->upload_queue_length } |] setUploadQueueLength :: MonadIO m => PeerInfo -> CInt -> m () setUploadQueueLength ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->upload_queue_length = $(int val)} |] getFailcount :: MonadIO m => PeerInfo -> m CInt getFailcount ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->failcount } |] setFailcount :: MonadIO m => PeerInfo -> CInt -> m () setFailcount ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->failcount = $(int val)} |] getDownloadingPieceIndex :: MonadIO m => PeerInfo -> m CInt getDownloadingPieceIndex ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->downloading_piece_index } |] setDownloadingPieceIndex :: MonadIO m => PeerInfo -> CInt -> m () setDownloadingPieceIndex ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->downloading_piece_index = $(int val)} |] getDownloadingBlockIndex :: MonadIO m => PeerInfo -> m CInt getDownloadingBlockIndex ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->downloading_block_index } |] setDownloadingBlockIndex :: MonadIO m => PeerInfo -> CInt -> m () setDownloadingBlockIndex ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->downloading_block_index = $(int val)} |] getDownloadingProgress :: MonadIO m => PeerInfo -> m CInt getDownloadingProgress ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->downloading_progress } |] setDownloadingProgress :: MonadIO m => PeerInfo -> CInt -> m () setDownloadingProgress ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->downloading_progress = $(int val)} |] getDownloadingTotal :: MonadIO m => PeerInfo -> m CInt getDownloadingTotal ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->downloading_total } |] setDownloadingTotal :: MonadIO m => PeerInfo -> CInt -> m () setDownloadingTotal ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->downloading_total = $(int val)} |] getConnectionType :: MonadIO m => PeerInfo -> m ConnectionType getConnectionType ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| int { $(peer_info * hoPtr)->connection_type } |] setConnectionType :: MonadIO m => PeerInfo -> ConnectionType -> m () setConnectionType ho flag = do let val = fromIntegral $ fromEnum flag liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->connection_type = $(int val)} |] getRemoteDlRate :: MonadIO m => PeerInfo -> m CInt getRemoteDlRate ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->remote_dl_rate } |] setRemoteDlRate :: MonadIO m => PeerInfo -> CInt -> m () setRemoteDlRate ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->remote_dl_rate = $(int val)} |] getPendingDiskBytes :: MonadIO m => PeerInfo -> m CInt getPendingDiskBytes ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->pending_disk_bytes } |] setPendingDiskBytes :: MonadIO m => PeerInfo -> CInt -> m () setPendingDiskBytes ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->pending_disk_bytes = $(int val)} |] -- getPendingDiskReadBytes :: MonadIO m => PeerInfo -> m CInt -- getPendingDiskReadBytes ho = -- liftIO . withPtr ho $ \hoPtr -> -- [CU.exp| int { $(peer_info * hoPtr)->pending_disk_read_bytes } |] -- setPendingDiskReadBytes :: MonadIO m => PeerInfo -> CInt -> m () -- setPendingDiskReadBytes ho val = -- liftIO . withPtr ho $ \hoPtr -> -- [CU.exp| void { $(peer_info * hoPtr)->pending_disk_read_bytes = $(int val)} |] getSendQuota :: MonadIO m => PeerInfo -> m CInt getSendQuota ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->send_quota } |] setSendQuota :: MonadIO m => PeerInfo -> CInt -> m () setSendQuota ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->send_quota = $(int val)} |] getReceiveQuota :: MonadIO m => PeerInfo -> m CInt getReceiveQuota ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->receive_quota } |] setReceiveQuota :: MonadIO m => PeerInfo -> CInt -> m () setReceiveQuota ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->receive_quota = $(int val)} |] getRtt :: MonadIO m => PeerInfo -> m CInt getRtt ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->rtt } |] setRtt :: MonadIO m => PeerInfo -> CInt -> m () setRtt ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->rtt = $(int val)} |] getPeerInfoNumPieces :: MonadIO m => PeerInfo -> m CInt getPeerInfoNumPieces ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->num_pieces } |] setPeerInfoNumPieces :: MonadIO m => PeerInfo -> CInt -> m () setPeerInfoNumPieces ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->num_pieces = $(int val)} |] getDownloadRatePeak :: MonadIO m => PeerInfo -> m CInt getDownloadRatePeak ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->download_rate_peak } |] setDownloadRatePeak :: MonadIO m => PeerInfo -> CInt -> m () setDownloadRatePeak ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->download_rate_peak = $(int val)} |] getUploadRatePeak :: MonadIO m => PeerInfo -> m CInt getUploadRatePeak ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->upload_rate_peak } |] setUploadRatePeak :: MonadIO m => PeerInfo -> CInt -> m () setUploadRatePeak ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->upload_rate_peak = $(int val)} |] getPeerInfoProgressPpm :: MonadIO m => PeerInfo -> m CInt getPeerInfoProgressPpm ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->progress_ppm } |] setPeerInfoProgressPpm :: MonadIO m => PeerInfo -> CInt -> m () setPeerInfoProgressPpm ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->progress_ppm = $(int val)} |] getEstimatedReciprocationRate :: MonadIO m => PeerInfo -> m CInt getEstimatedReciprocationRate ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->estimated_reciprocation_rate } |] setEstimatedReciprocationRate :: MonadIO m => PeerInfo -> CInt -> m () setEstimatedReciprocationRate ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->estimated_reciprocation_rate = $(int val)} |] getIp :: MonadIO m => PeerInfo -> m (Text, C.CShort) getIp ho = liftIO . withPtr ho $ \hoPtr -> do addr <- fromPtr [CU.block| string * { tcp::endpoint ep = $(peer_info * hoPtr)->ip; return new std::string(ep.address().to_string()); } |] port <- [CU.block| short { tcp::endpoint ep = $(peer_info * hoPtr)->ip; return ep.port(); } |] ( , port) <$> stdStringToText addr getLocalEndpoint :: MonadIO m => PeerInfo -> m (Text, C.CShort) getLocalEndpoint ho = liftIO . withPtr ho $ \hoPtr -> do addr <- fromPtr [CU.block| string * { tcp::endpoint ep = $(peer_info * hoPtr)->local_endpoint; return new std::string(ep.address().to_string()); } |] port <- [CU.block| short { tcp::endpoint ep = $(peer_info * hoPtr)->local_endpoint; return ep.port(); } |] ( , port) <$> stdStringToText addr getReadState :: MonadIO m => PeerInfo -> m (BitFlags BwState) getReadState ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| char { $(peer_info * hoPtr)->read_state } |] setReadState :: MonadIO m => PeerInfo -> BitFlags BwState -> m () setReadState ho flags = do let val = fromIntegral $ fromEnum flags liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->read_state = $(char val)} |] getWriteState :: MonadIO m => PeerInfo -> m (BitFlags BwState) getWriteState ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| char { $(peer_info * hoPtr)->write_state } |] setWriteState :: MonadIO m => PeerInfo -> BitFlags BwState -> m () setWriteState ho flags = do let val = fromIntegral $ fromEnum flags liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->write_state = $(char val)} |]
eryx67/haskell-libtorrent
src/Network/Libtorrent/PeerInfo.hs
bsd-3-clause
26,211
0
14
7,325
6,119
3,290
2,829
561
1
{-# LANGUAGE UndecidableInstances, FlexibleInstances, FlexibleContexts, TypeFamilies, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.Signal.Multichannel -- Copyright : (c) Alexander Vivian Hugh McPhail 2010, 2014, 2015, 2016 -- License : BSD3 -- -- Maintainer : haskell.vivian.mcphail <at> gmail <dot> com -- Stability : provisional -- Portability : uses Concurrency -- -- Signal processing functions, multichannel datatype -- -- link with '-threaded' and run with +RTS -Nn, where n is the number of CPUs -- ----------------------------------------------------------------------------- -- IncoherentInstances, module Numeric.Signal.Multichannel ( Multichannel,readMultichannel,writeMultichannel, createMultichannel, sampling_rate,precision,channels,samples, detrended,filtered, getChannel,getChannels, toMatrix, mapConcurrently, detrend,filter, slice, histograms, entropy_delta_phase,mi_phase ) where ----------------------------------------------------------------------------- import qualified Numeric.Signal as S --import Complex import qualified Data.Array.IArray as I import Data.Ix --import Data.Word import Control.Concurrent --import Control.Concurrent.MVar import System.IO.Unsafe(unsafePerformIO) --import qualified Data.List as L import Data.Binary import Data.Maybe import Foreign.Storable import Numeric.LinearAlgebra hiding(range) import qualified Data.Vector.Generic as GV --import qualified Numeric.GSL.Fourier as F import qualified Numeric.GSL.Histogram as H import qualified Numeric.GSL.Histogram2D as H2 import qualified Numeric.Statistics.Information as SI import Prelude hiding(filter) import Control.Monad(replicateM) {- ------------------------------------------------------------------- instance (Binary a, Storable a) => Binary (Vector a) where put v = do let d = GV.length v put d mapM_ (\i -> put $ v @> i) [0..(d-1)] get = do d <- get xs <- replicateM d get return $ fromList xs ------------------------------------------------------------------- -} ----------------------------------------------------------------------------- -- | data type with multiple channels data Multichannel a = MC { _sampling_rate :: Int -- ^ sampling rate , _precision :: Int -- ^ bits of precision , _channels :: Int -- ^ number of channels , _length :: Int -- ^ length in samples , _detrended :: Bool -- ^ was the data detrended? , _filtered :: Maybe (Int,Int) -- ^ if filtered the passband , _data :: I.Array Int (Vector a) -- ^ data } ----------------------------------------------------------------------------- instance Binary (Multichannel Double) where put (MC s p c l de f d) = do put s put p put c put l put de put f put $! fmap convert d where convert v = let (mi,ma) = (minElement v,maxElement v) v' = GV.map (\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v in (mi,ma,v' :: Vector Word64) get = do s <- get p <- get c <- get l <- get de <- get f <- get (d :: I.Array Int (Double,Double,Vector Word64)) <- get return $! (MC s p c l de f (seq d (fmap convert) d)) where convert (mi,ma,v) = GV.map (\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word64)) * (ma - mi) + mi) v instance Binary (Multichannel Float) where put (MC s p c l de f d) = do put s put p put c put l put de put f put $! fmap convert d where convert v = let (mi,ma) = (minElement v,maxElement v) v' = GV.map (\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v in (mi,ma,v' :: Vector Word64) get = do s <- get p <- get c <- get l <- get de <- get f <- get (d :: I.Array Int (Float,Float,Vector Word32)) <- get return $! (MC s p c l de f (seq d (fmap convert) d)) where convert (mi,ma,v) = GV.map (\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word32)) * (ma - mi) + mi) v instance Binary (Multichannel (Complex Double)) where put (MC s p c l de f d) = do put s put p put c put l put de put f put $! fmap ((\(r,j) -> (convert r, convert j)) . fromComplex) d where convert v = let (mi,ma) = (minElement v,maxElement v) v' = GV.map (\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v in (mi,ma,v' :: Vector Word64) get = do s <- get p <- get c <- get l <- get de <- get f <- get (d :: I.Array Int ((Double,Double,Vector Word64),(Double,Double,Vector Word64))) <- get return $! (MC s p c l de f (seq d (fmap (\(r,j) -> toComplex (convert r,convert j)) d))) where convert (mi,ma,v) = GV.map (\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word64)) * (ma - mi) + mi) v instance Binary (Multichannel (Complex Float)) where put (MC s p c l de f d) = do put s put p put c put l put de put f put $! fmap ((\(r,j) -> (convert r, convert j)) . fromComplex) d where convert v = let (mi,ma) = (minElement v,maxElement v) v' = GV.map (\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word32))) v in (mi,ma,v' :: Vector Word32) get = do s <- get p <- get c <- get l <- get de <- get f <- get (d :: I.Array Int ((Float,Float,Vector Word32),(Float,Float,Vector Word32))) <- get return $! (MC s p c l de f (seq d (fmap (\(r,j) -> toComplex (convert r,convert j)) d))) where convert (mi,ma,v) = GV.map (\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word32)) * (ma - mi) + mi) v ----------------------------------------------------------------------------- readMultichannel :: (Binary (Multichannel a)) => FilePath -> IO (Multichannel a) readMultichannel = decodeFile writeMultichannel :: (Binary (Multichannel a)) => FilePath -> Multichannel a -> IO () writeMultichannel = encodeFile ----------------------------------------------------------------------------- -- | create a multichannel data type createMultichannel :: Storable a => Int -- ^ sampling rate -> Int -- ^ bits of precision -> [Vector a] -- ^ data -> Multichannel a -- ^ datatype createMultichannel s p d = let c = length d in MC s p c (GV.length $ head d) False Nothing (I.listArray (1,c) d) -- | the sampling rate sampling_rate :: Multichannel a -> Int sampling_rate = _sampling_rate -- | the bits of precision precision :: Multichannel a -> Int precision = _precision -- | the number of channels channels :: Multichannel a -> Int channels = _channels -- | the length, in samples samples :: Multichannel a -> Int samples = _length -- | extract one channel getChannel :: Int -> Multichannel a -> Vector a getChannel c d = (_data d) I.! c -- | extract all channels getChannels :: Multichannel a -> I.Array Int (Vector a) getChannels d = _data d -- | convert the data to a matrix with channels as rows toMatrix :: Element a => Multichannel a -> Matrix a toMatrix = fromRows . I.elems . _data -- | was the data detrended? detrended :: Multichannel a -> Bool detrended = _detrended -- | was the data filtered? filtered :: Multichannel a -> Maybe (Int,Int) filtered = _filtered ----------------------------------------------------------------------------- -- | map a function executed concurrently mapArrayConcurrently :: Ix i => (a -> b) -- ^ function to map -> I.Array i a -- ^ input -> (I.Array i b) -- ^ output mapArrayConcurrently f d = unsafePerformIO $ do let b = I.bounds d results <- replicateM (rangeSize b) newEmptyMVar mapM_ (forkIO . applyFunction f) $ zip results (I.assocs d) vectors <- mapM takeMVar results return $ I.array b vectors where applyFunction f' (m,(j,e)) = putMVar m (j,f' e) {- -- | map a function executed concurrently mapListConcurrently :: (a -> b) -- ^ function to map -> [a] -- ^ input -> [b] -- ^ output mapListConcurrently f d = unsafePerformIO $ do results <- replicateM (length d) newEmptyMVar mapM_ (forkIO . applyFunction f) zip results d mapM takeMVar results where applyFunction f' (m,e) = putMVar m (f' e) -} -- | map a function executed concurrently mapConcurrently :: Storable b => (Vector a -> Vector b) -- ^ the function to be mapped -> Multichannel a -- ^ input data -> Multichannel b -- ^ output data mapConcurrently f (MC sr p c _ de fi d) = let d' = mapArrayConcurrently f d in MC sr p c (GV.length $ d' I.! 1) de fi d' -- | map a function mapMC :: Storable b => (Vector a -> Vector b) -- ^ the function to be mapped -> Multichannel a -- ^ input data -> Multichannel b -- ^ output data mapMC f (MC sr p c _ de fi d) = let d' = fmap f d in MC sr p c (GV.length $ d' I.! 1) de fi d' ----------------------------------------------------------------------------- -- | detrend the data with a specified window size detrend :: Int -> Multichannel Double -> Multichannel Double detrend w m = let m' = mapConcurrently (S.detrend w) m in m' { _detrended = True } -- | filter the data with the given passband filter :: (S.Filterable a, Double ~ DoubleOf a) => (Int,Int) -> Multichannel a -> Multichannel a filter pb m = let m' = mapConcurrently (S.broadband_filter (_sampling_rate m) pb) m in m' { _filtered = Just pb } ----------------------------------------------------------------------------- -- | extract a slice of the data slice :: Storable a => Int -- ^ starting sample number -> Int -- ^ length -> Multichannel a -> Multichannel a slice j w m = let m' = mapConcurrently (subVector j w) m in m' { _length = w } ----------------------------------------------------------------------------- -- | calculate histograms histograms :: (S.Filterable a, Double ~ DoubleOf a) => I.Array Int (Vector a) -> Int -> (Double,Double) -> Int -> Int -> (Double,Double) -> (Double,Double) -- ^ bins and ranges -> (I.Array Int H.Histogram,I.Array (Int,Int) H2.Histogram2D) histograms d' b (l,u) bx by (lx,ux) (ly,uy) = let d = fmap double d' (bl,bu) = I.bounds d br = ((bl,bl),(bu,bu)) histarray = mapArrayConcurrently (H.fromLimits b (l,u)) d pairs = I.array br $ map (\(m,n) -> ((m,n),(d I.! m,d I.! n))) (range br) hist2array = mapArrayConcurrently (\(x,y) -> (H2.addVector (H2.emptyLimits bx by (lx,ux) (ly,uy)) x y)) pairs in (histarray,hist2array) ----------------------------------------------------------------------------- -- | calculate the entropy of the phase difference between pairs of channels (fills upper half of matrix) entropy_delta_phase :: (S.Filterable a, Double ~ DoubleOf a) => Multichannel a -- ^ input data -> Matrix Double entropy_delta_phase m = let d = _data m c = _channels m b = ((1,1),(c,c)) r = I.range b diff = I.listArray b (map (\j@(x,y) -> (j,if x <= y then Just (double $ (d I.! y)-(d I.! x)) else Nothing)) r) :: I.Array (Int,Int) ((Int,Int),Maybe (Vector Double)) h = mapArrayConcurrently (maybe Nothing (\di -> Just $ H.fromLimits 128 ((-2)*pi,2*pi) di)) (fmap snd diff) ent = mapArrayConcurrently (\(j,difvec) -> case difvec of Nothing -> 0 :: Double Just da -> SI.entropy (fromJust (h I.! j)) da) diff in fromArray2D ent ----------------------------------------------------------------------------- -- | calculate the mutual information of the phase between pairs of channels (fills upper half of matrix) mi_phase :: (S.Filterable a, Double ~ DoubleOf a) => Multichannel a -- ^ input data -> Matrix Double mi_phase m = let d = _data m (histarray,hist2array) = histograms d 128 (-pi,pi) 128 128 (-pi,pi) (-pi,pi) indhist = I.listArray (I.bounds hist2array) (I.assocs hist2array) mi = mapArrayConcurrently (doMI histarray (fmap double d)) indhist in fromArray2D mi where doMI histarray d ((x,y),h2) | x <= y = SI.mutual_information h2 (histarray I.! x) (histarray I.! y) (d I.! x,d I.! y) | otherwise = 0 -----------------------------------------------------------------------------
amcphail/hsignal
lib/Numeric/Signal/Multichannel.hs
bsd-3-clause
15,032
0
21
5,490
4,146
2,193
1,953
230
3
-- Implements a simple language embedded in the reactive resumption -- monad, ReactT. First useful application example of resumptions. {-# OPTIONS -fglasgow-exts -fno-monomorphism-restriction #-} import InterpreterLib.Algebras import InterpreterLib.Functors import InterpreterLib.Terms.ArithTerm import InterpreterLib.Terms.IfTerm import InterpreterLib.Terms.LambdaTerm import InterpreterLib.Terms.VarTerm import InterpreterLib.Terms.ImperativeTerm import Data.Ratio import Monad import Control.Monad.Reader import Control.Monad.State import Monad.Resumption -- Basic value type including numbers, booleans and functions data Value = ValNum Int | ValBool Bool | ValLambda (ValueMonad -> ValueMonad) | ValRef Int | ValNull instance Show Value where show (ValNum x) = show x show (ValBool x) = show x show (ValLambda x) = show x show (ValRef x) = "<Reference " ++ (show x) ++ ">" show ValNull = "null" instance Eq Value where (==) (ValNum x) (ValNum y) = x == y (==) (ValBool x) (ValBool y) = x == y (==) (ValLambda x) (ValLambda y) = x == y (==) (ValRef x) (ValRef y) = x == y (==) ValNull ValNull = True -- Variable environment. String used to reference Value associated with -- variable of that name. type Gamma = [(String,Value)] -- Reference environment. Integer used to reference Value associated with -- location of that number type Env = [Value] -- Variable utility functions addSubst v g = v:g findSubstValue s g = case (lookup s g) of (Just x) -> x Nothing -> error "Variable not in scope" -- Reference utility functions addRef t st = t:st deref (ValRef x) refs = refs!!x replace x v vs = (take x vs) ++ (v:(drop (x+1) vs)) -- Value type nesting monads data SignalVal = Cont | Ack instance Signal SignalVal where cont = Cont ack = Ack type ValueMonad = (ReactT SignalVal SignalVal (StateT Env (Reader Gamma))) Value instance Show (ValueMonad -> ValueMonad) where show f = "<Function Value>" instance Eq (ValueMonad -> ValueMonad) where (==) _ _ = error "Cannot compare function values." -- Define numeric properties over value so we can use +,-,*,/ and friends -- rather than define a call helper functions everywhere. This is a big -- enough pain that helpers might be preferable. instance Num Value where (+) (ValNum x) (ValNum y) = ValNum (x+y) (+) (ValBool x) (ValBool y) = ValBool (x || y) (-) (ValNum x) (ValNum y) = ValNum (x-y) (*) (ValNum x) (ValNum y) = ValNum (x*y) (*) (ValBool x) (ValBool y) = ValBool (x && y) negate (ValNum x) = ValNum (-x) negate (ValBool x) = ValBool (not x) abs (ValNum x) = ValNum (abs x) signum (ValNum x) = ValNum (signum x) fromInteger = ValNum . fromInteger instance Enum Value where succ (ValNum x) = ValNum (x+1) pred (ValNum x) = ValNum (x-1) toEnum = ValNum fromEnum (ValNum x) = x instance Integral Value where (div) (ValNum x) (ValNum y) = ValNum (div x y) quotRem (ValNum x) (ValNum y) = case (quotRem x y) of (x,y) -> (ValNum x, ValNum y) toInteger (ValNum x) = toInteger x instance Real Value where toRational (ValNum x) = (toInteger x) % (toInteger 1) instance Ord Value where (<) (ValNum x) (ValNum y) = x < y (>=) (ValNum x) (ValNum y) = x >= y (>) (ValNum x) (ValNum y) = x > y (<=) (ValNum x) (ValNum y) = x <= y max (ValNum x) (ValNum y) = ValNum (max x y) min (ValNum x) (ValNum y) = ValNum (min x y) -- Now define the interpreter. First, define the functions for the -- semantices of various operations. phiArith (Add x1 x2) = liftM2 (+) x1 x2 phiArith (Sub x1 x2) = liftM2 (-) x1 x2 phiArith (Mult x1 x2) = liftM2 (*) x1 x2 phiArith (Div x1 x2) = liftM2 (div) x1 x2 phiArith (NumEq x1 x2) = liftM2 (\v1 -> \v2 -> if (v1==v2) then 1 else 0) x1 x2 phiArith (Num x1) = return (ValNum x1) phiIf (IfTerm x1 x2 x3) = do { (ValBool x1') <- x1 ; liftM id (if x1' then x2 else x3) } phiIf TrueTerm = return $ ValBool True phiIf FalseTerm = return $ ValBool False -- Need to undo the value addition. phiLambda (Lam s _ t) = do { g <- ask ; return $ ValLambda (\v -> do { v' <- v ; local (const ((s,v'):g)) t }) } phiLambda (App t1 t2) = do { (ValLambda f) <- t1 ; (f t2) } phiVar :: (VarTerm ValueMonad) -> ValueMonad phiVar (VarTerm s) = do { v <- asks (lookup s) ; case v of (Just x) -> return x Nothing -> error "Variable not found" } -- The dummy term definition helps Haskell figure out what type VarTerm -- is defined over. It is never used. phiVar (DummyTerm x) = return (ValBool True) phiImp (NewRef t) = do { st <- get ; t' <- t ; put (addRef t' st) ; return $ (ValRef (length st)) } phiImp (DeRef t) = do { t' <- t ; st <- get ; return $ deref t' st } phiImp (Assign t1 t2) = do { t1' <- t1 ; t2' <- t2 ; case t1' of (ValRef r) -> do { env <- get ; put (replace r t2' env) ; return ValNull } _ -> error "Cannot assign to non-reference value" } phiImp (SeqTerm t1 t2) = do { t1' <- t1 ; t2' <- t2 ; return $ t2' } -- Build the term type and the term language. type TermType = ArithTerm :$: IfTerm :$: LambdaTerm () :$: VarTerm :$: ImperativeTerm type TermLang = Fix TermType -- Build the explicit algebra. termAlgebra = (mkAlgebra phiArith) @+@ (mkAlgebra phiIf) @+@ (mkAlgebra phiLambda) @+@ (mkAlgebra phiVar) @+@ (mkAlgebra phiImp) -- Write a basic handler and scheduler function and type class. -- scheduler selects the monad to be resumed. handler resumes it and -- generates the new set of resumptions. class (MonadReact m req rsp) => Simulator m req rsp a where scheduler :: [(m req rsp a)] -> (m req rsp a) handler :: [(m req rsp a)] -> (m req resp a) -> [(m req rsp a)] instance Simulator (ReactT SignalVal SignalVal) where scheduler [] = error "No monad to resume." scheduler [rm:rms] = rm handler (D v) = return v handler (P q r) = [(r 1)] -- Here are several test terms and an evaluation function to play with. To -- evaluate a term, use the following: -- runReader (runStateT (runXXX (eval termX)) []) [] -- |(eval termX)| returns the monad resulting from evaluating |termX|. -- |runStateT| then evaluates that monad with the empty environment []|. -- |runReader| then evaluates the previous monad with the empty gamma. -- |In the past, we have encapsulated the environment in some kind of -- |constructed type. Here, we are just using a list. -- Shorthand eval function eval = (cata termAlgebra) -- Shorthans for (S (Right x)) and (S (Right y)) sright = S . Right sleft = S . Left -- Some simple arithmetic terms term1 = (inn (sleft (Num 1))) one = term1 two = (inn (sleft (Num 2))) three = (inn (sleft (Num 3))) term2 = (inn (sleft (Add term1 term1))) term3 = (inn (sleft (Mult term2 term2))) term4 = (inn (sleft (Sub term2 term1))) -- Shorthands for true and false values termTrue = (inn (sright (sleft TrueTerm))) termFalse = (inn (sright (sleft FalseTerm))) -- if term that returns true case term5 = (inn (sright (sleft (IfTerm termTrue term4 term3)))) -- if term that returns false case term6 = (inn (sright (sleft (IfTerm termFalse term4 term3)))) -- Constant function that always returns term6 term7 = (inn (sright (sright (sleft (Lam "x" () term6))))) -- Constant function applied to 1 term8 = (inn (sright (sright (sleft (App term7 term1))))) -- Variable x term9 = (inn (sright (sright (sright (sleft (VarTerm "x")))))) -- Identity function term10 = (inn (sright (sright (sleft (Lam "x" () term9))))) -- Identity function applied to 1 term11 = (inn (sright (sright (sleft (App term10 term1))))) -- NewRef and return term12 = (inn (sright (sright (sright (sright (NewRef term1)))))) -- Access allocated location term13 = (inn (sright (sright (sright (sright (DeRef term12)))))) -- Replace allocated location term14 = (inn (sright (sright (sright (sright (Assign term12 term1)))))) -- -- Lambda accessing memory -- Create a reference to value 1 term15a = (inn (sright (sright (sright (sright (NewRef one)))))) -- Dereference a reference to value 1 term15b = (inn (sright (sright (sright (sright (DeRef term9)))))) -- Create a lambda dereferencing a reference to value 1 term15 = (inn (sright (sright (sleft (Lam "x" () term15b))))) -- Applying memory access lambda to location term16 = (inn (sright (sright (sleft (App term15 term12))))) -- -- Sequencing two terms -- Assign 2 to the variable "x" term17a = (inn (sright (sright (sright (sright (Assign term9 two)))))) -- Sequence assinging 2 to "x" and dereferncing "x" term17b = (inn (sright (sright (sright (sright (SeqTerm term17a term15b)))))) -- Put the sequence in a lambda with "x" as the variable name term17c = (inn (sright (sright (sleft (Lam "x" () term17b))))) -- Evaluate the lambda on a reference to the value 1. Should return 2 term17 = (inn (sright (sright (sleft (App term17c term15a)))))
palexand/interpreters
AbstractInterp/Sample5.hs
bsd-3-clause
9,519
4
18
2,497
3,300
1,736
1,564
-1
-1
module StringCompressorKata.Day6 (compress) where import Data.Char (intToDigit) compress :: Maybe String -> Maybe String compress Nothing = Nothing compress (Just "") = Just "" compress (Just (c:str)) = Just $ compress' 1 c str where compress' :: Int -> Char -> String -> String compress' counter prev "" = intToDigit counter : prev : "" compress' counter prev (current:str) = case theSameChar of True -> compress' (counter + 1) prev str False -> intToDigit counter : prev : compress' 1 current str where theSameChar = current == prev
Alex-Diez/haskell-tdd-kata
old-katas/src/StringCompressorKata/Day6.hs
bsd-3-clause
674
0
12
227
213
108
105
12
3
module Language.Haskell.TH.SCCs (binding_group, binding_groups, scc, sccs, Dependencies(..), type_dependencies, td_recur, td_descend, Named(..), printQ ) where import Language.Haskell.TH.Syntax import qualified Data.Set as Set; import Data.Set (Set) import qualified Data.Map as Map import qualified Data.Traversable as Traversable import Control.Monad (liftM, liftM2, (<=<)) import Data.Graph (stronglyConnComp, SCC(..)) -- | Helpful for debugging generated code printQ :: Show a => Maybe String -> Q a -> Q [Dec] printQ s m = do x <- m runIO (maybe (return ()) putStr s >> print x) >> return [] -- | Computes the SCC that includes the declaration of the given name; @Left@ -- is a singly acyclic declaration, @Right@ is a mutually recursive group -- (possibly of size one: singly recursion). scc :: Name -> Q (Either Name (Set Name)) scc n = (head . filter (either (==n) (Set.member n))) `liftM` sccs [n] -- | Computes all SCCs for the given names (including those it dominates) sccs :: [Name] -> Q [Either Name (Set Name)] sccs ns = do let withK f k = (,) k `liftM` f k chaotic f = loop <=< analyze where analyze = Traversable.mapM f . Map.fromList . map (\ x -> (x, x)) . Set.toList loop m | Set.null fringe = return m | otherwise = Map.union m `liftM` analyze fringe >>= loop where fringe = Set.unions (Map.elems m) `Set.difference` Map.keysSet m names <- chaotic (fmap type_dependencies . reify) (Set.fromList ns) let listify (AcyclicSCC v) = Left v listify (CyclicSCC vs) = Right (Set.fromList vs) return (map listify (stronglyConnComp [(n, n, Set.toList deps) | (n, deps) <- Map.assocs names])) -- | Wrapper for 'scc' that forgets the distinction between a single acyclic -- SCC and a singly recursive SCC binding_group :: Name -> Q (Set Name) binding_group = liftM binding_group' . scc -- | Wrapper for 'sccs' that forgets the distinction between a single acyclic -- SCC and a singly recursive SCC binding_groups :: [Name] -> Q [Set Name] binding_groups ns = (filter relevant . map binding_group') `liftM` sccs ns where relevant bg = not (Set.null (Set.intersection (Set.fromList ns) bg)) binding_group' = either Set.singleton id -- | This is semantically murky: it's just the name of anything that -- \"naturally\" /defines/ a name; error if it doesn't. class Named t where name_of :: t -> Name instance Named Info where name_of i = case i of ClassI d _ -> name_of d ClassOpI n _ _ _ -> n TyConI d -> name_of d PrimTyConI n _ _ -> n DataConI n _ _ _ -> n VarI n _ _ _ -> n TyVarI n _ -> n instance Named Dec where name_of d = case d of FunD n _ -> n ValD p _ _ -> name_of p DataD _ n _ _ _ -> n NewtypeD _ n _ _ _ -> n TySynD n _ _ -> n ClassD _ n _ _ _ -> n FamilyD _ n _ _ -> n o -> error $ show o ++ " is not a named declaration." instance Named Con where name_of c = case c of NormalC n _ -> n RecC n _ -> n InfixC _ n _ -> n ForallC _ _ c -> name_of c instance Named Pat where name_of p = case p of VarP n -> n AsP n _ -> n SigP p _ -> name_of p o -> error $ "The pattern `" ++ show o ++ "' does not define exactly one name." -- | Calculate the type declarations upon which this construct syntactically -- depends. The first argument tracks the bindings traversed; use 'td_descend' -- to maintain it. class Dependencies t where type_dependencies' :: [Name] -> t -> Set Name type_dependencies :: Dependencies t => t -> Set Name type_dependencies = type_dependencies' [] -- | Just a bit shorter than 'type_dependencies'' td_recur :: Dependencies t => [Name] -> t -> Set Name td_recur ns = type_dependencies' ns -- | Shorter than 'type_dependencies'' and also adds the name of the seconda -- argument to the tracked bindings td_descend :: (Named a, Dependencies t) => [Name] -> a -> t -> Set Name td_descend ns x = type_dependencies' (ns ++ [name_of x]) instance Dependencies Info where type_dependencies' ns i = case i of TyConI d -> td_descend ns i d PrimTyConI n _ _ -> Set.empty _ -> error $ "This version of th-sccs only calculates mutually " ++ "recursive groups for types; " ++ show (name_of i) ++ " is not a type." instance Dependencies Dec where type_dependencies' ns d = case d of DataD _ _ _ cons _ -> Set.unions (map w cons) NewtypeD _ _ _ c _ -> w c TySynD _ _ ty -> w ty FamilyD {} -> error $ "This version of th-sccs cannot calculate mutually recursive " ++ "groups for types involving type families; " ++ show (last ns) ++ " uses " ++ show (name_of d) ++ "." o -> error $ "Unexpected declaration: " ++ show o ++ "." where w x = td_descend ns d x instance Dependencies Con where type_dependencies' ns c = case c of NormalC _ sts -> w $ map snd sts RecC _ vsts -> w $ map (\ (n, _, t) -> RecordField n t) vsts InfixC stL _ stR -> w $ map snd [stL, stR] ForallC _ _ c -> type_dependencies' ns c where w xs = Set.unions (map (td_descend ns c) xs) data RecordField = RecordField Name Type instance Named RecordField where name_of (RecordField n _) = n instance Dependencies RecordField where type_dependencies' ns rf@(RecordField _ ty) = td_descend ns rf ty instance Dependencies Type where type_dependencies' ns t = case t of ForallT _ _ t -> w t ConT n -> Set.singleton n AppT tfn targ -> Set.union (w tfn) (w targ) SigT t _ -> w t _ -> Set.empty where w x = td_recur ns x
nfrisby/th-sccs
Language/Haskell/TH/SCCs.hs
bsd-3-clause
5,645
0
18
1,432
1,969
986
983
116
2
module Paths_Todo ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/bin" libdir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/lib/x86_64-linux-ghc-7.10.3/Todo-0.1.0.0-IpKjDdVbKs8326hsSNRKrL" datadir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/share/x86_64-linux-ghc-7.10.3/Todo-0.1.0.0" libexecdir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/libexec" sysconfdir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "Todo_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "Todo_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "Todo_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "Todo_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "Todo_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
frankhucek/Todo
.stack-work/dist/x86_64-linux/Cabal-1.22.5.0/build/autogen/Paths_Todo.hs
bsd-3-clause
1,566
0
10
177
362
206
156
28
1
module PPTest.Grammars.Lexical (specs) where import PP import PP.Grammars.Lexical import Test.Hspec specs = describe "PPTest.Grammars.Lexical" $ do it "should parse a regular expression (any)" $ case parseAst "." :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "." it "should parse a regular expression (value)" $ case parseAst "a" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "a" it "should parse a regular expression (class interval)" $ case parseAst "[a-z]" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "[a-z]" it "should parse a regular expression (class)" $ case parseAst "[a-z0-9.-]" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "[a-z0-9.-]" it "should parse a regular expression (group)" $ case parseAst "(a)" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "(a)" it "should parse a regular expression (option)" $ case parseAst "a?" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "a?" it "should parse a regular expression (many1)" $ case parseAst "a+" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "a+" it "should parse a regular expression (many0)" $ case parseAst "a*" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "a*" it "should parse a regular expression (choice)" $ case parseAst "abc" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "abc" it "should parse a regular expression (regexpr)" $ case parseAst "ab|cd" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "ab|cd" it "should parse a complex regular expression" $ case parseAst "(a*b)?|[a-z]+(a|[b-d])?|(a|(b|c))de|.|" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "(a*b)?|[a-z]+(a|[b-d])?|(a|(b|c))de|.|" it "should parse all meta symbols into class" $ case parseAst "[[][|][*][+][?][(][(][]][.]" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "[[][|][*][+][?][(][(][]][.]"
chlablak/platinum-parsing
test/PPTest/Grammars/Lexical.hs
bsd-3-clause
2,584
0
13
662
746
359
387
53
13
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Main ( main ) where ------------------------------------------------------------------------------- import Control.Monad.IO.Class (liftIO) import Data.Aeson (FromJSON (..), defaultOptions, genericParseJSON, genericToJSON, object, (.=)) import Data.List.NonEmpty (NonEmpty (..)) import Data.Text (Text) import Data.Time.Calendar (Day (..)) import Data.Time.Clock (UTCTime (..), secondsToDiffTime) import qualified Data.Vector as V import Database.V5.Bloodhound import GHC.Generics (Generic) import Network.HTTP.Client (defaultManagerSettings) ------------------------------------------------------------------------------- data TweetMapping = TweetMapping deriving (Eq, Show) instance ToJSON TweetMapping where toJSON TweetMapping = object [ "properties" .= object ["location" .= object ["type" .= ("geo_point" :: Text)]] ] ------------------------------------------------------------------------------- data Tweet = Tweet { user :: Text , postDate :: UTCTime , message :: Text , age :: Int , location :: LatLon } deriving (Eq, Generic, Show) ------------------------------------------------------------------------------- exampleTweet :: Tweet exampleTweet = Tweet { user = "bitemyapp" , postDate = UTCTime (ModifiedJulianDay 55000) (secondsToDiffTime 10) , message = "Use haskell!" , age = 10000 , location = loc } where loc = LatLon {lat = 40.12, lon = -71.3} instance ToJSON Tweet where toJSON = genericToJSON defaultOptions instance FromJSON Tweet where parseJSON = genericParseJSON defaultOptions main :: IO () main = runBH' $ do -- set up index _ <- createIndex indexSettings testIndex True <- indexExists testIndex _ <- putMapping testIndex testMapping TweetMapping -- create a tweet resp <- indexDocument testIndex testMapping defaultIndexDocumentSettings exampleTweet (DocId "1") liftIO (print resp) -- Response {responseStatus = Status {statusCode = 201, statusMessage = "Created"}, responseVersion = HTTP/1.1, responseHeaders = [("Content-Type","application/json; charset=UTF-8"),("Content-Length","74")], responseBody = "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"1\",\"_version\":1,\"created\":true}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose} -- bulk load let stream = V.fromList [BulkIndex testIndex testMapping (DocId "2") (toJSON exampleTweet)] _ <- bulk stream -- Bulk loads require an index refresh before new data is loaded. _ <- refreshIndex testIndex -- set up some aliases let aliasName = IndexName "twitter-alias" let iAlias = IndexAlias testIndex (IndexAliasName aliasName) let aliasRouting = Nothing let aliasFiltering = Nothing let aliasCreate = IndexAliasCreate aliasRouting aliasFiltering _ <- updateIndexAliases (AddAlias iAlias aliasCreate :| []) True <- indexExists aliasName -- create a template so that if we just write into an index named tweet-2017-01-02, for instance, the index will be automatically created with the given mapping. This is a great idea for any ongoing indices because it makes them much easier to manage and rotate. let idxTpl = IndexTemplate (TemplatePattern "tweet-*") (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping] let templateName = TemplateName "tweet-tpl" _ <- putTemplate idxTpl templateName True <- templateExists templateName -- do a search let boost = Nothing let query = TermQuery (Term "user" "bitemyapp") boost let search = mkSearch (Just query) boost _ <- searchByType testIndex testMapping search -- clean up _ <- deleteTemplate templateName _ <- deleteIndex testIndex False <- indexExists testIndex return () where testServer = Server "http://localhost:9200" runBH' = withBH defaultManagerSettings testServer testIndex = IndexName "twitter" testMapping = MappingName "tweet" indexSettings = IndexSettings (ShardCount 1) (ReplicaCount 0)
bermanjosh/bloodhound
examples/Tweet.hs
bsd-3-clause
4,281
0
17
901
894
469
425
76
1
module Bot.Util where import Paths_5chbot import qualified Data.Version as V eitherToMaybe :: Either a b -> Maybe b eitherToMaybe (Left _) = Nothing eitherToMaybe (Right a) = Just a showVersion :: String showVersion = "5chbot ver. " ++ V.showVersion version
hithroc/5chbot
src/Bot/Util.hs
bsd-3-clause
262
0
7
44
84
45
39
8
1
module Scurry.Console ( consoleThread ) where import Control.Concurrent.STM.TChan import Control.Monad (forever) import Data.List import System.IO import System.Exit import qualified GHC.Conc as GC import Scurry.Console.Parser import Scurry.Comm.Message import Scurry.Comm.Util import Scurry.Types.Network import Scurry.Types.Console import Scurry.Types.Threads import Scurry.State import Scurry.Peer -- Console command interpreter consoleThread :: StateRef -> SockWriterChan -> IO () consoleThread sr chan = do (ScurryState {scurryPeers = peers, scurryMyRecord = rec}) <- getState sr mapM_ (\(PeerRecord { peerEndPoint = ep }) -> GC.atomically $ writeTChan chan (DestSingle ep,SJoin rec)) peers forever $ do ln <- getLine case parseConsole ln of (Left err) -> badCmd err (Right ln') -> goodCmd ln' where goodCmd cmd = case cmd of CmdShutdown -> exitWith ExitSuccess CmdListPeers -> getState sr >>= print {- TODO: Find a way to do this... -} {- (CmdNewPeer ha pn) -> addPeer sr (Nothing, (EndPoint ha pn)) -} CmdNewPeer _ _ -> putStrLn "CmdNewPeer disabled for now..." (CmdRemovePeer ha pn) -> delPeer sr (EndPoint ha pn) badCmd err = putStrLn $ "Bad Command: " ++ show err
dmagyar/scurry
src/Scurry/Console.hs
bsd-3-clause
1,459
0
14
453
357
190
167
31
5
-- | Korrekturfunktion für Faktorisierung -- joe@informatik.uni-leipzig.de -- benutzt code für challenger/PCProblem -- von Markus Kreuz mai99byv@studserv.uni-leipzig.de module Faktor.Times ( make_fixed , make_quiz ) where import Challenger.Partial import Autolib.ToDoc import Autolib.Reporter import Autolib.Ana import Autolib.Size import Inter.Types import Inter.Quiz import Faktor.Times.Param import System.Random import Data.Typeable ------------------------------------------------------------------------------- data Times = Times deriving ( Eq, Show, Read, Typeable ) instance OrderScore Times where scoringOrder _ = None instance Size Integer where size _ = 1 instance Partial Times [ Integer ] Integer where describe Times xs = vcat [ text "Gesucht ist das Produkt der Zahlen " , nest 4 $ toDoc xs ] initial Times xs = sum xs total Times xs y = do let p = product xs when (y /= p) $ reject $ fsep [ text "Das Produkt der Zahlen" , toDoc xs, text "ist nicht", toDoc y ] make_fixed :: Make make_fixed = direct Times [ 222222222 :: Integer , 44444444444444, 555555555555555 ] ------------------------------------------------------------------------------- make_quiz :: Make make_quiz = quiz Times Faktor.Times.Param.example roll :: Param -> IO [ Integer ] roll p = sequence $ do i <- [ 1 .. anzahl p ] return $ do cs <- sequence $ replicate ( stellen p ) $ randomRIO ( 0, 9 ) return $ foldl ( \ a b -> 10 * a + b ) 0 cs instance Generator Times Param [ Integer ] where generator _ conf key = do xs <- roll conf return xs instance Project Times [ Integer ][ Integer ] where project _ = id
florianpilz/autotool
src/Faktor/Times.hs
gpl-2.0
1,781
32
12
441
464
248
216
-1
-1
module PatNegateResult where f :: Bool -> Int f (- 3) = 5
roberth/uu-helium
test/typeerrors/Examples/PatNegateResult.hs
gpl-3.0
59
0
7
14
26
15
11
3
1
{- | Utilities for dealing with the location of parsed entities in their source files. -} {-# LANGUAGE OverloadedStrings #-} module Base.Location ( Location(..) , Position(..) ) where import Data.Monoid import Data.Text.Prettyprint.Doc (Pretty (..)) -- | Position within a text file. data Position = Position { line :: Int, column :: Int } deriving (Eq, Show) instance Ord Position where Position l1 c1 <= Position l2 c2 = l1 < l2 || (l1 == l2 && c1 <= c2) instance Pretty Position where pretty (Position l1 c1) = pretty l1 <> ":" <> pretty c1 data Location = Location { sourceFile :: FilePath , position :: Position } deriving (Show, Eq, Ord) instance Pretty Location where pretty (Location path pos) = pretty path <> ":" <> pretty pos
Verites/verigraph
src/library/Base/Location.hs
apache-2.0
789
0
10
180
242
133
109
19
0
<?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="zh-CN"> <title>Bug Tracker</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/bugtracker/src/main/javahelp/org/zaproxy/zap/extension/bugtracker/resources/help_zh_CN/helpset_zh_CN.hs
apache-2.0
957
84
52
157
392
207
185
-1
-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="pt-BR"> <title>Getting started Guide</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Localizar</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
brunoqc/zap-extensions
src/org/zaproxy/zap/extension/gettingStarted/resources/help_pt_BR/helpset_pt_BR.hs
apache-2.0
970
84
52
158
394
208
186
-1
-1
{-| Module : Servant.Server.Auth.Token.SingleUse Description : Specific functions to work with single usage codes. Copyright : (c) Anton Gushcha, 2016 License : MIT Maintainer : ncrashed@gmail.com Stability : experimental Portability : Portable -} module Servant.Server.Auth.Token.SingleUse( makeSingleUseExpire , registerSingleUseCode , invalidateSingleUseCode , validateSingleUseCode , generateSingleUsedCodes ) where import Control.Monad import Control.Monad.IO.Class import Data.Aeson.WithField import Data.Time import Servant.API.Auth.Token import Servant.Server.Auth.Token.Common import Servant.Server.Auth.Token.Model -- | Calculate expire date for single usage code makeSingleUseExpire :: MonadIO m => NominalDiffTime -- ^ Duration of code -> m UTCTime -- ^ Time when the code expires makeSingleUseExpire dt = do t <- liftIO getCurrentTime return $ dt `addUTCTime` t -- | Register single use code in DB registerSingleUseCode :: HasStorage m => UserImplId -- ^ Id of user -> SingleUseCode -- ^ Single usage code -> Maybe UTCTime -- ^ Time when the code expires, 'Nothing' is never expiring code -> m () registerSingleUseCode uid code expire = void $ insertSingleUseCode $ UserSingleUseCode code uid expire Nothing -- | Marks single use code that it cannot be used again invalidateSingleUseCode :: HasStorage m => UserSingleUseCodeId -- ^ Id of code -> m () invalidateSingleUseCode i = do t <- liftIO getCurrentTime setSingleUseCodeUsed i $ Just t -- | Check single use code and return 'True' on success. -- -- On success invalidates single use code. validateSingleUseCode :: HasStorage m => UserImplId -- ^ Id of user -> SingleUseCode -- ^ Single usage code -> m Bool validateSingleUseCode uid code = do t <- liftIO getCurrentTime mcode <- getUnusedCode code uid t whenJust mcode $ invalidateSingleUseCode . (\(WithField i _) -> i) return $ maybe False (const True) mcode -- | Generates a set single use codes that doesn't expire. -- -- Note: previous codes without expiration are invalidated. generateSingleUsedCodes :: HasStorage m => UserImplId -- ^ Id of user -> IO SingleUseCode -- ^ Generator of codes -> Word -- Count of codes -> m [SingleUseCode] generateSingleUsedCodes uid gen n = do t <- liftIO getCurrentTime invalidatePermamentCodes uid t replicateM (fromIntegral n) $ do code <- liftIO gen _ <- insertSingleUseCode $ UserSingleUseCode code uid Nothing Nothing return code
VyacheslavHashov/servant-auth-token
src/Servant/Server/Auth/Token/SingleUse.hs
bsd-3-clause
2,483
0
12
443
478
248
230
48
1
{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds #-} module Tests.Compile.Readme where import Data.Metrology.Poly hiding (LCSU) data LengthDim = LengthDim -- each dimension is a datatype that acts as its own proxy instance Dimension LengthDim data TimeDim = TimeDim instance Dimension TimeDim type VelocityDim = LengthDim :/ TimeDim data Meter = Meter instance Unit Meter where -- declare Meter as a Unit type BaseUnit Meter = Canonical -- Meters are "canonical" type DimOfUnit Meter = LengthDim -- Meters measure Lengths instance Show Meter where -- Show instances are optional but useful show _ = "m" -- do *not* examine the argument! data Foot = Foot instance Unit Foot where type BaseUnit Foot = Meter -- Foot is defined in terms of Meter conversionRatio _ = 0.3048 -- do *not* examine the argument! -- We don't need to specify the `DimOfUnit`; -- it's implied by the `BaseUnit`. instance Show Foot where show _ = "ft" data Second = Second instance Unit Second where type BaseUnit Second = Canonical type DimOfUnit Second = TimeDim instance Show Second where show _ = "s" type LCSU = MkLCSU '[(LengthDim, Meter), (TimeDim, Second)] type Length = MkQu_DLN LengthDim LCSU Double -- Length stores lengths in our defined LCSU, using `Double` as the numerical type type Length' = MkQu_ULN Foot LCSU Double -- same as Length. Note the `U` in `MkQu_ULN`, allowing it to take a unit type Time = MkQu_DLN TimeDim LCSU Double extend :: Length -> Length -- a function over lengths extend x = redim $ x |+| (1 % Meter) inMeters :: Length -> Double -- extract the # of meters inMeters = (# Meter) -- more on this later conversion :: Length -- mixing units conversion = (4 % Meter) |+| (10 % Foot) vel :: Length %/ Time -- The `%*` and `%/` operators allow -- you to combine types vel = (3 % Meter) |/| (2 % Second) data Kilo = Kilo instance UnitPrefix Kilo where multiplier _ = 1000 kilo :: unit -> Kilo :@ unit kilo = (Kilo :@) longWayAway :: Length longWayAway = 150 % kilo Meter longWayAwayInMeters :: Double longWayAwayInMeters = longWayAway # Meter -- 150000.0 type MetersPerSecond = Meter :/ Second type Velocity1 = MkQu_ULN MetersPerSecond LCSU Double speed :: Velocity1 speed = 20 % (Meter :/ Second) type Velocity2 = Length %/ Time -- same type as Velocity1 type MetersSquared = Meter :^ Two type Area1 = MkQu_ULN MetersSquared LCSU Double type Area2 = Length %^ Two -- same type as Area1 roomSize :: Area1 roomSize = 100 % (Meter :^ sTwo) roomSize' :: Area1 roomSize' = 100 % (Meter :* Meter) type Velocity3 = (MkQu_ULN Number LCSU Double) %/ Time %* Length addVels :: Velocity1 -> Velocity1 -> Velocity3 addVels v1 v2 = redim $ (v1 |+| v2) type instance DefaultUnitOfDim LengthDim = Meter type instance DefaultUnitOfDim TimeDim = Second -- type Length = MkQu_D LengthDim
goldfirere/units
units-test/Tests/Compile/Readme.hs
bsd-3-clause
3,352
8
11
1,057
698
394
304
64
1
-- | Basic data flow analysis over the Haste AST. module Haste.AST.FlowAnalysis ( Strict (..), VarInfo (..), InfoMap, ArgMap, mkVarInfo, nullInfo, mergeVarInfos, findVarInfos ) where import Haste.AST.Syntax import Control.Monad.State import Data.List (foldl', sort, group) import qualified Data.Set as S import qualified Data.Map as M data Strict = Strict | Unknown deriving (Eq, Show) data VarInfo = VarInfo { -- | Is this var always strict? varStrict :: Strict, -- | Does this var always have the same, statically known, arity? -- @Nothing@, if var is not a function. varArity :: Maybe Int, -- | What are the sources of this var? I.e. for each occurrence where the -- var is the LHS of an assignment or substitution (including function -- call), add the RHS to this list. varAlias :: [Var] } deriving (Eq, Show) mkVarInfo :: Strict -> Maybe Int -> VarInfo mkVarInfo s ar = VarInfo s ar [] type InfoMap = M.Map Var VarInfo type ArgMap = M.Map Var [Var] nullInfo :: VarInfo nullInfo = VarInfo Unknown Nothing [] -- | Merge two var infos. The aliases of the infos are simply concatenated -- and filtered for duplicates. For concrete information, if the two infos -- disagree on any field, that field becomes unknown. mergeVarInfos :: VarInfo -> VarInfo -> VarInfo mergeVarInfos a b = VarInfo strict' arity' (varAlias a `merge` varAlias b) where strict' | varStrict a == varStrict b = varStrict a | otherwise = Unknown arity' | varArity a == varArity b = varArity a | otherwise = Nothing merge as bs = map head . group . sort $ as ++ bs -- | Merge the infos of a var with that of all of its aliases. resolveVarInfo :: InfoMap -> Var -> Maybe VarInfo resolveVarInfo m var = go (S.singleton var) var where go seen v = do nfo <- M.lookup v m let xs' = filter (not . (`S.member` seen)) (varAlias nfo) seen' = foldl' (flip S.insert) seen xs' nfos <- mapM (go seen') xs' case foldl' mergeVarInfos (nfo {varAlias = xs'}) nfos of VarInfo Unknown Nothing _ -> Nothing nfo' -> return nfo' type EvalM = State InfoMap -- | Figure out as much statically known information as possible about all -- vars in a program. The returned map will be collapsed so that recursive -- lookups are not necessary, and the 'varAlias' field of each info will -- be empty. -- -- TODO: track return values, tail call status findVarInfos :: ArgMap -> Stm -> InfoMap findVarInfos argmap = mergeAll . snd . flip runState M.empty . goS where mergeAll m = M.foldWithKey resolve m m resolve v _ m = case resolveVarInfo m v of Just nfo -> M.insert v (nfo {varAlias = []}) m _ -> m goS Stop = return () goS Cont = return () goS (Forever s) = goS s goS (Case c d as next) = do goE c goS d mapM_ (\(e, s) -> goE e >> goS s) as goS next goS (Assign (NewVar _ v) rhs next) = handleAssign v rhs >> goS next goS (Assign (LhsExp _ (Var v)) rhs next) = handleAssign v rhs >> goS next goS (Assign (LhsExp _ lhs) rhs next) = goE lhs >> goE rhs >> goS next goS (Return ex) = goE ex goS (ThunkRet ex) = goE ex goS (Tailcall ex) = goE ex handleAssign v (Var v') = v `dependsOn` v' handleAssign v (Eval (Var v')) = v `dependsOn` v' handleAssign v (Fun args body) = do v `hasInfo` mkVarInfo Strict (Just $ length args) goS body handleAssign v (Lit _) = v `hasInfo` mkVarInfo Strict Nothing handleAssign v (JSLit _) = v `hasInfo` mkVarInfo Strict Nothing handleAssign v rhs = v `hasInfo` nullInfo >> goE rhs -- If a function is ever stored anywhere except as a pure alias, we must -- immediately stop assuming things about it, since we now have no idea -- where it may be called. If it is not stored, we know that all calls to -- it will be direct, so it is safe to assume things about its arguments -- based on our static analysis. -- To be safe - but overly conservative - we set the -- info of any arguments of each function aliased by a var that occurs -- outside a permitted context (function call or synonymous assignment) -- to nullInfo. goE (Var v) = setArgsOf v nullInfo (S.singleton v) goE (Lit _) = return () goE (JSLit _) = return () goE (Not ex) = goE ex goE (BinOp _ a b) = goE a >> goE b goE (Fun _ body) = goS body goE (Call _ _ (Var f) xs) = handleCall f xs goE (Call _ _ (Fun as b) xs) = handleArgs as xs >> goS b goE (Call _ _ f xs) = mapM_ goE (f:xs) goE (Index x ix) = goE x >> goE ix goE (Arr xs) = mapM_ goE xs goE (Member x _) = goE x goE (Obj xs) = mapM_ goE (map snd xs) goE (AssignEx (Var v) rhs) = handleAssign v rhs goE (AssignEx lhs rhs) = goE lhs >> goE rhs goE (IfEx c l r) = mapM_ goE [c, l, r] goE (Eval ex) = goE ex goE (Thunk _ body) = goS body handleArgs as xs = sequence_ (zipWith handleAssign as xs) handleCall f argexs = case M.lookup f argmap of Just argvars -> handleArgs argvars argexs _ -> return () -- Finds the functions (if any) aliased by v and sets the varinfo of their -- arguments to @nfo@. setArgsOf v nfo seen = do case M.lookup v argmap of Just args -> mapM_ (`hasInfo` nullInfo) args _ -> do nfos <- get case M.lookup v nfos of Nothing -> return () Just nfo' -> do let aliases = filter (not . (`S.member` seen)) (varAlias nfo') seen' = foldl' (flip S.insert) seen aliases mapM_ (\v' -> setArgsOf v' nfo seen') aliases hasInfo :: Var -> VarInfo -> EvalM () hasInfo v nfo = do nfos <- get put $ M.alter upd v nfos where upd (Just nfo') = Just $ mergeVarInfos nfo nfo' upd _ = Just nfo dependsOn :: Var -> Var -> EvalM () dependsOn v v' = do nfos <- get put $ M.alter upd v nfos where upd (Just nfo) = Just $ nfo {varAlias = v' : varAlias nfo} upd _ = Just $ nullInfo {varAlias = [v']}
kranich/haste-compiler
src/Haste/AST/FlowAnalysis.hs
bsd-3-clause
6,515
0
25
2,114
2,060
1,038
1,022
116
36
{-# LANGUAGE BangPatterns, DeriveFunctor, RecordWildCards #-} module Network.Wreq.Cache.Store ( Store , empty , insert , delete , lookup , fromList , toList ) where import Data.Hashable (Hashable) import Data.Int (Int64) import Data.List (foldl') import Prelude hiding (lookup, map) import qualified Data.HashPSQ as HashPSQ type Epoch = Int64 data Store k v = Store { capacity :: {-# UNPACK #-} !Int , size :: {-# UNPACK #-} !Int , epoch :: {-# UNPACK #-} !Epoch , psq :: !(HashPSQ.HashPSQ k Epoch v) } instance (Show k, Show v, Ord k, Hashable k) => Show (Store k v) where show st = "fromList " ++ show (toList st) empty :: Ord k => Int -> Store k v empty cap | cap <= 0 = error "empty: invalid capacity" | otherwise = Store cap 0 0 HashPSQ.empty {-# INLINABLE empty #-} insert :: (Ord k, Hashable k) => k -> v -> Store k v -> Store k v insert k v st@Store{..} = case HashPSQ.insertView k epoch v psq of (Just (_, _), psq0) -> st {epoch = epoch + 1, psq = psq0} (Nothing, psq0) | size < capacity -> st {size = size + 1, epoch = epoch + 1, psq = psq0} | otherwise -> st {epoch = epoch + 1, psq = HashPSQ.deleteMin psq0} {-# INLINABLE insert #-} lookup :: (Ord k, Hashable k) => k -> Store k v -> Maybe (v, Store k v) lookup k st@Store{..} = case HashPSQ.alter tick k psq of (Nothing, _) -> Nothing (Just v, psq0) -> Just (v, st { epoch = epoch + 1, psq = psq0 }) where tick Nothing = (Nothing, Nothing) tick (Just (_, v)) = (Just v, Just (epoch, v)) {-# INLINABLE lookup #-} delete :: (Ord k, Hashable k) => k -> Store k v -> Store k v delete k st@Store{..} = case HashPSQ.deleteView k psq of Nothing -> st Just (_, _, psq0) -> st {size = size - 1, psq = psq0} {-# INLINABLE delete #-} fromList :: (Ord k, Hashable k) => Int -> [(k, v)] -> Store k v fromList = foldl' (flip (uncurry insert)) . empty {-# INLINABLE fromList #-} toList :: (Ord k, Hashable k) => Store k v -> [(k, v)] toList Store{..} = [(k,v) | (k, _, v) <- HashPSQ.toList psq] {-# INLINABLE toList #-}
bitemyapp/wreq
Network/Wreq/Cache/Store.hs
bsd-3-clause
2,108
0
12
531
919
503
416
49
3
<?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="bs-BA"> <title>Directory List v2.3 LC</title> <maps> <homeID>directorylistv2_3_lc</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/directorylistv2_3_lc/src/main/javahelp/help_bs_BA/helpset_bs_BA.hs
apache-2.0
984
83
52
158
397
210
187
-1
-1
module A4 where data T a = C1 a over :: (T b) -> b over (C1 x) = x under :: (T a) -> a under (C1 x) = x
SAdams601/HaRe
old/testing/addCon/A4.hs
bsd-3-clause
109
0
7
36
72
39
33
6
1
{-| Module describing an NIC. The NIC data type only holds data about a NIC, but does not provide any logic. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Nic ( Nic(..) , Mode(..) , List , create ) where import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Types as T -- * Type declarations data Mode = Bridged | Routed | OpenVSwitch deriving (Show, Eq) -- | The NIC type. -- -- It holds the data for a NIC as it is provided via the IAllocator protocol -- for an instance creation request. All data in those request is optional, -- that's why all fields are Maybe's. -- -- TODO: Another name might be more appropriate for this type, as for example -- RequestedNic. But this type is used as a field in the Instance type, which -- is not named RequestedInstance, so such a name would be weird. PartialNic -- already exists in Objects, but doesn't fit the bill here, as it contains -- a required field (mac). Objects and the types therein are subject to being -- reworked, so until then this type is left as is. data Nic = Nic { mac :: Maybe String -- ^ MAC address of the NIC , ip :: Maybe String -- ^ IP address of the NIC , mode :: Maybe Mode -- ^ the mode the NIC operates in , link :: Maybe String -- ^ the link of the NIC , bridge :: Maybe String -- ^ the bridge this NIC is connected to if -- the mode is Bridged , network :: Maybe T.NetworkID -- ^ network UUID if this NIC is connected -- to a network } deriving (Show, Eq) -- | A simple name for an instance map. type List = Container.Container Nic -- * Initialization -- | Create a NIC. -- create :: Maybe String -> Maybe String -> Maybe Mode -> Maybe String -> Maybe String -> Maybe T.NetworkID -> Nic create mac_init ip_init mode_init link_init bridge_init network_init = Nic { mac = mac_init , ip = ip_init , mode = mode_init , link = link_init , bridge = bridge_init , network = network_init }
apyrgio/snf-ganeti
src/Ganeti/HTools/Nic.hs
bsd-2-clause
3,420
0
12
795
290
179
111
31
1
{-# LANGUAGE BangPatterns, OverloadedStrings #-} import Control.DeepSeq import Control.Exception import Control.Monad import Data.Aeson import Data.Aeson.Parser import Data.Attoparsec import Data.Time.Clock import System.Environment (getArgs) import System.IO import qualified Data.ByteString as B main = do (cnt:args) <- getArgs let count = read cnt :: Int forM_ args $ \arg -> bracket (openFile arg ReadMode) hClose $ \h -> do putStrLn $ arg ++ ":" start <- getCurrentTime let loop !n | n >= count = return () | otherwise = do let go = do s <- B.hGet h 16384 if B.null s then loop (n+1) else go go loop 0 end <- getCurrentTime putStrLn $ " " ++ show (diffUTCTime end start)
jprider63/aeson-ios-0.8.0.2
benchmarks/ReadFile.hs
bsd-3-clause
821
0
27
255
275
136
139
29
2
{-# LANGUAGE BangPatterns, Rank2Types, OverloadedStrings, RecordWildCards, MagicHash, UnboxedTuples #-} module Data.Attoparsec.Internal.Fhthagn ( inlinePerformIO ) where import GHC.Base (realWorld#) import GHC.IO (IO(IO)) -- | Just like unsafePerformIO, but we inline it. Big performance gains as -- it exposes lots of things to further inlining. /Very unsafe/. In -- particular, you should do no memory allocation inside an -- 'inlinePerformIO' block. On Hugs this is just @unsafePerformIO@. inlinePerformIO :: IO a -> a inlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r {-# INLINE inlinePerformIO #-}
DavidAlphaFox/ghc
utils/haddock/haddock-library/vendor/attoparsec-0.12.1.1/Data/Attoparsec/Internal/Fhthagn.hs
bsd-3-clause
636
0
8
110
87
52
35
10
1
module Main where import System.IO import DynFlags import GHC import Exception import Module import FastString import MonadUtils import Outputable import Bag (filterBag,isEmptyBag) import System.Directory (removeFile) import System.Environment( getArgs ) import PrelNames main :: IO() main = do [libdir] <- getArgs ok <- runGhc (Just libdir) $ do dflags <- getSessionDynFlags setSessionDynFlags dflags liftIO (setUnsafeGlobalDynFlags dflags) setContext [ IIDecl (simpleImportDecl pRELUDE_NAME) , IIDecl (simpleImportDecl (mkModuleNameFS (fsLit "System.IO")))] runDecls "data X = Y ()" execStmt "print True" execOptions gtry $ execStmt "print (Y ())" execOptions :: GhcMonad m => m (Either SomeException ExecResult) runDecls "data X = Y () deriving Show" _ <- dynCompileExpr "'x'" execStmt "print (Y ())" execOptions execStmt "System.IO.hFlush System.IO.stdout" execOptions print "done"
urbanslug/ghc
testsuite/tests/ghc-api/T8628.hs
bsd-3-clause
1,039
0
19
267
261
127
134
30
1
------------------------------------------------------------------------------- -- | -- Module : Network.CURL720 -- Copyright : Copyright (c) 2012-2015 Krzysztof Kardzis -- License : ISC License (MIT/BSD-style, see LICENSE file for details) -- -- Maintainer : Krzysztof Kardzis <kkardzis@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- <<https://ga-beacon.appspot.com/UA-53767359-1/curlhs/Network-CURL720>> ------------------------------------------------------------------------------- module Network.CURL720 ( module Network.CURL000 -- | -- This module exports __libcurl 7.20 API__. Version 7.20 or higher -- of the @libcurl[.dll|.so|.dylib]@ is required at program runtime. -- -- More info may be found in the <docs/#/README.md docs>. ------------------------------------------------------------------------------- -- * Global interface ------------------------------------------------------------------------------- -- ** Version info , curl_version , curl_version_info , CURL_version_info (..) , CURLfeature ( CURL_VERSION_IPV6 , CURL_VERSION_KERBEROS4 , CURL_VERSION_SSL , CURL_VERSION_LIBZ , CURL_VERSION_NTLM , CURL_VERSION_GSSNEGOTIATE , CURL_VERSION_DEBUG , CURL_VERSION_CURLDEBUG , CURL_VERSION_ASYNCHDNS , CURL_VERSION_SPNEGO , CURL_VERSION_LARGEFILE , CURL_VERSION_IDN , CURL_VERSION_SSPI , CURL_VERSION_CONV ) ------------------------------------------------------------------------------- -- * Easy interface -- | See <http://curl.haxx.se/libcurl/c/libcurl-easy.html> -- for easy interface overview. ------------------------------------------------------------------------------- -- ** Init / Cleanup , curl_easy_init , curl_easy_cleanup , curl_easy_reset , CURL -- ** Transfer , curl_easy_perform , curl_easy_recv , curl_easy_send -- ** Get info , curl_easy_getinfo , CURLinfo ( CURLINFO_EFFECTIVE_URL , CURLINFO_RESPONSE_CODE , CURLINFO_HTTP_CONNECTCODE , CURLINFO_FILETIME , CURLINFO_TOTAL_TIME , CURLINFO_NAMELOOKUP_TIME , CURLINFO_CONNECT_TIME , CURLINFO_APPCONNECT_TIME , CURLINFO_PRETRANSFER_TIME , CURLINFO_STARTTRANSFER_TIME , CURLINFO_REDIRECT_TIME , CURLINFO_REDIRECT_COUNT , CURLINFO_REDIRECT_URL , CURLINFO_SIZE_UPLOAD , CURLINFO_SIZE_DOWNLOAD , CURLINFO_SPEED_DOWNLOAD , CURLINFO_SPEED_UPLOAD , CURLINFO_HEADER_SIZE , CURLINFO_REQUEST_SIZE , CURLINFO_SSL_VERIFYRESULT , CURLINFO_SSL_ENGINES , CURLINFO_CONTENT_LENGTH_DOWNLOAD , CURLINFO_CONTENT_LENGTH_UPLOAD , CURLINFO_CONTENT_TYPE , CURLINFO_HTTPAUTH_AVAIL , CURLINFO_PROXYAUTH_AVAIL , CURLINFO_OS_ERRNO , CURLINFO_NUM_CONNECTS , CURLINFO_PRIMARY_IP , CURLINFO_COOKIELIST , CURLINFO_LASTSOCKET , CURLINFO_FTP_ENTRY_PATH , CURLINFO_CERTINFO , CURLINFO_CONDITION_UNMET , CURLINFO_RTSP_SESSION_ID , CURLINFO_RTSP_CLIENT_CSEQ , CURLINFO_RTSP_SERVER_CSEQ , CURLINFO_RTSP_CSEQ_RECV ) -- ** Set options , curl_easy_setopt , CURLoption ---- BEHAVIOR OPTIONS --------------------------------------------------- ( CURLOPT_VERBOSE , CURLOPT_HEADER , CURLOPT_NOPROGRESS , CURLOPT_NOSIGNAL ---- CALLBACK OPTIONS --------------------------------------------------- , CURLOPT_WRITEFUNCTION -- CURLOPT_WRITEDATA , CURLOPT_READFUNCTION -- CURLOPT_READDATA -- CURLOPT_IOCTLFUNCTION -- CURLOPT_IOCTLDATA -- CURLOPT_SEEKFUNCTION -- CURLOPT_SEEKDATA -- CURLOPT_SOCKOPTFUNCTION -- CURLOPT_SOCKOPTDATA -- CURLOPT_OPENSOCKETFUNCTION -- CURLOPT_OPENSOCKETDATA -- CURLOPT_PROGRESSFUNCTION -- CURLOPT_PROGRESSDATA , CURLOPT_HEADERFUNCTION -- CURLOPT_HEADERDATA -- CURLOPT_DEBUGFUNCTION -- CURLOPT_DEBUGDATA -- CURLOPT_SSL_CTX_FUNCTION -- CURLOPT_SSL_CTX_DATA -- CURLOPT_CONV_TO_NETWORK_FUNCTION -- CURLOPT_CONV_FROM_NETWORK_FUNCTION -- CURLOPT_CONV_FROM_UTF8_FUNCTION -- CURLOPT_INTERLEAVEFUNCTION -- CURLOPT_INTERLEAVEDATA ---- ERROR OPTIONS ------------------------------------------------------ -- CURLOPT_ERRORBUFFER -- CURLOPT_STDERR , CURLOPT_FAILONERROR ---- NETWORK OPTIONS ---------------------------------------------------- , CURLOPT_URL , CURLOPT_PROTOCOLS , CURLOPT_REDIR_PROTOCOLS , CURLOPT_PROXY , CURLOPT_PROXYPORT , CURLOPT_PROXYTYPE , CURLOPT_NOPROXY , CURLOPT_HTTPPROXYTUNNEL , CURLOPT_SOCKS5_GSSAPI_SERVICE , CURLOPT_SOCKS5_GSSAPI_NEC , CURLOPT_INTERFACE , CURLOPT_LOCALPORT , CURLOPT_LOCALPORTRANGE , CURLOPT_DNS_CACHE_TIMEOUT -- CURLOPT_DNS_USE_GLOBAL_CACHE , CURLOPT_BUFFERSIZE , CURLOPT_PORT , CURLOPT_TCP_NODELAY , CURLOPT_ADDRESS_SCOPE ---- NAMES and PASSWORDS OPTIONS (Authentication) ----------------------- , CURLOPT_NETRC , CURLOPT_NETRC_FILE , CURLOPT_USERPWD , CURLOPT_PROXYUSERPWD , CURLOPT_USERNAME , CURLOPT_PASSWORD , CURLOPT_PROXYUSERNAME , CURLOPT_PROXYPASSWORD , CURLOPT_HTTPAUTH , CURLOPT_PROXYAUTH ---- HTTP OPTIONS ------------------------------------------------------- , CURLOPT_AUTOREFERER , CURLOPT_ACCEPT_ENCODING -- CURLOPT_ENCODING , CURLOPT_FOLLOWLOCATION , CURLOPT_UNRESTRICTED_AUTH , CURLOPT_MAXREDIRS , CURLOPT_POSTREDIR , CURLOPT_PUT , CURLOPT_POST -- CURLOPT_POSTFIELDS , CURLOPT_POSTFIELDSIZE , CURLOPT_POSTFIELDSIZE_LARGE , CURLOPT_COPYPOSTFIELDS -- CURLOPT_HTTPPOST , CURLOPT_REFERER , CURLOPT_USERAGENT , CURLOPT_HTTPHEADER , CURLOPT_HTTP200ALIASES , CURLOPT_COOKIE , CURLOPT_COOKIEFILE , CURLOPT_COOKIEJAR , CURLOPT_COOKIESESSION , CURLOPT_COOKIELIST , CURLOPT_HTTPGET , CURLOPT_HTTP_VERSION , CURLOPT_IGNORE_CONTENT_LENGTH , CURLOPT_HTTP_CONTENT_DECODING , CURLOPT_HTTP_TRANSFER_DECODING ---- SMTP OPTIONS ------------------------------------------------------- , CURLOPT_MAIL_FROM , CURLOPT_MAIL_RCPT ---- TFTP OPTIONS ------------------------------------------------------- , CURLOPT_TFTP_BLKSIZE ---- FTP OPTIONS -------------------------------------------------------- , CURLOPT_FTPPORT , CURLOPT_QUOTE , CURLOPT_POSTQUOTE , CURLOPT_PREQUOTE , CURLOPT_DIRLISTONLY , CURLOPT_APPEND , CURLOPT_FTP_USE_EPRT , CURLOPT_FTP_USE_EPSV , CURLOPT_FTP_USE_PRET , CURLOPT_FTP_CREATE_MISSING_DIRS , CURLOPT_FTP_RESPONSE_TIMEOUT , CURLOPT_FTP_ALTERNATIVE_TO_USER , CURLOPT_FTP_SKIP_PASV_IP , CURLOPT_USE_SSL , CURLOPT_FTPSSLAUTH , CURLOPT_FTP_SSL_CCC , CURLOPT_FTP_ACCOUNT , CURLOPT_FTP_FILEMETHOD ---- RTSP OPTIONS ------------------------------------------------------- , CURLOPT_RTSP_REQUEST , CURLOPT_RTSP_SESSION_ID , CURLOPT_RTSP_STREAM_URI , CURLOPT_RTSP_TRANSPORT , CURLOPT_RTSP_HEADER , CURLOPT_RTSP_CLIENT_CSEQ , CURLOPT_RTSP_SERVER_CSEQ ---- PROTOCOL OPTIONS --------------------------------------------------- , CURLOPT_TRANSFERTEXT , CURLOPT_PROXY_TRANSFER_MODE , CURLOPT_CRLF , CURLOPT_RANGE , CURLOPT_RESUME_FROM , CURLOPT_RESUME_FROM_LARGE , CURLOPT_CUSTOMREQUEST , CURLOPT_FILETIME , CURLOPT_NOBODY , CURLOPT_INFILESIZE , CURLOPT_INFILESIZE_LARGE , CURLOPT_UPLOAD , CURLOPT_MAXFILESIZE , CURLOPT_MAXFILESIZE_LARGE , CURLOPT_TIMECONDITION , CURLOPT_TIMEVALUE ---- CONNECTION OPTIONS ------------------------------------------------- , CURLOPT_TIMEOUT , CURLOPT_TIMEOUT_MS , CURLOPT_LOW_SPEED_LIMIT , CURLOPT_LOW_SPEED_TIME , CURLOPT_MAX_SEND_SPEED_LARGE , CURLOPT_MAX_RECV_SPEED_LARGE , CURLOPT_MAXCONNECTS -- CURLOPT_CLOSEPOLICY , CURLOPT_FRESH_CONNECT , CURLOPT_FORBID_REUSE , CURLOPT_CONNECTTIMEOUT , CURLOPT_CONNECTTIMEOUT_MS , CURLOPT_IPRESOLVE , CURLOPT_CONNECT_ONLY ---- SSL and SECURITY OPTIONS ------------------------------------------- , CURLOPT_SSLCERT , CURLOPT_SSLCERTTYPE , CURLOPT_SSLKEY , CURLOPT_SSLKEYTYPE , CURLOPT_KEYPASSWD , CURLOPT_SSLENGINE , CURLOPT_SSLENGINE_DEFAULT , CURLOPT_SSLVERSION , CURLOPT_SSL_VERIFYPEER , CURLOPT_CAINFO , CURLOPT_ISSUERCERT , CURLOPT_CAPATH , CURLOPT_CRLFILE , CURLOPT_CERTINFO , CURLOPT_RANDOM_FILE , CURLOPT_EGDSOCKET , CURLOPT_SSL_VERIFYHOST , CURLOPT_SSL_CIPHER_LIST , CURLOPT_SSL_SESSIONID_CACHE , CURLOPT_KRBLEVEL ---- SSH OPTIONS -------------------------------------------------------- , CURLOPT_SSH_AUTH_TYPES , CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 , CURLOPT_SSH_PUBLIC_KEYFILE , CURLOPT_SSH_PRIVATE_KEYFILE , CURLOPT_SSH_KNOWNHOSTS -- CURLOPT_SSH_KEYFUNCTION -- CURLOPT_SSH_KEYDATA ---- OTHER OPTIONS ------------------------------------------------------ -- CURLOPT_PRIVATE , CURLOPT_SHARE , CURLOPT_NEW_FILE_PERMS , CURLOPT_NEW_DIRECTORY_PERMS ---- TELNET OPTIONS ----------------------------------------------------- , CURLOPT_TELNETOPTIONS ) -- *** Callbacks , CURL_write_callback , CURL_write_response (..) , CURL_read_callback , CURL_read_response (..) , CURL_header_callback, CURL_header_response (..) -- *** Constants , CURLproto ( CURLPROTO_ALL , CURLPROTO_HTTP , CURLPROTO_HTTPS , CURLPROTO_FTP , CURLPROTO_FTPS , CURLPROTO_SCP , CURLPROTO_SFTP , CURLPROTO_TELNET , CURLPROTO_LDAP , CURLPROTO_LDAPS , CURLPROTO_DICT , CURLPROTO_FILE , CURLPROTO_TFTP , CURLPROTO_IMAP , CURLPROTO_IMAPS , CURLPROTO_POP3 , CURLPROTO_POP3S , CURLPROTO_SMTP , CURLPROTO_SMTPS , CURLPROTO_RTSP ) , CURLproxy ( CURLPROXY_HTTP , CURLPROXY_HTTP_1_0 , CURLPROXY_SOCKS4 , CURLPROXY_SOCKS5 , CURLPROXY_SOCKS4A , CURLPROXY_SOCKS5_HOSTNAME ) , CURLnetrc ( CURL_NETRC_IGNORED , CURL_NETRC_OPTIONAL , CURL_NETRC_REQUIRED ) , CURLauth ( CURLAUTH_BASIC , CURLAUTH_DIGEST , CURLAUTH_DIGEST_IE , CURLAUTH_GSSNEGOTIATE , CURLAUTH_NTLM , CURLAUTH_ONLY , CURLAUTH_ANY , CURLAUTH_ANYSAFE ) , CURLredir ( CURL_REDIR_GET_ALL , CURL_REDIR_POST_301 , CURL_REDIR_POST_302 , CURL_REDIR_POST_ALL ) , CURLhttpver ( CURL_HTTP_VERSION_NONE , CURL_HTTP_VERSION_1_0 , CURL_HTTP_VERSION_1_1 ) , CURLftpcreate ( CURLFTP_CREATE_DIR_NONE , CURLFTP_CREATE_DIR , CURLFTP_CREATE_DIR_RETRY ) , CURLftpauth ( CURLFTPAUTH_DEFAULT , CURLFTPAUTH_SSL , CURLFTPAUTH_TLS ) , CURLftpssl ( CURLFTPSSL_CCC_NONE , CURLFTPSSL_CCC_PASSIVE , CURLFTPSSL_CCC_ACTIVE ) , CURLftpmethod ( CURLFTPMETHOD_DEFAULT , CURLFTPMETHOD_MULTICWD , CURLFTPMETHOD_NOCWD , CURLFTPMETHOD_SINGLECWD ) , CURLrtspreq ( CURL_RTSPREQ_OPTIONS , CURL_RTSPREQ_DESCRIBE , CURL_RTSPREQ_ANNOUNCE , CURL_RTSPREQ_SETUP , CURL_RTSPREQ_PLAY , CURL_RTSPREQ_PAUSE , CURL_RTSPREQ_TEARDOWN , CURL_RTSPREQ_GET_PARAMETER , CURL_RTSPREQ_SET_PARAMETER , CURL_RTSPREQ_RECORD , CURL_RTSPREQ_RECEIVE ) , CURLtimecond ( CURL_TIMECOND_NONE , CURL_TIMECOND_IFMODSINCE , CURL_TIMECOND_IFUNMODSINCE , CURL_TIMECOND_LASTMOD ) , CURLipresolve ( CURL_IPRESOLVE_WHATEVER , CURL_IPRESOLVE_V4 , CURL_IPRESOLVE_V6 ) , CURLusessl ( CURLUSESSL_NONE , CURLUSESSL_TRY , CURLUSESSL_CONTROL , CURLUSESSL_ALL ) , CURLsslver ( CURL_SSLVERSION_DEFAULT , CURL_SSLVERSION_TLSv1 , CURL_SSLVERSION_SSLv2 , CURL_SSLVERSION_SSLv3 ) , CURLsshauth ( CURLSSH_AUTH_ANY , CURLSSH_AUTH_NONE , CURLSSH_AUTH_PUBLICKEY , CURLSSH_AUTH_PASSWORD , CURLSSH_AUTH_HOST , CURLSSH_AUTH_KEYBOARD , CURLSSH_AUTH_DEFAULT ) -- ** Exceptions -- | More about error codes in libcurl on -- <http://curl.haxx.se/libcurl/c/libcurl-errors.html> , CURLE (..) , CURLC (..) ------------------------------------------------------------------------------- -- * Multi interface -- | See <http://curl.haxx.se/libcurl/c/libcurl-multi.html> -- for multi interface overview. ------------------------------------------------------------------------------- -- | TODO ------------------------------------------------------------------------------- -- * Share interface -- | See <http://curl.haxx.se/libcurl/c/libcurl-share.html> -- for share interface overview. ------------------------------------------------------------------------------- -- ** Init / Cleanup , curl_share_init , curl_share_cleanup , CURLSH -- ** Set options , curl_share_setopt , CURLSHoption ( CURLSHOPT_SHARE , CURLSHOPT_UNSHARE ) , CURLSHlockdata ( CURL_LOCK_DATA_COOKIE , CURL_LOCK_DATA_DNS , CURL_LOCK_DATA_SSL_SESSION ) -- ** Exceptions -- | More about error codes in libcurl on -- <http://curl.haxx.se/libcurl/c/libcurl-errors.html> , CURLSHE (..) , CURLSHC (..) ) where import Network.CURL000.LibHS import Network.CURL000.Types import Network.CURL000
kkardzis/curlhs
Network/CURL720.hs
isc
14,022
0
5
3,414
933
846
87
385
0
{-# LANGUAGE OverloadedStrings #-} module Jamo where import Prelude hiding (readFile, putStrLn, lookup, writeFile) import Data.List (intersect, (\\)) import Data.Map (fromList, lookup) import Data.Attoparsec.Text (takeWhile1, takeTill, inClass, char, parseOnly, choice, many', endOfInput) import Data.Text (Text, cons, unpack, pack, singleton, intercalate, intersperse) import Data.Text.IO (readFile, writeFile) import qualified Data.Text as T import Data.Monoid ((<>)) import Debug.Trace (trace) cho = "ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ" jong = "ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ" jung = "ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ" jaeum = intersect cho jong unique_cho = cho \\ jaeum unique_jong = jong \\ jaeum declBody :: Char -> Bool -> String -> Text declBody c indent = intercalate "\n" . map (\x -> pack ((if indent then " " else "") ++ x:" = " ++ c:x:"")) datas = fromList [ ("data-cho", intercalate "|" $ map (cons 'C' . singleton) cho) , ("data-jung", intercalate "|" $ map (cons 'M' . singleton) jung) , ("data-jong", intercalate "|" $ map (cons 'J' . singleton) ('_':jong)) , ("jaeum-comma-sep", intersperse ',' $ pack jaeum) , ("unique-cho-comma-sep", intersperse ',' $ pack unique_cho) , ("unique-jong-comma-sep", intersperse ',' $ pack unique_jong) , ("jung-comma-sep", intersperse ',' $ pack jung) , ("jaeum-cho", declBody 'C' True jaeum) , ("jaeum-jong", declBody 'J' True jaeum) , ("unique-cho", declBody 'C' False unique_cho) , ("unique-jong", declBody 'J' False unique_jong) , ("jung", declBody 'M' False jung) , ("data-deriving", "deriving (Enum, Eq, Ord, Show)") ] holeParser = do "{-!" a <- takeWhile1 (inClass "a-z-") let b = T.last a == '-' k = if b then T.init a else a if b then "}" else "-}" case lookup k datas of Just z -> return z Nothing -> error $ "Cannot find " ++ unpack k takeallParser = takeWhile1 (/='{') consumebraceParser = do char '{' a <- takeTill (=='{') return a main :: IO () main = do a <- readFile "template/Jamo.template.hs" case parseOnly (many' $ choice [holeParser, consumebraceParser, takeallParser]) a of Left err -> error err Right xs -> writeFile "src/Jamo.hs" $ T.concat xs
xnuk/another-aheui-interpreter
template/Jamo.hs
mit
2,569
0
17
659
797
432
365
54
4
----------------------------------------------------------------------------- -- -- Module : Network.Google -- Copyright : (c) 2012-13 Brian W Bush -- License : MIT -- -- Maintainer : Brian W Bush <b.w.bush@acm.org> -- Stability : Stable -- Portability : Portable -- -- | Helper functions for accessing Google APIs. -- ----------------------------------------------------------------------------- {-# LANGUAGE FlexibleInstances #-} module Network.Google ( -- * Types AccessToken , toAccessToken , ProjectId -- * Functions , appendBody , appendHeaders , appendQuery , doManagedRequest , doRequest , makeHeaderName , makeProjectRequest , makeRequest , makeRequestValue ) where import Control.Exception (finally) import Control.Monad.Trans.Resource (ResourceT, runResourceT) import Data.List (intercalate) import Data.Maybe (fromJust) import Data.ByteString as BS (ByteString) import Data.ByteString.Char8 as BS8 (ByteString, append, pack) import Data.ByteString.Lazy.Char8 as LBS8 (ByteString) import Data.ByteString.Lazy.UTF8 (toString) import Data.CaseInsensitive as CI (CI(..), mk) import Network.HTTP.Base (urlEncode) import Network.HTTP.Conduit (Manager, Request(..), RequestBody(..), Response(..), closeManager, def, httpLbs, newManager, responseBody) import Text.JSON (JSValue, Result(Ok), decode) import Text.XML.Light (Element, parseXMLDoc) -- | OAuth 2.0 access token. type AccessToken = BS.ByteString -- | Convert a string to an access token. toAccessToken :: String -- ^ The string. -> AccessToken -- ^ The OAuth 2.0 access token. toAccessToken = BS8.pack -- | Google API project ID, see <https://code.google.com/apis/console>. type ProjectId = String -- | Construct a Google API request. makeRequest :: AccessToken -- ^ The OAuth 2.0 access token. -> (String, String) -- ^ The Google API name and version. -> String -- ^ The HTTP method. -> (String, String) -- ^ The host and path for the request. -> Request m -- ^ The HTTP request. makeRequest accessToken (apiName, apiVersion) method (host, path) = -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. def { method = BS8.pack method , secure = True , host = BS8.pack host , port = 443 , path = BS8.pack path , requestHeaders = [ (makeHeaderName apiName, BS8.pack apiVersion) , (makeHeaderName "Authorization", BS8.append (BS8.pack "OAuth ") accessToken) ] } -- | Construct a project-related Google API request. makeProjectRequest :: ProjectId -- ^ The project ID. -> AccessToken -- ^ The OAuth 2.0 access token. -> (String, String) -- ^ The Google API name and version. -> String -- ^ The HTTP method. -> (String, String) -- ^ The host and path for the request. -> Request m -- ^ The HTTP request. makeProjectRequest projectId accessToken api method hostPath = appendHeaders [ ("x-goog-project-id", projectId) ] (makeRequest accessToken api method hostPath) -- | Class for Google API request. class DoRequest a where -- | Perform a request. doRequest :: Request (ResourceT IO) -- ^ The request. -> IO a -- ^ The action returning the result of performing the request. doRequest request = do {-- -- TODO: The following seems cleaner, but has type/instance problems: (_, manager) <- allocate (newManager def) closeManager doManagedRequest manager request --} manager <- newManager def finally (doManagedRequest manager request) (closeManager manager) doManagedRequest :: Manager -- ^ The conduit HTTP manager. -> Request (ResourceT IO) -- ^ The request. -> IO a -- ^ The action returning the result of performing the request. instance DoRequest LBS8.ByteString where doManagedRequest manager request = do response <- runResourceT (httpLbs request manager) return $ responseBody response instance DoRequest String where doManagedRequest manager request = do result <- doManagedRequest manager request return $ toString result instance DoRequest [(String, String)] where doManagedRequest manager request = do response <- runResourceT (httpLbs request manager) return $ read . show $ responseHeaders response instance DoRequest () where doManagedRequest manager request = do doManagedRequest manager request :: IO LBS8.ByteString return () instance DoRequest Element where doManagedRequest manager request = do result <- doManagedRequest manager request :: IO String return $ fromJust $ parseXMLDoc result instance DoRequest JSValue where doManagedRequest manager request = do result <- doManagedRequest manager request :: IO String let Ok result' = decode result return result' -- | Prepare a string for inclusion in a request. makeRequestValue :: String -- ^ The string. -> BS8.ByteString -- ^ The prepared string. -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. makeRequestValue = BS8.pack -- | Prepare a name\/key for a header. makeHeaderName :: String -- ^ The name. -> CI.CI BS8.ByteString -- ^ The prepared name. -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. makeHeaderName = CI.mk . BS8.pack -- | Prepare a value for a header. makeHeaderValue :: String -- ^ The value. -> BS8.ByteString -- ^ The prepared value. -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. makeHeaderValue = BS8.pack -- | Append headers to a request. appendHeaders :: [(String, String)] -- ^ The (name\/key, value) pairs for the headers. -> Request m -- ^ The request. -> Request m -- ^ The request with the additional headers. appendHeaders headers request = let headerize :: (String, String) -> (CI.CI BS8.ByteString, BS8.ByteString) headerize (n, v) = (makeHeaderName n, makeHeaderValue v) in request { requestHeaders = requestHeaders request ++ map headerize headers } -- | Append a body to a request. appendBody :: LBS8.ByteString -- ^ The data for the body. -> Request m -- ^ The request. -> Request m -- ^ The request with the body appended. appendBody bytes request = request { requestBody = RequestBodyLBS bytes } -- | Append a query to a request. appendQuery :: [(String, String)] -- ^ The query keys and values. -> Request m -- ^ The request. -> Request m -- ^ The request with the query appended. appendQuery query request = let makeParameter :: (String, String) -> String makeParameter (k, v) = k ++ "=" ++ urlEncode v query' :: String query' = intercalate "&" $ map makeParameter query in request { -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. queryString = BS8.pack $ '?' : query' }
rrnewton/hgdata_trash
src/Network/Google.hs
mit
7,085
0
12
1,661
1,345
756
589
148
1
module TeX.Alias ( Alias(AliasIfTrue, AliasIfFalse) , AliasMap(), emptyAliasMap, aliasLens ) where import qualified Data.Map as M import TeX.StateUtils import TeX.Token data Alias = AliasIfTrue | AliasIfFalse deriving (Eq, Show) newtype AliasMap = AliasMap (M.Map Token Alias) deriving (Show) emptyAliasMap :: AliasMap emptyAliasMap = AliasMap M.empty aliasLens :: Functor f => Token -> (Maybe Alias -> f (Maybe Alias)) -> AliasMap -> f AliasMap aliasLens = makeMapLens (\(AliasMap x) -> x) AliasMap
xymostech/tex-parser
src/TeX/Alias.hs
mit
510
0
12
81
178
101
77
18
1
------------------------------------------------------------------------------ -- | Defines the 'Charset' accept header with an 'Accept' instance for use in -- encoding negotiation. module Network.HTTP.Media.Charset ( Charset ) where import Network.HTTP.Media.Charset.Internal
zmthy/http-media
src/Network/HTTP/Media/Charset.hs
mit
292
0
4
41
24
18
6
3
0
module Sprinkler where import Control.Monad (when) import Control.Monad.Bayes.Class hard :: MonadBayes m => m Bool hard = do rain <- bernoulli 0.3 sprinkler <- bernoulli $ if rain then 0.1 else 0.4 wet <- bernoulli $ case (rain,sprinkler) of (True,True) -> 0.98 (True,False) -> 0.8 (False,True) -> 0.9 (False,False) -> 0.0 condition (wet == False) return rain soft :: MonadBayes m => m Bool soft = do rain <- bernoulli 0.3 when rain (factor 0.2) sprinkler <- bernoulli $ if rain then 0.1 else 0.4 when sprinkler (factor 0.1) return rain
ocramz/monad-bayes
models/Sprinkler.hs
mit
699
0
12
253
241
123
118
20
5
module CLI ( Options(..) , Command(..) , SolveOptions(..) , GenerateOptions(..) , parseOpts ) where import Options.Applicative data Options = Options { cmd :: Command , useAscii :: Bool } data Command = Solve SolveOptions | Generate GenerateOptions data SolveOptions = SolveOptions { puzzleFile :: String , allSolutions :: Bool } data GenerateOptions = GenerateOptions { hideSolution :: Bool } parseOpts :: IO Options parseOpts = customExecParser (prefs showHelpOnError) optParser where optParser = info (helper <*> parseOptions) $ fullDesc <> progDesc "Solve and generate sudoku puzzles" parseOptions = Options <$> parseCommand <*> parseUseAscii parseCommand = subparser $ command "solve" (Solve <$> parseSolveOptionInfo) <> command "generate" (Generate <$> parseGenerateOptionInfo) parseUseAscii = flag False True $ long "ascii" <> help "Render the board in ascii instead of unicode" parseSolveOptionInfo = info (helper <*> parseSolveOptions) $ progDesc "Solve a sudoku puzzle in PUZZLE_FILE" parseSolveOptions = SolveOptions <$> parsePuzzleFile <*> parseAllSolutions parseGenerateOptionInfo = info (helper <*> parseGenerateOptions) $ progDesc "Generate a random sudoku puzzle" parseGenerateOptions = GenerateOptions <$> parseHideSolution parsePuzzleFile = argument str $ metavar "PUZZLE_FILE" parseAllSolutions = flag False True $ long "all" <> short 'a' <> help "Find all solutions instead of stopping at one" parseHideSolution = flag False True $ long "hideSolution" <> help "Only show the puzzle, not its solution"
patrickherrmann/sudoku
src/CLI.hs
mit
1,764
0
11
452
375
201
174
49
1
{-# LANGUAGE OverloadedStrings #-} module GhostLang.LinkerTests ( -- Pre link semantic tests. checkEmptyModule , checkOneNonMainModule , checkMainModuleWithoutPatterns , checkOtherModuleWithPatterns , checkDuplicateMainModules , checkSingleCorrectMainModule , checkTwoCorrectModules -- Proc map tests. , findUndefinedProc , findDefinedProc , findDoubleDefinedProc -- Procedure resolving tests. , resolveLocalProc , resolveImportedProc , resolveProcInProc , resolveInLoopProc , resolveInConcProc , resolveUnimportedProc , resolveAmbiguousProc , resolveConflictingArityProc ) where import Data.List (sortBy) import GhostLang.Compiler.Linker ( ProcDef , semanticChecks , resolve , buildProcMap , findProcDefs ) import GhostLang.Interpreter (IntrinsicSet) import GhostLang.Types ( ModuleSegment , Value (..) , GhostModule (..) , ImportDecl (..) , ModuleDecl (..) , Pattern (..) , Procedure (..) , Operation (..) ) import Test.HUnit import Text.Parsec.Pos (initialPos) -- | Test that the semantic checker is rejecting an empty -- module list. checkEmptyModule :: Assertion checkEmptyModule = do let mods = [] :: [GhostModule IntrinsicSet] case semanticChecks mods of Right _ -> assertBool "Shall not accept empty list" False Left _ -> return () -- | Test that the semanic checker is rejecting a single module which -- name not is main. checkOneNonMainModule :: Assertion checkOneNonMainModule = do let mods = [GhostModule (moduleDecl ["Other"]) [] [emptyPattern] []] case semanticChecks mods of Right _ -> assertBool "Shall not accept single non main module" False Left _ -> return () -- | Test that the semantic checker is rejecting a main module without -- any patterns. checkMainModuleWithoutPatterns :: Assertion checkMainModuleWithoutPatterns = do let mods = [GhostModule (moduleDecl ["Main"]) [] [] []] case semanticChecks mods of Right _ -> assertBool "Shall not accept main module without patterns" False Left _ -> return () -- | Test that the semantic checker is rejecting an other module -- having patterns. checkOtherModuleWithPatterns :: Assertion checkOtherModuleWithPatterns = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [emptyPattern] [] , GhostModule (moduleDecl ["Other"]) [] [emptyPattern] [] ] case semanticChecks mods of Right _ -> assertBool "Shall not accept other module with patterns" False Left _ -> return () -- | Test that the semantic checker is rejecting duplicate main modules. checkDuplicateMainModules :: Assertion checkDuplicateMainModules = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [emptyPattern] [] , GhostModule (moduleDecl ["Main"]) [] [emptyPattern] [] ] case semanticChecks mods of Right _ -> assertBool "Shall reject duplicate main modules" False Left _ -> return () -- | Test that the semantic checker is accepting a single main module -- with one pattern. checkSingleCorrectMainModule :: Assertion checkSingleCorrectMainModule = do let mods = [GhostModule (moduleDecl ["Main"]) [] [emptyPattern] []] case semanticChecks mods of Right mods' -> mods @=? mods' _ -> assertBool "Shall accept" False -- | Test that the semantic checker is accepting is accepting two -- modules, one main module with a pattern and one other module -- without patterns. checkTwoCorrectModules :: Assertion checkTwoCorrectModules = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [emptyPattern] [] , GhostModule (moduleDecl ["Other"]) [] [] [] ] case semanticChecks mods of Right mods' -> mods @=? mods' _ -> assertBool "Shall accept" False -- | Try to find an undefined procedure. findUndefinedProc :: Assertion findUndefinedProc = do let mods = [] :: [GhostModule IntrinsicSet] procMap = buildProcMap mods [] @=? findProcDefs "foo" procMap -- | Try to find a procedure defined once. findDefinedProc :: Assertion findDefinedProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [] [ emptyProcedure ] ] procMap = buildProcMap mods [("Main", emptyProcedure)] @=? findProcDefs "foo" procMap -- | Find a procedure name defined in two modules. findDoubleDefinedProc :: Assertion findDoubleDefinedProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [] [ emptyProcedure ] , GhostModule (moduleDecl ["Other"]) [] [] [ emptyProcedure ] ] procMap = buildProcMap mods lhs = sortBy procSort [ ("Main", emptyProcedure) , ("Other", emptyProcedure) ] rhs = sortBy procSort $ findProcDefs "foo" procMap lhs @=? rhs -- | Resolve a module with a reference to a local procedure. resolveLocalProc :: Assertion resolveLocalProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [] ] ] [ emptyProcedure ] ] -- The expected result with the unresolved reference resolved. res = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Call emptyProcedure [] ] ] [ emptyProcedure ] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Resolve a module with a reference to an imported procedure. resolveImportedProc :: Assertion resolveImportedProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [ ImportDecl ["Other", "Module"] ] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [] ] ] [] , GhostModule (moduleDecl ["Other", "Module"]) [] [] [ emptyProcedure ] ] -- The expected result. res = [ GhostModule (moduleDecl ["Main"]) [ ImportDecl ["Other", "Module"] ] [ Pattern (initialPos "") "bar" 1 [ Call emptyProcedure [] ] ] [] , GhostModule (moduleDecl ["Other", "Module"]) [] [] [ emptyProcedure ] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Resolve a procedure called from within a procedure. resolveProcInProc :: Assertion resolveProcInProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "caller" [] ] ] [ Procedure "caller" [] [ Unresolved (initialPos "") "foo" [] ] , emptyProcedure ] ] -- The resolved caller proc. caller = Procedure "caller" [] [ Call emptyProcedure [] ] -- The expected result. res = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Call caller [] ] ] [ caller, emptyProcedure ] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Resolve a module with a procedure reference inside a loop. resolveInLoopProc :: Assertion resolveInLoopProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Loop (Literal 1) [ Unresolved (initialPos "") "foo" [] ] ] ] [ emptyProcedure ] ] -- The expected result. res = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Loop (Literal 1) [ Call emptyProcedure [] ] ] ] [ emptyProcedure] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Resolve a module with a procedure reference inside a concurrent section. resolveInConcProc :: Assertion resolveInConcProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Concurrently [ Unresolved (initialPos "") "foo" [] ] ] ] [ emptyProcedure ] ] -- The expect result. res = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Concurrently [ Call emptyProcedure [] ] ] ] [ emptyProcedure] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Try to resolve a module with an unresolvable (unimported) -- procedure. resolveUnimportedProc :: Assertion resolveUnimportedProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [] ] ] [] , GhostModule (moduleDecl ["Other", "Module"]) [] [] [ emptyProcedure ] ] case resolve mods of Right _ -> assertBool "Shall not accept unresolvable proc" False Left _ -> return () -- | Try to resolve an ambiguous procedure. resolveAmbiguousProc :: Assertion resolveAmbiguousProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [ ImportDecl ["Other", "Module"] , ImportDecl ["Other", "Module2"] ] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [] ] ] [] , GhostModule (moduleDecl ["Other", "Module"]) [] [] [ emptyProcedure ] , GhostModule (moduleDecl ["Other", "Module2"]) [] [] [ emptyProcedure ] ] case resolve mods of Right _ -> assertBool "Shall not accept ambiguous definitions" False Left _ -> return () -- | Try to resolve a procedure with different arity at definition and -- use. resolveConflictingArityProc :: Assertion resolveConflictingArityProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [Literal 1] ] ] [emptyProcedure] ] case resolve mods of Right _ -> assertBool "Shall not accept conflicting arity" False Left _ -> return () moduleDecl :: [ModuleSegment] -> ModuleDecl moduleDecl = ModuleDecl (initialPos "") emptyPattern :: Pattern IntrinsicSet emptyPattern = Pattern (initialPos "") "" 0 [] emptyProcedure :: Procedure IntrinsicSet emptyProcedure = Procedure "foo" [] [] procSort :: ProcDef a -> ProcDef a -> Ordering procSort x y = fst x `compare` fst y
kosmoskatten/ghost-lang
ghost-lang/test/GhostLang/LinkerTests.hs
mit
12,556
0
19
4,859
2,789
1,450
1,339
228
2
{-# LANGUAGE ForeignFunctionInterface #-} -- | -- Module : Crypto.Hash.BLAKE -- Copyright : (c) Austin Seipp 2013 -- License : MIT -- -- Maintainer : aseipp@pobox.com -- Stability : experimental -- Portability : portable -- -- BLAKE-256 and BLAKE-512 hashes. The underlying implementation uses -- the @ref@ code of @blake256@ and @blake512@ from SUPERCOP, and -- should be relatively fast. -- -- For more information visit <https://131002.net/blake/>. -- module Crypto.Hash.BLAKE ( blake256 -- :: ByteString -> ByteString , blake512 -- :: ByteString -> ByteString ) where import Data.Word import Foreign.C.Types import Foreign.Ptr import System.IO.Unsafe (unsafePerformIO) import Data.ByteString (ByteString) import Data.ByteString.Internal (create) import Data.ByteString.Unsafe (unsafeUseAsCStringLen) -- | Compute a 256-bit (32 byte) digest of an input string. blake256 :: ByteString -> ByteString blake256 xs = -- SHA256 has 32 bytes of output unsafePerformIO . create 32 $ \out -> unsafeUseAsCStringLen xs $ \(cstr,clen) -> c_blake256 out cstr (fromIntegral clen) >> return () {-# INLINE blake256 #-} -- | Compute a 512-bit (64 byte) digest of an input string. blake512 :: ByteString -> ByteString blake512 xs = -- The default primitive of SHA512 has 64 bytes of output. unsafePerformIO . create 64 $ \out -> unsafeUseAsCStringLen xs $ \(cstr,clen) -> c_blake512 out cstr (fromIntegral clen) >> return () {-# INLINE blake512 #-} -- -- FFI hash binding -- foreign import ccall unsafe "blake256" c_blake256 ::Ptr Word8 -> Ptr CChar -> CULLong -> IO CInt foreign import ccall unsafe "blake512" c_blake512 ::Ptr Word8 -> Ptr CChar -> CULLong -> IO CInt
thoughtpolice/hs-blake
src/Crypto/Hash/BLAKE.hs
mit
1,817
0
12
411
317
182
135
27
1
module Main where main :: IO () main = do input <- getLine print input -- getWrappingPaperSurfaceArea :: type Len = Integer data Box = Box Len Len Len data Side = Side Len Len getSides :: Box -> [Side] getSides (Box l w h) = [ Side l w , Side w h , Side l h ] class Shape a where area :: (Num b) => a -> b instance Shape Box where area b = 2 * sum (area <$> getSides b) instance Shape Side where area (Side x y) = fromIntegral (x * y) instance Read Box where readPrec = readNumber convertInt readListPrec = readListPrecDefault readList = readListDefault
spicydonuts/adventofcode-2015
2/Main.hs
mit
634
0
10
192
237
123
114
22
1
module GameIO (strToPegs, printCols, printWrLength, printRating, printWin, getGuess) where import GameRules import Data.List (lookup, repeat) import Data.Maybe (fromJust) import Control.Monad (forM, replicateM_) import Text.Printf (printf) import qualified System.Console.ANSI as Con chars = [('1', Red), ('2', Green), ('3', Blue), ('4', Yellow), ('5', Purple), ('6', Orange), ('R', Red), ('G', Green), ('B', Blue), ('Y', Yellow), ('P', Purple), ('O', Orange), ('r', Red), ('g', Green), ('b', Blue), ('y', Yellow), ('p', Purple), ('o', Orange)] -- convert user-input to data we can work with -- charToPeg :: Char -> Maybe PegColor charToPeg c = lookup c chars strToPegs :: String -> PegCode strToPegs = foldr con [] where con c xs = case charToPeg c of Just x -> x:xs Nothing -> xs colors = [ (Red, "[ Red ]"), (Green, "[ Green ]"), (Blue, "[ Blue ]"), (Yellow, "[ Yellow ]"), (Purple, "[ Purple ]"), (Orange, "[ Orange ]")] showCol :: PegColor -> String showCol c = case lookup c colors of Just s -> s Nothing -> error "well..." -- pretty output -- conColors = [ (Red, (Con.Red, Con.Dull)), (Green, (Con.Green, Con.Dull)), (Blue, (Con.Blue, Con.Dull)), (Yellow, (Con.Yellow, Con.Dull)), (Purple, (Con.Magenta, Con.Dull)), (Orange, (Con.Red, Con.Vivid))] -- | sets Foreground to Intensity and Color setConCol int col = Con.setSGR $ (:[]) $ Con.SetColor Con.Foreground int col resetConCol = Con.setSGR $ (:[]) $ Con.Reset printCols :: PegCode -> IO () printCols code = do forM code (\c -> do let (col, int) = fromJust $ lookup c conColors setConCol int col putStr $ showCol c ) resetConCol printWrLength :: IO () printWrLength = do setConCol Con.Dull Con.Red putStrLn "The code you entered has the wrong length!" resetConCol printRating :: Int -> PegCode -> CompRes -> IO() printRating n guess (n1,n2) = do putStr ">> " printCols guess putStr " [" setConCol Con.Vivid Con.Green putStr $ take n1 $ repeat '+' resetConCol putStr $ take n2 $ repeat 'o' putStr $ take (n - n1 - n2) $ repeat ' ' putStrLn "]" printWin :: PegCode -> IO () printWin code = do putStrLn "" setConCol Con.Vivid Con.Green putStr "++ " printCols code setConCol Con.Vivid Con.Green putStrLn " ++++" resetConCol prettyCount :: Int -> String prettyCount n | n < length ns = ns !! n | otherwise = (show n) ++ "th" where ns = ["last", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth"] getGuess :: Int -> IO String getGuess n = do printf "\nThis is your %s try. Your guess please:\n" $ prettyCount n str <- getLine Con.cursorUpLine 2 Con.clearFromCursorToScreenEnd return str
michi7x7/mastermind
GameIO.hs
gpl-2.0
2,909
0
16
750
1,101
596
505
81
2
{-# LANGUAGE DeriveDataTypeable #-} module Prolog.Data where import qualified Autolib.Reader as R import qualified Autolib.ToDoc as T import Autolib.Util.Size import Data.Char import Data.Set (Set) import qualified Data.Set as S import Data.Typeable data Identifier = Identifier { name :: String } deriving ( Eq, Ord, Typeable ) instance T.ToDoc Identifier where toDoc ( Identifier i ) = T.text i instance R.Reader Identifier where reader = do i <- R.my_identifier return $ Identifier i data Term = Variable Identifier | Apply Identifier [ Term ] deriving ( Eq, Typeable ) instance Size Term where size t = case t of Apply f xs -> succ $ sum $ map size xs _ -> 1 type Position = [Int] leaf_positions :: Term -> [ Position ] leaf_positions t = case t of Apply f xs | not ( null xs ) -> do ( k, x ) <- zip [ 0.. ] xs p <- leaf_positions x return $ k : p _ -> [ [] ] positions :: Term -> [ Position ] positions t = [] : case t of Apply f xs -> do ( k, x ) <- zip [ 0.. ] xs p <- positions x return $ k : p _ -> [] subterms :: Term -> [Term] subterms t = do p <- positions t ; return $ peek t p function_symbols :: Term -> [ Identifier ] function_symbols t = do Apply f _ <- subterms t return f peek :: Term -> Position -> Term peek t [] = t peek (Apply f xs) (p:ps) = peek ( xs !! p) ps poke :: Term -> Position -> Term -> Term poke t [] s = s poke (Apply f xs) (p:ps) s = let ( pre, x: post) = splitAt p xs in Apply f $ pre ++ poke ( xs !! p ) ps s : post type Terms = [ Term ] variables :: Term -> Set Identifier variables t = case t of Variable v -> S.singleton v Apply f xs -> S.unions $ map variables xs varmap :: ( Identifier -> Identifier ) -> ( Term -> Term ) varmap sub t = case t of Variable v -> Variable $ sub v Apply f xs -> Apply f ( map ( varmap sub ) xs ) instance T.ToDoc Term where toDoc t = case t of Variable v -> T.toDoc v Apply f [] -> T.toDoc f Apply f xs -> T.toDoc f T.<+> T.parens ( T.fsep $ T.punctuate T.comma $ map T.toDoc xs ) instance R.Reader Term where reader = do f <- R.reader if isUpper $ head $ name f then return $ Variable f else do xs <- R.option [] $ R.my_parens $ R.my_commaSep $ R.reader return $ Apply f xs
Erdwolf/autotool-bonn
src/Prolog/Data.hs
gpl-2.0
2,456
0
16
774
1,050
528
522
77
2