_id
stringlengths 64
64
| repository
stringlengths 6
84
| name
stringlengths 4
110
| content
stringlengths 0
248k
| license
null | download_url
stringlengths 89
454
| language
stringclasses 7
values | comments
stringlengths 0
74.6k
| code
stringlengths 0
248k
|
---|---|---|---|---|---|---|---|---|
8b872694874a44468de425b8232277d972c92d2023222bb8a5e77da5ac4f2578 | khotyn/4clojure-answer | 28-flatten-a-sequence.clj | (fn [coll]
(letfn [(my-flatten [coll]
(if coll
(let
[s (seq coll) f (first s)]
(concat
(if
(sequential? f)
(my-flatten f)
(cons f '()))
(my-flatten (next s))))))]
(my-flatten coll)))
| null | https://raw.githubusercontent.com/khotyn/4clojure-answer/3de82d732faedceafac4f1585a72d0712fe5d3c6/28-flatten-a-sequence.clj | clojure | (fn [coll]
(letfn [(my-flatten [coll]
(if coll
(let
[s (seq coll) f (first s)]
(concat
(if
(sequential? f)
(my-flatten f)
(cons f '()))
(my-flatten (next s))))))]
(my-flatten coll)))
|
|
d8144dd1a4bb7588d337b9661dbfd1a4d7f2ce6e03b84d9382546e095ceedf62 | NetworkVerification/nv | MapUnrollingUtils.mli | open Nv_lang.Collections
(**
Each entry in this list is:
* A map type
* The set of constant keys that are used for the map
* The set of symbolic variable keys that are used for the map
Note the nested tuple type.
*)
type maplist = (Nv_lang.Syntax.ty * (ExpSet.t * VarSet.t)) list
val maplist_to_string : maplist -> string
(** Given a program on which type inference has been run, goes through
it and returns a list of each map type which appears in that program,
combined with the set of keys used for that map type.
*)
val collect_map_types_and_keys : Nv_lang.Syntax.declarations -> maplist
| null | https://raw.githubusercontent.com/NetworkVerification/nv/e76824c537dcd535f2224b31f35cd37601a60957/src/lib/transformations/mapUnrolling/MapUnrollingUtils.mli | ocaml | *
Each entry in this list is:
* A map type
* The set of constant keys that are used for the map
* The set of symbolic variable keys that are used for the map
Note the nested tuple type.
* Given a program on which type inference has been run, goes through
it and returns a list of each map type which appears in that program,
combined with the set of keys used for that map type.
| open Nv_lang.Collections
type maplist = (Nv_lang.Syntax.ty * (ExpSet.t * VarSet.t)) list
val maplist_to_string : maplist -> string
val collect_map_types_and_keys : Nv_lang.Syntax.declarations -> maplist
|
89a0b3d919ad269d7800e6954bdff342ce686b268e59a0284495881b6e6ef474 | racket/plai | names.rkt | #lang plai/gc2/mutator
(allocator-setup "../good-collectors/good-collector.rkt" 10)
(let ([f (λ (x) x)]) f)
| null | https://raw.githubusercontent.com/racket/plai/164f3b763116fcfa7bd827be511650e71fa04319/plai-lib/tests/gc2/good-mutators/names.rkt | racket | #lang plai/gc2/mutator
(allocator-setup "../good-collectors/good-collector.rkt" 10)
(let ([f (λ (x) x)]) f)
|
|
2aae5007d1b79648a8ece7222e1a804e89e71fda1edc8fac4f365528105ea71a | ondrap/dynamodb-simple | THLens.hs | {-# LANGUAGE CPP #-}
# LANGUAGE TemplateHaskell #
-- | Create polymorphic lens to access table & indexes
module Database.DynamoDB.THLens where
import Control.Lens (over, _1)
import Control.Monad (forM_)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Writer.Lazy (WriterT, tell)
import Data.Function ((&))
import Data.List (isPrefixOf)
import Data.Monoid ((<>))
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (Name (..), OccName (..))
-- | Create lenses if the field in the primary table starts with _.
--
-- class Test_lens_field00 a b | a -> b where
-- _field :: Functor f => (b -> f b) -> a -> f a
-- instance Test_lens_field00 Test (Maybe T.Text) where
-- field f t = (\txt -> t{_field=txt}) <$> f (_field t)
createPolyLenses :: (String -> String) -> Name -> [Name] -> WriterT [Dec] Q ()
createPolyLenses translate table indexes = do
-- Get fields that can be lenses
tblfields <- getFieldNames table id
fields <- tblfields & map fst
& filter ("_" `isPrefixOf`)
& map ((,) <$> translate <*> drop 1)
& mapM mkLensClass
mapM_ createClass fields
createInstances fields table
mapM_ (createInstances fields) indexes
where
mkLensClass (field, lens) = do
clsname <- lift $ newName (nameBase table ++ "_lens_" ++ field)
return (field, (mkName lens, clsname))
createClass (_, (lensname, clsname)) = do
a <- lift $ newName "a"
b <- lift $ newName "b"
f <- lift $ newName "f"
lift (pure $ ClassD [] clsname [PlainTV a,PlainTV b] [FunDep [a] [b]]
[SigD lensname (ForallT [PlainTV f] [AppT (ConT ''Functor) (VarT f)]
(AppT (AppT ArrowT (AppT (AppT ArrowT (VarT b))
(AppT (VarT f) (VarT b)))) (AppT (AppT ArrowT (VarT a))
(AppT (VarT f) (VarT a)))))]) >>= say
createInstances lensfields idx = do
tblfields <- getFieldNames idx id
forM_ tblfields $ \(fieldname, ftype) ->
whenJust (lookup (translate fieldname) lensfields) $ \(lensname, clsname) -> do
f <- lift $ newName "f"
t <- lift $ newName "t"
val <- lift $ newName "val"
let fieldSel = mkName fieldname
#if __GLASGOW_HASKELL__ >= 800
lift (pure $ InstanceD Nothing [] (AppT (AppT (ConT clsname) (ConT idx)) ftype)
[FunD lensname [Clause [VarP f,VarP t] (NormalB (InfixE (Just (LamE [VarP val]
(RecUpdE (VarE t) [(fieldSel,VarE val)]))) (VarE 'fmap)
(Just (AppE (VarE f) (AppE (VarE fieldSel) (VarE t)))))) []]])
#else
lift (pure $ InstanceD [] (AppT (AppT (ConT clsname) (ConT idx)) ftype)
[FunD lensname [Clause [VarP f,VarP t] (NormalB (InfixE (Just (LamE [VarP val]
(RecUpdE (VarE t) [(fieldSel,VarE val)]))) (VarE 'fmap)
(Just (AppE (VarE f) (AppE (VarE fieldSel) (VarE t)))))) []]])
#endif
>>= say
whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()
whenJust (Just a) f = f a
whenJust Nothing _ = return ()
say :: Monad m => t -> WriterT [t] m ()
say a = tell [a]
-- | Reify name and return list of record fields with type
getFieldNames :: Name -> (String -> String) -> WriterT [Dec] Q [(String, Type)]
getFieldNames tbl translate = do
info <- lift $ reify tbl
case getRecords info of
Left err -> fail $ "Table " <> show tbl <> ": " <> err
Right lst -> return $ map (over _1 translate) lst
where
getRecords :: Info -> Either String [(String, Type)]
#if __GLASGOW_HASKELL__ >= 800
getRecords (TyConI (DataD _ _ _ _ [RecC _ vars] _)) = Right $ map (\(Name (OccName rname) _,_,typ) -> (rname, typ)) vars
#else
getRecords (TyConI (DataD _ _ _ [RecC _ vars] _)) = Right $ map (\(Name (OccName rname) _,_,typ) -> (rname, typ)) vars
#endif
getRecords _ = Left "not a record declaration with 1 constructor"
| null | https://raw.githubusercontent.com/ondrap/dynamodb-simple/fb7e3fe37d7e534161274cfd812cd11a82cc384b/src/Database/DynamoDB/THLens.hs | haskell | # LANGUAGE CPP #
| Create polymorphic lens to access table & indexes
| Create lenses if the field in the primary table starts with _.
class Test_lens_field00 a b | a -> b where
_field :: Functor f => (b -> f b) -> a -> f a
instance Test_lens_field00 Test (Maybe T.Text) where
field f t = (\txt -> t{_field=txt}) <$> f (_field t)
Get fields that can be lenses
| Reify name and return list of record fields with type | # LANGUAGE TemplateHaskell #
module Database.DynamoDB.THLens where
import Control.Lens (over, _1)
import Control.Monad (forM_)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Writer.Lazy (WriterT, tell)
import Data.Function ((&))
import Data.List (isPrefixOf)
import Data.Monoid ((<>))
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (Name (..), OccName (..))
createPolyLenses :: (String -> String) -> Name -> [Name] -> WriterT [Dec] Q ()
createPolyLenses translate table indexes = do
tblfields <- getFieldNames table id
fields <- tblfields & map fst
& filter ("_" `isPrefixOf`)
& map ((,) <$> translate <*> drop 1)
& mapM mkLensClass
mapM_ createClass fields
createInstances fields table
mapM_ (createInstances fields) indexes
where
mkLensClass (field, lens) = do
clsname <- lift $ newName (nameBase table ++ "_lens_" ++ field)
return (field, (mkName lens, clsname))
createClass (_, (lensname, clsname)) = do
a <- lift $ newName "a"
b <- lift $ newName "b"
f <- lift $ newName "f"
lift (pure $ ClassD [] clsname [PlainTV a,PlainTV b] [FunDep [a] [b]]
[SigD lensname (ForallT [PlainTV f] [AppT (ConT ''Functor) (VarT f)]
(AppT (AppT ArrowT (AppT (AppT ArrowT (VarT b))
(AppT (VarT f) (VarT b)))) (AppT (AppT ArrowT (VarT a))
(AppT (VarT f) (VarT a)))))]) >>= say
createInstances lensfields idx = do
tblfields <- getFieldNames idx id
forM_ tblfields $ \(fieldname, ftype) ->
whenJust (lookup (translate fieldname) lensfields) $ \(lensname, clsname) -> do
f <- lift $ newName "f"
t <- lift $ newName "t"
val <- lift $ newName "val"
let fieldSel = mkName fieldname
#if __GLASGOW_HASKELL__ >= 800
lift (pure $ InstanceD Nothing [] (AppT (AppT (ConT clsname) (ConT idx)) ftype)
[FunD lensname [Clause [VarP f,VarP t] (NormalB (InfixE (Just (LamE [VarP val]
(RecUpdE (VarE t) [(fieldSel,VarE val)]))) (VarE 'fmap)
(Just (AppE (VarE f) (AppE (VarE fieldSel) (VarE t)))))) []]])
#else
lift (pure $ InstanceD [] (AppT (AppT (ConT clsname) (ConT idx)) ftype)
[FunD lensname [Clause [VarP f,VarP t] (NormalB (InfixE (Just (LamE [VarP val]
(RecUpdE (VarE t) [(fieldSel,VarE val)]))) (VarE 'fmap)
(Just (AppE (VarE f) (AppE (VarE fieldSel) (VarE t)))))) []]])
#endif
>>= say
whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()
whenJust (Just a) f = f a
whenJust Nothing _ = return ()
say :: Monad m => t -> WriterT [t] m ()
say a = tell [a]
getFieldNames :: Name -> (String -> String) -> WriterT [Dec] Q [(String, Type)]
getFieldNames tbl translate = do
info <- lift $ reify tbl
case getRecords info of
Left err -> fail $ "Table " <> show tbl <> ": " <> err
Right lst -> return $ map (over _1 translate) lst
where
getRecords :: Info -> Either String [(String, Type)]
#if __GLASGOW_HASKELL__ >= 800
getRecords (TyConI (DataD _ _ _ _ [RecC _ vars] _)) = Right $ map (\(Name (OccName rname) _,_,typ) -> (rname, typ)) vars
#else
getRecords (TyConI (DataD _ _ _ [RecC _ vars] _)) = Right $ map (\(Name (OccName rname) _,_,typ) -> (rname, typ)) vars
#endif
getRecords _ = Left "not a record declaration with 1 constructor"
|
5cde716cd1eb192714135e16300637c982c92d7aeeba11d9872170f99e1f7cf5 | Risto-Stevcev/bastet | Test_JsFunctions.ml | open BsMocha.Mocha
open BsChai.Expect.Expect
open BsChai.Expect.Combos.End
open! Functors
;;
describe "Functions" (fun () ->
describe "Traversable" (fun () ->
describe "Array" (fun () ->
describe "Scan" (fun () ->
let scan_left, scan_right =
let open ArrayF.Int.Functions.Scan in
scan_left, scan_right
in
describe "scan_left" (fun () ->
it "should scan from the left" (fun () ->
expect (scan_left ( + ) 0 [|1; 2; 3|]) |> to_be [|1; 3; 6|];
expect (scan_left ( - ) 10 [|1; 2; 3|]) |> to_be [|9; 7; 4|]));
describe "scan_right" (fun () ->
it "should scan from the right (array)" (fun () ->
expect (scan_right ( + ) 0 [|1; 2; 3|]) |> to_be [|6; 5; 3|];
expect (scan_right (Function.flip ( - )) 10 [|1; 2; 3|])
|> to_be [|4; 5; 7|]))));
describe "List" (fun () ->
describe "Scan" (fun () ->
let scan_left, scan_right =
let open ListF.Int.Functions.Scan in
scan_left, scan_right
in
describe "scan_left" (fun () ->
it "should scan from the left" (fun () ->
expect (scan_left ( + ) 0 [1; 2; 3]) |> to_be [1; 3; 6];
expect (scan_left ( - ) 10 [1; 2; 3]) |> to_be [9; 7; 4]));
describe "scan_right" (fun () ->
it "should scan from the right (array)" (fun () ->
expect (scan_right ( + ) 0 [1; 2; 3]) |> to_be [6; 5; 3];
expect (scan_right (Function.flip ( - )) 10 [1; 2; 3]) |> to_be [4; 5; 7]))))))
| null | https://raw.githubusercontent.com/Risto-Stevcev/bastet/030db286f57d2e316897f0600d40b34777eabba6/bastet_js/test/Test_JsFunctions.ml | ocaml | open BsMocha.Mocha
open BsChai.Expect.Expect
open BsChai.Expect.Combos.End
open! Functors
;;
describe "Functions" (fun () ->
describe "Traversable" (fun () ->
describe "Array" (fun () ->
describe "Scan" (fun () ->
let scan_left, scan_right =
let open ArrayF.Int.Functions.Scan in
scan_left, scan_right
in
describe "scan_left" (fun () ->
it "should scan from the left" (fun () ->
expect (scan_left ( + ) 0 [|1; 2; 3|]) |> to_be [|1; 3; 6|];
expect (scan_left ( - ) 10 [|1; 2; 3|]) |> to_be [|9; 7; 4|]));
describe "scan_right" (fun () ->
it "should scan from the right (array)" (fun () ->
expect (scan_right ( + ) 0 [|1; 2; 3|]) |> to_be [|6; 5; 3|];
expect (scan_right (Function.flip ( - )) 10 [|1; 2; 3|])
|> to_be [|4; 5; 7|]))));
describe "List" (fun () ->
describe "Scan" (fun () ->
let scan_left, scan_right =
let open ListF.Int.Functions.Scan in
scan_left, scan_right
in
describe "scan_left" (fun () ->
it "should scan from the left" (fun () ->
expect (scan_left ( + ) 0 [1; 2; 3]) |> to_be [1; 3; 6];
expect (scan_left ( - ) 10 [1; 2; 3]) |> to_be [9; 7; 4]));
describe "scan_right" (fun () ->
it "should scan from the right (array)" (fun () ->
expect (scan_right ( + ) 0 [1; 2; 3]) |> to_be [6; 5; 3];
expect (scan_right (Function.flip ( - )) 10 [1; 2; 3]) |> to_be [4; 5; 7]))))))
|
|
1e108996c30108c00561ca67113dc31e423f5d13e1497d285ce2f50f752ad19c | mfikes/coal-mine | problem_8.cljc | (ns coal-mine.problem-8
(:require [coal-mine.checks :refer [defcheck-8] :rename {defcheck-8 defcheck}]
[clojure.test]
[clojure.set]))
(defcheck solution-1550092
#{:a :b :d :c })
(defcheck solution-27e70ccc
#{:d :c :b :a})
(defcheck solution-2aa50037
#{:a :c :b :d})
(defcheck solution-44052ae8
#{:a :c :b :d} #{:a :c :b :d})
(defcheck solution-46943be8
#{:b :c :d :a})
(defcheck solution-479643de
#{:a :b :c :d})
(defcheck solution-4d6c1e7e
#{:a :b :c :d} #{:a :b :c :d})
(defcheck solution-4daf81f6
#{:a :c :d :b})
(defcheck solution-5db6422e
'#{:a :b :c :d})
(defcheck solution-694a1f8e
#{:a :b :d :c})
(defcheck solution-6ec44dea
#{:a :b :c :d} #{:a :b :c :d})
(defcheck solution-6ffa5249
#{:a :c :b :d})
(defcheck solution-8d7379b7
(set '(:a :a :b :c :c :c :c :d :d)))
(defcheck solution-8ebcebe9
(set '(:d :c :a :b)))
(defcheck solution-8f9110f3
#{ :a :b :c :d })
(defcheck solution-966b5bee
#{:c :b :d :a})
(defcheck solution-9bc1390c
(set '(:a :b :c :d)))
(defcheck solution-a8eb82e0
(set '(:a :b :c :d)) (set '(:a :b :c :d)))
(defcheck solution-c446f333
(hash-set :d :c :b :a))
(defcheck solution-c5b999ea
(hash-set :a :b :c :d))
(defcheck solution-d014c0a8
(clojure.set/union #{:a :b :c} #{:b :c :d}))
(defcheck solution-da55b4
#{:a :b :c :d} #{:a :b :c :d})
(defcheck solution-dcd6f9b1
#{ :a :b :c :d})
(defcheck solution-e0afd95d
#{:a :b :c :d } #{:a :b :c :d })
(defcheck solution-e1af8ef2
(set '(:a :a :a :a :a :a :a :a :a :a :a :a :b :c :c :c :c :d :d)))
(defcheck solution-e58ed0f6
(set [:a :b :c :d]))
(defcheck solution-f8d036c3
#{:b :a :c :d})
(defcheck solution-fc863ace
#{:a :b :c :d })
(defn run-tests []
(clojure.test/run-tests 'coal-mine.problem-8))
(defn -main []
(run-tests))
#?(:cljs (set! *main-cli-fn* -main))
| null | https://raw.githubusercontent.com/mfikes/coal-mine/0961d085b37f4e59489a8cf6a2b8fef0a698d8fb/src/coal_mine/problem_8.cljc | clojure | (ns coal-mine.problem-8
(:require [coal-mine.checks :refer [defcheck-8] :rename {defcheck-8 defcheck}]
[clojure.test]
[clojure.set]))
(defcheck solution-1550092
#{:a :b :d :c })
(defcheck solution-27e70ccc
#{:d :c :b :a})
(defcheck solution-2aa50037
#{:a :c :b :d})
(defcheck solution-44052ae8
#{:a :c :b :d} #{:a :c :b :d})
(defcheck solution-46943be8
#{:b :c :d :a})
(defcheck solution-479643de
#{:a :b :c :d})
(defcheck solution-4d6c1e7e
#{:a :b :c :d} #{:a :b :c :d})
(defcheck solution-4daf81f6
#{:a :c :d :b})
(defcheck solution-5db6422e
'#{:a :b :c :d})
(defcheck solution-694a1f8e
#{:a :b :d :c})
(defcheck solution-6ec44dea
#{:a :b :c :d} #{:a :b :c :d})
(defcheck solution-6ffa5249
#{:a :c :b :d})
(defcheck solution-8d7379b7
(set '(:a :a :b :c :c :c :c :d :d)))
(defcheck solution-8ebcebe9
(set '(:d :c :a :b)))
(defcheck solution-8f9110f3
#{ :a :b :c :d })
(defcheck solution-966b5bee
#{:c :b :d :a})
(defcheck solution-9bc1390c
(set '(:a :b :c :d)))
(defcheck solution-a8eb82e0
(set '(:a :b :c :d)) (set '(:a :b :c :d)))
(defcheck solution-c446f333
(hash-set :d :c :b :a))
(defcheck solution-c5b999ea
(hash-set :a :b :c :d))
(defcheck solution-d014c0a8
(clojure.set/union #{:a :b :c} #{:b :c :d}))
(defcheck solution-da55b4
#{:a :b :c :d} #{:a :b :c :d})
(defcheck solution-dcd6f9b1
#{ :a :b :c :d})
(defcheck solution-e0afd95d
#{:a :b :c :d } #{:a :b :c :d })
(defcheck solution-e1af8ef2
(set '(:a :a :a :a :a :a :a :a :a :a :a :a :b :c :c :c :c :d :d)))
(defcheck solution-e58ed0f6
(set [:a :b :c :d]))
(defcheck solution-f8d036c3
#{:b :a :c :d})
(defcheck solution-fc863ace
#{:a :b :c :d })
(defn run-tests []
(clojure.test/run-tests 'coal-mine.problem-8))
(defn -main []
(run-tests))
#?(:cljs (set! *main-cli-fn* -main))
|
|
2ec9839fee9b647de2acc22c916371a0c05f15ef2e92d863e24bd724a57e7c56 | mbj/stratosphere | NetworkConfigProperty.hs | module Stratosphere.SageMaker.MonitoringSchedule.NetworkConfigProperty (
module Exports, NetworkConfigProperty(..), mkNetworkConfigProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.SageMaker.MonitoringSchedule.VpcConfigProperty as Exports
import Stratosphere.ResourceProperties
import Stratosphere.Value
data NetworkConfigProperty
= NetworkConfigProperty {enableInterContainerTrafficEncryption :: (Prelude.Maybe (Value Prelude.Bool)),
enableNetworkIsolation :: (Prelude.Maybe (Value Prelude.Bool)),
vpcConfig :: (Prelude.Maybe VpcConfigProperty)}
mkNetworkConfigProperty :: NetworkConfigProperty
mkNetworkConfigProperty
= NetworkConfigProperty
{enableInterContainerTrafficEncryption = Prelude.Nothing,
enableNetworkIsolation = Prelude.Nothing,
vpcConfig = Prelude.Nothing}
instance ToResourceProperties NetworkConfigProperty where
toResourceProperties NetworkConfigProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::MonitoringSchedule.NetworkConfig",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "EnableInterContainerTrafficEncryption"
Prelude.<$> enableInterContainerTrafficEncryption,
(JSON..=) "EnableNetworkIsolation"
Prelude.<$> enableNetworkIsolation,
(JSON..=) "VpcConfig" Prelude.<$> vpcConfig])}
instance JSON.ToJSON NetworkConfigProperty where
toJSON NetworkConfigProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "EnableInterContainerTrafficEncryption"
Prelude.<$> enableInterContainerTrafficEncryption,
(JSON..=) "EnableNetworkIsolation"
Prelude.<$> enableNetworkIsolation,
(JSON..=) "VpcConfig" Prelude.<$> vpcConfig]))
instance Property "EnableInterContainerTrafficEncryption" NetworkConfigProperty where
type PropertyType "EnableInterContainerTrafficEncryption" NetworkConfigProperty = Value Prelude.Bool
set newValue NetworkConfigProperty {..}
= NetworkConfigProperty
{enableInterContainerTrafficEncryption = Prelude.pure newValue, ..}
instance Property "EnableNetworkIsolation" NetworkConfigProperty where
type PropertyType "EnableNetworkIsolation" NetworkConfigProperty = Value Prelude.Bool
set newValue NetworkConfigProperty {..}
= NetworkConfigProperty
{enableNetworkIsolation = Prelude.pure newValue, ..}
instance Property "VpcConfig" NetworkConfigProperty where
type PropertyType "VpcConfig" NetworkConfigProperty = VpcConfigProperty
set newValue NetworkConfigProperty {..}
= NetworkConfigProperty {vpcConfig = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/MonitoringSchedule/NetworkConfigProperty.hs | haskell | # SOURCE # | module Stratosphere.SageMaker.MonitoringSchedule.NetworkConfigProperty (
module Exports, NetworkConfigProperty(..), mkNetworkConfigProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data NetworkConfigProperty
= NetworkConfigProperty {enableInterContainerTrafficEncryption :: (Prelude.Maybe (Value Prelude.Bool)),
enableNetworkIsolation :: (Prelude.Maybe (Value Prelude.Bool)),
vpcConfig :: (Prelude.Maybe VpcConfigProperty)}
mkNetworkConfigProperty :: NetworkConfigProperty
mkNetworkConfigProperty
= NetworkConfigProperty
{enableInterContainerTrafficEncryption = Prelude.Nothing,
enableNetworkIsolation = Prelude.Nothing,
vpcConfig = Prelude.Nothing}
instance ToResourceProperties NetworkConfigProperty where
toResourceProperties NetworkConfigProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::MonitoringSchedule.NetworkConfig",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "EnableInterContainerTrafficEncryption"
Prelude.<$> enableInterContainerTrafficEncryption,
(JSON..=) "EnableNetworkIsolation"
Prelude.<$> enableNetworkIsolation,
(JSON..=) "VpcConfig" Prelude.<$> vpcConfig])}
instance JSON.ToJSON NetworkConfigProperty where
toJSON NetworkConfigProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "EnableInterContainerTrafficEncryption"
Prelude.<$> enableInterContainerTrafficEncryption,
(JSON..=) "EnableNetworkIsolation"
Prelude.<$> enableNetworkIsolation,
(JSON..=) "VpcConfig" Prelude.<$> vpcConfig]))
instance Property "EnableInterContainerTrafficEncryption" NetworkConfigProperty where
type PropertyType "EnableInterContainerTrafficEncryption" NetworkConfigProperty = Value Prelude.Bool
set newValue NetworkConfigProperty {..}
= NetworkConfigProperty
{enableInterContainerTrafficEncryption = Prelude.pure newValue, ..}
instance Property "EnableNetworkIsolation" NetworkConfigProperty where
type PropertyType "EnableNetworkIsolation" NetworkConfigProperty = Value Prelude.Bool
set newValue NetworkConfigProperty {..}
= NetworkConfigProperty
{enableNetworkIsolation = Prelude.pure newValue, ..}
instance Property "VpcConfig" NetworkConfigProperty where
type PropertyType "VpcConfig" NetworkConfigProperty = VpcConfigProperty
set newValue NetworkConfigProperty {..}
= NetworkConfigProperty {vpcConfig = Prelude.pure newValue, ..} |
ce930bdabdf624317a815008228d1b8728881bc7f483d277b635b0cb070712cc | input-output-hk/cardano-ledger | Body.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
module Cardano.Ledger.Api.Tx.Body (
-- | Building and inspecting transaction outputs
module Cardano.Ledger.Api.Tx.Out,
| Working with Timelock scripts and scripts
module Cardano.Ledger.Api.Scripts,
EraTxBody (..),
* Era
ShelleyTxBody,
ShelleyEraTxBody (..),
-- * Allegra Era
AllegraEraTxBody (..),
*
MaryEraTxBody (..),
-- * Alonzo Era
AlonzoTxBody,
AlonzoEraTxBody (..),
-- * Babbage Era
BabbageTxBody,
BabbageEraTxBody (..),
)
where
import Cardano.Ledger.Allegra.Core (AllegraEraTxBody (..))
import Cardano.Ledger.Alonzo.TxBody (AlonzoEraTxBody (..), AlonzoTxBody)
import Cardano.Ledger.Api.Scripts
import Cardano.Ledger.Api.Tx.Out
import Cardano.Ledger.Babbage.TxBody (BabbageEraTxBody (..), BabbageTxBody)
import Cardano.Ledger.Core (EraTxBody (..))
import Cardano.Ledger.Mary.Core (MaryEraTxBody (..))
import Cardano.Ledger.Shelley (ShelleyTxBody)
import Cardano.Ledger.Shelley.Core (ShelleyEraTxBody (..))
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/31c0bb1f5e78e40b83adfd1a916e69f47fdc9835/libs/cardano-ledger-api/src/Cardano/Ledger/Api/Tx/Body.hs | haskell | # LANGUAGE RankNTypes #
| Building and inspecting transaction outputs
* Allegra Era
* Alonzo Era
* Babbage Era | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
module Cardano.Ledger.Api.Tx.Body (
module Cardano.Ledger.Api.Tx.Out,
| Working with Timelock scripts and scripts
module Cardano.Ledger.Api.Scripts,
EraTxBody (..),
* Era
ShelleyTxBody,
ShelleyEraTxBody (..),
AllegraEraTxBody (..),
*
MaryEraTxBody (..),
AlonzoTxBody,
AlonzoEraTxBody (..),
BabbageTxBody,
BabbageEraTxBody (..),
)
where
import Cardano.Ledger.Allegra.Core (AllegraEraTxBody (..))
import Cardano.Ledger.Alonzo.TxBody (AlonzoEraTxBody (..), AlonzoTxBody)
import Cardano.Ledger.Api.Scripts
import Cardano.Ledger.Api.Tx.Out
import Cardano.Ledger.Babbage.TxBody (BabbageEraTxBody (..), BabbageTxBody)
import Cardano.Ledger.Core (EraTxBody (..))
import Cardano.Ledger.Mary.Core (MaryEraTxBody (..))
import Cardano.Ledger.Shelley (ShelleyTxBody)
import Cardano.Ledger.Shelley.Core (ShelleyEraTxBody (..))
|
3e1703d30b7011f6dcdecd2c2abd5138b9be97ca8ebabcc5022658ca29fbf381 | xively/clj-mqtt | puback_test.clj | (ns mqtt.packets.puback-test
(:use clojure.test
mqtt.test-helpers
mqtt.decoder
mqtt.encoder
mqtt.packets.common
mqtt.packets.puback)
(:import [io.netty.buffer Unpooled]
[io.netty.handler.codec EncoderException]))
(deftest puback-validate-message-test
(testing "nil when valid"
(is (= nil (validate-message {:type :puback
:message-id 1}))))
(testing "it throws if no message-id"
(is (thrown? EncoderException (validate-message {:type :puback}))))
(testing "it throws if message-id is 0"
(is (thrown? EncoderException (validate-message {:type :puback
:message-id 0})))))
(deftest puback-encoding-test
(testing "when encoding a simple puback packet"
(let [encoder (make-encoder)
packet {:type :puback :message-id 5}
out (Unpooled/buffer 4)]
(.encode encoder nil packet out)
(is (= (byte-buffer-to-bytes out)
[;; fixed header
2r01000000
;; remaining length
2
;; message id
0 5])))))
(deftest decoding-puback-packet-test
(testing "when parsing a simple puback packet"
(let [decoder (make-decoder)
packet (bytes-to-byte-buffer
;; fixed header
2r01000000
;; remaining length
2
;; message id
0 5)
out (new java.util.ArrayList)
_ (.decode decoder nil packet out)
decoded (first out)]
(testing "parses a packet"
(is (not (nil? decoded)))
(is (= :puback (:type decoded))))
(testing "should not be a duplicate"
(is (= false (:duplicate decoded))))
(testing "parses the qos"
(is (= 0 (:qos decoded))))
(testing "should not be retained"
(is (= false (:retain decoded))))
(testing "it parses the message id"
(is (= 5 (:message-id decoded)))))))
| null | https://raw.githubusercontent.com/xively/clj-mqtt/74964112505da717ea88279b62f239146450528c/test/mqtt/packets/puback_test.clj | clojure | fixed header
remaining length
message id
fixed header
remaining length
message id | (ns mqtt.packets.puback-test
(:use clojure.test
mqtt.test-helpers
mqtt.decoder
mqtt.encoder
mqtt.packets.common
mqtt.packets.puback)
(:import [io.netty.buffer Unpooled]
[io.netty.handler.codec EncoderException]))
(deftest puback-validate-message-test
(testing "nil when valid"
(is (= nil (validate-message {:type :puback
:message-id 1}))))
(testing "it throws if no message-id"
(is (thrown? EncoderException (validate-message {:type :puback}))))
(testing "it throws if message-id is 0"
(is (thrown? EncoderException (validate-message {:type :puback
:message-id 0})))))
(deftest puback-encoding-test
(testing "when encoding a simple puback packet"
(let [encoder (make-encoder)
packet {:type :puback :message-id 5}
out (Unpooled/buffer 4)]
(.encode encoder nil packet out)
(is (= (byte-buffer-to-bytes out)
2r01000000
2
0 5])))))
(deftest decoding-puback-packet-test
(testing "when parsing a simple puback packet"
(let [decoder (make-decoder)
packet (bytes-to-byte-buffer
2r01000000
2
0 5)
out (new java.util.ArrayList)
_ (.decode decoder nil packet out)
decoded (first out)]
(testing "parses a packet"
(is (not (nil? decoded)))
(is (= :puback (:type decoded))))
(testing "should not be a duplicate"
(is (= false (:duplicate decoded))))
(testing "parses the qos"
(is (= 0 (:qos decoded))))
(testing "should not be retained"
(is (= false (:retain decoded))))
(testing "it parses the message id"
(is (= 5 (:message-id decoded)))))))
|
854c5f71f4ab1e1f5e556408b5a35d20d78ac20c4af1b5b25b9410647ee53c7f | thierry-martinez/stdcompat | arg.mli | type spec =
| Unit of (unit -> unit)
| Bool of (bool -> unit)
| Set of bool ref
| Clear of bool ref
| String of (string -> unit)
| Set_string of string ref
| Int of (int -> unit)
| Set_int of int ref
| Float of (float -> unit)
| Set_float of float ref
| Tuple of spec list
| Symbol of string list * (string -> unit)
| Rest of (string -> unit)
type key = string
type doc = string
type usage_msg = string
type anon_fun = string -> unit
val parse : (key * spec * doc) list -> anon_fun -> usage_msg -> unit
val parse_argv :
?current:int ref ->
string array -> (key * spec * doc) list -> anon_fun -> usage_msg -> unit
exception Help of string
exception Bad of string
val usage : (key * spec * doc) list -> usage_msg -> unit
val usage_string : (key * spec * doc) list -> usage_msg -> string
val align : (key * spec * doc) list -> (key * spec * doc) list
val current : int ref
| null | https://raw.githubusercontent.com/thierry-martinez/stdcompat/83d786cdb17fae0caadf5c342e283c3dcfee2279/interfaces/3.12/arg.mli | ocaml | type spec =
| Unit of (unit -> unit)
| Bool of (bool -> unit)
| Set of bool ref
| Clear of bool ref
| String of (string -> unit)
| Set_string of string ref
| Int of (int -> unit)
| Set_int of int ref
| Float of (float -> unit)
| Set_float of float ref
| Tuple of spec list
| Symbol of string list * (string -> unit)
| Rest of (string -> unit)
type key = string
type doc = string
type usage_msg = string
type anon_fun = string -> unit
val parse : (key * spec * doc) list -> anon_fun -> usage_msg -> unit
val parse_argv :
?current:int ref ->
string array -> (key * spec * doc) list -> anon_fun -> usage_msg -> unit
exception Help of string
exception Bad of string
val usage : (key * spec * doc) list -> usage_msg -> unit
val usage_string : (key * spec * doc) list -> usage_msg -> string
val align : (key * spec * doc) list -> (key * spec * doc) list
val current : int ref
|
|
2d52d0f6e816fd278c06cc5804eeae5428f9a3653964dac93ba6377f0a8ea62e | snowleopard/hadrian | TestSettings.hs | -- | We create a file <root>/test/ghcconfig containing configuration of test
-- | compiler. We need to search this file for required keys and setting
| required for testsuite e.g. WORDSIZE , HOSTOS etc .
module Oracles.TestSettings (TestSetting (..), testSetting, testRTSSettings) where
import Base
import Hadrian.Oracles.TextFile
testConfigFile :: Action FilePath
testConfigFile = buildRoot <&> (-/- "test/ghcconfig")
| Test settings that are obtained from ghcconfig file .
data TestSetting = TestHostOS
| TestWORDSIZE
| TestTARGETPLATFORM
| TestTargetOS_CPP
| TestTargetARCH_CPP
| TestGhcStage
| TestGhcDebugged
| TestGhcWithNativeCodeGen
| TestGhcWithInterpreter
| TestGhcUnregisterised
| TestGhcWithSMP
| TestGhcDynamicByDefault
| TestGhcDynamic
| TestGhcProfiled
| TestAR
| TestCLANG
| TestLLC
| TestTEST_CC
| TestGhcPackageDbFlag
| TestMinGhcVersion711
| TestMinGhcVersion801
deriving (Show)
-- | Lookup a test setting in @ghcconfig@ file.
-- | To obtain RTS ways supported in @ghcconfig@ file, use 'testRTSSettings'.
testSetting :: TestSetting -> Action String
testSetting key = do
file <- testConfigFile
lookupValueOrError file $ case key of
TestHostOS -> "HostOS"
TestWORDSIZE -> "WORDSIZE"
TestTARGETPLATFORM -> "TARGETPLATFORM"
TestTargetOS_CPP -> "TargetOS_CPP"
TestTargetARCH_CPP -> "TargetARCH_CPP"
TestGhcStage -> "GhcStage"
TestGhcDebugged -> "GhcDebugged"
TestGhcWithNativeCodeGen -> "GhcWithNativeCodeGen"
TestGhcWithInterpreter -> "GhcWithInterpreter"
TestGhcUnregisterised -> "GhcUnregisterised"
TestGhcWithSMP -> "GhcWithSMP"
TestGhcDynamicByDefault -> "GhcDynamicByDefault"
TestGhcDynamic -> "GhcDynamic"
TestGhcProfiled -> "GhcProfiled"
TestAR -> "AR"
TestCLANG -> "CLANG"
TestLLC -> "LLC"
TestTEST_CC -> "TEST_CC"
TestGhcPackageDbFlag -> "GhcPackageDbFlag"
TestMinGhcVersion711 -> "MinGhcVersion711"
TestMinGhcVersion801 -> "MinGhcVersion801"
-- | Get the RTS ways of the test compiler
testRTSSettings :: Action [String]
testRTSSettings = do
file <- testConfigFile
words <$> lookupValueOrError file "GhcRTSWays"
| null | https://raw.githubusercontent.com/snowleopard/hadrian/b9a3f9521b315942e1dabb006688ee7c9902f5fe/src/Oracles/TestSettings.hs | haskell | | We create a file <root>/test/ghcconfig containing configuration of test
| compiler. We need to search this file for required keys and setting
| Lookup a test setting in @ghcconfig@ file.
| To obtain RTS ways supported in @ghcconfig@ file, use 'testRTSSettings'.
| Get the RTS ways of the test compiler | | required for testsuite e.g. WORDSIZE , HOSTOS etc .
module Oracles.TestSettings (TestSetting (..), testSetting, testRTSSettings) where
import Base
import Hadrian.Oracles.TextFile
testConfigFile :: Action FilePath
testConfigFile = buildRoot <&> (-/- "test/ghcconfig")
| Test settings that are obtained from ghcconfig file .
data TestSetting = TestHostOS
| TestWORDSIZE
| TestTARGETPLATFORM
| TestTargetOS_CPP
| TestTargetARCH_CPP
| TestGhcStage
| TestGhcDebugged
| TestGhcWithNativeCodeGen
| TestGhcWithInterpreter
| TestGhcUnregisterised
| TestGhcWithSMP
| TestGhcDynamicByDefault
| TestGhcDynamic
| TestGhcProfiled
| TestAR
| TestCLANG
| TestLLC
| TestTEST_CC
| TestGhcPackageDbFlag
| TestMinGhcVersion711
| TestMinGhcVersion801
deriving (Show)
testSetting :: TestSetting -> Action String
testSetting key = do
file <- testConfigFile
lookupValueOrError file $ case key of
TestHostOS -> "HostOS"
TestWORDSIZE -> "WORDSIZE"
TestTARGETPLATFORM -> "TARGETPLATFORM"
TestTargetOS_CPP -> "TargetOS_CPP"
TestTargetARCH_CPP -> "TargetARCH_CPP"
TestGhcStage -> "GhcStage"
TestGhcDebugged -> "GhcDebugged"
TestGhcWithNativeCodeGen -> "GhcWithNativeCodeGen"
TestGhcWithInterpreter -> "GhcWithInterpreter"
TestGhcUnregisterised -> "GhcUnregisterised"
TestGhcWithSMP -> "GhcWithSMP"
TestGhcDynamicByDefault -> "GhcDynamicByDefault"
TestGhcDynamic -> "GhcDynamic"
TestGhcProfiled -> "GhcProfiled"
TestAR -> "AR"
TestCLANG -> "CLANG"
TestLLC -> "LLC"
TestTEST_CC -> "TEST_CC"
TestGhcPackageDbFlag -> "GhcPackageDbFlag"
TestMinGhcVersion711 -> "MinGhcVersion711"
TestMinGhcVersion801 -> "MinGhcVersion801"
testRTSSettings :: Action [String]
testRTSSettings = do
file <- testConfigFile
words <$> lookupValueOrError file "GhcRTSWays"
|
13a0c168a76019a6c726c6f3f09a16bb43bff2da40d037a0b5e18f285d2048c6 | tsurucapital/franz | Contents.hs | # LANGUAGE NamedFieldPuns #
{-# LANGUAGE BangPatterns #-}
# LANGUAGE RecordWildCards #
module Database.Franz.Contents
( Contents
, Database.Franz.Internal.Contents.indexNames
, Item(..)
, toList
, toVector
, last
, length
, index
, lookupIndex
) where
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import Database.Franz.Internal.Protocol
import Database.Franz.Internal.Contents
import Data.Int
import Prelude hiding (length, last)
data Item = Item
{ seqNo :: !Int
, indices :: !(U.Vector Int64)
, payload :: !B.ByteString
} deriving (Show, Eq)
toList :: Contents -> [Item]
toList contents = [unsafeIndex contents i | i <- [0..length contents - 1]]
toVector :: Contents -> V.Vector Item
toVector contents = V.generate (length contents) (unsafeIndex contents)
last :: Contents -> Maybe Item
last contents
| i >= 0 = Just $ unsafeIndex contents i
| otherwise = Nothing
where
i = length contents - 1
index :: Contents -> Int -> Maybe Item
index contents i
| i >= length contents || i < 0 = Nothing
| otherwise = Just $ unsafeIndex contents i
unsafeIndex :: Contents -> Int -> Item
unsafeIndex Contents{..} i = Item{..}
where
ofs0 = maybe payloadOffset fst $ indicess V.!? (i - 1)
(ofs1, indices) = indicess V.! i
seqNo = seqnoOffset + i + 1
payload = B.take (ofs1 - ofs0) $ B.drop (ofs0 - payloadOffset) payloads
lookupIndex :: Contents -> IndexName -> Maybe (Item -> Int64)
lookupIndex Contents{indexNames} name
= (\j Item{indices} -> indices U.! j) <$> V.elemIndex name indexNames
| null | https://raw.githubusercontent.com/tsurucapital/franz/6894defd76d9be45af5abf59e2325baae109bef6/src/Database/Franz/Contents.hs | haskell | # LANGUAGE BangPatterns # | # LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
module Database.Franz.Contents
( Contents
, Database.Franz.Internal.Contents.indexNames
, Item(..)
, toList
, toVector
, last
, length
, index
, lookupIndex
) where
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import Database.Franz.Internal.Protocol
import Database.Franz.Internal.Contents
import Data.Int
import Prelude hiding (length, last)
data Item = Item
{ seqNo :: !Int
, indices :: !(U.Vector Int64)
, payload :: !B.ByteString
} deriving (Show, Eq)
toList :: Contents -> [Item]
toList contents = [unsafeIndex contents i | i <- [0..length contents - 1]]
toVector :: Contents -> V.Vector Item
toVector contents = V.generate (length contents) (unsafeIndex contents)
last :: Contents -> Maybe Item
last contents
| i >= 0 = Just $ unsafeIndex contents i
| otherwise = Nothing
where
i = length contents - 1
index :: Contents -> Int -> Maybe Item
index contents i
| i >= length contents || i < 0 = Nothing
| otherwise = Just $ unsafeIndex contents i
unsafeIndex :: Contents -> Int -> Item
unsafeIndex Contents{..} i = Item{..}
where
ofs0 = maybe payloadOffset fst $ indicess V.!? (i - 1)
(ofs1, indices) = indicess V.! i
seqNo = seqnoOffset + i + 1
payload = B.take (ofs1 - ofs0) $ B.drop (ofs0 - payloadOffset) payloads
lookupIndex :: Contents -> IndexName -> Maybe (Item -> Int64)
lookupIndex Contents{indexNames} name
= (\j Item{indices} -> indices U.! j) <$> V.elemIndex name indexNames
|
c90ada6ace558b5544785a8ce8599b4e492e76ee2e1d53fddfd3920136d19447 | gafiatulin/codewars | Palindromic.hs | -- Palindromic Numbers
-- /
module Palindromic where
palindromize :: Integer -> (Int, Integer)
palindromize x | (== show x) . reverse . show $ x = (0, x)
| otherwise = (\(k, p) -> (k+1, p)) . palindromize . (+x) . read . reverse . show $ x
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/6%20kyu/Palindromic.hs | haskell | Palindromic Numbers
/ |
module Palindromic where
palindromize :: Integer -> (Int, Integer)
palindromize x | (== show x) . reverse . show $ x = (0, x)
| otherwise = (\(k, p) -> (k+1, p)) . palindromize . (+x) . read . reverse . show $ x
|
41b75cb3de9aa56ca7675f764404d418e606cc2a37afc7dd44a21ee02c265754 | frodwith/cl-urbit | cell-meta.lisp | (defpackage #:urbit/nock/cell-meta
(:use #:cl #:urbit/nock/data #:urbit/nock/mug #:urbit/nock/ideal)
(:import-from #:alexandria #:when-let)
(:export #:cell-meta #:define-cell-methods))
(in-package #:urbit/nock/cell-meta)
; for defining "dumb" cells - you need a place to store a head, tail,
; and a meta object. DEFINE-CELL-METHODS will do the rest.
(deftype cell-meta ()
'(or null mug core-speed (cons mug core-speed) icell))
(defmacro define-cell-methods (klass head tail meta)
`(progn
(defmethod deep ((c ,klass))
t)
(defmethod cached-mug ((c ,klass))
(let ((m (,meta c)))
(etypecase m
(null nil)
(mug m)
(core-speed nil)
(cons (car m))
(icell (icell-mug m)))))
(defmethod (setf cached-mug) (val (c ,klass))
(let ((m (,meta c)))
(typecase m
(null (setf (,meta c) val))
(core-speed (setf (,meta c) (cons val m))))))
(defmethod cached-ideal ((c ,klass))
(let ((m (,meta c)))
(typecase m
(icell m))))
(defmethod (setf cached-ideal) ((val icell) (c ,klass))
(let ((m (,meta c)))
(when-let (spd (typecase m
(core-speed m)
(cons (cdr m))))
(setf (icell-speed val) spd))
(setf (,head c) (icell-head val))
(setf (,tail c) (icell-tail val))
(setf (,meta c) val)
val))
(defmethod head ((c ,klass))
(,head c))
(defmethod (setf head) (val (c ,klass))
(unless (typep (,head c) 'icell)
(setf (,head c) val)) val)
(defmethod tail ((c ,klass))
(,tail c))
(defmethod (setf tail) (val (c ,klass))
(unless (typep (,tail c) 'icell)
(setf (,tail c) val))
val)
(defmethod cached-battery ((c ,klass))
(let ((h (,head c)))
(and (typep h 'icell) h)))
(defmethod (setf cached-battery) ((val icell) (c ,klass))
(setf (,head c) val))
(defmethod cached-speed ((c ,klass))
(let ((m (,meta c)))
(typecase m
(core-speed m)
(cons (cdr m))
(icell (icell-speed m)))))
(defmethod (setf cached-speed) (val (c ,klass))
(let ((m (,meta c)))
(typecase m
((or null core-speed) (setf (,meta c) val))
(mug (setf (,meta c) (cons m val)))
(cons (setf (cdr m) val))
(icell (setf (icell-speed m) val)))))))
| null | https://raw.githubusercontent.com/frodwith/cl-urbit/65af924ee58c4c974056f369158bbc1401308fea/nock/cell-meta.lisp | lisp | for defining "dumb" cells - you need a place to store a head, tail,
and a meta object. DEFINE-CELL-METHODS will do the rest. | (defpackage #:urbit/nock/cell-meta
(:use #:cl #:urbit/nock/data #:urbit/nock/mug #:urbit/nock/ideal)
(:import-from #:alexandria #:when-let)
(:export #:cell-meta #:define-cell-methods))
(in-package #:urbit/nock/cell-meta)
(deftype cell-meta ()
'(or null mug core-speed (cons mug core-speed) icell))
(defmacro define-cell-methods (klass head tail meta)
`(progn
(defmethod deep ((c ,klass))
t)
(defmethod cached-mug ((c ,klass))
(let ((m (,meta c)))
(etypecase m
(null nil)
(mug m)
(core-speed nil)
(cons (car m))
(icell (icell-mug m)))))
(defmethod (setf cached-mug) (val (c ,klass))
(let ((m (,meta c)))
(typecase m
(null (setf (,meta c) val))
(core-speed (setf (,meta c) (cons val m))))))
(defmethod cached-ideal ((c ,klass))
(let ((m (,meta c)))
(typecase m
(icell m))))
(defmethod (setf cached-ideal) ((val icell) (c ,klass))
(let ((m (,meta c)))
(when-let (spd (typecase m
(core-speed m)
(cons (cdr m))))
(setf (icell-speed val) spd))
(setf (,head c) (icell-head val))
(setf (,tail c) (icell-tail val))
(setf (,meta c) val)
val))
(defmethod head ((c ,klass))
(,head c))
(defmethod (setf head) (val (c ,klass))
(unless (typep (,head c) 'icell)
(setf (,head c) val)) val)
(defmethod tail ((c ,klass))
(,tail c))
(defmethod (setf tail) (val (c ,klass))
(unless (typep (,tail c) 'icell)
(setf (,tail c) val))
val)
(defmethod cached-battery ((c ,klass))
(let ((h (,head c)))
(and (typep h 'icell) h)))
(defmethod (setf cached-battery) ((val icell) (c ,klass))
(setf (,head c) val))
(defmethod cached-speed ((c ,klass))
(let ((m (,meta c)))
(typecase m
(core-speed m)
(cons (cdr m))
(icell (icell-speed m)))))
(defmethod (setf cached-speed) (val (c ,klass))
(let ((m (,meta c)))
(typecase m
((or null core-speed) (setf (,meta c) val))
(mug (setf (,meta c) (cons m val)))
(cons (setf (cdr m) val))
(icell (setf (icell-speed m) val)))))))
|
8e6ab1b58c7fdf5f45448be4053076effe239e4050202ddefbcbeeba2c1d2d81 | whamtet/cljs-pdfkit | util.cljc | (ns cljs-pdfkit.util)
(defn capitalize [s]
(str (.toUpperCase (.substring s 0 1)) (.substring s 1)))
(defn camelize [kw]
(let [
[a & b] (.split (name kw) "-")
b (map capitalize b)
]
(symbol (apply str a b))))
(defn key-map [f m]
(zipmap (map f (keys m)) (vals m)))
#?(:cljs
(defn camelize-js [m]
(clj->js (key-map camelize m))))
(defn capitalize-map [m]
(key-map #(-> % name capitalize) m))
(defn cumul
"cumulation of seq"
[s]
(reduce
(fn [[sum done] new]
(conj done (+ sum new)))
[0 []] s))
| null | https://raw.githubusercontent.com/whamtet/cljs-pdfkit/b0e0b9c18df2442ffb0be049107ce3aef9f92037/src/cljs_pdfkit/util.cljc | clojure | (ns cljs-pdfkit.util)
(defn capitalize [s]
(str (.toUpperCase (.substring s 0 1)) (.substring s 1)))
(defn camelize [kw]
(let [
[a & b] (.split (name kw) "-")
b (map capitalize b)
]
(symbol (apply str a b))))
(defn key-map [f m]
(zipmap (map f (keys m)) (vals m)))
#?(:cljs
(defn camelize-js [m]
(clj->js (key-map camelize m))))
(defn capitalize-map [m]
(key-map #(-> % name capitalize) m))
(defn cumul
"cumulation of seq"
[s]
(reduce
(fn [[sum done] new]
(conj done (+ sum new)))
[0 []] s))
|
|
b0cc600fa6ff5b65e06a7981fe38f759103e76788588b43de0ca6429af47bd03 | finkel-lang/finkel | p08.hs | main = putStrLn "plugin/p08.hs"
| null | https://raw.githubusercontent.com/finkel-lang/finkel/74ce4bb779805ad2b141098e29c633523318fa3e/finkel-kernel/test/data/plugin/p08.hs | haskell | main = putStrLn "plugin/p08.hs"
|
|
118c0c45ece12d5c520a1190648e048a78cedab6b757191f971d54e4fc23c8a1 | lamdu/momentu | dropdownlist.hs | # LANGUAGE NoImplicitPrelude , DisambiguateRecordFields #
module Main (main) where
import Control.Lens.Operators
import qualified Data.IORef as IORef
import Data.IORef (IORef)
import qualified Data.Property as Property
import Data.Text (Text)
import GUI.Momentu ((/-/))
import qualified GUI.Momentu as M
import GUI.Momentu.DataFiles (getDefaultFontPath)
import qualified GUI.Momentu.Widgets.DropDownList as DropDownList
import qualified GUI.Momentu.Widgets.Label as Label
import Prelude.Compat
main :: IO ()
main =
do
fontPath <- getDefaultFontPath
dropDownListRef <- IORef.newIORef "blue"
M.defaultSetup "DropDownList" fontPath M.defaultSetupOptions (makeWidget dropDownListRef)
colors :: [(Text, M.Color)]
colors =
[ ("black" , M.Color 0 0 0 1)
, ("blue" , M.Color 0 0 1 1)
, ("green" , M.Color 0 1 0 1)
, ("teal" , M.Color 0 1 1 1)
, ("red" , M.Color 1 0 0 1)
, ("purple", M.Color 1 0 1 1)
, ("brown" , M.Color 0.8 0.5 0 1)
, ("grey" , M.Color 0.5 0.5 0.5 1)
]
makeWidget :: IORef Text -> (Float -> IO M.Font) -> M.DefaultEnvWithCursor -> IO (M.Widget IO)
makeWidget dropDownListRef _getFont env =
do
prop <- Property.fromIORef dropDownListRef ^. Property.mkProperty
let dropDownListWidget =
DropDownList.make env prop (map makeDropDownList colors)
(DropDownList.defaultConfig env "Color") mempty
^. M.tValue
let Just color = lookup (Property.value prop) colors
let box =
M.unitSquare env
& M.tint color
& M.scale 100
(pure box /-/ pure dropDownListWidget) env
& M.weakerEvents (M.quitEventMap env)
& pure
where
makeDropDownList (name, _color) = (name, Label.makeFocusable name env)
| null | https://raw.githubusercontent.com/lamdu/momentu/b287a15f0467176628b0eedf8c70907723a51e69/examples/dropdownlist.hs | haskell | # LANGUAGE NoImplicitPrelude , DisambiguateRecordFields #
module Main (main) where
import Control.Lens.Operators
import qualified Data.IORef as IORef
import Data.IORef (IORef)
import qualified Data.Property as Property
import Data.Text (Text)
import GUI.Momentu ((/-/))
import qualified GUI.Momentu as M
import GUI.Momentu.DataFiles (getDefaultFontPath)
import qualified GUI.Momentu.Widgets.DropDownList as DropDownList
import qualified GUI.Momentu.Widgets.Label as Label
import Prelude.Compat
main :: IO ()
main =
do
fontPath <- getDefaultFontPath
dropDownListRef <- IORef.newIORef "blue"
M.defaultSetup "DropDownList" fontPath M.defaultSetupOptions (makeWidget dropDownListRef)
colors :: [(Text, M.Color)]
colors =
[ ("black" , M.Color 0 0 0 1)
, ("blue" , M.Color 0 0 1 1)
, ("green" , M.Color 0 1 0 1)
, ("teal" , M.Color 0 1 1 1)
, ("red" , M.Color 1 0 0 1)
, ("purple", M.Color 1 0 1 1)
, ("brown" , M.Color 0.8 0.5 0 1)
, ("grey" , M.Color 0.5 0.5 0.5 1)
]
makeWidget :: IORef Text -> (Float -> IO M.Font) -> M.DefaultEnvWithCursor -> IO (M.Widget IO)
makeWidget dropDownListRef _getFont env =
do
prop <- Property.fromIORef dropDownListRef ^. Property.mkProperty
let dropDownListWidget =
DropDownList.make env prop (map makeDropDownList colors)
(DropDownList.defaultConfig env "Color") mempty
^. M.tValue
let Just color = lookup (Property.value prop) colors
let box =
M.unitSquare env
& M.tint color
& M.scale 100
(pure box /-/ pure dropDownListWidget) env
& M.weakerEvents (M.quitEventMap env)
& pure
where
makeDropDownList (name, _color) = (name, Label.makeFocusable name env)
|
|
e44b254e9a3ac1a1e82dd16de5d53cf3f19a65fa417f026d8a1b4acae31b0647 | mvdcamme/meta-tracing-JIT | Rec interpreter direct.scm |
;;;; Basic recursive Slip interpreter.
;;;; This is a stand-alone interpreter and should not be executed by another interpreter.
;;;; It contains no annotations for tracing.
;;;; It can be used to verify that the semantics of the other recursive Slip interpreter
;;;; (which are based on this interpreter) are correct.
(begin
(define (assocv el lst)
(cond ((null? lst) #f)
((eq? (vector-ref (car lst) 0) el) (car lst))
(else (assocv el (cdr lst)))))
(define debug '())
(define (map f lst)
(define (loop list acc)
(if (null? list)
(reverse acc)
(loop (cdr list) (cons (begin debug (f (car list))) acc))))
(loop lst '()))
(define (for-each f lst)
(define (loop list)
(if (not (null? list))
(begin (f (car list))
(loop (cdr list)))
'()))
(loop lst)
(void))
(define meta-circularity-level 0)
;;; Binds the symbol 'random to the native random function.
;;; In contrast with the other rec Slip interpreters, this random-function refers to the native
;;; Racket random function instead of the random-function introduced by the tracing interpreter.
(define random-binding (vector 'random random))
(define environment (list random-binding))
(define (loop output)
(define rollback environment)
(define evaluate '())
(define (abort message qualifier)
(display message)
message)
(define (bind-variable variable value)
(define binding (vector variable value))
(set! environment (cons binding environment)))
(define (bind-parameters parameters arguments)
(if (symbol? parameters)
(bind-variable parameters arguments)
(if (and (pair? parameters) (pair? arguments))
(let* ((variable (car parameters))
(value (car arguments)))
(bind-variable variable value)
(bind-parameters (cdr parameters) (cdr arguments)))
(if (not (and (null? parameters) (null? arguments)))
(error "Incorrect number of arguments, parameters: " parameters ", arguments: " arguments)
'()))))
(define (thunkify expression)
(define frozen-environment environment)
(define value (evaluate expression))
(set! environment frozen-environment)
value)
(define (evaluate-sequence expressions)
(if (null? expressions)
'()
(let* ((head (car expressions))
(tail (cdr expressions))
(value (evaluate head)))
(if (null? tail)
value
(evaluate-sequence tail)))))
(define (close parameters expressions)
(define lexical-environment environment)
(define (closure . arguments)
(define dynamic-environment environment)
(set! environment lexical-environment)
(bind-parameters parameters arguments)
(let* ((value (evaluate-sequence expressions)))
(set! environment dynamic-environment)
value))
closure)
(define (evaluate-and . expressions)
(define (and-loop expressions prev)
(if (null? expressions)
prev
(let* ((value (evaluate (car expressions))))
(if value
(and-loop (cdr expressions) value)
#f))))
(and-loop expressions #t))
(define (evaluate-application operator)
(lambda operands
(apply (evaluate operator) (map evaluate operands))))
(define (evaluate-apply . expressions)
(apply (evaluate (car expressions)) (evaluate (cadr expressions))))
(define (evaluate-begin . expressions)
(evaluate-sequence expressions))
(define (evaluate-cond . expressions)
(define (cond-loop expressions)
(cond ((null? expressions) '())
((eq? (car (car expressions)) 'else)
(if (not (null? (cdr expressions)))
(error "Syntax error: 'else' should be at the end of a cond-expression")
(evaluate-sequence (cdr (car expressions)))))
((not (eq? (evaluate (car (car expressions))) #f))
(evaluate-sequence (cdr (car expressions))))
(else (cond-loop (cdr expressions)))))
(cond-loop expressions))
(define (evaluate-define pattern . expressions)
(if (symbol? pattern)
(let* ((value (evaluate (car expressions)))
(binding (vector pattern value)))
(set! environment (cons binding environment))
value)
(let* ((binding (vector (car pattern) '())))
(set! environment (cons binding environment))
(let* ((closure (close (cdr pattern) expressions)))
(vector-set! binding 1 closure)
closure))))
(define (evaluate-eval expression)
(evaluate (evaluate expression)))
(define (evaluate-if predicate consequent . alternate)
(if (evaluate predicate)
(thunkify consequent)
(if (null? alternate)
'()
(thunkify (car alternate)))))
(define (evaluate-lambda parameters . expressions)
(close parameters expressions))
(define (evaluate-let . expressions)
(define frozen-environment environment)
(define (evaluate-bindings bindings bindings-to-add)
(if (null? bindings)
bindings-to-add
(let* ((let-binding (car bindings))
(variable (car let-binding))
(value (evaluate (cadr let-binding)))
(binding (vector variable value)))
(evaluate-bindings (cdr bindings) (cons binding bindings-to-add)))))
(for-each (lambda (binding) (set! environment (cons binding environment)))
(evaluate-bindings (car expressions) '()))
(let* ((value (evaluate-sequence (cdr expressions))))
(set! environment frozen-environment)
value))
(define (evaluate-let* bindings . expressions)
(define frozen-environment environment)
(define (evaluate-bindings bindings)
(if (not (null? bindings))
(let* ((let*-binding (car bindings))
(variable (car let*-binding))
(value (evaluate (cadr let*-binding)))
(binding (vector variable value)))
(set! environment (cons binding environment))
(evaluate-bindings (cdr bindings)))
'()))
(evaluate-bindings bindings)
(let* ((value (evaluate-sequence expressions)))
(set! environment frozen-environment)
value))
(define (evaluate-letrec . expressions)
(define frozen-environment environment)
(define (evaluate-bindings bindings)
(if (not (null? bindings))
(let* ((letrec-binding (car bindings))
(variable (car letrec-binding))
(binding (vector variable '())))
(set! environment (cons binding environment))
(vector-set! binding 1 (evaluate (cadr letrec-binding)))
(evaluate-bindings (cdr bindings)))
'()))
(evaluate-bindings (car expressions))
(let* ((value (evaluate-sequence (cdr expressions))))
(set! environment frozen-environment)
value))
(define (evaluate-load string)
(let* ((port (open-input-file string))
(exp (read port)))
(close-input-port port)
(evaluate exp)))
(define (evaluate-or . expressions)
(define (or-loop expressions)
(if (null? expressions)
#f
(let* ((value (evaluate (car expressions))))
(if value
value
(or-loop (cdr expressions))))))
(or-loop expressions))
(define (evaluate-quote expression)
expression)
(define (evaluate-set! variable expression)
(define value (evaluate expression))
(define binding (assocv variable environment))
(if (vector? binding)
(vector-set! binding 1 value)
(abort "inaccessible variable: " variable)))
(define (evaluate-variable variable)
(define binding (assocv variable environment))
(if (vector? binding)
(vector-ref binding 1)
((begin debug eval) variable (make-base-namespace))))
(define (actual-evaluate expression)
(cond
((symbol? expression)
(evaluate-variable expression))
((pair? expression)
(let* ((operator (car expression))
(operands (cdr expression)))
(apply
(cond ((eq? operator 'and)
evaluate-and)
((eq? operator 'apply)
evaluate-apply)
((eq? operator 'begin)
evaluate-begin)
((eq? operator 'cond)
evaluate-cond)
((eq? operator 'define)
evaluate-define)
((eq? operator 'eval)
evaluate-eval)
((eq? operator 'if)
evaluate-if)
((eq? operator 'lambda)
evaluate-lambda)
((eq? operator 'let)
evaluate-let)
((eq? operator 'let*)
evaluate-let*)
((eq? operator 'letrec)
evaluate-letrec)
((eq? operator 'load)
evaluate-load)
((eq? operator 'or)
evaluate-or)
((eq? operator 'quote)
evaluate-quote)
((eq? operator 'set!)
evaluate-set!)
(else
(evaluate-application operator))) operands)))
(else
expression)))
(set! evaluate actual-evaluate)
(evaluate-load "input_file.scm"))
(loop "Slip")) | null | https://raw.githubusercontent.com/mvdcamme/meta-tracing-JIT/640af917e473f3793ab12791dcb2c80f617b8a0d/benchmarks/Slip%20interpreters/Rec%20interpreter%20direct.scm | scheme | Basic recursive Slip interpreter.
This is a stand-alone interpreter and should not be executed by another interpreter.
It contains no annotations for tracing.
It can be used to verify that the semantics of the other recursive Slip interpreter
(which are based on this interpreter) are correct.
Binds the symbol 'random to the native random function.
In contrast with the other rec Slip interpreters, this random-function refers to the native
Racket random function instead of the random-function introduced by the tracing interpreter. |
(begin
(define (assocv el lst)
(cond ((null? lst) #f)
((eq? (vector-ref (car lst) 0) el) (car lst))
(else (assocv el (cdr lst)))))
(define debug '())
(define (map f lst)
(define (loop list acc)
(if (null? list)
(reverse acc)
(loop (cdr list) (cons (begin debug (f (car list))) acc))))
(loop lst '()))
(define (for-each f lst)
(define (loop list)
(if (not (null? list))
(begin (f (car list))
(loop (cdr list)))
'()))
(loop lst)
(void))
(define meta-circularity-level 0)
(define random-binding (vector 'random random))
(define environment (list random-binding))
(define (loop output)
(define rollback environment)
(define evaluate '())
(define (abort message qualifier)
(display message)
message)
(define (bind-variable variable value)
(define binding (vector variable value))
(set! environment (cons binding environment)))
(define (bind-parameters parameters arguments)
(if (symbol? parameters)
(bind-variable parameters arguments)
(if (and (pair? parameters) (pair? arguments))
(let* ((variable (car parameters))
(value (car arguments)))
(bind-variable variable value)
(bind-parameters (cdr parameters) (cdr arguments)))
(if (not (and (null? parameters) (null? arguments)))
(error "Incorrect number of arguments, parameters: " parameters ", arguments: " arguments)
'()))))
(define (thunkify expression)
(define frozen-environment environment)
(define value (evaluate expression))
(set! environment frozen-environment)
value)
(define (evaluate-sequence expressions)
(if (null? expressions)
'()
(let* ((head (car expressions))
(tail (cdr expressions))
(value (evaluate head)))
(if (null? tail)
value
(evaluate-sequence tail)))))
(define (close parameters expressions)
(define lexical-environment environment)
(define (closure . arguments)
(define dynamic-environment environment)
(set! environment lexical-environment)
(bind-parameters parameters arguments)
(let* ((value (evaluate-sequence expressions)))
(set! environment dynamic-environment)
value))
closure)
(define (evaluate-and . expressions)
(define (and-loop expressions prev)
(if (null? expressions)
prev
(let* ((value (evaluate (car expressions))))
(if value
(and-loop (cdr expressions) value)
#f))))
(and-loop expressions #t))
(define (evaluate-application operator)
(lambda operands
(apply (evaluate operator) (map evaluate operands))))
(define (evaluate-apply . expressions)
(apply (evaluate (car expressions)) (evaluate (cadr expressions))))
(define (evaluate-begin . expressions)
(evaluate-sequence expressions))
(define (evaluate-cond . expressions)
(define (cond-loop expressions)
(cond ((null? expressions) '())
((eq? (car (car expressions)) 'else)
(if (not (null? (cdr expressions)))
(error "Syntax error: 'else' should be at the end of a cond-expression")
(evaluate-sequence (cdr (car expressions)))))
((not (eq? (evaluate (car (car expressions))) #f))
(evaluate-sequence (cdr (car expressions))))
(else (cond-loop (cdr expressions)))))
(cond-loop expressions))
(define (evaluate-define pattern . expressions)
(if (symbol? pattern)
(let* ((value (evaluate (car expressions)))
(binding (vector pattern value)))
(set! environment (cons binding environment))
value)
(let* ((binding (vector (car pattern) '())))
(set! environment (cons binding environment))
(let* ((closure (close (cdr pattern) expressions)))
(vector-set! binding 1 closure)
closure))))
(define (evaluate-eval expression)
(evaluate (evaluate expression)))
(define (evaluate-if predicate consequent . alternate)
(if (evaluate predicate)
(thunkify consequent)
(if (null? alternate)
'()
(thunkify (car alternate)))))
(define (evaluate-lambda parameters . expressions)
(close parameters expressions))
(define (evaluate-let . expressions)
(define frozen-environment environment)
(define (evaluate-bindings bindings bindings-to-add)
(if (null? bindings)
bindings-to-add
(let* ((let-binding (car bindings))
(variable (car let-binding))
(value (evaluate (cadr let-binding)))
(binding (vector variable value)))
(evaluate-bindings (cdr bindings) (cons binding bindings-to-add)))))
(for-each (lambda (binding) (set! environment (cons binding environment)))
(evaluate-bindings (car expressions) '()))
(let* ((value (evaluate-sequence (cdr expressions))))
(set! environment frozen-environment)
value))
(define (evaluate-let* bindings . expressions)
(define frozen-environment environment)
(define (evaluate-bindings bindings)
(if (not (null? bindings))
(let* ((let*-binding (car bindings))
(variable (car let*-binding))
(value (evaluate (cadr let*-binding)))
(binding (vector variable value)))
(set! environment (cons binding environment))
(evaluate-bindings (cdr bindings)))
'()))
(evaluate-bindings bindings)
(let* ((value (evaluate-sequence expressions)))
(set! environment frozen-environment)
value))
(define (evaluate-letrec . expressions)
(define frozen-environment environment)
(define (evaluate-bindings bindings)
(if (not (null? bindings))
(let* ((letrec-binding (car bindings))
(variable (car letrec-binding))
(binding (vector variable '())))
(set! environment (cons binding environment))
(vector-set! binding 1 (evaluate (cadr letrec-binding)))
(evaluate-bindings (cdr bindings)))
'()))
(evaluate-bindings (car expressions))
(let* ((value (evaluate-sequence (cdr expressions))))
(set! environment frozen-environment)
value))
(define (evaluate-load string)
(let* ((port (open-input-file string))
(exp (read port)))
(close-input-port port)
(evaluate exp)))
(define (evaluate-or . expressions)
(define (or-loop expressions)
(if (null? expressions)
#f
(let* ((value (evaluate (car expressions))))
(if value
value
(or-loop (cdr expressions))))))
(or-loop expressions))
(define (evaluate-quote expression)
expression)
(define (evaluate-set! variable expression)
(define value (evaluate expression))
(define binding (assocv variable environment))
(if (vector? binding)
(vector-set! binding 1 value)
(abort "inaccessible variable: " variable)))
(define (evaluate-variable variable)
(define binding (assocv variable environment))
(if (vector? binding)
(vector-ref binding 1)
((begin debug eval) variable (make-base-namespace))))
(define (actual-evaluate expression)
(cond
((symbol? expression)
(evaluate-variable expression))
((pair? expression)
(let* ((operator (car expression))
(operands (cdr expression)))
(apply
(cond ((eq? operator 'and)
evaluate-and)
((eq? operator 'apply)
evaluate-apply)
((eq? operator 'begin)
evaluate-begin)
((eq? operator 'cond)
evaluate-cond)
((eq? operator 'define)
evaluate-define)
((eq? operator 'eval)
evaluate-eval)
((eq? operator 'if)
evaluate-if)
((eq? operator 'lambda)
evaluate-lambda)
((eq? operator 'let)
evaluate-let)
((eq? operator 'let*)
evaluate-let*)
((eq? operator 'letrec)
evaluate-letrec)
((eq? operator 'load)
evaluate-load)
((eq? operator 'or)
evaluate-or)
((eq? operator 'quote)
evaluate-quote)
((eq? operator 'set!)
evaluate-set!)
(else
(evaluate-application operator))) operands)))
(else
expression)))
(set! evaluate actual-evaluate)
(evaluate-load "input_file.scm"))
(loop "Slip")) |
40171649864f9e532c72817fe9454c63c9f344d4432d33852d0a142ce301f26c | tallaproject/onion | onion_base64.erl | %%%
Copyright ( c ) 2016 The Talla Authors . All rights reserved .
%%% Use of this source code is governed by a BSD-style
%%% license that can be found in the LICENSE file.
%%%
%%% -----------------------------------------------------------
@author < >
%%% @doc Base64 wrapper API
%%%
%%% This module contains a base64 API that allows us to encode
%%% and decode binaries without the ordinary Base64 padding.
%%%
%%% @end
%%% -----------------------------------------------------------
-module(onion_base64).
%% API.
-export([encode/1,
decode/1,
valid/1
]).
%% Types.
-export_type([base64_encoded/0]).
-type base64_encoded() :: binary().
-include("onion_test.hrl").
-define(BASE64_ALPHABET, lists:seq($0, $9) ++
lists:seq($a, $z) ++
lists:seq($A, $Z) ++
"+/").
-spec encode(Data) -> Encoded
when
Data :: binary(),
Encoded :: base64_encoded().
encode(Data) when is_binary(Data) ->
onion_binary:trim(base64:encode(Data), <<"=">>).
-spec decode(Encoded) -> {ok, Decoded} | {error, Reason}
when
Encoded :: base64_encoded(),
Decoded :: binary(),
Reason :: term().
decode(Encoded) when is_binary(Encoded) ->
try
case byte_size(Encoded) rem 4 of
3 ->
{ok, base64:decode(<<Encoded/binary, "=">>)};
2 ->
{ok, base64:decode(<<Encoded/binary, "==">>)};
_ ->
{ok, base64:decode(Encoded)}
end
catch _:_ ->
{error, invalid_base64}
end.
%% @doc Check if a given binary is valid Base64.
-spec valid(Data) -> boolean()
when
Data :: binary() | string().
valid(Data) when is_list(Data) ->
onion_string:valid(Data, ?BASE64_ALPHABET);
valid(Data) when is_binary(Data) ->
valid(binary_to_list(Data)).
-ifdef(TEST).
base64_rfc4648_encode_test() ->
[
?assertEqual(encode(<<>>), <<>>),
?assertEqual(encode(<<"f">>), <<"Zg">>),
?assertEqual(encode(<<"fo">>), <<"Zm8">>),
?assertEqual(encode(<<"foo">>), <<"Zm9v">>),
?assertEqual(encode(<<"foob">>), <<"Zm9vYg">>),
?assertEqual(encode(<<"fooba">>), <<"Zm9vYmE">>),
?assertEqual(encode(<<"foobar">>), <<"Zm9vYmFy">>)
].
base64_rfc4648_decode_test() ->
[
?assertEqual(decode(<<>>), {ok, <<>>}),
?assertEqual(decode(<<"Zg">>), {ok, <<"f">>}),
?assertEqual(decode(<<"Zm8">>), {ok, <<"fo">>}),
?assertEqual(decode(<<"Zm9v">>), {ok, <<"foo">>}),
?assertEqual(decode(<<"Zm9vYg">>), {ok, <<"foob">>}),
?assertEqual(decode(<<"Zm9vYmE">>), {ok, <<"fooba">>}),
?assertEqual(decode(<<"Zm9vYmFy">>), {ok, <<"foobar">>})
].
-endif.
| null | https://raw.githubusercontent.com/tallaproject/onion/d0c3f86c726c302744d3cfffa2de21f85c190cf0/src/onion_base64.erl | erlang |
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-----------------------------------------------------------
@doc Base64 wrapper API
This module contains a base64 API that allows us to encode
and decode binaries without the ordinary Base64 padding.
@end
-----------------------------------------------------------
API.
Types.
@doc Check if a given binary is valid Base64. | Copyright ( c ) 2016 The Talla Authors . All rights reserved .
@author < >
-module(onion_base64).
-export([encode/1,
decode/1,
valid/1
]).
-export_type([base64_encoded/0]).
-type base64_encoded() :: binary().
-include("onion_test.hrl").
-define(BASE64_ALPHABET, lists:seq($0, $9) ++
lists:seq($a, $z) ++
lists:seq($A, $Z) ++
"+/").
-spec encode(Data) -> Encoded
when
Data :: binary(),
Encoded :: base64_encoded().
encode(Data) when is_binary(Data) ->
onion_binary:trim(base64:encode(Data), <<"=">>).
-spec decode(Encoded) -> {ok, Decoded} | {error, Reason}
when
Encoded :: base64_encoded(),
Decoded :: binary(),
Reason :: term().
decode(Encoded) when is_binary(Encoded) ->
try
case byte_size(Encoded) rem 4 of
3 ->
{ok, base64:decode(<<Encoded/binary, "=">>)};
2 ->
{ok, base64:decode(<<Encoded/binary, "==">>)};
_ ->
{ok, base64:decode(Encoded)}
end
catch _:_ ->
{error, invalid_base64}
end.
-spec valid(Data) -> boolean()
when
Data :: binary() | string().
valid(Data) when is_list(Data) ->
onion_string:valid(Data, ?BASE64_ALPHABET);
valid(Data) when is_binary(Data) ->
valid(binary_to_list(Data)).
-ifdef(TEST).
base64_rfc4648_encode_test() ->
[
?assertEqual(encode(<<>>), <<>>),
?assertEqual(encode(<<"f">>), <<"Zg">>),
?assertEqual(encode(<<"fo">>), <<"Zm8">>),
?assertEqual(encode(<<"foo">>), <<"Zm9v">>),
?assertEqual(encode(<<"foob">>), <<"Zm9vYg">>),
?assertEqual(encode(<<"fooba">>), <<"Zm9vYmE">>),
?assertEqual(encode(<<"foobar">>), <<"Zm9vYmFy">>)
].
base64_rfc4648_decode_test() ->
[
?assertEqual(decode(<<>>), {ok, <<>>}),
?assertEqual(decode(<<"Zg">>), {ok, <<"f">>}),
?assertEqual(decode(<<"Zm8">>), {ok, <<"fo">>}),
?assertEqual(decode(<<"Zm9v">>), {ok, <<"foo">>}),
?assertEqual(decode(<<"Zm9vYg">>), {ok, <<"foob">>}),
?assertEqual(decode(<<"Zm9vYmE">>), {ok, <<"fooba">>}),
?assertEqual(decode(<<"Zm9vYmFy">>), {ok, <<"foobar">>})
].
-endif.
|
a87f7b355c8446197c02b9a74ad612337121cfefc1f7c82bd4be48d611092d0c | dannypsnl/k | info.rkt | #lang info
(define collection 'multi)
(define deps '())
(define build-deps '("base"
"rackunit-lib"
"k-core"
"k-lib"))
(define update-implies '("k-core" "k-lib"))
(define pkg-desc "test of k")
(define pkg-authors '(dannypsnl cybai))
| null | https://raw.githubusercontent.com/dannypsnl/k/2b5f5066806a5bbd0733b781a2ed5fce6956a4f5/k-test/info.rkt | racket | #lang info
(define collection 'multi)
(define deps '())
(define build-deps '("base"
"rackunit-lib"
"k-core"
"k-lib"))
(define update-implies '("k-core" "k-lib"))
(define pkg-desc "test of k")
(define pkg-authors '(dannypsnl cybai))
|
|
d663de491f515429cb7b191f4bb0ab769a1422578f29c7bc826e8cf4a705796b | learningclojurescript/code-examples | outer.cljs | (ns cljs-modules.outer
(:require [om.core :as om]
[om.dom :as dom :include-macros true]
[cljs-modules.render :as render]
[cljs-modules.modules :as modules]))
(defn outer-component [app owner opts]
(reify om/IRender
(render [_]
(dom/div #js {} nil
(dom/h1 #js {} "Hello from Outer!")
(dom/a #js {:href "/app"} "inner")))))
(defmethod render/active-component :outer/outer [_]
outer-component)
(modules/set-loaded! "outer")
| null | https://raw.githubusercontent.com/learningclojurescript/code-examples/fdbd0e35ae5a16d53f1f784a52c25bcd4e5a8097/chapter-6/cljs-modules/src/cljs_modules/outer.cljs | clojure | (ns cljs-modules.outer
(:require [om.core :as om]
[om.dom :as dom :include-macros true]
[cljs-modules.render :as render]
[cljs-modules.modules :as modules]))
(defn outer-component [app owner opts]
(reify om/IRender
(render [_]
(dom/div #js {} nil
(dom/h1 #js {} "Hello from Outer!")
(dom/a #js {:href "/app"} "inner")))))
(defmethod render/active-component :outer/outer [_]
outer-component)
(modules/set-loaded! "outer")
|
|
ba272f812458801edde33785ab17ed9fdac0d353f6add48dda073f6e02cdab6c | gedge-platform/gedge-platform | amqp10_client_sessions_sup.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(amqp10_client_sessions_sup).
-behaviour(supervisor).
%% Private API.
-export([start_link/0]).
%% Supervisor callbacks.
-export([init/1]).
-define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args},
transient, 5000, Type, [Mod]}).
%% -------------------------------------------------------------------
%% Private API.
%% -------------------------------------------------------------------
-spec start_link() ->
{ok, pid()} | ignore | {error, any()}.
start_link() ->
supervisor:start_link(?MODULE, []).
%% -------------------------------------------------------------------
%% Supervisor callbacks.
%% -------------------------------------------------------------------
init(Args) ->
Template = ?CHILD(session, amqp10_client_session, worker, Args),
{ok, {{simple_one_for_one, 0, 1}, [Template]}}.
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/amqp10_client/src/amqp10_client_sessions_sup.erl | erlang |
Private API.
Supervisor callbacks.
-------------------------------------------------------------------
Private API.
-------------------------------------------------------------------
-------------------------------------------------------------------
Supervisor callbacks.
------------------------------------------------------------------- | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(amqp10_client_sessions_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args},
transient, 5000, Type, [Mod]}).
-spec start_link() ->
{ok, pid()} | ignore | {error, any()}.
start_link() ->
supervisor:start_link(?MODULE, []).
init(Args) ->
Template = ?CHILD(session, amqp10_client_session, worker, Args),
{ok, {{simple_one_for_one, 0, 1}, [Template]}}.
|
244bf4d6df5f1993bd9b1fd6cc85e5b1eaca6c2f7b93b4535be13eece2fe8181 | bia-technologies/statsbit | health_test.clj | Copyright 2020 BIA - Technologies Limited Liability Company
;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; -2.0
;;
;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns ru.bia-tech.statsbit.http.health-test
(:require
[ru.bia-tech.statsbit.http.handler :as handler]
[ru.bia-tech.statsbit.test.fixtures :as fixtures]
[ring.mock.request :as mock.request]
[ring.util.http-predicates :as http-predicates]
[clojure.test :as t]))
(t/use-fixtures :each fixtures/each)
(t/deftest health
(let [handler (handler/build)
req (mock.request/request :get "/health")
resp (handler req)]
(t/is (http-predicates/ok? resp))))
| null | https://raw.githubusercontent.com/bia-technologies/statsbit/4102ca5e5d39b1c06541b49615c6de83e7f4ef36/backend/test/ru/bia_tech/statsbit/http/health_test.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Copyright 2020 BIA - Technologies Limited Liability Company
distributed under the License is distributed on an " AS IS " BASIS ,
(ns ru.bia-tech.statsbit.http.health-test
(:require
[ru.bia-tech.statsbit.http.handler :as handler]
[ru.bia-tech.statsbit.test.fixtures :as fixtures]
[ring.mock.request :as mock.request]
[ring.util.http-predicates :as http-predicates]
[clojure.test :as t]))
(t/use-fixtures :each fixtures/each)
(t/deftest health
(let [handler (handler/build)
req (mock.request/request :get "/health")
resp (handler req)]
(t/is (http-predicates/ok? resp))))
|
33343f1d4719647d8623a1598fe6f1b755b466972b253077257517cb73ab2ad0 | sol/doctest | Foo.hs | module Foo where
-- $setup
-- >>> import Test.QuickCheck
> > > let arbitraryEven = ( * 2 ) ` fmap ` arbitrary
-- |
-- prop> forAll arbitraryEven even
foo = undefined
| null | https://raw.githubusercontent.com/sol/doctest/ec6498542986b659f50e961b02144923f6f41eba/test/integration/property-setup/Foo.hs | haskell | $setup
>>> import Test.QuickCheck
|
prop> forAll arbitraryEven even | module Foo where
> > > let arbitraryEven = ( * 2 ) ` fmap ` arbitrary
foo = undefined
|
6df70e54494bc5ddf3595f515b93702acda6e62e4d24dad4654a84537d7b8acb | serokell/log-warper | LogHandler.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
|
Module : System . Log . LogHandler
Copyright : Copyright ( C ) 2004 - 2011 License : BSD3
Maintainer : < >
Stability : provisional
Portability : portable
Definition of log handler support
For some handlers , check out " System . WLog . Handler . Simple " and
" System . WLog . Handler . Syslog " .
Please see " System . WLog . Logger " for extensive documentation on the
logging system .
Written by , jgoerzen\@complete.org
Module : System.Log.LogHandler
Copyright : Copyright (C) 2004-2011 John Goerzen
License : BSD3
Maintainer : John Goerzen <>
Stability : provisional
Portability: portable
Definition of log handler support
For some handlers, check out "System.WLog.Handler.Simple" and
"System.WLog.Handler.Syslog".
Please see "System.WLog.Logger" for extensive documentation on the
logging system.
Written by John Goerzen, jgoerzen\@complete.org
-}
module System.Wlog.LogHandler
( -- * Basic Types
LogHandlerTag(..)
, LogHandler(..)
, logHandlerMessage
) where
import Universum
import Data.Text.Lazy.Builder as B
import System.Wlog.Formatter (LogFormatter, nullFormatter)
import System.Wlog.LoggerName (LoggerName (..))
import System.Wlog.Severity (LogRecord (..), Severities)
import qualified Data.Set as Set
-- | Logs an event if it meets the requirements
-- given by the most recent call to 'setLevel'.
logHandlerMessage :: (MonadIO m, LogHandler a) => a -> LogRecord -> LoggerName -> m ()
logHandlerMessage h lr@(LR pri _) logname =
when (pri `Set.member` getLevel h) $ do
let lName = getLoggerName logname
formattedMsg <- liftIO $ getFormatter h h lr lName
emit h formattedMsg lName
-- | Tag identifying handlers.
data LogHandlerTag
= HandlerFilelike FilePath
| HandlerOther String
deriving (Show, Eq)
-- | This is the base class for the various log handlers. They should
-- all adhere to this class.
class LogHandler a where
TODO it should be data / type family like in ' System . Exception '
-- | Tag of handler. Is arbitrary. Made for identification.
getTag :: a -> LogHandlerTag
-- | Sets the log level. 'handle' will drop items beneath this
-- level.
setLevel :: a -> Severities -> a
-- | Gets the current level.
getLevel :: a -> Severities
| Set a log formatter to customize the log format for this
setFormatter :: a -> LogFormatter a -> a
getFormatter :: a -> LogFormatter a
getFormatter _h = nullFormatter
-- | Forces an event to be logged regardless of
-- the configured level.
emit :: MonadIO m => a -> B.Builder -> Text -> m ()
| Read back from logger ( e.g. file ) , newest first . You specify
the number of ( newest ) logging entries . Logger can return @pure
-- []@ if this behaviour can't be emulated or store buffer.
readBack :: MonadIO m => a -> Int -> m [Text]
-- | Closes the logging system, causing it to close
-- any open files, etc.
close :: MonadIO m => a -> m ()
| null | https://raw.githubusercontent.com/serokell/log-warper/a6dd74a1085e8c6d94a4aefc2a036efe30f6cde5/src/System/Wlog/LogHandler.hs | haskell | * Basic Types
| Logs an event if it meets the requirements
given by the most recent call to 'setLevel'.
| Tag identifying handlers.
| This is the base class for the various log handlers. They should
all adhere to this class.
| Tag of handler. Is arbitrary. Made for identification.
| Sets the log level. 'handle' will drop items beneath this
level.
| Gets the current level.
| Forces an event to be logged regardless of
the configured level.
[]@ if this behaviour can't be emulated or store buffer.
| Closes the logging system, causing it to close
any open files, etc. | # LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
|
Module : System . Log . LogHandler
Copyright : Copyright ( C ) 2004 - 2011 License : BSD3
Maintainer : < >
Stability : provisional
Portability : portable
Definition of log handler support
For some handlers , check out " System . WLog . Handler . Simple " and
" System . WLog . Handler . Syslog " .
Please see " System . WLog . Logger " for extensive documentation on the
logging system .
Written by , jgoerzen\@complete.org
Module : System.Log.LogHandler
Copyright : Copyright (C) 2004-2011 John Goerzen
License : BSD3
Maintainer : John Goerzen <>
Stability : provisional
Portability: portable
Definition of log handler support
For some handlers, check out "System.WLog.Handler.Simple" and
"System.WLog.Handler.Syslog".
Please see "System.WLog.Logger" for extensive documentation on the
logging system.
Written by John Goerzen, jgoerzen\@complete.org
-}
module System.Wlog.LogHandler
LogHandlerTag(..)
, LogHandler(..)
, logHandlerMessage
) where
import Universum
import Data.Text.Lazy.Builder as B
import System.Wlog.Formatter (LogFormatter, nullFormatter)
import System.Wlog.LoggerName (LoggerName (..))
import System.Wlog.Severity (LogRecord (..), Severities)
import qualified Data.Set as Set
logHandlerMessage :: (MonadIO m, LogHandler a) => a -> LogRecord -> LoggerName -> m ()
logHandlerMessage h lr@(LR pri _) logname =
when (pri `Set.member` getLevel h) $ do
let lName = getLoggerName logname
formattedMsg <- liftIO $ getFormatter h h lr lName
emit h formattedMsg lName
data LogHandlerTag
= HandlerFilelike FilePath
| HandlerOther String
deriving (Show, Eq)
class LogHandler a where
TODO it should be data / type family like in ' System . Exception '
getTag :: a -> LogHandlerTag
setLevel :: a -> Severities -> a
getLevel :: a -> Severities
| Set a log formatter to customize the log format for this
setFormatter :: a -> LogFormatter a -> a
getFormatter :: a -> LogFormatter a
getFormatter _h = nullFormatter
emit :: MonadIO m => a -> B.Builder -> Text -> m ()
| Read back from logger ( e.g. file ) , newest first . You specify
the number of ( newest ) logging entries . Logger can return @pure
readBack :: MonadIO m => a -> Int -> m [Text]
close :: MonadIO m => a -> m ()
|
73e129bbb71f2f5ee2fa0ad72f868bbe9963431d7ba5f395c67228e17789e909 | NorfairKing/easyspec | Nine.hs | # LANGUAGE NoImplicitPrelude #
module Nine where
import Prelude ((+), (-), concat, drop, map, take)
{-# ANN module "HLint: ignore Use foldr" #-}
myId :: a -> a
myId a = a
myPlusPlus :: [a] -> [a] -> [a]
myPlusPlus (a:as) bs = a : myPlusPlus as bs
myPlusPlus [] bs = bs
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (a:as) = as `myPlusPlus` [a]
| null | https://raw.githubusercontent.com/NorfairKing/easyspec/b038b45a375cc0bed2b00c255b508bc06419c986/examples/runtime/Nine.hs | haskell | # ANN module "HLint: ignore Use foldr" # | # LANGUAGE NoImplicitPrelude #
module Nine where
import Prelude ((+), (-), concat, drop, map, take)
myId :: a -> a
myId a = a
myPlusPlus :: [a] -> [a] -> [a]
myPlusPlus (a:as) bs = a : myPlusPlus as bs
myPlusPlus [] bs = bs
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (a:as) = as `myPlusPlus` [a]
|
36579107871124b34e4d301c115f7ee7d3cf30fb7578a3f3a3b8abbec3845557 | fragnix/fragnix | Control.Concurrent.STM.TChan.hs | {-# LANGUAGE Haskell2010 #-}
# LINE 1 " Control / Concurrent / STM / TChan.hs " #
# OPTIONS_GHC -fno - warn - name - shadowing #
# LANGUAGE CPP , DeriveDataTypeable #
# LANGUAGE Trustworthy #
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.STM.TChan
Copyright : ( c ) The University of Glasgow 2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : experimental
Portability : non - portable ( requires STM )
--
TChan : Transactional channels
( GHC only )
--
-----------------------------------------------------------------------------
module Control.Concurrent.STM.TChan (
* TChans
TChan,
-- ** Construction
newTChan,
newTChanIO,
newBroadcastTChan,
newBroadcastTChanIO,
dupTChan,
cloneTChan,
-- ** Reading and writing
readTChan,
tryReadTChan,
peekTChan,
tryPeekTChan,
writeTChan,
unGetTChan,
isEmptyTChan
) where
import GHC.Conc
import Data.Typeable (Typeable)
| ' TChan ' is an abstract type representing an unbounded FIFO channel .
data TChan a = TChan {-# UNPACK #-} !(TVar (TVarList a))
{-# UNPACK #-} !(TVar (TVarList a))
deriving (Eq, Typeable)
type TVarList a = TVar (TList a)
data TList a = TNil | TCons a {-# UNPACK #-} !(TVarList a)
|Build and return a new instance of ' TChan '
newTChan :: STM (TChan a)
newTChan = do
hole <- newTVar TNil
read <- newTVar hole
write <- newTVar hole
return (TChan read write)
-- |@IO@ version of 'newTChan'. This is useful for creating top-level
' TChan 's using ' System . IO.Unsafe.unsafePerformIO ' , because using
-- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
-- possible.
newTChanIO :: IO (TChan a)
newTChanIO = do
hole <- newTVarIO TNil
read <- newTVarIO hole
write <- newTVarIO hole
return (TChan read write)
| Create a write - only ' TChan ' . More precisely , ' readTChan ' will ' retry '
-- even after items have been written to the channel. The only way to read
-- a broadcast channel is to duplicate it with 'dupTChan'.
--
-- Consider a server that broadcasts messages to clients:
--
> serve : : TChan Message - > Client - > IO loop
-- >serve broadcastChan client = do
-- > myChan <- dupTChan broadcastChan
-- > forever $ do
-- > message <- readTChan myChan
-- > send client message
--
-- The problem with using 'newTChan' to create the broadcast channel is that if
-- it is only written to and never read, items will pile up in memory. By
-- using 'newBroadcastTChan' to create the broadcast channel, items can be
-- garbage collected after clients have seen them.
--
@since 2.4
newBroadcastTChan :: STM (TChan a)
newBroadcastTChan = do
write_hole <- newTVar TNil
read <- newTVar (error "reading from a TChan created by newBroadcastTChan; use dupTChan first")
write <- newTVar write_hole
return (TChan read write)
| version of ' newBroadcastTChan ' .
--
@since 2.4
newBroadcastTChanIO :: IO (TChan a)
newBroadcastTChanIO = do
write_hole <- newTVarIO TNil
read <- newTVarIO (error "reading from a TChan created by newBroadcastTChanIO; use dupTChan first")
write <- newTVarIO write_hole
return (TChan read write)
|Write a value to a ' TChan ' .
writeTChan :: TChan a -> a -> STM ()
writeTChan (TChan _read write) a = do
listend = = TVar pointing to TNil
new_listend <- newTVar TNil
writeTVar listend (TCons a new_listend)
writeTVar write new_listend
|Read the next value from the ' TChan ' .
readTChan :: TChan a -> STM a
readTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> retry
TCons a tail -> do
writeTVar read tail
return a
-- | A version of 'readTChan' which does not retry. Instead it
-- returns @Nothing@ if no value is available.
tryReadTChan :: TChan a -> STM (Maybe a)
tryReadTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> return Nothing
TCons a tl -> do
writeTVar read tl
return (Just a)
-- | Get the next value from the @TChan@ without removing it,
-- retrying if the channel is empty.
peekTChan :: TChan a -> STM a
peekTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> retry
TCons a _ -> return a
-- | A version of 'peekTChan' which does not retry. Instead it
-- returns @Nothing@ if no value is available.
tryPeekTChan :: TChan a -> STM (Maybe a)
tryPeekTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> return Nothing
TCons a _ -> return (Just a)
|Duplicate a ' TChan ' : the duplicate channel begins empty , but data written to
-- either channel from then on will be available from both. Hence this creates
-- a kind of broadcast channel, where data written by anyone is seen by
-- everyone else.
dupTChan :: TChan a -> STM (TChan a)
dupTChan (TChan _read write) = do
hole <- readTVar write
new_read <- newTVar hole
return (TChan new_read write)
-- |Put a data item back onto a channel, where it will be the next item read.
unGetTChan :: TChan a -> a -> STM ()
unGetTChan (TChan read _write) a = do
listhead <- readTVar read
newhead <- newTVar (TCons a listhead)
writeTVar read newhead
|Returns ' True ' if the supplied ' TChan ' is empty .
isEmptyTChan :: TChan a -> STM Bool
isEmptyTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> return True
TCons _ _ -> return False
|Clone a ' TChan ' : similar to dupTChan , but the cloned channel starts with the
-- same content available as the original channel.
--
@since 2.4
cloneTChan :: TChan a -> STM (TChan a)
cloneTChan (TChan read write) = do
readpos <- readTVar read
new_read <- newTVar readpos
return (TChan new_read write)
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/scotty/Control.Concurrent.STM.TChan.hs | haskell | # LANGUAGE Haskell2010 #
---------------------------------------------------------------------------
|
Module : Control.Concurrent.STM.TChan
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : experimental
---------------------------------------------------------------------------
** Construction
** Reading and writing
# UNPACK #
# UNPACK #
# UNPACK #
|@IO@ version of 'newTChan'. This is useful for creating top-level
'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
possible.
even after items have been written to the channel. The only way to read
a broadcast channel is to duplicate it with 'dupTChan'.
Consider a server that broadcasts messages to clients:
>serve broadcastChan client = do
> myChan <- dupTChan broadcastChan
> forever $ do
> message <- readTChan myChan
> send client message
The problem with using 'newTChan' to create the broadcast channel is that if
it is only written to and never read, items will pile up in memory. By
using 'newBroadcastTChan' to create the broadcast channel, items can be
garbage collected after clients have seen them.
| A version of 'readTChan' which does not retry. Instead it
returns @Nothing@ if no value is available.
| Get the next value from the @TChan@ without removing it,
retrying if the channel is empty.
| A version of 'peekTChan' which does not retry. Instead it
returns @Nothing@ if no value is available.
either channel from then on will be available from both. Hence this creates
a kind of broadcast channel, where data written by anyone is seen by
everyone else.
|Put a data item back onto a channel, where it will be the next item read.
same content available as the original channel.
| # LINE 1 " Control / Concurrent / STM / TChan.hs " #
# OPTIONS_GHC -fno - warn - name - shadowing #
# LANGUAGE CPP , DeriveDataTypeable #
# LANGUAGE Trustworthy #
Copyright : ( c ) The University of Glasgow 2004
Portability : non - portable ( requires STM )
TChan : Transactional channels
( GHC only )
module Control.Concurrent.STM.TChan (
* TChans
TChan,
newTChan,
newTChanIO,
newBroadcastTChan,
newBroadcastTChanIO,
dupTChan,
cloneTChan,
readTChan,
tryReadTChan,
peekTChan,
tryPeekTChan,
writeTChan,
unGetTChan,
isEmptyTChan
) where
import GHC.Conc
import Data.Typeable (Typeable)
| ' TChan ' is an abstract type representing an unbounded FIFO channel .
deriving (Eq, Typeable)
type TVarList a = TVar (TList a)
|Build and return a new instance of ' TChan '
newTChan :: STM (TChan a)
newTChan = do
hole <- newTVar TNil
read <- newTVar hole
write <- newTVar hole
return (TChan read write)
' TChan 's using ' System . IO.Unsafe.unsafePerformIO ' , because using
newTChanIO :: IO (TChan a)
newTChanIO = do
hole <- newTVarIO TNil
read <- newTVarIO hole
write <- newTVarIO hole
return (TChan read write)
| Create a write - only ' TChan ' . More precisely , ' readTChan ' will ' retry '
> serve : : TChan Message - > Client - > IO loop
@since 2.4
newBroadcastTChan :: STM (TChan a)
newBroadcastTChan = do
write_hole <- newTVar TNil
read <- newTVar (error "reading from a TChan created by newBroadcastTChan; use dupTChan first")
write <- newTVar write_hole
return (TChan read write)
| version of ' newBroadcastTChan ' .
@since 2.4
newBroadcastTChanIO :: IO (TChan a)
newBroadcastTChanIO = do
write_hole <- newTVarIO TNil
read <- newTVarIO (error "reading from a TChan created by newBroadcastTChanIO; use dupTChan first")
write <- newTVarIO write_hole
return (TChan read write)
|Write a value to a ' TChan ' .
writeTChan :: TChan a -> a -> STM ()
writeTChan (TChan _read write) a = do
listend = = TVar pointing to TNil
new_listend <- newTVar TNil
writeTVar listend (TCons a new_listend)
writeTVar write new_listend
|Read the next value from the ' TChan ' .
readTChan :: TChan a -> STM a
readTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> retry
TCons a tail -> do
writeTVar read tail
return a
tryReadTChan :: TChan a -> STM (Maybe a)
tryReadTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> return Nothing
TCons a tl -> do
writeTVar read tl
return (Just a)
peekTChan :: TChan a -> STM a
peekTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> retry
TCons a _ -> return a
tryPeekTChan :: TChan a -> STM (Maybe a)
tryPeekTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> return Nothing
TCons a _ -> return (Just a)
|Duplicate a ' TChan ' : the duplicate channel begins empty , but data written to
dupTChan :: TChan a -> STM (TChan a)
dupTChan (TChan _read write) = do
hole <- readTVar write
new_read <- newTVar hole
return (TChan new_read write)
unGetTChan :: TChan a -> a -> STM ()
unGetTChan (TChan read _write) a = do
listhead <- readTVar read
newhead <- newTVar (TCons a listhead)
writeTVar read newhead
|Returns ' True ' if the supplied ' TChan ' is empty .
isEmptyTChan :: TChan a -> STM Bool
isEmptyTChan (TChan read _write) = do
listhead <- readTVar read
head <- readTVar listhead
case head of
TNil -> return True
TCons _ _ -> return False
|Clone a ' TChan ' : similar to dupTChan , but the cloned channel starts with the
@since 2.4
cloneTChan :: TChan a -> STM (TChan a)
cloneTChan (TChan read write) = do
readpos <- readTVar read
new_read <- newTVar readpos
return (TChan new_read write)
|
1b7bcf06aada85fc649931713fb0879a8b554740f46802672bdab240f9e3d382 | ejgallego/coq-serapi | ser_stm.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2016
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(************************************************************************)
(* Coq serialization API/Plugin *)
Copyright 2016 MINES ParisTech
(************************************************************************)
(* Status: Very Experimental *)
(************************************************************************)
open Sexplib
type interactive_top = Stm.interactive_top
*
* val sexp_of_interactive_top : Stm.interactive_top - > Sexp.t
* val interactive_top_of_sexp : Sexp.t - > Stm.interactive_top
*
* val sexp_of_interactive_top : Stm.interactive_top -> Sexp.t
* val interactive_top_of_sexp : Sexp.t -> Stm.interactive_top *)
type focus = Stm.focus
val sexp_of_focus : Stm.focus -> Sexp.t
val focus_of_sexp : Sexp.t -> Stm.focus
type add_focus = Stm.add_focus
val sexp_of_add_focus : Stm.add_focus -> Sexp.t
val add_focus_of_sexp : Sexp.t -> Stm.add_focus
| null | https://raw.githubusercontent.com/ejgallego/coq-serapi/61d2a5c092c1918312b8a92f43a374639d1786f9/serlib/ser_stm.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
**********************************************************************
Coq serialization API/Plugin
**********************************************************************
Status: Very Experimental
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2016
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Copyright 2016 MINES ParisTech
open Sexplib
type interactive_top = Stm.interactive_top
*
* val sexp_of_interactive_top : Stm.interactive_top - > Sexp.t
* val interactive_top_of_sexp : Sexp.t - > Stm.interactive_top
*
* val sexp_of_interactive_top : Stm.interactive_top -> Sexp.t
* val interactive_top_of_sexp : Sexp.t -> Stm.interactive_top *)
type focus = Stm.focus
val sexp_of_focus : Stm.focus -> Sexp.t
val focus_of_sexp : Sexp.t -> Stm.focus
type add_focus = Stm.add_focus
val sexp_of_add_focus : Stm.add_focus -> Sexp.t
val add_focus_of_sexp : Sexp.t -> Stm.add_focus
|
c2747d849a33c577ba2f104f68e845e35d324e11f8c9c3532d92d742038b13ee | penpot/penpot | libraries.cljs | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
;; Copyright (c) KALEIDOS INC
(ns app.main.data.workspace.libraries
(:require
[app.common.data :as d]
[app.common.files.features :as ffeat]
[app.common.geom.point :as gpt]
[app.common.logging :as log]
[app.common.pages :as cp]
[app.common.pages.changes :as ch]
[app.common.pages.changes-builder :as pcb]
[app.common.pages.changes-spec :as pcs]
[app.common.pages.helpers :as cph]
[app.common.spec :as us]
[app.common.types.color :as ctc]
[app.common.types.components-list :as ctkl]
[app.common.types.container :as ctn]
[app.common.types.file :as ctf]
[app.common.types.file.media-object :as ctfm]
[app.common.types.pages-list :as ctpl]
[app.common.types.typography :as ctt]
[app.common.uuid :as uuid]
[app.main.data.dashboard :as dd]
[app.main.data.events :as ev]
[app.main.data.messages :as dm]
[app.main.data.workspace.changes :as dch]
[app.main.data.workspace.groups :as dwg]
[app.main.data.workspace.libraries-helpers :as dwlh]
[app.main.data.workspace.selection :as dws]
[app.main.data.workspace.shapes :as dwsh]
[app.main.data.workspace.state-helpers :as wsh]
[app.main.data.workspace.undo :as dwu]
[app.main.features :as features]
[app.main.refs :as refs]
[app.main.repo :as rp]
[app.main.store :as st]
[app.util.i18n :refer [tr]]
[app.util.router :as rt]
[app.util.time :as dt]
[beicon.core :as rx]
[cljs.spec.alpha :as s]
[potok.core :as ptk]))
;; Change this to :info :debug or :trace to debug this module, or :warn to reset to default
(log/set-level! :warn)
(s/def ::file ::dd/file)
(defn- log-changes
[changes file]
(let [extract-change
(fn [change]
(let [shape (when (:id change)
(cond
(:page-id change)
(get-in file [:pages-index
(:page-id change)
:objects
(:id change)])
(:component-id change)
(get-in file [:components
(:component-id change)
:objects
(:id change)])
:else nil))
prefix (if (:component-id change) "[C] " "[P] ")
extract (cond-> {:type (:type change)
:raw-change change}
shape
(assoc :shape (str prefix (:name shape)))
(:operations change)
(assoc :operations (:operations change)))]
extract))]
(map extract-change changes)))
(declare sync-file)
(defn set-assets-box-open
[file-id box open?]
(ptk/reify ::set-assets-box-open
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-global :assets-files-open file-id box] open?))))
(defn set-assets-group-open
[file-id box path open?]
(ptk/reify ::set-assets-group-open
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-global :assets-files-open file-id :groups box path] open?))))
(defn extract-path-if-missing
[item]
(let [[path name] (cph/parse-path-name (:name item))]
(if (and
(= (:name item) name)
(contains? item :path))
item
(assoc item :path path :name name))))
(defn default-color-name [color]
(or (:color color)
(case (get-in color [:gradient :type])
:linear (tr "workspace.gradients.linear")
:radial (tr "workspace.gradients.radial"))))
(defn add-color
[color]
(let [id (uuid/next)
color (-> color
(assoc :id id)
(assoc :name (default-color-name color)))]
(us/assert ::ctc/color color)
(ptk/reify ::add-color
IDeref
(-deref [_] color)
ptk/WatchEvent
(watch [it _ _]
(let [changes (-> (pcb/empty-changes it)
(pcb/add-color color))]
(rx/of #(assoc-in % [:workspace-local :color-for-rename] id)
(dch/commit-changes changes)))))))
(defn add-recent-color
[color]
(us/assert! ::ctc/recent-color color)
(ptk/reify ::add-recent-color
ptk/WatchEvent
(watch [it _ _]
(let [changes (-> (pcb/empty-changes it)
(pcb/add-recent-color color))]
(rx/of (dch/commit-changes changes))))))
(def clear-color-for-rename
(ptk/reify ::clear-color-for-rename
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-local :color-for-rename] nil))))
(defn- do-update-color
[it state color file-id]
(let [data (get state :workspace-data)
[path name] (cph/parse-path-name (:name color))
color (assoc color :path path :name name)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/update-color color))
undo-id (js/Symbol)]
(rx/of (dwu/start-undo-transaction undo-id)
(dch/commit-changes changes)
(sync-file (:current-file-id state) file-id :colors (:id color))
(dwu/commit-undo-transaction undo-id))))
(defn update-color
[color file-id]
(us/assert ::ctc/color color)
(us/assert ::us/uuid file-id)
(ptk/reify ::update-color
ptk/WatchEvent
(watch [it state _]
(do-update-color it state color file-id))))
(defn rename-color
[file-id id new-name]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid id)
(us/assert ::us/string new-name)
(ptk/reify ::rename-color
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
object (get-in data [:colors id])
new-object (assoc object :name new-name)]
(do-update-color it state new-object file-id)))))
(defn delete-color
[{:keys [id] :as params}]
(us/assert ::us/uuid id)
(ptk/reify ::delete-color
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/delete-color id))]
(rx/of (dch/commit-changes changes))))))
(defn add-media
[media]
(us/assert ::ctfm/media-object media)
(ptk/reify ::add-media
ptk/WatchEvent
(watch [it _ _]
(let [obj (select-keys media [:id :name :width :height :mtype])
changes (-> (pcb/empty-changes it)
(pcb/add-media obj))]
(rx/of (dch/commit-changes changes))))))
(defn rename-media
[id new-name]
(us/assert ::us/uuid id)
(us/assert ::us/string new-name)
(ptk/reify ::rename-media
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
[path name] (cph/parse-path-name new-name)
object (get-in data [:media id])
new-object (assoc object :path path :name name)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/update-media new-object))]
(rx/of (dch/commit-changes changes))))))
(defn delete-media
[{:keys [id] :as params}]
(us/assert ::us/uuid id)
(ptk/reify ::delete-media
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/delete-media id))]
(rx/of (dch/commit-changes changes))))))
(defn add-typography
([typography] (add-typography typography true))
([typography edit?]
(let [typography (update typography :id #(or % (uuid/next)))]
(us/assert ::ctt/typography typography)
(ptk/reify ::add-typography
IDeref
(-deref [_] typography)
ptk/WatchEvent
(watch [it _ _]
(let [changes (-> (pcb/empty-changes it)
(pcb/add-typography typography))]
(rx/of (dch/commit-changes changes)
#(cond-> %
edit?
(assoc-in [:workspace-global :rename-typography] (:id typography))))))))))
(defn- do-update-tipography
[it state typography file-id]
(let [data (get state :workspace-data)
typography (extract-path-if-missing typography)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/update-typography typography))
undo-id (js/Symbol)]
(rx/of (dwu/start-undo-transaction undo-id)
(dch/commit-changes changes)
(sync-file (:current-file-id state) file-id :typographies (:id typography))
(dwu/commit-undo-transaction undo-id))))
(defn update-typography
[typography file-id]
(us/assert ::ctt/typography typography)
(us/assert ::us/uuid file-id)
(ptk/reify ::update-typography
ptk/WatchEvent
(watch [it state _]
(do-update-tipography it state typography file-id))))
(defn rename-typography
[file-id id new-name]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid id)
(us/assert ::us/string new-name)
(ptk/reify ::rename-typography
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
[path name] (cph/parse-path-name new-name)
object (get-in data [:typographies id])
new-object (assoc object :path path :name name)]
(do-update-tipography it state new-object file-id)))))
(defn delete-typography
[id]
(us/assert ::us/uuid id)
(ptk/reify ::delete-typography
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/delete-typography id))]
(rx/of (dch/commit-changes changes))))))
(defn- add-component2
"This is the second step of the component creation."
[selected components-v2]
(ptk/reify ::add-component2
IDeref
(-deref [_] {:num-shapes (count selected)})
ptk/WatchEvent
(watch [it state _]
(let [file-id (:current-file-id state)
page-id (:current-page-id state)
objects (wsh/lookup-page-objects state page-id)
shapes (dwg/shapes-for-grouping objects selected)]
(when-not (empty? shapes)
(let [[group _ changes]
(dwlh/generate-add-component it shapes objects page-id file-id components-v2)]
(when-not (empty? (:redo-changes changes))
(rx/of (dch/commit-changes changes)
(dws/select-shapes (d/ordered-set (:id group)))))))))))
(defn add-component
"Add a new component to current file library, from the currently selected shapes.
This operation is made in two steps, first one for calculate the
shapes that will be part of the component and the second one with
the component creation."
[]
(ptk/reify ::add-component
ptk/WatchEvent
(watch [_ state _]
(let [objects (wsh/lookup-page-objects state)
selected (->> (wsh/lookup-selected state)
(cph/clean-loops objects))
components-v2 (features/active-feature? state :components-v2)]
(rx/of (add-component2 selected components-v2))))))
(defn rename-component
"Rename the component with the given id, in the current file library."
[id new-name]
(us/assert ::us/uuid id)
(us/assert ::us/string new-name)
(ptk/reify ::rename-component
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
[path name] (cph/parse-path-name new-name)
update-fn
(fn [component]
;; NOTE: we need to ensure the component exists,
;; because there are small possibilities of race
;; conditions with component deletion.
(when component
(-> component
(assoc :path path)
(assoc :name name)
(update :objects
;; Give the same name to the root shape
#(assoc-in % [id :name] name)))))
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/update-component id update-fn))]
(rx/of (dch/commit-changes changes))))))
(defn duplicate-component
"Create a new component copied from the one with the given id."
[{:keys [id] :as params}]
(ptk/reify ::duplicate-component
ptk/WatchEvent
(watch [it state _]
(let [libraries (wsh/get-libraries state)
component (cph/get-component libraries id)
new-name (:name component)
components-v2 (features/active-feature? state :components-v2)
main-instance-page (when components-v2
(wsh/lookup-page state (:main-instance-page component)))
main-instance-shape (when components-v2
(ctn/get-shape main-instance-page (:main-instance-id component)))
[new-component-shape new-component-shapes
new-main-instance-shape new-main-instance-shapes]
(dwlh/duplicate-component component main-instance-page main-instance-shape)
changes (-> (pcb/empty-changes it nil)
(pcb/with-page main-instance-page)
(pcb/with-objects (:objects main-instance-page))
(pcb/add-objects new-main-instance-shapes {:ignore-touched true})
(pcb/add-component (:id new-component-shape)
(:path component)
new-name
new-component-shapes
[]
(:id new-main-instance-shape)
(:id main-instance-page)))]
(rx/of (dch/commit-changes changes))))))
(defn delete-component
"Delete the component with the given id, from the current file library."
[{:keys [id] :as params}]
(us/assert ::us/uuid id)
(ptk/reify ::delete-component
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)]
(if (features/active-feature? state :components-v2)
(let [component (ctkl/get-component data id)
page (ctpl/get-page data (:main-instance-page component))
shape (ctn/get-shape page (:main-instance-id component))]
(rx/of (dwsh/delete-shapes (:id page) #{(:id shape)})))
(let [changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/delete-component id false))]
(rx/of (dch/commit-changes changes))))))))
(defn restore-component
"Restore a deleted component, with the given id, in the given file library."
[library-id component-id]
(us/assert ::us/uuid library-id)
(us/assert ::us/uuid component-id)
(ptk/reify ::restore-component
ptk/WatchEvent
(watch [it state _]
(let [file-data (wsh/get-file state library-id)
component (ctf/get-deleted-component file-data component-id)
page (ctpl/get-page file-data (:main-instance-page component))
; Make a new main instance, with the same id of the original
[_main-instance shapes]
(ctn/make-component-instance page
component
(:id file-data)
(gpt/point (:main-instance-x component)
(:main-instance-y component))
{:main-instance? true
:force-id (:main-instance-id component)})
changes (-> (pcb/empty-changes it)
(pcb/with-library-data file-data)
(pcb/with-page page))
changes (reduce #(pcb/add-object %1 %2 {:ignore-touched true})
changes
shapes)
; restore-component change needs to be done after add main instance
; because when undo changes, the orden is inverse
changes (pcb/restore-component changes component-id)]
(rx/of (dch/commit-changes (assoc changes :file-id library-id)))))))
(defn instantiate-component
"Create a new shape in the current page, from the component with the given id
in the given file library. Then selects the newly created instance."
[file-id component-id position]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid component-id)
(us/assert ::gpt/point position)
(ptk/reify ::instantiate-component
ptk/WatchEvent
(watch [it state _]
(let [page (wsh/lookup-page state)
libraries (wsh/get-libraries state)
[new-shape changes]
(dwlh/generate-instantiate-component it
file-id
component-id
position
page
libraries)
undo-id (js/Symbol)]
(rx/of (dwu/start-undo-transaction undo-id)
(dch/commit-changes changes)
(ptk/data-event :layout/update [(:id new-shape)])
(dws/select-shapes (d/ordered-set (:id new-shape)))
(dwu/commit-undo-transaction undo-id))))))
(defn detach-component
"Remove all references to components in the shape with the given id,
and all its children, at the current page."
[id]
(us/assert ::us/uuid id)
(ptk/reify ::detach-component
ptk/WatchEvent
(watch [it state _]
(let [file (wsh/get-local-file state)
page-id (get state :current-page-id)
container (cph/get-container file :page page-id)
changes (-> (pcb/empty-changes it)
(pcb/with-container container)
(pcb/with-objects (:objects container))
(dwlh/generate-detach-instance container id))]
(rx/of (dch/commit-changes changes))))))
(def detach-selected-components
(ptk/reify ::detach-selected-components
ptk/WatchEvent
(watch [it state _]
(let [page-id (:current-page-id state)
objects (wsh/lookup-page-objects state page-id)
file (wsh/get-local-file state)
container (cph/get-container file :page page-id)
selected (->> state
(wsh/lookup-selected)
(cph/clean-loops objects))
changes (reduce
(fn [changes id]
(dwlh/generate-detach-instance changes container id))
(-> (pcb/empty-changes it)
(pcb/with-container container)
(pcb/with-objects objects))
selected)]
(rx/of (dch/commit-changes changes))))))
(defn nav-to-component-file
[file-id]
(us/assert ::us/uuid file-id)
(ptk/reify ::nav-to-component-file
ptk/WatchEvent
(watch [_ state _]
(let [file (get-in state [:workspace-libraries file-id])
path-params {:project-id (:project-id file)
:file-id (:id file)}
query-params {:page-id (first (get-in file [:data :pages]))
:layout :assets}]
(rx/of (rt/nav-new-window* {:rname :workspace
:path-params path-params
:query-params query-params}))))))
(defn ext-library-changed
[file-id modified-at revn changes]
(us/assert ::us/uuid file-id)
(us/assert ::pcs/changes changes)
(ptk/reify ::ext-library-changed
ptk/UpdateEvent
(update [_ state]
(-> state
(update-in [:workspace-libraries file-id]
assoc :modified-at modified-at :revn revn)
(d/update-in-when [:workspace-libraries file-id :data]
cp/process-changes changes)))))
(defn reset-component
"Cancels all modifications in the shape with the given id, and all its children, in
the current page. Set all attributes equal to the ones in the linked component,
and untouched."
[id]
(us/assert ::us/uuid id)
(ptk/reify ::reset-component
ptk/WatchEvent
(watch [it state _]
(log/info :msg "RESET-COMPONENT of shape" :id (str id))
(let [file (wsh/get-local-file state)
libraries (wsh/get-libraries state)
page-id (:current-page-id state)
container (cph/get-container file :page page-id)
components-v2
(features/active-feature? state :components-v2)
changes
(-> (pcb/empty-changes it)
(pcb/with-container container)
(pcb/with-objects (:objects container))
(dwlh/generate-sync-shape-direct libraries container id true components-v2))]
(log/debug :msg "RESET-COMPONENT finished" :js/rchanges (log-changes
(:redo-changes changes)
file))
(rx/of (dch/commit-changes changes))))))
(defn update-component
"Modify the component linked to the shape with the given id, in the
current page, so that all attributes of its shapes are equal to the
shape and its children. Also set all attributes of the shape
untouched.
NOTE: It's possible that the component to update is defined in an
external library file, so this function may cause to modify a file
different of that the one we are currently editing."
[id]
(us/assert ::us/uuid id)
(ptk/reify ::update-component
ptk/WatchEvent
(watch [it state _]
(log/info :msg "UPDATE-COMPONENT of shape" :id (str id))
(let [page-id (get state :current-page-id)
local-file (wsh/get-local-file state)
libraries (wsh/get-libraries state)
container (cph/get-container local-file :page page-id)
shape (ctn/get-shape container id)
changes
(-> (pcb/empty-changes it)
(pcb/with-container container)
(dwlh/generate-sync-shape-inverse libraries container id))
file-id (:component-file shape)
file (wsh/get-file state file-id)
xf-filter (comp
(filter :local-change?)
(map #(dissoc % :local-change?)))
local-changes (-> changes
(update :redo-changes #(into [] xf-filter %))
(update :undo-changes #(into [] xf-filter %)))
xf-remove (comp
(remove :local-change?)
(map #(dissoc % :local-change?)))
nonlocal-changes (-> changes
(update :redo-changes #(into [] xf-remove %))
(update :undo-changes #(into [] xf-remove %)))]
(log/debug :msg "UPDATE-COMPONENT finished"
:js/local-changes (log-changes
(:redo-changes local-changes)
file)
:js/nonlocal-changes (log-changes
(:redo-changes nonlocal-changes)
file))
(rx/of
(when (seq (:redo-changes local-changes))
(dch/commit-changes (assoc local-changes
:file-id (:id local-file))))
(when (seq (:redo-changes nonlocal-changes))
(dch/commit-changes (assoc nonlocal-changes
:file-id file-id))))))))
(defn update-component-sync
[shape-id file-id]
(ptk/reify ::update-component-sync
ptk/WatchEvent
(watch [_ state _]
(let [current-file-id (:current-file-id state)
page (wsh/lookup-page state)
shape (ctn/get-shape page shape-id)
undo-id (js/Symbol)]
(rx/of
(dwu/start-undo-transaction undo-id)
(update-component shape-id)
(sync-file current-file-id file-id :components (:component-id shape))
(when (not= current-file-id file-id)
(sync-file file-id file-id :components (:component-id shape)))
(dwu/commit-undo-transaction undo-id))))))
(defn update-component-in-bulk
[shapes file-id]
(ptk/reify ::update-component-in-bulk
ptk/WatchEvent
(watch [_ _ _]
(let [undo-id (js/Symbol)]
(rx/concat
(rx/of (dwu/start-undo-transaction undo-id))
(rx/map #(update-component-sync (:id %) file-id) (rx/from shapes))
(rx/of (dwu/commit-undo-transaction undo-id)))))))
(declare sync-file-2nd-stage)
(defn sync-file
"Synchronize the given file from the given library. Walk through all
shapes in all pages in the file that use some color, typography or
component of the library, and copy the new values to the shapes. Do
it also for shapes inside components of the local file library.
If it's known that only one asset has changed, you can give its
type and id, and only shapes that use it will be synced, thus avoiding
a lot of unneeded checks."
([file-id library-id]
(sync-file file-id library-id nil nil))
([file-id library-id asset-type asset-id]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid library-id)
(us/assert (s/nilable #{:colors :components :typographies}) asset-type)
(us/assert (s/nilable ::us/uuid) asset-id)
(ptk/reify ::sync-file
ptk/UpdateEvent
(update [_ state]
(if (and (not= library-id (:current-file-id state))
(nil? asset-id))
(d/assoc-in-when state [:workspace-libraries library-id :synced-at] (dt/now))
state))
ptk/WatchEvent
(watch [it state _]
(when (and (some? file-id) (some? library-id)) ; Prevent race conditions while navigating out of the file
(log/info :msg "SYNC-FILE"
:file (dwlh/pretty-file file-id state)
:library (dwlh/pretty-file library-id state)
:asset-type asset-type
:asset-id asset-id)
(let [file (wsh/get-file state file-id)
sync-components? (or (nil? asset-type) (= asset-type :components))
sync-colors? (or (nil? asset-type) (= asset-type :colors))
sync-typographies? (or (nil? asset-type) (= asset-type :typographies))
library-changes (reduce
pcb/concat-changes
(pcb/empty-changes it)
[(when sync-components?
(dwlh/generate-sync-library it file-id :components asset-id library-id state))
(when sync-colors?
(dwlh/generate-sync-library it file-id :colors asset-id library-id state))
(when sync-typographies?
(dwlh/generate-sync-library it file-id :typographies asset-id library-id state))])
file-changes (reduce
pcb/concat-changes
(pcb/empty-changes it)
[(when sync-components?
(dwlh/generate-sync-file it file-id :components asset-id library-id state))
(when sync-colors?
(dwlh/generate-sync-file it file-id :colors asset-id library-id state))
(when sync-typographies?
(dwlh/generate-sync-file it file-id :typographies asset-id library-id state))])
changes (pcb/concat-changes library-changes file-changes)]
(log/debug :msg "SYNC-FILE finished" :js/rchanges (log-changes
(:redo-changes changes)
file))
(rx/concat
(rx/of (dm/hide-tag :sync-dialog))
(when (seq (:redo-changes changes))
TODO a ver qué pasa con esto
:file-id file-id))))
(when (not= file-id library-id)
;; When we have just updated the library file, give some time for the
;; update to finish, before marking this file as synced.
;; TODO: look for a more precise way of syncing this.
Maybe by using the stream ( second argument passed to watch )
;; to wait for the corresponding changes-committed and then proceed
;; with the :update-file-library-sync-status mutation.
(rx/concat (rx/timer 3000)
(rp/cmd! :update-file-library-sync-status
{:file-id file-id
:library-id library-id})))
(when (and (seq (:redo-changes library-changes))
sync-components?)
(rx/of (sync-file-2nd-stage file-id library-id asset-id))))))))))
(defn- sync-file-2nd-stage
"If some components have been modified, we need to launch another synchronization
to update the instances of the changed components."
;; TODO: this does not work if there are multiple nested components. Only the
first level will be updated .
;; To solve this properly, it would be better to launch another sync-file
;; recursively. But for this not to cause an infinite loop, we need to
;; implement updated-at at component level, to detect what components have
;; not changed, and then not to apply sync and terminate the loop.
[file-id library-id asset-id]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid library-id)
(us/assert (s/nilable ::us/uuid) asset-id)
(ptk/reify ::sync-file-2nd-stage
ptk/WatchEvent
(watch [it state _]
(log/info :msg "SYNC-FILE (2nd stage)"
:file (dwlh/pretty-file file-id state)
:library (dwlh/pretty-file library-id state))
(let [file (wsh/get-file state file-id)
changes (reduce
pcb/concat-changes
(pcb/empty-changes it)
[(dwlh/generate-sync-file it file-id :components asset-id library-id state)
(dwlh/generate-sync-library it file-id :components asset-id library-id state)])]
(log/debug :msg "SYNC-FILE (2nd stage) finished" :js/rchanges (log-changes
(:redo-changes changes)
file))
(when (seq (:redo-changes changes))
(rx/of (dch/commit-changes (assoc changes :file-id file-id))))))))
(def ignore-sync
(ptk/reify ::ignore-sync
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-file :ignore-sync-until] (dt/now)))
ptk/WatchEvent
(watch [_ state _]
(rp/cmd! :ignore-file-library-sync-status
{:file-id (get-in state [:workspace-file :id])
:date (dt/now)}))))
(defn notify-sync-file
[file-id]
(us/assert ::us/uuid file-id)
(ptk/reify ::notify-sync-file
ptk/WatchEvent
(watch [_ state _]
(let [libraries-need-sync (filter #(> (:modified-at %) (:synced-at %))
(vals (get state :workspace-libraries)))
do-update #(do (apply st/emit! (map (fn [library]
(sync-file (:current-file-id state)
(:id library)))
libraries-need-sync))
(st/emit! dm/hide))
do-dismiss #(do (st/emit! ignore-sync)
(st/emit! dm/hide))]
(rx/of (dm/info-dialog
(tr "workspace.updates.there-are-updates")
:inline-actions
[{:label (tr "workspace.updates.update")
:callback do-update}
{:label (tr "workspace.updates.dismiss")
:callback do-dismiss}]
:sync-dialog))))))
(defn watch-component-changes
"Watch the state for changes that affect to any main instance. If a change is detected will throw
an update-component-sync, so changes are immediately propagated to the component and copies."
[]
(ptk/reify ::watch-component-changes
ptk/WatchEvent
(watch [_ state stream]
(let [components-v2 (features/active-feature? state :components-v2)
stopper
(->> stream
(rx/filter #(or (= :app.main.data.workspace/finalize-page (ptk/type %))
(= ::watch-component-changes (ptk/type %)))))
workspace-data-s
(->> (rx/concat
(rx/of nil)
(rx/from-atom refs/workspace-data {:emit-current-value? true})))
change-s
(->> stream
(rx/filter #(or (dch/commit-changes? %)
(= (ptk/type %) :app.main.data.workspace.notifications/handle-file-change)))
(rx/observe-on :async))
check-changes
(fn [[event data]]
(let [{:keys [changes save-undo?]} (deref event)
components-changed (reduce #(into %1 (ch/components-changed data %2))
#{}
changes)]
(when (and (d/not-empty? components-changed) save-undo?)
(log/info :msg "DETECTED COMPONENTS CHANGED"
:ids (map str components-changed))
(run! st/emit!
(map #(update-component-sync % (:id data))
components-changed)))))]
(when components-v2
(->> change-s
(rx/with-latest-from workspace-data-s)
(rx/map check-changes)
(rx/take-until stopper)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Backend interactions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-file-shared
[id is-shared]
{:pre [(uuid? id) (boolean? is-shared)]}
(ptk/reify ::set-file-shared
IDeref
(-deref [_]
{::ev/origin "workspace" :id id :shared is-shared})
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-file :is-shared] is-shared))
ptk/WatchEvent
(watch [_ _ _]
(let [params {:id id :is-shared is-shared}]
(->> (rp/cmd! :set-file-shared params)
(rx/ignore))))))
(defn- shared-files-fetched
[files]
(us/verify (s/every ::file) files)
(ptk/reify ::shared-files-fetched
ptk/UpdateEvent
(update [_ state]
(let [state (dissoc state :files)]
(assoc state :workspace-shared-files files)))))
(defn fetch-shared-files
[{:keys [team-id] :as params}]
(us/assert ::us/uuid team-id)
(ptk/reify ::fetch-shared-files
ptk/WatchEvent
(watch [_ _ _]
(->> (rp/cmd! :get-team-shared-files {:team-id team-id})
(rx/map shared-files-fetched)))))
;; --- Link and unlink Files
(defn link-file-to-library
[file-id library-id]
(ptk/reify ::attach-library
ptk/WatchEvent
(watch [_ state _]
(let [features (cond-> ffeat/enabled
(features/active-feature? state :components-v2)
(conj "components/v2"))]
(rx/concat
(->> (rp/cmd! :link-file-to-library {:file-id file-id :library-id library-id})
(rx/ignore))
(->> (rp/cmd! :get-file {:id library-id :features features})
(rx/map (fn [file]
(fn [state]
(assoc-in state [:workspace-libraries library-id] file))))))))))
(defn unlink-file-from-library
[file-id library-id]
(ptk/reify ::detach-library
ptk/UpdateEvent
(update [_ state]
(d/dissoc-in state [:workspace-libraries library-id]))
ptk/WatchEvent
(watch [_ _ _]
(let [params {:file-id file-id
:library-id library-id}]
(->> (rp/cmd! :unlink-file-from-library params)
(rx/ignore))))))
| null | https://raw.githubusercontent.com/penpot/penpot/62aa6569f258829d36bbdf7d43819fe876f6b8b2/frontend/src/app/main/data/workspace/libraries.cljs | clojure |
Copyright (c) KALEIDOS INC
Change this to :info :debug or :trace to debug this module, or :warn to reset to default
NOTE: we need to ensure the component exists,
because there are small possibilities of race
conditions with component deletion.
Give the same name to the root shape
Make a new main instance, with the same id of the original
restore-component change needs to be done after add main instance
because when undo changes, the orden is inverse
Prevent race conditions while navigating out of the file
When we have just updated the library file, give some time for the
update to finish, before marking this file as synced.
TODO: look for a more precise way of syncing this.
to wait for the corresponding changes-committed and then proceed
with the :update-file-library-sync-status mutation.
TODO: this does not work if there are multiple nested components. Only the
To solve this properly, it would be better to launch another sync-file
recursively. But for this not to cause an infinite loop, we need to
implement updated-at at component level, to detect what components have
not changed, and then not to apply sync and terminate the loop.
Backend interactions
--- Link and unlink Files | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns app.main.data.workspace.libraries
(:require
[app.common.data :as d]
[app.common.files.features :as ffeat]
[app.common.geom.point :as gpt]
[app.common.logging :as log]
[app.common.pages :as cp]
[app.common.pages.changes :as ch]
[app.common.pages.changes-builder :as pcb]
[app.common.pages.changes-spec :as pcs]
[app.common.pages.helpers :as cph]
[app.common.spec :as us]
[app.common.types.color :as ctc]
[app.common.types.components-list :as ctkl]
[app.common.types.container :as ctn]
[app.common.types.file :as ctf]
[app.common.types.file.media-object :as ctfm]
[app.common.types.pages-list :as ctpl]
[app.common.types.typography :as ctt]
[app.common.uuid :as uuid]
[app.main.data.dashboard :as dd]
[app.main.data.events :as ev]
[app.main.data.messages :as dm]
[app.main.data.workspace.changes :as dch]
[app.main.data.workspace.groups :as dwg]
[app.main.data.workspace.libraries-helpers :as dwlh]
[app.main.data.workspace.selection :as dws]
[app.main.data.workspace.shapes :as dwsh]
[app.main.data.workspace.state-helpers :as wsh]
[app.main.data.workspace.undo :as dwu]
[app.main.features :as features]
[app.main.refs :as refs]
[app.main.repo :as rp]
[app.main.store :as st]
[app.util.i18n :refer [tr]]
[app.util.router :as rt]
[app.util.time :as dt]
[beicon.core :as rx]
[cljs.spec.alpha :as s]
[potok.core :as ptk]))
(log/set-level! :warn)
(s/def ::file ::dd/file)
(defn- log-changes
[changes file]
(let [extract-change
(fn [change]
(let [shape (when (:id change)
(cond
(:page-id change)
(get-in file [:pages-index
(:page-id change)
:objects
(:id change)])
(:component-id change)
(get-in file [:components
(:component-id change)
:objects
(:id change)])
:else nil))
prefix (if (:component-id change) "[C] " "[P] ")
extract (cond-> {:type (:type change)
:raw-change change}
shape
(assoc :shape (str prefix (:name shape)))
(:operations change)
(assoc :operations (:operations change)))]
extract))]
(map extract-change changes)))
(declare sync-file)
(defn set-assets-box-open
[file-id box open?]
(ptk/reify ::set-assets-box-open
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-global :assets-files-open file-id box] open?))))
(defn set-assets-group-open
[file-id box path open?]
(ptk/reify ::set-assets-group-open
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-global :assets-files-open file-id :groups box path] open?))))
(defn extract-path-if-missing
[item]
(let [[path name] (cph/parse-path-name (:name item))]
(if (and
(= (:name item) name)
(contains? item :path))
item
(assoc item :path path :name name))))
(defn default-color-name [color]
(or (:color color)
(case (get-in color [:gradient :type])
:linear (tr "workspace.gradients.linear")
:radial (tr "workspace.gradients.radial"))))
(defn add-color
[color]
(let [id (uuid/next)
color (-> color
(assoc :id id)
(assoc :name (default-color-name color)))]
(us/assert ::ctc/color color)
(ptk/reify ::add-color
IDeref
(-deref [_] color)
ptk/WatchEvent
(watch [it _ _]
(let [changes (-> (pcb/empty-changes it)
(pcb/add-color color))]
(rx/of #(assoc-in % [:workspace-local :color-for-rename] id)
(dch/commit-changes changes)))))))
(defn add-recent-color
[color]
(us/assert! ::ctc/recent-color color)
(ptk/reify ::add-recent-color
ptk/WatchEvent
(watch [it _ _]
(let [changes (-> (pcb/empty-changes it)
(pcb/add-recent-color color))]
(rx/of (dch/commit-changes changes))))))
(def clear-color-for-rename
(ptk/reify ::clear-color-for-rename
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-local :color-for-rename] nil))))
(defn- do-update-color
[it state color file-id]
(let [data (get state :workspace-data)
[path name] (cph/parse-path-name (:name color))
color (assoc color :path path :name name)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/update-color color))
undo-id (js/Symbol)]
(rx/of (dwu/start-undo-transaction undo-id)
(dch/commit-changes changes)
(sync-file (:current-file-id state) file-id :colors (:id color))
(dwu/commit-undo-transaction undo-id))))
(defn update-color
[color file-id]
(us/assert ::ctc/color color)
(us/assert ::us/uuid file-id)
(ptk/reify ::update-color
ptk/WatchEvent
(watch [it state _]
(do-update-color it state color file-id))))
(defn rename-color
[file-id id new-name]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid id)
(us/assert ::us/string new-name)
(ptk/reify ::rename-color
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
object (get-in data [:colors id])
new-object (assoc object :name new-name)]
(do-update-color it state new-object file-id)))))
(defn delete-color
[{:keys [id] :as params}]
(us/assert ::us/uuid id)
(ptk/reify ::delete-color
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/delete-color id))]
(rx/of (dch/commit-changes changes))))))
(defn add-media
[media]
(us/assert ::ctfm/media-object media)
(ptk/reify ::add-media
ptk/WatchEvent
(watch [it _ _]
(let [obj (select-keys media [:id :name :width :height :mtype])
changes (-> (pcb/empty-changes it)
(pcb/add-media obj))]
(rx/of (dch/commit-changes changes))))))
(defn rename-media
[id new-name]
(us/assert ::us/uuid id)
(us/assert ::us/string new-name)
(ptk/reify ::rename-media
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
[path name] (cph/parse-path-name new-name)
object (get-in data [:media id])
new-object (assoc object :path path :name name)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/update-media new-object))]
(rx/of (dch/commit-changes changes))))))
(defn delete-media
[{:keys [id] :as params}]
(us/assert ::us/uuid id)
(ptk/reify ::delete-media
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/delete-media id))]
(rx/of (dch/commit-changes changes))))))
(defn add-typography
([typography] (add-typography typography true))
([typography edit?]
(let [typography (update typography :id #(or % (uuid/next)))]
(us/assert ::ctt/typography typography)
(ptk/reify ::add-typography
IDeref
(-deref [_] typography)
ptk/WatchEvent
(watch [it _ _]
(let [changes (-> (pcb/empty-changes it)
(pcb/add-typography typography))]
(rx/of (dch/commit-changes changes)
#(cond-> %
edit?
(assoc-in [:workspace-global :rename-typography] (:id typography))))))))))
(defn- do-update-tipography
[it state typography file-id]
(let [data (get state :workspace-data)
typography (extract-path-if-missing typography)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/update-typography typography))
undo-id (js/Symbol)]
(rx/of (dwu/start-undo-transaction undo-id)
(dch/commit-changes changes)
(sync-file (:current-file-id state) file-id :typographies (:id typography))
(dwu/commit-undo-transaction undo-id))))
(defn update-typography
[typography file-id]
(us/assert ::ctt/typography typography)
(us/assert ::us/uuid file-id)
(ptk/reify ::update-typography
ptk/WatchEvent
(watch [it state _]
(do-update-tipography it state typography file-id))))
(defn rename-typography
[file-id id new-name]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid id)
(us/assert ::us/string new-name)
(ptk/reify ::rename-typography
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
[path name] (cph/parse-path-name new-name)
object (get-in data [:typographies id])
new-object (assoc object :path path :name name)]
(do-update-tipography it state new-object file-id)))))
(defn delete-typography
[id]
(us/assert ::us/uuid id)
(ptk/reify ::delete-typography
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/delete-typography id))]
(rx/of (dch/commit-changes changes))))))
(defn- add-component2
"This is the second step of the component creation."
[selected components-v2]
(ptk/reify ::add-component2
IDeref
(-deref [_] {:num-shapes (count selected)})
ptk/WatchEvent
(watch [it state _]
(let [file-id (:current-file-id state)
page-id (:current-page-id state)
objects (wsh/lookup-page-objects state page-id)
shapes (dwg/shapes-for-grouping objects selected)]
(when-not (empty? shapes)
(let [[group _ changes]
(dwlh/generate-add-component it shapes objects page-id file-id components-v2)]
(when-not (empty? (:redo-changes changes))
(rx/of (dch/commit-changes changes)
(dws/select-shapes (d/ordered-set (:id group)))))))))))
(defn add-component
"Add a new component to current file library, from the currently selected shapes.
This operation is made in two steps, first one for calculate the
shapes that will be part of the component and the second one with
the component creation."
[]
(ptk/reify ::add-component
ptk/WatchEvent
(watch [_ state _]
(let [objects (wsh/lookup-page-objects state)
selected (->> (wsh/lookup-selected state)
(cph/clean-loops objects))
components-v2 (features/active-feature? state :components-v2)]
(rx/of (add-component2 selected components-v2))))))
(defn rename-component
"Rename the component with the given id, in the current file library."
[id new-name]
(us/assert ::us/uuid id)
(us/assert ::us/string new-name)
(ptk/reify ::rename-component
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)
[path name] (cph/parse-path-name new-name)
update-fn
(fn [component]
(when component
(-> component
(assoc :path path)
(assoc :name name)
(update :objects
#(assoc-in % [id :name] name)))))
changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/update-component id update-fn))]
(rx/of (dch/commit-changes changes))))))
(defn duplicate-component
"Create a new component copied from the one with the given id."
[{:keys [id] :as params}]
(ptk/reify ::duplicate-component
ptk/WatchEvent
(watch [it state _]
(let [libraries (wsh/get-libraries state)
component (cph/get-component libraries id)
new-name (:name component)
components-v2 (features/active-feature? state :components-v2)
main-instance-page (when components-v2
(wsh/lookup-page state (:main-instance-page component)))
main-instance-shape (when components-v2
(ctn/get-shape main-instance-page (:main-instance-id component)))
[new-component-shape new-component-shapes
new-main-instance-shape new-main-instance-shapes]
(dwlh/duplicate-component component main-instance-page main-instance-shape)
changes (-> (pcb/empty-changes it nil)
(pcb/with-page main-instance-page)
(pcb/with-objects (:objects main-instance-page))
(pcb/add-objects new-main-instance-shapes {:ignore-touched true})
(pcb/add-component (:id new-component-shape)
(:path component)
new-name
new-component-shapes
[]
(:id new-main-instance-shape)
(:id main-instance-page)))]
(rx/of (dch/commit-changes changes))))))
(defn delete-component
"Delete the component with the given id, from the current file library."
[{:keys [id] :as params}]
(us/assert ::us/uuid id)
(ptk/reify ::delete-component
ptk/WatchEvent
(watch [it state _]
(let [data (get state :workspace-data)]
(if (features/active-feature? state :components-v2)
(let [component (ctkl/get-component data id)
page (ctpl/get-page data (:main-instance-page component))
shape (ctn/get-shape page (:main-instance-id component))]
(rx/of (dwsh/delete-shapes (:id page) #{(:id shape)})))
(let [changes (-> (pcb/empty-changes it)
(pcb/with-library-data data)
(pcb/delete-component id false))]
(rx/of (dch/commit-changes changes))))))))
(defn restore-component
"Restore a deleted component, with the given id, in the given file library."
[library-id component-id]
(us/assert ::us/uuid library-id)
(us/assert ::us/uuid component-id)
(ptk/reify ::restore-component
ptk/WatchEvent
(watch [it state _]
(let [file-data (wsh/get-file state library-id)
component (ctf/get-deleted-component file-data component-id)
page (ctpl/get-page file-data (:main-instance-page component))
[_main-instance shapes]
(ctn/make-component-instance page
component
(:id file-data)
(gpt/point (:main-instance-x component)
(:main-instance-y component))
{:main-instance? true
:force-id (:main-instance-id component)})
changes (-> (pcb/empty-changes it)
(pcb/with-library-data file-data)
(pcb/with-page page))
changes (reduce #(pcb/add-object %1 %2 {:ignore-touched true})
changes
shapes)
changes (pcb/restore-component changes component-id)]
(rx/of (dch/commit-changes (assoc changes :file-id library-id)))))))
(defn instantiate-component
"Create a new shape in the current page, from the component with the given id
in the given file library. Then selects the newly created instance."
[file-id component-id position]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid component-id)
(us/assert ::gpt/point position)
(ptk/reify ::instantiate-component
ptk/WatchEvent
(watch [it state _]
(let [page (wsh/lookup-page state)
libraries (wsh/get-libraries state)
[new-shape changes]
(dwlh/generate-instantiate-component it
file-id
component-id
position
page
libraries)
undo-id (js/Symbol)]
(rx/of (dwu/start-undo-transaction undo-id)
(dch/commit-changes changes)
(ptk/data-event :layout/update [(:id new-shape)])
(dws/select-shapes (d/ordered-set (:id new-shape)))
(dwu/commit-undo-transaction undo-id))))))
(defn detach-component
"Remove all references to components in the shape with the given id,
and all its children, at the current page."
[id]
(us/assert ::us/uuid id)
(ptk/reify ::detach-component
ptk/WatchEvent
(watch [it state _]
(let [file (wsh/get-local-file state)
page-id (get state :current-page-id)
container (cph/get-container file :page page-id)
changes (-> (pcb/empty-changes it)
(pcb/with-container container)
(pcb/with-objects (:objects container))
(dwlh/generate-detach-instance container id))]
(rx/of (dch/commit-changes changes))))))
(def detach-selected-components
(ptk/reify ::detach-selected-components
ptk/WatchEvent
(watch [it state _]
(let [page-id (:current-page-id state)
objects (wsh/lookup-page-objects state page-id)
file (wsh/get-local-file state)
container (cph/get-container file :page page-id)
selected (->> state
(wsh/lookup-selected)
(cph/clean-loops objects))
changes (reduce
(fn [changes id]
(dwlh/generate-detach-instance changes container id))
(-> (pcb/empty-changes it)
(pcb/with-container container)
(pcb/with-objects objects))
selected)]
(rx/of (dch/commit-changes changes))))))
(defn nav-to-component-file
[file-id]
(us/assert ::us/uuid file-id)
(ptk/reify ::nav-to-component-file
ptk/WatchEvent
(watch [_ state _]
(let [file (get-in state [:workspace-libraries file-id])
path-params {:project-id (:project-id file)
:file-id (:id file)}
query-params {:page-id (first (get-in file [:data :pages]))
:layout :assets}]
(rx/of (rt/nav-new-window* {:rname :workspace
:path-params path-params
:query-params query-params}))))))
(defn ext-library-changed
[file-id modified-at revn changes]
(us/assert ::us/uuid file-id)
(us/assert ::pcs/changes changes)
(ptk/reify ::ext-library-changed
ptk/UpdateEvent
(update [_ state]
(-> state
(update-in [:workspace-libraries file-id]
assoc :modified-at modified-at :revn revn)
(d/update-in-when [:workspace-libraries file-id :data]
cp/process-changes changes)))))
(defn reset-component
"Cancels all modifications in the shape with the given id, and all its children, in
the current page. Set all attributes equal to the ones in the linked component,
and untouched."
[id]
(us/assert ::us/uuid id)
(ptk/reify ::reset-component
ptk/WatchEvent
(watch [it state _]
(log/info :msg "RESET-COMPONENT of shape" :id (str id))
(let [file (wsh/get-local-file state)
libraries (wsh/get-libraries state)
page-id (:current-page-id state)
container (cph/get-container file :page page-id)
components-v2
(features/active-feature? state :components-v2)
changes
(-> (pcb/empty-changes it)
(pcb/with-container container)
(pcb/with-objects (:objects container))
(dwlh/generate-sync-shape-direct libraries container id true components-v2))]
(log/debug :msg "RESET-COMPONENT finished" :js/rchanges (log-changes
(:redo-changes changes)
file))
(rx/of (dch/commit-changes changes))))))
(defn update-component
"Modify the component linked to the shape with the given id, in the
current page, so that all attributes of its shapes are equal to the
shape and its children. Also set all attributes of the shape
untouched.
NOTE: It's possible that the component to update is defined in an
external library file, so this function may cause to modify a file
different of that the one we are currently editing."
[id]
(us/assert ::us/uuid id)
(ptk/reify ::update-component
ptk/WatchEvent
(watch [it state _]
(log/info :msg "UPDATE-COMPONENT of shape" :id (str id))
(let [page-id (get state :current-page-id)
local-file (wsh/get-local-file state)
libraries (wsh/get-libraries state)
container (cph/get-container local-file :page page-id)
shape (ctn/get-shape container id)
changes
(-> (pcb/empty-changes it)
(pcb/with-container container)
(dwlh/generate-sync-shape-inverse libraries container id))
file-id (:component-file shape)
file (wsh/get-file state file-id)
xf-filter (comp
(filter :local-change?)
(map #(dissoc % :local-change?)))
local-changes (-> changes
(update :redo-changes #(into [] xf-filter %))
(update :undo-changes #(into [] xf-filter %)))
xf-remove (comp
(remove :local-change?)
(map #(dissoc % :local-change?)))
nonlocal-changes (-> changes
(update :redo-changes #(into [] xf-remove %))
(update :undo-changes #(into [] xf-remove %)))]
(log/debug :msg "UPDATE-COMPONENT finished"
:js/local-changes (log-changes
(:redo-changes local-changes)
file)
:js/nonlocal-changes (log-changes
(:redo-changes nonlocal-changes)
file))
(rx/of
(when (seq (:redo-changes local-changes))
(dch/commit-changes (assoc local-changes
:file-id (:id local-file))))
(when (seq (:redo-changes nonlocal-changes))
(dch/commit-changes (assoc nonlocal-changes
:file-id file-id))))))))
(defn update-component-sync
[shape-id file-id]
(ptk/reify ::update-component-sync
ptk/WatchEvent
(watch [_ state _]
(let [current-file-id (:current-file-id state)
page (wsh/lookup-page state)
shape (ctn/get-shape page shape-id)
undo-id (js/Symbol)]
(rx/of
(dwu/start-undo-transaction undo-id)
(update-component shape-id)
(sync-file current-file-id file-id :components (:component-id shape))
(when (not= current-file-id file-id)
(sync-file file-id file-id :components (:component-id shape)))
(dwu/commit-undo-transaction undo-id))))))
(defn update-component-in-bulk
[shapes file-id]
(ptk/reify ::update-component-in-bulk
ptk/WatchEvent
(watch [_ _ _]
(let [undo-id (js/Symbol)]
(rx/concat
(rx/of (dwu/start-undo-transaction undo-id))
(rx/map #(update-component-sync (:id %) file-id) (rx/from shapes))
(rx/of (dwu/commit-undo-transaction undo-id)))))))
(declare sync-file-2nd-stage)
(defn sync-file
"Synchronize the given file from the given library. Walk through all
shapes in all pages in the file that use some color, typography or
component of the library, and copy the new values to the shapes. Do
it also for shapes inside components of the local file library.
If it's known that only one asset has changed, you can give its
type and id, and only shapes that use it will be synced, thus avoiding
a lot of unneeded checks."
([file-id library-id]
(sync-file file-id library-id nil nil))
([file-id library-id asset-type asset-id]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid library-id)
(us/assert (s/nilable #{:colors :components :typographies}) asset-type)
(us/assert (s/nilable ::us/uuid) asset-id)
(ptk/reify ::sync-file
ptk/UpdateEvent
(update [_ state]
(if (and (not= library-id (:current-file-id state))
(nil? asset-id))
(d/assoc-in-when state [:workspace-libraries library-id :synced-at] (dt/now))
state))
ptk/WatchEvent
(watch [it state _]
(log/info :msg "SYNC-FILE"
:file (dwlh/pretty-file file-id state)
:library (dwlh/pretty-file library-id state)
:asset-type asset-type
:asset-id asset-id)
(let [file (wsh/get-file state file-id)
sync-components? (or (nil? asset-type) (= asset-type :components))
sync-colors? (or (nil? asset-type) (= asset-type :colors))
sync-typographies? (or (nil? asset-type) (= asset-type :typographies))
library-changes (reduce
pcb/concat-changes
(pcb/empty-changes it)
[(when sync-components?
(dwlh/generate-sync-library it file-id :components asset-id library-id state))
(when sync-colors?
(dwlh/generate-sync-library it file-id :colors asset-id library-id state))
(when sync-typographies?
(dwlh/generate-sync-library it file-id :typographies asset-id library-id state))])
file-changes (reduce
pcb/concat-changes
(pcb/empty-changes it)
[(when sync-components?
(dwlh/generate-sync-file it file-id :components asset-id library-id state))
(when sync-colors?
(dwlh/generate-sync-file it file-id :colors asset-id library-id state))
(when sync-typographies?
(dwlh/generate-sync-file it file-id :typographies asset-id library-id state))])
changes (pcb/concat-changes library-changes file-changes)]
(log/debug :msg "SYNC-FILE finished" :js/rchanges (log-changes
(:redo-changes changes)
file))
(rx/concat
(rx/of (dm/hide-tag :sync-dialog))
(when (seq (:redo-changes changes))
TODO a ver qué pasa con esto
:file-id file-id))))
(when (not= file-id library-id)
Maybe by using the stream ( second argument passed to watch )
(rx/concat (rx/timer 3000)
(rp/cmd! :update-file-library-sync-status
{:file-id file-id
:library-id library-id})))
(when (and (seq (:redo-changes library-changes))
sync-components?)
(rx/of (sync-file-2nd-stage file-id library-id asset-id))))))))))
(defn- sync-file-2nd-stage
"If some components have been modified, we need to launch another synchronization
to update the instances of the changed components."
first level will be updated .
[file-id library-id asset-id]
(us/assert ::us/uuid file-id)
(us/assert ::us/uuid library-id)
(us/assert (s/nilable ::us/uuid) asset-id)
(ptk/reify ::sync-file-2nd-stage
ptk/WatchEvent
(watch [it state _]
(log/info :msg "SYNC-FILE (2nd stage)"
:file (dwlh/pretty-file file-id state)
:library (dwlh/pretty-file library-id state))
(let [file (wsh/get-file state file-id)
changes (reduce
pcb/concat-changes
(pcb/empty-changes it)
[(dwlh/generate-sync-file it file-id :components asset-id library-id state)
(dwlh/generate-sync-library it file-id :components asset-id library-id state)])]
(log/debug :msg "SYNC-FILE (2nd stage) finished" :js/rchanges (log-changes
(:redo-changes changes)
file))
(when (seq (:redo-changes changes))
(rx/of (dch/commit-changes (assoc changes :file-id file-id))))))))
(def ignore-sync
(ptk/reify ::ignore-sync
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-file :ignore-sync-until] (dt/now)))
ptk/WatchEvent
(watch [_ state _]
(rp/cmd! :ignore-file-library-sync-status
{:file-id (get-in state [:workspace-file :id])
:date (dt/now)}))))
(defn notify-sync-file
[file-id]
(us/assert ::us/uuid file-id)
(ptk/reify ::notify-sync-file
ptk/WatchEvent
(watch [_ state _]
(let [libraries-need-sync (filter #(> (:modified-at %) (:synced-at %))
(vals (get state :workspace-libraries)))
do-update #(do (apply st/emit! (map (fn [library]
(sync-file (:current-file-id state)
(:id library)))
libraries-need-sync))
(st/emit! dm/hide))
do-dismiss #(do (st/emit! ignore-sync)
(st/emit! dm/hide))]
(rx/of (dm/info-dialog
(tr "workspace.updates.there-are-updates")
:inline-actions
[{:label (tr "workspace.updates.update")
:callback do-update}
{:label (tr "workspace.updates.dismiss")
:callback do-dismiss}]
:sync-dialog))))))
(defn watch-component-changes
"Watch the state for changes that affect to any main instance. If a change is detected will throw
an update-component-sync, so changes are immediately propagated to the component and copies."
[]
(ptk/reify ::watch-component-changes
ptk/WatchEvent
(watch [_ state stream]
(let [components-v2 (features/active-feature? state :components-v2)
stopper
(->> stream
(rx/filter #(or (= :app.main.data.workspace/finalize-page (ptk/type %))
(= ::watch-component-changes (ptk/type %)))))
workspace-data-s
(->> (rx/concat
(rx/of nil)
(rx/from-atom refs/workspace-data {:emit-current-value? true})))
change-s
(->> stream
(rx/filter #(or (dch/commit-changes? %)
(= (ptk/type %) :app.main.data.workspace.notifications/handle-file-change)))
(rx/observe-on :async))
check-changes
(fn [[event data]]
(let [{:keys [changes save-undo?]} (deref event)
components-changed (reduce #(into %1 (ch/components-changed data %2))
#{}
changes)]
(when (and (d/not-empty? components-changed) save-undo?)
(log/info :msg "DETECTED COMPONENTS CHANGED"
:ids (map str components-changed))
(run! st/emit!
(map #(update-component-sync % (:id data))
components-changed)))))]
(when components-v2
(->> change-s
(rx/with-latest-from workspace-data-s)
(rx/map check-changes)
(rx/take-until stopper)))))))
(defn set-file-shared
[id is-shared]
{:pre [(uuid? id) (boolean? is-shared)]}
(ptk/reify ::set-file-shared
IDeref
(-deref [_]
{::ev/origin "workspace" :id id :shared is-shared})
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-file :is-shared] is-shared))
ptk/WatchEvent
(watch [_ _ _]
(let [params {:id id :is-shared is-shared}]
(->> (rp/cmd! :set-file-shared params)
(rx/ignore))))))
(defn- shared-files-fetched
[files]
(us/verify (s/every ::file) files)
(ptk/reify ::shared-files-fetched
ptk/UpdateEvent
(update [_ state]
(let [state (dissoc state :files)]
(assoc state :workspace-shared-files files)))))
(defn fetch-shared-files
[{:keys [team-id] :as params}]
(us/assert ::us/uuid team-id)
(ptk/reify ::fetch-shared-files
ptk/WatchEvent
(watch [_ _ _]
(->> (rp/cmd! :get-team-shared-files {:team-id team-id})
(rx/map shared-files-fetched)))))
(defn link-file-to-library
[file-id library-id]
(ptk/reify ::attach-library
ptk/WatchEvent
(watch [_ state _]
(let [features (cond-> ffeat/enabled
(features/active-feature? state :components-v2)
(conj "components/v2"))]
(rx/concat
(->> (rp/cmd! :link-file-to-library {:file-id file-id :library-id library-id})
(rx/ignore))
(->> (rp/cmd! :get-file {:id library-id :features features})
(rx/map (fn [file]
(fn [state]
(assoc-in state [:workspace-libraries library-id] file))))))))))
(defn unlink-file-from-library
[file-id library-id]
(ptk/reify ::detach-library
ptk/UpdateEvent
(update [_ state]
(d/dissoc-in state [:workspace-libraries library-id]))
ptk/WatchEvent
(watch [_ _ _]
(let [params {:file-id file-id
:library-id library-id}]
(->> (rp/cmd! :unlink-file-from-library params)
(rx/ignore))))))
|
677edb06b2c2c8cae841b2b390f1d7b5143818327109de43396474ea31f8bbee | ml4tp/tcoq | kindops.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Decl_kinds
(** Operations about types defined in [Decl_kinds] *)
val logical_kind_of_goal_kind : goal_object_kind -> logical_kind
val string_of_theorem_kind : theorem_kind -> string
val string_of_definition_kind : definition_kind -> string
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/library/kindops.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* Operations about types defined in [Decl_kinds] | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Decl_kinds
val logical_kind_of_goal_kind : goal_object_kind -> logical_kind
val string_of_theorem_kind : theorem_kind -> string
val string_of_definition_kind : definition_kind -> string
|
63dcc56ca9de8d7212d7b51eb37ef48bac48fe16f22c08d086f9b1b0270e6ba3 | WormBase/wormbase_rest | expression.clj | (ns rest-api.classes.pseudogene.widgets.expression
(:require
[rest-api.classes.generic-fields :as generic]
[rest-api.formatters.object :as obj :refer [pack-obj]]))
(defn microarray-results [p]
{:data (some->> (:microarray-results.pseudogene/_pseudogene p)
(map :microarray-results/_pseudogene)
(map pack-obj)
(sort-by :label))
:description "Microarray results"})
(def widget
{:name generic/name-field
:microarray_results microarray-results})
| null | https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/pseudogene/widgets/expression.clj | clojure | (ns rest-api.classes.pseudogene.widgets.expression
(:require
[rest-api.classes.generic-fields :as generic]
[rest-api.formatters.object :as obj :refer [pack-obj]]))
(defn microarray-results [p]
{:data (some->> (:microarray-results.pseudogene/_pseudogene p)
(map :microarray-results/_pseudogene)
(map pack-obj)
(sort-by :label))
:description "Microarray results"})
(def widget
{:name generic/name-field
:microarray_results microarray-results})
|
|
f64c11c9c48e6c2cfc02c1c1f22f2bdcc709226863aa1185fd67f18df32ab7b8 | bsansouci/reasonglexampleproject | mylazy.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Para , INRIA Rocquencourt
(* *)
Copyright 1997 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : mylazy.mli , v 1.1 2002/04/09 11:00:09 furuse Exp $
(** Deferred computations. *)
type 'a status =
Delayed of (unit -> 'a)
| Value of 'a
| Exception of exn
type 'a t = 'a status ref
(** A value of type ['a Lazy.t] is a deferred computation (also called a
suspension) that computes a result of type ['a]. The expression
[lazy (expr)] returns a suspension that computes [expr]. **)
exception Undefined
val make : (unit -> 'a) -> 'a t
val make_val : 'a -> 'a t
val force : 'a t -> 'a
* [ Lazy.force x ] computes the suspension [ x ] and returns its result .
If the suspension was already computed , [ Lazy.force x ] returns the
same value again . If it raised an exception , the same exception is
raised again .
Raise [ Undefined ] if the evaluation of the suspension requires its
own result .
If the suspension was already computed, [Lazy.force x] returns the
same value again. If it raised an exception, the same exception is
raised again.
Raise [Undefined] if the evaluation of the suspension requires its
own result.
*)
| null | https://raw.githubusercontent.com/bsansouci/reasonglexampleproject/4ecef2cdad3a1a157318d1d64dba7def92d8a924/vendor/camlimages/examples/liv/mylazy.mli | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* Deferred computations.
* A value of type ['a Lazy.t] is a deferred computation (also called a
suspension) that computes a result of type ['a]. The expression
[lazy (expr)] returns a suspension that computes [expr]. * | , projet Para , INRIA Rocquencourt
Copyright 1997 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : mylazy.mli , v 1.1 2002/04/09 11:00:09 furuse Exp $
type 'a status =
Delayed of (unit -> 'a)
| Value of 'a
| Exception of exn
type 'a t = 'a status ref
exception Undefined
val make : (unit -> 'a) -> 'a t
val make_val : 'a -> 'a t
val force : 'a t -> 'a
* [ Lazy.force x ] computes the suspension [ x ] and returns its result .
If the suspension was already computed , [ Lazy.force x ] returns the
same value again . If it raised an exception , the same exception is
raised again .
Raise [ Undefined ] if the evaluation of the suspension requires its
own result .
If the suspension was already computed, [Lazy.force x] returns the
same value again. If it raised an exception, the same exception is
raised again.
Raise [Undefined] if the evaluation of the suspension requires its
own result.
*)
|
eb9045f6cf0206923206ecc70570941be65d3725d9df55b2e95d27728c964e57 | odis-labs/onix | Onix_lock_nix.ml | open Prelude
let gen_pkg ~lock_dir ~ocaml_version ~gitignore ~with_test ~with_doc
~with_dev_setup (lock_pkg : Lock_pkg.t) =
let pkg_name = OpamPackage.name_to_string lock_pkg.opam_details.package in
let pkg_lock_dir = lock_dir </> "packages" </> pkg_name in
let pkg_default_nix =
OpamFilename.mkdir pkg_lock_dir;
OpamFilename.to_string (pkg_lock_dir <//> "default.nix")
in
Out_channel.with_open_text pkg_default_nix @@ fun chan ->
let nix_pkg =
Nix_pkg.of_lock_pkg ~ocaml_version ~with_test ~with_doc ~with_dev_setup
lock_pkg
in
Nix_pkg.copy_extra_files ~pkg_lock_dir nix_pkg.extra_files;
(* let nix_pkg = Nix_pkg.resolve_files ~lock_dir nix_pkg in *)
let out = Format.formatter_of_out_channel chan in
Fmt.pf out "%a" (Pp.pp_pkg ~gitignore) nix_pkg
let gen_overlay ~lock_dir =
let overlay_dir = lock_dir </> "overlay" in
List.iter
(fun relpath ->
let file = OpamFilename.(create overlay_dir (Base.of_string relpath)) in
let dir = OpamFilename.dirname file in
OpamFilename.mkdir dir;
match Overlay_files.read relpath with
| None ->
Fmt.failwith "internal error: could not read embedded overlay file: %a"
Opam_utils.pp_filename file
| Some file_content -> OpamFilename.write file file_content)
Overlay_files.file_list
let gen_index ~lock_dir lock_pkgs =
let index_file =
OpamFilename.Op.(lock_dir // "default.nix") |> OpamFilename.to_string
in
Out_channel.with_open_text index_file @@ fun chan ->
let f = Format.formatter_of_out_channel chan in
Pp.pp_index f lock_pkgs
let gen ~gitignore ~lock_dir ~with_test ~with_doc ~with_dev_setup
(lock_file : Lock_file.t) =
let ocaml_version = OpamPackage.version lock_file.compiler in
let lock_dir = OpamFilename.Dir.of_string lock_dir in
OpamFilename.rmdir lock_dir;
OpamFilename.mkdir lock_dir;
gen_overlay ~lock_dir;
gen_index ~lock_dir lock_file.packages;
List.iter
(gen_pkg ~lock_dir ~ocaml_version ~gitignore ~with_test ~with_doc
~with_dev_setup)
lock_file.packages
module Nix_pkg = Nix_pkg
module Nix_filter = Nix_filter
module Pp = Pp
| null | https://raw.githubusercontent.com/odis-labs/onix/81cc82953ef062425656ac9bf80474f2ce642f5b/src/onix_lock_nix/Onix_lock_nix.ml | ocaml | let nix_pkg = Nix_pkg.resolve_files ~lock_dir nix_pkg in | open Prelude
let gen_pkg ~lock_dir ~ocaml_version ~gitignore ~with_test ~with_doc
~with_dev_setup (lock_pkg : Lock_pkg.t) =
let pkg_name = OpamPackage.name_to_string lock_pkg.opam_details.package in
let pkg_lock_dir = lock_dir </> "packages" </> pkg_name in
let pkg_default_nix =
OpamFilename.mkdir pkg_lock_dir;
OpamFilename.to_string (pkg_lock_dir <//> "default.nix")
in
Out_channel.with_open_text pkg_default_nix @@ fun chan ->
let nix_pkg =
Nix_pkg.of_lock_pkg ~ocaml_version ~with_test ~with_doc ~with_dev_setup
lock_pkg
in
Nix_pkg.copy_extra_files ~pkg_lock_dir nix_pkg.extra_files;
let out = Format.formatter_of_out_channel chan in
Fmt.pf out "%a" (Pp.pp_pkg ~gitignore) nix_pkg
let gen_overlay ~lock_dir =
let overlay_dir = lock_dir </> "overlay" in
List.iter
(fun relpath ->
let file = OpamFilename.(create overlay_dir (Base.of_string relpath)) in
let dir = OpamFilename.dirname file in
OpamFilename.mkdir dir;
match Overlay_files.read relpath with
| None ->
Fmt.failwith "internal error: could not read embedded overlay file: %a"
Opam_utils.pp_filename file
| Some file_content -> OpamFilename.write file file_content)
Overlay_files.file_list
let gen_index ~lock_dir lock_pkgs =
let index_file =
OpamFilename.Op.(lock_dir // "default.nix") |> OpamFilename.to_string
in
Out_channel.with_open_text index_file @@ fun chan ->
let f = Format.formatter_of_out_channel chan in
Pp.pp_index f lock_pkgs
let gen ~gitignore ~lock_dir ~with_test ~with_doc ~with_dev_setup
(lock_file : Lock_file.t) =
let ocaml_version = OpamPackage.version lock_file.compiler in
let lock_dir = OpamFilename.Dir.of_string lock_dir in
OpamFilename.rmdir lock_dir;
OpamFilename.mkdir lock_dir;
gen_overlay ~lock_dir;
gen_index ~lock_dir lock_file.packages;
List.iter
(gen_pkg ~lock_dir ~ocaml_version ~gitignore ~with_test ~with_doc
~with_dev_setup)
lock_file.packages
module Nix_pkg = Nix_pkg
module Nix_filter = Nix_filter
module Pp = Pp
|
52378667f69af76fcd1687230f6cad8a980c127b8f735c21163b1cc68bc3b757 | ocaml/ocaml | pr7553.ml | (* TEST
flags = " -w +A -strict-sequence "
* expect
*)
module A = struct type foo end;;
[%%expect {|
module A : sig type foo end
|}]
module rec B : sig
open A
type bar = Bar of foo
end = B;;
[%%expect {|
module rec B : sig type bar = Bar of A.foo end
|}]
module rec C : sig
open A
end = C;;
[%%expect {|
Line 2, characters 2-8:
2 | open A
^^^^^^
Warning 33 [unused-open]: unused open A.
module rec C : sig end
|}]
module rec D : sig
module M : module type of struct
module X : sig end = struct
open A
let None = None
end
end
end = D;;
[%%expect {|
Line 5, characters 10-14:
5 | let None = None
^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Some _
Line 4, characters 6-12:
4 | open A
^^^^^^
Warning 33 [unused-open]: unused open A.
module rec D : sig module M : sig module X : sig end end end
|}]
| null | https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-warnings/pr7553.ml | ocaml | TEST
flags = " -w +A -strict-sequence "
* expect
|
module A = struct type foo end;;
[%%expect {|
module A : sig type foo end
|}]
module rec B : sig
open A
type bar = Bar of foo
end = B;;
[%%expect {|
module rec B : sig type bar = Bar of A.foo end
|}]
module rec C : sig
open A
end = C;;
[%%expect {|
Line 2, characters 2-8:
2 | open A
^^^^^^
Warning 33 [unused-open]: unused open A.
module rec C : sig end
|}]
module rec D : sig
module M : module type of struct
module X : sig end = struct
open A
let None = None
end
end
end = D;;
[%%expect {|
Line 5, characters 10-14:
5 | let None = None
^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Some _
Line 4, characters 6-12:
4 | open A
^^^^^^
Warning 33 [unused-open]: unused open A.
module rec D : sig module M : sig module X : sig end end end
|}]
|
30be0ed16fb17657b543096413567dfac1abd148dd59b7c9555dc24d37bfc3fe | zanderso/cil-template | tut2.ml |
open Cil
module E = Errormsg
open Tututil
class assignRmVisitor (vname : string) = object(self)
inherit nopCilVisitor
method vinst (i : instr) =
match i with
| Set((Var vi, NoOffset), _, loc) when vi.vname = vname && vi.vglob ->
E.log "%a: Assignment deleted: %a\n" d_loc loc d_instr i;
ChangeTo []
| _ -> SkipChildren
end
let processFunction ((tf, tv) : string * string) (fd : fundec) (loc : location) : unit =
if fd.svar.vname <> tf then () else begin
let vis = new assignRmVisitor tv in
ignore(visitCilFunction vis fd)
end
let tut2 (funvar : string * string) (f : file) : unit =
funvar |> processFunction |> onlyFunctions |> iterGlobals f
| null | https://raw.githubusercontent.com/zanderso/cil-template/fc2a0548b2644c53c4840df2a09c1c90b2af2aee/src/tut2.ml | ocaml |
open Cil
module E = Errormsg
open Tututil
class assignRmVisitor (vname : string) = object(self)
inherit nopCilVisitor
method vinst (i : instr) =
match i with
| Set((Var vi, NoOffset), _, loc) when vi.vname = vname && vi.vglob ->
E.log "%a: Assignment deleted: %a\n" d_loc loc d_instr i;
ChangeTo []
| _ -> SkipChildren
end
let processFunction ((tf, tv) : string * string) (fd : fundec) (loc : location) : unit =
if fd.svar.vname <> tf then () else begin
let vis = new assignRmVisitor tv in
ignore(visitCilFunction vis fd)
end
let tut2 (funvar : string * string) (f : file) : unit =
funvar |> processFunction |> onlyFunctions |> iterGlobals f
|
|
040a279da6d7164fd5291362001322a6c46648da459d43580653603a496ae4fe | bract/bract.core | project.clj | (defproject bract/bract.core "0.6.2"
:description "Multi-purpose, modular Clojure application initialization framework"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:global-vars {*warn-on-reflection* true
*assert* true
*unchecked-math* :warn-on-boxed}
:dependencies [[keypin "0.8.2"]]
:java-source-paths ["src-java"]
:javac-options ["-target" "1.7" "-source" "1.7" "-Xlint:-options"]
:profiles {:provided {:dependencies [[org.clojure/clojure "1.7.0"]]}
:coverage {:plugins [[lein-cloverage "1.0.9"]]}
:rel {:min-lein-version "2.7.1"
:pedantic? :abort}
:c07 {:dependencies [[org.clojure/clojure "1.7.0"]]}
:c08 {:dependencies [[org.clojure/clojure "1.8.0"]]}
:c09 {:dependencies [[org.clojure/clojure "1.9.0"]]}
:c10 {:dependencies [[org.clojure/clojure "1.10.3-rc1"]]}
:dln {:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}}
:aliases {"test-all" ["with-profile" "c07:c08:c09:c10" "test"]})
| null | https://raw.githubusercontent.com/bract/bract.core/625b8738554b1e1b61bd8522397fb698fb12d3d3/project.clj | clojure | (defproject bract/bract.core "0.6.2"
:description "Multi-purpose, modular Clojure application initialization framework"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:global-vars {*warn-on-reflection* true
*assert* true
*unchecked-math* :warn-on-boxed}
:dependencies [[keypin "0.8.2"]]
:java-source-paths ["src-java"]
:javac-options ["-target" "1.7" "-source" "1.7" "-Xlint:-options"]
:profiles {:provided {:dependencies [[org.clojure/clojure "1.7.0"]]}
:coverage {:plugins [[lein-cloverage "1.0.9"]]}
:rel {:min-lein-version "2.7.1"
:pedantic? :abort}
:c07 {:dependencies [[org.clojure/clojure "1.7.0"]]}
:c08 {:dependencies [[org.clojure/clojure "1.8.0"]]}
:c09 {:dependencies [[org.clojure/clojure "1.9.0"]]}
:c10 {:dependencies [[org.clojure/clojure "1.10.3-rc1"]]}
:dln {:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}}
:aliases {"test-all" ["with-profile" "c07:c08:c09:c10" "test"]})
|
|
3c0e287f6d602eb55fe3594b936d8f2053583bcc330bffcd98a648d932f17e95 | mwand/eopl3 | pairval1.scm | (module pairval1 (lib "eopl.ss" "eopl")
(require "drscheme-init.scm")
(require "store.scm")
(provide (all-defined-out))
;;;;;;;;;;;;;;;; mutable pairs ;;;;;;;;;;;;;;;;
represent a mutable pair as two references .
Page : 124
(define-datatype mutpair mutpair?
(a-pair
(left-loc reference?)
(right-loc reference?)))
make - pair : ExpVal * ExpVal - > MutPair
Page : 124
(define make-pair
(lambda (val1 val2)
(a-pair
(newref val1)
(newref val2))))
left : MutPair - > ExpVal
Page : 125
(define left
(lambda (p)
(cases mutpair p
(a-pair (left-loc right-loc)
(deref left-loc)))))
right : MutPair - > ExpVal
Page : 125
(define right
(lambda (p)
(cases mutpair p
(a-pair (left-loc right-loc)
(deref right-loc)))))
;; setleft : MutPair * ExpVal -> Unspecified
Page : 125
(define setleft
(lambda (p val)
(cases mutpair p
(a-pair (left-loc right-loc)
(setref! left-loc val)))))
;; setright : MutPair * ExpVal -> Unspecified
Page : 125
(define setright
(lambda (p val)
(cases mutpair p
(a-pair (left-loc right-loc)
(setref! right-loc val)))))
)
| null | https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter4/call-by-reference/pairval1.scm | scheme | mutable pairs ;;;;;;;;;;;;;;;;
setleft : MutPair * ExpVal -> Unspecified
setright : MutPair * ExpVal -> Unspecified | (module pairval1 (lib "eopl.ss" "eopl")
(require "drscheme-init.scm")
(require "store.scm")
(provide (all-defined-out))
represent a mutable pair as two references .
Page : 124
(define-datatype mutpair mutpair?
(a-pair
(left-loc reference?)
(right-loc reference?)))
make - pair : ExpVal * ExpVal - > MutPair
Page : 124
(define make-pair
(lambda (val1 val2)
(a-pair
(newref val1)
(newref val2))))
left : MutPair - > ExpVal
Page : 125
(define left
(lambda (p)
(cases mutpair p
(a-pair (left-loc right-loc)
(deref left-loc)))))
right : MutPair - > ExpVal
Page : 125
(define right
(lambda (p)
(cases mutpair p
(a-pair (left-loc right-loc)
(deref right-loc)))))
Page : 125
(define setleft
(lambda (p val)
(cases mutpair p
(a-pair (left-loc right-loc)
(setref! left-loc val)))))
Page : 125
(define setright
(lambda (p val)
(cases mutpair p
(a-pair (left-loc right-loc)
(setref! right-loc val)))))
)
|
49371b42c15d27a4a59f1e382dfca1feb69851202268bf4405706ae146e626db | saep/nvim-hs-ghcid | Main.hs | module Main where
import Neovim
import qualified Neovim.Ghcid as Ghcid
main :: IO ()
main = neovim defaultConfig{plugins = [Ghcid.plugin]}
| null | https://raw.githubusercontent.com/saep/nvim-hs-ghcid/bb31f389542328d2e024858815a4bf179d5fafef/executable/Main.hs | haskell | module Main where
import Neovim
import qualified Neovim.Ghcid as Ghcid
main :: IO ()
main = neovim defaultConfig{plugins = [Ghcid.plugin]}
|
|
721f238f3f69ca273eec8333a095af1aa3d16b925fc57a4c82a901fd7bc33a88 | runexec/chp | chp.clj | (ns chp.routes.chp
(:use chp.core
[cheshire.core
:only [generate-string]]
[chp.api
:only [api->where]]
[chp.builder
:only [binding-exist?]]))
(defchp chp-builder-paths
(chp-route "/chp/api" (root-parse "chp/api.chtml"))
(chp-route ["/chp/api/:table" :table #"[a-zA-Z0-9-_]*"]
(try
(let [table ($p table)
return (api->where (keyword table) ($ params))]
(if-not (seq return)
"{}"
(let [return (mapv #(generate-string % {:pretty true})
return)
rc (count return)]
(format "{\"data\": [%s]}"
(apply str
(if (<= rc 1)
return
(drop-last
(interleave return
(repeat rc ",")))))))))
(catch Exception e
(println e "=>" (.. e getMessage))
"An error occured")))
(chp-route "/chp/login"
(or (chp-when :get (root-parse "chp/login.chtml"))
(chp-when :post (root-parse "chp/login-session.chtml"))
"Not Found")))
(defn display? [] (binding-exist? ($p table)))
(comment
Disabled by default and could be dangerous on a live site
Add this body to the routes for quick testing, but use the
view generator just to be safe.
: table gets passed to functions in chp.builder , and these functions
;; turn the :table->:keyword to resources/bindings/keyword.clj. Removing the
;; regex restraints can be potentially dangerous.
(chp-route ["/chp/list/:table" :table #"[a-zA-Z0-9-_]*"]
(if (display?)
(root-parse "chp/list.chtml")
"Not Found"))
(chp-route ["/chp/new/:table" :table #"[a-zA-Z0-9-_]*"]
(if (display?)
(root-parse "chp/new.chtml")
"Not Found"))
(chp-route ["/chp/edit/:table/:id"
:table #"[a-zA-Z0-9-_]*"
:id #"\d+"]
(if (display?)
(root-parse "chp/edit.chtml")
"Not Found"))
(chp-route ["/chp/view/:table/:id"
:table #"[a-zA-Z0-9-_]*"
:id #"\d+"]
(if (display?)
(root-parse "chp/view.chtml")
"Not Found")))
| null | https://raw.githubusercontent.com/runexec/chp/9059399c46fb4106a73631c741f1e557af541a8b/src/chp/routes/chp.clj | clojure | turn the :table->:keyword to resources/bindings/keyword.clj. Removing the
regex restraints can be potentially dangerous. | (ns chp.routes.chp
(:use chp.core
[cheshire.core
:only [generate-string]]
[chp.api
:only [api->where]]
[chp.builder
:only [binding-exist?]]))
(defchp chp-builder-paths
(chp-route "/chp/api" (root-parse "chp/api.chtml"))
(chp-route ["/chp/api/:table" :table #"[a-zA-Z0-9-_]*"]
(try
(let [table ($p table)
return (api->where (keyword table) ($ params))]
(if-not (seq return)
"{}"
(let [return (mapv #(generate-string % {:pretty true})
return)
rc (count return)]
(format "{\"data\": [%s]}"
(apply str
(if (<= rc 1)
return
(drop-last
(interleave return
(repeat rc ",")))))))))
(catch Exception e
(println e "=>" (.. e getMessage))
"An error occured")))
(chp-route "/chp/login"
(or (chp-when :get (root-parse "chp/login.chtml"))
(chp-when :post (root-parse "chp/login-session.chtml"))
"Not Found")))
(defn display? [] (binding-exist? ($p table)))
(comment
Disabled by default and could be dangerous on a live site
Add this body to the routes for quick testing, but use the
view generator just to be safe.
: table gets passed to functions in chp.builder , and these functions
(chp-route ["/chp/list/:table" :table #"[a-zA-Z0-9-_]*"]
(if (display?)
(root-parse "chp/list.chtml")
"Not Found"))
(chp-route ["/chp/new/:table" :table #"[a-zA-Z0-9-_]*"]
(if (display?)
(root-parse "chp/new.chtml")
"Not Found"))
(chp-route ["/chp/edit/:table/:id"
:table #"[a-zA-Z0-9-_]*"
:id #"\d+"]
(if (display?)
(root-parse "chp/edit.chtml")
"Not Found"))
(chp-route ["/chp/view/:table/:id"
:table #"[a-zA-Z0-9-_]*"
:id #"\d+"]
(if (display?)
(root-parse "chp/view.chtml")
"Not Found")))
|
76d46b42979ab1b21c795466d734be60fe5a3f7de6d932a546adc803052b1f64 | ucsd-progsys/liquid-fixpoint | Theories.hs | {-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE CPP #
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE DeriveDataTypeable #-}
# OPTIONS_GHC -Wno - orphans #
{-# OPTIONS_GHC -Wno-name-shadowing #-}
| This module contains the types defining an SMTLIB2 interface .
module Language.Fixpoint.Types.Theories (
-- * Serialized Representation
Raw
-- * Theory Symbol
, TheorySymbol (..)
, Sem (..)
-- * Theory Sorts
, SmtSort (..)
, sortSmtSort
, isIntSmtSort
-- * Symbol Environments
, SymEnv (..)
, symEnv
, symEnvSort
, symEnvTheory
, insertSymEnv
, insertsSymEnv
, symbolAtName
, symbolAtSmtName
) where
import Data.Generics (Data)
import Data.Typeable (Typeable)
import Data.Hashable
import GHC.Generics (Generic)
import Control.DeepSeq
import Language.Fixpoint.Types.PrettyPrint
import Language.Fixpoint.Types.Names
import Language.Fixpoint.Types.Sorts
import Language.Fixpoint.Types.Errors
import Language.Fixpoint.Types.Environments
import Text.PrettyPrint.HughesPJ.Compat
import qualified Data.List as L
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Store as S
import qualified Data.HashMap.Strict as M
import qualified Language.Fixpoint.Misc as Misc
--------------------------------------------------------------------------------
| ' Raw ' is the low - level representation for SMT values
--------------------------------------------------------------------------------
type Raw = Text
--------------------------------------------------------------------------------
| ' SymEnv ' is used to resolve the ' Sort ' and ' Sem ' of each ' Symbol '
--------------------------------------------------------------------------------
data SymEnv = SymEnv
{ seSort :: !(SEnv Sort) -- ^ Sorts of *all* defined symbols
, seTheory :: !(SEnv TheorySymbol) -- ^ Information about theory-specific Symbols
, seData :: !(SEnv DataDecl) -- ^ User-defined data-declarations
, seLits :: !(SEnv Sort) -- ^ Distinct Constant symbols
, seAppls :: !(M.HashMap FuncSort Int) -- ^ Types at which `apply` was used;
-- see [NOTE:apply-monomorphization]
}
deriving (Eq, Show, Data, Typeable, Generic)
{- type FuncSort = {v:Sort | isFFunc v} @-}
type FuncSort = (SmtSort, SmtSort)
instance NFData SymEnv
instance S.Store SymEnv
instance Semigroup SymEnv where
e1 <> e2 = SymEnv { seSort = seSort e1 <> seSort e2
, seTheory = seTheory e1 <> seTheory e2
, seData = seData e1 <> seData e2
, seLits = seLits e1 <> seLits e2
, seAppls = seAppls e1 <> seAppls e2
}
instance Monoid SymEnv where
mempty = SymEnv emptySEnv emptySEnv emptySEnv emptySEnv mempty
mappend = (<>)
symEnv :: SEnv Sort -> SEnv TheorySymbol -> [DataDecl] -> SEnv Sort -> [Sort] -> SymEnv
symEnv xEnv fEnv ds ls ts = SymEnv xEnv' fEnv dEnv ls sortMap
where
xEnv' = unionSEnv xEnv wiredInEnv
dEnv = fromListSEnv [(symbol d, d) | d <- ds]
sortMap = M.fromList (zip smts [0..])
smts = funcSorts dEnv ts
-- | These are "BUILT-in" polymorphic functions which are
UNININTERPRETED but POLYMORPHIC , hence need to go through
-- the apply-defunc stuff.
wiredInEnv :: M.HashMap Symbol Sort
wiredInEnv = M.fromList
[ (toIntName, mkFFunc 1 [FVar 0, FInt])
, (tyCastName, FAbs 0 $ FAbs 1 $ FFunc (FVar 0) (FVar 1))
]
| ' smtSorts ' attempts to compute a list of all the input - output sorts
-- at which applications occur. This is a gross hack; as during unfolding
-- we may create _new_ terms with wierd new sorts. Ideally, we MUST allow
-- for EXTENDING the apply-sorts with those newly created terms.
-- the solution is perhaps to *preface* each VC query of the form
--
-- push
-- assert p
-- check-sat
-- pop
--
with the declarations needed to make ' p ' well - sorted under SMT , i.e.
-- change the above to
--
-- declare apply-sorts
-- push
-- assert p
-- check-sat
-- pop
--
such a strategy would NUKE the entire apply - sort machinery from the CODE base .
-- [TODO]: dynamic-apply-declaration
funcSorts :: SEnv DataDecl -> [Sort] -> [FuncSort]
funcSorts dEnv ts = [ (t1, t2) | t1 <- smts, t2 <- smts]
where
smts = Misc.sortNub $ concat [ [tx t1, tx t2] | FFunc t1 t2 <- ts]
tx = applySmtSort dEnv
symEnvTheory :: Symbol -> SymEnv -> Maybe TheorySymbol
symEnvTheory x env = lookupSEnv x (seTheory env)
symEnvSort :: Symbol -> SymEnv -> Maybe Sort
symEnvSort x env = lookupSEnv x (seSort env)
insertSymEnv :: Symbol -> Sort -> SymEnv -> SymEnv
insertSymEnv x t env = env { seSort = insertSEnv x t (seSort env) }
insertsSymEnv :: SymEnv -> [(Symbol, Sort)] -> SymEnv
insertsSymEnv = L.foldl' (\env (x, s) -> insertSymEnv x s env)
symbolAtName :: (PPrint a) => Symbol -> SymEnv -> a -> Sort -> Text
symbolAtName mkSym env e = symbolAtSmtName mkSym env e . ffuncSort env
# SCC symbolAtName #
symbolAtSmtName :: (PPrint a) => Symbol -> SymEnv -> a -> FuncSort -> Text
symbolAtSmtName mkSym env e s =
formerly : intSymbol mkSym . funcSortIndex env e
appendSymbolText mkSym $ Text.pack (show (funcSortIndex env e s))
# SCC symbolAtSmtName #
funcSortIndex :: (PPrint a) => SymEnv -> a -> FuncSort -> Int
funcSortIndex env e z = M.lookupDefault err z (seAppls env)
where
err = panic ("Unknown func-sort: " ++ showpp z ++ " for " ++ showpp e)
ffuncSort :: SymEnv -> Sort -> FuncSort
tracepp ( " ffuncSort " + + showpp ( ) )
where
tx = applySmtSort (seData env)
(t1, t2) = args t
args (FFunc a b) = (a, b)
args _ = (FInt, FInt)
applySmtSort :: SEnv DataDecl -> Sort -> SmtSort
applySmtSort = sortSmtSort False
isIntSmtSort :: SEnv DataDecl -> Sort -> Bool
isIntSmtSort env s = SInt == applySmtSort env s
--------------------------------------------------------------------------------
| ' ' represents the information about each interpreted ' Symbol '
--------------------------------------------------------------------------------
data TheorySymbol = Thy
{ tsSym :: !Symbol -- ^ name
^ serialized name
, tsSort :: !Sort -- ^ sort
, tsInterp :: !Sem -- ^ TRUE = defined (interpreted), FALSE = declared (uninterpreted)
}
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance NFData Sem
instance NFData TheorySymbol
instance S.Store TheorySymbol
instance PPrint Sem where
pprintTidy _ = text . show
instance Fixpoint TheorySymbol where
toFix (Thy x _ t d) = text "TheorySymbol" <+> pprint (x, t) <+> parens (pprint d)
instance PPrint TheorySymbol where
pprintTidy k (Thy x _ t d) = text "TheorySymbol" <+> pprintTidy k (x, t) <+> parens (pprint d)
--------------------------------------------------------------------------------
| ' Sem ' describes the SMT semantics for a given symbol
--------------------------------------------------------------------------------
data Sem
^ for UDF : ` len ` , ` height ` , ` append `
^ for ADT constructor and tests : ` cons ` , ` nil `
^ for ADT tests : ` is$cons `
^ for ADT field : ` hd ` , ` tl `
| Theory -- ^ for theory ops: mem, cup, select
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance S.Store Sem
--------------------------------------------------------------------------------
-- | A Refinement of 'Sort' that describes SMTLIB Sorts
--------------------------------------------------------------------------------
data SmtSort
= SInt
| SBool
| SReal
| SString
| SSet
| SMap
| SBitVec !Int
| SVar !Int
| SData !FTycon ![SmtSort]
HKT | SApp ! [ SmtSort ] -- ^ Representing HKT
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance Hashable SmtSort
instance NFData SmtSort
instance S.Store SmtSort
-- | The 'poly' parameter is True when we are *declaring* sorts,
-- and so we need to leave the top type variables be; it is False when
-- we are declaring variables etc., and there, we serialize them
-- using `Int` (though really, there SHOULD BE NO floating tyVars...
-- 'smtSort True msg t' serializes a sort 't' using type variables,
-- 'smtSort False msg t' serializes a sort 't' using 'Int' instead of tyvars.
sortSmtSort :: Bool -> SEnv DataDecl -> Sort -> SmtSort
sortSmtSort poly env t = {- tracepp ("sortSmtSort: " ++ showpp t) else id) $ -} go . unAbs $ t
where
m = sortAbs t
go (FFunc _ _) = SInt
go FInt = SInt
go FReal = SReal
go t
| t == boolSort = SBool
| isString t = SString
go (FVar i)
| poly, i < m = SVar i
| otherwise = SInt
go t
| (ct:ts) <- unFApp t = fappSmtSort poly m env ct ts
| otherwise = error "Unexpected empty 'unFApp t'"
fappSmtSort :: Bool -> Int -> SEnv DataDecl -> Sort -> [Sort] -> SmtSort
fappSmtSort poly m env = go
where
HKT go t@(FVar _ ) ts = SApp ( sortSmtSort poly env < $ > ( t : ts ) )
go (FTC c) _
| setConName == symbol c = SSet
go (FTC c) _
| mapConName == symbol c = SMap
go (FTC bv) [FTC s]
| bitVecName == symbol bv
, Just n <- sizeBv s = SBitVec n
go s []
| isString s = SString
go (FTC c) ts
| Just n <- tyArgs c env
, let i = n - length ts = SData c ((sortSmtSort poly env . FAbs m <$> ts) ++ pad i)
go _ _ = SInt
pad i | poly = []
| otherwise = replicate i SInt
tyArgs :: (Symbolic x) => x -> SEnv DataDecl -> Maybe Int
tyArgs x env = ddVars <$> lookupSEnv (symbol x) env
instance PPrint SmtSort where
pprintTidy _ SInt = text "Int"
pprintTidy _ SBool = text "Bool"
pprintTidy _ SReal = text "Real"
pprintTidy _ SString = text "Str"
pprintTidy _ SSet = text "Set"
pprintTidy _ SMap = text "Map"
pprintTidy _ (SBitVec n) = text "BitVec" <+> int n
pprintTidy _ (SVar i) = text "@" <-> int i
HKT pprintTidy k ( SApp ts ) = ppParens k ( pprintTidy k tyAppName ) ts
pprintTidy k (SData c ts) = ppParens k (pprintTidy k c) ts
ppParens :: (PPrint d) => Tidy -> Doc -> [d] -> Doc
ppParens k d ds = parens $ Misc.intersperse (text "") (d : (pprintTidy k <$> ds))
| null | https://raw.githubusercontent.com/ucsd-progsys/liquid-fixpoint/0e1a4725793740f495c26957044c56488d6e1efc/src/Language/Fixpoint/Types/Theories.hs | haskell | # LANGUAGE TypeSynonymInstances #
# LANGUAGE DeriveGeneric #
# LANGUAGE PatternGuards #
# LANGUAGE DeriveDataTypeable #
# OPTIONS_GHC -Wno-name-shadowing #
* Serialized Representation
* Theory Symbol
* Theory Sorts
* Symbol Environments
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
^ Sorts of *all* defined symbols
^ Information about theory-specific Symbols
^ User-defined data-declarations
^ Distinct Constant symbols
^ Types at which `apply` was used;
see [NOTE:apply-monomorphization]
type FuncSort = {v:Sort | isFFunc v} @
| These are "BUILT-in" polymorphic functions which are
the apply-defunc stuff.
at which applications occur. This is a gross hack; as during unfolding
we may create _new_ terms with wierd new sorts. Ideally, we MUST allow
for EXTENDING the apply-sorts with those newly created terms.
the solution is perhaps to *preface* each VC query of the form
push
assert p
check-sat
pop
change the above to
declare apply-sorts
push
assert p
check-sat
pop
[TODO]: dynamic-apply-declaration
------------------------------------------------------------------------------
------------------------------------------------------------------------------
^ name
^ sort
^ TRUE = defined (interpreted), FALSE = declared (uninterpreted)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
^ for theory ops: mem, cup, select
------------------------------------------------------------------------------
| A Refinement of 'Sort' that describes SMTLIB Sorts
------------------------------------------------------------------------------
^ Representing HKT
| The 'poly' parameter is True when we are *declaring* sorts,
and so we need to leave the top type variables be; it is False when
we are declaring variables etc., and there, we serialize them
using `Int` (though really, there SHOULD BE NO floating tyVars...
'smtSort True msg t' serializes a sort 't' using type variables,
'smtSort False msg t' serializes a sort 't' using 'Int' instead of tyvars.
tracepp ("sortSmtSort: " ++ showpp t) else id) $ | # LANGUAGE CPP #
# OPTIONS_GHC -Wno - orphans #
| This module contains the types defining an SMTLIB2 interface .
module Language.Fixpoint.Types.Theories (
Raw
, TheorySymbol (..)
, Sem (..)
, SmtSort (..)
, sortSmtSort
, isIntSmtSort
, SymEnv (..)
, symEnv
, symEnvSort
, symEnvTheory
, insertSymEnv
, insertsSymEnv
, symbolAtName
, symbolAtSmtName
) where
import Data.Generics (Data)
import Data.Typeable (Typeable)
import Data.Hashable
import GHC.Generics (Generic)
import Control.DeepSeq
import Language.Fixpoint.Types.PrettyPrint
import Language.Fixpoint.Types.Names
import Language.Fixpoint.Types.Sorts
import Language.Fixpoint.Types.Errors
import Language.Fixpoint.Types.Environments
import Text.PrettyPrint.HughesPJ.Compat
import qualified Data.List as L
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Store as S
import qualified Data.HashMap.Strict as M
import qualified Language.Fixpoint.Misc as Misc
| ' Raw ' is the low - level representation for SMT values
type Raw = Text
| ' SymEnv ' is used to resolve the ' Sort ' and ' Sem ' of each ' Symbol '
data SymEnv = SymEnv
}
deriving (Eq, Show, Data, Typeable, Generic)
type FuncSort = (SmtSort, SmtSort)
instance NFData SymEnv
instance S.Store SymEnv
instance Semigroup SymEnv where
e1 <> e2 = SymEnv { seSort = seSort e1 <> seSort e2
, seTheory = seTheory e1 <> seTheory e2
, seData = seData e1 <> seData e2
, seLits = seLits e1 <> seLits e2
, seAppls = seAppls e1 <> seAppls e2
}
instance Monoid SymEnv where
mempty = SymEnv emptySEnv emptySEnv emptySEnv emptySEnv mempty
mappend = (<>)
symEnv :: SEnv Sort -> SEnv TheorySymbol -> [DataDecl] -> SEnv Sort -> [Sort] -> SymEnv
symEnv xEnv fEnv ds ls ts = SymEnv xEnv' fEnv dEnv ls sortMap
where
xEnv' = unionSEnv xEnv wiredInEnv
dEnv = fromListSEnv [(symbol d, d) | d <- ds]
sortMap = M.fromList (zip smts [0..])
smts = funcSorts dEnv ts
UNININTERPRETED but POLYMORPHIC , hence need to go through
wiredInEnv :: M.HashMap Symbol Sort
wiredInEnv = M.fromList
[ (toIntName, mkFFunc 1 [FVar 0, FInt])
, (tyCastName, FAbs 0 $ FAbs 1 $ FFunc (FVar 0) (FVar 1))
]
| ' smtSorts ' attempts to compute a list of all the input - output sorts
with the declarations needed to make ' p ' well - sorted under SMT , i.e.
such a strategy would NUKE the entire apply - sort machinery from the CODE base .
funcSorts :: SEnv DataDecl -> [Sort] -> [FuncSort]
funcSorts dEnv ts = [ (t1, t2) | t1 <- smts, t2 <- smts]
where
smts = Misc.sortNub $ concat [ [tx t1, tx t2] | FFunc t1 t2 <- ts]
tx = applySmtSort dEnv
symEnvTheory :: Symbol -> SymEnv -> Maybe TheorySymbol
symEnvTheory x env = lookupSEnv x (seTheory env)
symEnvSort :: Symbol -> SymEnv -> Maybe Sort
symEnvSort x env = lookupSEnv x (seSort env)
insertSymEnv :: Symbol -> Sort -> SymEnv -> SymEnv
insertSymEnv x t env = env { seSort = insertSEnv x t (seSort env) }
insertsSymEnv :: SymEnv -> [(Symbol, Sort)] -> SymEnv
insertsSymEnv = L.foldl' (\env (x, s) -> insertSymEnv x s env)
symbolAtName :: (PPrint a) => Symbol -> SymEnv -> a -> Sort -> Text
symbolAtName mkSym env e = symbolAtSmtName mkSym env e . ffuncSort env
# SCC symbolAtName #
symbolAtSmtName :: (PPrint a) => Symbol -> SymEnv -> a -> FuncSort -> Text
symbolAtSmtName mkSym env e s =
formerly : intSymbol mkSym . funcSortIndex env e
appendSymbolText mkSym $ Text.pack (show (funcSortIndex env e s))
# SCC symbolAtSmtName #
funcSortIndex :: (PPrint a) => SymEnv -> a -> FuncSort -> Int
funcSortIndex env e z = M.lookupDefault err z (seAppls env)
where
err = panic ("Unknown func-sort: " ++ showpp z ++ " for " ++ showpp e)
ffuncSort :: SymEnv -> Sort -> FuncSort
tracepp ( " ffuncSort " + + showpp ( ) )
where
tx = applySmtSort (seData env)
(t1, t2) = args t
args (FFunc a b) = (a, b)
args _ = (FInt, FInt)
applySmtSort :: SEnv DataDecl -> Sort -> SmtSort
applySmtSort = sortSmtSort False
isIntSmtSort :: SEnv DataDecl -> Sort -> Bool
isIntSmtSort env s = SInt == applySmtSort env s
| ' ' represents the information about each interpreted ' Symbol '
data TheorySymbol = Thy
^ serialized name
}
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance NFData Sem
instance NFData TheorySymbol
instance S.Store TheorySymbol
instance PPrint Sem where
pprintTidy _ = text . show
instance Fixpoint TheorySymbol where
toFix (Thy x _ t d) = text "TheorySymbol" <+> pprint (x, t) <+> parens (pprint d)
instance PPrint TheorySymbol where
pprintTidy k (Thy x _ t d) = text "TheorySymbol" <+> pprintTidy k (x, t) <+> parens (pprint d)
| ' Sem ' describes the SMT semantics for a given symbol
data Sem
^ for UDF : ` len ` , ` height ` , ` append `
^ for ADT constructor and tests : ` cons ` , ` nil `
^ for ADT tests : ` is$cons `
^ for ADT field : ` hd ` , ` tl `
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance S.Store Sem
data SmtSort
= SInt
| SBool
| SReal
| SString
| SSet
| SMap
| SBitVec !Int
| SVar !Int
| SData !FTycon ![SmtSort]
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance Hashable SmtSort
instance NFData SmtSort
instance S.Store SmtSort
sortSmtSort :: Bool -> SEnv DataDecl -> Sort -> SmtSort
where
m = sortAbs t
go (FFunc _ _) = SInt
go FInt = SInt
go FReal = SReal
go t
| t == boolSort = SBool
| isString t = SString
go (FVar i)
| poly, i < m = SVar i
| otherwise = SInt
go t
| (ct:ts) <- unFApp t = fappSmtSort poly m env ct ts
| otherwise = error "Unexpected empty 'unFApp t'"
fappSmtSort :: Bool -> Int -> SEnv DataDecl -> Sort -> [Sort] -> SmtSort
fappSmtSort poly m env = go
where
HKT go t@(FVar _ ) ts = SApp ( sortSmtSort poly env < $ > ( t : ts ) )
go (FTC c) _
| setConName == symbol c = SSet
go (FTC c) _
| mapConName == symbol c = SMap
go (FTC bv) [FTC s]
| bitVecName == symbol bv
, Just n <- sizeBv s = SBitVec n
go s []
| isString s = SString
go (FTC c) ts
| Just n <- tyArgs c env
, let i = n - length ts = SData c ((sortSmtSort poly env . FAbs m <$> ts) ++ pad i)
go _ _ = SInt
pad i | poly = []
| otherwise = replicate i SInt
tyArgs :: (Symbolic x) => x -> SEnv DataDecl -> Maybe Int
tyArgs x env = ddVars <$> lookupSEnv (symbol x) env
instance PPrint SmtSort where
pprintTidy _ SInt = text "Int"
pprintTidy _ SBool = text "Bool"
pprintTidy _ SReal = text "Real"
pprintTidy _ SString = text "Str"
pprintTidy _ SSet = text "Set"
pprintTidy _ SMap = text "Map"
pprintTidy _ (SBitVec n) = text "BitVec" <+> int n
pprintTidy _ (SVar i) = text "@" <-> int i
HKT pprintTidy k ( SApp ts ) = ppParens k ( pprintTidy k tyAppName ) ts
pprintTidy k (SData c ts) = ppParens k (pprintTidy k c) ts
ppParens :: (PPrint d) => Tidy -> Doc -> [d] -> Doc
ppParens k d ds = parens $ Misc.intersperse (text "") (d : (pprintTidy k <$> ds))
|
2fe03daf7ff0e4a9f5886bc283c6c802e6fbfdde0d076d6d6ae9726ad588681d | 47degrees/org | state.cljc | (ns org.state)
(def default-state
{:filter-language nil
:order :stars
:query ""})
| null | https://raw.githubusercontent.com/47degrees/org/3c5038f5f5f1bf97c5930bd94a51e171b33cd027/src/org/state.cljc | clojure | (ns org.state)
(def default-state
{:filter-language nil
:order :stars
:query ""})
|
|
07a2c26360be79c661deeda9683670500166b99ae9d685df86282c67f765557b | PLTools/GT | test804polyvar.ml | open GT
module L : sig
type 'a list = [`Nil | `Cons of 'a * 'a list ]
[@@deriving gt ~options:{gmap }]
end = struct
type 'a list = [`Nil | `Cons of 'a * 'a list ]
[@@deriving gt ~options:{gmap }]
end
type 'a maybe = Just of 'a | Nothing
[@@deriving gt ~options:{show; fmt }]
type 'a pv = [ `A of 'a ]
[@@deriving gt ~options:{show; fmt}]
let () =
let sh x = GT.show pv GT.id x in
Printf.printf "%s\n%!" (sh @@ `A "aaa")
include (struct
type 'a wtf = [ `C of 'a | 'a pv ] maybe
[@@deriving gt ~options:{show; fmt}]
end (* : sig
type 'a wtf = [ `C of 'a | 'a pv ] maybe
[@@deriving gt ~options:{show; fmt}]
end *)
)
let () =
let sh x = GT.show wtf GT.id x in
Printf.printf "%s\t%s\n%!" (sh @@ Just(`A "a")) (sh @@ Just (`C "ccc"))
| null | https://raw.githubusercontent.com/PLTools/GT/62d1a424a3336f2317ba67e447a9ff09d179b583/regression/test804polyvar.ml | ocaml | : sig
type 'a wtf = [ `C of 'a | 'a pv ] maybe
[@@deriving gt ~options:{show; fmt}]
end | open GT
module L : sig
type 'a list = [`Nil | `Cons of 'a * 'a list ]
[@@deriving gt ~options:{gmap }]
end = struct
type 'a list = [`Nil | `Cons of 'a * 'a list ]
[@@deriving gt ~options:{gmap }]
end
type 'a maybe = Just of 'a | Nothing
[@@deriving gt ~options:{show; fmt }]
type 'a pv = [ `A of 'a ]
[@@deriving gt ~options:{show; fmt}]
let () =
let sh x = GT.show pv GT.id x in
Printf.printf "%s\n%!" (sh @@ `A "aaa")
include (struct
type 'a wtf = [ `C of 'a | 'a pv ] maybe
[@@deriving gt ~options:{show; fmt}]
)
let () =
let sh x = GT.show wtf GT.id x in
Printf.printf "%s\t%s\n%!" (sh @@ Just(`A "a")) (sh @@ Just (`C "ccc"))
|
e03db34de4634cdc2d8fcda08bee447ed981f57d62abd713d079581ef2b1be91 | talex5/wayland-proxy-virtwl | main.ml | open Lwt.Syntax
open Lwt.Infix
let ( let*! ) x f =
x >>= function
| `Ok x -> f x
| `Error _ as e -> Lwt.return e
let rec listen ~config ~virtio_gpu socket =
let* (client, _addr) = Lwt_unix.accept socket in
Lwt_unix.set_close_on_exec client;
Log.info (fun f -> f "New connection");
Lwt.async (fun () ->
Lwt.finalize
(fun () ->
let* r = Relay.create ?virtio_gpu config in
Relay.accept r client
)
(fun () ->
Lwt_unix.close client
)
);
listen ~config ~virtio_gpu socket
Connect to socket at [ path ] ( and then close it ) , to see if anyone 's already listening there .
let is_listening path =
let s = Unix.(socket PF_UNIX SOCK_STREAM 0) in
Fun.protect ~finally:(fun () -> Unix.close s) @@ fun () ->
match Unix.connect s (Unix.ADDR_UNIX path) with
| () -> true
| exception Unix.Unix_error(Unix.ECONNREFUSED, _, _) -> false
| exception ex ->
Log.warn (fun f -> f "Error testing socket %S: %a" path Fmt.exn ex);
false
(* Start listening for connections to [wayland_display]. *)
let listen_wayland ~config ~virtio_gpu wayland_display =
let socket_path = Wayland.Unix_transport.socket_path ~wayland_display () in
let existing_socket = Sys.file_exists socket_path in
if existing_socket && is_listening socket_path then (
Lwt.return (`Error (false, Fmt.str "A server is already listening on %S!" socket_path))
) else (
if existing_socket then Unix.unlink socket_path;
let listening_socket = Unix.(socket PF_UNIX SOCK_STREAM 0) in
Unix.set_close_on_exec listening_socket;
Unix.bind listening_socket (Unix.ADDR_UNIX socket_path);
Unix.listen listening_socket 5;
Log.info (fun f -> f "Listening on %S for Wayland clients" socket_path);
Lwt.async (fun () -> listen ~config ~virtio_gpu (Lwt_unix.of_unix_file_descr listening_socket));
Lwt.return (`Ok ())
)
(* Start listening for connections to [x_display] and set $DISPLAY. *)
let listen_x11 ~config ~virtio_gpu x_display =
let xwayland_listening_socket =
let path = Printf.sprintf "\x00/tmp/.X11-unix/X%d" x_display in
let sock = Unix.(socket PF_UNIX SOCK_STREAM 0) in
Unix.set_close_on_exec sock;
Unix.bind sock (Unix.ADDR_UNIX path);
Unix.listen sock 5;
Log.info (fun f -> f "Listening on %S for X clients" path);
sock
in
Lwt.async (fun () -> Xwayland.listen ~config ~virtio_gpu ~display:x_display (Lwt_unix.of_unix_file_descr xwayland_listening_socket));
Unix.putenv "DISPLAY" (Printf.sprintf ":%d" x_display)
let env_replace k v l =
let prefix = k ^ "=" in
(prefix ^ v) :: List.filter (fun x -> not (Config.starts_with ~prefix x)) l
let main setup_tracing use_virtio_gpu wayland_display x_display config args =
Lwt_main.run begin
let* virtio_gpu =
if use_virtio_gpu then
Virtio_gpu.find_device () >|= function
| Ok x -> Some x
| Error (`Msg m) ->
Fmt.epr "No virtio-gpu device: %s@." m;
exit 1
else Lwt.return_none
in
let* () = setup_tracing ~wayland_display in
Listen for incoming Wayland client connections :
let*! () = listen_wayland ~config ~virtio_gpu wayland_display in
(* Listen for incoming X11 client connections, if configured: *)
Option.iter (listen_x11 ~config ~virtio_gpu) x_display;
(* Run the application (if any), or just wait (if not): *)
match args with
| [] ->
fst (Lwt.wait ())
| args ->
let env =
Unix.environment ()
|> Array.to_list
|> env_replace "WAYLAND_DISPLAY" wayland_display
|> Array.of_list
in
let child = Lwt_process.open_process_none ("", Array.of_list args) ~env in
let* status = child#status in
Log.info (fun f -> f "Application process ended (%a)" Trace.pp_status status);
Lwt.return (`Ok ())
end
open Cmdliner
let x_display =
Arg.value @@
Arg.(opt (some int)) None @@
Arg.info
~doc:"Number of X display to listen on (e.g. 2 for DISPLAY=:2)"
["x-display"]
let wayland_display =
Arg.value @@
Arg.(opt string) "wayland-1" @@
Arg.info
~doc:"Name or path of socket to listen on"
["wayland-display"]
let virtio_gpu =
Arg.value @@
Arg.flag @@
Arg.info
~doc:"Use virtio-gpu to connect to compositor on host"
["virtio-gpu"]
let args =
Arg.value @@
Arg.(pos_all string) [] @@
Arg.info
~doc:"Sub-command to execute"
[]
let virtwl_proxy =
let info = Cmd.info "wayland-proxy-virtwl" in
Cmd.v info Term.(ret (const main $ Trace.cmdliner $ virtio_gpu $ wayland_display $ x_display $ Config.cmdliner $ args))
let () =
exit @@ Cmd.eval virtwl_proxy
| null | https://raw.githubusercontent.com/talex5/wayland-proxy-virtwl/6b786639747a0720cc774334a18a81a857641d55/main.ml | ocaml | Start listening for connections to [wayland_display].
Start listening for connections to [x_display] and set $DISPLAY.
Listen for incoming X11 client connections, if configured:
Run the application (if any), or just wait (if not): | open Lwt.Syntax
open Lwt.Infix
let ( let*! ) x f =
x >>= function
| `Ok x -> f x
| `Error _ as e -> Lwt.return e
let rec listen ~config ~virtio_gpu socket =
let* (client, _addr) = Lwt_unix.accept socket in
Lwt_unix.set_close_on_exec client;
Log.info (fun f -> f "New connection");
Lwt.async (fun () ->
Lwt.finalize
(fun () ->
let* r = Relay.create ?virtio_gpu config in
Relay.accept r client
)
(fun () ->
Lwt_unix.close client
)
);
listen ~config ~virtio_gpu socket
Connect to socket at [ path ] ( and then close it ) , to see if anyone 's already listening there .
let is_listening path =
let s = Unix.(socket PF_UNIX SOCK_STREAM 0) in
Fun.protect ~finally:(fun () -> Unix.close s) @@ fun () ->
match Unix.connect s (Unix.ADDR_UNIX path) with
| () -> true
| exception Unix.Unix_error(Unix.ECONNREFUSED, _, _) -> false
| exception ex ->
Log.warn (fun f -> f "Error testing socket %S: %a" path Fmt.exn ex);
false
let listen_wayland ~config ~virtio_gpu wayland_display =
let socket_path = Wayland.Unix_transport.socket_path ~wayland_display () in
let existing_socket = Sys.file_exists socket_path in
if existing_socket && is_listening socket_path then (
Lwt.return (`Error (false, Fmt.str "A server is already listening on %S!" socket_path))
) else (
if existing_socket then Unix.unlink socket_path;
let listening_socket = Unix.(socket PF_UNIX SOCK_STREAM 0) in
Unix.set_close_on_exec listening_socket;
Unix.bind listening_socket (Unix.ADDR_UNIX socket_path);
Unix.listen listening_socket 5;
Log.info (fun f -> f "Listening on %S for Wayland clients" socket_path);
Lwt.async (fun () -> listen ~config ~virtio_gpu (Lwt_unix.of_unix_file_descr listening_socket));
Lwt.return (`Ok ())
)
let listen_x11 ~config ~virtio_gpu x_display =
let xwayland_listening_socket =
let path = Printf.sprintf "\x00/tmp/.X11-unix/X%d" x_display in
let sock = Unix.(socket PF_UNIX SOCK_STREAM 0) in
Unix.set_close_on_exec sock;
Unix.bind sock (Unix.ADDR_UNIX path);
Unix.listen sock 5;
Log.info (fun f -> f "Listening on %S for X clients" path);
sock
in
Lwt.async (fun () -> Xwayland.listen ~config ~virtio_gpu ~display:x_display (Lwt_unix.of_unix_file_descr xwayland_listening_socket));
Unix.putenv "DISPLAY" (Printf.sprintf ":%d" x_display)
let env_replace k v l =
let prefix = k ^ "=" in
(prefix ^ v) :: List.filter (fun x -> not (Config.starts_with ~prefix x)) l
let main setup_tracing use_virtio_gpu wayland_display x_display config args =
Lwt_main.run begin
let* virtio_gpu =
if use_virtio_gpu then
Virtio_gpu.find_device () >|= function
| Ok x -> Some x
| Error (`Msg m) ->
Fmt.epr "No virtio-gpu device: %s@." m;
exit 1
else Lwt.return_none
in
let* () = setup_tracing ~wayland_display in
Listen for incoming Wayland client connections :
let*! () = listen_wayland ~config ~virtio_gpu wayland_display in
Option.iter (listen_x11 ~config ~virtio_gpu) x_display;
match args with
| [] ->
fst (Lwt.wait ())
| args ->
let env =
Unix.environment ()
|> Array.to_list
|> env_replace "WAYLAND_DISPLAY" wayland_display
|> Array.of_list
in
let child = Lwt_process.open_process_none ("", Array.of_list args) ~env in
let* status = child#status in
Log.info (fun f -> f "Application process ended (%a)" Trace.pp_status status);
Lwt.return (`Ok ())
end
open Cmdliner
let x_display =
Arg.value @@
Arg.(opt (some int)) None @@
Arg.info
~doc:"Number of X display to listen on (e.g. 2 for DISPLAY=:2)"
["x-display"]
let wayland_display =
Arg.value @@
Arg.(opt string) "wayland-1" @@
Arg.info
~doc:"Name or path of socket to listen on"
["wayland-display"]
let virtio_gpu =
Arg.value @@
Arg.flag @@
Arg.info
~doc:"Use virtio-gpu to connect to compositor on host"
["virtio-gpu"]
let args =
Arg.value @@
Arg.(pos_all string) [] @@
Arg.info
~doc:"Sub-command to execute"
[]
let virtwl_proxy =
let info = Cmd.info "wayland-proxy-virtwl" in
Cmd.v info Term.(ret (const main $ Trace.cmdliner $ virtio_gpu $ wayland_display $ x_display $ Config.cmdliner $ args))
let () =
exit @@ Cmd.eval virtwl_proxy
|
13a3cc00f197915cd7889864bb3988da0407f51a887d43a5cc66760e39460238 | r0man/sqlingvo.node | async_test.cljs | (ns sqlingvo.node.async-test
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [cljs.core.async :as async]
[clojure.pprint :refer [pprint]]
[clojure.string :as str]
[clojure.test :refer [async deftest is testing]]
[sqlingvo.core :as sql]
[sqlingvo.node.async :as node :refer-macros [<? <!?]]))
(defn underscore [s]
(str/replace (name s) "-" "_"))
(defn hypenate [s]
(str/replace (name s) "_" "-"))
(def db (node/db "postgresql:scotch@localhost/sqlingvo_node"
{:sql-name underscore
:sql-identifier hypenate}))
(deftest test-db-spec
(is (fn? (:sql-name db)))
(is (fn? (:sql-identifier db))))
(def country-data
[{:code "de" :name "Germany"}
{:code "es" :name "Spain"}])
(defn create-countries
"Create the countries table."
[db]
(sql/create-table db :countries
(sql/column :id :serial :primary-key? true)
(sql/column :name :text :unique? true)
(sql/column :code :text)))
(defn drop-countries
"Drop the countries table."
[db]
(sql/drop-table
db [:countries]
(sql/if-exists true)))
(defn insert-countries
"Drop the countries table."
[db]
(sql/insert db :countries []
(sql/values country-data)
(sql/returning :*)))
(defn countries
"Return all countries."
[db]
(sql/select db [:*]
(sql/from :countries)))
(deftest test-connect
(async done
(go (try
(let [db (<? (node/connect db))]
(is (:connection db))
(node/disconnect db)
(done))
(catch js/Error e
(prn (prn (.-stack e))))))))
(deftest test-connect-error
(async done
(go (try [db (<? (node/connect (node/db "postgresql")))]
(assert false "Connection error expected.")
(catch js/Error e
(let [message (str/replace (.-message e) #"\n" "")]
(is (re-matches #".*does not exist.*" message))))
(finally (done))))))
(deftest test-disconnect
(async done
(go (let [db (node/disconnect (<? (node/connect db)))]
(is (nil? (:connection db)))
(done)))))
(deftest test-run-queries
(async done
(go (let [db (<? (node/connect db))
_ (<!? (drop-countries db))
_ (<!? (create-countries db))]
(is (= (<!? (insert-countries db))
(<!? (countries db))))
_ (<!? (drop-countries db))
(done)))))
(def pg-statisticts
{:commit-action nil,
:reference-generation nil,
:is-typed "NO",
:is-insertable-into "YES",
:table-catalog "sqlingvo_node",
:user-defined-type-schema nil,
:user-defined-type-name nil,
:user-defined-type-catalog nil,
:table-schema "pg_catalog",
:self-referencing-column-name nil,
:table-name "pg_statistic",
:table-type "BASE TABLE"})
(defn- select-pg-statisticts [db]
(sql/select db [:*]
(sql/from :information_schema.tables)
(sql/where '(= :table_name "pg_statistic"))))
(deftest test-hyphenate
(async done
(go (let [db (<? (node/connect db))]
(is (= (<!? (select-pg-statisticts db))
[pg-statisticts]))
(<? (node/disconnect db))
(done)))))
(deftest test-pool
(async done
(go (let [db (node/start db)]
(is (:pool db))
(is (= (.-totalCount (:pool db)) 0))
(testing "use first available client"
(is (= (<!? (select-pg-statisticts db))
[pg-statisticts])))
(testing "connect client and release"
(let [db (<? (node/connect db))]
(is (:connection db))
(is (= (.-totalCount (:pool db)) 1))
(is (= (<!? (select-pg-statisticts db))
[pg-statisticts]))
(let [db (<? (node/disconnect db))]
(is (nil? (:connection db)))
(let [db (<? (node/stop db))]
(is (nil? (:pool db)))
(done)))))))))
| null | https://raw.githubusercontent.com/r0man/sqlingvo.node/ccb9784f895c7c6fc781c3174b1826cad29ab572/test/sqlingvo/node/async_test.cljs | clojure | (ns sqlingvo.node.async-test
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [cljs.core.async :as async]
[clojure.pprint :refer [pprint]]
[clojure.string :as str]
[clojure.test :refer [async deftest is testing]]
[sqlingvo.core :as sql]
[sqlingvo.node.async :as node :refer-macros [<? <!?]]))
(defn underscore [s]
(str/replace (name s) "-" "_"))
(defn hypenate [s]
(str/replace (name s) "_" "-"))
(def db (node/db "postgresql:scotch@localhost/sqlingvo_node"
{:sql-name underscore
:sql-identifier hypenate}))
(deftest test-db-spec
(is (fn? (:sql-name db)))
(is (fn? (:sql-identifier db))))
(def country-data
[{:code "de" :name "Germany"}
{:code "es" :name "Spain"}])
(defn create-countries
"Create the countries table."
[db]
(sql/create-table db :countries
(sql/column :id :serial :primary-key? true)
(sql/column :name :text :unique? true)
(sql/column :code :text)))
(defn drop-countries
"Drop the countries table."
[db]
(sql/drop-table
db [:countries]
(sql/if-exists true)))
(defn insert-countries
"Drop the countries table."
[db]
(sql/insert db :countries []
(sql/values country-data)
(sql/returning :*)))
(defn countries
"Return all countries."
[db]
(sql/select db [:*]
(sql/from :countries)))
(deftest test-connect
(async done
(go (try
(let [db (<? (node/connect db))]
(is (:connection db))
(node/disconnect db)
(done))
(catch js/Error e
(prn (prn (.-stack e))))))))
(deftest test-connect-error
(async done
(go (try [db (<? (node/connect (node/db "postgresql")))]
(assert false "Connection error expected.")
(catch js/Error e
(let [message (str/replace (.-message e) #"\n" "")]
(is (re-matches #".*does not exist.*" message))))
(finally (done))))))
(deftest test-disconnect
(async done
(go (let [db (node/disconnect (<? (node/connect db)))]
(is (nil? (:connection db)))
(done)))))
(deftest test-run-queries
(async done
(go (let [db (<? (node/connect db))
_ (<!? (drop-countries db))
_ (<!? (create-countries db))]
(is (= (<!? (insert-countries db))
(<!? (countries db))))
_ (<!? (drop-countries db))
(done)))))
(def pg-statisticts
{:commit-action nil,
:reference-generation nil,
:is-typed "NO",
:is-insertable-into "YES",
:table-catalog "sqlingvo_node",
:user-defined-type-schema nil,
:user-defined-type-name nil,
:user-defined-type-catalog nil,
:table-schema "pg_catalog",
:self-referencing-column-name nil,
:table-name "pg_statistic",
:table-type "BASE TABLE"})
(defn- select-pg-statisticts [db]
(sql/select db [:*]
(sql/from :information_schema.tables)
(sql/where '(= :table_name "pg_statistic"))))
(deftest test-hyphenate
(async done
(go (let [db (<? (node/connect db))]
(is (= (<!? (select-pg-statisticts db))
[pg-statisticts]))
(<? (node/disconnect db))
(done)))))
(deftest test-pool
(async done
(go (let [db (node/start db)]
(is (:pool db))
(is (= (.-totalCount (:pool db)) 0))
(testing "use first available client"
(is (= (<!? (select-pg-statisticts db))
[pg-statisticts])))
(testing "connect client and release"
(let [db (<? (node/connect db))]
(is (:connection db))
(is (= (.-totalCount (:pool db)) 1))
(is (= (<!? (select-pg-statisticts db))
[pg-statisticts]))
(let [db (<? (node/disconnect db))]
(is (nil? (:connection db)))
(let [db (<? (node/stop db))]
(is (nil? (:pool db)))
(done)))))))))
|
|
185081447ca2da81c0c14b09fef47ff3ad2b4e933fe1e29678c390fed0d07554 | inria-parkas/sundialsml | cvode.ml | (***********************************************************************)
(* *)
(* OCaml interface to Sundials *)
(* *)
( ) , ( ) , and ( LIENS )
(* *)
Copyright 2014 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
(* under a New BSD License, refer to the file LICENSE. *)
(* *)
(***********************************************************************)
open Sundials
include Cvode_impl
* NB : The order of variant constructors and record fields is important !
* If these types are changed or augmented , the corresponding declarations
* in cvode_serial.h ( and code in cvode_serial.c ) must also be updated .
* NB: The order of variant constructors and record fields is important!
* If these types are changed or augmented, the corresponding declarations
* in cvode_serial.h (and code in cvode_serial.c) must also be updated.
*)
(* Solver exceptions *)
exception IllInput
exception TooClose
exception TooMuchWork
exception TooMuchAccuracy
exception ErrFailure
exception ConvergenceFailure
exception LinearInitFailure
exception LinearSetupFailure of exn option
exception LinearSolveFailure of exn option
exception NonlinearSolverFailure
exception NonlinearInitFailure
exception NonlinearSetupFailure
exception RhsFuncFailure
exception FirstRhsFuncFailure
exception RepeatedRhsFuncFailure
exception UnrecoverableRhsFuncFailure
exception RootFuncFailure
exception ConstraintFailure
(* get_dky exceptions *)
exception BadK
exception BadT
exception VectorOpErr
exception ProjFuncFailure
exception RepeatedProjFuncError
exception ProjectionNotEnabled
let no_roots = (0, dummy_rootsfn)
type lmm =
| Adams
| BDF
synchronized with cvode_ml.h : cvode_integrator_stats_index
type integrator_stats = {
num_steps : int;
num_rhs_evals : int;
num_lin_solv_setups : int;
num_err_test_fails : int;
last_order : int;
current_order : int;
actual_init_step : float;
last_step : float;
current_step : float;
current_time : float
}
synchronized with cvode_ml.h : cvode_linear_solver_stats_index
type linear_solver_stats = {
jac_evals : int;
lin_rhs_evals : int;
lin_iters : int;
lin_conv_fails : int;
prec_evals : int;
prec_solves : int;
jtsetup_evals : int;
jtimes_evals : int;
}
external c_root_init : ('a, 'k) session -> int -> unit
= "sunml_cvode_root_init"
let root_init session (nroots, rootsfn) =
c_root_init session nroots;
session.rootsfn <- rootsfn
4.0.0 < = Sundials
external c_set_linear_solver
: ('d, 'k) session
-> ('m, 'd, 'k) LSI.cptr
-> ('mk, 'm, 'd, 'k) Matrix.t option
-> bool
-> bool
-> unit
= "sunml_cvode_set_linear_solver"
module Diag = struct (* {{{ *)
external sunml_cvode_diag : ('a, 'k) session -> unit
= "sunml_cvode_diag"
let solver session _ =
sunml_cvode_diag session;
session.ls_precfns <- NoPrecFns;
session.ls_callbacks <- DiagNoCallbacks
external get_work_space : ('a, 'k) session -> int * int
= "sunml_cvode_diag_get_work_space"
let get_work_space s =
ls_check_diag s;
get_work_space s
external get_num_rhs_evals : ('a, 'k) session -> int
= "sunml_cvode_diag_get_num_rhs_evals"
let get_num_rhs_evals s =
ls_check_diag s;
get_num_rhs_evals s
end (* }}} *)
module Dls = struct (* {{{ *)
include DirectTypes
include LinearSolver.Direct
Sundials < 3.0.0
external c_dls_dense : 'k serial_session -> int -> bool -> unit
= "sunml_cvode_dls_dense"
Sundials < 3.0.0
external c_dls_lapack_dense : 'k serial_session -> int -> bool -> unit
= "sunml_cvode_dls_lapack_dense"
Sundials < 3.0.0
external c_dls_band : 'k serial_session -> int -> int -> int -> bool -> unit
= "sunml_cvode_dls_band"
Sundials < 3.0.0
external c_dls_lapack_band
: 'k serial_session -> int -> int -> int -> bool -> unit
= "sunml_cvode_dls_lapack_band"
Sundials < 3.0.0
external c_klu
: 'k serial_session -> 's Matrix.Sparse.sformat -> int -> int -> unit
= "sunml_cvode_klu_init"
Sundials < 3.0.0
external c_klu_set_ordering
: 'k serial_session -> LinearSolver.Direct.Klu.ordering -> unit
= "sunml_cvode_klu_set_ordering"
Sundials < 3.0.0
external c_klu_reinit : 'k serial_session -> int -> int -> unit
= "sunml_cvode_klu_reinit"
Sundials < 3.0.0
external c_superlumt
: 'k serial_session -> int -> int -> int -> unit
= "sunml_cvode_superlumt_init"
Sundials < 3.0.0
external c_superlumt_set_ordering
: 'k serial_session -> LinearSolver.Direct.Superlumt.ordering -> unit
= "sunml_cvode_superlumt_set_ordering"
Sundials < 3.0.0
let klu_set_ordering session ordering =
match session.ls_callbacks with
| SlsKluCallback _ | BSlsKluCallback _ | BSlsKluCallbackSens _ ->
c_klu_set_ordering session ordering
| _ -> ()
Sundials < 3.0.0
let klu_reinit session n onnz =
match session.ls_callbacks with
| SlsKluCallback _ | BSlsKluCallback _ | BSlsKluCallbackSens _ ->
c_klu_reinit session n (match onnz with None -> 0 | Some nnz -> nnz)
| _ -> ()
Sundials < 3.0.0
let superlumt_set_ordering session ordering =
match session.ls_callbacks with
| SlsSuperlumtCallback _ | BSlsSuperlumtCallback _
| BSlsSuperlumtCallbackSens _ ->
c_superlumt_set_ordering session ordering
| _ -> ()
Sundials < 3.0.0
let make_compat (type s) (type tag) hasjac
(solver_data : (s, 'nd, 'nk, tag) LSI.solver_data)
(mat : ('k, s, 'nd, 'nk) Matrix.t) session =
match solver_data with
| LSI.Dense ->
let m, n = Matrix.(Dense.size (unwrap mat)) in
if m <> n then raise LinearSolver.MatrixNotSquare;
c_dls_dense session m hasjac
| LSI.LapackDense ->
let m, n = Matrix.(Dense.size (unwrap mat)) in
if m <> n then raise LinearSolver.MatrixNotSquare;
c_dls_lapack_dense session m hasjac
| LSI.Band ->
let open Matrix.Band in
let { n; mu; ml } = dims (Matrix.unwrap mat) in
c_dls_band session n mu ml hasjac
| LSI.LapackBand ->
let open Matrix.Band in
let { n; mu; ml } = dims (Matrix.unwrap mat) in
c_dls_lapack_band session n mu ml hasjac
| LSI.Klu sinfo ->
if not Config.klu_enabled
then raise Config.NotImplementedBySundialsVersion;
let smat = Matrix.unwrap mat in
let m, n = Matrix.Sparse.size smat in
let nnz, _ = Matrix.Sparse.dims smat in
if m <> n then raise LinearSolver.MatrixNotSquare;
let open LSI.Klu in
sinfo.set_ordering <- klu_set_ordering session;
sinfo.reinit <- klu_reinit session;
c_klu session (Matrix.Sparse.sformat smat) m nnz;
(match sinfo.ordering with None -> ()
| Some o -> c_klu_set_ordering session o)
| LSI.Superlumt sinfo ->
if not Config.superlumt_enabled
then raise Config.NotImplementedBySundialsVersion;
let smat = Matrix.unwrap mat in
let m, n = Matrix.Sparse.size smat in
let nnz, _ = Matrix.Sparse.dims smat in
if m <> n then raise LinearSolver.MatrixNotSquare;
let open LSI.Superlumt in
sinfo.set_ordering <- superlumt_set_ordering session;
c_superlumt session m nnz sinfo.num_threads;
(match sinfo.ordering with None -> ()
| Some o -> c_superlumt_set_ordering session o)
| _ -> assert false
let check_dqjac (type k m nd nk) jac (mat : (k,m,nd,nk) Matrix.t) =
let open Matrix in
match get_id mat with
| Dense -> ()
| Band -> ()
| _ -> if jac = None then invalid_arg "A Jacobian function is required"
let set_ls_callbacks (type m) (type tag)
?jac ?(linsys : m linsys_fn option)
(solver_data : (m, 'nd, 'nk, tag) LSI.solver_data)
(mat : ('mk, m, 'nd, 'nk) Matrix.t)
session =
let cb = { jacfn = (match jac with None -> no_callback | Some f -> f);
jmat = (None : m option) } in
let ls = match linsys with None -> DirectTypes.no_linsysfn | Some f -> f in
begin match solver_data with
| LSI.Dense ->
session.ls_callbacks <- DlsDenseCallback (cb, ls)
| LSI.LapackDense ->
session.ls_callbacks <- DlsDenseCallback (cb, ls)
| LSI.Band ->
session.ls_callbacks <- DlsBandCallback (cb, ls)
| LSI.LapackBand ->
session.ls_callbacks <- DlsBandCallback (cb, ls)
| LSI.Klu _ ->
if jac = None then invalid_arg "Klu requires Jacobian function";
session.ls_callbacks <- SlsKluCallback (cb, ls)
| LSI.Superlumt _ ->
if jac = None then invalid_arg "Superlumt requires Jacobian function";
session.ls_callbacks <- SlsSuperlumtCallback (cb, ls)
| LSI.Custom _ ->
check_dqjac jac mat;
session.ls_callbacks <- DirectCustomCallback (cb, ls)
| _ -> assert false
end;
session.ls_precfns <- NoPrecFns
3.0.0 < = Sundials < 4.0.0
external c_dls_set_linear_solver
: 'k serial_session
-> ('m, Nvector_serial.data, 'k) LSI.cptr
-> ('mk, 'm, Nvector_serial.data, 'k) Matrix.t
-> bool
-> unit
= "sunml_cvode_dls_set_linear_solver"
let assert_matrix = function
| Some m -> m
| None -> failwith "a direct linear solver is required"
let solver ?jac ?linsys ls session _ =
let LSI.LS ({ LSI.rawptr; LSI.solver; LSI.matrix } as hls) = ls in
let matrix = assert_matrix matrix in
if Sundials_impl.Version.lt500 && linsys <> None
then raise Config.NotImplementedBySundialsVersion;
set_ls_callbacks ?jac ?linsys solver matrix session;
if Sundials_impl.Version.in_compat_mode2
then make_compat (jac <> None) solver matrix session
else if Sundials_impl.Version.in_compat_mode2_3
then c_dls_set_linear_solver session rawptr matrix (jac <> None)
else c_set_linear_solver session rawptr (Some matrix) (jac <> None)
(linsys <> None);
LSI.attach ls;
session.ls_solver <- LSI.HLS hls
Sundials < 3.0.0
let invalidate_callback session =
if Sundials_impl.Version.in_compat_mode2 then
match session.ls_callbacks with
| DlsDenseCallback ({ jmat = Some d } as cb, _) ->
Matrix.Dense.invalidate d;
cb.jmat <- None
| DlsBandCallback ({ jmat = Some d } as cb, _) ->
Matrix.Band.invalidate d;
cb.jmat <- None
| SlsKluCallback ({ jmat = Some d } as cb, _) ->
Matrix.Sparse.invalidate d;
cb.jmat <- None
| SlsSuperlumtCallback ({ jmat = Some d } as cb, _) ->
Matrix.Sparse.invalidate d;
cb.jmat <- None
| _ -> ()
external get_work_space : 'k serial_session -> int * int
= "sunml_cvode_dls_get_work_space"
let get_work_space s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_direct s;
get_work_space s
external c_get_num_jac_evals : 'k serial_session -> int
= "sunml_cvode_get_num_jac_evals"
Sundials < 3.0.0
external c_klu_get_num_jac_evals : 'k serial_session -> int
= "sunml_cvode_klu_get_num_jac_evals"
Sundials < 3.0.0
external c_superlumt_get_num_jac_evals : 'k serial_session -> int
= "sunml_cvode_superlumt_get_num_jac_evals"
let compat_get_num_jac_evals s =
match s.ls_callbacks with
| SlsKluCallback _ | BSlsKluCallback _ | BSlsKluCallbackSens _ ->
c_klu_get_num_jac_evals s
| SlsSuperlumtCallback _ | BSlsSuperlumtCallback _
| BSlsSuperlumtCallbackSens _ -> c_superlumt_get_num_jac_evals s
| _ -> c_get_num_jac_evals s
let get_num_jac_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_direct s;
if Sundials_impl.Version.in_compat_mode2 then compat_get_num_jac_evals s else
c_get_num_jac_evals s
external c_get_num_lin_rhs_evals : 'k serial_session -> int
= "sunml_cvode_dls_get_num_lin_rhs_evals"
let get_num_lin_rhs_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_direct s;
c_get_num_lin_rhs_evals s
end (* }}} *)
module Spils = struct (* {{{ *)
include SpilsTypes
include LinearSolver.Iterative
Sundials < 3.0.0
external c_spgmr
: ('a, 'k) session
-> int -> LinearSolver.Iterative.preconditioning_type -> unit
= "sunml_cvode_spils_spgmr"
Sundials < 3.0.0
external c_spbcgs
: ('a, 'k) session
-> int -> LinearSolver.Iterative.preconditioning_type -> unit
= "sunml_cvode_spils_spbcgs"
Sundials < 3.0.0
external c_sptfqmr
: ('a, 'k) session
-> int -> LinearSolver.Iterative.preconditioning_type -> unit
= "sunml_cvode_spils_sptfqmr"
Sundials < 3.0.0
external c_set_gs_type
: ('a, 'k) session -> LinearSolver.Iterative.gramschmidt_type -> unit
= "sunml_cvode_spils_set_gs_type"
Sundials < 3.0.0
external c_set_maxl : ('a, 'k) session -> int -> unit
= "sunml_cvode_spils_set_maxl"
Sundials < 3.0.0
external c_set_prec_type
: ('a, 'k) session -> LinearSolver.Iterative.preconditioning_type -> unit
= "sunml_cvode_spils_set_prec_type"
let old_set_maxl s maxl =
ls_check_spils s;
c_set_maxl s maxl
let old_set_prec_type s t =
ls_check_spils s;
c_set_prec_type s t
let old_set_gs_type s t =
ls_check_spils s;
c_set_gs_type s t
external c_set_jac_times : ('a, 'k) session -> bool -> bool -> unit
= "sunml_cvode_set_jac_times"
external c_set_jac_times_rhsfn : ('a, 'k) session -> bool -> unit
= "sunml_cvode_set_jac_times_rhsfn"
external c_set_preconditioner
: ('a, 'k) session -> bool -> unit
= "sunml_cvode_set_preconditioner"
Sundials < 4.0.0
external c_spils_set_linear_solver
: ('a, 'k) session -> ('m, 'a, 'k) LSI.cptr -> unit
= "sunml_cvode_spils_set_linear_solver"
let init_preconditioner solve setup session _ =
c_set_preconditioner session (setup <> None);
session.ls_precfns <- PrecFns { prec_solve_fn = solve;
prec_setup_fn = setup }
let prec_none = LSI.Iterative.(PrecNone,
fun session _ -> session.ls_precfns <- NoPrecFns)
let prec_left ?setup solve = LSI.Iterative.(PrecLeft,
init_preconditioner solve setup)
let prec_right ?setup solve = LSI.Iterative.(PrecRight,
init_preconditioner solve setup)
let prec_both ?setup solve = LSI.Iterative.(PrecBoth,
init_preconditioner solve setup)
Sundials < 3.0.0
let make_compat (type tag) compat prec_type
(solver_data : ('s, 'nd, 'nk, tag) LSI.solver_data) session =
let { LSI.Iterative.maxl; LSI.Iterative.gs_type } = compat in
match solver_data with
| LSI.Spgmr ->
c_spgmr session maxl prec_type;
(match gs_type with None -> () | Some t -> c_set_gs_type session t);
LSI.Iterative.(compat.set_gs_type <- old_set_gs_type session);
LSI.Iterative.(compat.set_prec_type <- old_set_prec_type session)
| LSI.Spbcgs ->
c_spbcgs session maxl prec_type;
LSI.Iterative.(compat.set_maxl <- old_set_maxl session);
LSI.Iterative.(compat.set_prec_type <- old_set_prec_type session)
| LSI.Sptfqmr ->
c_sptfqmr session maxl prec_type;
LSI.Iterative.(compat.set_maxl <- old_set_maxl session);
LSI.Iterative.(compat.set_prec_type <- old_set_prec_type session)
| _ -> raise Config.NotImplementedBySundialsVersion
let solver
(LSI.LS ({ LSI.rawptr; LSI.solver; LSI.compat } as hls) as ls)
?jac_times_vec ?jac_times_rhs (prec_type, set_prec) session nv =
let jac_times_setup, jac_times_vec =
match jac_times_vec with
| None -> None, None
| Some _ when jac_times_rhs <> None ->
invalid_arg "cannot pass both jac_times_vec and jac_times_rhs"
| Some (ojts, jtv) -> ojts, Some jtv
in
if Sundials_impl.Version.lt530 && jac_times_rhs <> None
then raise Config.NotImplementedBySundialsVersion;
if Sundials_impl.Version.in_compat_mode2 then begin
if jac_times_setup <> None then
raise Config.NotImplementedBySundialsVersion;
make_compat compat prec_type solver session;
session.ls_solver <- LSI.HLS hls;
set_prec session nv;
session.ls_callbacks <- SpilsCallback1 (jac_times_vec, None);
if jac_times_vec <> None then c_set_jac_times session true false
end else
if Sundials_impl.Version.in_compat_mode2_3
then c_spils_set_linear_solver session rawptr
else c_set_linear_solver session rawptr None false false;
LSI.attach ls;
session.ls_solver <- LSI.HLS hls;
LSI.(impl_set_prec_type rawptr solver prec_type false);
set_prec session nv;
match jac_times_rhs with
| Some jtrhsfn -> begin
session.ls_callbacks <- SpilsCallback2 jtrhsfn;
c_set_jac_times_rhsfn session true
end
| None -> begin
session.ls_callbacks <-
SpilsCallback1 (jac_times_vec, jac_times_setup);
if jac_times_setup <> None || jac_times_vec <> None then
c_set_jac_times session (jac_times_setup <> None)
(jac_times_vec <> None)
end
(* Drop this function? *)
let set_jac_times s ?jac_times_setup f =
if Sundials_impl.Version.in_compat_mode2 && jac_times_setup <> None then
raise Config.NotImplementedBySundialsVersion;
match s.ls_callbacks with
| SpilsCallback1 _ ->
c_set_jac_times s (jac_times_setup <> None) true;
s.ls_callbacks <- SpilsCallback1 (Some f, jac_times_setup)
| _ -> raise LinearSolver.InvalidLinearSolver
(* Drop this function? *)
let clear_jac_times s =
match s.ls_callbacks with
| SpilsCallback1 _ ->
c_set_jac_times s false false;
s.ls_callbacks <- SpilsCallback1 (None, None)
| _ -> raise LinearSolver.InvalidLinearSolver
let set_preconditioner s ?setup solve =
match s.ls_callbacks with
| SpilsCallback1 _ | SpilsCallback2 _ ->
c_set_preconditioner s (setup <> None);
s.ls_precfns <- PrecFns { prec_setup_fn = setup;
prec_solve_fn = solve }
| _ -> raise LinearSolver.InvalidLinearSolver
external set_jac_eval_frequency : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_jac_eval_frequency"
let set_jac_eval_frequency s maxsteps =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
set_jac_eval_frequency s maxsteps
external set_lsetup_frequency : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_lsetup_frequency"
external set_linear_solution_scaling : ('d, 'k) session -> bool -> unit
= "sunml_cvode_set_linear_solution_scaling"
external set_eps_lin : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_eps_lin"
let set_eps_lin s epsl =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
set_eps_lin s epsl
external set_ls_norm_factor : ('d, 'k) session -> float -> unit
= "sunml_cvode_set_ls_norm_factor"
external get_num_lin_iters : ('a, 'k) session -> int
= "sunml_cvode_get_num_lin_iters"
let get_num_lin_iters s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_lin_iters s
external get_num_lin_conv_fails : ('a, 'k) session -> int
= "sunml_cvode_get_num_lin_conv_fails"
let get_num_lin_conv_fails s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_lin_conv_fails s
external get_work_space : ('a, 'k) session -> int * int
= "sunml_cvode_spils_get_work_space"
let get_work_space s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_work_space s
external get_num_prec_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_prec_evals"
let get_num_prec_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_prec_evals s
external get_num_prec_solves : ('a, 'k) session -> int
= "sunml_cvode_get_num_prec_solves"
let get_num_prec_solves s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_prec_solves s
external get_num_jtsetup_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_jtsetup_evals"
let get_num_jtsetup_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_jtsetup_evals s
external get_num_jtimes_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_jtimes_evals"
let get_num_jtimes_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_jtimes_evals s
external get_num_lin_rhs_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_lin_rhs_evals"
let get_num_lin_rhs_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_lin_rhs_evals s
module Banded = struct (* {{{ *)
(* These fields are accessed from cvode_ml.c *)
type bandrange = { mupper : int; mlower : int; }
external c_set_preconditioner
: ('a, 'k) session -> int -> int -> int -> unit
= "sunml_cvode_set_banded_preconditioner"
Note : CVBandPrecInit seems to be designed only to be called on
a fresh spils solver ( i.e. right after CVSpgmr , CVSpbcg , or
) .
In Sundials 2.5.0 and 2.6.2 , calling
CVSpgmr - > CVBandPrecInit - > CVBandPrecInit
triggers a memory leak . Calling CVodeReInit does NOT help .
The only way to prevent leakage is to allocate a fresh spils
instance , thus :
CVSpgmr - > CVBandPrecInit - > CVSpgmr - > CVBandPrecInit .
If you call
CVSpgmr - > - > CVBandPrecInit ,
nothing serious happens , but the memory associated with
CVBandPrecInit wo n't be freed until the spils solver is torn
down . If you call BandPrecInit - > SetPreconditioner - >
BandPrecInit , you also get a memory leak .
( Perhaps set_preconditioner should be hidden too ? In that
case , we should somehow strip set_prec_type of the ability
to change PrecNone to anything else . )
set_jac_times_vec_fn , as well as similar functions for Dls
solvers , are kept because they accept NULL to remove the
callback . This design clearly anticipates being called
multiple times on the same solver instance .
a fresh spils solver (i.e. right after CVSpgmr, CVSpbcg, or
CVSptfqmr).
In Sundials 2.5.0 and 2.6.2, calling
CVSpgmr -> CVBandPrecInit -> CVBandPrecInit
triggers a memory leak. Calling CVodeReInit does NOT help.
The only way to prevent leakage is to allocate a fresh spils
instance, thus:
CVSpgmr -> CVBandPrecInit -> CVSpgmr -> CVBandPrecInit.
If you call
CVSpgmr -> CVSpilsSetPreconditioner -> CVBandPrecInit,
nothing serious happens, but the memory associated with
CVBandPrecInit won't be freed until the spils solver is torn
down. If you call BandPrecInit -> SetPreconditioner ->
BandPrecInit, you also get a memory leak.
(Perhaps set_preconditioner should be hidden too? In that
case, we should somehow strip set_prec_type of the ability
to change PrecNone to anything else.)
set_jac_times_vec_fn, as well as similar functions for Dls
solvers, are kept because they accept NULL to remove the
callback. This design clearly anticipates being called
multiple times on the same solver instance. *)
let init_preconditioner bandrange session nv =
let n = RealArray.length (Nvector.unwrap nv) in
c_set_preconditioner session n bandrange.mupper bandrange.mlower;
session.ls_precfns <- BandedPrecFns
let prec_left bandrange =
LSI.Iterative.(PrecLeft, init_preconditioner bandrange)
let prec_right bandrange =
LSI.Iterative.(PrecRight, init_preconditioner bandrange)
let prec_both bandrange =
LSI.Iterative.(PrecBoth, init_preconditioner bandrange)
external get_work_space : 'k serial_session -> int * int
= "sunml_cvode_bandprec_get_work_space"
let get_work_space s =
ls_check_spils_band s;
get_work_space s
external get_num_rhs_evals : 'k serial_session -> int
= "sunml_cvode_bandprec_get_num_rhs_evals"
let get_num_rhs_evals s =
ls_check_spils_band s;
get_num_rhs_evals s
end (* }}} *)
end (* }}} *)
let matrix_embedded_solver ((LSI.LS ({ LSI.rawptr; _ } as hls)) as ls) session _ =
if Sundials_impl.Version.lt580
then raise Config.NotImplementedBySundialsVersion;
c_set_linear_solver session rawptr None false false;
LSI.attach ls;
session.ls_solver <- LSI.HLS hls
external sv_tolerances : ('a, 'k) session -> float -> ('a, 'k) nvector -> unit
= "sunml_cvode_sv_tolerances"
external ss_tolerances : ('a, 'k) session -> float -> float -> unit
= "sunml_cvode_ss_tolerances"
external wf_tolerances : ('a, 'k) session -> unit
= "sunml_cvode_wf_tolerances"
type ('a, 'k) tolerance =
| SStolerances of float * float
| SVtolerances of float * ('a, 'k) nvector
| WFtolerances of 'a error_weight_fun
let default_tolerances = SStolerances (1.0e-4, 1.0e-8)
let set_tolerances s tol =
match tol with
| SStolerances (rel, abs) -> (s.errw <- dummy_errw; ss_tolerances s rel abs)
| SVtolerances (rel, abs) -> (if Sundials_configuration.safe then s.checkvec abs;
s.errw <- dummy_errw; sv_tolerances s rel abs)
| WFtolerances ferrw -> (s.errw <- ferrw; wf_tolerances s)
external c_session_finalize : ('a, 'kind) session -> unit
= "sunml_cvode_session_finalize"
let session_finalize s =
Dls.invalidate_callback s;
(match s.nls_solver with
| None -> ()
| Some nls -> NLSI.detach nls);
(match s.sensext with
| FwdSensExt { fnls_solver = NLSI.NLS nls } -> NLSI.detach nls
| FwdSensExt { fnls_solver = NLSI.NLS_sens nls } -> NLSI.detach nls
| _ -> ());
c_session_finalize s
Sundials > = 4.0.0
external c_set_nonlinear_solver
: ('d, 'k) session
-> ('d, 'k, ('d, 'k) session, [`Nvec]) NLSI.cptr
-> unit
= "sunml_cvode_set_nonlinear_solver"
external c_init
: ('a, 'k) session Weak.t
-> lmm
-> bool
-> ('a, 'k) Nvector.t
-> float
-> Context.t
-> (cvode_mem * c_weak_ref)
= "sunml_cvode_init_byte"
"sunml_cvode_init"
external c_set_proj_fn : ('d, 'k) session -> unit
= "sunml_cvode_set_proj_fn"
external c_set_nls_rhs_fn : ('d, 'k) session -> unit
= "sunml_cvode_set_nls_rhs_fn"
let init ?context lmm tol
?(nlsolver : ('data, 'kind, ('data, 'kind) session, [`Nvec])
Sundials_NonlinearSolver.t option)
?nlsrhsfn
?lsolver f ?(roots=no_roots)
?projfn t0 y0 =
let (nroots, roots) = roots in
let checkvec = Nvector.check y0 in
if Sundials_configuration.safe && nroots < 0
then invalid_arg "number of root functions is negative";
let weakref = Weak.create 1 in
let iter = match nlsolver with
| None -> true
| Some { NLSI.solver = NLSI.NewtonSolver _ } -> true
| Some _ -> false
in
let hasprojfn, projfn = match projfn with
| None -> false, dummy_projfn
| Some f -> true, f
in
let ctx = Sundials_impl.Context.get context in
let cvode_mem, backref = c_init weakref lmm iter y0 t0 ctx in
(* cvode_mem and backref have to be immediately captured in a session and
associated with the finalizer before we do anything else. *)
let session = {
cvode = cvode_mem;
backref = backref;
nroots = nroots;
checkvec = checkvec;
context = ctx;
exn_temp = None;
rhsfn = f;
rootsfn = roots;
errh = dummy_errh;
errw = dummy_errw;
error_file = None;
projfn = projfn;
monitorfn = dummy_monitorfn;
ls_solver = LSI.NoHLS;
ls_callbacks = NoCallbacks;
ls_precfns = NoPrecFns;
nls_solver = None;
nls_rhsfn = dummy_nlsrhsfn;
sensext = NoSensExt;
} in
Gc.finalise session_finalize session;
Weak.set weakref 0 (Some session);
Now the session is safe to use . If any of the following fails and raises
an exception , the GC will take care of freeing cvode_mem and backref .
an exception, the GC will take care of freeing cvode_mem and backref. *)
if nroots > 0 then
c_root_init session nroots;
set_tolerances session tol;
(match lsolver, nlsolver with
| None, None -> Diag.solver session y0
| None, Some _ -> ()
| Some linsolv, _ -> linsolv session y0);
(match nlsolver with
| Some ({ NLSI.rawptr = nlcptr } as nls)
when not Sundials_impl.Version.in_compat_mode2_3 ->
NLSI.attach nls;
session.nls_solver <- Some nls;
c_set_nonlinear_solver session nlcptr
| _ -> ());
(match nlsrhsfn with
| None -> () | _ when Sundials_impl.Version.lt580 -> ()
| Some f -> session.nls_rhsfn <- f;
c_set_nls_rhs_fn session);
if hasprojfn then c_set_proj_fn session;
session
let get_num_roots { nroots } = nroots
Sundials < 4.0.0
external c_set_functional : ('a, 'k) session -> unit
= "sunml_cvode_set_functional"
Sundials < 4.0.0
external c_set_newton : ('a, 'k) session -> unit
= "sunml_cvode_set_newton"
external c_reinit
: ('a, 'k) session -> float -> ('a, 'k) nvector -> unit
= "sunml_cvode_reinit"
let reinit session ?nlsolver ?nlsrhsfn ?lsolver ?roots ?rhsfn t0 y0 =
if Sundials_configuration.safe then session.checkvec y0;
Dls.invalidate_callback session;
c_reinit session t0 y0;
(match lsolver with
| None -> ()
| Some linsolv -> linsolv session y0);
(if Sundials_impl.Version.in_compat_mode2_3 then
match nlsolver with
| None -> ()
| Some { NLSI.solver = NLSI.FixedPointSolver _ } -> c_set_functional session
| Some _ -> c_set_newton session
else
match nlsolver with
| Some ({ NLSI.rawptr = nlcptr } as nls) ->
(match session.nls_solver with
| None -> () | Some old_nls -> NLSI.detach old_nls);
NLSI.attach nls;
session.nls_solver <- Some nls;
c_set_nonlinear_solver session nlcptr
| _ -> ());
(match nlsrhsfn with
| None -> () | _ when Sundials_impl.Version.lt580 -> ()
| Some f -> session.nls_rhsfn <- f;
c_set_nls_rhs_fn session);
(match roots with
| None -> ()
| Some roots -> root_init session roots);
(match rhsfn with None -> () | Some f -> session.rhsfn <- f)
external get_root_info : ('a, 'k) session -> Roots.t -> unit
= "sunml_cvode_get_root_info"
type solver_result =
| Success (** CV_SUCCESS *)
| RootsFound (** CV_ROOT_RETURN *)
*
external c_solve_normal : ('a, 'k) session -> float -> ('a, 'k) nvector
-> float * solver_result
= "sunml_cvode_solve_normal"
let solve_normal s t y =
if Sundials_configuration.safe then s.checkvec y;
c_solve_normal s t y
external c_solve_one_step : ('a, 'k) session -> float -> ('a, 'k) nvector
-> float * solver_result
= "sunml_cvode_solve_one_step"
let solve_one_step s t y =
if Sundials_configuration.safe then s.checkvec y;
c_solve_one_step s t y
external c_get_dky
: ('a, 'k) session -> float -> int -> ('a, 'k) nvector -> unit
= "sunml_cvode_get_dky"
let get_dky s y =
if Sundials_configuration.safe then s.checkvec y;
fun t k -> c_get_dky s t k y
external get_integrator_stats : ('a, 'k) session -> integrator_stats
= "sunml_cvode_get_integrator_stats"
external get_linear_solver_stats : ('a, 'k) session -> linear_solver_stats
= "sunml_cvode_get_linear_solver_stats"
external get_work_space : ('a, 'k) session -> int * int
= "sunml_cvode_get_work_space"
external get_num_steps : ('a, 'k) session -> int
= "sunml_cvode_get_num_steps"
external get_num_rhs_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_rhs_evals"
external get_num_lin_solv_setups : ('a, 'k) session -> int
= "sunml_cvode_get_num_lin_solv_setups"
external get_num_err_test_fails : ('a, 'k) session -> int
= "sunml_cvode_get_num_err_test_fails"
external get_last_order : ('a, 'k) session -> int
= "sunml_cvode_get_last_order"
external get_current_order : ('a, 'k) session -> int
= "sunml_cvode_get_current_order"
external get_current_state : ('d, 'k) session -> 'd
= "sunml_cvode_get_current_state"
must correspond to cvode_nonlin_system_data_index in cvode_ml.h
type 'd nonlin_system_data = {
tn : float;
ypred : 'd;
yn : 'd;
fn : 'd;
gamma : float;
rl1 : float;
zn1 : 'd;
}
external get_nonlin_system_data
: ('d, 'k) session -> 'd nonlin_system_data
= "sunml_cvode_get_nonlin_system_data"
external compute_state
: ('d, 'k) session
-> ('d, 'k) Nvector.t
-> ('d, 'k) Nvector.t
-> unit
= "sunml_cvode_compute_state"
let compute_state s ycor yn =
if Sundials_configuration.safe then (s.checkvec ycor; s.checkvec yn);
compute_state s ycor yn
external get_current_gamma : ('d, 'k) session -> (float [@unboxed])
= "sunml_cvode_get_current_gamma"
"sunml_cvode_get_current_gamma_unboxed"
(* Could also be [@@noalloc] if it were not for the version check and
possible exception. *)
external get_actual_init_step : ('a, 'k) session -> float
= "sunml_cvode_get_actual_init_step"
external get_last_step : ('a, 'k) session -> float
= "sunml_cvode_get_last_step"
external get_current_step : ('a, 'k) session -> float
= "sunml_cvode_get_current_step"
external get_current_time : ('a, 'k) session -> float
= "sunml_cvode_get_current_time"
let print_integrator_stats s oc =
let stats = get_integrator_stats s
in
Printf.fprintf oc "num_steps = %d\n" stats.num_steps;
Printf.fprintf oc "num_rhs_evals = %d\n" stats.num_rhs_evals;
Printf.fprintf oc "num_lin_solv_setups = %d\n" stats.num_lin_solv_setups;
Printf.fprintf oc "num_err_test_fails = %d\n" stats.num_err_test_fails;
Printf.fprintf oc "last_order = %d\n" stats.last_order;
Printf.fprintf oc "current_order = %d\n" stats.current_order;
Printf.fprintf oc "actual_init_step = %e\n" stats.actual_init_step;
Printf.fprintf oc "last_step = %e\n" stats.last_step;
Printf.fprintf oc "current_step = %e\n" stats.current_step;
Printf.fprintf oc "current_time = %e\n" stats.current_time;
external c_set_error_file : ('a, 'k) session -> Logfile.t -> unit
= "sunml_cvode_set_error_file"
let set_error_file s f =
s.error_file <- Some f;
c_set_error_file s f
external set_err_handler_fn : ('a, 'k) session -> unit
= "sunml_cvode_set_err_handler_fn"
let set_err_handler_fn s ferrh =
s.errh <- ferrh;
set_err_handler_fn s
external clear_err_handler_fn : ('a, 'k) session -> unit
= "sunml_cvode_clear_err_handler_fn"
let clear_err_handler_fn s =
s.errh <- dummy_errh;
clear_err_handler_fn s
external c_set_monitor_fn : ('a, 'k) session -> bool -> unit
= "sunml_cvode_set_monitor_fn"
external c_set_monitor_frequency : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_monitor_frequency"
let set_monitor_fn s freq monitorfn =
if Sundials_configuration.monitoring_enabled then begin
s.monitorfn <- monitorfn;
c_set_monitor_fn s true;
c_set_monitor_frequency s freq
end else raise Config.NotImplementedBySundialsVersion
let set_monitor_frequency s freq =
if Sundials_configuration.monitoring_enabled
then c_set_monitor_frequency s freq
else raise Config.NotImplementedBySundialsVersion
let clear_monitor_fn s =
if Sundials_configuration.monitoring_enabled then begin
c_set_monitor_fn s false;
s.monitorfn <- dummy_monitorfn
end
external set_max_ord : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_ord"
external set_max_num_steps : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_num_steps"
external set_max_hnil_warns : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_hnil_warns"
external set_stab_lim_det : ('a, 'k) session -> bool -> unit
= "sunml_cvode_set_stab_lim_det"
external set_init_step : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_init_step"
external set_min_step : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_min_step"
external set_max_step : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_max_step"
external set_stop_time : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_stop_time"
external set_max_err_test_fails : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_err_test_fails"
external set_max_nonlin_iters : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_nonlin_iters"
external set_max_conv_fails : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_conv_fails"
external set_nonlin_conv_coef : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_nonlin_conv_coef"
external c_set_constraints : ('a,'k) session -> ('a,'k) Nvector.t -> unit
= "sunml_cvode_set_constraints"
external c_clear_constraints : ('a,'k) session -> unit
= "sunml_cvode_clear_constraints"
let set_constraints s nv =
(match Config.sundials_version with
| 2,_,_ | 3,1,_ -> raise Config.NotImplementedBySundialsVersion
| _ -> ());
if Sundials_configuration.safe then s.checkvec nv;
c_set_constraints s nv
let clear_constraints s =
(match Config.sundials_version with
| 2,_,_ | 3,1,_ -> raise Config.NotImplementedBySundialsVersion
| _ -> ());
c_clear_constraints s
external set_proj_err_est : ('d, 'k) session -> bool -> unit
= "sunml_cvode_set_proj_err_est"
external set_proj_frequency : ('d, 'k) session -> int -> unit
= "sunml_cvode_set_proj_frequency"
external set_max_num_proj_fails : ('d, 'k) session -> int -> unit
= "sunml_cvode_set_max_num_proj_fails"
external set_eps_proj : ('d, 'k) session -> float -> unit
= "sunml_cvode_set_eps_proj"
external set_proj_fail_eta : ('d, 'k) session -> float -> unit
= "sunml_cvode_set_proj_fail_eta"
external get_num_proj_evals : ('d, 'k) session -> int
= "sunml_cvode_get_num_proj_evals"
external get_num_proj_fails : ('d, 'k) session -> int
= "sunml_cvode_get_num_proj_fails"
external set_root_direction' : ('a, 'k) session -> RootDirs.t -> unit
= "sunml_cvode_set_root_direction"
let set_root_direction s rda =
set_root_direction' s (RootDirs.copy (get_num_roots s) rda)
let set_all_root_directions s rd =
set_root_direction' s (RootDirs.make (get_num_roots s) rd)
external set_no_inactive_root_warn : ('a, 'k) session -> unit
= "sunml_cvode_set_no_inactive_root_warn"
external get_num_stab_lim_order_reds : ('a, 'k) session -> int
= "sunml_cvode_get_num_stab_lim_order_reds"
external get_tol_scale_factor : ('a, 'k) session -> float
= "sunml_cvode_get_tol_scale_factor"
external c_get_err_weights : ('a, 'k) session -> ('a, 'k) nvector -> unit
= "sunml_cvode_get_err_weights"
let get_err_weights s ew =
if Sundials_configuration.safe then s.checkvec ew;
c_get_err_weights s ew
external c_get_est_local_errors : ('a, 'k) session -> ('a, 'k) nvector -> unit
= "sunml_cvode_get_est_local_errors"
let get_est_local_errors s ew =
if Sundials_configuration.safe then s.checkvec ew;
c_get_est_local_errors s ew
external get_num_nonlin_solv_iters : ('a, 'k) session -> int
= "sunml_cvode_get_num_nonlin_solv_iters"
external get_num_nonlin_solv_conv_fails : ('a, 'k) session -> int
= "sunml_cvode_get_num_nonlin_solv_conv_fails"
external get_nonlin_solv_stats : ('a, 'k) session -> int * int
= "sunml_cvode_get_nonlin_solv_stats"
external get_num_g_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_g_evals"
(* Let C code know about some of the values in this module. *)
external c_init_module : exn array -> unit =
"sunml_cvode_init_module"
let _ =
c_init_module
(* Exceptions must be listed in the same order as
cvode_exn_index. *)
[|IllInput;
TooClose;
TooMuchWork;
TooMuchAccuracy;
ErrFailure;
ConvergenceFailure;
LinearInitFailure;
LinearSetupFailure None;
LinearSolveFailure None;
NonlinearSolverFailure;
NonlinearInitFailure;
NonlinearSetupFailure;
RhsFuncFailure;
FirstRhsFuncFailure;
RepeatedRhsFuncFailure;
UnrecoverableRhsFuncFailure;
RootFuncFailure;
ConstraintFailure;
BadK;
BadT;
VectorOpErr;
ProjFuncFailure;
RepeatedProjFuncError;
ProjectionNotEnabled;
|]
| null | https://raw.githubusercontent.com/inria-parkas/sundialsml/a72ebfc84b55470ed97fbb0b45d700deebfc1664/src/cvode/cvode.ml | ocaml | *********************************************************************
OCaml interface to Sundials
under a New BSD License, refer to the file LICENSE.
*********************************************************************
Solver exceptions
get_dky exceptions
{{{
}}}
{{{
}}}
{{{
Drop this function?
Drop this function?
{{{
These fields are accessed from cvode_ml.c
}}}
}}}
cvode_mem and backref have to be immediately captured in a session and
associated with the finalizer before we do anything else.
* CV_SUCCESS
* CV_ROOT_RETURN
Could also be [@@noalloc] if it were not for the version check and
possible exception.
Let C code know about some of the values in this module.
Exceptions must be listed in the same order as
cvode_exn_index. | ( ) , ( ) , and ( LIENS )
Copyright 2014 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
open Sundials
include Cvode_impl
* NB : The order of variant constructors and record fields is important !
* If these types are changed or augmented , the corresponding declarations
* in cvode_serial.h ( and code in cvode_serial.c ) must also be updated .
* NB: The order of variant constructors and record fields is important!
* If these types are changed or augmented, the corresponding declarations
* in cvode_serial.h (and code in cvode_serial.c) must also be updated.
*)
exception IllInput
exception TooClose
exception TooMuchWork
exception TooMuchAccuracy
exception ErrFailure
exception ConvergenceFailure
exception LinearInitFailure
exception LinearSetupFailure of exn option
exception LinearSolveFailure of exn option
exception NonlinearSolverFailure
exception NonlinearInitFailure
exception NonlinearSetupFailure
exception RhsFuncFailure
exception FirstRhsFuncFailure
exception RepeatedRhsFuncFailure
exception UnrecoverableRhsFuncFailure
exception RootFuncFailure
exception ConstraintFailure
exception BadK
exception BadT
exception VectorOpErr
exception ProjFuncFailure
exception RepeatedProjFuncError
exception ProjectionNotEnabled
let no_roots = (0, dummy_rootsfn)
type lmm =
| Adams
| BDF
synchronized with cvode_ml.h : cvode_integrator_stats_index
type integrator_stats = {
num_steps : int;
num_rhs_evals : int;
num_lin_solv_setups : int;
num_err_test_fails : int;
last_order : int;
current_order : int;
actual_init_step : float;
last_step : float;
current_step : float;
current_time : float
}
synchronized with cvode_ml.h : cvode_linear_solver_stats_index
type linear_solver_stats = {
jac_evals : int;
lin_rhs_evals : int;
lin_iters : int;
lin_conv_fails : int;
prec_evals : int;
prec_solves : int;
jtsetup_evals : int;
jtimes_evals : int;
}
external c_root_init : ('a, 'k) session -> int -> unit
= "sunml_cvode_root_init"
let root_init session (nroots, rootsfn) =
c_root_init session nroots;
session.rootsfn <- rootsfn
4.0.0 < = Sundials
external c_set_linear_solver
: ('d, 'k) session
-> ('m, 'd, 'k) LSI.cptr
-> ('mk, 'm, 'd, 'k) Matrix.t option
-> bool
-> bool
-> unit
= "sunml_cvode_set_linear_solver"
external sunml_cvode_diag : ('a, 'k) session -> unit
= "sunml_cvode_diag"
let solver session _ =
sunml_cvode_diag session;
session.ls_precfns <- NoPrecFns;
session.ls_callbacks <- DiagNoCallbacks
external get_work_space : ('a, 'k) session -> int * int
= "sunml_cvode_diag_get_work_space"
let get_work_space s =
ls_check_diag s;
get_work_space s
external get_num_rhs_evals : ('a, 'k) session -> int
= "sunml_cvode_diag_get_num_rhs_evals"
let get_num_rhs_evals s =
ls_check_diag s;
get_num_rhs_evals s
include DirectTypes
include LinearSolver.Direct
Sundials < 3.0.0
external c_dls_dense : 'k serial_session -> int -> bool -> unit
= "sunml_cvode_dls_dense"
Sundials < 3.0.0
external c_dls_lapack_dense : 'k serial_session -> int -> bool -> unit
= "sunml_cvode_dls_lapack_dense"
Sundials < 3.0.0
external c_dls_band : 'k serial_session -> int -> int -> int -> bool -> unit
= "sunml_cvode_dls_band"
Sundials < 3.0.0
external c_dls_lapack_band
: 'k serial_session -> int -> int -> int -> bool -> unit
= "sunml_cvode_dls_lapack_band"
Sundials < 3.0.0
external c_klu
: 'k serial_session -> 's Matrix.Sparse.sformat -> int -> int -> unit
= "sunml_cvode_klu_init"
Sundials < 3.0.0
external c_klu_set_ordering
: 'k serial_session -> LinearSolver.Direct.Klu.ordering -> unit
= "sunml_cvode_klu_set_ordering"
Sundials < 3.0.0
external c_klu_reinit : 'k serial_session -> int -> int -> unit
= "sunml_cvode_klu_reinit"
Sundials < 3.0.0
external c_superlumt
: 'k serial_session -> int -> int -> int -> unit
= "sunml_cvode_superlumt_init"
Sundials < 3.0.0
external c_superlumt_set_ordering
: 'k serial_session -> LinearSolver.Direct.Superlumt.ordering -> unit
= "sunml_cvode_superlumt_set_ordering"
Sundials < 3.0.0
let klu_set_ordering session ordering =
match session.ls_callbacks with
| SlsKluCallback _ | BSlsKluCallback _ | BSlsKluCallbackSens _ ->
c_klu_set_ordering session ordering
| _ -> ()
Sundials < 3.0.0
let klu_reinit session n onnz =
match session.ls_callbacks with
| SlsKluCallback _ | BSlsKluCallback _ | BSlsKluCallbackSens _ ->
c_klu_reinit session n (match onnz with None -> 0 | Some nnz -> nnz)
| _ -> ()
Sundials < 3.0.0
let superlumt_set_ordering session ordering =
match session.ls_callbacks with
| SlsSuperlumtCallback _ | BSlsSuperlumtCallback _
| BSlsSuperlumtCallbackSens _ ->
c_superlumt_set_ordering session ordering
| _ -> ()
Sundials < 3.0.0
let make_compat (type s) (type tag) hasjac
(solver_data : (s, 'nd, 'nk, tag) LSI.solver_data)
(mat : ('k, s, 'nd, 'nk) Matrix.t) session =
match solver_data with
| LSI.Dense ->
let m, n = Matrix.(Dense.size (unwrap mat)) in
if m <> n then raise LinearSolver.MatrixNotSquare;
c_dls_dense session m hasjac
| LSI.LapackDense ->
let m, n = Matrix.(Dense.size (unwrap mat)) in
if m <> n then raise LinearSolver.MatrixNotSquare;
c_dls_lapack_dense session m hasjac
| LSI.Band ->
let open Matrix.Band in
let { n; mu; ml } = dims (Matrix.unwrap mat) in
c_dls_band session n mu ml hasjac
| LSI.LapackBand ->
let open Matrix.Band in
let { n; mu; ml } = dims (Matrix.unwrap mat) in
c_dls_lapack_band session n mu ml hasjac
| LSI.Klu sinfo ->
if not Config.klu_enabled
then raise Config.NotImplementedBySundialsVersion;
let smat = Matrix.unwrap mat in
let m, n = Matrix.Sparse.size smat in
let nnz, _ = Matrix.Sparse.dims smat in
if m <> n then raise LinearSolver.MatrixNotSquare;
let open LSI.Klu in
sinfo.set_ordering <- klu_set_ordering session;
sinfo.reinit <- klu_reinit session;
c_klu session (Matrix.Sparse.sformat smat) m nnz;
(match sinfo.ordering with None -> ()
| Some o -> c_klu_set_ordering session o)
| LSI.Superlumt sinfo ->
if not Config.superlumt_enabled
then raise Config.NotImplementedBySundialsVersion;
let smat = Matrix.unwrap mat in
let m, n = Matrix.Sparse.size smat in
let nnz, _ = Matrix.Sparse.dims smat in
if m <> n then raise LinearSolver.MatrixNotSquare;
let open LSI.Superlumt in
sinfo.set_ordering <- superlumt_set_ordering session;
c_superlumt session m nnz sinfo.num_threads;
(match sinfo.ordering with None -> ()
| Some o -> c_superlumt_set_ordering session o)
| _ -> assert false
let check_dqjac (type k m nd nk) jac (mat : (k,m,nd,nk) Matrix.t) =
let open Matrix in
match get_id mat with
| Dense -> ()
| Band -> ()
| _ -> if jac = None then invalid_arg "A Jacobian function is required"
let set_ls_callbacks (type m) (type tag)
?jac ?(linsys : m linsys_fn option)
(solver_data : (m, 'nd, 'nk, tag) LSI.solver_data)
(mat : ('mk, m, 'nd, 'nk) Matrix.t)
session =
let cb = { jacfn = (match jac with None -> no_callback | Some f -> f);
jmat = (None : m option) } in
let ls = match linsys with None -> DirectTypes.no_linsysfn | Some f -> f in
begin match solver_data with
| LSI.Dense ->
session.ls_callbacks <- DlsDenseCallback (cb, ls)
| LSI.LapackDense ->
session.ls_callbacks <- DlsDenseCallback (cb, ls)
| LSI.Band ->
session.ls_callbacks <- DlsBandCallback (cb, ls)
| LSI.LapackBand ->
session.ls_callbacks <- DlsBandCallback (cb, ls)
| LSI.Klu _ ->
if jac = None then invalid_arg "Klu requires Jacobian function";
session.ls_callbacks <- SlsKluCallback (cb, ls)
| LSI.Superlumt _ ->
if jac = None then invalid_arg "Superlumt requires Jacobian function";
session.ls_callbacks <- SlsSuperlumtCallback (cb, ls)
| LSI.Custom _ ->
check_dqjac jac mat;
session.ls_callbacks <- DirectCustomCallback (cb, ls)
| _ -> assert false
end;
session.ls_precfns <- NoPrecFns
3.0.0 < = Sundials < 4.0.0
external c_dls_set_linear_solver
: 'k serial_session
-> ('m, Nvector_serial.data, 'k) LSI.cptr
-> ('mk, 'm, Nvector_serial.data, 'k) Matrix.t
-> bool
-> unit
= "sunml_cvode_dls_set_linear_solver"
let assert_matrix = function
| Some m -> m
| None -> failwith "a direct linear solver is required"
let solver ?jac ?linsys ls session _ =
let LSI.LS ({ LSI.rawptr; LSI.solver; LSI.matrix } as hls) = ls in
let matrix = assert_matrix matrix in
if Sundials_impl.Version.lt500 && linsys <> None
then raise Config.NotImplementedBySundialsVersion;
set_ls_callbacks ?jac ?linsys solver matrix session;
if Sundials_impl.Version.in_compat_mode2
then make_compat (jac <> None) solver matrix session
else if Sundials_impl.Version.in_compat_mode2_3
then c_dls_set_linear_solver session rawptr matrix (jac <> None)
else c_set_linear_solver session rawptr (Some matrix) (jac <> None)
(linsys <> None);
LSI.attach ls;
session.ls_solver <- LSI.HLS hls
Sundials < 3.0.0
let invalidate_callback session =
if Sundials_impl.Version.in_compat_mode2 then
match session.ls_callbacks with
| DlsDenseCallback ({ jmat = Some d } as cb, _) ->
Matrix.Dense.invalidate d;
cb.jmat <- None
| DlsBandCallback ({ jmat = Some d } as cb, _) ->
Matrix.Band.invalidate d;
cb.jmat <- None
| SlsKluCallback ({ jmat = Some d } as cb, _) ->
Matrix.Sparse.invalidate d;
cb.jmat <- None
| SlsSuperlumtCallback ({ jmat = Some d } as cb, _) ->
Matrix.Sparse.invalidate d;
cb.jmat <- None
| _ -> ()
external get_work_space : 'k serial_session -> int * int
= "sunml_cvode_dls_get_work_space"
let get_work_space s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_direct s;
get_work_space s
external c_get_num_jac_evals : 'k serial_session -> int
= "sunml_cvode_get_num_jac_evals"
Sundials < 3.0.0
external c_klu_get_num_jac_evals : 'k serial_session -> int
= "sunml_cvode_klu_get_num_jac_evals"
Sundials < 3.0.0
external c_superlumt_get_num_jac_evals : 'k serial_session -> int
= "sunml_cvode_superlumt_get_num_jac_evals"
let compat_get_num_jac_evals s =
match s.ls_callbacks with
| SlsKluCallback _ | BSlsKluCallback _ | BSlsKluCallbackSens _ ->
c_klu_get_num_jac_evals s
| SlsSuperlumtCallback _ | BSlsSuperlumtCallback _
| BSlsSuperlumtCallbackSens _ -> c_superlumt_get_num_jac_evals s
| _ -> c_get_num_jac_evals s
let get_num_jac_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_direct s;
if Sundials_impl.Version.in_compat_mode2 then compat_get_num_jac_evals s else
c_get_num_jac_evals s
external c_get_num_lin_rhs_evals : 'k serial_session -> int
= "sunml_cvode_dls_get_num_lin_rhs_evals"
let get_num_lin_rhs_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_direct s;
c_get_num_lin_rhs_evals s
include SpilsTypes
include LinearSolver.Iterative
Sundials < 3.0.0
external c_spgmr
: ('a, 'k) session
-> int -> LinearSolver.Iterative.preconditioning_type -> unit
= "sunml_cvode_spils_spgmr"
Sundials < 3.0.0
external c_spbcgs
: ('a, 'k) session
-> int -> LinearSolver.Iterative.preconditioning_type -> unit
= "sunml_cvode_spils_spbcgs"
Sundials < 3.0.0
external c_sptfqmr
: ('a, 'k) session
-> int -> LinearSolver.Iterative.preconditioning_type -> unit
= "sunml_cvode_spils_sptfqmr"
Sundials < 3.0.0
external c_set_gs_type
: ('a, 'k) session -> LinearSolver.Iterative.gramschmidt_type -> unit
= "sunml_cvode_spils_set_gs_type"
Sundials < 3.0.0
external c_set_maxl : ('a, 'k) session -> int -> unit
= "sunml_cvode_spils_set_maxl"
Sundials < 3.0.0
external c_set_prec_type
: ('a, 'k) session -> LinearSolver.Iterative.preconditioning_type -> unit
= "sunml_cvode_spils_set_prec_type"
let old_set_maxl s maxl =
ls_check_spils s;
c_set_maxl s maxl
let old_set_prec_type s t =
ls_check_spils s;
c_set_prec_type s t
let old_set_gs_type s t =
ls_check_spils s;
c_set_gs_type s t
external c_set_jac_times : ('a, 'k) session -> bool -> bool -> unit
= "sunml_cvode_set_jac_times"
external c_set_jac_times_rhsfn : ('a, 'k) session -> bool -> unit
= "sunml_cvode_set_jac_times_rhsfn"
external c_set_preconditioner
: ('a, 'k) session -> bool -> unit
= "sunml_cvode_set_preconditioner"
Sundials < 4.0.0
external c_spils_set_linear_solver
: ('a, 'k) session -> ('m, 'a, 'k) LSI.cptr -> unit
= "sunml_cvode_spils_set_linear_solver"
let init_preconditioner solve setup session _ =
c_set_preconditioner session (setup <> None);
session.ls_precfns <- PrecFns { prec_solve_fn = solve;
prec_setup_fn = setup }
let prec_none = LSI.Iterative.(PrecNone,
fun session _ -> session.ls_precfns <- NoPrecFns)
let prec_left ?setup solve = LSI.Iterative.(PrecLeft,
init_preconditioner solve setup)
let prec_right ?setup solve = LSI.Iterative.(PrecRight,
init_preconditioner solve setup)
let prec_both ?setup solve = LSI.Iterative.(PrecBoth,
init_preconditioner solve setup)
Sundials < 3.0.0
let make_compat (type tag) compat prec_type
(solver_data : ('s, 'nd, 'nk, tag) LSI.solver_data) session =
let { LSI.Iterative.maxl; LSI.Iterative.gs_type } = compat in
match solver_data with
| LSI.Spgmr ->
c_spgmr session maxl prec_type;
(match gs_type with None -> () | Some t -> c_set_gs_type session t);
LSI.Iterative.(compat.set_gs_type <- old_set_gs_type session);
LSI.Iterative.(compat.set_prec_type <- old_set_prec_type session)
| LSI.Spbcgs ->
c_spbcgs session maxl prec_type;
LSI.Iterative.(compat.set_maxl <- old_set_maxl session);
LSI.Iterative.(compat.set_prec_type <- old_set_prec_type session)
| LSI.Sptfqmr ->
c_sptfqmr session maxl prec_type;
LSI.Iterative.(compat.set_maxl <- old_set_maxl session);
LSI.Iterative.(compat.set_prec_type <- old_set_prec_type session)
| _ -> raise Config.NotImplementedBySundialsVersion
let solver
(LSI.LS ({ LSI.rawptr; LSI.solver; LSI.compat } as hls) as ls)
?jac_times_vec ?jac_times_rhs (prec_type, set_prec) session nv =
let jac_times_setup, jac_times_vec =
match jac_times_vec with
| None -> None, None
| Some _ when jac_times_rhs <> None ->
invalid_arg "cannot pass both jac_times_vec and jac_times_rhs"
| Some (ojts, jtv) -> ojts, Some jtv
in
if Sundials_impl.Version.lt530 && jac_times_rhs <> None
then raise Config.NotImplementedBySundialsVersion;
if Sundials_impl.Version.in_compat_mode2 then begin
if jac_times_setup <> None then
raise Config.NotImplementedBySundialsVersion;
make_compat compat prec_type solver session;
session.ls_solver <- LSI.HLS hls;
set_prec session nv;
session.ls_callbacks <- SpilsCallback1 (jac_times_vec, None);
if jac_times_vec <> None then c_set_jac_times session true false
end else
if Sundials_impl.Version.in_compat_mode2_3
then c_spils_set_linear_solver session rawptr
else c_set_linear_solver session rawptr None false false;
LSI.attach ls;
session.ls_solver <- LSI.HLS hls;
LSI.(impl_set_prec_type rawptr solver prec_type false);
set_prec session nv;
match jac_times_rhs with
| Some jtrhsfn -> begin
session.ls_callbacks <- SpilsCallback2 jtrhsfn;
c_set_jac_times_rhsfn session true
end
| None -> begin
session.ls_callbacks <-
SpilsCallback1 (jac_times_vec, jac_times_setup);
if jac_times_setup <> None || jac_times_vec <> None then
c_set_jac_times session (jac_times_setup <> None)
(jac_times_vec <> None)
end
let set_jac_times s ?jac_times_setup f =
if Sundials_impl.Version.in_compat_mode2 && jac_times_setup <> None then
raise Config.NotImplementedBySundialsVersion;
match s.ls_callbacks with
| SpilsCallback1 _ ->
c_set_jac_times s (jac_times_setup <> None) true;
s.ls_callbacks <- SpilsCallback1 (Some f, jac_times_setup)
| _ -> raise LinearSolver.InvalidLinearSolver
let clear_jac_times s =
match s.ls_callbacks with
| SpilsCallback1 _ ->
c_set_jac_times s false false;
s.ls_callbacks <- SpilsCallback1 (None, None)
| _ -> raise LinearSolver.InvalidLinearSolver
let set_preconditioner s ?setup solve =
match s.ls_callbacks with
| SpilsCallback1 _ | SpilsCallback2 _ ->
c_set_preconditioner s (setup <> None);
s.ls_precfns <- PrecFns { prec_setup_fn = setup;
prec_solve_fn = solve }
| _ -> raise LinearSolver.InvalidLinearSolver
external set_jac_eval_frequency : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_jac_eval_frequency"
let set_jac_eval_frequency s maxsteps =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
set_jac_eval_frequency s maxsteps
external set_lsetup_frequency : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_lsetup_frequency"
external set_linear_solution_scaling : ('d, 'k) session -> bool -> unit
= "sunml_cvode_set_linear_solution_scaling"
external set_eps_lin : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_eps_lin"
let set_eps_lin s epsl =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
set_eps_lin s epsl
external set_ls_norm_factor : ('d, 'k) session -> float -> unit
= "sunml_cvode_set_ls_norm_factor"
external get_num_lin_iters : ('a, 'k) session -> int
= "sunml_cvode_get_num_lin_iters"
let get_num_lin_iters s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_lin_iters s
external get_num_lin_conv_fails : ('a, 'k) session -> int
= "sunml_cvode_get_num_lin_conv_fails"
let get_num_lin_conv_fails s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_lin_conv_fails s
external get_work_space : ('a, 'k) session -> int * int
= "sunml_cvode_spils_get_work_space"
let get_work_space s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_work_space s
external get_num_prec_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_prec_evals"
let get_num_prec_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_prec_evals s
external get_num_prec_solves : ('a, 'k) session -> int
= "sunml_cvode_get_num_prec_solves"
let get_num_prec_solves s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_prec_solves s
external get_num_jtsetup_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_jtsetup_evals"
let get_num_jtsetup_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_jtsetup_evals s
external get_num_jtimes_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_jtimes_evals"
let get_num_jtimes_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_jtimes_evals s
external get_num_lin_rhs_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_lin_rhs_evals"
let get_num_lin_rhs_evals s =
if Sundials_impl.Version.in_compat_mode2_3 then ls_check_spils s;
get_num_lin_rhs_evals s
type bandrange = { mupper : int; mlower : int; }
external c_set_preconditioner
: ('a, 'k) session -> int -> int -> int -> unit
= "sunml_cvode_set_banded_preconditioner"
Note : CVBandPrecInit seems to be designed only to be called on
a fresh spils solver ( i.e. right after CVSpgmr , CVSpbcg , or
) .
In Sundials 2.5.0 and 2.6.2 , calling
CVSpgmr - > CVBandPrecInit - > CVBandPrecInit
triggers a memory leak . Calling CVodeReInit does NOT help .
The only way to prevent leakage is to allocate a fresh spils
instance , thus :
CVSpgmr - > CVBandPrecInit - > CVSpgmr - > CVBandPrecInit .
If you call
CVSpgmr - > - > CVBandPrecInit ,
nothing serious happens , but the memory associated with
CVBandPrecInit wo n't be freed until the spils solver is torn
down . If you call BandPrecInit - > SetPreconditioner - >
BandPrecInit , you also get a memory leak .
( Perhaps set_preconditioner should be hidden too ? In that
case , we should somehow strip set_prec_type of the ability
to change PrecNone to anything else . )
set_jac_times_vec_fn , as well as similar functions for Dls
solvers , are kept because they accept NULL to remove the
callback . This design clearly anticipates being called
multiple times on the same solver instance .
a fresh spils solver (i.e. right after CVSpgmr, CVSpbcg, or
CVSptfqmr).
In Sundials 2.5.0 and 2.6.2, calling
CVSpgmr -> CVBandPrecInit -> CVBandPrecInit
triggers a memory leak. Calling CVodeReInit does NOT help.
The only way to prevent leakage is to allocate a fresh spils
instance, thus:
CVSpgmr -> CVBandPrecInit -> CVSpgmr -> CVBandPrecInit.
If you call
CVSpgmr -> CVSpilsSetPreconditioner -> CVBandPrecInit,
nothing serious happens, but the memory associated with
CVBandPrecInit won't be freed until the spils solver is torn
down. If you call BandPrecInit -> SetPreconditioner ->
BandPrecInit, you also get a memory leak.
(Perhaps set_preconditioner should be hidden too? In that
case, we should somehow strip set_prec_type of the ability
to change PrecNone to anything else.)
set_jac_times_vec_fn, as well as similar functions for Dls
solvers, are kept because they accept NULL to remove the
callback. This design clearly anticipates being called
multiple times on the same solver instance. *)
let init_preconditioner bandrange session nv =
let n = RealArray.length (Nvector.unwrap nv) in
c_set_preconditioner session n bandrange.mupper bandrange.mlower;
session.ls_precfns <- BandedPrecFns
let prec_left bandrange =
LSI.Iterative.(PrecLeft, init_preconditioner bandrange)
let prec_right bandrange =
LSI.Iterative.(PrecRight, init_preconditioner bandrange)
let prec_both bandrange =
LSI.Iterative.(PrecBoth, init_preconditioner bandrange)
external get_work_space : 'k serial_session -> int * int
= "sunml_cvode_bandprec_get_work_space"
let get_work_space s =
ls_check_spils_band s;
get_work_space s
external get_num_rhs_evals : 'k serial_session -> int
= "sunml_cvode_bandprec_get_num_rhs_evals"
let get_num_rhs_evals s =
ls_check_spils_band s;
get_num_rhs_evals s
let matrix_embedded_solver ((LSI.LS ({ LSI.rawptr; _ } as hls)) as ls) session _ =
if Sundials_impl.Version.lt580
then raise Config.NotImplementedBySundialsVersion;
c_set_linear_solver session rawptr None false false;
LSI.attach ls;
session.ls_solver <- LSI.HLS hls
external sv_tolerances : ('a, 'k) session -> float -> ('a, 'k) nvector -> unit
= "sunml_cvode_sv_tolerances"
external ss_tolerances : ('a, 'k) session -> float -> float -> unit
= "sunml_cvode_ss_tolerances"
external wf_tolerances : ('a, 'k) session -> unit
= "sunml_cvode_wf_tolerances"
type ('a, 'k) tolerance =
| SStolerances of float * float
| SVtolerances of float * ('a, 'k) nvector
| WFtolerances of 'a error_weight_fun
let default_tolerances = SStolerances (1.0e-4, 1.0e-8)
let set_tolerances s tol =
match tol with
| SStolerances (rel, abs) -> (s.errw <- dummy_errw; ss_tolerances s rel abs)
| SVtolerances (rel, abs) -> (if Sundials_configuration.safe then s.checkvec abs;
s.errw <- dummy_errw; sv_tolerances s rel abs)
| WFtolerances ferrw -> (s.errw <- ferrw; wf_tolerances s)
external c_session_finalize : ('a, 'kind) session -> unit
= "sunml_cvode_session_finalize"
let session_finalize s =
Dls.invalidate_callback s;
(match s.nls_solver with
| None -> ()
| Some nls -> NLSI.detach nls);
(match s.sensext with
| FwdSensExt { fnls_solver = NLSI.NLS nls } -> NLSI.detach nls
| FwdSensExt { fnls_solver = NLSI.NLS_sens nls } -> NLSI.detach nls
| _ -> ());
c_session_finalize s
Sundials > = 4.0.0
external c_set_nonlinear_solver
: ('d, 'k) session
-> ('d, 'k, ('d, 'k) session, [`Nvec]) NLSI.cptr
-> unit
= "sunml_cvode_set_nonlinear_solver"
external c_init
: ('a, 'k) session Weak.t
-> lmm
-> bool
-> ('a, 'k) Nvector.t
-> float
-> Context.t
-> (cvode_mem * c_weak_ref)
= "sunml_cvode_init_byte"
"sunml_cvode_init"
external c_set_proj_fn : ('d, 'k) session -> unit
= "sunml_cvode_set_proj_fn"
external c_set_nls_rhs_fn : ('d, 'k) session -> unit
= "sunml_cvode_set_nls_rhs_fn"
let init ?context lmm tol
?(nlsolver : ('data, 'kind, ('data, 'kind) session, [`Nvec])
Sundials_NonlinearSolver.t option)
?nlsrhsfn
?lsolver f ?(roots=no_roots)
?projfn t0 y0 =
let (nroots, roots) = roots in
let checkvec = Nvector.check y0 in
if Sundials_configuration.safe && nroots < 0
then invalid_arg "number of root functions is negative";
let weakref = Weak.create 1 in
let iter = match nlsolver with
| None -> true
| Some { NLSI.solver = NLSI.NewtonSolver _ } -> true
| Some _ -> false
in
let hasprojfn, projfn = match projfn with
| None -> false, dummy_projfn
| Some f -> true, f
in
let ctx = Sundials_impl.Context.get context in
let cvode_mem, backref = c_init weakref lmm iter y0 t0 ctx in
let session = {
cvode = cvode_mem;
backref = backref;
nroots = nroots;
checkvec = checkvec;
context = ctx;
exn_temp = None;
rhsfn = f;
rootsfn = roots;
errh = dummy_errh;
errw = dummy_errw;
error_file = None;
projfn = projfn;
monitorfn = dummy_monitorfn;
ls_solver = LSI.NoHLS;
ls_callbacks = NoCallbacks;
ls_precfns = NoPrecFns;
nls_solver = None;
nls_rhsfn = dummy_nlsrhsfn;
sensext = NoSensExt;
} in
Gc.finalise session_finalize session;
Weak.set weakref 0 (Some session);
Now the session is safe to use . If any of the following fails and raises
an exception , the GC will take care of freeing cvode_mem and backref .
an exception, the GC will take care of freeing cvode_mem and backref. *)
if nroots > 0 then
c_root_init session nroots;
set_tolerances session tol;
(match lsolver, nlsolver with
| None, None -> Diag.solver session y0
| None, Some _ -> ()
| Some linsolv, _ -> linsolv session y0);
(match nlsolver with
| Some ({ NLSI.rawptr = nlcptr } as nls)
when not Sundials_impl.Version.in_compat_mode2_3 ->
NLSI.attach nls;
session.nls_solver <- Some nls;
c_set_nonlinear_solver session nlcptr
| _ -> ());
(match nlsrhsfn with
| None -> () | _ when Sundials_impl.Version.lt580 -> ()
| Some f -> session.nls_rhsfn <- f;
c_set_nls_rhs_fn session);
if hasprojfn then c_set_proj_fn session;
session
let get_num_roots { nroots } = nroots
Sundials < 4.0.0
external c_set_functional : ('a, 'k) session -> unit
= "sunml_cvode_set_functional"
Sundials < 4.0.0
external c_set_newton : ('a, 'k) session -> unit
= "sunml_cvode_set_newton"
external c_reinit
: ('a, 'k) session -> float -> ('a, 'k) nvector -> unit
= "sunml_cvode_reinit"
let reinit session ?nlsolver ?nlsrhsfn ?lsolver ?roots ?rhsfn t0 y0 =
if Sundials_configuration.safe then session.checkvec y0;
Dls.invalidate_callback session;
c_reinit session t0 y0;
(match lsolver with
| None -> ()
| Some linsolv -> linsolv session y0);
(if Sundials_impl.Version.in_compat_mode2_3 then
match nlsolver with
| None -> ()
| Some { NLSI.solver = NLSI.FixedPointSolver _ } -> c_set_functional session
| Some _ -> c_set_newton session
else
match nlsolver with
| Some ({ NLSI.rawptr = nlcptr } as nls) ->
(match session.nls_solver with
| None -> () | Some old_nls -> NLSI.detach old_nls);
NLSI.attach nls;
session.nls_solver <- Some nls;
c_set_nonlinear_solver session nlcptr
| _ -> ());
(match nlsrhsfn with
| None -> () | _ when Sundials_impl.Version.lt580 -> ()
| Some f -> session.nls_rhsfn <- f;
c_set_nls_rhs_fn session);
(match roots with
| None -> ()
| Some roots -> root_init session roots);
(match rhsfn with None -> () | Some f -> session.rhsfn <- f)
external get_root_info : ('a, 'k) session -> Roots.t -> unit
= "sunml_cvode_get_root_info"
type solver_result =
*
external c_solve_normal : ('a, 'k) session -> float -> ('a, 'k) nvector
-> float * solver_result
= "sunml_cvode_solve_normal"
let solve_normal s t y =
if Sundials_configuration.safe then s.checkvec y;
c_solve_normal s t y
external c_solve_one_step : ('a, 'k) session -> float -> ('a, 'k) nvector
-> float * solver_result
= "sunml_cvode_solve_one_step"
let solve_one_step s t y =
if Sundials_configuration.safe then s.checkvec y;
c_solve_one_step s t y
external c_get_dky
: ('a, 'k) session -> float -> int -> ('a, 'k) nvector -> unit
= "sunml_cvode_get_dky"
let get_dky s y =
if Sundials_configuration.safe then s.checkvec y;
fun t k -> c_get_dky s t k y
external get_integrator_stats : ('a, 'k) session -> integrator_stats
= "sunml_cvode_get_integrator_stats"
external get_linear_solver_stats : ('a, 'k) session -> linear_solver_stats
= "sunml_cvode_get_linear_solver_stats"
external get_work_space : ('a, 'k) session -> int * int
= "sunml_cvode_get_work_space"
external get_num_steps : ('a, 'k) session -> int
= "sunml_cvode_get_num_steps"
external get_num_rhs_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_rhs_evals"
external get_num_lin_solv_setups : ('a, 'k) session -> int
= "sunml_cvode_get_num_lin_solv_setups"
external get_num_err_test_fails : ('a, 'k) session -> int
= "sunml_cvode_get_num_err_test_fails"
external get_last_order : ('a, 'k) session -> int
= "sunml_cvode_get_last_order"
external get_current_order : ('a, 'k) session -> int
= "sunml_cvode_get_current_order"
external get_current_state : ('d, 'k) session -> 'd
= "sunml_cvode_get_current_state"
must correspond to cvode_nonlin_system_data_index in cvode_ml.h
type 'd nonlin_system_data = {
tn : float;
ypred : 'd;
yn : 'd;
fn : 'd;
gamma : float;
rl1 : float;
zn1 : 'd;
}
external get_nonlin_system_data
: ('d, 'k) session -> 'd nonlin_system_data
= "sunml_cvode_get_nonlin_system_data"
external compute_state
: ('d, 'k) session
-> ('d, 'k) Nvector.t
-> ('d, 'k) Nvector.t
-> unit
= "sunml_cvode_compute_state"
let compute_state s ycor yn =
if Sundials_configuration.safe then (s.checkvec ycor; s.checkvec yn);
compute_state s ycor yn
external get_current_gamma : ('d, 'k) session -> (float [@unboxed])
= "sunml_cvode_get_current_gamma"
"sunml_cvode_get_current_gamma_unboxed"
external get_actual_init_step : ('a, 'k) session -> float
= "sunml_cvode_get_actual_init_step"
external get_last_step : ('a, 'k) session -> float
= "sunml_cvode_get_last_step"
external get_current_step : ('a, 'k) session -> float
= "sunml_cvode_get_current_step"
external get_current_time : ('a, 'k) session -> float
= "sunml_cvode_get_current_time"
let print_integrator_stats s oc =
let stats = get_integrator_stats s
in
Printf.fprintf oc "num_steps = %d\n" stats.num_steps;
Printf.fprintf oc "num_rhs_evals = %d\n" stats.num_rhs_evals;
Printf.fprintf oc "num_lin_solv_setups = %d\n" stats.num_lin_solv_setups;
Printf.fprintf oc "num_err_test_fails = %d\n" stats.num_err_test_fails;
Printf.fprintf oc "last_order = %d\n" stats.last_order;
Printf.fprintf oc "current_order = %d\n" stats.current_order;
Printf.fprintf oc "actual_init_step = %e\n" stats.actual_init_step;
Printf.fprintf oc "last_step = %e\n" stats.last_step;
Printf.fprintf oc "current_step = %e\n" stats.current_step;
Printf.fprintf oc "current_time = %e\n" stats.current_time;
external c_set_error_file : ('a, 'k) session -> Logfile.t -> unit
= "sunml_cvode_set_error_file"
let set_error_file s f =
s.error_file <- Some f;
c_set_error_file s f
external set_err_handler_fn : ('a, 'k) session -> unit
= "sunml_cvode_set_err_handler_fn"
let set_err_handler_fn s ferrh =
s.errh <- ferrh;
set_err_handler_fn s
external clear_err_handler_fn : ('a, 'k) session -> unit
= "sunml_cvode_clear_err_handler_fn"
let clear_err_handler_fn s =
s.errh <- dummy_errh;
clear_err_handler_fn s
external c_set_monitor_fn : ('a, 'k) session -> bool -> unit
= "sunml_cvode_set_monitor_fn"
external c_set_monitor_frequency : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_monitor_frequency"
let set_monitor_fn s freq monitorfn =
if Sundials_configuration.monitoring_enabled then begin
s.monitorfn <- monitorfn;
c_set_monitor_fn s true;
c_set_monitor_frequency s freq
end else raise Config.NotImplementedBySundialsVersion
let set_monitor_frequency s freq =
if Sundials_configuration.monitoring_enabled
then c_set_monitor_frequency s freq
else raise Config.NotImplementedBySundialsVersion
let clear_monitor_fn s =
if Sundials_configuration.monitoring_enabled then begin
c_set_monitor_fn s false;
s.monitorfn <- dummy_monitorfn
end
external set_max_ord : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_ord"
external set_max_num_steps : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_num_steps"
external set_max_hnil_warns : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_hnil_warns"
external set_stab_lim_det : ('a, 'k) session -> bool -> unit
= "sunml_cvode_set_stab_lim_det"
external set_init_step : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_init_step"
external set_min_step : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_min_step"
external set_max_step : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_max_step"
external set_stop_time : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_stop_time"
external set_max_err_test_fails : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_err_test_fails"
external set_max_nonlin_iters : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_nonlin_iters"
external set_max_conv_fails : ('a, 'k) session -> int -> unit
= "sunml_cvode_set_max_conv_fails"
external set_nonlin_conv_coef : ('a, 'k) session -> float -> unit
= "sunml_cvode_set_nonlin_conv_coef"
external c_set_constraints : ('a,'k) session -> ('a,'k) Nvector.t -> unit
= "sunml_cvode_set_constraints"
external c_clear_constraints : ('a,'k) session -> unit
= "sunml_cvode_clear_constraints"
let set_constraints s nv =
(match Config.sundials_version with
| 2,_,_ | 3,1,_ -> raise Config.NotImplementedBySundialsVersion
| _ -> ());
if Sundials_configuration.safe then s.checkvec nv;
c_set_constraints s nv
let clear_constraints s =
(match Config.sundials_version with
| 2,_,_ | 3,1,_ -> raise Config.NotImplementedBySundialsVersion
| _ -> ());
c_clear_constraints s
external set_proj_err_est : ('d, 'k) session -> bool -> unit
= "sunml_cvode_set_proj_err_est"
external set_proj_frequency : ('d, 'k) session -> int -> unit
= "sunml_cvode_set_proj_frequency"
external set_max_num_proj_fails : ('d, 'k) session -> int -> unit
= "sunml_cvode_set_max_num_proj_fails"
external set_eps_proj : ('d, 'k) session -> float -> unit
= "sunml_cvode_set_eps_proj"
external set_proj_fail_eta : ('d, 'k) session -> float -> unit
= "sunml_cvode_set_proj_fail_eta"
external get_num_proj_evals : ('d, 'k) session -> int
= "sunml_cvode_get_num_proj_evals"
external get_num_proj_fails : ('d, 'k) session -> int
= "sunml_cvode_get_num_proj_fails"
external set_root_direction' : ('a, 'k) session -> RootDirs.t -> unit
= "sunml_cvode_set_root_direction"
let set_root_direction s rda =
set_root_direction' s (RootDirs.copy (get_num_roots s) rda)
let set_all_root_directions s rd =
set_root_direction' s (RootDirs.make (get_num_roots s) rd)
external set_no_inactive_root_warn : ('a, 'k) session -> unit
= "sunml_cvode_set_no_inactive_root_warn"
external get_num_stab_lim_order_reds : ('a, 'k) session -> int
= "sunml_cvode_get_num_stab_lim_order_reds"
external get_tol_scale_factor : ('a, 'k) session -> float
= "sunml_cvode_get_tol_scale_factor"
external c_get_err_weights : ('a, 'k) session -> ('a, 'k) nvector -> unit
= "sunml_cvode_get_err_weights"
let get_err_weights s ew =
if Sundials_configuration.safe then s.checkvec ew;
c_get_err_weights s ew
external c_get_est_local_errors : ('a, 'k) session -> ('a, 'k) nvector -> unit
= "sunml_cvode_get_est_local_errors"
let get_est_local_errors s ew =
if Sundials_configuration.safe then s.checkvec ew;
c_get_est_local_errors s ew
external get_num_nonlin_solv_iters : ('a, 'k) session -> int
= "sunml_cvode_get_num_nonlin_solv_iters"
external get_num_nonlin_solv_conv_fails : ('a, 'k) session -> int
= "sunml_cvode_get_num_nonlin_solv_conv_fails"
external get_nonlin_solv_stats : ('a, 'k) session -> int * int
= "sunml_cvode_get_nonlin_solv_stats"
external get_num_g_evals : ('a, 'k) session -> int
= "sunml_cvode_get_num_g_evals"
external c_init_module : exn array -> unit =
"sunml_cvode_init_module"
let _ =
c_init_module
[|IllInput;
TooClose;
TooMuchWork;
TooMuchAccuracy;
ErrFailure;
ConvergenceFailure;
LinearInitFailure;
LinearSetupFailure None;
LinearSolveFailure None;
NonlinearSolverFailure;
NonlinearInitFailure;
NonlinearSetupFailure;
RhsFuncFailure;
FirstRhsFuncFailure;
RepeatedRhsFuncFailure;
UnrecoverableRhsFuncFailure;
RootFuncFailure;
ConstraintFailure;
BadK;
BadT;
VectorOpErr;
ProjFuncFailure;
RepeatedProjFuncError;
ProjectionNotEnabled;
|]
|
abe3ef368bfdeb316ca3d6a339f2dea6a8569e7ea2b95df4314f86a4ec24b270 | jrm-code-project/LISP-Machine | disk-cadr.lisp | -*- Mode : LISP ; Package : SYSTEM - INTERNALS ; Base:8 ; : T -*-
A hardware bug causes this to lose if > 1 page ( Fixed by DC ECO#1 )
;Returns T if they match and NIL if they don't
(DEFUN DISK-READ-COMPARE (RQB UNIT ADDRESS
&OPTIONAL (MICROCODE-ERROR-RECOVERY LET-MICROCODE-HANDLE-DISK-ERRORS)
do-not-offset)
"Compare data from disk UNIT at block ADDRESS with the data in RQB.
The length of data compared is simply the number of pages of data in RQB.
UNIT can be either a disk unit number or a function to perform
the transfer. That is how transfers to other machines' disks are done.
The function receives arguments ':READ-COMPARE, the RQB, and the ADDRESS."
(lambda-or-cadr-only)
(COND ((NUMBERP UNIT)
(WIRE-DISK-RQB RQB)
(DISK-READ-COMPARE-WIRED RQB UNIT ADDRESS MICROCODE-ERROR-RECOVERY do-not-offset)
(UNWIRE-DISK-RQB RQB)
(ZEROP (LDB %%DISK-STATUS-HIGH-READ-COMPARE-DIFFERENCE
(AREF RQB %DISK-RQ-STATUS-HIGH))))
((SEND UNIT (if do-not-offset ':read-compare-physical ':READ-COMPARE) RQB ADDRESS))))
;;; Get STATUS of a unit by doing OFFSET-CLEAR (nebbish command) to it
;;; Leaves the status in the rqb
(DEFUN GET-DISK-STATUS (RQB UNIT)
(select-processor
(:cadr
(DISK-RUN RQB UNIT 0 1 1 %DISK-COMMAND-OFFSET-CLEAR "Offset Clear" T))
((:lambda :explorer)
(ferror nil "obsolete"))))
;;; Power up a drive, return T if successful, NIL if timed out
(DEFUN POWER-UP-DISK (UNIT &AUX RQB)
"Attempt to turn on disk unit UNIT. Return T if successful."
(select-processor
(:cadr
(UNWIND-PROTECT
(PROGN (SETQ RQB (GET-DISK-RQB))
(DO ((START-TIME (TIME)))
((OR (> (TIME-DIFFERENCE (TIME) START-TIME) (* 30. 60.))
(NOT (LDB-TEST %%DISK-STATUS-LOW-OFF-CYLINDER
(PROGN (GET-DISK-STATUS RQB UNIT)
(AREF RQB %DISK-RQ-STATUS-LOW)))))
(NOT (LDB-TEST %%DISK-STATUS-LOW-OFF-CYLINDER
(AREF RQB %DISK-RQ-STATUS-LOW))))
(PROCESS-SLEEP 60.)))
(RETURN-DISK-RQB RQB)))
((:lambda :explorer)
(ferror nil "obsolete"))))
(DEFUN CLEAR-DISK-FAULT (UNIT &AUX RQB)
"Clear any error indicators on disk drive UNIT."
(select-processor
(:cadr
(UNWIND-PROTECT
(PROGN (SETQ RQB (GET-DISK-RQB))
(DISK-RUN RQB UNIT 0 1 1 %DISK-COMMAND-FAULT-CLEAR "Fault Clear" T))
(RETURN-DISK-RQB RQB)))
((:lambda :explorer)
(ferror nil "obsolete"))))
;;; A debugging function
(DEFUN PRINT-RQB (RQB)
(DO ((I 0 (1+ I))
(L DISK-RQ-HWDS (CDR L)))
((NULL (CDR L))
(PRINT (CAR L)) ;CCW list
(DO ((I I (+ I 2))) (())
(FORMAT T " ~O" (DPB (AREF RQB (1+ I)) #o2020 (AREF RQB I)))
(OR (BIT-TEST 1 (AREF RQB I)) (RETURN NIL)))
(TERPRI))
(FORMAT T "~%~S ~O" (CAR L) (AREF RQB I))))
A hardware bug causes this to lose if > 1 page ( Fixed by DC ECO#1 )
;;; Returns T if read-compare difference detected
(DEFUN DISK-READ-COMPARE-WIRED (RQB UNIT ADDRESS
&OPTIONAL (MICROCODE-ERROR-RECOVERY LET-MICROCODE-HANDLE-DISK-ERRORS)
do-not-offset
&AUX (SECTORS-PER-TRACK (AREF DISK-SECTORS-PER-TRACK-ARRAY UNIT))
(HEADS-PER-CYLINDER (AREF DISK-HEADS-PER-CYLINDER-ARRAY UNIT)))
(select-processor
(:cadr
(DISK-RUN RQB UNIT ADDRESS SECTORS-PER-TRACK HEADS-PER-CYLINDER
(LOGIOR %DISK-COMMAND-READ-COMPARE
(IF MICROCODE-ERROR-RECOVERY %DISK-COMMAND-DONE-INTERRUPT-ENABLE 0))
"read-compare" nil do-not-offset)
(LDB-TEST %%DISK-STATUS-HIGH-READ-COMPARE-DIFFERENCE
(AREF RQB %DISK-RQ-STATUS-HIGH)))
((:lambda :explorer)
(ferror nil "can't do read-compare on this processor"))))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/io/disk-cadr.lisp | lisp | Package : SYSTEM - INTERNALS ; Base:8 ; : T -*-
Returns T if they match and NIL if they don't
Get STATUS of a unit by doing OFFSET-CLEAR (nebbish command) to it
Leaves the status in the rqb
Power up a drive, return T if successful, NIL if timed out
A debugging function
CCW list
Returns T if read-compare difference detected |
A hardware bug causes this to lose if > 1 page ( Fixed by DC ECO#1 )
(DEFUN DISK-READ-COMPARE (RQB UNIT ADDRESS
&OPTIONAL (MICROCODE-ERROR-RECOVERY LET-MICROCODE-HANDLE-DISK-ERRORS)
do-not-offset)
"Compare data from disk UNIT at block ADDRESS with the data in RQB.
The length of data compared is simply the number of pages of data in RQB.
UNIT can be either a disk unit number or a function to perform
the transfer. That is how transfers to other machines' disks are done.
The function receives arguments ':READ-COMPARE, the RQB, and the ADDRESS."
(lambda-or-cadr-only)
(COND ((NUMBERP UNIT)
(WIRE-DISK-RQB RQB)
(DISK-READ-COMPARE-WIRED RQB UNIT ADDRESS MICROCODE-ERROR-RECOVERY do-not-offset)
(UNWIRE-DISK-RQB RQB)
(ZEROP (LDB %%DISK-STATUS-HIGH-READ-COMPARE-DIFFERENCE
(AREF RQB %DISK-RQ-STATUS-HIGH))))
((SEND UNIT (if do-not-offset ':read-compare-physical ':READ-COMPARE) RQB ADDRESS))))
(DEFUN GET-DISK-STATUS (RQB UNIT)
(select-processor
(:cadr
(DISK-RUN RQB UNIT 0 1 1 %DISK-COMMAND-OFFSET-CLEAR "Offset Clear" T))
((:lambda :explorer)
(ferror nil "obsolete"))))
(DEFUN POWER-UP-DISK (UNIT &AUX RQB)
"Attempt to turn on disk unit UNIT. Return T if successful."
(select-processor
(:cadr
(UNWIND-PROTECT
(PROGN (SETQ RQB (GET-DISK-RQB))
(DO ((START-TIME (TIME)))
((OR (> (TIME-DIFFERENCE (TIME) START-TIME) (* 30. 60.))
(NOT (LDB-TEST %%DISK-STATUS-LOW-OFF-CYLINDER
(PROGN (GET-DISK-STATUS RQB UNIT)
(AREF RQB %DISK-RQ-STATUS-LOW)))))
(NOT (LDB-TEST %%DISK-STATUS-LOW-OFF-CYLINDER
(AREF RQB %DISK-RQ-STATUS-LOW))))
(PROCESS-SLEEP 60.)))
(RETURN-DISK-RQB RQB)))
((:lambda :explorer)
(ferror nil "obsolete"))))
(DEFUN CLEAR-DISK-FAULT (UNIT &AUX RQB)
"Clear any error indicators on disk drive UNIT."
(select-processor
(:cadr
(UNWIND-PROTECT
(PROGN (SETQ RQB (GET-DISK-RQB))
(DISK-RUN RQB UNIT 0 1 1 %DISK-COMMAND-FAULT-CLEAR "Fault Clear" T))
(RETURN-DISK-RQB RQB)))
((:lambda :explorer)
(ferror nil "obsolete"))))
(DEFUN PRINT-RQB (RQB)
(DO ((I 0 (1+ I))
(L DISK-RQ-HWDS (CDR L)))
((NULL (CDR L))
(DO ((I I (+ I 2))) (())
(FORMAT T " ~O" (DPB (AREF RQB (1+ I)) #o2020 (AREF RQB I)))
(OR (BIT-TEST 1 (AREF RQB I)) (RETURN NIL)))
(TERPRI))
(FORMAT T "~%~S ~O" (CAR L) (AREF RQB I))))
A hardware bug causes this to lose if > 1 page ( Fixed by DC ECO#1 )
(DEFUN DISK-READ-COMPARE-WIRED (RQB UNIT ADDRESS
&OPTIONAL (MICROCODE-ERROR-RECOVERY LET-MICROCODE-HANDLE-DISK-ERRORS)
do-not-offset
&AUX (SECTORS-PER-TRACK (AREF DISK-SECTORS-PER-TRACK-ARRAY UNIT))
(HEADS-PER-CYLINDER (AREF DISK-HEADS-PER-CYLINDER-ARRAY UNIT)))
(select-processor
(:cadr
(DISK-RUN RQB UNIT ADDRESS SECTORS-PER-TRACK HEADS-PER-CYLINDER
(LOGIOR %DISK-COMMAND-READ-COMPARE
(IF MICROCODE-ERROR-RECOVERY %DISK-COMMAND-DONE-INTERRUPT-ENABLE 0))
"read-compare" nil do-not-offset)
(LDB-TEST %%DISK-STATUS-HIGH-READ-COMPARE-DIFFERENCE
(AREF RQB %DISK-RQ-STATUS-HIGH)))
((:lambda :explorer)
(ferror nil "can't do read-compare on this processor"))))
|
380c16d4e24321cb2a4092f4fd99d73df1c9d7ba106dcb3f6ff8ee66db7fb842 | racket/gui | gl-context.rkt | #lang racket/base
(require racket/class
racket/promise
racket/string
ffi/unsafe
ffi/unsafe/define
ffi/unsafe/alloc
ffi/cvector
(prefix-in draw: racket/draw/private/gl-context)
racket/draw/private/gl-config
"../../lock.rkt"
"types.rkt"
"utils.rkt"
"window.rkt"
"x11.rkt")
(provide
(protect-out prepare-widget-gl-context
create-widget-gl-context
create-and-install-gl-context
get-gdk-pixmap
install-gl-context))
(define (ffi-lib/complaint-on-failure name vers)
(ffi-lib name vers
#:fail (lambda ()
(log-warning "could not load library ~a ~a"
name vers)
#f)))
;; ===================================================================================================
;; X11/GLX FFI
(define gl-lib (ffi-lib/complaint-on-failure "libGL" '("1" "")))
(define-ffi-definer define-glx gl-lib
#:default-make-fail make-not-available)
;; X #defines/typedefs/enums
(define _Display (_cpointer 'Display))
(define _XErrorEvent (_cpointer 'XErrorEvent))
(define _XID _ulong)
(define True 1)
(define False 0)
(define None 0)
(define Success 0)
;; GLX #defines/typedefs/enums
(define _GLXFBConfig (_cpointer 'GLXFBConfig))
(define _GLXContext (_cpointer/null 'GLXContext))
(define _XVisualInfo (_cpointer 'XVisualInfo))
Attribute tokens for glXGetConfig variants ( all GLX versions ):
(define GLX_DOUBLEBUFFER 5)
(define GLX_STEREO 6)
(define GLX_DEPTH_SIZE 12)
(define GLX_STENCIL_SIZE 13)
(define GLX_ACCUM_RED_SIZE 14)
(define GLX_ACCUM_GREEN_SIZE 15)
(define GLX_ACCUM_BLUE_SIZE 16)
(define GLX_ACCUM_ALPHA_SIZE 17)
GLX 1.3 and later :
(define GLX_X_RENDERABLE #x8012)
(define GLX_RGBA_TYPE #x8014)
GLX 1.4 and later :
(define GLX_SAMPLES #x186a1)
(define GLX_SAMPLE_BUFFERS #x186a0)
Attribute tokens for glXCreateContextAttribsARB ( also GLX 1.4 and later ):
(define GLX_CONTEXT_MAJOR_VERSION_ARB #x2091)
(define GLX_CONTEXT_MINOR_VERSION_ARB #x2092)
(define GLX_CONTEXT_FLAGS_ARB #x2094)
(define GLX_CONTEXT_PROFILE_MASK_ARB #x9126)
;; GLX_CONTEXT_FLAGS_ARB bits
(define GLX_CONTEXT_DEBUG_BIT_ARB #x1)
(define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB #x2)
GLX_CONTEXT_PROFILE_MASK_ARB bits
(define GLX_CONTEXT_CORE_PROFILE_BIT_ARB #x1)
(define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB #x2)
(define-x11 XFree (_fun _pointer -> _int)
#:wrap (deallocator))
(define-x11 XSetErrorHandler
(_fun _fpointer -> _fpointer))
(define-x11 XSync
(_fun _Display _int -> _void))
(define-glx glXQueryVersion
(_fun _Display (major : (_ptr o _int)) (minor : (_ptr o _int))
-> (ret : _bool)
-> (values ret major minor)))
(define-glx glXQueryExtensionsString
(_fun _Display _int -> _string/utf-8))
(define-glx glXChooseFBConfig
(_fun _Display _int (_list i _int) (len : (_ptr o _int))
-> (_cvector o _GLXFBConfig len))
#:wrap (allocator (λ (v) (XFree (cvector-ptr v)))))
(define-glx glXGetFBConfigAttrib
(_fun _Display _GLXFBConfig _int (out : (_ptr o _int))
-> (ret : _int)
-> (values ret out)))
(define-glx glXCreateNewContext
(_fun _Display _GLXFBConfig _int _GLXContext _bool -> _GLXContext))
(define-glx glXDestroyContext
(_fun _Display _GLXContext -> _void))
(define-glx glXMakeCurrent
(_fun _Display _XID _GLXContext -> _bool))
(define-glx glXSwapBuffers
(_fun _Display _XID -> _void))
(define-glx glXIsDirect
(_fun _Display _GLXContext -> _bool))
(define-glx glXGetVisualFromFBConfig
(_fun _Display _GLXFBConfig -> _XVisualInfo)
#:wrap (allocator XFree))
(define-glx glXCreateGLXPixmap
(_fun _Display _XVisualInfo _XID -> _XID))
(define-glx glXDestroyGLXPixmap
(_fun _Display _XID -> _void))
(define-glx glXGetProcAddressARB
(_fun _string -> _pointer))
(define lazy-glXCreateContextAttribsARB
(delay
(function-ptr (glXGetProcAddressARB "glXCreateContextAttribsARB")
(_fun _Display _GLXFBConfig _GLXContext _bool (_list i _int)
-> _GLXContext))))
(define (glXCreateContextAttribsARB . args)
(apply (force lazy-glXCreateContextAttribsARB) args))
(define-gtk gtk_widget_get_display (_fun _GtkWidget -> _GdkDisplay))
(define-gtk gtk_widget_get_screen (_fun _GtkWidget -> _GdkScreen))
(define-glx glXSwapIntervalEXT (_fun _Display _XID _int -> _void)
#:fail (lambda () void))
;; ===================================================================================================
GLX versions and extensions queries
(define lazy-get-glx-version
(delay
(define-values (worked? glx-major glx-minor)
(glXQueryVersion (gdk_x11_display_get_xdisplay (gdk_display_get_default))))
(unless worked?
(error 'get-glx-version "can't get GLX version using default display"))
(define glx-version (+ glx-major (/ glx-minor 10)))
(when (< glx-version #e1.3)
(error 'get-glx-version "need GLX version 1.3 or greater; given version ~a.~a"
glx-major glx-minor))
glx-version))
;; -> positive-exact-rational
(define (get-glx-version)
(force lazy-get-glx-version))
(define lazy-glx-extensions
(delay
(define str
(glXQueryExtensionsString (gdk_x11_display_get_xdisplay (gdk_display_get_default))
(gdk_x11_screen_get_screen_number (gdk_screen_get_default))))
(string-split str)))
(define lazy-GLX_ARB_create_context?
(delay (member "GLX_ARB_create_context"
(force lazy-glx-extensions))))
(define lazy-GLX_ARB_create_context_profile?
(delay (member "GLX_ARB_create_context_profile"
(force lazy-glx-extensions))))
;; ===================================================================================================
Wrapper for the _ GLXContext ( if we can get one from GLX )
(define gl-context%
(class draw:gl-context%
(init-field gl display drawable pixmap)
(define/override (get-handle) gl)
(define/public (get-gtk-display) display)
(define/public (get-gtk-drawable) drawable)
(define/public (get-glx-pixmap) pixmap)
(define (get-drawable-xid)
(if pixmap pixmap (gdk_x11_drawable_get_xid drawable)))
(define/override (draw:do-call-as-current t)
(define xdisplay (gdk_x11_display_get_xdisplay display))
(dynamic-wind
(lambda ()
(glXMakeCurrent xdisplay (get-drawable-xid) gl))
t
(lambda ()
(glXMakeCurrent xdisplay 0 #f))))
(define/override (draw:do-swap-buffers)
(glXSwapBuffers (gdk_x11_display_get_xdisplay display)
(get-drawable-xid)))
(super-new)))
;; ===================================================================================================
;; Getting OpenGL contexts
;; STUPIDITY ALERT
;; Apparently, the designers of glXCreateNewContext and glXCreateContextAttribsARB didn't trust us to
;; check return values or output arguments, so when these functions fail, they raise an X error and
;; send an error code to the X error handler. X errors, by default, *terminate the program* and print
;; an annoyingly vague, barely helpful error message.
;; This is especially bad with glXCreateContextAttribsARB, which always fails (i.e. crashes the
;; program) if we ask for an unsupported OpenGL version. Worse, this is the only way to find out
;; which OpenGL versions are available!
;; So we override the X error handler to silently fail, and sync right after the calls to make sure
;; the errors are processed immediately. With glXCreateContextAttribsARB, we then try the next lowest
OpenGL version . If all attempts to get a context fail , we return # f.
(define create-context-error? #f)
(define (flag-x-error-handler xdisplay xerrorevent)
(set! create-context-error? #t)
0)
_ Display _ GLXFBConfig _ GLXContext - > _ GLXContext
(define (glx-create-new-context xdisplay cfg share-gl)
Sync right now , or the sync further on could crash Racket with an [ xcb ] error about events
;; happening out of sequence
(XSync xdisplay False)
(define old-handler #f)
(define gl
(dynamic-wind
(λ ()
(set! old-handler
(XSetErrorHandler
(cast flag-x-error-handler
(_fun #:atomic? #t _Display _XErrorEvent -> _int)
_fpointer))))
(λ ()
(set! create-context-error? #f)
(glXCreateNewContext xdisplay cfg GLX_RGBA_TYPE share-gl #t))
(λ ()
Sync to ensure errors are processed
(XSync xdisplay False)
(XSetErrorHandler old-handler))))
(cond
[(and gl create-context-error?)
(log-error (string-append
"gl-context: glXCreateNewContext raised an error but (contrary to standards)"
" returned a non-NULL context; ignoring possibly corrupt context"))
#f]
[else
(unless gl
(log-warning "gl-context: glXCreateNewContext was unable to get an OpenGL context"))
gl]))
;; OpenGL core versions we'll try to get, in order
(define core-gl-versions '((4 5) (4 4) (4 3) (4 2) (4 1) (4 0) (3 3) (3 2) (3 1) (3 0)))
_ Display _ GLXFBConfig _ GLXContext ( List Byte Byte ) - > _ GLXContext
(define (glx-create-context-attribs xdisplay cfg share-gl gl-version)
Sync right now , or the sync further on could crash Racket with an [ xcb ] error about events
;; happening out of sequence
(XSync xdisplay False)
(define gl-major (car gl-version))
(define gl-minor (cadr gl-version))
(define context-attribs
(list GLX_CONTEXT_MAJOR_VERSION_ARB gl-major
GLX_CONTEXT_MINOR_VERSION_ARB gl-minor
GLX_CONTEXT_PROFILE_MASK_ARB GLX_CONTEXT_CORE_PROFILE_BIT_ARB
None))
(define old-handler #f)
(define gl
(dynamic-wind
(λ ()
(set! old-handler
(XSetErrorHandler
(cast flag-x-error-handler
(_fun #:atomic? #t _Display _XErrorEvent -> _int)
_fpointer))))
(λ ()
(set! create-context-error? #f)
(glXCreateContextAttribsARB xdisplay cfg share-gl #t context-attribs))
(λ ()
Sync to ensure errors are processed
(XSync xdisplay False)
(XSetErrorHandler old-handler))))
(cond
[(and gl create-context-error?)
(log-error (string-append
"gl-context: glXCreateContextAttribsARB raised an error for version ~a.~a but"
" (contrary to standards) returned a non-NULL context;"
" ignoring possibly corrupt context")
gl-major gl-minor)
#f]
[else
(unless gl
(log-info "gl-context: glXCreateContextAttribsARB returned NULL for version ~a.~a"
gl-major gl-minor))
gl]))
_ Display _ GLXFBConfig _ GLXContext - > _ GLXContext
(define (glx-create-core-context xdisplay cfg share-gl)
(let/ec return
(for ([gl-version (in-list core-gl-versions)])
(define gl (glx-create-context-attribs xdisplay cfg share-gl gl-version))
(when gl (return gl)))
(log-warning "gl-context: unable to get core context; falling back")
(glx-create-new-context xdisplay cfg share-gl)))
;; ===================================================================================================
( or / c # f _ GtkWidget ) - > _ GdkDisplay
(define (gtk-maybe-widget-get-display widget)
(cond [widget (gtk_widget_get_display widget)]
[else (gdk_display_get_default)]))
( or / c # f _ GtkWidget ) - > _ GdkScreen
(define (gtk-maybe-widget-get-screen widget)
(cond [widget (gtk_widget_get_screen widget)]
[else (gdk_screen_get_default)]))
;; _Display _GLXFBConfig int int -> int
(define (glx-get-fbconfig-attrib xdisplay cfg attrib bad-value)
(define-values (err value) (glXGetFBConfigAttrib xdisplay cfg attrib))
(if (= err Success) value bad-value))
( or / c # f _ GtkWidget ) _ GdkDrawable gl - config% boolean ? - > gl - context%
where _ GdkDrawable = ( or / c _ GtkWindow _ )
(define (make-gtk-drawable-gl-context widget drawable conf wants-double?)
(define glx-version (get-glx-version))
;; If widget isn't #f, use its display and screen
(define display (gtk-maybe-widget-get-display widget))
(define screen (gtk-maybe-widget-get-screen widget))
Get the X objects wrapped by the GDK objects
(define xdisplay (gdk_x11_display_get_xdisplay display))
(define xscreen (gdk_x11_screen_get_screen_number screen))
Create an attribute list using the GL config
(define xattribs
(append
;; Be aware: we may get double buffering even if we don't ask for it
(if wants-double?
(if (send conf get-double-buffered) (list GLX_DOUBLEBUFFER True) null)
null)
(if (send conf get-stereo) (list GLX_STEREO True) null)
Finish out with standard GLX 1.3 attributes
(list
yes , we want to use OpenGL to render today
GLX_DEPTH_SIZE (send conf get-depth-size)
GLX_STENCIL_SIZE (send conf get-stencil-size)
GLX_ACCUM_RED_SIZE (send conf get-accum-size)
GLX_ACCUM_GREEN_SIZE (send conf get-accum-size)
GLX_ACCUM_BLUE_SIZE (send conf get-accum-size)
GLX_ACCUM_ALPHA_SIZE (send conf get-accum-size)
GLX_SAMPLES is handled below - GLX regards it as an absolute lower bound , which makes it
;; too easy for user programs to fail to get a context
None)))
(define multisample-size (send conf get-multisample-size))
;; Get all framebuffer configs for this display and screen that match the requested attributes,
;; then sort them to put the best in front
GLX already sorts them pretty well , so we just need a stable sort on multisamples at the moment
(define cfgs
(let* ([cfgs (cvector->list (glXChooseFBConfig xdisplay xscreen xattribs))]
Keep all configs with multisample size < = requested ( i.e. make multisample - size an
;; abolute upper bound)
[cfgs (if (< glx-version #e1.4)
cfgs
(filter (λ (cfg)
(define m (glx-get-fbconfig-attrib xdisplay cfg GLX_SAMPLES 0))
(<= m multisample-size))
cfgs))]
Sort all configs by multisample size , decreasing
[cfgs (if (< glx-version #e1.4)
cfgs
(sort cfgs >
#:key (λ (cfg) (glx-get-fbconfig-attrib xdisplay cfg GLX_SAMPLES 0))
#:cache-keys? #t))])
cfgs))
(cond
[(null? cfgs) #f]
[else
The framebuffer configs are sorted best - first , so choose the first
(define cfg (car cfgs))
(define share-gl
(let ([share-ctxt (send conf get-share-context)])
(and share-ctxt (send share-ctxt get-handle))))
Get a GL context
(define gl
(if (and (>= glx-version #e1.4)
(not (send conf get-legacy?))
(force lazy-GLX_ARB_create_context?)
(force lazy-GLX_ARB_create_context_profile?))
If the GLX version is high enough , legacy ? is # f , and GLX has the right extensions ,
;; try to get a core-profile context
(glx-create-core-context xdisplay cfg share-gl)
;; Otherwise use the old method
(glx-create-new-context xdisplay cfg share-gl)))
;; The above will return a direct rendering context when it can
If it does n't , the context will be version 1.4 or lower , unless GLX is implemented with
proprietary extensions ( NVIDIA 's drivers sometimes do this )
(when (and widget (send conf get-sync-swap))
(glXSwapIntervalEXT xdisplay (gdk_x11_drawable_get_xid drawable) 1))
Now wrap the GLX context in a gl - context%
(cond
[gl
If there 's no widget , this is for a pixmap , so get the stupid GLX wrapper for it or
;; indirect rendering may crash on some systems (notably mine)
(define pixmap
(if widget #f (glXCreateGLXPixmap xdisplay
(glXGetVisualFromFBConfig xdisplay cfg)
(if gtk3?
(cast drawable _Pixmap _ulong)
(gdk_x11_drawable_get_xid drawable)))))
(define ctxt (new gl-context% [gl gl] [display display] [drawable drawable] [pixmap pixmap]))
Refcount these so they do n't go away until the finalizer below destroys the GLXContext
(g_object_ref display)
(unless (and gtk3? (not widget)) (g_object_ref drawable))
(register-finalizer
ctxt
(λ (ctxt)
(define gl (send ctxt get-handle))
(define display (send ctxt get-gtk-display))
(define drawable (send ctxt get-gtk-drawable))
(define pixmap (send ctxt get-glx-pixmap))
(define xdisplay (gdk_x11_display_get_xdisplay display))
(when pixmap (glXDestroyGLXPixmap xdisplay pixmap))
(glXDestroyContext xdisplay gl)
(unless (and gtk3? (not widget)) (g_object_unref drawable))
(g_object_unref display)))
ctxt]
[else #f])]))
(define (make-gtk-widget-gl-context widget conf)
(atomically
(make-gtk-drawable-gl-context widget (widget-window widget) conf #t)))
(define (make-gtk-pixmap-gl-context pixmap conf)
(atomically
(make-gtk-drawable-gl-context #f pixmap conf #f)))
;; ===================================================================================================
(define widget-config-hash (make-weak-hasheq))
(define (prepare-widget-gl-context widget conf)
(hash-set! widget-config-hash widget (if conf conf (make-object gl-config%))))
(define (create-widget-gl-context widget)
(define conf (hash-ref widget-config-hash widget #f))
(and conf (make-gtk-widget-gl-context widget conf)))
(define-local-member-name
get-gdk-pixmap
install-gl-context)
(define (create-and-install-gl-context bm conf)
(define ctxt (make-gtk-pixmap-gl-context (send bm get-gdk-pixmap) conf))
(and ctxt (send bm install-gl-context ctxt)))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/mred/private/wx/gtk/gl-context.rkt | racket | ===================================================================================================
X11/GLX FFI
X #defines/typedefs/enums
GLX #defines/typedefs/enums
GLX_CONTEXT_FLAGS_ARB bits
===================================================================================================
-> positive-exact-rational
===================================================================================================
===================================================================================================
Getting OpenGL contexts
STUPIDITY ALERT
Apparently, the designers of glXCreateNewContext and glXCreateContextAttribsARB didn't trust us to
check return values or output arguments, so when these functions fail, they raise an X error and
send an error code to the X error handler. X errors, by default, *terminate the program* and print
an annoyingly vague, barely helpful error message.
This is especially bad with glXCreateContextAttribsARB, which always fails (i.e. crashes the
program) if we ask for an unsupported OpenGL version. Worse, this is the only way to find out
which OpenGL versions are available!
So we override the X error handler to silently fail, and sync right after the calls to make sure
the errors are processed immediately. With glXCreateContextAttribsARB, we then try the next lowest
happening out of sequence
OpenGL core versions we'll try to get, in order
happening out of sequence
===================================================================================================
_Display _GLXFBConfig int int -> int
If widget isn't #f, use its display and screen
Be aware: we may get double buffering even if we don't ask for it
too easy for user programs to fail to get a context
Get all framebuffer configs for this display and screen that match the requested attributes,
then sort them to put the best in front
abolute upper bound)
try to get a core-profile context
Otherwise use the old method
The above will return a direct rendering context when it can
indirect rendering may crash on some systems (notably mine)
=================================================================================================== | #lang racket/base
(require racket/class
racket/promise
racket/string
ffi/unsafe
ffi/unsafe/define
ffi/unsafe/alloc
ffi/cvector
(prefix-in draw: racket/draw/private/gl-context)
racket/draw/private/gl-config
"../../lock.rkt"
"types.rkt"
"utils.rkt"
"window.rkt"
"x11.rkt")
(provide
(protect-out prepare-widget-gl-context
create-widget-gl-context
create-and-install-gl-context
get-gdk-pixmap
install-gl-context))
(define (ffi-lib/complaint-on-failure name vers)
(ffi-lib name vers
#:fail (lambda ()
(log-warning "could not load library ~a ~a"
name vers)
#f)))
(define gl-lib (ffi-lib/complaint-on-failure "libGL" '("1" "")))
(define-ffi-definer define-glx gl-lib
#:default-make-fail make-not-available)
(define _Display (_cpointer 'Display))
(define _XErrorEvent (_cpointer 'XErrorEvent))
(define _XID _ulong)
(define True 1)
(define False 0)
(define None 0)
(define Success 0)
(define _GLXFBConfig (_cpointer 'GLXFBConfig))
(define _GLXContext (_cpointer/null 'GLXContext))
(define _XVisualInfo (_cpointer 'XVisualInfo))
Attribute tokens for glXGetConfig variants ( all GLX versions ):
(define GLX_DOUBLEBUFFER 5)
(define GLX_STEREO 6)
(define GLX_DEPTH_SIZE 12)
(define GLX_STENCIL_SIZE 13)
(define GLX_ACCUM_RED_SIZE 14)
(define GLX_ACCUM_GREEN_SIZE 15)
(define GLX_ACCUM_BLUE_SIZE 16)
(define GLX_ACCUM_ALPHA_SIZE 17)
GLX 1.3 and later :
(define GLX_X_RENDERABLE #x8012)
(define GLX_RGBA_TYPE #x8014)
GLX 1.4 and later :
(define GLX_SAMPLES #x186a1)
(define GLX_SAMPLE_BUFFERS #x186a0)
Attribute tokens for glXCreateContextAttribsARB ( also GLX 1.4 and later ):
(define GLX_CONTEXT_MAJOR_VERSION_ARB #x2091)
(define GLX_CONTEXT_MINOR_VERSION_ARB #x2092)
(define GLX_CONTEXT_FLAGS_ARB #x2094)
(define GLX_CONTEXT_PROFILE_MASK_ARB #x9126)
(define GLX_CONTEXT_DEBUG_BIT_ARB #x1)
(define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB #x2)
GLX_CONTEXT_PROFILE_MASK_ARB bits
(define GLX_CONTEXT_CORE_PROFILE_BIT_ARB #x1)
(define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB #x2)
(define-x11 XFree (_fun _pointer -> _int)
#:wrap (deallocator))
(define-x11 XSetErrorHandler
(_fun _fpointer -> _fpointer))
(define-x11 XSync
(_fun _Display _int -> _void))
(define-glx glXQueryVersion
(_fun _Display (major : (_ptr o _int)) (minor : (_ptr o _int))
-> (ret : _bool)
-> (values ret major minor)))
(define-glx glXQueryExtensionsString
(_fun _Display _int -> _string/utf-8))
(define-glx glXChooseFBConfig
(_fun _Display _int (_list i _int) (len : (_ptr o _int))
-> (_cvector o _GLXFBConfig len))
#:wrap (allocator (λ (v) (XFree (cvector-ptr v)))))
(define-glx glXGetFBConfigAttrib
(_fun _Display _GLXFBConfig _int (out : (_ptr o _int))
-> (ret : _int)
-> (values ret out)))
(define-glx glXCreateNewContext
(_fun _Display _GLXFBConfig _int _GLXContext _bool -> _GLXContext))
(define-glx glXDestroyContext
(_fun _Display _GLXContext -> _void))
(define-glx glXMakeCurrent
(_fun _Display _XID _GLXContext -> _bool))
(define-glx glXSwapBuffers
(_fun _Display _XID -> _void))
(define-glx glXIsDirect
(_fun _Display _GLXContext -> _bool))
(define-glx glXGetVisualFromFBConfig
(_fun _Display _GLXFBConfig -> _XVisualInfo)
#:wrap (allocator XFree))
(define-glx glXCreateGLXPixmap
(_fun _Display _XVisualInfo _XID -> _XID))
(define-glx glXDestroyGLXPixmap
(_fun _Display _XID -> _void))
(define-glx glXGetProcAddressARB
(_fun _string -> _pointer))
(define lazy-glXCreateContextAttribsARB
(delay
(function-ptr (glXGetProcAddressARB "glXCreateContextAttribsARB")
(_fun _Display _GLXFBConfig _GLXContext _bool (_list i _int)
-> _GLXContext))))
(define (glXCreateContextAttribsARB . args)
(apply (force lazy-glXCreateContextAttribsARB) args))
(define-gtk gtk_widget_get_display (_fun _GtkWidget -> _GdkDisplay))
(define-gtk gtk_widget_get_screen (_fun _GtkWidget -> _GdkScreen))
(define-glx glXSwapIntervalEXT (_fun _Display _XID _int -> _void)
#:fail (lambda () void))
GLX versions and extensions queries
(define lazy-get-glx-version
(delay
(define-values (worked? glx-major glx-minor)
(glXQueryVersion (gdk_x11_display_get_xdisplay (gdk_display_get_default))))
(unless worked?
(error 'get-glx-version "can't get GLX version using default display"))
(define glx-version (+ glx-major (/ glx-minor 10)))
(when (< glx-version #e1.3)
(error 'get-glx-version "need GLX version 1.3 or greater; given version ~a.~a"
glx-major glx-minor))
glx-version))
(define (get-glx-version)
(force lazy-get-glx-version))
(define lazy-glx-extensions
(delay
(define str
(glXQueryExtensionsString (gdk_x11_display_get_xdisplay (gdk_display_get_default))
(gdk_x11_screen_get_screen_number (gdk_screen_get_default))))
(string-split str)))
(define lazy-GLX_ARB_create_context?
(delay (member "GLX_ARB_create_context"
(force lazy-glx-extensions))))
(define lazy-GLX_ARB_create_context_profile?
(delay (member "GLX_ARB_create_context_profile"
(force lazy-glx-extensions))))
Wrapper for the _ GLXContext ( if we can get one from GLX )
(define gl-context%
(class draw:gl-context%
(init-field gl display drawable pixmap)
(define/override (get-handle) gl)
(define/public (get-gtk-display) display)
(define/public (get-gtk-drawable) drawable)
(define/public (get-glx-pixmap) pixmap)
(define (get-drawable-xid)
(if pixmap pixmap (gdk_x11_drawable_get_xid drawable)))
(define/override (draw:do-call-as-current t)
(define xdisplay (gdk_x11_display_get_xdisplay display))
(dynamic-wind
(lambda ()
(glXMakeCurrent xdisplay (get-drawable-xid) gl))
t
(lambda ()
(glXMakeCurrent xdisplay 0 #f))))
(define/override (draw:do-swap-buffers)
(glXSwapBuffers (gdk_x11_display_get_xdisplay display)
(get-drawable-xid)))
(super-new)))
OpenGL version . If all attempts to get a context fail , we return # f.
(define create-context-error? #f)
(define (flag-x-error-handler xdisplay xerrorevent)
(set! create-context-error? #t)
0)
_ Display _ GLXFBConfig _ GLXContext - > _ GLXContext
(define (glx-create-new-context xdisplay cfg share-gl)
Sync right now , or the sync further on could crash Racket with an [ xcb ] error about events
(XSync xdisplay False)
(define old-handler #f)
(define gl
(dynamic-wind
(λ ()
(set! old-handler
(XSetErrorHandler
(cast flag-x-error-handler
(_fun #:atomic? #t _Display _XErrorEvent -> _int)
_fpointer))))
(λ ()
(set! create-context-error? #f)
(glXCreateNewContext xdisplay cfg GLX_RGBA_TYPE share-gl #t))
(λ ()
Sync to ensure errors are processed
(XSync xdisplay False)
(XSetErrorHandler old-handler))))
(cond
[(and gl create-context-error?)
(log-error (string-append
"gl-context: glXCreateNewContext raised an error but (contrary to standards)"
" returned a non-NULL context; ignoring possibly corrupt context"))
#f]
[else
(unless gl
(log-warning "gl-context: glXCreateNewContext was unable to get an OpenGL context"))
gl]))
(define core-gl-versions '((4 5) (4 4) (4 3) (4 2) (4 1) (4 0) (3 3) (3 2) (3 1) (3 0)))
_ Display _ GLXFBConfig _ GLXContext ( List Byte Byte ) - > _ GLXContext
(define (glx-create-context-attribs xdisplay cfg share-gl gl-version)
Sync right now , or the sync further on could crash Racket with an [ xcb ] error about events
(XSync xdisplay False)
(define gl-major (car gl-version))
(define gl-minor (cadr gl-version))
(define context-attribs
(list GLX_CONTEXT_MAJOR_VERSION_ARB gl-major
GLX_CONTEXT_MINOR_VERSION_ARB gl-minor
GLX_CONTEXT_PROFILE_MASK_ARB GLX_CONTEXT_CORE_PROFILE_BIT_ARB
None))
(define old-handler #f)
(define gl
(dynamic-wind
(λ ()
(set! old-handler
(XSetErrorHandler
(cast flag-x-error-handler
(_fun #:atomic? #t _Display _XErrorEvent -> _int)
_fpointer))))
(λ ()
(set! create-context-error? #f)
(glXCreateContextAttribsARB xdisplay cfg share-gl #t context-attribs))
(λ ()
Sync to ensure errors are processed
(XSync xdisplay False)
(XSetErrorHandler old-handler))))
(cond
[(and gl create-context-error?)
(log-error (string-append
"gl-context: glXCreateContextAttribsARB raised an error for version ~a.~a but"
" (contrary to standards) returned a non-NULL context;"
" ignoring possibly corrupt context")
gl-major gl-minor)
#f]
[else
(unless gl
(log-info "gl-context: glXCreateContextAttribsARB returned NULL for version ~a.~a"
gl-major gl-minor))
gl]))
_ Display _ GLXFBConfig _ GLXContext - > _ GLXContext
(define (glx-create-core-context xdisplay cfg share-gl)
(let/ec return
(for ([gl-version (in-list core-gl-versions)])
(define gl (glx-create-context-attribs xdisplay cfg share-gl gl-version))
(when gl (return gl)))
(log-warning "gl-context: unable to get core context; falling back")
(glx-create-new-context xdisplay cfg share-gl)))
( or / c # f _ GtkWidget ) - > _ GdkDisplay
(define (gtk-maybe-widget-get-display widget)
(cond [widget (gtk_widget_get_display widget)]
[else (gdk_display_get_default)]))
( or / c # f _ GtkWidget ) - > _ GdkScreen
(define (gtk-maybe-widget-get-screen widget)
(cond [widget (gtk_widget_get_screen widget)]
[else (gdk_screen_get_default)]))
(define (glx-get-fbconfig-attrib xdisplay cfg attrib bad-value)
(define-values (err value) (glXGetFBConfigAttrib xdisplay cfg attrib))
(if (= err Success) value bad-value))
( or / c # f _ GtkWidget ) _ GdkDrawable gl - config% boolean ? - > gl - context%
where _ GdkDrawable = ( or / c _ GtkWindow _ )
(define (make-gtk-drawable-gl-context widget drawable conf wants-double?)
(define glx-version (get-glx-version))
(define display (gtk-maybe-widget-get-display widget))
(define screen (gtk-maybe-widget-get-screen widget))
Get the X objects wrapped by the GDK objects
(define xdisplay (gdk_x11_display_get_xdisplay display))
(define xscreen (gdk_x11_screen_get_screen_number screen))
Create an attribute list using the GL config
(define xattribs
(append
(if wants-double?
(if (send conf get-double-buffered) (list GLX_DOUBLEBUFFER True) null)
null)
(if (send conf get-stereo) (list GLX_STEREO True) null)
Finish out with standard GLX 1.3 attributes
(list
yes , we want to use OpenGL to render today
GLX_DEPTH_SIZE (send conf get-depth-size)
GLX_STENCIL_SIZE (send conf get-stencil-size)
GLX_ACCUM_RED_SIZE (send conf get-accum-size)
GLX_ACCUM_GREEN_SIZE (send conf get-accum-size)
GLX_ACCUM_BLUE_SIZE (send conf get-accum-size)
GLX_ACCUM_ALPHA_SIZE (send conf get-accum-size)
GLX_SAMPLES is handled below - GLX regards it as an absolute lower bound , which makes it
None)))
(define multisample-size (send conf get-multisample-size))
GLX already sorts them pretty well , so we just need a stable sort on multisamples at the moment
(define cfgs
(let* ([cfgs (cvector->list (glXChooseFBConfig xdisplay xscreen xattribs))]
Keep all configs with multisample size < = requested ( i.e. make multisample - size an
[cfgs (if (< glx-version #e1.4)
cfgs
(filter (λ (cfg)
(define m (glx-get-fbconfig-attrib xdisplay cfg GLX_SAMPLES 0))
(<= m multisample-size))
cfgs))]
Sort all configs by multisample size , decreasing
[cfgs (if (< glx-version #e1.4)
cfgs
(sort cfgs >
#:key (λ (cfg) (glx-get-fbconfig-attrib xdisplay cfg GLX_SAMPLES 0))
#:cache-keys? #t))])
cfgs))
(cond
[(null? cfgs) #f]
[else
The framebuffer configs are sorted best - first , so choose the first
(define cfg (car cfgs))
(define share-gl
(let ([share-ctxt (send conf get-share-context)])
(and share-ctxt (send share-ctxt get-handle))))
Get a GL context
(define gl
(if (and (>= glx-version #e1.4)
(not (send conf get-legacy?))
(force lazy-GLX_ARB_create_context?)
(force lazy-GLX_ARB_create_context_profile?))
If the GLX version is high enough , legacy ? is # f , and GLX has the right extensions ,
(glx-create-core-context xdisplay cfg share-gl)
(glx-create-new-context xdisplay cfg share-gl)))
If it does n't , the context will be version 1.4 or lower , unless GLX is implemented with
proprietary extensions ( NVIDIA 's drivers sometimes do this )
(when (and widget (send conf get-sync-swap))
(glXSwapIntervalEXT xdisplay (gdk_x11_drawable_get_xid drawable) 1))
Now wrap the GLX context in a gl - context%
(cond
[gl
If there 's no widget , this is for a pixmap , so get the stupid GLX wrapper for it or
(define pixmap
(if widget #f (glXCreateGLXPixmap xdisplay
(glXGetVisualFromFBConfig xdisplay cfg)
(if gtk3?
(cast drawable _Pixmap _ulong)
(gdk_x11_drawable_get_xid drawable)))))
(define ctxt (new gl-context% [gl gl] [display display] [drawable drawable] [pixmap pixmap]))
Refcount these so they do n't go away until the finalizer below destroys the GLXContext
(g_object_ref display)
(unless (and gtk3? (not widget)) (g_object_ref drawable))
(register-finalizer
ctxt
(λ (ctxt)
(define gl (send ctxt get-handle))
(define display (send ctxt get-gtk-display))
(define drawable (send ctxt get-gtk-drawable))
(define pixmap (send ctxt get-glx-pixmap))
(define xdisplay (gdk_x11_display_get_xdisplay display))
(when pixmap (glXDestroyGLXPixmap xdisplay pixmap))
(glXDestroyContext xdisplay gl)
(unless (and gtk3? (not widget)) (g_object_unref drawable))
(g_object_unref display)))
ctxt]
[else #f])]))
(define (make-gtk-widget-gl-context widget conf)
(atomically
(make-gtk-drawable-gl-context widget (widget-window widget) conf #t)))
(define (make-gtk-pixmap-gl-context pixmap conf)
(atomically
(make-gtk-drawable-gl-context #f pixmap conf #f)))
(define widget-config-hash (make-weak-hasheq))
(define (prepare-widget-gl-context widget conf)
(hash-set! widget-config-hash widget (if conf conf (make-object gl-config%))))
(define (create-widget-gl-context widget)
(define conf (hash-ref widget-config-hash widget #f))
(and conf (make-gtk-widget-gl-context widget conf)))
(define-local-member-name
get-gdk-pixmap
install-gl-context)
(define (create-and-install-gl-context bm conf)
(define ctxt (make-gtk-pixmap-gl-context (send bm get-gdk-pixmap) conf))
(and ctxt (send bm install-gl-context ctxt)))
|
cd19395de28c3fd6025067e67ee72603c196b8848270e1b971ecf5bb9959a283 | yonatane/bytegeist | project.clj | (defproject bytegeist "0.1.0-SNAPSHOT"
:description "Binary protocol specs for clojure"
:url ""
:license {:name "MIT License"}
:deploy-repositories [["releases" {:url ""
:sign-releases false
:username :env/clojars_user
:password :env/clojars_pass}]
["snapshots" {:url ""
:username :env/clojars_user
:password :env/clojars_pass}]]
:dependencies [[org.clojure/clojure "1.10.1"]
[io.netty/netty-buffer "4.1.49.Final"]]
:profiles {:dev {:source-paths ["dev"]
:dependencies [[org.clojure/tools.namespace "1.0.0"]
[criterium "0.4.5"]
[com.clojure-goes-fast/clj-async-profiler "0.4.1"]]}}
:java-source-paths ["src-java"]
:repl-options {:init-ns bytegeist.dev}
:global-vars {*warn-on-reflection* true}
:pedantic? :abort)
| null | https://raw.githubusercontent.com/yonatane/bytegeist/ba3355965b88a4b4882503e9c3919eba4623d862/project.clj | clojure | (defproject bytegeist "0.1.0-SNAPSHOT"
:description "Binary protocol specs for clojure"
:url ""
:license {:name "MIT License"}
:deploy-repositories [["releases" {:url ""
:sign-releases false
:username :env/clojars_user
:password :env/clojars_pass}]
["snapshots" {:url ""
:username :env/clojars_user
:password :env/clojars_pass}]]
:dependencies [[org.clojure/clojure "1.10.1"]
[io.netty/netty-buffer "4.1.49.Final"]]
:profiles {:dev {:source-paths ["dev"]
:dependencies [[org.clojure/tools.namespace "1.0.0"]
[criterium "0.4.5"]
[com.clojure-goes-fast/clj-async-profiler "0.4.1"]]}}
:java-source-paths ["src-java"]
:repl-options {:init-ns bytegeist.dev}
:global-vars {*warn-on-reflection* true}
:pedantic? :abort)
|
|
d240d2d6e577569080c5a190b23e910db85bb6407c138f0bf8ff083f8f0bb226 | Opetushallitus/ataru | valintatulosservice_service.clj | (ns ataru.valinta-tulos-service.valintatulosservice_service
(:require [ataru.valinta-tulos-service.valintatulosservice-client :as client]
[ataru.valinta-tulos-service.valintatulosservice-protocol :refer [ValintaTulosService]]
[clojure.set :refer [union]]))
(defn- get-hakukohteen-ehdolliset
[cas-client hakukohde-oid]
(let [hakukohteessa (future
(client/get-hyvaksynnan-ehto-hakukohteessa
cas-client
hakukohde-oid))
valintatapajonoissa (client/get-hyvaksynnan-ehto-valintatapajonoissa
cas-client
hakukohde-oid)]
(apply union
(set (keys @hakukohteessa))
(map #(set (keys %))
(vals valintatapajonoissa)))))
(defrecord RemoteValintaTulosService [cas-client valinta-laskenta-service]
ValintaTulosService
(hakukohteen-ehdolliset [_ hakukohde-oid]
(get-hakukohteen-ehdolliset cas-client hakukohde-oid))
(valinnan-tulos-hakemukselle [_ haku-oid hakemus-oid]
(client/get-valinnan-tulos-hakemukselle cas-client haku-oid hakemus-oid)))
| null | https://raw.githubusercontent.com/Opetushallitus/ataru/27f650e0665e2735aab0c4059f766a3fb2826246/src/clj/ataru/valinta_tulos_service/valintatulosservice_service.clj | clojure | (ns ataru.valinta-tulos-service.valintatulosservice_service
(:require [ataru.valinta-tulos-service.valintatulosservice-client :as client]
[ataru.valinta-tulos-service.valintatulosservice-protocol :refer [ValintaTulosService]]
[clojure.set :refer [union]]))
(defn- get-hakukohteen-ehdolliset
[cas-client hakukohde-oid]
(let [hakukohteessa (future
(client/get-hyvaksynnan-ehto-hakukohteessa
cas-client
hakukohde-oid))
valintatapajonoissa (client/get-hyvaksynnan-ehto-valintatapajonoissa
cas-client
hakukohde-oid)]
(apply union
(set (keys @hakukohteessa))
(map #(set (keys %))
(vals valintatapajonoissa)))))
(defrecord RemoteValintaTulosService [cas-client valinta-laskenta-service]
ValintaTulosService
(hakukohteen-ehdolliset [_ hakukohde-oid]
(get-hakukohteen-ehdolliset cas-client hakukohde-oid))
(valinnan-tulos-hakemukselle [_ haku-oid hakemus-oid]
(client/get-valinnan-tulos-hakemukselle cas-client haku-oid hakemus-oid)))
|
|
2a1a799bdbb346991b94ec260f926f2e0d2fb0905e69662edb86bcb6ece5fffd | dparis/gen-phzr | array_utils.cljs | (ns phzr.array-utils
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [shuffle]))
(defn find-closest-
"Snaps a value to the nearest value in an array.
The result will always be in the range `[first_value, last_value]`.
Parameters:
* value (number) - The search value
* arr (Array.<number>) - The input array which _must_ be sorted.
Returns: number - The nearest value found."
([value arr]
(phaser->clj
(.findClosest js/Phaser.ArrayUtils
(clj->phaser value)
(clj->phaser arr)))))
(defn get-random-item-
"Fetch a random entry from the given array.
Will return null if there are no array items that fall within the specified range
or if there is no item for the randomly choosen index.
Parameters:
* objects (Array.<any>) - An array of objects.
* start-index (integer) - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
* length (integer) - Optional restriction on the number of values you want to randomly select from.
Returns: object - The random object that was selected."
([objects start-index length]
(phaser->clj
(.getRandomItem js/Phaser.ArrayUtils
(clj->phaser objects)
(clj->phaser start-index)
(clj->phaser length)))))
(defn number-array-
"Create an array representing the inclusive range of numbers (usually integers) in `[start, end]`.
This is equivalent to `numberArrayStep(start, end, 1)`.
Parameters:
* start (number) - The minimum value the array starts with.
* end (number) - The maximum value the array contains.
Returns: Array.<number> - The array of number values."
([start end]
(phaser->clj
(.numberArray js/Phaser.ArrayUtils
(clj->phaser start)
(clj->phaser end)))))
(defn number-array-step-
"Create an array of numbers (positive and/or negative) progressing from `start`
up to but not including `end` by advancing by `step`.
If `start` is less than `stop` a zero-length range is created unless a negative `step` is specified.
Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0;
for forward compatibility make sure to pass in actual numbers.
Parameters:
* start (number) - The start of the range.
* end (number) - The end of the range.
* step (number) {optional} - The value to increment or decrement by.
Returns: Array - Returns the new array of numbers."
([start end]
(phaser->clj
(.numberArrayStep js/Phaser.ArrayUtils
(clj->phaser start)
(clj->phaser end))))
([start end step]
(phaser->clj
(.numberArrayStep js/Phaser.ArrayUtils
(clj->phaser start)
(clj->phaser end)
(clj->phaser step)))))
(defn remove-random-item-
"Removes a random object from the given array and returns it.
Will return null if there are no array items that fall within the specified range
or if there is no item for the randomly choosen index.
Parameters:
* objects (Array.<any>) - An array of objects.
* start-index (integer) - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
* length (integer) - Optional restriction on the number of values you want to randomly select from.
Returns: object - The random object that was removed."
([objects start-index length]
(phaser->clj
(.removeRandomItem js/Phaser.ArrayUtils
(clj->phaser objects)
(clj->phaser start-index)
(clj->phaser length)))))
(defn rotate-
"Moves the element from the start of the array to the end, shifting all items in the process.
The 'rotation' happens to the left.
Parameters:
* array (Array.<any>) - The array to shift/rotate. The array is modified.
Returns: any - The shifted value."
([array]
(phaser->clj
(.rotate js/Phaser.ArrayUtils
(clj->phaser array)))))
(defn rotate-matrix-
"Rotates the given matrix (array of arrays).
Based on the routine from {@link /}.
Parameters:
* matrix (Array.<Array.<any>>) - The array to rotate; this matrix _may_ be altered.
* direction (number | string) - The amount to rotate: the roation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180').
Returns: Array.<Array.<any>> - The rotated matrix. The source matrix should be discarded for the returned matrix."
([matrix direction]
(phaser->clj
(.rotateMatrix js/Phaser.ArrayUtils
(clj->phaser matrix)
(clj->phaser direction)))))
(defn shuffle-
"A standard Fisher-Yates Array shuffle implementation which modifies the array in place.
Parameters:
* array (Array.<any>) - The array to shuffle.
Returns: Array.<any> - The original array, now shuffled."
([array]
(phaser->clj
(.shuffle js/Phaser.ArrayUtils
(clj->phaser array)))))
(defn transpose-matrix-
"Transposes the elements of the given matrix (array of arrays).
Parameters:
* array (Array.<Array.<any>>) - The matrix to transpose.
Returns: Array.<Array.<any>> - A new transposed matrix"
([array]
(phaser->clj
(.transposeMatrix js/Phaser.ArrayUtils
(clj->phaser array))))) | null | https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/array_utils.cljs | clojure |
this matrix _may_ be altered. | (ns phzr.array-utils
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [shuffle]))
(defn find-closest-
"Snaps a value to the nearest value in an array.
The result will always be in the range `[first_value, last_value]`.
Parameters:
* value (number) - The search value
* arr (Array.<number>) - The input array which _must_ be sorted.
Returns: number - The nearest value found."
([value arr]
(phaser->clj
(.findClosest js/Phaser.ArrayUtils
(clj->phaser value)
(clj->phaser arr)))))
(defn get-random-item-
"Fetch a random entry from the given array.
Will return null if there are no array items that fall within the specified range
or if there is no item for the randomly choosen index.
Parameters:
* objects (Array.<any>) - An array of objects.
* start-index (integer) - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
* length (integer) - Optional restriction on the number of values you want to randomly select from.
Returns: object - The random object that was selected."
([objects start-index length]
(phaser->clj
(.getRandomItem js/Phaser.ArrayUtils
(clj->phaser objects)
(clj->phaser start-index)
(clj->phaser length)))))
(defn number-array-
"Create an array representing the inclusive range of numbers (usually integers) in `[start, end]`.
This is equivalent to `numberArrayStep(start, end, 1)`.
Parameters:
* start (number) - The minimum value the array starts with.
* end (number) - The maximum value the array contains.
Returns: Array.<number> - The array of number values."
([start end]
(phaser->clj
(.numberArray js/Phaser.ArrayUtils
(clj->phaser start)
(clj->phaser end)))))
(defn number-array-step-
"Create an array of numbers (positive and/or negative) progressing from `start`
up to but not including `end` by advancing by `step`.
If `start` is less than `stop` a zero-length range is created unless a negative `step` is specified.
for forward compatibility make sure to pass in actual numbers.
Parameters:
* start (number) - The start of the range.
* end (number) - The end of the range.
* step (number) {optional} - The value to increment or decrement by.
Returns: Array - Returns the new array of numbers."
([start end]
(phaser->clj
(.numberArrayStep js/Phaser.ArrayUtils
(clj->phaser start)
(clj->phaser end))))
([start end step]
(phaser->clj
(.numberArrayStep js/Phaser.ArrayUtils
(clj->phaser start)
(clj->phaser end)
(clj->phaser step)))))
(defn remove-random-item-
"Removes a random object from the given array and returns it.
Will return null if there are no array items that fall within the specified range
or if there is no item for the randomly choosen index.
Parameters:
* objects (Array.<any>) - An array of objects.
* start-index (integer) - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
* length (integer) - Optional restriction on the number of values you want to randomly select from.
Returns: object - The random object that was removed."
([objects start-index length]
(phaser->clj
(.removeRandomItem js/Phaser.ArrayUtils
(clj->phaser objects)
(clj->phaser start-index)
(clj->phaser length)))))
(defn rotate-
"Moves the element from the start of the array to the end, shifting all items in the process.
The 'rotation' happens to the left.
Parameters:
* array (Array.<any>) - The array to shift/rotate. The array is modified.
Returns: any - The shifted value."
([array]
(phaser->clj
(.rotate js/Phaser.ArrayUtils
(clj->phaser array)))))
(defn rotate-matrix-
"Rotates the given matrix (array of arrays).
Based on the routine from {@link /}.
Parameters:
* direction (number | string) - The amount to rotate: the roation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180').
Returns: Array.<Array.<any>> - The rotated matrix. The source matrix should be discarded for the returned matrix."
([matrix direction]
(phaser->clj
(.rotateMatrix js/Phaser.ArrayUtils
(clj->phaser matrix)
(clj->phaser direction)))))
(defn shuffle-
"A standard Fisher-Yates Array shuffle implementation which modifies the array in place.
Parameters:
* array (Array.<any>) - The array to shuffle.
Returns: Array.<any> - The original array, now shuffled."
([array]
(phaser->clj
(.shuffle js/Phaser.ArrayUtils
(clj->phaser array)))))
(defn transpose-matrix-
"Transposes the elements of the given matrix (array of arrays).
Parameters:
* array (Array.<Array.<any>>) - The matrix to transpose.
Returns: Array.<Array.<any>> - A new transposed matrix"
([array]
(phaser->clj
(.transposeMatrix js/Phaser.ArrayUtils
(clj->phaser array))))) |
136283bbc485c48706e466585827af647b8eb8b180eab4134f278a511a110263 | softwarelanguageslab/maf | trapr.scm | (define NumWorkers (int-top))
(define Precision (int-top))
(define L (int-top))
(define R (int-top))
(define (exp x)
(expt 2.718281828459045 x))
(define (fx x)
(let* ((a (sin (- (expt x 3) 1)))
(b (+ x 1))
(c (/ a b))
(d (sqrt (+ 1 (exp (sqrt (* 2 x))))))
(r (* c d)))
r))
(define (compute-area l r h)
(let ((n (inexact->exact (floor (/ (abs (- r l)) h)))))
(letrec ((loop (lambda (i acc)
(if (= i n)
acc
(let* ((lx (+ (* i h) l))
(rx (+ lx h))
(ly (fx lx))
(ry (fx rx)))
(loop (+ i 1) (+ acc (* 0.5 (+ ly ry) h))))))))
(loop 0 0))))
(define (build-vector n f)
(letrec ((v (make-vector n #f))
(loop (lambda (i)
(if (< i n)
(begin
(vector-set! v i (f i))
(loop (+ i 1)))
v))))
(loop 0)))
(define master-actor
(actor "master-actor" (workers terms-received result-area)
;; (start (workers)
;; (become master-actor workers terms-received result-area))
(result (v id)
(if (= (+ terms-received 1) NumWorkers)
(terminate)
(become master-actor workers (+ terms-received 1) (+ result-area v))))
(work (l r h)
(let ((range (/ (- r l) NumWorkers)))
(letrec ((loop (lambda (i)
(if (= i NumWorkers)
(become master-actor workers terms-received result-area)
(let* ((wl (+ (* range i) l))
(wr (+ wl range)))
(send (vector-ref workers i) work wl wr h)
(loop (+ i 1)))))))
(loop 0))))))
(define master-actor-init
(actor "master-actor-init" ()
(start ()
(let ((workers (build-vector NumWorkers (lambda (i) (create worker-actor master i)))))
(send a/self work L R Precision)
(become master-actor workers 0 0)))))
(define worker-actor
(actor "worker-actor" (master id)
(work (l r h)
(let ((area (compute-area l r h)))
(send master result area id)
(terminate)))))
;; (define master (create master-actor #f 0 0))
;; (send master start )
(define master (create master-actor-init))
(send master start)
| null | https://raw.githubusercontent.com/softwarelanguageslab/maf/be58e02c63d25cab5b48fdf7b737b68b882e9dca/test/concurrentScheme/actors/contracts/savina/trapr.scm | scheme | (start (workers)
(become master-actor workers terms-received result-area))
(define master (create master-actor #f 0 0))
(send master start ) | (define NumWorkers (int-top))
(define Precision (int-top))
(define L (int-top))
(define R (int-top))
(define (exp x)
(expt 2.718281828459045 x))
(define (fx x)
(let* ((a (sin (- (expt x 3) 1)))
(b (+ x 1))
(c (/ a b))
(d (sqrt (+ 1 (exp (sqrt (* 2 x))))))
(r (* c d)))
r))
(define (compute-area l r h)
(let ((n (inexact->exact (floor (/ (abs (- r l)) h)))))
(letrec ((loop (lambda (i acc)
(if (= i n)
acc
(let* ((lx (+ (* i h) l))
(rx (+ lx h))
(ly (fx lx))
(ry (fx rx)))
(loop (+ i 1) (+ acc (* 0.5 (+ ly ry) h))))))))
(loop 0 0))))
(define (build-vector n f)
(letrec ((v (make-vector n #f))
(loop (lambda (i)
(if (< i n)
(begin
(vector-set! v i (f i))
(loop (+ i 1)))
v))))
(loop 0)))
(define master-actor
(actor "master-actor" (workers terms-received result-area)
(result (v id)
(if (= (+ terms-received 1) NumWorkers)
(terminate)
(become master-actor workers (+ terms-received 1) (+ result-area v))))
(work (l r h)
(let ((range (/ (- r l) NumWorkers)))
(letrec ((loop (lambda (i)
(if (= i NumWorkers)
(become master-actor workers terms-received result-area)
(let* ((wl (+ (* range i) l))
(wr (+ wl range)))
(send (vector-ref workers i) work wl wr h)
(loop (+ i 1)))))))
(loop 0))))))
(define master-actor-init
(actor "master-actor-init" ()
(start ()
(let ((workers (build-vector NumWorkers (lambda (i) (create worker-actor master i)))))
(send a/self work L R Precision)
(become master-actor workers 0 0)))))
(define worker-actor
(actor "worker-actor" (master id)
(work (l r h)
(let ((area (compute-area l r h)))
(send master result area id)
(terminate)))))
(define master (create master-actor-init))
(send master start)
|
a865766321b9838c6f0a8b3c8a11b17807bb73103cf3f8834d66189d49a36bf0 | g-andrade/aequitas | aequitas_sup.erl | Copyright ( c ) 2018 - 2022
%%
%% Permission is hereby granted, free of charge, to any person obtaining a
%% copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction , including without limitation
%% the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software , and to permit persons to whom the
%% Software is furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
%% DEALINGS IN THE SOFTWARE.
@private
-module(aequitas_sup).
-behaviour(supervisor).
%% ------------------------------------------------------------------
%% API Function Exports
%% ------------------------------------------------------------------
-export(
[start_link/0
]).
-ignore_xref(
[start_link/0
]).
%% ------------------------------------------------------------------
supervisor Function Exports
%% ------------------------------------------------------------------
-export(
[init/1
]).
%% ------------------------------------------------------------------
Macro Definitions
%% ------------------------------------------------------------------
-define(SERVER, ?MODULE).
%% ------------------------------------------------------------------
%% API Function Definitions
%% ------------------------------------------------------------------
-spec start_link() -> {ok, pid()}.
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%% ------------------------------------------------------------------
%% supervisor Function Definitions
%% ------------------------------------------------------------------
-spec init([]) -> {ok, {supervisor:sup_flags(),
[supervisor:child_spec(), ...]}}.
init([]) ->
SupFlags =
#{ strategy => rest_for_one,
intensity => 10,
period => 1
},
ChildSpecs =
[#{ id => proc_reg,
start => {aequitas_proc_reg, start_link, []}
},
#{ id => cfg,
start => {aequitas_cfg, start_link, []}
},
#{ id => work_stats_sup,
start => {aequitas_work_stats_sup, start_link, []},
type => supervisor
},
#{ id => category_sup,
start => {aequitas_category_sup, start_link, []},
type => supervisor
},
#{ id => boot_categories,
start => {aequitas_boot_categories, start_link, []}
}],
{ok, {SupFlags, ChildSpecs}}.
| null | https://raw.githubusercontent.com/g-andrade/aequitas/35c446847e2827a478844231c671e0a52bbed2c5/src/aequitas_sup.erl | erlang |
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------
API Function Exports
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
API Function Definitions
------------------------------------------------------------------
------------------------------------------------------------------
supervisor Function Definitions
------------------------------------------------------------------ | Copyright ( c ) 2018 - 2022
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
@private
-module(aequitas_sup).
-behaviour(supervisor).
-export(
[start_link/0
]).
-ignore_xref(
[start_link/0
]).
supervisor Function Exports
-export(
[init/1
]).
Macro Definitions
-define(SERVER, ?MODULE).
-spec start_link() -> {ok, pid()}.
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
-spec init([]) -> {ok, {supervisor:sup_flags(),
[supervisor:child_spec(), ...]}}.
init([]) ->
SupFlags =
#{ strategy => rest_for_one,
intensity => 10,
period => 1
},
ChildSpecs =
[#{ id => proc_reg,
start => {aequitas_proc_reg, start_link, []}
},
#{ id => cfg,
start => {aequitas_cfg, start_link, []}
},
#{ id => work_stats_sup,
start => {aequitas_work_stats_sup, start_link, []},
type => supervisor
},
#{ id => category_sup,
start => {aequitas_category_sup, start_link, []},
type => supervisor
},
#{ id => boot_categories,
start => {aequitas_boot_categories, start_link, []}
}],
{ok, {SupFlags, ChildSpecs}}.
|
58c81353fdc648fa49434a4ac56b0bfadfb796cf18bbe32b7ef9a3c5d9b73349 | quil-lang/qvm | utilities.lisp | ;;;; utilities.lisp
;;;;
Author :
(in-package #:qvm-app)
(defun slurp-lines (&optional (stream *standard-input*))
(flet ((line () (read-line stream nil nil nil)))
(with-output-to-string (s)
(loop :for line := (line) :then (line)
:while line
:do (write-line line s)))))
(defmacro with-timeout (&body body)
(let ((f (gensym "TIME-LIMITED-BODY-")))
`(flet ((,f () ,@body))
(declare (dynamic-extent (function ,f)))
(if (null *time-limit*)
(,f)
(bt:with-timeout (*time-limit*)
(,f))))))
(defmacro with-timing ((var) &body body)
(let ((start (gensym "START-")))
`(let ((,start (get-internal-real-time)))
(multiple-value-prog1 (progn ,@body)
(setf ,var (round (* 1000 (- (get-internal-real-time) ,start))
internal-time-units-per-second))))))
(defun slurp-stream (stream)
(with-output-to-string (s)
(loop :for byte := (read-byte stream nil nil) :then (read-byte stream nil nil)
:until (null byte)
:do (write-char (code-char byte) s))))
(defun keywordify (str)
(intern (string-upcase str) :keyword))
(declaim (inline write-64-be))
(defun write-64-be (byte stream)
"Write the 64-bit unsigned-byte BYTE to the binary stream STREAM."
(declare (optimize speed (safety 0) (debug 0))
(type (unsigned-byte 64) byte))
(let ((a (ldb (byte 8 0) byte))
(b (ldb (byte 8 8) byte))
(c (ldb (byte 8 16) byte))
(d (ldb (byte 8 24) byte))
(e (ldb (byte 8 32) byte))
(f (ldb (byte 8 40) byte))
(g (ldb (byte 8 48) byte))
(h (ldb (byte 8 56) byte)))
(declare (type (unsigned-byte 8) a b c d e f g h))
(write-byte h stream)
(write-byte g stream)
(write-byte f stream)
(write-byte e stream)
(write-byte d stream)
(write-byte c stream)
(write-byte b stream)
(write-byte a stream)
nil))
(declaim (inline write-complex-double-float-as-binary))
(defun write-complex-double-float-as-binary (z stream)
"Take a complex double-float and write to STREAM its binary representation in big endian (total 16 octets)."
(declare #.qvm::*optimize-dangerously-fast*
(type (complex double-float) z))
(let ((re (realpart z))
(im (imagpart z)))
(declare (type double-float re im)
(dynamic-extent re im))
(let ((encoded-re (ieee-floats:encode-float64 re))
(encoded-im (ieee-floats:encode-float64 im)))
(declare (type (unsigned-byte 64) encoded-re encoded-im)
(dynamic-extent encoded-re encoded-im))
(write-64-be encoded-re stream)
(write-64-be encoded-im stream))))
(declaim (inline write-double-float-as-binary))
(defun write-double-float-as-binary (x stream)
"Take a double-float and write to STREAM its binary representation in big endian (total 8 octets)."
(declare #.qvm::*optimize-dangerously-fast*
(type double-float x))
(let ((encoded (ieee-floats:encode-float64 x)))
(declare (type (unsigned-byte 64) encoded)
(dynamic-extent encoded))
(write-64-be encoded stream)))
(defun encode-list-as-json-list (list stream)
(if (endp list)
(format stream "[]")
(yason:encode list stream)))
;;; Functions depending on the server state
(defun session-info ()
(if (or (not (boundp 'tbnl:*session*))
(null tbnl:*session*))
""
(format nil
"[~A Session:~D] "
(tbnl:session-remote-addr tbnl:*session*)
(tbnl:session-id tbnl:*session*))))
(global-vars:define-global-var **log-lock** (bt:make-lock "Log Lock"))
(defmacro with-locked-log (() &body body)
`(bt:with-lock-held (**log-lock**)
,@body))
(defmacro format-log (level-or-fmt-string &rest fmt-string-or-args)
"Send a message to syslog. If the first argument LEVEL-OR-FMT-STRING is a
keyword it is assumed to be a non-default log level (:debug), otherwise it is a control
string followed by optional args (as in FORMAT)."
(when (keywordp level-or-fmt-string)
;; Sanity check that it's a valid log level at macroexpansion
;; time.
(cl-syslog:get-priority level-or-fmt-string))
(if (keywordp level-or-fmt-string)
`(with-locked-log ()
(cl-syslog:format-log
*logger*
',level-or-fmt-string
"~A~@?"
(session-info)
,@fmt-string-or-args))
`(with-locked-log ()
(cl-syslog:format-log
*logger*
':debug
"~A~@?"
(session-info)
,level-or-fmt-string
,@fmt-string-or-args))))
| null | https://raw.githubusercontent.com/quil-lang/qvm/de95ead6e7df70a1f8e0212455a802bd0cef201c/app/src/utilities.lisp | lisp | utilities.lisp
Functions depending on the server state
Sanity check that it's a valid log level at macroexpansion
time. | Author :
(in-package #:qvm-app)
(defun slurp-lines (&optional (stream *standard-input*))
(flet ((line () (read-line stream nil nil nil)))
(with-output-to-string (s)
(loop :for line := (line) :then (line)
:while line
:do (write-line line s)))))
(defmacro with-timeout (&body body)
(let ((f (gensym "TIME-LIMITED-BODY-")))
`(flet ((,f () ,@body))
(declare (dynamic-extent (function ,f)))
(if (null *time-limit*)
(,f)
(bt:with-timeout (*time-limit*)
(,f))))))
(defmacro with-timing ((var) &body body)
(let ((start (gensym "START-")))
`(let ((,start (get-internal-real-time)))
(multiple-value-prog1 (progn ,@body)
(setf ,var (round (* 1000 (- (get-internal-real-time) ,start))
internal-time-units-per-second))))))
(defun slurp-stream (stream)
(with-output-to-string (s)
(loop :for byte := (read-byte stream nil nil) :then (read-byte stream nil nil)
:until (null byte)
:do (write-char (code-char byte) s))))
(defun keywordify (str)
(intern (string-upcase str) :keyword))
(declaim (inline write-64-be))
(defun write-64-be (byte stream)
"Write the 64-bit unsigned-byte BYTE to the binary stream STREAM."
(declare (optimize speed (safety 0) (debug 0))
(type (unsigned-byte 64) byte))
(let ((a (ldb (byte 8 0) byte))
(b (ldb (byte 8 8) byte))
(c (ldb (byte 8 16) byte))
(d (ldb (byte 8 24) byte))
(e (ldb (byte 8 32) byte))
(f (ldb (byte 8 40) byte))
(g (ldb (byte 8 48) byte))
(h (ldb (byte 8 56) byte)))
(declare (type (unsigned-byte 8) a b c d e f g h))
(write-byte h stream)
(write-byte g stream)
(write-byte f stream)
(write-byte e stream)
(write-byte d stream)
(write-byte c stream)
(write-byte b stream)
(write-byte a stream)
nil))
(declaim (inline write-complex-double-float-as-binary))
(defun write-complex-double-float-as-binary (z stream)
"Take a complex double-float and write to STREAM its binary representation in big endian (total 16 octets)."
(declare #.qvm::*optimize-dangerously-fast*
(type (complex double-float) z))
(let ((re (realpart z))
(im (imagpart z)))
(declare (type double-float re im)
(dynamic-extent re im))
(let ((encoded-re (ieee-floats:encode-float64 re))
(encoded-im (ieee-floats:encode-float64 im)))
(declare (type (unsigned-byte 64) encoded-re encoded-im)
(dynamic-extent encoded-re encoded-im))
(write-64-be encoded-re stream)
(write-64-be encoded-im stream))))
(declaim (inline write-double-float-as-binary))
(defun write-double-float-as-binary (x stream)
"Take a double-float and write to STREAM its binary representation in big endian (total 8 octets)."
(declare #.qvm::*optimize-dangerously-fast*
(type double-float x))
(let ((encoded (ieee-floats:encode-float64 x)))
(declare (type (unsigned-byte 64) encoded)
(dynamic-extent encoded))
(write-64-be encoded stream)))
(defun encode-list-as-json-list (list stream)
(if (endp list)
(format stream "[]")
(yason:encode list stream)))
(defun session-info ()
(if (or (not (boundp 'tbnl:*session*))
(null tbnl:*session*))
""
(format nil
"[~A Session:~D] "
(tbnl:session-remote-addr tbnl:*session*)
(tbnl:session-id tbnl:*session*))))
(global-vars:define-global-var **log-lock** (bt:make-lock "Log Lock"))
(defmacro with-locked-log (() &body body)
`(bt:with-lock-held (**log-lock**)
,@body))
(defmacro format-log (level-or-fmt-string &rest fmt-string-or-args)
"Send a message to syslog. If the first argument LEVEL-OR-FMT-STRING is a
keyword it is assumed to be a non-default log level (:debug), otherwise it is a control
string followed by optional args (as in FORMAT)."
(when (keywordp level-or-fmt-string)
(cl-syslog:get-priority level-or-fmt-string))
(if (keywordp level-or-fmt-string)
`(with-locked-log ()
(cl-syslog:format-log
*logger*
',level-or-fmt-string
"~A~@?"
(session-info)
,@fmt-string-or-args))
`(with-locked-log ()
(cl-syslog:format-log
*logger*
':debug
"~A~@?"
(session-info)
,level-or-fmt-string
,@fmt-string-or-args))))
|
e7d1cffce6ac1783d4d719dde3a26509191c411adbbf6d6ac5b1995899494d00 | gtk2hs/gtk2hs | Graph.hs | --
Author : < >
--
-- This code is in the public domain.
--
Based off Drawing2.hs
--
updated to GTK 3 by
--
import qualified Graphics.UI.Gtk as G
import qualified Graphics.Rendering.Cairo as C
import qualified Graphics.Rendering.Cairo.Matrix as M
f x = sin (x*5) / (x*5)
main = graph f
windowSize :: Int
windowSize = 400
graph :: (Double -> Double) -> IO ()
graph f = do
G.initGUI
window <- G.windowNew
canvas <- G.drawingAreaNew
Gtk3 no longer has size requests , and window does not have a drawable
-- area to fill, thus we must explicitly tell it how to draw the window size.
G.windowSetDefaultSize window windowSize windowSize
G.windowSetGeometryHints window (Just window)
(Just (0, 0)) (Just (windowSize, windowSize))
Nothing Nothing (Just (1,1))
-- press any key to quit
window `G.on` G.keyPressEvent $ G.tryEvent $ do C.liftIO G.mainQuit
canvas `G.on` G.draw $ (prologue canvas >> renderG f)
G.set window [G.containerChild G.:= canvas, G.windowResizable G.:= False]
G.widgetShowAll window
G.mainGUI
foreach :: (Monad m) => [a] -> (a -> m b) -> m [b]
foreach = flip mapM
deriv :: (Double -> Double) -> Double -> Double
deriv f x = ((f $ x + 0.05) - (f $ x - 0.05)) * 10
gen :: Double -> Double -> (Double -> Double) -> [Double]
gen v t f | v > t = []
gen v t f = v : (gen (f v) t f)
skipBy f = foldr (\x c -> if f x then c else x : c) []
falloff x = 0.25 * (x + 1.5) / ((x+0.5)^5 + 1)
renderG :: (Double -> Double) -> C.Render ()
renderG f = do
C.moveTo (-5) (f (-5))
sequence_ $ map (\d -> C.lineTo d $ f d) $ skipBy (isInfinite . f) [-4.9,-4.8..5]
--Adaptive attempt (falloff func is what really needs work)
sequence _ $ map ( \d - > C.lineTo d $ f d ) $ skipBy ( isInfinite . f ) $ tail $ gen ( -5 ) 5 ( \x - > x + ( falloff $ abs $ deriv ( deriv f ) x ) )
C.stroke
-- Set up stuff
prologue canvas = do
wWidth' <- C.liftIO $ G.widgetGetAllocatedWidth canvas
wHeight' <- C.liftIO $ G.widgetGetAllocatedHeight canvas
let wWidth = realToFrac wWidth'
wHeight = realToFrac wHeight'
width = 10
height = 10
xmax = width / 2
xmin = - xmax
ymax = height / 2
ymin = - ymax
scaleX = realToFrac wWidth / width
scaleY = realToFrac wHeight / height
-- style and color
C.setLineCap C.LineCapRound
C.setLineJoin C.LineJoinRound
C.setLineWidth $ 1 / max scaleX scaleY
-- Set up user coordinates
C.scale scaleX scaleY
-- center origin
C.translate (width / 2) (height / 2)
-- positive y-axis upwards
let flipY = M.Matrix 1 0 0 (-1) 0 0
C.transform flipY
C.setSourceRGBA 0 0 0 1
grid xmin xmax ymin ymax
-- Grid and axes
grid xmin xmax ymin ymax = do
-- axes
C.moveTo 0 ymin; C.lineTo 0 ymax; C.stroke
C.moveTo xmin 0; C.lineTo xmax 0; C.stroke
-- grid
C.setDash [0.01, 0.99] 0
foreach [xmin .. xmax] $ \ x ->
do C.moveTo x ymin
C.lineTo x ymax
C.stroke
C.setDash [] 0
| null | https://raw.githubusercontent.com/gtk2hs/gtk2hs/0f90caa1dae319a0f4bbab76ed1a84f17c730adf/cairo/demo/gtk3/Graph.hs | haskell |
This code is in the public domain.
area to fill, thus we must explicitly tell it how to draw the window size.
press any key to quit
Adaptive attempt (falloff func is what really needs work)
Set up stuff
style and color
Set up user coordinates
center origin
positive y-axis upwards
Grid and axes
axes
grid | Author : < >
Based off Drawing2.hs
updated to GTK 3 by
import qualified Graphics.UI.Gtk as G
import qualified Graphics.Rendering.Cairo as C
import qualified Graphics.Rendering.Cairo.Matrix as M
f x = sin (x*5) / (x*5)
main = graph f
windowSize :: Int
windowSize = 400
graph :: (Double -> Double) -> IO ()
graph f = do
G.initGUI
window <- G.windowNew
canvas <- G.drawingAreaNew
Gtk3 no longer has size requests , and window does not have a drawable
G.windowSetDefaultSize window windowSize windowSize
G.windowSetGeometryHints window (Just window)
(Just (0, 0)) (Just (windowSize, windowSize))
Nothing Nothing (Just (1,1))
window `G.on` G.keyPressEvent $ G.tryEvent $ do C.liftIO G.mainQuit
canvas `G.on` G.draw $ (prologue canvas >> renderG f)
G.set window [G.containerChild G.:= canvas, G.windowResizable G.:= False]
G.widgetShowAll window
G.mainGUI
foreach :: (Monad m) => [a] -> (a -> m b) -> m [b]
foreach = flip mapM
deriv :: (Double -> Double) -> Double -> Double
deriv f x = ((f $ x + 0.05) - (f $ x - 0.05)) * 10
gen :: Double -> Double -> (Double -> Double) -> [Double]
gen v t f | v > t = []
gen v t f = v : (gen (f v) t f)
skipBy f = foldr (\x c -> if f x then c else x : c) []
falloff x = 0.25 * (x + 1.5) / ((x+0.5)^5 + 1)
renderG :: (Double -> Double) -> C.Render ()
renderG f = do
C.moveTo (-5) (f (-5))
sequence_ $ map (\d -> C.lineTo d $ f d) $ skipBy (isInfinite . f) [-4.9,-4.8..5]
sequence _ $ map ( \d - > C.lineTo d $ f d ) $ skipBy ( isInfinite . f ) $ tail $ gen ( -5 ) 5 ( \x - > x + ( falloff $ abs $ deriv ( deriv f ) x ) )
C.stroke
prologue canvas = do
wWidth' <- C.liftIO $ G.widgetGetAllocatedWidth canvas
wHeight' <- C.liftIO $ G.widgetGetAllocatedHeight canvas
let wWidth = realToFrac wWidth'
wHeight = realToFrac wHeight'
width = 10
height = 10
xmax = width / 2
xmin = - xmax
ymax = height / 2
ymin = - ymax
scaleX = realToFrac wWidth / width
scaleY = realToFrac wHeight / height
C.setLineCap C.LineCapRound
C.setLineJoin C.LineJoinRound
C.setLineWidth $ 1 / max scaleX scaleY
C.scale scaleX scaleY
C.translate (width / 2) (height / 2)
let flipY = M.Matrix 1 0 0 (-1) 0 0
C.transform flipY
C.setSourceRGBA 0 0 0 1
grid xmin xmax ymin ymax
grid xmin xmax ymin ymax = do
C.moveTo 0 ymin; C.lineTo 0 ymax; C.stroke
C.moveTo xmin 0; C.lineTo xmax 0; C.stroke
C.setDash [0.01, 0.99] 0
foreach [xmin .. xmax] $ \ x ->
do C.moveTo x ymin
C.lineTo x ymax
C.stroke
C.setDash [] 0
|
c09e3f91fd8221c374bc0500f058843473c1d02907202a3c11880f63f363e886 | FundingCircle/jackdaw | simple_ledger.clj | (ns simple-ledger
"This tutorial contains a simple stream processing application using
Jackdaw and Kafka Streams.
It begins with Pipe which is then extended using an interactive
workflow. The result is a simple ledger."
(:gen-class)
(:require [clojure.spec.alpha :as s]
[clojure.tools.logging :refer [info]]
[clj-uuid :as uuid]
[jackdaw.streams :as j]
[jackdaw.serdes.edn :as jse])
(:import [org.apache.kafka.common.serialization Serdes]))
;;; Topic Configuration
;;;
(defn topic-config
"Takes a topic name and (optionally) a key and value serde and
returns a topic configuration map, which may be used to create a
topic or produce/consume records."
([topic-name]
(topic-config topic-name (jse/serde) (jse/serde)))
([topic-name key-serde value-serde]
{:topic-name topic-name
:partition-count 1
:replication-factor 1
:topic-config {}
:key-serde key-serde
:value-serde value-serde}))
;;; App Template
;;;
(defn app-config
"Returns the application config."
[]
{"application.id" "simple-ledger"
"bootstrap.servers" "localhost:9092"
"cache.max.bytes.buffering" "0"})
(defn build-topology
"Returns a topology builder.
WARNING: This is just a stub. Before publishing to the input topic,
evaluate one of the `build-topology` functions in the comment forms
below."
[builder]
(-> (j/kstream builder (topic-config "ledger-entries-requested"))
(j/peek (fn [[k v]]
(info (str {:key k :value v}))))
(j/to (topic-config "ledger-transaction-added")))
builder)
(defn start-app
"Starts the stream processing application."
[app-config]
(let [builder (j/streams-builder)
topology (build-topology builder)
app (j/kafka-streams topology app-config)]
(j/start app)
(info "simple-ledger is up")
app))
(defn stop-app
"Stops the stream processing application."
[app]
(j/close app)
(info "simple-ledger is down"))
(defn -main
[& _]
(start-app (app-config)))
(comment
;;; Start
;;;
;; Needed to invoke the forms from this namespace. When typing
directly in the REPL , skip this step .
(require '[user :refer :all :exclude [topic-config]])
Start ZooKeeper and .
;; This requires the Confluent Platform CLI which may be obtained
from ` / ` . If ZooKeeper and
;; are already running, skip this step.
(confluent/start)
;; Create the topics, and start the app.
(start)
;; Write to the input stream.
(publish (topic-config "ledger-entries-requested")
nil
"this is a pipe")
;; Read from the output stream.
(get-keyvals (topic-config "ledger-transaction-added")))
(comment
;;; Add input validation
;;;
(do
(s/def ::ledger-entries-requested-value
(s/keys :req-un [::id
::entries]))
(s/def ::id uuid?)
(s/def ::entries (s/+ ::entry))
(s/def ::entry
(s/and (s/keys :req-un [::debit-account-name
::credit-account-name
::amount])
#(not= (:debit-account-name %)
(:credit-account-name %))))
(s/def ::debit-account-name string?)
(s/def ::credit-account-name string?)
(s/def ::amount pos-int?))
(do
(defn valid-input?
[[_ v]]
(s/valid? ::ledger-entries-requested-value v))
(defn log-bad-input
[[k v]]
(info (str "Bad input: "
(s/explain-data ::ledger-entries-requested-value v))))
(defn build-topology
[builder]
(let [input (j/kstream builder
(topic-config "ledger-entries-requested"))
[valid invalid] (j/branch input [valid-input?
(constantly true)])
_ (j/peek invalid log-bad-input)]
(-> valid
(j/to (topic-config "ledger-transaction-added")))
builder)))
;; Reset the app.
(reset)
;; Write valid input.
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
;; Read from the output stream.
(get-keyvals (topic-config "ledger-transaction-added"))
;; Reset the app.
(reset)
;; Write invalid input.
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "foo"
:amount 10}]})
;; Read from the output stream.
(get-keyvals (topic-config "ledger-transaction-added")))
(comment
;;; Split `ledger-entries-requested` events into ledger
;;; transactions (aka debits and credits).
;;;
(do
(defn entry-sides
[{:keys [debit-account-name
credit-account-name
amount]}]
[[debit-account-name
{:account-name debit-account-name
:amount (- amount)}]
[credit-account-name
{:account-name credit-account-name
:amount amount}]])
(defn entries->transactions
[[_ v]]
(reduce #(concat %1 (entry-sides %2)) [] (:entries v)))
(defn build-topology
[builder]
(let [input (j/kstream builder
(topic-config "ledger-entries-requested"))
[valid invalid] (j/branch input [valid-input?
(constantly true)])
_ (j/peek invalid log-bad-input)
transactions (j/flat-map valid entries->transactions)]
(-> transactions
(j/to (topic-config "ledger-transaction-added")))
builder)))
;; Reset the app.
(reset)
;; Write valid input.
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
;; Read from the output stream.
(get-keyvals (topic-config "ledger-transaction-added"))
;; Write valid input (again).
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
;; Read from the output stream (again).
(get-keyvals (topic-config "ledger-transaction-added")))
(comment
;;; Add unique identifiers and reference IDs.
;;;
(defn entries->transactions
[[_ v]]
(->> (:entries v)
(reduce #(concat %1 (entry-sides %2)) [])
(map-indexed #(assoc-in %2 [1 :id] (uuid/v5 (:id v) %1)))
(map #(assoc-in %1 [1 :causation-id] (:id v)))))
;; Reset the app.
(reset)
;; Write valid input.
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
;; Read from the output stream.
(get-keyvals (topic-config "ledger-transaction-added"))
;; Write valid input (again).
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
;; Read from the output stream (again).
(get-keyvals (topic-config "ledger-transaction-added"))
;; Read from the output stream ("foo" only).
(->> (get-keyvals (topic-config "ledger-transaction-added"))
(filter (fn [[k v]] (= "foo" k)))))
(comment
;;; Keep track of running balances.
;;;
(do
(defn account-balance-reducer
[x y]
(let [starting-balance (:current-balance x)]
(merge y {:starting-balance starting-balance
:current-balance (+ starting-balance (:amount y))})))
(defn build-topology
[builder]
(let [input (j/kstream builder
(topic-config "ledger-entries-requested"))
[valid invalid] (j/branch input [valid-input?
(constantly true)])
_ (j/peek invalid log-bad-input)
transactions (j/flat-map valid entries->transactions)
balances
(-> transactions
(j/map-values (fn [v]
(merge v
{:starting-balance 0
:current-balance (:amount v)})))
(j/group-by-key (topic-config nil (Serdes/String)
(jse/serde)))
(j/reduce account-balance-reducer
(topic-config "balances")))]
(-> balances
(j/to-kstream)
(j/to (topic-config "ledger-transaction-added")))
builder)))
;; Reset the app.
(reset)
;; Write valid input.
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
;; Read from the output stream.
(get-keyvals (topic-config "ledger-transaction-added"))
;; Write valid input (again).
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
;; Read from the output stream (again).
(get-keyvals (topic-config "ledger-transaction-added"))
;; Read from the output stream ("foo" only).
(->> (get-keyvals (topic-config "ledger-transaction-added"))
(filter (fn [[k v]] (= "foo" k)))))
| null | https://raw.githubusercontent.com/FundingCircle/jackdaw/b4f67106cc12a78d9dcc64b6cba668ab6a804d04/examples/simple-ledger/src/simple_ledger.clj | clojure | Topic Configuration
App Template
Start
Needed to invoke the forms from this namespace. When typing
This requires the Confluent Platform CLI which may be obtained
are already running, skip this step.
Create the topics, and start the app.
Write to the input stream.
Read from the output stream.
Add input validation
Reset the app.
Write valid input.
Read from the output stream.
Reset the app.
Write invalid input.
Read from the output stream.
Split `ledger-entries-requested` events into ledger
transactions (aka debits and credits).
Reset the app.
Write valid input.
Read from the output stream.
Write valid input (again).
Read from the output stream (again).
Add unique identifiers and reference IDs.
Reset the app.
Write valid input.
Read from the output stream.
Write valid input (again).
Read from the output stream (again).
Read from the output stream ("foo" only).
Keep track of running balances.
Reset the app.
Write valid input.
Read from the output stream.
Write valid input (again).
Read from the output stream (again).
Read from the output stream ("foo" only). | (ns simple-ledger
"This tutorial contains a simple stream processing application using
Jackdaw and Kafka Streams.
It begins with Pipe which is then extended using an interactive
workflow. The result is a simple ledger."
(:gen-class)
(:require [clojure.spec.alpha :as s]
[clojure.tools.logging :refer [info]]
[clj-uuid :as uuid]
[jackdaw.streams :as j]
[jackdaw.serdes.edn :as jse])
(:import [org.apache.kafka.common.serialization Serdes]))
(defn topic-config
"Takes a topic name and (optionally) a key and value serde and
returns a topic configuration map, which may be used to create a
topic or produce/consume records."
([topic-name]
(topic-config topic-name (jse/serde) (jse/serde)))
([topic-name key-serde value-serde]
{:topic-name topic-name
:partition-count 1
:replication-factor 1
:topic-config {}
:key-serde key-serde
:value-serde value-serde}))
(defn app-config
"Returns the application config."
[]
{"application.id" "simple-ledger"
"bootstrap.servers" "localhost:9092"
"cache.max.bytes.buffering" "0"})
(defn build-topology
"Returns a topology builder.
WARNING: This is just a stub. Before publishing to the input topic,
evaluate one of the `build-topology` functions in the comment forms
below."
[builder]
(-> (j/kstream builder (topic-config "ledger-entries-requested"))
(j/peek (fn [[k v]]
(info (str {:key k :value v}))))
(j/to (topic-config "ledger-transaction-added")))
builder)
(defn start-app
"Starts the stream processing application."
[app-config]
(let [builder (j/streams-builder)
topology (build-topology builder)
app (j/kafka-streams topology app-config)]
(j/start app)
(info "simple-ledger is up")
app))
(defn stop-app
"Stops the stream processing application."
[app]
(j/close app)
(info "simple-ledger is down"))
(defn -main
[& _]
(start-app (app-config)))
(comment
directly in the REPL , skip this step .
(require '[user :refer :all :exclude [topic-config]])
Start ZooKeeper and .
from ` / ` . If ZooKeeper and
(confluent/start)
(start)
(publish (topic-config "ledger-entries-requested")
nil
"this is a pipe")
(get-keyvals (topic-config "ledger-transaction-added")))
(comment
(do
(s/def ::ledger-entries-requested-value
(s/keys :req-un [::id
::entries]))
(s/def ::id uuid?)
(s/def ::entries (s/+ ::entry))
(s/def ::entry
(s/and (s/keys :req-un [::debit-account-name
::credit-account-name
::amount])
#(not= (:debit-account-name %)
(:credit-account-name %))))
(s/def ::debit-account-name string?)
(s/def ::credit-account-name string?)
(s/def ::amount pos-int?))
(do
(defn valid-input?
[[_ v]]
(s/valid? ::ledger-entries-requested-value v))
(defn log-bad-input
[[k v]]
(info (str "Bad input: "
(s/explain-data ::ledger-entries-requested-value v))))
(defn build-topology
[builder]
(let [input (j/kstream builder
(topic-config "ledger-entries-requested"))
[valid invalid] (j/branch input [valid-input?
(constantly true)])
_ (j/peek invalid log-bad-input)]
(-> valid
(j/to (topic-config "ledger-transaction-added")))
builder)))
(reset)
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
(get-keyvals (topic-config "ledger-transaction-added"))
(reset)
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "foo"
:amount 10}]})
(get-keyvals (topic-config "ledger-transaction-added")))
(comment
(do
(defn entry-sides
[{:keys [debit-account-name
credit-account-name
amount]}]
[[debit-account-name
{:account-name debit-account-name
:amount (- amount)}]
[credit-account-name
{:account-name credit-account-name
:amount amount}]])
(defn entries->transactions
[[_ v]]
(reduce #(concat %1 (entry-sides %2)) [] (:entries v)))
(defn build-topology
[builder]
(let [input (j/kstream builder
(topic-config "ledger-entries-requested"))
[valid invalid] (j/branch input [valid-input?
(constantly true)])
_ (j/peek invalid log-bad-input)
transactions (j/flat-map valid entries->transactions)]
(-> transactions
(j/to (topic-config "ledger-transaction-added")))
builder)))
(reset)
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
(get-keyvals (topic-config "ledger-transaction-added"))
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
(get-keyvals (topic-config "ledger-transaction-added")))
(comment
(defn entries->transactions
[[_ v]]
(->> (:entries v)
(reduce #(concat %1 (entry-sides %2)) [])
(map-indexed #(assoc-in %2 [1 :id] (uuid/v5 (:id v) %1)))
(map #(assoc-in %1 [1 :causation-id] (:id v)))))
(reset)
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
(get-keyvals (topic-config "ledger-transaction-added"))
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
(get-keyvals (topic-config "ledger-transaction-added"))
(->> (get-keyvals (topic-config "ledger-transaction-added"))
(filter (fn [[k v]] (= "foo" k)))))
(comment
(do
(defn account-balance-reducer
[x y]
(let [starting-balance (:current-balance x)]
(merge y {:starting-balance starting-balance
:current-balance (+ starting-balance (:amount y))})))
(defn build-topology
[builder]
(let [input (j/kstream builder
(topic-config "ledger-entries-requested"))
[valid invalid] (j/branch input [valid-input?
(constantly true)])
_ (j/peek invalid log-bad-input)
transactions (j/flat-map valid entries->transactions)
balances
(-> transactions
(j/map-values (fn [v]
(merge v
{:starting-balance 0
:current-balance (:amount v)})))
(j/group-by-key (topic-config nil (Serdes/String)
(jse/serde)))
(j/reduce account-balance-reducer
(topic-config "balances")))]
(-> balances
(j/to-kstream)
(j/to (topic-config "ledger-transaction-added")))
builder)))
(reset)
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
(get-keyvals (topic-config "ledger-transaction-added"))
(publish (topic-config "ledger-entries-requested")
nil
{:id (java.util.UUID/randomUUID)
:entries [{:debit-account-name "foo"
:credit-account-name "bar"
:amount 10}
{:debit-account-name "foo"
:credit-account-name "qux"
:amount 20}]})
(get-keyvals (topic-config "ledger-transaction-added"))
(->> (get-keyvals (topic-config "ledger-transaction-added"))
(filter (fn [[k v]] (= "foo" k)))))
|
9d95da3285d8421e712218cf2e69acbbac6106401408d0e3d9541a505f8f2470 | gregr/ina | mvector.scm | (define (mvector . args)
(let ((x (make-mvector (length args) 0)))
(let loop ((i 0) (args args))
(cond ((null? args) x)
(else (mvector-set! x i (car args))
(loop (+ i 1) (cdr args)))))))
(define (mvector-transform-range! mv start end f)
;; TODO: always requiring (= 0 start) ? That's not very useful.
(unless (and (= 0 start) (<= start end) (<= end (mvector-length mv)))
(error "invalid mvector range"
'length (mvector-length mv) 'start start 'end end))
(let loop ((i start)) (when (< i end)
(mvector-set! mv i (f i))
(loop (+ i 1)))))
(define (mvector-fill! mv v)
(mvector-transform-range! mv 0 (mvector-length mv) (lambda (_) v)))
(define (mvector-copy! mv start src start.src end.src)
(let-values (((ref length)
(cond ((mvector? src) (values mvector-ref mvector-length))
((vector? src) (values vector-ref vector-length))
(else (error "invalid source for mvector-copy!" src)))))
(unless (and (<= 0 start.src) (<= start.src end.src) (<= end.src (length src)))
(error "invalid source range" 'length (length src) 'start start.src 'end end.src))
(mvector-transform-range! mv start (+ start (- end.src start.src))
(lambda (i) (ref src (+ start.src (- i start)))))))
| null | https://raw.githubusercontent.com/gregr/ina/236e478c9e2ed6e4ee92bc06b742c97d7b92580c/nscheme/include/base/mvector.scm | scheme | TODO: always requiring (= 0 start) ? That's not very useful. | (define (mvector . args)
(let ((x (make-mvector (length args) 0)))
(let loop ((i 0) (args args))
(cond ((null? args) x)
(else (mvector-set! x i (car args))
(loop (+ i 1) (cdr args)))))))
(define (mvector-transform-range! mv start end f)
(unless (and (= 0 start) (<= start end) (<= end (mvector-length mv)))
(error "invalid mvector range"
'length (mvector-length mv) 'start start 'end end))
(let loop ((i start)) (when (< i end)
(mvector-set! mv i (f i))
(loop (+ i 1)))))
(define (mvector-fill! mv v)
(mvector-transform-range! mv 0 (mvector-length mv) (lambda (_) v)))
(define (mvector-copy! mv start src start.src end.src)
(let-values (((ref length)
(cond ((mvector? src) (values mvector-ref mvector-length))
((vector? src) (values vector-ref vector-length))
(else (error "invalid source for mvector-copy!" src)))))
(unless (and (<= 0 start.src) (<= start.src end.src) (<= end.src (length src)))
(error "invalid source range" 'length (length src) 'start start.src 'end end.src))
(mvector-transform-range! mv start (+ start (- end.src start.src))
(lambda (i) (ref src (+ start.src (- i start)))))))
|
2a894983edfcb9aae49fd37124ce781033827e52cc0e7f849bd255b2b31da03b | ygrek/mldonkey | gui_downloads.ml | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
(** GUI for the lists of files. *)
open Printf2
open Options
open Md4
open Gettext
open Gui_global
open CommonTypes
open GuiTypes
open GuiProto
open Gui_columns
module M = Gui_messages
module P = Gpattern
module O = Gui_options
module G = Gui_global
module VB = VerificationBitmap
let preview file () = Gui_com.send (Preview file.file_num)
let save_menu_items file =
List.map
(fun name ->
`I (name,
(fun _ ->
Gui_com.send (GuiProto.SaveFile (file.file_num, name))
)
)
)
file.file_names
let save_as file () =
let file_opt = GToolbox.input_string ~title: (gettext M.save)
(gettext M.save) in
match file_opt with
None -> ()
| Some name ->
Gui_com.send (GuiProto.SaveFile (file.file_num, name))
let (!!) = Options.(!!)
let file_first_name f = f.file_name
let string_of_file_state state =
match state with
| FileDownloading -> (gettext M.downloading)
| FileCancelled -> (gettext M.cancelled)
| FileQueued -> (gettext M.queued)
| FilePaused -> (gettext M.paused)
| FileDownloaded
| FileShared -> (gettext M.dl_done)
| FileNew -> assert false
| FileAborted s -> Printf.sprintf "Aborted: %s" s
let some_is_available f =
let b = ref false in
List.iter (fun (_, avail) ->
We can not use anymore relative availability as we can not relate the
partial chunks with positions in the availability ...
if ! ! Gui_options.use_relative_availability
then
for i = 0 to String.length avail - 1 do
if CommonGlobals.partial_chunk f.file_chunks.[i ] & &
f.file_availability.[i ] < > ' \000 '
then true
else loop ( i - 1 )
in
loop ( ( String.length f.file_availability ) - 1 )
else
partial chunks with positions in the availability...
if !!Gui_options.use_relative_availability
then
for i = 0 to String.length avail - 1 do
if CommonGlobals.partial_chunk f.file_chunks.[i] &&
f.file_availability.[i] <> '\000'
then true
else loop (i - 1)
in
loop ((String.length f.file_availability) - 1)
else
*)
let len = String.length avail in
for i = 0 to len - 1 do
b := !b || avail.[i] <> '\000'
done;
) f.file_availability;
!b
let color_opt_of_file f =
if f.file_download_rate > 0. then
Some !!O.color_downloading
else if some_is_available f then
Some !!O.color_available
else
Some !!O.color_not_available
let float_avail s =
try float_of_string s
with _ -> 0.0
let file_availability f =
match f.file_chunks with
| None -> "---"
| Some chunks ->
match f.file_availability with
(_,avail) :: _ ->
let rec loop i p n =
if i < 0 then
if n = 0 then "---"
else Printf.sprintf "%5.1f" ((float p) /. (float n) *. 100.0)
else
loop (i - 1)
(if CommonGlobals.partial_chunk (VerificationBitmap.get chunks i) then p + 1 else p)
(if avail.[i] <> (char_of_int 0) then n + 1 else n)
in
loop ((String.length avail) - 1) 0 0
| _ -> "---"
let string_availability f =
let maxi = ref 0. in
List.iter (fun (_, avail) ->
let len = String.length avail in
let p = ref 0 in
for i = 0 to len - 1 do
if avail.[i] <> '\000' then begin
incr p
end
done;
maxi := max !maxi (float_of_int !p /. float_of_int len *. 100.)
) f.file_availability;
Printf.sprintf "%5.1f" !maxi
let string_of_format format =
match format with
AVI f ->
Printf.sprintf "AVI: %s %dx%d %g fps %d bpf"
f.avi_codec f.avi_width f.avi_height
(float_of_int(f.avi_fps) *. 0.001) f.avi_rate
| MP3 (tag, _) ->
let module M = Mp3tag.Id3v1 in
Printf.sprintf "MP3: %s - %s (%d): %s"
tag.M.artist tag.M.album
tag.M.tracknum tag.M.title
| _ -> (gettext M.unknown)
let max_eta = 1000.0 *. 60.0 *. 60.0 *. 24.0
let calc_file_eta f =
let size = Int64.to_float f.file_size in
let downloaded = Int64.to_float f.file_downloaded in
let missing = size -. downloaded in
let rate = f.file_download_rate in
let rate =
if rate = 0.
then
let time = BasicSocket.last_time () in
let age = time - f.file_age in
if age > 0
then downloaded /. (float_of_int age)
else 0.
else rate
in
let eta =
if rate = 0.0 then max_eta else
let eta = missing /. rate in
if eta < 0. || eta > max_eta then max_eta else
eta
in
int_of_float eta
class box columns sel_mode () =
let titles = List.map Gui_columns.File.string_of_column !!columns in
object (self)
inherit [file_info] Gpattern.plist sel_mode titles true (fun f -> f.file_num) as pl
inherit Gui_downloads_base.box () as box
val mutable columns = columns
method set_columns l =
columns <- l;
self#set_titles (List.map Gui_columns.File.string_of_column !!columns);
self#update
method column_menu i =
[
`I ("Autosize", fun _ -> self#wlist#columns_autosize ());
`I ("Sort", self#resort_column i);
`I ("Remove Column",
(fun _ ->
match !!columns with
_ :: _ :: _ ->
(let l = !!columns in
match List2.cut i l with
l1, _ :: l2 ->
columns =:= l1 @ l2;
self#set_columns columns
| _ -> ())
| _ -> ()
)
);
`M ("Add Column After", (
List.map (fun (c,s) ->
(`I (s, (fun _ ->
let c1, c2 = List2.cut (i+1) !!columns in
columns =:= c1 @ [c] @ c2;
self#set_columns columns
)))
) Gui_columns.file_column_strings));
`M ("Add Column Before", (
List.map (fun (c,s) ->
(`I (s, (fun _ ->
let c1, c2 = List2.cut i !!columns in
columns =:= c1 @ [c] @ c2;
self#set_columns columns
)))
) Gui_columns.file_column_strings));
]
method box = box#coerce
method vbox = box#vbox
method compare_by_col col f1 f2 =
match col with
| Col_file_name -> compare f1.file_name f2.file_name
| Col_file_size -> compare f1.file_size f2.file_size
| Col_file_downloaded -> compare f1.file_downloaded f2.file_downloaded
| Col_file_percent -> compare
(Int64.to_float f1.file_downloaded /. Int64.to_float f1.file_size)
(Int64.to_float f2.file_downloaded /. Int64.to_float f2.file_size)
| Col_file_rate-> compare f1.file_download_rate f2.file_download_rate
| Col_file_state -> compare f1.file_state f2.file_state
| Col_file_availability ->
let fn =
if !!Gui_options.use_relative_availability
then file_availability
else string_availability
in
compare (float_avail (fn f1)) (float_avail (fn f2))
| Col_file_md4 -> compare (Md4.to_string f1.file_md4) (Md4.to_string f2.file_md4)
| Col_file_format -> compare f1.file_format f2.file_format
| Col_file_network -> compare f1.file_network f2.file_network
| Col_file_age -> compare f1.file_age f2.file_age
| Col_file_last_seen -> compare f1.file_last_seen f2.file_last_seen
| Col_file_eta -> compare (calc_file_eta f1) (calc_file_eta f2)
| Col_file_priority -> compare f1.file_priority f2.file_priority
method compare f1 f2 =
let abs = if current_sort >= 0 then current_sort else - current_sort in
let col =
try List.nth !!columns (abs - 1)
with _ -> Col_file_name
in
let res = self#compare_by_col col f1 f2 in
current_sort * res
method content_by_col f col =
match col with
Col_file_name ->
let s_file = Gui_misc.short_name f.file_name in
s_file
| Col_file_size ->
Gui_misc.size_of_int64 f.file_size
| Col_file_downloaded ->
Gui_misc.size_of_int64 f.file_downloaded
| Col_file_percent ->
Printf.sprintf "%5.1f"
(Int64.to_float f.file_downloaded /. Int64.to_float f.file_size *. 100.)
| Col_file_rate ->
if f.file_download_rate > 0. then
Printf.sprintf "%5.1f" (f.file_download_rate /. 1024.)
else ""
| Col_file_state ->
string_of_file_state f.file_state
| Col_file_availability ->
if !!Gui_options.use_relative_availability
then file_availability f
else string_availability f
| Col_file_md4 -> Md4.to_string f.file_md4
| Col_file_format -> string_of_format f.file_format
| Col_file_network -> Gui_global.network_name f.file_network
| Col_file_age ->
let age = (BasicSocket.last_time ()) - f.file_age in
Date.time_to_string age "long"
| Col_file_last_seen ->
if f.file_last_seen > 0
then let last = (BasicSocket.last_time ())
- f.file_last_seen in
Date.time_to_string last "long"
else Printf.sprintf "---"
| Col_file_eta ->
let eta = calc_file_eta f in
if eta >= 1000 * 60 * 60 * 24 then
Printf.sprintf "---"
else Date.time_to_string eta "long"
| Col_file_priority ->
Printf.sprintf "%3d" f.file_priority
method content f =
let strings = List.map
(fun col -> P.String (self#content_by_col f col))
!!columns
in
let col_opt =
match color_opt_of_file f with
None -> Some `BLACK
| Some c -> Some (`NAME c)
in
(strings, col_opt)
method find_file num = self#find num
method remove_file f row =
self#remove_item row f;
selection <- List.filter (fun fi -> fi.file_num <> f.file_num) selection
method set_tb_style tb =
if Options.(!!) Gui_options.mini_toolbars then
(wtool1#misc#hide (); wtool2#misc#show ()) else
(wtool2#misc#hide (); wtool1#misc#show ());
wtool2#set_style tb;
wtool1#set_style tb
initializer
box#vbox#pack ~expand: true pl#box;
end
class box_downloaded wl_status () =
object (self)
inherit box O.downloaded_columns `SINGLE () as super
method update_wl_status : unit =
wl_status#set_text
(Printf.sprintf !!Gui_messages.downloaded_files !G.ndownloaded !G.ndownloads)
method content f =
(fst (super#content f), Some (`NAME !!O.color_downloaded))
method save ev =
match self#selection with
f :: _ ->
let items = save_menu_items f in
GAutoconf.popup_menu ~entries: items ~button: 1 ~time: 0
| _ ->
()
method save_all () =
self#iter (fun f ->
Gui_com.send (GuiProto.SaveFile (f.file_num, file_first_name f)))
method edit_mp3_tags () =
match self#selection with
file :: _ ->
(
match file.file_format with
MP3 (tag,_) ->
Mp3_ui.edit_tag_v1 (gettext M.edit_mp3) tag ;
Gui_com.send (GuiProto.ModifyMp3Tags (file.file_num, tag))
| _ ->
()
)
| _ ->
()
method menu =
match self#selection with
[] -> [ `I ((gettext M.save_all), self#save_all) ]
| file :: _ ->
[
`I ((gettext M.save_as), save_as file) ;
`M ((gettext M.save), save_menu_items file) ;
`I ((gettext M.preview), preview file) ;
] @
(match file.file_format with
MP3 _ -> [`I ((gettext M.edit_mp3), self#edit_mp3_tags)]
| _ -> []) @
[ `S ;
`I ((gettext M.save_all), self#save_all)
]
* { 2 Handling core messages }
method h_downloaded f =
try
ignore (self#find_file f.file_num)
with
Not_found ->
incr ndownloaded;
self#update_wl_status ;
self#add_item f
method h_removed f =
try
let (row, _) = self#find_file f.file_num in
decr ndownloaded;
self#update_wl_status ;
self#remove_file f row
with
Not_found ->
()
method preview () =
match self#selection with
[] -> ()
| file :: _ -> preview file ()
method save_as () =
match self#selection with
| [] -> ()
| file :: _ -> save_as file ()
initializer
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.save)
~tooltip: (gettext M.save)
~icon: (M.o_xpm_save)
~callback: self#save
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.save_as)
~tooltip: (gettext M.save_as)
~icon: (M.o_xpm_save_as)
~callback: self#save_as
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.save_all)
~tooltip: (gettext M.save_all)
~icon: (M.o_xpm_save_all)
~callback: self#save_all
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.edit_mp3)
~tooltip: (gettext M.edit_mp3)
~icon: (M.o_xpm_edit_mp3)
~callback: self#edit_mp3_tags
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.preview)
~tooltip: (gettext M.preview)
~icon: (M.o_xpm_preview)
~callback: self#preview
();
end
let colorGreen = `NAME "green"
let colorRed = `NAME "red"
let colorBlue = `NAME "blue"
let colorGray = `NAME "gray"
let colorWhite =`WHITE
let colorBlack = `BLACK
let colorCyan = `NAME "cyan"
let drawing = ref (None : [ `window] GDraw.drawable option)
let draw_chunks (drawing : unit GDraw.drawable) file =
match file.file_chunks with
| None -> ()
| Some chunks ->
let wx, wy = drawing#size in
drawing#set_foreground colorWhite;
drawing#rectangle ~filled: true ~x:0 ~y:0 ~width:wx ~height:wy ();
let nchunks = VerificationBitmap.length chunks in
let dx = min !!O.chunk_width (wx / nchunks) in
if wx > nchunks*dx && dx > 0 then
let offset = (wx - nchunks * dx) / 2 in
let offset = if offset < 0 then 0 else offset in
let dx2 = if dx <= 2 then dx else dx - 1 in
for i = 0 to nchunks - 1 do
drawing#set_foreground (
match VerificationBitmap.get chunks i with
| VerificationBitmap.State_missing -> colorRed
| VerificationBitmap.State_partial -> colorBlue
| VerificationBitmap.State_complete -> colorBlack
| VerificationBitmap.State_verified -> colorGreen);
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ()
done
else
let group = (nchunks+wx-1) / wx in
let chunk n =
let p = n * group in
let get i =
if i < nchunks then VerificationBitmap.get chunks i
else VerificationBitmap.State_complete
in
let current = ref 0 in
for i = p to p+group-1 do
match get i with
| VB.State_missing -> ()
| VB.State_partial -> if !current = 0 then current := 1
| VB.State_complete | VB.State_verified ->
current := 2
done;
String.make 1 (char_of_int !current)
in
let dx = 1 in
let nchunks = nchunks / group in
let offset = (wx - nchunks * dx) / 2 in
let offset = if offset < 0 then 0 else offset in
let dx2 = if dx <= 2 then dx else dx - 1 in
for i = 0 to nchunks - 1 do
let chunk = chunk i in
drawing#set_foreground (
match VerificationBitmap.get chunks i with
| VerificationBitmap.State_missing -> colorRed
| VerificationBitmap.State_partial -> colorBlue
| VerificationBitmap.State_complete -> colorBlack
| VerificationBitmap.State_verified -> colorGreen);
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ()
done
let draw_availability (drawing: unit GDraw.drawable) availability =
let wx, wy = drawing#size in
drawing#set_foreground colorWhite;
drawing#rectangle ~filled: true ~x:0 ~y:0 ~width:wx ~height:wy ();
let nchunks = String.length availability in
let dx = min !!O.chunk_width (wx / nchunks) in
if wx > nchunks*dx && dx > 0 then
let offset = (wx - nchunks * dx) / 2 in
let offset = if offset < 0 then 0 else offset in
let dx2 = if dx <= 2 then dx else dx - 1 in
for i = 0 to nchunks - 1 do
if !!Gui_options.use_availability_height
then begin
let h = int_of_char (availability.[i])
in
if h = 0
then
begin
drawing#set_foreground colorRed;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ();
end
else begin
let h = min ((wy * h) / !!Gui_options.availability_max) wy in
drawing#set_foreground colorGray;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height: (wy - h) ();
drawing#set_foreground colorBlue;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: (wy - h)
~width: dx2 ~height:h ();
end
end else begin
drawing#set_foreground (
match int_of_char availability.[i] with
0 -> colorRed
| 1 -> colorBlue
| _ -> colorBlack);
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ()
end
done
else
let group = (nchunks+wx-1) / wx in
let avail i =
let p = i * group in
let get i =
if i < nchunks then availability.[i] else '\200'
in
let current = ref (get p) in
for i = p+1 to p+group-1 do
current := min (get i) !current
done;
!current
in
let dx = 1 in
let nchunks = nchunks / group in
let offset = (wx - nchunks * dx) / 2 in
let offset = if offset < 0 then 0 else offset in
let dx2 = if dx <= 2 then dx else dx - 1 in
for i = 0 to nchunks - 1 do
let avail = avail i in
if !!Gui_options.use_availability_height
then begin
let h = int_of_char avail
in
if h = 0
then
begin
drawing#set_foreground colorRed;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ();
end
else begin
let h = min ((wy * h) / !!Gui_options.availability_max) wy in
drawing#set_foreground colorGray;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height: (wy - h) ();
drawing#set_foreground colorBlue;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: (wy - h)
~width: dx2 ~height:h ();
end
end else begin
drawing#set_foreground (
match int_of_char avail with
0 -> colorRed
| 1 -> colorBlue
| _ -> colorBlack);
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ()
end
done
let redraw_chunks display_caption draw_avail view_availability file =
let (drawing : unit GDraw.drawable) = match !drawing with
None ->
let w = draw_avail#misc#window in
let d = new GDraw.drawable w in
draw_avail#misc#show ();
drawing := Some d;
d
| Some d -> d
in
try
if view_availability = 0 then begin
display_caption#set_text "Downloaded Chunks";
draw_chunks drawing file
end else
let (net, a) =
List.nth file.file_availability (view_availability-1) in
display_caption#set_text (Printf.sprintf "Availability on %s"
(try (Hashtbl.find networks net).net_name with _ -> "??"));
draw_availability drawing a
with e ->
Printf2.lprintf "Exception %s during drawing\n"
(Printexc2.to_string e)
class box_downloads box_locs wl_status () =
let draw_availability =
GMisc.drawing_area ~height:20
()
in
let display_caption =
GMisc.label ~text:"Current chunks" ~justify:`LEFT ~line_wrap:true
~xalign:(-1.0) ~yalign:(-1.0) ()
in
let label_file_info = GMisc.label () in
object (self)
inherit box O.downloads_columns `EXTENDED ()
method update_wl_status : unit =
wl_status#set_text
(Printf.sprintf !!Gui_messages.downloaded_files !G.ndownloaded !G.ndownloads)
method cancel () =
let s = Gui_messages.ask_cancel_download_files
(List.map (fun f -> file_first_name f) self#selection)
in
match GToolbox.question_box (gettext Gui_messages.cancel)
[ gettext Gui_messages.yes ; gettext Gui_messages.no] s
with
1 ->
List.iter
(fun f -> Gui_com.send (RemoveDownload_query f.file_num))
self#selection
| _ ->
()
method retry_connect () =
List.iter
(fun f -> Gui_com.send (ConnectAll f.file_num))
self#selection
method pause_resume () =
List.iter
(fun f -> Gui_com.send (SwitchDownload (f.file_num,
match f.file_state with
FilePaused | FileAborted _ -> true
| _ -> false
)))
self#selection
method verify_chunks () =
List.iter
(fun f -> Gui_com.send (VerifyAllChunks f.file_num))
self#selection
method get_format () =
List.iter
(fun f -> Gui_com.send (QueryFormat f.file_num))
self#selection
method set_priority prio () =
List.iter
(fun f -> Gui_com.send (SetFilePriority (f.file_num, prio)))
self#selection
method menu =
match self#selection with
[] -> []
| file :: tail ->
`I ((gettext M.pause_resume_dl), self#pause_resume) ::
`I ((gettext M.retry_connect), self#retry_connect) ::
`I ((gettext M.cancel), self#cancel) ::
`I ((gettext M.verify_chunks), self#verify_chunks) ::
`M ("Set priority", [
`I ("High", self#set_priority 10);
`I ("Normal", self#set_priority 0);
`I ("Low", self#set_priority (-10));
]) ::
`I ((gettext M.get_format), self#get_format) ::
(if tail = [] then
[
`I ((gettext M.preview), preview file) ;
`M ((gettext M.save), save_menu_items file) ;
`I ((gettext M.save_as), save_as file) ;
]
else [])
0 = current chunks , 1 - n availability
val mutable view_availability = 0
val mutable last_displayed_file = None
val mutable label_shown = false
method on_select file =
if not label_shown then begin
label_shown <- true;
let hbox = GPack.hbox ~homogeneous:false () in
let button = GButton.button () in
self#vbox#pack ~expand: false ~fill: true label_file_info#coerce ;
self#vbox#pack ~expand:false ~fill:true hbox#coerce;
hbox#pack ~expand:false ~fill:false button#coerce;
hbox#add draw_availability#coerce;
button#add display_caption#coerce;
ignore (button#connect#clicked (fun _ ->
match last_displayed_file with
Some file ->
let n = view_availability + 1 in
lprintf " view_availability % d/%d\n " n
( file.file_availability ) ;
(List.length file.file_availability); *)
view_availability <- (if
n > List.length file.file_availability
then 0 else n);
redraw_chunks display_caption draw_availability view_availability file;
| _ -> ()));
end;
label_file_info#set_text
(
Printf.sprintf "NAME: %s SIZE: %s FORMAT: %s"
(file.file_name)
(Int64.to_string file.file_size)
(string_of_format file.file_format)
;
);
view_availability <- 0;
redraw_chunks display_caption draw_availability view_availability file;
last_displayed_file <- Some file;
box_locs#update_data_by_file (Some file)
method on_deselect _ =
box_locs#update_data_by_file None
* { 2 Handling core messages }
method update_file f f_new row =
f.file_md4 <- f_new.file_md4 ;
f.file_name <- f_new.file_name ;
f.file_names <- f_new.file_names ;
f.file_size <- f_new.file_size ;
f.file_downloaded <- f_new.file_downloaded ;
f.file_all_sources <- f_new.file_all_sources ;
f.file_active_sources <- f_new.file_active_sources ;
f.file_state <- f_new.file_state ;
let must_redraw =
(f.file_chunks <> f_new.file_chunks) ||
(f.file_availability <> f_new.file_availability)
in
f.file_chunks <- f_new.file_chunks ;
f.file_availability <- f_new.file_availability ;
f.file_priority <- f_new.file_priority;
if f_new.file_sources <> None then
f.file_sources <- f_new.file_sources ;
f.file_download_rate <- f_new.file_download_rate ;
f.file_format <- f_new.file_format;
f.file_age <- f_new.file_age;
f.file_last_seen <- f_new.file_last_seen;
self#update_row f row;
if must_redraw then
match last_displayed_file with
| Some file when f == file ->
redraw_chunks display_caption draw_availability view_availability file;
| _ -> ()
method h_file_downloaded num dled rate =
try
let (row, f) = self#find_file num in
self#update_file f
{ f with file_downloaded = dled ; file_download_rate = rate }
row
with
Not_found ->
()
method h_paused f =
try
let (row, fi) = self#find_file f.file_num in
self#update_file fi f row
with
Not_found ->
incr ndownloads;
self#update_wl_status ;
self#add_item f
method h_cancelled f =
try
let (row, fi) = self#find_file f.file_num in
decr ndownloads;
self#update_wl_status ;
self#remove_file fi row
with
Not_found ->
()
method h_downloaded = self#h_cancelled
method h_downloading f = self#h_paused f
method h_file_availability file_num client_num avail =
try
let files = Intmap.find client_num !availabilities in
try
let (s,file) = Intmap.find file_num !files in
String.blit avail 0 s 0 (String.length avail);
with _ ->
let _, file = self#find_file file_num in
files := Intmap.add file_num (avail,file) !files
with _ ->
let _, file = self#find_file file_num in
availabilities := Intmap.add client_num
(ref (Intmap.add file_num (avail,file) Intmap.empty)) !availabilities
(*
try
let (row, f) = self#find_file file_num in
self#update_file f
{ f with file_chunks = chunks ; file_availability = avail }
row
with Not_found -> ()
*)
(*
method remove_client c =
List.iter (fun file ->
match file.file_sources with
None -> ()
| Some sources ->
if List.memq c sources then
let (row, file) = self#find_file file.file_num in
(* lprintf "Removing client from sources";
lprint_newline (); *)
self#update_file file { file with file_sources = Some (
List.filter (fun cc -> cc != c) sources) }
row
) data
*)
method h_file_age num age =
try
let (row, f) = self#find_file num in
self#update_file f
{ f with file_age = age }
row
with Not_found -> ()
method h_file_last_seen num last =
try
let (row, f) = self#find_file num in
self#update_file f
{ f with file_last_seen = last }
row
with Not_found -> ()
method h_file_location num src =
try
(* lprintf "Source %d for %d" src num; lprint_newline (); *)
let (row, f) = self#find_file num in
self#update_file f
{ f with
file_sources = Some (
(match f.file_sources with
None -> [src]
| Some list -> if not (List.mem src list) then
list@[src] else list ))
}
row
with Not_found ->
(* some sources are sent for shared files in eDonkey. have to fix that *)
lprintf " No such file % d " num ; ( )
()
method h_file_remove_location (num:int) (src:int) =
try
(* lprintf "Source %d for %d" src num; lprint_newline (); *)
let (row, f) = self#find_file num in
match f.file_sources with
None -> ()
| Some list ->
if List.memq src list then
self#update_file f { f with
file_sources = Some (List.filter
(fun s -> s<>src)
list)
}
row
with Not_found ->
(* some sources are sent for shared files in eDonkey. have to fix that *)
lprintf " No such file % d " num ; ( )
()
method clean_table list =
let set = ref Intset.empty in
List.iter (fun c_num ->
set := Intset.add c_num !set
) list;
self#iter (fun file ->
match file.file_sources with
None -> ()
| Some sources ->
file.file_sources <- Some (List.filter (fun c ->
Intset.mem c !set) sources)
);
let all = Hashtbl2.to_list locations in
Hashtbl.clear locations;
List.iter (fun c ->
if Intset.mem c.client_num !set then
Hashtbl.add locations c.client_num c
) all
method preview () =
match self#selection with
[] -> ()
| file :: _ -> preview file ()
initializer
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.cancel)
~tooltip: (gettext M.cancel)
~icon: (M.o_xpm_cancel)
~callback: self#cancel
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.retry_connect)
~tooltip: (gettext M.retry_connect)
~icon: (M.o_xpm_retry_connect)
~callback: self#retry_connect
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.pause_resume_dl)
~tooltip: (gettext M.pause_resume_dl)
~icon: (M.o_xpm_pause_resume)
~callback: self#pause_resume
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.verify_chunks)
~tooltip: (gettext M.verify_chunks)
~icon: (M.o_xpm_verify_chunks)
~callback: self#verify_chunks
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.preview)
~tooltip: (gettext M.preview)
~icon: (M.o_xpm_preview)
~callback: self#preview
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.get_format)
~tooltip: (gettext M.get_format)
~icon: (M.o_xpm_get_format)
~callback: self#get_format
();
ignore (draw_availability#event#connect#expose (fun _ ->
match last_displayed_file with
None -> true
| Some file ->
redraw_chunks display_caption draw_availability view_availability file; true
));
end
class pane_downloads () =
let wl_status = GMisc.label ~text: "" ~show: true () in
let scroll_box = GPack.vbox () in
let scroll = GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC ~placement:`TOP_LEFT ~packing:scroll_box#add () in
let client_info_box = GPack.vbox ~packing:scroll#add_with_viewport () in
let locs = new Gui_friends.box_list client_info_box false in
let dled = new box_downloaded wl_status () in
let dls = new box_downloads locs wl_status () in
let downloads_frame =
GBin.frame ~border_width:5 ~label:"Running Downloads" ~label_xalign:(-1.0)
~label_yalign:(-1.0) ~shadow_type:`ETCHED_OUT ()
in
let downloaded_frame =
GBin.frame ~border_width:5 ~label:"Completed Downloads"
~label_xalign:(-1.0) ~label_yalign:(-1.0) ~shadow_type:`ETCHED_OUT
()
in
object (self)
inherit Gui_downloads_base.paned ()
method wl_status = wl_status
method box_downloads = dls
method box_downloaded = dled
method box_locations = locs
method set_tb_style st =
locs#set_tb_style st;
dled#set_tb_style st;
dls#set_tb_style st
method clear =
wl_status#set_text "";
locs#clear;
dled#clear;
dls#clear
* { 2 Handling core messages }
method h_file_info f =
match f.file_state with
FileNew -> assert false
| FileCancelled ->
dls#h_cancelled f
| FileDownloaded ->
dls#h_cancelled f;
dled#h_downloaded f
| FileShared ->
dled#h_removed f
| FilePaused | FileQueued | FileAborted _ ->
dls#h_paused f
| FileDownloading ->
dls#h_downloading f
method h_file_availability = dls#h_file_availability
method h_file_age = dls#h_file_age
method h_file_last_seen = dls#h_file_last_seen
method h_file_downloaded = dls#h_file_downloaded
method h_file_location = dls#h_file_location
method h_file_remove_location = dls#h_file_remove_location
method h_update_location c_new =
locs#h_update_location c_new
(* method h_remove_client c = dls#remove_client c *)
method clean_table clients = dls#clean_table clients
method on_entry_return () =
match entry_ed2k_url#text with
"" -> ()
| s ->
Gui_com.send (GuiProto.Url s);
entry_ed2k_url#set_text ""
initializer
Okey.add entry_ed2k_url
~mods: []
GdkKeysyms._Return
self#on_entry_return;
clients_wpane#add1 locs#coerce;
clients_wpane#add2 scroll_box#coerce;
downloaded_frame#add dled#coerce;
downloads_frame#add dls#coerce ;
if !!Gui_options.downloads_up then begin
vpaned#add1 downloads_frame#coerce;
vpaned#add2 downloaded_frame#coerce;
end else begin
vpaned#add2 downloads_frame#coerce;
vpaned#add1 downloaded_frame#coerce;
end
end
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/gtk/gui/gui_downloads.ml | ocaml | * GUI for the lists of files.
try
let (row, f) = self#find_file file_num in
self#update_file f
{ f with file_chunks = chunks ; file_availability = avail }
row
with Not_found -> ()
method remove_client c =
List.iter (fun file ->
match file.file_sources with
None -> ()
| Some sources ->
if List.memq c sources then
let (row, file) = self#find_file file.file_num in
(* lprintf "Removing client from sources";
lprint_newline ();
lprintf "Source %d for %d" src num; lprint_newline ();
some sources are sent for shared files in eDonkey. have to fix that
lprintf "Source %d for %d" src num; lprint_newline ();
some sources are sent for shared files in eDonkey. have to fix that
method h_remove_client c = dls#remove_client c | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Printf2
open Options
open Md4
open Gettext
open Gui_global
open CommonTypes
open GuiTypes
open GuiProto
open Gui_columns
module M = Gui_messages
module P = Gpattern
module O = Gui_options
module G = Gui_global
module VB = VerificationBitmap
let preview file () = Gui_com.send (Preview file.file_num)
let save_menu_items file =
List.map
(fun name ->
`I (name,
(fun _ ->
Gui_com.send (GuiProto.SaveFile (file.file_num, name))
)
)
)
file.file_names
let save_as file () =
let file_opt = GToolbox.input_string ~title: (gettext M.save)
(gettext M.save) in
match file_opt with
None -> ()
| Some name ->
Gui_com.send (GuiProto.SaveFile (file.file_num, name))
let (!!) = Options.(!!)
let file_first_name f = f.file_name
let string_of_file_state state =
match state with
| FileDownloading -> (gettext M.downloading)
| FileCancelled -> (gettext M.cancelled)
| FileQueued -> (gettext M.queued)
| FilePaused -> (gettext M.paused)
| FileDownloaded
| FileShared -> (gettext M.dl_done)
| FileNew -> assert false
| FileAborted s -> Printf.sprintf "Aborted: %s" s
let some_is_available f =
let b = ref false in
List.iter (fun (_, avail) ->
We can not use anymore relative availability as we can not relate the
partial chunks with positions in the availability ...
if ! ! Gui_options.use_relative_availability
then
for i = 0 to String.length avail - 1 do
if CommonGlobals.partial_chunk f.file_chunks.[i ] & &
f.file_availability.[i ] < > ' \000 '
then true
else loop ( i - 1 )
in
loop ( ( String.length f.file_availability ) - 1 )
else
partial chunks with positions in the availability...
if !!Gui_options.use_relative_availability
then
for i = 0 to String.length avail - 1 do
if CommonGlobals.partial_chunk f.file_chunks.[i] &&
f.file_availability.[i] <> '\000'
then true
else loop (i - 1)
in
loop ((String.length f.file_availability) - 1)
else
*)
let len = String.length avail in
for i = 0 to len - 1 do
b := !b || avail.[i] <> '\000'
done;
) f.file_availability;
!b
let color_opt_of_file f =
if f.file_download_rate > 0. then
Some !!O.color_downloading
else if some_is_available f then
Some !!O.color_available
else
Some !!O.color_not_available
let float_avail s =
try float_of_string s
with _ -> 0.0
let file_availability f =
match f.file_chunks with
| None -> "---"
| Some chunks ->
match f.file_availability with
(_,avail) :: _ ->
let rec loop i p n =
if i < 0 then
if n = 0 then "---"
else Printf.sprintf "%5.1f" ((float p) /. (float n) *. 100.0)
else
loop (i - 1)
(if CommonGlobals.partial_chunk (VerificationBitmap.get chunks i) then p + 1 else p)
(if avail.[i] <> (char_of_int 0) then n + 1 else n)
in
loop ((String.length avail) - 1) 0 0
| _ -> "---"
let string_availability f =
let maxi = ref 0. in
List.iter (fun (_, avail) ->
let len = String.length avail in
let p = ref 0 in
for i = 0 to len - 1 do
if avail.[i] <> '\000' then begin
incr p
end
done;
maxi := max !maxi (float_of_int !p /. float_of_int len *. 100.)
) f.file_availability;
Printf.sprintf "%5.1f" !maxi
let string_of_format format =
match format with
AVI f ->
Printf.sprintf "AVI: %s %dx%d %g fps %d bpf"
f.avi_codec f.avi_width f.avi_height
(float_of_int(f.avi_fps) *. 0.001) f.avi_rate
| MP3 (tag, _) ->
let module M = Mp3tag.Id3v1 in
Printf.sprintf "MP3: %s - %s (%d): %s"
tag.M.artist tag.M.album
tag.M.tracknum tag.M.title
| _ -> (gettext M.unknown)
let max_eta = 1000.0 *. 60.0 *. 60.0 *. 24.0
let calc_file_eta f =
let size = Int64.to_float f.file_size in
let downloaded = Int64.to_float f.file_downloaded in
let missing = size -. downloaded in
let rate = f.file_download_rate in
let rate =
if rate = 0.
then
let time = BasicSocket.last_time () in
let age = time - f.file_age in
if age > 0
then downloaded /. (float_of_int age)
else 0.
else rate
in
let eta =
if rate = 0.0 then max_eta else
let eta = missing /. rate in
if eta < 0. || eta > max_eta then max_eta else
eta
in
int_of_float eta
class box columns sel_mode () =
let titles = List.map Gui_columns.File.string_of_column !!columns in
object (self)
inherit [file_info] Gpattern.plist sel_mode titles true (fun f -> f.file_num) as pl
inherit Gui_downloads_base.box () as box
val mutable columns = columns
method set_columns l =
columns <- l;
self#set_titles (List.map Gui_columns.File.string_of_column !!columns);
self#update
method column_menu i =
[
`I ("Autosize", fun _ -> self#wlist#columns_autosize ());
`I ("Sort", self#resort_column i);
`I ("Remove Column",
(fun _ ->
match !!columns with
_ :: _ :: _ ->
(let l = !!columns in
match List2.cut i l with
l1, _ :: l2 ->
columns =:= l1 @ l2;
self#set_columns columns
| _ -> ())
| _ -> ()
)
);
`M ("Add Column After", (
List.map (fun (c,s) ->
(`I (s, (fun _ ->
let c1, c2 = List2.cut (i+1) !!columns in
columns =:= c1 @ [c] @ c2;
self#set_columns columns
)))
) Gui_columns.file_column_strings));
`M ("Add Column Before", (
List.map (fun (c,s) ->
(`I (s, (fun _ ->
let c1, c2 = List2.cut i !!columns in
columns =:= c1 @ [c] @ c2;
self#set_columns columns
)))
) Gui_columns.file_column_strings));
]
method box = box#coerce
method vbox = box#vbox
method compare_by_col col f1 f2 =
match col with
| Col_file_name -> compare f1.file_name f2.file_name
| Col_file_size -> compare f1.file_size f2.file_size
| Col_file_downloaded -> compare f1.file_downloaded f2.file_downloaded
| Col_file_percent -> compare
(Int64.to_float f1.file_downloaded /. Int64.to_float f1.file_size)
(Int64.to_float f2.file_downloaded /. Int64.to_float f2.file_size)
| Col_file_rate-> compare f1.file_download_rate f2.file_download_rate
| Col_file_state -> compare f1.file_state f2.file_state
| Col_file_availability ->
let fn =
if !!Gui_options.use_relative_availability
then file_availability
else string_availability
in
compare (float_avail (fn f1)) (float_avail (fn f2))
| Col_file_md4 -> compare (Md4.to_string f1.file_md4) (Md4.to_string f2.file_md4)
| Col_file_format -> compare f1.file_format f2.file_format
| Col_file_network -> compare f1.file_network f2.file_network
| Col_file_age -> compare f1.file_age f2.file_age
| Col_file_last_seen -> compare f1.file_last_seen f2.file_last_seen
| Col_file_eta -> compare (calc_file_eta f1) (calc_file_eta f2)
| Col_file_priority -> compare f1.file_priority f2.file_priority
method compare f1 f2 =
let abs = if current_sort >= 0 then current_sort else - current_sort in
let col =
try List.nth !!columns (abs - 1)
with _ -> Col_file_name
in
let res = self#compare_by_col col f1 f2 in
current_sort * res
method content_by_col f col =
match col with
Col_file_name ->
let s_file = Gui_misc.short_name f.file_name in
s_file
| Col_file_size ->
Gui_misc.size_of_int64 f.file_size
| Col_file_downloaded ->
Gui_misc.size_of_int64 f.file_downloaded
| Col_file_percent ->
Printf.sprintf "%5.1f"
(Int64.to_float f.file_downloaded /. Int64.to_float f.file_size *. 100.)
| Col_file_rate ->
if f.file_download_rate > 0. then
Printf.sprintf "%5.1f" (f.file_download_rate /. 1024.)
else ""
| Col_file_state ->
string_of_file_state f.file_state
| Col_file_availability ->
if !!Gui_options.use_relative_availability
then file_availability f
else string_availability f
| Col_file_md4 -> Md4.to_string f.file_md4
| Col_file_format -> string_of_format f.file_format
| Col_file_network -> Gui_global.network_name f.file_network
| Col_file_age ->
let age = (BasicSocket.last_time ()) - f.file_age in
Date.time_to_string age "long"
| Col_file_last_seen ->
if f.file_last_seen > 0
then let last = (BasicSocket.last_time ())
- f.file_last_seen in
Date.time_to_string last "long"
else Printf.sprintf "---"
| Col_file_eta ->
let eta = calc_file_eta f in
if eta >= 1000 * 60 * 60 * 24 then
Printf.sprintf "---"
else Date.time_to_string eta "long"
| Col_file_priority ->
Printf.sprintf "%3d" f.file_priority
method content f =
let strings = List.map
(fun col -> P.String (self#content_by_col f col))
!!columns
in
let col_opt =
match color_opt_of_file f with
None -> Some `BLACK
| Some c -> Some (`NAME c)
in
(strings, col_opt)
method find_file num = self#find num
method remove_file f row =
self#remove_item row f;
selection <- List.filter (fun fi -> fi.file_num <> f.file_num) selection
method set_tb_style tb =
if Options.(!!) Gui_options.mini_toolbars then
(wtool1#misc#hide (); wtool2#misc#show ()) else
(wtool2#misc#hide (); wtool1#misc#show ());
wtool2#set_style tb;
wtool1#set_style tb
initializer
box#vbox#pack ~expand: true pl#box;
end
class box_downloaded wl_status () =
object (self)
inherit box O.downloaded_columns `SINGLE () as super
method update_wl_status : unit =
wl_status#set_text
(Printf.sprintf !!Gui_messages.downloaded_files !G.ndownloaded !G.ndownloads)
method content f =
(fst (super#content f), Some (`NAME !!O.color_downloaded))
method save ev =
match self#selection with
f :: _ ->
let items = save_menu_items f in
GAutoconf.popup_menu ~entries: items ~button: 1 ~time: 0
| _ ->
()
method save_all () =
self#iter (fun f ->
Gui_com.send (GuiProto.SaveFile (f.file_num, file_first_name f)))
method edit_mp3_tags () =
match self#selection with
file :: _ ->
(
match file.file_format with
MP3 (tag,_) ->
Mp3_ui.edit_tag_v1 (gettext M.edit_mp3) tag ;
Gui_com.send (GuiProto.ModifyMp3Tags (file.file_num, tag))
| _ ->
()
)
| _ ->
()
method menu =
match self#selection with
[] -> [ `I ((gettext M.save_all), self#save_all) ]
| file :: _ ->
[
`I ((gettext M.save_as), save_as file) ;
`M ((gettext M.save), save_menu_items file) ;
`I ((gettext M.preview), preview file) ;
] @
(match file.file_format with
MP3 _ -> [`I ((gettext M.edit_mp3), self#edit_mp3_tags)]
| _ -> []) @
[ `S ;
`I ((gettext M.save_all), self#save_all)
]
* { 2 Handling core messages }
method h_downloaded f =
try
ignore (self#find_file f.file_num)
with
Not_found ->
incr ndownloaded;
self#update_wl_status ;
self#add_item f
method h_removed f =
try
let (row, _) = self#find_file f.file_num in
decr ndownloaded;
self#update_wl_status ;
self#remove_file f row
with
Not_found ->
()
method preview () =
match self#selection with
[] -> ()
| file :: _ -> preview file ()
method save_as () =
match self#selection with
| [] -> ()
| file :: _ -> save_as file ()
initializer
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.save)
~tooltip: (gettext M.save)
~icon: (M.o_xpm_save)
~callback: self#save
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.save_as)
~tooltip: (gettext M.save_as)
~icon: (M.o_xpm_save_as)
~callback: self#save_as
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.save_all)
~tooltip: (gettext M.save_all)
~icon: (M.o_xpm_save_all)
~callback: self#save_all
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.edit_mp3)
~tooltip: (gettext M.edit_mp3)
~icon: (M.o_xpm_edit_mp3)
~callback: self#edit_mp3_tags
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.preview)
~tooltip: (gettext M.preview)
~icon: (M.o_xpm_preview)
~callback: self#preview
();
end
let colorGreen = `NAME "green"
let colorRed = `NAME "red"
let colorBlue = `NAME "blue"
let colorGray = `NAME "gray"
let colorWhite =`WHITE
let colorBlack = `BLACK
let colorCyan = `NAME "cyan"
let drawing = ref (None : [ `window] GDraw.drawable option)
let draw_chunks (drawing : unit GDraw.drawable) file =
match file.file_chunks with
| None -> ()
| Some chunks ->
let wx, wy = drawing#size in
drawing#set_foreground colorWhite;
drawing#rectangle ~filled: true ~x:0 ~y:0 ~width:wx ~height:wy ();
let nchunks = VerificationBitmap.length chunks in
let dx = min !!O.chunk_width (wx / nchunks) in
if wx > nchunks*dx && dx > 0 then
let offset = (wx - nchunks * dx) / 2 in
let offset = if offset < 0 then 0 else offset in
let dx2 = if dx <= 2 then dx else dx - 1 in
for i = 0 to nchunks - 1 do
drawing#set_foreground (
match VerificationBitmap.get chunks i with
| VerificationBitmap.State_missing -> colorRed
| VerificationBitmap.State_partial -> colorBlue
| VerificationBitmap.State_complete -> colorBlack
| VerificationBitmap.State_verified -> colorGreen);
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ()
done
else
let group = (nchunks+wx-1) / wx in
let chunk n =
let p = n * group in
let get i =
if i < nchunks then VerificationBitmap.get chunks i
else VerificationBitmap.State_complete
in
let current = ref 0 in
for i = p to p+group-1 do
match get i with
| VB.State_missing -> ()
| VB.State_partial -> if !current = 0 then current := 1
| VB.State_complete | VB.State_verified ->
current := 2
done;
String.make 1 (char_of_int !current)
in
let dx = 1 in
let nchunks = nchunks / group in
let offset = (wx - nchunks * dx) / 2 in
let offset = if offset < 0 then 0 else offset in
let dx2 = if dx <= 2 then dx else dx - 1 in
for i = 0 to nchunks - 1 do
let chunk = chunk i in
drawing#set_foreground (
match VerificationBitmap.get chunks i with
| VerificationBitmap.State_missing -> colorRed
| VerificationBitmap.State_partial -> colorBlue
| VerificationBitmap.State_complete -> colorBlack
| VerificationBitmap.State_verified -> colorGreen);
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ()
done
let draw_availability (drawing: unit GDraw.drawable) availability =
let wx, wy = drawing#size in
drawing#set_foreground colorWhite;
drawing#rectangle ~filled: true ~x:0 ~y:0 ~width:wx ~height:wy ();
let nchunks = String.length availability in
let dx = min !!O.chunk_width (wx / nchunks) in
if wx > nchunks*dx && dx > 0 then
let offset = (wx - nchunks * dx) / 2 in
let offset = if offset < 0 then 0 else offset in
let dx2 = if dx <= 2 then dx else dx - 1 in
for i = 0 to nchunks - 1 do
if !!Gui_options.use_availability_height
then begin
let h = int_of_char (availability.[i])
in
if h = 0
then
begin
drawing#set_foreground colorRed;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ();
end
else begin
let h = min ((wy * h) / !!Gui_options.availability_max) wy in
drawing#set_foreground colorGray;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height: (wy - h) ();
drawing#set_foreground colorBlue;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: (wy - h)
~width: dx2 ~height:h ();
end
end else begin
drawing#set_foreground (
match int_of_char availability.[i] with
0 -> colorRed
| 1 -> colorBlue
| _ -> colorBlack);
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ()
end
done
else
let group = (nchunks+wx-1) / wx in
let avail i =
let p = i * group in
let get i =
if i < nchunks then availability.[i] else '\200'
in
let current = ref (get p) in
for i = p+1 to p+group-1 do
current := min (get i) !current
done;
!current
in
let dx = 1 in
let nchunks = nchunks / group in
let offset = (wx - nchunks * dx) / 2 in
let offset = if offset < 0 then 0 else offset in
let dx2 = if dx <= 2 then dx else dx - 1 in
for i = 0 to nchunks - 1 do
let avail = avail i in
if !!Gui_options.use_availability_height
then begin
let h = int_of_char avail
in
if h = 0
then
begin
drawing#set_foreground colorRed;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ();
end
else begin
let h = min ((wy * h) / !!Gui_options.availability_max) wy in
drawing#set_foreground colorGray;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height: (wy - h) ();
drawing#set_foreground colorBlue;
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: (wy - h)
~width: dx2 ~height:h ();
end
end else begin
drawing#set_foreground (
match int_of_char avail with
0 -> colorRed
| 1 -> colorBlue
| _ -> colorBlack);
drawing#rectangle ~filled: true
~x:(offset + i*dx) ~y: 0
~width: dx2 ~height:wy ()
end
done
let redraw_chunks display_caption draw_avail view_availability file =
let (drawing : unit GDraw.drawable) = match !drawing with
None ->
let w = draw_avail#misc#window in
let d = new GDraw.drawable w in
draw_avail#misc#show ();
drawing := Some d;
d
| Some d -> d
in
try
if view_availability = 0 then begin
display_caption#set_text "Downloaded Chunks";
draw_chunks drawing file
end else
let (net, a) =
List.nth file.file_availability (view_availability-1) in
display_caption#set_text (Printf.sprintf "Availability on %s"
(try (Hashtbl.find networks net).net_name with _ -> "??"));
draw_availability drawing a
with e ->
Printf2.lprintf "Exception %s during drawing\n"
(Printexc2.to_string e)
class box_downloads box_locs wl_status () =
let draw_availability =
GMisc.drawing_area ~height:20
()
in
let display_caption =
GMisc.label ~text:"Current chunks" ~justify:`LEFT ~line_wrap:true
~xalign:(-1.0) ~yalign:(-1.0) ()
in
let label_file_info = GMisc.label () in
object (self)
inherit box O.downloads_columns `EXTENDED ()
method update_wl_status : unit =
wl_status#set_text
(Printf.sprintf !!Gui_messages.downloaded_files !G.ndownloaded !G.ndownloads)
method cancel () =
let s = Gui_messages.ask_cancel_download_files
(List.map (fun f -> file_first_name f) self#selection)
in
match GToolbox.question_box (gettext Gui_messages.cancel)
[ gettext Gui_messages.yes ; gettext Gui_messages.no] s
with
1 ->
List.iter
(fun f -> Gui_com.send (RemoveDownload_query f.file_num))
self#selection
| _ ->
()
method retry_connect () =
List.iter
(fun f -> Gui_com.send (ConnectAll f.file_num))
self#selection
method pause_resume () =
List.iter
(fun f -> Gui_com.send (SwitchDownload (f.file_num,
match f.file_state with
FilePaused | FileAborted _ -> true
| _ -> false
)))
self#selection
method verify_chunks () =
List.iter
(fun f -> Gui_com.send (VerifyAllChunks f.file_num))
self#selection
method get_format () =
List.iter
(fun f -> Gui_com.send (QueryFormat f.file_num))
self#selection
method set_priority prio () =
List.iter
(fun f -> Gui_com.send (SetFilePriority (f.file_num, prio)))
self#selection
method menu =
match self#selection with
[] -> []
| file :: tail ->
`I ((gettext M.pause_resume_dl), self#pause_resume) ::
`I ((gettext M.retry_connect), self#retry_connect) ::
`I ((gettext M.cancel), self#cancel) ::
`I ((gettext M.verify_chunks), self#verify_chunks) ::
`M ("Set priority", [
`I ("High", self#set_priority 10);
`I ("Normal", self#set_priority 0);
`I ("Low", self#set_priority (-10));
]) ::
`I ((gettext M.get_format), self#get_format) ::
(if tail = [] then
[
`I ((gettext M.preview), preview file) ;
`M ((gettext M.save), save_menu_items file) ;
`I ((gettext M.save_as), save_as file) ;
]
else [])
0 = current chunks , 1 - n availability
val mutable view_availability = 0
val mutable last_displayed_file = None
val mutable label_shown = false
method on_select file =
if not label_shown then begin
label_shown <- true;
let hbox = GPack.hbox ~homogeneous:false () in
let button = GButton.button () in
self#vbox#pack ~expand: false ~fill: true label_file_info#coerce ;
self#vbox#pack ~expand:false ~fill:true hbox#coerce;
hbox#pack ~expand:false ~fill:false button#coerce;
hbox#add draw_availability#coerce;
button#add display_caption#coerce;
ignore (button#connect#clicked (fun _ ->
match last_displayed_file with
Some file ->
let n = view_availability + 1 in
lprintf " view_availability % d/%d\n " n
( file.file_availability ) ;
(List.length file.file_availability); *)
view_availability <- (if
n > List.length file.file_availability
then 0 else n);
redraw_chunks display_caption draw_availability view_availability file;
| _ -> ()));
end;
label_file_info#set_text
(
Printf.sprintf "NAME: %s SIZE: %s FORMAT: %s"
(file.file_name)
(Int64.to_string file.file_size)
(string_of_format file.file_format)
;
);
view_availability <- 0;
redraw_chunks display_caption draw_availability view_availability file;
last_displayed_file <- Some file;
box_locs#update_data_by_file (Some file)
method on_deselect _ =
box_locs#update_data_by_file None
* { 2 Handling core messages }
method update_file f f_new row =
f.file_md4 <- f_new.file_md4 ;
f.file_name <- f_new.file_name ;
f.file_names <- f_new.file_names ;
f.file_size <- f_new.file_size ;
f.file_downloaded <- f_new.file_downloaded ;
f.file_all_sources <- f_new.file_all_sources ;
f.file_active_sources <- f_new.file_active_sources ;
f.file_state <- f_new.file_state ;
let must_redraw =
(f.file_chunks <> f_new.file_chunks) ||
(f.file_availability <> f_new.file_availability)
in
f.file_chunks <- f_new.file_chunks ;
f.file_availability <- f_new.file_availability ;
f.file_priority <- f_new.file_priority;
if f_new.file_sources <> None then
f.file_sources <- f_new.file_sources ;
f.file_download_rate <- f_new.file_download_rate ;
f.file_format <- f_new.file_format;
f.file_age <- f_new.file_age;
f.file_last_seen <- f_new.file_last_seen;
self#update_row f row;
if must_redraw then
match last_displayed_file with
| Some file when f == file ->
redraw_chunks display_caption draw_availability view_availability file;
| _ -> ()
method h_file_downloaded num dled rate =
try
let (row, f) = self#find_file num in
self#update_file f
{ f with file_downloaded = dled ; file_download_rate = rate }
row
with
Not_found ->
()
method h_paused f =
try
let (row, fi) = self#find_file f.file_num in
self#update_file fi f row
with
Not_found ->
incr ndownloads;
self#update_wl_status ;
self#add_item f
method h_cancelled f =
try
let (row, fi) = self#find_file f.file_num in
decr ndownloads;
self#update_wl_status ;
self#remove_file fi row
with
Not_found ->
()
method h_downloaded = self#h_cancelled
method h_downloading f = self#h_paused f
method h_file_availability file_num client_num avail =
try
let files = Intmap.find client_num !availabilities in
try
let (s,file) = Intmap.find file_num !files in
String.blit avail 0 s 0 (String.length avail);
with _ ->
let _, file = self#find_file file_num in
files := Intmap.add file_num (avail,file) !files
with _ ->
let _, file = self#find_file file_num in
availabilities := Intmap.add client_num
(ref (Intmap.add file_num (avail,file) Intmap.empty)) !availabilities
self#update_file file { file with file_sources = Some (
List.filter (fun cc -> cc != c) sources) }
row
) data
*)
method h_file_age num age =
try
let (row, f) = self#find_file num in
self#update_file f
{ f with file_age = age }
row
with Not_found -> ()
method h_file_last_seen num last =
try
let (row, f) = self#find_file num in
self#update_file f
{ f with file_last_seen = last }
row
with Not_found -> ()
method h_file_location num src =
try
let (row, f) = self#find_file num in
self#update_file f
{ f with
file_sources = Some (
(match f.file_sources with
None -> [src]
| Some list -> if not (List.mem src list) then
list@[src] else list ))
}
row
with Not_found ->
lprintf " No such file % d " num ; ( )
()
method h_file_remove_location (num:int) (src:int) =
try
let (row, f) = self#find_file num in
match f.file_sources with
None -> ()
| Some list ->
if List.memq src list then
self#update_file f { f with
file_sources = Some (List.filter
(fun s -> s<>src)
list)
}
row
with Not_found ->
lprintf " No such file % d " num ; ( )
()
method clean_table list =
let set = ref Intset.empty in
List.iter (fun c_num ->
set := Intset.add c_num !set
) list;
self#iter (fun file ->
match file.file_sources with
None -> ()
| Some sources ->
file.file_sources <- Some (List.filter (fun c ->
Intset.mem c !set) sources)
);
let all = Hashtbl2.to_list locations in
Hashtbl.clear locations;
List.iter (fun c ->
if Intset.mem c.client_num !set then
Hashtbl.add locations c.client_num c
) all
method preview () =
match self#selection with
[] -> ()
| file :: _ -> preview file ()
initializer
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.cancel)
~tooltip: (gettext M.cancel)
~icon: (M.o_xpm_cancel)
~callback: self#cancel
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.retry_connect)
~tooltip: (gettext M.retry_connect)
~icon: (M.o_xpm_retry_connect)
~callback: self#retry_connect
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.pause_resume_dl)
~tooltip: (gettext M.pause_resume_dl)
~icon: (M.o_xpm_pause_resume)
~callback: self#pause_resume
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.verify_chunks)
~tooltip: (gettext M.verify_chunks)
~icon: (M.o_xpm_verify_chunks)
~callback: self#verify_chunks
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.preview)
~tooltip: (gettext M.preview)
~icon: (M.o_xpm_preview)
~callback: self#preview
();
Gui_misc.insert_buttons wtool1 wtool2
~text: (gettext M.get_format)
~tooltip: (gettext M.get_format)
~icon: (M.o_xpm_get_format)
~callback: self#get_format
();
ignore (draw_availability#event#connect#expose (fun _ ->
match last_displayed_file with
None -> true
| Some file ->
redraw_chunks display_caption draw_availability view_availability file; true
));
end
class pane_downloads () =
let wl_status = GMisc.label ~text: "" ~show: true () in
let scroll_box = GPack.vbox () in
let scroll = GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC ~placement:`TOP_LEFT ~packing:scroll_box#add () in
let client_info_box = GPack.vbox ~packing:scroll#add_with_viewport () in
let locs = new Gui_friends.box_list client_info_box false in
let dled = new box_downloaded wl_status () in
let dls = new box_downloads locs wl_status () in
let downloads_frame =
GBin.frame ~border_width:5 ~label:"Running Downloads" ~label_xalign:(-1.0)
~label_yalign:(-1.0) ~shadow_type:`ETCHED_OUT ()
in
let downloaded_frame =
GBin.frame ~border_width:5 ~label:"Completed Downloads"
~label_xalign:(-1.0) ~label_yalign:(-1.0) ~shadow_type:`ETCHED_OUT
()
in
object (self)
inherit Gui_downloads_base.paned ()
method wl_status = wl_status
method box_downloads = dls
method box_downloaded = dled
method box_locations = locs
method set_tb_style st =
locs#set_tb_style st;
dled#set_tb_style st;
dls#set_tb_style st
method clear =
wl_status#set_text "";
locs#clear;
dled#clear;
dls#clear
* { 2 Handling core messages }
method h_file_info f =
match f.file_state with
FileNew -> assert false
| FileCancelled ->
dls#h_cancelled f
| FileDownloaded ->
dls#h_cancelled f;
dled#h_downloaded f
| FileShared ->
dled#h_removed f
| FilePaused | FileQueued | FileAborted _ ->
dls#h_paused f
| FileDownloading ->
dls#h_downloading f
method h_file_availability = dls#h_file_availability
method h_file_age = dls#h_file_age
method h_file_last_seen = dls#h_file_last_seen
method h_file_downloaded = dls#h_file_downloaded
method h_file_location = dls#h_file_location
method h_file_remove_location = dls#h_file_remove_location
method h_update_location c_new =
locs#h_update_location c_new
method clean_table clients = dls#clean_table clients
method on_entry_return () =
match entry_ed2k_url#text with
"" -> ()
| s ->
Gui_com.send (GuiProto.Url s);
entry_ed2k_url#set_text ""
initializer
Okey.add entry_ed2k_url
~mods: []
GdkKeysyms._Return
self#on_entry_return;
clients_wpane#add1 locs#coerce;
clients_wpane#add2 scroll_box#coerce;
downloaded_frame#add dled#coerce;
downloads_frame#add dls#coerce ;
if !!Gui_options.downloads_up then begin
vpaned#add1 downloads_frame#coerce;
vpaned#add2 downloaded_frame#coerce;
end else begin
vpaned#add2 downloads_frame#coerce;
vpaned#add1 downloaded_frame#coerce;
end
end
|
1fad9ebc92621652d2003bf1bb067d54484dd53c9d04e52d2995b12a31135f75 | protz/mezzo | Mark.ml | (*****************************************************************************)
(* Mezzo, a programming language based on permissions *)
Copyright ( C ) 2011 , 2012 and
(* *)
(* This program is free software: you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
(* along with this program. If not, see </>. *)
(* *)
(*****************************************************************************)
type t = unit ref
let create () =
ref ()
let equals =
(==)
| null | https://raw.githubusercontent.com/protz/mezzo/4e9d917558bd96067437116341b7a6ea02ab9c39/typing/Mark.ml | ocaml | ***************************************************************************
Mezzo, a programming language based on permissions
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
*************************************************************************** | Copyright ( C ) 2011 , 2012 and
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
type t = unit ref
let create () =
ref ()
let equals =
(==)
|
7ac1aff0f88c28df75ddbc274db8f8cab8df40fbf1fee210f306b4618b92baeb | mbillingr/lisp-in-small-pieces | common.scm |
(define-library (06-fast-interpreter common)
(export activation-frame-argument
activation-frame-argument-length
allocate-activation-frame
compute-kind
definitial
description-extend!
environment-next
g.current
g.current-extend!
g.init
g.init-extend!
get-description
global-fetch
global-update!
listify!
predefined-fetch
r.init
r-extend*
sg.current
sg.current.names
sg.init
sr.init
sr-extend*
set-activation-frame-argument!
static-wrong
undefined-value)
(import (builtin core)
(libs utils)
(libs book))
(begin
(define (static-wrong message . culprits)
(println `(*static-error* ,message . ,culprits))
(lambda _args
(apply wrong (cons message culprits))))
(define (deep-fetch sr i j)
(if (= i 0)
(activation-frame-argument sr j)
(deep-fetch (environment-next sr) (- i 1) j)))
(define (deep-update! sr i j v)
(if (= i 0)
(set-activation-frame-argument! sr j v)
(deep-update! (environment-next sr) (- i 1) j v)))
(define (r-extend* r n*)
(cons n* r))
(define g.current '())
(define g.init '())
(define (sr-extend* sr v*)
(set-environment-next! v* sr)
v*)
(define r.init '())
(define sr.init '())
(define (compute-kind r n)
(or (local-variable? r 0 n)
(global-variable? g.current n)
(global-variable? g.init n)))
(define (g.current-extend! n)
(let ((level (length g.current)))
(set! g.current (cons (cons n `(global . ,level)) g.current))
level))
(define (g.init-extend! n)
(let ((level (length g.init)))
(set! g.init (cons (cons n `(predefined . ,level)) g.init))
level))
(define (global-variable? g n)
(let ((var (assq n g)))
(and (pair? var) (cdr var))))
(define (local-variable? r i n)
(define (scan names j)
(cond ((pair? names) (if (eq? n (car names))
`(local ,i . ,j)
(scan (cdr names) (+ 1 j))))
((null? names) (local-variable? (cdr r) (+ i 1) n))
((eq? n names) `(local ,i . ,j))))
(and (pair? r)
(scan (car r) 0)))
(define (listify! v* arity)
(define (loop index result)
(if (= arity index)
(set-activation-frame-argument! v* arity result)
(loop (- index 1)
(cons (activation-frame-argument v* (- index 1))
result))))
(loop (- (activation-frame-argument-length v*) 1) '()))
(define (definitial name value)
(g.init-initialize! name value))
(define sg.current (make-vector 100))
(define sg.init (make-vector 100))
(define sg.current.names '())
(define (global-fetch i)
(vector-ref sg.current i))
(define (global-update! i v)
(vector-set! sg.current i v))
(define (predefined-fetch i)
(vector-ref sg.init i))
(define (g.current-initialize! name)
(let ((kind (compute-kind r.init name)))
(if kind
(case (car kind)
((global)
(vector-set! sg.current (cdr kind) undefined-value))
(else (static-wrong "Wrong redefinition" name)))
(let ((index (g.current-extend! name)))
(vector-set! sg.current index undefined-value))))
name)
(define (g.init-initialize! name value)
(let ((kind (compute-kind r.init name)))
(if kind
(case (car kind)
((predefined)
(vector-set! sg.init (cdr kind) value))
(else (static-wrong "Wrong redefinition" name)))
(let ((index (g.init-extend! name)))
(vector-set! sg.init index value))))
name)
(define desc.init '())
(define (description-extend! name description)
(set! desc.init (cons (cons name description) desc.init))
name)
(define (get-description name)
(let ((p (assq name desc.init)))
(and (pair? p) (cdr p))))
(define undefined-value '*undefined*)
(g.current-initialize! 'x)
(g.current-initialize! 'y)
(g.current-initialize! 'z)
(g.current-initialize! 'foo)
(g.current-initialize! 'bar)
; The following implementations are not defined in the book, so I'm making them up...
(define (environment-next frame)
(car frame))
(define (set-environment-next! frame sr)
(set-car! frame sr))
(define (allocate-activation-frame size)
(list '() (make-vector size) size))
(define (activation-frame-argument frame index)
(vector-ref (cadr frame) index))
(define (set-activation-frame-argument! frame index value)
(vector-set! (cadr frame) index value))
(define (activation-frame-argument-length frame)
(caddr frame))))
| null | https://raw.githubusercontent.com/mbillingr/lisp-in-small-pieces/b2b158dfa91dc95d75af4bd7d93f8df22219047e/06-fast-interpreter/common.scm | scheme | The following implementations are not defined in the book, so I'm making them up... |
(define-library (06-fast-interpreter common)
(export activation-frame-argument
activation-frame-argument-length
allocate-activation-frame
compute-kind
definitial
description-extend!
environment-next
g.current
g.current-extend!
g.init
g.init-extend!
get-description
global-fetch
global-update!
listify!
predefined-fetch
r.init
r-extend*
sg.current
sg.current.names
sg.init
sr.init
sr-extend*
set-activation-frame-argument!
static-wrong
undefined-value)
(import (builtin core)
(libs utils)
(libs book))
(begin
(define (static-wrong message . culprits)
(println `(*static-error* ,message . ,culprits))
(lambda _args
(apply wrong (cons message culprits))))
(define (deep-fetch sr i j)
(if (= i 0)
(activation-frame-argument sr j)
(deep-fetch (environment-next sr) (- i 1) j)))
(define (deep-update! sr i j v)
(if (= i 0)
(set-activation-frame-argument! sr j v)
(deep-update! (environment-next sr) (- i 1) j v)))
(define (r-extend* r n*)
(cons n* r))
(define g.current '())
(define g.init '())
(define (sr-extend* sr v*)
(set-environment-next! v* sr)
v*)
(define r.init '())
(define sr.init '())
(define (compute-kind r n)
(or (local-variable? r 0 n)
(global-variable? g.current n)
(global-variable? g.init n)))
(define (g.current-extend! n)
(let ((level (length g.current)))
(set! g.current (cons (cons n `(global . ,level)) g.current))
level))
(define (g.init-extend! n)
(let ((level (length g.init)))
(set! g.init (cons (cons n `(predefined . ,level)) g.init))
level))
(define (global-variable? g n)
(let ((var (assq n g)))
(and (pair? var) (cdr var))))
(define (local-variable? r i n)
(define (scan names j)
(cond ((pair? names) (if (eq? n (car names))
`(local ,i . ,j)
(scan (cdr names) (+ 1 j))))
((null? names) (local-variable? (cdr r) (+ i 1) n))
((eq? n names) `(local ,i . ,j))))
(and (pair? r)
(scan (car r) 0)))
(define (listify! v* arity)
(define (loop index result)
(if (= arity index)
(set-activation-frame-argument! v* arity result)
(loop (- index 1)
(cons (activation-frame-argument v* (- index 1))
result))))
(loop (- (activation-frame-argument-length v*) 1) '()))
(define (definitial name value)
(g.init-initialize! name value))
(define sg.current (make-vector 100))
(define sg.init (make-vector 100))
(define sg.current.names '())
(define (global-fetch i)
(vector-ref sg.current i))
(define (global-update! i v)
(vector-set! sg.current i v))
(define (predefined-fetch i)
(vector-ref sg.init i))
(define (g.current-initialize! name)
(let ((kind (compute-kind r.init name)))
(if kind
(case (car kind)
((global)
(vector-set! sg.current (cdr kind) undefined-value))
(else (static-wrong "Wrong redefinition" name)))
(let ((index (g.current-extend! name)))
(vector-set! sg.current index undefined-value))))
name)
(define (g.init-initialize! name value)
(let ((kind (compute-kind r.init name)))
(if kind
(case (car kind)
((predefined)
(vector-set! sg.init (cdr kind) value))
(else (static-wrong "Wrong redefinition" name)))
(let ((index (g.init-extend! name)))
(vector-set! sg.init index value))))
name)
(define desc.init '())
(define (description-extend! name description)
(set! desc.init (cons (cons name description) desc.init))
name)
(define (get-description name)
(let ((p (assq name desc.init)))
(and (pair? p) (cdr p))))
(define undefined-value '*undefined*)
(g.current-initialize! 'x)
(g.current-initialize! 'y)
(g.current-initialize! 'z)
(g.current-initialize! 'foo)
(g.current-initialize! 'bar)
(define (environment-next frame)
(car frame))
(define (set-environment-next! frame sr)
(set-car! frame sr))
(define (allocate-activation-frame size)
(list '() (make-vector size) size))
(define (activation-frame-argument frame index)
(vector-ref (cadr frame) index))
(define (set-activation-frame-argument! frame index value)
(vector-set! (cadr frame) index value))
(define (activation-frame-argument-length frame)
(caddr frame))))
|
5c15290bfcf0b54fad89c08ff448769da57e4c8822ef60c5bd37e1a56591771e | reflectionalist/S9fES | draw-tree.scm | Scheme 9 from Empty Space , Function Library
By , 2009 - 2012
; Placed in the Public Domain
;
; (draw-tree object) ==> unspecific
;
; Print a tree structure resembling a Scheme datum. Each cons
cell is represented by [ ] with lines leading to their car
and cdr parts . Conses with a cdr value of ( ) are represented
by [ ] .
;
; (Example): (draw-tree '((a) (b . c) (d e))) ==> unspecific
;
; Output: [o|o]---[o|o]---[o|/]
; | | |
[ ] | [ o|o]---[o|/ ]
; | | | |
; a | d e
; |
; [o|o]--- c
; |
; b
(define (draw-tree n)
(define *nothing* (cons 'N '()))
(define *visited* (cons 'V '()))
(define (empty? x) (eq? x *nothing*))
(define (visited? x) (eq? (car x) *visited*))
(define (mark-visited x) (cons *visited* x))
(define (members-of x) (cdr x))
(define (done? x)
(and (pair? x)
(visited? x)
(null? (cdr x))))
(define (draw-fixed-string s)
(let* ((b (make-string 8 #\space))
(k (string-length s))
(s (if (> k 7) (substring s 0 7) s))
(s (if (< k 3) (string-append " " s) s))
(k (string-length s)))
(display (string-append s (substring b 0 (- 8 k))))))
(define (draw-atom n)
(cond ((null? n)
(draw-fixed-string "()"))
((symbol? n)
(draw-fixed-string (symbol->string n)))
((number? n)
(draw-fixed-string (number->string n)))
((string? n)
(draw-fixed-string (string-append "\"" n "\"")))
((char? n)
(draw-fixed-string (string-append "#\\" (string n))))
((eq? n #t)
(draw-fixed-string "#t"))
((eq? n #f)
(draw-fixed-string "#f"))
(else
(error "draw-atom: unknown type" n))))
(define (draw-conses n)
(let draw-conses ((n n)
(r '()))
(cond ((not (pair? n))
(draw-atom n)
(reverse! r))
((null? (cdr n))
(display "[o|/]")
(reverse! (cons (car n) r)))
(else
(display "[o|o]---")
(draw-conses (cdr n) (cons (car n) r))))))
(define (draw-bars n)
(let draw-bars ((n (members-of n)))
(cond ((not (pair? n)))
((empty? (car n))
(draw-fixed-string "")
(draw-bars (cdr n)))
((and (pair? (car n))
(visited? (car n)))
(draw-bars (members-of (car n)))
(draw-bars (cdr n)))
(else
(draw-fixed-string "|")
(draw-bars (cdr n))))))
(define (skip-empty n)
(if (and (pair? n)
(or (empty? (car n))
(done? (car n))))
(skip-empty (cdr n))
n))
(define (remove-trailing-nothing n)
(reverse (skip-empty (reverse n))))
(define (all-vertical? n)
(or (not (pair? n))
(and (null? (cdr n))
(all-vertical? (car n)))))
(define (draw-members n)
(let draw-members ((n (members-of n))
(r '()))
(cond ((not (pair? n))
(mark-visited
(remove-trailing-nothing
(reverse r))))
((empty? (car n))
(draw-fixed-string "")
(draw-members (cdr n)
(cons *nothing* r)))
((not (pair? (car n)))
(draw-atom (car n))
(draw-members (cdr n)
(cons *nothing* r)))
((null? (cdr n))
(draw-members (cdr n)
(cons (draw-final (car n)) r)))
((all-vertical? (car n))
(draw-fixed-string "[o|/]")
(draw-members (cdr n)
(cons (caar n) r)))
(else
(draw-fixed-string "|")
(draw-members (cdr n)
(cons (car n) r))))))
(define (draw-final n)
(cond ((not (pair? n))
(draw-atom n)
*nothing*)
((visited? n)
(draw-members n))
(else
(mark-visited (draw-conses n)))))
(if (not (pair? n))
(draw-atom n)
(let draw-tree ((n (mark-visited (draw-conses n))))
(if (not (done? n))
(begin (newline)
(draw-bars n)
(newline)
(draw-tree (draw-members n))))))
(newline))
(define dt draw-tree)
| null | https://raw.githubusercontent.com/reflectionalist/S9fES/0ade11593cf35f112e197026886fc819042058dd/contrib/draw-tree.scm | scheme | Placed in the Public Domain
(draw-tree object) ==> unspecific
Print a tree structure resembling a Scheme datum. Each cons
(Example): (draw-tree '((a) (b . c) (d e))) ==> unspecific
Output: [o|o]---[o|o]---[o|/]
| | |
| | | |
a | d e
|
[o|o]--- c
|
b | Scheme 9 from Empty Space , Function Library
By , 2009 - 2012
cell is represented by [ ] with lines leading to their car
and cdr parts . Conses with a cdr value of ( ) are represented
by [ ] .
[ ] | [ o|o]---[o|/ ]
(define (draw-tree n)
(define *nothing* (cons 'N '()))
(define *visited* (cons 'V '()))
(define (empty? x) (eq? x *nothing*))
(define (visited? x) (eq? (car x) *visited*))
(define (mark-visited x) (cons *visited* x))
(define (members-of x) (cdr x))
(define (done? x)
(and (pair? x)
(visited? x)
(null? (cdr x))))
(define (draw-fixed-string s)
(let* ((b (make-string 8 #\space))
(k (string-length s))
(s (if (> k 7) (substring s 0 7) s))
(s (if (< k 3) (string-append " " s) s))
(k (string-length s)))
(display (string-append s (substring b 0 (- 8 k))))))
(define (draw-atom n)
(cond ((null? n)
(draw-fixed-string "()"))
((symbol? n)
(draw-fixed-string (symbol->string n)))
((number? n)
(draw-fixed-string (number->string n)))
((string? n)
(draw-fixed-string (string-append "\"" n "\"")))
((char? n)
(draw-fixed-string (string-append "#\\" (string n))))
((eq? n #t)
(draw-fixed-string "#t"))
((eq? n #f)
(draw-fixed-string "#f"))
(else
(error "draw-atom: unknown type" n))))
(define (draw-conses n)
(let draw-conses ((n n)
(r '()))
(cond ((not (pair? n))
(draw-atom n)
(reverse! r))
((null? (cdr n))
(display "[o|/]")
(reverse! (cons (car n) r)))
(else
(display "[o|o]---")
(draw-conses (cdr n) (cons (car n) r))))))
(define (draw-bars n)
(let draw-bars ((n (members-of n)))
(cond ((not (pair? n)))
((empty? (car n))
(draw-fixed-string "")
(draw-bars (cdr n)))
((and (pair? (car n))
(visited? (car n)))
(draw-bars (members-of (car n)))
(draw-bars (cdr n)))
(else
(draw-fixed-string "|")
(draw-bars (cdr n))))))
(define (skip-empty n)
(if (and (pair? n)
(or (empty? (car n))
(done? (car n))))
(skip-empty (cdr n))
n))
(define (remove-trailing-nothing n)
(reverse (skip-empty (reverse n))))
(define (all-vertical? n)
(or (not (pair? n))
(and (null? (cdr n))
(all-vertical? (car n)))))
(define (draw-members n)
(let draw-members ((n (members-of n))
(r '()))
(cond ((not (pair? n))
(mark-visited
(remove-trailing-nothing
(reverse r))))
((empty? (car n))
(draw-fixed-string "")
(draw-members (cdr n)
(cons *nothing* r)))
((not (pair? (car n)))
(draw-atom (car n))
(draw-members (cdr n)
(cons *nothing* r)))
((null? (cdr n))
(draw-members (cdr n)
(cons (draw-final (car n)) r)))
((all-vertical? (car n))
(draw-fixed-string "[o|/]")
(draw-members (cdr n)
(cons (caar n) r)))
(else
(draw-fixed-string "|")
(draw-members (cdr n)
(cons (car n) r))))))
(define (draw-final n)
(cond ((not (pair? n))
(draw-atom n)
*nothing*)
((visited? n)
(draw-members n))
(else
(mark-visited (draw-conses n)))))
(if (not (pair? n))
(draw-atom n)
(let draw-tree ((n (mark-visited (draw-conses n))))
(if (not (done? n))
(begin (newline)
(draw-bars n)
(newline)
(draw-tree (draw-members n))))))
(newline))
(define dt draw-tree)
|
4b43d1c24db238e740f20ffca4425dfabf4acabd0cc25bc3b24c4c24b47fb930 | haskell-gi/haskell-gi | GIHelper.hs | module GIHelper(dialogRun, dialogAddButton) where
import qualified GI.Cairo
import qualified GI.Gtk as GTK
import qualified Data.Text as Text
dialogRun :: GTK.IsDialog a => a -> IO GTK.ResponseType
dialogRun dialog = toEnum . fromIntegral <$> GTK.dialogRun dialog
dialogAddButton :: GTK.IsDialog a => a -> String -> GTK.ResponseType -> IO GTK.Widget
dialogAddButton dialog text response =
GTK.dialogAddButton dialog (Text.pack text) (fromIntegral $ fromEnum response)
| null | https://raw.githubusercontent.com/haskell-gi/haskell-gi/253a34ba08b968b62f9ed3d199d943551b5fe6aa/cairo/examples/hlabyrinth/src/GIHelper.hs | haskell | module GIHelper(dialogRun, dialogAddButton) where
import qualified GI.Cairo
import qualified GI.Gtk as GTK
import qualified Data.Text as Text
dialogRun :: GTK.IsDialog a => a -> IO GTK.ResponseType
dialogRun dialog = toEnum . fromIntegral <$> GTK.dialogRun dialog
dialogAddButton :: GTK.IsDialog a => a -> String -> GTK.ResponseType -> IO GTK.Widget
dialogAddButton dialog text response =
GTK.dialogAddButton dialog (Text.pack text) (fromIntegral $ fromEnum response)
|
|
2a55421dfc5f6cbff33570a4c994cb2ee07f70aea7f82d419487878f4b33ce2d | databrary/databrary | Tag.hs | # LANGUAGE TemplateHaskell , QuasiQuotes , RecordWildCards , OverloadedStrings ,
module Model.Tag
( module Model.Tag.Types
, lookupTag
, lookupTags
, findTags
, addTag
, lookupVolumeTagUseRows
, addTagUse
, removeTagUse
, lookupTopTagWeight
, lookupTagCoverage
, lookupSlotTagCoverage
, lookupSlotKeywords
, tagWeightJSON
, tagCoverageJSON
) where
import Control.Applicative (empty, pure)
import Control.Monad (guard)
import qualified Data.ByteString.Char8 as BSC
import Data.Int (Int64)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import qualified Data.String
import Database . PostgreSQL.Typed ( pgSQL )
import Database.PostgreSQL.Typed.Types
import Has (peek)
import qualified JSON
import Service.DB
import Model.SQL
import Model.Party.Types
import Model.Identity.Types
import Model.Volume.Types
import Model.Container.Types
import Model.Slot.Types
import Model.Tag.Types
import Model.Tag.SQL
lookupTag :: MonadDB c m => TagName -> m (Maybe Tag)
lookupTag n =
dbQuery1 $(selectQuery selectTag "$WHERE tag.name = ${n}::varchar")
lookupTags :: MonadDB c m => m [Tag]
lookupTags = do
let _tenv_a6Dq8 = unknownPGTypeEnv
( selectQuery selectTag " " )
(mapQuery2
(BSC.concat
[Data.String.fromString "SELECT tag.id,tag.name FROM tag "])
(\ [_cid_a6Dq9, _cname_a6Dqa]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Dq8
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6Dq9,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Dq8
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cname_a6Dqa)))
pure
(fmap
(\ (vid_a6Dpn, vname_a6Dpo) -> Tag vid_a6Dpn vname_a6Dpo)
rows)
findTags :: MonadDB c m => TagName -> Int -> m [Tag]
findTags (TagName n) lim = -- TagName restrictions obviate pattern escaping
dbQuery $(selectQuery selectTag "$WHERE tag.name LIKE ${n `BSC.snoc` '%'}::varchar LIMIT ${fromIntegral lim :: Int64}")
addTag :: MonadDB c m => TagName -> m Tag
addTag n = do
let _tenv_a6GtM = unknownPGTypeEnv
row <- dbQuery1' -- [pgSQL|!SELECT get_tag(${n})|]
(mapQuery2
((\ _p_a6GtN ->
BSC.concat
[Data.String.fromString "SELECT get_tag(",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6GtM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_p_a6GtN,
Data.String.fromString ")"])
n)
(\ [_cget_tag_a6GtO]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6GtM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cget_tag_a6GtO)))
pure ((`Tag` n) row)
lookupVolumeTagUseRows :: MonadDB c m => Volume -> m [TagUseRow]
lookupVolumeTagUseRows v = do
let _tenv_a6PCr = unknownPGTypeEnv
( selectQuery selectTagUseRow " JOIN container ON tag_use.container = container.id WHERE container.volume = $ { volumeId $ volumeRow v } ORDER BY container.id " )
(mapQuery2
((\ _p_a6PCs ->
BSC.concat
[Data.String.fromString
"SELECT tag_use.who,tag_use.container,tag_use.segment,tag_use.tableoid = 'keyword_use'::regclass,tag.id,tag.name FROM tag_use JOIN tag ON tag_use.tag = tag.id JOIN container ON tag_use.container = container.id WHERE container.volume = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PCs,
Data.String.fromString " ORDER BY container.id"])
(volumeId $ volumeRow v))
(\
[_cwho_a6PCt,
_ccontainer_a6PCu,
_csegment_a6PCv,
_ccolumn_a6PCw,
_cid_a6PCx,
_cname_a6PCy]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cwho_a6PCt,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_ccontainer_a6PCu,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_csegment_a6PCv,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "boolean")
_ccolumn_a6PCw,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6PCx,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cname_a6PCy)))
pure
(fmap
(\ (vwho_a6PC1, vcontainer_a6PC2, vsegment_a6PC3, vregclass_a6PC4,
vid_a6PC5, vname_a6PC6)
-> ($)
(($)
(Model.Tag.SQL.makeTagUseRow
vwho_a6PC1 vcontainer_a6PC2 vsegment_a6PC3)
vregclass_a6PC4)
(Tag vid_a6PC5 vname_a6PC6))
rows)
addTagUse :: MonadDB c m => TagUse -> m Bool
addTagUse t = either (const False) id <$> do
let (_tenv_a6PDJ, _tenv_a6PEH) = (unknownPGTypeEnv, unknownPGTypeEnv)
dbTryJust (guard . isExclusionViolation)
$ dbExecute1 (if tagKeyword t
then -- (insertTagUse True 't)
mapQuery2
((\ _p_a6PDK _p_a6PDL _p_a6PDM _p_a6PDN ->
(BSC.concat
[Data.String.fromString
"INSERT INTO keyword_use (tag, container, segment, who) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PDJ
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PDK,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PDJ
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PDL,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PDJ
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6PDM,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PDJ
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PDN,
Data.String.fromString ")"]))
(tagId $ useTag t)
(containerId $ containerRow $ slotContainer $ tagSlot t)
(slotSegment $ tagSlot t)
(partyId $ partyRow $ accountParty $ tagWho t))
(\[] -> ())
else -- (insertTagUse False 't))
mapQuery2
((\ _p_a6PEI _p_a6PEJ _p_a6PEK _p_a6PEL ->
(BSC.concat
[Data.String.fromString
"INSERT INTO tag_use (tag, container, segment, who) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEH
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PEI,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEH
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PEJ,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEH
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6PEK,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEH
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PEL,
Data.String.fromString ")"]))
(tagId $ useTag t)
(containerId $ containerRow $ slotContainer $ tagSlot t)
(slotSegment $ tagSlot t)
(partyId $ partyRow $ accountParty $ tagWho t))
(\[] -> ()))
removeTagUse :: MonadDB c m => TagUse -> m Int
removeTagUse t = do
let (_tenv_a6PFr, _tenv_a6PGB) = (unknownPGTypeEnv, unknownPGTypeEnv)
dbExecute
(if tagKeyword t
then -- (deleteTagUse True 't)
mapQuery2
((\ _p_a6PFs _p_a6PFt _p_a6PFu ->
(BSC.concat
[Data.String.fromString
"DELETE FROM ONLY keyword_use WHERE tag = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PFs,
Data.String.fromString " AND container = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PFt,
Data.String.fromString " AND segment <@ ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6PFu]))
(tagId $ useTag t)
(containerId $ containerRow $ slotContainer $ tagSlot t)
(slotSegment $ tagSlot t))
(\[] -> ())
else -- (deleteTagUse False 't))
mapQuery2
((\ _p_a6PGC _p_a6PGD _p_a6PGE _p_a6PGF ->
(BSC.concat
[Data.String.fromString "DELETE FROM ONLY tag_use WHERE tag = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PGB
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PGC,
Data.String.fromString " AND container = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PGB
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PGD,
Data.String.fromString " AND segment <@ ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PGB
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6PGE,
Data.String.fromString " AND who = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PGB
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PGF]))
(tagId $ useTag t)
(containerId $ containerRow $ slotContainer $ tagSlot t)
(slotSegment $ tagSlot t)
(partyId $ partyRow $ accountParty $ tagWho t))
(\[] -> ()))
lookupTopTagWeight :: MonadDB c m => Int -> m [TagWeight]
lookupTopTagWeight lim =
dbQuery $(selectQuery (selectTagWeight "") "$!ORDER BY weight DESC LIMIT ${fromIntegral lim :: Int64}")
emptyTagCoverage :: Tag -> Container -> TagCoverage
emptyTagCoverage t c = TagCoverage (TagWeight t 0) c [] [] []
lookupTagCoverage :: (MonadDB c m, MonadHasIdentity c m) => Tag -> Slot -> m TagCoverage
lookupTagCoverage t (Slot c s) = do
ident <- peek
fromMaybe (emptyTagCoverage t c) <$> dbQuery1 (($ c) . ($ t) <$> $(selectQuery (selectTagCoverage 'ident "WHERE container = ${containerId $ containerRow c} AND segment && ${s} AND tag = ${tagId t}") "$!"))
lookupSlotTagCoverage :: (MonadDB c m, MonadHasIdentity c m) => Slot -> Int -> m [TagCoverage]
lookupSlotTagCoverage slot lim = do
ident <- peek
dbQuery $(selectQuery (selectSlotTagCoverage 'ident 'slot) "$!ORDER BY weight DESC LIMIT ${fromIntegral lim :: Int64}")
lookupSlotKeywords :: (MonadDB c m) => Slot -> m [Tag]
lookupSlotKeywords Slot{..} = do
let _tenv_a6Q2M = unknownPGTypeEnv
( selectQuery selectTag " JOIN keyword_use ON i d = tag WHERE container = $ { containerId $ containerRow slotContainer } AND segment = $ { slotSegment } " )
(mapQuery2
((\ _p_a6Q2N _p_a6Q2O ->
(BSC.concat
[Data.String.fromString
"SELECT tag.id,tag.name FROM tag JOIN keyword_use ON id = tag WHERE container = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6Q2M
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6Q2N,
Data.String.fromString " AND segment = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6Q2M
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6Q2O]))
(containerId $ containerRow slotContainer) slotSegment)
(\ [_cid_a6Q2P, _cname_a6Q2Q]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Q2M
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6Q2P,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Q2M
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cname_a6Q2Q)))
pure
(fmap
(\ (vid_a6Q1R, vname_a6Q1S) -> Tag vid_a6Q1R vname_a6Q1S)
rows)
tagWeightJSON :: JSON.ToObject o => TagWeight -> JSON.Record TagName o
tagWeightJSON TagWeight{..} = JSON.Record (tagName tagWeightTag) $
"weight" JSON..= tagWeightWeight
tagCoverageJSON :: JSON.ToObject o => TagCoverage -> JSON.Record TagName o
tagCoverageJSON TagCoverage{..} = tagWeightJSON tagCoverageWeight `JSON.foldObjectIntoRec`
( "coverage" JSON..= tagCoverageSegments
<> "keyword" `JSON.kvObjectOrEmpty` (if null tagCoverageKeywords then empty else pure tagCoverageKeywords)
<> "vote" `JSON.kvObjectOrEmpty` (if null tagCoverageVotes then empty else pure tagCoverageVotes))
| null | https://raw.githubusercontent.com/databrary/databrary/685f3c625b960268f5d9b04e3d7c6146bea5afda/src/Model/Tag.hs | haskell | TagName restrictions obviate pattern escaping
[pgSQL|!SELECT get_tag(${n})|]
(insertTagUse True 't)
(insertTagUse False 't))
(deleteTagUse True 't)
(deleteTagUse False 't)) | # LANGUAGE TemplateHaskell , QuasiQuotes , RecordWildCards , OverloadedStrings ,
module Model.Tag
( module Model.Tag.Types
, lookupTag
, lookupTags
, findTags
, addTag
, lookupVolumeTagUseRows
, addTagUse
, removeTagUse
, lookupTopTagWeight
, lookupTagCoverage
, lookupSlotTagCoverage
, lookupSlotKeywords
, tagWeightJSON
, tagCoverageJSON
) where
import Control.Applicative (empty, pure)
import Control.Monad (guard)
import qualified Data.ByteString.Char8 as BSC
import Data.Int (Int64)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import qualified Data.String
import Database . PostgreSQL.Typed ( pgSQL )
import Database.PostgreSQL.Typed.Types
import Has (peek)
import qualified JSON
import Service.DB
import Model.SQL
import Model.Party.Types
import Model.Identity.Types
import Model.Volume.Types
import Model.Container.Types
import Model.Slot.Types
import Model.Tag.Types
import Model.Tag.SQL
lookupTag :: MonadDB c m => TagName -> m (Maybe Tag)
lookupTag n =
dbQuery1 $(selectQuery selectTag "$WHERE tag.name = ${n}::varchar")
lookupTags :: MonadDB c m => m [Tag]
lookupTags = do
let _tenv_a6Dq8 = unknownPGTypeEnv
( selectQuery selectTag " " )
(mapQuery2
(BSC.concat
[Data.String.fromString "SELECT tag.id,tag.name FROM tag "])
(\ [_cid_a6Dq9, _cname_a6Dqa]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Dq8
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6Dq9,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Dq8
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cname_a6Dqa)))
pure
(fmap
(\ (vid_a6Dpn, vname_a6Dpo) -> Tag vid_a6Dpn vname_a6Dpo)
rows)
findTags :: MonadDB c m => TagName -> Int -> m [Tag]
dbQuery $(selectQuery selectTag "$WHERE tag.name LIKE ${n `BSC.snoc` '%'}::varchar LIMIT ${fromIntegral lim :: Int64}")
addTag :: MonadDB c m => TagName -> m Tag
addTag n = do
let _tenv_a6GtM = unknownPGTypeEnv
(mapQuery2
((\ _p_a6GtN ->
BSC.concat
[Data.String.fromString "SELECT get_tag(",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6GtM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_p_a6GtN,
Data.String.fromString ")"])
n)
(\ [_cget_tag_a6GtO]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6GtM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cget_tag_a6GtO)))
pure ((`Tag` n) row)
lookupVolumeTagUseRows :: MonadDB c m => Volume -> m [TagUseRow]
lookupVolumeTagUseRows v = do
let _tenv_a6PCr = unknownPGTypeEnv
( selectQuery selectTagUseRow " JOIN container ON tag_use.container = container.id WHERE container.volume = $ { volumeId $ volumeRow v } ORDER BY container.id " )
(mapQuery2
((\ _p_a6PCs ->
BSC.concat
[Data.String.fromString
"SELECT tag_use.who,tag_use.container,tag_use.segment,tag_use.tableoid = 'keyword_use'::regclass,tag.id,tag.name FROM tag_use JOIN tag ON tag_use.tag = tag.id JOIN container ON tag_use.container = container.id WHERE container.volume = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PCs,
Data.String.fromString " ORDER BY container.id"])
(volumeId $ volumeRow v))
(\
[_cwho_a6PCt,
_ccontainer_a6PCu,
_csegment_a6PCv,
_ccolumn_a6PCw,
_cid_a6PCx,
_cname_a6PCy]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cwho_a6PCt,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_ccontainer_a6PCu,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_csegment_a6PCv,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "boolean")
_ccolumn_a6PCw,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6PCx,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PCr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cname_a6PCy)))
pure
(fmap
(\ (vwho_a6PC1, vcontainer_a6PC2, vsegment_a6PC3, vregclass_a6PC4,
vid_a6PC5, vname_a6PC6)
-> ($)
(($)
(Model.Tag.SQL.makeTagUseRow
vwho_a6PC1 vcontainer_a6PC2 vsegment_a6PC3)
vregclass_a6PC4)
(Tag vid_a6PC5 vname_a6PC6))
rows)
addTagUse :: MonadDB c m => TagUse -> m Bool
addTagUse t = either (const False) id <$> do
let (_tenv_a6PDJ, _tenv_a6PEH) = (unknownPGTypeEnv, unknownPGTypeEnv)
dbTryJust (guard . isExclusionViolation)
$ dbExecute1 (if tagKeyword t
mapQuery2
((\ _p_a6PDK _p_a6PDL _p_a6PDM _p_a6PDN ->
(BSC.concat
[Data.String.fromString
"INSERT INTO keyword_use (tag, container, segment, who) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PDJ
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PDK,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PDJ
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PDL,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PDJ
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6PDM,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PDJ
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PDN,
Data.String.fromString ")"]))
(tagId $ useTag t)
(containerId $ containerRow $ slotContainer $ tagSlot t)
(slotSegment $ tagSlot t)
(partyId $ partyRow $ accountParty $ tagWho t))
(\[] -> ())
mapQuery2
((\ _p_a6PEI _p_a6PEJ _p_a6PEK _p_a6PEL ->
(BSC.concat
[Data.String.fromString
"INSERT INTO tag_use (tag, container, segment, who) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEH
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PEI,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEH
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PEJ,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEH
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6PEK,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEH
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PEL,
Data.String.fromString ")"]))
(tagId $ useTag t)
(containerId $ containerRow $ slotContainer $ tagSlot t)
(slotSegment $ tagSlot t)
(partyId $ partyRow $ accountParty $ tagWho t))
(\[] -> ()))
removeTagUse :: MonadDB c m => TagUse -> m Int
removeTagUse t = do
let (_tenv_a6PFr, _tenv_a6PGB) = (unknownPGTypeEnv, unknownPGTypeEnv)
dbExecute
(if tagKeyword t
mapQuery2
((\ _p_a6PFs _p_a6PFt _p_a6PFu ->
(BSC.concat
[Data.String.fromString
"DELETE FROM ONLY keyword_use WHERE tag = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PFs,
Data.String.fromString " AND container = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PFt,
Data.String.fromString " AND segment <@ ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFr
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6PFu]))
(tagId $ useTag t)
(containerId $ containerRow $ slotContainer $ tagSlot t)
(slotSegment $ tagSlot t))
(\[] -> ())
mapQuery2
((\ _p_a6PGC _p_a6PGD _p_a6PGE _p_a6PGF ->
(BSC.concat
[Data.String.fromString "DELETE FROM ONLY tag_use WHERE tag = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PGB
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PGC,
Data.String.fromString " AND container = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PGB
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PGD,
Data.String.fromString " AND segment <@ ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PGB
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6PGE,
Data.String.fromString " AND who = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PGB
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PGF]))
(tagId $ useTag t)
(containerId $ containerRow $ slotContainer $ tagSlot t)
(slotSegment $ tagSlot t)
(partyId $ partyRow $ accountParty $ tagWho t))
(\[] -> ()))
lookupTopTagWeight :: MonadDB c m => Int -> m [TagWeight]
lookupTopTagWeight lim =
dbQuery $(selectQuery (selectTagWeight "") "$!ORDER BY weight DESC LIMIT ${fromIntegral lim :: Int64}")
emptyTagCoverage :: Tag -> Container -> TagCoverage
emptyTagCoverage t c = TagCoverage (TagWeight t 0) c [] [] []
lookupTagCoverage :: (MonadDB c m, MonadHasIdentity c m) => Tag -> Slot -> m TagCoverage
lookupTagCoverage t (Slot c s) = do
ident <- peek
fromMaybe (emptyTagCoverage t c) <$> dbQuery1 (($ c) . ($ t) <$> $(selectQuery (selectTagCoverage 'ident "WHERE container = ${containerId $ containerRow c} AND segment && ${s} AND tag = ${tagId t}") "$!"))
lookupSlotTagCoverage :: (MonadDB c m, MonadHasIdentity c m) => Slot -> Int -> m [TagCoverage]
lookupSlotTagCoverage slot lim = do
ident <- peek
dbQuery $(selectQuery (selectSlotTagCoverage 'ident 'slot) "$!ORDER BY weight DESC LIMIT ${fromIntegral lim :: Int64}")
lookupSlotKeywords :: (MonadDB c m) => Slot -> m [Tag]
lookupSlotKeywords Slot{..} = do
let _tenv_a6Q2M = unknownPGTypeEnv
( selectQuery selectTag " JOIN keyword_use ON i d = tag WHERE container = $ { containerId $ containerRow slotContainer } AND segment = $ { slotSegment } " )
(mapQuery2
((\ _p_a6Q2N _p_a6Q2O ->
(BSC.concat
[Data.String.fromString
"SELECT tag.id,tag.name FROM tag JOIN keyword_use ON id = tag WHERE container = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6Q2M
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6Q2N,
Data.String.fromString " AND segment = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6Q2M
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "segment")
_p_a6Q2O]))
(containerId $ containerRow slotContainer) slotSegment)
(\ [_cid_a6Q2P, _cname_a6Q2Q]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Q2M
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6Q2P,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Q2M
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cname_a6Q2Q)))
pure
(fmap
(\ (vid_a6Q1R, vname_a6Q1S) -> Tag vid_a6Q1R vname_a6Q1S)
rows)
tagWeightJSON :: JSON.ToObject o => TagWeight -> JSON.Record TagName o
tagWeightJSON TagWeight{..} = JSON.Record (tagName tagWeightTag) $
"weight" JSON..= tagWeightWeight
tagCoverageJSON :: JSON.ToObject o => TagCoverage -> JSON.Record TagName o
tagCoverageJSON TagCoverage{..} = tagWeightJSON tagCoverageWeight `JSON.foldObjectIntoRec`
( "coverage" JSON..= tagCoverageSegments
<> "keyword" `JSON.kvObjectOrEmpty` (if null tagCoverageKeywords then empty else pure tagCoverageKeywords)
<> "vote" `JSON.kvObjectOrEmpty` (if null tagCoverageVotes then empty else pure tagCoverageVotes))
|
fc40e7680d966b2de24e1d0c68ac5484e55b55b2ce065fd1332ff1befbfa92d3 | elaforge/karya | Html_test.hs | Copyright 2018
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
# LANGUAGE RecordWildCards #
module Solkattu.Format.Html_test where
import qualified Data.Text.IO as Text.IO
import qualified Util.Html
import qualified Solkattu.Dsl.Solkattu as G
import qualified Solkattu.Format.Format as Format
import qualified Solkattu.Format.Html as Html
import qualified Solkattu.Instrument.Mridangam as Mridangam
import qualified Solkattu.Korvai as Korvai
import qualified Solkattu.Realize as Realize
import qualified Solkattu.Tala as Tala
import Global
import Util.Test
manual_test = do
let p = Text.IO.putStrLn
p $ render Format.defaultAbstraction $ korvai $ G.sarvaM _ 4
p $ render mempty $ korvai $ mconcat $
G.p6 : replicate 5 G.__
p $ render Format.defaultAbstraction $ korvai $ mconcat $
G.p6 : replicate 5 G.__
test_spellRests :: Test
test_spellRests = do
let f = mconcat . map toSpace . map Util.Html.un_html
. Html.spellRests . zip [0..]
equal (f ["_", "_", "_", "_", "_", "_", "_"]) "‗ _ "
equal (f ["x", "_", "_", "_", "_", "_", "_"]) "x _ _ "
toSpace :: Text -> Text
toSpace "" = " "
toSpace s = s
korvai :: Korvai.Sequence -> Korvai.Korvai
korvai = Korvai.korvai Tala.adi_tala (G.makeMridangam [])
. Korvai.inferSections . (:[])
render :: Format.Abstraction -> Korvai.Korvai -> Text
render abstraction =
Util.Html.un_html . mconcat . Html.sectionHtmls Korvai.IMridangam config
where
config = Html.Config
{ _abstraction = abstraction
, _font = Html.instrumentFont
, _rulerEach = 4
}
defaultStrokeMap :: Korvai.StrokeMaps
defaultStrokeMap = mempty
{ Korvai.smapMridangam = Realize.strokeMap Mridangam.defaultPatterns [] }
where Mridangam.Strokes {..} = Mridangam.notes
| null | https://raw.githubusercontent.com/elaforge/karya/8ea15e6a5fb57e2f15f8c19836751e315f9c09f2/Solkattu/Format/Html_test.hs | haskell | This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt | Copyright 2018
# LANGUAGE RecordWildCards #
module Solkattu.Format.Html_test where
import qualified Data.Text.IO as Text.IO
import qualified Util.Html
import qualified Solkattu.Dsl.Solkattu as G
import qualified Solkattu.Format.Format as Format
import qualified Solkattu.Format.Html as Html
import qualified Solkattu.Instrument.Mridangam as Mridangam
import qualified Solkattu.Korvai as Korvai
import qualified Solkattu.Realize as Realize
import qualified Solkattu.Tala as Tala
import Global
import Util.Test
manual_test = do
let p = Text.IO.putStrLn
p $ render Format.defaultAbstraction $ korvai $ G.sarvaM _ 4
p $ render mempty $ korvai $ mconcat $
G.p6 : replicate 5 G.__
p $ render Format.defaultAbstraction $ korvai $ mconcat $
G.p6 : replicate 5 G.__
test_spellRests :: Test
test_spellRests = do
let f = mconcat . map toSpace . map Util.Html.un_html
. Html.spellRests . zip [0..]
equal (f ["_", "_", "_", "_", "_", "_", "_"]) "‗ _ "
equal (f ["x", "_", "_", "_", "_", "_", "_"]) "x _ _ "
toSpace :: Text -> Text
toSpace "" = " "
toSpace s = s
korvai :: Korvai.Sequence -> Korvai.Korvai
korvai = Korvai.korvai Tala.adi_tala (G.makeMridangam [])
. Korvai.inferSections . (:[])
render :: Format.Abstraction -> Korvai.Korvai -> Text
render abstraction =
Util.Html.un_html . mconcat . Html.sectionHtmls Korvai.IMridangam config
where
config = Html.Config
{ _abstraction = abstraction
, _font = Html.instrumentFont
, _rulerEach = 4
}
defaultStrokeMap :: Korvai.StrokeMaps
defaultStrokeMap = mempty
{ Korvai.smapMridangam = Realize.strokeMap Mridangam.defaultPatterns [] }
where Mridangam.Strokes {..} = Mridangam.notes
|
42fcd86162ef3f6a7a8131e707025697e97b49d76ae90931520834279320cb05 | circuithub/rel8 | Identity.hs | # language DataKinds #
{-# language FlexibleContexts #-}
# language StandaloneKindSignatures #
{-# language TypeFamilies #-}
{-# language UndecidableInstances #-}
module Rel8.Schema.HTable.Identity
( HIdentity( HIdentity, unHIdentity )
)
where
-- base
import Data.Kind ( Type )
import Data.Type.Equality ( (:~:)( Refl ) )
import Prelude
-- rel8
import Rel8.Schema.Dict ( Dict( Dict ) )
import Rel8.Schema.HTable
( HTable, HConstrainTable, HField
, hfield, htabulate, htraverse, hdicts, hspecs
)
import qualified Rel8.Schema.Kind as K
import Rel8.Schema.Null ( Sql )
import Rel8.Schema.Spec ( specification )
import Rel8.Type ( DBType )
type HIdentity :: Type -> K.HTable
newtype HIdentity a context = HIdentity
{ unHIdentity :: context a
}
instance Sql DBType a => HTable (HIdentity a) where
type HConstrainTable (HIdentity a) constraint = constraint a
type HField (HIdentity a) = (:~:) a
hfield (HIdentity a) Refl = a
htabulate f = HIdentity $ f Refl
htraverse f (HIdentity a) = HIdentity <$> f a
hdicts = HIdentity Dict
hspecs = HIdentity specification
| null | https://raw.githubusercontent.com/circuithub/rel8/f47423ec17c36f441bab4c0cbb2036dc8aecacbd/src/Rel8/Schema/HTable/Identity.hs | haskell | # language FlexibleContexts #
# language TypeFamilies #
# language UndecidableInstances #
base
rel8 | # language DataKinds #
# language StandaloneKindSignatures #
module Rel8.Schema.HTable.Identity
( HIdentity( HIdentity, unHIdentity )
)
where
import Data.Kind ( Type )
import Data.Type.Equality ( (:~:)( Refl ) )
import Prelude
import Rel8.Schema.Dict ( Dict( Dict ) )
import Rel8.Schema.HTable
( HTable, HConstrainTable, HField
, hfield, htabulate, htraverse, hdicts, hspecs
)
import qualified Rel8.Schema.Kind as K
import Rel8.Schema.Null ( Sql )
import Rel8.Schema.Spec ( specification )
import Rel8.Type ( DBType )
type HIdentity :: Type -> K.HTable
newtype HIdentity a context = HIdentity
{ unHIdentity :: context a
}
instance Sql DBType a => HTable (HIdentity a) where
type HConstrainTable (HIdentity a) constraint = constraint a
type HField (HIdentity a) = (:~:) a
hfield (HIdentity a) Refl = a
htabulate f = HIdentity $ f Refl
htraverse f (HIdentity a) = HIdentity <$> f a
hdicts = HIdentity Dict
hspecs = HIdentity specification
|
59b844c088efc9e4bed99a671f8803e92c8c2cb58c69dea623016354c1d17c92 | moby/vpnkit | utils.mli |
val somaxconn: int ref (* can be overriden by the command-line *)
val rtlGenRandom: int -> bytes option
* [ rtlGenRandom len ] returns [ len ] bytes of secure random data on Windows .
Returns None if called on non - Windows platforms
Returns None if called on non-Windows platforms *)
val setSocketTTL: Unix.file_descr -> int -> unit
* [ setSocketTTL s ] sets the TTL on the socket [ s ] to [ ]
| null | https://raw.githubusercontent.com/moby/vpnkit/7bfcba6e59c1e5450b667a392bf56371faae58b2/src/hostnet/utils.mli | ocaml | can be overriden by the command-line |
val rtlGenRandom: int -> bytes option
* [ rtlGenRandom len ] returns [ len ] bytes of secure random data on Windows .
Returns None if called on non - Windows platforms
Returns None if called on non-Windows platforms *)
val setSocketTTL: Unix.file_descr -> int -> unit
* [ setSocketTTL s ] sets the TTL on the socket [ s ] to [ ]
|
0f5cf391825c33569df2d0193668c13ad61041a72cd683361bd4f0adbfe04b16 | takikawa/tr-pfds | redblacktrees-tests.rkt | #lang typed/scheme
(require pfds/red-black-tree)
(require typed/test-engine/scheme-tests)
;; NOTE:
Rebalancing used in Okasaki version of Red Black Trees is slightly
;; different from that of popular version.
;; As a consequence of this difference,
;; - Okasaki version is easy to implement.
;; - There is a difference in ordering of elements. For example, in the
test below , popular version would give ( list 2 3 4 1 5 ) . Because
;; redblacktree->list takes the root element in the red-black tree and
;; populates it in a list and then deletes the root element. When it
;; deletes the root node, balancing is done, since the balancing differs
in version , 4 becomes the root of the tree instead of 3 which
;; is the case in the popular version.
(check-expect (redblacktree->list (redblacktree < 1 2 3 4 5))
(list 2 4 3 1 5))
(check-expect (root (redblacktree < 1 2 3 4 5 6 7)) 4)
(check-expect (root (redblacktree < 1 2 3 4 5)) 2)
(define lst (build-list 100 (λ: ([x : Integer]) x)))
(check-expect ((inst sort Integer Integer) (redblacktree->list (apply redblacktree < lst)) <) lst)
(check-expect (root (delete 2 (redblacktree < 1 2 3 4 5))) 4)
(check-expect (root (delete-root (redblacktree < 1 2 3 4 5))) 4)
(check-expect (member? 5 (redblacktree < 1 2 3 4 5)) #t)
(check-expect (member? 5 (redblacktree > 1 2 3 4 5)) #t)
(check-expect (member? 50 (redblacktree > 1 2 3 4 5)) #f)
(check-expect (member? 50 (redblacktree < 1 2 3 4 5)) #f)
(check-expect (member? 1 (redblacktree > 1 2 3 4 5)) #t)
(check-expect (member? 2 (redblacktree > 1 2 3 4 5)) #t)
(check-expect (member? 95 (apply redblacktree < lst)) #t)
(check-expect (empty? (delete-root (redblacktree < 1))) #t)
(check-expect (empty? (redblacktree < 1)) #f)
(check-error (root (delete-root (redblacktree < 1)))
"root: given tree is empty")
(check-error (delete 1 (delete-root (redblacktree < 1)))
"delete: given key not found in the tree")
(check-error (delete-root (delete-root (redblacktree < 1)))
"delete-root: given tree is empty")
(test)
| null | https://raw.githubusercontent.com/takikawa/tr-pfds/a08810bdfc760bb9ed68d08ea222a59135d9a203/pfds/tests/redblacktrees-tests.rkt | racket | NOTE:
different from that of popular version.
As a consequence of this difference,
- Okasaki version is easy to implement.
- There is a difference in ordering of elements. For example, in the
redblacktree->list takes the root element in the red-black tree and
populates it in a list and then deletes the root element. When it
deletes the root node, balancing is done, since the balancing differs
is the case in the popular version. | #lang typed/scheme
(require pfds/red-black-tree)
(require typed/test-engine/scheme-tests)
Rebalancing used in Okasaki version of Red Black Trees is slightly
test below , popular version would give ( list 2 3 4 1 5 ) . Because
in version , 4 becomes the root of the tree instead of 3 which
(check-expect (redblacktree->list (redblacktree < 1 2 3 4 5))
(list 2 4 3 1 5))
(check-expect (root (redblacktree < 1 2 3 4 5 6 7)) 4)
(check-expect (root (redblacktree < 1 2 3 4 5)) 2)
(define lst (build-list 100 (λ: ([x : Integer]) x)))
(check-expect ((inst sort Integer Integer) (redblacktree->list (apply redblacktree < lst)) <) lst)
(check-expect (root (delete 2 (redblacktree < 1 2 3 4 5))) 4)
(check-expect (root (delete-root (redblacktree < 1 2 3 4 5))) 4)
(check-expect (member? 5 (redblacktree < 1 2 3 4 5)) #t)
(check-expect (member? 5 (redblacktree > 1 2 3 4 5)) #t)
(check-expect (member? 50 (redblacktree > 1 2 3 4 5)) #f)
(check-expect (member? 50 (redblacktree < 1 2 3 4 5)) #f)
(check-expect (member? 1 (redblacktree > 1 2 3 4 5)) #t)
(check-expect (member? 2 (redblacktree > 1 2 3 4 5)) #t)
(check-expect (member? 95 (apply redblacktree < lst)) #t)
(check-expect (empty? (delete-root (redblacktree < 1))) #t)
(check-expect (empty? (redblacktree < 1)) #f)
(check-error (root (delete-root (redblacktree < 1)))
"root: given tree is empty")
(check-error (delete 1 (delete-root (redblacktree < 1)))
"delete: given key not found in the tree")
(check-error (delete-root (delete-root (redblacktree < 1)))
"delete-root: given tree is empty")
(test)
|
2607e7e5274fe1378bbaa18237fb030234adcd889f8cdbfff4407a1801240dd3 | input-output-hk/project-icarus-importer | Wallets.hs | # LANGUAGE ApplicativeDo #
-- | Functions for working with Wallets configuration file.
module Bench.Cardano.Wallet.Config.Wallets
( getWalletsConfig
) where
import Universum
import qualified Data.Yaml as Yaml
import Data.Yaml ((.:))
import Data.Aeson.Types (typeMismatch)
import Bench.Cardano.Wallet.Types (WalletAccount (..), Wallet (..),
WalletsConfig (..))
import Pos.Wallet.Web.ClientTypes (CAccountId (..), CId (..), CHash (..))
instance Yaml.FromJSON CAccountId where
parseJSON (Yaml.String t) = return $ CAccountId t
parseJSON invalid = typeMismatch "CAccountId" invalid
instance Yaml.FromJSON (CId a) where
parseJSON (Yaml.String h) = return $ CId (CHash h)
parseJSON invalid = typeMismatch "CId a" invalid
instance Yaml.FromJSON WalletAccount where
parseJSON (Yaml.Object o) = WalletAccount
<$> o .: "AccountId"
<*> o .: "Addresses"
parseJSON invalid = typeMismatch "WalletAccount" invalid
instance Yaml.FromJSON Wallet where
parseJSON (Yaml.Object o) = Wallet
<$> o .: "WalletId"
<*> o .: "Accounts"
parseJSON invalid = typeMismatch "Wallet" invalid
instance Yaml.FromJSON WalletsConfig where
parseJSON (Yaml.Object o) = WalletsConfig
<$> o .: "Wallets"
parseJSON invalid = typeMismatch "WalletsConfig" invalid
-- | Reads Wallets configuration from the local .yaml-file.
getWalletsConfig :: FilePath -> IO WalletsConfig
getWalletsConfig pathToConfig =
(Yaml.decodeFile pathToConfig :: IO (Maybe WalletsConfig)) >>= \case
Nothing -> reportAboutInvalidConfig
Just conf -> return conf
where
reportAboutInvalidConfig :: IO a
reportAboutInvalidConfig = error . toText $
"Unable to read endpoints configuration " <> pathToConfig
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/bench/Bench/Cardano/Wallet/Config/Wallets.hs | haskell | | Functions for working with Wallets configuration file.
| Reads Wallets configuration from the local .yaml-file. | # LANGUAGE ApplicativeDo #
module Bench.Cardano.Wallet.Config.Wallets
( getWalletsConfig
) where
import Universum
import qualified Data.Yaml as Yaml
import Data.Yaml ((.:))
import Data.Aeson.Types (typeMismatch)
import Bench.Cardano.Wallet.Types (WalletAccount (..), Wallet (..),
WalletsConfig (..))
import Pos.Wallet.Web.ClientTypes (CAccountId (..), CId (..), CHash (..))
instance Yaml.FromJSON CAccountId where
parseJSON (Yaml.String t) = return $ CAccountId t
parseJSON invalid = typeMismatch "CAccountId" invalid
instance Yaml.FromJSON (CId a) where
parseJSON (Yaml.String h) = return $ CId (CHash h)
parseJSON invalid = typeMismatch "CId a" invalid
instance Yaml.FromJSON WalletAccount where
parseJSON (Yaml.Object o) = WalletAccount
<$> o .: "AccountId"
<*> o .: "Addresses"
parseJSON invalid = typeMismatch "WalletAccount" invalid
instance Yaml.FromJSON Wallet where
parseJSON (Yaml.Object o) = Wallet
<$> o .: "WalletId"
<*> o .: "Accounts"
parseJSON invalid = typeMismatch "Wallet" invalid
instance Yaml.FromJSON WalletsConfig where
parseJSON (Yaml.Object o) = WalletsConfig
<$> o .: "Wallets"
parseJSON invalid = typeMismatch "WalletsConfig" invalid
getWalletsConfig :: FilePath -> IO WalletsConfig
getWalletsConfig pathToConfig =
(Yaml.decodeFile pathToConfig :: IO (Maybe WalletsConfig)) >>= \case
Nothing -> reportAboutInvalidConfig
Just conf -> return conf
where
reportAboutInvalidConfig :: IO a
reportAboutInvalidConfig = error . toText $
"Unable to read endpoints configuration " <> pathToConfig
|
ac545b8704f8ad2a48490aadff9412ca1105929af2cf779ca1876119e1e27a7b | ring-clojure/ring-headers | x_headers.clj | (ns ring.middleware.x-headers
"Middleware for adding various 'X-' response headers."
(:require [clojure.string :as str]
[ring.util.response :as resp]))
(defn- allow-from? [frame-options]
(and (map? frame-options)
(= (keys frame-options) [:allow-from])
(string? (:allow-from frame-options))))
(defn- format-frame-options [frame-options]
(if (map? frame-options)
(str "ALLOW-FROM " (:allow-from frame-options))
(str/upper-case (name frame-options))))
(defn- format-xss-protection [enable? options]
(str (if enable? "1" "0") (if options "; mode=block")))
(defn- wrap-x-header [handler header-name header-value]
(fn
([request]
(some-> (handler request) (resp/header header-name header-value)))
([request respond raise]
(handler request #(respond (some-> % (resp/header header-name header-value))) raise))))
(defn frame-options-response
"Add the X-Frame-Options header to the response. See: wrap-frame-options."
[response frame-options]
(some-> response (resp/header "X-Frame-Options" (format-frame-options frame-options))))
(defn wrap-frame-options
"Middleware that adds the X-Frame-Options header to the response. This governs
whether your site can be rendered in a <frame>, <iframe> or <object>, and is
typically used to prevent clickjacking attacks.
The following frame options are allowed:
:deny - prevent any framing of the content
:sameorigin - allow only the current site to frame the content
{:allow-from uri} - allow only the specified URI to frame the page
The :deny and :sameorigin options are keywords, while the :allow-from option
is a map consisting of one key/value pair.
Note that browser support for :allow-from is incomplete. See:
-US/docs/Web/HTTP/X-Frame-Options"
[handler frame-options]
{:pre [(or (= frame-options :deny)
(= frame-options :sameorigin)
(allow-from? frame-options))]}
(wrap-x-header handler "X-Frame-Options" (format-frame-options frame-options)))
(defn content-type-options-response
"Add the X-Content-Type-Options header to the response.
See: wrap-content-type-options."
[response content-type-options]
(some-> response (resp/header "X-Content-Type-Options" (name content-type-options))))
(defn wrap-content-type-options
"Middleware that adds the X-Content-Type-Options header to the response. This
currently only accepts one option:
:nosniff - prevent resources with invalid media types being loaded as
stylesheets or scripts
This prevents attacks based around media type confusion. See:
-us/library/ie/gg622941(v=vs.85).aspx"
[handler content-type-options]
{:pre [(= content-type-options :nosniff)]}
(wrap-x-header handler "X-Content-Type-Options" (name content-type-options)))
(defn xss-protection-response
"Add the X-XSS-Protection header to the response. See: wrap-xss-protection."
([response enable?]
(xss-protection-response response enable? nil))
([response enable? options]
(some-> response
(resp/header "X-XSS-Protection" (format-xss-protection enable? options)))))
(defn wrap-xss-protection
"Middleware that adds the X-XSS-Protection header to the response. This header
enables a heuristic filter in browsers for detecting cross-site scripting
attacks. Usually on by default.
The enable? attribute determines whether the filter should be turned on.
Accepts one additional option:
:mode - currently accepts only :block
See: -us/library/dd565647(v=vs.85).aspx"
([handler enable?]
(wrap-xss-protection handler enable? nil))
([handler enable? options]
{:pre [(or (nil? options) (= options {:mode :block}))]}
(wrap-x-header handler "X-XSS-Protection" (format-xss-protection enable? options))))
| null | https://raw.githubusercontent.com/ring-clojure/ring-headers/3c803eb0864d7fbe93ba1595d5d0d6ae09d51eb0/src/ring/middleware/x_headers.clj | clojure | (ns ring.middleware.x-headers
"Middleware for adding various 'X-' response headers."
(:require [clojure.string :as str]
[ring.util.response :as resp]))
(defn- allow-from? [frame-options]
(and (map? frame-options)
(= (keys frame-options) [:allow-from])
(string? (:allow-from frame-options))))
(defn- format-frame-options [frame-options]
(if (map? frame-options)
(str "ALLOW-FROM " (:allow-from frame-options))
(str/upper-case (name frame-options))))
(defn- format-xss-protection [enable? options]
(str (if enable? "1" "0") (if options "; mode=block")))
(defn- wrap-x-header [handler header-name header-value]
(fn
([request]
(some-> (handler request) (resp/header header-name header-value)))
([request respond raise]
(handler request #(respond (some-> % (resp/header header-name header-value))) raise))))
(defn frame-options-response
"Add the X-Frame-Options header to the response. See: wrap-frame-options."
[response frame-options]
(some-> response (resp/header "X-Frame-Options" (format-frame-options frame-options))))
(defn wrap-frame-options
"Middleware that adds the X-Frame-Options header to the response. This governs
whether your site can be rendered in a <frame>, <iframe> or <object>, and is
typically used to prevent clickjacking attacks.
The following frame options are allowed:
:deny - prevent any framing of the content
:sameorigin - allow only the current site to frame the content
{:allow-from uri} - allow only the specified URI to frame the page
The :deny and :sameorigin options are keywords, while the :allow-from option
is a map consisting of one key/value pair.
Note that browser support for :allow-from is incomplete. See:
-US/docs/Web/HTTP/X-Frame-Options"
[handler frame-options]
{:pre [(or (= frame-options :deny)
(= frame-options :sameorigin)
(allow-from? frame-options))]}
(wrap-x-header handler "X-Frame-Options" (format-frame-options frame-options)))
(defn content-type-options-response
"Add the X-Content-Type-Options header to the response.
See: wrap-content-type-options."
[response content-type-options]
(some-> response (resp/header "X-Content-Type-Options" (name content-type-options))))
(defn wrap-content-type-options
"Middleware that adds the X-Content-Type-Options header to the response. This
currently only accepts one option:
:nosniff - prevent resources with invalid media types being loaded as
stylesheets or scripts
This prevents attacks based around media type confusion. See:
-us/library/ie/gg622941(v=vs.85).aspx"
[handler content-type-options]
{:pre [(= content-type-options :nosniff)]}
(wrap-x-header handler "X-Content-Type-Options" (name content-type-options)))
(defn xss-protection-response
"Add the X-XSS-Protection header to the response. See: wrap-xss-protection."
([response enable?]
(xss-protection-response response enable? nil))
([response enable? options]
(some-> response
(resp/header "X-XSS-Protection" (format-xss-protection enable? options)))))
(defn wrap-xss-protection
"Middleware that adds the X-XSS-Protection header to the response. This header
enables a heuristic filter in browsers for detecting cross-site scripting
attacks. Usually on by default.
The enable? attribute determines whether the filter should be turned on.
Accepts one additional option:
:mode - currently accepts only :block
See: -us/library/dd565647(v=vs.85).aspx"
([handler enable?]
(wrap-xss-protection handler enable? nil))
([handler enable? options]
{:pre [(or (nil? options) (= options {:mode :block}))]}
(wrap-x-header handler "X-XSS-Protection" (format-xss-protection enable? options))))
|
|
f8871d57d57922a341d13ef7b65174259bd300d6c4a1ea6005d0f83ffa237684 | dparis/lein-essthree | repository.clj | (ns lein-essthree.repository
"Middleware to update project repositories to include any
configured S3 buckets."
(:require [cuerdas.core :as c]
[lein-essthree.schemas
:refer [RepoConfig]]
[schema.core :as s]))
(s/defn ^:private get-config :- (s/maybe RepoConfig)
[project]
(get-in project [:essthree :repository]))
(s/defn ^:private build-repo-url :- s/Str
[config :- RepoConfig
build-category :- (s/enum "releases" "snapshots")]
(let [bucket (:bucket config)
path (:path config)
url (->> [bucket path build-category]
(filter identity)
(map #(c/trim % "/"))
(c/join "/"))]
(str "s3://" url)))
(s/defschema ^:private Repo
(s/pair
(s/enum "essthree-releases" "essthree-snapshots")
"repo-name"
{:url s/Str
(s/optional-key :username) s/Str
(s/optional-key :password) s/Str}
"repo-data"))
(s/defn ^:private build-repo :- Repo
[config :- RepoConfig
build-category :- (s/enum "releases" "snapshots")]
(let [url (build-repo-url config build-category)
lein-keys [:sign-releases :checksum :update]
snapshots (= "snapshots" build-category)
repo-data (merge {:url url
:snapshots snapshots}
(select-keys config lein-keys))
aws-creds (:aws-creds config)
username (or (:access-key-id aws-creds)
:env/aws_access_key_id)
password (or (:secret-access-key aws-creds)
:env/aws_secret_access_key)]
[(str "essthree-" build-category)
(merge repo-data
{:username username
:password password})]))
(defn update-repositories
[project]
(if-let [config (get-config project)]
(-> project
(update-in [:repositories] conj
(build-repo config "snapshots"))
(update-in [:repositories] conj
(build-repo config "releases")))
project))
| null | https://raw.githubusercontent.com/dparis/lein-essthree/a351693b850ba4bd478c9e922969d057b61b7b45/src/lein_essthree/repository.clj | clojure | (ns lein-essthree.repository
"Middleware to update project repositories to include any
configured S3 buckets."
(:require [cuerdas.core :as c]
[lein-essthree.schemas
:refer [RepoConfig]]
[schema.core :as s]))
(s/defn ^:private get-config :- (s/maybe RepoConfig)
[project]
(get-in project [:essthree :repository]))
(s/defn ^:private build-repo-url :- s/Str
[config :- RepoConfig
build-category :- (s/enum "releases" "snapshots")]
(let [bucket (:bucket config)
path (:path config)
url (->> [bucket path build-category]
(filter identity)
(map #(c/trim % "/"))
(c/join "/"))]
(str "s3://" url)))
(s/defschema ^:private Repo
(s/pair
(s/enum "essthree-releases" "essthree-snapshots")
"repo-name"
{:url s/Str
(s/optional-key :username) s/Str
(s/optional-key :password) s/Str}
"repo-data"))
(s/defn ^:private build-repo :- Repo
[config :- RepoConfig
build-category :- (s/enum "releases" "snapshots")]
(let [url (build-repo-url config build-category)
lein-keys [:sign-releases :checksum :update]
snapshots (= "snapshots" build-category)
repo-data (merge {:url url
:snapshots snapshots}
(select-keys config lein-keys))
aws-creds (:aws-creds config)
username (or (:access-key-id aws-creds)
:env/aws_access_key_id)
password (or (:secret-access-key aws-creds)
:env/aws_secret_access_key)]
[(str "essthree-" build-category)
(merge repo-data
{:username username
:password password})]))
(defn update-repositories
[project]
(if-let [config (get-config project)]
(-> project
(update-in [:repositories] conj
(build-repo config "snapshots"))
(update-in [:repositories] conj
(build-repo config "releases")))
project))
|
|
3b5a6cb87cce3c4b023c31e238ad0ca81ed73eee828974d7bb49b8e9a15a711b | Gopiandcode/guile-ocaml | turtle_program.ml | type direction = Up | Down | Left | Right
let turn_right = function Up -> Left | Left -> Down | Down -> Right | Right -> Up
let turn_left = function Left -> Up | Down -> Left | Right -> Down | Up -> Right
let move n (x,y) = function
| Up -> (x, y + n)
| Down -> (x, y - n)
| Left -> (x - n, y)
| Right -> (x + n, y)
let pen_down = ref false
let direction = ref Up
let set_pen_down v =
if not @@ Guile.Bool.is_bool v then
failwith "expected boolean argument";
let v = Guile.Bool.from_raw v in
pen_down := v;
Guile.eol
let turn_left _ =
direction := turn_left !direction;
Guile.eol
let turn_right _ =
direction := turn_right !direction;
Guile.eol
let move_by n =
if not @@ Guile.Number.is_integer n then
failwith "expected numeric arg";
let n = Guile.Number.int_from_raw n in
let x, y =
let cur_pos = Graphics.current_point () in
move n cur_pos !direction in
if !pen_down then
Graphics.lineto x y;
Graphics.moveto x y;
Guile.eol
let move_to x y =
if (not @@ Guile.Number.is_integer x) ||
(not @@ Guile.Number.is_integer y) then
failwith "expected numeric position";
let x, y =
Guile.Number.int_from_raw x,
Guile.Number.int_from_raw y in
if !pen_down then
Graphics.lineto x y;
Graphics.moveto x y;
Guile.eol
let () =
Graphics.open_graph " 400x400+50-0";
Graphics.auto_synchronize true;
Graphics.moveto 200 200;
Guile.init ();
ignore @@ Guile.Functions.register_fun1 "pen-down" set_pen_down;
ignore @@ Guile.Functions.register_fun1 ~no_opt:1 "turn-left" turn_left;
ignore @@ Guile.Functions.register_fun1 ~no_opt:1 "turn-right" turn_right;
ignore @@ Guile.Functions.register_fun1 "move-by" move_by;
ignore @@ Guile.Functions.register_fun2 "move-to" move_to;
Guile.shell ()
| null | https://raw.githubusercontent.com/Gopiandcode/guile-ocaml/247adf5a6adbbfd85696498b390167a9faa77779/examples/turtle-program/turtle_program.ml | ocaml | type direction = Up | Down | Left | Right
let turn_right = function Up -> Left | Left -> Down | Down -> Right | Right -> Up
let turn_left = function Left -> Up | Down -> Left | Right -> Down | Up -> Right
let move n (x,y) = function
| Up -> (x, y + n)
| Down -> (x, y - n)
| Left -> (x - n, y)
| Right -> (x + n, y)
let pen_down = ref false
let direction = ref Up
let set_pen_down v =
if not @@ Guile.Bool.is_bool v then
failwith "expected boolean argument";
let v = Guile.Bool.from_raw v in
pen_down := v;
Guile.eol
let turn_left _ =
direction := turn_left !direction;
Guile.eol
let turn_right _ =
direction := turn_right !direction;
Guile.eol
let move_by n =
if not @@ Guile.Number.is_integer n then
failwith "expected numeric arg";
let n = Guile.Number.int_from_raw n in
let x, y =
let cur_pos = Graphics.current_point () in
move n cur_pos !direction in
if !pen_down then
Graphics.lineto x y;
Graphics.moveto x y;
Guile.eol
let move_to x y =
if (not @@ Guile.Number.is_integer x) ||
(not @@ Guile.Number.is_integer y) then
failwith "expected numeric position";
let x, y =
Guile.Number.int_from_raw x,
Guile.Number.int_from_raw y in
if !pen_down then
Graphics.lineto x y;
Graphics.moveto x y;
Guile.eol
let () =
Graphics.open_graph " 400x400+50-0";
Graphics.auto_synchronize true;
Graphics.moveto 200 200;
Guile.init ();
ignore @@ Guile.Functions.register_fun1 "pen-down" set_pen_down;
ignore @@ Guile.Functions.register_fun1 ~no_opt:1 "turn-left" turn_left;
ignore @@ Guile.Functions.register_fun1 ~no_opt:1 "turn-right" turn_right;
ignore @@ Guile.Functions.register_fun1 "move-by" move_by;
ignore @@ Guile.Functions.register_fun2 "move-to" move_to;
Guile.shell ()
|
|
87a7962c5292953833652c62babc1a4b7d657fde2bb74593fc621555e6e8637a | bmeurer/ocaml-experimental | typecheck.mli | (*************************************************************************)
(* *)
(* Objective Caml LablTk library *)
(* *)
, Kyoto University RIMS
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
(* General Public License, with the special exception on linking *)
(* described in file ../../../LICENSE. *)
(* *)
(*************************************************************************)
$ Id$
open Widget
open Mytypes
val nowarnings : bool ref
val f : edit_window -> any widget list
(* Typechecks the window as much as possible *)
| null | https://raw.githubusercontent.com/bmeurer/ocaml-experimental/fe5c10cdb0499e43af4b08f35a3248e5c1a8b541/otherlibs/labltk/browser/typecheck.mli | ocaml | ***********************************************************************
Objective Caml LablTk library
General Public License, with the special exception on linking
described in file ../../../LICENSE.
***********************************************************************
Typechecks the window as much as possible | , Kyoto University RIMS
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
$ Id$
open Widget
open Mytypes
val nowarnings : bool ref
val f : edit_window -> any widget list
|
e7ba92531a20c63d021f8d1205bac9a90b30421c43ccf91ae3623f19978440d0 | nunchaku-inria/nunchaku | Polarize.mli |
(* This file is free software, part of nunchaku. See file "license" for more details. *)
(** {1 Polarize}
This duplicates some predicate definitions (either recursive equations,
or (co)inductive specifications) depending on the call-site polarity.
*)
open Nunchaku_core
type term = Term.t
type decode_state
val name : string
* inductive predicates and possibly some other predicates
in the problem .
@param polarize_rec if true , some propositions defined with ` rec `
might be polarized
in the problem.
@param polarize_rec if true, some propositions defined with `rec`
might be polarized *)
val polarize :
polarize_rec:bool ->
(term, term) Problem.t ->
(term, term) Problem.t * decode_state
val decode_model : state:decode_state -> (term,term) Model.t -> (term,term) Model.t
(** Pipeline component *)
val pipe :
polarize_rec:bool ->
print:bool ->
check:bool ->
((term, term) Problem.t,
(term, term) Problem.t,
(term, term) Problem.Res.t,
(term, term) Problem.Res.t) Transform.t
(** Generic Pipe Component
@param decode the decode function that takes an applied [(module S)]
in addition to the state *)
val pipe_with :
?on_decoded:('d -> unit) list ->
decode:(decode_state -> 'c -> 'd) ->
polarize_rec:bool ->
print:bool ->
check:bool ->
((term, term) Problem.t,
(term, term) Problem.t,
'c, 'd
) Transform.t
| null | https://raw.githubusercontent.com/nunchaku-inria/nunchaku/16f33db3f5e92beecfb679a13329063b194f753d/src/transformations/Polarize.mli | ocaml | This file is free software, part of nunchaku. See file "license" for more details.
* {1 Polarize}
This duplicates some predicate definitions (either recursive equations,
or (co)inductive specifications) depending on the call-site polarity.
* Pipeline component
* Generic Pipe Component
@param decode the decode function that takes an applied [(module S)]
in addition to the state |
open Nunchaku_core
type term = Term.t
type decode_state
val name : string
* inductive predicates and possibly some other predicates
in the problem .
@param polarize_rec if true , some propositions defined with ` rec `
might be polarized
in the problem.
@param polarize_rec if true, some propositions defined with `rec`
might be polarized *)
val polarize :
polarize_rec:bool ->
(term, term) Problem.t ->
(term, term) Problem.t * decode_state
val decode_model : state:decode_state -> (term,term) Model.t -> (term,term) Model.t
val pipe :
polarize_rec:bool ->
print:bool ->
check:bool ->
((term, term) Problem.t,
(term, term) Problem.t,
(term, term) Problem.Res.t,
(term, term) Problem.Res.t) Transform.t
val pipe_with :
?on_decoded:('d -> unit) list ->
decode:(decode_state -> 'c -> 'd) ->
polarize_rec:bool ->
print:bool ->
check:bool ->
((term, term) Problem.t,
(term, term) Problem.t,
'c, 'd
) Transform.t
|
e24ba5a191496ad25373082337a85561c85b0c0d9100e1010c92c0937210d95d | babashka/babashka | curl_test.clj | (ns babashka.curl-test
(:require [babashka.curl :as curl]
[cheshire.core :as json]
[clojure.test :as t :refer [deftest]]))
(deftest curl-test
(require '[babashka.curl :as curl] :reload-all)
(prn (:status (curl/get "")))
(prn (:status (curl/get "-echo.com/get?foo1=bar1&foo2=bar2")))
(prn (:status (curl/post "-echo.com/post")))
(prn (:status (curl/post "-echo.com/post"
{:body (json/generate-string {:a 1})
:headers {"X-Hasura-Role" "admin"}
:content-type :json
:accept :json})))
(prn (:status (curl/put "-echo.com/put"
{:body (json/generate-string {:a 1})
:headers {"X-Hasura-Role" "admin"}
:content-type :json
:accept :json}))))
| null | https://raw.githubusercontent.com/babashka/babashka/3dfc15f5a40efaec07cba991892c1207a352fab4/test-resources/lib_tests/babashka/curl_test.clj | clojure | (ns babashka.curl-test
(:require [babashka.curl :as curl]
[cheshire.core :as json]
[clojure.test :as t :refer [deftest]]))
(deftest curl-test
(require '[babashka.curl :as curl] :reload-all)
(prn (:status (curl/get "")))
(prn (:status (curl/get "-echo.com/get?foo1=bar1&foo2=bar2")))
(prn (:status (curl/post "-echo.com/post")))
(prn (:status (curl/post "-echo.com/post"
{:body (json/generate-string {:a 1})
:headers {"X-Hasura-Role" "admin"}
:content-type :json
:accept :json})))
(prn (:status (curl/put "-echo.com/put"
{:body (json/generate-string {:a 1})
:headers {"X-Hasura-Role" "admin"}
:content-type :json
:accept :json}))))
|
|
896a07ef74d5dd8d01b7d4f106507b0c8818f167c22392a6063d7f3a7f49ab00 | leviroth/ocaml-reddit-api | subreddit_traffic.mli | open! Core
type t [@@deriving sexp]
include Json_object.S_with_fields with type t := t
module By_date : sig
type t =
{ date : Date.t
; uniques : int
; pageviews : int
; subscriptions : int
}
[@@deriving sexp]
end
module By_month : sig
type t =
{ year : int
; month : Month.t
; uniques : int
; pageviews : int
}
[@@deriving sexp]
end
module By_hour : sig
type t =
{ hour : Time_ns.t
; uniques : int
; pageviews : int
}
[@@deriving sexp]
end
val by_date : t -> By_date.t list
val by_month : t -> By_month.t list
val by_hour : t -> By_hour.t list
| null | https://raw.githubusercontent.com/leviroth/ocaml-reddit-api/0ce219356a5b3b38445868eb5dce10951f3eb4e0/reddit_api_kernel/subreddit_traffic.mli | ocaml | open! Core
type t [@@deriving sexp]
include Json_object.S_with_fields with type t := t
module By_date : sig
type t =
{ date : Date.t
; uniques : int
; pageviews : int
; subscriptions : int
}
[@@deriving sexp]
end
module By_month : sig
type t =
{ year : int
; month : Month.t
; uniques : int
; pageviews : int
}
[@@deriving sexp]
end
module By_hour : sig
type t =
{ hour : Time_ns.t
; uniques : int
; pageviews : int
}
[@@deriving sexp]
end
val by_date : t -> By_date.t list
val by_month : t -> By_month.t list
val by_hour : t -> By_hour.t list
|
|
601bf705b1a52ff8bf5e8693953a4f30e5fb1b9b318c9c919db52f49d37da95d | helium/miner | miner_ct_utils.erl | -module(miner_ct_utils).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("blockchain/include/blockchain_vars.hrl").
-include_lib("blockchain/include/blockchain.hrl").
-include_lib("blockchain/include/blockchain_txn_fees.hrl").
-include("miner_ct_macros.hrl").
-define(BASE_TMP_DIR, "./_build/test/tmp").
-define(BASE_TMP_DIR_TEMPLATE, "XXXXXXXXXX").
-export([
init_per_testcase/3,
end_per_testcase/2,
pmap/2, pmap/3,
wait_until/1, wait_until/3,
wait_until_disconnected/2,
wait_until_local_height/1,
get_addrs/1,
start_miner/2,
start_node/1,
partition_cluster/2,
heal_cluster/2,
connect/1,
count/2,
randname/1,
get_config/2,
get_gw_owner/2,
get_balance/2,
get_nonce/2,
get_dc_balance/2,
get_dc_nonce/2,
get_block/2,
make_vars/1, make_vars/2, make_vars/3,
tmp_dir/0, tmp_dir/1, nonl/1,
cleanup_tmp_dir/1,
init_base_dir_config/3,
generate_keys/1,
new_random_key/1,
new_random_key_with_sig_fun/1,
stop_miners/1, stop_miners/2,
start_miners/1, start_miners/2,
height/1,
heights/1,
unique_heights/1,
consensus_members/1, consensus_members/2,
miners_by_consensus_state/1,
in_consensus_miners/1,
non_consensus_miners/1,
election_check/4,
integrate_genesis_block/2,
shuffle/1,
partition_miners/2,
node2addr/2,
node2sigfun/2,
node2pubkeybin/2,
addr2node/2,
addr_list/1,
blockchain_worker_check/1,
wait_for_registration/2, wait_for_registration/3,
wait_for_app_start/2, wait_for_app_start/3,
wait_for_app_stop/2, wait_for_app_stop/3,
wait_for_in_consensus/2, wait_for_in_consensus/3,
wait_for_chain_var_update/3, wait_for_chain_var_update/4,
wait_for_lora_port/3,
delete_dirs/2,
initial_dkg/5, initial_dkg/6,
confirm_balance/3,
confirm_balance_both_sides/5,
wait_for_gte/3, wait_for_gte/5,
wait_for_equalized_heights/1,
wait_for_chain_stall/1,
wait_for_chain_stall/2,
assert_chain_halted/1,
assert_chain_halted/3,
assert_chain_advanced/1,
assert_chain_advanced/3,
submit_txn/2,
wait_for_txn/2, wait_for_txn/3, wait_for_txn/4,
format_txn_mgr_list/1,
get_txn_block_details/2, get_txn_block_details/3,
get_txn/2, get_txns/2,
get_genesis_block/2,
load_genesis_block/3,
chain_var_lookup_all/2,
chain_var_lookup_one/2,
build_gateways/2,
build_asserts/2,
add_block/3,
gen_gateways/2, gen_payments/1, gen_locations/1,
existing_vars/0, start_blockchain/2,
create_block/2
]).
chain_var_lookup_all(Key, Nodes) ->
[chain_var_lookup_one(Key, Node) || Node <- Nodes].
chain_var_lookup_one(Key, Node) ->
Chain = ct_rpc:call(Node, blockchain_worker, blockchain, [], 500),
Ledger = ct_rpc:call(Node, blockchain, ledger, [Chain]),
Result = ct_rpc:call(Node, blockchain, config, [Key, Ledger], 500),
ct:pal("Var lookup. Node:~p, Result:~p", [Node, Result]),
Result.
-spec assert_chain_advanced([node()]) -> ok.
assert_chain_advanced(Miners) ->
Height = wait_for_equalized_heights(Miners),
?assertMatch(
ok,
miner_ct_utils:wait_for_gte(height, Miners, Height + 1),
"Chain advanced."
),
ok.
assert_chain_advanced(_, _, N) when N =< 0 ->
ok;
assert_chain_advanced(Miners, Interval, N) ->
ok = assert_chain_advanced(Miners),
timer:sleep(Interval),
assert_chain_advanced(Miners, Interval, N - 1).
-spec assert_chain_halted([node()]) -> ok.
assert_chain_halted(Miners) ->
assert_chain_halted(Miners, 5000, 20).
-spec assert_chain_halted([node()], timeout(), pos_integer()) -> ok.
assert_chain_halted(Miners, Interval, Retries) ->
_ = lists:foldl(
fun (_, HeightPrev) ->
HeightCurr = wait_for_equalized_heights(Miners),
?assertEqual(HeightPrev, HeightCurr, "Chain halted."),
timer:sleep(Interval),
HeightCurr
end,
wait_for_equalized_heights(Miners),
lists:duplicate(Retries, {})
),
ok.
wait_for_chain_stall(Miners) ->
wait_for_chain_stall(Miners, #{}).
-spec wait_for_chain_stall([node()], Options) -> ok | error when
Options :: #{
interval => timeout(),
retries_max => pos_integer(),
streak_target => pos_integer()
}.
wait_for_chain_stall(Miners, Options=#{}) ->
State =
#{
interval => maps:get(interval, Options, 5000),
retries_max => maps:get(retries_max, Options, 100),
streak_target => maps:get(streak_target, Options, 5),
streak_prev => 0,
retries_cur => 0,
height_prev => 0
},
wait_for_chain_stall_(Miners, State).
wait_for_chain_stall_(_, #{streak_target := Target, streak_prev := Streak}) when Streak >= Target ->
ok;
wait_for_chain_stall_(_, #{retries_cur := Cur, retries_max := Max}) when Cur >= Max ->
error;
wait_for_chain_stall_(
Miners,
#{
interval := Interval,
streak_prev := StreakPrev,
height_prev := HeightPrev,
retries_cur := RetriesCur
}=State0
) ->
{HeightCurr, StreakCurr} =
case wait_for_equalized_heights(Miners) of
HeightPrev -> {HeightPrev, 1 + StreakPrev};
HeightCurr0 -> {HeightCurr0, 0}
end,
timer:sleep(Interval),
State1 = State0#{
height_prev := HeightCurr,
streak_prev := StreakCurr,
retries_cur := RetriesCur + 1
},
wait_for_chain_stall_(Miners, State1).
-spec wait_for_equalized_heights([node()]) -> non_neg_integer().
wait_for_equalized_heights(Miners) ->
?assert(
miner_ct_utils:wait_until(
fun() ->
case unique_heights(Miners) of
[_] -> true;
[_|_] -> false
end
end,
50,
1000
),
"Heights equalized."
),
UniqueHeights = unique_heights(Miners),
?assertMatch([_], UniqueHeights, "All heights are equal."),
[Height] = UniqueHeights,
Height.
wait_until_local_height(TargetHeight) ->
miner_ct_utils:wait_until(
fun() ->
C = blockchain_worker:blockchain(),
{ok, CurHeight} = blockchain:height(C),
ct:pal("local height ~p", [CurHeight]),
CurHeight >= TargetHeight
end,
30,
timer:seconds(1)
).
stop_miners(Miners) ->
stop_miners(Miners, 60).
stop_miners(Miners, Retries) ->
Res = [begin
ct:pal("capturing env for ~p", [Miner]),
LagerEnv = ct_rpc:call(Miner, application, get_all_env, [lager]),
P2PEnv = ct_rpc:call(Miner, application, get_all_env, [libp2p]),
BlockchainEnv = ct_rpc:call(Miner, application, get_all_env, [blockchain]),
MinerEnv = ct_rpc:call(Miner, application, get_all_env, [miner]),
ct:pal("stopping ~p", [Miner]),
erlang:monitor_node(Miner, true),
ct_slave:stop(Miner),
receive
{nodedown, Miner} ->
ok
after timer:seconds(Retries) ->
error(stop_timeout)
end,
ct:pal("stopped ~p", [Miner]),
{Miner, [{lager, LagerEnv}, {libp2p, P2PEnv}, {blockchain, BlockchainEnv}, {miner, MinerEnv}]}
end
|| Miner <- Miners],
Res.
start_miner(Name0, Options) ->
Name = start_node(Name0),
Keys = make_keys(Name, {45000, 0, 4466}),
config_node(Keys, Options),
{Name, Keys}.
start_miners(Miners) ->
start_miners(Miners, 60).
start_miners(MinersAndEnv, Retries) ->
[begin
ct:pal("starting ~p", [Miner]),
start_node(Miner),
ct:pal("loading env ~p", [Miner]),
ok = ct_rpc:call(Miner, application, set_env, [Env]),
ct:pal("starting miner on ~p", [Miner]),
{ok, _StartedApps} = ct_rpc:call(Miner, application, ensure_all_started, [miner]),
ct:pal("started miner on ~p : ~p", [Miner, _StartedApps])
end
|| {Miner, Env} <- MinersAndEnv],
{Miners, _Env} = lists:unzip(MinersAndEnv),
ct:pal("waiting for blockchain worker to start on ~p", [Miners]),
ok = miner_ct_utils:wait_for_registration(Miners, blockchain_worker, Retries),
ok.
height(Miner) ->
C0 = ct_rpc:call(Miner, blockchain_worker, blockchain, []),
{ok, Height} = ct_rpc:call(Miner, blockchain, height, [C0]),
ct:pal("miner ~p height ~p", [Miner, Height]),
Height.
heights(Miners) ->
lists:foldl(fun(Miner, Acc) ->
C = ct_rpc:call(Miner, blockchain_worker, blockchain, []),
{ok, H} = ct_rpc:call(Miner, blockchain, height, [C]),
[{Miner, H} | Acc]
end, [], Miners).
-spec unique_heights([node()]) -> [non_neg_integer()].
unique_heights(Miners) ->
lists:usort([H || {_, H} <- miner_ct_utils:heights(Miners)]).
consensus_members([]) ->
error(no_members);
consensus_members([M | Tail]) ->
case handle_get_consensus_miners(M) of
{ok, Members} ->
Members;
{error, _} ->
timer:sleep(500),
consensus_members(Tail)
end.
consensus_members(Epoch, []) ->
error({no_members_at_epoch, Epoch});
consensus_members(Epoch, [M | Tail]) ->
try ct_rpc:call(M, miner_cli_info, get_info, [], 2000) of
{_, _, Epoch} ->
{ok, Members} = handle_get_consensus_miners(M),
Members;
Other ->
ct:pal("~p had Epoch ~p", [M, Other]),
timer:sleep(500),
consensus_members(Epoch, Tail)
catch C:E ->
ct:pal("~p threw error ~p:~p", [M, C, E]),
timer:sleep(500),
consensus_members(Epoch, Tail)
end.
miners_by_consensus_state(Miners)->
handle_miners_by_consensus(partition, true, Miners).
in_consensus_miners(Miners)->
handle_miners_by_consensus(filtermap, true, Miners).
non_consensus_miners(Miners)->
handle_miners_by_consensus(filtermap, false, Miners).
election_check([], _Miners, _AddrList, Owner) ->
Owner ! seen_all;
election_check(NotSeen0, Miners, AddrList, Owner) ->
timer:sleep(500),
NotSeen =
try
Members = miner_ct_utils:consensus_members(Miners),
MinerNames = lists:map(fun(Member)-> miner_ct_utils:addr2node(Member, AddrList) end, Members),
NotSeen1 = NotSeen0 -- MinerNames,
Owner ! {not_seen, NotSeen1},
NotSeen1
catch _C:_E ->
NotSeen0
end,
election_check(NotSeen, Miners, AddrList, Owner).
integrate_genesis_block(ConsensusMiner, NonConsensusMiners)->
Blockchain = ct_rpc:call(ConsensusMiner, blockchain_worker, blockchain, []),
{ok, GenesisBlock} = ct_rpc:call(ConsensusMiner, blockchain, genesis_block, [Blockchain]),
%% TODO - do we need to assert here on results from genesis load ?
miner_ct_utils:pmap(fun(M) ->
ct_rpc:call(M, blockchain_worker, integrate_genesis_block, [GenesisBlock])
end, NonConsensusMiners).
blockchain_worker_check(Miners)->
lists:all(
fun(Res) ->
Res /= undefined
end,
lists:foldl(
fun(Miner, Acc) ->
R = ct_rpc:call(Miner, blockchain_worker, blockchain, []),
[R | Acc]
end, [], Miners)).
confirm_balance(Miners, Addr, Bal) ->
?assertAsync(begin
Result = lists:all(
fun(Miner) ->
Bal == miner_ct_utils:get_balance(Miner, Addr)
end, Miners)
end,
Result == true, 60, timer:seconds(5)),
ok.
confirm_balance_both_sides(Miners, PayerAddr, PayeeAddr, PayerBal, PayeeBal) ->
?assertAsync(begin
Result = lists:all(
fun(Miner) ->
PayerBal == miner_ct_utils:get_balance(Miner, PayerAddr) andalso
PayeeBal == miner_ct_utils:get_balance(Miner, PayeeAddr)
end, Miners)
end,
Result == true, 60, timer:seconds(1)),
ok.
submit_txn(Txn, Miners) ->
lists:foreach(fun(Miner) ->
ct_rpc:call(Miner, blockchain_worker, submit_txn, [Txn])
end, Miners).
wait_for_gte(height = Type, Miners, Threshold)->
wait_for_gte(Type, Miners, Threshold, all, 60);
wait_for_gte(epoch = Type, Miners, Threshold)->
wait_for_gte(Type, Miners, Threshold, any, 60);
wait_for_gte(height_exactly = Type, Miners, Threshold)->
wait_for_gte(Type, Miners, Threshold, all, 60).
wait_for_gte(Type, Miners, Threshold, Mod, Retries)->
Res = ?noAssertAsync(begin
lists:Mod(
fun(Miner) ->
try
handle_gte_type(Type, Miner, Threshold)
catch What:Why ->
ct:pal("Failed to check GTE ~p ~p ~p: ~p:~p", [Type, Miner, Threshold, What, Why]),
false
end
end, miner_ct_utils:shuffle(Miners))
end,
Retries, timer:seconds(1)),
case Res of
true -> ok;
false -> {error, false}
end.
wait_for_registration(Miners, Mod) ->
wait_for_registration(Miners, Mod, 300).
wait_for_registration(Miners, Mod, Timeout) ->
?assertAsync(begin
RegistrationResult
= lists:all(
fun(Miner) ->
case ct_rpc:call(Miner, erlang, whereis, [Mod], Timeout) of
P when is_pid(P) ->
true;
Other ->
ct:pal("~p result ~p~n", [Miner, Other]),
false
end
end, Miners)
end,
RegistrationResult, 90, timer:seconds(1)),
ok.
wait_for_app_start(Miners, App) ->
wait_for_app_start(Miners, App, 60).
wait_for_app_start(Miners, App, Retries) ->
?assertAsync(begin
AppStartResult =
lists:all(
fun(Miner) ->
case ct_rpc:call(Miner, application, which_applications, []) of
{badrpc, _} ->
false;
Apps ->
lists:keymember(App, 1, Apps)
end
end, Miners)
end,
AppStartResult, Retries, 500),
ok.
wait_for_app_stop(Miners, App) ->
wait_for_app_stop(Miners, App, 30).
wait_for_app_stop(Miners, App, Retries) ->
?assertAsync(begin
Result = lists:all(
fun(Miner) ->
case ct_rpc:call(Miner, application, which_applications, []) of
{badrpc, nodedown} ->
true;
{badrpc, _Which} ->
ct:pal("~p ~p", [Miner, _Which]),
false;
Apps ->
ct:pal("~p ~p", [Miner, Apps]),
not lists:keymember(App, 1, Apps)
end
end, Miners)
end,
Result == true, Retries, 500),
ok.
wait_for_in_consensus(Miners, NumInConsensus)->
wait_for_in_consensus(Miners, NumInConsensus, 500).
wait_for_in_consensus(Miners, NumInConsensus, Timeout)->
?assertAsync(begin
Result = lists:filtermap(
fun(Miner) ->
C1 = ct_rpc:call(Miner, blockchain_worker, blockchain, [], Timeout),
L1 = ct_rpc:call(Miner, blockchain, ledger, [C1], Timeout),
case ct_rpc:call(Miner, blockchain, config, [num_consensus_members, L1], Timeout) of
{ok, _Sz} ->
true == ct_rpc:call(Miner, miner_consensus_mgr, in_consensus, []);
_ ->
%% badrpc
false
end
end, Miners),
ct:pal("size ~p", [length(Result)]),
Result
end,
NumInConsensus == length(Result), 60, timer:seconds(1)),
ok.
wait_for_chain_var_update(Miners, Key, Value)->
wait_for_chain_var_update(Miners, Key, Value, 20).
wait_for_chain_var_update(Miners, Key, Value, Retries)->
case wait_until(
fun() ->
lists:all(
fun(Miner) ->
{ok, Value} == chain_var_lookup_one(Key, Miner)
end, miner_ct_utils:shuffle(Miners))
end,
Retries * 2, 500) of
%% back compat
true -> ok;
Else -> Else
end.
wait_for_lora_port(Miners, Mod, Retries)->
?noAssertAsync(begin
lists:all(
fun(Miner) ->
try
case ct_rpc:call(Miner, Mod, port, []) of
{error, _} ->
ct:pal("Failed to find lora port ~p via module ~p", [Miner, Mod]),
false;
_ -> true
end
catch _:_ ->
ct:pal("Failed to find lora port ~p", [Miner]),
false
end
end, Miners)
end,
Retries, timer:seconds(1)).
delete_dirs(DirWildcard, SubDir)->
Dirs = filelib:wildcard(DirWildcard),
[begin
ct:pal("rm dir ~s", [Dir ++ SubDir]),
os:cmd("rm -r " ++ Dir ++ SubDir)
end
|| Dir <- Dirs],
ok.
initial_dkg(Miners, Txns, Addresses, NumConsensusMembers, Curve)->
initial_dkg(Miners, Txns, Addresses, NumConsensusMembers, Curve, 60000).
initial_dkg(Miners, Txns, Addresses, NumConsensusMembers, Curve, Timeout) ->
SuperParent = self(),
SuperTimeout = Timeout + 5000,
Threshold = (NumConsensusMembers - 1) div 3,
spawn(fun() ->
Parent = self(),
lists:foreach(
fun(Miner) ->
spawn(fun() ->
Res = ct_rpc:call(Miner, miner_consensus_mgr, initial_dkg,
[Txns, Addresses, NumConsensusMembers, Curve], Timeout),
Parent ! {Miner, Res}
end)
end, Miners),
SuperParent ! receive_dkg_results(Threshold, Miners, [])
end),
receive
DKGResults ->
DKGResults
after SuperTimeout ->
{error, dkg_timeout}
end.
receive_dkg_results(Threshold, [], OKResults) ->
ct:pal("only ~p completed dkg, lower than threshold of ~p", [OKResults, Threshold]),
{error, insufficent_dkg_completion};
receive_dkg_results(Threshold, _Miners, OKResults) when length(OKResults) >= Threshold ->
{ok, OKResults};
receive_dkg_results(Threshold, Miners, OKResults) ->
receive
{Miner, ok} ->
case lists:member(Miner, Miners) of
true ->
receive_dkg_results(Threshold, Miners -- [Miner], [Miner|OKResults]);
false ->
receive_dkg_results(Threshold, Miners, OKResults)
end;
{Miner, OtherResult} ->
ct:pal("Miner ~p failed DKG: ~p", [Miner, OtherResult]),
receive_dkg_results(Threshold, Miners -- [Miner], OKResults)
end.
pmap(F, L) ->
pmap(F, L, timer:seconds(90)).
pmap(F, L, Timeout) ->
Parent = self(),
lists:foldl(
fun(X, N) ->
spawn_link(fun() ->
Parent ! {pmap, N, F(X)}
end),
N+1
end, 0, L),
L2 = [receive
{pmap, N, R} ->
{N,R}
after Timeout->
error(timeout_expired)
end || _ <- L],
{_, L3} = lists:unzip(lists:keysort(1, L2)),
L3.
wait_until(Fun) ->
wait_until(Fun, 40, 100).
wait_until(Fun, Retry, Delay) when Retry > 0 ->
Res = Fun(),
try Res of
true ->
true;
_ when Retry == 1 ->
false;
_ ->
timer:sleep(Delay),
wait_until(Fun, Retry-1, Delay)
catch _:_ ->
timer:sleep(Delay),
wait_until(Fun, Retry-1, Delay)
end.
wait_until_offline(Node) ->
wait_until(fun() ->
pang == net_adm:ping(Node)
end, 60*2, 500).
wait_until_disconnected(Node1, Node2) ->
wait_until(fun() ->
pang == rpc:call(Node1, net_adm, ping, [Node2])
end, 60*2, 500).
wait_until_connected(Node1, Node2) ->
wait_until(fun() ->
pong == rpc:call(Node1, net_adm, ping, [Node2])
end, 60*2, 500).
start_node(Name) ->
CodePath = lists:filter(fun filelib:is_dir/1, code:get_path()),
%% have the slave nodes monitor the runner node, so they can't outlive it
NodeConfig = [
{monitor_master, true},
{boot_timeout, 30},
{init_timeout, 30},
{startup_timeout, 30},
{startup_functions, [
{code, set_path, [CodePath]}
]}],
case ct_slave:start(Name, NodeConfig) of
{ok, Node} ->
?assertAsync(Result = net_adm:ping(Node), Result == pong, 60, 500),
Node;
{error, already_started, Node} ->
ct_slave:stop(Name),
wait_until_offline(Node),
start_node(Name);
{error, started_not_connected, Node} ->
connect(Node),
ct_slave:stop(Name),
wait_until_offline(Node),
start_node(Name);
Other ->
Other
end.
partition_cluster(ANodes, BNodes) ->
pmap(fun({Node1, Node2}) ->
true = rpc:call(Node1, erlang, set_cookie, [Node2, canttouchthis]),
true = rpc:call(Node1, erlang, disconnect_node, [Node2]),
true = wait_until_disconnected(Node1, Node2)
end,
[{Node1, Node2} || Node1 <- ANodes, Node2 <- BNodes]),
ok.
heal_cluster(ANodes, BNodes) ->
GoodCookie = erlang:get_cookie(),
pmap(fun({Node1, Node2}) ->
true = rpc:call(Node1, erlang, set_cookie, [Node2, GoodCookie]),
true = wait_until_connected(Node1, Node2)
end,
[{Node1, Node2} || Node1 <- ANodes, Node2 <- BNodes]),
ok.
connect(Node) ->
connect(Node, true).
connect(NodeStr, Auto) when is_list(NodeStr) ->
connect(erlang:list_to_atom(lists:flatten(NodeStr)), Auto);
connect(Node, Auto) when is_atom(Node) ->
connect(node(), Node, Auto).
connect(Node, Node, _) ->
{error, self_join};
connect(_, Node, _Auto) ->
attempt_connect(Node).
attempt_connect(Node) ->
case net_kernel:connect_node(Node) of
false ->
{error, not_reachable};
true ->
{ok, connected}
end.
count(_, []) -> 0;
count(X, [X|XS]) -> 1 + count(X, XS);
count(X, [_|XS]) -> count(X, XS).
randname(N) ->
randname(N, []).
randname(0, Acc) ->
Acc;
randname(N, Acc) ->
randname(N - 1, [rand:uniform(26) + 96 | Acc]).
get_config(Arg, Default) ->
case os:getenv(Arg, Default) of
false -> Default;
T when is_list(T) -> list_to_integer(T);
T -> T
end.
shuffle(List) ->
R = [{rand:uniform(1000000), I} || I <- List],
O = lists:sort(R),
{_, S} = lists:unzip(O),
S.
node2sigfun(Node, KeyList) ->
{_Miner, {_TCPPort, _UDPPort, _JsonRpcPort}, _ECDH, _PubKey, _Addr, SigFun} = lists:keyfind(Node, 1, KeyList),
SigFun.
node2pubkeybin(Node, KeyList) ->
{_Miner, {_TCPPort, _UDPPort, _JsonRpcPort}, _ECDH, _PubKey, Addr, _SigFun} = lists:keyfind(Node, 1, KeyList),
Addr.
node2addr(Node, AddrList) ->
{_, Addr} = lists:keyfind(Node, 1, AddrList),
Addr.
addr2node(Addr, AddrList) ->
{Node, _} = lists:keyfind(Addr, 2, AddrList),
Node.
addr_list(Miners) ->
miner_ct_utils:pmap(
fun(M) ->
Addr = ct_rpc:call(M, blockchain_swarm, pubkey_bin, []),
{M, Addr}
end, Miners).
partition_miners(Members, AddrList) ->
{Miners, _} = lists:unzip(AddrList),
lists:partition(fun(Miner) ->
Addr = miner_ct_utils:node2addr(Miner, AddrList),
lists:member(Addr, Members)
end, Miners).
init_per_testcase(Mod, TestCase, Config0) ->
Config = init_base_dir_config(Mod, TestCase, Config0),
BaseDir = ?config(base_dir, Config),
LogDir = ?config(log_dir, Config),
SplitMiners = proplists:get_value(split_miners_vals_and_gateways, Config, false),
NumValidators = proplists:get_value(num_validators, Config, 0),
NumGateways = proplists:get_value(num_gateways, Config, get_config("T", 8)),
NumConsensusMembers = proplists:get_value(num_consensus_members, Config, get_config("N", 7)),
LoadChainOnGateways = proplists:get_value(gateways_run_chain, Config, true),
GwMuxEnable = proplists:get_value(gateway_and_mux_enable, Config, false),
DefaultKeys = proplists:get_value(default_keys, Config, false),
os:cmd(os:find_executable("epmd")++" -daemon"),
{ok, Hostname} = inet:gethostname(),
case net_kernel:start([list_to_atom("runner-miner" ++
integer_to_list(erlang:system_time(nanosecond)) ++
"@"++Hostname), shortnames]) of
{ok, _} -> ok;
{error, {already_started, _}} -> ok;
{error, {{already_started, _},_}} -> ok
end,
TotalMiners = NumValidators + NumGateways,
SeedNodes = [],
UdpBase = 1690,
GwApiBase = 5068,
JsonRpcBase = 4486,
Port = get_config("PORT", 0),
Curve = 'SS512',
BlockTime = get_config("BT", 100),
BatchSize = get_config("BS", 500),
Interval = get_config("INT", 5),
MinersAndPorts = lists:reverse(lists:foldl(
fun(I, Acc) ->
MinerName = list_to_atom(integer_to_list(I) ++ miner_ct_utils:randname(5)),
[{start_node(MinerName), {GwApiBase + I, UdpBase + (I * 3), JsonRpcBase + I}} | Acc]
end,
[],
lists:seq(1, TotalMiners)
)),
ct:pal("MinersAndPorts: ~p",[MinersAndPorts]),
case lists:any(fun({{error, _}, _}) -> true; (_) -> false end, MinersAndPorts) of
true ->
%% kill any nodes we started and throw error
miner_ct_utils:pmap(fun({error, _}) -> ok; (Miner) -> ct_slave:stop(Miner) end, element(1, lists:unzip(MinersAndPorts))),
throw(hd([ E || {{error, E}, _} <- MinersAndPorts ]));
false ->
ok
end,
Keys = lists:reverse(lists:foldl(
fun({Miner, Ports}, Acc) ->
[make_keys(Miner, Ports) | Acc]
end, [], MinersAndPorts)),
ct:pal("Keys: ~p", [Keys]),
{_Miner, {_GwApiPort, _UDPPort, _JsonRpcPort}, _ECDH, _PubKey, Addr, _SigFun} = hd(Keys),
DefaultRouters = libp2p_crypto:pubkey_bin_to_p2p(Addr),
Options = [{mod, Mod},
{logdir, LogDir},
{basedir, BaseDir},
{seed_nodes, SeedNodes},
{total_miners, TotalMiners},
{curve, Curve},
{gateways_run_chain, LoadChainOnGateways},
{default_keys, DefaultKeys},
{default_routers, DefaultRouters},
{port, Port}],
%% config nodes
ConfigResult =
case SplitMiners of
true ->
if config says to use validators for CG then
%% split key sets into validators and miners
{ValKeys, GatewayKeys} = lists:split(NumValidators, Keys),
ct:pal("validator keys: ~p", [ValKeys]),
ct:pal("gateway keys: ~p", [GatewayKeys]),
carry the poc transport setting through to config node so that it can
%% set the app env var appropiately on each node
_GatewayConfigResult = miner_ct_utils:pmap(fun(N) -> config_node(N, [{gateway_and_mux_enable, GwMuxEnable}, {mode, gateway} | Options]) end, GatewayKeys),
ValConfigResult = miner_ct_utils:pmap(fun(N) -> config_node(N, [{mode, validator} | Options]) end, ValKeys),
ValConfigResult;
_ ->
miner_ct_utils:pmap(fun(N) -> config_node(N, [{mode, validator} | Options]) end, Keys)
end,
Miners = [M || {M, _} <- MinersAndPorts],
ct:pal("Miners: ~p", [Miners]),
%% get a sep list of validator and gateway node names
if SplitMiners is false then all miners will be gateways
{Validators, Gateways} =
case SplitMiners of
true ->
lists:split(NumValidators, Miners);
_ ->
{[], Miners}
end,
ct:pal("Validators: ~p", [Validators]),
ct:pal("Gateways: ~p", [Gateways]),
%% check that the config loaded correctly on each miner
true = lists:all(
fun(ok) -> true;
(Res) ->
ct:pal("config setup failure: ~p", [Res]),
false
end,
ConfigResult
),
%% hardcode some alias for our localhost miners
%% sibyl will not return routing data unless a miner/validator has a public address
%% so force an alias for each of our miners to a public IP
MinerAliases = lists:foldl(
fun({_, _, _, _, AliasAddr, _}, Acc) ->
P2PAddr = libp2p_crypto:pubkey_bin_to_p2p(AliasAddr),
[{P2PAddr, "/ip4/52.8.80.146/tcp/2154" } | Acc]
end, [], Keys),
ct:pal("miner aliases ~p", [MinerAliases]),
lists:foreach(fun(Miner)-> ct_rpc:call(Miner, application, set_env, [libp2p, node_aliases, MinerAliases]) end, Miners),
Addrs = get_addrs(Miners),
ct:pal("Addrs: ~p", [Addrs]),
miner_ct_utils:pmap(
fun(Miner) ->
TID = ct_rpc:call(Miner, blockchain_swarm, tid, [], 2000),
ct_rpc:call(Miner, miner_poc, add_stream_handler, [TID], 2000),
Swarm = ct_rpc:call(Miner, blockchain_swarm, tid, [], 2000),
lists:foreach(
fun(A) ->
ct_rpc:call(Miner, libp2p_swarm, connect, [Swarm, A], 2000)
end, Addrs)
end, Miners),
%% make sure each node is gossiping with a majority of its peers
true = miner_ct_utils:wait_until(
fun() ->
lists:all(
fun(Miner) ->
try
GossipPeers = ct_rpc:call(Miner, blockchain_swarm, gossip_peers, [], 500),
ct:pal("Miner: ~p, GossipPeers: ~p", [Miner, GossipPeers]),
case length(GossipPeers) >= (length(Miners) / 2) + 1 of
true -> true;
false ->
ct:pal("~p is not connected to enough peers ~p", [Miner, GossipPeers]),
Swarm = ct_rpc:call(Miner, blockchain_swarm, tid, [], 500),
lists:foreach(
fun(A) ->
CRes = ct_rpc:call(Miner, libp2p_swarm, connect, [Swarm, A], 500),
ct:pal("Connecting ~p to ~p: ~p", [Miner, A, CRes])
end, Addrs),
false
end
catch _C:_E ->
false
end
end, Miners)
end, 200, 150),
%% to enable the tests to run over grpc we need to deterministically set the grpc listen addr
with libp2p all the port data is in the peer entries
%% in the real world we would run grpc over a known port
%% but for the sake of the tests which run multiple nodes on a single instance
%% we need to choose a random port for each node
%% and the client needs to know which port was choosen
so for the sake of the tests what we do here is get the libp2p port
%% and run grpc on that value + 1000
the client then just has to pull the libp2p peer data
retrieve the libp2p port and derive the grpc port from that
GRPCServerConfigFun = fun(PeerPort)->
[#{grpc_opts => #{service_protos => [gateway_pb],
services => #{'helium.gateway' => helium_gateway_service}
},
transport_opts => #{ssl => false},
listen_opts => #{port => PeerPort,
ip => {0,0,0,0}},
pool_opts => #{size => 2},
server_opts => #{header_table_size => 4096,
enable_push => 1,
max_concurrent_streams => unlimited,
initial_window_size => 65535,
max_frame_size => 16384,
max_header_list_size => unlimited}}]
end,
ok = lists:foreach(fun(Node) ->
Swarm = ct_rpc:call(Node, blockchain_swarm, swarm, []),
TID = ct_rpc:call(Node, blockchain_swarm, tid, []),
ListenAddrs = ct_rpc:call(Node, libp2p_swarm, listen_addrs, [Swarm]),
[H | _ ] = _SortedAddrs = ct_rpc:call(Node, libp2p_transport, sort_addrs, [TID, ListenAddrs]),
[_, _, _IP,_, Libp2pPort] = _Full = re:split(H, "/"),
ThisPort = list_to_integer(binary_to_list(Libp2pPort)),
_ = ct_rpc:call(Node, application, set_env, [grpcbox, servers, GRPCServerConfigFun(ThisPort + 1000)]),
_ = ct_rpc:call(Node, application, ensure_all_started, [grpcbox]),
ok
end, Miners),
%% setup a bunch of aliases for the running miner grpc hosts
as per above , each such port will be the equivilent libp2p port + 1000
%% these grpc aliases are added purely for testing purposes
%% no current need to support in the wild
MinerGRPCPortAliases = lists:foldl(
fun({Miner, _, _, _, GrpcAliasAddr, _}, Acc) ->
P2PAddr = libp2p_crypto:pubkey_bin_to_p2p(GrpcAliasAddr),
Swarm = ct_rpc:call(Miner, blockchain_swarm, swarm, []),
TID = ct_rpc:call(Miner, blockchain_swarm, tid, []),
ListenAddrs = ct_rpc:call(Miner, libp2p_swarm, listen_addrs, [Swarm]),
[H | _ ] = _SortedAddrs = ct_rpc:call(Miner, libp2p_transport, sort_addrs, [TID, ListenAddrs]),
[_, _, _IP,_, Libp2pPort] = _Full = re:split(H, "/"),
GrpcPort = list_to_integer(binary_to_list(Libp2pPort)) + 1000,
[{P2PAddr, {GrpcPort, false}} | Acc]
end, [], Keys),
ct:pal("miner grpc port aliases ~p", [MinerGRPCPortAliases]),
create a list of validators and for each their p2p addr , ip addr and grpc port
%% use this list to set an app env var to provide a list of default validators to which
%% gateways can connect
%% only used when testing grpc gateways
SeedValidators = lists:foldl(
fun({Miner, _, _, _, ValAddr, _}, Acc) ->
P2PAddr = libp2p_crypto:pubkey_bin_to_p2p(ValAddr),
Swarm = ct_rpc:call(Miner, blockchain_swarm, swarm, []),
TID = ct_rpc:call(Miner, blockchain_swarm, tid, []),
ListenAddrs = ct_rpc:call(Miner, libp2p_swarm, listen_addrs, [Swarm]),
[H | _ ] = _SortedAddrs = ct_rpc:call(Miner, libp2p_transport, sort_addrs, [TID, ListenAddrs]),
[_, _, _IP,_, Libp2pPort] = _Full = re:split(H, "/"),
GrpcPort = list_to_integer(binary_to_list(Libp2pPort)) + 1000,
[{P2PAddr, "127.0.0.1", GrpcPort} | Acc]
end, [], Keys),
ct:pal("seed validators: ~p", [SeedValidators]),
set any required env vars for gateways
lists:foreach(fun(Gateway)->
ct_rpc:call(Gateway, application, set_env, [miner, seed_validators, SeedValidators])
end, Gateways),
%% set any required env vars for validators
lists:foreach(fun(Val)->
ct_rpc:call(Val, application, set_env, [sibyl, node_grpc_port_aliases, MinerGRPCPortAliases]),
ct_rpc:call(Val, application, set_env, [sibyl, poc_mgr_mod, miner_poc_mgr]),
ct_rpc:call(Val, application, set_env, [sibyl, poc_report_handler, miner_poc_report_handler])
end, Validators),
%% accumulate the address of each miner
MinerTaggedAddresses = lists:reverse(lists:foldl(
fun(Miner, Acc) ->
PubKeyBin = ct_rpc:call(Miner, blockchain_swarm, pubkey_bin, []),
[{Miner, PubKeyBin} | Acc]
end,
[],
Miners
)),
ct:pal("MinerTaggedAddresses: ~p", [MinerTaggedAddresses]),
%% save a version of the address list with the miner and address tuple
%% and then a version with just a list of addresses
{_Keys, Addresses} = lists:unzip(MinerTaggedAddresses),
{ValidatorAddrs, GatewayAddrs} =
case SplitMiners of
true ->
lists:split(NumValidators, Addresses);
_ ->
{[], Addresses}
end,
ct:pal("Validator Addrs: ~p", [ValidatorAddrs]),
ct:pal("Gateway Addrs: ~p", [GatewayAddrs]),
{ok, _} = ct_cover:add_nodes(Miners),
%% wait until we get confirmation the miners are fully up
%% which we are determining by the miner_consensus_mgr being registered
%% if we have a split of validators and gateways, we only need to wait on the validators
%% otherwise wait for all gateways
case SplitMiners of
true ->
ok = miner_ct_utils:wait_for_registration(Validators, miner_consensus_mgr);
false ->
ok = miner_ct_utils:wait_for_registration(Miners, miner_consensus_mgr)
end,
%% get a sep list of ports for validators and gateways
{ValidatorPorts, GatewayPorts} =
case SplitMiners of
true ->
lists:split(NumValidators, MinersAndPorts);
_ ->
{[], MinersAndPorts}
end,
UpdatedValidatorPorts = lists:map(fun({Miner, {_, _, JsonRpcPort}}) ->
{Miner, {ignore, ignore, JsonRpcPort}}
end, ValidatorPorts),
[
{miners, Miners},
{validators, Validators},
{gateways, Gateways},
{validator_addrs, ValidatorAddrs},
{gateway_addrs, GatewayAddrs},
{addrs, Addrs},
{keys, Keys},
{ports, UpdatedValidatorPorts ++ GatewayPorts},
{validator_ports, UpdatedValidatorPorts},
{gateway_ports, GatewayPorts},
{node_options, Options},
{addresses, Addresses},
{tagged_miner_addresses, MinerTaggedAddresses},
{block_time, BlockTime},
{batch_size, BatchSize},
{dkg_curve, Curve},
{election_interval, Interval},
{num_consensus_members, NumConsensusMembers},
{rpc_timeout, timer:seconds(30)}
| Config
].
get_addrs(Miners) ->
lists:foldl(
fun(Miner, Acc) ->
Swarm = ct_rpc:call(Miner, blockchain_swarm, swarm, [], 2000),
ct:pal("swarm ~p ~p", [Miner, Swarm]),
true = miner_ct_utils:wait_until(
fun() ->
length(ct_rpc:call(Miner, libp2p_swarm, listen_addrs, [Swarm], 5000)) > 0
end, 20, 1000),
[H|_] = ct_rpc:call(Miner, libp2p_swarm, listen_addrs, [Swarm], 5000),
ct:pal("miner ~p has addr ~p", [Miner, H]),
[H | Acc]
end, [], Miners).
make_keys(Miner, Ports) ->
#{secret := GPriv, public := GPub} =
libp2p_crypto:generate_keys(ecc_compact),
GECDH = libp2p_crypto:mk_ecdh_fun(GPriv),
GAddr = libp2p_crypto:pubkey_to_bin(GPub),
GSigFun = libp2p_crypto:mk_sig_fun(GPriv),
{Miner, Ports, GECDH, GPub, GAddr, GSigFun}.
config_node({Miner, {GwApiPort, UDPPort, JSONRPCPort}, ECDH, PubKey, _Addr, SigFun}, Options) ->
Mod = proplists:get_value(mod, Options),
LogDir = proplists:get_value(logdir, Options),
BaseDir = proplists:get_value(basedir, Options),
SeedNodes = proplists:get_value(seed_nodes, Options),
TotalMiners = proplists:get_value(total_miners, Options),
Curve = proplists:get_value(curve, Options),
DefaultRouters = proplists:get_value(default_routers, Options),
Port = proplists:get_value(port, Options),
Mode = proplists:get_value(mode, Options, gateway),
GwMuxEnable = proplists:get_value(gateway_and_mux_enable, Options, false),
LoadChainOnGateways = proplists:get_value(gateways_run_chain, Options, true),
ct:pal("Miner ~p", [Miner]),
ct_rpc:call(Miner, cover, start, []),
ct_rpc:call(Miner, application, load, [lager]),
ct_rpc:call(Miner, application, load, [miner]),
ct_rpc:call(Miner, application, load, [blockchain]),
ct_rpc:call(Miner, application, load, [libp2p]),
%% give each miner its own log directory
LogRoot = LogDir ++ "_" ++ atom_to_list(Miner),
ct:pal("MinerLogRoot: ~p", [LogRoot]),
ct_rpc:call(Miner, application, set_env, [lager, log_root, LogRoot]),
ct_rpc:call(Miner, application, set_env, [lager, metadata_whitelist, [poc_id]]),
%% set blockchain configuration
Key =
case proplists:get_value(default_keys, Options) of
true -> undefined;
false -> #{pubkey => PubKey, ecdh_fun => ECDH, sig_fun => SigFun}
end,
MinerBaseDir = BaseDir ++ "_" ++ atom_to_list(Miner),
ct:pal("MinerBaseDir: ~p", [MinerBaseDir]),
%% set blockchain env
ct_rpc:call(Miner, application, set_env, [blockchain, enable_nat, false]),
ct_rpc:call(Miner, application, set_env, [blockchain, base_dir, MinerBaseDir]),
ct_rpc:call(Miner, application, set_env, [blockchain, port, Port]),
ct_rpc:call(Miner, application, set_env, [blockchain, seed_nodes, SeedNodes]),
ct_rpc:call(Miner, application, set_env, [blockchain, key, Key]),
ct_rpc:call(Miner, application, set_env, [blockchain, peer_cache_timeout, 30000]),
ct_rpc:call(Miner, application, set_env, [blockchain, peerbook_update_interval, 200]),
ct_rpc:call(Miner, application, set_env, [blockchain, peerbook_allow_rfc1918, true]),
ct_rpc:call(Miner, application, set_env, [blockchain, disable_poc_v4_target_challenge_age, true]),
ct_rpc:call(Miner, application, set_env, [blockchain, max_inbound_connections, TotalMiners*2]),
ct_rpc:call(Miner, application, set_env, [blockchain, outbound_gossip_connections, TotalMiners]),
ct_rpc:call(Miner, application, set_env, [blockchain, sync_cooldown_time, 5]),
ct_rpc:call(Miner, application, set_env, [blockchain, sc_packet_handler, miner_test_sc_packet_handler]),
%% set miner configuration
ct_rpc:call(Miner, application, set_env, [miner, curve, Curve]),
ct_rpc:call(Miner, application, set_env, [miner, gateway_api_port, GwApiPort]),
ct_rpc:call(Miner, application, set_env, [miner, jsonrpc_port, JSONRPCPort]),
ct_rpc:call(Miner, application, set_env, [miner, mode, Mode]),
ct_rpc:call(Miner, application, set_env, [miner, gateway_and_mux_enable, GwMuxEnable]),
ct_rpc:call(Miner, application, set_env, [miner, gateways_run_chain, LoadChainOnGateways]),
ct_rpc:call(Miner, application, set_env, [miner, radio_device, {{127,0,0,1}, UDPPort, deprecated, deprecated}]),
ct_rpc:call(Miner, application, set_env, [miner, stabilization_period_start, 2]),
ct_rpc:call(Miner, application, set_env, [miner, default_routers, [DefaultRouters]]),
case Mod of
miner_poc_v11_SUITE ->
Do n't set anything region related with poc - v11
ok;
_ ->
ct_rpc:call(Miner, application, set_env, [miner, region_override, 'US915']),
ct_rpc:call(Miner, application, set_env,
[miner, frequency_data,
#{'US915' => [903.9, 904.1, 904.3, 904.5, 904.7, 904.9, 905.1, 905.3],
'EU868' => [867.1, 867.3, 867.5, 867.7, 867.9, 868.1, 868.3, 868.5],
'EU433' => [433.175, 433.375, 433.575],
'CN470' => [486.3, 486.5, 486.7, 486.9, 487.1, 487.3, 487.5, 487.7 ],
'CN779' => [779.5, 779.7, 779.9],
'AU915' => [916.8, 917.0, 917.2, 917.4, 917.5, 917.6, 917.8, 918.0, 918.2],
'AS923_1' => [923.2, 923.4, 923.6, 923.8, 924.0, 924.2, 924.4, 924.6],
'AS923_1B' => [922.0, 922.2, 922.4, 922.6, 922.8, 923.0, 923.2, 923.4],
'AS923_2' => [921.4, 921.6, 921.8, 922.0, 922.2, 922.4, 922.6, 922.8],
'AS923_3' => [916.6, 916.8, 917.0, 917.2, 917.4, 917.6, 917.8, 918.0],
'AS923_4' => [917.3, 917.5, 917.7, 917.9, 918.1, 918.3, 918.5, 918.7],
'KR920' => [922.1, 922.3, 922.5, 922.7, 922.9, 923.1, 923.3],
'IN865' => [865.0625, 865.4025, 865.985]}])
end,
{ok, _StartedApps} = ct_rpc:call(Miner, application, ensure_all_started, [miner]),
ok.
end_per_testcase(TestCase, Config) ->
Miners = ?config(miners, Config),
miner_ct_utils:pmap(fun(Miner) -> ct_slave:stop(Miner) end, Miners),
case ?config(tc_status, Config) of
ok ->
%% test passed, we can cleanup
%% cleanup_per_testcase(TestCase, Config),
ok;
_ ->
%% leave results alone for analysis
ok
end,
{comment, done}.
cleanup_per_testcase(_TestCase, Config) ->
Miners = ?config(miners, Config),
BaseDir = ?config(base_dir, Config),
LogDir = ?config(log_dir, Config),
lists:foreach(fun(Miner) ->
LogRoot = LogDir ++ "_" ++ atom_to_list(Miner),
Res = os:cmd("rm -rf " ++ LogRoot),
ct:pal("rm -rf ~p -> ~p", [LogRoot, Res]),
DataDir = BaseDir ++ "_" ++ atom_to_list(Miner),
Res2 = os:cmd("rm -rf " ++ DataDir),
ct:pal("rm -rf ~p -> ~p", [DataDir, Res2]),
ok
end, Miners).
get_gw_owner(Miner, GwAddr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_gateway_info,
[GwAddr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, GwInfo} ->
ct_rpc:call(Miner, blockchain_ledger_gateway_v2, owner_address,
[GwInfo])
end
end
end.
get_balance(Miner, Addr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_entry, [Addr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, Entry} ->
ct_rpc:call(Miner, blockchain_ledger_entry_v1, balance, [Entry])
end
end
end.
get_nonce(Miner, Addr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_entry, [Addr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, Entry} ->
ct_rpc:call(Miner, blockchain_ledger_entry_v1, nonce, [Entry])
end
end
end.
get_dc_balance(Miner, Addr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_dc_entry, [Addr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, Entry} ->
ct_rpc:call(Miner, blockchain_ledger_data_credits_entry_v1, balance, [Entry])
end
end
end.
get_dc_nonce(Miner, Addr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_dc_entry, [Addr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, Entry} ->
ct_rpc:call(Miner, blockchain_ledger_data_credits_entry_v1, nonce, [Entry])
end
end
end.
get_block(Block, Miner) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, get_block, [Block, Chain]) of
{badrpc, Error} ->
Error;
{ok, BlockRec} ->
BlockRec
end
end.
make_vars(Keys) ->
make_vars(Keys, #{}).
make_vars(Keys, Map) ->
make_vars(Keys, Map, modern).
make_vars(Keys, Map, Mode) ->
Vars1 = #{?chain_vars_version => 2,
?block_time => 2,
?election_interval => 30,
?election_restart_interval => 10,
?num_consensus_members => 7,
?batch_size => 2500,
?vars_commit_delay => 1,
?var_gw_inactivity_threshold => 20,
?block_version => v1,
?dkg_curve => 'SS512',
?predicate_callback_mod => miner,
?predicate_callback_fun => test_version,
?predicate_threshold => 0.60,
?monthly_reward => 5000000 * 1000000,
?securities_percent => 0.35,
?dc_percent => 0.0,
?poc_challengees_percent => 0.19 + 0.16,
?poc_challengers_percent => 0.09 + 0.06,
?poc_witnesses_percent => 0.02 + 0.03,
?consensus_percent => 0.10,
?election_version => 5,
?election_bba_penalty => 0.01,
?election_seen_penalty => 0.05,
?election_cluster_res => 8,
?election_removal_pct => 85,
?election_selection_pct => 60,
?election_replacement_factor => 4,
?election_replacement_slope => 20,
?min_score => 0.2,
?alpha_decay => 0.007,
?beta_decay => 0.0005,
?max_staleness => 100000,
?min_assert_h3_res => 12,
?h3_neighbor_res => 12,
?h3_max_grid_distance => 13,
?h3_exclusion_ring_dist => 2,
?poc_challenge_interval => 10,
?poc_version => 3,
?poc_path_limit => 7,
?poc_typo_fixes => true,
?sc_grace_blocks => 4,
?validator_version => 2,
?validator_minimum_stake => ?bones(10000),
?validator_liveness_grace_period => 10,
?validator_liveness_interval => 5,
?stake_withdrawal_cooldown => 55,
?dkg_penalty => 1.0,
?tenure_penalty => 1.0,
?validator_penalty_filter => 5.0,
?penalty_history_limit => 100
},
#{secret := Priv, public := Pub} = Keys,
BinPub = libp2p_crypto:pubkey_to_bin(Pub),
Vars = maps:merge(Vars1, Map),
case Mode of
modern ->
Txn = blockchain_txn_vars_v1:new(Vars, 1, #{master_key => BinPub}),
Proof = blockchain_txn_vars_v1:create_proof(Priv, Txn),
[blockchain_txn_vars_v1:key_proof(Txn, Proof)];
%% in legacy mode, we have to do without some stuff
%% because everything will break if there are too many vars
legacy ->
%% ideally figure out a few more that are safe to
%% remove or bring back the splitting code
LegVars = maps:without([?poc_version, ?poc_path_limit, ?sc_grace_blocks,
?election_version, ?election_removal_pct, ?election_cluster_res,
?chain_vars_version, ?block_version, ?election_bba_penalty,
?election_seen_penalty, ?sc_grace_blocks, ?validator_minimum_stake,
?validator_liveness_grace_period, ?validator_liveness_interval,
?poc_typo_fixes, ?election_bba_penalty, ?election_seen_penalty,
?election_cluster_res, ?stake_withdrawal_cooldown,
?validator_penalty_filter
],
Vars),
Proof = blockchain_txn_vars_v1:legacy_create_proof(Priv, LegVars),
Txn = blockchain_txn_vars_v1:new(LegVars, 1, #{master_key => BinPub,
key_proof => Proof}),
[Txn]
end.
nonl([$\n|T]) -> nonl(T);
nonl([H|T]) -> [H|nonl(T)];
nonl([]) -> [].
generate_keys(N) ->
lists:foldl(
fun(_, Acc) ->
{PrivKey, PubKey} = new_random_key(ecc_compact),
SigFun = libp2p_crypto:mk_sig_fun(PrivKey),
[{libp2p_crypto:pubkey_to_bin(PubKey), {PubKey, PrivKey, SigFun}}|Acc]
end,
[],
lists:seq(1, N)
).
new_random_key(Curve) ->
#{secret := PrivKey, public := PubKey} = libp2p_crypto:generate_keys(Curve),
{PrivKey, PubKey}.
new_random_key_with_sig_fun(Curve) ->
#{secret := PrivKey, public := PubKey} = libp2p_crypto:generate_keys(Curve),
SigFun = libp2p_crypto:mk_sig_fun(PrivKey),
{PrivKey, PubKey, SigFun}.
%%--------------------------------------------------------------------
%% @doc
%% generate a tmp directory to be used as a scratch by eunit tests
%% @end
%%-------------------------------------------------------------------
tmp_dir() ->
os:cmd("mkdir -p " ++ ?BASE_TMP_DIR),
create_tmp_dir(?BASE_TMP_DIR_TEMPLATE).
tmp_dir(SubDir) ->
Path = filename:join(?BASE_TMP_DIR, SubDir),
os:cmd("mkdir -p " ++ Path),
create_tmp_dir(Path ++ "/" ++ ?BASE_TMP_DIR_TEMPLATE).
%%--------------------------------------------------------------------
%% @doc
%% Deletes the specified directory
%% @end
%%-------------------------------------------------------------------
-spec cleanup_tmp_dir(list()) -> ok.
cleanup_tmp_dir(Dir)->
os:cmd("rm -rf " ++ Dir),
ok.
%%--------------------------------------------------------------------
%% @doc
%% create a tmp directory at the specified path
%% @end
%%-------------------------------------------------------------------
-spec create_tmp_dir(list()) -> list().
create_tmp_dir(Path)->
?MODULE:nonl(os:cmd("mktemp -d " ++ Path)).
%%--------------------------------------------------------------------
%% @doc
generate a tmp directory based off priv_dir to be used as a scratch by common tests
%% @end
%%-------------------------------------------------------------------
-spec init_base_dir_config(atom(), atom(), Config) -> Config when
Config :: ct_suite:ct_config().
init_base_dir_config(Mod, TestCase, Config)->
PrivDir = ?config(priv_dir, Config),
BaseDir = PrivDir ++ "data/" ++ erlang:atom_to_list(Mod) ++ "_" ++ erlang:atom_to_list(TestCase),
LogDir = PrivDir ++ "logs/" ++ erlang:atom_to_list(Mod) ++ "_" ++ erlang:atom_to_list(TestCase),
[
{base_dir, BaseDir},
{log_dir, LogDir}
| Config
].
%%--------------------------------------------------------------------
%% @doc
%% Wait for a txn to occur.
%%
%% Examples:
%%
CheckType = fun(T ) - > blockchain_txn : type(T ) = = SomeTxnType end ,
wait_for_txn(Miners , CheckType )
%%
CheckTxn = fun(T ) - > T = = SomeSignedTxn end ,
%% wait_for_txn(Miners, CheckTxn)
%%
%% @end
%%-------------------------------------------------------------------
wait_for_txn(Miners, PredFun) ->
wait_for_txn(Miners, PredFun, timer:seconds(30), true).
wait_for_txn(Miners, PredFun, Timeout) ->
wait_for_txn(Miners, PredFun, Timeout, true).
wait_for_txn(Miners, PredFun, Timeout, ExpectedResult)->
timeout is in ms , we want to retry every 200
Count = Timeout div 200,
?assertAsync(begin
Result = lists:all(
fun(Miner) ->
Res = get_txn_block_details(Miner, PredFun, 500),
Res /= []
end, miner_ct_utils:shuffle(Miners))
end,
Result == ExpectedResult, Count, 200),
ok.
format_txn_mgr_list(TxnList) ->
maps:fold(fun(Txn, TxnData, Acc) ->
TxnMod = blockchain_txn:type(Txn),
TxnHash = blockchain_txn:hash(Txn),
Acceptions = proplists:get_value(acceptions, TxnData, []),
Rejections = proplists:get_value(rejections, TxnData, []),
RecvBlockHeight = proplists:get_value(recv_block_height, TxnData, undefined),
Dialers = proplists:get_value(dialers, TxnData, undefined),
[
[{txn_type, atom_to_list(TxnMod)},
{txn_hash, io_lib:format("~p", [libp2p_crypto:bin_to_b58(TxnHash)])},
{acceptions, length(Acceptions)},
{rejections, length(Rejections)},
{accepted_block_height, RecvBlockHeight},
{active_dialers, length(Dialers)}]
| Acc]
end, [], TxnList).
get_txn_block_details(Miner, PredFun) ->
get_txn_block_details(Miner, PredFun, timer:seconds(5)).
get_txn_block_details(Miner, PredFun, Timeout) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, [], Timeout) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, blocks, [Chain], Timeout) of
{badrpc, Error} ->
Error;
Blocks ->
lists:filter(fun({_Hash, Block}) ->
BH = blockchain_block : height(Block ) ,
Txns = blockchain_block:transactions(Block),
ToFind = lists:filter(fun(T) ->
PredFun(T)
end,
Txns),
%% ct:pal("BlockHeight: ~p, ToFind: ~p", [BH, ToFind]),
ToFind /= []
end,
maps:to_list(Blocks))
end
end.
get_txn([{_, B}], PredFun) ->
hd(lists:filter(fun(T) ->
PredFun(T)
end,
blockchain_block:transactions(B))).
get_txns(Blocks, PredFun) when is_map(Blocks) ->
lists:foldl(fun({_, B}, Acc) ->
Acc ++ lists:filter(fun(T) -> PredFun(T) end,
blockchain_block:transactions(B))
end, [], maps:to_list(Blocks)).
%% ------------------------------------------------------------------
%% Local Helper functions
%% ------------------------------------------------------------------
handle_get_consensus_miners(Miner)->
try
Blockchain = ct_rpc:call(Miner, blockchain_worker, blockchain, [], 2000),
Ledger = ct_rpc:call(Miner, blockchain, ledger, [Blockchain], 2000),
{ok, Members} = ct_rpc:call(Miner, blockchain_ledger_v1, consensus_members, [Ledger], 2000),
{ok, Members}
catch
_:_ -> {error, miner_down}
end.
handle_miners_by_consensus(Mod, Bool, Miners)->
lists:Mod(
fun(Miner) ->
Bool == ct_rpc:call(Miner, miner_consensus_mgr, in_consensus, [])
end, Miners).
handle_gte_type(height, Miner, Threshold)->
C0 = ct_rpc:call(Miner, blockchain_worker, blockchain, [], 2000),
{ok, Height} = ct_rpc:call(Miner, blockchain, height, [C0], 2000),
case Height >= Threshold of
false ->
ct:pal("miner ~p height ~p Threshold ~p", [Miner, Height, Threshold]),
false;
true ->
true
end;
handle_gte_type(epoch, Miner, Threshold)->
{Height, _, Epoch} = ct_rpc:call(Miner, miner_cli_info, get_info, [], 2000),
ct:pal("miner ~p Height ~p Epoch ~p Threshold ~p", [Miner, Height, Epoch, Threshold]),
Epoch >= Threshold;
handle_gte_type(height_exactly, Miner, Threshold)->
C = ct_rpc:call(Miner, blockchain_worker, blockchain, []),
{ok, Ht} = ct_rpc:call(Miner, blockchain, height, [C]),
ct:pal("miner ~p height ~p Exact Threshold ~p", [Miner, Ht, Threshold]),
Ht == Threshold.
get_genesis_block(Miners, Config) ->
RPCTimeout = ?config(rpc_timeout, Config),
ct:pal("RPCTimeout: ~p", [RPCTimeout]),
%% obtain the genesis block
GenesisBlock = get_genesis_block_(Miners, RPCTimeout),
?assertNotEqual(undefined, GenesisBlock),
GenesisBlock.
get_genesis_block_([Miner|Miners], RPCTimeout) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, [], RPCTimeout) of
{badrpc, Reason} ->
ct:fail(Reason),
get_genesis_block_(Miners ++ [Miner], RPCTimeout);
undefined ->
get_genesis_block_(Miners ++ [Miner], RPCTimeout);
Chain ->
{ok, GBlock} = rpc:call(Miner, blockchain, genesis_block, [Chain], RPCTimeout),
GBlock
end.
load_genesis_block(GenesisBlock, Miners, Config) ->
RPCTimeout = ?config(rpc_timeout, Config),
%% load the genesis block on all the nodes
lists:foreach(
fun(Miner) ->
%% wait for the consensus manager to be booted
true = miner_ct_utils:wait_until(
fun() ->
is_boolean(ct_rpc:call(Miner, miner_consensus_mgr, in_consensus, [], RPCTimeout))
end),
case ct_rpc:call(Miner, miner_consensus_mgr, in_consensus, [], RPCTimeout) of
true ->
ok;
false ->
Res = ct_rpc:call(Miner, blockchain_worker,
integrate_genesis_block, [GenesisBlock], RPCTimeout),
ct:pal("loading genesis ~p block on ~p ~p", [GenesisBlock, Miner, Res]);
{badrpc, Reason} ->
ct:pal("failed to load genesis block on ~p: ~p", [Miner, Reason])
end
end,
Miners
),
ok = miner_ct_utils:wait_for_gte(height, Miners, 1, all, 30).
build_gateways(LatLongs, {PrivKey, PubKey}) ->
lists:foldl(
fun({_LatLong, {GatewayPrivKey, GatewayPubKey}}, Acc) ->
% Create a Gateway
Gateway = libp2p_crypto:pubkey_to_bin(GatewayPubKey),
GatewaySigFun = libp2p_crypto:mk_sig_fun(GatewayPrivKey),
OwnerSigFun = libp2p_crypto:mk_sig_fun(PrivKey),
Owner = libp2p_crypto:pubkey_to_bin(PubKey),
AddGatewayTx = blockchain_txn_add_gateway_v1:new(Owner, Gateway),
SignedOwnerAddGatewayTx = blockchain_txn_add_gateway_v1:sign(AddGatewayTx, OwnerSigFun),
SignedGatewayAddGatewayTx = blockchain_txn_add_gateway_v1:sign_request(SignedOwnerAddGatewayTx, GatewaySigFun),
[SignedGatewayAddGatewayTx|Acc]
end,
[],
LatLongs
).
build_asserts(LatLongs, {PrivKey, PubKey}) ->
lists:foldl(
fun({LatLong, {GatewayPrivKey, GatewayPubKey}}, Acc) ->
Gateway = libp2p_crypto:pubkey_to_bin(GatewayPubKey),
GatewaySigFun = libp2p_crypto:mk_sig_fun(GatewayPrivKey),
OwnerSigFun = libp2p_crypto:mk_sig_fun(PrivKey),
Owner = libp2p_crypto:pubkey_to_bin(PubKey),
Index = h3:from_geo(LatLong, 12),
AssertLocationRequestTx = blockchain_txn_assert_location_v1:new(Gateway, Owner, Index, 1),
PartialAssertLocationTxn = blockchain_txn_assert_location_v1:sign_request(AssertLocationRequestTx, GatewaySigFun),
SignedAssertLocationTx = blockchain_txn_assert_location_v1:sign(PartialAssertLocationTxn, OwnerSigFun),
[SignedAssertLocationTx|Acc]
end,
[],
LatLongs
).
add_block(Chain, ConsensusMembers, Txns) ->
SortedTxns = lists:sort(fun blockchain_txn:sort/2, Txns),
B = create_block(ConsensusMembers, SortedTxns),
ok = blockchain:add_block(B, Chain).
create_block(ConsensusMembers, Txs) ->
Blockchain = blockchain_worker:blockchain(),
{ok, PrevHash} = blockchain:head_hash(Blockchain),
{ok, HeadBlock} = blockchain:head_block(Blockchain),
Height = blockchain_block:height(HeadBlock) + 1,
Block0 = blockchain_block_v1:new(#{prev_hash => PrevHash,
height => Height,
transactions => Txs,
signatures => [],
time => 0,
hbbft_round => 0,
election_epoch => 1,
epoch_start => 1,
seen_votes => [],
bba_completion => <<>>,
poc_keys => []}),
BinBlock = blockchain_block:serialize(blockchain_block:set_signatures(Block0, [])),
Signatures = signatures(ConsensusMembers, BinBlock),
Block1 = blockchain_block:set_signatures(Block0, Signatures),
Block1.
signatures(ConsensusMembers, BinBlock) ->
lists:foldl(
fun({A, {_, _, F}}, Acc) ->
Sig = F(BinBlock),
[{A, Sig}|Acc]
end
,[]
,ConsensusMembers
).
gen_gateways(Addresses, Locations) ->
[blockchain_txn_gen_gateway_v1:new(Addr, Addr, Loc, 0)
|| {Addr, Loc} <- lists:zip(Addresses, Locations)].
gen_payments(Addresses) ->
[ blockchain_txn_coinbase_v1:new(Addr, 5000)
|| Addr <- Addresses].
%% ideally keep these synced with mainnet
existing_vars() ->
#{
?allow_payment_v2_memos => true,
?allow_zero_amount => false,
?alpha_decay => 0.0035,
?assert_loc_txn_version => 2,
?batch_size => 400,
?beta_decay => 0.002,
?block_time => 60000,
?block_version => v1,
?chain_vars_version => 2,
?consensus_percent => 0.06,
?data_aggregation_version => 2,
?dc_payload_size => 24,
?dc_percent => 0.325,
?density_tgt_res => 4,
?dkg_curve => 'SS512',
?election_bba_penalty => 0.001,
?election_cluster_res => 4,
?election_interval => 30,
?election_removal_pct => 40,
?election_replacement_factor => 4,
?election_replacement_slope => 20,
?election_restart_interval => 5,
?election_seen_penalty => 0.0033333,
?election_selection_pct => 1,
?election_version => 4,
?h3_exclusion_ring_dist => 6,
?h3_max_grid_distance => 120,
?h3_neighbor_res => 12,
?hip17_interactivity_blocks => 3600,
?hip17_res_0 => <<"2,100000,100000">>,
?hip17_res_1 => <<"2,100000,100000">>,
?hip17_res_10 => <<"2,1,1">>,
?hip17_res_11 => <<"2,100000,100000">>,
?hip17_res_12 => <<"2,100000,100000">>,
?hip17_res_2 => <<"2,100000,100000">>,
?hip17_res_3 => <<"2,100000,100000">>,
?hip17_res_4 => <<"1,250,800">>,
?hip17_res_5 => <<"1,100,400">>,
?hip17_res_6 => <<"1,25,100">>,
?hip17_res_7 => <<"2,5,20">>,
?hip17_res_8 => <<"2,1,4">>,
?hip17_res_9 => <<"2,1,2">>,
?max_antenna_gain => 150,
?max_open_sc => 5,
?max_payments => 50,
?max_staleness => 100000,
?max_subnet_num => 5,
?max_subnet_size => 65536,
?max_xor_filter_num => 5,
?max_xor_filter_size => 102400,
?min_antenna_gain => 10,
?min_assert_h3_res => 12,
?min_expire_within => 15,
?min_score => 0.15,
?min_subnet_size => 8,
?monthly_reward => 500000000000000,
?num_consensus_members => 16,
?poc_addr_hash_byte_count => 8,
?poc_centrality_wt => 0.5,
?poc_challenge_interval => 480,
?poc_challenge_sync_interval => 90,
?poc_challengees_percent => 0.0531,
?poc_challengers_percent => 0.0095,
?poc_good_bucket_high => -70,
?poc_good_bucket_low => -130,
?poc_max_hop_cells => 2000,
?poc_path_limit => 1,
?poc_per_hop_max_witnesses => 25,
?poc_reward_decay_rate => 0.8,
?poc_target_hex_parent_res => 5,
?poc_typo_fixes => true,
?poc_v4_exclusion_cells => 8,
?poc_v4_parent_res => 11,
?poc_v4_prob_bad_rssi => 0.01,
?poc_v4_prob_count_wt => 0.0,
?poc_v4_prob_good_rssi => 1.0,
?poc_v4_prob_no_rssi => 0.5,
?poc_v4_prob_rssi_wt => 0.0,
?poc_v4_prob_time_wt => 0.0,
?poc_v4_randomness_wt => 0.5,
?poc_v4_target_challenge_age => 1000,
?poc_v4_target_exclusion_cells => 6000,
?poc_v4_target_prob_edge_wt => 0.0,
?poc_v4_target_prob_score_wt => 0.0,
?poc_v4_target_score_curve => 5,
?poc_v5_target_prob_randomness_wt => 1.0,
?poc_version => 10,
?poc_witness_consideration_limit => 20,
?poc_witnesses_percent => 0.2124,
?predicate_callback_fun => version,
?predicate_callback_mod => miner,
?predicate_threshold => 0.95,
?price_oracle_height_delta => 10,
?price_oracle_price_scan_delay => 3600,
?price_oracle_price_scan_max => 90000,
?price_oracle_public_keys =>
<<33, 1, 32, 30, 226, 70, 15, 7, 0, 161, 150, 108, 195, 90, 205, 113, 146, 41, 110, 194,
43, 86, 168, 161, 93, 241, 68, 41, 125, 160, 229, 130, 205, 140, 33, 1, 32, 237, 78,
201, 132, 45, 19, 192, 62, 81, 209, 208, 156, 103, 224, 137, 51, 193, 160, 15, 96,
238, 160, 42, 235, 174, 99, 128, 199, 20, 154, 222, 33, 1, 143, 166, 65, 105, 75,
56, 206, 157, 86, 46, 225, 174, 232, 27, 183, 145, 248, 50, 141, 210, 144, 155, 254,
80, 225, 240, 164, 164, 213, 12, 146, 100, 33, 1, 20, 131, 51, 235, 13, 175, 124,
98, 154, 135, 90, 196, 83, 14, 118, 223, 189, 221, 154, 181, 62, 105, 183, 135, 121,
105, 101, 51, 163, 119, 206, 132, 33, 1, 254, 129, 70, 123, 51, 101, 208, 224, 99,
172, 62, 126, 252, 59, 130, 84, 93, 231, 214, 248, 207, 139, 84, 158, 120, 232, 6,
8, 121, 243, 25, 205, 33, 1, 148, 214, 252, 181, 1, 33, 200, 69, 148, 146, 34, 29,
22, 91, 108, 16, 18, 33, 45, 0, 210, 100, 253, 211, 177, 78, 82, 113, 122, 149, 47,
240, 33, 1, 170, 219, 208, 73, 156, 141, 219, 148, 7, 148, 253, 209, 66, 48, 218,
91, 71, 232, 244, 198, 253, 236, 40, 201, 90, 112, 61, 236, 156, 69, 235, 109, 33,
1, 154, 235, 195, 88, 165, 97, 21, 203, 1, 161, 96, 71, 236, 193, 188, 50, 185, 214,
15, 14, 86, 61, 245, 131, 110, 22, 150, 8, 48, 174, 104, 66, 33, 1, 254, 248, 78,
138, 218, 174, 201, 86, 100, 210, 209, 229, 149, 130, 203, 83, 149, 204, 154, 58,
32, 192, 118, 144, 129, 178, 83, 253, 8, 199, 161, 128>>,
?price_oracle_refresh_interval => 10,
?reward_version => 5,
?rewards_txn_version => 2,
?sc_causality_fix => 1,
?sc_gc_interval => 10,
?sc_grace_blocks => 10,
?sc_open_validation_bugfix => 1,
?sc_overcommit => 2,
?sc_version => 2,
?securities_percent => 0.34,
?snapshot_interval => 720,
?snapshot_version => 1,
?stake_withdrawal_cooldown => 250000,
?stake_withdrawal_max => 60,
?staking_fee_txn_add_gateway_v1 => 4000000,
?staking_fee_txn_assert_location_v1 => 1000000,
?staking_fee_txn_oui_v1 => 10000000,
?staking_fee_txn_oui_v1_per_address => 10000000,
?staking_keys =>
<<33, 1, 37, 193, 104, 249, 129, 155, 16, 116, 103, 223, 160, 89, 196, 199, 11, 94, 109,
49, 204, 84, 242, 3, 141, 250, 172, 153, 4, 226, 99, 215, 122, 202, 33, 1, 90, 111,
210, 126, 196, 168, 67, 148, 63, 188, 231, 78, 255, 150, 151, 91, 237, 189, 148, 99,
248, 41, 4, 103, 140, 225, 49, 117, 68, 212, 132, 113, 33, 1, 81, 215, 107, 13, 100,
54, 92, 182, 84, 235, 120, 236, 201, 115, 77, 249, 2, 33, 68, 206, 129, 109, 248,
58, 188, 53, 45, 34, 109, 251, 217, 130, 33, 1, 251, 174, 74, 242, 43, 25, 156, 188,
167, 30, 41, 145, 14, 91, 0, 202, 115, 173, 26, 162, 174, 205, 45, 244, 46, 171,
200, 191, 85, 222, 98, 120, 33, 1, 253, 88, 22, 88, 46, 94, 130, 1, 58, 115, 46,
153, 194, 91, 1, 57, 194, 165, 181, 225, 251, 12, 13, 104, 171, 131, 151, 164, 83,
113, 147, 216, 33, 1, 6, 76, 109, 192, 213, 45, 64, 27, 225, 251, 102, 247, 132, 42,
154, 145, 70, 61, 127, 106, 188, 70, 87, 23, 13, 91, 43, 28, 70, 197, 41, 91, 33, 1,
53, 200, 215, 84, 164, 84, 136, 102, 97, 157, 211, 75, 206, 229, 73, 177, 83, 153,
199, 255, 43, 180, 114, 30, 253, 206, 245, 194, 79, 156, 218, 193, 33, 1, 229, 253,
194, 42, 80, 229, 8, 183, 20, 35, 52, 137, 60, 18, 191, 28, 127, 218, 234, 118, 173,
23, 91, 129, 251, 16, 39, 223, 252, 71, 165, 120, 33, 1, 54, 171, 198, 219, 118,
150, 6, 150, 227, 80, 208, 92, 252, 28, 183, 217, 134, 4, 217, 2, 166, 9, 57, 106,
38, 182, 158, 255, 19, 16, 239, 147, 33, 1, 51, 170, 177, 11, 57, 0, 18, 245, 73,
13, 235, 147, 51, 37, 187, 248, 125, 197, 173, 25, 11, 36, 187, 66, 9, 240, 61, 104,
28, 102, 194, 66, 33, 1, 187, 46, 236, 46, 25, 214, 204, 51, 20, 191, 86, 116, 0,
174, 4, 247, 132, 145, 22, 83, 66, 159, 78, 13, 54, 52, 251, 8, 143, 59, 191, 196>>,
?transfer_hotspot_stale_poc_blocks => 1200,
?txn_fee_multiplier => 5000,
?txn_fees => true,
?validator_liveness_grace_period => 50,
?validator_liveness_interval => 100,
?validator_minimum_stake => 1000000000000,
?validator_version => 1,
?var_gw_inactivity_threshold => 600,
?vars_commit_delay => 1,
?witness_redundancy => 4,
?witness_refresh_interval => 200,
?witness_refresh_rand_n => 1000
}.
gen_locations(Addresses) ->
lists:foldl(
fun(I, Acc) ->
[h3:from_geo({37.780586, -122.469470 + I / 50}, 13) | Acc]
end,
[],
lists:seq(1, length(Addresses))
).
start_blockchain(Config, GenesisVars) ->
Miners = ?config(miners, Config),
Addresses = ?config(addresses, Config),
Curve = ?config(dkg_curve, Config),
NumConsensusMembers = ?config(num_consensus_members, Config),
#{secret := Priv, public := Pub} =
Keys =
libp2p_crypto:generate_keys(ecc_compact),
InitialVars = make_vars(Keys, GenesisVars),
InitialPayments = gen_payments(Addresses),
Locations = gen_locations(Addresses),
InitialGws = gen_gateways(Addresses, Locations),
Txns = InitialVars ++ InitialPayments ++ InitialGws,
{ok, DKGCompletedNodes} = initial_dkg(
Miners,
Txns,
Addresses,
NumConsensusMembers,
Curve
),
%% integrate genesis block
_GenesisLoadResults = integrate_genesis_block(
hd(DKGCompletedNodes),
Miners -- DKGCompletedNodes
),
{ConsensusMiners, NonConsensusMiners} = miners_by_consensus_state(Miners),
ct:pal("ConsensusMiners: ~p, NonConsensusMiners: ~p", [ConsensusMiners, NonConsensusMiners]),
MinerHts = pmap(
fun(M) ->
Ch = ct_rpc:call(M, blockchain_worker, blockchain, [], 2000),
{ok, Ht} = ct_rpc:call(M, blockchain, height, [Ch], 2000),
{M, Ht}
end, Miners),
%% check that all miners are booted and have genesis block
true = lists:all(
fun({_, Ht}) ->
Ht == 1
end,
MinerHts),
[
{master_key, {Priv, Pub}},
{consensus_miners, ConsensusMiners},
{non_consensus_miners, NonConsensusMiners}
| Config
].
| null | https://raw.githubusercontent.com/helium/miner/f6ce13a0ee90794086fb932b80d28e2bb2bd1b32/test/miner_ct_utils.erl | erlang | TODO - do we need to assert here on results from genesis load ?
badrpc
back compat
have the slave nodes monitor the runner node, so they can't outlive it
kill any nodes we started and throw error
config nodes
split key sets into validators and miners
set the app env var appropiately on each node
get a sep list of validator and gateway node names
check that the config loaded correctly on each miner
hardcode some alias for our localhost miners
sibyl will not return routing data unless a miner/validator has a public address
so force an alias for each of our miners to a public IP
make sure each node is gossiping with a majority of its peers
to enable the tests to run over grpc we need to deterministically set the grpc listen addr
in the real world we would run grpc over a known port
but for the sake of the tests which run multiple nodes on a single instance
we need to choose a random port for each node
and the client needs to know which port was choosen
and run grpc on that value + 1000
setup a bunch of aliases for the running miner grpc hosts
these grpc aliases are added purely for testing purposes
no current need to support in the wild
use this list to set an app env var to provide a list of default validators to which
gateways can connect
only used when testing grpc gateways
set any required env vars for validators
accumulate the address of each miner
save a version of the address list with the miner and address tuple
and then a version with just a list of addresses
wait until we get confirmation the miners are fully up
which we are determining by the miner_consensus_mgr being registered
if we have a split of validators and gateways, we only need to wait on the validators
otherwise wait for all gateways
get a sep list of ports for validators and gateways
give each miner its own log directory
set blockchain configuration
set blockchain env
set miner configuration
test passed, we can cleanup
cleanup_per_testcase(TestCase, Config),
leave results alone for analysis
in legacy mode, we have to do without some stuff
because everything will break if there are too many vars
ideally figure out a few more that are safe to
remove or bring back the splitting code
--------------------------------------------------------------------
@doc
generate a tmp directory to be used as a scratch by eunit tests
@end
-------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Deletes the specified directory
@end
-------------------------------------------------------------------
--------------------------------------------------------------------
@doc
create a tmp directory at the specified path
@end
-------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Wait for a txn to occur.
Examples:
wait_for_txn(Miners, CheckTxn)
@end
-------------------------------------------------------------------
ct:pal("BlockHeight: ~p, ToFind: ~p", [BH, ToFind]),
------------------------------------------------------------------
Local Helper functions
------------------------------------------------------------------
obtain the genesis block
load the genesis block on all the nodes
wait for the consensus manager to be booted
Create a Gateway
ideally keep these synced with mainnet
integrate genesis block
check that all miners are booted and have genesis block | -module(miner_ct_utils).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("blockchain/include/blockchain_vars.hrl").
-include_lib("blockchain/include/blockchain.hrl").
-include_lib("blockchain/include/blockchain_txn_fees.hrl").
-include("miner_ct_macros.hrl").
-define(BASE_TMP_DIR, "./_build/test/tmp").
-define(BASE_TMP_DIR_TEMPLATE, "XXXXXXXXXX").
-export([
init_per_testcase/3,
end_per_testcase/2,
pmap/2, pmap/3,
wait_until/1, wait_until/3,
wait_until_disconnected/2,
wait_until_local_height/1,
get_addrs/1,
start_miner/2,
start_node/1,
partition_cluster/2,
heal_cluster/2,
connect/1,
count/2,
randname/1,
get_config/2,
get_gw_owner/2,
get_balance/2,
get_nonce/2,
get_dc_balance/2,
get_dc_nonce/2,
get_block/2,
make_vars/1, make_vars/2, make_vars/3,
tmp_dir/0, tmp_dir/1, nonl/1,
cleanup_tmp_dir/1,
init_base_dir_config/3,
generate_keys/1,
new_random_key/1,
new_random_key_with_sig_fun/1,
stop_miners/1, stop_miners/2,
start_miners/1, start_miners/2,
height/1,
heights/1,
unique_heights/1,
consensus_members/1, consensus_members/2,
miners_by_consensus_state/1,
in_consensus_miners/1,
non_consensus_miners/1,
election_check/4,
integrate_genesis_block/2,
shuffle/1,
partition_miners/2,
node2addr/2,
node2sigfun/2,
node2pubkeybin/2,
addr2node/2,
addr_list/1,
blockchain_worker_check/1,
wait_for_registration/2, wait_for_registration/3,
wait_for_app_start/2, wait_for_app_start/3,
wait_for_app_stop/2, wait_for_app_stop/3,
wait_for_in_consensus/2, wait_for_in_consensus/3,
wait_for_chain_var_update/3, wait_for_chain_var_update/4,
wait_for_lora_port/3,
delete_dirs/2,
initial_dkg/5, initial_dkg/6,
confirm_balance/3,
confirm_balance_both_sides/5,
wait_for_gte/3, wait_for_gte/5,
wait_for_equalized_heights/1,
wait_for_chain_stall/1,
wait_for_chain_stall/2,
assert_chain_halted/1,
assert_chain_halted/3,
assert_chain_advanced/1,
assert_chain_advanced/3,
submit_txn/2,
wait_for_txn/2, wait_for_txn/3, wait_for_txn/4,
format_txn_mgr_list/1,
get_txn_block_details/2, get_txn_block_details/3,
get_txn/2, get_txns/2,
get_genesis_block/2,
load_genesis_block/3,
chain_var_lookup_all/2,
chain_var_lookup_one/2,
build_gateways/2,
build_asserts/2,
add_block/3,
gen_gateways/2, gen_payments/1, gen_locations/1,
existing_vars/0, start_blockchain/2,
create_block/2
]).
chain_var_lookup_all(Key, Nodes) ->
[chain_var_lookup_one(Key, Node) || Node <- Nodes].
chain_var_lookup_one(Key, Node) ->
Chain = ct_rpc:call(Node, blockchain_worker, blockchain, [], 500),
Ledger = ct_rpc:call(Node, blockchain, ledger, [Chain]),
Result = ct_rpc:call(Node, blockchain, config, [Key, Ledger], 500),
ct:pal("Var lookup. Node:~p, Result:~p", [Node, Result]),
Result.
-spec assert_chain_advanced([node()]) -> ok.
assert_chain_advanced(Miners) ->
Height = wait_for_equalized_heights(Miners),
?assertMatch(
ok,
miner_ct_utils:wait_for_gte(height, Miners, Height + 1),
"Chain advanced."
),
ok.
assert_chain_advanced(_, _, N) when N =< 0 ->
ok;
assert_chain_advanced(Miners, Interval, N) ->
ok = assert_chain_advanced(Miners),
timer:sleep(Interval),
assert_chain_advanced(Miners, Interval, N - 1).
-spec assert_chain_halted([node()]) -> ok.
assert_chain_halted(Miners) ->
assert_chain_halted(Miners, 5000, 20).
-spec assert_chain_halted([node()], timeout(), pos_integer()) -> ok.
assert_chain_halted(Miners, Interval, Retries) ->
_ = lists:foldl(
fun (_, HeightPrev) ->
HeightCurr = wait_for_equalized_heights(Miners),
?assertEqual(HeightPrev, HeightCurr, "Chain halted."),
timer:sleep(Interval),
HeightCurr
end,
wait_for_equalized_heights(Miners),
lists:duplicate(Retries, {})
),
ok.
wait_for_chain_stall(Miners) ->
wait_for_chain_stall(Miners, #{}).
-spec wait_for_chain_stall([node()], Options) -> ok | error when
Options :: #{
interval => timeout(),
retries_max => pos_integer(),
streak_target => pos_integer()
}.
wait_for_chain_stall(Miners, Options=#{}) ->
State =
#{
interval => maps:get(interval, Options, 5000),
retries_max => maps:get(retries_max, Options, 100),
streak_target => maps:get(streak_target, Options, 5),
streak_prev => 0,
retries_cur => 0,
height_prev => 0
},
wait_for_chain_stall_(Miners, State).
wait_for_chain_stall_(_, #{streak_target := Target, streak_prev := Streak}) when Streak >= Target ->
ok;
wait_for_chain_stall_(_, #{retries_cur := Cur, retries_max := Max}) when Cur >= Max ->
error;
wait_for_chain_stall_(
Miners,
#{
interval := Interval,
streak_prev := StreakPrev,
height_prev := HeightPrev,
retries_cur := RetriesCur
}=State0
) ->
{HeightCurr, StreakCurr} =
case wait_for_equalized_heights(Miners) of
HeightPrev -> {HeightPrev, 1 + StreakPrev};
HeightCurr0 -> {HeightCurr0, 0}
end,
timer:sleep(Interval),
State1 = State0#{
height_prev := HeightCurr,
streak_prev := StreakCurr,
retries_cur := RetriesCur + 1
},
wait_for_chain_stall_(Miners, State1).
-spec wait_for_equalized_heights([node()]) -> non_neg_integer().
wait_for_equalized_heights(Miners) ->
?assert(
miner_ct_utils:wait_until(
fun() ->
case unique_heights(Miners) of
[_] -> true;
[_|_] -> false
end
end,
50,
1000
),
"Heights equalized."
),
UniqueHeights = unique_heights(Miners),
?assertMatch([_], UniqueHeights, "All heights are equal."),
[Height] = UniqueHeights,
Height.
wait_until_local_height(TargetHeight) ->
miner_ct_utils:wait_until(
fun() ->
C = blockchain_worker:blockchain(),
{ok, CurHeight} = blockchain:height(C),
ct:pal("local height ~p", [CurHeight]),
CurHeight >= TargetHeight
end,
30,
timer:seconds(1)
).
stop_miners(Miners) ->
stop_miners(Miners, 60).
stop_miners(Miners, Retries) ->
Res = [begin
ct:pal("capturing env for ~p", [Miner]),
LagerEnv = ct_rpc:call(Miner, application, get_all_env, [lager]),
P2PEnv = ct_rpc:call(Miner, application, get_all_env, [libp2p]),
BlockchainEnv = ct_rpc:call(Miner, application, get_all_env, [blockchain]),
MinerEnv = ct_rpc:call(Miner, application, get_all_env, [miner]),
ct:pal("stopping ~p", [Miner]),
erlang:monitor_node(Miner, true),
ct_slave:stop(Miner),
receive
{nodedown, Miner} ->
ok
after timer:seconds(Retries) ->
error(stop_timeout)
end,
ct:pal("stopped ~p", [Miner]),
{Miner, [{lager, LagerEnv}, {libp2p, P2PEnv}, {blockchain, BlockchainEnv}, {miner, MinerEnv}]}
end
|| Miner <- Miners],
Res.
start_miner(Name0, Options) ->
Name = start_node(Name0),
Keys = make_keys(Name, {45000, 0, 4466}),
config_node(Keys, Options),
{Name, Keys}.
start_miners(Miners) ->
start_miners(Miners, 60).
start_miners(MinersAndEnv, Retries) ->
[begin
ct:pal("starting ~p", [Miner]),
start_node(Miner),
ct:pal("loading env ~p", [Miner]),
ok = ct_rpc:call(Miner, application, set_env, [Env]),
ct:pal("starting miner on ~p", [Miner]),
{ok, _StartedApps} = ct_rpc:call(Miner, application, ensure_all_started, [miner]),
ct:pal("started miner on ~p : ~p", [Miner, _StartedApps])
end
|| {Miner, Env} <- MinersAndEnv],
{Miners, _Env} = lists:unzip(MinersAndEnv),
ct:pal("waiting for blockchain worker to start on ~p", [Miners]),
ok = miner_ct_utils:wait_for_registration(Miners, blockchain_worker, Retries),
ok.
height(Miner) ->
C0 = ct_rpc:call(Miner, blockchain_worker, blockchain, []),
{ok, Height} = ct_rpc:call(Miner, blockchain, height, [C0]),
ct:pal("miner ~p height ~p", [Miner, Height]),
Height.
heights(Miners) ->
lists:foldl(fun(Miner, Acc) ->
C = ct_rpc:call(Miner, blockchain_worker, blockchain, []),
{ok, H} = ct_rpc:call(Miner, blockchain, height, [C]),
[{Miner, H} | Acc]
end, [], Miners).
-spec unique_heights([node()]) -> [non_neg_integer()].
unique_heights(Miners) ->
lists:usort([H || {_, H} <- miner_ct_utils:heights(Miners)]).
consensus_members([]) ->
error(no_members);
consensus_members([M | Tail]) ->
case handle_get_consensus_miners(M) of
{ok, Members} ->
Members;
{error, _} ->
timer:sleep(500),
consensus_members(Tail)
end.
consensus_members(Epoch, []) ->
error({no_members_at_epoch, Epoch});
consensus_members(Epoch, [M | Tail]) ->
try ct_rpc:call(M, miner_cli_info, get_info, [], 2000) of
{_, _, Epoch} ->
{ok, Members} = handle_get_consensus_miners(M),
Members;
Other ->
ct:pal("~p had Epoch ~p", [M, Other]),
timer:sleep(500),
consensus_members(Epoch, Tail)
catch C:E ->
ct:pal("~p threw error ~p:~p", [M, C, E]),
timer:sleep(500),
consensus_members(Epoch, Tail)
end.
miners_by_consensus_state(Miners)->
handle_miners_by_consensus(partition, true, Miners).
in_consensus_miners(Miners)->
handle_miners_by_consensus(filtermap, true, Miners).
non_consensus_miners(Miners)->
handle_miners_by_consensus(filtermap, false, Miners).
election_check([], _Miners, _AddrList, Owner) ->
Owner ! seen_all;
election_check(NotSeen0, Miners, AddrList, Owner) ->
timer:sleep(500),
NotSeen =
try
Members = miner_ct_utils:consensus_members(Miners),
MinerNames = lists:map(fun(Member)-> miner_ct_utils:addr2node(Member, AddrList) end, Members),
NotSeen1 = NotSeen0 -- MinerNames,
Owner ! {not_seen, NotSeen1},
NotSeen1
catch _C:_E ->
NotSeen0
end,
election_check(NotSeen, Miners, AddrList, Owner).
integrate_genesis_block(ConsensusMiner, NonConsensusMiners)->
Blockchain = ct_rpc:call(ConsensusMiner, blockchain_worker, blockchain, []),
{ok, GenesisBlock} = ct_rpc:call(ConsensusMiner, blockchain, genesis_block, [Blockchain]),
miner_ct_utils:pmap(fun(M) ->
ct_rpc:call(M, blockchain_worker, integrate_genesis_block, [GenesisBlock])
end, NonConsensusMiners).
blockchain_worker_check(Miners)->
lists:all(
fun(Res) ->
Res /= undefined
end,
lists:foldl(
fun(Miner, Acc) ->
R = ct_rpc:call(Miner, blockchain_worker, blockchain, []),
[R | Acc]
end, [], Miners)).
confirm_balance(Miners, Addr, Bal) ->
?assertAsync(begin
Result = lists:all(
fun(Miner) ->
Bal == miner_ct_utils:get_balance(Miner, Addr)
end, Miners)
end,
Result == true, 60, timer:seconds(5)),
ok.
confirm_balance_both_sides(Miners, PayerAddr, PayeeAddr, PayerBal, PayeeBal) ->
?assertAsync(begin
Result = lists:all(
fun(Miner) ->
PayerBal == miner_ct_utils:get_balance(Miner, PayerAddr) andalso
PayeeBal == miner_ct_utils:get_balance(Miner, PayeeAddr)
end, Miners)
end,
Result == true, 60, timer:seconds(1)),
ok.
submit_txn(Txn, Miners) ->
lists:foreach(fun(Miner) ->
ct_rpc:call(Miner, blockchain_worker, submit_txn, [Txn])
end, Miners).
wait_for_gte(height = Type, Miners, Threshold)->
wait_for_gte(Type, Miners, Threshold, all, 60);
wait_for_gte(epoch = Type, Miners, Threshold)->
wait_for_gte(Type, Miners, Threshold, any, 60);
wait_for_gte(height_exactly = Type, Miners, Threshold)->
wait_for_gte(Type, Miners, Threshold, all, 60).
wait_for_gte(Type, Miners, Threshold, Mod, Retries)->
Res = ?noAssertAsync(begin
lists:Mod(
fun(Miner) ->
try
handle_gte_type(Type, Miner, Threshold)
catch What:Why ->
ct:pal("Failed to check GTE ~p ~p ~p: ~p:~p", [Type, Miner, Threshold, What, Why]),
false
end
end, miner_ct_utils:shuffle(Miners))
end,
Retries, timer:seconds(1)),
case Res of
true -> ok;
false -> {error, false}
end.
wait_for_registration(Miners, Mod) ->
wait_for_registration(Miners, Mod, 300).
wait_for_registration(Miners, Mod, Timeout) ->
?assertAsync(begin
RegistrationResult
= lists:all(
fun(Miner) ->
case ct_rpc:call(Miner, erlang, whereis, [Mod], Timeout) of
P when is_pid(P) ->
true;
Other ->
ct:pal("~p result ~p~n", [Miner, Other]),
false
end
end, Miners)
end,
RegistrationResult, 90, timer:seconds(1)),
ok.
wait_for_app_start(Miners, App) ->
wait_for_app_start(Miners, App, 60).
wait_for_app_start(Miners, App, Retries) ->
?assertAsync(begin
AppStartResult =
lists:all(
fun(Miner) ->
case ct_rpc:call(Miner, application, which_applications, []) of
{badrpc, _} ->
false;
Apps ->
lists:keymember(App, 1, Apps)
end
end, Miners)
end,
AppStartResult, Retries, 500),
ok.
wait_for_app_stop(Miners, App) ->
wait_for_app_stop(Miners, App, 30).
wait_for_app_stop(Miners, App, Retries) ->
?assertAsync(begin
Result = lists:all(
fun(Miner) ->
case ct_rpc:call(Miner, application, which_applications, []) of
{badrpc, nodedown} ->
true;
{badrpc, _Which} ->
ct:pal("~p ~p", [Miner, _Which]),
false;
Apps ->
ct:pal("~p ~p", [Miner, Apps]),
not lists:keymember(App, 1, Apps)
end
end, Miners)
end,
Result == true, Retries, 500),
ok.
wait_for_in_consensus(Miners, NumInConsensus)->
wait_for_in_consensus(Miners, NumInConsensus, 500).
wait_for_in_consensus(Miners, NumInConsensus, Timeout)->
?assertAsync(begin
Result = lists:filtermap(
fun(Miner) ->
C1 = ct_rpc:call(Miner, blockchain_worker, blockchain, [], Timeout),
L1 = ct_rpc:call(Miner, blockchain, ledger, [C1], Timeout),
case ct_rpc:call(Miner, blockchain, config, [num_consensus_members, L1], Timeout) of
{ok, _Sz} ->
true == ct_rpc:call(Miner, miner_consensus_mgr, in_consensus, []);
_ ->
false
end
end, Miners),
ct:pal("size ~p", [length(Result)]),
Result
end,
NumInConsensus == length(Result), 60, timer:seconds(1)),
ok.
wait_for_chain_var_update(Miners, Key, Value)->
wait_for_chain_var_update(Miners, Key, Value, 20).
wait_for_chain_var_update(Miners, Key, Value, Retries)->
case wait_until(
fun() ->
lists:all(
fun(Miner) ->
{ok, Value} == chain_var_lookup_one(Key, Miner)
end, miner_ct_utils:shuffle(Miners))
end,
Retries * 2, 500) of
true -> ok;
Else -> Else
end.
wait_for_lora_port(Miners, Mod, Retries)->
?noAssertAsync(begin
lists:all(
fun(Miner) ->
try
case ct_rpc:call(Miner, Mod, port, []) of
{error, _} ->
ct:pal("Failed to find lora port ~p via module ~p", [Miner, Mod]),
false;
_ -> true
end
catch _:_ ->
ct:pal("Failed to find lora port ~p", [Miner]),
false
end
end, Miners)
end,
Retries, timer:seconds(1)).
delete_dirs(DirWildcard, SubDir)->
Dirs = filelib:wildcard(DirWildcard),
[begin
ct:pal("rm dir ~s", [Dir ++ SubDir]),
os:cmd("rm -r " ++ Dir ++ SubDir)
end
|| Dir <- Dirs],
ok.
initial_dkg(Miners, Txns, Addresses, NumConsensusMembers, Curve)->
initial_dkg(Miners, Txns, Addresses, NumConsensusMembers, Curve, 60000).
initial_dkg(Miners, Txns, Addresses, NumConsensusMembers, Curve, Timeout) ->
SuperParent = self(),
SuperTimeout = Timeout + 5000,
Threshold = (NumConsensusMembers - 1) div 3,
spawn(fun() ->
Parent = self(),
lists:foreach(
fun(Miner) ->
spawn(fun() ->
Res = ct_rpc:call(Miner, miner_consensus_mgr, initial_dkg,
[Txns, Addresses, NumConsensusMembers, Curve], Timeout),
Parent ! {Miner, Res}
end)
end, Miners),
SuperParent ! receive_dkg_results(Threshold, Miners, [])
end),
receive
DKGResults ->
DKGResults
after SuperTimeout ->
{error, dkg_timeout}
end.
receive_dkg_results(Threshold, [], OKResults) ->
ct:pal("only ~p completed dkg, lower than threshold of ~p", [OKResults, Threshold]),
{error, insufficent_dkg_completion};
receive_dkg_results(Threshold, _Miners, OKResults) when length(OKResults) >= Threshold ->
{ok, OKResults};
receive_dkg_results(Threshold, Miners, OKResults) ->
receive
{Miner, ok} ->
case lists:member(Miner, Miners) of
true ->
receive_dkg_results(Threshold, Miners -- [Miner], [Miner|OKResults]);
false ->
receive_dkg_results(Threshold, Miners, OKResults)
end;
{Miner, OtherResult} ->
ct:pal("Miner ~p failed DKG: ~p", [Miner, OtherResult]),
receive_dkg_results(Threshold, Miners -- [Miner], OKResults)
end.
pmap(F, L) ->
pmap(F, L, timer:seconds(90)).
pmap(F, L, Timeout) ->
Parent = self(),
lists:foldl(
fun(X, N) ->
spawn_link(fun() ->
Parent ! {pmap, N, F(X)}
end),
N+1
end, 0, L),
L2 = [receive
{pmap, N, R} ->
{N,R}
after Timeout->
error(timeout_expired)
end || _ <- L],
{_, L3} = lists:unzip(lists:keysort(1, L2)),
L3.
wait_until(Fun) ->
wait_until(Fun, 40, 100).
wait_until(Fun, Retry, Delay) when Retry > 0 ->
Res = Fun(),
try Res of
true ->
true;
_ when Retry == 1 ->
false;
_ ->
timer:sleep(Delay),
wait_until(Fun, Retry-1, Delay)
catch _:_ ->
timer:sleep(Delay),
wait_until(Fun, Retry-1, Delay)
end.
wait_until_offline(Node) ->
wait_until(fun() ->
pang == net_adm:ping(Node)
end, 60*2, 500).
wait_until_disconnected(Node1, Node2) ->
wait_until(fun() ->
pang == rpc:call(Node1, net_adm, ping, [Node2])
end, 60*2, 500).
wait_until_connected(Node1, Node2) ->
wait_until(fun() ->
pong == rpc:call(Node1, net_adm, ping, [Node2])
end, 60*2, 500).
start_node(Name) ->
CodePath = lists:filter(fun filelib:is_dir/1, code:get_path()),
NodeConfig = [
{monitor_master, true},
{boot_timeout, 30},
{init_timeout, 30},
{startup_timeout, 30},
{startup_functions, [
{code, set_path, [CodePath]}
]}],
case ct_slave:start(Name, NodeConfig) of
{ok, Node} ->
?assertAsync(Result = net_adm:ping(Node), Result == pong, 60, 500),
Node;
{error, already_started, Node} ->
ct_slave:stop(Name),
wait_until_offline(Node),
start_node(Name);
{error, started_not_connected, Node} ->
connect(Node),
ct_slave:stop(Name),
wait_until_offline(Node),
start_node(Name);
Other ->
Other
end.
partition_cluster(ANodes, BNodes) ->
pmap(fun({Node1, Node2}) ->
true = rpc:call(Node1, erlang, set_cookie, [Node2, canttouchthis]),
true = rpc:call(Node1, erlang, disconnect_node, [Node2]),
true = wait_until_disconnected(Node1, Node2)
end,
[{Node1, Node2} || Node1 <- ANodes, Node2 <- BNodes]),
ok.
heal_cluster(ANodes, BNodes) ->
GoodCookie = erlang:get_cookie(),
pmap(fun({Node1, Node2}) ->
true = rpc:call(Node1, erlang, set_cookie, [Node2, GoodCookie]),
true = wait_until_connected(Node1, Node2)
end,
[{Node1, Node2} || Node1 <- ANodes, Node2 <- BNodes]),
ok.
connect(Node) ->
connect(Node, true).
connect(NodeStr, Auto) when is_list(NodeStr) ->
connect(erlang:list_to_atom(lists:flatten(NodeStr)), Auto);
connect(Node, Auto) when is_atom(Node) ->
connect(node(), Node, Auto).
connect(Node, Node, _) ->
{error, self_join};
connect(_, Node, _Auto) ->
attempt_connect(Node).
attempt_connect(Node) ->
case net_kernel:connect_node(Node) of
false ->
{error, not_reachable};
true ->
{ok, connected}
end.
count(_, []) -> 0;
count(X, [X|XS]) -> 1 + count(X, XS);
count(X, [_|XS]) -> count(X, XS).
randname(N) ->
randname(N, []).
randname(0, Acc) ->
Acc;
randname(N, Acc) ->
randname(N - 1, [rand:uniform(26) + 96 | Acc]).
get_config(Arg, Default) ->
case os:getenv(Arg, Default) of
false -> Default;
T when is_list(T) -> list_to_integer(T);
T -> T
end.
shuffle(List) ->
R = [{rand:uniform(1000000), I} || I <- List],
O = lists:sort(R),
{_, S} = lists:unzip(O),
S.
node2sigfun(Node, KeyList) ->
{_Miner, {_TCPPort, _UDPPort, _JsonRpcPort}, _ECDH, _PubKey, _Addr, SigFun} = lists:keyfind(Node, 1, KeyList),
SigFun.
node2pubkeybin(Node, KeyList) ->
{_Miner, {_TCPPort, _UDPPort, _JsonRpcPort}, _ECDH, _PubKey, Addr, _SigFun} = lists:keyfind(Node, 1, KeyList),
Addr.
node2addr(Node, AddrList) ->
{_, Addr} = lists:keyfind(Node, 1, AddrList),
Addr.
addr2node(Addr, AddrList) ->
{Node, _} = lists:keyfind(Addr, 2, AddrList),
Node.
addr_list(Miners) ->
miner_ct_utils:pmap(
fun(M) ->
Addr = ct_rpc:call(M, blockchain_swarm, pubkey_bin, []),
{M, Addr}
end, Miners).
partition_miners(Members, AddrList) ->
{Miners, _} = lists:unzip(AddrList),
lists:partition(fun(Miner) ->
Addr = miner_ct_utils:node2addr(Miner, AddrList),
lists:member(Addr, Members)
end, Miners).
init_per_testcase(Mod, TestCase, Config0) ->
Config = init_base_dir_config(Mod, TestCase, Config0),
BaseDir = ?config(base_dir, Config),
LogDir = ?config(log_dir, Config),
SplitMiners = proplists:get_value(split_miners_vals_and_gateways, Config, false),
NumValidators = proplists:get_value(num_validators, Config, 0),
NumGateways = proplists:get_value(num_gateways, Config, get_config("T", 8)),
NumConsensusMembers = proplists:get_value(num_consensus_members, Config, get_config("N", 7)),
LoadChainOnGateways = proplists:get_value(gateways_run_chain, Config, true),
GwMuxEnable = proplists:get_value(gateway_and_mux_enable, Config, false),
DefaultKeys = proplists:get_value(default_keys, Config, false),
os:cmd(os:find_executable("epmd")++" -daemon"),
{ok, Hostname} = inet:gethostname(),
case net_kernel:start([list_to_atom("runner-miner" ++
integer_to_list(erlang:system_time(nanosecond)) ++
"@"++Hostname), shortnames]) of
{ok, _} -> ok;
{error, {already_started, _}} -> ok;
{error, {{already_started, _},_}} -> ok
end,
TotalMiners = NumValidators + NumGateways,
SeedNodes = [],
UdpBase = 1690,
GwApiBase = 5068,
JsonRpcBase = 4486,
Port = get_config("PORT", 0),
Curve = 'SS512',
BlockTime = get_config("BT", 100),
BatchSize = get_config("BS", 500),
Interval = get_config("INT", 5),
MinersAndPorts = lists:reverse(lists:foldl(
fun(I, Acc) ->
MinerName = list_to_atom(integer_to_list(I) ++ miner_ct_utils:randname(5)),
[{start_node(MinerName), {GwApiBase + I, UdpBase + (I * 3), JsonRpcBase + I}} | Acc]
end,
[],
lists:seq(1, TotalMiners)
)),
ct:pal("MinersAndPorts: ~p",[MinersAndPorts]),
case lists:any(fun({{error, _}, _}) -> true; (_) -> false end, MinersAndPorts) of
true ->
miner_ct_utils:pmap(fun({error, _}) -> ok; (Miner) -> ct_slave:stop(Miner) end, element(1, lists:unzip(MinersAndPorts))),
throw(hd([ E || {{error, E}, _} <- MinersAndPorts ]));
false ->
ok
end,
Keys = lists:reverse(lists:foldl(
fun({Miner, Ports}, Acc) ->
[make_keys(Miner, Ports) | Acc]
end, [], MinersAndPorts)),
ct:pal("Keys: ~p", [Keys]),
{_Miner, {_GwApiPort, _UDPPort, _JsonRpcPort}, _ECDH, _PubKey, Addr, _SigFun} = hd(Keys),
DefaultRouters = libp2p_crypto:pubkey_bin_to_p2p(Addr),
Options = [{mod, Mod},
{logdir, LogDir},
{basedir, BaseDir},
{seed_nodes, SeedNodes},
{total_miners, TotalMiners},
{curve, Curve},
{gateways_run_chain, LoadChainOnGateways},
{default_keys, DefaultKeys},
{default_routers, DefaultRouters},
{port, Port}],
ConfigResult =
case SplitMiners of
true ->
if config says to use validators for CG then
{ValKeys, GatewayKeys} = lists:split(NumValidators, Keys),
ct:pal("validator keys: ~p", [ValKeys]),
ct:pal("gateway keys: ~p", [GatewayKeys]),
carry the poc transport setting through to config node so that it can
_GatewayConfigResult = miner_ct_utils:pmap(fun(N) -> config_node(N, [{gateway_and_mux_enable, GwMuxEnable}, {mode, gateway} | Options]) end, GatewayKeys),
ValConfigResult = miner_ct_utils:pmap(fun(N) -> config_node(N, [{mode, validator} | Options]) end, ValKeys),
ValConfigResult;
_ ->
miner_ct_utils:pmap(fun(N) -> config_node(N, [{mode, validator} | Options]) end, Keys)
end,
Miners = [M || {M, _} <- MinersAndPorts],
ct:pal("Miners: ~p", [Miners]),
if SplitMiners is false then all miners will be gateways
{Validators, Gateways} =
case SplitMiners of
true ->
lists:split(NumValidators, Miners);
_ ->
{[], Miners}
end,
ct:pal("Validators: ~p", [Validators]),
ct:pal("Gateways: ~p", [Gateways]),
true = lists:all(
fun(ok) -> true;
(Res) ->
ct:pal("config setup failure: ~p", [Res]),
false
end,
ConfigResult
),
MinerAliases = lists:foldl(
fun({_, _, _, _, AliasAddr, _}, Acc) ->
P2PAddr = libp2p_crypto:pubkey_bin_to_p2p(AliasAddr),
[{P2PAddr, "/ip4/52.8.80.146/tcp/2154" } | Acc]
end, [], Keys),
ct:pal("miner aliases ~p", [MinerAliases]),
lists:foreach(fun(Miner)-> ct_rpc:call(Miner, application, set_env, [libp2p, node_aliases, MinerAliases]) end, Miners),
Addrs = get_addrs(Miners),
ct:pal("Addrs: ~p", [Addrs]),
miner_ct_utils:pmap(
fun(Miner) ->
TID = ct_rpc:call(Miner, blockchain_swarm, tid, [], 2000),
ct_rpc:call(Miner, miner_poc, add_stream_handler, [TID], 2000),
Swarm = ct_rpc:call(Miner, blockchain_swarm, tid, [], 2000),
lists:foreach(
fun(A) ->
ct_rpc:call(Miner, libp2p_swarm, connect, [Swarm, A], 2000)
end, Addrs)
end, Miners),
true = miner_ct_utils:wait_until(
fun() ->
lists:all(
fun(Miner) ->
try
GossipPeers = ct_rpc:call(Miner, blockchain_swarm, gossip_peers, [], 500),
ct:pal("Miner: ~p, GossipPeers: ~p", [Miner, GossipPeers]),
case length(GossipPeers) >= (length(Miners) / 2) + 1 of
true -> true;
false ->
ct:pal("~p is not connected to enough peers ~p", [Miner, GossipPeers]),
Swarm = ct_rpc:call(Miner, blockchain_swarm, tid, [], 500),
lists:foreach(
fun(A) ->
CRes = ct_rpc:call(Miner, libp2p_swarm, connect, [Swarm, A], 500),
ct:pal("Connecting ~p to ~p: ~p", [Miner, A, CRes])
end, Addrs),
false
end
catch _C:_E ->
false
end
end, Miners)
end, 200, 150),
with libp2p all the port data is in the peer entries
so for the sake of the tests what we do here is get the libp2p port
the client then just has to pull the libp2p peer data
retrieve the libp2p port and derive the grpc port from that
GRPCServerConfigFun = fun(PeerPort)->
[#{grpc_opts => #{service_protos => [gateway_pb],
services => #{'helium.gateway' => helium_gateway_service}
},
transport_opts => #{ssl => false},
listen_opts => #{port => PeerPort,
ip => {0,0,0,0}},
pool_opts => #{size => 2},
server_opts => #{header_table_size => 4096,
enable_push => 1,
max_concurrent_streams => unlimited,
initial_window_size => 65535,
max_frame_size => 16384,
max_header_list_size => unlimited}}]
end,
ok = lists:foreach(fun(Node) ->
Swarm = ct_rpc:call(Node, blockchain_swarm, swarm, []),
TID = ct_rpc:call(Node, blockchain_swarm, tid, []),
ListenAddrs = ct_rpc:call(Node, libp2p_swarm, listen_addrs, [Swarm]),
[H | _ ] = _SortedAddrs = ct_rpc:call(Node, libp2p_transport, sort_addrs, [TID, ListenAddrs]),
[_, _, _IP,_, Libp2pPort] = _Full = re:split(H, "/"),
ThisPort = list_to_integer(binary_to_list(Libp2pPort)),
_ = ct_rpc:call(Node, application, set_env, [grpcbox, servers, GRPCServerConfigFun(ThisPort + 1000)]),
_ = ct_rpc:call(Node, application, ensure_all_started, [grpcbox]),
ok
end, Miners),
as per above , each such port will be the equivilent libp2p port + 1000
MinerGRPCPortAliases = lists:foldl(
fun({Miner, _, _, _, GrpcAliasAddr, _}, Acc) ->
P2PAddr = libp2p_crypto:pubkey_bin_to_p2p(GrpcAliasAddr),
Swarm = ct_rpc:call(Miner, blockchain_swarm, swarm, []),
TID = ct_rpc:call(Miner, blockchain_swarm, tid, []),
ListenAddrs = ct_rpc:call(Miner, libp2p_swarm, listen_addrs, [Swarm]),
[H | _ ] = _SortedAddrs = ct_rpc:call(Miner, libp2p_transport, sort_addrs, [TID, ListenAddrs]),
[_, _, _IP,_, Libp2pPort] = _Full = re:split(H, "/"),
GrpcPort = list_to_integer(binary_to_list(Libp2pPort)) + 1000,
[{P2PAddr, {GrpcPort, false}} | Acc]
end, [], Keys),
ct:pal("miner grpc port aliases ~p", [MinerGRPCPortAliases]),
create a list of validators and for each their p2p addr , ip addr and grpc port
SeedValidators = lists:foldl(
fun({Miner, _, _, _, ValAddr, _}, Acc) ->
P2PAddr = libp2p_crypto:pubkey_bin_to_p2p(ValAddr),
Swarm = ct_rpc:call(Miner, blockchain_swarm, swarm, []),
TID = ct_rpc:call(Miner, blockchain_swarm, tid, []),
ListenAddrs = ct_rpc:call(Miner, libp2p_swarm, listen_addrs, [Swarm]),
[H | _ ] = _SortedAddrs = ct_rpc:call(Miner, libp2p_transport, sort_addrs, [TID, ListenAddrs]),
[_, _, _IP,_, Libp2pPort] = _Full = re:split(H, "/"),
GrpcPort = list_to_integer(binary_to_list(Libp2pPort)) + 1000,
[{P2PAddr, "127.0.0.1", GrpcPort} | Acc]
end, [], Keys),
ct:pal("seed validators: ~p", [SeedValidators]),
set any required env vars for gateways
lists:foreach(fun(Gateway)->
ct_rpc:call(Gateway, application, set_env, [miner, seed_validators, SeedValidators])
end, Gateways),
lists:foreach(fun(Val)->
ct_rpc:call(Val, application, set_env, [sibyl, node_grpc_port_aliases, MinerGRPCPortAliases]),
ct_rpc:call(Val, application, set_env, [sibyl, poc_mgr_mod, miner_poc_mgr]),
ct_rpc:call(Val, application, set_env, [sibyl, poc_report_handler, miner_poc_report_handler])
end, Validators),
MinerTaggedAddresses = lists:reverse(lists:foldl(
fun(Miner, Acc) ->
PubKeyBin = ct_rpc:call(Miner, blockchain_swarm, pubkey_bin, []),
[{Miner, PubKeyBin} | Acc]
end,
[],
Miners
)),
ct:pal("MinerTaggedAddresses: ~p", [MinerTaggedAddresses]),
{_Keys, Addresses} = lists:unzip(MinerTaggedAddresses),
{ValidatorAddrs, GatewayAddrs} =
case SplitMiners of
true ->
lists:split(NumValidators, Addresses);
_ ->
{[], Addresses}
end,
ct:pal("Validator Addrs: ~p", [ValidatorAddrs]),
ct:pal("Gateway Addrs: ~p", [GatewayAddrs]),
{ok, _} = ct_cover:add_nodes(Miners),
case SplitMiners of
true ->
ok = miner_ct_utils:wait_for_registration(Validators, miner_consensus_mgr);
false ->
ok = miner_ct_utils:wait_for_registration(Miners, miner_consensus_mgr)
end,
{ValidatorPorts, GatewayPorts} =
case SplitMiners of
true ->
lists:split(NumValidators, MinersAndPorts);
_ ->
{[], MinersAndPorts}
end,
UpdatedValidatorPorts = lists:map(fun({Miner, {_, _, JsonRpcPort}}) ->
{Miner, {ignore, ignore, JsonRpcPort}}
end, ValidatorPorts),
[
{miners, Miners},
{validators, Validators},
{gateways, Gateways},
{validator_addrs, ValidatorAddrs},
{gateway_addrs, GatewayAddrs},
{addrs, Addrs},
{keys, Keys},
{ports, UpdatedValidatorPorts ++ GatewayPorts},
{validator_ports, UpdatedValidatorPorts},
{gateway_ports, GatewayPorts},
{node_options, Options},
{addresses, Addresses},
{tagged_miner_addresses, MinerTaggedAddresses},
{block_time, BlockTime},
{batch_size, BatchSize},
{dkg_curve, Curve},
{election_interval, Interval},
{num_consensus_members, NumConsensusMembers},
{rpc_timeout, timer:seconds(30)}
| Config
].
get_addrs(Miners) ->
lists:foldl(
fun(Miner, Acc) ->
Swarm = ct_rpc:call(Miner, blockchain_swarm, swarm, [], 2000),
ct:pal("swarm ~p ~p", [Miner, Swarm]),
true = miner_ct_utils:wait_until(
fun() ->
length(ct_rpc:call(Miner, libp2p_swarm, listen_addrs, [Swarm], 5000)) > 0
end, 20, 1000),
[H|_] = ct_rpc:call(Miner, libp2p_swarm, listen_addrs, [Swarm], 5000),
ct:pal("miner ~p has addr ~p", [Miner, H]),
[H | Acc]
end, [], Miners).
make_keys(Miner, Ports) ->
#{secret := GPriv, public := GPub} =
libp2p_crypto:generate_keys(ecc_compact),
GECDH = libp2p_crypto:mk_ecdh_fun(GPriv),
GAddr = libp2p_crypto:pubkey_to_bin(GPub),
GSigFun = libp2p_crypto:mk_sig_fun(GPriv),
{Miner, Ports, GECDH, GPub, GAddr, GSigFun}.
config_node({Miner, {GwApiPort, UDPPort, JSONRPCPort}, ECDH, PubKey, _Addr, SigFun}, Options) ->
Mod = proplists:get_value(mod, Options),
LogDir = proplists:get_value(logdir, Options),
BaseDir = proplists:get_value(basedir, Options),
SeedNodes = proplists:get_value(seed_nodes, Options),
TotalMiners = proplists:get_value(total_miners, Options),
Curve = proplists:get_value(curve, Options),
DefaultRouters = proplists:get_value(default_routers, Options),
Port = proplists:get_value(port, Options),
Mode = proplists:get_value(mode, Options, gateway),
GwMuxEnable = proplists:get_value(gateway_and_mux_enable, Options, false),
LoadChainOnGateways = proplists:get_value(gateways_run_chain, Options, true),
ct:pal("Miner ~p", [Miner]),
ct_rpc:call(Miner, cover, start, []),
ct_rpc:call(Miner, application, load, [lager]),
ct_rpc:call(Miner, application, load, [miner]),
ct_rpc:call(Miner, application, load, [blockchain]),
ct_rpc:call(Miner, application, load, [libp2p]),
LogRoot = LogDir ++ "_" ++ atom_to_list(Miner),
ct:pal("MinerLogRoot: ~p", [LogRoot]),
ct_rpc:call(Miner, application, set_env, [lager, log_root, LogRoot]),
ct_rpc:call(Miner, application, set_env, [lager, metadata_whitelist, [poc_id]]),
Key =
case proplists:get_value(default_keys, Options) of
true -> undefined;
false -> #{pubkey => PubKey, ecdh_fun => ECDH, sig_fun => SigFun}
end,
MinerBaseDir = BaseDir ++ "_" ++ atom_to_list(Miner),
ct:pal("MinerBaseDir: ~p", [MinerBaseDir]),
ct_rpc:call(Miner, application, set_env, [blockchain, enable_nat, false]),
ct_rpc:call(Miner, application, set_env, [blockchain, base_dir, MinerBaseDir]),
ct_rpc:call(Miner, application, set_env, [blockchain, port, Port]),
ct_rpc:call(Miner, application, set_env, [blockchain, seed_nodes, SeedNodes]),
ct_rpc:call(Miner, application, set_env, [blockchain, key, Key]),
ct_rpc:call(Miner, application, set_env, [blockchain, peer_cache_timeout, 30000]),
ct_rpc:call(Miner, application, set_env, [blockchain, peerbook_update_interval, 200]),
ct_rpc:call(Miner, application, set_env, [blockchain, peerbook_allow_rfc1918, true]),
ct_rpc:call(Miner, application, set_env, [blockchain, disable_poc_v4_target_challenge_age, true]),
ct_rpc:call(Miner, application, set_env, [blockchain, max_inbound_connections, TotalMiners*2]),
ct_rpc:call(Miner, application, set_env, [blockchain, outbound_gossip_connections, TotalMiners]),
ct_rpc:call(Miner, application, set_env, [blockchain, sync_cooldown_time, 5]),
ct_rpc:call(Miner, application, set_env, [blockchain, sc_packet_handler, miner_test_sc_packet_handler]),
ct_rpc:call(Miner, application, set_env, [miner, curve, Curve]),
ct_rpc:call(Miner, application, set_env, [miner, gateway_api_port, GwApiPort]),
ct_rpc:call(Miner, application, set_env, [miner, jsonrpc_port, JSONRPCPort]),
ct_rpc:call(Miner, application, set_env, [miner, mode, Mode]),
ct_rpc:call(Miner, application, set_env, [miner, gateway_and_mux_enable, GwMuxEnable]),
ct_rpc:call(Miner, application, set_env, [miner, gateways_run_chain, LoadChainOnGateways]),
ct_rpc:call(Miner, application, set_env, [miner, radio_device, {{127,0,0,1}, UDPPort, deprecated, deprecated}]),
ct_rpc:call(Miner, application, set_env, [miner, stabilization_period_start, 2]),
ct_rpc:call(Miner, application, set_env, [miner, default_routers, [DefaultRouters]]),
case Mod of
miner_poc_v11_SUITE ->
Do n't set anything region related with poc - v11
ok;
_ ->
ct_rpc:call(Miner, application, set_env, [miner, region_override, 'US915']),
ct_rpc:call(Miner, application, set_env,
[miner, frequency_data,
#{'US915' => [903.9, 904.1, 904.3, 904.5, 904.7, 904.9, 905.1, 905.3],
'EU868' => [867.1, 867.3, 867.5, 867.7, 867.9, 868.1, 868.3, 868.5],
'EU433' => [433.175, 433.375, 433.575],
'CN470' => [486.3, 486.5, 486.7, 486.9, 487.1, 487.3, 487.5, 487.7 ],
'CN779' => [779.5, 779.7, 779.9],
'AU915' => [916.8, 917.0, 917.2, 917.4, 917.5, 917.6, 917.8, 918.0, 918.2],
'AS923_1' => [923.2, 923.4, 923.6, 923.8, 924.0, 924.2, 924.4, 924.6],
'AS923_1B' => [922.0, 922.2, 922.4, 922.6, 922.8, 923.0, 923.2, 923.4],
'AS923_2' => [921.4, 921.6, 921.8, 922.0, 922.2, 922.4, 922.6, 922.8],
'AS923_3' => [916.6, 916.8, 917.0, 917.2, 917.4, 917.6, 917.8, 918.0],
'AS923_4' => [917.3, 917.5, 917.7, 917.9, 918.1, 918.3, 918.5, 918.7],
'KR920' => [922.1, 922.3, 922.5, 922.7, 922.9, 923.1, 923.3],
'IN865' => [865.0625, 865.4025, 865.985]}])
end,
{ok, _StartedApps} = ct_rpc:call(Miner, application, ensure_all_started, [miner]),
ok.
end_per_testcase(TestCase, Config) ->
Miners = ?config(miners, Config),
miner_ct_utils:pmap(fun(Miner) -> ct_slave:stop(Miner) end, Miners),
case ?config(tc_status, Config) of
ok ->
ok;
_ ->
ok
end,
{comment, done}.
cleanup_per_testcase(_TestCase, Config) ->
Miners = ?config(miners, Config),
BaseDir = ?config(base_dir, Config),
LogDir = ?config(log_dir, Config),
lists:foreach(fun(Miner) ->
LogRoot = LogDir ++ "_" ++ atom_to_list(Miner),
Res = os:cmd("rm -rf " ++ LogRoot),
ct:pal("rm -rf ~p -> ~p", [LogRoot, Res]),
DataDir = BaseDir ++ "_" ++ atom_to_list(Miner),
Res2 = os:cmd("rm -rf " ++ DataDir),
ct:pal("rm -rf ~p -> ~p", [DataDir, Res2]),
ok
end, Miners).
get_gw_owner(Miner, GwAddr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_gateway_info,
[GwAddr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, GwInfo} ->
ct_rpc:call(Miner, blockchain_ledger_gateway_v2, owner_address,
[GwInfo])
end
end
end.
get_balance(Miner, Addr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_entry, [Addr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, Entry} ->
ct_rpc:call(Miner, blockchain_ledger_entry_v1, balance, [Entry])
end
end
end.
get_nonce(Miner, Addr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_entry, [Addr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, Entry} ->
ct_rpc:call(Miner, blockchain_ledger_entry_v1, nonce, [Entry])
end
end
end.
get_dc_balance(Miner, Addr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_dc_entry, [Addr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, Entry} ->
ct_rpc:call(Miner, blockchain_ledger_data_credits_entry_v1, balance, [Entry])
end
end
end.
get_dc_nonce(Miner, Addr) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, ledger, [Chain]) of
{badrpc, Error} ->
Error;
Ledger ->
case ct_rpc:call(Miner, blockchain_ledger_v1, find_dc_entry, [Addr, Ledger]) of
{badrpc, Error} ->
Error;
{ok, Entry} ->
ct_rpc:call(Miner, blockchain_ledger_data_credits_entry_v1, nonce, [Entry])
end
end
end.
get_block(Block, Miner) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, []) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, get_block, [Block, Chain]) of
{badrpc, Error} ->
Error;
{ok, BlockRec} ->
BlockRec
end
end.
make_vars(Keys) ->
make_vars(Keys, #{}).
make_vars(Keys, Map) ->
make_vars(Keys, Map, modern).
make_vars(Keys, Map, Mode) ->
Vars1 = #{?chain_vars_version => 2,
?block_time => 2,
?election_interval => 30,
?election_restart_interval => 10,
?num_consensus_members => 7,
?batch_size => 2500,
?vars_commit_delay => 1,
?var_gw_inactivity_threshold => 20,
?block_version => v1,
?dkg_curve => 'SS512',
?predicate_callback_mod => miner,
?predicate_callback_fun => test_version,
?predicate_threshold => 0.60,
?monthly_reward => 5000000 * 1000000,
?securities_percent => 0.35,
?dc_percent => 0.0,
?poc_challengees_percent => 0.19 + 0.16,
?poc_challengers_percent => 0.09 + 0.06,
?poc_witnesses_percent => 0.02 + 0.03,
?consensus_percent => 0.10,
?election_version => 5,
?election_bba_penalty => 0.01,
?election_seen_penalty => 0.05,
?election_cluster_res => 8,
?election_removal_pct => 85,
?election_selection_pct => 60,
?election_replacement_factor => 4,
?election_replacement_slope => 20,
?min_score => 0.2,
?alpha_decay => 0.007,
?beta_decay => 0.0005,
?max_staleness => 100000,
?min_assert_h3_res => 12,
?h3_neighbor_res => 12,
?h3_max_grid_distance => 13,
?h3_exclusion_ring_dist => 2,
?poc_challenge_interval => 10,
?poc_version => 3,
?poc_path_limit => 7,
?poc_typo_fixes => true,
?sc_grace_blocks => 4,
?validator_version => 2,
?validator_minimum_stake => ?bones(10000),
?validator_liveness_grace_period => 10,
?validator_liveness_interval => 5,
?stake_withdrawal_cooldown => 55,
?dkg_penalty => 1.0,
?tenure_penalty => 1.0,
?validator_penalty_filter => 5.0,
?penalty_history_limit => 100
},
#{secret := Priv, public := Pub} = Keys,
BinPub = libp2p_crypto:pubkey_to_bin(Pub),
Vars = maps:merge(Vars1, Map),
case Mode of
modern ->
Txn = blockchain_txn_vars_v1:new(Vars, 1, #{master_key => BinPub}),
Proof = blockchain_txn_vars_v1:create_proof(Priv, Txn),
[blockchain_txn_vars_v1:key_proof(Txn, Proof)];
legacy ->
LegVars = maps:without([?poc_version, ?poc_path_limit, ?sc_grace_blocks,
?election_version, ?election_removal_pct, ?election_cluster_res,
?chain_vars_version, ?block_version, ?election_bba_penalty,
?election_seen_penalty, ?sc_grace_blocks, ?validator_minimum_stake,
?validator_liveness_grace_period, ?validator_liveness_interval,
?poc_typo_fixes, ?election_bba_penalty, ?election_seen_penalty,
?election_cluster_res, ?stake_withdrawal_cooldown,
?validator_penalty_filter
],
Vars),
Proof = blockchain_txn_vars_v1:legacy_create_proof(Priv, LegVars),
Txn = blockchain_txn_vars_v1:new(LegVars, 1, #{master_key => BinPub,
key_proof => Proof}),
[Txn]
end.
nonl([$\n|T]) -> nonl(T);
nonl([H|T]) -> [H|nonl(T)];
nonl([]) -> [].
generate_keys(N) ->
lists:foldl(
fun(_, Acc) ->
{PrivKey, PubKey} = new_random_key(ecc_compact),
SigFun = libp2p_crypto:mk_sig_fun(PrivKey),
[{libp2p_crypto:pubkey_to_bin(PubKey), {PubKey, PrivKey, SigFun}}|Acc]
end,
[],
lists:seq(1, N)
).
new_random_key(Curve) ->
#{secret := PrivKey, public := PubKey} = libp2p_crypto:generate_keys(Curve),
{PrivKey, PubKey}.
new_random_key_with_sig_fun(Curve) ->
#{secret := PrivKey, public := PubKey} = libp2p_crypto:generate_keys(Curve),
SigFun = libp2p_crypto:mk_sig_fun(PrivKey),
{PrivKey, PubKey, SigFun}.
tmp_dir() ->
os:cmd("mkdir -p " ++ ?BASE_TMP_DIR),
create_tmp_dir(?BASE_TMP_DIR_TEMPLATE).
tmp_dir(SubDir) ->
Path = filename:join(?BASE_TMP_DIR, SubDir),
os:cmd("mkdir -p " ++ Path),
create_tmp_dir(Path ++ "/" ++ ?BASE_TMP_DIR_TEMPLATE).
-spec cleanup_tmp_dir(list()) -> ok.
cleanup_tmp_dir(Dir)->
os:cmd("rm -rf " ++ Dir),
ok.
-spec create_tmp_dir(list()) -> list().
create_tmp_dir(Path)->
?MODULE:nonl(os:cmd("mktemp -d " ++ Path)).
generate a tmp directory based off priv_dir to be used as a scratch by common tests
-spec init_base_dir_config(atom(), atom(), Config) -> Config when
Config :: ct_suite:ct_config().
init_base_dir_config(Mod, TestCase, Config)->
PrivDir = ?config(priv_dir, Config),
BaseDir = PrivDir ++ "data/" ++ erlang:atom_to_list(Mod) ++ "_" ++ erlang:atom_to_list(TestCase),
LogDir = PrivDir ++ "logs/" ++ erlang:atom_to_list(Mod) ++ "_" ++ erlang:atom_to_list(TestCase),
[
{base_dir, BaseDir},
{log_dir, LogDir}
| Config
].
CheckType = fun(T ) - > blockchain_txn : type(T ) = = SomeTxnType end ,
wait_for_txn(Miners , CheckType )
CheckTxn = fun(T ) - > T = = SomeSignedTxn end ,
wait_for_txn(Miners, PredFun) ->
wait_for_txn(Miners, PredFun, timer:seconds(30), true).
wait_for_txn(Miners, PredFun, Timeout) ->
wait_for_txn(Miners, PredFun, Timeout, true).
wait_for_txn(Miners, PredFun, Timeout, ExpectedResult)->
timeout is in ms , we want to retry every 200
Count = Timeout div 200,
?assertAsync(begin
Result = lists:all(
fun(Miner) ->
Res = get_txn_block_details(Miner, PredFun, 500),
Res /= []
end, miner_ct_utils:shuffle(Miners))
end,
Result == ExpectedResult, Count, 200),
ok.
format_txn_mgr_list(TxnList) ->
maps:fold(fun(Txn, TxnData, Acc) ->
TxnMod = blockchain_txn:type(Txn),
TxnHash = blockchain_txn:hash(Txn),
Acceptions = proplists:get_value(acceptions, TxnData, []),
Rejections = proplists:get_value(rejections, TxnData, []),
RecvBlockHeight = proplists:get_value(recv_block_height, TxnData, undefined),
Dialers = proplists:get_value(dialers, TxnData, undefined),
[
[{txn_type, atom_to_list(TxnMod)},
{txn_hash, io_lib:format("~p", [libp2p_crypto:bin_to_b58(TxnHash)])},
{acceptions, length(Acceptions)},
{rejections, length(Rejections)},
{accepted_block_height, RecvBlockHeight},
{active_dialers, length(Dialers)}]
| Acc]
end, [], TxnList).
get_txn_block_details(Miner, PredFun) ->
get_txn_block_details(Miner, PredFun, timer:seconds(5)).
get_txn_block_details(Miner, PredFun, Timeout) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, [], Timeout) of
{badrpc, Error} ->
Error;
Chain ->
case ct_rpc:call(Miner, blockchain, blocks, [Chain], Timeout) of
{badrpc, Error} ->
Error;
Blocks ->
lists:filter(fun({_Hash, Block}) ->
BH = blockchain_block : height(Block ) ,
Txns = blockchain_block:transactions(Block),
ToFind = lists:filter(fun(T) ->
PredFun(T)
end,
Txns),
ToFind /= []
end,
maps:to_list(Blocks))
end
end.
get_txn([{_, B}], PredFun) ->
hd(lists:filter(fun(T) ->
PredFun(T)
end,
blockchain_block:transactions(B))).
get_txns(Blocks, PredFun) when is_map(Blocks) ->
lists:foldl(fun({_, B}, Acc) ->
Acc ++ lists:filter(fun(T) -> PredFun(T) end,
blockchain_block:transactions(B))
end, [], maps:to_list(Blocks)).
handle_get_consensus_miners(Miner)->
try
Blockchain = ct_rpc:call(Miner, blockchain_worker, blockchain, [], 2000),
Ledger = ct_rpc:call(Miner, blockchain, ledger, [Blockchain], 2000),
{ok, Members} = ct_rpc:call(Miner, blockchain_ledger_v1, consensus_members, [Ledger], 2000),
{ok, Members}
catch
_:_ -> {error, miner_down}
end.
handle_miners_by_consensus(Mod, Bool, Miners)->
lists:Mod(
fun(Miner) ->
Bool == ct_rpc:call(Miner, miner_consensus_mgr, in_consensus, [])
end, Miners).
handle_gte_type(height, Miner, Threshold)->
C0 = ct_rpc:call(Miner, blockchain_worker, blockchain, [], 2000),
{ok, Height} = ct_rpc:call(Miner, blockchain, height, [C0], 2000),
case Height >= Threshold of
false ->
ct:pal("miner ~p height ~p Threshold ~p", [Miner, Height, Threshold]),
false;
true ->
true
end;
handle_gte_type(epoch, Miner, Threshold)->
{Height, _, Epoch} = ct_rpc:call(Miner, miner_cli_info, get_info, [], 2000),
ct:pal("miner ~p Height ~p Epoch ~p Threshold ~p", [Miner, Height, Epoch, Threshold]),
Epoch >= Threshold;
handle_gte_type(height_exactly, Miner, Threshold)->
C = ct_rpc:call(Miner, blockchain_worker, blockchain, []),
{ok, Ht} = ct_rpc:call(Miner, blockchain, height, [C]),
ct:pal("miner ~p height ~p Exact Threshold ~p", [Miner, Ht, Threshold]),
Ht == Threshold.
get_genesis_block(Miners, Config) ->
RPCTimeout = ?config(rpc_timeout, Config),
ct:pal("RPCTimeout: ~p", [RPCTimeout]),
GenesisBlock = get_genesis_block_(Miners, RPCTimeout),
?assertNotEqual(undefined, GenesisBlock),
GenesisBlock.
get_genesis_block_([Miner|Miners], RPCTimeout) ->
case ct_rpc:call(Miner, blockchain_worker, blockchain, [], RPCTimeout) of
{badrpc, Reason} ->
ct:fail(Reason),
get_genesis_block_(Miners ++ [Miner], RPCTimeout);
undefined ->
get_genesis_block_(Miners ++ [Miner], RPCTimeout);
Chain ->
{ok, GBlock} = rpc:call(Miner, blockchain, genesis_block, [Chain], RPCTimeout),
GBlock
end.
load_genesis_block(GenesisBlock, Miners, Config) ->
RPCTimeout = ?config(rpc_timeout, Config),
lists:foreach(
fun(Miner) ->
true = miner_ct_utils:wait_until(
fun() ->
is_boolean(ct_rpc:call(Miner, miner_consensus_mgr, in_consensus, [], RPCTimeout))
end),
case ct_rpc:call(Miner, miner_consensus_mgr, in_consensus, [], RPCTimeout) of
true ->
ok;
false ->
Res = ct_rpc:call(Miner, blockchain_worker,
integrate_genesis_block, [GenesisBlock], RPCTimeout),
ct:pal("loading genesis ~p block on ~p ~p", [GenesisBlock, Miner, Res]);
{badrpc, Reason} ->
ct:pal("failed to load genesis block on ~p: ~p", [Miner, Reason])
end
end,
Miners
),
ok = miner_ct_utils:wait_for_gte(height, Miners, 1, all, 30).
build_gateways(LatLongs, {PrivKey, PubKey}) ->
lists:foldl(
fun({_LatLong, {GatewayPrivKey, GatewayPubKey}}, Acc) ->
Gateway = libp2p_crypto:pubkey_to_bin(GatewayPubKey),
GatewaySigFun = libp2p_crypto:mk_sig_fun(GatewayPrivKey),
OwnerSigFun = libp2p_crypto:mk_sig_fun(PrivKey),
Owner = libp2p_crypto:pubkey_to_bin(PubKey),
AddGatewayTx = blockchain_txn_add_gateway_v1:new(Owner, Gateway),
SignedOwnerAddGatewayTx = blockchain_txn_add_gateway_v1:sign(AddGatewayTx, OwnerSigFun),
SignedGatewayAddGatewayTx = blockchain_txn_add_gateway_v1:sign_request(SignedOwnerAddGatewayTx, GatewaySigFun),
[SignedGatewayAddGatewayTx|Acc]
end,
[],
LatLongs
).
build_asserts(LatLongs, {PrivKey, PubKey}) ->
lists:foldl(
fun({LatLong, {GatewayPrivKey, GatewayPubKey}}, Acc) ->
Gateway = libp2p_crypto:pubkey_to_bin(GatewayPubKey),
GatewaySigFun = libp2p_crypto:mk_sig_fun(GatewayPrivKey),
OwnerSigFun = libp2p_crypto:mk_sig_fun(PrivKey),
Owner = libp2p_crypto:pubkey_to_bin(PubKey),
Index = h3:from_geo(LatLong, 12),
AssertLocationRequestTx = blockchain_txn_assert_location_v1:new(Gateway, Owner, Index, 1),
PartialAssertLocationTxn = blockchain_txn_assert_location_v1:sign_request(AssertLocationRequestTx, GatewaySigFun),
SignedAssertLocationTx = blockchain_txn_assert_location_v1:sign(PartialAssertLocationTxn, OwnerSigFun),
[SignedAssertLocationTx|Acc]
end,
[],
LatLongs
).
add_block(Chain, ConsensusMembers, Txns) ->
SortedTxns = lists:sort(fun blockchain_txn:sort/2, Txns),
B = create_block(ConsensusMembers, SortedTxns),
ok = blockchain:add_block(B, Chain).
create_block(ConsensusMembers, Txs) ->
Blockchain = blockchain_worker:blockchain(),
{ok, PrevHash} = blockchain:head_hash(Blockchain),
{ok, HeadBlock} = blockchain:head_block(Blockchain),
Height = blockchain_block:height(HeadBlock) + 1,
Block0 = blockchain_block_v1:new(#{prev_hash => PrevHash,
height => Height,
transactions => Txs,
signatures => [],
time => 0,
hbbft_round => 0,
election_epoch => 1,
epoch_start => 1,
seen_votes => [],
bba_completion => <<>>,
poc_keys => []}),
BinBlock = blockchain_block:serialize(blockchain_block:set_signatures(Block0, [])),
Signatures = signatures(ConsensusMembers, BinBlock),
Block1 = blockchain_block:set_signatures(Block0, Signatures),
Block1.
signatures(ConsensusMembers, BinBlock) ->
lists:foldl(
fun({A, {_, _, F}}, Acc) ->
Sig = F(BinBlock),
[{A, Sig}|Acc]
end
,[]
,ConsensusMembers
).
gen_gateways(Addresses, Locations) ->
[blockchain_txn_gen_gateway_v1:new(Addr, Addr, Loc, 0)
|| {Addr, Loc} <- lists:zip(Addresses, Locations)].
gen_payments(Addresses) ->
[ blockchain_txn_coinbase_v1:new(Addr, 5000)
|| Addr <- Addresses].
existing_vars() ->
#{
?allow_payment_v2_memos => true,
?allow_zero_amount => false,
?alpha_decay => 0.0035,
?assert_loc_txn_version => 2,
?batch_size => 400,
?beta_decay => 0.002,
?block_time => 60000,
?block_version => v1,
?chain_vars_version => 2,
?consensus_percent => 0.06,
?data_aggregation_version => 2,
?dc_payload_size => 24,
?dc_percent => 0.325,
?density_tgt_res => 4,
?dkg_curve => 'SS512',
?election_bba_penalty => 0.001,
?election_cluster_res => 4,
?election_interval => 30,
?election_removal_pct => 40,
?election_replacement_factor => 4,
?election_replacement_slope => 20,
?election_restart_interval => 5,
?election_seen_penalty => 0.0033333,
?election_selection_pct => 1,
?election_version => 4,
?h3_exclusion_ring_dist => 6,
?h3_max_grid_distance => 120,
?h3_neighbor_res => 12,
?hip17_interactivity_blocks => 3600,
?hip17_res_0 => <<"2,100000,100000">>,
?hip17_res_1 => <<"2,100000,100000">>,
?hip17_res_10 => <<"2,1,1">>,
?hip17_res_11 => <<"2,100000,100000">>,
?hip17_res_12 => <<"2,100000,100000">>,
?hip17_res_2 => <<"2,100000,100000">>,
?hip17_res_3 => <<"2,100000,100000">>,
?hip17_res_4 => <<"1,250,800">>,
?hip17_res_5 => <<"1,100,400">>,
?hip17_res_6 => <<"1,25,100">>,
?hip17_res_7 => <<"2,5,20">>,
?hip17_res_8 => <<"2,1,4">>,
?hip17_res_9 => <<"2,1,2">>,
?max_antenna_gain => 150,
?max_open_sc => 5,
?max_payments => 50,
?max_staleness => 100000,
?max_subnet_num => 5,
?max_subnet_size => 65536,
?max_xor_filter_num => 5,
?max_xor_filter_size => 102400,
?min_antenna_gain => 10,
?min_assert_h3_res => 12,
?min_expire_within => 15,
?min_score => 0.15,
?min_subnet_size => 8,
?monthly_reward => 500000000000000,
?num_consensus_members => 16,
?poc_addr_hash_byte_count => 8,
?poc_centrality_wt => 0.5,
?poc_challenge_interval => 480,
?poc_challenge_sync_interval => 90,
?poc_challengees_percent => 0.0531,
?poc_challengers_percent => 0.0095,
?poc_good_bucket_high => -70,
?poc_good_bucket_low => -130,
?poc_max_hop_cells => 2000,
?poc_path_limit => 1,
?poc_per_hop_max_witnesses => 25,
?poc_reward_decay_rate => 0.8,
?poc_target_hex_parent_res => 5,
?poc_typo_fixes => true,
?poc_v4_exclusion_cells => 8,
?poc_v4_parent_res => 11,
?poc_v4_prob_bad_rssi => 0.01,
?poc_v4_prob_count_wt => 0.0,
?poc_v4_prob_good_rssi => 1.0,
?poc_v4_prob_no_rssi => 0.5,
?poc_v4_prob_rssi_wt => 0.0,
?poc_v4_prob_time_wt => 0.0,
?poc_v4_randomness_wt => 0.5,
?poc_v4_target_challenge_age => 1000,
?poc_v4_target_exclusion_cells => 6000,
?poc_v4_target_prob_edge_wt => 0.0,
?poc_v4_target_prob_score_wt => 0.0,
?poc_v4_target_score_curve => 5,
?poc_v5_target_prob_randomness_wt => 1.0,
?poc_version => 10,
?poc_witness_consideration_limit => 20,
?poc_witnesses_percent => 0.2124,
?predicate_callback_fun => version,
?predicate_callback_mod => miner,
?predicate_threshold => 0.95,
?price_oracle_height_delta => 10,
?price_oracle_price_scan_delay => 3600,
?price_oracle_price_scan_max => 90000,
?price_oracle_public_keys =>
<<33, 1, 32, 30, 226, 70, 15, 7, 0, 161, 150, 108, 195, 90, 205, 113, 146, 41, 110, 194,
43, 86, 168, 161, 93, 241, 68, 41, 125, 160, 229, 130, 205, 140, 33, 1, 32, 237, 78,
201, 132, 45, 19, 192, 62, 81, 209, 208, 156, 103, 224, 137, 51, 193, 160, 15, 96,
238, 160, 42, 235, 174, 99, 128, 199, 20, 154, 222, 33, 1, 143, 166, 65, 105, 75,
56, 206, 157, 86, 46, 225, 174, 232, 27, 183, 145, 248, 50, 141, 210, 144, 155, 254,
80, 225, 240, 164, 164, 213, 12, 146, 100, 33, 1, 20, 131, 51, 235, 13, 175, 124,
98, 154, 135, 90, 196, 83, 14, 118, 223, 189, 221, 154, 181, 62, 105, 183, 135, 121,
105, 101, 51, 163, 119, 206, 132, 33, 1, 254, 129, 70, 123, 51, 101, 208, 224, 99,
172, 62, 126, 252, 59, 130, 84, 93, 231, 214, 248, 207, 139, 84, 158, 120, 232, 6,
8, 121, 243, 25, 205, 33, 1, 148, 214, 252, 181, 1, 33, 200, 69, 148, 146, 34, 29,
22, 91, 108, 16, 18, 33, 45, 0, 210, 100, 253, 211, 177, 78, 82, 113, 122, 149, 47,
240, 33, 1, 170, 219, 208, 73, 156, 141, 219, 148, 7, 148, 253, 209, 66, 48, 218,
91, 71, 232, 244, 198, 253, 236, 40, 201, 90, 112, 61, 236, 156, 69, 235, 109, 33,
1, 154, 235, 195, 88, 165, 97, 21, 203, 1, 161, 96, 71, 236, 193, 188, 50, 185, 214,
15, 14, 86, 61, 245, 131, 110, 22, 150, 8, 48, 174, 104, 66, 33, 1, 254, 248, 78,
138, 218, 174, 201, 86, 100, 210, 209, 229, 149, 130, 203, 83, 149, 204, 154, 58,
32, 192, 118, 144, 129, 178, 83, 253, 8, 199, 161, 128>>,
?price_oracle_refresh_interval => 10,
?reward_version => 5,
?rewards_txn_version => 2,
?sc_causality_fix => 1,
?sc_gc_interval => 10,
?sc_grace_blocks => 10,
?sc_open_validation_bugfix => 1,
?sc_overcommit => 2,
?sc_version => 2,
?securities_percent => 0.34,
?snapshot_interval => 720,
?snapshot_version => 1,
?stake_withdrawal_cooldown => 250000,
?stake_withdrawal_max => 60,
?staking_fee_txn_add_gateway_v1 => 4000000,
?staking_fee_txn_assert_location_v1 => 1000000,
?staking_fee_txn_oui_v1 => 10000000,
?staking_fee_txn_oui_v1_per_address => 10000000,
?staking_keys =>
<<33, 1, 37, 193, 104, 249, 129, 155, 16, 116, 103, 223, 160, 89, 196, 199, 11, 94, 109,
49, 204, 84, 242, 3, 141, 250, 172, 153, 4, 226, 99, 215, 122, 202, 33, 1, 90, 111,
210, 126, 196, 168, 67, 148, 63, 188, 231, 78, 255, 150, 151, 91, 237, 189, 148, 99,
248, 41, 4, 103, 140, 225, 49, 117, 68, 212, 132, 113, 33, 1, 81, 215, 107, 13, 100,
54, 92, 182, 84, 235, 120, 236, 201, 115, 77, 249, 2, 33, 68, 206, 129, 109, 248,
58, 188, 53, 45, 34, 109, 251, 217, 130, 33, 1, 251, 174, 74, 242, 43, 25, 156, 188,
167, 30, 41, 145, 14, 91, 0, 202, 115, 173, 26, 162, 174, 205, 45, 244, 46, 171,
200, 191, 85, 222, 98, 120, 33, 1, 253, 88, 22, 88, 46, 94, 130, 1, 58, 115, 46,
153, 194, 91, 1, 57, 194, 165, 181, 225, 251, 12, 13, 104, 171, 131, 151, 164, 83,
113, 147, 216, 33, 1, 6, 76, 109, 192, 213, 45, 64, 27, 225, 251, 102, 247, 132, 42,
154, 145, 70, 61, 127, 106, 188, 70, 87, 23, 13, 91, 43, 28, 70, 197, 41, 91, 33, 1,
53, 200, 215, 84, 164, 84, 136, 102, 97, 157, 211, 75, 206, 229, 73, 177, 83, 153,
199, 255, 43, 180, 114, 30, 253, 206, 245, 194, 79, 156, 218, 193, 33, 1, 229, 253,
194, 42, 80, 229, 8, 183, 20, 35, 52, 137, 60, 18, 191, 28, 127, 218, 234, 118, 173,
23, 91, 129, 251, 16, 39, 223, 252, 71, 165, 120, 33, 1, 54, 171, 198, 219, 118,
150, 6, 150, 227, 80, 208, 92, 252, 28, 183, 217, 134, 4, 217, 2, 166, 9, 57, 106,
38, 182, 158, 255, 19, 16, 239, 147, 33, 1, 51, 170, 177, 11, 57, 0, 18, 245, 73,
13, 235, 147, 51, 37, 187, 248, 125, 197, 173, 25, 11, 36, 187, 66, 9, 240, 61, 104,
28, 102, 194, 66, 33, 1, 187, 46, 236, 46, 25, 214, 204, 51, 20, 191, 86, 116, 0,
174, 4, 247, 132, 145, 22, 83, 66, 159, 78, 13, 54, 52, 251, 8, 143, 59, 191, 196>>,
?transfer_hotspot_stale_poc_blocks => 1200,
?txn_fee_multiplier => 5000,
?txn_fees => true,
?validator_liveness_grace_period => 50,
?validator_liveness_interval => 100,
?validator_minimum_stake => 1000000000000,
?validator_version => 1,
?var_gw_inactivity_threshold => 600,
?vars_commit_delay => 1,
?witness_redundancy => 4,
?witness_refresh_interval => 200,
?witness_refresh_rand_n => 1000
}.
gen_locations(Addresses) ->
lists:foldl(
fun(I, Acc) ->
[h3:from_geo({37.780586, -122.469470 + I / 50}, 13) | Acc]
end,
[],
lists:seq(1, length(Addresses))
).
start_blockchain(Config, GenesisVars) ->
Miners = ?config(miners, Config),
Addresses = ?config(addresses, Config),
Curve = ?config(dkg_curve, Config),
NumConsensusMembers = ?config(num_consensus_members, Config),
#{secret := Priv, public := Pub} =
Keys =
libp2p_crypto:generate_keys(ecc_compact),
InitialVars = make_vars(Keys, GenesisVars),
InitialPayments = gen_payments(Addresses),
Locations = gen_locations(Addresses),
InitialGws = gen_gateways(Addresses, Locations),
Txns = InitialVars ++ InitialPayments ++ InitialGws,
{ok, DKGCompletedNodes} = initial_dkg(
Miners,
Txns,
Addresses,
NumConsensusMembers,
Curve
),
_GenesisLoadResults = integrate_genesis_block(
hd(DKGCompletedNodes),
Miners -- DKGCompletedNodes
),
{ConsensusMiners, NonConsensusMiners} = miners_by_consensus_state(Miners),
ct:pal("ConsensusMiners: ~p, NonConsensusMiners: ~p", [ConsensusMiners, NonConsensusMiners]),
MinerHts = pmap(
fun(M) ->
Ch = ct_rpc:call(M, blockchain_worker, blockchain, [], 2000),
{ok, Ht} = ct_rpc:call(M, blockchain, height, [Ch], 2000),
{M, Ht}
end, Miners),
true = lists:all(
fun({_, Ht}) ->
Ht == 1
end,
MinerHts),
[
{master_key, {Priv, Pub}},
{consensus_miners, ConsensusMiners},
{non_consensus_miners, NonConsensusMiners}
| Config
].
|
9d4c3bb3e14366457b48a59172826664986cd9a4605c3b99d042ea9c8a673a70 | haskus/packages | Colored.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE TemplateHaskell #
# LANGUAGE DeriveFunctor #
# LANGUAGE RecordWildCards #
# LANGUAGE KindSignatures #
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
module Haskus.UI.Object.Colored
( ColoredF (..)
, pattern Colored
)
where
import Haskus.Utils.Flow
import Haskus.Utils.EADT
import Haskus.Utils.EADT.TH
import Haskus.UI.Object
import Haskus.UI.Common
-- | Add default color to inner object
data ColoredF e = ColoredF Color e deriving (Functor)
eadtPattern 'ColoredF "Colored"
instance Object e => Object (ColoredF e) where
hit r (ColoredF c o) = hit r o ||> (\x -> x { hitColor = Just c })
| null | https://raw.githubusercontent.com/haskus/packages/40ea6101cea84e2c1466bc55cdb22bed92f642a2/haskus-ui/src/lib/Haskus/UI/Object/Colored.hs | haskell | | Add default color to inner object | # LANGUAGE PatternSynonyms #
# LANGUAGE TemplateHaskell #
# LANGUAGE DeriveFunctor #
# LANGUAGE RecordWildCards #
# LANGUAGE KindSignatures #
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
module Haskus.UI.Object.Colored
( ColoredF (..)
, pattern Colored
)
where
import Haskus.Utils.Flow
import Haskus.Utils.EADT
import Haskus.Utils.EADT.TH
import Haskus.UI.Object
import Haskus.UI.Common
data ColoredF e = ColoredF Color e deriving (Functor)
eadtPattern 'ColoredF "Colored"
instance Object e => Object (ColoredF e) where
hit r (ColoredF c o) = hit r o ||> (\x -> x { hitColor = Just c })
|
513973a191913ff2975c3636b000e13ea598db3d40e76d303089a84f5b4a4244 | open-company/open-company-storage | dev.clj | (ns dev
(:require [com.stuartsierra.component :as component]
[clojure.tools.namespace.repl :as ctnrepl]
[oc.lib.db.pool :as pool]
[oc.storage.config :as c]
[oc.storage.util.search :as search]
[oc.storage.app :as app]
[oc.storage.components :as components]
[oc.storage.async.auth-notification :as auth-notification]
[oc.storage.async.storage-notification :as storage-notification]))
(defonce system nil)
(defonce conn nil)
(defn init
([] (init c/storage-server-port))
([port]
(alter-var-root #'system (constantly (components/storage-system
{:handler-fn app/app
:port port
:auth-sqs-queue c/aws-sqs-auth-queue
:auth-sqs-msg-handler auth-notification/sqs-handler
:storage-sqs-queue c/aws-sqs-storage-queue
:storage-sqs-msg-handler storage-notification/sqs-handler
:sqs-creds {:access-key c/aws-access-key-id
:secret-key c/aws-secret-access-key}})))))
(defn init-db []
(alter-var-root #'system (constantly (components/db-only-storage-system {}))))
(defn bind-conn! []
(alter-var-root #'conn (constantly (pool/claim (get-in system [:db-pool :pool])))))
(defn- start⬆ []
(alter-var-root #'system component/start))
(defn stop []
(alter-var-root #'system (fn [s] (when s (component/stop s))))
(println (str "\nWhen you're ready to start the system again, just type: (go)\n")))
(defn go-db []
(init-db)
(start⬆)
(bind-conn!)
(println (str "A DB connection is available with: conn\n"
"When you're ready to stop the system, just type: (stop)\n")))
(defn go
([] (go c/storage-server-port))
([port]
(init port)
(start⬆)
(bind-conn!)
(app/echo-config port)
(println (str "Now serving storage from the REPL.\n"
"A DB connection is available with: conn\n"
"When you're ready to stop the system, just type: (stop)\n"))
port))
(defn reset []
(stop)
(ctnrepl/refresh :after 'user/go))
(defn send-data-to-search-index []
(search/index-all-entries conn)) | null | https://raw.githubusercontent.com/open-company/open-company-storage/ae4bbe6245f8736f3c1813c3048448035aff5815/src/dev.clj | clojure | (ns dev
(:require [com.stuartsierra.component :as component]
[clojure.tools.namespace.repl :as ctnrepl]
[oc.lib.db.pool :as pool]
[oc.storage.config :as c]
[oc.storage.util.search :as search]
[oc.storage.app :as app]
[oc.storage.components :as components]
[oc.storage.async.auth-notification :as auth-notification]
[oc.storage.async.storage-notification :as storage-notification]))
(defonce system nil)
(defonce conn nil)
(defn init
([] (init c/storage-server-port))
([port]
(alter-var-root #'system (constantly (components/storage-system
{:handler-fn app/app
:port port
:auth-sqs-queue c/aws-sqs-auth-queue
:auth-sqs-msg-handler auth-notification/sqs-handler
:storage-sqs-queue c/aws-sqs-storage-queue
:storage-sqs-msg-handler storage-notification/sqs-handler
:sqs-creds {:access-key c/aws-access-key-id
:secret-key c/aws-secret-access-key}})))))
(defn init-db []
(alter-var-root #'system (constantly (components/db-only-storage-system {}))))
(defn bind-conn! []
(alter-var-root #'conn (constantly (pool/claim (get-in system [:db-pool :pool])))))
(defn- start⬆ []
(alter-var-root #'system component/start))
(defn stop []
(alter-var-root #'system (fn [s] (when s (component/stop s))))
(println (str "\nWhen you're ready to start the system again, just type: (go)\n")))
(defn go-db []
(init-db)
(start⬆)
(bind-conn!)
(println (str "A DB connection is available with: conn\n"
"When you're ready to stop the system, just type: (stop)\n")))
(defn go
([] (go c/storage-server-port))
([port]
(init port)
(start⬆)
(bind-conn!)
(app/echo-config port)
(println (str "Now serving storage from the REPL.\n"
"A DB connection is available with: conn\n"
"When you're ready to stop the system, just type: (stop)\n"))
port))
(defn reset []
(stop)
(ctnrepl/refresh :after 'user/go))
(defn send-data-to-search-index []
(search/index-all-entries conn)) |
|
f7a041254cf1240a44db0c1c9475233b70993c83f79e1a154aff7ce6a5fea060 | manuel-serrano/bigloo | port.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / / runtime / Ieee / port.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Mon Feb 20 16:53:27 1995 * /
* Last change : Fri Feb 18 08:54:26 2022 ( serrano ) * /
;* ------------------------------------------------------------- */
* 6.10.1 Ports ( page 29 , r4 ) * /
;* ------------------------------------------------------------- */
;* Source documentation: */
;* @path ../../manuals/io.texi@ */
;* @node Input And Output@ */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* Le module */
;*---------------------------------------------------------------------*/
(module __r4_ports_6_10_1
(import __error
__bexit
__r4_input_6_10_2
__object
__thread
__param
__gunzip
__url
__http
__ftp)
(use __type
__bigloo
__tvector
__socket
__os
__binary
__base64
__bignum
__rgc
__bit
__r4_vectors_6_8
__r4_strings_6_7
__r4_characters_6_6
__r4_control_features_6_9
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_pairs_and_lists_6_3
__r4_output_6_10_3
__r5_control_features_6_4
__evenv)
(extern (macro c-input-port?::bool (::obj)
"INPUT_PORTP")
(macro c-input-string-port?::bool (::obj)
"INPUT_STRING_PORTP")
(macro c-input-procedure-port?::bool (::obj)
"INPUT_PROCEDURE_PORTP")
(macro c-input-gzip-port?::bool (::obj)
"INPUT_GZIP_PORTP")
(macro c-output-port?::bool (::obj)
"OUTPUT_PORTP")
(macro c-output-string-port?::bool (::obj)
"BGL_OUTPUT_STRING_PORTP")
(macro c-output-procedure-port?::bool (::obj)
"BGL_OUTPUT_PROCEDURE_PORTP")
(macro c-current-output-port::output-port (::dynamic-env)
"BGL_ENV_CURRENT_OUTPUT_PORT")
(macro c-current-error-port::output-port (::dynamic-env)
"BGL_ENV_CURRENT_ERROR_PORT")
(macro c-current-input-port::input-port (::dynamic-env)
"BGL_ENV_CURRENT_INPUT_PORT")
(macro c-current-output-port-set!::void (::dynamic-env ::output-port)
"BGL_ENV_CURRENT_OUTPUT_PORT_SET")
(macro c-current-error-port-set!::void (::dynamic-env ::output-port)
"BGL_ENV_CURRENT_ERROR_PORT_SET")
(macro c-current-input-port-set!::void (::dynamic-env ::input-port)
"BGL_ENV_CURRENT_INPUT_PORT_SET")
(macro c-input-gzip-port-input-port::input-port (::input-port)
"BGL_INPUT_GZIP_PORT_INPUT_PORT")
($open-input-file::obj (::bstring ::bstring) "bgl_open_input_file")
($open-input-descriptor::obj (::int ::bstring) "bgl_open_input_descriptor")
($open-input-pipe::obj (::bstring ::bstring) "bgl_open_input_pipe")
($open-input-resource::obj (::bstring ::bstring) "bgl_open_input_resource")
($open-input-c-string::obj (::string) "bgl_open_input_c_string")
($reopen-input-c-string::obj (::input-port ::string) "bgl_reopen_input_c_string")
($open-input-substring::input-port (::bstring ::long ::long) "bgl_open_input_substring")
($open-input-substring!::input-port (::bstring ::long ::long) "bgl_open_input_substring_bang")
($open-input-procedure::input-port (::procedure ::bstring) "bgl_open_input_procedure")
($input-port-timeout-set!::bool (::input-port ::long) "bgl_input_port_timeout_set")
($output-port-timeout-set!::bool (::output-port ::long) "bgl_output_port_timeout_set")
($open-output-file::obj (::bstring ::bstring) "bgl_open_output_file")
($append-output-file::obj (::bstring ::bstring) "bgl_append_output_file")
($open-output-string::output-port (::bstring) "bgl_open_output_string")
($open-output-procedure::obj (::procedure ::procedure ::procedure ::bstring) "bgl_open_output_procedure")
($close-input-port::obj (::obj) "bgl_close_input_port")
($input-port-reopen!::obj (::input-port) "bgl_input_port_reopen")
($input-port-clone!::input-port (::input-port ::input-port) "bgl_input_port_clone")
($set-input-port-position!::void (::input-port ::long) "bgl_input_port_seek")
(macro c-input-port-position::long (::input-port)
"INPUT_PORT_FILEPOS")
(macro $input-port-fill-barrier::long (::input-port)
"INPUT_PORT_FILLBARRIER")
(macro $input-port-fill-barrier-set!::void (::input-port ::long)
"INPUT_PORT_FILLBARRIER_SET")
(macro $input-port-length::elong (::input-port)
"BGL_INPUT_PORT_LENGTH")
(macro $input-port-length-set!::void (::input-port ::elong)
"BGL_INPUT_PORT_LENGTH_SET")
(macro c-input-port-last-token-position::elong (::input-port)
"INPUT_PORT_TOKENPOS")
(macro c-input-port-bufsiz::long (::input-port)
"BGL_INPUT_PORT_BUFSIZ")
(macro c-closed-input-port?::bool (::obj)
"INPUT_PORT_CLOSEP")
(macro $closed-output-port?::bool (::obj)
"OUTPUT_PORT_CLOSEP")
(macro c-output-port-position::long (::output-port)
"BGL_OUTPUT_PORT_FILEPOS")
(c-set-output-port-position!::obj (::output-port ::long) "bgl_output_port_seek")
($close-output-port::obj (::output-port) "bgl_close_output_port")
(c-get-output-string::bstring (::output-port)"get_output_string")
(c-default-io-bufsiz::long "default_io_bufsiz")
(c-reset-eof::bool (::obj) "reset_eof")
(macro c-flush-output-port::obj (::output-port)
"bgl_flush_output_port")
(macro $reset-output-string-port::obj (::output-port)
"bgl_reset_output_string_port")
(macro $reset-output-port-error::obj (::output-port)
"bgl_reset_output_port_error")
(c-fexists?::bool (::string) "fexists")
(macro c-delete-file::bool (::string) "unlink")
(macro c-delete-directory::bool (::string) "rmdir")
(macro c-rename-file::int (::string ::string) "rename")
(macro $truncate-file::int (::string ::long) "truncate")
(macro $ftruncate::int (::output-port ::long) "bgl_output_port_truncate")
(macro c-mkdir::bool (::string ::long) "!BGL_MKDIR")
(macro $port-isatty?::bool (::output-port) "bgl_port_isatty")
(macro $output-port-name::bstring (::output-port) "OUTPUT_PORT_NAME")
(macro $output-port-name-set!::void (::output-port ::bstring) "OUTPUT_PORT_NAME_SET")
(macro $input-port-name::bstring (::input-port) "INPUT_PORT_NAME")
(macro $input-port-name-set!::void (::input-port ::bstring) "INPUT_PORT_NAME_SET")
(macro c-output-port-chook::obj (::output-port)
"PORT_CHOOK")
(macro c-output-port-chook-set!::void (::output-port ::procedure)
"PORT_CHOOK_SET")
(macro $output-port-fhook::obj (::output-port)
"BGL_OUTPUT_PORT_FHOOK")
(macro $output-port-fhook-set!::void (::output-port ::obj)
"BGL_OUTPUT_PORT_FHOOK_SET")
(macro $output-port-flushbuf::obj (::output-port)
"BGL_OUTPUT_PORT_FLUSHBUF")
(macro $output-port-flushbuf-set!::void (::output-port ::obj)
"BGL_OUTPUT_PORT_FLUSHBUF_SET")
(macro $input-port-chook::obj (::input-port)
"PORT_CHOOK")
(macro $input-port-chook-set!::void (::input-port ::procedure)
"PORT_CHOOK_SET")
(macro $input-port-useek::obj (::input-port)
"BGL_INPUT_PORT_USEEK")
(macro $input-port-useek-set!::void (::input-port ::procedure)
"BGL_INPUT_PORT_USEEK_SET")
(macro $input-port-buffer::bstring (::input-port)
"BGL_INPUT_PORT_BUFFER")
(macro $input-port-buffer-set!::void (::input-port ::bstring)
"bgl_input_port_buffer_set")
(macro $output-port-buffer::bstring (::output-port)
"BGL_OUTPUT_PORT_BUFFER")
(macro $output-port-buffer-set!::void (::output-port ::bstring)
"bgl_output_port_buffer_set")
($directory?::bool (::string) "bgl_directoryp")
($directory->list::obj (::string) "bgl_directory_to_list")
($directory->path-list::obj (::string ::int ::char)
"bgl_directory_to_path_list")
($modification-time::elong (::string) "bgl_last_modification_time")
($change-time::elong (::string) "bgl_last_change_time")
($access-time::elong (::string) "bgl_last_access_time")
($utime::int (::string ::elong ::elong) "bgl_utime")
($file-size::elong (::string) "bgl_file_size")
($file-uid::long (::string) "bgl_file_uid")
($file-gid::long (::string) "bgl_file_gid")
($file-mode::long (::string) "bgl_file_mode")
($file-type::symbol (::string) "bgl_file_type")
($symlink::int (::string ::string) "bgl_symlink")
($select::pair-nil (::long ::pair-nil ::pair-nil ::pair-nil) "bgl_select")
($open-pipes::obj (::obj) "bgl_open_pipes")
($lockf::bool (::output-port ::int ::long) "bgl_lockf")
(macro $F_LOCK::int "F_LOCK")
(macro $F_TLOCK::int "F_TLOCK")
(macro $F_ULOCK::int "F_ULOCK")
(macro $F_TEST::int "F_TEST"))
(java (class foreign
(method static c-input-port?::bool (::obj)
"INPUT_PORTP")
(method static c-input-string-port?::bool (::obj)
"INPUT_STRING_PORTP")
(method static c-input-procedure-port?::bool (::obj)
"INPUT_PROCEDURE_PORTP")
(method static c-input-gzip-port?::bool (::obj)
"INPUT_GZIP_PORTP")
(method static c-output-port?::bool (::obj)
"OUTPUT_PORTP")
(method static c-output-string-port?::bool (::obj)
"OUTPUT_STRING_PORTP")
(method static c-output-procedure-port?::bool (::obj)
"OUTPUT_PROCEDURE_PORTP")
(field static c-default-io-bufsiz::int
"default_io_bufsiz")
(method static c-current-output-port::output-port (::dynamic-env)
"getCurrentOutputPort")
(method static c-current-error-port::output-port (::dynamic-env)
"getCurrentErrorPort")
(method static c-current-input-port::input-port (::dynamic-env)
"getCurrentInputPort")
(method static c-current-output-port-set!::void (::dynamic-env ::output-port)
"setCurrentOutputPort")
(method static c-current-error-port-set!::void (::dynamic-env ::output-port)
"setCurrentErrorPort")
(method static c-current-input-port-set!::void (::dynamic-env ::input-port)
"setCurrentInputPort")
(method static $open-input-file::obj (::bstring ::bstring)
"bgl_open_input_file")
(method static $open-input-descriptor::obj (::int ::bstring)
"bgl_open_input_descriptor")
(method static $open-input-pipe::obj (::bstring ::bstring)
"bgl_open_input_pipe")
(method static $open-input-resource::obj (::bstring ::bstring)
"bgl_open_input_resource")
(method static $open-input-c-string::obj (::string)
"bgl_open_input_c_string")
(method static $reopen-input-c-string::obj (::input-port ::string)
"bgl_reopen_input_c_string")
(method static $open-input-substring::input-port (::bstring ::int ::int)
"bgl_open_input_substring")
(method static $open-input-substring!::input-port (::bstring ::int ::int)
"bgl_open_input_substring_bang")
(method static $open-input-procedure::obj (::procedure ::bstring)
"bgl_open_input_procedure")
(method static $input-port-timeout-set!::bool (::input-port ::long)
"bgl_input_port_timeout_set")
(method static $output-port-timeout-set!::bool (::output-port ::long)
"bgl_output_port_timeout_set")
(method static $open-output-file::obj (::bstring ::bstring)
"bgl_open_output_file")
(method static $append-output-file::obj (::bstring ::bstring)
"bgl_append_output_file")
(method static $open-output-string::output-port (::bstring)
"bgl_open_output_string")
(method static $open-output-procedure::obj (::procedure ::procedure ::procedure ::bstring)
"bgl_open_output_procedure")
(method static $close-input-port::obj (::input-port)
"bgl_close_input_port")
(method static $input-port-reopen!::obj (::input-port)
"bgl_input_port_reopen")
(method static $input-port-clone!::input-port (::input-port ::input-port)
"bgl_input_port_clone")
(method static $set-input-port-position!::void (::input-port ::long)
"bgl_input_port_seek")
(method static c-set-output-port-position!::obj (::output-port ::long)
"bgl_output_port_seek")
(method static c-input-port-bufsiz::int (::input-port)
"bgl_input_port_bufsiz")
(method static c-closed-input-port?::bool (::input-port)
"CLOSED_RGC_BUFFER")
(method static $closed-output-port?::bool (::output-port)
"CLOSED_OUTPUT_PORT")
(method static $close-output-port::obj (::output-port)
"bgl_close_output_port")
(method static c-get-output-string::bstring (::output-port)
"get_output_string")
(method static c-reset-eof::bool (::obj)
"reset_eof")
(method static c-flush-output-port::obj (::output-port)
"FLUSH_OUTPUT_PORT")
(method static $reset-output-string-port::obj (::output-port)
"bgl_reset_output_string_port")
(method static $reset-output-port-error::obj (::output-port)
"bgl_reset_output_port_error")
(method static c-fexists?::bool (::string)
"fexists")
(method static c-delete-file::bool (::string)
"unlink")
(method static c-delete-directory::bool (::string)
"rmdir")
(method static c-rename-file::int (::string ::string)
"rename")
(method static $truncate-file::int (::string ::long)
"truncate")
(method static $ftruncate::bool (::output-port ::long)
"bgl_output_port_truncate")
(method static c-mkdir::bool (::string ::int)
"mkdir")
(method static c-output-port-position::long (::output-port)
"OUTPUT_PORT_FILEPOS")
(method static c-input-port-position::long (::input-port)
"INPUT_PORT_FILEPOS")
(method static $input-port-fill-barrier::long (::input-port)
"INPUT_PORT_FILLBARRIER")
(method static $input-port-fill-barrier-set!::void (::input-port ::long)
"INPUT_PORT_FILLBARRIER_SET")
(method static $input-port-length::elong (::input-port)
"BGL_INPUT_PORT_LENGTH")
(method static $input-port-length-set!::void (::input-port ::elong)
"BGL_INPUT_PORT_LENGTH_SET")
(method static c-input-port-last-token-position::long (::input-port)
"INPUT_PORT_TOKENPOS")
(method static $input-port-name-set!::void (::input-port ::bstring)
"INPUT_PORT_NAME")
(method static $input-port-name::bstring (::input-port)
"INPUT_PORT_NAME")
(method static $output-port-name::bstring (::output-port)
"OUTPUT_PORT_NAME")
(method static $output-port-name-set!::void (::output-port ::bstring)
"OUTPUT_PORT_NAME_SET")
(method static c-output-port-chook::obj (::output-port)
"OUTPUT_PORT_CHOOK")
(method static c-output-port-chook-set!::void (::output-port ::procedure)
"OUTPUT_PORT_CHOOK_SET")
(method static $output-port-fhook::obj (::output-port)
"OUTPUT_PORT_FHOOK")
(method static $output-port-fhook-set!::void (::output-port ::obj)
"OUTPUT_PORT_FHOOK_SET")
(method static $output-port-flushbuf::obj (::output-port)
"OUTPUT_PORT_FLUSHBUF")
(method static $output-port-flushbuf-set!::void (::output-port ::obj)
"OUTPUT_PORT_FLUSHBUF_SET")
(method static $input-port-chook::obj (::input-port)
"INPUT_PORT_CHOOK")
(method static $input-port-chook-set!::void (::input-port ::procedure)
"INPUT_PORT_CHOOK_SET")
(method static $input-port-useek::obj (::input-port)
"INPUT_PORT_USEEK")
(method static $input-port-useek-set!::void (::input-port ::procedure)
"INPUT_PORT_USEEK_SET")
(method static $input-port-buffer::bstring (::input-port)
"BGL_INPUT_PORT_BUFFER")
(method static $input-port-buffer-set!::void (::input-port ::bstring)
"bgl_input_port_buffer_set")
(method static $output-port-buffer::bstring (::output-port)
"BGL_OUTPUT_PORT_BUFFER")
(method static $output-port-buffer-set!::void (::output-port ::bstring)
"bgl_output_port_buffer_set")
(method static c-input-gzip-port-input-port::input-port (::input-port)
"BGL_INPUT_GZIP_PORT_INPUT_PORT")
(method static $directory?::bool (::string)
"bgl_directoryp")
(method static $directory->list::obj (::string)
"bgl_directory_to_list")
(method static $modification-time::elong (::string)
"bgl_last_modification_time")
(method static $change-time::elong (::string)
"bgl_last_change_time")
(method static $access-time::elong (::string)
"bgl_last_access_time")
(method static $utime::int (::string ::elong ::elong)
"bgl_utime")
(method static $file-size::elong (::string)
"bgl_file_size")
(method static $file-uid::int (::string)
"bgl_file_uid")
(method static $file-gid::int (::string)
"bgl_file_gid")
(method static $file-mode::int (::string)
"bgl_file_mode")
(method static $file-type::symbol (::string)
"bgl_file_type")
(method static $symlink::int (::string ::string)
"bgl_symlink")
(method static $select::pair-nil (::long ::pair-nil ::pair-nil ::pair-nil)
"bgl_select")
(method static $open-pipes::obj (::obj)
"bgl_open_pipes")))
(export (call-with-input-file ::bstring ::procedure)
(call-with-input-string ::bstring ::procedure)
(call-with-output-file ::bstring ::procedure)
(call-with-append-file ::bstring ::procedure)
(call-with-output-string::bstring ::procedure)
(inline input-port? ::obj)
(inline input-string-port? ::obj)
(inline input-procedure-port? ::obj)
(inline input-gzip-port? ::obj)
(inline output-port? ::obj)
(inline port?::bool ::obj)
(inline output-string-port? ::obj)
(inline output-procedure-port? ::obj)
(inline current-input-port::input-port)
(inline current-error-port::output-port)
(inline current-output-port::output-port)
(with-input-from-file ::bstring ::procedure)
(with-input-from-string ::bstring ::procedure)
(with-input-from-port ::input-port ::procedure)
(with-input-from-procedure ::procedure ::procedure)
(with-output-to-file ::bstring ::procedure)
(with-append-to-file ::bstring ::procedure)
(with-output-to-string::bstring ::procedure)
(with-error-to-string::bstring ::procedure)
(with-output-to-port ::output-port ::procedure)
(with-output-to-procedure ::procedure ::procedure)
(with-error-to-file ::bstring ::procedure)
(with-error-to-port ::output-port ::procedure)
(with-error-to-procedure ::procedure ::procedure)
(open-input-file ::bstring #!optional (bufinfo #t) (timeout 5000000))
(open-input-descriptor ::int #!optional (bufinfo #t))
(open-input-string::input-port string::bstring
#!optional (start 0) (end (string-length string)))
(open-input-string!::input-port string::bstring
#!optional (start 0) (end (string-length string)))
(open-input-procedure ::procedure #!optional (bufinfo #t))
(open-input-gzip-port ::input-port #!optional (bufinfo #t))
(inline input-port-timeout-set! ::input-port ::long)
(inline open-input-c-string ::string)
(inline reopen-input-c-string ::input-port ::string)
(open-output-file ::bstring #!optional (bufinfo #t))
(append-output-file ::bstring #!optional (bufinfo #t))
(open-output-string::output-port #!optional (bufinfo #t))
(open-output-procedure ::procedure #!optional (flush::procedure (lambda () #f)) (bufinfo #t) (close::procedure (lambda () #f)))
(inline output-port-timeout-set! ::output-port ::long)
(inline closed-input-port?::bool ::input-port)
(inline close-input-port ::input-port)
(inline get-output-string::bstring ::output-port)
(inline close-output-port ::output-port)
(inline flush-output-port ::output-port)
(inline reset-output-port ::output-port)
(inline reset-eof::bool ::input-port)
(inline output-port-name::bstring ::output-port)
(inline output-port-name-set! ::output-port ::bstring)
(inline output-port-position::long ::output-port)
(inline output-port-isatty?::bool ::output-port)
(inline set-output-port-position! ::output-port ::long)
(set-input-port-position! ::input-port ::long)
(inline input-port-position::long ::input-port)
(inline input-port-fill-barrier ::input-port)
(inline input-port-fill-barrier-set! ::input-port ::long)
(inline input-port-last-token-position::long ::input-port)
(inline input-port-reopen! ::input-port)
(inline input-port-clone! ::input-port ::input-port)
(inline input-port-name::bstring ::input-port)
(inline input-port-name-set! ::input-port ::bstring)
(inline input-port-length::elong ::input-port)
(inline output-port-close-hook::obj ::output-port)
(inline closed-output-port?::bool ::output-port)
(output-port-close-hook-set! ::output-port ::procedure)
(inline output-port-flush-hook::obj ::output-port)
(output-port-flush-hook-set! ::output-port ::obj)
(inline output-port-flush-buffer::obj ::output-port)
(inline output-port-flush-buffer-set! ::output-port ::obj)
(inline input-port-close-hook::obj ::input-port)
(input-port-close-hook-set! ::input-port ::procedure)
(inline input-port-seek::procedure ::input-port)
(input-port-seek-set! ::input-port ::procedure)
(inline input-port-buffer::bstring ::input-port)
(inline input-port-buffer-set! ::input-port ::bstring)
(inline output-port-buffer::bstring ::output-port)
(inline output-port-buffer-set! ::output-port ::bstring)
(inline file-exists?::bool ::string)
(file-gzip? name)
(inline delete-file ::string)
(inline make-directory::bool ::string)
(make-directories::bool ::bstring)
(inline delete-directory ::string)
(inline rename-file::bool ::string ::string)
(inline truncate-file::bool ::string ::long)
(inline output-port-truncate::bool ::output-port ::long)
(copy-file ::string ::string)
(inline directory?::bool ::string)
(inline directory->list ::string)
(directory->path-list ::bstring)
(inline file-modification-time::elong ::string)
(inline file-change-time::elong ::string)
(inline file-access-time::elong ::string)
(inline file-times-set!::int ::string ::elong ::elong)
(inline file-size::elong ::string)
(inline file-uid::int ::string)
(inline file-gid::int ::string)
(inline file-mode::int ::string)
(inline file-type::symbol ::string)
(inline make-symlink ::bstring ::bstring)
(inline select::pair-nil #!key (timeout 0) (read '()) (write '()) (except '()))
(inline open-pipes #!optional name)
(input-port-protocol prototcol)
(input-port-protocol-set! protocol open)
(get-port-buffer::bstring ::obj ::obj ::int)
(lockf::bool ::output-port ::symbol #!optional (len 0)))
(pragma (c-input-port? (predicate-of input-port) nesting)
(c-output-port? (predicate-of output-port) nesting)
(c-output-string-port? nesting)
(c-input-string-port? nesting)
(file-exists? side-effect-free nesting)))
;*---------------------------------------------------------------------*/
;* call-with-input-file ... */
;*---------------------------------------------------------------------*/
(define (call-with-input-file string proc)
(let ((port (open-input-file string)))
(if (input-port? port)
(unwind-protect
(proc port)
(close-input-port port))
(error/errno $errno-io-port-error
"call-with-input-file" "can't open file" string))))
;*---------------------------------------------------------------------*/
;* call-with-input-string ... */
;*---------------------------------------------------------------------*/
(define (call-with-input-string string proc)
(let ((port (open-input-string string)))
;; No need to force closing it, will be garbage collected anyhow.
(let ((res (proc port)))
(close-input-port port)
res)))
;*---------------------------------------------------------------------*/
;* call-with-output-file ... */
;*---------------------------------------------------------------------*/
(define (call-with-output-file string proc)
(let ((port (open-output-file string)))
(if (output-port? port)
(unwind-protect
(proc port)
(close-output-port port))
(error/errno $errno-io-port-error
"call-with-output-file" "can't open file" string))))
;*---------------------------------------------------------------------*/
;* call-with-append-file ... */
;*---------------------------------------------------------------------*/
(define (call-with-append-file string proc)
(let ((port (append-output-file string)))
(if (output-port? port)
(unwind-protect
(proc port)
(close-output-port port))
(error/errno $errno-io-port-error
"call-with-append-file" "can't open file" string))))
;*---------------------------------------------------------------------*/
;* call-with-output-string ... */
;*---------------------------------------------------------------------*/
(define (call-with-output-string proc)
(let ((port (open-output-string)))
(proc port)
(close-output-port port)))
;*---------------------------------------------------------------------*/
;* input-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port? obj)
(c-input-port? obj))
;*---------------------------------------------------------------------*/
;* input-string-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (input-string-port? obj)
(c-input-string-port? obj))
;*---------------------------------------------------------------------*/
;* input-procedure-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (input-procedure-port? obj)
(c-input-procedure-port? obj))
;*---------------------------------------------------------------------*/
;* input-gzip-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (input-gzip-port? obj)
(c-input-gzip-port? obj))
;*---------------------------------------------------------------------*/
;* output-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port? obj)
(c-output-port? obj))
;*---------------------------------------------------------------------*/
;* output-string-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (output-string-port? obj)
(c-output-string-port? obj))
;*---------------------------------------------------------------------*/
;* output-procedure-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (output-procedure-port? obj)
(c-output-procedure-port? obj))
;*---------------------------------------------------------------------*/
;* current-input-port ... */
;*---------------------------------------------------------------------*/
(define-inline (current-input-port)
(c-current-input-port ($current-dynamic-env)))
;*---------------------------------------------------------------------*/
;* current-output-port ... */
;*---------------------------------------------------------------------*/
(define-inline (current-output-port)
(c-current-output-port ($current-dynamic-env)))
;*---------------------------------------------------------------------*/
;* current-error-port ... */
;*---------------------------------------------------------------------*/
(define-inline (current-error-port)
(c-current-error-port ($current-dynamic-env)))
;*---------------------------------------------------------------------*/
;* @deffn input-port-reopen!@ ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-reopen! port::input-port)
(unless ($input-port-reopen! port)
(error/errno
$errno-io-port-error "input-port-reopen!" "Cannot reopen port" port)))
;*---------------------------------------------------------------------*/
;* @deffn input-port-clone!! ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-clone! dst::input-port src::input-port)
($input-port-clone! dst src))
;*---------------------------------------------------------------------*/
;* @deffn with-input-from-file@ ... */
;*---------------------------------------------------------------------*/
(define (with-input-from-file string thunk)
(let ((port (open-input-file string)))
(if (input-port? port)
(let* ((denv ($current-dynamic-env))
(old-input-port (c-current-input-port denv)))
(unwind-protect
(begin
(c-current-input-port-set! denv port)
(thunk))
(begin
(c-current-input-port-set! denv old-input-port)
(close-input-port port))))
(error/errno $errno-io-port-error
"with-input-from-file" "can't open file" string))))
;*---------------------------------------------------------------------*/
;* @deffn with-input-from-string@ ... */
;*---------------------------------------------------------------------*/
(define (with-input-from-string string thunk)
(let* ((port (open-input-string string))
(denv ($current-dynamic-env))
(old-input-port (c-current-input-port denv)))
(unwind-protect
(begin
(c-current-input-port-set! denv port)
(thunk))
(begin
(c-current-input-port-set! denv old-input-port)
(close-input-port port)))))
;*---------------------------------------------------------------------*/
;* with-input-from-port ... */
;*---------------------------------------------------------------------*/
(define (with-input-from-port port thunk)
(let* ((denv ($current-dynamic-env))
(old-input-port (c-current-input-port denv)))
(unwind-protect
(begin
(c-current-input-port-set! denv port)
(thunk))
(c-current-input-port-set! denv old-input-port))))
;*---------------------------------------------------------------------*/
;* @deffn with-input-from-procedure@ ... */
;*---------------------------------------------------------------------*/
(define (with-input-from-procedure proc thunk)
(let ((port (open-input-procedure proc)))
(if (input-port? port)
(let* ((denv ($current-dynamic-env))
(old-input-port (c-current-input-port denv)))
(unwind-protect
(begin
(c-current-input-port-set! denv port)
(thunk))
(begin
(c-current-input-port-set! denv old-input-port)
(close-input-port port))))
(error "with-input-from-procedure" "can't open procedure" proc))))
;*---------------------------------------------------------------------*/
;* with-output-to-file ... */
;*---------------------------------------------------------------------*/
(define (with-output-to-file string thunk)
(let ((port (open-output-file string)))
(if (output-port? port)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv)))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(begin
(c-current-output-port-set! denv old-output-port)
(close-output-port port))))
(error/errno $errno-io-port-error
"with-output-to-file" "can't open file" string))))
;*---------------------------------------------------------------------*/
;* with-append-to-file ... */
;*---------------------------------------------------------------------*/
(define (with-append-to-file string thunk)
(let ((port (append-output-file string)))
(if (output-port? port)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv)))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(begin
(c-current-output-port-set! denv old-output-port)
(close-output-port port))))
(error/errno $errno-io-port-error
"with-output-to-file" "can't open file" string))))
;*---------------------------------------------------------------------*/
;* @deffn with-output-to-port@ ... */
;*---------------------------------------------------------------------*/
(define (with-output-to-port port thunk)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv)))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(c-current-output-port-set! denv old-output-port))))
;*---------------------------------------------------------------------*/
;* @deffn with-output-to-string@ ... */
;*---------------------------------------------------------------------*/
(define (with-output-to-string thunk)
(let* ((port (open-output-string))
(denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv))
(res #unspecified))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(begin
(c-current-output-port-set! denv old-output-port)
(set! res (close-output-port port))))
res))
;*---------------------------------------------------------------------*/
;* with-output-to-procedure ... */
;*---------------------------------------------------------------------*/
(define (with-output-to-procedure proc thunk)
(let* ((port (open-output-procedure proc))
(denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv))
(res #unspecified))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(begin
(c-current-output-port-set! denv old-output-port)
(set! res (close-output-port port))))
res))
;*---------------------------------------------------------------------*/
;* @deffn with-error-to-string@ ... */
;*---------------------------------------------------------------------*/
(define (with-error-to-string thunk)
(let ((port (open-output-string)))
(if (output-port? port)
(let* ((denv ($current-dynamic-env))
(old-error-port (c-current-error-port denv))
(res #unspecified))
(unwind-protect
(begin
(c-current-error-port-set! denv port)
(thunk))
(begin
(c-current-error-port-set! denv old-error-port)
(set! res (close-output-port port))))
res)
(error/errno $errno-io-port-error
'with-error-to-string
"can't open string"
#unspecified))))
;*---------------------------------------------------------------------*/
;* @deffn with-error-to-file@ ... */
;*---------------------------------------------------------------------*/
(define (with-error-to-file string thunk)
(let ((port (open-output-file string)))
(if (output-port? port)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-error-port denv)))
(unwind-protect
(begin
(c-current-error-port-set! denv port)
(thunk))
(begin
(c-current-error-port-set! denv old-output-port)
(close-output-port port))))
(error/errno $errno-io-port-error
'with-error-to-file
"can't open file"
string))))
;*---------------------------------------------------------------------*/
;* with-error-to-port ... */
;*---------------------------------------------------------------------*/
(define (with-error-to-port port thunk)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-error-port denv)))
(unwind-protect
(begin
(c-current-error-port-set! denv port)
(thunk))
(c-current-error-port-set! denv old-output-port))))
;*---------------------------------------------------------------------*/
;* with-error-to-procedure ... */
;*---------------------------------------------------------------------*/
(define (with-error-to-procedure proc thunk)
(let* ((port (open-output-procedure proc))
(denv ($current-dynamic-env))
(old-error-port (c-current-error-port denv))
(res #unspecified))
(unwind-protect
(begin
(c-current-error-port-set! denv port)
(thunk))
(begin
(c-current-error-port-set! denv old-error-port)
(set! res (close-output-port port))))
res))
;*---------------------------------------------------------------------*/
;* *input-port-protocols-mutex* ... */
;*---------------------------------------------------------------------*/
(define *input-port-protocols-mutex* (make-mutex "input-port-protocols"))
;*---------------------------------------------------------------------*/
;* *input-port-protocols* ... */
;*---------------------------------------------------------------------*/
(define *input-port-protocols*
`(("file:" . ,%open-input-file)
("string:" . ,(lambda (s p tmt) (open-input-string s)))
("| " . ,%open-input-pipe)
("pipe:" . ,%open-input-pipe)
("http://" . ,%open-input-http-socket)
("gzip:" . ,open-input-gzip-file)
("zlib:" . ,open-input-zlib-file)
("inflate:" . ,open-input-inflate-file)
("/resource/" . ,%open-input-resource)
("ftp://" . ,open-input-ftp-file)
("fd:" . ,%open-input-descriptor)))
;*---------------------------------------------------------------------*/
;* input-port-protocols ... */
;*---------------------------------------------------------------------*/
(define (input-port-protocols)
(synchronize *input-port-protocols-mutex*
(reverse! (reverse *input-port-protocols*))))
;*---------------------------------------------------------------------*/
;* input-port-protocol ... */
;*---------------------------------------------------------------------*/
(define (input-port-protocol prototcol)
(let ((cell (synchronize *input-port-protocols-mutex*
(assoc prototcol *input-port-protocols*))))
(if (pair? cell)
(cdr cell)
#f)))
;*---------------------------------------------------------------------*/
;* input-port-protocol-set! ... */
;*---------------------------------------------------------------------*/
(define (input-port-protocol-set! protocol open)
(synchronize *input-port-protocols-mutex*
(unless (and (procedure? open) (correct-arity? open 3))
(error "input-port-protocol-set!"
"Illegal open procedure for protocol"
protocol))
(let ((c (assoc protocol *input-port-protocols*)))
(if (pair? c)
(set-cdr! c open)
(set! *input-port-protocols*
(cons (cons protocol open) *input-port-protocols*)))))
open)
;*---------------------------------------------------------------------*/
;* get-port-buffer ... */
;*---------------------------------------------------------------------*/
(define (get-port-buffer who bufinfo defsiz)
(cond
((eq? bufinfo #t)
($make-string/wo-fill defsiz))
((eq? bufinfo #f)
($make-string/wo-fill 2))
((string? bufinfo)
bufinfo)
((fixnum? bufinfo)
(if (>=fx bufinfo 2)
($make-string/wo-fill bufinfo)
($make-string/wo-fill 2)))
(else
(error who "Illegal buffer" bufinfo))))
;*---------------------------------------------------------------------*/
;* %open-input-file ... */
;*---------------------------------------------------------------------*/
(define (%open-input-file string buf tmt)
($open-input-file string buf))
;*---------------------------------------------------------------------*/
;* %open-input-descriptor ... */
;*---------------------------------------------------------------------*/
(define (%open-input-descriptor string buf tmt)
(let ((fd (string->integer (substring string 3))))
($open-input-descriptor fd buf)))
;*---------------------------------------------------------------------*/
;* %open-input-pipe ... */
;*---------------------------------------------------------------------*/
(define-inline (%open-input-pipe string bufinfo tmt)
(let ((buf (get-port-buffer "open-input-pipe" bufinfo 1024)))
($open-input-pipe string buf)))
;*---------------------------------------------------------------------*/
;* %open-input-resource ... */
;*---------------------------------------------------------------------*/
(define (%open-input-resource file bufinfo tmt)
(let ((buf (get-port-buffer "open-input-file" bufinfo c-default-io-bufsiz)))
($open-input-resource file buf)))
;*---------------------------------------------------------------------*/
;* %open-input-http-socket ... */
;*---------------------------------------------------------------------*/
(define (%open-input-http-socket string bufinfo timeout)
(define (parser ip status-code header clen tenc)
(when (and (>=fx status-code 200) (<=fx status-code 299))
(cond
((not (input-port? ip))
(open-input-string ""))
((and (elong? clen) (>elong clen 0))
(input-port-fill-barrier-set! ip (elong->fixnum clen))
($input-port-length-set! ip clen)
ip)
(else
ip))))
(multiple-value-bind (protocol login host port abspath)
(url-sans-protocol-parse string "http")
(let loop ((ip #f)
(header '((user-agent: "Mozilla/5.0") (Connection: close))))
(let* ((sock (http :host host
:port port
:login login
:path abspath
:timeout timeout
:header header))
(op (socket-output sock)))
(if (input-port? ip)
;; the socket has been re-opened for seek, reuse
;; the user input-port
(input-port-clone! ip (socket-input sock))
(set! ip (socket-input sock)))
(input-port-close-hook-set! ip
(lambda (ip)
(close-output-port op)
(socket-close sock)))
(input-port-seek-set! ip
(lambda (ip offset)
(socket-close sock)
(let ((r (string-append "bytes=" (integer->string offset) "-")))
(loop ip `((range: ,r) (user-agent: "Mozilla/5.0"))))))
(with-handler
(lambda (e)
(socket-close sock)
(when (isa? e &http-redirection)
(with-access::&http-redirection e (url)
(open-input-file url bufinfo))))
(http-parse-response ip op parser))))))
;*---------------------------------------------------------------------*/
;* open-input-file ... */
;* ------------------------------------------------------------- */
;* This new version of open-input-file accept extended syntax. */
;* It may open plain file, strings, pipes, http/ftp files. The */
;* syntax is inspired by Web browsers, e.g.: */
;* "/etc/passwd" */
;* "file:/etc/passwd" */
;* "string:bozo" */
;* "pipe:ls -lR /" */
;* "" */
;* ":10000/" */
;* */
;* it also accepts the former form for pipes: */
;* "| ls -lR /" */
;* ------------------------------------------------------------- */
;* Implementation note: remember that STRING-LENGTH is a O-macro */
;* thus, (STRING-LENGTH <a-constant-string>) is replaced with the */
;* actual length of the constant. */
;*---------------------------------------------------------------------*/
(define (open-input-file string #!optional (bufinfo #t) (timeout 5000000))
(let ((buffer (get-port-buffer "open-input-file" bufinfo c-default-io-bufsiz)))
(let loop ((protos *input-port-protocols*))
(if (null? protos)
;; a plain file
(%open-input-file string buffer timeout)
(let* ((cell (car protos))
(ident (car cell))
(l (string-length ident))
(open (cdr cell)))
(if (substring=? string ident l)
;; we have found the open function
(let ((name (substring string l (string-length string))))
(open name buffer timeout))
(loop (cdr protos))))))))
;*---------------------------------------------------------------------*/
;* open-input-descriptor ... */
;*---------------------------------------------------------------------*/
(define (open-input-descriptor fd #!optional (bufinfo #t))
(let ((buffer (get-port-buffer "open-input-file" bufinfo c-default-io-bufsiz)))
($open-input-descriptor fd buffer)))
;*---------------------------------------------------------------------*/
;* open-input-string ... */
;*---------------------------------------------------------------------*/
(define (open-input-string string
#!optional (start 0) (end (string-length string)))
(cond
((<fx start 0)
(error "open-input-string" "Illegal start offset" start))
((>fx start (string-length string))
(error "open-input-string" "Start offset out of bounds" start))
((>fx start end)
(error "open-input-string" "Start offset greater than end" start))
((>fx end (string-length string))
(error "open-input-string" "End offset out of bounds" end))
(else
($open-input-substring string start end))))
;*---------------------------------------------------------------------*/
;* open-input-string! ... */
;*---------------------------------------------------------------------*/
(define (open-input-string! string
#!optional (start 0) (end (string-length string)))
(cond
((<fx start 0)
(error "open-input-string!" "Illegal start offset" start))
((>fx start (string-length string))
(error "open-input-string!" "Start offset out of bounds" start))
((>fx start end)
(error "open-input-string!" "Start offset greater than end" start))
((>fx end (string-length string))
(error "open-input-string!" "End offset out of bounds" end))
(else
($open-input-substring! string start end))))
;*---------------------------------------------------------------------*/
;* open-input-procedure ... */
;*---------------------------------------------------------------------*/
(define (open-input-procedure proc #!optional (bufinfo #t))
(let ((buf (get-port-buffer "open-input-procedure" bufinfo 1024)))
($open-input-procedure proc buf)))
;*---------------------------------------------------------------------*/
;* open-input-gzip-port ... */
;*---------------------------------------------------------------------*/
(define (open-input-gzip-port in::input-port #!optional (bufinfo #t))
(let ((buf (get-port-buffer "open-input-gzip-port" bufinfo c-default-io-bufsiz)))
(port->gzip-port in buf)))
;*---------------------------------------------------------------------*/
;* open-input-c-string ... */
;*---------------------------------------------------------------------*/
(define-inline (open-input-c-string string)
($open-input-c-string string))
;*---------------------------------------------------------------------*/
;* reopen-input-c-string ... */
;*---------------------------------------------------------------------*/
(define-inline (reopen-input-c-string port::input-port string)
($reopen-input-c-string port string))
;*---------------------------------------------------------------------*/
;* input-port-timeout-set! ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-timeout-set! port::input-port timeout::long)
($input-port-timeout-set! port timeout))
;*---------------------------------------------------------------------*/
;* open-output-file ... */
;*---------------------------------------------------------------------*/
(define (open-output-file string #!optional (bufinfo #t))
(let ((buf (get-port-buffer "open-output-file" bufinfo c-default-io-bufsiz)))
($open-output-file string buf)))
;*---------------------------------------------------------------------*/
;* append-output-file ... */
;*---------------------------------------------------------------------*/
(define (append-output-file string #!optional (bufinfo #t))
(let ((buf (get-port-buffer "append-output-file" bufinfo c-default-io-bufsiz)))
($append-output-file string buf)))
;*---------------------------------------------------------------------*/
;* open-output-string ... */
;*---------------------------------------------------------------------*/
(define (open-output-string #!optional (bufinfo #t))
(let ((buf (get-port-buffer "open-output-file" bufinfo 128)))
($open-output-string buf)))
;*---------------------------------------------------------------------*/
;* open-output-procedure ... */
;*---------------------------------------------------------------------*/
(define (open-output-procedure proc
#!optional
(flush::procedure (lambda () #f))
(bufinfo #t)
(close::procedure (lambda () #f)))
(cond
((not (correct-arity? proc 1))
(error/errno $errno-io-port-error
"open-output-procedure"
"Illegal write procedure"
proc))
((or (not (procedure? flush))
(not (correct-arity? flush 0)))
(error/errno $errno-io-port-error
"open-output-procedure"
"Illegal flush procedure"
flush))
((or (not (procedure? close))
(not (correct-arity? close 0)))
(error/errno $errno-io-port-error
"open-output-procedure"
"Illegal close procedure"
flush))
(else
(let ((buf (get-port-buffer "open-output-procedure" bufinfo 128)))
($open-output-procedure proc flush close buf)))))
;*---------------------------------------------------------------------*/
;* output-port-timeout-set! ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-timeout-set! port::output-port timeout::long)
($output-port-timeout-set! port timeout))
;*---------------------------------------------------------------------*/
;* closed-input-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (closed-input-port? port)
(c-closed-input-port? port))
;*---------------------------------------------------------------------*/
;* close-input-port ... */
;*---------------------------------------------------------------------*/
(define-inline (close-input-port port)
($close-input-port port))
;*---------------------------------------------------------------------*/
;* get-output-string ... */
;*---------------------------------------------------------------------*/
(define-inline (get-output-string port)
(c-get-output-string port))
;*---------------------------------------------------------------------*/
;* close-output-port ... */
;*---------------------------------------------------------------------*/
(define-inline (close-output-port port)
($close-output-port port))
;*---------------------------------------------------------------------*/
;* flush-output-port ... */
;*---------------------------------------------------------------------*/
(define-inline (flush-output-port port)
(c-flush-output-port port))
;*---------------------------------------------------------------------*/
;* reset-string-port ... */
;*---------------------------------------------------------------------*/
(define-inline (reset-output-port port)
($reset-output-port-error port)
(if (c-output-string-port? port)
($reset-output-string-port port)
(flush-output-port port)))
;*---------------------------------------------------------------------*/
;* reset-eof ... */
;*---------------------------------------------------------------------*/
(define-inline (reset-eof port)
(c-reset-eof port))
;*---------------------------------------------------------------------*/
;* set-input-port-position! ... */
;*---------------------------------------------------------------------*/
(define (set-input-port-position! port::input-port pos::long)
(let ((useek ($input-port-useek port)))
(if (procedure? useek)
(useek port pos)
($set-input-port-position! port pos)))
#unspecified)
;*---------------------------------------------------------------------*/
;* input-port-position ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-position port)
(c-input-port-position port))
;*---------------------------------------------------------------------*/
;* input-port-fill-barrier ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-fill-barrier port::input-port)
($input-port-fill-barrier port))
;*---------------------------------------------------------------------*/
;* input-port-fill-barrier-set! ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-fill-barrier-set! port::input-port pos::long)
($input-port-fill-barrier-set! port pos)
pos)
;*---------------------------------------------------------------------*/
;* input-port-last-token-position ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-last-token-position port)
(c-input-port-last-token-position port))
;*---------------------------------------------------------------------*/
;* output-port-name ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-name port)
($output-port-name port))
;*---------------------------------------------------------------------*/
;* output-port-name-set! ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-name-set! port name)
($output-port-name-set! port name))
;*---------------------------------------------------------------------*/
;* set-output-port-position! ... */
;*---------------------------------------------------------------------*/
(define-inline (set-output-port-position! port::output-port pos::long)
(unless (c-set-output-port-position! port pos)
(error/errno $errno-io-port-error
"set-output-port-position!" "Cannot seek port" port)))
;*---------------------------------------------------------------------*/
;* output-port-position ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-position port)
(c-output-port-position port))
;*---------------------------------------------------------------------*/
;* output-port-isatty? ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-isatty? port)
(cond-expand
(bigloo-c ($port-isatty? port))
(else #t)))
;*---------------------------------------------------------------------*/
;* input-port-name ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-name port)
($input-port-name port))
;*---------------------------------------------------------------------*/
;* input-port-name-set! ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-name-set! port name)
($input-port-name-set! port name))
;*---------------------------------------------------------------------*/
;* input-port-length ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-length port)
($input-port-length port))
;*---------------------------------------------------------------------*/
;* output-port-close-hook ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-close-hook port)
(c-output-port-chook port))
;*---------------------------------------------------------------------*/
;* closed-output-port? ... */
;*---------------------------------------------------------------------*/
(define-inline (closed-output-port? port)
($closed-output-port? port))
;*---------------------------------------------------------------------*/
;* output-port-close-hook-set! ... */
;*---------------------------------------------------------------------*/
(define (output-port-close-hook-set! port proc)
(if (not (and (procedure? proc) (correct-arity? proc 1)))
(error/errno $errno-io-port-error
"output-port-close-hook-set!" "Illegal hook" proc)
(begin
(c-output-port-chook-set! port proc)
proc)))
;*---------------------------------------------------------------------*/
;* output-port-flush-hook ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-flush-hook port)
($output-port-fhook port))
;*---------------------------------------------------------------------*/
;* output-port-flush-hook-set! ... */
;*---------------------------------------------------------------------*/
(define (output-port-flush-hook-set! port proc)
(if (and (procedure? proc) (not (correct-arity? proc 2)))
(error/errno $errno-io-port-error
"output-port-flush-hook-set!" "Illegal hook" proc)
(begin
($output-port-fhook-set! port proc)
proc)))
;*---------------------------------------------------------------------*/
;* output-port-flush-buffer ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-flush-buffer port)
($output-port-flushbuf port))
;*---------------------------------------------------------------------*/
;* output-port-flush-buffer-set! ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-flush-buffer-set! port buf)
($output-port-flushbuf-set! port buf)
buf)
;*---------------------------------------------------------------------*/
;* input-port-close-hook ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-close-hook port)
($input-port-chook port))
;*---------------------------------------------------------------------*/
;* input-port-close-hook-set! ... */
;*---------------------------------------------------------------------*/
(define (input-port-close-hook-set! port proc)
(if (not (and (procedure? proc) (correct-arity? proc 1)))
(error/errno $errno-io-port-error
"input-port-close-hook-set!" "Illegal hook" proc)
(begin
($input-port-chook-set! port proc)
proc)))
;*---------------------------------------------------------------------*/
;* input-port-seek ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-seek port)
($input-port-useek port))
;*---------------------------------------------------------------------*/
;* input-port-seek-set! ... */
;*---------------------------------------------------------------------*/
(define (input-port-seek-set! port proc)
(if (not (and (procedure? proc) (correct-arity? proc 2)))
(error/errno $errno-io-port-error
"input-port-seek-set!" "Illegal seek procedure" proc)
(begin
($input-port-useek-set! port proc)
proc)))
;*---------------------------------------------------------------------*/
;* input-port-buffer ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-buffer port)
($input-port-buffer port))
;*---------------------------------------------------------------------*/
;* input-port-buffer-set! ... */
;*---------------------------------------------------------------------*/
(define-inline (input-port-buffer-set! port buffer)
(begin ($input-port-buffer-set! port buffer) port))
;*---------------------------------------------------------------------*/
;* output-port-buffer ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-buffer port)
($output-port-buffer port))
;*---------------------------------------------------------------------*/
;* output-port-buffer-set! ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-buffer-set! port buffer)
(begin ($output-port-buffer-set! port buffer) port))
;*---------------------------------------------------------------------*/
;* file-exists? ... */
;*---------------------------------------------------------------------*/
(define-inline (file-exists? name)
(c-fexists? name))
;*---------------------------------------------------------------------*/
;* file-gzip? ... */
;*---------------------------------------------------------------------*/
(define (file-gzip? name)
(and (file-exists? name)
(with-input-from-file name
(lambda ()
(with-handler
(lambda (e)
#f)
(gunzip-parse-header (current-input-port)))))))
;*---------------------------------------------------------------------*/
;* delete-file ... */
;*---------------------------------------------------------------------*/
(define-inline (delete-file string)
(not (c-delete-file string)))
;*---------------------------------------------------------------------*/
;* make-directory ... */
;*---------------------------------------------------------------------*/
(define-inline (make-directory string)
(c-mkdir string #o777))
;*---------------------------------------------------------------------*/
;* make-directories ... */
;*---------------------------------------------------------------------*/
(define (make-directories string)
(or (directory? string)
(make-directory string)
(let ((dname (dirname string)))
(if (or (=fx (string-length dname) 0) (file-exists? dname))
#f
(let ((aux (make-directories dname)))
(if (char=? (string-ref string (-fx (string-length string) 1))
(file-separator))
aux
(make-directory string)))))))
;*---------------------------------------------------------------------*/
;* delete-directory ... */
;*---------------------------------------------------------------------*/
(define-inline (delete-directory string)
(not (c-delete-directory string)))
;*---------------------------------------------------------------------*/
;* rename-file ... */
;*---------------------------------------------------------------------*/
(define-inline (rename-file string1 string2)
(if (eq? (c-rename-file string1 string2) 0) #t #f))
;*---------------------------------------------------------------------*/
;* truncate-file ... */
;*---------------------------------------------------------------------*/
(define-inline (truncate-file path size)
($truncate-file path size))
;*---------------------------------------------------------------------*/
;* output-port-truncate ... */
;*---------------------------------------------------------------------*/
(define-inline (output-port-truncate oport size)
($ftruncate oport size))
;*---------------------------------------------------------------------*/
;* copy-file ... */
;*---------------------------------------------------------------------*/
(define (copy-file string1 string2)
(let ((pi (open-input-binary-file string1)))
(when (binary-port? pi)
(let ((po (open-output-binary-file string2)))
(if (not (binary-port? po))
(begin
(close-binary-port pi)
#f)
(let ((s (make-string 1024)))
(let loop ((l (input-fill-string! pi s)))
(if (=fx l 1024)
(begin
(output-string po s)
(loop (input-fill-string! pi s)))
(begin
(output-string po (string-shrink! s l))
(close-binary-port pi)
(close-binary-port po)
#t)))))))))
;*---------------------------------------------------------------------*/
;* port? ... */
;*---------------------------------------------------------------------*/
(define-inline (port? obj)
(or (output-port? obj) (input-port? obj)))
;*---------------------------------------------------------------------*/
;* directory? ... */
;*---------------------------------------------------------------------*/
(define-inline (directory? string)
($directory? string))
;*---------------------------------------------------------------------*/
;* directory->list ... */
;*---------------------------------------------------------------------*/
(define-inline (directory->list string)
($directory->list string))
;*---------------------------------------------------------------------*/
;* directory->path-list ... */
;*---------------------------------------------------------------------*/
(define (directory->path-list dir)
(let ((l (string-length dir)))
(cond
((=fx l 0)
'())
((char=? (string-ref dir (-fx l 1)) (file-separator))
(cond-expand
(bigloo-c
($directory->path-list dir (-fx l 1) (file-separator)))
(else
(map! (lambda (f) (string-append dir f))
(directory->list dir)))))
(else
(cond-expand
(bigloo-c
($directory->path-list dir l (file-separator)))
(else
(map! (lambda (f) (make-file-name dir f))
(directory->list dir))))))))
;*---------------------------------------------------------------------*/
;* @deffn file-modification-time@ ... */
;*---------------------------------------------------------------------*/
(define-inline (file-modification-time file)
($modification-time file))
;*---------------------------------------------------------------------*/
;* @deffn file-change-time@ ... */
;*---------------------------------------------------------------------*/
(define-inline (file-change-time file)
($change-time file))
;*---------------------------------------------------------------------*/
;* @deffn file-access-time@ ... */
;*---------------------------------------------------------------------*/
(define-inline (file-access-time file)
($access-time file))
;*---------------------------------------------------------------------*/
;* @deffn file-times-set!@ ... */
;*---------------------------------------------------------------------*/
(define-inline (file-times-set! file atime mtime)
($utime file atime mtime))
;*---------------------------------------------------------------------*/
;* @deffn file-size@ ... */
;*---------------------------------------------------------------------*/
(define-inline (file-size file)
($file-size file))
;*---------------------------------------------------------------------*/
* @deffn file - uid@ ... * /
;*---------------------------------------------------------------------*/
(define-inline (file-uid file)
($file-uid file))
;*---------------------------------------------------------------------*/
;* @deffn file-gid@ ... */
;*---------------------------------------------------------------------*/
(define-inline (file-gid file)
($file-gid file))
;*---------------------------------------------------------------------*/
;* @deffn file-mode@ ... */
;*---------------------------------------------------------------------*/
(define-inline (file-mode file)
($file-mode file))
;*---------------------------------------------------------------------*/
;* @deffn file-type@ ... */
;*---------------------------------------------------------------------*/
(define-inline (file-type file)
($file-type file))
;*---------------------------------------------------------------------*/
;* make-symlink ... */
;*---------------------------------------------------------------------*/
(define-inline (make-symlink path1 path2)
($symlink path1 path2))
;*---------------------------------------------------------------------*/
;* select ... */
;*---------------------------------------------------------------------*/
(define-inline (select #!key (timeout 0) (read '()) (write '()) (except '()))
($select timeout read write except))
;*---------------------------------------------------------------------*/
;* open-pipes ... */
;*---------------------------------------------------------------------*/
(define-inline (open-pipes #!optional name)
($open-pipes name))
;*---------------------------------------------------------------------*/
;* lockf ... */
;*---------------------------------------------------------------------*/
(define (lockf port cmd #!optional (len 0))
(cond-expand
(bigloo-c
(case cmd
((lock) ($lockf port $F_LOCK len))
((tlock) ($lockf port $F_TLOCK len))
((ulock) ($lockf port $F_ULOCK len))
((test) ($lockf port $F_TEST len))
(else (error "lockf" "Bad command" cmd))))
(else #f)))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/c1f0f7bf50595ba03bcdb7c48f14494b54a369d3/runtime/Ieee/port.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* Source documentation: */
* @path ../../manuals/io.texi@ */
* @node Input And Output@ */
*=====================================================================*/
*---------------------------------------------------------------------*/
* Le module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* call-with-input-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* call-with-input-string ... */
*---------------------------------------------------------------------*/
No need to force closing it, will be garbage collected anyhow.
*---------------------------------------------------------------------*/
* call-with-output-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* call-with-append-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* call-with-output-string ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-string-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-procedure-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-gzip-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-string-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-procedure-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* current-input-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* current-output-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* current-error-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn input-port-reopen!@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn input-port-clone!! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn with-input-from-file@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn with-input-from-string@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* with-input-from-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn with-input-from-procedure@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* with-output-to-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* with-append-to-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn with-output-to-port@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn with-output-to-string@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* with-output-to-procedure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn with-error-to-string@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn with-error-to-file@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* with-error-to-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* with-error-to-procedure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *input-port-protocols-mutex* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *input-port-protocols* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-protocols ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-protocol ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-protocol-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-port-buffer ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %open-input-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %open-input-descriptor ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %open-input-pipe ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %open-input-resource ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %open-input-http-socket ... */
*---------------------------------------------------------------------*/
the socket has been re-opened for seek, reuse
the user input-port
*---------------------------------------------------------------------*/
* open-input-file ... */
* ------------------------------------------------------------- */
* This new version of open-input-file accept extended syntax. */
* It may open plain file, strings, pipes, http/ftp files. The */
* syntax is inspired by Web browsers, e.g.: */
* "/etc/passwd" */
* "file:/etc/passwd" */
* "string:bozo" */
* "pipe:ls -lR /" */
* "" */
* ":10000/" */
* */
* it also accepts the former form for pipes: */
* "| ls -lR /" */
* ------------------------------------------------------------- */
* Implementation note: remember that STRING-LENGTH is a O-macro */
* thus, (STRING-LENGTH <a-constant-string>) is replaced with the */
* actual length of the constant. */
*---------------------------------------------------------------------*/
a plain file
we have found the open function
*---------------------------------------------------------------------*/
* open-input-descriptor ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-input-string ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-input-string! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-input-procedure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-input-gzip-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-input-c-string ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reopen-input-c-string ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-timeout-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-output-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* append-output-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-output-string ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-output-procedure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-timeout-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* closed-input-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* close-input-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-output-string ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* close-output-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* flush-output-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-string-port ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-eof ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* set-input-port-position! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-position ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-fill-barrier ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-fill-barrier-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-last-token-position ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-name ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-name-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* set-output-port-position! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-position ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-isatty? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-name ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-name-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-length ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-close-hook ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* closed-output-port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-close-hook-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-flush-hook ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-flush-hook-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-flush-buffer ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-flush-buffer-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-close-hook ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-close-hook-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-seek ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-seek-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-buffer ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* input-port-buffer-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-buffer ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-buffer-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* file-exists? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* file-gzip? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* delete-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-directory ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-directories ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* delete-directory ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* rename-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* truncate-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* output-port-truncate ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* copy-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* port? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* directory? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* directory->list ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* directory->path-list ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn file-modification-time@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn file-change-time@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn file-access-time@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn file-times-set!@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn file-size@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn file-gid@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn file-mode@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @deffn file-type@ ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-symlink ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* select ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* open-pipes ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* lockf ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / / runtime / Ieee / port.scm * /
* Author : * /
* Creation : Mon Feb 20 16:53:27 1995 * /
* Last change : Fri Feb 18 08:54:26 2022 ( serrano ) * /
* 6.10.1 Ports ( page 29 , r4 ) * /
(module __r4_ports_6_10_1
(import __error
__bexit
__r4_input_6_10_2
__object
__thread
__param
__gunzip
__url
__http
__ftp)
(use __type
__bigloo
__tvector
__socket
__os
__binary
__base64
__bignum
__rgc
__bit
__r4_vectors_6_8
__r4_strings_6_7
__r4_characters_6_6
__r4_control_features_6_9
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_pairs_and_lists_6_3
__r4_output_6_10_3
__r5_control_features_6_4
__evenv)
(extern (macro c-input-port?::bool (::obj)
"INPUT_PORTP")
(macro c-input-string-port?::bool (::obj)
"INPUT_STRING_PORTP")
(macro c-input-procedure-port?::bool (::obj)
"INPUT_PROCEDURE_PORTP")
(macro c-input-gzip-port?::bool (::obj)
"INPUT_GZIP_PORTP")
(macro c-output-port?::bool (::obj)
"OUTPUT_PORTP")
(macro c-output-string-port?::bool (::obj)
"BGL_OUTPUT_STRING_PORTP")
(macro c-output-procedure-port?::bool (::obj)
"BGL_OUTPUT_PROCEDURE_PORTP")
(macro c-current-output-port::output-port (::dynamic-env)
"BGL_ENV_CURRENT_OUTPUT_PORT")
(macro c-current-error-port::output-port (::dynamic-env)
"BGL_ENV_CURRENT_ERROR_PORT")
(macro c-current-input-port::input-port (::dynamic-env)
"BGL_ENV_CURRENT_INPUT_PORT")
(macro c-current-output-port-set!::void (::dynamic-env ::output-port)
"BGL_ENV_CURRENT_OUTPUT_PORT_SET")
(macro c-current-error-port-set!::void (::dynamic-env ::output-port)
"BGL_ENV_CURRENT_ERROR_PORT_SET")
(macro c-current-input-port-set!::void (::dynamic-env ::input-port)
"BGL_ENV_CURRENT_INPUT_PORT_SET")
(macro c-input-gzip-port-input-port::input-port (::input-port)
"BGL_INPUT_GZIP_PORT_INPUT_PORT")
($open-input-file::obj (::bstring ::bstring) "bgl_open_input_file")
($open-input-descriptor::obj (::int ::bstring) "bgl_open_input_descriptor")
($open-input-pipe::obj (::bstring ::bstring) "bgl_open_input_pipe")
($open-input-resource::obj (::bstring ::bstring) "bgl_open_input_resource")
($open-input-c-string::obj (::string) "bgl_open_input_c_string")
($reopen-input-c-string::obj (::input-port ::string) "bgl_reopen_input_c_string")
($open-input-substring::input-port (::bstring ::long ::long) "bgl_open_input_substring")
($open-input-substring!::input-port (::bstring ::long ::long) "bgl_open_input_substring_bang")
($open-input-procedure::input-port (::procedure ::bstring) "bgl_open_input_procedure")
($input-port-timeout-set!::bool (::input-port ::long) "bgl_input_port_timeout_set")
($output-port-timeout-set!::bool (::output-port ::long) "bgl_output_port_timeout_set")
($open-output-file::obj (::bstring ::bstring) "bgl_open_output_file")
($append-output-file::obj (::bstring ::bstring) "bgl_append_output_file")
($open-output-string::output-port (::bstring) "bgl_open_output_string")
($open-output-procedure::obj (::procedure ::procedure ::procedure ::bstring) "bgl_open_output_procedure")
($close-input-port::obj (::obj) "bgl_close_input_port")
($input-port-reopen!::obj (::input-port) "bgl_input_port_reopen")
($input-port-clone!::input-port (::input-port ::input-port) "bgl_input_port_clone")
($set-input-port-position!::void (::input-port ::long) "bgl_input_port_seek")
(macro c-input-port-position::long (::input-port)
"INPUT_PORT_FILEPOS")
(macro $input-port-fill-barrier::long (::input-port)
"INPUT_PORT_FILLBARRIER")
(macro $input-port-fill-barrier-set!::void (::input-port ::long)
"INPUT_PORT_FILLBARRIER_SET")
(macro $input-port-length::elong (::input-port)
"BGL_INPUT_PORT_LENGTH")
(macro $input-port-length-set!::void (::input-port ::elong)
"BGL_INPUT_PORT_LENGTH_SET")
(macro c-input-port-last-token-position::elong (::input-port)
"INPUT_PORT_TOKENPOS")
(macro c-input-port-bufsiz::long (::input-port)
"BGL_INPUT_PORT_BUFSIZ")
(macro c-closed-input-port?::bool (::obj)
"INPUT_PORT_CLOSEP")
(macro $closed-output-port?::bool (::obj)
"OUTPUT_PORT_CLOSEP")
(macro c-output-port-position::long (::output-port)
"BGL_OUTPUT_PORT_FILEPOS")
(c-set-output-port-position!::obj (::output-port ::long) "bgl_output_port_seek")
($close-output-port::obj (::output-port) "bgl_close_output_port")
(c-get-output-string::bstring (::output-port)"get_output_string")
(c-default-io-bufsiz::long "default_io_bufsiz")
(c-reset-eof::bool (::obj) "reset_eof")
(macro c-flush-output-port::obj (::output-port)
"bgl_flush_output_port")
(macro $reset-output-string-port::obj (::output-port)
"bgl_reset_output_string_port")
(macro $reset-output-port-error::obj (::output-port)
"bgl_reset_output_port_error")
(c-fexists?::bool (::string) "fexists")
(macro c-delete-file::bool (::string) "unlink")
(macro c-delete-directory::bool (::string) "rmdir")
(macro c-rename-file::int (::string ::string) "rename")
(macro $truncate-file::int (::string ::long) "truncate")
(macro $ftruncate::int (::output-port ::long) "bgl_output_port_truncate")
(macro c-mkdir::bool (::string ::long) "!BGL_MKDIR")
(macro $port-isatty?::bool (::output-port) "bgl_port_isatty")
(macro $output-port-name::bstring (::output-port) "OUTPUT_PORT_NAME")
(macro $output-port-name-set!::void (::output-port ::bstring) "OUTPUT_PORT_NAME_SET")
(macro $input-port-name::bstring (::input-port) "INPUT_PORT_NAME")
(macro $input-port-name-set!::void (::input-port ::bstring) "INPUT_PORT_NAME_SET")
(macro c-output-port-chook::obj (::output-port)
"PORT_CHOOK")
(macro c-output-port-chook-set!::void (::output-port ::procedure)
"PORT_CHOOK_SET")
(macro $output-port-fhook::obj (::output-port)
"BGL_OUTPUT_PORT_FHOOK")
(macro $output-port-fhook-set!::void (::output-port ::obj)
"BGL_OUTPUT_PORT_FHOOK_SET")
(macro $output-port-flushbuf::obj (::output-port)
"BGL_OUTPUT_PORT_FLUSHBUF")
(macro $output-port-flushbuf-set!::void (::output-port ::obj)
"BGL_OUTPUT_PORT_FLUSHBUF_SET")
(macro $input-port-chook::obj (::input-port)
"PORT_CHOOK")
(macro $input-port-chook-set!::void (::input-port ::procedure)
"PORT_CHOOK_SET")
(macro $input-port-useek::obj (::input-port)
"BGL_INPUT_PORT_USEEK")
(macro $input-port-useek-set!::void (::input-port ::procedure)
"BGL_INPUT_PORT_USEEK_SET")
(macro $input-port-buffer::bstring (::input-port)
"BGL_INPUT_PORT_BUFFER")
(macro $input-port-buffer-set!::void (::input-port ::bstring)
"bgl_input_port_buffer_set")
(macro $output-port-buffer::bstring (::output-port)
"BGL_OUTPUT_PORT_BUFFER")
(macro $output-port-buffer-set!::void (::output-port ::bstring)
"bgl_output_port_buffer_set")
($directory?::bool (::string) "bgl_directoryp")
($directory->list::obj (::string) "bgl_directory_to_list")
($directory->path-list::obj (::string ::int ::char)
"bgl_directory_to_path_list")
($modification-time::elong (::string) "bgl_last_modification_time")
($change-time::elong (::string) "bgl_last_change_time")
($access-time::elong (::string) "bgl_last_access_time")
($utime::int (::string ::elong ::elong) "bgl_utime")
($file-size::elong (::string) "bgl_file_size")
($file-uid::long (::string) "bgl_file_uid")
($file-gid::long (::string) "bgl_file_gid")
($file-mode::long (::string) "bgl_file_mode")
($file-type::symbol (::string) "bgl_file_type")
($symlink::int (::string ::string) "bgl_symlink")
($select::pair-nil (::long ::pair-nil ::pair-nil ::pair-nil) "bgl_select")
($open-pipes::obj (::obj) "bgl_open_pipes")
($lockf::bool (::output-port ::int ::long) "bgl_lockf")
(macro $F_LOCK::int "F_LOCK")
(macro $F_TLOCK::int "F_TLOCK")
(macro $F_ULOCK::int "F_ULOCK")
(macro $F_TEST::int "F_TEST"))
(java (class foreign
(method static c-input-port?::bool (::obj)
"INPUT_PORTP")
(method static c-input-string-port?::bool (::obj)
"INPUT_STRING_PORTP")
(method static c-input-procedure-port?::bool (::obj)
"INPUT_PROCEDURE_PORTP")
(method static c-input-gzip-port?::bool (::obj)
"INPUT_GZIP_PORTP")
(method static c-output-port?::bool (::obj)
"OUTPUT_PORTP")
(method static c-output-string-port?::bool (::obj)
"OUTPUT_STRING_PORTP")
(method static c-output-procedure-port?::bool (::obj)
"OUTPUT_PROCEDURE_PORTP")
(field static c-default-io-bufsiz::int
"default_io_bufsiz")
(method static c-current-output-port::output-port (::dynamic-env)
"getCurrentOutputPort")
(method static c-current-error-port::output-port (::dynamic-env)
"getCurrentErrorPort")
(method static c-current-input-port::input-port (::dynamic-env)
"getCurrentInputPort")
(method static c-current-output-port-set!::void (::dynamic-env ::output-port)
"setCurrentOutputPort")
(method static c-current-error-port-set!::void (::dynamic-env ::output-port)
"setCurrentErrorPort")
(method static c-current-input-port-set!::void (::dynamic-env ::input-port)
"setCurrentInputPort")
(method static $open-input-file::obj (::bstring ::bstring)
"bgl_open_input_file")
(method static $open-input-descriptor::obj (::int ::bstring)
"bgl_open_input_descriptor")
(method static $open-input-pipe::obj (::bstring ::bstring)
"bgl_open_input_pipe")
(method static $open-input-resource::obj (::bstring ::bstring)
"bgl_open_input_resource")
(method static $open-input-c-string::obj (::string)
"bgl_open_input_c_string")
(method static $reopen-input-c-string::obj (::input-port ::string)
"bgl_reopen_input_c_string")
(method static $open-input-substring::input-port (::bstring ::int ::int)
"bgl_open_input_substring")
(method static $open-input-substring!::input-port (::bstring ::int ::int)
"bgl_open_input_substring_bang")
(method static $open-input-procedure::obj (::procedure ::bstring)
"bgl_open_input_procedure")
(method static $input-port-timeout-set!::bool (::input-port ::long)
"bgl_input_port_timeout_set")
(method static $output-port-timeout-set!::bool (::output-port ::long)
"bgl_output_port_timeout_set")
(method static $open-output-file::obj (::bstring ::bstring)
"bgl_open_output_file")
(method static $append-output-file::obj (::bstring ::bstring)
"bgl_append_output_file")
(method static $open-output-string::output-port (::bstring)
"bgl_open_output_string")
(method static $open-output-procedure::obj (::procedure ::procedure ::procedure ::bstring)
"bgl_open_output_procedure")
(method static $close-input-port::obj (::input-port)
"bgl_close_input_port")
(method static $input-port-reopen!::obj (::input-port)
"bgl_input_port_reopen")
(method static $input-port-clone!::input-port (::input-port ::input-port)
"bgl_input_port_clone")
(method static $set-input-port-position!::void (::input-port ::long)
"bgl_input_port_seek")
(method static c-set-output-port-position!::obj (::output-port ::long)
"bgl_output_port_seek")
(method static c-input-port-bufsiz::int (::input-port)
"bgl_input_port_bufsiz")
(method static c-closed-input-port?::bool (::input-port)
"CLOSED_RGC_BUFFER")
(method static $closed-output-port?::bool (::output-port)
"CLOSED_OUTPUT_PORT")
(method static $close-output-port::obj (::output-port)
"bgl_close_output_port")
(method static c-get-output-string::bstring (::output-port)
"get_output_string")
(method static c-reset-eof::bool (::obj)
"reset_eof")
(method static c-flush-output-port::obj (::output-port)
"FLUSH_OUTPUT_PORT")
(method static $reset-output-string-port::obj (::output-port)
"bgl_reset_output_string_port")
(method static $reset-output-port-error::obj (::output-port)
"bgl_reset_output_port_error")
(method static c-fexists?::bool (::string)
"fexists")
(method static c-delete-file::bool (::string)
"unlink")
(method static c-delete-directory::bool (::string)
"rmdir")
(method static c-rename-file::int (::string ::string)
"rename")
(method static $truncate-file::int (::string ::long)
"truncate")
(method static $ftruncate::bool (::output-port ::long)
"bgl_output_port_truncate")
(method static c-mkdir::bool (::string ::int)
"mkdir")
(method static c-output-port-position::long (::output-port)
"OUTPUT_PORT_FILEPOS")
(method static c-input-port-position::long (::input-port)
"INPUT_PORT_FILEPOS")
(method static $input-port-fill-barrier::long (::input-port)
"INPUT_PORT_FILLBARRIER")
(method static $input-port-fill-barrier-set!::void (::input-port ::long)
"INPUT_PORT_FILLBARRIER_SET")
(method static $input-port-length::elong (::input-port)
"BGL_INPUT_PORT_LENGTH")
(method static $input-port-length-set!::void (::input-port ::elong)
"BGL_INPUT_PORT_LENGTH_SET")
(method static c-input-port-last-token-position::long (::input-port)
"INPUT_PORT_TOKENPOS")
(method static $input-port-name-set!::void (::input-port ::bstring)
"INPUT_PORT_NAME")
(method static $input-port-name::bstring (::input-port)
"INPUT_PORT_NAME")
(method static $output-port-name::bstring (::output-port)
"OUTPUT_PORT_NAME")
(method static $output-port-name-set!::void (::output-port ::bstring)
"OUTPUT_PORT_NAME_SET")
(method static c-output-port-chook::obj (::output-port)
"OUTPUT_PORT_CHOOK")
(method static c-output-port-chook-set!::void (::output-port ::procedure)
"OUTPUT_PORT_CHOOK_SET")
(method static $output-port-fhook::obj (::output-port)
"OUTPUT_PORT_FHOOK")
(method static $output-port-fhook-set!::void (::output-port ::obj)
"OUTPUT_PORT_FHOOK_SET")
(method static $output-port-flushbuf::obj (::output-port)
"OUTPUT_PORT_FLUSHBUF")
(method static $output-port-flushbuf-set!::void (::output-port ::obj)
"OUTPUT_PORT_FLUSHBUF_SET")
(method static $input-port-chook::obj (::input-port)
"INPUT_PORT_CHOOK")
(method static $input-port-chook-set!::void (::input-port ::procedure)
"INPUT_PORT_CHOOK_SET")
(method static $input-port-useek::obj (::input-port)
"INPUT_PORT_USEEK")
(method static $input-port-useek-set!::void (::input-port ::procedure)
"INPUT_PORT_USEEK_SET")
(method static $input-port-buffer::bstring (::input-port)
"BGL_INPUT_PORT_BUFFER")
(method static $input-port-buffer-set!::void (::input-port ::bstring)
"bgl_input_port_buffer_set")
(method static $output-port-buffer::bstring (::output-port)
"BGL_OUTPUT_PORT_BUFFER")
(method static $output-port-buffer-set!::void (::output-port ::bstring)
"bgl_output_port_buffer_set")
(method static c-input-gzip-port-input-port::input-port (::input-port)
"BGL_INPUT_GZIP_PORT_INPUT_PORT")
(method static $directory?::bool (::string)
"bgl_directoryp")
(method static $directory->list::obj (::string)
"bgl_directory_to_list")
(method static $modification-time::elong (::string)
"bgl_last_modification_time")
(method static $change-time::elong (::string)
"bgl_last_change_time")
(method static $access-time::elong (::string)
"bgl_last_access_time")
(method static $utime::int (::string ::elong ::elong)
"bgl_utime")
(method static $file-size::elong (::string)
"bgl_file_size")
(method static $file-uid::int (::string)
"bgl_file_uid")
(method static $file-gid::int (::string)
"bgl_file_gid")
(method static $file-mode::int (::string)
"bgl_file_mode")
(method static $file-type::symbol (::string)
"bgl_file_type")
(method static $symlink::int (::string ::string)
"bgl_symlink")
(method static $select::pair-nil (::long ::pair-nil ::pair-nil ::pair-nil)
"bgl_select")
(method static $open-pipes::obj (::obj)
"bgl_open_pipes")))
(export (call-with-input-file ::bstring ::procedure)
(call-with-input-string ::bstring ::procedure)
(call-with-output-file ::bstring ::procedure)
(call-with-append-file ::bstring ::procedure)
(call-with-output-string::bstring ::procedure)
(inline input-port? ::obj)
(inline input-string-port? ::obj)
(inline input-procedure-port? ::obj)
(inline input-gzip-port? ::obj)
(inline output-port? ::obj)
(inline port?::bool ::obj)
(inline output-string-port? ::obj)
(inline output-procedure-port? ::obj)
(inline current-input-port::input-port)
(inline current-error-port::output-port)
(inline current-output-port::output-port)
(with-input-from-file ::bstring ::procedure)
(with-input-from-string ::bstring ::procedure)
(with-input-from-port ::input-port ::procedure)
(with-input-from-procedure ::procedure ::procedure)
(with-output-to-file ::bstring ::procedure)
(with-append-to-file ::bstring ::procedure)
(with-output-to-string::bstring ::procedure)
(with-error-to-string::bstring ::procedure)
(with-output-to-port ::output-port ::procedure)
(with-output-to-procedure ::procedure ::procedure)
(with-error-to-file ::bstring ::procedure)
(with-error-to-port ::output-port ::procedure)
(with-error-to-procedure ::procedure ::procedure)
(open-input-file ::bstring #!optional (bufinfo #t) (timeout 5000000))
(open-input-descriptor ::int #!optional (bufinfo #t))
(open-input-string::input-port string::bstring
#!optional (start 0) (end (string-length string)))
(open-input-string!::input-port string::bstring
#!optional (start 0) (end (string-length string)))
(open-input-procedure ::procedure #!optional (bufinfo #t))
(open-input-gzip-port ::input-port #!optional (bufinfo #t))
(inline input-port-timeout-set! ::input-port ::long)
(inline open-input-c-string ::string)
(inline reopen-input-c-string ::input-port ::string)
(open-output-file ::bstring #!optional (bufinfo #t))
(append-output-file ::bstring #!optional (bufinfo #t))
(open-output-string::output-port #!optional (bufinfo #t))
(open-output-procedure ::procedure #!optional (flush::procedure (lambda () #f)) (bufinfo #t) (close::procedure (lambda () #f)))
(inline output-port-timeout-set! ::output-port ::long)
(inline closed-input-port?::bool ::input-port)
(inline close-input-port ::input-port)
(inline get-output-string::bstring ::output-port)
(inline close-output-port ::output-port)
(inline flush-output-port ::output-port)
(inline reset-output-port ::output-port)
(inline reset-eof::bool ::input-port)
(inline output-port-name::bstring ::output-port)
(inline output-port-name-set! ::output-port ::bstring)
(inline output-port-position::long ::output-port)
(inline output-port-isatty?::bool ::output-port)
(inline set-output-port-position! ::output-port ::long)
(set-input-port-position! ::input-port ::long)
(inline input-port-position::long ::input-port)
(inline input-port-fill-barrier ::input-port)
(inline input-port-fill-barrier-set! ::input-port ::long)
(inline input-port-last-token-position::long ::input-port)
(inline input-port-reopen! ::input-port)
(inline input-port-clone! ::input-port ::input-port)
(inline input-port-name::bstring ::input-port)
(inline input-port-name-set! ::input-port ::bstring)
(inline input-port-length::elong ::input-port)
(inline output-port-close-hook::obj ::output-port)
(inline closed-output-port?::bool ::output-port)
(output-port-close-hook-set! ::output-port ::procedure)
(inline output-port-flush-hook::obj ::output-port)
(output-port-flush-hook-set! ::output-port ::obj)
(inline output-port-flush-buffer::obj ::output-port)
(inline output-port-flush-buffer-set! ::output-port ::obj)
(inline input-port-close-hook::obj ::input-port)
(input-port-close-hook-set! ::input-port ::procedure)
(inline input-port-seek::procedure ::input-port)
(input-port-seek-set! ::input-port ::procedure)
(inline input-port-buffer::bstring ::input-port)
(inline input-port-buffer-set! ::input-port ::bstring)
(inline output-port-buffer::bstring ::output-port)
(inline output-port-buffer-set! ::output-port ::bstring)
(inline file-exists?::bool ::string)
(file-gzip? name)
(inline delete-file ::string)
(inline make-directory::bool ::string)
(make-directories::bool ::bstring)
(inline delete-directory ::string)
(inline rename-file::bool ::string ::string)
(inline truncate-file::bool ::string ::long)
(inline output-port-truncate::bool ::output-port ::long)
(copy-file ::string ::string)
(inline directory?::bool ::string)
(inline directory->list ::string)
(directory->path-list ::bstring)
(inline file-modification-time::elong ::string)
(inline file-change-time::elong ::string)
(inline file-access-time::elong ::string)
(inline file-times-set!::int ::string ::elong ::elong)
(inline file-size::elong ::string)
(inline file-uid::int ::string)
(inline file-gid::int ::string)
(inline file-mode::int ::string)
(inline file-type::symbol ::string)
(inline make-symlink ::bstring ::bstring)
(inline select::pair-nil #!key (timeout 0) (read '()) (write '()) (except '()))
(inline open-pipes #!optional name)
(input-port-protocol prototcol)
(input-port-protocol-set! protocol open)
(get-port-buffer::bstring ::obj ::obj ::int)
(lockf::bool ::output-port ::symbol #!optional (len 0)))
(pragma (c-input-port? (predicate-of input-port) nesting)
(c-output-port? (predicate-of output-port) nesting)
(c-output-string-port? nesting)
(c-input-string-port? nesting)
(file-exists? side-effect-free nesting)))
(define (call-with-input-file string proc)
(let ((port (open-input-file string)))
(if (input-port? port)
(unwind-protect
(proc port)
(close-input-port port))
(error/errno $errno-io-port-error
"call-with-input-file" "can't open file" string))))
(define (call-with-input-string string proc)
(let ((port (open-input-string string)))
(let ((res (proc port)))
(close-input-port port)
res)))
(define (call-with-output-file string proc)
(let ((port (open-output-file string)))
(if (output-port? port)
(unwind-protect
(proc port)
(close-output-port port))
(error/errno $errno-io-port-error
"call-with-output-file" "can't open file" string))))
(define (call-with-append-file string proc)
(let ((port (append-output-file string)))
(if (output-port? port)
(unwind-protect
(proc port)
(close-output-port port))
(error/errno $errno-io-port-error
"call-with-append-file" "can't open file" string))))
(define (call-with-output-string proc)
(let ((port (open-output-string)))
(proc port)
(close-output-port port)))
(define-inline (input-port? obj)
(c-input-port? obj))
(define-inline (input-string-port? obj)
(c-input-string-port? obj))
(define-inline (input-procedure-port? obj)
(c-input-procedure-port? obj))
(define-inline (input-gzip-port? obj)
(c-input-gzip-port? obj))
(define-inline (output-port? obj)
(c-output-port? obj))
(define-inline (output-string-port? obj)
(c-output-string-port? obj))
(define-inline (output-procedure-port? obj)
(c-output-procedure-port? obj))
(define-inline (current-input-port)
(c-current-input-port ($current-dynamic-env)))
(define-inline (current-output-port)
(c-current-output-port ($current-dynamic-env)))
(define-inline (current-error-port)
(c-current-error-port ($current-dynamic-env)))
(define-inline (input-port-reopen! port::input-port)
(unless ($input-port-reopen! port)
(error/errno
$errno-io-port-error "input-port-reopen!" "Cannot reopen port" port)))
(define-inline (input-port-clone! dst::input-port src::input-port)
($input-port-clone! dst src))
(define (with-input-from-file string thunk)
(let ((port (open-input-file string)))
(if (input-port? port)
(let* ((denv ($current-dynamic-env))
(old-input-port (c-current-input-port denv)))
(unwind-protect
(begin
(c-current-input-port-set! denv port)
(thunk))
(begin
(c-current-input-port-set! denv old-input-port)
(close-input-port port))))
(error/errno $errno-io-port-error
"with-input-from-file" "can't open file" string))))
(define (with-input-from-string string thunk)
(let* ((port (open-input-string string))
(denv ($current-dynamic-env))
(old-input-port (c-current-input-port denv)))
(unwind-protect
(begin
(c-current-input-port-set! denv port)
(thunk))
(begin
(c-current-input-port-set! denv old-input-port)
(close-input-port port)))))
(define (with-input-from-port port thunk)
(let* ((denv ($current-dynamic-env))
(old-input-port (c-current-input-port denv)))
(unwind-protect
(begin
(c-current-input-port-set! denv port)
(thunk))
(c-current-input-port-set! denv old-input-port))))
(define (with-input-from-procedure proc thunk)
(let ((port (open-input-procedure proc)))
(if (input-port? port)
(let* ((denv ($current-dynamic-env))
(old-input-port (c-current-input-port denv)))
(unwind-protect
(begin
(c-current-input-port-set! denv port)
(thunk))
(begin
(c-current-input-port-set! denv old-input-port)
(close-input-port port))))
(error "with-input-from-procedure" "can't open procedure" proc))))
(define (with-output-to-file string thunk)
(let ((port (open-output-file string)))
(if (output-port? port)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv)))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(begin
(c-current-output-port-set! denv old-output-port)
(close-output-port port))))
(error/errno $errno-io-port-error
"with-output-to-file" "can't open file" string))))
(define (with-append-to-file string thunk)
(let ((port (append-output-file string)))
(if (output-port? port)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv)))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(begin
(c-current-output-port-set! denv old-output-port)
(close-output-port port))))
(error/errno $errno-io-port-error
"with-output-to-file" "can't open file" string))))
(define (with-output-to-port port thunk)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv)))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(c-current-output-port-set! denv old-output-port))))
(define (with-output-to-string thunk)
(let* ((port (open-output-string))
(denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv))
(res #unspecified))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(begin
(c-current-output-port-set! denv old-output-port)
(set! res (close-output-port port))))
res))
(define (with-output-to-procedure proc thunk)
(let* ((port (open-output-procedure proc))
(denv ($current-dynamic-env))
(old-output-port (c-current-output-port denv))
(res #unspecified))
(unwind-protect
(begin
(c-current-output-port-set! denv port)
(thunk))
(begin
(c-current-output-port-set! denv old-output-port)
(set! res (close-output-port port))))
res))
(define (with-error-to-string thunk)
(let ((port (open-output-string)))
(if (output-port? port)
(let* ((denv ($current-dynamic-env))
(old-error-port (c-current-error-port denv))
(res #unspecified))
(unwind-protect
(begin
(c-current-error-port-set! denv port)
(thunk))
(begin
(c-current-error-port-set! denv old-error-port)
(set! res (close-output-port port))))
res)
(error/errno $errno-io-port-error
'with-error-to-string
"can't open string"
#unspecified))))
(define (with-error-to-file string thunk)
(let ((port (open-output-file string)))
(if (output-port? port)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-error-port denv)))
(unwind-protect
(begin
(c-current-error-port-set! denv port)
(thunk))
(begin
(c-current-error-port-set! denv old-output-port)
(close-output-port port))))
(error/errno $errno-io-port-error
'with-error-to-file
"can't open file"
string))))
(define (with-error-to-port port thunk)
(let* ((denv ($current-dynamic-env))
(old-output-port (c-current-error-port denv)))
(unwind-protect
(begin
(c-current-error-port-set! denv port)
(thunk))
(c-current-error-port-set! denv old-output-port))))
(define (with-error-to-procedure proc thunk)
(let* ((port (open-output-procedure proc))
(denv ($current-dynamic-env))
(old-error-port (c-current-error-port denv))
(res #unspecified))
(unwind-protect
(begin
(c-current-error-port-set! denv port)
(thunk))
(begin
(c-current-error-port-set! denv old-error-port)
(set! res (close-output-port port))))
res))
(define *input-port-protocols-mutex* (make-mutex "input-port-protocols"))
(define *input-port-protocols*
`(("file:" . ,%open-input-file)
("string:" . ,(lambda (s p tmt) (open-input-string s)))
("| " . ,%open-input-pipe)
("pipe:" . ,%open-input-pipe)
("http://" . ,%open-input-http-socket)
("gzip:" . ,open-input-gzip-file)
("zlib:" . ,open-input-zlib-file)
("inflate:" . ,open-input-inflate-file)
("/resource/" . ,%open-input-resource)
("ftp://" . ,open-input-ftp-file)
("fd:" . ,%open-input-descriptor)))
(define (input-port-protocols)
(synchronize *input-port-protocols-mutex*
(reverse! (reverse *input-port-protocols*))))
(define (input-port-protocol prototcol)
(let ((cell (synchronize *input-port-protocols-mutex*
(assoc prototcol *input-port-protocols*))))
(if (pair? cell)
(cdr cell)
#f)))
(define (input-port-protocol-set! protocol open)
(synchronize *input-port-protocols-mutex*
(unless (and (procedure? open) (correct-arity? open 3))
(error "input-port-protocol-set!"
"Illegal open procedure for protocol"
protocol))
(let ((c (assoc protocol *input-port-protocols*)))
(if (pair? c)
(set-cdr! c open)
(set! *input-port-protocols*
(cons (cons protocol open) *input-port-protocols*)))))
open)
(define (get-port-buffer who bufinfo defsiz)
(cond
((eq? bufinfo #t)
($make-string/wo-fill defsiz))
((eq? bufinfo #f)
($make-string/wo-fill 2))
((string? bufinfo)
bufinfo)
((fixnum? bufinfo)
(if (>=fx bufinfo 2)
($make-string/wo-fill bufinfo)
($make-string/wo-fill 2)))
(else
(error who "Illegal buffer" bufinfo))))
(define (%open-input-file string buf tmt)
($open-input-file string buf))
(define (%open-input-descriptor string buf tmt)
(let ((fd (string->integer (substring string 3))))
($open-input-descriptor fd buf)))
(define-inline (%open-input-pipe string bufinfo tmt)
(let ((buf (get-port-buffer "open-input-pipe" bufinfo 1024)))
($open-input-pipe string buf)))
(define (%open-input-resource file bufinfo tmt)
(let ((buf (get-port-buffer "open-input-file" bufinfo c-default-io-bufsiz)))
($open-input-resource file buf)))
(define (%open-input-http-socket string bufinfo timeout)
(define (parser ip status-code header clen tenc)
(when (and (>=fx status-code 200) (<=fx status-code 299))
(cond
((not (input-port? ip))
(open-input-string ""))
((and (elong? clen) (>elong clen 0))
(input-port-fill-barrier-set! ip (elong->fixnum clen))
($input-port-length-set! ip clen)
ip)
(else
ip))))
(multiple-value-bind (protocol login host port abspath)
(url-sans-protocol-parse string "http")
(let loop ((ip #f)
(header '((user-agent: "Mozilla/5.0") (Connection: close))))
(let* ((sock (http :host host
:port port
:login login
:path abspath
:timeout timeout
:header header))
(op (socket-output sock)))
(if (input-port? ip)
(input-port-clone! ip (socket-input sock))
(set! ip (socket-input sock)))
(input-port-close-hook-set! ip
(lambda (ip)
(close-output-port op)
(socket-close sock)))
(input-port-seek-set! ip
(lambda (ip offset)
(socket-close sock)
(let ((r (string-append "bytes=" (integer->string offset) "-")))
(loop ip `((range: ,r) (user-agent: "Mozilla/5.0"))))))
(with-handler
(lambda (e)
(socket-close sock)
(when (isa? e &http-redirection)
(with-access::&http-redirection e (url)
(open-input-file url bufinfo))))
(http-parse-response ip op parser))))))
(define (open-input-file string #!optional (bufinfo #t) (timeout 5000000))
(let ((buffer (get-port-buffer "open-input-file" bufinfo c-default-io-bufsiz)))
(let loop ((protos *input-port-protocols*))
(if (null? protos)
(%open-input-file string buffer timeout)
(let* ((cell (car protos))
(ident (car cell))
(l (string-length ident))
(open (cdr cell)))
(if (substring=? string ident l)
(let ((name (substring string l (string-length string))))
(open name buffer timeout))
(loop (cdr protos))))))))
(define (open-input-descriptor fd #!optional (bufinfo #t))
(let ((buffer (get-port-buffer "open-input-file" bufinfo c-default-io-bufsiz)))
($open-input-descriptor fd buffer)))
(define (open-input-string string
#!optional (start 0) (end (string-length string)))
(cond
((<fx start 0)
(error "open-input-string" "Illegal start offset" start))
((>fx start (string-length string))
(error "open-input-string" "Start offset out of bounds" start))
((>fx start end)
(error "open-input-string" "Start offset greater than end" start))
((>fx end (string-length string))
(error "open-input-string" "End offset out of bounds" end))
(else
($open-input-substring string start end))))
(define (open-input-string! string
#!optional (start 0) (end (string-length string)))
(cond
((<fx start 0)
(error "open-input-string!" "Illegal start offset" start))
((>fx start (string-length string))
(error "open-input-string!" "Start offset out of bounds" start))
((>fx start end)
(error "open-input-string!" "Start offset greater than end" start))
((>fx end (string-length string))
(error "open-input-string!" "End offset out of bounds" end))
(else
($open-input-substring! string start end))))
(define (open-input-procedure proc #!optional (bufinfo #t))
(let ((buf (get-port-buffer "open-input-procedure" bufinfo 1024)))
($open-input-procedure proc buf)))
(define (open-input-gzip-port in::input-port #!optional (bufinfo #t))
(let ((buf (get-port-buffer "open-input-gzip-port" bufinfo c-default-io-bufsiz)))
(port->gzip-port in buf)))
(define-inline (open-input-c-string string)
($open-input-c-string string))
(define-inline (reopen-input-c-string port::input-port string)
($reopen-input-c-string port string))
(define-inline (input-port-timeout-set! port::input-port timeout::long)
($input-port-timeout-set! port timeout))
(define (open-output-file string #!optional (bufinfo #t))
(let ((buf (get-port-buffer "open-output-file" bufinfo c-default-io-bufsiz)))
($open-output-file string buf)))
(define (append-output-file string #!optional (bufinfo #t))
(let ((buf (get-port-buffer "append-output-file" bufinfo c-default-io-bufsiz)))
($append-output-file string buf)))
(define (open-output-string #!optional (bufinfo #t))
(let ((buf (get-port-buffer "open-output-file" bufinfo 128)))
($open-output-string buf)))
(define (open-output-procedure proc
#!optional
(flush::procedure (lambda () #f))
(bufinfo #t)
(close::procedure (lambda () #f)))
(cond
((not (correct-arity? proc 1))
(error/errno $errno-io-port-error
"open-output-procedure"
"Illegal write procedure"
proc))
((or (not (procedure? flush))
(not (correct-arity? flush 0)))
(error/errno $errno-io-port-error
"open-output-procedure"
"Illegal flush procedure"
flush))
((or (not (procedure? close))
(not (correct-arity? close 0)))
(error/errno $errno-io-port-error
"open-output-procedure"
"Illegal close procedure"
flush))
(else
(let ((buf (get-port-buffer "open-output-procedure" bufinfo 128)))
($open-output-procedure proc flush close buf)))))
(define-inline (output-port-timeout-set! port::output-port timeout::long)
($output-port-timeout-set! port timeout))
(define-inline (closed-input-port? port)
(c-closed-input-port? port))
(define-inline (close-input-port port)
($close-input-port port))
(define-inline (get-output-string port)
(c-get-output-string port))
(define-inline (close-output-port port)
($close-output-port port))
(define-inline (flush-output-port port)
(c-flush-output-port port))
(define-inline (reset-output-port port)
($reset-output-port-error port)
(if (c-output-string-port? port)
($reset-output-string-port port)
(flush-output-port port)))
(define-inline (reset-eof port)
(c-reset-eof port))
(define (set-input-port-position! port::input-port pos::long)
(let ((useek ($input-port-useek port)))
(if (procedure? useek)
(useek port pos)
($set-input-port-position! port pos)))
#unspecified)
(define-inline (input-port-position port)
(c-input-port-position port))
(define-inline (input-port-fill-barrier port::input-port)
($input-port-fill-barrier port))
(define-inline (input-port-fill-barrier-set! port::input-port pos::long)
($input-port-fill-barrier-set! port pos)
pos)
(define-inline (input-port-last-token-position port)
(c-input-port-last-token-position port))
(define-inline (output-port-name port)
($output-port-name port))
(define-inline (output-port-name-set! port name)
($output-port-name-set! port name))
(define-inline (set-output-port-position! port::output-port pos::long)
(unless (c-set-output-port-position! port pos)
(error/errno $errno-io-port-error
"set-output-port-position!" "Cannot seek port" port)))
(define-inline (output-port-position port)
(c-output-port-position port))
(define-inline (output-port-isatty? port)
(cond-expand
(bigloo-c ($port-isatty? port))
(else #t)))
(define-inline (input-port-name port)
($input-port-name port))
(define-inline (input-port-name-set! port name)
($input-port-name-set! port name))
(define-inline (input-port-length port)
($input-port-length port))
(define-inline (output-port-close-hook port)
(c-output-port-chook port))
(define-inline (closed-output-port? port)
($closed-output-port? port))
(define (output-port-close-hook-set! port proc)
(if (not (and (procedure? proc) (correct-arity? proc 1)))
(error/errno $errno-io-port-error
"output-port-close-hook-set!" "Illegal hook" proc)
(begin
(c-output-port-chook-set! port proc)
proc)))
(define-inline (output-port-flush-hook port)
($output-port-fhook port))
(define (output-port-flush-hook-set! port proc)
(if (and (procedure? proc) (not (correct-arity? proc 2)))
(error/errno $errno-io-port-error
"output-port-flush-hook-set!" "Illegal hook" proc)
(begin
($output-port-fhook-set! port proc)
proc)))
(define-inline (output-port-flush-buffer port)
($output-port-flushbuf port))
(define-inline (output-port-flush-buffer-set! port buf)
($output-port-flushbuf-set! port buf)
buf)
(define-inline (input-port-close-hook port)
($input-port-chook port))
(define (input-port-close-hook-set! port proc)
(if (not (and (procedure? proc) (correct-arity? proc 1)))
(error/errno $errno-io-port-error
"input-port-close-hook-set!" "Illegal hook" proc)
(begin
($input-port-chook-set! port proc)
proc)))
(define-inline (input-port-seek port)
($input-port-useek port))
(define (input-port-seek-set! port proc)
(if (not (and (procedure? proc) (correct-arity? proc 2)))
(error/errno $errno-io-port-error
"input-port-seek-set!" "Illegal seek procedure" proc)
(begin
($input-port-useek-set! port proc)
proc)))
(define-inline (input-port-buffer port)
($input-port-buffer port))
(define-inline (input-port-buffer-set! port buffer)
(begin ($input-port-buffer-set! port buffer) port))
(define-inline (output-port-buffer port)
($output-port-buffer port))
(define-inline (output-port-buffer-set! port buffer)
(begin ($output-port-buffer-set! port buffer) port))
(define-inline (file-exists? name)
(c-fexists? name))
(define (file-gzip? name)
(and (file-exists? name)
(with-input-from-file name
(lambda ()
(with-handler
(lambda (e)
#f)
(gunzip-parse-header (current-input-port)))))))
(define-inline (delete-file string)
(not (c-delete-file string)))
(define-inline (make-directory string)
(c-mkdir string #o777))
(define (make-directories string)
(or (directory? string)
(make-directory string)
(let ((dname (dirname string)))
(if (or (=fx (string-length dname) 0) (file-exists? dname))
#f
(let ((aux (make-directories dname)))
(if (char=? (string-ref string (-fx (string-length string) 1))
(file-separator))
aux
(make-directory string)))))))
(define-inline (delete-directory string)
(not (c-delete-directory string)))
(define-inline (rename-file string1 string2)
(if (eq? (c-rename-file string1 string2) 0) #t #f))
(define-inline (truncate-file path size)
($truncate-file path size))
(define-inline (output-port-truncate oport size)
($ftruncate oport size))
(define (copy-file string1 string2)
(let ((pi (open-input-binary-file string1)))
(when (binary-port? pi)
(let ((po (open-output-binary-file string2)))
(if (not (binary-port? po))
(begin
(close-binary-port pi)
#f)
(let ((s (make-string 1024)))
(let loop ((l (input-fill-string! pi s)))
(if (=fx l 1024)
(begin
(output-string po s)
(loop (input-fill-string! pi s)))
(begin
(output-string po (string-shrink! s l))
(close-binary-port pi)
(close-binary-port po)
#t)))))))))
(define-inline (port? obj)
(or (output-port? obj) (input-port? obj)))
(define-inline (directory? string)
($directory? string))
(define-inline (directory->list string)
($directory->list string))
(define (directory->path-list dir)
(let ((l (string-length dir)))
(cond
((=fx l 0)
'())
((char=? (string-ref dir (-fx l 1)) (file-separator))
(cond-expand
(bigloo-c
($directory->path-list dir (-fx l 1) (file-separator)))
(else
(map! (lambda (f) (string-append dir f))
(directory->list dir)))))
(else
(cond-expand
(bigloo-c
($directory->path-list dir l (file-separator)))
(else
(map! (lambda (f) (make-file-name dir f))
(directory->list dir))))))))
(define-inline (file-modification-time file)
($modification-time file))
(define-inline (file-change-time file)
($change-time file))
(define-inline (file-access-time file)
($access-time file))
(define-inline (file-times-set! file atime mtime)
($utime file atime mtime))
(define-inline (file-size file)
($file-size file))
* @deffn file - uid@ ... * /
(define-inline (file-uid file)
($file-uid file))
(define-inline (file-gid file)
($file-gid file))
(define-inline (file-mode file)
($file-mode file))
(define-inline (file-type file)
($file-type file))
(define-inline (make-symlink path1 path2)
($symlink path1 path2))
(define-inline (select #!key (timeout 0) (read '()) (write '()) (except '()))
($select timeout read write except))
(define-inline (open-pipes #!optional name)
($open-pipes name))
(define (lockf port cmd #!optional (len 0))
(cond-expand
(bigloo-c
(case cmd
((lock) ($lockf port $F_LOCK len))
((tlock) ($lockf port $F_TLOCK len))
((ulock) ($lockf port $F_ULOCK len))
((test) ($lockf port $F_TEST len))
(else (error "lockf" "Bad command" cmd))))
(else #f)))
|
cd684e181b056921ec8dbc8959f2c79801790264931eb3aff72296c8cdc146e0 | hatashiro/line | Types.hs | {-|
This module provides types to be used with "Line.Messaging.API".
-}
# LANGUAGE DuplicateRecordFields #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
module Line.Messaging.API.Types (
-- * Common types
-- | Re-exported for convenience.
module Line.Messaging.Common.Types,
-- * Message types
Messageable,
Message (..),
-- ** Text
Text (..),
-- ** Image
Image (..),
-- ** Video
Video (..),
-- ** Audio
Audio (..),
-- ** Location
Location (..),
-- ** Sticker
Sticker (..),
-- ** Image map
ImageMap (..),
ImageMapAction (..),
ImageMapArea,
-- ** Template
Template (..),
Buttons (..),
Confirm (..),
Carousel (..),
ImageCarousel (..),
Column (..),
ImageColumn (..),
Label,
TemplateAction (..),
DatetimeMode (..),
-- * Profile
Profile (..),
-- * Error types
APIError (..),
APIErrorBody (..),
) where
import Control.Applicative ((<|>))
import Control.Exception (SomeException)
import Data.Aeson (FromJSON(..), ToJSON(..), Value(..), object, (.:), (.=))
import Data.Aeson.Types (Pair)
import Data.Maybe (maybeToList)
import Line.Messaging.Common.Types
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as BL
-- | A type class representing types to be converted into 'Message'.
--
-- It has @toType@ and @toObject@ as its minimal complete definition, but it
-- is not recommended to define any extra instance, as the new type may not work
-- with the LINE APIs.
--
-- About existing messageable types, please refer to the following instances.
-- Each instance is matched with a message object described in
-- <-api/reference/#message-objects the LINE documentation>.
class Messageable a where
toType :: a -> T.Text
toObject :: a -> [Pair]
toValue :: a -> Value
toValue a = object $ ("type" .= toType a) : toObject a
-- | A type representing a message to be sent.
--
The data constructor converts ' ' into ' Message ' . It allows
different types of ' ' to be sent through a single API call .
--
-- An example usage is like below.
--
-- @
-- pushTextAndImage :: ID -> APIIO ()
-- pushTextAndImage identifier = push identifier [
-- Message $ 'Text' "hello",
-- Message $ 'Image' "" ""
-- ]
-- @
data Message = forall a. (Show a, Messageable a) => Message a
deriving instance Show Message
instance ToJSON Message where
toJSON (Message m) = toValue m
| ' ' for text data .
--
-- It contains 'T.Text' of "Data.Text". Its corresponding JSON spec is described
-- <-api/reference/#text here>.
--
-- This type is also used to decode text event message from webhook request.
-- About the webhook usage, please refer to
-- <./Line-Messaging-Webhook-Types.html#t:EventMessage EventMessage> in
-- "Line.Messaging.Webhook.Types".
newtype Text = Text { getText :: T.Text }
deriving (Eq, Ord, Show)
instance FromJSON Text where
parseJSON (Object v) = Text <$> v .: "text"
parseJSON (String text) = return $ Text text
parseJSON _ = fail "Text"
instance Messageable Text where
toType _ = "text"
toObject (Text text) = [ "text" .= text ]
| ' ' for image data .
--
-- It contains URLs of an original image and its preview. Its corresponding JSON
-- spec is described <-api/reference/#image here>.
data Image = Image { getURL :: URL
, getPreviewURL :: URL
}
deriving (Eq, Show)
instance Messageable Image where
toType _ = "image"
toObject (Image original preview) = [ "originalContentUrl" .= original
, "previewImageUrl" .= preview
]
| ' ' for video data .
--
-- It contains URLs of an original video and its preview. Its corresponding JSON
-- spec is described <-api/reference/#video here>.
data Video = Video { getURL :: URL
, getPreviewURL :: URL
}
deriving (Eq, Show)
instance Messageable Video where
toType _ = "video"
toObject (Video original preview) = [ "originalContentUrl" .= original
, "previewImageUrl" .= preview
]
| ' ' for audio data .
--
-- It contains a URL of an audio, and its duration in milliseconds. Its
-- corresponding JSON spec is described
-- <-api/reference/#audio here>.
data Audio = Audio { getURL :: URL
, getDuration :: Integer
}
deriving (Eq, Show)
instance Messageable Audio where
toType _ = "audio"
toObject (Audio original duration) = [ "originalContentUrl" .= original
, "duration" .= duration
]
| ' ' for location data .
--
-- It contains a title, address, and geographic coordination of a location.
-- Its corresponding JSON spec is described
-- <-api/reference/#location here>.
--
-- This type is also used to decode location event message from webhook request.
-- About the webhook usage, please refer to
-- <./Line-Messaging-Webhook-Types.html#t:EventMessage EventMessage> in
-- "Line.Messaging.Webhook.Types".
data Location = Location { getTitle :: T.Text
, getAddress :: T.Text
, getLatitude :: Double
, getLongitude :: Double
}
deriving (Eq, Show)
instance FromJSON Location where
parseJSON (Object v) = Location <$> v .: "title"
<*> v .: "address"
<*> v .: "latitude"
<*> v .: "longitude"
parseJSON _ = fail "Location"
instance Messageable Location where
toType _ = "location"
toObject (Location title address latitude longitude) = [ "title" .= title
, "address" .= address
, "latitude" .= latitude
, "longitude" .= longitude
]
| ' ' for sticker data .
--
-- It contains its package and sticker ID. Its corresponding JSON spec is
-- described <-api/reference/#sticker here>.
--
-- This type is also used to decode sticker event message from webhook request.
-- About the webhook usage, please refer to
-- <./Line-Messaging-Webhook-Types.html#t:EventMessage EventMessage> in
-- "Line.Messaging.Webhook.Types".
data Sticker = Sticker { getPackageID :: ID
, getStickerID :: ID
}
deriving (Eq, Show)
instance FromJSON Sticker where
parseJSON (Object v) = Sticker <$> v .: "packageId"
<*> v .: "stickerId"
parseJSON _ = fail "Sticker"
instance Messageable Sticker where
toType _ = "sticker"
toObject (Sticker packageId stickerId) = [ "packageId" .= packageId
, "stickerId" .= stickerId
]
| ' ' for image map data .
--
-- About how to send an image map message and what each field means, please
-- refer to
-- <-api/reference/#imagemap-message image map message spec>.
data ImageMap = ImageMap { getBaseImageURL :: URL
-- ^ <-api/reference/#base-url Base URL> of images
, getAltText :: T.Text
-- ^ Alt text for devices not supporting image map
, getBaseImageSize :: (Integer, Integer)
-- ^ Image size tuple, (width, height) specifically.
-- The width to be set to 1040, the height to be set to
-- the value corresponding to a width of 1040.
, getActions :: [ImageMapAction]
-- ^ Actions to be executed when each area is tapped
}
deriving (Eq, Show)
instance Messageable ImageMap where
toType _ = "imagemap"
toObject (ImageMap url alt (w, h) as) = [ "baseUrl" .= url
, "altText" .= alt
, "baseSize" .= object [ "width" .= w
, "height" .= h
]
, "actions" .= toJSON as
]
-- | A type representing actions when a specific area of an image map is tapped.
--
-- It contains action data and area information.
data ImageMapAction = IMURIAction URL ImageMapArea
-- ^ Open a web page when an area is tapped.
| IMMessageAction T.Text ImageMapArea
-- ^ Send a text message from the user who tapped an area.
deriving (Eq, Show)
instance ToJSON ImageMapAction where
toJSON (IMURIAction uri area) = object [ "type" .= ("uri" :: T.Text)
, "linkUri" .= uri
, "area" .= toAreaJSON area
]
toJSON (IMMessageAction text area) = object [ "type" .= ("message" :: T.Text)
, "text" .= text
, "area" .= toAreaJSON area
]
-- | A type representing a tappable area in an image map
--
-- Each component means (x, y, width, height) correspondingly.
type ImageMapArea = (Integer, Integer, Integer, Integer)
toAreaJSON :: ImageMapArea -> Value
toAreaJSON (x, y, w, h) = object [ "x" .= x, "y" .= y, "width" .= w, "height" .= h ]
| ' ' for template data .
--
-- It has a type parameter @t@ which means a template content type. The type is
polymolphic , but ' ' instances are defined only for ' Buttons ' ,
' Confirm ' , ' Carousel ' , and ' ImageCarousel ' .
--
-- About how to send template message and what each field means, please
-- refer to
-- <-api/reference/#template-messages template message spec>.
data Template t = Template { getAltText :: T.Text
-- ^ Alt text for devices not supporting template message
, getTemplateContent :: t
-- ^ Template content type
}
deriving (Eq, Show)
templateType :: Template a -> T.Text
templateType _ = "template"
templateToObject :: ToJSON a => Template a -> [Pair]
templateToObject (Template alt a) = [ "altText" .= alt
, "template" .= toJSON a
]
instance Messageable (Template Buttons) where
toType = templateType
toObject = templateToObject
instance Messageable (Template Confirm) where
toType = templateType
toObject = templateToObject
instance Messageable (Template Carousel) where
toType = templateType
toObject = templateToObject
instance Messageable (Template ImageCarousel) where
toType = templateType
toObject = templateToObject
-- | The buttons content type for template message.
--
-- <<-api/messages/buttons.png Buttons template>>
--
-- For more details of each field, please refer to the
-- <-api/reference/#buttons Buttons> section in the LINE
-- documentation.
data Buttons = Buttons { getThumbnailURL :: Maybe URL
-- ^ URL for thumbnail image
, getTitle :: Maybe T.Text
-- ^ Title text
, getText :: T.Text
-- ^ Description text
, getActions :: [TemplateAction]
-- ^ A list of template actions, each of which represents
a button ( max : 4 )
}
deriving (Eq, Show)
instance ToJSON Buttons where
toJSON (Buttons maybeURL maybeTitle text actions) =
object . concat $
[ [ "type" .= ("buttons" :: T.Text)
, "text" .= text
, "actions" .= toJSON actions
]
, maybeToList $ ("thumbnailImageUrl" .=) <$> maybeURL
, maybeToList $ ("title" .=) <$> maybeTitle
]
-- | The confirm content type for template message.
--
< < -api/messages/confirm.png Confirm template > >
--
-- For more details of each field, please refer to the
-- <-api/reference/#confirm Confirm> section in the LINE
-- documentation.
data Confirm = Confirm { getText :: T.Text
-- ^ Confirm text
, getActions :: [TemplateAction]
-- ^ A list of template actions, each of which represents
a button ( max : 2 )
}
deriving (Eq, Show)
instance ToJSON Confirm where
toJSON (Confirm text actions) = object [ "type" .= ("confirm" :: T.Text)
, "text" .= text
, "actions" .= toJSON actions
]
-- | The carousel content type for template message.
--
-- <<-api/messages/carousel.png Carousel template>>
--
-- For more details of each field, please refer to the
-- <-api/reference/#carousel Carousel> section in the LINE
-- documentation.
data Carousel = Carousel { getColumns :: [Column]
-- ^ A list of columns for a carousel template
}
deriving (Eq, Show)
instance ToJSON Carousel where
toJSON (Carousel columns) = object [ "type" .= ("carousel" :: T.Text)
, "columns" .= toJSON columns
]
-- | Actual contents of carousel template.
--
-- It has the same fields as 'Buttons', except that the number of actions is
up to 3 .
data Column = Column { getThumbnailURL :: Maybe URL
-- ^ URL for thumbnail image
, getTitle :: Maybe T.Text
-- ^ Title text
, getText :: T.Text
-- ^ Description text
, getActions :: [TemplateAction]
-- ^ A list of template actions, each of which represents
a button ( max : 3 )
}
deriving (Eq, Show)
instance ToJSON Column where
toJSON (Column maybeURL maybeTitle text actions) =
object . concat $
[ [ "text" .= text
, "actions" .= toJSON actions
]
, maybeToList $ ("thumbnailImageUrl" .=) <$> maybeURL
, maybeToList $ ("title" .=) <$> maybeTitle
]
-- | The image carousel content type for template message.
--
-- <<-api/messages/image-carousel.png Image carousel template>>
--
-- For more details of each field, please refer to the
-- <-api/reference/#image-carousel Image carousel> section in the LINE
-- documentation.
data ImageCarousel = ImageCarousel { getColumns :: [ImageColumn]
-- ^ A list of columns for an image carousel template
}
deriving (Eq, Show)
instance ToJSON ImageCarousel where
toJSON (ImageCarousel columns) = object [ "type" .= ("image_carousel" :: T.Text)
, "columns" .= toJSON columns
]
-- | Actual contents of carousel template.
--
-- It has the same fields as 'Buttons', except that the number of actions is
up to 3 .
data ImageColumn = ImageColumn { getImageURL :: URL
-- ^ URL for thumbnail image
, getAction :: TemplateAction
-- ^ A template action
}
deriving (Eq, Show)
instance ToJSON ImageColumn where
toJSON (ImageColumn url action) =
object [ "imageUrl" .= url
, "action" .= toJSON action
]
| Just a type alias for ' T.Text ' , used with ' TemplateAction ' .
type Label = T.Text
-- | A data type for possible template actions.
--
-- Each action object represents a button in template message. A button has a
-- label and an actual action fired by click.
data TemplateAction = TplMessageAction Label T.Text
-- ^ Message action. When clicked, a specified text will
-- be sent into the same room by a user who clicked the
-- button.
| TplPostbackAction Label T.Text (Maybe T.Text)
-- ^ Postback action. When clicked, a specified text will
-- be sent, and postback data will be sent to webhook
-- server as a postback event.
| TplURIAction Label URL
-- ^ URI action. When clicked, a web page with a specified
URI will open in the in - app browser .
| TplDatetimePickerAction { label' :: (Maybe Label)
, data' :: T.Text
, mode' :: DatetimeMode
, initial' :: (Maybe T.Text)
, max' :: (Maybe T.Text)
, min' :: (Maybe T.Text)
}
-- ^ Datetime picker action. When clicked, a postback action
-- will be sent with the date and time selected by the
-- user from the date and time selection dialog. For the
-- detailed information of datetime picker, please refer
-- to the <-api/reference/#datetime-picker-action official documentation>.
deriving (Eq, Show)
instance ToJSON TemplateAction where
toJSON (TplPostbackAction label data'' maybeText) =
object . concat $
[ [ "type" .= ("postback" :: T.Text)
, "label" .= label
, "data" .= data''
]
, maybeToList $ ("text" .=) <$> maybeText
]
toJSON (TplMessageAction label text) = object [ "type" .= ("message" :: T.Text)
, "label" .= label
, "text" .= text
]
toJSON (TplURIAction label uri) = object [ "type" .= ("uri" :: T.Text)
, "label" .= label
, "uri" .= uri
]
toJSON (TplDatetimePickerAction label data'' mode initial max'' min'') =
object . concat $ [ [ "type" .= ("datetimepicker" :: T.Text)
, "data" .= data''
, "mode" .= mode
]
, maybeToList $ ("label" .=) <$> label
, maybeToList $ ("initial" .=) <$> initial
, maybeToList $ ("max" .=) <$> max''
, maybeToList $ ("min" .=) <$> min''
]
data DatetimeMode = Date | Time | Datetime deriving (Eq, Show)
instance ToJSON DatetimeMode where
toJSON Date = "date"
toJSON Time = "time"
toJSON Datetime = "datetime"
-- | A type to represent a user's profile.
--
-- It is the return type of the <./Line-Messaging-API.html#v:getProfile getProfile>
-- API in the "Line.Messaging.API" module.
data Profile = Profile { getUserID :: ID
, getDisplayName :: T.Text
, getPictureURL :: Maybe URL
, getStatusMessage :: Maybe T.Text
}
deriving (Eq, Show)
instance FromJSON Profile where
parseJSON (Object v) = Profile <$> v .: "userId"
<*> v .: "displayName"
<*> v .: "pictureUrl"
<*> v .: "statusMessage"
parseJSON _ = fail "Profile"
-- | An error type possibly returned from the
-- @<./Line-Messaging-API.html#t:APIIO APIIO>@ type.
--
State code errors may contain a parsed error body . Other types of errors ,
-- which may rarely occur if used properly, does not.
--
-- For more details of error types, please refer to
-- <-api/reference/#status-codes Status codes> and
-- <-api/reference/#error-responses Error response> sections in the
-- LINE documentation.
data APIError = BadRequest (Maybe APIErrorBody)
^ 400 Bad Request with a parsed error body , caused by badly
-- formatted request.
| Unauthorized (Maybe APIErrorBody)
^ 401 Unauthorized with a parsed error body , caused by invalid
-- access token.
| Forbidden (Maybe APIErrorBody)
^ 403 Forbidden with a parsed error body , caused by
-- unauthorized account or plan.
| TooManyRequests (Maybe APIErrorBody)
^ 429 Too Many Requests with a parsed error body , caused by
-- exceeding the <-api/reference/#rate-limits rate limit>.
| InternalServerError (Maybe APIErrorBody)
^ 500 Internal Server Error with a parsed error body .
| UndefinedStatusCode Int BL.ByteString
^ Caused by status codes other than 200 and listed statuses
-- above, with the status code and request body.
| JSONDecodeError String
-- ^ Caused by badly formatted response body from APIs.
| UndefinedError SomeException
^ Any other exception caught as ' SomeException ' .
deriving Show
-- | An error body type.
--
-- It contains error message, and may contain property information and detailed
-- error bodies.
data APIErrorBody = APIErrorBody { getErrorMessage :: T.Text
, getErrorProperty :: Maybe T.Text
, getErrorDetails :: Maybe [APIErrorBody]
}
deriving (Eq, Show)
instance FromJSON APIErrorBody where
parseJSON (Object v) = APIErrorBody <$> v .: "message"
<*> (v .: "property" <|> return Nothing)
<*> (v .: "details" <|> return Nothing)
parseJSON _ = fail "APIErrorBody"
| null | https://raw.githubusercontent.com/hatashiro/line/3b5ddb0b98e5937d86157308512c1c96cd49c86a/src/Line/Messaging/API/Types.hs | haskell | |
This module provides types to be used with "Line.Messaging.API".
* Common types
| Re-exported for convenience.
* Message types
** Text
** Image
** Video
** Audio
** Location
** Sticker
** Image map
** Template
* Profile
* Error types
| A type class representing types to be converted into 'Message'.
It has @toType@ and @toObject@ as its minimal complete definition, but it
is not recommended to define any extra instance, as the new type may not work
with the LINE APIs.
About existing messageable types, please refer to the following instances.
Each instance is matched with a message object described in
<-api/reference/#message-objects the LINE documentation>.
| A type representing a message to be sent.
An example usage is like below.
@
pushTextAndImage :: ID -> APIIO ()
pushTextAndImage identifier = push identifier [
Message $ 'Text' "hello",
Message $ 'Image' "" ""
]
@
It contains 'T.Text' of "Data.Text". Its corresponding JSON spec is described
<-api/reference/#text here>.
This type is also used to decode text event message from webhook request.
About the webhook usage, please refer to
<./Line-Messaging-Webhook-Types.html#t:EventMessage EventMessage> in
"Line.Messaging.Webhook.Types".
It contains URLs of an original image and its preview. Its corresponding JSON
spec is described <-api/reference/#image here>.
It contains URLs of an original video and its preview. Its corresponding JSON
spec is described <-api/reference/#video here>.
It contains a URL of an audio, and its duration in milliseconds. Its
corresponding JSON spec is described
<-api/reference/#audio here>.
It contains a title, address, and geographic coordination of a location.
Its corresponding JSON spec is described
<-api/reference/#location here>.
This type is also used to decode location event message from webhook request.
About the webhook usage, please refer to
<./Line-Messaging-Webhook-Types.html#t:EventMessage EventMessage> in
"Line.Messaging.Webhook.Types".
It contains its package and sticker ID. Its corresponding JSON spec is
described <-api/reference/#sticker here>.
This type is also used to decode sticker event message from webhook request.
About the webhook usage, please refer to
<./Line-Messaging-Webhook-Types.html#t:EventMessage EventMessage> in
"Line.Messaging.Webhook.Types".
About how to send an image map message and what each field means, please
refer to
<-api/reference/#imagemap-message image map message spec>.
^ <-api/reference/#base-url Base URL> of images
^ Alt text for devices not supporting image map
^ Image size tuple, (width, height) specifically.
The width to be set to 1040, the height to be set to
the value corresponding to a width of 1040.
^ Actions to be executed when each area is tapped
| A type representing actions when a specific area of an image map is tapped.
It contains action data and area information.
^ Open a web page when an area is tapped.
^ Send a text message from the user who tapped an area.
| A type representing a tappable area in an image map
Each component means (x, y, width, height) correspondingly.
It has a type parameter @t@ which means a template content type. The type is
About how to send template message and what each field means, please
refer to
<-api/reference/#template-messages template message spec>.
^ Alt text for devices not supporting template message
^ Template content type
| The buttons content type for template message.
<<-api/messages/buttons.png Buttons template>>
For more details of each field, please refer to the
<-api/reference/#buttons Buttons> section in the LINE
documentation.
^ URL for thumbnail image
^ Title text
^ Description text
^ A list of template actions, each of which represents
| The confirm content type for template message.
For more details of each field, please refer to the
<-api/reference/#confirm Confirm> section in the LINE
documentation.
^ Confirm text
^ A list of template actions, each of which represents
| The carousel content type for template message.
<<-api/messages/carousel.png Carousel template>>
For more details of each field, please refer to the
<-api/reference/#carousel Carousel> section in the LINE
documentation.
^ A list of columns for a carousel template
| Actual contents of carousel template.
It has the same fields as 'Buttons', except that the number of actions is
^ URL for thumbnail image
^ Title text
^ Description text
^ A list of template actions, each of which represents
| The image carousel content type for template message.
<<-api/messages/image-carousel.png Image carousel template>>
For more details of each field, please refer to the
<-api/reference/#image-carousel Image carousel> section in the LINE
documentation.
^ A list of columns for an image carousel template
| Actual contents of carousel template.
It has the same fields as 'Buttons', except that the number of actions is
^ URL for thumbnail image
^ A template action
| A data type for possible template actions.
Each action object represents a button in template message. A button has a
label and an actual action fired by click.
^ Message action. When clicked, a specified text will
be sent into the same room by a user who clicked the
button.
^ Postback action. When clicked, a specified text will
be sent, and postback data will be sent to webhook
server as a postback event.
^ URI action. When clicked, a web page with a specified
^ Datetime picker action. When clicked, a postback action
will be sent with the date and time selected by the
user from the date and time selection dialog. For the
detailed information of datetime picker, please refer
to the <-api/reference/#datetime-picker-action official documentation>.
| A type to represent a user's profile.
It is the return type of the <./Line-Messaging-API.html#v:getProfile getProfile>
API in the "Line.Messaging.API" module.
| An error type possibly returned from the
@<./Line-Messaging-API.html#t:APIIO APIIO>@ type.
which may rarely occur if used properly, does not.
For more details of error types, please refer to
<-api/reference/#status-codes Status codes> and
<-api/reference/#error-responses Error response> sections in the
LINE documentation.
formatted request.
access token.
unauthorized account or plan.
exceeding the <-api/reference/#rate-limits rate limit>.
above, with the status code and request body.
^ Caused by badly formatted response body from APIs.
| An error body type.
It contains error message, and may contain property information and detailed
error bodies. |
# LANGUAGE DuplicateRecordFields #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
module Line.Messaging.API.Types (
module Line.Messaging.Common.Types,
Messageable,
Message (..),
Text (..),
Image (..),
Video (..),
Audio (..),
Location (..),
Sticker (..),
ImageMap (..),
ImageMapAction (..),
ImageMapArea,
Template (..),
Buttons (..),
Confirm (..),
Carousel (..),
ImageCarousel (..),
Column (..),
ImageColumn (..),
Label,
TemplateAction (..),
DatetimeMode (..),
Profile (..),
APIError (..),
APIErrorBody (..),
) where
import Control.Applicative ((<|>))
import Control.Exception (SomeException)
import Data.Aeson (FromJSON(..), ToJSON(..), Value(..), object, (.:), (.=))
import Data.Aeson.Types (Pair)
import Data.Maybe (maybeToList)
import Line.Messaging.Common.Types
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as BL
class Messageable a where
toType :: a -> T.Text
toObject :: a -> [Pair]
toValue :: a -> Value
toValue a = object $ ("type" .= toType a) : toObject a
The data constructor converts ' ' into ' Message ' . It allows
different types of ' ' to be sent through a single API call .
data Message = forall a. (Show a, Messageable a) => Message a
deriving instance Show Message
instance ToJSON Message where
toJSON (Message m) = toValue m
| ' ' for text data .
newtype Text = Text { getText :: T.Text }
deriving (Eq, Ord, Show)
instance FromJSON Text where
parseJSON (Object v) = Text <$> v .: "text"
parseJSON (String text) = return $ Text text
parseJSON _ = fail "Text"
instance Messageable Text where
toType _ = "text"
toObject (Text text) = [ "text" .= text ]
| ' ' for image data .
data Image = Image { getURL :: URL
, getPreviewURL :: URL
}
deriving (Eq, Show)
instance Messageable Image where
toType _ = "image"
toObject (Image original preview) = [ "originalContentUrl" .= original
, "previewImageUrl" .= preview
]
| ' ' for video data .
data Video = Video { getURL :: URL
, getPreviewURL :: URL
}
deriving (Eq, Show)
instance Messageable Video where
toType _ = "video"
toObject (Video original preview) = [ "originalContentUrl" .= original
, "previewImageUrl" .= preview
]
| ' ' for audio data .
data Audio = Audio { getURL :: URL
, getDuration :: Integer
}
deriving (Eq, Show)
instance Messageable Audio where
toType _ = "audio"
toObject (Audio original duration) = [ "originalContentUrl" .= original
, "duration" .= duration
]
| ' ' for location data .
data Location = Location { getTitle :: T.Text
, getAddress :: T.Text
, getLatitude :: Double
, getLongitude :: Double
}
deriving (Eq, Show)
instance FromJSON Location where
parseJSON (Object v) = Location <$> v .: "title"
<*> v .: "address"
<*> v .: "latitude"
<*> v .: "longitude"
parseJSON _ = fail "Location"
instance Messageable Location where
toType _ = "location"
toObject (Location title address latitude longitude) = [ "title" .= title
, "address" .= address
, "latitude" .= latitude
, "longitude" .= longitude
]
| ' ' for sticker data .
data Sticker = Sticker { getPackageID :: ID
, getStickerID :: ID
}
deriving (Eq, Show)
instance FromJSON Sticker where
parseJSON (Object v) = Sticker <$> v .: "packageId"
<*> v .: "stickerId"
parseJSON _ = fail "Sticker"
instance Messageable Sticker where
toType _ = "sticker"
toObject (Sticker packageId stickerId) = [ "packageId" .= packageId
, "stickerId" .= stickerId
]
| ' ' for image map data .
data ImageMap = ImageMap { getBaseImageURL :: URL
, getAltText :: T.Text
, getBaseImageSize :: (Integer, Integer)
, getActions :: [ImageMapAction]
}
deriving (Eq, Show)
instance Messageable ImageMap where
toType _ = "imagemap"
toObject (ImageMap url alt (w, h) as) = [ "baseUrl" .= url
, "altText" .= alt
, "baseSize" .= object [ "width" .= w
, "height" .= h
]
, "actions" .= toJSON as
]
data ImageMapAction = IMURIAction URL ImageMapArea
| IMMessageAction T.Text ImageMapArea
deriving (Eq, Show)
instance ToJSON ImageMapAction where
toJSON (IMURIAction uri area) = object [ "type" .= ("uri" :: T.Text)
, "linkUri" .= uri
, "area" .= toAreaJSON area
]
toJSON (IMMessageAction text area) = object [ "type" .= ("message" :: T.Text)
, "text" .= text
, "area" .= toAreaJSON area
]
type ImageMapArea = (Integer, Integer, Integer, Integer)
toAreaJSON :: ImageMapArea -> Value
toAreaJSON (x, y, w, h) = object [ "x" .= x, "y" .= y, "width" .= w, "height" .= h ]
| ' ' for template data .
polymolphic , but ' ' instances are defined only for ' Buttons ' ,
' Confirm ' , ' Carousel ' , and ' ImageCarousel ' .
data Template t = Template { getAltText :: T.Text
, getTemplateContent :: t
}
deriving (Eq, Show)
templateType :: Template a -> T.Text
templateType _ = "template"
templateToObject :: ToJSON a => Template a -> [Pair]
templateToObject (Template alt a) = [ "altText" .= alt
, "template" .= toJSON a
]
instance Messageable (Template Buttons) where
toType = templateType
toObject = templateToObject
instance Messageable (Template Confirm) where
toType = templateType
toObject = templateToObject
instance Messageable (Template Carousel) where
toType = templateType
toObject = templateToObject
instance Messageable (Template ImageCarousel) where
toType = templateType
toObject = templateToObject
data Buttons = Buttons { getThumbnailURL :: Maybe URL
, getTitle :: Maybe T.Text
, getText :: T.Text
, getActions :: [TemplateAction]
a button ( max : 4 )
}
deriving (Eq, Show)
instance ToJSON Buttons where
toJSON (Buttons maybeURL maybeTitle text actions) =
object . concat $
[ [ "type" .= ("buttons" :: T.Text)
, "text" .= text
, "actions" .= toJSON actions
]
, maybeToList $ ("thumbnailImageUrl" .=) <$> maybeURL
, maybeToList $ ("title" .=) <$> maybeTitle
]
< < -api/messages/confirm.png Confirm template > >
data Confirm = Confirm { getText :: T.Text
, getActions :: [TemplateAction]
a button ( max : 2 )
}
deriving (Eq, Show)
instance ToJSON Confirm where
toJSON (Confirm text actions) = object [ "type" .= ("confirm" :: T.Text)
, "text" .= text
, "actions" .= toJSON actions
]
data Carousel = Carousel { getColumns :: [Column]
}
deriving (Eq, Show)
instance ToJSON Carousel where
toJSON (Carousel columns) = object [ "type" .= ("carousel" :: T.Text)
, "columns" .= toJSON columns
]
up to 3 .
data Column = Column { getThumbnailURL :: Maybe URL
, getTitle :: Maybe T.Text
, getText :: T.Text
, getActions :: [TemplateAction]
a button ( max : 3 )
}
deriving (Eq, Show)
instance ToJSON Column where
toJSON (Column maybeURL maybeTitle text actions) =
object . concat $
[ [ "text" .= text
, "actions" .= toJSON actions
]
, maybeToList $ ("thumbnailImageUrl" .=) <$> maybeURL
, maybeToList $ ("title" .=) <$> maybeTitle
]
data ImageCarousel = ImageCarousel { getColumns :: [ImageColumn]
}
deriving (Eq, Show)
instance ToJSON ImageCarousel where
toJSON (ImageCarousel columns) = object [ "type" .= ("image_carousel" :: T.Text)
, "columns" .= toJSON columns
]
up to 3 .
data ImageColumn = ImageColumn { getImageURL :: URL
, getAction :: TemplateAction
}
deriving (Eq, Show)
instance ToJSON ImageColumn where
toJSON (ImageColumn url action) =
object [ "imageUrl" .= url
, "action" .= toJSON action
]
| Just a type alias for ' T.Text ' , used with ' TemplateAction ' .
type Label = T.Text
data TemplateAction = TplMessageAction Label T.Text
| TplPostbackAction Label T.Text (Maybe T.Text)
| TplURIAction Label URL
URI will open in the in - app browser .
| TplDatetimePickerAction { label' :: (Maybe Label)
, data' :: T.Text
, mode' :: DatetimeMode
, initial' :: (Maybe T.Text)
, max' :: (Maybe T.Text)
, min' :: (Maybe T.Text)
}
deriving (Eq, Show)
instance ToJSON TemplateAction where
toJSON (TplPostbackAction label data'' maybeText) =
object . concat $
[ [ "type" .= ("postback" :: T.Text)
, "label" .= label
, "data" .= data''
]
, maybeToList $ ("text" .=) <$> maybeText
]
toJSON (TplMessageAction label text) = object [ "type" .= ("message" :: T.Text)
, "label" .= label
, "text" .= text
]
toJSON (TplURIAction label uri) = object [ "type" .= ("uri" :: T.Text)
, "label" .= label
, "uri" .= uri
]
toJSON (TplDatetimePickerAction label data'' mode initial max'' min'') =
object . concat $ [ [ "type" .= ("datetimepicker" :: T.Text)
, "data" .= data''
, "mode" .= mode
]
, maybeToList $ ("label" .=) <$> label
, maybeToList $ ("initial" .=) <$> initial
, maybeToList $ ("max" .=) <$> max''
, maybeToList $ ("min" .=) <$> min''
]
data DatetimeMode = Date | Time | Datetime deriving (Eq, Show)
instance ToJSON DatetimeMode where
toJSON Date = "date"
toJSON Time = "time"
toJSON Datetime = "datetime"
data Profile = Profile { getUserID :: ID
, getDisplayName :: T.Text
, getPictureURL :: Maybe URL
, getStatusMessage :: Maybe T.Text
}
deriving (Eq, Show)
instance FromJSON Profile where
parseJSON (Object v) = Profile <$> v .: "userId"
<*> v .: "displayName"
<*> v .: "pictureUrl"
<*> v .: "statusMessage"
parseJSON _ = fail "Profile"
State code errors may contain a parsed error body . Other types of errors ,
data APIError = BadRequest (Maybe APIErrorBody)
^ 400 Bad Request with a parsed error body , caused by badly
| Unauthorized (Maybe APIErrorBody)
^ 401 Unauthorized with a parsed error body , caused by invalid
| Forbidden (Maybe APIErrorBody)
^ 403 Forbidden with a parsed error body , caused by
| TooManyRequests (Maybe APIErrorBody)
^ 429 Too Many Requests with a parsed error body , caused by
| InternalServerError (Maybe APIErrorBody)
^ 500 Internal Server Error with a parsed error body .
| UndefinedStatusCode Int BL.ByteString
^ Caused by status codes other than 200 and listed statuses
| JSONDecodeError String
| UndefinedError SomeException
^ Any other exception caught as ' SomeException ' .
deriving Show
data APIErrorBody = APIErrorBody { getErrorMessage :: T.Text
, getErrorProperty :: Maybe T.Text
, getErrorDetails :: Maybe [APIErrorBody]
}
deriving (Eq, Show)
instance FromJSON APIErrorBody where
parseJSON (Object v) = APIErrorBody <$> v .: "message"
<*> (v .: "property" <|> return Nothing)
<*> (v .: "details" <|> return Nothing)
parseJSON _ = fail "APIErrorBody"
|
b82c75a2bb2be160b5fb42ba7d5a75f67fa45bc81461128b6531ccfbb6546d39 | joearms/ezwebframe | chat2.erl | -module(chat2).
-export([start/1]).
start(Browser) ->
case whereis(irc) of
undefined -> irc:start();
_ -> true
end,
idle(Browser).
idle(Browser) ->
receive
{Browser, {struct, [{join,Who}]}} ->
irc ! {join, self(), Who},
idle(Browser);
{irc, welcome, Who} ->
Browser ! [{cmd,hide_div},{id,idle}],
Browser ! [{cmd,show_div},{id,running}],
running(Browser, Who);
X ->
io:format("chat idle received:~p~n",[X]),
idle(Browser)
end.
running(Browser, Who) ->
receive
{Browser,{struct, [{entry,<<"tell">>},{txt,Txt}]}} ->
irc ! {broadcast, Who, Txt},
running(Browser, Who);
{Browser,{struct, [{clicked,<<"Leave">>}]}} ->
irc ! {leave, Who},
Browser ! [{cmd,hide_div},{id,running}],
Browser ! [{cmd,show_div},{id,idle}],
idle(Browser);
{irc, scroll, Bin} ->
Browser ! [{cmd,append_div},{id,scroll}, {txt, Bin}],
running(Browser, Who);
{irc, groups, Bin} ->
Browser ! [{cmd,fill_div},{id,users}, {txt, Bin}],
running(Browser, Who);
X ->
io:format("chat running received:~p~n",[X]),
running(Browser, Who)
end.
| null | https://raw.githubusercontent.com/joearms/ezwebframe/9eb320ff61d4dc7b0885f700414e56b7554788bf/demos/chat/chat2.erl | erlang | -module(chat2).
-export([start/1]).
start(Browser) ->
case whereis(irc) of
undefined -> irc:start();
_ -> true
end,
idle(Browser).
idle(Browser) ->
receive
{Browser, {struct, [{join,Who}]}} ->
irc ! {join, self(), Who},
idle(Browser);
{irc, welcome, Who} ->
Browser ! [{cmd,hide_div},{id,idle}],
Browser ! [{cmd,show_div},{id,running}],
running(Browser, Who);
X ->
io:format("chat idle received:~p~n",[X]),
idle(Browser)
end.
running(Browser, Who) ->
receive
{Browser,{struct, [{entry,<<"tell">>},{txt,Txt}]}} ->
irc ! {broadcast, Who, Txt},
running(Browser, Who);
{Browser,{struct, [{clicked,<<"Leave">>}]}} ->
irc ! {leave, Who},
Browser ! [{cmd,hide_div},{id,running}],
Browser ! [{cmd,show_div},{id,idle}],
idle(Browser);
{irc, scroll, Bin} ->
Browser ! [{cmd,append_div},{id,scroll}, {txt, Bin}],
running(Browser, Who);
{irc, groups, Bin} ->
Browser ! [{cmd,fill_div},{id,users}, {txt, Bin}],
running(Browser, Who);
X ->
io:format("chat running received:~p~n",[X]),
running(Browser, Who)
end.
|
|
3fac874a0e9a57674347716eb4ab35ba2c21fe002e5ef8cc9ec72ffd65774f9b | bamarco/onyx-sim | flui.cljc | (ns onyx.sim.flui
(:require [taoensso.timbre :as log]
#?(:cljs [re-com.core :as rc])
[onyx.sim.utils :refer [mapply ppr-str]]))
;;;
;;; !!!: This is an experimental volatile file. Do not expect it to stay the same.
;;;
(defn call
"Because you can't use reagent on the serverside. :("
[f & args]
#?(:cljs (into [f] args)
:clj (apply f args)))
(defn stub
"Provides a stub for functions that aren't implemented yet."
[fn-name]
(fn [& args]
[:div.stub [:p (str "STUB for: " (pr-str (cons fn-name args)))]]))
#?
(:cljs
(defn code*
"Eventually a pretty lookin code block with syntax highlighting."
[& {:as args :keys [code child pr-fn] cl :class}]
;; TODO: word-wrap and line numbers
;; TODO: syntax highlighting
(let [args (-> args
(dissoc :code :pr-fn)
(assoc :class (str "rc-code " cl )))
code ((or pr-fn ppr-str) code)]
(assert (not child) (str "Code should not have a :child element. Got " child))
(mapply rc/box :child [:code [:pre code]] args))))
(def none [:span])
(def code
#?(:clj (stub 'code)
:cljs code*))
(def button
#?(:clj (stub 'button)
:cljs (partial call rc/button)))
(def radio-button
#?(:clj (stub 'radio-button)
:cljs (partial call rc/radio-button)))
(def gap
#?(:clj (stub 'gap)
:cljs (partial call rc/gap)))
(def p
#?(:clj (stub 'p)
:cljs (partial call rc/p)))
(def horizontal-tabs
#?(:clj (stub 'horizontal-tabs)
:cljs (partial call rc/horizontal-tabs)))
(def horizontal-pill-tabs
#?(:clj (stub 'horizontal-tabs)
:cljs (partial call rc/horizontal-pill-tabs)))
(def horizontal-bar-tabs
#?(:clj (stub 'horizontal-tabs)
:cljs (partial call rc/horizontal-bar-tabs)))
(def checkbox
#?(:clj (stub 'checkbox)
:cljs (partial call rc/checkbox)))
(def h-box
#?(:clj (stub 'h-box)
:cljs (partial call rc/h-box)))
(def v-box
#?(:clj (stub 'v-box)
:cljs (partial call rc/v-box)))
(def box
#?(:clj (stub 'box)
:cljs (partial call rc/box)))
(def label
#?(:clj (stub 'label)
:cljs (partial call rc/label)))
(def title
#?(:clj (stub 'title)
:cljs (partial call rc/title)))
(def input-text
#?(:clj (stub 'input-text)
:cljs (partial call rc/input-text)))
(def input-textarea
#?(:clj (stub 'input-textarea)
:cljs (partial call rc/input-textarea)))
(def selection-list
#?(:clj (stub 'selection-list)
:cljs (partial call rc/selection-list)))
(def single-dropdown
#?(:clj (stub 'single-dropdown)
:cljs (partial call rc/single-dropdown)))
| null | https://raw.githubusercontent.com/bamarco/onyx-sim/5c911eec3540db7ba5e6681fe405070e03ecb4de/src/cljc/onyx/sim/flui.cljc | clojure |
!!!: This is an experimental volatile file. Do not expect it to stay the same.
TODO: word-wrap and line numbers
TODO: syntax highlighting | (ns onyx.sim.flui
(:require [taoensso.timbre :as log]
#?(:cljs [re-com.core :as rc])
[onyx.sim.utils :refer [mapply ppr-str]]))
(defn call
"Because you can't use reagent on the serverside. :("
[f & args]
#?(:cljs (into [f] args)
:clj (apply f args)))
(defn stub
"Provides a stub for functions that aren't implemented yet."
[fn-name]
(fn [& args]
[:div.stub [:p (str "STUB for: " (pr-str (cons fn-name args)))]]))
#?
(:cljs
(defn code*
"Eventually a pretty lookin code block with syntax highlighting."
[& {:as args :keys [code child pr-fn] cl :class}]
(let [args (-> args
(dissoc :code :pr-fn)
(assoc :class (str "rc-code " cl )))
code ((or pr-fn ppr-str) code)]
(assert (not child) (str "Code should not have a :child element. Got " child))
(mapply rc/box :child [:code [:pre code]] args))))
(def none [:span])
(def code
#?(:clj (stub 'code)
:cljs code*))
(def button
#?(:clj (stub 'button)
:cljs (partial call rc/button)))
(def radio-button
#?(:clj (stub 'radio-button)
:cljs (partial call rc/radio-button)))
(def gap
#?(:clj (stub 'gap)
:cljs (partial call rc/gap)))
(def p
#?(:clj (stub 'p)
:cljs (partial call rc/p)))
(def horizontal-tabs
#?(:clj (stub 'horizontal-tabs)
:cljs (partial call rc/horizontal-tabs)))
(def horizontal-pill-tabs
#?(:clj (stub 'horizontal-tabs)
:cljs (partial call rc/horizontal-pill-tabs)))
(def horizontal-bar-tabs
#?(:clj (stub 'horizontal-tabs)
:cljs (partial call rc/horizontal-bar-tabs)))
(def checkbox
#?(:clj (stub 'checkbox)
:cljs (partial call rc/checkbox)))
(def h-box
#?(:clj (stub 'h-box)
:cljs (partial call rc/h-box)))
(def v-box
#?(:clj (stub 'v-box)
:cljs (partial call rc/v-box)))
(def box
#?(:clj (stub 'box)
:cljs (partial call rc/box)))
(def label
#?(:clj (stub 'label)
:cljs (partial call rc/label)))
(def title
#?(:clj (stub 'title)
:cljs (partial call rc/title)))
(def input-text
#?(:clj (stub 'input-text)
:cljs (partial call rc/input-text)))
(def input-textarea
#?(:clj (stub 'input-textarea)
:cljs (partial call rc/input-textarea)))
(def selection-list
#?(:clj (stub 'selection-list)
:cljs (partial call rc/selection-list)))
(def single-dropdown
#?(:clj (stub 'single-dropdown)
:cljs (partial call rc/single-dropdown)))
|
1b4798f348e1dffb082f83cb017a0114bddcb9c0ca0ce8d47406cc1a85ca785e | andyfriesen/buffer-builder-aeson | Bench.hs | {-# LANGUAGE OverloadedStrings, RecordWildCards #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MagicHash #
{-# LANGUAGE BangPatterns #-}
module Main where
import Control.DeepSeq (force)
import Criterion
import Criterion.Main
import qualified Data.Aeson as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.BufferBuilder.Json as Json
import qualified Data.BufferBuilder.Aeson ()
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified Data.Vector.Unboxed as UnboxedVector
assumeSuccess :: Either a b -> b
assumeSuccess (Right r) = r
assumeSuccess _ = error "assumeSuccess"
main :: IO ()
main = do
content <- BS.readFile "test.json"
let lazyContent = force $ BSL.fromChunks [content]
let parsedUserList :: [Aeson.Value]
Just parsedUserList = Aeson.decode lazyContent
let compareBench name !value =
bgroup name
[ bench "bufferbuilder" $ nf Json.encodeJson value
, bench "aeson" $ nf Aeson.encode value
]
defaultMain
[ compareBench "list bool" $ Aeson.Array $ Vector.fromList $ fmap Aeson.Bool $ replicate 65536 False
, compareBench "list null" $ Aeson.Array $ Vector.replicate 65536 Aeson.Null
, compareBench "list empty object" $ Aeson.Array $ Vector.replicate 65536 $ Aeson.object []
, compareBench "list empty array" $ Aeson.Array $ Vector.replicate 65536 $ Aeson.Array Vector.empty
, compareBench "list string" $ Aeson.Array $ Vector.fromList $ fmap (Aeson.String . Text.pack . show) ([0..65535] :: [Int])
, compareBench "list int" $ Aeson.Array $ Vector.fromList $ fmap (Aeson.Number . fromIntegral) ([0..65535] :: [Int])
, compareBench "hash string" $ Aeson.object $ fmap (\e -> (Text.pack $ show e, Aeson.Null)) ([0..65535] :: [Int])
, compareBench "list record" parsedUserList
, bench "intvector" $ nf Json.encodeJson (UnboxedVector.fromList $! [0..65535] :: UnboxedVector.Vector Int)
]
| null | https://raw.githubusercontent.com/andyfriesen/buffer-builder-aeson/5b85148ef8908554cf0b858dd1473131d231a594/bench/Bench.hs | haskell | # LANGUAGE OverloadedStrings, RecordWildCards #
# LANGUAGE BangPatterns # | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MagicHash #
module Main where
import Control.DeepSeq (force)
import Criterion
import Criterion.Main
import qualified Data.Aeson as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.BufferBuilder.Json as Json
import qualified Data.BufferBuilder.Aeson ()
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified Data.Vector.Unboxed as UnboxedVector
assumeSuccess :: Either a b -> b
assumeSuccess (Right r) = r
assumeSuccess _ = error "assumeSuccess"
main :: IO ()
main = do
content <- BS.readFile "test.json"
let lazyContent = force $ BSL.fromChunks [content]
let parsedUserList :: [Aeson.Value]
Just parsedUserList = Aeson.decode lazyContent
let compareBench name !value =
bgroup name
[ bench "bufferbuilder" $ nf Json.encodeJson value
, bench "aeson" $ nf Aeson.encode value
]
defaultMain
[ compareBench "list bool" $ Aeson.Array $ Vector.fromList $ fmap Aeson.Bool $ replicate 65536 False
, compareBench "list null" $ Aeson.Array $ Vector.replicate 65536 Aeson.Null
, compareBench "list empty object" $ Aeson.Array $ Vector.replicate 65536 $ Aeson.object []
, compareBench "list empty array" $ Aeson.Array $ Vector.replicate 65536 $ Aeson.Array Vector.empty
, compareBench "list string" $ Aeson.Array $ Vector.fromList $ fmap (Aeson.String . Text.pack . show) ([0..65535] :: [Int])
, compareBench "list int" $ Aeson.Array $ Vector.fromList $ fmap (Aeson.Number . fromIntegral) ([0..65535] :: [Int])
, compareBench "hash string" $ Aeson.object $ fmap (\e -> (Text.pack $ show e, Aeson.Null)) ([0..65535] :: [Int])
, compareBench "list record" parsedUserList
, bench "intvector" $ nf Json.encodeJson (UnboxedVector.fromList $! [0..65535] :: UnboxedVector.Vector Int)
]
|
813584f0c493136ad90c6e4c6183ba4af3e4febb85a12e9e76714c6cfe587441 | strega-nil/stregaml | Type.ml | include Types.Type
let mutability_equal lhs rhs =
match (lhs, rhs) with
| Immutable, Immutable -> true
| Mutable, Mutable -> true
| _ -> false
let mutability_to_string mut ~lang =
match mut with
| Immutable -> Lang.keyword_to_string Token.Keyword.Ref ~lang
| Mutable -> Lang.keyword_to_string Token.Keyword.Mut ~lang
let rec to_string : type cat. cat t -> lang:Lang.t -> string =
fun ty ~lang ->
match ty with
| Named id -> (id :> string)
| Reference (pointee, _) -> "&" ^ to_string ~lang pointee
| Tuple xs ->
let f (x, _) = to_string x ~lang in
let xs = String.concat ~sep:", " (List.map xs ~f) in
String.concat ["("; xs; ")"]
| Function {params; ret_ty} ->
let f (x, _) = to_string x ~lang in
let ret_ty =
match ret_ty with Some x -> ") -> " ^ f x | None -> ")"
in
let params = String.concat ~sep:", " (List.map params ~f) in
String.concat ["func("; params; ret_ty]
| Place {mutability = mut, _; ty = ty, _} ->
String.concat
[mutability_to_string ~lang mut; " "; to_string ~lang ty]
| Any ty -> to_string ty ~lang
module Data = struct
include Types.Type_Data
let to_string ?name data ~lang =
let kind, data =
match data with
| Record {fields} ->
let f ((name, ty), _) =
let (name, _) : Nfc_string.t Spanned.t = name in
let ty, _ = ty in
String.concat
[ "\n "
; (name :> string)
; ": "
; to_string ty ~lang
; ";" ]
in
let fields = String.concat (List.map fields ~f) in
(Token.Keyword.Record, fields)
| Variant {variants} ->
let f ((name, ty), _) =
let (name, _) : Nfc_string.t Spanned.t = name in
match ty with
| Some (ty, _) ->
String.concat
[ "\n "
; (name :> string)
; ": "
; to_string ty ~lang
; ";" ]
| None -> String.concat ["\n "; (name :> string); ";"]
in
let variants = String.concat (List.map variants ~f) in
(Token.Keyword.Variant, variants)
| Integer {bits} ->
let data =
String.concat ["\n bits = "; Int.to_string bits; ";"]
in
(Token.Keyword.Integer, data)
in
let name = match name with Some n -> " " ^ n | None -> "" in
String.concat
[Lang.keyword_to_string ~lang kind; name; " {"; data; "\n }"]
end
module Definition = Types.Type_Definition
| null | https://raw.githubusercontent.com/strega-nil/stregaml/83b51826d5776926fb3f4b7ad03c7ffe837ecbf8/lib/parse/Type.ml | ocaml | include Types.Type
let mutability_equal lhs rhs =
match (lhs, rhs) with
| Immutable, Immutable -> true
| Mutable, Mutable -> true
| _ -> false
let mutability_to_string mut ~lang =
match mut with
| Immutable -> Lang.keyword_to_string Token.Keyword.Ref ~lang
| Mutable -> Lang.keyword_to_string Token.Keyword.Mut ~lang
let rec to_string : type cat. cat t -> lang:Lang.t -> string =
fun ty ~lang ->
match ty with
| Named id -> (id :> string)
| Reference (pointee, _) -> "&" ^ to_string ~lang pointee
| Tuple xs ->
let f (x, _) = to_string x ~lang in
let xs = String.concat ~sep:", " (List.map xs ~f) in
String.concat ["("; xs; ")"]
| Function {params; ret_ty} ->
let f (x, _) = to_string x ~lang in
let ret_ty =
match ret_ty with Some x -> ") -> " ^ f x | None -> ")"
in
let params = String.concat ~sep:", " (List.map params ~f) in
String.concat ["func("; params; ret_ty]
| Place {mutability = mut, _; ty = ty, _} ->
String.concat
[mutability_to_string ~lang mut; " "; to_string ~lang ty]
| Any ty -> to_string ty ~lang
module Data = struct
include Types.Type_Data
let to_string ?name data ~lang =
let kind, data =
match data with
| Record {fields} ->
let f ((name, ty), _) =
let (name, _) : Nfc_string.t Spanned.t = name in
let ty, _ = ty in
String.concat
[ "\n "
; (name :> string)
; ": "
; to_string ty ~lang
; ";" ]
in
let fields = String.concat (List.map fields ~f) in
(Token.Keyword.Record, fields)
| Variant {variants} ->
let f ((name, ty), _) =
let (name, _) : Nfc_string.t Spanned.t = name in
match ty with
| Some (ty, _) ->
String.concat
[ "\n "
; (name :> string)
; ": "
; to_string ty ~lang
; ";" ]
| None -> String.concat ["\n "; (name :> string); ";"]
in
let variants = String.concat (List.map variants ~f) in
(Token.Keyword.Variant, variants)
| Integer {bits} ->
let data =
String.concat ["\n bits = "; Int.to_string bits; ";"]
in
(Token.Keyword.Integer, data)
in
let name = match name with Some n -> " " ^ n | None -> "" in
String.concat
[Lang.keyword_to_string ~lang kind; name; " {"; data; "\n }"]
end
module Definition = Types.Type_Definition
|
|
9e0883643a7e7693f7a37a61e0a3e5353f043ec0a73fce4cfee15376932868a9 | fabianbergmark/ECMA-262 | Parser.hs | module Language.JavaScript.Parser
( parseJavaScript ) where
import Control.Applicative ((<*), (*>))
import Text.Parsec
import Language.JavaScript.AST
import Language.JavaScript.Lexer (lexJavaScript)
import Language.JavaScript.Prim
import Language.JavaScript.Util
chainl1' :: (Stream s m t) =>
ParsecT s u m a -> ParsecT s u m b -> ParsecT s u m (a -> b -> a) -> ParsecT s u m a
chainl1' pa pb op = do
a <- pa
rest a
where
rest a = do { f <- op; b <- pb; rest (f a b) } <|> return a
primExpr :: JSParser PrimExpr
primExpr =
do { identName "this" ; return PrimExprThis } <|>
do { name <- getIdent; return $ PrimExprIdent name} <|>
do { l <- getLiteral; return $ PrimExprLiteral l } <|>
do { a <- arrayLit; return $ PrimExprArray a } <|>
do { o <- objectLit; return $ PrimExprObject o } <|>
do { punctuator "("; e <- expr; punctuator ")"; return $ PrimExprParens e }
arrayLit :: JSParser ArrayLit
arrayLit =
try (do { punctuator "["; me <- optionMaybe elision; punctuator "]"; return $ ArrayLitH me }) <|>
try (do { punctuator "["; el <- elementList; punctuator "]"; return $ ArrayLit el }) <|>
do { punctuator "[";
el <- elementList;
punctuator ",";
me <- optionMaybe elision;
punctuator "]";
return $ ArrayLitT el me }
elementList :: JSParser ElementList
elementList =
do { me <- optionMaybe elision; ae <- assignExpr; applyRest elementListRest (ElementList me ae) }
elementListRest :: JSParser (ElementList -> JSParser ElementList)
elementListRest =
do { punctuator ","; me <- optionMaybe elision; ae <- assignExpr; return $ \el -> applyRest elementListRest (ElementListCons el me ae) }
elision :: JSParser Elision
elision =
do { punctuator ","; applyRest elisionRest ElisionComma }
elisionRest :: JSParser (Elision -> JSParser Elision)
elisionRest =
do { punctuator ","; return $ \e -> applyRest elisionRest (ElisionCons e) }
objectLit :: JSParser ObjectLit
objectLit =
try (do { punctuator "{"; punctuator "}"; return ObjectLitEmpty }) <|>
do { punctuator "{"; pl <- propList; optional $ punctuator ","; punctuator "}"; return $ ObjectLit pl }
propList :: JSParser PropList
propList =
do { pa <- propAssign; applyRest propListRest (PropListAssign pa) }
propListRest :: JSParser (PropList -> JSParser PropList)
propListRest =
do { punctuator ","; pa <- propAssign; return $ \pl -> applyRest propListRest (PropListCons pl pa) }
propAssign :: JSParser PropAssign
propAssign =
do { pn <- propName; punctuator ":"; ae <- assignExpr; return $ PropAssignField pn ae } <|>
do { identName "get"; pn <- propName; punctuator "("; punctuator ")"; punctuator "{"; fb <- funcBody; punctuator "}"; return $ PropAssignGet pn fb } <|>
do { identName "set"; pn <- propName; punctuator "("; pl <- propSetParamList; punctuator ")"; punctuator "{"; fb <- funcBody; punctuator "}"; return $ PropAssignSet pn pl fb }
propName :: JSParser PropName
propName =
do { name <- getIdentName; return $ PropNameId name } <|>
do { sl <- getStringLit; return $ PropNameStr sl } <|>
do { nl <- getNumLit; return $ PropNameNum nl }
propSetParamList :: JSParser PropSetParamList
propSetParamList =
do { i <- getIdent; return $ PropSetParamList i }
memberExpr :: JSParser MemberExpr
memberExpr =
do { identName "new"; me <- memberExpr; args <- arguments; applyRest memberExprRest (MemberExprNew me args) } <|>
do { pe <- primExpr; applyRest memberExprRest (MemberExprPrim pe) } <|>
do { fe <- funcExpr; applyRest memberExprRest (MemberExprFunc fe) }
memberExprRest :: JSParser (MemberExpr -> JSParser MemberExpr)
memberExprRest =
do { punctuator "["; e <- expr; punctuator "]"; return $ \me -> applyRest memberExprRest (MemberExprArray me e) } <|>
do { punctuator "."; name <- getIdentName; return $ \me -> applyRest memberExprRest (MemberExprDot me name) }
newExpr :: JSParser NewExpr
newExpr =
try (do { me <- memberExpr; return $ NewExprMember me }) <|>
do { identName "new"; ne <- newExpr; return $ NewExprNew ne }
callExpr :: JSParser CallExpr
callExpr =
do { me <- memberExpr; args <- arguments; applyRest callExprRest (CallExprMember me args) }
callExprRest :: JSParser (CallExpr -> JSParser CallExpr)
callExprRest =
do { args <- arguments; return $ \ce -> applyRest callExprRest (CallExprCall ce args) } <|>
do { punctuator "["; e <- expr; punctuator "]"; return $ \ce -> applyRest callExprRest (CallExprArray ce e) } <|>
do { punctuator "."; name <- getIdentName; return $ \ce -> applyRest callExprRest (CallExprDot ce name) }
arguments :: JSParser Arguments
arguments =
try (do { punctuator "("; punctuator ")"; return ArgumentsEmpty }) <|>
do { punctuator "("; al <- argumentList; punctuator ")"; return $ Arguments al }
argumentList :: JSParser ArgumentList
argumentList =
chainl1'
(do { ae <- assignExpr; return $ ArgumentList ae })
assignExpr
(do { punctuator ","; return ArgumentListCons })
leftExpr :: JSParser LeftExpr
leftExpr =
try (do { ce <- callExpr; return $ LeftExprCallExpr ce }) <|>
do { ne <- newExpr; return $ LeftExprNewExpr ne }
postFixExpr :: JSParser PostFixExpr
postFixExpr = do
le <- leftExpr
do { punctuator "++"; return $ PostFixExprPostInc le } <|>
do { punctuator "--"; return $ PostFixExprPostDec le } <|>
do { return $ PostFixExprLeftExpr le }
uExpr :: JSParser UExpr
uExpr =
do { identName "delete"; u <- uExpr; return $ UExprDelete u } <|>
do { identName "void"; u <- uExpr; return $ UExprVoid u } <|>
do { identName "typeof"; u <- uExpr; return $ UExprTypeOf u } <|>
do { punctuator "++"; u <- uExpr; return $ UExprDoublePlus u } <|>
do { punctuator "--"; u <- uExpr; return $ UExprDoubleMinus u } <|>
do { punctuator "+"; u <- uExpr; return $ UExprUnaryPlus u } <|>
do { punctuator "-"; u <- uExpr; return $ UExprUnaryMinus u } <|>
do { punctuator "~"; u <- uExpr; return $ UExprBitNot u } <|>
do { punctuator "!"; u <- uExpr; return $ UExprNot u } <|>
do { pe <- postFixExpr; return $ UExprPostFix pe }
multExpr :: JSParser MultExpr
multExpr =
chainl1'
(do { u <- uExpr; return $ MultExpr u })
uExpr
(do { punctuator "*"; return MultExprMult } <|>
do { punctuator "/"; return MultExprDiv } <|>
do { punctuator "%"; return MultExprMod })
addExpr :: JSParser AddExpr
addExpr =
chainl1'
(do { m <- multExpr; return $ AddExpr m })
multExpr
(do { punctuator "+"; return AddExprAdd } <|>
do { punctuator "-"; return AddExprSub })
shiftExpr :: JSParser ShiftExpr
shiftExpr =
chainl1'
(do { a <- addExpr; return $ ShiftExpr a })
addExpr
(do { punctuator "<<"; return ShiftExprLeft } <|>
do { punctuator ">>"; return ShiftExprRight } <|>
do { punctuator ">>>"; return ShiftExprRightZero })
relExpr :: JSParser RelExpr
relExpr =
chainl1'
(do { s <- shiftExpr; return $ RelExpr s })
shiftExpr
(do { punctuator "<"; return RelExprLess } <|>
do { punctuator ">"; return RelExprGreater } <|>
do { punctuator "<="; return RelExprLessEq } <|>
do { punctuator ">="; return RelExprGreaterEq } <|>
do { identName "instanceof"; return RelExprInstanceOf } <|>
do { identName "in"; return RelExprIn })
relExprNoIn :: JSParser RelExprNoIn
relExprNoIn =
chainl1'
(do { s <- shiftExpr; return $ RelExprNoIn s })
shiftExpr
(do { punctuator "<"; return RelExprNoInLess } <|>
do { punctuator ">"; return RelExprNoInGreater } <|>
do { punctuator "<="; return RelExprNoInLessEq } <|>
do { punctuator ">="; return RelExprNoInGreaterEq } <|>
do { identName "instanceof"; return RelExprNoInInstanceOf })
eqExpr :: JSParser EqExpr
eqExpr =
chainl1'
(do { r <- relExpr; return $ EqExpr r })
relExpr
(do { punctuator "=="; return EqExprEq } <|>
do { punctuator "!="; return EqExprNotEq } <|>
do { punctuator "==="; return EqExprStrictEq } <|>
do { punctuator "!=="; return EqExprStrictNotEq })
eqExprNoIn :: JSParser EqExprNoIn
eqExprNoIn =
chainl1'
(do { r <- relExprNoIn; return $ EqExprNoIn r })
relExprNoIn
(do { punctuator "=="; return EqExprNoInEq } <|>
do { punctuator "!="; return EqExprNoInNotEq } <|>
do { punctuator "==="; return EqExprNoInStrictEq } <|>
do { punctuator "!=="; return EqExprNoInStrictNotEq })
bitAndExpr :: JSParser BitAndExpr
bitAndExpr =
chainl1'
(do { e <- eqExpr; return $ BitAndExpr e })
eqExpr
(do { punctuator "&"; return $ BitAndExprAnd })
bitAndExprNoIn :: JSParser BitAndExprNoIn
bitAndExprNoIn =
chainl1'
(do { e <- eqExprNoIn; return $ BitAndExprNoIn e })
eqExprNoIn
(do { punctuator "&"; return $ BitAndExprNoInAnd })
bitXorExpr :: JSParser BitXorExpr
bitXorExpr =
chainl1'
(do { bae <- bitAndExpr; return $ BitXorExpr bae })
bitAndExpr
(do { punctuator "^"; return $ BitXorExprXor })
bitXorExprNoIn :: JSParser BitXorExprNoIn
bitXorExprNoIn =
chainl1'
(do { bae <- bitAndExprNoIn; return $ BitXorExprNoIn bae })
bitAndExprNoIn
(do { punctuator "^"; return $ BitXorExprNoInXor })
bitOrExpr :: JSParser BitOrExpr
bitOrExpr =
chainl1'
(do { bxe <- bitXorExpr; return $ BitOrExpr bxe })
bitXorExpr
(do { punctuator "|"; return $ BitOrExprOr })
bitOrExprNoIn :: JSParser BitOrExprNoIn
bitOrExprNoIn =
chainl1'
(do { bxe <- bitXorExprNoIn; return $ BitOrExprNoIn bxe })
bitXorExprNoIn
(do { punctuator "|"; return $ BitOrExprNoInOr })
logicalAndExpr :: JSParser LogicalAndExpr
logicalAndExpr =
chainl1'
(do { boe <- bitOrExpr; return $ LogicalAndExpr boe })
bitOrExpr
(do { punctuator "&&"; return $ LogicalAndExprAnd })
logicalAndExprNoIn :: JSParser LogicalAndExprNoIn
logicalAndExprNoIn =
chainl1'
(do { boe <- bitOrExprNoIn; return $ LogicalAndExprNoIn boe })
bitOrExprNoIn
(do { punctuator "&&"; return $ LogicalAndExprNoInAnd })
logicalOrExpr :: JSParser LogicalOrExpr
logicalOrExpr =
chainl1'
(do { lae <- logicalAndExpr; return $ LogicalOrExpr lae })
logicalAndExpr
(do { punctuator "||"; return $ LogicalOrExprOr })
logicalOrExprNoIn :: JSParser LogicalOrExprNoIn
logicalOrExprNoIn =
chainl1'
(do { lae <- logicalAndExprNoIn; return $ LogicalOrExprNoIn lae })
logicalAndExprNoIn
(do { punctuator "||"; return $ LogicalOrExprNoInOr })
condExpr :: JSParser CondExpr
condExpr = do
loe <- logicalOrExpr
do { try $ do { punctuator "?"; }; ae1 <- assignExpr; punctuator ":"; ae2 <- assignExpr; return $ CondExprIf loe ae1 ae2 } <|>
do { return $ CondExpr loe }
condExprNoIn :: JSParser CondExprNoIn
condExprNoIn = do
loe <- logicalOrExprNoIn;
do { try $ do { punctuator "?"; }; ae1 <- assignExpr; punctuator ":"; ae2 <- assignExpr; return $ CondExprNoInIf loe ae1 ae2 } <|>
do { return $ CondExprNoIn loe }
assignExpr :: JSParser AssignExpr
assignExpr =
try (do { le <- leftExpr; ao <- assignOp; ae <- assignExpr; return $ AssignExprAssign le ao ae }) <|>
do { ce <- condExpr; return $ AssignExprCondExpr ce }
assignExprNoIn :: JSParser AssignExprNoIn
assignExprNoIn =
try (do { le <- leftExpr; ao <- assignOp; ae <- assignExprNoIn; return $ AssignExprNoInAssign le ao ae }) <|>
do { ce <- condExprNoIn; return $ AssignExprNoInCondExpr ce }
assignOp :: JSParser AssignOp
assignOp =
do { punctuator "="; return AssignOpNormal } <|>
do { punctuator "*="; return AssignOpMult } <|>
do { punctuator "/="; return AssignOpDiv } <|>
do { punctuator "%="; return AssignOpMod } <|>
do { punctuator "+="; return AssignOpPlus } <|>
do { punctuator "-="; return AssignOpMinus } <|>
do { punctuator "<<="; return AssignOpShiftLeft } <|>
do { punctuator ">>="; return AssignOpShiftRight } <|>
do { punctuator ">>>="; return AssignOpShiftRightZero } <|>
do { punctuator "&="; return AssignOpBitAnd } <|>
do { punctuator "^="; return AssignOpBitXor } <|>
do { punctuator "|="; return AssignOpBitOr }
expr :: JSParser Expr
expr =
chainl1'
(do { ae <- assignExpr; return $ Expr ae })
assignExpr
(do { punctuator ","; return ExprCons })
exprNoIn :: JSParser ExprNoIn
exprNoIn =
chainl1'
(do { ae <- assignExprNoIn; return $ ExprNoIn ae })
assignExprNoIn
(do { punctuator ","; return ExprNoInCons })
stmt :: JSParser Stmt
stmt =
do { b <- block; return $ StmtBlock b } <|>
do { vs <- varStmt; return $ StmtVar vs } <|>
do { es <- emptyStmt; return $ StmtEmpty es } <|>
try (do { es <- exprStmt; return $ StmtExpr es }) <|>
do { ic <- contStmt; return $ StmtCont ic } <|>
do { is <- ifStmt; return $ StmtIf is } <|>
do { is <- itStmt; return $ StmtIt is } <|>
do { bs <- breakStmt; return $ StmtBreak bs } <|>
do { rs <- returnStmt; return $ StmtReturn rs } <|>
do { ws <- withStmt; return $ StmtWith ws } <|>
do { ss <- switchStmt; return $ StmtSwitch ss } <|>
do { ts <- throwStmt; return $ StmtThrow ts } <|>
do { ts <- tryStmt; return $ StmtTry ts } <|>
do { ds <- dbgStmt; return $ StmtDbg ds } <|>
do { ls <- labelledStmt; return $ StmtLabelled ls }
block :: JSParser Block
block =
do { punctuator "{"; msl <- optionMaybe stmtList; punctuator "}"; return $ Block msl }
stmtList :: JSParser StmtList
stmtList =
chainl1'
(do { s <- stmt; return $ StmtList s })
stmt
(do { return StmtListCons })
varStmt :: JSParser VarStmt
varStmt =
do { identName "var"; vdl <- varDeclList; return $ VarStmt vdl }
varDeclList :: JSParser VarDeclList
varDeclList =
chainl1'
(do { vd <- varDecl; return $ VarDeclList vd})
varDecl
(do { punctuator ","; return $ VarDeclListCons })
varDeclListNoIn :: JSParser VarDeclListNoIn
varDeclListNoIn =
chainl1'
(do { vd <- varDeclNoIn; return $ VarDeclListNoIn vd})
varDeclNoIn
(do { punctuator ","; return $ VarDeclListNoInCons})
varDecl :: JSParser VarDecl
varDecl =
do { i <- getIdent; mInit <- optionMaybe initialiser; return $ VarDecl i mInit }
varDeclNoIn :: JSParser VarDeclNoIn
varDeclNoIn =
do { i <- getIdent; mInit <- optionMaybe initialiserNoIn; return $ VarDeclNoIn i mInit }
initialiser :: JSParser Initialiser
initialiser =
do { punctuator "="; ae <- assignExpr; return $ Initialiser ae }
initialiserNoIn :: JSParser InitialiserNoIn
initialiserNoIn =
do { punctuator "="; ae <- assignExprNoIn; return $ InitialiserNoIn ae }
emptyStmt :: JSParser EmptyStmt
emptyStmt =
do { punctuator ";"; return EmptyStmt }
exprStmt :: JSParser ExprStmt
exprStmt =
do { notFollowedBy (try $ punctuator "{" <|> identName "function"); e <- expr; autoSemi; return $ ExprStmt e }
ifStmt :: JSParser IfStmt
ifStmt =
try (do { identName "if"; punctuator "("; e <- expr; punctuator ")"; s1 <- stmt; identName "else"; s2 <- stmt; return $ IfStmtIfElse e s1 s2 }) <|>
do { identName "if"; punctuator "("; e <- expr; punctuator ")"; s <- stmt; return $ IfStmtIf e s }
itStmt :: JSParser ItStmt
itStmt =
try (do { identName "do"; s <- stmt; identName "while"; punctuator "("; e <- expr; punctuator ")"; return $ ItStmtDoWhile s e }) <|>
try (do { identName "while"; punctuator "("; e <- expr; punctuator ")"; s <- stmt; return $ ItStmtWhile e s }) <|>
try (do { identName "for"; punctuator "("; me1 <- optionMaybe exprNoIn; punctuator ";"; me2 <- optionMaybe expr; punctuator ";"; me3 <- optionMaybe expr; punctuator ")"; s <- stmt; return $ ItStmtFor me1 me2 me3 s }) <|>
try (do { identName "for"; punctuator "("; identName "var"; vdl <- varDeclListNoIn; punctuator ";"; me1 <- optionMaybe expr; punctuator ";"; me2 <- optionMaybe expr; punctuator ")"; s <- stmt; return $ ItStmtForVar vdl me1 me2 s }) <|>
do { identName "for"; punctuator "("; le <- leftExpr; identName "in"; e <- expr; punctuator ")"; s <- stmt; return $ ItStmtForIn le e s } <|>
do { identName "for"; punctuator "("; identName "var"; vd <- varDeclNoIn; identName "in"; e <- expr; punctuator ")"; s <- stmt; return $ ItStmtForVarIn vd e s }
contStmt :: JSParser ContStmt
contStmt =
try (do { identName "continue"; autoSemi; return ContStmt }) <|>
do { identName "continue"; noLineTerminatorHere; i <- getIdent; autoSemi; return $ ContStmtLabelled i }
breakStmt :: JSParser BreakStmt
breakStmt =
try (do { identName "break"; autoSemi; return BreakStmt }) <|>
do { identName "break"; noLineTerminatorHere; i <- getIdent; autoSemi; return $ BreakStmtLabelled i }
returnStmt :: JSParser ReturnStmt
returnStmt =
try (do { identName "return"; autoSemi; return ReturnStmt }) <|>
do { identName "return"; noLineTerminatorHere; e <- expr; autoSemi; return $ ReturnStmtExpr e }
withStmt :: JSParser WithStmt
withStmt =
do { identName "with"; punctuator "("; e <- expr; punctuator ")"; s <- stmt; return $ WithStmt e s }
switchStmt :: JSParser SwitchStmt
switchStmt =
do { identName "switch"; punctuator "("; e <- expr; punctuator ")"; cb <- caseBlock; return $ SwitchStmt e cb }
caseBlock :: JSParser CaseBlock
caseBlock =
try (do { punctuator "{"; mcc <- optionMaybe caseClauses; punctuator "}"; return $ CaseBlock mcc }) <|>
do { punctuator "{"; mcc1 <- optionMaybe caseClauses; dc <- defaultClause; mcc2 <- optionMaybe caseClauses; punctuator "}"; return $ CaseBlockDefault mcc1 dc mcc2 }
caseClauses :: JSParser CaseClauses
caseClauses =
chainl1'
(do { cc <- caseClause; return $ CaseClauses cc })
caseClause
(do { return $ CaseClausesCons })
caseClause :: JSParser CaseClause
caseClause =
do { identName "case"; e <- expr; punctuator ":"; msl <- optionMaybe stmtList; return $ CaseClause e msl }
defaultClause :: JSParser DefaultClause
defaultClause =
do { identName "default"; punctuator ":"; msl <- optionMaybe stmtList; return $ DefaultClause msl }
labelledStmt :: JSParser LabelledStmt
labelledStmt =
do { i <- getIdent; punctuator ":"; s <- stmt; return $ LabelledStmt i s }
throwStmt :: JSParser ThrowStmt
throwStmt =
do { identName "throw"; noLineTerminatorHere; e <- expr; autoSemi; return $ ThrowStmt e }
tryStmt :: JSParser TryStmt
tryStmt = do
identName "try"
b <- block
do { f <- finally; return $ TryStmtBF b f } <|>
do { c <- catch;
do { f <- finally; return $ TryStmtBCF b c f } <|>
do { return $ TryStmtBC b c }
}
catch :: JSParser Catch
catch =
do { identName "catch"; punctuator "("; i <- getIdent; punctuator ")"; b <- block; return $ Catch i b }
finally :: JSParser Finally
finally =
do { identName "finally"; b <- block; return $ Finally b }
dbgStmt :: JSParser DbgStmt
dbgStmt =
do { identName "debugger"; autoSemi; return DbgStmt }
funcDecl :: JSParser FuncDecl
funcDecl =
do { identName "function"; i <- getIdent; punctuator "("; mfpl <- optionMaybe formalParamList; punctuator ")"; punctuator "{"; fb <- funcBody; punctuator "}"; return $ FuncDecl i mfpl fb }
funcExpr :: JSParser FuncExpr
funcExpr =
do { identName "function"; mi <- optionMaybe getIdent; punctuator "("; mfpl <- optionMaybe formalParamList; punctuator ")"; punctuator "{"; fb <- funcBody; punctuator "}"; return $ FuncExpr mi mfpl fb }
formalParamList :: JSParser FormalParamList
formalParamList =
chainl1'
(do { i <- getIdent; return $ FormalParamList i })
getIdent
(do { punctuator ","; return $ FormalParamListCons })
funcBody :: JSParser FuncBody
funcBody =
do { mse <- optionMaybe sourceElements; return $ FuncBody mse }
program :: JSParser Program
program =
do { mse <- optionMaybe sourceElements; return $ Program mse }
sourceElements :: JSParser SourceElements
sourceElements =
chainl1'
(do { se <- sourceElement; return $ SourceElements se })
sourceElement
(do { return SourceElementsCons })
sourceElement :: JSParser SourceElement
sourceElement =
do { s <- stmt; return $ SourceElementStmt s } <|>
do { fd <- funcDecl; return $ SourceElementFuncDecl fd }
parseJavaScript :: String -> Either ParseError Program
parseJavaScript input =
let p = many lineTerminator *> program <* many lineTerminator <* eof
in runParser p newJSPState "" $ lexJavaScript input
| null | https://raw.githubusercontent.com/fabianbergmark/ECMA-262/ff1d8c347514625595f34b48e95a594c35b052ea/src/Language/JavaScript/Parser.hs | haskell | module Language.JavaScript.Parser
( parseJavaScript ) where
import Control.Applicative ((<*), (*>))
import Text.Parsec
import Language.JavaScript.AST
import Language.JavaScript.Lexer (lexJavaScript)
import Language.JavaScript.Prim
import Language.JavaScript.Util
chainl1' :: (Stream s m t) =>
ParsecT s u m a -> ParsecT s u m b -> ParsecT s u m (a -> b -> a) -> ParsecT s u m a
chainl1' pa pb op = do
a <- pa
rest a
where
rest a = do { f <- op; b <- pb; rest (f a b) } <|> return a
primExpr :: JSParser PrimExpr
primExpr =
do { identName "this" ; return PrimExprThis } <|>
do { name <- getIdent; return $ PrimExprIdent name} <|>
do { l <- getLiteral; return $ PrimExprLiteral l } <|>
do { a <- arrayLit; return $ PrimExprArray a } <|>
do { o <- objectLit; return $ PrimExprObject o } <|>
do { punctuator "("; e <- expr; punctuator ")"; return $ PrimExprParens e }
arrayLit :: JSParser ArrayLit
arrayLit =
try (do { punctuator "["; me <- optionMaybe elision; punctuator "]"; return $ ArrayLitH me }) <|>
try (do { punctuator "["; el <- elementList; punctuator "]"; return $ ArrayLit el }) <|>
do { punctuator "[";
el <- elementList;
punctuator ",";
me <- optionMaybe elision;
punctuator "]";
return $ ArrayLitT el me }
elementList :: JSParser ElementList
elementList =
do { me <- optionMaybe elision; ae <- assignExpr; applyRest elementListRest (ElementList me ae) }
elementListRest :: JSParser (ElementList -> JSParser ElementList)
elementListRest =
do { punctuator ","; me <- optionMaybe elision; ae <- assignExpr; return $ \el -> applyRest elementListRest (ElementListCons el me ae) }
elision :: JSParser Elision
elision =
do { punctuator ","; applyRest elisionRest ElisionComma }
elisionRest :: JSParser (Elision -> JSParser Elision)
elisionRest =
do { punctuator ","; return $ \e -> applyRest elisionRest (ElisionCons e) }
objectLit :: JSParser ObjectLit
objectLit =
try (do { punctuator "{"; punctuator "}"; return ObjectLitEmpty }) <|>
do { punctuator "{"; pl <- propList; optional $ punctuator ","; punctuator "}"; return $ ObjectLit pl }
propList :: JSParser PropList
propList =
do { pa <- propAssign; applyRest propListRest (PropListAssign pa) }
propListRest :: JSParser (PropList -> JSParser PropList)
propListRest =
do { punctuator ","; pa <- propAssign; return $ \pl -> applyRest propListRest (PropListCons pl pa) }
propAssign :: JSParser PropAssign
propAssign =
do { pn <- propName; punctuator ":"; ae <- assignExpr; return $ PropAssignField pn ae } <|>
do { identName "get"; pn <- propName; punctuator "("; punctuator ")"; punctuator "{"; fb <- funcBody; punctuator "}"; return $ PropAssignGet pn fb } <|>
do { identName "set"; pn <- propName; punctuator "("; pl <- propSetParamList; punctuator ")"; punctuator "{"; fb <- funcBody; punctuator "}"; return $ PropAssignSet pn pl fb }
propName :: JSParser PropName
propName =
do { name <- getIdentName; return $ PropNameId name } <|>
do { sl <- getStringLit; return $ PropNameStr sl } <|>
do { nl <- getNumLit; return $ PropNameNum nl }
propSetParamList :: JSParser PropSetParamList
propSetParamList =
do { i <- getIdent; return $ PropSetParamList i }
memberExpr :: JSParser MemberExpr
memberExpr =
do { identName "new"; me <- memberExpr; args <- arguments; applyRest memberExprRest (MemberExprNew me args) } <|>
do { pe <- primExpr; applyRest memberExprRest (MemberExprPrim pe) } <|>
do { fe <- funcExpr; applyRest memberExprRest (MemberExprFunc fe) }
memberExprRest :: JSParser (MemberExpr -> JSParser MemberExpr)
memberExprRest =
do { punctuator "["; e <- expr; punctuator "]"; return $ \me -> applyRest memberExprRest (MemberExprArray me e) } <|>
do { punctuator "."; name <- getIdentName; return $ \me -> applyRest memberExprRest (MemberExprDot me name) }
newExpr :: JSParser NewExpr
newExpr =
try (do { me <- memberExpr; return $ NewExprMember me }) <|>
do { identName "new"; ne <- newExpr; return $ NewExprNew ne }
callExpr :: JSParser CallExpr
callExpr =
do { me <- memberExpr; args <- arguments; applyRest callExprRest (CallExprMember me args) }
callExprRest :: JSParser (CallExpr -> JSParser CallExpr)
callExprRest =
do { args <- arguments; return $ \ce -> applyRest callExprRest (CallExprCall ce args) } <|>
do { punctuator "["; e <- expr; punctuator "]"; return $ \ce -> applyRest callExprRest (CallExprArray ce e) } <|>
do { punctuator "."; name <- getIdentName; return $ \ce -> applyRest callExprRest (CallExprDot ce name) }
arguments :: JSParser Arguments
arguments =
try (do { punctuator "("; punctuator ")"; return ArgumentsEmpty }) <|>
do { punctuator "("; al <- argumentList; punctuator ")"; return $ Arguments al }
argumentList :: JSParser ArgumentList
argumentList =
chainl1'
(do { ae <- assignExpr; return $ ArgumentList ae })
assignExpr
(do { punctuator ","; return ArgumentListCons })
leftExpr :: JSParser LeftExpr
leftExpr =
try (do { ce <- callExpr; return $ LeftExprCallExpr ce }) <|>
do { ne <- newExpr; return $ LeftExprNewExpr ne }
postFixExpr :: JSParser PostFixExpr
postFixExpr = do
le <- leftExpr
do { punctuator "++"; return $ PostFixExprPostInc le } <|>
do { punctuator "--"; return $ PostFixExprPostDec le } <|>
do { return $ PostFixExprLeftExpr le }
uExpr :: JSParser UExpr
uExpr =
do { identName "delete"; u <- uExpr; return $ UExprDelete u } <|>
do { identName "void"; u <- uExpr; return $ UExprVoid u } <|>
do { identName "typeof"; u <- uExpr; return $ UExprTypeOf u } <|>
do { punctuator "++"; u <- uExpr; return $ UExprDoublePlus u } <|>
do { punctuator "--"; u <- uExpr; return $ UExprDoubleMinus u } <|>
do { punctuator "+"; u <- uExpr; return $ UExprUnaryPlus u } <|>
do { punctuator "-"; u <- uExpr; return $ UExprUnaryMinus u } <|>
do { punctuator "~"; u <- uExpr; return $ UExprBitNot u } <|>
do { punctuator "!"; u <- uExpr; return $ UExprNot u } <|>
do { pe <- postFixExpr; return $ UExprPostFix pe }
multExpr :: JSParser MultExpr
multExpr =
chainl1'
(do { u <- uExpr; return $ MultExpr u })
uExpr
(do { punctuator "*"; return MultExprMult } <|>
do { punctuator "/"; return MultExprDiv } <|>
do { punctuator "%"; return MultExprMod })
addExpr :: JSParser AddExpr
addExpr =
chainl1'
(do { m <- multExpr; return $ AddExpr m })
multExpr
(do { punctuator "+"; return AddExprAdd } <|>
do { punctuator "-"; return AddExprSub })
shiftExpr :: JSParser ShiftExpr
shiftExpr =
chainl1'
(do { a <- addExpr; return $ ShiftExpr a })
addExpr
(do { punctuator "<<"; return ShiftExprLeft } <|>
do { punctuator ">>"; return ShiftExprRight } <|>
do { punctuator ">>>"; return ShiftExprRightZero })
relExpr :: JSParser RelExpr
relExpr =
chainl1'
(do { s <- shiftExpr; return $ RelExpr s })
shiftExpr
(do { punctuator "<"; return RelExprLess } <|>
do { punctuator ">"; return RelExprGreater } <|>
do { punctuator "<="; return RelExprLessEq } <|>
do { punctuator ">="; return RelExprGreaterEq } <|>
do { identName "instanceof"; return RelExprInstanceOf } <|>
do { identName "in"; return RelExprIn })
relExprNoIn :: JSParser RelExprNoIn
relExprNoIn =
chainl1'
(do { s <- shiftExpr; return $ RelExprNoIn s })
shiftExpr
(do { punctuator "<"; return RelExprNoInLess } <|>
do { punctuator ">"; return RelExprNoInGreater } <|>
do { punctuator "<="; return RelExprNoInLessEq } <|>
do { punctuator ">="; return RelExprNoInGreaterEq } <|>
do { identName "instanceof"; return RelExprNoInInstanceOf })
eqExpr :: JSParser EqExpr
eqExpr =
chainl1'
(do { r <- relExpr; return $ EqExpr r })
relExpr
(do { punctuator "=="; return EqExprEq } <|>
do { punctuator "!="; return EqExprNotEq } <|>
do { punctuator "==="; return EqExprStrictEq } <|>
do { punctuator "!=="; return EqExprStrictNotEq })
eqExprNoIn :: JSParser EqExprNoIn
eqExprNoIn =
chainl1'
(do { r <- relExprNoIn; return $ EqExprNoIn r })
relExprNoIn
(do { punctuator "=="; return EqExprNoInEq } <|>
do { punctuator "!="; return EqExprNoInNotEq } <|>
do { punctuator "==="; return EqExprNoInStrictEq } <|>
do { punctuator "!=="; return EqExprNoInStrictNotEq })
bitAndExpr :: JSParser BitAndExpr
bitAndExpr =
chainl1'
(do { e <- eqExpr; return $ BitAndExpr e })
eqExpr
(do { punctuator "&"; return $ BitAndExprAnd })
bitAndExprNoIn :: JSParser BitAndExprNoIn
bitAndExprNoIn =
chainl1'
(do { e <- eqExprNoIn; return $ BitAndExprNoIn e })
eqExprNoIn
(do { punctuator "&"; return $ BitAndExprNoInAnd })
bitXorExpr :: JSParser BitXorExpr
bitXorExpr =
chainl1'
(do { bae <- bitAndExpr; return $ BitXorExpr bae })
bitAndExpr
(do { punctuator "^"; return $ BitXorExprXor })
bitXorExprNoIn :: JSParser BitXorExprNoIn
bitXorExprNoIn =
chainl1'
(do { bae <- bitAndExprNoIn; return $ BitXorExprNoIn bae })
bitAndExprNoIn
(do { punctuator "^"; return $ BitXorExprNoInXor })
bitOrExpr :: JSParser BitOrExpr
bitOrExpr =
chainl1'
(do { bxe <- bitXorExpr; return $ BitOrExpr bxe })
bitXorExpr
(do { punctuator "|"; return $ BitOrExprOr })
bitOrExprNoIn :: JSParser BitOrExprNoIn
bitOrExprNoIn =
chainl1'
(do { bxe <- bitXorExprNoIn; return $ BitOrExprNoIn bxe })
bitXorExprNoIn
(do { punctuator "|"; return $ BitOrExprNoInOr })
logicalAndExpr :: JSParser LogicalAndExpr
logicalAndExpr =
chainl1'
(do { boe <- bitOrExpr; return $ LogicalAndExpr boe })
bitOrExpr
(do { punctuator "&&"; return $ LogicalAndExprAnd })
logicalAndExprNoIn :: JSParser LogicalAndExprNoIn
logicalAndExprNoIn =
chainl1'
(do { boe <- bitOrExprNoIn; return $ LogicalAndExprNoIn boe })
bitOrExprNoIn
(do { punctuator "&&"; return $ LogicalAndExprNoInAnd })
logicalOrExpr :: JSParser LogicalOrExpr
logicalOrExpr =
chainl1'
(do { lae <- logicalAndExpr; return $ LogicalOrExpr lae })
logicalAndExpr
(do { punctuator "||"; return $ LogicalOrExprOr })
logicalOrExprNoIn :: JSParser LogicalOrExprNoIn
logicalOrExprNoIn =
chainl1'
(do { lae <- logicalAndExprNoIn; return $ LogicalOrExprNoIn lae })
logicalAndExprNoIn
(do { punctuator "||"; return $ LogicalOrExprNoInOr })
condExpr :: JSParser CondExpr
condExpr = do
loe <- logicalOrExpr
do { try $ do { punctuator "?"; }; ae1 <- assignExpr; punctuator ":"; ae2 <- assignExpr; return $ CondExprIf loe ae1 ae2 } <|>
do { return $ CondExpr loe }
condExprNoIn :: JSParser CondExprNoIn
condExprNoIn = do
loe <- logicalOrExprNoIn;
do { try $ do { punctuator "?"; }; ae1 <- assignExpr; punctuator ":"; ae2 <- assignExpr; return $ CondExprNoInIf loe ae1 ae2 } <|>
do { return $ CondExprNoIn loe }
assignExpr :: JSParser AssignExpr
assignExpr =
try (do { le <- leftExpr; ao <- assignOp; ae <- assignExpr; return $ AssignExprAssign le ao ae }) <|>
do { ce <- condExpr; return $ AssignExprCondExpr ce }
assignExprNoIn :: JSParser AssignExprNoIn
assignExprNoIn =
try (do { le <- leftExpr; ao <- assignOp; ae <- assignExprNoIn; return $ AssignExprNoInAssign le ao ae }) <|>
do { ce <- condExprNoIn; return $ AssignExprNoInCondExpr ce }
assignOp :: JSParser AssignOp
assignOp =
do { punctuator "="; return AssignOpNormal } <|>
do { punctuator "*="; return AssignOpMult } <|>
do { punctuator "/="; return AssignOpDiv } <|>
do { punctuator "%="; return AssignOpMod } <|>
do { punctuator "+="; return AssignOpPlus } <|>
do { punctuator "-="; return AssignOpMinus } <|>
do { punctuator "<<="; return AssignOpShiftLeft } <|>
do { punctuator ">>="; return AssignOpShiftRight } <|>
do { punctuator ">>>="; return AssignOpShiftRightZero } <|>
do { punctuator "&="; return AssignOpBitAnd } <|>
do { punctuator "^="; return AssignOpBitXor } <|>
do { punctuator "|="; return AssignOpBitOr }
expr :: JSParser Expr
expr =
chainl1'
(do { ae <- assignExpr; return $ Expr ae })
assignExpr
(do { punctuator ","; return ExprCons })
exprNoIn :: JSParser ExprNoIn
exprNoIn =
chainl1'
(do { ae <- assignExprNoIn; return $ ExprNoIn ae })
assignExprNoIn
(do { punctuator ","; return ExprNoInCons })
stmt :: JSParser Stmt
stmt =
do { b <- block; return $ StmtBlock b } <|>
do { vs <- varStmt; return $ StmtVar vs } <|>
do { es <- emptyStmt; return $ StmtEmpty es } <|>
try (do { es <- exprStmt; return $ StmtExpr es }) <|>
do { ic <- contStmt; return $ StmtCont ic } <|>
do { is <- ifStmt; return $ StmtIf is } <|>
do { is <- itStmt; return $ StmtIt is } <|>
do { bs <- breakStmt; return $ StmtBreak bs } <|>
do { rs <- returnStmt; return $ StmtReturn rs } <|>
do { ws <- withStmt; return $ StmtWith ws } <|>
do { ss <- switchStmt; return $ StmtSwitch ss } <|>
do { ts <- throwStmt; return $ StmtThrow ts } <|>
do { ts <- tryStmt; return $ StmtTry ts } <|>
do { ds <- dbgStmt; return $ StmtDbg ds } <|>
do { ls <- labelledStmt; return $ StmtLabelled ls }
block :: JSParser Block
block =
do { punctuator "{"; msl <- optionMaybe stmtList; punctuator "}"; return $ Block msl }
stmtList :: JSParser StmtList
stmtList =
chainl1'
(do { s <- stmt; return $ StmtList s })
stmt
(do { return StmtListCons })
varStmt :: JSParser VarStmt
varStmt =
do { identName "var"; vdl <- varDeclList; return $ VarStmt vdl }
varDeclList :: JSParser VarDeclList
varDeclList =
chainl1'
(do { vd <- varDecl; return $ VarDeclList vd})
varDecl
(do { punctuator ","; return $ VarDeclListCons })
varDeclListNoIn :: JSParser VarDeclListNoIn
varDeclListNoIn =
chainl1'
(do { vd <- varDeclNoIn; return $ VarDeclListNoIn vd})
varDeclNoIn
(do { punctuator ","; return $ VarDeclListNoInCons})
varDecl :: JSParser VarDecl
varDecl =
do { i <- getIdent; mInit <- optionMaybe initialiser; return $ VarDecl i mInit }
varDeclNoIn :: JSParser VarDeclNoIn
varDeclNoIn =
do { i <- getIdent; mInit <- optionMaybe initialiserNoIn; return $ VarDeclNoIn i mInit }
initialiser :: JSParser Initialiser
initialiser =
do { punctuator "="; ae <- assignExpr; return $ Initialiser ae }
initialiserNoIn :: JSParser InitialiserNoIn
initialiserNoIn =
do { punctuator "="; ae <- assignExprNoIn; return $ InitialiserNoIn ae }
emptyStmt :: JSParser EmptyStmt
emptyStmt =
do { punctuator ";"; return EmptyStmt }
exprStmt :: JSParser ExprStmt
exprStmt =
do { notFollowedBy (try $ punctuator "{" <|> identName "function"); e <- expr; autoSemi; return $ ExprStmt e }
ifStmt :: JSParser IfStmt
ifStmt =
try (do { identName "if"; punctuator "("; e <- expr; punctuator ")"; s1 <- stmt; identName "else"; s2 <- stmt; return $ IfStmtIfElse e s1 s2 }) <|>
do { identName "if"; punctuator "("; e <- expr; punctuator ")"; s <- stmt; return $ IfStmtIf e s }
itStmt :: JSParser ItStmt
itStmt =
try (do { identName "do"; s <- stmt; identName "while"; punctuator "("; e <- expr; punctuator ")"; return $ ItStmtDoWhile s e }) <|>
try (do { identName "while"; punctuator "("; e <- expr; punctuator ")"; s <- stmt; return $ ItStmtWhile e s }) <|>
try (do { identName "for"; punctuator "("; me1 <- optionMaybe exprNoIn; punctuator ";"; me2 <- optionMaybe expr; punctuator ";"; me3 <- optionMaybe expr; punctuator ")"; s <- stmt; return $ ItStmtFor me1 me2 me3 s }) <|>
try (do { identName "for"; punctuator "("; identName "var"; vdl <- varDeclListNoIn; punctuator ";"; me1 <- optionMaybe expr; punctuator ";"; me2 <- optionMaybe expr; punctuator ")"; s <- stmt; return $ ItStmtForVar vdl me1 me2 s }) <|>
do { identName "for"; punctuator "("; le <- leftExpr; identName "in"; e <- expr; punctuator ")"; s <- stmt; return $ ItStmtForIn le e s } <|>
do { identName "for"; punctuator "("; identName "var"; vd <- varDeclNoIn; identName "in"; e <- expr; punctuator ")"; s <- stmt; return $ ItStmtForVarIn vd e s }
contStmt :: JSParser ContStmt
contStmt =
try (do { identName "continue"; autoSemi; return ContStmt }) <|>
do { identName "continue"; noLineTerminatorHere; i <- getIdent; autoSemi; return $ ContStmtLabelled i }
breakStmt :: JSParser BreakStmt
breakStmt =
try (do { identName "break"; autoSemi; return BreakStmt }) <|>
do { identName "break"; noLineTerminatorHere; i <- getIdent; autoSemi; return $ BreakStmtLabelled i }
returnStmt :: JSParser ReturnStmt
returnStmt =
try (do { identName "return"; autoSemi; return ReturnStmt }) <|>
do { identName "return"; noLineTerminatorHere; e <- expr; autoSemi; return $ ReturnStmtExpr e }
withStmt :: JSParser WithStmt
withStmt =
do { identName "with"; punctuator "("; e <- expr; punctuator ")"; s <- stmt; return $ WithStmt e s }
switchStmt :: JSParser SwitchStmt
switchStmt =
do { identName "switch"; punctuator "("; e <- expr; punctuator ")"; cb <- caseBlock; return $ SwitchStmt e cb }
caseBlock :: JSParser CaseBlock
caseBlock =
try (do { punctuator "{"; mcc <- optionMaybe caseClauses; punctuator "}"; return $ CaseBlock mcc }) <|>
do { punctuator "{"; mcc1 <- optionMaybe caseClauses; dc <- defaultClause; mcc2 <- optionMaybe caseClauses; punctuator "}"; return $ CaseBlockDefault mcc1 dc mcc2 }
caseClauses :: JSParser CaseClauses
caseClauses =
chainl1'
(do { cc <- caseClause; return $ CaseClauses cc })
caseClause
(do { return $ CaseClausesCons })
caseClause :: JSParser CaseClause
caseClause =
do { identName "case"; e <- expr; punctuator ":"; msl <- optionMaybe stmtList; return $ CaseClause e msl }
defaultClause :: JSParser DefaultClause
defaultClause =
do { identName "default"; punctuator ":"; msl <- optionMaybe stmtList; return $ DefaultClause msl }
labelledStmt :: JSParser LabelledStmt
labelledStmt =
do { i <- getIdent; punctuator ":"; s <- stmt; return $ LabelledStmt i s }
throwStmt :: JSParser ThrowStmt
throwStmt =
do { identName "throw"; noLineTerminatorHere; e <- expr; autoSemi; return $ ThrowStmt e }
tryStmt :: JSParser TryStmt
tryStmt = do
identName "try"
b <- block
do { f <- finally; return $ TryStmtBF b f } <|>
do { c <- catch;
do { f <- finally; return $ TryStmtBCF b c f } <|>
do { return $ TryStmtBC b c }
}
catch :: JSParser Catch
catch =
do { identName "catch"; punctuator "("; i <- getIdent; punctuator ")"; b <- block; return $ Catch i b }
finally :: JSParser Finally
finally =
do { identName "finally"; b <- block; return $ Finally b }
dbgStmt :: JSParser DbgStmt
dbgStmt =
do { identName "debugger"; autoSemi; return DbgStmt }
funcDecl :: JSParser FuncDecl
funcDecl =
do { identName "function"; i <- getIdent; punctuator "("; mfpl <- optionMaybe formalParamList; punctuator ")"; punctuator "{"; fb <- funcBody; punctuator "}"; return $ FuncDecl i mfpl fb }
funcExpr :: JSParser FuncExpr
funcExpr =
do { identName "function"; mi <- optionMaybe getIdent; punctuator "("; mfpl <- optionMaybe formalParamList; punctuator ")"; punctuator "{"; fb <- funcBody; punctuator "}"; return $ FuncExpr mi mfpl fb }
formalParamList :: JSParser FormalParamList
formalParamList =
chainl1'
(do { i <- getIdent; return $ FormalParamList i })
getIdent
(do { punctuator ","; return $ FormalParamListCons })
funcBody :: JSParser FuncBody
funcBody =
do { mse <- optionMaybe sourceElements; return $ FuncBody mse }
program :: JSParser Program
program =
do { mse <- optionMaybe sourceElements; return $ Program mse }
sourceElements :: JSParser SourceElements
sourceElements =
chainl1'
(do { se <- sourceElement; return $ SourceElements se })
sourceElement
(do { return SourceElementsCons })
sourceElement :: JSParser SourceElement
sourceElement =
do { s <- stmt; return $ SourceElementStmt s } <|>
do { fd <- funcDecl; return $ SourceElementFuncDecl fd }
parseJavaScript :: String -> Either ParseError Program
parseJavaScript input =
let p = many lineTerminator *> program <* many lineTerminator <* eof
in runParser p newJSPState "" $ lexJavaScript input
|
|
19efe67c9f0b31588b0dc1ae1376a8e19e66ad4a8a5967da907b234940f91f29 | pmonks/spinner | ansi.clj | ;
Copyright © 2022
;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; -2.0
;
; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
SPDX - License - Identifier : Apache-2.0
;
(ns progress.ansi
"Handy ANSI related functionality. Note: requiring this namespace has the side effect of enabling JANSI."
(:require [clojure.string :as s]
[jansi-clj.core :as jansi]))
(jansi/enable!)
(defn save-cursor!
"Issues both SCO and DEC save-cursor ANSI codes, for maximum compatibility."
[]
JANSI uses SCO code for cursor positioning , which is unfortunate as they 're less widely supported
So we manually send a DEC code too
(flush))
(defn restore-cursor!
"Issues both SCO and DEC restore-cursor ANSI codes, for maximum compatibility."
[]
JANSI uses SCO code for cursor positioning , which is unfortunate as they 're less widely supported
So we manually send a DEC code too
(flush))
(defn print-at
"Send text output to the specified screen locations (note: ANSI screen coordinates are 1-based). msgs may include jansi formatting."
[x y & msgs]
(save-cursor!)
(jansi/cursor! x y)
(jansi/erase-line!)
(apply print msgs)
(restore-cursor!))
(defn debug-print-at
"Send debug output to the specified screen location (note: ANSI screen coordinates are 1-based)."
[x y & args]
(print-at x y (jansi/a :bold (jansi/fg-bright :yellow (jansi/bg :red (str "DEBUG: " (s/join " " args)))))))
(defn debug-print
"Send debug output to the upper left corner of the screen, where (hopefully) it minimises interference with everything else."
[& args]
(apply debug-print-at 1 1 args))
(defn apply-colour
"Applies an 'enhanced' colour keyword (which may include the prefix 'bright-') to either the foreground or background of body."
[fg? colour-key s]
(let [bright? (s/starts-with? (name colour-key) "bright-")
colour-name (if bright? (keyword (subs (name colour-key) (count "bright-"))) colour-key)]
(case [fg? bright?]
[true true] (jansi/fg-bright colour-name s)
[true false] (jansi/fg colour-name s)
[false true] (jansi/bg-bright colour-name s)
[false false] (jansi/bg colour-name s))))
(defn apply-attributes
"Applies all of provided attributes (a seq) to s (a string)."
[attributes s]
((apply comp (map #(partial jansi/a %) attributes)) s))
(defn apply-colours-and-attrs
"Applies the foreground colour, background colour, and attributes (a seq) to s (a string)."
[fg-colour bg-colour attrs s]
(apply-attributes (if (seq attrs) attrs [:default])
(apply-colour false (if bg-colour bg-colour :default)
((partial apply-colour true (if fg-colour fg-colour :default)) s))))
| null | https://raw.githubusercontent.com/pmonks/spinner/bc29faefad8caf4bfa3ab2ef1785de04ed514fed/src/progress/ansi.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| Copyright © 2022
distributed under the License is distributed on an " AS IS " BASIS ,
SPDX - License - Identifier : Apache-2.0
(ns progress.ansi
"Handy ANSI related functionality. Note: requiring this namespace has the side effect of enabling JANSI."
(:require [clojure.string :as s]
[jansi-clj.core :as jansi]))
(jansi/enable!)
(defn save-cursor!
"Issues both SCO and DEC save-cursor ANSI codes, for maximum compatibility."
[]
JANSI uses SCO code for cursor positioning , which is unfortunate as they 're less widely supported
So we manually send a DEC code too
(flush))
(defn restore-cursor!
"Issues both SCO and DEC restore-cursor ANSI codes, for maximum compatibility."
[]
JANSI uses SCO code for cursor positioning , which is unfortunate as they 're less widely supported
So we manually send a DEC code too
(flush))
(defn print-at
"Send text output to the specified screen locations (note: ANSI screen coordinates are 1-based). msgs may include jansi formatting."
[x y & msgs]
(save-cursor!)
(jansi/cursor! x y)
(jansi/erase-line!)
(apply print msgs)
(restore-cursor!))
(defn debug-print-at
"Send debug output to the specified screen location (note: ANSI screen coordinates are 1-based)."
[x y & args]
(print-at x y (jansi/a :bold (jansi/fg-bright :yellow (jansi/bg :red (str "DEBUG: " (s/join " " args)))))))
(defn debug-print
"Send debug output to the upper left corner of the screen, where (hopefully) it minimises interference with everything else."
[& args]
(apply debug-print-at 1 1 args))
(defn apply-colour
"Applies an 'enhanced' colour keyword (which may include the prefix 'bright-') to either the foreground or background of body."
[fg? colour-key s]
(let [bright? (s/starts-with? (name colour-key) "bright-")
colour-name (if bright? (keyword (subs (name colour-key) (count "bright-"))) colour-key)]
(case [fg? bright?]
[true true] (jansi/fg-bright colour-name s)
[true false] (jansi/fg colour-name s)
[false true] (jansi/bg-bright colour-name s)
[false false] (jansi/bg colour-name s))))
(defn apply-attributes
"Applies all of provided attributes (a seq) to s (a string)."
[attributes s]
((apply comp (map #(partial jansi/a %) attributes)) s))
(defn apply-colours-and-attrs
"Applies the foreground colour, background colour, and attributes (a seq) to s (a string)."
[fg-colour bg-colour attrs s]
(apply-attributes (if (seq attrs) attrs [:default])
(apply-colour false (if bg-colour bg-colour :default)
((partial apply-colour true (if fg-colour fg-colour :default)) s))))
|
446eb2432e381200e6409485db164f5fe9d3002eb2af48ae915732f9989de352 | Clojure2D/clojure2d | protocols.clj | (ns clojure2d.protocols)
(defprotocol ImageProto
"Image Protocol"
(get-image [i] "Return BufferedImage")
(width [i] "Width of the image.")
(height [i] "Height of the image.")
(save [i n] "Save image `i` to a file `n`.")
(convolve [i t] "Convolve with Java ConvolveOp. See [[convolution-matrices]] for kernel names.")
(subimage [i x y w h] "Return part of the image.")
(resize [i w h] "Resize image."))
(defprotocol MouseXYProto
"Mouse position."
(mouse-x [m] "Mouse horizontal position within window. 0 - left side. -1 outside window.")
(mouse-y [m] "Mouse vertical position. 0 - top, -1 outside window.")
(mouse-pos [m] "Mouse position as [[Vec2]] type. [0,0] - top left, [-1,-1] outside window."))
(defprotocol MouseButtonProto
"Get pressed mouse button status."
(mouse-button [m] "Get mouse pressed button status: :left :right :center or :none"))
(defprotocol KeyEventProto
"Access to key event data"
(key-code [e] "Keycode mapped to keyword. See `java.awt.event.KeyEvent` documentation. Eg. `VK_LEFT` is mapped to `:left`.")
(key-char [e] "Key as char.")
(key-raw [e] "Raw value for pressed key (as integer)."))
(defprotocol ModifiersProto
"Get state of keyboard modifiers."
(control-down? [e] "CONTROL key state as boolean.")
(alt-down? [e] "ALT key state as boolean.")
(meta-down? [e] "META key state as boolean.")
(shift-down? [e] "SHIFT key state as boolean.")
(alt-gr-down? [e] "ALT-GR key state as boolean."))
(defprotocol PressedProto
"Key or mouse pressed status."
(^{:metadoc/categories #{:window :events}} key-pressed? [w] "Any key pressed? (boolean)")
(^{:metadoc/categories #{:window :events}} mouse-pressed? [w] "Any mouse button pressed? (boolean)"))
Define ` ColorProto ` for representation conversions .
(defprotocol ColorProto
"Basic color operations"
(to-color [c] "Convert any color representation to `Vec4` vector.")
(to-awt-color [c] "Convert any color representation to `java.awt.Color`.")
(luma [c] "Returns luma")
(red [c] "Returns red (first channel) value. See also [[ch0]].")
(green [c] "Returns green (second channel) value. See also [[ch1]].")
(blue [c] "Returns blue (third channel) value. See also [[ch2]].")
(alpha [c] "Returns alpha value."))
(defprotocol PixelsProto
"Functions for accessing and setting channel values or colors. PixelsProto is used in following types:
* `Pixels` - all functions
* `Image`, `Canvas`, `Window` - Only [[get-value]] and [[get-color]] for given position and conversion to Pixels. Accessing color or channel value is slow.
* `Log density renderer` - Only [[set-color!]], [[get-color]] and conversion to Pixels. "
(get-value [pixels ch x y] [pixels ch idx] "Get channel value by index or position.")
(get-color [pixels x y] [pixels idx] "Get color by index or position. In case of low density rendering returns current average color without alpha value.")
(set-value! [pixels ch x y v] [pixels ch idx v] "Set channel value by index or position")
(set-color! [pixels x y v] [pixels idx v] "Set color value by index or position.")
(get-channel [pixels ch] "Return whole `ints` array with chosen channel")
(set-channel! [pixels ch v] "Set whole channel (as `ints` array)")
(to-pixels [pixels] [pixels cfg] [pixels x y w h] "Convert to Pixels. For low density rendering provide configuration. Works with Image/Canvas/Window and low density renderer."))
(defprotocol RendererProto
(add-pixel! [r x y] [r x y c])
(get-pixel [r x y]))
(defprotocol ShapeProto
(bounding-box [shape])
(contains-point? [shape x y])
(contains-rectangle? [shape x y w h])
(intersects-rectangle? [shape x y w h]))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d/5cb4dbfe6ed492c8c003f28aea4f1611470484c2/src/clojure2d/protocols.clj | clojure | (ns clojure2d.protocols)
(defprotocol ImageProto
"Image Protocol"
(get-image [i] "Return BufferedImage")
(width [i] "Width of the image.")
(height [i] "Height of the image.")
(save [i n] "Save image `i` to a file `n`.")
(convolve [i t] "Convolve with Java ConvolveOp. See [[convolution-matrices]] for kernel names.")
(subimage [i x y w h] "Return part of the image.")
(resize [i w h] "Resize image."))
(defprotocol MouseXYProto
"Mouse position."
(mouse-x [m] "Mouse horizontal position within window. 0 - left side. -1 outside window.")
(mouse-y [m] "Mouse vertical position. 0 - top, -1 outside window.")
(mouse-pos [m] "Mouse position as [[Vec2]] type. [0,0] - top left, [-1,-1] outside window."))
(defprotocol MouseButtonProto
"Get pressed mouse button status."
(mouse-button [m] "Get mouse pressed button status: :left :right :center or :none"))
(defprotocol KeyEventProto
"Access to key event data"
(key-code [e] "Keycode mapped to keyword. See `java.awt.event.KeyEvent` documentation. Eg. `VK_LEFT` is mapped to `:left`.")
(key-char [e] "Key as char.")
(key-raw [e] "Raw value for pressed key (as integer)."))
(defprotocol ModifiersProto
"Get state of keyboard modifiers."
(control-down? [e] "CONTROL key state as boolean.")
(alt-down? [e] "ALT key state as boolean.")
(meta-down? [e] "META key state as boolean.")
(shift-down? [e] "SHIFT key state as boolean.")
(alt-gr-down? [e] "ALT-GR key state as boolean."))
(defprotocol PressedProto
"Key or mouse pressed status."
(^{:metadoc/categories #{:window :events}} key-pressed? [w] "Any key pressed? (boolean)")
(^{:metadoc/categories #{:window :events}} mouse-pressed? [w] "Any mouse button pressed? (boolean)"))
Define ` ColorProto ` for representation conversions .
(defprotocol ColorProto
"Basic color operations"
(to-color [c] "Convert any color representation to `Vec4` vector.")
(to-awt-color [c] "Convert any color representation to `java.awt.Color`.")
(luma [c] "Returns luma")
(red [c] "Returns red (first channel) value. See also [[ch0]].")
(green [c] "Returns green (second channel) value. See also [[ch1]].")
(blue [c] "Returns blue (third channel) value. See also [[ch2]].")
(alpha [c] "Returns alpha value."))
(defprotocol PixelsProto
"Functions for accessing and setting channel values or colors. PixelsProto is used in following types:
* `Pixels` - all functions
* `Image`, `Canvas`, `Window` - Only [[get-value]] and [[get-color]] for given position and conversion to Pixels. Accessing color or channel value is slow.
* `Log density renderer` - Only [[set-color!]], [[get-color]] and conversion to Pixels. "
(get-value [pixels ch x y] [pixels ch idx] "Get channel value by index or position.")
(get-color [pixels x y] [pixels idx] "Get color by index or position. In case of low density rendering returns current average color without alpha value.")
(set-value! [pixels ch x y v] [pixels ch idx v] "Set channel value by index or position")
(set-color! [pixels x y v] [pixels idx v] "Set color value by index or position.")
(get-channel [pixels ch] "Return whole `ints` array with chosen channel")
(set-channel! [pixels ch v] "Set whole channel (as `ints` array)")
(to-pixels [pixels] [pixels cfg] [pixels x y w h] "Convert to Pixels. For low density rendering provide configuration. Works with Image/Canvas/Window and low density renderer."))
(defprotocol RendererProto
(add-pixel! [r x y] [r x y c])
(get-pixel [r x y]))
(defprotocol ShapeProto
(bounding-box [shape])
(contains-point? [shape x y])
(contains-rectangle? [shape x y w h])
(intersects-rectangle? [shape x y w h]))
|
|
91a51939ffe6c2af35192d89736524140b26983ad5a178dffc8f3b294cfef85b | russmatney/org-crud | core.clj | (ns organum.core
"From: "
(:require [clojure.java.io :as io]
[clojure.string :as string]
[babashka.fs :as fs]))
(defn classify-line
"Classify a line for dispatch to handle-line multimethod."
[ln]
(let [headline-re #"^(\*+)\s*(.*)$"
pdrawer-re #"^\s*:(PROPERTIES|END):"
pdrawer (fn [x] (second (re-matches pdrawer-re x)))
pdrawer-item-re #"^\s*:([0-9A-Za-z_\-]+):\s*(.*)$"
block-re #"^\s*#\+(BEGIN|END|begin|end)_(\w*)\s*([0-9A-Za-z_\-]*)?.*"
block (fn [x] (rest (re-matches block-re x)))
def-list-re #"^\s*(-|\+|\s+[*])\s*(.*?)::.*"
ordered-list-re #"^\s*\d+(\.|\))\s+.*"
unordered-list-re #"^\s*(-|\+|\s+[*])\s+.*"
metadata-re #"^\s*(CLOCK|DEADLINE|START|CLOSED|SCHEDULED):.*"
table-sep-re #"^\s*\|[-\|\+]*\s*$"
table-row-re #"^\\s*\\|.*"
inline-example-re #"^\s*:\s.*"
horiz-re #"^\s*-{5,}\s*$"]
(cond
(re-matches headline-re ln) :headline
(string/blank? ln) :blank
(re-matches def-list-re ln) :definition-list
(re-matches ordered-list-re ln) :ordered-list
(re-matches unordered-list-re ln) :unordered-list
(= (pdrawer ln) "PROPERTIES") :property-drawer-begin-block
(= (pdrawer ln) "END") :property-drawer-end-block
(re-matches pdrawer-item-re ln) :property-drawer-item
(re-matches metadata-re ln) :metadata
(#{"BEGIN" "begin"} (first (block ln))) :begin-block
(#{"END" "end"} (first (block ln))) :end-block
(= (second (block ln)) "COMMENT") :comment
(= (first ln) \#) #_ (not (= (second ln) \+)) :comment
(re-matches table-sep-re ln) :table-separator
(re-matches table-row-re ln) :table-row
(re-matches inline-example-re ln) :inline-example
(re-matches horiz-re ln) :horizontal-rule
:else :paragraph)))
(defn strip-tags
"Return the line with tags stripped out and list of tags"
[ln]
(if-let [[_ text tags] (re-matches #"(.*?)\s*(:[\w:]*:)\s*$" ln)]
[text (remove string/blank? (string/split tags #":"))]
[ln nil]))
(defn strip-keyword
"Return the line with keyword stripped out and list of keywords"
[ln]
(let [keywords-re #"()?"
words (string/split ln #"\s+")]
(if (re-matches keywords-re (words 0))
[(string/triml (string/replace-first ln (words 0) "")) (words 0)]
[ln nil])))
;; node constructors
(defn node [type] {:type type :content []})
(defn root [] (node :root))
(defn section [level name tags kw]
(merge (node :section)
{:level level :name name :tags tags :kw kw}))
(defn block [type qualifier]
(merge (node :block)
{:block-type type :qualifier qualifier}))
(defn drawer [] (node :drawer))
(defn line [type text]
{:line-type type :text text})
State helpers
(defn subsume
"Updates the current node (header, block, drawer) to contain the specified
item."
[state item]
(let [top (last state)
new (update-in top [:content] conj item)]
(conj (pop state) new)))
(defn subsume-top
"Closes off the top node by subsuming it into its parent's content"
[state]
(let [top (last state)
state (pop state)]
(subsume state top)))
(defn create-new-section [ln]
(when-let [[_ prefix text] (re-matches #"^(\*+)\s*(.*?)$" ln)]
(let [[text tags] (strip-tags text)
[text kw] (strip-keyword text)]
(section (count prefix) text tags kw))))
(defn parse-block [ln]
(let [block-re #"^\s*#\+(BEGIN|END|begin|end)_(\w*)\s*([0-9A-Za-z_\-]*)?"
[_ _ type qualifier] (re-matches block-re ln)]
TODO get other key values on blocks ?
(block type qualifier)))
;; handle line
(defmulti handle-line
"Parse line and return updated state."
(fn [_state ln] (classify-line ln)))
(defmethod handle-line :headline [state ln]
(conj state (create-new-section ln)))
(defmethod handle-line :begin-block [state ln]
(conj state (parse-block ln)))
(defmethod handle-line :end-block [state _ln]
(subsume-top state))
(defmethod handle-line :property-drawer-begin-block [state _ln]
(conj state (drawer)))
(defmethod handle-line :property-drawer-end-block [state _ln]
(subsume-top state))
(defmethod handle-line :default [state ln]
(subsume state (line (classify-line ln) ln)))
;; parse file
(defn parse-file
"Parse file (name / url / File) into (flat) sequence of sections. First section may be type :root,
subsequent are type :section. Other parsed representations may be contained within the sections"
[f]
(with-open [rdr (io/reader f)]
(reduce handle-line [(root)] (line-seq rdr))))
(comment
(parse-file (str (fs/home) "/todo/readme.org"))
(parse-file (str (fs/home) "/todo/daily/2022-09-26.org"))
(parse-file (str (fs/home) "/todo/daily/2022-09-27.org"))
(parse-file (str (fs/home) "/todo/journal.org")))
| null | https://raw.githubusercontent.com/russmatney/org-crud/11069d59925461601718c4bb4c29f74126093891/src/organum/core.clj | clojure | node constructors
handle line
parse file | (ns organum.core
"From: "
(:require [clojure.java.io :as io]
[clojure.string :as string]
[babashka.fs :as fs]))
(defn classify-line
"Classify a line for dispatch to handle-line multimethod."
[ln]
(let [headline-re #"^(\*+)\s*(.*)$"
pdrawer-re #"^\s*:(PROPERTIES|END):"
pdrawer (fn [x] (second (re-matches pdrawer-re x)))
pdrawer-item-re #"^\s*:([0-9A-Za-z_\-]+):\s*(.*)$"
block-re #"^\s*#\+(BEGIN|END|begin|end)_(\w*)\s*([0-9A-Za-z_\-]*)?.*"
block (fn [x] (rest (re-matches block-re x)))
def-list-re #"^\s*(-|\+|\s+[*])\s*(.*?)::.*"
ordered-list-re #"^\s*\d+(\.|\))\s+.*"
unordered-list-re #"^\s*(-|\+|\s+[*])\s+.*"
metadata-re #"^\s*(CLOCK|DEADLINE|START|CLOSED|SCHEDULED):.*"
table-sep-re #"^\s*\|[-\|\+]*\s*$"
table-row-re #"^\\s*\\|.*"
inline-example-re #"^\s*:\s.*"
horiz-re #"^\s*-{5,}\s*$"]
(cond
(re-matches headline-re ln) :headline
(string/blank? ln) :blank
(re-matches def-list-re ln) :definition-list
(re-matches ordered-list-re ln) :ordered-list
(re-matches unordered-list-re ln) :unordered-list
(= (pdrawer ln) "PROPERTIES") :property-drawer-begin-block
(= (pdrawer ln) "END") :property-drawer-end-block
(re-matches pdrawer-item-re ln) :property-drawer-item
(re-matches metadata-re ln) :metadata
(#{"BEGIN" "begin"} (first (block ln))) :begin-block
(#{"END" "end"} (first (block ln))) :end-block
(= (second (block ln)) "COMMENT") :comment
(= (first ln) \#) #_ (not (= (second ln) \+)) :comment
(re-matches table-sep-re ln) :table-separator
(re-matches table-row-re ln) :table-row
(re-matches inline-example-re ln) :inline-example
(re-matches horiz-re ln) :horizontal-rule
:else :paragraph)))
(defn strip-tags
"Return the line with tags stripped out and list of tags"
[ln]
(if-let [[_ text tags] (re-matches #"(.*?)\s*(:[\w:]*:)\s*$" ln)]
[text (remove string/blank? (string/split tags #":"))]
[ln nil]))
(defn strip-keyword
"Return the line with keyword stripped out and list of keywords"
[ln]
(let [keywords-re #"()?"
words (string/split ln #"\s+")]
(if (re-matches keywords-re (words 0))
[(string/triml (string/replace-first ln (words 0) "")) (words 0)]
[ln nil])))
(defn node [type] {:type type :content []})
(defn root [] (node :root))
(defn section [level name tags kw]
(merge (node :section)
{:level level :name name :tags tags :kw kw}))
(defn block [type qualifier]
(merge (node :block)
{:block-type type :qualifier qualifier}))
(defn drawer [] (node :drawer))
(defn line [type text]
{:line-type type :text text})
State helpers
(defn subsume
"Updates the current node (header, block, drawer) to contain the specified
item."
[state item]
(let [top (last state)
new (update-in top [:content] conj item)]
(conj (pop state) new)))
(defn subsume-top
"Closes off the top node by subsuming it into its parent's content"
[state]
(let [top (last state)
state (pop state)]
(subsume state top)))
(defn create-new-section [ln]
(when-let [[_ prefix text] (re-matches #"^(\*+)\s*(.*?)$" ln)]
(let [[text tags] (strip-tags text)
[text kw] (strip-keyword text)]
(section (count prefix) text tags kw))))
(defn parse-block [ln]
(let [block-re #"^\s*#\+(BEGIN|END|begin|end)_(\w*)\s*([0-9A-Za-z_\-]*)?"
[_ _ type qualifier] (re-matches block-re ln)]
TODO get other key values on blocks ?
(block type qualifier)))
(defmulti handle-line
"Parse line and return updated state."
(fn [_state ln] (classify-line ln)))
(defmethod handle-line :headline [state ln]
(conj state (create-new-section ln)))
(defmethod handle-line :begin-block [state ln]
(conj state (parse-block ln)))
(defmethod handle-line :end-block [state _ln]
(subsume-top state))
(defmethod handle-line :property-drawer-begin-block [state _ln]
(conj state (drawer)))
(defmethod handle-line :property-drawer-end-block [state _ln]
(subsume-top state))
(defmethod handle-line :default [state ln]
(subsume state (line (classify-line ln) ln)))
(defn parse-file
"Parse file (name / url / File) into (flat) sequence of sections. First section may be type :root,
subsequent are type :section. Other parsed representations may be contained within the sections"
[f]
(with-open [rdr (io/reader f)]
(reduce handle-line [(root)] (line-seq rdr))))
(comment
(parse-file (str (fs/home) "/todo/readme.org"))
(parse-file (str (fs/home) "/todo/daily/2022-09-26.org"))
(parse-file (str (fs/home) "/todo/daily/2022-09-27.org"))
(parse-file (str (fs/home) "/todo/journal.org")))
|
5ccc4b1384e084fb949d93113062001ae3db4f79560513b7f5f73bdc2895a67e | anoma/juvix | Base.hs | module BackendC.Base where
import Base
import Data.FileEmbed
import Data.Text.IO qualified as TIO
import Juvix.Compiler.Backend.C.Translation.FromInternal as MiniC
import Juvix.Compiler.Builtins (iniState)
import Juvix.Compiler.Pipeline
import System.Process qualified as P
clangCompile ::
(Path Abs File -> Path Abs File -> [String]) ->
MiniC.MiniCResult ->
(Path Abs File -> IO Text) ->
(String -> IO ()) ->
IO Text
clangCompile mkClangArgs cResult execute step =
withTempDir'
( \dirPath -> do
let cOutputFile = dirPath <//> $(mkRelFile "out.c")
wasmOutputFile = dirPath <//> $(mkRelFile "Input.wasm")
TIO.writeFile (toFilePath cOutputFile) (cResult ^. MiniC.resultCCode)
step "WASM generation"
P.callProcess
"clang"
(mkClangArgs wasmOutputFile cOutputFile)
step "WASM execution"
execute wasmOutputFile
)
wasmClangAssertionCGenOnly :: Path Abs File -> ((String -> IO ()) -> Assertion)
wasmClangAssertionCGenOnly mainFile step = do
step "C Generation"
root <- getCurrentDir
let entryPoint = defaultEntryPoint root mainFile
(void . runIO' iniState entryPoint) upToMiniC
wasmClangAssertion :: WASMInfo -> Path Abs File -> Path Abs File -> ((String -> IO ()) -> Assertion)
wasmClangAssertion WASMInfo {..} mainFile expectedFile step = do
step "Check clang and wasmer are on path"
assertCmdExists $(mkRelFile "clang")
assertCmdExists $(mkRelFile "wasmer")
root <- getCurrentDir
step "C Generation"
let entryPoint = defaultEntryPoint root mainFile
p :: MiniC.MiniCResult <- snd <$> runIO' iniState entryPoint upToMiniC
expected <- TIO.readFile (toFilePath expectedFile)
step "Compile C with wasm standalone runtime"
actualStandalone <- clangCompile standaloneArgs p _wasmInfoActual step
step "Compare expected and actual program output"
assertEqDiffText ("Check: WASM output = " <> toFilePath expectedFile) actualStandalone expected
wasiClangAssertion :: StdlibMode -> Path Abs File -> Path Abs File -> Text -> ((String -> IO ()) -> Assertion)
wasiClangAssertion stdlibMode mainFile expectedFile stdinText step = do
step "Check clang and wasmer are on path"
assertCmdExists $(mkRelFile "clang")
assertCmdExists $(mkRelFile "wasmer")
step "Lookup WASI_SYSROOT_PATH"
sysrootPath <- getWasiSysrootPath
root <- getCurrentDir
step "C Generation"
let entryPoint = (defaultEntryPoint root mainFile) {_entryPointNoStdlib = stdlibMode == StdlibExclude}
p :: MiniC.MiniCResult <- snd <$> runIO' iniState entryPoint upToMiniC
expected <- TIO.readFile (toFilePath expectedFile)
let execute :: Path Abs File -> IO Text
execute outputFile = pack <$> P.readProcess "wasmer" [toFilePath outputFile] (unpack stdinText)
step "Compile C with standalone runtime"
actualStandalone <- clangCompile (wasiStandaloneArgs sysrootPath) p execute step
step "Compare expected and actual program output"
assertEqDiffText ("check: WASM output = " <> toFilePath expectedFile) actualStandalone expected
step "Compile C with libc runtime"
actualLibc <- clangCompile (libcArgs sysrootPath) p execute step
step "Compare expected and actual program output"
assertEqDiffText ("check: WASM output = " <> toFilePath expectedFile) actualLibc expected
builtinRuntime :: Path Abs Dir
builtinRuntime = absDir $(makeRelativeToProject "c-runtime/builtins" >>= strToExp)
standaloneArgs :: Path Abs File -> Path Abs File -> [String]
standaloneArgs wasmOutputFile cOutputFile =
[ "-nodefaultlibs",
"-std=c99",
"-Oz",
"-I",
toFilePath (parent minicRuntime),
"-I",
toFilePath builtinRuntime,
"-Werror",
"--target=wasm32",
"-nostartfiles",
"-Wl,--no-entry",
"-o",
toFilePath wasmOutputFile,
toFilePath wallocPath,
toFilePath cOutputFile
]
where
minicRuntime :: Path Abs File
minicRuntime = absFile $(makeRelativeToProject "c-runtime/standalone/c-runtime.h" >>= strToExp)
wallocPath :: Path Abs File
wallocPath = absFile $(makeRelativeToProject "c-runtime/walloc/walloc.c" >>= strToExp)
wasiStandaloneArgs :: Path Abs Dir -> Path Abs File -> Path Abs File -> [String]
wasiStandaloneArgs sysrootPath wasmOutputFile cOutputFile =
[ "-nodefaultlibs",
"-std=c99",
"-Oz",
"-I",
toFilePath (parent minicRuntime),
"-I",
toFilePath builtinRuntime,
"-Werror",
"--target=wasm32-wasi",
"--sysroot",
toFilePath sysrootPath,
"-o",
toFilePath wasmOutputFile,
toFilePath wallocPath,
toFilePath cOutputFile
]
where
minicRuntime :: Path Abs File
minicRuntime = absFile $(makeRelativeToProject "c-runtime/wasi-standalone/c-runtime.h" >>= strToExp)
wallocPath :: Path Abs File
wallocPath = absFile $(makeRelativeToProject "c-runtime/walloc/walloc.c" >>= strToExp)
libcArgs :: Path Abs Dir -> Path Abs File -> Path Abs File -> [String]
libcArgs sysrootPath wasmOutputFile cOutputFile =
[ "-nodefaultlibs",
"-std=c99",
"-Oz",
"-I",
toFilePath (parent minicRuntime),
"-I",
toFilePath builtinRuntime,
"-Werror",
"-lc",
"--target=wasm32-wasi",
"--sysroot",
toFilePath sysrootPath,
"-o",
toFilePath wasmOutputFile,
toFilePath cOutputFile
]
where
minicRuntime :: Path Abs File
minicRuntime = absFile $(makeRelativeToProject "c-runtime/wasi-libc/c-runtime.h" >>= strToExp)
| null | https://raw.githubusercontent.com/anoma/juvix/764c6faa8097066687cdb0431b17bf43a94adab1/test/BackendC/Base.hs | haskell | module BackendC.Base where
import Base
import Data.FileEmbed
import Data.Text.IO qualified as TIO
import Juvix.Compiler.Backend.C.Translation.FromInternal as MiniC
import Juvix.Compiler.Builtins (iniState)
import Juvix.Compiler.Pipeline
import System.Process qualified as P
clangCompile ::
(Path Abs File -> Path Abs File -> [String]) ->
MiniC.MiniCResult ->
(Path Abs File -> IO Text) ->
(String -> IO ()) ->
IO Text
clangCompile mkClangArgs cResult execute step =
withTempDir'
( \dirPath -> do
let cOutputFile = dirPath <//> $(mkRelFile "out.c")
wasmOutputFile = dirPath <//> $(mkRelFile "Input.wasm")
TIO.writeFile (toFilePath cOutputFile) (cResult ^. MiniC.resultCCode)
step "WASM generation"
P.callProcess
"clang"
(mkClangArgs wasmOutputFile cOutputFile)
step "WASM execution"
execute wasmOutputFile
)
wasmClangAssertionCGenOnly :: Path Abs File -> ((String -> IO ()) -> Assertion)
wasmClangAssertionCGenOnly mainFile step = do
step "C Generation"
root <- getCurrentDir
let entryPoint = defaultEntryPoint root mainFile
(void . runIO' iniState entryPoint) upToMiniC
wasmClangAssertion :: WASMInfo -> Path Abs File -> Path Abs File -> ((String -> IO ()) -> Assertion)
wasmClangAssertion WASMInfo {..} mainFile expectedFile step = do
step "Check clang and wasmer are on path"
assertCmdExists $(mkRelFile "clang")
assertCmdExists $(mkRelFile "wasmer")
root <- getCurrentDir
step "C Generation"
let entryPoint = defaultEntryPoint root mainFile
p :: MiniC.MiniCResult <- snd <$> runIO' iniState entryPoint upToMiniC
expected <- TIO.readFile (toFilePath expectedFile)
step "Compile C with wasm standalone runtime"
actualStandalone <- clangCompile standaloneArgs p _wasmInfoActual step
step "Compare expected and actual program output"
assertEqDiffText ("Check: WASM output = " <> toFilePath expectedFile) actualStandalone expected
wasiClangAssertion :: StdlibMode -> Path Abs File -> Path Abs File -> Text -> ((String -> IO ()) -> Assertion)
wasiClangAssertion stdlibMode mainFile expectedFile stdinText step = do
step "Check clang and wasmer are on path"
assertCmdExists $(mkRelFile "clang")
assertCmdExists $(mkRelFile "wasmer")
step "Lookup WASI_SYSROOT_PATH"
sysrootPath <- getWasiSysrootPath
root <- getCurrentDir
step "C Generation"
let entryPoint = (defaultEntryPoint root mainFile) {_entryPointNoStdlib = stdlibMode == StdlibExclude}
p :: MiniC.MiniCResult <- snd <$> runIO' iniState entryPoint upToMiniC
expected <- TIO.readFile (toFilePath expectedFile)
let execute :: Path Abs File -> IO Text
execute outputFile = pack <$> P.readProcess "wasmer" [toFilePath outputFile] (unpack stdinText)
step "Compile C with standalone runtime"
actualStandalone <- clangCompile (wasiStandaloneArgs sysrootPath) p execute step
step "Compare expected and actual program output"
assertEqDiffText ("check: WASM output = " <> toFilePath expectedFile) actualStandalone expected
step "Compile C with libc runtime"
actualLibc <- clangCompile (libcArgs sysrootPath) p execute step
step "Compare expected and actual program output"
assertEqDiffText ("check: WASM output = " <> toFilePath expectedFile) actualLibc expected
builtinRuntime :: Path Abs Dir
builtinRuntime = absDir $(makeRelativeToProject "c-runtime/builtins" >>= strToExp)
standaloneArgs :: Path Abs File -> Path Abs File -> [String]
standaloneArgs wasmOutputFile cOutputFile =
[ "-nodefaultlibs",
"-std=c99",
"-Oz",
"-I",
toFilePath (parent minicRuntime),
"-I",
toFilePath builtinRuntime,
"-Werror",
"--target=wasm32",
"-nostartfiles",
"-Wl,--no-entry",
"-o",
toFilePath wasmOutputFile,
toFilePath wallocPath,
toFilePath cOutputFile
]
where
minicRuntime :: Path Abs File
minicRuntime = absFile $(makeRelativeToProject "c-runtime/standalone/c-runtime.h" >>= strToExp)
wallocPath :: Path Abs File
wallocPath = absFile $(makeRelativeToProject "c-runtime/walloc/walloc.c" >>= strToExp)
wasiStandaloneArgs :: Path Abs Dir -> Path Abs File -> Path Abs File -> [String]
wasiStandaloneArgs sysrootPath wasmOutputFile cOutputFile =
[ "-nodefaultlibs",
"-std=c99",
"-Oz",
"-I",
toFilePath (parent minicRuntime),
"-I",
toFilePath builtinRuntime,
"-Werror",
"--target=wasm32-wasi",
"--sysroot",
toFilePath sysrootPath,
"-o",
toFilePath wasmOutputFile,
toFilePath wallocPath,
toFilePath cOutputFile
]
where
minicRuntime :: Path Abs File
minicRuntime = absFile $(makeRelativeToProject "c-runtime/wasi-standalone/c-runtime.h" >>= strToExp)
wallocPath :: Path Abs File
wallocPath = absFile $(makeRelativeToProject "c-runtime/walloc/walloc.c" >>= strToExp)
libcArgs :: Path Abs Dir -> Path Abs File -> Path Abs File -> [String]
libcArgs sysrootPath wasmOutputFile cOutputFile =
[ "-nodefaultlibs",
"-std=c99",
"-Oz",
"-I",
toFilePath (parent minicRuntime),
"-I",
toFilePath builtinRuntime,
"-Werror",
"-lc",
"--target=wasm32-wasi",
"--sysroot",
toFilePath sysrootPath,
"-o",
toFilePath wasmOutputFile,
toFilePath cOutputFile
]
where
minicRuntime :: Path Abs File
minicRuntime = absFile $(makeRelativeToProject "c-runtime/wasi-libc/c-runtime.h" >>= strToExp)
|
|
2dd189ccba851b6f7370477677e2c69a352c4594a989d1c86f74deea3e3328ac | input-output-hk/cardano-ledger | Deleg.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno - orphans #
module Cardano.Ledger.Shelley.Rules.Deleg (
ShelleyDELEG,
DelegEnv (..),
PredicateFailure,
ShelleyDelegPredFailure (..),
)
where
import Cardano.Ledger.BaseTypes (Globals (..), ShelleyBase, epochInfoPure, invalidKey)
import Cardano.Ledger.Binary (
DecCBOR (..),
EncCBOR (..),
decodeRecordSum,
encodeListLen,
)
import Cardano.Ledger.Coin (Coin (..), DeltaCoin (..), addDeltaCoin, toDeltaCoin)
import Cardano.Ledger.Core
import Cardano.Ledger.Credential (Credential)
import Cardano.Ledger.Keys (
GenDelegPair (..),
GenDelegs (..),
Hash,
KeyHash,
KeyRole (..),
VerKeyVRF,
)
import Cardano.Ledger.Shelley.Era (ShelleyDELEG)
import Cardano.Ledger.Shelley.HardForks as HardForks (allowMIRTransfer)
import Cardano.Ledger.Shelley.LedgerState (
AccountState (..),
DState (..),
FutureGenDeleg (..),
InstantaneousRewards (..),
availableAfterMIR,
delegations,
dsFutureGenDelegs,
dsGenDelegs,
dsIRewards,
rewards,
)
import Cardano.Ledger.Shelley.TxBody (
ConstitutionalDelegCert (..),
DCert (..),
DelegCert (..),
Delegation (..),
MIRCert (..),
MIRPot (..),
MIRTarget (..),
Ptr,
)
import Cardano.Ledger.Slot (
Duration (..),
EpochNo (..),
SlotNo,
epochInfoEpoch,
epochInfoFirst,
(*-),
(+*),
)
import Cardano.Ledger.UMapCompact (RDPair (..), View (..), compactCoinOrError, fromCompact)
import qualified Cardano.Ledger.UMapCompact as UM
import Control.DeepSeq
import Control.Monad.Trans.Reader (asks)
import Control.SetAlgebra (eval, range, singleton, (∉), (∪), (⨃))
import Control.State.Transition
import Data.Foldable (fold)
import Data.Group (Group (..))
import qualified Data.Map.Strict as Map
import Data.Maybe (isJust)
import qualified Data.Set as Set
import Data.Typeable (Typeable)
import Data.Word (Word8)
import GHC.Generics (Generic)
import Lens.Micro ((^.))
import NoThunks.Class (NoThunks (..))
data DelegEnv era = DelegEnv
{ slotNo :: SlotNo
, ptr_ :: Ptr
, acnt_ :: AccountState
, ppDE :: PParams era -- The protocol parameters are only used for the HardFork mechanism
}
deriving instance (Show (PParams era)) => Show (DelegEnv era)
deriving instance (Eq (PParams era)) => Eq (DelegEnv era)
data ShelleyDelegPredFailure era
= StakeKeyAlreadyRegisteredDELEG
Credential which is already registered
| -- | Indicates that the stake key is somehow already in the rewards map.
-- This error is now redundant with StakeKeyAlreadyRegisteredDELEG.
-- We should remove it and replace its one use with StakeKeyAlreadyRegisteredDELEG.
StakeKeyInRewardsDELEG
!(Credential 'Staking (EraCrypto era)) -- DEPRECATED, now redundant with StakeKeyAlreadyRegisteredDELEG
| StakeKeyNotRegisteredDELEG
Credential which is not registered
| StakeKeyNonZeroAccountBalanceDELEG
!(Maybe Coin) -- The remaining reward account balance, if it exists
| StakeDelegationImpossibleDELEG
Credential that is not registered
| WrongCertificateTypeDELEG -- The DCertPool constructor should not be used by this transition
| GenesisKeyNotInMappingDELEG
Unknown Genesis KeyHash
| DuplicateGenesisDelegateDELEG
which is already delegated to
| InsufficientForInstantaneousRewardsDELEG
which pot the rewards are to be drawn from , treasury or reserves
!Coin -- amount of rewards to be given out
!Coin -- size of the pot from which the lovelace is drawn
| MIRCertificateTooLateinEpochDELEG
!SlotNo -- current slot
!SlotNo -- EraRule "MIR" must be submitted before this slot
| DuplicateGenesisVRFDELEG
!(Hash (EraCrypto era) (VerKeyVRF (EraCrypto era))) -- VRF KeyHash which is already delegated to
| MIRTransferNotCurrentlyAllowed
| MIRNegativesNotCurrentlyAllowed
| InsufficientForTransferDELEG
which pot the rewards are to be drawn from , treasury or reserves
!Coin -- amount attempted to transfer
!Coin -- amount available
| MIRProducesNegativeUpdate
| MIRNegativeTransfer
which pot the rewards are to be drawn from , treasury or reserves
!Coin -- amount attempted to transfer
deriving (Show, Eq, Generic)
newtype ShelleyDelegEvent era = NewEpoch EpochNo
instance EraPParams era => STS (ShelleyDELEG era) where
type State (ShelleyDELEG era) = DState (EraCrypto era)
type Signal (ShelleyDELEG era) = DCert (EraCrypto era)
type Environment (ShelleyDELEG era) = DelegEnv era
type BaseM (ShelleyDELEG era) = ShelleyBase
type PredicateFailure (ShelleyDELEG era) = ShelleyDelegPredFailure era
type Event (ShelleyDELEG era) = ShelleyDelegEvent era
transitionRules = [delegationTransition]
instance NoThunks (ShelleyDelegPredFailure era)
instance NFData (ShelleyDelegPredFailure era)
instance
(Era era, Typeable (Script era)) =>
EncCBOR (ShelleyDelegPredFailure era)
where
encCBOR = \case
StakeKeyAlreadyRegisteredDELEG cred ->
encodeListLen 2 <> encCBOR (0 :: Word8) <> encCBOR cred
StakeKeyNotRegisteredDELEG cred ->
encodeListLen 2 <> encCBOR (1 :: Word8) <> encCBOR cred
StakeKeyNonZeroAccountBalanceDELEG rewardBalance ->
encodeListLen 2 <> encCBOR (2 :: Word8) <> encCBOR rewardBalance
StakeDelegationImpossibleDELEG cred ->
encodeListLen 2 <> encCBOR (3 :: Word8) <> encCBOR cred
WrongCertificateTypeDELEG ->
encodeListLen 1 <> encCBOR (4 :: Word8)
GenesisKeyNotInMappingDELEG gkh ->
encodeListLen 2 <> encCBOR (5 :: Word8) <> encCBOR gkh
DuplicateGenesisDelegateDELEG kh ->
encodeListLen 2 <> encCBOR (6 :: Word8) <> encCBOR kh
InsufficientForInstantaneousRewardsDELEG pot needed potAmount ->
encodeListLen 4
<> encCBOR (7 :: Word8)
<> encCBOR pot
<> encCBOR needed
<> encCBOR potAmount
MIRCertificateTooLateinEpochDELEG sNow sTooLate ->
encodeListLen 3 <> encCBOR (8 :: Word8) <> encCBOR sNow <> encCBOR sTooLate
DuplicateGenesisVRFDELEG vrf ->
encodeListLen 2 <> encCBOR (9 :: Word8) <> encCBOR vrf
StakeKeyInRewardsDELEG cred ->
encodeListLen 2 <> encCBOR (10 :: Word8) <> encCBOR cred
MIRTransferNotCurrentlyAllowed ->
encodeListLen 1 <> encCBOR (11 :: Word8)
MIRNegativesNotCurrentlyAllowed ->
encodeListLen 1 <> encCBOR (12 :: Word8)
InsufficientForTransferDELEG pot needed available ->
encodeListLen 4
<> encCBOR (13 :: Word8)
<> encCBOR pot
<> encCBOR needed
<> encCBOR available
MIRProducesNegativeUpdate ->
encodeListLen 1 <> encCBOR (14 :: Word8)
MIRNegativeTransfer pot amt ->
encodeListLen 3
<> encCBOR (15 :: Word8)
<> encCBOR pot
<> encCBOR amt
instance
(Era era, Typeable (Script era)) =>
DecCBOR (ShelleyDelegPredFailure era)
where
decCBOR = decodeRecordSum "PredicateFailure (DELEG era)" $
\case
0 -> do
kh <- decCBOR
pure (2, StakeKeyAlreadyRegisteredDELEG kh)
1 -> do
kh <- decCBOR
pure (2, StakeKeyNotRegisteredDELEG kh)
2 -> do
b <- decCBOR
pure (2, StakeKeyNonZeroAccountBalanceDELEG b)
3 -> do
kh <- decCBOR
pure (2, StakeDelegationImpossibleDELEG kh)
4 -> do
pure (1, WrongCertificateTypeDELEG)
5 -> do
gkh <- decCBOR
pure (2, GenesisKeyNotInMappingDELEG gkh)
6 -> do
kh <- decCBOR
pure (2, DuplicateGenesisDelegateDELEG kh)
7 -> do
pot <- decCBOR
needed <- decCBOR
potAmount <- decCBOR
pure (4, InsufficientForInstantaneousRewardsDELEG pot needed potAmount)
8 -> do
sNow <- decCBOR
sTooLate <- decCBOR
pure (3, MIRCertificateTooLateinEpochDELEG sNow sTooLate)
9 -> do
vrf <- decCBOR
pure (2, DuplicateGenesisVRFDELEG vrf)
10 -> do
kh <- decCBOR
pure (2, StakeKeyInRewardsDELEG kh)
11 -> do
pure (1, MIRTransferNotCurrentlyAllowed)
12 -> do
pure (1, MIRNegativesNotCurrentlyAllowed)
13 -> do
pot <- decCBOR
needed <- decCBOR
available <- decCBOR
pure (4, InsufficientForTransferDELEG pot needed available)
14 -> do
pure (1, MIRProducesNegativeUpdate)
15 -> do
pot <- decCBOR
amt <- decCBOR
pure (3, MIRNegativeTransfer pot amt)
k -> invalidKey k
delegationTransition :: EraPParams era => TransitionRule (ShelleyDELEG era)
delegationTransition = do
TRC (DelegEnv slot ptr acnt pp, ds, c) <- judgmentContext
let pv = pp ^. ppProtocolVersionL
case c of
DCertDeleg (RegKey hk) -> do
( hk ∉ dom ( rewards ds ) )
UM.notMember hk (rewards ds) ?! StakeKeyAlreadyRegisteredDELEG hk
let u1 = dsUnified ds
deposit = compactCoinOrError (pp ^. ppKeyDepositL)
u2 = RewardDeposits u1 UM.∪ (hk, RDPair (UM.CompactCoin 0) deposit)
u3 = Ptrs u2 UM.∪ (ptr, hk)
pure (ds {dsUnified = u3})
DCertDeleg (DeRegKey hk) -> do
-- note that pattern match is used instead of cwitness, as in the spec
-- (hk ∈ dom (rewards ds))
UM.member hk (rewards ds) ?! StakeKeyNotRegisteredDELEG hk
let rewardCoin = rdReward <$> UM.lookup hk (rewards ds)
rewardCoin == Just mempty ?! StakeKeyNonZeroAccountBalanceDELEG (fromCompact <$> rewardCoin)
let u0 = dsUnified ds
u1 = Set.singleton hk UM.⋪ RewardDeposits u0
u2 = Set.singleton hk UM.⋪ Delegations u1
u3 = Ptrs u2 UM.⋫ Set.singleton hk
u4 = ds {dsUnified = u3}
pure u4
DCertDeleg (Delegate (Delegation hk dpool)) -> do
note that pattern match is used instead of cwitness and dpool , as in the spec
-- (hk ∈ dom (rewards ds))
UM.member hk (rewards ds) ?! StakeDelegationImpossibleDELEG hk
pure (ds {dsUnified = delegations ds UM.⨃ Map.singleton hk dpool})
DCertGenesis (ConstitutionalDelegCert gkh vkh vrf) -> do
sp <- liftSTS $ asks stabilityWindow
-- note that pattern match is used instead of genesisDeleg, as in the spec
let s' = slot +* Duration sp
GenDelegs genDelegs = dsGenDelegs ds
-- gkh ∈ dom genDelegs ?! GenesisKeyNotInMappingDELEG gkh
isJust (Map.lookup gkh genDelegs) ?! GenesisKeyNotInMappingDELEG gkh
let cod =
range $
Map.filterWithKey (\g _ -> g /= gkh) genDelegs
fod =
range $
Map.filterWithKey (\(FutureGenDeleg _ g) _ -> g /= gkh) (dsFutureGenDelegs ds)
currentOtherColdKeyHashes = Set.map genDelegKeyHash cod
currentOtherVrfKeyHashes = Set.map genDelegVrfHash cod
futureOtherColdKeyHashes = Set.map genDelegKeyHash fod
futureOtherVrfKeyHashes = Set.map genDelegVrfHash fod
eval (vkh ∉ (currentOtherColdKeyHashes ∪ futureOtherColdKeyHashes))
?! DuplicateGenesisDelegateDELEG vkh
eval (vrf ∉ (currentOtherVrfKeyHashes ∪ futureOtherVrfKeyHashes))
?! DuplicateGenesisVRFDELEG vrf
pure $
ds
{ dsFutureGenDelegs =
eval (dsFutureGenDelegs ds ⨃ singleton (FutureGenDeleg s' gkh) (GenDelegPair vkh vrf))
}
DCertMir (MIRCert targetPot mirTarget) -> do
checkSlotNotTooLate slot
case mirTarget of
StakeAddressesMIR credCoinMap -> do
let (potAmount, delta, instantaneousRewards) =
case targetPot of
ReservesMIR -> (asReserves acnt, deltaReserves $ dsIRewards ds, iRReserves $ dsIRewards ds)
TreasuryMIR -> (asTreasury acnt, deltaTreasury $ dsIRewards ds, iRTreasury $ dsIRewards ds)
let credCoinMap' = Map.map (\(DeltaCoin x) -> Coin x) credCoinMap
(combinedMap, available) <-
if HardForks.allowMIRTransfer pv
then do
let cm = Map.unionWith (<>) credCoinMap' instantaneousRewards
all (>= mempty) cm ?! MIRProducesNegativeUpdate
pure (cm, potAmount `addDeltaCoin` delta)
else do
all (>= mempty) credCoinMap ?! MIRNegativesNotCurrentlyAllowed
pure (Map.union credCoinMap' instantaneousRewards, potAmount)
updateReservesAndTreasury targetPot combinedMap available ds
SendToOppositePotMIR coin ->
if HardForks.allowMIRTransfer pv
then do
let available = availableAfterMIR targetPot acnt (dsIRewards ds)
coin >= mempty ?! MIRNegativeTransfer targetPot coin
coin <= available ?! InsufficientForTransferDELEG targetPot coin available
let ir = dsIRewards ds
dr = deltaReserves ir
dt = deltaTreasury ir
case targetPot of
ReservesMIR ->
pure $
ds
{ dsIRewards =
ir
{ deltaReserves = dr <> invert (toDeltaCoin coin)
, deltaTreasury = dt <> toDeltaCoin coin
}
}
TreasuryMIR ->
pure $
ds
{ dsIRewards =
ir
{ deltaReserves = dr <> toDeltaCoin coin
, deltaTreasury = dt <> invert (toDeltaCoin coin)
}
}
else do
failBecause MIRTransferNotCurrentlyAllowed
pure ds
DCertPool _ -> do
failBecause WrongCertificateTypeDELEG -- this always fails
pure ds
checkSlotNotTooLate ::
EraPParams era =>
SlotNo ->
Rule (ShelleyDELEG era) 'Transition ()
checkSlotNotTooLate slot = do
sp <- liftSTS $ asks stabilityWindow
ei <- liftSTS $ asks epochInfoPure
EpochNo currEpoch <- liftSTS $ epochInfoEpoch ei slot
let newEpoch = EpochNo (currEpoch + 1)
tellEvent (NewEpoch newEpoch)
firstSlot <- liftSTS $ epochInfoFirst ei newEpoch
let tooLate = firstSlot *- Duration sp
slot < tooLate ?! MIRCertificateTooLateinEpochDELEG slot tooLate
updateReservesAndTreasury ::
MIRPot ->
Map.Map (Credential 'Staking (EraCrypto era)) Coin ->
Coin ->
DState (EraCrypto era) ->
Rule (ShelleyDELEG era) 'Transition (DState (EraCrypto era))
updateReservesAndTreasury targetPot combinedMap available ds = do
let requiredForRewards = fold combinedMap
requiredForRewards
<= available
?! InsufficientForInstantaneousRewardsDELEG targetPot requiredForRewards available
pure $
case targetPot of
ReservesMIR -> ds {dsIRewards = (dsIRewards ds) {iRReserves = combinedMap}}
TreasuryMIR -> ds {dsIRewards = (dsIRewards ds) {iRTreasury = combinedMap}}
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/b9aa1ad1728c0ceeca62657ec94d6d099896c052/eras/shelley/impl/src/Cardano/Ledger/Shelley/Rules/Deleg.hs | haskell | # LANGUAGE OverloadedStrings #
The protocol parameters are only used for the HardFork mechanism
| Indicates that the stake key is somehow already in the rewards map.
This error is now redundant with StakeKeyAlreadyRegisteredDELEG.
We should remove it and replace its one use with StakeKeyAlreadyRegisteredDELEG.
DEPRECATED, now redundant with StakeKeyAlreadyRegisteredDELEG
The remaining reward account balance, if it exists
The DCertPool constructor should not be used by this transition
amount of rewards to be given out
size of the pot from which the lovelace is drawn
current slot
EraRule "MIR" must be submitted before this slot
VRF KeyHash which is already delegated to
amount attempted to transfer
amount available
amount attempted to transfer
note that pattern match is used instead of cwitness, as in the spec
(hk ∈ dom (rewards ds))
(hk ∈ dom (rewards ds))
note that pattern match is used instead of genesisDeleg, as in the spec
gkh ∈ dom genDelegs ?! GenesisKeyNotInMappingDELEG gkh
this always fails | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno - orphans #
module Cardano.Ledger.Shelley.Rules.Deleg (
ShelleyDELEG,
DelegEnv (..),
PredicateFailure,
ShelleyDelegPredFailure (..),
)
where
import Cardano.Ledger.BaseTypes (Globals (..), ShelleyBase, epochInfoPure, invalidKey)
import Cardano.Ledger.Binary (
DecCBOR (..),
EncCBOR (..),
decodeRecordSum,
encodeListLen,
)
import Cardano.Ledger.Coin (Coin (..), DeltaCoin (..), addDeltaCoin, toDeltaCoin)
import Cardano.Ledger.Core
import Cardano.Ledger.Credential (Credential)
import Cardano.Ledger.Keys (
GenDelegPair (..),
GenDelegs (..),
Hash,
KeyHash,
KeyRole (..),
VerKeyVRF,
)
import Cardano.Ledger.Shelley.Era (ShelleyDELEG)
import Cardano.Ledger.Shelley.HardForks as HardForks (allowMIRTransfer)
import Cardano.Ledger.Shelley.LedgerState (
AccountState (..),
DState (..),
FutureGenDeleg (..),
InstantaneousRewards (..),
availableAfterMIR,
delegations,
dsFutureGenDelegs,
dsGenDelegs,
dsIRewards,
rewards,
)
import Cardano.Ledger.Shelley.TxBody (
ConstitutionalDelegCert (..),
DCert (..),
DelegCert (..),
Delegation (..),
MIRCert (..),
MIRPot (..),
MIRTarget (..),
Ptr,
)
import Cardano.Ledger.Slot (
Duration (..),
EpochNo (..),
SlotNo,
epochInfoEpoch,
epochInfoFirst,
(*-),
(+*),
)
import Cardano.Ledger.UMapCompact (RDPair (..), View (..), compactCoinOrError, fromCompact)
import qualified Cardano.Ledger.UMapCompact as UM
import Control.DeepSeq
import Control.Monad.Trans.Reader (asks)
import Control.SetAlgebra (eval, range, singleton, (∉), (∪), (⨃))
import Control.State.Transition
import Data.Foldable (fold)
import Data.Group (Group (..))
import qualified Data.Map.Strict as Map
import Data.Maybe (isJust)
import qualified Data.Set as Set
import Data.Typeable (Typeable)
import Data.Word (Word8)
import GHC.Generics (Generic)
import Lens.Micro ((^.))
import NoThunks.Class (NoThunks (..))
data DelegEnv era = DelegEnv
{ slotNo :: SlotNo
, ptr_ :: Ptr
, acnt_ :: AccountState
}
deriving instance (Show (PParams era)) => Show (DelegEnv era)
deriving instance (Eq (PParams era)) => Eq (DelegEnv era)
data ShelleyDelegPredFailure era
= StakeKeyAlreadyRegisteredDELEG
Credential which is already registered
StakeKeyInRewardsDELEG
| StakeKeyNotRegisteredDELEG
Credential which is not registered
| StakeKeyNonZeroAccountBalanceDELEG
| StakeDelegationImpossibleDELEG
Credential that is not registered
| GenesisKeyNotInMappingDELEG
Unknown Genesis KeyHash
| DuplicateGenesisDelegateDELEG
which is already delegated to
| InsufficientForInstantaneousRewardsDELEG
which pot the rewards are to be drawn from , treasury or reserves
| MIRCertificateTooLateinEpochDELEG
| DuplicateGenesisVRFDELEG
| MIRTransferNotCurrentlyAllowed
| MIRNegativesNotCurrentlyAllowed
| InsufficientForTransferDELEG
which pot the rewards are to be drawn from , treasury or reserves
| MIRProducesNegativeUpdate
| MIRNegativeTransfer
which pot the rewards are to be drawn from , treasury or reserves
deriving (Show, Eq, Generic)
newtype ShelleyDelegEvent era = NewEpoch EpochNo
instance EraPParams era => STS (ShelleyDELEG era) where
type State (ShelleyDELEG era) = DState (EraCrypto era)
type Signal (ShelleyDELEG era) = DCert (EraCrypto era)
type Environment (ShelleyDELEG era) = DelegEnv era
type BaseM (ShelleyDELEG era) = ShelleyBase
type PredicateFailure (ShelleyDELEG era) = ShelleyDelegPredFailure era
type Event (ShelleyDELEG era) = ShelleyDelegEvent era
transitionRules = [delegationTransition]
instance NoThunks (ShelleyDelegPredFailure era)
instance NFData (ShelleyDelegPredFailure era)
instance
(Era era, Typeable (Script era)) =>
EncCBOR (ShelleyDelegPredFailure era)
where
encCBOR = \case
StakeKeyAlreadyRegisteredDELEG cred ->
encodeListLen 2 <> encCBOR (0 :: Word8) <> encCBOR cred
StakeKeyNotRegisteredDELEG cred ->
encodeListLen 2 <> encCBOR (1 :: Word8) <> encCBOR cred
StakeKeyNonZeroAccountBalanceDELEG rewardBalance ->
encodeListLen 2 <> encCBOR (2 :: Word8) <> encCBOR rewardBalance
StakeDelegationImpossibleDELEG cred ->
encodeListLen 2 <> encCBOR (3 :: Word8) <> encCBOR cred
WrongCertificateTypeDELEG ->
encodeListLen 1 <> encCBOR (4 :: Word8)
GenesisKeyNotInMappingDELEG gkh ->
encodeListLen 2 <> encCBOR (5 :: Word8) <> encCBOR gkh
DuplicateGenesisDelegateDELEG kh ->
encodeListLen 2 <> encCBOR (6 :: Word8) <> encCBOR kh
InsufficientForInstantaneousRewardsDELEG pot needed potAmount ->
encodeListLen 4
<> encCBOR (7 :: Word8)
<> encCBOR pot
<> encCBOR needed
<> encCBOR potAmount
MIRCertificateTooLateinEpochDELEG sNow sTooLate ->
encodeListLen 3 <> encCBOR (8 :: Word8) <> encCBOR sNow <> encCBOR sTooLate
DuplicateGenesisVRFDELEG vrf ->
encodeListLen 2 <> encCBOR (9 :: Word8) <> encCBOR vrf
StakeKeyInRewardsDELEG cred ->
encodeListLen 2 <> encCBOR (10 :: Word8) <> encCBOR cred
MIRTransferNotCurrentlyAllowed ->
encodeListLen 1 <> encCBOR (11 :: Word8)
MIRNegativesNotCurrentlyAllowed ->
encodeListLen 1 <> encCBOR (12 :: Word8)
InsufficientForTransferDELEG pot needed available ->
encodeListLen 4
<> encCBOR (13 :: Word8)
<> encCBOR pot
<> encCBOR needed
<> encCBOR available
MIRProducesNegativeUpdate ->
encodeListLen 1 <> encCBOR (14 :: Word8)
MIRNegativeTransfer pot amt ->
encodeListLen 3
<> encCBOR (15 :: Word8)
<> encCBOR pot
<> encCBOR amt
instance
(Era era, Typeable (Script era)) =>
DecCBOR (ShelleyDelegPredFailure era)
where
decCBOR = decodeRecordSum "PredicateFailure (DELEG era)" $
\case
0 -> do
kh <- decCBOR
pure (2, StakeKeyAlreadyRegisteredDELEG kh)
1 -> do
kh <- decCBOR
pure (2, StakeKeyNotRegisteredDELEG kh)
2 -> do
b <- decCBOR
pure (2, StakeKeyNonZeroAccountBalanceDELEG b)
3 -> do
kh <- decCBOR
pure (2, StakeDelegationImpossibleDELEG kh)
4 -> do
pure (1, WrongCertificateTypeDELEG)
5 -> do
gkh <- decCBOR
pure (2, GenesisKeyNotInMappingDELEG gkh)
6 -> do
kh <- decCBOR
pure (2, DuplicateGenesisDelegateDELEG kh)
7 -> do
pot <- decCBOR
needed <- decCBOR
potAmount <- decCBOR
pure (4, InsufficientForInstantaneousRewardsDELEG pot needed potAmount)
8 -> do
sNow <- decCBOR
sTooLate <- decCBOR
pure (3, MIRCertificateTooLateinEpochDELEG sNow sTooLate)
9 -> do
vrf <- decCBOR
pure (2, DuplicateGenesisVRFDELEG vrf)
10 -> do
kh <- decCBOR
pure (2, StakeKeyInRewardsDELEG kh)
11 -> do
pure (1, MIRTransferNotCurrentlyAllowed)
12 -> do
pure (1, MIRNegativesNotCurrentlyAllowed)
13 -> do
pot <- decCBOR
needed <- decCBOR
available <- decCBOR
pure (4, InsufficientForTransferDELEG pot needed available)
14 -> do
pure (1, MIRProducesNegativeUpdate)
15 -> do
pot <- decCBOR
amt <- decCBOR
pure (3, MIRNegativeTransfer pot amt)
k -> invalidKey k
delegationTransition :: EraPParams era => TransitionRule (ShelleyDELEG era)
delegationTransition = do
TRC (DelegEnv slot ptr acnt pp, ds, c) <- judgmentContext
let pv = pp ^. ppProtocolVersionL
case c of
DCertDeleg (RegKey hk) -> do
( hk ∉ dom ( rewards ds ) )
UM.notMember hk (rewards ds) ?! StakeKeyAlreadyRegisteredDELEG hk
let u1 = dsUnified ds
deposit = compactCoinOrError (pp ^. ppKeyDepositL)
u2 = RewardDeposits u1 UM.∪ (hk, RDPair (UM.CompactCoin 0) deposit)
u3 = Ptrs u2 UM.∪ (ptr, hk)
pure (ds {dsUnified = u3})
DCertDeleg (DeRegKey hk) -> do
UM.member hk (rewards ds) ?! StakeKeyNotRegisteredDELEG hk
let rewardCoin = rdReward <$> UM.lookup hk (rewards ds)
rewardCoin == Just mempty ?! StakeKeyNonZeroAccountBalanceDELEG (fromCompact <$> rewardCoin)
let u0 = dsUnified ds
u1 = Set.singleton hk UM.⋪ RewardDeposits u0
u2 = Set.singleton hk UM.⋪ Delegations u1
u3 = Ptrs u2 UM.⋫ Set.singleton hk
u4 = ds {dsUnified = u3}
pure u4
DCertDeleg (Delegate (Delegation hk dpool)) -> do
note that pattern match is used instead of cwitness and dpool , as in the spec
UM.member hk (rewards ds) ?! StakeDelegationImpossibleDELEG hk
pure (ds {dsUnified = delegations ds UM.⨃ Map.singleton hk dpool})
DCertGenesis (ConstitutionalDelegCert gkh vkh vrf) -> do
sp <- liftSTS $ asks stabilityWindow
let s' = slot +* Duration sp
GenDelegs genDelegs = dsGenDelegs ds
isJust (Map.lookup gkh genDelegs) ?! GenesisKeyNotInMappingDELEG gkh
let cod =
range $
Map.filterWithKey (\g _ -> g /= gkh) genDelegs
fod =
range $
Map.filterWithKey (\(FutureGenDeleg _ g) _ -> g /= gkh) (dsFutureGenDelegs ds)
currentOtherColdKeyHashes = Set.map genDelegKeyHash cod
currentOtherVrfKeyHashes = Set.map genDelegVrfHash cod
futureOtherColdKeyHashes = Set.map genDelegKeyHash fod
futureOtherVrfKeyHashes = Set.map genDelegVrfHash fod
eval (vkh ∉ (currentOtherColdKeyHashes ∪ futureOtherColdKeyHashes))
?! DuplicateGenesisDelegateDELEG vkh
eval (vrf ∉ (currentOtherVrfKeyHashes ∪ futureOtherVrfKeyHashes))
?! DuplicateGenesisVRFDELEG vrf
pure $
ds
{ dsFutureGenDelegs =
eval (dsFutureGenDelegs ds ⨃ singleton (FutureGenDeleg s' gkh) (GenDelegPair vkh vrf))
}
DCertMir (MIRCert targetPot mirTarget) -> do
checkSlotNotTooLate slot
case mirTarget of
StakeAddressesMIR credCoinMap -> do
let (potAmount, delta, instantaneousRewards) =
case targetPot of
ReservesMIR -> (asReserves acnt, deltaReserves $ dsIRewards ds, iRReserves $ dsIRewards ds)
TreasuryMIR -> (asTreasury acnt, deltaTreasury $ dsIRewards ds, iRTreasury $ dsIRewards ds)
let credCoinMap' = Map.map (\(DeltaCoin x) -> Coin x) credCoinMap
(combinedMap, available) <-
if HardForks.allowMIRTransfer pv
then do
let cm = Map.unionWith (<>) credCoinMap' instantaneousRewards
all (>= mempty) cm ?! MIRProducesNegativeUpdate
pure (cm, potAmount `addDeltaCoin` delta)
else do
all (>= mempty) credCoinMap ?! MIRNegativesNotCurrentlyAllowed
pure (Map.union credCoinMap' instantaneousRewards, potAmount)
updateReservesAndTreasury targetPot combinedMap available ds
SendToOppositePotMIR coin ->
if HardForks.allowMIRTransfer pv
then do
let available = availableAfterMIR targetPot acnt (dsIRewards ds)
coin >= mempty ?! MIRNegativeTransfer targetPot coin
coin <= available ?! InsufficientForTransferDELEG targetPot coin available
let ir = dsIRewards ds
dr = deltaReserves ir
dt = deltaTreasury ir
case targetPot of
ReservesMIR ->
pure $
ds
{ dsIRewards =
ir
{ deltaReserves = dr <> invert (toDeltaCoin coin)
, deltaTreasury = dt <> toDeltaCoin coin
}
}
TreasuryMIR ->
pure $
ds
{ dsIRewards =
ir
{ deltaReserves = dr <> toDeltaCoin coin
, deltaTreasury = dt <> invert (toDeltaCoin coin)
}
}
else do
failBecause MIRTransferNotCurrentlyAllowed
pure ds
DCertPool _ -> do
pure ds
checkSlotNotTooLate ::
EraPParams era =>
SlotNo ->
Rule (ShelleyDELEG era) 'Transition ()
checkSlotNotTooLate slot = do
sp <- liftSTS $ asks stabilityWindow
ei <- liftSTS $ asks epochInfoPure
EpochNo currEpoch <- liftSTS $ epochInfoEpoch ei slot
let newEpoch = EpochNo (currEpoch + 1)
tellEvent (NewEpoch newEpoch)
firstSlot <- liftSTS $ epochInfoFirst ei newEpoch
let tooLate = firstSlot *- Duration sp
slot < tooLate ?! MIRCertificateTooLateinEpochDELEG slot tooLate
updateReservesAndTreasury ::
MIRPot ->
Map.Map (Credential 'Staking (EraCrypto era)) Coin ->
Coin ->
DState (EraCrypto era) ->
Rule (ShelleyDELEG era) 'Transition (DState (EraCrypto era))
updateReservesAndTreasury targetPot combinedMap available ds = do
let requiredForRewards = fold combinedMap
requiredForRewards
<= available
?! InsufficientForInstantaneousRewardsDELEG targetPot requiredForRewards available
pure $
case targetPot of
ReservesMIR -> ds {dsIRewards = (dsIRewards ds) {iRReserves = combinedMap}}
TreasuryMIR -> ds {dsIRewards = (dsIRewards ds) {iRTreasury = combinedMap}}
|
bb4df1968c49389a2d0e7e0c80449f375141bbd6bf314f100d0ab88bf9648459 | codereport/plr | data.cljs | (ns plr.data)
(def sites [:so :octo :rm :languish :pypl :ieee :tiobe])
(def names {:so "StackOverflow" :octo "Octoverse" :rm "RedMonk" :languish "Languish"
:pypl "PYPL" :ieee "IEEE Spectrum" :tiobe "TIOBE"})
(def links {:octo "-programming-languages"
:ieee "-programming-languages-2022"
:rm "-rankings-6-22/"
:languish "/"
:so "/#most-popular-technologies-language"
:pypl ""
:tiobe "-index/"})
(def octoverse ["JavaScript" "Python" "Java" "TypeScript" "C#" "C++" "PHP" "Shell" "C" "Ruby"])
(def ieee ["Python" "C" "C++" "C#" "Java" "SQL" "JavaScript" "R" "HTML" "TypeScript" "Go" "PHP" "Shell" "Ruby" "Scala" "MATLAB" "SAS" "Assembly" "Kotlin" "Rust" "Perl" "Objective-C" "Dart" "Swift" "Verilog" "Arduino" "D" "Julia" "CUDA" "VHDL" "Visual Basic" "LabView" "Groovy" "Lua" "Ada" "Scheme" "ABAP" "Haskell" "COBOL" "Elixir" "F#" "Lisp" "Delphi" "Fortran" "TCL" "Clojure" "Prolog" "OCaml" "Ladder Logic" "Erlang" "J" "Forth" "Elm" "Raku" "WebAssembly" "CoffeScript" "Eiffel"])
(def redmonk ["JavaScript" "Python" "Java" "PHP" "C#" "CSS" "C++" "TypeScript" "Ruby" "C" "Swift" "R" "Objective-C" "Shell" "Scala" "Go" "PowerShell" "Kotlin" "Rust" "Dart"])
(def languish ["Python" "JavaScript" "TypeScript" "Java" "C++" "C#" "Go" "HTML" "Markdown" "C" "PHP" "Rust" "CSS" "Shell" "Kotlin" "Jupyter Notebook" "R" "Dart" "Swift" "Vue" "SQL" "Ruby" "JSON" "Lua" "Dockerfile" "PowerShell"])
(def stack-overflow ["JavaScript" "HTML" "SQL" "Python" "TypeScript" "Java" "Shell" "C#" "C++" "PHP" "C" "PowerShell" "Go" "Rust" "Kotlin" "Dart" "Ruby" "Assembly" "Swift" "R" "VBA" "MATLAB" "Lua" "Groovy" "Delphi" "Scala" "Objective-C" "Perl" "Haskell" "Elixir" "Julia" "Clojure" "Solidity" "Lisp" "F#" "Fortran" "Erlang" "APL" "COBOL" "SAS" "OCaml" "Crystal"])
(def pypl ["Python" "Java" "JavaScript" "C#" "C++" "PHP" "R" "TypeScript" "Swift" "Objective-C" "Go" "Rust" "Kotlin" "MATLAB" "Ruby" "VBA" "Ada" "Dart" "Scala" "Visual Basic" "Lua" "ABAP" "Haskell" "Julia" "Groovy" "COBOL" "Perl" "Delphi"])
(def tiobe ["Python" "C" "C++" "Java" "C#" "Visual Basic" "JavaScript" "SQL" "Assembly" "PHP" "Swift" "Go" "R" "Classic Visual Basic" "MATLAB" "Ruby" "Delphi" "Rust" "Perl" "Scratch" "FoxPro" "SAS" "Objective-C" "Lua" "Kotlin" "Ada" "Fortran" "Lisp" "Julia" "Transact-SQL" "COBOL" "Scala" "F#" "Logo" "TypeScript" "Groovy" "Shell" "Dart" "RPG" "PL/SQL" "PowerShell" "Awk" "Prolog" "CFML" "Haskell" "D" "LabView" "Scheme" "ABAP" "OCaml"])
StackOverflow
[] ; Octoverse
Redmonk
[[29 "VBA"]
[30 "Scala"]
[32 "Objective-C"]
[36 "Solidity"]
[39 "Assembly"]
[44 "Julia"]
[51 "MATLAB"]
[54 "Groovy"]
[66 "CUDA"]
[67 "Delphi"]
[72 "Arduino"]
[75 "Verilog"]
[112 "Crystal"]
[115 "VHDL"]
[138 "D"]
[145 "ABAP"]
[166 "Ada"]
[185 "LabView"]
[212 "COBOL"]
[249 "APL"]
[261 "Visual Basic"]
[301 "J"]]
PYPL
IEEE Spectrum
TIOBE
])
(def odd ["Markdown" "CSS" "HTML" "SAS" "Jupyter Notebook" "Vue" "JSON" "Dockerfile" "SQL"])
| null | https://raw.githubusercontent.com/codereport/plr/4496371fd5dab64686fd9fa2c0f0697e75b47e50/src/plr/data.cljs | clojure | Octoverse | (ns plr.data)
(def sites [:so :octo :rm :languish :pypl :ieee :tiobe])
(def names {:so "StackOverflow" :octo "Octoverse" :rm "RedMonk" :languish "Languish"
:pypl "PYPL" :ieee "IEEE Spectrum" :tiobe "TIOBE"})
(def links {:octo "-programming-languages"
:ieee "-programming-languages-2022"
:rm "-rankings-6-22/"
:languish "/"
:so "/#most-popular-technologies-language"
:pypl ""
:tiobe "-index/"})
(def octoverse ["JavaScript" "Python" "Java" "TypeScript" "C#" "C++" "PHP" "Shell" "C" "Ruby"])
(def ieee ["Python" "C" "C++" "C#" "Java" "SQL" "JavaScript" "R" "HTML" "TypeScript" "Go" "PHP" "Shell" "Ruby" "Scala" "MATLAB" "SAS" "Assembly" "Kotlin" "Rust" "Perl" "Objective-C" "Dart" "Swift" "Verilog" "Arduino" "D" "Julia" "CUDA" "VHDL" "Visual Basic" "LabView" "Groovy" "Lua" "Ada" "Scheme" "ABAP" "Haskell" "COBOL" "Elixir" "F#" "Lisp" "Delphi" "Fortran" "TCL" "Clojure" "Prolog" "OCaml" "Ladder Logic" "Erlang" "J" "Forth" "Elm" "Raku" "WebAssembly" "CoffeScript" "Eiffel"])
(def redmonk ["JavaScript" "Python" "Java" "PHP" "C#" "CSS" "C++" "TypeScript" "Ruby" "C" "Swift" "R" "Objective-C" "Shell" "Scala" "Go" "PowerShell" "Kotlin" "Rust" "Dart"])
(def languish ["Python" "JavaScript" "TypeScript" "Java" "C++" "C#" "Go" "HTML" "Markdown" "C" "PHP" "Rust" "CSS" "Shell" "Kotlin" "Jupyter Notebook" "R" "Dart" "Swift" "Vue" "SQL" "Ruby" "JSON" "Lua" "Dockerfile" "PowerShell"])
(def stack-overflow ["JavaScript" "HTML" "SQL" "Python" "TypeScript" "Java" "Shell" "C#" "C++" "PHP" "C" "PowerShell" "Go" "Rust" "Kotlin" "Dart" "Ruby" "Assembly" "Swift" "R" "VBA" "MATLAB" "Lua" "Groovy" "Delphi" "Scala" "Objective-C" "Perl" "Haskell" "Elixir" "Julia" "Clojure" "Solidity" "Lisp" "F#" "Fortran" "Erlang" "APL" "COBOL" "SAS" "OCaml" "Crystal"])
(def pypl ["Python" "Java" "JavaScript" "C#" "C++" "PHP" "R" "TypeScript" "Swift" "Objective-C" "Go" "Rust" "Kotlin" "MATLAB" "Ruby" "VBA" "Ada" "Dart" "Scala" "Visual Basic" "Lua" "ABAP" "Haskell" "Julia" "Groovy" "COBOL" "Perl" "Delphi"])
(def tiobe ["Python" "C" "C++" "Java" "C#" "Visual Basic" "JavaScript" "SQL" "Assembly" "PHP" "Swift" "Go" "R" "Classic Visual Basic" "MATLAB" "Ruby" "Delphi" "Rust" "Perl" "Scratch" "FoxPro" "SAS" "Objective-C" "Lua" "Kotlin" "Ada" "Fortran" "Lisp" "Julia" "Transact-SQL" "COBOL" "Scala" "F#" "Logo" "TypeScript" "Groovy" "Shell" "Dart" "RPG" "PL/SQL" "PowerShell" "Awk" "Prolog" "CFML" "Haskell" "D" "LabView" "Scheme" "ABAP" "OCaml"])
StackOverflow
Redmonk
[[29 "VBA"]
[30 "Scala"]
[32 "Objective-C"]
[36 "Solidity"]
[39 "Assembly"]
[44 "Julia"]
[51 "MATLAB"]
[54 "Groovy"]
[66 "CUDA"]
[67 "Delphi"]
[72 "Arduino"]
[75 "Verilog"]
[112 "Crystal"]
[115 "VHDL"]
[138 "D"]
[145 "ABAP"]
[166 "Ada"]
[185 "LabView"]
[212 "COBOL"]
[249 "APL"]
[261 "Visual Basic"]
[301 "J"]]
PYPL
IEEE Spectrum
TIOBE
])
(def odd ["Markdown" "CSS" "HTML" "SAS" "Jupyter Notebook" "Vue" "JSON" "Dockerfile" "SQL"])
|
c85be936f98014d0825a7604a55892557aeeadac87a5a8cb3e01b5f2d688c9f7 | haskell/haskell-language-server | GoldenNote.expected.hs | note :: e -> Maybe a -> Either e a
note e Nothing = Left e
note _ (Just a) = Right a
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/GoldenNote.expected.hs | haskell | note :: e -> Maybe a -> Either e a
note e Nothing = Left e
note _ (Just a) = Right a
|
|
52db4ff78059f14e937fda355dcc06f21e10eed774ddd6d2829fab6c3225903f | vikram/lisplibraries | parser.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
parser.lisp : Code for writing parsers based on
Copyright ( C ) 2004 < >
;;;;
;;;; This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details .
;;;;
You should have received a copy of the GNU Library General Public
;;;; License along with this library; if not, write to the
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 , USA .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :xmls-tools)
(defun make-xml-parser (&optional (default-handler #'ignore-element))
(cons (make-hash-table :test #'equal)
default-handler))
(defun ignore-element (tree &rest args)
(declare (ignore tree args))
nil)
(defmacro def-element-handler (element-name
(xml-tree-name &rest args)
(xml-parser)
&body handler-code)
`(setf (gethash ,element-name (car ,xml-parser))
(let ((xml-parser ,xml-parser))
(declare (ignorable xml-parser))
(lambda (,xml-tree-name ,@args state)
(declare (ignorable ,xml-tree-name state ,@args))
,@handler-code))))
(defmacro with-state ((state-key state-value) &body body)
`(let ((state (acons ,state-key ,state-value state)))
,@body))
(defmacro with-parser (xml-parser &body body)
`(let ((state nil)
(xml-parser ,xml-parser))
,@body))
(defmacro process-xml (tree &rest args)
`(if (null ,tree)
nil
(funcall (gethash (node-name ,tree) (car xml-parser)
(cdr xml-parser))
,tree ,@args state)))
(defun %compress-whitespace (string)
(let ((out-stream (make-string-output-stream))
(in-whitespace-p nil))
(do ((i 0 (1+ i)))
((>= i (length string))
(get-output-stream-string out-stream))
(let ((c (char string i)))
(cond
((member c xmls::*whitespace*)
(unless in-whitespace-p
(princ #\space out-stream)
(setf in-whitespace-p t)))
(t
(princ c out-stream)
(when in-whitespace-p
(setf in-whitespace-p nil))))))))
(defmacro compress-whitespace (string)
`(if (cdr (assoc :compress-whitespace state))
(%compress-whitespace ,string)
,string))
(defmacro with-indent (stream &body body)
`(let* ((old-stream ,stream)
(,stream (make-string-output-stream)))
,@body
;; print line by line with single-space indents on front
(princ #\space old-stream)
(do ((string (get-output-stream-string ,stream))
(i 0 (1+ i)))
((>= i (length string)))
(let ((c (char string i)))
(princ c old-stream)
(when (and (char= c #\newline)
(< i (1- (length string))))
(princ #\space old-stream))))))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/xmls-tools/parser.lisp | lisp |
This library is free software; you can redistribute it and/or
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
License along with this library; if not, write to the
print line by line with single-space indents on front | parser.lisp : Code for writing parsers based on
Copyright ( C ) 2004 < >
modify it under the terms of the GNU Library General Public
version 2 of the License , or ( at your option ) any later version .
Library General Public License for more details .
You should have received a copy of the GNU Library General Public
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 , USA .
(in-package :xmls-tools)
(defun make-xml-parser (&optional (default-handler #'ignore-element))
(cons (make-hash-table :test #'equal)
default-handler))
(defun ignore-element (tree &rest args)
(declare (ignore tree args))
nil)
(defmacro def-element-handler (element-name
(xml-tree-name &rest args)
(xml-parser)
&body handler-code)
`(setf (gethash ,element-name (car ,xml-parser))
(let ((xml-parser ,xml-parser))
(declare (ignorable xml-parser))
(lambda (,xml-tree-name ,@args state)
(declare (ignorable ,xml-tree-name state ,@args))
,@handler-code))))
(defmacro with-state ((state-key state-value) &body body)
`(let ((state (acons ,state-key ,state-value state)))
,@body))
(defmacro with-parser (xml-parser &body body)
`(let ((state nil)
(xml-parser ,xml-parser))
,@body))
(defmacro process-xml (tree &rest args)
`(if (null ,tree)
nil
(funcall (gethash (node-name ,tree) (car xml-parser)
(cdr xml-parser))
,tree ,@args state)))
(defun %compress-whitespace (string)
(let ((out-stream (make-string-output-stream))
(in-whitespace-p nil))
(do ((i 0 (1+ i)))
((>= i (length string))
(get-output-stream-string out-stream))
(let ((c (char string i)))
(cond
((member c xmls::*whitespace*)
(unless in-whitespace-p
(princ #\space out-stream)
(setf in-whitespace-p t)))
(t
(princ c out-stream)
(when in-whitespace-p
(setf in-whitespace-p nil))))))))
(defmacro compress-whitespace (string)
`(if (cdr (assoc :compress-whitespace state))
(%compress-whitespace ,string)
,string))
(defmacro with-indent (stream &body body)
`(let* ((old-stream ,stream)
(,stream (make-string-output-stream)))
,@body
(princ #\space old-stream)
(do ((string (get-output-stream-string ,stream))
(i 0 (1+ i)))
((>= i (length string)))
(let ((c (char string i)))
(princ c old-stream)
(when (and (char= c #\newline)
(< i (1- (length string))))
(princ #\space old-stream))))))
|
10e57d7fefd37b1e32c1800514ebc0f5e29e0245ff46e8d22858a3fd43565e19 | transient-haskell/transient-stack | TLS.hs | -----------------------------------------------------------------------------
--
-- Module : Transient.MoveTLS
-- Copyright :
-- License : GPL-3
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- | see <-haskell-processes-between-nodes-transient-effects-iv>
-----------------------------------------------------------------------------
# LANGUAGE CPP , OverloadedStrings , BangPatterns , ScopedTypeVariables #
module Transient.TLS(initTLS, initTLS') where
#ifndef ghcjs_HOST_OS
import Transient.Internals
import Transient.Move.Internals
import Transient.Backtrack
import Transient.Parse
import Network.Socket as NSS
import Network.Socket.ByteString as NS
import Network.TLS as TLS
import Network.TLS.Extra as TLSExtra
import qualified Crypto.Random.AESCtr as AESCtr
import qualified Network.Socket.ByteString.Lazy as SBSL
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString as BE
import qualified Data.X509.CertificateStore as C
import Data.Default
import Control.Applicative
import Control.Exception as E hiding (onException)
import Control.Monad.State
import Data.IORef
import Unsafe.Coerce
import System.IO.Unsafe
import System.Directory
import System.X509 (getSystemCertificateStore) --to avoid checking certificate. delete
import Debug.Trace
-- | init TLS with the files "cert.pem" and "key.pem"
initTLS :: MonadIO m => m ()
initTLS = initTLS' "cert.pem" "key.pem"
-- | init TLS using certificate.pem and a key.pem files
initTLS' :: MonadIO m => FilePath -> FilePath -> m ()
initTLS' certpath keypath = liftIO $ writeIORef
tlsHooks
( True
, unsafeCoerce $ (TLS.sendData :: TLS.Context -> BL8.ByteString -> IO ())
, unsafeCoerce $ (TLS.recvData :: TLS.Context -> IO BE.ByteString)
, unsafeCoerce $ Transient.TLS.maybeTLSServerHandshake certpath keypath
, unsafeCoerce $ Transient.TLS.maybeClientTLSHandshake
, unsafeCoerce $ (Transient.TLS.tlsClose :: TLS.Context -> IO ())
)
tlsClose ctx= bye ctx >> contextClose ctx
maybeTLSServerHandshake
:: FilePath -> FilePath -> Socket -> BL8.ByteString -> TransIO ()
maybeTLSServerHandshake certpath keypath sock input= do
c <- liftIO $ doesFileExist "cert.pem"
k <- liftIO $ doesFileExist "key.pem"
when (not c || not k) $ error "cert.pem and key.pem must exist withing the current directory"
if ((not $ BL.null input) && BL.head input == 0x16)
then do
mctx <- liftIO $( do
ctx <- makeServerContext (ssettings certpath keypath) sock input
TLS.handshake ctx
return $Just ctx )
`catch` \(e:: SomeException) -> do
putStr "maybeTLSServerHandshake: "
print e
return Nothing -- !> "after handshake"
case mctx of
Nothing -> return ()
Just ctx -> do
tr "TLS CONNECTION"
modifyState $ \(Just c ) - > Just c{connData= Just $ TLSNode2Node $ unsafeCoerce ctx }
conn <- getSData <|> error "TLS: no socket connection"
liftIO $ writeIORef (connData conn) $ Just $ TLSNode2Node $ unsafeCoerce ctx
modify $ \s -> s{ parseContext=ParseContext (TLS.recvData ctx >>= return . SMore . BL8.fromStrict)
"" (unsafePerformIO $ newIORef False)}
onException $ \(e:: SomeException) -> liftIO $ TLS.contextClose ctx
else return ()
ssettings :: FilePath -> FilePath -> ServerParams
ssettings certpath keypath = unsafePerformIO $ do
cred <- either error id <$> TLS.credentialLoadX509 certpath keypath
return $ makeServerSettings cred
maybeClientTLSHandshake :: String -> Socket -> BL8.ByteString -> TransIO ()
maybeClientTLSHandshake hostname sock input = do
mctx <- liftIO $ (do
global <- getSystemCertificateStore
let sp= makeClientSettings global hostname
ctx <- makeClientContext sp sock input
TLS.handshake ctx
return $ Just ctx)
`catch` \(e :: SomeException) -> return Nothing
case mctx of
Nothing -> error $ hostname ++": No secure connection" -- !> "NO TLS"
Just ctx -> do
-- liftIO $ print "TLS connection" >> return () -- !> "TLS"
modifyState $ \(Just c ) - > Just c{connData= Just $ TLSNode2Node $ unsafeCoerce ctx }
conn <- getSData <|> error "TLS: no socket connection"
liftIO $ writeIORef (connData conn) $ Just $ TLSNode2Node $ unsafeCoerce ctx
tctx <- makeParseContext $ TLS.recvData ctx >>= return . BL.fromChunks . (:[])
let tctx= ParseContext ( TLS.recvData ctx > > = return . SMore . BL.fromChunks . (: [ ] ) )
( unsafePerformIO $ newIORef False )
modify $ \st -> st{parseContext= tctx}
liftIO $ writeIORef (istream conn) tctx
onException $ \(_ :: SomeException) -> liftIO $ TLS.contextClose ctx
makeClientSettings global hostname= ClientParams{
TLS.clientEarlyData= Nothing
, TLS.clientUseMaxFragmentLength= Nothing
, TLS.clientServerIdentification= (hostname,"")
, TLS.clientUseServerNameIndication = False
, TLS.clientWantSessionResume = Nothing
, TLS.clientShared = novalidate
, TLS.clientHooks = def
, TLS.clientDebug= def
, TLS.clientSupported = supported
}
where
novalidate = def
{ TLS.sharedCAStore = global
, TLS.sharedValidationCache = validationCache
-- , TLS.sharedSessionManager = connectionSessionManager
}
validationCache= TLS.ValidationCache (\_ _ _ -> return TLS.ValidationCachePass)
(\_ _ _ -> return ())
makeServerSettings credential = def { -- TLS.ServerParams
TLS.serverWantClientCert = False
, TLS.serverCACertificates = []
, TLS.serverDHEParams = Nothing
, TLS.serverHooks = hooks
, TLS.serverShared = shared
, TLS.serverSupported = supported
}
where
-- Adding alpn to user's tlsServerHooks.
hooks = def
-- TLS.ServerHooks {
-- TLS.onALPNClientSuggest = TLS.onALPNClientSuggest tlsServerHooks <|>
-- (if settingsHTTP2Enabled set then Just alpn else Nothing)
-- }
shared = def {
TLS.sharedCredentials = TLS.Credentials [credential]
}
TLS.Supported
TLS.supportedVersions = [TLS.TLS12,TLS.TLS11,TLS.TLS10]
, TLS.supportedCiphers = ciphers
, TLS.supportedCompressions = [TLS.nullCompression]
, TLS.supportedHashSignatures = [
Safari 8 and go tls have bugs on SHA 512 and SHA 384 .
-- So, we don't specify them here at this moment.
(TLS.HashSHA256, TLS.SignatureRSA)
, (TLS.HashSHA224, TLS.SignatureRSA)
, (TLS.HashSHA1, TLS.SignatureRSA)
, (TLS.HashSHA1, TLS.SignatureDSS)
]
, TLS.supportedSecureRenegotiation = True
, TLS.supportedClientInitiatedRenegotiation = False
, TLS.supportedSession = True
, TLS.supportedFallbackScsv = True
}
ciphers :: [TLS.Cipher]
ciphers =
[ TLSExtra.cipher_ECDHE_RSA_AES128GCM_SHA256
, TLSExtra.cipher_ECDHE_RSA_AES128CBC_SHA256
, TLSExtra.cipher_ECDHE_RSA_AES128CBC_SHA
, TLSExtra.cipher_DHE_RSA_AES128GCM_SHA256
, TLSExtra.cipher_DHE_RSA_AES256_SHA256
, TLSExtra.cipher_DHE_RSA_AES128_SHA256
, TLSExtra.cipher_DHE_RSA_AES256_SHA1
, TLSExtra.cipher_DHE_RSA_AES128_SHA1
, TLSExtra.cipher_DHE_DSS_AES128_SHA1
, TLSExtra.cipher_DHE_DSS_AES256_SHA1
, TLSExtra.cipher_AES128_SHA1
, TLSExtra.cipher_AES256_SHA1
]
makeClientContext params sock _= do
input <- liftIO $ SBSL.getContents sock
inputBuffer <- newIORef input
liftIO $ TLS.contextNew (backend inputBuffer) params
where
backend inputBuffer= TLS.Backend {
TLS.backendFlush = return ()
, TLS.backendClose = NSS.close sock
, TLS.backendSend = NS.sendAll sock
\n - > NS.recv sock n > > = \x - > print ( " l=",B.length x ) > > return x ` catch ` \(SomeException _ ) - > error " EEEEEEERRRRRRRRRRRRRRRRRR " --do
input <- readIORef inputBuffer
let (res,input')= BL.splitAt (fromIntegral n) input
writeIORef inputBuffer input'
return $ BL8.toStrict res
}
step ! acc 0 = return acc
-- step !acc n = do
-- bs <- NS.recv sock n
step ( acc ` B.append ` bs ) ( n - B.length bs )
-- | Make a server-side TLS 'Context' for the given settings, on top of the
given TCP ` Socket ` connected to the remote end .
makeServerContext :: MonadIO m => TLS.ServerParams -> Socket -> BL.ByteString -> m Context
makeServerContext params sock input= liftIO $ do
inputBuffer <- newIORef input
TLS.contextNew (backend inputBuffer) params
where
backend inputBuffer= TLS.Backend {
TLS.backendFlush = return ()
, TLS.backendClose = NSS.close sock
, TLS.backendSend = NS.sendAll sock
NS.recv sock n
do
input <- readIORef inputBuffer
let (res,input')= BL.splitAt (fromIntegral n) input
writeIORef inputBuffer input'
return $ toStrict res
}
toStrict s= BE.concat $ BL.toChunks s :: BE.ByteString
sendAll ' sock bs = NS.sendAll sock bs ` E.catch ` \(SomeException e ) - > throwIO e
#else
import Control.Monad.IO.Class
initTLS :: MonadIO m => m ()
initTLS= return ()
initTLS' :: MonadIO m => FilePath -> FilePath -> m ()
initTLS' _ _ = return ()
#endif
| null | https://raw.githubusercontent.com/transient-haskell/transient-stack/dde6f6613a946d57bb70879a5c0e7e5a73a91dbe/transient-universe-tls/src/Transient/TLS.hs | haskell | ---------------------------------------------------------------------------
Module : Transient.MoveTLS
Copyright :
License : GPL-3
Maintainer :
Stability :
Portability :
| see <-haskell-processes-between-nodes-transient-effects-iv>
---------------------------------------------------------------------------
to avoid checking certificate. delete
| init TLS with the files "cert.pem" and "key.pem"
| init TLS using certificate.pem and a key.pem files
!> "after handshake"
!> "NO TLS"
liftIO $ print "TLS connection" >> return () -- !> "TLS"
, TLS.sharedSessionManager = connectionSessionManager
TLS.ServerParams
Adding alpn to user's tlsServerHooks.
TLS.ServerHooks {
TLS.onALPNClientSuggest = TLS.onALPNClientSuggest tlsServerHooks <|>
(if settingsHTTP2Enabled set then Just alpn else Nothing)
}
So, we don't specify them here at this moment.
do
step !acc n = do
bs <- NS.recv sock n
| Make a server-side TLS 'Context' for the given settings, on top of the |
# LANGUAGE CPP , OverloadedStrings , BangPatterns , ScopedTypeVariables #
module Transient.TLS(initTLS, initTLS') where
#ifndef ghcjs_HOST_OS
import Transient.Internals
import Transient.Move.Internals
import Transient.Backtrack
import Transient.Parse
import Network.Socket as NSS
import Network.Socket.ByteString as NS
import Network.TLS as TLS
import Network.TLS.Extra as TLSExtra
import qualified Crypto.Random.AESCtr as AESCtr
import qualified Network.Socket.ByteString.Lazy as SBSL
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString as BE
import qualified Data.X509.CertificateStore as C
import Data.Default
import Control.Applicative
import Control.Exception as E hiding (onException)
import Control.Monad.State
import Data.IORef
import Unsafe.Coerce
import System.IO.Unsafe
import System.Directory
import Debug.Trace
initTLS :: MonadIO m => m ()
initTLS = initTLS' "cert.pem" "key.pem"
initTLS' :: MonadIO m => FilePath -> FilePath -> m ()
initTLS' certpath keypath = liftIO $ writeIORef
tlsHooks
( True
, unsafeCoerce $ (TLS.sendData :: TLS.Context -> BL8.ByteString -> IO ())
, unsafeCoerce $ (TLS.recvData :: TLS.Context -> IO BE.ByteString)
, unsafeCoerce $ Transient.TLS.maybeTLSServerHandshake certpath keypath
, unsafeCoerce $ Transient.TLS.maybeClientTLSHandshake
, unsafeCoerce $ (Transient.TLS.tlsClose :: TLS.Context -> IO ())
)
tlsClose ctx= bye ctx >> contextClose ctx
maybeTLSServerHandshake
:: FilePath -> FilePath -> Socket -> BL8.ByteString -> TransIO ()
maybeTLSServerHandshake certpath keypath sock input= do
c <- liftIO $ doesFileExist "cert.pem"
k <- liftIO $ doesFileExist "key.pem"
when (not c || not k) $ error "cert.pem and key.pem must exist withing the current directory"
if ((not $ BL.null input) && BL.head input == 0x16)
then do
mctx <- liftIO $( do
ctx <- makeServerContext (ssettings certpath keypath) sock input
TLS.handshake ctx
return $Just ctx )
`catch` \(e:: SomeException) -> do
putStr "maybeTLSServerHandshake: "
print e
case mctx of
Nothing -> return ()
Just ctx -> do
tr "TLS CONNECTION"
modifyState $ \(Just c ) - > Just c{connData= Just $ TLSNode2Node $ unsafeCoerce ctx }
conn <- getSData <|> error "TLS: no socket connection"
liftIO $ writeIORef (connData conn) $ Just $ TLSNode2Node $ unsafeCoerce ctx
modify $ \s -> s{ parseContext=ParseContext (TLS.recvData ctx >>= return . SMore . BL8.fromStrict)
"" (unsafePerformIO $ newIORef False)}
onException $ \(e:: SomeException) -> liftIO $ TLS.contextClose ctx
else return ()
ssettings :: FilePath -> FilePath -> ServerParams
ssettings certpath keypath = unsafePerformIO $ do
cred <- either error id <$> TLS.credentialLoadX509 certpath keypath
return $ makeServerSettings cred
maybeClientTLSHandshake :: String -> Socket -> BL8.ByteString -> TransIO ()
maybeClientTLSHandshake hostname sock input = do
mctx <- liftIO $ (do
global <- getSystemCertificateStore
let sp= makeClientSettings global hostname
ctx <- makeClientContext sp sock input
TLS.handshake ctx
return $ Just ctx)
`catch` \(e :: SomeException) -> return Nothing
case mctx of
Just ctx -> do
modifyState $ \(Just c ) - > Just c{connData= Just $ TLSNode2Node $ unsafeCoerce ctx }
conn <- getSData <|> error "TLS: no socket connection"
liftIO $ writeIORef (connData conn) $ Just $ TLSNode2Node $ unsafeCoerce ctx
tctx <- makeParseContext $ TLS.recvData ctx >>= return . BL.fromChunks . (:[])
let tctx= ParseContext ( TLS.recvData ctx > > = return . SMore . BL.fromChunks . (: [ ] ) )
( unsafePerformIO $ newIORef False )
modify $ \st -> st{parseContext= tctx}
liftIO $ writeIORef (istream conn) tctx
onException $ \(_ :: SomeException) -> liftIO $ TLS.contextClose ctx
makeClientSettings global hostname= ClientParams{
TLS.clientEarlyData= Nothing
, TLS.clientUseMaxFragmentLength= Nothing
, TLS.clientServerIdentification= (hostname,"")
, TLS.clientUseServerNameIndication = False
, TLS.clientWantSessionResume = Nothing
, TLS.clientShared = novalidate
, TLS.clientHooks = def
, TLS.clientDebug= def
, TLS.clientSupported = supported
}
where
novalidate = def
{ TLS.sharedCAStore = global
, TLS.sharedValidationCache = validationCache
}
validationCache= TLS.ValidationCache (\_ _ _ -> return TLS.ValidationCachePass)
(\_ _ _ -> return ())
TLS.serverWantClientCert = False
, TLS.serverCACertificates = []
, TLS.serverDHEParams = Nothing
, TLS.serverHooks = hooks
, TLS.serverShared = shared
, TLS.serverSupported = supported
}
where
hooks = def
shared = def {
TLS.sharedCredentials = TLS.Credentials [credential]
}
TLS.Supported
TLS.supportedVersions = [TLS.TLS12,TLS.TLS11,TLS.TLS10]
, TLS.supportedCiphers = ciphers
, TLS.supportedCompressions = [TLS.nullCompression]
, TLS.supportedHashSignatures = [
Safari 8 and go tls have bugs on SHA 512 and SHA 384 .
(TLS.HashSHA256, TLS.SignatureRSA)
, (TLS.HashSHA224, TLS.SignatureRSA)
, (TLS.HashSHA1, TLS.SignatureRSA)
, (TLS.HashSHA1, TLS.SignatureDSS)
]
, TLS.supportedSecureRenegotiation = True
, TLS.supportedClientInitiatedRenegotiation = False
, TLS.supportedSession = True
, TLS.supportedFallbackScsv = True
}
ciphers :: [TLS.Cipher]
ciphers =
[ TLSExtra.cipher_ECDHE_RSA_AES128GCM_SHA256
, TLSExtra.cipher_ECDHE_RSA_AES128CBC_SHA256
, TLSExtra.cipher_ECDHE_RSA_AES128CBC_SHA
, TLSExtra.cipher_DHE_RSA_AES128GCM_SHA256
, TLSExtra.cipher_DHE_RSA_AES256_SHA256
, TLSExtra.cipher_DHE_RSA_AES128_SHA256
, TLSExtra.cipher_DHE_RSA_AES256_SHA1
, TLSExtra.cipher_DHE_RSA_AES128_SHA1
, TLSExtra.cipher_DHE_DSS_AES128_SHA1
, TLSExtra.cipher_DHE_DSS_AES256_SHA1
, TLSExtra.cipher_AES128_SHA1
, TLSExtra.cipher_AES256_SHA1
]
makeClientContext params sock _= do
input <- liftIO $ SBSL.getContents sock
inputBuffer <- newIORef input
liftIO $ TLS.contextNew (backend inputBuffer) params
where
backend inputBuffer= TLS.Backend {
TLS.backendFlush = return ()
, TLS.backendClose = NSS.close sock
, TLS.backendSend = NS.sendAll sock
input <- readIORef inputBuffer
let (res,input')= BL.splitAt (fromIntegral n) input
writeIORef inputBuffer input'
return $ BL8.toStrict res
}
step ! acc 0 = return acc
step ( acc ` B.append ` bs ) ( n - B.length bs )
given TCP ` Socket ` connected to the remote end .
makeServerContext :: MonadIO m => TLS.ServerParams -> Socket -> BL.ByteString -> m Context
makeServerContext params sock input= liftIO $ do
inputBuffer <- newIORef input
TLS.contextNew (backend inputBuffer) params
where
backend inputBuffer= TLS.Backend {
TLS.backendFlush = return ()
, TLS.backendClose = NSS.close sock
, TLS.backendSend = NS.sendAll sock
NS.recv sock n
do
input <- readIORef inputBuffer
let (res,input')= BL.splitAt (fromIntegral n) input
writeIORef inputBuffer input'
return $ toStrict res
}
toStrict s= BE.concat $ BL.toChunks s :: BE.ByteString
sendAll ' sock bs = NS.sendAll sock bs ` E.catch ` \(SomeException e ) - > throwIO e
#else
import Control.Monad.IO.Class
initTLS :: MonadIO m => m ()
initTLS= return ()
initTLS' :: MonadIO m => FilePath -> FilePath -> m ()
initTLS' _ _ = return ()
#endif
|
a471031f391f12796bc15f8526f7b959d92828eba0ff65a83087b2bc31e1eca3 | guardian/content-api-haskell-client | Section.hs | module Network.Guardian.ContentApi.Section where
import Data.Text (Text)
data Section = Section {
sectionId :: Text
, name :: Text
} deriving (Show)
| null | https://raw.githubusercontent.com/guardian/content-api-haskell-client/f80195c4117570bc3013cbe93ceb9c5d3f5e17bd/guardian-content-api-client/Network/Guardian/ContentApi/Section.hs | haskell | module Network.Guardian.ContentApi.Section where
import Data.Text (Text)
data Section = Section {
sectionId :: Text
, name :: Text
} deriving (Show)
|
|
342b6663fc6835edbd7a829de3cd7102f3407025c88a57fc56e8846d3bb0ad4a | abdulapopoola/SICPBook | Ex2.86.scm | #lang planet neil/sicp
;; INSTALLATION
External interface for Integer package
(put 'square 'integer
(lambda (x) (tag (* x x))))
(put 'arctan '(integer integer)
(lambda (x y) (make-real (atan x y))))
(put 'sine 'integer
(lambda (x) (make-real (sin x))))
(put 'cosine 'integer
(lambda (x) (make-real (cos x))))
;; Rational number package
;; External interface for Rational package
(put 'square 'rational
(lambda (x) (make-real (mul-rat x x))))
(put 'arctan '(rational rational)
(lambda (x y)
(make-real (atan (/ (numer x) (denom x))
(/ (numer y) (denom y))))))
(put 'sine 'rational
(lambda (x) (make-real (sin (/ (numer x) (denom x))))))
(put 'cosine 'rational
(lambda (x) (make-real (cos (/ (numer x) (denom x))))))
;; Real number package
;; External interface for Real package
(put 'square 'complex
(lambda (x) (tag (* x x))))
(put 'arctan '(real real)
(lambda (x y) (tag (atan x y))))
(put 'cosine '(real)
(lambda (x) (tag (cos x))))
(put 'sine '(real)
(lambda (x) (tag (sin x)))) | null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%202/2.5/Ex2.86.scm | scheme | INSTALLATION
Rational number package
External interface for Rational package
Real number package
External interface for Real package | #lang planet neil/sicp
External interface for Integer package
(put 'square 'integer
(lambda (x) (tag (* x x))))
(put 'arctan '(integer integer)
(lambda (x y) (make-real (atan x y))))
(put 'sine 'integer
(lambda (x) (make-real (sin x))))
(put 'cosine 'integer
(lambda (x) (make-real (cos x))))
(put 'square 'rational
(lambda (x) (make-real (mul-rat x x))))
(put 'arctan '(rational rational)
(lambda (x y)
(make-real (atan (/ (numer x) (denom x))
(/ (numer y) (denom y))))))
(put 'sine 'rational
(lambda (x) (make-real (sin (/ (numer x) (denom x))))))
(put 'cosine 'rational
(lambda (x) (make-real (cos (/ (numer x) (denom x))))))
(put 'square 'complex
(lambda (x) (tag (* x x))))
(put 'arctan '(real real)
(lambda (x y) (tag (atan x y))))
(put 'cosine '(real)
(lambda (x) (tag (cos x))))
(put 'sine '(real)
(lambda (x) (tag (sin x)))) |
592eb9db8f31f8766e0b0ae439ff2cca05cf4bb776dd496c7da47e27cdc657f6 | modular-macros/ocaml-macros | t250-closurerec-2.ml | open Lib;;
let rec f _ = 23 in
if f 0 <> 23 then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 15
11 CONSTINT 23
13 RETURN 1
15 CLOSUREREC 0 , 11
19 CONSTINT 23
21 PUSHCONST0
22 PUSHACC2
23 APPLY1
24 NEQ
25 BRANCHIFNOT 32
27 GETGLOBAL Not_found
29 MAKEBLOCK1 0
31 RAISE
32 POP 1
34 ATOM0
35 SETGLOBAL T250 - closurerec-2
37 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 15
11 CONSTINT 23
13 RETURN 1
15 CLOSUREREC 0, 11
19 CONSTINT 23
21 PUSHCONST0
22 PUSHACC2
23 APPLY1
24 NEQ
25 BRANCHIFNOT 32
27 GETGLOBAL Not_found
29 MAKEBLOCK1 0
31 RAISE
32 POP 1
34 ATOM0
35 SETGLOBAL T250-closurerec-2
37 STOP
**)
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/tool-ocaml/t250-closurerec-2.ml | ocaml | open Lib;;
let rec f _ = 23 in
if f 0 <> 23 then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 15
11 CONSTINT 23
13 RETURN 1
15 CLOSUREREC 0 , 11
19 CONSTINT 23
21 PUSHCONST0
22 PUSHACC2
23 APPLY1
24 NEQ
25 BRANCHIFNOT 32
27 GETGLOBAL Not_found
29 MAKEBLOCK1 0
31 RAISE
32 POP 1
34 ATOM0
35 SETGLOBAL T250 - closurerec-2
37 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 15
11 CONSTINT 23
13 RETURN 1
15 CLOSUREREC 0, 11
19 CONSTINT 23
21 PUSHCONST0
22 PUSHACC2
23 APPLY1
24 NEQ
25 BRANCHIFNOT 32
27 GETGLOBAL Not_found
29 MAKEBLOCK1 0
31 RAISE
32 POP 1
34 ATOM0
35 SETGLOBAL T250-closurerec-2
37 STOP
**)
|
|
6a79aacb3c15ea57950c96825d8d0879bdca2965f36a5bc6806c88d34f8bc451 | Liqwid-Labs/plutus-extra | Extra.hs | # OPTIONS_GHC -fno - omit - interface - pragmas #
module PlutusTx.Maybe.Extra (maybeMap) where
--------------------------------------------------------------------------------
import Data.Kind (Type)
--------------------------------------------------------------------------------
import PlutusTx.Maybe (Maybe, mapMaybe)
import PlutusTx.Prelude (flip)
--------------------------------------------------------------------------------
-- | Flipped version of `mapMaybe`, to correspond with `>>=`
# INLINEABLE maybeMap #
maybeMap :: forall (a :: Type) (b :: Type). [a] -> (a -> Maybe b) -> [b]
maybeMap = flip mapMaybe
| null | https://raw.githubusercontent.com/Liqwid-Labs/plutus-extra/347dd304e9b580d1747439a888bfaa79f1c5a25e/plutus-extra/src/PlutusTx/Maybe/Extra.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Flipped version of `mapMaybe`, to correspond with `>>=` | # OPTIONS_GHC -fno - omit - interface - pragmas #
module PlutusTx.Maybe.Extra (maybeMap) where
import Data.Kind (Type)
import PlutusTx.Maybe (Maybe, mapMaybe)
import PlutusTx.Prelude (flip)
# INLINEABLE maybeMap #
maybeMap :: forall (a :: Type) (b :: Type). [a] -> (a -> Maybe b) -> [b]
maybeMap = flip mapMaybe
|
34d60b9c354834c585a3599dad907db18015a46f8ac94a462ee3d1f26bf9c312 | massung/queue | queue.lisp | ;;;; Simple FIFO for Common Lisp
;;;;
Copyright ( c )
;;;;
This file is provided to you under the Apache License ,
;;;; Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
;;;; a copy of the License at
;;;;
;;;; -2.0
;;;;
;;;; Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
;;;; KIND, either express or implied. See the License for the
;;;; specific language governing permissions and limitations
;;;; under the License.
;;;;
(defpackage :queue
(:use :cl)
(:export
#:make-queue
;; push/pop elements on/off the queue
#:queue-push
#:queue-pop
#:queue-list))
(in-package :queue)
;;; ----------------------------------------------------
(defstruct (queue (:constructor %make-queue (xs &aux (ys (last xs)))))
(head xs :read-only t)
(tail ys :read-only t))
;;; ----------------------------------------------------
(defun make-queue (&key initial-contents)
"Create a new queue."
(%make-queue (cons nil initial-contents)))
;;; ----------------------------------------------------
(defmethod print-object ((q queue) stream)
"Output a deque to a stream."
(print-unreadable-object (q stream :type t)
(format stream "~:[EMPTY~;~:*~a~]" (rest (queue-head q)))))
;;; ----------------------------------------------------
(defun queue-push (x q)
"Push a value onto the tail of the queue."
(with-slots (tail)
q
(car (setf tail (cdr (rplacd tail (list x)))))))
;;; ----------------------------------------------------
(defun queue-pop (q)
"Pop a value off a queue, return the value and success flag."
(with-slots (head)
q
(when (rest head)
(values (car (setf head (cdr head))) t))))
;;; ----------------------------------------------------
(defun queue-list (q)
"Return the list of elements in the queue; does not alter the queue."
(rest (queue-head q)))
| null | https://raw.githubusercontent.com/massung/queue/84a88b3adbe2ff4f6cbc8d487d430fa1611c30e5/queue.lisp | lisp | Simple FIFO for Common Lisp
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
push/pop elements on/off the queue
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
---------------------------------------------------- | Copyright ( c )
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
(defpackage :queue
(:use :cl)
(:export
#:make-queue
#:queue-push
#:queue-pop
#:queue-list))
(in-package :queue)
(defstruct (queue (:constructor %make-queue (xs &aux (ys (last xs)))))
(head xs :read-only t)
(tail ys :read-only t))
(defun make-queue (&key initial-contents)
"Create a new queue."
(%make-queue (cons nil initial-contents)))
(defmethod print-object ((q queue) stream)
"Output a deque to a stream."
(print-unreadable-object (q stream :type t)
(format stream "~:[EMPTY~;~:*~a~]" (rest (queue-head q)))))
(defun queue-push (x q)
"Push a value onto the tail of the queue."
(with-slots (tail)
q
(car (setf tail (cdr (rplacd tail (list x)))))))
(defun queue-pop (q)
"Pop a value off a queue, return the value and success flag."
(with-slots (head)
q
(when (rest head)
(values (car (setf head (cdr head))) t))))
(defun queue-list (q)
"Return the list of elements in the queue; does not alter the queue."
(rest (queue-head q)))
|
5b124d792def78ec74b039a54aa7cfe96fa1eebdc14f63a3a92e41abc0928a46 | achirkin/vulkan | Foreign.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE Strict #-}
# LANGUAGE TypeApplications #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
-- | Collection of functions adapted from @Foreign@ module hierarchy
module Lib.Program.Foreign
( Ptr, plusPtr, Storable.sizeOf
, withVkArrayLen
, alloca, allocaArray
, peek, peekArray, poke
, ptrAtIndex
, asListVk
, allocaPeek, allocaPeekVk, allocaPeekDF
, mallocRes, mallocArrayRes, newArrayRes
) where
import qualified GHC.Base
import Control.Concurrent.MVar
import Control.Monad.IO.Class
import qualified Foreign.Marshal.Alloc as Foreign
import qualified Foreign.Marshal.Array as Foreign
import Foreign.Ptr
import Foreign.Storable (Storable)
import qualified Foreign.Storable as Storable
import Graphics.Vulkan.Marshal
import Numeric.DataFrame
import Numeric.DataFrame.IO
import Numeric.Dimensions
import Lib.Program
| This should probably be in Graphics . Vulkan . Marshal
withArrayLen :: (Storable a, VulkanMarshal a) => [a] -> (Word32 -> Ptr a -> IO b) -> IO b
withArrayLen xs pf = do
ret <- Foreign.withArrayLen xs (pf . fromIntegral)
touch xs
return ret
# INLINE withArrayLen #
withVkArrayLen :: (Storable a, VulkanMarshal a) => [a] -> (Word32 -> Ptr a -> Program' b) -> Program r b
withVkArrayLen xs pf = liftIOWith (withArrayLen xs . curry) (uncurry pf)
# INLINE withVkArrayLen #
| Prevent earlier GC of given value
touch :: a -> IO ()
touch x = GHC.Base.IO $ \s -> case GHC.Base.touch# x s of s' -> (# s', () #)
# INLINE touch #
alloca :: Storable a
=> (Ptr a -> Program' b)
-> Program r b
alloca = liftIOWith Foreign.alloca
-- | Despite its name, this command does not copy data from a created pointer.
-- It uses `newVkData` function inside.
allocaPeekVk :: VulkanMarshal a
=> (Ptr a -> Program () ())
-> Program r a
allocaPeekVk pf = Program $ \ref c -> do
locVar <- liftIO newEmptyMVar
a <- newVkData (\ptr -> unProgram (pf ptr) ref (putMVar locVar))
takeMVar locVar >>= c . (a <$)
allocaPeekDF :: forall a (ns :: [Nat]) r
. (PrimBytes a, Dimensions ns)
=> (Ptr a -> Program () ())
-> Program r (DataFrame a ns)
allocaPeekDF pf
| Dict <- inferKnownBackend @a @ns
= Program $ \ref c -> do
mdf <- newPinnedDataFrame
locVar <- liftIO newEmptyMVar
withDataFramePtr mdf $ \ptr -> unProgram (pf ptr) ref (putMVar locVar)
df <- unsafeFreezeDataFrame mdf
takeMVar locVar >>= c . (df <$)
allocaArray :: Storable a
=> Int
-> (Ptr a -> Program' b)
-> Program r b
allocaArray = liftIOWith . Foreign.allocaArray
allocaPeek :: Storable a
=> (Ptr a -> Program (Either VulkanException a) ())
-> Program r a
allocaPeek f = alloca $ \ptr -> f ptr >> liftIO (Storable.peek ptr)
peekArray :: Storable a => Int -> Ptr a -> Program r [a]
peekArray n = liftIO . Foreign.peekArray n
peek :: Storable a => Ptr a -> Program r a
peek = liftIO . Storable.peek
poke :: Storable a => Ptr a -> a -> Program r ()
poke p v = liftIO $ Storable.poke p v
ptrAtIndex :: forall a. Storable a => Ptr a -> Int -> Ptr a
ptrAtIndex ptr i = ptr `plusPtr` (i * Storable.sizeOf @a undefined)
-- | Get size of action output and then get the result,
-- performing data copy.
asListVk :: Storable x
=> (Ptr Word32 -> Ptr x -> Program (Either VulkanException [x]) ())
-> Program r [x]
asListVk action = alloca $ \counterPtr -> do
action counterPtr VK_NULL_HANDLE
counter <- liftIO $ fromIntegral <$> Storable.peek counterPtr
if counter <= 0
then pure []
else allocaArray counter $ \valPtr -> do
action counterPtr valPtr
liftIO $ Foreign.peekArray counter valPtr
-- | Allocate an array and release it after continuation finishes.
-- Uses @allocaArray@ from @Foreign@ inside.
--
-- Use `locally` to bound the scope of resource allocation.
mallocArrayRes :: Storable a => Int -> Program r (Ptr a)
mallocArrayRes n = Program $ \_ c -> Foreign.allocaArray n (c . Right)
| Allocate some memory for and release it after continuation finishes .
-- Uses @alloca@ from @Foreign@ inside.
--
-- Use `locally` to bound the scope of resource allocation.
mallocRes :: Storable a => Program r (Ptr a)
mallocRes = Program $ \_ c -> Foreign.alloca (c . Right)
-- | Temporarily store a list of storable values in memory
-- and release it after continuation finishes.
-- Uses @withArray@ from @Foreign@ inside.
--
-- Use `locally` to bound the scope of resource allocation.
newArrayRes :: Storable a => [a] -> Program r (Ptr a)
newArrayRes xs = Program $ \_ c -> Foreign.withArray xs (c . Right)
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-triangles/src/Lib/Program/Foreign.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE Strict #
| Collection of functions adapted from @Foreign@ module hierarchy
| Despite its name, this command does not copy data from a created pointer.
It uses `newVkData` function inside.
| Get size of action output and then get the result,
performing data copy.
| Allocate an array and release it after continuation finishes.
Uses @allocaArray@ from @Foreign@ inside.
Use `locally` to bound the scope of resource allocation.
Uses @alloca@ from @Foreign@ inside.
Use `locally` to bound the scope of resource allocation.
| Temporarily store a list of storable values in memory
and release it after continuation finishes.
Uses @withArray@ from @Foreign@ inside.
Use `locally` to bound the scope of resource allocation. | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
module Lib.Program.Foreign
( Ptr, plusPtr, Storable.sizeOf
, withVkArrayLen
, alloca, allocaArray
, peek, peekArray, poke
, ptrAtIndex
, asListVk
, allocaPeek, allocaPeekVk, allocaPeekDF
, mallocRes, mallocArrayRes, newArrayRes
) where
import qualified GHC.Base
import Control.Concurrent.MVar
import Control.Monad.IO.Class
import qualified Foreign.Marshal.Alloc as Foreign
import qualified Foreign.Marshal.Array as Foreign
import Foreign.Ptr
import Foreign.Storable (Storable)
import qualified Foreign.Storable as Storable
import Graphics.Vulkan.Marshal
import Numeric.DataFrame
import Numeric.DataFrame.IO
import Numeric.Dimensions
import Lib.Program
| This should probably be in Graphics . Vulkan . Marshal
withArrayLen :: (Storable a, VulkanMarshal a) => [a] -> (Word32 -> Ptr a -> IO b) -> IO b
withArrayLen xs pf = do
ret <- Foreign.withArrayLen xs (pf . fromIntegral)
touch xs
return ret
# INLINE withArrayLen #
withVkArrayLen :: (Storable a, VulkanMarshal a) => [a] -> (Word32 -> Ptr a -> Program' b) -> Program r b
withVkArrayLen xs pf = liftIOWith (withArrayLen xs . curry) (uncurry pf)
# INLINE withVkArrayLen #
| Prevent earlier GC of given value
touch :: a -> IO ()
touch x = GHC.Base.IO $ \s -> case GHC.Base.touch# x s of s' -> (# s', () #)
# INLINE touch #
alloca :: Storable a
=> (Ptr a -> Program' b)
-> Program r b
alloca = liftIOWith Foreign.alloca
allocaPeekVk :: VulkanMarshal a
=> (Ptr a -> Program () ())
-> Program r a
allocaPeekVk pf = Program $ \ref c -> do
locVar <- liftIO newEmptyMVar
a <- newVkData (\ptr -> unProgram (pf ptr) ref (putMVar locVar))
takeMVar locVar >>= c . (a <$)
allocaPeekDF :: forall a (ns :: [Nat]) r
. (PrimBytes a, Dimensions ns)
=> (Ptr a -> Program () ())
-> Program r (DataFrame a ns)
allocaPeekDF pf
| Dict <- inferKnownBackend @a @ns
= Program $ \ref c -> do
mdf <- newPinnedDataFrame
locVar <- liftIO newEmptyMVar
withDataFramePtr mdf $ \ptr -> unProgram (pf ptr) ref (putMVar locVar)
df <- unsafeFreezeDataFrame mdf
takeMVar locVar >>= c . (df <$)
allocaArray :: Storable a
=> Int
-> (Ptr a -> Program' b)
-> Program r b
allocaArray = liftIOWith . Foreign.allocaArray
allocaPeek :: Storable a
=> (Ptr a -> Program (Either VulkanException a) ())
-> Program r a
allocaPeek f = alloca $ \ptr -> f ptr >> liftIO (Storable.peek ptr)
peekArray :: Storable a => Int -> Ptr a -> Program r [a]
peekArray n = liftIO . Foreign.peekArray n
peek :: Storable a => Ptr a -> Program r a
peek = liftIO . Storable.peek
poke :: Storable a => Ptr a -> a -> Program r ()
poke p v = liftIO $ Storable.poke p v
ptrAtIndex :: forall a. Storable a => Ptr a -> Int -> Ptr a
ptrAtIndex ptr i = ptr `plusPtr` (i * Storable.sizeOf @a undefined)
asListVk :: Storable x
=> (Ptr Word32 -> Ptr x -> Program (Either VulkanException [x]) ())
-> Program r [x]
asListVk action = alloca $ \counterPtr -> do
action counterPtr VK_NULL_HANDLE
counter <- liftIO $ fromIntegral <$> Storable.peek counterPtr
if counter <= 0
then pure []
else allocaArray counter $ \valPtr -> do
action counterPtr valPtr
liftIO $ Foreign.peekArray counter valPtr
mallocArrayRes :: Storable a => Int -> Program r (Ptr a)
mallocArrayRes n = Program $ \_ c -> Foreign.allocaArray n (c . Right)
| Allocate some memory for and release it after continuation finishes .
mallocRes :: Storable a => Program r (Ptr a)
mallocRes = Program $ \_ c -> Foreign.alloca (c . Right)
newArrayRes :: Storable a => [a] -> Program r (Ptr a)
newArrayRes xs = Program $ \_ c -> Foreign.withArray xs (c . Right)
|
b7e4e7f03971ac1f9ea25749f73616ccb398782fcd17ee967550e96116474181 | richcarl/eunit | eunit_server.erl | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may
%% not use this file except in compliance with the License. You may obtain
%% a copy of the License at <-2.0>
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% Alternatively, you may use this file under the terms of the GNU Lesser
General Public License ( the " LGPL " ) as published by the Free Software
Foundation ; either version 2.1 , or ( at your option ) any later version .
%% If you wish to allow use of your version of this file only under the
%% terms of the LGPL, you should delete the provisions above and replace
%% them with the notice and other provisions required by the LGPL; see
%% </>. If you do not delete the provisions
%% above, a recipient may use your version of this file under the terms of
either the Apache License or the LGPL .
%%
@author < >
2006
@private
%% @see eunit
@doc EUnit server process
-module(eunit_server).
-export([start/1, stop/1, start_test/4, watch/3, watch_path/3,
watch_regexp/3]).
-export([main/1]). % private
-include("eunit.hrl").
-include("eunit_internal.hrl").
-define(AUTO_TIMEOUT, 60000). %% auto test time limit
%% TODO: pass options to server, such as default timeout?
start(Server) when is_atom(Server) ->
ensure_started(Server).
stop(Server) ->
command(Server, stop).
-record(job, {super, test, options}).
The ` Super ' process will receive a stream of status messages ; see
%% eunit_proc:status_message/3 for details.
start_test(Server, Super, T, Options) ->
command(Server, {start, #job{super = Super,
test = T,
options = Options}}).
watch(Server, Module, Opts) when is_atom(Module) ->
command(Server, {watch, {module, Module}, Opts}).
watch_path(Server, Path, Opts) ->
command(Server, {watch, {path, filename:flatten(Path)}, Opts}).
%% note that the user must use $ at the end to match whole paths only
watch_regexp(Server, Regex, Opts) ->
case re:compile(Regex,[anchored]) of
{ok, R} ->
command(Server, {watch, {regexp, R}, Opts});
{error, _}=Error ->
Error
end.
%% This makes sure the server is started before sending the command, and
%% returns {ok, Result} if the server accepted the command or {error,
%% server_down} if the server process crashes. If the server does not
%% reply, this function will wait until the server is killed.
command(Server, Cmd) ->
if is_atom(Server), Cmd /= stop -> ensure_started(Server);
true -> ok
end,
if is_pid(Server) -> command_1(Server, Cmd);
true ->
case whereis(Server) of
undefined -> {error, server_down};
Pid -> command_1(Pid, Cmd)
end
end.
command_1(Pid, Cmd) when is_pid(Pid) ->
Pid ! {command, self(), Cmd},
command_wait(Pid, 1000, undefined).
command_wait(Pid, Timeout, Monitor) ->
receive
{Pid, Result} -> Result;
{'DOWN', Monitor, process, Pid, _R} -> {error, server_down}
after Timeout ->
%% avoid creating a monitor unless some time has passed
command_wait(Pid, infinity, erlang:monitor(process, Pid))
end.
%% Starting the server
ensure_started(Name) ->
ensure_started(Name, 5).
ensure_started(Name, N) when N > 0 ->
case whereis(Name) of
undefined ->
Parent = self(),
Pid = spawn(fun () -> server_start(Name, Parent) end),
receive
{Pid, ok} ->
Pid;
{Pid, error} ->
receive after 200 -> ensure_started(Name, N - 1) end
end;
Pid ->
Pid
end;
ensure_started(_, _) ->
throw(no_server).
server_start(undefined = Name, Parent) ->
%% anonymous server
server_start_1(Name, Parent);
server_start(Name, Parent) ->
try register(Name, self()) of
true -> server_start_1(Name, Parent)
catch
_:_ ->
Parent ! {self(), error},
exit(error)
end.
server_start_1(Name, Parent) ->
Parent ! {self(), ok},
server_init(Name).
-record(state, {name,
stopped,
jobs,
queue,
auto_test,
modules,
paths,
regexps}).
server_init(Name) ->
server(#state{name = Name,
stopped = false,
jobs = dict:new(),
queue = queue:new(),
auto_test = queue:new(),
modules = sets:new(),
paths = sets:new(),
regexps = sets:new()}).
server(St) ->
server_check_exit(St),
?MODULE:main(St).
@private
main(St) ->
receive
{done, auto_test, _Pid} ->
server(auto_test_done(St));
{done, Reference, _Pid} ->
server(handle_done(Reference, St));
{command, From, _Cmd} when St#state.stopped ->
From ! {self(), stopped};
{command, From, Cmd} ->
server_command(From, Cmd, St);
{code_monitor, {loaded, M, _Time}} ->
case is_watched(M, St) of
true ->
server(new_auto_test(self(), M, St));
false ->
server(St)
end
end.
server_check_exit(St) ->
case dict:size(St#state.jobs) of
0 when St#state.stopped -> exit(normal);
_ -> ok
end.
server_command(From, {start, Job}, St) ->
Reference = make_ref(),
St1 = case proplists:get_bool(enqueue, Job#job.options) of
true ->
enqueue(Job, From, Reference, St);
false ->
start_job(Job, From, Reference, St)
end,
server_command_reply(From, {ok, Reference}),
server(St1);
server_command(From, stop, St) ->
%% unregister the server name and let remaining jobs finish
server_command_reply(From, {error, stopped}),
catch unregister(St#state.name),
server(St#state{stopped = true});
server_command(From, {watch, Target, _Opts}, St) ->
%% the code watcher is only started on demand
%% TODO: this is disabled for now
%%code_monitor:monitor(self()),
%% TODO: propagate options to testing stage
St1 = add_watch(Target, St),
server_command_reply(From, ok),
server(St1);
server_command(From, {forget, Target}, St) ->
St1 = delete_watch(Target, St),
server_command_reply(From, ok),
server(St1);
server_command(From, Cmd, St) ->
server_command_reply(From, {error, {unknown_command, Cmd}}),
server(St).
server_command_reply(From, Result) ->
From ! {self(), Result}.
enqueue(Job, From, Reference, St) ->
case dict:size(St#state.jobs) of
0 ->
start_job(Job, From, Reference, St);
_ ->
St#state{queue = queue:in({Job, From, Reference},
St#state.queue)}
end.
dequeue(St) ->
case queue:out(St#state.queue) of
{empty, _} ->
St;
{{value, {Job, From, Reference}}, Queue} ->
start_job(Job, From, Reference, St#state{queue = Queue})
end.
start_job(Job, From, Reference, St) ->
From ! {start, Reference},
%% The default is to run tests in order unless otherwise specified
Order = proplists:get_value(order, Job#job.options, inorder),
eunit_proc:start(Job#job.test, Order, Job#job.super, Reference),
St#state{jobs = dict:store(Reference, From, St#state.jobs)}.
handle_done(Reference, St) ->
case dict:find(Reference, St#state.jobs) of
{ok, From} ->
From ! {done, Reference},
dequeue(St#state{jobs = dict:erase(Reference,
St#state.jobs)});
error ->
St
end.
%% Adding and removing watched modules or paths
add_watch({module, M}, St) ->
St#state{modules = sets:add_element(M, St#state.modules)};
add_watch({path, P}, St) ->
St#state{paths = sets:add_element(P, St#state.paths)};
add_watch({regexp, R}, St) ->
St#state{regexps = sets:add_element(R, St#state.regexps)}.
delete_watch({module, M}, St) ->
St#state{modules = sets:del_element(M, St#state.modules)};
delete_watch({path, P}, St) ->
St#state{paths = sets:del_element(P, St#state.paths)};
delete_watch({regexp, R}, St) ->
St#state{regexps = sets:del_element(R, St#state.regexps)}.
%% Checking if a module is being watched
is_watched(M, St) when is_atom(M) ->
sets:is_element(M, St#state.modules) orelse
is_watched(code:which(M), St);
is_watched(Path, St) ->
sets:is_element(filename:dirname(Path), St#state.paths) orelse
match_any(sets:to_list(St#state.regexps), Path).
match_any([R | Rs], Str) ->
case re:run(Str, R, [{capture,none}]) of
match -> true;
_ -> match_any(Rs, Str)
end;
match_any([], _Str) -> false.
%% Running automatic tests when a watched module is loaded.
%% Uses a queue in order to avoid overlapping output when several
%% watched modules are loaded simultaneously. (The currently running
%% automatic test is kept in the queue until it is done. An empty queue
%% means that no automatic test is running.)
new_auto_test(Server, M, St) ->
case queue:is_empty(St#state.auto_test) of
true ->
start_auto_test(Server, M);
false ->
ok
end,
St#state{auto_test = queue:in({Server, M}, St#state.auto_test)}.
auto_test_done(St) ->
%% remove finished test from queue before checking for more
{_, Queue} = queue:out(St#state.auto_test),
case queue:out(Queue) of
{{value, {Server, M}}, _} ->
%% this is just lookahead - the item is not removed
start_auto_test(Server, M);
{empty, _} ->
ok
end,
St#state{auto_test = Queue}.
start_auto_test(Server, M) ->
spawn(fun () -> auto_super(Server, M) end).
auto_super(Server, M) ->
process_flag(trap_exit, true),
%% Give the user a short delay before any output is produced
receive after 333 -> ok end,
%% Make sure output is sent to console on server node
group_leader(whereis(user), self()),
Pid = spawn_link(fun () -> auto_proc(Server, M) end),
receive
{'EXIT', Pid, _} ->
ok
after ?AUTO_TIMEOUT ->
exit(Pid, kill),
io:put_chars("\n== EUnit: automatic test was aborted ==\n"),
io:put_chars("\n> ")
end,
Server ! {done, auto_test, self()}.
auto_proc(Server, M) ->
%% Make the output start on a new line instead of on the same line
%% as the current shell prompt.
io:fwrite("\n== EUnit: testing module ~w ==\n", [M]),
eunit:test(Server, M, [enqueue]),
%% Make sure to print a dummy prompt at the end of the output, most
of all so that the Emacs mode realizes that input is active .
io:put_chars("\n-> ").
| null | https://raw.githubusercontent.com/richcarl/eunit/cb7eb2bc2cec01e405c717b6f6b551be7d256f06/src/eunit_server.erl | erlang | not use this file except in compliance with the License. You may obtain
a copy of the License at <-2.0>
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Alternatively, you may use this file under the terms of the GNU Lesser
If you wish to allow use of your version of this file only under the
terms of the LGPL, you should delete the provisions above and replace
them with the notice and other provisions required by the LGPL; see
</>. If you do not delete the provisions
above, a recipient may use your version of this file under the terms of
@see eunit
private
auto test time limit
TODO: pass options to server, such as default timeout?
eunit_proc:status_message/3 for details.
note that the user must use $ at the end to match whole paths only
This makes sure the server is started before sending the command, and
returns {ok, Result} if the server accepted the command or {error,
server_down} if the server process crashes. If the server does not
reply, this function will wait until the server is killed.
avoid creating a monitor unless some time has passed
Starting the server
anonymous server
unregister the server name and let remaining jobs finish
the code watcher is only started on demand
TODO: this is disabled for now
code_monitor:monitor(self()),
TODO: propagate options to testing stage
The default is to run tests in order unless otherwise specified
Adding and removing watched modules or paths
Checking if a module is being watched
Running automatic tests when a watched module is loaded.
Uses a queue in order to avoid overlapping output when several
watched modules are loaded simultaneously. (The currently running
automatic test is kept in the queue until it is done. An empty queue
means that no automatic test is running.)
remove finished test from queue before checking for more
this is just lookahead - the item is not removed
Give the user a short delay before any output is produced
Make sure output is sent to console on server node
Make the output start on a new line instead of on the same line
as the current shell prompt.
Make sure to print a dummy prompt at the end of the output, most | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may
distributed under the License is distributed on an " AS IS " BASIS ,
General Public License ( the " LGPL " ) as published by the Free Software
Foundation ; either version 2.1 , or ( at your option ) any later version .
either the Apache License or the LGPL .
@author < >
2006
@private
@doc EUnit server process
-module(eunit_server).
-export([start/1, stop/1, start_test/4, watch/3, watch_path/3,
watch_regexp/3]).
-include("eunit.hrl").
-include("eunit_internal.hrl").
start(Server) when is_atom(Server) ->
ensure_started(Server).
stop(Server) ->
command(Server, stop).
-record(job, {super, test, options}).
The ` Super ' process will receive a stream of status messages ; see
start_test(Server, Super, T, Options) ->
command(Server, {start, #job{super = Super,
test = T,
options = Options}}).
watch(Server, Module, Opts) when is_atom(Module) ->
command(Server, {watch, {module, Module}, Opts}).
watch_path(Server, Path, Opts) ->
command(Server, {watch, {path, filename:flatten(Path)}, Opts}).
watch_regexp(Server, Regex, Opts) ->
case re:compile(Regex,[anchored]) of
{ok, R} ->
command(Server, {watch, {regexp, R}, Opts});
{error, _}=Error ->
Error
end.
command(Server, Cmd) ->
if is_atom(Server), Cmd /= stop -> ensure_started(Server);
true -> ok
end,
if is_pid(Server) -> command_1(Server, Cmd);
true ->
case whereis(Server) of
undefined -> {error, server_down};
Pid -> command_1(Pid, Cmd)
end
end.
command_1(Pid, Cmd) when is_pid(Pid) ->
Pid ! {command, self(), Cmd},
command_wait(Pid, 1000, undefined).
command_wait(Pid, Timeout, Monitor) ->
receive
{Pid, Result} -> Result;
{'DOWN', Monitor, process, Pid, _R} -> {error, server_down}
after Timeout ->
command_wait(Pid, infinity, erlang:monitor(process, Pid))
end.
ensure_started(Name) ->
ensure_started(Name, 5).
ensure_started(Name, N) when N > 0 ->
case whereis(Name) of
undefined ->
Parent = self(),
Pid = spawn(fun () -> server_start(Name, Parent) end),
receive
{Pid, ok} ->
Pid;
{Pid, error} ->
receive after 200 -> ensure_started(Name, N - 1) end
end;
Pid ->
Pid
end;
ensure_started(_, _) ->
throw(no_server).
server_start(undefined = Name, Parent) ->
server_start_1(Name, Parent);
server_start(Name, Parent) ->
try register(Name, self()) of
true -> server_start_1(Name, Parent)
catch
_:_ ->
Parent ! {self(), error},
exit(error)
end.
server_start_1(Name, Parent) ->
Parent ! {self(), ok},
server_init(Name).
-record(state, {name,
stopped,
jobs,
queue,
auto_test,
modules,
paths,
regexps}).
server_init(Name) ->
server(#state{name = Name,
stopped = false,
jobs = dict:new(),
queue = queue:new(),
auto_test = queue:new(),
modules = sets:new(),
paths = sets:new(),
regexps = sets:new()}).
server(St) ->
server_check_exit(St),
?MODULE:main(St).
@private
main(St) ->
receive
{done, auto_test, _Pid} ->
server(auto_test_done(St));
{done, Reference, _Pid} ->
server(handle_done(Reference, St));
{command, From, _Cmd} when St#state.stopped ->
From ! {self(), stopped};
{command, From, Cmd} ->
server_command(From, Cmd, St);
{code_monitor, {loaded, M, _Time}} ->
case is_watched(M, St) of
true ->
server(new_auto_test(self(), M, St));
false ->
server(St)
end
end.
server_check_exit(St) ->
case dict:size(St#state.jobs) of
0 when St#state.stopped -> exit(normal);
_ -> ok
end.
server_command(From, {start, Job}, St) ->
Reference = make_ref(),
St1 = case proplists:get_bool(enqueue, Job#job.options) of
true ->
enqueue(Job, From, Reference, St);
false ->
start_job(Job, From, Reference, St)
end,
server_command_reply(From, {ok, Reference}),
server(St1);
server_command(From, stop, St) ->
server_command_reply(From, {error, stopped}),
catch unregister(St#state.name),
server(St#state{stopped = true});
server_command(From, {watch, Target, _Opts}, St) ->
St1 = add_watch(Target, St),
server_command_reply(From, ok),
server(St1);
server_command(From, {forget, Target}, St) ->
St1 = delete_watch(Target, St),
server_command_reply(From, ok),
server(St1);
server_command(From, Cmd, St) ->
server_command_reply(From, {error, {unknown_command, Cmd}}),
server(St).
server_command_reply(From, Result) ->
From ! {self(), Result}.
enqueue(Job, From, Reference, St) ->
case dict:size(St#state.jobs) of
0 ->
start_job(Job, From, Reference, St);
_ ->
St#state{queue = queue:in({Job, From, Reference},
St#state.queue)}
end.
dequeue(St) ->
case queue:out(St#state.queue) of
{empty, _} ->
St;
{{value, {Job, From, Reference}}, Queue} ->
start_job(Job, From, Reference, St#state{queue = Queue})
end.
start_job(Job, From, Reference, St) ->
From ! {start, Reference},
Order = proplists:get_value(order, Job#job.options, inorder),
eunit_proc:start(Job#job.test, Order, Job#job.super, Reference),
St#state{jobs = dict:store(Reference, From, St#state.jobs)}.
handle_done(Reference, St) ->
case dict:find(Reference, St#state.jobs) of
{ok, From} ->
From ! {done, Reference},
dequeue(St#state{jobs = dict:erase(Reference,
St#state.jobs)});
error ->
St
end.
add_watch({module, M}, St) ->
St#state{modules = sets:add_element(M, St#state.modules)};
add_watch({path, P}, St) ->
St#state{paths = sets:add_element(P, St#state.paths)};
add_watch({regexp, R}, St) ->
St#state{regexps = sets:add_element(R, St#state.regexps)}.
delete_watch({module, M}, St) ->
St#state{modules = sets:del_element(M, St#state.modules)};
delete_watch({path, P}, St) ->
St#state{paths = sets:del_element(P, St#state.paths)};
delete_watch({regexp, R}, St) ->
St#state{regexps = sets:del_element(R, St#state.regexps)}.
is_watched(M, St) when is_atom(M) ->
sets:is_element(M, St#state.modules) orelse
is_watched(code:which(M), St);
is_watched(Path, St) ->
sets:is_element(filename:dirname(Path), St#state.paths) orelse
match_any(sets:to_list(St#state.regexps), Path).
match_any([R | Rs], Str) ->
case re:run(Str, R, [{capture,none}]) of
match -> true;
_ -> match_any(Rs, Str)
end;
match_any([], _Str) -> false.
new_auto_test(Server, M, St) ->
case queue:is_empty(St#state.auto_test) of
true ->
start_auto_test(Server, M);
false ->
ok
end,
St#state{auto_test = queue:in({Server, M}, St#state.auto_test)}.
auto_test_done(St) ->
{_, Queue} = queue:out(St#state.auto_test),
case queue:out(Queue) of
{{value, {Server, M}}, _} ->
start_auto_test(Server, M);
{empty, _} ->
ok
end,
St#state{auto_test = Queue}.
start_auto_test(Server, M) ->
spawn(fun () -> auto_super(Server, M) end).
auto_super(Server, M) ->
process_flag(trap_exit, true),
receive after 333 -> ok end,
group_leader(whereis(user), self()),
Pid = spawn_link(fun () -> auto_proc(Server, M) end),
receive
{'EXIT', Pid, _} ->
ok
after ?AUTO_TIMEOUT ->
exit(Pid, kill),
io:put_chars("\n== EUnit: automatic test was aborted ==\n"),
io:put_chars("\n> ")
end,
Server ! {done, auto_test, self()}.
auto_proc(Server, M) ->
io:fwrite("\n== EUnit: testing module ~w ==\n", [M]),
eunit:test(Server, M, [enqueue]),
of all so that the Emacs mode realizes that input is active .
io:put_chars("\n-> ").
|