_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
|
---|---|---|---|---|---|---|---|---|
c982769456e73efdc335d9bfaab79570dd636b8e7252d706e8ecb7be0a203f00 | janestreet/memtrace_viewer_with_deps | test_sexp.ml | open! Core_kernel
open! Import
open! Sexp
module With_text = struct
open! With_text
let sexp_of_il = sexp_of_list sexp_of_int
let il_of_sexp = list_of_sexp int_of_sexp
let il_of_text text = Or_error.ok_exn (of_text il_of_sexp text)
let il_of_value il = of_value sexp_of_il il
module IL = struct
type t = int list [@@deriving compare, sexp_of]
let equal = [%compare.equal: t]
end
let t = il_of_value [ 3; 4 ]
let%expect_test _ =
print_s [%sexp (text t : string)];
[%expect {| "(3 4)" |}]
;;
let t' = il_of_text (text t)
let%expect_test _ =
require_equal [%here] (module IL) (value t') [ 3; 4 ];
[%expect {| |}]
;;
let%expect_test _ =
print_s [%sexp (t : il t)];
[%expect {| "(3 4)" |}]
;;
let%expect_test _ =
require_equal
[%here]
(module IL)
(value (t_of_sexp il_of_sexp (Atom "(3 4)")))
[ 3; 4 ];
[%expect {| |}]
;;
let%expect_test _ =
require_equal
[%here]
(module IL)
[ 8; 9 ]
(value (il_of_text ";this is a comment\n (8; foo\n 9) \n "));
[%expect {| |}]
;;
let%expect_test _ =
require_does_raise [%here] (fun () -> il_of_text "(1 2 bla)");
[%expect
{|
(Of_sexp_error :1:5 "int_of_sexp: (Failure int_of_string)" (invalid_sexp bla)) |}]
;;
let%expect_test _ =
require_does_raise [%here] (fun () ->
t_of_sexp il_of_sexp (Sexp.of_string "\"(1 2 bla)\""));
[%expect
{|
(Of_sexp_error :1:5 "int_of_sexp: (Failure int_of_string)" (invalid_sexp bla)) |}]
;;
end
let%test_module _ =
(module struct
type t1 = Sexp.t [@@deriving bin_io]
type t2 = Sexp.Stable.V1.t [@@deriving bin_io]
type t3 = Core_kernel_stable.Sexp.V1.t [@@deriving bin_io]
let%expect_test "Sexp.t, Sexp.Stable.V1.t and Core_kernel_stable.Sexp.V1.t \
bin_digests match"
=
print_endline [%bin_digest: t1];
print_endline [%bin_digest: t2];
print_endline [%bin_digest: t3];
[%expect
{|
832b40ae394f2851da8ba67b3339b429
832b40ae394f2851da8ba67b3339b429
832b40ae394f2851da8ba67b3339b429 |}]
;;
end)
;;
let%test_module "of_sexp_allow_extra_fields_recursively" =
(module struct
module V = struct
type v1 =
{ a : string
; b : int
; suffix : string
}
[@@deriving sexp]
type v2 =
{ a : string
; b : int
}
[@@deriving sexp]
type t = v2 [@@deriving sexp_of]
let t_of_sexp sexp : t =
try v2_of_sexp sexp with
| e ->
(match v1_of_sexp sexp with
| { a; b; suffix } -> { a = a ^ suffix; b }
| exception _ -> raise e)
;;
end
type t = { v : V.t } [@@deriving sexp]
let%expect_test "affect sexp converter globally" =
let sexp = Sexp.of_string {|((v ((a a)(b 0)(suffix "-suffix"))))|} in
let t = t_of_sexp sexp in
print_s (sexp_of_t t);
[%expect
{|
((
v (
(a a-suffix)
(b 0)))) |}];
let t = Sexp.of_sexp_allow_extra_fields_recursively t_of_sexp sexp in
print_s (sexp_of_t t);
[%expect {|
((
v (
(a a)
(b 0)))) |}]
;;
end)
;;
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/core_kernel/test/src/test_sexp.ml | ocaml | open! Core_kernel
open! Import
open! Sexp
module With_text = struct
open! With_text
let sexp_of_il = sexp_of_list sexp_of_int
let il_of_sexp = list_of_sexp int_of_sexp
let il_of_text text = Or_error.ok_exn (of_text il_of_sexp text)
let il_of_value il = of_value sexp_of_il il
module IL = struct
type t = int list [@@deriving compare, sexp_of]
let equal = [%compare.equal: t]
end
let t = il_of_value [ 3; 4 ]
let%expect_test _ =
print_s [%sexp (text t : string)];
[%expect {| "(3 4)" |}]
;;
let t' = il_of_text (text t)
let%expect_test _ =
require_equal [%here] (module IL) (value t') [ 3; 4 ];
[%expect {| |}]
;;
let%expect_test _ =
print_s [%sexp (t : il t)];
[%expect {| "(3 4)" |}]
;;
let%expect_test _ =
require_equal
[%here]
(module IL)
(value (t_of_sexp il_of_sexp (Atom "(3 4)")))
[ 3; 4 ];
[%expect {| |}]
;;
let%expect_test _ =
require_equal
[%here]
(module IL)
[ 8; 9 ]
(value (il_of_text ";this is a comment\n (8; foo\n 9) \n "));
[%expect {| |}]
;;
let%expect_test _ =
require_does_raise [%here] (fun () -> il_of_text "(1 2 bla)");
[%expect
{|
(Of_sexp_error :1:5 "int_of_sexp: (Failure int_of_string)" (invalid_sexp bla)) |}]
;;
let%expect_test _ =
require_does_raise [%here] (fun () ->
t_of_sexp il_of_sexp (Sexp.of_string "\"(1 2 bla)\""));
[%expect
{|
(Of_sexp_error :1:5 "int_of_sexp: (Failure int_of_string)" (invalid_sexp bla)) |}]
;;
end
let%test_module _ =
(module struct
type t1 = Sexp.t [@@deriving bin_io]
type t2 = Sexp.Stable.V1.t [@@deriving bin_io]
type t3 = Core_kernel_stable.Sexp.V1.t [@@deriving bin_io]
let%expect_test "Sexp.t, Sexp.Stable.V1.t and Core_kernel_stable.Sexp.V1.t \
bin_digests match"
=
print_endline [%bin_digest: t1];
print_endline [%bin_digest: t2];
print_endline [%bin_digest: t3];
[%expect
{|
832b40ae394f2851da8ba67b3339b429
832b40ae394f2851da8ba67b3339b429
832b40ae394f2851da8ba67b3339b429 |}]
;;
end)
;;
let%test_module "of_sexp_allow_extra_fields_recursively" =
(module struct
module V = struct
type v1 =
{ a : string
; b : int
; suffix : string
}
[@@deriving sexp]
type v2 =
{ a : string
; b : int
}
[@@deriving sexp]
type t = v2 [@@deriving sexp_of]
let t_of_sexp sexp : t =
try v2_of_sexp sexp with
| e ->
(match v1_of_sexp sexp with
| { a; b; suffix } -> { a = a ^ suffix; b }
| exception _ -> raise e)
;;
end
type t = { v : V.t } [@@deriving sexp]
let%expect_test "affect sexp converter globally" =
let sexp = Sexp.of_string {|((v ((a a)(b 0)(suffix "-suffix"))))|} in
let t = t_of_sexp sexp in
print_s (sexp_of_t t);
[%expect
{|
((
v (
(a a-suffix)
(b 0)))) |}];
let t = Sexp.of_sexp_allow_extra_fields_recursively t_of_sexp sexp in
print_s (sexp_of_t t);
[%expect {|
((
v (
(a a)
(b 0)))) |}]
;;
end)
;;
|
|
9102b2981caa695cf3a74369cf596d3d1a43824775da34ad1c12316c16ace973 | ocaml-obuild/obuild | modname.ml | open Ext.Filepath
open Ext.Fugue
open Ext.Compat
type t = string
exception InvalidModuleName of string
exception EmptyModuleName
exception ModuleFilenameNotValid of string
let char_isalpha c = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
let char_is_valid_modchar c = char_isalpha c || (c >= '0' && c <= '9') || c == '_'
let string_all p s =
let valid = ref true in
for i = 0 to String.length s - 1 do
valid := !valid && p s.[i]
done;
!valid
let wrap x =
if String.length x = 0 then
raise EmptyModuleName
else if not (string_all char_is_valid_modchar x) then
raise (InvalidModuleName x)
else if char_uppercase x.[0] <> x.[0] then
raise (InvalidModuleName x)
else
x
let of_string x = wrap x
let to_string x = x
let to_dir x = string_uncapitalize x
let to_x ext modname = fn (string_uncapitalize modname ^ ext)
let to_o = to_x ".o"
let to_directory = to_x ""
let to_filename = to_x ".ml"
let to_parser = to_x ".mly"
let to_lexer = to_x ".mll"
let atd_modname modname =
if String.length modname > 2 then
let b, e = string_splitAt (String.length modname - 2) modname in
match e with
| "_t" | "_v" | "_j" -> b
| _ -> modname
else
modname
let to_atd modname = to_x ".atd" (atd_modname modname)
let module_lookup_methods = [ to_directory; to_parser; to_lexer; to_atd; to_filename ]
let of_directory filename = wrap (string_capitalize (fn_to_string filename))
let of_filename filename =
try wrap (string_capitalize (Filename.chop_extension (fn_to_string filename))) with
| EmptyModuleName -> raise (ModuleFilenameNotValid (fn_to_string filename))
| Invalid_argument _ -> raise (ModuleFilenameNotValid (fn_to_string filename))
| null | https://raw.githubusercontent.com/ocaml-obuild/obuild/58459992ee9b3d56f09f6ff3dd434a52657b836c/obuild/modname.ml | ocaml | open Ext.Filepath
open Ext.Fugue
open Ext.Compat
type t = string
exception InvalidModuleName of string
exception EmptyModuleName
exception ModuleFilenameNotValid of string
let char_isalpha c = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
let char_is_valid_modchar c = char_isalpha c || (c >= '0' && c <= '9') || c == '_'
let string_all p s =
let valid = ref true in
for i = 0 to String.length s - 1 do
valid := !valid && p s.[i]
done;
!valid
let wrap x =
if String.length x = 0 then
raise EmptyModuleName
else if not (string_all char_is_valid_modchar x) then
raise (InvalidModuleName x)
else if char_uppercase x.[0] <> x.[0] then
raise (InvalidModuleName x)
else
x
let of_string x = wrap x
let to_string x = x
let to_dir x = string_uncapitalize x
let to_x ext modname = fn (string_uncapitalize modname ^ ext)
let to_o = to_x ".o"
let to_directory = to_x ""
let to_filename = to_x ".ml"
let to_parser = to_x ".mly"
let to_lexer = to_x ".mll"
let atd_modname modname =
if String.length modname > 2 then
let b, e = string_splitAt (String.length modname - 2) modname in
match e with
| "_t" | "_v" | "_j" -> b
| _ -> modname
else
modname
let to_atd modname = to_x ".atd" (atd_modname modname)
let module_lookup_methods = [ to_directory; to_parser; to_lexer; to_atd; to_filename ]
let of_directory filename = wrap (string_capitalize (fn_to_string filename))
let of_filename filename =
try wrap (string_capitalize (Filename.chop_extension (fn_to_string filename))) with
| EmptyModuleName -> raise (ModuleFilenameNotValid (fn_to_string filename))
| Invalid_argument _ -> raise (ModuleFilenameNotValid (fn_to_string filename))
|
|
d57373eaae3de72be83012068dbe774810dea2f9caaf316afc71e806950a2238 | helins/kafka.clj | stream.clj | (ns dvlopt.kstreams.stream
"Kafka Streams' abstraction of streams.
Cf. `dvlopt.kstreams.builder` for the big picture and details
A stream can be transformed by various functions. Those functions returns themselves a new stream representing the transformation.
Hence, a single stream can be used for the base of more than one transformation.
The values of a stream can be aggregated. Prior to this, it needs to be grouped by using the `group-by` or `group-by-key` function from
this namespace. If needed, a grouped stream can then be windowed by fixed time intervals or by sessions. Then, an appropriate `reduce-*`
function can be used to perform the aggregation which always result in a table.
A whole variety of joins between a stream and anything else are available."
{:author "Adam Helinski"}
(:refer-clojure :exclude [group-by])
(:require [dvlopt.kafka.-interop.java :as K.-interop.java]
[dvlopt.kstreams.store :as KS.store])
(:import (org.apache.kafka.streams.kstream GlobalKTable
KeyValueMapper
KGroupedStream
KStream
KTable
Predicate
SessionWindowedKStream
TimeWindowedKStream)))
;;;;;;;;;; Transformations
(defn branch
"Given a list of predicate functions, returns a vector of new corresponding streams such that as soon as a key-value from
the original stream returns true on a predicate, it is sent to the corresponding stream (and only that one).
A record is dropped if it matches no predicate.
Divives a stream into 3 new streams containing respectively : red values , : black ones , and any other ones .
(branch stream
[(fn only-red [k v]
(= v
:red))
(fn only-black [k v]
(= v
:black))
(fn other [k v]
true)])"
[^KStream stream predicates]
(into []
(.branch stream
(into-array Predicate
(map K.-interop.java/predicate
predicates)))))
(defn merge-stream
"Returns a new stream merging the two given ones.
There is no guarantee about the ordering of the records between streams. However, order is preserved for each stream."
^KStream
[^KStream stream ^KStream other-stream]
(.merge stream
other-stream))
(defn filter-kv
"Returns a new stream filtering out key-values from the given one.
Keeps values greater than or equal to 42 .
(filter-kv stream
(fn [k v]
(>= v
42)))"
^KStream
[^KStream stream predicate]
(.filter stream
(K.-interop.java/predicate predicate)))
(defn map-kv
"Returns a new stream mapping key-values from the given one.
Marks the resulting stream for repartioning.
Cf. `dvlopt.kstreams.builder`
Ex. ;; The key is an ip address mapped to a country and the value is a collection mapped to its
number of items.
(map-kv stream
(fn [k v]
[(country-from-ip k)
(count v)]))"
^KStream
[^KStream stream f]
(.map stream
(K.-interop.java/key-value-mapper f)))
(defn map-keys
"Returns a new stream efficiently mapping keys from the given one.
Marks the resulting stream for repartioning.
Cf. `dvlopt.kstreams.builder`
Ex. ;; The key is an ip address mapped to a country.
(map-keys stream
(fn [k v]
(country-from-ip k)))"
^KStream
[^KStream stream f]
(.selectKey stream
(K.-interop.java/key-value-mapper--raw f)))
(defn map-values
"Returns a new stream efficiently mapping values from the given one.
Unlike other mapping functions, does not mark the resulting stream for repartioning as the keys remain intact.
Ex. ;; The value is a collection mapped to its number of items.
(map-values stream
(fn [k v]
(count v)))"
^KStream
[^KStream kstream f]
(.mapValues kstream
(K.-interop.java/value-mapper-with-key f)))
(defn fmap-kv
"Returns a new stream mapping key-values from the given one into a collection of [key value]'s (or nil).
Marks the resulting stream for repartioning.
Cf. `dvlopt.kstreams.builder`
Ex. ;; The value is a list of tokens and we want to count them individually so that we end up with
a collection where the key is a unique token and the value is its count.
(fmap-kv stream
(fn [k v]
(reduce (fn [hmap token]
(assoc hmap
token
(inc (get hmap
token
0))))
{}
v)))"
^KStream
[^KStream kstream f]
(.flatMap kstream
(K.-interop.java/key-value-mapper--flat f)))
(defn fmap-values
"Returns a new stream mapping values from the given one into a collection of values (or nil).
Unlike `fmap-kv`, does not mark the resulting stream for repartioning as the keys remain intact.
The value is a list we want to split into individual items while filtering out nils .
(fmap-values stream
(fn [k v]
(filter some?
v)))"
^KStream
[^KStream kstream f]
(.flatMapValues kstream
(K.-interop.java/value-mapper-with-key f)))
(defn process
"Returns a new stream processing the records from the given one using a low-level processor.
For when the high-level API is not enough. It is typically used for an `fmap-kv` like behavior involving some state.
Cf. `dvlopt.kstreams.topology/add-processor`
:dvlopt.kstreams/processor.on-record may be used to explicitly forward records using the associated context.
Marks the topic for repartioning.
Cf. `dvlopt.kstreams.builder`
A map of options may be given :
:dvlopt.kstreams.store/names
List of state store names previously added to the underlying builder this processor need to access.
Cf. `dvlopt.kstreams.builder/add-store`"
(^KStream
[stream processor]
(process stream
processor
nil))
(^KStream
[^KStream stream processor options]
(.transform stream
(K.-interop.java/transformer-supplier processor)
(into-array String
(::KS.store/names options)))))
(defn process-values
"Returns a new stream efficiently proccessing the values of the given one using a low-level processor.
Unlike `process`, does not mark the resulting stream for repartioning as the keys remain intact. Also, because this
function is about processing values, there is no point forwarding records using the associated context so doing so
will throw an exception. Rather, the library maps the original value of the records to the value returned by
:dvlopt.kstreams/processor.on-record (which may be nil).
It is typically used when some state is needed.
A map of options may be given, just like in `process`."
(^KStream
[stream processor]
(process-values stream
processor
nil))
(^KStream
[^KStream stream processor options]
(.transformValues stream
(K.-interop.java/value-transformer-with-key-supplier processor)
^"[Ljava.lang.String;" (into-array String
(::KS.store/names options)))))
;;;;;;;;;; Joins
(defn join-with-stream
"Returns a new stream inner joining values from both given streams every time :
a) They shares the same key.
b) The difference in the timestamps of both records is <= the given interval.
Cf. `dvlopt.kafka` for descriptions of time intervals.
Hence, for the same key, several joins might happen within a single interval.
Records with a nil key or nil value are ignored.
Input streams are repartitioned if they were marked for repartitioning and a store will be generated for
each of them.
Cf. `dvlopt.kstreams.builder` for requirements related to joins
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/serializer.key
:dvlopt.kstreams/left
:dvlopt.kstreams/right
Maps which may contain value ser/de :
:dvlopt.kafka/deserializer.value
:dvlopt.kafka/serializer.value
Cf. `dvlopt.kafka` for description of serializers and deserializers.
:dvlopt.kstreams.store/retention
Cf. `dvlopt.kstreams.store`
Ex. (join-with-stream left-stream
right-stream
(fn [v-left v-right]
(str \"left = \" v-left \"and right = \" v-right))
[2 :seconds])"
(^KStream
[^KStream left-stream ^KStream right-stream f interval]
(join-with-stream left-stream
right-stream
f
interval
nil))
(^KStream
[^KStream left-stream ^KStream right-stream f interval options]
(.join left-stream
right-stream
(K.-interop.java/value-joiner f)
(K.-interop.java/join-windows interval
options)
(K.-interop.java/joined options))))
(defn left-join-with-stream
"Exactly like `join-with-stream` but the join is triggered even if there is no record with the same key yet in
the right stream for a given time window. In such case, the right value provided for the join is nil."
(^KStream
[^KStream left-stream ^KStream right-stream f interval]
(left-join-with-stream left-stream
right-stream
f
interval
nil))
(^KStream
[^KStream left-stream ^KStream right-stream f interval options]
(.leftJoin left-stream
right-stream
(K.-interop.java/value-joiner f)
(K.-interop.java/join-windows interval
options)
(K.-interop.java/joined options))))
(defn outer-join-with-stream
"Exactly like `join-with-stream` but the join is triggered even if there is no record with the same key yet in
the other stream for a given time window. In such case, the value provided for this side of the join is nil."
(^KStream
[^KStream left-stream ^KStream right-stream f interval]
(outer-join-with-stream left-stream
right-stream
f
interval
nil))
(^KStream
[^KStream left-stream ^KStream right-stream f interval options]
(.outerJoin left-stream
right-stream
(K.-interop.java/value-joiner f)
(K.-interop.java/join-windows interval
options)
(K.-interop.java/joined options))))
(defn join-with-table
"Returns a new stream inner joining the given stream with the given table. The join is triggered everytime
a new record arrives in the stream and the table contains the key of this record. This is very useful for
enriching a stream with some up-to-date information.
Records from the input stream with a nil key or value are ignored. Records from the input table with a nil
value removes the corresponding key from this table.
The input stream is repartioned if it was marked for repartioning.
A map of options may be given, just like in `join-with-stream`.
Ex. (join-with-table stream
table
(fn [v-stream v-table]
(assoc v-stream
:last-known-location
(:location v-table))))"
(^KStream
[^KStream left-stream ^KTable right-table f]
(join-with-table left-stream
right-table
f
nil))
(^KStream
[^KStream left-stream ^KTable right-table f options]
(.join left-stream
right-table
(K.-interop.java/value-joiner f)
(K.-interop.java/joined options))))
(defn left-join-with-table
"Exactly like `join-with-table` but the join is triggered even if the table does contain the key. In such case, the
right value supplied during the join in nil."
(^KStream
[^KStream left-stream ^KTable right-table f]
(left-join-with-table left-stream
right-table
f
nil))
(^KStream
[^KStream left-stream ^KTable right-table f options]
(.leftJoin left-stream
right-table
(K.-interop.java/value-joiner f)
(K.-interop.java/joined options))))
(defn join-with-global-table
"Similar to `join-with-table` but offers the following :
- Data need not to be co-partitioned.
- More efficient when a regular table is skewed (some partitions are heavily populated, some not).
- Typically more efficient that performing several joins in order to reach the same result.
- Allows for joining on a different key.
Each record of the input stream is mapped to a new key which triggers a join if the global table contains that mapped
key. The value resulting from the join is associated with the key of the original record.
Records from the input stream with a nil key or value are ignored. Records from the global table with a nil value
removes the corresponding key from this global table.
The input stream is repartitioned if it was marked for repartitioning.
Ex. ;; Enrich a stream of users by adding the most popular song of the country they are from.
(join-with-global-table stream
global-table
(fn map-k [k v]
(:country v))
(fn join [v-stream v-global-table]
(assoc v-stream
:song
(first (:top-10 v-global-table)))))"
^KStream
[^KStream left-stream ^GlobalKTable right-global-table f-map-k f-join]
(.join left-stream
right-global-table
(K.-interop.java/key-value-mapper--raw f-map-k)
(K.-interop.java/value-joiner f-join)))
(defn left-join-with-global-table
"Exactly like `join-with-global-table` but the join is triggered even if the global table does not contain the mapped
key. In such case, the right value supplied during the join is nil."
^KStream
[^KStream left-stream ^GlobalKTable right-global-table f-map-k f-join]
(.leftJoin left-stream
right-global-table
(K.-interop.java/key-value-mapper--raw f-map-k)
(K.-interop.java/value-joiner f-join)))
Grouping , windowing and aggregating
(defn group-by
"Returns a new grouped stream grouping values based on a chosen key.
Drops records leading to a nil chosen key.
Because a new key is explicitly selected, the data is repartioned.
Cf. `dvlopt.kstreams.builder` about repartioning.
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/deserializer.value
:dvlopt.kafka/serializer.key
:dvlopt.kafka/serializer.value
Cf. `dvlopt.kafka` for description of deserializers
:dvlopt.kstreams/repartition-name
Cf. `dvlopt.kstreams.builder` section \"State and repartitioning\"
Ex. (group-by stream
(fn by-country [k v]
(:country v)))"
(^KGroupedStream
[stream f]
(group-by stream
f
nil))
(^KGroupedStream
[^KStream kstream f options]
(.groupBy kstream
(K.-interop.java/key-value-mapper--raw f)
(K.-interop.java/grouped options))))
(defn group-by-key
"Exactly like `group-by` but groups directly by the original key than a selected one.
Unless the stream was marked for repartioning, this function will not repartition it as keys remain intact."
(^KGroupedStream
[^KStream stream]
(group-by-key stream
nil))
(^KGroupedStream
[^KStream stream options]
(.groupByKey stream
(K.-interop.java/serialized options))))
(defn window
"Returns a new time windowed stream windowing values by a fixed time interval for each key of the given grouped stream.
A map of options may be given :
:dvlopt.kstreams.store/retention
Cf. `dvlopt.kstreams.store`
::interval.type
Fixed time windows can behave in 3 fashions :
:hopping
Hopping windows of interval I advance by sub-interval J <= I and are aligned to the epoch, meaning they
always start at time 0. The lower bound is inclusive and upper bound is exclusive.
Ex. I = 5 seconds, J = 3 seconds (thus every window overlaps with its neighbor by 2 seconds)
5 ) , [ 3;8 ) , [ 6;11 ) , ...
:tumbling (default)
Tumbling windows are simply non-overlapping hopping windows (ie. I = J).
5 ) , [ 5;10 ) , [ 10;15 ) , ...
:sliding
Sliding windows are aligned to the timestamps of the records and not the epoch. Two records are said to
be part of the same sliding window if the difference of their timestamps <= I, where both the lower and
upper bound are inclusive.
Windows of type :hopping accepts the following additional option :
::advance-by
The J sub-interval.
Cf. `dvlopt.kafka` for description of time intervals.
`dvlopt.kstreams.store` for description of time windows.
Windows of 5 seconds advancing by 3 seconds ( thus overlapping 2 seconds ) .
(window grouped-stream
[5 :seconds]
{::interval.type :hopping
::advance-by [3 :seconds]})"
(^TimeWindowedKStream
[grouped-stream interval]
(window grouped-stream
interval
nil))
(^TimeWindowedKStream
[^KGroupedStream grouped-stream interval options]
(.windowedBy grouped-stream
(K.-interop.java/time-windows interval
options))))
(defn window-by-session
"Returns a new session windowed stream windowing values by sessions for each key of the given grouped stream.
Sessions are non-fixed intervals of activity between fixed intervals of inactivity.
Cf. `dvlopt.kafka` for description of time intervals
Cf. `dvlopt.kstreams.store` for description of sessions
A map of options may be given :
:dvlopt.kstreams.store/retention
Cf. `dvlopt.kstreams.store`"
(^SessionWindowedKStream
[grouped-stream interval]
(window-by-session grouped-stream
interval
nil))
(^SessionWindowedKStream
[^KGroupedStream grouped-stream interval options]
(.windowedBy grouped-stream
(K.-interop.java/session-windows interval
options))))
(defn reduce-values
"Returns a new table aggregating values for each key of the given grouped stream.
A map of standard table options may be given (cf. `dvlopt.kstreams.table`).
Ex. (reduce-values grouped-stream
(fn reduce [aggregated k v]
(+ aggregated
v))
(fn seed []
0))"
(^KTable
[grouped-stream fn-reduce fn-seed]
(reduce-values grouped-stream
fn-reduce
fn-seed
nil))
(^KTable
[^KGroupedStream grouped-stream fn-reduce fn-seed options]
(.aggregate grouped-stream
(K.-interop.java/initializer fn-seed)
(K.-interop.java/aggregator fn-reduce)
(K.-interop.java/materialized--kv options))))
(defn reduce-windows
"Returns a new table aggregating values for each time window of each key of the given time-windowed stream.
Cf. `reduce-values`
A map of standard table options may be given (cf. `dvlopt.kstreams.table`)."
(^KTable
[time-windowed-stream fn-reduce fn-seed]
(reduce-windows time-windowed-stream
fn-reduce
fn-seed
nil))
(^KTable
[^TimeWindowedKStream time-windowed-stream fn-reduce fn-seed options]
(.aggregate time-windowed-stream
(K.-interop.java/initializer fn-seed)
(K.-interop.java/aggregator fn-reduce)
(K.-interop.java/materialized--by-name options))))
(defn reduce-sessions
"Returns a new table aggregating values for each session of each key for the given session-windowed stream.
Sessions might merge, hence the need for a function being able to do so.
A map of standard table options may be given (cf. `dvlopt.kstreams.table`).
Ex. (reduce-sessions grouped-stream
(fn reduce [aggregated k v]
(+ aggregated
v))
(fn merge [aggregated-session-1 aggregated-session-2 k]
(+ aggregated-session-1
aggregated-session-2))
(fn seed []
0))"
(^KTable
[session-windowed-stream fn-reduce fn-merge fn-seed]
(reduce-sessions session-windowed-stream
fn-reduce
fn-merge
fn-seed
nil))
(^KTable
[^SessionWindowedKStream session-windowed-stream fn-reduce fn-merge fn-seed options]
(.aggregate session-windowed-stream
(K.-interop.java/initializer fn-seed)
(K.-interop.java/aggregator fn-reduce)
(K.-interop.java/merger fn-merge)
(K.-interop.java/materialized--by-name options))))
Transitions
(defn through-topic
"Sends each record of the given stream to a given topic and then continue streaming.
Useful when the stream was marked for repartioning. Streaming to a chosen topic before a stateful operation will avoid
automatic repartioning.
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/deserializer.value
:dvlopt.kafka/serializer.key
:dvlopt.kafka/serializer.value
Cf. `dvlopt.kafka` for description of serializers and deserializers.
:dvlopt.kstreams/select-partition
Cf. `dvlopt.kstreams.builder`"
(^KStream
[stream topic]
(through-topic stream
topic
nil))
(^KStream
[^KStream stream ^String topic options]
(.through stream
topic
(K.-interop.java/produced options))))
(defn do-kv
"For each key-value, do a side-effect and then continue streaming.
Side effects cannot be tracked by Kafka, hence they do not benefit from Kafka's processing garantees.
Ex. (do-kv stream
(fn [k v]
(println :key k :value v)))"
^KStream
[^KStream stream f]
(.peek stream
(K.-interop.java/foreach-action f)))
;;;;;;;;;; Terminating streams
(defn sink-process
"Marks the end of the given stream by processing each record with a low-level processor.
Returns nil.
A map of options may be given, just like in `process`."
(^KStream
[stream processor]
(process stream
processor
nil))
(^KStream
[^KStream stream processor options]
(.process stream
(K.-interop.java/processor-supplier processor)
(into-array String
(::KS.store/names options)))))
(defn sink-topic
"Marks the end of the given stream by sending each key-value to a chosen topic.
In this case, topic might be either :
- [:always TopicName]
Where TopicName is the name of the unique topic the records will always be sent to.
- [:select (fn [record])]
Where the function is used to dynamically select a topic. All the values in the provided record refer
to what is known about the original record sourced from Kafka. As such, even ::topic might be missing.
Returns nil.
A map of options may be given, the same one as for `through-topic`."
([stream topic]
(sink-topic stream
topic
nil))
([^KStream stream topic options]
(let [options' (K.-interop.java/produced options)
[type
target] topic]
(condp identical?
type
:always (.to stream
^String target
options')
:select (.to stream
(K.-interop.java/topic-name-extractor target)
options')))))
(defn sink-do
"Marks the end of the given stream by doing a side-effect for each key-value.
Side effects cannot be tracked by Kafka, hence they do not benefit from Kafka's processing garantees.
Returns nil.
Ex. (sink-do stream
(fn [k v]
(println :key k :value v)))"
[^KStream stream f]
(.foreach stream
(K.-interop.java/foreach-action f)))
| null | https://raw.githubusercontent.com/helins/kafka.clj/ecf688f1a8700491c2cd65bcfb19a3781aa4f575/src/dvlopt/kstreams/stream.clj | clojure | Transformations
The key is an ip address mapped to a country and the value is a collection mapped to its
The key is an ip address mapped to a country.
The value is a collection mapped to its number of items.
The value is a list of tokens and we want to count them individually so that we end up with
Joins
Enrich a stream of users by adding the most popular song of the country they are from.
8 ) , [ 6;11 ) , ...
10 ) , [ 10;15 ) , ...
Terminating streams | (ns dvlopt.kstreams.stream
"Kafka Streams' abstraction of streams.
Cf. `dvlopt.kstreams.builder` for the big picture and details
A stream can be transformed by various functions. Those functions returns themselves a new stream representing the transformation.
Hence, a single stream can be used for the base of more than one transformation.
The values of a stream can be aggregated. Prior to this, it needs to be grouped by using the `group-by` or `group-by-key` function from
this namespace. If needed, a grouped stream can then be windowed by fixed time intervals or by sessions. Then, an appropriate `reduce-*`
function can be used to perform the aggregation which always result in a table.
A whole variety of joins between a stream and anything else are available."
{:author "Adam Helinski"}
(:refer-clojure :exclude [group-by])
(:require [dvlopt.kafka.-interop.java :as K.-interop.java]
[dvlopt.kstreams.store :as KS.store])
(:import (org.apache.kafka.streams.kstream GlobalKTable
KeyValueMapper
KGroupedStream
KStream
KTable
Predicate
SessionWindowedKStream
TimeWindowedKStream)))
(defn branch
"Given a list of predicate functions, returns a vector of new corresponding streams such that as soon as a key-value from
the original stream returns true on a predicate, it is sent to the corresponding stream (and only that one).
A record is dropped if it matches no predicate.
Divives a stream into 3 new streams containing respectively : red values , : black ones , and any other ones .
(branch stream
[(fn only-red [k v]
(= v
:red))
(fn only-black [k v]
(= v
:black))
(fn other [k v]
true)])"
[^KStream stream predicates]
(into []
(.branch stream
(into-array Predicate
(map K.-interop.java/predicate
predicates)))))
(defn merge-stream
"Returns a new stream merging the two given ones.
There is no guarantee about the ordering of the records between streams. However, order is preserved for each stream."
^KStream
[^KStream stream ^KStream other-stream]
(.merge stream
other-stream))
(defn filter-kv
"Returns a new stream filtering out key-values from the given one.
Keeps values greater than or equal to 42 .
(filter-kv stream
(fn [k v]
(>= v
42)))"
^KStream
[^KStream stream predicate]
(.filter stream
(K.-interop.java/predicate predicate)))
(defn map-kv
"Returns a new stream mapping key-values from the given one.
Marks the resulting stream for repartioning.
Cf. `dvlopt.kstreams.builder`
number of items.
(map-kv stream
(fn [k v]
[(country-from-ip k)
(count v)]))"
^KStream
[^KStream stream f]
(.map stream
(K.-interop.java/key-value-mapper f)))
(defn map-keys
"Returns a new stream efficiently mapping keys from the given one.
Marks the resulting stream for repartioning.
Cf. `dvlopt.kstreams.builder`
(map-keys stream
(fn [k v]
(country-from-ip k)))"
^KStream
[^KStream stream f]
(.selectKey stream
(K.-interop.java/key-value-mapper--raw f)))
(defn map-values
"Returns a new stream efficiently mapping values from the given one.
Unlike other mapping functions, does not mark the resulting stream for repartioning as the keys remain intact.
(map-values stream
(fn [k v]
(count v)))"
^KStream
[^KStream kstream f]
(.mapValues kstream
(K.-interop.java/value-mapper-with-key f)))
(defn fmap-kv
"Returns a new stream mapping key-values from the given one into a collection of [key value]'s (or nil).
Marks the resulting stream for repartioning.
Cf. `dvlopt.kstreams.builder`
a collection where the key is a unique token and the value is its count.
(fmap-kv stream
(fn [k v]
(reduce (fn [hmap token]
(assoc hmap
token
(inc (get hmap
token
0))))
{}
v)))"
^KStream
[^KStream kstream f]
(.flatMap kstream
(K.-interop.java/key-value-mapper--flat f)))
(defn fmap-values
"Returns a new stream mapping values from the given one into a collection of values (or nil).
Unlike `fmap-kv`, does not mark the resulting stream for repartioning as the keys remain intact.
The value is a list we want to split into individual items while filtering out nils .
(fmap-values stream
(fn [k v]
(filter some?
v)))"
^KStream
[^KStream kstream f]
(.flatMapValues kstream
(K.-interop.java/value-mapper-with-key f)))
(defn process
"Returns a new stream processing the records from the given one using a low-level processor.
For when the high-level API is not enough. It is typically used for an `fmap-kv` like behavior involving some state.
Cf. `dvlopt.kstreams.topology/add-processor`
:dvlopt.kstreams/processor.on-record may be used to explicitly forward records using the associated context.
Marks the topic for repartioning.
Cf. `dvlopt.kstreams.builder`
A map of options may be given :
:dvlopt.kstreams.store/names
List of state store names previously added to the underlying builder this processor need to access.
Cf. `dvlopt.kstreams.builder/add-store`"
(^KStream
[stream processor]
(process stream
processor
nil))
(^KStream
[^KStream stream processor options]
(.transform stream
(K.-interop.java/transformer-supplier processor)
(into-array String
(::KS.store/names options)))))
(defn process-values
"Returns a new stream efficiently proccessing the values of the given one using a low-level processor.
Unlike `process`, does not mark the resulting stream for repartioning as the keys remain intact. Also, because this
function is about processing values, there is no point forwarding records using the associated context so doing so
will throw an exception. Rather, the library maps the original value of the records to the value returned by
:dvlopt.kstreams/processor.on-record (which may be nil).
It is typically used when some state is needed.
A map of options may be given, just like in `process`."
(^KStream
[stream processor]
(process-values stream
processor
nil))
(^KStream
[^KStream stream processor options]
(.transformValues stream
(K.-interop.java/value-transformer-with-key-supplier processor)
^"[Ljava.lang.String;" (into-array String
(::KS.store/names options)))))
(defn join-with-stream
"Returns a new stream inner joining values from both given streams every time :
a) They shares the same key.
b) The difference in the timestamps of both records is <= the given interval.
Cf. `dvlopt.kafka` for descriptions of time intervals.
Hence, for the same key, several joins might happen within a single interval.
Records with a nil key or nil value are ignored.
Input streams are repartitioned if they were marked for repartitioning and a store will be generated for
each of them.
Cf. `dvlopt.kstreams.builder` for requirements related to joins
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/serializer.key
:dvlopt.kstreams/left
:dvlopt.kstreams/right
Maps which may contain value ser/de :
:dvlopt.kafka/deserializer.value
:dvlopt.kafka/serializer.value
Cf. `dvlopt.kafka` for description of serializers and deserializers.
:dvlopt.kstreams.store/retention
Cf. `dvlopt.kstreams.store`
Ex. (join-with-stream left-stream
right-stream
(fn [v-left v-right]
(str \"left = \" v-left \"and right = \" v-right))
[2 :seconds])"
(^KStream
[^KStream left-stream ^KStream right-stream f interval]
(join-with-stream left-stream
right-stream
f
interval
nil))
(^KStream
[^KStream left-stream ^KStream right-stream f interval options]
(.join left-stream
right-stream
(K.-interop.java/value-joiner f)
(K.-interop.java/join-windows interval
options)
(K.-interop.java/joined options))))
(defn left-join-with-stream
"Exactly like `join-with-stream` but the join is triggered even if there is no record with the same key yet in
the right stream for a given time window. In such case, the right value provided for the join is nil."
(^KStream
[^KStream left-stream ^KStream right-stream f interval]
(left-join-with-stream left-stream
right-stream
f
interval
nil))
(^KStream
[^KStream left-stream ^KStream right-stream f interval options]
(.leftJoin left-stream
right-stream
(K.-interop.java/value-joiner f)
(K.-interop.java/join-windows interval
options)
(K.-interop.java/joined options))))
(defn outer-join-with-stream
"Exactly like `join-with-stream` but the join is triggered even if there is no record with the same key yet in
the other stream for a given time window. In such case, the value provided for this side of the join is nil."
(^KStream
[^KStream left-stream ^KStream right-stream f interval]
(outer-join-with-stream left-stream
right-stream
f
interval
nil))
(^KStream
[^KStream left-stream ^KStream right-stream f interval options]
(.outerJoin left-stream
right-stream
(K.-interop.java/value-joiner f)
(K.-interop.java/join-windows interval
options)
(K.-interop.java/joined options))))
(defn join-with-table
"Returns a new stream inner joining the given stream with the given table. The join is triggered everytime
a new record arrives in the stream and the table contains the key of this record. This is very useful for
enriching a stream with some up-to-date information.
Records from the input stream with a nil key or value are ignored. Records from the input table with a nil
value removes the corresponding key from this table.
The input stream is repartioned if it was marked for repartioning.
A map of options may be given, just like in `join-with-stream`.
Ex. (join-with-table stream
table
(fn [v-stream v-table]
(assoc v-stream
:last-known-location
(:location v-table))))"
(^KStream
[^KStream left-stream ^KTable right-table f]
(join-with-table left-stream
right-table
f
nil))
(^KStream
[^KStream left-stream ^KTable right-table f options]
(.join left-stream
right-table
(K.-interop.java/value-joiner f)
(K.-interop.java/joined options))))
(defn left-join-with-table
"Exactly like `join-with-table` but the join is triggered even if the table does contain the key. In such case, the
right value supplied during the join in nil."
(^KStream
[^KStream left-stream ^KTable right-table f]
(left-join-with-table left-stream
right-table
f
nil))
(^KStream
[^KStream left-stream ^KTable right-table f options]
(.leftJoin left-stream
right-table
(K.-interop.java/value-joiner f)
(K.-interop.java/joined options))))
(defn join-with-global-table
"Similar to `join-with-table` but offers the following :
- Data need not to be co-partitioned.
- More efficient when a regular table is skewed (some partitions are heavily populated, some not).
- Typically more efficient that performing several joins in order to reach the same result.
- Allows for joining on a different key.
Each record of the input stream is mapped to a new key which triggers a join if the global table contains that mapped
key. The value resulting from the join is associated with the key of the original record.
Records from the input stream with a nil key or value are ignored. Records from the global table with a nil value
removes the corresponding key from this global table.
The input stream is repartitioned if it was marked for repartitioning.
(join-with-global-table stream
global-table
(fn map-k [k v]
(:country v))
(fn join [v-stream v-global-table]
(assoc v-stream
:song
(first (:top-10 v-global-table)))))"
^KStream
[^KStream left-stream ^GlobalKTable right-global-table f-map-k f-join]
(.join left-stream
right-global-table
(K.-interop.java/key-value-mapper--raw f-map-k)
(K.-interop.java/value-joiner f-join)))
(defn left-join-with-global-table
"Exactly like `join-with-global-table` but the join is triggered even if the global table does not contain the mapped
key. In such case, the right value supplied during the join is nil."
^KStream
[^KStream left-stream ^GlobalKTable right-global-table f-map-k f-join]
(.leftJoin left-stream
right-global-table
(K.-interop.java/key-value-mapper--raw f-map-k)
(K.-interop.java/value-joiner f-join)))
Grouping , windowing and aggregating
(defn group-by
"Returns a new grouped stream grouping values based on a chosen key.
Drops records leading to a nil chosen key.
Because a new key is explicitly selected, the data is repartioned.
Cf. `dvlopt.kstreams.builder` about repartioning.
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/deserializer.value
:dvlopt.kafka/serializer.key
:dvlopt.kafka/serializer.value
Cf. `dvlopt.kafka` for description of deserializers
:dvlopt.kstreams/repartition-name
Cf. `dvlopt.kstreams.builder` section \"State and repartitioning\"
Ex. (group-by stream
(fn by-country [k v]
(:country v)))"
(^KGroupedStream
[stream f]
(group-by stream
f
nil))
(^KGroupedStream
[^KStream kstream f options]
(.groupBy kstream
(K.-interop.java/key-value-mapper--raw f)
(K.-interop.java/grouped options))))
(defn group-by-key
"Exactly like `group-by` but groups directly by the original key than a selected one.
Unless the stream was marked for repartioning, this function will not repartition it as keys remain intact."
(^KGroupedStream
[^KStream stream]
(group-by-key stream
nil))
(^KGroupedStream
[^KStream stream options]
(.groupByKey stream
(K.-interop.java/serialized options))))
(defn window
"Returns a new time windowed stream windowing values by a fixed time interval for each key of the given grouped stream.
A map of options may be given :
:dvlopt.kstreams.store/retention
Cf. `dvlopt.kstreams.store`
::interval.type
Fixed time windows can behave in 3 fashions :
:hopping
Hopping windows of interval I advance by sub-interval J <= I and are aligned to the epoch, meaning they
always start at time 0. The lower bound is inclusive and upper bound is exclusive.
Ex. I = 5 seconds, J = 3 seconds (thus every window overlaps with its neighbor by 2 seconds)
:tumbling (default)
Tumbling windows are simply non-overlapping hopping windows (ie. I = J).
:sliding
Sliding windows are aligned to the timestamps of the records and not the epoch. Two records are said to
be part of the same sliding window if the difference of their timestamps <= I, where both the lower and
upper bound are inclusive.
Windows of type :hopping accepts the following additional option :
::advance-by
The J sub-interval.
Cf. `dvlopt.kafka` for description of time intervals.
`dvlopt.kstreams.store` for description of time windows.
Windows of 5 seconds advancing by 3 seconds ( thus overlapping 2 seconds ) .
(window grouped-stream
[5 :seconds]
{::interval.type :hopping
::advance-by [3 :seconds]})"
(^TimeWindowedKStream
[grouped-stream interval]
(window grouped-stream
interval
nil))
(^TimeWindowedKStream
[^KGroupedStream grouped-stream interval options]
(.windowedBy grouped-stream
(K.-interop.java/time-windows interval
options))))
(defn window-by-session
"Returns a new session windowed stream windowing values by sessions for each key of the given grouped stream.
Sessions are non-fixed intervals of activity between fixed intervals of inactivity.
Cf. `dvlopt.kafka` for description of time intervals
Cf. `dvlopt.kstreams.store` for description of sessions
A map of options may be given :
:dvlopt.kstreams.store/retention
Cf. `dvlopt.kstreams.store`"
(^SessionWindowedKStream
[grouped-stream interval]
(window-by-session grouped-stream
interval
nil))
(^SessionWindowedKStream
[^KGroupedStream grouped-stream interval options]
(.windowedBy grouped-stream
(K.-interop.java/session-windows interval
options))))
(defn reduce-values
"Returns a new table aggregating values for each key of the given grouped stream.
A map of standard table options may be given (cf. `dvlopt.kstreams.table`).
Ex. (reduce-values grouped-stream
(fn reduce [aggregated k v]
(+ aggregated
v))
(fn seed []
0))"
(^KTable
[grouped-stream fn-reduce fn-seed]
(reduce-values grouped-stream
fn-reduce
fn-seed
nil))
(^KTable
[^KGroupedStream grouped-stream fn-reduce fn-seed options]
(.aggregate grouped-stream
(K.-interop.java/initializer fn-seed)
(K.-interop.java/aggregator fn-reduce)
(K.-interop.java/materialized--kv options))))
(defn reduce-windows
"Returns a new table aggregating values for each time window of each key of the given time-windowed stream.
Cf. `reduce-values`
A map of standard table options may be given (cf. `dvlopt.kstreams.table`)."
(^KTable
[time-windowed-stream fn-reduce fn-seed]
(reduce-windows time-windowed-stream
fn-reduce
fn-seed
nil))
(^KTable
[^TimeWindowedKStream time-windowed-stream fn-reduce fn-seed options]
(.aggregate time-windowed-stream
(K.-interop.java/initializer fn-seed)
(K.-interop.java/aggregator fn-reduce)
(K.-interop.java/materialized--by-name options))))
(defn reduce-sessions
"Returns a new table aggregating values for each session of each key for the given session-windowed stream.
Sessions might merge, hence the need for a function being able to do so.
A map of standard table options may be given (cf. `dvlopt.kstreams.table`).
Ex. (reduce-sessions grouped-stream
(fn reduce [aggregated k v]
(+ aggregated
v))
(fn merge [aggregated-session-1 aggregated-session-2 k]
(+ aggregated-session-1
aggregated-session-2))
(fn seed []
0))"
(^KTable
[session-windowed-stream fn-reduce fn-merge fn-seed]
(reduce-sessions session-windowed-stream
fn-reduce
fn-merge
fn-seed
nil))
(^KTable
[^SessionWindowedKStream session-windowed-stream fn-reduce fn-merge fn-seed options]
(.aggregate session-windowed-stream
(K.-interop.java/initializer fn-seed)
(K.-interop.java/aggregator fn-reduce)
(K.-interop.java/merger fn-merge)
(K.-interop.java/materialized--by-name options))))
Transitions
(defn through-topic
"Sends each record of the given stream to a given topic and then continue streaming.
Useful when the stream was marked for repartioning. Streaming to a chosen topic before a stateful operation will avoid
automatic repartioning.
A map of options may be given :
:dvlopt.kafka/deserializer.key
:dvlopt.kafka/deserializer.value
:dvlopt.kafka/serializer.key
:dvlopt.kafka/serializer.value
Cf. `dvlopt.kafka` for description of serializers and deserializers.
:dvlopt.kstreams/select-partition
Cf. `dvlopt.kstreams.builder`"
(^KStream
[stream topic]
(through-topic stream
topic
nil))
(^KStream
[^KStream stream ^String topic options]
(.through stream
topic
(K.-interop.java/produced options))))
(defn do-kv
"For each key-value, do a side-effect and then continue streaming.
Side effects cannot be tracked by Kafka, hence they do not benefit from Kafka's processing garantees.
Ex. (do-kv stream
(fn [k v]
(println :key k :value v)))"
^KStream
[^KStream stream f]
(.peek stream
(K.-interop.java/foreach-action f)))
(defn sink-process
"Marks the end of the given stream by processing each record with a low-level processor.
Returns nil.
A map of options may be given, just like in `process`."
(^KStream
[stream processor]
(process stream
processor
nil))
(^KStream
[^KStream stream processor options]
(.process stream
(K.-interop.java/processor-supplier processor)
(into-array String
(::KS.store/names options)))))
(defn sink-topic
"Marks the end of the given stream by sending each key-value to a chosen topic.
In this case, topic might be either :
- [:always TopicName]
Where TopicName is the name of the unique topic the records will always be sent to.
- [:select (fn [record])]
Where the function is used to dynamically select a topic. All the values in the provided record refer
to what is known about the original record sourced from Kafka. As such, even ::topic might be missing.
Returns nil.
A map of options may be given, the same one as for `through-topic`."
([stream topic]
(sink-topic stream
topic
nil))
([^KStream stream topic options]
(let [options' (K.-interop.java/produced options)
[type
target] topic]
(condp identical?
type
:always (.to stream
^String target
options')
:select (.to stream
(K.-interop.java/topic-name-extractor target)
options')))))
(defn sink-do
"Marks the end of the given stream by doing a side-effect for each key-value.
Side effects cannot be tracked by Kafka, hence they do not benefit from Kafka's processing garantees.
Returns nil.
Ex. (sink-do stream
(fn [k v]
(println :key k :value v)))"
[^KStream stream f]
(.foreach stream
(K.-interop.java/foreach-action f)))
|
903dccdf8d6fd5c7dd309ed83bed522bfe075c9dd02628af8da9bf19538a9cc7 | icicle-lang/p-ambiata | Strict.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE NoImplicitPrelude #
module P.Maybe.Strict (
Maybe'(..)
, fromMaybe'
, fromMaybeM'
, isJust'
, isNothing'
, maybe'
) where
import Control.Applicative (Applicative(..), Alternative(..))
import Control.DeepSeq (NFData(..), rnf)
import Control.Monad (Monad(..), MonadPlus(..))
import Data.Bool (Bool(..))
import Data.Data (Data)
import Data.Eq (Eq)
import Data.Foldable (Foldable)
import Data.Function (flip)
import Data.Functor (Functor(..))
import Data.Ord (Ord)
import Data.Traversable (Traversable)
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Text.Show (Show)
import Text.Read (Read)
-- | Strict version of 'Data.Maybe.Maybe'.
data Maybe' a =
Just' !a
| Nothing'
deriving (Eq, Ord, Read, Show, Foldable, Traversable, Generic, Data, Typeable)
instance Functor Maybe' where
fmap _ Nothing' = Nothing'
fmap f (Just' x) = Just' (f x)
instance Applicative Maybe' where
pure = Just'
Just' f <*> m = fmap f m
Nothing' <*> _m = Nothing'
Just' _m1 *> m2 = m2
Nothing' *> _m2 = Nothing'
instance Alternative Maybe' where
empty =
Nothing'
(<|>) l r =
case l of
Nothing' ->
r
Just' _ ->
l
instance MonadPlus Maybe' where
mzero =
empty
mplus =
(<|>)
-- | Not technically a monad due to bottom, but included anyway as we don't
-- use partial functions.
instance Monad Maybe' where
(Just' x) >>= k = k x
Nothing' >>= _ = Nothing'
(>>) = (*>)
return = Just'
fail _ = Nothing'
instance NFData a => NFData (Maybe' a) where
rnf Nothing' = ()
rnf (Just' x) = rnf x
maybe' :: b -> (a -> b) -> Maybe' a -> b
maybe' n _ Nothing' = n
maybe' _ f (Just' x) = f x
isJust' :: Maybe' a -> Bool
isJust' Nothing' = False
isJust' (Just' _) = True
isNothing' :: Maybe' a -> Bool
isNothing' Nothing' = True
isNothing' (Just' _) = False
fromMaybe' :: a -> Maybe' a -> a
fromMaybe' x Nothing' = x
fromMaybe' _ (Just' y) = y
fromMaybeM' :: Applicative f => f a -> Maybe' a -> f a
fromMaybeM' = flip maybe' pure
| null | https://raw.githubusercontent.com/icicle-lang/p-ambiata/3098e411c9d521321e866b2f9637113223ef41d1/src/P/Maybe/Strict.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveTraversable #
| Strict version of 'Data.Maybe.Maybe'.
| Not technically a monad due to bottom, but included anyway as we don't
use partial functions. | # LANGUAGE DeriveFoldable #
# LANGUAGE DeriveGeneric #
# LANGUAGE NoImplicitPrelude #
module P.Maybe.Strict (
Maybe'(..)
, fromMaybe'
, fromMaybeM'
, isJust'
, isNothing'
, maybe'
) where
import Control.Applicative (Applicative(..), Alternative(..))
import Control.DeepSeq (NFData(..), rnf)
import Control.Monad (Monad(..), MonadPlus(..))
import Data.Bool (Bool(..))
import Data.Data (Data)
import Data.Eq (Eq)
import Data.Foldable (Foldable)
import Data.Function (flip)
import Data.Functor (Functor(..))
import Data.Ord (Ord)
import Data.Traversable (Traversable)
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Text.Show (Show)
import Text.Read (Read)
data Maybe' a =
Just' !a
| Nothing'
deriving (Eq, Ord, Read, Show, Foldable, Traversable, Generic, Data, Typeable)
instance Functor Maybe' where
fmap _ Nothing' = Nothing'
fmap f (Just' x) = Just' (f x)
instance Applicative Maybe' where
pure = Just'
Just' f <*> m = fmap f m
Nothing' <*> _m = Nothing'
Just' _m1 *> m2 = m2
Nothing' *> _m2 = Nothing'
instance Alternative Maybe' where
empty =
Nothing'
(<|>) l r =
case l of
Nothing' ->
r
Just' _ ->
l
instance MonadPlus Maybe' where
mzero =
empty
mplus =
(<|>)
instance Monad Maybe' where
(Just' x) >>= k = k x
Nothing' >>= _ = Nothing'
(>>) = (*>)
return = Just'
fail _ = Nothing'
instance NFData a => NFData (Maybe' a) where
rnf Nothing' = ()
rnf (Just' x) = rnf x
maybe' :: b -> (a -> b) -> Maybe' a -> b
maybe' n _ Nothing' = n
maybe' _ f (Just' x) = f x
isJust' :: Maybe' a -> Bool
isJust' Nothing' = False
isJust' (Just' _) = True
isNothing' :: Maybe' a -> Bool
isNothing' Nothing' = True
isNothing' (Just' _) = False
fromMaybe' :: a -> Maybe' a -> a
fromMaybe' x Nothing' = x
fromMaybe' _ (Just' y) = y
fromMaybeM' :: Applicative f => f a -> Maybe' a -> f a
fromMaybeM' = flip maybe' pure
|
d2cc7ab5ed63b57739f1f4099993cd9daed1b8667a6d6f2d0667c4c90cc2eb1f | mzp/coq-ruby | subtac_utils.mli | open Term
open Libnames
open Coqlib
open Environ
open Pp
open Evd
open Decl_kinds
open Topconstr
open Rawterm
open Util
open Evarutil
open Names
open Sign
val ($) : ('a -> 'b) -> 'a -> 'b
val contrib_name : string
val subtac_dir : string list
val fix_sub_module : string
val fixsub_module : string list
val init_constant : string list -> string -> constr
val init_reference : string list -> string -> global_reference
val fixsub : constr lazy_t
val well_founded_ref : global_reference lazy_t
val acc_ref : global_reference lazy_t
val acc_inv_ref : global_reference lazy_t
val fix_sub_ref : global_reference lazy_t
val fix_measure_sub_ref : global_reference lazy_t
val lt_ref : global_reference lazy_t
val lt_wf_ref : global_reference lazy_t
val refl_ref : global_reference lazy_t
val sig_ref : reference
val proj1_sig_ref : reference
val proj2_sig_ref : reference
val build_sig : unit -> coq_sigma_data
val sig_ : coq_sigma_data lazy_t
val eq_ind : constr lazy_t
val eq_rec : constr lazy_t
val eq_rect : constr lazy_t
val eq_refl : constr lazy_t
val not_ref : constr lazy_t
val and_typ : constr lazy_t
val eqdep_ind : constr lazy_t
val eqdep_rec : constr lazy_t
val jmeq_ind : unit -> constr
val jmeq_rec : unit -> constr
val jmeq_refl : unit -> constr
val boolind : constr lazy_t
val sumboolind : constr lazy_t
val natind : constr lazy_t
val intind : constr lazy_t
val existSind : constr lazy_t
val existS : coq_sigma_data lazy_t
val prod : coq_sigma_data lazy_t
val well_founded : constr lazy_t
val fix : constr lazy_t
val acc : constr lazy_t
val acc_inv : constr lazy_t
val extconstr : constr -> constr_expr
val extsort : sorts -> constr_expr
val my_print_constr : env -> constr -> std_ppcmds
val my_print_constr_expr : constr_expr -> std_ppcmds
val my_print_evardefs : evar_defs -> std_ppcmds
val my_print_context : env -> std_ppcmds
val my_print_rel_context : env -> rel_context -> std_ppcmds
val my_print_named_context : env -> std_ppcmds
val my_print_env : env -> std_ppcmds
val my_print_rawconstr : env -> rawconstr -> std_ppcmds
val my_print_tycon_type : env -> type_constraint_type -> std_ppcmds
val debug : int -> std_ppcmds -> unit
val debug_msg : int -> std_ppcmds -> std_ppcmds
val trace : std_ppcmds -> unit
val wf_relations : (constr, constr lazy_t) Hashtbl.t
type binders = local_binder list
val app_opt : ('a -> 'a) option -> 'a -> 'a
val print_args : env -> constr array -> std_ppcmds
val make_existential : loc -> ?opaque:obligation_definition_status ->
env -> evar_defs ref -> types -> constr
val make_existential_expr : loc -> 'a -> 'b -> constr_expr
val string_of_hole_kind : hole_kind -> string
val evars_of_term : evar_map -> evar_map -> constr -> evar_map
val non_instanciated_map : env -> evar_defs ref -> evar_map -> evar_map
val global_kind : logical_kind
val goal_kind : locality * goal_object_kind
val global_proof_kind : logical_kind
val goal_proof_kind : locality * goal_object_kind
val global_fix_kind : logical_kind
val goal_fix_kind : locality * goal_object_kind
val mkSubset : name -> constr -> constr -> constr
val mkProj1 : constr -> constr -> constr -> constr
val mkProj1 : constr -> constr -> constr -> constr
val mk_ex_pi1 : constr -> constr -> constr -> constr
val mk_ex_pi1 : constr -> constr -> constr -> constr
val mk_eq : types -> constr -> constr -> types
val mk_eq_refl : types -> constr -> constr
val mk_JMeq : types -> constr -> types -> constr -> types
val mk_JMeq_refl : types -> constr -> constr
val mk_conj : types list -> types
val mk_not : types -> types
val build_dependent_sum : (identifier * types) list -> Proof_type.tactic * types
val and_tac : (identifier * 'a * constr * Proof_type.tactic) list ->
((constr -> (identifier * 'a * constr * constr) list) -> Tacexpr.declaration_hook) -> unit
val destruct_ex : constr -> constr -> constr list
val id_of_name : name -> identifier
val definition_message : identifier -> std_ppcmds
val recursive_message : constant array -> std_ppcmds
val print_message : std_ppcmds -> unit
val solve_by_tac : evar_info -> Tacmach.tactic -> constr
val string_of_list : string -> ('a -> string) -> 'a list -> string
val string_of_intset : Intset.t -> string
val pr_evar_defs : evar_defs -> Pp.std_ppcmds
val tactics_call : string -> Tacexpr.glob_tactic_arg list -> Tacexpr.glob_tactic_expr
val pp_list : ('a -> Pp.std_ppcmds) -> 'a list -> Pp.std_ppcmds
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/contrib/subtac/subtac_utils.mli | ocaml | open Term
open Libnames
open Coqlib
open Environ
open Pp
open Evd
open Decl_kinds
open Topconstr
open Rawterm
open Util
open Evarutil
open Names
open Sign
val ($) : ('a -> 'b) -> 'a -> 'b
val contrib_name : string
val subtac_dir : string list
val fix_sub_module : string
val fixsub_module : string list
val init_constant : string list -> string -> constr
val init_reference : string list -> string -> global_reference
val fixsub : constr lazy_t
val well_founded_ref : global_reference lazy_t
val acc_ref : global_reference lazy_t
val acc_inv_ref : global_reference lazy_t
val fix_sub_ref : global_reference lazy_t
val fix_measure_sub_ref : global_reference lazy_t
val lt_ref : global_reference lazy_t
val lt_wf_ref : global_reference lazy_t
val refl_ref : global_reference lazy_t
val sig_ref : reference
val proj1_sig_ref : reference
val proj2_sig_ref : reference
val build_sig : unit -> coq_sigma_data
val sig_ : coq_sigma_data lazy_t
val eq_ind : constr lazy_t
val eq_rec : constr lazy_t
val eq_rect : constr lazy_t
val eq_refl : constr lazy_t
val not_ref : constr lazy_t
val and_typ : constr lazy_t
val eqdep_ind : constr lazy_t
val eqdep_rec : constr lazy_t
val jmeq_ind : unit -> constr
val jmeq_rec : unit -> constr
val jmeq_refl : unit -> constr
val boolind : constr lazy_t
val sumboolind : constr lazy_t
val natind : constr lazy_t
val intind : constr lazy_t
val existSind : constr lazy_t
val existS : coq_sigma_data lazy_t
val prod : coq_sigma_data lazy_t
val well_founded : constr lazy_t
val fix : constr lazy_t
val acc : constr lazy_t
val acc_inv : constr lazy_t
val extconstr : constr -> constr_expr
val extsort : sorts -> constr_expr
val my_print_constr : env -> constr -> std_ppcmds
val my_print_constr_expr : constr_expr -> std_ppcmds
val my_print_evardefs : evar_defs -> std_ppcmds
val my_print_context : env -> std_ppcmds
val my_print_rel_context : env -> rel_context -> std_ppcmds
val my_print_named_context : env -> std_ppcmds
val my_print_env : env -> std_ppcmds
val my_print_rawconstr : env -> rawconstr -> std_ppcmds
val my_print_tycon_type : env -> type_constraint_type -> std_ppcmds
val debug : int -> std_ppcmds -> unit
val debug_msg : int -> std_ppcmds -> std_ppcmds
val trace : std_ppcmds -> unit
val wf_relations : (constr, constr lazy_t) Hashtbl.t
type binders = local_binder list
val app_opt : ('a -> 'a) option -> 'a -> 'a
val print_args : env -> constr array -> std_ppcmds
val make_existential : loc -> ?opaque:obligation_definition_status ->
env -> evar_defs ref -> types -> constr
val make_existential_expr : loc -> 'a -> 'b -> constr_expr
val string_of_hole_kind : hole_kind -> string
val evars_of_term : evar_map -> evar_map -> constr -> evar_map
val non_instanciated_map : env -> evar_defs ref -> evar_map -> evar_map
val global_kind : logical_kind
val goal_kind : locality * goal_object_kind
val global_proof_kind : logical_kind
val goal_proof_kind : locality * goal_object_kind
val global_fix_kind : logical_kind
val goal_fix_kind : locality * goal_object_kind
val mkSubset : name -> constr -> constr -> constr
val mkProj1 : constr -> constr -> constr -> constr
val mkProj1 : constr -> constr -> constr -> constr
val mk_ex_pi1 : constr -> constr -> constr -> constr
val mk_ex_pi1 : constr -> constr -> constr -> constr
val mk_eq : types -> constr -> constr -> types
val mk_eq_refl : types -> constr -> constr
val mk_JMeq : types -> constr -> types -> constr -> types
val mk_JMeq_refl : types -> constr -> constr
val mk_conj : types list -> types
val mk_not : types -> types
val build_dependent_sum : (identifier * types) list -> Proof_type.tactic * types
val and_tac : (identifier * 'a * constr * Proof_type.tactic) list ->
((constr -> (identifier * 'a * constr * constr) list) -> Tacexpr.declaration_hook) -> unit
val destruct_ex : constr -> constr -> constr list
val id_of_name : name -> identifier
val definition_message : identifier -> std_ppcmds
val recursive_message : constant array -> std_ppcmds
val print_message : std_ppcmds -> unit
val solve_by_tac : evar_info -> Tacmach.tactic -> constr
val string_of_list : string -> ('a -> string) -> 'a list -> string
val string_of_intset : Intset.t -> string
val pr_evar_defs : evar_defs -> Pp.std_ppcmds
val tactics_call : string -> Tacexpr.glob_tactic_arg list -> Tacexpr.glob_tactic_expr
val pp_list : ('a -> Pp.std_ppcmds) -> 'a list -> Pp.std_ppcmds
|
|
447b3d38d6626a1a72a1d06f4daca845c0ae65b15df1cbfe4d689c46834664a8 | ocaml-ppx/ocamlformat | profiles2.ml | let a = aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
let b = bbbbbbbbbbbbbbbbbbvvbbb bbbvvvbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbb
| null | https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/3d1c992240f7d30bcb8151285274f44619dae197/test/passing/tests/profiles2.ml | ocaml | let a = aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
let b = bbbbbbbbbbbbbbbbbbvvbbb bbbvvvbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbb
|
|
d01ad2835ead7fa2bac73ef9f713afff4726324e804f05b5b849e18bc5a2bda0 | overtone/overtone | sc-one.clj | (ns sc-one
(:use [overtone.live]))
page 4
play({SinOsc.ar(LFNoise0.kr(12 , mul : 600 , add : 1000 ) , 0.3 ) } )
(demo 10 (sin-osc (+ 1000 (* 600 (lf-noise0:kr 12))) 0.3))
;;;;;;;;
page 5
play({RLPF.ar(Dust.ar([12 , 15 ] ) , LFNoise1.ar(1/[3,4 ] , 1500 , 1600 ) , 0.02 ) } )
(demo 10 (rlpf (dust [12 15]) (+ 1600 (* 1500 (lf-noise1 [1/3, 1/4]))) 0.02 ))
Page 6
///////////// Figure 1.1 Example of additive synthesis
;;
;;play({
var sines = 5 , speed = 6 ;
;; Mix.fill(sines,
;; {arg x;
;; Pan2.ar(
SinOsc.ar(x+1 * 100 ,
;; mul: max(0,
;; LFNoise1.kr(speed) +
Line.kr(1 , -1 , 30 )
;; )
;; ), rand2(1.0))})/sines})
;;
;;/////////////
(demo 2 (let [sines 5
speed 6]
(* (mix
(map #(pan2 (* (sin-osc (* % 100))
(max 0 (+ (lf-noise1:kr speed) (line:kr 1 -1 30))))
(- (clojure.core/rand 2) 1))
(range sines)))
(/ 1 sines))))
Page 10
///////////// Figure 1.3 Fortuitous futuristic nested music .
;;
;;(
;;play(
;; {
;; CombN.ar(
;; SinOsc.ar(
;; midicps(
LFNoise1.ar(3 , 24 ,
LFSaw.ar([5 , 5.123 ] , 0 , 3 , 80 )
;; )
;; ),
0 , 0.4 ) ,
1 , 0.3 , 2 )
;; }
;;)
;;)
;;
;;/////////////
(demo 10 (let [noise (lf-noise1 3)
saws (mul-add (lf-saw [5 5.123]) 3 80)
freq (midicps (mul-add noise 24 saws))
src (* 0.4 (sin-osc freq))]
(comb-n src 1 0.3 2)))
;;;;;;;;;
Pages 15 - 16
( PMOsc.ar(440 , MouseY.kr(1 , 550 ) , MouseX.kr(1 , 15))}.play
{ PMOsc.ar(100 , 500 , 10 , 0 , 0.5)}.play
;;
is n't an actual ugen , it 's actually a pseudo ugen defined for backwards
;;compatibility with older scsynth implementations. Its definition is as follows:
{
;;
* ar { arg , , pmindex=0.0,modphase=0.0,mul=1.0,add=0.0 ;
^SinOsc.ar(carfreq , SinOsc.ar(modfreq , modphase , pmindex),mul , add )
;; }
;;
* kr { arg carfreq , , pmindex=0.0,modphase=0.0,mul=1.0,add=0.0 ;
^SinOsc.kr(carfreq , SinOsc.kr(modfreq , modphase , pmindex),mul , add )
;; }
;;
;;}
(demo (* 0.5 (sin-osc 100 (* 10 (sin-osc 500 0)))))
;;we can use the pm-osc cgen provided by overtone:
(demo (* 0.5 (pm-osc 100 500 10 0)))
(demo 10 (pm-osc 440 (mouse-y:kr 1 550) (mouse-x:kr 1 15)))
Page 17
///////////// Figure 1.4 VCO , VCF , VCA
;;
;;(
;;{
;; Blip.ar(
;; TRand.kr( // frequency or VCO
100 , 1000 , // range
Impulse.kr(Line.kr(1 , 20 , 60 ) ) ) , // trigger
TRand.kr ( // number of harmonics or VCF
1 , 10 , // range
Impulse.kr(Line.kr(1 , 20 , 60 ) ) ) , // trigger
Linen.kr ( // , or amplitude , VCA
Impulse.kr(Line.kr(1 , 20 , 60 ) ) , // trigger
;; 0, // attack
0.5 , // sustain level
1 / Line.kr(1 , 20 , 60 ) ) // trigger
;; )
;;}.play
;;)
;;
;;/////////////
(demo 10
(let [trigger (line:kr :start 1, :end 20, :dur 60)
freq (t-rand:kr :lo 100, :hi 1000, :trig (impulse:kr trigger))
num-harmonics (t-rand:kr :lo 1, :hi 10, :trig (impulse:kr trigger))
amp (linen:kr :gate (impulse:kr trigger) :attack-time 0, :sus-level 0.5, :release-time (/ 1 trigger))]
(* amp (blip freq num-harmonics))))
;;;;;;;;;
page 19
;;
;;
;;(
;;{
r = , 10 ) ;
SinOsc.ar(mul : ) , 0 , 1 , 1 / r ) )
;;}.play
;;)
(demo 10 (let [rate (mouse-x (/ 1 3) 10)
amp (linen:kr :gate (impulse:kr rate), :attack-time 0, :sus-level 1, :release-time (/ 1 rate))]
(* amp (sin-osc))))
///////////// Example 1.5 Synthesis example with variables and statements
;;
;;(
// run this first
;;p = { // make p equal to this function
r = Line.kr(1 , 20 , 60 ) ; // rate
// r = LFTri.kr(1/10 ) * 3 + 7 ;
;;t = Impulse.kr(r); // trigger
;;// t = Dust.kr(r);
e = Linen.kr(t , 0 , 0.5 , 1 / r ) ; // envelope uses r and t
f = TRand.kr(1 , 10 , t ) ; // triggered random also uses t
// f = e + 1 * 4 ;
, f , e ) // f , and e used in Blip
;;}.play
;;)
;;
;;p.free; // run this to stop it
;;
///////////// Figure 1.6 Phase modulation with modulator as ratio
(demo 10 (let [r (line:kr :start 1, :end 20, :dur 60)
r ( + 7 ( * 3 ( lf - tri : kr 0.1 ) ) )
t (impulse:kr r)
;;t (dust:kr r)
e (linen:kr :gate t, :attack-time 0, :sus-level 0.5, :release-time (/ 1 r))
f (t-rand:kr :lo 1, :hi 10, :trig t)
f ( * 4 ( + 1 e ) )
]
(* e (blip :freq (* f 100), :numharm f))))
Page 21
///////////// Figure 1.6 Phase modulation with modulator as ratio
;;
;;(
;;{ // carrier and modulator not linked
;; r = Impulse.kr(10);
c = TRand.kr(100 , 5000 , r ) ;
m = TRand.kr(100 , 5000 , r ) ;
PMOsc.ar(c , m , 12)*0.3
;;}.play
;;)
;;
;;(
;;{
var rate = 4 , carrier , modRatio ; // declare variables
carrier = LFNoise0.kr(rate ) * 500 + 700 ;
;; modRatio = MouseX.kr(1, 2.0);
;; // modulator expressed as ratio, therefore timbre
PMOsc.ar(carrier , carrier*modRatio , 12)*0.3
;;}.play
;;)
;;
;;/////////////
(demo 10 (let [r (impulse:kr 10)
c (t-rand:kr :lo 100, :hi 5000, :trig r)
m (t-rand:kr :lo 100, :hi 5000, :trig r)]
(* [0.3 0.3] (pm-osc c m 12 0))))
(demo 10 (let [rate 4
carrier (+ 700 (* 500 (lf-noise0:kr rate)))
mod-ratio (mouse-x :min 1, :max 2)]
(* 0.3 (pm-osc carrier (* carrier mod-ratio) 12 9))))
Page 22
;;
;;SynthDef("sine", {Out.ar(0, SinOsc.ar)}).play
;;
;;SynthDef("sine", {Out.ar(1, SinOsc.ar)}).play // right channel
;;
;;// or
;;
;;(
;;SynthDef("one_tone_only", {
var out , freq = 440 ;
;; out = SinOsc.ar(freq);
;; Out.ar(0, out)
;;}).play
;;)
(defsynth left-sine [] (out 0 (sin-osc)))
(left-sine)
(stop)
(defsynth right-sine [] (out 1 (sin-osc)))
(right-sine)
(stop)
(defsynth one-tone-only [] (let [freq 440
src (sin-osc freq)]
(out 0 src)))
(one-tone-only)
(stop)
Page 23
;;/////////////
;;
;;(
SynthDef("different_tones " , {
arg freq = 440 ; // declare an argument and give it a default value
;; var out;
;; out = SinOsc.ar(freq)*0.3;
;; Out.ar(0, out)
;;}).play
;;)
;;
;;/////////////
(defsynth different-tones [freq 440]
(let [src (* 0.3 (sin-osc freq))]
(out 0 src)))
run all four , then stop all
(different-tones 550)
(different-tones 660)
(different-tones :freq 880)
(different-tones)
(stop)
;;tracking and controlling synths independently
(def a (different-tones :freq (midi->hz 64)))
(def b (different-tones :freq (midi->hz 67)))
(def c (different-tones :freq (midi->hz 72)))
(ctl a :freq (midi->hz 65))
(ctl c :freq (midi->hz 71))
(do
(ctl a :freq (midi->hz 64))
(ctl c :freq (midi->hz 72)))
(do
(kill a)
(kill b)
(kill c))
Page 24
;;
///////////// Figure 1.7 Synth definition
;;
;;(
//run this first
;;SynthDef("PMCrotale", {
arg midi = 60 , tone = 3 , art = 1 , amp = 0.8 , pan = 0 ;
;;var env, out, mod, freq;
;;
;;freq = midi.midicps;
env = Env.perc(0 , art ) ;
mod = 5 + ( 1 / IRand(2 , 6 ) ) ;
;;
;;out = PMOsc.ar(freq, mod*freq,
pmindex : EnvGen.kr(env , : art , levelScale : tone ) ,
mul : EnvGen.kr(env , : art , levelScale : 0.3 ) ) ;
;;
;;out = Pan2.ar(out, pan);
;;
out = out * EnvGen.kr(env , : 1.3*art ,
levelScale : Rand(0.1 , 0.5 ) , doneAction:2 ) ;
, out ) ; //Out.ar(bus , out ) ;
;;
;;}).add;
;;)
(defsynth pmc-rotale [midi 60 tone 3 art 1 amp 0.8 pan 0]
(let [freq (midicps midi)
env (perc 0 art)
mod (+ 5 (/ 1 (i-rand 2 6)))
src (* (pm-osc freq (* mod freq) (env-gen:kr env :time-scale art, :level-scale tone) 0)
(env-gen:kr env :time-scale art, :level-scale 0.3))
src (pan2 src pan)
src (* src (env-gen:kr env :time-scale (* art 1.3) :level-scale (ranged-rand 0.1 0.5) :action FREE))]
(out 0 src)))
Synth("PMCrotale " , [ " midi " , rrand(48 , ) , " tone " , , 6 ) ] )
(pmc-rotale :midi (ranged-rand 48 72) :tone (ranged-rand 1 6))
Page 25
;;
;;~houston = Buffer.read(s, "sounds/a11wlk01-44_1.aiff");
= Buffer.read(s , " sounds / a11wlk01.wav " ) ;
;;
;;{PlayBuf.ar(1, ~houston)}.play;
;;{PlayBuf.ar(1, ~chooston)}.play;
this assumes you have a separate install of SuperCollider and
;;you're running OS X. Feel free to change the following audio paths
;;to any other audio file on your disk...
(def houston (load-sample "/Applications/SuperCollider/sounds/a11wlk01-44_1.aiff"))
(def chooston (load-sample "/Applications/SuperCollider/sounds/a11wlk01.wav"))
(demo 4 (play-buf 1 houston))
(demo 5 (play-buf 1 chooston))
Page 26
;;
;;[~houston.bufnum, ~houston.numChannels, ~houston.path, ~houston.numFrames];
[ , ~chooston.numChannels , ~chooston.path , ~chooston.numFrames ] ;
;;samples are represented as standard clojure maps
houston
chooston
;;(
;;{
;; var rate, trigger, frames;
;; frames = ~houston.numFrames;
;;
rate = [ 1 , 1.01 ] ;
;; trigger = Impulse.kr(rate);
PlayBuf.ar(1 , ~houston , 1 , trigger , frames * Line.kr(0 , 1 , 60 ) ) *
EnvGen.kr(Env.linen(0.01 , 0.96 , 0.01 ) , trigger ) * rate ;
;;}.play
;;)
(demo 60 (let [frames (num-frames houston)
rate [1 1.01]
trigger (impulse:kr rate)
src (play-buf 1 houston 1 trigger (* frames (line:kr 0 1 60)))
env (env-gen:kr (lin 0.01 0.96 0.01) trigger)]
(* src env rate)))
;; note how the envelope is used to stop clicking between segments. Contrast with the following
(demo 5 (let [frames (num-frames houston)
rate [1 1.01]
trigger (impulse:kr rate)
src (play-buf 1 houston 1 trigger (* frames (line:kr 0 1 60)))]
(* src rate)))
;;( // speed and direction change
;;{
;; var speed, direction;
speed = LFNoise0.kr(12 ) * 0.2 + 1 ;
;; direction = ]LFClipNoise.kr(1/3);
PlayBuf.ar(1 , ~houston , ( speed * direction ) , loop : 1 ) ;
;;}.play
;;)
(demo 5 (let [speed (+ 1 (* 0.2 (lf-noise0:kr 12)))
direction (lf-clip-noise:kr 1/3)]
(play-buf 1 houston (* speed direction) :loop 1)))
Page 27
;;( // if these haven't been used they will hold 0
~kbus1 = Bus.control ; // a control bus
;;~kbus2 = Bus.control; // a control bus
;;{
;; var speed, direction;
speed = In.kr(~kbus1 , 1 ) * 0.2 + 1 ;
;; direction = In.kr(~kbus2);
PlayBuf.ar(1 , , ( speed * direction ) , loop : 1 ) ;
;;}.play
;;)
;;
;;(
;;// now start the controls
;;{Out.kr(~kbus1, LFNoise0.kr(12))}.play;
{ Out.kr(~kbus2 , ;
;;)
// Now start the second buffer with the same control input buses ,
;;// but send it to the right channel using Out.ar(1 etc.
;;
;;(
;;{
;; var speed, direction;
speed = In.kr(~kbus1 , 1 ) * 0.2 + 1 ;
;; direction = In.kr(~kbus2);
Out.ar(1 , PlayBuf.ar(1 , ~houston , ( speed * direction ) , loop : 1 ) ) ;
;;}.play;
;;)
(def kbus1 (control-bus))
(def kbus2 (control-bus))
(defsynth src []
(let [speed (+ 1 (* 0.2 (in:kr kbus1 1)))
direction (in:kr kbus2)]
(out 0 (play-buf 1 chooston (* speed direction) :loop 1))))
(defsynth control1 []
(out:kr kbus1 (lf-noise0:kr 12)))
(defsynth control2 []
(out:kr kbus2 (lf-clip-noise:kr 1/4)))
(defsynth player []
(let [speed (+ 1 (* 0.2 (in:kr kbus1 1)))
direction (in:kr kbus2)]
(out 1 (play-buf 1 houston (* speed direction) :loop 1))))
(do
(src)
(control1)
(control2)
(player))
(stop)
Page 28
;;~kbus3 = Bus.control;
;;~kbus4 = Bus.control;
{ Out.kr(~kbus3 , SinOsc.kr(3).range(340 , 540))}.play ;
{ Out.kr(~kbus4 , , 640))}.play ;
SynthDef("Switch " , { arg freq = 440 ; , SinOsc.ar(freq , 0 , 0.3))}).add
;;x = Synth("Switch");
;;x.map(\freq, ~kbus3)
;;x.map(\freq, ~kbus4)
(do
(def kbus3 (control-bus))
(def kbus4 (control-bus))
(defsynth wave-ctl [] (out:kr kbus3 (lin-lin (sin-osc:kr 1) -1 1 340 540)))
(defsynth pulse-ctl [] (out:kr kbus4 (lin-lin (sin-osc:kr 1) -1 1 240 640)))
(defsynth switch [freq 440]
(out 0 (sin-osc:ar freq 0 0.3)))
(def s (switch))
(def w (wave-ctl))
(def p (pulse-ctl)))
;;try evaling these
(map-ctl s :freq kbus3)
(map-ctl s :freq kbus4)
(stop)
Page 29
;;(
;;{
;; Out.ar(0,
( PlayBuf.ar(1 , ~houston , loop : 1 ) *
SinOsc.ar(LFNoise0.kr(12 , : 500 , add : 600 ) ) ,
0.5 )
;; )
;;}.play
;;)
(demo 10 (pan2 (* (play-buf 1 houston :loop 1)
(sin-osc (+ 600 (* 500 (lf-noise0:kr 12)))))
0.5))
;;
;;(
;;{
;; var source, delay;
source = PlayBuf.ar(1 , , loop : 1 ) ;
delay = AllpassC.ar(source , 2 , [ 0.65 , 1.15 ] , 10 ) ;
;; Out.ar(0, Pan2.ar(source) + delay)
;;}.play
;;)
(demo 10 (let [source (play-buf 1 chooston :loop 1)
delay (allpass-c source 2 [0.65 1.15] 10)]
(+ delay (pan2 source))))
;;//Create and name buses
~delay = Bus.audio(s , 2 ) ;
~mod = Bus.audio(s , 2 ) ;
~gate = Bus.audio(s , 2 ) ;
;;~k5 = Bus.control;
;;
;;~controlSyn= {Out.kr(~k5, LFNoise0.kr(4))}.play //start the control
;;
;;// Start the last item in the chain, the delay
~delaySyn = { Out.ar(0 , AllpassC.ar(In.ar(~delay , 2 ) , 2 , [ 0.65 , 1.15 ] , 10))}.play(~controlSyn , addAction : \addAfter ) ;
;;
;;// Start the next to last item, the modulation
~modSyn = { Out.ar(~delay , In.ar(~mod , 2 ) * SinOsc.ar(In.kr(~k5 ) * 500 + 1100))}.play(~delaySyn , addAction : \addBefore ) ;
;;
//Start the third to last item , the gate
~gateSyn = { Out.ar([0 , ~mod ] , In.ar(~gate , 2 ) * max(0 , In.kr(~k5)))}.play(~modSyn , addAction : \addBefore ) ;
;;
//make a group for the PlayBuf synths at the head of the chain
~pbGroup = ) ;
;;
// Start one buffer . Since we add to the group , we know where it will go
{ Out.ar(~gate , Pan2.ar(PlayBuf.ar(1 , ~houston , loop : 1 ) , 0.5))}.play(~pbGroup ) ;
;;
;;// Start the other
{ Out.ar(~gate , Pan2.ar(PlayBuf.ar(1 , , loop : 1 ) , -0.5))}.play(~pbGroup ) ;
(do
(def delay-b (audio-bus 2))
(def mod-b (audio-bus 2))
(def gate-b (audio-bus 2))
(def k5-b (control-bus))
(defsynth control-syn [] (out:kr k5-b (lf-noise0:kr 4)))
(def c-syn (control-syn))
(defsynth delay-syn [] (out:ar 0 (allpass-c (in delay-b 2) 2 [0.65 1.15] 10)))
(def d-syn (delay-syn [ :after c-syn]))
(defsynth mod-syn [] (out delay-b (* (in mod-b 2) (sin-osc (+ 1100 (* 500 (in:kr k5-b)))))))
(def m-syn (mod-syn [:before d-syn]))
(defsynth gate-syn [] (out [0 mod-b] (* (in gate-b 2) (max 0 (in:kr k5-b)))))
(def g-syn (gate-syn [:before m-syn]))
(def pb-group (group :before c-syn))
(defsynth hous [] (out gate-b (pan2 (play-buf 1 houston :loop 1) 0.5)))
(defsynth choos [] (out gate-b (pan2 (play-buf 1 chooston :loop 1) -0.5))))
(hous [:tail pb-group])
(choos [:tail pb-group])
(stop)
Page 32
// This uses the PMCrotale synth definition
;;(
a = [ " C " , " C # " , " D " , " Eb " , " E " , " F " , " F # " , " G " , " Ab " , " A " , " Bb " , " B " ] ;
;;"event, midi, pitch, octave".postln;
;;r = Task({
;; inf.do({ arg count;
var midi , oct , density ;
density = 1.0 ;
// density = 0.7 ;
// density = 0.3 ;
midi = [ 0 , 2 , 4 , 7 , 9].choose ;
// midi = [ 0 , 2 , 4 , 5 , 7 , 9 , 11].choose
// midi = [ 0 , 2 , 3 , 5 , 6 , 8 , 9 , 11].choose ;
// midi = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11].choose ;
oct = [ 48 , 60 , 72].choose ;
;; if(density.coin,
;; { // true action
;; "".postln;
[ midi + oct , a.wrapAt(midi ) ,
;; (oct/12).round(1)].post;
;; Synth("PMCrotale",
[ " midi " , midi + oct , " tone " , , 7 ) ,
" art " , rrand(0.3 , 2.0 ) , " amp " , rrand(0.3 , 0.6 ) , " pan " , 1.0.rand2 ] ) ;
;; }, {["rest"].post}); // false action
;; 0.2.wait;
;; });
;;}).start
;; )
(def cont (atom true))
(do
(def a [:C :C# :D :Eb :E :F :F# :G :Ab :A :Bb :B])
(future
(loop []
(let [density 1
midi (choose [0 2 4 7 9])
oct (choose [48 60 72])]
(if (weighted-coin density)
(do
(println "")
(println [(+ midi oct) (nth (cycle a) midi) (round-to (/ oct 12) 1)])
(pmc-rotale :midi (+ midi oct)
:tone (ranged-rand 1 7)
:art (ranged-rand 0.3 2.0)
:amp (ranged-rand 0.3 0.6)
:pan (ranged-rand -1 1)))
(println "rest"))
(Thread/sleep 200)
(when @cont (recur))))))
;; to stop
(reset! cont false)
Page 36
;;// Mix down a few of them tuned to harmonics
;;
;;(
;;{
var fund = 220 ;
;; Mix.ar(
;; [
SinOsc.ar(220 , : max(0 , LFNoise1.kr(12 ) ) ) ,
SinOsc.ar(440 , : max(0 , LFNoise1.kr(12 ) ) ) * 1/2 ,
SinOsc.ar(660 , mul : max(0 , LFNoise1.kr(12 ) ) ) * 1/3 ,
SinOsc.ar(880 , : max(0 , LFNoise1.kr(12 ) ) ) * 1/4 ,
SinOsc.ar(1110 , mul : max(0 , LFNoise1.kr(12 ) ) ) * 1/5 ,
SinOsc.ar(1320 , : max(0 , LFNoise1.kr(12 ) ) ) * 1/6
;; ]
) * 0.3
;;}.play
;;)
(demo 15
(* 0.3
(+ (* (sin-osc 220) (max 0 (lf-noise1:kr 12)) 1)
(* (sin-osc 440) (max 0 (lf-noise1:kr 12)) 1/2)
(* (sin-osc 660) (max 0 (lf-noise1:kr 12)) 1/3)
(* (sin-osc 880) (max 0 (lf-noise1:kr 12)) 1/4 )
(* (sin-osc 1110) (max 0 (lf-noise1:kr 12)) 1/5)
(* (sin-osc 1320) (max 0 (lf-noise1:kr 12)) 1/6))))
;; or the more compact but equivalent:
(demo 15
(let [freqs [220 440 660 880 1110 1320]
muls [1 1/2 1/3 1/4 1/5 1/6]
mk-sin #(* (sin-osc %1) (max 0 (lf-noise1 12)) %2)
sins (map mk-sin freqs muls)]
(* (mix sins) 0.3)))
Page 37
;;// And a patch
;;(
;;{
;; Mix.ar(
Array.fill(12 ,
;; {arg count;
;; var harm;
harm = count + 1 * 110 ; //remember precedence ; count + 1 , then * 110
SinOsc.ar(harm , : max([0 , 0 ] , SinOsc.kr(count + 1/4 ) ) ) * 1/(count + 1 )
;; })
) * 0.7}.play
;;)
(demo 15
(* 0.7
(mix
(for [count (range 12)]
(let [harm (* (inc count) 110)]
(* (sin-osc harm)
(max [0 0] (sin-osc:kr (/ (inc count) 4)))
(/ 1 (inc count))))))))
Page 38
;;(
;;{
;; var scale, specs, freqs, amps, rings,
numRes = 5 , bells = 20 , pan ;
scale = [ 60 , 62 , 64 , 67 , 69].midicps ;
Mix.fill(bells , {
;; freqs = Array.fill(numRes, {rrand(1, 15)*(scale.choose)});
amps = Array.fill(numRes , { rrand(0.3 , 0.9 ) } ) ;
rings = Array.fill(numRes , { rrand(1.0 , 4.0 ) } ) ;
specs = [ freqs , amps , rings].round(0.01 ) ;
specs.postln ;
pan = ( ) ) * 2).softclip ;
(
Klank.ar(`specs ,
Dust.ar(1/6 , 0.03 ) ) ,
;; pan)
;; })
;;}.play;
;;)
(demo 10
(let [num-res 5
bells 20
scale (map midi->hz [60 62 64 67 69])
mk-bell (fn [] (let [freqs (repeatedly num-res #(* (ranged-rand 1 5) (choose scale)))
amps (repeatedly num-res #(ranged-rand 0.3 0.9))
rings (repeatedly num-res #(ranged-rand 1 4))
specs [freqs amps rings]
pan (softclip (* 2 (lf-noise1:kr (ranged-rand 3 6))))]
(pan2 (klank specs (* 0.03 (dust (/ 1 6)) ))
pan)))]
(out 0 (mix (repeatedly bells mk-bell)))))
| null | https://raw.githubusercontent.com/overtone/overtone/02f8cdd2817bf810ff390b6f91d3e84d61afcc85/docs/sc-book/sc-one.clj | clojure |
play({
Mix.fill(sines,
{arg x;
Pan2.ar(
mul: max(0,
LFNoise1.kr(speed) +
)
), rand2(1.0))})/sines})
/////////////
(
play(
{
CombN.ar(
SinOsc.ar(
midicps(
)
),
}
)
)
/////////////
compatibility with older scsynth implementations. Its definition is as follows:
}
}
}
we can use the pm-osc cgen provided by overtone:
(
{
Blip.ar(
TRand.kr( // frequency or VCO
0, // attack
)
}.play
)
/////////////
(
{
}.play
)
(
p = { // make p equal to this function
// rate
t = Impulse.kr(r); // trigger
// t = Dust.kr(r);
// envelope uses r and t
// triggered random also uses t
}.play
)
p.free; // run this to stop it
t (dust:kr r)
(
{ // carrier and modulator not linked
r = Impulse.kr(10);
}.play
)
(
{
// declare variables
modRatio = MouseX.kr(1, 2.0);
// modulator expressed as ratio, therefore timbre
}.play
)
/////////////
SynthDef("sine", {Out.ar(0, SinOsc.ar)}).play
SynthDef("sine", {Out.ar(1, SinOsc.ar)}).play // right channel
// or
(
SynthDef("one_tone_only", {
out = SinOsc.ar(freq);
Out.ar(0, out)
}).play
)
/////////////
(
// declare an argument and give it a default value
var out;
out = SinOsc.ar(freq)*0.3;
Out.ar(0, out)
}).play
)
/////////////
tracking and controlling synths independently
(
SynthDef("PMCrotale", {
var env, out, mod, freq;
freq = midi.midicps;
out = PMOsc.ar(freq, mod*freq,
out = Pan2.ar(out, pan);
//Out.ar(bus , out ) ;
}).add;
)
~houston = Buffer.read(s, "sounds/a11wlk01-44_1.aiff");
{PlayBuf.ar(1, ~houston)}.play;
{PlayBuf.ar(1, ~chooston)}.play;
you're running OS X. Feel free to change the following audio paths
to any other audio file on your disk...
[~houston.bufnum, ~houston.numChannels, ~houston.path, ~houston.numFrames];
samples are represented as standard clojure maps
(
{
var rate, trigger, frames;
frames = ~houston.numFrames;
trigger = Impulse.kr(rate);
}.play
)
note how the envelope is used to stop clicking between segments. Contrast with the following
( // speed and direction change
{
var speed, direction;
direction = ]LFClipNoise.kr(1/3);
}.play
)
( // if these haven't been used they will hold 0
// a control bus
~kbus2 = Bus.control; // a control bus
{
var speed, direction;
direction = In.kr(~kbus2);
}.play
)
(
// now start the controls
{Out.kr(~kbus1, LFNoise0.kr(12))}.play;
)
// but send it to the right channel using Out.ar(1 etc.
(
{
var speed, direction;
direction = In.kr(~kbus2);
}.play;
)
~kbus3 = Bus.control;
~kbus4 = Bus.control;
, SinOsc.ar(freq , 0 , 0.3))}).add
x = Synth("Switch");
x.map(\freq, ~kbus3)
x.map(\freq, ~kbus4)
try evaling these
(
{
Out.ar(0,
)
}.play
)
(
{
var source, delay;
Out.ar(0, Pan2.ar(source) + delay)
}.play
)
//Create and name buses
~k5 = Bus.control;
~controlSyn= {Out.kr(~k5, LFNoise0.kr(4))}.play //start the control
// Start the last item in the chain, the delay
// Start the next to last item, the modulation
// Start the other
(
"event, midi, pitch, octave".postln;
r = Task({
inf.do({ arg count;
if(density.coin,
{ // true action
"".postln;
(oct/12).round(1)].post;
Synth("PMCrotale",
}, {["rest"].post}); // false action
0.2.wait;
});
}).start
)
to stop
// Mix down a few of them tuned to harmonics
(
{
Mix.ar(
[
]
}.play
)
or the more compact but equivalent:
// And a patch
(
{
Mix.ar(
{arg count;
var harm;
//remember precedence ; count + 1 , then * 110
})
)
(
{
var scale, specs, freqs, amps, rings,
freqs = Array.fill(numRes, {rrand(1, 15)*(scale.choose)});
pan)
})
}.play;
) | (ns sc-one
(:use [overtone.live]))
page 4
play({SinOsc.ar(LFNoise0.kr(12 , mul : 600 , add : 1000 ) , 0.3 ) } )
(demo 10 (sin-osc (+ 1000 (* 600 (lf-noise0:kr 12))) 0.3))
page 5
play({RLPF.ar(Dust.ar([12 , 15 ] ) , LFNoise1.ar(1/[3,4 ] , 1500 , 1600 ) , 0.02 ) } )
(demo 10 (rlpf (dust [12 15]) (+ 1600 (* 1500 (lf-noise1 [1/3, 1/4]))) 0.02 ))
Page 6
///////////// Figure 1.1 Example of additive synthesis
SinOsc.ar(x+1 * 100 ,
Line.kr(1 , -1 , 30 )
(demo 2 (let [sines 5
speed 6]
(* (mix
(map #(pan2 (* (sin-osc (* % 100))
(max 0 (+ (lf-noise1:kr speed) (line:kr 1 -1 30))))
(- (clojure.core/rand 2) 1))
(range sines)))
(/ 1 sines))))
Page 10
///////////// Figure 1.3 Fortuitous futuristic nested music .
LFNoise1.ar(3 , 24 ,
LFSaw.ar([5 , 5.123 ] , 0 , 3 , 80 )
0 , 0.4 ) ,
1 , 0.3 , 2 )
(demo 10 (let [noise (lf-noise1 3)
saws (mul-add (lf-saw [5 5.123]) 3 80)
freq (midicps (mul-add noise 24 saws))
src (* 0.4 (sin-osc freq))]
(comb-n src 1 0.3 2)))
Pages 15 - 16
( PMOsc.ar(440 , MouseY.kr(1 , 550 ) , MouseX.kr(1 , 15))}.play
{ PMOsc.ar(100 , 500 , 10 , 0 , 0.5)}.play
is n't an actual ugen , it 's actually a pseudo ugen defined for backwards
{
^SinOsc.ar(carfreq , SinOsc.ar(modfreq , modphase , pmindex),mul , add )
^SinOsc.kr(carfreq , SinOsc.kr(modfreq , modphase , pmindex),mul , add )
(demo (* 0.5 (sin-osc 100 (* 10 (sin-osc 500 0)))))
(demo (* 0.5 (pm-osc 100 500 10 0)))
(demo 10 (pm-osc 440 (mouse-y:kr 1 550) (mouse-x:kr 1 15)))
Page 17
///////////// Figure 1.4 VCO , VCF , VCA
100 , 1000 , // range
Impulse.kr(Line.kr(1 , 20 , 60 ) ) ) , // trigger
TRand.kr ( // number of harmonics or VCF
1 , 10 , // range
Impulse.kr(Line.kr(1 , 20 , 60 ) ) ) , // trigger
Linen.kr ( // , or amplitude , VCA
Impulse.kr(Line.kr(1 , 20 , 60 ) ) , // trigger
0.5 , // sustain level
1 / Line.kr(1 , 20 , 60 ) ) // trigger
(demo 10
(let [trigger (line:kr :start 1, :end 20, :dur 60)
freq (t-rand:kr :lo 100, :hi 1000, :trig (impulse:kr trigger))
num-harmonics (t-rand:kr :lo 1, :hi 10, :trig (impulse:kr trigger))
amp (linen:kr :gate (impulse:kr trigger) :attack-time 0, :sus-level 0.5, :release-time (/ 1 trigger))]
(* amp (blip freq num-harmonics))))
page 19
SinOsc.ar(mul : ) , 0 , 1 , 1 / r ) )
(demo 10 (let [rate (mouse-x (/ 1 3) 10)
amp (linen:kr :gate (impulse:kr rate), :attack-time 0, :sus-level 1, :release-time (/ 1 rate))]
(* amp (sin-osc))))
///////////// Example 1.5 Synthesis example with variables and statements
// run this first
, f , e ) // f , and e used in Blip
///////////// Figure 1.6 Phase modulation with modulator as ratio
(demo 10 (let [r (line:kr :start 1, :end 20, :dur 60)
r ( + 7 ( * 3 ( lf - tri : kr 0.1 ) ) )
t (impulse:kr r)
e (linen:kr :gate t, :attack-time 0, :sus-level 0.5, :release-time (/ 1 r))
f (t-rand:kr :lo 1, :hi 10, :trig t)
f ( * 4 ( + 1 e ) )
]
(* e (blip :freq (* f 100), :numharm f))))
Page 21
///////////// Figure 1.6 Phase modulation with modulator as ratio
PMOsc.ar(c , m , 12)*0.3
PMOsc.ar(carrier , carrier*modRatio , 12)*0.3
(demo 10 (let [r (impulse:kr 10)
c (t-rand:kr :lo 100, :hi 5000, :trig r)
m (t-rand:kr :lo 100, :hi 5000, :trig r)]
(* [0.3 0.3] (pm-osc c m 12 0))))
(demo 10 (let [rate 4
carrier (+ 700 (* 500 (lf-noise0:kr rate)))
mod-ratio (mouse-x :min 1, :max 2)]
(* 0.3 (pm-osc carrier (* carrier mod-ratio) 12 9))))
Page 22
(defsynth left-sine [] (out 0 (sin-osc)))
(left-sine)
(stop)
(defsynth right-sine [] (out 1 (sin-osc)))
(right-sine)
(stop)
(defsynth one-tone-only [] (let [freq 440
src (sin-osc freq)]
(out 0 src)))
(one-tone-only)
(stop)
Page 23
SynthDef("different_tones " , {
(defsynth different-tones [freq 440]
(let [src (* 0.3 (sin-osc freq))]
(out 0 src)))
run all four , then stop all
(different-tones 550)
(different-tones 660)
(different-tones :freq 880)
(different-tones)
(stop)
(def a (different-tones :freq (midi->hz 64)))
(def b (different-tones :freq (midi->hz 67)))
(def c (different-tones :freq (midi->hz 72)))
(ctl a :freq (midi->hz 65))
(ctl c :freq (midi->hz 71))
(do
(ctl a :freq (midi->hz 64))
(ctl c :freq (midi->hz 72)))
(do
(kill a)
(kill b)
(kill c))
Page 24
///////////// Figure 1.7 Synth definition
//run this first
pmindex : EnvGen.kr(env , : art , levelScale : tone ) ,
out = out * EnvGen.kr(env , : 1.3*art ,
(defsynth pmc-rotale [midi 60 tone 3 art 1 amp 0.8 pan 0]
(let [freq (midicps midi)
env (perc 0 art)
mod (+ 5 (/ 1 (i-rand 2 6)))
src (* (pm-osc freq (* mod freq) (env-gen:kr env :time-scale art, :level-scale tone) 0)
(env-gen:kr env :time-scale art, :level-scale 0.3))
src (pan2 src pan)
src (* src (env-gen:kr env :time-scale (* art 1.3) :level-scale (ranged-rand 0.1 0.5) :action FREE))]
(out 0 src)))
Synth("PMCrotale " , [ " midi " , rrand(48 , ) , " tone " , , 6 ) ] )
(pmc-rotale :midi (ranged-rand 48 72) :tone (ranged-rand 1 6))
Page 25
this assumes you have a separate install of SuperCollider and
(def houston (load-sample "/Applications/SuperCollider/sounds/a11wlk01-44_1.aiff"))
(def chooston (load-sample "/Applications/SuperCollider/sounds/a11wlk01.wav"))
(demo 4 (play-buf 1 houston))
(demo 5 (play-buf 1 chooston))
Page 26
houston
chooston
PlayBuf.ar(1 , ~houston , 1 , trigger , frames * Line.kr(0 , 1 , 60 ) ) *
(demo 60 (let [frames (num-frames houston)
rate [1 1.01]
trigger (impulse:kr rate)
src (play-buf 1 houston 1 trigger (* frames (line:kr 0 1 60)))
env (env-gen:kr (lin 0.01 0.96 0.01) trigger)]
(* src env rate)))
(demo 5 (let [frames (num-frames houston)
rate [1 1.01]
trigger (impulse:kr rate)
src (play-buf 1 houston 1 trigger (* frames (line:kr 0 1 60)))]
(* src rate)))
(demo 5 (let [speed (+ 1 (* 0.2 (lf-noise0:kr 12)))
direction (lf-clip-noise:kr 1/3)]
(play-buf 1 houston (* speed direction) :loop 1)))
Page 27
// Now start the second buffer with the same control input buses ,
(def kbus1 (control-bus))
(def kbus2 (control-bus))
(defsynth src []
(let [speed (+ 1 (* 0.2 (in:kr kbus1 1)))
direction (in:kr kbus2)]
(out 0 (play-buf 1 chooston (* speed direction) :loop 1))))
(defsynth control1 []
(out:kr kbus1 (lf-noise0:kr 12)))
(defsynth control2 []
(out:kr kbus2 (lf-clip-noise:kr 1/4)))
(defsynth player []
(let [speed (+ 1 (* 0.2 (in:kr kbus1 1)))
direction (in:kr kbus2)]
(out 1 (play-buf 1 houston (* speed direction) :loop 1))))
(do
(src)
(control1)
(control2)
(player))
(stop)
Page 28
(do
(def kbus3 (control-bus))
(def kbus4 (control-bus))
(defsynth wave-ctl [] (out:kr kbus3 (lin-lin (sin-osc:kr 1) -1 1 340 540)))
(defsynth pulse-ctl [] (out:kr kbus4 (lin-lin (sin-osc:kr 1) -1 1 240 640)))
(defsynth switch [freq 440]
(out 0 (sin-osc:ar freq 0 0.3)))
(def s (switch))
(def w (wave-ctl))
(def p (pulse-ctl)))
(map-ctl s :freq kbus3)
(map-ctl s :freq kbus4)
(stop)
Page 29
( PlayBuf.ar(1 , ~houston , loop : 1 ) *
SinOsc.ar(LFNoise0.kr(12 , : 500 , add : 600 ) ) ,
0.5 )
(demo 10 (pan2 (* (play-buf 1 houston :loop 1)
(sin-osc (+ 600 (* 500 (lf-noise0:kr 12)))))
0.5))
(demo 10 (let [source (play-buf 1 chooston :loop 1)
delay (allpass-c source 2 [0.65 1.15] 10)]
(+ delay (pan2 source))))
//Start the third to last item , the gate
//make a group for the PlayBuf synths at the head of the chain
// Start one buffer . Since we add to the group , we know where it will go
(do
(def delay-b (audio-bus 2))
(def mod-b (audio-bus 2))
(def gate-b (audio-bus 2))
(def k5-b (control-bus))
(defsynth control-syn [] (out:kr k5-b (lf-noise0:kr 4)))
(def c-syn (control-syn))
(defsynth delay-syn [] (out:ar 0 (allpass-c (in delay-b 2) 2 [0.65 1.15] 10)))
(def d-syn (delay-syn [ :after c-syn]))
(defsynth mod-syn [] (out delay-b (* (in mod-b 2) (sin-osc (+ 1100 (* 500 (in:kr k5-b)))))))
(def m-syn (mod-syn [:before d-syn]))
(defsynth gate-syn [] (out [0 mod-b] (* (in gate-b 2) (max 0 (in:kr k5-b)))))
(def g-syn (gate-syn [:before m-syn]))
(def pb-group (group :before c-syn))
(defsynth hous [] (out gate-b (pan2 (play-buf 1 houston :loop 1) 0.5)))
(defsynth choos [] (out gate-b (pan2 (play-buf 1 chooston :loop 1) -0.5))))
(hous [:tail pb-group])
(choos [:tail pb-group])
(stop)
Page 32
// This uses the PMCrotale synth definition
// midi = [ 0 , 2 , 4 , 5 , 7 , 9 , 11].choose
[ midi + oct , a.wrapAt(midi ) ,
[ " midi " , midi + oct , " tone " , , 7 ) ,
(def cont (atom true))
(do
(def a [:C :C# :D :Eb :E :F :F# :G :Ab :A :Bb :B])
(future
(loop []
(let [density 1
midi (choose [0 2 4 7 9])
oct (choose [48 60 72])]
(if (weighted-coin density)
(do
(println "")
(println [(+ midi oct) (nth (cycle a) midi) (round-to (/ oct 12) 1)])
(pmc-rotale :midi (+ midi oct)
:tone (ranged-rand 1 7)
:art (ranged-rand 0.3 2.0)
:amp (ranged-rand 0.3 0.6)
:pan (ranged-rand -1 1)))
(println "rest"))
(Thread/sleep 200)
(when @cont (recur))))))
(reset! cont false)
Page 36
SinOsc.ar(220 , : max(0 , LFNoise1.kr(12 ) ) ) ,
SinOsc.ar(440 , : max(0 , LFNoise1.kr(12 ) ) ) * 1/2 ,
SinOsc.ar(660 , mul : max(0 , LFNoise1.kr(12 ) ) ) * 1/3 ,
SinOsc.ar(880 , : max(0 , LFNoise1.kr(12 ) ) ) * 1/4 ,
SinOsc.ar(1110 , mul : max(0 , LFNoise1.kr(12 ) ) ) * 1/5 ,
SinOsc.ar(1320 , : max(0 , LFNoise1.kr(12 ) ) ) * 1/6
) * 0.3
(demo 15
(* 0.3
(+ (* (sin-osc 220) (max 0 (lf-noise1:kr 12)) 1)
(* (sin-osc 440) (max 0 (lf-noise1:kr 12)) 1/2)
(* (sin-osc 660) (max 0 (lf-noise1:kr 12)) 1/3)
(* (sin-osc 880) (max 0 (lf-noise1:kr 12)) 1/4 )
(* (sin-osc 1110) (max 0 (lf-noise1:kr 12)) 1/5)
(* (sin-osc 1320) (max 0 (lf-noise1:kr 12)) 1/6))))
(demo 15
(let [freqs [220 440 660 880 1110 1320]
muls [1 1/2 1/3 1/4 1/5 1/6]
mk-sin #(* (sin-osc %1) (max 0 (lf-noise1 12)) %2)
sins (map mk-sin freqs muls)]
(* (mix sins) 0.3)))
Page 37
Array.fill(12 ,
SinOsc.ar(harm , : max([0 , 0 ] , SinOsc.kr(count + 1/4 ) ) ) * 1/(count + 1 )
) * 0.7}.play
(demo 15
(* 0.7
(mix
(for [count (range 12)]
(let [harm (* (inc count) 110)]
(* (sin-osc harm)
(max [0 0] (sin-osc:kr (/ (inc count) 4)))
(/ 1 (inc count))))))))
Page 38
Mix.fill(bells , {
(
Klank.ar(`specs ,
Dust.ar(1/6 , 0.03 ) ) ,
(demo 10
(let [num-res 5
bells 20
scale (map midi->hz [60 62 64 67 69])
mk-bell (fn [] (let [freqs (repeatedly num-res #(* (ranged-rand 1 5) (choose scale)))
amps (repeatedly num-res #(ranged-rand 0.3 0.9))
rings (repeatedly num-res #(ranged-rand 1 4))
specs [freqs amps rings]
pan (softclip (* 2 (lf-noise1:kr (ranged-rand 3 6))))]
(pan2 (klank specs (* 0.03 (dust (/ 1 6)) ))
pan)))]
(out 0 (mix (repeatedly bells mk-bell)))))
|
d9969ad73b6aff2c98d513a5f09fed88b0a54ed6da0eccc451887e03ad491065 | agda/agda | Statistics.hs | -- | Collect statistics.
module Agda.TypeChecking.Monad.Statistics
( MonadStatistics(..), tick, tickN, tickMax, getStatistics, modifyStatistics, printStatistics
) where
import Control.DeepSeq
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Trans.Maybe
import qualified Data.Map as Map
import qualified Text.PrettyPrint.Boxes as Boxes
import Agda.Syntax.TopLevelModuleName (TopLevelModuleName)
import Agda.TypeChecking.Monad.Base
import Agda.TypeChecking.Monad.Debug
import Agda.Utils.Maybe
import Agda.Utils.Null
import Agda.Utils.Pretty
import Agda.Utils.String
class ReadTCState m => MonadStatistics m where
modifyCounter :: String -> (Integer -> Integer) -> m ()
default modifyCounter
:: (MonadStatistics n, MonadTrans t, t n ~ m)
=> String -> (Integer -> Integer) -> m ()
modifyCounter x = lift . modifyCounter x
instance MonadStatistics m => MonadStatistics (ExceptT e m)
instance MonadStatistics m => MonadStatistics (MaybeT m)
instance MonadStatistics m => MonadStatistics (ReaderT r m)
instance MonadStatistics m => MonadStatistics (StateT s m)
instance (MonadStatistics m, Monoid w) => MonadStatistics (WriterT w m)
instance MonadStatistics TCM where
modifyCounter x f = modifyStatistics $ force . update
where
-- We need to be strict in the map.
, 2014 - 03 - 22 : Could we take Data . Map . Strict instead of this hack ?
-- Or force the map by looking up the very element we inserted?
-- force m = Map.lookup x m `seq` m
-- Or use insertLookupWithKey?
-- update m = old `seq` m' where
-- (old, m') = Map.insertLookupWithKey (\ _ new old -> f old) x dummy m
Ulf , 2018 - 04 - 10 : Neither of these approaches are strict enough in the
-- map (nor are they less hacky). It's not enough to be strict in the
-- values stored in the map, we also need to be strict in the *structure*
-- of the map. A less hacky solution is to deepseq the map.
force m = rnf m `seq` m
update = Map.insertWith (\ new old -> f old) x dummy
dummy = f 0
-- | Get the statistics.
getStatistics :: ReadTCState m => m Statistics
getStatistics = useR stStatistics
-- | Modify the statistics via given function.
modifyStatistics :: (Statistics -> Statistics) -> TCM ()
modifyStatistics f = stStatistics `modifyTCLens` f
| Increase specified counter by @1@.
tick :: MonadStatistics m => String -> m ()
tick x = tickN x 1
-- | Increase specified counter by @n@.
tickN :: MonadStatistics m => String -> Integer -> m ()
tickN s n = modifyCounter s (n +)
-- | Set the specified counter to the maximum of its current value and @n@.
tickMax :: MonadStatistics m => String -> Integer -> m ()
tickMax s n = modifyCounter s (max n)
-- | Print the given statistics.
printStatistics
:: (MonadDebug m, MonadTCEnv m, HasOptions m)
=> Maybe TopLevelModuleName -> Statistics -> m ()
printStatistics mmname stats = do
unlessNull (Map.toList stats) $ \ stats -> do
First column ( left aligned ) is accounts .
col1 = Boxes.vcat Boxes.left $ map (Boxes.text . fst) stats
Second column ( right aligned ) is numbers .
col2 = Boxes.vcat Boxes.right $ map (Boxes.text . showThousandSep . snd) stats
table = Boxes.hsep 1 Boxes.left [col1, col2]
reportSLn "" 1 $ caseMaybe mmname "Accumulated statistics" $ \ mname ->
"Statistics for " ++ prettyShow mname
reportSLn "" 1 $ Boxes.render table
| null | https://raw.githubusercontent.com/agda/agda/c859b5e8737a006b559723a1048bba10806bda2d/src/full/Agda/TypeChecking/Monad/Statistics.hs | haskell | | Collect statistics.
We need to be strict in the map.
Or force the map by looking up the very element we inserted?
force m = Map.lookup x m `seq` m
Or use insertLookupWithKey?
update m = old `seq` m' where
(old, m') = Map.insertLookupWithKey (\ _ new old -> f old) x dummy m
map (nor are they less hacky). It's not enough to be strict in the
values stored in the map, we also need to be strict in the *structure*
of the map. A less hacky solution is to deepseq the map.
| Get the statistics.
| Modify the statistics via given function.
| Increase specified counter by @n@.
| Set the specified counter to the maximum of its current value and @n@.
| Print the given statistics. |
module Agda.TypeChecking.Monad.Statistics
( MonadStatistics(..), tick, tickN, tickMax, getStatistics, modifyStatistics, printStatistics
) where
import Control.DeepSeq
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Trans.Maybe
import qualified Data.Map as Map
import qualified Text.PrettyPrint.Boxes as Boxes
import Agda.Syntax.TopLevelModuleName (TopLevelModuleName)
import Agda.TypeChecking.Monad.Base
import Agda.TypeChecking.Monad.Debug
import Agda.Utils.Maybe
import Agda.Utils.Null
import Agda.Utils.Pretty
import Agda.Utils.String
class ReadTCState m => MonadStatistics m where
modifyCounter :: String -> (Integer -> Integer) -> m ()
default modifyCounter
:: (MonadStatistics n, MonadTrans t, t n ~ m)
=> String -> (Integer -> Integer) -> m ()
modifyCounter x = lift . modifyCounter x
instance MonadStatistics m => MonadStatistics (ExceptT e m)
instance MonadStatistics m => MonadStatistics (MaybeT m)
instance MonadStatistics m => MonadStatistics (ReaderT r m)
instance MonadStatistics m => MonadStatistics (StateT s m)
instance (MonadStatistics m, Monoid w) => MonadStatistics (WriterT w m)
instance MonadStatistics TCM where
modifyCounter x f = modifyStatistics $ force . update
where
, 2014 - 03 - 22 : Could we take Data . Map . Strict instead of this hack ?
Ulf , 2018 - 04 - 10 : Neither of these approaches are strict enough in the
force m = rnf m `seq` m
update = Map.insertWith (\ new old -> f old) x dummy
dummy = f 0
getStatistics :: ReadTCState m => m Statistics
getStatistics = useR stStatistics
modifyStatistics :: (Statistics -> Statistics) -> TCM ()
modifyStatistics f = stStatistics `modifyTCLens` f
| Increase specified counter by @1@.
tick :: MonadStatistics m => String -> m ()
tick x = tickN x 1
tickN :: MonadStatistics m => String -> Integer -> m ()
tickN s n = modifyCounter s (n +)
tickMax :: MonadStatistics m => String -> Integer -> m ()
tickMax s n = modifyCounter s (max n)
printStatistics
:: (MonadDebug m, MonadTCEnv m, HasOptions m)
=> Maybe TopLevelModuleName -> Statistics -> m ()
printStatistics mmname stats = do
unlessNull (Map.toList stats) $ \ stats -> do
First column ( left aligned ) is accounts .
col1 = Boxes.vcat Boxes.left $ map (Boxes.text . fst) stats
Second column ( right aligned ) is numbers .
col2 = Boxes.vcat Boxes.right $ map (Boxes.text . showThousandSep . snd) stats
table = Boxes.hsep 1 Boxes.left [col1, col2]
reportSLn "" 1 $ caseMaybe mmname "Accumulated statistics" $ \ mname ->
"Statistics for " ++ prettyShow mname
reportSLn "" 1 $ Boxes.render table
|
2f26cd2f39e4647fa01e0393003d0175c32e15d818c436045b5de1ab7f38b04e | facebook/duckling | Rules.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
# LANGUAGE NoRebindableSyntax #
module Duckling.Rules
( allRules
, rulesFor
) where
import Data.HashSet (HashSet)
import Prelude
import qualified Data.HashSet as HashSet
import Duckling.Dimensions
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Types
import qualified Duckling.Rules.AF as AFRules
import qualified Duckling.Rules.AR as ARRules
import qualified Duckling.Rules.Common as CommonRules
import qualified Duckling.Rules.BG as BGRules
import qualified Duckling.Rules.BN as BNRules
import qualified Duckling.Rules.CA as CARules
import qualified Duckling.Rules.CS as CSRules
import qualified Duckling.Rules.DA as DARules
import qualified Duckling.Rules.DE as DERules
import qualified Duckling.Rules.EL as ELRules
import qualified Duckling.Rules.EN as ENRules
import qualified Duckling.Rules.ES as ESRules
import qualified Duckling.Rules.ET as ETRules
import qualified Duckling.Rules.FI as FIRules
import qualified Duckling.Rules.FA as FARules
import qualified Duckling.Rules.FR as FRRules
import qualified Duckling.Rules.GA as GARules
import qualified Duckling.Rules.HE as HERules
import qualified Duckling.Rules.HI as HIRules
import qualified Duckling.Rules.HR as HRRules
import qualified Duckling.Rules.HU as HURules
import qualified Duckling.Rules.ID as IDRules
import qualified Duckling.Rules.IS as ISRules
import qualified Duckling.Rules.IT as ITRules
import qualified Duckling.Rules.JA as JARules
import qualified Duckling.Rules.KA as KARules
import qualified Duckling.Rules.KM as KMRules
import qualified Duckling.Rules.KN as KNRules
import qualified Duckling.Rules.KO as KORules
import qualified Duckling.Rules.LO as LORules
import qualified Duckling.Rules.ML as MLRules
import qualified Duckling.Rules.MN as MNRules
import qualified Duckling.Rules.MY as MYRules
import qualified Duckling.Rules.NB as NBRules
import qualified Duckling.Rules.NE as NERules
import qualified Duckling.Rules.NL as NLRules
import qualified Duckling.Rules.PL as PLRules
import qualified Duckling.Rules.PT as PTRules
import qualified Duckling.Rules.RO as RORules
import qualified Duckling.Rules.RU as RURules
import qualified Duckling.Rules.SK as SKRules
import qualified Duckling.Rules.SV as SVRules
import qualified Duckling.Rules.SW as SWRules
import qualified Duckling.Rules.TA as TARules
import qualified Duckling.Rules.TE as TERules
import qualified Duckling.Rules.TH as THRules
import qualified Duckling.Rules.TR as TRRules
import qualified Duckling.Rules.UK as UKRules
import qualified Duckling.Rules.VI as VIRules
import qualified Duckling.Rules.ZH as ZHRules
-- | Returns the minimal set of rules required for `targets`.
rulesFor :: Locale -> HashSet (Seal Dimension) -> [Rule]
rulesFor locale targets
| HashSet.null targets = allRules locale
| otherwise = [ rules | dims <- HashSet.toList $ explicitDimensions targets
, rules <- rulesFor' locale dims ]
-- | Returns all the rules for the provided locale.
We ca n't really use ` allDimensions ` as - is , since ` TimeGrain ` is not present .
allRules :: Locale -> [Rule]
allRules locale@(Locale lang _) = concatMap (rulesFor' locale) . HashSet.toList
. explicitDimensions . HashSet.fromList $ allDimensions lang
rulesFor' :: Locale -> Seal Dimension -> [Rule]
rulesFor' (Locale lang (Just region)) dim =
CommonRules.rules dim ++ langRules lang dim ++ localeRules lang region dim
rulesFor' (Locale lang Nothing) dim =
CommonRules.rules dim ++ defaultRules lang dim
-- | Default rules when no locale, for backward compatibility.
defaultRules :: Lang -> Seal Dimension -> [Rule]
defaultRules AF = AFRules.defaultRules
defaultRules AR = ARRules.defaultRules
defaultRules BG = BGRules.defaultRules
defaultRules BN = BNRules.defaultRules
defaultRules CA = CARules.defaultRules
defaultRules CS = CSRules.defaultRules
defaultRules DA = DARules.defaultRules
defaultRules DE = DERules.defaultRules
defaultRules EL = ELRules.defaultRules
defaultRules EN = ENRules.defaultRules
defaultRules ES = ESRules.defaultRules
defaultRules ET = ETRules.defaultRules
defaultRules FI = FIRules.defaultRules
defaultRules FA = FARules.defaultRules
defaultRules FR = FRRules.defaultRules
defaultRules GA = GARules.defaultRules
defaultRules HE = HERules.defaultRules
defaultRules HI = HIRules.defaultRules
defaultRules HR = HRRules.defaultRules
defaultRules HU = HURules.defaultRules
defaultRules ID = IDRules.defaultRules
defaultRules IS = ISRules.defaultRules
defaultRules IT = ITRules.defaultRules
defaultRules JA = JARules.defaultRules
defaultRules KA = KARules.defaultRules
defaultRules KM = KMRules.defaultRules
defaultRules KN = KNRules.defaultRules
defaultRules KO = KORules.defaultRules
defaultRules LO = LORules.defaultRules
defaultRules ML = MLRules.defaultRules
defaultRules MN = MNRules.defaultRules
defaultRules MY = MYRules.defaultRules
defaultRules NB = NBRules.defaultRules
defaultRules NE = NERules.defaultRules
defaultRules NL = NLRules.defaultRules
defaultRules PL = PLRules.defaultRules
defaultRules PT = PTRules.defaultRules
defaultRules RO = RORules.defaultRules
defaultRules RU = RURules.defaultRules
defaultRules SK = SKRules.defaultRules
defaultRules SV = SVRules.defaultRules
defaultRules SW = SWRules.defaultRules
defaultRules TA = TARules.defaultRules
defaultRules TE = TERules.defaultRules
defaultRules TH = THRules.defaultRules
defaultRules TR = TRRules.defaultRules
defaultRules UK = UKRules.defaultRules
defaultRules VI = VIRules.defaultRules
defaultRules ZH = ZHRules.defaultRules
localeRules :: Lang -> Region -> Seal Dimension -> [Rule]
localeRules AF = AFRules.localeRules
localeRules AR = ARRules.localeRules
localeRules BG = BGRules.localeRules
localeRules BN = BNRules.localeRules
localeRules CA = CARules.localeRules
localeRules CS = CSRules.localeRules
localeRules DA = DARules.localeRules
localeRules DE = DERules.localeRules
localeRules EL = ELRules.localeRules
localeRules EN = ENRules.localeRules
localeRules ES = ESRules.localeRules
localeRules ET = ETRules.localeRules
localeRules FI = FIRules.localeRules
localeRules FA = FARules.localeRules
localeRules FR = FRRules.localeRules
localeRules GA = GARules.localeRules
localeRules HE = HERules.localeRules
localeRules HI = HIRules.localeRules
localeRules HR = HRRules.localeRules
localeRules HU = HURules.localeRules
localeRules ID = IDRules.localeRules
localeRules IS = ISRules.localeRules
localeRules IT = ITRules.localeRules
localeRules JA = JARules.localeRules
localeRules KA = KARules.localeRules
localeRules KM = KMRules.localeRules
localeRules KN = KNRules.localeRules
localeRules KO = KORules.localeRules
localeRules LO = LORules.localeRules
localeRules ML = MLRules.localeRules
localeRules MN = MNRules.localeRules
localeRules MY = MYRules.localeRules
localeRules NB = NBRules.localeRules
localeRules NE = NERules.localeRules
localeRules NL = NLRules.localeRules
localeRules PL = PLRules.localeRules
localeRules PT = PTRules.localeRules
localeRules RO = RORules.localeRules
localeRules RU = RURules.localeRules
localeRules SK = SKRules.localeRules
localeRules SV = SVRules.localeRules
localeRules SW = SWRules.localeRules
localeRules TA = TARules.localeRules
localeRules TE = TERules.localeRules
localeRules TH = THRules.localeRules
localeRules TR = TRRules.localeRules
localeRules UK = UKRules.localeRules
localeRules VI = VIRules.localeRules
localeRules ZH = ZHRules.localeRules
langRules :: Lang -> Seal Dimension -> [Rule]
langRules AF = AFRules.langRules
langRules AR = ARRules.langRules
langRules BG = BGRules.langRules
langRules BN = BNRules.langRules
langRules CA = CARules.langRules
langRules CS = CSRules.langRules
langRules DA = DARules.langRules
langRules DE = DERules.langRules
langRules EL = ELRules.langRules
langRules EN = ENRules.langRules
langRules ES = ESRules.langRules
langRules ET = ETRules.langRules
langRules FI = FIRules.langRules
langRules FA = FARules.langRules
langRules FR = FRRules.langRules
langRules GA = GARules.langRules
langRules HE = HERules.langRules
langRules HI = HIRules.langRules
langRules KN = KNRules.langRules
langRules HR = HRRules.langRules
langRules HU = HURules.langRules
langRules ID = IDRules.langRules
langRules IS = ISRules.langRules
langRules IT = ITRules.langRules
langRules JA = JARules.langRules
langRules KA = KARules.langRules
langRules KM = KMRules.langRules
langRules KO = KORules.langRules
langRules LO = LORules.langRules
langRules ML = MLRules.langRules
langRules MN = MNRules.langRules
langRules MY = MYRules.langRules
langRules NB = NBRules.langRules
langRules NE = NERules.langRules
langRules NL = NLRules.langRules
langRules PL = PLRules.langRules
langRules PT = PTRules.langRules
langRules RO = RORules.langRules
langRules RU = RURules.langRules
langRules SK = SKRules.langRules
langRules SV = SVRules.langRules
langRules SW = SWRules.langRules
langRules TA = TARules.langRules
langRules TE = TERules.langRules
langRules TH = THRules.langRules
langRules TR = TRRules.langRules
langRules UK = UKRules.langRules
langRules VI = VIRules.langRules
langRules ZH = ZHRules.langRules
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Rules.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE GADTs #
| Returns the minimal set of rules required for `targets`.
| Returns all the rules for the provided locale.
| Default rules when no locale, for backward compatibility. | Copyright ( c ) 2016 - present , Facebook , Inc.
# LANGUAGE NoRebindableSyntax #
module Duckling.Rules
( allRules
, rulesFor
) where
import Data.HashSet (HashSet)
import Prelude
import qualified Data.HashSet as HashSet
import Duckling.Dimensions
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Types
import qualified Duckling.Rules.AF as AFRules
import qualified Duckling.Rules.AR as ARRules
import qualified Duckling.Rules.Common as CommonRules
import qualified Duckling.Rules.BG as BGRules
import qualified Duckling.Rules.BN as BNRules
import qualified Duckling.Rules.CA as CARules
import qualified Duckling.Rules.CS as CSRules
import qualified Duckling.Rules.DA as DARules
import qualified Duckling.Rules.DE as DERules
import qualified Duckling.Rules.EL as ELRules
import qualified Duckling.Rules.EN as ENRules
import qualified Duckling.Rules.ES as ESRules
import qualified Duckling.Rules.ET as ETRules
import qualified Duckling.Rules.FI as FIRules
import qualified Duckling.Rules.FA as FARules
import qualified Duckling.Rules.FR as FRRules
import qualified Duckling.Rules.GA as GARules
import qualified Duckling.Rules.HE as HERules
import qualified Duckling.Rules.HI as HIRules
import qualified Duckling.Rules.HR as HRRules
import qualified Duckling.Rules.HU as HURules
import qualified Duckling.Rules.ID as IDRules
import qualified Duckling.Rules.IS as ISRules
import qualified Duckling.Rules.IT as ITRules
import qualified Duckling.Rules.JA as JARules
import qualified Duckling.Rules.KA as KARules
import qualified Duckling.Rules.KM as KMRules
import qualified Duckling.Rules.KN as KNRules
import qualified Duckling.Rules.KO as KORules
import qualified Duckling.Rules.LO as LORules
import qualified Duckling.Rules.ML as MLRules
import qualified Duckling.Rules.MN as MNRules
import qualified Duckling.Rules.MY as MYRules
import qualified Duckling.Rules.NB as NBRules
import qualified Duckling.Rules.NE as NERules
import qualified Duckling.Rules.NL as NLRules
import qualified Duckling.Rules.PL as PLRules
import qualified Duckling.Rules.PT as PTRules
import qualified Duckling.Rules.RO as RORules
import qualified Duckling.Rules.RU as RURules
import qualified Duckling.Rules.SK as SKRules
import qualified Duckling.Rules.SV as SVRules
import qualified Duckling.Rules.SW as SWRules
import qualified Duckling.Rules.TA as TARules
import qualified Duckling.Rules.TE as TERules
import qualified Duckling.Rules.TH as THRules
import qualified Duckling.Rules.TR as TRRules
import qualified Duckling.Rules.UK as UKRules
import qualified Duckling.Rules.VI as VIRules
import qualified Duckling.Rules.ZH as ZHRules
rulesFor :: Locale -> HashSet (Seal Dimension) -> [Rule]
rulesFor locale targets
| HashSet.null targets = allRules locale
| otherwise = [ rules | dims <- HashSet.toList $ explicitDimensions targets
, rules <- rulesFor' locale dims ]
We ca n't really use ` allDimensions ` as - is , since ` TimeGrain ` is not present .
allRules :: Locale -> [Rule]
allRules locale@(Locale lang _) = concatMap (rulesFor' locale) . HashSet.toList
. explicitDimensions . HashSet.fromList $ allDimensions lang
rulesFor' :: Locale -> Seal Dimension -> [Rule]
rulesFor' (Locale lang (Just region)) dim =
CommonRules.rules dim ++ langRules lang dim ++ localeRules lang region dim
rulesFor' (Locale lang Nothing) dim =
CommonRules.rules dim ++ defaultRules lang dim
defaultRules :: Lang -> Seal Dimension -> [Rule]
defaultRules AF = AFRules.defaultRules
defaultRules AR = ARRules.defaultRules
defaultRules BG = BGRules.defaultRules
defaultRules BN = BNRules.defaultRules
defaultRules CA = CARules.defaultRules
defaultRules CS = CSRules.defaultRules
defaultRules DA = DARules.defaultRules
defaultRules DE = DERules.defaultRules
defaultRules EL = ELRules.defaultRules
defaultRules EN = ENRules.defaultRules
defaultRules ES = ESRules.defaultRules
defaultRules ET = ETRules.defaultRules
defaultRules FI = FIRules.defaultRules
defaultRules FA = FARules.defaultRules
defaultRules FR = FRRules.defaultRules
defaultRules GA = GARules.defaultRules
defaultRules HE = HERules.defaultRules
defaultRules HI = HIRules.defaultRules
defaultRules HR = HRRules.defaultRules
defaultRules HU = HURules.defaultRules
defaultRules ID = IDRules.defaultRules
defaultRules IS = ISRules.defaultRules
defaultRules IT = ITRules.defaultRules
defaultRules JA = JARules.defaultRules
defaultRules KA = KARules.defaultRules
defaultRules KM = KMRules.defaultRules
defaultRules KN = KNRules.defaultRules
defaultRules KO = KORules.defaultRules
defaultRules LO = LORules.defaultRules
defaultRules ML = MLRules.defaultRules
defaultRules MN = MNRules.defaultRules
defaultRules MY = MYRules.defaultRules
defaultRules NB = NBRules.defaultRules
defaultRules NE = NERules.defaultRules
defaultRules NL = NLRules.defaultRules
defaultRules PL = PLRules.defaultRules
defaultRules PT = PTRules.defaultRules
defaultRules RO = RORules.defaultRules
defaultRules RU = RURules.defaultRules
defaultRules SK = SKRules.defaultRules
defaultRules SV = SVRules.defaultRules
defaultRules SW = SWRules.defaultRules
defaultRules TA = TARules.defaultRules
defaultRules TE = TERules.defaultRules
defaultRules TH = THRules.defaultRules
defaultRules TR = TRRules.defaultRules
defaultRules UK = UKRules.defaultRules
defaultRules VI = VIRules.defaultRules
defaultRules ZH = ZHRules.defaultRules
localeRules :: Lang -> Region -> Seal Dimension -> [Rule]
localeRules AF = AFRules.localeRules
localeRules AR = ARRules.localeRules
localeRules BG = BGRules.localeRules
localeRules BN = BNRules.localeRules
localeRules CA = CARules.localeRules
localeRules CS = CSRules.localeRules
localeRules DA = DARules.localeRules
localeRules DE = DERules.localeRules
localeRules EL = ELRules.localeRules
localeRules EN = ENRules.localeRules
localeRules ES = ESRules.localeRules
localeRules ET = ETRules.localeRules
localeRules FI = FIRules.localeRules
localeRules FA = FARules.localeRules
localeRules FR = FRRules.localeRules
localeRules GA = GARules.localeRules
localeRules HE = HERules.localeRules
localeRules HI = HIRules.localeRules
localeRules HR = HRRules.localeRules
localeRules HU = HURules.localeRules
localeRules ID = IDRules.localeRules
localeRules IS = ISRules.localeRules
localeRules IT = ITRules.localeRules
localeRules JA = JARules.localeRules
localeRules KA = KARules.localeRules
localeRules KM = KMRules.localeRules
localeRules KN = KNRules.localeRules
localeRules KO = KORules.localeRules
localeRules LO = LORules.localeRules
localeRules ML = MLRules.localeRules
localeRules MN = MNRules.localeRules
localeRules MY = MYRules.localeRules
localeRules NB = NBRules.localeRules
localeRules NE = NERules.localeRules
localeRules NL = NLRules.localeRules
localeRules PL = PLRules.localeRules
localeRules PT = PTRules.localeRules
localeRules RO = RORules.localeRules
localeRules RU = RURules.localeRules
localeRules SK = SKRules.localeRules
localeRules SV = SVRules.localeRules
localeRules SW = SWRules.localeRules
localeRules TA = TARules.localeRules
localeRules TE = TERules.localeRules
localeRules TH = THRules.localeRules
localeRules TR = TRRules.localeRules
localeRules UK = UKRules.localeRules
localeRules VI = VIRules.localeRules
localeRules ZH = ZHRules.localeRules
langRules :: Lang -> Seal Dimension -> [Rule]
langRules AF = AFRules.langRules
langRules AR = ARRules.langRules
langRules BG = BGRules.langRules
langRules BN = BNRules.langRules
langRules CA = CARules.langRules
langRules CS = CSRules.langRules
langRules DA = DARules.langRules
langRules DE = DERules.langRules
langRules EL = ELRules.langRules
langRules EN = ENRules.langRules
langRules ES = ESRules.langRules
langRules ET = ETRules.langRules
langRules FI = FIRules.langRules
langRules FA = FARules.langRules
langRules FR = FRRules.langRules
langRules GA = GARules.langRules
langRules HE = HERules.langRules
langRules HI = HIRules.langRules
langRules KN = KNRules.langRules
langRules HR = HRRules.langRules
langRules HU = HURules.langRules
langRules ID = IDRules.langRules
langRules IS = ISRules.langRules
langRules IT = ITRules.langRules
langRules JA = JARules.langRules
langRules KA = KARules.langRules
langRules KM = KMRules.langRules
langRules KO = KORules.langRules
langRules LO = LORules.langRules
langRules ML = MLRules.langRules
langRules MN = MNRules.langRules
langRules MY = MYRules.langRules
langRules NB = NBRules.langRules
langRules NE = NERules.langRules
langRules NL = NLRules.langRules
langRules PL = PLRules.langRules
langRules PT = PTRules.langRules
langRules RO = RORules.langRules
langRules RU = RURules.langRules
langRules SK = SKRules.langRules
langRules SV = SVRules.langRules
langRules SW = SWRules.langRules
langRules TA = TARules.langRules
langRules TE = TERules.langRules
langRules TH = THRules.langRules
langRules TR = TRRules.langRules
langRules UK = UKRules.langRules
langRules VI = VIRules.langRules
langRules ZH = ZHRules.langRules
|
3d45ae25033cc9c8445b1d10354a266d968b22baeda039f247c979bd08b1906f | youngnh/parsatron | project.clj | (defproject the/parsatron "0.0.9-SNAPSHOT"
:description "Clojure parser combinators"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"]]
:plugins [[lein-cljsbuild "1.1.7"]]
:source-paths ["src/clj" "src/cljs"]
:test-paths ["test/clj"]
:global-vars {*warn-on-reflection* false}
:cljsbuild {:builds [{:source-paths ["src/cljs" "test/cljs"]
:compiler {:optimizations :simple
:target :nodejs
:output-to "test/resources/parsatron_test.js"}}]
:test-commands { "unit" ["node" "test/resources/parsatron_test.js"]}})
| null | https://raw.githubusercontent.com/youngnh/parsatron/418d2d7cd93e6ac6fd72b8516118000e4d5af073/project.clj | clojure | (defproject the/parsatron "0.0.9-SNAPSHOT"
:description "Clojure parser combinators"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"]]
:plugins [[lein-cljsbuild "1.1.7"]]
:source-paths ["src/clj" "src/cljs"]
:test-paths ["test/clj"]
:global-vars {*warn-on-reflection* false}
:cljsbuild {:builds [{:source-paths ["src/cljs" "test/cljs"]
:compiler {:optimizations :simple
:target :nodejs
:output-to "test/resources/parsatron_test.js"}}]
:test-commands { "unit" ["node" "test/resources/parsatron_test.js"]}})
|
|
c51c1f2d819dff360e40c25c6f8e12f43d42537a2745d6d43e8b1d3368db80ac | rescript-lang/rescript-compiler | cmij_cache.ml | type t = { module_names : string array; module_data : bytes array }
type cmi_data = Cmi_format.cmi_infos
type cmj_data = { values : Js_cmj_format.keyed_cmj_value array; pure : bool }
let marshal_cmi_data (cmi_data : cmi_data) = Marshal.to_bytes cmi_data []
let marshal_cmj_data (cmj_data : cmj_data) = Marshal.to_bytes cmj_data []
let unmarshal_cmi_data bytes : cmi_data = Marshal.from_bytes bytes 0
let unmarshal_cmj_data bytes : cmj_data = Marshal.from_bytes bytes 0
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/81a3dc63ca387b2af23fed297db283254ae3ab20/jscomp/cmij/cmij_cache.ml | ocaml | type t = { module_names : string array; module_data : bytes array }
type cmi_data = Cmi_format.cmi_infos
type cmj_data = { values : Js_cmj_format.keyed_cmj_value array; pure : bool }
let marshal_cmi_data (cmi_data : cmi_data) = Marshal.to_bytes cmi_data []
let marshal_cmj_data (cmj_data : cmj_data) = Marshal.to_bytes cmj_data []
let unmarshal_cmi_data bytes : cmi_data = Marshal.from_bytes bytes 0
let unmarshal_cmj_data bytes : cmj_data = Marshal.from_bytes bytes 0
|
|
05616b17f56fbc74138df52b4b3826cc3ff745513fbe01ef3a0837131a77efe4 | chaoxu/fancy-walks | 56.hs |
import Data.Char
problem_56 = maximum $ map (sum.map digitToInt.show) [a^b | a <- [1..100], b <- [1..100]]
main = print problem_56
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/projecteuler.net/56.hs | haskell |
import Data.Char
problem_56 = maximum $ map (sum.map digitToInt.show) [a^b | a <- [1..100], b <- [1..100]]
main = print problem_56
|
|
55d665cfe38c293e383a22f27c35566902024b89d4095dc6ea136900b457f88c | danidiaz/colchis | JSONRPC20.hs | # LANGUAGE ViewPatterns #
{-# LANGUAGE OverloadedStrings #-}
module Network.Colchis.Protocol.JSONRPC20 (
module Network.Colchis.Protocol
, jsonRPC20
, JSONRPC20Error (..)
, IN.ErrorObject (..)
) where
import Network.Colchis.Protocol
import qualified Network.Colchis.Protocol.JSONRPC20.Request as OUT
import qualified Network.Colchis.Protocol.JSONRPC20.Response as IN
import Data.Text (Text,pack)
import Data.Aeson
import Data.Aeson.Types
import Control.Monad
import Control.Monad.Trans.Except
import Control.Monad.Trans.State.Strict
import Pipes
import Pipes.Core
import Pipes.Lift
import qualified Pipes.Prelude as P
import Pipes.Aeson
data JSONRPC20Error =
MalformedResponse Text Value
|ProtocolMismatch Text
|ResponseIdMismatch Int Int
|ErrorResponse IN.ErrorObject
deriving (Show)
--
jsonRPC20 :: Monad m => Protocol Text m (Text,Value,JSONRPC20Error)
jsonRPC20 = evalStateP 0 `liftM` go
where
go (method,mkStructured -> j) = do
msgId <- freshId
jresp <- request . toJSON $ OUT.Request protocolVer method j msgId
let throwE' x = lift . lift . throwE $ (method,j,x)
case parseEither parseJSON jresp of
Left str -> throwE' $ MalformedResponse (pack str) jresp
Right (IN.Response p' rm' em' id') -> do
if protocolVer /= p'
then throwE' $ ProtocolMismatch p'
else case em' of
Just err -> throwE' $ ErrorResponse err
Nothing -> case rm' of
Nothing -> throwE' $
MalformedResponse "missing fields" jresp
Just val -> case parseEither parseJSON id' of
Left str -> throwE' $
MalformedResponse "strange id" jresp
Right i -> if msgId /= i
then throwE' $ ResponseIdMismatch msgId i
else respond val >>= go
freshId = lift $ withStateT (flip mod 100 . succ) get
protocolVer = "2.0"
mkStructured j = case j of
o@Object {} -> o
a@Array {} -> a
Null -> emptyArray
x -> toJSON $ [x]
| null | https://raw.githubusercontent.com/danidiaz/colchis/3cf55d337a65f09026e6c9bdbc71f54d6f16f680/src/Network/Colchis/Protocol/JSONRPC20.hs | haskell | # LANGUAGE OverloadedStrings #
| # LANGUAGE ViewPatterns #
module Network.Colchis.Protocol.JSONRPC20 (
module Network.Colchis.Protocol
, jsonRPC20
, JSONRPC20Error (..)
, IN.ErrorObject (..)
) where
import Network.Colchis.Protocol
import qualified Network.Colchis.Protocol.JSONRPC20.Request as OUT
import qualified Network.Colchis.Protocol.JSONRPC20.Response as IN
import Data.Text (Text,pack)
import Data.Aeson
import Data.Aeson.Types
import Control.Monad
import Control.Monad.Trans.Except
import Control.Monad.Trans.State.Strict
import Pipes
import Pipes.Core
import Pipes.Lift
import qualified Pipes.Prelude as P
import Pipes.Aeson
data JSONRPC20Error =
MalformedResponse Text Value
|ProtocolMismatch Text
|ResponseIdMismatch Int Int
|ErrorResponse IN.ErrorObject
deriving (Show)
jsonRPC20 :: Monad m => Protocol Text m (Text,Value,JSONRPC20Error)
jsonRPC20 = evalStateP 0 `liftM` go
where
go (method,mkStructured -> j) = do
msgId <- freshId
jresp <- request . toJSON $ OUT.Request protocolVer method j msgId
let throwE' x = lift . lift . throwE $ (method,j,x)
case parseEither parseJSON jresp of
Left str -> throwE' $ MalformedResponse (pack str) jresp
Right (IN.Response p' rm' em' id') -> do
if protocolVer /= p'
then throwE' $ ProtocolMismatch p'
else case em' of
Just err -> throwE' $ ErrorResponse err
Nothing -> case rm' of
Nothing -> throwE' $
MalformedResponse "missing fields" jresp
Just val -> case parseEither parseJSON id' of
Left str -> throwE' $
MalformedResponse "strange id" jresp
Right i -> if msgId /= i
then throwE' $ ResponseIdMismatch msgId i
else respond val >>= go
freshId = lift $ withStateT (flip mod 100 . succ) get
protocolVer = "2.0"
mkStructured j = case j of
o@Object {} -> o
a@Array {} -> a
Null -> emptyArray
x -> toJSON $ [x]
|
8e6a9f11858e3cfd5ba9accbcf9582b8a7f804ad7776c21d1f3df251205dd053 | PLTools/GT | discover.ml | module Cfg = Configurator.V1
(*** utility functions ***)
(* pretty dumb file reading *)
let read_file fn =
let ichan = open_in fn in
let rec helper lines =
try
let line = input_line ichan in
helper (line :: lines)
with End_of_file -> lines
in
let lines = List.rev @@ helper [] in
String.concat "\n" lines
let extract_words = Cfg.Flags.extract_comma_space_separated_words
let string_match re s = Str.string_match re s 0
let match_fn_ext fn ext =
String.equal ext @@ Filename.extension fn
(* scans `regression` folder looking for `test*.ml` files *)
let get_tests ?(except=[]) pattern tests_dir =
let re = Str.regexp pattern in
let check_fn fn =
(string_match re fn)
&& (match_fn_ext fn ".ml")
(* `dune` doesn't give us direct access to `source` folder, only to the `build` folder,
* thus we have to exclude files generated by the preprocessor
*)
&& (not @@ match_fn_ext (Filename.remove_extension fn) ".pp")
(* `tester.ml` also should be excluded *)
&& (not @@ String.equal fn "tester.ml")
in
Sys.readdir tests_dir
|> Array.to_list
|> List.filter check_fn
|> List.map Filename.remove_extension
|> List.filter (fun s -> not (List.mem s except))
|> List.sort String.compare
(*** discovering ***)
let discover_camlp5_dir cfg =
String.trim @@
Cfg.Process.run_capture_exn cfg
"ocamlfind" ["query"; "camlp5"]
let discover_camlp5_flags cfg =
let camlp5_dir = discover_camlp5_dir cfg in
let camlp5_archives =
List.map
(fun arch -> String.concat Filename.dir_sep [camlp5_dir; arch])
["pa_o.cmo"; "pa_op.cmo"; "pr_o.cmo"]
in
Cfg.Flags.write_lines "camlp5-flags.cfg" camlp5_archives
let discover_logger_flags cfg =
logger has two kinds of CMOs : two from camlp5 ( pr_o and pr_dump ) and one for logger .
` pr_o ` is required because logger uses pretty - printing inside itself .
` pr_dump ` is required for printing result in binary format ( to save line numbers ) .
` pa_log ` for logger itself
in META file they are listed as ` pr_o.cmo pr_dump.cmo pa_log.cmo `
With ocamlfind they are passed as is to compilation command prefixed by
linking directory options . Because of that we ca n't write , for example ,
' .. /camlp5 / pr_o.cmo ` in META file .
With dune these three cmos are prefixed using full path , so using naive
approach they are all located in the same directory $ LIB / logger . This is
wrong but we can hack it in dune script because we know exact names of cmos .
`pr_o` is required because logger uses pretty-printing inside itself.
`pr_dump` is required for printing result in binary format (to save line numbers).
`pa_log` for logger itself
in META file they are listed as `pr_o.cmo pr_dump.cmo pa_log.cmo`
With ocamlfind they are passed as is to compilation command prefixed by
linking directory options. Because of that we can't write, for example,
'../camlp5/pr_o.cmo` in META file.
With dune these three cmos are prefixed using full path, so using naive
approach they are all located in the same directory $LIB/logger. This is
wrong but we can hack it in dune script because we know exact names of cmos.
*)
let camlp5_dir = discover_camlp5_dir cfg in
let logger_archives =
Cfg.Process.run_capture_exn cfg
"ocamlfind" ["query"; "-pp"; "camlp5"; "-a-format"; "-predicates"; "byte"; "logger,logger.syntax"]
in
let pr_o_cmo = "pr_o.cmo" in
let pr_dump_cmo = "pr_dump.cmo" in
let cmos =
extract_words logger_archives |>
List.map (fun file ->
if Filename.basename file = pr_o_cmo then
Filename.concat camlp5_dir pr_o_cmo
else if Filename.basename file = pr_dump_cmo then
Filename.concat camlp5_dir pr_dump_cmo
else file
)
in
Cfg.Flags.write_lines "logger-flags.cfg" cmos
let discover_tests ?(except=[]) cfg pattern =
let out =
Cfg.Process.run_capture_exn cfg ~dir:"../../regression"
"find" ["."; "-maxdepth"; "1"; "-iname"; pattern; "-exec"; "basename"; "{}"; "'.ml'"; "\\;"]
in
let out = Str.global_replace (Str.regexp "\n") " " out in
Format.printf "out = '%s'\n%!" out;
let out = Cfg.Flags.extract_blank_separated_words out in
let out = List.filter (fun s -> not (List.mem s except)) out in
out
(*** generating dune files ***)
let camlp5_rectypes_tests =
[ "test081llist"
]
let ppx_rectypes_tests =
[ "test798gen"; "test817logic"
]
let camlp5_tests dir =
(get_tests "test0" ~except:camlp5_rectypes_tests dir) @
["test705"; ]
let ppx_tests dir =
let except =
[ "test809cool"
; "test810cool"
; "test808ext"
; "test801mutal"
; "test814nonreg"
] @ ppx_rectypes_tests
in
get_tests "test8" ~except dir
(* generates build rules for `test*.exe` *)
let gen_tests_dune dir =
let cramch =
let f = Format.sprintf "regression.t" in
let _ = Sys.command (Format.sprintf "rm -f %s" f) in
open_out f
in
let outch = open_out (Format.sprintf "dune.tests") in
let fmt = Format.formatter_of_out_channel outch in
Format.pp_set_margin fmt 80;
Format.pp_set_max_indent fmt 6;
let wrap ?flags desc tests rewriter =
tests |> List.iter (fun s ->
Printf.fprintf cramch " $ ./%s.exe\n%!" s
);
match tests with
| [] -> ()
| _ ->
let exes = String.concat " " @@ List.map (Printf.sprintf "%s.exe") tests in
Format.fprintf fmt "\n; %s\n" desc;
Format.fprintf fmt "(cram (deps %s))\n" exes;
tests |> List.iter (fun test ->
Format.fprintf fmt "@[(executable";
Format.fprintf fmt "@[<v 2> ";
Format.fprintf fmt "@[(name %s)@]@," test;
Format.fprintf fmt "@[(modules %s)@]@," test;
let () = match flags with
| None -> ()
| Some f -> Format.fprintf fmt "@[(flags (:standard %s))@]@," f
in
Format.fprintf fmt "@[(libraries GT)@]@,";
Format.fprintf fmt "@[%a@]" rewriter ();
close vbox
Format.fprintf fmt ")@]\n"
);
Format.pp_print_flush fmt ()
in
let p5_rewriter ppf () =
let pp = "%{project_root}/camlp5/pp5+gt+plugins+dump.exe" in
Format.fprintf ppf "@[(preprocess (action (run %s %%{input-file})))@]@," pp;
Format.fprintf ppf "@[(preprocessor_deps (file %s))@]@," pp
in
let ppx_rewriter ppf () =
let pp = "%{project_root}/ppx/pp_gt.exe" in
--as - pp will output serialized AST
without it the human - readable AST will be printed
* *
without it the human-readable AST will be printed
***)
Format.fprintf ppf "@[(preprocess (action (run %s --as-pp %%{input-file})))@]@," pp;
Format.fprintf ppf "@[(preprocessor_deps (file %s))@]@," pp
in
let () = wrap "camlp5 " (camlp5_tests dir) p5_rewriter in
let () = wrap ~flags:"-rectypes" "camlp5+rectypes" (camlp5_rectypes_tests) p5_rewriter in
let () = wrap "ppx" (ppx_tests dir) ppx_rewriter in
let () = wrap ~flags:"-rectypes" "ppx+rectypes" (ppx_rectypes_tests) ppx_rewriter in
close_out cramch;
close_out outch
let discover_doc () =
let filename = "package-doc.cfg" in
Sys.command (Printf.sprintf "rm -fr '%s'" filename) |> ignore;
try
let _ = Unix.getenv "GT_WITH_DOCS" in
Cfg.Flags.write_lines filename ["-package"; "pa_ppx"]
with Not_found ->
Cfg.Flags.write_lines filename [];
()
(*** command line arguments ***)
let tests = ref false
let tests_dune = ref false
let tests_dir = ref "./regression"
let camlp5_flags = ref false
let doc_flags = ref false
let logger_flags = ref false
let all_flags = ref false
let all = ref false
let args =
let set_tests_dir s = tests_dir := s in
Arg.align @@
[ ("-tests-dir" , Arg.String set_tests_dir, "DIR discover tests in this directory" )
; ("-tests" , Arg.Set tests_dune , " generate dune build file for tests" )
; ("-camlp5-flags", Arg.Set camlp5_flags , " discover camlp5 flags (camlp5-flags.cfg)" )
; ("-doc-flags" , Arg.Set doc_flags , " discover whether to build documentation")
; ("-logger-flags", Arg.Set logger_flags , " discover logger flags (logger-flags.cfg)" )
; ("-all-flags" , Arg.Set all_flags , " discover all flags" )
; ("-all" , Arg.Set all , " discover all" )
]
(*** main ***)
let () =
Cfg.main ~name:"GT" ~args (fun cfg ->
if !doc_flags || !all then
discover_doc ();
if !tests_dune || !all then
gen_tests_dune !tests_dir;
if !camlp5_flags || !all_flags || !all then
discover_camlp5_flags cfg;
if !logger_flags || !all_flags || !all then
discover_logger_flags cfg;
()
)
| null | https://raw.githubusercontent.com/PLTools/GT/62d1a424a3336f2317ba67e447a9ff09d179b583/config/discover.ml | ocaml | ** utility functions **
pretty dumb file reading
scans `regression` folder looking for `test*.ml` files
`dune` doesn't give us direct access to `source` folder, only to the `build` folder,
* thus we have to exclude files generated by the preprocessor
`tester.ml` also should be excluded
** discovering **
** generating dune files **
generates build rules for `test*.exe`
** command line arguments **
** main ** | module Cfg = Configurator.V1
let read_file fn =
let ichan = open_in fn in
let rec helper lines =
try
let line = input_line ichan in
helper (line :: lines)
with End_of_file -> lines
in
let lines = List.rev @@ helper [] in
String.concat "\n" lines
let extract_words = Cfg.Flags.extract_comma_space_separated_words
let string_match re s = Str.string_match re s 0
let match_fn_ext fn ext =
String.equal ext @@ Filename.extension fn
let get_tests ?(except=[]) pattern tests_dir =
let re = Str.regexp pattern in
let check_fn fn =
(string_match re fn)
&& (match_fn_ext fn ".ml")
&& (not @@ match_fn_ext (Filename.remove_extension fn) ".pp")
&& (not @@ String.equal fn "tester.ml")
in
Sys.readdir tests_dir
|> Array.to_list
|> List.filter check_fn
|> List.map Filename.remove_extension
|> List.filter (fun s -> not (List.mem s except))
|> List.sort String.compare
let discover_camlp5_dir cfg =
String.trim @@
Cfg.Process.run_capture_exn cfg
"ocamlfind" ["query"; "camlp5"]
let discover_camlp5_flags cfg =
let camlp5_dir = discover_camlp5_dir cfg in
let camlp5_archives =
List.map
(fun arch -> String.concat Filename.dir_sep [camlp5_dir; arch])
["pa_o.cmo"; "pa_op.cmo"; "pr_o.cmo"]
in
Cfg.Flags.write_lines "camlp5-flags.cfg" camlp5_archives
let discover_logger_flags cfg =
logger has two kinds of CMOs : two from camlp5 ( pr_o and pr_dump ) and one for logger .
` pr_o ` is required because logger uses pretty - printing inside itself .
` pr_dump ` is required for printing result in binary format ( to save line numbers ) .
` pa_log ` for logger itself
in META file they are listed as ` pr_o.cmo pr_dump.cmo pa_log.cmo `
With ocamlfind they are passed as is to compilation command prefixed by
linking directory options . Because of that we ca n't write , for example ,
' .. /camlp5 / pr_o.cmo ` in META file .
With dune these three cmos are prefixed using full path , so using naive
approach they are all located in the same directory $ LIB / logger . This is
wrong but we can hack it in dune script because we know exact names of cmos .
`pr_o` is required because logger uses pretty-printing inside itself.
`pr_dump` is required for printing result in binary format (to save line numbers).
`pa_log` for logger itself
in META file they are listed as `pr_o.cmo pr_dump.cmo pa_log.cmo`
With ocamlfind they are passed as is to compilation command prefixed by
linking directory options. Because of that we can't write, for example,
'../camlp5/pr_o.cmo` in META file.
With dune these three cmos are prefixed using full path, so using naive
approach they are all located in the same directory $LIB/logger. This is
wrong but we can hack it in dune script because we know exact names of cmos.
*)
let camlp5_dir = discover_camlp5_dir cfg in
let logger_archives =
Cfg.Process.run_capture_exn cfg
"ocamlfind" ["query"; "-pp"; "camlp5"; "-a-format"; "-predicates"; "byte"; "logger,logger.syntax"]
in
let pr_o_cmo = "pr_o.cmo" in
let pr_dump_cmo = "pr_dump.cmo" in
let cmos =
extract_words logger_archives |>
List.map (fun file ->
if Filename.basename file = pr_o_cmo then
Filename.concat camlp5_dir pr_o_cmo
else if Filename.basename file = pr_dump_cmo then
Filename.concat camlp5_dir pr_dump_cmo
else file
)
in
Cfg.Flags.write_lines "logger-flags.cfg" cmos
let discover_tests ?(except=[]) cfg pattern =
let out =
Cfg.Process.run_capture_exn cfg ~dir:"../../regression"
"find" ["."; "-maxdepth"; "1"; "-iname"; pattern; "-exec"; "basename"; "{}"; "'.ml'"; "\\;"]
in
let out = Str.global_replace (Str.regexp "\n") " " out in
Format.printf "out = '%s'\n%!" out;
let out = Cfg.Flags.extract_blank_separated_words out in
let out = List.filter (fun s -> not (List.mem s except)) out in
out
let camlp5_rectypes_tests =
[ "test081llist"
]
let ppx_rectypes_tests =
[ "test798gen"; "test817logic"
]
let camlp5_tests dir =
(get_tests "test0" ~except:camlp5_rectypes_tests dir) @
["test705"; ]
let ppx_tests dir =
let except =
[ "test809cool"
; "test810cool"
; "test808ext"
; "test801mutal"
; "test814nonreg"
] @ ppx_rectypes_tests
in
get_tests "test8" ~except dir
let gen_tests_dune dir =
let cramch =
let f = Format.sprintf "regression.t" in
let _ = Sys.command (Format.sprintf "rm -f %s" f) in
open_out f
in
let outch = open_out (Format.sprintf "dune.tests") in
let fmt = Format.formatter_of_out_channel outch in
Format.pp_set_margin fmt 80;
Format.pp_set_max_indent fmt 6;
let wrap ?flags desc tests rewriter =
tests |> List.iter (fun s ->
Printf.fprintf cramch " $ ./%s.exe\n%!" s
);
match tests with
| [] -> ()
| _ ->
let exes = String.concat " " @@ List.map (Printf.sprintf "%s.exe") tests in
Format.fprintf fmt "\n; %s\n" desc;
Format.fprintf fmt "(cram (deps %s))\n" exes;
tests |> List.iter (fun test ->
Format.fprintf fmt "@[(executable";
Format.fprintf fmt "@[<v 2> ";
Format.fprintf fmt "@[(name %s)@]@," test;
Format.fprintf fmt "@[(modules %s)@]@," test;
let () = match flags with
| None -> ()
| Some f -> Format.fprintf fmt "@[(flags (:standard %s))@]@," f
in
Format.fprintf fmt "@[(libraries GT)@]@,";
Format.fprintf fmt "@[%a@]" rewriter ();
close vbox
Format.fprintf fmt ")@]\n"
);
Format.pp_print_flush fmt ()
in
let p5_rewriter ppf () =
let pp = "%{project_root}/camlp5/pp5+gt+plugins+dump.exe" in
Format.fprintf ppf "@[(preprocess (action (run %s %%{input-file})))@]@," pp;
Format.fprintf ppf "@[(preprocessor_deps (file %s))@]@," pp
in
let ppx_rewriter ppf () =
let pp = "%{project_root}/ppx/pp_gt.exe" in
--as - pp will output serialized AST
without it the human - readable AST will be printed
* *
without it the human-readable AST will be printed
***)
Format.fprintf ppf "@[(preprocess (action (run %s --as-pp %%{input-file})))@]@," pp;
Format.fprintf ppf "@[(preprocessor_deps (file %s))@]@," pp
in
let () = wrap "camlp5 " (camlp5_tests dir) p5_rewriter in
let () = wrap ~flags:"-rectypes" "camlp5+rectypes" (camlp5_rectypes_tests) p5_rewriter in
let () = wrap "ppx" (ppx_tests dir) ppx_rewriter in
let () = wrap ~flags:"-rectypes" "ppx+rectypes" (ppx_rectypes_tests) ppx_rewriter in
close_out cramch;
close_out outch
let discover_doc () =
let filename = "package-doc.cfg" in
Sys.command (Printf.sprintf "rm -fr '%s'" filename) |> ignore;
try
let _ = Unix.getenv "GT_WITH_DOCS" in
Cfg.Flags.write_lines filename ["-package"; "pa_ppx"]
with Not_found ->
Cfg.Flags.write_lines filename [];
()
let tests = ref false
let tests_dune = ref false
let tests_dir = ref "./regression"
let camlp5_flags = ref false
let doc_flags = ref false
let logger_flags = ref false
let all_flags = ref false
let all = ref false
let args =
let set_tests_dir s = tests_dir := s in
Arg.align @@
[ ("-tests-dir" , Arg.String set_tests_dir, "DIR discover tests in this directory" )
; ("-tests" , Arg.Set tests_dune , " generate dune build file for tests" )
; ("-camlp5-flags", Arg.Set camlp5_flags , " discover camlp5 flags (camlp5-flags.cfg)" )
; ("-doc-flags" , Arg.Set doc_flags , " discover whether to build documentation")
; ("-logger-flags", Arg.Set logger_flags , " discover logger flags (logger-flags.cfg)" )
; ("-all-flags" , Arg.Set all_flags , " discover all flags" )
; ("-all" , Arg.Set all , " discover all" )
]
let () =
Cfg.main ~name:"GT" ~args (fun cfg ->
if !doc_flags || !all then
discover_doc ();
if !tests_dune || !all then
gen_tests_dune !tests_dir;
if !camlp5_flags || !all_flags || !all then
discover_camlp5_flags cfg;
if !logger_flags || !all_flags || !all then
discover_logger_flags cfg;
()
)
|
7cd0c49ed1e67a0fcfce49cf581383e73bad649b402f30c7200012cf023b1cbb | richcarl/erlguten | eg_xml2richText.erl | %%==========================================================================
Copyright ( C ) 2003
%%
%% 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.
%%
Author : < >
%%==========================================================================
-module(eg_xml2richText).
-export([normalise_xml/2,
normalise_xml/3,
default_tagMap/1]).
-include("eg.hrl").
%% -define(DEBUG, true).
-ifdef(DEBUG).
dbg_io(Str) -> dbg_io(Str,[]).
dbg_io(Str,Args) ->
io:format("eg_xml2richText: ~p " ++ Str, [self()] ++ Args),
ok.
-else.
%dbg_io(_) -> ok.
dbg_io(_,_) -> ok.
-endif.
%%----------------------------------------------------------------------
normalise_xml(XML , , ) - >
%% XML = XML parse tree
The tree is walked - if any Tag is in
%% Then the subtree of this tag is assumend to be rich text
= [ Tag ]
= [ # face { } ]
%% Invarients no consequative spaces
or spaces next to NLs
default_tagMap(Pts) ->
{[p],
[{default,eg_richText:mk_face("Times-Roman", Pts, true, default, 0)},
{em, eg_richText:mk_face("Times-Italic", Pts, true, default, 0)},
XXX ! ! ! the font ZapfChancery - MediumItalic is not availible
{red, eg_richText:mk_face("ZapfChancery-MediumItalic", Pts, true,
{1,0,0},0)},
{blue, eg_richText:mk_face("ZapfChancery-MediumItalic", Pts, true,
{0,0,1},0)},
{code, eg_richText:mk_face("Courier", Pts, false, default, 0)},
{b, eg_richText:mk_face("Times-Bold", Pts, true, default, 0)}
]}.
normalise_xml(XML, {StandardTags, TagMap}) ->
normalise_xml(XML, StandardTags, TagMap).
normalise_xml({Tag, Args, L}, RichTextTags, TagMap) ->
case lists:member(Tag, RichTextTags) of
true ->
L1 = normalise_richText(L, TagMap),
{Tag, Args, L1};
false ->
L1 = lists:map(fun(I) ->
normalise_xml(I, RichTextTags, TagMap)
end, L),
{Tag, Args, L1}
end;
normalise_xml(Z, _, _) ->
dbg_io("I cannot normalise:~p~n",[Z]).
normalise_richText(Items, FontMap) ->
L0 = lists:foldl(fun(I, L0) -> normalise_inline(I, FontMap, L0) end,
[], Items),
L1 = lists:reverse(L0),
test_inline_invarient(L1),
{richText, L1}.
test_inline_invarient([H1,H2|T]) ->
case {eg_richText:classify_inline(H1), eg_richText:classify_inline(H2)} of
{space, space} ->
dbg_io("Warning spaces:~p ~p~n",[H1,H2]),
test_inline_invarient([H2|T]);
{nl, space} ->
dbg_io("Warning NL + NL:~p ~p~n",[H1,H2]),
test_inline_invarient([H1|T]);
{space,nl} ->
dbg_io("Warning spaces + NL:~p ~p~n",[H1,H2]),
test_inline_invarient([H2|T]);
_ ->
test_inline_invarient([H2|T])
end;
test_inline_invarient(_) ->
true.
normalise_inline({raw,Str}, FontMap, L) ->
normalise_tag(default, Str, FontMap, L);
normalise_inline({Tag, _, [{raw,Str}]}, FontMap, L) ->
normalise_tag(Tag, Str, FontMap, L);
normalise_inline({_Tag, _, []}, _FontMap, L) ->
L.
normalise_tag(Tag, Str, FontMap, L) ->
Face = get_face(Tag, FontMap),
case eg_richText:is_face_breakable(Face) of
true ->
normalise_str(Str, Face, L, skip_ws);
false ->
normalise_str(Str, Face, L, keep_ws)
Wd = eg_richText : mk_fixedStr(Face , ) ,
% [Wd|L]
end.
get_face(Tag, [{Tag,Face}|_]) -> Face;
get_face(Tag, [_|T]) -> get_face(Tag, T);
get_face(Tag, []) ->
dbg_io("There is no face associated with Tag=~p~n",[Tag]),
eg_pdf:default_face().
Collect spaces nls etc .
%% in a breakable face
normalise_str([$\r,$\n|T], Face, L, WS) ->
normalise_str(T, Face, [eg_richText:mk_nl(Face)|L], WS);
normalise_str([$\n|T], Face, L, WS) ->
normalise_str(T, Face, [eg_richText:mk_nl(Face)|L], WS);
normalise_str([H|T], Face, L, WS) ->
case {is_white(H), WS} of
{true, skip_ws} ->
%% Hop over the white space
If we get to put in a NL otherwise
%% put in a space
T1 = skip_white(T),
case T1 of
[] ->
Space = eg_richText:mk_space(Face),
normalise_str(T1, Face, [Space|L], WS);
[H2|_] ->
case is_nl(H2) of
true ->
normalise_str(T1, Face, L, WS);
false ->
Space = eg_richText:mk_space(Face),
normalise_str(T1, Face, [Space|L], WS)
end
end;
{true, keep_ws} ->
Space = eg_richText:mk_space(Face),
normalise_str(T, Face, [Space|L], WS);
{false, _} ->
{Str, T1} = collect_word(T, [H]),
Word = eg_richText:mk_word(Face, Str),
normalise_str(T1, Face, [Word|L], WS)
end;
normalise_str([], _, L, _WS) ->
L.
%% End Normalise XML
%%----------------------------------------------------------------------
%%----------------------------------------------------------------------
%% misc
is_white($\s) -> true;
is_white($\t) -> true;
is_white(_) -> false.
is_white_or_nl($\n) -> true;
is_white_or_nl($\r) -> true;
is_white_or_nl(X) -> is_white(X).
is_nl($\n) -> true;
is_nl($\r) -> true;
is_nl(_) -> false.
skip_white(X=[H|T]) ->
case is_white(H) of
true -> skip_white(T);
false -> X
end;
skip_white([]) ->
[].
collect_word(X=[H|T], L) ->
case is_white_or_nl(H) of
true -> {lists:reverse(L), X};
false -> collect_word(T, [H|L])
end;
collect_word([], L) ->
{lists:reverse(L), []}.
| null | https://raw.githubusercontent.com/richcarl/erlguten/debd6120907e5e18b4bca5fbd5bdd9cb653f282d/src/eg_xml2richText.erl | erlang | ==========================================================================
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
without limitation the rights to use, copy, modify, merge, publish,
following conditions:
The above copyright notice and this permission notice shall be included
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,
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
==========================================================================
-define(DEBUG, true).
dbg_io(_) -> ok.
----------------------------------------------------------------------
XML = XML parse tree
Then the subtree of this tag is assumend to be rich text
Invarients no consequative spaces
[Wd|L]
in a breakable face
Hop over the white space
put in a space
End Normalise XML
----------------------------------------------------------------------
----------------------------------------------------------------------
misc | Copyright ( C ) 2003
" Software " ) , to deal in the Software without restriction , including
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
in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR
Author : < >
-module(eg_xml2richText).
-export([normalise_xml/2,
normalise_xml/3,
default_tagMap/1]).
-include("eg.hrl").
-ifdef(DEBUG).
dbg_io(Str) -> dbg_io(Str,[]).
dbg_io(Str,Args) ->
io:format("eg_xml2richText: ~p " ++ Str, [self()] ++ Args),
ok.
-else.
dbg_io(_,_) -> ok.
-endif.
normalise_xml(XML , , ) - >
The tree is walked - if any Tag is in
= [ Tag ]
= [ # face { } ]
or spaces next to NLs
default_tagMap(Pts) ->
{[p],
[{default,eg_richText:mk_face("Times-Roman", Pts, true, default, 0)},
{em, eg_richText:mk_face("Times-Italic", Pts, true, default, 0)},
XXX ! ! ! the font ZapfChancery - MediumItalic is not availible
{red, eg_richText:mk_face("ZapfChancery-MediumItalic", Pts, true,
{1,0,0},0)},
{blue, eg_richText:mk_face("ZapfChancery-MediumItalic", Pts, true,
{0,0,1},0)},
{code, eg_richText:mk_face("Courier", Pts, false, default, 0)},
{b, eg_richText:mk_face("Times-Bold", Pts, true, default, 0)}
]}.
normalise_xml(XML, {StandardTags, TagMap}) ->
normalise_xml(XML, StandardTags, TagMap).
normalise_xml({Tag, Args, L}, RichTextTags, TagMap) ->
case lists:member(Tag, RichTextTags) of
true ->
L1 = normalise_richText(L, TagMap),
{Tag, Args, L1};
false ->
L1 = lists:map(fun(I) ->
normalise_xml(I, RichTextTags, TagMap)
end, L),
{Tag, Args, L1}
end;
normalise_xml(Z, _, _) ->
dbg_io("I cannot normalise:~p~n",[Z]).
normalise_richText(Items, FontMap) ->
L0 = lists:foldl(fun(I, L0) -> normalise_inline(I, FontMap, L0) end,
[], Items),
L1 = lists:reverse(L0),
test_inline_invarient(L1),
{richText, L1}.
test_inline_invarient([H1,H2|T]) ->
case {eg_richText:classify_inline(H1), eg_richText:classify_inline(H2)} of
{space, space} ->
dbg_io("Warning spaces:~p ~p~n",[H1,H2]),
test_inline_invarient([H2|T]);
{nl, space} ->
dbg_io("Warning NL + NL:~p ~p~n",[H1,H2]),
test_inline_invarient([H1|T]);
{space,nl} ->
dbg_io("Warning spaces + NL:~p ~p~n",[H1,H2]),
test_inline_invarient([H2|T]);
_ ->
test_inline_invarient([H2|T])
end;
test_inline_invarient(_) ->
true.
normalise_inline({raw,Str}, FontMap, L) ->
normalise_tag(default, Str, FontMap, L);
normalise_inline({Tag, _, [{raw,Str}]}, FontMap, L) ->
normalise_tag(Tag, Str, FontMap, L);
normalise_inline({_Tag, _, []}, _FontMap, L) ->
L.
normalise_tag(Tag, Str, FontMap, L) ->
Face = get_face(Tag, FontMap),
case eg_richText:is_face_breakable(Face) of
true ->
normalise_str(Str, Face, L, skip_ws);
false ->
normalise_str(Str, Face, L, keep_ws)
Wd = eg_richText : mk_fixedStr(Face , ) ,
end.
get_face(Tag, [{Tag,Face}|_]) -> Face;
get_face(Tag, [_|T]) -> get_face(Tag, T);
get_face(Tag, []) ->
dbg_io("There is no face associated with Tag=~p~n",[Tag]),
eg_pdf:default_face().
Collect spaces nls etc .
normalise_str([$\r,$\n|T], Face, L, WS) ->
normalise_str(T, Face, [eg_richText:mk_nl(Face)|L], WS);
normalise_str([$\n|T], Face, L, WS) ->
normalise_str(T, Face, [eg_richText:mk_nl(Face)|L], WS);
normalise_str([H|T], Face, L, WS) ->
case {is_white(H), WS} of
{true, skip_ws} ->
If we get to put in a NL otherwise
T1 = skip_white(T),
case T1 of
[] ->
Space = eg_richText:mk_space(Face),
normalise_str(T1, Face, [Space|L], WS);
[H2|_] ->
case is_nl(H2) of
true ->
normalise_str(T1, Face, L, WS);
false ->
Space = eg_richText:mk_space(Face),
normalise_str(T1, Face, [Space|L], WS)
end
end;
{true, keep_ws} ->
Space = eg_richText:mk_space(Face),
normalise_str(T, Face, [Space|L], WS);
{false, _} ->
{Str, T1} = collect_word(T, [H]),
Word = eg_richText:mk_word(Face, Str),
normalise_str(T1, Face, [Word|L], WS)
end;
normalise_str([], _, L, _WS) ->
L.
is_white($\s) -> true;
is_white($\t) -> true;
is_white(_) -> false.
is_white_or_nl($\n) -> true;
is_white_or_nl($\r) -> true;
is_white_or_nl(X) -> is_white(X).
is_nl($\n) -> true;
is_nl($\r) -> true;
is_nl(_) -> false.
skip_white(X=[H|T]) ->
case is_white(H) of
true -> skip_white(T);
false -> X
end;
skip_white([]) ->
[].
collect_word(X=[H|T], L) ->
case is_white_or_nl(H) of
true -> {lists:reverse(L), X};
false -> collect_word(T, [H|L])
end;
collect_word([], L) ->
{lists:reverse(L), []}.
|
5d4316ba4a4536b7591827cf07cd58d4bc489fb01a4aef1c2ae9c14fa81adbed | leifp/clj-isa-protocol | multimethods.clj | (ns dispatch.multimethods
(:refer-clojure :exclude [remove-all-methods remove-method prefer-method
methods get-method prefers defmulti defmethod])
(:use [dispatch.is-a-protocol :only [is-a? global-is-a-hierarchy]]))
mostly stolen from clojurescript
;;NB: hierarchy must be IRef
in this case , use Var ; in cljs , they use Atom
(defn- reset-cache
[method-cache method-table cached-hierarchy hierarchy]
(swap! method-cache (fn [_] (deref method-table)))
(swap! cached-hierarchy (fn [_] (deref hierarchy))))
(defn- prefers*
[x y prefer-table]
(let [xprefs (@prefer-table x)]
(or
(when (and xprefs (xprefs y))
true)
(loop [ps (parents y)]
(when (pos? (count ps))
(when (prefers* x (first ps) prefer-table)
true)
(recur (rest ps))))
(loop [ps (parents x)]
(when (pos? (count ps))
(when (prefers* (first ps) y prefer-table)
true)
(recur (rest ps))))
false)))
(defn- dominates
[x y prefer-table]
(or (prefers* x y prefer-table) (is-a? x y)))
(defn- find-and-cache-best-method
[name dispatch-val hierarchy method-table prefer-table method-cache cached-hierarchy]
(let [best-entry (reduce (fn [be [k _ :as e]]
(if (is-a? dispatch-val k)
(let [be2 (if (or (nil? be) (dominates k (first be) prefer-table))
e
be)]
(when-not (dominates (first be2) k prefer-table)
(throw (Error.
(str "Multiple methods in multimethod '" name
"' match dispatch value: " dispatch-val " -> " k
" and " (first be2) ", and neither is preferred"))))
be2)
be))
nil @method-table)]
(when best-entry
(if (= @cached-hierarchy @hierarchy)
(do
(swap! method-cache assoc dispatch-val (second best-entry))
(second best-entry))
(do
(reset-cache method-cache method-table cached-hierarchy hierarchy)
(find-and-cache-best-method name dispatch-val hierarchy method-table prefer-table
method-cache cached-hierarchy))))))
(defprotocol IMultiFn
(-reset [mf])
(-add-method [mf dispatch-val method])
(-remove-method [mf dispatch-val])
(-prefer-method [mf dispatch-val dispatch-val-y])
(-get-method [mf dispatch-val])
(-methods [mf])
(-prefers [mf])
(-dispatch [mf args]))
(defn- do-dispatch
[mf dispatch-fn args]
(let [dispatch-val (apply dispatch-fn args)
target-fn (-get-method mf dispatch-val)]
(when-not target-fn
(throw (Error. (str "No method in multimethod '" name "' for dispatch value: " dispatch-val))))
(apply target-fn args)))
(deftype MultiFn [name dispatch-fn default-dispatch-val hierarchy
method-table prefer-table method-cache cached-hierarchy]
IMultiFn
(-reset [mf]
(swap! method-table (fn [mf] {}))
(swap! method-cache (fn [mf] {}))
(swap! prefer-table (fn [mf] {}))
(swap! cached-hierarchy (fn [mf] nil))
mf)
(-add-method [mf dispatch-val method]
(swap! method-table assoc dispatch-val method)
(reset-cache method-cache method-table cached-hierarchy hierarchy)
mf)
(-remove-method [mf dispatch-val]
(swap! method-table dissoc dispatch-val)
(reset-cache method-cache method-table cached-hierarchy hierarchy)
mf)
(-get-method [mf dispatch-val]
(when-not (= @cached-hierarchy @hierarchy)
(reset-cache method-cache method-table cached-hierarchy hierarchy))
(if-let [target-fn (@method-cache dispatch-val)]
target-fn
(if-let [target-fn (find-and-cache-best-method name dispatch-val hierarchy method-table
prefer-table method-cache cached-hierarchy)]
target-fn
(@method-table default-dispatch-val))))
(-prefer-method [mf dispatch-val-x dispatch-val-y]
(when (prefers* dispatch-val-x dispatch-val-y prefer-table)
(throw (Error. (str "Preference conflict in multimethod '" name "': " dispatch-val-y
" is already preferred to " dispatch-val-x))))
(swap! prefer-table
(fn [old]
(assoc old dispatch-val-x
(conj (get old dispatch-val-x #{})
dispatch-val-y))))
(reset-cache method-cache method-table cached-hierarchy hierarchy))
(-methods [mf] @method-table)
(-prefers [mf] @prefer-table)
(-dispatch [mf args] (do-dispatch mf dispatch-fn args))
;; IHash
;; (-hash [this] (hash this))
clojure.lang.IFn
;;TODO: do we need all these? can it just be
;;(invoke [this & args] (-dispatch this args))
(invoke [this] (-dispatch this ()))
(invoke [this a1] (-dispatch this (list a1)))
(invoke [this a1 a2] (-dispatch this (list a1 a2)))
(invoke [this a1 a2 a3] (-dispatch this (list a1 a2 a3)))
(invoke [this a1 a2 a3 a4] (-dispatch this (list a1 a2 a3 a4)))
(invoke [this a1 a2 a3 a4 a5] (-dispatch this (list a1 a2 a3 a4 a5)))
(invoke [this a1 a2 a3 a4 a5 a6] (-dispatch this (list a1 a2 a3 a4 a5 a6)))
(invoke [this a1 a2 a3 a4 a5 a6 a7]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 restargs]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 restargs)))
(applyTo [this args] (-dispatch this args)))
metafns on
(defn remove-all-methods
"Removes all of the methods of multimethod."
[multifn]
(-reset multifn))
(defn remove-method
"Removes the method of multimethod associated with dispatch-value."
[multifn dispatch-val]
(-remove-method multifn dispatch-val))
(defn prefer-method
"Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y
when there is a conflict"
[multifn dispatch-val-x dispatch-val-y]
(-prefer-method multifn dispatch-val-x dispatch-val-y))
(defn methods
"Given a multimethod, returns a map of dispatch values -> dispatch fns"
[multifn] (-methods multifn))
(defn get-method
"Given a multimethod and a dispatch value, returns the dispatch fn
that would apply to that value, or nil if none apply and no default"
[multifn dispatch-val] (-get-method multifn dispatch-val))
(defn prefers
"Given a multimethod, returns a map of preferred value -> set of other values"
[multifn] (-prefers multifn))
creating multimethods
(defn ^:private check-valid-options
"Throws an exception if the given option map contains keys not listed
as valid, else returns nil."
[options & valid-keys]
(when (seq (apply disj (apply hash-set (keys options)) valid-keys))
(throw
(apply str "Only these options are valid: "
(first valid-keys)
(map #(str ", " %) (rest valid-keys))))))
(defmacro defmulti
"Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.
Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
[mm-name & options]
(let [docstring (if (string? (first options))
(first options)
nil)
options (if (string? (first options))
(next options)
options)
m (if (map? (first options))
(first options)
{})
options (if (map? (first options))
(next options)
options)
dispatch-fn (first options)
options (next options)
m (if docstring
(assoc m :doc docstring)
m)
m (if (meta mm-name)
(conj (meta mm-name) m)
m)]
(when (= (count options) 1)
(throw "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)"))
(let [options (apply hash-map options)
default (get options :default :default)]
(check-valid-options options :default :hierarchy)
`(def ~(with-meta mm-name m)
(let [method-table# (atom {})
prefer-table# (atom {})
method-cache# (atom {})
cached-hierarchy# (atom {})
hierarchy# (get ~options :hierarchy #'global-is-a-hierarchy)]
(MultiFn. ~(name mm-name) ~dispatch-fn ~default hierarchy#
method-table# prefer-table# method-cache# cached-hierarchy#))))))
(defmacro defmethod
"Creates and installs a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val & fn-tail]
`(-add-method ~(with-meta multifn {:tag 'multimethods/MultiFn}) ~dispatch-val (fn ~@fn-tail)))
;;TODO: need to throw useful exceptions when dispatch fails
| null | https://raw.githubusercontent.com/leifp/clj-isa-protocol/98900fee78672e9d5c267f7c51fd59d4f57d3aab/src/dispatch/multimethods.clj | clojure | NB: hierarchy must be IRef
in cljs , they use Atom
IHash
(-hash [this] (hash this))
TODO: do we need all these? can it just be
(invoke [this & args] (-dispatch this args))
TODO: need to throw useful exceptions when dispatch fails | (ns dispatch.multimethods
(:refer-clojure :exclude [remove-all-methods remove-method prefer-method
methods get-method prefers defmulti defmethod])
(:use [dispatch.is-a-protocol :only [is-a? global-is-a-hierarchy]]))
mostly stolen from clojurescript
(defn- reset-cache
[method-cache method-table cached-hierarchy hierarchy]
(swap! method-cache (fn [_] (deref method-table)))
(swap! cached-hierarchy (fn [_] (deref hierarchy))))
(defn- prefers*
[x y prefer-table]
(let [xprefs (@prefer-table x)]
(or
(when (and xprefs (xprefs y))
true)
(loop [ps (parents y)]
(when (pos? (count ps))
(when (prefers* x (first ps) prefer-table)
true)
(recur (rest ps))))
(loop [ps (parents x)]
(when (pos? (count ps))
(when (prefers* (first ps) y prefer-table)
true)
(recur (rest ps))))
false)))
(defn- dominates
[x y prefer-table]
(or (prefers* x y prefer-table) (is-a? x y)))
(defn- find-and-cache-best-method
[name dispatch-val hierarchy method-table prefer-table method-cache cached-hierarchy]
(let [best-entry (reduce (fn [be [k _ :as e]]
(if (is-a? dispatch-val k)
(let [be2 (if (or (nil? be) (dominates k (first be) prefer-table))
e
be)]
(when-not (dominates (first be2) k prefer-table)
(throw (Error.
(str "Multiple methods in multimethod '" name
"' match dispatch value: " dispatch-val " -> " k
" and " (first be2) ", and neither is preferred"))))
be2)
be))
nil @method-table)]
(when best-entry
(if (= @cached-hierarchy @hierarchy)
(do
(swap! method-cache assoc dispatch-val (second best-entry))
(second best-entry))
(do
(reset-cache method-cache method-table cached-hierarchy hierarchy)
(find-and-cache-best-method name dispatch-val hierarchy method-table prefer-table
method-cache cached-hierarchy))))))
(defprotocol IMultiFn
(-reset [mf])
(-add-method [mf dispatch-val method])
(-remove-method [mf dispatch-val])
(-prefer-method [mf dispatch-val dispatch-val-y])
(-get-method [mf dispatch-val])
(-methods [mf])
(-prefers [mf])
(-dispatch [mf args]))
(defn- do-dispatch
[mf dispatch-fn args]
(let [dispatch-val (apply dispatch-fn args)
target-fn (-get-method mf dispatch-val)]
(when-not target-fn
(throw (Error. (str "No method in multimethod '" name "' for dispatch value: " dispatch-val))))
(apply target-fn args)))
(deftype MultiFn [name dispatch-fn default-dispatch-val hierarchy
method-table prefer-table method-cache cached-hierarchy]
IMultiFn
(-reset [mf]
(swap! method-table (fn [mf] {}))
(swap! method-cache (fn [mf] {}))
(swap! prefer-table (fn [mf] {}))
(swap! cached-hierarchy (fn [mf] nil))
mf)
(-add-method [mf dispatch-val method]
(swap! method-table assoc dispatch-val method)
(reset-cache method-cache method-table cached-hierarchy hierarchy)
mf)
(-remove-method [mf dispatch-val]
(swap! method-table dissoc dispatch-val)
(reset-cache method-cache method-table cached-hierarchy hierarchy)
mf)
(-get-method [mf dispatch-val]
(when-not (= @cached-hierarchy @hierarchy)
(reset-cache method-cache method-table cached-hierarchy hierarchy))
(if-let [target-fn (@method-cache dispatch-val)]
target-fn
(if-let [target-fn (find-and-cache-best-method name dispatch-val hierarchy method-table
prefer-table method-cache cached-hierarchy)]
target-fn
(@method-table default-dispatch-val))))
(-prefer-method [mf dispatch-val-x dispatch-val-y]
(when (prefers* dispatch-val-x dispatch-val-y prefer-table)
(throw (Error. (str "Preference conflict in multimethod '" name "': " dispatch-val-y
" is already preferred to " dispatch-val-x))))
(swap! prefer-table
(fn [old]
(assoc old dispatch-val-x
(conj (get old dispatch-val-x #{})
dispatch-val-y))))
(reset-cache method-cache method-table cached-hierarchy hierarchy))
(-methods [mf] @method-table)
(-prefers [mf] @prefer-table)
(-dispatch [mf args] (do-dispatch mf dispatch-fn args))
clojure.lang.IFn
(invoke [this] (-dispatch this ()))
(invoke [this a1] (-dispatch this (list a1)))
(invoke [this a1 a2] (-dispatch this (list a1 a2)))
(invoke [this a1 a2 a3] (-dispatch this (list a1 a2 a3)))
(invoke [this a1 a2 a3 a4] (-dispatch this (list a1 a2 a3 a4)))
(invoke [this a1 a2 a3 a4 a5] (-dispatch this (list a1 a2 a3 a4 a5)))
(invoke [this a1 a2 a3 a4 a5 a6] (-dispatch this (list a1 a2 a3 a4 a5 a6)))
(invoke [this a1 a2 a3 a4 a5 a6 a7]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20)))
(invoke [this a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 restargs]
(-dispatch this (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 restargs)))
(applyTo [this args] (-dispatch this args)))
metafns on
(defn remove-all-methods
"Removes all of the methods of multimethod."
[multifn]
(-reset multifn))
(defn remove-method
"Removes the method of multimethod associated with dispatch-value."
[multifn dispatch-val]
(-remove-method multifn dispatch-val))
(defn prefer-method
"Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y
when there is a conflict"
[multifn dispatch-val-x dispatch-val-y]
(-prefer-method multifn dispatch-val-x dispatch-val-y))
(defn methods
"Given a multimethod, returns a map of dispatch values -> dispatch fns"
[multifn] (-methods multifn))
(defn get-method
"Given a multimethod and a dispatch value, returns the dispatch fn
that would apply to that value, or nil if none apply and no default"
[multifn dispatch-val] (-get-method multifn dispatch-val))
(defn prefers
"Given a multimethod, returns a map of preferred value -> set of other values"
[multifn] (-prefers multifn))
creating multimethods
(defn ^:private check-valid-options
"Throws an exception if the given option map contains keys not listed
as valid, else returns nil."
[options & valid-keys]
(when (seq (apply disj (apply hash-set (keys options)) valid-keys))
(throw
(apply str "Only these options are valid: "
(first valid-keys)
(map #(str ", " %) (rest valid-keys))))))
(defmacro defmulti
"Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.
Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
[mm-name & options]
(let [docstring (if (string? (first options))
(first options)
nil)
options (if (string? (first options))
(next options)
options)
m (if (map? (first options))
(first options)
{})
options (if (map? (first options))
(next options)
options)
dispatch-fn (first options)
options (next options)
m (if docstring
(assoc m :doc docstring)
m)
m (if (meta mm-name)
(conj (meta mm-name) m)
m)]
(when (= (count options) 1)
(throw "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)"))
(let [options (apply hash-map options)
default (get options :default :default)]
(check-valid-options options :default :hierarchy)
`(def ~(with-meta mm-name m)
(let [method-table# (atom {})
prefer-table# (atom {})
method-cache# (atom {})
cached-hierarchy# (atom {})
hierarchy# (get ~options :hierarchy #'global-is-a-hierarchy)]
(MultiFn. ~(name mm-name) ~dispatch-fn ~default hierarchy#
method-table# prefer-table# method-cache# cached-hierarchy#))))))
(defmacro defmethod
"Creates and installs a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val & fn-tail]
`(-add-method ~(with-meta multifn {:tag 'multimethods/MultiFn}) ~dispatch-val (fn ~@fn-tail)))
|
ea166af25aadb281cac137a4f23b95280997a27c90767f647e045263bde55e42 | ds-wizard/engine-backend | Api.hs | module Wizard.Api.Handler.DocumentTemplateDraft.Api where
import Servant
import Servant.Swagger.Tags
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_DELETE
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_Documents_Preview_GET
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_Documents_Preview_Settings_PUT
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_GET
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_PUT
import Wizard.Api.Handler.DocumentTemplateDraft.List_GET
import Wizard.Api.Handler.DocumentTemplateDraft.List_POST
import Wizard.Model.Context.BaseContext
type DocumentTemplateDraftAPI =
Tags "Document Template Draft"
:> ( List_GET
:<|> List_POST
:<|> Detail_GET
:<|> Detail_PUT
:<|> Detail_DELETE
:<|> Detail_Documents_Preview_GET
:<|> Detail_Documents_Preview_Settings_PUT
)
documentTemplateDraftApi :: Proxy DocumentTemplateDraftAPI
documentTemplateDraftApi = Proxy
documentTemplateDraftServer :: ServerT DocumentTemplateDraftAPI BaseContextM
documentTemplateDraftServer =
list_GET
:<|> list_POST
:<|> detail_GET
:<|> detail_PUT
:<|> detail_DELETE
:<|> detail_documents_preview_GET
:<|> detail_documents_preview_settings_PUT
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Api/Handler/DocumentTemplateDraft/Api.hs | haskell | module Wizard.Api.Handler.DocumentTemplateDraft.Api where
import Servant
import Servant.Swagger.Tags
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_DELETE
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_Documents_Preview_GET
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_Documents_Preview_Settings_PUT
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_GET
import Wizard.Api.Handler.DocumentTemplateDraft.Detail_PUT
import Wizard.Api.Handler.DocumentTemplateDraft.List_GET
import Wizard.Api.Handler.DocumentTemplateDraft.List_POST
import Wizard.Model.Context.BaseContext
type DocumentTemplateDraftAPI =
Tags "Document Template Draft"
:> ( List_GET
:<|> List_POST
:<|> Detail_GET
:<|> Detail_PUT
:<|> Detail_DELETE
:<|> Detail_Documents_Preview_GET
:<|> Detail_Documents_Preview_Settings_PUT
)
documentTemplateDraftApi :: Proxy DocumentTemplateDraftAPI
documentTemplateDraftApi = Proxy
documentTemplateDraftServer :: ServerT DocumentTemplateDraftAPI BaseContextM
documentTemplateDraftServer =
list_GET
:<|> list_POST
:<|> detail_GET
:<|> detail_PUT
:<|> detail_DELETE
:<|> detail_documents_preview_GET
:<|> detail_documents_preview_settings_PUT
|
|
5a1ec3313cf8dee4afa71181152fded567f4b0a66fef61195a03283f752877fd | jeffshrager/biobike | meta1.lisp | Copyright ( c ) 2002 - 2003 by and ; All rights reserved .
;;; This software is made avilable for EDUCATIONAL PURPOSES
;;; ONLY, and WITHOUT ANY WARRANTY, express or implied, of
;;; its merchantability or fitness for a particular purpose.
(in-package USER)
(defstruct reaction
reactants ; Lefthand side
catalyst
Righthand side
)
(defstruct molecule
abbrev ; The abbreviation we'll use for convenience.
fullname ; The pretty-printing name.
S , NS , or INS
)
(defvar *molecules* nil)
(defvar *reactions* nil)
(defmacro add-molecule (abbrev fullname type &rest constituents)
`(push (make-molecule :abbrev ',abbrev
:fullname ,fullname
:type ',type)
*molecules*))
(compile
(defun find-molecules (abbrevs)
(loop for molecule in *molecules*
when (member (molecule-abbrev molecule) abbrevs)
collect molecule)))
Same thing , but only for one molcule :
(compile
(defun find-molecule (abbrev)
(loop for molecule in *molecules*
when (eq (molecule-abbrev molecule) abbrev)
do (return molecule))))
(defmacro add-reaction (reactants products enzyme)
`(push (make-reaction :reactants (find-molecules ',reactants)
:catalyst ',enzyme
:products (find-molecules ',products)
)
*reactions*))
(defun init-objects ()
(setq *molecules* nil)
(add-molecule P "phosphatate" ins)
(add-molecule C "carbon" ins)
(add-molecule aden "adenosine" ns)
(add-molecule guan "guanosine" ns)
(add-molecule H+ "H+" ns)
(add-molecule H2O "H2O" ns)
(add-molecule NAD+ "NAD+" ns)
(add-molecule FAD "FAD" ns)
(add-molecule coa "CoA" s)
(add-molecule atp "ATP" ins)
(add-molecule adp "ADP" ins)
(add-molecule gdp "GDP" ins)
(add-molecule gtp "GTP" ins)
(add-molecule NADH "NADH" ns)
(add-molecule CO2 "Co2" ins)
(add-molecule FADH2 "FADH2" ns)
(add-molecule glu "glucose" s)
(add-molecule fru "fructose" s)
(add-molecule dha "dihydroxyacetone" s)
(add-molecule glh "glyceraldehyde" s)
(add-molecule gla "glycerate" s)
(add-molecule pyr "pyruvate" s)
(add-molecule ace "acetyl" s)
(add-molecule oxa "oxaloacetate" s)
(add-molecule cit "citrate" s)
(add-molecule ict "isocitrate" s)
(add-molecule akg "a-ketoglutarate" s)
(add-molecule suc "succinate" s)
(add-molecule fum "fumarate" s)
(add-molecule mal "malate" s)
(add-molecule g6p "glucose 6-phosphate" s)
(add-molecule f1p "fructose 1-phosphate" s)
(add-molecule f6p "fructose 6-phosphate" s)
(add-molecule fbp "fructose 1,6 bisphosphate" s)
(add-molecule dap "dihydrozyacetone phosphate" s)
(add-molecule g3p "glyceraldehyde 3-phosphate" s)
(add-molecule bpg "1,3-bisphosphoglycerate" s)
(add-molecule 3pg "3-phosphoglycerate" s)
(add-molecule 2pg "2-phosphoglycerate" s)
(add-molecule pep "phosphoenolpyruvate" s)
(add-molecule aca "acetyl CoA" s)
(add-molecule sca "succinyl CoA" s)
;; Reactions:
(setq *reactions* nil)
(add-reaction (fru) (f1p) "Fructokinase")
(add-reaction (f1p) (glh dap) "Fructose 1-phosphate aldolase")
(add-reaction (glh) (g3p) "G3p kinase")
(add-reaction (glu atp) (g6p adp) "Hexokinase")
(add-reaction (g6p) (f6p) "Phosphoglucomutase")
(add-reaction (f6p atp) (fbp adp) "Phosphofructokinase")
(add-reaction (fbp) (dap g3p) "Aldolase")
(add-reaction (dap) (g3p) "Isomerase")
(add-reaction (P NAD+ g3p) (NADH H+ bpg) "G3p dehydrogenase")
(add-reaction (bpg adp) (3pg atp) "Phosphoglycerate kinase")
(add-reaction (3pg) (2pg) "Phosphoglyceromutase")
(add-reaction (2pg) (pep H2O) "Enolase")
(add-reaction (pep atp) (pyr adp) "Pyruvate kinase")
(add-reaction (pyr NAD+ coa) (NADH H+ CO2 aca) "Citrate synthase")
(add-reaction (cit) (ict) "Aconitase")
(add-reaction (ict NAD+) (akg NADH H+ CO2) "Isocitrate dehydrogenase")
(add-reaction (akg NAD+ coa) (sca NADH H+ CO2) "a-ketogluterate dehydrogenase complex")
(add-reaction (sca gdp P) (suc gtp coa) "Succinyl CoA synthase")
(add-reaction (suc FAD) (fum FADH2) "Succinate dehydrogenase")
(add-reaction (fum H2O) (mal) "Fumerase")
(add-reaction (mal NAD+) (oxa NADH H+) "Malate dehydrogenase")
)
(defun pp-reaction (r)
(let* ((catalyst (reaction-catalyst r))
(reactants (reaction-reactants r))
(products (reaction-products r))
)
(pp-mols reactants)
(format t " --[~a]--> " catalyst)
(pp-mols products)
(format t "~%"))
r)
(defun pp-mols (m*)
(loop for m+ on m*
do (format t "~A" (molecule-fullname (car m+)))
(when (cdr m+)
(format t " + "))))
(defmacro pp-reactions (reactions)
`(loop for reaction in ,reactions
do (pp-reaction reaction)))
(defvar *env* nil)
(defun init-env ()
(setq *env*
(find-molecules '(frk f1pa tk atp adp gdp gtp fru glu NAD+ FAD P hxk pfk pgm ald
gapdh pgk pym eno pyk iso csy act idh adhc scs sdh fas mdh))))
(defvar *goal* nil)
(defun init-goal ()
(setq *goal* (find-molecule 'mal)))
(defun init ()
(init-objects)
(init-env)
(init-goal))
(compile
(defun possible-reactions (env)
(loop for reaction in *reactions*
when (loop for reactant in (reaction-reactants reaction)
when (not (find reactant env))
do (return nil)
finally (return t))
collect reaction)))
(compile
(defun apply-reaction (reaction env)
(append env
(loop for product in (reaction-products reaction)
unless (member product env)
collect product))))
(compile
(defun paths (env goal &optional path)
(cond ((find goal env) (list path))
(t (loop for reaction in (possible-reactions env)
append (paths (apply-reaction reaction env)
goal
(cons reaction path)))))))
(compile
(defun paths (env goal &optional path)
(cond ((find goal env) (list path))
(t (loop for reaction in (loop for reaction in (possible-reactions env)
when (not (member reaction path))
collect reaction)
append (paths (apply-reaction reaction env) goal (cons reaction path))))
)))
(defmacro pathsto (goal)
`(length (setq *pathways*
(paths *env* (find-molecule ',goal)))))
(compile
(defun remove-duplicate-paths (path*)
(loop for this-path in path*
;; When the current path is NOT a superset of
;; anything else in the path list then collect it.
;; (Careful not to remove it when it matches itself!)
when (loop for target-path in path*
when (and (not (eq this-path target-path))
(superset? this-path target-path))
do (return nil)
finally (return t))
collect this-path)))
(compile
(defun superset? (s1 s2)
(and (>= (length s1) (length s2))
(loop for a in s2
when (not (member a s1))
do (return nil)
finally (return t)))))
(defmacro pathsto (goal)
`(length (setq *pathways*
(remove-duplicate-paths
(paths *env* (find-molecule ',goal))))))
(defun ppp (&optional (pwys *pathways*))
(loop for path-n from 1 by 1
as path in pwys
do (format t "~%~%Pathway #~a:~%~%" path-n)
;; We copy the list
(pp-reactions (reverse (copy-list path)))))
;;; We have to come from a particular molecule, and we have to pass
;;; the pathway down alongwith us, so that we can use the previous
;;; reaction to constrain the search.
(defun paths-between (from to &optional (env *env*) path)
(cond ((member to env) (list path)) ; If we've found our goal, we're done! (LIST for appends up the stack.)
(t (loop for reaction in (possible-reactions-from from env)
when (not (member reaction path))
append (paths-via (cons reaction path) to (apply-reaction reaction env))))
))
;;; Track each SPECIFIC reaction product molecule into a new path.
(defun paths-via (path to env)
(loop for link-mol in (reaction-products (car path))
when (eq 's (molecule-type link-mol))
append (paths-between link-mol to env path)))
;;; This is a constrained version of POSSIBLE-REACTIONS.
;;; The only difference is the (AND (MEMBER ...) ...) which
;;; ensures that the reaction chosen also links to the FROM molecule.
(defun possible-reactions-from (from env)
(loop for reaction in *reactions*
as reactants = (reaction-reactants reaction)
when (and (member from reactants)
(loop for reactant in reactants
when (not (find reactant env))
do (return nil)
finally (return t)))
collect reaction))
;;; And we'll make a new PATHTO for this search as well; We'll
;;; call it FPATHSTO -- F for "Fast"! This version doesn't even
;;; do the superset duplicate removal!
(defmacro fpathsto (from to)
`(length (setq *pathways*
(paths-between (find-molecule ',from)
(find-molecule ',to)
*env*))))
| null | https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/OriginalCode/meta1.lisp | lisp | All rights reserved .
This software is made avilable for EDUCATIONAL PURPOSES
ONLY, and WITHOUT ANY WARRANTY, express or implied, of
its merchantability or fitness for a particular purpose.
Lefthand side
The abbreviation we'll use for convenience.
The pretty-printing name.
Reactions:
When the current path is NOT a superset of
anything else in the path list then collect it.
(Careful not to remove it when it matches itself!)
We copy the list
We have to come from a particular molecule, and we have to pass
the pathway down alongwith us, so that we can use the previous
reaction to constrain the search.
If we've found our goal, we're done! (LIST for appends up the stack.)
Track each SPECIFIC reaction product molecule into a new path.
This is a constrained version of POSSIBLE-REACTIONS.
The only difference is the (AND (MEMBER ...) ...) which
ensures that the reaction chosen also links to the FROM molecule.
And we'll make a new PATHTO for this search as well; We'll
call it FPATHSTO -- F for "Fast"! This version doesn't even
do the superset duplicate removal! |
(in-package USER)
(defstruct reaction
catalyst
Righthand side
)
(defstruct molecule
S , NS , or INS
)
(defvar *molecules* nil)
(defvar *reactions* nil)
(defmacro add-molecule (abbrev fullname type &rest constituents)
`(push (make-molecule :abbrev ',abbrev
:fullname ,fullname
:type ',type)
*molecules*))
(compile
(defun find-molecules (abbrevs)
(loop for molecule in *molecules*
when (member (molecule-abbrev molecule) abbrevs)
collect molecule)))
Same thing , but only for one molcule :
(compile
(defun find-molecule (abbrev)
(loop for molecule in *molecules*
when (eq (molecule-abbrev molecule) abbrev)
do (return molecule))))
(defmacro add-reaction (reactants products enzyme)
`(push (make-reaction :reactants (find-molecules ',reactants)
:catalyst ',enzyme
:products (find-molecules ',products)
)
*reactions*))
(defun init-objects ()
(setq *molecules* nil)
(add-molecule P "phosphatate" ins)
(add-molecule C "carbon" ins)
(add-molecule aden "adenosine" ns)
(add-molecule guan "guanosine" ns)
(add-molecule H+ "H+" ns)
(add-molecule H2O "H2O" ns)
(add-molecule NAD+ "NAD+" ns)
(add-molecule FAD "FAD" ns)
(add-molecule coa "CoA" s)
(add-molecule atp "ATP" ins)
(add-molecule adp "ADP" ins)
(add-molecule gdp "GDP" ins)
(add-molecule gtp "GTP" ins)
(add-molecule NADH "NADH" ns)
(add-molecule CO2 "Co2" ins)
(add-molecule FADH2 "FADH2" ns)
(add-molecule glu "glucose" s)
(add-molecule fru "fructose" s)
(add-molecule dha "dihydroxyacetone" s)
(add-molecule glh "glyceraldehyde" s)
(add-molecule gla "glycerate" s)
(add-molecule pyr "pyruvate" s)
(add-molecule ace "acetyl" s)
(add-molecule oxa "oxaloacetate" s)
(add-molecule cit "citrate" s)
(add-molecule ict "isocitrate" s)
(add-molecule akg "a-ketoglutarate" s)
(add-molecule suc "succinate" s)
(add-molecule fum "fumarate" s)
(add-molecule mal "malate" s)
(add-molecule g6p "glucose 6-phosphate" s)
(add-molecule f1p "fructose 1-phosphate" s)
(add-molecule f6p "fructose 6-phosphate" s)
(add-molecule fbp "fructose 1,6 bisphosphate" s)
(add-molecule dap "dihydrozyacetone phosphate" s)
(add-molecule g3p "glyceraldehyde 3-phosphate" s)
(add-molecule bpg "1,3-bisphosphoglycerate" s)
(add-molecule 3pg "3-phosphoglycerate" s)
(add-molecule 2pg "2-phosphoglycerate" s)
(add-molecule pep "phosphoenolpyruvate" s)
(add-molecule aca "acetyl CoA" s)
(add-molecule sca "succinyl CoA" s)
(setq *reactions* nil)
(add-reaction (fru) (f1p) "Fructokinase")
(add-reaction (f1p) (glh dap) "Fructose 1-phosphate aldolase")
(add-reaction (glh) (g3p) "G3p kinase")
(add-reaction (glu atp) (g6p adp) "Hexokinase")
(add-reaction (g6p) (f6p) "Phosphoglucomutase")
(add-reaction (f6p atp) (fbp adp) "Phosphofructokinase")
(add-reaction (fbp) (dap g3p) "Aldolase")
(add-reaction (dap) (g3p) "Isomerase")
(add-reaction (P NAD+ g3p) (NADH H+ bpg) "G3p dehydrogenase")
(add-reaction (bpg adp) (3pg atp) "Phosphoglycerate kinase")
(add-reaction (3pg) (2pg) "Phosphoglyceromutase")
(add-reaction (2pg) (pep H2O) "Enolase")
(add-reaction (pep atp) (pyr adp) "Pyruvate kinase")
(add-reaction (pyr NAD+ coa) (NADH H+ CO2 aca) "Citrate synthase")
(add-reaction (cit) (ict) "Aconitase")
(add-reaction (ict NAD+) (akg NADH H+ CO2) "Isocitrate dehydrogenase")
(add-reaction (akg NAD+ coa) (sca NADH H+ CO2) "a-ketogluterate dehydrogenase complex")
(add-reaction (sca gdp P) (suc gtp coa) "Succinyl CoA synthase")
(add-reaction (suc FAD) (fum FADH2) "Succinate dehydrogenase")
(add-reaction (fum H2O) (mal) "Fumerase")
(add-reaction (mal NAD+) (oxa NADH H+) "Malate dehydrogenase")
)
(defun pp-reaction (r)
(let* ((catalyst (reaction-catalyst r))
(reactants (reaction-reactants r))
(products (reaction-products r))
)
(pp-mols reactants)
(format t " --[~a]--> " catalyst)
(pp-mols products)
(format t "~%"))
r)
(defun pp-mols (m*)
(loop for m+ on m*
do (format t "~A" (molecule-fullname (car m+)))
(when (cdr m+)
(format t " + "))))
(defmacro pp-reactions (reactions)
`(loop for reaction in ,reactions
do (pp-reaction reaction)))
(defvar *env* nil)
(defun init-env ()
(setq *env*
(find-molecules '(frk f1pa tk atp adp gdp gtp fru glu NAD+ FAD P hxk pfk pgm ald
gapdh pgk pym eno pyk iso csy act idh adhc scs sdh fas mdh))))
(defvar *goal* nil)
(defun init-goal ()
(setq *goal* (find-molecule 'mal)))
(defun init ()
(init-objects)
(init-env)
(init-goal))
(compile
(defun possible-reactions (env)
(loop for reaction in *reactions*
when (loop for reactant in (reaction-reactants reaction)
when (not (find reactant env))
do (return nil)
finally (return t))
collect reaction)))
(compile
(defun apply-reaction (reaction env)
(append env
(loop for product in (reaction-products reaction)
unless (member product env)
collect product))))
(compile
(defun paths (env goal &optional path)
(cond ((find goal env) (list path))
(t (loop for reaction in (possible-reactions env)
append (paths (apply-reaction reaction env)
goal
(cons reaction path)))))))
(compile
(defun paths (env goal &optional path)
(cond ((find goal env) (list path))
(t (loop for reaction in (loop for reaction in (possible-reactions env)
when (not (member reaction path))
collect reaction)
append (paths (apply-reaction reaction env) goal (cons reaction path))))
)))
(defmacro pathsto (goal)
`(length (setq *pathways*
(paths *env* (find-molecule ',goal)))))
(compile
(defun remove-duplicate-paths (path*)
(loop for this-path in path*
when (loop for target-path in path*
when (and (not (eq this-path target-path))
(superset? this-path target-path))
do (return nil)
finally (return t))
collect this-path)))
(compile
(defun superset? (s1 s2)
(and (>= (length s1) (length s2))
(loop for a in s2
when (not (member a s1))
do (return nil)
finally (return t)))))
(defmacro pathsto (goal)
`(length (setq *pathways*
(remove-duplicate-paths
(paths *env* (find-molecule ',goal))))))
(defun ppp (&optional (pwys *pathways*))
(loop for path-n from 1 by 1
as path in pwys
do (format t "~%~%Pathway #~a:~%~%" path-n)
(pp-reactions (reverse (copy-list path)))))
(defun paths-between (from to &optional (env *env*) path)
(t (loop for reaction in (possible-reactions-from from env)
when (not (member reaction path))
append (paths-via (cons reaction path) to (apply-reaction reaction env))))
))
(defun paths-via (path to env)
(loop for link-mol in (reaction-products (car path))
when (eq 's (molecule-type link-mol))
append (paths-between link-mol to env path)))
(defun possible-reactions-from (from env)
(loop for reaction in *reactions*
as reactants = (reaction-reactants reaction)
when (and (member from reactants)
(loop for reactant in reactants
when (not (find reactant env))
do (return nil)
finally (return t)))
collect reaction))
(defmacro fpathsto (from to)
`(length (setq *pathways*
(paths-between (find-molecule ',from)
(find-molecule ',to)
*env*))))
|
f55b0e262ddb76f0f9ff1abf5e48104f8feec6da063b06deaa13ab28f82b608c | fimad/prometheus-haskell | HistogramSpec.hs | {-# language OverloadedStrings #-}
module Prometheus.Metric.HistogramSpec (
spec
) where
import Prometheus.Metric.Histogram
import Prometheus.Metric.Observer
import Prometheus.Registry
import Prometheus.Info
import qualified Data.Map.Strict as Map
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec = describe "Prometheus.Metric.Histogram" $ do
context "Maintains invariants" invariantTests
context "Laziness tests" observeToUnsafe
# NOINLINE testMetric #
testMetric :: Histogram
testMetric = do
unsafeRegister $ histogram (Info "test_histogram" "") defaultBuckets
observeToUnsafe :: Spec
observeToUnsafe =
it "Is able to observe to a top-level 'unsafeRegister' metric" $ do
observe testMetric 1 `shouldReturn` ()
--------------------------------------------------------------------------------
-- QuickCheck tests
invariantTests :: Spec
invariantTests = do
it "Total count is greater than or equal to sum of counts per bucket." $
property prop_totalCountVsCountPerBucket
prop_totalCountVsCountPerBucket :: [Double] -> Bool
prop_totalCountVsCountPerBucket observations =
let bucketCounts = bucketCountsAfterObserving observations
in sum (Map.elems (histCountsPerBucket bucketCounts)) <= histCount bucketCounts
bucketCountsAfterObserving :: [Double] -> BucketCounts
bucketCountsAfterObserving = foldr insert (emptyCounts defaultBuckets)
| null | https://raw.githubusercontent.com/fimad/prometheus-haskell/4e2c2f1da1f891e9de3ce5a5260ae92882a9f35e/prometheus-client/tests/Prometheus/Metric/HistogramSpec.hs | haskell | # language OverloadedStrings #
------------------------------------------------------------------------------
QuickCheck tests |
module Prometheus.Metric.HistogramSpec (
spec
) where
import Prometheus.Metric.Histogram
import Prometheus.Metric.Observer
import Prometheus.Registry
import Prometheus.Info
import qualified Data.Map.Strict as Map
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec = describe "Prometheus.Metric.Histogram" $ do
context "Maintains invariants" invariantTests
context "Laziness tests" observeToUnsafe
# NOINLINE testMetric #
testMetric :: Histogram
testMetric = do
unsafeRegister $ histogram (Info "test_histogram" "") defaultBuckets
observeToUnsafe :: Spec
observeToUnsafe =
it "Is able to observe to a top-level 'unsafeRegister' metric" $ do
observe testMetric 1 `shouldReturn` ()
invariantTests :: Spec
invariantTests = do
it "Total count is greater than or equal to sum of counts per bucket." $
property prop_totalCountVsCountPerBucket
prop_totalCountVsCountPerBucket :: [Double] -> Bool
prop_totalCountVsCountPerBucket observations =
let bucketCounts = bucketCountsAfterObserving observations
in sum (Map.elems (histCountsPerBucket bucketCounts)) <= histCount bucketCounts
bucketCountsAfterObserving :: [Double] -> BucketCounts
bucketCountsAfterObserving = foldr insert (emptyCounts defaultBuckets)
|
3d084d783e92f6002ebe5640880e992ab68412907d5bbc427a67f5a348115c03 | potapenko/playphraseme-site | favorites.clj | (ns playphraseme.api.routes.favorites
(:require [playphraseme.api.middleware.cors :refer [cors-mw]]
[playphraseme.api.middleware.token-auth :refer [token-auth-mw]]
[playphraseme.api.middleware.authenticated :refer [authenticated-mw]]
[playphraseme.api.route-functions.search.phrases-search :refer :all]
[playphraseme.api.queries.favorites :refer :all]
[ring.util.http-response :refer :all]
[compojure.api.sweet :refer :all]
[schema.core :as s]))
(def favorites-routes
"Specify routes for Favorites Phrases"
(context "/api/v1/favorites" []
:tags ["Favorites"]
(GET "/" request
:return s/Any
:middleware [token-auth-mw cors-mw authenticated-mw]
:header-params [authorization :- String]
:query-params [{skip :- s/Num 0} {limit :- s/Num 10}]
:summary "Return user favorites"
(let [user-id (-> request :identity :id)]
(ok {:count (get-favorites-count user-id)
:favorites (get-favorites-by-user user-id skip limit)})))
(GET "/:phrase-id" [phrase-id :as request]
:return s/Any
:middleware [token-auth-mw cors-mw authenticated-mw]
:header-params [authorization :- String]
:summary "Get phrase favorite"
(let [user-id (-> request :identity :id)]
(ok (get-favorite-by-phrase-id phrase-id user-id))))
(POST "/:phrase-id" [phrase-id :as request]
:return s/Str
:middleware [token-auth-mw cors-mw authenticated-mw]
:summary "Add favorite"
(do (insert-favorite! phrase-id (-> request :identity :id))
(ok "OK")))
(DELETE "/:phrase-id" [phrase-id :as request]
:return s/Str
:middleware [token-auth-mw cors-mw authenticated-mw]
:summary "Remove favorite"
(do (delete-favorite-by-phrase-id! phrase-id (-> request :identity :id))
(ok "OK")))))
| null | https://raw.githubusercontent.com/potapenko/playphraseme-site/d50a62a6bc8f463e08365dca96b3a6e5dde4fb12/src/clj/playphraseme/api/routes/favorites.clj | clojure | (ns playphraseme.api.routes.favorites
(:require [playphraseme.api.middleware.cors :refer [cors-mw]]
[playphraseme.api.middleware.token-auth :refer [token-auth-mw]]
[playphraseme.api.middleware.authenticated :refer [authenticated-mw]]
[playphraseme.api.route-functions.search.phrases-search :refer :all]
[playphraseme.api.queries.favorites :refer :all]
[ring.util.http-response :refer :all]
[compojure.api.sweet :refer :all]
[schema.core :as s]))
(def favorites-routes
"Specify routes for Favorites Phrases"
(context "/api/v1/favorites" []
:tags ["Favorites"]
(GET "/" request
:return s/Any
:middleware [token-auth-mw cors-mw authenticated-mw]
:header-params [authorization :- String]
:query-params [{skip :- s/Num 0} {limit :- s/Num 10}]
:summary "Return user favorites"
(let [user-id (-> request :identity :id)]
(ok {:count (get-favorites-count user-id)
:favorites (get-favorites-by-user user-id skip limit)})))
(GET "/:phrase-id" [phrase-id :as request]
:return s/Any
:middleware [token-auth-mw cors-mw authenticated-mw]
:header-params [authorization :- String]
:summary "Get phrase favorite"
(let [user-id (-> request :identity :id)]
(ok (get-favorite-by-phrase-id phrase-id user-id))))
(POST "/:phrase-id" [phrase-id :as request]
:return s/Str
:middleware [token-auth-mw cors-mw authenticated-mw]
:summary "Add favorite"
(do (insert-favorite! phrase-id (-> request :identity :id))
(ok "OK")))
(DELETE "/:phrase-id" [phrase-id :as request]
:return s/Str
:middleware [token-auth-mw cors-mw authenticated-mw]
:summary "Remove favorite"
(do (delete-favorite-by-phrase-id! phrase-id (-> request :identity :id))
(ok "OK")))))
|
|
e104670e6ca5a2cb401118a13a65ffa4d6da615df6a816bb56aa4180dd2f9d66 | diskuv/dkml-c-probe | show_conf_signature.ml | #use "topfind";;
#require "dkml-c-probe";;
#show Dkml_c_probe.C_conf;;
| null | https://raw.githubusercontent.com/diskuv/dkml-c-probe/c852632a1c091ed212c8af13b4544294cfe03e4b/samples/show_conf_signature.ml | ocaml | #use "topfind";;
#require "dkml-c-probe";;
#show Dkml_c_probe.C_conf;;
|
|
279319784e5b0f8f3ef96443d3f5d1f18457129a99d2cb008ed2a40cc7057502 | ckruse/irckerl | irc_parser_test.erl | Copyright ( C ) 2011 by < >
%% 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.
-module(irc_parser_test).
-author("Christian Kruse <>").
-vsn("0.1").
-include("irckerl.hrl").
-include_lib("eunit/include/eunit.hrl").
parse_prefix_test() ->
?assertMatch(
{ok, #irc_cmd{prefix = {"gagarin.epd-me.net"}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<":gagarin.epd-me.net NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<"NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {"cjk101010", "ckruse", "localhost"}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<":cjk101010!ckruse@localhost NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {"cjk101010", "ckruse", ""}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<":cjk101010!ckruse NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {"cjk101010[]", "", ""}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<":cjk101010[] NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{error, _},
irc_parser:parse(<<":cjk101010__ NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertEqual(
{ok, {"cjk101010"}},
irc_parser:parse_prefix(<<":cjk101010">>)
).
parse_test() ->
?assertMatch(
{error, _},
irc_parser:parse(<<":lala __">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {}, cmd = "JOIN", params = [["#lala","#lulu"]]}},
irc_parser:parse(<<"JOIN #lala,#lulu">>)
).
eof
| null | https://raw.githubusercontent.com/ckruse/irckerl/2fd47c79a74b580d2d1448d15c5e9e2271e58daa/test/irc_parser_test.erl | erlang | Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. | Copyright ( C ) 2011 by < >
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
-module(irc_parser_test).
-author("Christian Kruse <>").
-vsn("0.1").
-include("irckerl.hrl").
-include_lib("eunit/include/eunit.hrl").
parse_prefix_test() ->
?assertMatch(
{ok, #irc_cmd{prefix = {"gagarin.epd-me.net"}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<":gagarin.epd-me.net NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<"NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {"cjk101010", "ckruse", "localhost"}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<":cjk101010!ckruse@localhost NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {"cjk101010", "ckruse", ""}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<":cjk101010!ckruse NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {"cjk101010[]", "", ""}, cmd = "NOTICE", params = [["AUTH"], ["*** Looking up your hostname..."]]}},
irc_parser:parse(<<":cjk101010[] NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertMatch(
{error, _},
irc_parser:parse(<<":cjk101010__ NOTICE AUTH :*** Looking up your hostname...">>)
),
?assertEqual(
{ok, {"cjk101010"}},
irc_parser:parse_prefix(<<":cjk101010">>)
).
parse_test() ->
?assertMatch(
{error, _},
irc_parser:parse(<<":lala __">>)
),
?assertMatch(
{ok, #irc_cmd{prefix = {}, cmd = "JOIN", params = [["#lala","#lulu"]]}},
irc_parser:parse(<<"JOIN #lala,#lulu">>)
).
eof
|
728a4088a99203f941661afec74651f31db30fde1d11b4ee403b6f583ac1454d | msgpack/msgpack-haskell | Put.hs | # LANGUAGE LambdaCase #
--------------------------------------------------------------------
-- |
-- Module : Data.MessagePack.Put
Copyright : © Hideyuki Tanaka 2009 - 2015
, 2019
-- License : BSD3
--
-- MessagePack Serializer using "Data.Binary".
--
--------------------------------------------------------------------
module Data.MessagePack.Put (
putNil, putBool, putFloat, putDouble,
putInt, putWord, putInt64, putWord64,
putStr, putBin, putArray, putArray', putMap, putExt, putExt'
) where
import Compat.Prelude
import Prelude hiding (putStr)
import qualified Data.ByteString as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import Compat.Binary
import Data.MessagePack.Integer
import Data.MessagePack.Tags
putNil :: Put
putNil = putWord8 TAG_nil
putBool :: Bool -> Put
putBool False = putWord8 TAG_false
putBool True = putWord8 TAG_true
| Encodes an ' Int ' to MessagePack
--
-- See also 'MPInteger' and its 'Binary' instance.
putInt :: Int -> Put
putInt = put . toMPInteger
| @since 1.0.1.0
putWord :: Word -> Put
putWord = put . toMPInteger
| @since 1.0.1.0
putInt64 :: Int64 -> Put
putInt64 = put . toMPInteger
| @since 1.0.1.0
putWord64 :: Word64 -> Put
putWord64 = put . toMPInteger
putFloat :: Float -> Put
putFloat f = putWord8 TAG_float32 >> putFloat32be f
putDouble :: Double -> Put
putDouble d = putWord8 TAG_float64 >> putFloat64be d
putStr :: T.Text -> Put
putStr t = do
let bs = T.encodeUtf8 t
toSizeM ("putStr: data exceeds 2^32-1 byte limit of MessagePack") (S.length bs) >>= \case
len | len < 32 -> putWord8 (TAG_fixstr .|. fromIntegral len)
| len < 0x100 -> putWord8 TAG_str8 >> putWord8 (fromIntegral len)
| len < 0x10000 -> putWord8 TAG_str16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_str32 >> putWord32be (fromIntegral len)
putByteString bs
putBin :: S.ByteString -> Put
putBin bs = do
toSizeM ("putBin: data exceeds 2^32-1 byte limit of MessagePack") (S.length bs) >>= \case
len | len < 0x100 -> putWord8 TAG_bin8 >> putWord8 (fromIntegral len)
| len < 0x10000 -> putWord8 TAG_bin16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_bin32 >> putWord32be (fromIntegral len)
putByteString bs
putArray :: (a -> Put) -> V.Vector a -> Put
putArray p xs = do
len <- toSizeM ("putArray: data exceeds 2^32-1 element limit of MessagePack") (V.length xs)
putArray' len (V.mapM_ p xs)
-- | @since 1.1.0.0
putArray' :: Word32 -- ^ number of array elements
-> Put -- ^ 'Put' action emitting array elements (__NOTE__: it's the responsibility of the caller to ensure that the declared array length matches exactly the data generated by the 'Put' action)
-> Put
putArray' len putter = do
case () of
_ | len < 16 -> putWord8 (TAG_fixarray .|. fromIntegral len)
| len < 0x10000 -> putWord8 TAG_array16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_array32 >> putWord32be (fromIntegral len)
putter
putMap :: (a -> Put) -> (b -> Put) -> V.Vector (a, b) -> Put
putMap p q xs = do
toSizeM ("putMap: data exceeds 2^32-1 element limit of MessagePack") (V.length xs) >>= \case
len | len < 16 -> putWord8 (TAG_fixmap .|. fromIntegral len)
| len < 0x10000 -> putWord8 TAG_map16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_map32 >> putWord32be (fromIntegral len)
V.mapM_ (\(a, b) -> p a >> q b) xs
| _ _ NOTE _ _ : MessagePack is limited to maximum extended data payload size of \ ( 2^{32}-1 \ ) bytes .
putExt :: Int8 -> S.ByteString -> Put
putExt typ dat = do
sz <- toSizeM "putExt: data exceeds 2^32-1 byte limit of MessagePack" (S.length dat)
putExt' typ (sz, putByteString dat)
-- | @since 1.1.0.0
^ type - id of extension data ( _ _ NOTE _ _ : The values @ [ -128 .. -2 ] @ are reserved for future use by the MessagePack specification ) .
-> (Word32,Put) -- ^ @(size-of-data, data-'Put'-action)@ (__NOTE__: it's the responsibility of the caller to ensure that the declared size matches exactly the data generated by the 'Put' action)
-> Put
putExt' typ (sz,putdat) = do
case sz of
1 -> putWord8 TAG_fixext1
2 -> putWord8 TAG_fixext2
4 -> putWord8 TAG_fixext4
8 -> putWord8 TAG_fixext8
16 -> putWord8 TAG_fixext16
len | len < 0x100 -> putWord8 TAG_ext8 >> putWord8 (fromIntegral len)
| len < 0x10000 -> putWord8 TAG_ext16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_ext32 >> putWord32be (fromIntegral len)
putInt8 typ
putdat
----------------------------------------------------------------------------
toSizeM :: String -> Int -> PutM Word32
toSizeM label len0 = maybe (error label) pure (intCastMaybe len0)
| null | https://raw.githubusercontent.com/msgpack/msgpack-haskell/f52a5d2db620a7be70810eca648fd152141f8b14/msgpack/src/Data/MessagePack/Put.hs | haskell | ------------------------------------------------------------------
|
Module : Data.MessagePack.Put
License : BSD3
MessagePack Serializer using "Data.Binary".
------------------------------------------------------------------
See also 'MPInteger' and its 'Binary' instance.
| @since 1.1.0.0
^ number of array elements
^ 'Put' action emitting array elements (__NOTE__: it's the responsibility of the caller to ensure that the declared array length matches exactly the data generated by the 'Put' action)
| @since 1.1.0.0
^ @(size-of-data, data-'Put'-action)@ (__NOTE__: it's the responsibility of the caller to ensure that the declared size matches exactly the data generated by the 'Put' action)
-------------------------------------------------------------------------- | # LANGUAGE LambdaCase #
Copyright : © Hideyuki Tanaka 2009 - 2015
, 2019
module Data.MessagePack.Put (
putNil, putBool, putFloat, putDouble,
putInt, putWord, putInt64, putWord64,
putStr, putBin, putArray, putArray', putMap, putExt, putExt'
) where
import Compat.Prelude
import Prelude hiding (putStr)
import qualified Data.ByteString as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import Compat.Binary
import Data.MessagePack.Integer
import Data.MessagePack.Tags
putNil :: Put
putNil = putWord8 TAG_nil
putBool :: Bool -> Put
putBool False = putWord8 TAG_false
putBool True = putWord8 TAG_true
| Encodes an ' Int ' to MessagePack
putInt :: Int -> Put
putInt = put . toMPInteger
| @since 1.0.1.0
putWord :: Word -> Put
putWord = put . toMPInteger
| @since 1.0.1.0
putInt64 :: Int64 -> Put
putInt64 = put . toMPInteger
| @since 1.0.1.0
putWord64 :: Word64 -> Put
putWord64 = put . toMPInteger
putFloat :: Float -> Put
putFloat f = putWord8 TAG_float32 >> putFloat32be f
putDouble :: Double -> Put
putDouble d = putWord8 TAG_float64 >> putFloat64be d
putStr :: T.Text -> Put
putStr t = do
let bs = T.encodeUtf8 t
toSizeM ("putStr: data exceeds 2^32-1 byte limit of MessagePack") (S.length bs) >>= \case
len | len < 32 -> putWord8 (TAG_fixstr .|. fromIntegral len)
| len < 0x100 -> putWord8 TAG_str8 >> putWord8 (fromIntegral len)
| len < 0x10000 -> putWord8 TAG_str16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_str32 >> putWord32be (fromIntegral len)
putByteString bs
putBin :: S.ByteString -> Put
putBin bs = do
toSizeM ("putBin: data exceeds 2^32-1 byte limit of MessagePack") (S.length bs) >>= \case
len | len < 0x100 -> putWord8 TAG_bin8 >> putWord8 (fromIntegral len)
| len < 0x10000 -> putWord8 TAG_bin16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_bin32 >> putWord32be (fromIntegral len)
putByteString bs
putArray :: (a -> Put) -> V.Vector a -> Put
putArray p xs = do
len <- toSizeM ("putArray: data exceeds 2^32-1 element limit of MessagePack") (V.length xs)
putArray' len (V.mapM_ p xs)
-> Put
putArray' len putter = do
case () of
_ | len < 16 -> putWord8 (TAG_fixarray .|. fromIntegral len)
| len < 0x10000 -> putWord8 TAG_array16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_array32 >> putWord32be (fromIntegral len)
putter
putMap :: (a -> Put) -> (b -> Put) -> V.Vector (a, b) -> Put
putMap p q xs = do
toSizeM ("putMap: data exceeds 2^32-1 element limit of MessagePack") (V.length xs) >>= \case
len | len < 16 -> putWord8 (TAG_fixmap .|. fromIntegral len)
| len < 0x10000 -> putWord8 TAG_map16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_map32 >> putWord32be (fromIntegral len)
V.mapM_ (\(a, b) -> p a >> q b) xs
| _ _ NOTE _ _ : MessagePack is limited to maximum extended data payload size of \ ( 2^{32}-1 \ ) bytes .
putExt :: Int8 -> S.ByteString -> Put
putExt typ dat = do
sz <- toSizeM "putExt: data exceeds 2^32-1 byte limit of MessagePack" (S.length dat)
putExt' typ (sz, putByteString dat)
^ type - id of extension data ( _ _ NOTE _ _ : The values @ [ -128 .. -2 ] @ are reserved for future use by the MessagePack specification ) .
-> Put
putExt' typ (sz,putdat) = do
case sz of
1 -> putWord8 TAG_fixext1
2 -> putWord8 TAG_fixext2
4 -> putWord8 TAG_fixext4
8 -> putWord8 TAG_fixext8
16 -> putWord8 TAG_fixext16
len | len < 0x100 -> putWord8 TAG_ext8 >> putWord8 (fromIntegral len)
| len < 0x10000 -> putWord8 TAG_ext16 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 TAG_ext32 >> putWord32be (fromIntegral len)
putInt8 typ
putdat
toSizeM :: String -> Int -> PutM Word32
toSizeM label len0 = maybe (error label) pure (intCastMaybe len0)
|
045444516058552118e02c195b6d10ef0551b80dabafe61b4f04cd6fd3b7c593 | khibino/haskell-relational-record | Persistable.hs | module Database.HDBC.PostgreSQL.Persistable
# DEPRECATED " import Database . Record . HDBC.PostgreSQL " #
() where
import Database.Relational.HDBC.PostgreSQL ()
| null | https://raw.githubusercontent.com/khibino/haskell-relational-record/759b3d7cea207e64d2bd1cf195125182f73d2a52/persistable-types-HDBC-pg/src/Database/HDBC/PostgreSQL/Persistable.hs | haskell | module Database.HDBC.PostgreSQL.Persistable
# DEPRECATED " import Database . Record . HDBC.PostgreSQL " #
() where
import Database.Relational.HDBC.PostgreSQL ()
|
|
fd34b73a9aa95acdbe1e03e5748c2d6a53a5b342b35d00a6cf92867e18cade41 | fakedata-haskell/fakedata | BoJackHorseman.hs | {-# LANGUAGE OverloadedStrings #-}
module Faker.TvShow.BoJackHorseman where
import Data.Text
import Faker
import Faker.Internal
import Faker.Provider.BoJackHorseman
character :: Fake Text
character =
Fake $
cachedRandomVec "boJackHorseman" "character" boJackHorsemanCharacterProvider
quote :: Fake Text
quote =
Fake $ cachedRandomVec "boJackHorseman" "quote" boJackHorsemanQuoteProvider
tongueTwister :: Fake Text
tongueTwister =
Fake $
cachedRandomVec "boJackHorseman" "quote" boJackHorsemanTongueTwisterProvider
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/src/Faker/TvShow/BoJackHorseman.hs | haskell | # LANGUAGE OverloadedStrings # |
module Faker.TvShow.BoJackHorseman where
import Data.Text
import Faker
import Faker.Internal
import Faker.Provider.BoJackHorseman
character :: Fake Text
character =
Fake $
cachedRandomVec "boJackHorseman" "character" boJackHorsemanCharacterProvider
quote :: Fake Text
quote =
Fake $ cachedRandomVec "boJackHorseman" "quote" boJackHorsemanQuoteProvider
tongueTwister :: Fake Text
tongueTwister =
Fake $
cachedRandomVec "boJackHorseman" "quote" boJackHorsemanTongueTwisterProvider
|
2e46810ea995db7fe009b79a7341712f4ab8e0e206539ef136bc1b59e6ff5d79 | prl-julia/juliette-wa | redex.rkt | #lang racket
(require redex)
; import surface language
(require "../../../src/redex/core/wa-surface.rkt")
; import full language
(require "../../../src/redex/core/wa-full.rkt")
; import optimizations
(require "../../../src/redex/optimizations/wa-optimized.rkt")
(displayln "Test for litmus-wa/test06:")
(define p
(term
(evalg
(seq
(mdef "l" () (evalg (seq (evalg (mdef "f1" () 2)) (mcall f1))))
(mcall l))))
)
(test-equal (term (run-to-r ,p)) (term 2))
(test-results) | null | https://raw.githubusercontent.com/prl-julia/juliette-wa/1d1a2154e7b4e232ea2166fba485a3bf574ebd88/tests/litmus-wa/test06/redex.rkt | racket | import surface language
import full language
import optimizations | #lang racket
(require redex)
(require "../../../src/redex/core/wa-surface.rkt")
(require "../../../src/redex/core/wa-full.rkt")
(require "../../../src/redex/optimizations/wa-optimized.rkt")
(displayln "Test for litmus-wa/test06:")
(define p
(term
(evalg
(seq
(mdef "l" () (evalg (seq (evalg (mdef "f1" () 2)) (mcall f1))))
(mcall l))))
)
(test-equal (term (run-to-r ,p)) (term 2))
(test-results) |
67aef24d8ecfd4c11c327c56d084cf5d93aa740f9af15eb6ae437d135c0fb56c | xclerc/ocamljava | javalink_parameters.mli |
* This file is part of compiler .
* Copyright ( C ) 2007 - 2015 .
*
* compiler is free software ; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* ( with a change to choice of law ) .
*
* compiler 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
* Q Public License for more details .
*
* You should have received a copy of the Q Public License
* along with this program . If not , see
* < -1.0 > .
* This file is part of OCaml-Java compiler.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java compiler is free software; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* Trolltech (with a change to choice of law).
*
* OCaml-Java compiler 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
* Q Public License for more details.
*
* You should have received a copy of the Q Public License
* along with this program. If not, see
* <-1.0>.
*)
(** Check and compile a runtime parameter list. *)
val compile : string list -> BaristaLibrary.Bytes.t
(** Compile the passed runtime parameter list, raising an exception if
any parameter is invalid. *)
| null | https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/compiler/javacomp/javalink_parameters.mli | ocaml | * Check and compile a runtime parameter list.
* Compile the passed runtime parameter list, raising an exception if
any parameter is invalid. |
* This file is part of compiler .
* Copyright ( C ) 2007 - 2015 .
*
* compiler is free software ; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* ( with a change to choice of law ) .
*
* compiler 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
* Q Public License for more details .
*
* You should have received a copy of the Q Public License
* along with this program . If not , see
* < -1.0 > .
* This file is part of OCaml-Java compiler.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java compiler is free software; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* Trolltech (with a change to choice of law).
*
* OCaml-Java compiler 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
* Q Public License for more details.
*
* You should have received a copy of the Q Public License
* along with this program. If not, see
* <-1.0>.
*)
val compile : string list -> BaristaLibrary.Bytes.t
|
e30157d4ae1042d38d33d3e49b1cbc1bc12b408f8f6e226d11bec0f951f63cbc | mbg/hindley-milner | TypeSpec.hs | --------------------------------------------------------------------------------
module Language.HM.TypeSpec where
--------------------------------------------------------------------------------
import Test.Hspec
import qualified Data.Set as S
import Language.HM
--------------------------------------------------------------------------------
t0 :: Sigma
t0 = forAllT "a" (monoT $ (varT "a") `arrowT` (varT "a"))
t1 :: Sigma
t1 = forAllT "b" (monoT $ (varT "b") `arrowT` (varT "b"))
t2 :: Sigma
t2 = forAllT "b" (monoT $ (varT "b") `arrowT` (varT "a"))
t3 :: Sigma
t3 = monoT $ varT "a"
t4 :: Sigma
t4 = monoT $ varT "b"
spec :: Spec
spec = do
describe "alpha equivalence" $ do
context "are alpha equivalent" $ do
it "same type" $ alphaEq t0 t0 `shouldBe` True
it "alpha-equivalent type" $ alphaEq t0 t1 `shouldBe` True
context "are not alpha equivalent" $ do
it "free variable 1" $ alphaEq t0 t2 `shouldBe` False
it "free variable 2" $ alphaEq t3 t4 `shouldBe` False
describe "type variables" $ do
it "t0" $ tyVars t0 `shouldBe` S.fromList []
it "t1" $ tyVars t1 `shouldBe` S.fromList []
it "t2" $ tyVars t2 `shouldBe` S.fromList ["a"]
it "t3" $ tyVars t3 `shouldBe` S.fromList ["a"]
it "t4" $ tyVars t4 `shouldBe` S.fromList ["b"]
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/mbg/hindley-milner/015679609409df8c6c2632a99e16aa271f37ed5d/test/Language/HM/TypeSpec.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ |
module Language.HM.TypeSpec where
import Test.Hspec
import qualified Data.Set as S
import Language.HM
t0 :: Sigma
t0 = forAllT "a" (monoT $ (varT "a") `arrowT` (varT "a"))
t1 :: Sigma
t1 = forAllT "b" (monoT $ (varT "b") `arrowT` (varT "b"))
t2 :: Sigma
t2 = forAllT "b" (monoT $ (varT "b") `arrowT` (varT "a"))
t3 :: Sigma
t3 = monoT $ varT "a"
t4 :: Sigma
t4 = monoT $ varT "b"
spec :: Spec
spec = do
describe "alpha equivalence" $ do
context "are alpha equivalent" $ do
it "same type" $ alphaEq t0 t0 `shouldBe` True
it "alpha-equivalent type" $ alphaEq t0 t1 `shouldBe` True
context "are not alpha equivalent" $ do
it "free variable 1" $ alphaEq t0 t2 `shouldBe` False
it "free variable 2" $ alphaEq t3 t4 `shouldBe` False
describe "type variables" $ do
it "t0" $ tyVars t0 `shouldBe` S.fromList []
it "t1" $ tyVars t1 `shouldBe` S.fromList []
it "t2" $ tyVars t2 `shouldBe` S.fromList ["a"]
it "t3" $ tyVars t3 `shouldBe` S.fromList ["a"]
it "t4" $ tyVars t4 `shouldBe` S.fromList ["b"]
|
0e20b20a0ab22a007566c3b83e7d5813f6596303c968df3c5cca860f9ded3dae | yuriy-chumak/ol | opengl.scm | (runtime-error "Example deprecated!" '())
(define SHADER_NUM 1)
/ - The Scheme Programming Language ( Fourth Edition )
; -faq-standards#implementations
;!
(define *USE_GLBEGIN* 1)
(import (owl ffi))
(import (lib windows))
(import (OpenGL version-2-1))
; вспомогательный макрос для собрать в кучку все bor
(define OR (lambda list (fold bor 0 list)))
(define width 1280)
(define height 720)
(define window (CreateWindowEx
# 32770 is for system classname for DIALOG
(OR WS_OVERLAPPEDWINDOW WS_CLIPSIBLINGS WS_CLIPCHILDREN)
0 0 width height ; x y width height
null ; no parent window
null ; no menu
null ; instance
todo : override as ' ( INTEGER . 0 )
переключение режим -
; PIXELFORMATDESCRIPTOR
(define pfd (list->bytevector '(#x28 00 1 00 #x25 00 00 00 00 #x10 00 00 00 00 00 00
00 00 00 00 00 00 00 #x10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00)))
(define hDC (GetDC window))
(define PixelFormat (ChoosePixelFormat hDC pfd))
(print "PixelFormat = " PixelFormat)
(print "SetPixelFormat = "
(SetPixelFormat hDC PixelFormat pfd))
(define hRC (wglCreateContext hDC))
(print "wglMakeCurrent = "
(wglMakeCurrent hDC hRC))
(print "OpenGL version: " (glGetString GL_VERSION))
(print "OpenGL vendor: " (glGetString GL_VENDOR))
(print "OpenGL renderer: " (glGetString GL_RENDERER))
todo : тип для ( dlsym ) - всегда число ,
my temporary stubs for opengl ( у меня пока ж и т.д . )
; real code
(define void fft-void)
void GLvoid
typedef unsigned int GLenum - fix+ значит , что это целое число
(define GLfloat fft-float) ; typedef float GLfloat (same as type-rational)
typedef int GLint
typedef int
typedef unsigned int GLbitfield ;
typedef double ;
typedef unsigned int GLuint ;
typedef unsigned ;
(define GLubyte type-int+) ;typedef unsigned char GLubyte;
(define GLubyte* type-string)
(define GLclampf fft-float)
проверка , что все запустилось .
(define (msgbox)
(if (=
(MessageBox 0 "Please, press OK for test pass!" "load-library test"
(bor MB_OKCANCEL MB_ICONASTERISK))
IDOK)
(print "OK")
(print "CANCEL")))
; todo: вроде бы все строки и так заканчиваются на '\0' - проверить
;(define echo "echo server")
; в момент импорта сделать все нужные привязки
export ( MessageBox ) и т.д .
(define GLchar** type-vector)
(define GLint* type-vptr)
(define GLsizei* type-vptr)
(define GLchar* type-string)
(define void* type-vptr)
; opengl 1.2
(define glCreateShader (glGetProcAddress GLuint "glCreateShader" GLenum))
(define GL_VERTEX_SHADER #x8B31)
(define GL_FRAGMENT_SHADER #x8B30)
(define glShaderSource (glGetProcAddress void "glShaderSource" GLuint GLsizei GLchar** GLint*))
(define glCompileShader (glGetProcAddress void "glCompileShader" GLuint))
(define glCreateProgram (glGetProcAddress GLuint "glCreateProgram"))
(define glAttachShader (glGetProcAddress void "glAttachShader" GLuint GLuint))
(define glDetachShader (glGetProcAddress void "glDetachShader" GLuint GLuint))
(define glLinkProgram (glGetProcAddress void "glLinkProgram" GLuint))
(define glUseProgram (glGetProcAddress void "glUseProgram" GLuint))
(define glGetShaderiv (glGetProcAddress void "glGetShaderiv" GLuint GLenum GLint*))
(define GL_COMPILE_STATUS #x8B81)
(define GL_LINK_STATUS #x8B82)
(define GL_VALIDATE_STATUS #x8B83)
(define GL_INFO_LOG_LENGTH #x8B84)
(define glGetShaderInfoLog (glGetProcAddress void "glGetShaderInfoLog" GLuint GLsizei GLsizei* GLchar*))
(define glGetUniformLocation (glGetProcAddress GLint "glGetUniformLocation" GLuint GLchar*))
(define glUniform1i (glGetProcAddress void "glUniform1i" GLint GLint))
(define glUniform1f (glGetProcAddress void "glUniform1f" GLint GLfloat))
(define glUniform2f (glGetProcAddress void "glUniform2f" GLint GLfloat GLfloat))
(define glEnableVertexAttribArray (glGetProcAddress void "glEnableVertexAttribArray" GLuint))
(define glVertexAttribPointer (glGetProcAddress void "glVertexAttribPointer" GLuint GLint GLenum GLboolean GLsizei void*))
(define GL_FLOAT #x1406)
(define glDrawArrays (glGetProcAddress void "glDrawArrays" GLenum GLint GLsizei))
(define (file->string path)
(bytes->string
(blob-iter
(let ((vec (file->bytevector path)))
(if vec vec
(error "Unable to load: " path))))))
пример как
а можно еще попробовать их
;(fasl-save (file->string "raw/geometry.fs") "raw/geometry.compiled.fs")
( fasl - load " raw / geometry.compiled.fs " " void main(void ) { gl_FragColor = vec4(1.0 , 0.0 , 0.0 , 1.0 ) ; } " )
(define po (glCreateProgram))
(print "po: " po)
(define vs (glCreateShader GL_VERTEX_SHADER))
(print "vs: " vs)
пример , как можно на строки :
(glShaderSource vs 2 ["#version 120 // OpenGL 2.1\n"
"
void main() {
// - vec4(1.0 , 1.0 , 0.0 , 0.0 ) ; // gl_ModelViewMatrix *
}"] null)
(glCompileShader vs)
(define isCompiled "word")
(glGetShaderiv vs GL_COMPILE_STATUS isCompiled)
(if (= (ref isCompiled 0) 0)
(begin
(define maxLength "word")
(glGetShaderiv vs GL_INFO_LOG_LENGTH maxLength)
(define maxLengthValue (+ (ref maxLength 0) (* (ref maxLength 1) 256)))
(define errorLog (make-string maxLengthValue 0))
(glGetShaderInfoLog vs maxLengthValue maxLength errorLog)
(print errorLog)
(print "@")
(halt 0)))
(glAttachShader po vs)
;; полезные шейдеры:
;; #19171.3 - цифровое табло
(define fs (glCreateShader GL_FRAGMENT_SHADER))
(glShaderSource fs 1 [(file->string
(case SHADER_NUM
(2 "raw/geometry.fs")
(3 "raw/water.fs")
(4 "raw/18850")
(5 "raw/minecraft.fs")
(6 "raw/moon.fs")
(0 "raw/black.fs")
(1 "raw/itsfullofstars.fs")))] null)
(glCompileShader fs)
(define isCompiled "word")
(glGetShaderiv fs GL_COMPILE_STATUS isCompiled)
(if (= (ref isCompiled 0) 0)
(begin
(define maxLength "word")
(glGetShaderiv fs GL_INFO_LOG_LENGTH maxLength)
(define maxLengthValue (+ (ref maxLength 0) (* (ref maxLength 1) 256)))
(define errorLog (make-string maxLengthValue 0))
(glGetShaderInfoLog fs maxLengthValue maxLength errorLog)
(print errorLog)
(print "@")
(halt 0)))
(glAttachShader po fs)
(glLinkProgram po)
(glDetachShader po fs)
(glDetachShader po vs)
(define time (glGetUniformLocation po "time"))
(define resolution (glGetUniformLocation po "resolution"))
;(print "glGetUniformLocation: " (glGetUniformLocation po "color"))
(ShowWindow window SW_SHOW)
(SetForegroundWindow window)
(SetFocus window)
; ResizeGLScene
(glViewport 0 0 width height)
(glMatrixMode GL_PROJECTION)
(glLoadIdentity)
(glMatrixMode GL_MODELVIEW)
(glLoadIdentity)
(glShadeModel GL_SMOOTH)
(glClearColor 0 0 1 1)
( define ( list->bytevector ' (
( glVertex2i 2 0 )
00 00 # x00 # x40 0 0 # x00 # x00 0 0 0 0 00 00 # x80 # x3F
( glVertex2i 1 2 )
00 00 # x80 # x3F 0 0 # x00 # x40 0 0 0 0 00 00 # x80 # x3F
;; (glVertex2i 0 0)
00 00 # x00 # x00 0 0 # x00 # x00 0 0 0 0 00 00 # x80 # x3F
;)))
( define MSG ( make - bytevector 28 0 ) ) ; sizeof(MSG)=28
sizeof(MSG)=28
;(call/cc (lambda (return)
(let cycle () ;MSG
(if (= 1 (PeekMessage MSG null 0 0 PM_REMOVE))
(begin
(TranslateMessage MSG)
(DispatchMessage MSG))
(begin ; DrawGLScene
(glClear GL_COLOR_BUFFER_BIT)
(glUseProgram po)
(let* ((ss ms (clock)))
раз в час будем сбрасывать период
(if (> resolution 0)
(glUniform2f resolution width height))
(glBegin GL_TRIANGLE_STRIP)
( glVertex3i 0 0 0 )
( glVertex3i 2 0 0 )
; (glVertex3i 0 2 0)
( glVertex3i 2 2 0 )
(glVertex2f -1 -1)
(glVertex2f +1 -1)
(glVertex2f -1 +1)
(glVertex2f +1 +1)
(glEnd)
; (glEnableVertexAttribArray 0)
( glVertexAttribPointer 0 4 0 0 vertexPositions )
( glDrawArrays GL_TRIANGLES 0 3 )
(glUseProgram 0)
(SwapBuffers hDC)))
(if (= (GetAsyncKeyState 27) 0) (cycle)))
KillGLWindow
; (wglMakeCurrent 0 0)
(wglDeleteContext hRC)
(ReleaseDC window hDC)
(DestroyWindow window)
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/tests/disabled/opengl.scm | scheme | -faq-standards#implementations
!
вспомогательный макрос для собрать в кучку все bor
x y width height
no parent window
no menu
instance
PIXELFORMATDESCRIPTOR
real code
typedef float GLfloat (same as type-rational)
typedef unsigned char GLubyte;
todo: вроде бы все строки и так заканчиваются на '\0' - проверить
(define echo "echo server")
в момент импорта сделать все нужные привязки
opengl 1.2
(fasl-save (file->string "raw/geometry.fs") "raw/geometry.compiled.fs")
// gl_ModelViewMatrix *
полезные шейдеры:
#19171.3 - цифровое табло
(print "glGetUniformLocation: " (glGetUniformLocation po "color"))
ResizeGLScene
(glVertex2i 0 0)
)))
sizeof(MSG)=28
(call/cc (lambda (return)
MSG
DrawGLScene
(glVertex3i 0 2 0)
(glEnableVertexAttribArray 0)
(wglMakeCurrent 0 0) | (runtime-error "Example deprecated!" '())
(define SHADER_NUM 1)
/ - The Scheme Programming Language ( Fourth Edition )
(define *USE_GLBEGIN* 1)
(import (owl ffi))
(import (lib windows))
(import (OpenGL version-2-1))
(define OR (lambda list (fold bor 0 list)))
(define width 1280)
(define height 720)
(define window (CreateWindowEx
# 32770 is for system classname for DIALOG
(OR WS_OVERLAPPEDWINDOW WS_CLIPSIBLINGS WS_CLIPCHILDREN)
todo : override as ' ( INTEGER . 0 )
переключение режим -
(define pfd (list->bytevector '(#x28 00 1 00 #x25 00 00 00 00 #x10 00 00 00 00 00 00
00 00 00 00 00 00 00 #x10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00)))
(define hDC (GetDC window))
(define PixelFormat (ChoosePixelFormat hDC pfd))
(print "PixelFormat = " PixelFormat)
(print "SetPixelFormat = "
(SetPixelFormat hDC PixelFormat pfd))
(define hRC (wglCreateContext hDC))
(print "wglMakeCurrent = "
(wglMakeCurrent hDC hRC))
(print "OpenGL version: " (glGetString GL_VERSION))
(print "OpenGL vendor: " (glGetString GL_VENDOR))
(print "OpenGL renderer: " (glGetString GL_RENDERER))
todo : тип для ( dlsym ) - всегда число ,
my temporary stubs for opengl ( у меня пока ж и т.д . )
(define void fft-void)
void GLvoid
typedef unsigned int GLenum - fix+ значит , что это целое число
typedef int GLint
typedef int
(define GLubyte* type-string)
(define GLclampf fft-float)
проверка , что все запустилось .
(define (msgbox)
(if (=
(MessageBox 0 "Please, press OK for test pass!" "load-library test"
(bor MB_OKCANCEL MB_ICONASTERISK))
IDOK)
(print "OK")
(print "CANCEL")))
export ( MessageBox ) и т.д .
(define GLchar** type-vector)
(define GLint* type-vptr)
(define GLsizei* type-vptr)
(define GLchar* type-string)
(define void* type-vptr)
(define glCreateShader (glGetProcAddress GLuint "glCreateShader" GLenum))
(define GL_VERTEX_SHADER #x8B31)
(define GL_FRAGMENT_SHADER #x8B30)
(define glShaderSource (glGetProcAddress void "glShaderSource" GLuint GLsizei GLchar** GLint*))
(define glCompileShader (glGetProcAddress void "glCompileShader" GLuint))
(define glCreateProgram (glGetProcAddress GLuint "glCreateProgram"))
(define glAttachShader (glGetProcAddress void "glAttachShader" GLuint GLuint))
(define glDetachShader (glGetProcAddress void "glDetachShader" GLuint GLuint))
(define glLinkProgram (glGetProcAddress void "glLinkProgram" GLuint))
(define glUseProgram (glGetProcAddress void "glUseProgram" GLuint))
(define glGetShaderiv (glGetProcAddress void "glGetShaderiv" GLuint GLenum GLint*))
(define GL_COMPILE_STATUS #x8B81)
(define GL_LINK_STATUS #x8B82)
(define GL_VALIDATE_STATUS #x8B83)
(define GL_INFO_LOG_LENGTH #x8B84)
(define glGetShaderInfoLog (glGetProcAddress void "glGetShaderInfoLog" GLuint GLsizei GLsizei* GLchar*))
(define glGetUniformLocation (glGetProcAddress GLint "glGetUniformLocation" GLuint GLchar*))
(define glUniform1i (glGetProcAddress void "glUniform1i" GLint GLint))
(define glUniform1f (glGetProcAddress void "glUniform1f" GLint GLfloat))
(define glUniform2f (glGetProcAddress void "glUniform2f" GLint GLfloat GLfloat))
(define glEnableVertexAttribArray (glGetProcAddress void "glEnableVertexAttribArray" GLuint))
(define glVertexAttribPointer (glGetProcAddress void "glVertexAttribPointer" GLuint GLint GLenum GLboolean GLsizei void*))
(define GL_FLOAT #x1406)
(define glDrawArrays (glGetProcAddress void "glDrawArrays" GLenum GLint GLsizei))
(define (file->string path)
(bytes->string
(blob-iter
(let ((vec (file->bytevector path)))
(if vec vec
(error "Unable to load: " path))))))
пример как
а можно еще попробовать их
( fasl - load " raw / geometry.compiled.fs " " void main(void ) { gl_FragColor = vec4(1.0 , 0.0 , 0.0 , 1.0 ) ; } " )
(define po (glCreateProgram))
(print "po: " po)
(define vs (glCreateShader GL_VERTEX_SHADER))
(print "vs: " vs)
пример , как можно на строки :
(glShaderSource vs 2 ["#version 120 // OpenGL 2.1\n"
"
void main() {
}"] null)
(glCompileShader vs)
(define isCompiled "word")
(glGetShaderiv vs GL_COMPILE_STATUS isCompiled)
(if (= (ref isCompiled 0) 0)
(begin
(define maxLength "word")
(glGetShaderiv vs GL_INFO_LOG_LENGTH maxLength)
(define maxLengthValue (+ (ref maxLength 0) (* (ref maxLength 1) 256)))
(define errorLog (make-string maxLengthValue 0))
(glGetShaderInfoLog vs maxLengthValue maxLength errorLog)
(print errorLog)
(print "@")
(halt 0)))
(glAttachShader po vs)
(define fs (glCreateShader GL_FRAGMENT_SHADER))
(glShaderSource fs 1 [(file->string
(case SHADER_NUM
(2 "raw/geometry.fs")
(3 "raw/water.fs")
(4 "raw/18850")
(5 "raw/minecraft.fs")
(6 "raw/moon.fs")
(0 "raw/black.fs")
(1 "raw/itsfullofstars.fs")))] null)
(glCompileShader fs)
(define isCompiled "word")
(glGetShaderiv fs GL_COMPILE_STATUS isCompiled)
(if (= (ref isCompiled 0) 0)
(begin
(define maxLength "word")
(glGetShaderiv fs GL_INFO_LOG_LENGTH maxLength)
(define maxLengthValue (+ (ref maxLength 0) (* (ref maxLength 1) 256)))
(define errorLog (make-string maxLengthValue 0))
(glGetShaderInfoLog fs maxLengthValue maxLength errorLog)
(print errorLog)
(print "@")
(halt 0)))
(glAttachShader po fs)
(glLinkProgram po)
(glDetachShader po fs)
(glDetachShader po vs)
(define time (glGetUniformLocation po "time"))
(define resolution (glGetUniformLocation po "resolution"))
(ShowWindow window SW_SHOW)
(SetForegroundWindow window)
(SetFocus window)
(glViewport 0 0 width height)
(glMatrixMode GL_PROJECTION)
(glLoadIdentity)
(glMatrixMode GL_MODELVIEW)
(glLoadIdentity)
(glShadeModel GL_SMOOTH)
(glClearColor 0 0 1 1)
( define ( list->bytevector ' (
( glVertex2i 2 0 )
00 00 # x00 # x40 0 0 # x00 # x00 0 0 0 0 00 00 # x80 # x3F
( glVertex2i 1 2 )
00 00 # x80 # x3F 0 0 # x00 # x40 0 0 0 0 00 00 # x80 # x3F
00 00 # x00 # x00 0 0 # x00 # x00 0 0 0 0 00 00 # x80 # x3F
sizeof(MSG)=28
(if (= 1 (PeekMessage MSG null 0 0 PM_REMOVE))
(begin
(TranslateMessage MSG)
(DispatchMessage MSG))
(glClear GL_COLOR_BUFFER_BIT)
(glUseProgram po)
(let* ((ss ms (clock)))
раз в час будем сбрасывать период
(if (> resolution 0)
(glUniform2f resolution width height))
(glBegin GL_TRIANGLE_STRIP)
( glVertex3i 0 0 0 )
( glVertex3i 2 0 0 )
( glVertex3i 2 2 0 )
(glVertex2f -1 -1)
(glVertex2f +1 -1)
(glVertex2f -1 +1)
(glVertex2f +1 +1)
(glEnd)
( glVertexAttribPointer 0 4 0 0 vertexPositions )
( glDrawArrays GL_TRIANGLES 0 3 )
(glUseProgram 0)
(SwapBuffers hDC)))
(if (= (GetAsyncKeyState 27) 0) (cycle)))
KillGLWindow
(wglDeleteContext hRC)
(ReleaseDC window hDC)
(DestroyWindow window)
|
a3b2188a3e912ad8b9300418beabb8d95d276ba2c58c378c0cea7c71b1dc2c21 | ocaml-multicore/eventlog-tools | test_parser.ml | module E = Eventlog
module R = Rresult.R
open R.Infix
let load_file path =
let open Rresult.R.Infix in
Fpath.of_string path
>>= Bos.OS.File.read
>>= fun content ->
Ok (Bigstringaf.of_string ~off:0 ~len:(String.length content) content)
let parse path expected =
load_file path >>= fun file ->
let decoder = E.Parser.decoder () in
let len = Bigstringaf.length file in
E.Parser.src decoder file 0 len true;
let rec aux count =
match E.Parser.decode decoder with
| `Await -> R.error_msg "unexpected await returned by decode"
| `End -> Ok count
| `Error msg -> Error msg
| `Ok _ -> aux (succ count)
in
aux 0 >>= fun count ->
if count != expected then
R.error_msgf
"%s: decoded event count %d doesn't match expected count: %d"
path count expected
else
Ok ()
let parse_simple () = parse "assets/simple.eventlog" 137
let parse_be () = parse "assets/be.eventlog" 137
let parse_empty () = parse "assets/empty.eventlog" 0
let add_trace () =
Ok ()
let tests = [
"parse_simple", parse_simple;
"parse_empty", parse_empty;
"parse_be", parse_be;
]
| null | https://raw.githubusercontent.com/ocaml-multicore/eventlog-tools/9ed1e4f50ad935c43d6d5a44efc7ed43e381233b/test/test_parser.ml | ocaml | module E = Eventlog
module R = Rresult.R
open R.Infix
let load_file path =
let open Rresult.R.Infix in
Fpath.of_string path
>>= Bos.OS.File.read
>>= fun content ->
Ok (Bigstringaf.of_string ~off:0 ~len:(String.length content) content)
let parse path expected =
load_file path >>= fun file ->
let decoder = E.Parser.decoder () in
let len = Bigstringaf.length file in
E.Parser.src decoder file 0 len true;
let rec aux count =
match E.Parser.decode decoder with
| `Await -> R.error_msg "unexpected await returned by decode"
| `End -> Ok count
| `Error msg -> Error msg
| `Ok _ -> aux (succ count)
in
aux 0 >>= fun count ->
if count != expected then
R.error_msgf
"%s: decoded event count %d doesn't match expected count: %d"
path count expected
else
Ok ()
let parse_simple () = parse "assets/simple.eventlog" 137
let parse_be () = parse "assets/be.eventlog" 137
let parse_empty () = parse "assets/empty.eventlog" 0
let add_trace () =
Ok ()
let tests = [
"parse_simple", parse_simple;
"parse_empty", parse_empty;
"parse_be", parse_be;
]
|
|
b06b0dd8949dfe1fe3db287602e952b0047c6b08ed2c246c2f99ed22373c3844 | con-kitty/categorifier-c | F.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
| This is similar to the @recursive - types@ example , except that the @Tree@ type
-- is monomorphic. This makes it slightly more complicated, because in the other
example , we could define the @TargetOb@ instance for @Tree@ as
--
-- @
-- type instance TargetOb (Tree a) = Tree (TargetOb a)
-- @
--
while here we have to create another data type , , and use it to define
-- @TargetOb Tree@.
--
-- Note that the following won't work:
--
-- @
-- Wo n't work because does not have CGeneric instance
type instance TargetOb Tree = TargetOb ( CG.Rep Tree ( ) )
--
-- -- Won't work because this doesn't terminate (Tree is recursive)
type instance TargetOb Tree = TargetOb ( Categorifier . Client . )
-- @
--
The generated C code is the same as the @recursive - types@ eaxmple .
module F (fCategorified) where
import qualified Categorifier.C.CExpr.Cat as C
import Categorifier.C.CExpr.Cat.TargetOb (TargetOb)
import Categorifier.C.CTypes.CGeneric (CGeneric)
import qualified Categorifier.C.CTypes.CGeneric as CG
import Categorifier.C.CTypes.GArrays (GArrays)
import Categorifier.C.KTypes.C (C)
import qualified Categorifier.Categorify as Categorify
import qualified Categorifier.Client as Client
import Data.Int (Int32, Int64)
import GHC.Generics (Generic)
data Input = Input
{ iInt32 :: C Int32,
iInt64 :: C Int64
}
deriving (Generic)
Client.deriveHasRep ''Input
instance CGeneric Input
instance GArrays C Input
type instance TargetOb Input = TargetOb (CG.Rep Input ())
data Output = Output
{ oInt64 :: C Int64,
oBool :: Bool
}
deriving (Generic)
Client.deriveHasRep ''Output
instance CGeneric Output
instance GArrays C Output
type instance TargetOb Output = TargetOb (CG.Rep Output ())
data Tree = Empty | Branch (C Int32) Tree Tree
deriving (Generic)
Client.deriveHasRep ''Tree
data TreeAux = EmptyAux | BranchAux (TargetOb Int32) TreeAux TreeAux
deriving (Generic)
Client.deriveHasRep ''TreeAux
type instance TargetOb Tree = TreeAux
f :: Input -> Output
f = h . g
g :: Input -> Tree
g inp = Branch (iInt32 inp) (Branch (fromIntegral (iInt64 inp)) Empty Empty) Empty
h :: Tree -> Output
h = \case
Empty -> Output {oInt64 = 0, oBool = False}
Branch x l r ->
Output
{ oInt64 = fromIntegral x + oInt64 (h l) + oInt64 (h r),
oBool = True
}
fCategorified :: Input `C.Cat` Output
fCategorified = Categorify.expression f
| null | https://raw.githubusercontent.com/con-kitty/categorifier-c/dd5ba3ac4d39629b99200bdffa0af54d124233f0/examples/recursive-types-2/F.hs | haskell | is monomorphic. This makes it slightly more complicated, because in the other
@
type instance TargetOb (Tree a) = Tree (TargetOb a)
@
@TargetOb Tree@.
Note that the following won't work:
@
Wo n't work because does not have CGeneric instance
-- Won't work because this doesn't terminate (Tree is recursive)
@
| # LANGUAGE DeriveGeneric #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
| This is similar to the @recursive - types@ example , except that the @Tree@ type
example , we could define the @TargetOb@ instance for @Tree@ as
while here we have to create another data type , , and use it to define
type instance TargetOb Tree = TargetOb ( CG.Rep Tree ( ) )
type instance TargetOb Tree = TargetOb ( Categorifier . Client . )
The generated C code is the same as the @recursive - types@ eaxmple .
module F (fCategorified) where
import qualified Categorifier.C.CExpr.Cat as C
import Categorifier.C.CExpr.Cat.TargetOb (TargetOb)
import Categorifier.C.CTypes.CGeneric (CGeneric)
import qualified Categorifier.C.CTypes.CGeneric as CG
import Categorifier.C.CTypes.GArrays (GArrays)
import Categorifier.C.KTypes.C (C)
import qualified Categorifier.Categorify as Categorify
import qualified Categorifier.Client as Client
import Data.Int (Int32, Int64)
import GHC.Generics (Generic)
data Input = Input
{ iInt32 :: C Int32,
iInt64 :: C Int64
}
deriving (Generic)
Client.deriveHasRep ''Input
instance CGeneric Input
instance GArrays C Input
type instance TargetOb Input = TargetOb (CG.Rep Input ())
data Output = Output
{ oInt64 :: C Int64,
oBool :: Bool
}
deriving (Generic)
Client.deriveHasRep ''Output
instance CGeneric Output
instance GArrays C Output
type instance TargetOb Output = TargetOb (CG.Rep Output ())
data Tree = Empty | Branch (C Int32) Tree Tree
deriving (Generic)
Client.deriveHasRep ''Tree
data TreeAux = EmptyAux | BranchAux (TargetOb Int32) TreeAux TreeAux
deriving (Generic)
Client.deriveHasRep ''TreeAux
type instance TargetOb Tree = TreeAux
f :: Input -> Output
f = h . g
g :: Input -> Tree
g inp = Branch (iInt32 inp) (Branch (fromIntegral (iInt64 inp)) Empty Empty) Empty
h :: Tree -> Output
h = \case
Empty -> Output {oInt64 = 0, oBool = False}
Branch x l r ->
Output
{ oInt64 = fromIntegral x + oInt64 (h l) + oInt64 (h r),
oBool = True
}
fCategorified :: Input `C.Cat` Output
fCategorified = Categorify.expression f
|
fee62bf30335703c318dbebcd52e24ca32cef05466e7a4fe1208f4bc1827227c | opencog/learn | class-merge-basic.scm | ;
; class-merge-basic.scm
Unit test for merging of Connectors - merge two classes .
;
Tests merging of two word classes , one into the other . This is
; a basic test of the simplest case.
;
Created October 2021
(use-modules (opencog) (opencog matrix))
(use-modules (opencog nlp))
(use-modules (opencog learn))
(use-modules (opencog test-runner))
(use-modules (srfi srfi-64))
(opencog-test-runner)
(load "connector-setup.scm")
(load "class-data.scm")
; ---------------------------------------------------------------
;
; This diagram explains what is being tested here:
;
( { ej } , abc ) + ( { rs } , abc ) - > ( { ej } , abc )
( { ej } , ) + none - > ( { ej } , )
none + ( { rs } , dgh ) - > ( { ej } , )
;
In this diagram , ( e , abc ) is abbreviated notation for
( Section ( Word e ) ( ConnectorList ( Connector a ) ( Connector b ) ( Connector c ) ) )
; and so on.
{ ej } is short for ( WordClassNode " e j " ) ( a set of two words )
;
What about the CrossSections ?
We expect 12 to be created , 3 each for the 4 total Sections .
For example , ( { ej } , abc ) explodes to
[ a , < { ej } , vbc > ] and [ b , < { ej } , avc > ] and [ c , < { ej } , abv > ]
; where [] denotes the CrossSection, and <> denotes the Shape. The "v"
; is the variable node in the Shape (that the germ of the cross-section
; plugs into).
;
; These should stay consistent with the merged sections. i.e. these
should reduce to 9=12 - 6 + 3 grand - total , with appropriate counts .
All 9 of them will have { ej } as the point , none will have { rs } as
; the point.
(define t-class-merge "simple two-cluster merge test")
(test-begin t-class-merge)
; Open the database
(setup-database)
; Load some data
(setup-ej-sections)
; Define matrix API to the data
(define pca (make-pseudo-cset-api))
(define gsc (add-covering-sections pca))
; Verify that the data loaded correctly
We expect 2 sections on " ej " and two on " rs "
(test-equal 2 (length (gsc 'right-stars (WordClass "e j"))))
(test-equal 2 (length (gsc 'right-stars (WordClass "r s"))))
; Get the total count on all Sections
(define totcnt (fold + 0 (map cog-count (cog-get-atoms 'Section))))
Create CrossSections and verify that they got created
(gsc 'explode-sections)
(test-equal 12 (length (cog-get-atoms 'CrossSection)))
; Verify that direct-sum object is accessing shapes correctly
i.e. the ' explode should have created some CrossSections
(test-equal 1 (length (gsc 'right-stars (Word "g"))))
(test-equal 1 (length (gsc 'right-stars (Word "h"))))
Should not be any CrossSections on e , j ; should be same as before .
(test-equal 2 (length (gsc 'right-stars (WordClass "e j"))))
(test-equal 2 (length (gsc 'right-stars (WordClass "r s"))))
(test-equal 2 (length (gsc 'right-stars (Word "a"))))
(test-equal 2 (length (gsc 'right-stars (Word "b"))))
We expect a total of 2 + 2=5 Sections
(test-equal 4 (length (cog-get-atoms 'Section)))
; --------------------------
; Merge two sections together.
(merge gsc (WordClass "e j") (WordClass "r s") 0)
We expect three sections on " e " , the abc , dgh and klm sections .
(test-equal 3 (length (gsc 'right-stars (WordClass "e j"))))
; We expect no sections remaining on rs
(test-equal 0 (length (gsc 'right-stars (WordClass "r s"))))
Of the 4 original Sections , 2 are deleted , and 1 is created ,
leaving a grand total of 3 . The new one is ( ej , ) .
The deleted ones are the two rs sections .
(test-equal 3 (length (cog-get-atoms 'Section)))
Of the 12 original CrossSections , 6 are deleted outright , three
get their counts incremented , and three get created .
(test-equal 9 (length (cog-get-atoms 'CrossSection)))
; --------------
Validate counts .
; For example:
(define epsilon 1.0e-8)
(test-approximate cnt-ej-klm
(cog-count (car (gsc 'right-stars (WordClass "e j")))) epsilon)
; To gain access to the counts, load them by name.
(expected-ej-sections)
(test-approximate (+ cnt-ej-abc cnt-rs-abc) (cog-count sec-ej-abc) epsilon)
(test-approximate cnt-rs-dgh (cog-count sec-ej-dgh) epsilon)
(test-approximate cnt-ej-klm (cog-count sec-ej-klm) epsilon)
Validate counts on select CrossSections ...
(test-approximate (+ cnt-ej-abc cnt-rs-abc) (cog-count xes-b-ej-avc) epsilon)
(test-approximate cnt-ej-klm (cog-count xes-k-ej-vlm) epsilon)
(test-approximate cnt-rs-dgh (cog-count xes-d-ej-vgh) epsilon)
; -----------------------
; Verify detailed balance
(test-assert (check-sections gsc epsilon))
(test-assert (check-crosses gsc epsilon))
(test-assert (check-shapes gsc epsilon))
; Verify no change in totals
(test-approximate totcnt (fold + 0 (map cog-count (cog-get-atoms 'Section)))
epsilon)
(test-end t-class-merge)
; ---------------------------------------------------------------
(opencog-test-end)
| null | https://raw.githubusercontent.com/opencog/learn/e00a803620491a7df4fc0d6b3dda2879a9dcb8cb/tests/merge/class-merge-basic.scm | scheme |
class-merge-basic.scm
a basic test of the simplest case.
---------------------------------------------------------------
This diagram explains what is being tested here:
and so on.
where [] denotes the CrossSection, and <> denotes the Shape. The "v"
is the variable node in the Shape (that the germ of the cross-section
plugs into).
These should stay consistent with the merged sections. i.e. these
the point.
Open the database
Load some data
Define matrix API to the data
Verify that the data loaded correctly
Get the total count on all Sections
Verify that direct-sum object is accessing shapes correctly
should be same as before .
--------------------------
Merge two sections together.
We expect no sections remaining on rs
--------------
For example:
To gain access to the counts, load them by name.
-----------------------
Verify detailed balance
Verify no change in totals
--------------------------------------------------------------- | Unit test for merging of Connectors - merge two classes .
Tests merging of two word classes , one into the other . This is
Created October 2021
(use-modules (opencog) (opencog matrix))
(use-modules (opencog nlp))
(use-modules (opencog learn))
(use-modules (opencog test-runner))
(use-modules (srfi srfi-64))
(opencog-test-runner)
(load "connector-setup.scm")
(load "class-data.scm")
( { ej } , abc ) + ( { rs } , abc ) - > ( { ej } , abc )
( { ej } , ) + none - > ( { ej } , )
none + ( { rs } , dgh ) - > ( { ej } , )
In this diagram , ( e , abc ) is abbreviated notation for
( Section ( Word e ) ( ConnectorList ( Connector a ) ( Connector b ) ( Connector c ) ) )
{ ej } is short for ( WordClassNode " e j " ) ( a set of two words )
What about the CrossSections ?
We expect 12 to be created , 3 each for the 4 total Sections .
For example , ( { ej } , abc ) explodes to
[ a , < { ej } , vbc > ] and [ b , < { ej } , avc > ] and [ c , < { ej } , abv > ]
should reduce to 9=12 - 6 + 3 grand - total , with appropriate counts .
All 9 of them will have { ej } as the point , none will have { rs } as
(define t-class-merge "simple two-cluster merge test")
(test-begin t-class-merge)
(setup-database)
(setup-ej-sections)
(define pca (make-pseudo-cset-api))
(define gsc (add-covering-sections pca))
We expect 2 sections on " ej " and two on " rs "
(test-equal 2 (length (gsc 'right-stars (WordClass "e j"))))
(test-equal 2 (length (gsc 'right-stars (WordClass "r s"))))
(define totcnt (fold + 0 (map cog-count (cog-get-atoms 'Section))))
Create CrossSections and verify that they got created
(gsc 'explode-sections)
(test-equal 12 (length (cog-get-atoms 'CrossSection)))
i.e. the ' explode should have created some CrossSections
(test-equal 1 (length (gsc 'right-stars (Word "g"))))
(test-equal 1 (length (gsc 'right-stars (Word "h"))))
(test-equal 2 (length (gsc 'right-stars (WordClass "e j"))))
(test-equal 2 (length (gsc 'right-stars (WordClass "r s"))))
(test-equal 2 (length (gsc 'right-stars (Word "a"))))
(test-equal 2 (length (gsc 'right-stars (Word "b"))))
We expect a total of 2 + 2=5 Sections
(test-equal 4 (length (cog-get-atoms 'Section)))
(merge gsc (WordClass "e j") (WordClass "r s") 0)
We expect three sections on " e " , the abc , dgh and klm sections .
(test-equal 3 (length (gsc 'right-stars (WordClass "e j"))))
(test-equal 0 (length (gsc 'right-stars (WordClass "r s"))))
Of the 4 original Sections , 2 are deleted , and 1 is created ,
leaving a grand total of 3 . The new one is ( ej , ) .
The deleted ones are the two rs sections .
(test-equal 3 (length (cog-get-atoms 'Section)))
Of the 12 original CrossSections , 6 are deleted outright , three
get their counts incremented , and three get created .
(test-equal 9 (length (cog-get-atoms 'CrossSection)))
Validate counts .
(define epsilon 1.0e-8)
(test-approximate cnt-ej-klm
(cog-count (car (gsc 'right-stars (WordClass "e j")))) epsilon)
(expected-ej-sections)
(test-approximate (+ cnt-ej-abc cnt-rs-abc) (cog-count sec-ej-abc) epsilon)
(test-approximate cnt-rs-dgh (cog-count sec-ej-dgh) epsilon)
(test-approximate cnt-ej-klm (cog-count sec-ej-klm) epsilon)
Validate counts on select CrossSections ...
(test-approximate (+ cnt-ej-abc cnt-rs-abc) (cog-count xes-b-ej-avc) epsilon)
(test-approximate cnt-ej-klm (cog-count xes-k-ej-vlm) epsilon)
(test-approximate cnt-rs-dgh (cog-count xes-d-ej-vgh) epsilon)
(test-assert (check-sections gsc epsilon))
(test-assert (check-crosses gsc epsilon))
(test-assert (check-shapes gsc epsilon))
(test-approximate totcnt (fold + 0 (map cog-count (cog-get-atoms 'Section)))
epsilon)
(test-end t-class-merge)
(opencog-test-end)
|
8996c931d73d8c09312c873fe5af566e8e5612e12f9690c173c6ee7ff17b59f4 | haskell-opengl/OpenGLRaw | GPUShader4.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.GPUShader4
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.GPUShader4 (
-- * Extension Support
glGetEXTGPUShader4,
gl_EXT_gpu_shader4,
-- * Enums
pattern GL_INT_SAMPLER_1D_ARRAY_EXT,
pattern GL_INT_SAMPLER_1D_EXT,
pattern GL_INT_SAMPLER_2D_ARRAY_EXT,
pattern GL_INT_SAMPLER_2D_EXT,
pattern GL_INT_SAMPLER_2D_RECT_EXT,
pattern GL_INT_SAMPLER_3D_EXT,
pattern GL_INT_SAMPLER_BUFFER_EXT,
pattern GL_INT_SAMPLER_CUBE_EXT,
pattern GL_MAX_PROGRAM_TEXEL_OFFSET_EXT,
pattern GL_MIN_PROGRAM_TEXEL_OFFSET_EXT,
pattern GL_SAMPLER_1D_ARRAY_EXT,
pattern GL_SAMPLER_1D_ARRAY_SHADOW_EXT,
pattern GL_SAMPLER_2D_ARRAY_EXT,
pattern GL_SAMPLER_2D_ARRAY_SHADOW_EXT,
pattern GL_SAMPLER_BUFFER_EXT,
pattern GL_SAMPLER_CUBE_SHADOW_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_1D_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_2D_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_3D_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_CUBE_EXT,
pattern GL_UNSIGNED_INT_VEC2_EXT,
pattern GL_UNSIGNED_INT_VEC3_EXT,
pattern GL_UNSIGNED_INT_VEC4_EXT,
pattern GL_VERTEX_ATTRIB_ARRAY_INTEGER_EXT,
-- * Functions
glBindFragDataLocationEXT,
glGetFragDataLocationEXT,
glGetUniformuivEXT,
glUniform1uiEXT,
glUniform1uivEXT,
glUniform2uiEXT,
glUniform2uivEXT,
glUniform3uiEXT,
glUniform3uivEXT,
glUniform4uiEXT,
glUniform4uivEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/EXT/GPUShader4.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.EXT.GPUShader4
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums
* Functions | # LANGUAGE PatternSynonyms #
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.EXT.GPUShader4 (
glGetEXTGPUShader4,
gl_EXT_gpu_shader4,
pattern GL_INT_SAMPLER_1D_ARRAY_EXT,
pattern GL_INT_SAMPLER_1D_EXT,
pattern GL_INT_SAMPLER_2D_ARRAY_EXT,
pattern GL_INT_SAMPLER_2D_EXT,
pattern GL_INT_SAMPLER_2D_RECT_EXT,
pattern GL_INT_SAMPLER_3D_EXT,
pattern GL_INT_SAMPLER_BUFFER_EXT,
pattern GL_INT_SAMPLER_CUBE_EXT,
pattern GL_MAX_PROGRAM_TEXEL_OFFSET_EXT,
pattern GL_MIN_PROGRAM_TEXEL_OFFSET_EXT,
pattern GL_SAMPLER_1D_ARRAY_EXT,
pattern GL_SAMPLER_1D_ARRAY_SHADOW_EXT,
pattern GL_SAMPLER_2D_ARRAY_EXT,
pattern GL_SAMPLER_2D_ARRAY_SHADOW_EXT,
pattern GL_SAMPLER_BUFFER_EXT,
pattern GL_SAMPLER_CUBE_SHADOW_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_1D_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_2D_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_3D_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT,
pattern GL_UNSIGNED_INT_SAMPLER_CUBE_EXT,
pattern GL_UNSIGNED_INT_VEC2_EXT,
pattern GL_UNSIGNED_INT_VEC3_EXT,
pattern GL_UNSIGNED_INT_VEC4_EXT,
pattern GL_VERTEX_ATTRIB_ARRAY_INTEGER_EXT,
glBindFragDataLocationEXT,
glGetFragDataLocationEXT,
glGetUniformuivEXT,
glUniform1uiEXT,
glUniform1uivEXT,
glUniform2uiEXT,
glUniform2uivEXT,
glUniform3uiEXT,
glUniform3uivEXT,
glUniform4uiEXT,
glUniform4uivEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
5e7ab06da5f4ed5ad7a9aa81014df560770782ddfb1fa687805d41370626a7a1 | originrose/think.image | histogram.clj | (ns think.image.histogram
(:require [think.image.pixel :refer :all]
[think.image.quantize :as quantize]
[mikera.image.core :as image]
[clojure.core.matrix :as mat])
(:import [java.awt.image BufferedImage]))
(defn sparse-histogram-from-pixels
"Create a sparse histogram map of color->pixel-count from integer pixel data"
[^ints pixels width height]
(let [n-pixels (* width height)]
[(persistent! (reduce (fn [retval idx]
(let [px (get-masked-pixel (aget pixels idx))
px-count (inc (get retval px 0))]
(assoc! retval px px-count)))
(transient {})
(range (count pixels))))
n-pixels]))
(defn sparse-histogram-64
"Create a sparse histogram of colors in an image"
[^BufferedImage img]
(let [width (.getWidth img)
height (.getHeight img)
^ints pixels (quantize/quantize-range-pixels (image/get-pixels img) 3.0)]
(sparse-histogram-from-pixels pixels width height)))
(defn sparse-histogram-64-to-dense-histogram-64
"sparse-unnormalized to dense normalized"
[sparse-histogram-retval]
(let [[histo npix] sparse-histogram-retval]
(map (fn [bin-color]
(let [px-count (get histo bin-color 0)]
[bin-color (/ px-count npix)]))
quantize/BINS)))
(defn dense-histogram-to-vector
"Create a vector of the histogram of colors"
[histo]
(mat/array (map second histo)))
| null | https://raw.githubusercontent.com/originrose/think.image/0179d104d5fa74977890942858b44e1349457514/src/clj/think/image/histogram.clj | clojure | (ns think.image.histogram
(:require [think.image.pixel :refer :all]
[think.image.quantize :as quantize]
[mikera.image.core :as image]
[clojure.core.matrix :as mat])
(:import [java.awt.image BufferedImage]))
(defn sparse-histogram-from-pixels
"Create a sparse histogram map of color->pixel-count from integer pixel data"
[^ints pixels width height]
(let [n-pixels (* width height)]
[(persistent! (reduce (fn [retval idx]
(let [px (get-masked-pixel (aget pixels idx))
px-count (inc (get retval px 0))]
(assoc! retval px px-count)))
(transient {})
(range (count pixels))))
n-pixels]))
(defn sparse-histogram-64
"Create a sparse histogram of colors in an image"
[^BufferedImage img]
(let [width (.getWidth img)
height (.getHeight img)
^ints pixels (quantize/quantize-range-pixels (image/get-pixels img) 3.0)]
(sparse-histogram-from-pixels pixels width height)))
(defn sparse-histogram-64-to-dense-histogram-64
"sparse-unnormalized to dense normalized"
[sparse-histogram-retval]
(let [[histo npix] sparse-histogram-retval]
(map (fn [bin-color]
(let [px-count (get histo bin-color 0)]
[bin-color (/ px-count npix)]))
quantize/BINS)))
(defn dense-histogram-to-vector
"Create a vector of the histogram of colors"
[histo]
(mat/array (map second histo)))
|
|
3113eb5461b973a16c548e2b6e01630c06897a9a07809d825f4b360647cdf3a1 | Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library | SourceMandateNotificationBacsDebitData.hs | {-# LANGUAGE MultiWayIf #-}
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
{-# LANGUAGE OverloadedStrings #-}
| Contains the types generated from the schema SourceMandateNotificationBacsDebitData
module StripeAPI.Types.SourceMandateNotificationBacsDebitData where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | Defines the object schema located at @components.schemas.source_mandate_notification_bacs_debit_data@ in the specification.
data SourceMandateNotificationBacsDebitData = SourceMandateNotificationBacsDebitData
{ -- | last4: Last 4 digits of the account number associated with the debit.
--
-- Constraints:
--
* Maximum length of 5000
sourceMandateNotificationBacsDebitDataLast4 :: (GHC.Maybe.Maybe Data.Text.Internal.Text)
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON SourceMandateNotificationBacsDebitData where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("last4" Data.Aeson.Types.ToJSON..=)) (sourceMandateNotificationBacsDebitDataLast4 obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("last4" Data.Aeson.Types.ToJSON..=)) (sourceMandateNotificationBacsDebitDataLast4 obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON SourceMandateNotificationBacsDebitData where
parseJSON = Data.Aeson.Types.FromJSON.withObject "SourceMandateNotificationBacsDebitData" (\obj -> GHC.Base.pure SourceMandateNotificationBacsDebitData GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "last4"))
-- | Create a new 'SourceMandateNotificationBacsDebitData' with all required fields.
mkSourceMandateNotificationBacsDebitData :: SourceMandateNotificationBacsDebitData
mkSourceMandateNotificationBacsDebitData = SourceMandateNotificationBacsDebitData {sourceMandateNotificationBacsDebitDataLast4 = GHC.Maybe.Nothing}
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/SourceMandateNotificationBacsDebitData.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| Defines the object schema located at @components.schemas.source_mandate_notification_bacs_debit_data@ in the specification.
| last4: Last 4 digits of the account number associated with the debit.
Constraints:
| Create a new 'SourceMandateNotificationBacsDebitData' with all required fields. | CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
| Contains the types generated from the schema SourceMandateNotificationBacsDebitData
module StripeAPI.Types.SourceMandateNotificationBacsDebitData where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
data SourceMandateNotificationBacsDebitData = SourceMandateNotificationBacsDebitData
* Maximum length of 5000
sourceMandateNotificationBacsDebitDataLast4 :: (GHC.Maybe.Maybe Data.Text.Internal.Text)
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON SourceMandateNotificationBacsDebitData where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("last4" Data.Aeson.Types.ToJSON..=)) (sourceMandateNotificationBacsDebitDataLast4 obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("last4" Data.Aeson.Types.ToJSON..=)) (sourceMandateNotificationBacsDebitDataLast4 obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON SourceMandateNotificationBacsDebitData where
parseJSON = Data.Aeson.Types.FromJSON.withObject "SourceMandateNotificationBacsDebitData" (\obj -> GHC.Base.pure SourceMandateNotificationBacsDebitData GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "last4"))
mkSourceMandateNotificationBacsDebitData :: SourceMandateNotificationBacsDebitData
mkSourceMandateNotificationBacsDebitData = SourceMandateNotificationBacsDebitData {sourceMandateNotificationBacsDebitDataLast4 = GHC.Maybe.Nothing}
|
c89b5f9dd3eaa63bdf803ac292af2e130146f7e44a9e0f8bbb8bcea419ea8afc | oscoin/oscoin | Arbitrary.hs | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE UndecidableInstances #
module Oscoin.Test.Crypto.Blockchain.Block.Arbitrary where
import Oscoin.Prelude
import Oscoin.Crypto.Blockchain
import Oscoin.Test.Crypto
import Oscoin.Test.Crypto.Blockchain.Block.Generators
import Oscoin.Test.Crypto.Hash.Arbitrary ()
import Oscoin.Test.Time ()
import Codec.Serialise (Serialise)
import Test.QuickCheck
instance Arbitrary s => Arbitrary (Sealed c s) where
arbitrary = genSeal
instance ( Serialise tx
, Serialise s
, Arbitrary tx
, Arbitrary s
, IsCrypto c
) => Arbitrary (Block c tx s) where
arbitrary = genStandaloneBlock
instance
forall tx c.
( IsCrypto c
, Arbitrary tx
, Serialise tx
)
=> Arbitrary (BlockData c tx)
where
arbitrary = do
h <- arbitrary
txs <- arbitrary :: Gen [tx]
pure $ mkBlockData h txs
| null | https://raw.githubusercontent.com/oscoin/oscoin/2eb5652c9999dd0f30c70b3ba6b638156c74cdb1/test/Oscoin/Test/Crypto/Blockchain/Block/Arbitrary.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE UndecidableInstances #
module Oscoin.Test.Crypto.Blockchain.Block.Arbitrary where
import Oscoin.Prelude
import Oscoin.Crypto.Blockchain
import Oscoin.Test.Crypto
import Oscoin.Test.Crypto.Blockchain.Block.Generators
import Oscoin.Test.Crypto.Hash.Arbitrary ()
import Oscoin.Test.Time ()
import Codec.Serialise (Serialise)
import Test.QuickCheck
instance Arbitrary s => Arbitrary (Sealed c s) where
arbitrary = genSeal
instance ( Serialise tx
, Serialise s
, Arbitrary tx
, Arbitrary s
, IsCrypto c
) => Arbitrary (Block c tx s) where
arbitrary = genStandaloneBlock
instance
forall tx c.
( IsCrypto c
, Arbitrary tx
, Serialise tx
)
=> Arbitrary (BlockData c tx)
where
arbitrary = do
h <- arbitrary
txs <- arbitrary :: Gen [tx]
pure $ mkBlockData h txs
|
|
1d86626f6c1151aafbe7c7ab9d934f950dc6990055fb3acdf3fcc91ffa7541c6 | Glue42/gateway-modules | restrictions.cljc | (ns gateway.restrictions
(:require [gateway.reason :refer [throw-reason]]
[instaparse.transform :as ipt]
[instaparse.core :as ip]
#?(:cljs [cljs.reader :as reader])))
(def restrictions-parser
(ip/parser "
expr=and-or
<and-or>=<ws*> (eq-neq | and | or)
<eq-neq>=<ws*> (term | eq | neq | match)
and=and-or <ws*> <'&&'> eq-neq
or=and-or <ws*> <'||'> eq-neq
eq=eq-neq <ws*> <'=='> term
neq=eq-neq <ws*> <'!='> term
match=eq-neq <ws*> <'?'> term
<term>=<ws*> (ident | own-ident | number | str | lparen and-or rparen)
<lparen> = <ws*'('ws*>
<rparen> = <ws*')'ws*>
ident=<'$'> word
own-ident=<'#'> word
str=<'\\''> #'[^\\']+' <'\\''>
word=#'[a-zA-Z]+'
number=#'[-+]?[0-9]*\\.?[0-9]+'
ws=#'[\\s\\t]+'
"))
(defn- invalid? [parsed-restriction]
(when-not (nil? parsed-restriction)
(when-let [failure (ip/get-failure parsed-restriction)]
#?(:clj (with-out-str (clojure.pprint/pprint failure))
:cljs (str failure))
)))
(defn parse
[restrictions]
(when (seq restrictions)
(let [parsed (ip/parse restrictions-parser restrictions)]
(if-let [errors (invalid? parsed)]
(throw (ex-info (str "Error parsing restrictions " errors) {:message errors}))
parsed))))
(defn check? [parsed-restriction own-context context]
(if (seq parsed-restriction)
(ipt/transform
{:and (fn [lhs rhs] (and lhs rhs))
:or (fn [lhs rhs] (or lhs rhs))
:eq =
:neq not=
:match (fn [lhs rhs] (if (and rhs lhs) (re-matches (re-pattern rhs) lhs)))
:str identity
:number #?(:clj clojure.edn/read-string
:cljs reader/read-string)
:expr identity
:own-ident (fn [[_ idn]] (or (get own-context idn) (get own-context (keyword idn))))
:ident (fn [[_ idn]] (or (get context idn) (get context (keyword idn))))
} parsed-restriction)
true))
| null | https://raw.githubusercontent.com/Glue42/gateway-modules/957c4e91548c9f47b7145a1ee0dad45b56063ed3/common/src/gateway/restrictions.cljc | clojure | (ns gateway.restrictions
(:require [gateway.reason :refer [throw-reason]]
[instaparse.transform :as ipt]
[instaparse.core :as ip]
#?(:cljs [cljs.reader :as reader])))
(def restrictions-parser
(ip/parser "
expr=and-or
<and-or>=<ws*> (eq-neq | and | or)
<eq-neq>=<ws*> (term | eq | neq | match)
and=and-or <ws*> <'&&'> eq-neq
or=and-or <ws*> <'||'> eq-neq
eq=eq-neq <ws*> <'=='> term
neq=eq-neq <ws*> <'!='> term
match=eq-neq <ws*> <'?'> term
<term>=<ws*> (ident | own-ident | number | str | lparen and-or rparen)
<lparen> = <ws*'('ws*>
<rparen> = <ws*')'ws*>
ident=<'$'> word
own-ident=<'#'> word
str=<'\\''> #'[^\\']+' <'\\''>
word=#'[a-zA-Z]+'
number=#'[-+]?[0-9]*\\.?[0-9]+'
ws=#'[\\s\\t]+'
"))
(defn- invalid? [parsed-restriction]
(when-not (nil? parsed-restriction)
(when-let [failure (ip/get-failure parsed-restriction)]
#?(:clj (with-out-str (clojure.pprint/pprint failure))
:cljs (str failure))
)))
(defn parse
[restrictions]
(when (seq restrictions)
(let [parsed (ip/parse restrictions-parser restrictions)]
(if-let [errors (invalid? parsed)]
(throw (ex-info (str "Error parsing restrictions " errors) {:message errors}))
parsed))))
(defn check? [parsed-restriction own-context context]
(if (seq parsed-restriction)
(ipt/transform
{:and (fn [lhs rhs] (and lhs rhs))
:or (fn [lhs rhs] (or lhs rhs))
:eq =
:neq not=
:match (fn [lhs rhs] (if (and rhs lhs) (re-matches (re-pattern rhs) lhs)))
:str identity
:number #?(:clj clojure.edn/read-string
:cljs reader/read-string)
:expr identity
:own-ident (fn [[_ idn]] (or (get own-context idn) (get own-context (keyword idn))))
:ident (fn [[_ idn]] (or (get context idn) (get context (keyword idn))))
} parsed-restriction)
true))
|
|
0ede19078eb3f933fd3d40d069624d4c78aaf0ea1719ed450f93de1baf5fd22c | vonli/Ext2-for-movitz | basic-macros.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2000 - 2005 ,
Department of Computer Science , University of Tromso , Norway
;;;;
;;;; Filename: basic-macros.lisp
;;;; Description:
Author : < >
;;;; Created at: Wed Nov 8 18:44:57 2000
;;;; Distribution: See the accompanying file COPYING.
;;;;
$ I d : basic - macros.lisp , v 1.70 2007/03/26 21:11:40 Exp $
;;;;
;;;;------------------------------------------------------------------
(provide :muerte/basic-macros)
First of all we must define DEFMACRO ..
(muerte::defmacro-compile-time muerte.cl:defmacro (name lambda-list &body macro-body)
(`(muerte.cl:progn
(muerte::defmacro-compile-time ,name ,lambda-list ,macro-body)
',name)))
(muerte.cl:defmacro muerte.cl:in-package (name)
`(progn
(eval-when (:compile-toplevel)
(in-package ,(movitz::movitzify-package-name name)))))
(in-package muerte)
(defmacro defmacro (name lambda-list &body macro-body)
`(progn
(defmacro-compile-time ,name ,lambda-list ,macro-body)
#+ignore
(eval-when (:compile-toplevel)
(let ((name (intern (symbol-name ',name))))
(when (eq (symbol-package name)
(find-package 'muerte.common-lisp))
;; (warn "setting ~S" name)
(setf (movitz:movitz-env-get name 'macro-expansion)
(list* 'lambda ',lambda-list
',macro-body)))))
',name))
(defmacro defun (function-name lambda-list &body body)
"Define a function."
;;; (warn "defun ~S.." function-name)
(multiple-value-bind (real-body declarations docstring)
(movitz::parse-docstring-declarations-and-body body 'cl:declare)
(let ((block-name (compute-function-block-name function-name)))
`(progn
(make-named-function ,function-name ,lambda-list
,declarations ,docstring
(block ,block-name ,@real-body))
',function-name))))
(defmacro defun-by-proto (function-name proto-name &rest parameters)
`(define-prototyped-function ,function-name ,proto-name ,@parameters))
(defmacro define-compiler-macro (name lambda-list &body body)
`(progn
(muerte::define-compiler-macro-compile-time ,name ,lambda-list ,body)
',name))
(defmacro define-primitive-function (function-name lambda-list docstring &body body)
(declare (ignore lambda-list))
(assert (stringp docstring) (docstring)
"Mandatory docstring for define-primitive-function.")
`(make-primitive-function ,function-name ,docstring
,(cons 'cl:progn body)))
(defmacro defpackage (package-name &rest options)
(let ((uses (union (if (not (assoc :use options))
(list 'muerte.cl)
(cdr (assoc :use options)))
(when (find-package package-name)
(mapcar #'package-name (package-use-list package-name))))))
(setf uses (mapcar (lambda (use)
(if (member use (cons :common-lisp (package-nicknames :common-lisp))
:test #'string=)
:muerte.cl
use))
uses))
(when (or (member :muerte.cl uses :test #'string=)
(member :muerte.common-lisp uses :test #'string=))
(push '(:shadowing-import-from :common-lisp nil) options))
(let ((movitz-options (cons (cons :use uses)
(remove :use options :key #'car))))
`(eval-when (:compile-toplevel)
(defpackage ,package-name ,@movitz-options)))))
(defmacro cond (&rest clauses)
(if (null clauses)
nil
(destructuring-bind (test-form &rest then-forms)
(car clauses)
(if (null then-forms)
(let ((cond-test-var (gensym "cond-test-var-")))
`(let ((,cond-test-var ,test-form))
(if ,cond-test-var
,cond-test-var
(cond ,@(rest clauses)))))
`(if ,test-form
(progn ,@then-forms)
(cond ,@(rest clauses)))))))
(define-compiler-macro cond (&body cond-body)
(cons 'compiled-cond cond-body))
(define-compiler-macro if (test-form then-form &optional else-form &environment env)
(when (and (movitz:movitz-constantp then-form env) (movitz:movitz-constantp else-form env))
(warn "if: ~S // ~S" then-form else-form))
(if else-form
`(compiled-cond (,test-form ,then-form) (t ,else-form))
`(compiled-cond (,test-form ,then-form))))
(defmacro throw (tag result-form)
(let ((tag-var (gensym "throw-tag-")))
`(let ((,tag-var ,tag))
(exact-throw (find-catch-tag ,tag-var)
,result-form
(error 'throw-error :tag ,tag-var)))))
(defmacro when (test-form &rest forms)
`(cond (,test-form ,@forms)))
(defmacro unless (test-form &rest forms)
`(cond ((not ,test-form) ,@forms)))
(defmacro declaim (&rest declaration-specifiers)
`(muerte::declaim-compile-time ,@declaration-specifiers))
(defmacro defparameter (name initial-value &optional docstring &environment env)
(declare (ignore docstring))
`(progn
(declaim (special ,name))
;; (muerte::compile-time-setq ,name ,initial-value)
(setq ,name ,initial-value)))
(define-compiler-macro defparameter (&whole form name initial-value
&optional docstring &environment env)
(declare (ignore docstring))
(if (not (movitz:movitz-constantp initial-value env))
form
(let ((mname (translate-program name :cl :muerte.cl)))
(setf (movitz::movitz-symbol-value (movitz:movitz-read mname))
(movitz:movitz-eval initial-value env))
`(declaim (special ,name)))))
(defmacro defvar (name &optional (value nil valuep) documentation)
(if (not valuep)
`(declaim (special ,name))
`(defparameter ,name ,value ,documentation)))
(defmacro define-compile-time-variable (name value)
(let ((the-value (eval value)))
`(progn
(eval-when (:compile-toplevel)
(define-symbol-macro ,name
(getf (movitz::image-compile-time-variables movitz::*image*)
',name))
(setf ,name (or ,name ',the-value)))
(eval-when (:load-toplevel :excute)
(defvar ,name 'uninitialized-compile-time-variable)))))
(defmacro let* (var-list &body declarations-and-body)
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
(labels ((expand (rest-vars body)
(if (null rest-vars)
body
`((let (,(car rest-vars))
(declare ,@declarations)
,@(expand (cdr rest-vars) body))))))
(if (endp var-list)
`(let () ,@body)
(car (expand var-list body))))))
(defmacro or (&rest forms)
(cond
((null forms) nil)
((null (cdr forms))
(first forms))
(t (cons 'cond (maplist (lambda (x)
(if (rest x)
(list (car x))
(list t (car x))))
forms)))))
(defmacro and (&rest forms)
(cond
((null forms) t)
((null (cdr forms))
(first forms))
(t `(when ,(first forms) (and ,@(rest forms))))))
(define-compiler-macro and (&rest forms)
(case (length forms)
(0 t)
(1 (first forms))
(2 `(compiled-cond (,(first forms) ,(second forms))))
(t `(compiled-cond ((and ,@(butlast forms))
,@(last forms))))))
(defmacro psetq (&rest pairs)
(assert (evenp (length pairs)) (pairs)
"Uneven arguments to PSETQ: ~S." pairs)
(case (length pairs)
(0 nil)
(2 `(setq ,(first pairs) ,(second pairs)))
(t (multiple-value-bind (setq-specs let-specs)
(loop for (var form) on pairs by #'cddr
as temp-var = (gensym)
collect (list temp-var form) into let-specs
collect var into setq-specs
collect temp-var into setq-specs
finally (return (values setq-specs let-specs)))
`(let ,(butlast let-specs)
(setq ,@(last pairs 2) ,@(butlast setq-specs 2)))))))
(defmacro return (&optional (result-form nil result-form-p))
(if result-form-p
`(return-from nil ,result-form)
`(return-from nil)))
(define-compiler-macro do (var-specs (end-test-form &rest result-forms) &body declarations-and-body)
(flet ((var-spec-let-spec (var-spec)
(cond
((symbolp var-spec)
var-spec)
((cddr var-spec)
(subseq var-spec 0 2))
(t var-spec)))
(var-spec-var (var-spec)
(if (symbolp var-spec) var-spec (car var-spec)))
(var-spec-step-form (var-spec)
(and (listp var-spec)
(= 3 (list-length var-spec))
(or (third var-spec)
'(quote nil)))))
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
(let* ((loop-tag (gensym "do-loop"))
(start-tag (gensym "do-start")))
`(block nil
(let ,(mapcar #'var-spec-let-spec var-specs)
(declare ,@declarations (loop-tag ,loop-tag))
(tagbody
,(unless (and (movitz:movitz-constantp end-test-form)
(not (movitz::movitz-eval end-test-form)))
`(go ,start-tag))
,loop-tag
,@body
(psetq ,@(loop for var-spec in var-specs
as step-form = (var-spec-step-form var-spec)
when step-form
append (list (var-spec-var var-spec) step-form)))
,start-tag
(unless ,end-test-form (go ,loop-tag)))
,@result-forms))))))
(defmacro do* (var-specs (end-test-form &rest result-forms) &body declarations-and-body)
(flet ((var-spec-let-spec (var-spec)
(cond
((symbolp var-spec)
var-spec)
((cddr var-spec)
(subseq var-spec 0 2))
(t var-spec)))
(var-spec-var (var-spec)
(if (symbolp var-spec) var-spec (car var-spec)))
(var-spec-step-form (var-spec)
(and (listp var-spec)
(= 3 (list-length var-spec))
(or (third var-spec)
'(quote nil)))))
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
(let* ((loop-tag (gensym "do*-loop"))
(start-tag (gensym "do*-start")))
`(block nil
(let* ,(mapcar #'var-spec-let-spec var-specs)
(declare ,@declarations)
(tagbody
(go ,start-tag)
,loop-tag
,@body
(setq ,@(loop for var-spec in var-specs
as step-form = (var-spec-step-form var-spec)
when step-form
append (list (var-spec-var var-spec) step-form)))
,start-tag
(unless ,end-test-form (go ,loop-tag)))
,@result-forms))))))
(define-compiler-macro do* (var-specs (end-test-form &rest result-forms) &body declarations-and-body)
(flet ((var-spec-let-spec (var-spec)
(if (symbolp var-spec) var-spec (subseq var-spec 0 2)))
(var-spec-var (var-spec)
(if (symbolp var-spec) var-spec (car var-spec)))
(var-spec-step-form (var-spec)
(and (listp var-spec)
(= 3 (list-length var-spec))
(or (third var-spec)
'(quote nil)))))
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
(let* ((loop-tag (gensym "do*-loop"))
(start-tag (gensym "do*-start")))
`(block nil
(let* ,(mapcar #'var-spec-let-spec var-specs)
(declare ,@declarations (loop-tag ,loop-tag))
(tagbody
(go ,start-tag)
,loop-tag
,@body
(setq ,@(loop for var-spec in var-specs
as step-form = (var-spec-step-form var-spec)
when step-form
append (list (var-spec-var var-spec) step-form)))
,start-tag
(unless ,end-test-form (go ,loop-tag)))
,@result-forms))))))
(defmacro case (keyform &rest clauses)
(flet ((otherwise-clause-p (x)
(member (car x) '(t otherwise))))
(let ((key-var (make-symbol "case-key-var")))
`(let ((,key-var ,keyform))
(cond
,@(loop for clause-head on clauses
as clause = (first clause-head)
as keys = (first clause)
as forms = (rest clause)
do ( warn " clause : ~S , op : ~S " clause ( otherwise - clause - p clause ) )
if (and (endp (rest clause-head)) (otherwise-clause-p clause))
collect (cons t forms)
else if (otherwise-clause-p clause)
do (error "Case's otherwise clause must be the last clause.")
else if (atom keys)
collect `((eql ,key-var ',keys) ,@forms)
else collect `((or ,@(mapcar #'(lambda (c)
`(eql ,key-var ',c))
keys))
,@forms)))))))
(define-compiler-macro case (keyform &rest clauses)
(case (length clauses)
(0 keyform)
(1 (let ((clause (first clauses)))
(case (car clause)
((nil) keyform)
((t otherwise)
`(progn keyform ,@(cdr clause)))
(t (if (atom (car clause))
`(when (eql ,keyform ',(car clause))
,@(cdr clause))
`(compiled-case ,keyform ,@clauses))))))
(t `(compiled-case ,keyform ,@clauses))))
(defmacro ecase (keyform &rest clauses)
;; "Not quite implemented.."
`(case ,keyform ,@clauses (t (error "~S fell through an ecase where the legal cases were ~S"
,keyform
',(mapcar #'first clauses)))))
(define-compiler-macro asm-register (register-name)
(if (member register-name '(:eax :ebx :ecx :untagged-fixnum-ecx :edx))
`(with-inline-assembly (:returns ,register-name) ())
`(with-inline-assembly (:returns :eax)
(:movl ,register-name :eax))))
(defmacro movitz-accessor (object-form type slot-name)
(warn "movitz-accesor deprecated.")
`(with-inline-assembly (:returns :register :side-effects nil)
(:compile-form (:result-mode :eax) ,object-form)
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl (:eax ,(bt:slot-offset (find-symbol (string type) :movitz)
(find-symbol (string slot-name) :movitz)))
(:result-register))))
(defmacro setf-movitz-accessor ((object-form type slot-name) value-form)
(warn "setf-movitz-accesor deprecated.")
`(with-inline-assembly (:returns :eax :side-effects t)
(:compile-two-forms (:eax :ebx) ,value-form ,object-form)
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx ,(bt:slot-offset (find-symbol (string type) :movitz)
(find-symbol (string slot-name) :movitz))))))
(defmacro movitz-accessor-u16 (object-form type slot-name)
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) ,object-form)
(:movzxw (:eax ,(bt:slot-offset (find-symbol (string type) :movitz)
(find-symbol (string slot-name) :movitz)))
:ecx)
(:leal ((:ecx #.movitz::+movitz-fixnum-factor+) :edi ,(- (movitz::image-nil-word movitz::*image*)))
:eax)))
(defmacro set-movitz-accessor-u16 (object-form type slot-name value)
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) ,object-form ,value)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:movw :cx (:eax ,(bt:slot-offset (find-symbol (string type) :movitz)
(find-symbol (string slot-name) :movitz))))
(:leal ((:ecx #.movitz::+movitz-fixnum-factor+) :edi ,(- (movitz::image-nil-word movitz::*image*)))
:eax)))
(define-compiler-macro movitz-type-word-size (type &environment env)
(if (not (movitz:movitz-constantp type env))
(error "Non-constant movitz-type-word-size call.")
(movitz::movitz-type-word-size (intern (symbol-name (movitz:movitz-eval type env))
:movitz))))
(define-compiler-macro movitz-type-slot-offset (type slot &environment env)
(if (not (and (movitz:movitz-constantp type env)
(movitz:movitz-constantp slot env)))
(error "Non-constant movitz-type-slot-offset call.")
(bt:slot-offset (intern (symbol-name (movitz:movitz-eval type env)) :movitz)
(intern (symbol-name (movitz:movitz-eval slot env)) :movitz))))
(define-compiler-macro movitz-type-location-offset (type slot &environment env)
(if (not (and (movitz:movitz-constantp type env)
(movitz:movitz-constantp slot env)))
(error "Non-constant movitz-type-slot-offset call.")
(truncate (+ -6 (bt:slot-offset (intern (symbol-name (movitz:movitz-eval type env)) :movitz)
(intern (symbol-name (movitz:movitz-eval slot env)) :movitz)))
4)))
(define-compiler-macro not (x)
`(muerte::inlined-not ,x))
(define-compiler-macro null (x)
`(muerte::inlined-not ,x))
(define-compiler-macro eq (&whole form &environment env x y)
(cond
((movitz:movitz-constantp y env)
(let ((y (movitz:movitz-eval y env)))
(cond
((movitz:movitz-constantp x env)
(warn "constant eq!: ~S" form)
(eq y (movitz:movitz-eval x env)))
((eq y nil)
`(muerte::inlined-not ,x))
((eql y 0)
`(with-inline-assembly-case (:side-effects nil)
(do-case ((:boolean-branch-on-true :boolean-branch-on-false)
:boolean-zf=1)
(:compile-form (:result-mode :eax) ,x)
(:testl :eax :eax))
(do-case (t :boolean-cf=1)
(:compile-form (:result-mode :eax) ,x)
(:cmpl 1 :eax))))
((typep y '(or symbol (unsigned-byte 29)))
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,x)
(:load-constant ,y :eax :op :cmpl)))
(t `(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,x ,y)
(:cmpl :eax :ebx))))))
((movitz:movitz-constantp x env)
`(eq ,y ',(movitz:movitz-eval x env)))
(t `(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,x ,y)
(:cmpl :eax :ebx)))))
(define-compiler-macro eql (x y)
`(let ((x ,x) (y ,y))
(eql%b x y)))
(define-compiler-macro values (&rest sub-forms)
`(inline-values ,@sub-forms))
(defmacro multiple-value-list (form)
`(multiple-value-call #'list ,form))
(defmacro nth-value (n form)
`(nth ,n (multiple-value-list ,form)))
(define-compiler-macro nth-value (n form)
`(compiled-nth-value ,n ,form))
(defmacro prog1 (first-form &rest rest-forms)
This definition of PROG1 is not as inefficient as it looks .
The combination of VALUES and M - V - PROG1 will lead to reasonable code .
`(values (multiple-value-prog1 ,first-form ,@rest-forms)))
(defmacro prog2 (first-form second-form &rest rest-forms)
`(progn ,first-form (prog1 ,second-form ,@rest-forms)))
(defmacro prog (variable-list &body declarations-and-body)
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
`(block nil (let ,variable-list (declare ,@declarations) (tagbody ,@body)))))
(defmacro prog* (variable-list &body declarations-and-body)
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
`(block nil (let* ,variable-list (declare ,@declarations) (tagbody ,@body)))))
(defmacro multiple-value-setq (vars form)
(let ((tmp-vars (loop repeat (length vars) collect (gensym))))
`(multiple-value-bind ,tmp-vars ,form
(setq ,@(loop for v in vars and tmp in tmp-vars collect v collect tmp)))))
( defmacro declaim ( & rest declarations )
;;; (movitz::movitz-env-load-declarations declarations nil :declaim)
;;; (values))
(define-compiler-macro defconstant (name initial-value &optional documentation)
(declare (ignore documentation))
(check-type name symbol)
`(progn
(eval-when (:compile-toplevel)
(let* ((movitz-name (movitz::translate-program ',name :cl :muerte.cl))
(movitz-symbol (movitz::movitz-read movitz-name))
(movitz-value (movitz::translate-program (movitz::movitz-eval ',initial-value)
:cl :muerte.cl)))
(when (and (movitz:movitz-constantp ',name)
(not (equalp (movitz::movitz-eval ',name) movitz-value)))
(warn "Redefining constant variable ~S from ~S to ~S."
',name
(movitz::movitz-eval ',name)
movitz-value))
(proclaim `(special ,movitz-name))
(setf (movitz::movitz-symbol-value movitz-symbol) (movitz::movitz-read movitz-value)
(symbol-value movitz-name) movitz-value)))
(declaim (muerte::constant-variable ,name))))
(defmacro define-symbol-macro (symbol expansion)
(check-type symbol symbol "a symbol-macro symbol")
`(progn
(eval-when (:compile-toplevel)
(movitz::movitz-env-add-binding nil (make-instance 'movitz::symbol-macro-binding
:name ',symbol
:expander (lambda (form env)
(declare (ignore form env))
(movitz::translate-program ',expansion
:cl :muerte.cl)))))
',symbol))
(defmacro check-type (place type &optional type-string)
(if (not (stringp type-string))
`(let ((place-value ,place))
(unless (typep place-value ',type)
(check-type-failed place-value ',type ',place)))
`(let ((place-value ,place))
(unless (typep place-value ',type)
(check-type-failed place-value ',type ',place ,type-string)))))
(define-compiler-macro check-type (&whole form place type &optional type-string &environment env)
(declare (ignore type-string))
(cond
((movitz:movitz-constantp place env)
(assert (typep (movitz::eval-form place env) type))
nil)
(t (if (member type '(standard-gf-instance function pointer atom
integer fixnum positive-fixnum cons symbol character null list
string vector simple-vector vector-u8 vector-u16))
`(with-inline-assembly (:returns :nothing :labels (check-type-failed retry-check-type))
retry-check-type
(:compile-form (:result-mode (:boolean-branch-on-false . check-type-failed))
(typep ,place ',type))
(:jnever '(:sub-program (check-type-failed)
(:compile-form (:result-mode :edx) (quote ,type))
(:compile-form (:result-mode :ignore)
(setf ,place (with-inline-assembly (:returns :eax)
(:int 60))))
(:jmp 'retry-check-type))))
form))))
(defmacro assert (test-form &optional places datum-form &rest argument-forms)
(declare (ignore places))
(cond
(datum-form
`(progn
(unless ,test-form
(error ,datum-form ,@argument-forms)
nil)))
(t `(progn
(unless ,test-form
(error "The assertion ~A failed." ',test-form))
nil))))
(define-compiler-macro car (x)
`(let ((cell ,x))
(with-inline-assembly-case (:side-effects t)
(do-case (t :register)
(:cons-get :car (:lexical-binding cell) (:result-register))))))
(define-compiler-macro cdr (x)
`(let ((cell ,x))
(with-inline-assembly-case (:side-effects t)
(do-case (t :register)
(:cons-get :cdr (:lexical-binding cell) (:result-register))))))
(define-compiler-macro cadr (x)
`(car (cdr ,x)))
(define-compiler-macro cddr (x)
`(cdr (cdr ,x)))
(define-compiler-macro caddr (x)
`(car (cdr (cdr ,x))))
(define-compiler-macro cadddr (x)
`(car (cdr (cdr (cdr ,x)))))
(define-compiler-macro cdar (x)
`(cdr (car ,x)))
(define-compiler-macro rest (x) `(cdr ,x))
(define-compiler-macro first (x) `(car ,x))
(define-compiler-macro second (x) `(cadr ,x))
(define-compiler-macro third (x) `(caddr ,x))
(define-compiler-macro fourth (x) `(cadddr ,x))
(define-compiler-macro (setf car) (value cell &environment env)
(if (and (movitz:movitz-constantp value env)
(eq nil (movitz::eval-form value env)))
`(with-inline-assembly (:returns :edi)
(:compile-form (:result-mode :eax) ,cell)
(:leal (:eax -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program () (:int 61)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :edi (:eax -1)))
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) ,value ,cell)
(:leal (:ebx -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program ()
(:movl :ebx :eax)
(:xorl :ecx :ecx)
(:int 69)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx -1)))))
(define-compiler-macro (setf cdr) (value cell &environment env)
(if (and (movitz:movitz-constantp value env)
(eq nil (movitz::eval-form value env)))
`(with-inline-assembly (:returns :edi)
(:compile-form (:result-mode :eax) ,cell)
(:leal (:eax -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program () (:int 61)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :edi (:eax 3)))
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) ,value ,cell)
(:leal (:ebx -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program ()
(:movl :ebx :eax)
(:xorl :ecx :ecx)
(:int 69)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx 3)))))
(define-compiler-macro rplaca (cons object)
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) ,cons ,object)
(:leal (:eax -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program ()
(:xorl :ecx :ecx)
(:int 69)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :ebx (:eax -1))))
(define-compiler-macro rplacd (cons object)
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) ,cons ,object)
(:leal (:eax -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program ()
(:xorl :ecx :ecx)
(:int 69)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :ebx (:eax 3))))
(define-compiler-macro endp (x)
`(let ((cell ,x))
(with-inline-assembly-case (:side-effects nil)
(do-case (t :same)
(:endp (:lexical-binding cell) (:returns-mode))))))
(define-compiler-macro cons (car cdr)
`(compiled-cons ,car ,cdr))
(define-compiler-macro list (&whole form &rest elements &environment env)
(case (length elements)
(0 nil)
(1 `(cons ,(car elements) nil))
(t form)))
(defmacro with-unbound-protect (x &body error-continuation &environment env)
(cond
((movitz:movitz-constantp x env)
`(values ,x))
(movitz::*compiler-use-into-unbound-protocol*
(let ((unbound-continue (gensym "unbound-continue-")))
`(with-inline-assembly (:returns :register)
(:compile-form (:result-mode :register) ,x)
(:cmpl -1 (:result-register))
(:jo '(:sub-program (unbound)
(:compile-form (:result-mode :eax) (progn ,@error-continuation))
(:jmp ',unbound-continue)))
,unbound-continue)))
(t (let ((var (gensym)))
`(let ((,var ,x))
(if (not (eq ,var (load-global-constant new-unbound-value)))
,var
(progn ,@error-continuation)))))))
(define-compiler-macro current-run-time-context ()
`(with-inline-assembly (:returns :register)
(:locally (:movl (:edi (:edi-offset self)) (:result-register)))))
#+ignore
(define-compiler-macro apply (&whole form function &rest args)
(if (and nil (consp function) (eq 'function (first function)) (symbolp (second function)))
`(apply ',(second function) ,@args) ; we prefer 'foo over #'foo.
form))
(define-compiler-macro funcall (&whole form function &rest arguments)
(or (and (listp function)
(eq 'muerte.cl:function (first function))
(let ((fname (second function)))
(or (and (symbolp fname)
`(,fname ,@arguments))
(and (listp fname)
(eq 'muerte.cl:setf (first fname))
`(,(movitz::movitz-env-setf-operator-name (movitz::translate-program (second fname)
:cl :muerte.cl))
,@arguments)))))
(case (length arguments)
(0 `(funcall%0ops ,function))
(1 `(funcall%1ops ,function ,(first arguments)))
(2 `(funcall%2ops ,function ,(first arguments) ,(second arguments)))
(3 `(funcall%3ops ,function ,(first arguments) ,(second arguments) ,(third arguments)))
(t form))))
(define-compiler-macro funcall%0ops (&whole form function)
`(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-form (:result-mode :edx) ,function)
(:leal (:edx -7) :ecx)
(:andb 7 :cl)
(:jnz 'not-symbol)
(:movl (:edx (:offset movitz-symbol function-value)) :esi)
(:jmp 'funobj-ok)
not-symbol
(:cmpb 7 :cl)
(:jne '(:sub-program (not-funobj)
(:movb 1 :cl)
(:int 69)))
(:cmpb ,(movitz:tag :funobj) (:edx ,movitz:+other-type-offset+))
(:jne 'not-funobj)
(:movl :edx :esi)
funobj-ok
(:xorl :ecx :ecx)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector))))))
(define-compiler-macro compiler-error (&rest args)
(apply 'error args))
(define-compiler-macro funcall%1ops (&whole form function argument)
`(compiler-typecase ,function
((or nil null)
(compiler-error "Can't compile funcall of NIL."))
(function
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:edx :eax) ,function ,argument)
(:movl :edx :esi)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op))))))
(symbol
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:edx :eax) ,function ,argument)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op))))))
((or symbol function)
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:edx :eax) ,function ,argument)
(:leal (:edx -5) :ecx)
(:andl 5 :ecx)
(:movl :edx :esi)
(:jnz 'funobj-ok) ; not a symbol, so it must be a funobj.
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
funobj-ok
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op))))))
(t (with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:edx :eax) ,function ,argument)
(:leal (:edx -7) :ecx)
(:testb 7 :cl)
(:jnz 'not-symbol)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
(:jmp 'funobj-ok)
not-symbol
(:leal (:edx -6) :ecx)
(:testb 7 :cl)
(:jne '(:sub-program (not-funobj)
(:movb 1 :cl)
(:int 69)))
(:cmpb ,(movitz::tag :funobj) (:edx ,movitz:+other-type-offset+))
(:jne 'not-funobj)
(:movl :edx :esi)
funobj-ok
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op))))))))
(define-compiler-macro funcall%2ops (function arg0 arg1)
(let ((function-var (gensym)))
`(let ((,function-var ,function))
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:eax :ebx) ,arg0 ,arg1)
(:compile-form (:result-mode :edx) ,function-var)
(:leal (:edx -7) :ecx)
(:andb 7 :cl)
(:jnz 'not-symbol)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
(:jmp 'funobj-ok)
not-symbol
(:cmpb 7 :cl)
(:jnz '(:sub-program (not-funobj)
(:movb 1 :cl)
(:int 69)))
(:cmpb ,(movitz::tag :funobj) (:edx ,movitz:+other-type-offset+))
(:jne 'not-funobj)
(:movl :edx :esi)
funobj-ok
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%2op))))))))
(define-compiler-macro funcall%3ops (function arg0 arg1 arg2)
(let ((function-var (gensym)))
`(let ((,function-var ,function))
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-arglist () ,arg0 ,arg1 ,arg2)
(:compile-form (:result-mode :edx) ,function-var)
(:leal (:edx -7) :ecx)
(:andb 7 :cl)
(:jnz 'not-symbol)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
(:jmp 'funobj-ok)
not-symbol
(:cmpb 7 :cl)
(:jnz '(:sub-program (not-funobj)
(:movb 1 :cl)
(:int 69)))
(:cmpb ,(movitz::tag :funobj) (:edx ,movitz:+other-type-offset+))
(:jne 'not-funobj)
(:movl :edx :esi)
funobj-ok
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%3op)))
(:leal (:esp 4) :esp))))))
(define-compiler-macro funcall%unsafe%1ops (function arg0)
`(with-inline-assembly (:returns :multiple-values)
(:compile-two-forms (:eax :esi) ,arg0 ,function)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op)))))
(define-compiler-macro funcall%unsafe%2ops (function arg0 arg1)
`(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :push) ,function)
(:compile-two-forms (:eax :ebx) ,arg0 ,arg1)
(:popl :esi)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%2op)))))
(define-compiler-macro funcall%unsafe%3ops (function arg0 arg1 arg2)
`(let ((fn ,function))
(with-inline-assembly (:returns :multiple-values)
(:compile-arglist () ,arg0 ,arg1 ,arg2)
(:compile-form (:result-mode :esi) fn)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%3op)))
(:leal (:esp 4) :esp))))
(define-compiler-macro funcall%unsafe (function &rest args)
(case (length args)
(0 `(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :esi) ,function)
(:xorl :ecx :ecx)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector)))))
(1 `(funcall%unsafe%1ops ,function ,(first args)))
(2 `(funcall%unsafe%2ops ,function ,(first args) ,(second args)))
(3 `(funcall%unsafe%3ops ,function ,(first args) ,(second args) ,(third args)))
(t `(funcall ,function ,@args))))
(defmacro with-funcallable ((name &optional (function-form name)) &body body)
(let ((function (gensym "with-function-")))
`(let ((,function (ensure-funcallable ,function-form)))
(macrolet ((,name (&rest args) `(funcall%unsafe ,',function ,@args)))
,@body))))
(defmacro lambda (&whole form)
`(function ,form))
(defmacro backquote (form)
(typecase form
(list
(if (eq 'backquote-comma (car form))
(cadr form)
(cons 'append
(loop for sub-form-head on form
as sub-form = (and (consp sub-form-head)
(car sub-form-head))
collecting
(cond
((atom sub-form-head)
(list 'quote sub-form-head))
((atom sub-form)
(list 'quote (list sub-form)))
(t (case (car sub-form)
(backquote-comma
(list 'list (cadr sub-form)))
(backquote-comma-at
(cadr sub-form))
(t (list 'list (list 'backquote sub-form))))))))))
(array
(error "Array backquote not implemented."))
(t (list 'quote form))))
(define-compiler-macro find-class (&whole form &environment env symbol &optional (errorp t) (environment nil envp))
(declare (ignore errorp environment))
(if (or envp (not (movitz:movitz-constantp symbol env)))
form
(let* ((type (movitz:movitz-eval symbol env))
(movitz-type (movitz-program type))
(cl-type (host-program type)))
(cond
((eq t cl-type)
`(load-global-constant the-class-t))
((member movitz-type (movitz::image-classes-map movitz:*image*))
`(with-inline-assembly (:returns :register)
(:globally (:movl (:edi (:edi-offset classes)) (:result-register)))
(:movl ((:result-register) ,(movitz::class-object-offset movitz-type))
(:result-register))))
(t (warn "unknown find-class: ~S [~S] [~S]" cl-type
(and (symbolp cl-type) (symbol-package cl-type))
(and (symbolp movitz-type) (symbol-package movitz-type)))
form))
#+ignore
(case cl-type
((t) `(load-global-constant the-class-t))
(fixnum '(load-global-constant the-class-fixnum))
(null `(load-global-constant the-class-null))
(symbol '(load-global-constant the-class-symbol))
(cons '(load-global-constant the-class-cons))
(t form)))))
(define-compiler-macro class-of (object)
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) ,object)
(:movl :eax :ecx)
(:andl #x7 :ecx)
(:call (:edi (:ecx 4) ,(movitz::global-constant-offset 'fast-class-of)))))
(defmacro std-instance-reader (slot instance-form)
(let ((slot (intern (symbol-name slot) :movitz)))
`(with-inline-assembly-case ()
(do-case (:ecx)
(:warn "std-instance-reader ~S for ecx!" ',slot)
(:not-implemented))
(do-case (t :register)
(:compile-form (:result-mode :register) ,instance-form)
(:leal ((:result-register) ,(- (movitz::tag :other)))
:ecx)
(:testb 7 :cl)
(:jnz '(:sub-program () (:int 66)))
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl ((:result-register) ,(bt:slot-offset 'movitz::movitz-std-instance slot))
(:result-register))))))
(defmacro std-instance-writer (slot value instance-form)
(let ((slot (intern (symbol-name slot) :movitz)))
`(with-inline-assembly-case ()
(do-case (t :eax)
(:compile-two-forms (:eax :ebx) ,value ,instance-form)
(:leal (:ebx ,(- (movitz::tag :other)))
:ecx)
(:testb 7 :cl)
(:jnz '(:sub-program () (:int 66)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx ,(bt:slot-offset 'movitz::movitz-std-instance slot)))))))
(define-compiler-macro std-instance-class (instance)
`(std-instance-reader class ,instance))
(define-compiler-macro (setf std-instance-class) (value instance)
`(std-instance-writer class ,value ,instance))
(define-compiler-macro std-instance-slots (instance)
`(std-instance-reader slots ,instance))
(define-compiler-macro (setf std-instance-slots) (value instance)
`(std-instance-writer slots ,value ,instance))
(define-compiler-macro standard-instance-access (instance location)
`(svref (std-instance-slots ,instance) ,location))
(define-compiler-macro with-stack-check (&body body)
`(let ((before (with-inline-assembly (:returns :eax)
(:movl :esp :ecx)
(:leal ((:ecx 2)) :eax))))
,@body
(let ((delta (- before (with-inline-assembly (:returns :eax)
(:movl :esp :ecx)
(:leal ((:ecx 2)) :eax)))))
(warn "stack delta: ~D" delta))))
(defmacro with-symbol-mutex ((sym &key (recursive t)) &body body)
"Not implemented."
(declare (ignore sym recursive))
`(progn ,@body))
(defmacro with-inline-assembly ((&key returns (side-effects t) (type t) labels) &body program)
`(with-inline-assembly-case (:side-effects ,side-effects :type ,type)
(do-case (t ,returns :labels ,labels)
,@program)))
(defmacro numargs-case (&rest args)
(declare (ignore args))
(error "numargs-case at illegal position."))
(defmacro movitz-backquote (expression)
(un-backquote expression 0))
(define-compiler-macro spin-wait-pause ()
"Insert a pause instruction, which improves performance of
busy-waiting loop on P4."
'(with-inline-assembly (:returns :nothing)
(:pause)))
(defmacro spin-wait-pause ())
(defmacro capture-reg8 (reg)
`(with-inline-assembly (:returns :eax)
(:movzxb ,reg :eax)
(:shll ,movitz::+movitz-fixnum-shift+ :eax)))
(defmacro asm (&rest prg)
"Insert a single assembly instruction that returns noting."
`(with-inline-assembly (:returns :nothing)
,prg))
(defmacro asm1 (&rest prg)
"Insert a single assembly instruction that returns a value in eax."
`(with-inline-assembly (:returns :eax)
,prg))
(defmacro load-global-constant (name &key thread-local)
(if thread-local
`(with-inline-assembly (:returns :register)
(:locally (:movl (:edi (:edi-offset ,name)) (:result-register))))
`(with-inline-assembly (:returns :register)
(:globally (:movl (:edi (:edi-offset ,name)) (:result-register))))))
(defmacro load-global-constant-u32 (name &key thread-local)
(if thread-local
`(with-inline-assembly (:returns :untagged-fixnum-ecx)
(:locally (:movl (:edi (:edi-offset ,name)) :ecx)))
`(with-inline-assembly (:returns :untagged-fixnum-ecx)
(:globally (:movl (:edi (:edi-offset ,name)) :ecx)))))
(define-compiler-macro halt-cpu (&optional eax-form)
(let ((infinite-loop-label (make-symbol "infinite-loop")))
`(with-inline-assembly (:returns :nothing)
,@(when eax-form
`((:compile-form (:result-mode :eax) ,eax-form)))
,infinite-loop-label
(:halt)
(:jmp ',infinite-loop-label))))
(defmacro function-name-or-nil ()
(let ((function-name-not-found-label (gensym)))
`(with-inline-assembly (:returns :eax)
(:movl :edi :eax)
Check if EDX is a symbol
(:xorb ,(movitz::tag :symbol) :dl)
(:testb 7 :dl)
(:jnz ',function-name-not-found-label)
(:xorb ,(movitz::tag :symbol) :dl)
Check if symbol 's function - value is eq to our current funobj ( in ESI ) .
(:cmpl :esi (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)))
(:jne ',function-name-not-found-label)
(:movl :edx :eax)
,function-name-not-found-label)))
(defmacro word-nibble (word-form nibble)
(check-type nibble (integer 0 7))
`(with-inline-assembly (:returns :untagged-fixnum-ecx)
(:compile-form (:result-mode :eax) ,word-form)
(:movl :eax :ecx)
(:shrl ,(* 4 nibble) :ecx)
(:andl #xf :ecx)))
(define-compiler-macro boundp (symbol)
`(with-inline-assembly-case ()
(do-case (t :boolean-zf=0 :labels (boundp-done))
(:compile-form (:result-mode :ebx) ,symbol)
(:leal (:ebx ,(- (movitz:tag :null))) :ecx)
(:testb 5 :cl)
(:jne '(:sub-program () (:int 66)))
(:call-local-pf dynamic-variable-lookup)
(:globally (:cmpl (:edi (:edi-offset new-unbound-value)) :eax)))))
(defmacro define-global-variable (name init-form &optional docstring)
"A global variable will be accessed by ignoring local bindings."
`(progn
(defparameter ,name ,init-form ,docstring)
(define-symbol-macro ,name (%symbol-global-value ',name))))
(define-compiler-macro assembly-register (register)
`(with-inline-assembly (:returns :eax)
(:movl ,register :eax)))
(defmacro with-allocation-assembly
((size-form &key object-register size-register fixed-size-p labels) &body code)
(assert (eq object-register :eax))
(assert (or fixed-size-p (eq size-register :ecx)))
(let ((size-var (gensym "malloc-size-")))
`(let ((,size-var ,size-form))
(with-inline-assembly (:returns :eax :labels (retry-alloc retry-jumper ,@labels))
(:declare-label-set retry-jumper (retry-alloc))
;; Set up atomically continuation.
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
retry-alloc
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding ,size-var) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:call-local-pf cons-pointer)
,@code
,@(when fixed-size-p
`((:load-lexical (:lexical-binding ,size-var) :ecx)))
(:call-local-pf cons-commit)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)))))
(defmacro with-non-pointer-allocation-assembly
((size-form &key object-register size-register fixed-size-p labels) &body code)
(assert (eq object-register :eax))
(assert (or fixed-size-p (eq size-register :ecx)))
(let ((size-var (gensym "malloc-size-")))
`(let ((,size-var ,size-form))
(with-inline-assembly (:returns :eax :labels (retry-alloc retry-jumper ,@labels))
(:declare-label-set retry-jumper (retry-alloc))
;; Set up atomically continuation.
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
retry-alloc
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding ,size-var) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:call-local-pf cons-non-pointer)
,@code
,@(when fixed-size-p
`((:load-lexical (:lexical-binding ,size-var) :ecx)))
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)))))
(defmacro with-non-header-allocation-assembly
((size-form &key object-register size-register fixed-size-p labels) &body code)
(assert (eq object-register :eax))
(assert (or fixed-size-p (eq size-register :ecx)))
(let ((size-var (gensym "malloc-size-")))
`(let ((,size-var ,size-form))
(with-inline-assembly (:returns :eax :labels (retry-alloc retry-jumper ,@labels))
(:declare-label-set retry-jumper (retry-alloc))
;; Set up atomically continuation.
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
retry-alloc
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding ,size-var) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:call-local-pf cons-non-header)
,@code
,@(when fixed-size-p
`((:load-lexical (:lexical-binding ,size-var) :ecx)))
(:call-local-pf cons-commit-non-header)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)))))
(define-compiler-macro cli ()
`(with-inline-assembly (:returns :nothing) (:cli)))
(define-compiler-macro sti ()
`(with-inline-assembly (:returns :nothing) (:sti)))
(defmacro check-the (type form)
(let ((x (gensym "check-the-")))
`(the ,type (let ((,x ,form)) (check-type ,x ,type) ,x))))
(require :muerte/setf)
| null | https://raw.githubusercontent.com/vonli/Ext2-for-movitz/81b6f8e165de3e1ea9cc7d2035b9259af83a6d26/losp/muerte/basic-macros.lisp | lisp | ------------------------------------------------------------------
Filename: basic-macros.lisp
Description:
Created at: Wed Nov 8 18:44:57 2000
Distribution: See the accompanying file COPYING.
------------------------------------------------------------------
(warn "setting ~S" name)
(warn "defun ~S.." function-name)
(muerte::compile-time-setq ,name ,initial-value)
"Not quite implemented.."
(movitz::movitz-env-load-declarations declarations nil :declaim)
(values))
we prefer 'foo over #'foo.
not a symbol, so it must be a funobj.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Now inside atomically section.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Now inside atomically section.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Now inside atomically section. | Copyright ( C ) 2000 - 2005 ,
Department of Computer Science , University of Tromso , Norway
Author : < >
$ I d : basic - macros.lisp , v 1.70 2007/03/26 21:11:40 Exp $
(provide :muerte/basic-macros)
First of all we must define DEFMACRO ..
(muerte::defmacro-compile-time muerte.cl:defmacro (name lambda-list &body macro-body)
(`(muerte.cl:progn
(muerte::defmacro-compile-time ,name ,lambda-list ,macro-body)
',name)))
(muerte.cl:defmacro muerte.cl:in-package (name)
`(progn
(eval-when (:compile-toplevel)
(in-package ,(movitz::movitzify-package-name name)))))
(in-package muerte)
(defmacro defmacro (name lambda-list &body macro-body)
`(progn
(defmacro-compile-time ,name ,lambda-list ,macro-body)
#+ignore
(eval-when (:compile-toplevel)
(let ((name (intern (symbol-name ',name))))
(when (eq (symbol-package name)
(find-package 'muerte.common-lisp))
(setf (movitz:movitz-env-get name 'macro-expansion)
(list* 'lambda ',lambda-list
',macro-body)))))
',name))
(defmacro defun (function-name lambda-list &body body)
"Define a function."
(multiple-value-bind (real-body declarations docstring)
(movitz::parse-docstring-declarations-and-body body 'cl:declare)
(let ((block-name (compute-function-block-name function-name)))
`(progn
(make-named-function ,function-name ,lambda-list
,declarations ,docstring
(block ,block-name ,@real-body))
',function-name))))
(defmacro defun-by-proto (function-name proto-name &rest parameters)
`(define-prototyped-function ,function-name ,proto-name ,@parameters))
(defmacro define-compiler-macro (name lambda-list &body body)
`(progn
(muerte::define-compiler-macro-compile-time ,name ,lambda-list ,body)
',name))
(defmacro define-primitive-function (function-name lambda-list docstring &body body)
(declare (ignore lambda-list))
(assert (stringp docstring) (docstring)
"Mandatory docstring for define-primitive-function.")
`(make-primitive-function ,function-name ,docstring
,(cons 'cl:progn body)))
(defmacro defpackage (package-name &rest options)
(let ((uses (union (if (not (assoc :use options))
(list 'muerte.cl)
(cdr (assoc :use options)))
(when (find-package package-name)
(mapcar #'package-name (package-use-list package-name))))))
(setf uses (mapcar (lambda (use)
(if (member use (cons :common-lisp (package-nicknames :common-lisp))
:test #'string=)
:muerte.cl
use))
uses))
(when (or (member :muerte.cl uses :test #'string=)
(member :muerte.common-lisp uses :test #'string=))
(push '(:shadowing-import-from :common-lisp nil) options))
(let ((movitz-options (cons (cons :use uses)
(remove :use options :key #'car))))
`(eval-when (:compile-toplevel)
(defpackage ,package-name ,@movitz-options)))))
(defmacro cond (&rest clauses)
(if (null clauses)
nil
(destructuring-bind (test-form &rest then-forms)
(car clauses)
(if (null then-forms)
(let ((cond-test-var (gensym "cond-test-var-")))
`(let ((,cond-test-var ,test-form))
(if ,cond-test-var
,cond-test-var
(cond ,@(rest clauses)))))
`(if ,test-form
(progn ,@then-forms)
(cond ,@(rest clauses)))))))
(define-compiler-macro cond (&body cond-body)
(cons 'compiled-cond cond-body))
(define-compiler-macro if (test-form then-form &optional else-form &environment env)
(when (and (movitz:movitz-constantp then-form env) (movitz:movitz-constantp else-form env))
(warn "if: ~S // ~S" then-form else-form))
(if else-form
`(compiled-cond (,test-form ,then-form) (t ,else-form))
`(compiled-cond (,test-form ,then-form))))
(defmacro throw (tag result-form)
(let ((tag-var (gensym "throw-tag-")))
`(let ((,tag-var ,tag))
(exact-throw (find-catch-tag ,tag-var)
,result-form
(error 'throw-error :tag ,tag-var)))))
(defmacro when (test-form &rest forms)
`(cond (,test-form ,@forms)))
(defmacro unless (test-form &rest forms)
`(cond ((not ,test-form) ,@forms)))
(defmacro declaim (&rest declaration-specifiers)
`(muerte::declaim-compile-time ,@declaration-specifiers))
(defmacro defparameter (name initial-value &optional docstring &environment env)
(declare (ignore docstring))
`(progn
(declaim (special ,name))
(setq ,name ,initial-value)))
(define-compiler-macro defparameter (&whole form name initial-value
&optional docstring &environment env)
(declare (ignore docstring))
(if (not (movitz:movitz-constantp initial-value env))
form
(let ((mname (translate-program name :cl :muerte.cl)))
(setf (movitz::movitz-symbol-value (movitz:movitz-read mname))
(movitz:movitz-eval initial-value env))
`(declaim (special ,name)))))
(defmacro defvar (name &optional (value nil valuep) documentation)
(if (not valuep)
`(declaim (special ,name))
`(defparameter ,name ,value ,documentation)))
(defmacro define-compile-time-variable (name value)
(let ((the-value (eval value)))
`(progn
(eval-when (:compile-toplevel)
(define-symbol-macro ,name
(getf (movitz::image-compile-time-variables movitz::*image*)
',name))
(setf ,name (or ,name ',the-value)))
(eval-when (:load-toplevel :excute)
(defvar ,name 'uninitialized-compile-time-variable)))))
(defmacro let* (var-list &body declarations-and-body)
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
(labels ((expand (rest-vars body)
(if (null rest-vars)
body
`((let (,(car rest-vars))
(declare ,@declarations)
,@(expand (cdr rest-vars) body))))))
(if (endp var-list)
`(let () ,@body)
(car (expand var-list body))))))
(defmacro or (&rest forms)
(cond
((null forms) nil)
((null (cdr forms))
(first forms))
(t (cons 'cond (maplist (lambda (x)
(if (rest x)
(list (car x))
(list t (car x))))
forms)))))
(defmacro and (&rest forms)
(cond
((null forms) t)
((null (cdr forms))
(first forms))
(t `(when ,(first forms) (and ,@(rest forms))))))
(define-compiler-macro and (&rest forms)
(case (length forms)
(0 t)
(1 (first forms))
(2 `(compiled-cond (,(first forms) ,(second forms))))
(t `(compiled-cond ((and ,@(butlast forms))
,@(last forms))))))
(defmacro psetq (&rest pairs)
(assert (evenp (length pairs)) (pairs)
"Uneven arguments to PSETQ: ~S." pairs)
(case (length pairs)
(0 nil)
(2 `(setq ,(first pairs) ,(second pairs)))
(t (multiple-value-bind (setq-specs let-specs)
(loop for (var form) on pairs by #'cddr
as temp-var = (gensym)
collect (list temp-var form) into let-specs
collect var into setq-specs
collect temp-var into setq-specs
finally (return (values setq-specs let-specs)))
`(let ,(butlast let-specs)
(setq ,@(last pairs 2) ,@(butlast setq-specs 2)))))))
(defmacro return (&optional (result-form nil result-form-p))
(if result-form-p
`(return-from nil ,result-form)
`(return-from nil)))
(define-compiler-macro do (var-specs (end-test-form &rest result-forms) &body declarations-and-body)
(flet ((var-spec-let-spec (var-spec)
(cond
((symbolp var-spec)
var-spec)
((cddr var-spec)
(subseq var-spec 0 2))
(t var-spec)))
(var-spec-var (var-spec)
(if (symbolp var-spec) var-spec (car var-spec)))
(var-spec-step-form (var-spec)
(and (listp var-spec)
(= 3 (list-length var-spec))
(or (third var-spec)
'(quote nil)))))
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
(let* ((loop-tag (gensym "do-loop"))
(start-tag (gensym "do-start")))
`(block nil
(let ,(mapcar #'var-spec-let-spec var-specs)
(declare ,@declarations (loop-tag ,loop-tag))
(tagbody
,(unless (and (movitz:movitz-constantp end-test-form)
(not (movitz::movitz-eval end-test-form)))
`(go ,start-tag))
,loop-tag
,@body
(psetq ,@(loop for var-spec in var-specs
as step-form = (var-spec-step-form var-spec)
when step-form
append (list (var-spec-var var-spec) step-form)))
,start-tag
(unless ,end-test-form (go ,loop-tag)))
,@result-forms))))))
(defmacro do* (var-specs (end-test-form &rest result-forms) &body declarations-and-body)
(flet ((var-spec-let-spec (var-spec)
(cond
((symbolp var-spec)
var-spec)
((cddr var-spec)
(subseq var-spec 0 2))
(t var-spec)))
(var-spec-var (var-spec)
(if (symbolp var-spec) var-spec (car var-spec)))
(var-spec-step-form (var-spec)
(and (listp var-spec)
(= 3 (list-length var-spec))
(or (third var-spec)
'(quote nil)))))
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
(let* ((loop-tag (gensym "do*-loop"))
(start-tag (gensym "do*-start")))
`(block nil
(let* ,(mapcar #'var-spec-let-spec var-specs)
(declare ,@declarations)
(tagbody
(go ,start-tag)
,loop-tag
,@body
(setq ,@(loop for var-spec in var-specs
as step-form = (var-spec-step-form var-spec)
when step-form
append (list (var-spec-var var-spec) step-form)))
,start-tag
(unless ,end-test-form (go ,loop-tag)))
,@result-forms))))))
(define-compiler-macro do* (var-specs (end-test-form &rest result-forms) &body declarations-and-body)
(flet ((var-spec-let-spec (var-spec)
(if (symbolp var-spec) var-spec (subseq var-spec 0 2)))
(var-spec-var (var-spec)
(if (symbolp var-spec) var-spec (car var-spec)))
(var-spec-step-form (var-spec)
(and (listp var-spec)
(= 3 (list-length var-spec))
(or (third var-spec)
'(quote nil)))))
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
(let* ((loop-tag (gensym "do*-loop"))
(start-tag (gensym "do*-start")))
`(block nil
(let* ,(mapcar #'var-spec-let-spec var-specs)
(declare ,@declarations (loop-tag ,loop-tag))
(tagbody
(go ,start-tag)
,loop-tag
,@body
(setq ,@(loop for var-spec in var-specs
as step-form = (var-spec-step-form var-spec)
when step-form
append (list (var-spec-var var-spec) step-form)))
,start-tag
(unless ,end-test-form (go ,loop-tag)))
,@result-forms))))))
(defmacro case (keyform &rest clauses)
(flet ((otherwise-clause-p (x)
(member (car x) '(t otherwise))))
(let ((key-var (make-symbol "case-key-var")))
`(let ((,key-var ,keyform))
(cond
,@(loop for clause-head on clauses
as clause = (first clause-head)
as keys = (first clause)
as forms = (rest clause)
do ( warn " clause : ~S , op : ~S " clause ( otherwise - clause - p clause ) )
if (and (endp (rest clause-head)) (otherwise-clause-p clause))
collect (cons t forms)
else if (otherwise-clause-p clause)
do (error "Case's otherwise clause must be the last clause.")
else if (atom keys)
collect `((eql ,key-var ',keys) ,@forms)
else collect `((or ,@(mapcar #'(lambda (c)
`(eql ,key-var ',c))
keys))
,@forms)))))))
(define-compiler-macro case (keyform &rest clauses)
(case (length clauses)
(0 keyform)
(1 (let ((clause (first clauses)))
(case (car clause)
((nil) keyform)
((t otherwise)
`(progn keyform ,@(cdr clause)))
(t (if (atom (car clause))
`(when (eql ,keyform ',(car clause))
,@(cdr clause))
`(compiled-case ,keyform ,@clauses))))))
(t `(compiled-case ,keyform ,@clauses))))
(defmacro ecase (keyform &rest clauses)
`(case ,keyform ,@clauses (t (error "~S fell through an ecase where the legal cases were ~S"
,keyform
',(mapcar #'first clauses)))))
(define-compiler-macro asm-register (register-name)
(if (member register-name '(:eax :ebx :ecx :untagged-fixnum-ecx :edx))
`(with-inline-assembly (:returns ,register-name) ())
`(with-inline-assembly (:returns :eax)
(:movl ,register-name :eax))))
(defmacro movitz-accessor (object-form type slot-name)
(warn "movitz-accesor deprecated.")
`(with-inline-assembly (:returns :register :side-effects nil)
(:compile-form (:result-mode :eax) ,object-form)
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl (:eax ,(bt:slot-offset (find-symbol (string type) :movitz)
(find-symbol (string slot-name) :movitz)))
(:result-register))))
(defmacro setf-movitz-accessor ((object-form type slot-name) value-form)
(warn "setf-movitz-accesor deprecated.")
`(with-inline-assembly (:returns :eax :side-effects t)
(:compile-two-forms (:eax :ebx) ,value-form ,object-form)
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx ,(bt:slot-offset (find-symbol (string type) :movitz)
(find-symbol (string slot-name) :movitz))))))
(defmacro movitz-accessor-u16 (object-form type slot-name)
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) ,object-form)
(:movzxw (:eax ,(bt:slot-offset (find-symbol (string type) :movitz)
(find-symbol (string slot-name) :movitz)))
:ecx)
(:leal ((:ecx #.movitz::+movitz-fixnum-factor+) :edi ,(- (movitz::image-nil-word movitz::*image*)))
:eax)))
(defmacro set-movitz-accessor-u16 (object-form type slot-name value)
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) ,object-form ,value)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:movw :cx (:eax ,(bt:slot-offset (find-symbol (string type) :movitz)
(find-symbol (string slot-name) :movitz))))
(:leal ((:ecx #.movitz::+movitz-fixnum-factor+) :edi ,(- (movitz::image-nil-word movitz::*image*)))
:eax)))
(define-compiler-macro movitz-type-word-size (type &environment env)
(if (not (movitz:movitz-constantp type env))
(error "Non-constant movitz-type-word-size call.")
(movitz::movitz-type-word-size (intern (symbol-name (movitz:movitz-eval type env))
:movitz))))
(define-compiler-macro movitz-type-slot-offset (type slot &environment env)
(if (not (and (movitz:movitz-constantp type env)
(movitz:movitz-constantp slot env)))
(error "Non-constant movitz-type-slot-offset call.")
(bt:slot-offset (intern (symbol-name (movitz:movitz-eval type env)) :movitz)
(intern (symbol-name (movitz:movitz-eval slot env)) :movitz))))
(define-compiler-macro movitz-type-location-offset (type slot &environment env)
(if (not (and (movitz:movitz-constantp type env)
(movitz:movitz-constantp slot env)))
(error "Non-constant movitz-type-slot-offset call.")
(truncate (+ -6 (bt:slot-offset (intern (symbol-name (movitz:movitz-eval type env)) :movitz)
(intern (symbol-name (movitz:movitz-eval slot env)) :movitz)))
4)))
(define-compiler-macro not (x)
`(muerte::inlined-not ,x))
(define-compiler-macro null (x)
`(muerte::inlined-not ,x))
(define-compiler-macro eq (&whole form &environment env x y)
(cond
((movitz:movitz-constantp y env)
(let ((y (movitz:movitz-eval y env)))
(cond
((movitz:movitz-constantp x env)
(warn "constant eq!: ~S" form)
(eq y (movitz:movitz-eval x env)))
((eq y nil)
`(muerte::inlined-not ,x))
((eql y 0)
`(with-inline-assembly-case (:side-effects nil)
(do-case ((:boolean-branch-on-true :boolean-branch-on-false)
:boolean-zf=1)
(:compile-form (:result-mode :eax) ,x)
(:testl :eax :eax))
(do-case (t :boolean-cf=1)
(:compile-form (:result-mode :eax) ,x)
(:cmpl 1 :eax))))
((typep y '(or symbol (unsigned-byte 29)))
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,x)
(:load-constant ,y :eax :op :cmpl)))
(t `(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,x ,y)
(:cmpl :eax :ebx))))))
((movitz:movitz-constantp x env)
`(eq ,y ',(movitz:movitz-eval x env)))
(t `(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,x ,y)
(:cmpl :eax :ebx)))))
(define-compiler-macro eql (x y)
`(let ((x ,x) (y ,y))
(eql%b x y)))
(define-compiler-macro values (&rest sub-forms)
`(inline-values ,@sub-forms))
(defmacro multiple-value-list (form)
`(multiple-value-call #'list ,form))
(defmacro nth-value (n form)
`(nth ,n (multiple-value-list ,form)))
(define-compiler-macro nth-value (n form)
`(compiled-nth-value ,n ,form))
(defmacro prog1 (first-form &rest rest-forms)
This definition of PROG1 is not as inefficient as it looks .
The combination of VALUES and M - V - PROG1 will lead to reasonable code .
`(values (multiple-value-prog1 ,first-form ,@rest-forms)))
(defmacro prog2 (first-form second-form &rest rest-forms)
`(progn ,first-form (prog1 ,second-form ,@rest-forms)))
(defmacro prog (variable-list &body declarations-and-body)
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
`(block nil (let ,variable-list (declare ,@declarations) (tagbody ,@body)))))
(defmacro prog* (variable-list &body declarations-and-body)
(multiple-value-bind (body declarations)
(movitz::parse-declarations-and-body declarations-and-body 'cl:declare)
`(block nil (let* ,variable-list (declare ,@declarations) (tagbody ,@body)))))
(defmacro multiple-value-setq (vars form)
(let ((tmp-vars (loop repeat (length vars) collect (gensym))))
`(multiple-value-bind ,tmp-vars ,form
(setq ,@(loop for v in vars and tmp in tmp-vars collect v collect tmp)))))
( defmacro declaim ( & rest declarations )
(define-compiler-macro defconstant (name initial-value &optional documentation)
(declare (ignore documentation))
(check-type name symbol)
`(progn
(eval-when (:compile-toplevel)
(let* ((movitz-name (movitz::translate-program ',name :cl :muerte.cl))
(movitz-symbol (movitz::movitz-read movitz-name))
(movitz-value (movitz::translate-program (movitz::movitz-eval ',initial-value)
:cl :muerte.cl)))
(when (and (movitz:movitz-constantp ',name)
(not (equalp (movitz::movitz-eval ',name) movitz-value)))
(warn "Redefining constant variable ~S from ~S to ~S."
',name
(movitz::movitz-eval ',name)
movitz-value))
(proclaim `(special ,movitz-name))
(setf (movitz::movitz-symbol-value movitz-symbol) (movitz::movitz-read movitz-value)
(symbol-value movitz-name) movitz-value)))
(declaim (muerte::constant-variable ,name))))
(defmacro define-symbol-macro (symbol expansion)
(check-type symbol symbol "a symbol-macro symbol")
`(progn
(eval-when (:compile-toplevel)
(movitz::movitz-env-add-binding nil (make-instance 'movitz::symbol-macro-binding
:name ',symbol
:expander (lambda (form env)
(declare (ignore form env))
(movitz::translate-program ',expansion
:cl :muerte.cl)))))
',symbol))
(defmacro check-type (place type &optional type-string)
(if (not (stringp type-string))
`(let ((place-value ,place))
(unless (typep place-value ',type)
(check-type-failed place-value ',type ',place)))
`(let ((place-value ,place))
(unless (typep place-value ',type)
(check-type-failed place-value ',type ',place ,type-string)))))
(define-compiler-macro check-type (&whole form place type &optional type-string &environment env)
(declare (ignore type-string))
(cond
((movitz:movitz-constantp place env)
(assert (typep (movitz::eval-form place env) type))
nil)
(t (if (member type '(standard-gf-instance function pointer atom
integer fixnum positive-fixnum cons symbol character null list
string vector simple-vector vector-u8 vector-u16))
`(with-inline-assembly (:returns :nothing :labels (check-type-failed retry-check-type))
retry-check-type
(:compile-form (:result-mode (:boolean-branch-on-false . check-type-failed))
(typep ,place ',type))
(:jnever '(:sub-program (check-type-failed)
(:compile-form (:result-mode :edx) (quote ,type))
(:compile-form (:result-mode :ignore)
(setf ,place (with-inline-assembly (:returns :eax)
(:int 60))))
(:jmp 'retry-check-type))))
form))))
(defmacro assert (test-form &optional places datum-form &rest argument-forms)
(declare (ignore places))
(cond
(datum-form
`(progn
(unless ,test-form
(error ,datum-form ,@argument-forms)
nil)))
(t `(progn
(unless ,test-form
(error "The assertion ~A failed." ',test-form))
nil))))
(define-compiler-macro car (x)
`(let ((cell ,x))
(with-inline-assembly-case (:side-effects t)
(do-case (t :register)
(:cons-get :car (:lexical-binding cell) (:result-register))))))
(define-compiler-macro cdr (x)
`(let ((cell ,x))
(with-inline-assembly-case (:side-effects t)
(do-case (t :register)
(:cons-get :cdr (:lexical-binding cell) (:result-register))))))
(define-compiler-macro cadr (x)
`(car (cdr ,x)))
(define-compiler-macro cddr (x)
`(cdr (cdr ,x)))
(define-compiler-macro caddr (x)
`(car (cdr (cdr ,x))))
(define-compiler-macro cadddr (x)
`(car (cdr (cdr (cdr ,x)))))
(define-compiler-macro cdar (x)
`(cdr (car ,x)))
(define-compiler-macro rest (x) `(cdr ,x))
(define-compiler-macro first (x) `(car ,x))
(define-compiler-macro second (x) `(cadr ,x))
(define-compiler-macro third (x) `(caddr ,x))
(define-compiler-macro fourth (x) `(cadddr ,x))
(define-compiler-macro (setf car) (value cell &environment env)
(if (and (movitz:movitz-constantp value env)
(eq nil (movitz::eval-form value env)))
`(with-inline-assembly (:returns :edi)
(:compile-form (:result-mode :eax) ,cell)
(:leal (:eax -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program () (:int 61)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :edi (:eax -1)))
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) ,value ,cell)
(:leal (:ebx -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program ()
(:movl :ebx :eax)
(:xorl :ecx :ecx)
(:int 69)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx -1)))))
(define-compiler-macro (setf cdr) (value cell &environment env)
(if (and (movitz:movitz-constantp value env)
(eq nil (movitz::eval-form value env)))
`(with-inline-assembly (:returns :edi)
(:compile-form (:result-mode :eax) ,cell)
(:leal (:eax -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program () (:int 61)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :edi (:eax 3)))
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) ,value ,cell)
(:leal (:ebx -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program ()
(:movl :ebx :eax)
(:xorl :ecx :ecx)
(:int 69)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx 3)))))
(define-compiler-macro rplaca (cons object)
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) ,cons ,object)
(:leal (:eax -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program ()
(:xorl :ecx :ecx)
(:int 69)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :ebx (:eax -1))))
(define-compiler-macro rplacd (cons object)
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) ,cons ,object)
(:leal (:eax -1) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program ()
(:xorl :ecx :ecx)
(:int 69)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :ebx (:eax 3))))
(define-compiler-macro endp (x)
`(let ((cell ,x))
(with-inline-assembly-case (:side-effects nil)
(do-case (t :same)
(:endp (:lexical-binding cell) (:returns-mode))))))
(define-compiler-macro cons (car cdr)
`(compiled-cons ,car ,cdr))
(define-compiler-macro list (&whole form &rest elements &environment env)
(case (length elements)
(0 nil)
(1 `(cons ,(car elements) nil))
(t form)))
(defmacro with-unbound-protect (x &body error-continuation &environment env)
(cond
((movitz:movitz-constantp x env)
`(values ,x))
(movitz::*compiler-use-into-unbound-protocol*
(let ((unbound-continue (gensym "unbound-continue-")))
`(with-inline-assembly (:returns :register)
(:compile-form (:result-mode :register) ,x)
(:cmpl -1 (:result-register))
(:jo '(:sub-program (unbound)
(:compile-form (:result-mode :eax) (progn ,@error-continuation))
(:jmp ',unbound-continue)))
,unbound-continue)))
(t (let ((var (gensym)))
`(let ((,var ,x))
(if (not (eq ,var (load-global-constant new-unbound-value)))
,var
(progn ,@error-continuation)))))))
(define-compiler-macro current-run-time-context ()
`(with-inline-assembly (:returns :register)
(:locally (:movl (:edi (:edi-offset self)) (:result-register)))))
#+ignore
(define-compiler-macro apply (&whole form function &rest args)
(if (and nil (consp function) (eq 'function (first function)) (symbolp (second function)))
form))
(define-compiler-macro funcall (&whole form function &rest arguments)
(or (and (listp function)
(eq 'muerte.cl:function (first function))
(let ((fname (second function)))
(or (and (symbolp fname)
`(,fname ,@arguments))
(and (listp fname)
(eq 'muerte.cl:setf (first fname))
`(,(movitz::movitz-env-setf-operator-name (movitz::translate-program (second fname)
:cl :muerte.cl))
,@arguments)))))
(case (length arguments)
(0 `(funcall%0ops ,function))
(1 `(funcall%1ops ,function ,(first arguments)))
(2 `(funcall%2ops ,function ,(first arguments) ,(second arguments)))
(3 `(funcall%3ops ,function ,(first arguments) ,(second arguments) ,(third arguments)))
(t form))))
(define-compiler-macro funcall%0ops (&whole form function)
`(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-form (:result-mode :edx) ,function)
(:leal (:edx -7) :ecx)
(:andb 7 :cl)
(:jnz 'not-symbol)
(:movl (:edx (:offset movitz-symbol function-value)) :esi)
(:jmp 'funobj-ok)
not-symbol
(:cmpb 7 :cl)
(:jne '(:sub-program (not-funobj)
(:movb 1 :cl)
(:int 69)))
(:cmpb ,(movitz:tag :funobj) (:edx ,movitz:+other-type-offset+))
(:jne 'not-funobj)
(:movl :edx :esi)
funobj-ok
(:xorl :ecx :ecx)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector))))))
(define-compiler-macro compiler-error (&rest args)
(apply 'error args))
(define-compiler-macro funcall%1ops (&whole form function argument)
`(compiler-typecase ,function
((or nil null)
(compiler-error "Can't compile funcall of NIL."))
(function
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:edx :eax) ,function ,argument)
(:movl :edx :esi)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op))))))
(symbol
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:edx :eax) ,function ,argument)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op))))))
((or symbol function)
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:edx :eax) ,function ,argument)
(:leal (:edx -5) :ecx)
(:andl 5 :ecx)
(:movl :edx :esi)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
funobj-ok
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op))))))
(t (with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:edx :eax) ,function ,argument)
(:leal (:edx -7) :ecx)
(:testb 7 :cl)
(:jnz 'not-symbol)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
(:jmp 'funobj-ok)
not-symbol
(:leal (:edx -6) :ecx)
(:testb 7 :cl)
(:jne '(:sub-program (not-funobj)
(:movb 1 :cl)
(:int 69)))
(:cmpb ,(movitz::tag :funobj) (:edx ,movitz:+other-type-offset+))
(:jne 'not-funobj)
(:movl :edx :esi)
funobj-ok
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op))))))))
(define-compiler-macro funcall%2ops (function arg0 arg1)
(let ((function-var (gensym)))
`(let ((,function-var ,function))
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-two-forms (:eax :ebx) ,arg0 ,arg1)
(:compile-form (:result-mode :edx) ,function-var)
(:leal (:edx -7) :ecx)
(:andb 7 :cl)
(:jnz 'not-symbol)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
(:jmp 'funobj-ok)
not-symbol
(:cmpb 7 :cl)
(:jnz '(:sub-program (not-funobj)
(:movb 1 :cl)
(:int 69)))
(:cmpb ,(movitz::tag :funobj) (:edx ,movitz:+other-type-offset+))
(:jne 'not-funobj)
(:movl :edx :esi)
funobj-ok
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%2op))))))))
(define-compiler-macro funcall%3ops (function arg0 arg1 arg2)
(let ((function-var (gensym)))
`(let ((,function-var ,function))
(with-inline-assembly-case ()
(do-case (t :multiple-values :labels (not-symbol not-funobj funobj-ok))
(:compile-arglist () ,arg0 ,arg1 ,arg2)
(:compile-form (:result-mode :edx) ,function-var)
(:leal (:edx -7) :ecx)
(:andb 7 :cl)
(:jnz 'not-symbol)
(:movl (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)) :esi)
(:jmp 'funobj-ok)
not-symbol
(:cmpb 7 :cl)
(:jnz '(:sub-program (not-funobj)
(:movb 1 :cl)
(:int 69)))
(:cmpb ,(movitz::tag :funobj) (:edx ,movitz:+other-type-offset+))
(:jne 'not-funobj)
(:movl :edx :esi)
funobj-ok
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%3op)))
(:leal (:esp 4) :esp))))))
(define-compiler-macro funcall%unsafe%1ops (function arg0)
`(with-inline-assembly (:returns :multiple-values)
(:compile-two-forms (:eax :esi) ,arg0 ,function)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%1op)))))
(define-compiler-macro funcall%unsafe%2ops (function arg0 arg1)
`(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :push) ,function)
(:compile-two-forms (:eax :ebx) ,arg0 ,arg1)
(:popl :esi)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%2op)))))
(define-compiler-macro funcall%unsafe%3ops (function arg0 arg1 arg2)
`(let ((fn ,function))
(with-inline-assembly (:returns :multiple-values)
(:compile-arglist () ,arg0 ,arg1 ,arg2)
(:compile-form (:result-mode :esi) fn)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector%3op)))
(:leal (:esp 4) :esp))))
(define-compiler-macro funcall%unsafe (function &rest args)
(case (length args)
(0 `(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :esi) ,function)
(:xorl :ecx :ecx)
(:call (:esi ,(bt:slot-offset 'movitz::movitz-funobj 'movitz::code-vector)))))
(1 `(funcall%unsafe%1ops ,function ,(first args)))
(2 `(funcall%unsafe%2ops ,function ,(first args) ,(second args)))
(3 `(funcall%unsafe%3ops ,function ,(first args) ,(second args) ,(third args)))
(t `(funcall ,function ,@args))))
(defmacro with-funcallable ((name &optional (function-form name)) &body body)
(let ((function (gensym "with-function-")))
`(let ((,function (ensure-funcallable ,function-form)))
(macrolet ((,name (&rest args) `(funcall%unsafe ,',function ,@args)))
,@body))))
(defmacro lambda (&whole form)
`(function ,form))
(defmacro backquote (form)
(typecase form
(list
(if (eq 'backquote-comma (car form))
(cadr form)
(cons 'append
(loop for sub-form-head on form
as sub-form = (and (consp sub-form-head)
(car sub-form-head))
collecting
(cond
((atom sub-form-head)
(list 'quote sub-form-head))
((atom sub-form)
(list 'quote (list sub-form)))
(t (case (car sub-form)
(backquote-comma
(list 'list (cadr sub-form)))
(backquote-comma-at
(cadr sub-form))
(t (list 'list (list 'backquote sub-form))))))))))
(array
(error "Array backquote not implemented."))
(t (list 'quote form))))
(define-compiler-macro find-class (&whole form &environment env symbol &optional (errorp t) (environment nil envp))
(declare (ignore errorp environment))
(if (or envp (not (movitz:movitz-constantp symbol env)))
form
(let* ((type (movitz:movitz-eval symbol env))
(movitz-type (movitz-program type))
(cl-type (host-program type)))
(cond
((eq t cl-type)
`(load-global-constant the-class-t))
((member movitz-type (movitz::image-classes-map movitz:*image*))
`(with-inline-assembly (:returns :register)
(:globally (:movl (:edi (:edi-offset classes)) (:result-register)))
(:movl ((:result-register) ,(movitz::class-object-offset movitz-type))
(:result-register))))
(t (warn "unknown find-class: ~S [~S] [~S]" cl-type
(and (symbolp cl-type) (symbol-package cl-type))
(and (symbolp movitz-type) (symbol-package movitz-type)))
form))
#+ignore
(case cl-type
((t) `(load-global-constant the-class-t))
(fixnum '(load-global-constant the-class-fixnum))
(null `(load-global-constant the-class-null))
(symbol '(load-global-constant the-class-symbol))
(cons '(load-global-constant the-class-cons))
(t form)))))
(define-compiler-macro class-of (object)
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) ,object)
(:movl :eax :ecx)
(:andl #x7 :ecx)
(:call (:edi (:ecx 4) ,(movitz::global-constant-offset 'fast-class-of)))))
(defmacro std-instance-reader (slot instance-form)
(let ((slot (intern (symbol-name slot) :movitz)))
`(with-inline-assembly-case ()
(do-case (:ecx)
(:warn "std-instance-reader ~S for ecx!" ',slot)
(:not-implemented))
(do-case (t :register)
(:compile-form (:result-mode :register) ,instance-form)
(:leal ((:result-register) ,(- (movitz::tag :other)))
:ecx)
(:testb 7 :cl)
(:jnz '(:sub-program () (:int 66)))
(#.movitz:*compiler-nonlocal-lispval-read-segment-prefix*
:movl ((:result-register) ,(bt:slot-offset 'movitz::movitz-std-instance slot))
(:result-register))))))
(defmacro std-instance-writer (slot value instance-form)
(let ((slot (intern (symbol-name slot) :movitz)))
`(with-inline-assembly-case ()
(do-case (t :eax)
(:compile-two-forms (:eax :ebx) ,value ,instance-form)
(:leal (:ebx ,(- (movitz::tag :other)))
:ecx)
(:testb 7 :cl)
(:jnz '(:sub-program () (:int 66)))
(#.movitz:*compiler-nonlocal-lispval-write-segment-prefix*
:movl :eax (:ebx ,(bt:slot-offset 'movitz::movitz-std-instance slot)))))))
(define-compiler-macro std-instance-class (instance)
`(std-instance-reader class ,instance))
(define-compiler-macro (setf std-instance-class) (value instance)
`(std-instance-writer class ,value ,instance))
(define-compiler-macro std-instance-slots (instance)
`(std-instance-reader slots ,instance))
(define-compiler-macro (setf std-instance-slots) (value instance)
`(std-instance-writer slots ,value ,instance))
(define-compiler-macro standard-instance-access (instance location)
`(svref (std-instance-slots ,instance) ,location))
(define-compiler-macro with-stack-check (&body body)
`(let ((before (with-inline-assembly (:returns :eax)
(:movl :esp :ecx)
(:leal ((:ecx 2)) :eax))))
,@body
(let ((delta (- before (with-inline-assembly (:returns :eax)
(:movl :esp :ecx)
(:leal ((:ecx 2)) :eax)))))
(warn "stack delta: ~D" delta))))
(defmacro with-symbol-mutex ((sym &key (recursive t)) &body body)
"Not implemented."
(declare (ignore sym recursive))
`(progn ,@body))
(defmacro with-inline-assembly ((&key returns (side-effects t) (type t) labels) &body program)
`(with-inline-assembly-case (:side-effects ,side-effects :type ,type)
(do-case (t ,returns :labels ,labels)
,@program)))
(defmacro numargs-case (&rest args)
(declare (ignore args))
(error "numargs-case at illegal position."))
(defmacro movitz-backquote (expression)
(un-backquote expression 0))
(define-compiler-macro spin-wait-pause ()
"Insert a pause instruction, which improves performance of
busy-waiting loop on P4."
'(with-inline-assembly (:returns :nothing)
(:pause)))
(defmacro spin-wait-pause ())
(defmacro capture-reg8 (reg)
`(with-inline-assembly (:returns :eax)
(:movzxb ,reg :eax)
(:shll ,movitz::+movitz-fixnum-shift+ :eax)))
(defmacro asm (&rest prg)
"Insert a single assembly instruction that returns noting."
`(with-inline-assembly (:returns :nothing)
,prg))
(defmacro asm1 (&rest prg)
"Insert a single assembly instruction that returns a value in eax."
`(with-inline-assembly (:returns :eax)
,prg))
(defmacro load-global-constant (name &key thread-local)
(if thread-local
`(with-inline-assembly (:returns :register)
(:locally (:movl (:edi (:edi-offset ,name)) (:result-register))))
`(with-inline-assembly (:returns :register)
(:globally (:movl (:edi (:edi-offset ,name)) (:result-register))))))
(defmacro load-global-constant-u32 (name &key thread-local)
(if thread-local
`(with-inline-assembly (:returns :untagged-fixnum-ecx)
(:locally (:movl (:edi (:edi-offset ,name)) :ecx)))
`(with-inline-assembly (:returns :untagged-fixnum-ecx)
(:globally (:movl (:edi (:edi-offset ,name)) :ecx)))))
(define-compiler-macro halt-cpu (&optional eax-form)
(let ((infinite-loop-label (make-symbol "infinite-loop")))
`(with-inline-assembly (:returns :nothing)
,@(when eax-form
`((:compile-form (:result-mode :eax) ,eax-form)))
,infinite-loop-label
(:halt)
(:jmp ',infinite-loop-label))))
(defmacro function-name-or-nil ()
(let ((function-name-not-found-label (gensym)))
`(with-inline-assembly (:returns :eax)
(:movl :edi :eax)
Check if EDX is a symbol
(:xorb ,(movitz::tag :symbol) :dl)
(:testb 7 :dl)
(:jnz ',function-name-not-found-label)
(:xorb ,(movitz::tag :symbol) :dl)
Check if symbol 's function - value is eq to our current funobj ( in ESI ) .
(:cmpl :esi (:edx ,(bt:slot-offset 'movitz::movitz-symbol 'movitz::function-value)))
(:jne ',function-name-not-found-label)
(:movl :edx :eax)
,function-name-not-found-label)))
(defmacro word-nibble (word-form nibble)
(check-type nibble (integer 0 7))
`(with-inline-assembly (:returns :untagged-fixnum-ecx)
(:compile-form (:result-mode :eax) ,word-form)
(:movl :eax :ecx)
(:shrl ,(* 4 nibble) :ecx)
(:andl #xf :ecx)))
(define-compiler-macro boundp (symbol)
`(with-inline-assembly-case ()
(do-case (t :boolean-zf=0 :labels (boundp-done))
(:compile-form (:result-mode :ebx) ,symbol)
(:leal (:ebx ,(- (movitz:tag :null))) :ecx)
(:testb 5 :cl)
(:jne '(:sub-program () (:int 66)))
(:call-local-pf dynamic-variable-lookup)
(:globally (:cmpl (:edi (:edi-offset new-unbound-value)) :eax)))))
(defmacro define-global-variable (name init-form &optional docstring)
"A global variable will be accessed by ignoring local bindings."
`(progn
(defparameter ,name ,init-form ,docstring)
(define-symbol-macro ,name (%symbol-global-value ',name))))
(define-compiler-macro assembly-register (register)
`(with-inline-assembly (:returns :eax)
(:movl ,register :eax)))
(defmacro with-allocation-assembly
((size-form &key object-register size-register fixed-size-p labels) &body code)
(assert (eq object-register :eax))
(assert (or fixed-size-p (eq size-register :ecx)))
(let ((size-var (gensym "malloc-size-")))
`(let ((,size-var ,size-form))
(with-inline-assembly (:returns :eax :labels (retry-alloc retry-jumper ,@labels))
(:declare-label-set retry-jumper (retry-alloc))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
retry-alloc
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding ,size-var) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:call-local-pf cons-pointer)
,@code
,@(when fixed-size-p
`((:load-lexical (:lexical-binding ,size-var) :ecx)))
(:call-local-pf cons-commit)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)))))
(defmacro with-non-pointer-allocation-assembly
((size-form &key object-register size-register fixed-size-p labels) &body code)
(assert (eq object-register :eax))
(assert (or fixed-size-p (eq size-register :ecx)))
(let ((size-var (gensym "malloc-size-")))
`(let ((,size-var ,size-form))
(with-inline-assembly (:returns :eax :labels (retry-alloc retry-jumper ,@labels))
(:declare-label-set retry-jumper (retry-alloc))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
retry-alloc
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding ,size-var) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:call-local-pf cons-non-pointer)
,@code
,@(when fixed-size-p
`((:load-lexical (:lexical-binding ,size-var) :ecx)))
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)))))
(defmacro with-non-header-allocation-assembly
((size-form &key object-register size-register fixed-size-p labels) &body code)
(assert (eq object-register :eax))
(assert (or fixed-size-p (eq size-register :ecx)))
(let ((size-var (gensym "malloc-size-")))
`(let ((,size-var ,size-form))
(with-inline-assembly (:returns :eax :labels (retry-alloc retry-jumper ,@labels))
(:declare-label-set retry-jumper (retry-alloc))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
retry-alloc
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding ,size-var) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:call-local-pf cons-non-header)
,@code
,@(when fixed-size-p
`((:load-lexical (:lexical-binding ,size-var) :ecx)))
(:call-local-pf cons-commit-non-header)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)))))
(define-compiler-macro cli ()
`(with-inline-assembly (:returns :nothing) (:cli)))
(define-compiler-macro sti ()
`(with-inline-assembly (:returns :nothing) (:sti)))
(defmacro check-the (type form)
(let ((x (gensym "check-the-")))
`(the ,type (let ((,x ,form)) (check-type ,x ,type) ,x))))
(require :muerte/setf)
|
68113b982a4c74dd1638cb983cb01318dd02a586c26ae9d1dccfd8c266a6819b | xach/zpng | rgb.lisp | (defpackage #:rgb
(:use #:cl #:zpng))
(in-package #:rgb)
(defun draw-rgb (file)
(let ((png (make-instance 'pixel-streamed-png
:color-type :truecolor-alpha
:width 200
:height 200)))
(with-open-file (stream file
:direction :output
:if-exists :supersede
:if-does-not-exist :create
:element-type '(unsigned-byte 8))
(start-png png stream)
(loop for a from 38 to 255 by 31
do (loop for b from 10 to 255 by 10
do (loop for g from 38 to 255 by 31
do (loop for r from 10 to 255 by 10
do (write-pixel (list r g b a) png)))))
(finish-png png))))
| null | https://raw.githubusercontent.com/xach/zpng/c808a48eb9ece6f04eb25a11a2eedb738fd4f0e2/doc/rgb.lisp | lisp | (defpackage #:rgb
(:use #:cl #:zpng))
(in-package #:rgb)
(defun draw-rgb (file)
(let ((png (make-instance 'pixel-streamed-png
:color-type :truecolor-alpha
:width 200
:height 200)))
(with-open-file (stream file
:direction :output
:if-exists :supersede
:if-does-not-exist :create
:element-type '(unsigned-byte 8))
(start-png png stream)
(loop for a from 38 to 255 by 31
do (loop for b from 10 to 255 by 10
do (loop for g from 38 to 255 by 31
do (loop for r from 10 to 255 by 10
do (write-pixel (list r g b a) png)))))
(finish-png png))))
|
|
2ea465bccc84bf6e1b2fde06ae06224fe99aa9665e14f79d03a1a5e04b7f45f6 | composewell/streamly | Prelude.hs | -- |
Module : Streamly . Data . Stream . Prelude
Copyright : ( c ) 2022 Composewell Technologies
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : experimental
Portability : GHC
--
This module re - exports the " Streamly . Data . Stream " module from the
-- "streamly-core" package and additionally provides concurrency, time and
-- lifted exception operations as well in a single module.
--
-- Also see the following modules for more pre-release operations:
--
* " Streamly . Internal . Data . Stream . Concurrent "
* " Streamly . Internal . Data . Stream . Time "
* " Streamly . Internal . Data . Stream . Exception . Lifted "
--
module Streamly.Data.Stream.Prelude
( module Streamly.Data.Stream
, module Streamly.Data.Stream.Concurrent
, module Streamly.Data.Stream.Time
, module Streamly.Data.Stream.Exception
)
where
import Streamly.Data.Stream
import Streamly.Data.Stream.Concurrent
import Streamly.Data.Stream.Exception
import Streamly.Data.Stream.Time
| null | https://raw.githubusercontent.com/composewell/streamly/769538d8d1dac434fe95dc3d4883c9d05f8ecdef/src/Streamly/Data/Stream/Prelude.hs | haskell | |
License : BSD-3-Clause
Maintainer :
Stability : experimental
"streamly-core" package and additionally provides concurrency, time and
lifted exception operations as well in a single module.
Also see the following modules for more pre-release operations:
| Module : Streamly . Data . Stream . Prelude
Copyright : ( c ) 2022 Composewell Technologies
Portability : GHC
This module re - exports the " Streamly . Data . Stream " module from the
* " Streamly . Internal . Data . Stream . Concurrent "
* " Streamly . Internal . Data . Stream . Time "
* " Streamly . Internal . Data . Stream . Exception . Lifted "
module Streamly.Data.Stream.Prelude
( module Streamly.Data.Stream
, module Streamly.Data.Stream.Concurrent
, module Streamly.Data.Stream.Time
, module Streamly.Data.Stream.Exception
)
where
import Streamly.Data.Stream
import Streamly.Data.Stream.Concurrent
import Streamly.Data.Stream.Exception
import Streamly.Data.Stream.Time
|
5628e837ce9ef62f5c457425bee442aa3078169c9e6716b31b3639f8d46ba856 | Jell/euroclojure-2016 | enfocus_demo.cljs | (ns euroclojure.enfocus-demo
(:require-macros [euroclojure.utils :refer [code-snippet]])
(:require [reagent.core :as reagent]
[enfocus.core :as ef]
[euroclojure.enfocus-template :refer [mount]]))
(defn slide [opts]
(reagent/create-class
{:component-did-mount
(fn [component]
(let [node (reagent/dom-node component)]
(mount node)))
:reagent-render
(fn render-enfocus-slide [_]
[:div.slide
[:div#enfocus "replace-me"]
(code-snippet "html" "resources/private/templates/enfocus.html")
(code-snippet "clojure" "src/euroclojure/enfocus_template.cljs")])}))
| null | https://raw.githubusercontent.com/Jell/euroclojure-2016/a8ca883e8480a4616ede19995aaacd4a495608af/src/euroclojure/enfocus_demo.cljs | clojure | (ns euroclojure.enfocus-demo
(:require-macros [euroclojure.utils :refer [code-snippet]])
(:require [reagent.core :as reagent]
[enfocus.core :as ef]
[euroclojure.enfocus-template :refer [mount]]))
(defn slide [opts]
(reagent/create-class
{:component-did-mount
(fn [component]
(let [node (reagent/dom-node component)]
(mount node)))
:reagent-render
(fn render-enfocus-slide [_]
[:div.slide
[:div#enfocus "replace-me"]
(code-snippet "html" "resources/private/templates/enfocus.html")
(code-snippet "clojure" "src/euroclojure/enfocus_template.cljs")])}))
|
|
d048e1a3a32094fac7cac81ee2a37ef5bcfca9737c4fe3c15140c2e1bf6a16ae | cnuernber/dtype-next | global_to_local_test.clj | (ns tech.v3.tensor.dimensions.global-to-local-test
(:require [tech.v3.tensor.dimensions :as dims]
[tech.v3.tensor.dimensions.global-to-local :as gtol]
[tech.v3.tensor.dimensions.gtol-insn :as gtol-insn]
[tech.v3.tensor.dimensions.analytics :as dims-analytics]
[tech.v3.datatype.functional :as dtype-fn]
[clojure.test :refer [deftest is]]
[clojure.pprint :as pp])
(:import [tech.v3.datatype Buffer]))
(set! *unchecked-math* true)
(defn compare-reader-impls
[base-dims expected-reduced-shape correct-addrs]
(let [reduced-dims (dims-analytics/reduce-dimensionality base-dims)
default-reader (gtol/elem-idx->addr-fn reduced-dims)
ast-reader (gtol/get-or-create-reader reduced-dims)
reduced-dims-ast (gtol-insn/signature->ast
(gtol/reduced-dims->signature reduced-dims))]
(is (= expected-reduced-shape
(->> reduced-dims
(map (fn [[k v]] [k (vec v)]))
(into {}))))
(is (dtype-fn/equals correct-addrs default-reader))
(is (dtype-fn/equals correct-addrs ast-reader)
(with-out-str (pp/pprint (:ast reduced-dims-ast))))))
(deftest strided-image-test
(compare-reader-impls (dims/dimensions [2 4 4] [32 4 1])
{:shape [2 16]
:strides [32 1]
:offsets [0 0]
:shape-ecounts [2 16]
:shape-ecount-strides [16 1]}
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 32 33 34
35 36 37 38 39 40 41 42 43 44 45 46 47]))
(deftest strided-image-reverse-rgb-test
(compare-reader-impls (dims/dimensions [2 4 [3 2 1 0]] [32 4 1])
{:shape [2 4 [3 2 1 0]]
:strides [32 4 1]
:offsets [0 0 0]
:shape-ecounts [2 4 4]
:shape-ecount-strides [16 4 1]}
[3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12 35 34
33 32 39 38 37 36 43 42 41 40 47 46 45 44]))
(deftest strided-image-reverse-rgb--most-sig-dim-test
(compare-reader-impls (dims/dimensions [[1 0] 4 4] [32 4 1])
{:shape [[1 0] 16]
:strides [32 1]
:offsets [0 0]
:shape-ecounts [2 16]
:shape-ecount-strides [16 1]}
[32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]))
;;TODO - check broadcasting on leading dimension
(deftest leading-bcast-1
(compare-reader-impls (-> (dims/dimensions [2 4 4]
[32 4 1])
(dims/broadcast [4 4 4]))
{:shape [2 16]
:strides [32 1]
:offsets [0 0]
:shape-ecounts [4 16]
:shape-ecount-strides [16 1]}
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 32 33 34
35 36 37 38 39 40 41 42 43 44 45 46 47 0 1 2 3
4 5 6 7 8 9 10 11 12 13 14 15 32 33 34 35 36 37
38 39 40 41 42 43 44 45 46 47]))
(deftest leading-bcast-2
(compare-reader-impls (-> (dims/dimensions [2 4 4]
[16 4 1])
(dims/broadcast [4 4 4]))
{:shape [32]
:strides [1]
:offsets [0]
:shape-ecounts [64]
:shape-ecount-strides [1]}
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31]))
(deftest offsets
(compare-reader-impls (-> (dims/dimensions [2 4 4] [32 4 1])
(dims/rotate [0 0 1])
(dims/broadcast [4 4 4]))
{:shape [2 4 4],
:strides [32 4 1],
:offsets [0 0 1],
:shape-ecounts [4 4 4],
:shape-ecount-strides [16 4 1]}
[1 2 3 0 5 6 7 4 9 10 11 8 13 14 15 12 33 34
35 32 37 38 39 36 41 42 43 40 45 46 47 44 1
2 3 0 5 6 7 4 9 10 11 8 13 14 15 12 33 34 35
32 37 38 39 36 41 42 43 40 45 46 47 44]))
(deftest offsets2
(compare-reader-impls (-> (dims/dimensions [(int 4) 4] [4 1])
(dims/rotate [1 1])
(dims/broadcast [4 4]))
{:shape [4 4]
:strides [4 1]
:offsets [1 1]
:shape-ecounts [4 4]
:shape-ecount-strides [4 1]}
[5 6 7 4 9 10 11 8 13 14 15 12 1 2 3 0]))
(comment
(do
(println "Dimension indexing system reader timings")
(let [base-dims (dims/dimensions [256 256 4] [8192 4 1])
reduced-dims (dims-analytics/reduce-dimensionality base-dims)
^Buffer default-reader (gtol/elem-idx->addr-fn reduced-dims)
^Buffer ast-reader (gtol/get-or-create-reader reduced-dims)
n-elems (.lsize default-reader)
read-all-fn (fn [^Buffer rdr]
(dotimes [idx n-elems]
(.readLong rdr idx)))]
(println "Default Reader:")
(crit/quick-bench (read-all-fn default-reader))
(println "AST Reader:")
(crit/quick-bench (read-all-fn ast-reader))))
(do
(println "Dimension indirect indexing system reader timings")
(let [base-dims (dims/dimensions [256 256 [3 2 1 0]] [8192 4 1])
reduced-dims (dims-analytics/reduce-dimensionality base-dims)
^Buffer default-reader (gtol/elem-idx->addr-fn reduced-dims)
^Buffer ast-reader (gtol/get-or-create-reader reduced-dims)
n-elems (.lsize default-reader)
read-all-fn (fn [^Buffer rdr]
(dotimes [idx n-elems]
(.readLong rdr idx)))]
(println "Default Reader:")
(crit/quick-bench (read-all-fn default-reader))
(println "AST Reader:")
(crit/quick-bench (read-all-fn ast-reader))))
)
| null | https://raw.githubusercontent.com/cnuernber/dtype-next/8fb3166a44a2ce21a673c864ae4d0351b6813d46/test/tech/v3/tensor/dimensions/global_to_local_test.clj | clojure | TODO - check broadcasting on leading dimension | (ns tech.v3.tensor.dimensions.global-to-local-test
(:require [tech.v3.tensor.dimensions :as dims]
[tech.v3.tensor.dimensions.global-to-local :as gtol]
[tech.v3.tensor.dimensions.gtol-insn :as gtol-insn]
[tech.v3.tensor.dimensions.analytics :as dims-analytics]
[tech.v3.datatype.functional :as dtype-fn]
[clojure.test :refer [deftest is]]
[clojure.pprint :as pp])
(:import [tech.v3.datatype Buffer]))
(set! *unchecked-math* true)
(defn compare-reader-impls
[base-dims expected-reduced-shape correct-addrs]
(let [reduced-dims (dims-analytics/reduce-dimensionality base-dims)
default-reader (gtol/elem-idx->addr-fn reduced-dims)
ast-reader (gtol/get-or-create-reader reduced-dims)
reduced-dims-ast (gtol-insn/signature->ast
(gtol/reduced-dims->signature reduced-dims))]
(is (= expected-reduced-shape
(->> reduced-dims
(map (fn [[k v]] [k (vec v)]))
(into {}))))
(is (dtype-fn/equals correct-addrs default-reader))
(is (dtype-fn/equals correct-addrs ast-reader)
(with-out-str (pp/pprint (:ast reduced-dims-ast))))))
(deftest strided-image-test
(compare-reader-impls (dims/dimensions [2 4 4] [32 4 1])
{:shape [2 16]
:strides [32 1]
:offsets [0 0]
:shape-ecounts [2 16]
:shape-ecount-strides [16 1]}
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 32 33 34
35 36 37 38 39 40 41 42 43 44 45 46 47]))
(deftest strided-image-reverse-rgb-test
(compare-reader-impls (dims/dimensions [2 4 [3 2 1 0]] [32 4 1])
{:shape [2 4 [3 2 1 0]]
:strides [32 4 1]
:offsets [0 0 0]
:shape-ecounts [2 4 4]
:shape-ecount-strides [16 4 1]}
[3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12 35 34
33 32 39 38 37 36 43 42 41 40 47 46 45 44]))
(deftest strided-image-reverse-rgb--most-sig-dim-test
(compare-reader-impls (dims/dimensions [[1 0] 4 4] [32 4 1])
{:shape [[1 0] 16]
:strides [32 1]
:offsets [0 0]
:shape-ecounts [2 16]
:shape-ecount-strides [16 1]}
[32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]))
(deftest leading-bcast-1
(compare-reader-impls (-> (dims/dimensions [2 4 4]
[32 4 1])
(dims/broadcast [4 4 4]))
{:shape [2 16]
:strides [32 1]
:offsets [0 0]
:shape-ecounts [4 16]
:shape-ecount-strides [16 1]}
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 32 33 34
35 36 37 38 39 40 41 42 43 44 45 46 47 0 1 2 3
4 5 6 7 8 9 10 11 12 13 14 15 32 33 34 35 36 37
38 39 40 41 42 43 44 45 46 47]))
(deftest leading-bcast-2
(compare-reader-impls (-> (dims/dimensions [2 4 4]
[16 4 1])
(dims/broadcast [4 4 4]))
{:shape [32]
:strides [1]
:offsets [0]
:shape-ecounts [64]
:shape-ecount-strides [1]}
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31]))
(deftest offsets
(compare-reader-impls (-> (dims/dimensions [2 4 4] [32 4 1])
(dims/rotate [0 0 1])
(dims/broadcast [4 4 4]))
{:shape [2 4 4],
:strides [32 4 1],
:offsets [0 0 1],
:shape-ecounts [4 4 4],
:shape-ecount-strides [16 4 1]}
[1 2 3 0 5 6 7 4 9 10 11 8 13 14 15 12 33 34
35 32 37 38 39 36 41 42 43 40 45 46 47 44 1
2 3 0 5 6 7 4 9 10 11 8 13 14 15 12 33 34 35
32 37 38 39 36 41 42 43 40 45 46 47 44]))
(deftest offsets2
(compare-reader-impls (-> (dims/dimensions [(int 4) 4] [4 1])
(dims/rotate [1 1])
(dims/broadcast [4 4]))
{:shape [4 4]
:strides [4 1]
:offsets [1 1]
:shape-ecounts [4 4]
:shape-ecount-strides [4 1]}
[5 6 7 4 9 10 11 8 13 14 15 12 1 2 3 0]))
(comment
(do
(println "Dimension indexing system reader timings")
(let [base-dims (dims/dimensions [256 256 4] [8192 4 1])
reduced-dims (dims-analytics/reduce-dimensionality base-dims)
^Buffer default-reader (gtol/elem-idx->addr-fn reduced-dims)
^Buffer ast-reader (gtol/get-or-create-reader reduced-dims)
n-elems (.lsize default-reader)
read-all-fn (fn [^Buffer rdr]
(dotimes [idx n-elems]
(.readLong rdr idx)))]
(println "Default Reader:")
(crit/quick-bench (read-all-fn default-reader))
(println "AST Reader:")
(crit/quick-bench (read-all-fn ast-reader))))
(do
(println "Dimension indirect indexing system reader timings")
(let [base-dims (dims/dimensions [256 256 [3 2 1 0]] [8192 4 1])
reduced-dims (dims-analytics/reduce-dimensionality base-dims)
^Buffer default-reader (gtol/elem-idx->addr-fn reduced-dims)
^Buffer ast-reader (gtol/get-or-create-reader reduced-dims)
n-elems (.lsize default-reader)
read-all-fn (fn [^Buffer rdr]
(dotimes [idx n-elems]
(.readLong rdr idx)))]
(println "Default Reader:")
(crit/quick-bench (read-all-fn default-reader))
(println "AST Reader:")
(crit/quick-bench (read-all-fn ast-reader))))
)
|
59ae7664c56c858387305f2fc7b1379cd1687dd4fd17cf4a5dfe54c2d30b36a3 | white-silence88/cse | json-file.lisp | ;; json-file
(in-package #:cse)
;; tree/build-key
;;
;;
;; Description:
;; procedure for get value for key for tree pair
;; Params:
;; key [String] name of tree node
;; type [String] type of tree
;; reserved [List<String>] list of reserved words
;; Returns
;; name of treee node
(defun tree<-get-key (key type reserved)
(cond
((member key reserved :test (lambda (k v) (string= k v))) key)
(t (if (string= type "routes")
(concatenate 'string "/" key)
key))))
;; tree/value
;;
;;
;; Description:
;; procedure for get value for current iterations.
;; If type of value is List - add list procedure and return.
If type of value is HashTable - run hash->>tree procedure with new current arguments
;; Else - return value.
;; Params:
value [ HashTable|List|Any ] value for current key
;; Returns:
(defun tree<-get-value (value type)
(cond
((typep value 'hash-table)
(hash->>tree (alexandria:hash-table-keys value) value type))
(t value)))
;; hash->>tree/iteration
;;
;;
;; Description:
;; procedure for get result iteration content convertations
;; Params:
;; key [String] name of property
content [ HashTable < String|HashTable|List < String > > ] routes HashTable
;; type [String] type of tree
;; Returns:
;; current iteration pair (key and value)
(defun hash->>tree/iteration (key content type)
(let
((value (gethash key content))
(reserved
(list
*route-config-routes-field*
*route-config-description-field*
*route-config-on-request-field*
*route-config-on-response-field*
*route-config-methods-field*
*route-config-handler-field*
*route-config-answer-field*
"title"
"message"
"description"
"data")))
(cons (tree<-get-key key type reserved) (tree<-get-value value type))))
;; hash->>tree
;;
;;
;; Description:
procedure for create list of pairs from HashTable by keys
;; Params:
;; keys [List<String>] list of hash table keys
content [ HashTable < String|HashTable|List < String > > ] routes HashTable
;; type [String] type of tree
;; Returns:
;; routes tree
(defun hash->>tree (keys content type)
(map 'list
(lambda (key)
(hash->>tree/iteration key content type))
keys))
;; file->hash->tree
;;
;;
;; Description:
;; function for create routes tree from JSON file
;; Params:
;; filepath [String] full file path
;; type [String] type of tree
;; Returns:
;; routes file tree
(defun file->hash->tree (filepath type)
(let*
((content-as-string (uiop:read-file-string filepath))
(content-as-hash (jonathan:parse content-as-string :as :hash-table))
(keys (alexandria:hash-table-keys content-as-hash)))
(hash->>tree keys content-as-hash type)))
;; file->>routes-tree
;;
;;
;; Description:
;; procedure for convert file content (.json-file) for route tree
;; Params:
;; filepath [String] full file path
;; Returns:
;; routes tree from JSON file
(defun json-file->>routes-tree (filepath)
(file->hash->tree filepath *routes-tree*))
file->>tree
;;
;;
;; Description:
;; procedure for convert file content (.json-file) for tree
;; Params:
;; filepath [String] full file path
;; Returns:
;; tree from JSON file
(defun json-file->>tree (filepath)
(file->hash->tree filepath *simple-tree*))
| null | https://raw.githubusercontent.com/white-silence88/cse/9d938129a86f701fbe618a545b45c8f16f27b879/src/common/json-file.lisp | lisp | json-file
tree/build-key
Description:
procedure for get value for key for tree pair
Params:
key [String] name of tree node
type [String] type of tree
reserved [List<String>] list of reserved words
Returns
name of treee node
tree/value
Description:
procedure for get value for current iterations.
If type of value is List - add list procedure and return.
Else - return value.
Params:
Returns:
hash->>tree/iteration
Description:
procedure for get result iteration content convertations
Params:
key [String] name of property
type [String] type of tree
Returns:
current iteration pair (key and value)
hash->>tree
Description:
Params:
keys [List<String>] list of hash table keys
type [String] type of tree
Returns:
routes tree
file->hash->tree
Description:
function for create routes tree from JSON file
Params:
filepath [String] full file path
type [String] type of tree
Returns:
routes file tree
file->>routes-tree
Description:
procedure for convert file content (.json-file) for route tree
Params:
filepath [String] full file path
Returns:
routes tree from JSON file
Description:
procedure for convert file content (.json-file) for tree
Params:
filepath [String] full file path
Returns:
tree from JSON file | (in-package #:cse)
(defun tree<-get-key (key type reserved)
(cond
((member key reserved :test (lambda (k v) (string= k v))) key)
(t (if (string= type "routes")
(concatenate 'string "/" key)
key))))
If type of value is HashTable - run hash->>tree procedure with new current arguments
value [ HashTable|List|Any ] value for current key
(defun tree<-get-value (value type)
(cond
((typep value 'hash-table)
(hash->>tree (alexandria:hash-table-keys value) value type))
(t value)))
content [ HashTable < String|HashTable|List < String > > ] routes HashTable
(defun hash->>tree/iteration (key content type)
(let
((value (gethash key content))
(reserved
(list
*route-config-routes-field*
*route-config-description-field*
*route-config-on-request-field*
*route-config-on-response-field*
*route-config-methods-field*
*route-config-handler-field*
*route-config-answer-field*
"title"
"message"
"description"
"data")))
(cons (tree<-get-key key type reserved) (tree<-get-value value type))))
procedure for create list of pairs from HashTable by keys
content [ HashTable < String|HashTable|List < String > > ] routes HashTable
(defun hash->>tree (keys content type)
(map 'list
(lambda (key)
(hash->>tree/iteration key content type))
keys))
(defun file->hash->tree (filepath type)
(let*
((content-as-string (uiop:read-file-string filepath))
(content-as-hash (jonathan:parse content-as-string :as :hash-table))
(keys (alexandria:hash-table-keys content-as-hash)))
(hash->>tree keys content-as-hash type)))
(defun json-file->>routes-tree (filepath)
(file->hash->tree filepath *routes-tree*))
file->>tree
(defun json-file->>tree (filepath)
(file->hash->tree filepath *simple-tree*))
|
e38f55356885ae810040a91e6e1b3096d3fb9aab31a6c6a0951b2890d2e5d25d | haskell-repa/repa | Simple.hs |
module Data.Repa.Flow.Simple
( module Data.Repa.Flow.States
, Source
, Sink
-- * Evaluation
, drainS
-- * Conversions
, fromList
, toList
, takeList
-- * Finalizers
, finalize_i
, finalize_o
-- * Flow Operators
-- ** Constructors
, repeat_i
, replicate_i
, prepend_i
-- ** Mapping
, map_i, map_o
-- ** Connecting
, dup_oo, dup_io, dup_oi
, connect_i
-- ** Splitting
, head_i
, peek_i
-- ** Grouping
, groups_i
-- ** Packing
, pack_ii
-- ** Folding
, folds_ii
-- ** Watching
, watch_i
, watch_o
, trigger_o
-- ** Ignorance
, ignore_o
, abandon_o
-- * Flow IO
-- ** Sourcing
, fromFiles
, sourceBytes
, sourceRecords
-- ** Sinking
, toFiles
, sinkBytes)
where
import Data.Repa.Flow.States
import Data.Repa.Flow.Simple.Base
import Data.Repa.Flow.Simple.List
import Data.Repa.Flow.Simple.Operator
import Data.Repa.Flow.Simple.IO
import qualified Data.Repa.Flow.Generic.Eval as G
#include "repa-flow.h"
-- | Pull all available values from the source and push them to the sink.
drainS :: Monad m
=> Source m a -> Sink m a -> m ()
drainS = G.drainS
# INLINE drainS #
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-flow/Data/Repa/Flow/Simple.hs | haskell | * Evaluation
* Conversions
* Finalizers
* Flow Operators
** Constructors
** Mapping
** Connecting
** Splitting
** Grouping
** Packing
** Folding
** Watching
** Ignorance
* Flow IO
** Sourcing
** Sinking
| Pull all available values from the source and push them to the sink. |
module Data.Repa.Flow.Simple
( module Data.Repa.Flow.States
, Source
, Sink
, drainS
, fromList
, toList
, takeList
, finalize_i
, finalize_o
, repeat_i
, replicate_i
, prepend_i
, map_i, map_o
, dup_oo, dup_io, dup_oi
, connect_i
, head_i
, peek_i
, groups_i
, pack_ii
, folds_ii
, watch_i
, watch_o
, trigger_o
, ignore_o
, abandon_o
, fromFiles
, sourceBytes
, sourceRecords
, toFiles
, sinkBytes)
where
import Data.Repa.Flow.States
import Data.Repa.Flow.Simple.Base
import Data.Repa.Flow.Simple.List
import Data.Repa.Flow.Simple.Operator
import Data.Repa.Flow.Simple.IO
import qualified Data.Repa.Flow.Generic.Eval as G
#include "repa-flow.h"
drainS :: Monad m
=> Source m a -> Sink m a -> m ()
drainS = G.drainS
# INLINE drainS #
|
9b120f87a72169e8e5b35d3a7fcdec11cec75ba64d95afc3cec6c275a3450984 | typedclojure/typedclojure | infer_vars.clj | Copyright ( c ) , contributors .
;; 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.
(ns typed.clj.checker.experimental.infer-vars
(:require
[clojure.core.typed.util-vars :as vs]
[typed.cljc.checker.type-rep :as r]
[typed.cljc.checker.type-ctors :as c]
[typed.clj.checker.parse-unparse :as prs]
[clojure.core.typed.current-impl :as impl]
[typed.cljc.runtime.env :as env]))
(defn add-inferred-type
"Add type t to the pool of inferred types of var vsym in namespace ns."
[nsym vsym t]
{:pre [(symbol? nsym)
(symbol? vsym)
(r/Type? t)]
:post [(nil? %)]}
(env/swap-checker! update-in
[:inferred-unchecked-vars nsym vsym]
(fnil conj [])
(binding [vs/*verbose-types* true]
(prs/unparse-type t)))
nil)
(defn inferred-var-in-ns
[nsym vsym]
{:pre [(symbol? nsym)
(symbol? vsym)]
:post [(r/Type? %)]}
(if-some [ts (seq (get-in (env/deref-checker) [:inferred-unchecked-vars nsym vsym]))]
(apply c/Un (map prs/parse-type ts))
r/-any))
(defn using-alias-in-ns [nsym vsym]
{:pre [(symbol? nsym)
(symbol? vsym)
(namespace vsym)]
:post [(symbol? %)]}
(if-let [alias (some-> nsym find-ns (prs/alias-in-ns (symbol (namespace vsym))))]
(symbol (str alias) (name vsym))
vsym))
(defn prepare-inferred-untyped-var-expression
"Return an expression to eval in namespace nsym, which declares
untyped var vsym as its inferred type."
[nsym vsym]
(let [t (inferred-var-in-ns nsym vsym)]
(prs/with-unparse-ns nsym
(list (using-alias-in-ns nsym 'clojure.core.typed/ann)
(using-alias-in-ns nsym vsym)
(prs/unparse-type t)))))
(defn infer-unannotated-vars
"Return a vector of syntax that can be spliced into the given namespace,
that annotates the inferred untyped variables."
[nsym]
(mapv (fn [vsym] (prepare-inferred-untyped-var-expression nsym vsym))
(keys (get-in (env/deref-checker) [:inferred-unchecked-vars nsym]))))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/3f30bcedfdca0d4e9a8af3fc95985372d129cd4c/typed/clj.checker/src/typed/clj/checker/experimental/infer_vars.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. | Copyright ( c ) , contributors .
(ns typed.clj.checker.experimental.infer-vars
(:require
[clojure.core.typed.util-vars :as vs]
[typed.cljc.checker.type-rep :as r]
[typed.cljc.checker.type-ctors :as c]
[typed.clj.checker.parse-unparse :as prs]
[clojure.core.typed.current-impl :as impl]
[typed.cljc.runtime.env :as env]))
(defn add-inferred-type
"Add type t to the pool of inferred types of var vsym in namespace ns."
[nsym vsym t]
{:pre [(symbol? nsym)
(symbol? vsym)
(r/Type? t)]
:post [(nil? %)]}
(env/swap-checker! update-in
[:inferred-unchecked-vars nsym vsym]
(fnil conj [])
(binding [vs/*verbose-types* true]
(prs/unparse-type t)))
nil)
(defn inferred-var-in-ns
[nsym vsym]
{:pre [(symbol? nsym)
(symbol? vsym)]
:post [(r/Type? %)]}
(if-some [ts (seq (get-in (env/deref-checker) [:inferred-unchecked-vars nsym vsym]))]
(apply c/Un (map prs/parse-type ts))
r/-any))
(defn using-alias-in-ns [nsym vsym]
{:pre [(symbol? nsym)
(symbol? vsym)
(namespace vsym)]
:post [(symbol? %)]}
(if-let [alias (some-> nsym find-ns (prs/alias-in-ns (symbol (namespace vsym))))]
(symbol (str alias) (name vsym))
vsym))
(defn prepare-inferred-untyped-var-expression
"Return an expression to eval in namespace nsym, which declares
untyped var vsym as its inferred type."
[nsym vsym]
(let [t (inferred-var-in-ns nsym vsym)]
(prs/with-unparse-ns nsym
(list (using-alias-in-ns nsym 'clojure.core.typed/ann)
(using-alias-in-ns nsym vsym)
(prs/unparse-type t)))))
(defn infer-unannotated-vars
"Return a vector of syntax that can be spliced into the given namespace,
that annotates the inferred untyped variables."
[nsym]
(mapv (fn [vsym] (prepare-inferred-untyped-var-expression nsym vsym))
(keys (get-in (env/deref-checker) [:inferred-unchecked-vars nsym]))))
|
322e53110851dfe171d9f49cd0c761c9443b88ac9402081648a852ea20035bf2 | ekmett/distributive | Trustworthy.hs | # LANGUAGE Unsafe #
-- |
Copyright : ( c ) 2021
License : BSD-2 - Clause OR Apache-2.0
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
Safe Haskell has a pretty egregious design flaw .
--
-- If you use @-Winferred-safe-imports@, which is really
-- your only way to get visibility into upstream safety,
-- there is generally no way to escape the warnings it
-- gives except to expect upstream packages to fix their code.
--
-- The "fix" is to import a module that isn't @Safe@ so
I can forcibly downgrade myself to @Trustworthy@.
--
Ideally , I 'd just have @{- # LANGUAGE TrustworthyOrBetter # -}@
-- extension, but every time I've asked for it, I've been
-- told this is against the spirit of the extension, which
-- as far as I can tell exists solely to make my life hell.
module Trustworthy () where
| null | https://raw.githubusercontent.com/ekmett/distributive/a606a9efd2f3e0458fb5808c70445333fdaae34b/src/Trustworthy.hs | haskell | |
Stability : experimental
Portability : non-portable
If you use @-Winferred-safe-imports@, which is really
your only way to get visibility into upstream safety,
there is generally no way to escape the warnings it
gives except to expect upstream packages to fix their code.
The "fix" is to import a module that isn't @Safe@ so
# LANGUAGE TrustworthyOrBetter #
extension, but every time I've asked for it, I've been
told this is against the spirit of the extension, which
as far as I can tell exists solely to make my life hell. | # LANGUAGE Unsafe #
Copyright : ( c ) 2021
License : BSD-2 - Clause OR Apache-2.0
Maintainer : < >
Safe Haskell has a pretty egregious design flaw .
I can forcibly downgrade myself to @Trustworthy@.
module Trustworthy () where
|
b4a313e72908886f93981e46f2ab6289a65f93e27069e74d9679b023668fc45e | jackfirth/resyntax | match-shortcuts-test.rkt | #lang resyntax/testing/refactoring-test
require: resyntax/default-recommendations match-shortcuts
header:
------------------------------
#lang racket/base
(require racket/match)
------------------------------
test: "single-clause match expressions can be replaced with match-define expressions"
------------------------------
(define (foo x)
(match x
[(list a b c)
(displayln "foo!")
(+ a b c)]))
------------------------------
------------------------------
(define (foo x)
(match-define (list a b c) x)
(displayln "foo!")
(+ a b c))
------------------------------
| null | https://raw.githubusercontent.com/jackfirth/resyntax/15b5cdea07ca616b60431fdfc414faae4848f8d9/default-recommendations/match-shortcuts-test.rkt | racket | #lang resyntax/testing/refactoring-test
require: resyntax/default-recommendations match-shortcuts
header:
------------------------------
#lang racket/base
(require racket/match)
------------------------------
test: "single-clause match expressions can be replaced with match-define expressions"
------------------------------
(define (foo x)
(match x
[(list a b c)
(displayln "foo!")
(+ a b c)]))
------------------------------
------------------------------
(define (foo x)
(match-define (list a b c) x)
(displayln "foo!")
(+ a b c))
------------------------------
|
|
d630b3e3d59b99a91b126d23747d507718176a2d5ffd994af5141e7303566fd7 | ds-wizard/engine-backend | Detail_Password_PUT.hs | module Wizard.Api.Handler.User.Detail_Password_PUT where
import Data.Maybe (fromMaybe)
import qualified Data.UUID as U
import Servant
import Shared.Api.Handler.Common
import Shared.Model.Context.TransactionState
import Wizard.Api.Handler.Common
import Wizard.Api.Resource.User.UserPasswordDTO
import Wizard.Api.Resource.User.UserPasswordJM ()
import Wizard.Model.Context.BaseContext
import Wizard.Service.User.UserService
type Detail_Password_PUT =
Header "Authorization" String
:> Header "Host" String
:> ReqBody '[SafeJSON] UserPasswordDTO
:> "users"
:> Capture "uUuid" String
:> "password"
:> QueryParam "hash" String
:> Verb PUT 204 '[SafeJSON] (Headers '[Header "x-trace-uuid" String] NoContent)
detail_password_PUT
:: Maybe String
-> Maybe String
-> UserPasswordDTO
-> String
-> Maybe String
-> BaseContextM (Headers '[Header "x-trace-uuid" String] NoContent)
detail_password_PUT mTokenHeader mServerUrl reqDto uUuid mHash =
getMaybeAuthServiceExecutor mTokenHeader mServerUrl $ \runInAuthService ->
runInAuthService Transactional $
addTraceUuidHeader =<< do
ia <- isAdmin
if ia
then do
changeUserPasswordByAdmin uUuid reqDto
return NoContent
else do
let hash = fromMaybe (U.toString U.nil) mHash
changeUserPasswordByHash uUuid hash reqDto
return NoContent
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Api/Handler/User/Detail_Password_PUT.hs | haskell | module Wizard.Api.Handler.User.Detail_Password_PUT where
import Data.Maybe (fromMaybe)
import qualified Data.UUID as U
import Servant
import Shared.Api.Handler.Common
import Shared.Model.Context.TransactionState
import Wizard.Api.Handler.Common
import Wizard.Api.Resource.User.UserPasswordDTO
import Wizard.Api.Resource.User.UserPasswordJM ()
import Wizard.Model.Context.BaseContext
import Wizard.Service.User.UserService
type Detail_Password_PUT =
Header "Authorization" String
:> Header "Host" String
:> ReqBody '[SafeJSON] UserPasswordDTO
:> "users"
:> Capture "uUuid" String
:> "password"
:> QueryParam "hash" String
:> Verb PUT 204 '[SafeJSON] (Headers '[Header "x-trace-uuid" String] NoContent)
detail_password_PUT
:: Maybe String
-> Maybe String
-> UserPasswordDTO
-> String
-> Maybe String
-> BaseContextM (Headers '[Header "x-trace-uuid" String] NoContent)
detail_password_PUT mTokenHeader mServerUrl reqDto uUuid mHash =
getMaybeAuthServiceExecutor mTokenHeader mServerUrl $ \runInAuthService ->
runInAuthService Transactional $
addTraceUuidHeader =<< do
ia <- isAdmin
if ia
then do
changeUserPasswordByAdmin uUuid reqDto
return NoContent
else do
let hash = fromMaybe (U.toString U.nil) mHash
changeUserPasswordByHash uUuid hash reqDto
return NoContent
|
|
c9c4acc17ea63b56dff2248f98e0655776f45448a80465d6f0f1021d1e59033a | dpom/clj-duckling | money.clj | (ns clj-duckling.dims.money
(:require
[clj-duckling.util.engine :refer [export-value]]))
(defmethod export-value :amount-of-money [{:keys [value unit] :as token} _]
{:type "value" :value value :unit unit})
(defmethod export-value :budget [{:keys [value unit level] :as token} _]
{:type "value" :value value :unit unit :level level})
| null | https://raw.githubusercontent.com/dpom/clj-duckling/8728f9a99b4b002e9ce2ea62b3a82a61b0cdac06/src/clj_duckling/dims/money.clj | clojure | (ns clj-duckling.dims.money
(:require
[clj-duckling.util.engine :refer [export-value]]))
(defmethod export-value :amount-of-money [{:keys [value unit] :as token} _]
{:type "value" :value value :unit unit})
(defmethod export-value :budget [{:keys [value unit level] :as token} _]
{:type "value" :value value :unit unit :level level})
|
|
84497c432975fca79eca57aa6b25b5547dddeb766cac14b9eb01a2a7cdba5584 | haskell-tools/haskell-tools | Representation.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
-- | Representation of the modules and packages in the daemon session.
module Language.Haskell.Tools.Daemon.Representation where
import Control.Reference
import Data.Function (on)
import Data.Map.Strict as Map
import Data.Maybe
import DynFlags
import GHC
import Language.Haskell.Tools.Refactor
| The modules of a library , executable , test or benchmark . A package contains one or more module collection .
data ModuleCollection k
= ModuleCollection { _mcId :: ModuleCollectionId
, _mcLoadDone :: Bool
, _mcRoot :: FilePath
, _mcSourceDirs :: [FilePath]
, _mcModuleFiles :: [(ModuleNameStr, FilePath)]
, _mcModules :: (Map.Map k ModuleRecord)
^ Sets up the ghc environment for compiling the modules of this collection
^ Sets up the ghc environment for dependency analysis
, _mcDependencies :: [ModuleCollectionId]
}
modCollToSfk :: ModuleCollection ModuleNameStr -> ModuleCollection SourceFileKey
modCollToSfk ModuleCollection{..} = ModuleCollection{ _mcModules = Map.mapKeys (SourceFileKey "") _mcModules, ..}
-- | The state of a module.
data ModuleRecord
= ModuleNotLoaded { _modRecCodeGen :: CodeGenPolicy
, _recModuleExposed :: Bool
}
| ModuleParsed { _parsedRecModule :: UnnamedModule
, _modRecMS :: ModSummary
}
| ModuleRenamed { _renamedRecModule :: UnnamedModule
, _modRecMS :: ModSummary
}
| ModuleTypeChecked { _typedRecModule :: UnnamedModule
, _modRecMS :: ModSummary
, _modRecCodeGen :: CodeGenPolicy
}
isLoaded :: ModuleRecord -> Bool
isLoaded ModuleTypeChecked{} = True
isLoaded _ = False
data CodeGenPolicy = NoCodeGen | InterpretedCode | GeneratedCode
deriving (Eq, Ord, Show)
-- | An alias for module names
type ModuleNameStr = String
-- | This data structure identifies a module collection.
data ModuleCollectionId = DirectoryMC FilePath
| LibraryMC String
| ExecutableMC String String
| TestSuiteMC String String
| BenchmarkMC String String
deriving (Eq, Ord, Show)
instance Eq (ModuleCollection k) where
(==) = (==) `on` _mcId
instance Show k => Show (ModuleCollection k) where
show (ModuleCollection id loaded root srcDirs mapping mods _ _ deps)
= "ModuleCollection (" ++ show id ++ ") " ++ show loaded ++ " " ++ root ++ " " ++ show srcDirs ++ " " ++ show mapping
++ " (" ++ show mods ++ ") " ++ show deps
makeReferences ''ModuleCollection
makeReferences ''ModuleRecord
instance Show ModuleRecord where
show (ModuleNotLoaded code exposed) = "ModuleNotLoaded " ++ show code ++ " " ++ show exposed
show mr@(ModuleParsed {}) = "ModuleParsed (" ++ (GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod $ fromJust $ mr ^? modRecMS) ++ ")"
show mr@(ModuleRenamed {}) = "ModuleRenamed (" ++ (GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod $ fromJust $ mr ^? modRecMS) ++ ")"
show mr@(ModuleTypeChecked {}) = "ModuleTypeChecked (" ++ (GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod $ fromJust $ mr ^? modRecMS) ++ ")"
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/daemon/Language/Haskell/Tools/Daemon/Representation.hs | haskell | | Representation of the modules and packages in the daemon session.
| The state of a module.
| An alias for module names
| This data structure identifies a module collection. | # LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
module Language.Haskell.Tools.Daemon.Representation where
import Control.Reference
import Data.Function (on)
import Data.Map.Strict as Map
import Data.Maybe
import DynFlags
import GHC
import Language.Haskell.Tools.Refactor
| The modules of a library , executable , test or benchmark . A package contains one or more module collection .
data ModuleCollection k
= ModuleCollection { _mcId :: ModuleCollectionId
, _mcLoadDone :: Bool
, _mcRoot :: FilePath
, _mcSourceDirs :: [FilePath]
, _mcModuleFiles :: [(ModuleNameStr, FilePath)]
, _mcModules :: (Map.Map k ModuleRecord)
^ Sets up the ghc environment for compiling the modules of this collection
^ Sets up the ghc environment for dependency analysis
, _mcDependencies :: [ModuleCollectionId]
}
modCollToSfk :: ModuleCollection ModuleNameStr -> ModuleCollection SourceFileKey
modCollToSfk ModuleCollection{..} = ModuleCollection{ _mcModules = Map.mapKeys (SourceFileKey "") _mcModules, ..}
data ModuleRecord
= ModuleNotLoaded { _modRecCodeGen :: CodeGenPolicy
, _recModuleExposed :: Bool
}
| ModuleParsed { _parsedRecModule :: UnnamedModule
, _modRecMS :: ModSummary
}
| ModuleRenamed { _renamedRecModule :: UnnamedModule
, _modRecMS :: ModSummary
}
| ModuleTypeChecked { _typedRecModule :: UnnamedModule
, _modRecMS :: ModSummary
, _modRecCodeGen :: CodeGenPolicy
}
isLoaded :: ModuleRecord -> Bool
isLoaded ModuleTypeChecked{} = True
isLoaded _ = False
data CodeGenPolicy = NoCodeGen | InterpretedCode | GeneratedCode
deriving (Eq, Ord, Show)
type ModuleNameStr = String
data ModuleCollectionId = DirectoryMC FilePath
| LibraryMC String
| ExecutableMC String String
| TestSuiteMC String String
| BenchmarkMC String String
deriving (Eq, Ord, Show)
instance Eq (ModuleCollection k) where
(==) = (==) `on` _mcId
instance Show k => Show (ModuleCollection k) where
show (ModuleCollection id loaded root srcDirs mapping mods _ _ deps)
= "ModuleCollection (" ++ show id ++ ") " ++ show loaded ++ " " ++ root ++ " " ++ show srcDirs ++ " " ++ show mapping
++ " (" ++ show mods ++ ") " ++ show deps
makeReferences ''ModuleCollection
makeReferences ''ModuleRecord
instance Show ModuleRecord where
show (ModuleNotLoaded code exposed) = "ModuleNotLoaded " ++ show code ++ " " ++ show exposed
show mr@(ModuleParsed {}) = "ModuleParsed (" ++ (GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod $ fromJust $ mr ^? modRecMS) ++ ")"
show mr@(ModuleRenamed {}) = "ModuleRenamed (" ++ (GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod $ fromJust $ mr ^? modRecMS) ++ ")"
show mr@(ModuleTypeChecked {}) = "ModuleTypeChecked (" ++ (GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod $ fromJust $ mr ^? modRecMS) ++ ")"
|
503504c89bfe3b53fd13a5cd448dcbf46fdd213c32fa3c0eff8de9d18fa4c3df | oker1/websocket-chat | websocket_handler.erl | -module(websocket_handler).
-behaviour(cowboy_websocket_handler).
-export([init/3, websocket_init/3, websocket_handle/3,
websocket_info/3, websocket_terminate/3]).
init({tcp, http}, _Req, _Opts) ->
{upgrade, protocol, cowboy_websocket}.
websocket_init(_Any, Req, _Opts) ->
cset_server:register(self()),
Req2 = cowboy_req:compact(Req),
{ok, Req2, undefined_state, hibernate}.
websocket_handle({text, Msg}, Req, State) ->
cset_server:incomingMessageFromClient(Msg, self()),
{ok, Req, State};
websocket_handle(_Any, Req, State) ->
{ok, Req, State}.
websocket_info({outgoingMessage, Msg}, Req, State) ->
{reply, {text, Msg}, Req, State, hibernate};
websocket_info(_Info, Req, State) ->
{ok, Req, State, hibernate}.
websocket_terminate(_Reason, _Req, _State) ->
cset_server:unregister(self()),
ok. | null | https://raw.githubusercontent.com/oker1/websocket-chat/8dfbd7357b2e37615d1d055f8cbb70777e5d82c8/src/websocket_handler.erl | erlang | -module(websocket_handler).
-behaviour(cowboy_websocket_handler).
-export([init/3, websocket_init/3, websocket_handle/3,
websocket_info/3, websocket_terminate/3]).
init({tcp, http}, _Req, _Opts) ->
{upgrade, protocol, cowboy_websocket}.
websocket_init(_Any, Req, _Opts) ->
cset_server:register(self()),
Req2 = cowboy_req:compact(Req),
{ok, Req2, undefined_state, hibernate}.
websocket_handle({text, Msg}, Req, State) ->
cset_server:incomingMessageFromClient(Msg, self()),
{ok, Req, State};
websocket_handle(_Any, Req, State) ->
{ok, Req, State}.
websocket_info({outgoingMessage, Msg}, Req, State) ->
{reply, {text, Msg}, Req, State, hibernate};
websocket_info(_Info, Req, State) ->
{ok, Req, State, hibernate}.
websocket_terminate(_Reason, _Req, _State) ->
cset_server:unregister(self()),
ok. |
|
2b2ae435751ad4cb153817c5469f41d88deedd234930ac658b11cd2f59ca937d | robrix/Manifold | Checking.hs | # LANGUAGE DeriveFunctor , FlexibleContexts , FlexibleInstances , MultiParamTypeClasses , PolyKinds , TypeApplications , TypeOperators , UndecidableInstances #
module Manifold.Proof.Checking where
import Control.Effect
import Data.Foldable (foldl')
import Data.Semiring (Semiring(..), Unital(..), zero)
import Data.Semilattice.Lower
import Manifold.Constraint
import Manifold.Context
import Manifold.Declaration
import Manifold.Module as Module
import Manifold.Name
import Manifold.Name.Annotated
import Manifold.Pattern
import Manifold.Proof
import Manifold.Proof.Formation
import Manifold.Purpose
import Manifold.Substitution
import Manifold.Term
import Manifold.Term.Elim
import Manifold.Term.Intro
import Manifold.Type hiding (Var, Elim, Intro)
import Manifold.Type.Intro
import Manifold.Unification
checkModule :: ( Carrier sig m
, Effect sig
, Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member (Reader (ModuleTable Name (Term Name))) sig
, Member (State (ModuleTable (Annotated usage) (Term Name))) sig
, Monoid usage
, Unital usage
)
=> Module Name (Term Name)
-> Proof usage m (Module (Annotated usage) (Term Name))
checkModule m = lookupEvaluated (moduleName m) >>= maybe (cacheModule m) pure
cacheModule :: ( Carrier sig m
, Effect sig
, Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member (Reader (ModuleTable Name (Term Name))) sig
, Member (State (ModuleTable (Annotated usage) (Term Name))) sig
, Monoid usage
, Unital usage
)
=> Module Name (Term Name)
-> Proof usage m (Module (Annotated usage) (Term Name))
cacheModule (Module name imports decls) = do
cacheEvaluated (Module name imports [])
imports' <- traverse (\ name -> lookupUnevaluated name >>= maybe (unknownModule name) checkModule) imports
decls' <- runFresh (runProof (runContext (runIsType (foldr (>-) (foldr combine (pure []) decls) (imports' >>= moduleExports)))))
let m = Module name imports decls'
m <$ cacheEvaluated m
where combine decl rest = do
decl' <- checkDeclaration decl
foldr (>-) ((decl' :) <$> rest) (declarationSignatures decl')
lookupUnevaluated :: (Member (Reader (ModuleTable Name (Term Name))) sig, Carrier sig m) => Name -> Proof usage m (Maybe (Module Name (Term Name)))
lookupUnevaluated name = asks (Module.lookup name)
lookupEvaluated :: (Member (State (ModuleTable (Annotated usage) (Term Name))) sig, Carrier sig m) => Name -> Proof usage m (Maybe (Module (Annotated usage) (Term Name)))
lookupEvaluated name = gets (Module.lookup name)
cacheEvaluated :: (Member (State (ModuleTable (Annotated usage) (Term Name))) sig, Carrier sig m) => Module (Annotated usage) (Term Name) -> Proof usage m ()
cacheEvaluated = modify . insert
checkDeclaration :: ( Carrier sig m
, Effect sig
, Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member Fresh sig
, Member (IsType usage) sig
, Member (Reader (Context (Constraint (Annotated usage) (Type (Annotated usage))))) sig
, Monoid usage
, Unital usage
)
=> Declaration Name (Term Name)
-> Proof usage m (Declaration (Annotated usage) (Term Name))
checkDeclaration (Binding (name ::: ty) term) = do
ty' <- isType ty
let annotated = Annotated name one
ty'' <- annotated ::: ty' >- runSigma Intensional (runSubstitution (runUnify (runCheck (check term ty'))))
pure (Binding (annotated ::: ty'') term)
checkDeclaration (Datatype (name ::: ty) constructors) = do
ty' <- isType ty
let annotated = Annotated name zero
constructors' <- annotated ::: ty' >- runSigma Extensional (traverse checkConstructor constructors)
pure (Datatype (annotated ::: ty') constructors')
where checkConstructor (name ::: ty) = (Annotated name zero :::) <$> isType ty
runCheck :: ( Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member Fresh sig
, Member (Reader usage) sig
, Member (Reader (Context (Constraint (Annotated usage) (Type (Annotated usage))))) sig
, Member (State (Substitution (Type (Annotated usage)))) sig
, Member (Unify usage) sig
, Monoid usage
, Carrier sig m
, Unital usage
)
=> Proof usage (CheckC usage (Proof usage m)) a
-> Proof usage m a
runCheck = runCheckC . interpret . runProof
newtype CheckC usage m a = CheckC { runCheckC :: m a }
instance ( Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member Fresh sig
, Member (Reader usage) sig
, Member (Reader (Context (Constraint (Annotated usage) (Type (Annotated usage))))) sig
, Member (State (Substitution (Type (Annotated usage)))) sig
, Member (Unify usage) sig
, Monoid usage
, Carrier sig m
, Unital usage
)
=> Carrier (Check usage :+: sig) (CheckC usage (Proof usage m)) where
gen = CheckC . gen
alg = algC \/ (CheckC . alg . handlePure runCheckC)
where algC (Check term expected k) = CheckC $ case (unTerm term, unType expected) of
(Intro (Abs var body), IntroT (Annotated name pi ::: _S :-> _T))
| _S == typeT -> do
runCheck (check term _T) >>= runCheckC . k
| otherwise -> do
sigma <- ask
_T' <- Annotated var (sigma >< pi) ::: _S >- runCheck (check body _T)
runCheckC (k (Annotated name pi ::: _S .-> _T'))
(Elim (Case subject matches), _) -> do
subject' <- runCheck (infer subject)
foldl' (checkMatch subject') (pure expected) matches >>= runCheckC . k
_ -> do
actual <- runCheck (infer term)
unify actual expected >>= runCheckC . k
where checkMatch subject expected (pattern, body) = do
expected' <- expected
checkPattern pattern subject (runCheck (check body expected'))
algC (Infer term k) = CheckC $ case unTerm term of
Var name -> lookupType name >>= runCheckC . k
Intro (Data name vs) -> do
_C <- lookupType name
checkFields _C vs >>= runCheckC . k
where checkFields ty [] = pure ty
checkFields (Type (IntroT (_ ::: ty :-> ret))) (v : vs) = runCheck (check v ty) >> checkFields ret vs
checkFields ty _ = do
t1 <- freshName
t2 <- freshName
cannotUnify ty (Annotated t1 zero ::: ty .-> tvar t2)
Elim (App f a) -> do
n <- I <$> fresh
t1 <- freshName
t2 <- freshName
_ <- runCheck (check f (Annotated n zero ::: tvar t1 .-> tvar t2))
_ <- runCheck (check a (tvar t1))
runCheckC (k (tvar t2))
_ -> noRuleToInferType term >>= runCheckC . k
checkPattern :: ( Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member Fresh sig
, Member (Reader usage) sig
, Member (Reader (Context (Constraint (Annotated usage) (Type (Annotated usage))))) sig
, Member (State (Substitution (Type (Annotated usage)))) sig
, Member (Unify usage) sig
, Carrier sig m
, Monoid usage
)
=> Pattern Name
-> Type (Annotated usage)
-> Proof usage m (Type (Annotated usage))
-> Proof usage m (Type (Annotated usage))
checkPattern (Pattern Wildcard) _ = id
checkPattern (Pattern (Variable name)) subject = (Annotated name zero ::: subject >-)
checkPattern (Pattern (Constructor name patterns)) subject = \ action -> do
conTy <- lookupType name
checkPatterns conTy patterns action
where checkPatterns ty [] = (unify ty subject >>)
checkPatterns (Type (IntroT (_ ::: ty :-> ret))) (p : ps) = checkPattern p ty . checkPatterns ret ps
checkPatterns ty _ = const (cannotUnify ty subject)
runSubstitution :: (Carrier sig m, Effect sig) => Named var => Proof usage (StateC (Substitution (Type var)) (Proof usage m)) (Type var) -> Proof usage m (Type var)
runSubstitution = fmap (uncurry apply) . runState lowerBound . runProof
runSigma :: (Carrier sig m, Monoid usage, Unital usage) => Purpose -> Proof usage (ReaderC usage (Proof usage m)) a -> Proof usage m a
runSigma Extensional = runReader zero . runProof
runSigma Intensional = runReader one . runProof
check :: (Member (Check usage) sig, Carrier sig m) => Term Name -> Type (Annotated usage) -> Proof usage m (Type (Annotated usage))
check term ty = send (Check term ty gen)
infer :: (Member (Check usage) sig, Carrier sig m) => Term Name -> Proof usage m (Type (Annotated usage))
infer term = send (Infer term gen)
data Check usage m k
= Check (Term Name) (Type (Annotated usage)) (Type (Annotated usage) -> k)
| Infer (Term Name) (Type (Annotated usage) -> k)
deriving (Functor)
instance HFunctor (Check usage) where
hfmap _ (Check tm ty k) = Check tm ty k
hfmap _ (Infer tm k) = Infer tm k
instance Effect (Check usage) where
handle state handler (Check term ty k) = Check term ty (handler . (<$ state) . k)
handle state handler (Infer term k) = Infer term (handler . (<$ state) . k)
| null | https://raw.githubusercontent.com/robrix/Manifold/3cc7a49c90b9cc7d1da61c532d0ee526ccdd3474/src/Manifold/Proof/Checking.hs | haskell | # LANGUAGE DeriveFunctor , FlexibleContexts , FlexibleInstances , MultiParamTypeClasses , PolyKinds , TypeApplications , TypeOperators , UndecidableInstances #
module Manifold.Proof.Checking where
import Control.Effect
import Data.Foldable (foldl')
import Data.Semiring (Semiring(..), Unital(..), zero)
import Data.Semilattice.Lower
import Manifold.Constraint
import Manifold.Context
import Manifold.Declaration
import Manifold.Module as Module
import Manifold.Name
import Manifold.Name.Annotated
import Manifold.Pattern
import Manifold.Proof
import Manifold.Proof.Formation
import Manifold.Purpose
import Manifold.Substitution
import Manifold.Term
import Manifold.Term.Elim
import Manifold.Term.Intro
import Manifold.Type hiding (Var, Elim, Intro)
import Manifold.Type.Intro
import Manifold.Unification
checkModule :: ( Carrier sig m
, Effect sig
, Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member (Reader (ModuleTable Name (Term Name))) sig
, Member (State (ModuleTable (Annotated usage) (Term Name))) sig
, Monoid usage
, Unital usage
)
=> Module Name (Term Name)
-> Proof usage m (Module (Annotated usage) (Term Name))
checkModule m = lookupEvaluated (moduleName m) >>= maybe (cacheModule m) pure
cacheModule :: ( Carrier sig m
, Effect sig
, Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member (Reader (ModuleTable Name (Term Name))) sig
, Member (State (ModuleTable (Annotated usage) (Term Name))) sig
, Monoid usage
, Unital usage
)
=> Module Name (Term Name)
-> Proof usage m (Module (Annotated usage) (Term Name))
cacheModule (Module name imports decls) = do
cacheEvaluated (Module name imports [])
imports' <- traverse (\ name -> lookupUnevaluated name >>= maybe (unknownModule name) checkModule) imports
decls' <- runFresh (runProof (runContext (runIsType (foldr (>-) (foldr combine (pure []) decls) (imports' >>= moduleExports)))))
let m = Module name imports decls'
m <$ cacheEvaluated m
where combine decl rest = do
decl' <- checkDeclaration decl
foldr (>-) ((decl' :) <$> rest) (declarationSignatures decl')
lookupUnevaluated :: (Member (Reader (ModuleTable Name (Term Name))) sig, Carrier sig m) => Name -> Proof usage m (Maybe (Module Name (Term Name)))
lookupUnevaluated name = asks (Module.lookup name)
lookupEvaluated :: (Member (State (ModuleTable (Annotated usage) (Term Name))) sig, Carrier sig m) => Name -> Proof usage m (Maybe (Module (Annotated usage) (Term Name)))
lookupEvaluated name = gets (Module.lookup name)
cacheEvaluated :: (Member (State (ModuleTable (Annotated usage) (Term Name))) sig, Carrier sig m) => Module (Annotated usage) (Term Name) -> Proof usage m ()
cacheEvaluated = modify . insert
checkDeclaration :: ( Carrier sig m
, Effect sig
, Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member Fresh sig
, Member (IsType usage) sig
, Member (Reader (Context (Constraint (Annotated usage) (Type (Annotated usage))))) sig
, Monoid usage
, Unital usage
)
=> Declaration Name (Term Name)
-> Proof usage m (Declaration (Annotated usage) (Term Name))
checkDeclaration (Binding (name ::: ty) term) = do
ty' <- isType ty
let annotated = Annotated name one
ty'' <- annotated ::: ty' >- runSigma Intensional (runSubstitution (runUnify (runCheck (check term ty'))))
pure (Binding (annotated ::: ty'') term)
checkDeclaration (Datatype (name ::: ty) constructors) = do
ty' <- isType ty
let annotated = Annotated name zero
constructors' <- annotated ::: ty' >- runSigma Extensional (traverse checkConstructor constructors)
pure (Datatype (annotated ::: ty') constructors')
where checkConstructor (name ::: ty) = (Annotated name zero :::) <$> isType ty
runCheck :: ( Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member Fresh sig
, Member (Reader usage) sig
, Member (Reader (Context (Constraint (Annotated usage) (Type (Annotated usage))))) sig
, Member (State (Substitution (Type (Annotated usage)))) sig
, Member (Unify usage) sig
, Monoid usage
, Carrier sig m
, Unital usage
)
=> Proof usage (CheckC usage (Proof usage m)) a
-> Proof usage m a
runCheck = runCheckC . interpret . runProof
newtype CheckC usage m a = CheckC { runCheckC :: m a }
instance ( Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member Fresh sig
, Member (Reader usage) sig
, Member (Reader (Context (Constraint (Annotated usage) (Type (Annotated usage))))) sig
, Member (State (Substitution (Type (Annotated usage)))) sig
, Member (Unify usage) sig
, Monoid usage
, Carrier sig m
, Unital usage
)
=> Carrier (Check usage :+: sig) (CheckC usage (Proof usage m)) where
gen = CheckC . gen
alg = algC \/ (CheckC . alg . handlePure runCheckC)
where algC (Check term expected k) = CheckC $ case (unTerm term, unType expected) of
(Intro (Abs var body), IntroT (Annotated name pi ::: _S :-> _T))
| _S == typeT -> do
runCheck (check term _T) >>= runCheckC . k
| otherwise -> do
sigma <- ask
_T' <- Annotated var (sigma >< pi) ::: _S >- runCheck (check body _T)
runCheckC (k (Annotated name pi ::: _S .-> _T'))
(Elim (Case subject matches), _) -> do
subject' <- runCheck (infer subject)
foldl' (checkMatch subject') (pure expected) matches >>= runCheckC . k
_ -> do
actual <- runCheck (infer term)
unify actual expected >>= runCheckC . k
where checkMatch subject expected (pattern, body) = do
expected' <- expected
checkPattern pattern subject (runCheck (check body expected'))
algC (Infer term k) = CheckC $ case unTerm term of
Var name -> lookupType name >>= runCheckC . k
Intro (Data name vs) -> do
_C <- lookupType name
checkFields _C vs >>= runCheckC . k
where checkFields ty [] = pure ty
checkFields (Type (IntroT (_ ::: ty :-> ret))) (v : vs) = runCheck (check v ty) >> checkFields ret vs
checkFields ty _ = do
t1 <- freshName
t2 <- freshName
cannotUnify ty (Annotated t1 zero ::: ty .-> tvar t2)
Elim (App f a) -> do
n <- I <$> fresh
t1 <- freshName
t2 <- freshName
_ <- runCheck (check f (Annotated n zero ::: tvar t1 .-> tvar t2))
_ <- runCheck (check a (tvar t1))
runCheckC (k (tvar t2))
_ -> noRuleToInferType term >>= runCheckC . k
checkPattern :: ( Eq usage
, Member (Error (ProofError (Annotated usage))) sig
, Member Fresh sig
, Member (Reader usage) sig
, Member (Reader (Context (Constraint (Annotated usage) (Type (Annotated usage))))) sig
, Member (State (Substitution (Type (Annotated usage)))) sig
, Member (Unify usage) sig
, Carrier sig m
, Monoid usage
)
=> Pattern Name
-> Type (Annotated usage)
-> Proof usage m (Type (Annotated usage))
-> Proof usage m (Type (Annotated usage))
checkPattern (Pattern Wildcard) _ = id
checkPattern (Pattern (Variable name)) subject = (Annotated name zero ::: subject >-)
checkPattern (Pattern (Constructor name patterns)) subject = \ action -> do
conTy <- lookupType name
checkPatterns conTy patterns action
where checkPatterns ty [] = (unify ty subject >>)
checkPatterns (Type (IntroT (_ ::: ty :-> ret))) (p : ps) = checkPattern p ty . checkPatterns ret ps
checkPatterns ty _ = const (cannotUnify ty subject)
runSubstitution :: (Carrier sig m, Effect sig) => Named var => Proof usage (StateC (Substitution (Type var)) (Proof usage m)) (Type var) -> Proof usage m (Type var)
runSubstitution = fmap (uncurry apply) . runState lowerBound . runProof
runSigma :: (Carrier sig m, Monoid usage, Unital usage) => Purpose -> Proof usage (ReaderC usage (Proof usage m)) a -> Proof usage m a
runSigma Extensional = runReader zero . runProof
runSigma Intensional = runReader one . runProof
check :: (Member (Check usage) sig, Carrier sig m) => Term Name -> Type (Annotated usage) -> Proof usage m (Type (Annotated usage))
check term ty = send (Check term ty gen)
infer :: (Member (Check usage) sig, Carrier sig m) => Term Name -> Proof usage m (Type (Annotated usage))
infer term = send (Infer term gen)
data Check usage m k
= Check (Term Name) (Type (Annotated usage)) (Type (Annotated usage) -> k)
| Infer (Term Name) (Type (Annotated usage) -> k)
deriving (Functor)
instance HFunctor (Check usage) where
hfmap _ (Check tm ty k) = Check tm ty k
hfmap _ (Infer tm k) = Infer tm k
instance Effect (Check usage) where
handle state handler (Check term ty k) = Check term ty (handler . (<$ state) . k)
handle state handler (Infer term k) = Infer term (handler . (<$ state) . k)
|
|
016a088dab5542fff6bade5a3be5770ac689c3787a34291c5cd28b86fc84c7dd | Ptival/language-ocaml | Test.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
module Language.OCaml.Parser.AttrId.Test
( testStrings,
)
where
import Data.String.Interpolate
import qualified Language.OCaml.Parser.SingleAttrId.Test as SingleAttrId
limit :: Int
limit = 10
testStrings :: [String]
testStrings =
[]
++ SingleAttrId.testStrings
++ [ [i| #{sai}.#{ai} ] |]
| sai <- SingleAttrId.testStrings,
ai <- take limit testStrings
]
| null | https://raw.githubusercontent.com/Ptival/language-ocaml/7b07fd3cc466bb2ad2cac4bfe3099505cb63a4f4/test/Language/OCaml/Parser/AttrId/Test.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE QuasiQuotes #
module Language.OCaml.Parser.AttrId.Test
( testStrings,
)
where
import Data.String.Interpolate
import qualified Language.OCaml.Parser.SingleAttrId.Test as SingleAttrId
limit :: Int
limit = 10
testStrings :: [String]
testStrings =
[]
++ SingleAttrId.testStrings
++ [ [i| #{sai}.#{ai} ] |]
| sai <- SingleAttrId.testStrings,
ai <- take limit testStrings
]
|
5fc37cef6c36c5d421f49b6b5e5f3e430bf233e452ca2b8d6fb82343873bc556 | bsansouci/bsb-native | test_nomli.ml | type t = A | B
[@@mli]
and s = C | D
[@@mli abstract]
module X = struct
type t = X | Y
[@@mli]
and s
let id x = x
[@@mli]
end
module Y : sig type t type s end = struct
type t = X | Y
type s = A | B
end
let f x y = x + y
[@@mli]
and g a b = (a, b)
[@@mli]
and h a b = (a, b)
[@@mli (h : int -> int -> int * int)]
let (x, y, z) = (1, 2, 3)
[@@mli (x : int), (y : int)]
| null | https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/experimental/frisch/test_nomli.ml | ocaml | type t = A | B
[@@mli]
and s = C | D
[@@mli abstract]
module X = struct
type t = X | Y
[@@mli]
and s
let id x = x
[@@mli]
end
module Y : sig type t type s end = struct
type t = X | Y
type s = A | B
end
let f x y = x + y
[@@mli]
and g a b = (a, b)
[@@mli]
and h a b = (a, b)
[@@mli (h : int -> int -> int * int)]
let (x, y, z) = (1, 2, 3)
[@@mli (x : int), (y : int)]
|
|
dd923ff7922a6dae48ef5d4882ec4f48bc170b269859b96b1ee11d7e8e608c16 | rubenbarroso/EOPL | 1_16.scm | 1
(define up
(lambda (lst)
(cond ((null? lst)
'())
((pair? (car lst))
(append (car lst) (up (cdr lst))))
(else (cons (car lst) (up (cdr lst)))))))
> ( up ' ( ( 1 2 ) ( 3 4 ) ) )
( 1 2 3 4 )
;> (up '((x (y)) z))
;(x (y) z)
Let 's check that ( down ( up lst ) ) is not lst :
;> (down (up '((x (y)) z)))
;((x) ((y)) (z))
;This is because we lose information when up-ing, since the non-list
;elements are left as-is, and then down does not know if they were
;lists or not.
2
;This is a *-function (see Little Schemer)
(define swapper
(lambda (s1 s2 slist)
(cond ((null? slist)
'())
((pair? (car slist))
(cons (swapper s1 s2 (car slist))
(swapper s1 s2 (cdr slist))))
((eq? s1 (car slist))
(cons s2
(swapper s1 s2 (cdr slist))))
((eq? s2 (car slist))
(cons s1
(swapper s1 s2 (cdr slist))))
(else (cons (car slist)
(swapper s1 s2 (cdr slist)))))))
;> (swapper 'a 'd '(a b c d))
;(d b c a)
;> (swapper 'a 'd '(a d () c d))
;(d a () c a)
;> (swapper 'x 'y '((x) y (z (x))))
;((y) x (z (y)))
3
(define count-occurrences
(lambda (s slist)
(cond ((null? slist) 0)
((pair? (car slist))
(+ (count-occurrences s (car slist))
(count-occurrences s (cdr slist))))
((eqv? s (car slist))
(+ 1 (count-occurrences s (cdr slist))))
(else (count-occurrences s (cdr slist))))))
;> (count-occurrences 'x '((f x) y (((x z) x))))
3
;> (count-occurrences 'x '((f x) y (((x z) () x))))
3
;> (count-occurrences 'w '((f x) y (((x z) z))))
0
4
(define flatten
(lambda (slist)
(cond ((null? slist) '())
((null? (car slist)) (flatten (cdr slist)))
((pair? (car slist))
(append (flatten (car slist))
(flatten (cdr slist))))
(else (cons (car slist)
(flatten (cdr slist)))))))
;> (flatten '((a) () (b ()) () (c)))
;(a b c)
;> (flatten '(a b c))
;(a b c)
;> (flatten '((a) () (b ()) () (c)))
;(a b c)
;> (flatten '((a b) c (((d)) e)))
;(a b c d e)
;> (flatten '(a b (() (c))))
;(a b c)
5
(define merge
(lambda (lon1 lon2)
(cond ((null? lon1) lon2)
((null? lon2) lon1)
((<= (car lon1) (car lon2))
(cons (car lon1)
(merge (cdr lon1) lon2)))
(else (cons (car lon2)
(merge lon1 (cdr lon2)))))))
> ( merge ' ( 1 4 ) ' ( 1 2 8) )
( 1 1 2 4 8)
> ( merge ' ( 35 62 81 90 91 ) ' ( 3 83 85 90 ) )
( 3 35 62 81 83 85 90 90 91 )
| null | https://raw.githubusercontent.com/rubenbarroso/EOPL/f9b3c03c2fcbaddf64694ee3243d54be95bfe31d/src/chapter1/1_16.scm | scheme | > (up '((x (y)) z))
(x (y) z)
> (down (up '((x (y)) z)))
((x) ((y)) (z))
This is because we lose information when up-ing, since the non-list
elements are left as-is, and then down does not know if they were
lists or not.
This is a *-function (see Little Schemer)
> (swapper 'a 'd '(a b c d))
(d b c a)
> (swapper 'a 'd '(a d () c d))
(d a () c a)
> (swapper 'x 'y '((x) y (z (x))))
((y) x (z (y)))
> (count-occurrences 'x '((f x) y (((x z) x))))
> (count-occurrences 'x '((f x) y (((x z) () x))))
> (count-occurrences 'w '((f x) y (((x z) z))))
> (flatten '((a) () (b ()) () (c)))
(a b c)
> (flatten '(a b c))
(a b c)
> (flatten '((a) () (b ()) () (c)))
(a b c)
> (flatten '((a b) c (((d)) e)))
(a b c d e)
> (flatten '(a b (() (c))))
(a b c) | 1
(define up
(lambda (lst)
(cond ((null? lst)
'())
((pair? (car lst))
(append (car lst) (up (cdr lst))))
(else (cons (car lst) (up (cdr lst)))))))
> ( up ' ( ( 1 2 ) ( 3 4 ) ) )
( 1 2 3 4 )
Let 's check that ( down ( up lst ) ) is not lst :
2
(define swapper
(lambda (s1 s2 slist)
(cond ((null? slist)
'())
((pair? (car slist))
(cons (swapper s1 s2 (car slist))
(swapper s1 s2 (cdr slist))))
((eq? s1 (car slist))
(cons s2
(swapper s1 s2 (cdr slist))))
((eq? s2 (car slist))
(cons s1
(swapper s1 s2 (cdr slist))))
(else (cons (car slist)
(swapper s1 s2 (cdr slist)))))))
3
(define count-occurrences
(lambda (s slist)
(cond ((null? slist) 0)
((pair? (car slist))
(+ (count-occurrences s (car slist))
(count-occurrences s (cdr slist))))
((eqv? s (car slist))
(+ 1 (count-occurrences s (cdr slist))))
(else (count-occurrences s (cdr slist))))))
3
3
0
4
(define flatten
(lambda (slist)
(cond ((null? slist) '())
((null? (car slist)) (flatten (cdr slist)))
((pair? (car slist))
(append (flatten (car slist))
(flatten (cdr slist))))
(else (cons (car slist)
(flatten (cdr slist)))))))
5
(define merge
(lambda (lon1 lon2)
(cond ((null? lon1) lon2)
((null? lon2) lon1)
((<= (car lon1) (car lon2))
(cons (car lon1)
(merge (cdr lon1) lon2)))
(else (cons (car lon2)
(merge lon1 (cdr lon2)))))))
> ( merge ' ( 1 4 ) ' ( 1 2 8) )
( 1 1 2 4 8)
> ( merge ' ( 35 62 81 90 91 ) ' ( 3 83 85 90 ) )
( 3 35 62 81 83 85 90 90 91 )
|
d96dc0bf69de5c9c87a883f86cfc295fb108d6cd67a4956f217d0cad48aec952 | dfinity-side-projects/dhc | rundhc.hs | import Data.Char
import qualified Data.ByteString as B
import Hero.Hero
main :: IO ()
main = putStr =<< runDemo =<< B.getContents
runDemo :: B.ByteString -> IO String
runDemo asm = stateVM . snd <$> runWasm "main" [] (mkHeroVM "" syscall wasm [])
where
wasm = either error id $ parseWasm asm
syscall ("system", "putStr") vm [I32_const ptr, I32_const len] = pure ([],
putStateVM (stateVM vm ++ [chr $ getNumVM 1 (ptr + i) vm | i <- [0..len - 1]]) vm)
syscall ("system", "putInt") vm [I32_const lo, I32_const hi] = pure ([],
putStateVM (stateVM vm ++ show (fromIntegral lo + fromIntegral hi * 2^(32 :: Integer) :: Integer)) vm)
syscall a _ b = error $ show ("BUG! bad syscall", a, b)
| null | https://raw.githubusercontent.com/dfinity-side-projects/dhc/60ac6c85ca02b53c0fdd1f5852c1eaf35f97d579/test/rundhc.hs | haskell | import Data.Char
import qualified Data.ByteString as B
import Hero.Hero
main :: IO ()
main = putStr =<< runDemo =<< B.getContents
runDemo :: B.ByteString -> IO String
runDemo asm = stateVM . snd <$> runWasm "main" [] (mkHeroVM "" syscall wasm [])
where
wasm = either error id $ parseWasm asm
syscall ("system", "putStr") vm [I32_const ptr, I32_const len] = pure ([],
putStateVM (stateVM vm ++ [chr $ getNumVM 1 (ptr + i) vm | i <- [0..len - 1]]) vm)
syscall ("system", "putInt") vm [I32_const lo, I32_const hi] = pure ([],
putStateVM (stateVM vm ++ show (fromIntegral lo + fromIntegral hi * 2^(32 :: Integer) :: Integer)) vm)
syscall a _ b = error $ show ("BUG! bad syscall", a, b)
|
|
a77d80f0807a74a4fb040dd2aa008347e041fc0f20b81b0e1e28252fd82c65d5 | NorfairKing/smos | BackupGarbageCollectorSpec.hs | module Smos.Server.Looper.BackupGarbageCollectorSpec where
import Control.Monad
import Control.Monad.State.Strict
import Data.GenValidity.Persist ()
import Data.Int
import Data.Set (Set)
import qualified Data.Set as S
import Data.Time
import Database.Persist.Sql
import Smos.Server.DB
import Smos.Server.Gen ()
import Smos.Server.Looper.BackupGarbageCollector
import Test.Syd
import Test.Syd.Validity
spec :: Spec
spec = do
describe "decideBackupsToDelete" $ do
it "only ever selects backups to delete, from the list" $
forAllValid $ \now ->
forAllValid $ \backups ->
let backupsToDelete = decideBackupsToDelete now defaultPeriods backups
ids = S.fromList $ map fst backups
in shouldSatisfyNamed
backupsToDelete
("`S.isSubsetOf` " <> show ids)
(`S.isSubsetOf` ids)
it "works with this single interval where a backup falls outside the interval" $
let t y m d = UTCTime (fromGregorian y m d) 0
periods =
[ (nominalDay * 3, 3)
]
backups =
[ (toSqlKey 1, t 2022 01 01),
(toSqlKey 2, t 2022 01 02),
< -- keeping this one
< -- keeping this one
< -- keeping this one
]
expectedBackupsToDelete =
S.fromList
[ toSqlKey 1,
toSqlKey 2
]
actualBackupsToDelete = decideBackupsToDelete (t 2022 01 05) periods backups
in actualBackupsToDelete `shouldBe` expectedBackupsToDelete
it "works with this single example" $
let t y m d = UTCTime (fromGregorian y m d) 0
periods =
[ (nominalDay * 3, 2)
]
backups =
< -- keeping this one
< -- keeping this one
(toSqlKey 3, t 2022 01 03)
]
expectedBackupsToDelete =
S.fromList
[ toSqlKey 1
]
actualBackupsToDelete = decideBackupsToDelete (t 2022 01 04) periods backups
in actualBackupsToDelete `shouldBe` expectedBackupsToDelete
it "works on this example" $
let t y m d = UTCTime (fromGregorian y m d) 0
periods =
[ (nominalDay * 2, 1),
(nominalDay * 7, 1),
(nominalDay * 14, 1),
(nominalDay * 30, 1)
]
backups =
[ (toSqlKey 1, t 2022 01 01),
(toSqlKey 2, t 2022 01 02),
< - keep this one
(toSqlKey 4, t 2022 01 04),
(toSqlKey 5, t 2022 01 05),
(toSqlKey 6, t 2022 01 06),
(toSqlKey 7, t 2022 01 07),
(toSqlKey 8, t 2022 01 08),
(toSqlKey 9, t 2022 01 09),
(toSqlKey 10, t 2022 01 10),
(toSqlKey 11, t 2022 01 11),
(toSqlKey 12, t 2022 01 12),
(toSqlKey 13, t 2022 01 13),
(toSqlKey 14, t 2022 01 14),
(toSqlKey 15, t 2022 01 15),
(toSqlKey 16, t 2022 01 16),
(toSqlKey 17, t 2022 01 17),
(toSqlKey 18, t 2022 01 18),
< - keep this one
(toSqlKey 20, t 2022 01 20),
(toSqlKey 21, t 2022 01 21),
(toSqlKey 22, t 2022 01 22),
(toSqlKey 23, t 2022 01 23),
(toSqlKey 24, t 2022 01 24),
(toSqlKey 25, t 2022 01 25),
< - keep this one
(toSqlKey 27, t 2022 01 27),
(toSqlKey 28, t 2022 01 28),
(toSqlKey 29, t 2022 01 29),
(toSqlKey 30, t 2022 01 30),
< -- keeping this one
]
expectedBackupsToKeep =
S.fromList
[ toSqlKey 3,
toSqlKey 19,
toSqlKey 26,
toSqlKey 31
]
actualBackupsToDelete = decideBackupsToDelete (t 2022 02 01) periods backups
actualBackupsToKeep = S.fromList (map fst backups) `S.difference` actualBackupsToDelete
in actualBackupsToKeep `shouldBe` expectedBackupsToKeep
iterationSpec
data S = S
{ sDateTime :: !UTCTime,
sNextBackupId :: !BackupId,
sBackups :: !(Set (BackupId, UTCTime))
}
deriving (Show)
beginState :: Day -> S
beginState d =
S
{ sDateTime = UTCTime d 0,
sNextBackupId = toSqlKey 0,
sBackups = S.empty
}
nextTime :: NominalDiffTime -> State S ()
nextTime diff = modify $ \s -> s {sDateTime = addUTCTime diff $ sDateTime s}
nextBackupId :: State S BackupId
nextBackupId = do
next <- gets sNextBackupId
modify $ \s -> s {sNextBackupId = toSqlKey $ succ $ fromSqlKey $ sNextBackupId s}
pure next
makeBackup :: State S ()
makeBackup = do
dateTime <- gets sDateTime
next <- nextBackupId
modify $ \s ->
s
{ sBackups =
S.insert
(next, dateTime)
(sBackups s)
}
collectGarbage :: [(NominalDiffTime, Word)] -> State S ()
collectGarbage periods = modify $ \s ->
s
{ sBackups =
let backups = S.toList $ sBackups s
backupsToKeep = decideBackupsToKeep (sDateTime s) periods backups
in S.filter (\(bid, _) -> bid `S.member` backupsToKeep) (sBackups s)
}
iteration :: NominalDiffTime -> [(NominalDiffTime, Word)] -> State S ()
iteration diff periods = do
nextTime diff
makeBackup
collectGarbage periods
iterationSpec :: Spec
iterationSpec = do
it "works with iterations when keeping 3 backups in the last 3 days" $ do
let endState =
flip execState (beginState (fromGregorian 2022 01 30)) $
replicateM_ 9 $ iteration nominalDay [(nominalDay * 3, 3)]
let b :: Int64 -> Int -> (BackupId, UTCTime)
b i d = (toSqlKey i, UTCTime (fromGregorian 2022 02 d) 0)
sBackups endState
`shouldBe` S.fromList
[ b 6 06,
b 7 07,
b 8 08
]
it "works with iterations when keeping a backup every other day and one per 4 days" $ do
let endState =
flip execState (beginState (fromGregorian 2022 01 30)) $
replicateM_ 12 $
iteration
nominalDay
[ (nominalDay * 2, 1),
(nominalDay * 4, 1)
]
let b :: Int64 -> Int -> (BackupId, UTCTime)
b i d = (toSqlKey i, UTCTime (fromGregorian 2022 02 d) 0)
sBackups endState
`shouldBe` S.fromList
[ b 8 08,
b 10 10
]
it "works with the default period for a day" $ do
let endState =
flip execState (beginState (fromGregorian 2022 05 27)) $
replicateM_ 23 $
iteration
3600 -- Backup every hour
defaultPeriods
let b :: Int64 -> Int -> (BackupId, UTCTime)
b i h = (toSqlKey i, UTCTime (fromGregorian 2022 05 27) (fromIntegral (h * 3600)))
sBackups endState
`shouldBe` S.fromList
[ b 0 01,
b 6 07,
b 12 13,
b 18 19,
b 19 20,
b 20 21,
b 21 22,
b 22 23
]
it "works with the default period for a year" $ do
let endState =
flip execState (beginState (fromGregorian 2022 01 01)) $
replicateM_ (365 * 24 - 1) $
iteration
3600 -- Backup every hour
defaultPeriods
let b :: Int64 -> Int -> Int -> Int -> (BackupId, UTCTime)
b i m d h = (toSqlKey i, UTCTime (fromGregorian 2022 m d) (fromIntegral (h * 3600)))
sBackups endState
`shouldBe` S.fromList
[ b 0000 01 01 01,
b 0840 02 05 01,
b 1680 03 12 01,
b 2520 04 16 01,
b 3360 05 21 01,
b 4200 06 25 01,
b 5040 07 30 01,
b 5880 09 03 01,
b 6720 10 08 01,
b 7392 11 05 01,
b 7560 11 12 01,
b 7728 11 19 01,
b 7896 11 26 01,
b 8064 12 03 01,
b 8232 12 10 01,
b 8400 12 17 01,
b 8568 12 24 01,
b 8592 12 25 01,
b 8616 12 26 01,
b 8640 12 27 01,
b 8664 12 28 01,
b 8688 12 29 01,
b 8712 12 30 01,
b 8736 12 31 01,
b 8742 12 31 07,
b 8748 12 31 13,
b 8754 12 31 19,
b 8755 12 31 20,
b 8756 12 31 21,
b 8757 12 31 22,
b 8758 12 31 23
]
| null | https://raw.githubusercontent.com/NorfairKing/smos/41d5ba29be87ce5c224d4b33790809a4528f81e3/smos-server-gen/test/Smos/Server/Looper/BackupGarbageCollectorSpec.hs | haskell | keeping this one
keeping this one
keeping this one
keeping this one
keeping this one
keeping this one
Backup every hour
Backup every hour | module Smos.Server.Looper.BackupGarbageCollectorSpec where
import Control.Monad
import Control.Monad.State.Strict
import Data.GenValidity.Persist ()
import Data.Int
import Data.Set (Set)
import qualified Data.Set as S
import Data.Time
import Database.Persist.Sql
import Smos.Server.DB
import Smos.Server.Gen ()
import Smos.Server.Looper.BackupGarbageCollector
import Test.Syd
import Test.Syd.Validity
spec :: Spec
spec = do
describe "decideBackupsToDelete" $ do
it "only ever selects backups to delete, from the list" $
forAllValid $ \now ->
forAllValid $ \backups ->
let backupsToDelete = decideBackupsToDelete now defaultPeriods backups
ids = S.fromList $ map fst backups
in shouldSatisfyNamed
backupsToDelete
("`S.isSubsetOf` " <> show ids)
(`S.isSubsetOf` ids)
it "works with this single interval where a backup falls outside the interval" $
let t y m d = UTCTime (fromGregorian y m d) 0
periods =
[ (nominalDay * 3, 3)
]
backups =
[ (toSqlKey 1, t 2022 01 01),
(toSqlKey 2, t 2022 01 02),
]
expectedBackupsToDelete =
S.fromList
[ toSqlKey 1,
toSqlKey 2
]
actualBackupsToDelete = decideBackupsToDelete (t 2022 01 05) periods backups
in actualBackupsToDelete `shouldBe` expectedBackupsToDelete
it "works with this single example" $
let t y m d = UTCTime (fromGregorian y m d) 0
periods =
[ (nominalDay * 3, 2)
]
backups =
(toSqlKey 3, t 2022 01 03)
]
expectedBackupsToDelete =
S.fromList
[ toSqlKey 1
]
actualBackupsToDelete = decideBackupsToDelete (t 2022 01 04) periods backups
in actualBackupsToDelete `shouldBe` expectedBackupsToDelete
it "works on this example" $
let t y m d = UTCTime (fromGregorian y m d) 0
periods =
[ (nominalDay * 2, 1),
(nominalDay * 7, 1),
(nominalDay * 14, 1),
(nominalDay * 30, 1)
]
backups =
[ (toSqlKey 1, t 2022 01 01),
(toSqlKey 2, t 2022 01 02),
< - keep this one
(toSqlKey 4, t 2022 01 04),
(toSqlKey 5, t 2022 01 05),
(toSqlKey 6, t 2022 01 06),
(toSqlKey 7, t 2022 01 07),
(toSqlKey 8, t 2022 01 08),
(toSqlKey 9, t 2022 01 09),
(toSqlKey 10, t 2022 01 10),
(toSqlKey 11, t 2022 01 11),
(toSqlKey 12, t 2022 01 12),
(toSqlKey 13, t 2022 01 13),
(toSqlKey 14, t 2022 01 14),
(toSqlKey 15, t 2022 01 15),
(toSqlKey 16, t 2022 01 16),
(toSqlKey 17, t 2022 01 17),
(toSqlKey 18, t 2022 01 18),
< - keep this one
(toSqlKey 20, t 2022 01 20),
(toSqlKey 21, t 2022 01 21),
(toSqlKey 22, t 2022 01 22),
(toSqlKey 23, t 2022 01 23),
(toSqlKey 24, t 2022 01 24),
(toSqlKey 25, t 2022 01 25),
< - keep this one
(toSqlKey 27, t 2022 01 27),
(toSqlKey 28, t 2022 01 28),
(toSqlKey 29, t 2022 01 29),
(toSqlKey 30, t 2022 01 30),
]
expectedBackupsToKeep =
S.fromList
[ toSqlKey 3,
toSqlKey 19,
toSqlKey 26,
toSqlKey 31
]
actualBackupsToDelete = decideBackupsToDelete (t 2022 02 01) periods backups
actualBackupsToKeep = S.fromList (map fst backups) `S.difference` actualBackupsToDelete
in actualBackupsToKeep `shouldBe` expectedBackupsToKeep
iterationSpec
data S = S
{ sDateTime :: !UTCTime,
sNextBackupId :: !BackupId,
sBackups :: !(Set (BackupId, UTCTime))
}
deriving (Show)
beginState :: Day -> S
beginState d =
S
{ sDateTime = UTCTime d 0,
sNextBackupId = toSqlKey 0,
sBackups = S.empty
}
nextTime :: NominalDiffTime -> State S ()
nextTime diff = modify $ \s -> s {sDateTime = addUTCTime diff $ sDateTime s}
nextBackupId :: State S BackupId
nextBackupId = do
next <- gets sNextBackupId
modify $ \s -> s {sNextBackupId = toSqlKey $ succ $ fromSqlKey $ sNextBackupId s}
pure next
makeBackup :: State S ()
makeBackup = do
dateTime <- gets sDateTime
next <- nextBackupId
modify $ \s ->
s
{ sBackups =
S.insert
(next, dateTime)
(sBackups s)
}
collectGarbage :: [(NominalDiffTime, Word)] -> State S ()
collectGarbage periods = modify $ \s ->
s
{ sBackups =
let backups = S.toList $ sBackups s
backupsToKeep = decideBackupsToKeep (sDateTime s) periods backups
in S.filter (\(bid, _) -> bid `S.member` backupsToKeep) (sBackups s)
}
iteration :: NominalDiffTime -> [(NominalDiffTime, Word)] -> State S ()
iteration diff periods = do
nextTime diff
makeBackup
collectGarbage periods
iterationSpec :: Spec
iterationSpec = do
it "works with iterations when keeping 3 backups in the last 3 days" $ do
let endState =
flip execState (beginState (fromGregorian 2022 01 30)) $
replicateM_ 9 $ iteration nominalDay [(nominalDay * 3, 3)]
let b :: Int64 -> Int -> (BackupId, UTCTime)
b i d = (toSqlKey i, UTCTime (fromGregorian 2022 02 d) 0)
sBackups endState
`shouldBe` S.fromList
[ b 6 06,
b 7 07,
b 8 08
]
it "works with iterations when keeping a backup every other day and one per 4 days" $ do
let endState =
flip execState (beginState (fromGregorian 2022 01 30)) $
replicateM_ 12 $
iteration
nominalDay
[ (nominalDay * 2, 1),
(nominalDay * 4, 1)
]
let b :: Int64 -> Int -> (BackupId, UTCTime)
b i d = (toSqlKey i, UTCTime (fromGregorian 2022 02 d) 0)
sBackups endState
`shouldBe` S.fromList
[ b 8 08,
b 10 10
]
it "works with the default period for a day" $ do
let endState =
flip execState (beginState (fromGregorian 2022 05 27)) $
replicateM_ 23 $
iteration
defaultPeriods
let b :: Int64 -> Int -> (BackupId, UTCTime)
b i h = (toSqlKey i, UTCTime (fromGregorian 2022 05 27) (fromIntegral (h * 3600)))
sBackups endState
`shouldBe` S.fromList
[ b 0 01,
b 6 07,
b 12 13,
b 18 19,
b 19 20,
b 20 21,
b 21 22,
b 22 23
]
it "works with the default period for a year" $ do
let endState =
flip execState (beginState (fromGregorian 2022 01 01)) $
replicateM_ (365 * 24 - 1) $
iteration
defaultPeriods
let b :: Int64 -> Int -> Int -> Int -> (BackupId, UTCTime)
b i m d h = (toSqlKey i, UTCTime (fromGregorian 2022 m d) (fromIntegral (h * 3600)))
sBackups endState
`shouldBe` S.fromList
[ b 0000 01 01 01,
b 0840 02 05 01,
b 1680 03 12 01,
b 2520 04 16 01,
b 3360 05 21 01,
b 4200 06 25 01,
b 5040 07 30 01,
b 5880 09 03 01,
b 6720 10 08 01,
b 7392 11 05 01,
b 7560 11 12 01,
b 7728 11 19 01,
b 7896 11 26 01,
b 8064 12 03 01,
b 8232 12 10 01,
b 8400 12 17 01,
b 8568 12 24 01,
b 8592 12 25 01,
b 8616 12 26 01,
b 8640 12 27 01,
b 8664 12 28 01,
b 8688 12 29 01,
b 8712 12 30 01,
b 8736 12 31 01,
b 8742 12 31 07,
b 8748 12 31 13,
b 8754 12 31 19,
b 8755 12 31 20,
b 8756 12 31 21,
b 8757 12 31 22,
b 8758 12 31 23
]
|
bc7445210e1f02ae0d6d6c4ec2b32f6f63c4caa5584c3ea6baa049a8947a015e | mfey/units2 | ops.clj | ;; Mathy operations on the (generically defined) `units2.core.amount` type.
;; This implementation assumes:
;;
1 . that the values in ` amount ` , and any other numbers , are well - behaved under ` clojure.core/fns ` and ` Math / fns `
;; 2. that the units in `amount` are `Multiplicative`.
;; 3. that the units in `amount` are all linear rescalings without any `offset`.
;; (There are a few offset checks scattered throughout,
;; so offsets *usually* work, but there are no overall guarantees.)
;;
;; As such, it should be fairly easy to reuse most of this code for other implementations if
;; the provided decorators aren't good enough.
# #
;;
1 . The ops we define here are fine with ` require : refer : all ` , they reduce to their ` clojure.core/ ` and ` Math/ ` counterparts on non-`amount ? ` quantities .
;; 2. When standard functions would give surprising behaviour in combination with units, users might inadvertently write buggy code. We provide a version of the function that issues an Exception whenever it is used on units (to force the user to think about the behaviour they want).
3 . For many ops , we also provide a standardised augmented - arity version that uses divide - into - double on the first two args
< pre><code > ; ; these two expressions are equivalent
;; (pow a b c)
;; (Math/pow (divide-into-double a b) c)
;; </code></pre>
;; 4. The spec'd functions below have been *generatively tested*.
(ns units2.ops
redefinitions imminent ! ` : exclude ` turns off some WARNINGS .
(:refer-clojure :exclude [+ - * / rem quot == > >= < <= zero? pos? neg? min max])
(:require [units2.core :refer :all]
[clojure.spec.alpha :as spec]
[clojure.spec.gen.alpha :as gen])
)
;; ## Specs
(spec/def ::number-or-amount (spec/or :number number? :amount :units2.core/amount))
(spec/def ::compatible-amounts
(spec/and
(spec/* :units2.core/amount)
(fn [amountlist] ;; it's really the conformed value here, but for amounts it's the same thing!
(if (clojure.core/< (count amountlist) 2)
true ; obvious if
(every? #(compatible? (getUnit (first amountlist)) (getUnit %)) (rest amountlist))))))
(spec/def ::numbers-or-compatible-amounts
(spec/or :all-numbers (spec/* number?)
:all-amounts ::compatible-amounts))
(spec/def ::some-numbers-or-compatible-amounts
(spec/and ::numbers-or-compatible-amounts
#(not (empty? (spec/unform ::numbers-or-compatible-amounts %)))))
(spec/def ::linear-units
(spec/and ::compatible-amounts
(fn [amountlist] ;; it's really the conformed value here, but for amounts it's the same thing!
(if (clojure.core/< (count amountlist) 2)
true ; obvious if
(every?
#(linear? (getConverter (getUnit (first amountlist)) (getUnit %)))
(rest amountlist))))))
(spec/def ::nonzero-amount
(spec/and :units2.core/amount
#(not (clojure.core/zero? (getValue % (getUnit %))))))
(spec/def ::two-linear-units-second-nonzero
(spec/and (spec/coll-of :units2.core/amount :count 2)
::linear-units
#(spec/valid? ::nonzero-amount (second %))))
# # Arithmetic
# # # Dispatch helper macros ( possible code smell ... use instead ? )
;; dispatch for + and -
(defmacro ^:private threecond [[a b] both one neither]
`(cond
(and (amount? ~a) (amount? ~b)) ~both
(or (amount? ~a) (amount? ~b)) ~one
true ~neither))
;; dispatch for + and - with a check that the conversion is linear
(defmacro ^:private lincond [[a b] lin nonlin one neither]
`(threecond [~a ~b]
(if (linear? (getConverter (getUnit ~a) (getUnit ~b)))
~lin
~nonlin)
~one
~neither))
;; dispatch for * and /
(defmacro ^:private fourcond [[a b] one two three four]
`(cond
(and (amount? ~a) (amount? ~b)) ~one
(and (amount? ~a) (not (amount? ~b))) ~two
(and (amount? ~b) (not (amount? ~a))) ~three
(not (or (amount? ~a) (amount? ~b))) ~four))
# # # Abstract Algebra of Units in Arithmetic
(defn decorate-adder [adder]
(fn decorated-adder
([] (adder)) ; same return value as the original
([a] (if (amount? a)
(->amount (adder (getValue a (getUnit a))) (getUnit a))
(adder a)))
([a b]
(lincond [a b]
(->amount (adder (getValue a (getUnit a)) (getValue b (getUnit a))) (getUnit a))
(throw (UnsupportedOperationException. (str "Nonlinear conversion between `" (getUnit a) "' and `" (getUnit b)"'!")))
(throw (UnsupportedOperationException. (str "It's meaningless to apply" (str adder) " to numbers with and without units! (`" a "' and `" b "' provided)")))
(adder a b)))
([a b & rest] (reduce decorated-adder a (conj rest b))) ; speed of reduce vs recur?
)
)
(defn decorate-productor [productor]
(fn decorated-productor
([] (productor)) ; same return value as the original
([a] (if (amount? a)
(->amount (productor (getValue a (getUnit a))) (getUnit a))
(productor a)))
([a b] (fourcond [a b]
(->amount (productor (getValue a (getUnit a)) (getValue b (getUnit b))) (times (getUnit a) (getUnit b)))
(->amount (productor (getValue a (getUnit a)) (double b)) (getUnit a))
(->amount (productor (getValue b (getUnit b)) (double a)) (getUnit b))
(productor a b)))
([a b & rest] (reduce decorated-productor a (conj rest b))) ; speed of reduce vs recur?
)
)
(defn decorate-divider [divider]
(fn decorated-divider
zero arity explicitly an error , but let the original catch this .
([a] (if (amount? a)
(->amount (divider (getValue a (getUnit a))) (inverse (getUnit a)))
(divider a)))
([a b] (fourcond [a b]
(->amount (divider (getValue a (getUnit a)) (getValue b (getUnit b))) (divide (getUnit a) (getUnit b)))
(->amount (divider (getValue a (getUnit a)) (double b)) (getUnit a))
(->amount (divider (double a) (getValue b (getUnit b))) (inverse (getUnit b)))
(divider a b)))
([a b & rest] (reduce decorated-divider a (conj rest b))) ; speed of reduce vs recur?
)
)
# # # Concrete Arithmetic Ops ( with Specs and old docstrings )
(def ^{:doc (:doc (meta (var clojure.core/+)))} + (decorate-adder clojure.core/+))
(def ^{:doc (:doc (meta (var clojure.core/-)))} - (decorate-adder clojure.core/-))
(def ^{:doc (:doc (meta (var clojure.core/*)))} * (decorate-productor clojure.core/*))
(def ^{:doc (:doc (meta (var clojure.core//)))} / (decorate-divider clojure.core//))
(spec/fdef +
:args ::numbers-or-compatible-amounts
:ret ::number-or-amount
:fn #(if (every? number? (:args %))
(number? (:ret %))
(:units2.core/amount (:ret %)))
)
(spec/fdef -
:args ::some-numbers-or-compatible-amounts
:ret ::number-or-amount
:fn #(if (every? number? (:args %))
(number? (:ret %))
(:units2.core/amount (:ret %)))
)
(spec/fdef *
:args (spec/* (spec/or :amount :units2.core/amount :number number?))
:ret (spec/or :amount :units2.core/amount :number number?)
:fn #(if (every? number? (:args %))
(number? (:ret %))
(:units2.core/amount (:ret %)))
)
(spec/fdef /
:args (spec/and (spec/+ ::number-or-amount)
also : do n't divide by zero ! ! !
this is an unsafe version of zero ?
(if (empty? (rest x))
(not (unsafe-zero? (spec/unform ::number-or-amount (first x))))
(every? #(not (unsafe-zero? (spec/unform ::number-or-amount %))) (rest x))))))
:ret (spec/or :amount :units2.core/amount :number number?)
:fn #(if (every? number? (:args %))
(number? (:ret %))
(:units2.core/amount (:ret %)))
)
(spec/fdef divide-into-double :args ::two-linear-units-second-nonzero
:ret double?)
(defn divide-into-double
"When all units involved are linear rescalings of one another, fractions with the same dimensions in the numerator and denominator have a *unique* unit-free value.
This is basically syntactic sugar for `(getValue a (AsUnit b))` with some error checking."
^double [a b]
(if (and (amount? a)
(amount? b)
(compatible? (getUnit a) (getUnit b))
(linear? (getConverter (getUnit a) (getUnit b))))
(getValue a (AsUnit b))
(throw (IllegalArgumentException. (str "divide-into-double requires two amounts with linearly related units! (`" a "' and `" b "' provided)")))))
# # Modular Arithmetic
(let [PSA "Modular arithmetic interacts nontrivially with offsets of units."]
Modular arithmetic interacts nontrivially with rescalings of units .
;; Consider the following (incorrect) implementation:
;; <pre><code>
( let [ a ( ->amount 2.5 meter )
b ( ->amount 5 ( / meter 2 ) )
c ( ->amount 3 second ) ]
;; (list
;; (== a b) ; true
( rem a c ) ; 2.5 m / s
( rem b c ) ; 2 (
;; (== (rem a c)
( rem b c ) ) ) ) ; FALSE
;; </code></pre>
;; To avoid this, we also need to say how big the number `one' is
;; in order that these *integer* operations be well-defined.
(defn decorate-ratio [ratio]
(fn
([a b]
(if (or (amount? a) (amount? b))
(throw (UnsupportedOperationException. PSA))
(ratio a b)))
([a b c]
;; a is the numerator of the ratio
;; b is the modulus of the congruence (the denominator of the ratio)
;; c is the quantity that defines the size of `one' in this congruence
(let [U (AsUnit c)]
(->amount (ratio (getValue a U) (getValue b U)) U)))
)
)
(defn decorate-entier [entier]
(fn
([a]
(if (amount? a)
(throw (UnsupportedOperationException. PSA))
(entier a)))
treat second amount as the ` unity ' quantity , e.g. ( round ... 10 ) rounds to the nearest 10 .
(* (entier (divide-into-double a b)) b))
)
)
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/rem)))
"\n Units2 added doc: " PSA)}
rem (decorate-ratio clojure.core/rem))
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/quot)))
"\n Units2 added doc: " PSA)}
quot (decorate-ratio clojure.core/quot))
(def ^{:doc PSA} ceil (decorate-entier #(Math/ceil %)))
(def ^{:doc PSA} floor (decorate-entier #(Math/floor %)))
(def ^{:doc PSA} round (decorate-entier #(Math/round (double %)))) ; type hint
(def ^{:doc PSA} abs (decorate-entier #(cond (int? %) (Math/abs (int %))
(double? %) (Math/abs (double %))))) ; funny type hint
)
; specs here can probably be a bit "tighter", but I'm happy with this.
(spec/fdef rem :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret number?)
(spec/fdef quot :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret number?)
(spec/fdef ceil :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret double?)
(spec/fdef floor :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret double?)
(spec/fdef round :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret int?)
(spec/fdef abs :args (spec/or :one number? :bin ::two-linear-units-second-nonzero)
:ret (spec/and clojure.core/pos? (spec/or :int int? :double double?)))
# # Comparisons
;; Defining `==` , `>=`, or `<` seems easy; but the desired behaviour for
;; comparisons of incompatible units could be either to return false or
;; throw an exception; we opt for the latter, since strictly speaking
` is 3 meters smaller than 5 seconds ? ' is a meaningless question and
;; shouldn't be given a boolean answer; consider for a moment the alternate
;; behaviour, which violates the excluded-middle-law:
;; <pre><code> ;; this is ugly!
( not ( < ( m 4 ) ( celcius 6 ) ) ; ; not
( > = ( m 4 ) ( celcius 6 ) ) ; ;
;; </code></pre>
;;
;; The behaviour for `==` could be different than other comparators,
since e.g. 3 meters and 5 seconds are never the same amount ; but
;; consistently throwing exceptions seems like the safer route.
(defn decorate-comparator [cmp]
(fn decorated-comparator [& args]
(cond
(empty? args) (cmp)
(every? #(not (amount? %)) args)
(apply cmp args)
(every? amount? args)
(if (every? #(compatible? (getUnit (first args)) %) (map getUnit (rest args)))
(apply cmp (map (from (getUnit (first args))) args))
(throw (UnsupportedOperationException. (str "Can't compare quantities in incompatible units! (" args " provided)"))))
:else
(throw (UnsupportedOperationException. (str "Can't compare quantities with and without units! (" args " provided)")))
)
)
)
(def ^{:doc (:doc (meta (var clojure.core/==)))} == (decorate-comparator clojure.core/==))
(def ^{:doc (:doc (meta (var clojure.core/< )))} < (decorate-comparator clojure.core/<))
(def ^{:doc (:doc (meta (var clojure.core/> )))} > (decorate-comparator clojure.core/>))
(def ^{:doc (:doc (meta (var clojure.core/<=)))} <= (decorate-comparator clojure.core/<=))
(def ^{:doc (:doc (meta (var clojure.core/>=)))} >= (decorate-comparator clojure.core/>=))
(spec/fdef == :args ::some-numbers-or-compatible-amounts :ret boolean?)
(spec/fdef < :args ::some-numbers-or-compatible-amounts :ret boolean?)
(spec/fdef > :args ::some-numbers-or-compatible-amounts :ret boolean?)
(spec/fdef <= :args ::some-numbers-or-compatible-amounts :ret boolean?)
(spec/fdef >= :args ::some-numbers-or-compatible-amounts :ret boolean?)
(let [PSA "Sign checks interact nontrivially with offsets of units.\n Please use explicit `==`,`>`,`<` checks against a zero-valued quantity."]
` zero ? ` , ` pos ? ` , and ` neg ? ` can return different answers depending on the input units
( to see why , consider the and Celius temperature scales )
(defn decorate-sign-predicate [pred]
(fn [a]
(if (amount? a)
(throw (UnsupportedOperationException. PSA))
(pred a))))
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/zero?)))
"\n Units2 added doc: " PSA)}
zero? (decorate-sign-predicate clojure.core/zero?))
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/pos?)))
"\n Units2 added doc: " PSA)}
pos? (decorate-sign-predicate clojure.core/pos?))
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/neg?)))
"\n Units2 added doc: " PSA)}
neg? (decorate-sign-predicate clojure.core/neg?))
)
(spec/fdef zero? :args number? :ret boolean?)
(spec/fdef pos? :args number? :ret boolean?)
(spec/fdef neg? :args number? :ret boolean?)
(defn decorate-order-statistic [ord]
(fn decorated-order-statistic [& nums]
(cond
(empty? nums)
(ord)
(every? #(not (amount? %)) nums)
(apply ord nums)
(every? amount? nums)
(if (every? #(compatible? (getUnit (first nums)) (getUnit %)) (rest nums))
(let [U (getUnit (first nums))]
(->amount (apply ord (map (from U) nums)) U))
(throw (UnsupportedOperationException. (str "Can't order dimensionally incompatible quantities! (" nums " provided)"))))
:else
(throw (UnsupportedOperationException. (str "Can't order quantities with and without units! (" nums " provided)")))
)
)
)
(def ^{:doc (:doc (meta (var clojure.core/min)))} min (decorate-order-statistic clojure.core/min))
(def ^{:doc (:doc (meta (var clojure.core/max)))} max (decorate-order-statistic clojure.core/max))
(spec/fdef max :args ::some-numbers-or-compatible-amounts
:ret ::number-or-amount)
(spec/fdef min :args ::some-numbers-or-compatible-amounts
:ret ::number-or-amount)
# # Powers and Exponentiation
(spec/fdef expt :args (spec/and (spec/tuple :units2.core/amount integer?)
(fn [[base exponent]]
(if (<= 0 exponent)
true
(spec/valid? ::nonzero-amount base))))
:ret :units2.core/amount)
(defn expt
"`(expt b n) == b^n`
where `n` is a rational number and `b` is an amount. Also includes functionality of a root function since `(root x N)` <=> `(expt x (/ N))`
"
[b n]
(->amount (Math/pow (getValue b (getUnit b)) n) (power (getUnit b) n)))
(let [PSA "Exponentiation interacts nontrivially with rescalings of units."]
;; The exponential functions below should only be defined on dimensionless quantities
( to see why , just imagine - expanding the ` exp ` or ` ln ` functions )
so we define them over ratios of amounts : / b ) , sqrt(a / b ) , etc .
(defn decorate-expt [expt]
(fn
([a]
(if (amount? a)
(throw (UnsupportedOperationException. PSA))
(expt a)))
([a b]
(if (every? amount? [a b])
(expt (divide-into-double a b))
(throw (IllegalArgumentException. (str "Arity-2 exponentiation requires two amounts! (" a " and " b " provided)")))
))))
(def ^{:doc PSA} exp (decorate-expt #(Math/exp %)))
(def ^{:doc PSA} log (decorate-expt #(Math/log %)))
(def ^{:doc PSA} log10 (decorate-expt #(Math/log10 %)))
(def ^{:doc PSA} sqrt (decorate-expt #(Math/sqrt %)))
)
; specs separately (function ranges)
(spec/fdef exp :args (spec/or :one number?
:bin ::two-linear-units-second-nonzero)
:ret (spec/and clojure.core/pos? double?))
(spec/fdef log :args (spec/or :one (spec/and clojure.core/pos? number?)
:bin (spec/and ::two-linear-units-second-nonzero
#(clojure.core/pos? (divide-into-double (first %) (second %)))))
:ret double?)
(spec/fdef log10 :args (spec/or :one (spec/and clojure.core/pos? number?)
:bin (spec/and ::two-linear-units-second-nonzero
#(clojure.core/pos? (divide-into-double (first %) (second %)))))
:ret double?)
(spec/fdef sqrt :args (spec/or :one (spec/and clojure.core/pos? number?)
:bin (spec/and ::two-linear-units-second-nonzero
#(clojure.core/pos? (divide-into-double (first %) (second %)))))
:ret (spec/and clojure.core/pos? double?))
(spec/fdef pow :args (spec/or :bin (spec/tuple number? number?)
:tri ;(spec/with-gen
(spec/and (spec/tuple :units2.core/amount :units2.core/amount number?)
(fn [[a b _]] (spec/valid? ::two-linear-units-second-nonzero [a b])))
( fn [ ] ( gen / cat ( spec / gen : : two - linear - units - second - nonzero )
; (gen/fmap list (gen/gen-for-pred number?)))))
)
:ret double?)
(defn pow
"Also includes functionality of a root function since `(root x N)` <=> `(pow x (/ N))`"
([a b]
(fourcond [a b]
(throw (IllegalArgumentException. (str "`pow` can't deal with the provided arguments (" a " and " b " provided). Maybe you want to provide a third number without units?")))
(throw (IllegalArgumentException. (str "`pow` can't deal with the provided arguments (" a " and " b " provided). Maybe you want to call the `expt` function instead?")))
(throw (IllegalArgumentException. (str "Can't use a dimensionful quantity as an exponent (" b " provided).")))
(Math/pow a b)))
([a b c]
(if (and (amount? a) (amount? b) (compatible? (getUnit a) (getUnit b)) (not (amount? c)))
(Math/pow (divide-into-double a b) c)
(throw (IllegalArgumentException. (str "Arity-3 `pow` requires two compatible amounts and a number! (" a ", " b ", and " c " provided)"))))))
# # EVERYTHING TOGETHER
(defmacro ^:private defmacro-without-hygiene
"Expands into a `defmacro` with a `(let [bindings] body)` that gets
around Clojure's automatic namespacing in syntax-quote by building
the `let` form explicitly. Macros can be dangerous. Have fun!!!!"
[macroname docstring bindings]
(let [body (gensym)]
`(defmacro ~macroname ~docstring [& ~body]
(clojure.core/conj ~body '~bindings 'clojure.core/let))))
14/03/16 : Thanks to the ` Amsterdam Clojurians ` for noticing that ` conj ` should be ` clojure.core/conj ` in the above ,
;; with the comment "If you're willing to do that, you should be prepared for users willing to define their own `conj`."
(defmacro-without-hygiene with-unit-arithmetic
"Locally rebind arithmetic operators like `+`, and `/` to unit-aware equivalents."
[+ units2.ops/+
- units2.ops/-
* units2.ops/*
/ units2.ops//
quot units2.ops/quot
rem units2.ops/rem
])
(defmacro-without-hygiene with-unit-comparisons
"Locally rebind `==`, `>=`, `<`, `zero?`, `pos?`, `min`, ... to unit-aware equivalents."
[== units2.ops/==
> units2.ops/>
< units2.ops/<
>= units2.ops/>=
<= units2.ops/<=
zero? units2.ops/zero?
pos? units2.ops/pos?
neg? units2.ops/neg?
min units2.ops/min
max units2.ops/max
])
(defmacro-without-hygiene with-unit-expts
"Locally bind exponentiation functions to unit-aware equivalents."
[expt units2.ops/expt
exp units2.ops/exp
sqrt units2.ops/sqrt
pow units2.ops/pow
log units2.ops/log
log10 units2.ops/log10
])
(defmacro-without-hygiene with-unit-magnitudes ;; THIS IS A BAD NAME. FIND A BETTER NAME.
"Locally bind magnitude functions to unit-aware equivalents."
[abs units2.ops/abs
floor units2.ops/floor
ceil units2.ops/ceil
round units2.ops/round
])
(defmacro with-unit-
[labels & body] ; each of these expressions is used only once
(let [keywords {:arithmetic '[units2.ops/with-unit-arithmetic]
:expt '[units2.ops/with-unit-expts]
:magn '[units2.ops/with-unit-magnitudes]
:math '[units2.ops/with-unit-arithmetic
units2.ops/with-unit-expts]
:comp '[units2.ops/with-unit-comparisons]
:all '[units2.ops/with-unit-arithmetic
units2.ops/with-unit-expts
units2.ops/with-unit-comparisons
units2.ops/with-unit-magnitudes
]
}
; figure out which set of environments to use given the keywords
; we assume all envs are commutative, i.e. the set need not be ordered.
envs (remove nil? (set (flatten (map keywords labels))))]
; then right-fold the environment macros over the body, and give that as the form to evaluate
(reduce #(list %2 %1) `(do ~@body) envs)))
| null | https://raw.githubusercontent.com/mfey/units2/16630eab5a7d618216ee2713eb88b75bb6ae5000/src/units2/ops.clj | clojure | Mathy operations on the (generically defined) `units2.core.amount` type.
This implementation assumes:
2. that the units in `amount` are `Multiplicative`.
3. that the units in `amount` are all linear rescalings without any `offset`.
(There are a few offset checks scattered throughout,
so offsets *usually* work, but there are no overall guarantees.)
As such, it should be fairly easy to reuse most of this code for other implementations if
the provided decorators aren't good enough.
2. When standard functions would give surprising behaviour in combination with units, users might inadvertently write buggy code. We provide a version of the function that issues an Exception whenever it is used on units (to force the user to think about the behaviour they want).
; these two expressions are equivalent
(pow a b c)
(Math/pow (divide-into-double a b) c)
</code></pre>
4. The spec'd functions below have been *generatively tested*.
## Specs
it's really the conformed value here, but for amounts it's the same thing!
obvious if
it's really the conformed value here, but for amounts it's the same thing!
obvious if
dispatch for + and -
dispatch for + and - with a check that the conversion is linear
dispatch for * and /
same return value as the original
speed of reduce vs recur?
same return value as the original
speed of reduce vs recur?
speed of reduce vs recur?
Consider the following (incorrect) implementation:
<pre><code>
(list
(== a b) ; true
2.5 m / s
2 (
(== (rem a c)
FALSE
</code></pre>
To avoid this, we also need to say how big the number `one' is
in order that these *integer* operations be well-defined.
a is the numerator of the ratio
b is the modulus of the congruence (the denominator of the ratio)
c is the quantity that defines the size of `one' in this congruence
type hint
funny type hint
specs here can probably be a bit "tighter", but I'm happy with this.
Defining `==` , `>=`, or `<` seems easy; but the desired behaviour for
comparisons of incompatible units could be either to return false or
throw an exception; we opt for the latter, since strictly speaking
shouldn't be given a boolean answer; consider for a moment the alternate
behaviour, which violates the excluded-middle-law:
<pre><code> ;; this is ugly!
; not
;
</code></pre>
The behaviour for `==` could be different than other comparators,
but
consistently throwing exceptions seems like the safer route.
The exponential functions below should only be defined on dimensionless quantities
specs separately (function ranges)
(spec/with-gen
(gen/fmap list (gen/gen-for-pred number?)))))
with the comment "If you're willing to do that, you should be prepared for users willing to define their own `conj`."
THIS IS A BAD NAME. FIND A BETTER NAME.
each of these expressions is used only once
figure out which set of environments to use given the keywords
we assume all envs are commutative, i.e. the set need not be ordered.
then right-fold the environment macros over the body, and give that as the form to evaluate |
1 . that the values in ` amount ` , and any other numbers , are well - behaved under ` clojure.core/fns ` and ` Math / fns `
# #
1 . The ops we define here are fine with ` require : refer : all ` , they reduce to their ` clojure.core/ ` and ` Math/ ` counterparts on non-`amount ? ` quantities .
3 . For many ops , we also provide a standardised augmented - arity version that uses divide - into - double on the first two args
(ns units2.ops
redefinitions imminent ! ` : exclude ` turns off some WARNINGS .
(:refer-clojure :exclude [+ - * / rem quot == > >= < <= zero? pos? neg? min max])
(:require [units2.core :refer :all]
[clojure.spec.alpha :as spec]
[clojure.spec.gen.alpha :as gen])
)
(spec/def ::number-or-amount (spec/or :number number? :amount :units2.core/amount))
(spec/def ::compatible-amounts
(spec/and
(spec/* :units2.core/amount)
(if (clojure.core/< (count amountlist) 2)
(every? #(compatible? (getUnit (first amountlist)) (getUnit %)) (rest amountlist))))))
(spec/def ::numbers-or-compatible-amounts
(spec/or :all-numbers (spec/* number?)
:all-amounts ::compatible-amounts))
(spec/def ::some-numbers-or-compatible-amounts
(spec/and ::numbers-or-compatible-amounts
#(not (empty? (spec/unform ::numbers-or-compatible-amounts %)))))
(spec/def ::linear-units
(spec/and ::compatible-amounts
(if (clojure.core/< (count amountlist) 2)
(every?
#(linear? (getConverter (getUnit (first amountlist)) (getUnit %)))
(rest amountlist))))))
(spec/def ::nonzero-amount
(spec/and :units2.core/amount
#(not (clojure.core/zero? (getValue % (getUnit %))))))
(spec/def ::two-linear-units-second-nonzero
(spec/and (spec/coll-of :units2.core/amount :count 2)
::linear-units
#(spec/valid? ::nonzero-amount (second %))))
# # Arithmetic
# # # Dispatch helper macros ( possible code smell ... use instead ? )
(defmacro ^:private threecond [[a b] both one neither]
`(cond
(and (amount? ~a) (amount? ~b)) ~both
(or (amount? ~a) (amount? ~b)) ~one
true ~neither))
(defmacro ^:private lincond [[a b] lin nonlin one neither]
`(threecond [~a ~b]
(if (linear? (getConverter (getUnit ~a) (getUnit ~b)))
~lin
~nonlin)
~one
~neither))
(defmacro ^:private fourcond [[a b] one two three four]
`(cond
(and (amount? ~a) (amount? ~b)) ~one
(and (amount? ~a) (not (amount? ~b))) ~two
(and (amount? ~b) (not (amount? ~a))) ~three
(not (or (amount? ~a) (amount? ~b))) ~four))
# # # Abstract Algebra of Units in Arithmetic
(defn decorate-adder [adder]
(fn decorated-adder
([a] (if (amount? a)
(->amount (adder (getValue a (getUnit a))) (getUnit a))
(adder a)))
([a b]
(lincond [a b]
(->amount (adder (getValue a (getUnit a)) (getValue b (getUnit a))) (getUnit a))
(throw (UnsupportedOperationException. (str "Nonlinear conversion between `" (getUnit a) "' and `" (getUnit b)"'!")))
(throw (UnsupportedOperationException. (str "It's meaningless to apply" (str adder) " to numbers with and without units! (`" a "' and `" b "' provided)")))
(adder a b)))
)
)
(defn decorate-productor [productor]
(fn decorated-productor
([a] (if (amount? a)
(->amount (productor (getValue a (getUnit a))) (getUnit a))
(productor a)))
([a b] (fourcond [a b]
(->amount (productor (getValue a (getUnit a)) (getValue b (getUnit b))) (times (getUnit a) (getUnit b)))
(->amount (productor (getValue a (getUnit a)) (double b)) (getUnit a))
(->amount (productor (getValue b (getUnit b)) (double a)) (getUnit b))
(productor a b)))
)
)
(defn decorate-divider [divider]
(fn decorated-divider
zero arity explicitly an error , but let the original catch this .
([a] (if (amount? a)
(->amount (divider (getValue a (getUnit a))) (inverse (getUnit a)))
(divider a)))
([a b] (fourcond [a b]
(->amount (divider (getValue a (getUnit a)) (getValue b (getUnit b))) (divide (getUnit a) (getUnit b)))
(->amount (divider (getValue a (getUnit a)) (double b)) (getUnit a))
(->amount (divider (double a) (getValue b (getUnit b))) (inverse (getUnit b)))
(divider a b)))
)
)
# # # Concrete Arithmetic Ops ( with Specs and old docstrings )
(def ^{:doc (:doc (meta (var clojure.core/+)))} + (decorate-adder clojure.core/+))
(def ^{:doc (:doc (meta (var clojure.core/-)))} - (decorate-adder clojure.core/-))
(def ^{:doc (:doc (meta (var clojure.core/*)))} * (decorate-productor clojure.core/*))
(def ^{:doc (:doc (meta (var clojure.core//)))} / (decorate-divider clojure.core//))
(spec/fdef +
:args ::numbers-or-compatible-amounts
:ret ::number-or-amount
:fn #(if (every? number? (:args %))
(number? (:ret %))
(:units2.core/amount (:ret %)))
)
(spec/fdef -
:args ::some-numbers-or-compatible-amounts
:ret ::number-or-amount
:fn #(if (every? number? (:args %))
(number? (:ret %))
(:units2.core/amount (:ret %)))
)
(spec/fdef *
:args (spec/* (spec/or :amount :units2.core/amount :number number?))
:ret (spec/or :amount :units2.core/amount :number number?)
:fn #(if (every? number? (:args %))
(number? (:ret %))
(:units2.core/amount (:ret %)))
)
(spec/fdef /
:args (spec/and (spec/+ ::number-or-amount)
also : do n't divide by zero ! ! !
this is an unsafe version of zero ?
(if (empty? (rest x))
(not (unsafe-zero? (spec/unform ::number-or-amount (first x))))
(every? #(not (unsafe-zero? (spec/unform ::number-or-amount %))) (rest x))))))
:ret (spec/or :amount :units2.core/amount :number number?)
:fn #(if (every? number? (:args %))
(number? (:ret %))
(:units2.core/amount (:ret %)))
)
(spec/fdef divide-into-double :args ::two-linear-units-second-nonzero
:ret double?)
(defn divide-into-double
"When all units involved are linear rescalings of one another, fractions with the same dimensions in the numerator and denominator have a *unique* unit-free value.
This is basically syntactic sugar for `(getValue a (AsUnit b))` with some error checking."
^double [a b]
(if (and (amount? a)
(amount? b)
(compatible? (getUnit a) (getUnit b))
(linear? (getConverter (getUnit a) (getUnit b))))
(getValue a (AsUnit b))
(throw (IllegalArgumentException. (str "divide-into-double requires two amounts with linearly related units! (`" a "' and `" b "' provided)")))))
# # Modular Arithmetic
(let [PSA "Modular arithmetic interacts nontrivially with offsets of units."]
Modular arithmetic interacts nontrivially with rescalings of units .
( let [ a ( ->amount 2.5 meter )
b ( ->amount 5 ( / meter 2 ) )
c ( ->amount 3 second ) ]
(defn decorate-ratio [ratio]
(fn
([a b]
(if (or (amount? a) (amount? b))
(throw (UnsupportedOperationException. PSA))
(ratio a b)))
([a b c]
(let [U (AsUnit c)]
(->amount (ratio (getValue a U) (getValue b U)) U)))
)
)
(defn decorate-entier [entier]
(fn
([a]
(if (amount? a)
(throw (UnsupportedOperationException. PSA))
(entier a)))
treat second amount as the ` unity ' quantity , e.g. ( round ... 10 ) rounds to the nearest 10 .
(* (entier (divide-into-double a b)) b))
)
)
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/rem)))
"\n Units2 added doc: " PSA)}
rem (decorate-ratio clojure.core/rem))
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/quot)))
"\n Units2 added doc: " PSA)}
quot (decorate-ratio clojure.core/quot))
(def ^{:doc PSA} ceil (decorate-entier #(Math/ceil %)))
(def ^{:doc PSA} floor (decorate-entier #(Math/floor %)))
(def ^{:doc PSA} abs (decorate-entier #(cond (int? %) (Math/abs (int %))
)
(spec/fdef rem :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret number?)
(spec/fdef quot :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret number?)
(spec/fdef ceil :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret double?)
(spec/fdef floor :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret double?)
(spec/fdef round :args (spec/or :one number? :bin ::two-linear-units-second-nonzero) :ret int?)
(spec/fdef abs :args (spec/or :one number? :bin ::two-linear-units-second-nonzero)
:ret (spec/and clojure.core/pos? (spec/or :int int? :double double?)))
# # Comparisons
` is 3 meters smaller than 5 seconds ? ' is a meaningless question and
(defn decorate-comparator [cmp]
(fn decorated-comparator [& args]
(cond
(empty? args) (cmp)
(every? #(not (amount? %)) args)
(apply cmp args)
(every? amount? args)
(if (every? #(compatible? (getUnit (first args)) %) (map getUnit (rest args)))
(apply cmp (map (from (getUnit (first args))) args))
(throw (UnsupportedOperationException. (str "Can't compare quantities in incompatible units! (" args " provided)"))))
:else
(throw (UnsupportedOperationException. (str "Can't compare quantities with and without units! (" args " provided)")))
)
)
)
(def ^{:doc (:doc (meta (var clojure.core/==)))} == (decorate-comparator clojure.core/==))
(def ^{:doc (:doc (meta (var clojure.core/< )))} < (decorate-comparator clojure.core/<))
(def ^{:doc (:doc (meta (var clojure.core/> )))} > (decorate-comparator clojure.core/>))
(def ^{:doc (:doc (meta (var clojure.core/<=)))} <= (decorate-comparator clojure.core/<=))
(def ^{:doc (:doc (meta (var clojure.core/>=)))} >= (decorate-comparator clojure.core/>=))
(spec/fdef == :args ::some-numbers-or-compatible-amounts :ret boolean?)
(spec/fdef < :args ::some-numbers-or-compatible-amounts :ret boolean?)
(spec/fdef > :args ::some-numbers-or-compatible-amounts :ret boolean?)
(spec/fdef <= :args ::some-numbers-or-compatible-amounts :ret boolean?)
(spec/fdef >= :args ::some-numbers-or-compatible-amounts :ret boolean?)
(let [PSA "Sign checks interact nontrivially with offsets of units.\n Please use explicit `==`,`>`,`<` checks against a zero-valued quantity."]
` zero ? ` , ` pos ? ` , and ` neg ? ` can return different answers depending on the input units
( to see why , consider the and Celius temperature scales )
(defn decorate-sign-predicate [pred]
(fn [a]
(if (amount? a)
(throw (UnsupportedOperationException. PSA))
(pred a))))
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/zero?)))
"\n Units2 added doc: " PSA)}
zero? (decorate-sign-predicate clojure.core/zero?))
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/pos?)))
"\n Units2 added doc: " PSA)}
pos? (decorate-sign-predicate clojure.core/pos?))
(def ^{:doc (str "Official Clojure doc: " (:doc (meta (var clojure.core/neg?)))
"\n Units2 added doc: " PSA)}
neg? (decorate-sign-predicate clojure.core/neg?))
)
(spec/fdef zero? :args number? :ret boolean?)
(spec/fdef pos? :args number? :ret boolean?)
(spec/fdef neg? :args number? :ret boolean?)
(defn decorate-order-statistic [ord]
(fn decorated-order-statistic [& nums]
(cond
(empty? nums)
(ord)
(every? #(not (amount? %)) nums)
(apply ord nums)
(every? amount? nums)
(if (every? #(compatible? (getUnit (first nums)) (getUnit %)) (rest nums))
(let [U (getUnit (first nums))]
(->amount (apply ord (map (from U) nums)) U))
(throw (UnsupportedOperationException. (str "Can't order dimensionally incompatible quantities! (" nums " provided)"))))
:else
(throw (UnsupportedOperationException. (str "Can't order quantities with and without units! (" nums " provided)")))
)
)
)
(def ^{:doc (:doc (meta (var clojure.core/min)))} min (decorate-order-statistic clojure.core/min))
(def ^{:doc (:doc (meta (var clojure.core/max)))} max (decorate-order-statistic clojure.core/max))
(spec/fdef max :args ::some-numbers-or-compatible-amounts
:ret ::number-or-amount)
(spec/fdef min :args ::some-numbers-or-compatible-amounts
:ret ::number-or-amount)
# # Powers and Exponentiation
(spec/fdef expt :args (spec/and (spec/tuple :units2.core/amount integer?)
(fn [[base exponent]]
(if (<= 0 exponent)
true
(spec/valid? ::nonzero-amount base))))
:ret :units2.core/amount)
(defn expt
"`(expt b n) == b^n`
where `n` is a rational number and `b` is an amount. Also includes functionality of a root function since `(root x N)` <=> `(expt x (/ N))`
"
[b n]
(->amount (Math/pow (getValue b (getUnit b)) n) (power (getUnit b) n)))
(let [PSA "Exponentiation interacts nontrivially with rescalings of units."]
( to see why , just imagine - expanding the ` exp ` or ` ln ` functions )
so we define them over ratios of amounts : / b ) , sqrt(a / b ) , etc .
(defn decorate-expt [expt]
(fn
([a]
(if (amount? a)
(throw (UnsupportedOperationException. PSA))
(expt a)))
([a b]
(if (every? amount? [a b])
(expt (divide-into-double a b))
(throw (IllegalArgumentException. (str "Arity-2 exponentiation requires two amounts! (" a " and " b " provided)")))
))))
(def ^{:doc PSA} exp (decorate-expt #(Math/exp %)))
(def ^{:doc PSA} log (decorate-expt #(Math/log %)))
(def ^{:doc PSA} log10 (decorate-expt #(Math/log10 %)))
(def ^{:doc PSA} sqrt (decorate-expt #(Math/sqrt %)))
)
(spec/fdef exp :args (spec/or :one number?
:bin ::two-linear-units-second-nonzero)
:ret (spec/and clojure.core/pos? double?))
(spec/fdef log :args (spec/or :one (spec/and clojure.core/pos? number?)
:bin (spec/and ::two-linear-units-second-nonzero
#(clojure.core/pos? (divide-into-double (first %) (second %)))))
:ret double?)
(spec/fdef log10 :args (spec/or :one (spec/and clojure.core/pos? number?)
:bin (spec/and ::two-linear-units-second-nonzero
#(clojure.core/pos? (divide-into-double (first %) (second %)))))
:ret double?)
(spec/fdef sqrt :args (spec/or :one (spec/and clojure.core/pos? number?)
:bin (spec/and ::two-linear-units-second-nonzero
#(clojure.core/pos? (divide-into-double (first %) (second %)))))
:ret (spec/and clojure.core/pos? double?))
(spec/fdef pow :args (spec/or :bin (spec/tuple number? number?)
(spec/and (spec/tuple :units2.core/amount :units2.core/amount number?)
(fn [[a b _]] (spec/valid? ::two-linear-units-second-nonzero [a b])))
( fn [ ] ( gen / cat ( spec / gen : : two - linear - units - second - nonzero )
)
:ret double?)
(defn pow
"Also includes functionality of a root function since `(root x N)` <=> `(pow x (/ N))`"
([a b]
(fourcond [a b]
(throw (IllegalArgumentException. (str "`pow` can't deal with the provided arguments (" a " and " b " provided). Maybe you want to provide a third number without units?")))
(throw (IllegalArgumentException. (str "`pow` can't deal with the provided arguments (" a " and " b " provided). Maybe you want to call the `expt` function instead?")))
(throw (IllegalArgumentException. (str "Can't use a dimensionful quantity as an exponent (" b " provided).")))
(Math/pow a b)))
([a b c]
(if (and (amount? a) (amount? b) (compatible? (getUnit a) (getUnit b)) (not (amount? c)))
(Math/pow (divide-into-double a b) c)
(throw (IllegalArgumentException. (str "Arity-3 `pow` requires two compatible amounts and a number! (" a ", " b ", and " c " provided)"))))))
# # EVERYTHING TOGETHER
(defmacro ^:private defmacro-without-hygiene
"Expands into a `defmacro` with a `(let [bindings] body)` that gets
around Clojure's automatic namespacing in syntax-quote by building
the `let` form explicitly. Macros can be dangerous. Have fun!!!!"
[macroname docstring bindings]
(let [body (gensym)]
`(defmacro ~macroname ~docstring [& ~body]
(clojure.core/conj ~body '~bindings 'clojure.core/let))))
14/03/16 : Thanks to the ` Amsterdam Clojurians ` for noticing that ` conj ` should be ` clojure.core/conj ` in the above ,
(defmacro-without-hygiene with-unit-arithmetic
"Locally rebind arithmetic operators like `+`, and `/` to unit-aware equivalents."
[+ units2.ops/+
- units2.ops/-
* units2.ops/*
/ units2.ops//
quot units2.ops/quot
rem units2.ops/rem
])
(defmacro-without-hygiene with-unit-comparisons
"Locally rebind `==`, `>=`, `<`, `zero?`, `pos?`, `min`, ... to unit-aware equivalents."
[== units2.ops/==
> units2.ops/>
< units2.ops/<
>= units2.ops/>=
<= units2.ops/<=
zero? units2.ops/zero?
pos? units2.ops/pos?
neg? units2.ops/neg?
min units2.ops/min
max units2.ops/max
])
(defmacro-without-hygiene with-unit-expts
"Locally bind exponentiation functions to unit-aware equivalents."
[expt units2.ops/expt
exp units2.ops/exp
sqrt units2.ops/sqrt
pow units2.ops/pow
log units2.ops/log
log10 units2.ops/log10
])
"Locally bind magnitude functions to unit-aware equivalents."
[abs units2.ops/abs
floor units2.ops/floor
ceil units2.ops/ceil
round units2.ops/round
])
(defmacro with-unit-
(let [keywords {:arithmetic '[units2.ops/with-unit-arithmetic]
:expt '[units2.ops/with-unit-expts]
:magn '[units2.ops/with-unit-magnitudes]
:math '[units2.ops/with-unit-arithmetic
units2.ops/with-unit-expts]
:comp '[units2.ops/with-unit-comparisons]
:all '[units2.ops/with-unit-arithmetic
units2.ops/with-unit-expts
units2.ops/with-unit-comparisons
units2.ops/with-unit-magnitudes
]
}
envs (remove nil? (set (flatten (map keywords labels))))]
(reduce #(list %2 %1) `(do ~@body) envs)))
|
74ffdb9ef24809c1e2197b368996d065cfd4c21b4efaa4b61dba181c1165e880 | satori-com/mzbench | worker_start_linear.erl | [ % linear worker start, almost similar to loop with "spawn" option,
but in this case workers wo n't share one state
{pool, [{size, 60},
{worker_start, {linear, {1, rps}}},
{worker_type, dummy_worker}],
[{print, {sprintf, "My number is: ~p", [{round_robin, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}]}}]}
].
| null | https://raw.githubusercontent.com/satori-com/mzbench/02be2684655cde94d537c322bb0611e258ae9718/examples/worker_start_linear.erl | erlang | linear worker start, almost similar to loop with "spawn" option, | but in this case workers wo n't share one state
{pool, [{size, 60},
{worker_start, {linear, {1, rps}}},
{worker_type, dummy_worker}],
[{print, {sprintf, "My number is: ~p", [{round_robin, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}]}}]}
].
|
c97456ee8c465c14f5fd955b2b3acb411e2e43d08eb4b57c29c44ef0216fc9e7 | clojure-interop/google-cloud-clients | Options$QueryOption.clj | (ns com.google.cloud.spanner.Options$QueryOption
"Marker interface to mark options applicable to query operation."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.spanner Options$QueryOption]))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.spanner/src/com/google/cloud/spanner/Options%24QueryOption.clj | clojure | (ns com.google.cloud.spanner.Options$QueryOption
"Marker interface to mark options applicable to query operation."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.spanner Options$QueryOption]))
|
|
be188cabc940a07257cf6db0a5898d50e9f4f094276724fba653ae1e93c2805c | xvw/ocamlectron | Event.ml | open Js_of_ocaml
module EventEmitter = Electron_plumbing.EventEmitter
type 'a t = Js.js_string Js.t
type js = Electron_plumbing.Event.t
type listener_id = (unit -> unit)
let on (source : #EventEmitter.emitter Js.t) (event : ('a -> 'b) t) (f : ('a -> 'b)) =
let callback = Js.wrap_callback f in
let () = source ## on event callback in
fun () -> source ## off event callback
let off f = f ()
let make_s : (string -> 'a t) = Js.string
let make_lwt event source =
let elt = ref Js.null in
let task, await = Lwt.task () in
let cancel () = Js.Opt.iter !elt off in
let () = Lwt.on_cancel task cancel in
let () =
elt := Js.some (
on source event (fun ev ->
let () = cancel () in
Lwt.wakeup await ev
)
)
in task
let make event =
fun ?use_capture source ->
match use_capture with
| _ -> make_lwt (make_s event) source
let prevent_default event =
event ## preventDefault ()
| null | https://raw.githubusercontent.com/xvw/ocamlectron/3e0cb9575975e69ab34cb7e0e3549d31c07141c2/lib/electron_api/Event.ml | ocaml | open Js_of_ocaml
module EventEmitter = Electron_plumbing.EventEmitter
type 'a t = Js.js_string Js.t
type js = Electron_plumbing.Event.t
type listener_id = (unit -> unit)
let on (source : #EventEmitter.emitter Js.t) (event : ('a -> 'b) t) (f : ('a -> 'b)) =
let callback = Js.wrap_callback f in
let () = source ## on event callback in
fun () -> source ## off event callback
let off f = f ()
let make_s : (string -> 'a t) = Js.string
let make_lwt event source =
let elt = ref Js.null in
let task, await = Lwt.task () in
let cancel () = Js.Opt.iter !elt off in
let () = Lwt.on_cancel task cancel in
let () =
elt := Js.some (
on source event (fun ev ->
let () = cancel () in
Lwt.wakeup await ev
)
)
in task
let make event =
fun ?use_capture source ->
match use_capture with
| _ -> make_lwt (make_s event) source
let prevent_default event =
event ## preventDefault ()
|
|
de2a6460ac05ef94ee24102b5d6f8abc055d35f5802a9dc0914d818248c3de88 | babashka/sci | libsci.clj | (ns sci.impl.libsci
(:require [cheshire.core :as cheshire]
[sci.core :as sci])
(:gen-class
:methods [^{:static true} [evalString [String] String]]))
(defn -evalString [s]
(sci/binding [sci/out *out*] ;; this enables println etc.
(str (try (sci/eval-string
s
;; this brings cheshire.core into sci
{:namespaces {'cheshire.core {'generate-string cheshire/generate-string}}})
(catch Exception e
{:error (str (type e))
:message (.getMessage e)})))))
| null | https://raw.githubusercontent.com/babashka/sci/20616983a8be69f2c28c4ef453e7a4eb644a12ee/libsci/src/sci/impl/libsci.clj | clojure | this enables println etc.
this brings cheshire.core into sci | (ns sci.impl.libsci
(:require [cheshire.core :as cheshire]
[sci.core :as sci])
(:gen-class
:methods [^{:static true} [evalString [String] String]]))
(defn -evalString [s]
(str (try (sci/eval-string
s
{:namespaces {'cheshire.core {'generate-string cheshire/generate-string}}})
(catch Exception e
{:error (str (type e))
:message (.getMessage e)})))))
|
baf659b8ab79aa28a3cd4b8b002a0e8581a69a77f07a6dbb0222ffa206b36d5d | 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 "proc (x) -(x, 1)")
(a-program (proc-exp 'x (diff-exp (var-exp 'x)
(const-exp 1)))))
(check-equal?
(parse "letrec f(x) = a in b")
(a-program (letrec-exp 'f
'x
(var-exp 'a)
(var-exp 'b))))
(check-equal?
(parse "(f x)")
(a-program (call-exp (var-exp 'f)
(var-exp 'x))))
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/05-ch5/interpreters/racket/TRAMPOLINED-5.19/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 "proc (x) -(x, 1)")
(a-program (proc-exp 'x (diff-exp (var-exp 'x)
(const-exp 1)))))
(check-equal?
(parse "letrec f(x) = a in b")
(a-program (letrec-exp 'f
'x
(var-exp 'a)
(var-exp 'b))))
(check-equal?
(parse "(f x)")
(a-program (call-exp (var-exp 'f)
(var-exp 'x))))
|
|
e2028ee8b3167b6a16d1ea920ccf98983b62c79786af15773d8507c20fb5647c | janestreet/universe | nvim_command.mli | open Core
type nargs =
[ `Exactly of int
| `List
| `At_most_one
| `At_least_one
]
type addr_type =
[ `Lines
| `Args
| `Buffers
| `Loaded_bufs
| `Windows
| `Tabs
]
type range_type =
| Range of
[ `Defaults_to_current_line
| `Defaults_to_whole_file
| `Defaults_to_line_nr of int
]
| Count of int
type t =
{ name : string
; definition : string
; script_id : int
; bang : bool
; bar : bool
; register : bool
; nargs : nargs
; complete : string option
; complete_arg : string option
; range : range_type option
; addr : addr_type
}
val of_msgpack : Msgpack.t -> t Or_error.t
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/vcaml/src/nvim_command.mli | ocaml | open Core
type nargs =
[ `Exactly of int
| `List
| `At_most_one
| `At_least_one
]
type addr_type =
[ `Lines
| `Args
| `Buffers
| `Loaded_bufs
| `Windows
| `Tabs
]
type range_type =
| Range of
[ `Defaults_to_current_line
| `Defaults_to_whole_file
| `Defaults_to_line_nr of int
]
| Count of int
type t =
{ name : string
; definition : string
; script_id : int
; bang : bool
; bar : bool
; register : bool
; nargs : nargs
; complete : string option
; complete_arg : string option
; range : range_type option
; addr : addr_type
}
val of_msgpack : Msgpack.t -> t Or_error.t
|
|
b786bdeca4355ae643db97818a2eaa39ced16f7d9b8c19365dede820ad940cc1 | mejgun/haskell-tdlib | GetChatStatistics.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Query.GetChatStatistics where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
-- |
-- Returns detailed statistics about a chat. Currently, this method can be used only for supergroups and channels. Can be used only if supergroupFullInfo.can_get_statistics == true @chat_id Chat identifier @is_dark Pass true if a dark theme is used by the application
data GetChatStatistics = GetChatStatistics
{ -- |
is_dark :: Maybe Bool,
-- |
chat_id :: Maybe Int
}
deriving (Eq)
instance Show GetChatStatistics where
show
GetChatStatistics
{ is_dark = is_dark_,
chat_id = chat_id_
} =
"GetChatStatistics"
++ U.cc
[ U.p "is_dark" is_dark_,
U.p "chat_id" chat_id_
]
instance T.ToJSON GetChatStatistics where
toJSON
GetChatStatistics
{ is_dark = is_dark_,
chat_id = chat_id_
} =
A.object
[ "@type" A..= T.String "getChatStatistics",
"is_dark" A..= is_dark_,
"chat_id" A..= chat_id_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/81516bd04c25c7371d4a9a5c972499791111c407/src/TD/Query/GetChatStatistics.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
Returns detailed statistics about a chat. Currently, this method can be used only for supergroups and channels. Can be used only if supergroupFullInfo.can_get_statistics == true @chat_id Chat identifier @is_dark Pass true if a dark theme is used by the application
|
| |
module TD.Query.GetChatStatistics where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
data GetChatStatistics = GetChatStatistics
is_dark :: Maybe Bool,
chat_id :: Maybe Int
}
deriving (Eq)
instance Show GetChatStatistics where
show
GetChatStatistics
{ is_dark = is_dark_,
chat_id = chat_id_
} =
"GetChatStatistics"
++ U.cc
[ U.p "is_dark" is_dark_,
U.p "chat_id" chat_id_
]
instance T.ToJSON GetChatStatistics where
toJSON
GetChatStatistics
{ is_dark = is_dark_,
chat_id = chat_id_
} =
A.object
[ "@type" A..= T.String "getChatStatistics",
"is_dark" A..= is_dark_,
"chat_id" A..= chat_id_
]
|
a21023ec2296bbfc9567d794f3e8c7f2ddf7be180d3faf14deb92ead87125b74 | emina/rosette | cvc4.rkt | #lang racket
(require racket/runtime-path
"server.rkt" "env.rkt"
"../solver.rkt"
(prefix-in base/ "base-solver.rkt"))
(provide (rename-out [make-cvc4 cvc4]) cvc4? cvc4-available?)
(define-runtime-path cvc4-path (build-path ".." ".." ".." "bin" "cvc4"))
(define cvc4-opts '("-L" "smt2" "-q" "-m" "-i" "--bv-print-consts-as-indexed-symbols" "--bv-div-zero-const"))
(define (cvc4-available?)
(not (false? (base/find-solver "cvc4" cvc4-path #f))))
(define (make-cvc4 [solver #f] #:options [options (hash)] #:logic [logic #f] #:path [path #f])
(define config
(cond
[(cvc4? solver)
(base/solver-config solver)]
[else
(define real-cvc4-path (base/find-solver "cvc4" cvc4-path path))
(when (and (false? real-cvc4-path) (not (getenv "PLT_PKG_BUILD_SERVICE")))
(error 'cvc4 "cvc4 binary is not available (expected to be at ~a); try passing the #:path argument to (cvc4)" (path->string (simplify-path cvc4-path))))
(base/config options real-cvc4-path logic)]))
(cvc4 (server (base/config-path config) cvc4-opts (base/make-send-options config)) config '() '() '() (env) '()))
(struct cvc4 base/solver ()
#:property prop:solver-constructor make-cvc4
#:methods gen:custom-write
[(define (write-proc self port mode) (fprintf port "#<cvc4>"))]
#:methods gen:solver
[
(define (solver-features self)
'(qf_bv qf_uf qf_lia qf_nia qf_lra qf_nra quantifiers int2bv))
(define (solver-options self)
(base/solver-options self))
(define (solver-assert self bools)
(base/solver-assert self bools))
(define (solver-minimize self nums)
(base/solver-minimize self nums))
(define (solver-maximize self nums)
(base/solver-maximize self nums))
(define (solver-clear self)
(base/solver-clear self))
(define (solver-shutdown self)
(base/solver-shutdown self))
(define (solver-push self)
(base/solver-push self))
(define (solver-pop self [k 1])
(base/solver-pop self k))
(define (solver-check self)
(base/solver-check self))
(define (solver-debug self)
(base/solver-debug self))])
(define (set-default-options server)
void)
| null | https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/rosette/solver/smt/cvc4.rkt | racket | #lang racket
(require racket/runtime-path
"server.rkt" "env.rkt"
"../solver.rkt"
(prefix-in base/ "base-solver.rkt"))
(provide (rename-out [make-cvc4 cvc4]) cvc4? cvc4-available?)
(define-runtime-path cvc4-path (build-path ".." ".." ".." "bin" "cvc4"))
(define cvc4-opts '("-L" "smt2" "-q" "-m" "-i" "--bv-print-consts-as-indexed-symbols" "--bv-div-zero-const"))
(define (cvc4-available?)
(not (false? (base/find-solver "cvc4" cvc4-path #f))))
(define (make-cvc4 [solver #f] #:options [options (hash)] #:logic [logic #f] #:path [path #f])
(define config
(cond
[(cvc4? solver)
(base/solver-config solver)]
[else
(define real-cvc4-path (base/find-solver "cvc4" cvc4-path path))
(when (and (false? real-cvc4-path) (not (getenv "PLT_PKG_BUILD_SERVICE")))
(error 'cvc4 "cvc4 binary is not available (expected to be at ~a); try passing the #:path argument to (cvc4)" (path->string (simplify-path cvc4-path))))
(base/config options real-cvc4-path logic)]))
(cvc4 (server (base/config-path config) cvc4-opts (base/make-send-options config)) config '() '() '() (env) '()))
(struct cvc4 base/solver ()
#:property prop:solver-constructor make-cvc4
#:methods gen:custom-write
[(define (write-proc self port mode) (fprintf port "#<cvc4>"))]
#:methods gen:solver
[
(define (solver-features self)
'(qf_bv qf_uf qf_lia qf_nia qf_lra qf_nra quantifiers int2bv))
(define (solver-options self)
(base/solver-options self))
(define (solver-assert self bools)
(base/solver-assert self bools))
(define (solver-minimize self nums)
(base/solver-minimize self nums))
(define (solver-maximize self nums)
(base/solver-maximize self nums))
(define (solver-clear self)
(base/solver-clear self))
(define (solver-shutdown self)
(base/solver-shutdown self))
(define (solver-push self)
(base/solver-push self))
(define (solver-pop self [k 1])
(base/solver-pop self k))
(define (solver-check self)
(base/solver-check self))
(define (solver-debug self)
(base/solver-debug self))])
(define (set-default-options server)
void)
|
|
66158af4f569cd1535da29b38a6893d9c6948a44ff3b1df19ee24fad24fd4077 | den1k/vimsical | redis.clj | (ns vimsical.backend.adapters.redis
(:require
[clojure.spec.alpha :as s]
[com.stuartsierra.component :as cp]
[taoensso.carmine :as car :refer [wcar]]))
;;
;; * Helpers
;;
(defn flushall! [redis]
(car/wcar
redis
(car/flushall)))
;;
;; * Component
;;
(defrecord Redis [host port spec]
cp/Lifecycle
(start [this]
(let [spec {:host host :port port}]
(doto (assoc this :pool nil :spec spec)
(wcar
(car/ping)))))
(stop [this]
(-> this
(dissoc :host :port :spec))))
(s/def ::host string?)
(s/def ::port nat-int?)
(s/def ::opts
(s/keys :req-un [::host ::port]))
(s/fdef ->redis
:args (s/cat :opts ::opts)
:ret #(and % (instance? Redis %)))
(defn ->redis
[opts]
(map->Redis opts))
(s/def ::redis (fn [x] (and x (instance? Redis x))))
| null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/backend/vimsical/backend/adapters/redis.clj | clojure |
* Helpers
* Component
| (ns vimsical.backend.adapters.redis
(:require
[clojure.spec.alpha :as s]
[com.stuartsierra.component :as cp]
[taoensso.carmine :as car :refer [wcar]]))
(defn flushall! [redis]
(car/wcar
redis
(car/flushall)))
(defrecord Redis [host port spec]
cp/Lifecycle
(start [this]
(let [spec {:host host :port port}]
(doto (assoc this :pool nil :spec spec)
(wcar
(car/ping)))))
(stop [this]
(-> this
(dissoc :host :port :spec))))
(s/def ::host string?)
(s/def ::port nat-int?)
(s/def ::opts
(s/keys :req-un [::host ::port]))
(s/fdef ->redis
:args (s/cat :opts ::opts)
:ret #(and % (instance? Redis %)))
(defn ->redis
[opts]
(map->Redis opts))
(s/def ::redis (fn [x] (and x (instance? Redis x))))
|
e0601abb8a84a86407c6a50a9dad38c71bdcb01a55f884c429ce13195a47ddd7 | OCamlPro/alt-ergo | intervals.mli | (******************************************************************************)
(* *)
(* The Alt-Ergo theorem prover *)
Copyright ( C ) 2006 - 2013
(* *)
(* *)
(* *)
CNRS - INRIA - Universite Paris Sud
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(* ------------------------------------------------------------------------ *)
(* *)
Alt - Ergo : The SMT Solver For Software Verification
Copyright ( C ) 2013 - 2018
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(******************************************************************************)
type t
exception NotConsistent of Explanation.t
exception No_finite_bound
val undefined : Ty.t -> t
val is_undefined : t -> bool
val point : Numbers.Q.t -> Ty.t -> Explanation.t -> t
val doesnt_contain_0 : t -> Th_util.answer
val is_positive : t -> Th_util.answer
val is_strict_smaller : t -> t -> bool
val new_borne_sup : Explanation.t -> Numbers.Q.t -> is_le : bool -> t -> t
val new_borne_inf : Explanation.t -> Numbers.Q.t -> is_le : bool -> t -> t
val only_borne_sup : t -> t
(** Keep only the upper bound of the interval,
setting the lower bound to minus infty. *)
val only_borne_inf : t -> t
(** Keep only the lower bound of the interval,
setting the upper bound to plus infty. *)
val is_point : t -> (Numbers.Q.t * Explanation.t) option
val intersect : t -> t -> t
val exclude : t -> t -> t
val mult : t -> t -> t
val power : int -> t -> t
val sqrt : t -> t
val root : int -> t -> t
val add : t -> t -> t
val scale : Numbers.Q.t -> t -> t
val affine_scale : const:Numbers.Q.t -> coef:Numbers.Q.t -> t -> t
* Perform an affine transformation on the given bounds .
Suposing input bounds ( b1 , b2 ) , this will return
( const + coef * b1 , const + coef * b2 ) .
This function is useful to avoid the incorrect roundings that
can take place when scaling down an integer range .
Suposing input bounds (b1, b2), this will return
(const + coef * b1, const + coef * b2).
This function is useful to avoid the incorrect roundings that
can take place when scaling down an integer range. *)
val sub : t -> t -> t
val merge : t -> t -> t
val abs : t -> t
val pretty_print : Format.formatter -> t -> unit
val print : Format.formatter -> t -> unit
val finite_size : t -> Numbers.Q.t option
val borne_inf : t -> Numbers.Q.t * Explanation.t * bool
* bool is true when bound is large . Raise : No_finite_bound if no
finite lower bound
finite lower bound *)
val borne_sup : t -> Numbers.Q.t * Explanation.t * bool
* bool is true when bound is large . Raise : No_finite_bound if no
finite upper bound
finite upper bound*)
val div : t -> t -> t
val coerce : Ty.t -> t -> t
* Coerce an interval to the given type . The main use of that function is
to round a rational interval to an integer interval . This is particularly
useful to avoid roudning too many times when manipulating intervals that
at the end represent an integer interval , but whose intermediate state do
not need to represent integer intervals ( e.g. computing the interval for
an integer polynome from the intervals of the monomes ) .
to round a rational interval to an integer interval. This is particularly
useful to avoid roudning too many times when manipulating intervals that
at the end represent an integer interval, but whose intermediate state do
not need to represent integer intervals (e.g. computing the interval for
an integer polynome from the intervals of the monomes). *)
val mk_closed :
Numbers.Q.t -> Numbers.Q.t -> bool -> bool ->
Explanation.t -> Explanation.t -> Ty.t -> t
(**
takes as argument in this order:
- a lower bound
- an upper bound
- a bool that says if the lower bound it is large (true) or strict
- a bool that says if the upper bound it is large (true) or strict
- an explanation of the lower bound
- an explanation of the upper bound
- a type Ty.t (Tint or Treal *)
type bnd = (Numbers.Q.t * Numbers.Q.t) option * Explanation.t
- None < - > Infinity
- the first number is the real bound
- the second number if +1 ( resp . -1 ) for strict lower ( resp . upper ) bound ,
and 0 for large bounds
- the first number is the real bound
- the second number if +1 (resp. -1) for strict lower (resp. upper) bound,
and 0 for large bounds
*)
val bounds_of : t -> (bnd * bnd) list
val contains : t -> Numbers.Q.t -> bool
val add_explanation : t -> Explanation.t -> t
val equal : t -> t -> bool
type interval_matching =
((Numbers.Q.t * bool) option * (Numbers.Q.t * bool) option * Ty.t)
Var.Map.t
(** matchs the given lower and upper bounds against the given interval, and
update the given accumulator with the constraints. Returns None if
the matching problem is inconsistent
*)
val match_interval:
Symbols.bound -> Symbols.bound -> t -> interval_matching ->
interval_matching option
| null | https://raw.githubusercontent.com/OCamlPro/alt-ergo/e357e6a828124ed2553ec901728edf381862a77f/src/lib/reasoners/intervals.mli | ocaml | ****************************************************************************
The Alt-Ergo theorem prover
License version 2.0
------------------------------------------------------------------------
License version 2.0
****************************************************************************
* Keep only the upper bound of the interval,
setting the lower bound to minus infty.
* Keep only the lower bound of the interval,
setting the upper bound to plus infty.
*
takes as argument in this order:
- a lower bound
- an upper bound
- a bool that says if the lower bound it is large (true) or strict
- a bool that says if the upper bound it is large (true) or strict
- an explanation of the lower bound
- an explanation of the upper bound
- a type Ty.t (Tint or Treal
* matchs the given lower and upper bounds against the given interval, and
update the given accumulator with the constraints. Returns None if
the matching problem is inconsistent
| Copyright ( C ) 2006 - 2013
CNRS - INRIA - Universite Paris Sud
This file is distributed under the terms of the Apache Software
Alt - Ergo : The SMT Solver For Software Verification
Copyright ( C ) 2013 - 2018
This file is distributed under the terms of the Apache Software
type t
exception NotConsistent of Explanation.t
exception No_finite_bound
val undefined : Ty.t -> t
val is_undefined : t -> bool
val point : Numbers.Q.t -> Ty.t -> Explanation.t -> t
val doesnt_contain_0 : t -> Th_util.answer
val is_positive : t -> Th_util.answer
val is_strict_smaller : t -> t -> bool
val new_borne_sup : Explanation.t -> Numbers.Q.t -> is_le : bool -> t -> t
val new_borne_inf : Explanation.t -> Numbers.Q.t -> is_le : bool -> t -> t
val only_borne_sup : t -> t
val only_borne_inf : t -> t
val is_point : t -> (Numbers.Q.t * Explanation.t) option
val intersect : t -> t -> t
val exclude : t -> t -> t
val mult : t -> t -> t
val power : int -> t -> t
val sqrt : t -> t
val root : int -> t -> t
val add : t -> t -> t
val scale : Numbers.Q.t -> t -> t
val affine_scale : const:Numbers.Q.t -> coef:Numbers.Q.t -> t -> t
* Perform an affine transformation on the given bounds .
Suposing input bounds ( b1 , b2 ) , this will return
( const + coef * b1 , const + coef * b2 ) .
This function is useful to avoid the incorrect roundings that
can take place when scaling down an integer range .
Suposing input bounds (b1, b2), this will return
(const + coef * b1, const + coef * b2).
This function is useful to avoid the incorrect roundings that
can take place when scaling down an integer range. *)
val sub : t -> t -> t
val merge : t -> t -> t
val abs : t -> t
val pretty_print : Format.formatter -> t -> unit
val print : Format.formatter -> t -> unit
val finite_size : t -> Numbers.Q.t option
val borne_inf : t -> Numbers.Q.t * Explanation.t * bool
* bool is true when bound is large . Raise : No_finite_bound if no
finite lower bound
finite lower bound *)
val borne_sup : t -> Numbers.Q.t * Explanation.t * bool
* bool is true when bound is large . Raise : No_finite_bound if no
finite upper bound
finite upper bound*)
val div : t -> t -> t
val coerce : Ty.t -> t -> t
* Coerce an interval to the given type . The main use of that function is
to round a rational interval to an integer interval . This is particularly
useful to avoid roudning too many times when manipulating intervals that
at the end represent an integer interval , but whose intermediate state do
not need to represent integer intervals ( e.g. computing the interval for
an integer polynome from the intervals of the monomes ) .
to round a rational interval to an integer interval. This is particularly
useful to avoid roudning too many times when manipulating intervals that
at the end represent an integer interval, but whose intermediate state do
not need to represent integer intervals (e.g. computing the interval for
an integer polynome from the intervals of the monomes). *)
val mk_closed :
Numbers.Q.t -> Numbers.Q.t -> bool -> bool ->
Explanation.t -> Explanation.t -> Ty.t -> t
type bnd = (Numbers.Q.t * Numbers.Q.t) option * Explanation.t
- None < - > Infinity
- the first number is the real bound
- the second number if +1 ( resp . -1 ) for strict lower ( resp . upper ) bound ,
and 0 for large bounds
- the first number is the real bound
- the second number if +1 (resp. -1) for strict lower (resp. upper) bound,
and 0 for large bounds
*)
val bounds_of : t -> (bnd * bnd) list
val contains : t -> Numbers.Q.t -> bool
val add_explanation : t -> Explanation.t -> t
val equal : t -> t -> bool
type interval_matching =
((Numbers.Q.t * bool) option * (Numbers.Q.t * bool) option * Ty.t)
Var.Map.t
val match_interval:
Symbols.bound -> Symbols.bound -> t -> interval_matching ->
interval_matching option
|
db1d155fa64133669a4db3263dc78d8298f8042e8deefee9a19dce13df6905fa | reborg/clojure-essential-reference | 2.clj | < 1 >
(m1 [this])
(m2 [this])
(m3 [this]))
< 2 >
{:m1 (fn [this] (str "AFace::m1"))
:m2 (fn [this] (str "AFace::m2"))})
(defrecord MyFace []) ; <3>
(extend MyFace
IFace
< 4 >
< 5 >
;; "MyFace::m1"
< 6 >
;; "AFace::m2"
< 7 >
No implementation of method : : m3 of protocol : # ' user / IFace | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Types%2CClasses%2CHierarchiesandPolymorphism/extend%2Cextend-typeandextend-protocol/2.clj | clojure | <3>
"MyFace::m1"
"AFace::m2" | < 1 >
(m1 [this])
(m2 [this])
(m3 [this]))
< 2 >
{:m1 (fn [this] (str "AFace::m1"))
:m2 (fn [this] (str "AFace::m2"))})
(extend MyFace
IFace
< 4 >
< 5 >
< 6 >
< 7 >
No implementation of method : : m3 of protocol : # ' user / IFace |
a3f636d95b2406e33e471bfedbbcd5943df4fdfcb510ecd2eeffe0a882b94b17 | ChicagoBoss/ChicagoBoss | boss_template_adapter_jade.erl | %%-------------------------------------------------------------------
@author
ChicagoBoss Team and contributors , see file in root directory
%% @end
This file is part of ChicagoBoss project .
See file in root directory
%% for license information, see LICENSE file in root directory
%% @end
%% @doc
%%-------------------------------------------------------------------
-module(boss_template_adapter_jade).
-compile(export_all).
file_extensions() -> ["jade"].
translatable_strings(_Module) -> [].
source(_Module) -> "".
dependencies(_Module) -> [].
render(Module, Variables, Options) ->
Module:render(Variables, Options).
compile_file(ViewPath, Module, Options) ->
OutDir = proplists:get_value(out_dir, Options),
ok = jaderl:compile(ViewPath, Module, [{out_dir, OutDir}]),
{ok, Module}.
| null | https://raw.githubusercontent.com/ChicagoBoss/ChicagoBoss/113bac70c2f835c1e99c757170fd38abf09f5da2/src/boss/template_adapters/boss_template_adapter_jade.erl | erlang | -------------------------------------------------------------------
@end
for license information, see LICENSE file in root directory
@end
@doc
------------------------------------------------------------------- | @author
ChicagoBoss Team and contributors , see file in root directory
This file is part of ChicagoBoss project .
See file in root directory
-module(boss_template_adapter_jade).
-compile(export_all).
file_extensions() -> ["jade"].
translatable_strings(_Module) -> [].
source(_Module) -> "".
dependencies(_Module) -> [].
render(Module, Variables, Options) ->
Module:render(Variables, Options).
compile_file(ViewPath, Module, Options) ->
OutDir = proplists:get_value(out_dir, Options),
ok = jaderl:compile(ViewPath, Module, [{out_dir, OutDir}]),
{ok, Module}.
|
88610dc2000a9b240c2b7ec3d53f0bb407d1c5e93d4e01e8604fcdd1454989f1 | Glue42/gateway-modules | util.cljc | (ns gateway.domains.global.util
(:require [gateway.basic-auth.core :as basic]
[gateway.auth.core :as auth]
[gateway.domains.global.core :as global]
[clojure.core.async :as a]))
(defn ->auth []
{:default :basic
:available {:basic (basic/authenticator {})}})
(defn stop-auth [auths]
(doseq [a (vals (:available auths))]
(auth/stop a)))
(defn handle-hello
[state source request env]
(let [auth (->auth)]
(try
(let [ch (a/chan 100)]
(try
(let [[state _] (-> state
(global/handle-hello source request auth ch env))
[auth-msg _] (a/alts!! [ch (a/timeout 1000)])]
(-> state
(global/handle-request source (:body auth-msg) nil nil env)))
(finally
(a/close! ch))))
(finally
(stop-auth auth))))) | null | https://raw.githubusercontent.com/Glue42/gateway-modules/be48a132134b5f9f41fd6a6067800da6be5e6eca/global-domain/test/gateway/domains/global/util.cljc | clojure | (ns gateway.domains.global.util
(:require [gateway.basic-auth.core :as basic]
[gateway.auth.core :as auth]
[gateway.domains.global.core :as global]
[clojure.core.async :as a]))
(defn ->auth []
{:default :basic
:available {:basic (basic/authenticator {})}})
(defn stop-auth [auths]
(doseq [a (vals (:available auths))]
(auth/stop a)))
(defn handle-hello
[state source request env]
(let [auth (->auth)]
(try
(let [ch (a/chan 100)]
(try
(let [[state _] (-> state
(global/handle-hello source request auth ch env))
[auth-msg _] (a/alts!! [ch (a/timeout 1000)])]
(-> state
(global/handle-request source (:body auth-msg) nil nil env)))
(finally
(a/close! ch))))
(finally
(stop-auth auth))))) |
|
24d91f562a6fe57cfcfbb3e22fb61eb67c34924572d98605d1ed080acac01ee4 | ygrek/mldonkey | indexer.mli | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
module type Doc = sig
type t
val num : t -> int
val filtered : t -> bool
val filter : t -> bool -> unit
end
module type Make = functor (Doc: Doc) ->
sig
type index
val create : unit -> index
val add : index -> string -> Doc.t -> int -> unit
val clear : index -> unit
val filter_words : index -> string list -> unit
val clear_filter : index -> unit
val filtered : Doc.t -> bool
type doc = Doc.t
type node
val or_get_fields : Doc.t Intmap.t ref -> node -> int -> Doc.t Intmap.t
val find : index -> string -> node
val and_get_fields : node -> int -> Doc.t Intmap.t -> Doc.t Intmap.t
val size : node -> int
val stats : index -> int
end
type 'a query =
And of 'a query * 'a query
| Or of 'a query * 'a query
| AndNot of 'a query * 'a query
| HasWord of string
| HasField of int * string
| Predicate of ('a -> bool)
module type Index = sig
type index
type node
type doc
val or_get_fields : doc Intmap.t ref -> node -> int -> doc Intmap.t
val find : index -> string -> node
val and_get_fields : node -> int -> doc Intmap.t -> doc Intmap.t
val size : node -> int
val stats : index -> int
end
module QueryMake ( Index : Index) : sig
val query : Index.index -> Index.doc query -> Index.doc array
val query_map : Index.index -> Index.doc query -> Index.doc Intmap.t
end
module FullMake (Doc : Doc) (Make : Make) : sig
type index
val create : unit -> index
val add : index -> string -> Doc.t -> int -> unit
val clear : index -> unit
val filter_words : index -> string list -> unit
val clear_filter : index -> unit
val filtered : Doc.t -> bool
val query_map : index -> Doc.t query -> Doc.t Intmap.t
val query : index -> Doc.t query -> Doc.t array
val stats : index -> int
end
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/utils/lib/indexer.mli | ocaml | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
module type Doc = sig
type t
val num : t -> int
val filtered : t -> bool
val filter : t -> bool -> unit
end
module type Make = functor (Doc: Doc) ->
sig
type index
val create : unit -> index
val add : index -> string -> Doc.t -> int -> unit
val clear : index -> unit
val filter_words : index -> string list -> unit
val clear_filter : index -> unit
val filtered : Doc.t -> bool
type doc = Doc.t
type node
val or_get_fields : Doc.t Intmap.t ref -> node -> int -> Doc.t Intmap.t
val find : index -> string -> node
val and_get_fields : node -> int -> Doc.t Intmap.t -> Doc.t Intmap.t
val size : node -> int
val stats : index -> int
end
type 'a query =
And of 'a query * 'a query
| Or of 'a query * 'a query
| AndNot of 'a query * 'a query
| HasWord of string
| HasField of int * string
| Predicate of ('a -> bool)
module type Index = sig
type index
type node
type doc
val or_get_fields : doc Intmap.t ref -> node -> int -> doc Intmap.t
val find : index -> string -> node
val and_get_fields : node -> int -> doc Intmap.t -> doc Intmap.t
val size : node -> int
val stats : index -> int
end
module QueryMake ( Index : Index) : sig
val query : Index.index -> Index.doc query -> Index.doc array
val query_map : Index.index -> Index.doc query -> Index.doc Intmap.t
end
module FullMake (Doc : Doc) (Make : Make) : sig
type index
val create : unit -> index
val add : index -> string -> Doc.t -> int -> unit
val clear : index -> unit
val filter_words : index -> string list -> unit
val clear_filter : index -> unit
val filtered : Doc.t -> bool
val query_map : index -> Doc.t query -> Doc.t Intmap.t
val query : index -> Doc.t query -> Doc.t array
val stats : index -> int
end
|
|
3787faf0eb5585c8c8e8d890fafb286db04d85025ea925067a5a9a661ea61b61 | viercc/kitchen-sink-hs | iamemhn.hs | import Runner
main :: IO ()
main = runWork isSquare
-- With and without optimization , adding annotation
isSquare : : ( a , a , a ) = > a - > Bool
-- made no impact on performance
-- With and without optimization, adding annotation
isSquare :: (Num a, Enum a, Ord a) => a -> Bool
-- made no impact on performance
-}
isSquare n = n == c * c
where
c = head $ dropWhile (\m -> m * m < n) [0..]
# SCC isSquare #
| null | https://raw.githubusercontent.com/viercc/kitchen-sink-hs/391efc1a30f02a65bbcc37a4391bd5cb0d3eee8c/execs/perf-src/iamemhn.hs | haskell | With and without optimization , adding annotation
made no impact on performance
With and without optimization, adding annotation
made no impact on performance | import Runner
main :: IO ()
main = runWork isSquare
isSquare : : ( a , a , a ) = > a - > Bool
isSquare :: (Num a, Enum a, Ord a) => a -> Bool
-}
isSquare n = n == c * c
where
c = head $ dropWhile (\m -> m * m < n) [0..]
# SCC isSquare #
|
35c86213d6d18c7a2f85d5feee7b6825c03d3025efd95a7142f296a271ccdecc | quintenpalmer/dungeons | Test.hs | module Main where
import Data.Maybe (fromJust)
import Character (selectPlayer,
serializePlayerForTerminal)
main = do
mPlayer <- selectPlayer "Prompt"
putStrLn $ serializePlayerForTerminal $ fromJust mPlayer
| null | https://raw.githubusercontent.com/quintenpalmer/dungeons/ad9445882e3cfd9d63df42a4e37265a71374598d/server/Test.hs | haskell | module Main where
import Data.Maybe (fromJust)
import Character (selectPlayer,
serializePlayerForTerminal)
main = do
mPlayer <- selectPlayer "Prompt"
putStrLn $ serializePlayerForTerminal $ fromJust mPlayer
|
|
45b9834b04766ad0bd5ea31ae66a1cba92c74c70f42b790e562a1cb76be8320b | chaoxu/fancy-walks | B.hs | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances #
{-# OPTIONS_GHC -O2 #-}
import Data.List
import Data.Maybe
import Data.Char
import Data.Array
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control . Monad . State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
parseInput = do
n <- readInt
k <- fromIntegral <$> readInteger
a <- map fromIntegral <$> replicateM n readInt
return (n, k, a)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = do
(n, k, a) <- evalState parseInput <$> BS.getContents
let s = sum a
when (k > s) $ putStrLn "-1"
when (k < s) $ putStrLn $ unwords . map show $ solve n k a
solve :: Int -> Int64 -> [Int64] -> [Int]
solve n k a = go pairs 0 k
where
intMap = foldl (\map v -> IntMap.insertWith (+) (fromIntegral v) 1 map) IntMap.empty a :: IntMap Int64
ass = IntMap.assocs intMap
pairs = scanr (\(k, v) (_,v') -> (fromIntegral k, v+v')) (maxBound,0) ass :: [(Int64, Int64)]
go :: [(Int64,Int64)] -> Int64 -> Int64 -> [Int]
go [] _ _ = []
go ((k, v):xs) k' num
| num >= tot = go xs k (num - tot)
| otherwise = map fst $ hi ++ lo'
where
tot = (k - k') * v
a' = filter (\(id, num) -> num >= k) $ zip [1..] a
(height, width) = num `divMod` fromIntegral (length a')
(lo, hi) = splitAt (fromIntegral width) a'
lo' = if height + 1 == k - k' then filter (\(id, num) -> num > k) lo else lo
{ { { Start of a minimal State Monad
class (Monad m) => MonadState s m | m -> s where
get :: m s
put :: s -> m ()
modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
s <- get
put (f s)
gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
s <- get
return (f s)
newtype State s a = State { runState :: s -> (a, s) }
instance Functor (State s) where
fmap f m = State $ \s -> let
(a, s') = runState m s
in (f a, s')
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return a = State $ \s -> (a, s)
m >>= k = State $ \s -> let
(a, s') = runState m s
in runState (k a) s'
instance MonadState s (State s) where
get = State $ \s -> (s, s)
put s = State $ \_ -> ((), s)
evalState :: State s a -> s -> a
evalState m s = fst (runState m s)
execState :: State s a -> s -> s
execState m s = snd (runState m s)
mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m
withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f
state = State
} } } end of a minimal State Monad
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/codeforces.com/83/B.hs | haskell | # OPTIONS_GHC -O2 # | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances #
import Data.List
import Data.Maybe
import Data.Char
import Data.Array
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control . Monad . State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
parseInput = do
n <- readInt
k <- fromIntegral <$> readInteger
a <- map fromIntegral <$> replicateM n readInt
return (n, k, a)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = do
(n, k, a) <- evalState parseInput <$> BS.getContents
let s = sum a
when (k > s) $ putStrLn "-1"
when (k < s) $ putStrLn $ unwords . map show $ solve n k a
solve :: Int -> Int64 -> [Int64] -> [Int]
solve n k a = go pairs 0 k
where
intMap = foldl (\map v -> IntMap.insertWith (+) (fromIntegral v) 1 map) IntMap.empty a :: IntMap Int64
ass = IntMap.assocs intMap
pairs = scanr (\(k, v) (_,v') -> (fromIntegral k, v+v')) (maxBound,0) ass :: [(Int64, Int64)]
go :: [(Int64,Int64)] -> Int64 -> Int64 -> [Int]
go [] _ _ = []
go ((k, v):xs) k' num
| num >= tot = go xs k (num - tot)
| otherwise = map fst $ hi ++ lo'
where
tot = (k - k') * v
a' = filter (\(id, num) -> num >= k) $ zip [1..] a
(height, width) = num `divMod` fromIntegral (length a')
(lo, hi) = splitAt (fromIntegral width) a'
lo' = if height + 1 == k - k' then filter (\(id, num) -> num > k) lo else lo
{ { { Start of a minimal State Monad
class (Monad m) => MonadState s m | m -> s where
get :: m s
put :: s -> m ()
modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
s <- get
put (f s)
gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
s <- get
return (f s)
newtype State s a = State { runState :: s -> (a, s) }
instance Functor (State s) where
fmap f m = State $ \s -> let
(a, s') = runState m s
in (f a, s')
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return a = State $ \s -> (a, s)
m >>= k = State $ \s -> let
(a, s') = runState m s
in runState (k a) s'
instance MonadState s (State s) where
get = State $ \s -> (s, s)
put s = State $ \_ -> ((), s)
evalState :: State s a -> s -> a
evalState m s = fst (runState m s)
execState :: State s a -> s -> s
execState m s = snd (runState m s)
mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m
withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f
state = State
} } } end of a minimal State Monad
|
bd69bb23c68573d002636587e7f7ef7b8bf142f085c86bab3e286f640a074dd2 | refset/xtdb-workshop-reclojure-21 | workshop.clj | ;; # Workshop
# # 👋 XTDB Workshop - Re : Clojure 2021
Prepared by , @refset
# # 🛠 ️ Powered by Notespace ™
;; This experience was built with
... " a notebook experience in your Clojure namespace "
;;
;; Inspired after watching a recent walkthrough by @daslu_ -ws
# # 🧑 💻 To follow along
;; * clone -workshop-reclojure-22
;; * fire-up your REPL using `clojure -M:notespace`
* connect to the REPL from your preferred editor
;;
# # 🥱 Alternatively
;; * sit back & watch :)
:_
;; # Setup
;; ## Dependencies
(ns workshop.workshop
(:require [xtdb.api :as xt]
[scicloj.notespace.v4.api :as notespace]
[scicloj.kindly.kind :as kind]
[workshop.tt-vt :as tt-vt]
[workshop.xt-universal-relation :as xr]))
;;
# # Run Notespace
To start ( or restart ) Notespace , eval the following ` restart ! ` call
(comment
(notespace/restart!))
;; You should see the following message printed in the REPL:
;; ```
;; Server starting...
Ready at port 1903
;; ```
;;
;; You can then open :1903 in your browser, and eval the entire `workshop.clj` buffer using your editor
:_
;; # Usage
With the ` workshop.clj ` buffer evaluated , the Notespace browser view is populated with unevaluated forms .
;;
Notespace listens to file - save events and to code evaluations in your editor / REPL environment .
You can evaluate each form , one by one , to see the result displayed and persisted in the browser view ( alongside your regular editor experience ) .
;; * A file save or an evaluation of a whole file will result in updating the viewed code.
;; * An evaluation of a region will result in updating the last evaluation value, as well as the values of the evaluated forms, if they can be recognized in the code unambiguously.
# # Notespace usage tips
;; * eval the whole buffer after calling `(notespace/restart!)`
;; * save the `workshop.clj` file to refresh the view of the ns before eval'ing (notespace watches for saves)
;; * if things get confusing, just call `(notespace/restart!)` again _and_ refresh the browser
* sometimes , Notespace does not know how to recognize the evaluated forms unambiguously in your editor 's buffer . For example , maybe it appears more than once , maybe the file has n't been saved since some recent changes , and maybe the evaluated region is not a set of top - level forms
* ( possible Notespace bug - unconfirmed ! ) when forms are repeated exactly , I 've noticed the eval result gets shown next to the first instance , so just modify the latter forms slightly as a workaround
;;
# # Rendering Hiccup
;; Simply add a `^kind/hiccup` metadata tag before the relevant form, e.g.
^kind/hiccup
[:div
{:style {:margin "1em"}}
[:svg
[:rect {:width 30
:height 30
:fill "blue"}]]]
Notespace also exposes various other built - in rendering capabilities and extension points , e.g.
^kind/hiccup
[:p/sparklinespot
{:data (->> #(- (rand) 0.5)
(repeatedly 99)
(reductions +))
:svgHeight 50}]
:_
;; # Start XT
;; `xtdb.api/start-node` always takes an options map
;;
;; `{}` = the default in-memory configuration
(def n (xt/start-node {}))
(type n)
;; Is the node alive?
(xt/status n)
A node implements the ` Closeable ` interface , should you ever need ` .close ` it
(comment
(.close n))
;;
;; ## FYI
;; * in-process embedded node (although an HTTP server + clj client module is available too)
;; * in-memory by default (i.e. nothing is persisted)
;; * implementation is multi-threaded and uses off-heap memory & caching (i.e. not as lightweight as DataScript)
* implicitly a " standalone " node , since its locally provisioned tx - log and doc - store can not be accessed by other nodes to create a cluster topology
:_
;; # Basics
;; Let's find _everything_ in the database using a basic Datalog query.
This requires first creating a ` db ` snapshot which allows for repeatable reads .
;;
;; A Datalog query is like a set of simultaneous equations - it pattern matches over the logical variables (Clojure symbols), using the data in the database expressed as Entity-Attribute-Value triples, to produce a set of result tuples that satisfy those logic variables
;;
;; In this case the query finds all entities (`e`) where each entity has _some_ `:xt/id` value (`_` is a wildcard):
(xt/q (xt/db n)
'{:find [e]
:where [[e :xt/id _]]})
;; (hopefully the result is an empty set, if not you may want to start a new node!)
;;
;; Let's add some data by submit a transaction containing a `put` operation:
(xt/submit-tx n [[::xt/put {:xt/id "foo"
:my-number 123}]])
Here , the map ` { : xt / id " foo " : my - number 123 } ` is a " document " , which represents a version of an entity . The only constraints are that all documents must specify an ` : xt / id ` and that all fields ( Clojure keys ) must be Clojure keywords .
;;
Note that document field values with either sets or vectors are interpreted as composite values and are automatically decomposed into multiple EAVs ( i.e. all document attributes are potentially " cardinality many " ) . Other complex values types like maps are stored as opaque value " hashes " so deeply nested values inside documents wo n't be available for efficient lookups or joins .
;;
XT is asynchronous by nature , so although we have called ` submit - tx ` we do n't yet whether the transaction has been processed ( or committed , if a ` match ` operation was used ) . To be sure that this transaction has been processed that the data is ready to be queried , we can use the returned transaction receipt to block the thread and wait until the data has been processed :
(->> [[::xt/put {:xt/id "bar"
:my-number 123}]]
(xt/submit-tx n)
(xt/await-tx n))
;; Now let's a take a look at the list of entities again:
workaround for Notespace eval of identical forms
(xt/q (xt/db n)
'{:find [e]
:where [[e :xt/id _]]}))
;; Note that the set result tuples corresponds to the `:find` vector definition.
;; We can use the `pull` pattern feature to retrieve the full documents again:
(xt/q (xt/db n)
'{:find [(pull e [*])]
:where [[e :xt/id _]]})
` pull ` can be used for deeply nested selections and joins , and follows the " EQL " specification documented at -query-language.org/
;; We can also use the `entity` API to retrieve an individual document:
(xt/entity (xt/db n)
"foo")
:_
;; # Joins
To join across documents , all XT requires is that the values and IDs correlate . This is achieved dynamically since XT does not ask the user to define a schema , therefore binary hash comparisons are used to perform joins at runtime across all value types ( and XT supports arbitrary value types , thanks to ) .
(xt/q (xt/db n)
'{:find [e]
:where [["foo" :my-number mynum]
[e :my-number mynum]]})
Here we have used a literal value ` " foo " ` in the entity position of the first " triple clause " .
;;
More importantly , we also introduced a new logic variable , which acts as an implicit join between the first clause and the second clause . This allowed XT to join across the number ` 123 ` .
;;
;; Note that both entities are returned.
;;
;; ## How is this possible?
XT stores graph - friendly indexes , such that a pair of ` E+A->V ` and ` A+V->E ` indexes are combined to make arbitrary navigation symmetrical and efficient .
;;
As a crude approximation , there is a _ sorted _ Key - Value ( KV ) index for ` ` that looks like :
[["bar" :my-number 123]
["foo" :my-number 123]]
And another sorted KV index for ` A+V->E ` that looks like :
[[:my-number 123 "bar"]
[:my-number 123 "foo"]]
;;
;; ## FYI
* note that XT does not store an index that allows for wildcard attribute lookups , therefore the attribute position in triple clauses only accepts concrete values ( Clojure keywords )
:_
;; # Temporality
;; ## Each entity has a timeline of document versions
;; By default we always write a document "now", so we don't have to concern ourselves with time _until we absolutely have to_.
;;
First , let 's make it slightly more convenient to submit transactions :
(defn submit! [n tx]
(let [txr (xt/submit-tx n tx)]
(xt/sync n)
txr))
Note that ` sync ` will ensure all currently submitted transactions are processed ( imagine multiple nodes submitting transactions to the tx - log concurrently )
;;
;; Let's update our `"foo"` document:
(submit! n [[::xt/put {:xt/id "foo"
:my-number 123
:my-color "red"}]])
;; Note that we always transact in terms of whole documents. This has both some benefits and a some downsides, but is generally simpler than attempting to merge updates in a bitemporal environment without a user-supplied schema :)
;; We can now take a look at the `entity-history` of `"foo"`:
(xt/entity-history (xt/db n) "foo" :asc)
;; Let's try "backfilling" the history of `"foo"` by adding a `start-valid-time` parameter:
(submit! n [[::xt/put {:xt/id "foo"
:my-number 123
:my-color "red"}
#inst "2021-12-01"]])
;; Take a look at the `entity-history` again and note the new entry in the timeline using the valid-time ordering.
( Notespace workaround , again 🙈 )
(xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true}))
;; To correct history, simply submit a document at the same valid-time:
(submit! n [[::xt/put {:xt/id "foo"
:my-number 123
:my-color "blue"}
#inst "2021-12-01"]])
;; Again:
(do 2
(xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true}))
For auditing , and for global ` db ` consistency ( i.e. repeated querying against a database snapshot ) , XT also maintains efficient access to the previous entity versions from the perspective of transaction - time . To see this in the ` entity - history ` , simply provide an extra option to the call :
(xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true
:with-corrections? true})
;; Note that corrections are returned using a sub-ordering by transaction-time
;;
;; We can also `put` documents into the future:
(submit! n [[::xt/put {:xt/id "foo"
:my-number 42
:my-color "orange"}
#inst "2021-12-05"]])
;; Again:
(do 3
(xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true}))
;; Hmm, where is our new version? Try again without limiting our view of "history" (which includes the future!) to "now"
(xt/entity-history (xt/db n #inst "2030-01-01")
"foo"
:asc
{:with-docs? true})
:_
# Tt - Vt
Since we have two time dimensions for each entity , we can meaningfully visualize the entity versions in a 2D diagram .
;;
In response to diagrams seen in academic literature , requests from XT users , and other bitemporal data resources like -bitemporal-intervals/ - a work - in - progress ` tt - vt/->tt - vt ` function has been created to generate Tt - Vt diagrams as SVG
^kind/hiccup
[:div {:style {:margin "20px"}}
(->> (xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true
:with-corrections? true})
(tt-vt/entity-history->tt-vt 100 100 :my-color))]
:_
;; # Universal Relation
How might an XT database look through the lens of a traditional RDBMS ?
;;
See the REPL for this one
(xr/node->prn-table n)
;; Note that `:xt/nil` is simply padding for the table, representing the absence of data (since `nil` is a valid value).
:_
;; # Storage
;; ...
:_
;; # Graphs
Let 's pull some data and forms from Learn XTDB Datalog Today -xtdb-datalog-today/learn-xtdb-datalog-today
:_
;; # Transactions
;; ## Match Op
;; ...
;; ## Evict Op
;; ...
;; ## TxFns Ops
;; ...
;; ## `with-tx`
;; ...
:_
;; # See Also
;; ## Lots of documentation @ xtdb.com
;; ## Tutorials
;; API overview -tutorial
;;
Learn XTDB Datalog Today -xtdb-datalog-today/learn-xtdb-datalog-today
;;
;; HTTP + JSON -over-http/
# # Lucene
;; -text-search/
# # HTTP + JSON ( OpenAPI )
;; /
# # Java API
;; /
;; ## Advanced Configurations
# # Monitoring & Operations
;; /
;; /
:_
;; # Wrap-up
# # 🎉 Congratulations 🎉
;; If you spot any errors or would like to make a suggestion, issues and PRs are welcome!
# # 🙏 Have a nice day 🙏
nil
| null | https://raw.githubusercontent.com/refset/xtdb-workshop-reclojure-21/c1a01cb5ca5651d5e30f2807354f2f164cad2cbf/src/workshop/workshop.clj | clojure | # Workshop
This experience was built with
Inspired after watching a recent walkthrough by @daslu_ -ws
* clone -workshop-reclojure-22
* fire-up your REPL using `clojure -M:notespace`
* sit back & watch :)
# Setup
## Dependencies
You should see the following message printed in the REPL:
```
Server starting...
```
You can then open :1903 in your browser, and eval the entire `workshop.clj` buffer using your editor
# Usage
* A file save or an evaluation of a whole file will result in updating the viewed code.
* An evaluation of a region will result in updating the last evaluation value, as well as the values of the evaluated forms, if they can be recognized in the code unambiguously.
* eval the whole buffer after calling `(notespace/restart!)`
* save the `workshop.clj` file to refresh the view of the ns before eval'ing (notespace watches for saves)
* if things get confusing, just call `(notespace/restart!)` again _and_ refresh the browser
Simply add a `^kind/hiccup` metadata tag before the relevant form, e.g.
# Start XT
`xtdb.api/start-node` always takes an options map
`{}` = the default in-memory configuration
Is the node alive?
## FYI
* in-process embedded node (although an HTTP server + clj client module is available too)
* in-memory by default (i.e. nothing is persisted)
* implementation is multi-threaded and uses off-heap memory & caching (i.e. not as lightweight as DataScript)
# Basics
Let's find _everything_ in the database using a basic Datalog query.
A Datalog query is like a set of simultaneous equations - it pattern matches over the logical variables (Clojure symbols), using the data in the database expressed as Entity-Attribute-Value triples, to produce a set of result tuples that satisfy those logic variables
In this case the query finds all entities (`e`) where each entity has _some_ `:xt/id` value (`_` is a wildcard):
(hopefully the result is an empty set, if not you may want to start a new node!)
Let's add some data by submit a transaction containing a `put` operation:
Now let's a take a look at the list of entities again:
Note that the set result tuples corresponds to the `:find` vector definition.
We can use the `pull` pattern feature to retrieve the full documents again:
We can also use the `entity` API to retrieve an individual document:
# Joins
Note that both entities are returned.
## How is this possible?
## FYI
# Temporality
## Each entity has a timeline of document versions
By default we always write a document "now", so we don't have to concern ourselves with time _until we absolutely have to_.
Let's update our `"foo"` document:
Note that we always transact in terms of whole documents. This has both some benefits and a some downsides, but is generally simpler than attempting to merge updates in a bitemporal environment without a user-supplied schema :)
We can now take a look at the `entity-history` of `"foo"`:
Let's try "backfilling" the history of `"foo"` by adding a `start-valid-time` parameter:
Take a look at the `entity-history` again and note the new entry in the timeline using the valid-time ordering.
To correct history, simply submit a document at the same valid-time:
Again:
Note that corrections are returned using a sub-ordering by transaction-time
We can also `put` documents into the future:
Again:
Hmm, where is our new version? Try again without limiting our view of "history" (which includes the future!) to "now"
# Universal Relation
Note that `:xt/nil` is simply padding for the table, representing the absence of data (since `nil` is a valid value).
# Storage
...
# Graphs
# Transactions
## Match Op
...
## Evict Op
...
## TxFns Ops
...
## `with-tx`
...
# See Also
## Lots of documentation @ xtdb.com
## Tutorials
API overview -tutorial
HTTP + JSON -over-http/
-text-search/
/
/
## Advanced Configurations
/
/
# Wrap-up
If you spot any errors or would like to make a suggestion, issues and PRs are welcome! | # # 👋 XTDB Workshop - Re : Clojure 2021
Prepared by , @refset
# # 🛠 ️ Powered by Notespace ™
... " a notebook experience in your Clojure namespace "
# # 🧑 💻 To follow along
* connect to the REPL from your preferred editor
# # 🥱 Alternatively
:_
(ns workshop.workshop
(:require [xtdb.api :as xt]
[scicloj.notespace.v4.api :as notespace]
[scicloj.kindly.kind :as kind]
[workshop.tt-vt :as tt-vt]
[workshop.xt-universal-relation :as xr]))
# # Run Notespace
To start ( or restart ) Notespace , eval the following ` restart ! ` call
(comment
(notespace/restart!))
Ready at port 1903
:_
With the ` workshop.clj ` buffer evaluated , the Notespace browser view is populated with unevaluated forms .
Notespace listens to file - save events and to code evaluations in your editor / REPL environment .
You can evaluate each form , one by one , to see the result displayed and persisted in the browser view ( alongside your regular editor experience ) .
# # Notespace usage tips
* sometimes , Notespace does not know how to recognize the evaluated forms unambiguously in your editor 's buffer . For example , maybe it appears more than once , maybe the file has n't been saved since some recent changes , and maybe the evaluated region is not a set of top - level forms
* ( possible Notespace bug - unconfirmed ! ) when forms are repeated exactly , I 've noticed the eval result gets shown next to the first instance , so just modify the latter forms slightly as a workaround
# # Rendering Hiccup
^kind/hiccup
[:div
{:style {:margin "1em"}}
[:svg
[:rect {:width 30
:height 30
:fill "blue"}]]]
Notespace also exposes various other built - in rendering capabilities and extension points , e.g.
^kind/hiccup
[:p/sparklinespot
{:data (->> #(- (rand) 0.5)
(repeatedly 99)
(reductions +))
:svgHeight 50}]
:_
(def n (xt/start-node {}))
(type n)
(xt/status n)
A node implements the ` Closeable ` interface , should you ever need ` .close ` it
(comment
(.close n))
* implicitly a " standalone " node , since its locally provisioned tx - log and doc - store can not be accessed by other nodes to create a cluster topology
:_
This requires first creating a ` db ` snapshot which allows for repeatable reads .
(xt/q (xt/db n)
'{:find [e]
:where [[e :xt/id _]]})
(xt/submit-tx n [[::xt/put {:xt/id "foo"
:my-number 123}]])
Here , the map ` { : xt / id " foo " : my - number 123 } ` is a " document " , which represents a version of an entity . The only constraints are that all documents must specify an ` : xt / id ` and that all fields ( Clojure keys ) must be Clojure keywords .
Note that document field values with either sets or vectors are interpreted as composite values and are automatically decomposed into multiple EAVs ( i.e. all document attributes are potentially " cardinality many " ) . Other complex values types like maps are stored as opaque value " hashes " so deeply nested values inside documents wo n't be available for efficient lookups or joins .
XT is asynchronous by nature , so although we have called ` submit - tx ` we do n't yet whether the transaction has been processed ( or committed , if a ` match ` operation was used ) . To be sure that this transaction has been processed that the data is ready to be queried , we can use the returned transaction receipt to block the thread and wait until the data has been processed :
(->> [[::xt/put {:xt/id "bar"
:my-number 123}]]
(xt/submit-tx n)
(xt/await-tx n))
workaround for Notespace eval of identical forms
(xt/q (xt/db n)
'{:find [e]
:where [[e :xt/id _]]}))
(xt/q (xt/db n)
'{:find [(pull e [*])]
:where [[e :xt/id _]]})
` pull ` can be used for deeply nested selections and joins , and follows the " EQL " specification documented at -query-language.org/
(xt/entity (xt/db n)
"foo")
:_
To join across documents , all XT requires is that the values and IDs correlate . This is achieved dynamically since XT does not ask the user to define a schema , therefore binary hash comparisons are used to perform joins at runtime across all value types ( and XT supports arbitrary value types , thanks to ) .
(xt/q (xt/db n)
'{:find [e]
:where [["foo" :my-number mynum]
[e :my-number mynum]]})
Here we have used a literal value ` " foo " ` in the entity position of the first " triple clause " .
More importantly , we also introduced a new logic variable , which acts as an implicit join between the first clause and the second clause . This allowed XT to join across the number ` 123 ` .
XT stores graph - friendly indexes , such that a pair of ` E+A->V ` and ` A+V->E ` indexes are combined to make arbitrary navigation symmetrical and efficient .
As a crude approximation , there is a _ sorted _ Key - Value ( KV ) index for ` ` that looks like :
[["bar" :my-number 123]
["foo" :my-number 123]]
And another sorted KV index for ` A+V->E ` that looks like :
[[:my-number 123 "bar"]
[:my-number 123 "foo"]]
* note that XT does not store an index that allows for wildcard attribute lookups , therefore the attribute position in triple clauses only accepts concrete values ( Clojure keywords )
:_
First , let 's make it slightly more convenient to submit transactions :
(defn submit! [n tx]
(let [txr (xt/submit-tx n tx)]
(xt/sync n)
txr))
Note that ` sync ` will ensure all currently submitted transactions are processed ( imagine multiple nodes submitting transactions to the tx - log concurrently )
(submit! n [[::xt/put {:xt/id "foo"
:my-number 123
:my-color "red"}]])
(xt/entity-history (xt/db n) "foo" :asc)
(submit! n [[::xt/put {:xt/id "foo"
:my-number 123
:my-color "red"}
#inst "2021-12-01"]])
( Notespace workaround , again 🙈 )
(xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true}))
(submit! n [[::xt/put {:xt/id "foo"
:my-number 123
:my-color "blue"}
#inst "2021-12-01"]])
(do 2
(xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true}))
For auditing , and for global ` db ` consistency ( i.e. repeated querying against a database snapshot ) , XT also maintains efficient access to the previous entity versions from the perspective of transaction - time . To see this in the ` entity - history ` , simply provide an extra option to the call :
(xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true
:with-corrections? true})
(submit! n [[::xt/put {:xt/id "foo"
:my-number 42
:my-color "orange"}
#inst "2021-12-05"]])
(do 3
(xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true}))
(xt/entity-history (xt/db n #inst "2030-01-01")
"foo"
:asc
{:with-docs? true})
:_
# Tt - Vt
Since we have two time dimensions for each entity , we can meaningfully visualize the entity versions in a 2D diagram .
In response to diagrams seen in academic literature , requests from XT users , and other bitemporal data resources like -bitemporal-intervals/ - a work - in - progress ` tt - vt/->tt - vt ` function has been created to generate Tt - Vt diagrams as SVG
^kind/hiccup
[:div {:style {:margin "20px"}}
(->> (xt/entity-history (xt/db n)
"foo"
:asc
{:with-docs? true
:with-corrections? true})
(tt-vt/entity-history->tt-vt 100 100 :my-color))]
:_
How might an XT database look through the lens of a traditional RDBMS ?
See the REPL for this one
(xr/node->prn-table n)
:_
:_
Let 's pull some data and forms from Learn XTDB Datalog Today -xtdb-datalog-today/learn-xtdb-datalog-today
:_
:_
Learn XTDB Datalog Today -xtdb-datalog-today/learn-xtdb-datalog-today
# # Lucene
# # HTTP + JSON ( OpenAPI )
# # Java API
# # Monitoring & Operations
:_
# # 🎉 Congratulations 🎉
# # 🙏 Have a nice day 🙏
nil
|
4de064ad9d78b1344f29b7e5d8cab5dce679180a2e6876003a5a43691b4ee82f | rd--/hsc3 | miElements.help.hs | -- miElements ; basic ; model=0=Modal
let inp = pinkNoiseId 'α' ar * 0.3
gat = lfPulse kr 2 0 0.5
in X.miElements ar {-blow_in-} inp 0 gat 45 0.5 0.2 0 0 0 0.5 0.5 0.5 0.5 0.5 0.25 0.5 0.7 0.2 0.3 {-model-} 0 0
miElements ; ringing ; useId ' blow ' input and contour set to 0.5
let inp = pinkNoiseId 'α' ar * 0.3
in X.miElements ar inp 0 1 48 0.5 {-contour-} 0.5 0 0 0 0.5 0.5 0.5 0.5 0.5 0.25 0.5 0.7 0.2 0.3 0 0
-- miElements ; ringing ; use theId 'strike' input (which bypasses the exciter section)
let inp = pinkNoiseId 'α' ar * 0.3
strike_in
-- miElements ; bow
let pit = iRandId 'α' 32 44
bow_timb = lfNoise1Id 'β' kr 0.3 * 0.5 + 0.5
in X.miElements ar 0 0 1 pit 0.5 0.5 1 0 0 0.5 0.5 bow_timb 0.5 0.5 0.25 0.5 0.7 0.2 0.3 0 0 * 0.25
-- miElements ; blow
let mod1 = lfNoise1Id 'α' kr 0.4 * 0.5 + 0.5
mod2 = lfNoise1Id 'β' kr 0.2 * 0.5 + 0.5
pit = lfNoise0Id 'γ' kr 0.1 `in_range` (32,44)
in X.miElements ar 0 0 1 pit 0.5 0.5 0 0.6 0 mod1 0.5 0.5 mod2 0.5 0.25 0.5 0.7 0.2 0.3 0 0 * 0.2
-- miElements ; blow ; contour
let gat = lfPulse kr 1 0.01 0.5
pit = sinOsc kr 5 0 * 0.1 + 53
cont = sinOsc kr 0.8 0 `in_range` (0,1)
flow = lfNoise1Id 'α' kr 0.1 `in_range` (0,1)
in X.miElements ar 0 0 gat pit 0.5 cont 0 0.5 0 flow 0.5 0.5 0.3 0.5 0.25 0.3 0.8 0.2 0.3 0 0 * 0.25
-- miElements ; model=0=MODAL ; event control
let f (_,g,x,y,z,o,rx,ry,_,_,_) =
let tr = trig1 g controlDur
pit = x * 24 + 56
stre = ry * 0.5 + 0.25
cont = y
flo = o
geo = 0.15 + (latch y tr * 0.35)
bri = 0.5 - y * 0.35
dmp = 1 - x * 0.25
pos = o * 0.5
spc = 0.5 - y * 0.5
md = 0
in X.miElements ar 0 0 g pit stre cont 0 z 0 flo 0.5 0.5 (0.25 + rx * 0.5) 0.5 geo bri dmp pos spc md 0 * 0.25
in mix (voicer 6 f) * control kr "gain" 1
-- miElements ; metal, bells
let tr = dustId 'α' ar 2.5
inp = decay tr 0.01
g = X.tBrownRandId 'β' 0.5 0.9 0.2 0 (coinGateId 'γ' 0.05 tr)
space = range 0.5 1 (lfNoise1Id 'δ' kr 0.1)
in X.miElements ar 0 inp 0 40 0.5 0.2 0 0 0 0.5 0.5 0.5 0.5 0.5 g 0.4 0.9 0.2 space 0 0 * 0.35
-- miElements ; metal, bells ; event control
let f (_,g,x,y,z,o,_,_,_,_,_) =
let tr = trig1 (k2a g) sampleDur
inp = decay (tr * z * 4) 0.01
pit = latch x g * 12 + 36
geo = latch y g * 0.4 + 0.5
spc = o * 0.5 + 0.5
in X.miElements ar 0 inp 0 pit 0.5 0.2 0 0 0 0.5 0.5 0.5 0.5 0.5 geo 0.4 0.9 0.2 spc 0 0
in mix (voicer 6 f) * control kr "gain" 1
-- miElements ; strike input ; playing chords ; model=2=Strings
let inp = decay (dustId 'α' ar 1) 0.01
g = lfNoise1Id 'β' kr 0.1 * 0.5 + 0.5
in X.miElements ar 0 inp 0 {-pit-} 53 0.5 0.2 0 0 0 0.5 0.5 0.5 0.5 0.5 {-geom-} g {-bright-} 0.5 {-damp-} 0.9 0.2 0.3 {-model-} 2 0
-- miElements ; metal, bells ; event control
let f (_,g,x,y,z,o,rx,_,_,_,_) =
let tr = trig1 (k2a g) sampleDur
inp = decay tr 0.01
pit = x * 12 + 48
geo = latch o g -- lfNoise1Id 'β' kr 0.1 * 0.5 + 0.5
bri = latch y g
dam = latch (0.9 - z) g
md = 2
in X.miElements ar 0 inp 0 pit 0.5 0.2 0 0 0 0.5 0.5 0.5 0.5 0.5 geo bri dam 0.2 0.3 md 0
in mix (voicer 6 f) * control kr "gain" 1
-- miElements ; mallets, strength
let gat = coinGateId 'α' 0.4 (impulse kr 6 0)
stren = tRandId 'β' 0 1 gat
strike_timbre = lfNoise1Id 'γ' kr 0.3 * 0.5 + 0.5
in X.miElements ar 0 0 gat {-pit-} 40 stren 0.2 0 0 {-strike_level-} 0.5 0.5 {-mallet-} 0.7 0.5 0.5 strike_timbre 0.25 {-bright-} 0.3 {-damp-} 0.85 0.2 {-space-} 0.6 0 0 * 0.5
-- miElements ; mallets ; particles (mallet type=1 --> use internal model of bouncing particles)
let strike_timbre = lfNoise1Id 'α' kr 0.3 * 0.5 + 0.5
g = range 0.4 0.7 (lfNoise2Id 'β' kr 0.1)
maltype = 1
in X.miElements ar 0 0 {-gate-} 1 {-pit-} 40 0.5 {-contour-} 0.5 0 0 {-strike_level-} 0.5 0.5 {-mallet-} maltype 0.5 0.5 strike_timbre {-geom-} g 0.5 0.7 0.2 0.3 0 0
miElements ; easteregg : 2x2 - op FM synth
let n = lfNoise1Id 'α' kr 0.3 * 0.5 + 0.5
(r1,r2,r3) = (0.25,0.25,0.51)
easteregg
| null | https://raw.githubusercontent.com/rd--/hsc3/e1c9377f4985f4cc209a9cb11421bc8f1686c6f2/Help/Ugen/miElements.help.hs | haskell | miElements ; basic ; model=0=Modal
blow_in
model
contour
miElements ; ringing ; use theId 'strike' input (which bypasses the exciter section)
miElements ; bow
miElements ; blow
miElements ; blow ; contour
miElements ; model=0=MODAL ; event control
miElements ; metal, bells
miElements ; metal, bells ; event control
miElements ; strike input ; playing chords ; model=2=Strings
pit
geom
bright
damp
model
miElements ; metal, bells ; event control
lfNoise1Id 'β' kr 0.1 * 0.5 + 0.5
miElements ; mallets, strength
pit
strike_level
mallet
bright
damp
space
miElements ; mallets ; particles (mallet type=1 --> use internal model of bouncing particles)
gate
pit
contour
strike_level
mallet
geom | let inp = pinkNoiseId 'α' ar * 0.3
gat = lfPulse kr 2 0 0.5
miElements ; ringing ; useId ' blow ' input and contour set to 0.5
let inp = pinkNoiseId 'α' ar * 0.3
let inp = pinkNoiseId 'α' ar * 0.3
strike_in
let pit = iRandId 'α' 32 44
bow_timb = lfNoise1Id 'β' kr 0.3 * 0.5 + 0.5
in X.miElements ar 0 0 1 pit 0.5 0.5 1 0 0 0.5 0.5 bow_timb 0.5 0.5 0.25 0.5 0.7 0.2 0.3 0 0 * 0.25
let mod1 = lfNoise1Id 'α' kr 0.4 * 0.5 + 0.5
mod2 = lfNoise1Id 'β' kr 0.2 * 0.5 + 0.5
pit = lfNoise0Id 'γ' kr 0.1 `in_range` (32,44)
in X.miElements ar 0 0 1 pit 0.5 0.5 0 0.6 0 mod1 0.5 0.5 mod2 0.5 0.25 0.5 0.7 0.2 0.3 0 0 * 0.2
let gat = lfPulse kr 1 0.01 0.5
pit = sinOsc kr 5 0 * 0.1 + 53
cont = sinOsc kr 0.8 0 `in_range` (0,1)
flow = lfNoise1Id 'α' kr 0.1 `in_range` (0,1)
in X.miElements ar 0 0 gat pit 0.5 cont 0 0.5 0 flow 0.5 0.5 0.3 0.5 0.25 0.3 0.8 0.2 0.3 0 0 * 0.25
let f (_,g,x,y,z,o,rx,ry,_,_,_) =
let tr = trig1 g controlDur
pit = x * 24 + 56
stre = ry * 0.5 + 0.25
cont = y
flo = o
geo = 0.15 + (latch y tr * 0.35)
bri = 0.5 - y * 0.35
dmp = 1 - x * 0.25
pos = o * 0.5
spc = 0.5 - y * 0.5
md = 0
in X.miElements ar 0 0 g pit stre cont 0 z 0 flo 0.5 0.5 (0.25 + rx * 0.5) 0.5 geo bri dmp pos spc md 0 * 0.25
in mix (voicer 6 f) * control kr "gain" 1
let tr = dustId 'α' ar 2.5
inp = decay tr 0.01
g = X.tBrownRandId 'β' 0.5 0.9 0.2 0 (coinGateId 'γ' 0.05 tr)
space = range 0.5 1 (lfNoise1Id 'δ' kr 0.1)
in X.miElements ar 0 inp 0 40 0.5 0.2 0 0 0 0.5 0.5 0.5 0.5 0.5 g 0.4 0.9 0.2 space 0 0 * 0.35
let f (_,g,x,y,z,o,_,_,_,_,_) =
let tr = trig1 (k2a g) sampleDur
inp = decay (tr * z * 4) 0.01
pit = latch x g * 12 + 36
geo = latch y g * 0.4 + 0.5
spc = o * 0.5 + 0.5
in X.miElements ar 0 inp 0 pit 0.5 0.2 0 0 0 0.5 0.5 0.5 0.5 0.5 geo 0.4 0.9 0.2 spc 0 0
in mix (voicer 6 f) * control kr "gain" 1
let inp = decay (dustId 'α' ar 1) 0.01
g = lfNoise1Id 'β' kr 0.1 * 0.5 + 0.5
let f (_,g,x,y,z,o,rx,_,_,_,_) =
let tr = trig1 (k2a g) sampleDur
inp = decay tr 0.01
pit = x * 12 + 48
bri = latch y g
dam = latch (0.9 - z) g
md = 2
in X.miElements ar 0 inp 0 pit 0.5 0.2 0 0 0 0.5 0.5 0.5 0.5 0.5 geo bri dam 0.2 0.3 md 0
in mix (voicer 6 f) * control kr "gain" 1
let gat = coinGateId 'α' 0.4 (impulse kr 6 0)
stren = tRandId 'β' 0 1 gat
strike_timbre = lfNoise1Id 'γ' kr 0.3 * 0.5 + 0.5
let strike_timbre = lfNoise1Id 'α' kr 0.3 * 0.5 + 0.5
g = range 0.4 0.7 (lfNoise2Id 'β' kr 0.1)
maltype = 1
miElements ; easteregg : 2x2 - op FM synth
let n = lfNoise1Id 'α' kr 0.3 * 0.5 + 0.5
(r1,r2,r3) = (0.25,0.25,0.51)
easteregg
|
b4e505a3e2babf6433551a568d447acf878bfa52ff84af96f80ffd59f385770c | russmatney/org-crud | agenda.clj | (ns org-crud.agenda)
(defn print-agenda [& args]
(println "agenda" args))
| null | https://raw.githubusercontent.com/russmatney/org-crud/11069d59925461601718c4bb4c29f74126093891/src/org_crud/agenda.clj | clojure | (ns org-crud.agenda)
(defn print-agenda [& args]
(println "agenda" args))
|
|
d88beb2b200d9785494900d04646e65918d5b7f7a01414a578baca12ee45f81b | seagreen/ian | KiExperiment.hs | -- | Use:
--
-- > stack eval KiExperiment.test
module Scratch.KiExperiment where
import Control.Concurrent (forkIO, threadDelay)
import qualified Ki.Lite as Ki
import Relude
test :: IO ()
test = do
forkKiPrint
forkForkIOPrint
forever (threadDelay maxBound)
forkKiPrint :: IO ()
forkKiPrint = do
Ki.scoped $ \scope -> do
_ <- Ki.fork scope (printForever "Ki says hello")
threadDelay 1_000_000
putTextLn "Ki exit ---------------------------"
forkForkIOPrint :: IO ()
forkForkIOPrint = do
_ <- forkIO (printForever "forkIO says hello")
threadDelay 1_000_000
putTextLn "forkIO exit -----------------------"
printForever :: Text -> IO ()
printForever t =
forever $ do
putTextLn t
threadDelay 500_000
| null | https://raw.githubusercontent.com/seagreen/ian/f245fb68d94299f0e3e12744e9d1549447ad529a/haskell/src/Scratch/KiExperiment.hs | haskell | | Use:
> stack eval KiExperiment.test | module Scratch.KiExperiment where
import Control.Concurrent (forkIO, threadDelay)
import qualified Ki.Lite as Ki
import Relude
test :: IO ()
test = do
forkKiPrint
forkForkIOPrint
forever (threadDelay maxBound)
forkKiPrint :: IO ()
forkKiPrint = do
Ki.scoped $ \scope -> do
_ <- Ki.fork scope (printForever "Ki says hello")
threadDelay 1_000_000
putTextLn "Ki exit ---------------------------"
forkForkIOPrint :: IO ()
forkForkIOPrint = do
_ <- forkIO (printForever "forkIO says hello")
threadDelay 1_000_000
putTextLn "forkIO exit -----------------------"
printForever :: Text -> IO ()
printForever t =
forever $ do
putTextLn t
threadDelay 500_000
|
a116ec7d080a4d0ad1600761c2b93f937a6a779ac2b2a3836b036b2e9a2cb33a | flodihn/NextGen | sha512.erl | -module(sha512).
-export([start/0, stop/0, init/1]).
-export([hexdigest/1]).
start() ->
case erl_ddll:load_driver(".", "sha512_drv") of
ok -> ok;
{error, already_loaded} -> ok;
_ -> exit({error, could_not_load_driver})
end,
spawn(?MODULE, init, ["sha512_drv"]).
init(SharedLib) ->
register(sha512, self()),
Port = open_port({spawn, SharedLib}, []),
loop(Port).
stop() ->
sha512 ! stop.
hexdigest(Text) ->
sha512 ! {call, self(), Text},
receive
{sha512, Result} ->
hex_to_string(Result)
end.
loop(Port) ->
receive
{call, Caller, gaylord} ->
io:format("GYALORRD"),
loop(Port);
{call, Caller, Msg} ->
Port ! {self(), {command, encode(Msg)}},
receive
{Port, {data, Data}} ->
Caller ! {sha512, decode(Data)}
end,
loop(Port);
stop ->
Port ! {self(), close},
receive
{Port, closed} ->
exit(normal)
end;
{'EXIT', Port, Reason} ->
io:format("~p ~n", [Reason]),
exit(port_terminated)
end.
encode({foo, X}) -> [1, X];
encode({bar, Y}) -> [2, Y];
encode(Str) -> Str.
decode([Int]) -> Int;
decode(Str) -> Str.
hex_to_string(List) ->
hex_to_string(List, []).
hex_to_string([Head | Tail], Acc) ->
Char = io_lib:format("~2.16.0b", [Head]),
hex_to_string(Tail, lists:append(Acc, Char));
hex_to_string([], Acc) ->
lists:flatten(Acc).
| null | https://raw.githubusercontent.com/flodihn/NextGen/3da1c3ee0d8f658383bdf5fccbdd49ace3cdb323/ConnectionServer/sha512/sha512.erl | erlang | -module(sha512).
-export([start/0, stop/0, init/1]).
-export([hexdigest/1]).
start() ->
case erl_ddll:load_driver(".", "sha512_drv") of
ok -> ok;
{error, already_loaded} -> ok;
_ -> exit({error, could_not_load_driver})
end,
spawn(?MODULE, init, ["sha512_drv"]).
init(SharedLib) ->
register(sha512, self()),
Port = open_port({spawn, SharedLib}, []),
loop(Port).
stop() ->
sha512 ! stop.
hexdigest(Text) ->
sha512 ! {call, self(), Text},
receive
{sha512, Result} ->
hex_to_string(Result)
end.
loop(Port) ->
receive
{call, Caller, gaylord} ->
io:format("GYALORRD"),
loop(Port);
{call, Caller, Msg} ->
Port ! {self(), {command, encode(Msg)}},
receive
{Port, {data, Data}} ->
Caller ! {sha512, decode(Data)}
end,
loop(Port);
stop ->
Port ! {self(), close},
receive
{Port, closed} ->
exit(normal)
end;
{'EXIT', Port, Reason} ->
io:format("~p ~n", [Reason]),
exit(port_terminated)
end.
encode({foo, X}) -> [1, X];
encode({bar, Y}) -> [2, Y];
encode(Str) -> Str.
decode([Int]) -> Int;
decode(Str) -> Str.
hex_to_string(List) ->
hex_to_string(List, []).
hex_to_string([Head | Tail], Acc) ->
Char = io_lib:format("~2.16.0b", [Head]),
hex_to_string(Tail, lists:append(Acc, Char));
hex_to_string([], Acc) ->
lists:flatten(Acc).
|
|
cdee359bb1af219ad02237bafb140cf9ea1e7e586d2b370c3d18bcad85354720 | zlatozar/study-paip | prolog1.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CH11 - FIRST ; Base : 10 -*-
;;; Code from Paradigms of Artificial Intelligence Programming
Copyright ( c ) 1991
prolog1.lisp : First version of Prolog implementation
(in-package #:ch11-first)
;; Clauses are represented as (head . body) cons cells
(defun clause-head (clause) (first clause))
(defun clause-body (clause) (rest clause))
;; Clauses are stored on the predicate's plist
(defun get-clauses (pred) (get pred 'clauses))
(defun predicate (relation) (first relation))
(defvar *db-predicates* nil
"A list of all predicates stored in the database.")
(defmacro <- (&rest clause)
"Add a clause to the data base."
`(add-clause ',clause))
(defun add-clause (clause)
"Add a clause to the data base, indexed by head's predicate."
;; The predicate must be a non-variable symbol.
(let ((pred (predicate (clause-head clause))))
(assert (and (symbolp pred) (not (variable-p pred))))
(pushnew pred *db-predicates*)
(setf (get pred 'clauses)
(nconc (get-clauses pred) (list clause)))
pred))
(defun clear-db ()
"Remove all clauses (for all predicates) from the data base."
(mapc #'clear-predicate *db-predicates*))
(defun clear-predicate (predicate)
"Remove the clauses for a single predicate."
(setf (get predicate 'clauses) nil))
To prove a goal , first find all the candidate clauses for that goal . For each candidate ,
;; check if the goal unifies with the head of the clause. If it does, try to prove all the
;; goals in the body of the clause. For facts, there will be no goals in the body, so
;; success will be immediate. For rules, the goals in the body need to be proved one at a
;; time, making sure that bindings from the previous step are maintained.
(defun prove (goal bindings)
"Return a list of possible solutions to goal."
(mapcan #'(lambda (clause)
(let ((new-clause (rename-variables clause)))
(prove-all (clause-body new-clause)
(unify goal (clause-head new-clause) bindings))))
(get-clauses (predicate goal))))
(defun prove-all (goals bindings)
"Return a list of solutions to the conjunction of goals."
(cond ((eq bindings fail) fail)
((null goals) (list bindings))
(t (mapcan #'(lambda (goal1-solution)
(prove-all (rest goals) goal1-solution))
(prove (first goals) bindings)))))
;; Just as arguments to a function can have different values in different recursive calls
;; to the function, so the variables in a clause are allowed to take on different values in
;; different recursive uses.
(defun rename-variables (x)
"Replace all variables in X with new ones."
(sublis (mapcar #'(lambda (var) (cons var (gensym (string var))))
(variables-in x))
x))
(defun variables-in (exp)
"Return a list of all the variables in EXP."
(unique-find-anywhere-if #'variable-p exp))
(defun unique-find-anywhere-if (predicate tree
&optional found-so-far)
"Return a list of leaves of tree satisfying PREDICATE,
with duplicates removed."
(if (atom tree)
(if (funcall predicate tree)
(adjoin tree found-so-far)
found-so-far)
(unique-find-anywhere-if
predicate
(first tree)
(unique-find-anywhere-if predicate (rest tree)
found-so-far))))
(defun find-anywhere-if (predicate tree)
"Does PREDICATE apply to any atom in the TREE?"
(if (atom tree)
(funcall predicate tree)
(or (find-anywhere-if predicate (first tree))
(find-anywhere-if predicate (rest tree)))))
(defmacro ?- (&rest goals) `(top-level-prove ',goals))
(defun top-level-prove (goals)
"Prove the goals, and print variables readably."
(show-prolog-solutions
(variables-in goals)
(prove-all goals no-bindings)))
(defun show-prolog-solutions (vars solutions)
"Print the variables in each of the solutions."
(if (null solutions)
(format t "~&No.")
(mapc #'(lambda (solution) (show-prolog-vars vars solution))
solutions))
(values))
(defun show-prolog-vars (vars bindings)
"Print each variable with its binding."
(if (null vars)
(format t "~&Yes")
(dolist (var vars)
(format t "~&~a = ~a" var
(subst-bindings bindings var))))
(princ ";"))
| null | https://raw.githubusercontent.com/zlatozar/study-paip/dfa1ca6118f718f5d47d8c63cbb7b4cad23671e1/ch11/prolog1.lisp | lisp | Syntax : COMMON - LISP ; Package : CH11 - FIRST ; Base : 10 -*-
Code from Paradigms of Artificial Intelligence Programming
Clauses are represented as (head . body) cons cells
Clauses are stored on the predicate's plist
The predicate must be a non-variable symbol.
check if the goal unifies with the head of the clause. If it does, try to prove all the
goals in the body of the clause. For facts, there will be no goals in the body, so
success will be immediate. For rules, the goals in the body need to be proved one at a
time, making sure that bindings from the previous step are maintained.
Just as arguments to a function can have different values in different recursive calls
to the function, so the variables in a clause are allowed to take on different values in
different recursive uses. |
Copyright ( c ) 1991
prolog1.lisp : First version of Prolog implementation
(in-package #:ch11-first)
(defun clause-head (clause) (first clause))
(defun clause-body (clause) (rest clause))
(defun get-clauses (pred) (get pred 'clauses))
(defun predicate (relation) (first relation))
(defvar *db-predicates* nil
"A list of all predicates stored in the database.")
(defmacro <- (&rest clause)
"Add a clause to the data base."
`(add-clause ',clause))
(defun add-clause (clause)
"Add a clause to the data base, indexed by head's predicate."
(let ((pred (predicate (clause-head clause))))
(assert (and (symbolp pred) (not (variable-p pred))))
(pushnew pred *db-predicates*)
(setf (get pred 'clauses)
(nconc (get-clauses pred) (list clause)))
pred))
(defun clear-db ()
"Remove all clauses (for all predicates) from the data base."
(mapc #'clear-predicate *db-predicates*))
(defun clear-predicate (predicate)
"Remove the clauses for a single predicate."
(setf (get predicate 'clauses) nil))
To prove a goal , first find all the candidate clauses for that goal . For each candidate ,
(defun prove (goal bindings)
"Return a list of possible solutions to goal."
(mapcan #'(lambda (clause)
(let ((new-clause (rename-variables clause)))
(prove-all (clause-body new-clause)
(unify goal (clause-head new-clause) bindings))))
(get-clauses (predicate goal))))
(defun prove-all (goals bindings)
"Return a list of solutions to the conjunction of goals."
(cond ((eq bindings fail) fail)
((null goals) (list bindings))
(t (mapcan #'(lambda (goal1-solution)
(prove-all (rest goals) goal1-solution))
(prove (first goals) bindings)))))
(defun rename-variables (x)
"Replace all variables in X with new ones."
(sublis (mapcar #'(lambda (var) (cons var (gensym (string var))))
(variables-in x))
x))
(defun variables-in (exp)
"Return a list of all the variables in EXP."
(unique-find-anywhere-if #'variable-p exp))
(defun unique-find-anywhere-if (predicate tree
&optional found-so-far)
"Return a list of leaves of tree satisfying PREDICATE,
with duplicates removed."
(if (atom tree)
(if (funcall predicate tree)
(adjoin tree found-so-far)
found-so-far)
(unique-find-anywhere-if
predicate
(first tree)
(unique-find-anywhere-if predicate (rest tree)
found-so-far))))
(defun find-anywhere-if (predicate tree)
"Does PREDICATE apply to any atom in the TREE?"
(if (atom tree)
(funcall predicate tree)
(or (find-anywhere-if predicate (first tree))
(find-anywhere-if predicate (rest tree)))))
(defmacro ?- (&rest goals) `(top-level-prove ',goals))
(defun top-level-prove (goals)
"Prove the goals, and print variables readably."
(show-prolog-solutions
(variables-in goals)
(prove-all goals no-bindings)))
(defun show-prolog-solutions (vars solutions)
"Print the variables in each of the solutions."
(if (null solutions)
(format t "~&No.")
(mapc #'(lambda (solution) (show-prolog-vars vars solution))
solutions))
(values))
(defun show-prolog-vars (vars bindings)
"Print each variable with its binding."
(if (null vars)
(format t "~&Yes")
(dolist (var vars)
(format t "~&~a = ~a" var
(subst-bindings bindings var))))
(princ ";"))
|
75eea64562df4035cbdda7f26bc17376ea2fb69294707f1d6d6966766589c04b | mflatt/plai-typed | use-untyped.rkt | #lang racket
(require "untyped.rkt")
(define-syntax-rule (test a b)
(unless (equal? a b)
(error 'test "failed: ~.s" 'b)))
(test x '(a 2 "c" '(d)))
(test "ok" ((v-f i) "ok"))
(test add1 (v-f (v add1)))
(test #t (v? i))
(test "a" (f "a"))
(test 0 (f 0))
(test #t (ordinal? (ordinal "x")))
(test '(6 6) (apply-identity (lambda (x) 6) 5))
(test (void) (set-box! (box-number 5) 7))
(test (void) (set-box! (box-number 5) "apple"))
(test (list) (unbox boxed-null))
(test 7 (prm))
(test 18 (parameterize ([prm 18])
(get-prm)))
(test "5" ((get-prm-getter sprm)))
(test "dog?" (add-char "dog" #\?))
(test 65 (extract-first #"ABC"))
| null | https://raw.githubusercontent.com/mflatt/plai-typed/419102db1e44b74dea9daf7a75e9b0e2b9c97d05/plai-typed/tests/use-untyped.rkt | racket | #lang racket
(require "untyped.rkt")
(define-syntax-rule (test a b)
(unless (equal? a b)
(error 'test "failed: ~.s" 'b)))
(test x '(a 2 "c" '(d)))
(test "ok" ((v-f i) "ok"))
(test add1 (v-f (v add1)))
(test #t (v? i))
(test "a" (f "a"))
(test 0 (f 0))
(test #t (ordinal? (ordinal "x")))
(test '(6 6) (apply-identity (lambda (x) 6) 5))
(test (void) (set-box! (box-number 5) 7))
(test (void) (set-box! (box-number 5) "apple"))
(test (list) (unbox boxed-null))
(test 7 (prm))
(test 18 (parameterize ([prm 18])
(get-prm)))
(test "5" ((get-prm-getter sprm)))
(test "dog?" (add-char "dog" #\?))
(test 65 (extract-first #"ABC"))
|
|
96ad26f1181afcb2563d081ba69b06d52abef41454681fc4ac81aafc8d617d24 | arrayfire/arrayfire-haskell | Lex.hs | {-# LANGUAGE OverloadedStrings #-}
module Lex where
import Control.Arrow
import Data.Text (Text)
import qualified Data.Text as T
import Data.Char
import Types
symbols :: String
symbols = " *();,"
lex :: Text -> [Token]
lex = go NameMode
where
tokenize ' ' = []
tokenize '*' = [Star]
tokenize '(' = [LParen]
tokenize ')' = [RParen]
tokenize ';' = [Semi]
tokenize ',' = [Comma]
tokenize _ = []
go TokenMode xs = do
case T.uncons xs of
Nothing -> []
Just (c,cs)
| isAlpha c -> go NameMode (T.cons c cs)
| otherwise -> tokenize c ++ go TokenMode cs
go NameMode xs = do
let (match, rest) = partition xs
if match == "const"
then [] ++ go TokenMode rest
else Id match : go TokenMode rest
partition :: Text -> (Text,Text)
partition =
T.takeWhile (`notElem` symbols) &&&
T.dropWhile (`notElem` symbols)
| null | https://raw.githubusercontent.com/arrayfire/arrayfire-haskell/5d621602bb925ce5122a66011003498cbe638e2b/gen/Lex.hs | haskell | # LANGUAGE OverloadedStrings # | module Lex where
import Control.Arrow
import Data.Text (Text)
import qualified Data.Text as T
import Data.Char
import Types
symbols :: String
symbols = " *();,"
lex :: Text -> [Token]
lex = go NameMode
where
tokenize ' ' = []
tokenize '*' = [Star]
tokenize '(' = [LParen]
tokenize ')' = [RParen]
tokenize ';' = [Semi]
tokenize ',' = [Comma]
tokenize _ = []
go TokenMode xs = do
case T.uncons xs of
Nothing -> []
Just (c,cs)
| isAlpha c -> go NameMode (T.cons c cs)
| otherwise -> tokenize c ++ go TokenMode cs
go NameMode xs = do
let (match, rest) = partition xs
if match == "const"
then [] ++ go TokenMode rest
else Id match : go TokenMode rest
partition :: Text -> (Text,Text)
partition =
T.takeWhile (`notElem` symbols) &&&
T.dropWhile (`notElem` symbols)
|
2080066bfd79831a55a27591b04fd37e5e810e30563ce2a598b1a21141d9ac0b | binsec/xyntia | bitvector_test.ml | (**************************************************************************)
This file is part of BINSEC .
(* *)
Copyright ( C ) 2019 - 2022
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 ) .
(* *)
(**************************************************************************)
open OUnit2
let test_size_of _ =
let b = Bitvector.of_int32 (Int32.of_int 5) in
assert_equal 32 (Bitvector.size_of b)
let qcheck = [
QCheck.Test.make ~count:1000 ~name:"test_sgt"
QCheck.(pair int32 int32)
(fun (i1, i2) ->
let b1, b2 = Bitvector.of_int32 i1, Bitvector.of_int32 i2 in
(Bitvector.sgt b1 b2) = (i1 > i2));
]
let suite =
let ounit_suite = [
"test_sizeof">:: test_size_of;
] in
let qcheck_suite = List.map QCheck_ounit.to_ounit2_test qcheck in
"suite">:::(List.append ounit_suite qcheck_suite)
let () =
run_test_tt_main suite
| null | https://raw.githubusercontent.com/binsec/xyntia/523e4c93520843dfd6f84f0ef2cefa6dcef508e8/test/bitvector_test.ml | 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.
************************************************************************ | This file is part of BINSEC .
Copyright ( C ) 2019 - 2022
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 ) .
open OUnit2
let test_size_of _ =
let b = Bitvector.of_int32 (Int32.of_int 5) in
assert_equal 32 (Bitvector.size_of b)
let qcheck = [
QCheck.Test.make ~count:1000 ~name:"test_sgt"
QCheck.(pair int32 int32)
(fun (i1, i2) ->
let b1, b2 = Bitvector.of_int32 i1, Bitvector.of_int32 i2 in
(Bitvector.sgt b1 b2) = (i1 > i2));
]
let suite =
let ounit_suite = [
"test_sizeof">:: test_size_of;
] in
let qcheck_suite = List.map QCheck_ounit.to_ounit2_test qcheck in
"suite">:::(List.append ounit_suite qcheck_suite)
let () =
run_test_tt_main suite
|
dbe7c3bf33143b951a7bc7f1be3ce08ff2c640b2504385094e7080cf33e9d4bc | Smart-Sql/smart-sql | my_create_table_0.clj | (ns org.gridgain.plus.ddl.my-create-table-0
(:require
[org.gridgain.plus.dml.select-lexical :as my-lexical]
[org.gridgain.plus.dml.my-select-plus :as my-select]
[org.gridgain.plus.init.plus-init-sql :as plus-init-sql]
[clojure.core.reducers :as r]
[clojure.string :as str])
(:import (org.apache.ignite Ignite IgniteCache)
(com.google.common.base Strings)
(org.tools MyConvertUtil)
(cn.plus.model MyNoSqlCache MyCacheEx MyKeyValue MyLogCache SqlType)
(cn.plus.model.ddl MySchemaTable MyDataSet MyDeleteViews MyInsertViews MySelectViews MyTable MyTableIndex MyTableIndexItem MyTableItem MyTableItemPK)
(org.gridgain.ddl MyCreateTableUtil)
(java.util ArrayList Date Iterator)
(java.sql Timestamp)
(java.math BigDecimal)
)
(:gen-class
; 生成 class 的类名
:name org.gridgain.plus.dml.MyCreateTable_0
是否生成 class 的 main 方法
:main false
生成 java 静态的方法
;:methods [^:static [plus_create_table [org.apache.ignite.Ignite Long String String Long String String] void]]
))
(defn get-create-table-items
([lst] (get-create-table-items lst [] [] [] [] []))
([[f & r] create_table schema_name table_name items_line template]
(if (some? f)
(cond (empty? create_table) (recur r (conj create_table "create") schema_name table_name items_line template)
(and (not (empty? create_table)) (empty? schema_name)) (cond (and (= (count create_table) 1) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? f "table")) (recur r (conj create_table "table") schema_name table_name items_line template)
(and (= (count create_table) 2) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? (second create_table) "table")) (if (my-lexical/is-eq? f "if")
(recur r (conj create_table "if") schema_name table_name items_line template)
(recur r create_table (conj schema_name f) table_name items_line template))
(and (= (count create_table) 3) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? (nth create_table 1) "table") (my-lexical/is-eq? (nth create_table 2) "if") (my-lexical/is-eq? f "not")) (recur r (conj create_table "not") schema_name table_name items_line template)
(and (= (count create_table) 4) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? (nth create_table 1) "table") (my-lexical/is-eq? (nth create_table 2) "if") (my-lexical/is-eq? (nth create_table 3) "not") (my-lexical/is-eq? f "exists")) (recur r (conj create_table "exists") schema_name table_name items_line template)
(and (= (count create_table) 5) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? (nth create_table 1) "table") (my-lexical/is-eq? (nth create_table 2) "if") (my-lexical/is-eq? (nth create_table 3) "not") (my-lexical/is-eq? (nth create_table 4) "exists")) (recur r create_table (conj schema_name f) table_name items_line template)
:else
(throw (Exception. "Create Table 语句错误!"))
)
(and (not (empty? create_table)) (not (empty? schema_name)) (empty? table_name)) (cond (and (not (= (first schema_name) "")) (= f ".")) (recur (rest (rest r)) create_table schema_name (conj table_name (first r)) (conj items_line (second r)) template)
(and (not (= (first schema_name) "")) (= f "(")) (recur r create_table [""] [(first schema_name)] (conj items_line f) template)
:else
(throw (Exception. "Create Table 语句错误!"))
)
(and (not (empty? create_table)) (not (empty? schema_name)) (not (empty? table_name)) (not (empty? items_line)) (empty? template)) (if (and (my-lexical/is-eq? f "with") (= (count r) 1))
(recur [] create_table schema_name table_name items_line [(first r)])
(recur r create_table schema_name table_name (conj items_line f) template))
:else
(throw (Exception. "Create Table 语句错误!"))
)
{:create_table (str/join " " create_table) :schema_name (first schema_name) :table_name (first table_name) :items_line items_line :template (first template)})))
(defn get_tmp_item [^String item_line]
(if-let [items (my-lexical/to-back item_line)]
(if (and (= (count items) 3) (= (nth items 1) "="))
{:my_left (nth items 0) :my_right (nth items 2)}
(throw (Exception. (format "创建表的语句中 WITH 语句出错!位置:%s" item_line))))
(throw (Exception. (format "创建表的语句中 WITH 语句出错!位置:%s" item_line)))))
(defn get_tmp_items
([ignite lst_line] (get_tmp_items ignite lst_line [] (StringBuilder.)))
([ignite [f & r] lst sb]
(if (some? f)
(if (< (count lst) 2)
(let [{my_left :my_left my_right :my_right} (get_tmp_item f)]
(cond (.containsKey (.getTemplateConfiguration (.configuration ignite)) my_right) (recur ignite r (conj lst f) (doto sb (.append (format "%s," (.getTemplateValue (.get (.getTemplateConfiguration (.configuration ignite)) my_right))))))
(my-lexical/is-eq? my_left "AFFINITY_KEY") (recur ignite r (conj lst f) (doto sb (.append (format "AFFINITY_KEY=%s," my_right))))
:else
(throw (Exception. "创建表的语句中 WITH 语句出错!只能是 TEMPLATE=XXX,AFFINITY_KEY=YYY 这种形式"))
))
(throw (Exception. "创建表的语句中 WITH 语句出错!只能是 TEMPLATE=XXX,AFFINITY_KEY=YYY 这种形式")))
(.toString sb))))
(defn get_tmp_line [^Ignite ignite ^String template_line]
(if (re-find #"\"$" template_line)
(if-let [line (str/replace template_line #"\"$" "")]
(if-let [lst_line (str/split line #"\s*,\s*")]
(get_tmp_items ignite lst_line)
(throw (Exception. "创建表的语句中 WITH 语句出错!")))
(throw (Exception. "创建表的语句中 WITH 语句出错!")))
(throw (Exception. "创建表的语句中 WITH 语句出错!"))))
事务执行 DDL
创建一个recode 记录 ( sql un_sql )
; 形成这样的列表,当执行中有 false 就执行 un_sql,
; 来回滚事务
( defrecord ddl [ ^String sql ^String un_sql ^Boolean is_success ] )
(defn sql_lst
([lst] (sql_lst lst []))
([[f & r] rs]
(if (some? f)
(if (nil? r) (recur r (concat rs [f]))
(recur r (concat rs [f " "])))
rs)))
(defn get_sql [^String sql]
(str/join (sql_lst (my-lexical/to-back sql))))
; 获取 items 和 template
(defn get_items_tp [^String line_rs]
(if-let [items (str/split line_rs #"(?i)\s\)\sWITH\s\"")]
(if (= (count items) 2)
{:items_line (get items 0) :template (get items 1)})
(throw (Exception. "创建表的语句错误!没有 with 关键词!"))))
(defn get_items
([lst] (get_items lst [] [] []))
([[f & r] lst_stack item_stack lst]
(if (some? f)
(cond (= f "(") (recur r (conj lst_stack f) (conj item_stack f) lst)
(= f ")") (recur r (pop lst_stack) (conj item_stack f) lst)
(and (= f ",") (= (count lst_stack) 0) (> (count item_stack) 0)) (recur r lst_stack [] (conj lst item_stack))
:else
(recur r lst_stack (conj item_stack f) lst)
)
(if (> (count item_stack) 0)
(conj lst item_stack)
lst))))
(defn get_item_obj
([lst] (get_item_obj lst [] [] [] []))
([[f & r] pk_stack type_stack lst_type lst]
(if (some? f)
(cond (and (my-lexical/is-eq? f "comment") (= (first r) "(") (= (second (rest r)) ")")) (recur (rest (rest (rest r))) pk_stack type_stack lst_type (conj lst {:comment (second r)}))
(and (my-lexical/is-eq? f "PRIMARY") (my-lexical/is-eq? (first r) "KEY")) (if (> (count (rest r)) 0) (recur (rest (rest r)) (conj pk_stack (second r)) type_stack lst_type lst)
(recur nil nil type_stack lst_type (conj lst {:pk [(first lst)]})))
(and (> (count pk_stack) 0) (= f ")")) (recur r [] type_stack lst_type (conj lst {:pk (filter #(not= % ",") (rest pk_stack))}))
(and (> (count pk_stack) 0) (not= f ")")) (recur r (conj pk_stack f) type_stack lst_type lst)
(and (> (count type_stack) 0) (= f "(")) (recur r pk_stack (conj type_stack f) (conj lst_type f) lst)
(and (> (count type_stack) 0) (not= f ")")) (recur r pk_stack type_stack (conj lst_type f) lst)
(and (> (count type_stack) 0) (= f ")")) (if (= (count type_stack) 1) (recur r pk_stack [] [] (conj (pop lst) (assoc (peek lst) :vs lst_type))))
(and (my-lexical/is-eq? f "NOT") (my-lexical/is-eq? (first r) "NULL") (= (count pk_stack) 0)) (recur (rest r) pk_stack type_stack lst_type (conj lst {:not_null true}))
(my-lexical/is-eq? f "auto") (recur r pk_stack type_stack lst_type (conj lst {:auto true}))
(some? (re-find #"^(?i)float$|^(?i)double$|^(?i)long$|^(?i)integer$|^(?i)int$|^(?i)SMALLINT$|^(?i)TINYINT$|^(?i)varchar$|^(?i)varchar\(\d+\)$|^(?i)char$|^(?i)char\(\d+\)$|^(?i)BOOLEAN$|^(?i)BIGINT$|^(?i)BINARY$|^(?i)TIMESTAMP$|^(?i)Date$|^(?i)DATETIME$|^(?i)TIME$|^(?i)DECIMAL$|^(?i)REAL$|^(?i)VARBINARY$" f)) (if (= (first r) "(")
(recur (rest r) pk_stack (conj type_stack (first r)) lst_type (conj lst {:type (my-lexical/convert_to_type f)}))
(recur r pk_stack [] lst_type (conj lst {:type (my-lexical/convert_to_type f)})))
(and (my-lexical/is-eq? f "DEFAULT") (some? (first r))) (recur (rest r) pk_stack type_stack lst_type (conj lst {:default (first r)}))
:else
(recur r pk_stack type_stack lst_type (conj lst f)))
lst)))
(defn items_obj [my_items]
(loop [[f & r] my_items lst_items []]
(if (some? f)
(recur r (conj lst_items (get_item_obj f)))
lst_items)))
(defn to_item
([lst] (to_item lst (MyTableItem.) (StringBuilder.) #{}))
([[f & r] ^MyTableItem m ^StringBuilder code_line pk_set]
(if (some? f)
(cond (and (instance? String f) (= (Strings/isNullOrEmpty (.getColumn_name m)) true)) (let [column_name (str/lower-case f)]
(.setColumn_name m column_name)
(.append code_line column_name)
(recur r m code_line pk_set))
(and (instance? String f) (= (Strings/isNullOrEmpty (.getColumn_name m)) false)) (throw (Exception. (format "语句错误,位置在:%s" f)))
(and (map? f) (contains? f :pk) (= (Strings/isNullOrEmpty (.getColumn_name m)) false)) (if (= (count pk_set) 0)
(do
(.setPkid m true)
(recur r m code_line (conj pk_set (.getColumn_name m))))
(throw (Exception. "组合主键设置错误!")))
(and (map? f) (contains? f :pk) (= (Strings/isNullOrEmpty (.getColumn_name m)) true)) (recur r m code_line (concat pk_set (-> f :pk)))
(and (map? f) (contains? f :type)) (let [f-type (my-lexical/to-smart-sql-type (-> f :type))]
(.setColumn_type m f-type)
(.append code_line " ")
(.append code_line f-type)
(if (contains? f :vs)
(cond (= (count (-> f :vs)) 1) (let [len (nth (-> f :vs) 0)]
(.setColumn_len m (MyConvertUtil/ConvertToInt len))
(.append code_line "(")
(.append code_line len)
(.append code_line ")"))
(= (count (-> f :vs)) 3) (let [len (nth (-> f :vs) 0) scale (nth (-> f :vs) 2)]
(.setColumn_len m (MyConvertUtil/ConvertToInt len))
(.setScale m (MyConvertUtil/ConvertToInt scale))
(.append code_line "(")
(.append code_line len)
(.append code_line ",")
(.append code_line scale)
(.append code_line ")"))
))
(recur r m code_line pk_set))
(and (map? f) (contains? f :not_null)) (do (.setNot_null m (-> f :not_null))
(.append code_line " not null")
(recur r m code_line pk_set))
(and (map? f) (contains? f :default)) (do (.setDefault_value m (-> f :default))
(.append code_line (.concat " DEFAULT " (-> f :default)))
(recur r m code_line pk_set))
(and (map? f) (contains? f :comment)) (do (.setComment m (my-lexical/get_str_value (-> f :comment)))
(recur r m code_line pk_set))
(and (map? f) (contains? f :auto)) (do (.setAuto_increment m (-> f :auto))
(recur r m code_line pk_set))
)
(if (and (true? (.getAuto_increment m)) (not (some? (re-find #"^(?i)integer$|^(?i)int$|^(?i)SMALLINT$|^(?i)BIGINT$|^(?i)long$" (.getColumn_type m)))))
(throw (Exception. "自增长必须是 int 或者是 long 类型的!"))
{:table_item m :code code_line :pk pk_set}))))
(defn set_pk
([lst_table_item column_name] (set_pk lst_table_item column_name []))
([[f & r] ^String column_name ^ArrayList lst]
(if (some? f)
(if (my-lexical/is-eq? (.getColumn_name f) column_name)
(recur r column_name (conj lst (doto f (.setPkid true))))
(recur r column_name (conj lst f)))
lst)))
(defn set_pk_set [^ArrayList lst_table_item [f & r]]
(if (some? f)
(recur (set_pk lst_table_item f) r)
lst_table_item))
(defn item_obj [[f & r] item_name]
(if (and (some? f) (my-lexical/is-eq? (.getColumn_name f) item_name))
f
(recur r item_name)))
(defn new_pk [[f & r] lst_table_item ^StringBuilder sb]
(if (some? f)
(if-let [m (item_obj lst_table_item f)]
(do
;(.append sb (.concat (.getColumn_name m) "_pk"))
(.append sb (.concat " " (.getColumn_type m)))
(cond (and (not (nil? (.getColumn_len m))) (not (nil? (.getScale m))) (> (.getColumn_len m) 0) (> (.getScale m) 0)) (.append sb (str/join ["(" (.getColumn_len m) "," (.getScale m) ")"]))
(and (not (nil? (.getColumn_len m))) (> (.getColumn_len m) 0) ) (.append sb (str/join ["(" (.getColumn_len m) ")"]))
)
(if (= (Strings/isNullOrEmpty (.getDefault_value m)) false)
(.append sb (.concat " default " (.getDefault_value m))))
(.append sb ",")
(recur r lst_table_item sb))
(throw (Exception. "创建表的语句中主键错误!")))
(.toString sb)))
(defn pk_line
([pk_sets] (pk_line pk_sets (StringBuilder.)))
([[f & r] ^StringBuilder sb]
(if (some? f)
(if (= (count r) 0) (recur r (doto sb (.append (str/lower-case f))))
(recur r (doto sb (.append (.concat (str/lower-case f) ",")))))
(.toString sb))))
(defn get_pk_name_vs [pk_items]
(loop [[f & r] pk_items name (StringBuilder.) value (StringBuilder.)]
(if (some? f)
(if (= (count r) 0)
(recur r (doto name (.append (str/lower-case f))) (doto value (.append (str/lower-case f))))
(recur r (doto name (.append (.concat (str/lower-case f) "_"))) (doto value (.append (.concat (str/lower-case f) ",")))))
{:name (.toString name) :value (.toString value)})))
(defn get_pk_index_no_ds
([pk_sets ^String table_name] (if-let [lst_rs (get_pk_index_no_ds pk_sets table_name [])]
(if-let [{name :name value :value} (get_pk_name_vs pk_sets)]
(conj lst_rs {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_idx ON %s (%s)" table_name name table_name (str/lower-case value)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_idx" table_name name) :is_success nil})
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^String table_name lst]
(if (some? f)
(recur r table_name (conj lst {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_idx ON %s (%s)" table_name f table_name (str/lower-case f)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_idx" table_name f) :is_success nil}))
lst)))
(defn get_pk_index_ds
([pk_sets ^String schema_name ^String table_name ^String schema_name] (if-let [lst_rs (get_pk_index_ds pk_sets schema_name table_name [] schema_name)]
(if-let [{name :name value :value} (get_pk_name_vs pk_sets)]
(cond (and (= schema_name "") (not (= schema_name ""))) (conj lst_rs {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_%s_idx ON %s.%s (%s)" schema_name table_name name schema_name table_name (str/lower-case value)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_%s_idx" schema_name table_name name) :is_success nil})
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) (conj lst_rs {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_%s_idx ON %s.%s (%s)" schema_name table_name name schema_name table_name (str/lower-case value)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_%s_idx" schema_name table_name name) :is_success nil})
:else
(throw (Exception. "没有创建表语句的权限!"))
)
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^String schema_name ^String table_name lst ^String schema_name]
(if (some? f)
(cond (and (= schema_name "") (not (= schema_name ""))) (recur r schema_name table_name (conj lst {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_%s_idx ON %s.%s (%s)" schema_name table_name f schema_name table_name (str/lower-case f)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_%s_idx" schema_name table_name f) :is_success nil}) schema_name)
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) (recur r schema_name table_name (conj lst {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_%s_idx ON %s.%s (%s)" schema_name table_name f schema_name table_name (str/lower-case f)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_%s_idx" schema_name table_name f) :is_success nil}) schema_name)
:else
(throw (Exception. "没有创建表语句的权限!"))
)
lst)))
(defn get_pk_index [pk_sets ^String schema_name ^String table_name ^String schema_name]
;(get_pk_index_ds pk_sets schema_name table_name schema_name)
nil)
(defn table_items
([lst_table_item] (table_items lst_table_item []))
([[f & r] lst]
(if (some? f)
(if (not (Strings/isNullOrEmpty (.getColumn_name f)))
(recur r (conj lst f))
(recur r lst))
lst)))
(defn get_obj_ds
([items ^String schema_name ^String table_name ^String schema_name] (if-let [{lst_table_item :lst_table_item code_sb :code_sb pk_sets :pk_sets} (get_obj_ds items (ArrayList.) (StringBuilder.) #{} schema_name)]
(cond (= (count pk_sets) 1) {:lst_table_item (set_pk_set lst_table_item pk_sets) :code_sb (format "%s PRIMARY KEY (%s)" (.toString code_sb) (nth pk_sets 0))}
(> (count pk_sets) 1) (if-let [pk_set (set_pk_set lst_table_item pk_sets)]
{:lst_table_item pk_set :code_sb (format "%s PRIMARY KEY (%s)" (.toString code_sb) (pk_line pk_sets))
:indexs (get_pk_index pk_sets schema_name table_name schema_name)}
(throw (Exception. "主键设置错误!")))
:else
(throw (Exception. "主键设置错误!"))
)
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^ArrayList lst ^StringBuilder sb pk_sets schema_name]
(if (some? f)
(if-let [{table_item :table_item code_line :code pk :pk} (to_item f)]
(do (.add lst table_item)
(if (not (nil? (last (.trim (.toString code_line)))))
(.append sb (.concat (.trim (.toString code_line)) ",")))
(recur r lst sb (concat pk_sets pk) schema_name))
(throw (Exception. "创建表的语句错误!")))
{:lst_table_item (table_items lst) :code_sb sb :pk_sets pk_sets})))
(
( [ items ^String table_name ] ( if - let [ { lst_table_item : lst_table_item code_sb : code_sb pk_sets : pk_sets } ( get_obj_no_ds items ( ArrayList . ) ( StringBuilder . ) # { } ) ]
( cond (= ( count pk_sets ) 1 ) { : lst_table_item ( set_pk_set lst_table_item pk_sets ) : code_sb ( format " % s PRIMARY KEY ( % s ) " ( .toString code_sb ) ( nth pk_sets 0 ) ) }
( > ( count pk_sets ) 1 ) ( if - let [ pk_set ( set_pk_set lst_table_item pk_sets ) ]
{ : lst_table_item pk_set : code_sb ( format " % s % s PRIMARY KEY ( % s ) " ( .toString code_sb ) ( new_pk pk_sets pk_set ( StringBuilder . ) ) ( pk_line pk_sets ) )
; :indexs (get_pk_index pk_sets table_name nil)}
; (throw (Exception. "主键设置错误!")))
; :else
; (throw (Exception. "主键设置错误!"))
; )
; (throw (Exception. "创建表的语句错误!"))))
; ([[f & r] ^ArrayList lst ^StringBuilder sb pk_sets]
; (if (some? f)
; (if-let [{table_item :table_item code_line :code pk :pk} (to_item f)]
; (do (.add lst table_item)
; (if (not (nil? (last (.trim (.toString code_line)))))
; (.append sb (.concat (.trim (.toString code_line)) ",")))
; (recur r lst sb (concat pk_sets pk)))
; (throw (Exception. "创建表的语句错误!")))
; {:lst_table_item (table_items lst) :code_sb sb :pk_sets pk_sets})))
(defn get_obj [items ^String schema_name ^String table_name ^String schema_name]
(get_obj_ds items (str/lower-case schema_name) (str/lower-case table_name) (str/lower-case schema_name)))
items : " ( CategoryID INTEGER NOT NULL auto comment ( ' 产品类型ID ' ) , CategoryName VARCHAR ( 15 ) NOT NULL comment ( ' 产品类型名 ' ) , Description VARCHAR comment ( ' 类型说明 ' ) , Picture VARCHAR comment ( ' 产品样本 ' ) , PRIMARY KEY ( CategoryID ) "
items : " ( i d int PRIMARY KEY , city_id int , name , age int , company varchar "
(defn get_items_obj [items]
(when-let [my_items (items_obj (get_items (rest (my-lexical/to-back items))))]
my_items))
(defn get_items_obj_lst [items-lst]
(when-let [my_items (items_obj (get_items (drop-last 1 (rest items-lst))))]
my_items))
(defn get_template [^Ignite ignite ^String table_name ^String schema_name ^String schema_name ^String template]
(cond (and (= schema_name "") (not (= schema_name ""))) (format "%scache_name=f_%s_%s\"" (get_tmp_line ignite template) (str/lower-case schema_name) (str/lower-case table_name))
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) (format "%scache_name=f_%s_%s\"" (get_tmp_line ignite template) (str/lower-case schema_name) (str/lower-case table_name))
:else
(throw (Exception. "没有创建表语句的权限!"))
)
)
(defn get_table_line_obj [^Ignite ignite ^String sql_line ^String schema_name]
(letfn [(is-no-exists [lst]
(let [items (take 4 lst)]
(if (and (my-lexical/is-eq? (first items) "CREATE") (my-lexical/is-eq? (second items) "TABLE") (= (last items) "(") (my-lexical/is-eq? (first (take-last 2 lst)) "with"))
(if (nil? (last lst))
(throw (Exception. "创建表必须有 template 的设置!"))
(assoc (my-lexical/get-schema (nth items 2)) :create_table "CREATE TABLE" :items_line (drop-last 2 (drop 3 lst)) :template (last lst)))
)))
(is-exists [lst]
(let [items (take 7 lst)]
(if (and (my-lexical/is-eq? (first items) "CREATE") (my-lexical/is-eq? (second items) "TABLE") (my-lexical/is-eq? (nth items 2) "IF") (my-lexical/is-eq? (nth items 3) "NOT") (my-lexical/is-eq? (nth items 4) "EXISTS") (= (last items) "(") (my-lexical/is-eq? (first (take-last 2 lst)) "with"))
(assoc (my-lexical/get-schema (nth items 5)) :create_table "CREATE TABLE IF NOT EXISTS" :items_line (drop-last 2 (drop 6 lst)) :template (last lst)))))
(get-segment [lst]
(if-let [m (is-no-exists lst)]
m
(if-let [vs (is-exists lst)]
vs)))
(get-table-name [schema_name table_name]
(if (Strings/isNullOrEmpty schema_name)
table_name
(str schema_name "." table_name)))]
(let [{schema_name :schema_name table_name :table_name create_table :create_table items_line :items_line template :template} (get-segment (my-lexical/to-back sql_line)) schema_table (get-table-name schema_name table_name)]
(if-let [{lst_table_item :lst_table_item code_sb :code_sb indexs :indexs} (get_obj (get_items_obj_lst items_line) schema_name table_name schema_name)]
{:create_table create_table
:schema_name schema_name
:table_name table_name
:lst_table_item lst_table_item
:code_sb (.toString code_sb)
:indexs indexs
:template (get_template ignite table_name schema_name schema_name (str/join (rest template)))
}
(throw (Exception. "创建表的语句错误!")))
))
)
( defn get_table_line_obj_lst [ ^Ignite ignite lst ^String schema_name ]
( [ ( is - no - exists [ lst ]
( let [ items ( take 4 lst ) ]
( if ( and ( my - lexical / is - eq ? ( first items ) " CREATE " ) ( my - lexical / is - eq ? ( second items ) " TABLE " ) (= ( last items ) " ( " ) ( my - lexical / is - eq ? ( first ( take - last 2 lst ) ) " with " ) )
; (if (nil? (last lst))
( throw ( Exception . " 创建表必须有 template 的设置 ! " ) )
( assoc ( my - lexical / get - schema ( nth items 2 ) ) : create_table " CREATE TABLE " : items_line ( drop - last 2 ( drop 3 lst ) ) : template ( last lst ) ) )
; )))
; (is-exists [lst]
( let [ items ( take 7 lst ) ]
( if ( and ( my - lexical / is - eq ? ( first items ) " CREATE " ) ( my - lexical / is - eq ? ( second items ) " TABLE " ) ( my - lexical / is - eq ? ( nth items 2 ) " IF " ) ( my - lexical / is - eq ? ( nth items 3 ) " NOT " ) ( my - lexical / is - eq ? ( nth items 4 ) " EXISTS " ) (= ( last items ) " ( " ) ( my - lexical / is - eq ? ( first ( take - last 2 lst ) ) " with " ) )
( assoc ( my - lexical / get - schema ( nth items 5 ) ) : create_table " CREATE TABLE IF NOT EXISTS " : items_line ( drop - last 2 ( drop 6 lst ) ) : template ( last lst ) ) ) ) )
; (get-segment [lst]
( if - let [ m ( is - no - exists lst ) ]
; m
( if - let [ vs ( is - exists lst ) ]
; vs)))
; (get-table-name [schema_name table_name]
; (if (Strings/isNullOrEmpty schema_name)
; table_name
( str schema_name " . " table_name ) ) ) ]
; (let [{schema_name :schema_name table_name :table_name create_table :create_table items_line :items_line template :template} (get-segment lst) schema_table (get-table-name schema_name table_name)]
( if - let [ { lst_table_item : lst_table_item code_sb : ( get_obj ( get_items_obj_lst items_line ) schema_name table_name schema_name ) ]
; {:create_table create_table
; :schema_name schema_name
; :table_name table_name
: lst_table_item
; :code_sb (.toString code_sb)
:
: template ( get_template ignite table_name schema_name schema_name ( str / join ( rest template ) ) )
; }
; (throw (Exception. "创建表的语句错误!")))
; ))
; )
(defn get_table_line_obj_lst [^Ignite ignite lst ^String schema_name]
(let [{schema_name :schema_name table_name :table_name create_table :create_table items_line :items_line template :template} (get-create-table-items lst)]
(if-let [{lst_table_item :lst_table_item code_sb :code_sb indexs :indexs} (get_obj (get_items_obj_lst items_line) schema_name table_name schema_name)]
{:create_table create_table
:schema_name schema_name
:table_name table_name
:lst_table_item lst_table_item
:code_sb (.toString code_sb)
:indexs indexs
:template (get_template ignite table_name schema_name schema_name (str/join (rest template)))
}
(throw (Exception. "创建表的语句错误!")))
)
)
; json 转换为 ddl 序列
(defn to_ddl_lst [^Ignite ignite ^String sql_line ^String schema_name]
(if-let [{schema_name :schema_name create_table :create_table table_name :table_name lst_table_item :lst_table_item code_sb :code_sb indexs :indexs template :template} (get_table_line_obj ignite sql_line schema_name)]
(cond (and (= schema_name "") (not (= schema_name ""))) {:schema_name schema_name :table_name table_name :lst_table_item lst_table_item :lst_ddl (concat (conj [] {:sql (format "%s %s.%s (%s) WITH \"%s" create_table schema_name table_name code_sb template) :un_sql (format "DROP TABLE IF EXISTS %s.%s" schema_name table_name) :is_success nil}) indexs)}
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) {:schema_name schema_name :table_name table_name :lst_table_item lst_table_item :lst_ddl (concat (conj [] {:sql (format "%s %s.%s (%s) WITH \"%s" create_table schema_name table_name code_sb template) :un_sql (format "DROP TABLE IF EXISTS %s.%s" schema_name table_name) :is_success nil}) indexs)}
:else
(throw (Exception. "没有创建表语句的权限!"))
)
(throw (Exception. "创建表的语句错误!"))))
(defn get_pk_data [lst]
(loop [[f & r] lst dic-pk [] dic-data []]
(if (some? f)
(cond (true? (.getPkid f)) (recur r (conj dic-pk {:column_name (.getColumn_name f), :column_type (.getColumn_type f), :pkid true, :auto_increment (.getAuto_increment f)}) dic-data)
(false? (.getPkid f)) (recur r dic-pk (conj dic-data {:column_name (.getColumn_name f), :column_type (.getColumn_type f), :pkid false, :auto_increment (.getAuto_increment f)}))
)
{:pk dic-pk :data dic-data})))
(defn to_ddl_lsts [^Ignite ignite lst ^String schema_name]
(if-let [{schema_name-0 :schema_name create_table :create_table table_name-0 :table_name lst_table_item :lst_table_item code_sb :code_sb indexs :indexs template :template} (get_table_line_obj_lst ignite lst schema_name)]
(let [schema_name (str/lower-case schema_name-0) table_name (str/lower-case table_name-0)]
(cond (and (= schema_name "") (not (= schema_name ""))) {:schema_name schema_name :table_name table_name :pk-data (get_pk_data lst_table_item) :lst_table_item lst_table_item :lst_ddl (concat (conj [] {:sql (format "%s %s.%s (%s) WITH \"%s" create_table schema_name table_name code_sb template) :un_sql (format "DROP TABLE IF EXISTS %s.%s" schema_name table_name) :is_success nil}) indexs)}
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) {:schema_name schema_name :table_name table_name :pk-data (get_pk_data lst_table_item) :lst_table_item lst_table_item :lst_ddl (concat (conj [] {:sql (format "%s %s.%s (%s) WITH \"%s" create_table schema_name table_name code_sb template) :un_sql (format "DROP TABLE IF EXISTS %s.%s" schema_name table_name) :is_success nil}) indexs)}
:else
(throw (Exception. "没有创建表语句的权限!"))
))
(throw (Exception. "创建表的语句错误!"))))
; 生成 my_meta_tables
(defn get_table_obj [^Ignite ignite ^String table_name ^String descrip ^String code ^Long data_set_id]
(if-let [id (.incrementAndGet (.atomicSequence ignite "my_meta_tables" 0 true))]
(MyTable. id table_name descrip code data_set_id)
(throw (Exception. "数据库异常!"))))
(defn get_table_obj_lst [^Ignite ignite ^String table_name ^String descrip lst ^Long data_set_id]
(if-let [id (.incrementAndGet (.atomicSequence ignite "my_meta_tables" 0 true))]
(MyTable. id table_name descrip "" data_set_id)
(throw (Exception. "数据库异常!"))))
生成
(defn get_table_items_obj
([^Ignite ignite lst_table_item table_id] (get_table_items_obj ignite lst_table_item table_id []))
([^Ignite ignite [f & r] table_id lst]
(if (some? f)
(if-let [id (.incrementAndGet (.atomicSequence ignite "table_item" 0 true))]
(recur ignite r table_id (conj lst {:table "table_item" :key (MyTableItemPK. id table_id) :value (doto f (.setId id)
(.setTable_id table_id))}))
(throw (Exception. "数据库异常!")))
lst)))
; 生成 MyCacheEx
(defn get_my_table [^Ignite ignite ^String table_name ^String descrip ^String code lst_table_item ^Long data_set_id]
(if-let [table (get_table_obj ignite table_name descrip code data_set_id)]
(if-let [lst_items (get_table_items_obj ignite lst_table_item (.getId table))]
(cons {:table "my_meta_tables" :key (.getId table) :value table} lst_items)
(throw (Exception. "数据库异常!")))
(throw (Exception. "数据库异常!"))))
(defn get_my_table_lst [^Ignite ignite ^String table_name ^String descrip lst lst_table_item ^Long data_set_id]
(if-let [table (get_table_obj_lst ignite table_name descrip lst data_set_id)]
(if-let [lst_items (get_table_items_obj ignite lst_table_item (.getId table))]
(cons {:table "my_meta_tables" :key (.getId table) :value table} lst_items)
(throw (Exception. "数据库异常!")))
(throw (Exception. "数据库异常!"))))
(defn to_mycachex
([^Ignite ignite lst_dml_table] (to_mycachex ignite lst_dml_table (ArrayList.)))
([^Ignite ignite [f & r] lst]
(if (some? f)
(if-not (Strings/isNullOrEmpty (.getMyLogCls (.configuration ignite)))
(recur ignite r (doto lst (.add (MyCacheEx. (.cache ignite (-> f :table)) (-> f :key) (-> f :value) (SqlType/INSERT) (MyLogCache. (-> f :table) "MY_META" (-> f :table) (-> f :key) (-> f :value) (SqlType/INSERT))))))
(recur ignite r (doto lst (.add (MyCacheEx. (.cache ignite (-> f :table)) (-> f :key) (-> f :value) (SqlType/INSERT) nil)))))
lst)))
; 先执行 lst_ddl 全部成功后,在执行 lst_dml_table
; 如果 lst_dml_table 执行失败,上面的也要回滚
; lst_ddl: [ddl]
lst_dml_table : [ { : table " 表名 " : key PK_ID : value 值 } ]
转成 ArrayList 用 来执行
(defn run_ddl_dml [^Ignite ignite lst_ddl lst_dml_table no-sql-cache code]
(MyCreateTableUtil/run_ddl_dml ignite (my-lexical/to_arryList lst_ddl) lst_dml_table no-sql-cache code))
; group_id序列: group_id schema_name group_type dataset_id
(defn my_create_table_lst [^Ignite ignite group_id ^String descrip lst]
(if (= (first group_id) 0)
(if-let [{schema_name :schema_name table_name :table_name pk-data :pk-data lst_table_item :lst_table_item lst_ddl :lst_ddl} (to_ddl_lsts ignite lst (str/lower-case (second group_id)))]
(if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name))
(if-let [lst_dml_table (to_mycachex ignite (get_my_table_lst ignite table_name descrip lst lst_table_item 0))]
(if (true? (.isMultiUserGroup (.configuration ignite)))
(run_ddl_dml ignite lst_ddl lst_dml_table (MyNoSqlCache. "table_ast" schema_name table_name (MySchemaTable. schema_name table_name) pk-data (SqlType/INSERT)) (str/join " " lst)))
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "MY_META 数据集不能创建新的表!")))
(throw (Exception. "创建表的语句错误!")))
(if (contains? #{"ALL" "DDL"} (str/upper-case (nth group_id 2)))
(if-let [{schema_name :schema_name table_name :table_name pk-data :pk-data lst_table_item :lst_table_item lst_ddl :lst_ddl} (to_ddl_lsts ignite lst (str/lower-case (second group_id)))]
(if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name))
(if (and (not (my-lexical/is-eq? schema_name "my_meta")) (my-lexical/is-eq? schema_name (second group_id)))
(if-let [lst_dml_table (to_mycachex ignite (get_my_table_lst ignite table_name descrip lst lst_table_item (last group_id)))]
(if (true? (.isMultiUserGroup (.configuration ignite)))
(run_ddl_dml ignite lst_ddl lst_dml_table (MyNoSqlCache. "table_ast" schema_name table_name (MySchemaTable. schema_name table_name) pk-data (SqlType/INSERT)) (str/join " " lst)))
(throw (Exception. "创建表的语句错误!"))
))
(throw (Exception. "MY_META 数据集不能创建新的表!")))
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "该用户组没有创建表的权限!")))))
(defn my_get_obj_ds
([items] (if-let [{lst_table_item :lst_table_item code_sb :code_sb pk_sets :pk_sets} (my_get_obj_ds items (ArrayList.) (StringBuilder.) #{})]
(cond (= (count pk_sets) 1) {:lst_table_item (set_pk_set lst_table_item pk_sets) :code_sb (format "%s PRIMARY KEY (%s)" (.toString code_sb) (nth pk_sets 0))}
(> (count pk_sets) 1) (if-let [pk_set (set_pk_set lst_table_item pk_sets)]
{:lst_table_item pk_set :code_sb (format "%s PRIMARY KEY (%s)" (.toString code_sb) (pk_line pk_sets))}
(throw (Exception. "主键设置错误!")))
:else
(throw (Exception. "主键设置错误!"))
)
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^ArrayList lst ^StringBuilder sb pk_sets]
(if (some? f)
(if-let [{table_item :table_item code_line :code pk :pk} (to_item f)]
(do (.add lst table_item)
(if (not (nil? (last (.trim (.toString code_line)))))
(.append sb (.concat (.trim (.toString code_line)) ",")))
(recur r lst sb (concat pk_sets pk)))
(throw (Exception. "创建表的语句错误!")))
{:lst_table_item (table_items lst) :code_sb sb :pk_sets pk_sets})))
( defn my_create_table_lst [ ^Ignite ignite group_id ^String descrip lst ]
( if (= ( first group_id ) 0 )
( if - let [ { schema_name : schema_name table_name : table_name pk - data : pk - data lst_table_item : lst_table_item lst_ddl : lst_ddl } ( to_ddl_lsts ignite lst ( str / lower - case ( second group_id ) ) ) ]
; (if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name))
( if - let [ ( to_mycachex ignite ( get_my_table_lst ignite table_name descrip lst lst_table_item 0 ) ) ]
; (if (true? (.isMultiUserGroup (.configuration ignite)))
( run_ddl_dml ignite lst_ddl lst_dml_table ( MyNoSqlCache . " table_ast " schema_name table_name ( MySchemaTable . schema_name table_name ) pk - data ( SqlType / INSERT ) ) ( str / join " " lst ) ) )
; (throw (Exception. "创建表的语句错误!")))
( throw ( Exception . " MY_META 数据集不能创建新的表 ! " ) ) )
; (throw (Exception. "创建表的语句错误!")))
( if ( contains ? # { " ALL " " DDL " } ( str / upper - case ( nth group_id 2 ) ) )
( if - let [ { schema_name : schema_name table_name : table_name pk - data : pk - data lst_table_item : lst_table_item lst_ddl : lst_ddl } ( to_ddl_lsts ignite lst ( str / lower - case ( second group_id ) ) ) ]
; (if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name))
( if ( and ( not ( my - lexical / is - eq ? schema_name " my_meta " ) ) ( my - lexical / is - eq ? schema_name ( second group_id ) ) )
( if - let [ ( to_mycachex ignite ( get_my_table_lst ignite table_name descrip lst lst_table_item ( last group_id ) ) ) ]
; (if (true? (.isMultiUserGroup (.configuration ignite)))
( run_ddl_dml ignite lst_ddl lst_dml_table ( MyNoSqlCache . " table_ast " schema_name table_name ( MySchemaTable . schema_name table_name ) pk - data ( SqlType / INSERT ) ) ( str / join " " lst ) ) )
; (throw (Exception. "创建表的语句错误!"))
; ))
( throw ( Exception . " MY_META 数据集不能创建新的表 ! " ) ) )
; (throw (Exception. "创建表的语句错误!")))
( throw ( Exception . " 该用户组没有创建表的权限 ! " ) ) ) ) )
; group_id 列表: group_id schema_name group_type dataset_id
(defn create-table [^Ignite ignite group_id ^String descrip sql-line]
(my_create_table_lst ignite group_id descrip (my-lexical/to-back sql-line)))
; 用户 meta table 获取 ast
(defn get-meta-pk-data [^String sql]
(letfn [(meta_table_line_obj_lst [lst ^String schema_name]
(let [{schema_name :schema_name table_name :table_name create_table :create_table items_line :items_line template :template} (get-create-table-items lst)]
(if-let [{lst_table_item :lst_table_item code_sb :code_sb indexs :indexs} (get_obj (get_items_obj_lst items_line) schema_name table_name schema_name)]
{:create_table create_table
:schema_name schema_name
:table_name table_name
:lst_table_item lst_table_item
}
(throw (Exception. "创建表的语句错误!")))
)
)]
(let [{table_name :table_name lst_table_item :lst_table_item} (meta_table_line_obj_lst (my-lexical/to-back sql) "MY_META")]
{:schema_name "MY_META" :table_name table_name :value (get_pk_data lst_table_item)})))
java 中调用
( defn -plus_create_table [ ^Ignite ignite ^Long group_id ^String schema_name group_type ^Long dataset_id ^String descrip ^String code ]
; (my_create_table ignite group_id schema_name group_type dataset_id descrip code))
| null | https://raw.githubusercontent.com/Smart-Sql/smart-sql/d2f237f935472942a143816925221cdcf8246aff/src/main/clojure/org/gridgain/plus/ddl/my_create_table_0.clj | clojure | 生成 class 的类名
:methods [^:static [plus_create_table [org.apache.ignite.Ignite Long String String Long String String] void]]
形成这样的列表,当执行中有 false 就执行 un_sql,
来回滚事务
获取 items 和 template
(.append sb (.concat (.getColumn_name m) "_pk"))
(get_pk_index_ds pk_sets schema_name table_name schema_name)
:indexs (get_pk_index pk_sets table_name nil)}
(throw (Exception. "主键设置错误!")))
:else
(throw (Exception. "主键设置错误!"))
)
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^ArrayList lst ^StringBuilder sb pk_sets]
(if (some? f)
(if-let [{table_item :table_item code_line :code pk :pk} (to_item f)]
(do (.add lst table_item)
(if (not (nil? (last (.trim (.toString code_line)))))
(.append sb (.concat (.trim (.toString code_line)) ",")))
(recur r lst sb (concat pk_sets pk)))
(throw (Exception. "创建表的语句错误!")))
{:lst_table_item (table_items lst) :code_sb sb :pk_sets pk_sets})))
(if (nil? (last lst))
)))
(is-exists [lst]
(get-segment [lst]
m
vs)))
(get-table-name [schema_name table_name]
(if (Strings/isNullOrEmpty schema_name)
table_name
(let [{schema_name :schema_name table_name :table_name create_table :create_table items_line :items_line template :template} (get-segment lst) schema_table (get-table-name schema_name table_name)]
{:create_table create_table
:schema_name schema_name
:table_name table_name
:code_sb (.toString code_sb)
}
(throw (Exception. "创建表的语句错误!")))
))
)
json 转换为 ddl 序列
生成 my_meta_tables
生成 MyCacheEx
先执行 lst_ddl 全部成功后,在执行 lst_dml_table
如果 lst_dml_table 执行失败,上面的也要回滚
lst_ddl: [ddl]
group_id序列: group_id schema_name group_type dataset_id
(if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name))
(if (true? (.isMultiUserGroup (.configuration ignite)))
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "创建表的语句错误!")))
(if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name))
(if (true? (.isMultiUserGroup (.configuration ignite)))
(throw (Exception. "创建表的语句错误!"))
))
(throw (Exception. "创建表的语句错误!")))
group_id 列表: group_id schema_name group_type dataset_id
用户 meta table 获取 ast
(my_create_table ignite group_id schema_name group_type dataset_id descrip code)) | (ns org.gridgain.plus.ddl.my-create-table-0
(:require
[org.gridgain.plus.dml.select-lexical :as my-lexical]
[org.gridgain.plus.dml.my-select-plus :as my-select]
[org.gridgain.plus.init.plus-init-sql :as plus-init-sql]
[clojure.core.reducers :as r]
[clojure.string :as str])
(:import (org.apache.ignite Ignite IgniteCache)
(com.google.common.base Strings)
(org.tools MyConvertUtil)
(cn.plus.model MyNoSqlCache MyCacheEx MyKeyValue MyLogCache SqlType)
(cn.plus.model.ddl MySchemaTable MyDataSet MyDeleteViews MyInsertViews MySelectViews MyTable MyTableIndex MyTableIndexItem MyTableItem MyTableItemPK)
(org.gridgain.ddl MyCreateTableUtil)
(java.util ArrayList Date Iterator)
(java.sql Timestamp)
(java.math BigDecimal)
)
(:gen-class
:name org.gridgain.plus.dml.MyCreateTable_0
是否生成 class 的 main 方法
:main false
生成 java 静态的方法
))
(defn get-create-table-items
([lst] (get-create-table-items lst [] [] [] [] []))
([[f & r] create_table schema_name table_name items_line template]
(if (some? f)
(cond (empty? create_table) (recur r (conj create_table "create") schema_name table_name items_line template)
(and (not (empty? create_table)) (empty? schema_name)) (cond (and (= (count create_table) 1) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? f "table")) (recur r (conj create_table "table") schema_name table_name items_line template)
(and (= (count create_table) 2) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? (second create_table) "table")) (if (my-lexical/is-eq? f "if")
(recur r (conj create_table "if") schema_name table_name items_line template)
(recur r create_table (conj schema_name f) table_name items_line template))
(and (= (count create_table) 3) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? (nth create_table 1) "table") (my-lexical/is-eq? (nth create_table 2) "if") (my-lexical/is-eq? f "not")) (recur r (conj create_table "not") schema_name table_name items_line template)
(and (= (count create_table) 4) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? (nth create_table 1) "table") (my-lexical/is-eq? (nth create_table 2) "if") (my-lexical/is-eq? (nth create_table 3) "not") (my-lexical/is-eq? f "exists")) (recur r (conj create_table "exists") schema_name table_name items_line template)
(and (= (count create_table) 5) (my-lexical/is-eq? (first create_table) "create") (my-lexical/is-eq? (nth create_table 1) "table") (my-lexical/is-eq? (nth create_table 2) "if") (my-lexical/is-eq? (nth create_table 3) "not") (my-lexical/is-eq? (nth create_table 4) "exists")) (recur r create_table (conj schema_name f) table_name items_line template)
:else
(throw (Exception. "Create Table 语句错误!"))
)
(and (not (empty? create_table)) (not (empty? schema_name)) (empty? table_name)) (cond (and (not (= (first schema_name) "")) (= f ".")) (recur (rest (rest r)) create_table schema_name (conj table_name (first r)) (conj items_line (second r)) template)
(and (not (= (first schema_name) "")) (= f "(")) (recur r create_table [""] [(first schema_name)] (conj items_line f) template)
:else
(throw (Exception. "Create Table 语句错误!"))
)
(and (not (empty? create_table)) (not (empty? schema_name)) (not (empty? table_name)) (not (empty? items_line)) (empty? template)) (if (and (my-lexical/is-eq? f "with") (= (count r) 1))
(recur [] create_table schema_name table_name items_line [(first r)])
(recur r create_table schema_name table_name (conj items_line f) template))
:else
(throw (Exception. "Create Table 语句错误!"))
)
{:create_table (str/join " " create_table) :schema_name (first schema_name) :table_name (first table_name) :items_line items_line :template (first template)})))
(defn get_tmp_item [^String item_line]
(if-let [items (my-lexical/to-back item_line)]
(if (and (= (count items) 3) (= (nth items 1) "="))
{:my_left (nth items 0) :my_right (nth items 2)}
(throw (Exception. (format "创建表的语句中 WITH 语句出错!位置:%s" item_line))))
(throw (Exception. (format "创建表的语句中 WITH 语句出错!位置:%s" item_line)))))
(defn get_tmp_items
([ignite lst_line] (get_tmp_items ignite lst_line [] (StringBuilder.)))
([ignite [f & r] lst sb]
(if (some? f)
(if (< (count lst) 2)
(let [{my_left :my_left my_right :my_right} (get_tmp_item f)]
(cond (.containsKey (.getTemplateConfiguration (.configuration ignite)) my_right) (recur ignite r (conj lst f) (doto sb (.append (format "%s," (.getTemplateValue (.get (.getTemplateConfiguration (.configuration ignite)) my_right))))))
(my-lexical/is-eq? my_left "AFFINITY_KEY") (recur ignite r (conj lst f) (doto sb (.append (format "AFFINITY_KEY=%s," my_right))))
:else
(throw (Exception. "创建表的语句中 WITH 语句出错!只能是 TEMPLATE=XXX,AFFINITY_KEY=YYY 这种形式"))
))
(throw (Exception. "创建表的语句中 WITH 语句出错!只能是 TEMPLATE=XXX,AFFINITY_KEY=YYY 这种形式")))
(.toString sb))))
(defn get_tmp_line [^Ignite ignite ^String template_line]
(if (re-find #"\"$" template_line)
(if-let [line (str/replace template_line #"\"$" "")]
(if-let [lst_line (str/split line #"\s*,\s*")]
(get_tmp_items ignite lst_line)
(throw (Exception. "创建表的语句中 WITH 语句出错!")))
(throw (Exception. "创建表的语句中 WITH 语句出错!")))
(throw (Exception. "创建表的语句中 WITH 语句出错!"))))
事务执行 DDL
创建一个recode 记录 ( sql un_sql )
( defrecord ddl [ ^String sql ^String un_sql ^Boolean is_success ] )
(defn sql_lst
([lst] (sql_lst lst []))
([[f & r] rs]
(if (some? f)
(if (nil? r) (recur r (concat rs [f]))
(recur r (concat rs [f " "])))
rs)))
(defn get_sql [^String sql]
(str/join (sql_lst (my-lexical/to-back sql))))
(defn get_items_tp [^String line_rs]
(if-let [items (str/split line_rs #"(?i)\s\)\sWITH\s\"")]
(if (= (count items) 2)
{:items_line (get items 0) :template (get items 1)})
(throw (Exception. "创建表的语句错误!没有 with 关键词!"))))
(defn get_items
([lst] (get_items lst [] [] []))
([[f & r] lst_stack item_stack lst]
(if (some? f)
(cond (= f "(") (recur r (conj lst_stack f) (conj item_stack f) lst)
(= f ")") (recur r (pop lst_stack) (conj item_stack f) lst)
(and (= f ",") (= (count lst_stack) 0) (> (count item_stack) 0)) (recur r lst_stack [] (conj lst item_stack))
:else
(recur r lst_stack (conj item_stack f) lst)
)
(if (> (count item_stack) 0)
(conj lst item_stack)
lst))))
(defn get_item_obj
([lst] (get_item_obj lst [] [] [] []))
([[f & r] pk_stack type_stack lst_type lst]
(if (some? f)
(cond (and (my-lexical/is-eq? f "comment") (= (first r) "(") (= (second (rest r)) ")")) (recur (rest (rest (rest r))) pk_stack type_stack lst_type (conj lst {:comment (second r)}))
(and (my-lexical/is-eq? f "PRIMARY") (my-lexical/is-eq? (first r) "KEY")) (if (> (count (rest r)) 0) (recur (rest (rest r)) (conj pk_stack (second r)) type_stack lst_type lst)
(recur nil nil type_stack lst_type (conj lst {:pk [(first lst)]})))
(and (> (count pk_stack) 0) (= f ")")) (recur r [] type_stack lst_type (conj lst {:pk (filter #(not= % ",") (rest pk_stack))}))
(and (> (count pk_stack) 0) (not= f ")")) (recur r (conj pk_stack f) type_stack lst_type lst)
(and (> (count type_stack) 0) (= f "(")) (recur r pk_stack (conj type_stack f) (conj lst_type f) lst)
(and (> (count type_stack) 0) (not= f ")")) (recur r pk_stack type_stack (conj lst_type f) lst)
(and (> (count type_stack) 0) (= f ")")) (if (= (count type_stack) 1) (recur r pk_stack [] [] (conj (pop lst) (assoc (peek lst) :vs lst_type))))
(and (my-lexical/is-eq? f "NOT") (my-lexical/is-eq? (first r) "NULL") (= (count pk_stack) 0)) (recur (rest r) pk_stack type_stack lst_type (conj lst {:not_null true}))
(my-lexical/is-eq? f "auto") (recur r pk_stack type_stack lst_type (conj lst {:auto true}))
(some? (re-find #"^(?i)float$|^(?i)double$|^(?i)long$|^(?i)integer$|^(?i)int$|^(?i)SMALLINT$|^(?i)TINYINT$|^(?i)varchar$|^(?i)varchar\(\d+\)$|^(?i)char$|^(?i)char\(\d+\)$|^(?i)BOOLEAN$|^(?i)BIGINT$|^(?i)BINARY$|^(?i)TIMESTAMP$|^(?i)Date$|^(?i)DATETIME$|^(?i)TIME$|^(?i)DECIMAL$|^(?i)REAL$|^(?i)VARBINARY$" f)) (if (= (first r) "(")
(recur (rest r) pk_stack (conj type_stack (first r)) lst_type (conj lst {:type (my-lexical/convert_to_type f)}))
(recur r pk_stack [] lst_type (conj lst {:type (my-lexical/convert_to_type f)})))
(and (my-lexical/is-eq? f "DEFAULT") (some? (first r))) (recur (rest r) pk_stack type_stack lst_type (conj lst {:default (first r)}))
:else
(recur r pk_stack type_stack lst_type (conj lst f)))
lst)))
(defn items_obj [my_items]
(loop [[f & r] my_items lst_items []]
(if (some? f)
(recur r (conj lst_items (get_item_obj f)))
lst_items)))
(defn to_item
([lst] (to_item lst (MyTableItem.) (StringBuilder.) #{}))
([[f & r] ^MyTableItem m ^StringBuilder code_line pk_set]
(if (some? f)
(cond (and (instance? String f) (= (Strings/isNullOrEmpty (.getColumn_name m)) true)) (let [column_name (str/lower-case f)]
(.setColumn_name m column_name)
(.append code_line column_name)
(recur r m code_line pk_set))
(and (instance? String f) (= (Strings/isNullOrEmpty (.getColumn_name m)) false)) (throw (Exception. (format "语句错误,位置在:%s" f)))
(and (map? f) (contains? f :pk) (= (Strings/isNullOrEmpty (.getColumn_name m)) false)) (if (= (count pk_set) 0)
(do
(.setPkid m true)
(recur r m code_line (conj pk_set (.getColumn_name m))))
(throw (Exception. "组合主键设置错误!")))
(and (map? f) (contains? f :pk) (= (Strings/isNullOrEmpty (.getColumn_name m)) true)) (recur r m code_line (concat pk_set (-> f :pk)))
(and (map? f) (contains? f :type)) (let [f-type (my-lexical/to-smart-sql-type (-> f :type))]
(.setColumn_type m f-type)
(.append code_line " ")
(.append code_line f-type)
(if (contains? f :vs)
(cond (= (count (-> f :vs)) 1) (let [len (nth (-> f :vs) 0)]
(.setColumn_len m (MyConvertUtil/ConvertToInt len))
(.append code_line "(")
(.append code_line len)
(.append code_line ")"))
(= (count (-> f :vs)) 3) (let [len (nth (-> f :vs) 0) scale (nth (-> f :vs) 2)]
(.setColumn_len m (MyConvertUtil/ConvertToInt len))
(.setScale m (MyConvertUtil/ConvertToInt scale))
(.append code_line "(")
(.append code_line len)
(.append code_line ",")
(.append code_line scale)
(.append code_line ")"))
))
(recur r m code_line pk_set))
(and (map? f) (contains? f :not_null)) (do (.setNot_null m (-> f :not_null))
(.append code_line " not null")
(recur r m code_line pk_set))
(and (map? f) (contains? f :default)) (do (.setDefault_value m (-> f :default))
(.append code_line (.concat " DEFAULT " (-> f :default)))
(recur r m code_line pk_set))
(and (map? f) (contains? f :comment)) (do (.setComment m (my-lexical/get_str_value (-> f :comment)))
(recur r m code_line pk_set))
(and (map? f) (contains? f :auto)) (do (.setAuto_increment m (-> f :auto))
(recur r m code_line pk_set))
)
(if (and (true? (.getAuto_increment m)) (not (some? (re-find #"^(?i)integer$|^(?i)int$|^(?i)SMALLINT$|^(?i)BIGINT$|^(?i)long$" (.getColumn_type m)))))
(throw (Exception. "自增长必须是 int 或者是 long 类型的!"))
{:table_item m :code code_line :pk pk_set}))))
(defn set_pk
([lst_table_item column_name] (set_pk lst_table_item column_name []))
([[f & r] ^String column_name ^ArrayList lst]
(if (some? f)
(if (my-lexical/is-eq? (.getColumn_name f) column_name)
(recur r column_name (conj lst (doto f (.setPkid true))))
(recur r column_name (conj lst f)))
lst)))
(defn set_pk_set [^ArrayList lst_table_item [f & r]]
(if (some? f)
(recur (set_pk lst_table_item f) r)
lst_table_item))
(defn item_obj [[f & r] item_name]
(if (and (some? f) (my-lexical/is-eq? (.getColumn_name f) item_name))
f
(recur r item_name)))
(defn new_pk [[f & r] lst_table_item ^StringBuilder sb]
(if (some? f)
(if-let [m (item_obj lst_table_item f)]
(do
(.append sb (.concat " " (.getColumn_type m)))
(cond (and (not (nil? (.getColumn_len m))) (not (nil? (.getScale m))) (> (.getColumn_len m) 0) (> (.getScale m) 0)) (.append sb (str/join ["(" (.getColumn_len m) "," (.getScale m) ")"]))
(and (not (nil? (.getColumn_len m))) (> (.getColumn_len m) 0) ) (.append sb (str/join ["(" (.getColumn_len m) ")"]))
)
(if (= (Strings/isNullOrEmpty (.getDefault_value m)) false)
(.append sb (.concat " default " (.getDefault_value m))))
(.append sb ",")
(recur r lst_table_item sb))
(throw (Exception. "创建表的语句中主键错误!")))
(.toString sb)))
(defn pk_line
([pk_sets] (pk_line pk_sets (StringBuilder.)))
([[f & r] ^StringBuilder sb]
(if (some? f)
(if (= (count r) 0) (recur r (doto sb (.append (str/lower-case f))))
(recur r (doto sb (.append (.concat (str/lower-case f) ",")))))
(.toString sb))))
(defn get_pk_name_vs [pk_items]
(loop [[f & r] pk_items name (StringBuilder.) value (StringBuilder.)]
(if (some? f)
(if (= (count r) 0)
(recur r (doto name (.append (str/lower-case f))) (doto value (.append (str/lower-case f))))
(recur r (doto name (.append (.concat (str/lower-case f) "_"))) (doto value (.append (.concat (str/lower-case f) ",")))))
{:name (.toString name) :value (.toString value)})))
(defn get_pk_index_no_ds
([pk_sets ^String table_name] (if-let [lst_rs (get_pk_index_no_ds pk_sets table_name [])]
(if-let [{name :name value :value} (get_pk_name_vs pk_sets)]
(conj lst_rs {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_idx ON %s (%s)" table_name name table_name (str/lower-case value)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_idx" table_name name) :is_success nil})
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^String table_name lst]
(if (some? f)
(recur r table_name (conj lst {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_idx ON %s (%s)" table_name f table_name (str/lower-case f)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_idx" table_name f) :is_success nil}))
lst)))
(defn get_pk_index_ds
([pk_sets ^String schema_name ^String table_name ^String schema_name] (if-let [lst_rs (get_pk_index_ds pk_sets schema_name table_name [] schema_name)]
(if-let [{name :name value :value} (get_pk_name_vs pk_sets)]
(cond (and (= schema_name "") (not (= schema_name ""))) (conj lst_rs {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_%s_idx ON %s.%s (%s)" schema_name table_name name schema_name table_name (str/lower-case value)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_%s_idx" schema_name table_name name) :is_success nil})
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) (conj lst_rs {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_%s_idx ON %s.%s (%s)" schema_name table_name name schema_name table_name (str/lower-case value)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_%s_idx" schema_name table_name name) :is_success nil})
:else
(throw (Exception. "没有创建表语句的权限!"))
)
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^String schema_name ^String table_name lst ^String schema_name]
(if (some? f)
(cond (and (= schema_name "") (not (= schema_name ""))) (recur r schema_name table_name (conj lst {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_%s_idx ON %s.%s (%s)" schema_name table_name f schema_name table_name (str/lower-case f)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_%s_idx" schema_name table_name f) :is_success nil}) schema_name)
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) (recur r schema_name table_name (conj lst {:sql (format "CREATE INDEX IF NOT EXISTS %s_%s_%s_idx ON %s.%s (%s)" schema_name table_name f schema_name table_name (str/lower-case f)) :un_sql (format "DROP INDEX IF EXISTS %s_%s_%s_idx" schema_name table_name f) :is_success nil}) schema_name)
:else
(throw (Exception. "没有创建表语句的权限!"))
)
lst)))
(defn get_pk_index [pk_sets ^String schema_name ^String table_name ^String schema_name]
nil)
(defn table_items
([lst_table_item] (table_items lst_table_item []))
([[f & r] lst]
(if (some? f)
(if (not (Strings/isNullOrEmpty (.getColumn_name f)))
(recur r (conj lst f))
(recur r lst))
lst)))
(defn get_obj_ds
([items ^String schema_name ^String table_name ^String schema_name] (if-let [{lst_table_item :lst_table_item code_sb :code_sb pk_sets :pk_sets} (get_obj_ds items (ArrayList.) (StringBuilder.) #{} schema_name)]
(cond (= (count pk_sets) 1) {:lst_table_item (set_pk_set lst_table_item pk_sets) :code_sb (format "%s PRIMARY KEY (%s)" (.toString code_sb) (nth pk_sets 0))}
(> (count pk_sets) 1) (if-let [pk_set (set_pk_set lst_table_item pk_sets)]
{:lst_table_item pk_set :code_sb (format "%s PRIMARY KEY (%s)" (.toString code_sb) (pk_line pk_sets))
:indexs (get_pk_index pk_sets schema_name table_name schema_name)}
(throw (Exception. "主键设置错误!")))
:else
(throw (Exception. "主键设置错误!"))
)
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^ArrayList lst ^StringBuilder sb pk_sets schema_name]
(if (some? f)
(if-let [{table_item :table_item code_line :code pk :pk} (to_item f)]
(do (.add lst table_item)
(if (not (nil? (last (.trim (.toString code_line)))))
(.append sb (.concat (.trim (.toString code_line)) ",")))
(recur r lst sb (concat pk_sets pk) schema_name))
(throw (Exception. "创建表的语句错误!")))
{:lst_table_item (table_items lst) :code_sb sb :pk_sets pk_sets})))
(
( [ items ^String table_name ] ( if - let [ { lst_table_item : lst_table_item code_sb : code_sb pk_sets : pk_sets } ( get_obj_no_ds items ( ArrayList . ) ( StringBuilder . ) # { } ) ]
( cond (= ( count pk_sets ) 1 ) { : lst_table_item ( set_pk_set lst_table_item pk_sets ) : code_sb ( format " % s PRIMARY KEY ( % s ) " ( .toString code_sb ) ( nth pk_sets 0 ) ) }
( > ( count pk_sets ) 1 ) ( if - let [ pk_set ( set_pk_set lst_table_item pk_sets ) ]
{ : lst_table_item pk_set : code_sb ( format " % s % s PRIMARY KEY ( % s ) " ( .toString code_sb ) ( new_pk pk_sets pk_set ( StringBuilder . ) ) ( pk_line pk_sets ) )
(defn get_obj [items ^String schema_name ^String table_name ^String schema_name]
(get_obj_ds items (str/lower-case schema_name) (str/lower-case table_name) (str/lower-case schema_name)))
items : " ( CategoryID INTEGER NOT NULL auto comment ( ' 产品类型ID ' ) , CategoryName VARCHAR ( 15 ) NOT NULL comment ( ' 产品类型名 ' ) , Description VARCHAR comment ( ' 类型说明 ' ) , Picture VARCHAR comment ( ' 产品样本 ' ) , PRIMARY KEY ( CategoryID ) "
items : " ( i d int PRIMARY KEY , city_id int , name , age int , company varchar "
(defn get_items_obj [items]
(when-let [my_items (items_obj (get_items (rest (my-lexical/to-back items))))]
my_items))
(defn get_items_obj_lst [items-lst]
(when-let [my_items (items_obj (get_items (drop-last 1 (rest items-lst))))]
my_items))
(defn get_template [^Ignite ignite ^String table_name ^String schema_name ^String schema_name ^String template]
(cond (and (= schema_name "") (not (= schema_name ""))) (format "%scache_name=f_%s_%s\"" (get_tmp_line ignite template) (str/lower-case schema_name) (str/lower-case table_name))
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) (format "%scache_name=f_%s_%s\"" (get_tmp_line ignite template) (str/lower-case schema_name) (str/lower-case table_name))
:else
(throw (Exception. "没有创建表语句的权限!"))
)
)
(defn get_table_line_obj [^Ignite ignite ^String sql_line ^String schema_name]
(letfn [(is-no-exists [lst]
(let [items (take 4 lst)]
(if (and (my-lexical/is-eq? (first items) "CREATE") (my-lexical/is-eq? (second items) "TABLE") (= (last items) "(") (my-lexical/is-eq? (first (take-last 2 lst)) "with"))
(if (nil? (last lst))
(throw (Exception. "创建表必须有 template 的设置!"))
(assoc (my-lexical/get-schema (nth items 2)) :create_table "CREATE TABLE" :items_line (drop-last 2 (drop 3 lst)) :template (last lst)))
)))
(is-exists [lst]
(let [items (take 7 lst)]
(if (and (my-lexical/is-eq? (first items) "CREATE") (my-lexical/is-eq? (second items) "TABLE") (my-lexical/is-eq? (nth items 2) "IF") (my-lexical/is-eq? (nth items 3) "NOT") (my-lexical/is-eq? (nth items 4) "EXISTS") (= (last items) "(") (my-lexical/is-eq? (first (take-last 2 lst)) "with"))
(assoc (my-lexical/get-schema (nth items 5)) :create_table "CREATE TABLE IF NOT EXISTS" :items_line (drop-last 2 (drop 6 lst)) :template (last lst)))))
(get-segment [lst]
(if-let [m (is-no-exists lst)]
m
(if-let [vs (is-exists lst)]
vs)))
(get-table-name [schema_name table_name]
(if (Strings/isNullOrEmpty schema_name)
table_name
(str schema_name "." table_name)))]
(let [{schema_name :schema_name table_name :table_name create_table :create_table items_line :items_line template :template} (get-segment (my-lexical/to-back sql_line)) schema_table (get-table-name schema_name table_name)]
(if-let [{lst_table_item :lst_table_item code_sb :code_sb indexs :indexs} (get_obj (get_items_obj_lst items_line) schema_name table_name schema_name)]
{:create_table create_table
:schema_name schema_name
:table_name table_name
:lst_table_item lst_table_item
:code_sb (.toString code_sb)
:indexs indexs
:template (get_template ignite table_name schema_name schema_name (str/join (rest template)))
}
(throw (Exception. "创建表的语句错误!")))
))
)
( defn get_table_line_obj_lst [ ^Ignite ignite lst ^String schema_name ]
( [ ( is - no - exists [ lst ]
( let [ items ( take 4 lst ) ]
( if ( and ( my - lexical / is - eq ? ( first items ) " CREATE " ) ( my - lexical / is - eq ? ( second items ) " TABLE " ) (= ( last items ) " ( " ) ( my - lexical / is - eq ? ( first ( take - last 2 lst ) ) " with " ) )
( throw ( Exception . " 创建表必须有 template 的设置 ! " ) )
( assoc ( my - lexical / get - schema ( nth items 2 ) ) : create_table " CREATE TABLE " : items_line ( drop - last 2 ( drop 3 lst ) ) : template ( last lst ) ) )
( let [ items ( take 7 lst ) ]
( if ( and ( my - lexical / is - eq ? ( first items ) " CREATE " ) ( my - lexical / is - eq ? ( second items ) " TABLE " ) ( my - lexical / is - eq ? ( nth items 2 ) " IF " ) ( my - lexical / is - eq ? ( nth items 3 ) " NOT " ) ( my - lexical / is - eq ? ( nth items 4 ) " EXISTS " ) (= ( last items ) " ( " ) ( my - lexical / is - eq ? ( first ( take - last 2 lst ) ) " with " ) )
( assoc ( my - lexical / get - schema ( nth items 5 ) ) : create_table " CREATE TABLE IF NOT EXISTS " : items_line ( drop - last 2 ( drop 6 lst ) ) : template ( last lst ) ) ) ) )
( if - let [ m ( is - no - exists lst ) ]
( if - let [ vs ( is - exists lst ) ]
( str schema_name " . " table_name ) ) ) ]
( if - let [ { lst_table_item : lst_table_item code_sb : ( get_obj ( get_items_obj_lst items_line ) schema_name table_name schema_name ) ]
: lst_table_item
:
: template ( get_template ignite table_name schema_name schema_name ( str / join ( rest template ) ) )
(defn get_table_line_obj_lst [^Ignite ignite lst ^String schema_name]
(let [{schema_name :schema_name table_name :table_name create_table :create_table items_line :items_line template :template} (get-create-table-items lst)]
(if-let [{lst_table_item :lst_table_item code_sb :code_sb indexs :indexs} (get_obj (get_items_obj_lst items_line) schema_name table_name schema_name)]
{:create_table create_table
:schema_name schema_name
:table_name table_name
:lst_table_item lst_table_item
:code_sb (.toString code_sb)
:indexs indexs
:template (get_template ignite table_name schema_name schema_name (str/join (rest template)))
}
(throw (Exception. "创建表的语句错误!")))
)
)
(defn to_ddl_lst [^Ignite ignite ^String sql_line ^String schema_name]
(if-let [{schema_name :schema_name create_table :create_table table_name :table_name lst_table_item :lst_table_item code_sb :code_sb indexs :indexs template :template} (get_table_line_obj ignite sql_line schema_name)]
(cond (and (= schema_name "") (not (= schema_name ""))) {:schema_name schema_name :table_name table_name :lst_table_item lst_table_item :lst_ddl (concat (conj [] {:sql (format "%s %s.%s (%s) WITH \"%s" create_table schema_name table_name code_sb template) :un_sql (format "DROP TABLE IF EXISTS %s.%s" schema_name table_name) :is_success nil}) indexs)}
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) {:schema_name schema_name :table_name table_name :lst_table_item lst_table_item :lst_ddl (concat (conj [] {:sql (format "%s %s.%s (%s) WITH \"%s" create_table schema_name table_name code_sb template) :un_sql (format "DROP TABLE IF EXISTS %s.%s" schema_name table_name) :is_success nil}) indexs)}
:else
(throw (Exception. "没有创建表语句的权限!"))
)
(throw (Exception. "创建表的语句错误!"))))
(defn get_pk_data [lst]
(loop [[f & r] lst dic-pk [] dic-data []]
(if (some? f)
(cond (true? (.getPkid f)) (recur r (conj dic-pk {:column_name (.getColumn_name f), :column_type (.getColumn_type f), :pkid true, :auto_increment (.getAuto_increment f)}) dic-data)
(false? (.getPkid f)) (recur r dic-pk (conj dic-data {:column_name (.getColumn_name f), :column_type (.getColumn_type f), :pkid false, :auto_increment (.getAuto_increment f)}))
)
{:pk dic-pk :data dic-data})))
(defn to_ddl_lsts [^Ignite ignite lst ^String schema_name]
(if-let [{schema_name-0 :schema_name create_table :create_table table_name-0 :table_name lst_table_item :lst_table_item code_sb :code_sb indexs :indexs template :template} (get_table_line_obj_lst ignite lst schema_name)]
(let [schema_name (str/lower-case schema_name-0) table_name (str/lower-case table_name-0)]
(cond (and (= schema_name "") (not (= schema_name ""))) {:schema_name schema_name :table_name table_name :pk-data (get_pk_data lst_table_item) :lst_table_item lst_table_item :lst_ddl (concat (conj [] {:sql (format "%s %s.%s (%s) WITH \"%s" create_table schema_name table_name code_sb template) :un_sql (format "DROP TABLE IF EXISTS %s.%s" schema_name table_name) :is_success nil}) indexs)}
(or (and (not (= schema_name "")) (my-lexical/is-eq? schema_name "MY_META")) (and (not (= schema_name "")) (my-lexical/is-eq? schema_name schema_name))) {:schema_name schema_name :table_name table_name :pk-data (get_pk_data lst_table_item) :lst_table_item lst_table_item :lst_ddl (concat (conj [] {:sql (format "%s %s.%s (%s) WITH \"%s" create_table schema_name table_name code_sb template) :un_sql (format "DROP TABLE IF EXISTS %s.%s" schema_name table_name) :is_success nil}) indexs)}
:else
(throw (Exception. "没有创建表语句的权限!"))
))
(throw (Exception. "创建表的语句错误!"))))
(defn get_table_obj [^Ignite ignite ^String table_name ^String descrip ^String code ^Long data_set_id]
(if-let [id (.incrementAndGet (.atomicSequence ignite "my_meta_tables" 0 true))]
(MyTable. id table_name descrip code data_set_id)
(throw (Exception. "数据库异常!"))))
(defn get_table_obj_lst [^Ignite ignite ^String table_name ^String descrip lst ^Long data_set_id]
(if-let [id (.incrementAndGet (.atomicSequence ignite "my_meta_tables" 0 true))]
(MyTable. id table_name descrip "" data_set_id)
(throw (Exception. "数据库异常!"))))
生成
(defn get_table_items_obj
([^Ignite ignite lst_table_item table_id] (get_table_items_obj ignite lst_table_item table_id []))
([^Ignite ignite [f & r] table_id lst]
(if (some? f)
(if-let [id (.incrementAndGet (.atomicSequence ignite "table_item" 0 true))]
(recur ignite r table_id (conj lst {:table "table_item" :key (MyTableItemPK. id table_id) :value (doto f (.setId id)
(.setTable_id table_id))}))
(throw (Exception. "数据库异常!")))
lst)))
(defn get_my_table [^Ignite ignite ^String table_name ^String descrip ^String code lst_table_item ^Long data_set_id]
(if-let [table (get_table_obj ignite table_name descrip code data_set_id)]
(if-let [lst_items (get_table_items_obj ignite lst_table_item (.getId table))]
(cons {:table "my_meta_tables" :key (.getId table) :value table} lst_items)
(throw (Exception. "数据库异常!")))
(throw (Exception. "数据库异常!"))))
(defn get_my_table_lst [^Ignite ignite ^String table_name ^String descrip lst lst_table_item ^Long data_set_id]
(if-let [table (get_table_obj_lst ignite table_name descrip lst data_set_id)]
(if-let [lst_items (get_table_items_obj ignite lst_table_item (.getId table))]
(cons {:table "my_meta_tables" :key (.getId table) :value table} lst_items)
(throw (Exception. "数据库异常!")))
(throw (Exception. "数据库异常!"))))
(defn to_mycachex
([^Ignite ignite lst_dml_table] (to_mycachex ignite lst_dml_table (ArrayList.)))
([^Ignite ignite [f & r] lst]
(if (some? f)
(if-not (Strings/isNullOrEmpty (.getMyLogCls (.configuration ignite)))
(recur ignite r (doto lst (.add (MyCacheEx. (.cache ignite (-> f :table)) (-> f :key) (-> f :value) (SqlType/INSERT) (MyLogCache. (-> f :table) "MY_META" (-> f :table) (-> f :key) (-> f :value) (SqlType/INSERT))))))
(recur ignite r (doto lst (.add (MyCacheEx. (.cache ignite (-> f :table)) (-> f :key) (-> f :value) (SqlType/INSERT) nil)))))
lst)))
lst_dml_table : [ { : table " 表名 " : key PK_ID : value 值 } ]
转成 ArrayList 用 来执行
(defn run_ddl_dml [^Ignite ignite lst_ddl lst_dml_table no-sql-cache code]
(MyCreateTableUtil/run_ddl_dml ignite (my-lexical/to_arryList lst_ddl) lst_dml_table no-sql-cache code))
(defn my_create_table_lst [^Ignite ignite group_id ^String descrip lst]
(if (= (first group_id) 0)
(if-let [{schema_name :schema_name table_name :table_name pk-data :pk-data lst_table_item :lst_table_item lst_ddl :lst_ddl} (to_ddl_lsts ignite lst (str/lower-case (second group_id)))]
(if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name))
(if-let [lst_dml_table (to_mycachex ignite (get_my_table_lst ignite table_name descrip lst lst_table_item 0))]
(if (true? (.isMultiUserGroup (.configuration ignite)))
(run_ddl_dml ignite lst_ddl lst_dml_table (MyNoSqlCache. "table_ast" schema_name table_name (MySchemaTable. schema_name table_name) pk-data (SqlType/INSERT)) (str/join " " lst)))
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "MY_META 数据集不能创建新的表!")))
(throw (Exception. "创建表的语句错误!")))
(if (contains? #{"ALL" "DDL"} (str/upper-case (nth group_id 2)))
(if-let [{schema_name :schema_name table_name :table_name pk-data :pk-data lst_table_item :lst_table_item lst_ddl :lst_ddl} (to_ddl_lsts ignite lst (str/lower-case (second group_id)))]
(if-not (and (my-lexical/is-eq? schema_name "my_meta") (contains? plus-init-sql/my-grid-tables-set table_name))
(if (and (not (my-lexical/is-eq? schema_name "my_meta")) (my-lexical/is-eq? schema_name (second group_id)))
(if-let [lst_dml_table (to_mycachex ignite (get_my_table_lst ignite table_name descrip lst lst_table_item (last group_id)))]
(if (true? (.isMultiUserGroup (.configuration ignite)))
(run_ddl_dml ignite lst_ddl lst_dml_table (MyNoSqlCache. "table_ast" schema_name table_name (MySchemaTable. schema_name table_name) pk-data (SqlType/INSERT)) (str/join " " lst)))
(throw (Exception. "创建表的语句错误!"))
))
(throw (Exception. "MY_META 数据集不能创建新的表!")))
(throw (Exception. "创建表的语句错误!")))
(throw (Exception. "该用户组没有创建表的权限!")))))
(defn my_get_obj_ds
([items] (if-let [{lst_table_item :lst_table_item code_sb :code_sb pk_sets :pk_sets} (my_get_obj_ds items (ArrayList.) (StringBuilder.) #{})]
(cond (= (count pk_sets) 1) {:lst_table_item (set_pk_set lst_table_item pk_sets) :code_sb (format "%s PRIMARY KEY (%s)" (.toString code_sb) (nth pk_sets 0))}
(> (count pk_sets) 1) (if-let [pk_set (set_pk_set lst_table_item pk_sets)]
{:lst_table_item pk_set :code_sb (format "%s PRIMARY KEY (%s)" (.toString code_sb) (pk_line pk_sets))}
(throw (Exception. "主键设置错误!")))
:else
(throw (Exception. "主键设置错误!"))
)
(throw (Exception. "创建表的语句错误!"))))
([[f & r] ^ArrayList lst ^StringBuilder sb pk_sets]
(if (some? f)
(if-let [{table_item :table_item code_line :code pk :pk} (to_item f)]
(do (.add lst table_item)
(if (not (nil? (last (.trim (.toString code_line)))))
(.append sb (.concat (.trim (.toString code_line)) ",")))
(recur r lst sb (concat pk_sets pk)))
(throw (Exception. "创建表的语句错误!")))
{:lst_table_item (table_items lst) :code_sb sb :pk_sets pk_sets})))
( defn my_create_table_lst [ ^Ignite ignite group_id ^String descrip lst ]
( if (= ( first group_id ) 0 )
( if - let [ { schema_name : schema_name table_name : table_name pk - data : pk - data lst_table_item : lst_table_item lst_ddl : lst_ddl } ( to_ddl_lsts ignite lst ( str / lower - case ( second group_id ) ) ) ]
( if - let [ ( to_mycachex ignite ( get_my_table_lst ignite table_name descrip lst lst_table_item 0 ) ) ]
( run_ddl_dml ignite lst_ddl lst_dml_table ( MyNoSqlCache . " table_ast " schema_name table_name ( MySchemaTable . schema_name table_name ) pk - data ( SqlType / INSERT ) ) ( str / join " " lst ) ) )
( throw ( Exception . " MY_META 数据集不能创建新的表 ! " ) ) )
( if ( contains ? # { " ALL " " DDL " } ( str / upper - case ( nth group_id 2 ) ) )
( if - let [ { schema_name : schema_name table_name : table_name pk - data : pk - data lst_table_item : lst_table_item lst_ddl : lst_ddl } ( to_ddl_lsts ignite lst ( str / lower - case ( second group_id ) ) ) ]
( if ( and ( not ( my - lexical / is - eq ? schema_name " my_meta " ) ) ( my - lexical / is - eq ? schema_name ( second group_id ) ) )
( if - let [ ( to_mycachex ignite ( get_my_table_lst ignite table_name descrip lst lst_table_item ( last group_id ) ) ) ]
( run_ddl_dml ignite lst_ddl lst_dml_table ( MyNoSqlCache . " table_ast " schema_name table_name ( MySchemaTable . schema_name table_name ) pk - data ( SqlType / INSERT ) ) ( str / join " " lst ) ) )
( throw ( Exception . " MY_META 数据集不能创建新的表 ! " ) ) )
( throw ( Exception . " 该用户组没有创建表的权限 ! " ) ) ) ) )
(defn create-table [^Ignite ignite group_id ^String descrip sql-line]
(my_create_table_lst ignite group_id descrip (my-lexical/to-back sql-line)))
(defn get-meta-pk-data [^String sql]
(letfn [(meta_table_line_obj_lst [lst ^String schema_name]
(let [{schema_name :schema_name table_name :table_name create_table :create_table items_line :items_line template :template} (get-create-table-items lst)]
(if-let [{lst_table_item :lst_table_item code_sb :code_sb indexs :indexs} (get_obj (get_items_obj_lst items_line) schema_name table_name schema_name)]
{:create_table create_table
:schema_name schema_name
:table_name table_name
:lst_table_item lst_table_item
}
(throw (Exception. "创建表的语句错误!")))
)
)]
(let [{table_name :table_name lst_table_item :lst_table_item} (meta_table_line_obj_lst (my-lexical/to-back sql) "MY_META")]
{:schema_name "MY_META" :table_name table_name :value (get_pk_data lst_table_item)})))
java 中调用
( defn -plus_create_table [ ^Ignite ignite ^Long group_id ^String schema_name group_type ^Long dataset_id ^String descrip ^String code ]
|
ac4c0b865fe8f89eb70819f37d3c802cf0051952ea9a1efe026650940b514cfa | CloudI/CloudI | folsom_erlang_checks.erl | %%%
Copyright 2011 , Boundary
%%%
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.
%%%
%%%-------------------------------------------------------------------
%%% File: folsom_erlang_checks.erl
@author < >
%%% @doc
%%% @end
%%%------------------------------------------------------------------
-module(folsom_erlang_checks).
-include_lib("eunit/include/eunit.hrl").
-export([
create_metrics/0,
populate_metrics/0,
tag_metrics/0,
check_metrics/0,
check_group_metrics/0,
delete_metrics/0,
vm_metrics/0,
counter_metric/2,
cpu_topology/0,
c_compiler_used/0,
create_delete_metrics/0,
check_ets_leak/0
]).
-define(DATA, [0, 1, 5, 10, 100, 200, 500, 750, 1000, 2000, 5000]).
-define(HUGEDATA, lists:seq(1,10000)).
-define(DATA1, [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]).
-define(DATA2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]).
-include("folsom.hrl").
create_metrics() ->
ok = folsom_metrics:new_counter(counter),
ok = folsom_metrics:new_counter(counter2),
ok = folsom_metrics:new_gauge(<<"gauge">>),
ok = folsom_metrics:new_histogram(<<"uniform">>, uniform, 5000),
ok = folsom_metrics:new_histogram(<<"hugedata">>, uniform, 5000),
ok = folsom_metrics:new_histogram(exdec, exdec),
ok = folsom_metrics:new_histogram(none, none, 5000),
ok = folsom_metrics:new_histogram(nonea, none, 5000),
ok = folsom_metrics:new_histogram(noneb, none, 10),
ok = folsom_metrics:new_histogram(nonec, none, 5),
ok = folsom_metrics:new_histogram(slide_sorted_a, slide_sorted, 10),
ok = folsom_metrics:new_histogram(timed, none, 5000),
ok = folsom_metrics:new_histogram(timed2, none, 5000),
ok = folsom_metrics:new_history(<<"history">>),
ok = folsom_metrics:new_meter(meter),
ok = folsom_metrics:new_meter_reader(meter_reader),
ok = folsom_metrics:new_duration(duration),
ok = folsom_metrics:new_spiral(spiral),
ok = folsom_metrics:new_spiral(spiral_no_exceptions, no_exceptions),
?debugFmt("ensuring meter tick is registered with gen_server~n", []),
ok = ensure_meter_tick_exists(2),
?debugFmt("ensuring multiple timer registrations dont cause issues", []),
ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter),
ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter),
ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter),
?debugFmt("~p", [folsom_meter_timer_server:dump()]),
{state, List} = folsom_meter_timer_server:dump(),
2 = length(List),
check two servers got started for the spiral metrics
2 = length(supervisor:which_children(folsom_sample_slide_sup)),
19 = length(folsom_metrics:get_metrics()),
?debugFmt("~n~nmetrics: ~p~n", [folsom_metrics:get_metrics()]).
tag_metrics() ->
Group = "mygroup",
ok = folsom_metrics:tag_metric(counter, Group),
ok = folsom_metrics:tag_metric(counter2, Group),
ok = folsom_metrics:tag_metric(<<"gauge">>, Group),
ok = folsom_metrics:tag_metric(meter, Group),
ok = folsom_metrics:tag_metric(spiral, Group),
ok = folsom_metrics:tag_metric(spiral_no_exceptions, Group),
?debugFmt("~n~ntagged metrics: ~p, ~p, ~p, ~p, ~p and ~p in group ~p~n", [counter,counter2,<<"gauge">>,meter,spiral,spiral_no_exceptions,Group]).
populate_metrics() ->
ok = folsom_metrics:notify({counter, {inc, 1}}),
ok = folsom_metrics:notify({counter, {dec, 1}}),
ok = folsom_metrics:notify({counter2, {inc, 10}}),
ok = folsom_metrics:notify({counter2, {dec, 7}}),
meck:new(folsom_ets),
meck:expect(folsom_ets, notify, fun(_Event) -> meck:exception(error, something_wrong_with_ets) end),
{'EXIT', {something_wrong_with_ets, _}} = folsom_metrics:safely_notify({unknown_counter, {inc, 1}}),
meck:unload(folsom_ets),
ok = folsom_metrics:safely_histogram_timed_update(unknown_histogram, fun() -> ok end),
ok = folsom_metrics:safely_histogram_timed_update(unknown_histogram, fun(ok) -> ok end, [ok]),
3.141592653589793 = folsom_metrics:safely_histogram_timed_update(unknown_histogram, math, pi, []),
UnknownHistogramBegin = folsom_metrics:histogram_timed_begin(unknown_histogram),
{error, unknown_histogram, nonexistent_metric} = folsom_metrics:safely_histogram_timed_notify(UnknownHistogramBegin),
ok = folsom_metrics:notify({<<"gauge">>, 2}),
[ok = folsom_metrics:notify({<<"uniform">>, Value}) || Value <- ?DATA],
[ok = folsom_metrics:notify({<<"hugedata">>, Value}) || Value <- ?HUGEDATA],
[ok = folsom_metrics:notify({exdec, Value}) || Value <- lists:seq(1, 50000)],
Force a priority change in folson_sample_exdec : priority/1
receive
after 1000 ->
ok
end,
[ok = folsom_metrics:notify({exdec, Value}) || Value <- lists:seq(50000, 100000)],
[ok = folsom_metrics:notify({none, Value}) || Value <- ?DATA],
[ok = folsom_metrics:notify({nonea, Value}) || Value <- ?DATA1],
[ok = folsom_metrics:notify({noneb, Value}) || Value <- ?DATA2],
[ok = folsom_metrics:notify({nonec, Value}) || Value <- ?DATA2],
[ok = folsom_metrics:notify({slide_sorted_a, Value}) || Value <- ?DATA2],
ok = folsom_metrics:notify(tagged_metric, 1, meter, [a, b]),
ok = folsom_metrics:notify(tagged_metric, 1, meter, [c]),
{error, _, unsupported_metric_type} = folsom_metrics:notify(tagged_unknown_metric, 1, unknown_metric, [tag]),
3.141592653589793 = folsom_metrics:histogram_timed_update(timed, math, pi, []),
Begin = folsom_metrics:histogram_timed_begin(timed2),
folsom_metrics:histogram_timed_notify(Begin),
PopulateDuration = fun() ->
ok = folsom_metrics:notify_existing_metric(duration, timer_start, duration),
timer:sleep(10),
ok = folsom_metrics:notify_existing_metric(duration, timer_end, duration) end,
[PopulateDuration() || _ <- lists:seq(1, 10)],
ok = folsom_metrics:notify({<<"history">>, "string"}),
{error, _, nonexistent_metric} = folsom_metrics:notify({historya, "5"}),
ok = folsom_metrics:notify(historya, <<"binary">>, history),
?debugFmt("testing meter ...", []),
% simulate an interval tick
folsom_metrics_meter:tick(meter),
[ok,ok,ok,ok,ok] =
[ folsom_metrics:notify({meter, Item}) || Item <- [100, 100, 100, 100, 100]],
% simulate an interval tick
folsom_metrics_meter:tick(meter),
?debugFmt("testing meter reader ...", []),
% simulate an interval tick
folsom_metrics_meter_reader:tick(meter_reader),
[ok,ok,ok,ok,ok] =
[ folsom_metrics:notify({meter_reader, Item}) || Item <- [1, 10, 100, 1000, 10000]],
% simulate an interval tick
folsom_metrics_meter_reader:tick(meter_reader),
folsom_metrics:notify_existing_metric(spiral, 100, spiral),
folsom_metrics:notify_existing_metric(spiral_no_exceptions, 200, spiral).
check_metrics() ->
0 = folsom_metrics:get_metric_value(counter),
3 = folsom_metrics:get_metric_value(counter2),
ok = folsom_metrics:notify_existing_metric(counter2, clear, counter),
0 = folsom_metrics:get_metric_value(counter2),
2 = folsom_metrics:get_metric_value(<<"gauge">>),
true = sets:is_subset(sets:from_list([a,b,c]), folsom_metrics:get_tags(tagged_metric)),
[11,12,13,14,15,6,7,8,9,10] = folsom_metrics:get_metric_value(noneb),
[11,12,13,14,15] = folsom_metrics:get_metric_value(nonec),
[6,7,8,9,10,11,12,13,14,15] = folsom_metrics:get_metric_value(slide_sorted_a),
Histogram1 = folsom_metrics:get_histogram_statistics(<<"uniform">>),
histogram_checks(Histogram1),
MetricsSubset = [min, max],
ok = set_enabled_metrics(MetricsSubset),
Histogram2 = folsom_metrics:get_histogram_statistics(<<"uniform">>),
subset_checks(Histogram2, MetricsSubset),
ok = set_enabled_metrics(?DEFAULT_METRICS),
HugeHistogram = folsom_metrics:get_histogram_statistics(<<"hugedata">>),
huge_histogram_checks(HugeHistogram),
just check exdec for non - zero values
Exdec = folsom_metrics:get_histogram_statistics(exdec),
?debugFmt("checking exdec sample~n~p~n", [Exdec]),
ok = case proplists:get_value(median, Exdec) of
Median when Median > 0 ->
ok;
_ ->
error
end,
Histogram3 = folsom_metrics:get_histogram_statistics(none),
histogram_checks(Histogram3),
CoValues = folsom_metrics:get_histogram_statistics(none, nonea),
histogram_co_checks(CoValues),
List = folsom_metrics:get_metric_value(timed),
?debugFmt("timed update value: ~p", [List]),
List2 = folsom_metrics:get_metric_value(timed2),
?debugFmt("timed update value begin/end: ~p", [List2]),
1 = length(folsom_metrics:get_metric_value(<<"history">>)),
1 = length(folsom_metrics:get_metric_value(historya)),
?debugFmt("checking meter~n", []),
Meter = folsom_metrics:get_metric_value(meter),
?debugFmt("~p", [Meter]),
ok = case proplists:get_value(one, Meter) of
Value when Value > 1 ->
ok;
_ ->
error
end,
ok = case proplists:get_value(day, Meter) of
Value1 when Value1 > 0.005 ->
ok;
_ ->
error
end,
?debugFmt("checking meter reader~n", []),
MeterReader = folsom_metrics:get_metric_value(meter_reader),
?debugFmt("~p~n", [MeterReader]),
ok = case proplists:get_value(one, MeterReader) of
Value2 when Value2 > 1 ->
ok;
_ ->
error
end,
%% check duration
Dur = folsom_metrics:get_metric_value(duration),
duration_check(Dur),
ok = set_enabled_metrics(MetricsSubset),
Dur2 = folsom_metrics:get_metric_value(duration),
subset_checks(Dur2, MetricsSubset),
ok = set_enabled_metrics(?DEFAULT_METRICS),
%% check spiral
[{count, 100}, {one, 100}] = folsom_metrics:get_metric_value(spiral),
[{count, 200}, {one, 200}] = folsom_metrics:get_metric_value(spiral_no_exceptions).
check_group_metrics() ->
Group = "mygroup",
Metrics = folsom_metrics:get_metrics_value(Group),
6 = length(Metrics),
{counter, 0} = lists:keyfind(counter,1,Metrics),
{counter2, 0} = lists:keyfind(counter2,1,Metrics),
{<<"gauge">>, 2} = lists:keyfind(<<"gauge">>,1,Metrics),
{meter, Meter} = lists:keyfind(meter,1,Metrics),
ok = case proplists:get_value(one, Meter) of
Value when Value > 1 ->
ok;
_ ->
error
end,
ok = case proplists:get_value(day, Meter) of
Value1 when Value1 > 0.005 ->
ok;
_ ->
error
end,
{spiral, [{count, 100}, {one, 100}]} = lists:keyfind(spiral,1,Metrics),
{spiral_no_exceptions, [{count, 200}, {one, 200}]} = lists:keyfind(spiral_no_exceptions,1,Metrics),
Counters = folsom_metrics:get_metrics_value(Group,counter),
{counter, 0} = lists:keyfind(counter,1,Counters),
{counter2, 0} = lists:keyfind(counter2,1,Counters),
ok = folsom_metrics:untag_metric(counter2, Group),
ok = folsom_metrics:untag_metric(<<"gauge">>, Group),
ok = folsom_metrics:untag_metric(meter, Group),
ok = folsom_metrics:untag_metric(spiral, Group),
ok = folsom_metrics:untag_metric(spiral_no_exceptions, Group),
?debugFmt("~n~nuntagged metrics: ~p, ~p, ~p, ~p and ~p in group ~p~n", [counter2,<<"gauge">>,meter,spiral,spiral_no_exceptions,Group]),
RemainingMetrics = folsom_metrics:get_metrics_value(Group),
1 = length(RemainingMetrics),
{counter, 0} = lists:keyfind(counter,1,Metrics).
delete_metrics() ->
22 = length(ets:tab2list(?FOLSOM_TABLE)),
ok = folsom_metrics:delete_metric(counter),
ok = folsom_metrics:delete_metric(counter2),
ok = folsom_metrics:delete_metric(<<"gauge">>),
ok = folsom_metrics:delete_metric(<<"hugedata">>),
ok = folsom_metrics:delete_metric(<<"uniform">>),
ok = folsom_metrics:delete_metric(exdec),
ok = folsom_metrics:delete_metric(none),
ok = folsom_metrics:delete_metric(<<"history">>),
ok = folsom_metrics:delete_metric(historya),
ok = folsom_metrics:delete_metric(nonea),
ok = folsom_metrics:delete_metric(noneb),
ok = folsom_metrics:delete_metric(nonec),
ok = folsom_metrics:delete_metric(tagged_metric),
ok = folsom_metrics:delete_metric(slide_sorted_a),
ok = folsom_metrics:delete_metric(timed),
ok = folsom_metrics:delete_metric(timed2),
ok = folsom_metrics:delete_metric(testcounter),
ok = ensure_meter_tick_exists(2),
1 = length(ets:tab2list(?METER_TABLE)),
ok = folsom_metrics:delete_metric(meter),
0 = length(ets:tab2list(?METER_TABLE)),
1 = length(ets:tab2list(?METER_READER_TABLE)),
ok = folsom_metrics:delete_metric(meter_reader),
0 = length(ets:tab2list(?METER_READER_TABLE)),
ok = ensure_meter_tick_exists(0),
ok = folsom_metrics:delete_metric(duration),
ok = folsom_metrics:delete_metric(spiral),
ok = folsom_metrics:delete_metric(spiral_no_exceptions),
0 = length(ets:tab2list(?FOLSOM_TABLE)).
vm_metrics() ->
List1 = folsom_vm_metrics:get_memory(),
true = lists:keymember(total, 1, List1),
List2 = folsom_vm_metrics:get_statistics(),
true = lists:keymember(context_switches, 1, List2),
List3 = folsom_vm_metrics:get_system_info(),
true = lists:keymember(allocated_areas, 1, List3),
true = lists:keymember(port_count, 1, List3),
[{_, [{backtrace, _}| _]} | _] = folsom_vm_metrics:get_process_info(),
[{_, [{name, _}| _]} | _] = folsom_vm_metrics:get_port_info().
counter_metric(Count, Counter) ->
ok = folsom_metrics:new_counter(Counter),
?debugFmt("running ~p counter inc/dec rounds~n", [Count]),
for(Count, Counter),
Result = folsom_metrics:get_metric_value(Counter),
?debugFmt("counter result: ~p~n", [Result]),
0 = Result.
ensure_meter_tick_exists(MeterCnt) ->
{state, State} = folsom_meter_timer_server:dump(),
MeterCnt = length(State),
ok.
%% internal function
histogram_checks(List) ->
?debugFmt("checking histogram statistics", []),
?debugFmt("~p~n", [List]),
0 = proplists:get_value(min, List),
5000 = proplists:get_value(max, List),
869.6363636363636 = proplists:get_value(arithmetic_mean, List),
GeoMean = proplists:get_value(geometric_mean, List),
ok = case GeoMean - 100.17443147308997 of
GeoDiff when GeoDiff < 0.00000001 ->
ok;
_ ->
error
end,
Value = proplists:get_value(harmonic_mean, List),
%?debugFmt("~p~n", [Value]),
ok = case Value - 8.333122900936845 of
Diff when Diff < 0.00000001 ->
ok;
_ ->
error
end,
200 = proplists:get_value(median, List),
2254368.454545454 = proplists:get_value(variance, List),
1501.4554454080394 = proplists:get_value(standard_deviation, List),
1.8399452806806476 = proplists:get_value(skewness, List),
2.2856772911293204 = proplists:get_value(kurtosis, List),
List1 = proplists:get_value(percentile, List),
percentile_check(List1),
List2 = proplists:get_value(histogram, List),
histogram_check(List2).
huge_histogram_checks(List) ->
Skew = erlang:abs(proplists:get_value(skewness, List)),
A = skewness_is_too_high_for_sample_of_this_size,
B = this_event_is_very_unprobable,
C = please_rerun_this_test__if_it_fails_again_your_code_is_bugged,
{A, B, C, true} = {A, B, C, Skew < 0.2}.
histogram_co_checks(List) ->
?debugFmt("checking histogram covariance and etc statistics", []),
?debugFmt("~p~n", [List]),
[
{covariance,17209.545454545456},
{tau,1.0},
{rho,0.760297020598996},
{r,1.0}
] = List.
percentile_check(List) ->
750 = proplists:get_value(75, List),
2000 = proplists:get_value(95, List),
5000 = proplists:get_value(99, List),
5000 = proplists:get_value(999, List).
histogram_check(List) ->
[{2400,10},{5000,1},{8000,0}] = List.
counter_inc_dec(Counter) ->
ok = folsom_metrics:notify({Counter, {inc, 1}}),
ok = folsom_metrics:notify({Counter, {dec, 1}}).
for(N, Counter) ->
for(N, 0, Counter).
for(N, Count, _Counter) when N == Count ->
ok;
for(N, LoopCount, Counter) ->
counter_inc_dec(Counter),
for(N, LoopCount + 1, Counter).
cpu_topology() ->
?debugMsg("Testing various CPU topologies ...~n"),
P = "test/cpu_topo_data",
Path = case filelib:is_regular(P) of
true -> P;
false -> filename:join("..", P)
end,
{ok, [Data]} = file:consult(Path),
[run_convert_and_jsonify(Item) || Item <- Data].
run_convert_and_jsonify(Item) ->
?debugFmt("Converting ... ~n~p~n", [Item]),
Result = folsom_vm_metrics:convert_system_info(cpu_topology, Item),
%?debugFmt("~p~n", [mochijson2:encode(Result)]).
mochijson2:encode(Result).
c_compiler_used() ->
Test = [{gnuc, {4,4,5}},
{gnuc, {4,4}},
{msc, 1600}],
Expected = [[{compiler, gnuc}, {version, <<"4.4.5">>}],
[{compiler, gnuc}, {version, <<"4.4">>}],
[{compiler, msc}, {version, <<"1600">>}]],
?assertEqual(Expected, [folsom_vm_metrics:convert_system_info(c_compiler_used, {Compiler, Version})
|| {Compiler, Version} <- Test]).
duration_check(Duration) ->
[?assert(lists:keymember(Key, 1, Duration)) || Key <-
[count, last, min, max, arithmetic_mean,
geometric_mean, harmonic_mean, median,
variance, standard_deviation, skewness,
kurtosis, percentile, histogram]],
?assertEqual(10, proplists:get_value(count, Duration)),
Last = proplists:get_value(last, Duration),
?assert(Last > 10000).
create_delete_metrics() ->
?assertMatch(ok, folsom_metrics:new_counter(counter)),
?assertMatch(ok, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)),
?assertMatch(1, folsom_metrics:get_metric_value(counter)),
?assertMatch(ok, folsom_metrics:delete_metric(counter)),
?assertError(badarg, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)),
?assertMatch(ok, folsom_metrics:new_counter(counter)),
?assertMatch(ok, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)),
?assertMatch(1, folsom_metrics:get_metric_value(counter)).
set_enabled_metrics(Enabled) ->
application:set_env(folsom, enabled_metrics, Enabled).
subset_checks(List, Enabled) ->
?debugFmt("checking subset statistics", []),
?debugFmt("~p, ~p~n", [List, Enabled]),
Disabled = ?DEFAULT_METRICS -- Enabled,
true = lists:all(fun(K) ->
proplists:get_value(K, List) == undefined
end,
Disabled),
true = lists:all(fun(K) ->
proplists:get_value(K, List) /= undefined
end,
Enabled).
check_ets_leak() ->
L = ["gauge", "meter", "spiral"],
[begin
Name = list_to_atom(X ++ "_ets_leak"),
Table = list_to_atom("folsom_" ++ X ++ "s"),
Metric = list_to_atom(X),
[spawn(
fun() ->
folsom_metrics:notify(Name, 1, Metric)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(Table, Name)))
end || X <- L],
[spawn(
fun() ->
folsom_metrics:notify(counter_ets_leak, {inc, 1}, counter)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(folsom_counters, {counter_ets_leak, 0}))),
[spawn(
fun() ->
folsom_metrics:notify(history_ets_leak, <<"hist">>, history)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(folsom_histories, history_ets_leak))),
[spawn(
fun() ->
folsom_metrics:new_meter_reader(meter_reader_ets_leak)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(folsom_meter_readers, meter_reader_ets_leak))),
[spawn(
fun() ->
folsom_metrics:new_duration(duration_ets_leak)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(folsom_durations, duration_ets_leak))).
| null | https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/cloudi_x_folsom/test/folsom_erlang_checks.erl | erlang |
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.
-------------------------------------------------------------------
File: folsom_erlang_checks.erl
@doc
@end
------------------------------------------------------------------
simulate an interval tick
simulate an interval tick
simulate an interval tick
simulate an interval tick
check duration
check spiral
internal function
?debugFmt("~p~n", [Value]),
?debugFmt("~p~n", [mochijson2:encode(Result)]). | Copyright 2011 , Boundary
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
-module(folsom_erlang_checks).
-include_lib("eunit/include/eunit.hrl").
-export([
create_metrics/0,
populate_metrics/0,
tag_metrics/0,
check_metrics/0,
check_group_metrics/0,
delete_metrics/0,
vm_metrics/0,
counter_metric/2,
cpu_topology/0,
c_compiler_used/0,
create_delete_metrics/0,
check_ets_leak/0
]).
-define(DATA, [0, 1, 5, 10, 100, 200, 500, 750, 1000, 2000, 5000]).
-define(HUGEDATA, lists:seq(1,10000)).
-define(DATA1, [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]).
-define(DATA2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]).
-include("folsom.hrl").
create_metrics() ->
ok = folsom_metrics:new_counter(counter),
ok = folsom_metrics:new_counter(counter2),
ok = folsom_metrics:new_gauge(<<"gauge">>),
ok = folsom_metrics:new_histogram(<<"uniform">>, uniform, 5000),
ok = folsom_metrics:new_histogram(<<"hugedata">>, uniform, 5000),
ok = folsom_metrics:new_histogram(exdec, exdec),
ok = folsom_metrics:new_histogram(none, none, 5000),
ok = folsom_metrics:new_histogram(nonea, none, 5000),
ok = folsom_metrics:new_histogram(noneb, none, 10),
ok = folsom_metrics:new_histogram(nonec, none, 5),
ok = folsom_metrics:new_histogram(slide_sorted_a, slide_sorted, 10),
ok = folsom_metrics:new_histogram(timed, none, 5000),
ok = folsom_metrics:new_histogram(timed2, none, 5000),
ok = folsom_metrics:new_history(<<"history">>),
ok = folsom_metrics:new_meter(meter),
ok = folsom_metrics:new_meter_reader(meter_reader),
ok = folsom_metrics:new_duration(duration),
ok = folsom_metrics:new_spiral(spiral),
ok = folsom_metrics:new_spiral(spiral_no_exceptions, no_exceptions),
?debugFmt("ensuring meter tick is registered with gen_server~n", []),
ok = ensure_meter_tick_exists(2),
?debugFmt("ensuring multiple timer registrations dont cause issues", []),
ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter),
ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter),
ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter),
?debugFmt("~p", [folsom_meter_timer_server:dump()]),
{state, List} = folsom_meter_timer_server:dump(),
2 = length(List),
check two servers got started for the spiral metrics
2 = length(supervisor:which_children(folsom_sample_slide_sup)),
19 = length(folsom_metrics:get_metrics()),
?debugFmt("~n~nmetrics: ~p~n", [folsom_metrics:get_metrics()]).
tag_metrics() ->
Group = "mygroup",
ok = folsom_metrics:tag_metric(counter, Group),
ok = folsom_metrics:tag_metric(counter2, Group),
ok = folsom_metrics:tag_metric(<<"gauge">>, Group),
ok = folsom_metrics:tag_metric(meter, Group),
ok = folsom_metrics:tag_metric(spiral, Group),
ok = folsom_metrics:tag_metric(spiral_no_exceptions, Group),
?debugFmt("~n~ntagged metrics: ~p, ~p, ~p, ~p, ~p and ~p in group ~p~n", [counter,counter2,<<"gauge">>,meter,spiral,spiral_no_exceptions,Group]).
populate_metrics() ->
ok = folsom_metrics:notify({counter, {inc, 1}}),
ok = folsom_metrics:notify({counter, {dec, 1}}),
ok = folsom_metrics:notify({counter2, {inc, 10}}),
ok = folsom_metrics:notify({counter2, {dec, 7}}),
meck:new(folsom_ets),
meck:expect(folsom_ets, notify, fun(_Event) -> meck:exception(error, something_wrong_with_ets) end),
{'EXIT', {something_wrong_with_ets, _}} = folsom_metrics:safely_notify({unknown_counter, {inc, 1}}),
meck:unload(folsom_ets),
ok = folsom_metrics:safely_histogram_timed_update(unknown_histogram, fun() -> ok end),
ok = folsom_metrics:safely_histogram_timed_update(unknown_histogram, fun(ok) -> ok end, [ok]),
3.141592653589793 = folsom_metrics:safely_histogram_timed_update(unknown_histogram, math, pi, []),
UnknownHistogramBegin = folsom_metrics:histogram_timed_begin(unknown_histogram),
{error, unknown_histogram, nonexistent_metric} = folsom_metrics:safely_histogram_timed_notify(UnknownHistogramBegin),
ok = folsom_metrics:notify({<<"gauge">>, 2}),
[ok = folsom_metrics:notify({<<"uniform">>, Value}) || Value <- ?DATA],
[ok = folsom_metrics:notify({<<"hugedata">>, Value}) || Value <- ?HUGEDATA],
[ok = folsom_metrics:notify({exdec, Value}) || Value <- lists:seq(1, 50000)],
Force a priority change in folson_sample_exdec : priority/1
receive
after 1000 ->
ok
end,
[ok = folsom_metrics:notify({exdec, Value}) || Value <- lists:seq(50000, 100000)],
[ok = folsom_metrics:notify({none, Value}) || Value <- ?DATA],
[ok = folsom_metrics:notify({nonea, Value}) || Value <- ?DATA1],
[ok = folsom_metrics:notify({noneb, Value}) || Value <- ?DATA2],
[ok = folsom_metrics:notify({nonec, Value}) || Value <- ?DATA2],
[ok = folsom_metrics:notify({slide_sorted_a, Value}) || Value <- ?DATA2],
ok = folsom_metrics:notify(tagged_metric, 1, meter, [a, b]),
ok = folsom_metrics:notify(tagged_metric, 1, meter, [c]),
{error, _, unsupported_metric_type} = folsom_metrics:notify(tagged_unknown_metric, 1, unknown_metric, [tag]),
3.141592653589793 = folsom_metrics:histogram_timed_update(timed, math, pi, []),
Begin = folsom_metrics:histogram_timed_begin(timed2),
folsom_metrics:histogram_timed_notify(Begin),
PopulateDuration = fun() ->
ok = folsom_metrics:notify_existing_metric(duration, timer_start, duration),
timer:sleep(10),
ok = folsom_metrics:notify_existing_metric(duration, timer_end, duration) end,
[PopulateDuration() || _ <- lists:seq(1, 10)],
ok = folsom_metrics:notify({<<"history">>, "string"}),
{error, _, nonexistent_metric} = folsom_metrics:notify({historya, "5"}),
ok = folsom_metrics:notify(historya, <<"binary">>, history),
?debugFmt("testing meter ...", []),
folsom_metrics_meter:tick(meter),
[ok,ok,ok,ok,ok] =
[ folsom_metrics:notify({meter, Item}) || Item <- [100, 100, 100, 100, 100]],
folsom_metrics_meter:tick(meter),
?debugFmt("testing meter reader ...", []),
folsom_metrics_meter_reader:tick(meter_reader),
[ok,ok,ok,ok,ok] =
[ folsom_metrics:notify({meter_reader, Item}) || Item <- [1, 10, 100, 1000, 10000]],
folsom_metrics_meter_reader:tick(meter_reader),
folsom_metrics:notify_existing_metric(spiral, 100, spiral),
folsom_metrics:notify_existing_metric(spiral_no_exceptions, 200, spiral).
check_metrics() ->
0 = folsom_metrics:get_metric_value(counter),
3 = folsom_metrics:get_metric_value(counter2),
ok = folsom_metrics:notify_existing_metric(counter2, clear, counter),
0 = folsom_metrics:get_metric_value(counter2),
2 = folsom_metrics:get_metric_value(<<"gauge">>),
true = sets:is_subset(sets:from_list([a,b,c]), folsom_metrics:get_tags(tagged_metric)),
[11,12,13,14,15,6,7,8,9,10] = folsom_metrics:get_metric_value(noneb),
[11,12,13,14,15] = folsom_metrics:get_metric_value(nonec),
[6,7,8,9,10,11,12,13,14,15] = folsom_metrics:get_metric_value(slide_sorted_a),
Histogram1 = folsom_metrics:get_histogram_statistics(<<"uniform">>),
histogram_checks(Histogram1),
MetricsSubset = [min, max],
ok = set_enabled_metrics(MetricsSubset),
Histogram2 = folsom_metrics:get_histogram_statistics(<<"uniform">>),
subset_checks(Histogram2, MetricsSubset),
ok = set_enabled_metrics(?DEFAULT_METRICS),
HugeHistogram = folsom_metrics:get_histogram_statistics(<<"hugedata">>),
huge_histogram_checks(HugeHistogram),
just check exdec for non - zero values
Exdec = folsom_metrics:get_histogram_statistics(exdec),
?debugFmt("checking exdec sample~n~p~n", [Exdec]),
ok = case proplists:get_value(median, Exdec) of
Median when Median > 0 ->
ok;
_ ->
error
end,
Histogram3 = folsom_metrics:get_histogram_statistics(none),
histogram_checks(Histogram3),
CoValues = folsom_metrics:get_histogram_statistics(none, nonea),
histogram_co_checks(CoValues),
List = folsom_metrics:get_metric_value(timed),
?debugFmt("timed update value: ~p", [List]),
List2 = folsom_metrics:get_metric_value(timed2),
?debugFmt("timed update value begin/end: ~p", [List2]),
1 = length(folsom_metrics:get_metric_value(<<"history">>)),
1 = length(folsom_metrics:get_metric_value(historya)),
?debugFmt("checking meter~n", []),
Meter = folsom_metrics:get_metric_value(meter),
?debugFmt("~p", [Meter]),
ok = case proplists:get_value(one, Meter) of
Value when Value > 1 ->
ok;
_ ->
error
end,
ok = case proplists:get_value(day, Meter) of
Value1 when Value1 > 0.005 ->
ok;
_ ->
error
end,
?debugFmt("checking meter reader~n", []),
MeterReader = folsom_metrics:get_metric_value(meter_reader),
?debugFmt("~p~n", [MeterReader]),
ok = case proplists:get_value(one, MeterReader) of
Value2 when Value2 > 1 ->
ok;
_ ->
error
end,
Dur = folsom_metrics:get_metric_value(duration),
duration_check(Dur),
ok = set_enabled_metrics(MetricsSubset),
Dur2 = folsom_metrics:get_metric_value(duration),
subset_checks(Dur2, MetricsSubset),
ok = set_enabled_metrics(?DEFAULT_METRICS),
[{count, 100}, {one, 100}] = folsom_metrics:get_metric_value(spiral),
[{count, 200}, {one, 200}] = folsom_metrics:get_metric_value(spiral_no_exceptions).
check_group_metrics() ->
Group = "mygroup",
Metrics = folsom_metrics:get_metrics_value(Group),
6 = length(Metrics),
{counter, 0} = lists:keyfind(counter,1,Metrics),
{counter2, 0} = lists:keyfind(counter2,1,Metrics),
{<<"gauge">>, 2} = lists:keyfind(<<"gauge">>,1,Metrics),
{meter, Meter} = lists:keyfind(meter,1,Metrics),
ok = case proplists:get_value(one, Meter) of
Value when Value > 1 ->
ok;
_ ->
error
end,
ok = case proplists:get_value(day, Meter) of
Value1 when Value1 > 0.005 ->
ok;
_ ->
error
end,
{spiral, [{count, 100}, {one, 100}]} = lists:keyfind(spiral,1,Metrics),
{spiral_no_exceptions, [{count, 200}, {one, 200}]} = lists:keyfind(spiral_no_exceptions,1,Metrics),
Counters = folsom_metrics:get_metrics_value(Group,counter),
{counter, 0} = lists:keyfind(counter,1,Counters),
{counter2, 0} = lists:keyfind(counter2,1,Counters),
ok = folsom_metrics:untag_metric(counter2, Group),
ok = folsom_metrics:untag_metric(<<"gauge">>, Group),
ok = folsom_metrics:untag_metric(meter, Group),
ok = folsom_metrics:untag_metric(spiral, Group),
ok = folsom_metrics:untag_metric(spiral_no_exceptions, Group),
?debugFmt("~n~nuntagged metrics: ~p, ~p, ~p, ~p and ~p in group ~p~n", [counter2,<<"gauge">>,meter,spiral,spiral_no_exceptions,Group]),
RemainingMetrics = folsom_metrics:get_metrics_value(Group),
1 = length(RemainingMetrics),
{counter, 0} = lists:keyfind(counter,1,Metrics).
delete_metrics() ->
22 = length(ets:tab2list(?FOLSOM_TABLE)),
ok = folsom_metrics:delete_metric(counter),
ok = folsom_metrics:delete_metric(counter2),
ok = folsom_metrics:delete_metric(<<"gauge">>),
ok = folsom_metrics:delete_metric(<<"hugedata">>),
ok = folsom_metrics:delete_metric(<<"uniform">>),
ok = folsom_metrics:delete_metric(exdec),
ok = folsom_metrics:delete_metric(none),
ok = folsom_metrics:delete_metric(<<"history">>),
ok = folsom_metrics:delete_metric(historya),
ok = folsom_metrics:delete_metric(nonea),
ok = folsom_metrics:delete_metric(noneb),
ok = folsom_metrics:delete_metric(nonec),
ok = folsom_metrics:delete_metric(tagged_metric),
ok = folsom_metrics:delete_metric(slide_sorted_a),
ok = folsom_metrics:delete_metric(timed),
ok = folsom_metrics:delete_metric(timed2),
ok = folsom_metrics:delete_metric(testcounter),
ok = ensure_meter_tick_exists(2),
1 = length(ets:tab2list(?METER_TABLE)),
ok = folsom_metrics:delete_metric(meter),
0 = length(ets:tab2list(?METER_TABLE)),
1 = length(ets:tab2list(?METER_READER_TABLE)),
ok = folsom_metrics:delete_metric(meter_reader),
0 = length(ets:tab2list(?METER_READER_TABLE)),
ok = ensure_meter_tick_exists(0),
ok = folsom_metrics:delete_metric(duration),
ok = folsom_metrics:delete_metric(spiral),
ok = folsom_metrics:delete_metric(spiral_no_exceptions),
0 = length(ets:tab2list(?FOLSOM_TABLE)).
vm_metrics() ->
List1 = folsom_vm_metrics:get_memory(),
true = lists:keymember(total, 1, List1),
List2 = folsom_vm_metrics:get_statistics(),
true = lists:keymember(context_switches, 1, List2),
List3 = folsom_vm_metrics:get_system_info(),
true = lists:keymember(allocated_areas, 1, List3),
true = lists:keymember(port_count, 1, List3),
[{_, [{backtrace, _}| _]} | _] = folsom_vm_metrics:get_process_info(),
[{_, [{name, _}| _]} | _] = folsom_vm_metrics:get_port_info().
counter_metric(Count, Counter) ->
ok = folsom_metrics:new_counter(Counter),
?debugFmt("running ~p counter inc/dec rounds~n", [Count]),
for(Count, Counter),
Result = folsom_metrics:get_metric_value(Counter),
?debugFmt("counter result: ~p~n", [Result]),
0 = Result.
ensure_meter_tick_exists(MeterCnt) ->
{state, State} = folsom_meter_timer_server:dump(),
MeterCnt = length(State),
ok.
histogram_checks(List) ->
?debugFmt("checking histogram statistics", []),
?debugFmt("~p~n", [List]),
0 = proplists:get_value(min, List),
5000 = proplists:get_value(max, List),
869.6363636363636 = proplists:get_value(arithmetic_mean, List),
GeoMean = proplists:get_value(geometric_mean, List),
ok = case GeoMean - 100.17443147308997 of
GeoDiff when GeoDiff < 0.00000001 ->
ok;
_ ->
error
end,
Value = proplists:get_value(harmonic_mean, List),
ok = case Value - 8.333122900936845 of
Diff when Diff < 0.00000001 ->
ok;
_ ->
error
end,
200 = proplists:get_value(median, List),
2254368.454545454 = proplists:get_value(variance, List),
1501.4554454080394 = proplists:get_value(standard_deviation, List),
1.8399452806806476 = proplists:get_value(skewness, List),
2.2856772911293204 = proplists:get_value(kurtosis, List),
List1 = proplists:get_value(percentile, List),
percentile_check(List1),
List2 = proplists:get_value(histogram, List),
histogram_check(List2).
huge_histogram_checks(List) ->
Skew = erlang:abs(proplists:get_value(skewness, List)),
A = skewness_is_too_high_for_sample_of_this_size,
B = this_event_is_very_unprobable,
C = please_rerun_this_test__if_it_fails_again_your_code_is_bugged,
{A, B, C, true} = {A, B, C, Skew < 0.2}.
histogram_co_checks(List) ->
?debugFmt("checking histogram covariance and etc statistics", []),
?debugFmt("~p~n", [List]),
[
{covariance,17209.545454545456},
{tau,1.0},
{rho,0.760297020598996},
{r,1.0}
] = List.
percentile_check(List) ->
750 = proplists:get_value(75, List),
2000 = proplists:get_value(95, List),
5000 = proplists:get_value(99, List),
5000 = proplists:get_value(999, List).
histogram_check(List) ->
[{2400,10},{5000,1},{8000,0}] = List.
counter_inc_dec(Counter) ->
ok = folsom_metrics:notify({Counter, {inc, 1}}),
ok = folsom_metrics:notify({Counter, {dec, 1}}).
for(N, Counter) ->
for(N, 0, Counter).
for(N, Count, _Counter) when N == Count ->
ok;
for(N, LoopCount, Counter) ->
counter_inc_dec(Counter),
for(N, LoopCount + 1, Counter).
cpu_topology() ->
?debugMsg("Testing various CPU topologies ...~n"),
P = "test/cpu_topo_data",
Path = case filelib:is_regular(P) of
true -> P;
false -> filename:join("..", P)
end,
{ok, [Data]} = file:consult(Path),
[run_convert_and_jsonify(Item) || Item <- Data].
run_convert_and_jsonify(Item) ->
?debugFmt("Converting ... ~n~p~n", [Item]),
Result = folsom_vm_metrics:convert_system_info(cpu_topology, Item),
mochijson2:encode(Result).
c_compiler_used() ->
Test = [{gnuc, {4,4,5}},
{gnuc, {4,4}},
{msc, 1600}],
Expected = [[{compiler, gnuc}, {version, <<"4.4.5">>}],
[{compiler, gnuc}, {version, <<"4.4">>}],
[{compiler, msc}, {version, <<"1600">>}]],
?assertEqual(Expected, [folsom_vm_metrics:convert_system_info(c_compiler_used, {Compiler, Version})
|| {Compiler, Version} <- Test]).
duration_check(Duration) ->
[?assert(lists:keymember(Key, 1, Duration)) || Key <-
[count, last, min, max, arithmetic_mean,
geometric_mean, harmonic_mean, median,
variance, standard_deviation, skewness,
kurtosis, percentile, histogram]],
?assertEqual(10, proplists:get_value(count, Duration)),
Last = proplists:get_value(last, Duration),
?assert(Last > 10000).
create_delete_metrics() ->
?assertMatch(ok, folsom_metrics:new_counter(counter)),
?assertMatch(ok, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)),
?assertMatch(1, folsom_metrics:get_metric_value(counter)),
?assertMatch(ok, folsom_metrics:delete_metric(counter)),
?assertError(badarg, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)),
?assertMatch(ok, folsom_metrics:new_counter(counter)),
?assertMatch(ok, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)),
?assertMatch(1, folsom_metrics:get_metric_value(counter)).
set_enabled_metrics(Enabled) ->
application:set_env(folsom, enabled_metrics, Enabled).
subset_checks(List, Enabled) ->
?debugFmt("checking subset statistics", []),
?debugFmt("~p, ~p~n", [List, Enabled]),
Disabled = ?DEFAULT_METRICS -- Enabled,
true = lists:all(fun(K) ->
proplists:get_value(K, List) == undefined
end,
Disabled),
true = lists:all(fun(K) ->
proplists:get_value(K, List) /= undefined
end,
Enabled).
check_ets_leak() ->
L = ["gauge", "meter", "spiral"],
[begin
Name = list_to_atom(X ++ "_ets_leak"),
Table = list_to_atom("folsom_" ++ X ++ "s"),
Metric = list_to_atom(X),
[spawn(
fun() ->
folsom_metrics:notify(Name, 1, Metric)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(Table, Name)))
end || X <- L],
[spawn(
fun() ->
folsom_metrics:notify(counter_ets_leak, {inc, 1}, counter)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(folsom_counters, {counter_ets_leak, 0}))),
[spawn(
fun() ->
folsom_metrics:notify(history_ets_leak, <<"hist">>, history)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(folsom_histories, history_ets_leak))),
[spawn(
fun() ->
folsom_metrics:new_meter_reader(meter_reader_ets_leak)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(folsom_meter_readers, meter_reader_ets_leak))),
[spawn(
fun() ->
folsom_metrics:new_duration(duration_ets_leak)
end) || _ <- lists:seq(1, 1000)],
receive
after 100 ->
ok
end,
?assertEqual(1, length(ets:lookup(folsom_durations, duration_ets_leak))).
|
87510c114ba91a12008c88c51f9e952de33f317fbeffecb301e81881446316e4 | haskus/packages | Error.hs | # LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE PolyKinds #
-- | Type-level Error
module Haskus.Utils.Types.Error
( TypeError
, ErrorMessage (..)
, Assert
)
where
import GHC.TypeLits
-- | Like: If cond t (TypeError msg)
--
The difference is that the TypeError does n't appear in the RHS of the type
which leads to better error messages ( see GHC # 14771 ) .
--
-- For instance:
-- type family F n where
-- F n = If (n <=? 8) Int8 (TypeError (Text "ERROR"))
--
-- type family G n where
-- G n = Assert (n <=? 8) Int8 (Text "ERROR")
--
If GHC can not solve ` F n ~ Word ` , it shows : ERROR
If GHC can not solve ` G n ~ Word ` , it shows :
ca n't match ` Assert ... ` with ` Word `
--
type family Assert (prop :: Bool) (val :: k) (msg :: ErrorMessage) :: k where
Assert 'True val msg = val
Assert 'False val msg = TypeError msg
| null | https://raw.githubusercontent.com/haskus/packages/40ea6101cea84e2c1466bc55cdb22bed92f642a2/haskus-utils-types/src/lib/Haskus/Utils/Types/Error.hs | haskell | | Type-level Error
| Like: If cond t (TypeError msg)
For instance:
type family F n where
F n = If (n <=? 8) Int8 (TypeError (Text "ERROR"))
type family G n where
G n = Assert (n <=? 8) Int8 (Text "ERROR")
| # LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE PolyKinds #
module Haskus.Utils.Types.Error
( TypeError
, ErrorMessage (..)
, Assert
)
where
import GHC.TypeLits
The difference is that the TypeError does n't appear in the RHS of the type
which leads to better error messages ( see GHC # 14771 ) .
If GHC can not solve ` F n ~ Word ` , it shows : ERROR
If GHC can not solve ` G n ~ Word ` , it shows :
ca n't match ` Assert ... ` with ` Word `
type family Assert (prop :: Bool) (val :: k) (msg :: ErrorMessage) :: k where
Assert 'True val msg = val
Assert 'False val msg = TypeError msg
|
cc61a5d9abc6d63b25f9e64f239447c1cba9b4c5d09a3f3980cb5aaada82f0a0 | openbadgefactory/salava | settings_test.clj | (ns salava.page.settings-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]
[salava.core.helper :refer [dump]]))
(def test-user 1)
(def page-id 1)
(def page-owned-by-another-user 3)
(facts "about editing page settings"
(fact "user must be logged in to view page settings"
(:status (test-api-request :get (str "/page/settings/" page-id))) => 401)
(apply login! (test-user-credentials test-user))
(fact "user cannot access the settings of the page owned by another user"
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-owned-by-another-user))]
status => 500
body => "{\"errors\":\"(not (map? nil))\"}"))
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-id))]
(fact "page settings can be fetched for editing"
status => 200)
(fact "page has valid attributes"
(keys body) => (just [:description :tags :first_name :password :name :visible_before :visible_after :theme :ctime :id :padding :last_name :user_id :border :visibility :mtime] :in-any-order)))
(logout!))
(facts "about saving page settings"
(fact "user must be logged in to save page settings"
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 401)
(apply login! (test-user-credentials test-user))
(fact "user must be owner of the page"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-owned-by-another-user) {:password "" :tags [] :visibility "private"})]
status => 200
(:status body) => "error"))
(fact "visibility, password and tags are required"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {})]
status => 400
body => "{\"errors\":{\"tags\":\"missing-required-key\",\"visibility\":\"missing-required-key\",\"password\":\"missing-required-key\"}}"))
(fact "visibility must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "not-valid"})]
status => 400
body => "{\"errors\":{\"visibility\":\"(not (#{\\\"internal\\\" \\\"private\\\" \\\"password\\\" \\\"public\\\"} \\\"not-valid\\\"))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200)
(fact "tags must be a collection of strings"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags "not-valid" :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":\"(not (sequential? \\\"not-valid\\\"))\"}}")
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [0 1] :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":[\"(not (instance? java.lang.String 0))\",\"(not (instance? java.lang.String 1))\"]}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "secret" :tags ["tag" "another tag"] :visibility "password"})) => 200)
(fact "password must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password 0 :tags [] :visibility "password"})]
status => 400
body => "{\"errors\":{\"password\":\"(not (instance? java.lang.String 0))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "secret" :tags [] :visibility "password"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "not-saved" :tags [] :visibility "private"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:password body) => "")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "password"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:visibility body) => "private"))
(logout!))
(migrator/reset-seeds (migrator/test-config)) | null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/test_old/clj/salava/page/settings_test.clj | clojure | (ns salava.page.settings-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]
[salava.core.helper :refer [dump]]))
(def test-user 1)
(def page-id 1)
(def page-owned-by-another-user 3)
(facts "about editing page settings"
(fact "user must be logged in to view page settings"
(:status (test-api-request :get (str "/page/settings/" page-id))) => 401)
(apply login! (test-user-credentials test-user))
(fact "user cannot access the settings of the page owned by another user"
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-owned-by-another-user))]
status => 500
body => "{\"errors\":\"(not (map? nil))\"}"))
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-id))]
(fact "page settings can be fetched for editing"
status => 200)
(fact "page has valid attributes"
(keys body) => (just [:description :tags :first_name :password :name :visible_before :visible_after :theme :ctime :id :padding :last_name :user_id :border :visibility :mtime] :in-any-order)))
(logout!))
(facts "about saving page settings"
(fact "user must be logged in to save page settings"
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 401)
(apply login! (test-user-credentials test-user))
(fact "user must be owner of the page"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-owned-by-another-user) {:password "" :tags [] :visibility "private"})]
status => 200
(:status body) => "error"))
(fact "visibility, password and tags are required"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {})]
status => 400
body => "{\"errors\":{\"tags\":\"missing-required-key\",\"visibility\":\"missing-required-key\",\"password\":\"missing-required-key\"}}"))
(fact "visibility must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "not-valid"})]
status => 400
body => "{\"errors\":{\"visibility\":\"(not (#{\\\"internal\\\" \\\"private\\\" \\\"password\\\" \\\"public\\\"} \\\"not-valid\\\"))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200)
(fact "tags must be a collection of strings"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags "not-valid" :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":\"(not (sequential? \\\"not-valid\\\"))\"}}")
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [0 1] :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":[\"(not (instance? java.lang.String 0))\",\"(not (instance? java.lang.String 1))\"]}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "secret" :tags ["tag" "another tag"] :visibility "password"})) => 200)
(fact "password must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password 0 :tags [] :visibility "password"})]
status => 400
body => "{\"errors\":{\"password\":\"(not (instance? java.lang.String 0))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "secret" :tags [] :visibility "password"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "not-saved" :tags [] :visibility "private"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:password body) => "")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "password"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:visibility body) => "private"))
(logout!))
(migrator/reset-seeds (migrator/test-config)) |
|
2c59cf26d16631031502ef43e5ce3f5e052b88a21a544940a6255bc7df984fa3 | haskell-repa/repa | Layout.hs |
module Data.Repa.Array.Internals.Layout
(Layout (..), LayoutI)
where
import Data.Repa.Array.Internals.Shape
-- | A layout provides a total order on the elements of an index space.
--
-- We can talk about the n-th element of an array, independent of its
-- shape and dimensionality.
--
class Shape (Index l) => Layout l where
-- | Short name for a layout which does not include details of
-- the exact extent.
data Name l
-- | Type used to index into this array layout.
type Index l
-- | O(1). Proxy for the layout name.
name :: Name l
-- | O(1). Create a default layout of the given extent.
create :: Name l -> Index l -> l
-- | O(1). Yield the extent of the layout.
extent :: l -> Index l
-- | O(1). Convert a polymorphic index to a linear one.
toIndex :: l -> Index l -> Int
-- | O(1). Convert a linear index to a polymorphic one.
fromIndex :: l -> Int -> Index l
type LayoutI l = (Layout l, Index l ~ Int)
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-array/Data/Repa/Array/Internals/Layout.hs | haskell | | A layout provides a total order on the elements of an index space.
We can talk about the n-th element of an array, independent of its
shape and dimensionality.
| Short name for a layout which does not include details of
the exact extent.
| Type used to index into this array layout.
| O(1). Proxy for the layout name.
| O(1). Create a default layout of the given extent.
| O(1). Yield the extent of the layout.
| O(1). Convert a polymorphic index to a linear one.
| O(1). Convert a linear index to a polymorphic one. |
module Data.Repa.Array.Internals.Layout
(Layout (..), LayoutI)
where
import Data.Repa.Array.Internals.Shape
class Shape (Index l) => Layout l where
data Name l
type Index l
name :: Name l
create :: Name l -> Index l -> l
extent :: l -> Index l
toIndex :: l -> Index l -> Int
fromIndex :: l -> Int -> Index l
type LayoutI l = (Layout l, Index l ~ Int)
|
addc9232758306c91e7392f51f65a8c63448934764d69c59e20d2b3daa536f0c | portkey-cloud/aws-clj-sdk | _2016-09-29.clj | (ns portkey.aws.cloudfront.-2016-09-29 (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"us-east-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"sa-east-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ap-southeast-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ap-northeast-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"eu-west-3"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ca-central-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"eu-central-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"eu-west-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"us-west-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ap-south-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"aws-global"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4}})
(comment TODO support "rest-xml")
| null | https://raw.githubusercontent.com/portkey-cloud/aws-clj-sdk/10623a5c86bd56c8b312f56b76ae5ff52c26a945/src/portkey/aws/cloudfront/_2016-09-29.clj | clojure | (ns portkey.aws.cloudfront.-2016-09-29 (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"us-east-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"sa-east-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ap-southeast-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ap-northeast-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"eu-west-3"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ca-central-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"eu-central-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"eu-west-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"us-west-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"ap-south-1"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4},
"aws-global"
{:credential-scope {:service "cloudfront", :region "us-east-1"},
:ssl-common-name "cloudfront.amazonaws.com",
:endpoint "",
:signature-version :v4}})
(comment TODO support "rest-xml")
|
|
52d8cf66b6ed04c9ce24f72ebfe6f6885b810904ee5dfa98f5bd6b006bd4d90d | sorenmacbeth/flambo | accumulator.clj | (ns flambo.accumulator
(:import [org.apache.spark Accumulator]
[scala.Option])
(:refer-clojure :exclude [name]))
(defn accumulator
([sc value]
(.accumulator sc value))
([sc value name]
(.accumulator sc value name)))
(defn value [^Accumulator accumulator-var]
(.value accumulator-var))
(defn add [^Accumulator accumulator-var value]
(.add accumulator-var (int value)))
(defn name [^Accumulator accumulator-var]
(let [name-var (.name accumulator-var)]
(if (= scala.Some (class name-var))
(.x name-var))))
| null | https://raw.githubusercontent.com/sorenmacbeth/flambo/9c61467697547c5fe3d05070be84cd2320cb53ce/src/clojure/flambo/accumulator.clj | clojure | (ns flambo.accumulator
(:import [org.apache.spark Accumulator]
[scala.Option])
(:refer-clojure :exclude [name]))
(defn accumulator
([sc value]
(.accumulator sc value))
([sc value name]
(.accumulator sc value name)))
(defn value [^Accumulator accumulator-var]
(.value accumulator-var))
(defn add [^Accumulator accumulator-var value]
(.add accumulator-var (int value)))
(defn name [^Accumulator accumulator-var]
(let [name-var (.name accumulator-var)]
(if (= scala.Some (class name-var))
(.x name-var))))
|
|
34259a975dc4a994782690bef6c3c2705d79ebf8a4eb0b10bd24923a11daaf03 | jeapostrophe/exp | rom-link2.rkt | #lang racket
(require racket/cmdline)
(define wahcade-lst
(command-line #:program "rom-link2"
#:args (wahcade-lst) wahcade-lst))
(define (linkum name rom)
(define rom-pth
(build-path (current-directory)
"Roms"
(string-append rom ".nes")))
(define link-pth
(build-path (current-directory)
"Romsl"
(string-append name ".nes")))
(unless (file-exists? rom-pth)
(printf "~v\n" (list wahcade-lst name rom rom-pth))
(exit 1))
(make-file-or-directory-link rom-pth link-pth))
(let loop ([ls (file->lines wahcade-lst)])
(unless (empty? ls)
(define-values (fi nls) (split-at ls 13))
(match fi
[(list (? string? rom) (? string? name) "" "" "" "" "" "" "" "" "" "" "")
(linkum name rom)]
[_
(error 'rom-link2 "~S" fi)])
(loop nls))) | null | https://raw.githubusercontent.com/jeapostrophe/exp/43615110fd0439d2ef940c42629fcdc054c370f9/rom-link2.rkt | racket | #lang racket
(require racket/cmdline)
(define wahcade-lst
(command-line #:program "rom-link2"
#:args (wahcade-lst) wahcade-lst))
(define (linkum name rom)
(define rom-pth
(build-path (current-directory)
"Roms"
(string-append rom ".nes")))
(define link-pth
(build-path (current-directory)
"Romsl"
(string-append name ".nes")))
(unless (file-exists? rom-pth)
(printf "~v\n" (list wahcade-lst name rom rom-pth))
(exit 1))
(make-file-or-directory-link rom-pth link-pth))
(let loop ([ls (file->lines wahcade-lst)])
(unless (empty? ls)
(define-values (fi nls) (split-at ls 13))
(match fi
[(list (? string? rom) (? string? name) "" "" "" "" "" "" "" "" "" "" "")
(linkum name rom)]
[_
(error 'rom-link2 "~S" fi)])
(loop nls))) |
|
c7263c5c0e1d1edeaf6643bbd55226839e0979f59e56b67e2920553a07973636 | k0001/di | Types.hs | # LANGUAGE FlexibleInstances #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE TypeSynonymInstances #-}
module Df1.Types
( Log(Log, log_time, log_level, log_path, log_message)
, Level(Debug, Info, Notice, Warning, Error, Critical, Alert, Emergency)
, Path(Attr, Push), ToPath(path)
, Segment, unSegment, ToSegment(segment)
, Key, unKey, ToKey(key)
, Value, unValue, ToValue(value)
, Message, unMessage, ToMessage(message)
) where
import Control.Exception (SomeException)
import Data.Coerce (coerce)
import qualified Data.Fixed as Fixed
import Data.Foldable (toList)
import Data.Semigroup (Semigroup((<>)))
import Data.Sequence as Seq
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Word (Word8, Word16, Word32, Word64)
import Numeric.Natural (Natural)
import Data.String (IsString(fromString))
import qualified Data.Time as Time
import qualified Data.Time.Clock.System as Time
import qualified Data.Time.Format.ISO8601 as Time
--------------------------------------------------------------------------------
data Log = Log
{ log_time :: !Time.SystemTime
^ First known timestamp when the log was generated .
--
We use ' Time . SystemTime ' rather than ' Time . UTCTime ' because it is
-- cheaper to obtain and to render. You can use
-- 'Data.Time.Clock.System.systemToUTCTime' to convert it if necessary.
, log_level :: !Level
-- ^ Importance level of the logged message.
, log_path :: !(Seq.Seq Path)
-- ^ 'Path' where the logged message was created from.
--
-- The leftmost 'Path' is the closest to the root. The rightmost 'Path' is
the one closest to where the log was generated .
--
-- An 'Seq.empty' 'Seq.Seq' is acceptable, conveying the idea of the “root
-- path”.
, log_message :: !Message
-- ^ Human-readable message itself.
} deriving (Eq, Show)
--------------------------------------------------------------------------------
-- | A message text.
--
If you have the @OverloadedStrings@ GHC extension enabled , you can build a
-- 'Message' using a string literal:
--
-- @
-- \"foo\" :: 'Message'
-- @
--
-- Otherwise, you can use 'fromString' or 'message'.
--
Notice that @\"\ " : : ' Message'@ is acceptable , and will be correctly rendered
-- and parsed back.
newtype Message = Message TL.Text
deriving (Eq, Show)
unMessage :: Message -> TL.Text
unMessage = coerce
# INLINE unMessage #
instance IsString Message where
fromString = message
{-# INLINE fromString #-}
instance Semigroup Message where
(<>) = coerce ((<>) :: TL.Text -> TL.Text -> TL.Text)
{-# INLINE (<>) #-}
instance Monoid Message where
mempty = Message mempty
# INLINE mempty #
-- | Convert an arbitrary type to a 'Message'.
--
You are encouraged to create custom ' ToMessage ' instances for your types
-- making sure you avoid rendering sensitive details such as passwords, so that
-- they don't accidentally end up in logs.
--
-- Any characters that need to be escaped for rendering will be automatically
-- escaped at rendering time. You don't need to escape them here.
class ToMessage a where
message :: a -> Message
-- | Identity.
instance ToMessage Message where
message = id
# INLINE message #
-- |
-- @
x : : ' TL.Text ' = = ' unMessage ' ( ' message ' x )
-- @
instance ToMessage TL.Text where
message = Message
# INLINE message #
-- |
-- @
-- x :: 'T.Text' == 'TL.toStrict' ('unMessage' ('message' x))
-- @
instance ToMessage T.Text where
message = Message . TL.fromStrict
# INLINE message #
-- |
-- @
x : : ' String ' = = ' TL.unpack ' ( ' unMessage ' ( ' message ' x ) )
-- @
instance ToMessage String where
message = Message . TL.pack
# INLINE message #
instance ToMessage SomeException where
message = message . show
# INLINE message #
--------------------------------------------------------------------------------
-- | Importance of the logged message.
--
-- These levels, listed in increasing order of importance, correspond to the
-- levels used by [syslog(3)]().
data Level
= Debug
-- ^ Message intended to be useful only when deliberately debugging a program.
| Info
-- ^ Informational message.
| Notice
-- ^ A condition that is not an error, but should possibly be handled
-- specially.
| Warning
-- ^ A warning condition, such as an exception being gracefully handled or
-- some missing configuration setting being assigned a default value.
| Error
-- ^ Error condition, such as an unhandled exception.
| Critical
-- ^ Critical condition that could result in system failure, such as a disk
-- running out of space.
| Alert
-- ^ A condition that should be corrected immediately, such as a corrupted
-- database.
| Emergency
-- ^ System is unusable.
deriving (Eq, Show, Read, Bounded, Enum)
-- | Order of importance. For example, 'Emergency' is more important than
-- 'Debug':
--
-- @
-- 'Emergency' > 'Debug' == 'True'
-- @
deriving instance Ord Level
--------------------------------------------------------------------------------
-- | A path segment.
--
If you have the @OverloadedStrings@ GHC extension enabled , you can build a
-- 'Segment' using a string literal:
--
-- @
-- \"foo\" :: 'Segment'
-- @
--
-- Otherwise, you can use 'fromString' or 'segment'.
--
-- Notice that @\"\" :: 'Segment'@ is acceptable, and will be correctly rendered
-- and parsed back.
newtype Segment = Segment TL.Text
deriving (Eq, Show)
unSegment :: Segment -> TL.Text
unSegment = coerce
# INLINE unSegment #
instance IsString Segment where
fromString = segment
{-# INLINE fromString #-}
instance Semigroup Segment where
(<>) = coerce ((<>) :: TL.Text -> TL.Text -> TL.Text)
{-# INLINE (<>) #-}
instance Monoid Segment where
mempty = Segment mempty
# INLINE mempty #
-- | Convert an arbitrary type to a 'Segment'.
--
You are encouraged to create custom ' ' instances for your types
-- making sure you avoid rendering sensitive details such as passwords, so that
-- they don't accidentally end up in logs.
--
-- Any characters that need to be escaped for rendering will be automatically
-- escaped at rendering time. You don't need to escape them here.
class ToSegment a where
segment :: a -> Segment
-- | Identity.
instance ToSegment Segment where
segment = id
# INLINE segment #
-- |
-- @
x : : ' TL.Text ' = = ' unSegment ' ( ' segment ' x )
-- @
instance ToSegment TL.Text where
segment = Segment
# INLINE segment #
-- |
-- @
-- x :: 'T.Text' == 'TL.toStrict' ('unSegment' ('segment' x))
-- @
instance ToSegment T.Text where
segment = Segment . TL.fromStrict
# INLINE segment #
-- |
-- @
x : : ' String ' = = ' TL.unpack ' ( ' unSegment ' ( ' segment ' x ) )
-- @
instance ToSegment String where
segment = Segment . TL.pack
# INLINE segment #
instance ToSegment Char where
segment = Segment . TL.singleton
# INLINE segment #
--------------------------------------------------------------------------------
-- | An attribute key (see 'Attr').
--
If you have the @OverloadedStrings@ GHC extension enabled , you can build a
-- 'Key' using a string literal:
--
-- @
-- \"foo\" :: 'Key'
-- @
--
-- Otherwise, you can use 'fromString' or 'key'.
--
Notice that @\"\ " : : ' Key'@ is acceptable , and will be correctly rendered and
-- parsed back.
newtype Key = Key TL.Text
deriving (Eq, Show)
unKey :: Key -> TL.Text
unKey = coerce
# INLINE unKey #
instance IsString Key where
fromString = key
{-# INLINE fromString #-}
instance Semigroup Key where
(<>) = coerce ((<>) :: TL.Text -> TL.Text -> TL.Text)
{-# INLINE (<>) #-}
instance Monoid Key where
mempty = Key mempty
# INLINE mempty #
-- | Convert an arbitrary type to a 'Key'.
--
You are encouraged to create custom ' ToKey ' instances for your types
-- making sure you avoid rendering sensitive details such as passwords, so that
-- they don't accidentally end up in logs.
--
-- Any characters that need to be escaped for rendering will be automatically
-- escaped at rendering time. You don't need to escape them here.
class ToKey a where
key :: a -> Key
-- | Identity.
instance ToKey Key where
key = id
# INLINE key #
-- |
-- @
x : : ' TL.Text ' = = ' unKey ' ( ' key ' x )
-- @
instance ToKey TL.Text where
key = Key
# INLINE key #
-- |
-- @
x : : ' T.Text ' = = ' TL.toStrict ' ( ' unKey ' ( ' key ' x ) )
-- @
instance ToKey T.Text where
key = Key . TL.fromStrict
# INLINE key #
-- |
-- @
x : : ' String ' = = ' TL.unpack ' ( ' unKey ' ( ' key ' x ) )
-- @
instance ToKey String where
key = Key . TL.pack
# INLINE key #
instance ToKey Char where
key = Key . TL.singleton
# INLINE key #
--------------------------------------------------------------------------------
-- | An attribute value (see 'Attr').
--
If you have the @OverloadedStrings@ GHC extension enabled , you can build a
-- 'Value' using a string literal:
--
-- @
-- \"foo\" :: 'Value'
-- @
--
-- Otherwise, you can use 'fromString' or 'value'.
--
Notice that @\"\ " : : ' Value'@ is acceptable , and will be correctly rendered
-- and parsed back.
newtype Value = Value TL.Text
deriving (Eq, Show)
unValue :: Value -> TL.Text
unValue = coerce
# INLINE unValue #
instance IsString Value where
fromString = value
{-# INLINE fromString #-}
instance Semigroup Value where
(<>) = coerce ((<>) :: TL.Text -> TL.Text -> TL.Text)
{-# INLINE (<>) #-}
instance Monoid Value where
mempty = Value mempty
# INLINE mempty #
-- | Convert an arbitrary type to a 'Value'.
--
You are encouraged to create custom ' ToValue ' instances for your types
-- making sure you avoid rendering sensitive details such as passwords, so that
-- they don't accidentally end up in logs.
--
-- Any characters that need to be escaped for rendering will be automatically
-- escaped at rendering time. You don't need to escape them here.
class ToValue a where
value :: a -> Value
-- | Identity.
instance ToValue Value where
value = id
# INLINE value #
-- |
-- @
x : : ' TL.Text ' = = ' unValue ' ( ' value ' x )
-- @
instance ToValue TL.Text where
value = Value
# INLINE value #
-- |
-- @
-- x :: 'T.Text' == 'TL.toStrict' ('unValue' ('value' x))
-- @
instance ToValue T.Text where
value = Value . TL.fromStrict
# INLINE value #
-- |
-- @
x : : ' String ' = = ' TL.unpack ' ( ' unValue ' ( ' value ' x ) )
-- @
instance ToValue String where
value = Value . TL.pack
# INLINE value #
instance ToValue SomeException where
value = value . show
# INLINE value #
instance ToValue Bool where
value = \b -> if b then "true" else "false"
# INLINE value #
instance ToValue Char where
value = Value . TL.singleton
# INLINE value #
instance ToValue Int where
value = value . show
# INLINE value #
instance ToValue Int8 where
value = value . show
# INLINE value #
instance ToValue Int16 where
value = value . show
# INLINE value #
instance ToValue Int32 where
value = value . show
# INLINE value #
instance ToValue Int64 where
value = value . show
# INLINE value #
instance ToValue Word where
value = value . show
# INLINE value #
instance ToValue Word8 where
value = value . show
# INLINE value #
instance ToValue Word16 where
value = value . show
# INLINE value #
instance ToValue Word32 where
value = value . show
# INLINE value #
instance ToValue Word64 where
value = value . show
# INLINE value #
instance ToValue Integer where
value = value . show
# INLINE value #
instance ToValue Natural where
value = value . show
# INLINE value #
instance ToValue Float where
value = value . show
# INLINE value #
instance ToValue Double where
value = value . show
# INLINE value #
| Chops trailing zeros .
instance Fixed.HasResolution a => ToValue (Fixed.Fixed a) where
value = value . Fixed.showFixed True
# INLINE value #
| See ' Time . ' .
instance ToValue Time.CalendarDiffDays where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.CalendarDiffTime where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.Day where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.TimeZone where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.TimeOfDay where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.LocalTime where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.ZonedTime where
value = value . Time.iso8601Show
# INLINE value #
-- | @123456s@
instance ToValue Time.NominalDiffTime where
value = value . show
# INLINE value #
-- | @123456s@
instance ToValue Time.DiffTime where
value = value . show
# INLINE value #
| Lowercase @monday@ , @tuesday@ , etc .
instance ToValue Time.DayOfWeek where
value = \x -> case x of
Time.Monday -> "monday"
Time.Tuesday -> "tuesday"
Time.Wednesday -> "wednesday"
Time.Thursday -> "thursday"
Time.Friday -> "friday"
Time.Saturday -> "saturday"
Time.Sunday -> "sunday"
--------------------------------------------------------------------------------
-- | 'Path' represents the hierarchical structure of logged messages.
--
-- For example, consider a /df1/ log line as like the following:
--
-- @
1999 - 12 - 20T07:11:39.230553031Z \/foo x = a y = b \/bar \/qux z = c z = d WARNING Something
-- @
--
-- For that line, the 'log_path' attribute of the 'Log' datatype will contain
-- the following:
--
-- @
-- [ 'Push' ('segment' \"foo\")
, ' Attr ' ( ' key ' \"x\ " ) ( ' value ' \"a\ " )
-- , 'Attr' ('key' \"y\") ('value' \"b\")
, ' Push ' ( ' segment ' \"bar\ " )
-- , 'Push' ('segment' \"qux\")
-- , 'Attr' ('key' \"z\") ('value' \"c\")
-- , 'Attr' ('key' \"z\") ('value' \"d\")
-- ] :: 'Seq.Seq' 'Path'
-- @
--
-- Please notice that @[] :: 'Seq.Seq' 'Path'@ is a valid path insofar as /df1/
-- is concerned, and that 'Attr' and 'Push' can be juxtapositioned in any order.
data Path
= Push !Segment
| Attr !Key !Value
deriving (Eq, Show)
-- | Convert an arbitrary type to a 'Seq'uence of 'Path's.
--
You are encouraged to create custom ' ToPath ' instances for your types
-- making sure you avoid rendering sensitive details such as passwords, so that
-- they don't accidentally end up in logs.
--
-- Any characters that need to be escaped for rendering will be automatically
-- escaped at rendering time. You don't need to escape them here.
class ToPath a where
-- | The leftmost 'Path' is the closest to the root. The rightmost 'Path' is
the one closest to where the log was generated .
--
-- See the documentation for 'Path'.
path :: a -> Seq.Seq Path
-- | Identity.
instance ToPath (Seq.Seq Path) where
path = id
# INLINE path #
-- |
-- @
-- 'path' = 'Seq.fromList' . 'toList'
-- @
instance {-# OVERLAPPABLE #-} Foldable f => ToPath (f Path) where
path = Seq.fromList . toList
# INLINE path #
| null | https://raw.githubusercontent.com/k0001/di/8d9a2aa33bfe42ece88bd398fb44aebcfb1a9525/df1/lib/Df1/Types.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE TypeSynonymInstances #
------------------------------------------------------------------------------
cheaper to obtain and to render. You can use
'Data.Time.Clock.System.systemToUTCTime' to convert it if necessary.
^ Importance level of the logged message.
^ 'Path' where the logged message was created from.
The leftmost 'Path' is the closest to the root. The rightmost 'Path' is
An 'Seq.empty' 'Seq.Seq' is acceptable, conveying the idea of the “root
path”.
^ Human-readable message itself.
------------------------------------------------------------------------------
| A message text.
'Message' using a string literal:
@
\"foo\" :: 'Message'
@
Otherwise, you can use 'fromString' or 'message'.
and parsed back.
# INLINE fromString #
# INLINE (<>) #
| Convert an arbitrary type to a 'Message'.
making sure you avoid rendering sensitive details such as passwords, so that
they don't accidentally end up in logs.
Any characters that need to be escaped for rendering will be automatically
escaped at rendering time. You don't need to escape them here.
| Identity.
|
@
@
|
@
x :: 'T.Text' == 'TL.toStrict' ('unMessage' ('message' x))
@
|
@
@
------------------------------------------------------------------------------
| Importance of the logged message.
These levels, listed in increasing order of importance, correspond to the
levels used by [syslog(3)]().
^ Message intended to be useful only when deliberately debugging a program.
^ Informational message.
^ A condition that is not an error, but should possibly be handled
specially.
^ A warning condition, such as an exception being gracefully handled or
some missing configuration setting being assigned a default value.
^ Error condition, such as an unhandled exception.
^ Critical condition that could result in system failure, such as a disk
running out of space.
^ A condition that should be corrected immediately, such as a corrupted
database.
^ System is unusable.
| Order of importance. For example, 'Emergency' is more important than
'Debug':
@
'Emergency' > 'Debug' == 'True'
@
------------------------------------------------------------------------------
| A path segment.
'Segment' using a string literal:
@
\"foo\" :: 'Segment'
@
Otherwise, you can use 'fromString' or 'segment'.
Notice that @\"\" :: 'Segment'@ is acceptable, and will be correctly rendered
and parsed back.
# INLINE fromString #
# INLINE (<>) #
| Convert an arbitrary type to a 'Segment'.
making sure you avoid rendering sensitive details such as passwords, so that
they don't accidentally end up in logs.
Any characters that need to be escaped for rendering will be automatically
escaped at rendering time. You don't need to escape them here.
| Identity.
|
@
@
|
@
x :: 'T.Text' == 'TL.toStrict' ('unSegment' ('segment' x))
@
|
@
@
------------------------------------------------------------------------------
| An attribute key (see 'Attr').
'Key' using a string literal:
@
\"foo\" :: 'Key'
@
Otherwise, you can use 'fromString' or 'key'.
parsed back.
# INLINE fromString #
# INLINE (<>) #
| Convert an arbitrary type to a 'Key'.
making sure you avoid rendering sensitive details such as passwords, so that
they don't accidentally end up in logs.
Any characters that need to be escaped for rendering will be automatically
escaped at rendering time. You don't need to escape them here.
| Identity.
|
@
@
|
@
@
|
@
@
------------------------------------------------------------------------------
| An attribute value (see 'Attr').
'Value' using a string literal:
@
\"foo\" :: 'Value'
@
Otherwise, you can use 'fromString' or 'value'.
and parsed back.
# INLINE fromString #
# INLINE (<>) #
| Convert an arbitrary type to a 'Value'.
making sure you avoid rendering sensitive details such as passwords, so that
they don't accidentally end up in logs.
Any characters that need to be escaped for rendering will be automatically
escaped at rendering time. You don't need to escape them here.
| Identity.
|
@
@
|
@
x :: 'T.Text' == 'TL.toStrict' ('unValue' ('value' x))
@
|
@
@
| @123456s@
| @123456s@
------------------------------------------------------------------------------
| 'Path' represents the hierarchical structure of logged messages.
For example, consider a /df1/ log line as like the following:
@
@
For that line, the 'log_path' attribute of the 'Log' datatype will contain
the following:
@
[ 'Push' ('segment' \"foo\")
, 'Attr' ('key' \"y\") ('value' \"b\")
, 'Push' ('segment' \"qux\")
, 'Attr' ('key' \"z\") ('value' \"c\")
, 'Attr' ('key' \"z\") ('value' \"d\")
] :: 'Seq.Seq' 'Path'
@
Please notice that @[] :: 'Seq.Seq' 'Path'@ is a valid path insofar as /df1/
is concerned, and that 'Attr' and 'Push' can be juxtapositioned in any order.
| Convert an arbitrary type to a 'Seq'uence of 'Path's.
making sure you avoid rendering sensitive details such as passwords, so that
they don't accidentally end up in logs.
Any characters that need to be escaped for rendering will be automatically
escaped at rendering time. You don't need to escape them here.
| The leftmost 'Path' is the closest to the root. The rightmost 'Path' is
See the documentation for 'Path'.
| Identity.
|
@
'path' = 'Seq.fromList' . 'toList'
@
# OVERLAPPABLE # | # LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
module Df1.Types
( Log(Log, log_time, log_level, log_path, log_message)
, Level(Debug, Info, Notice, Warning, Error, Critical, Alert, Emergency)
, Path(Attr, Push), ToPath(path)
, Segment, unSegment, ToSegment(segment)
, Key, unKey, ToKey(key)
, Value, unValue, ToValue(value)
, Message, unMessage, ToMessage(message)
) where
import Control.Exception (SomeException)
import Data.Coerce (coerce)
import qualified Data.Fixed as Fixed
import Data.Foldable (toList)
import Data.Semigroup (Semigroup((<>)))
import Data.Sequence as Seq
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Word (Word8, Word16, Word32, Word64)
import Numeric.Natural (Natural)
import Data.String (IsString(fromString))
import qualified Data.Time as Time
import qualified Data.Time.Clock.System as Time
import qualified Data.Time.Format.ISO8601 as Time
data Log = Log
{ log_time :: !Time.SystemTime
^ First known timestamp when the log was generated .
We use ' Time . SystemTime ' rather than ' Time . UTCTime ' because it is
, log_level :: !Level
, log_path :: !(Seq.Seq Path)
the one closest to where the log was generated .
, log_message :: !Message
} deriving (Eq, Show)
If you have the @OverloadedStrings@ GHC extension enabled , you can build a
Notice that @\"\ " : : ' Message'@ is acceptable , and will be correctly rendered
newtype Message = Message TL.Text
deriving (Eq, Show)
unMessage :: Message -> TL.Text
unMessage = coerce
# INLINE unMessage #
instance IsString Message where
fromString = message
instance Semigroup Message where
(<>) = coerce ((<>) :: TL.Text -> TL.Text -> TL.Text)
instance Monoid Message where
mempty = Message mempty
# INLINE mempty #
You are encouraged to create custom ' ToMessage ' instances for your types
class ToMessage a where
message :: a -> Message
instance ToMessage Message where
message = id
# INLINE message #
x : : ' TL.Text ' = = ' unMessage ' ( ' message ' x )
instance ToMessage TL.Text where
message = Message
# INLINE message #
instance ToMessage T.Text where
message = Message . TL.fromStrict
# INLINE message #
x : : ' String ' = = ' TL.unpack ' ( ' unMessage ' ( ' message ' x ) )
instance ToMessage String where
message = Message . TL.pack
# INLINE message #
instance ToMessage SomeException where
message = message . show
# INLINE message #
data Level
= Debug
| Info
| Notice
| Warning
| Error
| Critical
| Alert
| Emergency
deriving (Eq, Show, Read, Bounded, Enum)
deriving instance Ord Level
If you have the @OverloadedStrings@ GHC extension enabled , you can build a
newtype Segment = Segment TL.Text
deriving (Eq, Show)
unSegment :: Segment -> TL.Text
unSegment = coerce
# INLINE unSegment #
instance IsString Segment where
fromString = segment
instance Semigroup Segment where
(<>) = coerce ((<>) :: TL.Text -> TL.Text -> TL.Text)
instance Monoid Segment where
mempty = Segment mempty
# INLINE mempty #
You are encouraged to create custom ' ' instances for your types
class ToSegment a where
segment :: a -> Segment
instance ToSegment Segment where
segment = id
# INLINE segment #
x : : ' TL.Text ' = = ' unSegment ' ( ' segment ' x )
instance ToSegment TL.Text where
segment = Segment
# INLINE segment #
instance ToSegment T.Text where
segment = Segment . TL.fromStrict
# INLINE segment #
x : : ' String ' = = ' TL.unpack ' ( ' unSegment ' ( ' segment ' x ) )
instance ToSegment String where
segment = Segment . TL.pack
# INLINE segment #
instance ToSegment Char where
segment = Segment . TL.singleton
# INLINE segment #
If you have the @OverloadedStrings@ GHC extension enabled , you can build a
Notice that @\"\ " : : ' Key'@ is acceptable , and will be correctly rendered and
newtype Key = Key TL.Text
deriving (Eq, Show)
unKey :: Key -> TL.Text
unKey = coerce
# INLINE unKey #
instance IsString Key where
fromString = key
instance Semigroup Key where
(<>) = coerce ((<>) :: TL.Text -> TL.Text -> TL.Text)
instance Monoid Key where
mempty = Key mempty
# INLINE mempty #
You are encouraged to create custom ' ToKey ' instances for your types
class ToKey a where
key :: a -> Key
instance ToKey Key where
key = id
# INLINE key #
x : : ' TL.Text ' = = ' unKey ' ( ' key ' x )
instance ToKey TL.Text where
key = Key
# INLINE key #
x : : ' T.Text ' = = ' TL.toStrict ' ( ' unKey ' ( ' key ' x ) )
instance ToKey T.Text where
key = Key . TL.fromStrict
# INLINE key #
x : : ' String ' = = ' TL.unpack ' ( ' unKey ' ( ' key ' x ) )
instance ToKey String where
key = Key . TL.pack
# INLINE key #
instance ToKey Char where
key = Key . TL.singleton
# INLINE key #
If you have the @OverloadedStrings@ GHC extension enabled , you can build a
Notice that @\"\ " : : ' Value'@ is acceptable , and will be correctly rendered
newtype Value = Value TL.Text
deriving (Eq, Show)
unValue :: Value -> TL.Text
unValue = coerce
# INLINE unValue #
instance IsString Value where
fromString = value
instance Semigroup Value where
(<>) = coerce ((<>) :: TL.Text -> TL.Text -> TL.Text)
instance Monoid Value where
mempty = Value mempty
# INLINE mempty #
You are encouraged to create custom ' ToValue ' instances for your types
class ToValue a where
value :: a -> Value
instance ToValue Value where
value = id
# INLINE value #
x : : ' TL.Text ' = = ' unValue ' ( ' value ' x )
instance ToValue TL.Text where
value = Value
# INLINE value #
instance ToValue T.Text where
value = Value . TL.fromStrict
# INLINE value #
x : : ' String ' = = ' TL.unpack ' ( ' unValue ' ( ' value ' x ) )
instance ToValue String where
value = Value . TL.pack
# INLINE value #
instance ToValue SomeException where
value = value . show
# INLINE value #
instance ToValue Bool where
value = \b -> if b then "true" else "false"
# INLINE value #
instance ToValue Char where
value = Value . TL.singleton
# INLINE value #
instance ToValue Int where
value = value . show
# INLINE value #
instance ToValue Int8 where
value = value . show
# INLINE value #
instance ToValue Int16 where
value = value . show
# INLINE value #
instance ToValue Int32 where
value = value . show
# INLINE value #
instance ToValue Int64 where
value = value . show
# INLINE value #
instance ToValue Word where
value = value . show
# INLINE value #
instance ToValue Word8 where
value = value . show
# INLINE value #
instance ToValue Word16 where
value = value . show
# INLINE value #
instance ToValue Word32 where
value = value . show
# INLINE value #
instance ToValue Word64 where
value = value . show
# INLINE value #
instance ToValue Integer where
value = value . show
# INLINE value #
instance ToValue Natural where
value = value . show
# INLINE value #
instance ToValue Float where
value = value . show
# INLINE value #
instance ToValue Double where
value = value . show
# INLINE value #
| Chops trailing zeros .
instance Fixed.HasResolution a => ToValue (Fixed.Fixed a) where
value = value . Fixed.showFixed True
# INLINE value #
| See ' Time . ' .
instance ToValue Time.CalendarDiffDays where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.CalendarDiffTime where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.Day where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.TimeZone where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.TimeOfDay where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.LocalTime where
value = value . Time.iso8601Show
# INLINE value #
| See ' Time . ' .
instance ToValue Time.ZonedTime where
value = value . Time.iso8601Show
# INLINE value #
instance ToValue Time.NominalDiffTime where
value = value . show
# INLINE value #
instance ToValue Time.DiffTime where
value = value . show
# INLINE value #
| Lowercase @monday@ , @tuesday@ , etc .
instance ToValue Time.DayOfWeek where
value = \x -> case x of
Time.Monday -> "monday"
Time.Tuesday -> "tuesday"
Time.Wednesday -> "wednesday"
Time.Thursday -> "thursday"
Time.Friday -> "friday"
Time.Saturday -> "saturday"
Time.Sunday -> "sunday"
1999 - 12 - 20T07:11:39.230553031Z \/foo x = a y = b \/bar \/qux z = c z = d WARNING Something
, ' Attr ' ( ' key ' \"x\ " ) ( ' value ' \"a\ " )
, ' Push ' ( ' segment ' \"bar\ " )
data Path
= Push !Segment
| Attr !Key !Value
deriving (Eq, Show)
You are encouraged to create custom ' ToPath ' instances for your types
class ToPath a where
the one closest to where the log was generated .
path :: a -> Seq.Seq Path
instance ToPath (Seq.Seq Path) where
path = id
# INLINE path #
path = Seq.fromList . toList
# INLINE path #
|
c89af150a0b5ddfee3cdbb3e75a2402b069615b99cce488059e104b4064dee0e | sneeuwballen/zipperposition | Position.ml |
This file is free software , part of Logtk . See file " license " for more details .
(** {1 Positions in terms, clauses...} *)
(** A position is a path in a tree *)
type t =
| Stop
| Type of t (** Switch to type *)
| Left of t (** Left term in curried application *)
| Right of t (** Right term in curried application, and subterm of binder *)
| Head of t (** Head of uncurried term *)
| Arg of int * t (** argument term in uncurried term, or in multiset *)
| Body of t (** Body of binder *)
type position = t
let stop = Stop
let type_ pos = Type pos
let left pos = Left pos
let right pos = Right pos
let head pos = Head pos
let arg i pos = Arg (i, pos)
let body pos = Body pos
let compare = CCShims_.Stdlib.compare
let equal p1 p2 = compare p1 p2 = 0
let hash p = Hashtbl.hash p
let rec size = function
| Stop -> 0
| Type p | Left p | Right p | Head p | Arg(_,p) | Body p -> 1 + size p
let rev pos =
let rec aux acc pos = match pos with
| Stop -> acc
| Type pos' -> aux (Type acc) pos'
| Left pos' -> aux (Left acc) pos'
| Right pos' -> aux (Right acc) pos'
| Head pos' -> aux (Head acc) pos'
| Arg (i, pos') -> aux (Arg (i,acc)) pos'
| Body pos' -> aux (Body acc) pos'
in
aux Stop pos
let opp = function
| Left p -> Right p
| Right p -> Left p
| pos -> pos
(* Recursive append *)
let rec append p1 p2 = match p1 with
| Stop -> p2
| Type p1' -> Type (append p1' p2)
| Left p1' -> Left (append p1' p2)
| Right p1' -> Right (append p1' p2)
| Head p1' -> Head (append p1' p2)
| Arg(i, p1') -> Arg (i,append p1' p2)
| Body p1' -> Body (append p1' p2)
let rec pp out pos = match pos with
| Stop -> CCFormat.string out "ε"
| Type p' -> CCFormat.string out "τ."; pp out p'
| Left p' -> CCFormat.string out "←."; pp out p'
| Right p' -> CCFormat.string out "→."; pp out p'
| Head p' -> CCFormat.string out "@."; pp out p'
| Arg (i,p') -> Format.fprintf out "%d." i; pp out p'
| Body p' -> Format.fprintf out "β."; pp out p'
let to_string = CCFormat.to_string pp
let rec is_prefix p1 p2 : bool = match p1, p2 with
| Stop, _ -> true
| Left l1, Left l2
| Right l1, Right l2
| Head l1, Head l2
| Body l1, Body l2
| Type l1, Type l2
->
is_prefix l1 l2
| Arg (i1,l1), Arg (i2,l2) -> i1=i2 && is_prefix l1 l2
| Left _, _
| Right _, _
| Head _, _
| Body _, _
| Arg _, _
| Type _, _
-> false
let is_strict_prefix p1 p2 = not (equal p1 p2) && is_prefix p1 p2
let rec until_first_fun =
function
| Stop -> Stop
| Type p -> Type (until_first_fun p)
| Left p -> Left (until_first_fun p)
| Right p -> Right (until_first_fun p)
| Head p -> Head (until_first_fun p)
| Arg(i, p) -> Arg (i, until_first_fun p)
| Body _ -> Stop
let rec num_of_funs = function
| Stop -> 0
| Type p' | Left p' | Right p' | Head p' | Arg (_,p') ->
num_of_funs p'
| Body p' -> 1 + num_of_funs p'
module Map = struct
include CCMap.Make(struct
type t = position
let compare = compare
end)
let prune_subsumed (m:_ t): _ t =
filter
(fun k _ -> not (exists (fun k' _ -> is_strict_prefix k' k) m))
m
end
* { 2 Position builder }
We use an adaptation of difference lists for this tasks
We use an adaptation of difference lists for this tasks *)
module Build = struct
type t =
| E (** Empty (identity function) *)
| P of position * t (** Pre-pend given position, then apply previous builder *)
| N of (position -> position) * t
(** Apply function to position, then apply linked builder *)
let empty = E
let of_pos p = P (p, E)
(* how to apply a difference list to a tail list *)
let rec apply_rec tail b = match b with
| E -> tail
| P (pos0,b') -> apply_rec (append pos0 tail) b'
| N (f, b') -> apply_rec (f tail) b'
let apply_flip b pos = apply_rec pos b
let to_pos b = apply_rec stop b
let suffix b pos =
given a suffix , first append pos to it , then apply b
N ((fun pos0 -> append pos pos0), b)
let prefix pos b =
tricky : this does n't follow the recursive structure . Hence we
need to first apply b totally , then pre - prend pos
need to first apply b totally, then pre-prend pos *)
N ((fun pos1 -> append pos (apply_rec pos1 b)), E)
let append p1 p2 = N(apply_flip p2, p1)
let left b = N (left, b)
let right b = N (right, b)
let type_ b = N (type_, b)
let head b = N(head, b)
let arg i b = N(arg i, b)
let body b = N(body, b)
let pp out t = pp out (to_pos t)
let to_string t = to_string (to_pos t)
end
(** {2 Pairing of value with Pos} *)
module With = struct
type 'a t = 'a * position
let get = fst
let pos = snd
let make x p : _ t = x, p
let of_pair p = p
let map_pos f (x,pos) = x, f pos
let map f (x,pos) = f x, pos
module Infix = struct
let (>|=) x f = map f x
end
include Infix
let equal f t1 t2 = f (get t1) (get t2) && equal (pos t1) (pos t2)
let compare f t1 t2 =
let c = f (get t1) (get t2) in
if c=0 then compare (pos t1) (pos t2) else c
let hash f t = Hash.combine3 41 (f (get t)) (hash (pos t))
let pp f out t =
CCFormat.fprintf out "(@[:pos %a :in %a@])" pp (pos t) f (get t)
end
| null | https://raw.githubusercontent.com/sneeuwballen/zipperposition/71798cc0559d2c365ad43a0a54e204a2d079cebd/src/core/Position.ml | ocaml | * {1 Positions in terms, clauses...}
* A position is a path in a tree
* Switch to type
* Left term in curried application
* Right term in curried application, and subterm of binder
* Head of uncurried term
* argument term in uncurried term, or in multiset
* Body of binder
Recursive append
* Empty (identity function)
* Pre-pend given position, then apply previous builder
* Apply function to position, then apply linked builder
how to apply a difference list to a tail list
* {2 Pairing of value with Pos} |
This file is free software , part of Logtk . See file " license " for more details .
type t =
| Stop
type position = t
let stop = Stop
let type_ pos = Type pos
let left pos = Left pos
let right pos = Right pos
let head pos = Head pos
let arg i pos = Arg (i, pos)
let body pos = Body pos
let compare = CCShims_.Stdlib.compare
let equal p1 p2 = compare p1 p2 = 0
let hash p = Hashtbl.hash p
let rec size = function
| Stop -> 0
| Type p | Left p | Right p | Head p | Arg(_,p) | Body p -> 1 + size p
let rev pos =
let rec aux acc pos = match pos with
| Stop -> acc
| Type pos' -> aux (Type acc) pos'
| Left pos' -> aux (Left acc) pos'
| Right pos' -> aux (Right acc) pos'
| Head pos' -> aux (Head acc) pos'
| Arg (i, pos') -> aux (Arg (i,acc)) pos'
| Body pos' -> aux (Body acc) pos'
in
aux Stop pos
let opp = function
| Left p -> Right p
| Right p -> Left p
| pos -> pos
let rec append p1 p2 = match p1 with
| Stop -> p2
| Type p1' -> Type (append p1' p2)
| Left p1' -> Left (append p1' p2)
| Right p1' -> Right (append p1' p2)
| Head p1' -> Head (append p1' p2)
| Arg(i, p1') -> Arg (i,append p1' p2)
| Body p1' -> Body (append p1' p2)
let rec pp out pos = match pos with
| Stop -> CCFormat.string out "ε"
| Type p' -> CCFormat.string out "τ."; pp out p'
| Left p' -> CCFormat.string out "←."; pp out p'
| Right p' -> CCFormat.string out "→."; pp out p'
| Head p' -> CCFormat.string out "@."; pp out p'
| Arg (i,p') -> Format.fprintf out "%d." i; pp out p'
| Body p' -> Format.fprintf out "β."; pp out p'
let to_string = CCFormat.to_string pp
let rec is_prefix p1 p2 : bool = match p1, p2 with
| Stop, _ -> true
| Left l1, Left l2
| Right l1, Right l2
| Head l1, Head l2
| Body l1, Body l2
| Type l1, Type l2
->
is_prefix l1 l2
| Arg (i1,l1), Arg (i2,l2) -> i1=i2 && is_prefix l1 l2
| Left _, _
| Right _, _
| Head _, _
| Body _, _
| Arg _, _
| Type _, _
-> false
let is_strict_prefix p1 p2 = not (equal p1 p2) && is_prefix p1 p2
let rec until_first_fun =
function
| Stop -> Stop
| Type p -> Type (until_first_fun p)
| Left p -> Left (until_first_fun p)
| Right p -> Right (until_first_fun p)
| Head p -> Head (until_first_fun p)
| Arg(i, p) -> Arg (i, until_first_fun p)
| Body _ -> Stop
let rec num_of_funs = function
| Stop -> 0
| Type p' | Left p' | Right p' | Head p' | Arg (_,p') ->
num_of_funs p'
| Body p' -> 1 + num_of_funs p'
module Map = struct
include CCMap.Make(struct
type t = position
let compare = compare
end)
let prune_subsumed (m:_ t): _ t =
filter
(fun k _ -> not (exists (fun k' _ -> is_strict_prefix k' k) m))
m
end
* { 2 Position builder }
We use an adaptation of difference lists for this tasks
We use an adaptation of difference lists for this tasks *)
module Build = struct
type t =
| N of (position -> position) * t
let empty = E
let of_pos p = P (p, E)
let rec apply_rec tail b = match b with
| E -> tail
| P (pos0,b') -> apply_rec (append pos0 tail) b'
| N (f, b') -> apply_rec (f tail) b'
let apply_flip b pos = apply_rec pos b
let to_pos b = apply_rec stop b
let suffix b pos =
given a suffix , first append pos to it , then apply b
N ((fun pos0 -> append pos pos0), b)
let prefix pos b =
tricky : this does n't follow the recursive structure . Hence we
need to first apply b totally , then pre - prend pos
need to first apply b totally, then pre-prend pos *)
N ((fun pos1 -> append pos (apply_rec pos1 b)), E)
let append p1 p2 = N(apply_flip p2, p1)
let left b = N (left, b)
let right b = N (right, b)
let type_ b = N (type_, b)
let head b = N(head, b)
let arg i b = N(arg i, b)
let body b = N(body, b)
let pp out t = pp out (to_pos t)
let to_string t = to_string (to_pos t)
end
module With = struct
type 'a t = 'a * position
let get = fst
let pos = snd
let make x p : _ t = x, p
let of_pair p = p
let map_pos f (x,pos) = x, f pos
let map f (x,pos) = f x, pos
module Infix = struct
let (>|=) x f = map f x
end
include Infix
let equal f t1 t2 = f (get t1) (get t2) && equal (pos t1) (pos t2)
let compare f t1 t2 =
let c = f (get t1) (get t2) in
if c=0 then compare (pos t1) (pos t2) else c
let hash f t = Hash.combine3 41 (f (get t)) (hash (pos t))
let pp f out t =
CCFormat.fprintf out "(@[:pos %a :in %a@])" pp (pos t) f (get t)
end
|
6a73491e9c0b359bf55bd1b6436554ecc74915ebb08b472952e6fa84523b6b86 | bos/rwh | SuffixTree.hs | import Data.List
type Edge = (String, STree)
data STree = Node [Edge]
| Leaf
deriving (Show)
type EdgeFunction = [String] -> (Int, [String])
construct :: String -> STree
construct = suf . suffixes
where suf [[]] = Leaf
suf ss = Node [([a], suf n)
| a <- ['\0'..'\255'],
n@(sa:_) <- [ss `clusterBy` a]]
clusterBy ss a = [cs | c:cs <- ss, c == a]
construct2 :: EdgeFunction -> [Char] -> String -> STree
construct2 edge alphabet = suf . suffixes
where suf [[]] = Leaf
suf ss = Node [(take (cpl+1) (a:sa), suf ssr)
| a <- alphabet,
n@(sa:_) <- [ss `clusterBy` a],
(cpl,ssr) <- [edge n]]
clusterBy ss a = [cs | c:cs <- ss, c == a]
simple :: EdgeFunction
simple n = (0, n)
cst :: EdgeFunction
cst [s] = (length s, [[]])
cst awss@((a:w):ss)
| null [c | c:_ <- ss, a /= c] = (cpl + 1, rss)
| otherwise = (0, awss)
where (cpl, rss) = cst (w:[u | _:u <- ss])
{-- snippet suffixes --}
suffixes :: [a] -> [[a]]
suffixes xs@(_:xs') = xs : suffixes xs'
suffixes _ = []
{-- /snippet suffixes --}
{-- snippet noAsPattern --}
noAsPattern :: [a] -> [[a]]
noAsPattern (x:xs) = (x:xs) : noAsPattern xs
noAsPattern _ = []
{-- /snippet noAsPattern --}
{-- snippet suffixes2 --}
suffixes2 xs = init (tails xs)
{-- /snippet suffixes2 --}
{-- snippet compose --}
compose :: (b -> c) -> (a -> b) -> a -> c
compose f g x = f (g x)
{-- /snippet compose --}
- snippet suffixes3 -
suffixes3 xs = compose init tails xs
- /snippet suffixes3 -
- snippet suffixes4 -
suffixes4 = compose init tails
{-- /snippet suffixes4 --}
- snippet suffixes5 -
suffixes5 = init . tails
- /snippet suffixes5 -
| null | https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch05/SuffixTree.hs | haskell | - snippet suffixes -
- /snippet suffixes -
- snippet noAsPattern -
- /snippet noAsPattern -
- snippet suffixes2 -
- /snippet suffixes2 -
- snippet compose -
- /snippet compose -
- /snippet suffixes4 - | import Data.List
type Edge = (String, STree)
data STree = Node [Edge]
| Leaf
deriving (Show)
type EdgeFunction = [String] -> (Int, [String])
construct :: String -> STree
construct = suf . suffixes
where suf [[]] = Leaf
suf ss = Node [([a], suf n)
| a <- ['\0'..'\255'],
n@(sa:_) <- [ss `clusterBy` a]]
clusterBy ss a = [cs | c:cs <- ss, c == a]
construct2 :: EdgeFunction -> [Char] -> String -> STree
construct2 edge alphabet = suf . suffixes
where suf [[]] = Leaf
suf ss = Node [(take (cpl+1) (a:sa), suf ssr)
| a <- alphabet,
n@(sa:_) <- [ss `clusterBy` a],
(cpl,ssr) <- [edge n]]
clusterBy ss a = [cs | c:cs <- ss, c == a]
simple :: EdgeFunction
simple n = (0, n)
cst :: EdgeFunction
cst [s] = (length s, [[]])
cst awss@((a:w):ss)
| null [c | c:_ <- ss, a /= c] = (cpl + 1, rss)
| otherwise = (0, awss)
where (cpl, rss) = cst (w:[u | _:u <- ss])
suffixes :: [a] -> [[a]]
suffixes xs@(_:xs') = xs : suffixes xs'
suffixes _ = []
noAsPattern :: [a] -> [[a]]
noAsPattern (x:xs) = (x:xs) : noAsPattern xs
noAsPattern _ = []
suffixes2 xs = init (tails xs)
compose :: (b -> c) -> (a -> b) -> a -> c
compose f g x = f (g x)
- snippet suffixes3 -
suffixes3 xs = compose init tails xs
- /snippet suffixes3 -
- snippet suffixes4 -
suffixes4 = compose init tails
- snippet suffixes5 -
suffixes5 = init . tails
- /snippet suffixes5 -
|
516178e8021c24de28588c3ba89b1f46c5e737955da1fe13cffff94656bead04 | drfloob/ezic | ezic.erl | -module(ezic).
-include("include/ezic.hrl").
-export([
localtime/1
, utc_to_local/2
, local_to_utc/2
, has_dst_utc/2
, has_dst_local/2
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PUBLIC API
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% returns local time in given timezone
localtime(TzName) ->
utc_to_local(erlang:universaltime(), TzName).
returns time in given timezone for corresponding utc time
utc_to_local(UTCDatetime, TzName) ->
NormalDatetime= ezic_date:normalize(UTCDatetime, u),
utc_to_local_handleFlatzone(UTCDatetime, ezic_db:flatzone(NormalDatetime, TzName)).
%% returns utc time for corresponding time in given timezone utc
local_to_utc(LocalDatetime, TzName) ->
NormalDatetime= ezic_date:normalize(LocalDatetime, w),
local_to_utc_handleFlatzone(LocalDatetime, ezic_db:flatzone(NormalDatetime, TzName)).
has_dst_utc(Datetime, TzName) ->
has_dst(Datetime, TzName, u).
has_dst_local(Datetime, TzName) ->
has_dst(Datetime, TzName, w).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PRIVATE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
utc_to_local_handleFlatzone(_, X={error,_}) ->
X;
utc_to_local_handleFlatzone(UTCDatetime, #flatzone{offset=Offset, dstoffset=DSTOffset}) ->
ezic_date:add_offset(
ezic_date:add_offset(
UTCDatetime
, Offset)
, DSTOffset).
local_to_utc_handleFlatzone(_, X={error, _}) ->
X;
local_to_utc_handleFlatzone(LocalDatetime, #flatzone{offset=Offset, dstoffset=DSTOffset}) ->
ezic_date:add_offset(
ezic_date:add_offset(
LocalDatetime
, Offset, {0,0,0})
, DSTOffset, {0,0,0}).
has_dst(Datetime, TzName, Flag) ->
NormalDatetime = ezic_date:normalize(Datetime, Flag),
case ezic_db:flatzone(NormalDatetime, TzName) of
#flatzone{dstoffset={0,0,0}} ->
false;
#flatzone{dstoffset={_,_,_}} ->
true
end.
| null | https://raw.githubusercontent.com/drfloob/ezic/d95e92d1dc5ac763558da52c271b8a1b76f48122/src/ezic.erl | erlang |
PUBLIC API
returns local time in given timezone
returns utc time for corresponding time in given timezone utc
PRIVATE
| -module(ezic).
-include("include/ezic.hrl").
-export([
localtime/1
, utc_to_local/2
, local_to_utc/2
, has_dst_utc/2
, has_dst_local/2
]).
localtime(TzName) ->
utc_to_local(erlang:universaltime(), TzName).
returns time in given timezone for corresponding utc time
utc_to_local(UTCDatetime, TzName) ->
NormalDatetime= ezic_date:normalize(UTCDatetime, u),
utc_to_local_handleFlatzone(UTCDatetime, ezic_db:flatzone(NormalDatetime, TzName)).
local_to_utc(LocalDatetime, TzName) ->
NormalDatetime= ezic_date:normalize(LocalDatetime, w),
local_to_utc_handleFlatzone(LocalDatetime, ezic_db:flatzone(NormalDatetime, TzName)).
has_dst_utc(Datetime, TzName) ->
has_dst(Datetime, TzName, u).
has_dst_local(Datetime, TzName) ->
has_dst(Datetime, TzName, w).
utc_to_local_handleFlatzone(_, X={error,_}) ->
X;
utc_to_local_handleFlatzone(UTCDatetime, #flatzone{offset=Offset, dstoffset=DSTOffset}) ->
ezic_date:add_offset(
ezic_date:add_offset(
UTCDatetime
, Offset)
, DSTOffset).
local_to_utc_handleFlatzone(_, X={error, _}) ->
X;
local_to_utc_handleFlatzone(LocalDatetime, #flatzone{offset=Offset, dstoffset=DSTOffset}) ->
ezic_date:add_offset(
ezic_date:add_offset(
LocalDatetime
, Offset, {0,0,0})
, DSTOffset, {0,0,0}).
has_dst(Datetime, TzName, Flag) ->
NormalDatetime = ezic_date:normalize(Datetime, Flag),
case ezic_db:flatzone(NormalDatetime, TzName) of
#flatzone{dstoffset={0,0,0}} ->
false;
#flatzone{dstoffset={_,_,_}} ->
true
end.
|
97226131be03d4c7d131fe7dc3133aac21ac9c0d6e2674799bf128edcfa1ceec | nyu-acsys/drift | a-mapi.ml |
let rec mapi_helper (hf: int -> int -> int) hi hn (ha: int array) (hb: int array) =
if (hi < hn) then
let _ = Array.set hb hi (hf hi (Array.get ha hi)) in
mapi_helper hf (hi + 1) hn ha hb
else hb
let rec mapi (mf: int -> int -> int) (ma: int array) =
let mn = Array.length ma in
let mb = Array.make mn 0 in
mapi_helper mf 0 mn ma mb
let add_idx sidx si = sidx + si
let main_p (n:int) =
if n > 0 then
let a = Array.make n 0 in
assert(Array.length (mapi add_idx a) = Array.length a)
else ()
let main (w:unit) =
let _ = main_p 5 in
let _ = main_p 19 in
()
let _ = main () | null | https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/DRIFT/array/a-mapi.ml | ocaml |
let rec mapi_helper (hf: int -> int -> int) hi hn (ha: int array) (hb: int array) =
if (hi < hn) then
let _ = Array.set hb hi (hf hi (Array.get ha hi)) in
mapi_helper hf (hi + 1) hn ha hb
else hb
let rec mapi (mf: int -> int -> int) (ma: int array) =
let mn = Array.length ma in
let mb = Array.make mn 0 in
mapi_helper mf 0 mn ma mb
let add_idx sidx si = sidx + si
let main_p (n:int) =
if n > 0 then
let a = Array.make n 0 in
assert(Array.length (mapi add_idx a) = Array.length a)
else ()
let main (w:unit) =
let _ = main_p 5 in
let _ = main_p 19 in
()
let _ = main () |
|
886db8635b5a6ed39cf577512a15931a26fdca974e4cea87048e6134ec422d27 | 2600hz/community-scripts | wh_binary.erl | %%%-------------------------------------------------------------------
( C ) 2010 - 2012 , VoIP INC
%%% @doc
%%% Various utilities - a veritable cornicopia
%%% @end
%%% @contributors
%%%-------------------------------------------------------------------
-module(wh_binary).
-export([to_lower/1]).
-export([to_upper/1]).
-export([ucfirst/1]).
-export([lcfirst/1]).
-export([strip/1
,strip/2
]).
-export([strip_left/2]).
-export([strip_right/2]).
-export([md5/1]).
-export([pad/3]).
-export([join/1
,join/2
]).
-export([hex/1]).
-export([rand_hex/1]).
-include_lib("kernel/include/inet.hrl").
-ifdef(TEST).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("wh_types.hrl").
-spec pad(binary(), non_neg_integer(), binary()) -> binary().
pad(Bin, Size, Value) when size(Bin) < Size ->
pad(<<Bin/binary, Value/binary>>, Size, Value);
pad(Bin, _, _) -> Bin.
-spec join([text() | atom(),...]) -> binary().
join(Bins) -> join(Bins, <<", ">>, []).
join(Bins, Sep) -> join(Bins, Sep, []).
-spec join([text() | atom(),...], binary()) -> binary().
join([], _, Acc) -> iolist_wh_types:to_binary(lists:reverse(Acc));
join([Bin], _, Acc) ->
iolist_to_binary(lists:reverse([wh_types:to_binary(Bin) | Acc]));
join([Bin|Bins], Sep, Acc) ->
join(Bins, Sep, [Sep, wh_types:to_binary(Bin) |Acc]).
-spec to_lower(term()) -> api_binary().
to_lower('undefined') -> 'undefined';
to_lower(Bin) when is_binary(Bin) -> << <<(wh_util:to_lower_char(B))>> || <<B>> <= Bin>>;
to_lower(Else) -> to_lower(wh_types:to_binary(Else)).
-spec ucfirst(ne_binary()) -> ne_binary().
ucfirst(<<F:8, Bin/binary>>) -> <<(wh_util:to_upper_char(F)):8, Bin/binary>>.
-spec lcfirst(ne_binary()) -> ne_binary().
lcfirst(<<F:8, Bin/binary>>) -> <<(wh_util:to_lower_char(F)):8, Bin/binary>>.
-spec to_upper(term()) -> api_binary().
to_upper('undefined') -> 'undefined';
to_upper(Bin) when is_binary(Bin) -> << <<(wh_util:to_upper_char(B))>> || <<B>> <= Bin>>;
to_upper(Else) -> to_upper(wh_types:to_binary(Else)).
-spec strip(binary()) -> binary().
-spec strip(binary(), 'both' | 'left' | 'right') -> binary().
-spec strip_left(binary(), char()) -> binary().
-spec strip_right(binary(), char()) -> binary().
strip(B) -> strip(B, 'both').
strip(B, 'left') -> strip_left(B, $\s);
strip(B, 'right') -> strip_right(B, $\s);
strip(B, 'both') -> strip_right(strip_left(B, $\s), $\s);
strip(B, C) when is_integer(C) -> strip_right(strip_left(B, C), C).
strip_left(<<C, B/binary>>, C) -> strip_left(B, C);
strip_left(B, _) -> B.
strip_right(C, C) -> <<>>;
strip_right(<<C, B/binary>>, C) ->
case strip_right(B, C) of
<<>> -> <<>>;
T -> <<C, T/binary>>
end;
strip_right(<<A, B/binary>>, C) -> <<A, (strip_right(B, C))/binary>>;
strip_right(<<>>, _) -> <<>>.
-spec md5(text()) -> ne_binary().
md5(Text) -> hex(erlang:md5(wh_types:to_binary(Text))).
-spec hex(binary() | string()) -> binary().
hex(S) ->
Bin = wh_types:to_binary(S),
<< <<(binary_to_hex_char(B div 16)), (binary_to_hex_char(B rem 16))>> || <<B>> <= Bin>>.
-spec rand_hex(pos_integer()) -> ne_binary().
rand_hex(Size) when is_integer(Size) andalso Size > 0 ->
hex(crypto:rand_bytes(Size)).
binary_to_hex_char(N) when N < 10 -> $0 + N;
binary_to_hex_char(N) when N < 16 -> $a - 10 + N.
-ifdef(TEST).
%% PROPER TESTING
proper_test_() ->
{"Runs the module's PropEr tests during eunit testing",
{timeout, 15000,
[
?_assertEqual([], proper:module(?MODULE, [{max_shrinks, 0}]))
]}}.
pad_binary_test() ->
?assertEqual(<<"1234500000">>, pad(<<"12345">>, 10, <<"0">>)).
join_binary_test() ->
?assertEqual(<<"foo">>, join([<<"foo">>], <<", ">>)),
?assertEqual(<<"foo, bar">>, join([<<"foo">>, <<"bar">>], <<", ">>)),
?assertEqual(<<"foo, bar, baz">>, join([<<"foo">>, <<"bar">>, <<"baz">>], <<", ">>)).
ucfirst_binary_test() ->
?assertEqual(<<"Foo">>, ucfirst(<<"foo">>)),
?assertEqual(<<"Foo">>, ucfirst(<<"Foo">>)),
?assertEqual(<<"FOO">>, ucfirst(<<"FOO">>)),
?assertEqual(<<"1oo">>, ucfirst(<<"1oo">>)),
?assertEqual(<<"100">>, ucfirst(<<"100">>)),
?assertEqual(<<"1FF">>, ucfirst(<<"1FF">>)).
lcfirst_binary_test() ->
?assertEqual(<<"foo">>, lcfirst(<<"foo">>)),
?assertEqual(<<"foo">>, lcfirst(<<"Foo">>)),
?assertEqual(<<"fOO">>, lcfirst(<<"FOO">>)),
?assertEqual(<<"1oo">>, lcfirst(<<"1oo">>)),
?assertEqual(<<"100">>, lcfirst(<<"100">>)),
?assertEqual(<<"1FF">>, lcfirst(<<"1FF">>)).
to_lower_binary_test() ->
?assertEqual(<<"foo">>, to_lower(<<"foo">>)),
?assertEqual(<<"foo">>, to_lower(<<"Foo">>)),
?assertEqual(<<"foo">>, to_lower(<<"FoO">>)),
?assertEqual(<<"f00">>, to_lower(<<"f00">>)),
?assertEqual(<<"f00">>, to_lower(<<"F00">>)).
to_upper_binary_test() ->
?assertEqual(<<"FOO">>, to_upper(<<"foo">>)),
?assertEqual(<<"FOO">>, to_upper(<<"Foo">>)),
?assertEqual(<<"FOO">>, to_upper(<<"FoO">>)),
?assertEqual(<<"F00">>, to_upper(<<"f00">>)),
?assertEqual(<<"F00">>, to_upper(<<"F00">>)).
strip_binary_test() ->
?assertEqual(<<"foo">>, strip(<<"foo">>)),
?assertEqual(<<"foo">>, strip(<<"foo ">>)),
?assertEqual(<<"foo">>, strip(<<" foo ">>)),
?assertEqual(<<"foo">>, strip(<<" foo ">>)),
?assertEqual(<<"foo">>, strip(<<" foo">>)),
?assertEqual(<<"foo">>, strip_left(<<"foo">>, $\s)),
?assertEqual(<<"foo">>, strip_left(<<" foo">>, $\s)),
?assertEqual(<<"foo ">>, strip_left(<<" foo ">>, $\s)),
?assertEqual(<<"foo ">>, strip_left(<<"foo ">>, $\s)),
?assertEqual(<<"foo">>, strip_right(<<"foo">>, $\s)),
?assertEqual(<<" foo">>, strip_right(<<" foo">>, $\s)),
?assertEqual(<<" foo">>, strip_right(<<" foo ">>, $\s)),
?assertEqual(<<"foo">>, strip_right(<<"foo ">>, $\s)).
strip_test() ->
?assertEqual(strip(<<"...Hello.....">>, $.), <<"Hello">>).
-endif.
| null | https://raw.githubusercontent.com/2600hz/community-scripts/b0b81342bf02300fcdbda99e4cecc1ee93823c70/CloneTools/src/wh_binary.erl | erlang | -------------------------------------------------------------------
@doc
Various utilities - a veritable cornicopia
@end
@contributors
-------------------------------------------------------------------
PROPER TESTING | ( C ) 2010 - 2012 , VoIP INC
-module(wh_binary).
-export([to_lower/1]).
-export([to_upper/1]).
-export([ucfirst/1]).
-export([lcfirst/1]).
-export([strip/1
,strip/2
]).
-export([strip_left/2]).
-export([strip_right/2]).
-export([md5/1]).
-export([pad/3]).
-export([join/1
,join/2
]).
-export([hex/1]).
-export([rand_hex/1]).
-include_lib("kernel/include/inet.hrl").
-ifdef(TEST).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("wh_types.hrl").
-spec pad(binary(), non_neg_integer(), binary()) -> binary().
pad(Bin, Size, Value) when size(Bin) < Size ->
pad(<<Bin/binary, Value/binary>>, Size, Value);
pad(Bin, _, _) -> Bin.
-spec join([text() | atom(),...]) -> binary().
join(Bins) -> join(Bins, <<", ">>, []).
join(Bins, Sep) -> join(Bins, Sep, []).
-spec join([text() | atom(),...], binary()) -> binary().
join([], _, Acc) -> iolist_wh_types:to_binary(lists:reverse(Acc));
join([Bin], _, Acc) ->
iolist_to_binary(lists:reverse([wh_types:to_binary(Bin) | Acc]));
join([Bin|Bins], Sep, Acc) ->
join(Bins, Sep, [Sep, wh_types:to_binary(Bin) |Acc]).
-spec to_lower(term()) -> api_binary().
to_lower('undefined') -> 'undefined';
to_lower(Bin) when is_binary(Bin) -> << <<(wh_util:to_lower_char(B))>> || <<B>> <= Bin>>;
to_lower(Else) -> to_lower(wh_types:to_binary(Else)).
-spec ucfirst(ne_binary()) -> ne_binary().
ucfirst(<<F:8, Bin/binary>>) -> <<(wh_util:to_upper_char(F)):8, Bin/binary>>.
-spec lcfirst(ne_binary()) -> ne_binary().
lcfirst(<<F:8, Bin/binary>>) -> <<(wh_util:to_lower_char(F)):8, Bin/binary>>.
-spec to_upper(term()) -> api_binary().
to_upper('undefined') -> 'undefined';
to_upper(Bin) when is_binary(Bin) -> << <<(wh_util:to_upper_char(B))>> || <<B>> <= Bin>>;
to_upper(Else) -> to_upper(wh_types:to_binary(Else)).
-spec strip(binary()) -> binary().
-spec strip(binary(), 'both' | 'left' | 'right') -> binary().
-spec strip_left(binary(), char()) -> binary().
-spec strip_right(binary(), char()) -> binary().
strip(B) -> strip(B, 'both').
strip(B, 'left') -> strip_left(B, $\s);
strip(B, 'right') -> strip_right(B, $\s);
strip(B, 'both') -> strip_right(strip_left(B, $\s), $\s);
strip(B, C) when is_integer(C) -> strip_right(strip_left(B, C), C).
strip_left(<<C, B/binary>>, C) -> strip_left(B, C);
strip_left(B, _) -> B.
strip_right(C, C) -> <<>>;
strip_right(<<C, B/binary>>, C) ->
case strip_right(B, C) of
<<>> -> <<>>;
T -> <<C, T/binary>>
end;
strip_right(<<A, B/binary>>, C) -> <<A, (strip_right(B, C))/binary>>;
strip_right(<<>>, _) -> <<>>.
-spec md5(text()) -> ne_binary().
md5(Text) -> hex(erlang:md5(wh_types:to_binary(Text))).
-spec hex(binary() | string()) -> binary().
hex(S) ->
Bin = wh_types:to_binary(S),
<< <<(binary_to_hex_char(B div 16)), (binary_to_hex_char(B rem 16))>> || <<B>> <= Bin>>.
-spec rand_hex(pos_integer()) -> ne_binary().
rand_hex(Size) when is_integer(Size) andalso Size > 0 ->
hex(crypto:rand_bytes(Size)).
binary_to_hex_char(N) when N < 10 -> $0 + N;
binary_to_hex_char(N) when N < 16 -> $a - 10 + N.
-ifdef(TEST).
proper_test_() ->
{"Runs the module's PropEr tests during eunit testing",
{timeout, 15000,
[
?_assertEqual([], proper:module(?MODULE, [{max_shrinks, 0}]))
]}}.
pad_binary_test() ->
?assertEqual(<<"1234500000">>, pad(<<"12345">>, 10, <<"0">>)).
join_binary_test() ->
?assertEqual(<<"foo">>, join([<<"foo">>], <<", ">>)),
?assertEqual(<<"foo, bar">>, join([<<"foo">>, <<"bar">>], <<", ">>)),
?assertEqual(<<"foo, bar, baz">>, join([<<"foo">>, <<"bar">>, <<"baz">>], <<", ">>)).
ucfirst_binary_test() ->
?assertEqual(<<"Foo">>, ucfirst(<<"foo">>)),
?assertEqual(<<"Foo">>, ucfirst(<<"Foo">>)),
?assertEqual(<<"FOO">>, ucfirst(<<"FOO">>)),
?assertEqual(<<"1oo">>, ucfirst(<<"1oo">>)),
?assertEqual(<<"100">>, ucfirst(<<"100">>)),
?assertEqual(<<"1FF">>, ucfirst(<<"1FF">>)).
lcfirst_binary_test() ->
?assertEqual(<<"foo">>, lcfirst(<<"foo">>)),
?assertEqual(<<"foo">>, lcfirst(<<"Foo">>)),
?assertEqual(<<"fOO">>, lcfirst(<<"FOO">>)),
?assertEqual(<<"1oo">>, lcfirst(<<"1oo">>)),
?assertEqual(<<"100">>, lcfirst(<<"100">>)),
?assertEqual(<<"1FF">>, lcfirst(<<"1FF">>)).
to_lower_binary_test() ->
?assertEqual(<<"foo">>, to_lower(<<"foo">>)),
?assertEqual(<<"foo">>, to_lower(<<"Foo">>)),
?assertEqual(<<"foo">>, to_lower(<<"FoO">>)),
?assertEqual(<<"f00">>, to_lower(<<"f00">>)),
?assertEqual(<<"f00">>, to_lower(<<"F00">>)).
to_upper_binary_test() ->
?assertEqual(<<"FOO">>, to_upper(<<"foo">>)),
?assertEqual(<<"FOO">>, to_upper(<<"Foo">>)),
?assertEqual(<<"FOO">>, to_upper(<<"FoO">>)),
?assertEqual(<<"F00">>, to_upper(<<"f00">>)),
?assertEqual(<<"F00">>, to_upper(<<"F00">>)).
strip_binary_test() ->
?assertEqual(<<"foo">>, strip(<<"foo">>)),
?assertEqual(<<"foo">>, strip(<<"foo ">>)),
?assertEqual(<<"foo">>, strip(<<" foo ">>)),
?assertEqual(<<"foo">>, strip(<<" foo ">>)),
?assertEqual(<<"foo">>, strip(<<" foo">>)),
?assertEqual(<<"foo">>, strip_left(<<"foo">>, $\s)),
?assertEqual(<<"foo">>, strip_left(<<" foo">>, $\s)),
?assertEqual(<<"foo ">>, strip_left(<<" foo ">>, $\s)),
?assertEqual(<<"foo ">>, strip_left(<<"foo ">>, $\s)),
?assertEqual(<<"foo">>, strip_right(<<"foo">>, $\s)),
?assertEqual(<<" foo">>, strip_right(<<" foo">>, $\s)),
?assertEqual(<<" foo">>, strip_right(<<" foo ">>, $\s)),
?assertEqual(<<"foo">>, strip_right(<<"foo ">>, $\s)).
strip_test() ->
?assertEqual(strip(<<"...Hello.....">>, $.), <<"Hello">>).
-endif.
|
cf32ceeda400a766a6ffa7aab9a822d33bd2eb8cf32021ddb6495279a8c1b2f1 | sgbj/MaximaSharp | dlasd1.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
;;; Using Lisp CMU Common Lisp 20d (20D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :lapack)
(let* ((one 1.0) (zero 0.0))
(declare (type (double-float 1.0 1.0) one)
(type (double-float 0.0 0.0) zero)
(ignorable one zero))
(defun dlasd1 (nl nr sqre d alpha beta u ldu vt ldvt idxq iwork work info)
(declare (type (array f2cl-lib:integer4 (*)) iwork idxq)
(type (double-float) beta alpha)
(type (array double-float (*)) work vt u d)
(type (f2cl-lib:integer4) info ldvt ldu sqre nr nl))
(f2cl-lib:with-multi-array-data
((d double-float d-%data% d-%offset%)
(u double-float u-%data% u-%offset%)
(vt double-float vt-%data% vt-%offset%)
(work double-float work-%data% work-%offset%)
(idxq f2cl-lib:integer4 idxq-%data% idxq-%offset%)
(iwork f2cl-lib:integer4 iwork-%data% iwork-%offset%))
(prog ((orgnrm 0.0) (coltyp 0) (i 0) (idx 0) (idxc 0) (idxp 0) (iq 0)
(isigma 0) (iu2 0) (ivt2 0) (iz 0) (k 0) (ldq 0) (ldu2 0)
(ldvt2 0) (m 0) (n 0) (n1 0) (n2 0))
(declare (type (double-float) orgnrm)
(type (f2cl-lib:integer4) coltyp i idx idxc idxp iq isigma iu2
ivt2 iz k ldq ldu2 ldvt2 m n n1 n2))
(setf info 0)
(cond
((< nl 1)
(setf info -1))
((< nr 1)
(setf info -2))
((or (< sqre 0) (> sqre 1))
(setf info -3)))
(cond
((/= info 0)
(xerbla "DLASD1" (f2cl-lib:int-sub info))
(go end_label)))
(setf n (f2cl-lib:int-add nl nr 1))
(setf m (f2cl-lib:int-add n sqre))
(setf ldu2 n)
(setf ldvt2 m)
(setf iz 1)
(setf isigma (f2cl-lib:int-add iz m))
(setf iu2 (f2cl-lib:int-add isigma n))
(setf ivt2 (f2cl-lib:int-add iu2 (f2cl-lib:int-mul ldu2 n)))
(setf iq (f2cl-lib:int-add ivt2 (f2cl-lib:int-mul ldvt2 m)))
(setf idx 1)
(setf idxc (f2cl-lib:int-add idx n))
(setf coltyp (f2cl-lib:int-add idxc n))
(setf idxp (f2cl-lib:int-add coltyp n))
(setf orgnrm (max (abs alpha) (abs beta)))
(setf (f2cl-lib:fref d-%data%
((f2cl-lib:int-add nl 1))
((1 *))
d-%offset%)
zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(cond
((> (abs (f2cl-lib:fref d (i) ((1 *)))) orgnrm)
(setf orgnrm
(abs (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%)))))
label10))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9)
(dlascl "G" 0 0 orgnrm one n 1 d n info)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7
var-8))
(setf info var-9))
(setf alpha (/ alpha orgnrm))
(setf beta (/ beta orgnrm))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9
var-10 var-11 var-12 var-13 var-14 var-15 var-16 var-17 var-18
var-19 var-20 var-21 var-22)
(dlasd2 nl nr sqre k d
(f2cl-lib:array-slice work-%data%
double-float
(iz)
((1 *))
work-%offset%)
alpha beta u ldu vt ldvt
(f2cl-lib:array-slice work-%data%
double-float
(isigma)
((1 *))
work-%offset%)
(f2cl-lib:array-slice work-%data%
double-float
(iu2)
((1 *))
work-%offset%)
ldu2
(f2cl-lib:array-slice work-%data%
double-float
(ivt2)
((1 *))
work-%offset%)
ldvt2
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(idxp)
((1 *))
iwork-%offset%)
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(idx)
((1 *))
iwork-%offset%)
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(idxc)
((1 *))
iwork-%offset%)
idxq
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(coltyp)
((1 *))
iwork-%offset%)
info)
(declare (ignore var-0 var-1 var-2 var-4 var-5 var-6 var-7 var-8
var-9 var-10 var-11 var-12 var-13 var-14 var-15
var-16 var-17 var-18 var-19 var-20 var-21))
(setf k var-3)
(setf info var-22))
(setf ldq k)
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9
var-10 var-11 var-12 var-13 var-14 var-15 var-16 var-17 var-18
var-19)
(dlasd3 nl nr sqre k d
(f2cl-lib:array-slice work-%data%
double-float
(iq)
((1 *))
work-%offset%)
ldq
(f2cl-lib:array-slice work-%data%
double-float
(isigma)
((1 *))
work-%offset%)
u ldu
(f2cl-lib:array-slice work-%data%
double-float
(iu2)
((1 *))
work-%offset%)
ldu2 vt ldvt
(f2cl-lib:array-slice work-%data%
double-float
(ivt2)
((1 *))
work-%offset%)
ldvt2
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(idxc)
((1 *))
iwork-%offset%)
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(coltyp)
((1 *))
iwork-%offset%)
(f2cl-lib:array-slice work-%data%
double-float
(iz)
((1 *))
work-%offset%)
info)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7
var-8 var-9 var-10 var-11 var-12 var-13 var-14
var-15 var-16 var-17 var-18))
(setf info var-19))
(cond
((/= info 0)
(go end_label)))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9)
(dlascl "G" 0 0 one orgnrm n 1 d n info)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7
var-8))
(setf info var-9))
(setf n1 k)
(setf n2 (f2cl-lib:int-sub n k))
(dlamrg n1 n2 d 1 -1 idxq)
(go end_label)
end_label
(return
(values nil
nil
nil
nil
alpha
beta
nil
nil
nil
nil
nil
nil
nil
info))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dlasd1
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (array double-float (*))
(double-float) (double-float) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::integer4 (*))
(array fortran-to-lisp::integer4 (*))
(array double-float (*)) (fortran-to-lisp::integer4))
:return-values '(nil nil nil nil fortran-to-lisp::alpha
fortran-to-lisp::beta nil nil nil nil nil nil nil
fortran-to-lisp::info)
:calls '(fortran-to-lisp::dlamrg fortran-to-lisp::dlasd3
fortran-to-lisp::dlasd2 fortran-to-lisp::dlascl
fortran-to-lisp::xerbla))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/lapack/dlasd1.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp 20d (20D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
(in-package :lapack)
(let* ((one 1.0) (zero 0.0))
(declare (type (double-float 1.0 1.0) one)
(type (double-float 0.0 0.0) zero)
(ignorable one zero))
(defun dlasd1 (nl nr sqre d alpha beta u ldu vt ldvt idxq iwork work info)
(declare (type (array f2cl-lib:integer4 (*)) iwork idxq)
(type (double-float) beta alpha)
(type (array double-float (*)) work vt u d)
(type (f2cl-lib:integer4) info ldvt ldu sqre nr nl))
(f2cl-lib:with-multi-array-data
((d double-float d-%data% d-%offset%)
(u double-float u-%data% u-%offset%)
(vt double-float vt-%data% vt-%offset%)
(work double-float work-%data% work-%offset%)
(idxq f2cl-lib:integer4 idxq-%data% idxq-%offset%)
(iwork f2cl-lib:integer4 iwork-%data% iwork-%offset%))
(prog ((orgnrm 0.0) (coltyp 0) (i 0) (idx 0) (idxc 0) (idxp 0) (iq 0)
(isigma 0) (iu2 0) (ivt2 0) (iz 0) (k 0) (ldq 0) (ldu2 0)
(ldvt2 0) (m 0) (n 0) (n1 0) (n2 0))
(declare (type (double-float) orgnrm)
(type (f2cl-lib:integer4) coltyp i idx idxc idxp iq isigma iu2
ivt2 iz k ldq ldu2 ldvt2 m n n1 n2))
(setf info 0)
(cond
((< nl 1)
(setf info -1))
((< nr 1)
(setf info -2))
((or (< sqre 0) (> sqre 1))
(setf info -3)))
(cond
((/= info 0)
(xerbla "DLASD1" (f2cl-lib:int-sub info))
(go end_label)))
(setf n (f2cl-lib:int-add nl nr 1))
(setf m (f2cl-lib:int-add n sqre))
(setf ldu2 n)
(setf ldvt2 m)
(setf iz 1)
(setf isigma (f2cl-lib:int-add iz m))
(setf iu2 (f2cl-lib:int-add isigma n))
(setf ivt2 (f2cl-lib:int-add iu2 (f2cl-lib:int-mul ldu2 n)))
(setf iq (f2cl-lib:int-add ivt2 (f2cl-lib:int-mul ldvt2 m)))
(setf idx 1)
(setf idxc (f2cl-lib:int-add idx n))
(setf coltyp (f2cl-lib:int-add idxc n))
(setf idxp (f2cl-lib:int-add coltyp n))
(setf orgnrm (max (abs alpha) (abs beta)))
(setf (f2cl-lib:fref d-%data%
((f2cl-lib:int-add nl 1))
((1 *))
d-%offset%)
zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(cond
((> (abs (f2cl-lib:fref d (i) ((1 *)))) orgnrm)
(setf orgnrm
(abs (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%)))))
label10))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9)
(dlascl "G" 0 0 orgnrm one n 1 d n info)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7
var-8))
(setf info var-9))
(setf alpha (/ alpha orgnrm))
(setf beta (/ beta orgnrm))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9
var-10 var-11 var-12 var-13 var-14 var-15 var-16 var-17 var-18
var-19 var-20 var-21 var-22)
(dlasd2 nl nr sqre k d
(f2cl-lib:array-slice work-%data%
double-float
(iz)
((1 *))
work-%offset%)
alpha beta u ldu vt ldvt
(f2cl-lib:array-slice work-%data%
double-float
(isigma)
((1 *))
work-%offset%)
(f2cl-lib:array-slice work-%data%
double-float
(iu2)
((1 *))
work-%offset%)
ldu2
(f2cl-lib:array-slice work-%data%
double-float
(ivt2)
((1 *))
work-%offset%)
ldvt2
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(idxp)
((1 *))
iwork-%offset%)
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(idx)
((1 *))
iwork-%offset%)
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(idxc)
((1 *))
iwork-%offset%)
idxq
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(coltyp)
((1 *))
iwork-%offset%)
info)
(declare (ignore var-0 var-1 var-2 var-4 var-5 var-6 var-7 var-8
var-9 var-10 var-11 var-12 var-13 var-14 var-15
var-16 var-17 var-18 var-19 var-20 var-21))
(setf k var-3)
(setf info var-22))
(setf ldq k)
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9
var-10 var-11 var-12 var-13 var-14 var-15 var-16 var-17 var-18
var-19)
(dlasd3 nl nr sqre k d
(f2cl-lib:array-slice work-%data%
double-float
(iq)
((1 *))
work-%offset%)
ldq
(f2cl-lib:array-slice work-%data%
double-float
(isigma)
((1 *))
work-%offset%)
u ldu
(f2cl-lib:array-slice work-%data%
double-float
(iu2)
((1 *))
work-%offset%)
ldu2 vt ldvt
(f2cl-lib:array-slice work-%data%
double-float
(ivt2)
((1 *))
work-%offset%)
ldvt2
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(idxc)
((1 *))
iwork-%offset%)
(f2cl-lib:array-slice iwork-%data%
f2cl-lib:integer4
(coltyp)
((1 *))
iwork-%offset%)
(f2cl-lib:array-slice work-%data%
double-float
(iz)
((1 *))
work-%offset%)
info)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7
var-8 var-9 var-10 var-11 var-12 var-13 var-14
var-15 var-16 var-17 var-18))
(setf info var-19))
(cond
((/= info 0)
(go end_label)))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9)
(dlascl "G" 0 0 one orgnrm n 1 d n info)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7
var-8))
(setf info var-9))
(setf n1 k)
(setf n2 (f2cl-lib:int-sub n k))
(dlamrg n1 n2 d 1 -1 idxq)
(go end_label)
end_label
(return
(values nil
nil
nil
nil
alpha
beta
nil
nil
nil
nil
nil
nil
nil
info))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dlasd1
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (array double-float (*))
(double-float) (double-float) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::integer4 (*))
(array fortran-to-lisp::integer4 (*))
(array double-float (*)) (fortran-to-lisp::integer4))
:return-values '(nil nil nil nil fortran-to-lisp::alpha
fortran-to-lisp::beta nil nil nil nil nil nil nil
fortran-to-lisp::info)
:calls '(fortran-to-lisp::dlamrg fortran-to-lisp::dlasd3
fortran-to-lisp::dlasd2 fortran-to-lisp::dlascl
fortran-to-lisp::xerbla))))
|
67d02582ad9e5ba6d68d9ab463b4b938a0ee04f9c1e0e927361bbf0c47250018 | myaosato/clcm | ordered-list.lisp | (defpackage :clcm/nodes/ordered-list
(:use :cl
:clcm/line
:clcm/node
:clcm/nodes/list)
(:import-from :cl-ppcre
:scan-to-strings)
(:export :ordered-list-node
:is-tight
:start
:is-ordered-list-line
:attach-ordered-list!?))
(in-package :clcm/nodes/ordered-list)
(defclass ordered-list-node (list-node)
((start :accessor start :initarg :start)))
;; block quote
(defun is-ordered-list-line (line offset)
(multiple-value-bind (indent content) (get-indented-depth-and-line line offset)
(if (> indent 3) (return-from is-ordered-list-line nil))
(multiple-value-bind (result marker)
(scan-to-strings "^(\\d{1,9}(:?\\.|\\)))(?:\\s|\\t|$)" content :start indent)
(if result
(aref marker 0)))))
(defun attach-ordered-list!? (node line offset)
(let ((marker (is-ordered-list-line line offset)))
(when marker
(let ((child (make-instance 'ordered-list-node
:start (parse-integer (subseq marker 0 (1- (length marker)))))))
(add-child node child)
(add!? child line offset)
child))))
| null | https://raw.githubusercontent.com/myaosato/clcm/fd0390bedf00c5be3f5c2eb8176ff73bede797b0/src/nodes/ordered-list.lisp | lisp | block quote | (defpackage :clcm/nodes/ordered-list
(:use :cl
:clcm/line
:clcm/node
:clcm/nodes/list)
(:import-from :cl-ppcre
:scan-to-strings)
(:export :ordered-list-node
:is-tight
:start
:is-ordered-list-line
:attach-ordered-list!?))
(in-package :clcm/nodes/ordered-list)
(defclass ordered-list-node (list-node)
((start :accessor start :initarg :start)))
(defun is-ordered-list-line (line offset)
(multiple-value-bind (indent content) (get-indented-depth-and-line line offset)
(if (> indent 3) (return-from is-ordered-list-line nil))
(multiple-value-bind (result marker)
(scan-to-strings "^(\\d{1,9}(:?\\.|\\)))(?:\\s|\\t|$)" content :start indent)
(if result
(aref marker 0)))))
(defun attach-ordered-list!? (node line offset)
(let ((marker (is-ordered-list-line line offset)))
(when marker
(let ((child (make-instance 'ordered-list-node
:start (parse-integer (subseq marker 0 (1- (length marker)))))))
(add-child node child)
(add!? child line offset)
child))))
|