lang
stringclasses
10 values
seed
stringlengths
5
2.12k
haskell
module Main where import qualified Advent.Day03 main :: IO () main = Advent.Day03.main
haskell
module Agda.TypeChecker ( checkDecls, checkDecl , inferExpr, checkExpr ) where import Agda.TypeChecking.Rules.Builtin as Rules import Agda.TypeChecking.Rules.Data as Rules import Agda.TypeChecking.Rules.Decl as Rules import Agda.TypeChecking.Rules.Def as Rules import Agda.TypeChecking.Rules.LHS as Rules import Agda.TypeChecking.Rules.Record as Rules import Agda.TypeChecking.Rules.Term as Rules
haskell
eRoundtripText <- lift $ runEncryptM encryptionSettings $ decryptText =<< encryptText originalText -- The result should be a 'Right' and match the 'originalText'
haskell
module SuccinctDeBruijn where import Types.AssemblyGraphs import Types.DNA assembledSequence = assemblyDeBruijn deBruijnGraph dnaSequences = map DNASequence ["ATGGCGTGCA"] deBruijnGraph = fromDNASequences 3 dnaSequences
haskell
where walk c t'@(TmVar _ x) | x == j + c = shift c s | otherwise = t' walk c (TmApp ifo t1 t2) = TmApp ifo (walk c t1) (walk c t2) walk c (TmAbs ifo x t1) = TmAbs ifo x (walk (c+1) t1) isValue :: Term -> Bool isValue (TmAbs _ _ _) = True isValue (TmVar _ _) = True isValue _ = False
haskell
discordOnEvent = flip runSqlPool pool . flip runReaderT cacheMVar . eventHandler actions prefix, discordOnStart = do -- Build list of cron jobs, saving them to the mvar. -- Note that we cannot just use @runSqlPool@ here - this creates -- a single transaction which is reverted in case of exception -- (which can just happen due to databases being unavailable -- sometimes). runReaderT (mapM (runCron pool) (compiledCronJobs actions) >>= liftIO . putMVar mvar) cacheMVar liftIO $ putStrLn "Tablebot lives!", -- Kill every cron job in the mvar. discordOnEnd = takeMVar mvar >>= killCron } TIO.putStrLn userFacingError
haskell
then (bor', a) else let i = abs ia - 1 geneValue = if testBit bor' i then SndValue else FstValue in (complementBit bor' i, toEnd n $ mapGene d geneValue a) where notFixed = testBit band ia = fromIntegral a i = abs ia - 1
haskell
mkShapeEnv :: ShapeType -> Either EvalErr (Env Expr) mkShapeEnv st = Map.foldlWithKey ( \menv x e -> menv >>= extend x e ) menv0
haskell
, vbfeBlocks :: (Vector (VBFSizeUnit, VBFBlock)) } -- ^ The entry file's data blocks. deriving (Eq, Show) -- | Request to insert a file into a VBF archive. data VBFEntryRequest = VBFEntryRequest { vbferLocalPath :: FilePath -- ^ Path to the file to add in the VBF archive. , vbferEntryPath :: FilePath } -- ^ Path of the file within the VBF archive. -- | Exceptions that might be thrown during VBF file handling.
haskell
See the file libraries/GLUT/LICENSE Support for reading a file of raw RGB data: 4 bytes big-endian width 4 bytes big-endian height width * height RGB byte triples -} module ReadImage ( readImage ) where import Data.Word ( Word8, Word32 )
haskell
TypeOperators, FlexibleInstances, DeriveFunctor, GeneralizedNewtypeDeriving, DeriveDataTypeable,
haskell
-- Portability: CPP, NoImplicitPrelude module Data.NumberLength.Internal where import Prelude (error) #if MIN_VERSION_base(4,7,0) import Data.Bits (FiniteBits(finiteBitSize)) #else import Data.Bits (Bits(bitSize)) #endif import Data.Function (($))
haskell
interpret f = f . runIdentityT -- | A free 'Pointed' instance Pointed f => Interpret Lift f where retract = elimLift point id interpret f x = elimLift point f x -- | A free 'Pointed' instance Pointed f => Interpret MaybeApply f where retract = either id point . runMaybeApply interpret f = either f point . runMaybeApply instance Interpret Backwards f where
haskell
import Language.C.Quote as QC -- friends import Language.C.Inline.Error -- |Annotating entities with hints. -- -- The alternatives are to provide an explicit marshalling hint with '(:>)', or to leave the marshalling -- implicitly defined by the name's type. -- data Annotated e where (:>) :: Hint hint => e -> hint -> Annotated e -- explicit marshalling hint Typed :: Name -> Annotated Name -- marshalling implicitly defined by name's type
haskell
import Templates.Footer embedInTemplate :: Bool -> [String] -> Html -> Html embedInTemplate isInteractive jsSources x = do docTypeHtml ! lang "en" $ do htmlHead isInteractive body $ do htmlHeader isInteractive x htmlFooter htmlScripts jsSources
haskell
guard = do _ <- P.string "Guard #" i <- int _ <- P.string " begins shift" return (GuardStart i) asleep x = P.string "falls asleep" >> return (FallAsleep x) wake x = P.string "wakes up" >> return (Wake x) solvePartA :: [Shift] -> Integer solvePartA shifts = sleepiestGuard * minute where bg = byGuard shifts
haskell
filter' :: (a -> Bool) -> [a] -> [a] filter' f lst = helper lst [] where helper [] aux = aux helper (x:xs) aux | f x = helper xs (x:aux) | otherwise = helper xs aux data InfNumber a = MinusInfinity | Number a
haskell
import Data.Era.AD import Data.Era.JpEra toJpEra :: AD -> Either String JpEra toJpEra (AD year) | year >= firstYear Heisei = makeJpEra Heisei $ year - firstYear Heisei + 1 | year >= firstYear Showa = makeJpEra Showa $ year - firstYear Showa + 1 | year >= firstYear Taisho = makeJpEra Taisho $ year - firstYear Taisho + 1 | year >= firstYear Meiji = makeJpEra Meiji $ year - firstYear Meiji + 1 fromJpEra :: JpEra -> AD fromJpEra (JpEra eraType year) = AD $ firstYear eraType + year - 1
haskell
= OutputPrefs { opUnmatchedAction :: UnmatchedAction , opOutputMode :: OutputMode } deriving Show -- | Determines what happens with unmatched input names. data UnmatchedAction = Display | DisplaySeperate | Hide deriving Show -- | Determines how a list of games is displayed.
haskell
-- | Stolen from rack-contrib: modifies the environment using the block given -- during initialization. module Hack2.Contrib.Middleware.Config (config) where import Hack2 config :: (Env -> Env) -> Middleware config alter app = \env -> app (alter env)
haskell
module Models.Vk.Wall where import Data.Aeson ( FromJSON (parseJSON), withObject ) -- TODO -- | Запись на стене data Wall = Wall {} deriving (Show) instance FromJSON Wall where parseJSON = withObject "Wall" $ \ _ -> return Wall
haskell
(p, moveEnd) <- runSFState posSFState pos -< i (bsEv, bsEnd) <- runSFState bSpawnSFState NoEvent -< (i, p) (_, dEv) <- runSFState destroySFState () -< (i, p) returnA -< (Output p bsEv, moveEnd `lMerge` dEv)) enemyMove posSFState = enemy posSFState (sfstate (const $ never &&& never)) (sfstate (const $ constant () &&& never)) draw :: Output -> Picture
haskell
module EKG.A276375 (a276375, a276375_list) where import EKG.A240024 (a240024) import HelperSequences.A002808 (a002808) a276375 :: Int -> Int a276375 n = a276375_list !! (n - 1) a276375_list :: [Int] a276375_list = filter (\i -> a240024 (i + 1) == a002808 i) [1..]
haskell
import OpalFalcon.Math.Matrix import OpalFalcon.Math.Transformations import OpalFalcon.Scene.Objects.PointLight import OpalFalcon.Scene.Objects.Disc import OpalFalcon.Scene.Objects.Plane import Data.Bits data DiscLight = MkDL Disc ColorRGBf Float -- Generates points on an (sxs) square centered at the origin; TODO: use RNG generateSquarePoints :: Double -> Integer -> [Vec2d] generateSquarePoints s c = let offset = s / (fromInteger c) c2 = shiftR c 2
haskell
let ms = readState fen in case ms of Right s -> map (\n -> (length (perft s n))) depths Left _ -> [] main :: IO () main = hspec $ do describe "perft" $ do it "handles chess960 position #11 from wiki" $ perftLengths "qnr1bkrb/pppp2pp/3np3/5p2/8/P2P2P1/NPP1PP1P/QN1RBKRB w GDg - 3 9" [1 .. 3] `shouldBe` [33, 823, 26895] it "handles chess960 position #33 from wiki" $
haskell
symmetric_positive sqrt x y csin x y = do write y (-1...1) lift1 sin x y periodic (2*pi) asin y x ccos x y = do
haskell
import Prelude import Data.List data Graph a = Graph [a] [(a, a)] deriving (Show, Eq) k4 = Graph ['a', 'b', 'c', 'd'] [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('a', 'c'), ('b', 'd')]
haskell
-- disallow circular references checkCyclic waif value let var = waifData waif :: PVar PropertyMap vspace = pvar_space var :: VSpace liftVTx $ modifyPVar var $ VHashMap . HM.insert name (vref vspace value) . unVHashMap return value checkCyclic :: WAIF -> Value -> MOO () checkCyclic waif = checkCyclic'
haskell
module Its.Timmys.Fault.Again where -- https://www.codewars.com/kata/55c28f7304e3eaebef0000da/train/haskell createList :: Int -> [Int] createList n = [1 .. n]
haskell
, decode , eitherDecode , encode ) where import Control.Monad ((>=>)) import qualified Data.Attoparsec.ByteString.Lazy as AP (eitherResult, parse) import qualified Data.BEncode.Builder as BEBuilder (value) import qualified Data.BEncode.Parser as BEParser (value) import Data.BEncode.Types import Data.ByteString.Builder (toLazyByteString)
haskell
putInt :: Putter Int putInt = putLazyByteString . toHex . (endFunc getSystemEndianness byteSwap32) . fromIntegral putMaybe :: Maybe a -> Putter a -> Put putMaybe mi = case mi of Just i -> ($ i) Nothing -> (\x -> return ()) -- -- getters -- getGeometry :: Get Geometry
haskell
import Control.Exception (evaluate) import qualified ScannerSpec import qualified ParserSpec import qualified InterpreterSpec main :: IO () main = hspec spec spec :: Spec spec = do describe "Basic Scanner Test" ScannerSpec.spec
haskell
) where import Control.Monad.Logger (logError, logInfo) import Control.Monad.Reader (asks) import LBKiirotori.AccessToken (getAccessToken) import LBKiirotori.API.ReplyMessage
haskell
-- is not present lookupUnsafe :: Show a => M.IntMap a -> String -> Int -> a lookupUnsafe m s u = case M.lookup u m of Just p -> p
haskell
walk :: Float -> Organism -> Organism walk dt u@(Uni p) = u {particleInfo = move dt p} walk dt (Multi p a os) = Multi p' a' os' where p' = move dt p
haskell
new_var, num) where import qualified Data.Map.Strict as M data Symtab a = Symtab { symbols :: M.Map a Int, next_id :: Int }
haskell
-- | Attribute key-value pairs can be declared in diagrams, nodes, boundaries -- | and flows. type Attributes = M.Map String Value -- | The top level diagram. data Diagram = Diagram Attributes [RootNode] [Flow] deriving (Eq, Show)
haskell
RoundedSpecialConstEffort MPFR where type SpecialConstEffortIndicator MPFR = MPFRPrec specialConstDefaultEffort sample = getPrecision sample instance RoundedSpecialConst MPFR where piUpEff prec _ = withPrec prec pi piDnEff prec _ = negate $ withPrecRoundDown prec (- pi) eUpEff prec _ = withPrec prec (exp 1)
haskell
main :: IO () main = do putStrLn "RVM code:" ; putStrLn ");'u?>vD?>vRD?>vRA?>vRA?>vR:?>vR=!(:lkm!':lkv6y" ; -- RVM code that prints HELLO! return ()
haskell
interpretM :: ParserM a -> A.Parser a interpretM = interpretWithMonad interpretP data Tree f a = Node a | Tree (f (Tree f a)) deriving (Foldable, Functor) -- | Pass values with all possible outermost constructors to 'parseJSON', -- and collect the results. -- fillOut :: FromJSON a => a -> Tree [] (ParserM a) fillOut _ = Tree [ Node $ parseJSON (Array u) , Node $ parseJSON (Object u)
haskell
main :: IO () main = do [n,m] <- map read . words <$> getLine :: IO [Int] print $ f n * f m where f x = if x < 2 then x else x - 2
haskell
validate 4012888888881882 `shouldBe` False describe "hanoi" $ do it "should return an empty list for zero discs" $ do hanoi 0 "a" "b" "c" `shouldBe` [] it "should solve for 1 disc" $ do hanoi 1 "a" "b" "c" `shouldBe` [("a", "b")] it "should solve for 2 discs" $ do
haskell
-- not True = False -- not False = True ----------- Natural numbers -- data Nat = Z | S Nat -- (==) :: Integer -> Integer -> Bool -- (==) a b = case (a, b) of -- (Z, Z) -> True -- (Z, _) -> False -- (_, Z) -> False
haskell
hSpwnProcess' (List (Atom func : args)) hn | Just fn <- lookup func shellOps = fn args hn hSpwnProcess' (List (Atom func : args)) hn | otherwise = spwnProcess (proc func (toString args)) $ UseHandle hn where toString = map showVal hSpwnProcess' (Atom cmd) hn = spwnProcess (proc cmd []) $ UseHandle hn hSpwnProcess' (String cmd) hn = spwnProcess (shell cmd) $ UseHandle hn spwnProcess :: CreateProcess -> StdStream -> IO Handle spwnProcess process inStream = do --(_, Just phout, _, pHandle) <- createProcess (proc cmd (map showVal args))
haskell
, _svcEndpoint = defaultEndpoint esService <&> endpointHost .~ error "ElasticSearch Service endpoint is not configured. example: 'let env2 = configure (setEndpoint True <hostname> 443 esService) env'" , _svcTimeout = _svcTimeout elasticSearch , _svcCheck = _svcCheck elasticSearch , _svcError = _svcError elasticSearch , _svcRetry = _svcRetry elasticSearch
haskell
-- -- Copyright (c) [1995..2000] <NAME> -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Library General Public -- License as published by the Free Software Foundation; either -- version 2 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Library General Public License for more details. -- --- DESCRIPTION ---------------------------------------------------------------
haskell
instance Alpha Expr instance Subst Expr Type instance Subst Expr ArithOp instance Subst Expr LogicalOp
haskell
case desc ^. GameUI.customEventHandler of Just f -> (liftIO . toIO $ packAnyHasIOUIToUIState <$> f event state) >>= continue Nothing -> continue $ packUIState state ui dispatchVtyEventGameUI :: (ToIO m, HasUI m s e) => s -> UI m s e ->
haskell
-- start: f--f--f- -- rewrite: f → f+f--f+f snowflake :: Int -> Command snowflake x = f(x) :#: angle :#: angle :#: f(x) :#: angle :#: angle :#: f(x) :#: angle :#: angle where f 0 = GrabPen white :#: Go 10 f x = f(x-1) :#: angle' :#: f(x-1) :#: angle :#: angle :#: f(x-1) :#: angle' :#: f(x-1) angle = Turn (-60) angle' = Turn (60) -- -- Peano-Gosper: -- angle: 60 -- start: f -- rewrite: f → f+g++g-f--ff-g+ g → -f+gg++g+f--f-g
haskell
truncate' :: Double -> Int -> Double truncate' x n = (fromIntegral (round (x * t))) / t where t = 10^n spec:: Spec spec = do describe "Testing Geo.Base" $ do it "Basic zero Point" $
haskell
Prelude.False -> Prelude.False} type EqDec a = a -> a -> Prelude.Bool -- singleton inductive, whose constructor was Build_eqDec eqDecide :: (EqDec a1) -> a1 -> a1 -> Prelude.Bool eqDecide eqDec = eqDec eqDecProd :: (EqDec a1) -> (EqDec a2) -> EqDec ((,) a1 a2) eqDecProd h h0 a a' = case a of { (,) a0 b ->
haskell
( -- * Reexports -- ** "Data.Function" reexports (.) , ($) , (&) , id , const , flip , fix
haskell
import AOC.Types day24 :: Solution [Int] Int Int day24 = Solution { parse = const Nothing
haskell
module Tinc.GhcInfo where import System.Process import Tinc.GhcPkg import Tinc.Types import Tinc.Fail data GhcInfo = GhcInfo { ghcInfoPlatform :: String , ghcInfoVersion :: String , ghcInfoGlobalPackageDb :: Path PackageDb } deriving (Eq, Show)
haskell
import Graphics.Gloss.Internals.Interface.Backend import Graphics.Gloss.Internals.Interface.Window import Graphics.Gloss.Internals.Interface.ViewState.Reshape import qualified Graphics.Gloss.Internals.Interface.Callback as Callback import Data.IORef import System.Mem interactWithBackend :: Backend a => a -- ^ Initial state of the backend. -> Display -- ^ Display config. -> Color -- ^ Background color. -> world -- ^ The initial world. -> (world -> IO Picture) -- ^ A function to produce the current picture.
haskell
sAtom :: Atom -> T.Text sAtom (Str t) = t sAtom (Atom t) = t myParser :: SExprParser Atom (SExpr Atom) myParser = mkParser pAtom
haskell
instance ToJSON LambdaFunctionTracingConfig where toJSON LambdaFunctionTracingConfig{..} = object $ catMaybes [ fmap (("Mode",) . toJSON) _lambdaFunctionTracingConfigMode ] instance FromJSON LambdaFunctionTracingConfig where parseJSON (Object obj) = LambdaFunctionTracingConfig <$>
haskell
addtbnds <- solveSubproblem prob rest_rhs (con rule) res <- case (trace ("subproblem complexity " ++ show addtbnds) addtbnds) of Just (add_bound, reach_rls) -> --FIXME pass invariant of SCC instead of true constraint case findInitCond [] (con rule) of Nothing -> return Nothing Just (x, c) -> let rexprs = map (\t -> map (arithSimp . poly2arith) (args t)) rec_calls lexprs = map (arithSimp . poly2arith) largs arg_pairs = zip lexprs rexprs in
haskell
shouldNotDecode :: forall a . (Eq a, Show a, Yaml.FromJSON a) => ByteString -> Expectation shouldNotDecode bStr = Yaml.decode bStr `shouldBe` (Nothing :: Maybe a) shouldGenerate :: forall a . (Eq a, Show a, Yaml.ToJSON a) => a -> ByteString -> Expectation
haskell
import Shared.Api.Handler.Common import Wizard.Api.Handler.Common import Wizard.Api.Resource.Plan.AppPlanJM () import Wizard.Model.Context.BaseContext import Wizard.Model.Plan.AppPlan
haskell
module Basketball (basketball, try) where {- Basketball (difficulty 2.7) - https://open.kattis.com/problems/competitivearcadebasketball An easy one we're doing just to put a Haskell solution on the leaderboard and see where it ranks in terms of running time compared to other languages. Result: It ranks horribly, at 1.3s
haskell
it "should do sample 4" $ do let input = "hgt:59cm ecl:zzz\neyr:2038 hcl:74454a iyr:2023\npid:3556412378 byr:2007" let expected = 0 day4b input `shouldBe` expected it "should do sample 5" $ do let input = "pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980\nhcl:#623a2f" let expected = 1 day4b input `shouldBe` expected it "should do sample 6" $ do let input = "eyr:2029 ecl:blu cid:129 byr:1989\niyr:2014 pid:896056539 hcl:#a97842 hgt:165cm" let expected = 1 day4b input `shouldBe` expected it "should do sample 7" $ do let input = "hcl:#888785\nhgt:164cm byr:2001 iyr:2015 cid:88\npid:545766238 ecl:hzl\neyr:2022"
haskell
module Enigma.Rotor ( Rotor , rotorPosAsChar , inwardOutput , outwardOutput , onNotch , step , buildRotor , buildGreekRotor
haskell
import qualified Data.Map as Map import Data.ByteString.Lazy.UTF8 import Data.Aeson import qualified Data.Text as Text -- | Formats a solution as an encoded Json string. solutionToJson :: Solution -> String solutionToJson (Solution list) = (\xs -> toString $ encodePretty $ Map.fromList xs) (map (\(x,y) -> (x, show y)) list)
haskell
where positions = M.fromList $ zip xs [1 .. length xs] next :: Game -> Game next (num, cur, positions) = case M.lookup num positions of Nothing -> (0, cur + 1, M.insert num cur positions) Just old -> (cur - old, cur + 1, M.insert num cur positions) part1 :: [Int] -> Int -> Int part1 xs stop = fst3 $ go (initialize xs) where go :: Game -> Game go game =
haskell
import Data.YAML as Yaml (prettyPosWithSource) import qualified Data.YAML.Aeson as Yaml import Fregot.Builtins.Internal import qualified Fregot.Eval.Json as Json import Fregot.Names import Fregot.Types.Builtins ((🡒)) import qualified Fregot.Types.Builtins as Ty
haskell
-- capitilization of the needles. The caller should be certain that if IgnoreCase -- is passed, the needles are already lower case. setSearcherCaseSensitivity :: CaseSensitivity -> Searcher v -> Searcher v setSearcherCaseSensitivity case_ searcher = searcher{ searcherCaseSensitive = case_ } -- | Return whether the haystack contains any of the needles. -- Case sensitivity depends on the properties of the searcher
haskell
logStr :: Event t Text -> m () -- | Access current time of server getTime :: m UTCTime -- | Get event that fires every n seconds. -- -- Note: the event will tick even there are no subscriders to it. Use -- 'tickEveryUntil' if you want to free underlying thread. tickEvery :: NominalDiffTime -> m (Event t ()) -- | Generate an event after given time once
haskell
newtype Unique = Unique Int deriving (Eq, Show) uniqueSupply :: [Unique] uniqueSupply = map Unique [0..] data Type = Int | String | Record [(Symbol, Type)] Unique | Array Type Unique | Nil | Unit | Name Symbol (Maybe Type) -- this is a ref in the book deriving (Show, Eq)
haskell
import qualified Snap.Chat.Internal.API.Tests import qualified Snap.Chat.Types.Tests main :: IO () main = defaultMain tests where tests = [ testGroup "Snap.Chat.ChatRoom.Tests" Snap.Chat.ChatRoom.Tests.tests , testGroup "Snap.Chat.Internal.API.Tests" Snap.Chat.Internal.API.Tests.tests , testGroup "Snap.Chat.Types.Tests" Snap.Chat.Types.Tests.tests
haskell
import Data.Typeable import Diagrams.Prelude import Diagrams.Backend.SVG import Diagrams.Backend.PGF import Diagrams.TwoD.Size
haskell
getSetCode Set1 = 1 getSetCode Set2 = 2 getSetCode Set3 = 3 data Card = Card { set :: Set, faction :: Faction, code :: Int, count :: Int } deriving (Eq, Ord, Show)
haskell
class Generic (a :: Type) where type Rep a :: Univ from :: a -> In (Rep a) to :: In (Rep a) -> a
haskell
MySQL.Year -> pure $ possiblyNullable scalarType $ MySQL.YearValue <$> P.string MySQL.Bit -> pure $ possiblyNullable scalarType $ MySQL.BitValue <$> P.boolean MySQL.String -> pure $ possiblyNullable scalarType $ MySQL.VarcharValue <$> P.string MySQL.VarChar -> pure $ possiblyNullable scalarType $ MySQL.VarcharValue <$> P.string MySQL.DateTime -> pure $ possiblyNullable scalarType $ MySQL.DatetimeValue <$> P.string MySQL.Blob -> pure $ possiblyNullable scalarType $ MySQL.BlobValue <$> bsParser MySQL.Timestamp -> pure $ possiblyNullable scalarType $ MySQL.TimestampValue <$> P.string
haskell
| m == 0 = convert6 n | k == 0 = convert3 m ++ " million" | otherwise = convert3 m ++ " million" ++ link k ++ convert6 k where (m, k) = (n `div` 1000000, n `mod` 1000000) -- Billions - 000,000,000,000's convert12 :: Int -> String
haskell
spec :: Spec spec = do describe "RenderNotation" $ do describe "validRenderNotes" $ do it "Should only contain lowercase characters (except for last character)" $ and [ (==) (last validRenderNotes) '.', (all isLower $ init validRenderNotes) ] `shouldBe` True
haskell
main :: IO () main = do (path:mimeType:_) <- getArgs run 3000 (app path $ encodeUtf8 mimeType) app :: Text -> ByteString -> Application app path mimeType _req sendResponse = do appianReq <- return . eitherDecode . fromStrict =<< requestBody _req :: IO (Either String AppianPage) putStrLn $ "The request is: " <> tshow appianReq print $ requestMethod _req ctnt <- readFile $ unpack path sendResponse $ responseLBS
haskell
module DeferredFolds.Unfoldl ( module Exports, ) where import DeferredFolds.Types as Exports (Unfoldl(..)) import DeferredFolds.Defs.Unfoldl as Exports
haskell
collatz :: Integer -> Maybe Integer collatz x | x <= 0 = Nothing collatz x = Just $ collatz' x 0 collatz' :: Integer -> Integer -> Integer collatz' 1 r = r
haskell
usingReaderT conn $ Database.attributesForInsert (password registrant) (email registrant) (username registrant) "" Nothing user <- withExceptT (internalServerError . show) $
haskell
ts <- gets threads pubs <- liftIO $ atomically $ readTVar $ publications n let mbpub = M.lookup name' pubs mb <- liftIO $ runReaderT (mkPub' mbpub bufferSize) (r,ts) case mb of Nothing -> return () Just pub' -> do liftIO $ atomically $ modifyTVar (publications n) $ M.insert name' pub' --put n { publications = M.insert name' pub' pubs } RN.registerPublicationNode name' pub' -- |Advertise a 'Topic' publishing a stream of 'IO' values with a -- per-client transmit buffer of the specified size. advertiseBuffered_ :: (RosBinary a, MsgInfo a, Typeable a) =>
haskell
import qualified Data.ByteString.Char8 as C import Network.Run.TCP (runTCPClient) import Network.Socket.ByteString (recv, sendAll) main :: IO () main = runTCPClient "127.0.0.1" "3000" $ \s -> do sendAll s "Hello, world!" msg <- recv s 1024 putStr "Received: " C.putStrLn msg
haskell
import Database.HDBC (disconnect, runRaw) import Spec import SpecHelper (loadFixture, openConnection) import Test.Hspec main :: IO () main = do c <- openConnection runRaw c "drop schema if exists public cascade" runRaw c "drop schema if exists dbapi cascade" loadFixture "schema" c loadFixture "role" c disconnect c
haskell
, docConfig = defaultConfig } type Encoder a = State EncoderState a type BlockEncoder = Block -> (Encoder Doc) type EncoderForDoc a = a -> (Encoder Doc) blockEncoder :: BlockEncoder blockEncoder = selectEncoder genericBlockEncoder [ context === constS "section" --> sectionEncoder , emptyContentS --> macroEncoder
haskell
spec = do it "emtpy equals empty" $ do sublist "" "" `shouldBe` Equal it "empty is sublist of anything" $ do sublist "" "anyhting" `shouldBe` Sublist
haskell
type instance Core.EraRule "TICKN" (SophieMAEra _ma _c) = Sophie.TICKN type instance Core.EraRule "UPEC" (SophieMAEra ma c) = Sophie.UPEC (SophieMAEra ma c) -- These rules are defined anew in the SophieMA era(s)
haskell
forceLocation (EditBuffer topLine (x, lineNumber) contents) moveToLineStart :: EditBuffer -> EditBuffer moveToLineStart (EditBuffer topLine (_,y) contents) = EditBuffer topLine (0,y) contents moveToLineEnd :: EditBuffer -> EditBuffer moveToLineEnd buffer@(EditBuffer topLine (_,y) contents) =
haskell
runDDB s f = runReaderT (unDDB f) s ------------------------------------------------------------------------------- tbl :: CreateTable tbl = CreateTable "timeseries" [ AttributeDefinition "_k" AttrBinary
haskell
(Color 255 255 255 255) ,DynData (x0 + 0.25,y0 - 2) (0.25,0.25) 108 (11,11) (Color 255 255 255 255) ,DynData (x0 - 0.25,y0 - 2.5) (0.25,0.25) 108 (10,12) (Color 255 255 255 255) ,DynData (x0 + 0.25,y0 - 2.5) (0.25,0.25) 108 (11,12) (Color 255 255 255 255)] -- 0 values are a basic cast (x0,y0) = (realToFrac x, realToFrac y) -- prime values locate the outer box (x',y') = (2*x0 - w',-2*y0 - h') (w',h') = (0.5*realToFrac w, 0.5*realToFrac h) -- double prime is the location of the inner box (x'',y'') = (x' + 1.0, y' + 3.0)
haskell
forAll2 neighDu5d "This one will fail with small number of notes: use tonalTranspCan (next test) instead. tonal transposition - neighbour notes in D up a fifth and neighbouring down" $ \x y -> do (x <=> y) (tonalTranspOf ~~ 1) forAll2 neighDu5d "tonal transposition more candidates - neighbour notes in D up a fifth and neighbouring down" $ \x y -> do (x <=> y) (tonalTranspOfCan ~~ 1) forAll2 neighAd5d "tonal transposition - neighbour notes in A down a fifth and neighbouring down" $ \x y -> do
haskell
imageSize = fromIntegral $ w * h * 3 } let p' = pixelBytes (toList p) w handle <- openFile filename WriteMode writeHeader handle header B.hPut handle p' hClose handle writeHeader :: Handle -> BMPHeader -> IO () writeHeader handle header = do B.hPut handle . signature $ header
haskell
module Kantour.Core.GameResource.MagicSpec where import Test.Hspec import Kantour.Core.GameResource.Magic spec :: Spec spec = describe "magicCode" $ specify "examples" $ do magicCode 184 "ship_banner" `shouldBe` 4357 magicCode 184 "ship_card" `shouldBe` 5681 magicCode 185 "ship_banner" `shouldBe` 5755 magicCode 185 "ship_card" `shouldBe` 2050
haskell
import qualified SendMail.Types as MailTypes import Data.ByteString import SendMail.Internal.SendMailInternal import Network.HTTP.Client.Conduit getEmailSenderFromFile :: Show env => env -> Manager -> FilePath -> IO (Maybe MailTypes.EmailSender) getEmailSenderFromFile = privateImplGetBackend getEmailSenderFromContent :: Show env => env -> Manager -> ByteString -> IO (Maybe MailTypes.EmailSender) getEmailSenderFromContent = privateImplGetBackendFromContent sendMail :: MailTypes.EmailSender -> MailTypes.Email -> IO (Either MailTypes.ErrorMessage MailTypes.OkMessage) sendMail (MailTypes.EmailSender sender) email = sender email
haskell
generalizeExpr (InfixAppExpr ident e1 e2 meta) = InfixAppExpr_ ident (generalizeExpr e1) (generalizeExpr e2) meta
haskell
[C.exp| TypeInfo* {new TypeInfo($(const char* s'), $(TypeInfo* ptr))} |] deleteTypeInfo :: Ptr TypeInfo -> IO () deleteTypeInfo ptr = [C.exp| void {delete $(TypeInfo* ptr)} |] instance Creatable (Ptr TypeInfo) where type CreationOptions (Ptr TypeInfo) = (String, Ptr TypeInfo) newObject = uncurry newTypeInfo deleteObject = liftIO . deleteTypeInfo class IsTypeOf a where -- | Check current type is type of specified type. typeInfoIsTypeOf :: (Parent TypeInfo t, Pointer p t, MonadIO m)
haskell
modules :: [String] modules = [ "-XOverloadedStrings" , "-XCPP" , "-XLambdaCase" , "-XPatternSynonyms" , "-i","-i.","-iinternal" , "-threaded" , "-package=dns"
haskell
import Advent (getIntcodeInput) import Intcode main :: IO () main = do pgm <- new <$> getIntcodeInput 2 print (startup 12 2 pgm) print (head [ 100 * noun + verb
haskell
onEvent st (VtyEvent (EvKey KEsc [])) = do halt $ st { appCancelled = True } onEvent st (VtyEvent (EvKey KEnter [])) = halt st onEvent st (VtyEvent e) = do list' <- handleListEvent e (appList st) continue $ st { appList = list' }
haskell
quicksort [] = [] quicksort (x:xs) = let left = quicksort [y | y <- xs, y <= x] right = quicksort [y | y <- xs, y > x] in left ++ [x] ++ right
haskell
data Expr = Lit Integer | Add Expr Expr | Mul Expr Expr deriving (Eq, Show) eval :: Expr -> Integer eval (Lit a) = a eval (Add x y) = eval x + eval y