_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 |
|---|---|---|---|---|---|---|---|---|
9e53c07fd9b05e357e3dc5d91fe7ab1a73be0c1748323f6af06b4f7c3187d723 | fp-works/2019-winter-Haskell-school | TestJoinList.hs | import JoinList
import Sized
import Scrabble
import Buffer
import Control.Applicative (liftA2)
import Data.Monoid
-- need safe
import Safe
import Test.Hspec
import Test.QuickCheck
instance (Monoid m, Arbitrary a, Arbitrary m) => Arbitrary (JoinList m a) where
arbitrary = sized arbitraryJoinList
arbitraryJoinList :: (Monoid m, Arbitrary m, Arbitrary a) => Int -> Gen (JoinList m a)
arbitraryJoinList 0 = pure Empty
arbitraryJoinList n = do
m <- arbitrary
a <- arbitrary
oneof [pure $ Single m a, liftA2 (+++) sublist sublist]
where sublist = arbitraryJoinList (n `div` 2)
validTags :: (Eq m, Monoid m) => (JoinList m a) -> Bool
validTags Empty = True
validTags (Single _ _) = True
validTags (Append m l1 l2) = m == (tag l1 <> tag l2)
validSize :: (Sized m) => (JoinList m a) -> Bool
validSize Empty = True
validSize (Single s _) = size s == Size 1
validSize (Append s l1 l2) =
size s == size l1 + size l2 && validSize l1 && validSize l2
replaceTagWithSize :: JoinList m a -> JoinList Size a
replaceTagWithSize Empty = Empty
replaceTagWithSize (Single _ a) = Single (Size 1) a
replaceTagWithSize (Append _ l1 l2) = l1' +++ l2'
where l1' = replaceTagWithSize l1
l2' = replaceTagWithSize l2
main :: IO ()
main = hspec $ do
describe "+++" $ do
it "should produce JoinList that has valid tags" $ property $
forAll (arbitrary :: Gen (JoinList (Sum Int) Char)) validTags
describe "indexJ" $ do
it "should produce data at the correct index" $ property $
forAll (arbitrary :: Gen (JoinList (Sum Int) Char, Small Int))
(\(l, i) -> let l' = replaceTagWithSize l
i' = getSmall i
in (indexJ i' l') == (jlToList l' `atMay` i'))
describe "dropJ" $ do
it "should drop exactly n number of elements at the beginning" $ property $
forAll (arbitrary :: Gen (JoinList (Sum Int) Char, Positive (Small Int)))
(\(l, n) -> let n' = getSmall . getPositive $ n
l' = dropJ n' . replaceTagWithSize $ l
in jlToList l' == drop n' (jlToList l) && validSize l')
it "can drop everything in the left sublist correctly" $ do
(jlToList . dropJ 1 $
(Append (Size 2) (Single (Size 1) 'a') (Single 1 'b')))
`shouldBe` "b"
describe "takeJ" $ do
it "should take exactly n number of elements at the beginning" $ property $
forAll (arbitrary :: Gen (JoinList (Sum Int) Char, Positive (Small Int)))
(\(l, n) -> let n' = getSmall . getPositive $ n
l' = takeJ n' . replaceTagWithSize $ l
in jlToList l' == take n' (jlToList l) && validSize l')
it "can take everything in the left sublist correctly" $ do
(jlToList . takeJ 1 $
(Append (Size 2) (Single (Size 1) 'a') (Single 1 'b')))
`shouldBe` "a"
describe "scoreLine" $ do
it "should return correct scrabble scores" $ do
scoreLine "yay " `shouldBe` (Single (Score 9) "yay ")
scoreLine "haskell!" `shouldBe` (Single (Score 14) "haskell!")
describe "Score" $ do
it "should yield correct scrabble score when joined with (+++)" $ do
scoreLine "yay " +++ scoreLine "haskell!"
`shouldBe` Append (Score 23)
(Single (Score 9) "yay ")
(Single (Score 14) "haskell!")
describe "Buffer JoinList" $ do
it "should satisfy: toString . fromString == id" $ do
forAll (arbitrary :: Gen [String])
(\xs -> let s = unlines xs
jl = (fromString s) :: JoinList (Score, Size) String
in toString jl == s)
it "should replace line given valid index" $ do
forAll (arbitrary :: Gen ([String], NonNegative Int))
(\(xs,n) -> let s = unlines xs
jl = (fromString s) :: JoinList (Score, Size) String
n' = getNonNegative n
jl' = replaceLine n' "YAY" jl
in size jl == size jl'
&& (line n' jl') == case compare (Size n') (size jl') of
LT -> Just "YAY"
_ -> Nothing)
| null | https://raw.githubusercontent.com/fp-works/2019-winter-Haskell-school/823b67f019b9e7bc0d3be36711c0cc7da4eba7d2/cis194/week7/zhansongl/TestJoinList.hs | haskell | need safe | import JoinList
import Sized
import Scrabble
import Buffer
import Control.Applicative (liftA2)
import Data.Monoid
import Safe
import Test.Hspec
import Test.QuickCheck
instance (Monoid m, Arbitrary a, Arbitrary m) => Arbitrary (JoinList m a) where
arbitrary = sized arbitraryJoinList
arbitraryJoinList :: (Monoid m, Arbitrary m, Arbitrary a) => Int -> Gen (JoinList m a)
arbitraryJoinList 0 = pure Empty
arbitraryJoinList n = do
m <- arbitrary
a <- arbitrary
oneof [pure $ Single m a, liftA2 (+++) sublist sublist]
where sublist = arbitraryJoinList (n `div` 2)
validTags :: (Eq m, Monoid m) => (JoinList m a) -> Bool
validTags Empty = True
validTags (Single _ _) = True
validTags (Append m l1 l2) = m == (tag l1 <> tag l2)
validSize :: (Sized m) => (JoinList m a) -> Bool
validSize Empty = True
validSize (Single s _) = size s == Size 1
validSize (Append s l1 l2) =
size s == size l1 + size l2 && validSize l1 && validSize l2
replaceTagWithSize :: JoinList m a -> JoinList Size a
replaceTagWithSize Empty = Empty
replaceTagWithSize (Single _ a) = Single (Size 1) a
replaceTagWithSize (Append _ l1 l2) = l1' +++ l2'
where l1' = replaceTagWithSize l1
l2' = replaceTagWithSize l2
main :: IO ()
main = hspec $ do
describe "+++" $ do
it "should produce JoinList that has valid tags" $ property $
forAll (arbitrary :: Gen (JoinList (Sum Int) Char)) validTags
describe "indexJ" $ do
it "should produce data at the correct index" $ property $
forAll (arbitrary :: Gen (JoinList (Sum Int) Char, Small Int))
(\(l, i) -> let l' = replaceTagWithSize l
i' = getSmall i
in (indexJ i' l') == (jlToList l' `atMay` i'))
describe "dropJ" $ do
it "should drop exactly n number of elements at the beginning" $ property $
forAll (arbitrary :: Gen (JoinList (Sum Int) Char, Positive (Small Int)))
(\(l, n) -> let n' = getSmall . getPositive $ n
l' = dropJ n' . replaceTagWithSize $ l
in jlToList l' == drop n' (jlToList l) && validSize l')
it "can drop everything in the left sublist correctly" $ do
(jlToList . dropJ 1 $
(Append (Size 2) (Single (Size 1) 'a') (Single 1 'b')))
`shouldBe` "b"
describe "takeJ" $ do
it "should take exactly n number of elements at the beginning" $ property $
forAll (arbitrary :: Gen (JoinList (Sum Int) Char, Positive (Small Int)))
(\(l, n) -> let n' = getSmall . getPositive $ n
l' = takeJ n' . replaceTagWithSize $ l
in jlToList l' == take n' (jlToList l) && validSize l')
it "can take everything in the left sublist correctly" $ do
(jlToList . takeJ 1 $
(Append (Size 2) (Single (Size 1) 'a') (Single 1 'b')))
`shouldBe` "a"
describe "scoreLine" $ do
it "should return correct scrabble scores" $ do
scoreLine "yay " `shouldBe` (Single (Score 9) "yay ")
scoreLine "haskell!" `shouldBe` (Single (Score 14) "haskell!")
describe "Score" $ do
it "should yield correct scrabble score when joined with (+++)" $ do
scoreLine "yay " +++ scoreLine "haskell!"
`shouldBe` Append (Score 23)
(Single (Score 9) "yay ")
(Single (Score 14) "haskell!")
describe "Buffer JoinList" $ do
it "should satisfy: toString . fromString == id" $ do
forAll (arbitrary :: Gen [String])
(\xs -> let s = unlines xs
jl = (fromString s) :: JoinList (Score, Size) String
in toString jl == s)
it "should replace line given valid index" $ do
forAll (arbitrary :: Gen ([String], NonNegative Int))
(\(xs,n) -> let s = unlines xs
jl = (fromString s) :: JoinList (Score, Size) String
n' = getNonNegative n
jl' = replaceLine n' "YAY" jl
in size jl == size jl'
&& (line n' jl') == case compare (Size n') (size jl') of
LT -> Just "YAY"
_ -> Nothing)
|
53ab125ad665067020dc6ddcfee0ed03fcfba4416d2de6123717d0baf307775c | mbj/stratosphere | StoppingConditionProperty.hs | module Stratosphere.SageMaker.ModelBiasJobDefinition.StoppingConditionProperty (
StoppingConditionProperty(..), mkStoppingConditionProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data StoppingConditionProperty
= StoppingConditionProperty {maxRuntimeInSeconds :: (Value Prelude.Integer)}
mkStoppingConditionProperty ::
Value Prelude.Integer -> StoppingConditionProperty
mkStoppingConditionProperty maxRuntimeInSeconds
= StoppingConditionProperty
{maxRuntimeInSeconds = maxRuntimeInSeconds}
instance ToResourceProperties StoppingConditionProperty where
toResourceProperties StoppingConditionProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::ModelBiasJobDefinition.StoppingCondition",
supportsTags = Prelude.False,
properties = ["MaxRuntimeInSeconds" JSON..= maxRuntimeInSeconds]}
instance JSON.ToJSON StoppingConditionProperty where
toJSON StoppingConditionProperty {..}
= JSON.object ["MaxRuntimeInSeconds" JSON..= maxRuntimeInSeconds]
instance Property "MaxRuntimeInSeconds" StoppingConditionProperty where
type PropertyType "MaxRuntimeInSeconds" StoppingConditionProperty = Value Prelude.Integer
set newValue StoppingConditionProperty {}
= StoppingConditionProperty {maxRuntimeInSeconds = newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/ModelBiasJobDefinition/StoppingConditionProperty.hs | haskell | module Stratosphere.SageMaker.ModelBiasJobDefinition.StoppingConditionProperty (
StoppingConditionProperty(..), mkStoppingConditionProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data StoppingConditionProperty
= StoppingConditionProperty {maxRuntimeInSeconds :: (Value Prelude.Integer)}
mkStoppingConditionProperty ::
Value Prelude.Integer -> StoppingConditionProperty
mkStoppingConditionProperty maxRuntimeInSeconds
= StoppingConditionProperty
{maxRuntimeInSeconds = maxRuntimeInSeconds}
instance ToResourceProperties StoppingConditionProperty where
toResourceProperties StoppingConditionProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::ModelBiasJobDefinition.StoppingCondition",
supportsTags = Prelude.False,
properties = ["MaxRuntimeInSeconds" JSON..= maxRuntimeInSeconds]}
instance JSON.ToJSON StoppingConditionProperty where
toJSON StoppingConditionProperty {..}
= JSON.object ["MaxRuntimeInSeconds" JSON..= maxRuntimeInSeconds]
instance Property "MaxRuntimeInSeconds" StoppingConditionProperty where
type PropertyType "MaxRuntimeInSeconds" StoppingConditionProperty = Value Prelude.Integer
set newValue StoppingConditionProperty {}
= StoppingConditionProperty {maxRuntimeInSeconds = newValue, ..} | |
e612d3b950c7e1a8f2010369cf24c284f5cf0626234a612064c7ae8200087937 | unison-code/unison | InstructionTypeGen.hs | |
Copyright : Copyright ( c ) 2016 , RISE SICS AB
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2016, RISE SICS AB
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
This file is part of Unison , see -code.github.io
Main authors:
Roberto Castaneda Lozano <>
This file is part of Unison, see -code.github.io
-}
module SpecsGen.InstructionTypeGen (emitInstructionType) where
import SpecsGen.SimpleYaml
import SpecsGen.HsGen
emitInstructionType targetName is =
let us2ids = infoToIds iType is
rhss = map (mkOpcRhs idToHsCon toInstructionTypeRhs) us2ids
in [hsModule
(moduleName targetName "InstructionType")
(Just [hsExportVar "instructionType"])
[unisonImport, instructionDeclImport targetName]
[simpleOpcFunBind "instructionType" rhss]]
toInstructionTypeRhs = toHsCon . toInstructionType
toInstructionType t = toOpType t ++ "InstructionType"
| null | https://raw.githubusercontent.com/unison-code/unison/9f8caf78230f956a57b50a327f8d1dca5839bf64/src/unison-specsgen/src/SpecsGen/InstructionTypeGen.hs | haskell | |
Copyright : Copyright ( c ) 2016 , RISE SICS AB
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2016, RISE SICS AB
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
This file is part of Unison , see -code.github.io
Main authors:
Roberto Castaneda Lozano <>
This file is part of Unison, see -code.github.io
-}
module SpecsGen.InstructionTypeGen (emitInstructionType) where
import SpecsGen.SimpleYaml
import SpecsGen.HsGen
emitInstructionType targetName is =
let us2ids = infoToIds iType is
rhss = map (mkOpcRhs idToHsCon toInstructionTypeRhs) us2ids
in [hsModule
(moduleName targetName "InstructionType")
(Just [hsExportVar "instructionType"])
[unisonImport, instructionDeclImport targetName]
[simpleOpcFunBind "instructionType" rhss]]
toInstructionTypeRhs = toHsCon . toInstructionType
toInstructionType t = toOpType t ++ "InstructionType"
| |
23568497e2c39b181bca68b965f109efb2cd36fe9a093285274b0d99a343aa3d | yetanalytics/dave | common_test.cljc | (ns com.yetanalytics.dave.func.common-test
(:require
[clojure.test #?(:cljs :refer-macros
:clj :refer) [deftest is testing]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as stest]
clojure.test.check.generators
[com.yetanalytics.dave.func.common :as common]
[com.yetanalytics.dave.test-support :refer [failures stc-opts]]))
(deftest scale-test
(is (empty?
(failures
(stest/check `common/scale)))))
(deftest get-helper-test
(is (empty?
(failures
(stest/check
`common/get-helper
{stc-opts
{:num-tests 10}})))))
(deftest get-ifi-test
(is (empty?
(failures
(stest/check
`common/get-ifi
{stc-opts
{:num-tests 10}})))))
(deftest get-lmap-val-test
(is (empty?
(failures
(stest/check
`common/get-lmap-val
{stc-opts
{:num-tests 10}})))))
(deftest parse-agent-test
(is (empty?
(failures
(stest/check
`common/parse-agent
{stc-opts
{:num-tests 10}})))))
(deftest parse-group-test
(is (empty?
(failures
(stest/check
`common/parse-group
{stc-opts
{:num-tests 10}})))))
(deftest parse-activity-test
(is (empty?
(failures
(stest/check
`common/parse-activity
{stc-opts
{:num-tests 10}})))))
(deftest parse-actor-test
(is (empty?
(failures
(stest/check
`common/parse-actor
{stc-opts
{:num-tests 10}})))))
(deftest parse-verb-test
(is (empty?
(failures
(stest/check
`common/parse-verb
{stc-opts
{:num-tests 10}})))))
(deftest parse-object-test
(is (empty?
(failures
(stest/check
`common/parse-object
{stc-opts
{:num-tests 10}})))))
(deftest parse-statement-simple-test
(is (empty?
(failures
(stest/check
`common/parse-statement-simple
{stc-opts
{:num-tests 10}})))))
(deftest handle-actor-test
(is (empty?
(failures
(stest/check
`common/handle-actor
{stc-opts
{:num-tests 10}})))))
(deftest handle-object-test
(is (empty?
(failures
(stest/check
`common/handle-object
{stc-opts
{:num-tests 10}})))))
| null | https://raw.githubusercontent.com/yetanalytics/dave/7a71c2017889862b2fb567edc8196b4382d01beb/test/com/yetanalytics/dave/func/common_test.cljc | clojure | (ns com.yetanalytics.dave.func.common-test
(:require
[clojure.test #?(:cljs :refer-macros
:clj :refer) [deftest is testing]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as stest]
clojure.test.check.generators
[com.yetanalytics.dave.func.common :as common]
[com.yetanalytics.dave.test-support :refer [failures stc-opts]]))
(deftest scale-test
(is (empty?
(failures
(stest/check `common/scale)))))
(deftest get-helper-test
(is (empty?
(failures
(stest/check
`common/get-helper
{stc-opts
{:num-tests 10}})))))
(deftest get-ifi-test
(is (empty?
(failures
(stest/check
`common/get-ifi
{stc-opts
{:num-tests 10}})))))
(deftest get-lmap-val-test
(is (empty?
(failures
(stest/check
`common/get-lmap-val
{stc-opts
{:num-tests 10}})))))
(deftest parse-agent-test
(is (empty?
(failures
(stest/check
`common/parse-agent
{stc-opts
{:num-tests 10}})))))
(deftest parse-group-test
(is (empty?
(failures
(stest/check
`common/parse-group
{stc-opts
{:num-tests 10}})))))
(deftest parse-activity-test
(is (empty?
(failures
(stest/check
`common/parse-activity
{stc-opts
{:num-tests 10}})))))
(deftest parse-actor-test
(is (empty?
(failures
(stest/check
`common/parse-actor
{stc-opts
{:num-tests 10}})))))
(deftest parse-verb-test
(is (empty?
(failures
(stest/check
`common/parse-verb
{stc-opts
{:num-tests 10}})))))
(deftest parse-object-test
(is (empty?
(failures
(stest/check
`common/parse-object
{stc-opts
{:num-tests 10}})))))
(deftest parse-statement-simple-test
(is (empty?
(failures
(stest/check
`common/parse-statement-simple
{stc-opts
{:num-tests 10}})))))
(deftest handle-actor-test
(is (empty?
(failures
(stest/check
`common/handle-actor
{stc-opts
{:num-tests 10}})))))
(deftest handle-object-test
(is (empty?
(failures
(stest/check
`common/handle-object
{stc-opts
{:num-tests 10}})))))
| |
d7270b3c7bff80acb1a28655b488178d95b86bb4d1166a6a5319bf9a23ecdc3b | cubicle-model-checker/cubicle | polynome.ml | (**************************************************************************)
(* *)
Cubicle
(* *)
Copyright ( C ) 2011 - 2014
(* *)
and
Universite Paris - Sud 11
(* *)
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(**************************************************************************)
open Format
open Num
exception Not_a_num
exception Maybe_zero
module type S = sig
type r
val compare : r -> r -> int
val term_embed : Term.t -> r
val mult : r -> r -> r
val print : Format.formatter -> r -> unit
end
module type T = sig
type r
type t
val compare : t -> t -> int
val hash : t -> int
val create : (num * r) list -> num -> Ty.t-> t
val add : t -> t -> t
val sub : t -> t -> t
val mult : t -> t -> t
val mult_const : num -> t -> t
val div : t -> t -> t * bool
val modulo : t -> t -> t
val is_empty : t -> bool
val find : r -> t -> num
val choose : t -> num * r
val subst : r -> t -> t -> t
val remove : r -> t -> t
val to_list : t -> (num * r) list * num
val print : Format.formatter -> t -> unit
val type_info : t -> Ty.t
val is_monomial : t -> (num * r * num) option
val ppmc_denominators : t -> num
val pgcd_numerators : t -> num
val normal_form : t -> t * num * num
val normal_form_pos : t -> t * num * num
end
module Make (X : S) = struct
type r = X.r
module M : Map.S with type key = r =
Map.Make(struct type t = r let compare x y = X.compare y x end)
type t = { m : num M.t; c : num; ty : Ty.t }
let compare p1 p2 =
let c = Ty.compare p1.ty p2.ty in
if c <> 0 then c
else
let c = compare_num p1.c p2.c in
if c = 0 then M.compare compare_num p1.m p2.m else c
let hash p =
abs (Hashtbl.hash p.m + 19*Hashtbl.hash p.c + 17 * Ty.hash p.ty)
let pprint fmt p =
M.iter
(fun x n ->
let s, n, op = match n with
| Int 1 -> "+", "", ""
| Int -1 -> "-", "", ""
| n ->
if n >/ Int 0 then "+", string_of_num n, "*"
else "-", string_of_num (minus_num n), "*"
in
fprintf fmt "%s%s%s%a" s n op X.print x
)p.m;
let s, n = if p.c >=/ Int 0 then "+", string_of_num p.c
else "-", string_of_num (minus_num p.c) in
fprintf fmt "%s%s" s n
let print fmt p =
M.iter
(fun t n -> fprintf fmt "%s*%a " (string_of_num n) X.print t) p.m;
fprintf fmt "%s" (string_of_num p.c);
fprintf fmt " [%a]" Ty.print p.ty
let is_num p = M.is_empty p.m
let find x m = try M.find x m with Not_found -> Int 0
let create l c ty =
let m =
List.fold_left
(fun m (n, x) ->
let n' = n +/ (find x m) in
if n' =/ (Int 0) then M.remove x m else M.add x n' m) M.empty l
in
{ m = m; c = c; ty = ty }
let add p1 p2 =
let m =
M.fold
(fun x a m ->
let a' = (find x m) +/ a in
if a' =/ (Int 0) then M.remove x m else M.add x a' m)
p2.m p1.m
in
{ m = m; c = p1.c +/ p2.c; ty = p1.ty }
let mult_const n p =
if n =/ (Int 0) then { m = M.empty; c = Int 0; ty = p.ty }
else { p with m = M.map (mult_num n) p.m; c = n */ p.c }
let mult_monome a x p =
let ax = { m = M.add x a M.empty; c = (Int 0); ty = p.ty} in
let acx = mult_const p.c ax in
let m =
M.fold
(fun xi ai m -> M.add (X.mult x xi) (a */ ai) m) p.m acx.m
in
{ acx with m = m}
let mult p1 p2 =
let p = mult_const p1.c p2 in
M.fold (fun x a p -> add (mult_monome a x p2) p) p1.m p
let sub p1 p2 =
add p1 (mult (create [] (Int (-1)) p1.ty) p2)
let div p1 p2 =
if M.is_empty p2.m then
if p2.c =/ Int 0 then raise Division_by_zero
else
let p = mult_const ((Int 1) // p2.c) p1 in
match M.is_empty p.m, p.ty with
| true, Ty.Tint -> {p with c = floor_num p.c}, false
| true, Ty.Treal -> p, false
| false, Ty.Tint -> p, true
| false, Ty.Treal -> p, false
| _ -> assert false
else raise Maybe_zero
let modulo p1 p2 =
if M.is_empty p2.m then
if p2.c =/ Int 0 then raise Division_by_zero
else
if M.is_empty p1.m then { p1 with c = mod_num p1.c p2.c }
else raise Not_a_num
else raise Maybe_zero
let find x p = M.find x p.m
let is_empty p = M.is_empty p.m
let choose p =
let tn= ref None in
(*version I : prend le premier element de la table*)
(try M.iter
(fun x a -> tn := Some (a, x); raise Exit) p.m with Exit -> ());
version II : prend le dernier element de la table i.e. le plus grand
M.iter ( fun x a - > tn : = Some ( a , x ) ) p.m ;
M.iter (fun x a -> tn := Some (a, x)) p.m;*)
match !tn with Some p -> p | _ -> raise Not_found
let subst x p1 p2 =
try
let a = M.find x p2.m in
add (mult_const a p1) { p2 with m = M.remove x p2.m}
with Not_found -> p2
let remove x p = { p with m = M.remove x p.m }
let to_list p =
let l = M.fold (fun x a aliens -> (a, x)::aliens ) p.m [] in
List.rev l, p.c
let type_info p = p.ty
let is_monomial p =
try
M.fold
(fun x a r ->
match r with
| None -> Some (a, x, p.c)
| _ -> raise Exit)
p.m None
with Exit -> None
let denominator = function
| Num.Int _ | Num.Big_int _ -> Big_int.unit_big_int
| Num.Ratio rat -> Ratio.denominator_ratio rat
let numerator = function
| Num.Int i -> Big_int.big_int_of_int i
| Num.Big_int b -> b
| Num.Ratio rat -> Ratio.numerator_ratio rat
let pgcd_bi a b = Big_int.gcd_big_int a b
let ppmc_bi a b = Big_int.div_big_int (Big_int.mult_big_int a b) (pgcd_bi a b)
let abs_big_int_to_num b =
let b =
try Int (Big_int.int_of_big_int b)
with Failure _ -> Big_int b
in
abs_num b
let ppmc_denominators {m=m} =
let res =
M.fold
(fun k c acc -> ppmc_bi (denominator c) acc)
m Big_int.unit_big_int in
abs_num (num_of_big_int res)
let pgcd_numerators {m=m} =
let res =
M.fold
(fun k c acc -> pgcd_bi (numerator c) acc)
m Big_int.zero_big_int in
abs_num (num_of_big_int res)
let normal_form ({ m = m; c = c } as p) =
if M.is_empty m then
{ p with c = Int 0 }, p.c, (Int 1)
else
let ppcm = ppmc_denominators p in
let pgcd = pgcd_numerators p in
let p = mult_const (ppcm // pgcd) p in
{ p with c = Int 0 }, p.c, (pgcd // ppcm)
let normal_form_pos p =
let p, c, d = normal_form p in
try
let a,x = choose p in
if a >/ (Int 0) then p, c, d
else mult_const (Int (-1)) p, minus_num c, minus_num d
with Not_found -> p, c, d
end
| null | https://raw.githubusercontent.com/cubicle-model-checker/cubicle/00f09bb2d4bb496549775e770d7ada08bc1e4866/smt/polynome.ml | ocaml | ************************************************************************
License version 2.0
************************************************************************
version I : prend le premier element de la table | Cubicle
Copyright ( C ) 2011 - 2014
and
Universite Paris - Sud 11
This file is distributed under the terms of the Apache Software
open Format
open Num
exception Not_a_num
exception Maybe_zero
module type S = sig
type r
val compare : r -> r -> int
val term_embed : Term.t -> r
val mult : r -> r -> r
val print : Format.formatter -> r -> unit
end
module type T = sig
type r
type t
val compare : t -> t -> int
val hash : t -> int
val create : (num * r) list -> num -> Ty.t-> t
val add : t -> t -> t
val sub : t -> t -> t
val mult : t -> t -> t
val mult_const : num -> t -> t
val div : t -> t -> t * bool
val modulo : t -> t -> t
val is_empty : t -> bool
val find : r -> t -> num
val choose : t -> num * r
val subst : r -> t -> t -> t
val remove : r -> t -> t
val to_list : t -> (num * r) list * num
val print : Format.formatter -> t -> unit
val type_info : t -> Ty.t
val is_monomial : t -> (num * r * num) option
val ppmc_denominators : t -> num
val pgcd_numerators : t -> num
val normal_form : t -> t * num * num
val normal_form_pos : t -> t * num * num
end
module Make (X : S) = struct
type r = X.r
module M : Map.S with type key = r =
Map.Make(struct type t = r let compare x y = X.compare y x end)
type t = { m : num M.t; c : num; ty : Ty.t }
let compare p1 p2 =
let c = Ty.compare p1.ty p2.ty in
if c <> 0 then c
else
let c = compare_num p1.c p2.c in
if c = 0 then M.compare compare_num p1.m p2.m else c
let hash p =
abs (Hashtbl.hash p.m + 19*Hashtbl.hash p.c + 17 * Ty.hash p.ty)
let pprint fmt p =
M.iter
(fun x n ->
let s, n, op = match n with
| Int 1 -> "+", "", ""
| Int -1 -> "-", "", ""
| n ->
if n >/ Int 0 then "+", string_of_num n, "*"
else "-", string_of_num (minus_num n), "*"
in
fprintf fmt "%s%s%s%a" s n op X.print x
)p.m;
let s, n = if p.c >=/ Int 0 then "+", string_of_num p.c
else "-", string_of_num (minus_num p.c) in
fprintf fmt "%s%s" s n
let print fmt p =
M.iter
(fun t n -> fprintf fmt "%s*%a " (string_of_num n) X.print t) p.m;
fprintf fmt "%s" (string_of_num p.c);
fprintf fmt " [%a]" Ty.print p.ty
let is_num p = M.is_empty p.m
let find x m = try M.find x m with Not_found -> Int 0
let create l c ty =
let m =
List.fold_left
(fun m (n, x) ->
let n' = n +/ (find x m) in
if n' =/ (Int 0) then M.remove x m else M.add x n' m) M.empty l
in
{ m = m; c = c; ty = ty }
let add p1 p2 =
let m =
M.fold
(fun x a m ->
let a' = (find x m) +/ a in
if a' =/ (Int 0) then M.remove x m else M.add x a' m)
p2.m p1.m
in
{ m = m; c = p1.c +/ p2.c; ty = p1.ty }
let mult_const n p =
if n =/ (Int 0) then { m = M.empty; c = Int 0; ty = p.ty }
else { p with m = M.map (mult_num n) p.m; c = n */ p.c }
let mult_monome a x p =
let ax = { m = M.add x a M.empty; c = (Int 0); ty = p.ty} in
let acx = mult_const p.c ax in
let m =
M.fold
(fun xi ai m -> M.add (X.mult x xi) (a */ ai) m) p.m acx.m
in
{ acx with m = m}
let mult p1 p2 =
let p = mult_const p1.c p2 in
M.fold (fun x a p -> add (mult_monome a x p2) p) p1.m p
let sub p1 p2 =
add p1 (mult (create [] (Int (-1)) p1.ty) p2)
let div p1 p2 =
if M.is_empty p2.m then
if p2.c =/ Int 0 then raise Division_by_zero
else
let p = mult_const ((Int 1) // p2.c) p1 in
match M.is_empty p.m, p.ty with
| true, Ty.Tint -> {p with c = floor_num p.c}, false
| true, Ty.Treal -> p, false
| false, Ty.Tint -> p, true
| false, Ty.Treal -> p, false
| _ -> assert false
else raise Maybe_zero
let modulo p1 p2 =
if M.is_empty p2.m then
if p2.c =/ Int 0 then raise Division_by_zero
else
if M.is_empty p1.m then { p1 with c = mod_num p1.c p2.c }
else raise Not_a_num
else raise Maybe_zero
let find x p = M.find x p.m
let is_empty p = M.is_empty p.m
let choose p =
let tn= ref None in
(try M.iter
(fun x a -> tn := Some (a, x); raise Exit) p.m with Exit -> ());
version II : prend le dernier element de la table i.e. le plus grand
M.iter ( fun x a - > tn : = Some ( a , x ) ) p.m ;
M.iter (fun x a -> tn := Some (a, x)) p.m;*)
match !tn with Some p -> p | _ -> raise Not_found
let subst x p1 p2 =
try
let a = M.find x p2.m in
add (mult_const a p1) { p2 with m = M.remove x p2.m}
with Not_found -> p2
let remove x p = { p with m = M.remove x p.m }
let to_list p =
let l = M.fold (fun x a aliens -> (a, x)::aliens ) p.m [] in
List.rev l, p.c
let type_info p = p.ty
let is_monomial p =
try
M.fold
(fun x a r ->
match r with
| None -> Some (a, x, p.c)
| _ -> raise Exit)
p.m None
with Exit -> None
let denominator = function
| Num.Int _ | Num.Big_int _ -> Big_int.unit_big_int
| Num.Ratio rat -> Ratio.denominator_ratio rat
let numerator = function
| Num.Int i -> Big_int.big_int_of_int i
| Num.Big_int b -> b
| Num.Ratio rat -> Ratio.numerator_ratio rat
let pgcd_bi a b = Big_int.gcd_big_int a b
let ppmc_bi a b = Big_int.div_big_int (Big_int.mult_big_int a b) (pgcd_bi a b)
let abs_big_int_to_num b =
let b =
try Int (Big_int.int_of_big_int b)
with Failure _ -> Big_int b
in
abs_num b
let ppmc_denominators {m=m} =
let res =
M.fold
(fun k c acc -> ppmc_bi (denominator c) acc)
m Big_int.unit_big_int in
abs_num (num_of_big_int res)
let pgcd_numerators {m=m} =
let res =
M.fold
(fun k c acc -> pgcd_bi (numerator c) acc)
m Big_int.zero_big_int in
abs_num (num_of_big_int res)
let normal_form ({ m = m; c = c } as p) =
if M.is_empty m then
{ p with c = Int 0 }, p.c, (Int 1)
else
let ppcm = ppmc_denominators p in
let pgcd = pgcd_numerators p in
let p = mult_const (ppcm // pgcd) p in
{ p with c = Int 0 }, p.c, (pgcd // ppcm)
let normal_form_pos p =
let p, c, d = normal_form p in
try
let a,x = choose p in
if a >/ (Int 0) then p, c, d
else mult_const (Int (-1)) p, minus_num c, minus_num d
with Not_found -> p, c, d
end
|
5e99010fb444c7f3b9fafcf832198ae028a946d1762100359cf621d19b7edacf | ShiiVa03/LI1 | Tarefa1_2019li1g050.hs | | Este módulo define do trabalho prático .
module Tarefa1_2019li1g050 where
import LI11920
import System.Random
-- * Testes
-- | Testes unitários da Tarefa 1.
--
Cada teste é um ( /número de ' Pista's/,/comprimento de cada ' Pista ' do ' aleatoriedades/ ) .
testesT1 :: [(Int,Int,Int)]
testesT1 = [(5,10,1),(1,1,2),(10,10,12366),(5,5,6),(5,5,0),(1,10,13)]
* .
| Função que gera aleatórios necessários para a construção do ' ' .
geraAleatorios :: Int -> Int -> [Int]
geraAleatorios n seed = take n (randomRs (0,9) (mkStdGen seed))
* Funções principais da Tarefa 1 .
| Função que dado um número de pistas , um comprimento e , cria um ' ' .
gera :: Int -> Int -> Int -> Mapa
gera npistas comprimento semente = adicionaPrimeiraPeca(geraMapa comprimento npistas (geraPares(separaPistas comprimento (geraAleatorios elementos semente))))
where elementos = ((npistas * comprimento) * 2) - (npistas * 2)
| Separa uma lista equitativamente .
Esta função é necessária de peças a .
Esta função é necessária para determinar corretamento o número de peças a serem criadas.
-}
separaPistas :: Int -> [Int] -> [[Int]]
separaPistas comprimento [] = []
separaPistas comprimento l@( h : t ) = l1 : separaPistas comprimento l2
where (l1,l2) = splitAt elemetos l
elemetos = (comprimento - 1) * 2
| Função que dada uma matriz dá uma matriz de pares ordenados .
geraPares :: [[Int]] -> [[(Int,Int)]]
geraPares [] = []
geraPares m = map geraPares' m
| Função que gera um ' ' dado um Pista ' , o número de ' Pista 's e uma matriz de pares ordenados .
esta função é à função _ _ _ _ , , a função _ _ GeraMapa _ _ é uma função genérica , ou seja , dados uns valores Mapa ' , ao contrário da função _ _ _ _ que depende dos aleatórios .
De notar que esta função é muito parecida à função __Gera__, porém , a função __GeraMapa__ é uma função genérica , ou seja, dados uns valores ela converte num 'Mapa', ao contrário da função __Gera__ que depende dos números aleatórios.
-}
geraMapa :: Int -> Int -> [[(Int,Int)]] -> Mapa
geraMapa 1 npistas l = geraVazia npistas
geraMapa comprimento npistas l = map (geraPista (Recta Terra 0)) l
| Função que cria uma ' Pista ' , dada uma ' ' anterior e uma lista de pares ordenados .
geraPista :: Peca -> [(Int,Int)] -> [Peca]
geraPista peca [] = []
geraPista peca (h:t) = (geraPeca peca h) : geraPista (geraPeca peca h) t
| Função que cria uma ' ' , dada uma ' ' anterior e um par ordenado .
geraPeca :: Peca -> (Int,Int) -> Peca
geraPeca (Recta piso altura) (x,y) = geraTipo altura (geraPiso piso x) y
geraPeca (Rampa piso alturaI alturaF) (x,y) = geraTipo alturaF (geraPiso piso x) y
-- | Função que determina o 'Piso'.
geraPiso :: Piso -> Int -> Piso
geraPiso pisoAnterior gama | 0 <= gama && gama <= 1 = Terra
| 2 <= gama && gama <= 3 = Relva
| gama == 4 = Lama
| gama == 5 = Boost
| 6 <= gama && gama <= 9 = pisoAnterior
|Função que contrói uma ' '
^ anterior
^
-> Int -- ^ Gama
^ com os argumentos anteriores
geraTipo alturaAnterior pisoAtual gama | 0 <= gama && gama <= 1 = constroiPecaSobe alturaAnterior (gama+1) pisoAtual
| 2 <= gama && gama <= 5 = constroiPecaDesce alturaAnterior (gama-1) pisoAtual
| 6 <= gama && gama <= 9 = (Recta pisoAtual alturaAnterior)
-- * Funções auxiliares da Tarefa 1
| Função que dada uma lista de inteiros cria uma lista de pares odenados .
geraPares' :: [Int] -> [(Int,Int)]
geraPares' [] = []
geraPares' (h : h2 : t) = (h,h2) : geraPares' t
| Função auxiliar que cria uma ' ' de declive _ _ positivo _ _ .
constroiPecaSobe :: Int -> Int -> Piso -> Peca
constroiPecaSobe alturaAnterior diferenca piso = (Rampa piso alturaAnterior (alturaAnterior+diferenca))
| Função auxiliar que cria uma ' ' de declive _ _ negativo _ _ .
constroiPecaDesce :: Int -> Int -> Piso -> Peca
constroiPecaDesce alturaAnterior diferenca piso | alturaAnterior - diferenca <= 0 = rectaOuRampa alturaAnterior diferenca piso
| otherwise = (Rampa piso alturaAnterior (alturaAnterior-diferenca))
|Função que auxilia na criação de uma ' ' ou ' Recta ' .
rectaOuRampa :: Int -> Int -> Piso -> Peca
rectaOuRampa alturaAnterior diferenca piso | alturaAnterior == 0 = (Recta piso 0)
| otherwise = (Rampa piso alturaAnterior 0)
| Função que garante que a primeira ' ' do ' ' é sempre /Recta Terra 0/.
adicionaPrimeiraPeca :: Mapa -> Mapa
adicionaPrimeiraPeca mapa = map ((Recta Terra 0):) mapa
| Função que cria um ' ' com só _ _ 1 _ _ de /comprimento/.
geraVazia :: Int -> [[a]]
geraVazia pistas | pistas /= 0 = [] : geraVazia (pistas-1)
| otherwise = [] | null | https://raw.githubusercontent.com/ShiiVa03/LI1/d75ede3d319a14d7729d34c47daffe12906fe4dd/Tarefa1_2019li1g050.hs | haskell | * Testes
| Testes unitários da Tarefa 1.
| Função que determina o 'Piso'.
^ Gama
* Funções auxiliares da Tarefa 1 | | Este módulo define do trabalho prático .
module Tarefa1_2019li1g050 where
import LI11920
import System.Random
Cada teste é um ( /número de ' Pista's/,/comprimento de cada ' Pista ' do ' aleatoriedades/ ) .
testesT1 :: [(Int,Int,Int)]
testesT1 = [(5,10,1),(1,1,2),(10,10,12366),(5,5,6),(5,5,0),(1,10,13)]
* .
| Função que gera aleatórios necessários para a construção do ' ' .
geraAleatorios :: Int -> Int -> [Int]
geraAleatorios n seed = take n (randomRs (0,9) (mkStdGen seed))
* Funções principais da Tarefa 1 .
| Função que dado um número de pistas , um comprimento e , cria um ' ' .
gera :: Int -> Int -> Int -> Mapa
gera npistas comprimento semente = adicionaPrimeiraPeca(geraMapa comprimento npistas (geraPares(separaPistas comprimento (geraAleatorios elementos semente))))
where elementos = ((npistas * comprimento) * 2) - (npistas * 2)
| Separa uma lista equitativamente .
Esta função é necessária de peças a .
Esta função é necessária para determinar corretamento o número de peças a serem criadas.
-}
separaPistas :: Int -> [Int] -> [[Int]]
separaPistas comprimento [] = []
separaPistas comprimento l@( h : t ) = l1 : separaPistas comprimento l2
where (l1,l2) = splitAt elemetos l
elemetos = (comprimento - 1) * 2
| Função que dada uma matriz dá uma matriz de pares ordenados .
geraPares :: [[Int]] -> [[(Int,Int)]]
geraPares [] = []
geraPares m = map geraPares' m
| Função que gera um ' ' dado um Pista ' , o número de ' Pista 's e uma matriz de pares ordenados .
esta função é à função _ _ _ _ , , a função _ _ GeraMapa _ _ é uma função genérica , ou seja , dados uns valores Mapa ' , ao contrário da função _ _ _ _ que depende dos aleatórios .
De notar que esta função é muito parecida à função __Gera__, porém , a função __GeraMapa__ é uma função genérica , ou seja, dados uns valores ela converte num 'Mapa', ao contrário da função __Gera__ que depende dos números aleatórios.
-}
geraMapa :: Int -> Int -> [[(Int,Int)]] -> Mapa
geraMapa 1 npistas l = geraVazia npistas
geraMapa comprimento npistas l = map (geraPista (Recta Terra 0)) l
| Função que cria uma ' Pista ' , dada uma ' ' anterior e uma lista de pares ordenados .
geraPista :: Peca -> [(Int,Int)] -> [Peca]
geraPista peca [] = []
geraPista peca (h:t) = (geraPeca peca h) : geraPista (geraPeca peca h) t
| Função que cria uma ' ' , dada uma ' ' anterior e um par ordenado .
geraPeca :: Peca -> (Int,Int) -> Peca
geraPeca (Recta piso altura) (x,y) = geraTipo altura (geraPiso piso x) y
geraPeca (Rampa piso alturaI alturaF) (x,y) = geraTipo alturaF (geraPiso piso x) y
geraPiso :: Piso -> Int -> Piso
geraPiso pisoAnterior gama | 0 <= gama && gama <= 1 = Terra
| 2 <= gama && gama <= 3 = Relva
| gama == 4 = Lama
| gama == 5 = Boost
| 6 <= gama && gama <= 9 = pisoAnterior
|Função que contrói uma ' '
^ anterior
^
^ com os argumentos anteriores
geraTipo alturaAnterior pisoAtual gama | 0 <= gama && gama <= 1 = constroiPecaSobe alturaAnterior (gama+1) pisoAtual
| 2 <= gama && gama <= 5 = constroiPecaDesce alturaAnterior (gama-1) pisoAtual
| 6 <= gama && gama <= 9 = (Recta pisoAtual alturaAnterior)
| Função que dada uma lista de inteiros cria uma lista de pares odenados .
geraPares' :: [Int] -> [(Int,Int)]
geraPares' [] = []
geraPares' (h : h2 : t) = (h,h2) : geraPares' t
| Função auxiliar que cria uma ' ' de declive _ _ positivo _ _ .
constroiPecaSobe :: Int -> Int -> Piso -> Peca
constroiPecaSobe alturaAnterior diferenca piso = (Rampa piso alturaAnterior (alturaAnterior+diferenca))
| Função auxiliar que cria uma ' ' de declive _ _ negativo _ _ .
constroiPecaDesce :: Int -> Int -> Piso -> Peca
constroiPecaDesce alturaAnterior diferenca piso | alturaAnterior - diferenca <= 0 = rectaOuRampa alturaAnterior diferenca piso
| otherwise = (Rampa piso alturaAnterior (alturaAnterior-diferenca))
|Função que auxilia na criação de uma ' ' ou ' Recta ' .
rectaOuRampa :: Int -> Int -> Piso -> Peca
rectaOuRampa alturaAnterior diferenca piso | alturaAnterior == 0 = (Recta piso 0)
| otherwise = (Rampa piso alturaAnterior 0)
| Função que garante que a primeira ' ' do ' ' é sempre /Recta Terra 0/.
adicionaPrimeiraPeca :: Mapa -> Mapa
adicionaPrimeiraPeca mapa = map ((Recta Terra 0):) mapa
| Função que cria um ' ' com só _ _ 1 _ _ de /comprimento/.
geraVazia :: Int -> [[a]]
geraVazia pistas | pistas /= 0 = [] : geraVazia (pistas-1)
| otherwise = [] |
86b7c7f47b66df316b58d7b836b11a049a53d63e9c7fc0e3bba4f57d25b88f65 | extend/elevators | e_graphic.erl | %%%----------------------------------------------------------------------
%%% File : e_graphic.erl
Author : >
%%% Purpose : Control process for the graphics of an elevator.
Created : 3 Aug 1999 by >
%%%----------------------------------------------------------------------
-module(e_graphic).
-author('').
-vsn("1.0").
-behaviour(gen_fsm).
%% External exports
-export([start_link/3]).
-export([open/1, close/1, stop/1, move/2, set_controller/2]).
-export([get_floor/3]).
%% gen_fsm callbacks
-export([init/1, open/2, closed/2, moving/2, stopping/2, handle_event/3,
handle_sync_event/4, handle_info/3, terminate/3, code_change/4]).
%%%----------------------------------------------------------------------
%%%
The graphical elevator is represented by an FSM with four states :
%%% open: Standing at a floor with the doors open
%%% closed: Standing at a floor with the doors closed
%%% moving: Moving
%%%
In addition to the state , the FSM has information about its position ,
%%% and the floor pixel coordinates in order to be able to detrmine when
%%% a floor is being approached/passed.
%%%
%%% The states, events and corresponding actions are:
%%%
%%%
%%% State | open | closed | moving | stopping
%%% Event | | | |
%%% -----------+--------------+--------------+---------------+--------------
open | N / A | Open doors | N / A | N / A
%%% | | -> open | |
%%% -----------+--------------+--------------+---------------+--------------
%%% close | Close doors | N/A | N/A | N/A
%%% | -> closed | | |
%%% -----------+--------------+--------------+---------------+--------------
%%% stop | N/A | N/A | Start stopping| N/A
%%% | | | -> stopping |
%%% -----------+--------------+--------------+---------------+--------------
{ move , / A | Start moving | N / A | N / A
%%% | | -> moving | |
%%% -----------+--------------+--------------+---------------+--------------
{ step , / A | N / A | take step | take step
%%% | | | check position| -> stopping
%%% | | | -> moving | -> closed
%%% -----------+--------------+--------------+---------------+--------------
%%% {epid, EP} | Set controlling process of elevator to EP
%%% -----------+--------------+--------------+---------------+--------------
%%%
%%%----------------------------------------------------------------------
%%%----------------------------------------------------------------------
%%% API
%%%----------------------------------------------------------------------
start_link(Pos, ElevG, Floors) ->
gen_fsm:start_link(e_graphic, [Pos, ElevG, Floors], []).
open(Elev) ->
gen_fsm:send_event(Elev, open).
close(Elev) ->
gen_fsm:send_event(Elev, close).
stop(Elev) ->
gen_fsm:send_event(Elev, stop).
move(Elev, Dir) ->
gen_fsm:send_event(Elev, {move, Dir}).
set_controller(Elev, EPid) ->
gen_fsm:send_all_state_event(Elev, {epid, EPid}).
%%%----------------------------------------------------------------------
%%% Callback functions from gen_fsm
%%%----------------------------------------------------------------------
init([Pos, ElevG, Floors]) ->
{ok, closed, {Pos, ElevG, nopid, nodir, Floors}}.
open(close, {Pos, ElevG, EPid, nodir, Floors}) ->
gs:config(ElevG, {fill, black}),
{next_state, closed, {Pos, ElevG, EPid, nodir, Floors}}.
closed(open, {Pos, ElevG, EPid, nodir, Floors}) ->
gs:config(ElevG, {fill, cyan}),
{next_state, open, {Pos, ElevG, EPid, nodir, Floors}};
closed({move, Dir}, {Pos, ElevG, EPid, nodir, Floors}) ->
gen_fsm:send_event(self(), {step, Dir}),
{next_state, moving, {Pos, ElevG, EPid, Dir, Floors}}.
moving({step, Dir}, {Pos, ElevG, EPid, Dir, Floors}) ->
Dy = dy(Dir),
NewPos = Pos + Dy,
gs:config(ElevG, {move, {0, Dy}}),
check_position(NewPos, Dir, EPid, Floors),
timer:apply_after(200, gen_fsm, send_event, [self(), {step, Dir}]),
{next_state, moving, {NewPos, ElevG, EPid, Dir, Floors}};
moving(stop, {Pos, ElevG, EPid, Dir, Floors}) ->
{next_state, stopping, {Pos, ElevG, EPid, Dir, Floors}}.
stopping({step, Dir}, {Pos, ElevG, EPid, Dir, Floors}) ->
case at_floor(Pos, Floors) of
false ->
Dy = dy(Dir),
NewPos = Pos + Dy,
gs:config(ElevG, {move, {0, Dy}}),
timer:apply_after(200, gen_fsm, send_event, [self(), {step, Dir}]),
{next_state, stopping, {NewPos, ElevG, EPid, Dir, Floors}};
{true, Floor} ->
elevator:at_floor(EPid, Floor),
{next_state, closed, {Pos, ElevG, EPid, nodir, Floors}}
end.
%%----------------------------------------------------------------------
%% Only all state event is to update the control process pid.
%%----------------------------------------------------------------------
handle_event({epid, EPid}, State, {Pos, ElevG, OldPid, Dir, Floors}) ->
elevator:reset(EPid, State, get_floor(Pos, Dir, Floors)),
{next_state, State, {Pos, ElevG, EPid, Dir, Floors}}.
%%----------------------------------------------------------------------
%% No sync events defined.
%%----------------------------------------------------------------------
handle_sync_event(Event, From, StateName, StateData) ->
Reply = ok,
{reply, Reply, StateName, StateData}.
%%----------------------------------------------------------------------
%% No info expected.
%%----------------------------------------------------------------------
handle_info(Info, StateName, StateData) ->
{next_state, StateName, StateData}.
%%----------------------------------------------------------------------
%% terminate has nothing to clean up.
%%----------------------------------------------------------------------
terminate(Reason, StateName, StatData) ->
ok.
%%----------------------------------------------------------------------
%% Code change is a no-op (no previous version exists).
%%----------------------------------------------------------------------
code_change(_OldVsn, State, Data, _Extra) ->
{ok, State, Data}.
%%%----------------------------------------------------------------------
Internal functions
%%%----------------------------------------------------------------------
%%----------------------------------------------------------------------
%% dy(Dir) -> int()
%% Dir = up | down
%%
%% Returns the y-offset to move the graphical elevator with when it's
travelling in the direction .
%%----------------------------------------------------------------------
dy(up) -> -10;
dy(down) -> 10.
%%----------------------------------------------------------------------
check_position(Pos , Dir , EPid , Floors )
%% Pos = int()
%% Dir = up | down
EPid = pid ( )
Floors = [ { FloorNo , YPos } , ... ]
%% FloorNo = int()
%% YPos = int()
%%
%% Checks whether an elevator at position Pos, travelling in the direction
dir is approaching a floor . If so , the elevator control process EPid
%% is informed.
%%----------------------------------------------------------------------
check_position(Pos, Dir, EPid, Floors) ->
case lists:keysearch(Pos + 2 * dy(Dir), 2, Floors) of
{value, {Floor, _}} ->
elevator:approaching(EPid, Floor);
_ ->
check_arrived(Pos, EPid, Floors)
end.
%%----------------------------------------------------------------------
check_arrived(Pos , EPid , Floors )
%% Pos = int()
EPid = pid ( )
Floors = [ { FloorNo , YPos } , ... ]
%% FloorNo = int()
%% YPos = int()
%%
%% Checks whether an elevator at position Pos is at a floor. If so, the
elevator control process EPid is informed .
%%----------------------------------------------------------------------
check_arrived(Pos, EPid, Floors) ->
case at_floor(Pos, Floors) of
{true, Floor} ->
elevator:at_floor(EPid, Floor);
false ->
ok
end.
%%----------------------------------------------------------------------
%% at_floor(Pos, Floors) -> {true, FloorNo} | false
%% Pos = int()
Floors = [ { FloorNo , YPos } , ... ]
%% FloorNo = int()
%% YPos = int()
%%
%% Checks whether an elevator at position Pos is at a floor.
%%----------------------------------------------------------------------
at_floor(Pos, Floors) ->
case lists:keysearch(Pos, 2, Floors) of
{value, {Floor, _}} ->
{true, Floor};
false ->
false
end.
%%----------------------------------------------------------------------
get_floor(Pos , , Floors ) - > FloorNo
%% Pos = int()
Dir = | up | down
Floors = [ { FloorNo , YPos } , ... ]
%% FloorNo = int()
%% YPos = int()
%%
%% Retrieves the last floor passed when the graphical elevator is at Pos,
travelling in the direction ( or standing still at a floor ) .
%%----------------------------------------------------------------------
get_floor(Pos, nodir, Floors) ->
{value, {Floor, _}} = lists:keysearch(Pos, 2, Floors),
Floor;
get_floor(Pos, up, Floors) ->
find(1, Pos, Floors, infinity, none);
get_floor(Pos, down, Floors) ->
find(-1, Pos, Floors, infinity, none).
find(Sign, Pos, [], Min, MinFloor) ->
MinFloor;
find(Sign, Pos, [{_F, Y} | Floors], Min, MinF) when Sign * (Y - Pos) < 0 ->
find(Sign, Pos, Floors, Min, MinF);
find(Sign, Pos, [{F, Y} | Floors], Min, _MinF) when Sign * (Y - Pos) < Min ->
find(Sign, Pos, Floors, Sign * (Y - Pos), F);
find(Sign, Pos, [{_F, _Y} | Floors], Min, MinF) ->
find(Sign, Pos, Floors, Min, MinF).
| null | https://raw.githubusercontent.com/extend/elevators/02276cc05da80017eea1691281fc062af62fa64a/src/e_graphic.erl | erlang | ----------------------------------------------------------------------
File : e_graphic.erl
Purpose : Control process for the graphics of an elevator.
----------------------------------------------------------------------
External exports
gen_fsm callbacks
----------------------------------------------------------------------
open: Standing at a floor with the doors open
closed: Standing at a floor with the doors closed
moving: Moving
and the floor pixel coordinates in order to be able to detrmine when
a floor is being approached/passed.
The states, events and corresponding actions are:
State | open | closed | moving | stopping
Event | | | |
-----------+--------------+--------------+---------------+--------------
| | -> open | |
-----------+--------------+--------------+---------------+--------------
close | Close doors | N/A | N/A | N/A
| -> closed | | |
-----------+--------------+--------------+---------------+--------------
stop | N/A | N/A | Start stopping| N/A
| | | -> stopping |
-----------+--------------+--------------+---------------+--------------
| | -> moving | |
-----------+--------------+--------------+---------------+--------------
| | | check position| -> stopping
| | | -> moving | -> closed
-----------+--------------+--------------+---------------+--------------
{epid, EP} | Set controlling process of elevator to EP
-----------+--------------+--------------+---------------+--------------
----------------------------------------------------------------------
----------------------------------------------------------------------
API
----------------------------------------------------------------------
----------------------------------------------------------------------
Callback functions from gen_fsm
----------------------------------------------------------------------
----------------------------------------------------------------------
Only all state event is to update the control process pid.
----------------------------------------------------------------------
----------------------------------------------------------------------
No sync events defined.
----------------------------------------------------------------------
----------------------------------------------------------------------
No info expected.
----------------------------------------------------------------------
----------------------------------------------------------------------
terminate has nothing to clean up.
----------------------------------------------------------------------
----------------------------------------------------------------------
Code change is a no-op (no previous version exists).
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
dy(Dir) -> int()
Dir = up | down
Returns the y-offset to move the graphical elevator with when it's
----------------------------------------------------------------------
----------------------------------------------------------------------
Pos = int()
Dir = up | down
FloorNo = int()
YPos = int()
Checks whether an elevator at position Pos, travelling in the direction
is informed.
----------------------------------------------------------------------
----------------------------------------------------------------------
Pos = int()
FloorNo = int()
YPos = int()
Checks whether an elevator at position Pos is at a floor. If so, the
----------------------------------------------------------------------
----------------------------------------------------------------------
at_floor(Pos, Floors) -> {true, FloorNo} | false
Pos = int()
FloorNo = int()
YPos = int()
Checks whether an elevator at position Pos is at a floor.
----------------------------------------------------------------------
----------------------------------------------------------------------
Pos = int()
FloorNo = int()
YPos = int()
Retrieves the last floor passed when the graphical elevator is at Pos,
----------------------------------------------------------------------
| Author : >
Created : 3 Aug 1999 by >
-module(e_graphic).
-author('').
-vsn("1.0").
-behaviour(gen_fsm).
-export([start_link/3]).
-export([open/1, close/1, stop/1, move/2, set_controller/2]).
-export([get_floor/3]).
-export([init/1, open/2, closed/2, moving/2, stopping/2, handle_event/3,
handle_sync_event/4, handle_info/3, terminate/3, code_change/4]).
The graphical elevator is represented by an FSM with four states :
In addition to the state , the FSM has information about its position ,
open | N / A | Open doors | N / A | N / A
{ move , / A | Start moving | N / A | N / A
{ step , / A | N / A | take step | take step
start_link(Pos, ElevG, Floors) ->
gen_fsm:start_link(e_graphic, [Pos, ElevG, Floors], []).
open(Elev) ->
gen_fsm:send_event(Elev, open).
close(Elev) ->
gen_fsm:send_event(Elev, close).
stop(Elev) ->
gen_fsm:send_event(Elev, stop).
move(Elev, Dir) ->
gen_fsm:send_event(Elev, {move, Dir}).
set_controller(Elev, EPid) ->
gen_fsm:send_all_state_event(Elev, {epid, EPid}).
init([Pos, ElevG, Floors]) ->
{ok, closed, {Pos, ElevG, nopid, nodir, Floors}}.
open(close, {Pos, ElevG, EPid, nodir, Floors}) ->
gs:config(ElevG, {fill, black}),
{next_state, closed, {Pos, ElevG, EPid, nodir, Floors}}.
closed(open, {Pos, ElevG, EPid, nodir, Floors}) ->
gs:config(ElevG, {fill, cyan}),
{next_state, open, {Pos, ElevG, EPid, nodir, Floors}};
closed({move, Dir}, {Pos, ElevG, EPid, nodir, Floors}) ->
gen_fsm:send_event(self(), {step, Dir}),
{next_state, moving, {Pos, ElevG, EPid, Dir, Floors}}.
moving({step, Dir}, {Pos, ElevG, EPid, Dir, Floors}) ->
Dy = dy(Dir),
NewPos = Pos + Dy,
gs:config(ElevG, {move, {0, Dy}}),
check_position(NewPos, Dir, EPid, Floors),
timer:apply_after(200, gen_fsm, send_event, [self(), {step, Dir}]),
{next_state, moving, {NewPos, ElevG, EPid, Dir, Floors}};
moving(stop, {Pos, ElevG, EPid, Dir, Floors}) ->
{next_state, stopping, {Pos, ElevG, EPid, Dir, Floors}}.
stopping({step, Dir}, {Pos, ElevG, EPid, Dir, Floors}) ->
case at_floor(Pos, Floors) of
false ->
Dy = dy(Dir),
NewPos = Pos + Dy,
gs:config(ElevG, {move, {0, Dy}}),
timer:apply_after(200, gen_fsm, send_event, [self(), {step, Dir}]),
{next_state, stopping, {NewPos, ElevG, EPid, Dir, Floors}};
{true, Floor} ->
elevator:at_floor(EPid, Floor),
{next_state, closed, {Pos, ElevG, EPid, nodir, Floors}}
end.
handle_event({epid, EPid}, State, {Pos, ElevG, OldPid, Dir, Floors}) ->
elevator:reset(EPid, State, get_floor(Pos, Dir, Floors)),
{next_state, State, {Pos, ElevG, EPid, Dir, Floors}}.
handle_sync_event(Event, From, StateName, StateData) ->
Reply = ok,
{reply, Reply, StateName, StateData}.
handle_info(Info, StateName, StateData) ->
{next_state, StateName, StateData}.
terminate(Reason, StateName, StatData) ->
ok.
code_change(_OldVsn, State, Data, _Extra) ->
{ok, State, Data}.
Internal functions
travelling in the direction .
dy(up) -> -10;
dy(down) -> 10.
check_position(Pos , Dir , EPid , Floors )
EPid = pid ( )
Floors = [ { FloorNo , YPos } , ... ]
dir is approaching a floor . If so , the elevator control process EPid
check_position(Pos, Dir, EPid, Floors) ->
case lists:keysearch(Pos + 2 * dy(Dir), 2, Floors) of
{value, {Floor, _}} ->
elevator:approaching(EPid, Floor);
_ ->
check_arrived(Pos, EPid, Floors)
end.
check_arrived(Pos , EPid , Floors )
EPid = pid ( )
Floors = [ { FloorNo , YPos } , ... ]
elevator control process EPid is informed .
check_arrived(Pos, EPid, Floors) ->
case at_floor(Pos, Floors) of
{true, Floor} ->
elevator:at_floor(EPid, Floor);
false ->
ok
end.
Floors = [ { FloorNo , YPos } , ... ]
at_floor(Pos, Floors) ->
case lists:keysearch(Pos, 2, Floors) of
{value, {Floor, _}} ->
{true, Floor};
false ->
false
end.
get_floor(Pos , , Floors ) - > FloorNo
Dir = | up | down
Floors = [ { FloorNo , YPos } , ... ]
travelling in the direction ( or standing still at a floor ) .
get_floor(Pos, nodir, Floors) ->
{value, {Floor, _}} = lists:keysearch(Pos, 2, Floors),
Floor;
get_floor(Pos, up, Floors) ->
find(1, Pos, Floors, infinity, none);
get_floor(Pos, down, Floors) ->
find(-1, Pos, Floors, infinity, none).
find(Sign, Pos, [], Min, MinFloor) ->
MinFloor;
find(Sign, Pos, [{_F, Y} | Floors], Min, MinF) when Sign * (Y - Pos) < 0 ->
find(Sign, Pos, Floors, Min, MinF);
find(Sign, Pos, [{F, Y} | Floors], Min, _MinF) when Sign * (Y - Pos) < Min ->
find(Sign, Pos, Floors, Sign * (Y - Pos), F);
find(Sign, Pos, [{_F, _Y} | Floors], Min, MinF) ->
find(Sign, Pos, Floors, Min, MinF).
|
dab87dd559c504451283ccf4f2bf4df56066cac755302f42637e1735ff9b2189 | shaobo-he/handbook-of-practical-logic-and-automated-reasoning-in-racket | formula-untyped.rkt | #lang racket/base
(require racket/match)
(require racket/set)
(provide atom-union)
;; grammar of formula
;; formula := #t
;; | #f
;; | (atom a)
;; | (not formula)
;; | (and formula formula)
;; | (or formula formula)
;; | (imp formula formula)
;; | (iff formula formula)
;; | (forall symbol formula)
;; | (exists symbol formula)
(define (overatoms fun fm b)
(match fm
[`(atom ,a) (fun a b)]
[`(not ,f) (overatoms fun f b)]
[`(,(or 'and 'or 'imp 'iff) ,f1 ,f2) (overatoms fun f1 (overatoms fun f2 b))]
[`(,(or 'forall 'exists) ,s ,f) (overatoms fun f b)]
[_ b]))
(define (atom-union fun fm)
(set->list (list->set (overatoms (λ (h t) (append (fun h) t)) fm '()))))
| null | https://raw.githubusercontent.com/shaobo-he/handbook-of-practical-logic-and-automated-reasoning-in-racket/1c292f533165ef5f3099185832768b9573ae370d/formula-untyped.rkt | racket | grammar of formula
formula := #t
| #f
| (atom a)
| (not formula)
| (and formula formula)
| (or formula formula)
| (imp formula formula)
| (iff formula formula)
| (forall symbol formula)
| (exists symbol formula) | #lang racket/base
(require racket/match)
(require racket/set)
(provide atom-union)
(define (overatoms fun fm b)
(match fm
[`(atom ,a) (fun a b)]
[`(not ,f) (overatoms fun f b)]
[`(,(or 'and 'or 'imp 'iff) ,f1 ,f2) (overatoms fun f1 (overatoms fun f2 b))]
[`(,(or 'forall 'exists) ,s ,f) (overatoms fun f b)]
[_ b]))
(define (atom-union fun fm)
(set->list (list->set (overatoms (λ (h t) (append (fun h) t)) fm '()))))
|
5fc9a6fb4931a4f970d7c4821b45053a282c132f2f3de0f46f8acd9f6f688b70 | thheller/shadow-cljs | builds.cljs | (ns shadow.cljs.ui.db.builds
(:require
[shadow.grove.db :as db]
[shadow.grove.events :as ev]
[shadow.grove.eql-query :as eql]
[shadow.cljs.model :as m]
[shadow.cljs.ui.db.env :as env]
[shadow.cljs.ui.db.relay-ws :as relay-ws]))
(defn forward-to-ws!
{::ev/handle
[::m/build-watch-compile!
::m/build-watch-stop!
::m/build-watch-start!
::m/build-compile!
::m/build-release!
::m/build-release-debug!]}
[env {:keys [e build-id]}]
(ev/queue-fx env
:relay-send
[{:op e
:to 1 ;; FIXME: don't hardcode CLJ runtime id
::m/build-id build-id}]))
(defmethod eql/attr ::m/active-builds
[env db _ query-part params]
(->> (db/all-of db ::m/build)
(filter ::m/build-worker-active)
(sort-by ::m/build-id)
(map :db/ident)
(into [])))
(defmethod eql/attr ::m/build-sources-sorted
[env db current query-part params]
(when-let [info (get-in current [::m/build-status :info])]
(let [{:keys [sources]} info]
(->> sources
(sort-by :resource-name)
(vec)
))))
(defmethod eql/attr ::m/build-warnings-count
[env db current query-part params]
(let [{:keys [warnings] :as info} (::m/build-status current)]
(count warnings)))
(defmethod eql/attr ::m/build-runtimes
[env db current query-part params]
(let [build-ident (get current :db/ident)
{::m/keys [build-id] :as build} (get db build-ident)]
(->> (db/all-of db ::m/runtime)
(filter (fn [{:keys [runtime-info]}]
(and (= :cljs (:lang runtime-info))
(= build-id (:build-id runtime-info)))))
(mapv :db/ident))))
(defmethod eql/attr ::m/build-runtime-count
[env db current query-part params]
(let [build-ident (get current :db/ident)
{::m/keys [build-id] :as build} (get db build-ident)]
(->> (db/all-of db ::m/runtime)
(filter (fn [{:keys [runtime-info]}]
(and (= :cljs (:lang runtime-info))
(= build-id (:build-id runtime-info)))))
(count))))
(defmethod relay-ws/handle-msg ::m/sub-msg
[env {::m/keys [topic] :as msg}]
(case topic
::m/build-status-update
(let [{:keys [build-id build-status]} msg
build-ident (db/make-ident ::m/build build-id)]
(assoc-in env [:db build-ident ::m/build-status] build-status))
::m/supervisor
(let [{::m/keys [worker-op build-id]} msg
build-ident (db/make-ident ::m/build build-id)]
(case worker-op
:worker-stop
(assoc-in env [:db build-ident ::m/build-worker-active] false)
:worker-start
(assoc-in env [:db build-ident ::m/build-worker-active] true)
(js/console.warn "unhandled supervisor msg" msg)))
(do (js/console.warn "unhandled sub msg" msg)
env))) | null | https://raw.githubusercontent.com/thheller/shadow-cljs/3194818f071a64329e488561591e93fc96e463dc/src/main/shadow/cljs/ui/db/builds.cljs | clojure | FIXME: don't hardcode CLJ runtime id | (ns shadow.cljs.ui.db.builds
(:require
[shadow.grove.db :as db]
[shadow.grove.events :as ev]
[shadow.grove.eql-query :as eql]
[shadow.cljs.model :as m]
[shadow.cljs.ui.db.env :as env]
[shadow.cljs.ui.db.relay-ws :as relay-ws]))
(defn forward-to-ws!
{::ev/handle
[::m/build-watch-compile!
::m/build-watch-stop!
::m/build-watch-start!
::m/build-compile!
::m/build-release!
::m/build-release-debug!]}
[env {:keys [e build-id]}]
(ev/queue-fx env
:relay-send
[{:op e
::m/build-id build-id}]))
(defmethod eql/attr ::m/active-builds
[env db _ query-part params]
(->> (db/all-of db ::m/build)
(filter ::m/build-worker-active)
(sort-by ::m/build-id)
(map :db/ident)
(into [])))
(defmethod eql/attr ::m/build-sources-sorted
[env db current query-part params]
(when-let [info (get-in current [::m/build-status :info])]
(let [{:keys [sources]} info]
(->> sources
(sort-by :resource-name)
(vec)
))))
(defmethod eql/attr ::m/build-warnings-count
[env db current query-part params]
(let [{:keys [warnings] :as info} (::m/build-status current)]
(count warnings)))
(defmethod eql/attr ::m/build-runtimes
[env db current query-part params]
(let [build-ident (get current :db/ident)
{::m/keys [build-id] :as build} (get db build-ident)]
(->> (db/all-of db ::m/runtime)
(filter (fn [{:keys [runtime-info]}]
(and (= :cljs (:lang runtime-info))
(= build-id (:build-id runtime-info)))))
(mapv :db/ident))))
(defmethod eql/attr ::m/build-runtime-count
[env db current query-part params]
(let [build-ident (get current :db/ident)
{::m/keys [build-id] :as build} (get db build-ident)]
(->> (db/all-of db ::m/runtime)
(filter (fn [{:keys [runtime-info]}]
(and (= :cljs (:lang runtime-info))
(= build-id (:build-id runtime-info)))))
(count))))
(defmethod relay-ws/handle-msg ::m/sub-msg
[env {::m/keys [topic] :as msg}]
(case topic
::m/build-status-update
(let [{:keys [build-id build-status]} msg
build-ident (db/make-ident ::m/build build-id)]
(assoc-in env [:db build-ident ::m/build-status] build-status))
::m/supervisor
(let [{::m/keys [worker-op build-id]} msg
build-ident (db/make-ident ::m/build build-id)]
(case worker-op
:worker-stop
(assoc-in env [:db build-ident ::m/build-worker-active] false)
:worker-start
(assoc-in env [:db build-ident ::m/build-worker-active] true)
(js/console.warn "unhandled supervisor msg" msg)))
(do (js/console.warn "unhandled sub msg" msg)
env))) |
0c97f89eeb059e892ab954aa16f1d7d75e1c1d191273996b2f1f99a37ebcdc29 | eccentric-j/clj-lineart | core.clj | (ns lineart.core
(:require
[clojure.string :as s]))
(def canvas-width 500)
(def canvas-height 100)
(def canvas-size (str canvas-width " " canvas-height))
(defn qs->hash-map
"
Parse the query string into a hash-map with keyword keys
Takes a string like \"bg=000000&fg=ffffff\"
Returns a hash-map like:
{:bg \"#000000\"
:fg \"#ffffff\"}
"
[qs]
(->> (s/split qs #"&")
(map #(s/split % #"="))
(map #(vector (keyword (first %)) (str "#" (second %))))
(into {})))
(defn rand-range
"
Generate an integer between the begin and end params
Takes a begin integer and an end integer.
The begin number must be less than end integer.
Returns an integer
"
[begin end]
(-> (- end begin)
(* (rand))
(+ begin)
(int)))
(defn canvas-rect
"
Create a rectangle the same dimensions as viewBox and canvas
Optionally takes other attributes to merge together
Returns the rectangle hiccup vector
[:rect
{...}]
"
[& [opts & _]]
[:rect
(merge
{:x 0
:y 0
:width canvas-width
:height canvas-height}
opts)])
(defn long-diag-lines
"
Default row of long diagonal lines across the image
Lines are 10px apart
Takes a hash-map:
- :fg Foreground color used for line stroke
Returns a hiccup group vector:
[:g
...]
"
[{:keys [fg]}]
[:g
(for [i (range 0 53)]
[:line
{:x1 (+ (* i 10) 0)
:x2 (+ (* i 10) -25)
:y1 20
:y2 80
:stroke fg
:stroke-opacity "15%"}])])
(defn rand-diag-lines
"
Random smaller lines that make the pattern a bit more visually interesting
Parallel to the long lines is -8px from (- x2 x1)
Takes a hash-map:
- :x-seed random int for x-coords
- :y-seed random int for y-coords
- :fg Foreground color used for line stroke
Returns a hiccup group vector:
[:g
...]
"
[{:keys [x-seed y-seed fg]}]
[:g
(for [i (range 0 54)]
[:line
{:x1 (+ (* i 10) x-seed)
:x2 (+ (* i 10) (- x-seed 8.25))
:y1 y-seed
:y2 (+ y-seed 20)
:stroke fg
:stroke-width 2
:stroke-opacity "15%"}])])
(defn generate
"
Generates an svg document in hiccup syntax (vectors) displaying two layers of
diagonal lines.
Takes a query string:
\"bg=363333&fg=f3c581\"
Returns the hiccup xml doc:
[:xml
{...}
...]
"
[qs]
(let [{:keys [bg fg]} (qs->hash-map qs)]
[:svg
{:version "1.1"
:xmlns ""
:xmlns:xlink ""
:x "0px"
:y "0px"
:viewBox (str "0 0 " canvas-size)
:xml:space "preserve"
:clip-path "url(#clip-box)"
:fill "#000"}
[:clipPath
{:id "clip-box"
:clipPathUnits "objectBoundingBox"}
(canvas-rect)]
(canvas-rect
{:fill bg})
(long-diag-lines
{:fg fg})
(rand-diag-lines
{:fg fg
:x-seed (rand-range -25 -10)
:y-seed (rand-range 20 60)})]))
(comment
(require '[hiccup2.core :refer [html]])
(generate "bg=363333&fg1=F3C581&fg2=FFFFFF"))
| null | https://raw.githubusercontent.com/eccentric-j/clj-lineart/9f36f61c286309780f9edf6e392f722621961d78/src/lineart/core.clj | clojure | (ns lineart.core
(:require
[clojure.string :as s]))
(def canvas-width 500)
(def canvas-height 100)
(def canvas-size (str canvas-width " " canvas-height))
(defn qs->hash-map
"
Parse the query string into a hash-map with keyword keys
Takes a string like \"bg=000000&fg=ffffff\"
Returns a hash-map like:
{:bg \"#000000\"
:fg \"#ffffff\"}
"
[qs]
(->> (s/split qs #"&")
(map #(s/split % #"="))
(map #(vector (keyword (first %)) (str "#" (second %))))
(into {})))
(defn rand-range
"
Generate an integer between the begin and end params
Takes a begin integer and an end integer.
The begin number must be less than end integer.
Returns an integer
"
[begin end]
(-> (- end begin)
(* (rand))
(+ begin)
(int)))
(defn canvas-rect
"
Create a rectangle the same dimensions as viewBox and canvas
Optionally takes other attributes to merge together
Returns the rectangle hiccup vector
[:rect
{...}]
"
[& [opts & _]]
[:rect
(merge
{:x 0
:y 0
:width canvas-width
:height canvas-height}
opts)])
(defn long-diag-lines
"
Default row of long diagonal lines across the image
Lines are 10px apart
Takes a hash-map:
- :fg Foreground color used for line stroke
Returns a hiccup group vector:
[:g
...]
"
[{:keys [fg]}]
[:g
(for [i (range 0 53)]
[:line
{:x1 (+ (* i 10) 0)
:x2 (+ (* i 10) -25)
:y1 20
:y2 80
:stroke fg
:stroke-opacity "15%"}])])
(defn rand-diag-lines
"
Random smaller lines that make the pattern a bit more visually interesting
Parallel to the long lines is -8px from (- x2 x1)
Takes a hash-map:
- :x-seed random int for x-coords
- :y-seed random int for y-coords
- :fg Foreground color used for line stroke
Returns a hiccup group vector:
[:g
...]
"
[{:keys [x-seed y-seed fg]}]
[:g
(for [i (range 0 54)]
[:line
{:x1 (+ (* i 10) x-seed)
:x2 (+ (* i 10) (- x-seed 8.25))
:y1 y-seed
:y2 (+ y-seed 20)
:stroke fg
:stroke-width 2
:stroke-opacity "15%"}])])
(defn generate
"
Generates an svg document in hiccup syntax (vectors) displaying two layers of
diagonal lines.
Takes a query string:
\"bg=363333&fg=f3c581\"
Returns the hiccup xml doc:
[:xml
{...}
...]
"
[qs]
(let [{:keys [bg fg]} (qs->hash-map qs)]
[:svg
{:version "1.1"
:xmlns ""
:xmlns:xlink ""
:x "0px"
:y "0px"
:viewBox (str "0 0 " canvas-size)
:xml:space "preserve"
:clip-path "url(#clip-box)"
:fill "#000"}
[:clipPath
{:id "clip-box"
:clipPathUnits "objectBoundingBox"}
(canvas-rect)]
(canvas-rect
{:fill bg})
(long-diag-lines
{:fg fg})
(rand-diag-lines
{:fg fg
:x-seed (rand-range -25 -10)
:y-seed (rand-range 20 60)})]))
(comment
(require '[hiccup2.core :refer [html]])
(generate "bg=363333&fg1=F3C581&fg2=FFFFFF"))
| |
3caec7d9ea01d15de87c80fbde928f047ca47f1558e4ea9853df837406f9d2c5 | ucsd-progsys/liquidhaskell | Split.hs | # LANGUAGE OverloadedStrings #
# LANGUAGE PartialTypeSignatures #
{-# LANGUAGE FlexibleContexts #-}
# OPTIONS_GHC -Wno - incomplete - uni - patterns #
--------------------------------------------------------------------------------
-- | Constraint Splitting ------------------------------------------------------
--------------------------------------------------------------------------------
module Language.Haskell.Liquid.Constraint.Split (
-- * Split Subtyping Constraints
splitC
-- * Split Well-formedness Constraints
, splitW
-- * ???
, envToSub
-- * Panic
, panicUnbound
) where
import Prelude hiding (error)
import Text.PrettyPrint.HughesPJ hiding (first, parens)
import Data.Maybe (fromMaybe)
import Control.Monad
import Control.Monad.State (gets)
import qualified Control.Exception as Ex
import qualified Language.Fixpoint.Types as F
import Language.Fixpoint.Misc hiding (errorstar)
import Language.Fixpoint.SortCheck (pruneUnsortedReft)
import Language.Haskell.Liquid.Misc -- (concatMapM)
import qualified Language.Haskell.Liquid.UX.CTags as Tg
import Language.Haskell.Liquid.Types hiding (loc)
import Language.Haskell.Liquid.Constraint.Types
import Language.Haskell.Liquid.Constraint.Env
import Language.Haskell.Liquid.Constraint.Constraint
import Language.Haskell.Liquid.Constraint.Monad (envToSub)
--------------------------------------------------------------------------------
splitW :: WfC -> CG [FixWfC]
--------------------------------------------------------------------------------
splitW (WfC γ t@(RFun x _ t1 t2 _))
= do ws' <- splitW (WfC γ t1)
γ' <- γ += ("splitW", x, t1)
ws <- bsplitW γ t
ws'' <- splitW (WfC γ' t2)
return $ ws ++ ws' ++ ws''
splitW (WfC γ t@(RImpF x _ t1 t2 _))
= do ws' <- splitW (WfC γ t1)
γ' <- γ += ("splitW", x, t1)
ws <- bsplitW γ t
ws'' <- splitW (WfC γ' t2)
return $ ws ++ ws' ++ ws''
splitW (WfC γ t@(RAppTy t1 t2 _))
= do ws <- bsplitW γ t
ws' <- splitW (WfC γ t1)
ws'' <- splitW (WfC γ t2)
return $ ws ++ ws' ++ ws''
splitW (WfC γ t'@(RAllT a t _))
= do γ' <- updateEnv γ a
ws <- bsplitW γ t'
ws' <- splitW (WfC γ' t)
return $ ws ++ ws'
splitW (WfC γ (RAllP _ r))
= splitW (WfC γ r)
splitW (WfC γ t@(RVar _ _))
= bsplitW γ t
splitW (WfC γ t@(RApp _ ts rs _))
= do ws <- bsplitW γ t
γ' <- if bscope (getConfig γ) then γ `extendEnvWithVV` t else return γ
ws' <- concat <$> mapM (splitW . WfC γ') ts
ws'' <- concat <$> mapM (rsplitW γ) rs
return $ ws ++ ws' ++ ws''
splitW (WfC γ (RAllE x tx t))
= do ws <- splitW (WfC γ tx)
γ' <- γ += ("splitW1", x, tx)
ws' <- splitW (WfC γ' t)
return $ ws ++ ws'
splitW (WfC γ (REx x tx t))
= do ws <- splitW (WfC γ tx)
γ' <- γ += ("splitW2", x, tx)
ws' <- splitW (WfC γ' t)
return $ ws ++ ws'
splitW (WfC γ (RRTy _ _ _ t))
= splitW (WfC γ t)
splitW (WfC _ t)
= panic Nothing $ "splitW cannot handle: " ++ showpp t
rsplitW :: CGEnv
-> Ref RSort SpecType
-> CG [FixWfC]
rsplitW _ (RProp _ (RHole _)) =
panic Nothing "Constrains: rsplitW for RProp _ (RHole _)"
rsplitW γ (RProp ss t0) = do
γ' <- foldM (+=) γ [("rsplitW", x, ofRSort s) | (x, s) <- ss]
splitW $ WfC γ' t0
bsplitW :: CGEnv -> SpecType -> CG [FixWfC]
bsplitW γ t =
do temp <- getTemplates
isHO <- gets allowHO
return $ bsplitW' γ t temp isHO
bsplitW' :: (PPrint r, F.Reftable r, SubsTy RTyVar RSort r, F.Reftable (RTProp RTyCon RTyVar r))
=> CGEnv -> RRType r -> F.Templates -> Bool -> [F.WfC Cinfo]
bsplitW' γ t temp isHO
| isHO || F.isNonTrivial r'
= F.wfC (feBinds $ fenv γ) r' ci
| otherwise
= []
where
r' = rTypeSortedReft' γ temp t
ci = Ci (getLocation γ) Nothing (cgVar γ)
splitfWithVariance :: Applicative f
=> (t -> t -> f [a]) -> t -> t -> Variance -> f [a]
splitfWithVariance f t1 t2 Invariant = (++) <$> f t1 t2 <*> f t2 t1
splitfWithVariance f t1 t2 Bivariant = (++) <$> f t1 t2 <*> f t2 t1
splitfWithVariance f t1 t2 Covariant = f t1 t2
splitfWithVariance f t1 t2 Contravariant = f t2 t1
updateEnv :: CGEnv -> RTVar RTyVar (RType RTyCon RTyVar b0) -> CG CGEnv
updateEnv γ a
| Just (x, s) <- rTVarToBind a
= γ += ("splitS RAllT", x, fmap (const mempty) s)
| otherwise
= return γ
------------------------------------------------------------
splitC :: Bool -> SubC -> CG [FixSubC]
------------------------------------------------------------
splitC allowTC (SubC γ (REx x tx t1) (REx x2 _ t2)) | x == x2
= do γ' <- γ += ("addExBind 0", x, forallExprRefType γ tx)
splitC allowTC (SubC γ' t1 t2)
splitC allowTC (SubC γ t1 (REx x tx t2))
= do y <- fresh
γ' <- γ += ("addExBind 1", y, forallExprRefType γ tx)
splitC allowTC (SubC γ' t1 (F.subst1 t2 (x, F.EVar y)))
-- existential at the left hand side is treated like forall
splitC allowTC (SubC γ (REx x tx t1) t2)
let tx ' = traceShow ( " splitC allowTC : " + + showpp z ) tx
y <- fresh
γ' <- γ += ("addExBind 2", y, forallExprRefType γ tx)
splitC allowTC (SubC γ' (F.subst1 t1 (x, F.EVar y)) t2)
splitC allowTC (SubC γ (RAllE x tx t1) (RAllE x2 _ t2)) | x == x2
= do γ' <- γ += ("addAllBind 3", x, forallExprRefType γ tx)
splitC allowTC (SubC γ' t1 t2)
splitC allowTC (SubC γ (RAllE x tx t1) t2)
= do y <- fresh
γ' <- γ += ("addAABind 1", y, forallExprRefType γ tx)
splitC allowTC (SubC γ' (t1 `F.subst1` (x, F.EVar y)) t2)
splitC allowTC (SubC γ t1 (RAllE x tx t2))
= do y <- fresh
γ' <- γ += ("addAllBind 2", y, forallExprRefType γ tx)
splitC allowTC (SubC γ' t1 (F.subst1 t2 (x, F.EVar y)))
splitC allowTC (SubC cgenv (RRTy env _ OCons t1) t2)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) cgenv xts
c1 <- splitC allowTC (SubC γ' t1' t2')
c2 <- splitC allowTC (SubC cgenv t1 t2 )
return $ c1 ++ c2
where
(xts, t1', t2') = envToSub env
splitC allowTC (SubC cgenv (RRTy e r o t1) t2)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) cgenv e
c1 <- splitC allowTC (SubR γ' o r)
c2 <- splitC allowTC (SubC cgenv t1 t2)
return $ c1 ++ c2
splitC allowTC (SubC γ (RFun x1 i1 t1 t1' r1) (RFun x2 i2 t2 t2' r2))
= do cs' <- splitC allowTC (SubC γ t2 t1)
γ' <- γ+= ("splitC allowTC", x2, t2)
cs <- bsplitC γ (RFun x1 i1 t1 t1' (r1 `F.subst1` (x1, F.EVar x2)))
(RFun x2 i2 t2 t2' r2)
let t1x2' = t1' `F.subst1` (x1, F.EVar x2)
cs'' <- splitC allowTC (SubC γ' t1x2' t2')
return $ cs ++ cs' ++ cs''
splitC allowTC (SubC γ (RImpF x1 i1 t1 t1' r1) (RImpF x2 i2 t2 t2' r2))
= do cs' <- splitC allowTC (SubC γ t2 t1)
γ' <- γ+= ("splitC allowTC", x2, t2)
cs <- bsplitC γ (RImpF x1 i1 t1 t1' (r1 `F.subst1` (x1, F.EVar x2)))
(RImpF x2 i2 t2 t2' r2)
let t1x2' = t1' `F.subst1` (x1, F.EVar x2)
cs'' <- splitC allowTC (SubC γ' t1x2' t2')
return $ cs ++ cs' ++ cs''
splitC allowTC (SubC γ t1@(RAppTy r1 r1' _) t2@(RAppTy r2 r2' _))
= do cs <- bsplitC γ t1 t2
cs' <- splitC allowTC (SubC γ r1 r2)
cs'' <- splitC allowTC (SubC γ r1' r2')
cs''' <- splitC allowTC (SubC γ r2' r1')
return $ cs ++ cs' ++ cs'' ++ cs'''
splitC allowTC (SubC γ t1 (RAllP p t))
= splitC allowTC $ SubC γ t1 t'
where
t' = fmap (replacePredsWithRefs su) t
su = (uPVar p, pVartoRConc p)
splitC _ (SubC γ t1@(RAllP _ _) t2)
= panic (Just $ getLocation γ) $ "Predicate in lhs of constraint:" ++ showpp t1 ++ "\n<:\n" ++ showpp t2
splitC allowTC (SubC γ t1'@(RAllT α1 t1 _) t2'@(RAllT α2 t2 _))
| α1 == α2
= do γ' <- updateEnv γ α2
cs <- bsplitC γ t1' t2'
cs' <- splitC allowTC $ SubC γ' t1 (F.subst su t2)
return (cs ++ cs')
| otherwise
= do γ' <- updateEnv γ α2
cs <- bsplitC γ t1' t2'
cs' <- splitC allowTC $ SubC γ' t1 (F.subst su t2'')
return (cs ++ cs')
where
t2'' = subsTyVarMeet' (ty_var_value α2, RVar (ty_var_value α1) mempty) t2
su = case (rTVarToBind α1, rTVarToBind α2) of
(Just (x1, _), Just (x2, _)) -> F.mkSubst [(x1, F.EVar x2)]
_ -> F.mkSubst []
splitC allowTC (SubC _ (RApp c1 _ _ _) (RApp c2 _ _ _)) | (if allowTC then isEmbeddedDict else isClass) c1 && c1 == c2
= return []
splitC _ (SubC γ t1@RApp{} t2@RApp{})
= do (t1',t2') <- unifyVV t1 t2
cs <- bsplitC γ t1' t2'
γ' <- if bscope (getConfig γ) then γ `extendEnvWithVV` t1' else return γ
let RApp c t1s r1s _ = t1'
let RApp _ t2s r2s _ = t2'
let isapplied = True -- TC.tyConArity (rtc_tc c) == length t1s
let tyInfo = rtc_info c
csvar <- splitsCWithVariance γ' t1s t2s $ varianceTyArgs tyInfo
csvar' <- rsplitsCWithVariance isapplied γ' r1s r2s $ variancePsArgs tyInfo
return $ cs ++ csvar ++ csvar'
splitC _ (SubC γ t1@(RVar a1 _) t2@(RVar a2 _))
| a1 == a2
= bsplitC γ t1 t2
splitC _ (SubC γ t1 t2)
= panic (Just $ getLocation γ) $ "(Another Broken Test!!!) splitc unexpected:\n" ++ traceTy t1 ++ "\n <:\n" ++ traceTy t2
splitC _ (SubR γ o r)
= do ts <- getTemplates
let r1' = pruneUnsortedReft γ'' ts r1
return $ F.subC γ' r1' r2 Nothing tag ci
where
γ'' = feEnv $ fenv γ
γ' = feBinds $ fenv γ
r1 = F.RR F.boolSort rr
r2 = F.RR F.boolSort $ F.Reft (vv, F.EVar vv)
vv = "vvRec"
ci = Ci src err (cgVar γ)
err = Just $ ErrAssType src o (text $ show o ++ "type error") g (rHole rr)
rr = F.toReft r
tag = getTag γ
src = getLocation γ
g = reLocal $ renv γ
traceTy :: SpecType -> String
traceTy (RVar v _) = parens ("RVar " ++ showpp v)
traceTy (RApp c ts _ _) = parens ("RApp " ++ showpp c ++ unwords (traceTy <$> ts))
traceTy (RAllP _ t) = parens ("RAllP " ++ traceTy t)
traceTy (RAllT _ t _) = parens ("RAllT " ++ traceTy t)
traceTy (RImpF _ _ t t' _) = parens ("RImpF " ++ parens (traceTy t) ++ parens (traceTy t'))
traceTy (RFun _ _ t t' _) = parens ("RFun " ++ parens (traceTy t) ++ parens (traceTy t'))
traceTy (RAllE _ tx t) = parens ("RAllE " ++ parens (traceTy tx) ++ parens (traceTy t))
traceTy (REx _ tx t) = parens ("REx " ++ parens (traceTy tx) ++ parens (traceTy t))
traceTy (RExprArg _) = "RExprArg"
traceTy (RAppTy t t' _) = parens ("RAppTy " ++ parens (traceTy t) ++ parens (traceTy t'))
traceTy (RHole _) = "rHole"
traceTy (RRTy _ _ _ t) = parens ("RRTy " ++ traceTy t)
parens :: String -> String
parens s = "(" ++ s ++ ")"
rHole :: F.Reft -> SpecType
rHole = RHole . uTop
splitsCWithVariance :: CGEnv
-> [SpecType]
-> [SpecType]
-> [Variance]
-> CG [FixSubC]
splitsCWithVariance γ t1s t2s variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (\s1 s2 -> splitC (typeclass (getConfig γ)) (SubC γ s1 s2)) t1 t2 v) (zip3 t1s t2s variants)
rsplitsCWithVariance :: Bool
-> CGEnv
-> [SpecProp]
-> [SpecProp]
-> [Variance]
-> CG [FixSubC]
rsplitsCWithVariance False _ _ _ _
= return []
rsplitsCWithVariance _ γ t1s t2s variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (rsplitC γ) t1 t2 v) (zip3 t1s t2s variants)
bsplitC :: CGEnv
-> SpecType
-> SpecType
-> CG [F.SubC Cinfo]
bsplitC γ t1 t2 = do
temp <- getTemplates
isHO <- gets allowHO
t1' <- addLhsInv γ <$> refreshVV t1
return $ bsplitC' γ t1' t2 temp isHO
addLhsInv :: CGEnv -> SpecType -> SpecType
addLhsInv γ t = addRTyConInv (invs γ) t `strengthen` r
where
r = (mempty :: UReft F.Reft) { ur_reft = F.Reft (F.dummySymbol, p) }
p = constraintToLogic rE' (lcs γ)
rE' = insertREnv v t (renv γ)
v = rTypeValueVar t
bsplitC' :: CGEnv -> SpecType -> SpecType -> F.Templates -> Bool -> [F.SubC Cinfo]
bsplitC' γ t1 t2 tem isHO
| isHO
= mkSubC γ' r1' r2' tag ci
| F.isFunctionSortedReft r1' && F.isNonTrivial r2'
= mkSubC γ' (r1' {F.sr_reft = mempty}) r2' tag ci
| F.isNonTrivial r2'
= mkSubC γ' r1' r2' tag ci
| otherwise
= []
where
γ' = feBinds $ fenv γ
r1' = rTypeSortedReft' γ tem t1
r2' = rTypeSortedReft' γ tem t2
tag = getTag γ
src = getLocation γ
g = reLocal $ renv γ
ci sr = Ci src (err sr) (cgVar γ)
err sr = Just $ fromMaybe (ErrSubType src (text "subtype") Nothing g t1 (replaceTop t2 sr)) (cerr γ)
mkSubC :: F.IBindEnv -> F.SortedReft -> F.SortedReft -> F.Tag -> (F.SortedReft -> a) -> [F.SubC a]
mkSubC g sr1 sr2 tag ci = concatMap (\sr2' -> F.subC g sr1 sr2' Nothing tag (ci sr2')) (splitSortedReft sr2)
splitSortedReft :: F.SortedReft -> [F.SortedReft]
splitSortedReft (F.RR t (F.Reft (v, r))) = [ F.RR t (F.Reft (v, ra)) | ra <- refaConjuncts r ]
refaConjuncts :: F.Expr -> [F.Expr]
refaConjuncts p = [p' | p' <- F.conjuncts p, not $ F.isTautoPred p']
replaceTop :: SpecType -> F.SortedReft -> SpecType
replaceTop (RApp c ts rs r) r' = RApp c ts rs $ replaceReft r r'
replaceTop (RVar a r) r' = RVar a $ replaceReft r r'
replaceTop (RFun b i t1 t2 r) r' = RFun b i t1 t2 $ replaceReft r r'
replaceTop (RAppTy t1 t2 r) r' = RAppTy t1 t2 $ replaceReft r r'
replaceTop (RAllT a t r) r' = RAllT a t $ replaceReft r r'
replaceTop t _ = t
replaceReft :: RReft -> F.SortedReft -> RReft
replaceReft rr (F.RR _ r) = rr {ur_reft = F.Reft (v, F.subst1 p (vr, F.EVar v) )}
where
F.Reft (v, _) = ur_reft rr
F.Reft (vr,p) = r
unifyVV :: SpecType -> SpecType -> CG (SpecType, SpecType)
unifyVV t1@RApp{} t2@RApp{}
= do vv <- F.vv . Just <$> fresh
return (shiftVV t1 vv, shiftVV t2 vv)
unifyVV _ _
= panic Nothing "Constraint.Generate.unifyVV called on invalid inputs"
rsplitC :: CGEnv
-> SpecProp
-> SpecProp
-> CG [FixSubC]
rsplitC _ _ (RProp _ (RHole _))
= panic Nothing "RefTypes.rsplitC on RProp _ (RHole _)"
rsplitC _ (RProp _ (RHole _)) _
= panic Nothing "RefTypes.rsplitC on RProp _ (RHole _)"
rsplitC γ (RProp s1 r1) (RProp s2 r2)
= do γ' <- foldM (+=) γ [("rsplitC1", x, ofRSort s) | (x, s) <- s2]
splitC (typeclass (getConfig γ)) (SubC γ' (F.subst su r1) r2)
where su = F.mkSubst [(x, F.EVar y) | ((x,_), (y,_)) <- zip s1 s2]
--------------------------------------------------------------------------------
| Reftypes from F.Fixpoint Expressions --------------------------------------
--------------------------------------------------------------------------------
forallExprRefType :: CGEnv -> SpecType -> SpecType
forallExprRefType γ t = t `strengthen` uTop r'
where
r' = fromMaybe mempty $ forallExprReft γ r
r = F.sr_reft $ rTypeSortedReft (emb γ) t
forallExprReft :: CGEnv -> F.Reft -> Maybe F.Reft
forallExprReft γ r =
do e <- F.isSingletonReft r
forallExprReft_ γ $ F.splitEApp e
forallExprReft_ :: CGEnv -> (F.Expr, [F.Expr]) -> Maybe F.Reft
forallExprReft_ γ (F.EVar x, [])
= case forallExprReftLookup γ x of
Just (_,_,_,_,t) -> Just $ F.sr_reft $ rTypeSortedReft (emb γ) t
Nothing -> Nothing
forallExprReft_ γ (F.EVar f, es)
= case forallExprReftLookup γ f of
Just (xs,_,_,_,t) -> let su = F.mkSubst $ safeZip "fExprRefType" xs es in
Just $ F.subst su $ F.sr_reft $ rTypeSortedReft (emb γ) t
Nothing -> Nothing
forallExprReft_ _ _
= Nothing
-- forallExprReftLookup :: CGEnv -> F.Symbol -> Int
forallExprReftLookup :: CGEnv
-> F.Symbol
-> Maybe ([F.Symbol], [RFInfo], [SpecType], [RReft], SpecType)
forallExprReftLookup γ sym = snap <$> F.lookupSEnv sym (syenv γ)
where
snap = mapFifth5 ignoreOblig . (\(_,(x,a,b,c),t)->(x,a,b,c,t)) . bkArrow . thd3 . bkUniv . lookup'
lookup' z = fromMaybe (panicUnbound γ z) (γ ?= F.symbol z)
--------------------------------------------------------------------------------
getTag :: CGEnv -> F.Tag
--------------------------------------------------------------------------------
getTag γ = maybe Tg.defaultTag (`Tg.getTag` tgEnv γ) (tgKey γ)
--------------------------------------------------------------------------------
-- | Constraint Generation Panic -----------------------------------------------
--------------------------------------------------------------------------------
panicUnbound :: (PPrint x) => CGEnv -> x -> a
panicUnbound γ x = Ex.throw (ErrUnbound (getLocation γ) (F.pprint x) :: Error)
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/efef712213416c8befb68c71800a169e85864a47/src/Language/Haskell/Liquid/Constraint/Split.hs | haskell | # LANGUAGE FlexibleContexts #
------------------------------------------------------------------------------
| Constraint Splitting ------------------------------------------------------
------------------------------------------------------------------------------
* Split Subtyping Constraints
* Split Well-formedness Constraints
* ???
* Panic
(concatMapM)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
----------------------------------------------------------
----------------------------------------------------------
existential at the left hand side is treated like forall
TC.tyConArity (rtc_tc c) == length t1s
------------------------------------------------------------------------------
------------------------------------
------------------------------------------------------------------------------
forallExprReftLookup :: CGEnv -> F.Symbol -> Int
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Constraint Generation Panic -----------------------------------------------
------------------------------------------------------------------------------ | # LANGUAGE OverloadedStrings #
# LANGUAGE PartialTypeSignatures #
# OPTIONS_GHC -Wno - incomplete - uni - patterns #
module Language.Haskell.Liquid.Constraint.Split (
splitC
, splitW
, envToSub
, panicUnbound
) where
import Prelude hiding (error)
import Text.PrettyPrint.HughesPJ hiding (first, parens)
import Data.Maybe (fromMaybe)
import Control.Monad
import Control.Monad.State (gets)
import qualified Control.Exception as Ex
import qualified Language.Fixpoint.Types as F
import Language.Fixpoint.Misc hiding (errorstar)
import Language.Fixpoint.SortCheck (pruneUnsortedReft)
import qualified Language.Haskell.Liquid.UX.CTags as Tg
import Language.Haskell.Liquid.Types hiding (loc)
import Language.Haskell.Liquid.Constraint.Types
import Language.Haskell.Liquid.Constraint.Env
import Language.Haskell.Liquid.Constraint.Constraint
import Language.Haskell.Liquid.Constraint.Monad (envToSub)
splitW :: WfC -> CG [FixWfC]
splitW (WfC γ t@(RFun x _ t1 t2 _))
= do ws' <- splitW (WfC γ t1)
γ' <- γ += ("splitW", x, t1)
ws <- bsplitW γ t
ws'' <- splitW (WfC γ' t2)
return $ ws ++ ws' ++ ws''
splitW (WfC γ t@(RImpF x _ t1 t2 _))
= do ws' <- splitW (WfC γ t1)
γ' <- γ += ("splitW", x, t1)
ws <- bsplitW γ t
ws'' <- splitW (WfC γ' t2)
return $ ws ++ ws' ++ ws''
splitW (WfC γ t@(RAppTy t1 t2 _))
= do ws <- bsplitW γ t
ws' <- splitW (WfC γ t1)
ws'' <- splitW (WfC γ t2)
return $ ws ++ ws' ++ ws''
splitW (WfC γ t'@(RAllT a t _))
= do γ' <- updateEnv γ a
ws <- bsplitW γ t'
ws' <- splitW (WfC γ' t)
return $ ws ++ ws'
splitW (WfC γ (RAllP _ r))
= splitW (WfC γ r)
splitW (WfC γ t@(RVar _ _))
= bsplitW γ t
splitW (WfC γ t@(RApp _ ts rs _))
= do ws <- bsplitW γ t
γ' <- if bscope (getConfig γ) then γ `extendEnvWithVV` t else return γ
ws' <- concat <$> mapM (splitW . WfC γ') ts
ws'' <- concat <$> mapM (rsplitW γ) rs
return $ ws ++ ws' ++ ws''
splitW (WfC γ (RAllE x tx t))
= do ws <- splitW (WfC γ tx)
γ' <- γ += ("splitW1", x, tx)
ws' <- splitW (WfC γ' t)
return $ ws ++ ws'
splitW (WfC γ (REx x tx t))
= do ws <- splitW (WfC γ tx)
γ' <- γ += ("splitW2", x, tx)
ws' <- splitW (WfC γ' t)
return $ ws ++ ws'
splitW (WfC γ (RRTy _ _ _ t))
= splitW (WfC γ t)
splitW (WfC _ t)
= panic Nothing $ "splitW cannot handle: " ++ showpp t
rsplitW :: CGEnv
-> Ref RSort SpecType
-> CG [FixWfC]
rsplitW _ (RProp _ (RHole _)) =
panic Nothing "Constrains: rsplitW for RProp _ (RHole _)"
rsplitW γ (RProp ss t0) = do
γ' <- foldM (+=) γ [("rsplitW", x, ofRSort s) | (x, s) <- ss]
splitW $ WfC γ' t0
bsplitW :: CGEnv -> SpecType -> CG [FixWfC]
bsplitW γ t =
do temp <- getTemplates
isHO <- gets allowHO
return $ bsplitW' γ t temp isHO
bsplitW' :: (PPrint r, F.Reftable r, SubsTy RTyVar RSort r, F.Reftable (RTProp RTyCon RTyVar r))
=> CGEnv -> RRType r -> F.Templates -> Bool -> [F.WfC Cinfo]
bsplitW' γ t temp isHO
| isHO || F.isNonTrivial r'
= F.wfC (feBinds $ fenv γ) r' ci
| otherwise
= []
where
r' = rTypeSortedReft' γ temp t
ci = Ci (getLocation γ) Nothing (cgVar γ)
splitfWithVariance :: Applicative f
=> (t -> t -> f [a]) -> t -> t -> Variance -> f [a]
splitfWithVariance f t1 t2 Invariant = (++) <$> f t1 t2 <*> f t2 t1
splitfWithVariance f t1 t2 Bivariant = (++) <$> f t1 t2 <*> f t2 t1
splitfWithVariance f t1 t2 Covariant = f t1 t2
splitfWithVariance f t1 t2 Contravariant = f t2 t1
updateEnv :: CGEnv -> RTVar RTyVar (RType RTyCon RTyVar b0) -> CG CGEnv
updateEnv γ a
| Just (x, s) <- rTVarToBind a
= γ += ("splitS RAllT", x, fmap (const mempty) s)
| otherwise
= return γ
splitC :: Bool -> SubC -> CG [FixSubC]
splitC allowTC (SubC γ (REx x tx t1) (REx x2 _ t2)) | x == x2
= do γ' <- γ += ("addExBind 0", x, forallExprRefType γ tx)
splitC allowTC (SubC γ' t1 t2)
splitC allowTC (SubC γ t1 (REx x tx t2))
= do y <- fresh
γ' <- γ += ("addExBind 1", y, forallExprRefType γ tx)
splitC allowTC (SubC γ' t1 (F.subst1 t2 (x, F.EVar y)))
splitC allowTC (SubC γ (REx x tx t1) t2)
let tx ' = traceShow ( " splitC allowTC : " + + showpp z ) tx
y <- fresh
γ' <- γ += ("addExBind 2", y, forallExprRefType γ tx)
splitC allowTC (SubC γ' (F.subst1 t1 (x, F.EVar y)) t2)
splitC allowTC (SubC γ (RAllE x tx t1) (RAllE x2 _ t2)) | x == x2
= do γ' <- γ += ("addAllBind 3", x, forallExprRefType γ tx)
splitC allowTC (SubC γ' t1 t2)
splitC allowTC (SubC γ (RAllE x tx t1) t2)
= do y <- fresh
γ' <- γ += ("addAABind 1", y, forallExprRefType γ tx)
splitC allowTC (SubC γ' (t1 `F.subst1` (x, F.EVar y)) t2)
splitC allowTC (SubC γ t1 (RAllE x tx t2))
= do y <- fresh
γ' <- γ += ("addAllBind 2", y, forallExprRefType γ tx)
splitC allowTC (SubC γ' t1 (F.subst1 t2 (x, F.EVar y)))
splitC allowTC (SubC cgenv (RRTy env _ OCons t1) t2)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) cgenv xts
c1 <- splitC allowTC (SubC γ' t1' t2')
c2 <- splitC allowTC (SubC cgenv t1 t2 )
return $ c1 ++ c2
where
(xts, t1', t2') = envToSub env
splitC allowTC (SubC cgenv (RRTy e r o t1) t2)
= do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) cgenv e
c1 <- splitC allowTC (SubR γ' o r)
c2 <- splitC allowTC (SubC cgenv t1 t2)
return $ c1 ++ c2
splitC allowTC (SubC γ (RFun x1 i1 t1 t1' r1) (RFun x2 i2 t2 t2' r2))
= do cs' <- splitC allowTC (SubC γ t2 t1)
γ' <- γ+= ("splitC allowTC", x2, t2)
cs <- bsplitC γ (RFun x1 i1 t1 t1' (r1 `F.subst1` (x1, F.EVar x2)))
(RFun x2 i2 t2 t2' r2)
let t1x2' = t1' `F.subst1` (x1, F.EVar x2)
cs'' <- splitC allowTC (SubC γ' t1x2' t2')
return $ cs ++ cs' ++ cs''
splitC allowTC (SubC γ (RImpF x1 i1 t1 t1' r1) (RImpF x2 i2 t2 t2' r2))
= do cs' <- splitC allowTC (SubC γ t2 t1)
γ' <- γ+= ("splitC allowTC", x2, t2)
cs <- bsplitC γ (RImpF x1 i1 t1 t1' (r1 `F.subst1` (x1, F.EVar x2)))
(RImpF x2 i2 t2 t2' r2)
let t1x2' = t1' `F.subst1` (x1, F.EVar x2)
cs'' <- splitC allowTC (SubC γ' t1x2' t2')
return $ cs ++ cs' ++ cs''
splitC allowTC (SubC γ t1@(RAppTy r1 r1' _) t2@(RAppTy r2 r2' _))
= do cs <- bsplitC γ t1 t2
cs' <- splitC allowTC (SubC γ r1 r2)
cs'' <- splitC allowTC (SubC γ r1' r2')
cs''' <- splitC allowTC (SubC γ r2' r1')
return $ cs ++ cs' ++ cs'' ++ cs'''
splitC allowTC (SubC γ t1 (RAllP p t))
= splitC allowTC $ SubC γ t1 t'
where
t' = fmap (replacePredsWithRefs su) t
su = (uPVar p, pVartoRConc p)
splitC _ (SubC γ t1@(RAllP _ _) t2)
= panic (Just $ getLocation γ) $ "Predicate in lhs of constraint:" ++ showpp t1 ++ "\n<:\n" ++ showpp t2
splitC allowTC (SubC γ t1'@(RAllT α1 t1 _) t2'@(RAllT α2 t2 _))
| α1 == α2
= do γ' <- updateEnv γ α2
cs <- bsplitC γ t1' t2'
cs' <- splitC allowTC $ SubC γ' t1 (F.subst su t2)
return (cs ++ cs')
| otherwise
= do γ' <- updateEnv γ α2
cs <- bsplitC γ t1' t2'
cs' <- splitC allowTC $ SubC γ' t1 (F.subst su t2'')
return (cs ++ cs')
where
t2'' = subsTyVarMeet' (ty_var_value α2, RVar (ty_var_value α1) mempty) t2
su = case (rTVarToBind α1, rTVarToBind α2) of
(Just (x1, _), Just (x2, _)) -> F.mkSubst [(x1, F.EVar x2)]
_ -> F.mkSubst []
splitC allowTC (SubC _ (RApp c1 _ _ _) (RApp c2 _ _ _)) | (if allowTC then isEmbeddedDict else isClass) c1 && c1 == c2
= return []
splitC _ (SubC γ t1@RApp{} t2@RApp{})
= do (t1',t2') <- unifyVV t1 t2
cs <- bsplitC γ t1' t2'
γ' <- if bscope (getConfig γ) then γ `extendEnvWithVV` t1' else return γ
let RApp c t1s r1s _ = t1'
let RApp _ t2s r2s _ = t2'
let tyInfo = rtc_info c
csvar <- splitsCWithVariance γ' t1s t2s $ varianceTyArgs tyInfo
csvar' <- rsplitsCWithVariance isapplied γ' r1s r2s $ variancePsArgs tyInfo
return $ cs ++ csvar ++ csvar'
splitC _ (SubC γ t1@(RVar a1 _) t2@(RVar a2 _))
| a1 == a2
= bsplitC γ t1 t2
splitC _ (SubC γ t1 t2)
= panic (Just $ getLocation γ) $ "(Another Broken Test!!!) splitc unexpected:\n" ++ traceTy t1 ++ "\n <:\n" ++ traceTy t2
splitC _ (SubR γ o r)
= do ts <- getTemplates
let r1' = pruneUnsortedReft γ'' ts r1
return $ F.subC γ' r1' r2 Nothing tag ci
where
γ'' = feEnv $ fenv γ
γ' = feBinds $ fenv γ
r1 = F.RR F.boolSort rr
r2 = F.RR F.boolSort $ F.Reft (vv, F.EVar vv)
vv = "vvRec"
ci = Ci src err (cgVar γ)
err = Just $ ErrAssType src o (text $ show o ++ "type error") g (rHole rr)
rr = F.toReft r
tag = getTag γ
src = getLocation γ
g = reLocal $ renv γ
traceTy :: SpecType -> String
traceTy (RVar v _) = parens ("RVar " ++ showpp v)
traceTy (RApp c ts _ _) = parens ("RApp " ++ showpp c ++ unwords (traceTy <$> ts))
traceTy (RAllP _ t) = parens ("RAllP " ++ traceTy t)
traceTy (RAllT _ t _) = parens ("RAllT " ++ traceTy t)
traceTy (RImpF _ _ t t' _) = parens ("RImpF " ++ parens (traceTy t) ++ parens (traceTy t'))
traceTy (RFun _ _ t t' _) = parens ("RFun " ++ parens (traceTy t) ++ parens (traceTy t'))
traceTy (RAllE _ tx t) = parens ("RAllE " ++ parens (traceTy tx) ++ parens (traceTy t))
traceTy (REx _ tx t) = parens ("REx " ++ parens (traceTy tx) ++ parens (traceTy t))
traceTy (RExprArg _) = "RExprArg"
traceTy (RAppTy t t' _) = parens ("RAppTy " ++ parens (traceTy t) ++ parens (traceTy t'))
traceTy (RHole _) = "rHole"
traceTy (RRTy _ _ _ t) = parens ("RRTy " ++ traceTy t)
parens :: String -> String
parens s = "(" ++ s ++ ")"
rHole :: F.Reft -> SpecType
rHole = RHole . uTop
splitsCWithVariance :: CGEnv
-> [SpecType]
-> [SpecType]
-> [Variance]
-> CG [FixSubC]
splitsCWithVariance γ t1s t2s variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (\s1 s2 -> splitC (typeclass (getConfig γ)) (SubC γ s1 s2)) t1 t2 v) (zip3 t1s t2s variants)
rsplitsCWithVariance :: Bool
-> CGEnv
-> [SpecProp]
-> [SpecProp]
-> [Variance]
-> CG [FixSubC]
rsplitsCWithVariance False _ _ _ _
= return []
rsplitsCWithVariance _ γ t1s t2s variants
= concatMapM (\(t1, t2, v) -> splitfWithVariance (rsplitC γ) t1 t2 v) (zip3 t1s t2s variants)
bsplitC :: CGEnv
-> SpecType
-> SpecType
-> CG [F.SubC Cinfo]
bsplitC γ t1 t2 = do
temp <- getTemplates
isHO <- gets allowHO
t1' <- addLhsInv γ <$> refreshVV t1
return $ bsplitC' γ t1' t2 temp isHO
addLhsInv :: CGEnv -> SpecType -> SpecType
addLhsInv γ t = addRTyConInv (invs γ) t `strengthen` r
where
r = (mempty :: UReft F.Reft) { ur_reft = F.Reft (F.dummySymbol, p) }
p = constraintToLogic rE' (lcs γ)
rE' = insertREnv v t (renv γ)
v = rTypeValueVar t
bsplitC' :: CGEnv -> SpecType -> SpecType -> F.Templates -> Bool -> [F.SubC Cinfo]
bsplitC' γ t1 t2 tem isHO
| isHO
= mkSubC γ' r1' r2' tag ci
| F.isFunctionSortedReft r1' && F.isNonTrivial r2'
= mkSubC γ' (r1' {F.sr_reft = mempty}) r2' tag ci
| F.isNonTrivial r2'
= mkSubC γ' r1' r2' tag ci
| otherwise
= []
where
γ' = feBinds $ fenv γ
r1' = rTypeSortedReft' γ tem t1
r2' = rTypeSortedReft' γ tem t2
tag = getTag γ
src = getLocation γ
g = reLocal $ renv γ
ci sr = Ci src (err sr) (cgVar γ)
err sr = Just $ fromMaybe (ErrSubType src (text "subtype") Nothing g t1 (replaceTop t2 sr)) (cerr γ)
mkSubC :: F.IBindEnv -> F.SortedReft -> F.SortedReft -> F.Tag -> (F.SortedReft -> a) -> [F.SubC a]
mkSubC g sr1 sr2 tag ci = concatMap (\sr2' -> F.subC g sr1 sr2' Nothing tag (ci sr2')) (splitSortedReft sr2)
splitSortedReft :: F.SortedReft -> [F.SortedReft]
splitSortedReft (F.RR t (F.Reft (v, r))) = [ F.RR t (F.Reft (v, ra)) | ra <- refaConjuncts r ]
refaConjuncts :: F.Expr -> [F.Expr]
refaConjuncts p = [p' | p' <- F.conjuncts p, not $ F.isTautoPred p']
replaceTop :: SpecType -> F.SortedReft -> SpecType
replaceTop (RApp c ts rs r) r' = RApp c ts rs $ replaceReft r r'
replaceTop (RVar a r) r' = RVar a $ replaceReft r r'
replaceTop (RFun b i t1 t2 r) r' = RFun b i t1 t2 $ replaceReft r r'
replaceTop (RAppTy t1 t2 r) r' = RAppTy t1 t2 $ replaceReft r r'
replaceTop (RAllT a t r) r' = RAllT a t $ replaceReft r r'
replaceTop t _ = t
replaceReft :: RReft -> F.SortedReft -> RReft
replaceReft rr (F.RR _ r) = rr {ur_reft = F.Reft (v, F.subst1 p (vr, F.EVar v) )}
where
F.Reft (v, _) = ur_reft rr
F.Reft (vr,p) = r
unifyVV :: SpecType -> SpecType -> CG (SpecType, SpecType)
unifyVV t1@RApp{} t2@RApp{}
= do vv <- F.vv . Just <$> fresh
return (shiftVV t1 vv, shiftVV t2 vv)
unifyVV _ _
= panic Nothing "Constraint.Generate.unifyVV called on invalid inputs"
rsplitC :: CGEnv
-> SpecProp
-> SpecProp
-> CG [FixSubC]
rsplitC _ _ (RProp _ (RHole _))
= panic Nothing "RefTypes.rsplitC on RProp _ (RHole _)"
rsplitC _ (RProp _ (RHole _)) _
= panic Nothing "RefTypes.rsplitC on RProp _ (RHole _)"
rsplitC γ (RProp s1 r1) (RProp s2 r2)
= do γ' <- foldM (+=) γ [("rsplitC1", x, ofRSort s) | (x, s) <- s2]
splitC (typeclass (getConfig γ)) (SubC γ' (F.subst su r1) r2)
where su = F.mkSubst [(x, F.EVar y) | ((x,_), (y,_)) <- zip s1 s2]
forallExprRefType :: CGEnv -> SpecType -> SpecType
forallExprRefType γ t = t `strengthen` uTop r'
where
r' = fromMaybe mempty $ forallExprReft γ r
r = F.sr_reft $ rTypeSortedReft (emb γ) t
forallExprReft :: CGEnv -> F.Reft -> Maybe F.Reft
forallExprReft γ r =
do e <- F.isSingletonReft r
forallExprReft_ γ $ F.splitEApp e
forallExprReft_ :: CGEnv -> (F.Expr, [F.Expr]) -> Maybe F.Reft
forallExprReft_ γ (F.EVar x, [])
= case forallExprReftLookup γ x of
Just (_,_,_,_,t) -> Just $ F.sr_reft $ rTypeSortedReft (emb γ) t
Nothing -> Nothing
forallExprReft_ γ (F.EVar f, es)
= case forallExprReftLookup γ f of
Just (xs,_,_,_,t) -> let su = F.mkSubst $ safeZip "fExprRefType" xs es in
Just $ F.subst su $ F.sr_reft $ rTypeSortedReft (emb γ) t
Nothing -> Nothing
forallExprReft_ _ _
= Nothing
forallExprReftLookup :: CGEnv
-> F.Symbol
-> Maybe ([F.Symbol], [RFInfo], [SpecType], [RReft], SpecType)
forallExprReftLookup γ sym = snap <$> F.lookupSEnv sym (syenv γ)
where
snap = mapFifth5 ignoreOblig . (\(_,(x,a,b,c),t)->(x,a,b,c,t)) . bkArrow . thd3 . bkUniv . lookup'
lookup' z = fromMaybe (panicUnbound γ z) (γ ?= F.symbol z)
getTag :: CGEnv -> F.Tag
getTag γ = maybe Tg.defaultTag (`Tg.getTag` tgEnv γ) (tgKey γ)
panicUnbound :: (PPrint x) => CGEnv -> x -> a
panicUnbound γ x = Ex.throw (ErrUnbound (getLocation γ) (F.pprint x) :: Error)
|
8066c9226df03a97a3ff34dc2a346382d132bc59922219841a55c493f35c5bdb | ThomasHintz/keep-the-records | amazon-s3-backup.scm | #!/usr/bin/csi
(use amazon-s3 send-grid srfi-19 shell)
(define *root* "/keep-the-records/")
(define ++ string-append)
(define (insert-file path)
(with-input-from-file path (lambda () (read-string))))
(print "loading/setting send-grid api keys")
(define api-user (insert-file (++ *root* "send-grid-user")))
(define api-key (insert-file (++ *root* "send-grid-key")))
(handle-exceptions
exn
(send-mail from: "" from-name: "Error" to: "" reply-to: "" subject: "Database backup job failed"
html: "Database backup job failed")
(begin
(print "loading/setting aws api keys")
(load (++ *root* "aws-setup.scm"))
(https #t)
(define bucket (make-parameter "keep-the-records-backup-job"))
(define (space->dash s)
(string-fold (lambda (c o) (string-append o (if (char=? #\space c) "-" (->string c)))) "" s))
(define (remove-colons s)
(string-fold (lambda (c o) (string-append o (if (char=? #\: c) "" (->string c)))) "" s))
(print "copying file")
(run "cp /keep-the-records/ktr-db /keep-the-records/ktr-db.bak")
(print "file copied")
(print "uploading...")
(put-file! (bucket) (remove-colons (space->dash (date->string (current-date) "~c"))) (++ *root* "ktr-db"))
(print "uploaded")
(print "sending success mail")
(send-mail from: "" from-name: "Success" to: "" reply-to: "" subject: "Database backup job succeeded"
html: "Database backup job succeeded")
(print "done")))
(exit)
| null | https://raw.githubusercontent.com/ThomasHintz/keep-the-records/c20e648e831bed2ced3f2f74bfc590dc06b5f076/amazon-s3-backup.scm | scheme | #!/usr/bin/csi
(use amazon-s3 send-grid srfi-19 shell)
(define *root* "/keep-the-records/")
(define ++ string-append)
(define (insert-file path)
(with-input-from-file path (lambda () (read-string))))
(print "loading/setting send-grid api keys")
(define api-user (insert-file (++ *root* "send-grid-user")))
(define api-key (insert-file (++ *root* "send-grid-key")))
(handle-exceptions
exn
(send-mail from: "" from-name: "Error" to: "" reply-to: "" subject: "Database backup job failed"
html: "Database backup job failed")
(begin
(print "loading/setting aws api keys")
(load (++ *root* "aws-setup.scm"))
(https #t)
(define bucket (make-parameter "keep-the-records-backup-job"))
(define (space->dash s)
(string-fold (lambda (c o) (string-append o (if (char=? #\space c) "-" (->string c)))) "" s))
(define (remove-colons s)
(string-fold (lambda (c o) (string-append o (if (char=? #\: c) "" (->string c)))) "" s))
(print "copying file")
(run "cp /keep-the-records/ktr-db /keep-the-records/ktr-db.bak")
(print "file copied")
(print "uploading...")
(put-file! (bucket) (remove-colons (space->dash (date->string (current-date) "~c"))) (++ *root* "ktr-db"))
(print "uploaded")
(print "sending success mail")
(send-mail from: "" from-name: "Success" to: "" reply-to: "" subject: "Database backup job succeeded"
html: "Database backup job succeeded")
(print "done")))
(exit)
| |
87df2a94071f8dc03e945d10ec20bb7598c4cb6c5e12d22975502734db9b384d | patricoferris/ppx_deriving_yaml | helpers.mli | open Ppxlib
val mkloc : 'a -> 'a Ppxlib.loc
val arg : int -> string
val suf_to : string
val suf_of : string
val mangle_suf : ?fixpoint:string -> string -> Longident.t -> Longident.t
val poly_fun : loc:location -> type_declaration -> expression -> expression
val ptuple : loc:location -> pattern list -> pattern
val etuple : loc:location -> expression list -> expression
val map_bind : loc:location -> expression
| null | https://raw.githubusercontent.com/patricoferris/ppx_deriving_yaml/f7e68abe062e57c97bded8e5111689391bba4c15/src/helpers.mli | ocaml | open Ppxlib
val mkloc : 'a -> 'a Ppxlib.loc
val arg : int -> string
val suf_to : string
val suf_of : string
val mangle_suf : ?fixpoint:string -> string -> Longident.t -> Longident.t
val poly_fun : loc:location -> type_declaration -> expression -> expression
val ptuple : loc:location -> pattern list -> pattern
val etuple : loc:location -> expression list -> expression
val map_bind : loc:location -> expression
| |
e84ccd016957b6b89a62bc13b67157b9a2fed2453754ad3878afe180c2bc28ed | pflanze/chj-schemelib | improper-length-test.scm | Copyright 2010 - 2018 by < >
;;; This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
;;; (at your option) any later version.
(require ;; (cj-source-util improper-length)
test)
(TEST
> (improper-length '())
0
> (improper-length '(1))
1
> (improper-length '(a b c))
3
> (improper-length '(a b . c))
-3
> (improper-length '(a . c))
-2
> (improper-length 'c)
-1)
| null | https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/improper-length-test.scm | scheme | This file is free software; you can redistribute it and/or modify
(at your option) any later version.
(cj-source-util improper-length) | Copyright 2010 - 2018 by < >
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
test)
(TEST
> (improper-length '())
0
> (improper-length '(1))
1
> (improper-length '(a b c))
3
> (improper-length '(a b . c))
-3
> (improper-length '(a . c))
-2
> (improper-length 'c)
-1)
|
7862a68d83da48c696ffed3e6988768d3a2fd0cf8e363eaf1e1c378ec70aabab | tjammer/raylib-ocaml | generate_c_rlgl.ml | let () =
print_endline "#include <rlgl.h>";
Cstubs.write_c Format.std_formatter ~prefix:Sys.argv.(1)
(module Raylib_rlgl.Description)
| null | https://raw.githubusercontent.com/tjammer/raylib-ocaml/fa2691a85f109209bbe6f05983b2fc7c5b590446/src/c/stubgen/generate_c_rlgl.ml | ocaml | let () =
print_endline "#include <rlgl.h>";
Cstubs.write_c Format.std_formatter ~prefix:Sys.argv.(1)
(module Raylib_rlgl.Description)
| |
cc31d75aac705ae500a7a63f95a6933baff0a89cdf8a0babddc7c45b5ce23082 | samply/blaze | spec.clj | (ns blaze.db.impl.index.spec
(:require
[clojure.spec.alpha :as s]))
(s/def :blaze.db.index.stats/total
nat-int?)
(s/def :blaze.db.index.stats/num-changes
nat-int?)
(s/def :blaze.db.index/stats
(s/keys :req-un [:blaze.db.index.stats/total :blaze.db.index.stats/num-changes]))
| null | https://raw.githubusercontent.com/samply/blaze/e84c106b5ca235600c20ba74fe8a2295eb18f350/modules/db/test/blaze/db/impl/index/spec.clj | clojure | (ns blaze.db.impl.index.spec
(:require
[clojure.spec.alpha :as s]))
(s/def :blaze.db.index.stats/total
nat-int?)
(s/def :blaze.db.index.stats/num-changes
nat-int?)
(s/def :blaze.db.index/stats
(s/keys :req-un [:blaze.db.index.stats/total :blaze.db.index.stats/num-changes]))
| |
de1308a9fe4e56cf5806725f426f77741751cc22a554c9342ff654aeddedb811 | sol/hspec-tutorial | AppSpec.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
module AppSpec (spec) where
import Test.Hspec hiding (pending)
import Test.Hspec.Wai
import Test.Hspec.Wai.QuickCheck
import Test.Hspec.Wai.JSON
import Data.ByteString
import Data.String
import App (app)
spec :: Spec
spec = with app $ do
describe "GET /" $ do
it "responds with HTTP status 200" $ do
get "/" `shouldRespondWith` 200
it "says 'Hello!'" $ do
get "/" `shouldRespondWith` [json|{body: "Hello!"}|]
context "when given an invalid request path" $ do
it "responds with HTTP status 404" $ do
pending
| null | https://raw.githubusercontent.com/sol/hspec-tutorial/92ced065e0bfdd688f6e18bda74da53d270d8cda/test/AppSpec.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE QuasiQuotes #
module AppSpec (spec) where
import Test.Hspec hiding (pending)
import Test.Hspec.Wai
import Test.Hspec.Wai.QuickCheck
import Test.Hspec.Wai.JSON
import Data.ByteString
import Data.String
import App (app)
spec :: Spec
spec = with app $ do
describe "GET /" $ do
it "responds with HTTP status 200" $ do
get "/" `shouldRespondWith` 200
it "says 'Hello!'" $ do
get "/" `shouldRespondWith` [json|{body: "Hello!"}|]
context "when given an invalid request path" $ do
it "responds with HTTP status 404" $ do
pending
|
d07bcea6c178790b91eb22f50072ef582bf89d2d143c69f61a3a1f5fbf0b9601 | racket/gui | arrow-toggle-snip.rkt | #lang racket/base
(require racket/class
racket/gui/base)
(provide arrow-toggle-snip%)
;; arrow-toggle-snip% represents a togglable state, displayed as a right-facing
;; arrow (off or "closed") or a downward-facing arrow (on or "open").
;; The size of the arrow is determined by the style (and font) applied to the
;; snip. The arrow is drawn inscribed in a square resting on the baseline, but
;; the snip reports its size (usually) as the same as a capital "X"; this means
;; that the snip should look good next to text (in the same style) no matter
;; whether base-aligned or top-aligned.
;; ------------------------------------------------------------
Paths and gradients , in terms of 100x100 box
(define (down-arrow-path scale yb)
(define (tx x) (* scale x))
(define (ty y) (+ yb (* scale y)))
(define p (new dc-path%))
(send* p
[move-to (tx 10) (ty 40)]
[line-to (tx 90) (ty 40)]
[line-to (tx 50) (ty 75)]
[line-to (tx 10) (ty 40)]
[close])
p)
(define (down-arrow-gradient scale xb yb dark?)
(define (tx x) (+ xb (* scale x)))
(define (ty y) (+ yb (* scale y)))
(new linear-gradient%
[x0 (tx 50)] [y0 (ty 40)]
[x1 (tx 50)] [y1 (ty 75)]
[stops (get-gradient-stops dark?)]))
(define (right-arrow-path scale yb)
(define (tx x) (* scale x))
(define (ty y) (+ yb (* scale y)))
(define p (new dc-path%))
(send* p
[move-to (tx 40) (ty 10)]
[line-to (tx 75) (ty 50)]
[line-to (tx 40) (ty 90)]
[line-to (tx 40) (ty 10)]
[close])
p)
(define (right-arrow-gradient scale xb yb dark?)
(define (tx x) (+ xb (* scale x)))
(define (ty y) (+ yb (* scale y)))
(new linear-gradient%
[x0 (tx 40)] [y0 (ty 50)]
[x1 (tx 75)] [y1 (ty 50)]
[stops (get-gradient-stops dark?)]))
(define (get-gradient-stops dark?)
(list (list 0 (if dark?
(make-object color% 20 20 255)
(make-object color% 240 240 255)))
(list 1 (make-object color% 128 128 255))))
;; ------------------------------------------------------------
(define arrow-toggle-snip%
(class snip%
(inherit get-admin get-flags get-style set-flags set-count)
(init [open? #f])
(init-field [callback void]
[size #f])
(field [state (if open? 'down 'up)]) ; (U 'up 'down 'up-click 'down-click)
(super-new)
(set-count 1)
(set-flags (cons 'handles-events (get-flags)))
(define/override (copy)
(new arrow-toggle-snip% (callback callback) (open? state) (size size)))
(define/override (draw dc x y left top right bottom dx dy draw-caret)
(define dark?
(let ([c (send (get-style) get-foreground)])
(and (< 220 (send c red))
(< 220 (send c green))
(< 220 (send c blue)))))
(define old-brush (send dc get-brush))
(define old-pen (send dc get-pen))
(define old-smoothing (send dc get-smoothing))
(define-values (size dy*) (get-target-size* dc))
(define scale-factor (/ size 100))
(define arrow-path
(case state
[(up up-click) (right-arrow-path scale-factor dy*)]
[(down down-click) (down-arrow-path scale-factor dy*)]))
(define arrow-gradient
(case state
[(up up-click) (right-arrow-gradient scale-factor x (+ dy* y) dark?)]
[(down down-click) (down-arrow-gradient scale-factor x (+ dy* y) dark?)]))
;; Draw arrow
(send* dc
[set-pen (if dark? "Gainsboro" "black") 0 'solid]
[set-brush (new brush% [gradient arrow-gradient])]
[set-smoothing 'aligned]
[draw-path arrow-path x y])
;; Restore
(send* dc
[set-brush old-brush]
[set-pen old-pen]))
(define/override (get-extent dc x y w h descent space lspace rspace)
(define-values (size dy) (get-target-size* dc))
(set-box/f! descent 0)
(set-box/f! space 0)
(set-box/f! lspace 0)
(set-box/f! rspace 0)
(set-box/f! w size)
(set-box/f! h (+ size dy)))
;; get-target-size* : -> (values Real Real)
;; Returns size of drawn square and dy to drop to baseline so whole
;; snip takes up same space as "X". (This is a hack because baseline
;; alignment would cause problems elsewhere.)
(define/private (get-target-size* dc)
(define-values (xw xh xd xa)
(send dc get-text-extent "X" (send (get-style) get-font)))
(let ([size (or size (* xh 0.6))])
(values size (max 0 (- xh xd size)))))
(define/override (on-event dc x y editorx editory evt)
(define-values (arrow-snip-width dh) (get-target-size* dc))
(define arrow-snip-height (+ arrow-snip-width dh))
(let ([snip-evt-x (- (send evt get-x) x)]
[snip-evt-y (- (send evt get-y) y)])
(cond
[(send evt button-down? 'left)
(set-state (case state
[(up) 'up-click]
[else 'down-click]))]
[(send evt button-up? 'left)
(cond [(and (<= 0 snip-evt-x arrow-snip-width)
(<= 0 snip-evt-y arrow-snip-height))
(set-state (case state
[(down down-click) 'up]
[else 'down]))]
[else
(set-state (case state
[(down down-click) 'down]
[else 'up]))])]
[(and (send evt get-left-down)
(send evt dragging?))
(cond [(and (<= 0 snip-evt-x arrow-snip-width)
(<= 0 snip-evt-y arrow-snip-height))
(set-state (case state
[(down down-click) 'down-click]
[else 'up-click]))]
[else
(set-state (case state
[(down down-click) 'down]
[else 'up]))])]))
(super on-event dc x y editorx editory evt))
(define/public (get-toggle-state)
(case state [(down down-click) #t] [else #f]))
(define/public (set-toggle-state new-state)
(set-state (if new-state 'down 'up)))
(define/private (set-state new-state)
(unless (eq? state new-state)
(define old-toggled? (get-toggle-state))
(set! state new-state)
(let ([admin (get-admin)])
(when admin
(define-values (size dy) (get-target-size* (send admin get-dc)))
(send admin needs-update this 0 0 size (+ size dy))))
(define new-toggled? (get-toggle-state))
(unless (equal? new-toggled? old-toggled?)
(callback new-toggled?))))
(define/override (adjust-cursor dc x y editorx editory event)
arrow-snip-cursor)
))
(define (set-box/f! b v) (when (box? b) (set-box! b v)))
(define arrow-snip-cursor (make-object cursor% 'arrow))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/mrlib/arrow-toggle-snip.rkt | racket | arrow-toggle-snip% represents a togglable state, displayed as a right-facing
arrow (off or "closed") or a downward-facing arrow (on or "open").
The size of the arrow is determined by the style (and font) applied to the
snip. The arrow is drawn inscribed in a square resting on the baseline, but
the snip reports its size (usually) as the same as a capital "X"; this means
that the snip should look good next to text (in the same style) no matter
whether base-aligned or top-aligned.
------------------------------------------------------------
------------------------------------------------------------
(U 'up 'down 'up-click 'down-click)
Draw arrow
Restore
get-target-size* : -> (values Real Real)
Returns size of drawn square and dy to drop to baseline so whole
snip takes up same space as "X". (This is a hack because baseline
alignment would cause problems elsewhere.) | #lang racket/base
(require racket/class
racket/gui/base)
(provide arrow-toggle-snip%)
Paths and gradients , in terms of 100x100 box
(define (down-arrow-path scale yb)
(define (tx x) (* scale x))
(define (ty y) (+ yb (* scale y)))
(define p (new dc-path%))
(send* p
[move-to (tx 10) (ty 40)]
[line-to (tx 90) (ty 40)]
[line-to (tx 50) (ty 75)]
[line-to (tx 10) (ty 40)]
[close])
p)
(define (down-arrow-gradient scale xb yb dark?)
(define (tx x) (+ xb (* scale x)))
(define (ty y) (+ yb (* scale y)))
(new linear-gradient%
[x0 (tx 50)] [y0 (ty 40)]
[x1 (tx 50)] [y1 (ty 75)]
[stops (get-gradient-stops dark?)]))
(define (right-arrow-path scale yb)
(define (tx x) (* scale x))
(define (ty y) (+ yb (* scale y)))
(define p (new dc-path%))
(send* p
[move-to (tx 40) (ty 10)]
[line-to (tx 75) (ty 50)]
[line-to (tx 40) (ty 90)]
[line-to (tx 40) (ty 10)]
[close])
p)
(define (right-arrow-gradient scale xb yb dark?)
(define (tx x) (+ xb (* scale x)))
(define (ty y) (+ yb (* scale y)))
(new linear-gradient%
[x0 (tx 40)] [y0 (ty 50)]
[x1 (tx 75)] [y1 (ty 50)]
[stops (get-gradient-stops dark?)]))
(define (get-gradient-stops dark?)
(list (list 0 (if dark?
(make-object color% 20 20 255)
(make-object color% 240 240 255)))
(list 1 (make-object color% 128 128 255))))
(define arrow-toggle-snip%
(class snip%
(inherit get-admin get-flags get-style set-flags set-count)
(init [open? #f])
(init-field [callback void]
[size #f])
(super-new)
(set-count 1)
(set-flags (cons 'handles-events (get-flags)))
(define/override (copy)
(new arrow-toggle-snip% (callback callback) (open? state) (size size)))
(define/override (draw dc x y left top right bottom dx dy draw-caret)
(define dark?
(let ([c (send (get-style) get-foreground)])
(and (< 220 (send c red))
(< 220 (send c green))
(< 220 (send c blue)))))
(define old-brush (send dc get-brush))
(define old-pen (send dc get-pen))
(define old-smoothing (send dc get-smoothing))
(define-values (size dy*) (get-target-size* dc))
(define scale-factor (/ size 100))
(define arrow-path
(case state
[(up up-click) (right-arrow-path scale-factor dy*)]
[(down down-click) (down-arrow-path scale-factor dy*)]))
(define arrow-gradient
(case state
[(up up-click) (right-arrow-gradient scale-factor x (+ dy* y) dark?)]
[(down down-click) (down-arrow-gradient scale-factor x (+ dy* y) dark?)]))
(send* dc
[set-pen (if dark? "Gainsboro" "black") 0 'solid]
[set-brush (new brush% [gradient arrow-gradient])]
[set-smoothing 'aligned]
[draw-path arrow-path x y])
(send* dc
[set-brush old-brush]
[set-pen old-pen]))
(define/override (get-extent dc x y w h descent space lspace rspace)
(define-values (size dy) (get-target-size* dc))
(set-box/f! descent 0)
(set-box/f! space 0)
(set-box/f! lspace 0)
(set-box/f! rspace 0)
(set-box/f! w size)
(set-box/f! h (+ size dy)))
(define/private (get-target-size* dc)
(define-values (xw xh xd xa)
(send dc get-text-extent "X" (send (get-style) get-font)))
(let ([size (or size (* xh 0.6))])
(values size (max 0 (- xh xd size)))))
(define/override (on-event dc x y editorx editory evt)
(define-values (arrow-snip-width dh) (get-target-size* dc))
(define arrow-snip-height (+ arrow-snip-width dh))
(let ([snip-evt-x (- (send evt get-x) x)]
[snip-evt-y (- (send evt get-y) y)])
(cond
[(send evt button-down? 'left)
(set-state (case state
[(up) 'up-click]
[else 'down-click]))]
[(send evt button-up? 'left)
(cond [(and (<= 0 snip-evt-x arrow-snip-width)
(<= 0 snip-evt-y arrow-snip-height))
(set-state (case state
[(down down-click) 'up]
[else 'down]))]
[else
(set-state (case state
[(down down-click) 'down]
[else 'up]))])]
[(and (send evt get-left-down)
(send evt dragging?))
(cond [(and (<= 0 snip-evt-x arrow-snip-width)
(<= 0 snip-evt-y arrow-snip-height))
(set-state (case state
[(down down-click) 'down-click]
[else 'up-click]))]
[else
(set-state (case state
[(down down-click) 'down]
[else 'up]))])]))
(super on-event dc x y editorx editory evt))
(define/public (get-toggle-state)
(case state [(down down-click) #t] [else #f]))
(define/public (set-toggle-state new-state)
(set-state (if new-state 'down 'up)))
(define/private (set-state new-state)
(unless (eq? state new-state)
(define old-toggled? (get-toggle-state))
(set! state new-state)
(let ([admin (get-admin)])
(when admin
(define-values (size dy) (get-target-size* (send admin get-dc)))
(send admin needs-update this 0 0 size (+ size dy))))
(define new-toggled? (get-toggle-state))
(unless (equal? new-toggled? old-toggled?)
(callback new-toggled?))))
(define/override (adjust-cursor dc x y editorx editory event)
arrow-snip-cursor)
))
(define (set-box/f! b v) (when (box? b) (set-box! b v)))
(define arrow-snip-cursor (make-object cursor% 'arrow))
|
6fc7dcb83ff8e21f07d5bfe112b7676ba7994caf0b7e17b83714ffb578e72beb | dennismckinnon/Ethereum-Contracts | Magnet-DB.lsp | Infohash Database manager with Membership structure
{
[[0x0]] 0x11 ;Admin member pointer
[[0x1]] 30 ;Number of segments per item
[[0x2]] 0x200 ;Member pointer
[[0x3]] 0x0 ;Number of members
[[0x4]] 0x1000 ;infohash list pointer
[[0x10]](caller) ;Set admin
[0x0] "A"
(call 0x11d11764cd7f6ecda172e0b72370e6ea7f75f290 0 0 0 1 0 0)
}
{
You ca n't do anything if you are n't a member so check that first
(for ["i"] 0x10 (< @"i" @@0x0) ["i"](+ @"i" 1)
{
(when (= @@ @"i" (caller))
[0x0] 1 ;Admin
)
}
)
(unless @0x0
(for ["i"] 0x200 (< @"i" @@0x200) ["i"](+ @"i" 1)
{
(when (= @@ @"i" (caller))
[0x0] 2 ;Normal member
)
}
)
)
(unless @0x0 (stop)) ;Not a member stop
First argument is txtype
No first argument stop
;Admin suicide (Format: "kill")
(when (&& (= @0x20 "kill") (= @0x20 1)) ;Admin and say kill suicide + deregister
{
(call 0x11d11764cd7f6ecda172e0b72370e6ea7f75f290 0 0 0 0 0 0)
(suicide @@0x10)
}
)
;Register new admin (Format: "regadm" 0xMemberaddress)
(when (&& (= @0x20 "regadm") (= @0x20 1))
{
Get second data argument
(when @0x40
{
[[@@0x0]] @0x40 ;Store the new member in then next admin slot
[[0x0]] (+ @@0x0 1) ;Increment admin pointer
}
)
(stop)
}
)
;Register new member (Format: "regmem" 0xMemberaddress)
(when (= @0x20 "regmem")
{
Get second data argument
(when @0x40
{
[[@@0x2]] @0x40 ;Store the new member in then next admin slot
[[0x2]] (+ @@0x2 1) ;Increment admin pointer
}
)
(stop)
}
)
;Delete normal member (must be an admin) (Format: "delmem" 0xMemberaddress)
(when (= @0x20 "delmem")
{
Get second data argument
(when @0x40
{
(for ["i"] 0x200 (< @"i" @@0x2) ["i"](+ @"i" 1)
{
(when (= @@ @"i" @0x40) ;delete and shuffle
{
[[0x2]] (- @@0x2 1)
[[@"i"]] @@ @@0x2
[[@@ @@0x2]] 0
(stop) ;don't need to do any more
}
)
}
)
}
)
}
)
;Delete Admin member (must be an admin that is higher then the member you re deleting) (Format: "deladm" 0xMemberaddress)
;Note: This is REALLY costly since order must be maintained
(when (= @0x20 "deladm")
{
Get second data argument
(when @0x40
{
[0x60] 0 ;Flag for if caller appears before attempted deletee
[0x80] 0 ;Flag for finding deletee AFTER your number
(for ["i"]0x10 (< @"i" @@0x0) ["i"](+ @"i" 1)
{
(when (&& (= @@ @"i" @0x40)(= @0x60 1)) [0x80]1) ;Flip ok to delete flag (if the line comes after the next you can delete yourself)
(when (= @@ @"i" (caller)) [0x60] 1) ;If caller was found flip flag
(when (= @0x80 1) ;delete and shuffle
[[@"i"]] @@ (+ @"i" 1)
)
}
)
(when (= @0x80 1) ;If deletion has occured
{
[[0x0]] (- @@0x0 1) ;Decrement admin pointer
[[@@0x0]] 0 ;Delete the last (duplicated guy)
}
)
}
)
}
)
Add / edit Magnet link ( Format : " modmag " 0xIndicator ( 4 hex digits ) 0xinfohash " filetype " " quality " " title " " description " ) - See top
(when (= @0x20 "modmag")
{
[0x40] (calldataload 32) ;Data telling which parts are available.
[0x60] (calldataload 64) ;This is the infohash. It is required!
(when (> @0x60 0xFFFFF) ;(not only must it exist but it has to be valid)
{
[0x110] 96 ;Calldata pointer
(unless @@ @0x60 ;If this hash hasn't been added yet add to list !!!This works because creator is
{
[[@@0x4]] @0x60 ;Copy infohash into list
[[0x4]] (+ @@0x4 1) ;Increment infohash pointer
;Special: Magnet link creator address
[[@0x60]] (caller) ;Copy data over (if you don't want to track this change to a constant)
}
)
[0x60] (+ @0x60 0x20) ;Increment storage pointer (logic is that this will need to skip over creator regardless)
FILETYPE ( 1 Seg )
[0x100] (MOD @0x40 0x10)
[0x40] (DIV @0x40 0x10) ;Copy out the new last digit
(when @0x100
{
[0x500] 1;Data field size in data segments
(for ["i"]0 (> @"i" @0x500) ["i"](+ @"i" 1)
{
[0x80] (calldataload @0x110) ;Get the next data segment
[[@0x60]] @0x80 ;Copy data over
[0x60] (+ @0x60 0x20) ;Increment storage pointer
}
)
}
)
FILE QUALITY ( 1 Seg )
[0x100] (MOD @0x40 0x10)
[0x40] (DIV @0x40 0x10) ;Copy out the new last digit
(when @0x100
{
[0x500] 1;Data field size in data segments
(for ["i"]0 (> @"i" @0x500) ["i"](+ @"i" 1)
{
[0x80] (calldataload @0x110) ;Get the next data segment
[[@0x60]] @0x80 ;Copy data over
[0x60] (+ @0x60 0x20) ;Increment storage pointer
}
)
}
)
FILE TITLE ( 2 )
[0x100] (MOD @0x40 0x10)
[0x40] (DIV @0x40 0x10) ;Copy out the new last digit
(when @0x100
{
[0x500] 2 ;Data field size in data segments
(for ["i"]0 (> @"i" @0x500) ["i"](+ @"i" 1)
{
[0x80] (calldataload @0x110) ;Get the next data segment
[[@0x60]] @0x80 ;Copy data over
[0x60] (+ @0x60 0x20) ;Increment storage pointer
}
)
}
)
FILE DESCRIPTION ( 25 )
[0x100] (MOD @0x40 0x10)
[0x40] (DIV @0x40 0x10) ;Copy out the new last digit
(when @0x100
{
[0x500] 25 ;Data field size in data segments
(for ["i"]0 (> @"i" @0x500) ["i"](+ @"i" 1)
{
[0x80] (calldataload @0x110) ;Get the next data segment
[[@0x60]] @0x80 ;Copy data over
[0x60] (+ @0x60 0x20) ;Increment storage pointer
}
)
}
)
}
)
(stop)
}
)
;Delete magnet link and data (Format: "delmag" 0xinfohash) ??ADMIN priveleges needed?
(when (= @0x20 "delmag")
{
Get second data argument
(when @0x40
{
(for ["i"] 0x1000 (< @"i" @@0x4) ["i"](+ @"i" 1)
{
(when (= @@ @"i" @0x40) ;delete and shuffle
{
[[0x4]] (- @@0x4 1)
[[@"i"]] @@ @@0x4
[[@@ @@0x4]] 0
(for ["j"]0 (< @"j" @@0x1) ["j"](+ @"j" 1)
{
[[@0x40]]0
[0x40] (+ @0x40 0x20) increment to next data slot
}
)
(stop) ;don't need to do any more
}
)
}
)
}
)
}
)
} | null | https://raw.githubusercontent.com/dennismckinnon/Ethereum-Contracts/25b5e7037da382dd95a1376fad81f936f6610b36/Magnet%20DB/Magnet-DB.lsp | lisp | Admin member pointer
Number of segments per item
Member pointer
Number of members
infohash list pointer
Set admin
Admin
Normal member
Not a member stop
Admin suicide (Format: "kill")
Admin and say kill suicide + deregister
Register new admin (Format: "regadm" 0xMemberaddress)
Store the new member in then next admin slot
Increment admin pointer
Register new member (Format: "regmem" 0xMemberaddress)
Store the new member in then next admin slot
Increment admin pointer
Delete normal member (must be an admin) (Format: "delmem" 0xMemberaddress)
delete and shuffle
don't need to do any more
Delete Admin member (must be an admin that is higher then the member you re deleting) (Format: "deladm" 0xMemberaddress)
Note: This is REALLY costly since order must be maintained
Flag for if caller appears before attempted deletee
Flag for finding deletee AFTER your number
Flip ok to delete flag (if the line comes after the next you can delete yourself)
If caller was found flip flag
delete and shuffle
If deletion has occured
Decrement admin pointer
Delete the last (duplicated guy)
Data telling which parts are available.
This is the infohash. It is required!
(not only must it exist but it has to be valid)
Calldata pointer
If this hash hasn't been added yet add to list !!!This works because creator is
Copy infohash into list
Increment infohash pointer
Special: Magnet link creator address
Copy data over (if you don't want to track this change to a constant)
Increment storage pointer (logic is that this will need to skip over creator regardless)
Copy out the new last digit
Data field size in data segments
Get the next data segment
Copy data over
Increment storage pointer
Copy out the new last digit
Data field size in data segments
Get the next data segment
Copy data over
Increment storage pointer
Copy out the new last digit
Data field size in data segments
Get the next data segment
Copy data over
Increment storage pointer
Copy out the new last digit
Data field size in data segments
Get the next data segment
Copy data over
Increment storage pointer
Delete magnet link and data (Format: "delmag" 0xinfohash) ??ADMIN priveleges needed?
delete and shuffle
don't need to do any more | Infohash Database manager with Membership structure
{
[0x0] "A"
(call 0x11d11764cd7f6ecda172e0b72370e6ea7f75f290 0 0 0 1 0 0)
}
{
You ca n't do anything if you are n't a member so check that first
(for ["i"] 0x10 (< @"i" @@0x0) ["i"](+ @"i" 1)
{
(when (= @@ @"i" (caller))
)
}
)
(unless @0x0
(for ["i"] 0x200 (< @"i" @@0x200) ["i"](+ @"i" 1)
{
(when (= @@ @"i" (caller))
)
}
)
)
First argument is txtype
No first argument stop
{
(call 0x11d11764cd7f6ecda172e0b72370e6ea7f75f290 0 0 0 0 0 0)
(suicide @@0x10)
}
)
(when (&& (= @0x20 "regadm") (= @0x20 1))
{
Get second data argument
(when @0x40
{
}
)
(stop)
}
)
(when (= @0x20 "regmem")
{
Get second data argument
(when @0x40
{
}
)
(stop)
}
)
(when (= @0x20 "delmem")
{
Get second data argument
(when @0x40
{
(for ["i"] 0x200 (< @"i" @@0x2) ["i"](+ @"i" 1)
{
{
[[0x2]] (- @@0x2 1)
[[@"i"]] @@ @@0x2
[[@@ @@0x2]] 0
}
)
}
)
}
)
}
)
(when (= @0x20 "deladm")
{
Get second data argument
(when @0x40
{
(for ["i"]0x10 (< @"i" @@0x0) ["i"](+ @"i" 1)
{
[[@"i"]] @@ (+ @"i" 1)
)
}
)
{
}
)
}
)
}
)
Add / edit Magnet link ( Format : " modmag " 0xIndicator ( 4 hex digits ) 0xinfohash " filetype " " quality " " title " " description " ) - See top
(when (= @0x20 "modmag")
{
{
{
}
)
FILETYPE ( 1 Seg )
[0x100] (MOD @0x40 0x10)
(when @0x100
{
(for ["i"]0 (> @"i" @0x500) ["i"](+ @"i" 1)
{
}
)
}
)
FILE QUALITY ( 1 Seg )
[0x100] (MOD @0x40 0x10)
(when @0x100
{
(for ["i"]0 (> @"i" @0x500) ["i"](+ @"i" 1)
{
}
)
}
)
FILE TITLE ( 2 )
[0x100] (MOD @0x40 0x10)
(when @0x100
{
(for ["i"]0 (> @"i" @0x500) ["i"](+ @"i" 1)
{
}
)
}
)
FILE DESCRIPTION ( 25 )
[0x100] (MOD @0x40 0x10)
(when @0x100
{
(for ["i"]0 (> @"i" @0x500) ["i"](+ @"i" 1)
{
}
)
}
)
}
)
(stop)
}
)
(when (= @0x20 "delmag")
{
Get second data argument
(when @0x40
{
(for ["i"] 0x1000 (< @"i" @@0x4) ["i"](+ @"i" 1)
{
{
[[0x4]] (- @@0x4 1)
[[@"i"]] @@ @@0x4
[[@@ @@0x4]] 0
(for ["j"]0 (< @"j" @@0x1) ["j"](+ @"j" 1)
{
[[@0x40]]0
[0x40] (+ @0x40 0x20) increment to next data slot
}
)
}
)
}
)
}
)
}
)
} |
24ea1f9bcdeb94ad415c007d96694dfbefdde01a08fa8278bbf99a17cba99f72 | spawnfest/eep49ers | wxIdleEvent.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
%%
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.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
-module(wxIdleEvent).
-include("wxe.hrl").
-export([getMode/0,moreRequested/1,requestMore/1,requestMore/2,setMode/1]).
%% inherited exports
-export([getId/1,getSkipped/1,getTimestamp/1,isCommandEvent/1,parent_class/1,
resumePropagation/2,shouldPropagate/1,skip/1,skip/2,stopPropagation/1]).
-type wxIdleEvent() :: wx:wx_object().
-include("wx.hrl").
-type wxIdleEventType() :: 'idle'.
-export_type([wxIdleEvent/0, wxIdle/0, wxIdleEventType/0]).
%% @hidden
parent_class(wxEvent) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
%% @doc See <a href="#wxidleeventgetmode">external documentation</a>.
%%<br /> Res = ?wxIDLE_PROCESS_ALL | ?wxIDLE_PROCESS_SPECIFIED
-spec getMode() -> wx:wx_enum().
getMode() ->
wxe_util:queue_cmd(?get_env(), ?wxIdleEvent_GetMode),
wxe_util:rec(?wxIdleEvent_GetMode).
%% @equiv requestMore(This, [])
-spec requestMore(This) -> 'ok' when
This::wxIdleEvent().
requestMore(This)
when is_record(This, wx_ref) ->
requestMore(This, []).
%% @doc See <a href="#wxidleeventrequestmore">external documentation</a>.
-spec requestMore(This, [Option]) -> 'ok' when
This::wxIdleEvent(),
Option :: {'needMore', boolean()}.
requestMore(#wx_ref{type=ThisT}=This, Options)
when is_list(Options) ->
?CLASS(ThisT,wxIdleEvent),
MOpts = fun({needMore, _needMore} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This, Opts,?get_env(),?wxIdleEvent_RequestMore).
%% @doc See <a href="#wxidleeventmorerequested">external documentation</a>.
-spec moreRequested(This) -> boolean() when
This::wxIdleEvent().
moreRequested(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxIdleEvent),
wxe_util:queue_cmd(This,?get_env(),?wxIdleEvent_MoreRequested),
wxe_util:rec(?wxIdleEvent_MoreRequested).
%% @doc See <a href="#wxidleeventsetmode">external documentation</a>.
%%<br /> Mode = ?wxIDLE_PROCESS_ALL | ?wxIDLE_PROCESS_SPECIFIED
-spec setMode(Mode) -> 'ok' when
Mode::wx:wx_enum().
setMode(Mode)
when is_integer(Mode) ->
wxe_util:queue_cmd(Mode,?get_env(),?wxIdleEvent_SetMode).
%% From wxEvent
%% @hidden
stopPropagation(This) -> wxEvent:stopPropagation(This).
%% @hidden
skip(This, Options) -> wxEvent:skip(This, Options).
%% @hidden
skip(This) -> wxEvent:skip(This).
%% @hidden
shouldPropagate(This) -> wxEvent:shouldPropagate(This).
%% @hidden
resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel).
%% @hidden
isCommandEvent(This) -> wxEvent:isCommandEvent(This).
%% @hidden
getTimestamp(This) -> wxEvent:getTimestamp(This).
%% @hidden
getSkipped(This) -> wxEvent:getSkipped(This).
%% @hidden
getId(This) -> wxEvent:getId(This).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxIdleEvent.erl | erlang |
%CopyrightBegin%
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.
%CopyrightEnd%
This file is generated DO NOT EDIT
inherited exports
@hidden
@doc See <a href="#wxidleeventgetmode">external documentation</a>.
<br /> Res = ?wxIDLE_PROCESS_ALL | ?wxIDLE_PROCESS_SPECIFIED
@equiv requestMore(This, [])
@doc See <a href="#wxidleeventrequestmore">external documentation</a>.
@doc See <a href="#wxidleeventmorerequested">external documentation</a>.
@doc See <a href="#wxidleeventsetmode">external documentation</a>.
<br /> Mode = ?wxIDLE_PROCESS_ALL | ?wxIDLE_PROCESS_SPECIFIED
From wxEvent
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(wxIdleEvent).
-include("wxe.hrl").
-export([getMode/0,moreRequested/1,requestMore/1,requestMore/2,setMode/1]).
-export([getId/1,getSkipped/1,getTimestamp/1,isCommandEvent/1,parent_class/1,
resumePropagation/2,shouldPropagate/1,skip/1,skip/2,stopPropagation/1]).
-type wxIdleEvent() :: wx:wx_object().
-include("wx.hrl").
-type wxIdleEventType() :: 'idle'.
-export_type([wxIdleEvent/0, wxIdle/0, wxIdleEventType/0]).
parent_class(wxEvent) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-spec getMode() -> wx:wx_enum().
getMode() ->
wxe_util:queue_cmd(?get_env(), ?wxIdleEvent_GetMode),
wxe_util:rec(?wxIdleEvent_GetMode).
-spec requestMore(This) -> 'ok' when
This::wxIdleEvent().
requestMore(This)
when is_record(This, wx_ref) ->
requestMore(This, []).
-spec requestMore(This, [Option]) -> 'ok' when
This::wxIdleEvent(),
Option :: {'needMore', boolean()}.
requestMore(#wx_ref{type=ThisT}=This, Options)
when is_list(Options) ->
?CLASS(ThisT,wxIdleEvent),
MOpts = fun({needMore, _needMore} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This, Opts,?get_env(),?wxIdleEvent_RequestMore).
-spec moreRequested(This) -> boolean() when
This::wxIdleEvent().
moreRequested(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxIdleEvent),
wxe_util:queue_cmd(This,?get_env(),?wxIdleEvent_MoreRequested),
wxe_util:rec(?wxIdleEvent_MoreRequested).
-spec setMode(Mode) -> 'ok' when
Mode::wx:wx_enum().
setMode(Mode)
when is_integer(Mode) ->
wxe_util:queue_cmd(Mode,?get_env(),?wxIdleEvent_SetMode).
stopPropagation(This) -> wxEvent:stopPropagation(This).
skip(This, Options) -> wxEvent:skip(This, Options).
skip(This) -> wxEvent:skip(This).
shouldPropagate(This) -> wxEvent:shouldPropagate(This).
resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel).
isCommandEvent(This) -> wxEvent:isCommandEvent(This).
getTimestamp(This) -> wxEvent:getTimestamp(This).
getSkipped(This) -> wxEvent:getSkipped(This).
getId(This) -> wxEvent:getId(This).
|
3811ef36be68f404346abca96d4a36201b774bd5d9d46c5e88d31c610273f5c9 | onedata/op-worker | nfs_helper_test_SUITE.erl | %%%-------------------------------------------------------------------
@author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
@doc Tests for NFS helper .
%%% @end
%%%-------------------------------------------------------------------
-module(nfs_helper_test_SUITE).
-author("Bartek Kryza").
-include("modules/storage/helpers/helpers.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include_lib("ctool/include/test/assertions.hrl").
-include_lib("ctool/include/test/test_utils.hrl").
-include_lib("ctool/include/test/performance.hrl").
%% export for ct
-export([all/0]).
%% tests
-export([create_test/1, mkdir_test/1, getattr_test/1, rmdir_test/1,
unlink_test/1, symlink_test/1, rename_test/1, chmod_test/1,
chown_test/1, flush_test/1, fsync_test/1, write_test/1,
multipart_write_test/1, truncate_test/1, write_read_test/1,
multipart_read_test/1, write_unlink_test/1,
write_read_truncate_unlink_test/1]).
%% test_bases
-export([create_test_base/1, write_test_base/1, multipart_write_test_base/1,
truncate_test_base/1, write_read_test_base/1, multipart_read_test_base/1,
write_unlink_test_base/1, write_read_truncate_unlink_test_base/1]).
-define(PERF_TEST_CASES, [
create_test,
write_test,
multipart_write_test,
truncate_test,
write_read_test,
multipart_read_test,
write_unlink_test,
write_read_truncate_unlink_test
]).
-define(TEST_CASES, [
flush_test, getattr_test, mkdir_test, rmdir_test, unlink_test, symlink_test,
rename_test, chmod_test, chown_test, fsync_test
]).
all() -> ?ALL(?TEST_CASES, ?PERF_TEST_CASES).
-define(NFS_VOLUME, <<"/nfsshare">>).
-define(NFS_VERSION, <<"3">>).
-define(FILE_ID_SIZE, 20).
-define(KB, 1024).
-define(MB, 1024 * 1024).
-define(TIMEOUT, timer:minutes(5)).
-define(THR_NUM(Value), [
{name, threads_num}, {value, Value}, {description, "Number of threads."}
]).
-define(OP_NUM(Value), lists:keyreplace(description, 1, ?OP_NUM(op, Value),
{description, "Number of operations."}
)).
-define(OP_NUM(Name, Value), [
{name, list_to_atom(atom_to_list(Name) ++ "_num")},
{value, Value},
{description, "Number of " ++ atom_to_list(Name) ++ " operations."}
]).
-define(OP_SIZE(Value), lists:keyreplace(description, 1, ?OP_SIZE(op, Value),
{description, "Size of single operation."}
)).
-define(OP_SIZE(Name, Value), [
{name, list_to_atom(atom_to_list(Name) ++ "_size")},
{value, Value},
{description, "Size of single " ++ atom_to_list(Name) ++ " operation."},
{unit, "MB"}
]).
-define(OP_BLK_SIZE(Name, Value), [
{name, list_to_atom(atom_to_list(Name) ++ "_blk_size")},
{value, Value},
{description, "Size of " ++ atom_to_list(Name) ++ " operation block."},
{unit, "KB"}
]).
-define(PERF_CFG(Name, Params), ?PERF_CFG(Name, "", Params)).
-define(PERF_CFG(Name, Description, Params), {config, [
{name, Name},
{description, Description},
{parameters, Params}
]}).
-define(REPEATS, 10).
-define(TEST_SIZE_BASE, 5).
%%%===================================================================
%%% Test functions
%%%===================================================================
create_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(write, 5), ?OP_SIZE(write, 1)]},
{description, "Multiple parallel write operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)])
]).
create_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
create(Helper, FileId)
end, lists:seq(1, ?config(write_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
write_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(write, 5), ?OP_SIZE(write, 1)]},
{description, "Multiple parallel write operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)])
]).
write_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, write),
write(Handle, ?config(write_size, Config) * ?MB),
release(Handle)
end, lists:seq(1, ?config(write_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
multipart_write_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?OP_SIZE(write, 1), ?OP_BLK_SIZE(write, 4)]},
{description, "Multipart write operation."},
?PERF_CFG(small, [?OP_SIZE(write, 2 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(write, ?TEST_SIZE_BASE)]),
?PERF_CFG(medium, [?OP_SIZE(write, 10 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(write, ?TEST_SIZE_BASE)]),
?PERF_CFG(large, [?OP_SIZE(write, 20 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(write, ?TEST_SIZE_BASE)])
]).
multipart_write_test_base(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, write),
Size = ?config(write_size, Config) * ?MB,
BlockSize = ?config(write_blk_size, Config) * ?KB,
multipart(Handle, fun write/3, Size, BlockSize),
release(Handle),
delete_helper(Helper).
truncate_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(truncate, 5)]},
{description, "Multiple parallel truncate operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(truncate, 2 * ?TEST_SIZE_BASE)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(truncate, 20 * ?TEST_SIZE_BASE)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(truncate, 20 * ?TEST_SIZE_BASE)])
]).
truncate_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
truncate(Helper, 0, 0)
end, lists:seq(1, ?config(truncate_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
write_read_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(5), ?OP_SIZE(1)]},
{description, "Multiple parallel write followed by read operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)])
]).
write_read_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, rdwr),
Content = write(Handle, 0, ?config(op_size, Config) * ?MB),
?assertEqual(Content, read(Handle, size(Content))),
release(Handle)
end, lists:seq(1, ?config(op_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
multipart_read_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?OP_SIZE(read, 1), ?OP_BLK_SIZE(read, 4)]},
{description, "Multipart read operation."},
?PERF_CFG(small, [?OP_SIZE(read, 2 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(read, ?TEST_SIZE_BASE)]),
?PERF_CFG(medium, [?OP_SIZE(read, 10 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(read, ?TEST_SIZE_BASE)]),
?PERF_CFG(large, [?OP_SIZE(read, 20 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(read, ?TEST_SIZE_BASE)])
]).
multipart_read_test_base(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, read),
Size = ?config(read_size, Config) * ?MB,
BlockSize = ?config(read_blk_size, Config) * ?KB,
write(Handle, 0, 0),
truncate(Helper, FileId, Size, 0),
multipart(Handle, fun read/3, 0, Size, BlockSize),
release(Handle),
delete_helper(Helper).
write_unlink_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(5), ?OP_SIZE(1)]},
{description, "Multiple parallel write followed by unlink operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)])
]).
write_unlink_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
Size = ?config(op_size, Config) * ?MB,
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, write),
write(Handle, 0, Size),
release(Handle),
unlink(Helper, FileId, Size)
end, lists:seq(1, ?config(op_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
write_read_truncate_unlink_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(5), ?OP_SIZE(1)]},
{description, "Multiple parallel sequence of write, read, truncate
and unlink operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)])
]).
write_read_truncate_unlink_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, rdwr),
Size = ?config(op_size, Config) * ?MB,
Content = write(Handle, 0, Size),
?assertEqual(Content, read(Handle, size(Content))),
truncate(Helper, FileId, 0, Size),
release(Handle),
unlink(Helper, FileId, 0)
end, lists:seq(1, ?config(op_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
getattr_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
?assertMatch({ok, #statbuf{}}, call(Helper, getattr, [FileId])).
mkdir_test(Config) ->
Helper = new_helper(Config),
DirId = random_file_id(),
?assertMatch(ok, mkdir(Helper, DirId)).
rmdir_test(Config) ->
Helper = new_helper(Config),
DirId = random_file_id(),
?assertMatch(ok, mkdir(Helper, DirId)),
?assertMatch(ok, call(Helper, rmdir, [DirId])).
unlink_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, unlink, [FileId, 0])).
symlink_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
SymLinkId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, symlink, [FileId, SymLinkId])).
rename_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
NewFileId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, rename, [FileId, NewFileId])),
?assertMatch({ok, _}, open(Helper, NewFileId, read)).
chmod_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, chmod, [FileId, 0])).
chown_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, chown, [FileId, -1, -1])).
flush_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = call(Helper, open, [FileId, write]),
write(Handle, 0, 1024),
?assertMatch(ok, call(Handle, flush, [])).
fsync_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = call(Helper, open, [FileId, write]),
write(Handle, 0, 1024),
?assertMatch(ok, call(Handle, fsync, [false])).
%%%===================================================================
Internal functions
%%%===================================================================
new_helper(Config) ->
process_flag(trap_exit, true),
[Node | _] = ?config(op_worker_nodes, Config),
NFSConfig = ?config(nfs, ?config(nfs, ?config(storages, Config))),
UserCtx = #{<<"uid">> => <<"0">>, <<"gid">> => <<"0">>},
{ok, Helper} = helper:new_helper(
?NFS_HELPER_NAME,
#{
<<"volume">> => ?NFS_VOLUME,
<<"version">> => ?NFS_VERSION,
<<"host">> => atom_to_binary(?config(host, NFSConfig), utf8),
<<"storagePathType">> => ?CANONICAL_STORAGE_PATH,
<<"skipStorageDetection">> => <<"false">>
},
UserCtx
),
spawn_link(Node, fun() ->
helper_loop(Helper, UserCtx)
end).
delete_helper(Helper) ->
Helper ! exit.
helper_loop(Helper, UserCtx) ->
Handle = helpers:get_helper_handle(Helper, UserCtx),
helper_loop(Handle).
helper_loop(Handle) ->
receive
exit ->
ok;
{Pid, {run_helpers, open, Args}} ->
{ok, FileHandle} = apply(helpers, open, [Handle | Args]),
HandlePid = spawn_link(fun() -> helper_handle_loop(FileHandle) end),
Pid ! {self(), {ok, HandlePid}},
helper_loop(Handle);
{Pid, {run_helpers, Method, Args}} ->
Pid ! {self(), apply(helpers, Method, [Handle | Args])},
helper_loop(Handle)
end.
helper_handle_loop(FileHandle) ->
process_flag(trap_exit, true),
receive
{'EXIT', _, _} ->
helpers:release(FileHandle);
{Pid, {run_helpers, Method, Args}} ->
Pid ! {self(), apply(helpers, Method, [FileHandle | Args])},
helper_handle_loop(FileHandle)
end.
call(Helper, Method, Args) ->
Helper ! {self(), {run_helpers, Method, Args}},
receive_result(Helper).
receive_result(Helper) ->
receive
{'EXIT', Helper, normal} -> receive_result(Helper);
{'EXIT', Helper, Reason} -> {error, Reason};
{Helper, Ans} -> Ans
after
?TIMEOUT -> {error, timeout}
end.
run(Fun, ThreadsNum) ->
Results = lists_utils:pmap(fun(_) ->
Fun(),
ok
end, lists:seq(1, ThreadsNum)),
?assert(lists:all(fun(Result) -> Result =:= ok end, Results)).
random_file_id() ->
re:replace(http_utils:base64url_encode(crypto:strong_rand_bytes(?FILE_ID_SIZE)),
"\\W", "", [global, {return, binary}]).
create(Helper, FileId) ->
call(Helper, mknod, [FileId, ?DEFAULT_FILE_PERMS, reg]).
mkdir(Helper, FileId) ->
call(Helper, mkdir, [FileId, ?DEFAULT_DIR_PERMS]).
open(Helper, FileId, Flag) ->
call(Helper, open, [FileId, Flag]).
release(FileHandle) ->
call(FileHandle, release, []).
read(FileHandle, Size) ->
read(FileHandle, 0, Size).
read(FileHandle, Offset, Size) ->
{ok, Content} =
?assertMatch({ok, _}, call(FileHandle, read, [Offset, Size])),
Content.
write(FileHandle, Size) ->
write(FileHandle, 0, Size).
write(FileHandle, Offset, Size) ->
Content = crypto:strong_rand_bytes(Size),
ActualSize = size(Content),
?assertEqual({ok, ActualSize}, call(FileHandle, write, [Offset, Content])),
Content.
truncate(Helper, Size, CurrentSize) ->
FileId = random_file_id(),
create(Helper, FileId),
truncate(Helper, FileId, Size, CurrentSize).
truncate(Helper, FileId, Size, CurrentSize) ->
?assertEqual(ok, call(Helper, truncate, [FileId, Size, CurrentSize])).
unlink(Helper, FileId, CurrentSize) ->
?assertEqual(ok, call(Helper, unlink, [FileId, CurrentSize])).
multipart(Helper, Method, Size, BlockSize) ->
multipart(Helper, Method, 0, Size, BlockSize).
multipart(_Helper, _Method, _Offset, 0, _BlockSize) ->
ok;
multipart(Helper, Method, Offset, Size, BlockSize)
when Size >= BlockSize ->
Method(Helper, Offset, BlockSize),
multipart(Helper, Method, Offset + BlockSize, Size - BlockSize, BlockSize);
multipart(Helper, Method, Offset, Size, BlockSize) ->
Method(Helper, Offset, Size),
multipart(Helper, Method, Offset + Size, 0, BlockSize).
| null | https://raw.githubusercontent.com/onedata/op-worker/f220870d18ec6a6d7201ca3f32b5d3b2e401e291/test_distributed/nfs_helper_test_SUITE.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@end
-------------------------------------------------------------------
export for ct
tests
test_bases
===================================================================
Test functions
===================================================================
===================================================================
=================================================================== | @author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
@doc Tests for NFS helper .
-module(nfs_helper_test_SUITE).
-author("Bartek Kryza").
-include("modules/storage/helpers/helpers.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include_lib("ctool/include/test/assertions.hrl").
-include_lib("ctool/include/test/test_utils.hrl").
-include_lib("ctool/include/test/performance.hrl").
-export([all/0]).
-export([create_test/1, mkdir_test/1, getattr_test/1, rmdir_test/1,
unlink_test/1, symlink_test/1, rename_test/1, chmod_test/1,
chown_test/1, flush_test/1, fsync_test/1, write_test/1,
multipart_write_test/1, truncate_test/1, write_read_test/1,
multipart_read_test/1, write_unlink_test/1,
write_read_truncate_unlink_test/1]).
-export([create_test_base/1, write_test_base/1, multipart_write_test_base/1,
truncate_test_base/1, write_read_test_base/1, multipart_read_test_base/1,
write_unlink_test_base/1, write_read_truncate_unlink_test_base/1]).
-define(PERF_TEST_CASES, [
create_test,
write_test,
multipart_write_test,
truncate_test,
write_read_test,
multipart_read_test,
write_unlink_test,
write_read_truncate_unlink_test
]).
-define(TEST_CASES, [
flush_test, getattr_test, mkdir_test, rmdir_test, unlink_test, symlink_test,
rename_test, chmod_test, chown_test, fsync_test
]).
all() -> ?ALL(?TEST_CASES, ?PERF_TEST_CASES).
-define(NFS_VOLUME, <<"/nfsshare">>).
-define(NFS_VERSION, <<"3">>).
-define(FILE_ID_SIZE, 20).
-define(KB, 1024).
-define(MB, 1024 * 1024).
-define(TIMEOUT, timer:minutes(5)).
-define(THR_NUM(Value), [
{name, threads_num}, {value, Value}, {description, "Number of threads."}
]).
-define(OP_NUM(Value), lists:keyreplace(description, 1, ?OP_NUM(op, Value),
{description, "Number of operations."}
)).
-define(OP_NUM(Name, Value), [
{name, list_to_atom(atom_to_list(Name) ++ "_num")},
{value, Value},
{description, "Number of " ++ atom_to_list(Name) ++ " operations."}
]).
-define(OP_SIZE(Value), lists:keyreplace(description, 1, ?OP_SIZE(op, Value),
{description, "Size of single operation."}
)).
-define(OP_SIZE(Name, Value), [
{name, list_to_atom(atom_to_list(Name) ++ "_size")},
{value, Value},
{description, "Size of single " ++ atom_to_list(Name) ++ " operation."},
{unit, "MB"}
]).
-define(OP_BLK_SIZE(Name, Value), [
{name, list_to_atom(atom_to_list(Name) ++ "_blk_size")},
{value, Value},
{description, "Size of " ++ atom_to_list(Name) ++ " operation block."},
{unit, "KB"}
]).
-define(PERF_CFG(Name, Params), ?PERF_CFG(Name, "", Params)).
-define(PERF_CFG(Name, Description, Params), {config, [
{name, Name},
{description, Description},
{parameters, Params}
]}).
-define(REPEATS, 10).
-define(TEST_SIZE_BASE, 5).
create_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(write, 5), ?OP_SIZE(write, 1)]},
{description, "Multiple parallel write operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)])
]).
create_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
create(Helper, FileId)
end, lists:seq(1, ?config(write_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
write_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(write, 5), ?OP_SIZE(write, 1)]},
{description, "Multiple parallel write operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(write, 2 * ?TEST_SIZE_BASE), ?OP_SIZE(write, 1)])
]).
write_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, write),
write(Handle, ?config(write_size, Config) * ?MB),
release(Handle)
end, lists:seq(1, ?config(write_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
multipart_write_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?OP_SIZE(write, 1), ?OP_BLK_SIZE(write, 4)]},
{description, "Multipart write operation."},
?PERF_CFG(small, [?OP_SIZE(write, 2 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(write, ?TEST_SIZE_BASE)]),
?PERF_CFG(medium, [?OP_SIZE(write, 10 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(write, ?TEST_SIZE_BASE)]),
?PERF_CFG(large, [?OP_SIZE(write, 20 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(write, ?TEST_SIZE_BASE)])
]).
multipart_write_test_base(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, write),
Size = ?config(write_size, Config) * ?MB,
BlockSize = ?config(write_blk_size, Config) * ?KB,
multipart(Handle, fun write/3, Size, BlockSize),
release(Handle),
delete_helper(Helper).
truncate_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(truncate, 5)]},
{description, "Multiple parallel truncate operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(truncate, 2 * ?TEST_SIZE_BASE)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(truncate, 20 * ?TEST_SIZE_BASE)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(truncate, 20 * ?TEST_SIZE_BASE)])
]).
truncate_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
truncate(Helper, 0, 0)
end, lists:seq(1, ?config(truncate_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
write_read_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(5), ?OP_SIZE(1)]},
{description, "Multiple parallel write followed by read operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)])
]).
write_read_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, rdwr),
Content = write(Handle, 0, ?config(op_size, Config) * ?MB),
?assertEqual(Content, read(Handle, size(Content))),
release(Handle)
end, lists:seq(1, ?config(op_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
multipart_read_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?OP_SIZE(read, 1), ?OP_BLK_SIZE(read, 4)]},
{description, "Multipart read operation."},
?PERF_CFG(small, [?OP_SIZE(read, 2 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(read, ?TEST_SIZE_BASE)]),
?PERF_CFG(medium, [?OP_SIZE(read, 10 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(read, ?TEST_SIZE_BASE)]),
?PERF_CFG(large, [?OP_SIZE(read, 20 * ?TEST_SIZE_BASE), ?OP_BLK_SIZE(read, ?TEST_SIZE_BASE)])
]).
multipart_read_test_base(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, read),
Size = ?config(read_size, Config) * ?MB,
BlockSize = ?config(read_blk_size, Config) * ?KB,
write(Handle, 0, 0),
truncate(Helper, FileId, Size, 0),
multipart(Handle, fun read/3, 0, Size, BlockSize),
release(Handle),
delete_helper(Helper).
write_unlink_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(5), ?OP_SIZE(1)]},
{description, "Multiple parallel write followed by unlink operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)])
]).
write_unlink_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
Size = ?config(op_size, Config) * ?MB,
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, write),
write(Handle, 0, Size),
release(Handle),
unlink(Helper, FileId, Size)
end, lists:seq(1, ?config(op_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
write_read_truncate_unlink_test(Config) ->
?PERFORMANCE(Config, [
{repeats, ?REPEATS},
{success_rate, 100},
{parameters, [?THR_NUM(1), ?OP_NUM(5), ?OP_SIZE(1)]},
{description, "Multiple parallel sequence of write, read, truncate
and unlink operations."},
?PERF_CFG(small, [?THR_NUM(?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(medium, [?THR_NUM(2 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)]),
?PERF_CFG(large, [?THR_NUM(4 * ?TEST_SIZE_BASE), ?OP_NUM(2 * ?TEST_SIZE_BASE), ?OP_SIZE(1)])
]).
write_read_truncate_unlink_test_base(Config) ->
run(fun() ->
Helper = new_helper(Config),
lists:foreach(fun(_) ->
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = open(Helper, FileId, rdwr),
Size = ?config(op_size, Config) * ?MB,
Content = write(Handle, 0, Size),
?assertEqual(Content, read(Handle, size(Content))),
truncate(Helper, FileId, 0, Size),
release(Handle),
unlink(Helper, FileId, 0)
end, lists:seq(1, ?config(op_num, Config))),
delete_helper(Helper)
end, ?config(threads_num, Config)).
getattr_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
?assertMatch({ok, #statbuf{}}, call(Helper, getattr, [FileId])).
mkdir_test(Config) ->
Helper = new_helper(Config),
DirId = random_file_id(),
?assertMatch(ok, mkdir(Helper, DirId)).
rmdir_test(Config) ->
Helper = new_helper(Config),
DirId = random_file_id(),
?assertMatch(ok, mkdir(Helper, DirId)),
?assertMatch(ok, call(Helper, rmdir, [DirId])).
unlink_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, unlink, [FileId, 0])).
symlink_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
SymLinkId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, symlink, [FileId, SymLinkId])).
rename_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
NewFileId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, rename, [FileId, NewFileId])),
?assertMatch({ok, _}, open(Helper, NewFileId, read)).
chmod_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, chmod, [FileId, 0])).
chown_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
?assertMatch(ok, call(Helper, chown, [FileId, -1, -1])).
flush_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = call(Helper, open, [FileId, write]),
write(Handle, 0, 1024),
?assertMatch(ok, call(Handle, flush, [])).
fsync_test(Config) ->
Helper = new_helper(Config),
FileId = random_file_id(),
create(Helper, FileId),
{ok, Handle} = call(Helper, open, [FileId, write]),
write(Handle, 0, 1024),
?assertMatch(ok, call(Handle, fsync, [false])).
Internal functions
new_helper(Config) ->
process_flag(trap_exit, true),
[Node | _] = ?config(op_worker_nodes, Config),
NFSConfig = ?config(nfs, ?config(nfs, ?config(storages, Config))),
UserCtx = #{<<"uid">> => <<"0">>, <<"gid">> => <<"0">>},
{ok, Helper} = helper:new_helper(
?NFS_HELPER_NAME,
#{
<<"volume">> => ?NFS_VOLUME,
<<"version">> => ?NFS_VERSION,
<<"host">> => atom_to_binary(?config(host, NFSConfig), utf8),
<<"storagePathType">> => ?CANONICAL_STORAGE_PATH,
<<"skipStorageDetection">> => <<"false">>
},
UserCtx
),
spawn_link(Node, fun() ->
helper_loop(Helper, UserCtx)
end).
delete_helper(Helper) ->
Helper ! exit.
helper_loop(Helper, UserCtx) ->
Handle = helpers:get_helper_handle(Helper, UserCtx),
helper_loop(Handle).
helper_loop(Handle) ->
receive
exit ->
ok;
{Pid, {run_helpers, open, Args}} ->
{ok, FileHandle} = apply(helpers, open, [Handle | Args]),
HandlePid = spawn_link(fun() -> helper_handle_loop(FileHandle) end),
Pid ! {self(), {ok, HandlePid}},
helper_loop(Handle);
{Pid, {run_helpers, Method, Args}} ->
Pid ! {self(), apply(helpers, Method, [Handle | Args])},
helper_loop(Handle)
end.
helper_handle_loop(FileHandle) ->
process_flag(trap_exit, true),
receive
{'EXIT', _, _} ->
helpers:release(FileHandle);
{Pid, {run_helpers, Method, Args}} ->
Pid ! {self(), apply(helpers, Method, [FileHandle | Args])},
helper_handle_loop(FileHandle)
end.
call(Helper, Method, Args) ->
Helper ! {self(), {run_helpers, Method, Args}},
receive_result(Helper).
receive_result(Helper) ->
receive
{'EXIT', Helper, normal} -> receive_result(Helper);
{'EXIT', Helper, Reason} -> {error, Reason};
{Helper, Ans} -> Ans
after
?TIMEOUT -> {error, timeout}
end.
run(Fun, ThreadsNum) ->
Results = lists_utils:pmap(fun(_) ->
Fun(),
ok
end, lists:seq(1, ThreadsNum)),
?assert(lists:all(fun(Result) -> Result =:= ok end, Results)).
random_file_id() ->
re:replace(http_utils:base64url_encode(crypto:strong_rand_bytes(?FILE_ID_SIZE)),
"\\W", "", [global, {return, binary}]).
create(Helper, FileId) ->
call(Helper, mknod, [FileId, ?DEFAULT_FILE_PERMS, reg]).
mkdir(Helper, FileId) ->
call(Helper, mkdir, [FileId, ?DEFAULT_DIR_PERMS]).
open(Helper, FileId, Flag) ->
call(Helper, open, [FileId, Flag]).
release(FileHandle) ->
call(FileHandle, release, []).
read(FileHandle, Size) ->
read(FileHandle, 0, Size).
read(FileHandle, Offset, Size) ->
{ok, Content} =
?assertMatch({ok, _}, call(FileHandle, read, [Offset, Size])),
Content.
write(FileHandle, Size) ->
write(FileHandle, 0, Size).
write(FileHandle, Offset, Size) ->
Content = crypto:strong_rand_bytes(Size),
ActualSize = size(Content),
?assertEqual({ok, ActualSize}, call(FileHandle, write, [Offset, Content])),
Content.
truncate(Helper, Size, CurrentSize) ->
FileId = random_file_id(),
create(Helper, FileId),
truncate(Helper, FileId, Size, CurrentSize).
truncate(Helper, FileId, Size, CurrentSize) ->
?assertEqual(ok, call(Helper, truncate, [FileId, Size, CurrentSize])).
unlink(Helper, FileId, CurrentSize) ->
?assertEqual(ok, call(Helper, unlink, [FileId, CurrentSize])).
multipart(Helper, Method, Size, BlockSize) ->
multipart(Helper, Method, 0, Size, BlockSize).
multipart(_Helper, _Method, _Offset, 0, _BlockSize) ->
ok;
multipart(Helper, Method, Offset, Size, BlockSize)
when Size >= BlockSize ->
Method(Helper, Offset, BlockSize),
multipart(Helper, Method, Offset + BlockSize, Size - BlockSize, BlockSize);
multipart(Helper, Method, Offset, Size, BlockSize) ->
Method(Helper, Offset, Size),
multipart(Helper, Method, Offset + Size, 0, BlockSize).
|
09a3a84976a0e4d9c5d17b1b116f3a7b44426c3f14d4a56ca9b8d13dfca811f6 | vikram/lisplibraries | swank-gray.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
swank-gray.lisp stream based IO redirection .
;;;
Created 2003
;;;
;;; This code has been placed in the Public Domain. All warranties
;;; are disclaimed.
;;;
(in-package :swank-backend)
(defclass slime-output-stream (fundamental-character-output-stream)
((output-fn :initarg :output-fn)
(buffer :initform (make-string 8000))
(fill-pointer :initform 0)
(column :initform 0)
(lock :initform (make-lock :name "buffer write lock"))))
(defmacro with-slime-output-stream (stream &body body)
`(with-slots (lock output-fn buffer fill-pointer column) ,stream
(call-with-lock-held lock (lambda () ,@body))))
(defmethod stream-write-char ((stream slime-output-stream) char)
(with-slime-output-stream stream
(setf (schar buffer fill-pointer) char)
(incf fill-pointer)
(incf column)
(when (char= #\newline char)
(setf column 0))
(when (= fill-pointer (length buffer))
(finish-output stream)))
char)
(defmethod stream-write-string ((stream slime-output-stream) string
&optional start end)
(with-slime-output-stream stream
(let* ((start (or start 0))
(end (or end (length string)))
(len (length buffer))
(count (- end start))
(free (- len fill-pointer)))
(when (>= count free)
(stream-finish-output stream))
(cond ((< count len)
(replace buffer string :start1 fill-pointer
:start2 start :end2 end)
(incf fill-pointer count))
(t
(funcall output-fn (subseq string start end))))
(let ((last-newline (position #\newline string :from-end t
:start start :end end)))
(setf column (if last-newline
(- end last-newline 1)
(+ column count))))))
string)
(defmethod stream-line-column ((stream slime-output-stream))
(with-slime-output-stream stream column))
(defmethod stream-line-length ((stream slime-output-stream))
75)
(defmethod stream-finish-output ((stream slime-output-stream))
(with-slime-output-stream stream
(unless (zerop fill-pointer)
(funcall output-fn (subseq buffer 0 fill-pointer))
(setf fill-pointer 0)))
nil)
(defmethod stream-force-output ((stream slime-output-stream))
(stream-finish-output stream))
(defmethod stream-fresh-line ((stream slime-output-stream))
(with-slime-output-stream stream
(cond ((zerop column) nil)
(t (terpri stream) t))))
(defclass slime-input-stream (fundamental-character-input-stream)
((input-fn :initarg :input-fn)
(buffer :initform "") (index :initform 0)
(lock :initform (make-lock :name "buffer read lock"))))
(defmethod stream-read-char ((s slime-input-stream))
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index input-fn) s
(when (= index (length buffer))
(let ((string (funcall input-fn)))
(cond ((zerop (length string))
(return-from stream-read-char :eof))
(t
(setf buffer string)
(setf index 0)))))
(assert (plusp (length buffer)))
(prog1 (aref buffer index) (incf index))))))
(defmethod stream-listen ((s slime-input-stream))
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index) s
(< index (length buffer))))))
(defmethod stream-unread-char ((s slime-input-stream) char)
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index) s
(decf index)
(cond ((eql (aref buffer index) char)
(setf (aref buffer index) char))
(t
(warn "stream-unread-char: ignoring ~S (expected ~S)"
char (aref buffer index)))))))
nil)
(defmethod stream-clear-input ((s slime-input-stream))
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index) s
(setf buffer ""
index 0))))
nil)
(defmethod stream-line-column ((s slime-input-stream))
nil)
(defmethod stream-line-length ((s slime-input-stream))
75)
CLISP extensions
;; We have to define an additional method for the sake of the C
function listen_char ( see src / stream.d ) , on which SYS::READ - FORM
;; depends.
We could make do with either of the two methods below .
(defmethod stream-read-char-no-hang ((s slime-input-stream))
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index) s
(when (< index (length buffer))
(prog1 (aref buffer index) (incf index)))))))
This CLISP extension is what listen_char actually calls . The
;; default method would call STREAM-READ-CHAR-NO-HANG, so it is a bit
;; more efficient to define it directly.
(defmethod stream-read-char-will-hang-p ((s slime-input-stream))
(with-slots (buffer index) s
(= index (length buffer))))
;;;
(defimplementation make-output-stream (write-string)
(make-instance 'slime-output-stream :output-fn write-string))
(defimplementation make-input-stream (read-string)
(make-instance 'slime-input-stream :input-fn read-string))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/slime/swank-gray.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
This code has been placed in the Public Domain. All warranties
are disclaimed.
We have to define an additional method for the sake of the C
depends.
default method would call STREAM-READ-CHAR-NO-HANG, so it is a bit
more efficient to define it directly.
| swank-gray.lisp stream based IO redirection .
Created 2003
(in-package :swank-backend)
(defclass slime-output-stream (fundamental-character-output-stream)
((output-fn :initarg :output-fn)
(buffer :initform (make-string 8000))
(fill-pointer :initform 0)
(column :initform 0)
(lock :initform (make-lock :name "buffer write lock"))))
(defmacro with-slime-output-stream (stream &body body)
`(with-slots (lock output-fn buffer fill-pointer column) ,stream
(call-with-lock-held lock (lambda () ,@body))))
(defmethod stream-write-char ((stream slime-output-stream) char)
(with-slime-output-stream stream
(setf (schar buffer fill-pointer) char)
(incf fill-pointer)
(incf column)
(when (char= #\newline char)
(setf column 0))
(when (= fill-pointer (length buffer))
(finish-output stream)))
char)
(defmethod stream-write-string ((stream slime-output-stream) string
&optional start end)
(with-slime-output-stream stream
(let* ((start (or start 0))
(end (or end (length string)))
(len (length buffer))
(count (- end start))
(free (- len fill-pointer)))
(when (>= count free)
(stream-finish-output stream))
(cond ((< count len)
(replace buffer string :start1 fill-pointer
:start2 start :end2 end)
(incf fill-pointer count))
(t
(funcall output-fn (subseq string start end))))
(let ((last-newline (position #\newline string :from-end t
:start start :end end)))
(setf column (if last-newline
(- end last-newline 1)
(+ column count))))))
string)
(defmethod stream-line-column ((stream slime-output-stream))
(with-slime-output-stream stream column))
(defmethod stream-line-length ((stream slime-output-stream))
75)
(defmethod stream-finish-output ((stream slime-output-stream))
(with-slime-output-stream stream
(unless (zerop fill-pointer)
(funcall output-fn (subseq buffer 0 fill-pointer))
(setf fill-pointer 0)))
nil)
(defmethod stream-force-output ((stream slime-output-stream))
(stream-finish-output stream))
(defmethod stream-fresh-line ((stream slime-output-stream))
(with-slime-output-stream stream
(cond ((zerop column) nil)
(t (terpri stream) t))))
(defclass slime-input-stream (fundamental-character-input-stream)
((input-fn :initarg :input-fn)
(buffer :initform "") (index :initform 0)
(lock :initform (make-lock :name "buffer read lock"))))
(defmethod stream-read-char ((s slime-input-stream))
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index input-fn) s
(when (= index (length buffer))
(let ((string (funcall input-fn)))
(cond ((zerop (length string))
(return-from stream-read-char :eof))
(t
(setf buffer string)
(setf index 0)))))
(assert (plusp (length buffer)))
(prog1 (aref buffer index) (incf index))))))
(defmethod stream-listen ((s slime-input-stream))
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index) s
(< index (length buffer))))))
(defmethod stream-unread-char ((s slime-input-stream) char)
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index) s
(decf index)
(cond ((eql (aref buffer index) char)
(setf (aref buffer index) char))
(t
(warn "stream-unread-char: ignoring ~S (expected ~S)"
char (aref buffer index)))))))
nil)
(defmethod stream-clear-input ((s slime-input-stream))
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index) s
(setf buffer ""
index 0))))
nil)
(defmethod stream-line-column ((s slime-input-stream))
nil)
(defmethod stream-line-length ((s slime-input-stream))
75)
CLISP extensions
function listen_char ( see src / stream.d ) , on which SYS::READ - FORM
We could make do with either of the two methods below .
(defmethod stream-read-char-no-hang ((s slime-input-stream))
(call-with-lock-held
(slot-value s 'lock)
(lambda ()
(with-slots (buffer index) s
(when (< index (length buffer))
(prog1 (aref buffer index) (incf index)))))))
This CLISP extension is what listen_char actually calls . The
(defmethod stream-read-char-will-hang-p ((s slime-input-stream))
(with-slots (buffer index) s
(= index (length buffer))))
(defimplementation make-output-stream (write-string)
(make-instance 'slime-output-stream :output-fn write-string))
(defimplementation make-input-stream (read-string)
(make-instance 'slime-input-stream :input-fn read-string))
|
f74b77a47e2b0c1a7702b444658120a1d6aac968003eca8789f237eb8761ccd1 | binsec/haunted | prover.mli | (**************************************************************************)
This file is part of BINSEC .
(* *)
Copyright ( C ) 2016 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It 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 Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
type executable = string ;;
type arguments = string array ;;
module Command : sig
type t = private {
executable : executable;
arguments : arguments;
} ;;
val to_string : t -> string ;;
end
type t = Formula_options.solver ;;
val pp : Format.formatter -> t -> unit ;;
val is_boolector : t -> bool ;;
val is_yices : t -> bool ;;
(** {2 Accessors} *)
val name_of : t -> string ;;
val command : ?incremental:bool -> int -> t -> Command.t ;;
val command_string : ?incremental:bool -> int -> t -> string ;;
val timeout_s : int -> t -> int ;;
| null | https://raw.githubusercontent.com/binsec/haunted/7ffc5f4072950fe138f53fe953ace98fff181c73/src/formula/prover.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It 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 Lesser General Public License for more details.
************************************************************************
* {2 Accessors} | This file is part of BINSEC .
Copyright ( C ) 2016 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
type executable = string ;;
type arguments = string array ;;
module Command : sig
type t = private {
executable : executable;
arguments : arguments;
} ;;
val to_string : t -> string ;;
end
type t = Formula_options.solver ;;
val pp : Format.formatter -> t -> unit ;;
val is_boolector : t -> bool ;;
val is_yices : t -> bool ;;
val name_of : t -> string ;;
val command : ?incremental:bool -> int -> t -> Command.t ;;
val command_string : ?incremental:bool -> int -> t -> string ;;
val timeout_s : int -> t -> int ;;
|
3f5339c6e801dd9e962c7718b59b49905513d4fab233f36dc21ad7080588f22f | alexandergunnarson/quantum | core.cljc | (ns quantum.test.core.type.core
(:require
[quantum.core.type.core :as this]
[quantum.core.test
:refer [deftest is testing]]))
#?(:clj
(deftest test|nth-elem-type|clj
(is (= "[D" (this/nth-elem-type|clj "[D" 0)))
(is (= 'double (this/nth-elem-type|clj "[D" 1)))
(is (= 'long (this/nth-elem-type|clj "[J" 1)))
(is (= "[Z" (this/nth-elem-type|clj "[[Z" 1)))
(is (= 'boolean (this/nth-elem-type|clj "[[Z" 2)))
(is (= "[Ljava.lang.Object;" (this/nth-elem-type|clj "[[Ljava.lang.Object;" 1)))
(is (= 'java.lang.Object (this/nth-elem-type|clj "[Ljava.lang.Object;" 1)))
(is (thrown? Throwable (this/nth-elem-type|clj "[[Z" 3)))
(is (thrown? Throwable (this/nth-elem-type|clj 'boolean 0)))
(is (thrown? Throwable (this/nth-elem-type|clj Boolean 0)))
(is (thrown? Throwable (this/nth-elem-type|clj "Boolean" 0)))))
| null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/test/quantum/test/core/type/core.cljc | clojure | (ns quantum.test.core.type.core
(:require
[quantum.core.type.core :as this]
[quantum.core.test
:refer [deftest is testing]]))
#?(:clj
(deftest test|nth-elem-type|clj
(is (= "[D" (this/nth-elem-type|clj "[D" 0)))
(is (= 'double (this/nth-elem-type|clj "[D" 1)))
(is (= 'long (this/nth-elem-type|clj "[J" 1)))
(is (= "[Z" (this/nth-elem-type|clj "[[Z" 1)))
(is (= 'boolean (this/nth-elem-type|clj "[[Z" 2)))
(is (= "[Ljava.lang.Object;" (this/nth-elem-type|clj "[[Ljava.lang.Object;" 1)))
(is (= 'java.lang.Object (this/nth-elem-type|clj "[Ljava.lang.Object;" 1)))
(is (thrown? Throwable (this/nth-elem-type|clj "[[Z" 3)))
(is (thrown? Throwable (this/nth-elem-type|clj 'boolean 0)))
(is (thrown? Throwable (this/nth-elem-type|clj Boolean 0)))
(is (thrown? Throwable (this/nth-elem-type|clj "Boolean" 0)))))
| |
949f09553e926d75cbb23ad01ee04fea8bcd9b9bc78c389cd09b7dfdc222b740 | tsdye/harris-matrix | package.lisp | package.lisp
(defpackage #:hm
(:use
:common-lisp
:cl-colors
:py-configparser
:alexandria
:inferior-shell)
(:export
:show-classifiable-attributes
:show-classifiers
:show-map
:write-default-configuration
:write-configuration
:reset-option
:set-input-file
:set-output-file
:show-configuration-options
:show-configuration-sections
:read-configuration-from-files
:run-project
:run-project/example
:write-classifier
:hm-main))
| null | https://raw.githubusercontent.com/tsdye/harris-matrix/9229fa7dfbfbfe23035ccfda8d89345d750e003f/src/package.lisp | lisp | package.lisp
(defpackage #:hm
(:use
:common-lisp
:cl-colors
:py-configparser
:alexandria
:inferior-shell)
(:export
:show-classifiable-attributes
:show-classifiers
:show-map
:write-default-configuration
:write-configuration
:reset-option
:set-input-file
:set-output-file
:show-configuration-options
:show-configuration-sections
:read-configuration-from-files
:run-project
:run-project/example
:write-classifier
:hm-main))
| |
b085a84e6c3edaedbf8186e6bb35175401f1ea6ba53ec9bc259f20e427245297 | tadeuzagallo/verve-lang | Main.hs | module Main where
import Compile
import Options
import Repl
import Runners
import System.Console.CmdArgs
options :: Options
options
= Options { dump_ir = def &= help "Dump the intermediate representation of the program"
, dump_bytecode = def &= help "Dump the bytecode representation of the program"
, dump_serialized_bytecode = def &= help "Dump the binary representation of the bytecode for program"
, dump_statements = def &= help "Dump the value and type of each statement in the program"
, files = def &= args &= typFile
}
main :: IO ()
main = do
args <- cmdArgs options
if null (files args) then runPipeline repl args else
if dump_statements args
then runPipeline (evalProgram runEach) args
else runPipeline (evalProgram runAll) args
| null | https://raw.githubusercontent.com/tadeuzagallo/verve-lang/c7db1f5d4bb399b6c2623dd2444a981b5aba1aa4/app/Main.hs | haskell | module Main where
import Compile
import Options
import Repl
import Runners
import System.Console.CmdArgs
options :: Options
options
= Options { dump_ir = def &= help "Dump the intermediate representation of the program"
, dump_bytecode = def &= help "Dump the bytecode representation of the program"
, dump_serialized_bytecode = def &= help "Dump the binary representation of the bytecode for program"
, dump_statements = def &= help "Dump the value and type of each statement in the program"
, files = def &= args &= typFile
}
main :: IO ()
main = do
args <- cmdArgs options
if null (files args) then runPipeline repl args else
if dump_statements args
then runPipeline (evalProgram runEach) args
else runPipeline (evalProgram runAll) args
| |
9998730a0a9583175864897077aa518fd801407befa62063fad8f0b2a8ad6e64 | emotiq/emotiq | node-0.0.1.lisp | (restas:define-module :route.node/0/0/1
(:nicknames :route.node/0/0
:route.node/0)
(:use :cl :emotiq-rest))
(in-package :route.node/0/0/1)
(restas:define-route %api
("/api/"
:content-type "text/html")
(as-html
(:html
(:body
(:h1 "Node API")
(:ul
(:li
(:a :href (restas:genurl '%tracker)
"[Get status from the tracker]")))))))
(restas:define-route %tracker
("/tracker"
:method :get
:content-type "text/plain")
(format nil "~a"
(emotiq/tracker:query-current-state)))
(restas:define-route %node
("/:node/"
:method :delete
:content-type "application/javascript")
(declare (ignore node))
"Unimplemented termination of node")
| null | https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/network/rest/node-0.0.1.lisp | lisp | (restas:define-module :route.node/0/0/1
(:nicknames :route.node/0/0
:route.node/0)
(:use :cl :emotiq-rest))
(in-package :route.node/0/0/1)
(restas:define-route %api
("/api/"
:content-type "text/html")
(as-html
(:html
(:body
(:h1 "Node API")
(:ul
(:li
(:a :href (restas:genurl '%tracker)
"[Get status from the tracker]")))))))
(restas:define-route %tracker
("/tracker"
:method :get
:content-type "text/plain")
(format nil "~a"
(emotiq/tracker:query-current-state)))
(restas:define-route %node
("/:node/"
:method :delete
:content-type "application/javascript")
(declare (ignore node))
"Unimplemented termination of node")
| |
f07661ea20e3377e2acad0a73b535d2dbcf05267dfddde858d3f12b654aea7a3 | serokell/ariadne | FeeEstimate.hs | -- | Calculate fee estimates for new transaction
module Ariadne.Wallet.Cardano.Kernel.FeeEstimate
( transactionInputs
, cardanoFee
) where
import qualified Text.Show (show)
import Crypto.Random (MonadRandom(..))
import qualified Data.ByteArray as ByteArray
import qualified Data.ByteString as B
import Data.Text.Buildable (Buildable(..))
import qualified Data.Vector as V
import Formatting (sformat)
import qualified Formatting as F
import System.Random.MWC (GenIO, asGenIO, initialize, uniformVector)
import Pos.Core
(Address(..), Coin(..), coinToInteger, sumCoins, unsafeIntegerToCoin)
import qualified Pos.Core as Core
import Pos.Core.Txp (TxOut(..), TxOutAux(..))
import Pos.Crypto (hash)
import Pos.Txp (Utxo)
import Ariadne.Wallet.Cardano.Kernel.CoinSelection.FromGeneric
(CoinSelFinalResult(..), CoinSelectionOptions(..),
ExpenseRegulation(SenderPaysFee), InputGrouping(PreferGrouping),
dummyAddrAttrSize, dummyTxAttrSize, estimateCardanoFee, estimateMaxTxInputs)
import Ariadne.Wallet.Cardano.Kernel.CoinSelection.Generic (CoinSelHardErr(..))
import qualified Ariadne.Wallet.Cardano.Kernel.CoinSelection.FromGeneric as CoinSelection
data TxInputsException = TxInputsCoinSelErr CoinSelHardErr
instance Buildable TxInputsException where
build (TxInputsCoinSelErr e) = case e of
(CoinSelHardErrOutputCannotCoverFee _ val) ->
"Payment to receiver insufficient to cover fee. Fee: " <> build val
(CoinSelHardErrOutputIsRedeemAddress _) ->
"Attempt to pay into a redeem-only address"
(CoinSelHardErrMaxInputsReached inputs) ->
"When trying to construct a transaction, the max number of allowed inputs was reached."
<> " Inputs: " <> build inputs
(CoinSelHardErrCannotCoverFee) ->
"UTxO exhausted whilst trying to pick inputs to cover remaining fee"
(CoinSelHardErrUtxoExhausted bal val) ->
"UTxO exhausted during input selection."
<> " Balance: " <> build bal
<> " Fee: " <> build val
(CoinSelHardErrUtxoDepleted) ->
"UTxO depleted using input selection"
(CoinSelHardErrAddressNotOwned _ addr) ->
"This wallet does not \"own\" the input address " <> build addr
instance Show TxInputsException where
show = toString . prettyL
instance Exception TxInputsException
-- | Special monad used to process the payments, which randomness is derived
-- from a fixed seed obtained from hashing the payees. This guarantees that
-- when we estimate the fees and later create a transaction, the coin selection
-- will always yield the same value, making the process externally-predicatable.
newtype PayMonad a = PayMonad {
buildPayment :: ReaderT Env IO a
} deriving ( Functor , Applicative , Monad , MonadIO, MonadReader Env)
| This ' Env ' datatype is necessary to convince GHC that indeed we have
-- a 'MonadReader' instance defined on 'GenIO' for the 'PayMonad'.
newtype Env = Env { getEnv :: GenIO }
| \"Invalid\ " ' MonadRandom ' instance for ' PayMonad ' which generates
randomness using the hash of ' NonEmpty ( Address , Coin ) ' as fixed seed ,
-- plus an internal counter used to shift the bits of such hash.
-- This ensures that the coin selection algorithm runs in a random environment
-- which is yet deterministically reproduceable by feeding the same set of
-- payees.
instance MonadRandom PayMonad where
getRandomBytes len = do
gen <- asks getEnv
randomBytes <- liftIO (asGenIO (flip uniformVector len) gen)
return $ ByteArray.convert (B.pack $ V.toList randomBytes)
-- | Creates inputs for new transaction
transactionInputs :: Utxo
-- ^ Available utxo
-> NonEmpty (Address, Coin)
-- ^ The payees
-> IO Int
transactionInputs availableUtxo payees = do
let options = CoinSelectionOptions cardanoFee PreferGrouping SenderPaysFee (Core.mkCoin 0)
maxInputs = estimateMaxTxInputs dummyAddrAttrSize dummyTxAttrSize 65536
initialEnv <- newEnvironment
-- Run coin selection.
res <- flip runReaderT initialEnv . buildPayment $
CoinSelection.random options
maxInputs
payees'
availableUtxo
case res of
Left e -> throwM $ TxInputsCoinSelErr e
Right (CoinSelFinalResult inputs _ _) -> return $ length inputs
where
newEnvironment :: IO Env
newEnvironment =
let initialSeed = V.fromList . map fromIntegral
. B.unpack
. encodeUtf8 @Text @ByteString
. sformat F.build
$ hash payees
in Env <$> initialize initialSeed
valueToPay :: Coin
valueToPay =
safe because the argument ca n't be greater than ' maxBound @Coin '
-- (because 'min')
-- and less than 0
-- (because we sum non-negative values).
unsafeIntegerToCoin
(min (coinToInteger maxBound)
(sumCoins (map snd payees))
)
We pass only one payee , because current implementation from
-- 'cardano-sl' fails when utxo size is less than number of
outputs , even though it might be a perfectly legal case (
one utxo entry with 100500 ADA and 100 outputs with 100 ADA ) .
payees' :: NonEmpty TxOutAux
payees' = one (TxOutAux (TxOut (fst (head payees)) valueToPay))
| An estimate of the Tx fees in Cardano based on a sensible number of defaults .
cardanoFee :: Int -> NonEmpty Coin -> Coin
cardanoFee inputs outputs = Core.mkCoin $
estimateCardanoFee linearFeePolicy inputs (toList $ fmap Core.getCoin outputs)
where
linearFeePolicy = Core.TxSizeLinear (Core.Coeff 155381) (Core.Coeff 43.946)
| null | https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ariadne/cardano/src/Ariadne/Wallet/Cardano/Kernel/FeeEstimate.hs | haskell | | Calculate fee estimates for new transaction
| Special monad used to process the payments, which randomness is derived
from a fixed seed obtained from hashing the payees. This guarantees that
when we estimate the fees and later create a transaction, the coin selection
will always yield the same value, making the process externally-predicatable.
a 'MonadReader' instance defined on 'GenIO' for the 'PayMonad'.
plus an internal counter used to shift the bits of such hash.
This ensures that the coin selection algorithm runs in a random environment
which is yet deterministically reproduceable by feeding the same set of
payees.
| Creates inputs for new transaction
^ Available utxo
^ The payees
Run coin selection.
(because 'min')
and less than 0
(because we sum non-negative values).
'cardano-sl' fails when utxo size is less than number of | module Ariadne.Wallet.Cardano.Kernel.FeeEstimate
( transactionInputs
, cardanoFee
) where
import qualified Text.Show (show)
import Crypto.Random (MonadRandom(..))
import qualified Data.ByteArray as ByteArray
import qualified Data.ByteString as B
import Data.Text.Buildable (Buildable(..))
import qualified Data.Vector as V
import Formatting (sformat)
import qualified Formatting as F
import System.Random.MWC (GenIO, asGenIO, initialize, uniformVector)
import Pos.Core
(Address(..), Coin(..), coinToInteger, sumCoins, unsafeIntegerToCoin)
import qualified Pos.Core as Core
import Pos.Core.Txp (TxOut(..), TxOutAux(..))
import Pos.Crypto (hash)
import Pos.Txp (Utxo)
import Ariadne.Wallet.Cardano.Kernel.CoinSelection.FromGeneric
(CoinSelFinalResult(..), CoinSelectionOptions(..),
ExpenseRegulation(SenderPaysFee), InputGrouping(PreferGrouping),
dummyAddrAttrSize, dummyTxAttrSize, estimateCardanoFee, estimateMaxTxInputs)
import Ariadne.Wallet.Cardano.Kernel.CoinSelection.Generic (CoinSelHardErr(..))
import qualified Ariadne.Wallet.Cardano.Kernel.CoinSelection.FromGeneric as CoinSelection
data TxInputsException = TxInputsCoinSelErr CoinSelHardErr
instance Buildable TxInputsException where
build (TxInputsCoinSelErr e) = case e of
(CoinSelHardErrOutputCannotCoverFee _ val) ->
"Payment to receiver insufficient to cover fee. Fee: " <> build val
(CoinSelHardErrOutputIsRedeemAddress _) ->
"Attempt to pay into a redeem-only address"
(CoinSelHardErrMaxInputsReached inputs) ->
"When trying to construct a transaction, the max number of allowed inputs was reached."
<> " Inputs: " <> build inputs
(CoinSelHardErrCannotCoverFee) ->
"UTxO exhausted whilst trying to pick inputs to cover remaining fee"
(CoinSelHardErrUtxoExhausted bal val) ->
"UTxO exhausted during input selection."
<> " Balance: " <> build bal
<> " Fee: " <> build val
(CoinSelHardErrUtxoDepleted) ->
"UTxO depleted using input selection"
(CoinSelHardErrAddressNotOwned _ addr) ->
"This wallet does not \"own\" the input address " <> build addr
instance Show TxInputsException where
show = toString . prettyL
instance Exception TxInputsException
newtype PayMonad a = PayMonad {
buildPayment :: ReaderT Env IO a
} deriving ( Functor , Applicative , Monad , MonadIO, MonadReader Env)
| This ' Env ' datatype is necessary to convince GHC that indeed we have
newtype Env = Env { getEnv :: GenIO }
| \"Invalid\ " ' MonadRandom ' instance for ' PayMonad ' which generates
randomness using the hash of ' NonEmpty ( Address , Coin ) ' as fixed seed ,
instance MonadRandom PayMonad where
getRandomBytes len = do
gen <- asks getEnv
randomBytes <- liftIO (asGenIO (flip uniformVector len) gen)
return $ ByteArray.convert (B.pack $ V.toList randomBytes)
transactionInputs :: Utxo
-> NonEmpty (Address, Coin)
-> IO Int
transactionInputs availableUtxo payees = do
let options = CoinSelectionOptions cardanoFee PreferGrouping SenderPaysFee (Core.mkCoin 0)
maxInputs = estimateMaxTxInputs dummyAddrAttrSize dummyTxAttrSize 65536
initialEnv <- newEnvironment
res <- flip runReaderT initialEnv . buildPayment $
CoinSelection.random options
maxInputs
payees'
availableUtxo
case res of
Left e -> throwM $ TxInputsCoinSelErr e
Right (CoinSelFinalResult inputs _ _) -> return $ length inputs
where
newEnvironment :: IO Env
newEnvironment =
let initialSeed = V.fromList . map fromIntegral
. B.unpack
. encodeUtf8 @Text @ByteString
. sformat F.build
$ hash payees
in Env <$> initialize initialSeed
valueToPay :: Coin
valueToPay =
safe because the argument ca n't be greater than ' maxBound @Coin '
unsafeIntegerToCoin
(min (coinToInteger maxBound)
(sumCoins (map snd payees))
)
We pass only one payee , because current implementation from
outputs , even though it might be a perfectly legal case (
one utxo entry with 100500 ADA and 100 outputs with 100 ADA ) .
payees' :: NonEmpty TxOutAux
payees' = one (TxOutAux (TxOut (fst (head payees)) valueToPay))
| An estimate of the Tx fees in Cardano based on a sensible number of defaults .
cardanoFee :: Int -> NonEmpty Coin -> Coin
cardanoFee inputs outputs = Core.mkCoin $
estimateCardanoFee linearFeePolicy inputs (toList $ fmap Core.getCoin outputs)
where
linearFeePolicy = Core.TxSizeLinear (Core.Coeff 155381) (Core.Coeff 43.946)
|
e46dbd19f01d68e5315378c8377ba2e3b22090ab935a4ac1e65690a0265f7cc1 | mpickering/apply-refact | Import12.hs | import A; import B; import A | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Import12.hs | haskell | import A; import B; import A | |
2d4bde4218afb42fc9fb924104de75bb7800ce3cb6b4c7815af33f9dc451c4f2 | ympbyc/Carrot | carrot-compile.scm | #!/usr/local/bin/gosh
(add-load-path "../lib/" :relative)
(add-load-path "../compilers/" :relative)
(add-load-path "/usr/local/share/Carrot/2.2.0/lib/" :absolute)
(add-load-path "/usr/local/share/Carrot/2.2.0/compilers/" :absolute)
(use Util)
(use DataTypes)
(define (main args)
(let* ([compiler-name (cadr args)]
[exprs*t (read)])
(format (standard-error-port)
"Compiling your carrot ~A...\n" compiler-name)
(load (str compiler-name ".scm"))
(let1 res (eval `(compile ,(fst exprs*t))
(find-module (string->symbol compiler-name)))
(cond [(hash-table? res)
(display (write-hash-table res))]
[string? res (display res)]))))
| null | https://raw.githubusercontent.com/ympbyc/Carrot/5ce3969b3833bcf1b466d808a74d0a03653ef6ab/bin/carrot-compile.scm | scheme | #!/usr/local/bin/gosh
(add-load-path "../lib/" :relative)
(add-load-path "../compilers/" :relative)
(add-load-path "/usr/local/share/Carrot/2.2.0/lib/" :absolute)
(add-load-path "/usr/local/share/Carrot/2.2.0/compilers/" :absolute)
(use Util)
(use DataTypes)
(define (main args)
(let* ([compiler-name (cadr args)]
[exprs*t (read)])
(format (standard-error-port)
"Compiling your carrot ~A...\n" compiler-name)
(load (str compiler-name ".scm"))
(let1 res (eval `(compile ,(fst exprs*t))
(find-module (string->symbol compiler-name)))
(cond [(hash-table? res)
(display (write-hash-table res))]
[string? res (display res)]))))
| |
d9a6e6aa33a3f00f619f1e9d630e9c23d5c6735341cfe0a756f36c1d7eb6e809 | lispbuilder/lispbuilder | gfx-string-shaded.lisp |
(in-package :lispbuilder-sdl)
(defmethod _draw-string-shaded-*_ ((string string) (x integer) (y integer) (fg-color sdl:color) (bg-color sdl:color) justify (surface sdl:sdl-surface) (font gfx-bitmap-font))
(unless (default-font-p font)
(sdl:set-default-font font))
(let ((x-pos x))
(if (eq justify :right)
(setf x-pos (- x-pos (* (char-width font) (length string)))))
(if (eq justify :center)
(setf x-pos (- x-pos (/ (* (char-width font) (length string)) 2))))
(draw-box-* x-pos y
(* (char-width font)
(length string))
(char-height font)
:color bg-color
:surface surface)
(gfx-string-color x-pos y string :surface surface :color fg-color))
surface)
(defun draw-character-shaded (c p1 fg-color bg-color &key
(font sdl:*default-font*)
(surface sdl:*default-surface*) (gfx-loaded-p *gfx-loaded-p*))
"See [DRAW-CHARACTER-SHADED-*](#draw-character-shaded-*).
##### Parameters
* `P1` is the x and y position to render the character, of type `SDL:POINT`."
(check-type p1 sdl:point)
(draw-character-shaded-* c (sdl:x p1) (sdl:y p1) fg-color bg-color
:font font
:surface surface :gfx-loaded-p gfx-loaded-p))
(defun draw-character-shaded-* (c x y fg-color bg-color &key
(font sdl:*default-font*)
(surface sdl:*default-surface*) (gfx-loaded-p *gfx-loaded-p*))
"See [DRAW-CHARACTER-SHADED-*](#draw-character-shaded-*).
##### Parameters
* `P1` is the x and y position to render the character, of type `SDL:POINT`."
(if gfx-loaded-p
(gfx-draw-character-shaded-* c x y fg-color bg-color
:font font
:surface surface)))
(defun gfx-draw-character-shaded-* (c x y fg-color bg-color &key
(font sdl:*default-font*)
(surface sdl:*default-surface*))
"Draw the character `C` at location `X` `Y` using font `FONT` with text color `FG-COLOR` and background color `BG-COLOR`
onto surface `SURFACE`.
The surface background is filled with `BG-COLOR` so the surface cannot be keyed over other surfaces.
##### Parameters
* `C` is the character to render.
* `X` and `Y` are the x and y position coordinates, as `INTEGERS`.
* `FG-COLOR` color is the character color, of type `SDL:COLOR`
* `BG-COLOR` color is the background color used to fill the surface `SURFACE`, of type `SDL:COLOR`
* `FONT` is the font face used to render the character. Of type `FONT`. Bound to `*DEFAULT-FONT*` if unspecified.
* `SURFACE` is the target surface, of type `SDL:SDL-SURFACE`. Bound to `SDL:\*DEFAULT-SURFACE\*` if unspecified.
##### Returns
* Returns the surface `SURFACE`.
##### Example
\(DRAW-CHARACTER-SHADED-* \"Hello World!\" 0 0 F-COLOR B-COLOR :SURFACE A-SURFACE\)"
(unless surface
(setf surface sdl:*default-display*))
(check-type surface sdl:sdl-surface)
(sdl:check-types sdl:color fg-color bg-color)
(unless (sdl:default-font-p font)
(sdl:set-default-font font))
(sdl:draw-box-* x y
(* (sdl:char-width font)
(length c))
(sdl:char-height font)
:color bg-color
:surface surface)
(gfx-character-color x y c :surface surface :color fg-color)
surface)
| null | https://raw.githubusercontent.com/lispbuilder/lispbuilder/589b3c6d552bbec4b520f61388117d6c7b3de5ab/lispbuilder-sdl/sdl/gfx-string-shaded.lisp | lisp |
(in-package :lispbuilder-sdl)
(defmethod _draw-string-shaded-*_ ((string string) (x integer) (y integer) (fg-color sdl:color) (bg-color sdl:color) justify (surface sdl:sdl-surface) (font gfx-bitmap-font))
(unless (default-font-p font)
(sdl:set-default-font font))
(let ((x-pos x))
(if (eq justify :right)
(setf x-pos (- x-pos (* (char-width font) (length string)))))
(if (eq justify :center)
(setf x-pos (- x-pos (/ (* (char-width font) (length string)) 2))))
(draw-box-* x-pos y
(* (char-width font)
(length string))
(char-height font)
:color bg-color
:surface surface)
(gfx-string-color x-pos y string :surface surface :color fg-color))
surface)
(defun draw-character-shaded (c p1 fg-color bg-color &key
(font sdl:*default-font*)
(surface sdl:*default-surface*) (gfx-loaded-p *gfx-loaded-p*))
"See [DRAW-CHARACTER-SHADED-*](#draw-character-shaded-*).
##### Parameters
* `P1` is the x and y position to render the character, of type `SDL:POINT`."
(check-type p1 sdl:point)
(draw-character-shaded-* c (sdl:x p1) (sdl:y p1) fg-color bg-color
:font font
:surface surface :gfx-loaded-p gfx-loaded-p))
(defun draw-character-shaded-* (c x y fg-color bg-color &key
(font sdl:*default-font*)
(surface sdl:*default-surface*) (gfx-loaded-p *gfx-loaded-p*))
"See [DRAW-CHARACTER-SHADED-*](#draw-character-shaded-*).
##### Parameters
* `P1` is the x and y position to render the character, of type `SDL:POINT`."
(if gfx-loaded-p
(gfx-draw-character-shaded-* c x y fg-color bg-color
:font font
:surface surface)))
(defun gfx-draw-character-shaded-* (c x y fg-color bg-color &key
(font sdl:*default-font*)
(surface sdl:*default-surface*))
"Draw the character `C` at location `X` `Y` using font `FONT` with text color `FG-COLOR` and background color `BG-COLOR`
onto surface `SURFACE`.
The surface background is filled with `BG-COLOR` so the surface cannot be keyed over other surfaces.
##### Parameters
* `C` is the character to render.
* `X` and `Y` are the x and y position coordinates, as `INTEGERS`.
* `FG-COLOR` color is the character color, of type `SDL:COLOR`
* `BG-COLOR` color is the background color used to fill the surface `SURFACE`, of type `SDL:COLOR`
* `FONT` is the font face used to render the character. Of type `FONT`. Bound to `*DEFAULT-FONT*` if unspecified.
* `SURFACE` is the target surface, of type `SDL:SDL-SURFACE`. Bound to `SDL:\*DEFAULT-SURFACE\*` if unspecified.
##### Returns
* Returns the surface `SURFACE`.
##### Example
\(DRAW-CHARACTER-SHADED-* \"Hello World!\" 0 0 F-COLOR B-COLOR :SURFACE A-SURFACE\)"
(unless surface
(setf surface sdl:*default-display*))
(check-type surface sdl:sdl-surface)
(sdl:check-types sdl:color fg-color bg-color)
(unless (sdl:default-font-p font)
(sdl:set-default-font font))
(sdl:draw-box-* x y
(* (sdl:char-width font)
(length c))
(sdl:char-height font)
:color bg-color
:surface surface)
(gfx-character-color x y c :surface surface :color fg-color)
surface)
| |
4c72f91116b3f9d1e4e4a73cf6cae53c1bf93de683d2a1eee6b0552402c740e8 | donut-party/datapotato | 08.clj | (ns donut.datapotato-tutorial.08
"collect constraint"
(:require [donut.datapotato.core :as dc]
[malli.generator :as mg]))
(def User
[:map
[:id pos-int?]
[:favorite-ids [:vector pos-int?]]])
(def Topic
[:map
[:id pos-int?]])
(def potato-schema
{:user {:prefix :u
:generate {:schema User}
:relations {:favorite-ids [:topic :id]}
:constraints {:favorite-ids #{:coll}}}
:topic {:prefix :t
:generate {:schema Topic}}})
(def potato-db
{:schema potato-schema
:generate {:generator mg/generate}})
(defn ex-01
[]
(dc/generate potato-db {:user [{:count 1}]}))
(defn ex-02
[]
(dc/generate potato-db {:user [{:refs {:favorite-ids 3}}]}))
(defn ex-03
[]
(dc/add-ents potato-db
{:user [{:refs {:count 2
:favorite-ids 3}}]}))
(defn ex-04
[]
(dc/add-ents potato-db
{:user [[1 {:refs {:favorite-ids [:my-p0 :my-p1]}}]
[1 {:refs {:favorite-ids [:my-p2 :my-p3]}}]]}))
(comment
(dc/view (ex-03) :fmt :svg)
(dc/view (ex-04) :fmt :svg))
| null | https://raw.githubusercontent.com/donut-party/datapotato/4f325977ea3639d6e6a954b49382c771a9b18320/docs/tutorial/donut/datapotato_tutorial/08.clj | clojure | (ns donut.datapotato-tutorial.08
"collect constraint"
(:require [donut.datapotato.core :as dc]
[malli.generator :as mg]))
(def User
[:map
[:id pos-int?]
[:favorite-ids [:vector pos-int?]]])
(def Topic
[:map
[:id pos-int?]])
(def potato-schema
{:user {:prefix :u
:generate {:schema User}
:relations {:favorite-ids [:topic :id]}
:constraints {:favorite-ids #{:coll}}}
:topic {:prefix :t
:generate {:schema Topic}}})
(def potato-db
{:schema potato-schema
:generate {:generator mg/generate}})
(defn ex-01
[]
(dc/generate potato-db {:user [{:count 1}]}))
(defn ex-02
[]
(dc/generate potato-db {:user [{:refs {:favorite-ids 3}}]}))
(defn ex-03
[]
(dc/add-ents potato-db
{:user [{:refs {:count 2
:favorite-ids 3}}]}))
(defn ex-04
[]
(dc/add-ents potato-db
{:user [[1 {:refs {:favorite-ids [:my-p0 :my-p1]}}]
[1 {:refs {:favorite-ids [:my-p2 :my-p3]}}]]}))
(comment
(dc/view (ex-03) :fmt :svg)
(dc/view (ex-04) :fmt :svg))
| |
7cf5cf86f0629e99434e0687da7161aec4a475444975f2cb09eabec107d7d2a2 | Erlang-Openid/erljwt | erljwt_key.erl | -module(erljwt_key).
-include("erljwt.hrl").
-export([to_key_list/1, get_needed/3]).
-spec to_key_list(keys()) -> [key()].
to_key_list(Json) when is_binary(Json) ->
to_key_list(erljwt_util:safe_jsone_decode(Json));
to_key_list(#{keys := KeyList}) when is_list(KeyList) ->
KeyList;
to_key_list(#{kty := _} = Key) ->
[Key];
to_key_list(invalid) ->
[].
-spec get_needed(algorithm(), keyid(), [key()]) -> key_result().
get_needed(Algo, KeyId, KeyList)
when Algo == hs256; Algo == hs384; Algo == hs512->
filter_oct_key(KeyId, KeyList);
get_needed(Algo, KeyId, KeyList)
when Algo == rs256; Algo == rs384; Algo == rs512 ->
filter_rsa_key(KeyId, KeyList);
get_needed(Algo, KeyId, KeyList)
when Algo == es256; Algo == es384; Algo == es512 ->
filter_ec_key(KeyId, Algo, KeyList);
get_needed(none, _, _) ->
{ok, <<>>};
get_needed(_, _, _) ->
{error, unknown_algorithm}.
filter_oct_key(KeyId, KeyList) ->
handle_filter_result(filter_key(KeyId, KeyList, [], <<"oct">>)).
filter_rsa_key(KeyId, KeyList) ->
handle_filter_result(filter_key(KeyId, KeyList, [], <<"RSA">>)).
filter_ec_key(KeyId, Algo, KeyList) ->
Keys = filter_key(KeyId, KeyList, [], <<"EC">>),
handle_filter_result(filter_curve(Keys, [], Algo)).
handle_filter_result([]) ->
{error, no_key_found};
handle_filter_result([Key]) ->
{ok, Key};
handle_filter_result([_ | _ ]) ->
{error, too_many_keys}.
filter_curve([], Keys, _) ->
Keys;
filter_curve([#{crv := <<"P-256">>} = Key | Tail ], List, Algo)
when Algo == es256->
filter_curve(Tail, [Key | List], Algo);
filter_curve([#{crv := <<"P-384">>} = Key | Tail ], List, Algo)
when Algo == es384->
filter_curve(Tail, [Key | List], Algo);
filter_curve([#{crv := <<"P-521">>} = Key | Tail ], List, Algo)
when Algo == es512->
filter_curve(Tail, [Key | List], Algo);
filter_curve([_ | Tail ], List, Algo) ->
filter_curve(Tail, List, Algo).
filter_key(_, [], Keys, _Type) ->
Keys;
filter_key(KeyId, [ #{kty := Type, kid:= KeyId } = Key | _], _, Type) ->
[Key];
filter_key(KeyId, [ #{kty := Type, kid := _Other} | Tail], List, Type) ->
filter_key(KeyId, Tail, List, Type);
filter_key(KeyId, [ #{kty := Type, use:=<<"sig">>} = Key | Tail],
List, Type) ->
filter_key(KeyId, Tail, [ Key | List ], Type);
filter_key(KeyId, [ #{kty := Type, use:= _} | Tail], List, Type) ->
filter_key(KeyId, Tail, List, Type);
filter_key(KeyId, [ #{kty := Type} = Key | Tail], List, Type) ->
filter_key(KeyId, Tail, [ Key | List ], Type);
filter_key(KeyId, [ _ | Tail ], List, Type) ->
filter_key(KeyId, Tail, List, Type).
| null | https://raw.githubusercontent.com/Erlang-Openid/erljwt/d2baeecd49c3dd6e41b8511bbf7a35ec995f06cf/src/erljwt_key.erl | erlang | -module(erljwt_key).
-include("erljwt.hrl").
-export([to_key_list/1, get_needed/3]).
-spec to_key_list(keys()) -> [key()].
to_key_list(Json) when is_binary(Json) ->
to_key_list(erljwt_util:safe_jsone_decode(Json));
to_key_list(#{keys := KeyList}) when is_list(KeyList) ->
KeyList;
to_key_list(#{kty := _} = Key) ->
[Key];
to_key_list(invalid) ->
[].
-spec get_needed(algorithm(), keyid(), [key()]) -> key_result().
get_needed(Algo, KeyId, KeyList)
when Algo == hs256; Algo == hs384; Algo == hs512->
filter_oct_key(KeyId, KeyList);
get_needed(Algo, KeyId, KeyList)
when Algo == rs256; Algo == rs384; Algo == rs512 ->
filter_rsa_key(KeyId, KeyList);
get_needed(Algo, KeyId, KeyList)
when Algo == es256; Algo == es384; Algo == es512 ->
filter_ec_key(KeyId, Algo, KeyList);
get_needed(none, _, _) ->
{ok, <<>>};
get_needed(_, _, _) ->
{error, unknown_algorithm}.
filter_oct_key(KeyId, KeyList) ->
handle_filter_result(filter_key(KeyId, KeyList, [], <<"oct">>)).
filter_rsa_key(KeyId, KeyList) ->
handle_filter_result(filter_key(KeyId, KeyList, [], <<"RSA">>)).
filter_ec_key(KeyId, Algo, KeyList) ->
Keys = filter_key(KeyId, KeyList, [], <<"EC">>),
handle_filter_result(filter_curve(Keys, [], Algo)).
handle_filter_result([]) ->
{error, no_key_found};
handle_filter_result([Key]) ->
{ok, Key};
handle_filter_result([_ | _ ]) ->
{error, too_many_keys}.
filter_curve([], Keys, _) ->
Keys;
filter_curve([#{crv := <<"P-256">>} = Key | Tail ], List, Algo)
when Algo == es256->
filter_curve(Tail, [Key | List], Algo);
filter_curve([#{crv := <<"P-384">>} = Key | Tail ], List, Algo)
when Algo == es384->
filter_curve(Tail, [Key | List], Algo);
filter_curve([#{crv := <<"P-521">>} = Key | Tail ], List, Algo)
when Algo == es512->
filter_curve(Tail, [Key | List], Algo);
filter_curve([_ | Tail ], List, Algo) ->
filter_curve(Tail, List, Algo).
filter_key(_, [], Keys, _Type) ->
Keys;
filter_key(KeyId, [ #{kty := Type, kid:= KeyId } = Key | _], _, Type) ->
[Key];
filter_key(KeyId, [ #{kty := Type, kid := _Other} | Tail], List, Type) ->
filter_key(KeyId, Tail, List, Type);
filter_key(KeyId, [ #{kty := Type, use:=<<"sig">>} = Key | Tail],
List, Type) ->
filter_key(KeyId, Tail, [ Key | List ], Type);
filter_key(KeyId, [ #{kty := Type, use:= _} | Tail], List, Type) ->
filter_key(KeyId, Tail, List, Type);
filter_key(KeyId, [ #{kty := Type} = Key | Tail], List, Type) ->
filter_key(KeyId, Tail, [ Key | List ], Type);
filter_key(KeyId, [ _ | Tail ], List, Type) ->
filter_key(KeyId, Tail, List, Type).
| |
c9479dfba9514894340dc3ac32ad3ef9ffb97abe57eff2e634ea3e84322040ed | alphagov/govuk-guix | delayed-job.scm | (define-module (gds services delayed-job)
#:use-module (srfi srfi-1)
#:use-module (ice-9 match)
#:use-module (guix gexp)
#:use-module (guix records)
#:use-module (guix packages)
#:use-module (gnu services shepherd)
#:use-module (gds services)
#:export (<delayed-job-config>
delayed-job-config
delayed-job-config?
delayed-job-config-queues
delayed-job-worker-shepherd-service))
(define-record-type* <delayed-job-config>
delayed-job-config make-delayed-job-config
delayed-job-config?
(queues delayed-job-config-queues
(default #f)))
(define (delayed-job-worker-shepherd-service
name
delayed-job-config
requirements
directory
user
environment)
(shepherd-service
(provision (list (string->symbol name)))
(documentation
(simple-format #f "~A service" name))
(requirement requirements)
(respawn? #f)
(start
#~(lambda args
(display #$(simple-format #f "starting ~A service\n" name))
(apply
#$#~(make-forkexec-constructor
'("rake" "jobs:work")
#:user #$user
#:log-file #$(string-append
"/var/log/" name ".log")
#:directory #$directory
#:environment-variables
'#$(map
(match-lambda
((key . value)
(string-append key "=" value)))
environment))
args)))
(stop #~(make-kill-destructor))))
| null | https://raw.githubusercontent.com/alphagov/govuk-guix/dea8c26d2ae882d0278be5c745e23abb25d4a4e2/gds/services/delayed-job.scm | scheme | (define-module (gds services delayed-job)
#:use-module (srfi srfi-1)
#:use-module (ice-9 match)
#:use-module (guix gexp)
#:use-module (guix records)
#:use-module (guix packages)
#:use-module (gnu services shepherd)
#:use-module (gds services)
#:export (<delayed-job-config>
delayed-job-config
delayed-job-config?
delayed-job-config-queues
delayed-job-worker-shepherd-service))
(define-record-type* <delayed-job-config>
delayed-job-config make-delayed-job-config
delayed-job-config?
(queues delayed-job-config-queues
(default #f)))
(define (delayed-job-worker-shepherd-service
name
delayed-job-config
requirements
directory
user
environment)
(shepherd-service
(provision (list (string->symbol name)))
(documentation
(simple-format #f "~A service" name))
(requirement requirements)
(respawn? #f)
(start
#~(lambda args
(display #$(simple-format #f "starting ~A service\n" name))
(apply
#$#~(make-forkexec-constructor
'("rake" "jobs:work")
#:user #$user
#:log-file #$(string-append
"/var/log/" name ".log")
#:directory #$directory
#:environment-variables
'#$(map
(match-lambda
((key . value)
(string-append key "=" value)))
environment))
args)))
(stop #~(make-kill-destructor))))
| |
47e0ff10e96c9684e2d965a9a17f299cf1fc15e955562de5863b633b1a3f34a8 | Mishio595/disml | role_id.ml | open Core
type t = [ `Role_id of Snowflake.t ] [@@deriving sexp]
let of_yojson a : (t, string) result =
match Snowflake.of_yojson a with
| Ok id -> Ok (`Role_id id)
| Error err -> Error err
let of_yojson_exn a : t = `Role_id (Snowflake.of_yojson_exn a)
let to_yojson (`Role_id id) = (Snowflake.to_yojson id)
let get_id (`Role_id id) = id | null | https://raw.githubusercontent.com/Mishio595/disml/cbb1e47a6d358eace03790c07a1b85641f4ca366/lib/models/id/role_id.ml | ocaml | open Core
type t = [ `Role_id of Snowflake.t ] [@@deriving sexp]
let of_yojson a : (t, string) result =
match Snowflake.of_yojson a with
| Ok id -> Ok (`Role_id id)
| Error err -> Error err
let of_yojson_exn a : t = `Role_id (Snowflake.of_yojson_exn a)
let to_yojson (`Role_id id) = (Snowflake.to_yojson id)
let get_id (`Role_id id) = id | |
5ec24fe6806ebf66d3d96900cbe6761d3aa78a4181c6815b045886a46ec01bbb | ktakashi/sagittarius-scheme | modular.scm | -*- mode : scheme ; coding : utf-8 ; -*-
;;;
;;; math/modular.scm - Modular arithmetic
;;;
Copyright ( c ) 2021 . All rights reserved .
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#!nounbound
(library (math modular)
(export :all)
(import (sagittarius crypto math modular)))
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/629ced3dc08fd1f8d97e58321d1f4130b8b5dc81/ext/crypto/math/modular.scm | scheme | coding : utf-8 ; -*-
math/modular.scm - Modular arithmetic
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE , DATA , OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | Copyright ( c ) 2021 . All rights reserved .
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
#!nounbound
(library (math modular)
(export :all)
(import (sagittarius crypto math modular)))
|
a9e4d796fb753028901b34d44e5bf3f38a86be50d81cc2de2edad05cc14b8908 | JHU-PL-Lab/jaylang | convert.ml | open! Core
let bluejay_edesc_to_jay ~do_wrap bluejay_edesc =
let bluejay_ast_internal =
Bluejay.Bluejay_ast_internal.to_internal_expr_desc bluejay_edesc
in
let core_ast, _bluejay_jay_maps =
Bluejay.Bluejay_to_jay.transform_bluejay ~do_wrap bluejay_ast_internal.body
in
Bluejay.Bluejay_ast_internal.to_jay_expr_desc core_ast
let bluejay_edesc_to_jayil ~do_wrap ~is_instrumented ~consts bluejay_edesc =
let consts =
Bluejay.Bluejay_ast_tools.defined_vars_of_expr_desc bluejay_edesc
|> Bluejay.Bluejay_ast.Ident_set.to_list
|> List.map ~f:(fun x -> Jayil.Ast.Var (x, None))
|> Jayil.Ast.Var_set.of_list
in
let bluejay_ast_internal =
Bluejay.Bluejay_ast_internal.to_internal_expr_desc bluejay_edesc
in
let core_ast, _bluejay_jay_maps =
Bluejay.Bluejay_to_jay.transform_bluejay ~do_wrap bluejay_ast_internal.body
in
let jay_edesc = Bluejay.Bluejay_ast_internal.to_jay_expr_desc core_ast in
Jay_translate.Jay_to_jayil.translate ~is_jay:true ~is_instrumented ~consts
jay_edesc
|> fun (e, _, _) -> e
let jay_edesc_to_jayil ~is_instrumented ~consts jay_edesc =
let consts =
Jay.Jay_ast_tools.defined_vars_of_expr_desc jay_edesc
|> Jay.Jay_ast.Ident_set.to_list
|> List.map ~f:(fun x -> Jayil.Ast.Var (x, None))
|> Jayil.Ast.Var_set.of_list
in
Jay_translate.Jay_to_jayil.translate ~is_jay:true ~is_instrumented ~consts
jay_edesc
|> fun (e, _, _) -> e
let jay_ast_to_jayil ~is_instrumented ~consts jay_ast =
let jay_edesc = Jay.Jay_ast.new_expr_desc jay_ast in
let consts =
Jay.Jay_ast_tools.defined_vars_of_expr_desc jay_edesc
|> Jay.Jay_ast.Ident_set.to_list
|> List.map ~f:(fun x -> Jayil.Ast.Var (x, None))
|> Jayil.Ast.Var_set.of_list
in
Jay_translate.Jay_to_jayil.translate ~is_jay:true ~is_instrumented ~consts
jay_edesc
|> fun (e, _, _) -> e
let instrument_jayil_if ~is_instrumented jayil_ast =
if is_instrumented
then Jay_instrumentation.Instrumentation.instrument_jayil jayil_ast |> fst
else jayil_ast
| null | https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/484b3876986a515fb57b11768a1b3b50418cde0c/src/dj-common/utils/convert.ml | ocaml | open! Core
let bluejay_edesc_to_jay ~do_wrap bluejay_edesc =
let bluejay_ast_internal =
Bluejay.Bluejay_ast_internal.to_internal_expr_desc bluejay_edesc
in
let core_ast, _bluejay_jay_maps =
Bluejay.Bluejay_to_jay.transform_bluejay ~do_wrap bluejay_ast_internal.body
in
Bluejay.Bluejay_ast_internal.to_jay_expr_desc core_ast
let bluejay_edesc_to_jayil ~do_wrap ~is_instrumented ~consts bluejay_edesc =
let consts =
Bluejay.Bluejay_ast_tools.defined_vars_of_expr_desc bluejay_edesc
|> Bluejay.Bluejay_ast.Ident_set.to_list
|> List.map ~f:(fun x -> Jayil.Ast.Var (x, None))
|> Jayil.Ast.Var_set.of_list
in
let bluejay_ast_internal =
Bluejay.Bluejay_ast_internal.to_internal_expr_desc bluejay_edesc
in
let core_ast, _bluejay_jay_maps =
Bluejay.Bluejay_to_jay.transform_bluejay ~do_wrap bluejay_ast_internal.body
in
let jay_edesc = Bluejay.Bluejay_ast_internal.to_jay_expr_desc core_ast in
Jay_translate.Jay_to_jayil.translate ~is_jay:true ~is_instrumented ~consts
jay_edesc
|> fun (e, _, _) -> e
let jay_edesc_to_jayil ~is_instrumented ~consts jay_edesc =
let consts =
Jay.Jay_ast_tools.defined_vars_of_expr_desc jay_edesc
|> Jay.Jay_ast.Ident_set.to_list
|> List.map ~f:(fun x -> Jayil.Ast.Var (x, None))
|> Jayil.Ast.Var_set.of_list
in
Jay_translate.Jay_to_jayil.translate ~is_jay:true ~is_instrumented ~consts
jay_edesc
|> fun (e, _, _) -> e
let jay_ast_to_jayil ~is_instrumented ~consts jay_ast =
let jay_edesc = Jay.Jay_ast.new_expr_desc jay_ast in
let consts =
Jay.Jay_ast_tools.defined_vars_of_expr_desc jay_edesc
|> Jay.Jay_ast.Ident_set.to_list
|> List.map ~f:(fun x -> Jayil.Ast.Var (x, None))
|> Jayil.Ast.Var_set.of_list
in
Jay_translate.Jay_to_jayil.translate ~is_jay:true ~is_instrumented ~consts
jay_edesc
|> fun (e, _, _) -> e
let instrument_jayil_if ~is_instrumented jayil_ast =
if is_instrumented
then Jay_instrumentation.Instrumentation.instrument_jayil jayil_ast |> fst
else jayil_ast
| |
9936e38f62a42aeb49c5619132d20742a56a5d4746ab5c31be824fb2dc759c81 | AndrasKovacs/ELTE-func-lang | Notes04.hs |
import Control.Monad (ap)
Maybe ismétlés , : mapM , sequence
do notáció
-- IO
további : replicateM , forever , filterM
-- Monad törvények
State monad
motiváció : Maybe : hibakódos hibakazelés ( sok zaj )
catch / throw ,
Maybe van
instance Monad Maybe -- Monad : custom
-- Maybe : mellékhatás = Nothing propagálás mint kivétel
-- Just :: a -> Maybe a
-- bind :: Maybe a -> (a -> Maybe b) -> Maybe b
bind :: Maybe a -> (a -> Maybe b) -> Maybe b
bind Nothing _ = Nothing
bind (Just a) f = f a
mapMaybe :: (a -> Maybe b) -> [a] -> Maybe [b]
mapMaybe f [] = Just []
mapMaybe f (a:as) = case f a of
Nothing -> Nothing
Just b -> case mapMaybe f as of
Nothing -> Nothing
Just bs -> Just (b:bs)
mapMaybe' :: (a -> Maybe b) -> [a] -> Maybe [b]
mapMaybe' f [] = Just []
mapMaybe' f (a:as) =
bind (f a) $ \b ->
bind (mapMaybe f as) $ \bs ->
Just (b:bs)
-- "monádikus" forma
-- sima függvény komp: (.) :: (b -> c) -> (a -> b) -> a -> c
-- (.) f g x = f (g x)
( std általános függvény is )
compMaybe' :: (a -> Maybe b) -> (b -> Maybe c) -> a -> Maybe c
compMaybe' f g a = case f a of
Nothing -> Nothing
Just b -> g b
compMaybe :: (a -> Maybe b) -> (b -> Maybe c) -> a -> Maybe c
compMaybe f g a = bind (f a) g
--------------------------------------------------------------------------------
-- class Functor f where
-- fmap :: (a -> b) -> f a -> f b
-- class Functor f => Applicative f where
-- pure :: a -> f a
-- (<*>) :: f (a -> b) -> f a -> f b -- ap
-- class Applicative m => Monad m where
-- return :: a -> m a
( > > : m a - > ( a - > m b ) - > m b -- ez a bind
return ugyanaz mint a pure ( konvenció : return definíciója ugyanaz , mint pure - é )
( )
-- (én személye szerint: csak a pure-t használom, a return-t)
-- instance Functor Maybe where
-- fmap f Nothing = Nothing
-- fmap f (Just a) = Just (f a)
-- instance Applicative Maybe where
-- pure = return
-- (<*>) = ap
instance Maybe where
-- return = Just
( > > bind
ha instance -- > Applicative triviális
-- ha van Applicative instance --> Functor triviális
data Maybe' a = Nothing' | Just' a
instance Functor Maybe' where
fmap = fmapFromMonad
instance Applicative Maybe' where
pure = return
(<*>) = ap
instance Monad Maybe' where
return = Just'
Nothing' >>= f = Nothing'
Just' a >>= f = f a
-- (>>=) :: m a -> (a -> m b) -> m b
-- pure/return :: a -> m a
fmapFromMonad :: Monad m => (a -> b) -> m a -> m b
fmapFromMonad f ma = ma >>= \a -> pure (f a)
-- f a :: b
--------------------------------------------------------------------------------
-- standard: mapM
monádikus map
mapM' :: Monad m => (a -> m b) -> [a] -> m [b]
tiszta értékre ,
mint mellékhatás - mentes műveletre
mapM' f (a:as) =
f a >>= \b ->
mapM' f as >>= \bs ->
pure (b:bs)
-- lista "szekvenciálás"
műveletek listája -- > listát
sequence' :: Monad m => [m a] -> m [a]
sequence' mas = mapM' (\ma -> ma) mas -- mapM' id
konstans bind : egymás után végrehajtunk két műveletet , függ
-- az első visszatérési értékétől
( > > ) : : = > m a - > m b - > m b
( > > ) = ma > > = \ _ - > mb
-- IO monád
--------------------------------------------------------------------------------
instance Monad IO
( )
p : : IO a -- , " a " típusú értékkel tér vissza
-- main függvény:
( ) standard típus , kiejtése " unit "
data One = One
data ( ) = ( ) -- ( )
-- print :: Show a => a -> IO ()
--
main : : IO ( ) -- IO mellékhatás + triviális értékkel tér vissza
main = print 100 > > print True > > print [ 0 .. 10 ]
getLine : : IO String -- egy sort beolvas stdin - ról
putStrLn : : String - > IO ( ) -- , newline a végére
-- main :: IO ()
-- main =
getLine > > = \l - >
l > >
l
-- do notation:
main :: IO ()
main = do
l <- getLine -- var l = getLine();
putStrLn l
putStrLn l
-- do
-- 1 vagy több sor
:
-- x <- rhs
-- p1
-- p2
-- példák a fordításra:
-- do
-- x <- rhs rhs >>= \x ->
-- p p
-- do
-- p1 p1 >>
-- p2 p2
main' :: IO ()
main' = do {l <- getLine; putStrLn l; putStrLn l}
-- Maybe
mapMaybe'' :: (a -> Maybe b) -> [a] -> Maybe [b]
mapMaybe'' f [] = pure []
mapMaybe'' f (a:as) = do
b <- f a
bs <- mapMaybe f as
pure (b:bs)
( ghci - ben : ha ( IO a ) értéket írunk be , azt le is futtatja )
mapM verziója , amikor a viszatérési érték nem érdekes , csak a hatás
mapM _ : : = > ( a - > m b ) - > [ a ] - > m ( )
mapM_' :: Monad m => (a -> m b) -> [a] -> m ()
mapM_' f [] = pure ()
mapM_' f (a:as) = f a >> mapM_' f as
Control . :
-- monadikus replicate
replicateM :: Monad m => Int -> m a -> m [a]
replicateM n ma | n <= 0 = pure []
replicateM n ma = do
a <- ma
as <- replicateM (n - 1) ma
pure (a:as)
replicateM_ :: Monad m => Int -> m a -> m ()
replicateM_ = undefined
forever :: Monad m => m a -> m b
forever ma = ma >> forever ma
-- "fish"
infixr 1 >=>
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
(>=>) f g a = f a >>= g
-- do b <- f a
-- g b
--------------------------------------------------------------------------------
Intuitívan , törvények : ( alapvető imperatív nyelvtől )
pure jár hatással
-- pure >=> f = f do {x <- pure v; f x} = f v
-- f >=> pure = f do {x <- f a; pure x} = f a
-- csak a műveletek *sorrendje* számít, a csoportosításuk nem (szekvencialitás)
minden imperatív program
-- f >=> (g >=> h) = (f >=> g) >=> h
do { x < - f a ; y ; h y } = do { y < - do { x < - f a ; g x } ; h y }
State monad
--------------------------------------------------------------------------------
p : : State s a -- művelet , " s " típusú változót tud
-- mutable módon írni / olvasni
State s a -- > nyelvbe beágyaz mutációt
intuíció : szimpla a függvényt ,
" s " típusú
s - > s ( nem elég , mert nincs visszatérési érték )
-- s -> (a, s)
-- input állapot (visszatérési érték, output állapot)
newtype State s a = State (s -> (a, s))
instance ( State s )
-- instance Applicative (State s)
instance ( State s )
-- get, put függvények (állapot-módosító függvények)
| null | https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/88d41930999d6056bdd7bfaa85761a527cce4113/2020-21-2/ea/Notes04.hs | haskell | IO
Monad törvények
Monad : custom
Maybe : mellékhatás = Nothing propagálás mint kivétel
Just :: a -> Maybe a
bind :: Maybe a -> (a -> Maybe b) -> Maybe b
"monádikus" forma
sima függvény komp: (.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g x = f (g x)
------------------------------------------------------------------------------
class Functor f where
fmap :: (a -> b) -> f a -> f b
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b -- ap
class Applicative m => Monad m where
return :: a -> m a
ez a bind
(én személye szerint: csak a pure-t használom, a return-t)
instance Functor Maybe where
fmap f Nothing = Nothing
fmap f (Just a) = Just (f a)
instance Applicative Maybe where
pure = return
(<*>) = ap
return = Just
> Applicative triviális
ha van Applicative instance --> Functor triviális
(>>=) :: m a -> (a -> m b) -> m b
pure/return :: a -> m a
f a :: b
------------------------------------------------------------------------------
standard: mapM
lista "szekvenciálás"
> listát
mapM' id
az első visszatérési értékétől
IO monád
------------------------------------------------------------------------------
, " a " típusú értékkel tér vissza
main függvény:
( )
print :: Show a => a -> IO ()
IO mellékhatás + triviális értékkel tér vissza
egy sort beolvas stdin - ról
, newline a végére
main :: IO ()
main =
do notation:
var l = getLine();
do
1 vagy több sor
x <- rhs
p1
p2
példák a fordításra:
do
x <- rhs rhs >>= \x ->
p p
do
p1 p1 >>
p2 p2
Maybe
monadikus replicate
"fish"
do b <- f a
g b
------------------------------------------------------------------------------
pure >=> f = f do {x <- pure v; f x} = f v
f >=> pure = f do {x <- f a; pure x} = f a
csak a műveletek *sorrendje* számít, a csoportosításuk nem (szekvencialitás)
f >=> (g >=> h) = (f >=> g) >=> h
------------------------------------------------------------------------------
művelet , " s " típusú változót tud
mutable módon írni / olvasni
> nyelvbe beágyaz mutációt
s -> (a, s)
input állapot (visszatérési érték, output állapot)
instance Applicative (State s)
get, put függvények (állapot-módosító függvények) |
import Control.Monad (ap)
Maybe ismétlés , : mapM , sequence
do notáció
további : replicateM , forever , filterM
State monad
motiváció : Maybe : hibakódos hibakazelés ( sok zaj )
catch / throw ,
Maybe van
bind :: Maybe a -> (a -> Maybe b) -> Maybe b
bind Nothing _ = Nothing
bind (Just a) f = f a
mapMaybe :: (a -> Maybe b) -> [a] -> Maybe [b]
mapMaybe f [] = Just []
mapMaybe f (a:as) = case f a of
Nothing -> Nothing
Just b -> case mapMaybe f as of
Nothing -> Nothing
Just bs -> Just (b:bs)
mapMaybe' :: (a -> Maybe b) -> [a] -> Maybe [b]
mapMaybe' f [] = Just []
mapMaybe' f (a:as) =
bind (f a) $ \b ->
bind (mapMaybe f as) $ \bs ->
Just (b:bs)
( std általános függvény is )
compMaybe' :: (a -> Maybe b) -> (b -> Maybe c) -> a -> Maybe c
compMaybe' f g a = case f a of
Nothing -> Nothing
Just b -> g b
compMaybe :: (a -> Maybe b) -> (b -> Maybe c) -> a -> Maybe c
compMaybe f g a = bind (f a) g
return ugyanaz mint a pure ( konvenció : return definíciója ugyanaz , mint pure - é )
( )
instance Maybe where
( > > bind
data Maybe' a = Nothing' | Just' a
instance Functor Maybe' where
fmap = fmapFromMonad
instance Applicative Maybe' where
pure = return
(<*>) = ap
instance Monad Maybe' where
return = Just'
Nothing' >>= f = Nothing'
Just' a >>= f = f a
fmapFromMonad :: Monad m => (a -> b) -> m a -> m b
fmapFromMonad f ma = ma >>= \a -> pure (f a)
monádikus map
mapM' :: Monad m => (a -> m b) -> [a] -> m [b]
tiszta értékre ,
mint mellékhatás - mentes műveletre
mapM' f (a:as) =
f a >>= \b ->
mapM' f as >>= \bs ->
pure (b:bs)
sequence' :: Monad m => [m a] -> m [a]
konstans bind : egymás után végrehajtunk két műveletet , függ
( > > ) : : = > m a - > m b - > m b
( > > ) = ma > > = \ _ - > mb
instance Monad IO
( )
( ) standard típus , kiejtése " unit "
data One = One
main = print 100 > > print True > > print [ 0 .. 10 ]
getLine > > = \l - >
l > >
l
main :: IO ()
main = do
putStrLn l
putStrLn l
:
main' :: IO ()
main' = do {l <- getLine; putStrLn l; putStrLn l}
mapMaybe'' :: (a -> Maybe b) -> [a] -> Maybe [b]
mapMaybe'' f [] = pure []
mapMaybe'' f (a:as) = do
b <- f a
bs <- mapMaybe f as
pure (b:bs)
( ghci - ben : ha ( IO a ) értéket írunk be , azt le is futtatja )
mapM verziója , amikor a viszatérési érték nem érdekes , csak a hatás
mapM _ : : = > ( a - > m b ) - > [ a ] - > m ( )
mapM_' :: Monad m => (a -> m b) -> [a] -> m ()
mapM_' f [] = pure ()
mapM_' f (a:as) = f a >> mapM_' f as
Control . :
replicateM :: Monad m => Int -> m a -> m [a]
replicateM n ma | n <= 0 = pure []
replicateM n ma = do
a <- ma
as <- replicateM (n - 1) ma
pure (a:as)
replicateM_ :: Monad m => Int -> m a -> m ()
replicateM_ = undefined
forever :: Monad m => m a -> m b
forever ma = ma >> forever ma
infixr 1 >=>
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
(>=>) f g a = f a >>= g
Intuitívan , törvények : ( alapvető imperatív nyelvtől )
pure jár hatással
minden imperatív program
do { x < - f a ; y ; h y } = do { y < - do { x < - f a ; g x } ; h y }
State monad
intuíció : szimpla a függvényt ,
" s " típusú
s - > s ( nem elég , mert nincs visszatérési érték )
newtype State s a = State (s -> (a, s))
instance ( State s )
instance ( State s )
|
670eadec8fe6d536177932a9cfe01537370ee699d24bee2c559d132b33447bc4 | sadiqj/ocaml-esp32 | profile.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Pierre Chambart, OCamlPro *)
(* *)
Copyright 2015 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Compiler performance recording *)
type file = string
val reset : unit -> unit
(** erase all recorded profile information *)
val record_call : ?accumulate:bool -> string -> (unit -> 'a) -> 'a
* [ record_call pass f ] calls [ f ] and records its profile information .
val record : ?accumulate:bool -> string -> ('a -> 'b) -> 'a -> 'b
(** [record pass f arg] records the profile information of [f arg] *)
type column = [ `Time | `Alloc | `Top_heap | `Abs_top_heap ]
val print : Format.formatter -> column list -> unit
(** Prints the selected recorded profiling information to the formatter. *)
(** Command line flags *)
val options_doc : string
val all_columns : column list
(** A few pass names that are needed in several places, and shared to
avoid typos. *)
val generate : string
val transl : string
val typing : string
| null | https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/utils/profile.mli | ocaml | ************************************************************************
OCaml
Pierre Chambart, OCamlPro
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Compiler performance recording
* erase all recorded profile information
* [record pass f arg] records the profile information of [f arg]
* Prints the selected recorded profiling information to the formatter.
* Command line flags
* A few pass names that are needed in several places, and shared to
avoid typos. | Copyright 2015 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
type file = string
val reset : unit -> unit
val record_call : ?accumulate:bool -> string -> (unit -> 'a) -> 'a
* [ record_call pass f ] calls [ f ] and records its profile information .
val record : ?accumulate:bool -> string -> ('a -> 'b) -> 'a -> 'b
type column = [ `Time | `Alloc | `Top_heap | `Abs_top_heap ]
val print : Format.formatter -> column list -> unit
val options_doc : string
val all_columns : column list
val generate : string
val transl : string
val typing : string
|
46d9dbb13969d06223901867c71566731c21c88ce6ac6f9d29e2fb5807c92976 | smart-chain-fr/tokenomia | Plan.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE TupleSections #
# LANGUAGE NumericUnderscores #
# LANGUAGE NamedFieldPuns #
# LANGUAGE TypeApplications #
# LANGUAGE FlexibleInstances #
module Tokenomia.ICO.Funds.Exchange.Plan
( mkPlan
, mkPlan'
, mkPlanSettings
, State (..)
, Plan (..)
, getTxBalance
, IOOnTokenAddress (..) ) where
import Prelude hiding (round,print)
import Data.Set.Ordered
import Ledger.Ada
import Data.List.NonEmpty as NEL
import Tokenomia.ICO.Funds.Exchange.ReceivedFunds
import Tokenomia.ICO.Funds.Exchange.Command
import Tokenomia.ICO.Funds.Exchange.Tokens
import Tokenomia.Common.Token
import qualified Data.Set.Ordered as SO
import qualified Data.Set.NonEmpty as NES
import Tokenomia.ICO.Funds.Exchange.Plan.Settings
import Tokenomia.ICO.Round.Settings
import Tokenomia.Common.Transacting
import Data.Set.NonEmpty (NESet)
import Tokenomia.ICO.Balanceable
mkPlan
:: PlanSettings
-> Ada
-> Maybe Fees
-> Maybe ExchangeToken
-> NESet AuthentifiedFunds
-> Plan Command
mkPlan a b c d e = snd $ mkPlan' a b c d e
mkPlan'
:: PlanSettings
-> Ada
-> Maybe Fees
-> Maybe ExchangeToken
-> NESet AuthentifiedFunds
-> (State,Plan Command)
mkPlan' settings minimumAdaRequiredOnUtxoWithToken feesMaybe exchangeTokenMaybe allReceivedFunds
= let (quotFees,remFees) = getQuotRem feesMaybe allReceivedFunds
s@State {commands} = foldr
transition
State
{ commands = empty
, quotientFeesPerFund = quotFees
, remainderFeesPerFund = remFees
, totalCommands = NES.size allReceivedFunds
, .. }
(NES.toDescList allReceivedFunds)
in (s,Plan
{ feesMaybe = feesMaybe
, ioOnTokenAddress = mkIOOnTokenAddress exchangeTokenMaybe commands
, commands = (NES.fromList . NEL.fromList . SO.toAscList) commands})
getQuotRem
:: Maybe Fees
-> NESet AuthentifiedFunds
-> (Fees,Fees)
getQuotRem Nothing _ = (0,0)
getQuotRem (Just totalFees ) xs = totalFees `quotRem` (fromIntegral . NES.size) xs
data State = State
{ settings :: !PlanSettings
, minimumAdaRequiredOnUtxoWithToken :: Ada
, feesMaybe :: ! (Maybe Fees)
, quotientFeesPerFund :: !Fees
, remainderFeesPerFund :: !Fees
, totalCommands :: !Int
, exchangeTokenMaybe :: !(Maybe ExchangeToken)
, commands :: !(OSet Command)} deriving Show
transition :: AuthentifiedFunds -> State -> State
transition AuthentifiedFunds {..} State {exchangeTokenMaybe = exchangeTokenMaybe@Nothing,..}
= appendCommand $ RejectBecauseTokensSoldOut
{rejectAmount = adas - feesPerCommand
,..}
where
appendCommand command = State { commands = commands |> command , .. }
feesPerCommand = quotientFeesPerFund + addRemainderFeesPerFundIfLastCommand
addRemainderFeesPerFundIfLastCommand = if totalCommands == size commands +1 then remainderFeesPerFund else 0
transition AuthentifiedFunds {..} State { exchangeTokenMaybe = exchangeTokenMaybe@(Just ExchangeToken{token = Token{ amount = exchangeTokenAmount, minimumAdaRequired = adasOnExchangeToken}})
, settings = settings@Settings {..},..}
| tokenSoldOutWithPreviousFunds
= appendCommand $ RejectBecauseTokensSoldOut {rejectAmount = adas - feesPerCommand,..}
| tokenSoldOutWithIncomingFund && refundIsUnderMinimum
= appendCommand
ExchangeAndPartiallyReject
{ collectedAmount = collectedAmmountWhenSoldoutWithIncomingFund - minimumAdaRequiredOnUtxoWithToken
, rejectAmount = rejectAmountWhenSoldOutWithIncomingFund + minimumAdaRequiredOnUtxoWithToken
, tokens = Token { assetClass = exchangeTokenId
, amount = availableTokenAmount
, minimumAdaRequired = minimumAdaRequiredOnUtxoWithToken}, ..}
| tokenSoldOutWithIncomingFund && collectIsUnderMinimum
= appendCommand
ExchangeAndPartiallyReject
{ collectedAmount = collectedAmmountWhenSoldoutWithIncomingFund + minimumAdaRequiredOnUtxoWithToken
, rejectAmount = rejectAmountWhenSoldOutWithIncomingFund - minimumAdaRequiredOnUtxoWithToken
, tokens = Token { assetClass = exchangeTokenId
, amount = availableTokenAmount
, minimumAdaRequired = minimumAdaRequiredOnUtxoWithToken}, ..}
| tokenSoldOutWithIncomingFund
= appendCommand
ExchangeAndPartiallyReject
{ collectedAmount = collectedAmmountWhenSoldoutWithIncomingFund
, rejectAmount = rejectAmountWhenSoldOutWithIncomingFund
, tokens = Token { assetClass = exchangeTokenId
, amount = availableTokenAmount
, minimumAdaRequired = minimumAdaRequiredOnUtxoWithToken}, ..}
| otherwise
= appendCommand $ Exchange
{ collectedAmount = adas - feesPerCommand - minimumAdaRequiredOnUtxoWithToken -- (899957104-1379280)/8562147
, tokens = Token { assetClass = exchangeTokenId
, amount = tokenAmountCurrentFund
, minimumAdaRequired = minimumAdaRequiredOnUtxoWithToken }, ..}
where
appendCommand command = State { commands = commands |> command , .. }
tokenAmountCurrentFund = floor (tokenRatePerLovelace * (fromIntegral adas - fromIntegral feesPerCommand))
tokenSoldOutWithPreviousFunds = getTokensSum commands >= exchangeTokenAmount
tokenSoldOutWithIncomingFund = getTokensSum commands + tokenAmountCurrentFund >= exchangeTokenAmount
availableTokenAmount = exchangeTokenAmount - getTokensSum commands
rejectAmountWhenSoldOutWithIncomingFund = adas - feesPerCommand - ceiling (fromIntegral availableTokenAmount / tokenRatePerLovelace)
feesPerCommand = quotientFeesPerFund + addRemainderFeesPerFundIfLastCommand
addRemainderFeesPerFundIfLastCommand = if totalCommands == size commands +1 then remainderFeesPerFund else 0
collectedAmmountWhenSoldoutWithIncomingFund = adas + adasOnExchangeToken - rejectAmountWhenSoldOutWithIncomingFund - minimumAdaRequiredOnUtxoWithToken - feesPerCommand
refundIsUnderMinimum = rejectAmountWhenSoldOutWithIncomingFund < minimumAdaRequiredOnUtxoWithToken
collectIsUnderMinimum = collectedAmmountWhenSoldoutWithIncomingFund < minimumAdaRequiredOnUtxoWithToken
mkIOOnTokenAddress :: Maybe ExchangeToken -> OSet Command -> Maybe IOOnTokenAddress
mkIOOnTokenAddress Nothing _ = Nothing
mkIOOnTokenAddress (Just source@ExchangeToken{token = Token {assetClass,amount = sourceAmount,..}}) commands =
let tokenExchangedAmount = getTokensSum commands
in case sourceAmount - tokenExchangedAmount of
tokenRemaining | tokenRemaining > 0 -> Just IOOnTokenAddress { remainingTokensMaybe = Just Token {assetClass = assetClass, amount = tokenRemaining , ..},..}
_ -> Just IOOnTokenAddress { remainingTokensMaybe = Nothing , ..}
data IOOnTokenAddress
= IOOnTokenAddress
{ source :: ExchangeToken
, remainingTokensMaybe :: Maybe Token} deriving Show
data Plan command
= Plan
{ feesMaybe :: Maybe Fees
, ioOnTokenAddress :: Maybe IOOnTokenAddress
, commands :: NES.NESet command }
instance (Show command) => Show (Plan command) where
show Plan {..} =
"\n|| PLAN || "
<> "\n| Fees = " <> show feesMaybe
<> "\n| IO On tokenAddress = " <> show ioOnTokenAddress
instance AdaBalanceable (Plan Command) where
adaBalance Plan {..} = adaBalance commands + adaBalance ioOnTokenAddress - adaBalance feesMaybe
instance TokenBalanceable (Plan Command) where
tokenBalance Plan {..} = tokenBalance commands - tokenBalance ioOnTokenAddress
instance AdaBalanceable IOOnTokenAddress where
adaBalance IOOnTokenAddress {..} = adaBalance source - adaBalance remainingTokensMaybe
instance TokenBalanceable IOOnTokenAddress where
tokenBalance IOOnTokenAddress {..} = tokenBalance source - tokenBalance remainingTokensMaybe
getTxBalance :: RoundAddresses -> Plan a -> TxBalance
getTxBalance _ Plan {feesMaybe = Just fees} = Balanced fees
getTxBalance roundAddresses Plan {feesMaybe = Nothing} = Unbalanced $ getFees roundAddresses
| null | https://raw.githubusercontent.com/smart-chain-fr/tokenomia/dfb46829f0a88c559eddb3181e5320ed1a33601e/src/Tokenomia/ICO/Funds/Exchange/Plan.hs | haskell | # LANGUAGE OverloadedStrings #
(899957104-1379280)/8562147 | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE TupleSections #
# LANGUAGE NumericUnderscores #
# LANGUAGE NamedFieldPuns #
# LANGUAGE TypeApplications #
# LANGUAGE FlexibleInstances #
module Tokenomia.ICO.Funds.Exchange.Plan
( mkPlan
, mkPlan'
, mkPlanSettings
, State (..)
, Plan (..)
, getTxBalance
, IOOnTokenAddress (..) ) where
import Prelude hiding (round,print)
import Data.Set.Ordered
import Ledger.Ada
import Data.List.NonEmpty as NEL
import Tokenomia.ICO.Funds.Exchange.ReceivedFunds
import Tokenomia.ICO.Funds.Exchange.Command
import Tokenomia.ICO.Funds.Exchange.Tokens
import Tokenomia.Common.Token
import qualified Data.Set.Ordered as SO
import qualified Data.Set.NonEmpty as NES
import Tokenomia.ICO.Funds.Exchange.Plan.Settings
import Tokenomia.ICO.Round.Settings
import Tokenomia.Common.Transacting
import Data.Set.NonEmpty (NESet)
import Tokenomia.ICO.Balanceable
mkPlan
:: PlanSettings
-> Ada
-> Maybe Fees
-> Maybe ExchangeToken
-> NESet AuthentifiedFunds
-> Plan Command
mkPlan a b c d e = snd $ mkPlan' a b c d e
mkPlan'
:: PlanSettings
-> Ada
-> Maybe Fees
-> Maybe ExchangeToken
-> NESet AuthentifiedFunds
-> (State,Plan Command)
mkPlan' settings minimumAdaRequiredOnUtxoWithToken feesMaybe exchangeTokenMaybe allReceivedFunds
= let (quotFees,remFees) = getQuotRem feesMaybe allReceivedFunds
s@State {commands} = foldr
transition
State
{ commands = empty
, quotientFeesPerFund = quotFees
, remainderFeesPerFund = remFees
, totalCommands = NES.size allReceivedFunds
, .. }
(NES.toDescList allReceivedFunds)
in (s,Plan
{ feesMaybe = feesMaybe
, ioOnTokenAddress = mkIOOnTokenAddress exchangeTokenMaybe commands
, commands = (NES.fromList . NEL.fromList . SO.toAscList) commands})
getQuotRem
:: Maybe Fees
-> NESet AuthentifiedFunds
-> (Fees,Fees)
getQuotRem Nothing _ = (0,0)
getQuotRem (Just totalFees ) xs = totalFees `quotRem` (fromIntegral . NES.size) xs
data State = State
{ settings :: !PlanSettings
, minimumAdaRequiredOnUtxoWithToken :: Ada
, feesMaybe :: ! (Maybe Fees)
, quotientFeesPerFund :: !Fees
, remainderFeesPerFund :: !Fees
, totalCommands :: !Int
, exchangeTokenMaybe :: !(Maybe ExchangeToken)
, commands :: !(OSet Command)} deriving Show
transition :: AuthentifiedFunds -> State -> State
transition AuthentifiedFunds {..} State {exchangeTokenMaybe = exchangeTokenMaybe@Nothing,..}
= appendCommand $ RejectBecauseTokensSoldOut
{rejectAmount = adas - feesPerCommand
,..}
where
appendCommand command = State { commands = commands |> command , .. }
feesPerCommand = quotientFeesPerFund + addRemainderFeesPerFundIfLastCommand
addRemainderFeesPerFundIfLastCommand = if totalCommands == size commands +1 then remainderFeesPerFund else 0
transition AuthentifiedFunds {..} State { exchangeTokenMaybe = exchangeTokenMaybe@(Just ExchangeToken{token = Token{ amount = exchangeTokenAmount, minimumAdaRequired = adasOnExchangeToken}})
, settings = settings@Settings {..},..}
| tokenSoldOutWithPreviousFunds
= appendCommand $ RejectBecauseTokensSoldOut {rejectAmount = adas - feesPerCommand,..}
| tokenSoldOutWithIncomingFund && refundIsUnderMinimum
= appendCommand
ExchangeAndPartiallyReject
{ collectedAmount = collectedAmmountWhenSoldoutWithIncomingFund - minimumAdaRequiredOnUtxoWithToken
, rejectAmount = rejectAmountWhenSoldOutWithIncomingFund + minimumAdaRequiredOnUtxoWithToken
, tokens = Token { assetClass = exchangeTokenId
, amount = availableTokenAmount
, minimumAdaRequired = minimumAdaRequiredOnUtxoWithToken}, ..}
| tokenSoldOutWithIncomingFund && collectIsUnderMinimum
= appendCommand
ExchangeAndPartiallyReject
{ collectedAmount = collectedAmmountWhenSoldoutWithIncomingFund + minimumAdaRequiredOnUtxoWithToken
, rejectAmount = rejectAmountWhenSoldOutWithIncomingFund - minimumAdaRequiredOnUtxoWithToken
, tokens = Token { assetClass = exchangeTokenId
, amount = availableTokenAmount
, minimumAdaRequired = minimumAdaRequiredOnUtxoWithToken}, ..}
| tokenSoldOutWithIncomingFund
= appendCommand
ExchangeAndPartiallyReject
{ collectedAmount = collectedAmmountWhenSoldoutWithIncomingFund
, rejectAmount = rejectAmountWhenSoldOutWithIncomingFund
, tokens = Token { assetClass = exchangeTokenId
, amount = availableTokenAmount
, minimumAdaRequired = minimumAdaRequiredOnUtxoWithToken}, ..}
| otherwise
= appendCommand $ Exchange
, tokens = Token { assetClass = exchangeTokenId
, amount = tokenAmountCurrentFund
, minimumAdaRequired = minimumAdaRequiredOnUtxoWithToken }, ..}
where
appendCommand command = State { commands = commands |> command , .. }
tokenAmountCurrentFund = floor (tokenRatePerLovelace * (fromIntegral adas - fromIntegral feesPerCommand))
tokenSoldOutWithPreviousFunds = getTokensSum commands >= exchangeTokenAmount
tokenSoldOutWithIncomingFund = getTokensSum commands + tokenAmountCurrentFund >= exchangeTokenAmount
availableTokenAmount = exchangeTokenAmount - getTokensSum commands
rejectAmountWhenSoldOutWithIncomingFund = adas - feesPerCommand - ceiling (fromIntegral availableTokenAmount / tokenRatePerLovelace)
feesPerCommand = quotientFeesPerFund + addRemainderFeesPerFundIfLastCommand
addRemainderFeesPerFundIfLastCommand = if totalCommands == size commands +1 then remainderFeesPerFund else 0
collectedAmmountWhenSoldoutWithIncomingFund = adas + adasOnExchangeToken - rejectAmountWhenSoldOutWithIncomingFund - minimumAdaRequiredOnUtxoWithToken - feesPerCommand
refundIsUnderMinimum = rejectAmountWhenSoldOutWithIncomingFund < minimumAdaRequiredOnUtxoWithToken
collectIsUnderMinimum = collectedAmmountWhenSoldoutWithIncomingFund < minimumAdaRequiredOnUtxoWithToken
mkIOOnTokenAddress :: Maybe ExchangeToken -> OSet Command -> Maybe IOOnTokenAddress
mkIOOnTokenAddress Nothing _ = Nothing
mkIOOnTokenAddress (Just source@ExchangeToken{token = Token {assetClass,amount = sourceAmount,..}}) commands =
let tokenExchangedAmount = getTokensSum commands
in case sourceAmount - tokenExchangedAmount of
tokenRemaining | tokenRemaining > 0 -> Just IOOnTokenAddress { remainingTokensMaybe = Just Token {assetClass = assetClass, amount = tokenRemaining , ..},..}
_ -> Just IOOnTokenAddress { remainingTokensMaybe = Nothing , ..}
data IOOnTokenAddress
= IOOnTokenAddress
{ source :: ExchangeToken
, remainingTokensMaybe :: Maybe Token} deriving Show
data Plan command
= Plan
{ feesMaybe :: Maybe Fees
, ioOnTokenAddress :: Maybe IOOnTokenAddress
, commands :: NES.NESet command }
instance (Show command) => Show (Plan command) where
show Plan {..} =
"\n|| PLAN || "
<> "\n| Fees = " <> show feesMaybe
<> "\n| IO On tokenAddress = " <> show ioOnTokenAddress
instance AdaBalanceable (Plan Command) where
adaBalance Plan {..} = adaBalance commands + adaBalance ioOnTokenAddress - adaBalance feesMaybe
instance TokenBalanceable (Plan Command) where
tokenBalance Plan {..} = tokenBalance commands - tokenBalance ioOnTokenAddress
instance AdaBalanceable IOOnTokenAddress where
adaBalance IOOnTokenAddress {..} = adaBalance source - adaBalance remainingTokensMaybe
instance TokenBalanceable IOOnTokenAddress where
tokenBalance IOOnTokenAddress {..} = tokenBalance source - tokenBalance remainingTokensMaybe
getTxBalance :: RoundAddresses -> Plan a -> TxBalance
getTxBalance _ Plan {feesMaybe = Just fees} = Balanced fees
getTxBalance roundAddresses Plan {feesMaybe = Nothing} = Unbalanced $ getFees roundAddresses
|
2f10c3f1386b582b079ec60954b8f1c9195d99ad2ae5459508b0485d875c04f5 | realgenekim/rss-reader-fulcro-demo | jib.clj | (ns jib
;(:require [clojure.tools.build.api :as b])
(:import
(com.google.cloud.tools.jib.api Jib
DockerDaemonImage
Containerizer
TarImage
RegistryImage
ImageReference CredentialRetriever Credential)
(com.google.cloud.tools.jib.api.buildplan AbsoluteUnixPath)
(com.google.cloud.tools.jib.frontend
CredentialRetrieverFactory)
(java.util.function Consumer)
(java.nio.file Paths)
(java.io File)
(java.util List ArrayList Optional)))
from - build : -jib-build
(defn- get-path [filename]
(Paths/get (.toURI (File. ^String filename))))
(defn- into-list
[& args]
(ArrayList. ^List args))
(defn- to-imgref [image-config]
(ImageReference/parse image-config))
from JUXT pack :
(defn make-logger [verbose]
(reify Consumer
(accept [this log-event]
(when verbose
(println (.getMessage log-event))))))
(def logger (make-logger true))
(def image-name "us.gcr.io/booktracker-1208/feedly-reader-exe:latest")
(def base-image-with-creds
; we can't run distroless, because we need /bin/bash and entrypoint.sh, until we can figure out how
; to set file modes to executable via jib
" debug " label gives
(-> (RegistryImage/named "gcr.io/distroless/base-debian11:debug")
60 MB , but
; error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
( - > ( RegistryImage / named " gcr.io/distroless/java:debug " )
359 MB
( - > ( RegistryImage / named " gcr.io/google-appengine/debian11 " )
123 MB
( - > ( RegistryImage / named " us.gcr.io/google-containers/alpine-with-bash:1.0 " )
(.addCredentialRetriever
(-> (CredentialRetrieverFactory/forImage
(to-imgref image-name)
logger)
(.dockerConfig)))))
;(.wellKnownCredentialHelpers)))))
(def local-standalone-jar-path "./feedly-reader-standalone")
(def app-layer [(into-list (get-path local-standalone-jar-path))
(AbsoluteUnixPath/get "/")])
(def entrypoint ["/busybox/sh" "entrypoint.sh"])
;(def entrypoint ["/bin/sh" "entrypoint.sh"])
(def arguments local-standalone-jar-path)
;(def image-name "us.gcr.io/booktracker-1208/pubsub-web-jib-test:latest")
;(def image-name "us.gcr.io/booktracker-1208/pubsub-web:latest")
(defn jib-deploy [_]
(time (-> (Jib/from base-image-with-creds)
; keys
(.addLayer (into-list (get-path "./bin/entrypoint.sh"))
(AbsoluteUnixPath/get "/"))
; jar file
(.addLayer (first app-layer) (second app-layer))
(.setEntrypoint (apply into-list entrypoint))
(.setProgramArguments (into-list arguments))
(.containerize
(Containerizer/to
(->
(RegistryImage/named
(to-imgref image-name))
(.addCredentialRetriever
(-> (CredentialRetrieverFactory/forImage
(to-imgref image-name)
logger),
;(.dockerCredentialHelper "/Users/genekim/software/google-cloud-sdk/bin/docker-credential-gcloud")
(.dockerConfig)))))))))
;(wellKnownCredentialHelpers)))))))))
| null | https://raw.githubusercontent.com/realgenekim/rss-reader-fulcro-demo/6eab011cfa9e24ef6cf670ad53ae101568e1df97/jib.clj | clojure | (:require [clojure.tools.build.api :as b])
we can't run distroless, because we need /bin/bash and entrypoint.sh, until we can figure out how
to set file modes to executable via jib
error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
(.wellKnownCredentialHelpers)))))
(def entrypoint ["/bin/sh" "entrypoint.sh"])
(def image-name "us.gcr.io/booktracker-1208/pubsub-web-jib-test:latest")
(def image-name "us.gcr.io/booktracker-1208/pubsub-web:latest")
keys
jar file
(.dockerCredentialHelper "/Users/genekim/software/google-cloud-sdk/bin/docker-credential-gcloud")
(wellKnownCredentialHelpers))))))))) | (ns jib
(:import
(com.google.cloud.tools.jib.api Jib
DockerDaemonImage
Containerizer
TarImage
RegistryImage
ImageReference CredentialRetriever Credential)
(com.google.cloud.tools.jib.api.buildplan AbsoluteUnixPath)
(com.google.cloud.tools.jib.frontend
CredentialRetrieverFactory)
(java.util.function Consumer)
(java.nio.file Paths)
(java.io File)
(java.util List ArrayList Optional)))
from - build : -jib-build
(defn- get-path [filename]
(Paths/get (.toURI (File. ^String filename))))
(defn- into-list
[& args]
(ArrayList. ^List args))
(defn- to-imgref [image-config]
(ImageReference/parse image-config))
from JUXT pack :
(defn make-logger [verbose]
(reify Consumer
(accept [this log-event]
(when verbose
(println (.getMessage log-event))))))
(def logger (make-logger true))
(def image-name "us.gcr.io/booktracker-1208/feedly-reader-exe:latest")
(def base-image-with-creds
" debug " label gives
(-> (RegistryImage/named "gcr.io/distroless/base-debian11:debug")
60 MB , but
( - > ( RegistryImage / named " gcr.io/distroless/java:debug " )
359 MB
( - > ( RegistryImage / named " gcr.io/google-appengine/debian11 " )
123 MB
( - > ( RegistryImage / named " us.gcr.io/google-containers/alpine-with-bash:1.0 " )
(.addCredentialRetriever
(-> (CredentialRetrieverFactory/forImage
(to-imgref image-name)
logger)
(.dockerConfig)))))
(def local-standalone-jar-path "./feedly-reader-standalone")
(def app-layer [(into-list (get-path local-standalone-jar-path))
(AbsoluteUnixPath/get "/")])
(def entrypoint ["/busybox/sh" "entrypoint.sh"])
(def arguments local-standalone-jar-path)
(defn jib-deploy [_]
(time (-> (Jib/from base-image-with-creds)
(.addLayer (into-list (get-path "./bin/entrypoint.sh"))
(AbsoluteUnixPath/get "/"))
(.addLayer (first app-layer) (second app-layer))
(.setEntrypoint (apply into-list entrypoint))
(.setProgramArguments (into-list arguments))
(.containerize
(Containerizer/to
(->
(RegistryImage/named
(to-imgref image-name))
(.addCredentialRetriever
(-> (CredentialRetrieverFactory/forImage
(to-imgref image-name)
logger),
(.dockerConfig)))))))))
|
f5698d1b728c043061ee4f3623821ddd34495c1ac47e7d46baacbc1016274f46 | gogins/csound-extended-nudruz | all-in-one-orc.lisp | ;; An example Csound orchestra for Common Lisp to be used with the
;; csound.lisp or sb-csound.lisp foreign function interfaces for Csound.
(in-package :cm)
(defparameter all-in-one-orc #>qqq>
sr = 48000
ksmps = 64
nchnls = 2
0dbfs = 32768
iampdbfs init 32768
prints "Default amplitude at 0 dBFS: %9.4f\n", iampdbfs
idbafs init dbamp(iampdbfs)
prints "dbA at 0 dBFS: %9.4f\n", idbafs
iheadroom init 6
prints "Headroom (dB): %9.4f\n", iheadroom
idbaheadroom init idbafs - iheadroom
prints "dbA at headroom: %9.4f\n", idbaheadroom
iampheadroom init ampdb(idbaheadroom)
prints "Amplitude at headroom: %9.4f\n", iampheadroom
prints "Balance so the overall amps at the end of performance is -6 dbfs.\n"
giFlatQ init sqrt(0.5)
giseed init 0.5
gkHarpsichordGain chnexport "gkHarpsichordGain", 1
gkHarpsichordGain init 1
gkHarpsichordPan chnexport "gkHarpsichordPan", 1
gkHarpsichordPan init 0.5
gkChebyshevDroneCoefficient1 chnexport "gkChebyshevDroneCoefficient1", 1
gkChebyshevDroneCoefficient1 init 0.5
gkChebyshevDroneCoefficient2 chnexport "gkChebyshevDroneCoefficient2", 1
gkChebyshevDroneCoefficient3 chnexport "gkChebyshevDroneCoefficient3", 1
gkChebyshevDroneCoefficient4 chnexport "gkChebyshevDroneCoefficient4", 1
gkChebyshevDroneCoefficient5 chnexport "gkChebyshevDroneCoefficient5", 1
gkChebyshevDroneCoefficient6 chnexport "gkChebyshevDroneCoefficient6", 1
gkChebyshevDroneCoefficient7 chnexport "gkChebyshevDroneCoefficient7", 1
gkChebyshevDroneCoefficient8 chnexport "gkChebyshevDroneCoefficient8", 1
gkChebyshevDroneCoefficient9 chnexport "gkChebyshevDroneCoefficient9", 1
gkChebyshevDroneCoefficient10 chnexport "gkChebyshevDroneCoefficient10", 1
gkChebyshevDroneCoefficient10 init 0.05
gkReverberationEnabled chnexport "gkReverberationEnabled", 1
gkReverberationEnabled init 1
gkReverberationDelay chnexport "gkReverberationDelay", 1
gkReverberationDelay init 0.325
gkReverberationWet chnexport "gkReverberationWet", 1
gkReverberationWet init 0.15
gkCompressorEnabled chnexport "gkCompressorEnabled", 1
gkCompressorEnabled init 0
gkCompressorThreshold chnexport "gkCompressorThreshold", 1
gkCompressorLowKnee chnexport "gkCompressorLowKnee", 1
gkCompressorHighKnee chnexport "gkCompressorHighknee", 1
gkCompressorRatio chnexport "gkCompressorRatio", 1
gkCompressorAttack chnexport "gkCompressorAttack", 1
gkCompressorRelease chnexport "gkCompressorRelease", 1
gkMasterLevel chnexport "gkMasterLevel", 1
gkMasterLevel init 1.5
connect "BanchoffKleinBottle", "outleft", "Reverberation", "inleft"
connect "BanchoffKleinBottle", "outright", "Reverberation", "inright"
connect "BandedWG", "outleft", "Reverberation", "inleft"
connect "BandedWG", "outright", "Reverberation", "inright"
connect "BassModel", "outleft", "Reverberation", "inleft"
connect "BassModel", "outright", "Reverberation", "inright"
connect "ChebyshevDrone", "outleft", "Reverberation", "inleft"
connect "ChebyshevDrone", "outright", "Reverberation", "inright"
connect "ChebyshevMelody", "outleft", "Reverberation", "inleft"
connect "ChebyshevMelody", "outright", "Reverberation", "inright"
connect "Compressor", "outleft", "MasterOutput", "inleft"
connect "Compressor", "outright", "MasterOutput", "inright"
connect "DelayedPluckedString", "outleft", "Reverberation", "inleft"
connect "DelayedPluckedString", "outright", "Reverberation", "inright"
connect "EnhancedFMBell", "outleft", "Reverberation", "inleft"
connect "EnhancedFMBell", "outright", "Reverberation", "inright"
connect "FenderRhodesModel", "outleft", "Reverberation", "inleft"
connect "FenderRhodesModel", "outright", "Reverberation", "inright"
connect "FilteredSines", "outleft", "Reverberation", "inleft"
connect "FilteredSines", "outright", "Reverberation", "inright"
connect "Flute", "outleft", "Reverberation", "inleft"
connect "Flute", "outright", "Reverberation", "inright"
connect "FMModulatedChorusing", "outleft", "Reverberation", "inleft"
connect "FMModulatedChorusing", "outright", "Reverberation", "inright"
connect "FMModerateIndex", "outleft", "Reverberation", "inleft"
connect "FMModerateIndex", "outright", "Reverberation", "inright"
connect "FMModerateIndex2", "outleft", "Reverberation", "inleft"
connect "FMModerateIndex2", "outright", "Reverberation", "inright"
connect "FMWaterBell", "outleft", "Reverberation", "inleft"
connect "FMWaterBell", "outright", "Reverberation", "inright"
connect "Granular", "outleft", "Reverberation", "inleft"
connect "Granular", "outright", "Reverberation", "inright"
connect "Guitar", "outleft", "Reverberation", "inleft"
connect "Guitar", "outright", "Reverberation", "inright"
connect "Guitar2", "outleft", "Reverberation", "inleft"
connect "Guitar2", "outright", "Reverberation", "inright"
connect "Harpsichord", "outleft", "Reverberation", "inleft"
connect "Harpsichord", "outright", "Reverberation", "inright"
connect "HeavyMetalModel", "outleft", "Reverberation", "inleft"
connect "HeavyMetalModel", "outright", "Reverberation", "inright"
connect "Hypocycloid", "outleft", "Reverberation", "inleft"
connect "Hypocycloid", "outright", "Reverberation", "inright"
connect "KungModulatedFM", "outleft", "Reverberation", "inleft"
connect "KungModulatedFM", "outright", "Reverberation", "inright"
connect "ModerateFM", "outleft", "Reverberation", "inleft"
connect "ModerateFM", "outright", "Reverberation", "inright"
connect "ModulatedFM", "outleft", "Reverberation", "inleft"
connect "ModulatedFM", "outright", "Reverberation", "inright"
connect "Melody", "outleft", "Reverberation", "inleft"
connect "Melody", "outright", "Reverberation", "inright"
connect "ParametricEq1", "outleft", "ParametricEq2", "inleft"
connect "ParametricEq1", "outright", "ParametricEq2", "inright"
connect "ParametricEq2", "outleft", "MasterOutput", "inleft"
connect "ParametricEq2", "outright", "MasterOutput", "inright"
connect "PianoOut", "outleft", "Reverberation", "inleft"
connect "PianoOut", "outright", "Reverberation", "inright"
connect "PlainPluckedString", "outleft", "Reverberation", "inleft"
connect "PlainPluckedString", "outright", "Reverberation", "inright"
connect "PRCBeeThree", "outleft", "Reverberation", "inleft"
connect "PRCBeeThree", "outright", "Reverberation", "inright"
connect "PRCBeeThreeDelayed", "outleft", "Reverberation", "inleft"
connect "PRCBeeThreeDelayed", "outright", "Reverberation", "inright"
connect "PRCBowed", "outleft", "Reverberation", "inleft"
connect "PRCBowed", "outright", "Reverberation", "inright"
connect "Reverberation", "outleft", "Compressor", "inleft"
connect "Reverberation", "outright", "Compressor", "inright"
connect "STKBandedWG", "outleft", "Reverberation", "inleft"
connect "STKBandedWG", "outright", "Reverberation", "inright"
connect "STKBeeThree", "outleft", "Reverberation", "inleft"
connect "STKBeeThree", "outright", "Reverberation", "inright"
connect "STKBlowBotl", "outleft", "Reverberation", "inleft"
connect "STKBlowBotl", "outright", "Reverberation", "inright"
connect "STKBlowHole", "outleft", "Reverberation", "inleft"
connect "STKBlowHole", "outright", "Reverberation", "inright"
connect "STKBowed", "outleft", "Reverberation", "inleft"
connect "STKBowed", "outright", "Reverberation", "inright"
connect "STKClarinet", "outleft", "Reverberation", "inleft"
connect "STKClarinet", "outright", "Reverberation", "inright"
connect "STKDrummer", "outleft", "Reverberation", "inleft"
connect "STKDrummer", "outright", "Reverberation", "inright"
connect "STKFlute", "outleft", "Reverberation", "inleft"
connect "STKFlute", "outright", "Reverberation", "inright"
connect "STKFMVoices", "outleft", "Reverberation", "inleft"
connect "STKFMVoices", "outright", "Reverberation", "inright"
connect "STKHvyMetl", "outleft", "Reverberation", "inleft"
connect "STKHvyMetl", "outright", "Reverberation", "inright"
connect "STKMandolin", "outleft", "Reverberation", "inleft"
connect "STKMandolin", "outright", "Reverberation", "inright"
connect "STKModalBar", "outleft", "Reverberation", "inleft"
connect "STKModalBar", "outright", "Reverberation", "inright"
connect "STKMoog", "outleft", "Reverberation", "inleft"
connect "STKMoog", "outright", "Reverberation", "inright"
connect "STKPercFlut", "outleft", "Reverberation", "inleft"
connect "STKPercFlut", "outright", "Reverberation", "inright"
connect "STKPlucked", "outleft", "Reverberation", "inleft"
connect "STKPlucked", "outright", "Reverberation", "inright"
connect "STKResonate", "outleft", "Reverberation", "inleft"
connect "STKResonate", "outright", "Reverberation", "inright"
connect "STKRhodey", "outleft", "Reverberation", "inleft"
connect "STKRhodey", "outright", "Reverberation", "inright"
connect "STKSaxofony", "outleft", "Reverberation", "inleft"
connect "STKSaxofony", "outright", "Reverberation", "inright"
connect "STKShakers", "outleft", "Reverberation", "inleft"
connect "STKShakers", "outright", "Reverberation", "inright"
connect "STKSimple", "outleft", "Reverberation", "inleft"
connect "STKSimple", "outright", "Reverberation", "inright"
connect "STKSitar", "outleft", "Reverberation", "inleft"
connect "STKSitar", "outright", "Reverberation", "inright"
connect "STKTubeBell", "outleft", "Reverberation", "inleft"
connect "STKTubeBell", "outright", "Reverberation", "inright"
connect "STKVoicForm", "outleft", "Reverberation", "inleft"
connect "STKVoicForm", "outright", "Reverberation", "inright"
connect "STKWhistle", "outleft", "Reverberation", "inleft"
connect "STKWhistle", "outright", "Reverberation", "inright"
connect "STKWurley", "outleft", "Reverberation", "inleft"
connect "STKWurley", "outright", "Reverberation", "inright"
connect "StringPad", "outleft", "Reverberation", "inleft"
connect "StringPad", "outright", "Reverberation", "inright"
connect "ToneWheelOrgan", "outleft", "Reverberation", "inleft"
connect "ToneWheelOrgan", "outright", "Reverberation", "inright"
connect "TubularBellModel", "outleft", "Reverberation", "inleft"
connect "TubularBellModel", "outright", "Reverberation", "inright"
connect "WaveguideGuitar", "outleft", "Reverberation", "inleft"
connect "WaveguideGuitar", "outright", "Reverberation", "inright"
connect "Xing", "outleft", "Reverberation", "inleft"
connect "Xing", "outright", "Reverberation", "inright"
connect "ZakianFlute", "outleft", "Reverberation", "inleft"
connect "ZakianFlute", "outright", "Reverberation", "inright"
alwayson "Reverberation"
alwayson "Compressor"
alwayson "MasterOutput"
instr BanchoffKleinBottle
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; p1 p2 p3 p4 p5 p6 p7
; Start Dur Amp Frqc U V
; i 4 32 6 6000 6.00 3 2
i 4 36 4 . 5.11 5.6 0.4
i 4 + 4 . 6.05 2 8.5
i 4 . 2 . 6.02 4 5
i 4 . 2 . 6.02 5 0.5
iHz = ifrequency
ifqc init iHz
ip4 init iamplitude
iu init 5 ; p6
iv init 0.5 ; p7
irt2 init sqrt(2)
aampenv linseg 0, 0.02, ip4, p3 - 0.04, ip4, 0.02, 0
isine ftgenonce 0, 0, 65536, 10, 1
icosine ftgenonce 0, 0, 65536, 11, 1
Cosines
acosu oscili 1, iu * ifqc, icosine
acosu2 oscili 1, iu * ifqc / 2, icosine
acosv oscili 1, iv * ifqc, icosine
Sines
asinu oscili 1, iu * ifqc, isine
asinu2 oscili 1, iu * ifqc / 2, isine
asinv oscili 1, iv * ifqc, isine
; Compute X and Y
ax = acosu * (acosu2 * (irt2 + acosv) + asinu2 * asinv * acosv)
ay = asinu * (acosu2 * (irt2 + acosv) + asinu2 * asinv * acosv)
Low frequency rotation in spherical coordinates z , phi , theta .
klfsinth oscili 1, 4, isine
klfsinph oscili 1, 1, isine
klfcosth oscili 1, 4, icosine
klfcosph oscili 1, 1, icosine
aox = -ax * klfsinth + ay * klfcosth
aoy = -ax * klfsinth * klfcosph - ay * klfsinth * klfcosph + klfsinph
aoutleft = aampenv * aox
aoutright = aampenv * aoy
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "BanchoffKlein i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr BandedWG
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 512
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
asignal STKBandedWG ifrequency,1
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "BandedWG i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr BassModel
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 35
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; p1 p2 p3 p4 p5 p6
Start Dur Amp Pitch PluckDur
i2 128 4 1400 6.00 0.25
; i2 + 2 1200 6.01 0.25
i2 . 4 1000 6.05 0.5
i2 . 2 500 6.04 1
i2 . 4 1000 6.03 0.5
i2 . 16 1000 6.00 0.5
iHz = ifrequency
ifqc = iHz
ip4 = iamplitude
ip6 = 0.5
ipluck = 1 / ifqc * ip6
kcount init 0
adline init 0
ablock2 init 0
ablock3 init 0
afiltr init 0
afeedbk init 0
koutenv linseg 0, .01, 1, p3 - .11 , 1, .1 , 0 ; Output envelope
kfltenv linseg 0, 1.5, 1, 1.5, 0
; This envelope loads the string with a triangle wave.
kenvstr linseg 0, ipluck / 4, -ip4 / 2, ipluck / 2, ip4 / 2, ipluck / 4, 0, p3 - ipluck, 0
aenvstr = kenvstr
ainput tone aenvstr, 200
; DC Blocker
ablock2 = afeedbk - ablock3 + .99 * ablock2
ablock3 = afeedbk
ablock = ablock2
; Delay line with filtered feedback
adline delay ablock + ainput, 1 / ifqc - 15 / sr
afiltr tone adline, 400
; Resonance of the body
abody1 reson afiltr, 110, 40
abody1 = abody1 / 5000
abody2 reson afiltr, 70, 20
abody2 = abody2 / 50000
afeedbk = afiltr
aout = afeedbk
asignal = 50 * koutenv * (aout + kfltenv * (abody1 + abody2))
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "BassModel i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ChebyshevDrone
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
By .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ihertz = cpsmidinn(i_midikey)
iamp = ampdb(i_midivelocity) * 6
idampingattack = .01
idampingrelease = .02
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
iattack init p3 / 4.0
idecay init p3 / 4.0
isustain init p3 / 2.0
aenvelope transeg 0.0, iattack / 2.0, 2.5, iamp / 2.0, iattack / 2.0, -2.5, iamp, isustain, 0.0, iamp, idecay / 2.0, 2.5, iamp / 2.0, idecay / 2.0, -2.5, 0.
isinetable ftgenonce 0, 0, 65536, 10, 1, 0, .02
asignal poscil3 1, ihertz, isinetable
asignal chebyshevpoly asignal, 0, gkChebyshevDroneCoefficient1, gkChebyshevDroneCoefficient2, gkChebyshevDroneCoefficient3, gkChebyshevDroneCoefficient4, gkChebyshevDroneCoefficient5, gkChebyshevDroneCoefficient6, gkChebyshevDroneCoefficient7, gkChebyshevDroneCoefficient8, gkChebyshevDroneCoefficient9, gkChebyshevDroneCoefficient10
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
asignal = asignal * aenvelope
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ChebyshevDrone i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ChebyshevMelody
///////////////////////////////////////////////////////
// Original by Jon Nelson.
// Adapted by Michael Gogins.
///////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iHz = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 7.
iattack = .01
isustain = p3
irelease = .01
p3 = iattack + isustain + irelease
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
kHz = k(iHz)
idB = i_midivelocity
i1 = iHz
k100 randi 1,0.05
isine ftgenonce 0, 0, 65536, 10, 1
k101 poscil 1, 5 + k100, isine
k102 linseg 0, .5, 1, p3, 1
k100 = i1 + (k101 * k102)
; Envelope for driving oscillator.
ip3 init 3.0
k1 linenr 0.5 , ip3 * .3 , ip3 * 2 , 0.01
k1 linseg 0, ip3 * .3, .5, ip3 * 2, 0.01, isustain, 0.01, irelease, 0
k2 line 1 , p3 , .5
k2 linseg 1.0, ip3, .5, isustain, .5, irelease, 0
k1 = k2 * k1
; Amplitude envelope.
k10 expseg 0.0001, iattack, 1.0, isustain, 0.8, irelease, .0001
k10 = (k10 - .0001)
; Power to partials.
k20 linseg 1.485, iattack, 1.5, (isustain + irelease), 1.485
a1 - 3 are for cheby with p6=1 - 4
icook3 ftgenonce 0, 0, 65536, 10, 1, .4, 0.2, 0.1, 0.1, .05
a1 poscil k1, k100 - .25, icook3
Tables a1 to fn13 , others normalize ,
ip6 ftgenonce 0, 0, 65536, -7, -1, 150, 0.1, 110, 0, 252, 0
a2 tablei a1, ip6, 1, .5
a3 balance a2, a1
; Try other waveforms as well.
a4 foscili 1, k100 + .04, 1, 2.000, k20, isine
a5 poscil 1, k100, isine
a6 = ((a3 * .1) + (a4 * .1) + (a5 * .8)) * k10
a7 comb a6, .5, 1 / i1
a8 = (a6 * .9) + (a7 * .1)
asignal balance a8, a1
asignal = asignal * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ChebyshevMel i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr DelayedPluckedString
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.02
isustain = p3
irelease = 0.15
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ikeyin = i_midikey
ihertz = cpsmidinn(ikeyin)
Detuning of strings by 4 cents each way .
idetune = 4.0 / 1200.0
ihertzleft = cpsmidinn(ikeyin + idetune)
ihertzright = cpsmidinn(ikeyin - idetune)
iamplitude = ampdb(i_midivelocity)
isine ftgenonce 0, 0, 65536, 10, 1
icosine ftgenonce 0, 0, 65536, 11, 1
igenleft = isine
igenright = icosine
kvibrato oscili 1.0 / 120.0, 7.0, icosine
kexponential expseg 1.0, p3 + iattack, 0.0001, irelease, 0.0001
aenvelope = (kexponential - 0.0001) * adeclick
ag pluck iamplitude, cpsmidinn(ikeyin + kvibrato), 200, igenleft, 1
agleft pluck iamplitude, ihertzleft, 200, igenleft, 1
agright pluck iamplitude, ihertzright, 200, igenright, 1
imsleft = 0.2 * 1000
imsright = 0.21 * 1000
adelayleft vdelay ag * aenvelope, imsleft, imsleft + 100
adelayright vdelay ag * aenvelope, imsright, imsright + 100
asignal = adeclick * (agleft + adelayleft + agright + adelayright)
Highpass filter to exclude speaker cone excursions .
asignal1 butterhp asignal, 32.0
asignal2 balance asignal1, asignal
aoutleft, aoutright pan2 asignal2 * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "DelayedPlucked i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr EnhancedFMBell
//////////////////////////////////////////////////////
// Original by John ffitch.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.005
isustain = p3
irelease = 0.25
i_duraton = 15; isustain + iattack + irelease
p3 = i_duration
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequency = cpsmidinn(i_midikey)
Normalize so iamplitude for p5 of 80 = = ampdb(80 ) .
iamplitude = ampdb(i_midivelocity)
idur = 50
iamp = iamplitude
iffitch1 ftgenonce 0, 0, 65536, 10, 1
iffitch2 ftgenonce 0, 0, 8193, 5, 1, 1024, 0.01
iffitch3 ftgenonce 0, 0, 8193, 5, 1, 1024, 0.001
ifenv = iffitch2 ; BELL SETTINGS:
AMP AND INDEX ENV ARE EXPONENTIAL
* 5 ; DECREASING , N1 : N2 IS 5:7 , imax=10
DURATION = 15 sec
ifq2 = cpsmidinn(i_midikey) * 5/7
if2 = iffitch1
imax = 10
aenv oscili iamp, 1 / idur, ifenv ; ENVELOPE
adyn oscili ifq2 * imax, 1 / idur, ifdyn ; DYNAMIC
anoise rand 50
MODULATOR
acar oscili aenv, ifq1 + amod, if1 ; CARRIER
timout 0.5, idur, noisend
knenv linsegr iamp, 0.2, iamp, 0.3, 0
anoise3 rand knenv
anoise4 butterbp anoise3, iamp, 100
anoise5 balance anoise4, anoise3
noisend:
arvb nreverb acar, 2, 0.1
aenvelope transeg 1, idur, -3, 0
asignal = aenvelope * (acar + arvb) ;+ anoise5
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "EnhancedFMBell i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FenderRhodesModel
//////////////////////////////////////////////////////
// Original by Perry Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.01
isustain = p3
irelease = 0.125
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
iindex = 4
icrossfade = 3
ivibedepth = 0.2
iviberate = 6
isine ftgenonce 0, 0, 65536, 10, 1
icosine ftgenonce 0, 0, 65536, 11, 1
Blank wavetable for some FM opcodes .
ifn1 = isine
ifn2 = icosine
ifn3 = isine
ifn4 = icookblank
ivibefn = isine
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
asignal fmrhode iamplitude, ifrequency, iindex, icrossfade, ivibedepth, iviberate, ifn1, ifn2, ifn3, ifn4, ivibefn
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FenderRhodes i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FilteredSines
//////////////////////////////////////////////////////
// Original by Michael Bergeman.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
; Original pfields
p1 p2 p3 p4 p5 p6 p7 p8 p9
ins db func at dec freq1 freq2
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.03
isustain = p3
irelease = 0.52
p3 = p3 + iattack + irelease
i_duration = p3
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ip4 = i_midivelocity
idb = ampdb(i_midivelocity) * 4
ibergeman ftgenonce 0, 0, 65536, 10, 0.28, 1, 0.74, 0.66, 0.78, 0.48, 0.05, 0.33, 0.12, 0.08, 0.01, 0.54, 0.19, 0.08, 0.05, 0.16, 0.01, 0.11, 0.3, 0.02, 0.2 ; Bergeman f1
ip5 = ibergeman
ip3 = i_duration
ip6 = i_duration * 0.25
ip7 = i_duration * 0.75
ip8 = cpsmidinn(i_midikey - 0.01)
ip9 = cpsmidinn(i_midikey + 0.01)
isc = idb * 0.333
k1 line 40, p3, 800
k2 line 440, p3, 220
k3 linen isc, ip6, p3, ip7
k4 line 800, ip3, 40
k5 line 220, ip3, 440
k6 linen isc, ip6, ip3, ip7
k7 linen 1, ip6, ip3, ip7
a5 oscili k3, ip8, ip5
a6 oscili k3, ip8 * 0.999, ip5
a7 oscili k3, ip8 * 1.001, ip5
a1 = a5 + a6 + a7
a8 oscili k6, ip9, ip5
a9 oscili k6, ip9 * 0.999, ip5
a10 oscili k6, ip9 * 1.001, ip5
a11 = a8 + a9 + a10
a2 butterbp a1, k1, 40
a3 butterbp a2, k5, k2 * 0.8
a4 balance a3, a1
a12 butterbp a11, k4, 40
a13 butterbp a12, k2, k5 * 0.8
a14 balance a13, a11
a15 reverb2 a4, 5, 0.3
a16 reverb2 a4, 4, 0.2
; Constant-power pan.
ipi = 4.0 * taninv(1.0)
iradians = i_pan * ipi / 2.0
itheta = iradians / 2.0
Translate angle in [ -1 , 1 ] to left and right gain factors .
irightgain = sqrt(2.0) / 2.0 * (cos(itheta) + sin(itheta))
ileftgain = sqrt(2.0) / 2.0 * (cos(itheta) - sin(itheta))
a17 = (a15 + a4) * ileftgain * k7
a18 = (a16 + a4) * irightgain * k7
aoutleft = a17 * adeclick
aoutright = a18 * adeclick
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FilteredSines i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Flute
//////////////////////////////////////////////////////
// Original by James Kelley.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
flute .
; Do some phasing.
icpsp1 = cpsmidinn(i_midikey - 0.0002)
icpsp2 = cpsmidinn(i_midikey + 0.0002)
ip6 = ampdb(i_midivelocity)
iattack = 0.04
isustain = p3
irelease = 0.15
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ip4 = 0
if (ip4 == int(ip4 / 2) * 2) goto initslurs
ihold
initslurs:
iatttm = 0.09
idectm = 0.1
isustm = p3 - iatttm - idectm
idec = ip6
ireinit = -1
if (ip4 > 1) goto checkafterslur
ilast = 0
checkafterslur:
if (ip4 == 1 || ip4 == 3) goto doneslurs
idec = 0
ireinit = 0
KONTROL
doneslurs:
if (isustm <= 0) goto simpleenv
kamp linsegr ilast, iatttm, ip6, isustm, ip6, idectm, idec, 0, idec
goto doneenv
simpleenv:
kamp linsegr ilast, p3 / 2,ip6, p3 / 2, idec, 0, idec
doneenv:
ilast = ip6
; Some vibrato.
kvrandamp rand 0.1
kvamp = (8 + p4) *.06 + kvrandamp
kvrandfreq rand 1
kvfreq = 5.5 + kvrandfreq
isine ftgenonce 0, 0, 65536, 10, 1
kvbra oscili kvamp, kvfreq, isine, ireinit
kfreq1 = icpsp1 + kvbra
kfreq2 = icpsp2 + kvbra
; Noise for burst at beginning of note.
knseenv expon ip6 / 4, 0.2, 1
; AUDIO
anoise1 rand knseenv
anoise tone anoise1, 200
a1 oscili kamp, kfreq1, ikellyflute, ireinit
a2 oscili kamp, kfreq2, ikellyflute, ireinit
a3 = a1 + a2 + anoise
aoutleft, aoutright pan2 a3 * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Flute i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FMModerateIndex
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 3
icarrier = 1
iratio = 1.25
ifmamplitude = 8
index = 5.4
iattack = 0.01
isustain = p3
irelease = 0.05
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequencyb = ifrequency * 1.003
icarrierb = icarrier * 1.004
kindenv transeg 0, iattack, -4, 1, isustain, -2, 0.125, irelease, -4, 0
kindex = kindenv * index * ifmamplitude
isine ftgenonce 0, 0, 65536, 10, 1
aouta foscili 1, ifrequency, icarrier, iratio, index, isine
aoutb foscili 1, ifrequencyb, icarrierb, iratio, index, isine
asignal = (aouta + aoutb) * kindenv
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FMModerateInd i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FMModerateIndex2
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 3
icarrier = 1
iratio = 1
ifmamplitude = 6
index = 2.5
iattack = 0.02
isustain = p3
irelease = 0.05
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequencyb = ifrequency * 1.003
icarrierb = icarrier * 1.004
kindenv expseg 0.000001, iattack, 1.0, isustain, 0.0125, irelease, 0.000001
kindex = kindenv * index * ifmamplitude - 0.000001
isine ftgenonce 0, 0, 65536, 10, 1
aouta foscili 1, ifrequency, icarrier, iratio, index, isine
aoutb foscili 1, ifrequencyb, icarrierb, iratio, index, isine
asignal = (aouta + aoutb) * kindenv
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FMModerateInd2 i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FMModulatedChorusing
//////////////////////////////////////////////
// Original by Thomas Kung.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.333333
irelease = 0.1
isustain = p3
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
iamplitude = ampdb(i_midikey) / 1200
ip6 = 0.3
ip7 = 2.2
; shift it.
ishift = 4.0 / 12000
convert parameter 5 to cps .
ipch = cpsmidinn(i_midikey)
convert parameter 5 to oct .
ioct = i_midikey
kadsr linen 1.0, iattack, irelease, 0.01
kmodi linseg 0, iattack, 5, isustain, 2, irelease, 0
r moves from ip6 to ip7 in p3 secs .
kmodr linseg ip6, p3, ip7
a1 = kmodi * (kmodr - 1 / kmodr) / 2
a1 * 2 is argument normalized from 0 - 1 .
a1ndx = abs(a1 * 2 / 20)
a2 = kmodi * (kmodr + 1 / kmodr) / 2
; Look up table is in f43, normalized index.
Unscaled ln(I(x ) ) from 0 to 20.0 .
a3 tablei a1ndx, iln, 1
Cosine wave . Get that noise down on the most widely used table !
ao1 oscili a1, ipch, icosine
a4 = exp(-0.5 * a3 + ao1)
Cosine
ao2 oscili a2 * ipch, ipch, icosine
isine ftgenonce 2, 0, 65536, 10, 1
; Final output left
aoutl oscili 1 * kadsr * a4, ao2 + cpsmidinn(ioct + ishift), isine
; Final output right
aoutr oscili 1 * kadsr * a4, ao2 + cpsmidinn(ioct - ishift), isine
asignal = aoutl + aoutr
asignal = asignal * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FMModulatedCho i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FMWaterBell
//////////////////////////////////////////////
// Original by Steven Yi.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ipch = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 2.0
ipch2 = ipch
kpchline line ipch, i_duration, ipch2
iamp = 2
ienvType = 2
kenv init 0
if ienvType == 0 kgoto env0 ; adsr
if ienvType == 1 kgoto env1 ; pyramid
if ienvType == 2 kgoto env2 ; ramp
env0:
kenv adsr .3, .2, .9, .5
kgoto endEnvelope
env1:
kenv linseg 0, i_duration * .5, 1, i_duration * .5, 0
kgoto endEnvelope
env2:
kenv linseg 0, i_duration - .1, 1, .1, 0
kgoto endEnvelope
endEnvelope:
kc1 = 5
kc2 = 5
kvdepth = 0.005
kvrate = 6
icosine ftgenonce 0, 0, 65536, 11, 1
ifn1 = icosine
ifn2 = icosine
ifn3 = icosine
ifn4 = icosine
ivfn = icosine
asignal fmbell iamp, kpchline, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn
iattack = 0.003
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 iamplitude * asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FMWaterBell i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Granular
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 175
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; f1 0 65536 1 "hahaha.aif" 0 4 0
f2 0 1024 7 0 224 1 800 0
f3 0 8192 7 1 8192 -1
f4 0 1024 7 0 512 1 512 0
f5 0 1024 10 1 .3 .1 0 .2 .02 0 .1 .04
; f6 0 1024 10 1 0 .5 0 .33 0 .25 0 .2 0 .167
; a0 14 50
p1 p2 p3 p4 p5 p6 p7 p8 p9 p10
; Start Dur Amp Freq GrTab WinTab FqcRng Dens Fade
i1 0.0 6.5 700 9.00 5 4 .210 200 1.8
i1 3.2 3.5 800 7.08 . 4 .042 100 0.8
i1 5.1 5.2 600 7.10 . 4 .032 100 0.9
i1 7.2 6.6 900 8.03 . 4 .021 150 1.6
i1 21.3 4.5 1000 9.00 . 4 .031 150 1.2
i1 26.5 13.5 1100 6.09 . 4 .121 150 1.5
i1 30.7 9.3 900 8.05 . 4 .014 150 2.5
i1 34.2 8.8 700 10.02 . 4 .14 150 1.6
igrtab ftgenonce 0, 0, 65536, 10, 1, .3, .1, 0, .2, .02, 0, .1, .04
iwintab ftgenonce 0, 0, 65536, 10, 1, 0, .5, 0, .33, 0, .25, 0, .2, 0, .167
iHz = ifrequency
ip4 = iamplitude
ip5 = iHz
ip6 = igrtab
ip7 = iwintab
ip8 = 0.033
ip9 = 150
ip10 = 1.6
idur = p3
iamp = iamplitude ; p4
ifqc = iHz ; cpspch(p5)
igrtab = ip6
iwintab = ip7
ifrng = ip8
idens = ip9
ifade = ip10
igdur = 0.2
kamp linseg 0, ifade, 1, idur - 2 * ifade, 1, ifade, 0
Amp Fqc Dense AmpOff PitchOff WinTable MaxGrDur
aoutl grain ip4, ifqc, idens, 100, ifqc * ifrng, igdur, igrtab, iwintab, 5
aoutr grain ip4, ifqc, idens, 100, ifqc * ifrng, igdur, igrtab, iwintab, 5
aoutleft = aoutl * kamp * iamplitude
aoutright = aoutr * kamp * iamplitude
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Granular i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Guitar
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 8.0
iattack = 0.01
isustain = p3
irelease = 0.05
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequency = cpsmidinn(p4)
iamplitude = ampdb(p5) * 20
kamp linsegr 0.0, iattack, iamplitude, isustain, iamplitude, irelease, 0.0
asigcomp pluck 1, 440, 440, 0, 1
asig pluck 1, ifrequency, ifrequency, 0, 1
af1 reson asig, 110, 80
af2 reson asig, 220, 100
af3 reson asig, 440, 80
aout balance 0.6 * af1+ af2 + 0.6 * af3 + 0.4 * asig, asigcomp
kexp expseg 1.0, iattack, 2.0, isustain, 1.0, irelease, 1.0
kenv = kexp - 1.0
asignal = aout * kenv * kamp
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Guitar i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Guitar2
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 12
iattack = 0.01
isustain = p3
irelease = 0.05
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
kamp linsegr 0.0, iattack, 1, isustain, 1, irelease, 0.0
asigcomp pluck kamp, 440, 440, 0, 1
asig pluck kamp, ifrequency, ifrequency, 0, 1
af1 reson asig, 110, 80
af2 reson asig, 220, 100
af3 reson asig, 440, 80
aout balance 0.6 * af1+ af2 + 0.6 * af3 + 0.4 * asig, asigcomp
kexp expseg 1.0, iattack, 2.0, isustain, 1.0, irelease, 1.0
kenv = kexp - 1.0
asignal = aout * kenv
asignal dcblock asignal
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Guitar2 i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Harpsichord
//////////////////////////////////////////////
// Original by James Kelley.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
insno = p1
itime = p2
iduration = p3
ikey = p4
ivelocity = p5
iphase = p6
ipan = p7
idepth = p8
iheight = p9
ipcs = p10
ihomogeneity = p11
gkHarpsichordGain = .25
gkHarpsichordPan = .5
iattack = .005
isustain = p3
irelease = .3
p3 = iattack + isustain + irelease
iHz = cpsmidinn(ikey)
kHz = k(iHz)
iamplitude = ampdb(ivelocity) * 36
aenvelope transeg 1.0, 20.0, -10.0, 0.05
apluck pluck 1, kHz, iHz, 0, 1
iharptable ftgenonce 0, 0, 65536, 7, -1, 1024, 1, 1024, -1
aharp poscil 1, kHz, iharptable
aharp2 balance apluck, aharp
asignal = (apluck + aharp2) * iamplitude * aenvelope * gkHarpsichordGain
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
aoutleft, aoutright pan2 asignal * adeclick, ipan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Harpsichord i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr HeavyMetalModel
//////////////////////////////////////////////
// Original by Perry Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.01
idecay = 2.0
isustain = i_duration
irelease = 0.125
p3 = iattack + iattack + idecay + irelease
adeclick linsegr 0.0, iattack, 1.0, idecay + isustain, 1.0, irelease, 0.0
iindex = 1
icrossfade = 3
ivibedepth = 0.02
iviberate = 4.8
isine ftgenonce 0, 0, 65536, 10, 1
Cosine wave . Get that noise down on the most widely used table !
iexponentialrise ftgenonce 0, 0, 65536, 5, 0.001, 513, 1 ; Exponential rise.
ithirteen ftgenonce 0, 0, 65536, 9, 1, 0.3, 0
ifn1 = isine
ifn2 = iexponentialrise
ifn3 = ithirteen
ifn4 = isine
ivibefn = icosine
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 48.0
adecay transeg 0.0, iattack, 4, 1.0, idecay + isustain, -4, 0.1, irelease, -4, 0.0
asignal fmmetal 0.1, ifrequency, iindex, icrossfade, ivibedepth, iviberate, ifn1, ifn2, ifn3, ifn4, ivibefn
asignal = asignal * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "HeavyMetalMod i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Hypocycloid
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
; This set of parametric equations defines the path traced by
; a point on a circle of radius B rotating inside a circle of
; radius A.
; p1 p2 p3 p4 p5 p6 p7 p8
; Start Dur Amp Frqc A B Hole
; i 3 16 6 8000 8.00 10 2 1
i 3 20 4 . 7.11 5.6 0.4 0.8
i 3 + 4 . 8.05 2 8.5 0.7
i 3 . 2 . 8.02 4 5 0.6
i 3 . 2 . 8.02 5 0.5 1.2
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
iHz = ifrequency
ifqc init iHz
ip4 init iamplitude
ifqci init iHz
ia = 0.6 ; p6
ib = 0.4 ; p7
ihole = 0.8 ; p8
iscale = (ia < ib ? 1 / ib : 1 / ia)
kampenv linseg 0, .1, ip4 * iscale, p3 - .2, ip4 * iscale, .1, 0
kptchenv linseg ifqci, .2 * p3, ifqc, .8 * p3, ifqc
kvibenv linseg 0, .5, 0, .2, 1, .2, 1
isine ftgenonce 0, 0, 65536, 10, 1
icosine ftgenonce 0, 0, 65536, 11, 1
kvibr oscili 20, 8, icosine
kfqc = kptchenv+kvibr*kvibenv
Sine and Cosine
acos1 oscili ia - ib, kfqc, icosine
acos2 oscili ib * ihole, (ia - ib) / ib * kfqc, icosine
ax = acos1 + acos2
asin1 oscili ia-ib, kfqc, isine
asin2 oscili ib, (ia - ib) / ib * kfqc, isine
ay = asin1 - asin2
aoutleft = kampenv * ax
aoutright = kampenv * ay
; Constant-power pan.
ipi = 4.0 * taninv(1.0)
iradians = i_pan * ipi / 2.0
itheta = iradians / 2.0
Translate angle in [ -1 , 1 ] to left and right gain factors .
irightgain = sqrt(2.0) / 2.0 * (cos(itheta) + sin(itheta))
ileftgain = sqrt(2.0) / 2.0 * (cos(itheta) - sin(itheta))
outleta "outleft", aoutleft * ileftgain
outleta "outright", aoutright * irightgain
prints "Hypocycloid i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ModerateFM
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.002
isustain = p3
idecay = 8
irelease = 0.05
iHz = cpsmidinn(i_midikey)
idB = i_midivelocity
iamplitude = ampdb(idB) * 4.0
icarrier = 1
imodulator = 0.5
ifmamplitude = 0.25
index = .5
ifrequencyb = iHz * 1.003
icarrierb = icarrier * 1.004
aindenv transeg 0.0, iattack, -11.0, 1.0, idecay, -7.0, 0.025, isustain, 0.0, 0.025, irelease, -7.0, 0.0
aindex = aindenv * index * ifmamplitude
isinetable ftgenonce 0, 0, 65536, 10, 1, 0, .02
ares foscili xamp , , xcar , xmod , kndx , ifn [ , iphs ]
aouta foscili 1.0, iHz, icarrier, imodulator, index / 4., isinetable
aoutb foscili 1.0, ifrequencyb, icarrierb, imodulator, index, isinetable
; Plus amplitude correction.
asignal = (aouta + aoutb) * aindenv
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
asignal = asignal * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ModerateFM i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ModulatedFM
//////////////////////////////////////////////
// Original by Thomas Kung.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = .25
isustain = p3
irelease = .33333333
p3 = iattack + isustain + irelease
iHz = cpsmidinn(i_midikey)
kHz = k(iHz)
idB = i_midivelocity
iamplitude = ampdb(i_midivelocity)
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
ip6 = 0.3
ip7 = 2.2
ishift = 4.0 / 12000.0
kpch = kHz
koct = octcps(kHz)
aadsr linen 1.0, iattack, irelease, 0.01
amodi linseg 0, iattack, 5, p3, 2, irelease, 0
r moves from ip6 to ip7 in p3 secs .
amodr linseg ip6, p3, ip7
a1 = amodi * (amodr - 1 / amodr) / 2
a1 * 2 is argument normalized from 0 - 1 .
a1ndx = abs(a1 * 2 / 20)
a2 = amodi * (amodr + 1 / amodr) / 2
Unscaled ln(I(x ) ) from 0 to 20.0 .
iln ftgenonce 0, 0, 65536, -12, 20.0
a3 tablei a1ndx, iln, 1
icosine ftgenonce 0, 0, 65536, 11, 1
ao1 poscil a1, kpch, icosine
a4 = exp(-0.5 * a3 + ao1)
Cosine
ao2 poscil a2 * kpch, kpch, icosine
isine ftgenonce 0, 0, 65536, 10, 1
; Final output left
aleft poscil a4, ao2 + cpsoct(koct + ishift), isine
; Final output right
aright poscil a4, ao2 + cpsoct(koct - ishift), isine
asignal = (aleft + aright) * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ModulatedFM i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
gk_PianoNote_midi_dynamic_range init 127
giPianoteq init 0
instr PianoNote
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
if p3 == -1 goto indefinite
goto non_indefinite
indefinite:
p3 = 1000000
non_indefinite:
i_instrument = p1
i_time = p2
i_duration = p3
i_midi_key = p4
i_midi_dynamic_range = i(gk_PianoNote_midi_dynamic_range)
i_midi_velocity = p5 * i_midi_dynamic_range / 127 + (63.6 - i_midi_dynamic_range / 2)
k_space_front_to_back = p6
k_space_left_to_right = p7
k_space_bottom_to_top = p8
i_phase = p9
i_homogeneity = p11
instances active p1
prints "PianoNotePt i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\\n", p1, p2, p3, p4, p5, p7, instances
i_pitch_correction = 44100 / sr
; prints "Pitch factor: %9.4f\n", i_pitch_correction
vstnote giPianoteq, i_instrument, i_midi_key, i_midi_velocity, i_duration
endin
instr PlainPluckedString
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.002
isustain = p3
irelease = 0.075
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
aenvelope transeg 0, iattack, -4, iamplitude, isustain, -4, iamplitude / 10.0, irelease, -4, 0
asignal1 pluck 1, ifrequency, ifrequency * 1.002, 0, 1
asignal2 pluck 1, ifrequency * 1.003, ifrequency, 0, 1
asignal = (asignal1 + asignal2) * aenvelope
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "PlainPluckedSt i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr PRCBeeThree
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
asignal STKBeeThree ifrequency, 1
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "PRCBeeThree i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr PRCBeeThreeDelayed
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
iattack = 0.2
isustain = p3
irelease = 0.3
p3 = isustain + iattack + irelease
asignal STKBeeThree ifrequency, 1, 2, 3, 1, 0, 11, 0
amodulator oscils 0.00015, 0.2, 0.0
Read delayed signal , first delayr instance :
adump delayr 4.0
associated with first delayr instance
Read delayed signal , second delayr instance :
adump delayr 4.0
associated with second delayr instance
; Do some cross-coupled manipulation:
afdbk1 = 0.7 * adly1 + 0.7 * adly2 + asignal
afdbk2 = -0.7 * adly1 + 0.7 * adly2 + asignal
Feed back signal , associated with first delayr instance :
delayw afdbk1
Feed back signal , associated with second delayr instance :
delayw afdbk2
asignal2 = adly1 + adly2
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal2 * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "PRCBeeThreeDel i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr PRCBowed
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
; Controllers:
; 1 Vibrato Gain
2 Bow Pressure
4 Bow Position
11 Vibrato Frequency
128 Volume
asignal STKBowed ifrequency, 1.0, 1, 1.8, 2, 120.0, 4, 50.0, 11, 20.0
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "PRCBowed i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBandedWG
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 256
asignal STKBandedWG ifrequency, 1.0
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBandedWG i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBeeThree
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 16
asignal STKBeeThree ifrequency, 1.0, 1, 1.5, 2, 4.8, 4, 2.1
aphased phaser1 asignal, 4000, 16, .2, .9
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 aphased * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBeeThree i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBlowBotl
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
asignal STKBlowBotl ifrequency, 1.0
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBlowBotl i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBlowHole
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
asignal STKBlowHole ifrequency, 1.0
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBlowHole i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBowed
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
; Controllers:
; 1 Vibrato Gain
2 Bow Pressure
4 Bow Position
11 Vibrato Frequency
128 Volume
asignal STKBowed ifrequency, 1.0, 1, 0.8, 2, 120.0, 4, 20.0, 11, 20.0
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBowed i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKClarinet
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
asignal STKClarinet ifrequency, 1.0, 1, 1.5
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKClarinet i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKDrummer
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKDrummer ifrequency, 1.0
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKDrummer i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKFlute
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
; Control Change Numbers:
* Jet Delay = 2
* Noise Gain = 4
* Vibrato Frequency = 11
* Vibrato Gain = 1
* Breath Pressure = 128
asignal STKFlute ifrequency, 1.0, 128, 100, 2, 70, 4, 10
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKFlute i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKFMVoices
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
; Control Change Numbers:
* Vowel = 2
* Spectral Tilt = 4
* LFO Speed = 11
* LFO Depth = 1
* ADSR 2 & 4 Target = 128
asignal STKFMVoices ifrequency, 1.0, 2, 1, 4, 3.0, 11, 5, 1, .8
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKFMVoices i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKHvyMetl
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
; Control Change Numbers:
* Total Modulator Index = 2
* Modulator Crossfade = 4
* LFO Speed = 11
* LFO Depth = 1
* ADSR 2 & 4 Target = 128
asignal STKHevyMetl ifrequency, 1.0, 2, 17.0, 4, 70, 128, 80
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKHvyMetl i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKMandolin
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 24
asignal STKMandolin ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKMandolin i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKModalBar
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 24
; Control Change Numbers:
* Stick Hardness = 2
* Stick Position = 4
* Vibrato Gain = 1
* Vibrato Frequency = 11
* Direct Stick Mix = 8
* Volume = 128
* Modal Presets = 16
o = 0
o Vibraphone = 1
o Agogo = 2
o Wood1 = 3
o Reso = 4
o Wood2 = 5
o Beats = 6
o Two Fixed = 7
o Clump = 8
asignal STKModalBar ifrequency, 1.0, 16, 1
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKModalBar i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKMoog
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKMoog ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKMoog i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKPercFlut
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKPercFlut ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKPercFlut i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKPlucked
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 16
asignal STKPlucked ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKPlucked i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKResonate
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity)
;Control Change Numbers:
* Resonance Frequency ( 0 - Nyquist ) = 2
* 4
* Notch Frequency ( 0 - Nyquist ) = 11
* Zero Radii = 1
* Envelope Gain = 128
, 2 , 40 , 4 , .7 , 11 , 120 , 1 , .5
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKResonate i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKRhodey
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKRhodey ifrequency, 1
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKRhodey i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKSaxofony
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
; Control Change Numbers:
* Reed Stiffness = 2
* Reed Aperture = 26
* Noise Gain = 4
* Blow Position = 11
* Vibrato Frequency = 29
* Vibrato Gain = 1
* Breath Pressure = 128
, 29 , 5 , 1 , 12
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKSaxofony i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKShakers
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 256
;Control Change Numbers:
* Shake Energy = 2
* System Decay = 4
* Number Of Objects = 11
* Resonance Frequency = 1
* Shake Energy = 128
* Instrument Selection = 1071
o Maraca = 0
o Cabasa = 1
o = 2
o = 3
o Water Drops = 4
o Bamboo Chimes = 5
o = 6
o Sleigh Bells = 7
o Sticks = 8
o Crunch = 9
o Wrench = 10
o Sand Paper = 11
o Coke Can = 12
o Next Mug = 13
o Penny + Mug = 14
o Nickle + Mug = 15
o Dime + Mug = 16
o Quarter + Mug = 17
o = 18
o Peso + Mug = 19
o Big Rocks = 20
o Little Rocks = 21
o Tuned Bamboo Chimes = 22
, 128 , 100 , 1 , 30
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKShakers i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKSimple
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 64
; Control Change Numbers:
* Filter Pole Position = 2
* Noise / Pitched Cross - Fade = 4
* Envelope Rate = 11
* Gain = 128
asignal STKSimple ifrequency, 1.0, 2, 98, 4, 50, 11, 3
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKSimple i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKSitar
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKSitar ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKSitar i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKTubeBell
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKTubeBell ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKTubeBell i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKVoicForm
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 16
asignal STKVoicForm ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKVoicForm i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKWhistle
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
asignal STKWhistle ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKWhistle i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKWurley
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 16
asignal STKWurley ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKWurley i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr StringPad
//////////////////////////////////////////////
// Original by Anthony Kozar.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
String - pad borrowed from the piece " " ,
; / Modified to fit my needs
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ihz = cpsmidinn(i_midikey)
iamp = ampdb(i_midivelocity) * 3
idb = i_midivelocity
ipos = i_pan
; Slow attack and release
akctrl linsegr 0, i_duration * 0.5, iamp, i_duration *.5, 0
; Slight chorus effect
iwave ftgenonce 0, 0, 65536, 10, 1, 0.5, 0.33, 0.25, 0.0, 0.1, 0.1, 0.1
afund oscili akctrl, ihz, iwave ; audio oscillator
acel1 oscili akctrl, ihz - 0.1, iwave ; audio oscillator - flat
acel2 oscili akctrl, ihz + 0.1, iwave ; audio oscillator - sharp
asig = afund + acel1 + acel2
; Cut-off high frequencies depending on midi-velocity
; (larger velocity implies more brighter sound)
asignal butterlp asig, (i_midivelocity - 60) * 40 + 900
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "StringPad i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ToneWheelOrgan
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 8.0
iattack = 0.02
isustain = i_duration
irelease = 0.1
i_duration = iattack + isustain + irelease
p3 = i_duration
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
; Rotor Tables
itonewheel1 ftgenonce 0, 0, 65536, 10, 1, 0.02, 0.01
itonewheel2 ftgenonce 0, 0, 65536, 10, 1, 0, 0.2, 0, 0.1, 0, 0.05, 0, 0.02
; Rotating Speaker Filter Envelopes
itonewheel3 ftgenonce 0, 0, 65536, 7, 0, 110, 0, 18, 1, 18, 0, 110, 0
itonewheel4 ftgenonce 0, 0, 65536, 7, 0, 80, 0.2, 16, 1, 64, 1, 16, 0.2, 80, 0
; Distortion Tables
itonewheel5 ftgenonce 0, 0, 65536, 8, -.8, 336, -.78, 800, -.7, 5920, 0.7, 800, 0.78, 336, 0.8
itonewheel6 ftgenonce 0, 0, 65536, 8, -.8, 336, -.76, 3000, -.7, 1520, 0.7, 3000, 0.76, 336, 0.8
icosine ftgenonce 0, 0, 65536, 11, 1
iphase = p2
ikey = 12 * int(i_midikey - 6) + 100 * (i_midikey - 6)
ifqc = ifrequency
; The lower tone wheels have increased odd harmonic content.
iwheel1 = ((ikey - 12) > 12 ? itonewheel1 : itonewheel2)
iwheel2 = ((ikey + 7) > 12 ? itonewheel1 : itonewheel2)
iwheel3 = (ikey > 12 ? itonewheel1 : itonewheel2)
iwheel4 = icosine
insno Start Dur Amp Pitch SubFund Sub3rd Fund 2nd 3rd 4th 5th 6th 8th
i 1 0 6 200 8.04 8 8 8 8 3 2 1 0 4
asubfund oscili 8, 0.5 * ifqc, iwheel1, iphase / (ikey - 12)
asub3rd oscili 8, 1.4983 * ifqc, iwheel2, iphase / (ikey + 7)
afund oscili 8, ifqc, iwheel3, iphase / ikey
a2nd oscili 8, 2 * ifqc, iwheel4, iphase / (ikey + 12)
a3rd oscili 3, 2.9966 * ifqc, iwheel4, iphase / (ikey + 19)
a4th oscili 2, 4 * ifqc, iwheel4, iphase / (ikey + 24)
a5th oscili 1, 5.0397 * ifqc, iwheel4, iphase / (ikey + 28)
a6th oscili 0, 5.9932 * ifqc, iwheel4, iphase / (ikey + 31)
a8th oscili 4, 8 * ifqc, iwheel4, iphase / (ikey + 36)
asignal = iamplitude * (asubfund + asub3rd + afund + a2nd + a3rd + a4th + a5th + a6th + a8th)
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ToneWheelOrgan i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr TubularBellModel
//////////////////////////////////////////////////////
// Original by Perry Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
iattack = 0.003
isustain = p3
irelease = 0.125
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
iindex = 1
icrossfade = 2
ivibedepth = 0.2
iviberate = 6
isine ftgenonce 0, 0, 65536, 10, 1
Cosine wave . Get that noise down on the most widely used table !
icook3 ftgenonce 0, 0, 65536, 10, 1, 0.4, 0.2, 0.1, 0.1, 0.05
ifn1 = isine
ifn2 = icook3
ifn3 = isine
ifn4 = isine
ivibefn = icosine
asignal fmbell 1.0, ifrequency, iindex, icrossfade, ivibedepth, iviberate, ifn1, ifn2, ifn3, ifn4, ivibefn
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "TubularBellMod i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr WaveguideGuitar
//////////////////////////////////////////////////////
// Original by Jeff Livingston.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 16
iHz = ifrequency
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The model takes pluck position, and pickup position (in % of string length), and generates
; a pluck excitation signal, representing the string displacement. The pluck consists
of a forward and backward traveling displacement wave , which are recirculated thru two
separate delay lines , to simulate the one dimensional string waveguide , with
; fixed ends.
;
; Losses due to internal friction of the string, and with air, as well as
; losses due to the mechanical impedance of the string terminations are simulated by
; low pass filtering the signal inside the feedback loops.
Delay line outputs at the bridge termination are summed and fed into an IIR filter
modeled to simulate the lowest two vibrational modes ( resonances ) of the guitar body .
; The theory implies that force due to string displacement, which is equivalent to
; displacement velocity times bridge mechanical impedance, is the input to the guitar
; body resonator model. Here we have modified the transfer fuction representing the bridge
; mech impedance, to become the string displacement to bridge input force transfer function.
; The output of the resulting filter represents the displacement of the guitar's top plate,
; and sound hole, since thier respective displacement with be propotional to input force.
; (based on a simplified model, viewing the top plate as a force driven spring).
;
; The effects of pluck hardness, and contact with frets during pluck release,
; have been modeled by injecting noise into the initial pluck, proportional to initial
; string displacement.
;
; Note on pluck shape: Starting with a triangular displacment, I found a decent sounding
; initial pluck shape after some trial and error. This pluck shape, which is a linear
; ramp, with steep fall off, doesn't necessarily agree with the pluck string models I've
; studied. I found that initial pluck shape significantly affects the realism of the
; sound output, but I the treatment of this topic in musical acoustics literature seems
; rather limited as far as I've encountered.
;
; Original pfields
p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13
in st dur amp pkupPos pluckPos brightness vibf vibd vibdel
i01.2 0.5 0.75 5000 7.11 .85 0.9975 .0 .25 1 0 0 0
ip4 init iamplitude
ip6 init 0.85
ip7 init 0.9975
ip8 init 0
ip9 init 0.25
ip10 init 1.0
ip11 init 0.001
ip12 init 0.0
ip13 init 0.0
afwav init 0
abkwav init 0
abkdout init 0
afwdout init 0
iEstr init 1.0 / cpspch(6.04)
ifqc init iHz ; cpspch(p5)
; note:delay time=2x length of string (time to traverse it)
idlt init 1.0 / ifqc
ipluck = 0.5 * idlt * ip6 * ifqc / cpspch(8.02)
ifbfac = ip7 ; feedback factor
; (exponentialy scaled) additive noise to add hi freq content
ibrightness = ip10 * exp(ip6 * log(2)) / 2
ivibRate = ip11
ivibDepth pow 2, ip12 / 12
; vibrato depth, +,- ivibDepth semitones
ivibDepth = idlt - 1.0 / (ivibDepth * ifqc)
; vibrato start delay (secs)
ivibStDly = ip13
; termination impedance model
cutoff freq of LPF due to mech . impedance at the nut ( 2kHz-10kHz )
if0 = 10000
; damping parameter of nut impedance
iA0 = ip7
ialpha = cos(2 * 3.14159265 * if0 * 1 / sr)
FIR LPF model of nut impedance , H(z)=a0+a1z^-1+a0z^-2
ia0 = 0.3 * iA0 / (2 * (1 - ialpha))
ia1 = iA0 - 2 * ia0
NOTE each filter pass adds a sampling period delay , so subtract 1 / sr from tap time to compensate
; determine (in crude fashion) which string is being played
icurStr = ( ifqc > cpspch(6.04 ) ? 2 : 1 )
icurStr = ( ifqc > cpspch(6.09 ) ? 3 : icurStr )
icurStr = ( ifqc > cpspch(7.02 ) ? 4 : icurStr )
icurStr = ( ifqc > cpspch(7.07 ) ? 5 : icurStr )
icurStr = ( ifqc > cpspch(7.11 ) ? 6 : icurStr )
ipupos = ip8 * idlt / 2 ; pick up position (in % of low E string length)
ippos = ip9 * idlt / 2 ; pluck position (in % of low E string length)
isegF = 1 / sr
isegF2 = ipluck
iplkdelF = (ipluck / 2 > ippos ? 0 : ippos - ipluck / 2)
isegB = 1 / sr
isegB2 = ipluck
iplkdelB = (ipluck / 2 > idlt / 2 - ippos ? 0 : idlt / 2 - ippos - ipluck / 2)
EXCITATION SIGNAL GENERATION
the two excitation signals are fed into the fwd delay represent the 1st and 2nd
reflections off of the left boundary , and two accelerations fed into the delay
represent the the 1st and 2nd reflections off of the right boundary .
; Likewise for the backward traveling acceleration waves, only they encouter the
; terminations in the opposite order.
ipw = 1
ipamp = ip4 * ipluck ; 4 / ipluck
aenvstrf linseg 0, isegF, -ipamp / 2, isegF2, 0
adel1 delayr (idlt > 0) ? idlt : 0.01
; initial forward traveling wave (pluck to bridge)
aenvstrf1 deltapi iplkdelF
; first forward traveling reflection (nut to bridge)
aenvstrf2 deltapi iplkdelB + idlt / 2
delayw aenvstrf
; inject noise for attack time string fret contact, and pre pluck vibrations against pick
anoiz rand ibrightness
aenvstrf1 = aenvstrf1 + anoiz*aenvstrf1
aenvstrf2 = aenvstrf2 + anoiz*aenvstrf2
; filter to account for losses along loop path
aenvstrf2 filter2 aenvstrf2, 3, 0, ia0, ia1, ia0
combine into one signal ( flip refl wave 's phase )
aenvstrf = aenvstrf1 - aenvstrf2
; initial backward excitation wave
aenvstrb linseg 0, isegB, - ipamp / 2, isegB2, 0
adel2 delayr (idlt > 0) ? idlt : 0.01
; initial bdwd traveling wave (pluck to nut)
aenvstrb1 deltapi iplkdelB
; first forward traveling reflection (nut to bridge)
aenvstrb2 deltapi idlt / 2 + iplkdelF
delayw aenvstrb
; initial bdwd traveling wave (pluck to nut)
; aenvstrb1 delay aenvstrb, iplkdelB
first bkwd traveling reflection ( bridge to nut )
aenvstrb2 delay aenvstrb , idlt/2+iplkdelF
; inject noise
aenvstrb1 = aenvstrb1 + anoiz*aenvstrb1
aenvstrb2 = aenvstrb2 + anoiz*aenvstrb2
; filter to account for losses along loop path
aenvstrb2 filter2 aenvstrb2, 3, 0, ia0, ia1, ia0
combine into one signal ( flip refl wave 's phase )
aenvstrb = aenvstrb1 - aenvstrb2
low pass to band limit initial accel signals to be < 1/2 the sampling freq
ainputf tone aenvstrf, sr * 0.9 / 2
ainputb tone aenvstrb, sr * 0.9 / 2
additional lowpass filtering for pluck shaping\
; Note, it would be more efficient to combine stages into a single filter
ainputf tone ainputf, sr * 0.9 / 2
ainputb tone ainputb, sr * 0.9 / 2
; Vibrato generator
icosine ftgenonce 0, 0, 65536, 11, 1.0
avib poscil ivibDepth, ivibRate, icosine
avibdl delayr (((ivibStDly * 1.1)) > 0.0) ? (ivibStDly * 1.1) : 0.01
avibrato deltapi ivibStDly
delayw avib
; Dual Delay line,
NOTE : delay length longer than needed by a bit so that the output at t = idlt will be interpolated properly
;forward traveling wave delay line
afd delayr (((idlt + ivibDepth) * 1.1) > 0.0) ? ((idlt + ivibDepth) * 1.1) : 0.01
; output tap point for fwd traveling wave
afwav deltapi ipupos
; output at end of fwd delay (left string boundary)
afwdout deltapi idlt - 1 / sr + avibrato
lpf / attn due to reflection impedance
afwdout filter2 afwdout, 3, 0, ia0, ia1, ia0
delayw ainputf + afwdout * ifbfac * ifbfac
; backward trav wave delay line
abkwd delayr (((idlt + ivibDepth) * 1.1) > 0) ? ((idlt + ivibDepth) * 1.1) : 0.01
; output tap point for bkwd traveling wave
abkwav deltapi idlt / 2 - ipupos
; output at the left boundary
; abkterm deltapi idlt/2
output at end of delay ( right string boundary )
abkdout deltapi idlt - 1 / sr + avibrato
abkdout filter2 abkdout, 3, 0, ia0, ia1, ia0
delayw ainputb + abkdout * ifbfac * ifbfac
resonant body filter model , from Cuzzucoli and
IIR filter derived via bilinear transform method
; the theoretical resonances resulting from circuit model should be:
resonance due to the air volume + soundhole = 110Hz ( strongest )
resonance due to the top plate = 220Hz
resonance due to the inclusion of the back plate = 400Hz ( weakest )
aresbod filter2 (afwdout + abkdout), 5, 4, 0.000000000005398681501844749, .00000000000001421085471520200, -.00000000001076383426834582, -00000000000001110223024625157, .000000000005392353230604385, -3.990098622573566, 5.974971737738533, -3.979630684599723, .9947612723736902
asignal = (1500 * (afwav + abkwav + aresbod * .000000000000000000003)) ; * adeclick
aoutleft, aoutright pan2 asignal * iamplitude, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "WaveguideGuit i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Xing
//////////////////////////////////////////////
// Original by Andrew Horner.
// Adapted by Michael Gogins.
// p4 pitch in octave.pch
// original pitch = A6
// range = C6 - C7
// extended range = F4 - C7
//////////////////////////////////////////////
insno = p1
itime = p2
iduration = p3
ikey = p4
ivelocity = p5
iphase = p6
ipan = p7
idepth = p8
iheight = p9
ipcs = p10
ihomogeneity = p11
kgain = 1.25
iHz = cpsmidinn(ikey)
kHz = k(iHz)
iattack = (440.0 / iHz) * 0.01
print iHz, iattack
isustain = p3
irelease = .3
p3 = iattack + isustain + irelease
iduration = p3
iamplitude = ampdb(ivelocity) * 8.
isine ftgenonce 0, 0, 65536, 10, 1
kfreq = cpsmidinn(ikey)
iamp = 1
inorm = 32310
aamp1 linseg 0,.001,5200,.001,800,.001,3000,.0025,1100,.002,2800,.0015,1500,.001,2100,.011,1600,.03,1400,.95,700,1,320,1,180,1,90,1,40,1,20,1,12,1,6,1,3,1,0,1,0
adevamp1 linseg 0, .05, .3, iduration - .05, 0
adev1 poscil adevamp1, 6.7, isine, .8
amp1 = aamp1 * (1 + adev1)
aamp2 linseg 0,.0009,22000,.0005,7300,.0009,11000,.0004,5500,.0006,15000,.0004,5500,.0008,2200,.055,7300,.02,8500,.38,5000,.5,300,.5,73,.5,5.,5,0,1,1
adevamp2 linseg 0,.12,.5,iduration-.12,0
adev2 poscil adevamp2, 10.5, isine, 0
amp2 = aamp2 * (1 + adev2)
aamp3 linseg 0,.001,3000,.001,1000,.0017,12000,.0013,3700,.001,12500,.0018,3000,.0012,1200,.001,1400,.0017,6000,.0023,200,.001,3000,.001,1200,.0015,8000,.001,1800,.0015,6000,.08,1200,.2,200,.2,40,.2,10,.4,0,1,0
adevamp3 linseg 0, .02, .8, iduration - .02, 0
adev3 poscil adevamp3, 70, isine ,0
amp3 = aamp3 * (1 + adev3)
awt1 poscil amp1, kfreq, isine
awt2 poscil amp2, 2.7 * kfreq, isine
awt3 poscil amp3, 4.95 * kfreq, isine
asig = awt1 + awt2 + awt3
arel linenr 1,0, iduration, .06
; asignal = asig * arel * (iamp / inorm) * iamplitude * kgain
asignal = asig * (iamp / inorm) * iamplitude * kgain
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
asignal = asignal
ipan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Xing i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ZakianFlute
//////////////////////////////////////////////
// Original by Lee Zakian.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
if1 ftgenonce 0, 0, 65536, 10, 1
iwtsin init if1
if2 ftgenonce 0, 0, 16, -2, 40, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 10240
if26 ftgenonce 0, 0, 65536, -10, 2000, 489, 74, 219, 125, 9, 33, 5, 5
if27 ftgenonce 0, 0, 65536, -10, 2729, 1926, 346, 662, 537, 110, 61, 29, 7
if28 ftgenonce 0, 0, 65536, -10, 2558, 2012, 390, 361, 534, 139, 53, 22, 10, 13, 10
if29 ftgenonce 0, 0, 65536, -10, 12318, 8844, 1841, 1636, 256, 150, 60, 46, 11
if30 ftgenonce 0, 0, 65536, -10, 1229, 16, 34, 57, 32
if31 ftgenonce 0, 0, 65536, -10, 163, 31, 1, 50, 31
if32 ftgenonce 0, 0, 65536, -10, 4128, 883, 354, 79, 59, 23
if33 ftgenonce 0, 0, 65536, -10, 1924, 930, 251, 50, 25, 14
if34 ftgenonce 0, 0, 65536, -10, 94, 6, 22, 8
if35 ftgenonce 0, 0, 65536, -10, 2661, 87, 33, 18
if36 ftgenonce 0, 0, 65536, -10, 174, 12
if37 ftgenonce 0, 0, 65536, -10, 314, 13
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
iattack = .25
isustain = p3
irelease = .33333333
p3 = iattack + isustain + irelease
iHz = ifrequency
kHz = k(iHz)
idB = i_midivelocity
adeclick77 linsegr 0, iattack, 1, isustain, 1, irelease, 0
ip3 = (p3 < 3.0 ? p3 : 3.0)
; parameters
; p4 overall amplitude scaling factor
ip4 init iamplitude
p5 pitch in Hertz ( normal pitch range : C4 - C7 )
ip5 init iHz
; p6 percent vibrato depth, recommended values in range [-1., +1.]
ip6 init 1
0.0 - > no vibrato
+1 . - > 1 % vibrato depth , where vibrato rate increases slightly
-1 . - > 1 % vibrato depth , where vibrato rate decreases slightly
p7 attack time in seconds
; recommended value: .12 for slurred notes, .06 for tongued notes
; (.03 for short notes)
ip7 init .08
p8 decay time in seconds
; recommended value: .1 (.05 for short notes)
ip8 init .08
; p9 overall brightness / filter cutoff factor
1 - > least bright / minimum filter cutoff frequency ( 40 Hz )
9 - > brightest / maximum filter cutoff frequency ( 10,240Hz )
ip9 init 5
; initial variables
iampscale = ip4 ; overall amplitude scaling factor
pitch in Hertz
ivibdepth = abs(ip6*ifreq/100.0) ; vibrato depth relative to fundamental frequency
attack time with up to + -10 % random deviation
giseed = frac(giseed*105.947) ; reset giseed
decay time with up to + -10 % random deviation
giseed = frac(giseed*105.947)
ifiltcut tablei ip9, if2 ; lowpass filter cutoff frequency
iattack = (iattack < 6/kr ? 6/kr : iattack) ; minimal attack length
idecay = (idecay < 6/kr ? 6/kr : idecay) ; minimal decay length
isustain = p3 - iattack - idecay
p3 = (isustain < 5/kr ? iattack+idecay+5/kr : p3) ; minimal sustain length
isustain = (isustain < 5/kr ? 5/kr : isustain)
iatt = iattack/6
isus = isustain/4
idec = idecay/6
use same phase for all wavetables
giseed = frac(giseed*105.947)
; vibrato block
kvibdepth linseg .1 , .8*p3 , 1 , .2*p3 , .7
kvibdepth linseg .1, .8*ip3, 1, isustain, 1, .2*ip3, .7
kvibdepth = kvibdepth* ivibdepth ; vibrato depth
up to 10 % vibrato depth variation
giseed = frac(giseed*105.947)
kvibdepth = kvibdepth + kvibdepthr
ivibr1 = giseed ; vibrato rate
giseed = frac(giseed*105.947)
ivibr2 = giseed
giseed = frac(giseed*105.947)
if ip6 < 0 goto vibrato1
kvibrate linseg 2.5+ivibr1, p3, 4.5+ivibr2 ; if p6 positive vibrato gets faster
goto vibrato2
vibrato1:
ivibr3 = giseed
giseed = frac(giseed*105.947)
kvibrate linseg 3.5+ivibr1, .1, 4.5+ivibr2, p3-.1, 2.5+ivibr3 ; if p6 negative vibrato gets slower
vibrato2:
up to 10 % vibrato rate variation
giseed = frac(giseed*105.947)
kvibrate = kvibrate + kvibrater
kvib oscili kvibdepth, kvibrate, iwtsin
ifdev1 = -.03 * giseed ; frequency deviation
giseed = frac(giseed*105.947)
ifdev2 = .003 * giseed
giseed = frac(giseed*105.947)
ifdev3 = -.0015 * giseed
giseed = frac(giseed*105.947)
ifdev4 = .012 * giseed
giseed = frac(giseed*105.947)
kfreqr linseg ifdev1, iattack, ifdev2, isustain, ifdev3, idecay, ifdev4
kfreq = kHz * (1 + kfreqr) + kvib
if ifreq < 427.28 goto range1 ; (cpspch(8.08) + cpspch(8.09))/2
( cpspch(9.02 ) + cpspch(9.03))/2
if ifreq < 1013.7 goto range3 ; (cpspch(9.11) + cpspch(10.00))/2
goto range4
; wavetable amplitude envelopes
range1: ; for low range tones
kamp1 linseg 0, iatt, 0.002, iatt, 0.045, iatt, 0.146, iatt, \
0.272, iatt, 0.072, iatt, 0.043, isus, 0.230, isus, 0.000, isus, \
0.118, isus, 0.923, idec, 1.191, idec, 0.794, idec, 0.418, idec, \
0.172, idec, 0.053, idec, 0
kamp2 linseg 0, iatt, 0.009, iatt, 0.022, iatt, -0.049, iatt, \
-0.120, iatt, 0.297, iatt, 1.890, isus, 1.543, isus, 0.000, isus, \
0.546, isus, 0.690, idec, -0.318, idec, -0.326, idec, -0.116, idec, \
-0.035, idec, -0.020, idec, 0
kamp3 linseg 0, iatt, 0.005, iatt, -0.026, iatt, 0.023, iatt, \
0.133, iatt, 0.060, iatt, -1.245, isus, -0.760, isus, 1.000, isus, \
0.360, isus, -0.526, idec, 0.165, idec, 0.184, idec, 0.060, idec, \
0.010, idec, 0.013, idec, 0
iwt1 = if26 ; wavetable numbers
iwt2 = if27
iwt3 = if28
inorm = 3949
goto end
range2: ; for low mid-range tones
kamp1 linseg 0, iatt, 0.000, iatt, -0.005, iatt, 0.000, iatt, \
0.030, iatt, 0.198, iatt, 0.664, isus, 1.451, isus, 1.782, isus, \
1.316, isus, 0.817, idec, 0.284, idec, 0.171, idec, 0.082, idec, \
0.037, idec, 0.012, idec, 0
kamp2 linseg 0, iatt, 0.000, iatt, 0.320, iatt, 0.882, iatt, \
1.863, iatt, 4.175, iatt, 4.355, isus, -5.329, isus, -8.303, isus, \
-1.480, isus, -0.472, idec, 1.819, idec, -0.135, idec, -0.082, idec, \
-0.170, idec, -0.065, idec, 0
kamp3 linseg 0, iatt, 1.000, iatt, 0.520, iatt, -0.303, iatt, \
0.059, iatt, -4.103, iatt, -6.784, isus, 7.006, isus, 11, isus, \
12.495, isus, -0.562, idec, -4.946, idec, -0.587, idec, 0.440, idec, \
0.174, idec, -0.027, idec, 0
iwt1 = if29
iwt2 = if30
iwt3 = if31
inorm = 27668.2
goto end
range3: ; for high mid-range tones
kamp1 linseg 0, iatt, 0.005, iatt, 0.000, iatt, -0.082, iatt, \
0.36, iatt, 0.581, iatt, 0.416, isus, 1.073, isus, 0.000, isus, \
0.356, isus, .86, idec, 0.532, idec, 0.162, idec, 0.076, idec, 0.064, \
idec, 0.031, idec, 0
kamp2 linseg 0, iatt, -0.005, iatt, 0.000, iatt, 0.205, iatt, \
-0.284, iatt, -0.208, iatt, 0.326, isus, -0.401, isus, 1.540, isus, \
0.589, isus, -0.486, idec, -0.016, idec, 0.141, idec, 0.105, idec, \
-0.003, idec, -0.023, idec, 0
kamp3 linseg 0, iatt, 0.722, iatt, 1.500, iatt, 3.697, iatt, \
0.080, iatt, -2.327, iatt, -0.684, isus, -2.638, isus, 0.000, isus, \
1.347, isus, 0.485, idec, -0.419, idec, -.700, idec, -0.278, idec, \
0.167, idec, -0.059, idec, 0
iwt1 = if32
iwt2 = if33
iwt3 = if34
inorm = 3775
goto end
range4: ; for high range tones
kamp1 linseg 0, iatt, 0.000, iatt, 0.000, iatt, 0.211, iatt, \
0.526, iatt, 0.989, iatt, 1.216, isus, 1.727, isus, 1.881, isus, \
1.462, isus, 1.28, idec, 0.75, idec, 0.34, idec, 0.154, idec, 0.122, \
idec, 0.028, idec, 0
kamp2 linseg 0, iatt, 0.500, iatt, 0.000, iatt, 0.181, iatt, \
0.859, iatt, -0.205, iatt, -0.430, isus, -0.725, isus, -0.544, isus, \
-0.436, isus, -0.109, idec, -0.03, idec, -0.022, idec, -0.046, idec, \
-0.071, idec, -0.019, idec, 0
kamp3 linseg 0, iatt, 0.000, iatt, 1.000, iatt, 0.426, iatt, \
0.222, iatt, 0.175, iatt, -0.153, isus, 0.355, isus, 0.175, isus, \
0.16, isus, -0.246, idec, -0.045, idec, -0.072, idec, 0.057, idec, \
-0.024, idec, 0.002, idec, 0
iwt1 = if35
iwt2 = if36
iwt3 = if37
inorm = 4909.05
goto end
end:
up to 2 % wavetable amplitude variation
giseed = frac(giseed*105.947)
kamp1 = kamp1 + kampr1
up to 2 % wavetable amplitude variation
giseed = frac(giseed*105.947)
kamp2 = kamp2 + kampr2
up to 2 % wavetable amplitude variation
giseed = frac(giseed*105.947)
kamp3 = kamp3 + kampr3
awt1 poscil kamp1, kfreq, iwt1, iphase ; wavetable lookup
awt2 poscil kamp2, kfreq, iwt2, iphase
awt3 poscil kamp3, kfreq, iwt3, iphase
asig = awt1 + awt2 + awt3
asig = asig*(iampscale/inorm)
kcut linseg 0, iattack, ifiltcut, isustain, ifiltcut, idecay, 0 ; lowpass filter for brightness control
afilt tone asig, kcut
asignal balance afilt, asig
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ZakianFlute i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
//////////////////////////////////////////////
// OUTPUT INSTRUMENTS MUST GO BELOW HERE
//////////////////////////////////////////////
instr Reverberation
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
ainleft inleta "inleft"
ainright inleta "inright"
if (gkReverberationEnabled == 0) goto reverberation_if_label
goto reverberation_else_label
reverberation_if_label:
aoutleft = ainleft
aoutright = ainright
kdry = 1.0 - gkReverberationWet
goto reverberation_endif_label
reverberation_else_label:
awetleft, awetright reverbsc ainleft, ainright, gkReverberationDelay, 18000.0
aoutleft = ainleft * kdry + awetleft * gkReverberationWet
aoutright = ainright * kdry + awetright * gkReverberationWet
reverberation_endif_label:
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Reverberation i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Compressor
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
ainleft inleta "inleft"
ainright inleta "inright"
if (gkCompressorEnabled == 0) goto compressor_if_label
goto compressor_else_label
compressor_if_label:
aoutleft = ainleft
aoutright = ainright
goto compressor_endif_label
compressor_else_label:
aoutleft compress ainleft, ainleft, gkCompressorThreshold, 100 * gkCompressorLowKnee, 100 * gkCompressorHighKnee, 100 * gkCompressorRatio, gkCompressorAttack, gkCompressorRelease, .05
aoutright compress ainright, ainright, gkCompressorThreshold, 100 * gkCompressorLowKnee, 100 * gkCompressorHighKnee, 100 * gkCompressorRatio, gkCompressorAttack, gkCompressorRelease, .05
compressor_endif_label:
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Compressor i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr MasterOutput
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
ainleft inleta "inleft"
ainright inleta "inright"
aoutleft = gkMasterLevel * ainleft
aoutright = gkMasterLevel * ainright
outs aoutleft, aoutright
prints "MasterOutput i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
qqq)
| null | https://raw.githubusercontent.com/gogins/csound-extended-nudruz/4551d54890f4adbadc5db8f46cc24af8e92fb9e9/sources/all-in-one-orc.lisp | lisp | An example Csound orchestra for Common Lisp to be used with the
csound.lisp or sb-csound.lisp foreign function interfaces for Csound.
p1 p2 p3 p4 p5 p6 p7
Start Dur Amp Frqc U V
i 4 32 6 6000 6.00 3 2
p6
p7
Compute X and Y
p1 p2 p3 p4 p5 p6
i2 + 2 1200 6.01 0.25
Output envelope
This envelope loads the string with a triangle wave.
DC Blocker
Delay line with filtered feedback
Resonance of the body
Envelope for driving oscillator.
Amplitude envelope.
Power to partials.
Try other waveforms as well.
isustain + iattack + irelease
BELL SETTINGS:
DECREASING , N1 : N2 IS 5:7 , imax=10
ENVELOPE
DYNAMIC
CARRIER
+ anoise5
Original pfields
Bergeman f1
Constant-power pan.
Do some phasing.
Some vibrato.
Noise for burst at beginning of note.
AUDIO
shift it.
Look up table is in f43, normalized index.
Final output left
Final output right
adsr
pyramid
ramp
f1 0 65536 1 "hahaha.aif" 0 4 0
f6 0 1024 10 1 0 .5 0 .33 0 .25 0 .2 0 .167
a0 14 50
Start Dur Amp Freq GrTab WinTab FqcRng Dens Fade
p4
cpspch(p5)
Exponential rise.
This set of parametric equations defines the path traced by
a point on a circle of radius B rotating inside a circle of
radius A.
p1 p2 p3 p4 p5 p6 p7 p8
Start Dur Amp Frqc A B Hole
i 3 16 6 8000 8.00 10 2 1
p6
p7
p8
Constant-power pan.
Plus amplitude correction.
Final output left
Final output right
prints "Pitch factor: %9.4f\n", i_pitch_correction
Do some cross-coupled manipulation:
Controllers:
1 Vibrato Gain
Controllers:
1 Vibrato Gain
Control Change Numbers:
Control Change Numbers:
Control Change Numbers:
Control Change Numbers:
Control Change Numbers:
Control Change Numbers:
Control Change Numbers:
Control Change Numbers:
/ Modified to fit my needs
Slow attack and release
Slight chorus effect
audio oscillator
audio oscillator - flat
audio oscillator - sharp
Cut-off high frequencies depending on midi-velocity
(larger velocity implies more brighter sound)
Rotor Tables
Rotating Speaker Filter Envelopes
Distortion Tables
The lower tone wheels have increased odd harmonic content.
The model takes pluck position, and pickup position (in % of string length), and generates
a pluck excitation signal, representing the string displacement. The pluck consists
fixed ends.
Losses due to internal friction of the string, and with air, as well as
losses due to the mechanical impedance of the string terminations are simulated by
low pass filtering the signal inside the feedback loops.
The theory implies that force due to string displacement, which is equivalent to
displacement velocity times bridge mechanical impedance, is the input to the guitar
body resonator model. Here we have modified the transfer fuction representing the bridge
mech impedance, to become the string displacement to bridge input force transfer function.
The output of the resulting filter represents the displacement of the guitar's top plate,
and sound hole, since thier respective displacement with be propotional to input force.
(based on a simplified model, viewing the top plate as a force driven spring).
The effects of pluck hardness, and contact with frets during pluck release,
have been modeled by injecting noise into the initial pluck, proportional to initial
string displacement.
Note on pluck shape: Starting with a triangular displacment, I found a decent sounding
initial pluck shape after some trial and error. This pluck shape, which is a linear
ramp, with steep fall off, doesn't necessarily agree with the pluck string models I've
studied. I found that initial pluck shape significantly affects the realism of the
sound output, but I the treatment of this topic in musical acoustics literature seems
rather limited as far as I've encountered.
Original pfields
cpspch(p5)
note:delay time=2x length of string (time to traverse it)
feedback factor
(exponentialy scaled) additive noise to add hi freq content
vibrato depth, +,- ivibDepth semitones
vibrato start delay (secs)
termination impedance model
damping parameter of nut impedance
determine (in crude fashion) which string is being played
pick up position (in % of low E string length)
pluck position (in % of low E string length)
Likewise for the backward traveling acceleration waves, only they encouter the
terminations in the opposite order.
4 / ipluck
initial forward traveling wave (pluck to bridge)
first forward traveling reflection (nut to bridge)
inject noise for attack time string fret contact, and pre pluck vibrations against pick
filter to account for losses along loop path
initial backward excitation wave
initial bdwd traveling wave (pluck to nut)
first forward traveling reflection (nut to bridge)
initial bdwd traveling wave (pluck to nut)
aenvstrb1 delay aenvstrb, iplkdelB
inject noise
filter to account for losses along loop path
Note, it would be more efficient to combine stages into a single filter
Vibrato generator
Dual Delay line,
forward traveling wave delay line
output tap point for fwd traveling wave
output at end of fwd delay (left string boundary)
backward trav wave delay line
output tap point for bkwd traveling wave
output at the left boundary
abkterm deltapi idlt/2
the theoretical resonances resulting from circuit model should be:
* adeclick
asignal = asig * arel * (iamp / inorm) * iamplitude * kgain
parameters
p4 overall amplitude scaling factor
p6 percent vibrato depth, recommended values in range [-1., +1.]
recommended value: .12 for slurred notes, .06 for tongued notes
(.03 for short notes)
recommended value: .1 (.05 for short notes)
p9 overall brightness / filter cutoff factor
initial variables
overall amplitude scaling factor
vibrato depth relative to fundamental frequency
reset giseed
lowpass filter cutoff frequency
minimal attack length
minimal decay length
minimal sustain length
vibrato block
vibrato depth
vibrato rate
if p6 positive vibrato gets faster
if p6 negative vibrato gets slower
frequency deviation
(cpspch(8.08) + cpspch(8.09))/2
(cpspch(9.11) + cpspch(10.00))/2
wavetable amplitude envelopes
for low range tones
wavetable numbers
for low mid-range tones
for high mid-range tones
for high range tones
wavetable lookup
lowpass filter for brightness control |
(in-package :cm)
(defparameter all-in-one-orc #>qqq>
sr = 48000
ksmps = 64
nchnls = 2
0dbfs = 32768
iampdbfs init 32768
prints "Default amplitude at 0 dBFS: %9.4f\n", iampdbfs
idbafs init dbamp(iampdbfs)
prints "dbA at 0 dBFS: %9.4f\n", idbafs
iheadroom init 6
prints "Headroom (dB): %9.4f\n", iheadroom
idbaheadroom init idbafs - iheadroom
prints "dbA at headroom: %9.4f\n", idbaheadroom
iampheadroom init ampdb(idbaheadroom)
prints "Amplitude at headroom: %9.4f\n", iampheadroom
prints "Balance so the overall amps at the end of performance is -6 dbfs.\n"
giFlatQ init sqrt(0.5)
giseed init 0.5
gkHarpsichordGain chnexport "gkHarpsichordGain", 1
gkHarpsichordGain init 1
gkHarpsichordPan chnexport "gkHarpsichordPan", 1
gkHarpsichordPan init 0.5
gkChebyshevDroneCoefficient1 chnexport "gkChebyshevDroneCoefficient1", 1
gkChebyshevDroneCoefficient1 init 0.5
gkChebyshevDroneCoefficient2 chnexport "gkChebyshevDroneCoefficient2", 1
gkChebyshevDroneCoefficient3 chnexport "gkChebyshevDroneCoefficient3", 1
gkChebyshevDroneCoefficient4 chnexport "gkChebyshevDroneCoefficient4", 1
gkChebyshevDroneCoefficient5 chnexport "gkChebyshevDroneCoefficient5", 1
gkChebyshevDroneCoefficient6 chnexport "gkChebyshevDroneCoefficient6", 1
gkChebyshevDroneCoefficient7 chnexport "gkChebyshevDroneCoefficient7", 1
gkChebyshevDroneCoefficient8 chnexport "gkChebyshevDroneCoefficient8", 1
gkChebyshevDroneCoefficient9 chnexport "gkChebyshevDroneCoefficient9", 1
gkChebyshevDroneCoefficient10 chnexport "gkChebyshevDroneCoefficient10", 1
gkChebyshevDroneCoefficient10 init 0.05
gkReverberationEnabled chnexport "gkReverberationEnabled", 1
gkReverberationEnabled init 1
gkReverberationDelay chnexport "gkReverberationDelay", 1
gkReverberationDelay init 0.325
gkReverberationWet chnexport "gkReverberationWet", 1
gkReverberationWet init 0.15
gkCompressorEnabled chnexport "gkCompressorEnabled", 1
gkCompressorEnabled init 0
gkCompressorThreshold chnexport "gkCompressorThreshold", 1
gkCompressorLowKnee chnexport "gkCompressorLowKnee", 1
gkCompressorHighKnee chnexport "gkCompressorHighknee", 1
gkCompressorRatio chnexport "gkCompressorRatio", 1
gkCompressorAttack chnexport "gkCompressorAttack", 1
gkCompressorRelease chnexport "gkCompressorRelease", 1
gkMasterLevel chnexport "gkMasterLevel", 1
gkMasterLevel init 1.5
connect "BanchoffKleinBottle", "outleft", "Reverberation", "inleft"
connect "BanchoffKleinBottle", "outright", "Reverberation", "inright"
connect "BandedWG", "outleft", "Reverberation", "inleft"
connect "BandedWG", "outright", "Reverberation", "inright"
connect "BassModel", "outleft", "Reverberation", "inleft"
connect "BassModel", "outright", "Reverberation", "inright"
connect "ChebyshevDrone", "outleft", "Reverberation", "inleft"
connect "ChebyshevDrone", "outright", "Reverberation", "inright"
connect "ChebyshevMelody", "outleft", "Reverberation", "inleft"
connect "ChebyshevMelody", "outright", "Reverberation", "inright"
connect "Compressor", "outleft", "MasterOutput", "inleft"
connect "Compressor", "outright", "MasterOutput", "inright"
connect "DelayedPluckedString", "outleft", "Reverberation", "inleft"
connect "DelayedPluckedString", "outright", "Reverberation", "inright"
connect "EnhancedFMBell", "outleft", "Reverberation", "inleft"
connect "EnhancedFMBell", "outright", "Reverberation", "inright"
connect "FenderRhodesModel", "outleft", "Reverberation", "inleft"
connect "FenderRhodesModel", "outright", "Reverberation", "inright"
connect "FilteredSines", "outleft", "Reverberation", "inleft"
connect "FilteredSines", "outright", "Reverberation", "inright"
connect "Flute", "outleft", "Reverberation", "inleft"
connect "Flute", "outright", "Reverberation", "inright"
connect "FMModulatedChorusing", "outleft", "Reverberation", "inleft"
connect "FMModulatedChorusing", "outright", "Reverberation", "inright"
connect "FMModerateIndex", "outleft", "Reverberation", "inleft"
connect "FMModerateIndex", "outright", "Reverberation", "inright"
connect "FMModerateIndex2", "outleft", "Reverberation", "inleft"
connect "FMModerateIndex2", "outright", "Reverberation", "inright"
connect "FMWaterBell", "outleft", "Reverberation", "inleft"
connect "FMWaterBell", "outright", "Reverberation", "inright"
connect "Granular", "outleft", "Reverberation", "inleft"
connect "Granular", "outright", "Reverberation", "inright"
connect "Guitar", "outleft", "Reverberation", "inleft"
connect "Guitar", "outright", "Reverberation", "inright"
connect "Guitar2", "outleft", "Reverberation", "inleft"
connect "Guitar2", "outright", "Reverberation", "inright"
connect "Harpsichord", "outleft", "Reverberation", "inleft"
connect "Harpsichord", "outright", "Reverberation", "inright"
connect "HeavyMetalModel", "outleft", "Reverberation", "inleft"
connect "HeavyMetalModel", "outright", "Reverberation", "inright"
connect "Hypocycloid", "outleft", "Reverberation", "inleft"
connect "Hypocycloid", "outright", "Reverberation", "inright"
connect "KungModulatedFM", "outleft", "Reverberation", "inleft"
connect "KungModulatedFM", "outright", "Reverberation", "inright"
connect "ModerateFM", "outleft", "Reverberation", "inleft"
connect "ModerateFM", "outright", "Reverberation", "inright"
connect "ModulatedFM", "outleft", "Reverberation", "inleft"
connect "ModulatedFM", "outright", "Reverberation", "inright"
connect "Melody", "outleft", "Reverberation", "inleft"
connect "Melody", "outright", "Reverberation", "inright"
connect "ParametricEq1", "outleft", "ParametricEq2", "inleft"
connect "ParametricEq1", "outright", "ParametricEq2", "inright"
connect "ParametricEq2", "outleft", "MasterOutput", "inleft"
connect "ParametricEq2", "outright", "MasterOutput", "inright"
connect "PianoOut", "outleft", "Reverberation", "inleft"
connect "PianoOut", "outright", "Reverberation", "inright"
connect "PlainPluckedString", "outleft", "Reverberation", "inleft"
connect "PlainPluckedString", "outright", "Reverberation", "inright"
connect "PRCBeeThree", "outleft", "Reverberation", "inleft"
connect "PRCBeeThree", "outright", "Reverberation", "inright"
connect "PRCBeeThreeDelayed", "outleft", "Reverberation", "inleft"
connect "PRCBeeThreeDelayed", "outright", "Reverberation", "inright"
connect "PRCBowed", "outleft", "Reverberation", "inleft"
connect "PRCBowed", "outright", "Reverberation", "inright"
connect "Reverberation", "outleft", "Compressor", "inleft"
connect "Reverberation", "outright", "Compressor", "inright"
connect "STKBandedWG", "outleft", "Reverberation", "inleft"
connect "STKBandedWG", "outright", "Reverberation", "inright"
connect "STKBeeThree", "outleft", "Reverberation", "inleft"
connect "STKBeeThree", "outright", "Reverberation", "inright"
connect "STKBlowBotl", "outleft", "Reverberation", "inleft"
connect "STKBlowBotl", "outright", "Reverberation", "inright"
connect "STKBlowHole", "outleft", "Reverberation", "inleft"
connect "STKBlowHole", "outright", "Reverberation", "inright"
connect "STKBowed", "outleft", "Reverberation", "inleft"
connect "STKBowed", "outright", "Reverberation", "inright"
connect "STKClarinet", "outleft", "Reverberation", "inleft"
connect "STKClarinet", "outright", "Reverberation", "inright"
connect "STKDrummer", "outleft", "Reverberation", "inleft"
connect "STKDrummer", "outright", "Reverberation", "inright"
connect "STKFlute", "outleft", "Reverberation", "inleft"
connect "STKFlute", "outright", "Reverberation", "inright"
connect "STKFMVoices", "outleft", "Reverberation", "inleft"
connect "STKFMVoices", "outright", "Reverberation", "inright"
connect "STKHvyMetl", "outleft", "Reverberation", "inleft"
connect "STKHvyMetl", "outright", "Reverberation", "inright"
connect "STKMandolin", "outleft", "Reverberation", "inleft"
connect "STKMandolin", "outright", "Reverberation", "inright"
connect "STKModalBar", "outleft", "Reverberation", "inleft"
connect "STKModalBar", "outright", "Reverberation", "inright"
connect "STKMoog", "outleft", "Reverberation", "inleft"
connect "STKMoog", "outright", "Reverberation", "inright"
connect "STKPercFlut", "outleft", "Reverberation", "inleft"
connect "STKPercFlut", "outright", "Reverberation", "inright"
connect "STKPlucked", "outleft", "Reverberation", "inleft"
connect "STKPlucked", "outright", "Reverberation", "inright"
connect "STKResonate", "outleft", "Reverberation", "inleft"
connect "STKResonate", "outright", "Reverberation", "inright"
connect "STKRhodey", "outleft", "Reverberation", "inleft"
connect "STKRhodey", "outright", "Reverberation", "inright"
connect "STKSaxofony", "outleft", "Reverberation", "inleft"
connect "STKSaxofony", "outright", "Reverberation", "inright"
connect "STKShakers", "outleft", "Reverberation", "inleft"
connect "STKShakers", "outright", "Reverberation", "inright"
connect "STKSimple", "outleft", "Reverberation", "inleft"
connect "STKSimple", "outright", "Reverberation", "inright"
connect "STKSitar", "outleft", "Reverberation", "inleft"
connect "STKSitar", "outright", "Reverberation", "inright"
connect "STKTubeBell", "outleft", "Reverberation", "inleft"
connect "STKTubeBell", "outright", "Reverberation", "inright"
connect "STKVoicForm", "outleft", "Reverberation", "inleft"
connect "STKVoicForm", "outright", "Reverberation", "inright"
connect "STKWhistle", "outleft", "Reverberation", "inleft"
connect "STKWhistle", "outright", "Reverberation", "inright"
connect "STKWurley", "outleft", "Reverberation", "inleft"
connect "STKWurley", "outright", "Reverberation", "inright"
connect "StringPad", "outleft", "Reverberation", "inleft"
connect "StringPad", "outright", "Reverberation", "inright"
connect "ToneWheelOrgan", "outleft", "Reverberation", "inleft"
connect "ToneWheelOrgan", "outright", "Reverberation", "inright"
connect "TubularBellModel", "outleft", "Reverberation", "inleft"
connect "TubularBellModel", "outright", "Reverberation", "inright"
connect "WaveguideGuitar", "outleft", "Reverberation", "inleft"
connect "WaveguideGuitar", "outright", "Reverberation", "inright"
connect "Xing", "outleft", "Reverberation", "inleft"
connect "Xing", "outright", "Reverberation", "inright"
connect "ZakianFlute", "outleft", "Reverberation", "inleft"
connect "ZakianFlute", "outright", "Reverberation", "inright"
alwayson "Reverberation"
alwayson "Compressor"
alwayson "MasterOutput"
instr BanchoffKleinBottle
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity)
i 4 36 4 . 5.11 5.6 0.4
i 4 + 4 . 6.05 2 8.5
i 4 . 2 . 6.02 4 5
i 4 . 2 . 6.02 5 0.5
iHz = ifrequency
ifqc init iHz
ip4 init iamplitude
irt2 init sqrt(2)
aampenv linseg 0, 0.02, ip4, p3 - 0.04, ip4, 0.02, 0
isine ftgenonce 0, 0, 65536, 10, 1
icosine ftgenonce 0, 0, 65536, 11, 1
Cosines
acosu oscili 1, iu * ifqc, icosine
acosu2 oscili 1, iu * ifqc / 2, icosine
acosv oscili 1, iv * ifqc, icosine
Sines
asinu oscili 1, iu * ifqc, isine
asinu2 oscili 1, iu * ifqc / 2, isine
asinv oscili 1, iv * ifqc, isine
ax = acosu * (acosu2 * (irt2 + acosv) + asinu2 * asinv * acosv)
ay = asinu * (acosu2 * (irt2 + acosv) + asinu2 * asinv * acosv)
Low frequency rotation in spherical coordinates z , phi , theta .
klfsinth oscili 1, 4, isine
klfsinph oscili 1, 1, isine
klfcosth oscili 1, 4, icosine
klfcosph oscili 1, 1, icosine
aox = -ax * klfsinth + ay * klfcosth
aoy = -ax * klfsinth * klfcosph - ay * klfsinth * klfcosph + klfsinph
aoutleft = aampenv * aox
aoutright = aampenv * aoy
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "BanchoffKlein i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr BandedWG
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 512
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
asignal STKBandedWG ifrequency,1
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "BandedWG i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr BassModel
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 35
Start Dur Amp Pitch PluckDur
i2 128 4 1400 6.00 0.25
i2 . 4 1000 6.05 0.5
i2 . 2 500 6.04 1
i2 . 4 1000 6.03 0.5
i2 . 16 1000 6.00 0.5
iHz = ifrequency
ifqc = iHz
ip4 = iamplitude
ip6 = 0.5
ipluck = 1 / ifqc * ip6
kcount init 0
adline init 0
ablock2 init 0
ablock3 init 0
afiltr init 0
afeedbk init 0
kfltenv linseg 0, 1.5, 1, 1.5, 0
kenvstr linseg 0, ipluck / 4, -ip4 / 2, ipluck / 2, ip4 / 2, ipluck / 4, 0, p3 - ipluck, 0
aenvstr = kenvstr
ainput tone aenvstr, 200
ablock2 = afeedbk - ablock3 + .99 * ablock2
ablock3 = afeedbk
ablock = ablock2
adline delay ablock + ainput, 1 / ifqc - 15 / sr
afiltr tone adline, 400
abody1 reson afiltr, 110, 40
abody1 = abody1 / 5000
abody2 reson afiltr, 70, 20
abody2 = abody2 / 50000
afeedbk = afiltr
aout = afeedbk
asignal = 50 * koutenv * (aout + kfltenv * (abody1 + abody2))
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "BassModel i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ChebyshevDrone
By .
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ihertz = cpsmidinn(i_midikey)
iamp = ampdb(i_midivelocity) * 6
idampingattack = .01
idampingrelease = .02
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
iattack init p3 / 4.0
idecay init p3 / 4.0
isustain init p3 / 2.0
aenvelope transeg 0.0, iattack / 2.0, 2.5, iamp / 2.0, iattack / 2.0, -2.5, iamp, isustain, 0.0, iamp, idecay / 2.0, 2.5, iamp / 2.0, idecay / 2.0, -2.5, 0.
isinetable ftgenonce 0, 0, 65536, 10, 1, 0, .02
asignal poscil3 1, ihertz, isinetable
asignal chebyshevpoly asignal, 0, gkChebyshevDroneCoefficient1, gkChebyshevDroneCoefficient2, gkChebyshevDroneCoefficient3, gkChebyshevDroneCoefficient4, gkChebyshevDroneCoefficient5, gkChebyshevDroneCoefficient6, gkChebyshevDroneCoefficient7, gkChebyshevDroneCoefficient8, gkChebyshevDroneCoefficient9, gkChebyshevDroneCoefficient10
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
asignal = asignal * aenvelope
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ChebyshevDrone i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ChebyshevMelody
///////////////////////////////////////////////////////
// Original by Jon Nelson.
// Adapted by Michael Gogins.
///////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iHz = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 7.
iattack = .01
isustain = p3
irelease = .01
p3 = iattack + isustain + irelease
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
kHz = k(iHz)
idB = i_midivelocity
i1 = iHz
k100 randi 1,0.05
isine ftgenonce 0, 0, 65536, 10, 1
k101 poscil 1, 5 + k100, isine
k102 linseg 0, .5, 1, p3, 1
k100 = i1 + (k101 * k102)
ip3 init 3.0
k1 linenr 0.5 , ip3 * .3 , ip3 * 2 , 0.01
k1 linseg 0, ip3 * .3, .5, ip3 * 2, 0.01, isustain, 0.01, irelease, 0
k2 line 1 , p3 , .5
k2 linseg 1.0, ip3, .5, isustain, .5, irelease, 0
k1 = k2 * k1
k10 expseg 0.0001, iattack, 1.0, isustain, 0.8, irelease, .0001
k10 = (k10 - .0001)
k20 linseg 1.485, iattack, 1.5, (isustain + irelease), 1.485
a1 - 3 are for cheby with p6=1 - 4
icook3 ftgenonce 0, 0, 65536, 10, 1, .4, 0.2, 0.1, 0.1, .05
a1 poscil k1, k100 - .25, icook3
Tables a1 to fn13 , others normalize ,
ip6 ftgenonce 0, 0, 65536, -7, -1, 150, 0.1, 110, 0, 252, 0
a2 tablei a1, ip6, 1, .5
a3 balance a2, a1
a4 foscili 1, k100 + .04, 1, 2.000, k20, isine
a5 poscil 1, k100, isine
a6 = ((a3 * .1) + (a4 * .1) + (a5 * .8)) * k10
a7 comb a6, .5, 1 / i1
a8 = (a6 * .9) + (a7 * .1)
asignal balance a8, a1
asignal = asignal * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ChebyshevMel i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr DelayedPluckedString
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.02
isustain = p3
irelease = 0.15
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ikeyin = i_midikey
ihertz = cpsmidinn(ikeyin)
Detuning of strings by 4 cents each way .
idetune = 4.0 / 1200.0
ihertzleft = cpsmidinn(ikeyin + idetune)
ihertzright = cpsmidinn(ikeyin - idetune)
iamplitude = ampdb(i_midivelocity)
isine ftgenonce 0, 0, 65536, 10, 1
icosine ftgenonce 0, 0, 65536, 11, 1
igenleft = isine
igenright = icosine
kvibrato oscili 1.0 / 120.0, 7.0, icosine
kexponential expseg 1.0, p3 + iattack, 0.0001, irelease, 0.0001
aenvelope = (kexponential - 0.0001) * adeclick
ag pluck iamplitude, cpsmidinn(ikeyin + kvibrato), 200, igenleft, 1
agleft pluck iamplitude, ihertzleft, 200, igenleft, 1
agright pluck iamplitude, ihertzright, 200, igenright, 1
imsleft = 0.2 * 1000
imsright = 0.21 * 1000
adelayleft vdelay ag * aenvelope, imsleft, imsleft + 100
adelayright vdelay ag * aenvelope, imsright, imsright + 100
asignal = adeclick * (agleft + adelayleft + agright + adelayright)
Highpass filter to exclude speaker cone excursions .
asignal1 butterhp asignal, 32.0
asignal2 balance asignal1, asignal
aoutleft, aoutright pan2 asignal2 * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "DelayedPlucked i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr EnhancedFMBell
//////////////////////////////////////////////////////
// Original by John ffitch.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.005
isustain = p3
irelease = 0.25
p3 = i_duration
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequency = cpsmidinn(i_midikey)
Normalize so iamplitude for p5 of 80 = = ampdb(80 ) .
iamplitude = ampdb(i_midivelocity)
idur = 50
iamp = iamplitude
iffitch1 ftgenonce 0, 0, 65536, 10, 1
iffitch2 ftgenonce 0, 0, 8193, 5, 1, 1024, 0.01
iffitch3 ftgenonce 0, 0, 8193, 5, 1, 1024, 0.001
AMP AND INDEX ENV ARE EXPONENTIAL
DURATION = 15 sec
ifq2 = cpsmidinn(i_midikey) * 5/7
if2 = iffitch1
imax = 10
anoise rand 50
MODULATOR
timout 0.5, idur, noisend
knenv linsegr iamp, 0.2, iamp, 0.3, 0
anoise3 rand knenv
anoise4 butterbp anoise3, iamp, 100
anoise5 balance anoise4, anoise3
noisend:
arvb nreverb acar, 2, 0.1
aenvelope transeg 1, idur, -3, 0
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "EnhancedFMBell i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FenderRhodesModel
//////////////////////////////////////////////////////
// Original by Perry Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.01
isustain = p3
irelease = 0.125
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
iindex = 4
icrossfade = 3
ivibedepth = 0.2
iviberate = 6
isine ftgenonce 0, 0, 65536, 10, 1
icosine ftgenonce 0, 0, 65536, 11, 1
Blank wavetable for some FM opcodes .
ifn1 = isine
ifn2 = icosine
ifn3 = isine
ifn4 = icookblank
ivibefn = isine
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
asignal fmrhode iamplitude, ifrequency, iindex, icrossfade, ivibedepth, iviberate, ifn1, ifn2, ifn3, ifn4, ivibefn
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FenderRhodes i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FilteredSines
//////////////////////////////////////////////////////
// Original by Michael Bergeman.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
p1 p2 p3 p4 p5 p6 p7 p8 p9
ins db func at dec freq1 freq2
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.03
isustain = p3
irelease = 0.52
p3 = p3 + iattack + irelease
i_duration = p3
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ip4 = i_midivelocity
idb = ampdb(i_midivelocity) * 4
ip5 = ibergeman
ip3 = i_duration
ip6 = i_duration * 0.25
ip7 = i_duration * 0.75
ip8 = cpsmidinn(i_midikey - 0.01)
ip9 = cpsmidinn(i_midikey + 0.01)
isc = idb * 0.333
k1 line 40, p3, 800
k2 line 440, p3, 220
k3 linen isc, ip6, p3, ip7
k4 line 800, ip3, 40
k5 line 220, ip3, 440
k6 linen isc, ip6, ip3, ip7
k7 linen 1, ip6, ip3, ip7
a5 oscili k3, ip8, ip5
a6 oscili k3, ip8 * 0.999, ip5
a7 oscili k3, ip8 * 1.001, ip5
a1 = a5 + a6 + a7
a8 oscili k6, ip9, ip5
a9 oscili k6, ip9 * 0.999, ip5
a10 oscili k6, ip9 * 1.001, ip5
a11 = a8 + a9 + a10
a2 butterbp a1, k1, 40
a3 butterbp a2, k5, k2 * 0.8
a4 balance a3, a1
a12 butterbp a11, k4, 40
a13 butterbp a12, k2, k5 * 0.8
a14 balance a13, a11
a15 reverb2 a4, 5, 0.3
a16 reverb2 a4, 4, 0.2
ipi = 4.0 * taninv(1.0)
iradians = i_pan * ipi / 2.0
itheta = iradians / 2.0
Translate angle in [ -1 , 1 ] to left and right gain factors .
irightgain = sqrt(2.0) / 2.0 * (cos(itheta) + sin(itheta))
ileftgain = sqrt(2.0) / 2.0 * (cos(itheta) - sin(itheta))
a17 = (a15 + a4) * ileftgain * k7
a18 = (a16 + a4) * irightgain * k7
aoutleft = a17 * adeclick
aoutright = a18 * adeclick
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FilteredSines i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Flute
//////////////////////////////////////////////////////
// Original by James Kelley.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
flute .
icpsp1 = cpsmidinn(i_midikey - 0.0002)
icpsp2 = cpsmidinn(i_midikey + 0.0002)
ip6 = ampdb(i_midivelocity)
iattack = 0.04
isustain = p3
irelease = 0.15
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ip4 = 0
if (ip4 == int(ip4 / 2) * 2) goto initslurs
ihold
initslurs:
iatttm = 0.09
idectm = 0.1
isustm = p3 - iatttm - idectm
idec = ip6
ireinit = -1
if (ip4 > 1) goto checkafterslur
ilast = 0
checkafterslur:
if (ip4 == 1 || ip4 == 3) goto doneslurs
idec = 0
ireinit = 0
KONTROL
doneslurs:
if (isustm <= 0) goto simpleenv
kamp linsegr ilast, iatttm, ip6, isustm, ip6, idectm, idec, 0, idec
goto doneenv
simpleenv:
kamp linsegr ilast, p3 / 2,ip6, p3 / 2, idec, 0, idec
doneenv:
ilast = ip6
kvrandamp rand 0.1
kvamp = (8 + p4) *.06 + kvrandamp
kvrandfreq rand 1
kvfreq = 5.5 + kvrandfreq
isine ftgenonce 0, 0, 65536, 10, 1
kvbra oscili kvamp, kvfreq, isine, ireinit
kfreq1 = icpsp1 + kvbra
kfreq2 = icpsp2 + kvbra
knseenv expon ip6 / 4, 0.2, 1
anoise1 rand knseenv
anoise tone anoise1, 200
a1 oscili kamp, kfreq1, ikellyflute, ireinit
a2 oscili kamp, kfreq2, ikellyflute, ireinit
a3 = a1 + a2 + anoise
aoutleft, aoutright pan2 a3 * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Flute i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FMModerateIndex
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 3
icarrier = 1
iratio = 1.25
ifmamplitude = 8
index = 5.4
iattack = 0.01
isustain = p3
irelease = 0.05
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequencyb = ifrequency * 1.003
icarrierb = icarrier * 1.004
kindenv transeg 0, iattack, -4, 1, isustain, -2, 0.125, irelease, -4, 0
kindex = kindenv * index * ifmamplitude
isine ftgenonce 0, 0, 65536, 10, 1
aouta foscili 1, ifrequency, icarrier, iratio, index, isine
aoutb foscili 1, ifrequencyb, icarrierb, iratio, index, isine
asignal = (aouta + aoutb) * kindenv
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FMModerateInd i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FMModerateIndex2
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 3
icarrier = 1
iratio = 1
ifmamplitude = 6
index = 2.5
iattack = 0.02
isustain = p3
irelease = 0.05
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequencyb = ifrequency * 1.003
icarrierb = icarrier * 1.004
kindenv expseg 0.000001, iattack, 1.0, isustain, 0.0125, irelease, 0.000001
kindex = kindenv * index * ifmamplitude - 0.000001
isine ftgenonce 0, 0, 65536, 10, 1
aouta foscili 1, ifrequency, icarrier, iratio, index, isine
aoutb foscili 1, ifrequencyb, icarrierb, iratio, index, isine
asignal = (aouta + aoutb) * kindenv
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FMModerateInd2 i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FMModulatedChorusing
//////////////////////////////////////////////
// Original by Thomas Kung.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.333333
irelease = 0.1
isustain = p3
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
iamplitude = ampdb(i_midikey) / 1200
ip6 = 0.3
ip7 = 2.2
ishift = 4.0 / 12000
convert parameter 5 to cps .
ipch = cpsmidinn(i_midikey)
convert parameter 5 to oct .
ioct = i_midikey
kadsr linen 1.0, iattack, irelease, 0.01
kmodi linseg 0, iattack, 5, isustain, 2, irelease, 0
r moves from ip6 to ip7 in p3 secs .
kmodr linseg ip6, p3, ip7
a1 = kmodi * (kmodr - 1 / kmodr) / 2
a1 * 2 is argument normalized from 0 - 1 .
a1ndx = abs(a1 * 2 / 20)
a2 = kmodi * (kmodr + 1 / kmodr) / 2
Unscaled ln(I(x ) ) from 0 to 20.0 .
a3 tablei a1ndx, iln, 1
Cosine wave . Get that noise down on the most widely used table !
ao1 oscili a1, ipch, icosine
a4 = exp(-0.5 * a3 + ao1)
Cosine
ao2 oscili a2 * ipch, ipch, icosine
isine ftgenonce 2, 0, 65536, 10, 1
aoutl oscili 1 * kadsr * a4, ao2 + cpsmidinn(ioct + ishift), isine
aoutr oscili 1 * kadsr * a4, ao2 + cpsmidinn(ioct - ishift), isine
asignal = aoutl + aoutr
asignal = asignal * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FMModulatedCho i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr FMWaterBell
//////////////////////////////////////////////
// Original by Steven Yi.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ipch = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 2.0
ipch2 = ipch
kpchline line ipch, i_duration, ipch2
iamp = 2
ienvType = 2
kenv init 0
env0:
kenv adsr .3, .2, .9, .5
kgoto endEnvelope
env1:
kenv linseg 0, i_duration * .5, 1, i_duration * .5, 0
kgoto endEnvelope
env2:
kenv linseg 0, i_duration - .1, 1, .1, 0
kgoto endEnvelope
endEnvelope:
kc1 = 5
kc2 = 5
kvdepth = 0.005
kvrate = 6
icosine ftgenonce 0, 0, 65536, 11, 1
ifn1 = icosine
ifn2 = icosine
ifn3 = icosine
ifn4 = icosine
ivfn = icosine
asignal fmbell iamp, kpchline, kc1, kc2, kvdepth, kvrate, ifn1, ifn2, ifn3, ifn4, ivfn
iattack = 0.003
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 iamplitude * asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "FMWaterBell i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Granular
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 175
f2 0 1024 7 0 224 1 800 0
f3 0 8192 7 1 8192 -1
f4 0 1024 7 0 512 1 512 0
f5 0 1024 10 1 .3 .1 0 .2 .02 0 .1 .04
p1 p2 p3 p4 p5 p6 p7 p8 p9 p10
i1 0.0 6.5 700 9.00 5 4 .210 200 1.8
i1 3.2 3.5 800 7.08 . 4 .042 100 0.8
i1 5.1 5.2 600 7.10 . 4 .032 100 0.9
i1 7.2 6.6 900 8.03 . 4 .021 150 1.6
i1 21.3 4.5 1000 9.00 . 4 .031 150 1.2
i1 26.5 13.5 1100 6.09 . 4 .121 150 1.5
i1 30.7 9.3 900 8.05 . 4 .014 150 2.5
i1 34.2 8.8 700 10.02 . 4 .14 150 1.6
igrtab ftgenonce 0, 0, 65536, 10, 1, .3, .1, 0, .2, .02, 0, .1, .04
iwintab ftgenonce 0, 0, 65536, 10, 1, 0, .5, 0, .33, 0, .25, 0, .2, 0, .167
iHz = ifrequency
ip4 = iamplitude
ip5 = iHz
ip6 = igrtab
ip7 = iwintab
ip8 = 0.033
ip9 = 150
ip10 = 1.6
idur = p3
igrtab = ip6
iwintab = ip7
ifrng = ip8
idens = ip9
ifade = ip10
igdur = 0.2
kamp linseg 0, ifade, 1, idur - 2 * ifade, 1, ifade, 0
Amp Fqc Dense AmpOff PitchOff WinTable MaxGrDur
aoutl grain ip4, ifqc, idens, 100, ifqc * ifrng, igdur, igrtab, iwintab, 5
aoutr grain ip4, ifqc, idens, 100, ifqc * ifrng, igdur, igrtab, iwintab, 5
aoutleft = aoutl * kamp * iamplitude
aoutright = aoutr * kamp * iamplitude
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Granular i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Guitar
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 8.0
iattack = 0.01
isustain = p3
irelease = 0.05
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequency = cpsmidinn(p4)
iamplitude = ampdb(p5) * 20
kamp linsegr 0.0, iattack, iamplitude, isustain, iamplitude, irelease, 0.0
asigcomp pluck 1, 440, 440, 0, 1
asig pluck 1, ifrequency, ifrequency, 0, 1
af1 reson asig, 110, 80
af2 reson asig, 220, 100
af3 reson asig, 440, 80
aout balance 0.6 * af1+ af2 + 0.6 * af3 + 0.4 * asig, asigcomp
kexp expseg 1.0, iattack, 2.0, isustain, 1.0, irelease, 1.0
kenv = kexp - 1.0
asignal = aout * kenv * kamp
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Guitar i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Guitar2
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 12
iattack = 0.01
isustain = p3
irelease = 0.05
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
kamp linsegr 0.0, iattack, 1, isustain, 1, irelease, 0.0
asigcomp pluck kamp, 440, 440, 0, 1
asig pluck kamp, ifrequency, ifrequency, 0, 1
af1 reson asig, 110, 80
af2 reson asig, 220, 100
af3 reson asig, 440, 80
aout balance 0.6 * af1+ af2 + 0.6 * af3 + 0.4 * asig, asigcomp
kexp expseg 1.0, iattack, 2.0, isustain, 1.0, irelease, 1.0
kenv = kexp - 1.0
asignal = aout * kenv
asignal dcblock asignal
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Guitar2 i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Harpsichord
//////////////////////////////////////////////
// Original by James Kelley.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
insno = p1
itime = p2
iduration = p3
ikey = p4
ivelocity = p5
iphase = p6
ipan = p7
idepth = p8
iheight = p9
ipcs = p10
ihomogeneity = p11
gkHarpsichordGain = .25
gkHarpsichordPan = .5
iattack = .005
isustain = p3
irelease = .3
p3 = iattack + isustain + irelease
iHz = cpsmidinn(ikey)
kHz = k(iHz)
iamplitude = ampdb(ivelocity) * 36
aenvelope transeg 1.0, 20.0, -10.0, 0.05
apluck pluck 1, kHz, iHz, 0, 1
iharptable ftgenonce 0, 0, 65536, 7, -1, 1024, 1, 1024, -1
aharp poscil 1, kHz, iharptable
aharp2 balance apluck, aharp
asignal = (apluck + aharp2) * iamplitude * aenvelope * gkHarpsichordGain
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
aoutleft, aoutright pan2 asignal * adeclick, ipan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Harpsichord i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr HeavyMetalModel
//////////////////////////////////////////////
// Original by Perry Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.01
idecay = 2.0
isustain = i_duration
irelease = 0.125
p3 = iattack + iattack + idecay + irelease
adeclick linsegr 0.0, iattack, 1.0, idecay + isustain, 1.0, irelease, 0.0
iindex = 1
icrossfade = 3
ivibedepth = 0.02
iviberate = 4.8
isine ftgenonce 0, 0, 65536, 10, 1
Cosine wave . Get that noise down on the most widely used table !
ithirteen ftgenonce 0, 0, 65536, 9, 1, 0.3, 0
ifn1 = isine
ifn2 = iexponentialrise
ifn3 = ithirteen
ifn4 = isine
ivibefn = icosine
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 48.0
adecay transeg 0.0, iattack, 4, 1.0, idecay + isustain, -4, 0.1, irelease, -4, 0.0
asignal fmmetal 0.1, ifrequency, iindex, icrossfade, ivibedepth, iviberate, ifn1, ifn2, ifn3, ifn4, ivibefn
asignal = asignal * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "HeavyMetalMod i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Hypocycloid
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i 3 20 4 . 7.11 5.6 0.4 0.8
i 3 + 4 . 8.05 2 8.5 0.7
i 3 . 2 . 8.02 4 5 0.6
i 3 . 2 . 8.02 5 0.5 1.2
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
iHz = ifrequency
ifqc init iHz
ip4 init iamplitude
ifqci init iHz
iscale = (ia < ib ? 1 / ib : 1 / ia)
kampenv linseg 0, .1, ip4 * iscale, p3 - .2, ip4 * iscale, .1, 0
kptchenv linseg ifqci, .2 * p3, ifqc, .8 * p3, ifqc
kvibenv linseg 0, .5, 0, .2, 1, .2, 1
isine ftgenonce 0, 0, 65536, 10, 1
icosine ftgenonce 0, 0, 65536, 11, 1
kvibr oscili 20, 8, icosine
kfqc = kptchenv+kvibr*kvibenv
Sine and Cosine
acos1 oscili ia - ib, kfqc, icosine
acos2 oscili ib * ihole, (ia - ib) / ib * kfqc, icosine
ax = acos1 + acos2
asin1 oscili ia-ib, kfqc, isine
asin2 oscili ib, (ia - ib) / ib * kfqc, isine
ay = asin1 - asin2
aoutleft = kampenv * ax
aoutright = kampenv * ay
ipi = 4.0 * taninv(1.0)
iradians = i_pan * ipi / 2.0
itheta = iradians / 2.0
Translate angle in [ -1 , 1 ] to left and right gain factors .
irightgain = sqrt(2.0) / 2.0 * (cos(itheta) + sin(itheta))
ileftgain = sqrt(2.0) / 2.0 * (cos(itheta) - sin(itheta))
outleta "outleft", aoutleft * ileftgain
outleta "outright", aoutright * irightgain
prints "Hypocycloid i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ModerateFM
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.002
isustain = p3
idecay = 8
irelease = 0.05
iHz = cpsmidinn(i_midikey)
idB = i_midivelocity
iamplitude = ampdb(idB) * 4.0
icarrier = 1
imodulator = 0.5
ifmamplitude = 0.25
index = .5
ifrequencyb = iHz * 1.003
icarrierb = icarrier * 1.004
aindenv transeg 0.0, iattack, -11.0, 1.0, idecay, -7.0, 0.025, isustain, 0.0, 0.025, irelease, -7.0, 0.0
aindex = aindenv * index * ifmamplitude
isinetable ftgenonce 0, 0, 65536, 10, 1, 0, .02
ares foscili xamp , , xcar , xmod , kndx , ifn [ , iphs ]
aouta foscili 1.0, iHz, icarrier, imodulator, index / 4., isinetable
aoutb foscili 1.0, ifrequencyb, icarrierb, imodulator, index, isinetable
asignal = (aouta + aoutb) * aindenv
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
asignal = asignal * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ModerateFM i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ModulatedFM
//////////////////////////////////////////////
// Original by Thomas Kung.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = .25
isustain = p3
irelease = .33333333
p3 = iattack + isustain + irelease
iHz = cpsmidinn(i_midikey)
kHz = k(iHz)
idB = i_midivelocity
iamplitude = ampdb(i_midivelocity)
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
ip6 = 0.3
ip7 = 2.2
ishift = 4.0 / 12000.0
kpch = kHz
koct = octcps(kHz)
aadsr linen 1.0, iattack, irelease, 0.01
amodi linseg 0, iattack, 5, p3, 2, irelease, 0
r moves from ip6 to ip7 in p3 secs .
amodr linseg ip6, p3, ip7
a1 = amodi * (amodr - 1 / amodr) / 2
a1 * 2 is argument normalized from 0 - 1 .
a1ndx = abs(a1 * 2 / 20)
a2 = amodi * (amodr + 1 / amodr) / 2
Unscaled ln(I(x ) ) from 0 to 20.0 .
iln ftgenonce 0, 0, 65536, -12, 20.0
a3 tablei a1ndx, iln, 1
icosine ftgenonce 0, 0, 65536, 11, 1
ao1 poscil a1, kpch, icosine
a4 = exp(-0.5 * a3 + ao1)
Cosine
ao2 poscil a2 * kpch, kpch, icosine
isine ftgenonce 0, 0, 65536, 10, 1
aleft poscil a4, ao2 + cpsoct(koct + ishift), isine
aright poscil a4, ao2 + cpsoct(koct - ishift), isine
asignal = (aleft + aright) * iamplitude
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ModulatedFM i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
gk_PianoNote_midi_dynamic_range init 127
giPianoteq init 0
instr PianoNote
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
if p3 == -1 goto indefinite
goto non_indefinite
indefinite:
p3 = 1000000
non_indefinite:
i_instrument = p1
i_time = p2
i_duration = p3
i_midi_key = p4
i_midi_dynamic_range = i(gk_PianoNote_midi_dynamic_range)
i_midi_velocity = p5 * i_midi_dynamic_range / 127 + (63.6 - i_midi_dynamic_range / 2)
k_space_front_to_back = p6
k_space_left_to_right = p7
k_space_bottom_to_top = p8
i_phase = p9
i_homogeneity = p11
instances active p1
prints "PianoNotePt i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\\n", p1, p2, p3, p4, p5, p7, instances
i_pitch_correction = 44100 / sr
vstnote giPianoteq, i_instrument, i_midi_key, i_midi_velocity, i_duration
endin
instr PlainPluckedString
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
iattack = 0.002
isustain = p3
irelease = 0.075
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
aenvelope transeg 0, iattack, -4, iamplitude, isustain, -4, iamplitude / 10.0, irelease, -4, 0
asignal1 pluck 1, ifrequency, ifrequency * 1.002, 0, 1
asignal2 pluck 1, ifrequency * 1.003, ifrequency, 0, 1
asignal = (asignal1 + asignal2) * aenvelope
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "PlainPluckedSt i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr PRCBeeThree
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
asignal STKBeeThree ifrequency, 1
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "PRCBeeThree i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr PRCBeeThreeDelayed
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
iattack = 0.2
isustain = p3
irelease = 0.3
p3 = isustain + iattack + irelease
asignal STKBeeThree ifrequency, 1, 2, 3, 1, 0, 11, 0
amodulator oscils 0.00015, 0.2, 0.0
Read delayed signal , first delayr instance :
adump delayr 4.0
associated with first delayr instance
Read delayed signal , second delayr instance :
adump delayr 4.0
associated with second delayr instance
afdbk1 = 0.7 * adly1 + 0.7 * adly2 + asignal
afdbk2 = -0.7 * adly1 + 0.7 * adly2 + asignal
Feed back signal , associated with first delayr instance :
delayw afdbk1
Feed back signal , associated with second delayr instance :
delayw afdbk2
asignal2 = adly1 + adly2
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal2 * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "PRCBeeThreeDel i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr PRCBowed
//////////////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 6
2 Bow Pressure
4 Bow Position
11 Vibrato Frequency
128 Volume
asignal STKBowed ifrequency, 1.0, 1, 1.8, 2, 120.0, 4, 50.0, 11, 20.0
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "PRCBowed i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBandedWG
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 256
asignal STKBandedWG ifrequency, 1.0
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBandedWG i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBeeThree
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 16
asignal STKBeeThree ifrequency, 1.0, 1, 1.5, 2, 4.8, 4, 2.1
aphased phaser1 asignal, 4000, 16, .2, .9
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 aphased * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBeeThree i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBlowBotl
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
asignal STKBlowBotl ifrequency, 1.0
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBlowBotl i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBlowHole
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
asignal STKBlowHole ifrequency, 1.0
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBlowHole i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKBowed
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
2 Bow Pressure
4 Bow Position
11 Vibrato Frequency
128 Volume
asignal STKBowed ifrequency, 1.0, 1, 0.8, 2, 120.0, 4, 20.0, 11, 20.0
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKBowed i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKClarinet
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
asignal STKClarinet ifrequency, 1.0, 1, 1.5
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKClarinet i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKDrummer
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKDrummer ifrequency, 1.0
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKDrummer i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKFlute
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
* Jet Delay = 2
* Noise Gain = 4
* Vibrato Frequency = 11
* Vibrato Gain = 1
* Breath Pressure = 128
asignal STKFlute ifrequency, 1.0, 128, 100, 2, 70, 4, 10
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKFlute i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKFMVoices
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
* Vowel = 2
* Spectral Tilt = 4
* LFO Speed = 11
* LFO Depth = 1
* ADSR 2 & 4 Target = 128
asignal STKFMVoices ifrequency, 1.0, 2, 1, 4, 3.0, 11, 5, 1, .8
idampingattack = .002
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKFMVoices i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKHvyMetl
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
* Total Modulator Index = 2
* Modulator Crossfade = 4
* LFO Speed = 11
* LFO Depth = 1
* ADSR 2 & 4 Target = 128
asignal STKHevyMetl ifrequency, 1.0, 2, 17.0, 4, 70, 128, 80
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKHvyMetl i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKMandolin
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 24
asignal STKMandolin ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKMandolin i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKModalBar
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 24
* Stick Hardness = 2
* Stick Position = 4
* Vibrato Gain = 1
* Vibrato Frequency = 11
* Direct Stick Mix = 8
* Volume = 128
* Modal Presets = 16
o = 0
o Vibraphone = 1
o Agogo = 2
o Wood1 = 3
o Reso = 4
o Wood2 = 5
o Beats = 6
o Two Fixed = 7
o Clump = 8
asignal STKModalBar ifrequency, 1.0, 16, 1
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKModalBar i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKMoog
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKMoog ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKMoog i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKPercFlut
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKPercFlut ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKPercFlut i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKPlucked
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 16
asignal STKPlucked ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKPlucked i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKResonate
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity)
* Resonance Frequency ( 0 - Nyquist ) = 2
* 4
* Notch Frequency ( 0 - Nyquist ) = 11
* Zero Radii = 1
* Envelope Gain = 128
, 2 , 40 , 4 , .7 , 11 , 120 , 1 , .5
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKResonate i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKRhodey
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKRhodey ifrequency, 1
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKRhodey i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKSaxofony
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
* Reed Stiffness = 2
* Reed Aperture = 26
* Noise Gain = 4
* Blow Position = 11
* Vibrato Frequency = 29
* Vibrato Gain = 1
* Breath Pressure = 128
, 29 , 5 , 1 , 12
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKSaxofony i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKShakers
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 256
* Shake Energy = 2
* System Decay = 4
* Number Of Objects = 11
* Resonance Frequency = 1
* Shake Energy = 128
* Instrument Selection = 1071
o Maraca = 0
o Cabasa = 1
o = 2
o = 3
o Water Drops = 4
o Bamboo Chimes = 5
o = 6
o Sleigh Bells = 7
o Sticks = 8
o Crunch = 9
o Wrench = 10
o Sand Paper = 11
o Coke Can = 12
o Next Mug = 13
o Penny + Mug = 14
o Nickle + Mug = 15
o Dime + Mug = 16
o Quarter + Mug = 17
o = 18
o Peso + Mug = 19
o Big Rocks = 20
o Little Rocks = 21
o Tuned Bamboo Chimes = 22
, 128 , 100 , 1 , 30
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKShakers i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKSimple
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 64
* Filter Pole Position = 2
* Noise / Pitched Cross - Fade = 4
* Envelope Rate = 11
* Gain = 128
asignal STKSimple ifrequency, 1.0, 2, 98, 4, 50, 11, 3
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKSimple i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKSitar
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKSitar ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKSitar i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKTubeBell
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 8
asignal STKTubeBell ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKTubeBell i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKVoicForm
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 16
asignal STKVoicForm ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKVoicForm i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKWhistle
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
asignal STKWhistle ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKWhistle i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr STKWurley
//////////////////////////////////////////////
// Original by Perry R. Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 16
asignal STKWurley ifrequency, 1.0
idampingattack = .0003
idampingrelease = .01
idampingsustain = p3
iduration = idampingattack + idampingsustain + idampingrelease
p3 = iduration
adeclick linsegr 0, idampingattack, 1, idampingsustain, 1, idampingrelease, 0
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "STKWurley i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr StringPad
//////////////////////////////////////////////
// Original by Anthony Kozar.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
String - pad borrowed from the piece " " ,
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ihz = cpsmidinn(i_midikey)
iamp = ampdb(i_midivelocity) * 3
idb = i_midivelocity
ipos = i_pan
akctrl linsegr 0, i_duration * 0.5, iamp, i_duration *.5, 0
iwave ftgenonce 0, 0, 65536, 10, 1, 0.5, 0.33, 0.25, 0.0, 0.1, 0.1, 0.1
asig = afund + acel1 + acel2
asignal butterlp asig, (i_midivelocity - 60) * 40 + 900
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "StringPad i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ToneWheelOrgan
//////////////////////////////////////////////
// Original by Hans Mikelson.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 8.0
iattack = 0.02
isustain = i_duration
irelease = 0.1
i_duration = iattack + isustain + irelease
p3 = i_duration
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
itonewheel1 ftgenonce 0, 0, 65536, 10, 1, 0.02, 0.01
itonewheel2 ftgenonce 0, 0, 65536, 10, 1, 0, 0.2, 0, 0.1, 0, 0.05, 0, 0.02
itonewheel3 ftgenonce 0, 0, 65536, 7, 0, 110, 0, 18, 1, 18, 0, 110, 0
itonewheel4 ftgenonce 0, 0, 65536, 7, 0, 80, 0.2, 16, 1, 64, 1, 16, 0.2, 80, 0
itonewheel5 ftgenonce 0, 0, 65536, 8, -.8, 336, -.78, 800, -.7, 5920, 0.7, 800, 0.78, 336, 0.8
itonewheel6 ftgenonce 0, 0, 65536, 8, -.8, 336, -.76, 3000, -.7, 1520, 0.7, 3000, 0.76, 336, 0.8
icosine ftgenonce 0, 0, 65536, 11, 1
iphase = p2
ikey = 12 * int(i_midikey - 6) + 100 * (i_midikey - 6)
ifqc = ifrequency
iwheel1 = ((ikey - 12) > 12 ? itonewheel1 : itonewheel2)
iwheel2 = ((ikey + 7) > 12 ? itonewheel1 : itonewheel2)
iwheel3 = (ikey > 12 ? itonewheel1 : itonewheel2)
iwheel4 = icosine
insno Start Dur Amp Pitch SubFund Sub3rd Fund 2nd 3rd 4th 5th 6th 8th
i 1 0 6 200 8.04 8 8 8 8 3 2 1 0 4
asubfund oscili 8, 0.5 * ifqc, iwheel1, iphase / (ikey - 12)
asub3rd oscili 8, 1.4983 * ifqc, iwheel2, iphase / (ikey + 7)
afund oscili 8, ifqc, iwheel3, iphase / ikey
a2nd oscili 8, 2 * ifqc, iwheel4, iphase / (ikey + 12)
a3rd oscili 3, 2.9966 * ifqc, iwheel4, iphase / (ikey + 19)
a4th oscili 2, 4 * ifqc, iwheel4, iphase / (ikey + 24)
a5th oscili 1, 5.0397 * ifqc, iwheel4, iphase / (ikey + 28)
a6th oscili 0, 5.9932 * ifqc, iwheel4, iphase / (ikey + 31)
a8th oscili 4, 8 * ifqc, iwheel4, iphase / (ikey + 36)
asignal = iamplitude * (asubfund + asub3rd + afund + a2nd + a3rd + a4th + a5th + a6th + a8th)
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ToneWheelOrgan i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr TubularBellModel
//////////////////////////////////////////////////////
// Original by Perry Cook.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
iattack = 0.003
isustain = p3
irelease = 0.125
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
iindex = 1
icrossfade = 2
ivibedepth = 0.2
iviberate = 6
isine ftgenonce 0, 0, 65536, 10, 1
Cosine wave . Get that noise down on the most widely used table !
icook3 ftgenonce 0, 0, 65536, 10, 1, 0.4, 0.2, 0.1, 0.1, 0.05
ifn1 = isine
ifn2 = icook3
ifn3 = isine
ifn4 = isine
ivibefn = icosine
asignal fmbell 1.0, ifrequency, iindex, icrossfade, ivibedepth, iviberate, ifn1, ifn2, ifn3, ifn4, ivibefn
aoutleft, aoutright pan2 asignal * iamplitude * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "TubularBellMod i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr WaveguideGuitar
//////////////////////////////////////////////////////
// Original by Jeff Livingston.
// Adapted by Michael Gogins.
//////////////////////////////////////////////////////
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) / 16
iHz = ifrequency
of a forward and backward traveling displacement wave , which are recirculated thru two
separate delay lines , to simulate the one dimensional string waveguide , with
Delay line outputs at the bridge termination are summed and fed into an IIR filter
modeled to simulate the lowest two vibrational modes ( resonances ) of the guitar body .
p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13
in st dur amp pkupPos pluckPos brightness vibf vibd vibdel
i01.2 0.5 0.75 5000 7.11 .85 0.9975 .0 .25 1 0 0 0
ip4 init iamplitude
ip6 init 0.85
ip7 init 0.9975
ip8 init 0
ip9 init 0.25
ip10 init 1.0
ip11 init 0.001
ip12 init 0.0
ip13 init 0.0
afwav init 0
abkwav init 0
abkdout init 0
afwdout init 0
iEstr init 1.0 / cpspch(6.04)
idlt init 1.0 / ifqc
ipluck = 0.5 * idlt * ip6 * ifqc / cpspch(8.02)
ibrightness = ip10 * exp(ip6 * log(2)) / 2
ivibRate = ip11
ivibDepth pow 2, ip12 / 12
ivibDepth = idlt - 1.0 / (ivibDepth * ifqc)
ivibStDly = ip13
cutoff freq of LPF due to mech . impedance at the nut ( 2kHz-10kHz )
if0 = 10000
iA0 = ip7
ialpha = cos(2 * 3.14159265 * if0 * 1 / sr)
FIR LPF model of nut impedance , H(z)=a0+a1z^-1+a0z^-2
ia0 = 0.3 * iA0 / (2 * (1 - ialpha))
ia1 = iA0 - 2 * ia0
NOTE each filter pass adds a sampling period delay , so subtract 1 / sr from tap time to compensate
icurStr = ( ifqc > cpspch(6.04 ) ? 2 : 1 )
icurStr = ( ifqc > cpspch(6.09 ) ? 3 : icurStr )
icurStr = ( ifqc > cpspch(7.02 ) ? 4 : icurStr )
icurStr = ( ifqc > cpspch(7.07 ) ? 5 : icurStr )
icurStr = ( ifqc > cpspch(7.11 ) ? 6 : icurStr )
isegF = 1 / sr
isegF2 = ipluck
iplkdelF = (ipluck / 2 > ippos ? 0 : ippos - ipluck / 2)
isegB = 1 / sr
isegB2 = ipluck
iplkdelB = (ipluck / 2 > idlt / 2 - ippos ? 0 : idlt / 2 - ippos - ipluck / 2)
EXCITATION SIGNAL GENERATION
the two excitation signals are fed into the fwd delay represent the 1st and 2nd
reflections off of the left boundary , and two accelerations fed into the delay
represent the the 1st and 2nd reflections off of the right boundary .
ipw = 1
aenvstrf linseg 0, isegF, -ipamp / 2, isegF2, 0
adel1 delayr (idlt > 0) ? idlt : 0.01
aenvstrf1 deltapi iplkdelF
aenvstrf2 deltapi iplkdelB + idlt / 2
delayw aenvstrf
anoiz rand ibrightness
aenvstrf1 = aenvstrf1 + anoiz*aenvstrf1
aenvstrf2 = aenvstrf2 + anoiz*aenvstrf2
aenvstrf2 filter2 aenvstrf2, 3, 0, ia0, ia1, ia0
combine into one signal ( flip refl wave 's phase )
aenvstrf = aenvstrf1 - aenvstrf2
aenvstrb linseg 0, isegB, - ipamp / 2, isegB2, 0
adel2 delayr (idlt > 0) ? idlt : 0.01
aenvstrb1 deltapi iplkdelB
aenvstrb2 deltapi idlt / 2 + iplkdelF
delayw aenvstrb
first bkwd traveling reflection ( bridge to nut )
aenvstrb2 delay aenvstrb , idlt/2+iplkdelF
aenvstrb1 = aenvstrb1 + anoiz*aenvstrb1
aenvstrb2 = aenvstrb2 + anoiz*aenvstrb2
aenvstrb2 filter2 aenvstrb2, 3, 0, ia0, ia1, ia0
combine into one signal ( flip refl wave 's phase )
aenvstrb = aenvstrb1 - aenvstrb2
low pass to band limit initial accel signals to be < 1/2 the sampling freq
ainputf tone aenvstrf, sr * 0.9 / 2
ainputb tone aenvstrb, sr * 0.9 / 2
additional lowpass filtering for pluck shaping\
ainputf tone ainputf, sr * 0.9 / 2
ainputb tone ainputb, sr * 0.9 / 2
icosine ftgenonce 0, 0, 65536, 11, 1.0
avib poscil ivibDepth, ivibRate, icosine
avibdl delayr (((ivibStDly * 1.1)) > 0.0) ? (ivibStDly * 1.1) : 0.01
avibrato deltapi ivibStDly
delayw avib
NOTE : delay length longer than needed by a bit so that the output at t = idlt will be interpolated properly
afd delayr (((idlt + ivibDepth) * 1.1) > 0.0) ? ((idlt + ivibDepth) * 1.1) : 0.01
afwav deltapi ipupos
afwdout deltapi idlt - 1 / sr + avibrato
lpf / attn due to reflection impedance
afwdout filter2 afwdout, 3, 0, ia0, ia1, ia0
delayw ainputf + afwdout * ifbfac * ifbfac
abkwd delayr (((idlt + ivibDepth) * 1.1) > 0) ? ((idlt + ivibDepth) * 1.1) : 0.01
abkwav deltapi idlt / 2 - ipupos
output at end of delay ( right string boundary )
abkdout deltapi idlt - 1 / sr + avibrato
abkdout filter2 abkdout, 3, 0, ia0, ia1, ia0
delayw ainputb + abkdout * ifbfac * ifbfac
resonant body filter model , from Cuzzucoli and
IIR filter derived via bilinear transform method
resonance due to the air volume + soundhole = 110Hz ( strongest )
resonance due to the top plate = 220Hz
resonance due to the inclusion of the back plate = 400Hz ( weakest )
aresbod filter2 (afwdout + abkdout), 5, 4, 0.000000000005398681501844749, .00000000000001421085471520200, -.00000000001076383426834582, -00000000000001110223024625157, .000000000005392353230604385, -3.990098622573566, 5.974971737738533, -3.979630684599723, .9947612723736902
aoutleft, aoutright pan2 asignal * iamplitude, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "WaveguideGuit i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Xing
//////////////////////////////////////////////
// Original by Andrew Horner.
// Adapted by Michael Gogins.
// p4 pitch in octave.pch
// original pitch = A6
// range = C6 - C7
// extended range = F4 - C7
//////////////////////////////////////////////
insno = p1
itime = p2
iduration = p3
ikey = p4
ivelocity = p5
iphase = p6
ipan = p7
idepth = p8
iheight = p9
ipcs = p10
ihomogeneity = p11
kgain = 1.25
iHz = cpsmidinn(ikey)
kHz = k(iHz)
iattack = (440.0 / iHz) * 0.01
print iHz, iattack
isustain = p3
irelease = .3
p3 = iattack + isustain + irelease
iduration = p3
iamplitude = ampdb(ivelocity) * 8.
isine ftgenonce 0, 0, 65536, 10, 1
kfreq = cpsmidinn(ikey)
iamp = 1
inorm = 32310
aamp1 linseg 0,.001,5200,.001,800,.001,3000,.0025,1100,.002,2800,.0015,1500,.001,2100,.011,1600,.03,1400,.95,700,1,320,1,180,1,90,1,40,1,20,1,12,1,6,1,3,1,0,1,0
adevamp1 linseg 0, .05, .3, iduration - .05, 0
adev1 poscil adevamp1, 6.7, isine, .8
amp1 = aamp1 * (1 + adev1)
aamp2 linseg 0,.0009,22000,.0005,7300,.0009,11000,.0004,5500,.0006,15000,.0004,5500,.0008,2200,.055,7300,.02,8500,.38,5000,.5,300,.5,73,.5,5.,5,0,1,1
adevamp2 linseg 0,.12,.5,iduration-.12,0
adev2 poscil adevamp2, 10.5, isine, 0
amp2 = aamp2 * (1 + adev2)
aamp3 linseg 0,.001,3000,.001,1000,.0017,12000,.0013,3700,.001,12500,.0018,3000,.0012,1200,.001,1400,.0017,6000,.0023,200,.001,3000,.001,1200,.0015,8000,.001,1800,.0015,6000,.08,1200,.2,200,.2,40,.2,10,.4,0,1,0
adevamp3 linseg 0, .02, .8, iduration - .02, 0
adev3 poscil adevamp3, 70, isine ,0
amp3 = aamp3 * (1 + adev3)
awt1 poscil amp1, kfreq, isine
awt2 poscil amp2, 2.7 * kfreq, isine
awt3 poscil amp3, 4.95 * kfreq, isine
asig = awt1 + awt2 + awt3
arel linenr 1,0, iduration, .06
asignal = asig * (iamp / inorm) * iamplitude * kgain
adeclick linsegr 0, iattack, 1, isustain, 1, irelease, 0
asignal = asignal
ipan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Xing i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr ZakianFlute
//////////////////////////////////////////////
// Original by Lee Zakian.
// Adapted by Michael Gogins.
//////////////////////////////////////////////
if1 ftgenonce 0, 0, 65536, 10, 1
iwtsin init if1
if2 ftgenonce 0, 0, 16, -2, 40, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 10240
if26 ftgenonce 0, 0, 65536, -10, 2000, 489, 74, 219, 125, 9, 33, 5, 5
if27 ftgenonce 0, 0, 65536, -10, 2729, 1926, 346, 662, 537, 110, 61, 29, 7
if28 ftgenonce 0, 0, 65536, -10, 2558, 2012, 390, 361, 534, 139, 53, 22, 10, 13, 10
if29 ftgenonce 0, 0, 65536, -10, 12318, 8844, 1841, 1636, 256, 150, 60, 46, 11
if30 ftgenonce 0, 0, 65536, -10, 1229, 16, 34, 57, 32
if31 ftgenonce 0, 0, 65536, -10, 163, 31, 1, 50, 31
if32 ftgenonce 0, 0, 65536, -10, 4128, 883, 354, 79, 59, 23
if33 ftgenonce 0, 0, 65536, -10, 1924, 930, 251, 50, 25, 14
if34 ftgenonce 0, 0, 65536, -10, 94, 6, 22, 8
if35 ftgenonce 0, 0, 65536, -10, 2661, 87, 33, 18
if36 ftgenonce 0, 0, 65536, -10, 174, 12
if37 ftgenonce 0, 0, 65536, -10, 314, 13
i_instrument = p1
i_time = p2
i_duration = p3
i_midikey = p4
i_midivelocity = p5
i_phase = p6
i_pan = p7
i_depth = p8
i_height = p9
i_pitchclassset = p10
i_homogeneity = p11
ifrequency = cpsmidinn(i_midikey)
iamplitude = ampdb(i_midivelocity) * 4
iattack = .25
isustain = p3
irelease = .33333333
p3 = iattack + isustain + irelease
iHz = ifrequency
kHz = k(iHz)
idB = i_midivelocity
adeclick77 linsegr 0, iattack, 1, isustain, 1, irelease, 0
ip3 = (p3 < 3.0 ? p3 : 3.0)
ip4 init iamplitude
p5 pitch in Hertz ( normal pitch range : C4 - C7 )
ip5 init iHz
ip6 init 1
0.0 - > no vibrato
+1 . - > 1 % vibrato depth , where vibrato rate increases slightly
-1 . - > 1 % vibrato depth , where vibrato rate decreases slightly
p7 attack time in seconds
ip7 init .08
p8 decay time in seconds
ip8 init .08
1 - > least bright / minimum filter cutoff frequency ( 40 Hz )
9 - > brightest / maximum filter cutoff frequency ( 10,240Hz )
ip9 init 5
pitch in Hertz
attack time with up to + -10 % random deviation
decay time with up to + -10 % random deviation
giseed = frac(giseed*105.947)
isustain = p3 - iattack - idecay
isustain = (isustain < 5/kr ? 5/kr : isustain)
iatt = iattack/6
isus = isustain/4
idec = idecay/6
use same phase for all wavetables
giseed = frac(giseed*105.947)
kvibdepth linseg .1 , .8*p3 , 1 , .2*p3 , .7
kvibdepth linseg .1, .8*ip3, 1, isustain, 1, .2*ip3, .7
up to 10 % vibrato depth variation
giseed = frac(giseed*105.947)
kvibdepth = kvibdepth + kvibdepthr
giseed = frac(giseed*105.947)
ivibr2 = giseed
giseed = frac(giseed*105.947)
if ip6 < 0 goto vibrato1
goto vibrato2
vibrato1:
ivibr3 = giseed
giseed = frac(giseed*105.947)
vibrato2:
up to 10 % vibrato rate variation
giseed = frac(giseed*105.947)
kvibrate = kvibrate + kvibrater
kvib oscili kvibdepth, kvibrate, iwtsin
giseed = frac(giseed*105.947)
ifdev2 = .003 * giseed
giseed = frac(giseed*105.947)
ifdev3 = -.0015 * giseed
giseed = frac(giseed*105.947)
ifdev4 = .012 * giseed
giseed = frac(giseed*105.947)
kfreqr linseg ifdev1, iattack, ifdev2, isustain, ifdev3, idecay, ifdev4
kfreq = kHz * (1 + kfreqr) + kvib
( cpspch(9.02 ) + cpspch(9.03))/2
goto range4
kamp1 linseg 0, iatt, 0.002, iatt, 0.045, iatt, 0.146, iatt, \
0.272, iatt, 0.072, iatt, 0.043, isus, 0.230, isus, 0.000, isus, \
0.118, isus, 0.923, idec, 1.191, idec, 0.794, idec, 0.418, idec, \
0.172, idec, 0.053, idec, 0
kamp2 linseg 0, iatt, 0.009, iatt, 0.022, iatt, -0.049, iatt, \
-0.120, iatt, 0.297, iatt, 1.890, isus, 1.543, isus, 0.000, isus, \
0.546, isus, 0.690, idec, -0.318, idec, -0.326, idec, -0.116, idec, \
-0.035, idec, -0.020, idec, 0
kamp3 linseg 0, iatt, 0.005, iatt, -0.026, iatt, 0.023, iatt, \
0.133, iatt, 0.060, iatt, -1.245, isus, -0.760, isus, 1.000, isus, \
0.360, isus, -0.526, idec, 0.165, idec, 0.184, idec, 0.060, idec, \
0.010, idec, 0.013, idec, 0
iwt2 = if27
iwt3 = if28
inorm = 3949
goto end
kamp1 linseg 0, iatt, 0.000, iatt, -0.005, iatt, 0.000, iatt, \
0.030, iatt, 0.198, iatt, 0.664, isus, 1.451, isus, 1.782, isus, \
1.316, isus, 0.817, idec, 0.284, idec, 0.171, idec, 0.082, idec, \
0.037, idec, 0.012, idec, 0
kamp2 linseg 0, iatt, 0.000, iatt, 0.320, iatt, 0.882, iatt, \
1.863, iatt, 4.175, iatt, 4.355, isus, -5.329, isus, -8.303, isus, \
-1.480, isus, -0.472, idec, 1.819, idec, -0.135, idec, -0.082, idec, \
-0.170, idec, -0.065, idec, 0
kamp3 linseg 0, iatt, 1.000, iatt, 0.520, iatt, -0.303, iatt, \
0.059, iatt, -4.103, iatt, -6.784, isus, 7.006, isus, 11, isus, \
12.495, isus, -0.562, idec, -4.946, idec, -0.587, idec, 0.440, idec, \
0.174, idec, -0.027, idec, 0
iwt1 = if29
iwt2 = if30
iwt3 = if31
inorm = 27668.2
goto end
kamp1 linseg 0, iatt, 0.005, iatt, 0.000, iatt, -0.082, iatt, \
0.36, iatt, 0.581, iatt, 0.416, isus, 1.073, isus, 0.000, isus, \
0.356, isus, .86, idec, 0.532, idec, 0.162, idec, 0.076, idec, 0.064, \
idec, 0.031, idec, 0
kamp2 linseg 0, iatt, -0.005, iatt, 0.000, iatt, 0.205, iatt, \
-0.284, iatt, -0.208, iatt, 0.326, isus, -0.401, isus, 1.540, isus, \
0.589, isus, -0.486, idec, -0.016, idec, 0.141, idec, 0.105, idec, \
-0.003, idec, -0.023, idec, 0
kamp3 linseg 0, iatt, 0.722, iatt, 1.500, iatt, 3.697, iatt, \
0.080, iatt, -2.327, iatt, -0.684, isus, -2.638, isus, 0.000, isus, \
1.347, isus, 0.485, idec, -0.419, idec, -.700, idec, -0.278, idec, \
0.167, idec, -0.059, idec, 0
iwt1 = if32
iwt2 = if33
iwt3 = if34
inorm = 3775
goto end
kamp1 linseg 0, iatt, 0.000, iatt, 0.000, iatt, 0.211, iatt, \
0.526, iatt, 0.989, iatt, 1.216, isus, 1.727, isus, 1.881, isus, \
1.462, isus, 1.28, idec, 0.75, idec, 0.34, idec, 0.154, idec, 0.122, \
idec, 0.028, idec, 0
kamp2 linseg 0, iatt, 0.500, iatt, 0.000, iatt, 0.181, iatt, \
0.859, iatt, -0.205, iatt, -0.430, isus, -0.725, isus, -0.544, isus, \
-0.436, isus, -0.109, idec, -0.03, idec, -0.022, idec, -0.046, idec, \
-0.071, idec, -0.019, idec, 0
kamp3 linseg 0, iatt, 0.000, iatt, 1.000, iatt, 0.426, iatt, \
0.222, iatt, 0.175, iatt, -0.153, isus, 0.355, isus, 0.175, isus, \
0.16, isus, -0.246, idec, -0.045, idec, -0.072, idec, 0.057, idec, \
-0.024, idec, 0.002, idec, 0
iwt1 = if35
iwt2 = if36
iwt3 = if37
inorm = 4909.05
goto end
end:
up to 2 % wavetable amplitude variation
giseed = frac(giseed*105.947)
kamp1 = kamp1 + kampr1
up to 2 % wavetable amplitude variation
giseed = frac(giseed*105.947)
kamp2 = kamp2 + kampr2
up to 2 % wavetable amplitude variation
giseed = frac(giseed*105.947)
kamp3 = kamp3 + kampr3
awt2 poscil kamp2, kfreq, iwt2, iphase
awt3 poscil kamp3, kfreq, iwt3, iphase
asig = awt1 + awt2 + awt3
asig = asig*(iampscale/inorm)
afilt tone asig, kcut
asignal balance afilt, asig
iattack = 0.005
isustain = p3
irelease = 0.06
p3 = isustain + iattack + irelease
adeclick linsegr 0.0, iattack, 1.0, isustain, 1.0, irelease, 0.0
aoutleft, aoutright pan2 asignal * adeclick, i_pan
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "ZakianFlute i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
//////////////////////////////////////////////
// OUTPUT INSTRUMENTS MUST GO BELOW HERE
//////////////////////////////////////////////
instr Reverberation
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
ainleft inleta "inleft"
ainright inleta "inright"
if (gkReverberationEnabled == 0) goto reverberation_if_label
goto reverberation_else_label
reverberation_if_label:
aoutleft = ainleft
aoutright = ainright
kdry = 1.0 - gkReverberationWet
goto reverberation_endif_label
reverberation_else_label:
awetleft, awetright reverbsc ainleft, ainright, gkReverberationDelay, 18000.0
aoutleft = ainleft * kdry + awetleft * gkReverberationWet
aoutright = ainright * kdry + awetright * gkReverberationWet
reverberation_endif_label:
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Reverberation i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr Compressor
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
ainleft inleta "inleft"
ainright inleta "inright"
if (gkCompressorEnabled == 0) goto compressor_if_label
goto compressor_else_label
compressor_if_label:
aoutleft = ainleft
aoutright = ainright
goto compressor_endif_label
compressor_else_label:
aoutleft compress ainleft, ainleft, gkCompressorThreshold, 100 * gkCompressorLowKnee, 100 * gkCompressorHighKnee, 100 * gkCompressorRatio, gkCompressorAttack, gkCompressorRelease, .05
aoutright compress ainright, ainright, gkCompressorThreshold, 100 * gkCompressorLowKnee, 100 * gkCompressorHighKnee, 100 * gkCompressorRatio, gkCompressorAttack, gkCompressorRelease, .05
compressor_endif_label:
outleta "outleft", aoutleft
outleta "outright", aoutright
prints "Compressor i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
instr MasterOutput
//////////////////////////////////////////////
// By Michael Gogins.
//////////////////////////////////////////////
ainleft inleta "inleft"
ainright inleta "inright"
aoutleft = gkMasterLevel * ainleft
aoutright = gkMasterLevel * ainright
outs aoutleft, aoutright
prints "MasterOutput i %9.4f t %9.4f d %9.4f k %9.4f v %9.4f p %9.4f #%3d\n", p1, p2, p3, p4, p5, p7, active(p1)
endin
qqq)
|
2042d196b7d2d77a1905b4f693e9f7f99e966dfe1f3d5416fa40b9c35906f2f7 | dwayne/eopl3 | ex1.21.rkt | #lang racket
;(define (product sos1 sos2)
; (foldl append '() (map
; (lambda (s1)
( map ( lambda ( s2 ) ( list s2 ) ) sos2 ) )
; sos1)))
;(define (product sos1 sos2)
; (append-map
; (lambda (s1)
( map ( lambda ( s2 ) ( list s2 ) ) sos2 ) )
; sos1))
(define (product sos1 sos2)
(for*/list ([s1 sos1]
[s2 sos2])
(list s1 s2)))
(module+ test
(require rackunit)
(check-equal?
(list->set (product '(a b c) '(x y)))
(list->set '((a x) (a y) (b x) (b y) (c x) (c y))))) | null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/01-ch1/racket/ex1.21.rkt | racket | (define (product sos1 sos2)
(foldl append '() (map
(lambda (s1)
sos1)))
(define (product sos1 sos2)
(append-map
(lambda (s1)
sos1)) | #lang racket
( map ( lambda ( s2 ) ( list s2 ) ) sos2 ) )
( map ( lambda ( s2 ) ( list s2 ) ) sos2 ) )
(define (product sos1 sos2)
(for*/list ([s1 sos1]
[s2 sos2])
(list s1 s2)))
(module+ test
(require rackunit)
(check-equal?
(list->set (product '(a b c) '(x y)))
(list->set '((a x) (a y) (b x) (b y) (c x) (c y))))) |
43c2d1ffe1b860c35bc3d90c367d7cb42fc528ba15c46ff7ba1b9ff769b0c7ac | milinda/ef | core.clj | (ns adder.test.core
(:use [adder.core])
(:use [clojure.test]))
(deftest replace-me ;; FIXME: write
(is false "No tests have been written."))
| null | https://raw.githubusercontent.com/milinda/ef/60901356e52eba33addfd509e909eaf8f0d2eab5/clojure-web/adder/test/adder/test/core.clj | clojure | FIXME: write | (ns adder.test.core
(:use [adder.core])
(:use [clojure.test]))
(is false "No tests have been written."))
|
1df67a698fced6774257b9b281bf1080b9d2af5499b852cb0f72bfc088f88f7e | singleheart/programming-in-haskell | countdown.hs | data Op
= Add
| Sub
| Mul
| Div
instance Show Op where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
valid :: Op -> Int -> Int -> Bool
valid Add x y = x <= y
valid Sub x y = x > y
valid Mul x y = x /= 1 && y /= 1 && x <= y
valid Div x y = y /= 1 && x `mod` y == 0
apply :: Op -> Int -> Int -> Int
apply Add x y = x + y
apply Sub x y = x - y
apply Mul x y = x * y
apply Div x y = x `div` y
data Expr
= Val Int
| App Op Expr Expr
instance Show Expr where
show (Val n) = show n
show (App o l r) = brak l ++ show o ++ brak r
where
brak (Val n) = show n
brak e = "(" ++ show e ++ ")"
values :: Expr -> [Int]
values (Val n) = [n]
values (App _ l r) = values l ++ values r
eval :: Expr -> [Int]
eval (Val n) = [n | n > 0]
eval (App o l r) = [apply o x y | x <- eval l, y <- eval r, valid o x y]
subs :: [a] -> [[a]]
subs [] = [[]]
subs (x:xs) = yss ++ map (x :) yss
where
yss = subs xs
interleave :: a -> [a] -> [[a]]
interleave x [] = [[x]]
interleave x (y:ys) = (x : y : ys) : map (y :) (interleave x ys)
perms :: [a] -> [[a]]
perms [] = [[]]
perms (x:xs) = concat (map (interleave x) (perms xs))
choices :: [a] -> [[a]]
choices = concat . map perms . subs
solution :: Expr -> [Int] -> Int -> Bool
solution e ns n = elem (values e) (choices ns) && eval e == [n]
split :: [a] -> [([a], [a])]
split [] = []
split [_] = []
split (x:xs) = ([x], xs) : [(x : ls, rs) | (ls, rs) <- split xs]
exprs :: [Int] -> [Expr]
exprs [] = []
exprs [n] = [Val n]
exprs ns =
[e | (ls, rs) <- split ns, l <- exprs ls, r <- exprs rs, e <- combine l r]
combine :: Expr -> Expr -> [Expr]
combine l r = [App o l r | o <- ops]
ops :: [Op]
ops = [Add, Sub, Mul, Div]
solutions :: [Int] -> Int -> [Expr]
solutions ns n = [e | ns' <- choices ns, e <- exprs ns', eval e == [n]]
type Result = (Expr, Int)
results :: [Int] -> [Result]
results [] = []
results [n] = [(Val n, n) | n > 0]
results ns =
[ res
| (ls, rs) <- split ns
, lx <- results ls
, ry <- results rs
, res <- combine' lx ry
]
combine' :: Result -> Result -> [Result]
combine' (l, x) (r, y) = [(App o l r, apply o x y) | o <- ops, valid o x y]
solutions' :: [Int] -> Int -> [Expr]
solutions' ns n = [e | ns' <- choices ns, (e, m) <- results ns', m == n]
main :: IO ()
main = print (solutions' [1, 3, 7, 10, 25, 50] 765)
| null | https://raw.githubusercontent.com/singleheart/programming-in-haskell/80c7efc0425babea3cd982e47e121f19bec0aba9/ch09/countdown.hs | haskell | data Op
= Add
| Sub
| Mul
| Div
instance Show Op where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
valid :: Op -> Int -> Int -> Bool
valid Add x y = x <= y
valid Sub x y = x > y
valid Mul x y = x /= 1 && y /= 1 && x <= y
valid Div x y = y /= 1 && x `mod` y == 0
apply :: Op -> Int -> Int -> Int
apply Add x y = x + y
apply Sub x y = x - y
apply Mul x y = x * y
apply Div x y = x `div` y
data Expr
= Val Int
| App Op Expr Expr
instance Show Expr where
show (Val n) = show n
show (App o l r) = brak l ++ show o ++ brak r
where
brak (Val n) = show n
brak e = "(" ++ show e ++ ")"
values :: Expr -> [Int]
values (Val n) = [n]
values (App _ l r) = values l ++ values r
eval :: Expr -> [Int]
eval (Val n) = [n | n > 0]
eval (App o l r) = [apply o x y | x <- eval l, y <- eval r, valid o x y]
subs :: [a] -> [[a]]
subs [] = [[]]
subs (x:xs) = yss ++ map (x :) yss
where
yss = subs xs
interleave :: a -> [a] -> [[a]]
interleave x [] = [[x]]
interleave x (y:ys) = (x : y : ys) : map (y :) (interleave x ys)
perms :: [a] -> [[a]]
perms [] = [[]]
perms (x:xs) = concat (map (interleave x) (perms xs))
choices :: [a] -> [[a]]
choices = concat . map perms . subs
solution :: Expr -> [Int] -> Int -> Bool
solution e ns n = elem (values e) (choices ns) && eval e == [n]
split :: [a] -> [([a], [a])]
split [] = []
split [_] = []
split (x:xs) = ([x], xs) : [(x : ls, rs) | (ls, rs) <- split xs]
exprs :: [Int] -> [Expr]
exprs [] = []
exprs [n] = [Val n]
exprs ns =
[e | (ls, rs) <- split ns, l <- exprs ls, r <- exprs rs, e <- combine l r]
combine :: Expr -> Expr -> [Expr]
combine l r = [App o l r | o <- ops]
ops :: [Op]
ops = [Add, Sub, Mul, Div]
solutions :: [Int] -> Int -> [Expr]
solutions ns n = [e | ns' <- choices ns, e <- exprs ns', eval e == [n]]
type Result = (Expr, Int)
results :: [Int] -> [Result]
results [] = []
results [n] = [(Val n, n) | n > 0]
results ns =
[ res
| (ls, rs) <- split ns
, lx <- results ls
, ry <- results rs
, res <- combine' lx ry
]
combine' :: Result -> Result -> [Result]
combine' (l, x) (r, y) = [(App o l r, apply o x y) | o <- ops, valid o x y]
solutions' :: [Int] -> Int -> [Expr]
solutions' ns n = [e | ns' <- choices ns, (e, m) <- results ns', m == n]
main :: IO ()
main = print (solutions' [1, 3, 7, 10, 25, 50] 765)
| |
fc1d2ed9a0bd556b03bd7414ac5e42330716133ba5a63a80fdc177ad9ecc7efb | smart-chain-fr/tokenomia | TxOutRef.hs | # LANGUAGE RecordWildCards #
# OPTIONS_GHC -Wno - orphans #
module Tokenomia.Common.TxOutRef
( showTxOutRef
, TxOutRef (..)
) where
import qualified Data.Text as T
import Ledger ( TxOutRef (..) )
import Tokenomia.Common.Serialise
instance ToCLI TxOutRef where
toCLI = T.pack . showTxOutRef
showTxOutRef :: TxOutRef -> String
showTxOutRef TxOutRef {..} = show txOutRefId <> "#" <> show txOutRefIdx
| null | https://raw.githubusercontent.com/smart-chain-fr/tokenomia/67b361e0bd8494ed0b1af701e28eb8b3e9211fc9/src/Tokenomia/Common/TxOutRef.hs | haskell | # LANGUAGE RecordWildCards #
# OPTIONS_GHC -Wno - orphans #
module Tokenomia.Common.TxOutRef
( showTxOutRef
, TxOutRef (..)
) where
import qualified Data.Text as T
import Ledger ( TxOutRef (..) )
import Tokenomia.Common.Serialise
instance ToCLI TxOutRef where
toCLI = T.pack . showTxOutRef
showTxOutRef :: TxOutRef -> String
showTxOutRef TxOutRef {..} = show txOutRefId <> "#" <> show txOutRefIdx
| |
b0a7e8e7c1bd0ba75061839b2921072c96141f798e02485f8e8c252adc7b4b63 | MinaProtocol/mina | graphql_basic_scalars.ml | *
This file defines basic graphql scalars in a shape usable by graphql_ppx for serialising .
It is meant to be used by backend graphql code .
It also includes basic round - trip testing facilities for GraphQL scalar types .
The [ graphql_lib ] library re - exports these basic scalars as well as other ones ,
and is meant to be used by client code ( via grapqh_ppx ) .
This file defines basic graphql scalars in a shape usable by graphql_ppx for serialising.
It is meant to be used by backend graphql code.
It also includes basic round-trip testing facilities for GraphQL scalar types.
The [graphql_lib] library re-exports these basic scalars as well as other ones,
and is meant to be used by client code (via grapqh_ppx).
*)
open Core_kernel
open Utils
module Make (Schema : Schema) = struct
open Schema
module type Json_intf =
Json_intf_any_typ with type ('a, 'b) typ := ('a, 'b) Schema.typ
let unsigned_scalar_scalar ~to_string typ_name =
scalar typ_name
~doc:
(Core.sprintf
!"String representing a %s number in base 10"
(Stdlib.String.lowercase_ascii typ_name) )
~coerce:(fun num -> `String (to_string num))
(* guard against negative wrap around behaviour from
the `integers` library *)
let parse_uinteger json ~f =
let s = Yojson.Basic.Util.to_string json in
let neg = String.is_prefix ~prefix:"-" s in
if neg then
failwith
"Cannot parse string starting with a minus as an unsigned integer"
else f s
module UInt32 : Json_intf with type t = Unsigned.UInt32.t = struct
type t = Unsigned.UInt32.t
let parse = parse_uinteger ~f:Unsigned.UInt32.of_string
let serialize value = `String (Unsigned.UInt32.to_string value)
let typ () =
unsigned_scalar_scalar ~to_string:Unsigned.UInt32.to_string "UInt32"
end
module UInt64 : Json_intf with type t = Unsigned.UInt64.t = struct
type t = Unsigned.UInt64.t
let parse = parse_uinteger ~f:Unsigned.UInt64.of_string
let serialize value = `String (Unsigned.UInt64.to_string value)
let typ () =
unsigned_scalar_scalar ~to_string:Unsigned.UInt64.to_string "UInt64"
end
module Index : Json_intf with type t = int = struct
type t = int
let parse json = Yojson.Basic.Util.to_string json |> int_of_string
let serialize value = `String (Int.to_string value)
let typ () =
scalar "Index" ~doc:"ocaml integer as a string" ~coerce:serialize
end
module JSON = struct
type t = Yojson.Basic.t
let parse = Base.Fn.id
let serialize = Base.Fn.id
let typ () = scalar "JSON" ~doc:"Arbitrary JSON" ~coerce:serialize
end
module String_json : Json_intf with type t = string = struct
type t = string
let parse json = Yojson.Basic.Util.to_string json
let serialize value = `String value
let typ () = string
end
module Time = struct
type t = Core_kernel.Time.t
let parse json =
Yojson.Basic.Util.to_string json |> Core_kernel.Time.of_string
let serialize t = `String (Core_kernel.Time.to_string t)
let typ () = scalar "Time" ~coerce:serialize
end
module Span = struct
type t = Core.Time.Span.t
let parse json =
Yojson.Basic.Util.to_string json
|> Int64.of_string |> Int64.to_float |> Core.Time.Span.of_ms
let serialize x =
`String (Core.Time.Span.to_ms x |> Int64.of_float |> Int64.to_string)
let typ () = scalar "Span" ~doc:"span" ~coerce:serialize
end
module InetAddr =
Make_scalar_using_to_string
(Core.Unix.Inet_addr)
(struct
let name = "InetAddr"
let doc = "network address"
end)
(Schema)
end
include Make (Schema)
module Utils = Utils
module Testing = Testing
let%test_module "Roundtrip tests" =
( module struct
open Testing
include Make (Test_schema)
module UInt32_gen = struct
include Unsigned.UInt32
let gen =
Int32.quickcheck_generator
|> Quickcheck.Generator.map ~f:Unsigned.UInt32.of_int32
let sexp_of_t = Fn.compose Int32.sexp_of_t Unsigned.UInt32.to_int32
end
let%test_module "UInt32" = (module Testing.Make_test (UInt32) (UInt32_gen))
module UInt64_gen = struct
include Unsigned.UInt64
let gen =
Int64.quickcheck_generator
|> Quickcheck.Generator.map ~f:Unsigned.UInt64.of_int64
let sexp_of_t = Fn.compose Int64.sexp_of_t Unsigned.UInt64.to_int64
end
let%test_module "UInt64" = (module Make_test (UInt64) (UInt64_gen))
module Index_gen = struct
include Int
let gen = quickcheck_generator
end
let%test_module "Index" = (module Make_test (Index) (Index_gen))
module String_gen = struct
include String
let gen = gen_nonempty
end
let%test_module "String_json" = (module Make_test (String_json) (String_gen))
module Span_gen = struct
include Core_kernel.Time.Span
let gen =
let open Core_kernel_private.Span_float in
let millenium = of_day (Float.round_up (365.2425 *. 1000.)) in
Quickcheck.Generator.filter quickcheck_generator ~f:(fun t ->
neg millenium <= t && t <= millenium )
let compare x y =
(* #L61 *)
Note : We have to use a different tolerance than
` Core_kernel . Time . Span.robustly_compare ` does
because spans are rounded to the millisecond when
serialized through GraphQL . See the implementation
of Span in the ` Graphql_basic_scalars ` module .
`Core_kernel.Time.Span.robustly_compare` does
because spans are rounded to the millisecond when
serialized through GraphQL. See the implementation
of Span in the `Graphql_basic_scalars` module. *)
let tolerance = 1E-3 in
let diff = x - y in
if diff < of_sec ~-.tolerance then -1
else if diff > of_sec tolerance then 1
else 0
end
let%test_module "Span" = (module Make_test (Span) (Span_gen))
module Time_gen = struct
type t = Core_kernel.Time.t
The following generator function is copied from version 0.15.0 of the core library , and only generates values that can be serialized .
#L742-L754 .
See issue .
Once the core library is updated to > = 0.15.0 , [ Core . Time.quickcheck_generator ] should be used instead work .
#L742-L754.
See issue .
Once the core library is updated to >= 0.15.0, [Core.Time.quickcheck_generator] should be used instead work.*)
let gen =
Quickcheck.Generator.map Span_gen.gen
~f:Core_kernel.Time.of_span_since_epoch
let sexp_of_t = Core.Time.sexp_of_t
let compare x y = Core_kernel.Time.robustly_compare x y
end
let%test_module "Time" = (module Make_test (Time) (Time_gen))
module InetAddr_gen = struct
include Core.Unix.Inet_addr
let gen =
Int32.gen_incl 0l Int32.max_value
|> Quickcheck.Generator.map ~f:inet4_addr_of_int32
end
let%test_module "InetAddr" = (module Make_test (InetAddr) (InetAddr_gen))
end )
| null | https://raw.githubusercontent.com/MinaProtocol/mina/b216c51c1935de1ede05135ac753ce1bad2620d8/src/lib/graphql_basic_scalars/graphql_basic_scalars.ml | ocaml | guard against negative wrap around behaviour from
the `integers` library
#L61 | *
This file defines basic graphql scalars in a shape usable by graphql_ppx for serialising .
It is meant to be used by backend graphql code .
It also includes basic round - trip testing facilities for GraphQL scalar types .
The [ graphql_lib ] library re - exports these basic scalars as well as other ones ,
and is meant to be used by client code ( via grapqh_ppx ) .
This file defines basic graphql scalars in a shape usable by graphql_ppx for serialising.
It is meant to be used by backend graphql code.
It also includes basic round-trip testing facilities for GraphQL scalar types.
The [graphql_lib] library re-exports these basic scalars as well as other ones,
and is meant to be used by client code (via grapqh_ppx).
*)
open Core_kernel
open Utils
module Make (Schema : Schema) = struct
open Schema
module type Json_intf =
Json_intf_any_typ with type ('a, 'b) typ := ('a, 'b) Schema.typ
let unsigned_scalar_scalar ~to_string typ_name =
scalar typ_name
~doc:
(Core.sprintf
!"String representing a %s number in base 10"
(Stdlib.String.lowercase_ascii typ_name) )
~coerce:(fun num -> `String (to_string num))
let parse_uinteger json ~f =
let s = Yojson.Basic.Util.to_string json in
let neg = String.is_prefix ~prefix:"-" s in
if neg then
failwith
"Cannot parse string starting with a minus as an unsigned integer"
else f s
module UInt32 : Json_intf with type t = Unsigned.UInt32.t = struct
type t = Unsigned.UInt32.t
let parse = parse_uinteger ~f:Unsigned.UInt32.of_string
let serialize value = `String (Unsigned.UInt32.to_string value)
let typ () =
unsigned_scalar_scalar ~to_string:Unsigned.UInt32.to_string "UInt32"
end
module UInt64 : Json_intf with type t = Unsigned.UInt64.t = struct
type t = Unsigned.UInt64.t
let parse = parse_uinteger ~f:Unsigned.UInt64.of_string
let serialize value = `String (Unsigned.UInt64.to_string value)
let typ () =
unsigned_scalar_scalar ~to_string:Unsigned.UInt64.to_string "UInt64"
end
module Index : Json_intf with type t = int = struct
type t = int
let parse json = Yojson.Basic.Util.to_string json |> int_of_string
let serialize value = `String (Int.to_string value)
let typ () =
scalar "Index" ~doc:"ocaml integer as a string" ~coerce:serialize
end
module JSON = struct
type t = Yojson.Basic.t
let parse = Base.Fn.id
let serialize = Base.Fn.id
let typ () = scalar "JSON" ~doc:"Arbitrary JSON" ~coerce:serialize
end
module String_json : Json_intf with type t = string = struct
type t = string
let parse json = Yojson.Basic.Util.to_string json
let serialize value = `String value
let typ () = string
end
module Time = struct
type t = Core_kernel.Time.t
let parse json =
Yojson.Basic.Util.to_string json |> Core_kernel.Time.of_string
let serialize t = `String (Core_kernel.Time.to_string t)
let typ () = scalar "Time" ~coerce:serialize
end
module Span = struct
type t = Core.Time.Span.t
let parse json =
Yojson.Basic.Util.to_string json
|> Int64.of_string |> Int64.to_float |> Core.Time.Span.of_ms
let serialize x =
`String (Core.Time.Span.to_ms x |> Int64.of_float |> Int64.to_string)
let typ () = scalar "Span" ~doc:"span" ~coerce:serialize
end
module InetAddr =
Make_scalar_using_to_string
(Core.Unix.Inet_addr)
(struct
let name = "InetAddr"
let doc = "network address"
end)
(Schema)
end
include Make (Schema)
module Utils = Utils
module Testing = Testing
let%test_module "Roundtrip tests" =
( module struct
open Testing
include Make (Test_schema)
module UInt32_gen = struct
include Unsigned.UInt32
let gen =
Int32.quickcheck_generator
|> Quickcheck.Generator.map ~f:Unsigned.UInt32.of_int32
let sexp_of_t = Fn.compose Int32.sexp_of_t Unsigned.UInt32.to_int32
end
let%test_module "UInt32" = (module Testing.Make_test (UInt32) (UInt32_gen))
module UInt64_gen = struct
include Unsigned.UInt64
let gen =
Int64.quickcheck_generator
|> Quickcheck.Generator.map ~f:Unsigned.UInt64.of_int64
let sexp_of_t = Fn.compose Int64.sexp_of_t Unsigned.UInt64.to_int64
end
let%test_module "UInt64" = (module Make_test (UInt64) (UInt64_gen))
module Index_gen = struct
include Int
let gen = quickcheck_generator
end
let%test_module "Index" = (module Make_test (Index) (Index_gen))
module String_gen = struct
include String
let gen = gen_nonempty
end
let%test_module "String_json" = (module Make_test (String_json) (String_gen))
module Span_gen = struct
include Core_kernel.Time.Span
let gen =
let open Core_kernel_private.Span_float in
let millenium = of_day (Float.round_up (365.2425 *. 1000.)) in
Quickcheck.Generator.filter quickcheck_generator ~f:(fun t ->
neg millenium <= t && t <= millenium )
let compare x y =
Note : We have to use a different tolerance than
` Core_kernel . Time . Span.robustly_compare ` does
because spans are rounded to the millisecond when
serialized through GraphQL . See the implementation
of Span in the ` Graphql_basic_scalars ` module .
`Core_kernel.Time.Span.robustly_compare` does
because spans are rounded to the millisecond when
serialized through GraphQL. See the implementation
of Span in the `Graphql_basic_scalars` module. *)
let tolerance = 1E-3 in
let diff = x - y in
if diff < of_sec ~-.tolerance then -1
else if diff > of_sec tolerance then 1
else 0
end
let%test_module "Span" = (module Make_test (Span) (Span_gen))
module Time_gen = struct
type t = Core_kernel.Time.t
The following generator function is copied from version 0.15.0 of the core library , and only generates values that can be serialized .
#L742-L754 .
See issue .
Once the core library is updated to > = 0.15.0 , [ Core . Time.quickcheck_generator ] should be used instead work .
#L742-L754.
See issue .
Once the core library is updated to >= 0.15.0, [Core.Time.quickcheck_generator] should be used instead work.*)
let gen =
Quickcheck.Generator.map Span_gen.gen
~f:Core_kernel.Time.of_span_since_epoch
let sexp_of_t = Core.Time.sexp_of_t
let compare x y = Core_kernel.Time.robustly_compare x y
end
let%test_module "Time" = (module Make_test (Time) (Time_gen))
module InetAddr_gen = struct
include Core.Unix.Inet_addr
let gen =
Int32.gen_incl 0l Int32.max_value
|> Quickcheck.Generator.map ~f:inet4_addr_of_int32
end
let%test_module "InetAddr" = (module Make_test (InetAddr) (InetAddr_gen))
end )
|
a060fdd9f6ccb08e3952b3762888c3d0332ae1c39a0f0a16fdb6e30944fc4ed7 | nvim-treesitter/nvim-treesitter | highlights.scm | ; Preproc
(unique_id) @preproc
(top_level_annotation_body) @preproc
; Includes
[
"import"
"$import"
"embed"
] @include
(import_path) @string
; Builtins
[
(primitive_type)
"List"
] @type.builtin
; Typedefs
(type_definition) @type.definition
; Labels (@number, @number!)
(field_version) @label
; Methods
(annotation_definition_identifier) @method
(method_identifier) @method
; Fields
(field_identifier) @field
; Properties
(property) @property
; Parameters
(param_identifier) @parameter
(return_identifier) @parameter
; Constants
(const_identifier) @constant
(local_const) @constant
(enum_member) @constant
(void) @constant.builtin
; Types
(enum_identifier) @type
(extend_type) @type
(type_identifier) @type
; Attributes
(annotation_identifier) @attribute
(attribute) @attribute
Operators
[
; @ ! -
"="
] @operator
; Keywords
[
"annotation"
"enum"
"group"
"interface"
"struct"
"union"
] @keyword
[
"extends"
"namespace"
"using"
(annotation_target)
] @keyword
; Literals
[
(string)
(concatenated_string)
(block_text)
(namespace)
] @string
(escape_sequence) @string.escape
(data_string) @string.special
(number) @number
(float) @float
(boolean) @boolean
; Misc
[
"const"
] @type.qualifier
[
"*"
"$"
":"
] @punctuation.special
["{" "}"] @punctuation.bracket
["(" ")"] @punctuation.bracket
["[" "]"] @punctuation.bracket
[
","
";"
"->"
] @punctuation.delimiter
(data_hex) @symbol
; Comments
(comment) @comment @spell
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/598b878a2b44e7e7a981acc5fc99bf8273cd1d0f/queries/capnp/highlights.scm | scheme | Preproc
Includes
Builtins
Typedefs
Labels (@number, @number!)
Methods
Fields
Properties
Parameters
Constants
Types
Attributes
@ ! -
Keywords
Literals
Misc
Comments |
(unique_id) @preproc
(top_level_annotation_body) @preproc
[
"import"
"$import"
"embed"
] @include
(import_path) @string
[
(primitive_type)
"List"
] @type.builtin
(type_definition) @type.definition
(field_version) @label
(annotation_definition_identifier) @method
(method_identifier) @method
(field_identifier) @field
(property) @property
(param_identifier) @parameter
(return_identifier) @parameter
(const_identifier) @constant
(local_const) @constant
(enum_member) @constant
(void) @constant.builtin
(enum_identifier) @type
(extend_type) @type
(type_identifier) @type
(annotation_identifier) @attribute
(attribute) @attribute
Operators
[
"="
] @operator
[
"annotation"
"enum"
"group"
"interface"
"struct"
"union"
] @keyword
[
"extends"
"namespace"
"using"
(annotation_target)
] @keyword
[
(string)
(concatenated_string)
(block_text)
(namespace)
] @string
(escape_sequence) @string.escape
(data_string) @string.special
(number) @number
(float) @float
(boolean) @boolean
[
"const"
] @type.qualifier
[
"*"
"$"
":"
] @punctuation.special
["{" "}"] @punctuation.bracket
["(" ")"] @punctuation.bracket
["[" "]"] @punctuation.bracket
[
","
";"
"->"
] @punctuation.delimiter
(data_hex) @symbol
(comment) @comment @spell
|
c45b7767ce510786712ea5ec2c49f3ac0a68c4a2e48b859670d222e90868ed1b | lnostdal/SymbolicWeb | reactive_paradigm.clj | (in-ns 'symbolicweb.core)
;;; Reactive programming
;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;
(defn clear-observers [^Observable observable]
(ref-set (.observers observable) #{}))
(defn ^Observable mk-Observable [^Fn notify-observers-fn]
(Observable. (ref #{}) ;; OBSERVERS
notify-observers-fn))
(defn notify-observers [^Observable observable & args]
(apply (.notify-observers-fn observable) observable args))
(def ^:dynamic *observables-stack* #{})
(defn observe "LIFETIME: If given an instance of Lifetime, observation will start once that Lifetime is activated and last until it is
as long as OBSERVABLE exists .
CALLBACK: (fn [inner-lifetime & args] ..), where INNER-LIFETIME may be an instance of Lifetime or FALSE.
Returns a (new) instance of Lifetime if LIFETIME was an instance of Lifetime, or FALSE otherwise. This is also the value passed
as the first argument to CALLBACK."
3 choices :
;; * Allow circular references fully, which might lead to infinite loops in some cases; so it's not really "allowed" anyway.
;; * Allow circular refeneces "partially"; let it recurse up until some limit then, say, show a warning or similar.
;; * Disallow circular references.
;;
I 've been playing around with these options , and it seems the first option is risky as it might lead to infinite loops and
stack overflows . The second option means stuff will break " sometimes " . The third option is simple ; things will always fail
;; early.
^Lifetime [^Observable observable lifetime ^Fn callback]
(let [callback (fn [& args]
(if (contains? *observables-stack* observable)
(throw (Exception. (str "OBSERVE: Circular reference; bailing out: " observable)))
(binding [*observables-stack* (conj *observables-stack* observable)]
(apply callback args))))]
(if lifetime
(let [inner-lifetime (mk-Lifetime)
callback (partial callback inner-lifetime)]
(add-lifetime-activation-fn inner-lifetime (fn [_] (add-observer observable callback)))
(add-lifetime-deactivation-fn inner-lifetime (fn [_] (remove-observer observable callback)))
(attach-lifetime lifetime inner-lifetime)
inner-lifetime)
(do
(add-observer observable (partial callback false))
false))))
#_(try
(dosync
(let [x (vm 0)]
(vm-observe x nil false (fn [lifetime old-value new-value]
(dbg [new-value old-value])))
(vm-set x 42)))
(catch Throwable e
(clojure.stacktrace/print-stack-trace e)))
[ new - value old - value ] = > [ 42 0 ]
42
#_(dosync
(let [x (vm 0)
squared-x (with-observed-vms nil
(* @x @x))] ;;(vm-sync x nil (fn [x & _] (* x x)))]
(println [@x @squared-x])
(vm-set x 2)
(println [@x @squared-x])))
;;; Playing around with "functional" stuff here.
;;
;;
;
;;(def -symbolicweb-world- (agent {}))
#_(defn sw-notify-observers [world ks k v old-value]
"Returns WORLD transformed."
Look up observers in WORLD via [ KS K ] . An observer is a vector of FNs .
TODO : Is it possible to serialize the FNs somehow ? I guess the [ KS K ] lookup will lead to code doing the same thing
for each SW server restart . ... or , there 's : -fn
)
#_(defn sw-update [world ks k v]
"Returns WORLD transformed."
(let [old-value (with (get-in world ks ::not-found)
(if (= ::not-found it)
::initial-update
(get it k ::initial-update)))]
(sw-notify-observers (update-in world ks
assoc k v)
ks k v old-value)))
#_(defn do-sw-update [ks k v]
(send -symbolicweb-world- sw-update ks k v))
| null | https://raw.githubusercontent.com/lnostdal/SymbolicWeb/d9600b286f70f88570deda57b05ca240e4e06567/src/symbolicweb/reactive_paradigm.clj | clojure | Reactive programming
OBSERVERS
* Allow circular references fully, which might lead to infinite loops in some cases; so it's not really "allowed" anyway.
* Allow circular refeneces "partially"; let it recurse up until some limit then, say, show a warning or similar.
* Disallow circular references.
things will always fail
early.
(vm-sync x nil (fn [x & _] (* x x)))]
Playing around with "functional" stuff here.
(def -symbolicweb-world- (agent {})) | (in-ns 'symbolicweb.core)
(defn clear-observers [^Observable observable]
(ref-set (.observers observable) #{}))
(defn ^Observable mk-Observable [^Fn notify-observers-fn]
notify-observers-fn))
(defn notify-observers [^Observable observable & args]
(apply (.notify-observers-fn observable) observable args))
(def ^:dynamic *observables-stack* #{})
(defn observe "LIFETIME: If given an instance of Lifetime, observation will start once that Lifetime is activated and last until it is
as long as OBSERVABLE exists .
CALLBACK: (fn [inner-lifetime & args] ..), where INNER-LIFETIME may be an instance of Lifetime or FALSE.
Returns a (new) instance of Lifetime if LIFETIME was an instance of Lifetime, or FALSE otherwise. This is also the value passed
as the first argument to CALLBACK."
3 choices :
I 've been playing around with these options , and it seems the first option is risky as it might lead to infinite loops and
^Lifetime [^Observable observable lifetime ^Fn callback]
(let [callback (fn [& args]
(if (contains? *observables-stack* observable)
(throw (Exception. (str "OBSERVE: Circular reference; bailing out: " observable)))
(binding [*observables-stack* (conj *observables-stack* observable)]
(apply callback args))))]
(if lifetime
(let [inner-lifetime (mk-Lifetime)
callback (partial callback inner-lifetime)]
(add-lifetime-activation-fn inner-lifetime (fn [_] (add-observer observable callback)))
(add-lifetime-deactivation-fn inner-lifetime (fn [_] (remove-observer observable callback)))
(attach-lifetime lifetime inner-lifetime)
inner-lifetime)
(do
(add-observer observable (partial callback false))
false))))
#_(try
(dosync
(let [x (vm 0)]
(vm-observe x nil false (fn [lifetime old-value new-value]
(dbg [new-value old-value])))
(vm-set x 42)))
(catch Throwable e
(clojure.stacktrace/print-stack-trace e)))
[ new - value old - value ] = > [ 42 0 ]
42
#_(dosync
(let [x (vm 0)
squared-x (with-observed-vms nil
(println [@x @squared-x])
(vm-set x 2)
(println [@x @squared-x])))
#_(defn sw-notify-observers [world ks k v old-value]
"Returns WORLD transformed."
Look up observers in WORLD via [ KS K ] . An observer is a vector of FNs .
TODO : Is it possible to serialize the FNs somehow ? I guess the [ KS K ] lookup will lead to code doing the same thing
for each SW server restart . ... or , there 's : -fn
)
#_(defn sw-update [world ks k v]
"Returns WORLD transformed."
(let [old-value (with (get-in world ks ::not-found)
(if (= ::not-found it)
::initial-update
(get it k ::initial-update)))]
(sw-notify-observers (update-in world ks
assoc k v)
ks k v old-value)))
#_(defn do-sw-update [ks k v]
(send -symbolicweb-world- sw-update ks k v))
|
4d4e339d1eb7aa5027c6aec0b7923abe754cf6789914b27ea382287d876d22fa | avsm/platform | class.mli | class type empty =
object
end
class type mutually =
object
end
and recursive =
object
end
class mutually' : mutually
and recursive' : recursive
class type virtual empty_virtual =
object
end
class virtual empty_virtual' : empty
class type ['a] polymorphic =
object
end
class ['a] polymorphic' : ['a] polymorphic
| null | https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/odoc.1.4.2/test/html/cases/class.mli | ocaml | class type empty =
object
end
class type mutually =
object
end
and recursive =
object
end
class mutually' : mutually
and recursive' : recursive
class type virtual empty_virtual =
object
end
class virtual empty_virtual' : empty
class type ['a] polymorphic =
object
end
class ['a] polymorphic' : ['a] polymorphic
| |
7d1b0ed2bbc067130a2f017ea80ba7f89720651f27c84fb1fb9023c57f548c27 | mbj/stratosphere | ActionProperty.hs | module Stratosphere.SES.ReceiptRule.ActionProperty (
module Exports, ActionProperty(..), mkActionProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.SES.ReceiptRule.AddHeaderActionProperty as Exports
import {-# SOURCE #-} Stratosphere.SES.ReceiptRule.BounceActionProperty as Exports
import {-# SOURCE #-} Stratosphere.SES.ReceiptRule.LambdaActionProperty as Exports
import {-# SOURCE #-} Stratosphere.SES.ReceiptRule.S3ActionProperty as Exports
import {-# SOURCE #-} Stratosphere.SES.ReceiptRule.SNSActionProperty as Exports
import {-# SOURCE #-} Stratosphere.SES.ReceiptRule.StopActionProperty as Exports
import {-# SOURCE #-} Stratosphere.SES.ReceiptRule.WorkmailActionProperty as Exports
import Stratosphere.ResourceProperties
data ActionProperty
= ActionProperty {addHeaderAction :: (Prelude.Maybe AddHeaderActionProperty),
bounceAction :: (Prelude.Maybe BounceActionProperty),
lambdaAction :: (Prelude.Maybe LambdaActionProperty),
s3Action :: (Prelude.Maybe S3ActionProperty),
sNSAction :: (Prelude.Maybe SNSActionProperty),
stopAction :: (Prelude.Maybe StopActionProperty),
workmailAction :: (Prelude.Maybe WorkmailActionProperty)}
mkActionProperty :: ActionProperty
mkActionProperty
= ActionProperty
{addHeaderAction = Prelude.Nothing, bounceAction = Prelude.Nothing,
lambdaAction = Prelude.Nothing, s3Action = Prelude.Nothing,
sNSAction = Prelude.Nothing, stopAction = Prelude.Nothing,
workmailAction = Prelude.Nothing}
instance ToResourceProperties ActionProperty where
toResourceProperties ActionProperty {..}
= ResourceProperties
{awsType = "AWS::SES::ReceiptRule.Action",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "AddHeaderAction" Prelude.<$> addHeaderAction,
(JSON..=) "BounceAction" Prelude.<$> bounceAction,
(JSON..=) "LambdaAction" Prelude.<$> lambdaAction,
(JSON..=) "S3Action" Prelude.<$> s3Action,
(JSON..=) "SNSAction" Prelude.<$> sNSAction,
(JSON..=) "StopAction" Prelude.<$> stopAction,
(JSON..=) "WorkmailAction" Prelude.<$> workmailAction])}
instance JSON.ToJSON ActionProperty where
toJSON ActionProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "AddHeaderAction" Prelude.<$> addHeaderAction,
(JSON..=) "BounceAction" Prelude.<$> bounceAction,
(JSON..=) "LambdaAction" Prelude.<$> lambdaAction,
(JSON..=) "S3Action" Prelude.<$> s3Action,
(JSON..=) "SNSAction" Prelude.<$> sNSAction,
(JSON..=) "StopAction" Prelude.<$> stopAction,
(JSON..=) "WorkmailAction" Prelude.<$> workmailAction]))
instance Property "AddHeaderAction" ActionProperty where
type PropertyType "AddHeaderAction" ActionProperty = AddHeaderActionProperty
set newValue ActionProperty {..}
= ActionProperty {addHeaderAction = Prelude.pure newValue, ..}
instance Property "BounceAction" ActionProperty where
type PropertyType "BounceAction" ActionProperty = BounceActionProperty
set newValue ActionProperty {..}
= ActionProperty {bounceAction = Prelude.pure newValue, ..}
instance Property "LambdaAction" ActionProperty where
type PropertyType "LambdaAction" ActionProperty = LambdaActionProperty
set newValue ActionProperty {..}
= ActionProperty {lambdaAction = Prelude.pure newValue, ..}
instance Property "S3Action" ActionProperty where
type PropertyType "S3Action" ActionProperty = S3ActionProperty
set newValue ActionProperty {..}
= ActionProperty {s3Action = Prelude.pure newValue, ..}
instance Property "SNSAction" ActionProperty where
type PropertyType "SNSAction" ActionProperty = SNSActionProperty
set newValue ActionProperty {..}
= ActionProperty {sNSAction = Prelude.pure newValue, ..}
instance Property "StopAction" ActionProperty where
type PropertyType "StopAction" ActionProperty = StopActionProperty
set newValue ActionProperty {..}
= ActionProperty {stopAction = Prelude.pure newValue, ..}
instance Property "WorkmailAction" ActionProperty where
type PropertyType "WorkmailAction" ActionProperty = WorkmailActionProperty
set newValue ActionProperty {..}
= ActionProperty {workmailAction = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/ses/gen/Stratosphere/SES/ReceiptRule/ActionProperty.hs | haskell | # SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE # | module Stratosphere.SES.ReceiptRule.ActionProperty (
module Exports, ActionProperty(..), mkActionProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
data ActionProperty
= ActionProperty {addHeaderAction :: (Prelude.Maybe AddHeaderActionProperty),
bounceAction :: (Prelude.Maybe BounceActionProperty),
lambdaAction :: (Prelude.Maybe LambdaActionProperty),
s3Action :: (Prelude.Maybe S3ActionProperty),
sNSAction :: (Prelude.Maybe SNSActionProperty),
stopAction :: (Prelude.Maybe StopActionProperty),
workmailAction :: (Prelude.Maybe WorkmailActionProperty)}
mkActionProperty :: ActionProperty
mkActionProperty
= ActionProperty
{addHeaderAction = Prelude.Nothing, bounceAction = Prelude.Nothing,
lambdaAction = Prelude.Nothing, s3Action = Prelude.Nothing,
sNSAction = Prelude.Nothing, stopAction = Prelude.Nothing,
workmailAction = Prelude.Nothing}
instance ToResourceProperties ActionProperty where
toResourceProperties ActionProperty {..}
= ResourceProperties
{awsType = "AWS::SES::ReceiptRule.Action",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "AddHeaderAction" Prelude.<$> addHeaderAction,
(JSON..=) "BounceAction" Prelude.<$> bounceAction,
(JSON..=) "LambdaAction" Prelude.<$> lambdaAction,
(JSON..=) "S3Action" Prelude.<$> s3Action,
(JSON..=) "SNSAction" Prelude.<$> sNSAction,
(JSON..=) "StopAction" Prelude.<$> stopAction,
(JSON..=) "WorkmailAction" Prelude.<$> workmailAction])}
instance JSON.ToJSON ActionProperty where
toJSON ActionProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "AddHeaderAction" Prelude.<$> addHeaderAction,
(JSON..=) "BounceAction" Prelude.<$> bounceAction,
(JSON..=) "LambdaAction" Prelude.<$> lambdaAction,
(JSON..=) "S3Action" Prelude.<$> s3Action,
(JSON..=) "SNSAction" Prelude.<$> sNSAction,
(JSON..=) "StopAction" Prelude.<$> stopAction,
(JSON..=) "WorkmailAction" Prelude.<$> workmailAction]))
instance Property "AddHeaderAction" ActionProperty where
type PropertyType "AddHeaderAction" ActionProperty = AddHeaderActionProperty
set newValue ActionProperty {..}
= ActionProperty {addHeaderAction = Prelude.pure newValue, ..}
instance Property "BounceAction" ActionProperty where
type PropertyType "BounceAction" ActionProperty = BounceActionProperty
set newValue ActionProperty {..}
= ActionProperty {bounceAction = Prelude.pure newValue, ..}
instance Property "LambdaAction" ActionProperty where
type PropertyType "LambdaAction" ActionProperty = LambdaActionProperty
set newValue ActionProperty {..}
= ActionProperty {lambdaAction = Prelude.pure newValue, ..}
instance Property "S3Action" ActionProperty where
type PropertyType "S3Action" ActionProperty = S3ActionProperty
set newValue ActionProperty {..}
= ActionProperty {s3Action = Prelude.pure newValue, ..}
instance Property "SNSAction" ActionProperty where
type PropertyType "SNSAction" ActionProperty = SNSActionProperty
set newValue ActionProperty {..}
= ActionProperty {sNSAction = Prelude.pure newValue, ..}
instance Property "StopAction" ActionProperty where
type PropertyType "StopAction" ActionProperty = StopActionProperty
set newValue ActionProperty {..}
= ActionProperty {stopAction = Prelude.pure newValue, ..}
instance Property "WorkmailAction" ActionProperty where
type PropertyType "WorkmailAction" ActionProperty = WorkmailActionProperty
set newValue ActionProperty {..}
= ActionProperty {workmailAction = Prelude.pure newValue, ..} |
37cf2b497a1ca31b06e589e96b4ad56a37344321f0371a7b69e199203cedb590 | bos/rwh | Expensive.hs | - snippet notQuiteRight -
import Control.Concurrent
notQuiteRight = do
mv <- newEmptyMVar
forkIO $ expensiveComputation_stricter mv
someOtherActivity
result <- takeMVar mv
print result
{-- /snippet notQuiteRight --}
{-- snippet expensiveComputation --}
expensiveComputation mv = do
let a = "this is "
b = "not really "
c = "all that expensive"
putMVar mv (a ++ b ++ c)
{-- /snippet expensiveComputation --}
someOtherActivity = return ()
| null | https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch24/Expensive.hs | haskell | - /snippet notQuiteRight -
- snippet expensiveComputation -
- /snippet expensiveComputation - | - snippet notQuiteRight -
import Control.Concurrent
notQuiteRight = do
mv <- newEmptyMVar
forkIO $ expensiveComputation_stricter mv
someOtherActivity
result <- takeMVar mv
print result
expensiveComputation mv = do
let a = "this is "
b = "not really "
c = "all that expensive"
putMVar mv (a ++ b ++ c)
someOtherActivity = return ()
|
2e7f003cecb02064f3d0a517d1a1e9a5f2bc8eb4077001c2f4d1b0b519809e24 | wargrey/graphics | grayscale.rkt | #lang typed/racket/base
(require "../digitama/stdio.rkt")
(require "../effect.rkt")
(define romedalen (read-bitmap (collection-file-path "romedalen.png" "bitmap" "tamer" "cairo") #:backing-scale 2.0))
romedalen
(bitmap-grayscale/lightness romedalen)
(bitmap-grayscale/average romedalen)
(bitmap-grayscale/luminosity romedalen)
'decomposition
(bitmap-grayscale/decomposition romedalen 'max)
(bitmap-grayscale/decomposition romedalen 'min)
'channel
(bitmap-grayscale/channel romedalen 'red)
(bitmap-grayscale/channel romedalen 'green)
(collect-garbage)
(bitmap-grayscale/channel romedalen 'blue)
| null | https://raw.githubusercontent.com/wargrey/graphics/50751297f244a01ac734099b9a1e9be97cd36f3f/bitmap/tamer/grayscale.rkt | racket | #lang typed/racket/base
(require "../digitama/stdio.rkt")
(require "../effect.rkt")
(define romedalen (read-bitmap (collection-file-path "romedalen.png" "bitmap" "tamer" "cairo") #:backing-scale 2.0))
romedalen
(bitmap-grayscale/lightness romedalen)
(bitmap-grayscale/average romedalen)
(bitmap-grayscale/luminosity romedalen)
'decomposition
(bitmap-grayscale/decomposition romedalen 'max)
(bitmap-grayscale/decomposition romedalen 'min)
'channel
(bitmap-grayscale/channel romedalen 'red)
(bitmap-grayscale/channel romedalen 'green)
(collect-garbage)
(bitmap-grayscale/channel romedalen 'blue)
| |
84df03f19c1b6e7341ab606deb3e4dafc1b07c3633da4b44b1391c669ff98b5f | pfdietz/ansi-test | define-symbol-macro.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Apr 20 12:55:05 2003
;;;; Contains: Tests of DEFINE-SYMBOL-MACRO
(deftest define-symbol-macro.error.1
(signals-error (funcall (macro-function 'define-symbol-macro))
program-error)
t)
(deftest define-symbol-macro.error.2
(signals-error (funcall (macro-function 'define-symbol-macro)
'(define-symbol-macro
nonexistent-symbol-macro nil))
program-error)
t)
(deftest define-symbol-macro.error.3
(signals-error (funcall (macro-function 'define-symbol-macro)
'(define-symbol-macro
nonexistent-symbol-macro nil)
nil nil)
program-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/eval-and-compile/define-symbol-macro.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of DEFINE-SYMBOL-MACRO | Author :
Created : Sun Apr 20 12:55:05 2003
(deftest define-symbol-macro.error.1
(signals-error (funcall (macro-function 'define-symbol-macro))
program-error)
t)
(deftest define-symbol-macro.error.2
(signals-error (funcall (macro-function 'define-symbol-macro)
'(define-symbol-macro
nonexistent-symbol-macro nil))
program-error)
t)
(deftest define-symbol-macro.error.3
(signals-error (funcall (macro-function 'define-symbol-macro)
'(define-symbol-macro
nonexistent-symbol-macro nil)
nil nil)
program-error)
t)
|
207ecdcbfc3cbfaa6fd8bf1818e8e74eef552399ef87f0926e55baf7d5f53c1c | lispcast/clojurescript-test | core_test.cljs | (ns lab-notebook.core-test
(:require [cljs.test :refer-macros [async deftest is testing]]
[lab-notebook.core :refer [delete ajax-get]]))
(deftest delete-test
(is (= [] (delete [1] 0)))
(is (= [2] (delete [1 2] 0)))
(is (= [1 3] (delete [1 2 3] 1))))
(deftest ajax-get-test
(async done
(ajax-get "/"
(fn [response]
(is (= 200 (:status response)))
(done)))))
| null | https://raw.githubusercontent.com/lispcast/clojurescript-test/369c18df2f6f336f9bd37a67fb62406f0d63111b/cljs-test/lab_notebook/core_test.cljs | clojure | (ns lab-notebook.core-test
(:require [cljs.test :refer-macros [async deftest is testing]]
[lab-notebook.core :refer [delete ajax-get]]))
(deftest delete-test
(is (= [] (delete [1] 0)))
(is (= [2] (delete [1 2] 0)))
(is (= [1 3] (delete [1 2 3] 1))))
(deftest ajax-get-test
(async done
(ajax-get "/"
(fn [response]
(is (= 200 (:status response)))
(done)))))
| |
8b766ca1f44bfd4ab8ef93ce5b33bc48dc1b169082cd0a4114292016a3f119ad | marick/fp-oo | higher-order-functions-2.clj |
7
(def check-sum
(fn [sequence]
(apply + (map *
(range 1 (inc (count sequence)))
sequence))))
8
(def isbn?
(fn [candidate]
(zero? (rem (check-sum (reversed-digits candidate)) 11))))
| null | https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/solutions/pieces/higher-order-functions-2.clj | clojure |
7
(def check-sum
(fn [sequence]
(apply + (map *
(range 1 (inc (count sequence)))
sequence))))
8
(def isbn?
(fn [candidate]
(zero? (rem (check-sum (reversed-digits candidate)) 11))))
| |
ed5d03b0f862689f35facf5abd7650338d67c079a3b7f8b9a88050075d0248b9 | 6502/JSLisp | calc.lisp | (defobject binop (precedence associativity f))
(defun val (e x)
(cond
Formula
((list? x) (val e (aref e (first x)))) ; Unboxing
(true x)))
(macrolet ((bop (precedence associativity f)
`(symbol-macrolet ((vx (val e x))
(vy (val e y)))
(new-binop ,precedence ',associativity (lambda (x y) (lambda (e) ,f))))))
(defvar binops
#(("**" (bop 1 R (expt vx vy)))
("*" (bop 2 L (* vx vy)))
("/" (bop 2 L (/ vx vy)))
("%" (bop 2 L (% vx vy)))
("+" (bop 3 L (+ vx vy)))
("-" (bop 3 L (- vx vy)))
("<<" (bop 4 L (ash vx vy)))
(">>" (bop 4 L (ash vx (- vy))))
("&" (bop 5 L (logand vx vy)))
("|" (bop 5 L (logior vx vy)))
("^" (bop 5 L (logxor vx vy)))
("<" (bop 6 L (< vx vy)))
("<=" (bop 6 L (<= vx vy)))
(">" (bop 6 L (> vx vy)))
(">=" (bop 6 L (>= vx vy)))
("==" (bop 6 L (= vx vy)))
("!=" (bop 6 L (/= vx vy)))
("and" (bop 7 L (and vx vy)))
("or" (bop 8 L (or vx vy)))
("=" (bop 9 R (setf (aref e (first x)) vy)))
(":=" (bop 10 R (progn (setf (aref e (first x)) y) vy))))))
(defvar expr_level (apply #'max (map (lambda (k) (aref binops k).precedence)
(keys binops))))
(defvar number "[0-9]+(?:\\.[0-9]*)?(?:[Ee][-+]?[0-9]+)?")
(defvar string "\"(?:[^\"\\\\]|\\\\.)*\"")
(defvar var "[A-Za-z_][A-Za-z0-9_]*")
(defvar tkexpr (+ (join (map #'regexp-escape
(sort (keys binops)
(lambda (x y) (> (length x) (length y))))) "|")
~"|[()]\
|{number}\
|{string}\
|True|False\
|{var}\
|[^ ]"))
(defvar string_esc #(("n" "\n")
("t" "\t")
("f" "\f")
("v" "\v")))
(defun calc (e s)
(let** ((tk (s.match (regexp tkexpr "g")))
(i 0)
(#'expr (level)
(when (= i (length tk))
(error "Expression expected"))
(if (= level 0)
(case (aref tk (1- (incf i)))
("-" (let ((x (expr 1)))
(lambda (e) (- (val e x)))))
("True" true)
("False" false)
("(" (let ((x (expr expr_level)))
(unless (= (aref tk i) ")")
(error "')' expected"))
(incf i)
x))
(otherwise
(let ((x (aref tk (1- i))))
(cond
((x.match (regexp var)) (list x))
((= (first x) "\"") (replace (slice x 1 -1)
"\\\\."
(lambda (x)
(or (aref string_esc (second x))
(second x)))))
(true (atof x))))))
(let ((x (expr (1- level)))
(op (aref binops (aref tk i))))
(do () ((or (not op) (/= op.precedence level)) x)
(incf i)
(let ((y (expr (if (= op.associativity 'R) level (1- level)))))
(setf x (op.f x y))
(setf op (aref binops (aref tk i))))))))
(x (expr expr_level)))
(unless (= i (length tk))
(error "Extra tokens at end of expression"))
(val e x)))
(defun main ()
(let ((input (append-child document.body (create-element "input")))
(env #()))
(set-timeout (lambda () (input.focus)) 10)
(setf input.style.width "100%")
(setf input.onkeydown
(lambda (event)
(if (= event.which 13)
(progn
(event.preventDefault)
(event.stopPropagation)
(let ((cmd (append-child document.body (create-element "div"))))
(setf cmd.innerText input.value))
(let ((res (append-child document.body (create-element "div"))))
(setf res.style.color "#F00")
(setf res.innerText (+ "==> " (try
(calc env input.value)
*exception*))))
(append-child document.body input)
(setf input.value "")
(set-timeout (lambda () (input.focus)) 10)))))))
(main) | null | https://raw.githubusercontent.com/6502/JSLisp/9a4aa1a9116f0cfc598ec9f3f30b59d99810a728/examples/calc.lisp | lisp | Unboxing | (defobject binop (precedence associativity f))
(defun val (e x)
(cond
Formula
(true x)))
(macrolet ((bop (precedence associativity f)
`(symbol-macrolet ((vx (val e x))
(vy (val e y)))
(new-binop ,precedence ',associativity (lambda (x y) (lambda (e) ,f))))))
(defvar binops
#(("**" (bop 1 R (expt vx vy)))
("*" (bop 2 L (* vx vy)))
("/" (bop 2 L (/ vx vy)))
("%" (bop 2 L (% vx vy)))
("+" (bop 3 L (+ vx vy)))
("-" (bop 3 L (- vx vy)))
("<<" (bop 4 L (ash vx vy)))
(">>" (bop 4 L (ash vx (- vy))))
("&" (bop 5 L (logand vx vy)))
("|" (bop 5 L (logior vx vy)))
("^" (bop 5 L (logxor vx vy)))
("<" (bop 6 L (< vx vy)))
("<=" (bop 6 L (<= vx vy)))
(">" (bop 6 L (> vx vy)))
(">=" (bop 6 L (>= vx vy)))
("==" (bop 6 L (= vx vy)))
("!=" (bop 6 L (/= vx vy)))
("and" (bop 7 L (and vx vy)))
("or" (bop 8 L (or vx vy)))
("=" (bop 9 R (setf (aref e (first x)) vy)))
(":=" (bop 10 R (progn (setf (aref e (first x)) y) vy))))))
(defvar expr_level (apply #'max (map (lambda (k) (aref binops k).precedence)
(keys binops))))
(defvar number "[0-9]+(?:\\.[0-9]*)?(?:[Ee][-+]?[0-9]+)?")
(defvar string "\"(?:[^\"\\\\]|\\\\.)*\"")
(defvar var "[A-Za-z_][A-Za-z0-9_]*")
(defvar tkexpr (+ (join (map #'regexp-escape
(sort (keys binops)
(lambda (x y) (> (length x) (length y))))) "|")
~"|[()]\
|{number}\
|{string}\
|True|False\
|{var}\
|[^ ]"))
(defvar string_esc #(("n" "\n")
("t" "\t")
("f" "\f")
("v" "\v")))
(defun calc (e s)
(let** ((tk (s.match (regexp tkexpr "g")))
(i 0)
(#'expr (level)
(when (= i (length tk))
(error "Expression expected"))
(if (= level 0)
(case (aref tk (1- (incf i)))
("-" (let ((x (expr 1)))
(lambda (e) (- (val e x)))))
("True" true)
("False" false)
("(" (let ((x (expr expr_level)))
(unless (= (aref tk i) ")")
(error "')' expected"))
(incf i)
x))
(otherwise
(let ((x (aref tk (1- i))))
(cond
((x.match (regexp var)) (list x))
((= (first x) "\"") (replace (slice x 1 -1)
"\\\\."
(lambda (x)
(or (aref string_esc (second x))
(second x)))))
(true (atof x))))))
(let ((x (expr (1- level)))
(op (aref binops (aref tk i))))
(do () ((or (not op) (/= op.precedence level)) x)
(incf i)
(let ((y (expr (if (= op.associativity 'R) level (1- level)))))
(setf x (op.f x y))
(setf op (aref binops (aref tk i))))))))
(x (expr expr_level)))
(unless (= i (length tk))
(error "Extra tokens at end of expression"))
(val e x)))
(defun main ()
(let ((input (append-child document.body (create-element "input")))
(env #()))
(set-timeout (lambda () (input.focus)) 10)
(setf input.style.width "100%")
(setf input.onkeydown
(lambda (event)
(if (= event.which 13)
(progn
(event.preventDefault)
(event.stopPropagation)
(let ((cmd (append-child document.body (create-element "div"))))
(setf cmd.innerText input.value))
(let ((res (append-child document.body (create-element "div"))))
(setf res.style.color "#F00")
(setf res.innerText (+ "==> " (try
(calc env input.value)
*exception*))))
(append-child document.body input)
(setf input.value "")
(set-timeout (lambda () (input.focus)) 10)))))))
(main) |
fef278412b8458c628bf01a19257f5af9c72a24f84e4ab3c09f04b594209cafe | haskus/packages | Line.hs | module Haskus.Maths.Geometry.Line
( Line (..)
, linePointNearest
, linePointOn
)
where
import Linear.V2
import Linear.Affine
import Linear.Metric
-- | A line
data Line a
= Line !a !a -- y = ax+b
| VLine !a -- { (a,y) }
deriving (Show,Eq,Ord)
-- | Get the point of the line nearest to the given point
--
> > > linePointNearest ( VLine ( 2 : : Double ) ) ( P ( V2 5 5 ) )
P ( V2 2.0 5.0 )
--
> > > linePointNearest ( Line ( 2 : : Double ) 2 ) ( P ( V2 5 5 ) )
-- P (V2 2.2 6.4)
--
> > > let l = Line ( 2 : : Double ) 2
-- >>> linePointOn l (linePointNearest l (P (V2 5 5)))
-- True
linePointNearest :: (Fractional a, Num a) => Line a -> Point V2 a -> Point V2 a
linePointNearest (VLine xo) (P (V2 _x y)) = P (V2 xo y)
linePointNearest (Line a b) (P p) = P (o + (project k (p - o)))
where
o = V2 0 b
k = V2 1 a
-- | Test if a point is one the line
--
-- >>> linePointOn (Line 2.0 3.0) (P (V2 5 5))
-- False
--
-- >>> linePointOn (Line 2.0 3.0) (P (V2 2 7))
-- True
linePointOn :: (Num a, Eq a) => Line a -> Point V2 a -> Bool
linePointOn (VLine xo) (P (V2 x _y)) = xo == x
linePointOn (Line a b) (P (V2 x y)) = y == a*x+b
| null | https://raw.githubusercontent.com/haskus/packages/40ea6101cea84e2c1466bc55cdb22bed92f642a2/haskus-maths/src/lib/Haskus/Maths/Geometry/Line.hs | haskell | | A line
y = ax+b
{ (a,y) }
| Get the point of the line nearest to the given point
P (V2 2.2 6.4)
>>> linePointOn l (linePointNearest l (P (V2 5 5)))
True
| Test if a point is one the line
>>> linePointOn (Line 2.0 3.0) (P (V2 5 5))
False
>>> linePointOn (Line 2.0 3.0) (P (V2 2 7))
True | module Haskus.Maths.Geometry.Line
( Line (..)
, linePointNearest
, linePointOn
)
where
import Linear.V2
import Linear.Affine
import Linear.Metric
data Line a
deriving (Show,Eq,Ord)
> > > linePointNearest ( VLine ( 2 : : Double ) ) ( P ( V2 5 5 ) )
P ( V2 2.0 5.0 )
> > > linePointNearest ( Line ( 2 : : Double ) 2 ) ( P ( V2 5 5 ) )
> > > let l = Line ( 2 : : Double ) 2
linePointNearest :: (Fractional a, Num a) => Line a -> Point V2 a -> Point V2 a
linePointNearest (VLine xo) (P (V2 _x y)) = P (V2 xo y)
linePointNearest (Line a b) (P p) = P (o + (project k (p - o)))
where
o = V2 0 b
k = V2 1 a
linePointOn :: (Num a, Eq a) => Line a -> Point V2 a -> Bool
linePointOn (VLine xo) (P (V2 x _y)) = xo == x
linePointOn (Line a b) (P (V2 x y)) = y == a*x+b
|
e641b1a379bc549538b9f7f480a332612e29afa170626b59df694cd76ff96338 | dwayne/eopl3 | parser.test.rkt | #lang racket
(require "./parser.rkt")
(require rackunit)
(check-equal?
(parse "1")
(a-program (const-exp 1)))
(check-equal?
(parse "x")
(a-program (var-exp 'x)))
(check-equal?
(parse "-(5, y)")
(a-program (diff-exp (const-exp 5) (var-exp 'y))))
(check-equal?
(parse "zero?(z)")
(a-program (zero?-exp (var-exp 'z))))
(check-equal?
(parse "if zero?(2) then 0 else 1")
(a-program (if-exp (zero?-exp (const-exp 2))
(const-exp 0)
(const-exp 1))))
(check-equal?
(parse "let n=10 in -(n, 1)")
(a-program (let-exp 'n (const-exp 10) (diff-exp (var-exp 'n) (const-exp 1)))))
(check-equal?
(parse "minus(-(minus(5), 9))")
(a-program (minus-exp (diff-exp (minus-exp (const-exp 5))
(const-exp 9)))))
(check-equal?
(parse "add(6, 2)")
(a-program (add-exp (const-exp 6)
(const-exp 2))))
(check-equal?
(parse "mul(6, 2)")
(a-program (mul-exp (const-exp 6)
(const-exp 2))))
(check-equal?
(parse "div(6, 2)")
(a-program (div-exp (const-exp 6)
(const-exp 2))))
(check-equal?
(parse "equal?(1, 2)")
(a-program (equal?-exp (const-exp 1)
(const-exp 2))))
(check-equal?
(parse "greater?(1, 2)")
(a-program (greater?-exp (const-exp 1)
(const-exp 2))))
(check-equal?
(parse "less?(1, 2)")
(a-program (less?-exp (const-exp 1)
(const-exp 2))))
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/03-ch3/interpreters/racket/LET-3.8/parser.test.rkt | racket | #lang racket
(require "./parser.rkt")
(require rackunit)
(check-equal?
(parse "1")
(a-program (const-exp 1)))
(check-equal?
(parse "x")
(a-program (var-exp 'x)))
(check-equal?
(parse "-(5, y)")
(a-program (diff-exp (const-exp 5) (var-exp 'y))))
(check-equal?
(parse "zero?(z)")
(a-program (zero?-exp (var-exp 'z))))
(check-equal?
(parse "if zero?(2) then 0 else 1")
(a-program (if-exp (zero?-exp (const-exp 2))
(const-exp 0)
(const-exp 1))))
(check-equal?
(parse "let n=10 in -(n, 1)")
(a-program (let-exp 'n (const-exp 10) (diff-exp (var-exp 'n) (const-exp 1)))))
(check-equal?
(parse "minus(-(minus(5), 9))")
(a-program (minus-exp (diff-exp (minus-exp (const-exp 5))
(const-exp 9)))))
(check-equal?
(parse "add(6, 2)")
(a-program (add-exp (const-exp 6)
(const-exp 2))))
(check-equal?
(parse "mul(6, 2)")
(a-program (mul-exp (const-exp 6)
(const-exp 2))))
(check-equal?
(parse "div(6, 2)")
(a-program (div-exp (const-exp 6)
(const-exp 2))))
(check-equal?
(parse "equal?(1, 2)")
(a-program (equal?-exp (const-exp 1)
(const-exp 2))))
(check-equal?
(parse "greater?(1, 2)")
(a-program (greater?-exp (const-exp 1)
(const-exp 2))))
(check-equal?
(parse "less?(1, 2)")
(a-program (less?-exp (const-exp 1)
(const-exp 2))))
| |
001b5f624e7233becede996945c6374c0564890b26f9eaf02ad48e3960a03359 | racket/racket7 | list.rkt | #lang racket/base
(require "write-with-max.rkt"
"mode.rkt"
"graph.rkt")
(provide print-list)
(define (print-list p who v mode o max-length graph config alt-list-prefix alt-list-constructor)
(define unquoted-pairs?
(and (eq? mode PRINT-MODE/UNQUOTED)
(not alt-list-constructor)
(not (uninterrupted-list? v graph))))
(let ([max-length
(cond
[(eq? mode PRINT-MODE/UNQUOTED)
(let ([max-length
(if unquoted-pairs?
(write-string/max "(cons" o max-length)
(write-string/max (or alt-list-constructor "(list") o max-length))])
(cond
[(null? v) max-length]
[else (write-string/max " " o max-length)]))]
[else (write-string/max (or alt-list-prefix "(") o max-length)])])
(let loop ([v v] [max-length max-length])
(cond
[(eq? max-length 'full) 'full]
[(null? v) (write-string/max ")" o max-length)]
[(and (null? (cdr v))
(not unquoted-pairs?))
(let ([max-length (p who (car v) mode o max-length graph config)])
(write-string/max ")" o max-length))]
[(and (pair? (cdr v))
(or (not graph) (non-graph? (hash-ref graph (cdr v) #f)))
(not unquoted-pairs?))
(let ([max-length (p who (car v) mode o max-length graph config)])
(loop (cdr v) (write-string/max " " o max-length)))]
[else
(let* ([max-length (p who (car v) mode o max-length graph config)]
[max-length (if unquoted-pairs?
(write-string/max " " o max-length)
(write-string/max " . " o max-length))]
[max-length (p who (cdr v) mode o max-length graph config)])
(write-string/max ")" o max-length))]))))
(define (uninterrupted-list? v graph)
(and (list? v)
(let loop ([v v])
(cond
[(null? v) #t]
[(non-graph? (hash-ref graph v #f))
(loop (cdr v))]
[else #f]))))
(define (non-graph? g)
(or (not g)
(and (as-constructor? g)
(not (as-constructor-tag g)))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/io/print/list.rkt | racket | #lang racket/base
(require "write-with-max.rkt"
"mode.rkt"
"graph.rkt")
(provide print-list)
(define (print-list p who v mode o max-length graph config alt-list-prefix alt-list-constructor)
(define unquoted-pairs?
(and (eq? mode PRINT-MODE/UNQUOTED)
(not alt-list-constructor)
(not (uninterrupted-list? v graph))))
(let ([max-length
(cond
[(eq? mode PRINT-MODE/UNQUOTED)
(let ([max-length
(if unquoted-pairs?
(write-string/max "(cons" o max-length)
(write-string/max (or alt-list-constructor "(list") o max-length))])
(cond
[(null? v) max-length]
[else (write-string/max " " o max-length)]))]
[else (write-string/max (or alt-list-prefix "(") o max-length)])])
(let loop ([v v] [max-length max-length])
(cond
[(eq? max-length 'full) 'full]
[(null? v) (write-string/max ")" o max-length)]
[(and (null? (cdr v))
(not unquoted-pairs?))
(let ([max-length (p who (car v) mode o max-length graph config)])
(write-string/max ")" o max-length))]
[(and (pair? (cdr v))
(or (not graph) (non-graph? (hash-ref graph (cdr v) #f)))
(not unquoted-pairs?))
(let ([max-length (p who (car v) mode o max-length graph config)])
(loop (cdr v) (write-string/max " " o max-length)))]
[else
(let* ([max-length (p who (car v) mode o max-length graph config)]
[max-length (if unquoted-pairs?
(write-string/max " " o max-length)
(write-string/max " . " o max-length))]
[max-length (p who (cdr v) mode o max-length graph config)])
(write-string/max ")" o max-length))]))))
(define (uninterrupted-list? v graph)
(and (list? v)
(let loop ([v v])
(cond
[(null? v) #t]
[(non-graph? (hash-ref graph v #f))
(loop (cdr v))]
[else #f]))))
(define (non-graph? g)
(or (not g)
(and (as-constructor? g)
(not (as-constructor-tag g)))))
| |
4a3e713650c5886dc5dbc66a4b4e3762404d92688c998d09d959ad82133c16b9 | kazu-yamamoto/cab | Run.hs | # LANGUAGE CPP #
module Run (run, toSwitch) where
import Data.List (intercalate)
import Distribution.Cab
#if MIN_VERSION_process(1,2,0)
import System.Process (callCommand)
#else
import Control.Monad (void)
import System.Cmd (system)
#endif
import Types
----------------------------------------------------------------
toSwitch :: Option -> Switch
toSwitch OptNoharm = SwNoharm
toSwitch OptRecursive = SwRecursive
toSwitch OptAll = SwAll
toSwitch OptInfo = SwInfo
toSwitch (OptFlag _) = SwFlag
toSwitch OptTest = SwTest
toSwitch OptBench = SwBench
toSwitch OptDepsOnly = SwDepsOnly
toSwitch OptLibProfile = SwLibProfile
toSwitch OptExecProfile = SwExecProfile
toSwitch OptDebug = SwDebug
toSwitch (OptJobs _) = SwJobs
toSwitch (OptImport _) = SwImport
toSwitch OptStatic = SwStatic
toSwitch OptFuture = SwFuture
toSwitch OptAllowNewer = SwAllowNewer
toSwitch _ = error "toSwitch"
----------------------------------------------------------------
optionArg :: Option -> String
optionArg (OptFlag str) = str
optionArg (OptJobs str) = str
optionArg (OptImport str) = str
optionArg _ = ""
optionsToString :: [Option] -> SwitchDB -> [String]
optionsToString opts swdb = concatMap suboption opts
where
suboption opt = case lookup (toSwitch opt) swdb of
Nothing -> []
Just None -> []
Just (Solo x) -> [x]
Just (WithEqArg x) -> [x ++ "=" ++ optionArg opt]
Just (FollowArg x) -> [x ++ optionArg opt]
----------------------------------------------------------------
run :: CommandSpec -> [Arg] -> [Option] -> IO ()
run cmdspec params opts = case routing cmdspec of
RouteFunc func -> func params opts options
RouteCabal subargs -> callProcess pro subargs params options
where
pro = "cabal"
sws = switches cmdspec
options = optionsToString opts sws
callProcess :: String -> [String] -> [Arg] -> [String] -> IO ()
callProcess pro args0 args1 options = systemCommand script
where
#if MIN_VERSION_process(1,2,0)
systemCommand = callCommand
#else
systemCommand = void . system
#endif
script = intercalate " " $ pro : args0 ++ cat args1 ++ options
cat [pkg,ver] = [pkg ++ "-" ++ ver]
cat x = x
| null | https://raw.githubusercontent.com/kazu-yamamoto/cab/dd9e59877b08b476268000967340e86e72fbda45/src/Run.hs | haskell | --------------------------------------------------------------
--------------------------------------------------------------
-------------------------------------------------------------- | # LANGUAGE CPP #
module Run (run, toSwitch) where
import Data.List (intercalate)
import Distribution.Cab
#if MIN_VERSION_process(1,2,0)
import System.Process (callCommand)
#else
import Control.Monad (void)
import System.Cmd (system)
#endif
import Types
toSwitch :: Option -> Switch
toSwitch OptNoharm = SwNoharm
toSwitch OptRecursive = SwRecursive
toSwitch OptAll = SwAll
toSwitch OptInfo = SwInfo
toSwitch (OptFlag _) = SwFlag
toSwitch OptTest = SwTest
toSwitch OptBench = SwBench
toSwitch OptDepsOnly = SwDepsOnly
toSwitch OptLibProfile = SwLibProfile
toSwitch OptExecProfile = SwExecProfile
toSwitch OptDebug = SwDebug
toSwitch (OptJobs _) = SwJobs
toSwitch (OptImport _) = SwImport
toSwitch OptStatic = SwStatic
toSwitch OptFuture = SwFuture
toSwitch OptAllowNewer = SwAllowNewer
toSwitch _ = error "toSwitch"
optionArg :: Option -> String
optionArg (OptFlag str) = str
optionArg (OptJobs str) = str
optionArg (OptImport str) = str
optionArg _ = ""
optionsToString :: [Option] -> SwitchDB -> [String]
optionsToString opts swdb = concatMap suboption opts
where
suboption opt = case lookup (toSwitch opt) swdb of
Nothing -> []
Just None -> []
Just (Solo x) -> [x]
Just (WithEqArg x) -> [x ++ "=" ++ optionArg opt]
Just (FollowArg x) -> [x ++ optionArg opt]
run :: CommandSpec -> [Arg] -> [Option] -> IO ()
run cmdspec params opts = case routing cmdspec of
RouteFunc func -> func params opts options
RouteCabal subargs -> callProcess pro subargs params options
where
pro = "cabal"
sws = switches cmdspec
options = optionsToString opts sws
callProcess :: String -> [String] -> [Arg] -> [String] -> IO ()
callProcess pro args0 args1 options = systemCommand script
where
#if MIN_VERSION_process(1,2,0)
systemCommand = callCommand
#else
systemCommand = void . system
#endif
script = intercalate " " $ pro : args0 ++ cat args1 ++ options
cat [pkg,ver] = [pkg ++ "-" ++ ver]
cat x = x
|
0e12217c448670e85a405034084d4d720fca1ee1c8766c53846183d2a50b2303 | yesodweb/yesod | Reps.hs | # LANGUAGE OverloadedStrings , TemplateHaskell , QuasiQuotes , TypeFamilies , MultiParamTypeClasses , ViewPatterns #
module YesodCoreTest.Reps
( specs
, Widget
, resourcesApp
) where
import Yesod.Core
import Test.Hspec
import Network.Wai
import Network.Wai.Test
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Char8 as S8
import Data.String (IsString)
import Data.Text (Text)
import Data.Maybe (fromJust)
import Data.Monoid (Endo (..))
import qualified Control.Monad.Trans.Writer as Writer
import qualified Data.Set as Set
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET !home
/json JsonR GET
/parent/#Int ParentR:
/#Text/child ChildR !child
|]
instance Yesod App
specialHtml :: IsString a => a
specialHtml = "text/html; charset=special"
getHomeR :: Handler TypedContent
getHomeR = selectRep $ do
rep typeHtml "HTML"
rep specialHtml "HTMLSPECIAL"
rep typeXml "XML"
rep typeJson "JSON"
rep :: Monad m => ContentType -> Text -> Writer.Writer (Data.Monoid.Endo [ProvidedRep m]) ()
rep ct t = provideRepType ct $ return (t :: Text)
getJsonR :: Handler TypedContent
getJsonR = selectRep $ do
rep typeHtml "HTML"
provideRep $ return $ object ["message" .= ("Invalid Login" :: Text)]
handleChildR :: Int -> Text -> Handler ()
handleChildR _ _ = return ()
testRequest :: Int -- ^ http status code
-> Request
-> ByteString -- ^ expected body
-> Spec
testRequest status req expected = it (S8.unpack $ fromJust $ lookup "Accept" $ requestHeaders req) $ do
app <- toWaiApp App
flip runSession app $ do
sres <- request req
assertStatus status sres
assertBody expected sres
test :: String -- ^ accept header
-> ByteString -- ^ expected body
-> Spec
test accept expected =
testRequest 200 (acceptRequest accept) expected
acceptRequest :: String -> Request
acceptRequest accept = defaultRequest
{ requestHeaders = [("Accept", S8.pack accept)]
}
specs :: Spec
specs = do
describe "selectRep" $ do
test "application/json" "JSON"
test (S8.unpack typeJson) "JSON"
test "text/xml" "XML"
test (S8.unpack typeXml) "XML"
test "text/xml,application/json" "XML"
test "text/xml;q=0.9,application/json;q=1.0" "JSON"
test (S8.unpack typeHtml) "HTML"
test "text/html" "HTML"
test specialHtml "HTMLSPECIAL"
testRequest 200 (acceptRequest "application/json") { pathInfo = ["json"] } "{\"message\":\"Invalid Login\"}"
test "text/*" "HTML"
test "*/*" "HTML"
describe "routeAttrs" $ do
it "HomeR" $ routeAttrs HomeR `shouldBe` Set.singleton "home"
it "JsonR" $ routeAttrs JsonR `shouldBe` Set.empty
it "ChildR" $ routeAttrs (ParentR 5 $ ChildR "ignored") `shouldBe` Set.singleton "child"
| null | https://raw.githubusercontent.com/yesodweb/yesod/c59993ff287b880abbf768f1e3f56ae9b19df51e/yesod-core/test/YesodCoreTest/Reps.hs | haskell | ^ http status code
^ expected body
^ accept header
^ expected body | # LANGUAGE OverloadedStrings , TemplateHaskell , QuasiQuotes , TypeFamilies , MultiParamTypeClasses , ViewPatterns #
module YesodCoreTest.Reps
( specs
, Widget
, resourcesApp
) where
import Yesod.Core
import Test.Hspec
import Network.Wai
import Network.Wai.Test
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Char8 as S8
import Data.String (IsString)
import Data.Text (Text)
import Data.Maybe (fromJust)
import Data.Monoid (Endo (..))
import qualified Control.Monad.Trans.Writer as Writer
import qualified Data.Set as Set
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET !home
/json JsonR GET
/parent/#Int ParentR:
/#Text/child ChildR !child
|]
instance Yesod App
specialHtml :: IsString a => a
specialHtml = "text/html; charset=special"
getHomeR :: Handler TypedContent
getHomeR = selectRep $ do
rep typeHtml "HTML"
rep specialHtml "HTMLSPECIAL"
rep typeXml "XML"
rep typeJson "JSON"
rep :: Monad m => ContentType -> Text -> Writer.Writer (Data.Monoid.Endo [ProvidedRep m]) ()
rep ct t = provideRepType ct $ return (t :: Text)
getJsonR :: Handler TypedContent
getJsonR = selectRep $ do
rep typeHtml "HTML"
provideRep $ return $ object ["message" .= ("Invalid Login" :: Text)]
handleChildR :: Int -> Text -> Handler ()
handleChildR _ _ = return ()
-> Request
-> Spec
testRequest status req expected = it (S8.unpack $ fromJust $ lookup "Accept" $ requestHeaders req) $ do
app <- toWaiApp App
flip runSession app $ do
sres <- request req
assertStatus status sres
assertBody expected sres
-> Spec
test accept expected =
testRequest 200 (acceptRequest accept) expected
acceptRequest :: String -> Request
acceptRequest accept = defaultRequest
{ requestHeaders = [("Accept", S8.pack accept)]
}
specs :: Spec
specs = do
describe "selectRep" $ do
test "application/json" "JSON"
test (S8.unpack typeJson) "JSON"
test "text/xml" "XML"
test (S8.unpack typeXml) "XML"
test "text/xml,application/json" "XML"
test "text/xml;q=0.9,application/json;q=1.0" "JSON"
test (S8.unpack typeHtml) "HTML"
test "text/html" "HTML"
test specialHtml "HTMLSPECIAL"
testRequest 200 (acceptRequest "application/json") { pathInfo = ["json"] } "{\"message\":\"Invalid Login\"}"
test "text/*" "HTML"
test "*/*" "HTML"
describe "routeAttrs" $ do
it "HomeR" $ routeAttrs HomeR `shouldBe` Set.singleton "home"
it "JsonR" $ routeAttrs JsonR `shouldBe` Set.empty
it "ChildR" $ routeAttrs (ParentR 5 $ ChildR "ignored") `shouldBe` Set.singleton "child"
|
dce7c7498088bf38fc3e4e101f20dee6eb36ce0ca0aadfa7dee32bc9333d7a2f | rjnw/sham | pat-stx.rkt | #lang racket
(require racket/syntax
(for-template racket syntax/parse))
(require "reqs.rkt"
"pat.rkt")
(provide (all-defined-out))
(struct cmplr:pat:stx:var cmplr:pat:tvar []
#:methods gen:stx
[(define (->syntax sv)
(match-define (cmplr:pat:stx:var id orig-id type) sv)
(if type
#`(~var #,(to-syntax id) #,(to-syntax type))
(to-syntax id)))])
(struct cmplr:pat:stx:dat pat:dat []
#:methods gen:stx
[(define (->syntax sd)
(match-define (cmplr:pat:stx:dat d) sd)
#`(~datum #,d))])
(struct cmplr:pat:stx:op pat:app []
#:methods gen:stx
[(define (->syntax so)
(match-define (cmplr:pat:stx:op op rands) so)
#`(#,op #,@(seq->syntax rands)))])
(struct cmplr:pat:stx:seq cmplr:pat:seq [paren-shape]
#:methods gen:stx
[(define (->syntax sv)
(match-define (cmplr:pat:stx:seq ps shape) sv)
#`(#,@(seq->syntax ps)))])
(struct cmplr:pat:stx:vec cmplr:pat:stx:seq []
#:methods gen:stx
[(define (->syntax sv)
(match-define (cmplr:pat:stx:vec ps shape) sv)
#`#(#,@(seq->syntax ps)))])
( struct cmplr : dir : bind : : dir : bind [ ] )
(define (combine-binds-with-let dirs body)
(define bind-groups (group-by cmplr:dir:bind? dirs))
(define (do-let bg body)
(define (create-let-bind dir)
(match dir
[(cmplr:dir:bind var val)
#`[#,(to-syntax var) #,(to-syntax val)]]))
(define let-binds (map create-let-bind bg))
#`(let #,let-binds #,(to-syntax body)))
(for/fold ([body body])
([bg bind-groups])
(cond [(andmap cmplr:dir:bind? bg) (do-let bg body)]
[(andmap syntax? bg) #`(begin #,@bg #,(to-syntax body))]
[else (error 'sham/sam/transform "unknown directives: ~a" bg)])))
(define (combine-binds-with-syntax dirs body)
(define (create-with-bind dir)
(define (var-stxid var)
(match var
[(? identifier?) var]
[(cmplr-bind-var stxid depth)
(to-syntax (stx-cls-with-var stxid depth))]))
(match dir
[(cmplr:dir:bind var val)
#`(#,(var-stxid var) #,(to-syntax val))]))
(define with-binds (map create-with-bind dirs))
#`(with-syntax #,with-binds #,(to-syntax body)))
(struct cmplr:dir:stx [])
;; syntax-class directive ; #:with/#:when/#:attr ...
(struct cmplr:dir:stx:kwrd [kwrd vals]
#:methods gen:stx
[(define (->syntax scp)
(match-define (cmplr:dir:stx:kwrd kwrd vals) scp)
(cons (to-syntax kwrd) (to-syntax vals)))])
(struct cmplr:dir:stx:with cmplr:dir:stx [pat-stx val-stx]
#:methods gen:stx
[(define (->syntax pw)
(match-define (cmplr:dir:stx:with pat-stx val-stx) pw)
(list #'#:with (to-syntax pat-stx) (to-syntax val-stx)))])
(struct cmplr:dir:stx:attr [attr-stx val]
#:methods gen:stx
[(define (->syntax pa)
(match-define (cmplr:dir:stx:attr attr-stx val-stx) pa)
(list #'#:attr (to-syntax attr-stx) (to-syntax val-stx)))])
(struct cmplr:stx:class:pat [pat dirs]
#:methods gen:stx
[(define (->syntax cp)
(match-define (cmplr:stx:class:pat pat dirs) cp)
(seq->syntax #'pattern pat dirs))])
(struct cmplr:stx:class [id parts splicing?]
#:methods gen:stx
[(define (->syntax sc)
(match-define (cmplr:stx:class id parts splicing?) sc)
(define definer (if splicing? #`define-splicing-syntax-class #`define-syntax-class))
#`(#,definer #,(to-syntax id) #,@(map to-syntax parts)))])
(struct stx-cls-attr-val [var id]
#:methods gen:stx
[(define (->syntax sca)
(match-define (stx-cls-attr-val var attr) sca)
(define var-stx (to-syntax var))
(define attr-stx (and attr (to-syntax attr)))
(if attr-stx
#`(attribute #,(format-id var-stx "~a.~a" var-stx attr-stx))
#`(attribute #,var)))])
(struct stx-cls-with-var [id depth]
#:methods gen:stx
[(define (->syntax sv)
(match-define (stx-cls-with-var id depth) sv)
(let rec ([d depth])
(match d
[#f (to-syntax id)]
[(cons (cons mn mx) rst)
#`(#,(rec rst) (... ...))])))])
(define (internal-class-args-stx args)
(append-map (λ (arg) (list (->syntax-keyword arg) arg)) args))
| null | https://raw.githubusercontent.com/rjnw/sham/6e0524b1eb01bcda83ae7a5be6339da4257c6781/sham-sam/sham/sam/syntax/cmplr/pat-stx.rkt | racket | syntax-class directive ; #:with/#:when/#:attr ... | #lang racket
(require racket/syntax
(for-template racket syntax/parse))
(require "reqs.rkt"
"pat.rkt")
(provide (all-defined-out))
(struct cmplr:pat:stx:var cmplr:pat:tvar []
#:methods gen:stx
[(define (->syntax sv)
(match-define (cmplr:pat:stx:var id orig-id type) sv)
(if type
#`(~var #,(to-syntax id) #,(to-syntax type))
(to-syntax id)))])
(struct cmplr:pat:stx:dat pat:dat []
#:methods gen:stx
[(define (->syntax sd)
(match-define (cmplr:pat:stx:dat d) sd)
#`(~datum #,d))])
(struct cmplr:pat:stx:op pat:app []
#:methods gen:stx
[(define (->syntax so)
(match-define (cmplr:pat:stx:op op rands) so)
#`(#,op #,@(seq->syntax rands)))])
(struct cmplr:pat:stx:seq cmplr:pat:seq [paren-shape]
#:methods gen:stx
[(define (->syntax sv)
(match-define (cmplr:pat:stx:seq ps shape) sv)
#`(#,@(seq->syntax ps)))])
(struct cmplr:pat:stx:vec cmplr:pat:stx:seq []
#:methods gen:stx
[(define (->syntax sv)
(match-define (cmplr:pat:stx:vec ps shape) sv)
#`#(#,@(seq->syntax ps)))])
( struct cmplr : dir : bind : : dir : bind [ ] )
(define (combine-binds-with-let dirs body)
(define bind-groups (group-by cmplr:dir:bind? dirs))
(define (do-let bg body)
(define (create-let-bind dir)
(match dir
[(cmplr:dir:bind var val)
#`[#,(to-syntax var) #,(to-syntax val)]]))
(define let-binds (map create-let-bind bg))
#`(let #,let-binds #,(to-syntax body)))
(for/fold ([body body])
([bg bind-groups])
(cond [(andmap cmplr:dir:bind? bg) (do-let bg body)]
[(andmap syntax? bg) #`(begin #,@bg #,(to-syntax body))]
[else (error 'sham/sam/transform "unknown directives: ~a" bg)])))
(define (combine-binds-with-syntax dirs body)
(define (create-with-bind dir)
(define (var-stxid var)
(match var
[(? identifier?) var]
[(cmplr-bind-var stxid depth)
(to-syntax (stx-cls-with-var stxid depth))]))
(match dir
[(cmplr:dir:bind var val)
#`(#,(var-stxid var) #,(to-syntax val))]))
(define with-binds (map create-with-bind dirs))
#`(with-syntax #,with-binds #,(to-syntax body)))
(struct cmplr:dir:stx [])
(struct cmplr:dir:stx:kwrd [kwrd vals]
#:methods gen:stx
[(define (->syntax scp)
(match-define (cmplr:dir:stx:kwrd kwrd vals) scp)
(cons (to-syntax kwrd) (to-syntax vals)))])
(struct cmplr:dir:stx:with cmplr:dir:stx [pat-stx val-stx]
#:methods gen:stx
[(define (->syntax pw)
(match-define (cmplr:dir:stx:with pat-stx val-stx) pw)
(list #'#:with (to-syntax pat-stx) (to-syntax val-stx)))])
(struct cmplr:dir:stx:attr [attr-stx val]
#:methods gen:stx
[(define (->syntax pa)
(match-define (cmplr:dir:stx:attr attr-stx val-stx) pa)
(list #'#:attr (to-syntax attr-stx) (to-syntax val-stx)))])
(struct cmplr:stx:class:pat [pat dirs]
#:methods gen:stx
[(define (->syntax cp)
(match-define (cmplr:stx:class:pat pat dirs) cp)
(seq->syntax #'pattern pat dirs))])
(struct cmplr:stx:class [id parts splicing?]
#:methods gen:stx
[(define (->syntax sc)
(match-define (cmplr:stx:class id parts splicing?) sc)
(define definer (if splicing? #`define-splicing-syntax-class #`define-syntax-class))
#`(#,definer #,(to-syntax id) #,@(map to-syntax parts)))])
(struct stx-cls-attr-val [var id]
#:methods gen:stx
[(define (->syntax sca)
(match-define (stx-cls-attr-val var attr) sca)
(define var-stx (to-syntax var))
(define attr-stx (and attr (to-syntax attr)))
(if attr-stx
#`(attribute #,(format-id var-stx "~a.~a" var-stx attr-stx))
#`(attribute #,var)))])
(struct stx-cls-with-var [id depth]
#:methods gen:stx
[(define (->syntax sv)
(match-define (stx-cls-with-var id depth) sv)
(let rec ([d depth])
(match d
[#f (to-syntax id)]
[(cons (cons mn mx) rst)
#`(#,(rec rst) (... ...))])))])
(define (internal-class-args-stx args)
(append-map (λ (arg) (list (->syntax-keyword arg) arg)) args))
|
0294fb09feda5f6038cc13bc51fc96b10ec7df4606b344b334b435abd8e6e636 | dongcarl/guix | transformations.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2016 , 2017 , 2019 , 2020 , 2021 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU 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.
;;;
;;; GNU Guix 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 GNU . If not , see < / > .
(define-module (test-transformations)
#:use-module (guix tests)
#:use-module (guix store)
#:use-module ((guix gexp) #:select (lower-object))
#:use-module ((guix profiles)
#:select (package->manifest-entry
manifest-entry-properties))
#:use-module (guix derivations)
#:use-module (guix packages)
#:use-module (guix git-download)
#:use-module (guix build-system)
#:use-module (guix build-system gnu)
#:use-module (guix transformations)
#:use-module ((guix gexp) #:select (local-file? local-file-file))
#:use-module (guix ui)
#:use-module (guix utils)
#:use-module (guix git)
#:use-module (guix upstream)
#:use-module (gnu packages)
#:use-module (gnu packages base)
#:use-module (gnu packages busybox)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-64))
(test-begin "transformations")
(test-assert "options->transformation, no transformations"
(let ((p (dummy-package "foo"))
(t (options->transformation '())))
(eq? (t p) p)))
(test-assert "options->transformation, with-source"
;; Our pseudo-package is called 'guix.scm' so the 'guix.scm' source should
;; be applicable.
(let* ((p (dummy-package "guix.scm"))
(s (search-path %load-path "guix.scm"))
(t (options->transformation `((with-source . ,s)))))
(with-store store
(let* ((new (t p))
(source (run-with-store store
(lower-object (package-source new)))))
(and (not (eq? new p))
(string=? source
(add-to-store store "guix.scm" #t
"sha256" s)))))))
(test-assert "options->transformation, with-source, replacement"
;; Same, but this time the original package has a 'replacement' field. We
;; expect that replacement to be set to #f in the new package.
(let* ((p (dummy-package "guix.scm" (replacement coreutils)))
(s (search-path %load-path "guix.scm"))
(t (options->transformation `((with-source . ,s)))))
(let ((new (t p)))
(and (not (eq? new p))
(not (package-replacement new))))))
(test-assert "options->transformation, with-source, with version"
;; Our pseudo-package is called 'guix.scm' so the 'guix.scm-2.0' source
;; should be applicable, and its version should be extracted.
(let ((p (dummy-package "foo"))
(s (search-path %load-path "guix.scm")))
(call-with-temporary-directory
(lambda (directory)
(let* ((f (string-append directory "/foo-42.0.tar.gz"))
(t (options->transformation `((with-source . ,f)))))
(copy-file s f)
(with-store store
(let* ((new (t p))
(source (run-with-store store
(lower-object (package-source new)))))
(and (not (eq? new p))
(string=? (package-name new) (package-name p))
(string=? (package-version new) "42.0")
(string=? source
(add-to-store store (basename f) #t
"sha256" f))))))))))
(test-assert "options->transformation, with-source, no matches"
;; When a transformation in not applicable, a warning must be raised.
(let* ((p (dummy-package "foobar"))
(s (search-path %load-path "guix.scm"))
(t (options->transformation `((with-source . ,s)))))
(let* ((port (open-output-string))
(new (parameterize ((guix-warning-port port))
(t p))))
(and (eq? new p)
(string-contains (get-output-string port)
"had no effect")))))
(test-assert "options->transformation, with-source, PKG=URI"
(let* ((p (dummy-package "foo"))
(s (search-path %load-path "guix.scm"))
(f (string-append "foo=" s))
(t (options->transformation `((with-source . ,f)))))
(with-store store
(let* ((new (t p))
(source (run-with-store store
(lower-object (package-source new)))))
(and (not (eq? new p))
(string=? (package-name new) (package-name p))
(string=? (package-version new)
(package-version p))
(string=? source
(add-to-store store (basename s) #t
"sha256" s)))))))
(test-assert "options->transformation, with-source, PKG@VER=URI"
(let* ((p (dummy-package "foo"))
(s (search-path %load-path "guix.scm"))
(f (string-append "foo@42.0=" s))
(t (options->transformation `((with-source . ,f)))))
(with-store store
(let* ((new (t p))
(source (run-with-store store
(lower-object (package-source new)))))
(and (not (eq? new p))
(string=? (package-name new) (package-name p))
(string=? (package-version new) "42.0")
(string=? source
(add-to-store store (basename s) #t
"sha256" s)))))))
(test-assert "options->transformation, with-input"
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,(specification->package "coreutils"))
("bar" ,(specification->package "grep"))
("baz" ,(dummy-package "chbouib"
(native-inputs `(("x" ,grep)))))))))
(t (options->transformation '((with-input . "coreutils=busybox")
(with-input . "grep=findutils")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2) ("baz" dep3))
(and (string=? (package-full-name dep1)
(package-full-name busybox))
(string=? (package-full-name dep2)
(package-full-name findutils))
(string=? (package-name dep3) "chbouib")
(match (package-native-inputs dep3)
((("x" dep))
(string=? (package-full-name dep)
(package-full-name findutils)))))))))))
(test-assert "options->transformation, with-graft"
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(native-inputs `(("x" ,grep)))))))))
(t (options->transformation '((with-graft . "grep=findutils")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(string=? (package-full-name (package-replacement dep1))
(package-full-name findutils))
(string=? (package-name dep2) "chbouib")
(match (package-native-inputs dep2)
((("x" dep))
(with-store store
(string=? (derivation-file-name
(package-derivation store findutils))
(derivation-file-name
(package-derivation store dep)))))))))))))
(test-equal "options->transformation, with-branch"
(git-checkout (url "")
(branch "devel")
(recursive? #t))
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit "cabba9e")))
(sha256 #f)))))))))
(t (options->transformation '((with-branch . "chbouib=devel")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(string=? (package-name dep2) "chbouib")
(package-source dep2))))))))
(test-equal "options->transformation, with-commit"
(git-checkout (url "")
(commit "abcdef")
(recursive? #t))
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit "cabba9e")))
(sha256 #f)))))))))
(t (options->transformation '((with-commit . "chbouib=abcdef")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(string=? (package-name dep2) "chbouib")
(package-source dep2))))))))
(test-equal "options->transformation, with-git-url"
(let ((source (git-checkout (url "")
(recursive? #t))))
(list source source))
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(native-inputs `(("x" ,grep)))))))))
(t (options->transformation '((with-git-url . "grep=")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(string=? (package-name dep2) "chbouib")
(match (package-native-inputs dep2)
((("x" dep3))
(map package-source (list dep1 dep3)))))))))))
(test-equal "options->transformation, with-git-url + with-branch"
Combine the two options and make sure the ' with - branch ' transformation
;; comes after the 'with-git-url' transformation.
(let ((source (git-checkout (url "")
(branch "BRANCH")
(recursive? #t))))
(list source source))
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(native-inputs `(("x" ,grep)))))))))
(t (options->transformation
(reverse '((with-git-url
. "grep=")
(with-branch . "grep=BRANCH"))))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-name dep1) "grep")
(string=? (package-name dep2) "chbouib")
(match (package-native-inputs dep2)
((("x" dep3))
(map package-source (list dep1 dep3)))))))))))
(define* (depends-on-toolchain? p #:optional (toolchain "gcc-toolchain"))
"Return true if P depends on TOOLCHAIN instead of the default tool chain."
(define toolchain-packages
'("gcc" "binutils" "glibc" "ld-wrapper"))
(define (package-name* obj)
(and (package? obj) (package-name obj)))
(match (bag-build-inputs (package->bag p))
(((_ (= package-name* packages) . _) ...)
(and (not (any (cut member <> packages) toolchain-packages))
(member toolchain packages)))))
(test-assert "options->transformation, with-c-toolchain"
(let* ((dep0 (dummy-package "chbouib"
(build-system gnu-build-system)
(native-inputs `(("y" ,grep)))))
(dep1 (dummy-package "stuff"
(native-inputs `(("x" ,dep0)))))
(p (dummy-package "thingie"
(build-system gnu-build-system)
(inputs `(("foo" ,grep)
("bar" ,dep1)))))
(t (options->transformation
'((with-c-toolchain . "chbouib=gcc-toolchain")))))
Here we check that the transformation applies to DEP0 and all its
dependents : DEP0 must use GCC - TOOLCHAIN , DEP1 must use GCC - TOOLCHAIN
and the DEP0 that uses GCC - TOOLCHAIN , and so on .
(let ((new (t p)))
(and (depends-on-toolchain? new "gcc-toolchain")
(match (bag-build-inputs (package->bag new))
((("foo" dep0) ("bar" dep1) _ ...)
(and (depends-on-toolchain? dep1 "gcc-toolchain")
(not (depends-on-toolchain? dep0 "gcc-toolchain"))
(string=? (package-full-name dep0)
(package-full-name grep))
(match (bag-build-inputs (package->bag dep1))
((("x" dep) _ ...)
(and (depends-on-toolchain? dep "gcc-toolchain")
(match (bag-build-inputs (package->bag dep))
((("y" dep) _ ...) ;this one is unchanged
(eq? dep grep)))))))))))))
(test-equal "options->transformation, with-c-toolchain twice"
(package-full-name grep)
(let* ((dep0 (dummy-package "chbouib"))
(dep1 (dummy-package "stuff"))
(p (dummy-package "thingie"
(build-system gnu-build-system)
(inputs `(("foo" ,dep0)
("bar" ,dep1)
("baz" ,grep)))))
(t (options->transformation
'((with-c-toolchain . "chbouib=clang-toolchain")
(with-c-toolchain . "stuff=clang-toolchain")))))
(let ((new (t p)))
(and (depends-on-toolchain? new "clang-toolchain")
(match (bag-build-inputs (package->bag new))
((("foo" dep0) ("bar" dep1) ("baz" dep2) _ ...)
(and (depends-on-toolchain? dep0 "clang-toolchain")
(depends-on-toolchain? dep1 "clang-toolchain")
(not (depends-on-toolchain? dep2 "clang-toolchain"))
(package-full-name dep2))))))))
(test-assert "options->transformation, with-c-toolchain, no effect"
(let ((p (dummy-package "thingie"))
(t (options->transformation
'((with-c-toolchain . "does-not-exist=gcc-toolchain")))))
;; When it has no effect, '--with-c-toolchain' returns P.
(eq? (t p) p)))
(test-equal "options->transformation, with-debug-info"
'(#:strip-binaries? #f)
(let* ((dep (dummy-package "chbouib"))
(p (dummy-package "thingie"
(build-system gnu-build-system)
(inputs `(("foo" ,dep)
("bar" ,grep)))))
(t (options->transformation
'((with-debug-info . "chbouib")))))
(let ((new (t p)))
(match (package-inputs new)
((("foo" dep0) ("bar" dep1))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(package-arguments (package-replacement dep0))))))))
(test-assert "options->transformation, without-tests"
(let* ((dep (dummy-package "dep"))
(p (dummy-package "foo"
(inputs `(("dep" ,dep)))))
(t (options->transformation '((without-tests . "dep")
(without-tests . "tar")))))
(let ((new (t p)))
(match (bag-direct-inputs (package->bag new))
((("dep" dep) ("tar" tar) _ ...)
(and (equal? (package-arguments dep) '(#:tests? #f))
(match (memq #:tests? (package-arguments tar))
((#:tests? #f _ ...) #t))))))))
(test-equal "options->transformation, with-patch"
(search-patches "glibc-locales.patch" "guile-relocatable.patch")
(let* ((dep (dummy-package "dep"
(source (dummy-origin))))
(p (dummy-package "foo"
(inputs `(("dep" ,dep)))))
(patch1 (search-patch "glibc-locales.patch"))
(patch2 (search-patch "guile-relocatable.patch"))
(t (options->transformation
`((with-patch . ,(string-append "dep=" patch1))
(with-patch . ,(string-append "dep=" patch2))
(with-patch . ,(string-append "tar=" patch1))))))
(let ((new (t p)))
(match (bag-direct-inputs (package->bag new))
((("dep" dep) ("tar" tar) _ ...)
(and (member patch1
(filter-map (lambda (patch)
(and (local-file? patch)
(local-file-file patch)))
(origin-patches (package-source tar))))
(map local-file-file
(origin-patches (package-source dep)))))))))
(test-equal "options->transformation, with-latest"
"42.0"
(mock ((guix upstream) %updaters
(delay (list (upstream-updater
(name 'dummy)
(pred (const #t))
(description "")
(latest (const (upstream-source
(package "foo")
(version "42.0")
(urls '("")))))))))
(let* ((p (dummy-package "foo" (version "1.0")))
(t (options->transformation
`((with-latest . "foo")))))
(package-version (t p)))))
(test-equal "options->transformation + package->manifest-entry"
'((transformations . ((without-tests . "foo"))))
(let* ((p (dummy-package "foo"))
(t (options->transformation '((without-tests . "foo"))))
(e (package->manifest-entry (t p))))
(manifest-entry-properties e)))
(test-end)
;;; Local Variables:
eval : ( put ' dummy - package ' scheme - indent - function 1 )
;;; End:
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/tests/transformations.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix 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.
Our pseudo-package is called 'guix.scm' so the 'guix.scm' source should
be applicable.
Same, but this time the original package has a 'replacement' field. We
expect that replacement to be set to #f in the new package.
Our pseudo-package is called 'guix.scm' so the 'guix.scm-2.0' source
should be applicable, and its version should be extracted.
When a transformation in not applicable, a warning must be raised.
comes after the 'with-git-url' transformation.
this one is unchanged
When it has no effect, '--with-c-toolchain' returns P.
Local Variables:
End: | Copyright © 2016 , 2017 , 2019 , 2020 , 2021 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (test-transformations)
#:use-module (guix tests)
#:use-module (guix store)
#:use-module ((guix gexp) #:select (lower-object))
#:use-module ((guix profiles)
#:select (package->manifest-entry
manifest-entry-properties))
#:use-module (guix derivations)
#:use-module (guix packages)
#:use-module (guix git-download)
#:use-module (guix build-system)
#:use-module (guix build-system gnu)
#:use-module (guix transformations)
#:use-module ((guix gexp) #:select (local-file? local-file-file))
#:use-module (guix ui)
#:use-module (guix utils)
#:use-module (guix git)
#:use-module (guix upstream)
#:use-module (gnu packages)
#:use-module (gnu packages base)
#:use-module (gnu packages busybox)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-64))
(test-begin "transformations")
(test-assert "options->transformation, no transformations"
(let ((p (dummy-package "foo"))
(t (options->transformation '())))
(eq? (t p) p)))
(test-assert "options->transformation, with-source"
(let* ((p (dummy-package "guix.scm"))
(s (search-path %load-path "guix.scm"))
(t (options->transformation `((with-source . ,s)))))
(with-store store
(let* ((new (t p))
(source (run-with-store store
(lower-object (package-source new)))))
(and (not (eq? new p))
(string=? source
(add-to-store store "guix.scm" #t
"sha256" s)))))))
(test-assert "options->transformation, with-source, replacement"
(let* ((p (dummy-package "guix.scm" (replacement coreutils)))
(s (search-path %load-path "guix.scm"))
(t (options->transformation `((with-source . ,s)))))
(let ((new (t p)))
(and (not (eq? new p))
(not (package-replacement new))))))
(test-assert "options->transformation, with-source, with version"
(let ((p (dummy-package "foo"))
(s (search-path %load-path "guix.scm")))
(call-with-temporary-directory
(lambda (directory)
(let* ((f (string-append directory "/foo-42.0.tar.gz"))
(t (options->transformation `((with-source . ,f)))))
(copy-file s f)
(with-store store
(let* ((new (t p))
(source (run-with-store store
(lower-object (package-source new)))))
(and (not (eq? new p))
(string=? (package-name new) (package-name p))
(string=? (package-version new) "42.0")
(string=? source
(add-to-store store (basename f) #t
"sha256" f))))))))))
(test-assert "options->transformation, with-source, no matches"
(let* ((p (dummy-package "foobar"))
(s (search-path %load-path "guix.scm"))
(t (options->transformation `((with-source . ,s)))))
(let* ((port (open-output-string))
(new (parameterize ((guix-warning-port port))
(t p))))
(and (eq? new p)
(string-contains (get-output-string port)
"had no effect")))))
(test-assert "options->transformation, with-source, PKG=URI"
(let* ((p (dummy-package "foo"))
(s (search-path %load-path "guix.scm"))
(f (string-append "foo=" s))
(t (options->transformation `((with-source . ,f)))))
(with-store store
(let* ((new (t p))
(source (run-with-store store
(lower-object (package-source new)))))
(and (not (eq? new p))
(string=? (package-name new) (package-name p))
(string=? (package-version new)
(package-version p))
(string=? source
(add-to-store store (basename s) #t
"sha256" s)))))))
(test-assert "options->transformation, with-source, PKG@VER=URI"
(let* ((p (dummy-package "foo"))
(s (search-path %load-path "guix.scm"))
(f (string-append "foo@42.0=" s))
(t (options->transformation `((with-source . ,f)))))
(with-store store
(let* ((new (t p))
(source (run-with-store store
(lower-object (package-source new)))))
(and (not (eq? new p))
(string=? (package-name new) (package-name p))
(string=? (package-version new) "42.0")
(string=? source
(add-to-store store (basename s) #t
"sha256" s)))))))
(test-assert "options->transformation, with-input"
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,(specification->package "coreutils"))
("bar" ,(specification->package "grep"))
("baz" ,(dummy-package "chbouib"
(native-inputs `(("x" ,grep)))))))))
(t (options->transformation '((with-input . "coreutils=busybox")
(with-input . "grep=findutils")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2) ("baz" dep3))
(and (string=? (package-full-name dep1)
(package-full-name busybox))
(string=? (package-full-name dep2)
(package-full-name findutils))
(string=? (package-name dep3) "chbouib")
(match (package-native-inputs dep3)
((("x" dep))
(string=? (package-full-name dep)
(package-full-name findutils)))))))))))
(test-assert "options->transformation, with-graft"
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(native-inputs `(("x" ,grep)))))))))
(t (options->transformation '((with-graft . "grep=findutils")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(string=? (package-full-name (package-replacement dep1))
(package-full-name findutils))
(string=? (package-name dep2) "chbouib")
(match (package-native-inputs dep2)
((("x" dep))
(with-store store
(string=? (derivation-file-name
(package-derivation store findutils))
(derivation-file-name
(package-derivation store dep)))))))))))))
(test-equal "options->transformation, with-branch"
(git-checkout (url "")
(branch "devel")
(recursive? #t))
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit "cabba9e")))
(sha256 #f)))))))))
(t (options->transformation '((with-branch . "chbouib=devel")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(string=? (package-name dep2) "chbouib")
(package-source dep2))))))))
(test-equal "options->transformation, with-commit"
(git-checkout (url "")
(commit "abcdef")
(recursive? #t))
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit "cabba9e")))
(sha256 #f)))))))))
(t (options->transformation '((with-commit . "chbouib=abcdef")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(string=? (package-name dep2) "chbouib")
(package-source dep2))))))))
(test-equal "options->transformation, with-git-url"
(let ((source (git-checkout (url "")
(recursive? #t))))
(list source source))
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(native-inputs `(("x" ,grep)))))))))
(t (options->transformation '((with-git-url . "grep=")))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(string=? (package-name dep2) "chbouib")
(match (package-native-inputs dep2)
((("x" dep3))
(map package-source (list dep1 dep3)))))))))))
(test-equal "options->transformation, with-git-url + with-branch"
Combine the two options and make sure the ' with - branch ' transformation
(let ((source (git-checkout (url "")
(branch "BRANCH")
(recursive? #t))))
(list source source))
(let* ((p (dummy-package "guix.scm"
(inputs `(("foo" ,grep)
("bar" ,(dummy-package "chbouib"
(native-inputs `(("x" ,grep)))))))))
(t (options->transformation
(reverse '((with-git-url
. "grep=")
(with-branch . "grep=BRANCH"))))))
(let ((new (t p)))
(and (not (eq? new p))
(match (package-inputs new)
((("foo" dep1) ("bar" dep2))
(and (string=? (package-name dep1) "grep")
(string=? (package-name dep2) "chbouib")
(match (package-native-inputs dep2)
((("x" dep3))
(map package-source (list dep1 dep3)))))))))))
(define* (depends-on-toolchain? p #:optional (toolchain "gcc-toolchain"))
"Return true if P depends on TOOLCHAIN instead of the default tool chain."
(define toolchain-packages
'("gcc" "binutils" "glibc" "ld-wrapper"))
(define (package-name* obj)
(and (package? obj) (package-name obj)))
(match (bag-build-inputs (package->bag p))
(((_ (= package-name* packages) . _) ...)
(and (not (any (cut member <> packages) toolchain-packages))
(member toolchain packages)))))
(test-assert "options->transformation, with-c-toolchain"
(let* ((dep0 (dummy-package "chbouib"
(build-system gnu-build-system)
(native-inputs `(("y" ,grep)))))
(dep1 (dummy-package "stuff"
(native-inputs `(("x" ,dep0)))))
(p (dummy-package "thingie"
(build-system gnu-build-system)
(inputs `(("foo" ,grep)
("bar" ,dep1)))))
(t (options->transformation
'((with-c-toolchain . "chbouib=gcc-toolchain")))))
Here we check that the transformation applies to DEP0 and all its
dependents : DEP0 must use GCC - TOOLCHAIN , DEP1 must use GCC - TOOLCHAIN
and the DEP0 that uses GCC - TOOLCHAIN , and so on .
(let ((new (t p)))
(and (depends-on-toolchain? new "gcc-toolchain")
(match (bag-build-inputs (package->bag new))
((("foo" dep0) ("bar" dep1) _ ...)
(and (depends-on-toolchain? dep1 "gcc-toolchain")
(not (depends-on-toolchain? dep0 "gcc-toolchain"))
(string=? (package-full-name dep0)
(package-full-name grep))
(match (bag-build-inputs (package->bag dep1))
((("x" dep) _ ...)
(and (depends-on-toolchain? dep "gcc-toolchain")
(match (bag-build-inputs (package->bag dep))
(eq? dep grep)))))))))))))
(test-equal "options->transformation, with-c-toolchain twice"
(package-full-name grep)
(let* ((dep0 (dummy-package "chbouib"))
(dep1 (dummy-package "stuff"))
(p (dummy-package "thingie"
(build-system gnu-build-system)
(inputs `(("foo" ,dep0)
("bar" ,dep1)
("baz" ,grep)))))
(t (options->transformation
'((with-c-toolchain . "chbouib=clang-toolchain")
(with-c-toolchain . "stuff=clang-toolchain")))))
(let ((new (t p)))
(and (depends-on-toolchain? new "clang-toolchain")
(match (bag-build-inputs (package->bag new))
((("foo" dep0) ("bar" dep1) ("baz" dep2) _ ...)
(and (depends-on-toolchain? dep0 "clang-toolchain")
(depends-on-toolchain? dep1 "clang-toolchain")
(not (depends-on-toolchain? dep2 "clang-toolchain"))
(package-full-name dep2))))))))
(test-assert "options->transformation, with-c-toolchain, no effect"
(let ((p (dummy-package "thingie"))
(t (options->transformation
'((with-c-toolchain . "does-not-exist=gcc-toolchain")))))
(eq? (t p) p)))
(test-equal "options->transformation, with-debug-info"
'(#:strip-binaries? #f)
(let* ((dep (dummy-package "chbouib"))
(p (dummy-package "thingie"
(build-system gnu-build-system)
(inputs `(("foo" ,dep)
("bar" ,grep)))))
(t (options->transformation
'((with-debug-info . "chbouib")))))
(let ((new (t p)))
(match (package-inputs new)
((("foo" dep0) ("bar" dep1))
(and (string=? (package-full-name dep1)
(package-full-name grep))
(package-arguments (package-replacement dep0))))))))
(test-assert "options->transformation, without-tests"
(let* ((dep (dummy-package "dep"))
(p (dummy-package "foo"
(inputs `(("dep" ,dep)))))
(t (options->transformation '((without-tests . "dep")
(without-tests . "tar")))))
(let ((new (t p)))
(match (bag-direct-inputs (package->bag new))
((("dep" dep) ("tar" tar) _ ...)
(and (equal? (package-arguments dep) '(#:tests? #f))
(match (memq #:tests? (package-arguments tar))
((#:tests? #f _ ...) #t))))))))
(test-equal "options->transformation, with-patch"
(search-patches "glibc-locales.patch" "guile-relocatable.patch")
(let* ((dep (dummy-package "dep"
(source (dummy-origin))))
(p (dummy-package "foo"
(inputs `(("dep" ,dep)))))
(patch1 (search-patch "glibc-locales.patch"))
(patch2 (search-patch "guile-relocatable.patch"))
(t (options->transformation
`((with-patch . ,(string-append "dep=" patch1))
(with-patch . ,(string-append "dep=" patch2))
(with-patch . ,(string-append "tar=" patch1))))))
(let ((new (t p)))
(match (bag-direct-inputs (package->bag new))
((("dep" dep) ("tar" tar) _ ...)
(and (member patch1
(filter-map (lambda (patch)
(and (local-file? patch)
(local-file-file patch)))
(origin-patches (package-source tar))))
(map local-file-file
(origin-patches (package-source dep)))))))))
(test-equal "options->transformation, with-latest"
"42.0"
(mock ((guix upstream) %updaters
(delay (list (upstream-updater
(name 'dummy)
(pred (const #t))
(description "")
(latest (const (upstream-source
(package "foo")
(version "42.0")
(urls '("")))))))))
(let* ((p (dummy-package "foo" (version "1.0")))
(t (options->transformation
`((with-latest . "foo")))))
(package-version (t p)))))
(test-equal "options->transformation + package->manifest-entry"
'((transformations . ((without-tests . "foo"))))
(let* ((p (dummy-package "foo"))
(t (options->transformation '((without-tests . "foo"))))
(e (package->manifest-entry (t p))))
(manifest-entry-properties e)))
(test-end)
eval : ( put ' dummy - package ' scheme - indent - function 1 )
|
3efcbde922c38a0936b41841c51bbe72702dab3a5052e898985d92df3aa7c9cc | racket/typed-racket | typed-provide.rkt | #lang racket/base
;; Test providing a value to an untyped context
(module a typed/racket/base
(provide f)
(define (f (x : (Boxof (Boxof Integer))))
(unbox (unbox x))))
(module b racket/base
(provide bbx)
(define bbx (box 0)))
(module c typed/racket/base/optional
(require (submod ".." a))
(require/typed (submod ".." b) (bbx (Boxof (Boxof Integer))))
(provide do-c bbx)
(define (do-c)
(f bbx)))
(require 'a rackunit)
(check-exn #rx"f: contract violation"
(lambda () (f 0)))
(require 'c)
(check-not-exn (lambda () (unbox bbx)))
(check-exn #rx"f: contract violation"
do-c)
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/optional/typed-provide.rkt | racket | Test providing a value to an untyped context | #lang racket/base
(module a typed/racket/base
(provide f)
(define (f (x : (Boxof (Boxof Integer))))
(unbox (unbox x))))
(module b racket/base
(provide bbx)
(define bbx (box 0)))
(module c typed/racket/base/optional
(require (submod ".." a))
(require/typed (submod ".." b) (bbx (Boxof (Boxof Integer))))
(provide do-c bbx)
(define (do-c)
(f bbx)))
(require 'a rackunit)
(check-exn #rx"f: contract violation"
(lambda () (f 0)))
(require 'c)
(check-not-exn (lambda () (unbox bbx)))
(check-exn #rx"f: contract violation"
do-c)
|
0401cff2f678a65ae3379f91cb54de68b2fbba72d5fddbd92c616529f7accd52 | marick/fp-oo | pattern.clj | (use 'patterned.sweet)
(defpatterned count-sequence
[so-far [ ] ] so-far
[so-far [head & tail] ] (count-sequence (inc so-far) tail))
| null | https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/sources/pattern.clj | clojure | (use 'patterned.sweet)
(defpatterned count-sequence
[so-far [ ] ] so-far
[so-far [head & tail] ] (count-sequence (inc so-far) tail))
| |
1ee16ad75946eba89d222ca69c74b706e6bc04beeaab07b76e69e3dac571d910 | snoyberg/why-you-should-use-stm | exercise.hs | #!/usr/bin/env stack
-- stack --resolver lts-13.21 script
import Control.Applicative
import Control.Concurrent.Async
import Control.Concurrent.STM
import Data.Time
myThreadDelay :: Int -> IO ()
myThreadDelay micros = do
putStrLn "This isn't right..."
myTimeout :: Int -> IO a -> IO (Maybe a)
myTimeout micros action = do
putStrLn "Neither is this"
Just <$> action
main :: IO ()
main = do
putStrLn "myThreadDelay"
getCurrentTime >>= print
myThreadDelay 1000000
getCurrentTime >>= print
putStrLn "\nmyTimeout"
getCurrentTime >>= print
myTimeout 1000000 (myThreadDelay 5000000) >>= print
getCurrentTime >>= print
| null | https://raw.githubusercontent.com/snoyberg/why-you-should-use-stm/adf3366aebd6daf1dd702ed4cad1c2303d296afc/exercises/11-register-delay/exercise.hs | haskell | stack --resolver lts-13.21 script | #!/usr/bin/env stack
import Control.Applicative
import Control.Concurrent.Async
import Control.Concurrent.STM
import Data.Time
myThreadDelay :: Int -> IO ()
myThreadDelay micros = do
putStrLn "This isn't right..."
myTimeout :: Int -> IO a -> IO (Maybe a)
myTimeout micros action = do
putStrLn "Neither is this"
Just <$> action
main :: IO ()
main = do
putStrLn "myThreadDelay"
getCurrentTime >>= print
myThreadDelay 1000000
getCurrentTime >>= print
putStrLn "\nmyTimeout"
getCurrentTime >>= print
myTimeout 1000000 (myThreadDelay 5000000) >>= print
getCurrentTime >>= print
|
5573851b946bc0e1baf1332f9d34d8486ae8cae627d4dfcdf507b1f95b14f84c | bldl/magnolisp | test-names-2.rkt | #lang magnolisp/2014
(typedef int (#:annos foreign))
(function (equal? x y)
(#:annos (type (fn int int Bool)) foreign)
(begin-racket
(local-require (only-in racket/base equal?))
(equal? x y)))
(function (f x y) (#:annos export (type (fn int int Bool)))
(equal? x y))
(f 1 1)
(f 1 2)
| null | https://raw.githubusercontent.com/bldl/magnolisp/191d529486e688e5dda2be677ad8fe3b654e0d4f/tests/test-names-2.rkt | racket | #lang magnolisp/2014
(typedef int (#:annos foreign))
(function (equal? x y)
(#:annos (type (fn int int Bool)) foreign)
(begin-racket
(local-require (only-in racket/base equal?))
(equal? x y)))
(function (f x y) (#:annos export (type (fn int int Bool)))
(equal? x y))
(f 1 1)
(f 1 2)
| |
2c98e72dee9a46dd5a276909492e0bb3d5e018c1373c39ee0f81ea6b047cc154 | metabase/metabase | user.clj | (ns metabase-enterprise.audit-app.api.user
"`/api/ee/audit-app/user` endpoints. These only work if you have a premium token with the `:audit-app` feature."
(:require
[compojure.core :refer [DELETE]]
[metabase.api.common :as api]
[metabase.api.user :as api.user]
[metabase.models.pulse :refer [Pulse]]
[metabase.models.pulse-channel-recipient :refer [PulseChannelRecipient]]
[toucan.db :as db]))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema DELETE "/:id/subscriptions"
"Delete all Alert and DashboardSubscription subscriptions for a User (i.e., so they will no longer receive them).
Archive all Alerts and DashboardSubscriptions created by the User. Only allowed for admins or for the current user."
[id]
(api.user/check-self-or-superuser id)
delete all ` PulseChannelRecipient ` rows for this User , which means they will no longer receive any
;; Alerts/DashboardSubscriptions
(db/delete! PulseChannelRecipient :user_id id)
;; archive anything they created.
(db/update-where! Pulse {:creator_id id, :archived false} :archived true)
api/generic-204-no-content)
(api/define-routes)
| null | https://raw.githubusercontent.com/metabase/metabase/6d7f778ef68761b9af943d07ed868d9d0f67f64a/enterprise/backend/src/metabase_enterprise/audit_app/api/user.clj | clojure | Alerts/DashboardSubscriptions
archive anything they created. | (ns metabase-enterprise.audit-app.api.user
"`/api/ee/audit-app/user` endpoints. These only work if you have a premium token with the `:audit-app` feature."
(:require
[compojure.core :refer [DELETE]]
[metabase.api.common :as api]
[metabase.api.user :as api.user]
[metabase.models.pulse :refer [Pulse]]
[metabase.models.pulse-channel-recipient :refer [PulseChannelRecipient]]
[toucan.db :as db]))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema DELETE "/:id/subscriptions"
"Delete all Alert and DashboardSubscription subscriptions for a User (i.e., so they will no longer receive them).
Archive all Alerts and DashboardSubscriptions created by the User. Only allowed for admins or for the current user."
[id]
(api.user/check-self-or-superuser id)
delete all ` PulseChannelRecipient ` rows for this User , which means they will no longer receive any
(db/delete! PulseChannelRecipient :user_id id)
(db/update-where! Pulse {:creator_id id, :archived false} :archived true)
api/generic-204-no-content)
(api/define-routes)
|
ca88bbcf31f6fe2038b92beb35f7a539b6596ee9861a96ae0b6e1a834d309de2 | input-output-hk/plutus | RelativizedMap.hs | -- editorconfig-checker-disable-file
{-# LANGUAGE TypeFamilies #-}
# LANGUAGE UndecidableInstances #
module Data.RandomAccessList.RelativizedMap (RelativizedMap (..))where
import Data.Word
import Data.RandomAccessList.Class qualified as RAL
import Data.IntMap.Strict qualified as IM
import GHC.Exts (IsList)
-- | A sequence implemented by a map from "levels" to values and a counter giving the "current" level.
data RelativizedMap a = RelativizedMap (IM.IntMap a) {-# UNPACK #-} !Word64
deriving stock (Show, Eq)
deriving (IsList) via RAL.AsRAL (RelativizedMap a)
instance RAL.RandomAccessList (RelativizedMap a) where
type Element (RelativizedMap a) = a
# INLINABLE empty #
empty = RelativizedMap mempty 0
# INLINABLE cons #
cons a (RelativizedMap im l) = RelativizedMap (IM.insert (fromIntegral l) a im) (l+1)
# INLINABLE uncons #
uncons (RelativizedMap _ 0) = Nothing
uncons (RelativizedMap im l) = case IM.maxViewWithKey im of
Nothing -> Nothing
Just ((_, a), res) -> Just (a, RelativizedMap res (l-1))
# INLINABLE length #
length (RelativizedMap _ l) = l
# INLINABLE indexZero #
indexZero (RelativizedMap _ 0) _ = Nothing
indexZero (RelativizedMap im l) w = let maxIndex = l-1 in if w > maxIndex then Nothing else IM.lookup (fromIntegral maxIndex - fromIntegral w) im
| null | https://raw.githubusercontent.com/input-output-hk/plutus/c8d4364d0e639fef4d5b93f7d6c0912d992b54f9/plutus-core/index-envs/src/Data/RandomAccessList/RelativizedMap.hs | haskell | editorconfig-checker-disable-file
# LANGUAGE TypeFamilies #
| A sequence implemented by a map from "levels" to values and a counter giving the "current" level.
# UNPACK # | # LANGUAGE UndecidableInstances #
module Data.RandomAccessList.RelativizedMap (RelativizedMap (..))where
import Data.Word
import Data.RandomAccessList.Class qualified as RAL
import Data.IntMap.Strict qualified as IM
import GHC.Exts (IsList)
deriving stock (Show, Eq)
deriving (IsList) via RAL.AsRAL (RelativizedMap a)
instance RAL.RandomAccessList (RelativizedMap a) where
type Element (RelativizedMap a) = a
# INLINABLE empty #
empty = RelativizedMap mempty 0
# INLINABLE cons #
cons a (RelativizedMap im l) = RelativizedMap (IM.insert (fromIntegral l) a im) (l+1)
# INLINABLE uncons #
uncons (RelativizedMap _ 0) = Nothing
uncons (RelativizedMap im l) = case IM.maxViewWithKey im of
Nothing -> Nothing
Just ((_, a), res) -> Just (a, RelativizedMap res (l-1))
# INLINABLE length #
length (RelativizedMap _ l) = l
# INLINABLE indexZero #
indexZero (RelativizedMap _ 0) _ = Nothing
indexZero (RelativizedMap im l) w = let maxIndex = l-1 in if w > maxIndex then Nothing else IM.lookup (fromIntegral maxIndex - fromIntegral w) im
|
de49923242ebebade02b1490d6c3b975b26e4a1537096a417d1165266b2a1189 | craigl64/clim-ccl | lucid-stream-functions.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Package : CLIM - UTILS ; Base : 10 ; Lowercase : Yes -*-
(in-package :clim-utils)
"Copyright (c) 1990, 1991, 1992 Symbolics, Inc. All rights reserved.
Portions copyright (c) 1989, 1990 International Lisp Associates."
;;; All of this is taken from the STREAM-DEFINITION-BY-USER proposal to
the X3J13 committee , made by of TI on 22 March 1989 . No
;;; Lisp implementation yet supports this proposal, so we implement it
;;; here in this separate package. This way we will be ready when some
;;; Lisp implementation adopts it (or something like it).
;;; just for development
#+ignore
(eval-when (compile load eval)
(defparameter sym-list '("PEEK-CHAR" "READ-BYTE" "READ-CHAR" "UNREAD-CHAR"
"READ-CHAR-NO-HANG" "LISTEN" "READ-LINE"
"CLEAR-INPUT" "WRITE-BYTE" "WRITE-CHAR"
"WRITE-STRING" "TERPRI" "FRESH-LINE" "FORCE-OUTPUT"
"FINISH-OUTPUT" "CLEAR-OUTPUT" ))
(dolist (sym sym-list)
(unintern (find-symbol sym :clim-lisp) :clim-lisp)
(unintern (find-symbol sym :clim) :clim)))
;;; Output functions
(defmacro write-forwarding-lucid-output-stream-function (name args)
(let* ((cl-name (find-symbol (symbol-name name) (find-package 'lisp)))
(method-name (intern (lisp:format nil "~A-~A" 'stream (symbol-name name))))
(optional-args (or (member '&optional args) (member '&key args)))
(required-args (ldiff args optional-args))
(optional-parameters (mapcan #'(lambda (arg)
(cond ((member arg lambda-list-keywords) nil)
((atom arg) (list arg))
(t (list (car arg)))))
optional-args))
(pass-args (append required-args optional-parameters))
;; optional-args are &optional in the method,
;; even if &key in the Common Lisp function
(method-args (if (eq (first optional-args) '&key)
(append required-args '(&optional) (cdr optional-args))
args))
(pass-keys (if (eq (first optional-args) '&key)
(mapcan #'(lambda (arg)
(unless (atom arg)
(setq arg (car arg)))
(list (intern (string arg) :keyword) arg))
(cdr optional-args))
optional-parameters))
)
(when (eq (first optional-args) '&optional)
(pop optional-args))
`(let ((orig-lucid-closure (or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
;;(proclaim '(inline ,name))
(defun ,name (,@required-args &optional stream ,@optional-args)
(cond ((null stream) (setq stream *standard-output*))
((eq stream t) (setq stream *terminal-io*)))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(,method-name stream ,@pass-args)
(funcall orig-lucid-closure ,@required-args stream ,@pass-keys)))
;; Define a default method for the generic function that calls back to the
;; system stream implementation. Call back via a message if there is one,
;; otherwise via the Common Lisp function.
;; Uses T as a parameter specializer name as a standin for cl:stream,
which does n't support as a builtin class
(defmethod ,method-name ((stream t) ,@method-args)
(,cl-name ,@required-args stream ,@pass-keys))
( import ' , name : clim - lisp )
( export ' , name : clim - lisp )
)))
(write-forwarding-lucid-output-stream-function lisp:write-byte (integer))
(write-forwarding-lucid-output-stream-function lisp:write-char (character))
(write-forwarding-lucid-output-stream-function lisp:write-string (string &key (start 0) end))
(write-forwarding-lucid-output-stream-function lisp:terpri ())
(write-forwarding-lucid-output-stream-function lisp:fresh-line ())
(write-forwarding-lucid-output-stream-function lisp:force-output ())
(write-forwarding-lucid-output-stream-function lisp:finish-output ())
(write-forwarding-lucid-output-stream-function lisp:clear-output ())
;;; Input functions
(defmacro write-forwarding-lucid-input-stream-function (name lambda-list
&key eof
additional-arguments)
(let* ((cl-name (find-symbol (symbol-name name) (find-package 'lisp)))
(method-name (intern (lisp:format nil "~A-~A" 'stream (symbol-name name))))
(method-lambda-list (set-difference lambda-list '(stream peek-type)))
(args (mapcar #'(lambda (var) (if (atom var) var (first var)))
(remove-if #'(lambda (x) (member x lambda-list-keywords))
lambda-list)))
(method-calling-args (set-difference args '(stream peek-type)))
(cleanup `(cond ((null stream) (setq stream *standard-input*))
((eq stream t) (setq stream *terminal-io*))))
(call-method `(,method-name stream ,@method-calling-args))
(calling-lambda-list (remove '&optional lambda-list)))
(when (member (first (last method-lambda-list)) lambda-list-keywords)
(setf method-lambda-list (butlast method-lambda-list)))
`(let ((orig-lucid-closure
(or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
;;(proclaim '(inline ,name))
,(if eof
(let ((args `(eof-error-p eof-value ,@(and (not (eq eof :no-recursive))
'(recursive-p)))))
`(defun ,name (,@lambda-list ,@args)
,cleanup
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(let ((result ,call-method))
(cond ((not (eq result *end-of-file-marker*))
result)
(eof-error-p
(signal-stream-eof stream ,@(and (not (eq eof :no-recursive))
'(recursive-p))))
(t
eof-value)))
(funcall orig-lucid-closure ,@calling-lambda-list ,@args))))
`(defun ,name ,lambda-list
,cleanup
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
,call-method
(funcall orig-lucid-closure ,@calling-lambda-list))))
;; Define a default method for the generic function that calls back to the
;; system stream implementation. Call back via a message if there is one,
;; otherwise via the Common Lisp function.
(defmethod ,method-name ((stream t) ,@method-lambda-list)
(,cl-name ,@additional-arguments ,@(remove 'peek-type args)
,@(when eof `(nil *end-of-file-marker*))))
( import ' , name : clim - lisp )
( export ' , name : clim - lisp )
)))
(write-forwarding-lucid-input-stream-function lisp:peek-char (&optional peek-type stream)
:eof t
:additional-arguments (nil))
(write-forwarding-lucid-input-stream-function lisp:read-byte (&optional stream)
:eof :no-recursive)
(write-forwarding-lucid-input-stream-function lisp:read-char (&optional stream) :eof t)
(write-forwarding-lucid-input-stream-function lisp:unread-char (character
&optional stream))
(write-forwarding-lucid-input-stream-function lisp:read-char-no-hang (&optional stream)
:eof t)
(write-forwarding-lucid-input-stream-function lisp:listen (&optional stream))
(write-forwarding-lucid-input-stream-function lisp:read-line (&optional stream) :eof t)
(write-forwarding-lucid-input-stream-function lisp:clear-input (&optional stream))
(defun signal-stream-eof (stream &optional recursive-p)
(declare (ignore recursive-p))
(error 'end-of-file :stream stream))
Make CLIM - LISP : FORMAT do something useful on CLIM windows .
#||
(defun format (stream format-control &rest format-args)
(when (null stream)
(return-from format
(apply #'lisp:format nil format-control format-args)))
(when (eq stream 't)
(setq stream *standard-output*))
(cond ((streamp stream)
;; this isn't going to quite work for ~&,
;; but it's better than nothing.
(write-string (apply #'lisp:format nil format-control format-args) stream)
nil)
(t
(apply #'lisp:format stream format-control format-args))))
||#
;;; Higher level lisp printing functions.
(eval-when (load)
(let ((original-lucid-closure
(or (getf (symbol-plist 'lisp:format) :original-lucid-closure)
(setf (getf (symbol-plist 'lisp:format) :original-lucid-closure)
(symbol-function 'lisp:format)))))
(defun format (stream format-control &rest format-args)
(when (eq stream 't)
(setq stream *standard-output*))
(cond ((null stream)
(apply original-lucid-closure nil format-control format-args))
clim stream
((and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(write-string (apply original-lucid-closure nil format-control format-args)
stream))
Lucid stream
(t
(apply original-lucid-closure stream format-control format-args))))))
Support for the IO functions with more varied argument templates and no
;;; Grey stream equivalent. Assumes there is an argument called "STREAM".
(defmacro redefine-lucid-io-function (name lambda-list &body clim-body)
(let ((args (mapcar #'(lambda (var) (if (atom var) var (first var)))
(remove-if #'(lambda (x) (member x lambda-list-keywords))
lambda-list))))
`(let ((orig-lucid-closure
(or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
(defun ,name ,lambda-list
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
,@clim-body
(funcall orig-lucid-closure ,@args))))))
(defmacro %string-stream (stream &body body)
`(let (result
(new-stream (cond ((encapsulating-stream-p ,stream)
(encapsulating-stream-stream ,stream))
((typep ,stream 'fundamental-stream)
,stream)
(t
(let ((*standard-output* *terminal-io*))
(error "Unknown stream type, ~S" ,stream))))))
(write-string
;; execute the body using the STREAM locally rebound
;; to an output stream object for I/O purposes:
(let ((,stream (make-string-output-stream)))
;; stream I/O stuff goes here
(setq result ,@body )
;; return the accumulated output string:
(get-output-stream-string ,stream))
;; use original output stream here ....
new-stream)
result))
(redefine-lucid-io-function lisp:streamp (stream) t)
(redefine-lucid-io-function lcl:underlying-stream (stream &optional direction
(recurse t)
exact-same)
(if (encapsulating-stream-p stream)
(encapsulating-stream-stream stream)
stream))
(redefine-lucid-io-function lisp:prin1 (object &optional (stream *standard-output*))
(%string-stream stream (lisp:prin1 object stream)))
(redefine-lucid-io-function lisp:print (object &optional (stream *standard-output*))
(%string-stream stream (lisp:print object stream)))
(redefine-lucid-io-function lisp:princ (object &optional (stream *standard-output*))
(%string-stream stream (lisp:princ object stream)))
(redefine-lucid-io-function lisp:pprint (object &optional (stream *standard-output*))
(%string-stream stream (lisp:pprint object stream)))
(redefine-lucid-io-function lisp:write-line (string &optional (stream *standard-output*)
&key (start 0) end)
(%string-stream stream (lisp:write-line string stream :start start :end end)))
;;; Easier to write this one out.
;;;
(let ((orig-lucid-closure (symbol-function 'lisp:write)))
(defun lisp:write (object
&key
((:stream stream) *standard-output*)
((:escape escapep) *print-escape*)
((:radix *print-radix*) *print-radix*)
((:base new-print-base) *print-base* print-base-p)
((:circle *print-circle*) *print-circle*)
((:pretty *print-pretty*) *print-pretty*)
((:level *print-level*) *print-level*)
((:length *print-length*) *print-length*)
((:case new-print-case) *print-case* print-case-p)
((:array *print-array*) *print-array*)
((:gensym *print-gensym*) *print-gensym*)
((:structure lcl:*print-structure*) lcl:*print-structure*))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(%string-stream stream (lisp:write object :stream stream
:escape escapep
:radix *print-radix*
:base new-print-base :circle *print-circle*
:pretty *print-pretty*
:level *print-level* :length *print-length*
:case new-print-case
:array *print-array* :gensym *print-gensym*
:structure lcl:*print-structure*))
(funcall orig-lucid-closure object :stream stream :escape escapep
:radix *print-radix*
:base new-print-base :circle *print-circle* :pretty *print-pretty*
:level *print-level* :length *print-length* :case new-print-case
:array *print-array* :gensym *print-gensym*
:structure lcl:*print-structure*))))
;;; Higher level lisp reading functions.
;; this hack is necessary in order to allow (ACCEPT 'T ...) and
;; (ACCEPT 'EXPRESSION ...) to function (sort of) correctly ....
(defmethod make-instance ((t-class (eql (find-class t))) &rest args)
(declare (ignore args) (dynamic-extent args))
t)
(redefine-lucid-io-function lisp:read (&optional (stream *standard-input*)
(eof-error-p t)
(eof-value nil)
(recursive-p nil))
;; ACCEPT is only a rough equivalent of READ
(clim:accept 'clim:expression :stream stream))
;;; Don't forget about this guys even if we don't implement them.
;; READ-PRESERVING-WHITESPACE (&OPTIONAL (STREAM *STANDARD-INPUT*)
;; (EOF-ERROR-P T)
( EOF - VALUE NIL )
( RECURSIVE - P NIL ) )
READ - DELIMITED - LIST ( CHAR & OPTIONAL ( STREAM * STANDARD - INPUT * ) ( RECURSIVE - P NIL ) )
;;; User Query Functions (interacts with the *QUERY-IO* stream):
;;; Y-OR-N-P (&OPTIONAL FORMAT-STRING &REST FORMAT-ARGS)
NOTE : the built - in presentation type CLIM : BOOLEAN requires YES or NO -- not
Y or P -- as would normally be expected from Y - OR - N - P.
(lcl:defadvice (lisp:y-or-n-p stream-wrapper) (&optional format-string &rest args)
(declare (dynamic-extent args))
(if (and (system:standard-object-p *query-io*)
(typep *query-io* 'fundamental-stream))
(clim:accept 'clim:boolean :prompt (apply #'lisp::format nil format-string
args))
(lcl:apply-advice-continue format-string args)))
;;; YES-OR-NO-P (&OPTIONAL FORMAT-STRING &REST FORMAT-ARGS)
;;;
(lcl:defadvice (lisp:yes-or-no-p stream-wrapper) (&optional format-string &rest args)
(declare (dynamic-extent args))
(if (and (system:standard-object-p *query-io*)
(typep *query-io* 'fundamental-stream))
(clim:accept 'clim:boolean :prompt (apply #'lisp:format nil format-string
args))
(lcl:apply-advice-continue format-string args)))
#+nope
(lcl:defadvice (lisp:format stream-wrapper) (stream control-string &rest args)
(let ((stream (if (eq stream t) *standard-output* stream)))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(apply #'clim:format stream control-string args)
(lcl:apply-advice-continue stream control-string args))))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/utils/lucid-stream-functions.lisp | lisp | Syntax : ANSI - Common - Lisp ; Package : CLIM - UTILS ; Base : 10 ; Lowercase : Yes -*-
All of this is taken from the STREAM-DEFINITION-BY-USER proposal to
Lisp implementation yet supports this proposal, so we implement it
here in this separate package. This way we will be ready when some
Lisp implementation adopts it (or something like it).
just for development
Output functions
optional-args are &optional in the method,
even if &key in the Common Lisp function
(proclaim '(inline ,name))
Define a default method for the generic function that calls back to the
system stream implementation. Call back via a message if there is one,
otherwise via the Common Lisp function.
Uses T as a parameter specializer name as a standin for cl:stream,
Input functions
(proclaim '(inline ,name))
Define a default method for the generic function that calls back to the
system stream implementation. Call back via a message if there is one,
otherwise via the Common Lisp function.
(defun format (stream format-control &rest format-args)
(when (null stream)
(return-from format
(apply #'lisp:format nil format-control format-args)))
(when (eq stream 't)
(setq stream *standard-output*))
(cond ((streamp stream)
;; this isn't going to quite work for ~&,
;; but it's better than nothing.
(write-string (apply #'lisp:format nil format-control format-args) stream)
nil)
(t
(apply #'lisp:format stream format-control format-args))))
Higher level lisp printing functions.
Grey stream equivalent. Assumes there is an argument called "STREAM".
execute the body using the STREAM locally rebound
to an output stream object for I/O purposes:
stream I/O stuff goes here
return the accumulated output string:
use original output stream here ....
Easier to write this one out.
Higher level lisp reading functions.
this hack is necessary in order to allow (ACCEPT 'T ...) and
(ACCEPT 'EXPRESSION ...) to function (sort of) correctly ....
ACCEPT is only a rough equivalent of READ
Don't forget about this guys even if we don't implement them.
READ-PRESERVING-WHITESPACE (&OPTIONAL (STREAM *STANDARD-INPUT*)
(EOF-ERROR-P T)
User Query Functions (interacts with the *QUERY-IO* stream):
Y-OR-N-P (&OPTIONAL FORMAT-STRING &REST FORMAT-ARGS)
YES-OR-NO-P (&OPTIONAL FORMAT-STRING &REST FORMAT-ARGS)
|
(in-package :clim-utils)
"Copyright (c) 1990, 1991, 1992 Symbolics, Inc. All rights reserved.
Portions copyright (c) 1989, 1990 International Lisp Associates."
the X3J13 committee , made by of TI on 22 March 1989 . No
#+ignore
(eval-when (compile load eval)
(defparameter sym-list '("PEEK-CHAR" "READ-BYTE" "READ-CHAR" "UNREAD-CHAR"
"READ-CHAR-NO-HANG" "LISTEN" "READ-LINE"
"CLEAR-INPUT" "WRITE-BYTE" "WRITE-CHAR"
"WRITE-STRING" "TERPRI" "FRESH-LINE" "FORCE-OUTPUT"
"FINISH-OUTPUT" "CLEAR-OUTPUT" ))
(dolist (sym sym-list)
(unintern (find-symbol sym :clim-lisp) :clim-lisp)
(unintern (find-symbol sym :clim) :clim)))
(defmacro write-forwarding-lucid-output-stream-function (name args)
(let* ((cl-name (find-symbol (symbol-name name) (find-package 'lisp)))
(method-name (intern (lisp:format nil "~A-~A" 'stream (symbol-name name))))
(optional-args (or (member '&optional args) (member '&key args)))
(required-args (ldiff args optional-args))
(optional-parameters (mapcan #'(lambda (arg)
(cond ((member arg lambda-list-keywords) nil)
((atom arg) (list arg))
(t (list (car arg)))))
optional-args))
(pass-args (append required-args optional-parameters))
(method-args (if (eq (first optional-args) '&key)
(append required-args '(&optional) (cdr optional-args))
args))
(pass-keys (if (eq (first optional-args) '&key)
(mapcan #'(lambda (arg)
(unless (atom arg)
(setq arg (car arg)))
(list (intern (string arg) :keyword) arg))
(cdr optional-args))
optional-parameters))
)
(when (eq (first optional-args) '&optional)
(pop optional-args))
`(let ((orig-lucid-closure (or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
(defun ,name (,@required-args &optional stream ,@optional-args)
(cond ((null stream) (setq stream *standard-output*))
((eq stream t) (setq stream *terminal-io*)))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(,method-name stream ,@pass-args)
(funcall orig-lucid-closure ,@required-args stream ,@pass-keys)))
which does n't support as a builtin class
(defmethod ,method-name ((stream t) ,@method-args)
(,cl-name ,@required-args stream ,@pass-keys))
( import ' , name : clim - lisp )
( export ' , name : clim - lisp )
)))
(write-forwarding-lucid-output-stream-function lisp:write-byte (integer))
(write-forwarding-lucid-output-stream-function lisp:write-char (character))
(write-forwarding-lucid-output-stream-function lisp:write-string (string &key (start 0) end))
(write-forwarding-lucid-output-stream-function lisp:terpri ())
(write-forwarding-lucid-output-stream-function lisp:fresh-line ())
(write-forwarding-lucid-output-stream-function lisp:force-output ())
(write-forwarding-lucid-output-stream-function lisp:finish-output ())
(write-forwarding-lucid-output-stream-function lisp:clear-output ())
(defmacro write-forwarding-lucid-input-stream-function (name lambda-list
&key eof
additional-arguments)
(let* ((cl-name (find-symbol (symbol-name name) (find-package 'lisp)))
(method-name (intern (lisp:format nil "~A-~A" 'stream (symbol-name name))))
(method-lambda-list (set-difference lambda-list '(stream peek-type)))
(args (mapcar #'(lambda (var) (if (atom var) var (first var)))
(remove-if #'(lambda (x) (member x lambda-list-keywords))
lambda-list)))
(method-calling-args (set-difference args '(stream peek-type)))
(cleanup `(cond ((null stream) (setq stream *standard-input*))
((eq stream t) (setq stream *terminal-io*))))
(call-method `(,method-name stream ,@method-calling-args))
(calling-lambda-list (remove '&optional lambda-list)))
(when (member (first (last method-lambda-list)) lambda-list-keywords)
(setf method-lambda-list (butlast method-lambda-list)))
`(let ((orig-lucid-closure
(or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
,(if eof
(let ((args `(eof-error-p eof-value ,@(and (not (eq eof :no-recursive))
'(recursive-p)))))
`(defun ,name (,@lambda-list ,@args)
,cleanup
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(let ((result ,call-method))
(cond ((not (eq result *end-of-file-marker*))
result)
(eof-error-p
(signal-stream-eof stream ,@(and (not (eq eof :no-recursive))
'(recursive-p))))
(t
eof-value)))
(funcall orig-lucid-closure ,@calling-lambda-list ,@args))))
`(defun ,name ,lambda-list
,cleanup
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
,call-method
(funcall orig-lucid-closure ,@calling-lambda-list))))
(defmethod ,method-name ((stream t) ,@method-lambda-list)
(,cl-name ,@additional-arguments ,@(remove 'peek-type args)
,@(when eof `(nil *end-of-file-marker*))))
( import ' , name : clim - lisp )
( export ' , name : clim - lisp )
)))
(write-forwarding-lucid-input-stream-function lisp:peek-char (&optional peek-type stream)
:eof t
:additional-arguments (nil))
(write-forwarding-lucid-input-stream-function lisp:read-byte (&optional stream)
:eof :no-recursive)
(write-forwarding-lucid-input-stream-function lisp:read-char (&optional stream) :eof t)
(write-forwarding-lucid-input-stream-function lisp:unread-char (character
&optional stream))
(write-forwarding-lucid-input-stream-function lisp:read-char-no-hang (&optional stream)
:eof t)
(write-forwarding-lucid-input-stream-function lisp:listen (&optional stream))
(write-forwarding-lucid-input-stream-function lisp:read-line (&optional stream) :eof t)
(write-forwarding-lucid-input-stream-function lisp:clear-input (&optional stream))
(defun signal-stream-eof (stream &optional recursive-p)
(declare (ignore recursive-p))
(error 'end-of-file :stream stream))
Make CLIM - LISP : FORMAT do something useful on CLIM windows .
(eval-when (load)
(let ((original-lucid-closure
(or (getf (symbol-plist 'lisp:format) :original-lucid-closure)
(setf (getf (symbol-plist 'lisp:format) :original-lucid-closure)
(symbol-function 'lisp:format)))))
(defun format (stream format-control &rest format-args)
(when (eq stream 't)
(setq stream *standard-output*))
(cond ((null stream)
(apply original-lucid-closure nil format-control format-args))
clim stream
((and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(write-string (apply original-lucid-closure nil format-control format-args)
stream))
Lucid stream
(t
(apply original-lucid-closure stream format-control format-args))))))
Support for the IO functions with more varied argument templates and no
(defmacro redefine-lucid-io-function (name lambda-list &body clim-body)
(let ((args (mapcar #'(lambda (var) (if (atom var) var (first var)))
(remove-if #'(lambda (x) (member x lambda-list-keywords))
lambda-list))))
`(let ((orig-lucid-closure
(or (getf (symbol-plist ',name) :original-lucid-closure)
(setf (getf (symbol-plist ',name) :original-lucid-closure)
(symbol-function ',name)))))
(defun ,name ,lambda-list
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
,@clim-body
(funcall orig-lucid-closure ,@args))))))
(defmacro %string-stream (stream &body body)
`(let (result
(new-stream (cond ((encapsulating-stream-p ,stream)
(encapsulating-stream-stream ,stream))
((typep ,stream 'fundamental-stream)
,stream)
(t
(let ((*standard-output* *terminal-io*))
(error "Unknown stream type, ~S" ,stream))))))
(write-string
(let ((,stream (make-string-output-stream)))
(setq result ,@body )
(get-output-stream-string ,stream))
new-stream)
result))
(redefine-lucid-io-function lisp:streamp (stream) t)
(redefine-lucid-io-function lcl:underlying-stream (stream &optional direction
(recurse t)
exact-same)
(if (encapsulating-stream-p stream)
(encapsulating-stream-stream stream)
stream))
(redefine-lucid-io-function lisp:prin1 (object &optional (stream *standard-output*))
(%string-stream stream (lisp:prin1 object stream)))
(redefine-lucid-io-function lisp:print (object &optional (stream *standard-output*))
(%string-stream stream (lisp:print object stream)))
(redefine-lucid-io-function lisp:princ (object &optional (stream *standard-output*))
(%string-stream stream (lisp:princ object stream)))
(redefine-lucid-io-function lisp:pprint (object &optional (stream *standard-output*))
(%string-stream stream (lisp:pprint object stream)))
(redefine-lucid-io-function lisp:write-line (string &optional (stream *standard-output*)
&key (start 0) end)
(%string-stream stream (lisp:write-line string stream :start start :end end)))
(let ((orig-lucid-closure (symbol-function 'lisp:write)))
(defun lisp:write (object
&key
((:stream stream) *standard-output*)
((:escape escapep) *print-escape*)
((:radix *print-radix*) *print-radix*)
((:base new-print-base) *print-base* print-base-p)
((:circle *print-circle*) *print-circle*)
((:pretty *print-pretty*) *print-pretty*)
((:level *print-level*) *print-level*)
((:length *print-length*) *print-length*)
((:case new-print-case) *print-case* print-case-p)
((:array *print-array*) *print-array*)
((:gensym *print-gensym*) *print-gensym*)
((:structure lcl:*print-structure*) lcl:*print-structure*))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(%string-stream stream (lisp:write object :stream stream
:escape escapep
:radix *print-radix*
:base new-print-base :circle *print-circle*
:pretty *print-pretty*
:level *print-level* :length *print-length*
:case new-print-case
:array *print-array* :gensym *print-gensym*
:structure lcl:*print-structure*))
(funcall orig-lucid-closure object :stream stream :escape escapep
:radix *print-radix*
:base new-print-base :circle *print-circle* :pretty *print-pretty*
:level *print-level* :length *print-length* :case new-print-case
:array *print-array* :gensym *print-gensym*
:structure lcl:*print-structure*))))
(defmethod make-instance ((t-class (eql (find-class t))) &rest args)
(declare (ignore args) (dynamic-extent args))
t)
(redefine-lucid-io-function lisp:read (&optional (stream *standard-input*)
(eof-error-p t)
(eof-value nil)
(recursive-p nil))
(clim:accept 'clim:expression :stream stream))
( EOF - VALUE NIL )
( RECURSIVE - P NIL ) )
READ - DELIMITED - LIST ( CHAR & OPTIONAL ( STREAM * STANDARD - INPUT * ) ( RECURSIVE - P NIL ) )
NOTE : the built - in presentation type CLIM : BOOLEAN requires YES or NO -- not
Y or P -- as would normally be expected from Y - OR - N - P.
(lcl:defadvice (lisp:y-or-n-p stream-wrapper) (&optional format-string &rest args)
(declare (dynamic-extent args))
(if (and (system:standard-object-p *query-io*)
(typep *query-io* 'fundamental-stream))
(clim:accept 'clim:boolean :prompt (apply #'lisp::format nil format-string
args))
(lcl:apply-advice-continue format-string args)))
(lcl:defadvice (lisp:yes-or-no-p stream-wrapper) (&optional format-string &rest args)
(declare (dynamic-extent args))
(if (and (system:standard-object-p *query-io*)
(typep *query-io* 'fundamental-stream))
(clim:accept 'clim:boolean :prompt (apply #'lisp:format nil format-string
args))
(lcl:apply-advice-continue format-string args)))
#+nope
(lcl:defadvice (lisp:format stream-wrapper) (stream control-string &rest args)
(let ((stream (if (eq stream t) *standard-output* stream)))
(if (and (system:standard-object-p stream)
(typep stream 'fundamental-stream))
(apply #'clim:format stream control-string args)
(lcl:apply-advice-continue stream control-string args))))
|
c9948104583027c6ca040d9d2b5b93037fce9e94d79b2042d65b6c7e91c131ab | VincentCordobes/prep | test.ml | open Prep
open ISO8601.Permissive
let drop_store () =
let store_path = try Sys.getenv "STORE_PATH" with Not_found -> "" in
if store_path <> "" && Sys.file_exists store_path then (
Fmt.pr "Removing existing store";
Sys.remove store_path)
let before_all () =
drop_store ();
Store.init ()
let () = before_all ()
2020 - 02 - 27T15:56:38Z
let%expect_test "List empty default boxes" =
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
|}]
let%expect_test "Add a file card" =
(* when *)
Cli.add_file "./knocking on heaven door";
(* then *)
[%expect {|Card added (id: .*) (regexp) |}]
let%expect_test "Add a file card with alias" =
(* when *)
Cli.add_file ~name:(Some "greenday") "./toto";
(* then *)
[%expect {|Card added (id: .*) (regexp) |}]
let%expect_test "Add a card" =
drop_store ();
[%expect.output] |> ignore;
Store.init ();
(* when *)
Cli.add ~last_reviewed_at:now
@@ Some {|Blink182 - All the small things
body|};
(* then *)
[%expect {|Card added (id: .*) (regexp) |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
3ca14 Blink182 - All the small things
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}]
let%expect_test "Card Rating" =
(* when *)
Cli.rate ~at:now Card.Rating.Bad [ "blink182 - all the small things" ];
(* then *)
[%expect {| Card rated bad |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
3ca14 Blink182 - All the small things
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
(* when *)
Cli.rate
~at:(datetime "2020-01-01T11:00:00")
Card.Rating.Again
[ "blink182 - all the small things" ];
[%expect {| Card rated again |}];
Cli.list_boxes ();
(* then *)
(* should not move the card but still update the last reviewed *)
[%expect
{|
#1 Every 1 day
3ca14 Blink182 - All the small things
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
(* when *)
Cli.rate ~at:now Card.Rating.Good [ "blink182" ];
[%expect {| Card rated good |}];
Cli.list_boxes ();
(* then *)
(* Should move the card a to the next box*)
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
3ca14 Blink182 - All the small things
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
(* when *)
Cli.rate ~at:now Card.Rating.Again [ "blink182 - all the small things" ];
[%expect {| Card rated again |}];
Cli.list_boxes ();
(* then *)
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
3ca14 Blink182 - All the small things
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
|}];
(* when *)
Cli.rate ~at:now Card.Rating.Easy [ "blink182 - all the small things" ];
[%expect {| Card rated easy |}];
Cli.list_boxes ();
(* then *)
(* should move the card at the end *)
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
3ca14 Blink182 - All the small things
|}];
(* when *)
Cli.rate ~at:now Card.Rating.Easy [ "blink182 - all the small things" ];
[%expect {| Card rated easy |}];
Cli.rate ~at:now Card.Rating.Good [ "blink182 - all the small things" ];
[%expect {| Card rated good |}];
Cli.list_boxes ();
(* then *)
(* Should not move the card *)
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
3ca14 Blink182 - All the small things
|}]
let%expect_test "Show a card either by name or id" =
(try Cli.show_card [ "azerty" ] with _ -> ());
[%expect {|
Error: No card found with id azerty
|}];
Cli.show_card [ "blink182 - all the small things" ];
[%expect {|
Blink182 - All the small things
body
|}];
(* Partial match *)
Cli.show_card [ "bliNk182" ];
[%expect {|
Blink182 - All the small things
body
|}];
(* partial match in the middle *)
Cli.show_card [ "all" ];
[%expect {|
Blink182 - All the small things
body
|}];
(* Exact match *)
Cli.add @@ Some {|blink|};
[%expect {| Card added (id: 967f8) |}];
Cli.show_card [ "967f852" ];
[%expect {| blink |}];
(* Ambigous match *)
(try Cli.show_card [ "bli" ] with _ -> ());
[%expect
{|
Error: Several cards matches id bli.
The most similar cards are
* 967f8 blink
* 3ca14 Blink182 - All the small things
|}];
Cli.remove (fun _ -> Some 'y') [ "967f852" ];
[%expect
{|
You are about to remove the card 'blink', continue? [y/N]: Card removed.
|}]
let%expect_test "Add a box" =
Cli.add_box (Interval.Day 400) |> ignore;
[%expect {| Box added (repetitions every 400 days) |}]
let%expect_test "Handle duplicate boxes" =
Cli.add_box (Interval.Day 400) |> ignore;
[%expect {| Error: A box with interval 400 days already exists |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
3ca14 Blink182 - All the small things
#9 Every 400 days
No card.
|}]
let%expect_test "Remove a card - abort" =
(* when *)
Cli.remove (fun _ -> Some 'n') [ "blink182" ];
(* then *)
[%expect
{|
You are about to remove the card 'Blink182 - All the small things', continue? [y/N]: Aborted!
|}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
3ca14 Blink182 - All the small things
#9 Every 400 days
No card.
|}]
let%expect_test "Remove a card" =
(* when *)
Cli.remove (fun _ -> Some 'y') [ "blink182" ];
(* then *)
[%expect
{|
You are about to remove the card 'Blink182 - All the small things', continue? [y/N]: Card removed.
|}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
#9 Every 400 days
No card.
|}]
let%expect_test "next review date" =
let add_card content =
Cli.add ~last_reviewed_at:now @@ Some content;
[%expect {| Card added (.*) (regexp)|}]
in
let rate_card_good card_id =
Cli.rate ~at:now Card.Rating.Good [ card_id ];
[%expect {| Card rated good |}]
in
add_card "song";
add_card "sing";
rate_card_good "sing";
Cli.list_boxes ();
Note that there are 29 days in in feb 2020
[%expect
{|
#1 Every 1 day
fb8c5 song
#2 Every 2 days
509a9 sing
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
#9 Every 400 days
No card.
|}];
rate_card_good "sing";
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
fb8c5 song
#2 Every 2 days
No card.
#3 Every 3 days
509a9 sing
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
#9 Every 400 days
No card.
|}];
rate_card_good "sing";
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
fb8c5 song
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
509a9 sing
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
#9 Every 400 days
No card.
|}]
let%expect_test "prep review" =
(* setup *)
drop_store ();
[%expect.output] |> ignore;
(* given *)
let store =
Store.empty_store ()
|> Store.add_box @@ Box.create @@ Day 3
|> Store.add
{
id = "first";
content = Plain "first card";
box = 0;
deck = Deck.default_id;
last_reviewed_at = datetime "2020-04-05T11:00:00";
archived = false;
}
in
Store.init ~store ();
Cli.review (date "2020-04-04");
[%expect {|
2020-04-04 --
2020-04-08 #1 first card (first)
|}];
Cli.review (date "2020-04-05");
[%expect {|
2020-04-05 --
2020-04-08 #1 first card (first)
|}];
Cli.review (date "2020-04-06");
[%expect {|
2020-04-06 --
2020-04-08 #1 first card (first)
|}];
Cli.review (date "2020-04-07");
[%expect {|
2020-04-07 --
2020-04-08 #1 first card (first)
|}];
Cli.review (datetime "2020-04-08T00:00");
[%expect {|
2020-04-08 #1 first card (first)
|}];
Cli.review (datetime "2020-04-08T10:00");
[%expect {|
2020-04-08 #1 first card (first)
|}];
Cli.review (datetime "2020-04-08T12:00");
[%expect {|
2020-04-08 #1 first card (first)
|}];
Cli.review (date "2020-04-09");
[%expect {|
2020-04-08 #1 first card (first)
2020-04-09 --
|}]
let%expect_test "Box are sorted by interval" =
drop_store ();
[%expect.output] |> ignore;
(* given *)
let store =
Store.empty_store ()
|> Store.add_box (Box.create @@ Day 4)
|> Store.add_box (Box.create @@ Day 2)
|> Store.add_box (Box.create @@ Week 2)
|> Store.add_box (Box.create @@ Day 3)
|> Store.add_box (Box.create @@ Day 8)
|> Store.add_box (Box.create @@ Week 1)
in
Store.init ~store ();
(* when *)
Cli.list_boxes ();
(* then *)
[%expect
{|
#1 Every 2 days
No card.
#2 Every 3 days
No card.
#3 Every 4 days
No card.
#4 Every 1 week
No card.
#5 Every 8 days
No card.
#6 Every 2 weeks
No card.
|}]
let%expect_test "Decks" =
drop_store ();
[%expect.output] |> ignore;
(* when no deck*)
Store.init ();
Cli.list_decks ();
(* then display default deck*)
[%expect {|
* default
|}];
(* when adding a new deck*)
Cli.add_deck "custom_deck";
Cli.list_decks ();
(* then *)
[%expect {|
* default
custom_deck
|}];
(* when adding a card *)
Cli.add_file ~last_reviewed_at:now "./dilaudid";
[%expect.output] |> ignore;
(* then deck are unchanged *)
Cli.list_decks ();
[%expect {|
* default
custom_deck |}];
Cli.list_boxes ();
(* and it's added to the default deck *)
[%expect
{|
#1 Every 1 day
f8385 dilaudid
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
(* when reviewing a deck *)
Cli.review (date "2022-04-05");
(* then it should only display current deck cards *)
[%expect {|
2020-02-28 #1 dilaudid (f8385)
2022-04-05 -- |}];
(* when switching the current deck*)
Cli.use_deck ~input_char:(fun _ -> None) "custom_deck";
Cli.list_boxes ();
(* then *)
[%expect
{|
Using deck custom_deck
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
(* when reviewing a deck *)
Cli.review (date "2022-04-05");
(* then it should only review the card of the current deck *)
[%expect {| No card. |}];
(* when adding a card to the current deck *)
Cli.add_file ~last_reviewed_at:now "./vince";
[%expect.output] |> ignore;
(* then it shows that card in boxes *)
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
62692 vince
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
Cli.review (date "2022-04-05");
(* and it reviews only that card *)
[%expect {|
2020-02-28 #1 vince (62692)
2022-04-05 -- |}]
let%expect_test "use" =
drop_store ();
[%expect.output] |> ignore;
(* when no deck*)
Store.init ();
Cli.list_decks ();
(* then display default deck*)
[%expect {|
* default
|}];
(* when the deck doesnt exists and we dont want to create it *)
Cli.use_deck ~input_char:(fun _ -> Some 'n') "toto";
[%expect
{|Deck toto doesn't exist. Do you want to create it? [y/N] Aborted!|}];
Cli.list_decks ();
(* then it doesn't create it *)
[%expect {| * default |}];
(* when the deck doesnt exists and we want to create it *)
Cli.use_deck ~input_char:(fun _ -> Some 'y') "toto";
[%expect
{|
Deck toto doesn't exist. Do you want to create it? [y/N] Deck created.
Using deck toto |}];
Cli.list_decks ();
then it creates a new one
[%expect {|
default
* toto
|}];
(* when adding a deck *)
Cli.add_deck "tata";
Cli.add_deck "titi";
Cli.list_decks ();
(* then *)
[%expect {|
default
* toto
tata
titi
|}]
let%expect_test "show card by id" =
drop_store ();
[%expect.output] |> ignore;
let a_card id content =
Card.
{
id;
content = Plain content;
box = 0;
deck = Deck.default_id;
last_reviewed_at = datetime "2020-04-05T11:00:00";
archived = false;
}
in
let store =
Store.empty_store ()
|> Store.add_box @@ Box.create @@ Day 3
|> Store.add (a_card "12345678-0000-0000-0000-000000000000" "First card")
|> Store.add (a_card "00000000-0000-0000-0000-000000000000" "Second card")
|> Store.add (a_card "00000001-0000-0000-0000-000000000000" "Third card")
in
Store.init ~store ();
(try Cli.show_card [ "1234567" ] with _ -> ());
[%expect {| First card |}];
(try Cli.show_card [ "1234" ] with _ -> ());
[%expect {| First card |}];
(try Cli.show_card [ "4567" ] with _ -> ());
[%expect {| Error: No card found with id 4567 |}];
(try Cli.show_card [ "00000000" ] with _ -> ());
[%expect {| Second card |}];
(try Cli.show_card [ "0000" ] with _ -> ());
[%expect
{|
Error: Several cards matches id 0000.
The most similar cards are
* 00000001 Third card
* 00000000 Second card |}]
| null | https://raw.githubusercontent.com/VincentCordobes/prep/104d8a0d406714b189917d6b05aa51a7e7f88393/test/test.ml | ocaml | when
then
when
then
when
then
when
then
when
then
should not move the card but still update the last reviewed
when
then
Should move the card a to the next box
when
then
when
then
should move the card at the end
when
then
Should not move the card
Partial match
partial match in the middle
Exact match
Ambigous match
when
then
when
then
setup
given
given
when
then
when no deck
then display default deck
when adding a new deck
then
when adding a card
then deck are unchanged
and it's added to the default deck
when reviewing a deck
then it should only display current deck cards
when switching the current deck
then
when reviewing a deck
then it should only review the card of the current deck
when adding a card to the current deck
then it shows that card in boxes
and it reviews only that card
when no deck
then display default deck
when the deck doesnt exists and we dont want to create it
then it doesn't create it
when the deck doesnt exists and we want to create it
when adding a deck
then | open Prep
open ISO8601.Permissive
let drop_store () =
let store_path = try Sys.getenv "STORE_PATH" with Not_found -> "" in
if store_path <> "" && Sys.file_exists store_path then (
Fmt.pr "Removing existing store";
Sys.remove store_path)
let before_all () =
drop_store ();
Store.init ()
let () = before_all ()
2020 - 02 - 27T15:56:38Z
let%expect_test "List empty default boxes" =
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
|}]
let%expect_test "Add a file card" =
Cli.add_file "./knocking on heaven door";
[%expect {|Card added (id: .*) (regexp) |}]
let%expect_test "Add a file card with alias" =
Cli.add_file ~name:(Some "greenday") "./toto";
[%expect {|Card added (id: .*) (regexp) |}]
let%expect_test "Add a card" =
drop_store ();
[%expect.output] |> ignore;
Store.init ();
Cli.add ~last_reviewed_at:now
@@ Some {|Blink182 - All the small things
body|};
[%expect {|Card added (id: .*) (regexp) |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
3ca14 Blink182 - All the small things
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}]
let%expect_test "Card Rating" =
Cli.rate ~at:now Card.Rating.Bad [ "blink182 - all the small things" ];
[%expect {| Card rated bad |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
3ca14 Blink182 - All the small things
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
Cli.rate
~at:(datetime "2020-01-01T11:00:00")
Card.Rating.Again
[ "blink182 - all the small things" ];
[%expect {| Card rated again |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
3ca14 Blink182 - All the small things
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
Cli.rate ~at:now Card.Rating.Good [ "blink182" ];
[%expect {| Card rated good |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
3ca14 Blink182 - All the small things
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
Cli.rate ~at:now Card.Rating.Again [ "blink182 - all the small things" ];
[%expect {| Card rated again |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
3ca14 Blink182 - All the small things
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
|}];
Cli.rate ~at:now Card.Rating.Easy [ "blink182 - all the small things" ];
[%expect {| Card rated easy |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
3ca14 Blink182 - All the small things
|}];
Cli.rate ~at:now Card.Rating.Easy [ "blink182 - all the small things" ];
[%expect {| Card rated easy |}];
Cli.rate ~at:now Card.Rating.Good [ "blink182 - all the small things" ];
[%expect {| Card rated good |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
3ca14 Blink182 - All the small things
|}]
let%expect_test "Show a card either by name or id" =
(try Cli.show_card [ "azerty" ] with _ -> ());
[%expect {|
Error: No card found with id azerty
|}];
Cli.show_card [ "blink182 - all the small things" ];
[%expect {|
Blink182 - All the small things
body
|}];
Cli.show_card [ "bliNk182" ];
[%expect {|
Blink182 - All the small things
body
|}];
Cli.show_card [ "all" ];
[%expect {|
Blink182 - All the small things
body
|}];
Cli.add @@ Some {|blink|};
[%expect {| Card added (id: 967f8) |}];
Cli.show_card [ "967f852" ];
[%expect {| blink |}];
(try Cli.show_card [ "bli" ] with _ -> ());
[%expect
{|
Error: Several cards matches id bli.
The most similar cards are
* 967f8 blink
* 3ca14 Blink182 - All the small things
|}];
Cli.remove (fun _ -> Some 'y') [ "967f852" ];
[%expect
{|
You are about to remove the card 'blink', continue? [y/N]: Card removed.
|}]
let%expect_test "Add a box" =
Cli.add_box (Interval.Day 400) |> ignore;
[%expect {| Box added (repetitions every 400 days) |}]
let%expect_test "Handle duplicate boxes" =
Cli.add_box (Interval.Day 400) |> ignore;
[%expect {| Error: A box with interval 400 days already exists |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
3ca14 Blink182 - All the small things
#9 Every 400 days
No card.
|}]
let%expect_test "Remove a card - abort" =
Cli.remove (fun _ -> Some 'n') [ "blink182" ];
[%expect
{|
You are about to remove the card 'Blink182 - All the small things', continue? [y/N]: Aborted!
|}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
3ca14 Blink182 - All the small things
#9 Every 400 days
No card.
|}]
let%expect_test "Remove a card" =
Cli.remove (fun _ -> Some 'y') [ "blink182" ];
[%expect
{|
You are about to remove the card 'Blink182 - All the small things', continue? [y/N]: Card removed.
|}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
#9 Every 400 days
No card.
|}]
let%expect_test "next review date" =
let add_card content =
Cli.add ~last_reviewed_at:now @@ Some content;
[%expect {| Card added (.*) (regexp)|}]
in
let rate_card_good card_id =
Cli.rate ~at:now Card.Rating.Good [ card_id ];
[%expect {| Card rated good |}]
in
add_card "song";
add_card "sing";
rate_card_good "sing";
Cli.list_boxes ();
Note that there are 29 days in in feb 2020
[%expect
{|
#1 Every 1 day
fb8c5 song
#2 Every 2 days
509a9 sing
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
#9 Every 400 days
No card.
|}];
rate_card_good "sing";
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
fb8c5 song
#2 Every 2 days
No card.
#3 Every 3 days
509a9 sing
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
#9 Every 400 days
No card.
|}];
rate_card_good "sing";
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
fb8c5 song
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
509a9 sing
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card.
#9 Every 400 days
No card.
|}]
let%expect_test "prep review" =
drop_store ();
[%expect.output] |> ignore;
let store =
Store.empty_store ()
|> Store.add_box @@ Box.create @@ Day 3
|> Store.add
{
id = "first";
content = Plain "first card";
box = 0;
deck = Deck.default_id;
last_reviewed_at = datetime "2020-04-05T11:00:00";
archived = false;
}
in
Store.init ~store ();
Cli.review (date "2020-04-04");
[%expect {|
2020-04-04 --
2020-04-08 #1 first card (first)
|}];
Cli.review (date "2020-04-05");
[%expect {|
2020-04-05 --
2020-04-08 #1 first card (first)
|}];
Cli.review (date "2020-04-06");
[%expect {|
2020-04-06 --
2020-04-08 #1 first card (first)
|}];
Cli.review (date "2020-04-07");
[%expect {|
2020-04-07 --
2020-04-08 #1 first card (first)
|}];
Cli.review (datetime "2020-04-08T00:00");
[%expect {|
2020-04-08 #1 first card (first)
|}];
Cli.review (datetime "2020-04-08T10:00");
[%expect {|
2020-04-08 #1 first card (first)
|}];
Cli.review (datetime "2020-04-08T12:00");
[%expect {|
2020-04-08 #1 first card (first)
|}];
Cli.review (date "2020-04-09");
[%expect {|
2020-04-08 #1 first card (first)
2020-04-09 --
|}]
let%expect_test "Box are sorted by interval" =
drop_store ();
[%expect.output] |> ignore;
let store =
Store.empty_store ()
|> Store.add_box (Box.create @@ Day 4)
|> Store.add_box (Box.create @@ Day 2)
|> Store.add_box (Box.create @@ Week 2)
|> Store.add_box (Box.create @@ Day 3)
|> Store.add_box (Box.create @@ Day 8)
|> Store.add_box (Box.create @@ Week 1)
in
Store.init ~store ();
Cli.list_boxes ();
[%expect
{|
#1 Every 2 days
No card.
#2 Every 3 days
No card.
#3 Every 4 days
No card.
#4 Every 1 week
No card.
#5 Every 8 days
No card.
#6 Every 2 weeks
No card.
|}]
let%expect_test "Decks" =
drop_store ();
[%expect.output] |> ignore;
Store.init ();
Cli.list_decks ();
[%expect {|
* default
|}];
Cli.add_deck "custom_deck";
Cli.list_decks ();
[%expect {|
* default
custom_deck
|}];
Cli.add_file ~last_reviewed_at:now "./dilaudid";
[%expect.output] |> ignore;
Cli.list_decks ();
[%expect {|
* default
custom_deck |}];
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
f8385 dilaudid
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
Cli.review (date "2022-04-05");
[%expect {|
2020-02-28 #1 dilaudid (f8385)
2022-04-05 -- |}];
Cli.use_deck ~input_char:(fun _ -> None) "custom_deck";
Cli.list_boxes ();
[%expect
{|
Using deck custom_deck
#1 Every 1 day
No card.
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
Cli.review (date "2022-04-05");
[%expect {| No card. |}];
Cli.add_file ~last_reviewed_at:now "./vince";
[%expect.output] |> ignore;
Cli.list_boxes ();
[%expect
{|
#1 Every 1 day
62692 vince
#2 Every 2 days
No card.
#3 Every 3 days
No card.
#4 Every 5 days
No card.
#5 Every 1 week
No card.
#6 Every 13 days
No card.
#7 Every 3 weeks
No card.
#8 Every 5 weeks
No card. |}];
Cli.review (date "2022-04-05");
[%expect {|
2020-02-28 #1 vince (62692)
2022-04-05 -- |}]
let%expect_test "use" =
drop_store ();
[%expect.output] |> ignore;
Store.init ();
Cli.list_decks ();
[%expect {|
* default
|}];
Cli.use_deck ~input_char:(fun _ -> Some 'n') "toto";
[%expect
{|Deck toto doesn't exist. Do you want to create it? [y/N] Aborted!|}];
Cli.list_decks ();
[%expect {| * default |}];
Cli.use_deck ~input_char:(fun _ -> Some 'y') "toto";
[%expect
{|
Deck toto doesn't exist. Do you want to create it? [y/N] Deck created.
Using deck toto |}];
Cli.list_decks ();
then it creates a new one
[%expect {|
default
* toto
|}];
Cli.add_deck "tata";
Cli.add_deck "titi";
Cli.list_decks ();
[%expect {|
default
* toto
tata
titi
|}]
let%expect_test "show card by id" =
drop_store ();
[%expect.output] |> ignore;
let a_card id content =
Card.
{
id;
content = Plain content;
box = 0;
deck = Deck.default_id;
last_reviewed_at = datetime "2020-04-05T11:00:00";
archived = false;
}
in
let store =
Store.empty_store ()
|> Store.add_box @@ Box.create @@ Day 3
|> Store.add (a_card "12345678-0000-0000-0000-000000000000" "First card")
|> Store.add (a_card "00000000-0000-0000-0000-000000000000" "Second card")
|> Store.add (a_card "00000001-0000-0000-0000-000000000000" "Third card")
in
Store.init ~store ();
(try Cli.show_card [ "1234567" ] with _ -> ());
[%expect {| First card |}];
(try Cli.show_card [ "1234" ] with _ -> ());
[%expect {| First card |}];
(try Cli.show_card [ "4567" ] with _ -> ());
[%expect {| Error: No card found with id 4567 |}];
(try Cli.show_card [ "00000000" ] with _ -> ());
[%expect {| Second card |}];
(try Cli.show_card [ "0000" ] with _ -> ());
[%expect
{|
Error: Several cards matches id 0000.
The most similar cards are
* 00000001 Third card
* 00000000 Second card |}]
|
9b9043f677967601ddb9125d743dea1ecaa83c12cbd50ae19f615df350b176c0 | CompSciCabal/SMRTYPRTY | exercises_2.1.rkt | #lang racket
provided from SICP
(define (gcd m n)
(cond ((< m n) (gcd n m))
((= n 0) m)
(else (gcd n (remainder m n)))))
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (numer r)
(car r))
(define (denom r)
(cdr r))
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (eql-rat? x y)
(= (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (print-rat r)
(fprintf (current-output-port)
"~a/~a~%"
(numer r)
(denom r)))
(displayln "exercise 2.1")
(define (impr-make-rat n d)
(let* ([abs-n (abs n)]
[abs-d (abs d)]
[sign-n (/ n abs-n)]
[sign-d (/ d abs-d)]
[g (gcd abs-n abs-d)])
(cons
(* (* sign-n sign-d) (/ abs-n g))
(/ abs-d g))))
(set! make-rat impr-make-rat)
(print-rat (make-rat -2 -4))
(print-rat (make-rat 2 -4))
(print-rat (make-rat -1 5))
(print-rat (make-rat 9 -3))
(displayln "exercise 2.2")
(define (make-point x y) (cons x y))
(define (p-x p) (car p))
(define (p-y p) (cdr p))
(define (p-print p)
(fprintf (current-output-port)
"(~a,~a)~%"
(p-x p)
(p-y p)))
(define (make-segment start end) (cons start end))
(define (seg-start s) (car s))
(define (seg-end s) (cdr s))
(define (seg-midpoint s)
(let ([start (seg-start s)]
[end (seg-end s)]
[avg (lambda (x y) (/ (+ x y) 2.0))])
(make-point (avg (p-x start) (p-x end))
(avg (p-y start) (p-y end)))))
(define a (make-point 0 0))
(define b (make-point 0 5))
(define c (make-point 2 7))
(define d (make-point 3 2))
(define e (make-point 2 3))
(define f (make-point 10 15))
(define g (make-point 10 0))
(p-print (seg-midpoint (make-segment a b)))
(p-print (seg-midpoint (make-segment a c)))
(p-print (seg-midpoint (make-segment b c)))
(p-print (seg-midpoint (make-segment c d)))
(p-print (seg-midpoint (make-segment e f)))
(displayln "exercise 2.3")
;; Design with wishful thinking
;; -- call the functions we want
;; -- define them when they are missing
I 'm defining rectangles as an origin and their two component
;; vectors. This should allow rectangles of any orientation to work.
;; Granted, I'm not doing anything to verify that vh and vw are
;; perpendicular.
( 0 , 5)<- vh
;;
;;
( 0 , 0)<- origin ( 10 , 0)<- vw
(define (make-rect origin vw vh)
(cons (make-segment origin vw)
(make-segment origin vh)))
(define (rect-perim r)
(* 2 (+ (rect-width r) (rect-height r))))
(define (rect-area r)
(* (rect-width r) (rect-height r)))
;; Implement required functions -- note: need to
;; add segment-length function. Putting here to
;; associate with this question. Otherwise it would
;; be placed with all the other segment code.
(define (rect-width r)
(seg-length (car r)))
(define (rect-height r)
(seg-length (cdr r)))
(define (seg-length s)
(let ([start (seg-start s)]
[end (seg-end s)]
[square (lambda (x) (expt x 2))])
(sqrt (+ (square (- (p-x end) (p-x start)))
(square (- (p-y end) (p-y start)))))))
(define rect-a (make-rect a g b))
(rect-width rect-a)
(rect-height rect-a)
(rect-perim rect-a)
(rect-area rect-a)
(displayln "exercise 2.3 ext: origin focused")
;; Instead simply base a rectangle by it's upper-right most edge
;; This makes rectangles origin based though
(define (alt-make-rect upper-right-x upper-right-y)
(cons upper-right-x upper-right-y))
(define (alt-rect-width r) (car r))
(define (alt-rect-height r) (cdr r))
(set! rect-width alt-rect-width)
(set! rect-height alt-rect-height)
(define rect-b (alt-make-rect 10 5))
(rect-width rect-b)
(rect-height rect-b)
(rect-perim rect-b)
(rect-area rect-b)
(displayln "exercise 2.3 ext: message passing")
;; Can we go even further such that how our rect-width
;; and rect-height are even abstracted? We could do it
;; using the message passing style
(define (make-msg-passing-rect origin vw vh)
(lambda (msg)
(cond [(= msg 0) (seg-length (make-segment origin vw))]
[(= msg 1) (seg-length (make-segment origin vh))])))
(define (msg-pass-rect-width r) (r 0))
(define (msg-pass-rect-height r) (r 1))
(set! rect-width msg-pass-rect-width)
(set! rect-height msg-pass-rect-height)
(define rect-c (make-msg-passing-rect a g b))
(rect-width rect-c)
(rect-height rect-c)
(rect-perim rect-c)
(rect-area rect-c)
(displayln "exercise 2.4")
(define (a-cons x y)
(lambda (m) (m x y)))
(define (a-car z)
(z (lambda (p q) p)))
What does the substitution of ( a - car ( a - cons 3 4 ) ) look like ?
( a - car ( lambda ( m ) ( m 3 4 ) )
;; A B
( ( lambda ( m ) ( m 3 4 ) ) ( lambda ( p q ) p ) )
;; m from A gets replaced with the provided lambda in B
Since m is applied , we need to pass in 3 and 4 to the
;; lambda in B
( lambda ( 3 4 ) 3 )
> 3
;; How could we do the same for a-cdr?
(define (a-cdr z)
(z (lambda (p q) q)))
(a-car (a-cons 3 4))
(a-cdr (a-cons 3 4))
(displayln "exercise 2.5")
;; I don't really _get_ this question
(define (num-cons a b) (* (expt 2 a) (expt 3 b)))
(define (num-car x) (count-0-remainder-divisions x 2))
(define (num-cdr x) (count-0-remainder-divisions x 3))
(define (count-0-remainder-divisions n divisor)
(define (iter try-exp)
(if (= 0 (remainder n (expt divisor try-exp)))
(iter (+ try-exp 1))
(- try-exp 1)))
(iter 1))
(num-car (num-cons 3 4))
(num-cdr (num-cons 3 4))
(displayln "exercise 2.6")
;; I'm not super super sure on this one.
;; Would be great to cover at the book club.
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
(lambda (f) (lambda (x) (f ((n f) x)))))
(add-1 zero)
;; Substitution Model:
;; Z
;; (add-1 (lambda (f) (lambda (x) x)))
;; In add-1 replace n with the lambda function identified by Z, to reduce
confusion let 's rename the variable f in zero to g
;; (add-1 (lambda (g) (lambda (x) x)))
;;(lambda (f)
;; (lambda (x)
;; (f (((lambda (g) (lambda (x) x)) f) x))))
;; Apply f to Z (lambda (g)....)
;; (lambda (f)
;; (lambda (x)
;; (f ((lambda (x) x) x))))
;; Now apply x to (lambda (x) ...)
;; (lambda (f) (lambda (x) (f x)))
So ... add-1 is really just ( f x ) . Therefore , to create one
and two all we need to do is define them as the application of the function
;; a number of times
(define (one f) (lambda (x) (f x)))
(define (two f) (lambda (x) (f (f x))))
;; If we look at the definition of Church Numerals we can see
;; that plus(m, n) is just (mf(nf(x))
;; #Calculation_with_Church_numerals
(define (church-sum m n)
First we need our f and x , which are just lambda functions
(lambda (f)
(lambda (x)
((m f) ((n f) x)))))
(display "section 2.1.4: extended exercise")
(define (add-interval x y)
(make-interval (+ (lower-bound x) (lower-bound y))
(+ (upper-bound x) (upper-bound y))))
(displayln "exercise 2.7")
(define (make-interval a b) (cons a b))
(define (lower-bound i) (min (car i) (cdr i)))
(define (upper-bound i) (max (car i) (cdr i)))
(lower-bound (make-interval 2 5))
(lower-bound (make-interval 8 2))
(displayln "exercise 2.8")
;; We can take the logic from the way division of intevals is performed
;; Instead of taking the reciprocal though, we take the negative value
;; then sum the them together.
(define (sub-interval x y)
(add-interval x (make-interval (- (upper-bound y))
(- (lower-bound y)))))
(sub-interval (make-interval 5 2) (make-interval 3 2))
(sub-interval (make-interval 3 1) (make-interval 3 2))
(displayln "exercise 2.9")
(displayln "exercise 2.9 a: See exercise-2.9.png for work")
(displayln "exercise 2.9 b")
(define (width-interval i)
(/ (- (upper-bound i) (lower-bound i)) 2))
;; For multiplication/division things don't play out as nicely. If we look at the
;; implementations we'll see that we end up using the largest and smallest combination
from the two intervals being operated on . When those intervals cross over into
;; negative values things start to get kinda weird
;; We can see this by taking intervals that have similar widths but will notice that
;; the widths of their products aren't the same
(define (mul-interval x y)
(let ([p1 (* (lower-bound x) (lower-bound y))]
[p2 (* (lower-bound x) (upper-bound y))]
[p3 (* (upper-bound x) (lower-bound y))]
[p4 (* (upper-bound x) (upper-bound y))])
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4))))
(define i1 (make-interval -1 1))
(define i2 (make-interval -5 5))
> 1
> 5
> 5
> 1
> 5
> 1
> 5
> 10
> 1
> 5
> 1
> 5
> 17
(displayln "exercise 2.10")
(define (div-interval x y)
(if (>= 0 (* (lower-bound y) (upper-bound y)))
(error "cannot divide by an interval that spans 0" y)
(mul-interval x
(make-interval (/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y))))))
(displayln "exercise 2.11")
(define (interval-sign i)
(let ([iL (lower-bound i)]
[iH (upper-bound i)])
(cond [(and (>= 0 iL) (>= 0 iH)) 1]
[(and (< 0 iL) (< 0 iH)) -1]
[else 0])))
;; ¯\(°_o)/¯ -- I'll try this one again later
(displayln "exercise 2.11 -- skipped / confused")
(displayln "exercise 2.12")
(define (make-center-width c w)
(make-interval (- c w) (+ c w)))
(define (center i)
(/ (+ (lower-bound i) (upper-bound i)) 2))
(define (width i)
(/ (- (upper-bound i) (lower-bound i)) 2))
(define (make-center-percent c pct)
(let ([pct-offset (* c (/ pct 100.0))])
(make-interval (- c pct-offset) (+ c pct-offset))))
(define (percent i)
(let* [(offset (/ (- (upper-bound i) (lower-bound i)) 2))
(center (+ (lower-bound i) offset))]
(* (/ offset center) 100)))
(define p1 (make-center-percent 100 10))
(define p2 (make-center-percent 5 5))
(define p3 (make-center-percent 30 2))
(define p4 (make-center-percent 20 15))
(define p5 (make-center-percent 30 1))
(map (lambda (x) (percent x)) (list p1 p2 p3 p4))
(displayln "exercise 2.13")
(percent (mul-interval p1 p2))
(percent (mul-interval p3 p4))
(percent (mul-interval p2 p4))
;; As we can see by taking the percentages of a few intervals, the
;; resulting percentage is approx. the sum of each intervals tolerance.
(displayln "exercise 2.14, 2.15, & 2.16")
(define (par1 r1 r2)
(div-interval (mul-interval r1 r2)
(add-interval r1 r2)))
(define (par2 r1 r2)
(let ([one (make-interval 1 1)])
(div-interval one
(add-interval (div-interval one r1)
(div-interval one r2)))))
(define A (make-interval 4.5 5.5))
(define B (make-interval 4.75 5.25))
(percent A)
(percent B)
2.14
(define A-div-A (div-interval A A))
(define A-div-B (div-interval A B))
(percent A-div-A)
(percent A-div-B)
;; There isn't an "identity" so we cannot differentiate between an interval dividing
;; itself and dividing being divided by another. In the case of A / A weouldn't expect to see
;; a change in the error, but instead we the tolerance increase by double.
2.15
(percent (par1 A B))
(percent (par2 A B))
Yes , is correct . There is a bunch of uncertainty in the values passed into par1 and as
we saw in 2.14 , dividing values by themselves results in disgustingly large increases in the
;; tolerance percentage. By avoiding these kinds of operations we can keep our tolerances down to
something manageable . By introducing the _ one _ interval we ensure that no provided interval is
;; dividing itself.
2.16
;; No I cannot devise an interval-arithmetic package
;;
;; If we look at other algebraic constructs(?) such as the set of real numbers(?) there are certain properties
that we need in order for two equations to be algebraically equivalent .
;; Properties of Real Numbers:
;; - Summation/Subtraction: There exists an identity X such that A+X = A and A-X = A
- Multiplication / Division : There exists an identiy Y such that A*Y = A and A / Y = A
;; The reason this works is because the values we are working with are discrete and we are completely confident
;; in their value.
;;
;; With the intervals the actual value can land *anywhere* within that interval, so subsequent
;; operations decrease our confidence in the interval. Depending on how we perform the operations we can cause
;; bigger and bigger increases to the tolerance.
;;
;; ? - My math knowledge discrete mathematics / set theory is terrible so I might be getting these names wrong.
;; I apologize. | null | https://raw.githubusercontent.com/CompSciCabal/SMRTYPRTY/4a5550789c997c20fb7256b81469de1f1fce3514/sicp/v2/2.1/csaunders/exercises_2.1.rkt | racket | Design with wishful thinking
-- call the functions we want
-- define them when they are missing
vectors. This should allow rectangles of any orientation to work.
Granted, I'm not doing anything to verify that vh and vw are
perpendicular.
Implement required functions -- note: need to
add segment-length function. Putting here to
associate with this question. Otherwise it would
be placed with all the other segment code.
Instead simply base a rectangle by it's upper-right most edge
This makes rectangles origin based though
Can we go even further such that how our rect-width
and rect-height are even abstracted? We could do it
using the message passing style
A B
m from A gets replaced with the provided lambda in B
lambda in B
How could we do the same for a-cdr?
I don't really _get_ this question
I'm not super super sure on this one.
Would be great to cover at the book club.
Substitution Model:
Z
(add-1 (lambda (f) (lambda (x) x)))
In add-1 replace n with the lambda function identified by Z, to reduce
(add-1 (lambda (g) (lambda (x) x)))
(lambda (f)
(lambda (x)
(f (((lambda (g) (lambda (x) x)) f) x))))
Apply f to Z (lambda (g)....)
(lambda (f)
(lambda (x)
(f ((lambda (x) x) x))))
Now apply x to (lambda (x) ...)
(lambda (f) (lambda (x) (f x)))
a number of times
If we look at the definition of Church Numerals we can see
that plus(m, n) is just (mf(nf(x))
#Calculation_with_Church_numerals
We can take the logic from the way division of intevals is performed
Instead of taking the reciprocal though, we take the negative value
then sum the them together.
For multiplication/division things don't play out as nicely. If we look at the
implementations we'll see that we end up using the largest and smallest combination
negative values things start to get kinda weird
We can see this by taking intervals that have similar widths but will notice that
the widths of their products aren't the same
¯\(°_o)/¯ -- I'll try this one again later
As we can see by taking the percentages of a few intervals, the
resulting percentage is approx. the sum of each intervals tolerance.
There isn't an "identity" so we cannot differentiate between an interval dividing
itself and dividing being divided by another. In the case of A / A weouldn't expect to see
a change in the error, but instead we the tolerance increase by double.
tolerance percentage. By avoiding these kinds of operations we can keep our tolerances down to
dividing itself.
No I cannot devise an interval-arithmetic package
If we look at other algebraic constructs(?) such as the set of real numbers(?) there are certain properties
Properties of Real Numbers:
- Summation/Subtraction: There exists an identity X such that A+X = A and A-X = A
The reason this works is because the values we are working with are discrete and we are completely confident
in their value.
With the intervals the actual value can land *anywhere* within that interval, so subsequent
operations decrease our confidence in the interval. Depending on how we perform the operations we can cause
bigger and bigger increases to the tolerance.
? - My math knowledge discrete mathematics / set theory is terrible so I might be getting these names wrong.
I apologize. | #lang racket
provided from SICP
(define (gcd m n)
(cond ((< m n) (gcd n m))
((= n 0) m)
(else (gcd n (remainder m n)))))
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (numer r)
(car r))
(define (denom r)
(cdr r))
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (eql-rat? x y)
(= (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (print-rat r)
(fprintf (current-output-port)
"~a/~a~%"
(numer r)
(denom r)))
(displayln "exercise 2.1")
(define (impr-make-rat n d)
(let* ([abs-n (abs n)]
[abs-d (abs d)]
[sign-n (/ n abs-n)]
[sign-d (/ d abs-d)]
[g (gcd abs-n abs-d)])
(cons
(* (* sign-n sign-d) (/ abs-n g))
(/ abs-d g))))
(set! make-rat impr-make-rat)
(print-rat (make-rat -2 -4))
(print-rat (make-rat 2 -4))
(print-rat (make-rat -1 5))
(print-rat (make-rat 9 -3))
(displayln "exercise 2.2")
(define (make-point x y) (cons x y))
(define (p-x p) (car p))
(define (p-y p) (cdr p))
(define (p-print p)
(fprintf (current-output-port)
"(~a,~a)~%"
(p-x p)
(p-y p)))
(define (make-segment start end) (cons start end))
(define (seg-start s) (car s))
(define (seg-end s) (cdr s))
(define (seg-midpoint s)
(let ([start (seg-start s)]
[end (seg-end s)]
[avg (lambda (x y) (/ (+ x y) 2.0))])
(make-point (avg (p-x start) (p-x end))
(avg (p-y start) (p-y end)))))
(define a (make-point 0 0))
(define b (make-point 0 5))
(define c (make-point 2 7))
(define d (make-point 3 2))
(define e (make-point 2 3))
(define f (make-point 10 15))
(define g (make-point 10 0))
(p-print (seg-midpoint (make-segment a b)))
(p-print (seg-midpoint (make-segment a c)))
(p-print (seg-midpoint (make-segment b c)))
(p-print (seg-midpoint (make-segment c d)))
(p-print (seg-midpoint (make-segment e f)))
(displayln "exercise 2.3")
I 'm defining rectangles as an origin and their two component
( 0 , 5)<- vh
( 0 , 0)<- origin ( 10 , 0)<- vw
(define (make-rect origin vw vh)
(cons (make-segment origin vw)
(make-segment origin vh)))
(define (rect-perim r)
(* 2 (+ (rect-width r) (rect-height r))))
(define (rect-area r)
(* (rect-width r) (rect-height r)))
(define (rect-width r)
(seg-length (car r)))
(define (rect-height r)
(seg-length (cdr r)))
(define (seg-length s)
(let ([start (seg-start s)]
[end (seg-end s)]
[square (lambda (x) (expt x 2))])
(sqrt (+ (square (- (p-x end) (p-x start)))
(square (- (p-y end) (p-y start)))))))
(define rect-a (make-rect a g b))
(rect-width rect-a)
(rect-height rect-a)
(rect-perim rect-a)
(rect-area rect-a)
(displayln "exercise 2.3 ext: origin focused")
(define (alt-make-rect upper-right-x upper-right-y)
(cons upper-right-x upper-right-y))
(define (alt-rect-width r) (car r))
(define (alt-rect-height r) (cdr r))
(set! rect-width alt-rect-width)
(set! rect-height alt-rect-height)
(define rect-b (alt-make-rect 10 5))
(rect-width rect-b)
(rect-height rect-b)
(rect-perim rect-b)
(rect-area rect-b)
(displayln "exercise 2.3 ext: message passing")
(define (make-msg-passing-rect origin vw vh)
(lambda (msg)
(cond [(= msg 0) (seg-length (make-segment origin vw))]
[(= msg 1) (seg-length (make-segment origin vh))])))
(define (msg-pass-rect-width r) (r 0))
(define (msg-pass-rect-height r) (r 1))
(set! rect-width msg-pass-rect-width)
(set! rect-height msg-pass-rect-height)
(define rect-c (make-msg-passing-rect a g b))
(rect-width rect-c)
(rect-height rect-c)
(rect-perim rect-c)
(rect-area rect-c)
(displayln "exercise 2.4")
(define (a-cons x y)
(lambda (m) (m x y)))
(define (a-car z)
(z (lambda (p q) p)))
What does the substitution of ( a - car ( a - cons 3 4 ) ) look like ?
( a - car ( lambda ( m ) ( m 3 4 ) )
( ( lambda ( m ) ( m 3 4 ) ) ( lambda ( p q ) p ) )
Since m is applied , we need to pass in 3 and 4 to the
( lambda ( 3 4 ) 3 )
> 3
(define (a-cdr z)
(z (lambda (p q) q)))
(a-car (a-cons 3 4))
(a-cdr (a-cons 3 4))
(displayln "exercise 2.5")
(define (num-cons a b) (* (expt 2 a) (expt 3 b)))
(define (num-car x) (count-0-remainder-divisions x 2))
(define (num-cdr x) (count-0-remainder-divisions x 3))
(define (count-0-remainder-divisions n divisor)
(define (iter try-exp)
(if (= 0 (remainder n (expt divisor try-exp)))
(iter (+ try-exp 1))
(- try-exp 1)))
(iter 1))
(num-car (num-cons 3 4))
(num-cdr (num-cons 3 4))
(displayln "exercise 2.6")
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
(lambda (f) (lambda (x) (f ((n f) x)))))
(add-1 zero)
confusion let 's rename the variable f in zero to g
So ... add-1 is really just ( f x ) . Therefore , to create one
and two all we need to do is define them as the application of the function
(define (one f) (lambda (x) (f x)))
(define (two f) (lambda (x) (f (f x))))
(define (church-sum m n)
First we need our f and x , which are just lambda functions
(lambda (f)
(lambda (x)
((m f) ((n f) x)))))
(display "section 2.1.4: extended exercise")
(define (add-interval x y)
(make-interval (+ (lower-bound x) (lower-bound y))
(+ (upper-bound x) (upper-bound y))))
(displayln "exercise 2.7")
(define (make-interval a b) (cons a b))
(define (lower-bound i) (min (car i) (cdr i)))
(define (upper-bound i) (max (car i) (cdr i)))
(lower-bound (make-interval 2 5))
(lower-bound (make-interval 8 2))
(displayln "exercise 2.8")
(define (sub-interval x y)
(add-interval x (make-interval (- (upper-bound y))
(- (lower-bound y)))))
(sub-interval (make-interval 5 2) (make-interval 3 2))
(sub-interval (make-interval 3 1) (make-interval 3 2))
(displayln "exercise 2.9")
(displayln "exercise 2.9 a: See exercise-2.9.png for work")
(displayln "exercise 2.9 b")
(define (width-interval i)
(/ (- (upper-bound i) (lower-bound i)) 2))
from the two intervals being operated on . When those intervals cross over into
(define (mul-interval x y)
(let ([p1 (* (lower-bound x) (lower-bound y))]
[p2 (* (lower-bound x) (upper-bound y))]
[p3 (* (upper-bound x) (lower-bound y))]
[p4 (* (upper-bound x) (upper-bound y))])
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4))))
(define i1 (make-interval -1 1))
(define i2 (make-interval -5 5))
> 1
> 5
> 5
> 1
> 5
> 1
> 5
> 10
> 1
> 5
> 1
> 5
> 17
(displayln "exercise 2.10")
(define (div-interval x y)
(if (>= 0 (* (lower-bound y) (upper-bound y)))
(error "cannot divide by an interval that spans 0" y)
(mul-interval x
(make-interval (/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y))))))
(displayln "exercise 2.11")
(define (interval-sign i)
(let ([iL (lower-bound i)]
[iH (upper-bound i)])
(cond [(and (>= 0 iL) (>= 0 iH)) 1]
[(and (< 0 iL) (< 0 iH)) -1]
[else 0])))
(displayln "exercise 2.11 -- skipped / confused")
(displayln "exercise 2.12")
(define (make-center-width c w)
(make-interval (- c w) (+ c w)))
(define (center i)
(/ (+ (lower-bound i) (upper-bound i)) 2))
(define (width i)
(/ (- (upper-bound i) (lower-bound i)) 2))
(define (make-center-percent c pct)
(let ([pct-offset (* c (/ pct 100.0))])
(make-interval (- c pct-offset) (+ c pct-offset))))
(define (percent i)
(let* [(offset (/ (- (upper-bound i) (lower-bound i)) 2))
(center (+ (lower-bound i) offset))]
(* (/ offset center) 100)))
(define p1 (make-center-percent 100 10))
(define p2 (make-center-percent 5 5))
(define p3 (make-center-percent 30 2))
(define p4 (make-center-percent 20 15))
(define p5 (make-center-percent 30 1))
(map (lambda (x) (percent x)) (list p1 p2 p3 p4))
(displayln "exercise 2.13")
(percent (mul-interval p1 p2))
(percent (mul-interval p3 p4))
(percent (mul-interval p2 p4))
(displayln "exercise 2.14, 2.15, & 2.16")
(define (par1 r1 r2)
(div-interval (mul-interval r1 r2)
(add-interval r1 r2)))
(define (par2 r1 r2)
(let ([one (make-interval 1 1)])
(div-interval one
(add-interval (div-interval one r1)
(div-interval one r2)))))
(define A (make-interval 4.5 5.5))
(define B (make-interval 4.75 5.25))
(percent A)
(percent B)
2.14
(define A-div-A (div-interval A A))
(define A-div-B (div-interval A B))
(percent A-div-A)
(percent A-div-B)
2.15
(percent (par1 A B))
(percent (par2 A B))
Yes , is correct . There is a bunch of uncertainty in the values passed into par1 and as
we saw in 2.14 , dividing values by themselves results in disgustingly large increases in the
something manageable . By introducing the _ one _ interval we ensure that no provided interval is
2.16
that we need in order for two equations to be algebraically equivalent .
- Multiplication / Division : There exists an identiy Y such that A*Y = A and A / Y = A |
e14dd7b3eefd1d9b6d1f84abbe8692728f13ca20f9dfacd44339d496d5f2b132 | semperos/rankle | table_test.clj | (ns com.semperos.rankle.table-test
(:require [clojure.test :refer :all]
[com.semperos.rankle.table :refer :all]))
(deftest test-table-and-column-map
(let [data (mapv (fn [idx]
{:foo (* (inc idx) 15)
:barcel (nth ["alpha" "beta" "gamma" "delta" "epsilon"] idx)
:baz (mapv #(* (inc idx) 2 %) [1 2 3])})
(range 5))
cm (to-column-map data)
t (to-table cm)]
(is (= t (flip cm)))
(is (= cm (flip t)))
(testing "Single row or column selector"
(is (= [15 30 45 60 75]
(t [nil :foo])))
(is (= [15 30 45 60 75]
(cm [:foo nil])))
(is (= (column-map [:foo :barcel :baz] [[15] ["alpha"] [[2 4 6]]])
(t [0 nil])))
(is (= (column-map [:foo :barcel :baz] [[15] ["alpha"] [[2 4 6]]])
(cm [nil 0]))))
(testing "Row and column selectors"
(is (= 15
(t [0 :foo])))
(is (= 60
(t [3 :foo])))
(is (= 15
(cm [:foo 0])))
(is (= 60
(cm [:foo 3])))
(testing "with nested tuples"
(testing "of one type"
(is (= (column-map [:foo :barcel :baz]
[[15 45] ["alpha" "gamma"] [[2 4 6] [6 12 18]]])
(t [[0 2] nil])))
(is (= (column-map {:foo [15 45]
:barcel ["alpha" "gamma"]
:baz [[2 4 6] [6 12 18]]})
(t [[0 2] nil])))
(is (= (column-map {:foo [30 60]
:barcel ["beta" "delta"]
:baz [[4 8 12] [8 16 24]]})
(t [[1 3] nil])))
(is (= [[15 30 45 60 75] ["alpha" "beta" "gamma" "delta" "epsilon"]]
(t [nil [:foo :barcel]])))
(is (= (column-map {:foo [15 60]
:barcel ["alpha" "delta"]
:baz [[2 4 6] [8 16 24]]})
(cm [nil [0 3]])))
(is (= (column-map {:foo [30 45]
:barcel ["beta" "gamma"]
:baz [[4 8 12] [6 12 18]]})
(cm [nil [1 2]])))
(is (= [[15 30 45 60 75]
[[2 4 6] [4 8 12] [6 12 18] [8 16 24] [10 20 30]]]
(cm [[:foo :baz] nil])))
(testing "with non-nested other"
(is (= (column-map [:foo]
[[15 45]])
(t [[0 2] :foo])))
(is (= [45 "gamma"]
(cm [[:foo :barcel] 2]))))
(testing "with nested other"
(is (= (column-map [:foo :barcel]
[[15 45] ["alpha" "gamma"]])
(t [[0 2] [:foo :barcel]])))
(is (= '((15 "alpha") (60 "delta"))
(cm [[:foo :barcel] [0 3]])))))))))
| null | https://raw.githubusercontent.com/semperos/rankle/d898c144e33056d743848620f17564d88d87e874/test/com/semperos/rankle/table_test.clj | clojure | (ns com.semperos.rankle.table-test
(:require [clojure.test :refer :all]
[com.semperos.rankle.table :refer :all]))
(deftest test-table-and-column-map
(let [data (mapv (fn [idx]
{:foo (* (inc idx) 15)
:barcel (nth ["alpha" "beta" "gamma" "delta" "epsilon"] idx)
:baz (mapv #(* (inc idx) 2 %) [1 2 3])})
(range 5))
cm (to-column-map data)
t (to-table cm)]
(is (= t (flip cm)))
(is (= cm (flip t)))
(testing "Single row or column selector"
(is (= [15 30 45 60 75]
(t [nil :foo])))
(is (= [15 30 45 60 75]
(cm [:foo nil])))
(is (= (column-map [:foo :barcel :baz] [[15] ["alpha"] [[2 4 6]]])
(t [0 nil])))
(is (= (column-map [:foo :barcel :baz] [[15] ["alpha"] [[2 4 6]]])
(cm [nil 0]))))
(testing "Row and column selectors"
(is (= 15
(t [0 :foo])))
(is (= 60
(t [3 :foo])))
(is (= 15
(cm [:foo 0])))
(is (= 60
(cm [:foo 3])))
(testing "with nested tuples"
(testing "of one type"
(is (= (column-map [:foo :barcel :baz]
[[15 45] ["alpha" "gamma"] [[2 4 6] [6 12 18]]])
(t [[0 2] nil])))
(is (= (column-map {:foo [15 45]
:barcel ["alpha" "gamma"]
:baz [[2 4 6] [6 12 18]]})
(t [[0 2] nil])))
(is (= (column-map {:foo [30 60]
:barcel ["beta" "delta"]
:baz [[4 8 12] [8 16 24]]})
(t [[1 3] nil])))
(is (= [[15 30 45 60 75] ["alpha" "beta" "gamma" "delta" "epsilon"]]
(t [nil [:foo :barcel]])))
(is (= (column-map {:foo [15 60]
:barcel ["alpha" "delta"]
:baz [[2 4 6] [8 16 24]]})
(cm [nil [0 3]])))
(is (= (column-map {:foo [30 45]
:barcel ["beta" "gamma"]
:baz [[4 8 12] [6 12 18]]})
(cm [nil [1 2]])))
(is (= [[15 30 45 60 75]
[[2 4 6] [4 8 12] [6 12 18] [8 16 24] [10 20 30]]]
(cm [[:foo :baz] nil])))
(testing "with non-nested other"
(is (= (column-map [:foo]
[[15 45]])
(t [[0 2] :foo])))
(is (= [45 "gamma"]
(cm [[:foo :barcel] 2]))))
(testing "with nested other"
(is (= (column-map [:foo :barcel]
[[15 45] ["alpha" "gamma"]])
(t [[0 2] [:foo :barcel]])))
(is (= '((15 "alpha") (60 "delta"))
(cm [[:foo :barcel] [0 3]])))))))))
| |
b16e741a48aba671d437e94da04839dbeaf2dcff4c0c0c4b1c51f3de4c386276 | clojurecup2014/parade-route | zip.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;functional hierarchical zipper, with navigation, editing and enumeration
see
(ns ^{:doc "Functional hierarchical zipper, with navigation, editing,
and enumeration. See Huet"
:author "Rich Hickey"}
clojure.zip
(:refer-clojure :exclude (replace remove next)))
(defn zipper
"Creates a new zipper structure.
branch? is a fn that, given a node, returns true if can have
children, even if it currently doesn't.
children is a fn that, given a branch node, returns a seq of its
children.
make-node is a fn that, given an existing node and a seq of
children, returns a new branch node with the supplied children.
root is the root node."
{:added "1.0"}
[branch? children make-node root]
^{:zip/branch? branch? :zip/children children :zip/make-node make-node}
[root nil])
(defn seq-zip
"Returns a zipper for nested sequences, given a root sequence"
{:added "1.0"}
[root]
(zipper seq?
identity
(fn [node children] (with-meta children (meta node)))
root))
(defn vector-zip
"Returns a zipper for nested vectors, given a root vector"
{:added "1.0"}
[root]
(zipper vector?
seq
(fn [node children] (with-meta (vec children) (meta node)))
root))
(defn xml-zip
"Returns a zipper for xml elements (as from xml/parse),
given a root element"
{:added "1.0"}
[root]
(zipper (complement string?)
(comp seq :content)
(fn [node children]
(assoc node :content (and children (apply vector children))))
root))
(defn node
"Returns the node at loc"
{:added "1.0"}
[loc] (loc 0))
(defn branch?
"Returns true if the node at loc is a branch"
{:added "1.0"}
[loc]
((:zip/branch? (meta loc)) (node loc)))
(defn children
"Returns a seq of the children of node at loc, which must be a branch"
{:added "1.0"}
[loc]
(if (branch? loc)
((:zip/children (meta loc)) (node loc))
(throw (Exception. "called children on a leaf node"))))
(defn make-node
"Returns a new branch node, given an existing node and new
children. The loc is only used to supply the constructor."
{:added "1.0"}
[loc node children]
((:zip/make-node (meta loc)) node children))
(defn path
"Returns a seq of nodes leading to this loc"
{:added "1.0"}
[loc]
(:pnodes (loc 1)))
(defn lefts
"Returns a seq of the left siblings of this loc"
{:added "1.0"}
[loc]
(seq (:l (loc 1))))
(defn rights
"Returns a seq of the right siblings of this loc"
{:added "1.0"}
[loc]
(:r (loc 1)))
(defn down
"Returns the loc of the leftmost child of the node at this loc, or
nil if no children"
{:added "1.0"}
[loc]
(when (branch? loc)
(let [[node path] loc
[c & cnext :as cs] (children loc)]
(when cs
(with-meta [c {:l []
:pnodes (if path (conj (:pnodes path) node) [node])
:ppath path
:r cnext}] (meta loc))))))
(defn up
"Returns the loc of the parent of the node at this loc, or nil if at
the top"
{:added "1.0"}
[loc]
(let [[node {l :l, ppath :ppath, pnodes :pnodes r :r, changed? :changed?, :as path}] loc]
(when pnodes
(let [pnode (peek pnodes)]
(with-meta (if changed?
[(make-node loc pnode (concat l (cons node r)))
(and ppath (assoc ppath :changed? true))]
[pnode ppath])
(meta loc))))))
(defn root
"zips all the way up and returns the root node, reflecting any
changes."
{:added "1.0"}
[loc]
(if (= :end (loc 1))
(node loc)
(let [p (up loc)]
(if p
(recur p)
(node loc)))))
(defn right
"Returns the loc of the right sibling of the node at this loc, or nil"
{:added "1.0"}
[loc]
(let [[node {l :l [r & rnext :as rs] :r :as path}] loc]
(when (and path rs)
(with-meta [r (assoc path :l (conj l node) :r rnext)] (meta loc)))))
(defn rightmost
"Returns the loc of the rightmost sibling of the node at this loc, or self"
{:added "1.0"}
[loc]
(let [[node {l :l r :r :as path}] loc]
(if (and path r)
(with-meta [(last r) (assoc path :l (apply conj l node (butlast r)) :r nil)] (meta loc))
loc)))
(defn left
"Returns the loc of the left sibling of the node at this loc, or nil"
{:added "1.0"}
[loc]
(let [[node {l :l r :r :as path}] loc]
(when (and path (seq l))
(with-meta [(peek l) (assoc path :l (pop l) :r (cons node r))] (meta loc)))))
(defn leftmost
"Returns the loc of the leftmost sibling of the node at this loc, or self"
{:added "1.0"}
[loc]
(let [[node {l :l r :r :as path}] loc]
(if (and path (seq l))
(with-meta [(first l) (assoc path :l [] :r (concat (rest l) [node] r))] (meta loc))
loc)))
(defn insert-left
"Inserts the item as the left sibling of the node at this loc,
without moving"
{:added "1.0"}
[loc item]
(let [[node {l :l :as path}] loc]
(if (nil? path)
(throw (new Exception "Insert at top"))
(with-meta [node (assoc path :l (conj l item) :changed? true)] (meta loc)))))
(defn insert-right
"Inserts the item as the right sibling of the node at this loc,
without moving"
{:added "1.0"}
[loc item]
(let [[node {r :r :as path}] loc]
(if (nil? path)
(throw (new Exception "Insert at top"))
(with-meta [node (assoc path :r (cons item r) :changed? true)] (meta loc)))))
(defn replace
"Replaces the node at this loc, without moving"
{:added "1.0"}
[loc node]
(let [[_ path] loc]
(with-meta [node (assoc path :changed? true)] (meta loc))))
(defn edit
"Replaces the node at this loc with the value of (f node args)"
{:added "1.0"}
[loc f & args]
(replace loc (apply f (node loc) args)))
(defn insert-child
"Inserts the item as the leftmost child of the node at this loc,
without moving"
{:added "1.0"}
[loc item]
(replace loc (make-node loc (node loc) (cons item (children loc)))))
(defn append-child
"Inserts the item as the rightmost child of the node at this loc,
without moving"
{:added "1.0"}
[loc item]
(replace loc (make-node loc (node loc) (concat (children loc) [item]))))
(defn next
"Moves to the next loc in the hierarchy, depth-first. When reaching
the end, returns a distinguished loc detectable via end?. If already
at the end, stays there."
{:added "1.0"}
[loc]
(if (= :end (loc 1))
loc
(or
(and (branch? loc) (down loc))
(right loc)
(loop [p loc]
(if (up p)
(or (right (up p)) (recur (up p)))
[(node p) :end])))))
(defn prev
"Moves to the previous loc in the hierarchy, depth-first. If already
at the root, returns nil."
{:added "1.0"}
[loc]
(if-let [lloc (left loc)]
(loop [loc lloc]
(if-let [child (and (branch? loc) (down loc))]
(recur (rightmost child))
loc))
(up loc)))
(defn end?
"Returns true if loc represents the end of a depth-first walk"
{:added "1.0"}
[loc]
(= :end (loc 1)))
(defn remove
"Removes the node at loc, returning the loc that would have preceded
it in a depth-first walk."
{:added "1.0"}
[loc]
(let [[node {l :l, ppath :ppath, pnodes :pnodes, rs :r, :as path}] loc]
(if (nil? path)
(throw (new Exception "Remove at top"))
(if (pos? (count l))
(loop [loc (with-meta [(peek l) (assoc path :l (pop l) :changed? true)] (meta loc))]
(if-let [child (and (branch? loc) (down loc))]
(recur (rightmost child))
loc))
(with-meta [(make-node loc (peek pnodes) rs)
(and ppath (assoc ppath :changed? true))]
(meta loc))))))
(comment
(load-file "/Users/rich/dev/clojure/src/zip.clj")
(refer 'zip)
(def data '[[a * b] + [c * d]])
(def dz (vector-zip data))
(right (down (right (right (down dz)))))
(lefts (right (down (right (right (down dz))))))
(rights (right (down (right (right (down dz))))))
(up (up (right (down (right (right (down dz)))))))
(path (right (down (right (right (down dz))))))
(-> dz down right right down right)
(-> dz down right right down right (replace '/) root)
(-> dz next next (edit str) next next next (replace '/) root)
(-> dz next next next next next next next next next remove root)
(-> dz next next next next next next next next next remove (insert-right 'e) root)
(-> dz next next next next next next next next next remove up (append-child 'e) root)
(end? (-> dz next next next next next next next next next remove next))
(-> dz next remove next remove root)
(loop [loc dz]
(if (end? loc)
(root loc)
(recur (next (if (= '* (node loc))
(replace loc '/)
loc)))))
(loop [loc dz]
(if (end? loc)
(root loc)
(recur (next (if (= '* (node loc))
(remove loc)
loc)))))
)
| null | https://raw.githubusercontent.com/clojurecup2014/parade-route/adb2e1ea202228e3da07902849dee08f0bb8d81c/Assets/Clojure/Internal/Plugins/clojure/zip.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
functional hierarchical zipper, with navigation, editing and enumeration | Copyright ( c ) . All rights reserved .
see
(ns ^{:doc "Functional hierarchical zipper, with navigation, editing,
and enumeration. See Huet"
:author "Rich Hickey"}
clojure.zip
(:refer-clojure :exclude (replace remove next)))
(defn zipper
"Creates a new zipper structure.
branch? is a fn that, given a node, returns true if can have
children, even if it currently doesn't.
children is a fn that, given a branch node, returns a seq of its
children.
make-node is a fn that, given an existing node and a seq of
children, returns a new branch node with the supplied children.
root is the root node."
{:added "1.0"}
[branch? children make-node root]
^{:zip/branch? branch? :zip/children children :zip/make-node make-node}
[root nil])
(defn seq-zip
"Returns a zipper for nested sequences, given a root sequence"
{:added "1.0"}
[root]
(zipper seq?
identity
(fn [node children] (with-meta children (meta node)))
root))
(defn vector-zip
"Returns a zipper for nested vectors, given a root vector"
{:added "1.0"}
[root]
(zipper vector?
seq
(fn [node children] (with-meta (vec children) (meta node)))
root))
(defn xml-zip
"Returns a zipper for xml elements (as from xml/parse),
given a root element"
{:added "1.0"}
[root]
(zipper (complement string?)
(comp seq :content)
(fn [node children]
(assoc node :content (and children (apply vector children))))
root))
(defn node
"Returns the node at loc"
{:added "1.0"}
[loc] (loc 0))
(defn branch?
"Returns true if the node at loc is a branch"
{:added "1.0"}
[loc]
((:zip/branch? (meta loc)) (node loc)))
(defn children
"Returns a seq of the children of node at loc, which must be a branch"
{:added "1.0"}
[loc]
(if (branch? loc)
((:zip/children (meta loc)) (node loc))
(throw (Exception. "called children on a leaf node"))))
(defn make-node
"Returns a new branch node, given an existing node and new
children. The loc is only used to supply the constructor."
{:added "1.0"}
[loc node children]
((:zip/make-node (meta loc)) node children))
(defn path
"Returns a seq of nodes leading to this loc"
{:added "1.0"}
[loc]
(:pnodes (loc 1)))
(defn lefts
"Returns a seq of the left siblings of this loc"
{:added "1.0"}
[loc]
(seq (:l (loc 1))))
(defn rights
"Returns a seq of the right siblings of this loc"
{:added "1.0"}
[loc]
(:r (loc 1)))
(defn down
"Returns the loc of the leftmost child of the node at this loc, or
nil if no children"
{:added "1.0"}
[loc]
(when (branch? loc)
(let [[node path] loc
[c & cnext :as cs] (children loc)]
(when cs
(with-meta [c {:l []
:pnodes (if path (conj (:pnodes path) node) [node])
:ppath path
:r cnext}] (meta loc))))))
(defn up
"Returns the loc of the parent of the node at this loc, or nil if at
the top"
{:added "1.0"}
[loc]
(let [[node {l :l, ppath :ppath, pnodes :pnodes r :r, changed? :changed?, :as path}] loc]
(when pnodes
(let [pnode (peek pnodes)]
(with-meta (if changed?
[(make-node loc pnode (concat l (cons node r)))
(and ppath (assoc ppath :changed? true))]
[pnode ppath])
(meta loc))))))
(defn root
"zips all the way up and returns the root node, reflecting any
changes."
{:added "1.0"}
[loc]
(if (= :end (loc 1))
(node loc)
(let [p (up loc)]
(if p
(recur p)
(node loc)))))
(defn right
"Returns the loc of the right sibling of the node at this loc, or nil"
{:added "1.0"}
[loc]
(let [[node {l :l [r & rnext :as rs] :r :as path}] loc]
(when (and path rs)
(with-meta [r (assoc path :l (conj l node) :r rnext)] (meta loc)))))
(defn rightmost
"Returns the loc of the rightmost sibling of the node at this loc, or self"
{:added "1.0"}
[loc]
(let [[node {l :l r :r :as path}] loc]
(if (and path r)
(with-meta [(last r) (assoc path :l (apply conj l node (butlast r)) :r nil)] (meta loc))
loc)))
(defn left
"Returns the loc of the left sibling of the node at this loc, or nil"
{:added "1.0"}
[loc]
(let [[node {l :l r :r :as path}] loc]
(when (and path (seq l))
(with-meta [(peek l) (assoc path :l (pop l) :r (cons node r))] (meta loc)))))
(defn leftmost
"Returns the loc of the leftmost sibling of the node at this loc, or self"
{:added "1.0"}
[loc]
(let [[node {l :l r :r :as path}] loc]
(if (and path (seq l))
(with-meta [(first l) (assoc path :l [] :r (concat (rest l) [node] r))] (meta loc))
loc)))
(defn insert-left
"Inserts the item as the left sibling of the node at this loc,
without moving"
{:added "1.0"}
[loc item]
(let [[node {l :l :as path}] loc]
(if (nil? path)
(throw (new Exception "Insert at top"))
(with-meta [node (assoc path :l (conj l item) :changed? true)] (meta loc)))))
(defn insert-right
"Inserts the item as the right sibling of the node at this loc,
without moving"
{:added "1.0"}
[loc item]
(let [[node {r :r :as path}] loc]
(if (nil? path)
(throw (new Exception "Insert at top"))
(with-meta [node (assoc path :r (cons item r) :changed? true)] (meta loc)))))
(defn replace
"Replaces the node at this loc, without moving"
{:added "1.0"}
[loc node]
(let [[_ path] loc]
(with-meta [node (assoc path :changed? true)] (meta loc))))
(defn edit
"Replaces the node at this loc with the value of (f node args)"
{:added "1.0"}
[loc f & args]
(replace loc (apply f (node loc) args)))
(defn insert-child
"Inserts the item as the leftmost child of the node at this loc,
without moving"
{:added "1.0"}
[loc item]
(replace loc (make-node loc (node loc) (cons item (children loc)))))
(defn append-child
"Inserts the item as the rightmost child of the node at this loc,
without moving"
{:added "1.0"}
[loc item]
(replace loc (make-node loc (node loc) (concat (children loc) [item]))))
(defn next
"Moves to the next loc in the hierarchy, depth-first. When reaching
the end, returns a distinguished loc detectable via end?. If already
at the end, stays there."
{:added "1.0"}
[loc]
(if (= :end (loc 1))
loc
(or
(and (branch? loc) (down loc))
(right loc)
(loop [p loc]
(if (up p)
(or (right (up p)) (recur (up p)))
[(node p) :end])))))
(defn prev
"Moves to the previous loc in the hierarchy, depth-first. If already
at the root, returns nil."
{:added "1.0"}
[loc]
(if-let [lloc (left loc)]
(loop [loc lloc]
(if-let [child (and (branch? loc) (down loc))]
(recur (rightmost child))
loc))
(up loc)))
(defn end?
"Returns true if loc represents the end of a depth-first walk"
{:added "1.0"}
[loc]
(= :end (loc 1)))
(defn remove
"Removes the node at loc, returning the loc that would have preceded
it in a depth-first walk."
{:added "1.0"}
[loc]
(let [[node {l :l, ppath :ppath, pnodes :pnodes, rs :r, :as path}] loc]
(if (nil? path)
(throw (new Exception "Remove at top"))
(if (pos? (count l))
(loop [loc (with-meta [(peek l) (assoc path :l (pop l) :changed? true)] (meta loc))]
(if-let [child (and (branch? loc) (down loc))]
(recur (rightmost child))
loc))
(with-meta [(make-node loc (peek pnodes) rs)
(and ppath (assoc ppath :changed? true))]
(meta loc))))))
(comment
(load-file "/Users/rich/dev/clojure/src/zip.clj")
(refer 'zip)
(def data '[[a * b] + [c * d]])
(def dz (vector-zip data))
(right (down (right (right (down dz)))))
(lefts (right (down (right (right (down dz))))))
(rights (right (down (right (right (down dz))))))
(up (up (right (down (right (right (down dz)))))))
(path (right (down (right (right (down dz))))))
(-> dz down right right down right)
(-> dz down right right down right (replace '/) root)
(-> dz next next (edit str) next next next (replace '/) root)
(-> dz next next next next next next next next next remove root)
(-> dz next next next next next next next next next remove (insert-right 'e) root)
(-> dz next next next next next next next next next remove up (append-child 'e) root)
(end? (-> dz next next next next next next next next next remove next))
(-> dz next remove next remove root)
(loop [loc dz]
(if (end? loc)
(root loc)
(recur (next (if (= '* (node loc))
(replace loc '/)
loc)))))
(loop [loc dz]
(if (end? loc)
(root loc)
(recur (next (if (= '* (node loc))
(remove loc)
loc)))))
)
|
1423003e806e0ed120ea939e79e53120109284ff8dfa2403b57ee44da8d08cd9 | frenetic-lang/netcore-1.0 | ShortestPath.hs | module ShortestPath
where
import qualified Debug.Trace as Trace
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Maybe
import Frenetic.NetCore
import Frenetic.NetCore.Semantics
import Frenetic.Topo
import Frenetic.TopoParser
type Node = Int
adjacent :: Topo -> Node -> Node -> Bool
adjacent gr n1 n2 =
Data.Maybe.isJust (getEdgeLabel gr n1 n2)
set_up_distances :: Topo -> Map.Map (Node, Node) (Maybe Int)
set_up_distances graph =
let nodes = switches graph in
foldl (\m n1 -> foldl (\m n2 ->
let val =
if n1 == n2 then Just 0 else
if adjacent graph n1 n2 then Just 1 else
Nothing in
Map.insert (n1, n2) val m) m nodes)
Map.empty nodes
set_up_nexts :: Topo -> Map.Map (Node, Node) (Maybe Node)
set_up_nexts graph =
let nodes = switches graph in
foldl (\m n1 ->
foldl (\m n2 ->
Map.insert (n1, n2) Nothing m) m nodes) Map.empty nodes
floydWarshall :: Topo -> (Map.Map (Node, Node) (Maybe Int), Map.Map (Node, Node) (Maybe Node))
floydWarshall graph =
let innerLoop (dists, nexts, knode, inode) jnode =
--Note that the default case below should never hapen
let distIJ = Map.findWithDefault Nothing (inode, jnode) dists
distIK = Map.findWithDefault Nothing (inode, knode) dists
distKJ = Map.findWithDefault Nothing (knode, jnode) dists
curNext = Map.findWithDefault Nothing (inode, jnode) nexts in
let newval (Just ij) (Just ik) (Just kj) =
if ij > ik + kj then (Just (ik + kj), Just knode)
else (Just ij, curNext)
newval Nothing (Just ik) (Just kj) = (Just (ik + kj), Just knode)
newval (Just ij) _ _ = (Just (ij), curNext)
newval _ _ _ = (Nothing, curNext) in
let (newDist, newNext) = newval distIJ distIK distKJ in
(Map.insert (inode, jnode) newDist dists,
Map.insert (inode, jnode) newNext nexts, knode, inode)
middleLoop (dists, nexts, knode) inode =
let (dists2, nexts2, knode2, inode2) =
foldl innerLoop (dists, nexts, knode, inode) nodes in
(dists2, nexts2, knode2)
outerLoop (dists, nexts) knode =
let (dists2, nexts2, knode2) =
foldl middleLoop (dists, nexts, knode) nodes in
(dists2, nexts2)
nodes = switches graph in
foldl outerLoop (set_up_distances graph, set_up_nexts graph) nodes
Finds the shortest path from one node to another using the results
of the floydWarshall methdod . The path is a maybe list of
the next node to go to and the port to get there .
of the floydWarshall methdod. The path is a maybe list of
the next node to go to and the port to get there.
-}
findPath :: Topo ->
(Map.Map (Node,Node) (Maybe Int),
Map.Map (Node,Node) (Maybe Node))
-> Node -> Node-> Maybe [(Node, Port)]
findPath graph (dists, nexts) fromNode toNode =
if Data.Maybe.isNothing (Map.findWithDefault Nothing (fromNode, toNode) dists)
then Nothing else
(Just (processPath graph fromNode (findPathHelper nexts fromNode toNode)))
findPathHelper :: Map.Map (Node, Node) (Maybe Node) -> Node -> Node-> [Node]
findPathHelper nexts fromNode toNode =
case Map.findWithDefault Nothing (fromNode, toNode) nexts of
Just n -> (findPathHelper nexts fromNode n) ++
(findPathHelper nexts n toNode)
Nothing -> [toNode]
processPath :: Topo -> Node -> [Node] -> [(Node, Port)]
processPath graph start nodeList =
let (newLst, _) = foldl (\(lst, prev) node ->
case getEdgeLabel graph prev node of
Just b -> ((prev, b):lst, node)
Nothing -> ([], node) --Shoudn't happen, all edges should exist
) ([], start) nodeList in
reverse newLst
Assumes that hosts have exactly one port , port 0 , as definined in Topo .
makePolicy :: Topo -> Policy
makePolicy graph =
let (dists, nexts) = floydWarshall graph
hostList = hosts graph
updateList lst host ((s, p):t) =
case getEdgeLabel graph s host of
Just port -> (host,s,port):lst
_ -> lst
updateList lst host [] = lst
hostSwitchList =
foldl (\lst h -> updateList lst h (lPorts graph h)) [] hostList in
let pol = foldl (\policy (h1, n1, p1) ->
foldl (\policy (h2, n2, p2) ->
if n1 == n2 then policy else
let path = findPath graph (dists, nexts) n1 n2 in
case path of
Nothing -> policy
Just p->
foldl (\policy (ni, pi) ->
PoBasic
(DlSrc (EthernetAddress (fromIntegral h1)) `And`
DlDst (EthernetAddress (fromIntegral h2)) `And`
Switch (fromIntegral ni))
[Forward (Physical pi) unmodified]
`PoUnion` policy)
policy p) policy hostSwitchList)
PoBottom hostSwitchList in
foldl (\policy (host, node, port) ->
PoBasic (DlDst (EthernetAddress (fromIntegral host))
`And` Switch (fromIntegral node))
[Forward (Physical port) unmodified]
`PoUnion` policy) pol hostSwitchList
--sample data from the net command of mininet
netOutput :: String
netOutput = "s5 <-> s6-eth3 s7-eth3\n" ++
"s6 <-> h1-eth0 h2-eth0 s5-eth1\n" ++
"s7 <-> h3-eth0 h4-eth0 s5-eth2"
--If the network could not be parsed, make an empty graph
buildTopo (Left(error)) = buildGraph []
buildTopo (Right(list)) = buildGraph (makeEdgeList list)
main addr = controller addr (makePolicy (buildTopo (parseTopo netOutput))) | null | https://raw.githubusercontent.com/frenetic-lang/netcore-1.0/976b08b740027e8ed19f2d55b1e77f663bee6f02/examples/ShortestPath.hs | haskell | Note that the default case below should never hapen
Shoudn't happen, all edges should exist
sample data from the net command of mininet
If the network could not be parsed, make an empty graph | module ShortestPath
where
import qualified Debug.Trace as Trace
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Maybe
import Frenetic.NetCore
import Frenetic.NetCore.Semantics
import Frenetic.Topo
import Frenetic.TopoParser
type Node = Int
adjacent :: Topo -> Node -> Node -> Bool
adjacent gr n1 n2 =
Data.Maybe.isJust (getEdgeLabel gr n1 n2)
set_up_distances :: Topo -> Map.Map (Node, Node) (Maybe Int)
set_up_distances graph =
let nodes = switches graph in
foldl (\m n1 -> foldl (\m n2 ->
let val =
if n1 == n2 then Just 0 else
if adjacent graph n1 n2 then Just 1 else
Nothing in
Map.insert (n1, n2) val m) m nodes)
Map.empty nodes
set_up_nexts :: Topo -> Map.Map (Node, Node) (Maybe Node)
set_up_nexts graph =
let nodes = switches graph in
foldl (\m n1 ->
foldl (\m n2 ->
Map.insert (n1, n2) Nothing m) m nodes) Map.empty nodes
floydWarshall :: Topo -> (Map.Map (Node, Node) (Maybe Int), Map.Map (Node, Node) (Maybe Node))
floydWarshall graph =
let innerLoop (dists, nexts, knode, inode) jnode =
let distIJ = Map.findWithDefault Nothing (inode, jnode) dists
distIK = Map.findWithDefault Nothing (inode, knode) dists
distKJ = Map.findWithDefault Nothing (knode, jnode) dists
curNext = Map.findWithDefault Nothing (inode, jnode) nexts in
let newval (Just ij) (Just ik) (Just kj) =
if ij > ik + kj then (Just (ik + kj), Just knode)
else (Just ij, curNext)
newval Nothing (Just ik) (Just kj) = (Just (ik + kj), Just knode)
newval (Just ij) _ _ = (Just (ij), curNext)
newval _ _ _ = (Nothing, curNext) in
let (newDist, newNext) = newval distIJ distIK distKJ in
(Map.insert (inode, jnode) newDist dists,
Map.insert (inode, jnode) newNext nexts, knode, inode)
middleLoop (dists, nexts, knode) inode =
let (dists2, nexts2, knode2, inode2) =
foldl innerLoop (dists, nexts, knode, inode) nodes in
(dists2, nexts2, knode2)
outerLoop (dists, nexts) knode =
let (dists2, nexts2, knode2) =
foldl middleLoop (dists, nexts, knode) nodes in
(dists2, nexts2)
nodes = switches graph in
foldl outerLoop (set_up_distances graph, set_up_nexts graph) nodes
Finds the shortest path from one node to another using the results
of the floydWarshall methdod . The path is a maybe list of
the next node to go to and the port to get there .
of the floydWarshall methdod. The path is a maybe list of
the next node to go to and the port to get there.
-}
findPath :: Topo ->
(Map.Map (Node,Node) (Maybe Int),
Map.Map (Node,Node) (Maybe Node))
-> Node -> Node-> Maybe [(Node, Port)]
findPath graph (dists, nexts) fromNode toNode =
if Data.Maybe.isNothing (Map.findWithDefault Nothing (fromNode, toNode) dists)
then Nothing else
(Just (processPath graph fromNode (findPathHelper nexts fromNode toNode)))
findPathHelper :: Map.Map (Node, Node) (Maybe Node) -> Node -> Node-> [Node]
findPathHelper nexts fromNode toNode =
case Map.findWithDefault Nothing (fromNode, toNode) nexts of
Just n -> (findPathHelper nexts fromNode n) ++
(findPathHelper nexts n toNode)
Nothing -> [toNode]
processPath :: Topo -> Node -> [Node] -> [(Node, Port)]
processPath graph start nodeList =
let (newLst, _) = foldl (\(lst, prev) node ->
case getEdgeLabel graph prev node of
Just b -> ((prev, b):lst, node)
) ([], start) nodeList in
reverse newLst
Assumes that hosts have exactly one port , port 0 , as definined in Topo .
makePolicy :: Topo -> Policy
makePolicy graph =
let (dists, nexts) = floydWarshall graph
hostList = hosts graph
updateList lst host ((s, p):t) =
case getEdgeLabel graph s host of
Just port -> (host,s,port):lst
_ -> lst
updateList lst host [] = lst
hostSwitchList =
foldl (\lst h -> updateList lst h (lPorts graph h)) [] hostList in
let pol = foldl (\policy (h1, n1, p1) ->
foldl (\policy (h2, n2, p2) ->
if n1 == n2 then policy else
let path = findPath graph (dists, nexts) n1 n2 in
case path of
Nothing -> policy
Just p->
foldl (\policy (ni, pi) ->
PoBasic
(DlSrc (EthernetAddress (fromIntegral h1)) `And`
DlDst (EthernetAddress (fromIntegral h2)) `And`
Switch (fromIntegral ni))
[Forward (Physical pi) unmodified]
`PoUnion` policy)
policy p) policy hostSwitchList)
PoBottom hostSwitchList in
foldl (\policy (host, node, port) ->
PoBasic (DlDst (EthernetAddress (fromIntegral host))
`And` Switch (fromIntegral node))
[Forward (Physical port) unmodified]
`PoUnion` policy) pol hostSwitchList
netOutput :: String
netOutput = "s5 <-> s6-eth3 s7-eth3\n" ++
"s6 <-> h1-eth0 h2-eth0 s5-eth1\n" ++
"s7 <-> h3-eth0 h4-eth0 s5-eth2"
buildTopo (Left(error)) = buildGraph []
buildTopo (Right(list)) = buildGraph (makeEdgeList list)
main addr = controller addr (makePolicy (buildTopo (parseTopo netOutput))) |
2f7a8bc7e4cb0feab3d438697648db2f542a81c335fefb4a42584ec620da62f6 | samrushing/irken-compiler | t_tail.scm |
(define (+ a b)
(%%cexp (int int -> int) "%0+%1" a b))
(define (thing1 x)
(define (thing2)
(+ 10 x)
)
(thing2)
)
(thing1 5)
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/t_tail.scm | scheme |
(define (+ a b)
(%%cexp (int int -> int) "%0+%1" a b))
(define (thing1 x)
(define (thing2)
(+ 10 x)
)
(thing2)
)
(thing1 5)
| |
0a6f11d7f845a60f7f73f7a9624adb2c19a97351149353a6e5d5a2ef535232d0 | ugglan/cljaws | sdb_test.clj | (ns cljaws.sdb-test
(:use (cljaws core sdb core-test helpers) :reload-all)
(:use [clojure.test]))
(def timeout-seconds 15)
(deftest list-domains-test
(let [domain-name (make-unique-name "domain")
domain-name2 (make-unique-name "domain")]
(with-aws :sdb
(create-domain domain-name)
(let [result (list-domains)]
(is (seq? result))
(is (pos? (count result))
"Should get list of available domains")
(is (string? (first result))))
(is (while-or-timeout
false? timeout-seconds
(contains-string? (list-domains) domain-name))
"Is this domain created?")
; commands should now autocreate domain if needed
(with-domain domain-name2
(add-attributes :row1 {:color "red" :name "apple"})
(while-or-timeout
false? timeout-seconds
(= 1 (count (select (str "* from `" domain-name2 "`")))))
(let [result (select (str "* from `" domain-name2 "`") )]
(is (= 1 (count result)))
(is (= "red" (:color (second (first result)))))
(is (= "apple" (:name (second (first result))))))
; implicit delete
(delete-domain))
;explicit delete
(delete-domain domain-name)
(is (while-or-timeout
false? timeout-seconds
(not (contains-string? (list-domains) domain-name))))
(is (while-or-timeout
false? timeout-seconds
(not (contains-string? (list-domains) domain-name2))))))) | null | https://raw.githubusercontent.com/ugglan/cljaws/0df2312d61e6c7d52520479b3c103858c72e9f5b/test/cljaws/sdb_test.clj | clojure | commands should now autocreate domain if needed
implicit delete
explicit delete | (ns cljaws.sdb-test
(:use (cljaws core sdb core-test helpers) :reload-all)
(:use [clojure.test]))
(def timeout-seconds 15)
(deftest list-domains-test
(let [domain-name (make-unique-name "domain")
domain-name2 (make-unique-name "domain")]
(with-aws :sdb
(create-domain domain-name)
(let [result (list-domains)]
(is (seq? result))
(is (pos? (count result))
"Should get list of available domains")
(is (string? (first result))))
(is (while-or-timeout
false? timeout-seconds
(contains-string? (list-domains) domain-name))
"Is this domain created?")
(with-domain domain-name2
(add-attributes :row1 {:color "red" :name "apple"})
(while-or-timeout
false? timeout-seconds
(= 1 (count (select (str "* from `" domain-name2 "`")))))
(let [result (select (str "* from `" domain-name2 "`") )]
(is (= 1 (count result)))
(is (= "red" (:color (second (first result)))))
(is (= "apple" (:name (second (first result))))))
(delete-domain))
(delete-domain domain-name)
(is (while-or-timeout
false? timeout-seconds
(not (contains-string? (list-domains) domain-name))))
(is (while-or-timeout
false? timeout-seconds
(not (contains-string? (list-domains) domain-name2))))))) |
6d71714bb707db61b525b115dc2e1becdc4044043d50d70951c225d64fc2767b | pink-gorilla/webly | deps.cljs | {:npm-deps
{; fonts
"@fortawesome/fontawesome-free" "^5.14.0"
"get-google-fonts" "^1.2.2"
; tailwind
"tailwindcss" "2.1.2"
"autoprefixer" "^10.0.2" ; peer dependency of tailwind. actually needed?
"postcss" "^8.1.13" ; peer dependency of tailwind
;
}}
| null | https://raw.githubusercontent.com/pink-gorilla/webly/66f0e64bff60b85b1a8b4b1a2a1ef09e6ad50960/frontend/src/frontend/deps.cljs | clojure | fonts
tailwind
peer dependency of tailwind. actually needed?
peer dependency of tailwind
| {:npm-deps
"@fortawesome/fontawesome-free" "^5.14.0"
"get-google-fonts" "^1.2.2"
"tailwindcss" "2.1.2"
}}
|
77601b27ab2b4d5889163e4814e325f710aa30c494aef68d4e0ea61adb74c541 | agrafix/Spock | Spec.hs | module Main where
import Test.Hspec
import qualified Web.Spock.CsrfSpec
import qualified Web.Spock.Internal.SessionManagerSpec
import qualified Web.Spock.Internal.SessionVaultSpec
import qualified Web.Spock.SafeSpec
main :: IO ()
main = hspec $
do
Web.Spock.Internal.SessionVaultSpec.spec
Web.Spock.Internal.SessionManagerSpec.spec
Web.Spock.SafeSpec.spec
Web.Spock.CsrfSpec.spec
| null | https://raw.githubusercontent.com/agrafix/Spock/6055362b54f2fae5418188c3fc2fc1659ca43e79/Spock/test/Spec.hs | haskell | module Main where
import Test.Hspec
import qualified Web.Spock.CsrfSpec
import qualified Web.Spock.Internal.SessionManagerSpec
import qualified Web.Spock.Internal.SessionVaultSpec
import qualified Web.Spock.SafeSpec
main :: IO ()
main = hspec $
do
Web.Spock.Internal.SessionVaultSpec.spec
Web.Spock.Internal.SessionManagerSpec.spec
Web.Spock.SafeSpec.spec
Web.Spock.CsrfSpec.spec
| |
52789eebde00f233d9fc949651661207167e19d1192430540cdff2b82b54c6bc | ahjones/lein-rpm | core.clj | (ns plugin.test.core
(:use [plugin.core])
(:use [clojure.test]))
(deftest replace-me ;; FIXME: write
(is false "No tests have been written."))
| null | https://raw.githubusercontent.com/ahjones/lein-rpm/eca4d93690db41a2d7c8a7eeaf9df879476b5c6d/test/plugin/test/core.clj | clojure | FIXME: write | (ns plugin.test.core
(:use [plugin.core])
(:use [clojure.test]))
(is false "No tests have been written."))
|
57346291b6d3cac99921bb5f195d81f9884e9db756be3b60223765db56c7c658 | let-def/ttx | ttypes.mli | open Ttx_base
type ('a, 'b) binder = ('a, 'b) Binder.t
module Arg_label : sig
type t =
| Nolabel
| Labelled of string
| Optional of string
end
type arg_label = Arg_label.t
module Type_expr : sig
include INDEXABLE
type arg_label =
| Nolabel
| Labelled of string
| Optional of string
type desc =
| Tarrow of arg_label * t * t
| Ttuple of t list
| Tconstr of t list * path
val desc : t -> desc
end
module type LOCATED = sig
include INDEXABLE
val location :
end
module Value : sig
include INDEXABLE
end
(* Value descriptions *)
type value_description =
{ val_type: type_expr; (* Type of the value *)
val_kind: value_kind;
val_loc: Location.t;
val_attributes: Parsetree.attributes;
}
and value_kind =
Val_reg (* Regular value *)
| Val_prim of Primitive.description (* Primitive *)
| Val_ivar of mutable_flag * string (* Instance variable (mutable ?) *)
| Val_self of class_signature * self_meths * Ident.t Vars.t * string
(* Self *)
| Val_anc of class_signature * Ident.t Meths.t * string
(* Ancestor *)
and self_meths =
| Self_concrete of Ident.t Meths.t
| Self_virtual of Ident.t Meths.t ref
and class_signature =
{ csig_self: type_expr;
mutable csig_self_row: type_expr;
mutable csig_vars: (mutable_flag * virtual_flag * type_expr) Vars.t;
mutable csig_meths: (private_flag * virtual_flag * type_expr) Meths.t; }
(* Variance *)
module Variance : sig
type t
type f =
May_pos (* allow positive occurrences *)
| May_neg (* allow negative occurrences *)
| May_weak (* allow occurrences under a negative position *)
| Inj (* type is injective in this parameter *)
| Pos (* there is a positive occurrence *)
| Neg (* there is a negative occurrence *)
| Inv (* both negative and positive occurrences *)
val null : t (* no occurrence *)
val full : t (* strictly invariant (all flags) *)
strictly covariant ( May_pos , Pos and Inj )
val unknown : t (* allow everything, guarantee nothing *)
val union : t -> t -> t
val inter : t -> t -> t
val subset : t -> t -> bool
val eq : t -> t -> bool
val set : f -> bool -> t -> t
val mem : f -> t -> bool
val conjugate : t -> t (* exchange positive and negative *)
val get_upper : t -> bool * bool (* may_pos, may_neg *)
pos , neg , inv ,
val unknown_signature : injective:bool -> arity:int -> t list
(** The most pessimistic variance for a completely unknown type. *)
end
module Separability : sig
(** see {!Typedecl_separability} for an explanation of separability
and separability modes.*)
type t = Ind | Sep | Deepsep
val eq : t -> t -> bool
val print : Format.formatter -> t -> unit
val rank : t -> int
* Modes are ordered from the least to the most demanding :
Ind < Sep < Deepsep .
' rank ' maps them to integers in an order - respecting way :
= > rank m1 < rank m2
Ind < Sep < Deepsep.
'rank' maps them to integers in an order-respecting way:
m1 < m2 <=> rank m1 < rank m2 *)
val compare : t -> t -> int
* Compare two mode according to their mode ordering .
val max : t -> t -> t
* [ max_mode ] returns the most demanding mode . It is used to
express the conjunction of two parameter mode constraints .
express the conjunction of two parameter mode constraints. *)
type signature = t list
(** The 'separability signature' of a type assigns a mode for
each of its parameters. [('a, 'b) t] has mode [(m1, m2)] if
[(t1, t2) t] is separable whenever [t1, t2] have mode [m1, m2]. *)
val print_signature : Format.formatter -> signature -> unit
val default_signature : arity:int -> signature
(** The most pessimistic separability for a completely unknown type. *)
end
(* Type definitions *)
type type_declaration =
{ type_params: type_expr list;
type_arity: int;
type_kind: type_decl_kind;
type_private: private_flag;
type_manifest: type_expr option;
type_variance: Variance.t list;
(* covariant, contravariant, weakly contravariant, injective *)
type_separability: Separability.t list;
type_is_newtype: bool;
type_expansion_scope: int;
type_loc: Location.t;
type_attributes: Parsetree.attributes;
type_immediate: Type_immediacy.t;
type_unboxed_default: bool;
(* true if the unboxed-ness of this type was chosen by a compiler flag *)
type_uid: Uid.t;
}
and type_decl_kind = (label_declaration, constructor_declaration) type_kind
and ('lbl, 'cstr) type_kind =
Type_abstract
| Type_record of 'lbl list * record_representation
| Type_variant of 'cstr list * variant_representation
| Type_open
and record_representation =
Record_regular (* All fields are boxed / tagged *)
| Record_float (* All fields are floats *)
| Record_unboxed of bool (* Unboxed single-field record, inlined or not *)
Inlined record
Inlined record under extension
and variant_representation =
Variant_regular (* Constant or boxed constructors *)
One unboxed single - field constructor
and label_declaration =
{
ld_id: Ident.t;
ld_mutable: mutable_flag;
ld_type: type_expr;
ld_loc: Location.t;
ld_attributes: Parsetree.attributes;
ld_uid: Uid.t;
}
and constructor_declaration =
{
cd_id: Ident.t;
cd_args: constructor_arguments;
cd_res: type_expr option;
cd_loc: Location.t;
cd_attributes: Parsetree.attributes;
cd_uid: Uid.t;
}
and constructor_arguments =
| Cstr_tuple of type_expr list
| Cstr_record of label_declaration list
type extension_constructor =
{
ext_type_path: Path.t;
ext_type_params: type_expr list;
ext_args: constructor_arguments;
ext_ret_type: type_expr option;
ext_private: private_flag;
ext_loc: Location.t;
ext_attributes: Parsetree.attributes;
ext_uid: Uid.t;
}
and type_transparence =
Type_public (* unrestricted expansion *)
| Type_new (* "new" type *)
| Type_private (* private type *)
(* Type expressions for the class language *)
type class_type =
Cty_constr of Path.t * type_expr list * class_type
| Cty_signature of class_signature
| Cty_arrow of arg_label * type_expr * class_type
type class_declaration =
{ cty_params: type_expr list;
mutable cty_type: class_type;
cty_path: Path.t;
cty_new: type_expr option;
cty_variance: Variance.t list;
cty_loc: Location.t;
cty_attributes: Parsetree.attributes;
cty_uid: Uid.t;
}
type class_type_declaration =
{ clty_params: type_expr list;
clty_type: class_type;
clty_path: Path.t;
clty_variance: Variance.t list;
clty_loc: Location.t;
clty_attributes: Parsetree.attributes;
clty_uid: Uid.t;
}
(* Type expressions for the module language *)
type visibility =
| Exported
| Hidden
type module_type =
Mty_ident of Path.t
| Mty_signature of signature
| Mty_functor of functor_parameter * module_type
| Mty_alias of Path.t
and functor_parameter =
| Unit
| Named of Ident.t option * module_type
and module_presence =
| Mp_present
| Mp_absent
and signature = signature_item list
and signature_item =
Sig_value of Ident.t * value_description * visibility
| Sig_type of Ident.t * type_declaration * rec_status * visibility
| Sig_typext of Ident.t * extension_constructor * ext_status * visibility
| Sig_module of
Ident.t * module_presence * module_declaration * rec_status * visibility
| Sig_modtype of Ident.t * modtype_declaration * visibility
| Sig_class of Ident.t * class_declaration * rec_status * visibility
| Sig_class_type of Ident.t * class_type_declaration * rec_status * visibility
and module_declaration =
{
md_type: module_type;
md_attributes: Parsetree.attributes;
md_loc: Location.t;
md_uid: Uid.t;
}
and modtype_declaration =
{
mtd_type: module_type option; (* None: abstract *)
mtd_attributes: Parsetree.attributes;
mtd_loc: Location.t;
mtd_uid: Uid.t;
}
and rec_status =
first in a nonrecursive group
first in a recursive group
not first in a recursive / nonrecursive group
and ext_status =
Text_first (* first constructor in an extension *)
not first constructor in an extension
| Text_exception
(* Constructor and record label descriptions inserted held in typing
environments *)
type constructor_description =
{ cstr_name: string; (* Constructor name *)
cstr_res: type_expr; (* Type of the result *)
cstr_existentials: type_expr list; (* list of existentials *)
cstr_args: type_expr list; (* Type of the arguments *)
cstr_arity: int; (* Number of arguments *)
cstr_tag: constructor_tag; (* Tag for heap blocks *)
cstr_consts: int; (* Number of constant constructors *)
cstr_nonconsts: int; (* Number of non-const constructors *)
Constrained return type ?
cstr_private: private_flag; (* Read-only constructor? *)
cstr_loc: Location.t;
cstr_attributes: Parsetree.attributes;
cstr_inlined: type_declaration option;
cstr_uid: Uid.t;
}
and constructor_tag =
Cstr_constant of int (* Constant constructor (an int) *)
| Cstr_block of int (* Regular constructor (a block) *)
Constructor of an unboxed type
| Cstr_extension of Path.t * bool (* Extension constructor
true if a constant false if a block*)
(* Constructors are the same *)
val equal_tag : constructor_tag -> constructor_tag -> bool
(* Constructors may be the same, given potential rebinding *)
val may_equal_constr :
constructor_description -> constructor_description -> bool
type label_description =
{ lbl_name: string; (* Short name *)
lbl_res: type_expr; (* Type of the result *)
lbl_arg: type_expr; (* Type of the argument *)
lbl_mut: mutable_flag; (* Is this a mutable field? *)
lbl_pos: int; (* Position in block *)
lbl_all: label_description array; (* All the labels in this type *)
lbl_repres: record_representation; (* Representation for this record *)
lbl_private: private_flag; (* Read-only field? *)
lbl_loc: Location.t;
lbl_attributes: Parsetree.attributes;
lbl_uid: Uid.t;
}
(** Extracts the list of "value" identifiers bound by a signature.
"Value" identifiers are identifiers for signature components that
correspond to a run-time value: values, extensions, modules, classes.
Note: manifest primitives do not correspond to a run-time value! *)
val bound_value_identifiers: signature -> Ident.t list
val signature_item_id : signature_item -> Ident.t
(**** Utilities for backtracking ****)
type snapshot
(* A snapshot for backtracking *)
val snapshot: unit -> snapshot
(* Make a snapshot for later backtracking. Costs nothing *)
val backtrack: cleanup_abbrev:(unit -> unit) -> snapshot -> unit
(* Backtrack to a given snapshot. Only possible if you have
not already backtracked to a previous snapshot.
Calls [cleanup_abbrev] internally *)
val undo_first_change_after: snapshot -> unit
Backtrack only the first change after a snapshot .
Does not update the list of changes
Does not update the list of changes *)
val undo_compress: snapshot -> unit
(* Backtrack only path compression. Only meaningful if you have
not already backtracked to a previous snapshot.
Does not call [cleanup_abbrev] *)
* Functions to use when modifying a type ( only Ctype ? ) .
The old values are logged and reverted on backtracking .
The old values are logged and reverted on backtracking.
*)
val link_type: type_expr -> type_expr -> unit
(* Set the desc field of [t1] to [Tlink t2], logging the old
value if there is an active snapshot *)
val set_type_desc: type_expr -> type_desc -> unit
(* Set directly the desc field, without sharing *)
val set_level: type_expr -> int -> unit
val set_scope: type_expr -> int -> unit
val set_name:
(Path.t * type_expr list) option ref ->
(Path.t * type_expr list) option -> unit
val link_row_field_ext: inside:row_field -> row_field -> unit
Extract the extension variable of [ inside ] and set it to the
second argument
second argument *)
val set_univar: type_expr option ref -> type_expr -> unit
val link_kind: inside:field_kind -> field_kind -> unit
val link_commu: inside:commutable -> commutable -> unit
val set_commu_ok: commutable -> unit
| null | https://raw.githubusercontent.com/let-def/ttx/0a50ba7253056d1202f108b67faf4d9cc78e020d/attic/attempt0/ttypes.mli | ocaml | Value descriptions
Type of the value
Regular value
Primitive
Instance variable (mutable ?)
Self
Ancestor
Variance
allow positive occurrences
allow negative occurrences
allow occurrences under a negative position
type is injective in this parameter
there is a positive occurrence
there is a negative occurrence
both negative and positive occurrences
no occurrence
strictly invariant (all flags)
allow everything, guarantee nothing
exchange positive and negative
may_pos, may_neg
* The most pessimistic variance for a completely unknown type.
* see {!Typedecl_separability} for an explanation of separability
and separability modes.
* The 'separability signature' of a type assigns a mode for
each of its parameters. [('a, 'b) t] has mode [(m1, m2)] if
[(t1, t2) t] is separable whenever [t1, t2] have mode [m1, m2].
* The most pessimistic separability for a completely unknown type.
Type definitions
covariant, contravariant, weakly contravariant, injective
true if the unboxed-ness of this type was chosen by a compiler flag
All fields are boxed / tagged
All fields are floats
Unboxed single-field record, inlined or not
Constant or boxed constructors
unrestricted expansion
"new" type
private type
Type expressions for the class language
Type expressions for the module language
None: abstract
first constructor in an extension
Constructor and record label descriptions inserted held in typing
environments
Constructor name
Type of the result
list of existentials
Type of the arguments
Number of arguments
Tag for heap blocks
Number of constant constructors
Number of non-const constructors
Read-only constructor?
Constant constructor (an int)
Regular constructor (a block)
Extension constructor
true if a constant false if a block
Constructors are the same
Constructors may be the same, given potential rebinding
Short name
Type of the result
Type of the argument
Is this a mutable field?
Position in block
All the labels in this type
Representation for this record
Read-only field?
* Extracts the list of "value" identifiers bound by a signature.
"Value" identifiers are identifiers for signature components that
correspond to a run-time value: values, extensions, modules, classes.
Note: manifest primitives do not correspond to a run-time value!
*** Utilities for backtracking ***
A snapshot for backtracking
Make a snapshot for later backtracking. Costs nothing
Backtrack to a given snapshot. Only possible if you have
not already backtracked to a previous snapshot.
Calls [cleanup_abbrev] internally
Backtrack only path compression. Only meaningful if you have
not already backtracked to a previous snapshot.
Does not call [cleanup_abbrev]
Set the desc field of [t1] to [Tlink t2], logging the old
value if there is an active snapshot
Set directly the desc field, without sharing | open Ttx_base
type ('a, 'b) binder = ('a, 'b) Binder.t
module Arg_label : sig
type t =
| Nolabel
| Labelled of string
| Optional of string
end
type arg_label = Arg_label.t
module Type_expr : sig
include INDEXABLE
type arg_label =
| Nolabel
| Labelled of string
| Optional of string
type desc =
| Tarrow of arg_label * t * t
| Ttuple of t list
| Tconstr of t list * path
val desc : t -> desc
end
module type LOCATED = sig
include INDEXABLE
val location :
end
module Value : sig
include INDEXABLE
end
type value_description =
val_kind: value_kind;
val_loc: Location.t;
val_attributes: Parsetree.attributes;
}
and value_kind =
| Val_self of class_signature * self_meths * Ident.t Vars.t * string
| Val_anc of class_signature * Ident.t Meths.t * string
and self_meths =
| Self_concrete of Ident.t Meths.t
| Self_virtual of Ident.t Meths.t ref
and class_signature =
{ csig_self: type_expr;
mutable csig_self_row: type_expr;
mutable csig_vars: (mutable_flag * virtual_flag * type_expr) Vars.t;
mutable csig_meths: (private_flag * virtual_flag * type_expr) Meths.t; }
module Variance : sig
type t
type f =
strictly covariant ( May_pos , Pos and Inj )
val union : t -> t -> t
val inter : t -> t -> t
val subset : t -> t -> bool
val eq : t -> t -> bool
val set : f -> bool -> t -> t
val mem : f -> t -> bool
pos , neg , inv ,
val unknown_signature : injective:bool -> arity:int -> t list
end
module Separability : sig
type t = Ind | Sep | Deepsep
val eq : t -> t -> bool
val print : Format.formatter -> t -> unit
val rank : t -> int
* Modes are ordered from the least to the most demanding :
Ind < Sep < Deepsep .
' rank ' maps them to integers in an order - respecting way :
= > rank m1 < rank m2
Ind < Sep < Deepsep.
'rank' maps them to integers in an order-respecting way:
m1 < m2 <=> rank m1 < rank m2 *)
val compare : t -> t -> int
* Compare two mode according to their mode ordering .
val max : t -> t -> t
* [ max_mode ] returns the most demanding mode . It is used to
express the conjunction of two parameter mode constraints .
express the conjunction of two parameter mode constraints. *)
type signature = t list
val print_signature : Format.formatter -> signature -> unit
val default_signature : arity:int -> signature
end
type type_declaration =
{ type_params: type_expr list;
type_arity: int;
type_kind: type_decl_kind;
type_private: private_flag;
type_manifest: type_expr option;
type_variance: Variance.t list;
type_separability: Separability.t list;
type_is_newtype: bool;
type_expansion_scope: int;
type_loc: Location.t;
type_attributes: Parsetree.attributes;
type_immediate: Type_immediacy.t;
type_unboxed_default: bool;
type_uid: Uid.t;
}
and type_decl_kind = (label_declaration, constructor_declaration) type_kind
and ('lbl, 'cstr) type_kind =
Type_abstract
| Type_record of 'lbl list * record_representation
| Type_variant of 'cstr list * variant_representation
| Type_open
and record_representation =
Inlined record
Inlined record under extension
and variant_representation =
One unboxed single - field constructor
and label_declaration =
{
ld_id: Ident.t;
ld_mutable: mutable_flag;
ld_type: type_expr;
ld_loc: Location.t;
ld_attributes: Parsetree.attributes;
ld_uid: Uid.t;
}
and constructor_declaration =
{
cd_id: Ident.t;
cd_args: constructor_arguments;
cd_res: type_expr option;
cd_loc: Location.t;
cd_attributes: Parsetree.attributes;
cd_uid: Uid.t;
}
and constructor_arguments =
| Cstr_tuple of type_expr list
| Cstr_record of label_declaration list
type extension_constructor =
{
ext_type_path: Path.t;
ext_type_params: type_expr list;
ext_args: constructor_arguments;
ext_ret_type: type_expr option;
ext_private: private_flag;
ext_loc: Location.t;
ext_attributes: Parsetree.attributes;
ext_uid: Uid.t;
}
and type_transparence =
type class_type =
Cty_constr of Path.t * type_expr list * class_type
| Cty_signature of class_signature
| Cty_arrow of arg_label * type_expr * class_type
type class_declaration =
{ cty_params: type_expr list;
mutable cty_type: class_type;
cty_path: Path.t;
cty_new: type_expr option;
cty_variance: Variance.t list;
cty_loc: Location.t;
cty_attributes: Parsetree.attributes;
cty_uid: Uid.t;
}
type class_type_declaration =
{ clty_params: type_expr list;
clty_type: class_type;
clty_path: Path.t;
clty_variance: Variance.t list;
clty_loc: Location.t;
clty_attributes: Parsetree.attributes;
clty_uid: Uid.t;
}
type visibility =
| Exported
| Hidden
type module_type =
Mty_ident of Path.t
| Mty_signature of signature
| Mty_functor of functor_parameter * module_type
| Mty_alias of Path.t
and functor_parameter =
| Unit
| Named of Ident.t option * module_type
and module_presence =
| Mp_present
| Mp_absent
and signature = signature_item list
and signature_item =
Sig_value of Ident.t * value_description * visibility
| Sig_type of Ident.t * type_declaration * rec_status * visibility
| Sig_typext of Ident.t * extension_constructor * ext_status * visibility
| Sig_module of
Ident.t * module_presence * module_declaration * rec_status * visibility
| Sig_modtype of Ident.t * modtype_declaration * visibility
| Sig_class of Ident.t * class_declaration * rec_status * visibility
| Sig_class_type of Ident.t * class_type_declaration * rec_status * visibility
and module_declaration =
{
md_type: module_type;
md_attributes: Parsetree.attributes;
md_loc: Location.t;
md_uid: Uid.t;
}
and modtype_declaration =
{
mtd_attributes: Parsetree.attributes;
mtd_loc: Location.t;
mtd_uid: Uid.t;
}
and rec_status =
first in a nonrecursive group
first in a recursive group
not first in a recursive / nonrecursive group
and ext_status =
not first constructor in an extension
| Text_exception
type constructor_description =
Constrained return type ?
cstr_loc: Location.t;
cstr_attributes: Parsetree.attributes;
cstr_inlined: type_declaration option;
cstr_uid: Uid.t;
}
and constructor_tag =
Constructor of an unboxed type
val equal_tag : constructor_tag -> constructor_tag -> bool
val may_equal_constr :
constructor_description -> constructor_description -> bool
type label_description =
lbl_loc: Location.t;
lbl_attributes: Parsetree.attributes;
lbl_uid: Uid.t;
}
val bound_value_identifiers: signature -> Ident.t list
val signature_item_id : signature_item -> Ident.t
type snapshot
val snapshot: unit -> snapshot
val backtrack: cleanup_abbrev:(unit -> unit) -> snapshot -> unit
val undo_first_change_after: snapshot -> unit
Backtrack only the first change after a snapshot .
Does not update the list of changes
Does not update the list of changes *)
val undo_compress: snapshot -> unit
* Functions to use when modifying a type ( only Ctype ? ) .
The old values are logged and reverted on backtracking .
The old values are logged and reverted on backtracking.
*)
val link_type: type_expr -> type_expr -> unit
val set_type_desc: type_expr -> type_desc -> unit
val set_level: type_expr -> int -> unit
val set_scope: type_expr -> int -> unit
val set_name:
(Path.t * type_expr list) option ref ->
(Path.t * type_expr list) option -> unit
val link_row_field_ext: inside:row_field -> row_field -> unit
Extract the extension variable of [ inside ] and set it to the
second argument
second argument *)
val set_univar: type_expr option ref -> type_expr -> unit
val link_kind: inside:field_kind -> field_kind -> unit
val link_commu: inside:commutable -> commutable -> unit
val set_commu_ok: commutable -> unit
|
ce4e42fe571f3de855feea5d7fbc3ceacc6452d7087dd1345bbead4af84c42bc | spawnfest/eep49ers | shell_default.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2016 . All Rights Reserved .
%%
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.
%%
%% %CopyrightEnd%
%%
%% This is just a empty template which calls routines in the module c
%% to do all the work!
-module(shell_default).
-export([help/0,lc/1,c/1,c/2,c/3,nc/1,nl/1,l/1,i/0,pid/3,i/3,m/0,m/1,lm/0,mm/0,
memory/0,memory/1,uptime/0,
erlangrc/1,bi/1, regs/0, flush/0,pwd/0,ls/0,ls/1,cd/1,
y/1, y/2,
xm/1, bt/1, q/0,
h/1, h/2, h/3, ht/1, ht/2, ht/3, hcb/1, hcb/2, hcb/3,
ni/0, nregs/0]).
-export([ih/0,iv/0,im/0,ii/1,ii/2,iq/1,ini/1,ini/2,inq/1,ib/2,ib/3,
ir/2,ir/3,ibd/2,ibe/2,iba/3,ibc/3,
ic/0,ir/1,ir/0,il/0,ipb/0,ipb/1,iaa/1,iaa/2,ist/1,ia/1,ia/2,ia/3,
ia/4,ip/0]).
-import(io, [format/1]).
help() ->
format("** shell internal commands **~n"),
format("b() -- display all variable bindings\n"),
format("e(N) -- repeat the expression in query <N>\n"),
format("f() -- forget all variable bindings\n"),
format("f(X) -- forget the binding of variable X\n"),
format("h() -- history\n"),
format("h(Mod) -- help about module\n"),
format("h(Mod,Func)-- help about function in module\n"),
format("h(Mod,Func,Arity) -- help about function with arity in module\n"),
format("ht(Mod) -- help about a module's types\n"),
format("ht(Mod,Type) -- help about type in module\n"),
format("ht(Mod,Type,Arity) -- help about type with arity in module\n"),
format("hcb(Mod) -- help about a module's callbacks\n"),
format("hcb(Mod,CB) -- help about callback in module\n"),
format("hcb(Mod,CB,Arity) -- help about callback with arity in module\n"),
format("history(N) -- set how many previous commands to keep\n"),
format("results(N) -- set how many previous command results to keep\n"),
format("catch_exception(B) -- how exceptions are handled\n"),
format("v(N) -- use the value of query <N>\n"),
format("rd(R,D) -- define a record\n"),
format("rf() -- remove all record information\n"),
format("rf(R) -- remove record information about R\n"),
format("rl() -- display all record information\n"),
format("rl(R) -- display record information about R\n"),
format("rp(Term) -- display Term using the shell's record information\n"),
format("rr(File) -- read record information from File (wildcards allowed)\n"),
format("rr(F,R) -- read selected record information from file(s)\n"),
format("rr(F,R,O) -- read selected record information with options\n"),
format("** commands in module c **\n"),
c:help(),
format("** commands in module i (interpreter interface) **\n"),
format("ih() -- print help for the i module\n"),
%% format("** private commands ** \n"),
%% format("myfunc() -- does my operation ...\n"),
true.
%% these are in alphabetic order it would be nice if they
%% were to *stay* so!
bi(I) -> c:bi(I).
bt(Pid) -> c:bt(Pid).
c(File) -> c:c(File).
c(File, Opt) -> c:c(File, Opt).
c(File, Opt, Filter) -> c:c(File, Opt, Filter).
cd(D) -> c:cd(D).
erlangrc(X) -> c:erlangrc(X).
flush() -> c:flush().
h(M) -> c:h(M).
h(M,F) -> c:h(M,F).
h(M,F,A) -> c:h(M,F,A).
ht(M) -> c:ht(M).
ht(M,F) -> c:ht(M,F).
ht(M,F,A) -> c:ht(M,F,A).
hcb(M) -> c:hcb(M).
hcb(M,F) -> c:hcb(M,F).
hcb(M,F,A) -> c:hcb(M,F,A).
i() -> c:i().
i(X,Y,Z) -> c:i(X,Y,Z).
l(Mod) -> c:l(Mod).
lc(X) -> c:lc(X).
ls() -> c:ls().
ls(S) -> c:ls(S).
m() -> c:m().
m(Mod) -> c:m(Mod).
lm() -> c:lm().
mm() -> c:mm().
memory() -> c:memory().
memory(Type) -> c:memory(Type).
nc(X) -> c:nc(X).
ni() -> c:ni().
nl(Mod) -> c:nl(Mod).
nregs() -> c:nregs().
pid(X,Y,Z) -> c:pid(X,Y,Z).
pwd() -> c:pwd().
q() -> c:q().
regs() -> c:regs().
uptime() -> c:uptime().
xm(Mod) -> c:xm(Mod).
y(File) -> c:y(File).
y(File, Opts) -> c:y(File, Opts).
iaa(Flag) -> calli(iaa, [Flag]).
iaa(Flag,Fnk) -> calli(iaa, [Flag,Fnk]).
ist(Flag) -> calli(ist, [Flag]).
ia(Pid) -> calli(ia, [Pid]).
ia(X,Y,Z) -> calli(ia, [X,Y,Z]).
ia(Pid,Fnk) -> calli(ia, [Pid,Fnk]).
ia(X,Y,Z,Fnk) -> calli(ia, [X,Y,Z,Fnk]).
ib(Mod,Line) -> calli(ib, [Mod,Line]).
ib(Mod,Fnk,Arity) -> calli(ib, [Mod,Fnk,Arity]).
ibd(Mod,Line) -> calli(ibd, [Mod,Line]).
ibe(Mod,Line) -> calli(ibe, [Mod,Line]).
iba(M,L,Action) -> calli(iba, [M,L,Action]).
ibc(M,L,Cond) -> calli(ibc, [M,L,Cond]).
ic() -> calli(ic, []).
ih() -> calli(help, []).
ii(Mod) -> calli(ii, [Mod]).
ii(Mod,Op) -> calli(ii, [Mod,Op]).
il() -> calli(il, []).
im() -> calli(im, []).
ini(Mod) -> calli(ini, [Mod]).
ini(Mod,Op) -> calli(ini, [Mod,Op]).
inq(Mod) -> calli(inq, [Mod]).
ip() -> calli(ip, []).
ipb() -> calli(ipb, []).
ipb(Mod) -> calli(ipb, [Mod]).
iq(Mod) -> calli(iq, [Mod]).
ir(Mod,Line) -> calli(ir, [Mod,Line]).
ir(Mod,Fnk,Arity) -> calli(ir, [Mod,Fnk,Arity]).
ir(Mod) -> calli(ir, [Mod]).
ir() -> calli(ir, []).
iv() -> calli(iv, []).
calli(F, Args) ->
c:appcall(debugger, i, F, Args).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/stdlib/src/shell_default.erl | erlang |
%CopyrightBegin%
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.
%CopyrightEnd%
This is just a empty template which calls routines in the module c
to do all the work!
format("** private commands ** \n"),
format("myfunc() -- does my operation ...\n"),
these are in alphabetic order it would be nice if they
were to *stay* so! | Copyright Ericsson AB 1996 - 2016 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(shell_default).
-export([help/0,lc/1,c/1,c/2,c/3,nc/1,nl/1,l/1,i/0,pid/3,i/3,m/0,m/1,lm/0,mm/0,
memory/0,memory/1,uptime/0,
erlangrc/1,bi/1, regs/0, flush/0,pwd/0,ls/0,ls/1,cd/1,
y/1, y/2,
xm/1, bt/1, q/0,
h/1, h/2, h/3, ht/1, ht/2, ht/3, hcb/1, hcb/2, hcb/3,
ni/0, nregs/0]).
-export([ih/0,iv/0,im/0,ii/1,ii/2,iq/1,ini/1,ini/2,inq/1,ib/2,ib/3,
ir/2,ir/3,ibd/2,ibe/2,iba/3,ibc/3,
ic/0,ir/1,ir/0,il/0,ipb/0,ipb/1,iaa/1,iaa/2,ist/1,ia/1,ia/2,ia/3,
ia/4,ip/0]).
-import(io, [format/1]).
help() ->
format("** shell internal commands **~n"),
format("b() -- display all variable bindings\n"),
format("e(N) -- repeat the expression in query <N>\n"),
format("f() -- forget all variable bindings\n"),
format("f(X) -- forget the binding of variable X\n"),
format("h() -- history\n"),
format("h(Mod) -- help about module\n"),
format("h(Mod,Func)-- help about function in module\n"),
format("h(Mod,Func,Arity) -- help about function with arity in module\n"),
format("ht(Mod) -- help about a module's types\n"),
format("ht(Mod,Type) -- help about type in module\n"),
format("ht(Mod,Type,Arity) -- help about type with arity in module\n"),
format("hcb(Mod) -- help about a module's callbacks\n"),
format("hcb(Mod,CB) -- help about callback in module\n"),
format("hcb(Mod,CB,Arity) -- help about callback with arity in module\n"),
format("history(N) -- set how many previous commands to keep\n"),
format("results(N) -- set how many previous command results to keep\n"),
format("catch_exception(B) -- how exceptions are handled\n"),
format("v(N) -- use the value of query <N>\n"),
format("rd(R,D) -- define a record\n"),
format("rf() -- remove all record information\n"),
format("rf(R) -- remove record information about R\n"),
format("rl() -- display all record information\n"),
format("rl(R) -- display record information about R\n"),
format("rp(Term) -- display Term using the shell's record information\n"),
format("rr(File) -- read record information from File (wildcards allowed)\n"),
format("rr(F,R) -- read selected record information from file(s)\n"),
format("rr(F,R,O) -- read selected record information with options\n"),
format("** commands in module c **\n"),
c:help(),
format("** commands in module i (interpreter interface) **\n"),
format("ih() -- print help for the i module\n"),
true.
bi(I) -> c:bi(I).
bt(Pid) -> c:bt(Pid).
c(File) -> c:c(File).
c(File, Opt) -> c:c(File, Opt).
c(File, Opt, Filter) -> c:c(File, Opt, Filter).
cd(D) -> c:cd(D).
erlangrc(X) -> c:erlangrc(X).
flush() -> c:flush().
h(M) -> c:h(M).
h(M,F) -> c:h(M,F).
h(M,F,A) -> c:h(M,F,A).
ht(M) -> c:ht(M).
ht(M,F) -> c:ht(M,F).
ht(M,F,A) -> c:ht(M,F,A).
hcb(M) -> c:hcb(M).
hcb(M,F) -> c:hcb(M,F).
hcb(M,F,A) -> c:hcb(M,F,A).
i() -> c:i().
i(X,Y,Z) -> c:i(X,Y,Z).
l(Mod) -> c:l(Mod).
lc(X) -> c:lc(X).
ls() -> c:ls().
ls(S) -> c:ls(S).
m() -> c:m().
m(Mod) -> c:m(Mod).
lm() -> c:lm().
mm() -> c:mm().
memory() -> c:memory().
memory(Type) -> c:memory(Type).
nc(X) -> c:nc(X).
ni() -> c:ni().
nl(Mod) -> c:nl(Mod).
nregs() -> c:nregs().
pid(X,Y,Z) -> c:pid(X,Y,Z).
pwd() -> c:pwd().
q() -> c:q().
regs() -> c:regs().
uptime() -> c:uptime().
xm(Mod) -> c:xm(Mod).
y(File) -> c:y(File).
y(File, Opts) -> c:y(File, Opts).
iaa(Flag) -> calli(iaa, [Flag]).
iaa(Flag,Fnk) -> calli(iaa, [Flag,Fnk]).
ist(Flag) -> calli(ist, [Flag]).
ia(Pid) -> calli(ia, [Pid]).
ia(X,Y,Z) -> calli(ia, [X,Y,Z]).
ia(Pid,Fnk) -> calli(ia, [Pid,Fnk]).
ia(X,Y,Z,Fnk) -> calli(ia, [X,Y,Z,Fnk]).
ib(Mod,Line) -> calli(ib, [Mod,Line]).
ib(Mod,Fnk,Arity) -> calli(ib, [Mod,Fnk,Arity]).
ibd(Mod,Line) -> calli(ibd, [Mod,Line]).
ibe(Mod,Line) -> calli(ibe, [Mod,Line]).
iba(M,L,Action) -> calli(iba, [M,L,Action]).
ibc(M,L,Cond) -> calli(ibc, [M,L,Cond]).
ic() -> calli(ic, []).
ih() -> calli(help, []).
ii(Mod) -> calli(ii, [Mod]).
ii(Mod,Op) -> calli(ii, [Mod,Op]).
il() -> calli(il, []).
im() -> calli(im, []).
ini(Mod) -> calli(ini, [Mod]).
ini(Mod,Op) -> calli(ini, [Mod,Op]).
inq(Mod) -> calli(inq, [Mod]).
ip() -> calli(ip, []).
ipb() -> calli(ipb, []).
ipb(Mod) -> calli(ipb, [Mod]).
iq(Mod) -> calli(iq, [Mod]).
ir(Mod,Line) -> calli(ir, [Mod,Line]).
ir(Mod,Fnk,Arity) -> calli(ir, [Mod,Fnk,Arity]).
ir(Mod) -> calli(ir, [Mod]).
ir() -> calli(ir, []).
iv() -> calli(iv, []).
calli(F, Args) ->
c:appcall(debugger, i, F, Args).
|
fed48ca5f9fb333124424ace503859553aa94e4674839a721dcbfcd6c77daaec | aria42/infer | matrix_test.clj | (ns infer.matrix-test
(:use clojure.test
infer.matrix))
(deftest leave-out-columns
(is (= #{0 1 4}
(leave-out [2 3] (range 0 5)))))
(deftest inc-at-test
(let [A (fill 0 3 3)]
(inc-at A 0 0)
(is (= 1 (get-at A 0 0)))
(inc-at A 2 0 0)
(is (= 3 (get-at A 0 0)))))
(deftest ensure-vecs-test
(let [v (ensure-vecs [[1]])
s (ensure-vecs (list (list 1) (list 2)))
vs (ensure-vecs [(list 1) (list 2)])]
(is (vector? v))
(is (vector? (first v)))
(is (vector? s))
(is (vector? (second s)))))
(deftest create-matrix
(let [m (matrix
[[1 2 3] [4 5 6]])
single-m (column-matrix [1 2 3 4 5 6])]
(is (= 6 (get-at m 1 2)))
(is (= 6 (get-at single-m 5 0)))))
(deftest to-and-from-matrix
(let [a [[1 2 3] [4 5 6]]
A (matrix
[[1 2 3] [4 5 6]])
b (from-matrix A)]
(is (= a b))))
(deftest to-and-from-sparse-matrix
(let [a [{0 1, 5 2, 9 3} {4 4,9 5, 16 6}]
A (sparse-matrix a)
b (from-sparse-2d-matrix A)]
(is (= a b))))
(deftest to-and-from-sparse-colt-matrix
(let [a [{0 1, 5 2, 9 3} {4 4,9 5, 16 6}]
A (sparse-colt-matrix a)
b (from-sparse-2d-matrix A)]
(is (= a b))))
(deftest to-and-from-sparse-pcolt-matrix
(let [a [{0 1, 5 2, 9 3} {4 4,9 5, 16 6}]
A (sparse-pcolt-matrix a)
b (from-sparse-2d-matrix A)]
(is (= a b))))
(deftest to-and-from-column-matrix
(let [a [1 2 3]
A (column-matrix
a)
b (from-column-matrix A)]
(is (= a b))))
(deftest identity-matrix
(let [i (from-matrix (I 2 2))]
(is (= [[1 0]
[0 1]]
i))))
(deftest create-diagonal-weights
(is (= [[1 0 0]
[0 2 0]
[0 0 3]]
(to-diag [1 2 3]))))
(deftest matrix-multiplication
(let [A (matrix [[1 1] [1 1]])
B (matrix [[2 2] [2 2]])
C (matrix [[2 0] [0 2]])]
(is (= (matrix [[4 4] [4 4]]) (times A B)))
(is (= (matrix [[8 8] [8 8]]) (times A B C)))))
;; (deftest matrix-divide
( let [ A ( matrix [ [ 1 1 ] [ 1 1 ] ] )
B ( matrix [ [ 2 2 ] [ 2 2 ] ] )
C ( matrix [ [ 2 0 ] [ 0 2 ] ] ) ]
( is (= ( matrix [ [ 0.5 0.5 ] [ 0.5 0.5 ] ] ) ( divide A B ) ) )
( is (= ( matrix [ [ 8 8 ] [ 8 8 ] ] ) ( divide A B C ) ) ) ) )
(deftest matrix-addition
(let [A (matrix [[1 1] [1 1]])
B (matrix [[2 2] [2 2]])
C (matrix [[2 0] [0 2]])]
(is (= (matrix [[3 3] [3 3]]) (plus A B)))
(is (= (matrix [[5 3] [3 5]]) (plus A B C)))))
(deftest matrix-subtraction
(let [A (matrix [[1 1] [1 1]])
B (matrix [[2 2] [2 2]])
C (matrix [[2 0] [0 2]])]
(is (= (matrix [[1 1] [1 1]]) (minus B A)))
(is (= (matrix [[-1 1] [1 -1]]) (minus B A C)))))
(deftest concat-columns
(is (= (from-matrix
(matrix [[1 2 3]
[2 3 4]]))
(from-matrix (column-concat
(column-matrix [1 2])
(column-matrix [2 3])
(column-matrix [3 4])))))) | null | https://raw.githubusercontent.com/aria42/infer/9849325a27770794b91415592a8706fd90777469/test/infer/matrix_test.clj | clojure | (deftest matrix-divide | (ns infer.matrix-test
(:use clojure.test
infer.matrix))
(deftest leave-out-columns
(is (= #{0 1 4}
(leave-out [2 3] (range 0 5)))))
(deftest inc-at-test
(let [A (fill 0 3 3)]
(inc-at A 0 0)
(is (= 1 (get-at A 0 0)))
(inc-at A 2 0 0)
(is (= 3 (get-at A 0 0)))))
(deftest ensure-vecs-test
(let [v (ensure-vecs [[1]])
s (ensure-vecs (list (list 1) (list 2)))
vs (ensure-vecs [(list 1) (list 2)])]
(is (vector? v))
(is (vector? (first v)))
(is (vector? s))
(is (vector? (second s)))))
(deftest create-matrix
(let [m (matrix
[[1 2 3] [4 5 6]])
single-m (column-matrix [1 2 3 4 5 6])]
(is (= 6 (get-at m 1 2)))
(is (= 6 (get-at single-m 5 0)))))
(deftest to-and-from-matrix
(let [a [[1 2 3] [4 5 6]]
A (matrix
[[1 2 3] [4 5 6]])
b (from-matrix A)]
(is (= a b))))
(deftest to-and-from-sparse-matrix
(let [a [{0 1, 5 2, 9 3} {4 4,9 5, 16 6}]
A (sparse-matrix a)
b (from-sparse-2d-matrix A)]
(is (= a b))))
(deftest to-and-from-sparse-colt-matrix
(let [a [{0 1, 5 2, 9 3} {4 4,9 5, 16 6}]
A (sparse-colt-matrix a)
b (from-sparse-2d-matrix A)]
(is (= a b))))
(deftest to-and-from-sparse-pcolt-matrix
(let [a [{0 1, 5 2, 9 3} {4 4,9 5, 16 6}]
A (sparse-pcolt-matrix a)
b (from-sparse-2d-matrix A)]
(is (= a b))))
(deftest to-and-from-column-matrix
(let [a [1 2 3]
A (column-matrix
a)
b (from-column-matrix A)]
(is (= a b))))
(deftest identity-matrix
(let [i (from-matrix (I 2 2))]
(is (= [[1 0]
[0 1]]
i))))
(deftest create-diagonal-weights
(is (= [[1 0 0]
[0 2 0]
[0 0 3]]
(to-diag [1 2 3]))))
(deftest matrix-multiplication
(let [A (matrix [[1 1] [1 1]])
B (matrix [[2 2] [2 2]])
C (matrix [[2 0] [0 2]])]
(is (= (matrix [[4 4] [4 4]]) (times A B)))
(is (= (matrix [[8 8] [8 8]]) (times A B C)))))
( let [ A ( matrix [ [ 1 1 ] [ 1 1 ] ] )
B ( matrix [ [ 2 2 ] [ 2 2 ] ] )
C ( matrix [ [ 2 0 ] [ 0 2 ] ] ) ]
( is (= ( matrix [ [ 0.5 0.5 ] [ 0.5 0.5 ] ] ) ( divide A B ) ) )
( is (= ( matrix [ [ 8 8 ] [ 8 8 ] ] ) ( divide A B C ) ) ) ) )
(deftest matrix-addition
(let [A (matrix [[1 1] [1 1]])
B (matrix [[2 2] [2 2]])
C (matrix [[2 0] [0 2]])]
(is (= (matrix [[3 3] [3 3]]) (plus A B)))
(is (= (matrix [[5 3] [3 5]]) (plus A B C)))))
(deftest matrix-subtraction
(let [A (matrix [[1 1] [1 1]])
B (matrix [[2 2] [2 2]])
C (matrix [[2 0] [0 2]])]
(is (= (matrix [[1 1] [1 1]]) (minus B A)))
(is (= (matrix [[-1 1] [1 -1]]) (minus B A C)))))
(deftest concat-columns
(is (= (from-matrix
(matrix [[1 2 3]
[2 3 4]]))
(from-matrix (column-concat
(column-matrix [1 2])
(column-matrix [2 3])
(column-matrix [3 4])))))) |
20e8aea76f334bbe05cba21a22f67311e493f86ea1507038e5b98626e9f931d8 | rrnewton/haskell-lockfree | Atomic.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE DefaultSignatures #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleInstances #
# LANGUAGE CPP #
module Data.Vector.Unboxed.Atomic
where
import Foreign.Storable (Storable, sizeOf)
import Data.Int
import Data.Word
import qualified Data.Vector.Primitive as P
-- The specific MV_* constructors that we need are here:
import Data.Vector.Unboxed.Base
import Data.Primitive (MutableByteArray)
import Data.Atomics (Ticket)
import qualified Data.Vector.Storable.Mutable as SM
import qualified Data.Bits.Atomic as BA
import Foreign.ForeignPtr (newForeignPtr, withForeignPtr)
import qualified Foreign.Ptr as P
--------------------------------------------------------------------------------
-- | Vector types which are implemented as single MutableByteArray, and whose
-- elements are of an appropriate size to perform atomic memory operations on them.
class IsOneMBV v a where
getMutableByteArray :: v s a -> MutableByteArray s
bitSize :: v s a -> Int
default bitSize :: (IsOneMBV v a, Storable a) => v s a -> Int
bitSize _ = sizeOf (undefined::a) * 8
bitSize : : a - > Int
default bitSize : : ( Storable a ) = > a - > Int
bitSize _ = ( undefined::a ) * 8
Huh , this ^^ attempt exposes some of the post - desugaring magic :
Possible fix : add an instance declaration for ( IsOneMBV v0 Int )
In the expression : ( Data . Vector . . )
In an equation for ` bitSize ' :
bitSize = ( Data . Vector . . )
bitSize :: a -> Int
default bitSize :: (Storable a) => a -> Int
bitSize _ = sizeOf (undefined::a) * 8
Huh, this ^^ attempt exposes some of the post-desugaring magic:
Possible fix: add an instance declaration for (IsOneMBV v0 Int)
In the expression: (Data.Vector.Unboxed.Atomic.$gdmbitSize)
In an equation for `bitSize':
bitSize = (Data.Vector.Unboxed.Atomic.$gdmbitSize)
-}
instance IsOneMBV MVector Int where getMutableByteArray (MV_Int (P.MVector _ _ a)) = a
instance IsOneMBV MVector Int8 where getMutableByteArray (MV_Int8 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Int16 where getMutableByteArray (MV_Int16 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Int32 where getMutableByteArray (MV_Int32 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Int64 where getMutableByteArray (MV_Int64 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word where getMutableByteArray (MV_Word (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word8 where getMutableByteArray (MV_Word8 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word16 where getMutableByteArray (MV_Word16 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word32 where getMutableByteArray (MV_Word32 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word64 where getMutableByteArray (MV_Word64 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Bool where getMutableByteArray (MV_Bool (P.MVector _ _ a)) = a
instance IsOneMBV MVector Char where getMutableByteArray (MV_Char (P.MVector _ _ a)) = a
instance IsOneMBV MVector Double where getMutableByteArray (MV_Double (P.MVector _ _ a)) = a
instance IsOneMBV MVector Float where getMutableByteArray (MV_Float (P.MVector _ _ a)) = a
--------------------------------------------------------------------------------
| A class for vectors whose contents are unboxed numbers , not heap objects .
class AtomicUVec v a where
fetchAndAdd :: v s a -> Int -> a -> IO a
fetchAndSub :: v s a -> Int -> a -> IO a
fetchAndOr :: v s a -> Int -> a -> IO a
fetchAndAnd :: v s a -> Int -> a -> IO a
fetchAndXor :: v s a -> Int -> a -> IO a
fetchAndNand :: v s a -> Int -> a -> IO a
addAndFetch :: v s a -> Int -> a -> IO a
subAndFetch :: v s a -> Int -> a -> IO a
orAndFetch :: v s a -> Int -> a -> IO a
andAndFetch :: v s a -> Int -> a -> IO a
xorAndFetch :: v s a -> Int -> a -> IO a
nandAndFetch :: v s a -> Int -> a -> IO a
lockTestAndSet : : v s a - > Int - > IO a
-- lockRelease :: v s a -> Int -> IO ()
compareAndSwap :: v s a -> Int -> a -> a -> IO (Maybe a)
| Atomic operations on /boxed/ vectors containing arbitrary values .
class AtomicVec v a where
compareAndSwapT :: v s a -> Int -> Ticket a -> a -> IO (Bool, Ticket a)
--
--
boundsCheck :: (Num a, Ord a) => String -> a -> a -> t -> t
boundsCheck name ix len x
| ix >= 0 && ix < len = x
| otherwise = error $ name ++": index out of bounds "
-- FIXME: BOUNDS CHECK:
#define DOOP(name) \
name (SM.MVector len fp) ix val = \
withForeignPtr fp (\ptr -> \
let offset = sizeOf (undefined::elt) * ix in \
boundsCheck "atomic vector op" ix len \
(BA.name (P.plusPtr ptr offset) val ))
instance (Storable elt, BA.AtomicBits elt) =>
AtomicUVec SM.MVector elt where
DOOP(fetchAndAdd)
DOOP(fetchAndSub)
DOOP(fetchAndOr)
DOOP(fetchAndAnd)
DOOP(fetchAndXor)
DOOP(fetchAndNand)
DOOP(addAndFetch)
DOOP(subAndFetch)
DOOP(orAndFetch)
DOOP(andAndFetch)
DOOP(xorAndFetch)
DOOP(nandAndFetch)
compareAndSwap (SM.MVector _len fp) ix old new =
withForeignPtr fp $ \ptr -> do
let offset = sizeOf (undefined::elt) * ix
old' <- BA.compareAndSwap (P.plusPtr ptr offset) old new
return $! if old' == old
then Nothing
else Just old'
-- compareAndSwapT arr ix tick new =
-- error "FINISHME - compareAndSwapT "
instance AtomicUVec SM.MVector Int where
| null | https://raw.githubusercontent.com/rrnewton/haskell-lockfree/87122157cbbc96954fcc575b4b110003d3e5c2f8/vector-atomics/Data/Vector/Unboxed/Atomic.hs | haskell | The specific MV_* constructors that we need are here:
------------------------------------------------------------------------------
| Vector types which are implemented as single MutableByteArray, and whose
elements are of an appropriate size to perform atomic memory operations on them.
------------------------------------------------------------------------------
lockRelease :: v s a -> Int -> IO ()
FIXME: BOUNDS CHECK:
compareAndSwapT arr ix tick new =
error "FINISHME - compareAndSwapT " | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE DefaultSignatures #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleInstances #
# LANGUAGE CPP #
module Data.Vector.Unboxed.Atomic
where
import Foreign.Storable (Storable, sizeOf)
import Data.Int
import Data.Word
import qualified Data.Vector.Primitive as P
import Data.Vector.Unboxed.Base
import Data.Primitive (MutableByteArray)
import Data.Atomics (Ticket)
import qualified Data.Vector.Storable.Mutable as SM
import qualified Data.Bits.Atomic as BA
import Foreign.ForeignPtr (newForeignPtr, withForeignPtr)
import qualified Foreign.Ptr as P
class IsOneMBV v a where
getMutableByteArray :: v s a -> MutableByteArray s
bitSize :: v s a -> Int
default bitSize :: (IsOneMBV v a, Storable a) => v s a -> Int
bitSize _ = sizeOf (undefined::a) * 8
bitSize : : a - > Int
default bitSize : : ( Storable a ) = > a - > Int
bitSize _ = ( undefined::a ) * 8
Huh , this ^^ attempt exposes some of the post - desugaring magic :
Possible fix : add an instance declaration for ( IsOneMBV v0 Int )
In the expression : ( Data . Vector . . )
In an equation for ` bitSize ' :
bitSize = ( Data . Vector . . )
bitSize :: a -> Int
default bitSize :: (Storable a) => a -> Int
bitSize _ = sizeOf (undefined::a) * 8
Huh, this ^^ attempt exposes some of the post-desugaring magic:
Possible fix: add an instance declaration for (IsOneMBV v0 Int)
In the expression: (Data.Vector.Unboxed.Atomic.$gdmbitSize)
In an equation for `bitSize':
bitSize = (Data.Vector.Unboxed.Atomic.$gdmbitSize)
-}
instance IsOneMBV MVector Int where getMutableByteArray (MV_Int (P.MVector _ _ a)) = a
instance IsOneMBV MVector Int8 where getMutableByteArray (MV_Int8 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Int16 where getMutableByteArray (MV_Int16 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Int32 where getMutableByteArray (MV_Int32 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Int64 where getMutableByteArray (MV_Int64 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word where getMutableByteArray (MV_Word (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word8 where getMutableByteArray (MV_Word8 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word16 where getMutableByteArray (MV_Word16 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word32 where getMutableByteArray (MV_Word32 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Word64 where getMutableByteArray (MV_Word64 (P.MVector _ _ a)) = a
instance IsOneMBV MVector Bool where getMutableByteArray (MV_Bool (P.MVector _ _ a)) = a
instance IsOneMBV MVector Char where getMutableByteArray (MV_Char (P.MVector _ _ a)) = a
instance IsOneMBV MVector Double where getMutableByteArray (MV_Double (P.MVector _ _ a)) = a
instance IsOneMBV MVector Float where getMutableByteArray (MV_Float (P.MVector _ _ a)) = a
| A class for vectors whose contents are unboxed numbers , not heap objects .
class AtomicUVec v a where
fetchAndAdd :: v s a -> Int -> a -> IO a
fetchAndSub :: v s a -> Int -> a -> IO a
fetchAndOr :: v s a -> Int -> a -> IO a
fetchAndAnd :: v s a -> Int -> a -> IO a
fetchAndXor :: v s a -> Int -> a -> IO a
fetchAndNand :: v s a -> Int -> a -> IO a
addAndFetch :: v s a -> Int -> a -> IO a
subAndFetch :: v s a -> Int -> a -> IO a
orAndFetch :: v s a -> Int -> a -> IO a
andAndFetch :: v s a -> Int -> a -> IO a
xorAndFetch :: v s a -> Int -> a -> IO a
nandAndFetch :: v s a -> Int -> a -> IO a
lockTestAndSet : : v s a - > Int - > IO a
compareAndSwap :: v s a -> Int -> a -> a -> IO (Maybe a)
| Atomic operations on /boxed/ vectors containing arbitrary values .
class AtomicVec v a where
compareAndSwapT :: v s a -> Int -> Ticket a -> a -> IO (Bool, Ticket a)
boundsCheck :: (Num a, Ord a) => String -> a -> a -> t -> t
boundsCheck name ix len x
| ix >= 0 && ix < len = x
| otherwise = error $ name ++": index out of bounds "
#define DOOP(name) \
name (SM.MVector len fp) ix val = \
withForeignPtr fp (\ptr -> \
let offset = sizeOf (undefined::elt) * ix in \
boundsCheck "atomic vector op" ix len \
(BA.name (P.plusPtr ptr offset) val ))
instance (Storable elt, BA.AtomicBits elt) =>
AtomicUVec SM.MVector elt where
DOOP(fetchAndAdd)
DOOP(fetchAndSub)
DOOP(fetchAndOr)
DOOP(fetchAndAnd)
DOOP(fetchAndXor)
DOOP(fetchAndNand)
DOOP(addAndFetch)
DOOP(subAndFetch)
DOOP(orAndFetch)
DOOP(andAndFetch)
DOOP(xorAndFetch)
DOOP(nandAndFetch)
compareAndSwap (SM.MVector _len fp) ix old new =
withForeignPtr fp $ \ptr -> do
let offset = sizeOf (undefined::elt) * ix
old' <- BA.compareAndSwap (P.plusPtr ptr offset) old new
return $! if old' == old
then Nothing
else Just old'
instance AtomicUVec SM.MVector Int where
|
a6b8a2efeed0d435725ca080cc4b37ded9db80ca90de9bf71c4634a004585c8d | DogLooksGood/holdem | router.cljs | (ns poker.events.router
(:require
[re-frame.core :as re-frame]
[reitit.frontend.easy :as rfe]
[reitit.frontend.controllers :as rfc]))
(re-frame/reg-fx :router/push-state
(fn [route]
(apply rfe/push-state route)))
(re-frame/reg-event-db :router/initialize-router
(fn [db _] (assoc db :current-route nil)))
(re-frame/reg-event-fx :router/push-state
(fn [_ [_ & route]] {:router/push-state route}))
(re-frame/reg-fx :router/new-game-window
(fn [{:keys [game-id]}]
(.open
js/window
(str "#/game/" game-id)
(str "Game@" game-id)
"directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,width=400,height=350")))
(re-frame/reg-event-db :router/navigated
(fn [db [_ new-match]]
(let [old-match (:current-route db)
controllers (rfc/apply-controllers (:controllers old-match)
new-match)]
(assoc db
:current-route
(assoc new-match :controllers controllers)))))
| null | https://raw.githubusercontent.com/DogLooksGood/holdem/bc0f93ed65cab54890c91f78bb95fe3ba020a41f/src/cljs/poker/events/router.cljs | clojure | (ns poker.events.router
(:require
[re-frame.core :as re-frame]
[reitit.frontend.easy :as rfe]
[reitit.frontend.controllers :as rfc]))
(re-frame/reg-fx :router/push-state
(fn [route]
(apply rfe/push-state route)))
(re-frame/reg-event-db :router/initialize-router
(fn [db _] (assoc db :current-route nil)))
(re-frame/reg-event-fx :router/push-state
(fn [_ [_ & route]] {:router/push-state route}))
(re-frame/reg-fx :router/new-game-window
(fn [{:keys [game-id]}]
(.open
js/window
(str "#/game/" game-id)
(str "Game@" game-id)
"directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,width=400,height=350")))
(re-frame/reg-event-db :router/navigated
(fn [db [_ new-match]]
(let [old-match (:current-route db)
controllers (rfc/apply-controllers (:controllers old-match)
new-match)]
(assoc db
:current-route
(assoc new-match :controllers controllers)))))
| |
e6953d2f788c2b6108dde6d75b48b9ca5deaa82cbc4238a59fd47dc484655ccf | bugczw/Introduction-to-Functional-Programming-in-OCaml | goodSignature.ml | module Naturals : sig
(* Invariant: A value of type t is a positive integer. *)
type t
val zero : t
val succ : t -> t
val pred : t -> t
end = struct
type t = int
let zero = 0
(* The functions maintain the invariant. *)
let succ n = if n = max_int then 0 else n + 1
let pred = function 0 -> 0 | n -> n - 1
end;;
open Naturals
let rec add : t -> t -> t = fun x y ->
if x = zero then y else succ (add (pred x) y);;
let i_break_the_abstraction = pred (-1)
| null | https://raw.githubusercontent.com/bugczw/Introduction-to-Functional-Programming-in-OCaml/13c4d1f92e7479f8eb10ea5d4c43a598b6676d0f/OCaml_MOOC_W6_ALL/goodSignature.ml | ocaml | Invariant: A value of type t is a positive integer.
The functions maintain the invariant. | module Naturals : sig
type t
val zero : t
val succ : t -> t
val pred : t -> t
end = struct
type t = int
let zero = 0
let succ n = if n = max_int then 0 else n + 1
let pred = function 0 -> 0 | n -> n - 1
end;;
open Naturals
let rec add : t -> t -> t = fun x y ->
if x = zero then y else succ (add (pred x) y);;
let i_break_the_abstraction = pred (-1)
|
2490d2ef2981fed71fba79910118eca210027b0d1b51c67a605e6423fabad1fa | ghc/testsuite | tcfail122.hs | # LANGUAGE RankNTypes , KindSignatures #
module ShouldFail where
-- There should be a kind error, when unifying (a b) against (c d)
foo = [ undefined :: forall a b. a b,
undefined :: forall (c:: (* -> *) -> *) (d :: * -> *). c d ]
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_fail/tcfail122.hs | haskell | There should be a kind error, when unifying (a b) against (c d) | # LANGUAGE RankNTypes , KindSignatures #
module ShouldFail where
foo = [ undefined :: forall a b. a b,
undefined :: forall (c:: (* -> *) -> *) (d :: * -> *). c d ]
|
0b5c5010c82961c7addcc7b61f7aabdb7c90ce06e339c1d9700722620097942c | alexandroid000/improv | GetMapActionFeedback.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Ros.Nav_msgs.GetMapActionFeedback where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.HeaderSupport
import qualified Ros.Actionlib_msgs.GoalStatus as GoalStatus
import qualified Ros.Nav_msgs.GetMapFeedback as GetMapFeedback
import qualified Ros.Std_msgs.Header as Header
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data GetMapActionFeedback = GetMapActionFeedback { _header :: Header.Header
, _status :: GoalStatus.GoalStatus
, _feedback :: GetMapFeedback.GetMapFeedback
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''GetMapActionFeedback)
instance RosBinary GetMapActionFeedback where
put obj' = put (_header obj') *> put (_status obj') *> put (_feedback obj')
get = GetMapActionFeedback <$> get <*> get <*> get
putMsg = putStampedMsg
instance HasHeader GetMapActionFeedback where
getSequence = view (header . Header.seq)
getFrame = view (header . Header.frame_id)
getStamp = view (header . Header.stamp)
setSequence = set (header . Header.seq)
instance MsgInfo GetMapActionFeedback where
sourceMD5 _ = "aae20e09065c3809e8a8e87c4c8953fd"
msgTypeName _ = "nav_msgs/GetMapActionFeedback"
instance D.Default GetMapActionFeedback
| null | https://raw.githubusercontent.com/alexandroid000/improv/ef0f4a6a5f99a9c7ff3d25f50529417aba9f757c/roshask/msgs/Nav_msgs/Ros/Nav_msgs/GetMapActionFeedback.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveDataTypeable # | # LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Ros.Nav_msgs.GetMapActionFeedback where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.HeaderSupport
import qualified Ros.Actionlib_msgs.GoalStatus as GoalStatus
import qualified Ros.Nav_msgs.GetMapFeedback as GetMapFeedback
import qualified Ros.Std_msgs.Header as Header
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data GetMapActionFeedback = GetMapActionFeedback { _header :: Header.Header
, _status :: GoalStatus.GoalStatus
, _feedback :: GetMapFeedback.GetMapFeedback
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''GetMapActionFeedback)
instance RosBinary GetMapActionFeedback where
put obj' = put (_header obj') *> put (_status obj') *> put (_feedback obj')
get = GetMapActionFeedback <$> get <*> get <*> get
putMsg = putStampedMsg
instance HasHeader GetMapActionFeedback where
getSequence = view (header . Header.seq)
getFrame = view (header . Header.frame_id)
getStamp = view (header . Header.stamp)
setSequence = set (header . Header.seq)
instance MsgInfo GetMapActionFeedback where
sourceMD5 _ = "aae20e09065c3809e8a8e87c4c8953fd"
msgTypeName _ = "nav_msgs/GetMapActionFeedback"
instance D.Default GetMapActionFeedback
|
56832e9d0166d97c8c4a2a906dc32471a0271044d6283b48abb5375193770785 | hypernumbers/hypernumbers | translator.erl | ( C ) 2009 - 2014 , Hypernumbers Ltd.
%%%-------------------------------------------------------------------
%%%
%%% LICENSE
%%%
%%% This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3
%%%
%%% 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 Affero General Public License for more details.
%%%
You should have received a copy of the GNU Affero General Public License
%%% along with this program. If not, see </>.
%%%-------------------------------------------------------------------
@private
-module(translator).
-export([do/1]).
do(Formula) ->
TODO : get french back in , stop it replacing trim with mirr
Languages = [ russian_lexer , spanish_lexer , ,
%% german_lexer, french_lexer, italian_lexer],
Languages = [russian_lexer, spanish_lexer, portuguese_lexer,
german_lexer, italian_lexer],
Fun = fun(Frontend, NewFormula) ->
{ok, Tokens, _} = Frontend:string(NewFormula),
lists:flatmap(fun({_, YYtext}) -> YYtext end, Tokens)
end,
R = lists:foldl(Fun, [$=|Formula], Languages),
tl(R). % Don't want the equals sign.
| null | https://raw.githubusercontent.com/hypernumbers/hypernumbers/281319f60c0ac60fb009ee6d1e4826f4f2d51c4e/lib/formula_engine-1.0/src/translator.erl | erlang | -------------------------------------------------------------------
LICENSE
This program is free software: you can redistribute it and/or modify
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 Affero General Public License for more details.
along with this program. If not, see </>.
-------------------------------------------------------------------
german_lexer, french_lexer, italian_lexer],
Don't want the equals sign. | ( C ) 2009 - 2014 , Hypernumbers Ltd.
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3
You should have received a copy of the GNU Affero General Public License
@private
-module(translator).
-export([do/1]).
do(Formula) ->
TODO : get french back in , stop it replacing trim with mirr
Languages = [ russian_lexer , spanish_lexer , ,
Languages = [russian_lexer, spanish_lexer, portuguese_lexer,
german_lexer, italian_lexer],
Fun = fun(Frontend, NewFormula) ->
{ok, Tokens, _} = Frontend:string(NewFormula),
lists:flatmap(fun({_, YYtext}) -> YYtext end, Tokens)
end,
R = lists:foldl(Fun, [$=|Formula], Languages),
|
41091b814bb44a2b53c4bd69f24ca17e3ae0c130eba2e294dfd3c548d3c4dff0 | lilactown/react-clj | fiber.clj | (ns lilactown.react.fiber
(:require
[clojure.zip :as zip]))
;;
;; Types and protocols
;;
(defprotocol IRender
(render [c props] "Render a component, return a tree of immutable elements"))
(defrecord Element [type props key])
(defrecord FiberNode [alternate type props state children])
(defn element?
[x]
(= Element (type x)))
(defn element-type?
[x]
(or (= Element (type x))
(string? x)
(number? x)))
(defn fiber?
[x]
(= FiberNode (type x)))
;;
Zipper setup
;;
(defn make-fiber
[fiber children]
(if (or (fiber? fiber)
(element? fiber))
(->FiberNode
(:alternate fiber)
(:type fiber)
(:props fiber)
(:state fiber)
children)
fiber))
(defn root-fiber
[alternate el]
(->FiberNode alternate :root {:children [el]} nil nil))
(defn fiber-zipper
[fiber]
(zip/zipper
fiber?
:children
make-fiber
fiber))
;;
;; Hooks
;;
(declare ^:dynamic *hooks-context*)
(defn hooks-context
[alternate-state]
{:state (atom {:index 0
:previous alternate-state
:current []})})
(defn get-previous-hook-state!
[ctx]
(let [{:keys [index previous]} @(:state ctx)]
(nth previous index)))
(defn set-current-hook-state!
[ctx state]
(swap! (:state ctx)
(fn [hooks-state]
(-> hooks-state
(update :current conj state)
(update :index inc)))))
(defn use-ref
[init]
(let [ctx *hooks-context*]
(or (get-previous-hook-state! ctx)
(doto (atom init)
(->> (set-current-hook-state! ctx))))))
(defn use-memo
[f deps]
(let [ctx *hooks-context*
[_ prev-deps :as prev-state] (get-previous-hook-state! ctx)]
(if (not= prev-deps deps)
(let [v (f)
state [v deps]]
(set-current-hook-state! ctx state)
state)
prev-state)))
(defn use-callback
[f deps]
(use-memo #(f) deps))
(defn use-reducer
([f initial]
(use-reducer f initial identity))
([_f initial init-fn]
(let [ctx *hooks-context*
state (or (get-previous-hook-state! ctx)
TODO allow implementation to be swapped in here
[(init-fn initial) (fn [& _])])]
(set-current-hook-state! ctx state)
state)))
(defn use-state
[init]
(let [[state dispatch] (use-reducer
(fn [state [arg & args]]
(if (ifn? arg)
(apply arg state args)
arg))
init)
set-state (use-callback
(fn [& args]
(dispatch args))
[])]
[state set-state]))
(defn use-effect
[f deps]
(let [context *hooks-context*
{:keys [index previous]} @(:state context)
prev-state (nth previous index)
state [f deps]]
deps not=
(when (not= (second prev-state) deps)
TODO schedule effect using impl TBD
nil)
(set-current-hook-state! context state)
nil))
(defn use-layout-effect
[f deps]
(let [context *hooks-context*
{:keys [index previous]} @(:state context)
prev-state (nth previous index)
state [f deps]]
deps not=
(when (not= (second prev-state) deps)
TODO schedule effect using impl TBD
nil)
(set-current-hook-state! context state)
nil))
;;
;; Reconciliation
;;
(defn perform-work
"Renders the fiber, returning child elements"
[{:keys [type props] :as _node}]
(cond
(satisfies? IRender type)
[(render type props)]
;; destructuring doesn't seem to fail if `_node` is actually a primitive
;; i.e. a string or number, so we can just check to see if `type` is
;; `nil` to know whether we are dealing with an actual element
(some? type)
(flatten (:children props))
:else nil))
(defn reconcile-node
[node host-config]
(let [hooks-context (hooks-context (-> node :previous :state))
results (binding [*hooks-context* hooks-context]
(perform-work node))]
(make-fiber
(if (map? node)
(assoc node :state (-> hooks-context :state deref :current))
node)
results)))
(defn reconcile
[fiber host-config]
(loop [loc (fiber-zipper fiber)]
(if (zip/end? loc)
(zip/root loc)
(recur (zip/next (zip/edit loc reconcile-node host-config))))))
;;
;; example
;;
(defn $
([t] (->Element t nil nil))
([t arg]
(if-not (element-type? arg)
(->Element t arg (:key arg))
(->Element t {:children (list arg)} nil)))
([t arg & args]
(if-not (element-type? arg)
(->Element t (assoc arg :children args) (:key arg))
(->Element t {:children (cons arg args)} nil))))
(extend-type clojure.lang.Fn
IRender
(render [f props] (f props)))
(defn greeting
[{:keys [user-name]}]
($ "div"
{:class "greeting"}
"Hello, " user-name "!"))
(defn counter
[_]
(let [[count set-count] (use-state 4)]
($ "div"
($ "button" {:on-click #(set-count inc)} "+")
(for [n (range count)]
($ "div" {:key n} n)))))
(defn app
[{:keys [user-name]}]
($ "div"
{:class "app container"}
($ "h1" "App title")
"foo"
($ greeting {:user-name user-name})
($ counter)))
(def fiber0
(reconcile
(root-fiber nil ($ app {:user-name "Will"}))
{}))
#_(reconcile
(root-fiber fiber0 ($ app {:user-name "Alan"}))
{})
| null | https://raw.githubusercontent.com/lilactown/react-clj/d315d59372dba28655d89a98b2523c36b3366d99/src/lilactown/react/fiber.clj | clojure |
Types and protocols
Hooks
Reconciliation
destructuring doesn't seem to fail if `_node` is actually a primitive
i.e. a string or number, so we can just check to see if `type` is
`nil` to know whether we are dealing with an actual element
example
| (ns lilactown.react.fiber
(:require
[clojure.zip :as zip]))
(defprotocol IRender
(render [c props] "Render a component, return a tree of immutable elements"))
(defrecord Element [type props key])
(defrecord FiberNode [alternate type props state children])
(defn element?
[x]
(= Element (type x)))
(defn element-type?
[x]
(or (= Element (type x))
(string? x)
(number? x)))
(defn fiber?
[x]
(= FiberNode (type x)))
Zipper setup
(defn make-fiber
[fiber children]
(if (or (fiber? fiber)
(element? fiber))
(->FiberNode
(:alternate fiber)
(:type fiber)
(:props fiber)
(:state fiber)
children)
fiber))
(defn root-fiber
[alternate el]
(->FiberNode alternate :root {:children [el]} nil nil))
(defn fiber-zipper
[fiber]
(zip/zipper
fiber?
:children
make-fiber
fiber))
(declare ^:dynamic *hooks-context*)
(defn hooks-context
[alternate-state]
{:state (atom {:index 0
:previous alternate-state
:current []})})
(defn get-previous-hook-state!
[ctx]
(let [{:keys [index previous]} @(:state ctx)]
(nth previous index)))
(defn set-current-hook-state!
[ctx state]
(swap! (:state ctx)
(fn [hooks-state]
(-> hooks-state
(update :current conj state)
(update :index inc)))))
(defn use-ref
[init]
(let [ctx *hooks-context*]
(or (get-previous-hook-state! ctx)
(doto (atom init)
(->> (set-current-hook-state! ctx))))))
(defn use-memo
[f deps]
(let [ctx *hooks-context*
[_ prev-deps :as prev-state] (get-previous-hook-state! ctx)]
(if (not= prev-deps deps)
(let [v (f)
state [v deps]]
(set-current-hook-state! ctx state)
state)
prev-state)))
(defn use-callback
[f deps]
(use-memo #(f) deps))
(defn use-reducer
([f initial]
(use-reducer f initial identity))
([_f initial init-fn]
(let [ctx *hooks-context*
state (or (get-previous-hook-state! ctx)
TODO allow implementation to be swapped in here
[(init-fn initial) (fn [& _])])]
(set-current-hook-state! ctx state)
state)))
(defn use-state
[init]
(let [[state dispatch] (use-reducer
(fn [state [arg & args]]
(if (ifn? arg)
(apply arg state args)
arg))
init)
set-state (use-callback
(fn [& args]
(dispatch args))
[])]
[state set-state]))
(defn use-effect
[f deps]
(let [context *hooks-context*
{:keys [index previous]} @(:state context)
prev-state (nth previous index)
state [f deps]]
deps not=
(when (not= (second prev-state) deps)
TODO schedule effect using impl TBD
nil)
(set-current-hook-state! context state)
nil))
(defn use-layout-effect
[f deps]
(let [context *hooks-context*
{:keys [index previous]} @(:state context)
prev-state (nth previous index)
state [f deps]]
deps not=
(when (not= (second prev-state) deps)
TODO schedule effect using impl TBD
nil)
(set-current-hook-state! context state)
nil))
(defn perform-work
"Renders the fiber, returning child elements"
[{:keys [type props] :as _node}]
(cond
(satisfies? IRender type)
[(render type props)]
(some? type)
(flatten (:children props))
:else nil))
(defn reconcile-node
[node host-config]
(let [hooks-context (hooks-context (-> node :previous :state))
results (binding [*hooks-context* hooks-context]
(perform-work node))]
(make-fiber
(if (map? node)
(assoc node :state (-> hooks-context :state deref :current))
node)
results)))
(defn reconcile
[fiber host-config]
(loop [loc (fiber-zipper fiber)]
(if (zip/end? loc)
(zip/root loc)
(recur (zip/next (zip/edit loc reconcile-node host-config))))))
(defn $
([t] (->Element t nil nil))
([t arg]
(if-not (element-type? arg)
(->Element t arg (:key arg))
(->Element t {:children (list arg)} nil)))
([t arg & args]
(if-not (element-type? arg)
(->Element t (assoc arg :children args) (:key arg))
(->Element t {:children (cons arg args)} nil))))
(extend-type clojure.lang.Fn
IRender
(render [f props] (f props)))
(defn greeting
[{:keys [user-name]}]
($ "div"
{:class "greeting"}
"Hello, " user-name "!"))
(defn counter
[_]
(let [[count set-count] (use-state 4)]
($ "div"
($ "button" {:on-click #(set-count inc)} "+")
(for [n (range count)]
($ "div" {:key n} n)))))
(defn app
[{:keys [user-name]}]
($ "div"
{:class "app container"}
($ "h1" "App title")
"foo"
($ greeting {:user-name user-name})
($ counter)))
(def fiber0
(reconcile
(root-fiber nil ($ app {:user-name "Will"}))
{}))
#_(reconcile
(root-fiber fiber0 ($ app {:user-name "Alan"}))
{})
|
f99804b9060c0cfef9e7938016d3e2ea9c8683c34ea4df4ec85be95a95951ba1 | jdan/ocaml-web-framework | http.ml | module RequestBuffer = struct
let buffer_length = 1024
(* *)
let index_string s1 s2 =
let re = Str.regexp_string s2
in
try Str.search_forward re s1 0
with Not_found -> -1
let rec recv_until socket buffer needle =
(* TODO: We don't need to check the entire buffer, just
the characters we've added to the buffer *)
let index = index_string buffer needle in
if index > -1 then
(* TODO: String.split_in_two *)
let str = String.sub buffer 0 index in
let remaining_buffer =
let start_index = index + (String.length needle) in
String.sub buffer start_index ((String.length buffer) - start_index)
in (str, remaining_buffer)
else
let in_bytes = Bytes.create buffer_length in
match (Unix.recv socket in_bytes 0 buffer_length []) with
| 0 -> ("", buffer)
| length ->
recv_until
socket
(buffer ^ (String.sub (Bytes.to_string in_bytes) 0 length))
needle
let recv_line socket buffer =
let (line, buffer) = recv_until socket buffer "\r\n" in
(* Debug! *)
print_endline ("> " ^ line);
(line, buffer)
end
module Request = struct
type request_line = { meth: string ;
path: string ;
version: string ;
}
type request = { line: request_line ;
headers: (string, string) Hashtbl.t ;
}
let req_method req = req.line.meth
let req_path req = req.line.path
let req_version req = req.line.version
let line_of_string line =
match (String.split_on_char ' ' line) with
| [meth ; path ; version] ->
{ meth = meth ;
path = path ;
version = version ;
}
| _ -> raise (Invalid_argument ("Invalid request line: " ^ line))
let request_of_line line = { line = line_of_string line ;
headers = Hashtbl.create 10 ;
}
let recv_request_line socket =
let (line, buffer) = RequestBuffer.recv_line socket "" in
(line_of_string line, buffer)
let recv_request_headers socket buffer =
let headers = Hashtbl.create 10 in
let rec inner buffer =
let (line, new_buffer) = RequestBuffer.recv_line socket buffer in
if line = "" then headers
else
match (Str.split_delim (Str.regexp_string ": ") line) with
| [key ; value] -> begin
Hashtbl.add headers key value;
inner new_buffer
end
| _ -> raise (Invalid_argument ("Invalid header: " ^ line))
in
inner buffer
let recv_request socket =
let (line, buffer) = recv_request_line socket in
let headers = recv_request_headers socket buffer in
{ line = line ;
headers = headers ;
}
end
module Response = struct
type response = { socket: Unix.file_descr ;
status: int ;
headers: (string, string) Hashtbl.t ;
body: string ;
}
let response_body response = response.body
let response_status response = response.status
let response_of_socket socket =
let headers = Hashtbl.create 10 in
Hashtbl.add headers "X-Served-By" "OCamlNet";
{ socket = socket ;
status = 200 ;
headers = headers ;
body = "" ;
}
let send_line res line =
let with_return = line ^ "\r\n" in
ignore (Unix.send res.socket (Bytes.of_string with_return) 0 (String.length with_return) [])
let phrase_of_status_code = function
| 200 -> "OK"
| 404 -> "Not found"
| _ -> "Unknown"
let send_headers res =
Hashtbl.iter
(fun k v ->
send_line res (Printf.sprintf "%s: %s" k v))
res.headers
let send res =
send_line
res
(Printf.sprintf "HTTP/1.1 %d %s"
res.status
(phrase_of_status_code res.status));
send_headers res;
send_line res "";
send_line res res.body
let set_status status res =
{ res with status = status }
let set_header k v res =
Hashtbl.add res.headers k v;
res
let set_body body res =
ignore (set_header "Content-Length" (string_of_int (String.length body)) res);
{ res with
body = body ;
}
let send_string str res =
send (set_body str res)
end
type handler = Request.request -> Response.response -> unit
let create_server port (handler: handler) =
let max_connections = 8 in
let my_addr = Unix.inet_addr_of_string "0.0.0.0" in
let s_descr = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
Unix.setsockopt s_descr Unix.SO_REUSEADDR true;
Unix.bind s_descr (Unix.ADDR_INET(my_addr, port));
Unix.listen s_descr max_connections;
while true do
let (conn_socket, conn_addr) = Unix.accept s_descr in
let req = Request.recv_request conn_socket in
let res = Response.response_of_socket conn_socket in
handler req res
done
| null | https://raw.githubusercontent.com/jdan/ocaml-web-framework/bfa2f240a9aecc4edbf02ab87a73cfd20da482a4/src/http.ml | ocaml |
TODO: We don't need to check the entire buffer, just
the characters we've added to the buffer
TODO: String.split_in_two
Debug! | module RequestBuffer = struct
let buffer_length = 1024
let index_string s1 s2 =
let re = Str.regexp_string s2
in
try Str.search_forward re s1 0
with Not_found -> -1
let rec recv_until socket buffer needle =
let index = index_string buffer needle in
if index > -1 then
let str = String.sub buffer 0 index in
let remaining_buffer =
let start_index = index + (String.length needle) in
String.sub buffer start_index ((String.length buffer) - start_index)
in (str, remaining_buffer)
else
let in_bytes = Bytes.create buffer_length in
match (Unix.recv socket in_bytes 0 buffer_length []) with
| 0 -> ("", buffer)
| length ->
recv_until
socket
(buffer ^ (String.sub (Bytes.to_string in_bytes) 0 length))
needle
let recv_line socket buffer =
let (line, buffer) = recv_until socket buffer "\r\n" in
print_endline ("> " ^ line);
(line, buffer)
end
module Request = struct
type request_line = { meth: string ;
path: string ;
version: string ;
}
type request = { line: request_line ;
headers: (string, string) Hashtbl.t ;
}
let req_method req = req.line.meth
let req_path req = req.line.path
let req_version req = req.line.version
let line_of_string line =
match (String.split_on_char ' ' line) with
| [meth ; path ; version] ->
{ meth = meth ;
path = path ;
version = version ;
}
| _ -> raise (Invalid_argument ("Invalid request line: " ^ line))
let request_of_line line = { line = line_of_string line ;
headers = Hashtbl.create 10 ;
}
let recv_request_line socket =
let (line, buffer) = RequestBuffer.recv_line socket "" in
(line_of_string line, buffer)
let recv_request_headers socket buffer =
let headers = Hashtbl.create 10 in
let rec inner buffer =
let (line, new_buffer) = RequestBuffer.recv_line socket buffer in
if line = "" then headers
else
match (Str.split_delim (Str.regexp_string ": ") line) with
| [key ; value] -> begin
Hashtbl.add headers key value;
inner new_buffer
end
| _ -> raise (Invalid_argument ("Invalid header: " ^ line))
in
inner buffer
let recv_request socket =
let (line, buffer) = recv_request_line socket in
let headers = recv_request_headers socket buffer in
{ line = line ;
headers = headers ;
}
end
module Response = struct
type response = { socket: Unix.file_descr ;
status: int ;
headers: (string, string) Hashtbl.t ;
body: string ;
}
let response_body response = response.body
let response_status response = response.status
let response_of_socket socket =
let headers = Hashtbl.create 10 in
Hashtbl.add headers "X-Served-By" "OCamlNet";
{ socket = socket ;
status = 200 ;
headers = headers ;
body = "" ;
}
let send_line res line =
let with_return = line ^ "\r\n" in
ignore (Unix.send res.socket (Bytes.of_string with_return) 0 (String.length with_return) [])
let phrase_of_status_code = function
| 200 -> "OK"
| 404 -> "Not found"
| _ -> "Unknown"
let send_headers res =
Hashtbl.iter
(fun k v ->
send_line res (Printf.sprintf "%s: %s" k v))
res.headers
let send res =
send_line
res
(Printf.sprintf "HTTP/1.1 %d %s"
res.status
(phrase_of_status_code res.status));
send_headers res;
send_line res "";
send_line res res.body
let set_status status res =
{ res with status = status }
let set_header k v res =
Hashtbl.add res.headers k v;
res
let set_body body res =
ignore (set_header "Content-Length" (string_of_int (String.length body)) res);
{ res with
body = body ;
}
let send_string str res =
send (set_body str res)
end
type handler = Request.request -> Response.response -> unit
let create_server port (handler: handler) =
let max_connections = 8 in
let my_addr = Unix.inet_addr_of_string "0.0.0.0" in
let s_descr = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
Unix.setsockopt s_descr Unix.SO_REUSEADDR true;
Unix.bind s_descr (Unix.ADDR_INET(my_addr, port));
Unix.listen s_descr max_connections;
while true do
let (conn_socket, conn_addr) = Unix.accept s_descr in
let req = Request.recv_request conn_socket in
let res = Response.response_of_socket conn_socket in
handler req res
done
|
7ca6ab0bae7a9d039b67bb76a48efbe1ccf1534330956a3909a1182cd2c91ffb | OlafChitil/hat | Ident.hs | module Ident
( Ident(..)
, getIdentAt -- :: FileNode -> IO Ident
) where
import LowLevel (FileNode(..))
import System.IO.Unsafe (unsafePerformIO)
import Foreign.Ptr (Ptr)
import Foreign.Marshal.Alloc (free)
import Foreign.C.String (CString, peekCString)
foreign import ccall " malloc.h & free " finaliserFree : : FunPtr ( Ptr a - > IO ( ) )
-- All possible relevant information about an identifier
data Ident = Ident
{ i_name :: String
, i_modname :: String
, i_srcfile :: String
, i_fixity :: Int
, i_arity :: Int
, i_defnline :: Int
, i_defncol :: Int
, i_defnlineend :: Int
, i_defncolend :: Int
, i_isTraced :: Bool
, i_caf :: Bool
, i_uses :: Int
, i_pending :: Int
, i_thunks :: Int
}
foreign import ccall "artutils.h" readAtomAt :: FileNode -> IO (Ptr Ident)
foreign import ccall "artutils.h" identName :: Ptr Ident -> IO CString
foreign import ccall "artutils.h" identModName :: Ptr Ident -> IO CString
foreign import ccall "artutils.h" identSrcFile :: Ptr Ident -> IO CString
foreign import ccall "artutils.h" identFixity :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identArity :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identDefnLine :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identDefnCol :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identDefnLineEnd :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identDefnColEnd :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identIsTraced :: Ptr Ident -> IO Bool
getIdentAt :: FileNode -> IO Ident
getIdentAt n = do
p is in C land
nm <- identName p
mod <- identModName p
src <- identSrcFile p
fix <- identFixity p
ar <- identArity p
dl <- identDefnLine p
dc <- identDefnCol p
dle <- identDefnLineEnd p
dce <- identDefnColEnd p
tr <- identIsTraced p
snm <- peekCString nm
smod <- peekCString mod
ssrc <- peekCString src
dispose of p again
return Ident
{ i_name = snm
, i_modname = smod
, i_srcfile = ssrc
, i_fixity = fix
, i_arity = ar
, i_defnline = dl
, i_defncol = dc
, i_defnlineend = dle
, i_defncolend = dce
, i_isTraced = tr
, i_caf = error "Ident.getIdentAt i_caf"
, i_uses = error "Ident.getIdentAt i_uses"
, i_pending = error "Ident.getIdentAt i_pending"
, i_thunks = error "Ident.getIdentAt i_thunks"
}
---------------------------------------------------------------------
| null | https://raw.githubusercontent.com/OlafChitil/hat/8840a480c076f9f01e58ce24b346850169498be2/tools/Ident.hs | haskell | :: FileNode -> IO Ident
All possible relevant information about an identifier
------------------------------------------------------------------- | module Ident
( Ident(..)
) where
import LowLevel (FileNode(..))
import System.IO.Unsafe (unsafePerformIO)
import Foreign.Ptr (Ptr)
import Foreign.Marshal.Alloc (free)
import Foreign.C.String (CString, peekCString)
foreign import ccall " malloc.h & free " finaliserFree : : FunPtr ( Ptr a - > IO ( ) )
data Ident = Ident
{ i_name :: String
, i_modname :: String
, i_srcfile :: String
, i_fixity :: Int
, i_arity :: Int
, i_defnline :: Int
, i_defncol :: Int
, i_defnlineend :: Int
, i_defncolend :: Int
, i_isTraced :: Bool
, i_caf :: Bool
, i_uses :: Int
, i_pending :: Int
, i_thunks :: Int
}
foreign import ccall "artutils.h" readAtomAt :: FileNode -> IO (Ptr Ident)
foreign import ccall "artutils.h" identName :: Ptr Ident -> IO CString
foreign import ccall "artutils.h" identModName :: Ptr Ident -> IO CString
foreign import ccall "artutils.h" identSrcFile :: Ptr Ident -> IO CString
foreign import ccall "artutils.h" identFixity :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identArity :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identDefnLine :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identDefnCol :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identDefnLineEnd :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identDefnColEnd :: Ptr Ident -> IO Int
foreign import ccall "artutils.h" identIsTraced :: Ptr Ident -> IO Bool
getIdentAt :: FileNode -> IO Ident
getIdentAt n = do
p is in C land
nm <- identName p
mod <- identModName p
src <- identSrcFile p
fix <- identFixity p
ar <- identArity p
dl <- identDefnLine p
dc <- identDefnCol p
dle <- identDefnLineEnd p
dce <- identDefnColEnd p
tr <- identIsTraced p
snm <- peekCString nm
smod <- peekCString mod
ssrc <- peekCString src
dispose of p again
return Ident
{ i_name = snm
, i_modname = smod
, i_srcfile = ssrc
, i_fixity = fix
, i_arity = ar
, i_defnline = dl
, i_defncol = dc
, i_defnlineend = dle
, i_defncolend = dce
, i_isTraced = tr
, i_caf = error "Ident.getIdentAt i_caf"
, i_uses = error "Ident.getIdentAt i_uses"
, i_pending = error "Ident.getIdentAt i_pending"
, i_thunks = error "Ident.getIdentAt i_thunks"
}
|
06734d1ba8540d3d03b7ac3b7abcf65fd2fa7de91040130fa46333a54f3f8d66 | mathematical-systems/clml | iterate-test.lisp | ;;; Test cases for Iterate.
Copyright ( c ) 2003 < >
Copyright ( c ) 2004 - 2007 < >
;;; License:
;; 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.
;;; Commentary:
;; Although growing, this testsuite does not yet cover every documented
;; feature of Iterate.
(cl:defpackage #:iterate.test
(:use #:cl #:iterate
#+sbcl #:sb-rt
#-sbcl #:regression-test))
(cl:in-package #:iterate.test)
(rem-all-tests)
(deftest dsetq.1
(let (x y)
(dsetq (x y) (list* 4 5 6))
(list x y))
(4 5))
(deftest dsetq.2
(let (x y)
(dsetq (x nil y) (list* 4 5 6 7))
(list x y))
(4 6))
(deftest dsetq.3
(let ((a '((1 2) 3)) b)
(dsetq (a b) a)
(values a b))
(1 2) 3)
(deftest dsetq.destructuring.1
(let (x y)
(dsetq (x . y) (list* 4 5 6))
(list x y))
(4 (5 . 6)))
(deftest dsetq.destructuring.2
(let (x y z)
(dsetq (x nil (y . z)) (list* 4 5 '(6 7 . 8) 9))
(list x y z))
(4 6 (7 . 8)))
(deftest dsetq.values.1
(let (x y)
(dsetq (values x y) (values 1 'a))
(list x y))
(1 a))
(deftest dsetq.values.2
(let (x y)
(dsetq (values x nil y) (values 1 'a "c"))
(list x y))
(1 "c"))
(deftest dsetq.values.3
(let (x)
(dsetq (values nil (nil . x)) (values 1 '(a b . c)))
x)
(b . c))
(deftest dsetq.values.4
(let (x y z) (dsetq (values nil x (y z))
(values 1 'a '(b c))) (list x y z))
(a b c))
(deftest repeat.1
(iter (repeat 9) (count 1))
9)
(deftest repeat.2
(iter (repeat 2.5s0) (counting t))
3)
(deftest repeat.3
(iter (repeat -1.5f0) (counting t))
0)
(deftest locally.1
(iterate (for i in '(1 2 3)) (repeat 2)
(locally (collect i) (collect 0)))
(1 0 2 0))
(deftest locally.2
(iterate (for i in '(1 2 3)) (repeat 2)
(locally
(declare (optimize safety))
(declare (fixnum i)) (collect i)))
(1 2))
(deftest always.1
(iter (repeat 3) (always 2))
2)
(deftest always.2
(iter (repeat 0) (always 2))
t)
(deftest always.3
(iter (for i in '()) (always i))
t)
(deftest always.never.1
(iterate (repeat 2)
(always 2)
(never nil))
2)
(deftest always.never.2
(iter (for x in '(b (2 . a)))
(if (consp x) (always (car x)) (always x))
(never nil))
2)
(deftest thereis.finally.1
(iter (repeat 3) (thereis nil) (finally (prin1 "hi")))
nil)
(deftest thereis.finally.2
(with-output-to-string (*standard-output*)
(iter (repeat 3) (thereis nil) (finally (princ "hi"))))
"hi")
(deftest thereis.finally.3
(iter (repeat 3) (thereis nil) (finally (return 2)))
2)
(deftest thereis.finally-protected.1
(iter (repeat 3) (thereis 4) (finally-protected (prin1 "hi")))
4)
(deftest thereis.finally-protected.2
(with-output-to-string (*standard-output*)
(iter (repeat 3) (thereis 4) (finally-protected (princ "hi"))))
"hi")
(deftest finding.such-that.2
(iter (for i in '(7 -4 2 -3 4))
(if (plusp i)
(finding i such-that (evenp i))
(finding (- i) such-that (oddp i))))
2)
(deftest finding.such-that.nest.1
(iter (for i in '(1 2 3))
(finding (1+ i)
such-that #'(lambda (x)
(declare (ignore x))
(collect (- i) into m))))
2) ; not -1 as some old version did
(deftest finding.such-that.nest.2
(iter (for i in '(1 2 3))
(finding (1+ i)
such-that #'(lambda (x)
(finding (- x)
such-that #'(lambda (x) x nil)
into n)
t)
into m)
(finally (return (values m n))))
2 nil) ; not -2 nil as some old version did
(deftest finding.thereis.1
(iterate (for x in '(a 7 (-4 -3)))
(thereis (consp x))
(finding x such-that (numberp x)))
7)
(deftest finding.thereis.2
(iterate (for x in '(a (-4 -3) 7))
(thereis (consp x))
(finding x such-that (numberp x)))
t)
(deftest finding.thereis.3
(iterate (for x in '(a #\b))
(thereis (consp x))
(finding x such-that (numberp x)))
nil)
(deftest finding.always.1
(iterate (for x in '(-4 -2 -3))
(always (numberp x))
(finding x such-that (plusp x) on-failure t))
t)
(deftest finding.always.2
(iterate (for x in '(-4 7 -2 -3))
(always (numberp x))
(finding x such-that (plusp x) on-failure t))
7)
(deftest finding.always.3
(iterate (for x in '(-4 c -3))
(always (numberp x))
(finding x such-that (plusp x) on-failure t))
nil)
(defun setup-hash-table (hash)
(dotimes (i (random 100)) (declare (ignorable i))
(setf (gethash (random 10000) hash) (random 10000))
(setf (gethash (gensym) hash) (gensym))))
(deftest in-hashtable.keys
(let* ((hash (make-hash-table))
(all-entries (progn (setup-hash-table hash) '()))
(generated-entries
(iterate (for (key) in-hashtable hash)
(collect key))))
(maphash (lambda (key value) value (push key all-entries)) hash)
(= (length all-entries)
(length generated-entries)
(length (union all-entries generated-entries
:test (hash-table-test hash)))))
t)
(deftest in-hashtable.items.1
(let ((items nil)
(hash (make-hash-table)))
(setup-hash-table hash)
(maphash (lambda (key item) key (push item items)) hash)
(set-difference items
(iterate (for (key item) in-hashtable hash)
(declare (ignore key))
(collect item))))
nil)
(deftest in-hashtable.items.2
(let ((items nil)
(hash (make-hash-table)))
(setup-hash-table hash)
(maphash (lambda (key item) key (push item items)) hash)
(set-difference items
(iterate (for (nil item) in-hashtable hash)
(collect item))))
nil)
(deftest in-hashtable.1
(let* ((hash (make-hash-table))
(all-entries (progn (setup-hash-table hash) '()))
(generated-entries
(iterate (as (key item) in-hashtable hash)
(collect (cons key item)))))
(maphash #'(lambda (key value) (push (cons key value) all-entries)) hash)
(= (length all-entries)
(length generated-entries)
(length (union all-entries generated-entries
:key #'car :test (hash-table-test hash)))))
t)
(deftest in-hashtable.destructuring.1
(let ((hash (make-hash-table :test #'equal))
(entries '(((a . b) . (1 . 2)) (("c" . 3) . (6 . "7")))))
(iterate (for (k . v) in entries)
(setf (gethash k hash) v))
(sort
(iterate (for ((nil . k2) (v1 . v2)) in-hashtable hash)
(always (numberp v1))
(while k2)
(collect (cons v1 k2) into vals)
(finally (return vals)))
#'< :key #'car))
((1 . b) (6 . 3)))
(deftest in-package.internals
(let ((syms nil)
(iter-syms (iterate (for sym in-package *package* :external-only nil)
(collect sym))))
(do-symbols (sym *package* nil)
(push sym syms))
(list
(set-difference syms iter-syms :test #'eq)
(set-difference iter-syms syms)))
(()()))
(deftest in-package.externals.1
(let ((syms nil)
(iter-syms (iterate (for sym in-package '#:cl-user external-only t)
(collect sym))))
(do-external-symbols (sym '#:cl-user nil)
(push sym syms))
(list
(set-difference syms iter-syms :test #'eq)
(set-difference iter-syms syms)))
(()()))
(deftest in-package.externals.2
(let ((sym-count 0))
(do-external-symbols (sym '#:iterate) (declare (ignore sym))
(incf sym-count))
(= sym-count
(iterate (for () in-package '#:iterate external-only t)
(count 1))))
t)
(deftest in-package.generator
(let ((syms nil)
(iter-syms (iterate (generate sym in-package *package*)
(collect (next sym)))))
(do-symbols (sym *package*)
(push sym syms))
(list
(set-difference syms iter-syms :test #'eq)
(set-difference iter-syms syms)))
(()()))
(deftest in-packages.external
(let ((syms nil)
(iter-syms (iterate (as (sym access package) in-packages '(#:cl-user)
:having-access (:external))
(collect sym))))
(do-external-symbols (sym '#:cl-user nil)
(push sym syms))
(list
(set-difference syms iter-syms :test #'eq)
(set-difference iter-syms syms)))
(()()))
(deftest in-packages.generator-access
(let ((iter-syms (iterate (generate (sym access) in-packages (list (find-package "COMMON-LISP")))
(repeat 1)
(next sym)
(collect (list sym access)))))
(equal (multiple-value-list
(find-symbol (symbol-name (caar iter-syms)) "COMMON-LISP"))
(car iter-syms)))
t)
(deftest in-stream.1
(iter (as x in-stream (make-string-input-stream "#xa()2"))
(collect x))
(10 () 2))
(deftest in-stream.previous
(iter (for x in-stream (make-string-input-stream "#xa()2"))
(as p previous x :initially 1)
(collect p))
(1 10 ()))
(deftest in-stream.2
This fails in cmucl , sbcl and gcl , because string - input - streams
;; are always open, even after close.
(let ((s (make-string-input-stream "(")))
(ignore-errors
(iter (for x in-stream s :using #'read)))
(open-stream-p s))
nil)
(deftest in-stream.3
(iter (for c in-stream (make-string-input-stream "235")
:using #'read-char)
(accumulating (digit-char-p c) by #'+ initial-value 0))
10)
(deftest in-stream.reducing
(iter (with s = (make-string-input-stream "(+ 2)(+ 10)(- 5)(+ 6)"))
(for (op num) in-stream s)
(reducing num :by op :initial-value 0))
13)
(deftest in-stream.accumulating
(iter (with s = (make-string-input-stream "(+ 2)(+ 10)(- 5)(+ 6)"))
(for (op num) in-stream s)
(accumulating num :by op :initial-value 0))
( 6 + ( 5 - ( 10 + ( 2 + 0 ) ) ) )
(deftest in-stream.generate
(iter (with s = (make-string-input-stream "2 + 10 - 5 + 6"))
(with start = (read s))
(generate e in-stream s using #'read)
(as op = (next e))
(for arg = (next e))
(reducing arg by op initial-value start))
13)
(deftest reducing.0
(iter (with expr = '(2 + 10 - 5 + 6))
(with start = (pop expr))
(for (op arg) on expr by #'cddr)
(reducing arg by op initial-value start))
13)
(deftest until.1
(iter (with rest = 235) (with digit = 0)
(multiple-value-setq (rest digit) (floor rest 10))
(sum digit into sum)
(multiplying digit into product)
(until (zerop rest))
(finally (return (values sum product))))
10 30)
(deftest until.2
(iter (for i in-sequence '#(1 2 -3 6))
(until (zerop (sum i into x)))
(multiplying i))
2)
(deftest while.1
(iter (for i in-sequence '#(1 2 -3 6))
(while (< (length (collect i)) 2)))
(1 2))
(deftest else.1
(iter (repeat 0)
(else (return 1)))
1)
(deftest else.2
(iter (for i below -3)
(else (return 2)))
2)
;;; tests for my examples:
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *an-alist* '((a . 2) (b . 3) (zero . 10) (c . 4) (one . 20) (d . 5) (e . 99)))
(defparameter *list-of-lists* (loop for i from 0 to 100
collect (loop for len from 0 to (random 20)
collect len)))
(defun longest-list (list1 list2)
(if (< (length list2) (length list1))
list1
list2)))
(deftest collect.1
(iterate (as (key . item) in *an-alist*)
(collect key into keys)
(collect item into items)
(finally (return (values keys items))))
#.(loop for (key . nil) in *an-alist*
collect key)
#.(loop for (key . item) in *an-alist*
collect item))
(deftest generate.1
(iterate (generate i from 0 to 6)
(for (key . value) in *an-alist*)
(when (>= value 10)
(collect (cons key (next i)))))
#.(loop with counter = 0
for (key . value) in *an-alist*
when (>= value 10)
collect (cons key (prog1 counter (incf counter)))))
(deftest find-longest-list.1
(iterate (for elt in *list-of-lists*)
(finding elt maximizing (length elt)))
#.(reduce #'longest-list *list-of-lists*))
(deftest find-longest-list.2
(iterate (for elt in *list-of-lists*)
(finding elt maximizing (length elt) into (e m))
(finally (return m)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest find-longest-list.3
(iterate (for elt in *list-of-lists*)
(finding elt maximizing #'length))
#.(reduce #'longest-list *list-of-lists*))
(deftest find-longest-list.4
(iterate (for elt in *list-of-lists*)
(finding elt maximizing #'length into (e m))
(finally (return m)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest maximize.1
(iterate (for elt in *list-of-lists*)
(maximizing (length elt) into m)
(finally (return m)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest maximize.2
(iterate (for elt in *list-of-lists*)
(maximize (length elt)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest finding.minimizing.1
(iterate (for elt in *list-of-lists*)
(finding elt minimizing #'length into (e m))
(finally (return m)))
#.(reduce #'min *list-of-lists* :key #'length))
(deftest minimize.1
(iterate (for elt in *list-of-lists*)
(minimizing (length elt) into m)
(finally (return m)))
#.(reduce #'min *list-of-lists* :key #'length))
(deftest minimize.2
(iterate (for elt in *list-of-lists*)
(minimize (length elt)))
#.(reduce #'min *list-of-lists* :key #'length))
(deftest subblocks.maximize.1
(iter outer (for elt in *list-of-lists*)
(iterate running (for e in elt)
(in outer (maximize e)))
(maximizing (length elt)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest subblocks.minimize.1
(iter outer (for elt in *list-of-lists*)
(minimizing (length elt))
(iterate running (for e in elt)
(in outer (minimize e))))
0)
(deftest maximize.3
(iterate (for i in-vector '#(-3))
(maximize i))
-3)
(deftest minimize.3
(iterate (as i in-vector '#(3))
(minimize i))
3)
(deftest maximize.multiple
(iter (as i from 3 downto -3 by 2) (maximize i)
(for j from -1) (maximizing j))
3)
(deftest minimize.multiple
(iter (as i from -3 to 3 by 2) (minimize i into x)
(for j downfrom -1) (minimizing j into x)
(finally (return x)))
-4)
(deftest accumulate.1
(iter (for c in-string "235")
(declare (type character c))
(accumulate (digit-char-p c) by '* initial-value 1))
30)
(deftest accumulate.2
(iter (for c in-sequence "235")
(accumulating (digit-char-p c) by #'* initial-value 1))
30)
(deftest accumulate.3
(iter (for c in-sequence "235")
(accumulate (digit-char-p c) by 'cons initial-value 1))
(5 3 2 . 1))
(deftest accumulate.4
(iter (for c in-vector "235")
(accumulating (digit-char-p c) by #'cons))
(5 3 2))
(deftest accumulate.5
(iter (repeat 0)
(accumulating 1 by #'cons))
nil)
(deftest accumulate.6
(iter (repeat 0)
(accumulate 1 by #'cons initial-value 2))
2)
(deftest in-string.downto.1
(iter (for c in-string "235" downto 1)
(accumulate (digit-char-p c) by 'cons))
(3 5))
(deftest in-sequence.downto.1
(iter (for c in-sequence "235" downto 1)
(accumulate (digit-char-p c) by #'cons))
(3 5))
(deftest reducing.1
(iter (for c in-string "235")
(reducing (digit-char-p c) by 'list initial-value 1))
(((1 2) 3) 5))
(deftest reducing.2
(iter (as x index-of-string "235")
(reducing x :by #'list initial-value -1))
(((-1 0) 1) 2))
(deftest reducing.3
(iter (repeat 0)
(reducing 1 #:by 'cons initial-value -1))
-1)
(deftest reducing.4
(iter (for i from 3 to 5)
(reducing i by #'- :initial-value '0))
-12)
(deftest reducing.5
(iter (for x in-vector #(3))
(reducing (cons x x) by #'list))
(3 . 3))
(deftest reducing.6
(iter (for x in-vector (vector 3))
(reducing (cons x x) by #'list :initial-value nil))
(nil (3 . 3)))
;; synonyms (e.g. GENERATING, COLLECTING) didn't work
(deftest generate.destructuring.1
(iter (generate (key . item) in '((a . 1) (b . 2) (c .3)))
(collect (next key))
(collect (next item)))
(a 2 c))
(deftest generating.destructuring.1
(iter (generating (key . item) in '((a . 1) (b . 2) (c .3)))
(collect (next key))
(collect (next item)))
(a 2 c))
(deftest for.generate-t.destructuring.1
(iter (for (key . item) in '((a . 1) (b . 2) (c .3)) :generate t)
(collect (next key))
(collect (next item)))
(a 2 c))
(deftest generate.next.1
(iter (generate c in '(a b c d e f g h i j k l m n o p q))
(for s in '(1 1 2 3 1 0 1 0 2 1))
(collect (next c s)))
(a b d g h h i i k l))
(deftest generate.previous.1
(iter (generate c in '(a b c d e f g h i j k l m n o p q))
(for s in '(1 1 2 3 1 0 1 0 2 1))
(for x = (next c s))
(as y previous x)
(collect (list y x)))
((nil a) (a b) (b d) (d g) (g h) (h h) (h i) (i i) (i k) (k l)))
(deftest generate.next.2
(with-output-to-string (*standard-output*)
(iter (generate i in '(1 2 3 4 5)) (princ (next i 2))))
"24")
(deftest if.1
(iter (generate x in-vector '#(t nil nil t))
(as i from 0)
(if (next x) (collect i)))
(0 3))
(deftest if.2
(iter (generate x in-vector '#(t nil nil t) with-index i)
(if (next x) (collect i)))
(0 3))
(deftest or.1
(iter (generate x in '(a nil nil 1))
(generate y in-vector '#(2 #\c #\d))
(collect (or (next x) (next y))))
(a 2 #\c 1))
(deftest or.2
(iter (generate x in '(a nil nil 1 nil))
(generate y in-sequence '#(2 nil #\c #\d))
(collect (or (next x) (next y) 3)))
(a 2 3 1 #\c))
(deftest setf.1
(iter (generate i from 0 to 3)
(with v = (vector 'a 'b 'c 'd))
(setf (aref v (next i)) i)
(finally (return v)))
#(0 1 2 3))
(deftest setf.2
These setf tests fail in CormanLisp 2.0 because ccl does
not respect setf evaluation order rules .
(iter (generate i from 0 to 3)
(with v = (vector 'a 'b 'c 'd))
(setf (aref v (next i)) (next i))
(finally (return v)))
#(1 b 3 d))
(deftest setf.3
(iter (generate i in '(0 1 2 3 4 5))
(with v = (vector 'a 'b 'c 'd))
(setf (aref v (next i)) (next i 2))
(finally (return v)))
#(2 b c 5))
(deftest setf.4
(iter (generate i from 0 to 3)
(with v = (vector 'a 'b 'c 'd))
(setf (apply #'aref v (list (next i))) (next i))
(finally (return v)))
#(1 b 3 d))
(deftest after-each.1
(iter (after-each (collecting 0))
(generate i in '(a b c))
(adjoining (next i)))
(a 0 b 0 c 0))
(deftest after-each.2
(iter (with i = 0)
(while (< i 4))
(after-each (incf i)) ; the C programmer's for (;;) loop
(collect i))
(0 1 2 3))
(deftest after-each.3
(iter (with i = 0)
(while (< i 4))
(collect i)
(after-each (incf i)))
(0 1 2 3))
(deftest next-iteration.1
(iter (for i below 10)
(when (oddp i) (next-iteration))
(count t))
5)
(deftest next-iteration.2
(iter (for thing in '(var &optional else &key (test #'eql)))
(collect
(cond ((consp thing) (first thing))
((not (member thing lambda-list-keywords)) thing)
(t (next-iteration)))))
(var else test))
;;;; tests from the documentation:
(deftest collect.2
(iter (for i from 1 to 10)
(collect i))
(1 2 3 4 5 6 7 8 9 10))
(deftest for-in.2
(iter (for el in '(1 2 3 4 5 6 f 7 8 9 a 10))
(if (and (numberp el) (oddp el))
(collect el)))
(1 3 5 7 9))
(deftest for.destructuring.1
(iter (for (key . item) in '((a . 10) (b . 20) (c . 30)))
(for i from 0)
(declare (fixnum i))
(collect (cons i key)))
((0 . a) (1 . b) (2 . c)))
(deftest repeat.0
(with-output-to-string (*standard-output*)
(iter (repeat 100)
(print "I will not talk in class.")))
#.(with-output-to-string (*standard-output*)
(dotimes (i 100)
(declare (ignorable i)) ; cmucl/sbcl complain about (ignore i)
(print "I will not talk in class."))))
;;; for.next.1 and for.do-next.1 used to be broken in older versions;
they did n't WALK their NEXT args .
(deftest for.next.1
(iterate (initially (setq i 0))
(for i next (if (> i 10) (terminate) (1+ i)))
(finally (return i)))
11)
;;; This gave STYLE-WARNINGS for undefined i in old versions.
(deftest for.do-next.1
(iterate (initially (setq i 0))
(as i do-next (if (> i 10) (terminate) (incf i)))
(finally (return i)))
11)
(deftest for.do-next.2
INITIALLY not needed because 0 is inferred from type declaration
(iterate (for i do-next (if (> i 7) (terminate) (incf i)))
(declare (type fixnum i))
(finally (return i)))
8)
(deftest for.do-next.3
(iter (for a from 1 to 3)
(for b = (1+ (* a a)))
;; (values ...) is supported, even though (x y) would do
(for (values x y) do-next (dsetq (values x y) (floor b a)))
(collect x) (collect y))
(2 0 2 1 3 1))
(deftest for.next.walk
(iter (repeat 2)
(for x next (progn (after-each (collect 1)) 2))
(collect x))
(2 1 2 1))
(deftest for.do-next.walk
(iter (repeat 2)
(for x do-next (progn (after-each (collect 1)) (dsetq x 2)))
(collect x))
(2 1 2 1))
(deftest for.next.previous
(iter (for i from 2 to 4)
(for x next (progn (after-each (collect i)) (- i)))
(for z previous x initially 0)
(nconcing (list z x)))
(0 -2 2 -2 -3 3 -3 -4 4))
(deftest for.do-next.previous
(iter (for i from 2 to 4)
(for x do-next (progn (setq x (- i)) (after-each (collect i))))
(for z previous x initially 0)
(appending (list z x)))
(0 -2 2 -2 -3 3 -3 -4 4))
(deftest for-nongenerator.1
(iter (for el in '(a b c d))
(generate i upfrom 1)
(if el (collect (cons el (next i)))))
#.(iter (for el in '(a b c d))
(for i upfrom 1)
(if el (collect (cons el i)))))
(deftest for.previous.in
(iter (for el in '(1 2 3 4))
(for pp-el previous el back 2 initially 0)
(collect pp-el))
(0 0 1 2))
(deftest for.previous.type.1
(iter (for el in '(1 2 3 4))
(declare (type integer el))
(for pp-el previous el back 2)
(collect pp-el))
(0 0 1 2))
(deftest for.previous.index-of-string.1
(iter (as x index-of-string "235")
(as p previous x :initially 9)
(collecting p))
(9 0 1))
(deftest for.previous.in-string.with-index
(iter (as x in-string "235" :with-index y)
(as p previous y :initially 9)
(collecting p))
(9 0 1))
(deftest for.previous.index-of-vector
(iter (as x index-of-vector '#(2 3 4 5))
(as p previous x :initially 9 back 2)
(collecting p))
(9 9 0 1))
(deftest for.previous.in-vector.with-index
(iter (as x in-vector '#(2 3 4 5) with-index y)
(as p previous y :initially 9 back 2)
(collecting p))
(9 9 0 1))
(deftest for.first.1
(iter (for num in '(20 19 18 17 16))
(for i first num then (1+ i))
(collect i))
(20 21 22 23 24))
(deftest for.initially.1
(iter (with (v z))
(for i initially (length v) then (1+ i))
(collect (cons i z))
(while (evenp i)))
((0) (1)))
(deftest sum.1
(iter (for el in '(100 200 300))
(sum el into x)
(declare (fixnum x))
(finally (return x)))
600)
(deftest collect.3
(iter (for i from 1 to 5)
(collect i))
(1 2 3 4 5))
(deftest collect.4
(iter (for i from 1 to 5)
(collect i at beginning))
(5 4 3 2 1))
(deftest collect.5
(iter (for i from 1 to 4)
(collect i at :end))
(1 2 3 4))
(deftest collect.6
(iter (for i from 1 to 3)
(collect i :at start))
(3 2 1))
(deftest collect-by.1
(iter (for i downfrom 10 by 2) (repeat 3)
(collect i))
(10 8 6))
(deftest in-vector.by.1
(iter (for i in-vector '#(0 1 2 3 4) by 2)
(collect i))
(0 2 4))
(deftest index-of-vector.by.1
(iter (for i index-of-vector '#(0 1 2 3 4) by 2)
(collect i))
(0 2 4))
(deftest in-vector.downto.1
(iter (for i in-vector '#(0 1 2 3 4) downto 0)
(collect i))
(4 3 2 1 0))
(deftest index-of-vector.downto.1
(iter (for i index-of-vector #(0 1 2 3 4) downto 0)
(collect i))
(4 3 2 1 0))
(deftest in-vector.downto.2
(iter (for i in-vector '#(0 1 2 3 4) downto 0 by 2)
(collect i))
erroneously got ( 3 1 ) in some past
(deftest index-of-vector.downto.2
(iter (for i index-of-vector #(0 1 2 3 4) downto 0 by 2)
(collect i))
(4 2 0))
(deftest generate.in-vector.downto.1
(iter (generate i in-vector #(0 1 2 3 4) downto 0 by 2)
(collect (next i)))
(4 2 0))
(deftest generate.index-of-vector.downto.1
(iter (generate i index-of-vector '#(0 1 2 3 4) downto 0 by 2)
(collect (next i)))
(4 2 0))
(deftest if-first-time.1
(with-output-to-string (*standard-output*)
(iter (for i from 200 to 203)
(if-first-time (format t "honka"))))
"honka")
(deftest if-first-time.2
(with-output-to-string (*standard-output*)
(iter (for i from 200 to 204)
(if (oddp i) (if-first-time (princ "honka") (princ "tah")))))
"honkatah")
(deftest if-first-time.3
(iter (for i to 5)
(when (oddp i)
(if-first-time nil (collect -1))
(collect i)))
(1 -1 3 -1 5))
(deftest first-time-p.0
(with-output-to-string (*standard-output*)
(iter (for el in '(nil 1 2 nil 3))
(when el
(unless (first-time-p)
(princ ", "))
(princ el))))
"1, 2, 3")
(deftest first-time-p.1
(iter (for i to 5)
(if (first-time-p) (collect -1))
(if (first-time-p) (collect -2))
(when (oddp i)
(if (first-time-p) nil (collect -1))
(collect i)))
(-1 -2 1 -1 3 -1 5))
(deftest first-iteration-p.1
(iter (for i to 5)
(if (first-iteration-p) (collect -1))
(if (first-iteration-p) (collect -2))
(when (oddp i)
(if (first-iteration-p) nil (collect -1))
(collect i)))
(-1 -2 -1 1 -1 3 -1 5))
(deftest collect.multiple.1
(iter (for i from 1 to 10)
(collect i into nums)
(collect (sqrt i) into nums)
(finally (return nums)))
#.(loop for i from 1 to 10
collect i
collect (sqrt i)))
(deftest collect.type.string.1
(locally (declare (optimize safety (debug 2) (speed 0) (space 1)))
(iter (declare (iterate:declare-variables))
(for s in-vector '#(\a |b| |cD|))
(collect (char (symbol-name s) 0) :result-type string)))
"abc")
(deftest collect.type.string.2
(iter (for c in-stream (make-string-input-stream "aBc") :using #'read-char)
(when (digit-char-p c 16)
(collect c :result-type string)))
"aBc")
(deftest collect.type.string.3
(iter (for c in-string "235" downfrom 1)
(collect c into s result-type string)
(finally (return s)))
"32")
(deftest collect.type.vector.1
(locally (declare (optimize safety (debug 2) (speed 0) (space 1)))
(iter (declare (iterate:declare-variables))
(for s in-vector '#(\a |b| |cD|))
(collect (char (symbol-name s) 0) :result-type vector)))
#(#\a #\b #\c))
(deftest collect.type.vector.2
(iter (for c in-vector "235" downfrom 1)
(collect (digit-char-p c) :into v :result-type vector)
(finally (return v)))
#(3 2))
(deftest adjoin.1
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining i at :start :test #'string-equal))
("abc" "ab"))
(deftest adjoin.2
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining i at :start))
("AB" "abc" "aB" "ab"))
(deftest adjoin.3
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining i :at end #:test #'string-equal))
("ab" "abc"))
(deftest adjoin.4
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining i at :end))
("ab" "aB" "abc" "AB"))
(deftest adjoin.5
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining (string-downcase i) at :start :test #'string-equal))
("abc" "ab"))
(deftest adjoin.6
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining (string-upcase i) #:at :end test #'string=))
("AB" "ABC"))
(deftest append.1
(iter (for l on '(1 2 3))
(appending l at :start))
(3 2 3 1 2 3))
(deftest nconc.1
(iter (for l on (list 1 2 3))
(nconcing (copy-list l) at :beginning))
(3 2 3 1 2 3))
(deftest append.2
(iter (for l on '(1 2 3))
(appending l :at #:end))
(1 2 3 2 3 3))
(deftest nconc.2
(iter (for l on (list 1 2 3))
(nconcing (copy-list l) at end))
(1 2 3 2 3 3))
(deftest append.3
(iter (for l on '(1 2 3))
(appending l into x) (finally (return x)))
(1 2 3 2 3 3))
(deftest nconc.3
(iter (for l on (list 1 2 3))
(nconcing (copy-list l) into x) (finally (return x)))
(1 2 3 2 3 3))
(deftest append.4
(iter (for l on '(1 2 3))
(appending l into x))
nil)
(deftest nconc.4
(iter (for l on (list 1 2 3))
(nconcing (copy-list l) into x))
nil)
(deftest append.5
(iter (for l on '(1 2 3))
(appending l :at #:end)
(collect (first l)))
(1 2 3 1 2 3 2 3 3))
(deftest append.6
(iter (for l on '(1 2 3))
(appending l :at :end)
(collect l))
(1 2 3 (1 2 3) 2 3 (2 3) 3 (3)))
(deftest nconc.5
(iter (for l on (list 1 2 3))
(collect (first l))
(nconcing (copy-list l) at end))
(1 1 2 3 2 2 3 3 3))
(deftest union.1
(iter (for l on '(a b c))
(unioning l)
(collect (first l)))
(a b c a b c))
(deftest union.2
(iter (for l on '(a b c))
(collecting (first l))
(unioning l :test #'eql))
(a b c b c))
(deftest union.3
(iter (for l in-vector '#("a" "A" "aB" "ab" "AB"))
(unioning (list l) :test #'string-equal))
("a" "aB"))
(deftest nunion.3
(iter (for l in-vector '#("a" "A" "aB" "ab" "AB"))
(nunioning (list l) :test #'string-equal :at :start))
("aB" "a"))
(deftest value.minimize
(iter (for i from 4 downto -3 by 3)
(collect (minimize (* i i) into foo)))
(16 1 1))
(deftest value.maximize
(iter (for i from 3 to 5)
(sum (maximize (- i 2) into foo)))
6)
(deftest value.finding-maximizing.1
(iter (for i from 3 to 6)
(adjoining (finding (* i i) maximizing #'integer-length
:into foo) :test #'=))
(9 16 36))
(deftest value.finding-maximizing.2
(iter (for i from 3 to 6)
(adjoining (finding (* i i) maximizing (integer-length i)
:into foo) :test #'=))
(9 16))
(deftest walk.counting
(iter (for i from 3 to 5)
(counting (if-first-time nil t)))
2)
(deftest value.counting
(iter (for x in-sequence '#(nil t nil t))
(collect (counting x into foo)))
(0 1 1 2))
(deftest value.adjoining
(iter (for i from 3 to 5)
(sum (length (adjoining i into foo))))
6)
(deftest value.collecting
(iter (for i from 3 to 5)
(collect (copy-list (collecting i :into foo at #:start))
:at end))
((3) (4 3) (5 4 3)))
(deftest value.accumulate
(iter (for c in-string "245")
(collect (accumulate (digit-char-p c) by #'+
:initial-value 0 into s) into l)
(finally (return (cons s l))))
(11 2 6 11))
(deftest value.always
(iter (for i from -3 downto -6 by 2)
(summing (always i) into x)
(finally (return x)))
-8)
(deftest dotted.1
(iter (for l on '(1 2 . 3))
(collect l))
((1 2 . 3) (2 . 3)))
(deftest dotted.2
(iter (for (e) on '(1 2 . 3))
(collect e))
(1 2))
(deftest dotted.3
(values (ignore-errors (iter (for i in '(1 2 . 3)) (count t))))
nil)
(deftest dotted.4
(iter (for i in '(1 1 2 3 . 3)) (thereis (evenp i)))
t)
(deftest dotted.5
(iter (for i in '(1 2 . 3)) (thereis (evenp i)))
t)
(deftest walk.multiple-value-bind
(string-upcase
(iter (for name in-vector (vector 'iterate "FoOBaRzOt" '#:repeat))
(multiple-value-bind (sym access)
(find-symbol (string name) #.*package*)
(declare (type symbol sym))
(collect (if access (char (symbol-name sym) 0) #\-)
result-type string))))
"I-R")
(deftest subblocks.1
(iter fred
(for i from 1 to 10)
(iter barney
(for j from i to 10)
(if (> (* i j) 17)
(return-from fred j))))
9)
(deftest subblocks.wrong.1
(let ((ar #2a((1 2 3)
(4 5 6)
(7 8 9))))
(iter (for i below (array-dimension ar 0))
(iter (for j below (array-dimension ar 1))
(collect (aref ar i j)))))
nil)
(deftest subblocks.2
(let ((ar #2a((1 2 3)
(4 5 6)
(7 8 9))))
(iter outer (for i below (array-dimension ar 0))
(iter (for j below (array-dimension ar 1))
(in outer (collect (aref ar i j))))))
(1 2 3 4 5 6 7 8 9))
(deftest destructuring.1
(iter (for (values (a . b) c)
= (funcall #'(lambda () (values (cons 1 'b) 2))))
(leave (list a b c)))
(1 b 2))
(deftest leave
(iter (for x in '(1 2 3))
(if (evenp x) (leave x))
(finally (error "not found")))
2)
(deftest lambda
(iter (for i index-of-sequence "ab")
(collecting ((lambda(n) (cons 1 n)) i)))
((1 . 0) (1 . 1)))
(deftest type.1
(iter (for el in '(1 2 3 4 5))
(declare (fixnum el))
(counting (oddp el)))
3)
(deftest type.2
(iter (for (the fixnum el) in '(1 2 3 4 5))
(counting (oddp el)))
3)
(deftest type.3
(iter (declare (iterate:declare-variables))
(for el in '(1 2 3 4 5))
(count (oddp el) into my-result)
(declare (integer my-result))
(finally (return my-result)))
3)
(deftest type.4
(iter (declare (iterate:declare-variables))
(for i from 1 to 10)
(collect i))
(1 2 3 4 5 6 7 8 9 10))
(deftest type.5
(iter (declare (iterate:declare-variables))
(repeat 0)
(minimize (the fixnum '1)))
0)
(deftest type.6
(iter (declare (iterate:declare-variables))
(repeat 0)
(maximize 1))
0)
(deftest type.7
(iter (declare (iterate:declare-variables))
(repeat 0)
(minimize (the double-float '1.0d0)))
0.0d0)
(deftest static.error.1
(values
(ignore-errors ; Iterate complains multiple values make no sense here
(macroexpand-1 '(iter (for (values a b) in '(1 2 3)))) t))
nil)
(deftest code-movement.1
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((x 3))
(initially (setq x 4))
(return x))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.2
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((x 3))
(collect i into x))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.3
(iter (with x = 3)
(for el in '(0 1 2 3))
(setq x 1)
(reducing el by #'+ initial-value x))
not 7
)
(deftest code-movement.else
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((x 3))
(else (return x)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.after-each
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(after-each (princ y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.declare.1
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(declare (optimize safety))
(after-each (princ y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.declare.2
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((safety i))
(after-each
(let ()
(declare (optimize safety))
(princ i))))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
nil)
(deftest code-movement.locally.1
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(else (locally (princ y))))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.locally.2
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(else (locally (princ i))))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
nil)
(deftest code-movement.initially
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(initially (princ y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.finally
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(finally (return y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.finally-protected
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(finally-protected (return y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest static.conflict.1
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(collect i) (sum i)))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
2005 : I 'm considering making this shadowing feature unspecified ( and
;;; removing the test), because it takes away implementation freedom of
choosing to reimplement Iterate 's own clauses via macrolet or defmacro .
(deftest macro.shadow.clause
(macrolet ((multiply (expr)
`(reducing ,expr :by #'+ :initial-value 0)))
(iter (for el in '(1 2 3 4))
(multiply el)))
10)
(deftest multiply.1
(iter (for el in '(1 2 3 4))
(multiply el))
24)
(defmacro sum-of-squares (expr)
(let ((temp (gensym)))
`(let ((,temp ,expr))
(sum (* ,temp ,temp)))))
(deftest sum-of-squares.1
(iter (for el in '(1 2 3))
(sum-of-squares el))
14)
(deftest defmacro-clause.1
(defmacro-clause (multiply.clause expr &optional INTO var)
"from testsuite"
`(reducing ,expr by #'* into ,var initial-value 1))
;; A better return value would be the exact list usable with remove-clause
;; The next version shall do that
(multiply.clause expr &optional INTO var))
(deftest multiply.clause
(iter (for el in '(1 2 3 4))
(multiply.clause el))
24)
(deftest remove-clause.1
(iter::remove-clause '(multiply.clause &optional INTO))
t)
(deftest remove-clause.2
(values
(ignore-errors
(iter::remove-clause '(multiply.clause &optional INTO))))
nil)
(iter:defmacro-clause (for var IN-WHOLE-VECTOR.clause v)
"All the elements of a vector (disregards fill-pointer)"
(let ((vect (gensym "VECTOR"))
(index (gensym "INDEX")))
`(progn
(with ,vect = ,v)
(for ,index from 0 below (array-dimension ,vect 0))
(for ,var = (aref ,vect ,index)))))
(deftest in-whole-vector.clause
(iter (for i IN-WHOLE-VECTOR.clause (make-array 3 :fill-pointer 2
:initial-contents '(1 2 3)))
(collect i))
(1 2 3))
(deftest in-vector.fill-pointer
(iter (for i in-vector (make-array 3 :fill-pointer 2
:initial-contents '(1 2 3)))
(collect i))
(1 2))
(iter:defmacro-driver (for var IN-WHOLE-VECTOR v)
"All the elements of a vector (disregards fill-pointer)"
(let ((vect (gensym "VECTOR"))
(end (gensym "END"))
(index (gensym "INDEX"))
(kwd (if iter:generate 'generate 'for)))
`(progn
(with ,vect = ,v)
(with ,end = (array-dimension ,vect 0))
(with ,index = -1)
(,kwd ,var next (progn (incf ,index)
(if (>= ,index ,end) (terminate))
(aref ,vect ,index))))))
(deftest in-whole-vector.driver
(iter (for i IN-WHOLE-VECTOR (make-array '(3) :fill-pointer 2
:initial-contents '(1 2 3)))
(collect i))
(1 2 3))
(deftest in-whole-vector.generate
(iter (generating i IN-WHOLE-VECTOR (make-array '(3) :fill-pointer 2
:initial-contents '(1 2 3)))
(collect (next i)))
(1 2 3))
(deftest defclause-sequence
(progn
(iter:defclause-sequence IN-WHOLE-VECTOR.seq INDEX-OF-WHOLE-VECTOR
:access-fn 'aref
:size-fn '#'(lambda (v) (array-dimension v 0))
:sequence-type 'vector
:element-type t
:element-doc-string
"Elements of a vector, disregarding fill-pointer"
:index-doc-string
"Indices of vector, disregarding fill-pointer")
t)
t)
(deftest in-whole-vector.seq
(iter (for i IN-WHOLE-VECTOR.seq (make-array '(3) :fill-pointer 2
:initial-contents '(1 2 3)))
(collect i))
(1 2 3))
(deftest in-whole-vector.seq.index
(iter (for i INDEX-OF-WHOLE-VECTOR
(make-array 3 :fill-pointer 2 :initial-contents '(1 2 3)))
(for j previous i :initially 9)
(collect (list j i)))
((9 0)(0 1)(1 2)))
(deftest in-whole-vector.seq.with-index
(iter (for e IN-WHOLE-VECTOR.seq
(make-array '(3) :fill-pointer 2 :initial-contents '(a b c))
:with-index i)
(for j previous i :initially 9)
(collect (list j i e)))
((9 0 a)(0 1 b)(1 2 c)))
(deftest in-whole-vector.seq.generate
(iter (generate e IN-WHOLE-VECTOR.seq
(make-array 3 :fill-pointer 2 :initial-contents '(a b c))
:with-index i)
(collect (list (next e) e i)))
((a a 0) (b b 1) (c c 2)))
The original example had three bugs :
;; - ,expr and ,func occured twice in expansion
;; - (finally (leave ,winner)) breaks because FINALLY does not walk
its forms , so does not work inside FINALLY .
;; - Do not use (finally (RETURN ,winner)) either, as that would
;; always return accumulated value, even in case of ... INTO nil.
(deftest defmacro-clause.2
(defmacro-clause (FINDING expr MAXING func &optional INTO var)
"Iterate paper demo example"
(let ((max-val (gensym "MAX-VAL"))
(temp1 (gensym "EL"))
(temp2 (gensym "VAL"))
(winner (or var iterate::*result-var*)))
`(progn
(with ,max-val = nil)
(with ,winner = nil)
(let* ((,temp1 ,expr)
(,temp2 (funcall ,func ,temp1)))
(when (or (null ,max-val) (> ,temp2 ,max-val))
(setq ,winner ,temp1 ,max-val ,temp2)))
#|(finally (return ,winner))|# )))
(FINDING expr MAXING func &optional INTO var))
(deftest maxing.1
(iter (for i in-vector #(1 5 3))
(finding i :maxing #'identity))
5)
(deftest maxing.2
(iter (for i in-vector #(1 5 3))
(finding i maxing #'identity into foo))
nil)
(deftest maxing.3
(iter (for i in-vector #(2 5 4))
(finding i maxing #'identity into foo)
(when (evenp i) (sum i)))
6)
(deftest display.1
(let ((*standard-output* (make-broadcast-stream)))
(display-iterate-clauses) t)
t)
(deftest display.2
(let ((*standard-output* (make-broadcast-stream)))
(display-iterate-clauses 'for) t)
t)
(deftest multiple-value-prog1.1
(iter (for x in '(a b c))
(collect (multiple-value-prog1 7)))
(7 7 7))
(deftest ignore-errors.1
(iter (for x in '(a b c))
(collect (ignore-errors x)))
(a b c))
(deftest ignore-errors.2
(iter (generate x in '(a b c))
(collect (ignore-errors (next x))))
(a b c))
(deftest handler-bind.1
(iter (for i from -1 to 2 by 2)
(handler-bind ((error (lambda(c) c nil)))
(collect i)))
(-1 1))
(deftest destructuring-bind.1
One version of Iterate would enter endless loop in ACL 7 and SBCL
reported by in early 2005
(null (macroexpand '(iter (for index in '((1 2)))
(collect (destructuring-bind (a b) index
(+ a b))))))
nil)
(deftest destructuring-bind.2
(iter (for index in '((1 2)))
(collect (destructuring-bind (a b) index
(+ a b))))
(3))
(deftest symbol-macrolet
(iter (for i from -1 downto -3)
(symbol-macrolet ((x (* i i)))
(declare (optimize debug))
(sum x)))
14)
(defclass polar ()
((rho :initarg :mag)
(theta :initform 0 :accessor angle)))
(deftest with-slots
(iter (with v = (vector (make-instance 'polar :mag 2)))
(for x in-sequence v)
(with-slots (rho) x
(multiplying rho)))
2)
(deftest with-accessors
(iter (with v = (vector (make-instance 'polar :mag 1)))
(for x in-sequence v)
(with-accessors ((alpha angle)) x
(incf alpha 2)
(summing alpha)))
2)
;;; Tests for bugs.
;; when these start failing, I have done something right (-:
;; The walker ignores function bindings,
;; therefore shadowing is not handled correctly.
(deftest bug/walk.1
(macrolet ((over(x) `(collect ,x)))
(iter (for i in '(1 2 3))
(flet ((over(x)(declare (ignore x)) (collect 1)))
(over i)))) ; would yield (1 1 1) if correct
(1 2 3))
(deftest bug/macrolet.2
(progn
(format *error-output*
"~&Note: These tests generate warnings ~
involving MACROLET within Iterate~%")
(values
would yield 1 if correct
(iterate (repeat 10)
(macrolet ((foo () 1))
(multiplying (foo)))))))
nil)
(deftest macrolet.3
(iterate (repeat 2)
(multiplying (macrolet ((foo () 1))
(foo))))
1)
;; Hashtable iterators are specified to be defined as macrolets.
;; But we handle these by special-casing with-hash-table/package-iterator
(deftest nested-hashtable.1
(let ((ht1 (make-hash-table))
(ht2 (make-hash-table)))
(setup-hash-table ht2)
(setf (gethash 'a ht1) ht2)
(= (hash-table-count ht2)
(length
(iter outer (for (k1 v1) in-hashtable ht1)
(iter (for (k2 v2) in-hashtable ht2)
(in outer (collect k2)))))))
t)
(deftest nested.in-hashtable.2
;; Here the inner macrolet code does not affect the outer iteration
(let ((ht1 (make-hash-table))
(ht2 (make-hash-table)))
(setup-hash-table ht2)
(setf (gethash 'a ht1) ht2)
(iter (for (k1 v1) in-hashtable ht1)
(counting
(iter (for (k2 nil) in-hashtable ht2)
(count k2)))))
1)
(deftest nested.in-hashtable.3
(let ((ht1 (make-hash-table))
(ht2 (make-hash-table)))
(setup-hash-table ht2)
(setf (gethash 'a ht1) ht2)
(iter (for (k1 v1) in-hashtable ht1)
(progn
(iter (for (nil v2) in-hashtable v1)
(count v2))
(collect k1))))
(a))
(deftest nested.in-package
(< 6
(print
(iter (for scl in-package '#:iterate :external-only t)
(count ; Iterate exports ~50 symbols
(iter (for si in-package #.*package*)
(thereis (eq si scl))))))
80)
t)
(deftest macrolet.loop-finish
(iter (for l on *an-alist*)
(loop for e in l
when (equal (car e) 'zero)
do (loop-finish)))
nil)
;; Misc tests to make sure that bugs don't reappear
(defmacro problem-because-i-return-nil (&rest args)
(declare (ignore args))
nil)
(deftest tagbody.nil-tags
Allegro ( correctly ) wo n't compile when a tag ( typically NIL ) is used more than once in a tagbody .
(labels ((find-tagbody (form)
(cond
((and (consp form)
(eq (first form)
'tagbody))
form)
((consp form)
(iter (for x in (rest form))
(thereis (find-tagbody x))))
(t nil)))
(all-tagbody-tags (form)
(iter (for tag-or-form in (rest (find-tagbody form)))
(when (symbolp tag-or-form)
(collect tag-or-form)))))
(let* ((form (macroexpand '
(iter (for x in '(1 2 3))
(problem-because-i-return-nil)
(+ x x)
(problem-because-i-return-nil))))
(tags (all-tagbody-tags form)))
(iter (for tag in tags)
;; invoke cl:count, not the Iterate clause:
(always (= 1 (funcall #'count tag tags :from-end nil))))))
t)
(deftest walk.tagbody.1
(iter (tagbody
(problem-because-i-return-nil)
3
(problem-because-i-return-nil)
(leave 2)))
2)
(deftest walk.tagbody.2
(symbol-macrolet ((error-out (error "do not expand me")))
(iter (tagbody error-out
(leave 2))))
2)
eof
| null | https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/addons/iterate/iterate-test.lisp | lisp | Test cases for Iterate.
License:
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
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
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.
Commentary:
Although growing, this testsuite does not yet cover every documented
feature of Iterate.
not -1 as some old version did
not -2 nil as some old version did
are always open, even after close.
tests for my examples:
synonyms (e.g. GENERATING, COLLECTING) didn't work
the C programmer's for (;;) loop
tests from the documentation:
cmucl/sbcl complain about (ignore i)
for.next.1 and for.do-next.1 used to be broken in older versions;
This gave STYLE-WARNINGS for undefined i in old versions.
(values ...) is supported, even though (x y) would do
Iterate complains multiple values make no sense here
removing the test), because it takes away implementation freedom of
A better return value would be the exact list usable with remove-clause
The next version shall do that
- ,expr and ,func occured twice in expansion
- (finally (leave ,winner)) breaks because FINALLY does not walk
- Do not use (finally (RETURN ,winner)) either, as that would
always return accumulated value, even in case of ... INTO nil.
(finally (return ,winner))
Tests for bugs.
when these start failing, I have done something right (-:
The walker ignores function bindings,
therefore shadowing is not handled correctly.
would yield (1 1 1) if correct
Hashtable iterators are specified to be defined as macrolets.
But we handle these by special-casing with-hash-table/package-iterator
Here the inner macrolet code does not affect the outer iteration
Iterate exports ~50 symbols
Misc tests to make sure that bugs don't reappear
invoke cl:count, not the Iterate clause: |
Copyright ( c ) 2003 < >
Copyright ( c ) 2004 - 2007 < >
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
(cl:defpackage #:iterate.test
(:use #:cl #:iterate
#+sbcl #:sb-rt
#-sbcl #:regression-test))
(cl:in-package #:iterate.test)
(rem-all-tests)
(deftest dsetq.1
(let (x y)
(dsetq (x y) (list* 4 5 6))
(list x y))
(4 5))
(deftest dsetq.2
(let (x y)
(dsetq (x nil y) (list* 4 5 6 7))
(list x y))
(4 6))
(deftest dsetq.3
(let ((a '((1 2) 3)) b)
(dsetq (a b) a)
(values a b))
(1 2) 3)
(deftest dsetq.destructuring.1
(let (x y)
(dsetq (x . y) (list* 4 5 6))
(list x y))
(4 (5 . 6)))
(deftest dsetq.destructuring.2
(let (x y z)
(dsetq (x nil (y . z)) (list* 4 5 '(6 7 . 8) 9))
(list x y z))
(4 6 (7 . 8)))
(deftest dsetq.values.1
(let (x y)
(dsetq (values x y) (values 1 'a))
(list x y))
(1 a))
(deftest dsetq.values.2
(let (x y)
(dsetq (values x nil y) (values 1 'a "c"))
(list x y))
(1 "c"))
(deftest dsetq.values.3
(let (x)
(dsetq (values nil (nil . x)) (values 1 '(a b . c)))
x)
(b . c))
(deftest dsetq.values.4
(let (x y z) (dsetq (values nil x (y z))
(values 1 'a '(b c))) (list x y z))
(a b c))
(deftest repeat.1
(iter (repeat 9) (count 1))
9)
(deftest repeat.2
(iter (repeat 2.5s0) (counting t))
3)
(deftest repeat.3
(iter (repeat -1.5f0) (counting t))
0)
(deftest locally.1
(iterate (for i in '(1 2 3)) (repeat 2)
(locally (collect i) (collect 0)))
(1 0 2 0))
(deftest locally.2
(iterate (for i in '(1 2 3)) (repeat 2)
(locally
(declare (optimize safety))
(declare (fixnum i)) (collect i)))
(1 2))
(deftest always.1
(iter (repeat 3) (always 2))
2)
(deftest always.2
(iter (repeat 0) (always 2))
t)
(deftest always.3
(iter (for i in '()) (always i))
t)
(deftest always.never.1
(iterate (repeat 2)
(always 2)
(never nil))
2)
(deftest always.never.2
(iter (for x in '(b (2 . a)))
(if (consp x) (always (car x)) (always x))
(never nil))
2)
(deftest thereis.finally.1
(iter (repeat 3) (thereis nil) (finally (prin1 "hi")))
nil)
(deftest thereis.finally.2
(with-output-to-string (*standard-output*)
(iter (repeat 3) (thereis nil) (finally (princ "hi"))))
"hi")
(deftest thereis.finally.3
(iter (repeat 3) (thereis nil) (finally (return 2)))
2)
(deftest thereis.finally-protected.1
(iter (repeat 3) (thereis 4) (finally-protected (prin1 "hi")))
4)
(deftest thereis.finally-protected.2
(with-output-to-string (*standard-output*)
(iter (repeat 3) (thereis 4) (finally-protected (princ "hi"))))
"hi")
(deftest finding.such-that.2
(iter (for i in '(7 -4 2 -3 4))
(if (plusp i)
(finding i such-that (evenp i))
(finding (- i) such-that (oddp i))))
2)
(deftest finding.such-that.nest.1
(iter (for i in '(1 2 3))
(finding (1+ i)
such-that #'(lambda (x)
(declare (ignore x))
(collect (- i) into m))))
(deftest finding.such-that.nest.2
(iter (for i in '(1 2 3))
(finding (1+ i)
such-that #'(lambda (x)
(finding (- x)
such-that #'(lambda (x) x nil)
into n)
t)
into m)
(finally (return (values m n))))
(deftest finding.thereis.1
(iterate (for x in '(a 7 (-4 -3)))
(thereis (consp x))
(finding x such-that (numberp x)))
7)
(deftest finding.thereis.2
(iterate (for x in '(a (-4 -3) 7))
(thereis (consp x))
(finding x such-that (numberp x)))
t)
(deftest finding.thereis.3
(iterate (for x in '(a #\b))
(thereis (consp x))
(finding x such-that (numberp x)))
nil)
(deftest finding.always.1
(iterate (for x in '(-4 -2 -3))
(always (numberp x))
(finding x such-that (plusp x) on-failure t))
t)
(deftest finding.always.2
(iterate (for x in '(-4 7 -2 -3))
(always (numberp x))
(finding x such-that (plusp x) on-failure t))
7)
(deftest finding.always.3
(iterate (for x in '(-4 c -3))
(always (numberp x))
(finding x such-that (plusp x) on-failure t))
nil)
(defun setup-hash-table (hash)
(dotimes (i (random 100)) (declare (ignorable i))
(setf (gethash (random 10000) hash) (random 10000))
(setf (gethash (gensym) hash) (gensym))))
(deftest in-hashtable.keys
(let* ((hash (make-hash-table))
(all-entries (progn (setup-hash-table hash) '()))
(generated-entries
(iterate (for (key) in-hashtable hash)
(collect key))))
(maphash (lambda (key value) value (push key all-entries)) hash)
(= (length all-entries)
(length generated-entries)
(length (union all-entries generated-entries
:test (hash-table-test hash)))))
t)
(deftest in-hashtable.items.1
(let ((items nil)
(hash (make-hash-table)))
(setup-hash-table hash)
(maphash (lambda (key item) key (push item items)) hash)
(set-difference items
(iterate (for (key item) in-hashtable hash)
(declare (ignore key))
(collect item))))
nil)
(deftest in-hashtable.items.2
(let ((items nil)
(hash (make-hash-table)))
(setup-hash-table hash)
(maphash (lambda (key item) key (push item items)) hash)
(set-difference items
(iterate (for (nil item) in-hashtable hash)
(collect item))))
nil)
(deftest in-hashtable.1
(let* ((hash (make-hash-table))
(all-entries (progn (setup-hash-table hash) '()))
(generated-entries
(iterate (as (key item) in-hashtable hash)
(collect (cons key item)))))
(maphash #'(lambda (key value) (push (cons key value) all-entries)) hash)
(= (length all-entries)
(length generated-entries)
(length (union all-entries generated-entries
:key #'car :test (hash-table-test hash)))))
t)
(deftest in-hashtable.destructuring.1
(let ((hash (make-hash-table :test #'equal))
(entries '(((a . b) . (1 . 2)) (("c" . 3) . (6 . "7")))))
(iterate (for (k . v) in entries)
(setf (gethash k hash) v))
(sort
(iterate (for ((nil . k2) (v1 . v2)) in-hashtable hash)
(always (numberp v1))
(while k2)
(collect (cons v1 k2) into vals)
(finally (return vals)))
#'< :key #'car))
((1 . b) (6 . 3)))
(deftest in-package.internals
(let ((syms nil)
(iter-syms (iterate (for sym in-package *package* :external-only nil)
(collect sym))))
(do-symbols (sym *package* nil)
(push sym syms))
(list
(set-difference syms iter-syms :test #'eq)
(set-difference iter-syms syms)))
(()()))
(deftest in-package.externals.1
(let ((syms nil)
(iter-syms (iterate (for sym in-package '#:cl-user external-only t)
(collect sym))))
(do-external-symbols (sym '#:cl-user nil)
(push sym syms))
(list
(set-difference syms iter-syms :test #'eq)
(set-difference iter-syms syms)))
(()()))
(deftest in-package.externals.2
(let ((sym-count 0))
(do-external-symbols (sym '#:iterate) (declare (ignore sym))
(incf sym-count))
(= sym-count
(iterate (for () in-package '#:iterate external-only t)
(count 1))))
t)
(deftest in-package.generator
(let ((syms nil)
(iter-syms (iterate (generate sym in-package *package*)
(collect (next sym)))))
(do-symbols (sym *package*)
(push sym syms))
(list
(set-difference syms iter-syms :test #'eq)
(set-difference iter-syms syms)))
(()()))
(deftest in-packages.external
(let ((syms nil)
(iter-syms (iterate (as (sym access package) in-packages '(#:cl-user)
:having-access (:external))
(collect sym))))
(do-external-symbols (sym '#:cl-user nil)
(push sym syms))
(list
(set-difference syms iter-syms :test #'eq)
(set-difference iter-syms syms)))
(()()))
(deftest in-packages.generator-access
(let ((iter-syms (iterate (generate (sym access) in-packages (list (find-package "COMMON-LISP")))
(repeat 1)
(next sym)
(collect (list sym access)))))
(equal (multiple-value-list
(find-symbol (symbol-name (caar iter-syms)) "COMMON-LISP"))
(car iter-syms)))
t)
(deftest in-stream.1
(iter (as x in-stream (make-string-input-stream "#xa()2"))
(collect x))
(10 () 2))
(deftest in-stream.previous
(iter (for x in-stream (make-string-input-stream "#xa()2"))
(as p previous x :initially 1)
(collect p))
(1 10 ()))
(deftest in-stream.2
This fails in cmucl , sbcl and gcl , because string - input - streams
(let ((s (make-string-input-stream "(")))
(ignore-errors
(iter (for x in-stream s :using #'read)))
(open-stream-p s))
nil)
(deftest in-stream.3
(iter (for c in-stream (make-string-input-stream "235")
:using #'read-char)
(accumulating (digit-char-p c) by #'+ initial-value 0))
10)
(deftest in-stream.reducing
(iter (with s = (make-string-input-stream "(+ 2)(+ 10)(- 5)(+ 6)"))
(for (op num) in-stream s)
(reducing num :by op :initial-value 0))
13)
(deftest in-stream.accumulating
(iter (with s = (make-string-input-stream "(+ 2)(+ 10)(- 5)(+ 6)"))
(for (op num) in-stream s)
(accumulating num :by op :initial-value 0))
( 6 + ( 5 - ( 10 + ( 2 + 0 ) ) ) )
(deftest in-stream.generate
(iter (with s = (make-string-input-stream "2 + 10 - 5 + 6"))
(with start = (read s))
(generate e in-stream s using #'read)
(as op = (next e))
(for arg = (next e))
(reducing arg by op initial-value start))
13)
(deftest reducing.0
(iter (with expr = '(2 + 10 - 5 + 6))
(with start = (pop expr))
(for (op arg) on expr by #'cddr)
(reducing arg by op initial-value start))
13)
(deftest until.1
(iter (with rest = 235) (with digit = 0)
(multiple-value-setq (rest digit) (floor rest 10))
(sum digit into sum)
(multiplying digit into product)
(until (zerop rest))
(finally (return (values sum product))))
10 30)
(deftest until.2
(iter (for i in-sequence '#(1 2 -3 6))
(until (zerop (sum i into x)))
(multiplying i))
2)
(deftest while.1
(iter (for i in-sequence '#(1 2 -3 6))
(while (< (length (collect i)) 2)))
(1 2))
(deftest else.1
(iter (repeat 0)
(else (return 1)))
1)
(deftest else.2
(iter (for i below -3)
(else (return 2)))
2)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *an-alist* '((a . 2) (b . 3) (zero . 10) (c . 4) (one . 20) (d . 5) (e . 99)))
(defparameter *list-of-lists* (loop for i from 0 to 100
collect (loop for len from 0 to (random 20)
collect len)))
(defun longest-list (list1 list2)
(if (< (length list2) (length list1))
list1
list2)))
(deftest collect.1
(iterate (as (key . item) in *an-alist*)
(collect key into keys)
(collect item into items)
(finally (return (values keys items))))
#.(loop for (key . nil) in *an-alist*
collect key)
#.(loop for (key . item) in *an-alist*
collect item))
(deftest generate.1
(iterate (generate i from 0 to 6)
(for (key . value) in *an-alist*)
(when (>= value 10)
(collect (cons key (next i)))))
#.(loop with counter = 0
for (key . value) in *an-alist*
when (>= value 10)
collect (cons key (prog1 counter (incf counter)))))
(deftest find-longest-list.1
(iterate (for elt in *list-of-lists*)
(finding elt maximizing (length elt)))
#.(reduce #'longest-list *list-of-lists*))
(deftest find-longest-list.2
(iterate (for elt in *list-of-lists*)
(finding elt maximizing (length elt) into (e m))
(finally (return m)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest find-longest-list.3
(iterate (for elt in *list-of-lists*)
(finding elt maximizing #'length))
#.(reduce #'longest-list *list-of-lists*))
(deftest find-longest-list.4
(iterate (for elt in *list-of-lists*)
(finding elt maximizing #'length into (e m))
(finally (return m)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest maximize.1
(iterate (for elt in *list-of-lists*)
(maximizing (length elt) into m)
(finally (return m)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest maximize.2
(iterate (for elt in *list-of-lists*)
(maximize (length elt)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest finding.minimizing.1
(iterate (for elt in *list-of-lists*)
(finding elt minimizing #'length into (e m))
(finally (return m)))
#.(reduce #'min *list-of-lists* :key #'length))
(deftest minimize.1
(iterate (for elt in *list-of-lists*)
(minimizing (length elt) into m)
(finally (return m)))
#.(reduce #'min *list-of-lists* :key #'length))
(deftest minimize.2
(iterate (for elt in *list-of-lists*)
(minimize (length elt)))
#.(reduce #'min *list-of-lists* :key #'length))
(deftest subblocks.maximize.1
(iter outer (for elt in *list-of-lists*)
(iterate running (for e in elt)
(in outer (maximize e)))
(maximizing (length elt)))
#.(reduce #'max *list-of-lists* :key #'length))
(deftest subblocks.minimize.1
(iter outer (for elt in *list-of-lists*)
(minimizing (length elt))
(iterate running (for e in elt)
(in outer (minimize e))))
0)
(deftest maximize.3
(iterate (for i in-vector '#(-3))
(maximize i))
-3)
(deftest minimize.3
(iterate (as i in-vector '#(3))
(minimize i))
3)
(deftest maximize.multiple
(iter (as i from 3 downto -3 by 2) (maximize i)
(for j from -1) (maximizing j))
3)
(deftest minimize.multiple
(iter (as i from -3 to 3 by 2) (minimize i into x)
(for j downfrom -1) (minimizing j into x)
(finally (return x)))
-4)
(deftest accumulate.1
(iter (for c in-string "235")
(declare (type character c))
(accumulate (digit-char-p c) by '* initial-value 1))
30)
(deftest accumulate.2
(iter (for c in-sequence "235")
(accumulating (digit-char-p c) by #'* initial-value 1))
30)
(deftest accumulate.3
(iter (for c in-sequence "235")
(accumulate (digit-char-p c) by 'cons initial-value 1))
(5 3 2 . 1))
(deftest accumulate.4
(iter (for c in-vector "235")
(accumulating (digit-char-p c) by #'cons))
(5 3 2))
(deftest accumulate.5
(iter (repeat 0)
(accumulating 1 by #'cons))
nil)
(deftest accumulate.6
(iter (repeat 0)
(accumulate 1 by #'cons initial-value 2))
2)
(deftest in-string.downto.1
(iter (for c in-string "235" downto 1)
(accumulate (digit-char-p c) by 'cons))
(3 5))
(deftest in-sequence.downto.1
(iter (for c in-sequence "235" downto 1)
(accumulate (digit-char-p c) by #'cons))
(3 5))
(deftest reducing.1
(iter (for c in-string "235")
(reducing (digit-char-p c) by 'list initial-value 1))
(((1 2) 3) 5))
(deftest reducing.2
(iter (as x index-of-string "235")
(reducing x :by #'list initial-value -1))
(((-1 0) 1) 2))
(deftest reducing.3
(iter (repeat 0)
(reducing 1 #:by 'cons initial-value -1))
-1)
(deftest reducing.4
(iter (for i from 3 to 5)
(reducing i by #'- :initial-value '0))
-12)
(deftest reducing.5
(iter (for x in-vector #(3))
(reducing (cons x x) by #'list))
(3 . 3))
(deftest reducing.6
(iter (for x in-vector (vector 3))
(reducing (cons x x) by #'list :initial-value nil))
(nil (3 . 3)))
(deftest generate.destructuring.1
(iter (generate (key . item) in '((a . 1) (b . 2) (c .3)))
(collect (next key))
(collect (next item)))
(a 2 c))
(deftest generating.destructuring.1
(iter (generating (key . item) in '((a . 1) (b . 2) (c .3)))
(collect (next key))
(collect (next item)))
(a 2 c))
(deftest for.generate-t.destructuring.1
(iter (for (key . item) in '((a . 1) (b . 2) (c .3)) :generate t)
(collect (next key))
(collect (next item)))
(a 2 c))
(deftest generate.next.1
(iter (generate c in '(a b c d e f g h i j k l m n o p q))
(for s in '(1 1 2 3 1 0 1 0 2 1))
(collect (next c s)))
(a b d g h h i i k l))
(deftest generate.previous.1
(iter (generate c in '(a b c d e f g h i j k l m n o p q))
(for s in '(1 1 2 3 1 0 1 0 2 1))
(for x = (next c s))
(as y previous x)
(collect (list y x)))
((nil a) (a b) (b d) (d g) (g h) (h h) (h i) (i i) (i k) (k l)))
(deftest generate.next.2
(with-output-to-string (*standard-output*)
(iter (generate i in '(1 2 3 4 5)) (princ (next i 2))))
"24")
(deftest if.1
(iter (generate x in-vector '#(t nil nil t))
(as i from 0)
(if (next x) (collect i)))
(0 3))
(deftest if.2
(iter (generate x in-vector '#(t nil nil t) with-index i)
(if (next x) (collect i)))
(0 3))
(deftest or.1
(iter (generate x in '(a nil nil 1))
(generate y in-vector '#(2 #\c #\d))
(collect (or (next x) (next y))))
(a 2 #\c 1))
(deftest or.2
(iter (generate x in '(a nil nil 1 nil))
(generate y in-sequence '#(2 nil #\c #\d))
(collect (or (next x) (next y) 3)))
(a 2 3 1 #\c))
(deftest setf.1
(iter (generate i from 0 to 3)
(with v = (vector 'a 'b 'c 'd))
(setf (aref v (next i)) i)
(finally (return v)))
#(0 1 2 3))
(deftest setf.2
These setf tests fail in CormanLisp 2.0 because ccl does
not respect setf evaluation order rules .
(iter (generate i from 0 to 3)
(with v = (vector 'a 'b 'c 'd))
(setf (aref v (next i)) (next i))
(finally (return v)))
#(1 b 3 d))
(deftest setf.3
(iter (generate i in '(0 1 2 3 4 5))
(with v = (vector 'a 'b 'c 'd))
(setf (aref v (next i)) (next i 2))
(finally (return v)))
#(2 b c 5))
(deftest setf.4
(iter (generate i from 0 to 3)
(with v = (vector 'a 'b 'c 'd))
(setf (apply #'aref v (list (next i))) (next i))
(finally (return v)))
#(1 b 3 d))
(deftest after-each.1
(iter (after-each (collecting 0))
(generate i in '(a b c))
(adjoining (next i)))
(a 0 b 0 c 0))
(deftest after-each.2
(iter (with i = 0)
(while (< i 4))
(collect i))
(0 1 2 3))
(deftest after-each.3
(iter (with i = 0)
(while (< i 4))
(collect i)
(after-each (incf i)))
(0 1 2 3))
(deftest next-iteration.1
(iter (for i below 10)
(when (oddp i) (next-iteration))
(count t))
5)
(deftest next-iteration.2
(iter (for thing in '(var &optional else &key (test #'eql)))
(collect
(cond ((consp thing) (first thing))
((not (member thing lambda-list-keywords)) thing)
(t (next-iteration)))))
(var else test))
(deftest collect.2
(iter (for i from 1 to 10)
(collect i))
(1 2 3 4 5 6 7 8 9 10))
(deftest for-in.2
(iter (for el in '(1 2 3 4 5 6 f 7 8 9 a 10))
(if (and (numberp el) (oddp el))
(collect el)))
(1 3 5 7 9))
(deftest for.destructuring.1
(iter (for (key . item) in '((a . 10) (b . 20) (c . 30)))
(for i from 0)
(declare (fixnum i))
(collect (cons i key)))
((0 . a) (1 . b) (2 . c)))
(deftest repeat.0
(with-output-to-string (*standard-output*)
(iter (repeat 100)
(print "I will not talk in class.")))
#.(with-output-to-string (*standard-output*)
(dotimes (i 100)
(print "I will not talk in class."))))
they did n't WALK their NEXT args .
(deftest for.next.1
(iterate (initially (setq i 0))
(for i next (if (> i 10) (terminate) (1+ i)))
(finally (return i)))
11)
(deftest for.do-next.1
(iterate (initially (setq i 0))
(as i do-next (if (> i 10) (terminate) (incf i)))
(finally (return i)))
11)
(deftest for.do-next.2
INITIALLY not needed because 0 is inferred from type declaration
(iterate (for i do-next (if (> i 7) (terminate) (incf i)))
(declare (type fixnum i))
(finally (return i)))
8)
(deftest for.do-next.3
(iter (for a from 1 to 3)
(for b = (1+ (* a a)))
(for (values x y) do-next (dsetq (values x y) (floor b a)))
(collect x) (collect y))
(2 0 2 1 3 1))
(deftest for.next.walk
(iter (repeat 2)
(for x next (progn (after-each (collect 1)) 2))
(collect x))
(2 1 2 1))
(deftest for.do-next.walk
(iter (repeat 2)
(for x do-next (progn (after-each (collect 1)) (dsetq x 2)))
(collect x))
(2 1 2 1))
(deftest for.next.previous
(iter (for i from 2 to 4)
(for x next (progn (after-each (collect i)) (- i)))
(for z previous x initially 0)
(nconcing (list z x)))
(0 -2 2 -2 -3 3 -3 -4 4))
(deftest for.do-next.previous
(iter (for i from 2 to 4)
(for x do-next (progn (setq x (- i)) (after-each (collect i))))
(for z previous x initially 0)
(appending (list z x)))
(0 -2 2 -2 -3 3 -3 -4 4))
(deftest for-nongenerator.1
(iter (for el in '(a b c d))
(generate i upfrom 1)
(if el (collect (cons el (next i)))))
#.(iter (for el in '(a b c d))
(for i upfrom 1)
(if el (collect (cons el i)))))
(deftest for.previous.in
(iter (for el in '(1 2 3 4))
(for pp-el previous el back 2 initially 0)
(collect pp-el))
(0 0 1 2))
(deftest for.previous.type.1
(iter (for el in '(1 2 3 4))
(declare (type integer el))
(for pp-el previous el back 2)
(collect pp-el))
(0 0 1 2))
(deftest for.previous.index-of-string.1
(iter (as x index-of-string "235")
(as p previous x :initially 9)
(collecting p))
(9 0 1))
(deftest for.previous.in-string.with-index
(iter (as x in-string "235" :with-index y)
(as p previous y :initially 9)
(collecting p))
(9 0 1))
(deftest for.previous.index-of-vector
(iter (as x index-of-vector '#(2 3 4 5))
(as p previous x :initially 9 back 2)
(collecting p))
(9 9 0 1))
(deftest for.previous.in-vector.with-index
(iter (as x in-vector '#(2 3 4 5) with-index y)
(as p previous y :initially 9 back 2)
(collecting p))
(9 9 0 1))
(deftest for.first.1
(iter (for num in '(20 19 18 17 16))
(for i first num then (1+ i))
(collect i))
(20 21 22 23 24))
(deftest for.initially.1
(iter (with (v z))
(for i initially (length v) then (1+ i))
(collect (cons i z))
(while (evenp i)))
((0) (1)))
(deftest sum.1
(iter (for el in '(100 200 300))
(sum el into x)
(declare (fixnum x))
(finally (return x)))
600)
(deftest collect.3
(iter (for i from 1 to 5)
(collect i))
(1 2 3 4 5))
(deftest collect.4
(iter (for i from 1 to 5)
(collect i at beginning))
(5 4 3 2 1))
(deftest collect.5
(iter (for i from 1 to 4)
(collect i at :end))
(1 2 3 4))
(deftest collect.6
(iter (for i from 1 to 3)
(collect i :at start))
(3 2 1))
(deftest collect-by.1
(iter (for i downfrom 10 by 2) (repeat 3)
(collect i))
(10 8 6))
(deftest in-vector.by.1
(iter (for i in-vector '#(0 1 2 3 4) by 2)
(collect i))
(0 2 4))
(deftest index-of-vector.by.1
(iter (for i index-of-vector '#(0 1 2 3 4) by 2)
(collect i))
(0 2 4))
(deftest in-vector.downto.1
(iter (for i in-vector '#(0 1 2 3 4) downto 0)
(collect i))
(4 3 2 1 0))
(deftest index-of-vector.downto.1
(iter (for i index-of-vector #(0 1 2 3 4) downto 0)
(collect i))
(4 3 2 1 0))
(deftest in-vector.downto.2
(iter (for i in-vector '#(0 1 2 3 4) downto 0 by 2)
(collect i))
erroneously got ( 3 1 ) in some past
(deftest index-of-vector.downto.2
(iter (for i index-of-vector #(0 1 2 3 4) downto 0 by 2)
(collect i))
(4 2 0))
(deftest generate.in-vector.downto.1
(iter (generate i in-vector #(0 1 2 3 4) downto 0 by 2)
(collect (next i)))
(4 2 0))
(deftest generate.index-of-vector.downto.1
(iter (generate i index-of-vector '#(0 1 2 3 4) downto 0 by 2)
(collect (next i)))
(4 2 0))
(deftest if-first-time.1
(with-output-to-string (*standard-output*)
(iter (for i from 200 to 203)
(if-first-time (format t "honka"))))
"honka")
(deftest if-first-time.2
(with-output-to-string (*standard-output*)
(iter (for i from 200 to 204)
(if (oddp i) (if-first-time (princ "honka") (princ "tah")))))
"honkatah")
(deftest if-first-time.3
(iter (for i to 5)
(when (oddp i)
(if-first-time nil (collect -1))
(collect i)))
(1 -1 3 -1 5))
(deftest first-time-p.0
(with-output-to-string (*standard-output*)
(iter (for el in '(nil 1 2 nil 3))
(when el
(unless (first-time-p)
(princ ", "))
(princ el))))
"1, 2, 3")
(deftest first-time-p.1
(iter (for i to 5)
(if (first-time-p) (collect -1))
(if (first-time-p) (collect -2))
(when (oddp i)
(if (first-time-p) nil (collect -1))
(collect i)))
(-1 -2 1 -1 3 -1 5))
(deftest first-iteration-p.1
(iter (for i to 5)
(if (first-iteration-p) (collect -1))
(if (first-iteration-p) (collect -2))
(when (oddp i)
(if (first-iteration-p) nil (collect -1))
(collect i)))
(-1 -2 -1 1 -1 3 -1 5))
(deftest collect.multiple.1
(iter (for i from 1 to 10)
(collect i into nums)
(collect (sqrt i) into nums)
(finally (return nums)))
#.(loop for i from 1 to 10
collect i
collect (sqrt i)))
(deftest collect.type.string.1
(locally (declare (optimize safety (debug 2) (speed 0) (space 1)))
(iter (declare (iterate:declare-variables))
(for s in-vector '#(\a |b| |cD|))
(collect (char (symbol-name s) 0) :result-type string)))
"abc")
(deftest collect.type.string.2
(iter (for c in-stream (make-string-input-stream "aBc") :using #'read-char)
(when (digit-char-p c 16)
(collect c :result-type string)))
"aBc")
(deftest collect.type.string.3
(iter (for c in-string "235" downfrom 1)
(collect c into s result-type string)
(finally (return s)))
"32")
(deftest collect.type.vector.1
(locally (declare (optimize safety (debug 2) (speed 0) (space 1)))
(iter (declare (iterate:declare-variables))
(for s in-vector '#(\a |b| |cD|))
(collect (char (symbol-name s) 0) :result-type vector)))
#(#\a #\b #\c))
(deftest collect.type.vector.2
(iter (for c in-vector "235" downfrom 1)
(collect (digit-char-p c) :into v :result-type vector)
(finally (return v)))
#(3 2))
(deftest adjoin.1
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining i at :start :test #'string-equal))
("abc" "ab"))
(deftest adjoin.2
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining i at :start))
("AB" "abc" "aB" "ab"))
(deftest adjoin.3
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining i :at end #:test #'string-equal))
("ab" "abc"))
(deftest adjoin.4
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining i at :end))
("ab" "aB" "abc" "AB"))
(deftest adjoin.5
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining (string-downcase i) at :start :test #'string-equal))
("abc" "ab"))
(deftest adjoin.6
(iter (for i in '("ab" "aB" "abc" "AB"))
(adjoining (string-upcase i) #:at :end test #'string=))
("AB" "ABC"))
(deftest append.1
(iter (for l on '(1 2 3))
(appending l at :start))
(3 2 3 1 2 3))
(deftest nconc.1
(iter (for l on (list 1 2 3))
(nconcing (copy-list l) at :beginning))
(3 2 3 1 2 3))
(deftest append.2
(iter (for l on '(1 2 3))
(appending l :at #:end))
(1 2 3 2 3 3))
(deftest nconc.2
(iter (for l on (list 1 2 3))
(nconcing (copy-list l) at end))
(1 2 3 2 3 3))
(deftest append.3
(iter (for l on '(1 2 3))
(appending l into x) (finally (return x)))
(1 2 3 2 3 3))
(deftest nconc.3
(iter (for l on (list 1 2 3))
(nconcing (copy-list l) into x) (finally (return x)))
(1 2 3 2 3 3))
(deftest append.4
(iter (for l on '(1 2 3))
(appending l into x))
nil)
(deftest nconc.4
(iter (for l on (list 1 2 3))
(nconcing (copy-list l) into x))
nil)
(deftest append.5
(iter (for l on '(1 2 3))
(appending l :at #:end)
(collect (first l)))
(1 2 3 1 2 3 2 3 3))
(deftest append.6
(iter (for l on '(1 2 3))
(appending l :at :end)
(collect l))
(1 2 3 (1 2 3) 2 3 (2 3) 3 (3)))
(deftest nconc.5
(iter (for l on (list 1 2 3))
(collect (first l))
(nconcing (copy-list l) at end))
(1 1 2 3 2 2 3 3 3))
(deftest union.1
(iter (for l on '(a b c))
(unioning l)
(collect (first l)))
(a b c a b c))
(deftest union.2
(iter (for l on '(a b c))
(collecting (first l))
(unioning l :test #'eql))
(a b c b c))
(deftest union.3
(iter (for l in-vector '#("a" "A" "aB" "ab" "AB"))
(unioning (list l) :test #'string-equal))
("a" "aB"))
(deftest nunion.3
(iter (for l in-vector '#("a" "A" "aB" "ab" "AB"))
(nunioning (list l) :test #'string-equal :at :start))
("aB" "a"))
(deftest value.minimize
(iter (for i from 4 downto -3 by 3)
(collect (minimize (* i i) into foo)))
(16 1 1))
(deftest value.maximize
(iter (for i from 3 to 5)
(sum (maximize (- i 2) into foo)))
6)
(deftest value.finding-maximizing.1
(iter (for i from 3 to 6)
(adjoining (finding (* i i) maximizing #'integer-length
:into foo) :test #'=))
(9 16 36))
(deftest value.finding-maximizing.2
(iter (for i from 3 to 6)
(adjoining (finding (* i i) maximizing (integer-length i)
:into foo) :test #'=))
(9 16))
(deftest walk.counting
(iter (for i from 3 to 5)
(counting (if-first-time nil t)))
2)
(deftest value.counting
(iter (for x in-sequence '#(nil t nil t))
(collect (counting x into foo)))
(0 1 1 2))
(deftest value.adjoining
(iter (for i from 3 to 5)
(sum (length (adjoining i into foo))))
6)
(deftest value.collecting
(iter (for i from 3 to 5)
(collect (copy-list (collecting i :into foo at #:start))
:at end))
((3) (4 3) (5 4 3)))
(deftest value.accumulate
(iter (for c in-string "245")
(collect (accumulate (digit-char-p c) by #'+
:initial-value 0 into s) into l)
(finally (return (cons s l))))
(11 2 6 11))
(deftest value.always
(iter (for i from -3 downto -6 by 2)
(summing (always i) into x)
(finally (return x)))
-8)
(deftest dotted.1
(iter (for l on '(1 2 . 3))
(collect l))
((1 2 . 3) (2 . 3)))
(deftest dotted.2
(iter (for (e) on '(1 2 . 3))
(collect e))
(1 2))
(deftest dotted.3
(values (ignore-errors (iter (for i in '(1 2 . 3)) (count t))))
nil)
(deftest dotted.4
(iter (for i in '(1 1 2 3 . 3)) (thereis (evenp i)))
t)
(deftest dotted.5
(iter (for i in '(1 2 . 3)) (thereis (evenp i)))
t)
(deftest walk.multiple-value-bind
(string-upcase
(iter (for name in-vector (vector 'iterate "FoOBaRzOt" '#:repeat))
(multiple-value-bind (sym access)
(find-symbol (string name) #.*package*)
(declare (type symbol sym))
(collect (if access (char (symbol-name sym) 0) #\-)
result-type string))))
"I-R")
(deftest subblocks.1
(iter fred
(for i from 1 to 10)
(iter barney
(for j from i to 10)
(if (> (* i j) 17)
(return-from fred j))))
9)
(deftest subblocks.wrong.1
(let ((ar #2a((1 2 3)
(4 5 6)
(7 8 9))))
(iter (for i below (array-dimension ar 0))
(iter (for j below (array-dimension ar 1))
(collect (aref ar i j)))))
nil)
(deftest subblocks.2
(let ((ar #2a((1 2 3)
(4 5 6)
(7 8 9))))
(iter outer (for i below (array-dimension ar 0))
(iter (for j below (array-dimension ar 1))
(in outer (collect (aref ar i j))))))
(1 2 3 4 5 6 7 8 9))
(deftest destructuring.1
(iter (for (values (a . b) c)
= (funcall #'(lambda () (values (cons 1 'b) 2))))
(leave (list a b c)))
(1 b 2))
(deftest leave
(iter (for x in '(1 2 3))
(if (evenp x) (leave x))
(finally (error "not found")))
2)
(deftest lambda
(iter (for i index-of-sequence "ab")
(collecting ((lambda(n) (cons 1 n)) i)))
((1 . 0) (1 . 1)))
(deftest type.1
(iter (for el in '(1 2 3 4 5))
(declare (fixnum el))
(counting (oddp el)))
3)
(deftest type.2
(iter (for (the fixnum el) in '(1 2 3 4 5))
(counting (oddp el)))
3)
(deftest type.3
(iter (declare (iterate:declare-variables))
(for el in '(1 2 3 4 5))
(count (oddp el) into my-result)
(declare (integer my-result))
(finally (return my-result)))
3)
(deftest type.4
(iter (declare (iterate:declare-variables))
(for i from 1 to 10)
(collect i))
(1 2 3 4 5 6 7 8 9 10))
(deftest type.5
(iter (declare (iterate:declare-variables))
(repeat 0)
(minimize (the fixnum '1)))
0)
(deftest type.6
(iter (declare (iterate:declare-variables))
(repeat 0)
(maximize 1))
0)
(deftest type.7
(iter (declare (iterate:declare-variables))
(repeat 0)
(minimize (the double-float '1.0d0)))
0.0d0)
(deftest static.error.1
(values
(macroexpand-1 '(iter (for (values a b) in '(1 2 3)))) t))
nil)
(deftest code-movement.1
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((x 3))
(initially (setq x 4))
(return x))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.2
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((x 3))
(collect i into x))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.3
(iter (with x = 3)
(for el in '(0 1 2 3))
(setq x 1)
(reducing el by #'+ initial-value x))
not 7
)
(deftest code-movement.else
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((x 3))
(else (return x)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.after-each
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(after-each (princ y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.declare.1
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(declare (optimize safety))
(after-each (princ y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.declare.2
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((safety i))
(after-each
(let ()
(declare (optimize safety))
(princ i))))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
nil)
(deftest code-movement.locally.1
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(else (locally (princ y))))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.locally.2
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(else (locally (princ i))))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
nil)
(deftest code-movement.initially
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(initially (princ y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.finally
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(finally (return y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest code-movement.finally-protected
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(let ((y i))
(finally-protected (return y)))))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
(deftest static.conflict.1
(handler-case (macroexpand '
(iter (for i from 1 to 10)
(collect i) (sum i)))
(error () t)
(:no-error (f x) (declare (ignore f x)) nil))
t)
2005 : I 'm considering making this shadowing feature unspecified ( and
choosing to reimplement Iterate 's own clauses via macrolet or defmacro .
(deftest macro.shadow.clause
(macrolet ((multiply (expr)
`(reducing ,expr :by #'+ :initial-value 0)))
(iter (for el in '(1 2 3 4))
(multiply el)))
10)
(deftest multiply.1
(iter (for el in '(1 2 3 4))
(multiply el))
24)
(defmacro sum-of-squares (expr)
(let ((temp (gensym)))
`(let ((,temp ,expr))
(sum (* ,temp ,temp)))))
(deftest sum-of-squares.1
(iter (for el in '(1 2 3))
(sum-of-squares el))
14)
(deftest defmacro-clause.1
(defmacro-clause (multiply.clause expr &optional INTO var)
"from testsuite"
`(reducing ,expr by #'* into ,var initial-value 1))
(multiply.clause expr &optional INTO var))
(deftest multiply.clause
(iter (for el in '(1 2 3 4))
(multiply.clause el))
24)
(deftest remove-clause.1
(iter::remove-clause '(multiply.clause &optional INTO))
t)
(deftest remove-clause.2
(values
(ignore-errors
(iter::remove-clause '(multiply.clause &optional INTO))))
nil)
(iter:defmacro-clause (for var IN-WHOLE-VECTOR.clause v)
"All the elements of a vector (disregards fill-pointer)"
(let ((vect (gensym "VECTOR"))
(index (gensym "INDEX")))
`(progn
(with ,vect = ,v)
(for ,index from 0 below (array-dimension ,vect 0))
(for ,var = (aref ,vect ,index)))))
(deftest in-whole-vector.clause
(iter (for i IN-WHOLE-VECTOR.clause (make-array 3 :fill-pointer 2
:initial-contents '(1 2 3)))
(collect i))
(1 2 3))
(deftest in-vector.fill-pointer
(iter (for i in-vector (make-array 3 :fill-pointer 2
:initial-contents '(1 2 3)))
(collect i))
(1 2))
(iter:defmacro-driver (for var IN-WHOLE-VECTOR v)
"All the elements of a vector (disregards fill-pointer)"
(let ((vect (gensym "VECTOR"))
(end (gensym "END"))
(index (gensym "INDEX"))
(kwd (if iter:generate 'generate 'for)))
`(progn
(with ,vect = ,v)
(with ,end = (array-dimension ,vect 0))
(with ,index = -1)
(,kwd ,var next (progn (incf ,index)
(if (>= ,index ,end) (terminate))
(aref ,vect ,index))))))
(deftest in-whole-vector.driver
(iter (for i IN-WHOLE-VECTOR (make-array '(3) :fill-pointer 2
:initial-contents '(1 2 3)))
(collect i))
(1 2 3))
(deftest in-whole-vector.generate
(iter (generating i IN-WHOLE-VECTOR (make-array '(3) :fill-pointer 2
:initial-contents '(1 2 3)))
(collect (next i)))
(1 2 3))
(deftest defclause-sequence
(progn
(iter:defclause-sequence IN-WHOLE-VECTOR.seq INDEX-OF-WHOLE-VECTOR
:access-fn 'aref
:size-fn '#'(lambda (v) (array-dimension v 0))
:sequence-type 'vector
:element-type t
:element-doc-string
"Elements of a vector, disregarding fill-pointer"
:index-doc-string
"Indices of vector, disregarding fill-pointer")
t)
t)
(deftest in-whole-vector.seq
(iter (for i IN-WHOLE-VECTOR.seq (make-array '(3) :fill-pointer 2
:initial-contents '(1 2 3)))
(collect i))
(1 2 3))
(deftest in-whole-vector.seq.index
(iter (for i INDEX-OF-WHOLE-VECTOR
(make-array 3 :fill-pointer 2 :initial-contents '(1 2 3)))
(for j previous i :initially 9)
(collect (list j i)))
((9 0)(0 1)(1 2)))
(deftest in-whole-vector.seq.with-index
(iter (for e IN-WHOLE-VECTOR.seq
(make-array '(3) :fill-pointer 2 :initial-contents '(a b c))
:with-index i)
(for j previous i :initially 9)
(collect (list j i e)))
((9 0 a)(0 1 b)(1 2 c)))
(deftest in-whole-vector.seq.generate
(iter (generate e IN-WHOLE-VECTOR.seq
(make-array 3 :fill-pointer 2 :initial-contents '(a b c))
:with-index i)
(collect (list (next e) e i)))
((a a 0) (b b 1) (c c 2)))
The original example had three bugs :
its forms , so does not work inside FINALLY .
(deftest defmacro-clause.2
(defmacro-clause (FINDING expr MAXING func &optional INTO var)
"Iterate paper demo example"
(let ((max-val (gensym "MAX-VAL"))
(temp1 (gensym "EL"))
(temp2 (gensym "VAL"))
(winner (or var iterate::*result-var*)))
`(progn
(with ,max-val = nil)
(with ,winner = nil)
(let* ((,temp1 ,expr)
(,temp2 (funcall ,func ,temp1)))
(when (or (null ,max-val) (> ,temp2 ,max-val))
(setq ,winner ,temp1 ,max-val ,temp2)))
(FINDING expr MAXING func &optional INTO var))
(deftest maxing.1
(iter (for i in-vector #(1 5 3))
(finding i :maxing #'identity))
5)
(deftest maxing.2
(iter (for i in-vector #(1 5 3))
(finding i maxing #'identity into foo))
nil)
(deftest maxing.3
(iter (for i in-vector #(2 5 4))
(finding i maxing #'identity into foo)
(when (evenp i) (sum i)))
6)
(deftest display.1
(let ((*standard-output* (make-broadcast-stream)))
(display-iterate-clauses) t)
t)
(deftest display.2
(let ((*standard-output* (make-broadcast-stream)))
(display-iterate-clauses 'for) t)
t)
(deftest multiple-value-prog1.1
(iter (for x in '(a b c))
(collect (multiple-value-prog1 7)))
(7 7 7))
(deftest ignore-errors.1
(iter (for x in '(a b c))
(collect (ignore-errors x)))
(a b c))
(deftest ignore-errors.2
(iter (generate x in '(a b c))
(collect (ignore-errors (next x))))
(a b c))
(deftest handler-bind.1
(iter (for i from -1 to 2 by 2)
(handler-bind ((error (lambda(c) c nil)))
(collect i)))
(-1 1))
(deftest destructuring-bind.1
One version of Iterate would enter endless loop in ACL 7 and SBCL
reported by in early 2005
(null (macroexpand '(iter (for index in '((1 2)))
(collect (destructuring-bind (a b) index
(+ a b))))))
nil)
(deftest destructuring-bind.2
(iter (for index in '((1 2)))
(collect (destructuring-bind (a b) index
(+ a b))))
(3))
(deftest symbol-macrolet
(iter (for i from -1 downto -3)
(symbol-macrolet ((x (* i i)))
(declare (optimize debug))
(sum x)))
14)
(defclass polar ()
((rho :initarg :mag)
(theta :initform 0 :accessor angle)))
(deftest with-slots
(iter (with v = (vector (make-instance 'polar :mag 2)))
(for x in-sequence v)
(with-slots (rho) x
(multiplying rho)))
2)
(deftest with-accessors
(iter (with v = (vector (make-instance 'polar :mag 1)))
(for x in-sequence v)
(with-accessors ((alpha angle)) x
(incf alpha 2)
(summing alpha)))
2)
(deftest bug/walk.1
(macrolet ((over(x) `(collect ,x)))
(iter (for i in '(1 2 3))
(flet ((over(x)(declare (ignore x)) (collect 1)))
(1 2 3))
(deftest bug/macrolet.2
(progn
(format *error-output*
"~&Note: These tests generate warnings ~
involving MACROLET within Iterate~%")
(values
would yield 1 if correct
(iterate (repeat 10)
(macrolet ((foo () 1))
(multiplying (foo)))))))
nil)
(deftest macrolet.3
(iterate (repeat 2)
(multiplying (macrolet ((foo () 1))
(foo))))
1)
(deftest nested-hashtable.1
(let ((ht1 (make-hash-table))
(ht2 (make-hash-table)))
(setup-hash-table ht2)
(setf (gethash 'a ht1) ht2)
(= (hash-table-count ht2)
(length
(iter outer (for (k1 v1) in-hashtable ht1)
(iter (for (k2 v2) in-hashtable ht2)
(in outer (collect k2)))))))
t)
(deftest nested.in-hashtable.2
(let ((ht1 (make-hash-table))
(ht2 (make-hash-table)))
(setup-hash-table ht2)
(setf (gethash 'a ht1) ht2)
(iter (for (k1 v1) in-hashtable ht1)
(counting
(iter (for (k2 nil) in-hashtable ht2)
(count k2)))))
1)
(deftest nested.in-hashtable.3
(let ((ht1 (make-hash-table))
(ht2 (make-hash-table)))
(setup-hash-table ht2)
(setf (gethash 'a ht1) ht2)
(iter (for (k1 v1) in-hashtable ht1)
(progn
(iter (for (nil v2) in-hashtable v1)
(count v2))
(collect k1))))
(a))
(deftest nested.in-package
(< 6
(print
(iter (for scl in-package '#:iterate :external-only t)
(iter (for si in-package #.*package*)
(thereis (eq si scl))))))
80)
t)
(deftest macrolet.loop-finish
(iter (for l on *an-alist*)
(loop for e in l
when (equal (car e) 'zero)
do (loop-finish)))
nil)
(defmacro problem-because-i-return-nil (&rest args)
(declare (ignore args))
nil)
(deftest tagbody.nil-tags
Allegro ( correctly ) wo n't compile when a tag ( typically NIL ) is used more than once in a tagbody .
(labels ((find-tagbody (form)
(cond
((and (consp form)
(eq (first form)
'tagbody))
form)
((consp form)
(iter (for x in (rest form))
(thereis (find-tagbody x))))
(t nil)))
(all-tagbody-tags (form)
(iter (for tag-or-form in (rest (find-tagbody form)))
(when (symbolp tag-or-form)
(collect tag-or-form)))))
(let* ((form (macroexpand '
(iter (for x in '(1 2 3))
(problem-because-i-return-nil)
(+ x x)
(problem-because-i-return-nil))))
(tags (all-tagbody-tags form)))
(iter (for tag in tags)
(always (= 1 (funcall #'count tag tags :from-end nil))))))
t)
(deftest walk.tagbody.1
(iter (tagbody
(problem-because-i-return-nil)
3
(problem-because-i-return-nil)
(leave 2)))
2)
(deftest walk.tagbody.2
(symbol-macrolet ((error-out (error "do not expand me")))
(iter (tagbody error-out
(leave 2))))
2)
eof
|
b0e8be2d025b3a69ff36db3694085bc9a7dfd7bcc93c32aaf2a6ad56ad68c2a1 | kawasima/back-channeling | routing.cljs | (ns back-channeling.routing
(:require [om.core :as om :include-macros true]
[clojure.browser.net :as net]
[secretary.core :as sec :include-macros true]
[goog.events :as events]
[goog.History]
[goog.history.EventType :as HistoryEventType]
[goog.net.EventType :as EventType]
[back-channeling.api :as api])
(:use [cljs.reader :only [read-string]])
(:import [goog.History]))
(defn fetch-private-tags [app]
(let [user-name (.. js/document (querySelector "meta[property='bc:user:name']") (getAttribute "content"))]
(api/request (str "/api/user/" user-name "/tags")
{:handler (fn [response]
(om/transact! app #(assoc % :private-tags response)))})))
(defn fetch-boards [app]
(api/request "/api/boards"
{:handler (fn [response]
(let [boards (->> response
(map #(update-in % [:board/threads] (fn [threads]
(when threads
(->> threads
(map (fn [t] {(:db/id t) t}))
(reduce merge {}))))))
(reduce #(assoc %1 (:board/name %2) {:value %2}) {}))]
(om/transact! app #(assoc % :boards boards :page :boards))))}))
(defn fetch-board [board-name app]
(api/request (str "/api/board/" board-name)
{:handler (fn [response]
(let [new-board (update-in response [:board/threads]
(fn [threads]
(->> threads
(map (fn [t] {(:db/id t) t}))
(reduce merge {}))))]
(if (get-in @app [:boards board-name])
(om/transact! app
(fn [app]
(-> app
(update-in [:boards board-name :value :board/threads]
#(merge-with merge % (:board/threads new-board)))
(assoc :page :board :target-board-name board-name)
(assoc-in [:boards board-name :target :thread] 0)
(assoc-in [:boards board-name :target :comment] nil))))
(om/transact! app
#(-> %
(assoc-in [:boards board-name :value] new-board)
(assoc :page :board :target-board-name board-name)
(assoc-in [:boards board-name :target :thread] 0)
(assoc-in [:boards board-name :target :comment] nil))))))}))
(defn fetch-thread [thread-id comment-no board-name app]
(when (> thread-id 0)
(let [from (inc (count (get-in @app [:boards board-name :value :board/threads thread-id :thread/comments] [])))]
(api/request (str "/api/thread/" thread-id "/comments/" from "-")
{:handler (fn [response]
(om/transact! app
#(-> %
(update-in [:boards board-name :value :board/threads thread-id :thread/comments]
(fn [comments new-comments]
(vec (concat comments new-comments))) response)
(assoc :page :board)
(assoc-in [:boards board-name :target :thread] thread-id)
(assoc-in [:boards board-name :target :comment] comment-no))))}))))
(defn fetch-articles [app]
(api/request (str "/api/articles")
{:handler (fn [response]
(om/transact! app
#(assoc % :page :article :articles response)))}))
(defn fetch-article [id app]
(api/request (str "/api/article/" id)
{:handler (fn [response]
(om/transact! app
#(assoc %
:page :article
:target-thread (js/parseInt (get-in response [:article/thread :db/id]))
:article response)))}))
(defn- setup-routing [app]
(sec/set-config! :prefix "#")
(sec/defroute "/" []
(fetch-boards app)
(fetch-private-tags app))
(sec/defroute "/board/:board-name" [board-name]
(fetch-board board-name app))
(sec/defroute "/board/:board-name/:thread-id" [board-name thread-id]
(fetch-thread (js/parseInt thread-id) nil board-name app))
(sec/defroute "/board/:board-name/:thread-id/:comment-no" [board-name thread-id comment-no]
(fetch-thread (js/parseInt thread-id) comment-no board-name app))
(sec/defroute "/articles/new" [query-params]
(om/transact! app #(assoc %
:page :article
:target-thread (js/parseInt (:thread-id query-params))
:article {:article/name nil :article/blocks []})))
(sec/defroute "/articles" []
(fetch-articles app))
(sec/defroute #"/article/(\d+)" [id]
(fetch-article id app)))
(defn- setup-history [owner]
(let [history (goog.History.)
navigation HistoryEventType/NAVIGATE]
(events/listen history
navigation
#(-> % .-token sec/dispatch!))
(.setEnabled history true)))
(defn init [app-state owner]
(setup-routing app-state)
(setup-history owner))
| null | https://raw.githubusercontent.com/kawasima/back-channeling/05d06278cedc35e4e7866384c2903d3c903a19fc/src/cljs/back_channeling/routing.cljs | clojure | (ns back-channeling.routing
(:require [om.core :as om :include-macros true]
[clojure.browser.net :as net]
[secretary.core :as sec :include-macros true]
[goog.events :as events]
[goog.History]
[goog.history.EventType :as HistoryEventType]
[goog.net.EventType :as EventType]
[back-channeling.api :as api])
(:use [cljs.reader :only [read-string]])
(:import [goog.History]))
(defn fetch-private-tags [app]
(let [user-name (.. js/document (querySelector "meta[property='bc:user:name']") (getAttribute "content"))]
(api/request (str "/api/user/" user-name "/tags")
{:handler (fn [response]
(om/transact! app #(assoc % :private-tags response)))})))
(defn fetch-boards [app]
(api/request "/api/boards"
{:handler (fn [response]
(let [boards (->> response
(map #(update-in % [:board/threads] (fn [threads]
(when threads
(->> threads
(map (fn [t] {(:db/id t) t}))
(reduce merge {}))))))
(reduce #(assoc %1 (:board/name %2) {:value %2}) {}))]
(om/transact! app #(assoc % :boards boards :page :boards))))}))
(defn fetch-board [board-name app]
(api/request (str "/api/board/" board-name)
{:handler (fn [response]
(let [new-board (update-in response [:board/threads]
(fn [threads]
(->> threads
(map (fn [t] {(:db/id t) t}))
(reduce merge {}))))]
(if (get-in @app [:boards board-name])
(om/transact! app
(fn [app]
(-> app
(update-in [:boards board-name :value :board/threads]
#(merge-with merge % (:board/threads new-board)))
(assoc :page :board :target-board-name board-name)
(assoc-in [:boards board-name :target :thread] 0)
(assoc-in [:boards board-name :target :comment] nil))))
(om/transact! app
#(-> %
(assoc-in [:boards board-name :value] new-board)
(assoc :page :board :target-board-name board-name)
(assoc-in [:boards board-name :target :thread] 0)
(assoc-in [:boards board-name :target :comment] nil))))))}))
(defn fetch-thread [thread-id comment-no board-name app]
(when (> thread-id 0)
(let [from (inc (count (get-in @app [:boards board-name :value :board/threads thread-id :thread/comments] [])))]
(api/request (str "/api/thread/" thread-id "/comments/" from "-")
{:handler (fn [response]
(om/transact! app
#(-> %
(update-in [:boards board-name :value :board/threads thread-id :thread/comments]
(fn [comments new-comments]
(vec (concat comments new-comments))) response)
(assoc :page :board)
(assoc-in [:boards board-name :target :thread] thread-id)
(assoc-in [:boards board-name :target :comment] comment-no))))}))))
(defn fetch-articles [app]
(api/request (str "/api/articles")
{:handler (fn [response]
(om/transact! app
#(assoc % :page :article :articles response)))}))
(defn fetch-article [id app]
(api/request (str "/api/article/" id)
{:handler (fn [response]
(om/transact! app
#(assoc %
:page :article
:target-thread (js/parseInt (get-in response [:article/thread :db/id]))
:article response)))}))
(defn- setup-routing [app]
(sec/set-config! :prefix "#")
(sec/defroute "/" []
(fetch-boards app)
(fetch-private-tags app))
(sec/defroute "/board/:board-name" [board-name]
(fetch-board board-name app))
(sec/defroute "/board/:board-name/:thread-id" [board-name thread-id]
(fetch-thread (js/parseInt thread-id) nil board-name app))
(sec/defroute "/board/:board-name/:thread-id/:comment-no" [board-name thread-id comment-no]
(fetch-thread (js/parseInt thread-id) comment-no board-name app))
(sec/defroute "/articles/new" [query-params]
(om/transact! app #(assoc %
:page :article
:target-thread (js/parseInt (:thread-id query-params))
:article {:article/name nil :article/blocks []})))
(sec/defroute "/articles" []
(fetch-articles app))
(sec/defroute #"/article/(\d+)" [id]
(fetch-article id app)))
(defn- setup-history [owner]
(let [history (goog.History.)
navigation HistoryEventType/NAVIGATE]
(events/listen history
navigation
#(-> % .-token sec/dispatch!))
(.setEnabled history true)))
(defn init [app-state owner]
(setup-routing app-state)
(setup-history owner))
| |
f3478a033e87fb4c1ef5c24c9fa7a4a5b458ecd342eb25a2a8f47b3ab343e169 | Shimuuar/histogram-fill | Histogram.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
-- |
-- Module : Data.Histogram
Copyright : Copyright ( c ) 2009 , < >
-- License : BSD3
Maintainer : < >
-- Stability : experimental
--
-- Immutable histograms. This module exports the same API as
-- 'Data.Histogram.Generic' but specialized to unboxed vectors. Please refer
-- to the aforementioned module for detailed documentation.
module Data.Histogram (
-- * Immutable histograms
Histogram
, module Data.Histogram.Bin
-- ** Constructors
, histogram
, histogramUO
-- ** Conversion to other data types
, asList
, asVector
-- * Serialization to strings
-- $serialization
, readHistogram
, readFileHistogram
-- * Accessors
, bins
, histData
, underflows
, overflows
, outOfRange
-- ** Indexing
, HistIndex(..)
, histIndex
, at
, atV
, atI
-- * Transformations
, map
, bmap
, mapData
, zip
, zipSafe
-- ** Type conversion
, convertBinning
-- * Folding
, foldl
, bfoldl
-- ** Specialized folds
, sum
, minimum
, minimumBy
, maximum
, maximumBy
, minIndex
, minIndexBy
, maxIndex
, maxIndexBy
, minBin
, minBinBy
, maxBin
, maxBinBy
-- * Slicing & rebinning
, slice
, rebin
, rebinFold
-- * 2D histograms
-- ** Slicing
, sliceAlongX
, sliceAlongY
, listSlicesAlongX
, listSlicesAlongY
-- ** Reducing along axis
, reduceX
, breduceX
, reduceY
, breduceY
-- * Lift histogram transform to 2D
, liftX
, liftY
) where
import qualified Data.Vector.Unboxed as U
import Data.Vector.Unboxed (Unbox,Vector)
import qualified Data.Histogram.Generic as H
import Data.Histogram.Generic (HistIndex(..),histIndex)
import Data.Histogram.Bin
import Prelude hiding (map, zip, foldl, sum, maximum, minimum)
-- | Immutable histogram. A histogram consists of a binning algorithm,
-- an optional number of under and overflows, and data.
type Histogram bin a = H.Histogram U.Vector bin a
histogram :: (Unbox a, Bin bin) => bin -> Vector a -> Histogram bin a
histogram = H.histogram
histogramUO :: (Unbox a, Bin bin) => bin -> Maybe (a,a) -> Vector a -> Histogram bin a
histogramUO = H.histogramUO
----------------------------------------------------------------
-- Instances & reading histograms from strings
----------------------------------------------------------------
readHistogram :: (Read bin, Read a, Bin bin, Unbox a) => String -> Histogram bin a
readHistogram = H.readHistogram
readFileHistogram :: (Read bin, Read a, Bin bin, Unbox a) => FilePath -> IO (Histogram bin a)
readFileHistogram = H.readFileHistogram
----------------------------------------------------------------
Accessors & conversion
----------------------------------------------------------------
bins :: Histogram bin a -> bin
bins = H.bins
histData :: Histogram bin a -> Vector a
histData = H.histData
underflows :: Histogram bin a -> Maybe a
underflows = H.underflows
overflows :: Histogram bin a -> Maybe a
overflows = H.overflows
outOfRange :: Histogram bin a -> Maybe (a,a)
outOfRange = H.outOfRange
asList :: (Unbox a, Bin bin) => Histogram bin a -> [(BinValue bin, a)]
asList = H.asList
asVector :: (Bin bin, Unbox a, Unbox (BinValue bin,a))
=> Histogram bin a -> Vector (BinValue bin, a)
asVector = H.asVector
at :: (Bin bin, Unbox a) => Histogram bin a -> HistIndex bin -> a
at = H.at
atV :: (Bin bin, Unbox a) => Histogram bin a -> BinValue bin -> a
atV = H.atV
atI :: (Bin bin, Unbox a) => Histogram bin a -> Int -> a
atI = H.atI
----------------------------------------------------------------
-- Modify histograms
----------------------------------------------------------------
map :: (Unbox a, Unbox b) => (a -> b) -> Histogram bin a -> Histogram bin b
map = H.map
bmap :: (Unbox a, Unbox b, Bin bin)
=> (BinValue bin -> a -> b) -> Histogram bin a -> Histogram bin b
bmap = H.bmap
mapData :: (Unbox a, Unbox b, Bin bin)
=> (Vector a -> Vector b) -> Histogram bin a -> Histogram bin b
mapData = H.mapData
zip :: (BinEq bin, Unbox a, Unbox b, Unbox c)
=> (a -> b -> c) -> Histogram bin a -> Histogram bin b -> Histogram bin c
zip = H.zip
zipSafe :: (BinEq bin, Unbox a, Unbox b, Unbox c)
=> (a -> b -> c) -> Histogram bin a -> Histogram bin b -> Maybe (Histogram bin c)
zipSafe = H.zipSafe
convertBinning :: (ConvertBin bin bin', Unbox a)
=> Histogram bin a -> Histogram bin' a
convertBinning = H.convertBinning
----------------------------------------------------------------
-- Folding
----------------------------------------------------------------
foldl :: (Unbox a) => (b -> a -> b) -> b -> Histogram bin a -> b
foldl = H.foldl
bfoldl :: (Bin bin, Unbox a) => (b -> BinValue bin -> a -> b) -> b -> Histogram bin a -> b
bfoldl = H.bfoldl
sum :: (Unbox a, Num a) => Histogram bin a -> a
sum = H.sum
minimum :: (Unbox a, Ord a) => Histogram bin a -> a
minimum = H.minimum
minimumBy :: (Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> a
minimumBy = H.minimumBy
maximum :: (Unbox a, Ord a) => Histogram bin a -> a
maximum = H.maximum
maximumBy :: (Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> a
maximumBy = H.maximumBy
minIndex :: (Ord a, Unbox a) => Histogram bin a -> Int
minIndex = H.minIndex
minIndexBy :: (Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> Int
minIndexBy = H.minIndexBy
maxIndex :: (Ord a, Unbox a) => Histogram bin a -> Int
maxIndex = H.maxIndex
maxIndexBy :: (Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> Int
maxIndexBy = H.maxIndexBy
minBin :: (Bin bin, Ord a, Unbox a) => Histogram bin a -> BinValue bin
minBin = H.minBin
minBinBy :: (Bin bin, Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> BinValue bin
minBinBy = H.minBinBy
maxBin :: (Bin bin, Ord a, Unbox a) => Histogram bin a -> BinValue bin
maxBin = H.maxBin
maxBinBy :: (Bin bin, Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> BinValue bin
maxBinBy = H.maxBinBy
----------------------------------------------------------------
-- Slicing and reducing histograms
----------------------------------------------------------------
slice :: (SliceableBin bin, Unbox a)
=> HistIndex bin
-> HistIndex bin
-> Histogram bin a
-> Histogram bin a
slice = H.slice
rebin :: (MergeableBin bin, Unbox a)
=> CutDirection
-> Int
-> (a -> a -> a)
-> Histogram bin a
-> Histogram bin a
rebin = H.rebin
{ - # INLINE rebin # - }
rebinFold :: (MergeableBin bin, Unbox a, Unbox b)
=> CutDirection
-> Int
-> (b -> a -> b)
-> b
-> Histogram bin a
-> Histogram bin b
rebinFold = H.rebinFold
-- {-# INLINE rebinFold #-}
----------------------------------------------------------------
-- 2D histograms
----------------------------------------------------------------
sliceAlongX :: (Unbox a, Bin bX, Bin bY)
=> Histogram (Bin2D bX bY) a
-> HistIndex bY
-> Histogram bX a
sliceAlongX = H.sliceAlongX
sliceAlongY :: (Unbox a, Bin bX, Bin bY)
=> Histogram (Bin2D bX bY) a
-> HistIndex bX
-> Histogram bY a
sliceAlongY = H.sliceAlongY
listSlicesAlongX :: (Unbox a, Bin bX, Bin bY)
=> Histogram (Bin2D bX bY) a
-> [(BinValue bY, Histogram bX a)]
listSlicesAlongX = H.listSlicesAlongX
listSlicesAlongY :: (Unbox a, Bin bX, Bin bY)
=> Histogram (Bin2D bX bY) a
-> [(BinValue bX, Histogram bY a)]
listSlicesAlongY = H.listSlicesAlongY
reduceX :: (Unbox a, Unbox b, Bin bX, Bin bY)
=> (Histogram bX a -> b)
-> Histogram (Bin2D bX bY) a
-> Histogram bY b
reduceX = H.reduceX
breduceX :: (Unbox a, Unbox b, Bin bX, Bin bY)
=> (BinValue bY -> Histogram bX a -> b)
-> Histogram (Bin2D bX bY) a
-> Histogram bY b
breduceX = H.breduceX
reduceY :: (Unbox a, Unbox b, Bin bX, Bin bY)
=> (Histogram bY a -> b)
-> Histogram (Bin2D bX bY) a
-> Histogram bX b
reduceY = H.reduceY
breduceY :: (Unbox a, Unbox b, Bin bX, Bin bY)
=> (BinValue bX -> Histogram bY a -> b)
-> Histogram (Bin2D bX bY) a
-> Histogram bX b
breduceY = H.breduceY
liftX :: (Bin bX, Bin bY, BinEq bX', Unbox a, Unbox b)
=> (Histogram bX a -> Histogram bX' b)
-> Histogram (Bin2D bX bY) a
-> Histogram (Bin2D bX' bY) b
liftX = H.liftX
liftY :: (Bin bX, Bin bY, BinEq bY', Unbox a, Unbox b)
=> (Histogram bY a -> Histogram bY' b)
-> Histogram (Bin2D bX bY ) a
-> Histogram (Bin2D bX bY') b
liftY = H.liftY
| null | https://raw.githubusercontent.com/Shimuuar/histogram-fill/3dff15027390cf64e7fc3fbaac34c28ffcdacbd6/histogram-fill/Data/Histogram.hs | haskell | # LANGUAGE GADTs #
|
Module : Data.Histogram
License : BSD3
Stability : experimental
Immutable histograms. This module exports the same API as
'Data.Histogram.Generic' but specialized to unboxed vectors. Please refer
to the aforementioned module for detailed documentation.
* Immutable histograms
** Constructors
** Conversion to other data types
* Serialization to strings
$serialization
* Accessors
** Indexing
* Transformations
** Type conversion
* Folding
** Specialized folds
* Slicing & rebinning
* 2D histograms
** Slicing
** Reducing along axis
* Lift histogram transform to 2D
| Immutable histogram. A histogram consists of a binning algorithm,
an optional number of under and overflows, and data.
--------------------------------------------------------------
Instances & reading histograms from strings
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
Modify histograms
--------------------------------------------------------------
--------------------------------------------------------------
Folding
--------------------------------------------------------------
--------------------------------------------------------------
Slicing and reducing histograms
--------------------------------------------------------------
{-# INLINE rebinFold #-}
--------------------------------------------------------------
2D histograms
-------------------------------------------------------------- | # LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
Copyright : Copyright ( c ) 2009 , < >
Maintainer : < >
module Data.Histogram (
Histogram
, module Data.Histogram.Bin
, histogram
, histogramUO
, asList
, asVector
, readHistogram
, readFileHistogram
, bins
, histData
, underflows
, overflows
, outOfRange
, HistIndex(..)
, histIndex
, at
, atV
, atI
, map
, bmap
, mapData
, zip
, zipSafe
, convertBinning
, foldl
, bfoldl
, sum
, minimum
, minimumBy
, maximum
, maximumBy
, minIndex
, minIndexBy
, maxIndex
, maxIndexBy
, minBin
, minBinBy
, maxBin
, maxBinBy
, slice
, rebin
, rebinFold
, sliceAlongX
, sliceAlongY
, listSlicesAlongX
, listSlicesAlongY
, reduceX
, breduceX
, reduceY
, breduceY
, liftX
, liftY
) where
import qualified Data.Vector.Unboxed as U
import Data.Vector.Unboxed (Unbox,Vector)
import qualified Data.Histogram.Generic as H
import Data.Histogram.Generic (HistIndex(..),histIndex)
import Data.Histogram.Bin
import Prelude hiding (map, zip, foldl, sum, maximum, minimum)
type Histogram bin a = H.Histogram U.Vector bin a
histogram :: (Unbox a, Bin bin) => bin -> Vector a -> Histogram bin a
histogram = H.histogram
histogramUO :: (Unbox a, Bin bin) => bin -> Maybe (a,a) -> Vector a -> Histogram bin a
histogramUO = H.histogramUO
readHistogram :: (Read bin, Read a, Bin bin, Unbox a) => String -> Histogram bin a
readHistogram = H.readHistogram
readFileHistogram :: (Read bin, Read a, Bin bin, Unbox a) => FilePath -> IO (Histogram bin a)
readFileHistogram = H.readFileHistogram
Accessors & conversion
bins :: Histogram bin a -> bin
bins = H.bins
histData :: Histogram bin a -> Vector a
histData = H.histData
underflows :: Histogram bin a -> Maybe a
underflows = H.underflows
overflows :: Histogram bin a -> Maybe a
overflows = H.overflows
outOfRange :: Histogram bin a -> Maybe (a,a)
outOfRange = H.outOfRange
asList :: (Unbox a, Bin bin) => Histogram bin a -> [(BinValue bin, a)]
asList = H.asList
asVector :: (Bin bin, Unbox a, Unbox (BinValue bin,a))
=> Histogram bin a -> Vector (BinValue bin, a)
asVector = H.asVector
at :: (Bin bin, Unbox a) => Histogram bin a -> HistIndex bin -> a
at = H.at
atV :: (Bin bin, Unbox a) => Histogram bin a -> BinValue bin -> a
atV = H.atV
atI :: (Bin bin, Unbox a) => Histogram bin a -> Int -> a
atI = H.atI
map :: (Unbox a, Unbox b) => (a -> b) -> Histogram bin a -> Histogram bin b
map = H.map
bmap :: (Unbox a, Unbox b, Bin bin)
=> (BinValue bin -> a -> b) -> Histogram bin a -> Histogram bin b
bmap = H.bmap
mapData :: (Unbox a, Unbox b, Bin bin)
=> (Vector a -> Vector b) -> Histogram bin a -> Histogram bin b
mapData = H.mapData
zip :: (BinEq bin, Unbox a, Unbox b, Unbox c)
=> (a -> b -> c) -> Histogram bin a -> Histogram bin b -> Histogram bin c
zip = H.zip
zipSafe :: (BinEq bin, Unbox a, Unbox b, Unbox c)
=> (a -> b -> c) -> Histogram bin a -> Histogram bin b -> Maybe (Histogram bin c)
zipSafe = H.zipSafe
convertBinning :: (ConvertBin bin bin', Unbox a)
=> Histogram bin a -> Histogram bin' a
convertBinning = H.convertBinning
foldl :: (Unbox a) => (b -> a -> b) -> b -> Histogram bin a -> b
foldl = H.foldl
bfoldl :: (Bin bin, Unbox a) => (b -> BinValue bin -> a -> b) -> b -> Histogram bin a -> b
bfoldl = H.bfoldl
sum :: (Unbox a, Num a) => Histogram bin a -> a
sum = H.sum
minimum :: (Unbox a, Ord a) => Histogram bin a -> a
minimum = H.minimum
minimumBy :: (Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> a
minimumBy = H.minimumBy
maximum :: (Unbox a, Ord a) => Histogram bin a -> a
maximum = H.maximum
maximumBy :: (Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> a
maximumBy = H.maximumBy
minIndex :: (Ord a, Unbox a) => Histogram bin a -> Int
minIndex = H.minIndex
minIndexBy :: (Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> Int
minIndexBy = H.minIndexBy
maxIndex :: (Ord a, Unbox a) => Histogram bin a -> Int
maxIndex = H.maxIndex
maxIndexBy :: (Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> Int
maxIndexBy = H.maxIndexBy
minBin :: (Bin bin, Ord a, Unbox a) => Histogram bin a -> BinValue bin
minBin = H.minBin
minBinBy :: (Bin bin, Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> BinValue bin
minBinBy = H.minBinBy
maxBin :: (Bin bin, Ord a, Unbox a) => Histogram bin a -> BinValue bin
maxBin = H.maxBin
maxBinBy :: (Bin bin, Unbox a) => (a -> a -> Ordering) -> Histogram bin a -> BinValue bin
maxBinBy = H.maxBinBy
slice :: (SliceableBin bin, Unbox a)
=> HistIndex bin
-> HistIndex bin
-> Histogram bin a
-> Histogram bin a
slice = H.slice
rebin :: (MergeableBin bin, Unbox a)
=> CutDirection
-> Int
-> (a -> a -> a)
-> Histogram bin a
-> Histogram bin a
rebin = H.rebin
{ - # INLINE rebin # - }
rebinFold :: (MergeableBin bin, Unbox a, Unbox b)
=> CutDirection
-> Int
-> (b -> a -> b)
-> b
-> Histogram bin a
-> Histogram bin b
rebinFold = H.rebinFold
sliceAlongX :: (Unbox a, Bin bX, Bin bY)
=> Histogram (Bin2D bX bY) a
-> HistIndex bY
-> Histogram bX a
sliceAlongX = H.sliceAlongX
sliceAlongY :: (Unbox a, Bin bX, Bin bY)
=> Histogram (Bin2D bX bY) a
-> HistIndex bX
-> Histogram bY a
sliceAlongY = H.sliceAlongY
listSlicesAlongX :: (Unbox a, Bin bX, Bin bY)
=> Histogram (Bin2D bX bY) a
-> [(BinValue bY, Histogram bX a)]
listSlicesAlongX = H.listSlicesAlongX
listSlicesAlongY :: (Unbox a, Bin bX, Bin bY)
=> Histogram (Bin2D bX bY) a
-> [(BinValue bX, Histogram bY a)]
listSlicesAlongY = H.listSlicesAlongY
reduceX :: (Unbox a, Unbox b, Bin bX, Bin bY)
=> (Histogram bX a -> b)
-> Histogram (Bin2D bX bY) a
-> Histogram bY b
reduceX = H.reduceX
breduceX :: (Unbox a, Unbox b, Bin bX, Bin bY)
=> (BinValue bY -> Histogram bX a -> b)
-> Histogram (Bin2D bX bY) a
-> Histogram bY b
breduceX = H.breduceX
reduceY :: (Unbox a, Unbox b, Bin bX, Bin bY)
=> (Histogram bY a -> b)
-> Histogram (Bin2D bX bY) a
-> Histogram bX b
reduceY = H.reduceY
breduceY :: (Unbox a, Unbox b, Bin bX, Bin bY)
=> (BinValue bX -> Histogram bY a -> b)
-> Histogram (Bin2D bX bY) a
-> Histogram bX b
breduceY = H.breduceY
liftX :: (Bin bX, Bin bY, BinEq bX', Unbox a, Unbox b)
=> (Histogram bX a -> Histogram bX' b)
-> Histogram (Bin2D bX bY) a
-> Histogram (Bin2D bX' bY) b
liftX = H.liftX
liftY :: (Bin bX, Bin bY, BinEq bY', Unbox a, Unbox b)
=> (Histogram bY a -> Histogram bY' b)
-> Histogram (Bin2D bX bY ) a
-> Histogram (Bin2D bX bY') b
liftY = H.liftY
|
4fe1032c546a1b79d7c1df8518903ddbe762ecd341fab46b7dbeed5942035683 | DaisukeBekki/lightblue | ProofTree.hs | module DTS.Alligator.ProofTree
(
prove,
settingDef,
settingDNE,
settingEFQ,
ProofMode(..),
Setting(..),
announce
) where
DTT
DTT
Arrowterm
import qualified Data.Text.Lazy as T -- text
import qualified Data.List as L -- base
import qualified DTS.Prover_daido.Judgement as J
import qualified Debug.Trace as D
import qualified Data.Text.Lazy.IO as T
import qualified Interface.HTML as HTML
import qualified Data.Maybe as M
data ProofMode = Plain | WithDNE | WithEFQ deriving (Show,Eq)
data Setting = Setting {mode :: ProofMode,falsum :: Bool,maxdepth :: Int,maxtime :: Int,debug :: Bool,nglst :: [(Int,A.Arrowterm)],typecheckTerm :: Maybe A.Arrowterm}
settingDef = Setting{mode = Plain,falsum = True,maxdepth = 9,maxtime = 100000,debug = False,nglst=[],typecheckTerm = Nothing}
settingDNE = Setting{mode = WithDNE,falsum = True,maxdepth = 9,maxtime = 100000,debug = True,nglst=[],typecheckTerm = Nothing}
settingEFQ = Setting{mode = WithEFQ,falsum = True,maxdepth = 9,maxtime = 100000,debug = False,nglst=[],typecheckTerm = Nothing}
announce :: [J.Tree J.Judgement] -> IO T.Text
announce [] = return $ T.pack "Nothing to announce"
announce jtrees = do
let jtree = head jtrees
return
$ T.append (T.pack HTML.htmlHeader4MathML) $
T.append HTML.startMathML $
T.append (J.treeToMathML jtree) $
T.append HTML.endMathML
(T.pack HTML.htmlFooter4MathML)
prove :: A.TEnv -- ^ var_context ex)[(DT.Con (T.pack "prop")),(DT.Con (T.pack "set")),(DT.Con (T.pack "prop"))]
-> A.TEnv -- ^ sig_context ex)[((T.pack "prop"),DT.Type),((T.pack "set"),DT.Type)] , classic
type ex ) ( DT.Pi ( DT.Var 0 ) ( DT.Sigma ( DT.Var 0,DT.Var 3 ) ) )
-> Setting
-> [J.Tree J.Judgement] -- term
prove var_env sig_env pre_type setting=
let var_env' = var_env ++ sig_env
arrow_env = map (A.dtToArrow . DT.toDTT . UD.betaReduce . DT.toUDTT) var_env'
arrow_type = (A.dtToArrow . DT.toDTT . UD.betaReduce . DT.toUDTT) pre_type
-- notate_type = con_arrow arrow_type
arrow_terms = searchProof arrow_env arrow_type 1 setting
in debugLog arrow_env arrow_type 0 setting "goal" $map A.aTreeTojTree arrow_terms
forwardContext :: [A.Arrowterm] -> [J.Tree A.AJudgement]
forwardContext context = do
let forwarded = concat $ zipWith (\ f fr -> map (\aTree -> let (A.AJudgement env aterm atype) = A.downSide aTree in A.changeDownSide aTree (A.AJudgement fr aterm atype)) (forward f fr)) context (init $ L.tails context)
adoptVarRuleAndType = concatMap (\fr -> (J.T J.VAR( A.AJudgement (tail fr) (head fr) (A.Conclusion DT.Type)) []): [J.T J.VAR(A.AJudgement fr (A.Conclusion $ DT.Var 0 ) (A.shiftIndices (head fr) 1 0)) [] ] )$ init $ L.tails context
connected = forwarded ++ adoptVarRuleAndType
map
(\aTree -> let (A.AJudgement env aTerm a_type) = A.downSide aTree; d = length context - length env in A.changeDownSide aTree $A.AJudgement context (A.shiftIndices aTerm d 0) (A.shiftIndices a_type d 0))
connected
[ u0 :p , u1:(u2 : p)→q ト [ u3 :p ] = > q : type , u0 :p , u1:(u2 : p)→q ト u1 : [ u3 :p ] = > q , u0 :p , u1:(u2 : p)→q ト p : type , u0 :p , u1:(u2 : p)→q ト u0 : p ]
term = A.Arrow [ A.Conclusion $ DT.Con $ T.pack " p " ] ( A.Arrow_Sigma ( A.Conclusion $ DT.Con $ T.pack " q " ) ( A.Conclusion $ DT.Con $ T.pack " r " ) )
forward :: A.Arrowterm -> [A.Arrowterm] -> [J.Tree A.AJudgement]
forward term env=
let baseCon = A.genFreeCon term "base"
forwarded' = forward' env baseCon term
in map
(\aTreef
-> let
aTree = aTreef (A.Conclusion $DT.Var 0)
(A.AJudgement con aTerm aType) = A.downSide aTree
newJ = A.AJudgement
con
(A.arrowSubst (A.shiftIndices aTerm 1 0) (A.Conclusion $ DT.Var 0) baseCon)
(A.arrowSubst (A.shiftIndices aType 1 0) (A.Conclusion $ DT.Var 0) baseCon)
in A.changeDownSide aTree newJ)
forwarded'
forward' :: [A.Arrowterm] -- ^ origin
-> A.Arrowterm -- ^ base
-> A.Arrowterm -- ^ target
-> [A.Arrowterm ->J.Tree A.AJudgement]
forward' context base (A.Arrow_Sigma h t) =
let fstbase = A.Arrow_Proj A.Arrow_Fst base
sndbase = A.Arrow_Proj A.Arrow_Snd base
t' = A.shiftIndices (A.arrowSubst t fstbase (A.Conclusion $ DT.Var 0)) (-1) 0
hForward = forward' context fstbase h
tForward = forward' context sndbase t'
hTree base' = J.T J.SigE (A.AJudgement context fstbase h) [J.T J.VAR(A.AJudgement context base' (A.Arrow_Sigma h t)) []]
tTree base'= J.T J.SigE (A.AJudgement context sndbase t') [J.T J.VAR(A.AJudgement context base' (A.Arrow_Sigma h t)) []]
in (if null tForward then [tTree] else tForward) ++ (if null hForward then [hTree] else hForward)
forward' context base (A.Arrow env (A.Arrow_Sigma h t)) =
let lenEnv = length env
term1 = addLam lenEnv $ A.Arrow_Proj A.Arrow_Fst $ addApp lenEnv base
term2 = addLam lenEnv $ A.Arrow_Proj A.Arrow_Snd $ addApp lenEnv base
t' = A.shiftIndices (A.arrowSubst t (A.shiftIndices term1 lenEnv 0) (A.Conclusion $ DT.Var 0)) (-1) 0
type1 = case h of (A.Arrow henv hcon) -> A.Arrow (henv ++ env) hcon ; _ -> A.Arrow env h
type2 = case t' of (A.Arrow tenv tcon) -> A.Arrow (tenv ++ env) tcon; _ ->A.Arrow env t'
hForward = forward' context term1 type1
tForward = forward' context term2 type2
tTree base'= J.T J.SigE (A.AJudgement context term2 type2) [J.T J.VAR(A.AJudgement context base' $ A.Arrow env (A.Arrow_Sigma h t)) []]
hTree base'= J.T J.SigE (A.AJudgement context term1 type1) [J.T J.VAR(A.AJudgement context base' $ A.Arrow env (A.Arrow_Sigma h t)) []]
result = (if null tForward then [tTree] else tForward) ++ (if null hForward then [hTree] else hForward)
in
result
forward' context base (A.Arrow a (A.Arrow b c)) =
forward' context base (A.Arrow (b ++ a) c)
forward' context base arrowterm = []
addApp ::Int -> A.Arrowterm -> A.Arrowterm
addApp 0 base = base
addApp num base = addApp (num - 1) $ A.Arrow_App (A.shiftIndices base 1 0) (A.Conclusion $ DT.Var 0)
addLam :: Int -> A.Arrowterm -> A.Arrowterm
addLam 0 term = term
addLam num term = A.Arrow_Lam $ addLam (num - 1) term
headIsType :: A.Arrowterm -> Bool
headIsType (A.Arrow env _) = (last env == A.Conclusion DT.Type) || (case last env of A.Arrow b1 b2 -> headIsType (A.Arrow b1 b2) ; _ -> False)
headIsType _=False
match :: Int -> A.Arrowterm -> A.Arrowterm -> Bool
match =A.canBeSame
tailIsB :: A.Arrowterm -> A.Arrowterm -> (Int,Bool)
tailIsB (A.Arrow env b) (A.Arrow env' b')=
let d = length env - length env'
in (d
,
d >= 0
&&
match (length env) b (A.shiftIndices b' d 0)
&&
and (map (\((s,num),t) -> match (num + d) s t) $zip (zip (take (length env') env) [0..]) (map (\c' -> A.shiftIndices c' d 0) env')))
tailIsB (A.Arrow env b) b'=
let result = (length env,match (length env) b (A.shiftIndices b' (length env) 0))
-D.trace ( " match " + + ( show $ length env)++(show ( A.Arrow env b))++ " b : " + + ( show b)++ " b ' : " + + ( show $ ( A.shiftIndices b ' ( length env ) 0))++ " result : " + + ( show result))-
result
tailIsB _ _ =(0,False)
arrowConclusionB :: A.AJudgement -> A.Arrowterm -> ((Int,Bool),A.AJudgement)
arrowConclusionB j b=
let foroutut = D.trace ( " arrowConclusion j:"++(show j)++ " b ) ) [ ] in
(tailIsB (A.typefromAJudgement j) b,j)
| pi型の後ろの方がbと一致するか
arrowConclusionBs :: [A.AJudgement] -> A.Arrowterm -> [(Int,J.Tree A.AJudgement)]
arrowConclusionBs judgements b=
map
(\((num ,b),j )-> (num,J.T J.VAR j []))
$filter
(snd . fst)
$map (\j -> arrowConclusionB j b) judgements
deduceEnv :: [A.Arrowterm] -> (Int,J.Tree A.AJudgement) -> Int -> Setting -> (J.Tree A.AJudgement,[[J.Tree A.AJudgement]])
deduceEnv con (num,aJudgement) depth setting=
case A.downSide aJudgement of
A.AJudgement _ _ (A.Arrow env _) ->
let deduceTargetAndCons = reverse $take num $reverse $ init $ L.tails env
proofForEnv = map (\(f:r) -> deduceWithLog (r++con) f depth setting) deduceTargetAndCons
in
if or $map (null) proofForEnv
then (aJudgement,[])
else (aJudgement,proofForEnv)
_ -> (aJudgement, [])
let ajudge = ( ( mapM ( : r ) - > deduceWithLog ( r++con ) f depth setting ) . ( \(A.AJudgement _ _ ( A.Arrow env _ ) ) - > init $ L.tails env ) ) . A.downSide ) ajudgement
deduceEnvs :: [A.Arrowterm] -> [(Int,J.Tree A.AJudgement)] -> Int -> Setting -> [(J.Tree A.AJudgement,[[J.Tree A.AJudgement]])]
deduceEnvs con aJudgements depth setting=
let ajudges = map (\aj ->deduceEnv con aj depth setting) aJudgements
in filter ((/= []) . snd) ajudges
appAs :: A.Arrowterm -> [A.Arrowterm] -> A.Arrowterm
appAs= foldl A.Arrow_App
substAsInPiElim:: A.Arrowterm -> [A.Arrowterm] -> A.Arrowterm
-- substAsInPiElim term [] = term
substAsInPiElim term ( ( fn , f):r ) = A.arrowSubst ( substAsInPiElim term r ) f ( A.Conclusion $ DT.Var fn )
-- substAsInPiElim term [] = term
substAsInPiElim (A.Arrow env t) args
| length env < length args = undefined
| otherwise =
let beforeSubst =
case (length env - length args) of
0 -> t
d -> A.Arrow (reverse $drop d $reverse env) t
afterSubst = foldr (\(num,a) -> \tt -> A.arrowSubst tt (A.shiftIndices a (length args) (0)) (A.Conclusion $ DT.Var num)) beforeSubst $zip [0..] args
in
A.shiftIndices afterSubst (0-length args) (length args)
substAsInPiElim _ _= undefined
searchProof :: [A.Arrowterm] ->A.Arrowterm -> Int -> Setting-> [J.Tree A.AJudgement]
searchProof a b c setting= L.nub $ deduceWithLog a b c setting
membership :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
membership con arrow_type depth setting=
debugLog con arrow_type depth setting "membership" $
let context = forwardContext con
matchlst = filter
(\xTree -> let x = A.downSide xTree in A.shiftIndices (A.typefromAJudgement x) (length con - length (A.envfromAJudgement x)) 0 == arrow_type)
context
in Right matchlst
piForm :: [A.Arrowterm] -> A.Arrowterm -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
piForm con (A.Arrow as b) arrow_type depth setting
| depth > (maxdepth setting) = debugLogWithTerm con (A.Arrow as b) arrow_type depth setting "piFormハズレ1" $ Left ("too deep @ piForm " ++ show con ++" | "++ show arrow_type)
| arrow_type `notElem` [A.Conclusion DT.Type,A.Conclusion DT.Kind] = debugLogWithTerm con (A.Arrow as b) arrow_type depth setting "piFormハズレ2" $Right []
| otherwise=
debugLogWithTerm con (A.Arrow as b) arrow_type depth setting "piForm1" $
let a = if length as == 1 then head as else last as
aTerm = concatMap (\dtterm -> withLog' typecheck con a (A.Conclusion dtterm) depth setting) [DT.Type,DT.Kind]
in
if null aTerm
then Right []
else
let bEnv = a: con
bJs = withLog' typecheck bEnv (if length as == 1 then b else A.Arrow (init as) b) arrow_type (depth + 1) setting
treeAB = zip (concatMap (replicate (length bJs)) aTerm) (cycle bJs)
in
Right $ map (\(aTree,bTree) -> let x = A.downSide bTree in J.T J.PiF (A.AJudgement con (A.Arrow as b) (A.typefromAJudgement x)) [aTree,bTree]) treeAB
piForm con arrow_term arrow_type depth setting = Right []
sigmaForm:: [A.Arrowterm] -> A.Arrowterm -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
sigmaForm con (A.Arrow_Sigma a b) arrow_type depth setting
| depth > (maxdepth setting) = debugLogWithTerm con (A.Arrow_Sigma a b) arrow_type depth setting "sigmaFormハズレ1" $ Left ("too deep @ piForm " ++ show con ++" | "++ show arrow_type)
| arrow_type `notElem`[A.Conclusion DT.Type,A.Conclusion DT.Kind] = debugLogWithTerm con (A.Arrow_Sigma a b) arrow_type depth setting"sigmaFormハズレ" $Right []
| otherwise =
debugLogWithTerm con (A.Arrow_Sigma a b) arrow_type depth setting "sigmaForm1" $
let aTerm = concatMap (\dtterm -> withLog' typecheck con a (A.Conclusion dtterm) depth setting) [DT.Type,DT.Kind]
in
if null aTerm
then
Right []
else
let bJs = concatMap (\dtterm -> withLog' typecheck (a:con) b (A.Conclusion dtterm) depth setting) [DT.Type,DT.Kind]
treeAB = zip (concatMap (replicate (length bJs)) aTerm) (cycle bJs)
in Right $ map (\(aTree,bTree) -> let x = A.downSide bTree in J.T J.SigF (A.AJudgement con (A.Arrow_Sigma a b) (A.typefromAJudgement x)) [aTree,bTree]) treeAB
sigmaForm con arrow_term arrow_type depth setting = Right []
piIntro :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
piIntro con (A.Arrow a b) depth setting
| depth > (maxdepth setting) = debugLog con (A.Arrow a b) depth setting "piIntroハズレ1" $Left ("too deep @ piIntro " ++ show con ++" ト "++ show (A.Arrow a b))
| null ( concatMap ( \dtterm - > withLog ' ( A.Arrow a b ) ( A.Conclusion dtterm ) ( depth + 1 ) setting ) [ DT.Type , DT.Kind ] ) = debugLog con ( A.Arrow a b ) depth setting " piIntroハズレ2 " $ Right [ ]
| otherwise =
debugLog con (A.Arrow a b) depth setting "piIntro1" $
let
bJs = deduceWithLog (a ++ con) b (depth + 1) setting
typeArrow = L.nub $ concatMap (\dtterm -> withLog' typecheck con (A.Arrow a b) (A.Conclusion dtterm) (depth + 1) setting) [DT.Type,DT.Kind]
treeTB = zip (concatMap (replicate (length bJs)) typeArrow) (cycle bJs)
piABJs =
map
(\(tJ,bJ) ->
let
env = con
aTerm = addLam (length a) (A.termfromAJudgement $ A.downSide bJ)
aType = A.Arrow a b
in
J.T J.PiI (A.AJudgement env aTerm aType) [tJ,bJ] )
treeTB
in Right piABJs
piIntro con arrow_type depth setting = debugLog con arrow_type depth setting "piIntro2" $Right []
A.arrowSubst ( substAsInPiElim term r ) f ( A.Conclusion $ DT.Var fn )
piElim :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
piElim con b1 depth setting
| depth > (maxdepth setting) = debugLog con b1 depth setting "piElimハズレ"$ Left ("too deep @ piElim " ++ show con ++" ト "++ show b1)
| typecheckTerm setting /= Nothing =
case typecheckTerm setting of
-- Just f a ->
-- let atree = deduceWithLog con a depth setting
-- justaType = case aTypes of [] -> Nothing;a:_ -> Just (A.typefromAJudgement $ A.downSide a)
-- in
-- case justaType of
-- Nothing -> debugLog con b1 depth setting ("piElim deduce失敗 : "++(show a))$ Right []
Just aType - >
-- let fType = A.arrowNotat $A.Arrow [aType] b1
ftree = withLog ' typecheck con f fType depth setting
--
Just (A.Arrow_App (A.Conclusion (DT.Var fn)) x) ->
let fType = A.shiftIndices (con !! fn) (fn+1) 0in
case fType of
A.Arrow (a:r) b ->
if b == b1
then
let proofForx = withLog' typecheck con x a (depth + 1) setting
ftree = J.T J.VAR (A.AJudgement con (A.Conclusion (DT.Var fn)) fType) []
downside = A.AJudgement con (A.Arrow_App (A.Conclusion (DT.Var fn)) x) (A.arrowNotat $ A.Arrow r b)
result = map (\xtree -> J.T J.PiE downside [ftree,xtree]) proofForx
in debugLogWithTerm con (A.Arrow_App (A.Conclusion (DT.Var fn)) x) b1 depth setting "piElimtypecheck"$ Right result
else
debugLogWithTerm con (A.Arrow_App (A.Conclusion (DT.Var fn)) x) b1 depth setting "piElimtypecheck ハズレ1"$ Right []
c -> debugLogWithTerm con c b1 depth setting "piElimtypecheck ハズレ2"$ Right []
Just term-> debugLogWithTerm con term b1 depth setting "piElimtypecheck ハズレ3"$ Right []
_ -> Right [] --ここに来ることはない
| otherwise =
let aJudgements = arrowConclusionBs (map A.downSide $ forwardContext con) b1 --
a_type_terms = deduceEnvs con aJudgements (depth+1) setting
in debugLog con b1 depth setting ("piElim1" ++ show aJudgements) $Right
$concatMap
(\(base,ass) ->
M.mapMaybe
(\as ->
let env' = con
args = map (A.termfromAJudgement . A.downSide) as
aTerms' = appAs (A.termfromAJudgement $ A.downSide base) args
a_type' = substAsInPiElim (A.typefromAJudgement $A.downSide base) $ args
in
if a_type' == b1
then
Just $ J.T J.PiE (A.AJudgement env' aTerms' a_type') [base,head as]
else
Nothing
)
(sequence ass)
)
(a_type_terms)
sigmaIntro :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
sigmaIntro con (A.Arrow_Sigma a b1) depth setting
| depth > (maxdepth setting) = debugLog con (A.Arrow_Sigma a b1) depth setting "sigmaIntro深さ"$Left ("too deep @ sigmaIntro " ++ show con ++" ト "++ show (A.Arrow_Sigma a b1))
| null $ concatMap ( \dtterm ->withLog ' ( A.Arrow_Sigma a b1 ) ( A.Conclusion dtterm ) depth setting ) [ DT.Type , DT.Kind ] = Right [ ]
| otherwise =
debugLog con (A.Arrow_Sigma a b1) depth setting "sigmaIntro1" $
let aTermJudgements' =deduceWithLog con a (depth + 1) setting
substedB b a= let base = A.genFreeCon b "base" in A.reduce $ A.arrowSubst (A.shiftIndices (A.arrowSubst b1 base (A.Conclusion $ DT.Var 0)) (-1) 0) a base
dependencyCheck = case aTermJudgements' of [] -> False ; (a:_) -> substedB b1 (A.termfromAJudgement $ A.downSide a) == A.shiftIndices b1 (-1) 0
aTermJudgements =
if dependencyCheck
then
(D.trace (L.replicate (depth+1) '\t'++"後件に影響ないから一個だけ見る" ++ (show $ map A.downSide aTermJudgements')) (take 1 $reverse aTermJudgements'))
else
(D.trace (L.replicate (depth+1) '\t'++"この辺見ていくよー" ++ (show $ map A.downSide aTermJudgements')) aTermJudgements')
typeAS = L.nub $ concatMap ( \dtterm - > withLog ' ( A.Arrow_Sigma a b1 ) ( A.Conclusion dtterm ) ( depth + 1 ) setting ) [ DT.Type , DT.Kind ]
aB1TermsJudgements =
concatMap
(\aJ ->
let b_type = D.trace (L.replicate (depth+1) '\t'++"ここ見てるよ" ++ (show aJ)) substedB b1 (A.termfromAJudgement $ A.downSide aJ)
let con2b = con
-- base = A.genFreeCon b1 "base"
b_type = D.trace ( L.replicate ( depth+1 ) ' \t'++"ここ見てるよ " + + ( show aJ ) ) A.reduce $ A.arrowSubst ( A.shiftIndices ( A.arrowSubst b1 base ( A.Conclusion $ DT.Var 0 ) ) ( -1 ) 0 ) ( A.termfromAJudgement $ A.downSide aJ ) base
treeAB = map (\bJ -> (aJ,bJ)) (deduceWithLog con b_type (depth+2) setting)
in treeAB)
-- zip (concatMap (replicate (length treeAB)) typeAS) (cycle treeAB))
(reverse aTermJudgements)
in
Right
$ map
(\(aJ,b1J) ->
let
env = con
aTerm = A.Arrow_Pair (A.termfromAJudgement $ A.downSide aJ) (A.termfromAJudgement $ A.downSide b1J)
a_type = A.Arrow_Sigma a b1
in J.T J.SigI (A.AJudgement env aTerm a_type) [aJ,b1J])
--(J.Treeで途中まで実装してしまったので)とりあえず型チェックした内容(tJ)を削っている
aB1TermsJudgements
sigmaIntro con arrow_type depth setting = debugLog con arrow_type depth setting "sigmaIntroハズレ" $Right []
eqIntro :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
eqIntro con (A.Arrow_Eq t a b) depth setting
| a /= b = debugLog con (A.Arrow_Eq t a b) depth setting "eqIntro1" $ Right []
| otherwise =
debugLog con (A.Arrow_Eq t a b) depth setting "eqIntro2" $
case withLog' typecheck con a t (depth + 1) setting of
[] -> Right []
typeTree ->
Right
$map
(\dTree -> let (A.AJudgement env aTerm a_type) = A.downSide dTree in J.T J.SigE (A.AJudgement con (A.Conclusion $ DT.Con $T.pack $ "eqIntro(" ++ (show a) ++ ")("++ (show t) ++")" ) (A.Arrow_Eq t a a)) [dTree])
typeTree
eqIntro con b depth setting= debugLog con b depth setting "eqIntro3" $ Right []
eqElim :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
eqElim con target depth setting
| depth > (maxdepth setting) = debugLog con target depth setting "eqElim深さ" $Left ("too deep @ eqElim " ++ show con ++" ト "++ show target)
| not $ any (A.canBeSame 0 (A.Arrow_Eq (A.Conclusion $DT.Var 0) (A.Conclusion $DT.Var 0) (A.Conclusion $DT.Var 0)) ) con = debugLog con target depth setting "eqElimハズレ" $ Right []
| otherwise =
debugLog con target depth setting "eqElim1" $
case target of
A.Conclusion (DT.Var varnum) -> -- | shiftIndices m d i-- add d to all the indices that is greater than or equal to i within m (=d-place shift)
let eqAboutDttermLst = M.catMaybes $map (\(dnum,term) -> case A.shiftIndices term (varnum - dnum) 0 of; (A.Arrow_Eq _ var1 var2) -> if var1 == (A.Conclusion $ DT.Var varnum) then Just (dnum,var2) else (if (var2 == (A.Conclusion $DT.Var varnum))then Just (dnum,var1) else Nothing) ; _ -> Nothing) (zip [(varnum-1),(varnum-2)..0] con) in
filter ( \(dnum , term ) ->case term of;A.Arrow_Eq ( A.Conclusion $ DT.Var num0 ) ( A.Conclusion $ DT.Var num1 ) _ - > True ; _ - > False ) eqlist in A.shiftIndices var1 ( -dnum ) dnum
let varLst = M.mapMaybe
(\(varid,dterm') ->
case deduceWithLog con dterm' (depth + 1) setting of
[] -> Nothing
dtermJs ->
let dtermJ = head dtermJs in
Just $ J.T J.PiE
(A.AJudgement con (A.Conclusion$ DT.Var varid{-暫定-}) target)
[
(J.T J.CON(A.AJudgement con (A.Conclusion$ DT.Var varid) (A.Arrow_Eq (A.Conclusion DT.Type) target dterm')) []),
dtermJ
]
)
eqAboutDttermLst
sigmaLst = [] -- sigmaelimをforward_contextでしているため
piLst = [] -- varで結局拾える
in Right $varLst ++ sigmaLst ++ piLst
_ -> debugLog con target depth setting "eqElim2" $Right[] --target が DT.App (f) (a)のときの対応
efq :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting ->Either String [J.Tree A.AJudgement]
efq con b depth setting
| depth > maxdepth setting = debugLog con b depth setting "efqハズレ1" $ Left $ "too deep @ efq " ++ show con ++" ト "++ show b
| null (withLog' typecheck con b (A.Conclusion DT.Type) (depth + 1) setting ) = debugLog con b depth setting "efqハズレ2"$ Right []
| otherwise =
if null (withLog membership con (A.Conclusion DT.Bot) depth setting)
then
case deduceWithLog con (A.Conclusion DT.Bot) (depth + 1) setting of
[] -> debugLog con b depth setting "efq1" $Right []
botJs -> debugLog con b depth setting "efq2" $
Right
$map
-(\dTree - > let ( A.AJudgement env aTerm a_type ) = A.downSide dTree in J.NotF ( A.AJudgement env ( A.Arrow_App ( A.Conclusion $ DT.Con $ T.pack " efq " ) aTerm ) b ) dTree )
botJs
else debugLog con b depth setting "efq3" $
Right
$map
(\dTree -> let (A.AJudgement env aTerm a_type) = A.downSide dTree in J.T J.SigE (A.AJudgement env (A.Arrow_App (A.Conclusion $ DT.Con $T.pack "efq") aTerm) b) [dTree])
(withLog membership con (A.Conclusion DT.Bot) depth setting)
--(J.Treeで途中まで実装してしまったので)とりあえずEFQの代わりにNotFを使っている
dne :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
dne con b depth setting
| depth > maxdepth setting = debugLog con b depth setting "dne深さ" $ Left $ "too deep @ dne " ++ show con ++" ト "++ show b
| b==A.Conclusion DT.Type =debugLog con b depth setting "dneハズレ2" $ Right []
| case b of (A.Arrow [A.Arrow _ (A.Conclusion DT.Bot)] (A.Conclusion DT.Bot)) -> True ; _ -> False= debugLog con b depth setting "dne2重" $Right []
| b `elem` (map (\(num,term) -> A.shiftIndices term (length con - num) 0) (nglst setting)) = debugLog con b depth setting "dne2回め" $Right []
| null (debugLog con b depth setting "dneが使えるか確認" (withLog' typecheck con b (A.Conclusion DT.Type) (depth + 1) setting)) = debugLog con b depth setting "dneハズレ1" $Right []
| otherwise =
debugLog con b depth setting "dne1" $
case deduceWithLog con (A.Arrow [A.Arrow [b] (A.Conclusion DT.Bot)] (A.Conclusion DT.Bot)) (depth + 1) setting{nglst = ((length con,b) : nglst setting)} of
[] -> Right []
dneJs ->
Right
$map
(\dTree -> let (A.AJudgement env aTerm a_type) = A.downSide dTree in J.T J.SigE (A.AJudgement env (A.Arrow_App (A.Conclusion $ DT.Con $T.pack "dne") aTerm) b) [dTree])
dneJs
--(J.Treeで途中まで実装してしまったので)とりあえずDNEの代わりにNotFを使っている
deduceWithLog :: [A.Arrowterm] -> A.Arrowterm ->Int -> Setting ->[J.Tree A.AJudgement]
deduceWithLog = withLog deduce
withLog' :: ([A.Arrowterm] -> A.Arrowterm -> A.Arrowterm ->Int -> Setting ->Either String [J.Tree A.AJudgement]) -> [A.Arrowterm] -> A.Arrowterm -> A.Arrowterm ->Int -> Setting ->[J.Tree A.AJudgement]
withLog' f con arrow_term arrow_type depth setting =
case f con arrow_term arrow_type depth setting of
Right j -> j
Left msg -> []
withLog :: ([A.Arrowterm] -> A.Arrowterm ->Int -> Setting ->Either String [J.Tree A.AJudgement]) -> [A.Arrowterm] -> A.Arrowterm ->Int -> Setting ->[J.Tree A.AJudgement]
withLog f con arrow_type depth setting =
case f con arrow_type depth setting of
D.trace ( " found : " + + ( show j ) )
D.trace " reset "
typecheck :: [A.Arrowterm] -- ^ context
-> A.Arrowterm -- ^ term
-> A.Arrowterm -- ^ type
-> Int -- ^ depth
-> Setting
-> Either String [J.Tree A.AJudgement]
typecheck con arrow_term arrow_type depth setting
| depth > (maxdepth setting) = Left ("too deep @ typecheck " ++ show con ++" | "++ show arrow_type)
| falsum setting && arrow_term == A.Conclusion DT.Bot && arrow_type == A.Conclusion DT.Type = Right [J.T J.BotF (A.AJudgement con arrow_term arrow_type) []]
| arrow_type == A.Conclusion DT.Kind = if arrow_term == A.Conclusion DT.Type then Right [J.T J.CON(A.AJudgement con arrow_term arrow_type) []] else Right []
| arrow_term == A.Conclusion DT.Kind = debugLogWithTerm con arrow_term arrow_type depth setting ("kindは証明項にはならないと思う") $Right []
| otherwise =
debugLogWithTerm con arrow_term arrow_type depth setting ("typecheck : ") $
let formjudgements = concatMap (\f -> withLog' f con arrow_term arrow_type (depth+1) setting{typecheckTerm = Just arrow_term}) [piForm,sigmaForm]
judgements = foldl
(\js f ->
let js' = filter (\a ->A.termfromAJudgement (A.downSide a) == A.shiftIndices arrow_term (length (A.envfromAJudgement $ A.downSide a)- length con ) 0) js
in if null js' then withLog f con arrow_type (depth+1) setting{typecheckTerm = Just arrow_term} else {-debugLogWithTerm con arrow_term arrow_type depth setting ("found : ") $-} js')
formjudgements
([membership,eqIntro,piIntro,sigmaIntro,piElim,eqElim] ++ [dne | arrow_type /= A.Conclusion DT.Bot && mode setting == WithDNE] ++ [efq | arrow_type /= A.Conclusion DT.Bot && mode setting == WithEFQ])
--
concatMap ( \f - > withLog f con arrow_type depth setting ) [ membership , piIntro , piElim , sigmaIntro ]
deducejudgements = filter ( \a ->A.termfromAJudgement ( A.downSide a ) = = A.shiftIndices arrow_term ( length ( A.envfromAJudgement $ A.downSide a)- length con ) 0 ) judgements
in
-- Right $ if null deducejudgements ++ concatMap (\f -> withLog' f con arrow_term arrow_type depth setting) [piForm,sigmaForm]
debugLogWithTerm con arrow_term arrow_type depth setting ("found : ") $Right judgements
-- | deduce (pi-intro + sigma-intro + membership + type-ax)
deduce :: [A.Arrowterm] -- ^ context
-> A.Arrowterm -- ^ type
-> Int -- ^ depth
-> Setting
->Either String [J.Tree A.AJudgement]
--type-ax
deduce _ (A.Conclusion DT.Kind) depth setting
| depth > maxdepth setting = Left "depth @ deduce - type-ax"
| otherwise = Right [J.T J.VAR(A.AJudgement [] (A.Conclusion DT.Type) (A.Conclusion DT.Kind)) []]
-- --
deduce con arrow_type depth setting
| depth > maxdepth setting = Left ("too deep @ deduce " ++ show con ++" | "++ show arrow_type)
| otherwise =
let judgements = foldl
(\js f -> if null js then withLog f con arrow_type depth setting{typecheckTerm = Nothing} else js)
[]
([membership,eqIntro,piIntro,sigmaIntro,piElim,eqElim] ++ [dne | arrow_type /= A.Conclusion DT.Bot && mode setting == WithDNE] ++ [efq | arrow_type /= A.Conclusion DT.Bot && mode setting == WithEFQ])
in (
if null judgements
then debugLog con arrow_type depth setting "deduce failed"
else
(
if debug setting
then D.trace (L.replicate depth '\t' ++ (show depth) ++ " deduced : " ++ (show $ A.downSide $ head judgements))
else id
)
)
$Right judgements
debugLog :: {-(Show a) =>-} [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> String -> a -> a
debugLog con=
debugLogWithTerm con (A.Conclusion $ DT.Con $T.pack "?")
debugLogWithTerm :: {-(Show a) =>-} [A.Arrowterm] -> A.Arrowterm -> A.Arrowterm -> Int -> Setting -> String -> a -> a
debugLogWithTerm con term target depth setting label answer=
if debug setting
then
D.trace
(L.replicate depth '\t' ++ (show depth) ++ " " ++ label ++ " " ++ (show $ A.AJudgement con term target)++ " ")
answer
else answer
| null | https://raw.githubusercontent.com/DaisukeBekki/lightblue/abdbf50c9418d64afb27b9e09c05b778dd4b98f9/src/DTS/Alligator/ProofTree.hs | haskell | text
base
^ var_context ex)[(DT.Con (T.pack "prop")),(DT.Con (T.pack "set")),(DT.Con (T.pack "prop"))]
^ sig_context ex)[((T.pack "prop"),DT.Type),((T.pack "set"),DT.Type)] , classic
term
notate_type = con_arrow arrow_type
^ origin
^ base
^ target
substAsInPiElim term [] = term
substAsInPiElim term [] = term
Just f a ->
let atree = deduceWithLog con a depth setting
justaType = case aTypes of [] -> Nothing;a:_ -> Just (A.typefromAJudgement $ A.downSide a)
in
case justaType of
Nothing -> debugLog con b1 depth setting ("piElim deduce失敗 : "++(show a))$ Right []
let fType = A.arrowNotat $A.Arrow [aType] b1
ここに来ることはない
base = A.genFreeCon b1 "base"
zip (concatMap (replicate (length treeAB)) typeAS) (cycle treeAB))
(J.Treeで途中まで実装してしまったので)とりあえず型チェックした内容(tJ)を削っている
| shiftIndices m d i-- add d to all the indices that is greater than or equal to i within m (=d-place shift)
暫定
sigmaelimをforward_contextでしているため
varで結局拾える
target が DT.App (f) (a)のときの対応
(J.Treeで途中まで実装してしまったので)とりあえずEFQの代わりにNotFを使っている
(J.Treeで途中まで実装してしまったので)とりあえずDNEの代わりにNotFを使っている
^ context
^ term
^ type
^ depth
debugLogWithTerm con arrow_term arrow_type depth setting ("found : ") $
Right $ if null deducejudgements ++ concatMap (\f -> withLog' f con arrow_term arrow_type depth setting) [piForm,sigmaForm]
| deduce (pi-intro + sigma-intro + membership + type-ax)
^ context
^ type
^ depth
type-ax
--
(Show a) =>
(Show a) => | module DTS.Alligator.ProofTree
(
prove,
settingDef,
settingDNE,
settingEFQ,
ProofMode(..),
Setting(..),
announce
) where
DTT
DTT
Arrowterm
import qualified DTS.Prover_daido.Judgement as J
import qualified Debug.Trace as D
import qualified Data.Text.Lazy.IO as T
import qualified Interface.HTML as HTML
import qualified Data.Maybe as M
data ProofMode = Plain | WithDNE | WithEFQ deriving (Show,Eq)
data Setting = Setting {mode :: ProofMode,falsum :: Bool,maxdepth :: Int,maxtime :: Int,debug :: Bool,nglst :: [(Int,A.Arrowterm)],typecheckTerm :: Maybe A.Arrowterm}
settingDef = Setting{mode = Plain,falsum = True,maxdepth = 9,maxtime = 100000,debug = False,nglst=[],typecheckTerm = Nothing}
settingDNE = Setting{mode = WithDNE,falsum = True,maxdepth = 9,maxtime = 100000,debug = True,nglst=[],typecheckTerm = Nothing}
settingEFQ = Setting{mode = WithEFQ,falsum = True,maxdepth = 9,maxtime = 100000,debug = False,nglst=[],typecheckTerm = Nothing}
announce :: [J.Tree J.Judgement] -> IO T.Text
announce [] = return $ T.pack "Nothing to announce"
announce jtrees = do
let jtree = head jtrees
return
$ T.append (T.pack HTML.htmlHeader4MathML) $
T.append HTML.startMathML $
T.append (J.treeToMathML jtree) $
T.append HTML.endMathML
(T.pack HTML.htmlFooter4MathML)
type ex ) ( DT.Pi ( DT.Var 0 ) ( DT.Sigma ( DT.Var 0,DT.Var 3 ) ) )
-> Setting
prove var_env sig_env pre_type setting=
let var_env' = var_env ++ sig_env
arrow_env = map (A.dtToArrow . DT.toDTT . UD.betaReduce . DT.toUDTT) var_env'
arrow_type = (A.dtToArrow . DT.toDTT . UD.betaReduce . DT.toUDTT) pre_type
arrow_terms = searchProof arrow_env arrow_type 1 setting
in debugLog arrow_env arrow_type 0 setting "goal" $map A.aTreeTojTree arrow_terms
forwardContext :: [A.Arrowterm] -> [J.Tree A.AJudgement]
forwardContext context = do
let forwarded = concat $ zipWith (\ f fr -> map (\aTree -> let (A.AJudgement env aterm atype) = A.downSide aTree in A.changeDownSide aTree (A.AJudgement fr aterm atype)) (forward f fr)) context (init $ L.tails context)
adoptVarRuleAndType = concatMap (\fr -> (J.T J.VAR( A.AJudgement (tail fr) (head fr) (A.Conclusion DT.Type)) []): [J.T J.VAR(A.AJudgement fr (A.Conclusion $ DT.Var 0 ) (A.shiftIndices (head fr) 1 0)) [] ] )$ init $ L.tails context
connected = forwarded ++ adoptVarRuleAndType
map
(\aTree -> let (A.AJudgement env aTerm a_type) = A.downSide aTree; d = length context - length env in A.changeDownSide aTree $A.AJudgement context (A.shiftIndices aTerm d 0) (A.shiftIndices a_type d 0))
connected
[ u0 :p , u1:(u2 : p)→q ト [ u3 :p ] = > q : type , u0 :p , u1:(u2 : p)→q ト u1 : [ u3 :p ] = > q , u0 :p , u1:(u2 : p)→q ト p : type , u0 :p , u1:(u2 : p)→q ト u0 : p ]
term = A.Arrow [ A.Conclusion $ DT.Con $ T.pack " p " ] ( A.Arrow_Sigma ( A.Conclusion $ DT.Con $ T.pack " q " ) ( A.Conclusion $ DT.Con $ T.pack " r " ) )
forward :: A.Arrowterm -> [A.Arrowterm] -> [J.Tree A.AJudgement]
forward term env=
let baseCon = A.genFreeCon term "base"
forwarded' = forward' env baseCon term
in map
(\aTreef
-> let
aTree = aTreef (A.Conclusion $DT.Var 0)
(A.AJudgement con aTerm aType) = A.downSide aTree
newJ = A.AJudgement
con
(A.arrowSubst (A.shiftIndices aTerm 1 0) (A.Conclusion $ DT.Var 0) baseCon)
(A.arrowSubst (A.shiftIndices aType 1 0) (A.Conclusion $ DT.Var 0) baseCon)
in A.changeDownSide aTree newJ)
forwarded'
-> [A.Arrowterm ->J.Tree A.AJudgement]
forward' context base (A.Arrow_Sigma h t) =
let fstbase = A.Arrow_Proj A.Arrow_Fst base
sndbase = A.Arrow_Proj A.Arrow_Snd base
t' = A.shiftIndices (A.arrowSubst t fstbase (A.Conclusion $ DT.Var 0)) (-1) 0
hForward = forward' context fstbase h
tForward = forward' context sndbase t'
hTree base' = J.T J.SigE (A.AJudgement context fstbase h) [J.T J.VAR(A.AJudgement context base' (A.Arrow_Sigma h t)) []]
tTree base'= J.T J.SigE (A.AJudgement context sndbase t') [J.T J.VAR(A.AJudgement context base' (A.Arrow_Sigma h t)) []]
in (if null tForward then [tTree] else tForward) ++ (if null hForward then [hTree] else hForward)
forward' context base (A.Arrow env (A.Arrow_Sigma h t)) =
let lenEnv = length env
term1 = addLam lenEnv $ A.Arrow_Proj A.Arrow_Fst $ addApp lenEnv base
term2 = addLam lenEnv $ A.Arrow_Proj A.Arrow_Snd $ addApp lenEnv base
t' = A.shiftIndices (A.arrowSubst t (A.shiftIndices term1 lenEnv 0) (A.Conclusion $ DT.Var 0)) (-1) 0
type1 = case h of (A.Arrow henv hcon) -> A.Arrow (henv ++ env) hcon ; _ -> A.Arrow env h
type2 = case t' of (A.Arrow tenv tcon) -> A.Arrow (tenv ++ env) tcon; _ ->A.Arrow env t'
hForward = forward' context term1 type1
tForward = forward' context term2 type2
tTree base'= J.T J.SigE (A.AJudgement context term2 type2) [J.T J.VAR(A.AJudgement context base' $ A.Arrow env (A.Arrow_Sigma h t)) []]
hTree base'= J.T J.SigE (A.AJudgement context term1 type1) [J.T J.VAR(A.AJudgement context base' $ A.Arrow env (A.Arrow_Sigma h t)) []]
result = (if null tForward then [tTree] else tForward) ++ (if null hForward then [hTree] else hForward)
in
result
forward' context base (A.Arrow a (A.Arrow b c)) =
forward' context base (A.Arrow (b ++ a) c)
forward' context base arrowterm = []
addApp ::Int -> A.Arrowterm -> A.Arrowterm
addApp 0 base = base
addApp num base = addApp (num - 1) $ A.Arrow_App (A.shiftIndices base 1 0) (A.Conclusion $ DT.Var 0)
addLam :: Int -> A.Arrowterm -> A.Arrowterm
addLam 0 term = term
addLam num term = A.Arrow_Lam $ addLam (num - 1) term
headIsType :: A.Arrowterm -> Bool
headIsType (A.Arrow env _) = (last env == A.Conclusion DT.Type) || (case last env of A.Arrow b1 b2 -> headIsType (A.Arrow b1 b2) ; _ -> False)
headIsType _=False
match :: Int -> A.Arrowterm -> A.Arrowterm -> Bool
match =A.canBeSame
tailIsB :: A.Arrowterm -> A.Arrowterm -> (Int,Bool)
tailIsB (A.Arrow env b) (A.Arrow env' b')=
let d = length env - length env'
in (d
,
d >= 0
&&
match (length env) b (A.shiftIndices b' d 0)
&&
and (map (\((s,num),t) -> match (num + d) s t) $zip (zip (take (length env') env) [0..]) (map (\c' -> A.shiftIndices c' d 0) env')))
tailIsB (A.Arrow env b) b'=
let result = (length env,match (length env) b (A.shiftIndices b' (length env) 0))
-D.trace ( " match " + + ( show $ length env)++(show ( A.Arrow env b))++ " b : " + + ( show b)++ " b ' : " + + ( show $ ( A.shiftIndices b ' ( length env ) 0))++ " result : " + + ( show result))-
result
tailIsB _ _ =(0,False)
arrowConclusionB :: A.AJudgement -> A.Arrowterm -> ((Int,Bool),A.AJudgement)
arrowConclusionB j b=
let foroutut = D.trace ( " arrowConclusion j:"++(show j)++ " b ) ) [ ] in
(tailIsB (A.typefromAJudgement j) b,j)
| pi型の後ろの方がbと一致するか
arrowConclusionBs :: [A.AJudgement] -> A.Arrowterm -> [(Int,J.Tree A.AJudgement)]
arrowConclusionBs judgements b=
map
(\((num ,b),j )-> (num,J.T J.VAR j []))
$filter
(snd . fst)
$map (\j -> arrowConclusionB j b) judgements
deduceEnv :: [A.Arrowterm] -> (Int,J.Tree A.AJudgement) -> Int -> Setting -> (J.Tree A.AJudgement,[[J.Tree A.AJudgement]])
deduceEnv con (num,aJudgement) depth setting=
case A.downSide aJudgement of
A.AJudgement _ _ (A.Arrow env _) ->
let deduceTargetAndCons = reverse $take num $reverse $ init $ L.tails env
proofForEnv = map (\(f:r) -> deduceWithLog (r++con) f depth setting) deduceTargetAndCons
in
if or $map (null) proofForEnv
then (aJudgement,[])
else (aJudgement,proofForEnv)
_ -> (aJudgement, [])
let ajudge = ( ( mapM ( : r ) - > deduceWithLog ( r++con ) f depth setting ) . ( \(A.AJudgement _ _ ( A.Arrow env _ ) ) - > init $ L.tails env ) ) . A.downSide ) ajudgement
deduceEnvs :: [A.Arrowterm] -> [(Int,J.Tree A.AJudgement)] -> Int -> Setting -> [(J.Tree A.AJudgement,[[J.Tree A.AJudgement]])]
deduceEnvs con aJudgements depth setting=
let ajudges = map (\aj ->deduceEnv con aj depth setting) aJudgements
in filter ((/= []) . snd) ajudges
appAs :: A.Arrowterm -> [A.Arrowterm] -> A.Arrowterm
appAs= foldl A.Arrow_App
substAsInPiElim:: A.Arrowterm -> [A.Arrowterm] -> A.Arrowterm
substAsInPiElim term ( ( fn , f):r ) = A.arrowSubst ( substAsInPiElim term r ) f ( A.Conclusion $ DT.Var fn )
substAsInPiElim (A.Arrow env t) args
| length env < length args = undefined
| otherwise =
let beforeSubst =
case (length env - length args) of
0 -> t
d -> A.Arrow (reverse $drop d $reverse env) t
afterSubst = foldr (\(num,a) -> \tt -> A.arrowSubst tt (A.shiftIndices a (length args) (0)) (A.Conclusion $ DT.Var num)) beforeSubst $zip [0..] args
in
A.shiftIndices afterSubst (0-length args) (length args)
substAsInPiElim _ _= undefined
searchProof :: [A.Arrowterm] ->A.Arrowterm -> Int -> Setting-> [J.Tree A.AJudgement]
searchProof a b c setting= L.nub $ deduceWithLog a b c setting
membership :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
membership con arrow_type depth setting=
debugLog con arrow_type depth setting "membership" $
let context = forwardContext con
matchlst = filter
(\xTree -> let x = A.downSide xTree in A.shiftIndices (A.typefromAJudgement x) (length con - length (A.envfromAJudgement x)) 0 == arrow_type)
context
in Right matchlst
piForm :: [A.Arrowterm] -> A.Arrowterm -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
piForm con (A.Arrow as b) arrow_type depth setting
| depth > (maxdepth setting) = debugLogWithTerm con (A.Arrow as b) arrow_type depth setting "piFormハズレ1" $ Left ("too deep @ piForm " ++ show con ++" | "++ show arrow_type)
| arrow_type `notElem` [A.Conclusion DT.Type,A.Conclusion DT.Kind] = debugLogWithTerm con (A.Arrow as b) arrow_type depth setting "piFormハズレ2" $Right []
| otherwise=
debugLogWithTerm con (A.Arrow as b) arrow_type depth setting "piForm1" $
let a = if length as == 1 then head as else last as
aTerm = concatMap (\dtterm -> withLog' typecheck con a (A.Conclusion dtterm) depth setting) [DT.Type,DT.Kind]
in
if null aTerm
then Right []
else
let bEnv = a: con
bJs = withLog' typecheck bEnv (if length as == 1 then b else A.Arrow (init as) b) arrow_type (depth + 1) setting
treeAB = zip (concatMap (replicate (length bJs)) aTerm) (cycle bJs)
in
Right $ map (\(aTree,bTree) -> let x = A.downSide bTree in J.T J.PiF (A.AJudgement con (A.Arrow as b) (A.typefromAJudgement x)) [aTree,bTree]) treeAB
piForm con arrow_term arrow_type depth setting = Right []
sigmaForm:: [A.Arrowterm] -> A.Arrowterm -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
sigmaForm con (A.Arrow_Sigma a b) arrow_type depth setting
| depth > (maxdepth setting) = debugLogWithTerm con (A.Arrow_Sigma a b) arrow_type depth setting "sigmaFormハズレ1" $ Left ("too deep @ piForm " ++ show con ++" | "++ show arrow_type)
| arrow_type `notElem`[A.Conclusion DT.Type,A.Conclusion DT.Kind] = debugLogWithTerm con (A.Arrow_Sigma a b) arrow_type depth setting"sigmaFormハズレ" $Right []
| otherwise =
debugLogWithTerm con (A.Arrow_Sigma a b) arrow_type depth setting "sigmaForm1" $
let aTerm = concatMap (\dtterm -> withLog' typecheck con a (A.Conclusion dtterm) depth setting) [DT.Type,DT.Kind]
in
if null aTerm
then
Right []
else
let bJs = concatMap (\dtterm -> withLog' typecheck (a:con) b (A.Conclusion dtterm) depth setting) [DT.Type,DT.Kind]
treeAB = zip (concatMap (replicate (length bJs)) aTerm) (cycle bJs)
in Right $ map (\(aTree,bTree) -> let x = A.downSide bTree in J.T J.SigF (A.AJudgement con (A.Arrow_Sigma a b) (A.typefromAJudgement x)) [aTree,bTree]) treeAB
sigmaForm con arrow_term arrow_type depth setting = Right []
piIntro :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
piIntro con (A.Arrow a b) depth setting
| depth > (maxdepth setting) = debugLog con (A.Arrow a b) depth setting "piIntroハズレ1" $Left ("too deep @ piIntro " ++ show con ++" ト "++ show (A.Arrow a b))
| null ( concatMap ( \dtterm - > withLog ' ( A.Arrow a b ) ( A.Conclusion dtterm ) ( depth + 1 ) setting ) [ DT.Type , DT.Kind ] ) = debugLog con ( A.Arrow a b ) depth setting " piIntroハズレ2 " $ Right [ ]
| otherwise =
debugLog con (A.Arrow a b) depth setting "piIntro1" $
let
bJs = deduceWithLog (a ++ con) b (depth + 1) setting
typeArrow = L.nub $ concatMap (\dtterm -> withLog' typecheck con (A.Arrow a b) (A.Conclusion dtterm) (depth + 1) setting) [DT.Type,DT.Kind]
treeTB = zip (concatMap (replicate (length bJs)) typeArrow) (cycle bJs)
piABJs =
map
(\(tJ,bJ) ->
let
env = con
aTerm = addLam (length a) (A.termfromAJudgement $ A.downSide bJ)
aType = A.Arrow a b
in
J.T J.PiI (A.AJudgement env aTerm aType) [tJ,bJ] )
treeTB
in Right piABJs
piIntro con arrow_type depth setting = debugLog con arrow_type depth setting "piIntro2" $Right []
A.arrowSubst ( substAsInPiElim term r ) f ( A.Conclusion $ DT.Var fn )
piElim :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
piElim con b1 depth setting
| depth > (maxdepth setting) = debugLog con b1 depth setting "piElimハズレ"$ Left ("too deep @ piElim " ++ show con ++" ト "++ show b1)
| typecheckTerm setting /= Nothing =
case typecheckTerm setting of
Just aType - >
ftree = withLog ' typecheck con f fType depth setting
Just (A.Arrow_App (A.Conclusion (DT.Var fn)) x) ->
let fType = A.shiftIndices (con !! fn) (fn+1) 0in
case fType of
A.Arrow (a:r) b ->
if b == b1
then
let proofForx = withLog' typecheck con x a (depth + 1) setting
ftree = J.T J.VAR (A.AJudgement con (A.Conclusion (DT.Var fn)) fType) []
downside = A.AJudgement con (A.Arrow_App (A.Conclusion (DT.Var fn)) x) (A.arrowNotat $ A.Arrow r b)
result = map (\xtree -> J.T J.PiE downside [ftree,xtree]) proofForx
in debugLogWithTerm con (A.Arrow_App (A.Conclusion (DT.Var fn)) x) b1 depth setting "piElimtypecheck"$ Right result
else
debugLogWithTerm con (A.Arrow_App (A.Conclusion (DT.Var fn)) x) b1 depth setting "piElimtypecheck ハズレ1"$ Right []
c -> debugLogWithTerm con c b1 depth setting "piElimtypecheck ハズレ2"$ Right []
Just term-> debugLogWithTerm con term b1 depth setting "piElimtypecheck ハズレ3"$ Right []
| otherwise =
a_type_terms = deduceEnvs con aJudgements (depth+1) setting
in debugLog con b1 depth setting ("piElim1" ++ show aJudgements) $Right
$concatMap
(\(base,ass) ->
M.mapMaybe
(\as ->
let env' = con
args = map (A.termfromAJudgement . A.downSide) as
aTerms' = appAs (A.termfromAJudgement $ A.downSide base) args
a_type' = substAsInPiElim (A.typefromAJudgement $A.downSide base) $ args
in
if a_type' == b1
then
Just $ J.T J.PiE (A.AJudgement env' aTerms' a_type') [base,head as]
else
Nothing
)
(sequence ass)
)
(a_type_terms)
sigmaIntro :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
sigmaIntro con (A.Arrow_Sigma a b1) depth setting
| depth > (maxdepth setting) = debugLog con (A.Arrow_Sigma a b1) depth setting "sigmaIntro深さ"$Left ("too deep @ sigmaIntro " ++ show con ++" ト "++ show (A.Arrow_Sigma a b1))
| null $ concatMap ( \dtterm ->withLog ' ( A.Arrow_Sigma a b1 ) ( A.Conclusion dtterm ) depth setting ) [ DT.Type , DT.Kind ] = Right [ ]
| otherwise =
debugLog con (A.Arrow_Sigma a b1) depth setting "sigmaIntro1" $
let aTermJudgements' =deduceWithLog con a (depth + 1) setting
substedB b a= let base = A.genFreeCon b "base" in A.reduce $ A.arrowSubst (A.shiftIndices (A.arrowSubst b1 base (A.Conclusion $ DT.Var 0)) (-1) 0) a base
dependencyCheck = case aTermJudgements' of [] -> False ; (a:_) -> substedB b1 (A.termfromAJudgement $ A.downSide a) == A.shiftIndices b1 (-1) 0
aTermJudgements =
if dependencyCheck
then
(D.trace (L.replicate (depth+1) '\t'++"後件に影響ないから一個だけ見る" ++ (show $ map A.downSide aTermJudgements')) (take 1 $reverse aTermJudgements'))
else
(D.trace (L.replicate (depth+1) '\t'++"この辺見ていくよー" ++ (show $ map A.downSide aTermJudgements')) aTermJudgements')
typeAS = L.nub $ concatMap ( \dtterm - > withLog ' ( A.Arrow_Sigma a b1 ) ( A.Conclusion dtterm ) ( depth + 1 ) setting ) [ DT.Type , DT.Kind ]
aB1TermsJudgements =
concatMap
(\aJ ->
let b_type = D.trace (L.replicate (depth+1) '\t'++"ここ見てるよ" ++ (show aJ)) substedB b1 (A.termfromAJudgement $ A.downSide aJ)
let con2b = con
b_type = D.trace ( L.replicate ( depth+1 ) ' \t'++"ここ見てるよ " + + ( show aJ ) ) A.reduce $ A.arrowSubst ( A.shiftIndices ( A.arrowSubst b1 base ( A.Conclusion $ DT.Var 0 ) ) ( -1 ) 0 ) ( A.termfromAJudgement $ A.downSide aJ ) base
treeAB = map (\bJ -> (aJ,bJ)) (deduceWithLog con b_type (depth+2) setting)
in treeAB)
(reverse aTermJudgements)
in
Right
$ map
(\(aJ,b1J) ->
let
env = con
aTerm = A.Arrow_Pair (A.termfromAJudgement $ A.downSide aJ) (A.termfromAJudgement $ A.downSide b1J)
a_type = A.Arrow_Sigma a b1
in J.T J.SigI (A.AJudgement env aTerm a_type) [aJ,b1J])
aB1TermsJudgements
sigmaIntro con arrow_type depth setting = debugLog con arrow_type depth setting "sigmaIntroハズレ" $Right []
eqIntro :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
eqIntro con (A.Arrow_Eq t a b) depth setting
| a /= b = debugLog con (A.Arrow_Eq t a b) depth setting "eqIntro1" $ Right []
| otherwise =
debugLog con (A.Arrow_Eq t a b) depth setting "eqIntro2" $
case withLog' typecheck con a t (depth + 1) setting of
[] -> Right []
typeTree ->
Right
$map
(\dTree -> let (A.AJudgement env aTerm a_type) = A.downSide dTree in J.T J.SigE (A.AJudgement con (A.Conclusion $ DT.Con $T.pack $ "eqIntro(" ++ (show a) ++ ")("++ (show t) ++")" ) (A.Arrow_Eq t a a)) [dTree])
typeTree
eqIntro con b depth setting= debugLog con b depth setting "eqIntro3" $ Right []
eqElim :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
eqElim con target depth setting
| depth > (maxdepth setting) = debugLog con target depth setting "eqElim深さ" $Left ("too deep @ eqElim " ++ show con ++" ト "++ show target)
| not $ any (A.canBeSame 0 (A.Arrow_Eq (A.Conclusion $DT.Var 0) (A.Conclusion $DT.Var 0) (A.Conclusion $DT.Var 0)) ) con = debugLog con target depth setting "eqElimハズレ" $ Right []
| otherwise =
debugLog con target depth setting "eqElim1" $
case target of
let eqAboutDttermLst = M.catMaybes $map (\(dnum,term) -> case A.shiftIndices term (varnum - dnum) 0 of; (A.Arrow_Eq _ var1 var2) -> if var1 == (A.Conclusion $ DT.Var varnum) then Just (dnum,var2) else (if (var2 == (A.Conclusion $DT.Var varnum))then Just (dnum,var1) else Nothing) ; _ -> Nothing) (zip [(varnum-1),(varnum-2)..0] con) in
filter ( \(dnum , term ) ->case term of;A.Arrow_Eq ( A.Conclusion $ DT.Var num0 ) ( A.Conclusion $ DT.Var num1 ) _ - > True ; _ - > False ) eqlist in A.shiftIndices var1 ( -dnum ) dnum
let varLst = M.mapMaybe
(\(varid,dterm') ->
case deduceWithLog con dterm' (depth + 1) setting of
[] -> Nothing
dtermJs ->
let dtermJ = head dtermJs in
Just $ J.T J.PiE
[
(J.T J.CON(A.AJudgement con (A.Conclusion$ DT.Var varid) (A.Arrow_Eq (A.Conclusion DT.Type) target dterm')) []),
dtermJ
]
)
eqAboutDttermLst
in Right $varLst ++ sigmaLst ++ piLst
efq :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting ->Either String [J.Tree A.AJudgement]
efq con b depth setting
| depth > maxdepth setting = debugLog con b depth setting "efqハズレ1" $ Left $ "too deep @ efq " ++ show con ++" ト "++ show b
| null (withLog' typecheck con b (A.Conclusion DT.Type) (depth + 1) setting ) = debugLog con b depth setting "efqハズレ2"$ Right []
| otherwise =
if null (withLog membership con (A.Conclusion DT.Bot) depth setting)
then
case deduceWithLog con (A.Conclusion DT.Bot) (depth + 1) setting of
[] -> debugLog con b depth setting "efq1" $Right []
botJs -> debugLog con b depth setting "efq2" $
Right
$map
-(\dTree - > let ( A.AJudgement env aTerm a_type ) = A.downSide dTree in J.NotF ( A.AJudgement env ( A.Arrow_App ( A.Conclusion $ DT.Con $ T.pack " efq " ) aTerm ) b ) dTree )
botJs
else debugLog con b depth setting "efq3" $
Right
$map
(\dTree -> let (A.AJudgement env aTerm a_type) = A.downSide dTree in J.T J.SigE (A.AJudgement env (A.Arrow_App (A.Conclusion $ DT.Con $T.pack "efq") aTerm) b) [dTree])
(withLog membership con (A.Conclusion DT.Bot) depth setting)
dne :: [A.Arrowterm] -> A.Arrowterm -> Int -> Setting -> Either String [J.Tree A.AJudgement]
dne con b depth setting
| depth > maxdepth setting = debugLog con b depth setting "dne深さ" $ Left $ "too deep @ dne " ++ show con ++" ト "++ show b
| b==A.Conclusion DT.Type =debugLog con b depth setting "dneハズレ2" $ Right []
| case b of (A.Arrow [A.Arrow _ (A.Conclusion DT.Bot)] (A.Conclusion DT.Bot)) -> True ; _ -> False= debugLog con b depth setting "dne2重" $Right []
| b `elem` (map (\(num,term) -> A.shiftIndices term (length con - num) 0) (nglst setting)) = debugLog con b depth setting "dne2回め" $Right []
| null (debugLog con b depth setting "dneが使えるか確認" (withLog' typecheck con b (A.Conclusion DT.Type) (depth + 1) setting)) = debugLog con b depth setting "dneハズレ1" $Right []
| otherwise =
debugLog con b depth setting "dne1" $
case deduceWithLog con (A.Arrow [A.Arrow [b] (A.Conclusion DT.Bot)] (A.Conclusion DT.Bot)) (depth + 1) setting{nglst = ((length con,b) : nglst setting)} of
[] -> Right []
dneJs ->
Right
$map
(\dTree -> let (A.AJudgement env aTerm a_type) = A.downSide dTree in J.T J.SigE (A.AJudgement env (A.Arrow_App (A.Conclusion $ DT.Con $T.pack "dne") aTerm) b) [dTree])
dneJs
deduceWithLog :: [A.Arrowterm] -> A.Arrowterm ->Int -> Setting ->[J.Tree A.AJudgement]
deduceWithLog = withLog deduce
withLog' :: ([A.Arrowterm] -> A.Arrowterm -> A.Arrowterm ->Int -> Setting ->Either String [J.Tree A.AJudgement]) -> [A.Arrowterm] -> A.Arrowterm -> A.Arrowterm ->Int -> Setting ->[J.Tree A.AJudgement]
withLog' f con arrow_term arrow_type depth setting =
case f con arrow_term arrow_type depth setting of
Right j -> j
Left msg -> []
withLog :: ([A.Arrowterm] -> A.Arrowterm ->Int -> Setting ->Either String [J.Tree A.AJudgement]) -> [A.Arrowterm] -> A.Arrowterm ->Int -> Setting ->[J.Tree A.AJudgement]
withLog f con arrow_type depth setting =
case f con arrow_type depth setting of
D.trace ( " found : " + + ( show j ) )
D.trace " reset "
-> Setting
-> Either String [J.Tree A.AJudgement]
typecheck con arrow_term arrow_type depth setting
| depth > (maxdepth setting) = Left ("too deep @ typecheck " ++ show con ++" | "++ show arrow_type)
| falsum setting && arrow_term == A.Conclusion DT.Bot && arrow_type == A.Conclusion DT.Type = Right [J.T J.BotF (A.AJudgement con arrow_term arrow_type) []]
| arrow_type == A.Conclusion DT.Kind = if arrow_term == A.Conclusion DT.Type then Right [J.T J.CON(A.AJudgement con arrow_term arrow_type) []] else Right []
| arrow_term == A.Conclusion DT.Kind = debugLogWithTerm con arrow_term arrow_type depth setting ("kindは証明項にはならないと思う") $Right []
| otherwise =
debugLogWithTerm con arrow_term arrow_type depth setting ("typecheck : ") $
let formjudgements = concatMap (\f -> withLog' f con arrow_term arrow_type (depth+1) setting{typecheckTerm = Just arrow_term}) [piForm,sigmaForm]
judgements = foldl
(\js f ->
let js' = filter (\a ->A.termfromAJudgement (A.downSide a) == A.shiftIndices arrow_term (length (A.envfromAJudgement $ A.downSide a)- length con ) 0) js
formjudgements
([membership,eqIntro,piIntro,sigmaIntro,piElim,eqElim] ++ [dne | arrow_type /= A.Conclusion DT.Bot && mode setting == WithDNE] ++ [efq | arrow_type /= A.Conclusion DT.Bot && mode setting == WithEFQ])
concatMap ( \f - > withLog f con arrow_type depth setting ) [ membership , piIntro , piElim , sigmaIntro ]
deducejudgements = filter ( \a ->A.termfromAJudgement ( A.downSide a ) = = A.shiftIndices arrow_term ( length ( A.envfromAJudgement $ A.downSide a)- length con ) 0 ) judgements
in
debugLogWithTerm con arrow_term arrow_type depth setting ("found : ") $Right judgements
-> Setting
->Either String [J.Tree A.AJudgement]
deduce _ (A.Conclusion DT.Kind) depth setting
| depth > maxdepth setting = Left "depth @ deduce - type-ax"
| otherwise = Right [J.T J.VAR(A.AJudgement [] (A.Conclusion DT.Type) (A.Conclusion DT.Kind)) []]
deduce con arrow_type depth setting
| depth > maxdepth setting = Left ("too deep @ deduce " ++ show con ++" | "++ show arrow_type)
| otherwise =
let judgements = foldl
(\js f -> if null js then withLog f con arrow_type depth setting{typecheckTerm = Nothing} else js)
[]
([membership,eqIntro,piIntro,sigmaIntro,piElim,eqElim] ++ [dne | arrow_type /= A.Conclusion DT.Bot && mode setting == WithDNE] ++ [efq | arrow_type /= A.Conclusion DT.Bot && mode setting == WithEFQ])
in (
if null judgements
then debugLog con arrow_type depth setting "deduce failed"
else
(
if debug setting
then D.trace (L.replicate depth '\t' ++ (show depth) ++ " deduced : " ++ (show $ A.downSide $ head judgements))
else id
)
)
$Right judgements
debugLog con=
debugLogWithTerm con (A.Conclusion $ DT.Con $T.pack "?")
debugLogWithTerm con term target depth setting label answer=
if debug setting
then
D.trace
(L.replicate depth '\t' ++ (show depth) ++ " " ++ label ++ " " ++ (show $ A.AJudgement con term target)++ " ")
answer
else answer
|
5ced07485563839a5f99edebd3944bed52d8609d1c82268bb1b56d920498b155 | mgree/smoosh | test_arith.ml | open Test_prelude
open Smoosh_num
open Smoosh
open Os_symbolic
open Arith
open Printf
let string_of_token tkn : string =
match tkn with
TNum n -> "NUM " ^ (Nat_big_num.to_string n)
| TVar s -> "VAR " ^ s
| TPlus -> "PLUS"
| TMinus -> "MINUS"
| TTimes -> "TIMES"
| TDiv -> "DIV"
| TMod -> "MOD"
| TBitNot -> "BITNOT"
| TBoolNot -> "BOOLNOT"
| TLShift -> "LSHIFT"
| TRShift -> "RSHIFT"
| TLt -> "LT"
| TLte -> "LTE"
| TGt -> "GT"
| TGte -> "GTE"
| TEq -> "EQ"
| TNEq -> "NEQ"
| TBitAnd -> "BITAND"
| TBitOr -> "BITOR"
| TBitXOr -> "BITXOR"
| TBoolAnd -> "BOOLAND"
| TBoolOr -> "BOOLOR"
| TQuestion -> "Q"
| TColon -> "COLON"
| TVarEq -> "VEQ"
| TVarPlusEq -> "VPEQ"
| TVarMinusEq -> "VMEQ"
| TVarTimesEq -> "VTEQ"
| TVarDivEq -> "VDEQ"
| TVarModEq -> "VMEQ"
| TVarLShiftEq -> "VLShiftEQ"
| TVarRShiftEq -> "VRShiftEQ"
| TVarBitAndEq -> "VBANDEQ"
| TVarBitOrEq -> "VBOREQ"
| TVarBitXOrEq -> "VBXOREQ"
| TLParen -> "LP"
| TRParen -> "RP"
let rec token_list_to_string = function
[] -> ""
| [t] -> string_of_token t
| t::ts -> (string_of_token t) ^ " " ^ (token_list_to_string ts)
TODO 2018 - 08 - 10 fixme
let check_lexer (name, input, expected_out) =
checker
lexer_integer
(Either.eitherEqualBy (=) (Lem_list.listEqualBy eq_token_integer))
(name, Xstring.explode input, expected_out)
let check_parser =
checker
(either_monad parse_arith_exp)
(Either.eitherEqualBy (=) eq_arith_integer)
let eval_equals out expected =
match (out, expected) with
| (Either.Right (s1, n1), Either.Right (s2, n2)) -> n1 = n2 && (Pmap.equal (=) s1.sh.env s2.sh.env)
| (Either.Left e1, Either.Left e2) -> e1 = e2
| _ -> false
let check_eval_big_num (name, state, input, expected_out) =
checker (symbolic_arith_big_num state) eval_equals (name, List.map (fun c -> Smoosh.C c) (Xstring.explode input),
either_monad (fun (st, n) -> Right (st, integerToFields n)) expected_out)
let check_eval_int32 (name, state, input, expected_out) =
checker (symbolic_arith32 state) eval_equals (name, List.map (fun c -> Smoosh.C c) (Xstring.explode input),
either_monad (fun (st, n) -> Right (st, int32ToFields n)) expected_out)
let check_eval_int64 (name, state, input, expected_out) =
checker (symbolic_arith64 state) eval_equals (name, List.map (fun c -> Smoosh.C c) (Xstring.explode input),
either_monad (fun (st, n) -> Right (st, int64ToFields n)) expected_out)
let lexer_tests:(string*string*(string, (Nat_big_num.num arith_token)list)Either.either)list=
([
("number 5", "5", Right [TNum (Nat_big_num.of_int 5)]);
("number 1234567890", "1234567890", Right [TNum (Nat_big_num.of_int 1234567890)]);
("octal 0755", "0755", Right [TNum (Nat_big_num.of_int 493)]);
("hex 0xFf", "0xFf", Right [TNum (Nat_big_num.of_int 255)]);
("large number 9223372036854775808", "9223372036854775808", Right [TNum (Nat_big_num.pow_int (Nat_big_num.of_int 2) 63)]);
("var x", "x", Right [TVar "x"]);
("var LongVarWithCaps", "LongVarWithCaps", Right [TVar "LongVarWithCaps"]);
(* Arithmetic ops *)
("Plus operator", "+", Right [TPlus]);
("Minus operator", "-", Right [TMinus]);
("Times operator", "*", Right [TTimes]);
("Div operator", "/", Right [TDiv]);
("Mod operator", "%", Right [TMod]);
("Bitwise negation operator", "~", Right [TBitNot]);
("Logical not operator", "!", Right [TBoolNot]);
("Bitwise left shift operator", "<<", Right [TLShift]);
("Bitwise right shift operator", ">>", Right [TRShift]);
Comparison ops
("Less than comparison operator", "<", Right [TLt]);
("Less than or equal comparison operator", "<=", Right [TLte]);
("Greater than comparison operator", ">", Right [TGt]);
("Greater than or equal comparison operator", ">=", Right [TGte]);
("Equal to comparison operator", "==", Right [TEq]);
("Not equal to comparison operator", "!=", Right [TNEq]);
("Bitwise and operator", "&", Right [TBitAnd]);
("Bitwise or operator", "|", Right [TBitOr]);
("Bitwise xor operator", "^", Right [TBitXOr]);
("Logical and operator", "&&", Right [TBoolAnd]);
("Logical or operator", "||", Right [TBoolOr]);
("", "? :", Right [TQuestion; TColon]);
(* Assignment operators *)
("Assignment var equals operator", "=", Right [TVarEq]);
("Assignment var plus equals operator", "+=", Right [TVarPlusEq]);
("Assignment var minus equals operator", "-=", Right [TVarMinusEq]);
("Assignment var times equals operator", "*=", Right [TVarTimesEq]);
("Assignment var div equals operator", "/=", Right [TVarDivEq]);
("Assignment var mod equals operator", "%=", Right [TVarModEq]);
("Assignment var lshift equals operator", "<<=", Right [TVarLShiftEq]);
("Assignment var rshift equals operator", ">>=", Right [TVarRShiftEq]);
("Assignment var bitwise and equals operator", "&=", Right [TVarBitAndEq]);
("Assignment var bitwise or equals operator", "|=", Right [TVarBitOrEq]);
("Assignment var bitwise xor equals operator", "^=", Right [TVarBitXOrEq]);
("Left parenthesis", "(", Right [TLParen]);
("Right parenthesis", ")", Right [TRParen]);
])
let lex_string str = lexer_integer (Xstring.explode str)
let num n = Num (Nat_big_num.of_int n)
let parser_tests:(string*(string,(Nat_big_num.num arith_token)list)Either.either*(string, Nat_big_num.num arith_exp)Either.either)list=
([
("single number", lex_string "13", Right(Num (Nat_big_num. of_int 13)));
("two number additon 2 + 3", lex_string "2 + 3", Right(BinOp (Plus, num 2, num 3)));
("two number subtraction 17 - 6", lex_string "17 - 6", Right(BinOp (Minus, num 17, num 6)));
("two number multiplication 4 * 8", lex_string "4 * 8", Right(BinOp (Times, num 4, num 8)));
("two number division 9 / 3", lex_string "9 / 3", Right(BinOp (Div, num 9, num 3)));
("two number mod 5 % 2", lex_string "5 % 2", Right(BinOp (Mod, num 5, num 2)));
("multiplication binds tighter than addition", lex_string "3+5*9", Right(BinOp (Plus, num 3, (BinOp (Times, num 5, num 9)))));
("division binds tighter than subtraction", lex_string "19-6 / 2", Right(BinOp (Minus, num 19, BinOp (Div, num 6, num 2))));
("single - parses as negation", lex_string "1 - -5", Right(BinOp (Minus, num 1, Neg(num 5))));
("Bitwise not on number", lex_string "~16 + 279", Right(BinOp (Plus, BitNot(num 16), num 279)));
("Bitwise not on expression", lex_string "~(16 - 279)", Right(BitNot (BinOp (Minus, num 16, num 279))));
("Logical not on number", lex_string "!47 / 4", Right(BinOp (Div, BoolNot(num 47), num 4)));
("Logical not on expression", lex_string "!(47 * 4)", Right(BoolNot (BinOp (Times, num 47, num 4))));
("Bitwise shift on numbers", lex_string "4 << 2 >> 32", Right(BinOp (RShift, BinOp (LShift, num 4, num 2), num 32)));
("Bitwise shift precedence", lex_string "3*2 << 2 + 4", Right((BinOp (LShift, BinOp (Times, num 3, num 2), BinOp (Plus, num 2, num 4)))));
("Simple assignment with variables", lex_string "x=x+1", Right(AssignVar ("x", None, BinOp (Plus, Var "x", num 1))));
])
let = Int64.of_int Nat_big_num.of_int
let eval_tests ofNumLiteral mul : (string * symbolic os_state * string * (string, symbolic os_state * 'a )Either.either)list=
[
("bare number", os_empty, "47", Right (os_empty, ofNumLiteral 47));
("addition two numbers", os_empty, "23 + 24", Right (os_empty, ofNumLiteral 47));
("addition three numbers", os_empty, "15 + 15 + 17", Right (os_empty, ofNumLiteral 47));
("addition three numbers parens left", os_empty, "(15 + 15) + 17", Right (os_empty, ofNumLiteral 47));
("addition three numbers parens right", os_empty, "15 + (15 + 17)", Right (os_empty, ofNumLiteral 47));
("subtraction two numbers", os_empty, "53 - 6", Right (os_empty, ofNumLiteral 47));
("subtraction three numbers", os_empty, "47 - 15 - 17", Right (os_empty, ofNumLiteral 15));
("subtraction three numbers parens left", os_empty, "(47 - 15) - 17", Right (os_empty, ofNumLiteral 15));
("subtraction three numbers parens right", os_empty, "47 - (15 - 17)", Right (os_empty, ofNumLiteral 49));
("multiplication two numbers", os_empty, "3 * 7", Right (os_empty, ofNumLiteral 21));
("multiplication three numbers", os_empty, "2 * 3 * 4", Right (os_empty, ofNumLiteral 24));
("multiplication three numbers parens left", os_empty, "(2 * 3) * 4", Right (os_empty, ofNumLiteral 24));
("multiplication three numbers parens right", os_empty, "2 * (3 * 4)", Right (os_empty, ofNumLiteral 24));
("division two numbers", os_empty, "10 / 2", Right (os_empty, ofNumLiteral 5));
("division three numbers", os_empty, "12 / 3 / 2", Right (os_empty, ofNumLiteral 2));
("division three numbers parens left", os_empty, "(12 / 3) / 2", Right (os_empty, ofNumLiteral 2));
("division three numbers parens right", os_empty, "12 / (3 / 2)", Right (os_empty, ofNumLiteral 12));
("modulo two numbers", os_empty, "10 % 2", Right (os_empty, ofNumLiteral 0));
("modulo three numbers", os_empty, "12 % 3 % 2", Right (os_empty, ofNumLiteral 0));
("modulo three numbers parens left", os_empty, "(12 % 3) % 2", Right (os_empty, ofNumLiteral 0));
("modulo three numbers parens right", os_empty, "12 % (3 % 2)", Right (os_empty, ofNumLiteral 0));
("left shift two numbers", os_empty, "10 << 2", Right (os_empty, ofNumLiteral 40));
("left shift three numbers", os_empty, "12 << 3 << 2", Right (os_empty, ofNumLiteral 384));
("left shift three numbers parens left", os_empty, "(12 << 3) << 2", Right (os_empty, ofNumLiteral 384));
("left shift three numbers parens right", os_empty, "12 << (3 << 2)", Right (os_empty, ofNumLiteral 49152));
("right shift two numbers", os_empty, "10 >> 2", Right (os_empty, ofNumLiteral 2));
("right shift three numbers", os_empty, "200 >> 3 >> 2", Right (os_empty, ofNumLiteral 6));
("right shift three numbers parens left", os_empty, "(200 >> 3) >> 2", Right (os_empty, ofNumLiteral 6));
("right shift three numbers parens right", os_empty, "12 >> (3 >> 2)", Right (os_empty, ofNumLiteral 12));
("bitwise and two numbers", os_empty, "10 & 7", Right (os_empty, ofNumLiteral 2));
("bitwise or two numbers", os_empty, "10 | 7", Right (os_empty, ofNumLiteral 15));
("bitwise and/or three numbers", os_empty, "23 & 7 | 8", Right (os_empty, ofNumLiteral 15));
("bitwise and/or three numbers parens left", os_empty, "(23 & 7) | 8", Right (os_empty, ofNumLiteral 15));
("bitwise and/or three numbers parens right", os_empty, "23 & (7 | 8)", Right (os_empty, ofNumLiteral 7));
("bitwise or/and three numbers", os_empty, "4 | 19 & 11", Right (os_empty, ofNumLiteral 7));
("bitwise or/and three numbers parens left", os_empty, "(4 | 19) & 11", Right (os_empty, ofNumLiteral 3));
("bitwise or/and three numbers parens right", os_empty, "4 | (19 & 11)", Right (os_empty, ofNumLiteral 7));
("bitwise xor two numbers", os_empty, "10 ^ 7", Right (os_empty, ofNumLiteral 13));
("bitwise xor three numbers", os_empty, "12 ^ 9 ^ 8", Right (os_empty, ofNumLiteral 13));
("bitwise xor three numbers parens left", os_empty, "(12 ^ 9) ^ 8", Right (os_empty, ofNumLiteral 13));
("bitwise xor three numbers parens right", os_empty, "12 ^ (9 ^ 8)", Right (os_empty, ofNumLiteral 13));
("divide by zero ", os_empty, "47 / 0", Left "arithmetic parse error on 47 / 0: Divide by zero");
("conditional true", os_empty, "18 ? 47 : 42", Right (os_empty, ofNumLiteral 47));
("conditional false", os_empty, "0 ? 47 : 42", Right (os_empty, ofNumLiteral 42));
("bitwise negation", os_empty, "~(-48)", Right (os_empty, ofNumLiteral 47));
("boolean not", os_empty, "!47", Right (os_empty, ofNumLiteral 0));
("boolean not", os_empty, "!0", Right (os_empty, ofNumLiteral 1));
("assign x to 5", os_empty, "x=5", Right (os_var_x_five, ofNumLiteral 5));
("x plus equals 2, x is set to 5", os_var_x_five, "x+=2", Right (add_literal_env_string "x" "7" os_empty, ofNumLiteral 7));
("x minus equals 2, x is set to 5", os_var_x_five, "x-=2", Right (add_literal_env_string "x" "3" os_empty, ofNumLiteral 3));
("x times equals 2, x is set to 5", os_var_x_five, "x*=2", Right (add_literal_env_string "x" "10" os_empty, ofNumLiteral 10));
("x div equals 2, x is set to 5", os_var_x_five, "x/=2", Right (add_literal_env_string "x" "2" os_empty, ofNumLiteral 2));
("x mod equals 2, x is set to 5", os_var_x_five, "x%=2", Right (add_literal_env_string "x" "1" os_empty, ofNumLiteral 1));
("x lshift equals 2, x is set to 5", os_var_x_five, "x<<=2", Right (add_literal_env_string "x" "20" os_empty, ofNumLiteral 20));
("x rshift equals 2, x is set to 5", os_var_x_five, "x>>=2", Right (add_literal_env_string "x" "1" os_empty, ofNumLiteral 1));
("x & equals 2, x is set to 5", os_var_x_five, "x&=2", Right (add_literal_env_string "x" "0" os_empty, ofNumLiteral 0));
("x | equals 2, x is set to 5", os_var_x_five, "x|=2", Right (add_literal_env_string "x" "7" os_empty, ofNumLiteral 7));
("x ^ equals 2, x is set to 5", os_var_x_five, "x^=2", Right (add_literal_env_string "x" "7" os_empty, ofNumLiteral 7));
("x = x + 1, x is unset", os_empty, "x=x+1", Right (add_literal_env_string "x" "1" os_empty, ofNumLiteral 1));
]
let eval_bignum_tests ofNumLiteral mul : (string * symbolic os_state * string * (string, symbolic os_state * Nat_big_num.num)Either.either)list =
[
("large number 9223372036854775808", os_empty, "9223372036854775808", Right (os_empty, mul (mul (ofNumLiteral 65536) (ofNumLiteral 65536)) (mul (ofNumLiteral 65536) (ofNumLiteral 32768))));
("large hex number 0x8000000000000000", os_empty, "0x8000000000000000", Right (os_empty, mul (mul (ofNumLiteral 65536) (ofNumLiteral 65536)) (mul (ofNumLiteral 65536) (ofNumLiteral 32768))));
("large oct number 01000000000000000000000", os_empty, "01000000000000000000000", Right (os_empty, mul (mul (ofNumLiteral 65536) (ofNumLiteral 65536)) (mul (ofNumLiteral 65536) (ofNumLiteral 32768))));
]
let eval_int64_tests ofNumLiteral mul : (string * symbolic os_state * string * (string, symbolic os_state * Int64.t)Either.either)list =
[
("large number 9223372036854775808", os_empty, "9223372036854775808", Right (os_empty, int64Max));
("large hex number 0x8000000000000000", os_empty, "0x8000000000000000", Right (os_empty, int64Max));
("large oct number 01000000000000000000000", os_empty, "01000000000000000000000", Right (os_empty, int64Max));
("arithmetic overflow", os_empty, "1073741824 * 1073741824 * 8", Right (os_empty, int64Min));
("left shift by negative", os_empty, "15 << -63", Right (os_empty, ofNumLiteral 30));
("right shift by negative", os_empty, "15 >> -63", Right (os_empty, ofNumLiteral 7));
("right shift uses arithmetic shift", os_empty, "(15 << -1) >> 1", Right (os_empty, Int64.div int64Min (ofNumLiteral 2)));
("x minus equals 7 return -2 when x is set to 5", os_var_x_five, "x-=7", Right (add_literal_env_string "x" "-2" os_empty, Int64.neg (ofNumLiteral 2)));
]
let eval_int32_tests ofNumLiteral mul : (string * symbolic os_state * string * (string, symbolic os_state * Int32.t)Either.either)list =
[
("large number 9223372036854775808", os_empty, "9223372036854775808", Right (os_empty, int32Max));
("large hex number 0x8000000000000000", os_empty, "0x8000000000000000", Right (os_empty, int32Max));
("large oct number 020000000000", os_empty, "020000000000", Right (os_empty, int32Max));
("large oct number 07777777777777777777777", os_empty, "07777777777777777777777", Right (os_empty, int32Max));
("arithmetic overflow", os_empty, "2147483647 + 1", Right (os_empty, int32Min));
("left shift by negative", os_empty, "15 << -31", Right (os_empty, ofNumLiteral 30));
("right shift by negative", os_empty, "15 >> -31", Right (os_empty, ofNumLiteral 7));
("right shift uses arithmetic shift", os_empty, "(15 << -1) >> 1", Right (os_empty, Int32.div int32Min (ofNumLiteral 2)));
]
(***********************************************************************)
(* DRIVER **************************************************************)
(***********************************************************************)
let run_tests () =
let failed = ref 0 in
let test_count = ref 0 in
let prnt = fun (s, n) -> ("<| " ^ (printable_shell_env s) ^ "; " ^ (string_of_fields n) ^ " |>") in
print_endline "\n=== Running arithmetic tests...";
Lexer tests
test_part "Lexer" check_lexer (Either.either_case id token_list_to_string) lexer_tests test_count failed;
Parser tests
test_part "Parser" check_parser (Either.either_case id string_of_aexp) parser_tests test_count failed;
(* General eval tests *)
test_part "General eval Nat_big_num" check_eval_big_num (Either.either_case id prnt) (eval_tests Nat_big_num.of_int Nat_big_num.mul) test_count failed;
test_part "General eval int32" check_eval_int32 (Either.either_case id prnt) (eval_tests Int32.of_int Int32.mul) test_count failed;
test_part "General eval int64" check_eval_int64 (Either.either_case id prnt) (eval_tests Int64.of_int Int64.mul) test_count failed;
(* Type specific eval tests *)
test_part "Eval Nat_big_num" check_eval_big_num (Either.either_case id prnt) (eval_bignum_tests Nat_big_num.of_int Nat_big_num.mul) test_count failed;
test_part "Eval int32" check_eval_int32 (Either.either_case id prnt) (eval_int32_tests Int32.of_int Int32.mul) test_count failed;
test_part "Eval int64" check_eval_int64 (Either.either_case id prnt) (eval_int64_tests Int64.of_int Int64.mul) test_count failed;
printf "=== ...ran %d arithmetic tests with %d failures.\n\n" !test_count !failed;
!failed = 0
| null | https://raw.githubusercontent.com/mgree/smoosh/84b1ff86f59573a2e4fd7e23edfa0cf9fdb45db9/src/test_arith.ml | ocaml | Arithmetic ops
Assignment operators
*********************************************************************
DRIVER *************************************************************
*********************************************************************
General eval tests
Type specific eval tests | open Test_prelude
open Smoosh_num
open Smoosh
open Os_symbolic
open Arith
open Printf
let string_of_token tkn : string =
match tkn with
TNum n -> "NUM " ^ (Nat_big_num.to_string n)
| TVar s -> "VAR " ^ s
| TPlus -> "PLUS"
| TMinus -> "MINUS"
| TTimes -> "TIMES"
| TDiv -> "DIV"
| TMod -> "MOD"
| TBitNot -> "BITNOT"
| TBoolNot -> "BOOLNOT"
| TLShift -> "LSHIFT"
| TRShift -> "RSHIFT"
| TLt -> "LT"
| TLte -> "LTE"
| TGt -> "GT"
| TGte -> "GTE"
| TEq -> "EQ"
| TNEq -> "NEQ"
| TBitAnd -> "BITAND"
| TBitOr -> "BITOR"
| TBitXOr -> "BITXOR"
| TBoolAnd -> "BOOLAND"
| TBoolOr -> "BOOLOR"
| TQuestion -> "Q"
| TColon -> "COLON"
| TVarEq -> "VEQ"
| TVarPlusEq -> "VPEQ"
| TVarMinusEq -> "VMEQ"
| TVarTimesEq -> "VTEQ"
| TVarDivEq -> "VDEQ"
| TVarModEq -> "VMEQ"
| TVarLShiftEq -> "VLShiftEQ"
| TVarRShiftEq -> "VRShiftEQ"
| TVarBitAndEq -> "VBANDEQ"
| TVarBitOrEq -> "VBOREQ"
| TVarBitXOrEq -> "VBXOREQ"
| TLParen -> "LP"
| TRParen -> "RP"
let rec token_list_to_string = function
[] -> ""
| [t] -> string_of_token t
| t::ts -> (string_of_token t) ^ " " ^ (token_list_to_string ts)
TODO 2018 - 08 - 10 fixme
let check_lexer (name, input, expected_out) =
checker
lexer_integer
(Either.eitherEqualBy (=) (Lem_list.listEqualBy eq_token_integer))
(name, Xstring.explode input, expected_out)
let check_parser =
checker
(either_monad parse_arith_exp)
(Either.eitherEqualBy (=) eq_arith_integer)
let eval_equals out expected =
match (out, expected) with
| (Either.Right (s1, n1), Either.Right (s2, n2)) -> n1 = n2 && (Pmap.equal (=) s1.sh.env s2.sh.env)
| (Either.Left e1, Either.Left e2) -> e1 = e2
| _ -> false
let check_eval_big_num (name, state, input, expected_out) =
checker (symbolic_arith_big_num state) eval_equals (name, List.map (fun c -> Smoosh.C c) (Xstring.explode input),
either_monad (fun (st, n) -> Right (st, integerToFields n)) expected_out)
let check_eval_int32 (name, state, input, expected_out) =
checker (symbolic_arith32 state) eval_equals (name, List.map (fun c -> Smoosh.C c) (Xstring.explode input),
either_monad (fun (st, n) -> Right (st, int32ToFields n)) expected_out)
let check_eval_int64 (name, state, input, expected_out) =
checker (symbolic_arith64 state) eval_equals (name, List.map (fun c -> Smoosh.C c) (Xstring.explode input),
either_monad (fun (st, n) -> Right (st, int64ToFields n)) expected_out)
let lexer_tests:(string*string*(string, (Nat_big_num.num arith_token)list)Either.either)list=
([
("number 5", "5", Right [TNum (Nat_big_num.of_int 5)]);
("number 1234567890", "1234567890", Right [TNum (Nat_big_num.of_int 1234567890)]);
("octal 0755", "0755", Right [TNum (Nat_big_num.of_int 493)]);
("hex 0xFf", "0xFf", Right [TNum (Nat_big_num.of_int 255)]);
("large number 9223372036854775808", "9223372036854775808", Right [TNum (Nat_big_num.pow_int (Nat_big_num.of_int 2) 63)]);
("var x", "x", Right [TVar "x"]);
("var LongVarWithCaps", "LongVarWithCaps", Right [TVar "LongVarWithCaps"]);
("Plus operator", "+", Right [TPlus]);
("Minus operator", "-", Right [TMinus]);
("Times operator", "*", Right [TTimes]);
("Div operator", "/", Right [TDiv]);
("Mod operator", "%", Right [TMod]);
("Bitwise negation operator", "~", Right [TBitNot]);
("Logical not operator", "!", Right [TBoolNot]);
("Bitwise left shift operator", "<<", Right [TLShift]);
("Bitwise right shift operator", ">>", Right [TRShift]);
Comparison ops
("Less than comparison operator", "<", Right [TLt]);
("Less than or equal comparison operator", "<=", Right [TLte]);
("Greater than comparison operator", ">", Right [TGt]);
("Greater than or equal comparison operator", ">=", Right [TGte]);
("Equal to comparison operator", "==", Right [TEq]);
("Not equal to comparison operator", "!=", Right [TNEq]);
("Bitwise and operator", "&", Right [TBitAnd]);
("Bitwise or operator", "|", Right [TBitOr]);
("Bitwise xor operator", "^", Right [TBitXOr]);
("Logical and operator", "&&", Right [TBoolAnd]);
("Logical or operator", "||", Right [TBoolOr]);
("", "? :", Right [TQuestion; TColon]);
("Assignment var equals operator", "=", Right [TVarEq]);
("Assignment var plus equals operator", "+=", Right [TVarPlusEq]);
("Assignment var minus equals operator", "-=", Right [TVarMinusEq]);
("Assignment var times equals operator", "*=", Right [TVarTimesEq]);
("Assignment var div equals operator", "/=", Right [TVarDivEq]);
("Assignment var mod equals operator", "%=", Right [TVarModEq]);
("Assignment var lshift equals operator", "<<=", Right [TVarLShiftEq]);
("Assignment var rshift equals operator", ">>=", Right [TVarRShiftEq]);
("Assignment var bitwise and equals operator", "&=", Right [TVarBitAndEq]);
("Assignment var bitwise or equals operator", "|=", Right [TVarBitOrEq]);
("Assignment var bitwise xor equals operator", "^=", Right [TVarBitXOrEq]);
("Left parenthesis", "(", Right [TLParen]);
("Right parenthesis", ")", Right [TRParen]);
])
let lex_string str = lexer_integer (Xstring.explode str)
let num n = Num (Nat_big_num.of_int n)
let parser_tests:(string*(string,(Nat_big_num.num arith_token)list)Either.either*(string, Nat_big_num.num arith_exp)Either.either)list=
([
("single number", lex_string "13", Right(Num (Nat_big_num. of_int 13)));
("two number additon 2 + 3", lex_string "2 + 3", Right(BinOp (Plus, num 2, num 3)));
("two number subtraction 17 - 6", lex_string "17 - 6", Right(BinOp (Minus, num 17, num 6)));
("two number multiplication 4 * 8", lex_string "4 * 8", Right(BinOp (Times, num 4, num 8)));
("two number division 9 / 3", lex_string "9 / 3", Right(BinOp (Div, num 9, num 3)));
("two number mod 5 % 2", lex_string "5 % 2", Right(BinOp (Mod, num 5, num 2)));
("multiplication binds tighter than addition", lex_string "3+5*9", Right(BinOp (Plus, num 3, (BinOp (Times, num 5, num 9)))));
("division binds tighter than subtraction", lex_string "19-6 / 2", Right(BinOp (Minus, num 19, BinOp (Div, num 6, num 2))));
("single - parses as negation", lex_string "1 - -5", Right(BinOp (Minus, num 1, Neg(num 5))));
("Bitwise not on number", lex_string "~16 + 279", Right(BinOp (Plus, BitNot(num 16), num 279)));
("Bitwise not on expression", lex_string "~(16 - 279)", Right(BitNot (BinOp (Minus, num 16, num 279))));
("Logical not on number", lex_string "!47 / 4", Right(BinOp (Div, BoolNot(num 47), num 4)));
("Logical not on expression", lex_string "!(47 * 4)", Right(BoolNot (BinOp (Times, num 47, num 4))));
("Bitwise shift on numbers", lex_string "4 << 2 >> 32", Right(BinOp (RShift, BinOp (LShift, num 4, num 2), num 32)));
("Bitwise shift precedence", lex_string "3*2 << 2 + 4", Right((BinOp (LShift, BinOp (Times, num 3, num 2), BinOp (Plus, num 2, num 4)))));
("Simple assignment with variables", lex_string "x=x+1", Right(AssignVar ("x", None, BinOp (Plus, Var "x", num 1))));
])
let = Int64.of_int Nat_big_num.of_int
let eval_tests ofNumLiteral mul : (string * symbolic os_state * string * (string, symbolic os_state * 'a )Either.either)list=
[
("bare number", os_empty, "47", Right (os_empty, ofNumLiteral 47));
("addition two numbers", os_empty, "23 + 24", Right (os_empty, ofNumLiteral 47));
("addition three numbers", os_empty, "15 + 15 + 17", Right (os_empty, ofNumLiteral 47));
("addition three numbers parens left", os_empty, "(15 + 15) + 17", Right (os_empty, ofNumLiteral 47));
("addition three numbers parens right", os_empty, "15 + (15 + 17)", Right (os_empty, ofNumLiteral 47));
("subtraction two numbers", os_empty, "53 - 6", Right (os_empty, ofNumLiteral 47));
("subtraction three numbers", os_empty, "47 - 15 - 17", Right (os_empty, ofNumLiteral 15));
("subtraction three numbers parens left", os_empty, "(47 - 15) - 17", Right (os_empty, ofNumLiteral 15));
("subtraction three numbers parens right", os_empty, "47 - (15 - 17)", Right (os_empty, ofNumLiteral 49));
("multiplication two numbers", os_empty, "3 * 7", Right (os_empty, ofNumLiteral 21));
("multiplication three numbers", os_empty, "2 * 3 * 4", Right (os_empty, ofNumLiteral 24));
("multiplication three numbers parens left", os_empty, "(2 * 3) * 4", Right (os_empty, ofNumLiteral 24));
("multiplication three numbers parens right", os_empty, "2 * (3 * 4)", Right (os_empty, ofNumLiteral 24));
("division two numbers", os_empty, "10 / 2", Right (os_empty, ofNumLiteral 5));
("division three numbers", os_empty, "12 / 3 / 2", Right (os_empty, ofNumLiteral 2));
("division three numbers parens left", os_empty, "(12 / 3) / 2", Right (os_empty, ofNumLiteral 2));
("division three numbers parens right", os_empty, "12 / (3 / 2)", Right (os_empty, ofNumLiteral 12));
("modulo two numbers", os_empty, "10 % 2", Right (os_empty, ofNumLiteral 0));
("modulo three numbers", os_empty, "12 % 3 % 2", Right (os_empty, ofNumLiteral 0));
("modulo three numbers parens left", os_empty, "(12 % 3) % 2", Right (os_empty, ofNumLiteral 0));
("modulo three numbers parens right", os_empty, "12 % (3 % 2)", Right (os_empty, ofNumLiteral 0));
("left shift two numbers", os_empty, "10 << 2", Right (os_empty, ofNumLiteral 40));
("left shift three numbers", os_empty, "12 << 3 << 2", Right (os_empty, ofNumLiteral 384));
("left shift three numbers parens left", os_empty, "(12 << 3) << 2", Right (os_empty, ofNumLiteral 384));
("left shift three numbers parens right", os_empty, "12 << (3 << 2)", Right (os_empty, ofNumLiteral 49152));
("right shift two numbers", os_empty, "10 >> 2", Right (os_empty, ofNumLiteral 2));
("right shift three numbers", os_empty, "200 >> 3 >> 2", Right (os_empty, ofNumLiteral 6));
("right shift three numbers parens left", os_empty, "(200 >> 3) >> 2", Right (os_empty, ofNumLiteral 6));
("right shift three numbers parens right", os_empty, "12 >> (3 >> 2)", Right (os_empty, ofNumLiteral 12));
("bitwise and two numbers", os_empty, "10 & 7", Right (os_empty, ofNumLiteral 2));
("bitwise or two numbers", os_empty, "10 | 7", Right (os_empty, ofNumLiteral 15));
("bitwise and/or three numbers", os_empty, "23 & 7 | 8", Right (os_empty, ofNumLiteral 15));
("bitwise and/or three numbers parens left", os_empty, "(23 & 7) | 8", Right (os_empty, ofNumLiteral 15));
("bitwise and/or three numbers parens right", os_empty, "23 & (7 | 8)", Right (os_empty, ofNumLiteral 7));
("bitwise or/and three numbers", os_empty, "4 | 19 & 11", Right (os_empty, ofNumLiteral 7));
("bitwise or/and three numbers parens left", os_empty, "(4 | 19) & 11", Right (os_empty, ofNumLiteral 3));
("bitwise or/and three numbers parens right", os_empty, "4 | (19 & 11)", Right (os_empty, ofNumLiteral 7));
("bitwise xor two numbers", os_empty, "10 ^ 7", Right (os_empty, ofNumLiteral 13));
("bitwise xor three numbers", os_empty, "12 ^ 9 ^ 8", Right (os_empty, ofNumLiteral 13));
("bitwise xor three numbers parens left", os_empty, "(12 ^ 9) ^ 8", Right (os_empty, ofNumLiteral 13));
("bitwise xor three numbers parens right", os_empty, "12 ^ (9 ^ 8)", Right (os_empty, ofNumLiteral 13));
("divide by zero ", os_empty, "47 / 0", Left "arithmetic parse error on 47 / 0: Divide by zero");
("conditional true", os_empty, "18 ? 47 : 42", Right (os_empty, ofNumLiteral 47));
("conditional false", os_empty, "0 ? 47 : 42", Right (os_empty, ofNumLiteral 42));
("bitwise negation", os_empty, "~(-48)", Right (os_empty, ofNumLiteral 47));
("boolean not", os_empty, "!47", Right (os_empty, ofNumLiteral 0));
("boolean not", os_empty, "!0", Right (os_empty, ofNumLiteral 1));
("assign x to 5", os_empty, "x=5", Right (os_var_x_five, ofNumLiteral 5));
("x plus equals 2, x is set to 5", os_var_x_five, "x+=2", Right (add_literal_env_string "x" "7" os_empty, ofNumLiteral 7));
("x minus equals 2, x is set to 5", os_var_x_five, "x-=2", Right (add_literal_env_string "x" "3" os_empty, ofNumLiteral 3));
("x times equals 2, x is set to 5", os_var_x_five, "x*=2", Right (add_literal_env_string "x" "10" os_empty, ofNumLiteral 10));
("x div equals 2, x is set to 5", os_var_x_five, "x/=2", Right (add_literal_env_string "x" "2" os_empty, ofNumLiteral 2));
("x mod equals 2, x is set to 5", os_var_x_five, "x%=2", Right (add_literal_env_string "x" "1" os_empty, ofNumLiteral 1));
("x lshift equals 2, x is set to 5", os_var_x_five, "x<<=2", Right (add_literal_env_string "x" "20" os_empty, ofNumLiteral 20));
("x rshift equals 2, x is set to 5", os_var_x_five, "x>>=2", Right (add_literal_env_string "x" "1" os_empty, ofNumLiteral 1));
("x & equals 2, x is set to 5", os_var_x_five, "x&=2", Right (add_literal_env_string "x" "0" os_empty, ofNumLiteral 0));
("x | equals 2, x is set to 5", os_var_x_five, "x|=2", Right (add_literal_env_string "x" "7" os_empty, ofNumLiteral 7));
("x ^ equals 2, x is set to 5", os_var_x_five, "x^=2", Right (add_literal_env_string "x" "7" os_empty, ofNumLiteral 7));
("x = x + 1, x is unset", os_empty, "x=x+1", Right (add_literal_env_string "x" "1" os_empty, ofNumLiteral 1));
]
let eval_bignum_tests ofNumLiteral mul : (string * symbolic os_state * string * (string, symbolic os_state * Nat_big_num.num)Either.either)list =
[
("large number 9223372036854775808", os_empty, "9223372036854775808", Right (os_empty, mul (mul (ofNumLiteral 65536) (ofNumLiteral 65536)) (mul (ofNumLiteral 65536) (ofNumLiteral 32768))));
("large hex number 0x8000000000000000", os_empty, "0x8000000000000000", Right (os_empty, mul (mul (ofNumLiteral 65536) (ofNumLiteral 65536)) (mul (ofNumLiteral 65536) (ofNumLiteral 32768))));
("large oct number 01000000000000000000000", os_empty, "01000000000000000000000", Right (os_empty, mul (mul (ofNumLiteral 65536) (ofNumLiteral 65536)) (mul (ofNumLiteral 65536) (ofNumLiteral 32768))));
]
let eval_int64_tests ofNumLiteral mul : (string * symbolic os_state * string * (string, symbolic os_state * Int64.t)Either.either)list =
[
("large number 9223372036854775808", os_empty, "9223372036854775808", Right (os_empty, int64Max));
("large hex number 0x8000000000000000", os_empty, "0x8000000000000000", Right (os_empty, int64Max));
("large oct number 01000000000000000000000", os_empty, "01000000000000000000000", Right (os_empty, int64Max));
("arithmetic overflow", os_empty, "1073741824 * 1073741824 * 8", Right (os_empty, int64Min));
("left shift by negative", os_empty, "15 << -63", Right (os_empty, ofNumLiteral 30));
("right shift by negative", os_empty, "15 >> -63", Right (os_empty, ofNumLiteral 7));
("right shift uses arithmetic shift", os_empty, "(15 << -1) >> 1", Right (os_empty, Int64.div int64Min (ofNumLiteral 2)));
("x minus equals 7 return -2 when x is set to 5", os_var_x_five, "x-=7", Right (add_literal_env_string "x" "-2" os_empty, Int64.neg (ofNumLiteral 2)));
]
let eval_int32_tests ofNumLiteral mul : (string * symbolic os_state * string * (string, symbolic os_state * Int32.t)Either.either)list =
[
("large number 9223372036854775808", os_empty, "9223372036854775808", Right (os_empty, int32Max));
("large hex number 0x8000000000000000", os_empty, "0x8000000000000000", Right (os_empty, int32Max));
("large oct number 020000000000", os_empty, "020000000000", Right (os_empty, int32Max));
("large oct number 07777777777777777777777", os_empty, "07777777777777777777777", Right (os_empty, int32Max));
("arithmetic overflow", os_empty, "2147483647 + 1", Right (os_empty, int32Min));
("left shift by negative", os_empty, "15 << -31", Right (os_empty, ofNumLiteral 30));
("right shift by negative", os_empty, "15 >> -31", Right (os_empty, ofNumLiteral 7));
("right shift uses arithmetic shift", os_empty, "(15 << -1) >> 1", Right (os_empty, Int32.div int32Min (ofNumLiteral 2)));
]
let run_tests () =
let failed = ref 0 in
let test_count = ref 0 in
let prnt = fun (s, n) -> ("<| " ^ (printable_shell_env s) ^ "; " ^ (string_of_fields n) ^ " |>") in
print_endline "\n=== Running arithmetic tests...";
Lexer tests
test_part "Lexer" check_lexer (Either.either_case id token_list_to_string) lexer_tests test_count failed;
Parser tests
test_part "Parser" check_parser (Either.either_case id string_of_aexp) parser_tests test_count failed;
test_part "General eval Nat_big_num" check_eval_big_num (Either.either_case id prnt) (eval_tests Nat_big_num.of_int Nat_big_num.mul) test_count failed;
test_part "General eval int32" check_eval_int32 (Either.either_case id prnt) (eval_tests Int32.of_int Int32.mul) test_count failed;
test_part "General eval int64" check_eval_int64 (Either.either_case id prnt) (eval_tests Int64.of_int Int64.mul) test_count failed;
test_part "Eval Nat_big_num" check_eval_big_num (Either.either_case id prnt) (eval_bignum_tests Nat_big_num.of_int Nat_big_num.mul) test_count failed;
test_part "Eval int32" check_eval_int32 (Either.either_case id prnt) (eval_int32_tests Int32.of_int Int32.mul) test_count failed;
test_part "Eval int64" check_eval_int64 (Either.either_case id prnt) (eval_int64_tests Int64.of_int Int64.mul) test_count failed;
printf "=== ...ran %d arithmetic tests with %d failures.\n\n" !test_count !failed;
!failed = 0
|
d9669d0b0469bb3d60ad1867e0760acb59645355b18110367e5028566f04b358 | screenshotbot/screenshotbot-oss | test-single.lisp | (defpackage :util/tests/test-single
(:use #:cl
#:fiveam)
(:import-from #:util/single
#:deserialize
#:serialize)
(:import-from #:fiveam-matchers/core
#:equal-to
#:has-typep
#:assert-that)
(:local-nicknames (#:a #:alexandria)))
(in-package :util/tests/test-single)
(util/fiveam:def-suite)
(defclass dummy-1 ()
((foo :initarg :foo)
(bar :initarg :bar)))
(def-fixture state ()
(uiop:with-temporary-file (:stream s :direction :io :element-type '(unsigned-byte 8))
(&body)))
(test preconditions ()
(with-fixture state ()
(let ((obj (make-instance 'dummy-1 :foo "bar")))
(finishes
(serialize obj s))
(file-position s 0)
(let ((result (deserialize s)))
(assert-that result
(has-typep 'dummy-1))
(assert-that (slot-value result 'foo)
(equal-to "bar"))
(is-false (slot-boundp result 'bar))))))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/a80bbf0bff1d64f165d38eafe0937dced0d3cc7e/src/util/tests/test-single.lisp | lisp | (defpackage :util/tests/test-single
(:use #:cl
#:fiveam)
(:import-from #:util/single
#:deserialize
#:serialize)
(:import-from #:fiveam-matchers/core
#:equal-to
#:has-typep
#:assert-that)
(:local-nicknames (#:a #:alexandria)))
(in-package :util/tests/test-single)
(util/fiveam:def-suite)
(defclass dummy-1 ()
((foo :initarg :foo)
(bar :initarg :bar)))
(def-fixture state ()
(uiop:with-temporary-file (:stream s :direction :io :element-type '(unsigned-byte 8))
(&body)))
(test preconditions ()
(with-fixture state ()
(let ((obj (make-instance 'dummy-1 :foo "bar")))
(finishes
(serialize obj s))
(file-position s 0)
(let ((result (deserialize s)))
(assert-that result
(has-typep 'dummy-1))
(assert-that (slot-value result 'foo)
(equal-to "bar"))
(is-false (slot-boundp result 'bar))))))
| |
4fdf6be355273b510b40d646e268a8f37abe651a1ae0da3efb378202a39c2d99 | tsloughter/kakapo | kakapo_broker_sup.erl | -module(kakapo_broker_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init(_Args) ->
RestartStrategy = one_for_one,
MaxRestarts = 1000,
MaxSecondsBetweenRestarts = 3600,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
ChildSpecs = [],
{ok, {SupFlags, ChildSpecs}}.
| null | https://raw.githubusercontent.com/tsloughter/kakapo/7f2062029a2a26825055ef19ebe8d043d300df6b/apps/kakapo_broker/src/kakapo_broker_sup.erl | erlang | API
Supervisor callbacks
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
=================================================================== | -module(kakapo_broker_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init(_Args) ->
RestartStrategy = one_for_one,
MaxRestarts = 1000,
MaxSecondsBetweenRestarts = 3600,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
ChildSpecs = [],
{ok, {SupFlags, ChildSpecs}}.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.