Search is not available for this dataset
repo_name
string
path
string
license
string
full_code
string
full_size
int64
uncommented_code
string
uncommented_size
int64
function_only_code
string
function_only_size
int64
is_commented
bool
is_signatured
bool
n_ast_errors
int64
ast_max_depth
int64
n_whitespaces
int64
n_ast_nodes
int64
n_ast_terminals
int64
n_ast_nonterminals
int64
loc
int64
cycloplexity
int64
fmapfmapfmap/amazonka
amazonka-ml/gen/Network/AWS/MachineLearning/CreateDataSourceFromS.hs
mpl-2.0
-- | The response status code. cdsfsrsResponseStatus :: Lens' CreateDataSourceFromSResponse Int cdsfsrsResponseStatus = lens _cdsfsrsResponseStatus (\ s a -> s{_cdsfsrsResponseStatus = a})
188
cdsfsrsResponseStatus :: Lens' CreateDataSourceFromSResponse Int cdsfsrsResponseStatus = lens _cdsfsrsResponseStatus (\ s a -> s{_cdsfsrsResponseStatus = a})
157
cdsfsrsResponseStatus = lens _cdsfsrsResponseStatus (\ s a -> s{_cdsfsrsResponseStatus = a})
92
true
true
0
9
21
40
22
18
null
null
pfq/PFQ
user/pfq-lang/src/Lang/Parser.hs
gpl-2.0
mkMainFunction :: String -> String mkMainFunction code = "(let " ++ code ++ " in main)"
87
mkMainFunction :: String -> String mkMainFunction code = "(let " ++ code ++ " in main)"
87
mkMainFunction code = "(let " ++ code ++ " in main)"
52
false
true
0
6
15
30
14
16
null
null
argiopetech/help
Help/Settings.hs
bsd-3-clause
logParser ∷ Getter Settings (Maybe (Parser Document)) logParser = to _logParser
79
logParser ∷ Getter Settings (Maybe (Parser Document)) logParser = to _logParser
79
logParser = to _logParser
25
false
true
1
9
10
36
15
21
null
null
Cedev/MemoTrie
src/Data/MemoTrie.hs
bsd-3-clause
as `weave` [] = as
18
as `weave` [] = as
18
as `weave` [] = as
18
false
false
0
6
4
16
8
8
null
null
CIFASIS/wavy
Sound/Wav/Binary.hs
bsd-3-clause
getInt16le :: Get Int16 getInt16le = fmap fromIntegral getWord16le
66
getInt16le :: Get Int16 getInt16le = fmap fromIntegral getWord16le
66
getInt16le = fmap fromIntegral getWord16le
42
false
true
0
5
8
19
9
10
null
null
bkoropoff/Idris-dev
src/Idris/Core/Elaborate.hs
bsd-3-clause
getLog :: Elab' aux String getLog = do ES p logs _ <- get return $! logs -- The primitives, from ProofState
120
getLog :: Elab' aux String getLog = do ES p logs _ <- get return $! logs -- The primitives, from ProofState
120
getLog = do ES p logs _ <- get return $! logs -- The primitives, from ProofState
93
false
true
0
8
34
44
19
25
null
null
naoto-ogawa/h-xproto-mysql
src/DataBase/MySQLX/Model.hs
mit
mkSessionVariableChanged :: PSVC.SessionVariableChanged mkSessionVariableChanged = PB.defaultValue
137
mkSessionVariableChanged :: PSVC.SessionVariableChanged mkSessionVariableChanged = PB.defaultValue
124
mkSessionVariableChanged = PB.defaultValue
55
false
true
0
5
44
15
8
7
null
null
HaskellCNOrg/snaplet-i18n
src/Snap/Snaplet/I18N.hs
bsd-3-clause
i18nSpanSplice :: HasI18N b => I.Splice (Handler b b) i18nSpanSplice = do input <- getParamNode v <- lift . lookupI18NValue $ getNameAttr input return [X.Element "span" (elementAttrs input) [X.TextNode v]] -- | Look up 'name' attribute value. --
258
i18nSpanSplice :: HasI18N b => I.Splice (Handler b b) i18nSpanSplice = do input <- getParamNode v <- lift . lookupI18NValue $ getNameAttr input return [X.Element "span" (elementAttrs input) [X.TextNode v]] -- | Look up 'name' attribute value. --
258
i18nSpanSplice = do input <- getParamNode v <- lift . lookupI18NValue $ getNameAttr input return [X.Element "span" (elementAttrs input) [X.TextNode v]] -- | Look up 'name' attribute value. --
204
false
true
0
12
50
90
43
47
null
null
spechub/Hets
Isabelle/IsaConsts.hs
gpl-2.0
funT :: Continuity -> Typ -> Typ -> Typ funT c a b = case c of IsCont _ -> mkContFun a b NotCont -> mkFunType a b
119
funT :: Continuity -> Typ -> Typ -> Typ funT c a b = case c of IsCont _ -> mkContFun a b NotCont -> mkFunType a b
119
funT c a b = case c of IsCont _ -> mkContFun a b NotCont -> mkFunType a b
79
false
true
0
8
33
59
28
31
null
null
hargettp/courier
src/Network/Transport.hs
mit
{-| A helper for ensuring there are 'Binding's of a specific 'Endpoint' to specific 'Name's on the provided 'Transport' during a function. -} withBinding4 :: Transport -> (Endpoint,Name) -> (Endpoint,Name) -> (Endpoint,Name) -> (Endpoint,Name) -> IO a -> IO a withBinding4 transport (endpoint1,name1) (endpoint2,name2) (endpoint3,name3) (endpoint4,name4) fn = withBinding transport endpoint1 name1 $ withBinding transport endpoint2 name2 $ withBinding transport endpoint3 name3 $ withBinding transport endpoint4 name4 fn
540
withBinding4 :: Transport -> (Endpoint,Name) -> (Endpoint,Name) -> (Endpoint,Name) -> (Endpoint,Name) -> IO a -> IO a withBinding4 transport (endpoint1,name1) (endpoint2,name2) (endpoint3,name3) (endpoint4,name4) fn = withBinding transport endpoint1 name1 $ withBinding transport endpoint2 name2 $ withBinding transport endpoint3 name3 $ withBinding transport endpoint4 name4 fn
398
withBinding4 transport (endpoint1,name1) (endpoint2,name2) (endpoint3,name3) (endpoint4,name4) fn = withBinding transport endpoint1 name1 $ withBinding transport endpoint2 name2 $ withBinding transport endpoint3 name3 $ withBinding transport endpoint4 name4 fn
280
true
true
0
13
87
156
79
77
null
null
hjwylde/werewolf
app/Werewolf/Command/Unvote.hs
bsd-3-clause
handle :: (MonadIO m, MonadRandom m) => Text -> Text -> m () handle callerName tag = do unlessM (doesGameExist tag) $ exitWith failure { messages = [noGameRunningMessage callerName] } game <- readGame tag command <- case game ^. stage of VillagesTurn -> return $ Villager.unvoteCommand callerName WerewolvesTurn -> return $ Werewolf.unvoteCommand callerName _ -> exitWith failure { messages = [playerCannotDoThatRightNowMessage callerName] } result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game case result of Left errorMessages -> exitWith failure { messages = errorMessages } Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
868
handle :: (MonadIO m, MonadRandom m) => Text -> Text -> m () handle callerName tag = do unlessM (doesGameExist tag) $ exitWith failure { messages = [noGameRunningMessage callerName] } game <- readGame tag command <- case game ^. stage of VillagesTurn -> return $ Villager.unvoteCommand callerName WerewolvesTurn -> return $ Werewolf.unvoteCommand callerName _ -> exitWith failure { messages = [playerCannotDoThatRightNowMessage callerName] } result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game case result of Left errorMessages -> exitWith failure { messages = errorMessages } Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
868
handle callerName tag = do unlessM (doesGameExist tag) $ exitWith failure { messages = [noGameRunningMessage callerName] } game <- readGame tag command <- case game ^. stage of VillagesTurn -> return $ Villager.unvoteCommand callerName WerewolvesTurn -> return $ Werewolf.unvoteCommand callerName _ -> exitWith failure { messages = [playerCannotDoThatRightNowMessage callerName] } result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game case result of Left errorMessages -> exitWith failure { messages = errorMessages } Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
807
false
true
0
16
250
256
123
133
null
null
mumuki/mulang
src/Language/Mulang/Transform/Normalizer.hs
gpl-3.0
normalizeArrows :: Expression -> Expression normalizeArrows (Sequence es) = Sequence . map normalizeArrows $ es
111
normalizeArrows :: Expression -> Expression normalizeArrows (Sequence es) = Sequence . map normalizeArrows $ es
111
normalizeArrows (Sequence es) = Sequence . map normalizeArrows $ es
67
false
true
0
7
14
35
17
18
null
null
BarrelfishOS/barrelfish
tools/skate/SkateBackendHeader.hs
mit
fmt_wr (TBuiltIn t) = builtin_fmt_wr t
38
fmt_wr (TBuiltIn t) = builtin_fmt_wr t
38
fmt_wr (TBuiltIn t) = builtin_fmt_wr t
38
false
false
0
6
5
19
8
11
null
null
sos22/ppres
ppres/driver/Reassembly.hs
gpl-2.0
reassembleInstruction :: Word64 -> ErrorT String AssemblyMonad (Maybe Word64) reassembleInstruction rip = do (after_prefix_rip, prefixes, prefixBytes) <- stripPrefixesAssembly rip lift $ assembleBytes prefixBytes hbyte <- assembleFetchByte after_prefix_rip case lookup hbyte instruction_templates of Nothing -> throwError $ "don't know what to do with hbyte 0x" ++ (showHex hbyte "") ++ " at 0x" ++ (showHex rip "") ++ " while reassembling" Just t -> dt ("reassembling around " ++ (showHex rip "")) $ it_reassemble t after_prefix_rip prefixes {- Do reassembly starting from rip until the doInstr worker tells us there are no more fall-throughs. Out of line branchs are accumulated in the AssemblyMonad. -}
782
reassembleInstruction :: Word64 -> ErrorT String AssemblyMonad (Maybe Word64) reassembleInstruction rip = do (after_prefix_rip, prefixes, prefixBytes) <- stripPrefixesAssembly rip lift $ assembleBytes prefixBytes hbyte <- assembleFetchByte after_prefix_rip case lookup hbyte instruction_templates of Nothing -> throwError $ "don't know what to do with hbyte 0x" ++ (showHex hbyte "") ++ " at 0x" ++ (showHex rip "") ++ " while reassembling" Just t -> dt ("reassembling around " ++ (showHex rip "")) $ it_reassemble t after_prefix_rip prefixes {- Do reassembly starting from rip until the doInstr worker tells us there are no more fall-throughs. Out of line branchs are accumulated in the AssemblyMonad. -}
782
reassembleInstruction rip = do (after_prefix_rip, prefixes, prefixBytes) <- stripPrefixesAssembly rip lift $ assembleBytes prefixBytes hbyte <- assembleFetchByte after_prefix_rip case lookup hbyte instruction_templates of Nothing -> throwError $ "don't know what to do with hbyte 0x" ++ (showHex hbyte "") ++ " at 0x" ++ (showHex rip "") ++ " while reassembling" Just t -> dt ("reassembling around " ++ (showHex rip "")) $ it_reassemble t after_prefix_rip prefixes {- Do reassembly starting from rip until the doInstr worker tells us there are no more fall-throughs. Out of line branchs are accumulated in the AssemblyMonad. -}
704
false
true
0
15
179
163
78
85
null
null
WawerOS/Chessotron2000
src/Chess.hs
mit
-- linePawns produce a line of pawns for a specific color for a new board linePawns :: Color -> [(Pos,Piece)] linePawns Black = map (\y -> ((6,y),Piece Black Pawn)) [0..7]
173
linePawns :: Color -> [(Pos,Piece)] linePawns Black = map (\y -> ((6,y),Piece Black Pawn)) [0..7]
97
linePawns Black = map (\y -> ((6,y),Piece Black Pawn)) [0..7]
61
true
true
0
9
31
69
37
32
null
null
Michaelt293/Lipid-Haskell
src/Lipid/Parsers/UnknownSn/Glycerophospholipid.hs
gpl-3.0
pip3MaybeOmegaP :: Parser (PIP3 (Maybe OmegaPosition)) pip3MaybeOmegaP = pip3P radylMaybeOmegaP
95
pip3MaybeOmegaP :: Parser (PIP3 (Maybe OmegaPosition)) pip3MaybeOmegaP = pip3P radylMaybeOmegaP
95
pip3MaybeOmegaP = pip3P radylMaybeOmegaP
40
false
true
0
9
9
29
14
15
null
null
vaibhav276/haskell_cs194_assignments
recursion_patterns/Golf.hs
mit
histogram :: [Integer] -> String histogram xs = plot xs ++ "==========\n0123456789\n"
85
histogram :: [Integer] -> String histogram xs = plot xs ++ "==========\n0123456789\n"
85
histogram xs = plot xs ++ "==========\n0123456789\n"
52
false
true
2
7
11
35
15
20
null
null
imh/plover
src/Language/Plover/Reduce.hs
mit
unifyT u bs (Dimension d1) (Dimension d2) = do unifyExpr u bs d1 d2
69
unifyT u bs (Dimension d1) (Dimension d2) = do unifyExpr u bs d1 d2
69
unifyT u bs (Dimension d1) (Dimension d2) = do unifyExpr u bs d1 d2
69
false
false
0
7
15
43
18
25
null
null
tonosaman/haskell-code-snippets
src/Codec/Base64.hs
bsd-2-clause
d2 b c = shiftL (b .&. 0x0f) 4 .|. shiftR c 2
45
d2 b c = shiftL (b .&. 0x0f) 4 .|. shiftR c 2
45
d2 b c = shiftL (b .&. 0x0f) 4 .|. shiftR c 2
45
false
false
0
8
12
32
15
17
null
null
Fuuzetsu/lens
src/Control/Lens/Fold.hs
bsd-3-clause
-- | Traverse the targets of an 'IndexedFold' or 'IndexedTraversal' with access to the index, discarding the results -- (with the arguments flipped). -- -- @ -- 'iforOf_' ≡ 'flip' '.' 'itraverseOf_' -- @ -- -- When you don't need access to the index then 'forOf_' is more flexible in what it accepts. -- -- @ -- 'forOf_' l a ≡ 'iforOf_' l a '.' 'const' -- @ -- -- @ -- 'iforOf_' :: 'Functor' f => 'IndexedGetter' i s a -> s -> (i -> a -> f r) -> f () -- 'iforOf_' :: 'Applicative' f => 'IndexedFold' i s a -> s -> (i -> a -> f r) -> f () -- 'iforOf_' :: 'Functor' f => 'IndexedLens'' i s a -> s -> (i -> a -> f r) -> f () -- 'iforOf_' :: 'Applicative' f => 'IndexedTraversal'' i s a -> s -> (i -> a -> f r) -> f () -- @ iforOf_ :: Functor f => IndexedGetting i (Traversed r f) s a -> s -> (i -> a -> f r) -> f () iforOf_ = flip . itraverseOf_
865
iforOf_ :: Functor f => IndexedGetting i (Traversed r f) s a -> s -> (i -> a -> f r) -> f () iforOf_ = flip . itraverseOf_
122
iforOf_ = flip . itraverseOf_
29
true
true
0
12
212
89
53
36
null
null
d0kt0r0/Tidal
src/Sound/Tidal/UI.hs
gpl-3.0
spreadr :: (t -> t1 -> Pattern b) -> [t] -> t1 -> Pattern b spreadr = spreadChoose
82
spreadr :: (t -> t1 -> Pattern b) -> [t] -> t1 -> Pattern b spreadr = spreadChoose
82
spreadr = spreadChoose
22
false
true
0
9
17
43
22
21
null
null
gencer/bond
compiler/src/Language/Bond/Codegen/Cpp/Comm_h.hs
mit
-- | Codegen template for generating /base_name/_comm.h containing declarations of -- of service interface and proxy. comm_h :: Maybe String -> MappingContext -> String -> [Import] -> [Declaration] -> (String, L.Text) comm_h export_attribute cpp file imports declarations = ("_comm.h", [lt| #pragma once #include <bond/comm/services.h> #include "#{file}_types.h" #{newlineSep 0 includeImport imports} #{CPP.openNamespace cpp} #{doubleLineSep 1 comm declarations} #{CPP.closeNamespace cpp} |]) where includeImport (Import path) = [lt|#include "#{dropExtension path}_comm.h"|] cppType = getTypeName cpp request mt = request' (payload mt) where payload = maybe "void" cppType request' params = [lt|::bond::comm::payload<#{padLeft}#{params}>|] where paramsText = toLazyText params padLeft = if L.head paramsText == ':' then [lt| |] else mempty response mt = response' (payload mt) where payload = maybe "void" cppType response' params = [lt|::bond::comm::message<#{padLeft}#{params}>|] where paramsText = toLazyText params padLeft = if L.head paramsText == ':' then [lt| |] else mempty callback m = [lt|const std::function<void (const #{response m}&)>& callback|] comm s@Service {..} = [lt|#{template}class #{declName} { public: virtual ~#{declName}() = default; #{doubleLineSep 2 virtualMethod serviceMethods} struct Schema; class Proxy; template <template <typename> class Promise> class Using; }; #{template}struct #{className}::Schema { #{export_attr}static const ::bond::Metadata metadata; #{newlineSep 2 methodMetadata serviceMethods} public: struct service { #{doubleLineSep 3 methodTemplate serviceMethods} }; private: typedef boost::mpl::list<> methods0; #{newlineSep 2 pushMethod indexedMethods} public: typedef #{typename}methods#{length serviceMethods}::type methods; #{constructor} }; #{onlyTemplate $ CPP.schemaMetadata cpp s} #{template}class #{className}::Proxy : public #{className} { public: template <typename ServiceProxy> explicit Proxy(const ServiceProxy& proxy, const std::string& name = #{className}::Schema::metadata.qualified_name) : _impl(boost::make_shared<__Impl<ServiceProxy>>(proxy, name)) {} explicit Proxy(const boost::shared_ptr<#{className}>& service) : _impl(service) {} Proxy() = default; #{doubleLineSep 2 proxyMethod serviceMethods} template <template <typename> class Promise> class Using; protected: boost::shared_ptr<#{className}> _impl; template <typename ServiceProxy> class __Impl : public #{className} { public: __Impl(const ServiceProxy& proxy, const std::string& name) : _proxy(proxy), _name(name) {} virtual ~__Impl() = default; #{doubleLineSep 3 implMethod serviceMethods} private: ServiceProxy _proxy; const std::string _name; }; }; #{template}template <template <typename> class Promise> class #{className}::Using : public #{className} { public: #{doubleLineSep 2 virtualFutureMethod serviceMethods} #{doubleLineSep 2 serviceMethod serviceMethods} }; #{template}template <template <typename> class Promise> class #{className}::Proxy::Using : public #{className}::Proxy { public: template <typename ServiceProxy> explicit Using(const ServiceProxy& proxy, const std::string& name = #{className}::Schema::metadata.qualified_name) : #{className}::Proxy(proxy, name) {} explicit Using(const boost::shared_ptr<#{className}>& service) : #{className}::Proxy(service) {} Using() = default; #{doubleLineSep 2 proxyFutureMethod serviceMethods} }; |] where className = CPP.className s template = CPP.template s onlyTemplate x = if null declParams then mempty else x typename = onlyTemplate [lt|typename |] export_attr = optional (\a -> [lt|#{a} |]) export_attribute methodMetadataVar m = [lt|s_#{methodName m}_metadata|] methodMetadata m = [lt|private: #{export_attr}static const ::bond::Metadata #{methodMetadataVar m};|] -- reversed list of method names zipped with indexes indexedMethods :: [(String, Int)] indexedMethods = zipWith ((,) . methodName) (reverse serviceMethods) [0..] pushMethod (method, i) = [lt|private: typedef #{typename}boost::mpl::push_front<methods#{i}, #{typename}service::#{method}>::type methods#{i + 1};|] -- constructor, generated only for service templates constructor = onlyTemplate [lt| Schema() { // Force instantiation of template statics (void)metadata; #{newlineSep 4 static serviceMethods} }|] where static m = [lt|(void)#{methodMetadataVar m};|] methodTemplate m = [lt|typedef ::bond::reflection::MethodTemplate< #{className}, #{request $ methodInput m}, #{result m}, &#{className}::#{methodName m}, &#{methodMetadataVar m} > #{methodName m};|] where result Event{} = "void" result Function{..} = response methodResult methodSignature n m = [lt|void #{methodName m}(#{commaLineSep n id $ methodParams m})|] where methodParams Event{..} = [ [lt|const #{request methodInput}& input|] ] methodParams Function{..} = [ [lt|const #{request methodInput}& input|] , callback methodResult ] resultOf x f = [lt|decltype(std::declval< #{x}>().#{f}())|] promiseType result = [lt|Promise< #{response result}>|] futureType result = resultOf (promiseType result) get_future where get_future = [lt|get_future|] methodFutureSignature Function{..} = [lt|auto #{methodName}(const #{request methodInput}& input) -> #{futureType methodResult}|] methodFutureSignature Event{..} = error "No future-based signature for Event methods" virtualMethod m = [lt|virtual #{methodSignature 3 m} = 0;|] virtualFutureMethod Event{} = mempty virtualFutureMethod m = [lt|virtual #{methodFutureSignature m} = 0;|] serviceMethod Event{} = mempty serviceMethod m@Function{..} = [lt|#{methodSignature 3 m} override { when(#{methodName}(input), ::bond::comm::Continuation(callback)); }|] proxyMethod m@Event{..} = [lt|#{methodSignature 3 m} override { _impl->#{methodName}(input); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| void #{methodName}() { _impl->#{methodName}(::bond::comm::payload<void>()); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| void #{methodName}(const #{cppType payload}& input) { _impl->#{methodName}(boost::cref(input)); }|] proxyMethodOverload _ = mempty proxyMethod m@Function{..} = [lt|#{methodSignature 3 m} override { _impl->#{methodName}(input, callback); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| void #{methodName}( #{callback methodResult}) { _impl->#{methodName}(::bond::comm::payload<void>(), callback); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| void #{methodName}(const #{cppType payload}& input, #{callback methodResult}) { _impl->#{methodName}(boost::cref(input), callback); }|] proxyMethodOverload _ = mempty proxyFutureMethod Event{} = mempty proxyFutureMethod m@Function{..} = [lt|using #{className}::Proxy::#{methodName}; #{methodFutureSignature m} { auto promise = boost::make_shared<#{promiseType methodResult}>(); _impl->#{methodName}(input, [=](const #{response methodResult}& result) mutable { promise->set_value(result); }); return promise->get_future(); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| auto #{methodName}() -> #{futureType methodResult} { return #{methodName}(::bond::comm::payload<void>()); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| auto #{methodName}(const #{cppType payload}& input) -> #{futureType methodResult} { return #{methodName}(#{request methodInput}(boost::cref(input))); } |] proxyMethodOverload _ = mempty implMethod m@Event{..} = [lt|#{methodSignature 4 m} override { _proxy.Send(_name, Schema::service::#{methodName}::metadata.name, input); }|] implMethod m@Function{..} = [lt|#{methodSignature 4 m} override { _proxy.Send(_name, Schema::service::#{methodName}::metadata.name, input, callback); }|] comm _ = mempty
9,971
comm_h :: Maybe String -> MappingContext -> String -> [Import] -> [Declaration] -> (String, L.Text) comm_h export_attribute cpp file imports declarations = ("_comm.h", [lt| #pragma once #include <bond/comm/services.h> #include "#{file}_types.h" #{newlineSep 0 includeImport imports} #{CPP.openNamespace cpp} #{doubleLineSep 1 comm declarations} #{CPP.closeNamespace cpp} |]) where includeImport (Import path) = [lt|#include "#{dropExtension path}_comm.h"|] cppType = getTypeName cpp request mt = request' (payload mt) where payload = maybe "void" cppType request' params = [lt|::bond::comm::payload<#{padLeft}#{params}>|] where paramsText = toLazyText params padLeft = if L.head paramsText == ':' then [lt| |] else mempty response mt = response' (payload mt) where payload = maybe "void" cppType response' params = [lt|::bond::comm::message<#{padLeft}#{params}>|] where paramsText = toLazyText params padLeft = if L.head paramsText == ':' then [lt| |] else mempty callback m = [lt|const std::function<void (const #{response m}&)>& callback|] comm s@Service {..} = [lt|#{template}class #{declName} { public: virtual ~#{declName}() = default; #{doubleLineSep 2 virtualMethod serviceMethods} struct Schema; class Proxy; template <template <typename> class Promise> class Using; }; #{template}struct #{className}::Schema { #{export_attr}static const ::bond::Metadata metadata; #{newlineSep 2 methodMetadata serviceMethods} public: struct service { #{doubleLineSep 3 methodTemplate serviceMethods} }; private: typedef boost::mpl::list<> methods0; #{newlineSep 2 pushMethod indexedMethods} public: typedef #{typename}methods#{length serviceMethods}::type methods; #{constructor} }; #{onlyTemplate $ CPP.schemaMetadata cpp s} #{template}class #{className}::Proxy : public #{className} { public: template <typename ServiceProxy> explicit Proxy(const ServiceProxy& proxy, const std::string& name = #{className}::Schema::metadata.qualified_name) : _impl(boost::make_shared<__Impl<ServiceProxy>>(proxy, name)) {} explicit Proxy(const boost::shared_ptr<#{className}>& service) : _impl(service) {} Proxy() = default; #{doubleLineSep 2 proxyMethod serviceMethods} template <template <typename> class Promise> class Using; protected: boost::shared_ptr<#{className}> _impl; template <typename ServiceProxy> class __Impl : public #{className} { public: __Impl(const ServiceProxy& proxy, const std::string& name) : _proxy(proxy), _name(name) {} virtual ~__Impl() = default; #{doubleLineSep 3 implMethod serviceMethods} private: ServiceProxy _proxy; const std::string _name; }; }; #{template}template <template <typename> class Promise> class #{className}::Using : public #{className} { public: #{doubleLineSep 2 virtualFutureMethod serviceMethods} #{doubleLineSep 2 serviceMethod serviceMethods} }; #{template}template <template <typename> class Promise> class #{className}::Proxy::Using : public #{className}::Proxy { public: template <typename ServiceProxy> explicit Using(const ServiceProxy& proxy, const std::string& name = #{className}::Schema::metadata.qualified_name) : #{className}::Proxy(proxy, name) {} explicit Using(const boost::shared_ptr<#{className}>& service) : #{className}::Proxy(service) {} Using() = default; #{doubleLineSep 2 proxyFutureMethod serviceMethods} }; |] where className = CPP.className s template = CPP.template s onlyTemplate x = if null declParams then mempty else x typename = onlyTemplate [lt|typename |] export_attr = optional (\a -> [lt|#{a} |]) export_attribute methodMetadataVar m = [lt|s_#{methodName m}_metadata|] methodMetadata m = [lt|private: #{export_attr}static const ::bond::Metadata #{methodMetadataVar m};|] -- reversed list of method names zipped with indexes indexedMethods :: [(String, Int)] indexedMethods = zipWith ((,) . methodName) (reverse serviceMethods) [0..] pushMethod (method, i) = [lt|private: typedef #{typename}boost::mpl::push_front<methods#{i}, #{typename}service::#{method}>::type methods#{i + 1};|] -- constructor, generated only for service templates constructor = onlyTemplate [lt| Schema() { // Force instantiation of template statics (void)metadata; #{newlineSep 4 static serviceMethods} }|] where static m = [lt|(void)#{methodMetadataVar m};|] methodTemplate m = [lt|typedef ::bond::reflection::MethodTemplate< #{className}, #{request $ methodInput m}, #{result m}, &#{className}::#{methodName m}, &#{methodMetadataVar m} > #{methodName m};|] where result Event{} = "void" result Function{..} = response methodResult methodSignature n m = [lt|void #{methodName m}(#{commaLineSep n id $ methodParams m})|] where methodParams Event{..} = [ [lt|const #{request methodInput}& input|] ] methodParams Function{..} = [ [lt|const #{request methodInput}& input|] , callback methodResult ] resultOf x f = [lt|decltype(std::declval< #{x}>().#{f}())|] promiseType result = [lt|Promise< #{response result}>|] futureType result = resultOf (promiseType result) get_future where get_future = [lt|get_future|] methodFutureSignature Function{..} = [lt|auto #{methodName}(const #{request methodInput}& input) -> #{futureType methodResult}|] methodFutureSignature Event{..} = error "No future-based signature for Event methods" virtualMethod m = [lt|virtual #{methodSignature 3 m} = 0;|] virtualFutureMethod Event{} = mempty virtualFutureMethod m = [lt|virtual #{methodFutureSignature m} = 0;|] serviceMethod Event{} = mempty serviceMethod m@Function{..} = [lt|#{methodSignature 3 m} override { when(#{methodName}(input), ::bond::comm::Continuation(callback)); }|] proxyMethod m@Event{..} = [lt|#{methodSignature 3 m} override { _impl->#{methodName}(input); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| void #{methodName}() { _impl->#{methodName}(::bond::comm::payload<void>()); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| void #{methodName}(const #{cppType payload}& input) { _impl->#{methodName}(boost::cref(input)); }|] proxyMethodOverload _ = mempty proxyMethod m@Function{..} = [lt|#{methodSignature 3 m} override { _impl->#{methodName}(input, callback); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| void #{methodName}( #{callback methodResult}) { _impl->#{methodName}(::bond::comm::payload<void>(), callback); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| void #{methodName}(const #{cppType payload}& input, #{callback methodResult}) { _impl->#{methodName}(boost::cref(input), callback); }|] proxyMethodOverload _ = mempty proxyFutureMethod Event{} = mempty proxyFutureMethod m@Function{..} = [lt|using #{className}::Proxy::#{methodName}; #{methodFutureSignature m} { auto promise = boost::make_shared<#{promiseType methodResult}>(); _impl->#{methodName}(input, [=](const #{response methodResult}& result) mutable { promise->set_value(result); }); return promise->get_future(); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| auto #{methodName}() -> #{futureType methodResult} { return #{methodName}(::bond::comm::payload<void>()); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| auto #{methodName}(const #{cppType payload}& input) -> #{futureType methodResult} { return #{methodName}(#{request methodInput}(boost::cref(input))); } |] proxyMethodOverload _ = mempty implMethod m@Event{..} = [lt|#{methodSignature 4 m} override { _proxy.Send(_name, Schema::service::#{methodName}::metadata.name, input); }|] implMethod m@Function{..} = [lt|#{methodSignature 4 m} override { _proxy.Send(_name, Schema::service::#{methodName}::metadata.name, input, callback); }|] comm _ = mempty
9,853
comm_h export_attribute cpp file imports declarations = ("_comm.h", [lt| #pragma once #include <bond/comm/services.h> #include "#{file}_types.h" #{newlineSep 0 includeImport imports} #{CPP.openNamespace cpp} #{doubleLineSep 1 comm declarations} #{CPP.closeNamespace cpp} |]) where includeImport (Import path) = [lt|#include "#{dropExtension path}_comm.h"|] cppType = getTypeName cpp request mt = request' (payload mt) where payload = maybe "void" cppType request' params = [lt|::bond::comm::payload<#{padLeft}#{params}>|] where paramsText = toLazyText params padLeft = if L.head paramsText == ':' then [lt| |] else mempty response mt = response' (payload mt) where payload = maybe "void" cppType response' params = [lt|::bond::comm::message<#{padLeft}#{params}>|] where paramsText = toLazyText params padLeft = if L.head paramsText == ':' then [lt| |] else mempty callback m = [lt|const std::function<void (const #{response m}&)>& callback|] comm s@Service {..} = [lt|#{template}class #{declName} { public: virtual ~#{declName}() = default; #{doubleLineSep 2 virtualMethod serviceMethods} struct Schema; class Proxy; template <template <typename> class Promise> class Using; }; #{template}struct #{className}::Schema { #{export_attr}static const ::bond::Metadata metadata; #{newlineSep 2 methodMetadata serviceMethods} public: struct service { #{doubleLineSep 3 methodTemplate serviceMethods} }; private: typedef boost::mpl::list<> methods0; #{newlineSep 2 pushMethod indexedMethods} public: typedef #{typename}methods#{length serviceMethods}::type methods; #{constructor} }; #{onlyTemplate $ CPP.schemaMetadata cpp s} #{template}class #{className}::Proxy : public #{className} { public: template <typename ServiceProxy> explicit Proxy(const ServiceProxy& proxy, const std::string& name = #{className}::Schema::metadata.qualified_name) : _impl(boost::make_shared<__Impl<ServiceProxy>>(proxy, name)) {} explicit Proxy(const boost::shared_ptr<#{className}>& service) : _impl(service) {} Proxy() = default; #{doubleLineSep 2 proxyMethod serviceMethods} template <template <typename> class Promise> class Using; protected: boost::shared_ptr<#{className}> _impl; template <typename ServiceProxy> class __Impl : public #{className} { public: __Impl(const ServiceProxy& proxy, const std::string& name) : _proxy(proxy), _name(name) {} virtual ~__Impl() = default; #{doubleLineSep 3 implMethod serviceMethods} private: ServiceProxy _proxy; const std::string _name; }; }; #{template}template <template <typename> class Promise> class #{className}::Using : public #{className} { public: #{doubleLineSep 2 virtualFutureMethod serviceMethods} #{doubleLineSep 2 serviceMethod serviceMethods} }; #{template}template <template <typename> class Promise> class #{className}::Proxy::Using : public #{className}::Proxy { public: template <typename ServiceProxy> explicit Using(const ServiceProxy& proxy, const std::string& name = #{className}::Schema::metadata.qualified_name) : #{className}::Proxy(proxy, name) {} explicit Using(const boost::shared_ptr<#{className}>& service) : #{className}::Proxy(service) {} Using() = default; #{doubleLineSep 2 proxyFutureMethod serviceMethods} }; |] where className = CPP.className s template = CPP.template s onlyTemplate x = if null declParams then mempty else x typename = onlyTemplate [lt|typename |] export_attr = optional (\a -> [lt|#{a} |]) export_attribute methodMetadataVar m = [lt|s_#{methodName m}_metadata|] methodMetadata m = [lt|private: #{export_attr}static const ::bond::Metadata #{methodMetadataVar m};|] -- reversed list of method names zipped with indexes indexedMethods :: [(String, Int)] indexedMethods = zipWith ((,) . methodName) (reverse serviceMethods) [0..] pushMethod (method, i) = [lt|private: typedef #{typename}boost::mpl::push_front<methods#{i}, #{typename}service::#{method}>::type methods#{i + 1};|] -- constructor, generated only for service templates constructor = onlyTemplate [lt| Schema() { // Force instantiation of template statics (void)metadata; #{newlineSep 4 static serviceMethods} }|] where static m = [lt|(void)#{methodMetadataVar m};|] methodTemplate m = [lt|typedef ::bond::reflection::MethodTemplate< #{className}, #{request $ methodInput m}, #{result m}, &#{className}::#{methodName m}, &#{methodMetadataVar m} > #{methodName m};|] where result Event{} = "void" result Function{..} = response methodResult methodSignature n m = [lt|void #{methodName m}(#{commaLineSep n id $ methodParams m})|] where methodParams Event{..} = [ [lt|const #{request methodInput}& input|] ] methodParams Function{..} = [ [lt|const #{request methodInput}& input|] , callback methodResult ] resultOf x f = [lt|decltype(std::declval< #{x}>().#{f}())|] promiseType result = [lt|Promise< #{response result}>|] futureType result = resultOf (promiseType result) get_future where get_future = [lt|get_future|] methodFutureSignature Function{..} = [lt|auto #{methodName}(const #{request methodInput}& input) -> #{futureType methodResult}|] methodFutureSignature Event{..} = error "No future-based signature for Event methods" virtualMethod m = [lt|virtual #{methodSignature 3 m} = 0;|] virtualFutureMethod Event{} = mempty virtualFutureMethod m = [lt|virtual #{methodFutureSignature m} = 0;|] serviceMethod Event{} = mempty serviceMethod m@Function{..} = [lt|#{methodSignature 3 m} override { when(#{methodName}(input), ::bond::comm::Continuation(callback)); }|] proxyMethod m@Event{..} = [lt|#{methodSignature 3 m} override { _impl->#{methodName}(input); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| void #{methodName}() { _impl->#{methodName}(::bond::comm::payload<void>()); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| void #{methodName}(const #{cppType payload}& input) { _impl->#{methodName}(boost::cref(input)); }|] proxyMethodOverload _ = mempty proxyMethod m@Function{..} = [lt|#{methodSignature 3 m} override { _impl->#{methodName}(input, callback); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| void #{methodName}( #{callback methodResult}) { _impl->#{methodName}(::bond::comm::payload<void>(), callback); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| void #{methodName}(const #{cppType payload}& input, #{callback methodResult}) { _impl->#{methodName}(boost::cref(input), callback); }|] proxyMethodOverload _ = mempty proxyFutureMethod Event{} = mempty proxyFutureMethod m@Function{..} = [lt|using #{className}::Proxy::#{methodName}; #{methodFutureSignature m} { auto promise = boost::make_shared<#{promiseType methodResult}>(); _impl->#{methodName}(input, [=](const #{response methodResult}& result) mutable { promise->set_value(result); }); return promise->get_future(); }#{proxyMethodOverload methodInput}|] where proxyMethodOverload Nothing = [lt| auto #{methodName}() -> #{futureType methodResult} { return #{methodName}(::bond::comm::payload<void>()); }|] proxyMethodOverload (Just payload) | isStruct payload = [lt| auto #{methodName}(const #{cppType payload}& input) -> #{futureType methodResult} { return #{methodName}(#{request methodInput}(boost::cref(input))); } |] proxyMethodOverload _ = mempty implMethod m@Event{..} = [lt|#{methodSignature 4 m} override { _proxy.Send(_name, Schema::service::#{methodName}::metadata.name, input); }|] implMethod m@Function{..} = [lt|#{methodSignature 4 m} override { _proxy.Send(_name, Schema::service::#{methodName}::metadata.name, input, callback); }|] comm _ = mempty
9,753
true
true
27
14
3,079
1,016
595
421
null
null
jwiegley/ghc-release
libraries/haskeline/System/Console/Haskeline/LineState.hs
gpl-3.0
replaceChar _ CEmpty = CEmpty
29
replaceChar _ CEmpty = CEmpty
29
replaceChar _ CEmpty = CEmpty
29
false
false
1
5
4
13
5
8
null
null
ocharles/snaplet-socketio
Example.hs
bsd-3-clause
initApp = Snap.makeSnaplet "app" "app" Nothing $ do Snap.addRoutes [ ("/socket.io.js", Snap.serveFile "node_modules/socket.io-client/dist/socket.io.js") , ("/", Snap.serveFile "example.html") ] CORS.wrapCORS App <$> Snap.nestSnaplet "socket.io" socketIO (SocketIO.init connectionHandler)
327
initApp = Snap.makeSnaplet "app" "app" Nothing $ do Snap.addRoutes [ ("/socket.io.js", Snap.serveFile "node_modules/socket.io-client/dist/socket.io.js") , ("/", Snap.serveFile "example.html") ] CORS.wrapCORS App <$> Snap.nestSnaplet "socket.io" socketIO (SocketIO.init connectionHandler)
327
initApp = Snap.makeSnaplet "app" "app" Nothing $ do Snap.addRoutes [ ("/socket.io.js", Snap.serveFile "node_modules/socket.io-client/dist/socket.io.js") , ("/", Snap.serveFile "example.html") ] CORS.wrapCORS App <$> Snap.nestSnaplet "socket.io" socketIO (SocketIO.init connectionHandler)
327
false
false
1
13
65
88
41
47
null
null
beni55/cryptol
src/Cryptol/TypeCheck/Solver/Numeric/Simplify1.hs
bsd-3-clause
-- | True pTrue :: I Bool pTrue = Return True
45
pTrue :: I Bool pTrue = Return True
35
pTrue = Return True
19
true
true
0
6
10
24
10
14
null
null
robeverest/accelerate
Data/Array/Accelerate/Smart.hs
bsd-3-clause
tix2 :: Elt s => TupleIdx (((t, s), s1), s2) s tix2 = SuccTupIdx tix1
69
tix2 :: Elt s => TupleIdx (((t, s), s1), s2) s tix2 = SuccTupIdx tix1
69
tix2 = SuccTupIdx tix1
22
false
true
0
9
14
44
24
20
null
null
CrazyMerlyn/99problems-haskell
11-20.hs
mit
split :: [a] -> Int -> ([a], [a]) split xs n = (take n xs, drop n xs)
69
split :: [a] -> Int -> ([a], [a]) split xs n = (take n xs, drop n xs)
69
split xs n = (take n xs, drop n xs)
35
false
true
0
8
17
55
30
25
null
null
deech/stack
src/Stack/Upgrade.hs
bsd-3-clause
upgrade :: (StackM env m, HasConfig env) => ConfigMonoid -> Maybe AbstractResolver -> Maybe String -- ^ git hash at time of building, if known -> UpgradeOpts -> m () upgrade gConfigMonoid mresolver builtHash (UpgradeOpts mbo mso) = case (mbo, mso) of -- FIXME It would be far nicer to capture this case in the -- options parser itself so we get better error messages, but -- I can't think of a way to make it happen. (Nothing, Nothing) -> error "You must allow either binary or source upgrade paths" (Just bo, Nothing) -> binary bo (Nothing, Just so) -> source so (Just bo, Just so) -> binary bo `catchAny` \e -> do $logWarn "Exception occured when trying to perform binary upgrade:" $logWarn $ T.pack $ show e $logWarn "Falling back to source upgrade" source so where binary bo = binaryUpgrade bo source so = sourceUpgrade gConfigMonoid mresolver builtHash so
1,019
upgrade :: (StackM env m, HasConfig env) => ConfigMonoid -> Maybe AbstractResolver -> Maybe String -- ^ git hash at time of building, if known -> UpgradeOpts -> m () upgrade gConfigMonoid mresolver builtHash (UpgradeOpts mbo mso) = case (mbo, mso) of -- FIXME It would be far nicer to capture this case in the -- options parser itself so we get better error messages, but -- I can't think of a way to make it happen. (Nothing, Nothing) -> error "You must allow either binary or source upgrade paths" (Just bo, Nothing) -> binary bo (Nothing, Just so) -> source so (Just bo, Just so) -> binary bo `catchAny` \e -> do $logWarn "Exception occured when trying to perform binary upgrade:" $logWarn $ T.pack $ show e $logWarn "Falling back to source upgrade" source so where binary bo = binaryUpgrade bo source so = sourceUpgrade gConfigMonoid mresolver builtHash so
1,019
upgrade gConfigMonoid mresolver builtHash (UpgradeOpts mbo mso) = case (mbo, mso) of -- FIXME It would be far nicer to capture this case in the -- options parser itself so we get better error messages, but -- I can't think of a way to make it happen. (Nothing, Nothing) -> error "You must allow either binary or source upgrade paths" (Just bo, Nothing) -> binary bo (Nothing, Just so) -> source so (Just bo, Just so) -> binary bo `catchAny` \e -> do $logWarn "Exception occured when trying to perform binary upgrade:" $logWarn $ T.pack $ show e $logWarn "Falling back to source upgrade" source so where binary bo = binaryUpgrade bo source so = sourceUpgrade gConfigMonoid mresolver builtHash so
813
false
true
1
14
308
235
115
120
null
null
spacekitteh/compdata
src/Data/Comp/Desugar.hs
bsd-3-clause
desugar = appHom desugHom
25
desugar = appHom desugHom
25
desugar = appHom desugHom
25
false
false
0
5
3
9
4
5
null
null
jean-edouard/manager
apptool/Import.hs
gpl-2.0
importDiskDefinition :: DIM -> VmPath -> Disk -> Import () importDiskDefinition dim vm disk = registerDiskCryptoKeys dim disk >> setupDiskFromFile hostFile where hostFile = fromMaybe "" (getDiskImportedPhysPath disk dim) setupDiskFromFile :: FilePath -> Import () setupDiskFromFile p = do diskP <- mkDiskPath <$> withXenmgrVm vm comCitrixXenclientXenmgrVmAddDisk let DiskPath diskPathStr = diskP appid <- app registerApplianceVmDisk appid disk diskPathStr withVmDisk diskP comCitrixXenclientVmdiskSetMode accessMode if (not $ diskIsCdrom disk) then do withVmDisk diskP comCitrixXenclientVmdiskAttachVhd p else do withVmDisk diskP comCitrixXenclientVmdiskSetPhysType "file" withVmDisk diskP comCitrixXenclientVmdiskSetDevtype "cdrom" withVmDisk diskP comCitrixXenclientVmdiskSetPhysPath p withVmDisk diskP comCitrixXenclientVmdiskSetShared True withVmDisk diskP comCitrixXenclientVmdiskSetEnabled (diskEnabled disk) withVmDisk diskP setProperties (diskPropertyOverrides disk) where accessMode = case diskAccess disk of DiskAccessRead -> "r" DiskAccessWrite -> "w" DiskAccessReadWrite -> "w"
1,274
importDiskDefinition :: DIM -> VmPath -> Disk -> Import () importDiskDefinition dim vm disk = registerDiskCryptoKeys dim disk >> setupDiskFromFile hostFile where hostFile = fromMaybe "" (getDiskImportedPhysPath disk dim) setupDiskFromFile :: FilePath -> Import () setupDiskFromFile p = do diskP <- mkDiskPath <$> withXenmgrVm vm comCitrixXenclientXenmgrVmAddDisk let DiskPath diskPathStr = diskP appid <- app registerApplianceVmDisk appid disk diskPathStr withVmDisk diskP comCitrixXenclientVmdiskSetMode accessMode if (not $ diskIsCdrom disk) then do withVmDisk diskP comCitrixXenclientVmdiskAttachVhd p else do withVmDisk diskP comCitrixXenclientVmdiskSetPhysType "file" withVmDisk diskP comCitrixXenclientVmdiskSetDevtype "cdrom" withVmDisk diskP comCitrixXenclientVmdiskSetPhysPath p withVmDisk diskP comCitrixXenclientVmdiskSetShared True withVmDisk diskP comCitrixXenclientVmdiskSetEnabled (diskEnabled disk) withVmDisk diskP setProperties (diskPropertyOverrides disk) where accessMode = case diskAccess disk of DiskAccessRead -> "r" DiskAccessWrite -> "w" DiskAccessReadWrite -> "w"
1,274
importDiskDefinition dim vm disk = registerDiskCryptoKeys dim disk >> setupDiskFromFile hostFile where hostFile = fromMaybe "" (getDiskImportedPhysPath disk dim) setupDiskFromFile :: FilePath -> Import () setupDiskFromFile p = do diskP <- mkDiskPath <$> withXenmgrVm vm comCitrixXenclientXenmgrVmAddDisk let DiskPath diskPathStr = diskP appid <- app registerApplianceVmDisk appid disk diskPathStr withVmDisk diskP comCitrixXenclientVmdiskSetMode accessMode if (not $ diskIsCdrom disk) then do withVmDisk diskP comCitrixXenclientVmdiskAttachVhd p else do withVmDisk diskP comCitrixXenclientVmdiskSetPhysType "file" withVmDisk diskP comCitrixXenclientVmdiskSetDevtype "cdrom" withVmDisk diskP comCitrixXenclientVmdiskSetPhysPath p withVmDisk diskP comCitrixXenclientVmdiskSetShared True withVmDisk diskP comCitrixXenclientVmdiskSetEnabled (diskEnabled disk) withVmDisk diskP setProperties (diskPropertyOverrides disk) where accessMode = case diskAccess disk of DiskAccessRead -> "r" DiskAccessWrite -> "w" DiskAccessReadWrite -> "w"
1,215
false
true
0
10
301
281
127
154
null
null
facebookincubator/duckling
Duckling/Numeral/ES/Rules.hs
bsd-3-clause
ruleLeadingDotNumeral :: Rule ruleLeadingDotNumeral = Rule { name = "dot number" , pattern = [regex "coma|punto", Predicate $ not . hasGrain] , prod = \case (_:Token Numeral NumeralData{TNumeral.value = v}:_) -> double $ decimalsToDouble v _ -> Nothing }
282
ruleLeadingDotNumeral :: Rule ruleLeadingDotNumeral = Rule { name = "dot number" , pattern = [regex "coma|punto", Predicate $ not . hasGrain] , prod = \case (_:Token Numeral NumeralData{TNumeral.value = v}:_) -> double $ decimalsToDouble v _ -> Nothing }
282
ruleLeadingDotNumeral = Rule { name = "dot number" , pattern = [regex "coma|punto", Predicate $ not . hasGrain] , prod = \case (_:Token Numeral NumeralData{TNumeral.value = v}:_) -> double $ decimalsToDouble v _ -> Nothing }
252
false
true
0
17
66
106
54
52
null
null
manpages/AAA
src/AAA/Session.hs
mit
-- | Invalidate all sessions with last tick older than given DiffTime -- as POSIXTime (eg. `5 :: POSIXTime -- 5s`). invalidate :: POSIXTime -> Sessions -> IO Sessions invalidate delta sessions = do tau <- getPOSIXTime let fresh = ((M.foldlWithKey g M.empty) . (M.filter $ f tau)) sessions return $ M.filterWithKey (h fresh) sessions where f t session = (t - (aaaSess_time session)) < delta g acc (a, s, _) _ = M.insert (a, s) True acc h pairs (a, s, _) _ = M.member (a, s) pairs -- | Terminate session with the given key
543
invalidate :: POSIXTime -> Sessions -> IO Sessions invalidate delta sessions = do tau <- getPOSIXTime let fresh = ((M.foldlWithKey g M.empty) . (M.filter $ f tau)) sessions return $ M.filterWithKey (h fresh) sessions where f t session = (t - (aaaSess_time session)) < delta g acc (a, s, _) _ = M.insert (a, s) True acc h pairs (a, s, _) _ = M.member (a, s) pairs -- | Terminate session with the given key
427
invalidate delta sessions = do tau <- getPOSIXTime let fresh = ((M.foldlWithKey g M.empty) . (M.filter $ f tau)) sessions return $ M.filterWithKey (h fresh) sessions where f t session = (t - (aaaSess_time session)) < delta g acc (a, s, _) _ = M.insert (a, s) True acc h pairs (a, s, _) _ = M.member (a, s) pairs -- | Terminate session with the given key
376
true
true
0
15
119
203
103
100
null
null
adarqui/99problems-hs
Experimentation/P21.hs
gpl-3.0
insertAt_nat_2 a lst n = sp1 ++ [a] ++ sp2 where (sp1, sp2) = splitAt (n-1) lst -- Tests
92
insertAt_nat_2 a lst n = sp1 ++ [a] ++ sp2 where (sp1, sp2) = splitAt (n-1) lst -- Tests
92
insertAt_nat_2 a lst n = sp1 ++ [a] ++ sp2 where (sp1, sp2) = splitAt (n-1) lst -- Tests
92
false
false
0
7
22
52
27
25
null
null
ml9951/ghc
compiler/llvmGen/LlvmCodeGen/CodeGen.hs
bsd-3-clause
genJump :: CmmExpr -> [GlobalReg] -> LlvmM StmtData -- Call to known function genJump (CmmLit (CmmLabel lbl)) live = do (vf, stmts, top) <- getHsFunc live lbl (stgRegs, stgStmts) <- funEpilogue live let s1 = Expr $ Call TailCall vf stgRegs llvmStdFunAttrs let s2 = Return Nothing return (stmts `appOL` stgStmts `snocOL` s1 `snocOL` s2, top) -- Call to unknown function / address
403
genJump :: CmmExpr -> [GlobalReg] -> LlvmM StmtData genJump (CmmLit (CmmLabel lbl)) live = do (vf, stmts, top) <- getHsFunc live lbl (stgRegs, stgStmts) <- funEpilogue live let s1 = Expr $ Call TailCall vf stgRegs llvmStdFunAttrs let s2 = Return Nothing return (stmts `appOL` stgStmts `snocOL` s1 `snocOL` s2, top) -- Call to unknown function / address
376
genJump (CmmLit (CmmLabel lbl)) live = do (vf, stmts, top) <- getHsFunc live lbl (stgRegs, stgStmts) <- funEpilogue live let s1 = Expr $ Call TailCall vf stgRegs llvmStdFunAttrs let s2 = Return Nothing return (stmts `appOL` stgStmts `snocOL` s1 `snocOL` s2, top) -- Call to unknown function / address
324
true
true
0
11
87
145
75
70
null
null
phischu/fragnix
builtins/ghc-prim/GHC.Prim.hs
bsd-3-clause
-- | Broadcast a scalar to all elements of a vector. broadcastInt32X16# :: Int# -> Int32X16# broadcastInt32X16# = broadcastInt32X16#
134
broadcastInt32X16# :: Int# -> Int32X16# broadcastInt32X16# = broadcastInt32X16#
79
broadcastInt32X16# = broadcastInt32X16#
39
true
true
0
5
20
16
9
7
null
null
vTurbine/ghc
compiler/prelude/PrelNames.hs
bsd-3-clause
orderingTyConName, ltDataConName, eqDataConName, gtDataConName :: Name orderingTyConName = tcQual gHC_TYPES (fsLit "Ordering") orderingTyConKey
144
orderingTyConName, ltDataConName, eqDataConName, gtDataConName :: Name orderingTyConName = tcQual gHC_TYPES (fsLit "Ordering") orderingTyConKey
144
orderingTyConName = tcQual gHC_TYPES (fsLit "Ordering") orderingTyConKey
73
false
true
0
7
13
30
18
12
null
null
andreyLevushkin/LambdaWars
src/Engine.hs
mit
sanitizeCommand (Decelerate value) = Decelerate $ bound 0 maxDeceleration value
79
sanitizeCommand (Decelerate value) = Decelerate $ bound 0 maxDeceleration value
79
sanitizeCommand (Decelerate value) = Decelerate $ bound 0 maxDeceleration value
79
false
false
0
7
9
26
12
14
null
null
wavewave/lhc-analysis-collection
analysis/Util.hs
gpl-3.0
fetchXSecNHist :: WebDAVConfig -> WebDAVRemoteDir -> String -> IO (Maybe (CrossSectionAndCount,[(JESParam,HistEType)])) fetchXSecNHist wdavcfg wdavrdir bname = do let fp1 = bname ++ "_ATLAS8TeV0L2to6JBkgTest.json" fp2 = bname ++ "_total_count.json" runMaybeT $ do (_,mr1) <- MaybeT . boolToMaybeM (doesFileExistInDAV wdavcfg wdavrdir fp1) . downloadFile True wdavcfg wdavrdir $ fp1 r1 <- liftM LB.pack (MaybeT . return $ mr1) (result :: [(JESParam, HistEType)]) <- MaybeT . return $ G.decode r1 (_,mr2) <- MaybeT . boolToMaybeM (doesFileExistInDAV wdavcfg wdavrdir fp2) . downloadFile True wdavcfg wdavrdir $ fp2 r2 <- liftM LB.pack (MaybeT . return $ mr2) (xsec :: CrossSectionAndCount) <- MaybeT . return $ G.decode r2 return (xsec,result)
856
fetchXSecNHist :: WebDAVConfig -> WebDAVRemoteDir -> String -> IO (Maybe (CrossSectionAndCount,[(JESParam,HistEType)])) fetchXSecNHist wdavcfg wdavrdir bname = do let fp1 = bname ++ "_ATLAS8TeV0L2to6JBkgTest.json" fp2 = bname ++ "_total_count.json" runMaybeT $ do (_,mr1) <- MaybeT . boolToMaybeM (doesFileExistInDAV wdavcfg wdavrdir fp1) . downloadFile True wdavcfg wdavrdir $ fp1 r1 <- liftM LB.pack (MaybeT . return $ mr1) (result :: [(JESParam, HistEType)]) <- MaybeT . return $ G.decode r1 (_,mr2) <- MaybeT . boolToMaybeM (doesFileExistInDAV wdavcfg wdavrdir fp2) . downloadFile True wdavcfg wdavrdir $ fp2 r2 <- liftM LB.pack (MaybeT . return $ mr2) (xsec :: CrossSectionAndCount) <- MaybeT . return $ G.decode r2 return (xsec,result)
856
fetchXSecNHist wdavcfg wdavrdir bname = do let fp1 = bname ++ "_ATLAS8TeV0L2to6JBkgTest.json" fp2 = bname ++ "_total_count.json" runMaybeT $ do (_,mr1) <- MaybeT . boolToMaybeM (doesFileExistInDAV wdavcfg wdavrdir fp1) . downloadFile True wdavcfg wdavrdir $ fp1 r1 <- liftM LB.pack (MaybeT . return $ mr1) (result :: [(JESParam, HistEType)]) <- MaybeT . return $ G.decode r1 (_,mr2) <- MaybeT . boolToMaybeM (doesFileExistInDAV wdavcfg wdavrdir fp2) . downloadFile True wdavcfg wdavrdir $ fp2 r2 <- liftM LB.pack (MaybeT . return $ mr2) (xsec :: CrossSectionAndCount) <- MaybeT . return $ G.decode r2 return (xsec,result)
720
false
true
0
16
218
298
149
149
null
null
adunning/pandoc-citeproc
src/Text/CSL/Util.hs
bsd-3-clause
parseString (Bool b) = return $ map toLower $ show b
54
parseString (Bool b) = return $ map toLower $ show b
54
parseString (Bool b) = return $ map toLower $ show b
54
false
false
0
7
12
30
13
17
null
null
martin-kolinek/stack
src/Stack/Docker.hs
bsd-3-clause
cleanup :: (StackM env m, HasConfig env) => CleanupOpts -> m () cleanup opts = do config <- view configL let docker = configDocker config envOverride <- getEnvOverride (configPlatform config) checkDockerVersion envOverride docker let runDocker = readDockerProcess envOverride Nothing imagesOut <- runDocker ["images","--no-trunc","-f","dangling=false"] danglingImagesOut <- runDocker ["images","--no-trunc","-f","dangling=true"] runningContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=running"] restartingContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=restarting"] exitedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=exited"] pausedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=paused"] let imageRepos = parseImagesOut imagesOut danglingImageHashes = Map.keys (parseImagesOut danglingImagesOut) runningContainers = parseContainersOut runningContainersOut ++ parseContainersOut restartingContainersOut stoppedContainers = parseContainersOut exitedContainersOut ++ parseContainersOut pausedContainersOut inspectMap <- inspects envOverride (Map.keys imageRepos ++ danglingImageHashes ++ map fst stoppedContainers ++ map fst runningContainers) (imagesLastUsed,curTime) <- liftIO ((,) <$> getDockerImagesLastUsed config <*> getZonedTime) let planWriter = buildPlan curTime imagesLastUsed imageRepos danglingImageHashes stoppedContainers runningContainers inspectMap plan = toLazyByteString (execWriter planWriter) plan' <- case dcAction opts of CleanupInteractive -> liftIO (editByteString (intercalate "-" [stackProgName ,dockerCmdName ,dockerCleanupCmdName ,"plan"]) plan) CleanupImmediate -> return plan CleanupDryRun -> do liftIO (LBS.hPut stdout plan) return LBS.empty mapM_ (performPlanLine envOverride) (reverse (filter filterPlanLine (lines (LBS.unpack plan')))) allImageHashesOut <- runDocker ["images","-aq","--no-trunc"] liftIO (pruneDockerImagesLastUsed config (lines (decodeUtf8 allImageHashesOut))) where filterPlanLine line = case line of c:_ | isSpace c -> False _ -> True performPlanLine envOverride line = case filter (not . null) (words (takeWhile (/= '#') line)) of [] -> return () (c:_):t:v:_ -> do args <- if | toUpper c == 'R' && t == imageStr -> do $logInfo (concatT ["Removing image: '",v,"'"]) return ["rmi",v] | toUpper c == 'R' && t == containerStr -> do $logInfo (concatT ["Removing container: '",v,"'"]) return ["rm","-f",v] | otherwise -> throwM (InvalidCleanupCommandException line) e <- try (readDockerProcess envOverride Nothing args) case e of Left ex@ProcessFailed{} -> $logError (concatT ["Could not remove: '",v,"': ", show ex]) Left e' -> throwM e' Right _ -> return () _ -> throwM (InvalidCleanupCommandException line) parseImagesOut = Map.fromListWith (++) . map parseImageRepo . drop 1 . lines . decodeUtf8 where parseImageRepo :: String -> (String, [String]) parseImageRepo line = case words line of repo:tag:hash:_ | repo == "<none>" -> (hash,[]) | tag == "<none>" -> (hash,[repo]) | otherwise -> (hash,[repo ++ ":" ++ tag]) _ -> impureThrow (InvalidImagesOutputException line) parseContainersOut = map parseContainer . drop 1 . lines . decodeUtf8 where parseContainer line = case words line of hash:image:rest -> (hash,(image,last rest)) _ -> impureThrow (InvalidPSOutputException line) buildPlan curTime imagesLastUsed imageRepos danglingImageHashes stoppedContainers runningContainers inspectMap = do case dcAction opts of CleanupInteractive -> do buildStrLn (concat ["# STACK DOCKER CLEANUP PLAN" ,"\n#" ,"\n# When you leave the editor, the lines in this plan will be processed." ,"\n#" ,"\n# Lines that begin with 'R' denote an image or container that will be." ,"\n# removed. You may change the first character to/from 'R' to remove/keep" ,"\n# and image or container that would otherwise be kept/removed." ,"\n#" ,"\n# To cancel the cleanup, delete all lines in this file." ,"\n#" ,"\n# By default, the following images/containers will be removed:" ,"\n#"]) buildDefault dcRemoveKnownImagesLastUsedDaysAgo "Known images last used" buildDefault dcRemoveUnknownImagesCreatedDaysAgo "Unknown images created" buildDefault dcRemoveDanglingImagesCreatedDaysAgo "Dangling images created" buildDefault dcRemoveStoppedContainersCreatedDaysAgo "Stopped containers created" buildDefault dcRemoveRunningContainersCreatedDaysAgo "Running containers created" buildStrLn (concat ["#" ,"\n# The default plan can be adjusted using command-line arguments." ,"\n# Run '" ++ unwords [stackProgName, dockerCmdName, dockerCleanupCmdName] ++ " --help' for details." ,"\n#"]) _ -> buildStrLn (unlines ["# Lines that begin with 'R' denote an image or container that will be." ,"# removed."]) buildSection "KNOWN IMAGES (pulled/used by stack)" imagesLastUsed buildKnownImage buildSection "UNKNOWN IMAGES (not managed by stack)" (sortCreated (Map.toList (foldl' (\m (h,_) -> Map.delete h m) imageRepos imagesLastUsed))) buildUnknownImage buildSection "DANGLING IMAGES (no named references and not depended on by other images)" (sortCreated (map (,()) danglingImageHashes)) buildDanglingImage buildSection "STOPPED CONTAINERS" (sortCreated stoppedContainers) (buildContainer (dcRemoveStoppedContainersCreatedDaysAgo opts)) buildSection "RUNNING CONTAINERS" (sortCreated runningContainers) (buildContainer (dcRemoveRunningContainersCreatedDaysAgo opts)) where buildDefault accessor description = case accessor opts of Just days -> buildStrLn ("# - " ++ description ++ " at least " ++ showDays days ++ ".") Nothing -> return () sortCreated = sortWith (\(_,_,x) -> Down x) . mapMaybe (\(h,r) -> case Map.lookup h inspectMap of Nothing -> Nothing Just ii -> Just (h,r,iiCreated ii)) buildSection sectionHead items itemBuilder = do let (anyWrote,b) = runWriter (forM items itemBuilder) when (or anyWrote) $ do buildSectionHead sectionHead tell b buildKnownImage (imageHash,lastUsedProjects) = case Map.lookup imageHash imageRepos of Just repos@(_:_) -> do case lastUsedProjects of (l,_):_ -> forM_ repos (buildImageTime (dcRemoveKnownImagesLastUsedDaysAgo opts) l) _ -> forM_ repos buildKeepImage forM_ lastUsedProjects buildProject buildInspect imageHash return True _ -> return False buildUnknownImage (hash, repos, created) = case repos of [] -> return False _ -> do forM_ repos (buildImageTime (dcRemoveUnknownImagesCreatedDaysAgo opts) created) buildInspect hash return True buildDanglingImage (hash, (), created) = do buildImageTime (dcRemoveDanglingImagesCreatedDaysAgo opts) created hash buildInspect hash return True buildContainer removeAge (hash,(image,name),created) = do let disp = name ++ " (image: " ++ image ++ ")" buildTime containerStr removeAge created disp buildInspect hash return True buildProject (lastUsedTime, projectPath) = buildInfo ("Last used " ++ showDaysAgo lastUsedTime ++ " in " ++ projectPath) buildInspect hash = case Map.lookup hash inspectMap of Just Inspect{iiCreated,iiVirtualSize} -> buildInfo ("Created " ++ showDaysAgo iiCreated ++ maybe "" (\s -> " (size: " ++ printf "%g" (fromIntegral s / 1024.0 / 1024.0 :: Float) ++ "M)") iiVirtualSize) Nothing -> return () showDays days = case days of 0 -> "today" 1 -> "yesterday" n -> show n ++ " days ago" showDaysAgo oldTime = showDays (daysAgo oldTime) daysAgo oldTime = let ZonedTime (LocalTime today _) zone = curTime LocalTime oldDay _ = utcToLocalTime zone oldTime in diffDays today oldDay buildImageTime = buildTime imageStr buildTime t removeAge time disp = case removeAge of Just d | daysAgo time >= d -> buildStrLn ("R " ++ t ++ " " ++ disp) _ -> buildKeep t disp buildKeep t d = buildStrLn (" " ++ t ++ " " ++ d) buildKeepImage = buildKeep imageStr buildSectionHead s = buildStrLn ("\n#\n# " ++ s ++ "\n#\n") buildInfo = buildStrLn . (" # " ++) buildStrLn l = do buildStr l tell (charUtf8 '\n') buildStr = tell . stringUtf8 imageStr = "image" containerStr = "container" -- | Inspect Docker image or container.
11,402
cleanup :: (StackM env m, HasConfig env) => CleanupOpts -> m () cleanup opts = do config <- view configL let docker = configDocker config envOverride <- getEnvOverride (configPlatform config) checkDockerVersion envOverride docker let runDocker = readDockerProcess envOverride Nothing imagesOut <- runDocker ["images","--no-trunc","-f","dangling=false"] danglingImagesOut <- runDocker ["images","--no-trunc","-f","dangling=true"] runningContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=running"] restartingContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=restarting"] exitedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=exited"] pausedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=paused"] let imageRepos = parseImagesOut imagesOut danglingImageHashes = Map.keys (parseImagesOut danglingImagesOut) runningContainers = parseContainersOut runningContainersOut ++ parseContainersOut restartingContainersOut stoppedContainers = parseContainersOut exitedContainersOut ++ parseContainersOut pausedContainersOut inspectMap <- inspects envOverride (Map.keys imageRepos ++ danglingImageHashes ++ map fst stoppedContainers ++ map fst runningContainers) (imagesLastUsed,curTime) <- liftIO ((,) <$> getDockerImagesLastUsed config <*> getZonedTime) let planWriter = buildPlan curTime imagesLastUsed imageRepos danglingImageHashes stoppedContainers runningContainers inspectMap plan = toLazyByteString (execWriter planWriter) plan' <- case dcAction opts of CleanupInteractive -> liftIO (editByteString (intercalate "-" [stackProgName ,dockerCmdName ,dockerCleanupCmdName ,"plan"]) plan) CleanupImmediate -> return plan CleanupDryRun -> do liftIO (LBS.hPut stdout plan) return LBS.empty mapM_ (performPlanLine envOverride) (reverse (filter filterPlanLine (lines (LBS.unpack plan')))) allImageHashesOut <- runDocker ["images","-aq","--no-trunc"] liftIO (pruneDockerImagesLastUsed config (lines (decodeUtf8 allImageHashesOut))) where filterPlanLine line = case line of c:_ | isSpace c -> False _ -> True performPlanLine envOverride line = case filter (not . null) (words (takeWhile (/= '#') line)) of [] -> return () (c:_):t:v:_ -> do args <- if | toUpper c == 'R' && t == imageStr -> do $logInfo (concatT ["Removing image: '",v,"'"]) return ["rmi",v] | toUpper c == 'R' && t == containerStr -> do $logInfo (concatT ["Removing container: '",v,"'"]) return ["rm","-f",v] | otherwise -> throwM (InvalidCleanupCommandException line) e <- try (readDockerProcess envOverride Nothing args) case e of Left ex@ProcessFailed{} -> $logError (concatT ["Could not remove: '",v,"': ", show ex]) Left e' -> throwM e' Right _ -> return () _ -> throwM (InvalidCleanupCommandException line) parseImagesOut = Map.fromListWith (++) . map parseImageRepo . drop 1 . lines . decodeUtf8 where parseImageRepo :: String -> (String, [String]) parseImageRepo line = case words line of repo:tag:hash:_ | repo == "<none>" -> (hash,[]) | tag == "<none>" -> (hash,[repo]) | otherwise -> (hash,[repo ++ ":" ++ tag]) _ -> impureThrow (InvalidImagesOutputException line) parseContainersOut = map parseContainer . drop 1 . lines . decodeUtf8 where parseContainer line = case words line of hash:image:rest -> (hash,(image,last rest)) _ -> impureThrow (InvalidPSOutputException line) buildPlan curTime imagesLastUsed imageRepos danglingImageHashes stoppedContainers runningContainers inspectMap = do case dcAction opts of CleanupInteractive -> do buildStrLn (concat ["# STACK DOCKER CLEANUP PLAN" ,"\n#" ,"\n# When you leave the editor, the lines in this plan will be processed." ,"\n#" ,"\n# Lines that begin with 'R' denote an image or container that will be." ,"\n# removed. You may change the first character to/from 'R' to remove/keep" ,"\n# and image or container that would otherwise be kept/removed." ,"\n#" ,"\n# To cancel the cleanup, delete all lines in this file." ,"\n#" ,"\n# By default, the following images/containers will be removed:" ,"\n#"]) buildDefault dcRemoveKnownImagesLastUsedDaysAgo "Known images last used" buildDefault dcRemoveUnknownImagesCreatedDaysAgo "Unknown images created" buildDefault dcRemoveDanglingImagesCreatedDaysAgo "Dangling images created" buildDefault dcRemoveStoppedContainersCreatedDaysAgo "Stopped containers created" buildDefault dcRemoveRunningContainersCreatedDaysAgo "Running containers created" buildStrLn (concat ["#" ,"\n# The default plan can be adjusted using command-line arguments." ,"\n# Run '" ++ unwords [stackProgName, dockerCmdName, dockerCleanupCmdName] ++ " --help' for details." ,"\n#"]) _ -> buildStrLn (unlines ["# Lines that begin with 'R' denote an image or container that will be." ,"# removed."]) buildSection "KNOWN IMAGES (pulled/used by stack)" imagesLastUsed buildKnownImage buildSection "UNKNOWN IMAGES (not managed by stack)" (sortCreated (Map.toList (foldl' (\m (h,_) -> Map.delete h m) imageRepos imagesLastUsed))) buildUnknownImage buildSection "DANGLING IMAGES (no named references and not depended on by other images)" (sortCreated (map (,()) danglingImageHashes)) buildDanglingImage buildSection "STOPPED CONTAINERS" (sortCreated stoppedContainers) (buildContainer (dcRemoveStoppedContainersCreatedDaysAgo opts)) buildSection "RUNNING CONTAINERS" (sortCreated runningContainers) (buildContainer (dcRemoveRunningContainersCreatedDaysAgo opts)) where buildDefault accessor description = case accessor opts of Just days -> buildStrLn ("# - " ++ description ++ " at least " ++ showDays days ++ ".") Nothing -> return () sortCreated = sortWith (\(_,_,x) -> Down x) . mapMaybe (\(h,r) -> case Map.lookup h inspectMap of Nothing -> Nothing Just ii -> Just (h,r,iiCreated ii)) buildSection sectionHead items itemBuilder = do let (anyWrote,b) = runWriter (forM items itemBuilder) when (or anyWrote) $ do buildSectionHead sectionHead tell b buildKnownImage (imageHash,lastUsedProjects) = case Map.lookup imageHash imageRepos of Just repos@(_:_) -> do case lastUsedProjects of (l,_):_ -> forM_ repos (buildImageTime (dcRemoveKnownImagesLastUsedDaysAgo opts) l) _ -> forM_ repos buildKeepImage forM_ lastUsedProjects buildProject buildInspect imageHash return True _ -> return False buildUnknownImage (hash, repos, created) = case repos of [] -> return False _ -> do forM_ repos (buildImageTime (dcRemoveUnknownImagesCreatedDaysAgo opts) created) buildInspect hash return True buildDanglingImage (hash, (), created) = do buildImageTime (dcRemoveDanglingImagesCreatedDaysAgo opts) created hash buildInspect hash return True buildContainer removeAge (hash,(image,name),created) = do let disp = name ++ " (image: " ++ image ++ ")" buildTime containerStr removeAge created disp buildInspect hash return True buildProject (lastUsedTime, projectPath) = buildInfo ("Last used " ++ showDaysAgo lastUsedTime ++ " in " ++ projectPath) buildInspect hash = case Map.lookup hash inspectMap of Just Inspect{iiCreated,iiVirtualSize} -> buildInfo ("Created " ++ showDaysAgo iiCreated ++ maybe "" (\s -> " (size: " ++ printf "%g" (fromIntegral s / 1024.0 / 1024.0 :: Float) ++ "M)") iiVirtualSize) Nothing -> return () showDays days = case days of 0 -> "today" 1 -> "yesterday" n -> show n ++ " days ago" showDaysAgo oldTime = showDays (daysAgo oldTime) daysAgo oldTime = let ZonedTime (LocalTime today _) zone = curTime LocalTime oldDay _ = utcToLocalTime zone oldTime in diffDays today oldDay buildImageTime = buildTime imageStr buildTime t removeAge time disp = case removeAge of Just d | daysAgo time >= d -> buildStrLn ("R " ++ t ++ " " ++ disp) _ -> buildKeep t disp buildKeep t d = buildStrLn (" " ++ t ++ " " ++ d) buildKeepImage = buildKeep imageStr buildSectionHead s = buildStrLn ("\n#\n# " ++ s ++ "\n#\n") buildInfo = buildStrLn . (" # " ++) buildStrLn l = do buildStr l tell (charUtf8 '\n') buildStr = tell . stringUtf8 imageStr = "image" containerStr = "container" -- | Inspect Docker image or container.
11,402
cleanup opts = do config <- view configL let docker = configDocker config envOverride <- getEnvOverride (configPlatform config) checkDockerVersion envOverride docker let runDocker = readDockerProcess envOverride Nothing imagesOut <- runDocker ["images","--no-trunc","-f","dangling=false"] danglingImagesOut <- runDocker ["images","--no-trunc","-f","dangling=true"] runningContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=running"] restartingContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=restarting"] exitedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=exited"] pausedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=paused"] let imageRepos = parseImagesOut imagesOut danglingImageHashes = Map.keys (parseImagesOut danglingImagesOut) runningContainers = parseContainersOut runningContainersOut ++ parseContainersOut restartingContainersOut stoppedContainers = parseContainersOut exitedContainersOut ++ parseContainersOut pausedContainersOut inspectMap <- inspects envOverride (Map.keys imageRepos ++ danglingImageHashes ++ map fst stoppedContainers ++ map fst runningContainers) (imagesLastUsed,curTime) <- liftIO ((,) <$> getDockerImagesLastUsed config <*> getZonedTime) let planWriter = buildPlan curTime imagesLastUsed imageRepos danglingImageHashes stoppedContainers runningContainers inspectMap plan = toLazyByteString (execWriter planWriter) plan' <- case dcAction opts of CleanupInteractive -> liftIO (editByteString (intercalate "-" [stackProgName ,dockerCmdName ,dockerCleanupCmdName ,"plan"]) plan) CleanupImmediate -> return plan CleanupDryRun -> do liftIO (LBS.hPut stdout plan) return LBS.empty mapM_ (performPlanLine envOverride) (reverse (filter filterPlanLine (lines (LBS.unpack plan')))) allImageHashesOut <- runDocker ["images","-aq","--no-trunc"] liftIO (pruneDockerImagesLastUsed config (lines (decodeUtf8 allImageHashesOut))) where filterPlanLine line = case line of c:_ | isSpace c -> False _ -> True performPlanLine envOverride line = case filter (not . null) (words (takeWhile (/= '#') line)) of [] -> return () (c:_):t:v:_ -> do args <- if | toUpper c == 'R' && t == imageStr -> do $logInfo (concatT ["Removing image: '",v,"'"]) return ["rmi",v] | toUpper c == 'R' && t == containerStr -> do $logInfo (concatT ["Removing container: '",v,"'"]) return ["rm","-f",v] | otherwise -> throwM (InvalidCleanupCommandException line) e <- try (readDockerProcess envOverride Nothing args) case e of Left ex@ProcessFailed{} -> $logError (concatT ["Could not remove: '",v,"': ", show ex]) Left e' -> throwM e' Right _ -> return () _ -> throwM (InvalidCleanupCommandException line) parseImagesOut = Map.fromListWith (++) . map parseImageRepo . drop 1 . lines . decodeUtf8 where parseImageRepo :: String -> (String, [String]) parseImageRepo line = case words line of repo:tag:hash:_ | repo == "<none>" -> (hash,[]) | tag == "<none>" -> (hash,[repo]) | otherwise -> (hash,[repo ++ ":" ++ tag]) _ -> impureThrow (InvalidImagesOutputException line) parseContainersOut = map parseContainer . drop 1 . lines . decodeUtf8 where parseContainer line = case words line of hash:image:rest -> (hash,(image,last rest)) _ -> impureThrow (InvalidPSOutputException line) buildPlan curTime imagesLastUsed imageRepos danglingImageHashes stoppedContainers runningContainers inspectMap = do case dcAction opts of CleanupInteractive -> do buildStrLn (concat ["# STACK DOCKER CLEANUP PLAN" ,"\n#" ,"\n# When you leave the editor, the lines in this plan will be processed." ,"\n#" ,"\n# Lines that begin with 'R' denote an image or container that will be." ,"\n# removed. You may change the first character to/from 'R' to remove/keep" ,"\n# and image or container that would otherwise be kept/removed." ,"\n#" ,"\n# To cancel the cleanup, delete all lines in this file." ,"\n#" ,"\n# By default, the following images/containers will be removed:" ,"\n#"]) buildDefault dcRemoveKnownImagesLastUsedDaysAgo "Known images last used" buildDefault dcRemoveUnknownImagesCreatedDaysAgo "Unknown images created" buildDefault dcRemoveDanglingImagesCreatedDaysAgo "Dangling images created" buildDefault dcRemoveStoppedContainersCreatedDaysAgo "Stopped containers created" buildDefault dcRemoveRunningContainersCreatedDaysAgo "Running containers created" buildStrLn (concat ["#" ,"\n# The default plan can be adjusted using command-line arguments." ,"\n# Run '" ++ unwords [stackProgName, dockerCmdName, dockerCleanupCmdName] ++ " --help' for details." ,"\n#"]) _ -> buildStrLn (unlines ["# Lines that begin with 'R' denote an image or container that will be." ,"# removed."]) buildSection "KNOWN IMAGES (pulled/used by stack)" imagesLastUsed buildKnownImage buildSection "UNKNOWN IMAGES (not managed by stack)" (sortCreated (Map.toList (foldl' (\m (h,_) -> Map.delete h m) imageRepos imagesLastUsed))) buildUnknownImage buildSection "DANGLING IMAGES (no named references and not depended on by other images)" (sortCreated (map (,()) danglingImageHashes)) buildDanglingImage buildSection "STOPPED CONTAINERS" (sortCreated stoppedContainers) (buildContainer (dcRemoveStoppedContainersCreatedDaysAgo opts)) buildSection "RUNNING CONTAINERS" (sortCreated runningContainers) (buildContainer (dcRemoveRunningContainersCreatedDaysAgo opts)) where buildDefault accessor description = case accessor opts of Just days -> buildStrLn ("# - " ++ description ++ " at least " ++ showDays days ++ ".") Nothing -> return () sortCreated = sortWith (\(_,_,x) -> Down x) . mapMaybe (\(h,r) -> case Map.lookup h inspectMap of Nothing -> Nothing Just ii -> Just (h,r,iiCreated ii)) buildSection sectionHead items itemBuilder = do let (anyWrote,b) = runWriter (forM items itemBuilder) when (or anyWrote) $ do buildSectionHead sectionHead tell b buildKnownImage (imageHash,lastUsedProjects) = case Map.lookup imageHash imageRepos of Just repos@(_:_) -> do case lastUsedProjects of (l,_):_ -> forM_ repos (buildImageTime (dcRemoveKnownImagesLastUsedDaysAgo opts) l) _ -> forM_ repos buildKeepImage forM_ lastUsedProjects buildProject buildInspect imageHash return True _ -> return False buildUnknownImage (hash, repos, created) = case repos of [] -> return False _ -> do forM_ repos (buildImageTime (dcRemoveUnknownImagesCreatedDaysAgo opts) created) buildInspect hash return True buildDanglingImage (hash, (), created) = do buildImageTime (dcRemoveDanglingImagesCreatedDaysAgo opts) created hash buildInspect hash return True buildContainer removeAge (hash,(image,name),created) = do let disp = name ++ " (image: " ++ image ++ ")" buildTime containerStr removeAge created disp buildInspect hash return True buildProject (lastUsedTime, projectPath) = buildInfo ("Last used " ++ showDaysAgo lastUsedTime ++ " in " ++ projectPath) buildInspect hash = case Map.lookup hash inspectMap of Just Inspect{iiCreated,iiVirtualSize} -> buildInfo ("Created " ++ showDaysAgo iiCreated ++ maybe "" (\s -> " (size: " ++ printf "%g" (fromIntegral s / 1024.0 / 1024.0 :: Float) ++ "M)") iiVirtualSize) Nothing -> return () showDays days = case days of 0 -> "today" 1 -> "yesterday" n -> show n ++ " days ago" showDaysAgo oldTime = showDays (daysAgo oldTime) daysAgo oldTime = let ZonedTime (LocalTime today _) zone = curTime LocalTime oldDay _ = utcToLocalTime zone oldTime in diffDays today oldDay buildImageTime = buildTime imageStr buildTime t removeAge time disp = case removeAge of Just d | daysAgo time >= d -> buildStrLn ("R " ++ t ++ " " ++ disp) _ -> buildKeep t disp buildKeep t d = buildStrLn (" " ++ t ++ " " ++ d) buildKeepImage = buildKeep imageStr buildSectionHead s = buildStrLn ("\n#\n# " ++ s ++ "\n#\n") buildInfo = buildStrLn . (" # " ++) buildStrLn l = do buildStr l tell (charUtf8 '\n') buildStr = tell . stringUtf8 imageStr = "image" containerStr = "container" -- | Inspect Docker image or container.
11,330
false
true
0
22
4,518
2,544
1,246
1,298
null
null
vincenthz/hs-foundation
foundation/benchs/Fake/ByteString.hs
bsd-3-clause
filter _ = undefined
23
filter _ = undefined
23
filter _ = undefined
23
false
false
0
5
6
9
4
5
null
null
elfeck/elfeckcom
src/Web/BetterMdParser.hs
mit
onlyContent (Raw l) = l
23
onlyContent (Raw l) = l
23
onlyContent (Raw l) = l
23
false
false
0
7
4
15
7
8
null
null
Motions/motions
src/Bio/Motions/Callback/StandardScore.hs
apache-2.0
-- |Returns the neighbours of a given position neighbours :: Vec3 -> [Vec3] neighbours x = (x ^+^) <$> ([id, negated] <*> basis)
128
neighbours :: Vec3 -> [Vec3] neighbours x = (x ^+^) <$> ([id, negated] <*> basis)
81
neighbours x = (x ^+^) <$> ([id, negated] <*> basis)
52
true
true
0
8
22
43
25
18
null
null
haskell/haddock
haddock-api/src/Haddock/Options.hs
bsd-2-clause
sourceUrls :: [Flag] -> (Maybe String, Maybe String, Maybe String, Maybe String) sourceUrls flags = (optLast [str | Flag_SourceBaseURL str <- flags] ,optLast [str | Flag_SourceModuleURL str <- flags] ,optLast [str | Flag_SourceEntityURL str <- flags] ,optLast [str | Flag_SourceLEntityURL str <- flags])
316
sourceUrls :: [Flag] -> (Maybe String, Maybe String, Maybe String, Maybe String) sourceUrls flags = (optLast [str | Flag_SourceBaseURL str <- flags] ,optLast [str | Flag_SourceModuleURL str <- flags] ,optLast [str | Flag_SourceEntityURL str <- flags] ,optLast [str | Flag_SourceLEntityURL str <- flags])
316
sourceUrls flags = (optLast [str | Flag_SourceBaseURL str <- flags] ,optLast [str | Flag_SourceModuleURL str <- flags] ,optLast [str | Flag_SourceEntityURL str <- flags] ,optLast [str | Flag_SourceLEntityURL str <- flags])
235
false
true
0
10
55
125
63
62
null
null
spechub/Hets
Maude/PreComorphism.hs
gpl-2.0
-- | generates the formulas for the rewrite predicate of the given sort rewPredicateSens :: Id -> [Named CAS.CASLFORMULA] -> [Named CAS.CASLFORMULA] rewPredicateSens kind acc = ref : trans : acc where ref = reflSen kind trans = transSen kind -- | creates the reflexivity predicate for the given kind
322
rewPredicateSens :: Id -> [Named CAS.CASLFORMULA] -> [Named CAS.CASLFORMULA] rewPredicateSens kind acc = ref : trans : acc where ref = reflSen kind trans = transSen kind -- | creates the reflexivity predicate for the given kind
250
rewPredicateSens kind acc = ref : trans : acc where ref = reflSen kind trans = transSen kind -- | creates the reflexivity predicate for the given kind
173
true
true
0
9
72
68
35
33
null
null
alexander-at-github/eta
compiler/ETA/SimplCore/CoreMonad.hs
bsd-3-clause
isZeroSimplCount (SimplCount { ticks = n }) = n==0
50
isZeroSimplCount (SimplCount { ticks = n }) = n==0
50
isZeroSimplCount (SimplCount { ticks = n }) = n==0
50
false
false
0
8
8
26
13
13
null
null
itayd/hh
src/hh.hs
bsd-3-clause
main :: IO () main = let shouldRun opts = null $ intersect [Version, Help, Init] opts in do ( word, opts ) <- getArgs >>= parseArgs cfg <- (loadConfig >>= flip (foldM handleOpt) opts) cfg' <- if shouldRun opts then play (0, 0, word) cfg else return cfg when (saveOnExit cfg') $ saveConfig cfg'
396
main :: IO () main = let shouldRun opts = null $ intersect [Version, Help, Init] opts in do ( word, opts ) <- getArgs >>= parseArgs cfg <- (loadConfig >>= flip (foldM handleOpt) opts) cfg' <- if shouldRun opts then play (0, 0, word) cfg else return cfg when (saveOnExit cfg') $ saveConfig cfg'
396
main = let shouldRun opts = null $ intersect [Version, Help, Init] opts in do ( word, opts ) <- getArgs >>= parseArgs cfg <- (loadConfig >>= flip (foldM handleOpt) opts) cfg' <- if shouldRun opts then play (0, 0, word) cfg else return cfg when (saveOnExit cfg') $ saveConfig cfg'
382
false
true
0
15
157
150
72
78
null
null
facebookincubator/duckling
Duckling/Time/Types.hs
bsd-3-clause
seasonStart :: Season -> Time.Day seasonStart (Season year Spring) = Time.fromGregorian year 3 20
97
seasonStart :: Season -> Time.Day seasonStart (Season year Spring) = Time.fromGregorian year 3 20
97
seasonStart (Season year Spring) = Time.fromGregorian year 3 20
63
false
true
0
7
13
37
18
19
null
null
rueshyna/gogol
gogol-youtube/gen/Network/Google/YouTube/Types/Product.hs
mpl-2.0
-- | Creates a value of 'ThumbnailSetResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tsrEtag' -- -- * 'tsrKind' -- -- * 'tsrItems' -- -- * 'tsrVisitorId' -- -- * 'tsrEventId' thumbnailSetResponse :: ThumbnailSetResponse thumbnailSetResponse = ThumbnailSetResponse' { _tsrEtag = Nothing , _tsrKind = "youtube#thumbnailSetResponse" , _tsrItems = Nothing , _tsrVisitorId = Nothing , _tsrEventId = Nothing }
531
thumbnailSetResponse :: ThumbnailSetResponse thumbnailSetResponse = ThumbnailSetResponse' { _tsrEtag = Nothing , _tsrKind = "youtube#thumbnailSetResponse" , _tsrItems = Nothing , _tsrVisitorId = Nothing , _tsrEventId = Nothing }
260
thumbnailSetResponse = ThumbnailSetResponse' { _tsrEtag = Nothing , _tsrKind = "youtube#thumbnailSetResponse" , _tsrItems = Nothing , _tsrVisitorId = Nothing , _tsrEventId = Nothing }
211
true
true
0
6
108
56
40
16
null
null
vialette/ppattern
src/Data/Algorithm/PPattern/Combinatorics.hs
mit
{-| 'xs `choose` k' returns all sublists of size 'k' of 'xs'. Choosing from the empty set. >>> [] `Combinatorics.choose` (-1) [] >>> [] `Combinatorics.choose` 0 [[]] >>> [] `Combinatorics.choose` 1 [] Choosing from a non-empty set. >>> [1..5] `Combinatorics.choose` (-1) [] >>> [1..5] `Combinatorics.choose` 0 [[]] >>> [1..5] `Combinatorics.choose` 1 [[1],[2],[3],[4],[5]] >>> [1..5] `Combinatorics.choose` 2 [[1,2],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,4],[3,5],[4,5]] >>> [1..5] `Combinatorics.choose` 3 [[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]] >>> [1..5] `Combinatorics.choose` 4 [[1,2,3,4],[1,2,3,5],[1,2,4,5],[1,3,4,5],[2,3,4,5]] >>> [1..5] `Combinatorics.choose` 5 [[1,2,3,4,5]] >>> [1..5] `Combinatorics.choose` 6 [] -} choose :: [a] -> Int -> [[a]] xs `choose` k | k < 0 = [] | otherwise = xs `chooseAux` k
980
choose :: [a] -> Int -> [[a]] xs `choose` k | k < 0 = [] | otherwise = xs `chooseAux` k
95
xs `choose` k | k < 0 = [] | otherwise = xs `chooseAux` k
65
true
true
1
8
223
63
34
29
null
null
rfranek/duckling
Duckling/Engine.hs
bsd-3-clause
matchFirst :: Document -> Stash -> Match -> Duckling [Match] matchFirst _ _ (Rule {pattern = []}, _, _) = return []
115
matchFirst :: Document -> Stash -> Match -> Duckling [Match] matchFirst _ _ (Rule {pattern = []}, _, _) = return []
115
matchFirst _ _ (Rule {pattern = []}, _, _) = return []
54
false
true
0
10
21
61
32
29
null
null
andrewMacmurray/haskell-book-solutions
src/ch7/penguins.hs
mit
isSouthAfrica :: WherePenguinsLive -> Bool isSouthAfrica SouthAfrica = True
75
isSouthAfrica :: WherePenguinsLive -> Bool isSouthAfrica SouthAfrica = True
75
isSouthAfrica SouthAfrica = True
32
false
true
0
5
8
18
9
9
null
null
kurnevsky/missile
src/GameTree.hs
agpl-3.0
unfoldFunction (field : t) = (field, [t])
41
unfoldFunction (field : t) = (field, [t])
41
unfoldFunction (field : t) = (field, [t])
41
false
false
0
6
6
26
14
12
null
null
plcplc/muPromote-code
node/src/MuPromote/Node/Main.hs
gpl-3.0
-- | The actual 'main' action. It lives as a self-contained 'Resource'. When -- first invoked, the resource is empty (though a 'Resource'-aware compilation -- procedure could seed the resource with other sub-resources), and default -- versions of config-file resources and database resources are created. This -- division is necessary to maintain the illusion that resources have -- 'persistent/start-stop' semantics. resourceMain :: ResourceM () resourceMain = do logAct <- wireLogRes uiApp <- wireUIRes logAct evStore <- wireStorageRes logAct -- Get the socket to listen to sockRh <- M.lookup "Listen-Socket" <$> resChildren -- An action to start the server, depending on whether a Listen-Socket was -- given. liftIO $ logAct $ LogDebug "Getting bound sock" startWarpAct <- case sockRh of Just sockRh' -> do sock <- getBoundSock sockRh' return $ runSettingsSocket (nodeWarpSettings logAct) sock Nothing -> return $ runSettings (nodeWarpSettings logAct) -- Construct the node. liftIO $ do let node = spawnNode evStore nilProcessorClient startWarpAct (runPWA $ liftPA (nodeApiApp node) <> uiApp) -- | The settings used by the Warp server.
1,194
resourceMain :: ResourceM () resourceMain = do logAct <- wireLogRes uiApp <- wireUIRes logAct evStore <- wireStorageRes logAct -- Get the socket to listen to sockRh <- M.lookup "Listen-Socket" <$> resChildren -- An action to start the server, depending on whether a Listen-Socket was -- given. liftIO $ logAct $ LogDebug "Getting bound sock" startWarpAct <- case sockRh of Just sockRh' -> do sock <- getBoundSock sockRh' return $ runSettingsSocket (nodeWarpSettings logAct) sock Nothing -> return $ runSettings (nodeWarpSettings logAct) -- Construct the node. liftIO $ do let node = spawnNode evStore nilProcessorClient startWarpAct (runPWA $ liftPA (nodeApiApp node) <> uiApp) -- | The settings used by the Warp server.
776
resourceMain = do logAct <- wireLogRes uiApp <- wireUIRes logAct evStore <- wireStorageRes logAct -- Get the socket to listen to sockRh <- M.lookup "Listen-Socket" <$> resChildren -- An action to start the server, depending on whether a Listen-Socket was -- given. liftIO $ logAct $ LogDebug "Getting bound sock" startWarpAct <- case sockRh of Just sockRh' -> do sock <- getBoundSock sockRh' return $ runSettingsSocket (nodeWarpSettings logAct) sock Nothing -> return $ runSettings (nodeWarpSettings logAct) -- Construct the node. liftIO $ do let node = spawnNode evStore nilProcessorClient startWarpAct (runPWA $ liftPA (nodeApiApp node) <> uiApp) -- | The settings used by the Warp server.
747
true
true
0
16
225
198
94
104
null
null
tjakway/ghcjvm
compiler/cmm/CmmCommonBlockElim.hs
bsd-3-clause
hash_block :: CmmBlock -> HashCode hash_block block = fromIntegral (foldBlockNodesB3 (hash_fst, hash_mid, hash_lst) block (0 :: Word32) .&. (0x7fffffff :: Word32)) -- UniqFM doesn't like negative Ints where hash_fst _ h = h hash_mid m h = hash_node m + h `shiftL` 1 hash_lst m h = hash_node m + h `shiftL` 1 hash_node :: CmmNode O x -> Word32 hash_node n | dont_care n = 0 -- don't care hash_node (CmmUnwind _ e) = hash_e e hash_node (CmmAssign r e) = hash_reg r + hash_e e hash_node (CmmStore e e') = hash_e e + hash_e e' hash_node (CmmUnsafeForeignCall t _ as) = hash_tgt t + hash_list hash_e as hash_node (CmmBranch _) = 23 -- NB. ignore the label hash_node (CmmCondBranch p _ _ _) = hash_e p hash_node (CmmCall e _ _ _ _ _) = hash_e e hash_node (CmmForeignCall t _ _ _ _ _ _) = hash_tgt t hash_node (CmmSwitch e _) = hash_e e hash_node _ = error "hash_node: unknown Cmm node!" hash_reg :: CmmReg -> Word32 hash_reg (CmmLocal localReg) = hash_unique localReg -- important for performance, see #10397 hash_reg (CmmGlobal _) = 19 hash_e :: CmmExpr -> Word32 hash_e (CmmLit l) = hash_lit l hash_e (CmmLoad e _) = 67 + hash_e e hash_e (CmmReg r) = hash_reg r hash_e (CmmMachOp _ es) = hash_list hash_e es -- pessimal - no operator check hash_e (CmmRegOff r i) = hash_reg r + cvt i hash_e (CmmStackSlot _ _) = 13 hash_lit :: CmmLit -> Word32 hash_lit (CmmInt i _) = fromInteger i hash_lit (CmmFloat r _) = truncate r hash_lit (CmmVec ls) = hash_list hash_lit ls hash_lit (CmmLabel _) = 119 -- ugh hash_lit (CmmLabelOff _ i) = cvt $ 199 + i hash_lit (CmmLabelDiffOff _ _ i) = cvt $ 299 + i hash_lit (CmmBlock _) = 191 -- ugh hash_lit (CmmHighStackMark) = cvt 313 hash_tgt (ForeignTarget e _) = hash_e e hash_tgt (PrimTarget _) = 31 -- lots of these hash_list f = foldl (\z x -> f x + z) (0::Word32) cvt = fromInteger . toInteger hash_unique :: Uniquable a => a -> Word32 hash_unique = cvt . getKey . getUnique -- | Ignore these node types for equality
2,282
hash_block :: CmmBlock -> HashCode hash_block block = fromIntegral (foldBlockNodesB3 (hash_fst, hash_mid, hash_lst) block (0 :: Word32) .&. (0x7fffffff :: Word32)) -- UniqFM doesn't like negative Ints where hash_fst _ h = h hash_mid m h = hash_node m + h `shiftL` 1 hash_lst m h = hash_node m + h `shiftL` 1 hash_node :: CmmNode O x -> Word32 hash_node n | dont_care n = 0 -- don't care hash_node (CmmUnwind _ e) = hash_e e hash_node (CmmAssign r e) = hash_reg r + hash_e e hash_node (CmmStore e e') = hash_e e + hash_e e' hash_node (CmmUnsafeForeignCall t _ as) = hash_tgt t + hash_list hash_e as hash_node (CmmBranch _) = 23 -- NB. ignore the label hash_node (CmmCondBranch p _ _ _) = hash_e p hash_node (CmmCall e _ _ _ _ _) = hash_e e hash_node (CmmForeignCall t _ _ _ _ _ _) = hash_tgt t hash_node (CmmSwitch e _) = hash_e e hash_node _ = error "hash_node: unknown Cmm node!" hash_reg :: CmmReg -> Word32 hash_reg (CmmLocal localReg) = hash_unique localReg -- important for performance, see #10397 hash_reg (CmmGlobal _) = 19 hash_e :: CmmExpr -> Word32 hash_e (CmmLit l) = hash_lit l hash_e (CmmLoad e _) = 67 + hash_e e hash_e (CmmReg r) = hash_reg r hash_e (CmmMachOp _ es) = hash_list hash_e es -- pessimal - no operator check hash_e (CmmRegOff r i) = hash_reg r + cvt i hash_e (CmmStackSlot _ _) = 13 hash_lit :: CmmLit -> Word32 hash_lit (CmmInt i _) = fromInteger i hash_lit (CmmFloat r _) = truncate r hash_lit (CmmVec ls) = hash_list hash_lit ls hash_lit (CmmLabel _) = 119 -- ugh hash_lit (CmmLabelOff _ i) = cvt $ 199 + i hash_lit (CmmLabelDiffOff _ _ i) = cvt $ 299 + i hash_lit (CmmBlock _) = 191 -- ugh hash_lit (CmmHighStackMark) = cvt 313 hash_tgt (ForeignTarget e _) = hash_e e hash_tgt (PrimTarget _) = 31 -- lots of these hash_list f = foldl (\z x -> f x + z) (0::Word32) cvt = fromInteger . toInteger hash_unique :: Uniquable a => a -> Word32 hash_unique = cvt . getKey . getUnique -- | Ignore these node types for equality
2,282
hash_block block = fromIntegral (foldBlockNodesB3 (hash_fst, hash_mid, hash_lst) block (0 :: Word32) .&. (0x7fffffff :: Word32)) -- UniqFM doesn't like negative Ints where hash_fst _ h = h hash_mid m h = hash_node m + h `shiftL` 1 hash_lst m h = hash_node m + h `shiftL` 1 hash_node :: CmmNode O x -> Word32 hash_node n | dont_care n = 0 -- don't care hash_node (CmmUnwind _ e) = hash_e e hash_node (CmmAssign r e) = hash_reg r + hash_e e hash_node (CmmStore e e') = hash_e e + hash_e e' hash_node (CmmUnsafeForeignCall t _ as) = hash_tgt t + hash_list hash_e as hash_node (CmmBranch _) = 23 -- NB. ignore the label hash_node (CmmCondBranch p _ _ _) = hash_e p hash_node (CmmCall e _ _ _ _ _) = hash_e e hash_node (CmmForeignCall t _ _ _ _ _ _) = hash_tgt t hash_node (CmmSwitch e _) = hash_e e hash_node _ = error "hash_node: unknown Cmm node!" hash_reg :: CmmReg -> Word32 hash_reg (CmmLocal localReg) = hash_unique localReg -- important for performance, see #10397 hash_reg (CmmGlobal _) = 19 hash_e :: CmmExpr -> Word32 hash_e (CmmLit l) = hash_lit l hash_e (CmmLoad e _) = 67 + hash_e e hash_e (CmmReg r) = hash_reg r hash_e (CmmMachOp _ es) = hash_list hash_e es -- pessimal - no operator check hash_e (CmmRegOff r i) = hash_reg r + cvt i hash_e (CmmStackSlot _ _) = 13 hash_lit :: CmmLit -> Word32 hash_lit (CmmInt i _) = fromInteger i hash_lit (CmmFloat r _) = truncate r hash_lit (CmmVec ls) = hash_list hash_lit ls hash_lit (CmmLabel _) = 119 -- ugh hash_lit (CmmLabelOff _ i) = cvt $ 199 + i hash_lit (CmmLabelDiffOff _ _ i) = cvt $ 299 + i hash_lit (CmmBlock _) = 191 -- ugh hash_lit (CmmHighStackMark) = cvt 313 hash_tgt (ForeignTarget e _) = hash_e e hash_tgt (PrimTarget _) = 31 -- lots of these hash_list f = foldl (\z x -> f x + z) (0::Word32) cvt = fromInteger . toInteger hash_unique :: Uniquable a => a -> Word32 hash_unique = cvt . getKey . getUnique -- | Ignore these node types for equality
2,247
false
true
66
11
699
796
405
391
null
null
markflorisson/hpack
testrepo/bytestring-0.10.2.0/Data/ByteString/Lazy.hs
bsd-3-clause
-- | 'foldl1' is a variant of 'foldl' that has no starting value -- argument, and thus must be applied to non-empty 'ByteStrings'. -- This function is subject to array fusion. foldl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8 foldl1 _ Empty = errorEmptyList "foldl1"
282
foldl1 :: (Word8 -> Word8 -> Word8) -> ByteString -> Word8 foldl1 _ Empty = errorEmptyList "foldl1"
106
foldl1 _ Empty = errorEmptyList "foldl1"
47
true
true
0
8
54
41
22
19
null
null
geophf/1HaskellADay
exercises/HAD/Y2018/M02/D06/Solution.hs
mit
-- we also need the indices to create the pivot between packets and articles. -- Now, when you store the articles, add the pivot information to the database -- see storeArticles -- note-to-self: CREATE TABLE article_packet ... insertPacketArtPvtStmt :: Query insertPacketArtPvtStmt = [sql|INSERT INTO article_packet (article_id,packet_id) VALUES (?,?)|]
360
insertPacketArtPvtStmt :: Query insertPacketArtPvtStmt = [sql|INSERT INTO article_packet (article_id,packet_id) VALUES (?,?)|]
129
insertPacketArtPvtStmt = [sql|INSERT INTO article_packet (article_id,packet_id) VALUES (?,?)|]
97
true
true
0
4
54
19
14
5
null
null
ezyang/ghc
compiler/types/Type.hs
bsd-3-clause
-- | Attempts to tease a list type apart and gives the type of the elements if -- successful (looks through type synonyms) splitListTyConApp_maybe :: Type -> Maybe Type splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of Just (tc,[e]) | tc == listTyCon -> Just e _other -> Nothing -- | What is the role assigned to the next parameter of this type? Usually, -- this will be 'Nominal', but if the type is a 'TyConApp', we may be able to -- do better. The type does *not* have to be well-kinded when applied for this -- to work!
563
splitListTyConApp_maybe :: Type -> Maybe Type splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of Just (tc,[e]) | tc == listTyCon -> Just e _other -> Nothing -- | What is the role assigned to the next parameter of this type? Usually, -- this will be 'Nominal', but if the type is a 'TyConApp', we may be able to -- do better. The type does *not* have to be well-kinded when applied for this -- to work!
440
splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of Just (tc,[e]) | tc == listTyCon -> Just e _other -> Nothing -- | What is the role assigned to the next parameter of this type? Usually, -- this will be 'Nominal', but if the type is a 'TyConApp', we may be able to -- do better. The type does *not* have to be well-kinded when applied for this -- to work!
394
true
true
0
11
127
71
37
34
null
null
pierric/neural-network
Backend-blashs/Test/Utils.hs
bsd-3-clause
ratio a b = let va = flatten a vb = flatten b ae :: V.Vector Float ae = V.zipWith (\a b -> abs (a - b)) va vb aa = V.sum ae / fromIntegral (V.length ae) err x 0 = x < 0.1 err x y = let e = x-y in (abs (e / y) < 0.02) in V.zipWith err va vb
295
ratio a b = let va = flatten a vb = flatten b ae :: V.Vector Float ae = V.zipWith (\a b -> abs (a - b)) va vb aa = V.sum ae / fromIntegral (V.length ae) err x 0 = x < 0.1 err x y = let e = x-y in (abs (e / y) < 0.02) in V.zipWith err va vb
295
ratio a b = let va = flatten a vb = flatten b ae :: V.Vector Float ae = V.zipWith (\a b -> abs (a - b)) va vb aa = V.sum ae / fromIntegral (V.length ae) err x 0 = x < 0.1 err x y = let e = x-y in (abs (e / y) < 0.02) in V.zipWith err va vb
295
false
false
1
15
119
174
82
92
null
null
urv/fixhs
src/Data/FIX/Spec/FIX43.hs
lgpl-2.1
tMidYield :: FIXTag tMidYield = FIXTag { tName = "MidYield" , tnum = 633 , tparser = toFIXDouble , arbitraryValue = FIXDouble <$> (return (-2.112 :: Double)) }
172
tMidYield :: FIXTag tMidYield = FIXTag { tName = "MidYield" , tnum = 633 , tparser = toFIXDouble , arbitraryValue = FIXDouble <$> (return (-2.112 :: Double)) }
172
tMidYield = FIXTag { tName = "MidYield" , tnum = 633 , tparser = toFIXDouble , arbitraryValue = FIXDouble <$> (return (-2.112 :: Double)) }
152
false
true
0
12
40
59
34
25
null
null
b0d0nne11/hauth
src/Models/User.hs
apache-2.0
findUserByName :: Key Account -- ^ Account ID -> T.Text -- ^ User name -> AppHandler (Entity User) -- ^ Returns a user findUserByName accountId name = do users <- runPersist $ select $ from $ \u -> do where_ $ u ^. UserAccountId ==. val accountId &&. u ^. UserName ==. val name return u case users of [u] -> return u _ -> notFound $ printf "user not found: account_id=%v user_name=%v" accountId name -- | Get a list of users
564
findUserByName :: Key Account -- ^ Account ID -> T.Text -- ^ User name -> AppHandler (Entity User) findUserByName accountId name = do users <- runPersist $ select $ from $ \u -> do where_ $ u ^. UserAccountId ==. val accountId &&. u ^. UserName ==. val name return u case users of [u] -> return u _ -> notFound $ printf "user not found: account_id=%v user_name=%v" accountId name -- | Get a list of users
544
findUserByName accountId name = do users <- runPersist $ select $ from $ \u -> do where_ $ u ^. UserAccountId ==. val accountId &&. u ^. UserName ==. val name return u case users of [u] -> return u _ -> notFound $ printf "user not found: account_id=%v user_name=%v" accountId name -- | Get a list of users
384
true
true
0
18
221
146
69
77
null
null
sdiehl/ghc
compiler/GHC/Cmm/CLabel.hs
bsd-3-clause
toSlowEntryLbl :: CLabel -> CLabel toSlowEntryLbl (IdLabel n _ BlockInfoTable) = pprPanic "toSlowEntryLbl" (ppr n)
116
toSlowEntryLbl :: CLabel -> CLabel toSlowEntryLbl (IdLabel n _ BlockInfoTable) = pprPanic "toSlowEntryLbl" (ppr n)
116
toSlowEntryLbl (IdLabel n _ BlockInfoTable) = pprPanic "toSlowEntryLbl" (ppr n)
81
false
true
0
7
16
39
19
20
null
null
Zoetermeer/latro
src/Latro/ILGen.hs
mit
ilGen (ExpGetAdtField p e i) = do e' <- ilGen e return $ ILGetAdtField p e' i
81
ilGen (ExpGetAdtField p e i) = do e' <- ilGen e return $ ILGetAdtField p e' i
81
ilGen (ExpGetAdtField p e i) = do e' <- ilGen e return $ ILGetAdtField p e' i
81
false
false
0
8
20
43
19
24
null
null
ksaveljev/hake-2
src/Render/ModelT.hs
bsd-3-clause
newModelT :: ModelT newModelT = ModelT { _mName = "" , _mRegistrationSequence = 0 , _mType = 0 , _mNumFrames = 0 , _mFlags = 0 , _mMins = V3 0 0 0 , _mMaxs = V3 0 0 0 , _mRadius = 0 , _mClipBox = False , _mClipMins = V3 0 0 0 , _mClipMaxs = V3 0 0 0 , _mFirstModelSurface = 0 , _mNumModelSurfaces = 0 , _mLightmap = 0 , _mNumSubModels = 0 , _mSubModels = V.empty , _mNumPlanes = 0 , _mPlanes = V.empty , _mNumLeafs = 0 , _mLeafs = V.empty , _mNumVertexes = 0 , _mVertexes = V.empty , _mNumEdges = 0 , _mEdges = V.empty , _mNumNodes = 0 , _mFirstNode = 0 , _mNodes = V.empty , _mNumTexInfo = 0 , _mTexInfo = V.empty , _mNumSurfaces = 0 , _mSurfaces = V.empty , _mNumSurfEdges = 0 , _mSurfEdges = V.empty , _mNumMarkSurfaces = 0 , _mMarkSurfaces = V.empty , _mVis = Nothing , _mLightdata = Nothing , _mSkins = V.empty , _mExtraDataSize = 0 , _mExtraData = Nothing }
1,679
newModelT :: ModelT newModelT = ModelT { _mName = "" , _mRegistrationSequence = 0 , _mType = 0 , _mNumFrames = 0 , _mFlags = 0 , _mMins = V3 0 0 0 , _mMaxs = V3 0 0 0 , _mRadius = 0 , _mClipBox = False , _mClipMins = V3 0 0 0 , _mClipMaxs = V3 0 0 0 , _mFirstModelSurface = 0 , _mNumModelSurfaces = 0 , _mLightmap = 0 , _mNumSubModels = 0 , _mSubModels = V.empty , _mNumPlanes = 0 , _mPlanes = V.empty , _mNumLeafs = 0 , _mLeafs = V.empty , _mNumVertexes = 0 , _mVertexes = V.empty , _mNumEdges = 0 , _mEdges = V.empty , _mNumNodes = 0 , _mFirstNode = 0 , _mNodes = V.empty , _mNumTexInfo = 0 , _mTexInfo = V.empty , _mNumSurfaces = 0 , _mSurfaces = V.empty , _mNumSurfEdges = 0 , _mSurfEdges = V.empty , _mNumMarkSurfaces = 0 , _mMarkSurfaces = V.empty , _mVis = Nothing , _mLightdata = Nothing , _mSkins = V.empty , _mExtraDataSize = 0 , _mExtraData = Nothing }
1,679
newModelT = ModelT { _mName = "" , _mRegistrationSequence = 0 , _mType = 0 , _mNumFrames = 0 , _mFlags = 0 , _mMins = V3 0 0 0 , _mMaxs = V3 0 0 0 , _mRadius = 0 , _mClipBox = False , _mClipMins = V3 0 0 0 , _mClipMaxs = V3 0 0 0 , _mFirstModelSurface = 0 , _mNumModelSurfaces = 0 , _mLightmap = 0 , _mNumSubModels = 0 , _mSubModels = V.empty , _mNumPlanes = 0 , _mPlanes = V.empty , _mNumLeafs = 0 , _mLeafs = V.empty , _mNumVertexes = 0 , _mVertexes = V.empty , _mNumEdges = 0 , _mEdges = V.empty , _mNumNodes = 0 , _mFirstNode = 0 , _mNodes = V.empty , _mNumTexInfo = 0 , _mTexInfo = V.empty , _mNumSurfaces = 0 , _mSurfaces = V.empty , _mNumSurfEdges = 0 , _mSurfEdges = V.empty , _mNumMarkSurfaces = 0 , _mMarkSurfaces = V.empty , _mVis = Nothing , _mLightdata = Nothing , _mSkins = V.empty , _mExtraDataSize = 0 , _mExtraData = Nothing }
1,659
false
true
0
7
994
303
190
113
null
null
brendanhay/gogol
gogol-videointelligence/gen/Network/Google/VideoIntelligence/Types/Product.hs
mpl-2.0
-- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gCategoryEntities' -- -- * 'gFrames' -- -- * 'gVersion' -- -- * 'gSegments' -- -- * 'gEntity' googleCloudVideointelligenceV1p3beta1_LabelAnnotation :: GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation googleCloudVideointelligenceV1p3beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation' { _gCategoryEntities = Nothing , _gFrames = Nothing , _gVersion = Nothing , _gSegments = Nothing , _gEntity = Nothing }
679
googleCloudVideointelligenceV1p3beta1_LabelAnnotation :: GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation googleCloudVideointelligenceV1p3beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation' { _gCategoryEntities = Nothing , _gFrames = Nothing , _gVersion = Nothing , _gSegments = Nothing , _gEntity = Nothing }
371
googleCloudVideointelligenceV1p3beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation' { _gCategoryEntities = Nothing , _gFrames = Nothing , _gVersion = Nothing , _gSegments = Nothing , _gEntity = Nothing }
256
true
true
0
6
106
56
40
16
null
null
keithodulaigh/Hets
CspCASL/Parse_CspCASL_Process.hs
gpl-2.0
chanComm :: AParser st EVENT chanComm = do (cn, sr) <- try $ pair channel_name $ asKeySign chan_sendS <|> asKeySign chan_receiveS if tokStr sr == chan_sendS then do -- a double colon makes the difference to a CASL term v <- try $ var << asKeySign svar_sortS s <- cspSortId return (ChanNonDetSend cn v s (compRange cn s)) <|> do t <- CASL.term cspKeywords return (ChanSend cn t (getRange cn)) else do v <- var << svarKey s <- cspSortId return (ChanRecv cn v s (compRange cn s))
586
chanComm :: AParser st EVENT chanComm = do (cn, sr) <- try $ pair channel_name $ asKeySign chan_sendS <|> asKeySign chan_receiveS if tokStr sr == chan_sendS then do -- a double colon makes the difference to a CASL term v <- try $ var << asKeySign svar_sortS s <- cspSortId return (ChanNonDetSend cn v s (compRange cn s)) <|> do t <- CASL.term cspKeywords return (ChanSend cn t (getRange cn)) else do v <- var << svarKey s <- cspSortId return (ChanRecv cn v s (compRange cn s))
586
chanComm = do (cn, sr) <- try $ pair channel_name $ asKeySign chan_sendS <|> asKeySign chan_receiveS if tokStr sr == chan_sendS then do -- a double colon makes the difference to a CASL term v <- try $ var << asKeySign svar_sortS s <- cspSortId return (ChanNonDetSend cn v s (compRange cn s)) <|> do t <- CASL.term cspKeywords return (ChanSend cn t (getRange cn)) else do v <- var << svarKey s <- cspSortId return (ChanRecv cn v s (compRange cn s))
557
false
true
0
15
197
202
94
108
null
null
Raynes/haskheap
src/Network/Haskheap.hs
mit
-- | Decode a paste to either a Maybe Error or a Paste. It works by first -- trying to decode the JSON as a Paste and if that fails, it tries to decode -- it as an Error. decodePaste :: B.ByteString -> Either Error Success decodePaste s = case decode s of (Just x) -> Right x Nothing -> case decode s of (Just x) -> Left x Nothing -> case toList (decode s :: Maybe Value) of Just [("content", String x)] -> Right $ Line $ T.unpack x _ -> Right Empty -- | Get a paste from refheap. Will return IO Nothing if the paste doesn't exist.
599
decodePaste :: B.ByteString -> Either Error Success decodePaste s = case decode s of (Just x) -> Right x Nothing -> case decode s of (Just x) -> Left x Nothing -> case toList (decode s :: Maybe Value) of Just [("content", String x)] -> Right $ Line $ T.unpack x _ -> Right Empty -- | Get a paste from refheap. Will return IO Nothing if the paste doesn't exist.
428
decodePaste s = case decode s of (Just x) -> Right x Nothing -> case decode s of (Just x) -> Left x Nothing -> case toList (decode s :: Maybe Value) of Just [("content", String x)] -> Right $ Line $ T.unpack x _ -> Right Empty -- | Get a paste from refheap. Will return IO Nothing if the paste doesn't exist.
376
true
true
0
17
177
147
72
75
null
null
DavidAlphaFox/ghc
compiler/basicTypes/Id.hs
bsd-3-clause
mkLocalIdWithInfo :: Name -> Type -> IdInfo -> Id mkLocalIdWithInfo name ty info = Var.mkLocalVar VanillaId name ty info
120
mkLocalIdWithInfo :: Name -> Type -> IdInfo -> Id mkLocalIdWithInfo name ty info = Var.mkLocalVar VanillaId name ty info
120
mkLocalIdWithInfo name ty info = Var.mkLocalVar VanillaId name ty info
70
false
true
0
7
18
41
20
21
null
null
tjakway/ghcjvm
compiler/coreSyn/TrieMap.hs
bsd-3-clause
mapList :: TrieMap m => (a->b) -> ListMap m a -> ListMap m b mapList f (LM { lm_nil = mnil, lm_cons = mcons }) = LM { lm_nil = fmap f mnil, lm_cons = mapTM (mapTM f) mcons }
175
mapList :: TrieMap m => (a->b) -> ListMap m a -> ListMap m b mapList f (LM { lm_nil = mnil, lm_cons = mcons }) = LM { lm_nil = fmap f mnil, lm_cons = mapTM (mapTM f) mcons }
175
mapList f (LM { lm_nil = mnil, lm_cons = mcons }) = LM { lm_nil = fmap f mnil, lm_cons = mapTM (mapTM f) mcons }
114
false
true
0
10
41
105
52
53
null
null
GaloisInc/hacrypto
calf/bin/Main.hs
bsd-3-clause
writeFile' = (reifyIOException "Couldn't open" .) . writeFile
61
writeFile' = (reifyIOException "Couldn't open" .) . writeFile
61
writeFile' = (reifyIOException "Couldn't open" .) . writeFile
61
false
false
0
7
7
17
9
8
null
null
fumieval/prelude-kai
src/Prelude/Kai.hs
bsd-3-clause
replicateA :: Applicative f => Int -> f a -> f [a] replicateA m f = go m where go 0 = pure [] go n = liftA2 (:) f (go (n - 1))
135
replicateA :: Applicative f => Int -> f a -> f [a] replicateA m f = go m where go 0 = pure [] go n = liftA2 (:) f (go (n - 1))
135
replicateA m f = go m where go 0 = pure [] go n = liftA2 (:) f (go (n - 1))
84
false
true
0
9
42
87
43
44
null
null
lucasbraun/mt-rewrite
src/MtRewriteSelect.hs
bsd-3-clause
consolidateSelectItems (Pa.SelectItem ann (Pa.BinaryOp a0 opName (Pa.Identifier i a) exp) (Pa.Nmc n):items) prov = -- re-use the consolidateSelectItems of Identifier... we know that right part is constant in tpch (Q7/Q8) let (p, (Pa.SelExp _ item:others)) = consolidateSelectItems (Pa.SelExp ann (Pa.Identifier i a):items) prov (provItems, _) = getProvenanceItem (Pa.Identifier i a) p consolidate [provItem] = addToProvenance n provItem p consolidate _ = p in (consolidate provItems, Pa.SelectItem ann (Pa.BinaryOp a0 opName item exp) (Pa.Nmc n):others)
619
consolidateSelectItems (Pa.SelectItem ann (Pa.BinaryOp a0 opName (Pa.Identifier i a) exp) (Pa.Nmc n):items) prov = -- re-use the consolidateSelectItems of Identifier... we know that right part is constant in tpch (Q7/Q8) let (p, (Pa.SelExp _ item:others)) = consolidateSelectItems (Pa.SelExp ann (Pa.Identifier i a):items) prov (provItems, _) = getProvenanceItem (Pa.Identifier i a) p consolidate [provItem] = addToProvenance n provItem p consolidate _ = p in (consolidate provItems, Pa.SelectItem ann (Pa.BinaryOp a0 opName item exp) (Pa.Nmc n):others)
619
consolidateSelectItems (Pa.SelectItem ann (Pa.BinaryOp a0 opName (Pa.Identifier i a) exp) (Pa.Nmc n):items) prov = -- re-use the consolidateSelectItems of Identifier... we know that right part is constant in tpch (Q7/Q8) let (p, (Pa.SelExp _ item:others)) = consolidateSelectItems (Pa.SelExp ann (Pa.Identifier i a):items) prov (provItems, _) = getProvenanceItem (Pa.Identifier i a) p consolidate [provItem] = addToProvenance n provItem p consolidate _ = p in (consolidate provItems, Pa.SelectItem ann (Pa.BinaryOp a0 opName item exp) (Pa.Nmc n):others)
619
false
false
0
15
139
218
109
109
null
null
h8gi/Open-usp-Tukubai
COMMANDS.HS/marume.hs
mit
cutFrac _ (n,[]) = read n
30
cutFrac _ (n,[]) = read n
30
cutFrac _ (n,[]) = read n
30
false
false
1
6
10
24
11
13
null
null
Concomitant/LambdaHack
Game/LambdaHack/Client/Key.hs
bsd-3-clause
pgupKM :: KM pgupKM = toKM NoModifier PgUp
42
pgupKM :: KM pgupKM = toKM NoModifier PgUp
42
pgupKM = toKM NoModifier PgUp
29
false
true
0
5
7
16
8
8
null
null
Numberartificial/workflow
snipets/src/Craft/Chapter8.hs
mit
convertMove 'P' = Paper
23
convertMove 'P' = Paper
23
convertMove 'P' = Paper
23
false
false
0
5
3
9
4
5
null
null
mietek/mighttpd2
Program/Mighty/ByteString.hs
bsd-3-clause
-- | Appending two 'ByteString'. (+++) :: ByteString -> ByteString -> ByteString (+++) = BS.append
98
(+++) :: ByteString -> ByteString -> ByteString (+++) = BS.append
65
(+++) = BS.append
17
true
true
0
6
14
26
16
10
null
null
Hodapp87/ivory
ivory-eval/src/Ivory/Eval.hs
bsd-3-clause
numUnOp op (Uint32 x) = Uint32 (op x)
37
numUnOp op (Uint32 x) = Uint32 (op x)
37
numUnOp op (Uint32 x) = Uint32 (op x)
37
false
false
0
7
7
26
12
14
null
null
davedissian/hackcambridge2016
ParserC.hs
mit
errloc (PErrIndent l) = Just l
30
errloc (PErrIndent l) = Just l
30
errloc (PErrIndent l) = Just l
30
false
false
0
7
5
18
8
10
null
null
gcampax/ghc
compiler/typecheck/TcGenDeriv.hs
bsd-3-clause
-- | showsPrec :: Show a => Int -> a -> ShowS mk_showsPrec_app :: Integer -> LHsExpr RdrName -> LHsExpr RdrName mk_showsPrec_app p x = nlHsApps showsPrec_RDR [nlHsLit (HsInt "" p), x]
183
mk_showsPrec_app :: Integer -> LHsExpr RdrName -> LHsExpr RdrName mk_showsPrec_app p x = nlHsApps showsPrec_RDR [nlHsLit (HsInt "" p), x]
137
mk_showsPrec_app p x = nlHsApps showsPrec_RDR [nlHsLit (HsInt "" p), x]
71
true
true
0
9
31
53
26
27
null
null
iand675/Zoom
Zoom/Task/Demo.hs
bsd-3-clause
demo :: Retrieve s => Task s demo = simpleTask { desc = "Prints out the string, \"This is a demo!\"" , task = flexDemo }
157
demo :: Retrieve s => Task s demo = simpleTask { desc = "Prints out the string, \"This is a demo!\"" , task = flexDemo }
157
demo = simpleTask { desc = "Prints out the string, \"This is a demo!\"" , task = flexDemo }
128
false
true
0
6
62
35
19
16
null
null
allanderek/ipclib
Language/Pepa/Probes/Syntax.hs
gpl-2.0
containsNeedlessRep (SPcond _c r) = containsNeedlessRep r
68
containsNeedlessRep (SPcond _c r) = containsNeedlessRep r
68
containsNeedlessRep (SPcond _c r) = containsNeedlessRep r
68
false
false
0
6
17
21
9
12
null
null
ghcjs/jsaddle-dom
src/JSDOM/Generated/AnalyserNode.hs
mit
-- | <https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode.smoothingTimeConstant Mozilla AnalyserNode.smoothingTimeConstant documentation> setSmoothingTimeConstant :: (MonadDOM m) => AnalyserNode -> Double -> m () setSmoothingTimeConstant self val = liftDOM (self ^. jss "smoothingTimeConstant" (toJSVal val))
346
setSmoothingTimeConstant :: (MonadDOM m) => AnalyserNode -> Double -> m () setSmoothingTimeConstant self val = liftDOM (self ^. jss "smoothingTimeConstant" (toJSVal val))
197
setSmoothingTimeConstant self val = liftDOM (self ^. jss "smoothingTimeConstant" (toJSVal val))
97
true
true
0
10
55
60
30
30
null
null
JakeWheat/Chaos-2010
Games/Chaos2010/Database/Fields.hs
bsd-3-clause
align_icons :: Align_icons align_icons = proxy
46
align_icons :: Align_icons align_icons = proxy
46
align_icons = proxy
19
false
true
0
4
5
11
6
5
null
null
jonsterling/singletons
Data/Singletons/Singletons.hs
bsd-3-clause
singInstanceTyCon :: Type singInstanceTyCon = ConT singInstanceName
67
singInstanceTyCon :: Type singInstanceTyCon = ConT singInstanceName
67
singInstanceTyCon = ConT singInstanceName
41
false
true
0
6
6
21
8
13
null
null
facebookincubator/duckling
Duckling/Time/ES/Rules.hs
bsd-3-clause
ruleHourofdayMinusHalf :: Rule ruleHourofdayMinusHalf = Rule { name = "<hour-of-day> minus half (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , regex "menos\\s? media" ] , prod = \tokens -> case tokens of (Token Time td:_) -> Token Time <$> minutesBefore 30 td _ -> Nothing }
322
ruleHourofdayMinusHalf :: Rule ruleHourofdayMinusHalf = Rule { name = "<hour-of-day> minus half (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , regex "menos\\s? media" ] , prod = \tokens -> case tokens of (Token Time td:_) -> Token Time <$> minutesBefore 30 td _ -> Nothing }
322
ruleHourofdayMinusHalf = Rule { name = "<hour-of-day> minus half (as relative minutes)" , pattern = [ Predicate isAnHourOfDay , regex "menos\\s? media" ] , prod = \tokens -> case tokens of (Token Time td:_) -> Token Time <$> minutesBefore 30 td _ -> Nothing }
291
false
true
0
14
79
92
48
44
null
null
ganeti-github-testing/ganeti-test-1
test/hs/Test/Ganeti/HTools/Container.hs
bsd-2-clause
prop_findByName :: Property prop_findByName = forAll (genNode (Just 1) Nothing) $ \node -> forAll (choose (1, 20)) $ \ cnt -> forAll (choose (0, cnt - 1)) $ \ fidx -> forAll (genUniquesList (cnt * 2) arbitrary) $ \ allnames -> forAll (arbitrary `suchThat` (`notElem` allnames)) $ \ othername -> let names = zip (take cnt allnames) (drop cnt allnames) nl = makeSmallCluster node cnt nodes = Container.elems nl nodes' = map (\((name, alias), nn) -> (Node.idx nn, nn { Node.name = name, Node.alias = alias })) $ zip names nodes nl' = Container.fromList nodes' target = snd (nodes' !! fidx) in conjoin [ Container.findByName nl' (Node.name target) ==? Just target , Container.findByName nl' (Node.alias target) ==? Just target , printTestCase "Found non-existing name" (isNothing (Container.findByName nl' othername)) ]
1,006
prop_findByName :: Property prop_findByName = forAll (genNode (Just 1) Nothing) $ \node -> forAll (choose (1, 20)) $ \ cnt -> forAll (choose (0, cnt - 1)) $ \ fidx -> forAll (genUniquesList (cnt * 2) arbitrary) $ \ allnames -> forAll (arbitrary `suchThat` (`notElem` allnames)) $ \ othername -> let names = zip (take cnt allnames) (drop cnt allnames) nl = makeSmallCluster node cnt nodes = Container.elems nl nodes' = map (\((name, alias), nn) -> (Node.idx nn, nn { Node.name = name, Node.alias = alias })) $ zip names nodes nl' = Container.fromList nodes' target = snd (nodes' !! fidx) in conjoin [ Container.findByName nl' (Node.name target) ==? Just target , Container.findByName nl' (Node.alias target) ==? Just target , printTestCase "Found non-existing name" (isNothing (Container.findByName nl' othername)) ]
1,006
prop_findByName = forAll (genNode (Just 1) Nothing) $ \node -> forAll (choose (1, 20)) $ \ cnt -> forAll (choose (0, cnt - 1)) $ \ fidx -> forAll (genUniquesList (cnt * 2) arbitrary) $ \ allnames -> forAll (arbitrary `suchThat` (`notElem` allnames)) $ \ othername -> let names = zip (take cnt allnames) (drop cnt allnames) nl = makeSmallCluster node cnt nodes = Container.elems nl nodes' = map (\((name, alias), nn) -> (Node.idx nn, nn { Node.name = name, Node.alias = alias })) $ zip names nodes nl' = Container.fromList nodes' target = snd (nodes' !! fidx) in conjoin [ Container.findByName nl' (Node.name target) ==? Just target , Container.findByName nl' (Node.alias target) ==? Just target , printTestCase "Found non-existing name" (isNothing (Container.findByName nl' othername)) ]
978
false
true
0
25
319
363
191
172
null
null
DaMSL/K3
src/Language/K3/Runtime/Engine.hs
apache-2.0
closeInternal :: String -> EngineM a () closeInternal n = ask >>= genericClose n . internalEndpoints . endpoints
112
closeInternal :: String -> EngineM a () closeInternal n = ask >>= genericClose n . internalEndpoints . endpoints
112
closeInternal n = ask >>= genericClose n . internalEndpoints . endpoints
72
false
true
0
8
17
40
19
21
null
null
facebookincubator/duckling
Duckling/AmountOfMoney/RU/Rules.hs
bsd-3-clause
ruleIntervalMax :: Rule ruleIntervalMax = Rule { name = "under/less/lower/no more than <amount-of-money>" , pattern = [ regex "под|((менее|меньше|ниже|не больше|не более)( чем)?)" , Predicate isSimpleAmountOfMoney ] , prod = \tokens -> case tokens of (_: Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to, TAmountOfMoney.currency = c}: _) -> Just . Token AmountOfMoney . withMax to $ currencyOnly c _ -> Nothing }
496
ruleIntervalMax :: Rule ruleIntervalMax = Rule { name = "under/less/lower/no more than <amount-of-money>" , pattern = [ regex "под|((менее|меньше|ниже|не больше|не более)( чем)?)" , Predicate isSimpleAmountOfMoney ] , prod = \tokens -> case tokens of (_: Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to, TAmountOfMoney.currency = c}: _) -> Just . Token AmountOfMoney . withMax to $ currencyOnly c _ -> Nothing }
496
ruleIntervalMax = Rule { name = "under/less/lower/no more than <amount-of-money>" , pattern = [ regex "под|((менее|меньше|ниже|не больше|не более)( чем)?)" , Predicate isSimpleAmountOfMoney ] , prod = \tokens -> case tokens of (_: Token AmountOfMoney AmountOfMoneyData{TAmountOfMoney.value = Just to, TAmountOfMoney.currency = c}: _) -> Just . Token AmountOfMoney . withMax to $ currencyOnly c _ -> Nothing }
472
false
true
0
19
123
133
67
66
null
null
karamellpelle/MEnv
source/File/Binary/Reader.hs
bsd-2-clause
rAlign :: UInt -> Reader () rAlign n = rOffset >>= \off -> do replicateM_ (fI $ (n - off `mod` n) `mod` n) rAnyWord8 return () -------------------------------------------------------------------------------- -- -- | little endian -> platform endian
274
rAlign :: UInt -> Reader () rAlign n = rOffset >>= \off -> do replicateM_ (fI $ (n - off `mod` n) `mod` n) rAnyWord8 return () -------------------------------------------------------------------------------- -- -- | little endian -> platform endian
274
rAlign n = rOffset >>= \off -> do replicateM_ (fI $ (n - off `mod` n) `mod` n) rAnyWord8 return () -------------------------------------------------------------------------------- -- -- | little endian -> platform endian
246
false
true
0
15
61
77
41
36
null
null
aostiles/LiveHaskell
src/IHaskell/Eval/Hoogle.hs
mit
renderPlain (DocResult resp) = printf "%s\nURL: %s\n%s" (self resp) (location resp) (docs resp)
103
renderPlain (DocResult resp) = printf "%s\nURL: %s\n%s" (self resp) (location resp) (docs resp)
103
renderPlain (DocResult resp) = printf "%s\nURL: %s\n%s" (self resp) (location resp) (docs resp)
103
false
false
0
6
20
46
20
26
null
null
luisgepeto/HaskellLearning
08 Own Types/04_derived_instances.hs
mit
--bounded interface properties demo21 = minBound :: Day
55
demo21 = minBound :: Day
24
demo21 = minBound :: Day
24
true
false
1
4
7
12
6
6
null
null
michaelt/pipes-network-tcp-examples
Examples/ServePipes.hs
bsd-3-clause
main :: IO () main = serve (Host "127.0.0.1") "4000" $ \(client,_) -> runEffect $ fromSocket client 4096 >-> Bytes.map toUpper >-> toSocket client
192
main :: IO () main = serve (Host "127.0.0.1") "4000" $ \(client,_) -> runEffect $ fromSocket client 4096 >-> Bytes.map toUpper >-> toSocket client
192
main = serve (Host "127.0.0.1") "4000" $ \(client,_) -> runEffect $ fromSocket client 4096 >-> Bytes.map toUpper >-> toSocket client
178
false
true
1
10
69
70
33
37
null
null
esmolanka/haddock
haddock-api/src/Haddock/Utils.hs
bsd-2-clause
markup m (DocOrderedList ds) = markupOrderedList m (map (markup m) ds)
78
markup m (DocOrderedList ds) = markupOrderedList m (map (markup m) ds)
78
markup m (DocOrderedList ds) = markupOrderedList m (map (markup m) ds)
78
false
false
0
9
18
36
17
19
null
null
josefs/MiniDSL
Feldspar/Frontend.hs
bsd-3-clause
_ <*> _ = Nothing
29
_ <*> _ = Nothing
29
_ <*> _ = Nothing
29
false
false
0
5
16
12
5
7
null
null
fmapfmapfmap/amazonka
amazonka-iam/gen/Network/AWS/IAM/UpdateOpenIdConnectProviderThumbprint.hs
mpl-2.0
-- | Creates a value of 'UpdateOpenIdConnectProviderThumbprintResponse' with the minimum fields required to make a request. -- updateOpenIdConnectProviderThumbprintResponse :: UpdateOpenIdConnectProviderThumbprintResponse updateOpenIdConnectProviderThumbprintResponse = UpdateOpenIdConnectProviderThumbprintResponse'
324
updateOpenIdConnectProviderThumbprintResponse :: UpdateOpenIdConnectProviderThumbprintResponse updateOpenIdConnectProviderThumbprintResponse = UpdateOpenIdConnectProviderThumbprintResponse'
197
updateOpenIdConnectProviderThumbprintResponse = UpdateOpenIdConnectProviderThumbprintResponse'
98
true
true
1
5
30
17
8
9
null
null
cheme/nanomsg-hs
System/NanoMsg.hs
mit
-- | Same as 'withSocket' but for raw socket. -- Throws NanoError withXSocket :: HasRawSocket a => a -> (Socket a -> IO b) -> IO b withXSocket t r = bracket (xsocket t) close r
176
withXSocket :: HasRawSocket a => a -> (Socket a -> IO b) -> IO b withXSocket t r = bracket (xsocket t) close r
110
withXSocket t r = bracket (xsocket t) close r
45
true
true
0
10
35
62
30
32
null
null
nukisman/elm-format-short
src/ElmFormat/Cli.hs
bsd-3-clause
main :: World m => ElmVersion -> String -> Maybe String -> (String -> Either String a) -> (a -> String) -> [String] -> m () main defaultElmVersion elmFormatVersion experimental parse render args = do let flags = Flags.parse' defaultElmVersion elmFormatVersion experimental args case flags of Right flags -> doIt defaultElmVersion elmFormatVersion experimental parse render flags
427
main :: World m => ElmVersion -> String -> Maybe String -> (String -> Either String a) -> (a -> String) -> [String] -> m () main defaultElmVersion elmFormatVersion experimental parse render args = do let flags = Flags.parse' defaultElmVersion elmFormatVersion experimental args case flags of Right flags -> doIt defaultElmVersion elmFormatVersion experimental parse render flags
427
main defaultElmVersion elmFormatVersion experimental parse render args = do let flags = Flags.parse' defaultElmVersion elmFormatVersion experimental args case flags of Right flags -> doIt defaultElmVersion elmFormatVersion experimental parse render flags
303
false
true
0
14
104
139
65
74
null
null
olsner/ghc
compiler/deSugar/Coverage.hs
bsd-3-clause
addTickHsExpr (HsBinTick t0 t1 e) = liftM (HsBinTick t0 t1) (addTickLHsExprNever e)
91
addTickHsExpr (HsBinTick t0 t1 e) = liftM (HsBinTick t0 t1) (addTickLHsExprNever e)
91
addTickHsExpr (HsBinTick t0 t1 e) = liftM (HsBinTick t0 t1) (addTickLHsExprNever e)
91
false
false
0
7
19
38
18
20
null
null
jstolarek/slicer
lib/Language/Slicer/Eval.hs
gpl-3.0
trace (EWhile e1 e2) = do cond <- trace e1 traceWhile cond e1 e2 -- exceptions
106
trace (EWhile e1 e2) = do cond <- trace e1 traceWhile cond e1 e2 -- exceptions
106
trace (EWhile e1 e2) = do cond <- trace e1 traceWhile cond e1 e2 -- exceptions
106
false
false
0
8
43
39
17
22
null
null
thewoolleyman/haskellbook
11/09/eric/Jammin.hs
unlicense
-- Function application required because sum(map(..)) thing -> sum (map(..) thing) -> sum([..]) -> Int totalJars :: [JamJars] -> Int totalJars = sum . map jars
159
totalJars :: [JamJars] -> Int totalJars = sum . map jars
56
totalJars = sum . map jars
26
true
true
0
6
25
26
14
12
null
null