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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jonsterling/Luitzen | src/Environment.hs | bsd-3-clause | -- | access current source location
getSourceLocation :: MonadReader Env m => m [SourceLocation]
getSourceLocation = asks sourceLocation | 136 | getSourceLocation :: MonadReader Env m => m [SourceLocation]
getSourceLocation = asks sourceLocation | 100 | getSourceLocation = asks sourceLocation | 39 | true | true | 0 | 7 | 17 | 30 | 15 | 15 | null | null |
dudebout/game-theoretic-learning | GTL/Interaction/Learning2.hs | isc | logVar :: Comp w x1 a1 s1 h1 h1' x2 a2 s2 h2 h2' ()
logVar = get >>= (tell . (:[])) | 83 | logVar :: Comp w x1 a1 s1 h1 h1' x2 a2 s2 h2 h2' ()
logVar = get >>= (tell . (:[])) | 83 | logVar = get >>= (tell . (:[])) | 31 | false | true | 0 | 9 | 21 | 55 | 29 | 26 | null | null |
gbataille/pandoc | src/Text/Pandoc/Readers/Txt2Tags.hs | gpl-2.0 | getT2TMeta :: [FilePath] -> FilePath -> IO T2TMeta
getT2TMeta inps out = do
curDate <- formatTime defaultTimeLocale "%F" <$> getZonedTime
let getModTime = fmap (formatTime defaultTimeLocale "%T") .
getModificationTime
curMtime <- case inps of
[] -> formatTime defaultTimeLocale "%T" <$> getZonedTime
_ -> catchIOError
(maximum <$> mapM getModTime inps)
(const (return ""))
return $ T2TMeta curDate curMtime (intercalate ", " inps) out
-- | Read Txt2Tags from an input string returning a Pandoc document | 626 | getT2TMeta :: [FilePath] -> FilePath -> IO T2TMeta
getT2TMeta inps out = do
curDate <- formatTime defaultTimeLocale "%F" <$> getZonedTime
let getModTime = fmap (formatTime defaultTimeLocale "%T") .
getModificationTime
curMtime <- case inps of
[] -> formatTime defaultTimeLocale "%T" <$> getZonedTime
_ -> catchIOError
(maximum <$> mapM getModTime inps)
(const (return ""))
return $ T2TMeta curDate curMtime (intercalate ", " inps) out
-- | Read Txt2Tags from an input string returning a Pandoc document | 626 | getT2TMeta inps out = do
curDate <- formatTime defaultTimeLocale "%F" <$> getZonedTime
let getModTime = fmap (formatTime defaultTimeLocale "%T") .
getModificationTime
curMtime <- case inps of
[] -> formatTime defaultTimeLocale "%T" <$> getZonedTime
_ -> catchIOError
(maximum <$> mapM getModTime inps)
(const (return ""))
return $ T2TMeta curDate curMtime (intercalate ", " inps) out
-- | Read Txt2Tags from an input string returning a Pandoc document | 575 | false | true | 0 | 15 | 197 | 158 | 75 | 83 | null | null |
timsears/species | Math/Combinatorics/Species/Util/Interval.hs | bsd-3-clause | -- | Decrement both endpoints of an interval.
decrI :: Interval -> Interval
decrI (I l h) = I (decr l) (decr h) | 111 | decrI :: Interval -> Interval
decrI (I l h) = I (decr l) (decr h) | 65 | decrI (I l h) = I (decr l) (decr h) | 35 | true | true | 0 | 7 | 22 | 44 | 22 | 22 | null | null |
fpco/hlint | src/HSE/Util.hs | bsd-3-clause | -- XmlPage/XmlHybrid
fromModuleName :: ModuleName S -> String
fromModuleName (ModuleName _ x) = x | 98 | fromModuleName :: ModuleName S -> String
fromModuleName (ModuleName _ x) = x | 76 | fromModuleName (ModuleName _ x) = x | 35 | true | true | 0 | 6 | 14 | 34 | 16 | 18 | null | null |
saffroy/buddhabrot | BBrotRender.hs | bsd-3-clause | render :: BBrotConf -> IO ()
render conf = do
-- Load points of interest, render their orbits into a PNG image.
whenNormal $ putStrLn $ "Loading cache " ++ icachepath conf ++ " ..."
maybePS <- if isComplex conf
then loadPointsComplex $ icachepath conf
else loadPointsJson $ icachepath conf
when (isNothing maybePS) $ do
hPutStrLn stderr $ "failed to parse " ++ icachepath conf
unless (isComplex conf) $
hPutStrLn stderr "try with flag -z"
exitFailure
let psel = pointList $ fromMaybe emptyPS maybePS
selected = map (\(BBPoint x y _) -> x :+ y) psel
orbits = concatMap orbs selected
result = filter inWindow $ if dontRender conf
then selected
else orbits
whenNormal $ putStrLn $ "selected points: " ++ show (length selected)
let xres = xpixels conf
yres = ypixels conf
coords = map (toImgCoords xres yres) result
img <- newArray ((0, 0), (xres - 1, yres - 1)) 0 :: IO (IOUArray (Int, Int) Word32)
mapM_ (plotPix img) coords
whenNormal $ putStrLn "done plotting"
img2 <- freeze img :: IO (UArray (Int, Int) Word32)
let values = elems img2
!v0 = head values
(!total, !smallest, !biggest) = foldl' f (0, v0, v0) values
where f (!x, !y, !z) !a = (a + x, min a y, max a z)
whenNormal $ do
putStrLn $ "img points: " ++ show total
putStrLn $ "value range: " ++ show smallest ++ "-" ++ show biggest
let outfile = fromMaybe defPath (imagepath conf)
where defPath = icachepath conf ++ ".png"
whenNormal $ putStrLn $ "Writing " ++ outfile ++ " ..."
let colorScheme = case palette conf of
Flames -> flames
Gray -> gray
Reddish -> reddish
curveFunc = case curve conf of
Line -> id
Root -> sqrt
Square -> (**2)
pixFunc = toPixel curveFunc smallest biggest colorScheme
renderer i j = pixFunc $ img2!(i,j)
writePng outfile $ generateImage (flip $ renderer) yres xres | 2,030 | render :: BBrotConf -> IO ()
render conf = do
-- Load points of interest, render their orbits into a PNG image.
whenNormal $ putStrLn $ "Loading cache " ++ icachepath conf ++ " ..."
maybePS <- if isComplex conf
then loadPointsComplex $ icachepath conf
else loadPointsJson $ icachepath conf
when (isNothing maybePS) $ do
hPutStrLn stderr $ "failed to parse " ++ icachepath conf
unless (isComplex conf) $
hPutStrLn stderr "try with flag -z"
exitFailure
let psel = pointList $ fromMaybe emptyPS maybePS
selected = map (\(BBPoint x y _) -> x :+ y) psel
orbits = concatMap orbs selected
result = filter inWindow $ if dontRender conf
then selected
else orbits
whenNormal $ putStrLn $ "selected points: " ++ show (length selected)
let xres = xpixels conf
yres = ypixels conf
coords = map (toImgCoords xres yres) result
img <- newArray ((0, 0), (xres - 1, yres - 1)) 0 :: IO (IOUArray (Int, Int) Word32)
mapM_ (plotPix img) coords
whenNormal $ putStrLn "done plotting"
img2 <- freeze img :: IO (UArray (Int, Int) Word32)
let values = elems img2
!v0 = head values
(!total, !smallest, !biggest) = foldl' f (0, v0, v0) values
where f (!x, !y, !z) !a = (a + x, min a y, max a z)
whenNormal $ do
putStrLn $ "img points: " ++ show total
putStrLn $ "value range: " ++ show smallest ++ "-" ++ show biggest
let outfile = fromMaybe defPath (imagepath conf)
where defPath = icachepath conf ++ ".png"
whenNormal $ putStrLn $ "Writing " ++ outfile ++ " ..."
let colorScheme = case palette conf of
Flames -> flames
Gray -> gray
Reddish -> reddish
curveFunc = case curve conf of
Line -> id
Root -> sqrt
Square -> (**2)
pixFunc = toPixel curveFunc smallest biggest colorScheme
renderer i j = pixFunc $ img2!(i,j)
writePng outfile $ generateImage (flip $ renderer) yres xres | 2,030 | render conf = do
-- Load points of interest, render their orbits into a PNG image.
whenNormal $ putStrLn $ "Loading cache " ++ icachepath conf ++ " ..."
maybePS <- if isComplex conf
then loadPointsComplex $ icachepath conf
else loadPointsJson $ icachepath conf
when (isNothing maybePS) $ do
hPutStrLn stderr $ "failed to parse " ++ icachepath conf
unless (isComplex conf) $
hPutStrLn stderr "try with flag -z"
exitFailure
let psel = pointList $ fromMaybe emptyPS maybePS
selected = map (\(BBPoint x y _) -> x :+ y) psel
orbits = concatMap orbs selected
result = filter inWindow $ if dontRender conf
then selected
else orbits
whenNormal $ putStrLn $ "selected points: " ++ show (length selected)
let xres = xpixels conf
yres = ypixels conf
coords = map (toImgCoords xres yres) result
img <- newArray ((0, 0), (xres - 1, yres - 1)) 0 :: IO (IOUArray (Int, Int) Word32)
mapM_ (plotPix img) coords
whenNormal $ putStrLn "done plotting"
img2 <- freeze img :: IO (UArray (Int, Int) Word32)
let values = elems img2
!v0 = head values
(!total, !smallest, !biggest) = foldl' f (0, v0, v0) values
where f (!x, !y, !z) !a = (a + x, min a y, max a z)
whenNormal $ do
putStrLn $ "img points: " ++ show total
putStrLn $ "value range: " ++ show smallest ++ "-" ++ show biggest
let outfile = fromMaybe defPath (imagepath conf)
where defPath = icachepath conf ++ ".png"
whenNormal $ putStrLn $ "Writing " ++ outfile ++ " ..."
let colorScheme = case palette conf of
Flames -> flames
Gray -> gray
Reddish -> reddish
curveFunc = case curve conf of
Line -> id
Root -> sqrt
Square -> (**2)
pixFunc = toPixel curveFunc smallest biggest colorScheme
renderer i j = pixFunc $ img2!(i,j)
writePng outfile $ generateImage (flip $ renderer) yres xres | 2,001 | false | true | 0 | 15 | 595 | 730 | 351 | 379 | null | null |
geophf/1HaskellADay | exercises/HAD/Y2018/M06/D26/Solution.hs | mit | rmDedLinez (h:t) = h:rmDedLinez t | 33 | rmDedLinez (h:t) = h:rmDedLinez t | 33 | rmDedLinez (h:t) = h:rmDedLinez t | 33 | false | false | 2 | 6 | 4 | 27 | 11 | 16 | null | null |
edsko/cabal | Cabal/tests/PackageTests.hs | bsd-3-clause | canonicalizePackageDB :: PackageDB -> IO PackageDB
canonicalizePackageDB (SpecificPackageDB path)
= SpecificPackageDB `fmap` canonicalizePath path | 150 | canonicalizePackageDB :: PackageDB -> IO PackageDB
canonicalizePackageDB (SpecificPackageDB path)
= SpecificPackageDB `fmap` canonicalizePath path | 150 | canonicalizePackageDB (SpecificPackageDB path)
= SpecificPackageDB `fmap` canonicalizePath path | 99 | false | true | 0 | 7 | 17 | 36 | 18 | 18 | null | null |
Chase-C/KDtree | src/KDtree.hs | gpl-2.0 | kNearestNeighbors :: KDtree a -> Vec3D -> Int -> [a]
kNearestNeighbors tree pos num = map fst $ kNearestNeighbors' tree pos num | 127 | kNearestNeighbors :: KDtree a -> Vec3D -> Int -> [a]
kNearestNeighbors tree pos num = map fst $ kNearestNeighbors' tree pos num | 127 | kNearestNeighbors tree pos num = map fst $ kNearestNeighbors' tree pos num | 74 | false | true | 0 | 10 | 21 | 55 | 25 | 30 | null | null |
anttisalonen/freekick2 | src/Listings.hs | gpl-3.0 | showPlayerNation 24 = "Northern Ireland" | 40 | showPlayerNation 24 = "Northern Ireland" | 40 | showPlayerNation 24 = "Northern Ireland" | 40 | false | false | 1 | 5 | 4 | 13 | 4 | 9 | null | null |
thalerjonathan/phd | public/ArtIterating/code/haskell/PureAgentsConc/src/PureAgentsConc.hs | gpl-3.0 | killAgentFold :: Map.Map AgentId (Agent m s e) -> Agent m s e -> Map.Map AgentId (Agent m s e)
killAgentFold am a
| killFlag a = am
| otherwise = Map.insert (agentId a) a am | 181 | killAgentFold :: Map.Map AgentId (Agent m s e) -> Agent m s e -> Map.Map AgentId (Agent m s e)
killAgentFold am a
| killFlag a = am
| otherwise = Map.insert (agentId a) a am | 181 | killAgentFold am a
| killFlag a = am
| otherwise = Map.insert (agentId a) a am | 86 | false | true | 0 | 10 | 43 | 104 | 47 | 57 | null | null |
apyrgio/ganeti | src/Ganeti/Config.hs | bsd-2-clause | -- | Returns the DRBD minors of a given 'Disk'
getDrbdMinorsForDisk :: Disk -> [(Int, String)]
getDrbdMinorsForDisk =
collectFromDrbdDisks (\nA nB _ mnA mnB _ -> [(mnA, nA), (mnB, nB)]) | 187 | getDrbdMinorsForDisk :: Disk -> [(Int, String)]
getDrbdMinorsForDisk =
collectFromDrbdDisks (\nA nB _ mnA mnB _ -> [(mnA, nA), (mnB, nB)]) | 140 | getDrbdMinorsForDisk =
collectFromDrbdDisks (\nA nB _ mnA mnB _ -> [(mnA, nA), (mnB, nB)]) | 92 | true | true | 0 | 9 | 31 | 64 | 38 | 26 | null | null |
triplepointfive/soten | src/Codec/Soten/Util.hs | mit | hasExtention :: Foldable t => FilePath -> t String -> Bool
hasExtention file = elem (map toLower (takeExtension file)) | 118 | hasExtention :: Foldable t => FilePath -> t String -> Bool
hasExtention file = elem (map toLower (takeExtension file)) | 118 | hasExtention file = elem (map toLower (takeExtension file)) | 59 | false | true | 0 | 9 | 18 | 49 | 23 | 26 | null | null |
NikolayS/postgrest | test/Feature/InsertSpec.hs | mit | spec :: Spec
spec = beforeAll_ resetDb $ around (withApp cfgDefault) $ do
describe "Posting new record" $ do
after_ (clearTable "menagerie") . context "disparate csv types" $ do
it "accepts disparate json types" $ do
p <- post "/menagerie"
[json| {
"integer": 13, "double": 3.14159, "varchar": "testing!"
, "boolean": false, "date": "1900-01-01", "money": "$3.99"
, "enum": "foo"
} |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleStatus p `shouldBe` created201
it "filters columns in result using &select" $
request methodPost "/menagerie?select=integer,varchar" [("Prefer", "return=representation")]
[json| {
"integer": 14, "double": 3.14159, "varchar": "testing!"
, "boolean": false, "date": "1900-01-01", "money": "$3.99"
, "enum": "foo"
} |] `shouldRespondWith` ResponseMatcher {
matchBody = Just [str|{"integer":14,"varchar":"testing!"}|]
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "application/json"]
}
it "includes related data after insert" $
request methodPost "/projects?select=id,name,clients{id,name}" [("Prefer", "return=representation")]
[str|{"id":5,"name":"New Project","client_id":2}|] `shouldRespondWith` ResponseMatcher {
matchBody = Just [str|{"id":5,"name":"New Project","clients":{"id":2,"name":"Apple"}}|]
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "application/json", "Location" <:> "/projects?id=eq.5"]
}
context "with no pk supplied" $ do
context "into a table with auto-incrementing pk" . after_ (clearTable "auto_incrementing_pk") $
it "succeeds with 201 and link" $ do
p <- post "/auto_incrementing_pk" [json| { "non_nullable_string":"not null"} |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/auto_incrementing_pk\\?id=eq\\.[0-9]+"
simpleStatus p `shouldBe` created201
let Just location = lookup hLocation $ simpleHeaders p
r <- get location
let [record] = fromJust (JSON.decode $ simpleBody r :: Maybe [IncPK])
liftIO $ do
incStr record `shouldBe` "not null"
incNullableStr record `shouldBe` Nothing
context "into a table with simple pk" $
it "fails with 400 and error" $
post "/simple_pk" [json| { "extra":"foo"} |]
`shouldRespondWith` 400
context "into a table with no pk" . after_ (clearTable "no_pk") $ do
it "succeeds with 201 and a link including all fields" $ do
p <- post "/no_pk" [json| { "a":"foo", "b":"bar" } |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=eq.foo&b=eq.bar"
simpleStatus p `shouldBe` created201
it "returns full details of inserted record if asked" $ do
p <- request methodPost "/no_pk"
[("Prefer", "return=representation")]
[json| { "a":"bar", "b":"baz" } |]
liftIO $ do
simpleBody p `shouldBe` [json| { "a":"bar", "b":"baz" } |]
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=eq.bar&b=eq.baz"
simpleStatus p `shouldBe` created201
it "can post nulls" $ do
p <- request methodPost "/no_pk"
[("Prefer", "return=representation")]
[json| { "a":null, "b":"foo" } |]
liftIO $ do
simpleBody p `shouldBe` [json| { "a":null, "b":"foo" } |]
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=is.null&b=eq.foo"
simpleStatus p `shouldBe` created201
context "with compound pk supplied" . after_ (clearTable "compound_pk") $
it "builds response location header appropriately" $
post "/compound_pk" [json| { "k1":12, "k2":42 } |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 201,
matchHeaders = ["Location" <:> "/compound_pk?k1=eq.12&k2=eq.42"]
}
context "with invalid json payload" $
it "fails with 400 and error" $
post "/simple_pk" "}{ x = 2" `shouldRespondWith` 400
context "jsonb" . after_ (clearTable "json") $ do
it "serializes nested object" $ do
let inserted = [json| { "data": { "foo":"bar" } } |]
request methodPost "/json"
[("Prefer", "return=representation")]
inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Location" <:> [str|/json?data=eq.{"foo":"bar"}|]]
}
-- TODO! the test above seems right, why was the one below working before and not now
-- p <- request methodPost "/json" [("Prefer", "return=representation")] inserted
-- liftIO $ do
-- simpleBody p `shouldBe` inserted
-- simpleHeaders p `shouldSatisfy` matchHeader hLocation "/json\\?data=eq\\.%7B%22foo%22%3A%22bar%22%7D"
-- simpleStatus p `shouldBe` created201
it "serializes nested array" $ do
let inserted = [json| { "data": [1,2,3] } |]
request methodPost "/json"
[("Prefer", "return=representation")]
inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Location" <:> [str|/json?data=eq.[1,2,3]|]]
}
-- TODO! the test above seems right, why was the one below working before and not now
-- p <- request methodPost "/json" [("Prefer", "return=representation")] inserted
-- liftIO $ do
-- simpleBody p `shouldBe` inserted
-- simpleHeaders p `shouldSatisfy` matchHeader hLocation "/json\\?data=eq\\.%5B1%2C2%2C3%5D"
-- simpleStatus p `shouldBe` created201
describe "CSV insert" $ do
after_ (clearTable "menagerie") . context "disparate csv types" $
it "succeeds with multipart response" $ do
pendingWith "Decide on what to do with CSV insert"
let inserted = [str|integer,double,varchar,boolean,date,money,enum
|13,3.14159,testing!,false,1900-01-01,$3.99,foo
|12,0.1,a string,true,1929-10-01,12,bar
|]
request methodPost "/menagerie" [("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")] inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv"]
}
-- p <- request methodPost "/menagerie" [("Content-Type", "text/csv")]
-- [str|integer,double,varchar,boolean,date,money,enum
-- |13,3.14159,testing!,false,1900-01-01,$3.99,foo
-- |12,0.1,a string,true,1929-10-01,12,bar
-- |]
-- liftIO $ do
-- simpleBody p `shouldBe` "Content-Type: application/json\nLocation: /menagerie?integer=eq.13\n\n\n--postgrest_boundary\nContent-Type: application/json\nLocation: /menagerie?integer=eq.12\n\n"
-- simpleStatus p `shouldBe` created201
after_ (clearTable "no_pk") . context "requesting full representation" $ do
it "returns full details of inserted record" $
request methodPost "/no_pk"
[("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")]
"a,b\nbar,baz"
`shouldRespondWith` ResponseMatcher {
matchBody = Just "a,b\nbar,baz"
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv",
"Location" <:> "/no_pk?a=eq.bar&b=eq.baz"]
}
-- it "can post nulls (old way)" $ do
-- pendingWith "changed the response when in csv mode"
-- request methodPost "/no_pk"
-- [("Content-Type", "text/csv"), ("Prefer", "return=representation")]
-- "a,b\nNULL,foo"
-- `shouldRespondWith` ResponseMatcher {
-- matchBody = Just [json| { "a":null, "b":"foo" } |]
-- , matchStatus = 201
-- , matchHeaders = ["Content-Type" <:> "application/json",
-- "Location" <:> "/no_pk?a=is.null&b=eq.foo"]
-- }
it "can post nulls" $
request methodPost "/no_pk"
[("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")]
"a,b\nNULL,foo"
`shouldRespondWith` ResponseMatcher {
matchBody = Just "a,b\n,foo"
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv",
"Location" <:> "/no_pk?a=is.null&b=eq.foo"]
}
after_ (clearTable "no_pk") . context "with wrong number of columns" $
it "fails for too few" $ do
p <- request methodPost "/no_pk" [("Content-Type", "text/csv")] "a,b\nfoo,bar\nbaz"
liftIO $ simpleStatus p `shouldBe` badRequest400
-- it does not fail because the extra columns are ignored
-- it "fails for too many" $ do
-- p <- request methodPost "/no_pk" [("Content-Type", "text/csv")] "a,b\nfoo,bar\nbaz,bat,bad"
-- liftIO $ simpleStatus p `shouldBe` badRequest400
describe "Putting record" $ do
context "to unkonwn uri" $
it "gives a 404" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/fake" []
[json| { "real": false } |]
`shouldRespondWith` 404
context "to a known uri" $ do
context "without a fully-specified primary key" $
it "is not an allowed operation" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/compound_pk?k1=eq.12" []
[json| { "k1":12, "k2":42 } |]
`shouldRespondWith` 405
context "with a fully-specified primary key" $ do
context "not specifying every column in the table" $
it "is rejected for lack of idempotence" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42 } |]
`shouldRespondWith` 400
context "specifying every column in the table" . after_ (clearTable "compound_pk") $ do
it "can create a new record" $ do
pendingWith "Decide on PUT usefullness"
p <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":3 } |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleStatus p `shouldBe` status204
r <- get "/compound_pk?k1=eq.12&k2=eq.42"
let rows = fromJust (JSON.decode $ simpleBody r :: Maybe [CompoundPK])
liftIO $ do
length rows `shouldBe` 1
let record = head rows
compoundK1 record `shouldBe` 12
compoundK2 record `shouldBe` 42
compoundExtra record `shouldBe` Just 3
it "can update an existing record" $ do
pendingWith "Decide on PUT usefullness"
_ <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":4 } |]
_ <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":5 } |]
r <- get "/compound_pk?k1=eq.12&k2=eq.42"
let rows = fromJust (JSON.decode $ simpleBody r :: Maybe [CompoundPK])
liftIO $ do
length rows `shouldBe` 1
let record = head rows
compoundExtra record `shouldBe` Just 5
context "with an auto-incrementing primary key" . after_ (clearTable "auto_incrementing_pk") $
it "succeeds with 204" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/auto_incrementing_pk?id=eq.1" []
[json| {
"id":1,
"nullable_string":"hi",
"non_nullable_string":"bye",
"inserted_at": "2020-11-11"
} |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 204,
matchHeaders = []
}
describe "Patching record" $ do
context "to unkonwn uri" $
it "gives a 404" $
request methodPatch "/fake" []
[json| { "real": false } |]
`shouldRespondWith` 404
context "on an empty table" $
it "indicates no records found to update" $
request methodPatch "/empty_table" []
[json| { "extra":20 } |]
`shouldRespondWith` 404
context "in a nonempty table" $ do
it "can update a single item" $ do
g <- get "/items?id=eq.42"
liftIO $ simpleHeaders g
`shouldSatisfy` matchHeader "Content-Range" "\\*/0"
request methodPatch "/items?id=eq.2" []
[json| { "id":42 } |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 204,
matchHeaders = ["Content-Range" <:> "0-0/1"]
}
g' <- get "/items?id=eq.42"
liftIO $ simpleHeaders g'
`shouldSatisfy` matchHeader "Content-Range" "0-0/1"
it "can update multiple items" $ do
replicateM_ 10 $ post "/auto_incrementing_pk"
[json| { non_nullable_string: "a" } |]
replicateM_ 10 $ post "/auto_incrementing_pk"
[json| { non_nullable_string: "b" } |]
_ <- request methodPatch
"/auto_incrementing_pk?non_nullable_string=eq.a" []
[json| { non_nullable_string: "c" } |]
g <- get "/auto_incrementing_pk?non_nullable_string=eq.c"
liftIO $ simpleHeaders g
`shouldSatisfy` matchHeader "Content-Range" "0-9/10"
it "can set a column to NULL" $ do
_ <- post "/no_pk" [json| { a: "keepme", b: "nullme" } |]
_ <- request methodPatch "/no_pk?b=eq.nullme" [] [json| { b: null } |]
get "/no_pk?a=eq.keepme" `shouldRespondWith`
[json| [{ a: "keepme", b: null }] |]
it "can update based on a computed column" $
request methodPatch
"/items?always_true=eq.false"
[("Prefer", "return=representation")]
[json| { id: 100 } |]
`shouldRespondWith` 404
it "can provide a representation" $ do
_ <- post "/items"
[json| { id: 1 } |]
request methodPatch
"/items?id=eq.1"
[("Prefer", "return=representation")]
[json| { id: 99 } |]
`shouldRespondWith` [json| [{id:99}] |]
describe "Row level permission" $
it "set user_id when inserting rows" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.y4vZuu1dDdwAl0-S00MCRWRYMlJ5YAMSir6Es6WtWx0"
_ <- post "/postgrest/users" [json| { "id":"jdoe", "pass": "1234", "role": "postgrest_test_author" } |]
_ <- post "/postgrest/users" [json| { "id":"jroe", "pass": "1234", "role": "postgrest_test_author" } |]
p1 <- request methodPost "/authors_only"
[ auth, ("Prefer", "return=representation") ]
[json| { "secret": "nyancat" } |]
liftIO $ do
simpleBody p1 `shouldBe` [str|{"owner":"jdoe","secret":"nyancat"}|]
simpleStatus p1 `shouldBe` created201
p2 <- request methodPost "/authors_only"
-- jwt token for jroe
[ authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqcm9lIn0.YuF_VfmyIxWyuceT7crnNKEprIYXsJAyXid3rjPjIow", ("Prefer", "return=representation") ]
[json| { "secret": "lolcat", "owner": "hacker" } |]
liftIO $ do
simpleBody p2 `shouldBe` [str|{"owner":"jroe","secret":"lolcat"}|]
simpleStatus p2 `shouldBe` created201 | 16,413 | spec :: Spec
spec = beforeAll_ resetDb $ around (withApp cfgDefault) $ do
describe "Posting new record" $ do
after_ (clearTable "menagerie") . context "disparate csv types" $ do
it "accepts disparate json types" $ do
p <- post "/menagerie"
[json| {
"integer": 13, "double": 3.14159, "varchar": "testing!"
, "boolean": false, "date": "1900-01-01", "money": "$3.99"
, "enum": "foo"
} |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleStatus p `shouldBe` created201
it "filters columns in result using &select" $
request methodPost "/menagerie?select=integer,varchar" [("Prefer", "return=representation")]
[json| {
"integer": 14, "double": 3.14159, "varchar": "testing!"
, "boolean": false, "date": "1900-01-01", "money": "$3.99"
, "enum": "foo"
} |] `shouldRespondWith` ResponseMatcher {
matchBody = Just [str|{"integer":14,"varchar":"testing!"}|]
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "application/json"]
}
it "includes related data after insert" $
request methodPost "/projects?select=id,name,clients{id,name}" [("Prefer", "return=representation")]
[str|{"id":5,"name":"New Project","client_id":2}|] `shouldRespondWith` ResponseMatcher {
matchBody = Just [str|{"id":5,"name":"New Project","clients":{"id":2,"name":"Apple"}}|]
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "application/json", "Location" <:> "/projects?id=eq.5"]
}
context "with no pk supplied" $ do
context "into a table with auto-incrementing pk" . after_ (clearTable "auto_incrementing_pk") $
it "succeeds with 201 and link" $ do
p <- post "/auto_incrementing_pk" [json| { "non_nullable_string":"not null"} |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/auto_incrementing_pk\\?id=eq\\.[0-9]+"
simpleStatus p `shouldBe` created201
let Just location = lookup hLocation $ simpleHeaders p
r <- get location
let [record] = fromJust (JSON.decode $ simpleBody r :: Maybe [IncPK])
liftIO $ do
incStr record `shouldBe` "not null"
incNullableStr record `shouldBe` Nothing
context "into a table with simple pk" $
it "fails with 400 and error" $
post "/simple_pk" [json| { "extra":"foo"} |]
`shouldRespondWith` 400
context "into a table with no pk" . after_ (clearTable "no_pk") $ do
it "succeeds with 201 and a link including all fields" $ do
p <- post "/no_pk" [json| { "a":"foo", "b":"bar" } |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=eq.foo&b=eq.bar"
simpleStatus p `shouldBe` created201
it "returns full details of inserted record if asked" $ do
p <- request methodPost "/no_pk"
[("Prefer", "return=representation")]
[json| { "a":"bar", "b":"baz" } |]
liftIO $ do
simpleBody p `shouldBe` [json| { "a":"bar", "b":"baz" } |]
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=eq.bar&b=eq.baz"
simpleStatus p `shouldBe` created201
it "can post nulls" $ do
p <- request methodPost "/no_pk"
[("Prefer", "return=representation")]
[json| { "a":null, "b":"foo" } |]
liftIO $ do
simpleBody p `shouldBe` [json| { "a":null, "b":"foo" } |]
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=is.null&b=eq.foo"
simpleStatus p `shouldBe` created201
context "with compound pk supplied" . after_ (clearTable "compound_pk") $
it "builds response location header appropriately" $
post "/compound_pk" [json| { "k1":12, "k2":42 } |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 201,
matchHeaders = ["Location" <:> "/compound_pk?k1=eq.12&k2=eq.42"]
}
context "with invalid json payload" $
it "fails with 400 and error" $
post "/simple_pk" "}{ x = 2" `shouldRespondWith` 400
context "jsonb" . after_ (clearTable "json") $ do
it "serializes nested object" $ do
let inserted = [json| { "data": { "foo":"bar" } } |]
request methodPost "/json"
[("Prefer", "return=representation")]
inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Location" <:> [str|/json?data=eq.{"foo":"bar"}|]]
}
-- TODO! the test above seems right, why was the one below working before and not now
-- p <- request methodPost "/json" [("Prefer", "return=representation")] inserted
-- liftIO $ do
-- simpleBody p `shouldBe` inserted
-- simpleHeaders p `shouldSatisfy` matchHeader hLocation "/json\\?data=eq\\.%7B%22foo%22%3A%22bar%22%7D"
-- simpleStatus p `shouldBe` created201
it "serializes nested array" $ do
let inserted = [json| { "data": [1,2,3] } |]
request methodPost "/json"
[("Prefer", "return=representation")]
inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Location" <:> [str|/json?data=eq.[1,2,3]|]]
}
-- TODO! the test above seems right, why was the one below working before and not now
-- p <- request methodPost "/json" [("Prefer", "return=representation")] inserted
-- liftIO $ do
-- simpleBody p `shouldBe` inserted
-- simpleHeaders p `shouldSatisfy` matchHeader hLocation "/json\\?data=eq\\.%5B1%2C2%2C3%5D"
-- simpleStatus p `shouldBe` created201
describe "CSV insert" $ do
after_ (clearTable "menagerie") . context "disparate csv types" $
it "succeeds with multipart response" $ do
pendingWith "Decide on what to do with CSV insert"
let inserted = [str|integer,double,varchar,boolean,date,money,enum
|13,3.14159,testing!,false,1900-01-01,$3.99,foo
|12,0.1,a string,true,1929-10-01,12,bar
|]
request methodPost "/menagerie" [("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")] inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv"]
}
-- p <- request methodPost "/menagerie" [("Content-Type", "text/csv")]
-- [str|integer,double,varchar,boolean,date,money,enum
-- |13,3.14159,testing!,false,1900-01-01,$3.99,foo
-- |12,0.1,a string,true,1929-10-01,12,bar
-- |]
-- liftIO $ do
-- simpleBody p `shouldBe` "Content-Type: application/json\nLocation: /menagerie?integer=eq.13\n\n\n--postgrest_boundary\nContent-Type: application/json\nLocation: /menagerie?integer=eq.12\n\n"
-- simpleStatus p `shouldBe` created201
after_ (clearTable "no_pk") . context "requesting full representation" $ do
it "returns full details of inserted record" $
request methodPost "/no_pk"
[("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")]
"a,b\nbar,baz"
`shouldRespondWith` ResponseMatcher {
matchBody = Just "a,b\nbar,baz"
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv",
"Location" <:> "/no_pk?a=eq.bar&b=eq.baz"]
}
-- it "can post nulls (old way)" $ do
-- pendingWith "changed the response when in csv mode"
-- request methodPost "/no_pk"
-- [("Content-Type", "text/csv"), ("Prefer", "return=representation")]
-- "a,b\nNULL,foo"
-- `shouldRespondWith` ResponseMatcher {
-- matchBody = Just [json| { "a":null, "b":"foo" } |]
-- , matchStatus = 201
-- , matchHeaders = ["Content-Type" <:> "application/json",
-- "Location" <:> "/no_pk?a=is.null&b=eq.foo"]
-- }
it "can post nulls" $
request methodPost "/no_pk"
[("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")]
"a,b\nNULL,foo"
`shouldRespondWith` ResponseMatcher {
matchBody = Just "a,b\n,foo"
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv",
"Location" <:> "/no_pk?a=is.null&b=eq.foo"]
}
after_ (clearTable "no_pk") . context "with wrong number of columns" $
it "fails for too few" $ do
p <- request methodPost "/no_pk" [("Content-Type", "text/csv")] "a,b\nfoo,bar\nbaz"
liftIO $ simpleStatus p `shouldBe` badRequest400
-- it does not fail because the extra columns are ignored
-- it "fails for too many" $ do
-- p <- request methodPost "/no_pk" [("Content-Type", "text/csv")] "a,b\nfoo,bar\nbaz,bat,bad"
-- liftIO $ simpleStatus p `shouldBe` badRequest400
describe "Putting record" $ do
context "to unkonwn uri" $
it "gives a 404" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/fake" []
[json| { "real": false } |]
`shouldRespondWith` 404
context "to a known uri" $ do
context "without a fully-specified primary key" $
it "is not an allowed operation" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/compound_pk?k1=eq.12" []
[json| { "k1":12, "k2":42 } |]
`shouldRespondWith` 405
context "with a fully-specified primary key" $ do
context "not specifying every column in the table" $
it "is rejected for lack of idempotence" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42 } |]
`shouldRespondWith` 400
context "specifying every column in the table" . after_ (clearTable "compound_pk") $ do
it "can create a new record" $ do
pendingWith "Decide on PUT usefullness"
p <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":3 } |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleStatus p `shouldBe` status204
r <- get "/compound_pk?k1=eq.12&k2=eq.42"
let rows = fromJust (JSON.decode $ simpleBody r :: Maybe [CompoundPK])
liftIO $ do
length rows `shouldBe` 1
let record = head rows
compoundK1 record `shouldBe` 12
compoundK2 record `shouldBe` 42
compoundExtra record `shouldBe` Just 3
it "can update an existing record" $ do
pendingWith "Decide on PUT usefullness"
_ <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":4 } |]
_ <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":5 } |]
r <- get "/compound_pk?k1=eq.12&k2=eq.42"
let rows = fromJust (JSON.decode $ simpleBody r :: Maybe [CompoundPK])
liftIO $ do
length rows `shouldBe` 1
let record = head rows
compoundExtra record `shouldBe` Just 5
context "with an auto-incrementing primary key" . after_ (clearTable "auto_incrementing_pk") $
it "succeeds with 204" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/auto_incrementing_pk?id=eq.1" []
[json| {
"id":1,
"nullable_string":"hi",
"non_nullable_string":"bye",
"inserted_at": "2020-11-11"
} |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 204,
matchHeaders = []
}
describe "Patching record" $ do
context "to unkonwn uri" $
it "gives a 404" $
request methodPatch "/fake" []
[json| { "real": false } |]
`shouldRespondWith` 404
context "on an empty table" $
it "indicates no records found to update" $
request methodPatch "/empty_table" []
[json| { "extra":20 } |]
`shouldRespondWith` 404
context "in a nonempty table" $ do
it "can update a single item" $ do
g <- get "/items?id=eq.42"
liftIO $ simpleHeaders g
`shouldSatisfy` matchHeader "Content-Range" "\\*/0"
request methodPatch "/items?id=eq.2" []
[json| { "id":42 } |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 204,
matchHeaders = ["Content-Range" <:> "0-0/1"]
}
g' <- get "/items?id=eq.42"
liftIO $ simpleHeaders g'
`shouldSatisfy` matchHeader "Content-Range" "0-0/1"
it "can update multiple items" $ do
replicateM_ 10 $ post "/auto_incrementing_pk"
[json| { non_nullable_string: "a" } |]
replicateM_ 10 $ post "/auto_incrementing_pk"
[json| { non_nullable_string: "b" } |]
_ <- request methodPatch
"/auto_incrementing_pk?non_nullable_string=eq.a" []
[json| { non_nullable_string: "c" } |]
g <- get "/auto_incrementing_pk?non_nullable_string=eq.c"
liftIO $ simpleHeaders g
`shouldSatisfy` matchHeader "Content-Range" "0-9/10"
it "can set a column to NULL" $ do
_ <- post "/no_pk" [json| { a: "keepme", b: "nullme" } |]
_ <- request methodPatch "/no_pk?b=eq.nullme" [] [json| { b: null } |]
get "/no_pk?a=eq.keepme" `shouldRespondWith`
[json| [{ a: "keepme", b: null }] |]
it "can update based on a computed column" $
request methodPatch
"/items?always_true=eq.false"
[("Prefer", "return=representation")]
[json| { id: 100 } |]
`shouldRespondWith` 404
it "can provide a representation" $ do
_ <- post "/items"
[json| { id: 1 } |]
request methodPatch
"/items?id=eq.1"
[("Prefer", "return=representation")]
[json| { id: 99 } |]
`shouldRespondWith` [json| [{id:99}] |]
describe "Row level permission" $
it "set user_id when inserting rows" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.y4vZuu1dDdwAl0-S00MCRWRYMlJ5YAMSir6Es6WtWx0"
_ <- post "/postgrest/users" [json| { "id":"jdoe", "pass": "1234", "role": "postgrest_test_author" } |]
_ <- post "/postgrest/users" [json| { "id":"jroe", "pass": "1234", "role": "postgrest_test_author" } |]
p1 <- request methodPost "/authors_only"
[ auth, ("Prefer", "return=representation") ]
[json| { "secret": "nyancat" } |]
liftIO $ do
simpleBody p1 `shouldBe` [str|{"owner":"jdoe","secret":"nyancat"}|]
simpleStatus p1 `shouldBe` created201
p2 <- request methodPost "/authors_only"
-- jwt token for jroe
[ authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqcm9lIn0.YuF_VfmyIxWyuceT7crnNKEprIYXsJAyXid3rjPjIow", ("Prefer", "return=representation") ]
[json| { "secret": "lolcat", "owner": "hacker" } |]
liftIO $ do
simpleBody p2 `shouldBe` [str|{"owner":"jroe","secret":"lolcat"}|]
simpleStatus p2 `shouldBe` created201 | 16,413 | spec = beforeAll_ resetDb $ around (withApp cfgDefault) $ do
describe "Posting new record" $ do
after_ (clearTable "menagerie") . context "disparate csv types" $ do
it "accepts disparate json types" $ do
p <- post "/menagerie"
[json| {
"integer": 13, "double": 3.14159, "varchar": "testing!"
, "boolean": false, "date": "1900-01-01", "money": "$3.99"
, "enum": "foo"
} |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleStatus p `shouldBe` created201
it "filters columns in result using &select" $
request methodPost "/menagerie?select=integer,varchar" [("Prefer", "return=representation")]
[json| {
"integer": 14, "double": 3.14159, "varchar": "testing!"
, "boolean": false, "date": "1900-01-01", "money": "$3.99"
, "enum": "foo"
} |] `shouldRespondWith` ResponseMatcher {
matchBody = Just [str|{"integer":14,"varchar":"testing!"}|]
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "application/json"]
}
it "includes related data after insert" $
request methodPost "/projects?select=id,name,clients{id,name}" [("Prefer", "return=representation")]
[str|{"id":5,"name":"New Project","client_id":2}|] `shouldRespondWith` ResponseMatcher {
matchBody = Just [str|{"id":5,"name":"New Project","clients":{"id":2,"name":"Apple"}}|]
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "application/json", "Location" <:> "/projects?id=eq.5"]
}
context "with no pk supplied" $ do
context "into a table with auto-incrementing pk" . after_ (clearTable "auto_incrementing_pk") $
it "succeeds with 201 and link" $ do
p <- post "/auto_incrementing_pk" [json| { "non_nullable_string":"not null"} |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/auto_incrementing_pk\\?id=eq\\.[0-9]+"
simpleStatus p `shouldBe` created201
let Just location = lookup hLocation $ simpleHeaders p
r <- get location
let [record] = fromJust (JSON.decode $ simpleBody r :: Maybe [IncPK])
liftIO $ do
incStr record `shouldBe` "not null"
incNullableStr record `shouldBe` Nothing
context "into a table with simple pk" $
it "fails with 400 and error" $
post "/simple_pk" [json| { "extra":"foo"} |]
`shouldRespondWith` 400
context "into a table with no pk" . after_ (clearTable "no_pk") $ do
it "succeeds with 201 and a link including all fields" $ do
p <- post "/no_pk" [json| { "a":"foo", "b":"bar" } |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=eq.foo&b=eq.bar"
simpleStatus p `shouldBe` created201
it "returns full details of inserted record if asked" $ do
p <- request methodPost "/no_pk"
[("Prefer", "return=representation")]
[json| { "a":"bar", "b":"baz" } |]
liftIO $ do
simpleBody p `shouldBe` [json| { "a":"bar", "b":"baz" } |]
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=eq.bar&b=eq.baz"
simpleStatus p `shouldBe` created201
it "can post nulls" $ do
p <- request methodPost "/no_pk"
[("Prefer", "return=representation")]
[json| { "a":null, "b":"foo" } |]
liftIO $ do
simpleBody p `shouldBe` [json| { "a":null, "b":"foo" } |]
simpleHeaders p `shouldSatisfy` matchHeader hLocation "/no_pk\\?a=is.null&b=eq.foo"
simpleStatus p `shouldBe` created201
context "with compound pk supplied" . after_ (clearTable "compound_pk") $
it "builds response location header appropriately" $
post "/compound_pk" [json| { "k1":12, "k2":42 } |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 201,
matchHeaders = ["Location" <:> "/compound_pk?k1=eq.12&k2=eq.42"]
}
context "with invalid json payload" $
it "fails with 400 and error" $
post "/simple_pk" "}{ x = 2" `shouldRespondWith` 400
context "jsonb" . after_ (clearTable "json") $ do
it "serializes nested object" $ do
let inserted = [json| { "data": { "foo":"bar" } } |]
request methodPost "/json"
[("Prefer", "return=representation")]
inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Location" <:> [str|/json?data=eq.{"foo":"bar"}|]]
}
-- TODO! the test above seems right, why was the one below working before and not now
-- p <- request methodPost "/json" [("Prefer", "return=representation")] inserted
-- liftIO $ do
-- simpleBody p `shouldBe` inserted
-- simpleHeaders p `shouldSatisfy` matchHeader hLocation "/json\\?data=eq\\.%7B%22foo%22%3A%22bar%22%7D"
-- simpleStatus p `shouldBe` created201
it "serializes nested array" $ do
let inserted = [json| { "data": [1,2,3] } |]
request methodPost "/json"
[("Prefer", "return=representation")]
inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Location" <:> [str|/json?data=eq.[1,2,3]|]]
}
-- TODO! the test above seems right, why was the one below working before and not now
-- p <- request methodPost "/json" [("Prefer", "return=representation")] inserted
-- liftIO $ do
-- simpleBody p `shouldBe` inserted
-- simpleHeaders p `shouldSatisfy` matchHeader hLocation "/json\\?data=eq\\.%5B1%2C2%2C3%5D"
-- simpleStatus p `shouldBe` created201
describe "CSV insert" $ do
after_ (clearTable "menagerie") . context "disparate csv types" $
it "succeeds with multipart response" $ do
pendingWith "Decide on what to do with CSV insert"
let inserted = [str|integer,double,varchar,boolean,date,money,enum
|13,3.14159,testing!,false,1900-01-01,$3.99,foo
|12,0.1,a string,true,1929-10-01,12,bar
|]
request methodPost "/menagerie" [("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")] inserted
`shouldRespondWith` ResponseMatcher {
matchBody = Just inserted
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv"]
}
-- p <- request methodPost "/menagerie" [("Content-Type", "text/csv")]
-- [str|integer,double,varchar,boolean,date,money,enum
-- |13,3.14159,testing!,false,1900-01-01,$3.99,foo
-- |12,0.1,a string,true,1929-10-01,12,bar
-- |]
-- liftIO $ do
-- simpleBody p `shouldBe` "Content-Type: application/json\nLocation: /menagerie?integer=eq.13\n\n\n--postgrest_boundary\nContent-Type: application/json\nLocation: /menagerie?integer=eq.12\n\n"
-- simpleStatus p `shouldBe` created201
after_ (clearTable "no_pk") . context "requesting full representation" $ do
it "returns full details of inserted record" $
request methodPost "/no_pk"
[("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")]
"a,b\nbar,baz"
`shouldRespondWith` ResponseMatcher {
matchBody = Just "a,b\nbar,baz"
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv",
"Location" <:> "/no_pk?a=eq.bar&b=eq.baz"]
}
-- it "can post nulls (old way)" $ do
-- pendingWith "changed the response when in csv mode"
-- request methodPost "/no_pk"
-- [("Content-Type", "text/csv"), ("Prefer", "return=representation")]
-- "a,b\nNULL,foo"
-- `shouldRespondWith` ResponseMatcher {
-- matchBody = Just [json| { "a":null, "b":"foo" } |]
-- , matchStatus = 201
-- , matchHeaders = ["Content-Type" <:> "application/json",
-- "Location" <:> "/no_pk?a=is.null&b=eq.foo"]
-- }
it "can post nulls" $
request methodPost "/no_pk"
[("Content-Type", "text/csv"), ("Accept", "text/csv"), ("Prefer", "return=representation")]
"a,b\nNULL,foo"
`shouldRespondWith` ResponseMatcher {
matchBody = Just "a,b\n,foo"
, matchStatus = 201
, matchHeaders = ["Content-Type" <:> "text/csv",
"Location" <:> "/no_pk?a=is.null&b=eq.foo"]
}
after_ (clearTable "no_pk") . context "with wrong number of columns" $
it "fails for too few" $ do
p <- request methodPost "/no_pk" [("Content-Type", "text/csv")] "a,b\nfoo,bar\nbaz"
liftIO $ simpleStatus p `shouldBe` badRequest400
-- it does not fail because the extra columns are ignored
-- it "fails for too many" $ do
-- p <- request methodPost "/no_pk" [("Content-Type", "text/csv")] "a,b\nfoo,bar\nbaz,bat,bad"
-- liftIO $ simpleStatus p `shouldBe` badRequest400
describe "Putting record" $ do
context "to unkonwn uri" $
it "gives a 404" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/fake" []
[json| { "real": false } |]
`shouldRespondWith` 404
context "to a known uri" $ do
context "without a fully-specified primary key" $
it "is not an allowed operation" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/compound_pk?k1=eq.12" []
[json| { "k1":12, "k2":42 } |]
`shouldRespondWith` 405
context "with a fully-specified primary key" $ do
context "not specifying every column in the table" $
it "is rejected for lack of idempotence" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42 } |]
`shouldRespondWith` 400
context "specifying every column in the table" . after_ (clearTable "compound_pk") $ do
it "can create a new record" $ do
pendingWith "Decide on PUT usefullness"
p <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":3 } |]
liftIO $ do
simpleBody p `shouldBe` ""
simpleStatus p `shouldBe` status204
r <- get "/compound_pk?k1=eq.12&k2=eq.42"
let rows = fromJust (JSON.decode $ simpleBody r :: Maybe [CompoundPK])
liftIO $ do
length rows `shouldBe` 1
let record = head rows
compoundK1 record `shouldBe` 12
compoundK2 record `shouldBe` 42
compoundExtra record `shouldBe` Just 3
it "can update an existing record" $ do
pendingWith "Decide on PUT usefullness"
_ <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":4 } |]
_ <- request methodPut "/compound_pk?k1=eq.12&k2=eq.42" []
[json| { "k1":12, "k2":42, "extra":5 } |]
r <- get "/compound_pk?k1=eq.12&k2=eq.42"
let rows = fromJust (JSON.decode $ simpleBody r :: Maybe [CompoundPK])
liftIO $ do
length rows `shouldBe` 1
let record = head rows
compoundExtra record `shouldBe` Just 5
context "with an auto-incrementing primary key" . after_ (clearTable "auto_incrementing_pk") $
it "succeeds with 204" $ do
pendingWith "Decide on PUT usefullness"
request methodPut "/auto_incrementing_pk?id=eq.1" []
[json| {
"id":1,
"nullable_string":"hi",
"non_nullable_string":"bye",
"inserted_at": "2020-11-11"
} |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 204,
matchHeaders = []
}
describe "Patching record" $ do
context "to unkonwn uri" $
it "gives a 404" $
request methodPatch "/fake" []
[json| { "real": false } |]
`shouldRespondWith` 404
context "on an empty table" $
it "indicates no records found to update" $
request methodPatch "/empty_table" []
[json| { "extra":20 } |]
`shouldRespondWith` 404
context "in a nonempty table" $ do
it "can update a single item" $ do
g <- get "/items?id=eq.42"
liftIO $ simpleHeaders g
`shouldSatisfy` matchHeader "Content-Range" "\\*/0"
request methodPatch "/items?id=eq.2" []
[json| { "id":42 } |]
`shouldRespondWith` ResponseMatcher {
matchBody = Nothing,
matchStatus = 204,
matchHeaders = ["Content-Range" <:> "0-0/1"]
}
g' <- get "/items?id=eq.42"
liftIO $ simpleHeaders g'
`shouldSatisfy` matchHeader "Content-Range" "0-0/1"
it "can update multiple items" $ do
replicateM_ 10 $ post "/auto_incrementing_pk"
[json| { non_nullable_string: "a" } |]
replicateM_ 10 $ post "/auto_incrementing_pk"
[json| { non_nullable_string: "b" } |]
_ <- request methodPatch
"/auto_incrementing_pk?non_nullable_string=eq.a" []
[json| { non_nullable_string: "c" } |]
g <- get "/auto_incrementing_pk?non_nullable_string=eq.c"
liftIO $ simpleHeaders g
`shouldSatisfy` matchHeader "Content-Range" "0-9/10"
it "can set a column to NULL" $ do
_ <- post "/no_pk" [json| { a: "keepme", b: "nullme" } |]
_ <- request methodPatch "/no_pk?b=eq.nullme" [] [json| { b: null } |]
get "/no_pk?a=eq.keepme" `shouldRespondWith`
[json| [{ a: "keepme", b: null }] |]
it "can update based on a computed column" $
request methodPatch
"/items?always_true=eq.false"
[("Prefer", "return=representation")]
[json| { id: 100 } |]
`shouldRespondWith` 404
it "can provide a representation" $ do
_ <- post "/items"
[json| { id: 1 } |]
request methodPatch
"/items?id=eq.1"
[("Prefer", "return=representation")]
[json| { id: 99 } |]
`shouldRespondWith` [json| [{id:99}] |]
describe "Row level permission" $
it "set user_id when inserting rows" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqZG9lIn0.y4vZuu1dDdwAl0-S00MCRWRYMlJ5YAMSir6Es6WtWx0"
_ <- post "/postgrest/users" [json| { "id":"jdoe", "pass": "1234", "role": "postgrest_test_author" } |]
_ <- post "/postgrest/users" [json| { "id":"jroe", "pass": "1234", "role": "postgrest_test_author" } |]
p1 <- request methodPost "/authors_only"
[ auth, ("Prefer", "return=representation") ]
[json| { "secret": "nyancat" } |]
liftIO $ do
simpleBody p1 `shouldBe` [str|{"owner":"jdoe","secret":"nyancat"}|]
simpleStatus p1 `shouldBe` created201
p2 <- request methodPost "/authors_only"
-- jwt token for jroe
[ authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicG9zdGdyZXN0X3Rlc3RfYXV0aG9yIiwiaWQiOiJqcm9lIn0.YuF_VfmyIxWyuceT7crnNKEprIYXsJAyXid3rjPjIow", ("Prefer", "return=representation") ]
[json| { "secret": "lolcat", "owner": "hacker" } |]
liftIO $ do
simpleBody p2 `shouldBe` [str|{"owner":"jroe","secret":"lolcat"}|]
simpleStatus p2 `shouldBe` created201 | 16,400 | false | true | 0 | 29 | 5,003 | 2,816 | 1,473 | 1,343 | null | null |
hellertime/consul-haskell | src/Network/Consul/Internal.hs | bsd-3-clause | putKeyAcquireLock :: MonadIO m => Manager -> Text -> PortNumber -> KeyValuePut -> Session -> Maybe Datacenter -> m Bool
putKeyAcquireLock manager hostname portNumber request (Session session _) dc = do
initReq <- createRequest hostname portNumber (T.concat ["/v1/kv/", kvpKey request]) fquery (Just $ kvpValue request) False dc
liftIO $ withResponse initReq manager $ \ response -> do
bodyParts <- brConsume $ responseBody response
let body = B.concat bodyParts
case TE.decodeUtf8 body of
"true" -> return True
"false" -> return False
_ -> return False
where
flags = fmap (\ x -> T.concat["flags=", T.pack $ show x]) $ kvpFlags request
cas = fmap (\ x -> T.concat["cas=",T.pack $ show x]) $ kvpCasIndex request
acquire = T.concat["acquire=",session]
query = T.intercalate "&" $ catMaybes [flags,cas,Just acquire]
fquery = if query /= T.empty then Just query else Nothing | 926 | putKeyAcquireLock :: MonadIO m => Manager -> Text -> PortNumber -> KeyValuePut -> Session -> Maybe Datacenter -> m Bool
putKeyAcquireLock manager hostname portNumber request (Session session _) dc = do
initReq <- createRequest hostname portNumber (T.concat ["/v1/kv/", kvpKey request]) fquery (Just $ kvpValue request) False dc
liftIO $ withResponse initReq manager $ \ response -> do
bodyParts <- brConsume $ responseBody response
let body = B.concat bodyParts
case TE.decodeUtf8 body of
"true" -> return True
"false" -> return False
_ -> return False
where
flags = fmap (\ x -> T.concat["flags=", T.pack $ show x]) $ kvpFlags request
cas = fmap (\ x -> T.concat["cas=",T.pack $ show x]) $ kvpCasIndex request
acquire = T.concat["acquire=",session]
query = T.intercalate "&" $ catMaybes [flags,cas,Just acquire]
fquery = if query /= T.empty then Just query else Nothing | 926 | putKeyAcquireLock manager hostname portNumber request (Session session _) dc = do
initReq <- createRequest hostname portNumber (T.concat ["/v1/kv/", kvpKey request]) fquery (Just $ kvpValue request) False dc
liftIO $ withResponse initReq manager $ \ response -> do
bodyParts <- brConsume $ responseBody response
let body = B.concat bodyParts
case TE.decodeUtf8 body of
"true" -> return True
"false" -> return False
_ -> return False
where
flags = fmap (\ x -> T.concat["flags=", T.pack $ show x]) $ kvpFlags request
cas = fmap (\ x -> T.concat["cas=",T.pack $ show x]) $ kvpCasIndex request
acquire = T.concat["acquire=",session]
query = T.intercalate "&" $ catMaybes [flags,cas,Just acquire]
fquery = if query /= T.empty then Just query else Nothing | 806 | false | true | 5 | 15 | 189 | 382 | 178 | 204 | null | null |
zerobuzz/hs-webdriver | test/etc/QuickCheck.hs | bsd-3-clause | config :: WDConfig
config = defaultConfig | 41 | config :: WDConfig
config = defaultConfig | 41 | config = defaultConfig | 22 | false | true | 0 | 4 | 5 | 11 | 6 | 5 | null | null |
abstools/abs-haskell-formal | benchmarks/2_primality_test/progs/500.hs | bsd-3-clause | main_ :: Method
main_ [] this wb k =
Assign n (Val (I 500)) $
Assign x (Sync is_prime [n]) $
k | 102 | main_ :: Method
main_ [] this wb k =
Assign n (Val (I 500)) $
Assign x (Sync is_prime [n]) $
k | 102 | main_ [] this wb k =
Assign n (Val (I 500)) $
Assign x (Sync is_prime [n]) $
k | 86 | false | true | 1 | 9 | 29 | 70 | 31 | 39 | null | null |
hesiod/OpenGL | src/Graphics/Rendering/OpenGL/GL/QueryObjects.hs | bsd-3-clause | withQuery :: QueryTarget -> QueryObject -> IO a -> IO a
withQuery t q = bracket_ (beginQuery t q) (endQuery t) | 110 | withQuery :: QueryTarget -> QueryObject -> IO a -> IO a
withQuery t q = bracket_ (beginQuery t q) (endQuery t) | 110 | withQuery t q = bracket_ (beginQuery t q) (endQuery t) | 54 | false | true | 0 | 8 | 20 | 53 | 25 | 28 | null | null |
avaitla/Haskell-to-C---Bridge | src/GCCXML/Types.hs | bsd-3-clause | xml_NN_CLASS = "Class" | 22 | xml_NN_CLASS = "Class" | 22 | xml_NN_CLASS = "Class" | 22 | false | false | 0 | 4 | 2 | 6 | 3 | 3 | null | null |
johnpmayer/elm-compiler | src/AST/Variable.hs | bsd-3-clause | -- CATEGORIZING VALUES
getValues :: [Value] -> [String]
getValues values =
Maybe.mapMaybe getValue values | 108 | getValues :: [Value] -> [String]
getValues values =
Maybe.mapMaybe getValue values | 84 | getValues values =
Maybe.mapMaybe getValue values | 51 | true | true | 0 | 6 | 16 | 35 | 18 | 17 | null | null |
deweyvm/pone | src/Pone/Test.hs | gpl-3.0 | getFiles (TestSpec t root (Single i)) = return $ [root ++ (intToFile i)] | 72 | getFiles (TestSpec t root (Single i)) = return $ [root ++ (intToFile i)] | 72 | getFiles (TestSpec t root (Single i)) = return $ [root ++ (intToFile i)] | 72 | false | false | 0 | 9 | 12 | 42 | 21 | 21 | null | null |
Michaelt293/Lipid-Haskell | src/Lipid/Parsers/KnownSn/Glycerolipid.hs | gpl-3.0 | tgDeltaP :: Parser (TG DeltaPosition)
tgDeltaP = tgP radylDeltaP | 64 | tgDeltaP :: Parser (TG DeltaPosition)
tgDeltaP = tgP radylDeltaP | 64 | tgDeltaP = tgP radylDeltaP | 26 | false | true | 0 | 7 | 8 | 23 | 11 | 12 | null | null |
dorchard/gram_lang | frontend/src/Language/Granule/Checker/Flatten.hs | bsd-3-clause | mguCoeffectTypes' s (isInterval -> Just t') t = do
-- See if we can recursively unify inside an interval
-- This is done in a local type checking context as `mguCoeffectType` can cause unification
coeffecTyUpper <- mguCoeffectTypes' s t' t
case coeffecTyUpper of
Just (upperTy, (inj1, inj2)) ->
return $ Just (TyApp (TyCon $ mkId "Interval") upperTy, (inj1', \x -> CInterval (inj2 x) (inj2 x)))
where inj1' = coeffectFold baseCoeffectFold{ cInterval = \c1 c2 -> CInterval (inj1 c1) (inj1 c2) }
Nothing -> return Nothing
-- No way to unify (outer function will take the product) | 613 | mguCoeffectTypes' s (isInterval -> Just t') t = do
-- See if we can recursively unify inside an interval
-- This is done in a local type checking context as `mguCoeffectType` can cause unification
coeffecTyUpper <- mguCoeffectTypes' s t' t
case coeffecTyUpper of
Just (upperTy, (inj1, inj2)) ->
return $ Just (TyApp (TyCon $ mkId "Interval") upperTy, (inj1', \x -> CInterval (inj2 x) (inj2 x)))
where inj1' = coeffectFold baseCoeffectFold{ cInterval = \c1 c2 -> CInterval (inj1 c1) (inj1 c2) }
Nothing -> return Nothing
-- No way to unify (outer function will take the product) | 613 | mguCoeffectTypes' s (isInterval -> Just t') t = do
-- See if we can recursively unify inside an interval
-- This is done in a local type checking context as `mguCoeffectType` can cause unification
coeffecTyUpper <- mguCoeffectTypes' s t' t
case coeffecTyUpper of
Just (upperTy, (inj1, inj2)) ->
return $ Just (TyApp (TyCon $ mkId "Interval") upperTy, (inj1', \x -> CInterval (inj2 x) (inj2 x)))
where inj1' = coeffectFold baseCoeffectFold{ cInterval = \c1 c2 -> CInterval (inj1 c1) (inj1 c2) }
Nothing -> return Nothing
-- No way to unify (outer function will take the product) | 613 | false | false | 1 | 19 | 131 | 177 | 90 | 87 | null | null |
brodyberg/LearnHaskell | Web/sqlitetest/PutJSON.hs | mit | renderJValue (JArray a) = "[" ++ values a ++ "]"
where values [] = ""
values vs = intercalate ", " (map renderJValue vs) | 134 | renderJValue (JArray a) = "[" ++ values a ++ "]"
where values [] = ""
values vs = intercalate ", " (map renderJValue vs) | 134 | renderJValue (JArray a) = "[" ++ values a ++ "]"
where values [] = ""
values vs = intercalate ", " (map renderJValue vs) | 134 | false | false | 1 | 7 | 37 | 59 | 28 | 31 | null | null |
fmapfmapfmap/amazonka | amazonka-ec2/gen/Network/AWS/EC2/Types/Product.hs | mpl-2.0 | -- | The name of the placement group.
pgGroupName :: Lens' PlacementGroup (Maybe Text)
pgGroupName = lens _pgGroupName (\ s a -> s{_pgGroupName = a}) | 149 | pgGroupName :: Lens' PlacementGroup (Maybe Text)
pgGroupName = lens _pgGroupName (\ s a -> s{_pgGroupName = a}) | 111 | pgGroupName = lens _pgGroupName (\ s a -> s{_pgGroupName = a}) | 62 | true | true | 0 | 9 | 24 | 46 | 25 | 21 | null | null |
knutwalker/hocker | src/lib/Hocker/Flags.hs | apache-2.0 | parseFlags' :: [String] -> Either FError RunCommand
parseFlags' args =
let (os, as, es) = getOpt Permute options args
opts = foldr ($) (Right mempty) os
fallback = either flags id opts
action = validateActions as fallback
errors = validateErrors es fallback
in do
o <- opts
_ <- errors
a <- action
return $! RunCommand o a
where
validateActions :: [String] -> Flags -> Either FError Action
validateActions [a] = parseAction a
validateActions [] = Left . NoAction
validateActions as = Left . MultipleActions as
parseAction :: String -> Flags -> Either FError Action
parseAction s o = maybe (Left (UnknownAction s o)) Right $ readAction s
readAction :: String -> Maybe Action
readAction s = case map toLower s of
"start" -> Just Start
"stop" -> Just Stop
"restart" -> Just Restart
"status" -> Just Status
"logs" -> Just Logs
_ -> Nothing
validateErrors :: [String] -> Flags -> Either FError ()
validateErrors [] _ = Right ()
validateErrors es o = Left (ParseError es o) | 1,141 | parseFlags' :: [String] -> Either FError RunCommand
parseFlags' args =
let (os, as, es) = getOpt Permute options args
opts = foldr ($) (Right mempty) os
fallback = either flags id opts
action = validateActions as fallback
errors = validateErrors es fallback
in do
o <- opts
_ <- errors
a <- action
return $! RunCommand o a
where
validateActions :: [String] -> Flags -> Either FError Action
validateActions [a] = parseAction a
validateActions [] = Left . NoAction
validateActions as = Left . MultipleActions as
parseAction :: String -> Flags -> Either FError Action
parseAction s o = maybe (Left (UnknownAction s o)) Right $ readAction s
readAction :: String -> Maybe Action
readAction s = case map toLower s of
"start" -> Just Start
"stop" -> Just Stop
"restart" -> Just Restart
"status" -> Just Status
"logs" -> Just Logs
_ -> Nothing
validateErrors :: [String] -> Flags -> Either FError ()
validateErrors [] _ = Right ()
validateErrors es o = Left (ParseError es o) | 1,141 | parseFlags' args =
let (os, as, es) = getOpt Permute options args
opts = foldr ($) (Right mempty) os
fallback = either flags id opts
action = validateActions as fallback
errors = validateErrors es fallback
in do
o <- opts
_ <- errors
a <- action
return $! RunCommand o a
where
validateActions :: [String] -> Flags -> Either FError Action
validateActions [a] = parseAction a
validateActions [] = Left . NoAction
validateActions as = Left . MultipleActions as
parseAction :: String -> Flags -> Either FError Action
parseAction s o = maybe (Left (UnknownAction s o)) Right $ readAction s
readAction :: String -> Maybe Action
readAction s = case map toLower s of
"start" -> Just Start
"stop" -> Just Stop
"restart" -> Just Restart
"status" -> Just Status
"logs" -> Just Logs
_ -> Nothing
validateErrors :: [String] -> Flags -> Either FError ()
validateErrors [] _ = Right ()
validateErrors es o = Left (ParseError es o) | 1,089 | false | true | 5 | 11 | 341 | 430 | 198 | 232 | null | null |
opqdonut/riot | Riot/Actions.hs | gpl-2.0 | move_tagged_after = Action "move tagged entries after current entry"
e_move_tagged_after | 121 | move_tagged_after = Action "move tagged entries after current entry"
e_move_tagged_after | 121 | move_tagged_after = Action "move tagged entries after current entry"
e_move_tagged_after | 121 | false | false | 1 | 5 | 42 | 14 | 5 | 9 | null | null |
rueshyna/gogol | gogol-deploymentmanager/gen/Network/Google/DeploymentManager/Types/Product.hs | mpl-2.0 | -- | [Output Only] Unique identifier for the resource; defined by the server.
rId :: Lens' Resource (Maybe Word64)
rId
= lens _rId (\ s a -> s{_rId = a}) . mapping _Coerce | 173 | rId :: Lens' Resource (Maybe Word64)
rId
= lens _rId (\ s a -> s{_rId = a}) . mapping _Coerce | 95 | rId
= lens _rId (\ s a -> s{_rId = a}) . mapping _Coerce | 58 | true | true | 0 | 10 | 34 | 55 | 28 | 27 | null | null |
AlexeyRaga/eta | compiler/ETA/Prelude/PrimOp.hs | bsd-3-clause | primOpHasSideEffects WriteOffAddrOp_Char = True | 47 | primOpHasSideEffects WriteOffAddrOp_Char = True | 47 | primOpHasSideEffects WriteOffAddrOp_Char = True | 47 | false | false | 0 | 4 | 3 | 10 | 4 | 6 | null | null |
zchn/ethereum-analyzer | ethereum-analyzer-deps/src/Blockchain/ExtWord.hs | apache-2.0 | bytesToWord160 _ =
error "bytesToWord128 was called with the wrong number of bytes" | 85 | bytesToWord160 _ =
error "bytesToWord128 was called with the wrong number of bytes" | 85 | bytesToWord160 _ =
error "bytesToWord128 was called with the wrong number of bytes" | 85 | false | false | 0 | 5 | 14 | 12 | 5 | 7 | null | null |
dikmax/haskell-blog | src/HtmlTags.hs | bsd-2-clause | --
-- img element
--
img :: Node
img = Element "img" [] [] | 58 | img :: Node
img = Element "img" [] [] | 37 | img = Element "img" [] [] | 25 | true | true | 0 | 6 | 13 | 31 | 15 | 16 | null | null |
ahodgen/archer-calc | src/BuiltIn/Date.hs | bsd-2-clause | now :: [Value] -> Interpreter EvalError Value
now [] = return . VDate $ unsafePerformIO T.getCurrentTime | 104 | now :: [Value] -> Interpreter EvalError Value
now [] = return . VDate $ unsafePerformIO T.getCurrentTime | 104 | now [] = return . VDate $ unsafePerformIO T.getCurrentTime | 58 | false | true | 3 | 8 | 15 | 47 | 21 | 26 | null | null |
ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/GT_7.hs | mit | compare0 x y MyTrue = GT | 24 | compare0 x y MyTrue = GT | 24 | compare0 x y MyTrue = GT | 24 | false | false | 1 | 5 | 5 | 19 | 6 | 13 | null | null |
headprogrammingczar/cabal | cabal-install/Distribution/Solver/Modular/PSQ.hs | bsd-3-clause | casePSQ :: PSQ k a -> r -> (k -> a -> PSQ k a -> r) -> r
casePSQ (PSQ xs) n c =
case xs of
[] -> n
(k, v) : ys -> c k v (PSQ ys) | 147 | casePSQ :: PSQ k a -> r -> (k -> a -> PSQ k a -> r) -> r
casePSQ (PSQ xs) n c =
case xs of
[] -> n
(k, v) : ys -> c k v (PSQ ys) | 147 | casePSQ (PSQ xs) n c =
case xs of
[] -> n
(k, v) : ys -> c k v (PSQ ys) | 90 | false | true | 0 | 12 | 59 | 102 | 51 | 51 | null | null |
Persi/shellcheck | ShellCheck/Analytics.hs | gpl-3.0 | checkUnquotedN _ _ = return () | 30 | checkUnquotedN _ _ = return () | 30 | checkUnquotedN _ _ = return () | 30 | false | false | 0 | 6 | 5 | 16 | 7 | 9 | null | null |
shangaslammi/hdrawgl | src/Graphics/DrawGL/Transform.hs | mit | transformVertices :: (Vertex -> Vertex) -> (Shape -> Shape)
transformVertices f = Transformed (second f) | 104 | transformVertices :: (Vertex -> Vertex) -> (Shape -> Shape)
transformVertices f = Transformed (second f) | 104 | transformVertices f = Transformed (second f) | 44 | false | true | 0 | 9 | 14 | 46 | 22 | 24 | null | null |
nrolland/persistentBHStyle | src/Query.hs | bsd-3-clause | getProductsPage n = P.selectList [ ] [ P.Asc ProductPrice, P.LimitTo 10, P.OffsetBy ((n-1)*10) ] | 96 | getProductsPage n = P.selectList [ ] [ P.Asc ProductPrice, P.LimitTo 10, P.OffsetBy ((n-1)*10) ] | 96 | getProductsPage n = P.selectList [ ] [ P.Asc ProductPrice, P.LimitTo 10, P.OffsetBy ((n-1)*10) ] | 96 | false | false | 0 | 11 | 13 | 56 | 28 | 28 | null | null |
nyson/haste-compiler | src/Haste/CodeGen.hs | bsd-3-clause | isNewtypeLike :: GHC.Var -> Bool
isNewtypeLike v = maybe False id $ do
(tycon, _) <- splitTyConApp_maybe (varType v)
case tyConDataCons tycon of
[c] -> case dataConRepArgTys c of
[t] -> return (isUnLiftedType t)
_ -> return False
_ -> return False
-- | Returns True if the given Var is an unboxed tuple with a single element
-- after any represenationless elements are discarded. | 410 | isNewtypeLike :: GHC.Var -> Bool
isNewtypeLike v = maybe False id $ do
(tycon, _) <- splitTyConApp_maybe (varType v)
case tyConDataCons tycon of
[c] -> case dataConRepArgTys c of
[t] -> return (isUnLiftedType t)
_ -> return False
_ -> return False
-- | Returns True if the given Var is an unboxed tuple with a single element
-- after any represenationless elements are discarded. | 410 | isNewtypeLike v = maybe False id $ do
(tycon, _) <- splitTyConApp_maybe (varType v)
case tyConDataCons tycon of
[c] -> case dataConRepArgTys c of
[t] -> return (isUnLiftedType t)
_ -> return False
_ -> return False
-- | Returns True if the given Var is an unboxed tuple with a single element
-- after any represenationless elements are discarded. | 377 | false | true | 2 | 16 | 95 | 123 | 57 | 66 | null | null |
shlevy/arithmoi | Math/NumberTheory/Primes/Factorisation/Utils.hs | mit | ppDivSum (p,k) = (p^(k+1)-1) `quot` (p-1) | 41 | ppDivSum (p,k) = (p^(k+1)-1) `quot` (p-1) | 41 | ppDivSum (p,k) = (p^(k+1)-1) `quot` (p-1) | 41 | false | false | 0 | 10 | 5 | 46 | 26 | 20 | null | null |
edom/ptt | src/Parse/Haskell/Lex.hs | apache-2.0 | (<:>) = A.liftA2 (:) | 20 | (<:>) = A.liftA2 (:) | 20 | (<:>) = A.liftA2 (:) | 20 | false | false | 0 | 6 | 3 | 15 | 9 | 6 | null | null |
cryptica/slapnet | src/Solver/LivenessInvariant.hs | gpl-3.0 | cutNames :: PetriNet -> NamedCut -> [String]
cutNames net (_, c) =
["@yone", "@comp0"] ++
map placeName (places net) ++
map fst c | 153 | cutNames :: PetriNet -> NamedCut -> [String]
cutNames net (_, c) =
["@yone", "@comp0"] ++
map placeName (places net) ++
map fst c | 153 | cutNames net (_, c) =
["@yone", "@comp0"] ++
map placeName (places net) ++
map fst c | 108 | false | true | 2 | 9 | 46 | 72 | 34 | 38 | null | null |
JenniferWang/incremental-haskell | src/Kind.hs | mit | iteriChildren _ _ = [] | 45 | iteriChildren _ _ = [] | 45 | iteriChildren _ _ = [] | 45 | false | false | 0 | 5 | 27 | 13 | 6 | 7 | null | null |
rueshyna/gogol | gogol-compute/gen/Network/Google/Compute/Types/Product.hs | mpl-2.0 | -- | [Output Only] Information about the last attempt to create or delete the
-- instance.
miLastAttempt :: Lens' ManagedInstance (Maybe ManagedInstanceLastAttempt)
miLastAttempt
= lens _miLastAttempt
(\ s a -> s{_miLastAttempt = a}) | 241 | miLastAttempt :: Lens' ManagedInstance (Maybe ManagedInstanceLastAttempt)
miLastAttempt
= lens _miLastAttempt
(\ s a -> s{_miLastAttempt = a}) | 150 | miLastAttempt
= lens _miLastAttempt
(\ s a -> s{_miLastAttempt = a}) | 76 | true | true | 2 | 9 | 40 | 56 | 26 | 30 | null | null |
jd823592/puppeteer | src/Puppet/Master/Worker.hs | mit | ask :: MonadIO m => Worker m -> m a -> IO a
ask w a = do
ref <- newEmptyMVar
writeChan (requests w) $ liftIO . putMVar ref =<< a
takeMVar ref | 153 | ask :: MonadIO m => Worker m -> m a -> IO a
ask w a = do
ref <- newEmptyMVar
writeChan (requests w) $ liftIO . putMVar ref =<< a
takeMVar ref | 153 | ask w a = do
ref <- newEmptyMVar
writeChan (requests w) $ liftIO . putMVar ref =<< a
takeMVar ref | 109 | false | true | 0 | 13 | 44 | 85 | 36 | 49 | null | null |
jrahm/DuckTest | src/DuckTest/Internal/State.hs | bsd-2-clause | returnHit :: InternalState e -> Bool
returnHit (InternalState _ _ True) = True | 78 | returnHit :: InternalState e -> Bool
returnHit (InternalState _ _ True) = True | 78 | returnHit (InternalState _ _ True) = True | 41 | false | true | 0 | 9 | 12 | 37 | 16 | 21 | null | null |
CristhianMotoche/scion | server/Scion/Server/Protocol.hs | bsd-3-clause | putString :: String -> ShowS
putString s = showString (show s) | 62 | putString :: String -> ShowS
putString s = showString (show s) | 62 | putString s = showString (show s) | 33 | false | true | 0 | 7 | 10 | 27 | 13 | 14 | null | null |
alexander-at-github/eta | compiler/ETA/Types/TyCon.hs | bsd-3-clause | isVoidRep :: PrimRep -> Bool
isVoidRep VoidRep = True | 53 | isVoidRep :: PrimRep -> Bool
isVoidRep VoidRep = True | 53 | isVoidRep VoidRep = True | 24 | false | true | 0 | 5 | 8 | 18 | 9 | 9 | null | null |
brendanhay/gogol | gogol-iap/gen/Network/Google/Resource/IAP/SetIAMPolicy.hs | mpl-2.0 | -- | REQUIRED: The resource for which the policy is being specified. See the
-- operation documentation for the appropriate value for this field.
sipResource :: Lens' SetIAMPolicy Text
sipResource
= lens _sipResource (\ s a -> s{_sipResource = a}) | 249 | sipResource :: Lens' SetIAMPolicy Text
sipResource
= lens _sipResource (\ s a -> s{_sipResource = a}) | 103 | sipResource
= lens _sipResource (\ s a -> s{_sipResource = a}) | 64 | true | true | 0 | 9 | 41 | 43 | 23 | 20 | null | null |
erochest/whatisdh | Model.hs | bsd-2-clause | getContent :: DocumentInfo -> (T.Text, T.Text)
getContent dinfo = (content, hash)
where content = maybe "" id . listToMaybe $ catMaybes
[ unTextarea <$> diContent dinfo
, (decodeUtf8 . toStrict . fileContent) <$> diFile dinfo
]
hash = makeHash content | 313 | getContent :: DocumentInfo -> (T.Text, T.Text)
getContent dinfo = (content, hash)
where content = maybe "" id . listToMaybe $ catMaybes
[ unTextarea <$> diContent dinfo
, (decodeUtf8 . toStrict . fileContent) <$> diFile dinfo
]
hash = makeHash content | 313 | getContent dinfo = (content, hash)
where content = maybe "" id . listToMaybe $ catMaybes
[ unTextarea <$> diContent dinfo
, (decodeUtf8 . toStrict . fileContent) <$> diFile dinfo
]
hash = makeHash content | 266 | false | true | 1 | 11 | 101 | 97 | 50 | 47 | null | null |
brendanhay/gogol | gogol-cloudprivatecatalogproducer/gen/Network/Google/CloudPrivateCatalogProducer/Types/Product.hs | mpl-2.0 | -- | Required. The parent resource name of the catalog, which can\'t be
-- changed after a catalog is created. It can only be an organization.
-- Values are of the form
-- \`\/\/cloudresourcemanager.googleapis.com\/organizations\/\`. Maximum
-- 256 characters in length.
gcpvcParent :: Lens' GoogleCloudPrivatecatalogproducerV1beta1Catalog (Maybe Text)
gcpvcParent
= lens _gcpvcParent (\ s a -> s{_gcpvcParent = a}) | 417 | gcpvcParent :: Lens' GoogleCloudPrivatecatalogproducerV1beta1Catalog (Maybe Text)
gcpvcParent
= lens _gcpvcParent (\ s a -> s{_gcpvcParent = a}) | 146 | gcpvcParent
= lens _gcpvcParent (\ s a -> s{_gcpvcParent = a}) | 64 | true | true | 1 | 9 | 58 | 56 | 29 | 27 | null | null |
vrom911/Compiler | src/Compiler/Rum/Internal/ToString.hs | mit | stmtToStr n IfElse{..} = tab n <> "if" <> tab (succ n) <> exprToStr ifCond <>
tab n <> "then" <> progToStr (succ n) trueAct <>
tab n <> "else" <> progToStr (succ n) falseAct <>
tab n <> "fi" | 287 | stmtToStr n IfElse{..} = tab n <> "if" <> tab (succ n) <> exprToStr ifCond <>
tab n <> "then" <> progToStr (succ n) trueAct <>
tab n <> "else" <> progToStr (succ n) falseAct <>
tab n <> "fi" | 287 | stmtToStr n IfElse{..} = tab n <> "if" <> tab (succ n) <> exprToStr ifCond <>
tab n <> "then" <> progToStr (succ n) trueAct <>
tab n <> "else" <> progToStr (succ n) falseAct <>
tab n <> "fi" | 287 | false | false | 0 | 17 | 136 | 109 | 49 | 60 | null | null |
GaloisInc/ivory-backend-acl2 | src/Ivory/Compile/ACL2/attic/ACL2ConvertRTL.hs | bsd-3-clause | replaceNth n l v = call "replace-nth" [n, l, v] | 47 | replaceNth n l v = call "replace-nth" [n, l, v] | 47 | replaceNth n l v = call "replace-nth" [n, l, v] | 47 | false | false | 1 | 6 | 9 | 33 | 14 | 19 | null | null |
jdubrule/bond | compiler/src/Language/Bond/Codegen/TypeMapping.hs | mit | javaBoxedType BT_UInt64 = pure "java.lang.Long" | 47 | javaBoxedType BT_UInt64 = pure "java.lang.Long" | 47 | javaBoxedType BT_UInt64 = pure "java.lang.Long" | 47 | false | false | 0 | 5 | 4 | 12 | 5 | 7 | null | null |
keithodulaigh/Hets | CspCASL/Morphism.hs | gpl-2.0 | mapCommAlphaAux :: Sort_map -> ChanMap -> CommAlpha -> CommAlpha
mapCommAlphaAux sm = Set.map . mapCommTypeAux sm | 113 | mapCommAlphaAux :: Sort_map -> ChanMap -> CommAlpha -> CommAlpha
mapCommAlphaAux sm = Set.map . mapCommTypeAux sm | 113 | mapCommAlphaAux sm = Set.map . mapCommTypeAux sm | 48 | false | true | 0 | 7 | 15 | 35 | 17 | 18 | null | null |
taktoa/SatOpt | Generate.hs | mit | -- Library
createLibraryDirectory :: String -> IO ()
createLibraryDirectory = createDirectory . libraryPath | 108 | createLibraryDirectory :: String -> IO ()
createLibraryDirectory = createDirectory . libraryPath | 96 | createLibraryDirectory = createDirectory . libraryPath | 54 | true | true | 0 | 7 | 13 | 25 | 13 | 12 | null | null |
nomeata/ghc | compiler/cmm/CmmRewriteAssignments.hs | bsd-3-clause | -- area, offset, width
overlaps :: CallSubArea -> CallSubArea -> Bool
overlaps (a, _, _) (a', _, _) | a /= a' = False | 117 | overlaps :: CallSubArea -> CallSubArea -> Bool
overlaps (a, _, _) (a', _, _) | a /= a' = False | 94 | overlaps (a, _, _) (a', _, _) | a /= a' = False | 47 | true | true | 0 | 8 | 23 | 53 | 29 | 24 | null | null |
fmthoma/ghc | compiler/typecheck/TcType.hs | bsd-3-clause | pprTcTyVarDetails (MetaTv { mtv_info = info, mtv_tclvl = tclvl })
= pp_info <> colon <> ppr tclvl
where
pp_info = case info of
ReturnTv -> ptext (sLit "ret")
TauTv True -> ptext (sLit "twc")
TauTv False -> ptext (sLit "tau")
SigTv -> ptext (sLit "sig")
FlatMetaTv -> ptext (sLit "fuv") | 384 | pprTcTyVarDetails (MetaTv { mtv_info = info, mtv_tclvl = tclvl })
= pp_info <> colon <> ppr tclvl
where
pp_info = case info of
ReturnTv -> ptext (sLit "ret")
TauTv True -> ptext (sLit "twc")
TauTv False -> ptext (sLit "tau")
SigTv -> ptext (sLit "sig")
FlatMetaTv -> ptext (sLit "fuv") | 384 | pprTcTyVarDetails (MetaTv { mtv_info = info, mtv_tclvl = tclvl })
= pp_info <> colon <> ppr tclvl
where
pp_info = case info of
ReturnTv -> ptext (sLit "ret")
TauTv True -> ptext (sLit "twc")
TauTv False -> ptext (sLit "tau")
SigTv -> ptext (sLit "sig")
FlatMetaTv -> ptext (sLit "fuv") | 384 | false | false | 0 | 10 | 148 | 131 | 63 | 68 | null | null |
ctford/Idris-Elba-dev | src/Idris/Core/Elaborate.hs | bsd-3-clause | get_instances :: Elab' aux [Name]
get_instances = do ES p _ _ <- get
return $! (instances (fst p))
-- given a desired hole name, return a unique hole name | 174 | get_instances :: Elab' aux [Name]
get_instances = do ES p _ _ <- get
return $! (instances (fst p))
-- given a desired hole name, return a unique hole name | 174 | get_instances = do ES p _ _ <- get
return $! (instances (fst p))
-- given a desired hole name, return a unique hole name | 140 | false | true | 1 | 12 | 49 | 57 | 26 | 31 | null | null |
hsyl20/HViperVM | lib/ViperVM/Backends/OpenCL/Query.hs | lgpl-3.0 | -- | Max size in bytes of a constant buffer allocation. The minimum value is
-- 64 KB.
--
-- This function execute OpenCL clGetDeviceInfo with
-- 'CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE'.
clGetDeviceMaxConstantBufferSize :: OpenCLLibrary -> CLDeviceID -> IO CLulong
clGetDeviceMaxConstantBufferSize lib = (getDeviceInfoUlong lib) . getCLValue $ CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE | 376 | clGetDeviceMaxConstantBufferSize :: OpenCLLibrary -> CLDeviceID -> IO CLulong
clGetDeviceMaxConstantBufferSize lib = (getDeviceInfoUlong lib) . getCLValue $ CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE | 191 | clGetDeviceMaxConstantBufferSize lib = (getDeviceInfoUlong lib) . getCLValue $ CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE | 113 | true | true | 0 | 8 | 45 | 44 | 24 | 20 | null | null |
roberth/uu-helium | test/typeerrors/Examples/RightSection.hs | gpl-3.0 | test :: [Int]
test = filter (False ==) [1..10] | 46 | test :: [Int]
test = filter (False ==) [1..10] | 46 | test = filter (False ==) [1..10] | 32 | false | true | 0 | 6 | 8 | 28 | 16 | 12 | null | null |
mgold/Elm | src/AST/Expression/Canonical.hs | bsd-3-clause | toSortedDefs :: Expr -> SortedDefs
toSortedDefs (A.A _ expr) =
case expr of
General.Let defs body ->
foldr defCons (toSortedDefs body) defs
_ ->
NoMain [] | 177 | toSortedDefs :: Expr -> SortedDefs
toSortedDefs (A.A _ expr) =
case expr of
General.Let defs body ->
foldr defCons (toSortedDefs body) defs
_ ->
NoMain [] | 177 | toSortedDefs (A.A _ expr) =
case expr of
General.Let defs body ->
foldr defCons (toSortedDefs body) defs
_ ->
NoMain [] | 142 | false | true | 3 | 8 | 48 | 68 | 33 | 35 | null | null |
nomeata/ghc | compiler/cmm/PprCmmExpr.hs | bsd-3-clause | genMachOp :: MachOp -> [CmmExpr] -> SDoc
genMachOp mop args
| Just doc <- infixMachOp mop = case args of
-- dyadic
[x,y] -> pprExpr9 x <+> doc <+> pprExpr9 y
-- unary
[x] -> doc <> pprExpr9 x
_ -> pprTrace "PprCmm.genMachOp: machop with strange number of args"
(pprMachOp mop <+>
parens (hcat $ punctuate comma (map pprExpr args)))
empty
| isJust (infixMachOp1 mop)
|| isJust (infixMachOp7 mop)
|| isJust (infixMachOp8 mop) = parens (pprExpr (CmmMachOp mop args))
| otherwise = char '%' <> ppr_op <> parens (commafy (map pprExpr args))
where ppr_op = text (map (\c -> if c == ' ' then '_' else c)
(show mop))
-- replace spaces in (show mop) with underscores,
--
-- Unsigned ops on the word size of the machine get nice symbols.
-- All else get dumped in their ugly format.
-- | 979 | genMachOp :: MachOp -> [CmmExpr] -> SDoc
genMachOp mop args
| Just doc <- infixMachOp mop = case args of
-- dyadic
[x,y] -> pprExpr9 x <+> doc <+> pprExpr9 y
-- unary
[x] -> doc <> pprExpr9 x
_ -> pprTrace "PprCmm.genMachOp: machop with strange number of args"
(pprMachOp mop <+>
parens (hcat $ punctuate comma (map pprExpr args)))
empty
| isJust (infixMachOp1 mop)
|| isJust (infixMachOp7 mop)
|| isJust (infixMachOp8 mop) = parens (pprExpr (CmmMachOp mop args))
| otherwise = char '%' <> ppr_op <> parens (commafy (map pprExpr args))
where ppr_op = text (map (\c -> if c == ' ' then '_' else c)
(show mop))
-- replace spaces in (show mop) with underscores,
--
-- Unsigned ops on the word size of the machine get nice symbols.
-- All else get dumped in their ugly format.
-- | 979 | genMachOp mop args
| Just doc <- infixMachOp mop = case args of
-- dyadic
[x,y] -> pprExpr9 x <+> doc <+> pprExpr9 y
-- unary
[x] -> doc <> pprExpr9 x
_ -> pprTrace "PprCmm.genMachOp: machop with strange number of args"
(pprMachOp mop <+>
parens (hcat $ punctuate comma (map pprExpr args)))
empty
| isJust (infixMachOp1 mop)
|| isJust (infixMachOp7 mop)
|| isJust (infixMachOp8 mop) = parens (pprExpr (CmmMachOp mop args))
| otherwise = char '%' <> ppr_op <> parens (commafy (map pprExpr args))
where ppr_op = text (map (\c -> if c == ' ' then '_' else c)
(show mop))
-- replace spaces in (show mop) with underscores,
--
-- Unsigned ops on the word size of the machine get nice symbols.
-- All else get dumped in their ugly format.
-- | 938 | false | true | 1 | 17 | 345 | 297 | 144 | 153 | null | null |
kowey/conceptdiagram-examples | conceptdiagram-examples.hs | bsd-3-clause | curveDog :: Diagram B R2
curveDog = namedCurve "Dog" # named "dog" | 66 | curveDog :: Diagram B R2
curveDog = namedCurve "Dog" # named "dog" | 66 | curveDog = namedCurve "Dog" # named "dog" | 41 | false | true | 0 | 6 | 11 | 26 | 12 | 14 | null | null |
tavisrudd/ghcjs-base | JavaScript/TypedArray/DataView.hs | mit | readInt16LE, readInt16BE, unsafeReadInt16LE, unsafeReadInt16BE
:: Int -> MutableDataView -> IO Int16
readInt16LE idx dv = IO (I.js_m_getInt16LE idx dv) | 165 | readInt16LE, readInt16BE, unsafeReadInt16LE, unsafeReadInt16BE
:: Int -> MutableDataView -> IO Int16
readInt16LE idx dv = IO (I.js_m_getInt16LE idx dv) | 165 | readInt16LE idx dv = IO (I.js_m_getInt16LE idx dv) | 62 | false | true | 4 | 8 | 32 | 52 | 25 | 27 | null | null |
hvr/jhc | regress/tests/6_fixed_bugs/Tree.hs | mit | leaves :: Tree -> Int
leaves Leaf = 1 | 56 | leaves :: Tree -> Int
leaves Leaf = 1 | 56 | leaves Leaf = 1 | 22 | false | true | 0 | 5 | 27 | 18 | 9 | 9 | null | null |
alphalambda/hsmath | src/Learn/Geometry/Drawing.hs | gpl-2.0 | draw = P.pictures | 17 | draw = P.pictures | 17 | draw = P.pictures | 17 | false | false | 1 | 6 | 2 | 12 | 4 | 8 | null | null |
ksaveljev/chip-8-emulator | Chip8/Emulator.hs | mit | execute (RND vx byte) = do
rnd <- randomWord8
store (Register vx) (MemoryValue8 $ rnd .&. byte) | 103 | execute (RND vx byte) = do
rnd <- randomWord8
store (Register vx) (MemoryValue8 $ rnd .&. byte) | 103 | execute (RND vx byte) = do
rnd <- randomWord8
store (Register vx) (MemoryValue8 $ rnd .&. byte) | 103 | false | false | 0 | 10 | 24 | 49 | 23 | 26 | null | null |
jb55/language-javascript | src/Language/JavaScript/Parser/AST.hs | bsd-3-clause | showStrippedNode (JSFunctionBody xs) = "JSFunctionBody " ++ sss xs | 66 | showStrippedNode (JSFunctionBody xs) = "JSFunctionBody " ++ sss xs | 66 | showStrippedNode (JSFunctionBody xs) = "JSFunctionBody " ++ sss xs | 66 | false | false | 0 | 6 | 8 | 23 | 10 | 13 | null | null |
KommuSoft/dep-software | Dep.Algorithms.Comb.hs | gpl-3.0 | scrapeMin n (ThDirect d) = scrapeMin (n+1) d | 44 | scrapeMin n (ThDirect d) = scrapeMin (n+1) d | 44 | scrapeMin n (ThDirect d) = scrapeMin (n+1) d | 44 | false | false | 0 | 7 | 7 | 29 | 14 | 15 | null | null |
da-x/ghc | compiler/utils/Outputable.hs | bsd-3-clause | keyword :: SDoc -> SDoc
keyword = bold | 38 | keyword :: SDoc -> SDoc
keyword = bold | 38 | keyword = bold | 14 | false | true | 0 | 5 | 7 | 15 | 8 | 7 | null | null |
input-output-hk/pos-haskell-prototype | wallet/test/integration/Test/Integration/Framework/DSL.hs | mit | addresses :: HasType [WalletAddress] s => Lens' s [WalletAddress]
addresses = typed | 83 | addresses :: HasType [WalletAddress] s => Lens' s [WalletAddress]
addresses = typed | 83 | addresses = typed | 17 | false | true | 0 | 7 | 11 | 31 | 16 | 15 | null | null |
abakst/liquidhaskell | benchmarks/vector-0.10.0.1/Data/Vector/Unboxed.hs | bsd-3-clause | unsafeTail = G.unsafeTail | 25 | unsafeTail = G.unsafeTail | 25 | unsafeTail = G.unsafeTail | 25 | false | false | 1 | 6 | 2 | 12 | 4 | 8 | null | null |
sdiehl/ghc | compiler/ghci/ByteCodeGen.hs | bsd-3-clause | runBc :: HscEnv -> UniqSupply -> Module -> Maybe ModBreaks
-> IdEnv (RemotePtr ())
-> BcM r
-> IO (BcM_State, r)
runBc hsc_env us this_mod modBreaks topStrings (BcM m)
= m (BcM_State hsc_env us this_mod 0 [] modBreaks IntMap.empty topStrings) | 263 | runBc :: HscEnv -> UniqSupply -> Module -> Maybe ModBreaks
-> IdEnv (RemotePtr ())
-> BcM r
-> IO (BcM_State, r)
runBc hsc_env us this_mod modBreaks topStrings (BcM m)
= m (BcM_State hsc_env us this_mod 0 [] modBreaks IntMap.empty topStrings) | 263 | runBc hsc_env us this_mod modBreaks topStrings (BcM m)
= m (BcM_State hsc_env us this_mod 0 [] modBreaks IntMap.empty topStrings) | 132 | false | true | 0 | 14 | 60 | 112 | 53 | 59 | null | null |
ComputationWithBoundedResources/tct-jbc | src/Tct/Jbc/Config.hs | bsd-3-clause | jbcUpdate :: JbcConfig -> JbcOptions -> JbcConfig
jbcUpdate cfg (JbcOptions Nothing) = cfg | 97 | jbcUpdate :: JbcConfig -> JbcOptions -> JbcConfig
jbcUpdate cfg (JbcOptions Nothing) = cfg | 97 | jbcUpdate cfg (JbcOptions Nothing) = cfg | 47 | false | true | 0 | 7 | 19 | 30 | 15 | 15 | null | null |
BlackBrane/quantum-random-numbers | src-lib/Quantum/Random/Store.hs | mit | display_ Nothing ws = getDefaultStyle >>= flip display ws | 62 | display_ Nothing ws = getDefaultStyle >>= flip display ws | 62 | display_ Nothing ws = getDefaultStyle >>= flip display ws | 62 | false | false | 0 | 6 | 13 | 21 | 9 | 12 | null | null |
amccausl/Swish | Swish/HaskellRDF/GraphTest.hs | lgpl-2.1 | p2 = LF "p2" | 12 | p2 = LF "p2" | 12 | p2 = LF "p2" | 12 | false | false | 1 | 5 | 3 | 12 | 4 | 8 | null | null |
fhaust/aer-utils | src/Data/Gabor.hs | mit | evalGabor (Gabor λ θ ψ σ γ ox oy) x y = gabor λ θ ψ σ γ (x-ox) (y-oy) | 69 | evalGabor (Gabor λ θ ψ σ γ ox oy) x y = gabor λ θ ψ σ γ (x-ox) (y-oy) | 69 | evalGabor (Gabor λ θ ψ σ γ ox oy) x y = gabor λ θ ψ σ γ (x-ox) (y-oy) | 69 | false | false | 0 | 7 | 19 | 60 | 30 | 30 | null | null |
alexander-at-github/eta | libraries/base/GHC/Event/TimerManager.hs | bsd-3-clause | -- #endif
-- | Create a new event manager.
new :: IO TimerManager
new = newWith =<< newDefaultBackend | 102 | new :: IO TimerManager
new = newWith =<< newDefaultBackend | 58 | new = newWith =<< newDefaultBackend | 35 | true | true | 0 | 5 | 18 | 20 | 11 | 9 | null | null |
darnuria/Yasc | Evaluation.hs | mit | evaluating _ badForm =
throwError (BadSpecialForm "Unrecognized special form" badForm) | 88 | evaluating _ badForm =
throwError (BadSpecialForm "Unrecognized special form" badForm) | 88 | evaluating _ badForm =
throwError (BadSpecialForm "Unrecognized special form" badForm) | 88 | false | false | 0 | 7 | 11 | 22 | 10 | 12 | null | null |
romanb/amazonka | amazonka-ec2/gen/Network/AWS/EC2/Types.hs | mpl-2.0 | -- | The reason code for the Spot Instance state change.
sisfCode :: Lens' SpotInstanceStateFault (Maybe Text)
sisfCode = lens _sisfCode (\s a -> s { _sisfCode = a }) | 166 | sisfCode :: Lens' SpotInstanceStateFault (Maybe Text)
sisfCode = lens _sisfCode (\s a -> s { _sisfCode = a }) | 109 | sisfCode = lens _sisfCode (\s a -> s { _sisfCode = a }) | 55 | true | true | 1 | 9 | 29 | 52 | 25 | 27 | null | null |
shlevy/ghc | compiler/prelude/PrelNames.hs | bsd-3-clause | gHC_RECORDS :: Module
gHC_RECORDS = mkBaseModule (fsLit "GHC.Records") | 70 | gHC_RECORDS :: Module
gHC_RECORDS = mkBaseModule (fsLit "GHC.Records") | 70 | gHC_RECORDS = mkBaseModule (fsLit "GHC.Records") | 48 | false | true | 0 | 7 | 7 | 20 | 10 | 10 | null | null |
vincenthz/cryptonite | Crypto/System/CPU.hs | bsd-3-clause | -- | Options which have been enabled at compile time and are supported by the
-- current CPU.
processorOptions :: [ProcessorOption]
processorOptions = unsafeDoIO $ do
p <- cryptonite_aes_cpu_init
options <- traverse (getOption p) aesOptions
rdrand <- hasRDRand
return (decodeOptions options ++ [ RDRAND | rdrand ])
where
aesOptions = [ AESNI .. PCLMUL ]
getOption p = peekElemOff p . fromEnum
decodeOptions = map toEnum . findIndices (> 0)
| 476 | processorOptions :: [ProcessorOption]
processorOptions = unsafeDoIO $ do
p <- cryptonite_aes_cpu_init
options <- traverse (getOption p) aesOptions
rdrand <- hasRDRand
return (decodeOptions options ++ [ RDRAND | rdrand ])
where
aesOptions = [ AESNI .. PCLMUL ]
getOption p = peekElemOff p . fromEnum
decodeOptions = map toEnum . findIndices (> 0)
| 382 | processorOptions = unsafeDoIO $ do
p <- cryptonite_aes_cpu_init
options <- traverse (getOption p) aesOptions
rdrand <- hasRDRand
return (decodeOptions options ++ [ RDRAND | rdrand ])
where
aesOptions = [ AESNI .. PCLMUL ]
getOption p = peekElemOff p . fromEnum
decodeOptions = map toEnum . findIndices (> 0)
| 344 | true | true | 0 | 12 | 106 | 123 | 62 | 61 | null | null |
fffej/HS-Poker | LookupPatternMatch.hs | bsd-3-clause | getValueFromProduct 489325 = 2986 | 33 | getValueFromProduct 489325 = 2986 | 33 | getValueFromProduct 489325 = 2986 | 33 | false | false | 0 | 5 | 3 | 9 | 4 | 5 | null | null |
kavigupta/Infsabot | Infsabot/MoveConflictResolution/Tests.hs | gpl-3.0 | propConflictOrderIndependence :: (RAAFL, RAAFL) -> Property
propConflictOrderIndependence (x, y) = positionOf x /= positionOf y
==> a == c && b == d
where
(a, b) = conflictsBetween x y
(d, c) = conflictsBetween y x | 234 | propConflictOrderIndependence :: (RAAFL, RAAFL) -> Property
propConflictOrderIndependence (x, y) = positionOf x /= positionOf y
==> a == c && b == d
where
(a, b) = conflictsBetween x y
(d, c) = conflictsBetween y x | 234 | propConflictOrderIndependence (x, y) = positionOf x /= positionOf y
==> a == c && b == d
where
(a, b) = conflictsBetween x y
(d, c) = conflictsBetween y x | 174 | false | true | 3 | 6 | 55 | 99 | 50 | 49 | null | null |
Happy0/snowdrift | Handler/Comment.hs | agpl-3.0 | postCommentApplyTag :: CommentId -> Handler ()
postCommentApplyTag comment_id = do
Entity user_id user <- requireAuth
unless (userCanAddTag user) $
permissionDenied "You must be an established user to add tags"
((result_apply, _), _) <- runFormPost (newCommentTagForm [] [])
case result_apply of
FormSuccess (mproject_tag_ids, mother_tag_ids) -> do
let project_tag_ids = fromMaybe [] mproject_tag_ids
other_tag_ids = fromMaybe [] mother_tag_ids
ok <- runDB $ do
valid_tags <- fetchTagsInDB (project_tag_ids <> other_tag_ids)
if null valid_tags
then return False
else do
void (insertMany $ fmap (\(Entity tag_id _) -> CommentTag comment_id tag_id user_id 1) valid_tags)
return True
unless ok (permissionDenied "Error: Invalid tag ID.")
FormMissing -> error "form missing"
FormFailure errs -> error $ T.unpack $ "Form failed: " <> T.intercalate "; " errs | 1,077 | postCommentApplyTag :: CommentId -> Handler ()
postCommentApplyTag comment_id = do
Entity user_id user <- requireAuth
unless (userCanAddTag user) $
permissionDenied "You must be an established user to add tags"
((result_apply, _), _) <- runFormPost (newCommentTagForm [] [])
case result_apply of
FormSuccess (mproject_tag_ids, mother_tag_ids) -> do
let project_tag_ids = fromMaybe [] mproject_tag_ids
other_tag_ids = fromMaybe [] mother_tag_ids
ok <- runDB $ do
valid_tags <- fetchTagsInDB (project_tag_ids <> other_tag_ids)
if null valid_tags
then return False
else do
void (insertMany $ fmap (\(Entity tag_id _) -> CommentTag comment_id tag_id user_id 1) valid_tags)
return True
unless ok (permissionDenied "Error: Invalid tag ID.")
FormMissing -> error "form missing"
FormFailure errs -> error $ T.unpack $ "Form failed: " <> T.intercalate "; " errs | 1,077 | postCommentApplyTag comment_id = do
Entity user_id user <- requireAuth
unless (userCanAddTag user) $
permissionDenied "You must be an established user to add tags"
((result_apply, _), _) <- runFormPost (newCommentTagForm [] [])
case result_apply of
FormSuccess (mproject_tag_ids, mother_tag_ids) -> do
let project_tag_ids = fromMaybe [] mproject_tag_ids
other_tag_ids = fromMaybe [] mother_tag_ids
ok <- runDB $ do
valid_tags <- fetchTagsInDB (project_tag_ids <> other_tag_ids)
if null valid_tags
then return False
else do
void (insertMany $ fmap (\(Entity tag_id _) -> CommentTag comment_id tag_id user_id 1) valid_tags)
return True
unless ok (permissionDenied "Error: Invalid tag ID.")
FormMissing -> error "form missing"
FormFailure errs -> error $ T.unpack $ "Form failed: " <> T.intercalate "; " errs | 1,030 | false | true | 4 | 15 | 342 | 263 | 131 | 132 | null | null |
brendanhay/gogol | gogol-cloudsearch/gen/Network/Google/CloudSearch/Types/Product.hs | mpl-2.0 | -- | The resource name of the person to provide information about. See
-- People.get from Google People API.
pName :: Lens' Person (Maybe Text)
pName = lens _pName (\ s a -> s{_pName = a}) | 188 | pName :: Lens' Person (Maybe Text)
pName = lens _pName (\ s a -> s{_pName = a}) | 79 | pName = lens _pName (\ s a -> s{_pName = a}) | 44 | true | true | 2 | 9 | 35 | 56 | 26 | 30 | null | null |
goldfirere/units | units-test/Tests/LennardJones.hs | bsd-3-clause | sNine = SS sEight | 20 | sNine = SS sEight | 20 | sNine = SS sEight | 20 | false | false | 0 | 5 | 6 | 9 | 4 | 5 | null | null |
urbanslug/ghc | compiler/main/DynFlags.hs | bsd-3-clause | opt_a :: DynFlags -> [String]
opt_a dflags = sOpt_a (settings dflags) | 85 | opt_a :: DynFlags -> [String]
opt_a dflags = sOpt_a (settings dflags) | 85 | opt_a dflags = sOpt_a (settings dflags) | 39 | false | true | 0 | 8 | 26 | 32 | 15 | 17 | null | null |
narrative/stack | src/Stack/Setup.hs | bsd-3-clause | loadGhcjsEnvConfig :: (MonadIO m, HasHttpManager r, MonadReader r m, HasTerminal r, HasReExec r, HasLogLevel r)
=> Path Abs File -> Path b t -> m EnvConfig
loadGhcjsEnvConfig stackYaml binPath = runInnerStackLoggingT $ do
lc <- loadConfig
(mempty
{ configMonoidInstallGHC = Just True
, configMonoidLocalBinPath = Just (toFilePath binPath)
})
(Just stackYaml)
Nothing
bconfig <- lcLoadBuildConfig lc Nothing
runInnerStackT bconfig $ setupEnv Nothing | 541 | loadGhcjsEnvConfig :: (MonadIO m, HasHttpManager r, MonadReader r m, HasTerminal r, HasReExec r, HasLogLevel r)
=> Path Abs File -> Path b t -> m EnvConfig
loadGhcjsEnvConfig stackYaml binPath = runInnerStackLoggingT $ do
lc <- loadConfig
(mempty
{ configMonoidInstallGHC = Just True
, configMonoidLocalBinPath = Just (toFilePath binPath)
})
(Just stackYaml)
Nothing
bconfig <- lcLoadBuildConfig lc Nothing
runInnerStackT bconfig $ setupEnv Nothing | 541 | loadGhcjsEnvConfig stackYaml binPath = runInnerStackLoggingT $ do
lc <- loadConfig
(mempty
{ configMonoidInstallGHC = Just True
, configMonoidLocalBinPath = Just (toFilePath binPath)
})
(Just stackYaml)
Nothing
bconfig <- lcLoadBuildConfig lc Nothing
runInnerStackT bconfig $ setupEnv Nothing | 364 | false | true | 0 | 16 | 154 | 161 | 76 | 85 | null | null |
dsalisbury/xmobar | src/Plugins/Monitors/Swap.hs | bsd-3-clause | formatSwap :: [Float] -> Monitor [String]
formatSwap (r:xs) = do
d <- getConfigValue decDigits
other <- mapM (showWithColors (showDigits d)) xs
ratio <- showPercentWithColors r
return $ ratio:other | 205 | formatSwap :: [Float] -> Monitor [String]
formatSwap (r:xs) = do
d <- getConfigValue decDigits
other <- mapM (showWithColors (showDigits d)) xs
ratio <- showPercentWithColors r
return $ ratio:other | 205 | formatSwap (r:xs) = do
d <- getConfigValue decDigits
other <- mapM (showWithColors (showDigits d)) xs
ratio <- showPercentWithColors r
return $ ratio:other | 163 | false | true | 0 | 12 | 35 | 94 | 43 | 51 | null | null |
agrafix/legoDSL | NXT/Compiler/Inference.hs | bsd-3-clause | declVar :: Env -> String -> IO ()
declVar envR name =
do varRef <- newIORef Nothing
modifyIORef envR $ \c -> c { env_vars = HM.insert name varRef (env_vars c) } | 171 | declVar :: Env -> String -> IO ()
declVar envR name =
do varRef <- newIORef Nothing
modifyIORef envR $ \c -> c { env_vars = HM.insert name varRef (env_vars c) } | 171 | declVar envR name =
do varRef <- newIORef Nothing
modifyIORef envR $ \c -> c { env_vars = HM.insert name varRef (env_vars c) } | 137 | false | true | 0 | 13 | 42 | 77 | 37 | 40 | null | null |
oldmanmike/ghc | compiler/hsSyn/HsExpr.hs | bsd-3-clause | ppr_expr (OpApp e1 op _ e2)
= case unLoc op of
HsVar (L _ v) -> pp_infixly v
HsRecFld f -> pp_infixly f
_ -> pp_prefixly
where
pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
pp_prefixly
= hang (ppr op) 2 (sep [pp_e1, pp_e2])
pp_infixly v
= sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]] | 427 | ppr_expr (OpApp e1 op _ e2)
= case unLoc op of
HsVar (L _ v) -> pp_infixly v
HsRecFld f -> pp_infixly f
_ -> pp_prefixly
where
pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
pp_prefixly
= hang (ppr op) 2 (sep [pp_e1, pp_e2])
pp_infixly v
= sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]] | 427 | ppr_expr (OpApp e1 op _ e2)
= case unLoc op of
HsVar (L _ v) -> pp_infixly v
HsRecFld f -> pp_infixly f
_ -> pp_prefixly
where
pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
pp_prefixly
= hang (ppr op) 2 (sep [pp_e1, pp_e2])
pp_infixly v
= sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]] | 427 | false | false | 3 | 10 | 136 | 150 | 74 | 76 | null | null |
Numberartificial/workflow | haskell-first-principles/haskell-programming-from-first-principles-master/src/Chapter12.hs | mit | isJust :: Maybe a -> Bool
isJust (Just _) = True | 48 | isJust :: Maybe a -> Bool
isJust (Just _) = True | 48 | isJust (Just _) = True | 22 | false | true | 0 | 6 | 10 | 31 | 14 | 17 | null | null |
emwap/feldspar-language | src/Feldspar/Core/Types.hs | bsd-3-clause | fromWordN NNative = id | 22 | fromWordN NNative = id | 22 | fromWordN NNative = id | 22 | false | false | 0 | 5 | 3 | 9 | 4 | 5 | null | null |
prowdsponsor/country-codes | src/Data/CountryCodes/ISO31661.hs | bsd-3-clause | fromMText "SV" = Just SV | 24 | fromMText "SV" = Just SV | 24 | fromMText "SV" = Just SV | 24 | false | false | 0 | 5 | 4 | 12 | 5 | 7 | null | null |
Course/HaskDB | src/System/HaskDB/Backend_test.hs | bsd-3-clause | arbitrary = oneof $ map return [Write , ReadWrite , Read] | 57 | arbitrary = oneof $ map return [Write , ReadWrite , Read] | 57 | arbitrary = oneof $ map return [Write , ReadWrite , Read] | 57 | false | false | 0 | 7 | 10 | 24 | 13 | 11 | null | null |
sdiehl/ghc | compiler/simplCore/OccurAnal.hs | bsd-3-clause | markInsideLam occ@(OneOcc {}) = occ { occ_in_lam = IsInsideLam } | 64 | markInsideLam occ@(OneOcc {}) = occ { occ_in_lam = IsInsideLam } | 64 | markInsideLam occ@(OneOcc {}) = occ { occ_in_lam = IsInsideLam } | 64 | false | false | 0 | 8 | 9 | 27 | 15 | 12 | null | null |
phischu/fragnix | tests/packages/scotty/System.FilePath.Posix.hs | bsd-3-clause | isValid path =
not (any isBadCharacter x2) &&
not (any f $ splitDirectories x2) &&
not (isJust (readDriveShare x1) && all isPathSeparator x1) &&
not (isJust (readDriveUNC x1) && not (hasTrailingPathSeparator x1))
where
(x1,x2) = splitDrive path
f x = map toUpper (dropWhileEnd (== ' ') $ dropExtensions x) `elem` badElements
-- | Take a FilePath and make it valid; does not change already valid FilePaths.
--
-- > isValid (makeValid x)
-- > isValid x ==> makeValid x == x
-- > makeValid "" == "_"
-- > makeValid "file\0name" == "file_name"
-- > Windows: makeValid "c:\\already\\/valid" == "c:\\already\\/valid"
-- > Windows: makeValid "c:\\test:of_test" == "c:\\test_of_test"
-- > Windows: makeValid "test*" == "test_"
-- > Windows: makeValid "c:\\test\\nul" == "c:\\test\\nul_"
-- > Windows: makeValid "c:\\test\\prn.txt" == "c:\\test\\prn_.txt"
-- > Windows: makeValid "c:\\test/prn.txt" == "c:\\test/prn_.txt"
-- > Windows: makeValid "c:\\nul\\file" == "c:\\nul_\\file"
-- > Windows: makeValid "\\\\\\foo" == "\\\\drive"
-- > Windows: makeValid "\\\\?\\D:file" == "\\\\?\\D:\\file"
-- > Windows: makeValid "nul .txt" == "nul _.txt" | 1,188 | isValid path =
not (any isBadCharacter x2) &&
not (any f $ splitDirectories x2) &&
not (isJust (readDriveShare x1) && all isPathSeparator x1) &&
not (isJust (readDriveUNC x1) && not (hasTrailingPathSeparator x1))
where
(x1,x2) = splitDrive path
f x = map toUpper (dropWhileEnd (== ' ') $ dropExtensions x) `elem` badElements
-- | Take a FilePath and make it valid; does not change already valid FilePaths.
--
-- > isValid (makeValid x)
-- > isValid x ==> makeValid x == x
-- > makeValid "" == "_"
-- > makeValid "file\0name" == "file_name"
-- > Windows: makeValid "c:\\already\\/valid" == "c:\\already\\/valid"
-- > Windows: makeValid "c:\\test:of_test" == "c:\\test_of_test"
-- > Windows: makeValid "test*" == "test_"
-- > Windows: makeValid "c:\\test\\nul" == "c:\\test\\nul_"
-- > Windows: makeValid "c:\\test\\prn.txt" == "c:\\test\\prn_.txt"
-- > Windows: makeValid "c:\\test/prn.txt" == "c:\\test/prn_.txt"
-- > Windows: makeValid "c:\\nul\\file" == "c:\\nul_\\file"
-- > Windows: makeValid "\\\\\\foo" == "\\\\drive"
-- > Windows: makeValid "\\\\?\\D:file" == "\\\\?\\D:\\file"
-- > Windows: makeValid "nul .txt" == "nul _.txt" | 1,188 | isValid path =
not (any isBadCharacter x2) &&
not (any f $ splitDirectories x2) &&
not (isJust (readDriveShare x1) && all isPathSeparator x1) &&
not (isJust (readDriveUNC x1) && not (hasTrailingPathSeparator x1))
where
(x1,x2) = splitDrive path
f x = map toUpper (dropWhileEnd (== ' ') $ dropExtensions x) `elem` badElements
-- | Take a FilePath and make it valid; does not change already valid FilePaths.
--
-- > isValid (makeValid x)
-- > isValid x ==> makeValid x == x
-- > makeValid "" == "_"
-- > makeValid "file\0name" == "file_name"
-- > Windows: makeValid "c:\\already\\/valid" == "c:\\already\\/valid"
-- > Windows: makeValid "c:\\test:of_test" == "c:\\test_of_test"
-- > Windows: makeValid "test*" == "test_"
-- > Windows: makeValid "c:\\test\\nul" == "c:\\test\\nul_"
-- > Windows: makeValid "c:\\test\\prn.txt" == "c:\\test\\prn_.txt"
-- > Windows: makeValid "c:\\test/prn.txt" == "c:\\test/prn_.txt"
-- > Windows: makeValid "c:\\nul\\file" == "c:\\nul_\\file"
-- > Windows: makeValid "\\\\\\foo" == "\\\\drive"
-- > Windows: makeValid "\\\\?\\D:file" == "\\\\?\\D:\\file"
-- > Windows: makeValid "nul .txt" == "nul _.txt" | 1,188 | false | false | 0 | 12 | 218 | 169 | 90 | 79 | null | null |
spacekitteh/smcghc | libraries/base/Data/Typeable/Internal.hs | bsd-3-clause | typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep
typeOf1 _ = typeRep (Proxy :: Proxy t) | 97 | typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep
typeOf1 _ = typeRep (Proxy :: Proxy t) | 97 | typeOf1 _ = typeRep (Proxy :: Proxy t) | 38 | false | true | 0 | 8 | 21 | 52 | 27 | 25 | null | null |
dimara/ganeti | src/Ganeti/WConfd/Core.hs | bsd-2-clause | -- ** Configuration related functions
checkConfigLock :: ClientId -> L.OwnerState -> WConfdMonad ()
checkConfigLock cid state = do
la <- readLockAllocation
unless (L.holdsLock cid ConfigLock state la)
. failError $ "Requested lock " ++ show state
++ " on the configuration missing"
-- | Read the configuration. | 348 | checkConfigLock :: ClientId -> L.OwnerState -> WConfdMonad ()
checkConfigLock cid state = do
la <- readLockAllocation
unless (L.holdsLock cid ConfigLock state la)
. failError $ "Requested lock " ++ show state
++ " on the configuration missing"
-- | Read the configuration. | 309 | checkConfigLock cid state = do
la <- readLockAllocation
unless (L.holdsLock cid ConfigLock state la)
. failError $ "Requested lock " ++ show state
++ " on the configuration missing"
-- | Read the configuration. | 247 | true | true | 0 | 14 | 84 | 79 | 38 | 41 | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.