_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 |
|---|---|---|---|---|---|---|---|---|
0db2877c6fbdb76125d09244a2a9d56e7bad451cf5998c233df14efab7f592c8 | swarmpit/swarmpit | form.cljs | (ns material.component.form
(:refer-clojure :exclude [comp])
(:require [material.components :as cmp]
[material.icon :as icon]
[sablono.core :refer-macros [html]]
[swarmpit.time :as time]))
(defn item-main
([name value]
(item-main name value true))
([name value separator?]
(cmp/box
{:className "Swarmpit-form-item-wrapper"}
(when separator?
(cmp/divider {}))
(cmp/box
{:className "Swarmpit-form-item"}
(cmp/box
{:className "Swarmpit-form-item-name"}
(cmp/typography {:variant "body2"} name))
(cmp/box
{:className "Swarmpit-form-item-value"}
(cmp/typography {:variant "body2"} value))))))
(defn item-date
[date]
(html
(if (= "0001-01-01T00:00:00Z" date)
"sometime"
[:time {:date-time date
:title (time/simplify date)}
(time/humanize date)])))
(defn item [name value]
(html
[:div {:class "Swarmpit-row-space"
:key (str "sri-" name)}
(cmp/typography {:variant "body2"
:color "textSecondary"} name)
(cmp/typography {:variant "body2"} value)]))
(defn item-info [message]
(cmp/typography {:variant "body2"
:color "textSecondary"} message))
(defn message [comp]
(html
[:span.Swarmpit-message
(icon/info {:style {:marginRight "8px"}})
[:span comp]]))
(defn error-message [text]
(cmp/snackbar-content
{:className "Swarmpit-label-red"
:elevation 0
:message (html [:span.Swarmpit-message
(icon/error {:className "Swarmpit-message-icon"}) text])}))
(defn item-labels [labels]
(html
[:div {:class "Swarmpit-form-card-labels"
:key "item-labels"}
labels]))
(defn section
([name]
(section name nil))
([name button]
(cmp/box
{:class "Swarmpit-form-section"
:id name}
(cmp/typography
{:variant "h6"} name)
button)))
(defn subsection
([name]
(subsection name nil))
([name button]
(cmp/box
{:class "Swarmpit-form-section Swarmpit-form-subsection"
:id name}
(cmp/typography
{:variant "subtitle2"} name)
button)))
(defn open-in-new [text href]
(html
[:a {:href href
:className "Swarmpit-new-tab"
:target "_blank"}
[:div text]
[:div (icon/open-in-new
{:className "Swarmpit-new-tab-ico"})]])) | null | https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/cljs/material/component/form.cljs | clojure | (ns material.component.form
(:refer-clojure :exclude [comp])
(:require [material.components :as cmp]
[material.icon :as icon]
[sablono.core :refer-macros [html]]
[swarmpit.time :as time]))
(defn item-main
([name value]
(item-main name value true))
([name value separator?]
(cmp/box
{:className "Swarmpit-form-item-wrapper"}
(when separator?
(cmp/divider {}))
(cmp/box
{:className "Swarmpit-form-item"}
(cmp/box
{:className "Swarmpit-form-item-name"}
(cmp/typography {:variant "body2"} name))
(cmp/box
{:className "Swarmpit-form-item-value"}
(cmp/typography {:variant "body2"} value))))))
(defn item-date
[date]
(html
(if (= "0001-01-01T00:00:00Z" date)
"sometime"
[:time {:date-time date
:title (time/simplify date)}
(time/humanize date)])))
(defn item [name value]
(html
[:div {:class "Swarmpit-row-space"
:key (str "sri-" name)}
(cmp/typography {:variant "body2"
:color "textSecondary"} name)
(cmp/typography {:variant "body2"} value)]))
(defn item-info [message]
(cmp/typography {:variant "body2"
:color "textSecondary"} message))
(defn message [comp]
(html
[:span.Swarmpit-message
(icon/info {:style {:marginRight "8px"}})
[:span comp]]))
(defn error-message [text]
(cmp/snackbar-content
{:className "Swarmpit-label-red"
:elevation 0
:message (html [:span.Swarmpit-message
(icon/error {:className "Swarmpit-message-icon"}) text])}))
(defn item-labels [labels]
(html
[:div {:class "Swarmpit-form-card-labels"
:key "item-labels"}
labels]))
(defn section
([name]
(section name nil))
([name button]
(cmp/box
{:class "Swarmpit-form-section"
:id name}
(cmp/typography
{:variant "h6"} name)
button)))
(defn subsection
([name]
(subsection name nil))
([name button]
(cmp/box
{:class "Swarmpit-form-section Swarmpit-form-subsection"
:id name}
(cmp/typography
{:variant "subtitle2"} name)
button)))
(defn open-in-new [text href]
(html
[:a {:href href
:className "Swarmpit-new-tab"
:target "_blank"}
[:div text]
[:div (icon/open-in-new
{:className "Swarmpit-new-tab-ico"})]])) | |
d965f93b21c6544b76b81353b2415319783c3a2a9cee2cbef3dd223d3112f9a2 | RedPRL/algaeff | Algaeff.mli | (** Reusable effects-based components. *)
(** {1 Reusable components} *)
module State : module type of State
module Reader : module type of Reader
module Sequencer : module type of Sequencer
module Mutex : module type of Mutex
module UniqueID : module type of UniqueID
module Unmonad : module type of Unmonad
* { 1 Auxiliary tools }
module Fun : module type of Fun
| null | https://raw.githubusercontent.com/RedPRL/algaeff/0a9742860a98d2ad0297ffed4760670baf91d041/src/Algaeff.mli | ocaml | * Reusable effects-based components.
* {1 Reusable components} |
module State : module type of State
module Reader : module type of Reader
module Sequencer : module type of Sequencer
module Mutex : module type of Mutex
module UniqueID : module type of UniqueID
module Unmonad : module type of Unmonad
* { 1 Auxiliary tools }
module Fun : module type of Fun
|
eaf4af69410f4caf0b61ce5bd1da64d5e14cfd5d51c9e5a455861361d0d6abae | owickstrom/komposition | DialogView.hs | # OPTIONS_GHC -fno - warn - orphans #
{-# LANGUAGE OverloadedLabels #-}
# LANGUAGE OverloadedLists #
{-# LANGUAGE OverloadedStrings #-}
module Komposition.UserInterface.GtkInterface.DialogView where
import qualified Data.Vector as Vector
import Komposition.Prelude hiding
(on)
import GI.Gtk (Align (..),
Box (..),
Button (..),
Dialog (..),
Dialog (..),
Label (..),
Orientation (..))
import GI.Gtk.Declarative
import Komposition.UserInterface.Dialog
import Komposition.UserInterface.GtkInterface.GtkWindowMarkup
instance DialogView GtkWindowMarkup where
dialogView props =
GtkModalMarkup $
bin Dialog [ #title := dialogTitle props
, on #deleteEvent (const (True, DialogClosed))
] $
container Box [ #orientation := OrientationVertical, classes ["dialog"] ]
[
BoxChild defaultBoxChildProperties { expand = False, fill = False, padding = 0 } $
widget Label [#label := dialogMessage props]
, BoxChild defaultBoxChildProperties { expand = False, fill = False, padding = 0 } $
container Box [classes ["choices"], #halign := AlignEnd] $
Vector.fromList (dialogChoices props) <&> \c ->
BoxChild defaultBoxChildProperties { expand = False, fill = False, padding = 0 } $
widget Button [ #label := toButtonLabel c
, classes ["choice"]
, on #clicked (DialogChoiceSelected c)
]
]
| null | https://raw.githubusercontent.com/owickstrom/komposition/64893d50941b90f44d77fea0dc6d30c061464cf3/src/Komposition/UserInterface/GtkInterface/DialogView.hs | haskell | # LANGUAGE OverloadedLabels #
# LANGUAGE OverloadedStrings # | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE OverloadedLists #
module Komposition.UserInterface.GtkInterface.DialogView where
import qualified Data.Vector as Vector
import Komposition.Prelude hiding
(on)
import GI.Gtk (Align (..),
Box (..),
Button (..),
Dialog (..),
Dialog (..),
Label (..),
Orientation (..))
import GI.Gtk.Declarative
import Komposition.UserInterface.Dialog
import Komposition.UserInterface.GtkInterface.GtkWindowMarkup
instance DialogView GtkWindowMarkup where
dialogView props =
GtkModalMarkup $
bin Dialog [ #title := dialogTitle props
, on #deleteEvent (const (True, DialogClosed))
] $
container Box [ #orientation := OrientationVertical, classes ["dialog"] ]
[
BoxChild defaultBoxChildProperties { expand = False, fill = False, padding = 0 } $
widget Label [#label := dialogMessage props]
, BoxChild defaultBoxChildProperties { expand = False, fill = False, padding = 0 } $
container Box [classes ["choices"], #halign := AlignEnd] $
Vector.fromList (dialogChoices props) <&> \c ->
BoxChild defaultBoxChildProperties { expand = False, fill = False, padding = 0 } $
widget Button [ #label := toButtonLabel c
, classes ["choice"]
, on #clicked (DialogChoiceSelected c)
]
]
|
aa2db843506d2a3993f999bbca0bfb054a226a4692f98510e7bb528a5494eb7a | mirage/capnp-rpc | main.ml | open Lwt.Infix
open Capnp_rpc_lwt
let () =
Logs.set_level (Some Logs.Warning);
Logs.set_reporter (Logs_fmt.reporter ())
let callback_fn msg =
Fmt.pr "Callback got %S@." msg
let run_client service =
Capability.with_ref (Echo.Callback.local callback_fn) @@ fun callback ->
Echo.heartbeat service "foo" callback
let secret_key = `Ephemeral
let listen_address = `TCP ("127.0.0.1", 7000)
let start_server () =
let config = Capnp_rpc_unix.Vat_config.create ~secret_key listen_address in
let service_id = Capnp_rpc_unix.Vat_config.derived_id config "main" in
let restore = Capnp_rpc_net.Restorer.single service_id Echo.local in
Capnp_rpc_unix.serve config ~restore >|= fun vat ->
Capnp_rpc_unix.Vat.sturdy_uri vat service_id
let () =
Lwt_main.run begin
start_server () >>= fun uri ->
Fmt.pr "Connecting to echo service at: %a@." Uri.pp_hum uri;
let client_vat = Capnp_rpc_unix.client_only_vat () in
let sr = Capnp_rpc_unix.Vat.import_exn client_vat uri in
Sturdy_ref.with_cap_exn sr run_client
end
| null | https://raw.githubusercontent.com/mirage/capnp-rpc/8a0b6dce373dc2e2d547d85e542962862773f74b/examples/v3/main.ml | ocaml | open Lwt.Infix
open Capnp_rpc_lwt
let () =
Logs.set_level (Some Logs.Warning);
Logs.set_reporter (Logs_fmt.reporter ())
let callback_fn msg =
Fmt.pr "Callback got %S@." msg
let run_client service =
Capability.with_ref (Echo.Callback.local callback_fn) @@ fun callback ->
Echo.heartbeat service "foo" callback
let secret_key = `Ephemeral
let listen_address = `TCP ("127.0.0.1", 7000)
let start_server () =
let config = Capnp_rpc_unix.Vat_config.create ~secret_key listen_address in
let service_id = Capnp_rpc_unix.Vat_config.derived_id config "main" in
let restore = Capnp_rpc_net.Restorer.single service_id Echo.local in
Capnp_rpc_unix.serve config ~restore >|= fun vat ->
Capnp_rpc_unix.Vat.sturdy_uri vat service_id
let () =
Lwt_main.run begin
start_server () >>= fun uri ->
Fmt.pr "Connecting to echo service at: %a@." Uri.pp_hum uri;
let client_vat = Capnp_rpc_unix.client_only_vat () in
let sr = Capnp_rpc_unix.Vat.import_exn client_vat uri in
Sturdy_ref.with_cap_exn sr run_client
end
| |
48412da8a334c9d1af31f827b94fd66d6b30e8427d8cf78672398125ed6334c7 | sentenai/reinforce | QTable.hs | module Main where
import Prelude
import Reinforce.Agents
import Reinforce.Agents.QTable
import Reinforce.Algorithms.QLearning
import Environments.Gym.ClassicControl.CartPoleV0
main :: IO ()
main = do
x <- runDefaultEnvironment False $
runQTable defaultConfigs (Left 0.85) $
runLearner (Just 10) (Just 10)
rolloutQLearning
print x
| null | https://raw.githubusercontent.com/sentenai/reinforce/03fdeea14c606f4fe2390863778c99ebe1f0a7ee/reinforce-zoo/examples/cartpole/QTable.hs | haskell | module Main where
import Prelude
import Reinforce.Agents
import Reinforce.Agents.QTable
import Reinforce.Algorithms.QLearning
import Environments.Gym.ClassicControl.CartPoleV0
main :: IO ()
main = do
x <- runDefaultEnvironment False $
runQTable defaultConfigs (Left 0.85) $
runLearner (Just 10) (Just 10)
rolloutQLearning
print x
| |
72ee25f0afa345220093e9d44794b3dad05f263d7ebe70ba84fb42c9f5009c5b | travis/lein-deb | core.clj | (ns deb_test.core)
| null | https://raw.githubusercontent.com/travis/lein-deb/8510d7d3103d50619d3ffd6220a7d4d46758a172/test_projects/sample/src/deb_test/core.clj | clojure | (ns deb_test.core)
| |
d4f980b6ccc9e363b32818cba12bbb9a840925c27c33cd656eff83489955c34e | Kong/HARchiver | regex.ml | open Core.Std
open Re_pcre
let create str = regexp str
let matches rex str =
let thunk = fun () -> exec ~rex ~pos:0 str |> fun x -> get_substring x 0 in
Result.try_with thunk |> Result.is_ok
| null | https://raw.githubusercontent.com/Kong/HARchiver/eb0aca5c15d536ab2d7fba9d00ed1928466e1a54/src/regex.ml | ocaml | open Core.Std
open Re_pcre
let create str = regexp str
let matches rex str =
let thunk = fun () -> exec ~rex ~pos:0 str |> fun x -> get_substring x 0 in
Result.try_with thunk |> Result.is_ok
| |
72a9c0f4feb08fa86391a33b16dde6257385995519c9db5314abe8563e59c952 | rixed/ramen | RamenTimeseries.ml | (* This program builds time series for the requested time range out of any
* operation field.
*
* The operation event-time has to be known, though.
*)
open Batteries
open RamenLog
open RamenHelpersNoLog
module C = RamenConf
module VSI = RamenSync.Value.SourceInfo
module O = RamenOperation
module T = RamenTypes
module N = RamenName
module Files = RamenFiles
module Paths = RamenPaths
(* Building time series with points at regular times *)
type bucket =
(* Hopefully count will be small enough that sum can be tracked accurately *)
{ mutable count : float ; mutable sum : float ;
mutable min : float ; mutable max : float }
let print_bucket oc b =
Printf.fprintf oc "{ count = %f; sum = %f; min = %f; max = %f }"
b.count b.sum b.min b.max
(* [nt] is the number of time steps while [nc] is the number of data fields: *)
let make_buckets nt nc =
Array.init nt (fun _ ->
Array.init nc (fun _ ->
{ count = 0. ; sum = 0. ; min = max_float ; max = min_float }))
let pour_into_bucket b bi ci v r =
b.(bi).(ci).count <- b.(bi).(ci).count +. r ;
b.(bi).(ci).min <- min b.(bi).(ci).min v ;
b.(bi).(ci).max <- max b.(bi).(ci).max v ;
b.(bi).(ci).sum <- b.(bi).(ci).sum +. v ;
!logger.debug " v=%f, r=%f -> b.(%d).(%d) = %a" v r bi ci print_bucket b.(bi).(ci)
Returns both the index and the ratio of this bucket on the left of t
* ( between 0 inc . and 1 excl . )
* (between 0 inc. and 1 excl.) *)
let bucket_of_time since dt t =
let t = t -. since in
let i = floor (t /. dt) in
int_of_float i,
(t -. (i *. dt)) /. dt
let bucket_sum b =
if b.count = 0. then None else Some b.sum
let bucket_avg b =
if b.count = 0. then None else Some (b.sum /. b.count)
let bucket_min b =
if b.count = 0. then None else Some b.min
let bucket_max b =
if b.count = 0. then None else Some b.max
let bucket_count b =
Some b.count
Enumerates all the time*values .
* Returns the array of factor - column and the Enum.t of data .
*
* Each factor - column is the list of values for each given factor ( for
* instance , if you ask factoring by [ " ip " ; " port " ] then for each column
* you will have [ " ip_value " ; " port_value " ] for that column . If you
* ask for no factor then you have only one column which values is the empty
* list [ ] .
*
* The enumeration of data is composed of one entry per time value in
* increasing order , each entry being composed of the time and an array
* of data - columns .
*
* A data - column is itself an array with one optional float per selected
* field ( each factor - column thus has one data - column per selected field ) .
* Returns the array of factor-column and the Enum.t of data.
*
* Each factor-column is the list of values for each given factor (for
* instance, if you ask factoring by ["ip"; "port"] then for each column
* you will have ["ip_value"; "port_value"] for that column. If you
* ask for no factor then you have only one column which values is the empty
* list [].
*
* The enumeration of data is composed of one entry per time value in
* increasing order, each entry being composed of the time and an array
* of data-columns.
*
* A data-column is itself an array with one optional float per selected
* field (each factor-column thus has one data-column per selected field).
*)
(* TODO: (consolidation * data_field) list instead of a single consolidation
* for all fields *)
type bucket_time = Begin | Middle | End
(* Assumes the confclient has RamenReplay.topics in sync: *)
let get conf session num_points since until where factors
?consolidation ?(bucket_time=Middle) worker data_fields
~while_ =
!logger.debug "Build time series for %a, data=%a, where=%a, factors=%a"
N.worker_print worker
(List.print N.field_print) data_fields
(List.print (fun oc (field, op, value) ->
Printf.fprintf oc "%a %s %a"
N.field_print field
op
T.print value)) where
(List.print N.field_print) factors ;
let num_data_fields = List.length data_fields
and num_factors = List.length factors in
(* Prepare the buckets in which to aggregate the data fields: *)
let dt = (until -. since) /. float_of_int num_points in
let per_factor_buckets = Hashtbl.create 11 in
let bucket_of_time = bucket_of_time since dt
and time_of_bucket =
match bucket_time with
| Begin -> fun i -> since +. dt *. float_of_int i
| Middle -> fun i -> since +. dt *. (float_of_int i +. 0.5)
| End -> fun i -> since +. dt *. float_of_int (i + 1)
in
(* And the aggregation function: *)
let consolidate aggr_str =
match String.lowercase aggr_str with
| "min" -> bucket_min | "max" -> bucket_max | "sum" -> bucket_sum
| "count" -> bucket_count | "avg" -> bucket_avg
| _ -> invalid_arg "RamenTimeseries.get: unknown consolidation function"
in
(* The data fields we are really interested about are: the data fields +
* the factors.
* Note that order of factors does matter, so do not rev_append here! *)
let tuple_fields = factors @ data_fields in
!logger.debug "tuple_fields = %a"
(List.print N.field_print) tuple_fields ;
let callback (head : RamenTuple.field_typ list) =
(* TODO: RamenTuple.typ should be an array *)
let head = Array.of_list head in
(* Extract fields of interest (data fields, keys...) from a tuple: *)
(* So tuple will be composed of rev factors then data_fields: *)
let key_of_factors tuple =
Array.sub tuple 0 num_factors in
let open RamenSerialization in
let def_aggr =
Array.init num_data_fields (fun i ->
match head.(num_factors + i).aggr with
| Some str -> consolidate str
| None ->
(match consolidation with
| None -> bucket_avg
| Some str -> consolidate str))
in
If we asked for some factors and have no data , then there will be no
* columns in the result , which is OK ( cartesian product of data fields and
* factors ) . But if we asked for no factors then we expect one column per
* data field , whether there is data or not . So in that case let 's create
* the buckets in advance , in case on_tuple is not called at all :
* columns in the result, which is OK (cartesian product of data fields and
* factors). But if we asked for no factors then we expect one column per
* data field, whether there is data or not. So in that case let's create
* the buckets in advance, in case on_tuple is not called at all: *)
if num_factors = 0 then (
let buckets = make_buckets num_points num_data_fields in
Hashtbl.add per_factor_buckets [||] buckets) ;
(fun t1 t2 tuple ->
let k = key_of_factors tuple in
let buckets =
try Hashtbl.find per_factor_buckets k
with Not_found ->
!logger.debug "New time series for column key %a"
(Array.print T.print) k ;
let buckets = make_buckets num_points num_data_fields in
Hashtbl.add per_factor_buckets k buckets ;
buckets in
let bi1, r1 = bucket_of_time t1 and bi2, r2 = bucket_of_time t2 in
!logger.debug "bi1=%d (r1=%f), bi2=%d (r2=%f)" bi1 r1 bi2 r2 ;
(* If bi2 ends up right on the boundary, speed things up by shortening
* the range: *)
let bi2, r2 =
if r2 = 0. && bi2 > bi1 then bi2 - 1, 1. else bi2, r2 in
(* Iter over all data_fields, that are the last components of tuple: *)
for i = 0 to num_data_fields - 1 do
We assume that the value is " intensive " rather than " extensive " ,
* and so contribute the same amount to each buckets of the interval ,
* instead of distributing the value ( TODO : extensive values )
* and so contribute the same amount to each buckets of the interval,
* instead of distributing the value (TODO: extensive values) *)
let v = T.float_of_scalar tuple.(num_factors + i) in
Option.may (fun v ->
let v, bi1, bi2, r =
if bi1 = bi2 then (
(* Special case: just soften v *)
let r = r2 -. r1 in
abs_float r *. v, bi1, bi2, r
) else (
(* Values on the edge should contribute in proportion to overlap: *)
let v1 = v *. (1. -. r1) and v2 = v *. r2 in
if bi1 > 0 && bi1 < Array.length buckets then
pour_into_bucket buckets bi1 i v1 (1. -. r1) ;
if bi2 > 0 && bi2 < Array.length buckets then
pour_into_bucket buckets bi2 i v2 r2 ;
v, bi1 + 1, bi2 - 1, 1.
) in
for bi = max bi1 0 to min bi2 (Array.length buckets - 1) do
pour_into_bucket buckets bi i v r
done
) v
done),
(fun () ->
Extract the results as an Enum , one value per key
let indices = Enum.range 0 ~until:(num_points - 1) in
(* Assume keys and values will enumerate keys in the same orders: *)
let columns =
Hashtbl.keys per_factor_buckets |>
Array.of_enum in
let ts =
Hashtbl.values per_factor_buckets |>
Array.of_enum in
columns,
indices /@
(fun i ->
let t = time_of_bucket i
and v =
Array.map (fun buckets ->
Array.mapi (fun data_field_idx bucket ->
def_aggr.(data_field_idx) bucket
) buckets.(i)
) ts in
t, v)) in
(* Must not add event time in front of factors: *)
RamenExport.replay conf ~while_ session worker tuple_fields where since until
~with_event_time:false callback
(* [get] uses the number of points but users can specify either num-points or
* the time-step (in which case [since] and [until] are aligned to a multiple
* of that time-step.
* This helper function thus computes the effective [since], [until] and
* [num_points] based on user supplied [since], [until], [num_points] and
* [time_step]: *)
let compute_num_points time_step num_points since until =
(* Either num_points or time_step (but not both) must be set (>0): *)
assert ((num_points > 0 || time_step > 0.) &&
(num_points <= 0 || time_step <= 0.)) ;
(* If time_step is given then align bucket times with it.
* Internally, we use num_points though: *)
if num_points > 0 then
num_points, since, until
else
let since = align_float time_step since
and until = align_float ~round:ceil time_step until in
let num_points = round_to_int ((until -. since) /. time_step) in
num_points, since, until
(*
* Factors.
*)
let possible_values conf ?since ?until prog_name func factor =
!logger.debug "Retrieving possible values for factor %a of %a"
N.field_print factor
N.func_print func.VSI.name ;
let factors =
O.factors_of_operation func.VSI.operation in
if not (List.mem factor factors) then
invalid_arg "get_possible_values: not a factor" ;
let dir =
N.path_cat [ Paths.factors_of_function conf prog_name func ;
Files.quote (N.path (factor :> string)) ] in
let min_times =
(try Files.files_of dir
with Sys_error _ -> Enum.empty ()) //@
(fun fname ->
try
let min_time = RingBufLib.strtod (fname :> string) in
if Option.map_default ((<=) min_time) true until then
Some (min_time, fname) else None
with (Not_found | Failure _) -> None) |>
Array.of_enum in
Array.sort (fun (a, _) (b, _) -> Float.compare a b) min_times ;
(* Iter over all files which max_time (ie. next min_time) is not before
* [since]: *)
Array.fold_lefti (fun s i (_, fname) ->
let max_time =
if i < Array.length min_times - 1 then fst min_times.(i + 1)
else max_float in
if Option.map_default ((>=) max_time) true since then (
let fname = N.path_cat [ dir ; fname ] in
let s' : T.value Set.t =
RamenAdvLock.with_r_lock
fname (Files.marshal_from_fd ~default:Set.empty fname) in
Set.union s s'
) else s
) Set.empty min_times
| null | https://raw.githubusercontent.com/rixed/ramen/212544a570c8b4573613c8686e96ab717350df5f/src/RamenTimeseries.ml | ocaml | This program builds time series for the requested time range out of any
* operation field.
*
* The operation event-time has to be known, though.
Building time series with points at regular times
Hopefully count will be small enough that sum can be tracked accurately
[nt] is the number of time steps while [nc] is the number of data fields:
TODO: (consolidation * data_field) list instead of a single consolidation
* for all fields
Assumes the confclient has RamenReplay.topics in sync:
Prepare the buckets in which to aggregate the data fields:
And the aggregation function:
The data fields we are really interested about are: the data fields +
* the factors.
* Note that order of factors does matter, so do not rev_append here!
TODO: RamenTuple.typ should be an array
Extract fields of interest (data fields, keys...) from a tuple:
So tuple will be composed of rev factors then data_fields:
If bi2 ends up right on the boundary, speed things up by shortening
* the range:
Iter over all data_fields, that are the last components of tuple:
Special case: just soften v
Values on the edge should contribute in proportion to overlap:
Assume keys and values will enumerate keys in the same orders:
Must not add event time in front of factors:
[get] uses the number of points but users can specify either num-points or
* the time-step (in which case [since] and [until] are aligned to a multiple
* of that time-step.
* This helper function thus computes the effective [since], [until] and
* [num_points] based on user supplied [since], [until], [num_points] and
* [time_step]:
Either num_points or time_step (but not both) must be set (>0):
If time_step is given then align bucket times with it.
* Internally, we use num_points though:
* Factors.
Iter over all files which max_time (ie. next min_time) is not before
* [since]: | open Batteries
open RamenLog
open RamenHelpersNoLog
module C = RamenConf
module VSI = RamenSync.Value.SourceInfo
module O = RamenOperation
module T = RamenTypes
module N = RamenName
module Files = RamenFiles
module Paths = RamenPaths
type bucket =
{ mutable count : float ; mutable sum : float ;
mutable min : float ; mutable max : float }
let print_bucket oc b =
Printf.fprintf oc "{ count = %f; sum = %f; min = %f; max = %f }"
b.count b.sum b.min b.max
let make_buckets nt nc =
Array.init nt (fun _ ->
Array.init nc (fun _ ->
{ count = 0. ; sum = 0. ; min = max_float ; max = min_float }))
let pour_into_bucket b bi ci v r =
b.(bi).(ci).count <- b.(bi).(ci).count +. r ;
b.(bi).(ci).min <- min b.(bi).(ci).min v ;
b.(bi).(ci).max <- max b.(bi).(ci).max v ;
b.(bi).(ci).sum <- b.(bi).(ci).sum +. v ;
!logger.debug " v=%f, r=%f -> b.(%d).(%d) = %a" v r bi ci print_bucket b.(bi).(ci)
Returns both the index and the ratio of this bucket on the left of t
* ( between 0 inc . and 1 excl . )
* (between 0 inc. and 1 excl.) *)
let bucket_of_time since dt t =
let t = t -. since in
let i = floor (t /. dt) in
int_of_float i,
(t -. (i *. dt)) /. dt
let bucket_sum b =
if b.count = 0. then None else Some b.sum
let bucket_avg b =
if b.count = 0. then None else Some (b.sum /. b.count)
let bucket_min b =
if b.count = 0. then None else Some b.min
let bucket_max b =
if b.count = 0. then None else Some b.max
let bucket_count b =
Some b.count
Enumerates all the time*values .
* Returns the array of factor - column and the Enum.t of data .
*
* Each factor - column is the list of values for each given factor ( for
* instance , if you ask factoring by [ " ip " ; " port " ] then for each column
* you will have [ " ip_value " ; " port_value " ] for that column . If you
* ask for no factor then you have only one column which values is the empty
* list [ ] .
*
* The enumeration of data is composed of one entry per time value in
* increasing order , each entry being composed of the time and an array
* of data - columns .
*
* A data - column is itself an array with one optional float per selected
* field ( each factor - column thus has one data - column per selected field ) .
* Returns the array of factor-column and the Enum.t of data.
*
* Each factor-column is the list of values for each given factor (for
* instance, if you ask factoring by ["ip"; "port"] then for each column
* you will have ["ip_value"; "port_value"] for that column. If you
* ask for no factor then you have only one column which values is the empty
* list [].
*
* The enumeration of data is composed of one entry per time value in
* increasing order, each entry being composed of the time and an array
* of data-columns.
*
* A data-column is itself an array with one optional float per selected
* field (each factor-column thus has one data-column per selected field).
*)
type bucket_time = Begin | Middle | End
let get conf session num_points since until where factors
?consolidation ?(bucket_time=Middle) worker data_fields
~while_ =
!logger.debug "Build time series for %a, data=%a, where=%a, factors=%a"
N.worker_print worker
(List.print N.field_print) data_fields
(List.print (fun oc (field, op, value) ->
Printf.fprintf oc "%a %s %a"
N.field_print field
op
T.print value)) where
(List.print N.field_print) factors ;
let num_data_fields = List.length data_fields
and num_factors = List.length factors in
let dt = (until -. since) /. float_of_int num_points in
let per_factor_buckets = Hashtbl.create 11 in
let bucket_of_time = bucket_of_time since dt
and time_of_bucket =
match bucket_time with
| Begin -> fun i -> since +. dt *. float_of_int i
| Middle -> fun i -> since +. dt *. (float_of_int i +. 0.5)
| End -> fun i -> since +. dt *. float_of_int (i + 1)
in
let consolidate aggr_str =
match String.lowercase aggr_str with
| "min" -> bucket_min | "max" -> bucket_max | "sum" -> bucket_sum
| "count" -> bucket_count | "avg" -> bucket_avg
| _ -> invalid_arg "RamenTimeseries.get: unknown consolidation function"
in
let tuple_fields = factors @ data_fields in
!logger.debug "tuple_fields = %a"
(List.print N.field_print) tuple_fields ;
let callback (head : RamenTuple.field_typ list) =
let head = Array.of_list head in
let key_of_factors tuple =
Array.sub tuple 0 num_factors in
let open RamenSerialization in
let def_aggr =
Array.init num_data_fields (fun i ->
match head.(num_factors + i).aggr with
| Some str -> consolidate str
| None ->
(match consolidation with
| None -> bucket_avg
| Some str -> consolidate str))
in
If we asked for some factors and have no data , then there will be no
* columns in the result , which is OK ( cartesian product of data fields and
* factors ) . But if we asked for no factors then we expect one column per
* data field , whether there is data or not . So in that case let 's create
* the buckets in advance , in case on_tuple is not called at all :
* columns in the result, which is OK (cartesian product of data fields and
* factors). But if we asked for no factors then we expect one column per
* data field, whether there is data or not. So in that case let's create
* the buckets in advance, in case on_tuple is not called at all: *)
if num_factors = 0 then (
let buckets = make_buckets num_points num_data_fields in
Hashtbl.add per_factor_buckets [||] buckets) ;
(fun t1 t2 tuple ->
let k = key_of_factors tuple in
let buckets =
try Hashtbl.find per_factor_buckets k
with Not_found ->
!logger.debug "New time series for column key %a"
(Array.print T.print) k ;
let buckets = make_buckets num_points num_data_fields in
Hashtbl.add per_factor_buckets k buckets ;
buckets in
let bi1, r1 = bucket_of_time t1 and bi2, r2 = bucket_of_time t2 in
!logger.debug "bi1=%d (r1=%f), bi2=%d (r2=%f)" bi1 r1 bi2 r2 ;
let bi2, r2 =
if r2 = 0. && bi2 > bi1 then bi2 - 1, 1. else bi2, r2 in
for i = 0 to num_data_fields - 1 do
We assume that the value is " intensive " rather than " extensive " ,
* and so contribute the same amount to each buckets of the interval ,
* instead of distributing the value ( TODO : extensive values )
* and so contribute the same amount to each buckets of the interval,
* instead of distributing the value (TODO: extensive values) *)
let v = T.float_of_scalar tuple.(num_factors + i) in
Option.may (fun v ->
let v, bi1, bi2, r =
if bi1 = bi2 then (
let r = r2 -. r1 in
abs_float r *. v, bi1, bi2, r
) else (
let v1 = v *. (1. -. r1) and v2 = v *. r2 in
if bi1 > 0 && bi1 < Array.length buckets then
pour_into_bucket buckets bi1 i v1 (1. -. r1) ;
if bi2 > 0 && bi2 < Array.length buckets then
pour_into_bucket buckets bi2 i v2 r2 ;
v, bi1 + 1, bi2 - 1, 1.
) in
for bi = max bi1 0 to min bi2 (Array.length buckets - 1) do
pour_into_bucket buckets bi i v r
done
) v
done),
(fun () ->
Extract the results as an Enum , one value per key
let indices = Enum.range 0 ~until:(num_points - 1) in
let columns =
Hashtbl.keys per_factor_buckets |>
Array.of_enum in
let ts =
Hashtbl.values per_factor_buckets |>
Array.of_enum in
columns,
indices /@
(fun i ->
let t = time_of_bucket i
and v =
Array.map (fun buckets ->
Array.mapi (fun data_field_idx bucket ->
def_aggr.(data_field_idx) bucket
) buckets.(i)
) ts in
t, v)) in
RamenExport.replay conf ~while_ session worker tuple_fields where since until
~with_event_time:false callback
let compute_num_points time_step num_points since until =
assert ((num_points > 0 || time_step > 0.) &&
(num_points <= 0 || time_step <= 0.)) ;
if num_points > 0 then
num_points, since, until
else
let since = align_float time_step since
and until = align_float ~round:ceil time_step until in
let num_points = round_to_int ((until -. since) /. time_step) in
num_points, since, until
let possible_values conf ?since ?until prog_name func factor =
!logger.debug "Retrieving possible values for factor %a of %a"
N.field_print factor
N.func_print func.VSI.name ;
let factors =
O.factors_of_operation func.VSI.operation in
if not (List.mem factor factors) then
invalid_arg "get_possible_values: not a factor" ;
let dir =
N.path_cat [ Paths.factors_of_function conf prog_name func ;
Files.quote (N.path (factor :> string)) ] in
let min_times =
(try Files.files_of dir
with Sys_error _ -> Enum.empty ()) //@
(fun fname ->
try
let min_time = RingBufLib.strtod (fname :> string) in
if Option.map_default ((<=) min_time) true until then
Some (min_time, fname) else None
with (Not_found | Failure _) -> None) |>
Array.of_enum in
Array.sort (fun (a, _) (b, _) -> Float.compare a b) min_times ;
Array.fold_lefti (fun s i (_, fname) ->
let max_time =
if i < Array.length min_times - 1 then fst min_times.(i + 1)
else max_float in
if Option.map_default ((>=) max_time) true since then (
let fname = N.path_cat [ dir ; fname ] in
let s' : T.value Set.t =
RamenAdvLock.with_r_lock
fname (Files.marshal_from_fd ~default:Set.empty fname) in
Set.union s s'
) else s
) Set.empty min_times
|
56900ebe0c1ae1ae08102220f204ff333462b8aec80ae68cbc6c00141f1de24f | serras/munihac-2020-miso | Main.hs | # language NamedFieldPuns #
{-# language OverloadedStrings #-}
# language RecordWildCards #
{-# language OverloadedLists #-}
module Main where
import Data.Foldable (asum)
import Data.List (transpose, (!!))
import Data.Map ()
import Data.Maybe (isJust)
import Miso
import Miso.String (MisoString)
main :: IO ()
main = startApp App { .. }
where
initialAction = None
model = Model { grid = emptyGrid }
update = updateModel
view = viewModel
events = defaultEvents
subs = []
mountPoint = Nothing
logLevel = Off
data Square
= X | O
deriving (Show, Eq)
type Grid = [[Maybe Square]]
emptyGrid, aGrid :: Grid
emptyGrid = replicate 3 (replicate 3 Nothing)
aGrid = [ [ Just X, Nothing, Nothing ]
, [ Nothing, Just O, Nothing ]
, replicate 3 Nothing ]
hasWinner :: Grid -> Maybe Square
hasWinner g
= asum (map isWinnerRow thingToCheck)
where
thingToCheck
= g ++ transpose g
++ [ [g !! 0 !! 0, g !! 1 !! 1, g !! 2 !! 2]
, [g !! 0 !! 2, g !! 1 !! 1, g !! 2 !! 0] ]
isWinnerRow :: [Maybe Square] -> Maybe Square
isWinnerRow row
| all isJust row, all (== head row) row
= head row
| otherwise
= Nothing
data Model
= Model { grid :: Grid }
deriving (Show, Eq)
data Action
= None
| ClickSquare Int Int
deriving (Show, Eq)
updateModel :: Action -> Model -> Effect Action Model
updateModel None m
= noEff m
updateModel (ClickSquare rowId colId) m
= noEff m
bootstrapUrl :: MisoString
bootstrapUrl = ""
viewModel :: Model -> View Action
viewModel m
= div_ [ class_ "container"]
[ headerView
, newGameView m
, contentView m
-- , statsView m
, link_ [ rel_ "stylesheet"
, href_ bootstrapUrl ] ]
headerView :: View Action
headerView
= nav_ [ class_ "navbar navbar-dark bg-dark"]
[ h2_ [ class_ "bd-title text-light" ]
[ text "Tic-Tac-Toe "
, span_ [ class_ "badge badge-warning"]
[ text "in miso!"] ] ]
newGameView :: Model -> View Action
newGameView _
= nav_ [ class_ "navbar navbar-light bg-light"]
[ form_ [ class_ "form-inline" ]
[ input_ [ class_ "form-control mr-sm-2"
, type_ "text"
-- , value_ player1Name
-- , onChange undefined
, placeholder_ "Player 1" ]
-- , select_ [ class_ "custom-select"
-- , style_ [("margin-right", "15px")] ]
-- (flip map ["A", "B"] $ \option ->
-- option_ [ ] [ text option])
, input_ [ class_ "form-control mr-sm-2"
, type_ "text"
-- , value_ player2Name
-- , onChange undefined
, placeholder_ "Player 2" ]
-- , select_ [ class_ "custom-select"
-- , style_ [("margin-right", "15px")] ]
-- (flip map ["A", "B"] $ \option ->
-- option_ [ ] [ text option])
, button_ [ class_ "btn btn-outline-warning"
, type_ "button"
-- , onClick undefined
, disabled_ False ]
[ text "New game" ] ] ]
contentView :: Model -> View Action
contentView Model { .. }
= div_ [ style_ [("margin", "20px")]]
[ gridView grid
, alertView "who is the winner?" ]
gridView :: Grid -> View Action
gridView grid
= div_ [ style_ [("margin", "20px")]]
[ div_ [ class_ "row justify-content-around align-items-center" ]
[ h3_ [ ] [ text "Player 1"]
, div_ [ style_ [("display", "inline-block")] ]
[ div_ [ style_ [ ("display", "grid")
, ("grid-template-rows", "1fr 1fr 1fr")
, ("grid-template-columns", "1fr 1fr 1fr")
, ("grid-gap", "2px") ] ]
( flip concatMap (zip [0 ..] grid) $ \(rowId, row) ->
flip map (zip [0 ..] row) $ \(colId, sq) ->
cell rowId colId sq )]
, h3_ [ ] [ text "Player 2"] ] ]
where
cell :: Int -> Int -> Maybe Square -> View Action
cell rowId colId square
= div_ [ style_ [("width", "100px"), ("height", "100px")] ]
[ button_ [ type_ "button"
, style_ [ ("width", "100%"), ("height", "100%")
, ("font-size", "xxx-large") ]
, class_ "btn btn-outline-secondary"
, onClick (ClickSquare rowId colId) ]
[ text "·" ] ]
alertView :: MisoString -> View Action
alertView v
= div_ [ class_ "alert alert-warning"
, style_ [("text-align", "center")] ]
[ h4_ [ class_ "alert-heading" ]
[ text v ] ]
fakeStats :: [MisoString]
fakeStats
= [ "A - B, won by A in 3 moves"
, "Quijote - Sancho, won by Sancho in 5 moves" ]
statsView :: Model -> View Action
statsView _
= div_ [ class_ "row justify-content-around align-items-center"
, style_ [("margin-bottom", "20px")] ]
[ ul_ [ class_ "list-group"]
( flip map fakeStats $ \elt ->
ul_ [ class_ "list-group-item" ] [ text elt ] ) ] | null | https://raw.githubusercontent.com/serras/munihac-2020-miso/ab91ced84877a6b0b938d89eeaaaea29b25ffb15/exercise/web/Main.hs | haskell | # language OverloadedStrings #
# language OverloadedLists #
, statsView m
, value_ player1Name
, onChange undefined
, select_ [ class_ "custom-select"
, style_ [("margin-right", "15px")] ]
(flip map ["A", "B"] $ \option ->
option_ [ ] [ text option])
, value_ player2Name
, onChange undefined
, select_ [ class_ "custom-select"
, style_ [("margin-right", "15px")] ]
(flip map ["A", "B"] $ \option ->
option_ [ ] [ text option])
, onClick undefined | # language NamedFieldPuns #
# language RecordWildCards #
module Main where
import Data.Foldable (asum)
import Data.List (transpose, (!!))
import Data.Map ()
import Data.Maybe (isJust)
import Miso
import Miso.String (MisoString)
main :: IO ()
main = startApp App { .. }
where
initialAction = None
model = Model { grid = emptyGrid }
update = updateModel
view = viewModel
events = defaultEvents
subs = []
mountPoint = Nothing
logLevel = Off
data Square
= X | O
deriving (Show, Eq)
type Grid = [[Maybe Square]]
emptyGrid, aGrid :: Grid
emptyGrid = replicate 3 (replicate 3 Nothing)
aGrid = [ [ Just X, Nothing, Nothing ]
, [ Nothing, Just O, Nothing ]
, replicate 3 Nothing ]
hasWinner :: Grid -> Maybe Square
hasWinner g
= asum (map isWinnerRow thingToCheck)
where
thingToCheck
= g ++ transpose g
++ [ [g !! 0 !! 0, g !! 1 !! 1, g !! 2 !! 2]
, [g !! 0 !! 2, g !! 1 !! 1, g !! 2 !! 0] ]
isWinnerRow :: [Maybe Square] -> Maybe Square
isWinnerRow row
| all isJust row, all (== head row) row
= head row
| otherwise
= Nothing
data Model
= Model { grid :: Grid }
deriving (Show, Eq)
data Action
= None
| ClickSquare Int Int
deriving (Show, Eq)
updateModel :: Action -> Model -> Effect Action Model
updateModel None m
= noEff m
updateModel (ClickSquare rowId colId) m
= noEff m
bootstrapUrl :: MisoString
bootstrapUrl = ""
viewModel :: Model -> View Action
viewModel m
= div_ [ class_ "container"]
[ headerView
, newGameView m
, contentView m
, link_ [ rel_ "stylesheet"
, href_ bootstrapUrl ] ]
headerView :: View Action
headerView
= nav_ [ class_ "navbar navbar-dark bg-dark"]
[ h2_ [ class_ "bd-title text-light" ]
[ text "Tic-Tac-Toe "
, span_ [ class_ "badge badge-warning"]
[ text "in miso!"] ] ]
newGameView :: Model -> View Action
newGameView _
= nav_ [ class_ "navbar navbar-light bg-light"]
[ form_ [ class_ "form-inline" ]
[ input_ [ class_ "form-control mr-sm-2"
, type_ "text"
, placeholder_ "Player 1" ]
, input_ [ class_ "form-control mr-sm-2"
, type_ "text"
, placeholder_ "Player 2" ]
, button_ [ class_ "btn btn-outline-warning"
, type_ "button"
, disabled_ False ]
[ text "New game" ] ] ]
contentView :: Model -> View Action
contentView Model { .. }
= div_ [ style_ [("margin", "20px")]]
[ gridView grid
, alertView "who is the winner?" ]
gridView :: Grid -> View Action
gridView grid
= div_ [ style_ [("margin", "20px")]]
[ div_ [ class_ "row justify-content-around align-items-center" ]
[ h3_ [ ] [ text "Player 1"]
, div_ [ style_ [("display", "inline-block")] ]
[ div_ [ style_ [ ("display", "grid")
, ("grid-template-rows", "1fr 1fr 1fr")
, ("grid-template-columns", "1fr 1fr 1fr")
, ("grid-gap", "2px") ] ]
( flip concatMap (zip [0 ..] grid) $ \(rowId, row) ->
flip map (zip [0 ..] row) $ \(colId, sq) ->
cell rowId colId sq )]
, h3_ [ ] [ text "Player 2"] ] ]
where
cell :: Int -> Int -> Maybe Square -> View Action
cell rowId colId square
= div_ [ style_ [("width", "100px"), ("height", "100px")] ]
[ button_ [ type_ "button"
, style_ [ ("width", "100%"), ("height", "100%")
, ("font-size", "xxx-large") ]
, class_ "btn btn-outline-secondary"
, onClick (ClickSquare rowId colId) ]
[ text "·" ] ]
alertView :: MisoString -> View Action
alertView v
= div_ [ class_ "alert alert-warning"
, style_ [("text-align", "center")] ]
[ h4_ [ class_ "alert-heading" ]
[ text v ] ]
fakeStats :: [MisoString]
fakeStats
= [ "A - B, won by A in 3 moves"
, "Quijote - Sancho, won by Sancho in 5 moves" ]
statsView :: Model -> View Action
statsView _
= div_ [ class_ "row justify-content-around align-items-center"
, style_ [("margin-bottom", "20px")] ]
[ ul_ [ class_ "list-group"]
( flip map fakeStats $ \elt ->
ul_ [ class_ "list-group-item" ] [ text elt ] ) ] |
adc3e2854f1704a31c6887b647a26210a900cb90868f1506650a423937daa5ad | hsyl20/haskus-system | Mount.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DataKinds #
# LANGUAGE TypeApplications #
-- | Filesystem mount
module Haskus.System.Linux.FileSystem.Mount
( MountFlag(..)
, MountFlags
, UnmountFlag(..)
, UnmountFlags
, sysMount
, sysUnmount
, mountSysFS
, mountDevFS
, mountProcFS
, mountTmpFS
)
where
import Foreign.Ptr (Ptr,nullPtr)
import Haskus.Format.Binary.Word
import Haskus.Format.Binary.BitSet
import Haskus.Format.String (withCString)
import qualified Haskus.Format.Binary.BitSet as BitSet
import Haskus.System.Linux.ErrorCode
import Haskus.System.Linux.Syscalls
import Haskus.System.Linux.Internals.FileSystem
import Haskus.Utils.Flow
| Unmount flag
data UnmountFlag
= UnmountForce -- ^ Force unmounting
| UnmountDetach -- ^ Just detach from the tree
^ for expiry
| UnmountDontFollow -- ^ Don't follow symlink on unmount
deriving (Show,Eq,Enum,CBitSet)
| Unmount flags
type UnmountFlags = BitSet Word64 UnmountFlag
-- | Mount a file system
sysMount :: MonadInIO m => String -> String -> String -> MountFlags -> Ptr () -> Excepts '[ErrorCode] m ()
sysMount source target fstype flags dat =
withCString source $ \source' ->
withCString target $ \target' ->
withCString fstype $ \fstype' ->
liftIO (syscall_mount source' target' fstype' (BitSet.toBits flags) dat)
>>= checkErrorCode_
| Unmount a file system
sysUnmount :: MonadInIO m => String -> UnmountFlags -> Excepts '[ErrorCode] m ()
sysUnmount target flags =
withCString target $ \target' ->
liftIO (syscall_umount2 target' (BitSet.toBits flags))
>>= checkErrorCode_
-- | Type of the low-level Linux "mount" function
type MountCall m = String -> String -> String -> MountFlags -> Ptr () -> Excepts '[ErrorCode] m ()
-- | Mount SysFS at the given location
mountSysFS :: MonadIO m => MountCall m -> FilePath -> Excepts '[ErrorCode] m ()
mountSysFS mount path = mount "none" path "sysfs" BitSet.empty nullPtr
-- | Mount DevFS at the given location
mountDevFS :: MonadIO m => MountCall m -> FilePath -> Excepts '[ErrorCode] m ()
mountDevFS mount path = mount "none" path "devtmpfs" BitSet.empty nullPtr
-- | Mount ProcFS at the given location
mountProcFS :: MonadIO m => MountCall m -> FilePath -> Excepts '[ErrorCode] m ()
mountProcFS mount path = mount "none" path "proc" BitSet.empty nullPtr
-- | Mount TmpFS at the given location
mountTmpFS :: MonadIO m => MountCall m -> FilePath -> Excepts '[ErrorCode] m ()
mountTmpFS mount path = mount "none" path "tmpfs" BitSet.empty nullPtr
| null | https://raw.githubusercontent.com/hsyl20/haskus-system/2f389c6ecae5b0180b464ddef51e36f6e567d690/haskus-system/src/lib/Haskus/System/Linux/FileSystem/Mount.hs | haskell | # LANGUAGE DeriveAnyClass #
| Filesystem mount
^ Force unmounting
^ Just detach from the tree
^ Don't follow symlink on unmount
| Mount a file system
| Type of the low-level Linux "mount" function
| Mount SysFS at the given location
| Mount DevFS at the given location
| Mount ProcFS at the given location
| Mount TmpFS at the given location | # LANGUAGE DataKinds #
# LANGUAGE TypeApplications #
module Haskus.System.Linux.FileSystem.Mount
( MountFlag(..)
, MountFlags
, UnmountFlag(..)
, UnmountFlags
, sysMount
, sysUnmount
, mountSysFS
, mountDevFS
, mountProcFS
, mountTmpFS
)
where
import Foreign.Ptr (Ptr,nullPtr)
import Haskus.Format.Binary.Word
import Haskus.Format.Binary.BitSet
import Haskus.Format.String (withCString)
import qualified Haskus.Format.Binary.BitSet as BitSet
import Haskus.System.Linux.ErrorCode
import Haskus.System.Linux.Syscalls
import Haskus.System.Linux.Internals.FileSystem
import Haskus.Utils.Flow
| Unmount flag
data UnmountFlag
^ for expiry
deriving (Show,Eq,Enum,CBitSet)
| Unmount flags
type UnmountFlags = BitSet Word64 UnmountFlag
sysMount :: MonadInIO m => String -> String -> String -> MountFlags -> Ptr () -> Excepts '[ErrorCode] m ()
sysMount source target fstype flags dat =
withCString source $ \source' ->
withCString target $ \target' ->
withCString fstype $ \fstype' ->
liftIO (syscall_mount source' target' fstype' (BitSet.toBits flags) dat)
>>= checkErrorCode_
| Unmount a file system
sysUnmount :: MonadInIO m => String -> UnmountFlags -> Excepts '[ErrorCode] m ()
sysUnmount target flags =
withCString target $ \target' ->
liftIO (syscall_umount2 target' (BitSet.toBits flags))
>>= checkErrorCode_
type MountCall m = String -> String -> String -> MountFlags -> Ptr () -> Excepts '[ErrorCode] m ()
mountSysFS :: MonadIO m => MountCall m -> FilePath -> Excepts '[ErrorCode] m ()
mountSysFS mount path = mount "none" path "sysfs" BitSet.empty nullPtr
mountDevFS :: MonadIO m => MountCall m -> FilePath -> Excepts '[ErrorCode] m ()
mountDevFS mount path = mount "none" path "devtmpfs" BitSet.empty nullPtr
mountProcFS :: MonadIO m => MountCall m -> FilePath -> Excepts '[ErrorCode] m ()
mountProcFS mount path = mount "none" path "proc" BitSet.empty nullPtr
mountTmpFS :: MonadIO m => MountCall m -> FilePath -> Excepts '[ErrorCode] m ()
mountTmpFS mount path = mount "none" path "tmpfs" BitSet.empty nullPtr
|
9ddbde36040fd39b1a1cbd1d169efbe0ea824d396ed4f8ca19664723c601fa6d | cachix/cachix | V2.hs | module Cachix.Types.DeployResponse.V2 where
import Data.Aeson
( FromJSON,
ToJSON,
)
import Data.HashMap.Strict
import Data.Swagger (ToSchema)
import Data.UUID (UUID)
import Protolude
data Details = Details
{ id :: UUID,
url :: Text
}
deriving stock (Show, Generic)
deriving anyclass (FromJSON, ToJSON, ToSchema, NFData)
newtype DeployResponse = DeployResponse
{ agents :: HashMap Text Details
}
deriving stock (Show, Generic)
deriving anyclass (FromJSON, ToJSON, ToSchema, NFData)
| null | https://raw.githubusercontent.com/cachix/cachix/0da6106c495474348a1a73a1a5fe16463eaa7fa5/cachix-api/src/Cachix/Types/DeployResponse/V2.hs | haskell | module Cachix.Types.DeployResponse.V2 where
import Data.Aeson
( FromJSON,
ToJSON,
)
import Data.HashMap.Strict
import Data.Swagger (ToSchema)
import Data.UUID (UUID)
import Protolude
data Details = Details
{ id :: UUID,
url :: Text
}
deriving stock (Show, Generic)
deriving anyclass (FromJSON, ToJSON, ToSchema, NFData)
newtype DeployResponse = DeployResponse
{ agents :: HashMap Text Details
}
deriving stock (Show, Generic)
deriving anyclass (FromJSON, ToJSON, ToSchema, NFData)
| |
e2ac2e2c89fc49829631b027dbe9a6156af3ebb5f16b3462c683f28c947f8586 | ds-wizard/engine-backend | FileSM.hs | module Shared.Api.Resource.Common.FileSM where
import Data.Swagger
import Servant
import Servant.Multipart
import Servant.Swagger.Internal
import Shared.Api.Resource.Common.FileDTO
instance HasSwagger api => HasSwagger (MultipartForm Mem FileDTO :> api) where
toSwagger _ = addParam param (toSwagger (Proxy :: Proxy api))
where
param =
Param
{ _paramName = "file"
, _paramDescription = Just "File to upload"
, _paramRequired = Just True
, _paramSchema =
ParamOther
( mempty
{ _paramOtherSchemaIn = ParamFormData
, _paramOtherSchemaParamSchema = mempty {_paramSchemaType = Just SwaggerFile}
}
)
}
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/12717256cde8d20020e30cd55dc3ef00fef9362a/engine-shared/src/Shared/Api/Resource/Common/FileSM.hs | haskell | module Shared.Api.Resource.Common.FileSM where
import Data.Swagger
import Servant
import Servant.Multipart
import Servant.Swagger.Internal
import Shared.Api.Resource.Common.FileDTO
instance HasSwagger api => HasSwagger (MultipartForm Mem FileDTO :> api) where
toSwagger _ = addParam param (toSwagger (Proxy :: Proxy api))
where
param =
Param
{ _paramName = "file"
, _paramDescription = Just "File to upload"
, _paramRequired = Just True
, _paramSchema =
ParamOther
( mempty
{ _paramOtherSchemaIn = ParamFormData
, _paramOtherSchemaParamSchema = mempty {_paramSchemaType = Just SwaggerFile}
}
)
}
| |
341294eafbf61005584b5924826dd3bc3f4fcc1c44610d078a95366fd573ccca | patricoferris/opam-github-workflow | types.mli | type kv = Yaml.value [@@deriving yaml]
(** A Yaml key-value store -- this is exposed in order to be flexible with
things like environment variable names which cannot be dynamically decided
by the user if bound to a record type *)
type env = kv
(** The type of environment variables *)
type output = kv
(** The type of outputs *)
type run = {
run_shell : string option; [@key "shell"]
run_workdir : string option; [@key "working-directory"]
}
(** The type of run statements *)
type defaults = { default_run : run [@key "run"] }
(** The type of defaults *)
type container = {
image : string option;
credentials : kv option;
container_env : env option; [@key "env"]
ports : int list option;
volumes : string list option;
options : string option;
}
(** The type of docker containers *)
type services = container
type with_ = kv
(** The type of input variables for external actions *)
type step = {
step_name : string option; [@key "name"]
uses : string option;
step_run : string option; [@key "run"]
step_env : env option; [@key "env"]
step_workdir : string option; [@key "working-directory"]
step_shell : string option; [@key "shell"]
with_ : with_ option; [@key "with"]
step_if : string option; [@key "if"]
continue_on_err : bool option; [@key "continue-on-error"]
}
(** The type of steps in a job *)
type strategy = {
matrix : kv option;
fail_fast : bool option; [@key "fail-fast"]
max_parallel : int option; [@key "max-parallel"]
}
(** The type of strategies to define things like matrices *)
type job = {
job_name : string option; [@key "name"]
strategy : strategy option;
runs_on : string; [@key "runs-on"]
container : container option;
services : services option;
outputs : output option;
job_env : env option; [@key "env"]
job_defaults : defaults option; [@key "defaults"]
job_if : string option; [@key "if"]
steps : step list;
timeout : int option; [@key "timeout-minutes"]
needs : string option;
}
[@@deriving yaml]
(** The type of jobs *)
type on =
| List of string list
| Complex of Events.t (** The type of triggers for the workflow *)
type 'a t = {
name : string option;
on : on;
env : env option;
defaults : defaults option;
jobs : 'a;
}
[@@deriving yaml]
* The type of Github Workflows -- the parameter [ ' a ] allows you supply names
to your jobs
to your jobs *)
| null | https://raw.githubusercontent.com/patricoferris/opam-github-workflow/6fe36af331853152da5a78b9bbc9a9ecd48b5160/lib/types.mli | ocaml | * A Yaml key-value store -- this is exposed in order to be flexible with
things like environment variable names which cannot be dynamically decided
by the user if bound to a record type
* The type of environment variables
* The type of outputs
* The type of run statements
* The type of defaults
* The type of docker containers
* The type of input variables for external actions
* The type of steps in a job
* The type of strategies to define things like matrices
* The type of jobs
* The type of triggers for the workflow | type kv = Yaml.value [@@deriving yaml]
type env = kv
type output = kv
type run = {
run_shell : string option; [@key "shell"]
run_workdir : string option; [@key "working-directory"]
}
type defaults = { default_run : run [@key "run"] }
type container = {
image : string option;
credentials : kv option;
container_env : env option; [@key "env"]
ports : int list option;
volumes : string list option;
options : string option;
}
type services = container
type with_ = kv
type step = {
step_name : string option; [@key "name"]
uses : string option;
step_run : string option; [@key "run"]
step_env : env option; [@key "env"]
step_workdir : string option; [@key "working-directory"]
step_shell : string option; [@key "shell"]
with_ : with_ option; [@key "with"]
step_if : string option; [@key "if"]
continue_on_err : bool option; [@key "continue-on-error"]
}
type strategy = {
matrix : kv option;
fail_fast : bool option; [@key "fail-fast"]
max_parallel : int option; [@key "max-parallel"]
}
type job = {
job_name : string option; [@key "name"]
strategy : strategy option;
runs_on : string; [@key "runs-on"]
container : container option;
services : services option;
outputs : output option;
job_env : env option; [@key "env"]
job_defaults : defaults option; [@key "defaults"]
job_if : string option; [@key "if"]
steps : step list;
timeout : int option; [@key "timeout-minutes"]
needs : string option;
}
[@@deriving yaml]
type on =
| List of string list
type 'a t = {
name : string option;
on : on;
env : env option;
defaults : defaults option;
jobs : 'a;
}
[@@deriving yaml]
* The type of Github Workflows -- the parameter [ ' a ] allows you supply names
to your jobs
to your jobs *)
|
4886c3a8c49c3bb6a297dc8dcd0677e5eda8eccd2a6e822474b46cc59106bfb8 | killme2008/ring.velocity | handler.clj | (ns demo.handler
(:use compojure.core)
(:use [ring.velocity.core :only [render template-resources]])
(:require [compojure.handler :as handler]
[compojure.route :as route]))
(defroutes app-routes
(GET "/" [] (render "index.vm"))
(POST "/hello" [name] (render "index.vm" :name name))
(template-resources "/vm")
(route/not-found "Not Found"))
(def app
(handler/site app-routes))
| null | https://raw.githubusercontent.com/killme2008/ring.velocity/e24e662e7ba46aae1d2f2cb5dcb5ccd1fe23dc78/demo/src/demo/handler.clj | clojure | (ns demo.handler
(:use compojure.core)
(:use [ring.velocity.core :only [render template-resources]])
(:require [compojure.handler :as handler]
[compojure.route :as route]))
(defroutes app-routes
(GET "/" [] (render "index.vm"))
(POST "/hello" [name] (render "index.vm" :name name))
(template-resources "/vm")
(route/not-found "Not Found"))
(def app
(handler/site app-routes))
| |
53f4ca7d17a2a3253e5c3b8214818a2b11e6a0cc7965db38e43c0fd701462340 | erlang-ls/erlang_ls | els_code_lens_suggest_spec.erl | %%==============================================================================
Code Lens : suggest_spec
%%==============================================================================
-module(els_code_lens_suggest_spec).
-behaviour(els_code_lens).
-export([
init/1,
command/3,
is_default/0,
pois/1
]).
%%==============================================================================
%% Includes
%%==============================================================================
-include_lib("kernel/include/logger.hrl").
%%==============================================================================
%% Type Definitions
%%==============================================================================
-type state() :: els_typer:info() | 'no_info'.
%%==============================================================================
%% Callback functions for the els_code_lens behaviour
%%==============================================================================
-spec init(els_dt_document:item()) -> state().
init(#{uri := Uri} = _Document) ->
try els_typer:get_info(Uri) of
Info ->
Info
catch
C:E:S ->
Fmt =
"Cannot extract typer info.~n"
"Class: ~p~n"
"Exception: ~p~n"
"Stacktrace: ~p~n",
?LOG_WARNING(Fmt, [C, E, S]),
'no_info'
end.
-spec command(els_dt_document:item(), els_poi:poi(), state()) -> els_command:command().
command(_Document, _POI, 'no_info') ->
CommandId = <<"suggest-spec">>,
Title = <<"Cannot extract specs (check logs for details)">>,
els_command:make_command(Title, CommandId, []);
command(Document, #{range := #{from := {Line, _}}} = POI, Info) ->
#{uri := Uri} = Document,
CommandId = <<"suggest-spec">>,
Spec = get_type_spec(POI, Info),
Title = truncate_spec_title(Spec, spec_title_max_length()),
CommandArgs = [
#{
uri => Uri,
line => Line,
spec => Spec
}
],
els_command:make_command(Title, CommandId, CommandArgs).
-spec is_default() -> boolean().
is_default() ->
false.
-spec pois(els_dt_document:item()) -> [els_poi:poi()].
pois(Document) ->
Functions = els_dt_document:pois(Document, [function]),
Specs = els_dt_document:pois(Document, [spec]),
SpecsIds = [Id || #{id := Id} <- Specs],
[POI || #{id := Id} = POI <- Functions, not lists:member(Id, SpecsIds)].
%%==============================================================================
Internal functions
%%==============================================================================
-spec get_type_spec(els_poi:poi(), els_typer:info()) -> binary().
get_type_spec(POI, Info) ->
#{id := {Function, Arity}} = POI,
Spec = els_typer:get_type_spec(Function, Arity, Info),
re:replace(Spec, ",", ", ", [global, {return, binary}]).
-spec truncate_spec_title(binary(), integer()) -> binary().
truncate_spec_title(Spec, MaxLength) ->
Length = string:length(Spec),
case Length > MaxLength of
true ->
Title = unicode:characters_to_binary(
string:slice(Spec, 0, MaxLength - 3)
),
<<Title/binary, "...">>;
false ->
Spec
end.
-spec spec_title_max_length() -> integer().
spec_title_max_length() ->
application:get_env(els_core, suggest_spec_title_max_length, 100).
| null | https://raw.githubusercontent.com/erlang-ls/erlang_ls/2c17eaed759bdca2b42361b9085c808603a22aa5/apps/els_lsp/src/els_code_lens_suggest_spec.erl | erlang | ==============================================================================
==============================================================================
==============================================================================
Includes
==============================================================================
==============================================================================
Type Definitions
==============================================================================
==============================================================================
Callback functions for the els_code_lens behaviour
==============================================================================
==============================================================================
============================================================================== | Code Lens : suggest_spec
-module(els_code_lens_suggest_spec).
-behaviour(els_code_lens).
-export([
init/1,
command/3,
is_default/0,
pois/1
]).
-include_lib("kernel/include/logger.hrl").
-type state() :: els_typer:info() | 'no_info'.
-spec init(els_dt_document:item()) -> state().
init(#{uri := Uri} = _Document) ->
try els_typer:get_info(Uri) of
Info ->
Info
catch
C:E:S ->
Fmt =
"Cannot extract typer info.~n"
"Class: ~p~n"
"Exception: ~p~n"
"Stacktrace: ~p~n",
?LOG_WARNING(Fmt, [C, E, S]),
'no_info'
end.
-spec command(els_dt_document:item(), els_poi:poi(), state()) -> els_command:command().
command(_Document, _POI, 'no_info') ->
CommandId = <<"suggest-spec">>,
Title = <<"Cannot extract specs (check logs for details)">>,
els_command:make_command(Title, CommandId, []);
command(Document, #{range := #{from := {Line, _}}} = POI, Info) ->
#{uri := Uri} = Document,
CommandId = <<"suggest-spec">>,
Spec = get_type_spec(POI, Info),
Title = truncate_spec_title(Spec, spec_title_max_length()),
CommandArgs = [
#{
uri => Uri,
line => Line,
spec => Spec
}
],
els_command:make_command(Title, CommandId, CommandArgs).
-spec is_default() -> boolean().
is_default() ->
false.
-spec pois(els_dt_document:item()) -> [els_poi:poi()].
pois(Document) ->
Functions = els_dt_document:pois(Document, [function]),
Specs = els_dt_document:pois(Document, [spec]),
SpecsIds = [Id || #{id := Id} <- Specs],
[POI || #{id := Id} = POI <- Functions, not lists:member(Id, SpecsIds)].
Internal functions
-spec get_type_spec(els_poi:poi(), els_typer:info()) -> binary().
get_type_spec(POI, Info) ->
#{id := {Function, Arity}} = POI,
Spec = els_typer:get_type_spec(Function, Arity, Info),
re:replace(Spec, ",", ", ", [global, {return, binary}]).
-spec truncate_spec_title(binary(), integer()) -> binary().
truncate_spec_title(Spec, MaxLength) ->
Length = string:length(Spec),
case Length > MaxLength of
true ->
Title = unicode:characters_to_binary(
string:slice(Spec, 0, MaxLength - 3)
),
<<Title/binary, "...">>;
false ->
Spec
end.
-spec spec_title_max_length() -> integer().
spec_title_max_length() ->
application:get_env(els_core, suggest_spec_title_max_length, 100).
|
52e84ae78e2cacd17e26a98a259fff4f95219425838da2e988a7c62c05110923 | lachenmayer/arrowsmith | Declaration.hs | # OPTIONS_GHC -Wall -fno - warn - unused - do - bind #
module Parse.Declaration where
import Control.Applicative ((<$>))
import Text.Parsec ( (<|>), (<?>), choice, digit, optionMaybe, string, try )
import qualified AST.Declaration as D
import qualified Parse.Expression as Expr
import Parse.Helpers
import qualified Parse.Type as Type
declaration :: IParser D.SourceDecl
declaration =
typeDecl <|> infixDecl <|> port <|> definition
-- TYPE ANNOTATIONS and DEFINITIONS
definition :: IParser D.SourceDecl
definition =
D.Definition <$> (Expr.typeAnnotation <|> Expr.definition)
-- TYPE ALIAS and UNION TYPES
typeDecl :: IParser D.SourceDecl
typeDecl =
do try (reserved "type") <?> "type declaration"
forcedWS
isAlias <- optionMaybe (string "alias" >> forcedWS)
name <- capVar
args <- spacePrefix lowVar
padded equals
case isAlias of
Just _ ->
do tipe <- Type.expr <?> "a type"
return (D.TypeAlias name args tipe)
Nothing ->
do tcs <- pipeSep1 Type.constructor <?> "a constructor for a union type"
return $ D.Datatype name args tcs
INFIX
infixDecl :: IParser D.SourceDecl
infixDecl =
do assoc <-
choice
[ try (reserved "infixl") >> return D.L
, try (reserved "infixr") >> return D.R
, try (reserved "infix") >> return D.N
]
forcedWS
n <- digit
forcedWS
D.Fixity assoc (read [n]) <$> anyOp
-- PORT
port :: IParser D.SourceDecl
port =
do try (reserved "port")
whitespace
name <- lowVar
whitespace
choice [ portAnnotation name, portDefinition name ]
where
portAnnotation name =
do try hasType
whitespace
tipe <- Type.expr <?> "a type"
return (D.Port (D.PortAnnotation name tipe))
portDefinition name =
do try equals
whitespace
expr <- Expr.expr
return (D.Port (D.PortDefinition name expr))
| null | https://raw.githubusercontent.com/lachenmayer/arrowsmith/34b6bdeddddb2d8b9c6f41002e87ec65ce8a701a/elm-compiler/src/Parse/Declaration.hs | haskell | TYPE ANNOTATIONS and DEFINITIONS
TYPE ALIAS and UNION TYPES
PORT | # OPTIONS_GHC -Wall -fno - warn - unused - do - bind #
module Parse.Declaration where
import Control.Applicative ((<$>))
import Text.Parsec ( (<|>), (<?>), choice, digit, optionMaybe, string, try )
import qualified AST.Declaration as D
import qualified Parse.Expression as Expr
import Parse.Helpers
import qualified Parse.Type as Type
declaration :: IParser D.SourceDecl
declaration =
typeDecl <|> infixDecl <|> port <|> definition
definition :: IParser D.SourceDecl
definition =
D.Definition <$> (Expr.typeAnnotation <|> Expr.definition)
typeDecl :: IParser D.SourceDecl
typeDecl =
do try (reserved "type") <?> "type declaration"
forcedWS
isAlias <- optionMaybe (string "alias" >> forcedWS)
name <- capVar
args <- spacePrefix lowVar
padded equals
case isAlias of
Just _ ->
do tipe <- Type.expr <?> "a type"
return (D.TypeAlias name args tipe)
Nothing ->
do tcs <- pipeSep1 Type.constructor <?> "a constructor for a union type"
return $ D.Datatype name args tcs
INFIX
infixDecl :: IParser D.SourceDecl
infixDecl =
do assoc <-
choice
[ try (reserved "infixl") >> return D.L
, try (reserved "infixr") >> return D.R
, try (reserved "infix") >> return D.N
]
forcedWS
n <- digit
forcedWS
D.Fixity assoc (read [n]) <$> anyOp
port :: IParser D.SourceDecl
port =
do try (reserved "port")
whitespace
name <- lowVar
whitespace
choice [ portAnnotation name, portDefinition name ]
where
portAnnotation name =
do try hasType
whitespace
tipe <- Type.expr <?> "a type"
return (D.Port (D.PortAnnotation name tipe))
portDefinition name =
do try equals
whitespace
expr <- Expr.expr
return (D.Port (D.PortDefinition name expr))
|
37a06c90365c079a7846173873d81162438f9143ecf1b46adbe97b995e12d231 | shirok/Gauche | fields.scm | (define (check-bit-field-operations)
(print-header "Checking bit field operations...")
(check (bitvector-field-any? (bitvector 0 1 0 0) 0 4) => #t)
(check (bitvector-field-any? (bitvector 0 0 0 0) 0 4) => #f)
(check (bitvector-field-any? (bitvector 0 1 0 0) 1 3) => #t)
(check (bitvector-field-any? (bitvector 0 1 0 0) 2 4) => #f)
(check (bitvector-field-every? (make-bitvector 4 1) 0 4) => #t)
(check (bitvector-field-every? (bitvector 1 1 1 0) 0 4) => #f)
(check (bitvector-field-every? (bitvector 1 1 0 0) 0 2) => #t)
(check (bitvector-field-every? (bitvector 1 1 0 0) 2 4) => #f)
(check (bitvector= (bitvector-field-clear (make-bitvector 4 1) 0 2)
(bitvector 0 0 1 1))
=> #t)
(let ((bvec (make-bitvector 4 1)))
(check (bitvector= (begin (bitvector-field-clear! bvec 0 2) bvec)
(bitvector 0 0 1 1))
=> #t))
(check (bitvector= (bitvector-field-set (make-bitvector 4 0) 0 2)
(bitvector 1 1 0 0))
=> #t)
(let ((bvec (make-bitvector 4 0)))
(check (bitvector= (begin (bitvector-field-set! bvec 0 2) bvec)
(bitvector 1 1 0 0))
=> #t))
;;; replace-same and replace
(check
(bitvector=
(bitvector-field-replace-same (make-bitvector 4 0)
(make-bitvector 4 1)
1
3)
(bitvector 0 1 1 0))
=> #t)
(let ((bvec (make-bitvector 4 0)))
(check
(bitvector= (begin
(bitvector-field-replace-same! bvec
(make-bitvector 4 1)
1
3)
bvec)
(bitvector 0 1 1 0))
=> #t))
(check
(bitvector=
(bitvector-field-replace (make-bitvector 4 0) (bitvector 1 0 0 0) 1 3)
(bitvector 0 1 0 0))
=> #t)
(let ((bvec (make-bitvector 4 0)))
(check
(bitvector= (begin
(bitvector-field-replace! bvec (make-bitvector 4 1) 1 3)
bvec)
(bitvector 0 1 1 0))
=> #t))
;;; rotate
(check (bitvector= (bitvector-field-rotate (bitvector 1 0 0 1) 1 0 4)
(bitvector 0 0 1 1))
=> #t)
(check (bitvector= (bitvector-field-rotate (bitvector 1 0 0 1) -1 0 4)
(bitvector 1 1 0 0))
=> #t)
(check (bitvector=
(bitvector-field-rotate (bitvector 1 0 0 1 1 0 1 0) 2 2 6)
(bitvector 1 0 1 0 0 1 1 0))
=> #t)
(check (bitvector=
(bitvector-field-rotate (bitvector 1 0 0 1 1 0 1 0) -3 2 6)
(bitvector 1 0 1 1 0 0 1 0))
=> #t)
;;; flip
(check (bitvector= (bitvector-field-flip (bitvector 0 1 0 1) 0 4)
(bitvector 1 0 1 0))
=> #t)
(check (bitvector= (bitvector-field-flip (bitvector 0 1 0 1) 2 4)
(bitvector 0 1 1 0))
=> #t)
(let ((bvec (bitvector 0 1 0 1)))
(check (bitvector= (begin (bitvector-field-flip! bvec 0 4) bvec)
(bitvector 1 0 1 0))
=> #t))
(let ((bvec (bitvector 0 1 0 1)))
(check (bitvector= (begin (bitvector-field-flip! bvec 2 4) bvec)
(bitvector 0 1 1 0))
=> #t))
)
| null | https://raw.githubusercontent.com/shirok/Gauche/ecaf82f72e2e946f62d99ed8febe0df8960d20c4/test/include/test/fields.scm | scheme | replace-same and replace
rotate
flip | (define (check-bit-field-operations)
(print-header "Checking bit field operations...")
(check (bitvector-field-any? (bitvector 0 1 0 0) 0 4) => #t)
(check (bitvector-field-any? (bitvector 0 0 0 0) 0 4) => #f)
(check (bitvector-field-any? (bitvector 0 1 0 0) 1 3) => #t)
(check (bitvector-field-any? (bitvector 0 1 0 0) 2 4) => #f)
(check (bitvector-field-every? (make-bitvector 4 1) 0 4) => #t)
(check (bitvector-field-every? (bitvector 1 1 1 0) 0 4) => #f)
(check (bitvector-field-every? (bitvector 1 1 0 0) 0 2) => #t)
(check (bitvector-field-every? (bitvector 1 1 0 0) 2 4) => #f)
(check (bitvector= (bitvector-field-clear (make-bitvector 4 1) 0 2)
(bitvector 0 0 1 1))
=> #t)
(let ((bvec (make-bitvector 4 1)))
(check (bitvector= (begin (bitvector-field-clear! bvec 0 2) bvec)
(bitvector 0 0 1 1))
=> #t))
(check (bitvector= (bitvector-field-set (make-bitvector 4 0) 0 2)
(bitvector 1 1 0 0))
=> #t)
(let ((bvec (make-bitvector 4 0)))
(check (bitvector= (begin (bitvector-field-set! bvec 0 2) bvec)
(bitvector 1 1 0 0))
=> #t))
(check
(bitvector=
(bitvector-field-replace-same (make-bitvector 4 0)
(make-bitvector 4 1)
1
3)
(bitvector 0 1 1 0))
=> #t)
(let ((bvec (make-bitvector 4 0)))
(check
(bitvector= (begin
(bitvector-field-replace-same! bvec
(make-bitvector 4 1)
1
3)
bvec)
(bitvector 0 1 1 0))
=> #t))
(check
(bitvector=
(bitvector-field-replace (make-bitvector 4 0) (bitvector 1 0 0 0) 1 3)
(bitvector 0 1 0 0))
=> #t)
(let ((bvec (make-bitvector 4 0)))
(check
(bitvector= (begin
(bitvector-field-replace! bvec (make-bitvector 4 1) 1 3)
bvec)
(bitvector 0 1 1 0))
=> #t))
(check (bitvector= (bitvector-field-rotate (bitvector 1 0 0 1) 1 0 4)
(bitvector 0 0 1 1))
=> #t)
(check (bitvector= (bitvector-field-rotate (bitvector 1 0 0 1) -1 0 4)
(bitvector 1 1 0 0))
=> #t)
(check (bitvector=
(bitvector-field-rotate (bitvector 1 0 0 1 1 0 1 0) 2 2 6)
(bitvector 1 0 1 0 0 1 1 0))
=> #t)
(check (bitvector=
(bitvector-field-rotate (bitvector 1 0 0 1 1 0 1 0) -3 2 6)
(bitvector 1 0 1 1 0 0 1 0))
=> #t)
(check (bitvector= (bitvector-field-flip (bitvector 0 1 0 1) 0 4)
(bitvector 1 0 1 0))
=> #t)
(check (bitvector= (bitvector-field-flip (bitvector 0 1 0 1) 2 4)
(bitvector 0 1 1 0))
=> #t)
(let ((bvec (bitvector 0 1 0 1)))
(check (bitvector= (begin (bitvector-field-flip! bvec 0 4) bvec)
(bitvector 1 0 1 0))
=> #t))
(let ((bvec (bitvector 0 1 0 1)))
(check (bitvector= (begin (bitvector-field-flip! bvec 2 4) bvec)
(bitvector 0 1 1 0))
=> #t))
)
|
c7b59218eb22730e2e4a630d32b365f7a35a7cb7963c5b9c4b86f34b9ee8e81a | CSCfi/rems | auth.cljs | (ns rems.auth.auth
(:require [re-frame.core :as rf]
[rems.atoms :as atoms]
[rems.auth.fake :as fake]
[rems.auth.oidc :as oidc]
[rems.guide-util :refer [component-info example]]
[rems.navbar :as nav]
[rems.text :refer [text]]))
(defn login-component []
(let [config @(rf/subscribe [:rems.config/config])
login-component (case (:authentication config)
:oidc (oidc/login-component)
:fake (fake/login-component)
nil)]
[:<>
(text :t.login/title)
(text :t.login/text)
(when login-component
[:div.login-component.w-100.mt-4
login-component])
(text :t.login/alternative-text)
(when-let [alternative-endpoint (:alternative-login-url config)]
[:div.text-center.w-100.mt-4
[atoms/link nil
alternative-endpoint
(text :t.login/alternative)]])]))
(defn guide []
[:div
(component-info oidc/login-component)
(example "oidc login" [oidc/login-component])])
| null | https://raw.githubusercontent.com/CSCfi/rems/ce5a8962d3a88016346e96bae4ae35059e7de75b/src/cljs/rems/auth/auth.cljs | clojure | (ns rems.auth.auth
(:require [re-frame.core :as rf]
[rems.atoms :as atoms]
[rems.auth.fake :as fake]
[rems.auth.oidc :as oidc]
[rems.guide-util :refer [component-info example]]
[rems.navbar :as nav]
[rems.text :refer [text]]))
(defn login-component []
(let [config @(rf/subscribe [:rems.config/config])
login-component (case (:authentication config)
:oidc (oidc/login-component)
:fake (fake/login-component)
nil)]
[:<>
(text :t.login/title)
(text :t.login/text)
(when login-component
[:div.login-component.w-100.mt-4
login-component])
(text :t.login/alternative-text)
(when-let [alternative-endpoint (:alternative-login-url config)]
[:div.text-center.w-100.mt-4
[atoms/link nil
alternative-endpoint
(text :t.login/alternative)]])]))
(defn guide []
[:div
(component-info oidc/login-component)
(example "oidc login" [oidc/login-component])])
| |
4c2d620e389ee9a76a12beb2b1321d37f3c191e58186121d0a9cf81c82e55e94 | rvantonder/hack_parallel | marshal_tools.ml | *
* Copyright ( c ) 2015 , Facebook , Inc.
* All rights reserved .
*
* This source code is licensed under the BSD - style license found in the
* LICENSE file in the " hack " directory of this source tree . An additional grant
* of patent rights can be found in the PATENTS file in the same directory .
*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the "hack" directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
*
* This tool allows for marshaling directly over file descriptors ( instead of
* ocaml " channels " ) to avoid buffering so that we can safely use marshaling
* and together .
*
* The problem :
* Ocaml 's marshaling is done over channels , which have their own internal
* buffer . This means after reading a marshaled object from a channel , the
* FD 's position is not guaranteed to be pointing to the beginning of the
* next marshaled object ( but instead points to the position after the
* buffered read ) . So another process can not receive this FD ( over
* ) to start reading the next object .
*
* The solution :
* Start each message with a fixed - size preamble that describes the
* size of the payload to read . Read precisely that many bytes directly
* from the FD avoiding Ocaml channels entirely .
* This tool allows for marshaling directly over file descriptors (instead of
* ocaml "channels") to avoid buffering so that we can safely use marshaling
* and libancillary together.
*
* The problem:
* Ocaml's marshaling is done over channels, which have their own internal
* buffer. This means after reading a marshaled object from a channel, the
* FD's position is not guaranteed to be pointing to the beginning of the
* next marshaled object (but instead points to the position after the
* buffered read). So another process cannot receive this FD (over
* libancillary) to start reading the next object.
*
* The solution:
* Start each message with a fixed-size preamble that describes the
* size of the payload to read. Read precisely that many bytes directly
* from the FD avoiding Ocaml channels entirely.
*)
exception Invalid_Int_Size_Exception
exception Payload_Size_Too_Large_Exception
exception Malformed_Preamble_Exception
exception Writing_Preamble_Exception
exception Writing_Payload_Exception
exception Reading_Preamble_Exception
exception Reading_Payload_Exception
(* We want to marshal exceptions (or at least their message+stacktrace) over *)
(* the wire. This type ensures that no one will attempt to pattern-match on *)
(* the thing we marshal: 'Values of extensible variant types, for example *)
(* exceptions (of extensible type exn), returned by the unmarhsaller should *)
(* not be pattern-matched over, because unmarshalling does not preserve the *)
(* information required for matching their constructors.' *)
(* -ocaml/libref/Marshal.html *)
type remote_exception_data = {
message : string;
stack : string;
}
let preamble_start_sentinel = '\142'
(** Size in bytes. *)
let preamble_core_size = 4
let expected_preamble_size = preamble_core_size + 1
* Payload size in bytes = 2 ^ 31 - 1 .
let maximum_payload_size = (1 lsl (preamble_core_size * 8)) - 1
let get_preamble_core (size : int) =
We limit payload size to 2 ^ 31 - 1 bytes .
if size >= maximum_payload_size then
raise Payload_Size_Too_Large_Exception;
let rec loop i (remainder: int) acc =
if i < 0 then acc
else loop (i - 1) (remainder / 256)
(Bytes.set acc i (Char.chr (remainder mod 256)); acc) in
loop (preamble_core_size - 1) size (Bytes.create preamble_core_size)
let make_preamble (size : int) =
let preamble_core = get_preamble_core size in
let preamble = Bytes.create (preamble_core_size + 1) in
Bytes.set preamble 0 preamble_start_sentinel;
Bytes.blit preamble_core 0 preamble 1 4;
preamble
let parse_preamble preamble =
if (Bytes.length preamble) <> expected_preamble_size
|| (Bytes.get preamble 0) <> preamble_start_sentinel then
raise Malformed_Preamble_Exception;
let rec loop i acc =
if i >= 5 then acc
else loop (i + 1) ((acc * 256) + (int_of_char (Bytes.get preamble i))) in
loop 1 0
let to_fd_with_preamble fd obj =
let flag_list = [] in
let payload = Marshal.to_bytes obj flag_list in
let size = Bytes.length payload in
let preamble = make_preamble size in
let preamble_bytes_written =
Unix.write fd preamble 0 expected_preamble_size in
if preamble_bytes_written <> expected_preamble_size then
raise Writing_Preamble_Exception;
let bytes_written = Unix.write fd payload 0 size in
if bytes_written <> size then
raise Writing_Payload_Exception;
()
let rec read_payload fd buffer offset to_read =
if to_read = 0 then offset else begin
let bytes_read = Unix.read fd buffer offset to_read in
if bytes_read = 0 then offset else begin
read_payload fd buffer (offset+bytes_read) (to_read-bytes_read)
end
end
let from_fd_with_preamble fd =
let preamble = Bytes.create expected_preamble_size in
let bytes_read = Unix.read fd preamble 0 expected_preamble_size in
if (bytes_read = 0)
(* Unix manpage for read says 0 bytes read indicates end of file. *)
then raise End_of_file
else if (bytes_read <> expected_preamble_size) then
(Printf.eprintf "Error, only read %d bytes for preamble.\n" bytes_read;
raise Reading_Preamble_Exception);
let payload_size = parse_preamble preamble in
let payload = Bytes.create payload_size in
let payload_size_read = read_payload fd payload 0 payload_size in
if (payload_size_read <> payload_size) then
raise Reading_Payload_Exception;
Marshal.from_bytes payload 0
| null | https://raw.githubusercontent.com/rvantonder/hack_parallel/c9d0714785adc100345835c1989f7c657e01f629/src/utils/marshal_tools.ml | ocaml | We want to marshal exceptions (or at least their message+stacktrace) over
the wire. This type ensures that no one will attempt to pattern-match on
the thing we marshal: 'Values of extensible variant types, for example
exceptions (of extensible type exn), returned by the unmarhsaller should
not be pattern-matched over, because unmarshalling does not preserve the
information required for matching their constructors.'
-ocaml/libref/Marshal.html
* Size in bytes.
Unix manpage for read says 0 bytes read indicates end of file. | *
* Copyright ( c ) 2015 , Facebook , Inc.
* All rights reserved .
*
* This source code is licensed under the BSD - style license found in the
* LICENSE file in the " hack " directory of this source tree . An additional grant
* of patent rights can be found in the PATENTS file in the same directory .
*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the "hack" directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
*
* This tool allows for marshaling directly over file descriptors ( instead of
* ocaml " channels " ) to avoid buffering so that we can safely use marshaling
* and together .
*
* The problem :
* Ocaml 's marshaling is done over channels , which have their own internal
* buffer . This means after reading a marshaled object from a channel , the
* FD 's position is not guaranteed to be pointing to the beginning of the
* next marshaled object ( but instead points to the position after the
* buffered read ) . So another process can not receive this FD ( over
* ) to start reading the next object .
*
* The solution :
* Start each message with a fixed - size preamble that describes the
* size of the payload to read . Read precisely that many bytes directly
* from the FD avoiding Ocaml channels entirely .
* This tool allows for marshaling directly over file descriptors (instead of
* ocaml "channels") to avoid buffering so that we can safely use marshaling
* and libancillary together.
*
* The problem:
* Ocaml's marshaling is done over channels, which have their own internal
* buffer. This means after reading a marshaled object from a channel, the
* FD's position is not guaranteed to be pointing to the beginning of the
* next marshaled object (but instead points to the position after the
* buffered read). So another process cannot receive this FD (over
* libancillary) to start reading the next object.
*
* The solution:
* Start each message with a fixed-size preamble that describes the
* size of the payload to read. Read precisely that many bytes directly
* from the FD avoiding Ocaml channels entirely.
*)
exception Invalid_Int_Size_Exception
exception Payload_Size_Too_Large_Exception
exception Malformed_Preamble_Exception
exception Writing_Preamble_Exception
exception Writing_Payload_Exception
exception Reading_Preamble_Exception
exception Reading_Payload_Exception
type remote_exception_data = {
message : string;
stack : string;
}
let preamble_start_sentinel = '\142'
let preamble_core_size = 4
let expected_preamble_size = preamble_core_size + 1
* Payload size in bytes = 2 ^ 31 - 1 .
let maximum_payload_size = (1 lsl (preamble_core_size * 8)) - 1
let get_preamble_core (size : int) =
We limit payload size to 2 ^ 31 - 1 bytes .
if size >= maximum_payload_size then
raise Payload_Size_Too_Large_Exception;
let rec loop i (remainder: int) acc =
if i < 0 then acc
else loop (i - 1) (remainder / 256)
(Bytes.set acc i (Char.chr (remainder mod 256)); acc) in
loop (preamble_core_size - 1) size (Bytes.create preamble_core_size)
let make_preamble (size : int) =
let preamble_core = get_preamble_core size in
let preamble = Bytes.create (preamble_core_size + 1) in
Bytes.set preamble 0 preamble_start_sentinel;
Bytes.blit preamble_core 0 preamble 1 4;
preamble
let parse_preamble preamble =
if (Bytes.length preamble) <> expected_preamble_size
|| (Bytes.get preamble 0) <> preamble_start_sentinel then
raise Malformed_Preamble_Exception;
let rec loop i acc =
if i >= 5 then acc
else loop (i + 1) ((acc * 256) + (int_of_char (Bytes.get preamble i))) in
loop 1 0
let to_fd_with_preamble fd obj =
let flag_list = [] in
let payload = Marshal.to_bytes obj flag_list in
let size = Bytes.length payload in
let preamble = make_preamble size in
let preamble_bytes_written =
Unix.write fd preamble 0 expected_preamble_size in
if preamble_bytes_written <> expected_preamble_size then
raise Writing_Preamble_Exception;
let bytes_written = Unix.write fd payload 0 size in
if bytes_written <> size then
raise Writing_Payload_Exception;
()
let rec read_payload fd buffer offset to_read =
if to_read = 0 then offset else begin
let bytes_read = Unix.read fd buffer offset to_read in
if bytes_read = 0 then offset else begin
read_payload fd buffer (offset+bytes_read) (to_read-bytes_read)
end
end
let from_fd_with_preamble fd =
let preamble = Bytes.create expected_preamble_size in
let bytes_read = Unix.read fd preamble 0 expected_preamble_size in
if (bytes_read = 0)
then raise End_of_file
else if (bytes_read <> expected_preamble_size) then
(Printf.eprintf "Error, only read %d bytes for preamble.\n" bytes_read;
raise Reading_Preamble_Exception);
let payload_size = parse_preamble preamble in
let payload = Bytes.create payload_size in
let payload_size_read = read_payload fd payload 0 payload_size in
if (payload_size_read <> payload_size) then
raise Reading_Payload_Exception;
Marshal.from_bytes payload 0
|
de79c31c05a4065dabd0b40d232c5fbe120ac1b99fb60edbb08ff6f2dbefe7ff | tcsprojects/pgsolver | stratimprlocal.mli | open Paritygame;;
val partially_solve : partial_solver
val solve : global_solver
val register: unit -> unit | null | https://raw.githubusercontent.com/tcsprojects/pgsolver/b0c31a8b367c405baed961385ad645d52f648325/src/solvers/stratimprlocal.mli | ocaml | open Paritygame;;
val partially_solve : partial_solver
val solve : global_solver
val register: unit -> unit | |
dec816cffbb810da33c95a037badacd98542aa286f8a96bd01743e73a0b0b759 | kbaird/consensus | candidate_test.erl | -module('candidate_test').
-author('Kevin C. Baird').
-include_lib("eunit/include/eunit.hrl").
candidate_setup() -> ok.
candidate_teardown(_) -> ok.
candidate_test_() ->
{setup, fun candidate_setup/0,
fun candidate_teardown/1,
[
fun make_case/0,
fun make_partisan_case/0
]
}.
make_case() ->
Cs = [candidate:make(I) || I <- [a, b, c]],
?assertEqual([a, b, c], lists:map(fun candidate:name/1, Cs)).
make_partisan_case() ->
Input = [{a, <<"lib">>}, {b, <<"con">>}, {c, <<"lab">>}],
Cs = [candidate:make(I) || I <- Input],
?assertEqual([a, b, c], lists:map(fun candidate:name/1, Cs)),
?assertEqual([<<"lib">>, <<"con">>, <<"lab">>], lists:map(fun candidate:party/1, Cs)).
%%% PRIVATE FUNCTIONS
| null | https://raw.githubusercontent.com/kbaird/consensus/d3387332009c36d44c9370331c61dd754e71d23d/test/candidate_test.erl | erlang | PRIVATE FUNCTIONS | -module('candidate_test').
-author('Kevin C. Baird').
-include_lib("eunit/include/eunit.hrl").
candidate_setup() -> ok.
candidate_teardown(_) -> ok.
candidate_test_() ->
{setup, fun candidate_setup/0,
fun candidate_teardown/1,
[
fun make_case/0,
fun make_partisan_case/0
]
}.
make_case() ->
Cs = [candidate:make(I) || I <- [a, b, c]],
?assertEqual([a, b, c], lists:map(fun candidate:name/1, Cs)).
make_partisan_case() ->
Input = [{a, <<"lib">>}, {b, <<"con">>}, {c, <<"lab">>}],
Cs = [candidate:make(I) || I <- Input],
?assertEqual([a, b, c], lists:map(fun candidate:name/1, Cs)),
?assertEqual([<<"lib">>, <<"con">>, <<"lab">>], lists:map(fun candidate:party/1, Cs)).
|
1e18b58dce864fb24fb1fc44c533c1e06b9b0f1cb25f6cb7f92bf5977e81efac | CatalaLang/catala | operator.mli | This file is part of the Catala compiler , a specification language for tax
and social benefits computation rules . Copyright ( C ) 2020 , contributor :
< >
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 .
and social benefits computation rules. Copyright (C) 2020 Inria, contributor:
Louis Gesbert <>
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. *)
* { 1 Catala operator utilities }
* Resolving operators from the surface syntax proceeds in three steps :
- During desugaring , the operators may remain untyped ( with [ TAny ] ) or , if
they have an explicit type suffix ( e.g. the [ $ ] for " money " in [ + $ ] ) ,
their operands types are already explicited in the [ EOp ] expression node .
- { ! modules : Shared_ast . Typing } will then enforce these constraints in
addition to the known built - in type for each operator ( e.g.
[ : ' a - > ' a - > ' a ] is n't encoded in the first - order AST types ) .
- Finally , during { ! modules : Scopelang . From_desugared } , these types are
leveraged to resolve the overloaded operators to their concrete ,
monomorphic counterparts
- During desugaring, the operators may remain untyped (with [TAny]) or, if
they have an explicit type suffix (e.g. the [$] for "money" in [+$]),
their operands types are already explicited in the [EOp] expression node.
- {!modules:Shared_ast.Typing} will then enforce these constraints in
addition to the known built-in type for each operator (e.g.
[Eq: 'a -> 'a -> 'a] isn't encoded in the first-order AST types).
- Finally, during {!modules:Scopelang.From_desugared}, these types are
leveraged to resolve the overloaded operators to their concrete,
monomorphic counterparts
*)
open Catala_utils
open Definitions
include module type of Definitions.Op
val equal : ('a1, 'k1) t -> ('a2, 'k2) t -> bool
val compare : ('a1, 'k1) t -> ('a2, 'k2) t -> int
val name : ('a, 'k) t -> string
* Returns the operator name as a valid ident starting with a lowercase
character . This is different from Print.operator which returns operator
symbols , e.g. [ + $ ] .
character. This is different from Print.operator which returns operator
symbols, e.g. [+$]. *)
val kind_dispatch :
polymorphic:((_ any, polymorphic) t -> 'b) ->
monomorphic:((_ any, monomorphic) t -> 'b) ->
?overloaded:((desugared, overloaded) t -> 'b) ->
?resolved:(([< scopelang | dcalc | lcalc ], resolved) t -> 'b) ->
('a, 'k) t ->
'b
* Calls one of the supplied functions depending on the kind of the operator
val translate :
([< scopelang | dcalc | lcalc ], 'k) t ->
([< scopelang | dcalc | lcalc ], 'k) t
(** An identity function that allows translating an operator between different
passes that don't change operator types *)
* { 2 Getting the types of operators }
val monomorphic_type : ('a any, monomorphic) t Marked.pos -> typ
val resolved_type :
([< scopelang | dcalc | lcalc ], resolved) t Marked.pos -> typ
val overload_type :
decl_ctx -> (desugared, overloaded) t Marked.pos -> typ list -> typ
(** The type for typing overloads is different since the types of the operands
are required in advance.
@raise a detailed user error if no matching operator can be found *)
(** Polymorphic operators are typed directly within [Typing], since their types
may contain type variables that can't be expressed outside of it*)
* { 2 Overload handling }
val resolve_overload :
decl_ctx ->
(desugared, overloaded) t Marked.pos ->
typ list ->
([< scopelang | dcalc | lcalc ], resolved) t * [ `Straight | `Reversed ]
(** Some overloads are sugar for an operation with reversed operands, e.g.
[TRat * TMoney] is using [mult_mon_rat]. [`Reversed] is returned to signify
this case. *)
| null | https://raw.githubusercontent.com/CatalaLang/catala/87cb8f95b879f1a64cb3f52d84020960a0492a42/compiler/shared_ast/operator.mli | ocaml | * An identity function that allows translating an operator between different
passes that don't change operator types
* The type for typing overloads is different since the types of the operands
are required in advance.
@raise a detailed user error if no matching operator can be found
* Polymorphic operators are typed directly within [Typing], since their types
may contain type variables that can't be expressed outside of it
* Some overloads are sugar for an operation with reversed operands, e.g.
[TRat * TMoney] is using [mult_mon_rat]. [`Reversed] is returned to signify
this case. | This file is part of the Catala compiler , a specification language for tax
and social benefits computation rules . Copyright ( C ) 2020 , contributor :
< >
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 .
and social benefits computation rules. Copyright (C) 2020 Inria, contributor:
Louis Gesbert <>
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. *)
* { 1 Catala operator utilities }
* Resolving operators from the surface syntax proceeds in three steps :
- During desugaring , the operators may remain untyped ( with [ TAny ] ) or , if
they have an explicit type suffix ( e.g. the [ $ ] for " money " in [ + $ ] ) ,
their operands types are already explicited in the [ EOp ] expression node .
- { ! modules : Shared_ast . Typing } will then enforce these constraints in
addition to the known built - in type for each operator ( e.g.
[ : ' a - > ' a - > ' a ] is n't encoded in the first - order AST types ) .
- Finally , during { ! modules : Scopelang . From_desugared } , these types are
leveraged to resolve the overloaded operators to their concrete ,
monomorphic counterparts
- During desugaring, the operators may remain untyped (with [TAny]) or, if
they have an explicit type suffix (e.g. the [$] for "money" in [+$]),
their operands types are already explicited in the [EOp] expression node.
- {!modules:Shared_ast.Typing} will then enforce these constraints in
addition to the known built-in type for each operator (e.g.
[Eq: 'a -> 'a -> 'a] isn't encoded in the first-order AST types).
- Finally, during {!modules:Scopelang.From_desugared}, these types are
leveraged to resolve the overloaded operators to their concrete,
monomorphic counterparts
*)
open Catala_utils
open Definitions
include module type of Definitions.Op
val equal : ('a1, 'k1) t -> ('a2, 'k2) t -> bool
val compare : ('a1, 'k1) t -> ('a2, 'k2) t -> int
val name : ('a, 'k) t -> string
* Returns the operator name as a valid ident starting with a lowercase
character . This is different from Print.operator which returns operator
symbols , e.g. [ + $ ] .
character. This is different from Print.operator which returns operator
symbols, e.g. [+$]. *)
val kind_dispatch :
polymorphic:((_ any, polymorphic) t -> 'b) ->
monomorphic:((_ any, monomorphic) t -> 'b) ->
?overloaded:((desugared, overloaded) t -> 'b) ->
?resolved:(([< scopelang | dcalc | lcalc ], resolved) t -> 'b) ->
('a, 'k) t ->
'b
* Calls one of the supplied functions depending on the kind of the operator
val translate :
([< scopelang | dcalc | lcalc ], 'k) t ->
([< scopelang | dcalc | lcalc ], 'k) t
* { 2 Getting the types of operators }
val monomorphic_type : ('a any, monomorphic) t Marked.pos -> typ
val resolved_type :
([< scopelang | dcalc | lcalc ], resolved) t Marked.pos -> typ
val overload_type :
decl_ctx -> (desugared, overloaded) t Marked.pos -> typ list -> typ
* { 2 Overload handling }
val resolve_overload :
decl_ctx ->
(desugared, overloaded) t Marked.pos ->
typ list ->
([< scopelang | dcalc | lcalc ], resolved) t * [ `Straight | `Reversed ]
|
59f9b5d26444ccd067d2c29fd9a3114fe95096ea99d28f59ee1e294bcc18272e | ppaml-op3/insomnia | Types.hs | # LANGUAGE
MultiParamTypeClasses ,
FlexibleInstances , FlexibleContexts ,
DeriveDataTypeable , DeriveGeneric
#
MultiParamTypeClasses,
FlexibleInstances, FlexibleContexts,
DeriveDataTypeable, DeriveGeneric
#-}
module Insomnia.Types where
import Control.Applicative
import Control.Lens
import Control.Monad (liftM, zipWithM_)
import Data.Function (on)
import qualified Data.Map as M
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Typeable(Typeable)
import Data.Format (Format(..))
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless
import qualified Unbound.Generics.LocallyNameless.Unsafe as UU
import Insomnia.Identifier
import Insomnia.Common.Literal
import {-# SOURCE #-} Insomnia.ModuleType (ModuleType)
import Insomnia.Unify (UVar, Unifiable(..),
HasUVars(..),
Partial(..),
MonadUnify(..),
MonadUnificationExcept(..),
UnificationFailure(..))
type TyVar = Name Type
type KindedTVar = (TyVar, Kind)
type Nat = Integer
TODO
data Kind = KType -- ^ the kind of types
-- | KROW -- ^ the kind ROW of rows. users can't write it directly
| KArr !Kind !Kind
deriving (Show, Typeable, Generic)
infixr 6 `KArr`
-- | A local type constructor name. These are similar to type variables, except they
-- are substituted by global type paths instead of by arbitrary types.
type TyConName = Name TypeConstructor
-- | A type path selects a type from a model named by field
data TypePath = TypePath Path Field
deriving (Show, Eq, Ord, Typeable, Generic)
-- | A type constructor is either local to the current model, or it is
-- global.
data TypeConstructor =
TCLocal TyConName
| TCGlobal TypePath
deriving (Show, Eq, Typeable, Generic)
instance Ord TypeConstructor where
compare tc1 tc2 =
case (tc1, tc2) of
(TCLocal n1, TCLocal n2) -> compare n1 n2
(TCLocal {}, TCGlobal {}) -> LT
(TCGlobal {}, TCLocal {}) -> GT
(TCGlobal p1, TCGlobal p2) -> compare p1 p2
-- | The types include type variables (which stand for types), unification
-- variables, type constructors, annotted kinds, type applications,
-- universally quantified types and record types.
data Type = TV TyVar
| TUVar (UVar Kind Type) -- invariant: unification variables should be fully applied -- XXX what does this mean? ak-20150825
| TC !TypeConstructor
| TAnn Type !Kind
| TApp Type Type
| TForall (Bind (TyVar, Kind) Type)
| TRecord Row
first class modules of the given module type
deriving (Show, Typeable, Generic)
infixl 6 `TApp`
-- | A label identifies a component of a row.
newtype Label = Label {labelName :: String}
deriving (Show, Eq, Ord, Typeable, Generic)
-- | Rows associate a set of types with a set of labels. For now this
-- is syntactically separate from other types and we don't have row
-- variables, so this is really just plain old non-extensible records.
data Row = Row [(Label, Type)]
deriving (Show, Typeable, Generic)
-- | iterate kind arrow construction
@kArrs [ k1 , ... kN ] = k1 ` KArr ` k2 ` KArr ` ... ` KArr ` kN ` kArr ` kcod@
kArrs :: [Kind] -> Kind -> Kind
kArrs [] kcod = kcod
kArrs (kdom:ks) kcod = kdom `KArr` kArrs ks kcod
-- | iterate type application
@tApps t0 [ t1 , ... , tN ] = t0 ` TApp ` t1 ` TApp ` ... ` TApp ` tN
tApps :: Type -> [Type] -> Type
tApps t0 [] = t0
tApps t0 (t1:ts) = tApps (TApp t0 t1) ts
tForalls :: [(TyVar, Kind)] -> Type -> Type
tForalls [] = id
tForalls (tvk:tvks) = TForall . bind tvk . tForalls tvks
-- | Sort the labels of a row into a canonical order
canonicalOrderRowLabels :: [(Label, a)] -> [(Label, a)]
canonicalOrderRowLabels = sortBy (comparing fst)
-- Formatted output
instance Format Kind
instance Format Type
-- Alpha equivalence
instance Alpha Label
instance Alpha TypePath
instance Alpha TypeConstructor
instance Alpha Type
instance Alpha Kind
instance Alpha Row
instance Eq Type where
(==) = aeq
-- Substitution
-- Capture avoiding substitution of type variables in types and terms.
instance Subst Type Type where
isvar (TV v) = Just (SubstName v)
isvar _ = Nothing
instance Subst Type Row
instance Subst Type Label where
subst _ _ = id
substs _ = id
instance Subst Type TypePath where
subst _ _ = id
substs _ = id
instance Subst Type Literal where
subst _ _ = id
substs _ = id
instance Subst Type Path where
subst _ _ = id
substs _ = id
instance Subst Type TypeConstructor where
subst _ _ = id
substs _ = id
instance Subst Type Kind where
subst _ _ = id
substs _ = id
-- unification variables are opaque boxes that can't be substituted into.
instance Subst Type (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst Type SigPath where
subst _ _ = id
substs _ = id
instance Subst SigPath Kind where
subst _ _ = id
substs _ = id
instance Subst Path Kind where
subst _ _ = id
substs _ = id
instance Subst Path Label where
subst _ _ = id
substs _ = id
instance Subst SigPath Type
instance Subst SigPath TypePath where
subst _ _ = id
substs _ = id
instance Subst SigPath Row
instance Subst SigPath Label where
subst _ _ = id
substs _ = id
instance Subst SigPath TypeConstructor
instance Subst SigPath (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst Path TypePath
instance Subst Path TypeConstructor
instance Subst Path Type
instance Subst Path Row
instance Subst TypeConstructor TypeConstructor where
isvar (TCLocal c) = Just (SubstName c)
isvar _ = Nothing
instance Subst TypeConstructor TypePath where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Path where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor SigPath where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Literal where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Label where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Kind where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Type
instance Subst TypeConstructor Row
Unification
instance Partial Kind Type where
_UVar = let
pick (TUVar u) = Just u
pick _ = Nothing
in prism' TUVar pick
instance HasUVars Type Type where
allUVars f t =
case t of
TV {} -> pure t
TUVar {} -> f t
TC {} -> pure t
TAnn t1 k -> TAnn <$> allUVars f t1 <*> pure k
TApp t1 t2 -> TApp <$> allUVars f t1 <*> allUVars f t2
TPack {} -> pure t
TForall bnd -> let
(vk, t1) = UU.unsafeUnbind bnd
in (TForall . bind vk) <$> allUVars f t1
TRecord row -> TRecord <$> allUVars f row
instance HasUVars Type Row where
allUVars f (Row ts) = Row <$> traverseOf (traverse . _2 . allUVars) f ts
-- | Make a fresh unification variable
freshUVarT :: MonadUnify e Kind Type m => Kind -> m Type
freshUVarT k = liftM TUVar (unconstrained k)
-- | Construct a fresh type expression composed of a unification var
-- of the given kind applied to sufficiently many ground arguments
-- such that the whole type expression has of kind ⋆.
--
-- @
-- ⌞⋆⌟ = u - u fresh
⌞ k1 → = apply u ( map ⌞ · ⌟ ks ) - u fresh
-- @
-- for example: @⌞a -> (b -> ⋆)⌟ = (u·⌞a⌟)·⌞b⌟@
groundUnificationVar :: MonadUnify TypeUnificationError Kind Type m => Kind -> m Type
groundUnificationVar = \ k -> do
tu <- freshUVarT k
go k tu
where
go KType thead = return thead
go (KArr kdom kcod) thead = do
targ <- groundUnificationVar kdom
go kcod (thead `TApp` targ)
data TypeUnificationError =
the two given types could not be simplified under the given constraints
the two given rows could not be unifified because they have different labels
the two given module types are not equivalent
class MonadTypeAlias m where
expandTypeAlias :: TypeConstructor -> m (Maybe Type)
instance (MonadUnify TypeUnificationError Kind Type m,
MonadUnificationExcept TypeUnificationError Kind Type m,
MonadTypeAlias m,
LFresh m)
=> Unifiable Kind Type TypeUnificationError m Type where
t1 =?= t2 =
case (t1, t2) of
(TForall bnd1, TForall bnd2) ->
lunbind2 bnd1 bnd2 $ \opn ->
case opn of
Just ((_, _), t1', (_, _), t2') ->
t1' =?= t2'
Nothing -> do
constraintMap <- reflectCollectedConstraints
throwUnificationFailure
$ Unsimplifiable (SimplificationFail constraintMap t1 t2)
-- (TForall bnd1, _) ->
-- lunbind bnd1 $ \ ((v1, _), t1_) -> do
-- tu1 <- freshUVarT
-- let t1' = subst v1 tu1 t1_
-- t1' =?= t2
-- (_, TForall {}) -> t2 =?= t1
(TRecord row1, TRecord row2) -> row1 =?= row2
(TPack modTy1, TPack modTy2) ->
if aeq modTy1 modTy2
then return ()
else throwUnificationFailure $ Unsimplifiable (PackedModuleTypesDifferFail modTy1 modTy2)
(TUVar u1, TUVar u2) | u1 == u2 -> return ()
(TUVar u1, _) -> u1 -?= t2
(_, TUVar u2) -> u2 -?= t1
(TAnn t1' _, TAnn t2' _) -> t1' =?= t2'
(TAnn t1' _, _) -> t1' =?= t2
(_, TAnn t2' _) -> t1 =?= t2'
(TV v1, TV v2) | v1 == v2 -> return ()
(TC c1, TC c2) ->
if c1 == c2
then return ()
else do
mexp1 <- expandTypeAlias c1
mexp2 <- expandTypeAlias c2
case (mexp1, mexp2) of
(Just t1', Just t2') -> t1' =?= t2'
(Just t1', Nothing) -> t1' =?= t2
(Nothing, Just t2') -> t1 =?= t2'
(Nothing, Nothing) -> failedToUnify
(TC c1, _) -> do
mexp <- expandTypeAlias c1
case mexp of
Nothing -> failedToUnify
Just t1' -> t1' =?= t2
(_, TC _c2) -> t2 =?= t1
(TApp t11 t12, TApp t21 t22) -> do
t11 =?= t21
t12 =?= t22
_ -> failedToUnify
where
failedToUnify = do
constraintMap <- reflectCollectedConstraints
throwUnificationFailure
$ Unsimplifiable (SimplificationFail constraintMap t1 t2)
instance (MonadUnify TypeUnificationError Kind Type m,
MonadUnificationExcept TypeUnificationError Kind Type m,
MonadTypeAlias m,
LFresh m)
=> Unifiable Kind Type TypeUnificationError m Row where
r1@(Row ls1_) =?= r2@(Row ls2_) =
let ls1 = canonicalOrderRowLabels ls1_
ls2 = canonicalOrderRowLabels ls2_
in if map fst ls1 == map fst ls2
then zipWithM_ ((=?=) `on` snd) ls1 ls2
else throwUnificationFailure $ Unsimplifiable (RowLabelsDifferFail r1 r2)
instance Plated Type where
plate _ (t@TUVar {}) = pure t
plate _ (t@TV {}) = pure t
plate _ (t@TC {}) = pure t
plate f (TPack modTy) = TPack <$> traverseTypes f modTy
plate f (TForall bnd) =
let (tvk,t) = UU.unsafeUnbind bnd
in (TForall . bind tvk) <$> f t
plate f (TAnn t k) = TAnn <$> f t <*> pure k
plate f (TApp t1 t2) = TApp <$> f t1 <*> f t2
plate f (TRecord ts) = TRecord <$> traverseTypes f ts
-- | Traverse the types in the given container
class TraverseTypes s t where
traverseTypes :: Traversal s t Type Type
instance TraverseTypes Row Row where
traverseTypes f (Row ts) = Row <$> traverseOf (traverse . _2) f ts
instance TraverseTypes a b => TraverseTypes (Maybe a) (Maybe b) where
traverseTypes _ Nothing = pure Nothing
traverseTypes f (Just a) = Just <$> traverseTypes f a
instance TraverseTypes a b => TraverseTypes [a] [b] where
traverseTypes _ [] = pure []
traverseTypes f (x:xs) = (:) <$> traverseTypes f x <*> traverseTypes f xs
transformEveryTypeM :: (TraverseTypes a a, Plated a, Monad m) => (Type -> m Type) -> a -> m a
transformEveryTypeM f = transformM (transformMOn traverseTypes f)
| null | https://raw.githubusercontent.com/ppaml-op3/insomnia/5fc6eb1d554e8853d2fc929a957c7edce9e8867d/src/Insomnia/Types.hs | haskell | # SOURCE #
^ the kind of types
| KROW -- ^ the kind ROW of rows. users can't write it directly
| A local type constructor name. These are similar to type variables, except they
are substituted by global type paths instead of by arbitrary types.
| A type path selects a type from a model named by field
| A type constructor is either local to the current model, or it is
global.
| The types include type variables (which stand for types), unification
variables, type constructors, annotted kinds, type applications,
universally quantified types and record types.
invariant: unification variables should be fully applied -- XXX what does this mean? ak-20150825
| A label identifies a component of a row.
| Rows associate a set of types with a set of labels. For now this
is syntactically separate from other types and we don't have row
variables, so this is really just plain old non-extensible records.
| iterate kind arrow construction
| iterate type application
| Sort the labels of a row into a canonical order
Formatted output
Alpha equivalence
Substitution
Capture avoiding substitution of type variables in types and terms.
unification variables are opaque boxes that can't be substituted into.
| Make a fresh unification variable
| Construct a fresh type expression composed of a unification var
of the given kind applied to sufficiently many ground arguments
such that the whole type expression has of kind ⋆.
@
⌞⋆⌟ = u - u fresh
@
for example: @⌞a -> (b -> ⋆)⌟ = (u·⌞a⌟)·⌞b⌟@
(TForall bnd1, _) ->
lunbind bnd1 $ \ ((v1, _), t1_) -> do
tu1 <- freshUVarT
let t1' = subst v1 tu1 t1_
t1' =?= t2
(_, TForall {}) -> t2 =?= t1
| Traverse the types in the given container | # LANGUAGE
MultiParamTypeClasses ,
FlexibleInstances , FlexibleContexts ,
DeriveDataTypeable , DeriveGeneric
#
MultiParamTypeClasses,
FlexibleInstances, FlexibleContexts,
DeriveDataTypeable, DeriveGeneric
#-}
module Insomnia.Types where
import Control.Applicative
import Control.Lens
import Control.Monad (liftM, zipWithM_)
import Data.Function (on)
import qualified Data.Map as M
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Typeable(Typeable)
import Data.Format (Format(..))
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless
import qualified Unbound.Generics.LocallyNameless.Unsafe as UU
import Insomnia.Identifier
import Insomnia.Common.Literal
import Insomnia.Unify (UVar, Unifiable(..),
HasUVars(..),
Partial(..),
MonadUnify(..),
MonadUnificationExcept(..),
UnificationFailure(..))
type TyVar = Name Type
type KindedTVar = (TyVar, Kind)
type Nat = Integer
TODO
| KArr !Kind !Kind
deriving (Show, Typeable, Generic)
infixr 6 `KArr`
type TyConName = Name TypeConstructor
data TypePath = TypePath Path Field
deriving (Show, Eq, Ord, Typeable, Generic)
data TypeConstructor =
TCLocal TyConName
| TCGlobal TypePath
deriving (Show, Eq, Typeable, Generic)
instance Ord TypeConstructor where
compare tc1 tc2 =
case (tc1, tc2) of
(TCLocal n1, TCLocal n2) -> compare n1 n2
(TCLocal {}, TCGlobal {}) -> LT
(TCGlobal {}, TCLocal {}) -> GT
(TCGlobal p1, TCGlobal p2) -> compare p1 p2
data Type = TV TyVar
| TC !TypeConstructor
| TAnn Type !Kind
| TApp Type Type
| TForall (Bind (TyVar, Kind) Type)
| TRecord Row
first class modules of the given module type
deriving (Show, Typeable, Generic)
infixl 6 `TApp`
newtype Label = Label {labelName :: String}
deriving (Show, Eq, Ord, Typeable, Generic)
data Row = Row [(Label, Type)]
deriving (Show, Typeable, Generic)
@kArrs [ k1 , ... kN ] = k1 ` KArr ` k2 ` KArr ` ... ` KArr ` kN ` kArr ` kcod@
kArrs :: [Kind] -> Kind -> Kind
kArrs [] kcod = kcod
kArrs (kdom:ks) kcod = kdom `KArr` kArrs ks kcod
@tApps t0 [ t1 , ... , tN ] = t0 ` TApp ` t1 ` TApp ` ... ` TApp ` tN
tApps :: Type -> [Type] -> Type
tApps t0 [] = t0
tApps t0 (t1:ts) = tApps (TApp t0 t1) ts
tForalls :: [(TyVar, Kind)] -> Type -> Type
tForalls [] = id
tForalls (tvk:tvks) = TForall . bind tvk . tForalls tvks
canonicalOrderRowLabels :: [(Label, a)] -> [(Label, a)]
canonicalOrderRowLabels = sortBy (comparing fst)
instance Format Kind
instance Format Type
instance Alpha Label
instance Alpha TypePath
instance Alpha TypeConstructor
instance Alpha Type
instance Alpha Kind
instance Alpha Row
instance Eq Type where
(==) = aeq
instance Subst Type Type where
isvar (TV v) = Just (SubstName v)
isvar _ = Nothing
instance Subst Type Row
instance Subst Type Label where
subst _ _ = id
substs _ = id
instance Subst Type TypePath where
subst _ _ = id
substs _ = id
instance Subst Type Literal where
subst _ _ = id
substs _ = id
instance Subst Type Path where
subst _ _ = id
substs _ = id
instance Subst Type TypeConstructor where
subst _ _ = id
substs _ = id
instance Subst Type Kind where
subst _ _ = id
substs _ = id
instance Subst Type (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst Type SigPath where
subst _ _ = id
substs _ = id
instance Subst SigPath Kind where
subst _ _ = id
substs _ = id
instance Subst Path Kind where
subst _ _ = id
substs _ = id
instance Subst Path Label where
subst _ _ = id
substs _ = id
instance Subst SigPath Type
instance Subst SigPath TypePath where
subst _ _ = id
substs _ = id
instance Subst SigPath Row
instance Subst SigPath Label where
subst _ _ = id
substs _ = id
instance Subst SigPath TypeConstructor
instance Subst SigPath (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst Path TypePath
instance Subst Path TypeConstructor
instance Subst Path Type
instance Subst Path Row
instance Subst TypeConstructor TypeConstructor where
isvar (TCLocal c) = Just (SubstName c)
isvar _ = Nothing
instance Subst TypeConstructor TypePath where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Path where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor SigPath where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Literal where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor (UVar w a) where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Label where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Kind where
subst _ _ = id
substs _ = id
instance Subst TypeConstructor Type
instance Subst TypeConstructor Row
Unification
instance Partial Kind Type where
_UVar = let
pick (TUVar u) = Just u
pick _ = Nothing
in prism' TUVar pick
instance HasUVars Type Type where
allUVars f t =
case t of
TV {} -> pure t
TUVar {} -> f t
TC {} -> pure t
TAnn t1 k -> TAnn <$> allUVars f t1 <*> pure k
TApp t1 t2 -> TApp <$> allUVars f t1 <*> allUVars f t2
TPack {} -> pure t
TForall bnd -> let
(vk, t1) = UU.unsafeUnbind bnd
in (TForall . bind vk) <$> allUVars f t1
TRecord row -> TRecord <$> allUVars f row
instance HasUVars Type Row where
allUVars f (Row ts) = Row <$> traverseOf (traverse . _2 . allUVars) f ts
freshUVarT :: MonadUnify e Kind Type m => Kind -> m Type
freshUVarT k = liftM TUVar (unconstrained k)
⌞ k1 → = apply u ( map ⌞ · ⌟ ks ) - u fresh
groundUnificationVar :: MonadUnify TypeUnificationError Kind Type m => Kind -> m Type
groundUnificationVar = \ k -> do
tu <- freshUVarT k
go k tu
where
go KType thead = return thead
go (KArr kdom kcod) thead = do
targ <- groundUnificationVar kdom
go kcod (thead `TApp` targ)
data TypeUnificationError =
the two given types could not be simplified under the given constraints
the two given rows could not be unifified because they have different labels
the two given module types are not equivalent
class MonadTypeAlias m where
expandTypeAlias :: TypeConstructor -> m (Maybe Type)
instance (MonadUnify TypeUnificationError Kind Type m,
MonadUnificationExcept TypeUnificationError Kind Type m,
MonadTypeAlias m,
LFresh m)
=> Unifiable Kind Type TypeUnificationError m Type where
t1 =?= t2 =
case (t1, t2) of
(TForall bnd1, TForall bnd2) ->
lunbind2 bnd1 bnd2 $ \opn ->
case opn of
Just ((_, _), t1', (_, _), t2') ->
t1' =?= t2'
Nothing -> do
constraintMap <- reflectCollectedConstraints
throwUnificationFailure
$ Unsimplifiable (SimplificationFail constraintMap t1 t2)
(TRecord row1, TRecord row2) -> row1 =?= row2
(TPack modTy1, TPack modTy2) ->
if aeq modTy1 modTy2
then return ()
else throwUnificationFailure $ Unsimplifiable (PackedModuleTypesDifferFail modTy1 modTy2)
(TUVar u1, TUVar u2) | u1 == u2 -> return ()
(TUVar u1, _) -> u1 -?= t2
(_, TUVar u2) -> u2 -?= t1
(TAnn t1' _, TAnn t2' _) -> t1' =?= t2'
(TAnn t1' _, _) -> t1' =?= t2
(_, TAnn t2' _) -> t1 =?= t2'
(TV v1, TV v2) | v1 == v2 -> return ()
(TC c1, TC c2) ->
if c1 == c2
then return ()
else do
mexp1 <- expandTypeAlias c1
mexp2 <- expandTypeAlias c2
case (mexp1, mexp2) of
(Just t1', Just t2') -> t1' =?= t2'
(Just t1', Nothing) -> t1' =?= t2
(Nothing, Just t2') -> t1 =?= t2'
(Nothing, Nothing) -> failedToUnify
(TC c1, _) -> do
mexp <- expandTypeAlias c1
case mexp of
Nothing -> failedToUnify
Just t1' -> t1' =?= t2
(_, TC _c2) -> t2 =?= t1
(TApp t11 t12, TApp t21 t22) -> do
t11 =?= t21
t12 =?= t22
_ -> failedToUnify
where
failedToUnify = do
constraintMap <- reflectCollectedConstraints
throwUnificationFailure
$ Unsimplifiable (SimplificationFail constraintMap t1 t2)
instance (MonadUnify TypeUnificationError Kind Type m,
MonadUnificationExcept TypeUnificationError Kind Type m,
MonadTypeAlias m,
LFresh m)
=> Unifiable Kind Type TypeUnificationError m Row where
r1@(Row ls1_) =?= r2@(Row ls2_) =
let ls1 = canonicalOrderRowLabels ls1_
ls2 = canonicalOrderRowLabels ls2_
in if map fst ls1 == map fst ls2
then zipWithM_ ((=?=) `on` snd) ls1 ls2
else throwUnificationFailure $ Unsimplifiable (RowLabelsDifferFail r1 r2)
instance Plated Type where
plate _ (t@TUVar {}) = pure t
plate _ (t@TV {}) = pure t
plate _ (t@TC {}) = pure t
plate f (TPack modTy) = TPack <$> traverseTypes f modTy
plate f (TForall bnd) =
let (tvk,t) = UU.unsafeUnbind bnd
in (TForall . bind tvk) <$> f t
plate f (TAnn t k) = TAnn <$> f t <*> pure k
plate f (TApp t1 t2) = TApp <$> f t1 <*> f t2
plate f (TRecord ts) = TRecord <$> traverseTypes f ts
class TraverseTypes s t where
traverseTypes :: Traversal s t Type Type
instance TraverseTypes Row Row where
traverseTypes f (Row ts) = Row <$> traverseOf (traverse . _2) f ts
instance TraverseTypes a b => TraverseTypes (Maybe a) (Maybe b) where
traverseTypes _ Nothing = pure Nothing
traverseTypes f (Just a) = Just <$> traverseTypes f a
instance TraverseTypes a b => TraverseTypes [a] [b] where
traverseTypes _ [] = pure []
traverseTypes f (x:xs) = (:) <$> traverseTypes f x <*> traverseTypes f xs
transformEveryTypeM :: (TraverseTypes a a, Plated a, Monad m) => (Type -> m Type) -> a -> m a
transformEveryTypeM f = transformM (transformMOn traverseTypes f)
|
022974248b1e574a0a0d55e995bed6e5119dfae2051768e188c7384d96f8fdce | binghe/fm-plugin-tools | packages.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
$ Header : /usr / local / cvsrep / regex - plugin / packages.lisp , v 1.8 2008/01/07 07:36:02 edi Exp $
Copyright ( c ) 2006 - 2008 , Dr. and Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage :regex-plugin
(:use :cl :capi :fm-plugin-tools)
(:add-use-defaults t))
| null | https://raw.githubusercontent.com/binghe/fm-plugin-tools/ddb970a38b9a6fb44e9fb49a3ef74a4d17ac8738/regex-plugin/packages.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| $ Header : /usr / local / cvsrep / regex - plugin / packages.lisp , v 1.8 2008/01/07 07:36:02 edi Exp $
Copyright ( c ) 2006 - 2008 , Dr. and Dr. . All rights reserved .
OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :cl-user)
(defpackage :regex-plugin
(:use :cl :capi :fm-plugin-tools)
(:add-use-defaults t))
|
ee4cde2ead335cd63a1e9e087878cb13b33dfd58eea07da37f108ee84d24fe84 | clojure-interop/aws-api | core.clj | (ns core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.amazonaws.services.securitytoken.core])
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.securitytoken/src/core.clj | clojure | (ns core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.amazonaws.services.securitytoken.core])
| |
634be6a614ce1c24fa2e404c4a90194d4553cce7e73f6c0a9ac6d411b9765436 | GaloisInc/llvm-verifier | Errors.hs | |
Module : $ Header$
Description : Error path and error handling tests
License : BSD3
Stability : provisional
Point - of - contact : atomb
Module : $Header$
Description : Error path and error handling tests
License : BSD3
Stability : provisional
Point-of-contact : atomb
-}
module Tests.Errors (errorTests) where
import Test.Tasty
import Tests.Common
errorTests :: [TestTree]
errorTests =
[ lssTestAll "ctests/test-error-paths-all" [] (Just 2) AllPathsErr
, lssTestAll "ctests/test-error-paths-some" [] (Just 1) (RV 0)
, lssTestAll "ctests/test-error-paths-some-more" [] (Just 2) (RV 0)
, lssTestAll "ctests/test-error-paths-bad-mem-trivial" [] (Just 1) AllPathsErr
, lssTestAll "ctests/test-error-paths-bad-mem-diverge" [] (Just 1) (RV 1)
5 second local timeout
withVerbModel "ctests/test-error-paths-bad-mem-symsize.bc" $ \v getmdl ->
testGroup "ctests/test-error-paths-bad-mem-symsize"
[ runLssTest "buddy model" v createBuddyModel getmdl [] (Just 1) (RV 1)
, runLssTest "dag model" v createDagModel getmdl [] Nothing (RV 1)
-- TODO: the following times out, but it's not critical that
-- we fix that soon, so let's ignore it for now.
, runLssTest " SAW model " v createSAWModel [ ] ( Just 1 ) ( RV 1 )
]
]
| null | https://raw.githubusercontent.com/GaloisInc/llvm-verifier/d97ee6d2e731f48db833cc451326e737e1e39963/test/src/Tests/Errors.hs | haskell | TODO: the following times out, but it's not critical that
we fix that soon, so let's ignore it for now. | |
Module : $ Header$
Description : Error path and error handling tests
License : BSD3
Stability : provisional
Point - of - contact : atomb
Module : $Header$
Description : Error path and error handling tests
License : BSD3
Stability : provisional
Point-of-contact : atomb
-}
module Tests.Errors (errorTests) where
import Test.Tasty
import Tests.Common
errorTests :: [TestTree]
errorTests =
[ lssTestAll "ctests/test-error-paths-all" [] (Just 2) AllPathsErr
, lssTestAll "ctests/test-error-paths-some" [] (Just 1) (RV 0)
, lssTestAll "ctests/test-error-paths-some-more" [] (Just 2) (RV 0)
, lssTestAll "ctests/test-error-paths-bad-mem-trivial" [] (Just 1) AllPathsErr
, lssTestAll "ctests/test-error-paths-bad-mem-diverge" [] (Just 1) (RV 1)
5 second local timeout
withVerbModel "ctests/test-error-paths-bad-mem-symsize.bc" $ \v getmdl ->
testGroup "ctests/test-error-paths-bad-mem-symsize"
[ runLssTest "buddy model" v createBuddyModel getmdl [] (Just 1) (RV 1)
, runLssTest "dag model" v createDagModel getmdl [] Nothing (RV 1)
, runLssTest " SAW model " v createSAWModel [ ] ( Just 1 ) ( RV 1 )
]
]
|
d63ab28b894e5c9e195ababea63f0d1d9405e20f0cf598f6a0061502144919c4 | reflex-frp/reflex-vty | CPU.hs | {-|
Description: A CPU usage indicator
-}
module Example.CPU where
import Control.Exception
import Control.Monad.Fix
import Control.Monad.IO.Class
import Data.Ratio
import Data.Time
import Data.Word
import qualified Data.Text as T
import qualified Graphics.Vty as V
import Text.Printf
import Reflex
import Reflex.Vty
-- | Each constructor represents a cpu statistic column as presented in @/proc/stat@
data CpuStat
= CpuStat_User
| CpuStat_Nice
| CpuStat_System
| CpuStat_Idle
| CpuStat_Iowait
| CpuStat_Irq
| CpuStat_Softirq
| CpuStat_Steal
| CpuStat_Guest
| CpuStat_GuestNice
deriving (Show, Read, Eq, Ord, Enum, Bounded)
-- | Read @/proc/stat@
getCpuStat :: IO (Maybe (CpuStat -> Word64))
getCpuStat = do
s <- readFile "/proc/stat"
_ <- evaluate $ length s -- Make readFile strict
pure $ do
cpuSummaryLine : _ <- pure $ lines s
[user, nice, system, idle, iowait, irq, softirq, steal, guest, guestNice] <- pure $ map read $ words $ drop 4 cpuSummaryLine
pure $ \case
CpuStat_User -> user
CpuStat_Nice -> nice
CpuStat_System -> system
CpuStat_Idle -> idle
CpuStat_Iowait -> iowait
CpuStat_Irq -> irq
CpuStat_Softirq -> softirq
CpuStat_Steal -> steal
CpuStat_Guest -> guest
CpuStat_GuestNice -> guestNice
sumStats :: (CpuStat -> Word64) -> [CpuStat] -> Word64
sumStats get stats = sum $ get <$> stats
-- | user + nice + system + irq + softirq + steal
nonIdleStats :: [CpuStat]
nonIdleStats =
[ CpuStat_User
, CpuStat_Nice
, CpuStat_System
, CpuStat_Irq
, CpuStat_Softirq
, CpuStat_Steal
]
-- | idle + iowait
idleStats :: [CpuStat]
idleStats =
[ CpuStat_Idle
, CpuStat_Iowait
]
-- | Draws the cpu usage percent as a live-updating bar graph. The output should look like:
--
> ╔ ═ ═ ═ ═ ═ ═ CPU Usage : 38 % ═ ═ ═ ═ ═ ═ ╗
-- > ║ ║
-- > ║ ║
-- > ║ ║
-- > ║ ║
-- > ║ ║
-- > ║ ║
-- > ║█████████████████████████████║
-- > ║█████████████████████████████║
-- > ║█████████████████████████████║
-- > ║█████████████████████████████║
-- > ╚═════════════════════════════╝
--
cpuStats
:: ( Reflex t
, MonadFix m
, MonadHold t m
, MonadIO (Performable m)
, MonadIO m
, PerformEvent t m
, PostBuild t m
, TriggerEvent t m
, HasDisplayRegion t m
, HasImageWriter t m
, HasLayout t m
, HasFocus t m
, HasInput t m
, HasFocusReader t m, HasTheme t m
)
=> m ()
cpuStats = do
tick <- tickLossy 0.25 =<< liftIO getCurrentTime
cpuStat :: Event t (Word64, Word64) <- fmap (fmapMaybe id) $
performEvent $ ffor tick $ \_ -> do
get <- liftIO getCpuStat
pure $ case get of
Nothing -> Nothing
Just get' -> Just (sumStats get' nonIdleStats, sumStats get' idleStats)
active <- foldDyn cpuPercentStep ((0, 0), 0) cpuStat
let pct = fmap snd active
chart pct
chart
:: ( MonadFix m
, HasFocus t m
, HasLayout t m
, HasImageWriter t m
, HasInput t m
, HasDisplayRegion t m
, HasFocusReader t m, HasTheme t m
)
=> Dynamic t (Ratio Word64) -> m ()
chart pct = do
let title = ffor pct $ \x -> mconcat
[ " CPU Usage: "
, T.pack (printf "%3d" $ (ceiling $ x * 100 :: Int))
, "% "
]
boxTitle (pure doubleBoxStyle) (current title) $ col $ do
grout flex blank
dh <- displayHeight
let heights = calcRowHeights <$> dh <*> pct
quarters = fst <$> heights
eighths = snd <$> heights
eighthRow = ffor eighths $ \x -> if x == 0 then 0 else 1
grout (fixed eighthRow) $ fill' (current $ eighthBlocks <$> eighths) $ current $
ffor quarters $ \q ->
if | _quarter_fourth q > 0 -> red
| _quarter_third q > 0 -> orange
| _quarter_second q > 0 -> yellow
| otherwise -> white
grout (fixed $ _quarter_fourth <$> quarters) $ fill' (pure '█') (pure red)
grout (fixed $ _quarter_third <$> quarters) $ fill' (pure '█') (pure orange)
grout (fixed $ _quarter_second <$> quarters) $ fill' (pure '█') (pure yellow)
grout (fixed $ _quarter_first <$> quarters) $ fill' (pure '█') (pure white)
where
-- Calculate number of full rows, height of partial row
calcRowHeights :: Int -> Ratio Word64 -> (Quarter Int, Int)
calcRowHeights h r =
let (full, leftovers) = divMod (numerator r * fromIntegral h) (denominator r)
partial = ceiling $ 8 * (leftovers % denominator r)
quarter = ceiling $ fromIntegral h / (4 :: Double)
n = fromIntegral full
in if | n <= quarter ->
(Quarter n 0 0 0, partial)
| n <= (2 * quarter) ->
(Quarter quarter (n - quarter) 0 0, partial)
| n <= (3 * quarter) ->
(Quarter quarter quarter (n - (2 * quarter)) 0, partial)
| otherwise ->
(Quarter quarter quarter quarter (n - (3 * quarter)), partial)
fill' bc attr = do
dw <- displayWidth
dh <- displayHeight
let fillImg =
(\w h c a -> [V.charFill a c w h])
<$> current dw
<*> current dh
<*> bc
<*> attr
tellImages fillImg
color :: Int -> Int -> Int -> V.Color
color = V.rgbColor
red = V.withForeColor V.defAttr $ color 255 0 0
orange = V.withForeColor V.defAttr $ color 255 165 0
yellow = V.withForeColor V.defAttr $ color 255 255 0
white = V.withForeColor V.defAttr $ color 255 255 255
data Quarter a = Quarter
{ _quarter_first :: a
, _quarter_second :: a
, _quarter_third :: a
, _quarter_fourth :: a
}
eighthBlocks :: (Eq a, Num a, Ord a) => a -> Char
eighthBlocks n =
if
| n <= 0 -> ' '
| n == 1 -> '▁'
| n == 2 -> '▂'
| n == 3 -> '▃'
| n == 4 -> '▄'
| n == 5 -> '▅'
| n == 6 -> '▆'
| n == 7 -> '▇'
| otherwise -> '█'
-- | Determine the current percentage usage according to this algorithm:
--
PrevIdle = previdle + previowait
-- Idle = idle + iowait
--
-- PrevNonIdle = prevuser + prevnice + prevsystem + previrq + prevsoftirq + prevsteal
-- NonIdle = user + nice + system + irq + softirq + steal
--
PrevTotal = PrevIdle + PrevNonIdle
-- Total = Idle + NonIdle
--
-- totald = Total - PrevTotal
-- idled = Idle - PrevIdle
--
-- CPU_Percentage = (totald - idled)/totald
--
-- Source: -calculation-of-cpu-usage-given-in-percentage-in-linux
cpuPercentStep
:: (Word64, Word64) -- Current active, Current idle
-> ((Word64, Word64), Ratio Word64) -- (Previous idle, Previous total), previous percent
-> ((Word64, Word64), Ratio Word64) -- (New idle, new total), percent
cpuPercentStep (nonidle, idle) ((previdle, prevtotal), _) =
let total = idle + nonidle
idled = idle - previdle
totald = total - prevtotal
in ( (idle, total)
, (totald - idled) % totald
)
| null | https://raw.githubusercontent.com/reflex-frp/reflex-vty/832956cf4c679a642509ebfe11160e5449558a74/src-bin/Example/CPU.hs | haskell | |
Description: A CPU usage indicator
| Each constructor represents a cpu statistic column as presented in @/proc/stat@
| Read @/proc/stat@
Make readFile strict
| user + nice + system + irq + softirq + steal
| idle + iowait
| Draws the cpu usage percent as a live-updating bar graph. The output should look like:
> ║ ║
> ║ ║
> ║ ║
> ║ ║
> ║ ║
> ║ ║
> ║█████████████████████████████║
> ║█████████████████████████████║
> ║█████████████████████████████║
> ║█████████████████████████████║
> ╚═════════════════════════════╝
Calculate number of full rows, height of partial row
| Determine the current percentage usage according to this algorithm:
Idle = idle + iowait
PrevNonIdle = prevuser + prevnice + prevsystem + previrq + prevsoftirq + prevsteal
NonIdle = user + nice + system + irq + softirq + steal
Total = Idle + NonIdle
totald = Total - PrevTotal
idled = Idle - PrevIdle
CPU_Percentage = (totald - idled)/totald
Source: -calculation-of-cpu-usage-given-in-percentage-in-linux
Current active, Current idle
(Previous idle, Previous total), previous percent
(New idle, new total), percent | module Example.CPU where
import Control.Exception
import Control.Monad.Fix
import Control.Monad.IO.Class
import Data.Ratio
import Data.Time
import Data.Word
import qualified Data.Text as T
import qualified Graphics.Vty as V
import Text.Printf
import Reflex
import Reflex.Vty
data CpuStat
= CpuStat_User
| CpuStat_Nice
| CpuStat_System
| CpuStat_Idle
| CpuStat_Iowait
| CpuStat_Irq
| CpuStat_Softirq
| CpuStat_Steal
| CpuStat_Guest
| CpuStat_GuestNice
deriving (Show, Read, Eq, Ord, Enum, Bounded)
getCpuStat :: IO (Maybe (CpuStat -> Word64))
getCpuStat = do
s <- readFile "/proc/stat"
pure $ do
cpuSummaryLine : _ <- pure $ lines s
[user, nice, system, idle, iowait, irq, softirq, steal, guest, guestNice] <- pure $ map read $ words $ drop 4 cpuSummaryLine
pure $ \case
CpuStat_User -> user
CpuStat_Nice -> nice
CpuStat_System -> system
CpuStat_Idle -> idle
CpuStat_Iowait -> iowait
CpuStat_Irq -> irq
CpuStat_Softirq -> softirq
CpuStat_Steal -> steal
CpuStat_Guest -> guest
CpuStat_GuestNice -> guestNice
sumStats :: (CpuStat -> Word64) -> [CpuStat] -> Word64
sumStats get stats = sum $ get <$> stats
nonIdleStats :: [CpuStat]
nonIdleStats =
[ CpuStat_User
, CpuStat_Nice
, CpuStat_System
, CpuStat_Irq
, CpuStat_Softirq
, CpuStat_Steal
]
idleStats :: [CpuStat]
idleStats =
[ CpuStat_Idle
, CpuStat_Iowait
]
> ╔ ═ ═ ═ ═ ═ ═ CPU Usage : 38 % ═ ═ ═ ═ ═ ═ ╗
cpuStats
:: ( Reflex t
, MonadFix m
, MonadHold t m
, MonadIO (Performable m)
, MonadIO m
, PerformEvent t m
, PostBuild t m
, TriggerEvent t m
, HasDisplayRegion t m
, HasImageWriter t m
, HasLayout t m
, HasFocus t m
, HasInput t m
, HasFocusReader t m, HasTheme t m
)
=> m ()
cpuStats = do
tick <- tickLossy 0.25 =<< liftIO getCurrentTime
cpuStat :: Event t (Word64, Word64) <- fmap (fmapMaybe id) $
performEvent $ ffor tick $ \_ -> do
get <- liftIO getCpuStat
pure $ case get of
Nothing -> Nothing
Just get' -> Just (sumStats get' nonIdleStats, sumStats get' idleStats)
active <- foldDyn cpuPercentStep ((0, 0), 0) cpuStat
let pct = fmap snd active
chart pct
chart
:: ( MonadFix m
, HasFocus t m
, HasLayout t m
, HasImageWriter t m
, HasInput t m
, HasDisplayRegion t m
, HasFocusReader t m, HasTheme t m
)
=> Dynamic t (Ratio Word64) -> m ()
chart pct = do
let title = ffor pct $ \x -> mconcat
[ " CPU Usage: "
, T.pack (printf "%3d" $ (ceiling $ x * 100 :: Int))
, "% "
]
boxTitle (pure doubleBoxStyle) (current title) $ col $ do
grout flex blank
dh <- displayHeight
let heights = calcRowHeights <$> dh <*> pct
quarters = fst <$> heights
eighths = snd <$> heights
eighthRow = ffor eighths $ \x -> if x == 0 then 0 else 1
grout (fixed eighthRow) $ fill' (current $ eighthBlocks <$> eighths) $ current $
ffor quarters $ \q ->
if | _quarter_fourth q > 0 -> red
| _quarter_third q > 0 -> orange
| _quarter_second q > 0 -> yellow
| otherwise -> white
grout (fixed $ _quarter_fourth <$> quarters) $ fill' (pure '█') (pure red)
grout (fixed $ _quarter_third <$> quarters) $ fill' (pure '█') (pure orange)
grout (fixed $ _quarter_second <$> quarters) $ fill' (pure '█') (pure yellow)
grout (fixed $ _quarter_first <$> quarters) $ fill' (pure '█') (pure white)
where
calcRowHeights :: Int -> Ratio Word64 -> (Quarter Int, Int)
calcRowHeights h r =
let (full, leftovers) = divMod (numerator r * fromIntegral h) (denominator r)
partial = ceiling $ 8 * (leftovers % denominator r)
quarter = ceiling $ fromIntegral h / (4 :: Double)
n = fromIntegral full
in if | n <= quarter ->
(Quarter n 0 0 0, partial)
| n <= (2 * quarter) ->
(Quarter quarter (n - quarter) 0 0, partial)
| n <= (3 * quarter) ->
(Quarter quarter quarter (n - (2 * quarter)) 0, partial)
| otherwise ->
(Quarter quarter quarter quarter (n - (3 * quarter)), partial)
fill' bc attr = do
dw <- displayWidth
dh <- displayHeight
let fillImg =
(\w h c a -> [V.charFill a c w h])
<$> current dw
<*> current dh
<*> bc
<*> attr
tellImages fillImg
color :: Int -> Int -> Int -> V.Color
color = V.rgbColor
red = V.withForeColor V.defAttr $ color 255 0 0
orange = V.withForeColor V.defAttr $ color 255 165 0
yellow = V.withForeColor V.defAttr $ color 255 255 0
white = V.withForeColor V.defAttr $ color 255 255 255
data Quarter a = Quarter
{ _quarter_first :: a
, _quarter_second :: a
, _quarter_third :: a
, _quarter_fourth :: a
}
eighthBlocks :: (Eq a, Num a, Ord a) => a -> Char
eighthBlocks n =
if
| n <= 0 -> ' '
| n == 1 -> '▁'
| n == 2 -> '▂'
| n == 3 -> '▃'
| n == 4 -> '▄'
| n == 5 -> '▅'
| n == 6 -> '▆'
| n == 7 -> '▇'
| otherwise -> '█'
PrevIdle = previdle + previowait
PrevTotal = PrevIdle + PrevNonIdle
cpuPercentStep
cpuPercentStep (nonidle, idle) ((previdle, prevtotal), _) =
let total = idle + nonidle
idled = idle - previdle
totald = total - prevtotal
in ( (idle, total)
, (totald - idled) % totald
)
|
bfaf8342bc899d07391286ecff43fdab320ea016f6e1b4b3f95aa608a666801e | kudu-dynamics/blaze | Solver.hs | {-# LANGUAGE RankNTypes #-}
# LANGUAGE DataKinds #
# LANGUAGE TemplateHaskell #
module Blaze.Types.Pil.Solver
( module Exports
, module Blaze.Types.Pil.Solver
) where
import Blaze.Prelude hiding (Symbol)
import Data.SBV.Internals (SolverContext (..), modelAssocs)
import Data.SBV.Dynamic (SVal, CV)
import qualified Data.SBV.Trans as SBV
import Data.SBV.Trans as Exports ( SymbolicT
, MonadSymbolic
, SMTConfig
, SBool
, runSMT
, runSMTWith
)
import Data.SBV.Trans.Control as Exports (ExtractIO)
import Data.SBV.Trans.Control (QueryT)
import qualified Data.SBV.Trans.Control as Q
import Blaze.Types.Pil (Expression, PilVar, Symbol)
import qualified Data.HashMap.Strict as HashMap
import Control.Monad.Fail (MonadFail(fail))
import Blaze.Types.Pil.Checker (DeepSymType, Sym, SymInfo)
import qualified Blaze.Types.Pil.Checker as Ch
type StmtIndex = Int
type DSTExpression = Ch.InfoExpression (SymInfo, Maybe DeepSymType)
data SolverError = DeepSymTypeConversionError { deepSymType :: DeepSymType, msg :: Text }
| PilVarConversionError { pilVar :: Symbol, conversionError :: SolverError }
| StmtError { stmtIndex :: Int, stmtErr :: SolverError }
| ExprError { exprSym :: Sym, exprErr :: SolverError }
| GuardError { name :: Text, kinds :: [SBV.Kind], msg :: Text }
| StubbedFunctionArgError { funcName :: Text, expected :: Int, got :: Int }
| ConversionError { msg :: Text }
| AlternativeEmpty
| SizeOfError { kind :: SBV.Kind }
| ExtractError { endIndex :: Bits
, startIndex :: Bits
, kind :: SBV.Kind
, msg :: Text
}
| ErrorMessage Text
deriving (Eq, Ord, Show, Generic)
type StubConstraintGen = SVal -> [SVal] -> Solver ()
data SolverLeniency = AbortOnError
| SkipStatementsWithErrors
deriving (Eq, Ord, Show, Generic)
data SolverCtx = SolverCtx
{ typeEnv :: HashMap PilVar DeepSymType
, funcConstraintGen :: HashMap Text StubConstraintGen
, useUnsatCore :: Bool
, leniency :: SolverLeniency
} deriving stock (Generic)
emptyCtx :: Bool -> SolverLeniency -> SolverCtx
emptyCtx = SolverCtx mempty mempty
data SolverState = SolverState
{ varMap :: HashMap PilVar SVal
, varNames :: HashMap PilVar Text
, currentStmtIndex :: Int
, errors :: [SolverError]
, stores :: HashMap Expression [SVal]
} deriving (Generic)
emptyState :: SolverState
emptyState = SolverState mempty mempty 0 [] mempty
-- TODO: it would be nice if the ExceptT wrapped `SymbolicT IO`
so that we could use all the stuff requiring Provable instance
-- (which is only `SymbolicT IO`)
newtype Solver a = Solver { runSolverMonad_ ::
ReaderT SolverCtx
(StateT SolverState
(SymbolicT (ExceptT SolverError IO))) a }
deriving newtype ( Functor, Applicative, Monad
, MonadError SolverError
, MonadReader SolverCtx
, MonadState SolverState
, MonadIO
, MonadSymbolic
)
instance Alternative Solver where
empty = throwError AlternativeEmpty
(<|>) a b = catchError a $ const b
instance MonadFail Solver where
fail = throwError . ErrorMessage . cs
instance SolverContext Solver where
addAxiom s = liftSymbolicT . addAxiom s
addSMTDefinition s = liftSymbolicT . addSMTDefinition s
constrain = liftSymbolicT . constrain
softConstrain = liftSymbolicT . softConstrain
namedConstraint s = liftSymbolicT . namedConstraint s
constrainWithAttribute xs = liftSymbolicT . constrainWithAttribute xs
setInfo s = liftSymbolicT . setInfo s
setOption = liftSymbolicT . setOption
setLogic = liftSymbolicT . setLogic
setTimeOut = liftSymbolicT . setTimeOut
contextState = liftSymbolicT contextState
runSolverWith :: SMTConfig
-> Solver a
-> (SolverState, SolverCtx)
-> IO (Either SolverError (a, SolverState))
runSolverWith solverCfg m (st, ctx) = runExceptT
. runSMTWith solverCfg
. flip runStateT st
. flip runReaderT ctx
. runSolverMonad_
$ do when (ctx ^. #useUnsatCore) $ do
setOption $ Q.ProduceUnsatCores True
when (isZ3 . SBV.name . SBV.solver $ solverCfg)
. setOption $ Q.OptionKeyword ":smt.core.minimize" ["true"]
m
where
-- No Eq instance for SBV.Solver
isZ3 :: SBV.Solver -> Bool
isZ3 SBV.Z3 = True
isZ3 _ = False
runSolverWith_ :: SMTConfig
-> Bool
-> SolverLeniency
-> Solver a
-> IO (Either SolverError (a, SolverState))
runSolverWith_ solverCfg useUnsatCore' solverLeniency =
flip (runSolverWith solverCfg) (emptyState, emptyCtx useUnsatCore' solverLeniency)
data SolverResult = Unsat (Maybe [String])
| Unk
| Sat (HashMap Text CV)
deriving (Eq, Ord, Show, Generic)
type Query a = QueryT (ExceptT SolverError IO) a
toSolverResult :: Q.CheckSatResult -> Query SolverResult
toSolverResult = \case
Q.Unsat -> fmap Unsat $ Q.getOption Q.ProduceUnsatCores >>= \case
(Just (Q.ProduceUnsatCores True)) -> Just <$> Q.getUnsatCore
_ -> return Nothing
Q.Unk -> return Unk
Q.DSat _precision -> do
model <- Q.getModel
return $ Sat . HashMap.fromList $ over _1 cs <$> modelAssocs model
Q.Sat -> do
model <- Q.getModel
return $ Sat . HashMap.fromList $ over _1 cs <$> modelAssocs model
querySolverResult_ :: Query SolverResult
querySolverResult_ = Q.checkSat >>= toSolverResult
querySolverResult :: Solver SolverResult
querySolverResult = liftSymbolicT . Q.query $ querySolverResult_
checkSatWith :: SMTConfig -> Solver () -> (SolverState, SolverCtx) -> IO (Either SolverError (SolverResult, SolverState))
checkSatWith cfg m = runSolverWith cfg (m >> querySolverResult)
checkSatWith_ :: SMTConfig -> Bool -> SolverLeniency -> Solver () -> IO (Either SolverError SolverResult)
checkSatWith_ cfg useUnsatCore' solverLeniency m = fmap fst <$> checkSatWith cfg m (emptyState, emptyCtx useUnsatCore' solverLeniency)
stmtError :: SolverError -> Solver a
stmtError e = do
si <- use #currentStmtIndex
throwError $ StmtError si e
liftSymbolicT :: SymbolicT (ExceptT SolverError IO) a -> Solver a
liftSymbolicT = Solver . lift . lift
data SolverReport = SolverReport
{ result :: SolverResult
, warnings :: [SolverError]
} deriving (Eq, Ord, Show, Generic)
$(makeFieldsNoPrefix ''SolverReport)
| null | https://raw.githubusercontent.com/kudu-dynamics/blaze/5fa75c97074783b9beb07e97e415571aaf503aeb/src/Blaze/Types/Pil/Solver.hs | haskell | # LANGUAGE RankNTypes #
TODO: it would be nice if the ExceptT wrapped `SymbolicT IO`
(which is only `SymbolicT IO`)
No Eq instance for SBV.Solver | # LANGUAGE DataKinds #
# LANGUAGE TemplateHaskell #
module Blaze.Types.Pil.Solver
( module Exports
, module Blaze.Types.Pil.Solver
) where
import Blaze.Prelude hiding (Symbol)
import Data.SBV.Internals (SolverContext (..), modelAssocs)
import Data.SBV.Dynamic (SVal, CV)
import qualified Data.SBV.Trans as SBV
import Data.SBV.Trans as Exports ( SymbolicT
, MonadSymbolic
, SMTConfig
, SBool
, runSMT
, runSMTWith
)
import Data.SBV.Trans.Control as Exports (ExtractIO)
import Data.SBV.Trans.Control (QueryT)
import qualified Data.SBV.Trans.Control as Q
import Blaze.Types.Pil (Expression, PilVar, Symbol)
import qualified Data.HashMap.Strict as HashMap
import Control.Monad.Fail (MonadFail(fail))
import Blaze.Types.Pil.Checker (DeepSymType, Sym, SymInfo)
import qualified Blaze.Types.Pil.Checker as Ch
type StmtIndex = Int
type DSTExpression = Ch.InfoExpression (SymInfo, Maybe DeepSymType)
data SolverError = DeepSymTypeConversionError { deepSymType :: DeepSymType, msg :: Text }
| PilVarConversionError { pilVar :: Symbol, conversionError :: SolverError }
| StmtError { stmtIndex :: Int, stmtErr :: SolverError }
| ExprError { exprSym :: Sym, exprErr :: SolverError }
| GuardError { name :: Text, kinds :: [SBV.Kind], msg :: Text }
| StubbedFunctionArgError { funcName :: Text, expected :: Int, got :: Int }
| ConversionError { msg :: Text }
| AlternativeEmpty
| SizeOfError { kind :: SBV.Kind }
| ExtractError { endIndex :: Bits
, startIndex :: Bits
, kind :: SBV.Kind
, msg :: Text
}
| ErrorMessage Text
deriving (Eq, Ord, Show, Generic)
type StubConstraintGen = SVal -> [SVal] -> Solver ()
data SolverLeniency = AbortOnError
| SkipStatementsWithErrors
deriving (Eq, Ord, Show, Generic)
data SolverCtx = SolverCtx
{ typeEnv :: HashMap PilVar DeepSymType
, funcConstraintGen :: HashMap Text StubConstraintGen
, useUnsatCore :: Bool
, leniency :: SolverLeniency
} deriving stock (Generic)
emptyCtx :: Bool -> SolverLeniency -> SolverCtx
emptyCtx = SolverCtx mempty mempty
data SolverState = SolverState
{ varMap :: HashMap PilVar SVal
, varNames :: HashMap PilVar Text
, currentStmtIndex :: Int
, errors :: [SolverError]
, stores :: HashMap Expression [SVal]
} deriving (Generic)
emptyState :: SolverState
emptyState = SolverState mempty mempty 0 [] mempty
so that we could use all the stuff requiring Provable instance
newtype Solver a = Solver { runSolverMonad_ ::
ReaderT SolverCtx
(StateT SolverState
(SymbolicT (ExceptT SolverError IO))) a }
deriving newtype ( Functor, Applicative, Monad
, MonadError SolverError
, MonadReader SolverCtx
, MonadState SolverState
, MonadIO
, MonadSymbolic
)
instance Alternative Solver where
empty = throwError AlternativeEmpty
(<|>) a b = catchError a $ const b
instance MonadFail Solver where
fail = throwError . ErrorMessage . cs
instance SolverContext Solver where
addAxiom s = liftSymbolicT . addAxiom s
addSMTDefinition s = liftSymbolicT . addSMTDefinition s
constrain = liftSymbolicT . constrain
softConstrain = liftSymbolicT . softConstrain
namedConstraint s = liftSymbolicT . namedConstraint s
constrainWithAttribute xs = liftSymbolicT . constrainWithAttribute xs
setInfo s = liftSymbolicT . setInfo s
setOption = liftSymbolicT . setOption
setLogic = liftSymbolicT . setLogic
setTimeOut = liftSymbolicT . setTimeOut
contextState = liftSymbolicT contextState
runSolverWith :: SMTConfig
-> Solver a
-> (SolverState, SolverCtx)
-> IO (Either SolverError (a, SolverState))
runSolverWith solverCfg m (st, ctx) = runExceptT
. runSMTWith solverCfg
. flip runStateT st
. flip runReaderT ctx
. runSolverMonad_
$ do when (ctx ^. #useUnsatCore) $ do
setOption $ Q.ProduceUnsatCores True
when (isZ3 . SBV.name . SBV.solver $ solverCfg)
. setOption $ Q.OptionKeyword ":smt.core.minimize" ["true"]
m
where
isZ3 :: SBV.Solver -> Bool
isZ3 SBV.Z3 = True
isZ3 _ = False
runSolverWith_ :: SMTConfig
-> Bool
-> SolverLeniency
-> Solver a
-> IO (Either SolverError (a, SolverState))
runSolverWith_ solverCfg useUnsatCore' solverLeniency =
flip (runSolverWith solverCfg) (emptyState, emptyCtx useUnsatCore' solverLeniency)
data SolverResult = Unsat (Maybe [String])
| Unk
| Sat (HashMap Text CV)
deriving (Eq, Ord, Show, Generic)
type Query a = QueryT (ExceptT SolverError IO) a
toSolverResult :: Q.CheckSatResult -> Query SolverResult
toSolverResult = \case
Q.Unsat -> fmap Unsat $ Q.getOption Q.ProduceUnsatCores >>= \case
(Just (Q.ProduceUnsatCores True)) -> Just <$> Q.getUnsatCore
_ -> return Nothing
Q.Unk -> return Unk
Q.DSat _precision -> do
model <- Q.getModel
return $ Sat . HashMap.fromList $ over _1 cs <$> modelAssocs model
Q.Sat -> do
model <- Q.getModel
return $ Sat . HashMap.fromList $ over _1 cs <$> modelAssocs model
querySolverResult_ :: Query SolverResult
querySolverResult_ = Q.checkSat >>= toSolverResult
querySolverResult :: Solver SolverResult
querySolverResult = liftSymbolicT . Q.query $ querySolverResult_
checkSatWith :: SMTConfig -> Solver () -> (SolverState, SolverCtx) -> IO (Either SolverError (SolverResult, SolverState))
checkSatWith cfg m = runSolverWith cfg (m >> querySolverResult)
checkSatWith_ :: SMTConfig -> Bool -> SolverLeniency -> Solver () -> IO (Either SolverError SolverResult)
checkSatWith_ cfg useUnsatCore' solverLeniency m = fmap fst <$> checkSatWith cfg m (emptyState, emptyCtx useUnsatCore' solverLeniency)
stmtError :: SolverError -> Solver a
stmtError e = do
si <- use #currentStmtIndex
throwError $ StmtError si e
liftSymbolicT :: SymbolicT (ExceptT SolverError IO) a -> Solver a
liftSymbolicT = Solver . lift . lift
data SolverReport = SolverReport
{ result :: SolverResult
, warnings :: [SolverError]
} deriving (Eq, Ord, Show, Generic)
$(makeFieldsNoPrefix ''SolverReport)
|
4fa9584fc1d8c2f413a6e441ce2ba3598999dbeb3a37563e4e23ff3c783c8798 | openvstorage/alba | lwt_extra2.ml |
Copyright ( C ) iNuron -
This file is part of Open vStorage . For license information , see < LICENSE.txt >
Copyright (C) iNuron -
This file is part of Open vStorage. For license information, see <LICENSE.txt>
*)
open! Prelude
open Lwt.Infix
let ignore_errors ?(logging=false) f =
Lwt.catch
f
(function
| Lwt.Canceled -> Lwt.fail Lwt.Canceled
| exn ->
if logging
then Lwt_log.info ~exn "ignoring"
else Lwt_log.debug ~exn "ignoring")
let with_timeout ~msg (timeout:float) f =
Lwt.catch
(fun () -> Lwt_unix.with_timeout timeout f)
(fun ex ->
begin
match ex with
| Lwt_unix.Timeout -> Lwt_log.debug_f "Timeout(%.2f):%s" timeout msg
| _ -> Lwt.return_unit
end >>= fun () -> Lwt.fail ex
)
let with_timeout_default ~msg timeout default f =
Lwt.catch
(fun () -> Lwt_unix.with_timeout timeout f)
(function
| Lwt_unix.Timeout ->
Lwt_log.debug_f "Timeout(%.2f):%s" timeout msg
>>= fun () ->
Lwt.return default
| exn -> Lwt.fail exn
)
module CountDownLatch = struct
type t = { mutable needed : int;
mutable waiters : unit Lwt.u list; }
let create ~count =
assert (count >= 0);
{ needed = count; waiters = [] }
let count_down t =
if t.needed <> 0
then
t.needed <- t.needed - 1;
if t.needed = 0
then begin
List.iter (fun lwtu -> Lwt.wakeup_later lwtu ()) t.waiters;
t.waiters <- []
end
let finished t = t.needed = 0
let current t = t.needed
let await t =
if finished t
then Lwt.return ()
else
let lwtt, lwtu = Lwt.wait () in
t.waiters <- lwtu :: t.waiters;
lwtt
end
module FoldingCountDownLatch = struct
type ('a, 'b) t = {
latch : CountDownLatch.t;
mutable acc : 'a;
f : 'a -> 'b -> 'a; }
let create ~count ~acc ~f =
{ latch = CountDownLatch.create ~count;
acc; f; }
let notify t b =
if t.latch.CountDownLatch.needed <> 0
then begin
t.acc <- t.f t.acc b;
CountDownLatch.count_down t.latch
end
let await t =
let open Lwt in
CountDownLatch.await t.latch >>= fun () ->
Lwt.return t.acc
end
let sleep_approx ?(jitter=0.1) duration =
let delta = Random.float (2. *. jitter) -. jitter in
Lwt_unix.sleep ((1. +. delta) *. duration)
let rec run_forever ?(stop=ref false) msg f delay =
Lwt.catch
f
(fun exn -> Lwt_log.info ~exn msg) >>= fun () ->
if !stop
then Lwt.return_unit
else
begin
sleep_approx delay >>= fun () ->
run_forever msg f delay
end
let lwt_unix_fd_to_fd
(fd : Lwt_unix.file_descr) : int =
Obj.magic (Obj.field (Obj.repr fd) 0)
let lwt_unix_fd_to_unix_fd
(fd : Lwt_unix.file_descr) : Unix.file_descr =
Obj.magic (Obj.field (Obj.repr fd) 0)
let unix_fd_to_fd (fd : Unix.file_descr) : int =
Obj.magic fd
let with_fd filename ~flags ~perm f =
Lwt_unix.openfile filename flags perm >>= fun fd ->
Lwt.finalize
(fun () -> f fd)
(fun () -> Lwt_unix.close fd)
let fsync_dir dir =
Lwt_unix.openfile dir [Unix.O_RDONLY] 0640 >>= fun dir_descr ->
Lwt.finalize
(fun () -> Lwt_unix.fsync dir_descr)
(fun () -> Lwt_unix.close dir_descr)
let fsync_dir_of_file filename =
fsync_dir (Filename.dirname filename)
let create_dir ?(sync = true) dir =
Lwt_unix.mkdir dir 0o775 >>= fun () ->
if sync
then fsync_dir_of_file dir
else Lwt.return ()
let unlink ?(may_not_exist=false) ~fsync_parent_dir file =
Lwt.catch
(fun () ->
Lwt_unix.unlink file >>= fun () ->
if fsync_parent_dir
then fsync_dir_of_file file
else Lwt.return ())
(function
| Unix.Unix_error(Unix.ENOENT, _, _) as exn ->
if may_not_exist
then Lwt.return_unit
else Lwt.fail exn
| exn ->
Lwt.fail exn)
let rename ~fsync_parent_dir from dest =
Lwt_unix.rename from dest >>= fun () ->
if fsync_parent_dir
then fsync_dir_of_file dest
else Lwt.return ()
let stat filename =
Lwt_log.debug_f "stat %S" filename >>= fun () ->
Lwt_unix.stat filename
let exists filename =
Lwt.catch
(fun () -> stat filename >>= fun _ -> Lwt.return true)
(function
| Unix.Unix_error (Unix.ENOENT,_,_) -> Lwt.return false
| e -> Lwt.fail e
)
let _read_all read_to_target ifd offset length =
let t0 = Unix.gettimeofday() in
let rec inner offset count = function
| 0 ->
begin
let took = Unix.gettimeofday () -. t0 in
if count < 20
|| (length / count > 32768)
|| took < 0.01 (* don't log if benign *)
then Lwt.return_unit
else
Lwt_log.info_f
"reading from fd %i: %iB in %i steps (took:%f)"
ifd length count took
end >>= fun () ->
Lwt.return length
| todo ->
read_to_target offset todo >>= function
| 0 -> Lwt.return (length - todo)
| got -> inner (offset + got) (count + 1) (todo - got)
in
inner offset 0 length
let read_all_lwt_bytes fd target offset length =
_read_all (Lwt_bytes.read_and_log fd target) (lwt_unix_fd_to_fd fd) offset length >>= fun result ->
begin
Lwt_log.ign_debug_f ">>> read_all_lwt_bytes from fd %i @ %nX size %i length %i offset %i end: %i -- %S"
(lwt_unix_fd_to_fd fd) (Lwt_bytes.raw_address target) (Lwt_bytes.length target)
length offset (offset + length)
(Printexc.get_callstack 5 |> Printexc.raw_backtrace_to_string);
Lwt.return result;
end
let expect_exact_length len length =
if len = length
then Lwt.return_unit
else Lwt.fail End_of_file
let read_all_lwt_bytes_exact fd target offset length =
read_all_lwt_bytes fd target offset length >>= expect_exact_length length
let read_all fd target offset length =
begin
Lwt_log.ign_debug_f ">>> read_all from fd %i length %i offset %i" (lwt_unix_fd_to_fd fd) length offset;
_read_all (Lwt_unix.read fd target) (lwt_unix_fd_to_fd fd) offset length;
end
let read_all_exact fd target offset length =
read_all fd target offset length >>= expect_exact_length length
let _read_buffer_at_least read_to_target ~offset ~max_length ~min_length =
let rec inner total_read =
read_to_target
(offset + total_read)
(max_length - total_read)
>>= function
| 0 -> Lwt.fail End_of_file
| read ->
let total_read = total_read + read in
if total_read >= min_length
then Lwt.return total_read
else inner total_read
in
inner 0
let read_lwt_bytes_at_least fd target = _read_buffer_at_least (Lwt_bytes.read_and_log fd target)
let read_bytes_at_least fd target = _read_buffer_at_least (Lwt_unix.read fd target)
let _write_all write_from_source ifd offset length =
let rec inner offset count = function
| 0 ->
if count < 20 || (length / count > 32768)
then Lwt.return_unit
else Lwt_log.info_f "writing to fd %i: %iB in %i steps" ifd length count
| todo ->
write_from_source offset todo >>= fun written ->
inner (offset + written) (count + 1) (todo - written)
in
inner offset 0 length
let write_all_lwt_bytes fd source offset length =
_write_all (Lwt_bytes.write fd source) (lwt_unix_fd_to_fd fd) offset length
let write_all fd source offset length =
_write_all (Lwt_unix.write fd source) (lwt_unix_fd_to_fd fd) offset length
let write_all' fd source =
write_all fd source 0 (Bytes.length source)
let llio_output_and_flush oc s =
Llio.output_string oc s >>= fun () ->
Lwt_io.flush oc
let flush_logging () =
(* this statement flushes the log output stream (aka stdout)
TODO: obviously it doesn't work in all cases
*)
Lwt_io.printf "%!"
let make_fuse_thread () =
let mvar = Lwt_mvar.create_empty () in
let signals = [ (Sys.sigterm, "SIGTERM");
(Sys.sigint, "SIGINT"); ] in
let signal_handler x =
Lwt.ignore_result (Lwt_mvar.put mvar x)
in
List.iter
(fun (signal, _) -> Lwt_unix.on_signal signal signal_handler |> ignore)
signals;
Lwt_mvar.take mvar >>= fun x ->
let sig_name = List.assoc x signals in
Lwt_log.warning_f "Got signal %s (%i), terminating..." sig_name x >>= fun () ->
flush_logging ()
let get_files_of_directory dir =
Lwt_stream.to_list (Lwt_unix.files_of_directory dir) >>= fun l ->
let res =
List.filter
(fun fn -> not (List.mem fn [ Filename.parent_dir_name;
Filename.current_dir_name; ]))
l
in
Lwt.return res
let read_file file =
Lwt_io.file_length file >>= fun len ->
let len' = Int64.to_int len in
let buf = Bytes.create len' in
with_fd
file
~flags:Lwt_unix.([O_RDONLY;])
~perm:0600
(fun fd ->
read_all fd buf 0 len' >>= fun read ->
assert (read = len');
Lwt.return ()) >>= fun () ->
Lwt.return buf
let write_file ~destination ~contents =
let tmp = destination ^ ".tmp" in
unlink ~fsync_parent_dir:false ~may_not_exist:true tmp >>= fun () ->
with_fd
tmp
~flags:Lwt_unix.([ O_WRONLY; O_CREAT; O_EXCL; ])
~perm:0o664
(fun fd ->
write_all
fd
contents 0 (String.length contents) >>= fun () ->
Lwt_unix.fsync fd
) >>= fun () ->
rename ~fsync_parent_dir:true tmp destination
let copy_using
reader writer
size buffer
=
let buffer_size = Lwt_bytes.length buffer in
let rec loop todo =
if todo = 0
then Lwt.return_unit
else
begin
let step =
if todo <= buffer_size
then todo
else buffer_size
in
reader buffer 0 step >>= fun bytes_read ->
writer buffer 0 bytes_read >>= fun () ->
loop (todo - bytes_read)
end
in
loop size
let copy_between_fds fd_in fd_out size buffer =
let reader = Lwt_bytes.read fd_in in
let writer = write_all_lwt_bytes fd_out in
copy_using reader writer size buffer
let join_threads_ignore_errors ts =
Lwt.join
(List.map
(fun t ->
Lwt.catch
(fun () -> t >>= fun _ -> Lwt.return_unit)
(fun exn -> Lwt.return_unit))
ts)
let with_timeout_no_cancel d f =
let result = ref `Unfinished in
Lwt.choose
[ begin
Lwt_unix.sleep d >>= fun () ->
let () =
match !result with
| `Unfinished -> result := `Timeout
| `Timeout -> assert false
| `Result _ -> ()
in
Lwt.return_unit
end;
begin
f () >>= fun r ->
let () =
match !result with
| `Unfinished -> result := `Result r
| `Timeout -> ()
| `Result _ -> assert false
in
Lwt.return_unit
end; ]
>>= fun () ->
match !result with
| `Unfinished -> assert false
| `Timeout -> Lwt.fail Lwt_unix.Timeout
| `Result r -> Lwt.return r
let first_n ~count ~slack f items ~test =
let t0 = Unix.gettimeofday() in
let success = CountDownLatch.create ~count in
let n_items = List.length items in
let failures = CountDownLatch.create ~count:(n_items - count + 1) in
let log_state index =
let open CountDownLatch in
Lwt_log.debug_f
"%i finished (needed=%i, distance to failure=%i)%!"
index
success.needed
failures.needed
in
let ts = List.mapi
(fun index item ->
Lwt.catch
(fun () ->
f item >>= fun r ->
if test r
then CountDownLatch.count_down success
else CountDownLatch.count_down failures;
log_state index >>= fun () ->
Lwt.return r)
(fun exn ->
CountDownLatch.count_down failures;
log_state index >>= fun () ->
Lwt.fail exn))
items
in
Lwt.choose [CountDownLatch.await success;
CountDownLatch.await failures;
]
>>= fun () ->
let t1 = Unix.gettimeofday() in
let so_far = t1 -. t0 in
let limit = so_far *. slack in
Lwt_log.debug_f "waiting for another %f * %f =%f" so_far slack limit
>>= fun () ->
Lwt.choose
[ begin
Lwt_unix.sleep limit >>= fun () ->
let slackers_count =
List.fold_left
(fun acc t ->
match Lwt.state t with
| Lwt.Return _ | Lwt.Fail _ -> acc
| Lwt.Sleep -> acc + 1
)
0
ts
in
if slackers_count > 0
then
Lwt_log.debug_f
"first n: timeout while waiting for %i slacker threads to join"
slackers_count
else
Lwt.return_unit
end;
join_threads_ignore_errors ts;
]
>>= fun () ->
Lwt.return (CountDownLatch.finished success, ts)
| null | https://raw.githubusercontent.com/openvstorage/alba/459bd459335138d6b282d332fcff53a1b4300c29/ocaml/src/tools/lwt_extra2.ml | ocaml | don't log if benign
this statement flushes the log output stream (aka stdout)
TODO: obviously it doesn't work in all cases
|
Copyright ( C ) iNuron -
This file is part of Open vStorage . For license information , see < LICENSE.txt >
Copyright (C) iNuron -
This file is part of Open vStorage. For license information, see <LICENSE.txt>
*)
open! Prelude
open Lwt.Infix
let ignore_errors ?(logging=false) f =
Lwt.catch
f
(function
| Lwt.Canceled -> Lwt.fail Lwt.Canceled
| exn ->
if logging
then Lwt_log.info ~exn "ignoring"
else Lwt_log.debug ~exn "ignoring")
let with_timeout ~msg (timeout:float) f =
Lwt.catch
(fun () -> Lwt_unix.with_timeout timeout f)
(fun ex ->
begin
match ex with
| Lwt_unix.Timeout -> Lwt_log.debug_f "Timeout(%.2f):%s" timeout msg
| _ -> Lwt.return_unit
end >>= fun () -> Lwt.fail ex
)
let with_timeout_default ~msg timeout default f =
Lwt.catch
(fun () -> Lwt_unix.with_timeout timeout f)
(function
| Lwt_unix.Timeout ->
Lwt_log.debug_f "Timeout(%.2f):%s" timeout msg
>>= fun () ->
Lwt.return default
| exn -> Lwt.fail exn
)
module CountDownLatch = struct
type t = { mutable needed : int;
mutable waiters : unit Lwt.u list; }
let create ~count =
assert (count >= 0);
{ needed = count; waiters = [] }
let count_down t =
if t.needed <> 0
then
t.needed <- t.needed - 1;
if t.needed = 0
then begin
List.iter (fun lwtu -> Lwt.wakeup_later lwtu ()) t.waiters;
t.waiters <- []
end
let finished t = t.needed = 0
let current t = t.needed
let await t =
if finished t
then Lwt.return ()
else
let lwtt, lwtu = Lwt.wait () in
t.waiters <- lwtu :: t.waiters;
lwtt
end
module FoldingCountDownLatch = struct
type ('a, 'b) t = {
latch : CountDownLatch.t;
mutable acc : 'a;
f : 'a -> 'b -> 'a; }
let create ~count ~acc ~f =
{ latch = CountDownLatch.create ~count;
acc; f; }
let notify t b =
if t.latch.CountDownLatch.needed <> 0
then begin
t.acc <- t.f t.acc b;
CountDownLatch.count_down t.latch
end
let await t =
let open Lwt in
CountDownLatch.await t.latch >>= fun () ->
Lwt.return t.acc
end
let sleep_approx ?(jitter=0.1) duration =
let delta = Random.float (2. *. jitter) -. jitter in
Lwt_unix.sleep ((1. +. delta) *. duration)
let rec run_forever ?(stop=ref false) msg f delay =
Lwt.catch
f
(fun exn -> Lwt_log.info ~exn msg) >>= fun () ->
if !stop
then Lwt.return_unit
else
begin
sleep_approx delay >>= fun () ->
run_forever msg f delay
end
let lwt_unix_fd_to_fd
(fd : Lwt_unix.file_descr) : int =
Obj.magic (Obj.field (Obj.repr fd) 0)
let lwt_unix_fd_to_unix_fd
(fd : Lwt_unix.file_descr) : Unix.file_descr =
Obj.magic (Obj.field (Obj.repr fd) 0)
let unix_fd_to_fd (fd : Unix.file_descr) : int =
Obj.magic fd
let with_fd filename ~flags ~perm f =
Lwt_unix.openfile filename flags perm >>= fun fd ->
Lwt.finalize
(fun () -> f fd)
(fun () -> Lwt_unix.close fd)
let fsync_dir dir =
Lwt_unix.openfile dir [Unix.O_RDONLY] 0640 >>= fun dir_descr ->
Lwt.finalize
(fun () -> Lwt_unix.fsync dir_descr)
(fun () -> Lwt_unix.close dir_descr)
let fsync_dir_of_file filename =
fsync_dir (Filename.dirname filename)
let create_dir ?(sync = true) dir =
Lwt_unix.mkdir dir 0o775 >>= fun () ->
if sync
then fsync_dir_of_file dir
else Lwt.return ()
let unlink ?(may_not_exist=false) ~fsync_parent_dir file =
Lwt.catch
(fun () ->
Lwt_unix.unlink file >>= fun () ->
if fsync_parent_dir
then fsync_dir_of_file file
else Lwt.return ())
(function
| Unix.Unix_error(Unix.ENOENT, _, _) as exn ->
if may_not_exist
then Lwt.return_unit
else Lwt.fail exn
| exn ->
Lwt.fail exn)
let rename ~fsync_parent_dir from dest =
Lwt_unix.rename from dest >>= fun () ->
if fsync_parent_dir
then fsync_dir_of_file dest
else Lwt.return ()
let stat filename =
Lwt_log.debug_f "stat %S" filename >>= fun () ->
Lwt_unix.stat filename
let exists filename =
Lwt.catch
(fun () -> stat filename >>= fun _ -> Lwt.return true)
(function
| Unix.Unix_error (Unix.ENOENT,_,_) -> Lwt.return false
| e -> Lwt.fail e
)
let _read_all read_to_target ifd offset length =
let t0 = Unix.gettimeofday() in
let rec inner offset count = function
| 0 ->
begin
let took = Unix.gettimeofday () -. t0 in
if count < 20
|| (length / count > 32768)
then Lwt.return_unit
else
Lwt_log.info_f
"reading from fd %i: %iB in %i steps (took:%f)"
ifd length count took
end >>= fun () ->
Lwt.return length
| todo ->
read_to_target offset todo >>= function
| 0 -> Lwt.return (length - todo)
| got -> inner (offset + got) (count + 1) (todo - got)
in
inner offset 0 length
let read_all_lwt_bytes fd target offset length =
_read_all (Lwt_bytes.read_and_log fd target) (lwt_unix_fd_to_fd fd) offset length >>= fun result ->
begin
Lwt_log.ign_debug_f ">>> read_all_lwt_bytes from fd %i @ %nX size %i length %i offset %i end: %i -- %S"
(lwt_unix_fd_to_fd fd) (Lwt_bytes.raw_address target) (Lwt_bytes.length target)
length offset (offset + length)
(Printexc.get_callstack 5 |> Printexc.raw_backtrace_to_string);
Lwt.return result;
end
let expect_exact_length len length =
if len = length
then Lwt.return_unit
else Lwt.fail End_of_file
let read_all_lwt_bytes_exact fd target offset length =
read_all_lwt_bytes fd target offset length >>= expect_exact_length length
let read_all fd target offset length =
begin
Lwt_log.ign_debug_f ">>> read_all from fd %i length %i offset %i" (lwt_unix_fd_to_fd fd) length offset;
_read_all (Lwt_unix.read fd target) (lwt_unix_fd_to_fd fd) offset length;
end
let read_all_exact fd target offset length =
read_all fd target offset length >>= expect_exact_length length
let _read_buffer_at_least read_to_target ~offset ~max_length ~min_length =
let rec inner total_read =
read_to_target
(offset + total_read)
(max_length - total_read)
>>= function
| 0 -> Lwt.fail End_of_file
| read ->
let total_read = total_read + read in
if total_read >= min_length
then Lwt.return total_read
else inner total_read
in
inner 0
let read_lwt_bytes_at_least fd target = _read_buffer_at_least (Lwt_bytes.read_and_log fd target)
let read_bytes_at_least fd target = _read_buffer_at_least (Lwt_unix.read fd target)
let _write_all write_from_source ifd offset length =
let rec inner offset count = function
| 0 ->
if count < 20 || (length / count > 32768)
then Lwt.return_unit
else Lwt_log.info_f "writing to fd %i: %iB in %i steps" ifd length count
| todo ->
write_from_source offset todo >>= fun written ->
inner (offset + written) (count + 1) (todo - written)
in
inner offset 0 length
let write_all_lwt_bytes fd source offset length =
_write_all (Lwt_bytes.write fd source) (lwt_unix_fd_to_fd fd) offset length
let write_all fd source offset length =
_write_all (Lwt_unix.write fd source) (lwt_unix_fd_to_fd fd) offset length
let write_all' fd source =
write_all fd source 0 (Bytes.length source)
let llio_output_and_flush oc s =
Llio.output_string oc s >>= fun () ->
Lwt_io.flush oc
let flush_logging () =
Lwt_io.printf "%!"
let make_fuse_thread () =
let mvar = Lwt_mvar.create_empty () in
let signals = [ (Sys.sigterm, "SIGTERM");
(Sys.sigint, "SIGINT"); ] in
let signal_handler x =
Lwt.ignore_result (Lwt_mvar.put mvar x)
in
List.iter
(fun (signal, _) -> Lwt_unix.on_signal signal signal_handler |> ignore)
signals;
Lwt_mvar.take mvar >>= fun x ->
let sig_name = List.assoc x signals in
Lwt_log.warning_f "Got signal %s (%i), terminating..." sig_name x >>= fun () ->
flush_logging ()
let get_files_of_directory dir =
Lwt_stream.to_list (Lwt_unix.files_of_directory dir) >>= fun l ->
let res =
List.filter
(fun fn -> not (List.mem fn [ Filename.parent_dir_name;
Filename.current_dir_name; ]))
l
in
Lwt.return res
let read_file file =
Lwt_io.file_length file >>= fun len ->
let len' = Int64.to_int len in
let buf = Bytes.create len' in
with_fd
file
~flags:Lwt_unix.([O_RDONLY;])
~perm:0600
(fun fd ->
read_all fd buf 0 len' >>= fun read ->
assert (read = len');
Lwt.return ()) >>= fun () ->
Lwt.return buf
let write_file ~destination ~contents =
let tmp = destination ^ ".tmp" in
unlink ~fsync_parent_dir:false ~may_not_exist:true tmp >>= fun () ->
with_fd
tmp
~flags:Lwt_unix.([ O_WRONLY; O_CREAT; O_EXCL; ])
~perm:0o664
(fun fd ->
write_all
fd
contents 0 (String.length contents) >>= fun () ->
Lwt_unix.fsync fd
) >>= fun () ->
rename ~fsync_parent_dir:true tmp destination
let copy_using
reader writer
size buffer
=
let buffer_size = Lwt_bytes.length buffer in
let rec loop todo =
if todo = 0
then Lwt.return_unit
else
begin
let step =
if todo <= buffer_size
then todo
else buffer_size
in
reader buffer 0 step >>= fun bytes_read ->
writer buffer 0 bytes_read >>= fun () ->
loop (todo - bytes_read)
end
in
loop size
let copy_between_fds fd_in fd_out size buffer =
let reader = Lwt_bytes.read fd_in in
let writer = write_all_lwt_bytes fd_out in
copy_using reader writer size buffer
let join_threads_ignore_errors ts =
Lwt.join
(List.map
(fun t ->
Lwt.catch
(fun () -> t >>= fun _ -> Lwt.return_unit)
(fun exn -> Lwt.return_unit))
ts)
let with_timeout_no_cancel d f =
let result = ref `Unfinished in
Lwt.choose
[ begin
Lwt_unix.sleep d >>= fun () ->
let () =
match !result with
| `Unfinished -> result := `Timeout
| `Timeout -> assert false
| `Result _ -> ()
in
Lwt.return_unit
end;
begin
f () >>= fun r ->
let () =
match !result with
| `Unfinished -> result := `Result r
| `Timeout -> ()
| `Result _ -> assert false
in
Lwt.return_unit
end; ]
>>= fun () ->
match !result with
| `Unfinished -> assert false
| `Timeout -> Lwt.fail Lwt_unix.Timeout
| `Result r -> Lwt.return r
let first_n ~count ~slack f items ~test =
let t0 = Unix.gettimeofday() in
let success = CountDownLatch.create ~count in
let n_items = List.length items in
let failures = CountDownLatch.create ~count:(n_items - count + 1) in
let log_state index =
let open CountDownLatch in
Lwt_log.debug_f
"%i finished (needed=%i, distance to failure=%i)%!"
index
success.needed
failures.needed
in
let ts = List.mapi
(fun index item ->
Lwt.catch
(fun () ->
f item >>= fun r ->
if test r
then CountDownLatch.count_down success
else CountDownLatch.count_down failures;
log_state index >>= fun () ->
Lwt.return r)
(fun exn ->
CountDownLatch.count_down failures;
log_state index >>= fun () ->
Lwt.fail exn))
items
in
Lwt.choose [CountDownLatch.await success;
CountDownLatch.await failures;
]
>>= fun () ->
let t1 = Unix.gettimeofday() in
let so_far = t1 -. t0 in
let limit = so_far *. slack in
Lwt_log.debug_f "waiting for another %f * %f =%f" so_far slack limit
>>= fun () ->
Lwt.choose
[ begin
Lwt_unix.sleep limit >>= fun () ->
let slackers_count =
List.fold_left
(fun acc t ->
match Lwt.state t with
| Lwt.Return _ | Lwt.Fail _ -> acc
| Lwt.Sleep -> acc + 1
)
0
ts
in
if slackers_count > 0
then
Lwt_log.debug_f
"first n: timeout while waiting for %i slacker threads to join"
slackers_count
else
Lwt.return_unit
end;
join_threads_ignore_errors ts;
]
>>= fun () ->
Lwt.return (CountDownLatch.finished success, ts)
|
077149fb5d23694cad8a1564f74bca03777fcdefa0da315bf36a6b5ac39173d7 | witheve/eve-experiments | db.clj | (ns server.db
(:require [server.edb :as edb]
[server.exec :as exec]))
;; this should have annotations so that it actually
captures the correct number of bits ( 96 )
(defrecord uuid [time batch machine])
(defrecord station [ip port])
(def machine-id (ref 113))
;; xxx - ignoro batcho
(defn genoid []
(uuid. (edb/now) 0 @machine-id))
(defn wrapoid [time batch machine] (uuid. time 0 machine))
(def uber-log (atom ()))
(def remove-fact 5)
(def name-oid 10)
(def implication-oid 11)
(def contains-oid 12)
(defn insert-implication [db relname parameters program]
(edb/insert db (object-array [(name relname)
implication-oid
(vector (map name parameters) program)])
(gensym "insert-implication")
(fn [t] ())))
i would like to use here , but clojure is really screwing
;; up my symbols
(defn weasl-implications-for [id]
(list (list
'bind 'main
(list (list 'scan [4] [])
(list '= [5] [4 1] implication-oid)
'(filter [5])
(list '= [5] [4 0] (name id))
'(filter [5])
(list 'tuple [5] exec/op-register [4 2])
(list 'send 'out [5])))))
(defn tuple-to-implication [tuple]
(exec/rget tuple [1]))
(defn for-each-implication [d id handler]
(exec/single d
(weasl-implications-for id)
(fn [tuple]
(when (= (exec/rget tuple exec/op-register) 'insert)
(apply handler (tuple-to-implication tuple))))))
;; @FIXME: This relies on exec/open flushing synchronously to determine if the implication currently exists
;; plumb bag in here
(defn implication-of [d id]
(let [impl (atom nil)]
(exec/single d (weasl-implications-for id)
(fn [tuple]
(when (= (exec/rget tuple exec/op-register) 'insert)
(reset! impl (tuple-to-implication tuple)))))
@impl))
| null | https://raw.githubusercontent.com/witheve/eve-experiments/8a1cdb353b3e728bc768b315e5b9a9f9dc785ae1/server/src/server/db.clj | clojure | this should have annotations so that it actually
xxx - ignoro batcho
up my symbols
@FIXME: This relies on exec/open flushing synchronously to determine if the implication currently exists
plumb bag in here | (ns server.db
(:require [server.edb :as edb]
[server.exec :as exec]))
captures the correct number of bits ( 96 )
(defrecord uuid [time batch machine])
(defrecord station [ip port])
(def machine-id (ref 113))
(defn genoid []
(uuid. (edb/now) 0 @machine-id))
(defn wrapoid [time batch machine] (uuid. time 0 machine))
(def uber-log (atom ()))
(def remove-fact 5)
(def name-oid 10)
(def implication-oid 11)
(def contains-oid 12)
(defn insert-implication [db relname parameters program]
(edb/insert db (object-array [(name relname)
implication-oid
(vector (map name parameters) program)])
(gensym "insert-implication")
(fn [t] ())))
i would like to use here , but clojure is really screwing
(defn weasl-implications-for [id]
(list (list
'bind 'main
(list (list 'scan [4] [])
(list '= [5] [4 1] implication-oid)
'(filter [5])
(list '= [5] [4 0] (name id))
'(filter [5])
(list 'tuple [5] exec/op-register [4 2])
(list 'send 'out [5])))))
(defn tuple-to-implication [tuple]
(exec/rget tuple [1]))
(defn for-each-implication [d id handler]
(exec/single d
(weasl-implications-for id)
(fn [tuple]
(when (= (exec/rget tuple exec/op-register) 'insert)
(apply handler (tuple-to-implication tuple))))))
(defn implication-of [d id]
(let [impl (atom nil)]
(exec/single d (weasl-implications-for id)
(fn [tuple]
(when (= (exec/rget tuple exec/op-register) 'insert)
(reset! impl (tuple-to-implication tuple)))))
@impl))
|
64ad2269311d5b7ef0ac7d2f97fc938c4d3081168ec271d443200bc46b01aed9 | caribou/caribou-core | auth.clj | (ns caribou.auth)
(import org.mindrot.jbcrypt.BCrypt)
(import [java.security MessageDigest])
(defn hash-bcrypt
"hash a password to store it in a password field"
[pass]
(. BCrypt hashpw pass (. BCrypt gensalt 13)))
(defn check-bcrypt
"check a raw password against a hash from the password field"
[pass hash]
(. BCrypt checkpw pass hash))
(def ^{:dynamic true} *default-hash* "SHA-256")
(defn hexdigest
"Returns the hex digest of an object. Expects a string as input."
([input] (hexdigest input *default-hash*))
([input hash-algo]
(if (string? input)
(let [hash (MessageDigest/getInstance hash-algo)]
(. hash update (.getBytes input))
(let [digest (.digest hash)]
(apply str (map #(format "%02x" (bit-and % 0xff)) digest))))
(do
(println "Invalid input! Expected string, got" (type input))
nil))))
(defn checkhex [obj ref-hash]
(= ref-hash (hexdigest obj)))
(def hash-password hexdigest)
(def check-password checkhex)
| null | https://raw.githubusercontent.com/caribou/caribou-core/6ebd9db4e14cddb1d6b4e152e771e016fa9c55f6/src/caribou/auth.clj | clojure | (ns caribou.auth)
(import org.mindrot.jbcrypt.BCrypt)
(import [java.security MessageDigest])
(defn hash-bcrypt
"hash a password to store it in a password field"
[pass]
(. BCrypt hashpw pass (. BCrypt gensalt 13)))
(defn check-bcrypt
"check a raw password against a hash from the password field"
[pass hash]
(. BCrypt checkpw pass hash))
(def ^{:dynamic true} *default-hash* "SHA-256")
(defn hexdigest
"Returns the hex digest of an object. Expects a string as input."
([input] (hexdigest input *default-hash*))
([input hash-algo]
(if (string? input)
(let [hash (MessageDigest/getInstance hash-algo)]
(. hash update (.getBytes input))
(let [digest (.digest hash)]
(apply str (map #(format "%02x" (bit-and % 0xff)) digest))))
(do
(println "Invalid input! Expected string, got" (type input))
nil))))
(defn checkhex [obj ref-hash]
(= ref-hash (hexdigest obj)))
(def hash-password hexdigest)
(def check-password checkhex)
| |
56ad8325efb610a9aca100a582ee8b1682c19cc107d22bc799d721670b8bf27e | tochicool/bitcoin-dca | Coinbase.hs | # LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE InstanceSigs #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module BitcoinDCA.Exchange.Coinbase where
import BitcoinDCA.Common
import BitcoinDCA.Exchange
import qualified BitcoinDCA.Exchange.Coinbase.API as API
import BitcoinDCA.Types
import Control.Arrow ((>>>))
import Control.Concurrent.Forkable (ForkableMonad (forkIO))
import Control.Monad.Except (MonadError)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Reader (ReaderT (..), ask)
import Control.Monad.Trans (MonadTrans (lift))
import qualified Data.ByteString as BS
import Data.Coerce (coerce)
import Data.Functor (void)
import Data.Maybe (fromMaybe)
import Data.UUID (fromASCIIBytes, toASCIIBytes)
import GHC.TypeLits (KnownSymbol)
import Servant.Client (ClientError, ClientM)
import Servant.Client.Internal.HttpClient.Extended ()
import UnliftIO (MonadUnliftIO)
newtype Coinbase a = Coinbase {unCoinbase :: ReaderT API.Config ClientM a}
deriving newtype (Functor, Applicative, Monad, MonadError ClientError, MonadIO, MonadUnliftIO)
fromCurrencyIdPair :: AssetId -> AssetId -> API.ProductId
fromCurrencyIdPair base quote =
API.ProductId $ BS.concat [coerce base, "-", coerce quote]
fromAPIOrderStatus :: API.OrderStatus -> OrderStatus
fromAPIOrderStatus = \case
API.Pending -> OrderPending
API.Done -> OrderComplete
_ -> OrderFailed
instance MonadExchange Coinbase where
type ExchangeError Coinbase = ClientError
type ExchangeConfig Coinbase = API.Config
getAssetPair :: forall base quote. (KnownSymbol base, KnownSymbol quote) => Coinbase (Maybe (AssetPair base quote))
getAssetPair = Coinbase . lift . expectNotFound $
do
API.Product {..} <- API.getProduct $ fromCurrencyIdPair (assetId @base) (assetId @quote)
return
AssetPair
{ base = coerce baseCurrency,
quote = coerce quoteCurrency,
minMarketFunds = 0,
maxMarketFunds = Nothing,
quoteIncrement = coerce quoteIncrement
}
placeMarketBuyOrder :: forall base quote. (KnownSymbol base, KnownSymbol quote) => Money quote -> Coinbase (OrderId, Maybe (Order base))
placeMarketBuyOrder amount = Coinbase . lift $
do
API.FundsMarketOrder {..} <-
API.placeFundsMarketOrder
API.FundsMarketOrderRequest
{ side = API.Buy,
productId = fromCurrencyIdPair (assetId @base) (assetId @quote),
funds = API.Funds . coerce $ amount
}
let orderId = coerce . toASCIIBytes . coerce $ id
return
( orderId,
Just Order {id = orderId, status = fromAPIOrderStatus status, filledSize = coerce filledSize}
)
getOrder (OrderId orderId)
| Just uuid <- fromASCIIBytes orderId = Coinbase . lift $
do
API.Order {..} <- API.getOrder . API.ClientOrderId $ uuid
let receivedOrderId = coerce . toASCIIBytes . coerce $ id
return . Just $
Order
{ id = receivedOrderId,
status = fromAPIOrderStatus status,
filledSize = coerce filledSize
}
| otherwise = Coinbase . lift . return $ Nothing
getAsset :: forall asset. KnownSymbol asset => Coinbase (Maybe (Asset asset))
getAsset = Coinbase . lift . expectNotFound $
do
let AssetId c = assetId @asset
API.CurrencyResponse {details = API.CurrencyResponseDetails {..}, ..} <- API.getCurrency . API.CurrencyId $ c
return
Asset
{ id = coerce id,
maxPrecision = coerce maxPrecision,
minWithdrawalAmount = fromMaybe 0 $ coerce minWithdrawalAmount,
maxWithdrawalAmount = coerce maxWithdrawalAmount
}
withdraw :: forall asset. KnownSymbol asset => Address -> Money asset -> Coinbase WithdrawId
withdraw address funds = Coinbase . lift $ do
API.WithdrawCryptoResponse {..} <-
API.withdrawCrypto $
API.WithdrawCryptoRequest
{ currency = coerce $ assetId @asset,
cryptoAddress = coerce address,
amount = coerce funds
}
return . coerce . toASCIIBytes . coerce $ id
getWithdraw (WithdrawId withdrawId)
| Just uuid <- fromASCIIBytes withdrawId = Coinbase . lift . expectNotFound $ do
API.Withdraw {..} <- API.getTransfer . API.WithdrawId $ uuid
let receivedWithdrawId = coerce . toASCIIBytes . coerce $ id
return
Withdraw
{ id = receivedWithdrawId,
status = case (completedAt, cancelledAt) of
(Just _, _) -> WithdrawComplete
(_, Just _) -> WithdrawFailed
(_, _) -> WithdrawPending
}
| otherwise = Coinbase . lift . return $ Nothing
instance MonadIO m => RunnableExchange m Coinbase where
runExchange config =
unCoinbase
>>> flip runReaderT config
>>> API.authenticateAndRunClientM config
>>> liftIO
instance ForkableMonad Coinbase where
forkIO m = do
config <- Coinbase ask
liftIO . forkIO . void . runExchange config $ m
| null | https://raw.githubusercontent.com/tochicool/bitcoin-dca/642016f54595194127fcbd24ff11e0d7b358b011/src/BitcoinDCA/Exchange/Coinbase.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE InstanceSigs #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module BitcoinDCA.Exchange.Coinbase where
import BitcoinDCA.Common
import BitcoinDCA.Exchange
import qualified BitcoinDCA.Exchange.Coinbase.API as API
import BitcoinDCA.Types
import Control.Arrow ((>>>))
import Control.Concurrent.Forkable (ForkableMonad (forkIO))
import Control.Monad.Except (MonadError)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Reader (ReaderT (..), ask)
import Control.Monad.Trans (MonadTrans (lift))
import qualified Data.ByteString as BS
import Data.Coerce (coerce)
import Data.Functor (void)
import Data.Maybe (fromMaybe)
import Data.UUID (fromASCIIBytes, toASCIIBytes)
import GHC.TypeLits (KnownSymbol)
import Servant.Client (ClientError, ClientM)
import Servant.Client.Internal.HttpClient.Extended ()
import UnliftIO (MonadUnliftIO)
newtype Coinbase a = Coinbase {unCoinbase :: ReaderT API.Config ClientM a}
deriving newtype (Functor, Applicative, Monad, MonadError ClientError, MonadIO, MonadUnliftIO)
fromCurrencyIdPair :: AssetId -> AssetId -> API.ProductId
fromCurrencyIdPair base quote =
API.ProductId $ BS.concat [coerce base, "-", coerce quote]
fromAPIOrderStatus :: API.OrderStatus -> OrderStatus
fromAPIOrderStatus = \case
API.Pending -> OrderPending
API.Done -> OrderComplete
_ -> OrderFailed
instance MonadExchange Coinbase where
type ExchangeError Coinbase = ClientError
type ExchangeConfig Coinbase = API.Config
getAssetPair :: forall base quote. (KnownSymbol base, KnownSymbol quote) => Coinbase (Maybe (AssetPair base quote))
getAssetPair = Coinbase . lift . expectNotFound $
do
API.Product {..} <- API.getProduct $ fromCurrencyIdPair (assetId @base) (assetId @quote)
return
AssetPair
{ base = coerce baseCurrency,
quote = coerce quoteCurrency,
minMarketFunds = 0,
maxMarketFunds = Nothing,
quoteIncrement = coerce quoteIncrement
}
placeMarketBuyOrder :: forall base quote. (KnownSymbol base, KnownSymbol quote) => Money quote -> Coinbase (OrderId, Maybe (Order base))
placeMarketBuyOrder amount = Coinbase . lift $
do
API.FundsMarketOrder {..} <-
API.placeFundsMarketOrder
API.FundsMarketOrderRequest
{ side = API.Buy,
productId = fromCurrencyIdPair (assetId @base) (assetId @quote),
funds = API.Funds . coerce $ amount
}
let orderId = coerce . toASCIIBytes . coerce $ id
return
( orderId,
Just Order {id = orderId, status = fromAPIOrderStatus status, filledSize = coerce filledSize}
)
getOrder (OrderId orderId)
| Just uuid <- fromASCIIBytes orderId = Coinbase . lift $
do
API.Order {..} <- API.getOrder . API.ClientOrderId $ uuid
let receivedOrderId = coerce . toASCIIBytes . coerce $ id
return . Just $
Order
{ id = receivedOrderId,
status = fromAPIOrderStatus status,
filledSize = coerce filledSize
}
| otherwise = Coinbase . lift . return $ Nothing
getAsset :: forall asset. KnownSymbol asset => Coinbase (Maybe (Asset asset))
getAsset = Coinbase . lift . expectNotFound $
do
let AssetId c = assetId @asset
API.CurrencyResponse {details = API.CurrencyResponseDetails {..}, ..} <- API.getCurrency . API.CurrencyId $ c
return
Asset
{ id = coerce id,
maxPrecision = coerce maxPrecision,
minWithdrawalAmount = fromMaybe 0 $ coerce minWithdrawalAmount,
maxWithdrawalAmount = coerce maxWithdrawalAmount
}
withdraw :: forall asset. KnownSymbol asset => Address -> Money asset -> Coinbase WithdrawId
withdraw address funds = Coinbase . lift $ do
API.WithdrawCryptoResponse {..} <-
API.withdrawCrypto $
API.WithdrawCryptoRequest
{ currency = coerce $ assetId @asset,
cryptoAddress = coerce address,
amount = coerce funds
}
return . coerce . toASCIIBytes . coerce $ id
getWithdraw (WithdrawId withdrawId)
| Just uuid <- fromASCIIBytes withdrawId = Coinbase . lift . expectNotFound $ do
API.Withdraw {..} <- API.getTransfer . API.WithdrawId $ uuid
let receivedWithdrawId = coerce . toASCIIBytes . coerce $ id
return
Withdraw
{ id = receivedWithdrawId,
status = case (completedAt, cancelledAt) of
(Just _, _) -> WithdrawComplete
(_, Just _) -> WithdrawFailed
(_, _) -> WithdrawPending
}
| otherwise = Coinbase . lift . return $ Nothing
instance MonadIO m => RunnableExchange m Coinbase where
runExchange config =
unCoinbase
>>> flip runReaderT config
>>> API.authenticateAndRunClientM config
>>> liftIO
instance ForkableMonad Coinbase where
forkIO m = do
config <- Coinbase ask
liftIO . forkIO . void . runExchange config $ m
|
ed0591b859a5a9974de276c5436a3b7e3f93ac021436a717b665b15761ff85e1 | mirage/alcotest | unicode_testname.ml | let () =
Alcotest.run
"Suite name containing file separators / and non-ASCII characters 🔥"
[
( "🔥",
[
Alcotest.test_case "Non ASCII unicode character" `Quick (fun () -> ());
] );
( "🔥a-b",
[
Alcotest.test_case "Non ASCII and ASCII characters" `Quick (fun () ->
());
] );
]
| null | https://raw.githubusercontent.com/mirage/alcotest/bb3492901dea03c72b4de6b5660852a020283921/test/e2e/alcotest/passing/unicode_testname.ml | ocaml | let () =
Alcotest.run
"Suite name containing file separators / and non-ASCII characters 🔥"
[
( "🔥",
[
Alcotest.test_case "Non ASCII unicode character" `Quick (fun () -> ());
] );
( "🔥a-b",
[
Alcotest.test_case "Non ASCII and ASCII characters" `Quick (fun () ->
());
] );
]
| |
187b001237ad43ed030ba1974bd8d4964e4277c26ed79eba3fa16e0231519e5d | haskell-hvr/cryptohash-sha1 | FFI.hs | # LANGUAGE CApiFFI #
# LANGUAGE Unsafe #
-- Ugly hack to workaround
{-# OPTIONS_GHC -O0
-fdo-lambda-eta-expansion
-fcase-merge
-fstrictness
-fno-omit-interface-pragmas
-fno-ignore-interface-pragmas #-}
{-# OPTIONS_GHC -optc-Wall -optc-O3 #-}
-- |
-- Module : Crypto.Hash.SHA1.FFI
-- License : BSD-3
--
module Crypto.Hash.SHA1.FFI where
import Data.ByteString (ByteString)
import Data.Word
import Foreign.C.Types
import Foreign.Ptr
-- | SHA-1 Context
--
The context data is exactly 92 bytes long , however
-- the data in the context is stored in host-endianness.
--
-- The context data is made up of
--
-- * a 'Word64' representing the number of bytes already feed to hash algorithm so far,
--
* a 64 - element ' Word8 ' buffer holding partial input - chunks , and finally
--
* a 5 - element ' ' array holding the current work - in - progress digest - value .
--
Consequently , a SHA-1 digest as produced by ' hash ' , ' hashlazy ' , or ' finalize ' is 20 bytes long .
newtype Ctx = Ctx ByteString
deriving (Eq)
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_init"
c_sha1_init :: Ptr Ctx -> IO ()
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_update"
c_sha1_update_unsafe :: Ptr Ctx -> Ptr Word8 -> CSize -> IO ()
foreign import capi safe "sha1.h hs_cryptohash_sha1_update"
c_sha1_update_safe :: Ptr Ctx -> Ptr Word8 -> CSize -> IO ()
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_finalize"
c_sha1_finalize :: Ptr Ctx -> Ptr Word8 -> IO ()
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_finalize"
c_sha1_finalize_len :: Ptr Ctx -> Ptr Word8 -> IO Word64
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_hash"
c_sha1_hash_unsafe :: Ptr Word8 -> CSize -> Ptr Word8 -> IO ()
foreign import capi safe "sha1.h hs_cryptohash_sha1_hash"
c_sha1_hash_safe :: Ptr Word8 -> CSize -> Ptr Word8 -> IO ()
| null | https://raw.githubusercontent.com/haskell-hvr/cryptohash-sha1/e857b23933ce724af9ec2d60d0432f3fd234c899/src/Crypto/Hash/SHA1/FFI.hs | haskell | Ugly hack to workaround
# OPTIONS_GHC -O0
-fdo-lambda-eta-expansion
-fcase-merge
-fstrictness
-fno-omit-interface-pragmas
-fno-ignore-interface-pragmas #
# OPTIONS_GHC -optc-Wall -optc-O3 #
|
Module : Crypto.Hash.SHA1.FFI
License : BSD-3
| SHA-1 Context
the data in the context is stored in host-endianness.
The context data is made up of
* a 'Word64' representing the number of bytes already feed to hash algorithm so far,
| # LANGUAGE CApiFFI #
# LANGUAGE Unsafe #
module Crypto.Hash.SHA1.FFI where
import Data.ByteString (ByteString)
import Data.Word
import Foreign.C.Types
import Foreign.Ptr
The context data is exactly 92 bytes long , however
* a 64 - element ' Word8 ' buffer holding partial input - chunks , and finally
* a 5 - element ' ' array holding the current work - in - progress digest - value .
Consequently , a SHA-1 digest as produced by ' hash ' , ' hashlazy ' , or ' finalize ' is 20 bytes long .
newtype Ctx = Ctx ByteString
deriving (Eq)
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_init"
c_sha1_init :: Ptr Ctx -> IO ()
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_update"
c_sha1_update_unsafe :: Ptr Ctx -> Ptr Word8 -> CSize -> IO ()
foreign import capi safe "sha1.h hs_cryptohash_sha1_update"
c_sha1_update_safe :: Ptr Ctx -> Ptr Word8 -> CSize -> IO ()
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_finalize"
c_sha1_finalize :: Ptr Ctx -> Ptr Word8 -> IO ()
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_finalize"
c_sha1_finalize_len :: Ptr Ctx -> Ptr Word8 -> IO Word64
foreign import capi unsafe "sha1.h hs_cryptohash_sha1_hash"
c_sha1_hash_unsafe :: Ptr Word8 -> CSize -> Ptr Word8 -> IO ()
foreign import capi safe "sha1.h hs_cryptohash_sha1_hash"
c_sha1_hash_safe :: Ptr Word8 -> CSize -> Ptr Word8 -> IO ()
|
ec4021ee6e9cc35190678f82556244ad47001a3997b1ef263b1c01552e4e7663 | softlab-ntua/bencherl | rm_chord.erl | 2008 - 2011 Zuse Institute Berlin
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.
@author < >
%% @doc Chord-like ring maintenance
%% @end
@version $ I d : rm_chord.erl 2639 2012 - 01 - 03 15:00:45Z $
-module(rm_chord).
-author('').
-vsn('$Id: rm_chord.erl 2639 2012-01-03 15:00:45Z $').
-include("scalaris.hrl").
-behavior(rm_beh).
-type(state() :: {Neighbors :: nodelist:neighborhood(),
TriggerState :: trigger:state()}).
% accepted messages of an initialized rm_chord process in addition to rm_loop
-type(custom_message() ::
{rm_trigger} |
{rm, get_succlist, Source_Pid::comm:mypid()} |
{{get_node_details_response, NodeDetails::node_details:node_details()}, rm} |
{rm, get_succlist_response, Succ::node:node_type(), SuccsSuccList::nodelist:non_empty_snodelist()}).
-define(SEND_OPTIONS, [{channel, prio}]).
note include after the type definitions for erlang < R13B04 !
-include("rm_beh.hrl").
-spec get_neighbors(state()) -> nodelist:neighborhood().
get_neighbors({Neighbors, _TriggerState}) ->
Neighbors.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Startup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@doc Initialises the state when rm_loop receives an init_rm message .
-spec init(Me::node:node_type(), Pred::node:node_type(),
Succ::node:node_type()) -> state().
init(Me, Pred, Succ) ->
Trigger = config:read(ringmaintenance_trigger),
TriggerState = trigger:init(Trigger, fun stabilizationInterval/0, rm_trigger),
NewTriggerState = trigger:now(TriggerState),
Neighborhood = nodelist:new_neighborhood(Pred, Me, Succ),
get_successorlist(node:pidX(Succ)),
{Neighborhood, NewTriggerState}.
-spec unittest_create_state(Neighbors::nodelist:neighborhood()) -> state().
unittest_create_state(Neighbors) ->
Trigger = config:read(ringmaintenance_trigger),
TriggerState = trigger:init(Trigger, fun stabilizationInterval/0, rm_trigger),
{Neighbors, TriggerState}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Message Loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% @doc Message handler when the module is fully initialized.
-spec on(custom_message(), state()) -> state() | unknown_event.
on({rm_trigger}, {Neighborhood, TriggerState}) ->
% new stabilization interval
case nodelist:has_real_succ(Neighborhood) of
true -> comm:send(node:pidX(nodelist:succ(Neighborhood)),
{get_node_details, comm:this_with_cookie(rm), [pred]},
?SEND_OPTIONS);
_ -> ok
end,
{Neighborhood, trigger:next(TriggerState)};
on({rm, get_succlist, Source_Pid}, {Neighborhood, _TriggerState} = State) ->
comm:send(Source_Pid, {rm, get_succlist_response,
nodelist:node(Neighborhood),
nodelist:succs(Neighborhood)},
?SEND_OPTIONS),
State;
% got node_details from our successor
on({{get_node_details_response, NodeDetails}, rm},
{OldNeighborhood, TriggerState}) ->
SuccsPred = node_details:get(NodeDetails, pred),
NewNeighborhood = nodelist:add_nodes(OldNeighborhood, [SuccsPred],
predListLength(), succListLength()),
get_successorlist(node:pidX(nodelist:succ(NewNeighborhood))),
{NewNeighborhood, TriggerState};
on({rm, get_succlist_response, Succ, SuccsSuccList},
{OldNeighborhood, TriggerState}) ->
NewNeighborhood = nodelist:add_nodes(OldNeighborhood, [Succ | SuccsSuccList],
predListLength(), succListLength()),
@TODO if(length(NewSuccs ) < succListLength ( ) / 2 ) do something right now
rm_loop:notify_new_pred(node:pidX(nodelist:succ(NewNeighborhood)),
nodelist:node(NewNeighborhood)),
{NewNeighborhood, TriggerState};
on(_, _State) -> unknown_event.
-spec new_pred(State::state(), NewPred::node:node_type()) -> state().
new_pred({OldNeighborhood, TriggerState}, NewPred) ->
NewNeighborhood = nodelist:add_node(OldNeighborhood, NewPred,
predListLength(), succListLength()),
{NewNeighborhood, TriggerState}.
-spec new_succ(State::state(), NewSucc::node:node_type()) -> state().
new_succ({OldNeighborhood, TriggerState}, NewSucc) ->
NewNeighborhood = nodelist:add_node(OldNeighborhood, NewSucc,
predListLength(), succListLength()),
{NewNeighborhood, TriggerState}.
-spec remove_pred(State::state(), OldPred::node:node_type(),
PredsPred::node:node_type()) -> state().
remove_pred({OldNeighborhood, TriggerState}, OldPred, PredsPred) ->
NewNbh1 = nodelist:remove(OldPred, OldNeighborhood),
NewNbh2 = nodelist:add_node(NewNbh1, PredsPred, predListLength(), succListLength()),
{NewNbh2, TriggerState}.
-spec remove_succ(State::state(), OldSucc::node:node_type(),
SuccsSucc::node:node_type()) -> state().
remove_succ({OldNeighborhood, TriggerState}, OldSucc, SuccsSucc) ->
NewNbh1 = nodelist:remove(OldSucc, OldNeighborhood),
NewNbh2 = nodelist:add_node(NewNbh1, SuccsSucc, predListLength(), succListLength()),
{NewNbh2, TriggerState}.
-spec update_node(State::state(), NewMe::node:node_type()) -> state().
update_node({OldNeighborhood, TriggerState}, NewMe) ->
NewNeighborhood = nodelist:update_node(OldNeighborhood, NewMe),
NewTriggerState = trigger:now(TriggerState), % inform neighbors
{NewNeighborhood, NewTriggerState}.
-spec leave(State::state()) -> ok.
leave(_State) -> ok.
% failure detector reported dead node
-spec crashed_node(State::state(), DeadPid::comm:mypid()) -> state().
crashed_node({OldNeighborhood, TriggerState}, DeadPid) ->
NewNeighborhood = nodelist:remove(DeadPid, OldNeighborhood),
{NewNeighborhood, TriggerState}.
% dead-node-cache reported dead node to be alive again
-spec zombie_node(State::state(), Node::node:node_type()) -> state().
zombie_node({OldNeighborhood, TriggerState}, Node) ->
% this node could potentially be useful as it has been in our state before
NewNeighborhood = nodelist:add_node(OldNeighborhood, Node,
predListLength(), succListLength()),
{NewNeighborhood, TriggerState}.
-spec get_web_debug_info(State::state()) -> [{string(), string()}].
get_web_debug_info(_State) -> [].
%% @doc Checks whether config parameters of the rm_chord process exist and are
%% valid.
-spec check_config() -> boolean().
check_config() ->
config:cfg_is_module(ringmaintenance_trigger) and
config:cfg_is_integer(stabilization_interval_max) and
config:cfg_is_greater_than(stabilization_interval_max, 0) and
config:cfg_is_integer(succ_list_length) and
config:cfg_is_greater_than(succ_list_length, 0).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Internal Functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@private
%% @doc Sends a message to the remote node's dht_node process asking for
%% its list of successors.
-spec get_successorlist(comm:mypid()) -> ok.
get_successorlist(RemoteDhtNodePid) ->
comm:send(RemoteDhtNodePid, {rm, get_succlist, comm:this()}, ?SEND_OPTIONS).
%% @doc the length of the successor list
-spec predListLength() -> pos_integer().
predListLength() -> 1.
%% @doc the length of the successor list
-spec succListLength() -> pos_integer().
succListLength() -> config:read(succ_list_length).
@doc the interval between two stabilization runs
-spec stabilizationInterval() -> pos_integer().
stabilizationInterval() -> config:read(stabilization_interval_max).
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/scalaris/src/rm_chord.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.
@doc Chord-like ring maintenance
@end
accepted messages of an initialized rm_chord process in addition to rm_loop
Startup
Message Loop
@doc Message handler when the module is fully initialized.
new stabilization interval
got node_details from our successor
inform neighbors
failure detector reported dead node
dead-node-cache reported dead node to be alive again
this node could potentially be useful as it has been in our state before
@doc Checks whether config parameters of the rm_chord process exist and are
valid.
Internal Functions
@doc Sends a message to the remote node's dht_node process asking for
its list of successors.
@doc the length of the successor list
@doc the length of the successor list | 2008 - 2011 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
@version $ I d : rm_chord.erl 2639 2012 - 01 - 03 15:00:45Z $
-module(rm_chord).
-author('').
-vsn('$Id: rm_chord.erl 2639 2012-01-03 15:00:45Z $').
-include("scalaris.hrl").
-behavior(rm_beh).
-type(state() :: {Neighbors :: nodelist:neighborhood(),
TriggerState :: trigger:state()}).
-type(custom_message() ::
{rm_trigger} |
{rm, get_succlist, Source_Pid::comm:mypid()} |
{{get_node_details_response, NodeDetails::node_details:node_details()}, rm} |
{rm, get_succlist_response, Succ::node:node_type(), SuccsSuccList::nodelist:non_empty_snodelist()}).
-define(SEND_OPTIONS, [{channel, prio}]).
note include after the type definitions for erlang < R13B04 !
-include("rm_beh.hrl").
-spec get_neighbors(state()) -> nodelist:neighborhood().
get_neighbors({Neighbors, _TriggerState}) ->
Neighbors.
@doc Initialises the state when rm_loop receives an init_rm message .
-spec init(Me::node:node_type(), Pred::node:node_type(),
Succ::node:node_type()) -> state().
init(Me, Pred, Succ) ->
Trigger = config:read(ringmaintenance_trigger),
TriggerState = trigger:init(Trigger, fun stabilizationInterval/0, rm_trigger),
NewTriggerState = trigger:now(TriggerState),
Neighborhood = nodelist:new_neighborhood(Pred, Me, Succ),
get_successorlist(node:pidX(Succ)),
{Neighborhood, NewTriggerState}.
-spec unittest_create_state(Neighbors::nodelist:neighborhood()) -> state().
unittest_create_state(Neighbors) ->
Trigger = config:read(ringmaintenance_trigger),
TriggerState = trigger:init(Trigger, fun stabilizationInterval/0, rm_trigger),
{Neighbors, TriggerState}.
-spec on(custom_message(), state()) -> state() | unknown_event.
on({rm_trigger}, {Neighborhood, TriggerState}) ->
case nodelist:has_real_succ(Neighborhood) of
true -> comm:send(node:pidX(nodelist:succ(Neighborhood)),
{get_node_details, comm:this_with_cookie(rm), [pred]},
?SEND_OPTIONS);
_ -> ok
end,
{Neighborhood, trigger:next(TriggerState)};
on({rm, get_succlist, Source_Pid}, {Neighborhood, _TriggerState} = State) ->
comm:send(Source_Pid, {rm, get_succlist_response,
nodelist:node(Neighborhood),
nodelist:succs(Neighborhood)},
?SEND_OPTIONS),
State;
on({{get_node_details_response, NodeDetails}, rm},
{OldNeighborhood, TriggerState}) ->
SuccsPred = node_details:get(NodeDetails, pred),
NewNeighborhood = nodelist:add_nodes(OldNeighborhood, [SuccsPred],
predListLength(), succListLength()),
get_successorlist(node:pidX(nodelist:succ(NewNeighborhood))),
{NewNeighborhood, TriggerState};
on({rm, get_succlist_response, Succ, SuccsSuccList},
{OldNeighborhood, TriggerState}) ->
NewNeighborhood = nodelist:add_nodes(OldNeighborhood, [Succ | SuccsSuccList],
predListLength(), succListLength()),
@TODO if(length(NewSuccs ) < succListLength ( ) / 2 ) do something right now
rm_loop:notify_new_pred(node:pidX(nodelist:succ(NewNeighborhood)),
nodelist:node(NewNeighborhood)),
{NewNeighborhood, TriggerState};
on(_, _State) -> unknown_event.
-spec new_pred(State::state(), NewPred::node:node_type()) -> state().
new_pred({OldNeighborhood, TriggerState}, NewPred) ->
NewNeighborhood = nodelist:add_node(OldNeighborhood, NewPred,
predListLength(), succListLength()),
{NewNeighborhood, TriggerState}.
-spec new_succ(State::state(), NewSucc::node:node_type()) -> state().
new_succ({OldNeighborhood, TriggerState}, NewSucc) ->
NewNeighborhood = nodelist:add_node(OldNeighborhood, NewSucc,
predListLength(), succListLength()),
{NewNeighborhood, TriggerState}.
-spec remove_pred(State::state(), OldPred::node:node_type(),
PredsPred::node:node_type()) -> state().
remove_pred({OldNeighborhood, TriggerState}, OldPred, PredsPred) ->
NewNbh1 = nodelist:remove(OldPred, OldNeighborhood),
NewNbh2 = nodelist:add_node(NewNbh1, PredsPred, predListLength(), succListLength()),
{NewNbh2, TriggerState}.
-spec remove_succ(State::state(), OldSucc::node:node_type(),
SuccsSucc::node:node_type()) -> state().
remove_succ({OldNeighborhood, TriggerState}, OldSucc, SuccsSucc) ->
NewNbh1 = nodelist:remove(OldSucc, OldNeighborhood),
NewNbh2 = nodelist:add_node(NewNbh1, SuccsSucc, predListLength(), succListLength()),
{NewNbh2, TriggerState}.
-spec update_node(State::state(), NewMe::node:node_type()) -> state().
update_node({OldNeighborhood, TriggerState}, NewMe) ->
NewNeighborhood = nodelist:update_node(OldNeighborhood, NewMe),
{NewNeighborhood, NewTriggerState}.
-spec leave(State::state()) -> ok.
leave(_State) -> ok.
-spec crashed_node(State::state(), DeadPid::comm:mypid()) -> state().
crashed_node({OldNeighborhood, TriggerState}, DeadPid) ->
NewNeighborhood = nodelist:remove(DeadPid, OldNeighborhood),
{NewNeighborhood, TriggerState}.
-spec zombie_node(State::state(), Node::node:node_type()) -> state().
zombie_node({OldNeighborhood, TriggerState}, Node) ->
NewNeighborhood = nodelist:add_node(OldNeighborhood, Node,
predListLength(), succListLength()),
{NewNeighborhood, TriggerState}.
-spec get_web_debug_info(State::state()) -> [{string(), string()}].
get_web_debug_info(_State) -> [].
-spec check_config() -> boolean().
check_config() ->
config:cfg_is_module(ringmaintenance_trigger) and
config:cfg_is_integer(stabilization_interval_max) and
config:cfg_is_greater_than(stabilization_interval_max, 0) and
config:cfg_is_integer(succ_list_length) and
config:cfg_is_greater_than(succ_list_length, 0).
@private
-spec get_successorlist(comm:mypid()) -> ok.
get_successorlist(RemoteDhtNodePid) ->
comm:send(RemoteDhtNodePid, {rm, get_succlist, comm:this()}, ?SEND_OPTIONS).
-spec predListLength() -> pos_integer().
predListLength() -> 1.
-spec succListLength() -> pos_integer().
succListLength() -> config:read(succ_list_length).
@doc the interval between two stabilization runs
-spec stabilizationInterval() -> pos_integer().
stabilizationInterval() -> config:read(stabilization_interval_max).
|
404cde9f125ae1e033d1fb3c788a49a2d4d2b857522ef9960fc40083e76d06ae | garrigue/labltk | shell.ml | (*************************************************************************)
(* *)
(* OCaml LablTk library *)
(* *)
, Kyoto University RIMS
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
(* General Public License, with the special exception on linking *)
(* described in file ../../../LICENSE. *)
(* *)
(*************************************************************************)
$ Id$
open StdLabels
module Unix = UnixLabels
open Tk
open Jg_tk
open Dummy
(* Here again, memoize regexps *)
let (~!) = Jg_memo.fast ~f:Str.regexp
Nice history class . May reuse
class ['a] history () = object
val mutable history = ([] : 'a list)
val mutable count = 0
method empty = history = []
method add s = count <- 0; history <- s :: history
method previous =
let s = List.nth history count in
count <- (count + 1) mod List.length history;
s
method next =
let l = List.length history in
count <- (l + count - 1) mod l;
List.nth history ((l + count - 1) mod l)
end
let dump_handle (h : Unix.file_descr) =
let obj = Obj.repr h in
if Obj.is_int obj || Obj.tag obj <> Obj.custom_tag then
invalid_arg "Shell.dump_handle";
Printf.sprintf "%nx" (Obj.obj obj)
(* The shell class. Now encapsulated *)
let protect f x = try f x with _ -> ()
let is_win32 = Sys.os_type = "Win32"
let use_threads = is_win32
let use_sigpipe = is_win32
class shell ~textw ~prog ~args ~env ~history =
let (in2,out1) = Unix.pipe ()
and (in1,out2) = Unix.pipe ()
and (err1,err2) = Unix.pipe ()
and (sig2,sig1) = Unix.pipe () in
object (self)
val pid =
let env =
if use_sigpipe then
let sigdef = "CAMLSIGPIPE=" ^ dump_handle sig2 in
Array.append env [|sigdef|]
else env
in
Unix.create_process_env ~prog ~args ~env
~stdin:in2 ~stdout:out2 ~stderr:err2
val out = Unix.out_channel_of_descr out1
val h : _ history = history
val mutable alive = true
val mutable reading = false
val ibuffer = Buffer.create 1024
val imutex = Mutex.create ()
val mutable ithreads = []
method alive = alive
method kill =
if Winfo.exists textw then Text.configure textw ~state:`Disabled;
if alive then begin
alive <- false;
protect close_out out;
try
if use_sigpipe then
ignore (Unix.write sig1 ~buf:(Bytes.make 1 'T') ~pos:0 ~len:1);
List.iter ~f:(protect Unix.close) [in1; err1; sig1; sig2];
if not use_threads then begin
Fileevent.remove_fileinput ~fd:in1;
Fileevent.remove_fileinput ~fd:err1;
end;
if not use_sigpipe then begin
Unix.kill ~pid ~signal:Sys.sigkill;
ignore (Unix.waitpid ~mode:[] pid)
end
with _ -> ()
end
method interrupt =
if alive then try
reading <- false;
if use_sigpipe then begin
ignore (Unix.write sig1 ~buf:(Bytes.make 1 'C') ~pos:0 ~len:1);
self#send " "
end else
Unix.kill ~pid ~signal:Sys.sigint
with Unix.Unix_error _ -> ()
method send s =
if alive then try
output_string out s;
flush out
with Sys_error _ -> ()
method private read ~fd ~len =
begin try
let buf = Bytes.create len in
let len = Unix.read fd ~buf ~pos:0 ~len in
if len > 0 then begin
self#insert (Bytes.sub_string buf ~pos:0 ~len);
Text.mark_set textw ~mark:"input" ~index:(`Mark"insert",[`Char(-1)])
end;
len
with Unix.Unix_error _ -> 0
end;
method history (dir : [`Next|`Previous]) =
if not h#empty then begin
if reading then begin
Text.delete textw ~start:(`Mark"input",[`Char 1])
~stop:(`Mark"insert",[])
end else begin
reading <- true;
Text.mark_set textw ~mark:"input"
~index:(`Mark"insert",[`Char(-1)])
end;
self#insert (if dir = `Previous then h#previous else h#next)
end
method private lex ?(start = `Mark"insert",[`Linestart])
?(stop = `Mark"insert",[`Lineend]) () =
Lexical.tag textw ~start ~stop
method insert text =
let idx = Text.index textw
~index:(`Mark"insert",[`Char(-1);`Linestart]) in
Text.insert textw ~text ~index:(`Mark"insert",[]);
self#lex ~start:(idx,[`Linestart]) ();
Text.see textw ~index:(`Mark"insert",[])
method private keypress c =
if not reading && c > " " then begin
reading <- true;
Text.mark_set textw ~mark:"input" ~index:(`Mark"insert",[`Char(-1)])
end
method private keyrelease c = if c <> "" then self#lex ()
method private return =
if reading then reading <- false
else Text.mark_set textw ~mark:"input"
~index:(`Mark"insert",[`Linestart;`Char 1]);
Text.mark_set textw ~mark:"insert" ~index:(`Mark"insert",[`Lineend]);
self#lex ~start:(`Mark"input",[`Linestart]) ();
let s =
input is one character before real input
Text.get textw ~start:(`Mark"input",[`Char 1])
~stop:(`Mark"insert",[]) in
h#add s;
Text.insert textw ~index:(`Mark"insert",[]) ~text:"\n";
Text.yview_index textw ~index:(`Mark"insert",[]);
self#send s;
self#send "\n"
method private paste ev =
if not reading then begin
reading <- true;
Text.mark_set textw ~mark:"input"
~index:(`Atxy(ev.ev_MouseX, ev.ev_MouseY),[`Char(-1)])
end
initializer
Lexical.init_tags textw;
let rec bindings =
[ ([], `KeyPress, [`Char], fun ev -> self#keypress ev.ev_Char);
([], `KeyRelease, [`Char], fun ev -> self#keyrelease ev.ev_Char);
(* [], `KeyPressDetail"Return", [], fun _ -> self#return; *)
([], `ButtonPressDetail 2, [`MouseX; `MouseY], self#paste);
([`Alt], `KeyPressDetail"p", [], fun _ -> self#history `Previous);
([`Alt], `KeyPressDetail"n", [], fun _ -> self#history `Next);
([`Meta], `KeyPressDetail"p", [], fun _ -> self#history `Previous);
([`Meta], `KeyPressDetail"n", [], fun _ -> self#history `Next);
([`Control], `KeyPressDetail"c", [], fun _ -> self#interrupt);
([], `Destroy, [], fun _ -> self#kill) ]
in
List.iter bindings ~f:
begin fun (modif,event,fields,action) ->
bind textw ~events:[`Modified(modif,event)] ~fields ~action
end;
bind textw ~events:[`KeyPressDetail"Return"] ~breakable:true
~action:(fun _ -> self#return; break());
List.iter ~f:Unix.close [in2;out2;err2];
if use_threads then begin
let fileinput_thread fd =
let buf = Bytes.create 1024 in
let len = ref 0 in
try while len := Unix.read fd ~buf ~pos:0 ~len:1024; !len > 0 do
Mutex.lock imutex;
Buffer.add_subbytes ibuffer buf 0 !len;
Mutex.unlock imutex
done with Unix.Unix_error _ -> ()
in
ithreads <- List.map [in1; err1] ~f:(Thread.create fileinput_thread);
let rec read_buffer () =
Mutex.lock imutex;
if Buffer.length ibuffer > 0 then begin
self#insert (Str.global_replace ~!"\r\n" "\n"
(Buffer.contents ibuffer));
Buffer.reset ibuffer;
Text.mark_set textw ~mark:"input" ~index:(`Mark"insert",[`Char(-1)])
end;
Mutex.unlock imutex;
Timer.set ~ms:100 ~callback:read_buffer
in
read_buffer ()
end else begin
try
List.iter [in1;err1] ~f:
begin fun fd ->
Fileevent.add_fileinput ~fd
~callback:(fun () -> ignore (self#read ~fd ~len:1024))
end
with _ -> ()
end
end
(* Specific use of shell, for OCamlBrowser *)
let shells : (string * shell) list ref = ref []
(* Called before exiting *)
let kill_all () =
List.iter !shells ~f:(fun (_,sh) -> if sh#alive then sh#kill);
shells := []
let get_all () =
let all = List.filter !shells ~f:(fun (_,sh) -> sh#alive) in
shells := all;
all
let may_exec_unix prog =
try Unix.access prog ~perm:[Unix.X_OK]; prog
with Unix.Unix_error _ -> ""
let may_exec_win prog =
let has_ext =
List.exists ~f:(Filename.check_suffix prog) ["exe"; "com"; "bat"] in
if has_ext then may_exec_unix prog else
List.fold_left [prog^".bat"; prog^".exe"; prog^".com"] ~init:""
~f:(fun res prog -> if res = "" then may_exec_unix prog else res)
let may_exec =
if is_win32 then may_exec_win else may_exec_unix
let path_sep = if is_win32 then ";" else ":"
let warnings = ref Warnings.defaults_w
let program_not_found prog =
Jg_message.info ~title:"Error"
("Program \"" ^ prog ^ "\"\nwas not found in path")
let protect_arg s =
if String.contains s ' ' then "\"" ^ s ^ "\"" else s
let f ~prog ~title =
let progargs =
List.filter ~f:((<>) "") (Str.split ~!" " prog) in
if progargs = [] then () else
let prog = List.hd progargs in
let path =
try Sys.getenv "PATH" with Not_found -> "/bin" ^ path_sep ^ "/usr/bin" in
let exec_path = Str.split ~!path_sep path in
let exec_path = if is_win32 then "."::exec_path else exec_path in
let progpath =
if not (Filename.is_implicit prog) then may_exec prog else
List.fold_left exec_path ~init:"" ~f:
(fun res dir ->
if res = "" then may_exec (Filename.concat dir prog) else res) in
if progpath = "" then program_not_found prog else
let tl = Jg_toplevel.titled title in
let menus = Menu.create tl ~name:"menubar" ~typ:`Menubar in
Toplevel.configure tl ~menu:menus;
let file_menu = new Jg_menu.c "File" ~parent:menus
and history_menu = new Jg_menu.c "History" ~parent:menus
and signal_menu = new Jg_menu.c "Signal" ~parent:menus in
let frame, tw, sb = Jg_text.create_with_scrollbar tl in
Text.configure tw ~background:`White;
pack [sb] ~fill:`Y ~side:`Right;
pack [tw] ~fill:`Both ~expand:true ~side:`Left;
pack [frame] ~fill:`Both ~expand:true;
let env = Array.map (Unix.environment ()) ~f:
begin fun s ->
if Str.string_match ~!"TERM=" s 0 then "TERM=dumb" else s
end in
let load_path =
List2.flat_map (Load_path.get_paths ()) ~f:(fun dir -> ["-I"; dir]) in
let load_path =
if is_win32 then List.map ~f:protect_arg load_path else load_path in
let labels = if !Clflags.classic then ["-nolabels"] else [] in
let rectypes = if !Clflags.recursive_types then ["-rectypes"] else [] in
let warnings =
if List.mem "-w" ~set:progargs || !warnings = "Al" then []
else ["-w"; !warnings]
in
let args =
Array.of_list (progargs @ labels @ warnings @ rectypes @ load_path) in
let history = new history () in
let start_shell () =
let sh = new shell ~textw:tw ~prog:progpath ~env ~args ~history in
shells := (title, sh) :: !shells;
sh
in
let sh = ref (start_shell ()) in
let current_dir = ref (Unix.getcwd ()) in
file_menu#add_command "Restart" ~command:
begin fun () ->
(!sh)#kill;
Text.configure tw ~state:`Normal;
Text.insert tw ~index:(`End,[]) ~text:"\n";
Text.see tw ~index:(`End,[]);
Text.mark_set tw ~mark:"insert" ~index:(`End,[]);
sh := start_shell ();
end;
file_menu#add_command "Use..." ~command:
begin fun () ->
Fileselect.f ~title:"Use File" ~filter:"*.ml"
~sync:true ~dir:!current_dir ()
~action:(fun l ->
if l = [] then () else
let name = Fileselect.caml_dir (List.hd l) in
current_dir := Filename.dirname name;
if Filename.check_suffix name ".ml"
then
let cmd = "#use \"" ^ String.escaped name ^ "\";;\n" in
(!sh)#insert cmd; (!sh)#send cmd)
end;
file_menu#add_command "Load..." ~command:
begin fun () ->
Fileselect.f ~title:"Load File" ~filter:"*.cm[oa]" ~sync:true ()
~dir:!current_dir
~action:(fun l ->
if l = [] then () else
let name = Fileselect.caml_dir (List.hd l) in
current_dir := Filename.dirname name;
if Filename.check_suffix name ".cmo" ||
Filename.check_suffix name ".cma"
then
let cmd = "#load \"" ^ String.escaped name ^ "\";;\n" in
(!sh)#insert cmd; (!sh)#send cmd)
end;
file_menu#add_command "Import path" ~command:
begin fun () ->
List.iter (List.rev (Load_path.get_paths ())) ~f:
(fun dir ->
(!sh)#send ("#directory \"" ^ String.escaped dir ^ "\";;\n"))
end;
file_menu#add_command "Close" ~command:(fun () -> destroy tl);
history_menu#add_command "Previous " ~accelerator:"M-p"
~command:(fun () -> (!sh)#history `Previous);
history_menu#add_command "Next" ~accelerator:"M-n"
~command:(fun () -> (!sh)#history `Next);
signal_menu#add_command "Interrupt " ~accelerator:"C-c"
~command:(fun () -> (!sh)#interrupt);
signal_menu#add_command "Kill" ~command:(fun () -> (!sh)#kill)
| null | https://raw.githubusercontent.com/garrigue/labltk/441705df2d88de01bc6aa28c31cc45e40751ee20/browser/shell.ml | ocaml | ***********************************************************************
OCaml LablTk library
General Public License, with the special exception on linking
described in file ../../../LICENSE.
***********************************************************************
Here again, memoize regexps
The shell class. Now encapsulated
[], `KeyPressDetail"Return", [], fun _ -> self#return;
Specific use of shell, for OCamlBrowser
Called before exiting | , Kyoto University RIMS
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
$ Id$
open StdLabels
module Unix = UnixLabels
open Tk
open Jg_tk
open Dummy
let (~!) = Jg_memo.fast ~f:Str.regexp
Nice history class . May reuse
class ['a] history () = object
val mutable history = ([] : 'a list)
val mutable count = 0
method empty = history = []
method add s = count <- 0; history <- s :: history
method previous =
let s = List.nth history count in
count <- (count + 1) mod List.length history;
s
method next =
let l = List.length history in
count <- (l + count - 1) mod l;
List.nth history ((l + count - 1) mod l)
end
let dump_handle (h : Unix.file_descr) =
let obj = Obj.repr h in
if Obj.is_int obj || Obj.tag obj <> Obj.custom_tag then
invalid_arg "Shell.dump_handle";
Printf.sprintf "%nx" (Obj.obj obj)
let protect f x = try f x with _ -> ()
let is_win32 = Sys.os_type = "Win32"
let use_threads = is_win32
let use_sigpipe = is_win32
class shell ~textw ~prog ~args ~env ~history =
let (in2,out1) = Unix.pipe ()
and (in1,out2) = Unix.pipe ()
and (err1,err2) = Unix.pipe ()
and (sig2,sig1) = Unix.pipe () in
object (self)
val pid =
let env =
if use_sigpipe then
let sigdef = "CAMLSIGPIPE=" ^ dump_handle sig2 in
Array.append env [|sigdef|]
else env
in
Unix.create_process_env ~prog ~args ~env
~stdin:in2 ~stdout:out2 ~stderr:err2
val out = Unix.out_channel_of_descr out1
val h : _ history = history
val mutable alive = true
val mutable reading = false
val ibuffer = Buffer.create 1024
val imutex = Mutex.create ()
val mutable ithreads = []
method alive = alive
method kill =
if Winfo.exists textw then Text.configure textw ~state:`Disabled;
if alive then begin
alive <- false;
protect close_out out;
try
if use_sigpipe then
ignore (Unix.write sig1 ~buf:(Bytes.make 1 'T') ~pos:0 ~len:1);
List.iter ~f:(protect Unix.close) [in1; err1; sig1; sig2];
if not use_threads then begin
Fileevent.remove_fileinput ~fd:in1;
Fileevent.remove_fileinput ~fd:err1;
end;
if not use_sigpipe then begin
Unix.kill ~pid ~signal:Sys.sigkill;
ignore (Unix.waitpid ~mode:[] pid)
end
with _ -> ()
end
method interrupt =
if alive then try
reading <- false;
if use_sigpipe then begin
ignore (Unix.write sig1 ~buf:(Bytes.make 1 'C') ~pos:0 ~len:1);
self#send " "
end else
Unix.kill ~pid ~signal:Sys.sigint
with Unix.Unix_error _ -> ()
method send s =
if alive then try
output_string out s;
flush out
with Sys_error _ -> ()
method private read ~fd ~len =
begin try
let buf = Bytes.create len in
let len = Unix.read fd ~buf ~pos:0 ~len in
if len > 0 then begin
self#insert (Bytes.sub_string buf ~pos:0 ~len);
Text.mark_set textw ~mark:"input" ~index:(`Mark"insert",[`Char(-1)])
end;
len
with Unix.Unix_error _ -> 0
end;
method history (dir : [`Next|`Previous]) =
if not h#empty then begin
if reading then begin
Text.delete textw ~start:(`Mark"input",[`Char 1])
~stop:(`Mark"insert",[])
end else begin
reading <- true;
Text.mark_set textw ~mark:"input"
~index:(`Mark"insert",[`Char(-1)])
end;
self#insert (if dir = `Previous then h#previous else h#next)
end
method private lex ?(start = `Mark"insert",[`Linestart])
?(stop = `Mark"insert",[`Lineend]) () =
Lexical.tag textw ~start ~stop
method insert text =
let idx = Text.index textw
~index:(`Mark"insert",[`Char(-1);`Linestart]) in
Text.insert textw ~text ~index:(`Mark"insert",[]);
self#lex ~start:(idx,[`Linestart]) ();
Text.see textw ~index:(`Mark"insert",[])
method private keypress c =
if not reading && c > " " then begin
reading <- true;
Text.mark_set textw ~mark:"input" ~index:(`Mark"insert",[`Char(-1)])
end
method private keyrelease c = if c <> "" then self#lex ()
method private return =
if reading then reading <- false
else Text.mark_set textw ~mark:"input"
~index:(`Mark"insert",[`Linestart;`Char 1]);
Text.mark_set textw ~mark:"insert" ~index:(`Mark"insert",[`Lineend]);
self#lex ~start:(`Mark"input",[`Linestart]) ();
let s =
input is one character before real input
Text.get textw ~start:(`Mark"input",[`Char 1])
~stop:(`Mark"insert",[]) in
h#add s;
Text.insert textw ~index:(`Mark"insert",[]) ~text:"\n";
Text.yview_index textw ~index:(`Mark"insert",[]);
self#send s;
self#send "\n"
method private paste ev =
if not reading then begin
reading <- true;
Text.mark_set textw ~mark:"input"
~index:(`Atxy(ev.ev_MouseX, ev.ev_MouseY),[`Char(-1)])
end
initializer
Lexical.init_tags textw;
let rec bindings =
[ ([], `KeyPress, [`Char], fun ev -> self#keypress ev.ev_Char);
([], `KeyRelease, [`Char], fun ev -> self#keyrelease ev.ev_Char);
([], `ButtonPressDetail 2, [`MouseX; `MouseY], self#paste);
([`Alt], `KeyPressDetail"p", [], fun _ -> self#history `Previous);
([`Alt], `KeyPressDetail"n", [], fun _ -> self#history `Next);
([`Meta], `KeyPressDetail"p", [], fun _ -> self#history `Previous);
([`Meta], `KeyPressDetail"n", [], fun _ -> self#history `Next);
([`Control], `KeyPressDetail"c", [], fun _ -> self#interrupt);
([], `Destroy, [], fun _ -> self#kill) ]
in
List.iter bindings ~f:
begin fun (modif,event,fields,action) ->
bind textw ~events:[`Modified(modif,event)] ~fields ~action
end;
bind textw ~events:[`KeyPressDetail"Return"] ~breakable:true
~action:(fun _ -> self#return; break());
List.iter ~f:Unix.close [in2;out2;err2];
if use_threads then begin
let fileinput_thread fd =
let buf = Bytes.create 1024 in
let len = ref 0 in
try while len := Unix.read fd ~buf ~pos:0 ~len:1024; !len > 0 do
Mutex.lock imutex;
Buffer.add_subbytes ibuffer buf 0 !len;
Mutex.unlock imutex
done with Unix.Unix_error _ -> ()
in
ithreads <- List.map [in1; err1] ~f:(Thread.create fileinput_thread);
let rec read_buffer () =
Mutex.lock imutex;
if Buffer.length ibuffer > 0 then begin
self#insert (Str.global_replace ~!"\r\n" "\n"
(Buffer.contents ibuffer));
Buffer.reset ibuffer;
Text.mark_set textw ~mark:"input" ~index:(`Mark"insert",[`Char(-1)])
end;
Mutex.unlock imutex;
Timer.set ~ms:100 ~callback:read_buffer
in
read_buffer ()
end else begin
try
List.iter [in1;err1] ~f:
begin fun fd ->
Fileevent.add_fileinput ~fd
~callback:(fun () -> ignore (self#read ~fd ~len:1024))
end
with _ -> ()
end
end
let shells : (string * shell) list ref = ref []
let kill_all () =
List.iter !shells ~f:(fun (_,sh) -> if sh#alive then sh#kill);
shells := []
let get_all () =
let all = List.filter !shells ~f:(fun (_,sh) -> sh#alive) in
shells := all;
all
let may_exec_unix prog =
try Unix.access prog ~perm:[Unix.X_OK]; prog
with Unix.Unix_error _ -> ""
let may_exec_win prog =
let has_ext =
List.exists ~f:(Filename.check_suffix prog) ["exe"; "com"; "bat"] in
if has_ext then may_exec_unix prog else
List.fold_left [prog^".bat"; prog^".exe"; prog^".com"] ~init:""
~f:(fun res prog -> if res = "" then may_exec_unix prog else res)
let may_exec =
if is_win32 then may_exec_win else may_exec_unix
let path_sep = if is_win32 then ";" else ":"
let warnings = ref Warnings.defaults_w
let program_not_found prog =
Jg_message.info ~title:"Error"
("Program \"" ^ prog ^ "\"\nwas not found in path")
let protect_arg s =
if String.contains s ' ' then "\"" ^ s ^ "\"" else s
let f ~prog ~title =
let progargs =
List.filter ~f:((<>) "") (Str.split ~!" " prog) in
if progargs = [] then () else
let prog = List.hd progargs in
let path =
try Sys.getenv "PATH" with Not_found -> "/bin" ^ path_sep ^ "/usr/bin" in
let exec_path = Str.split ~!path_sep path in
let exec_path = if is_win32 then "."::exec_path else exec_path in
let progpath =
if not (Filename.is_implicit prog) then may_exec prog else
List.fold_left exec_path ~init:"" ~f:
(fun res dir ->
if res = "" then may_exec (Filename.concat dir prog) else res) in
if progpath = "" then program_not_found prog else
let tl = Jg_toplevel.titled title in
let menus = Menu.create tl ~name:"menubar" ~typ:`Menubar in
Toplevel.configure tl ~menu:menus;
let file_menu = new Jg_menu.c "File" ~parent:menus
and history_menu = new Jg_menu.c "History" ~parent:menus
and signal_menu = new Jg_menu.c "Signal" ~parent:menus in
let frame, tw, sb = Jg_text.create_with_scrollbar tl in
Text.configure tw ~background:`White;
pack [sb] ~fill:`Y ~side:`Right;
pack [tw] ~fill:`Both ~expand:true ~side:`Left;
pack [frame] ~fill:`Both ~expand:true;
let env = Array.map (Unix.environment ()) ~f:
begin fun s ->
if Str.string_match ~!"TERM=" s 0 then "TERM=dumb" else s
end in
let load_path =
List2.flat_map (Load_path.get_paths ()) ~f:(fun dir -> ["-I"; dir]) in
let load_path =
if is_win32 then List.map ~f:protect_arg load_path else load_path in
let labels = if !Clflags.classic then ["-nolabels"] else [] in
let rectypes = if !Clflags.recursive_types then ["-rectypes"] else [] in
let warnings =
if List.mem "-w" ~set:progargs || !warnings = "Al" then []
else ["-w"; !warnings]
in
let args =
Array.of_list (progargs @ labels @ warnings @ rectypes @ load_path) in
let history = new history () in
let start_shell () =
let sh = new shell ~textw:tw ~prog:progpath ~env ~args ~history in
shells := (title, sh) :: !shells;
sh
in
let sh = ref (start_shell ()) in
let current_dir = ref (Unix.getcwd ()) in
file_menu#add_command "Restart" ~command:
begin fun () ->
(!sh)#kill;
Text.configure tw ~state:`Normal;
Text.insert tw ~index:(`End,[]) ~text:"\n";
Text.see tw ~index:(`End,[]);
Text.mark_set tw ~mark:"insert" ~index:(`End,[]);
sh := start_shell ();
end;
file_menu#add_command "Use..." ~command:
begin fun () ->
Fileselect.f ~title:"Use File" ~filter:"*.ml"
~sync:true ~dir:!current_dir ()
~action:(fun l ->
if l = [] then () else
let name = Fileselect.caml_dir (List.hd l) in
current_dir := Filename.dirname name;
if Filename.check_suffix name ".ml"
then
let cmd = "#use \"" ^ String.escaped name ^ "\";;\n" in
(!sh)#insert cmd; (!sh)#send cmd)
end;
file_menu#add_command "Load..." ~command:
begin fun () ->
Fileselect.f ~title:"Load File" ~filter:"*.cm[oa]" ~sync:true ()
~dir:!current_dir
~action:(fun l ->
if l = [] then () else
let name = Fileselect.caml_dir (List.hd l) in
current_dir := Filename.dirname name;
if Filename.check_suffix name ".cmo" ||
Filename.check_suffix name ".cma"
then
let cmd = "#load \"" ^ String.escaped name ^ "\";;\n" in
(!sh)#insert cmd; (!sh)#send cmd)
end;
file_menu#add_command "Import path" ~command:
begin fun () ->
List.iter (List.rev (Load_path.get_paths ())) ~f:
(fun dir ->
(!sh)#send ("#directory \"" ^ String.escaped dir ^ "\";;\n"))
end;
file_menu#add_command "Close" ~command:(fun () -> destroy tl);
history_menu#add_command "Previous " ~accelerator:"M-p"
~command:(fun () -> (!sh)#history `Previous);
history_menu#add_command "Next" ~accelerator:"M-n"
~command:(fun () -> (!sh)#history `Next);
signal_menu#add_command "Interrupt " ~accelerator:"C-c"
~command:(fun () -> (!sh)#interrupt);
signal_menu#add_command "Kill" ~command:(fun () -> (!sh)#kill)
|
0888fafd7e49ac473e2d44bff948f83766440f68572e7aae72afbcdd21966f6d | dongcarl/guix | lxde.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 >
Copyright © 2016 < >
Copyright © 2017 Nikita < >
Copyright © 2017 < >
Copyright © 2017 < >
Copyright © 2018–2021 < >
Copyright © 2018 ison < >
Copyright © 2018 , 2019 < >
Copyright © 2018 < >
Copyright © 2019 Meiyo < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages lxde)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages autotools)
#:use-module (gnu packages base)
#:use-module (gnu packages bash)
#:use-module (gnu packages curl)
#:use-module (gnu packages disk)
#:use-module (gnu packages docbook)
#:use-module (gnu packages file-systems)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages gettext)
#:use-module (gnu packages glib)
#:use-module (gnu packages gnome)
#:use-module (gnu packages gtk)
#:use-module (gnu packages image-viewers)
#:use-module (gnu packages libusb)
#:use-module (gnu packages linux)
#:use-module (gnu packages lsof)
#:use-module (gnu packages openbox)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages polkit)
#:use-module (gnu packages text-editors)
#:use-module (gnu packages video)
#:use-module (gnu packages wget)
#:use-module (gnu packages wm)
#:use-module (gnu packages xdisorg)
#:use-module (gnu packages xml)
#:use-module (gnu packages xorg)
#:use-module (guix build-system glib-or-gtk)
#:use-module (guix build-system gnu)
#:use-module (guix build-system trivial)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix utils))
(define-public libfm
(package
(name "libfm")
(version "1.3.2")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
"PCManFM%20%2B%20Libfm%20%28tarball%20release"
"%29/LibFM/" name "-" version ".tar.xz"))
(sha256
(base32
"1rfira3lx8v6scz1aq69925j4vslpp36bmgrrzcfby2c60q2c155"))))
(build-system gnu-build-system)
(inputs `(("glib" ,glib)
("gtk+" ,gtk+-2)))
(native-inputs `(("intltool" ,intltool)
("glib" ,glib "bin") ; for gtester
("libtool" ,libtool)
("menu-cache" ,menu-cache)
("pkg-config" ,pkg-config)
("vala" ,vala)))
(synopsis "File management support (core library)")
(description "LibFM provides file management functions built on top of
Glib/GIO giving a higher-level API.")
(home-page "")
(license license:gpl2+)))
(define-public libfm-extra
(package (inherit libfm)
(name "libfm-extra")
(arguments '(#:configure-flags '("--with-extra-only")))
(inputs `(("glib" ,glib)))
(native-inputs `(("intltool" ,intltool)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(synopsis "File management support (extra library)")
(description "This package contains a stand-alone library which extends the
libFM file management library.")))
(define-public lxappearance
(package
(name "lxappearance")
(version "0.6.3")
(source
(origin
(method url-fetch)
(uri (string-append "mirror/"
"LXAppearance/lxappearance-" version ".tar.xz"))
(sha256
(base32 "0f4bjaamfxxdr9civvy55pa6vv9dx1hjs522gjbbgx7yp1cdh8kj"))))
(build-system gnu-build-system)
(inputs `(("gtk+" ,gtk+-2)))
(native-inputs `(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(synopsis "LXDE GTK+ theme switcher")
(description "LXAppearance is a desktop-independent GTK+ theme switcher
able to change themes, icons, and fonts used by GTK+ applications.")
(home-page "")
(license license:gpl2+)))
(define-public lxrandr
(package
(name "lxrandr")
(version "0.3.2")
(source (origin
(method url-fetch)
(uri (string-append "mirror"
"%20%28monitor%20config%20tool%29/LXRandR%20"
(version-major+minor version) ".x/"
"lxrandr-" version ".tar.xz"))
(sha256
(base32
"04n3vgh3ix12p8jfs4w0dyfq3anbjy33h7g53wbbqqc0f74xyplb"))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'xrandr-absolutely
lxrandr is useless without xrandr and gives an unhelpful error
;; message if it's not in $PATH, so make it a hard dependency.
(lambda* (#:key input #:allow-other-keys)
(substitute* "src/lxrandr.c"
(("(\"|')xrandr\"" _ match)
(string-append match (which "xrandr") "\"")))
#t)))))
(inputs `(("gtk+" ,gtk+-2)
("xrandr" ,xrandr)))
(native-inputs `(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(synopsis "LXDE monitor configuration tool")
(description "LXRandR is a very basic monitor configuration tool. It
relies on the X11 resize-and-rotate (RandR) extension but doesn't aim to be a
full frontend of it. LXRandR only gives you some easy and quick options which
are intuitive. It's suitable for laptop users who frequently uses projectors
or external monitor.")
(home-page "")
(license license:gpl2+)))
(define-public lxtask
(package
(name "lxtask")
(version "0.1.10")
(source (origin
(method url-fetch)
(uri (string-append "mirror"
"%20%28task%20manager%29/LXTask%20"
(version-major+minor version) ".x/"
"lxtask-" version ".tar.xz"))
(sha256
(base32
"0b2fxg8jjjpk219gh7qa18g45365598nd2bq7rrq0bdvqjdxy5i2"))))
(build-system gnu-build-system)
(inputs `(("gtk+" ,gtk+-2)))
(native-inputs `(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(synopsis "LXDE task manager")
(description "LXTask is a lightweight task manager derived from Xfce task
manager with all dependencies on Xfce removed. LXTask is based on the GTK+
toolkit. It allows users to monitor and control of running processes.")
(home-page "")
(license license:gpl2+)))
(define-public lxterminal
(package
(name "lxterminal")
(version "0.3.2")
(source (origin
(method url-fetch)
(uri (string-append "mirror"
"%20%28terminal%20emulator%29/LXTerminal%20"
version "/" name "-" version ".tar.xz"))
(sha256
(base32
"1124pghrhnx6q4391ri8nvi6bsmvbj1dx81an08mird8jf2b2rii"))))
(build-system gnu-build-system)
(inputs `(("gtk+" ,gtk+-2)
("vte" ,vte/gtk+-2)))
(native-inputs `(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(synopsis "LXDE terminal emulator")
(description "LXTerminal is a VTE-based terminal emulator. It supports
multiple tabs and has only minimal dependencies thus being completely
desktop-independent. In order to reduce memory usage and increase the
performance, all instances of the terminal are sharing a single process.")
(home-page "")
(license license:gpl2+)))
(define-public menu-cache
(package
(name "menu-cache")
(version "1.1.0")
(source (origin
(method url-fetch)
(uri (string-append "mirror/" name "/"
(version-major+minor version) "/"
name "-" version ".tar.xz"))
(sha256
(base32
"1iry4zlpppww8qai2cw4zid4081hh7fz8nzsp5lqyffbkm2yn0pd"))))
(build-system gnu-build-system)
(inputs `(("glib" ,glib)
("libfm" ,libfm-extra)))
(native-inputs `(("pkg-config" ,pkg-config)))
(synopsis "LXDE implementation of the freedesktop menu's cache")
(description "Menu-cache is a library creating and utilizing caches to
speed up the access to freedesktop.org defined application menus.")
(home-page "")
(license license:lgpl2.1+)))
(define-public pcmanfm
(package
(name "pcmanfm")
(version "1.3.2")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
"PCManFM%20%2B%20Libfm%20%28tarball%20release"
"%29/PCManFM/pcmanfm-" version ".tar.xz"))
(sha256
(base32
"1xqc2k2jh165mm81xg0ghxx0ml1s3rhh4ndvbzkcri4kfhj7pjql"))))
(build-system gnu-build-system)
(inputs `(("gtk+" ,gtk+-2)
("gvfs" ,gvfs) ; for trash and mount support
("libfm" ,libfm)
("libx11" ,libx11)))
(native-inputs `(("intltool" ,intltool)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(propagated-inputs
for " Open With ... " application list
(synopsis "LXDE file manager")
(description "PCMan is a lightweight GTK+ based file manager, compliant
with freedesktop.org standard.")
(home-page "")
(license license:gpl2+)))
(define-public spacefm
SpaceFM is based on .
(package
(name "spacefm")
(version "1.0.6")
(source
(origin
(method git-fetch)
(uri
(git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32 "193mdcv73cfc2bnm4bzmnf1wmkzgj1ya64y0lgyxn3ww36ghcsx9"))
(modules '((guix build utils)))
(snippet
'(begin
(substitute* "src/main.c"
(("#include <sys/types\\.h>" all)
;; Add missing include for 'major' and 'minor' with glibc
> = 2.28 .
(string-append all "\n"
"#include <sys/sysmacros.h>\n")))
#t))))
(build-system glib-or-gtk-build-system)
(native-inputs
`(("desktop-file-utils" ,desktop-file-utils)
("glib:bin" ,glib "bin")
("gtk+:bin" ,gtk+ "bin")
("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(inputs
`(("bash" ,bash)
("btrfs-progs" ,btrfs-progs)
("cairo" ,cairo)
("coreutils" ,coreutils)
("curlftpfs" ,curlftpfs)
("e2fsprogs" ,e2fsprogs)
("eudev" ,eudev)
("fakeroot" ,fakeroot)
("ffmpegthumbnailer" ,ffmpegthumbnailer)
("fsarchiver" ,fsarchiver)
("fuseiso" ,fuseiso)
("glib" ,glib)
("gphotofs" ,gphotofs)
("gtk+" ,gtk+)
("ifuse" ,ifuse)
("jmtpfs" ,jmtpfs)
("ktsuss" ,ktsuss)
("libx11" ,libx11)
("lsof" ,lsof)
("ntfs-3g" ,ntfs-3g)
("pango" ,pango)
("procps" ,procps)
("shared-mime-info" ,shared-mime-info)
("startup-notification" ,startup-notification)
("udevil" ,udevil)
("util-linux" ,util-linux)
("wget" ,wget)))
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-bin-dirs
(lambda* (#:key inputs #:allow-other-keys)
(let* ((bash (assoc-ref inputs "bash"))
(coreutils (assoc-ref inputs "coreutils"))
(util-linux (assoc-ref inputs "util-linux"))
(procps (assoc-ref inputs "procps"))
(e2fsprogs (assoc-ref inputs "e2fsprogs"))
(btrfs-progs (assoc-ref inputs "btrfs-progs"))
(ntfs-3g (assoc-ref inputs "ntfs-3g"))
(lsof (assoc-ref inputs "lsof"))
(fsarchiver (assoc-ref inputs "fsarchiver"))
(ktsuss (assoc-ref inputs "ktsuss")))
(with-directory-excursion "src"
(substitute* '("ptk/ptk-file-task.c" "ptk/ptk-handler.h"
"ptk/ptk-location-view.c" "spacefm-auth"
"spacefm-auth.bash" "vfs/vfs-file-task.c"
"settings.c" "../data/ui/prefdlg.ui"
"../data/ui/prefdlg2.ui")
(("/bin/sh" file) (string-append bash file))
(("/bin/bash" file) (string-append bash file))
(("/bin/kill" file) (string-append coreutils file))
(("/bin/ls" file) (string-append coreutils file))
(("/usr(/bin/sha256sum)" _ file) (string-append coreutils file))
(("/usr(/bin/sha512sum)" _ file) (string-append coreutils file))
(("/sbin/fsck" file) (string-append util-linux file))
(("/sbin/mkfs" file) (string-append util-linux file))
(("/sbin/mkswap" file) (string-append util-linux file))
(("/bin/ps" file) (string-append procps file))
(("/sbin/tune2fs" file) (string-append e2fsprogs file))
(("/sbin/btrfs") (string-append btrfs-progs "/bin/btrfs"))
(("/sbin/ntfslabel" file) (string-append ntfs-3g file))
(("/usr(/bin/lsof)" _ file) (string-append lsof file))
(("(/usr)?/(sbin|bin)/fsarchiver") (string-append fsarchiver
"/sbin/fsarchiver"))
(("/usr(/bin/ktsuss)" _ file) (string-append ktsuss file))))
#t)))
(add-after 'patch-bin-dirs 'patch-share-dirs
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(share (string-append out "/share")))
(with-directory-excursion "src"
(substitute* '("main-window.c" "settings.c"
"ptk/ptk-app-chooser.c")
(("/usr(/local)?/share") share)))
#t)))
(add-after 'patch-share-dirs 'patch-mime-dirs
(lambda* (#:key inputs #:allow-other-keys)
(let* ((mime (string-append (assoc-ref inputs "shared-mime-info")
"/share/mime")))
(with-directory-excursion "src"
(substitute* '("mime-type/mime-type.c" "ptk/ptk-file-menu.c")
(("/usr(/local)?/share/mime") mime)))
#t)))
(add-after 'patch-mime-dirs 'patch-setuid-progs
(lambda _
(let* ((su "/run/setuid-programs/su")
(mount "/run/setuid-programs/mount")
(umount "/run/setuid-programs/umount")
(udevil "/run/setuid-programs/udevil"))
(with-directory-excursion "src"
(substitute* '("settings.c" "settings.h" "vfs/vfs-file-task.c"
"vfs/vfs-volume-hal.c" "../data/ui/prefdlg.ui"
"../data/ui/prefdlg2.ui")
(("(/usr)?/bin/su") su)
(("/(bin|sbin)/mount") mount)
(("/(bin|sbin)/umount") umount)
(("/usr/bin/udevil") udevil)))
#t)))
(add-after 'patch-setuid-progs 'patch-spacefm-conf
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "etc/spacefm.conf"
(("#terminal_su=/bin/su")
"terminal_su=/run/setuid-programs/su")
(("#graphical_su=/usr/bin/gksu")
(string-append "graphical_su="
(string-append (assoc-ref inputs "ktsuss")
"/bin/ktsuss"))))
#t)))
#:configure-flags (list
(string-append "--with-preferable-sudo="
(assoc-ref %build-inputs "ktsuss")
"/bin/ktsuss")
(string-append "--with-bash-path="
(assoc-ref %build-inputs "bash")
"/bin/bash")
(string-append "--sysconfdir="
(assoc-ref %outputs "out")
"/etc"))))
(home-page "/")
(synopsis "Multi-panel tabbed file manager")
(description "SpaceFM is a graphical, multi-panel, tabbed file manager
based on PCManFM with built-in virtual file system, udev-based device manager,
customizable menu system, and Bash integration.")
The combination is + but src / exo is under LGPLv3 + .
(license license:gpl3+)))
(define-public lxmenu-data
(package
(name "lxmenu-data")
(version "0.1.5")
(source
(origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.xz"))
(sha256
(base32
"1f5sh2dvb3pdnjlcsyzq9543ck2jsqizkx3204cr22zm5s6j3qwz"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)))
(synopsis "Freedesktop.org desktop menus for LXDE")
(description
"Lxmenu-data provides files required to build freedesktop.org
menu spec-compliant desktop menus for LXDE.")
(home-page "")
(license license:lgpl2.1+)))
(define-public lxde-icon-theme
(package
(name "lxde-icon-theme")
(version "0.5.1")
(source
(origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.xz"))
(sha256
(base32
"0v4i6x86fr2hbx4fb2si7y2qzmj7h6hcjwaifnin18r8kwwvgl73"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)))
(synopsis "LXDE default icon theme based on nuoveXT2")
(description
"Lxde-icon-theme provides an default icon theme for LXDE.")
(home-page "")
(license license:lgpl3)))
(define-public lxde-common
(package
(name "lxde-common")
(version "0.99.2")
(source
(origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.xz"))
(sha256
(base32
"0mj84fa3f4ak1jjslrwc2q3ci9zxrxpciggviza9bjb0168brn8w"))))
(build-system gnu-build-system)
(arguments
'(#:phases (modify-phases %standard-phases
(add-before 'configure 'set-lxsession
(lambda* (#:key inputs #:allow-other-keys)
;; Set the right file name for 'lxsession'.
(let ((lxsession (assoc-ref inputs "lxsession")))
(substitute* "startlxde.in"
(("^exec .*/bin/lxsession")
(string-append "exec " lxsession
"/bin/lxsession")))
#t))))))
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)
("lxmenu-data" ,lxmenu-data)
("lxde-icon-theme" ,lxde-icon-theme)))
(inputs
`(("lxsession" ,lxsession)
;; ("lxlock" ,lxlock) ;for 'lxde-screenlock.desktop'
))
(synopsis "Common files of the LXDE Desktop")
(description
"Lxde-common provides common files of the LXDE Desktop.")
(home-page "")
(license license:gpl2+)))
(define-public lxinput
(package
(name "lxinput")
(version "0.3.5")
(source
(origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.xz"))
(sha256
(base32
"123f3yn4rp1w5b3n5aj3ad9snkxab29qkrs7bcvf5bx4cn57g3sf"))))
(build-system gnu-build-system)
(inputs
`(("gtk+-2" ,gtk+-2)))
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)))
(synopsis "Tool for mouse and keyboard configuration in LXDE")
(description
"Lxinput provides a small program to configure keyboard and mouse
in LXDE.")
(home-page "")
(license license:gpl2+)))
(define-public lxsession
(package
(name "lxsession")
(version "0.5.5")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"lxsession-" version ".tar.xz"))
(sha256
(base32 "0imv9nysip1j9lrb2z96kl05isjgp312323wnnd5b59h0ff0sgp4"))
(modules '((guix build utils)))
(snippet
Remove C files generated by so we can build from source .
'(let* ((c->vala
(lambda (file)
(string-append (string-drop-right file 2)
".vala")))
(generated-c-file?
(lambda (file stat)
(and (string-suffix? ".c" file)
(file-exists? (c->vala file))))))
(for-each delete-file
(find-files "." generated-c-file?))
#t))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'rm-stamp
(lambda _
(for-each delete-file (find-files "." "\\.stamp$"))
Force regeneration of configure script .
(delete-file "configure")
#t)))))
(inputs
`(("gtk+-2" ,gtk+-2)
("polkit" ,polkit)))
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)
("docbook-xsl" ,docbook-xsl)
("vala" ,vala)
;; For bootstrapping.
("autoconf" ,autoconf)
("automake" ,automake)))
(synopsis "Lightweight X11 session manager")
(description
"Lxsession provides an lightweight X11 session manager.")
(home-page "")
(license license:gpl2+)))
(define-public lxpanel
(package
(name "lxpanel")
(version "0.10.0")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"lxpanel-" version ".tar.xz"))
(sha256
(base32 "0zis3b815p375s6mymhf5sn1a0c1xv0ixxzb0mh3fqhrby6cqy26"))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'install 'wrap
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(menu (assoc-ref inputs "lxmenu-data")))
(wrap-program (string-append out "/bin/lxpanel")
`("XDG_DATA_DIRS" ":" prefix
(,(string-append menu "/share"))))
#t))))))
(inputs
;; TODO: libindicator-0.3.0
`(("curl" ,curl)
("gtk+-2" ,gtk+-2)
("alsa-lib" ,alsa-lib)
("libwnck-2" ,libwnck-2)
("keybinder" ,keybinder)
("libxmu" ,libxmu)
("libxpm" ,libxpm)
("libxml2" ,libxml2)
("cairo" ,cairo)
("libx11" ,libx11)
("wireless-tools" ,wireless-tools)))
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)
("docbook-xml" ,docbook-xml)
("gettext-minimal" ,gettext-minimal)))
(propagated-inputs
`(("lxmenu-data" ,lxmenu-data)
("libfm" ,libfm)
("menu-cache" ,menu-cache)))
(synopsis "X11 Desktop panel for LXDE")
(description
"Lxpanel provides an X11 desktop panel for LXDE.")
(home-page "")
(license license:gpl2+)))
(define-public lxde
(package
(name "lxde")
(version (package-version lxde-common))
(source #f)
(build-system trivial-build-system)
(arguments '(#:builder (begin (mkdir %output) #t)))
(propagated-inputs
;; TODO:
;; lxshortcut, lxsession-edit
;; lxappearance-obconf
`(("menu-cache" ,menu-cache)
("gpicview" ,gpicview)
("leafpad" ,leafpad)
("lxappearance" ,lxappearance)
("lxde-icon-theme" ,lxde-icon-theme)
("lxde-common" ,lxde-common)
("lxmenu-data" ,lxmenu-data)
("lxpanel" ,lxpanel)
("lxrandr" ,lxrandr)
("lxsession" ,lxsession)
("libfm" ,libfm)
("libfm-extra" ,libfm-extra)
("lxtask" ,lxtask)
("lxterminal" ,lxterminal)
("pcmanfm" ,pcmanfm)
("openbox" ,openbox)
("obconf" ,obconf)))
(synopsis "Lightweight X11 Desktop Environment")
(description
"LXDE, which stands for Lightweight X11 Desktop Environment, is a
desktop environment which is lightweight and fast. It is designed to be
user friendly and slim, while keeping the resource usage low. LXDE uses
less RAM and less CPU while being a feature rich desktop environment. Unlike
other tightly integrated desktops LXDE strives to be modular, so each
component can be used independently with few dependencies.")
(home-page "")
(license license:gpl2+))) ; And others.
;;; lxde.scm ends here
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/packages/lxde.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
for gtester
message if it's not in $PATH, so make it a hard dependency.
for trash and mount support
Add missing include for 'major' and 'minor' with glibc
Set the right file name for 'lxsession'.
("lxlock" ,lxlock) ;for 'lxde-screenlock.desktop'
For bootstrapping.
TODO: libindicator-0.3.0
TODO:
lxshortcut, lxsession-edit
lxappearance-obconf
And others.
lxde.scm ends here | Copyright © 2015 >
Copyright © 2016 < >
Copyright © 2017 Nikita < >
Copyright © 2017 < >
Copyright © 2017 < >
Copyright © 2018–2021 < >
Copyright © 2018 ison < >
Copyright © 2018 , 2019 < >
Copyright © 2018 < >
Copyright © 2019 Meiyo < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages lxde)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages autotools)
#:use-module (gnu packages base)
#:use-module (gnu packages bash)
#:use-module (gnu packages curl)
#:use-module (gnu packages disk)
#:use-module (gnu packages docbook)
#:use-module (gnu packages file-systems)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages gettext)
#:use-module (gnu packages glib)
#:use-module (gnu packages gnome)
#:use-module (gnu packages gtk)
#:use-module (gnu packages image-viewers)
#:use-module (gnu packages libusb)
#:use-module (gnu packages linux)
#:use-module (gnu packages lsof)
#:use-module (gnu packages openbox)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages polkit)
#:use-module (gnu packages text-editors)
#:use-module (gnu packages video)
#:use-module (gnu packages wget)
#:use-module (gnu packages wm)
#:use-module (gnu packages xdisorg)
#:use-module (gnu packages xml)
#:use-module (gnu packages xorg)
#:use-module (guix build-system glib-or-gtk)
#:use-module (guix build-system gnu)
#:use-module (guix build-system trivial)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix utils))
(define-public libfm
(package
(name "libfm")
(version "1.3.2")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
"PCManFM%20%2B%20Libfm%20%28tarball%20release"
"%29/LibFM/" name "-" version ".tar.xz"))
(sha256
(base32
"1rfira3lx8v6scz1aq69925j4vslpp36bmgrrzcfby2c60q2c155"))))
(build-system gnu-build-system)
(inputs `(("glib" ,glib)
("gtk+" ,gtk+-2)))
(native-inputs `(("intltool" ,intltool)
("libtool" ,libtool)
("menu-cache" ,menu-cache)
("pkg-config" ,pkg-config)
("vala" ,vala)))
(synopsis "File management support (core library)")
(description "LibFM provides file management functions built on top of
Glib/GIO giving a higher-level API.")
(home-page "")
(license license:gpl2+)))
(define-public libfm-extra
(package (inherit libfm)
(name "libfm-extra")
(arguments '(#:configure-flags '("--with-extra-only")))
(inputs `(("glib" ,glib)))
(native-inputs `(("intltool" ,intltool)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(synopsis "File management support (extra library)")
(description "This package contains a stand-alone library which extends the
libFM file management library.")))
(define-public lxappearance
(package
(name "lxappearance")
(version "0.6.3")
(source
(origin
(method url-fetch)
(uri (string-append "mirror/"
"LXAppearance/lxappearance-" version ".tar.xz"))
(sha256
(base32 "0f4bjaamfxxdr9civvy55pa6vv9dx1hjs522gjbbgx7yp1cdh8kj"))))
(build-system gnu-build-system)
(inputs `(("gtk+" ,gtk+-2)))
(native-inputs `(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(synopsis "LXDE GTK+ theme switcher")
(description "LXAppearance is a desktop-independent GTK+ theme switcher
able to change themes, icons, and fonts used by GTK+ applications.")
(home-page "")
(license license:gpl2+)))
(define-public lxrandr
(package
(name "lxrandr")
(version "0.3.2")
(source (origin
(method url-fetch)
(uri (string-append "mirror"
"%20%28monitor%20config%20tool%29/LXRandR%20"
(version-major+minor version) ".x/"
"lxrandr-" version ".tar.xz"))
(sha256
(base32
"04n3vgh3ix12p8jfs4w0dyfq3anbjy33h7g53wbbqqc0f74xyplb"))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'xrandr-absolutely
lxrandr is useless without xrandr and gives an unhelpful error
(lambda* (#:key input #:allow-other-keys)
(substitute* "src/lxrandr.c"
(("(\"|')xrandr\"" _ match)
(string-append match (which "xrandr") "\"")))
#t)))))
(inputs `(("gtk+" ,gtk+-2)
("xrandr" ,xrandr)))
(native-inputs `(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(synopsis "LXDE monitor configuration tool")
(description "LXRandR is a very basic monitor configuration tool. It
relies on the X11 resize-and-rotate (RandR) extension but doesn't aim to be a
full frontend of it. LXRandR only gives you some easy and quick options which
are intuitive. It's suitable for laptop users who frequently uses projectors
or external monitor.")
(home-page "")
(license license:gpl2+)))
(define-public lxtask
(package
(name "lxtask")
(version "0.1.10")
(source (origin
(method url-fetch)
(uri (string-append "mirror"
"%20%28task%20manager%29/LXTask%20"
(version-major+minor version) ".x/"
"lxtask-" version ".tar.xz"))
(sha256
(base32
"0b2fxg8jjjpk219gh7qa18g45365598nd2bq7rrq0bdvqjdxy5i2"))))
(build-system gnu-build-system)
(inputs `(("gtk+" ,gtk+-2)))
(native-inputs `(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(synopsis "LXDE task manager")
(description "LXTask is a lightweight task manager derived from Xfce task
manager with all dependencies on Xfce removed. LXTask is based on the GTK+
toolkit. It allows users to monitor and control of running processes.")
(home-page "")
(license license:gpl2+)))
(define-public lxterminal
(package
(name "lxterminal")
(version "0.3.2")
(source (origin
(method url-fetch)
(uri (string-append "mirror"
"%20%28terminal%20emulator%29/LXTerminal%20"
version "/" name "-" version ".tar.xz"))
(sha256
(base32
"1124pghrhnx6q4391ri8nvi6bsmvbj1dx81an08mird8jf2b2rii"))))
(build-system gnu-build-system)
(inputs `(("gtk+" ,gtk+-2)
("vte" ,vte/gtk+-2)))
(native-inputs `(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(synopsis "LXDE terminal emulator")
(description "LXTerminal is a VTE-based terminal emulator. It supports
multiple tabs and has only minimal dependencies thus being completely
desktop-independent. In order to reduce memory usage and increase the
performance, all instances of the terminal are sharing a single process.")
(home-page "")
(license license:gpl2+)))
(define-public menu-cache
(package
(name "menu-cache")
(version "1.1.0")
(source (origin
(method url-fetch)
(uri (string-append "mirror/" name "/"
(version-major+minor version) "/"
name "-" version ".tar.xz"))
(sha256
(base32
"1iry4zlpppww8qai2cw4zid4081hh7fz8nzsp5lqyffbkm2yn0pd"))))
(build-system gnu-build-system)
(inputs `(("glib" ,glib)
("libfm" ,libfm-extra)))
(native-inputs `(("pkg-config" ,pkg-config)))
(synopsis "LXDE implementation of the freedesktop menu's cache")
(description "Menu-cache is a library creating and utilizing caches to
speed up the access to freedesktop.org defined application menus.")
(home-page "")
(license license:lgpl2.1+)))
(define-public pcmanfm
(package
(name "pcmanfm")
(version "1.3.2")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
"PCManFM%20%2B%20Libfm%20%28tarball%20release"
"%29/PCManFM/pcmanfm-" version ".tar.xz"))
(sha256
(base32
"1xqc2k2jh165mm81xg0ghxx0ml1s3rhh4ndvbzkcri4kfhj7pjql"))))
(build-system gnu-build-system)
(inputs `(("gtk+" ,gtk+-2)
("libfm" ,libfm)
("libx11" ,libx11)))
(native-inputs `(("intltool" ,intltool)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(propagated-inputs
for " Open With ... " application list
(synopsis "LXDE file manager")
(description "PCMan is a lightweight GTK+ based file manager, compliant
with freedesktop.org standard.")
(home-page "")
(license license:gpl2+)))
(define-public spacefm
SpaceFM is based on .
(package
(name "spacefm")
(version "1.0.6")
(source
(origin
(method git-fetch)
(uri
(git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32 "193mdcv73cfc2bnm4bzmnf1wmkzgj1ya64y0lgyxn3ww36ghcsx9"))
(modules '((guix build utils)))
(snippet
'(begin
(substitute* "src/main.c"
(("#include <sys/types\\.h>" all)
> = 2.28 .
(string-append all "\n"
"#include <sys/sysmacros.h>\n")))
#t))))
(build-system glib-or-gtk-build-system)
(native-inputs
`(("desktop-file-utils" ,desktop-file-utils)
("glib:bin" ,glib "bin")
("gtk+:bin" ,gtk+ "bin")
("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(inputs
`(("bash" ,bash)
("btrfs-progs" ,btrfs-progs)
("cairo" ,cairo)
("coreutils" ,coreutils)
("curlftpfs" ,curlftpfs)
("e2fsprogs" ,e2fsprogs)
("eudev" ,eudev)
("fakeroot" ,fakeroot)
("ffmpegthumbnailer" ,ffmpegthumbnailer)
("fsarchiver" ,fsarchiver)
("fuseiso" ,fuseiso)
("glib" ,glib)
("gphotofs" ,gphotofs)
("gtk+" ,gtk+)
("ifuse" ,ifuse)
("jmtpfs" ,jmtpfs)
("ktsuss" ,ktsuss)
("libx11" ,libx11)
("lsof" ,lsof)
("ntfs-3g" ,ntfs-3g)
("pango" ,pango)
("procps" ,procps)
("shared-mime-info" ,shared-mime-info)
("startup-notification" ,startup-notification)
("udevil" ,udevil)
("util-linux" ,util-linux)
("wget" ,wget)))
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-bin-dirs
(lambda* (#:key inputs #:allow-other-keys)
(let* ((bash (assoc-ref inputs "bash"))
(coreutils (assoc-ref inputs "coreutils"))
(util-linux (assoc-ref inputs "util-linux"))
(procps (assoc-ref inputs "procps"))
(e2fsprogs (assoc-ref inputs "e2fsprogs"))
(btrfs-progs (assoc-ref inputs "btrfs-progs"))
(ntfs-3g (assoc-ref inputs "ntfs-3g"))
(lsof (assoc-ref inputs "lsof"))
(fsarchiver (assoc-ref inputs "fsarchiver"))
(ktsuss (assoc-ref inputs "ktsuss")))
(with-directory-excursion "src"
(substitute* '("ptk/ptk-file-task.c" "ptk/ptk-handler.h"
"ptk/ptk-location-view.c" "spacefm-auth"
"spacefm-auth.bash" "vfs/vfs-file-task.c"
"settings.c" "../data/ui/prefdlg.ui"
"../data/ui/prefdlg2.ui")
(("/bin/sh" file) (string-append bash file))
(("/bin/bash" file) (string-append bash file))
(("/bin/kill" file) (string-append coreutils file))
(("/bin/ls" file) (string-append coreutils file))
(("/usr(/bin/sha256sum)" _ file) (string-append coreutils file))
(("/usr(/bin/sha512sum)" _ file) (string-append coreutils file))
(("/sbin/fsck" file) (string-append util-linux file))
(("/sbin/mkfs" file) (string-append util-linux file))
(("/sbin/mkswap" file) (string-append util-linux file))
(("/bin/ps" file) (string-append procps file))
(("/sbin/tune2fs" file) (string-append e2fsprogs file))
(("/sbin/btrfs") (string-append btrfs-progs "/bin/btrfs"))
(("/sbin/ntfslabel" file) (string-append ntfs-3g file))
(("/usr(/bin/lsof)" _ file) (string-append lsof file))
(("(/usr)?/(sbin|bin)/fsarchiver") (string-append fsarchiver
"/sbin/fsarchiver"))
(("/usr(/bin/ktsuss)" _ file) (string-append ktsuss file))))
#t)))
(add-after 'patch-bin-dirs 'patch-share-dirs
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(share (string-append out "/share")))
(with-directory-excursion "src"
(substitute* '("main-window.c" "settings.c"
"ptk/ptk-app-chooser.c")
(("/usr(/local)?/share") share)))
#t)))
(add-after 'patch-share-dirs 'patch-mime-dirs
(lambda* (#:key inputs #:allow-other-keys)
(let* ((mime (string-append (assoc-ref inputs "shared-mime-info")
"/share/mime")))
(with-directory-excursion "src"
(substitute* '("mime-type/mime-type.c" "ptk/ptk-file-menu.c")
(("/usr(/local)?/share/mime") mime)))
#t)))
(add-after 'patch-mime-dirs 'patch-setuid-progs
(lambda _
(let* ((su "/run/setuid-programs/su")
(mount "/run/setuid-programs/mount")
(umount "/run/setuid-programs/umount")
(udevil "/run/setuid-programs/udevil"))
(with-directory-excursion "src"
(substitute* '("settings.c" "settings.h" "vfs/vfs-file-task.c"
"vfs/vfs-volume-hal.c" "../data/ui/prefdlg.ui"
"../data/ui/prefdlg2.ui")
(("(/usr)?/bin/su") su)
(("/(bin|sbin)/mount") mount)
(("/(bin|sbin)/umount") umount)
(("/usr/bin/udevil") udevil)))
#t)))
(add-after 'patch-setuid-progs 'patch-spacefm-conf
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "etc/spacefm.conf"
(("#terminal_su=/bin/su")
"terminal_su=/run/setuid-programs/su")
(("#graphical_su=/usr/bin/gksu")
(string-append "graphical_su="
(string-append (assoc-ref inputs "ktsuss")
"/bin/ktsuss"))))
#t)))
#:configure-flags (list
(string-append "--with-preferable-sudo="
(assoc-ref %build-inputs "ktsuss")
"/bin/ktsuss")
(string-append "--with-bash-path="
(assoc-ref %build-inputs "bash")
"/bin/bash")
(string-append "--sysconfdir="
(assoc-ref %outputs "out")
"/etc"))))
(home-page "/")
(synopsis "Multi-panel tabbed file manager")
(description "SpaceFM is a graphical, multi-panel, tabbed file manager
based on PCManFM with built-in virtual file system, udev-based device manager,
customizable menu system, and Bash integration.")
The combination is + but src / exo is under LGPLv3 + .
(license license:gpl3+)))
(define-public lxmenu-data
(package
(name "lxmenu-data")
(version "0.1.5")
(source
(origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.xz"))
(sha256
(base32
"1f5sh2dvb3pdnjlcsyzq9543ck2jsqizkx3204cr22zm5s6j3qwz"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)))
(synopsis "Freedesktop.org desktop menus for LXDE")
(description
"Lxmenu-data provides files required to build freedesktop.org
menu spec-compliant desktop menus for LXDE.")
(home-page "")
(license license:lgpl2.1+)))
(define-public lxde-icon-theme
(package
(name "lxde-icon-theme")
(version "0.5.1")
(source
(origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.xz"))
(sha256
(base32
"0v4i6x86fr2hbx4fb2si7y2qzmj7h6hcjwaifnin18r8kwwvgl73"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)))
(synopsis "LXDE default icon theme based on nuoveXT2")
(description
"Lxde-icon-theme provides an default icon theme for LXDE.")
(home-page "")
(license license:lgpl3)))
(define-public lxde-common
(package
(name "lxde-common")
(version "0.99.2")
(source
(origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.xz"))
(sha256
(base32
"0mj84fa3f4ak1jjslrwc2q3ci9zxrxpciggviza9bjb0168brn8w"))))
(build-system gnu-build-system)
(arguments
'(#:phases (modify-phases %standard-phases
(add-before 'configure 'set-lxsession
(lambda* (#:key inputs #:allow-other-keys)
(let ((lxsession (assoc-ref inputs "lxsession")))
(substitute* "startlxde.in"
(("^exec .*/bin/lxsession")
(string-append "exec " lxsession
"/bin/lxsession")))
#t))))))
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)
("lxmenu-data" ,lxmenu-data)
("lxde-icon-theme" ,lxde-icon-theme)))
(inputs
`(("lxsession" ,lxsession)
))
(synopsis "Common files of the LXDE Desktop")
(description
"Lxde-common provides common files of the LXDE Desktop.")
(home-page "")
(license license:gpl2+)))
(define-public lxinput
(package
(name "lxinput")
(version "0.3.5")
(source
(origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.xz"))
(sha256
(base32
"123f3yn4rp1w5b3n5aj3ad9snkxab29qkrs7bcvf5bx4cn57g3sf"))))
(build-system gnu-build-system)
(inputs
`(("gtk+-2" ,gtk+-2)))
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)))
(synopsis "Tool for mouse and keyboard configuration in LXDE")
(description
"Lxinput provides a small program to configure keyboard and mouse
in LXDE.")
(home-page "")
(license license:gpl2+)))
(define-public lxsession
(package
(name "lxsession")
(version "0.5.5")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"lxsession-" version ".tar.xz"))
(sha256
(base32 "0imv9nysip1j9lrb2z96kl05isjgp312323wnnd5b59h0ff0sgp4"))
(modules '((guix build utils)))
(snippet
Remove C files generated by so we can build from source .
'(let* ((c->vala
(lambda (file)
(string-append (string-drop-right file 2)
".vala")))
(generated-c-file?
(lambda (file stat)
(and (string-suffix? ".c" file)
(file-exists? (c->vala file))))))
(for-each delete-file
(find-files "." generated-c-file?))
#t))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'rm-stamp
(lambda _
(for-each delete-file (find-files "." "\\.stamp$"))
Force regeneration of configure script .
(delete-file "configure")
#t)))))
(inputs
`(("gtk+-2" ,gtk+-2)
("polkit" ,polkit)))
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)
("docbook-xsl" ,docbook-xsl)
("vala" ,vala)
("autoconf" ,autoconf)
("automake" ,automake)))
(synopsis "Lightweight X11 session manager")
(description
"Lxsession provides an lightweight X11 session manager.")
(home-page "")
(license license:gpl2+)))
(define-public lxpanel
(package
(name "lxpanel")
(version "0.10.0")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"lxpanel-" version ".tar.xz"))
(sha256
(base32 "0zis3b815p375s6mymhf5sn1a0c1xv0ixxzb0mh3fqhrby6cqy26"))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'install 'wrap
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(menu (assoc-ref inputs "lxmenu-data")))
(wrap-program (string-append out "/bin/lxpanel")
`("XDG_DATA_DIRS" ":" prefix
(,(string-append menu "/share"))))
#t))))))
(inputs
`(("curl" ,curl)
("gtk+-2" ,gtk+-2)
("alsa-lib" ,alsa-lib)
("libwnck-2" ,libwnck-2)
("keybinder" ,keybinder)
("libxmu" ,libxmu)
("libxpm" ,libxpm)
("libxml2" ,libxml2)
("cairo" ,cairo)
("libx11" ,libx11)
("wireless-tools" ,wireless-tools)))
(native-inputs
`(("pkg-config" ,pkg-config)
("intltool" ,intltool)
("docbook-xml" ,docbook-xml)
("gettext-minimal" ,gettext-minimal)))
(propagated-inputs
`(("lxmenu-data" ,lxmenu-data)
("libfm" ,libfm)
("menu-cache" ,menu-cache)))
(synopsis "X11 Desktop panel for LXDE")
(description
"Lxpanel provides an X11 desktop panel for LXDE.")
(home-page "")
(license license:gpl2+)))
(define-public lxde
(package
(name "lxde")
(version (package-version lxde-common))
(source #f)
(build-system trivial-build-system)
(arguments '(#:builder (begin (mkdir %output) #t)))
(propagated-inputs
`(("menu-cache" ,menu-cache)
("gpicview" ,gpicview)
("leafpad" ,leafpad)
("lxappearance" ,lxappearance)
("lxde-icon-theme" ,lxde-icon-theme)
("lxde-common" ,lxde-common)
("lxmenu-data" ,lxmenu-data)
("lxpanel" ,lxpanel)
("lxrandr" ,lxrandr)
("lxsession" ,lxsession)
("libfm" ,libfm)
("libfm-extra" ,libfm-extra)
("lxtask" ,lxtask)
("lxterminal" ,lxterminal)
("pcmanfm" ,pcmanfm)
("openbox" ,openbox)
("obconf" ,obconf)))
(synopsis "Lightweight X11 Desktop Environment")
(description
"LXDE, which stands for Lightweight X11 Desktop Environment, is a
desktop environment which is lightweight and fast. It is designed to be
user friendly and slim, while keeping the resource usage low. LXDE uses
less RAM and less CPU while being a feature rich desktop environment. Unlike
other tightly integrated desktops LXDE strives to be modular, so each
component can be used independently with few dependencies.")
(home-page "")
|
8a0cecc443da7f909a2392306563ee8ce3916680a27a00c73e2d5acf1c067557 | metabase/metabase | moderation.clj | (ns metabase.moderation
(:require
[medley.core :as m]
[metabase.models.interface :as mi]
[metabase.util :as u]
[schema.core :as s]
[toucan.db :as db]
[toucan2.core :as t2]))
(def moderated-item-types
"Schema enum of the acceptable values for the `moderated_item_type` column"
(s/enum "card" "dashboard" :card :dashboard))
(def moderated-item-type->model
"Maps DB name of the moderated item type to the model symbol (used for db/select and such)"
{"card" 'Card
:card 'Card
"dashboard" 'Dashboard
:dashboard 'Dashboard})
(defn- object->type
"Convert a moderated item instance to the keyword stored in the database"
[instance]
(u/lower-case-en (name (t2/model instance))))
(mi/define-batched-hydration-method moderation-reviews-for-items
:moderation_reviews
"Hydrate moderation reviews onto a seq of items. All are cards or the nils that end up here on text dashboard
cards. In the future could have dashboards here as well."
[items]
;; no need to do work on empty items. Also, can have nil here due to text cards. I think this is a bug in toucan. To
get here we are ` ( hydrate dashboard [: ordered_cards [: card : moderation_reviews ] : series ] ... ) ` But ordered_cards
;; dont have to have cards. but the hydration will pass the nil card id into here. NOTE: it is important that each
;; item that comes into this comes out. The nested hydration is positional, not by an id so everything that comes in
;; must go out in the same order
(when (seq items)
(let [item-ids (not-empty (keep :id items))
all-reviews (when item-ids
(group-by (juxt :moderated_item_type :moderated_item_id)
(db/select 'ModerationReview
:moderated_item_type "card"
:moderated_item_id [:in item-ids]
{:order-by [[:id :desc]]})))]
(for [item items]
(if (nil? item)
nil
(let [k ((juxt (comp keyword object->type) u/the-id) item)]
(assoc item :moderation_reviews (get all-reviews k ()))))))))
(mi/define-batched-hydration-method moderation-user-details
:moderator_details
"User details on moderation reviews"
[moderation-reviews]
(when (seq moderation-reviews)
(let [id->user (m/index-by :id
(db/select 'User :id [:in (map :moderator_id moderation-reviews)]))]
(for [mr moderation-reviews]
(assoc mr :user (get id->user (:moderator_id mr)))))))
(mi/define-simple-hydration-method moderated-item
:moderated_item
"The moderated item for a given request or review"
[{:keys [moderated_item_id moderated_item_type]}]
(when (and moderated_item_type moderated_item_id)
(db/select-one (moderated-item-type->model moderated_item_type) :id moderated_item_id)))
| null | https://raw.githubusercontent.com/metabase/metabase/ff2c972dcb11f9355e314cffcc8e10b0e58f53bf/src/metabase/moderation.clj | clojure | no need to do work on empty items. Also, can have nil here due to text cards. I think this is a bug in toucan. To
dont have to have cards. but the hydration will pass the nil card id into here. NOTE: it is important that each
item that comes into this comes out. The nested hydration is positional, not by an id so everything that comes in
must go out in the same order | (ns metabase.moderation
(:require
[medley.core :as m]
[metabase.models.interface :as mi]
[metabase.util :as u]
[schema.core :as s]
[toucan.db :as db]
[toucan2.core :as t2]))
(def moderated-item-types
"Schema enum of the acceptable values for the `moderated_item_type` column"
(s/enum "card" "dashboard" :card :dashboard))
(def moderated-item-type->model
"Maps DB name of the moderated item type to the model symbol (used for db/select and such)"
{"card" 'Card
:card 'Card
"dashboard" 'Dashboard
:dashboard 'Dashboard})
(defn- object->type
"Convert a moderated item instance to the keyword stored in the database"
[instance]
(u/lower-case-en (name (t2/model instance))))
(mi/define-batched-hydration-method moderation-reviews-for-items
:moderation_reviews
"Hydrate moderation reviews onto a seq of items. All are cards or the nils that end up here on text dashboard
cards. In the future could have dashboards here as well."
[items]
get here we are ` ( hydrate dashboard [: ordered_cards [: card : moderation_reviews ] : series ] ... ) ` But ordered_cards
(when (seq items)
(let [item-ids (not-empty (keep :id items))
all-reviews (when item-ids
(group-by (juxt :moderated_item_type :moderated_item_id)
(db/select 'ModerationReview
:moderated_item_type "card"
:moderated_item_id [:in item-ids]
{:order-by [[:id :desc]]})))]
(for [item items]
(if (nil? item)
nil
(let [k ((juxt (comp keyword object->type) u/the-id) item)]
(assoc item :moderation_reviews (get all-reviews k ()))))))))
(mi/define-batched-hydration-method moderation-user-details
:moderator_details
"User details on moderation reviews"
[moderation-reviews]
(when (seq moderation-reviews)
(let [id->user (m/index-by :id
(db/select 'User :id [:in (map :moderator_id moderation-reviews)]))]
(for [mr moderation-reviews]
(assoc mr :user (get id->user (:moderator_id mr)))))))
(mi/define-simple-hydration-method moderated-item
:moderated_item
"The moderated item for a given request or review"
[{:keys [moderated_item_id moderated_item_type]}]
(when (and moderated_item_type moderated_item_id)
(db/select-one (moderated-item-type->model moderated_item_type) :id moderated_item_id)))
|
28939fd9700f734ce8b10ddee3d0aeef70420f76924ece673070d19859697afe | rotty/ocelotl | uri.scm | #!r6rs
uri.scm --- Wrapper for the URI library test suite
Copyright ( C ) 2011 < >
Author : < >
;; This program is free software, you can redistribute it and/or
modify it under the terms of the new - style BSD license .
You should have received a copy of the BSD license along with this
;; program. If not, see <>.
;;; Commentary:
;;; Code:
(import (rnrs)
(spells include)
(wak trc-testing)
(ocelotl net uri))
(include-file/downcase ((ocelotl private) test-uri))
(run-test-suite uri-tests)
| null | https://raw.githubusercontent.com/rotty/ocelotl/0c6aadaef99444b180574f18f1935d9507e20978/tests/uri.scm | scheme | This program is free software, you can redistribute it and/or
program. If not, see <>.
Commentary:
Code: | #!r6rs
uri.scm --- Wrapper for the URI library test suite
Copyright ( C ) 2011 < >
Author : < >
modify it under the terms of the new - style BSD license .
You should have received a copy of the BSD license along with this
(import (rnrs)
(spells include)
(wak trc-testing)
(ocelotl net uri))
(include-file/downcase ((ocelotl private) test-uri))
(run-test-suite uri-tests)
|
05a978fd102ee748173402b555c0904ec5edff7957979a0bd92a7b417633a5a1 | fragnix/fragnix | LocalSlice.hs | # LANGUAGE OverloadedStrings , StandaloneDeriving , DeriveGeneric , GeneralizedNewtypeDeriving #
module Fragnix.LocalSlice
( LocalSlice(..)
, LocalSliceID(..)
, LocalUse(..)
, LocalReference(..)
, LocalInstance(..)
, LocalInstanceID
) where
import Fragnix.Slice (
SliceID, OriginalModule, Language, Fragment, Qualification, UsedName,
InstancePart, InstanceID)
import Data.Aeson (FromJSON, ToJSON, ToJSONKey, FromJSONKey)
import Data.Text (Text)
import GHC.Generics (Generic)
-- | A local ID before slices have been hashed.
It has to be a valid Haskell module name .
newtype LocalSliceID = LocalSliceID Text
deriving instance Show LocalSliceID
deriving instance Eq LocalSliceID
deriving instance Ord LocalSliceID
deriving instance Generic LocalSliceID
instance ToJSON LocalSliceID
instance FromJSON LocalSliceID
deriving instance ToJSONKey LocalSliceID
deriving instance FromJSONKey LocalSliceID
-- | A Slice with a local ID that may use slices with local IDs as well as global
-- slices with slice IDs.
data LocalSlice = LocalSlice
{ localSliceID :: LocalSliceID
, language :: Language
, fragment :: Fragment
, localUses :: [LocalUse]
, localInstances :: [LocalInstance]
}
deriving instance Show LocalSlice
deriving instance Eq LocalSlice
deriving instance Ord LocalSlice
deriving instance Generic LocalSlice
instance ToJSON LocalSlice
instance FromJSON LocalSlice
-- | A local use may refer to local slices and global slices.
data LocalUse = LocalUse
{ qualification :: Maybe Qualification
, usedName :: UsedName
, localReference :: LocalReference
}
deriving instance Show LocalUse
deriving instance Eq LocalUse
deriving instance Ord LocalUse
deriving instance Generic LocalUse
instance ToJSON LocalUse
instance FromJSON LocalUse
data LocalReference =
OtherSlice SliceID |
Builtin OriginalModule |
OtherLocalSlice LocalSliceID
deriving instance Show LocalReference
deriving instance Eq LocalReference
deriving instance Ord LocalReference
deriving instance Generic LocalReference
instance ToJSON LocalReference
instance FromJSON LocalReference
-- TODO: Reorganize in order to avoid partial record labels.
data LocalInstance =
LocalInstance { instancePart :: InstancePart, localInstanceID :: LocalInstanceID } |
GlobalInstance { instancePart :: InstancePart, globalInstanceID :: InstanceID }
type LocalInstanceID = LocalSliceID
deriving instance Show LocalInstance
deriving instance Eq LocalInstance
deriving instance Ord LocalInstance
deriving instance Generic LocalInstance
instance ToJSON LocalInstance
instance FromJSON LocalInstance
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/src/Fragnix/LocalSlice.hs | haskell | | A local ID before slices have been hashed.
| A Slice with a local ID that may use slices with local IDs as well as global
slices with slice IDs.
| A local use may refer to local slices and global slices.
TODO: Reorganize in order to avoid partial record labels. | # LANGUAGE OverloadedStrings , StandaloneDeriving , DeriveGeneric , GeneralizedNewtypeDeriving #
module Fragnix.LocalSlice
( LocalSlice(..)
, LocalSliceID(..)
, LocalUse(..)
, LocalReference(..)
, LocalInstance(..)
, LocalInstanceID
) where
import Fragnix.Slice (
SliceID, OriginalModule, Language, Fragment, Qualification, UsedName,
InstancePart, InstanceID)
import Data.Aeson (FromJSON, ToJSON, ToJSONKey, FromJSONKey)
import Data.Text (Text)
import GHC.Generics (Generic)
It has to be a valid Haskell module name .
newtype LocalSliceID = LocalSliceID Text
deriving instance Show LocalSliceID
deriving instance Eq LocalSliceID
deriving instance Ord LocalSliceID
deriving instance Generic LocalSliceID
instance ToJSON LocalSliceID
instance FromJSON LocalSliceID
deriving instance ToJSONKey LocalSliceID
deriving instance FromJSONKey LocalSliceID
data LocalSlice = LocalSlice
{ localSliceID :: LocalSliceID
, language :: Language
, fragment :: Fragment
, localUses :: [LocalUse]
, localInstances :: [LocalInstance]
}
deriving instance Show LocalSlice
deriving instance Eq LocalSlice
deriving instance Ord LocalSlice
deriving instance Generic LocalSlice
instance ToJSON LocalSlice
instance FromJSON LocalSlice
data LocalUse = LocalUse
{ qualification :: Maybe Qualification
, usedName :: UsedName
, localReference :: LocalReference
}
deriving instance Show LocalUse
deriving instance Eq LocalUse
deriving instance Ord LocalUse
deriving instance Generic LocalUse
instance ToJSON LocalUse
instance FromJSON LocalUse
data LocalReference =
OtherSlice SliceID |
Builtin OriginalModule |
OtherLocalSlice LocalSliceID
deriving instance Show LocalReference
deriving instance Eq LocalReference
deriving instance Ord LocalReference
deriving instance Generic LocalReference
instance ToJSON LocalReference
instance FromJSON LocalReference
data LocalInstance =
LocalInstance { instancePart :: InstancePart, localInstanceID :: LocalInstanceID } |
GlobalInstance { instancePart :: InstancePart, globalInstanceID :: InstanceID }
type LocalInstanceID = LocalSliceID
deriving instance Show LocalInstance
deriving instance Eq LocalInstance
deriving instance Ord LocalInstance
deriving instance Generic LocalInstance
instance ToJSON LocalInstance
instance FromJSON LocalInstance
|
cde8c27278d27af16ba2c3a914e712e52457b03a98699268eb9d658c9434730c | herd/herdtools7 | X86Arch_litmus.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2010 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
open Printf
let comment = "#"
module Make(O:Arch_litmus.Config)(V:Constant.S) = struct
include X86Base
module V = V
module FaultType = FaultType.No
let reg_to_string r = match r with
| EAX -> "%eax"
| EBX -> "%ebx"
| ECX -> "%ecx"
| EDX -> "%edx"
| ESI -> "%esi"
| EDI -> "%edi"
| EBP -> "%ebp"
| Internal i -> sprintf "i%i" i
| _ -> assert false
include
ArchExtra_litmus.Make(O)
(struct
module V = V
type arch_reg = reg
let arch = `X86
let forbidden_regs = []
let pp_reg = pp_reg
let reg_compare = reg_compare
let reg_to_string = reg_to_string
let internal_init r =
if reg_compare r loop_idx = 0 then Some ("max_loop","int")
else None
let reg_class = function
as some instructions have eax as implicit argument ,
we must allocate our EAX to machine % eax
we must allocate our EAX to machine %eax *)
| EAX -> "=&a"
esi and edi implicit for MOVSD
| ESI -> "=&S"
| EDI -> "=&D"
| _ -> "=&r"
let reg_class_stable r = reg_class r
let comment = comment
let error _ _ = false
let warn _ _ = false
end)
let features = []
let nop = I_NOP
include HardwareExtra.No
module GetInstr = GetInstr.No(struct type instr=instruction end)
end
| null | https://raw.githubusercontent.com/herd/herdtools7/6d781eb91debffdf56998171862a18e40908c3c5/litmus/X86Arch_litmus.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
************************************************************************** | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2010 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
open Printf
let comment = "#"
module Make(O:Arch_litmus.Config)(V:Constant.S) = struct
include X86Base
module V = V
module FaultType = FaultType.No
let reg_to_string r = match r with
| EAX -> "%eax"
| EBX -> "%ebx"
| ECX -> "%ecx"
| EDX -> "%edx"
| ESI -> "%esi"
| EDI -> "%edi"
| EBP -> "%ebp"
| Internal i -> sprintf "i%i" i
| _ -> assert false
include
ArchExtra_litmus.Make(O)
(struct
module V = V
type arch_reg = reg
let arch = `X86
let forbidden_regs = []
let pp_reg = pp_reg
let reg_compare = reg_compare
let reg_to_string = reg_to_string
let internal_init r =
if reg_compare r loop_idx = 0 then Some ("max_loop","int")
else None
let reg_class = function
as some instructions have eax as implicit argument ,
we must allocate our EAX to machine % eax
we must allocate our EAX to machine %eax *)
| EAX -> "=&a"
esi and edi implicit for MOVSD
| ESI -> "=&S"
| EDI -> "=&D"
| _ -> "=&r"
let reg_class_stable r = reg_class r
let comment = comment
let error _ _ = false
let warn _ _ = false
end)
let features = []
let nop = I_NOP
include HardwareExtra.No
module GetInstr = GetInstr.No(struct type instr=instruction end)
end
|
e00d04c9e6b4b7cde5d1f3d8073256d3f54b9cc7548be2ab89d95979c1211579 | tezos/tezos-mirror | client_keys.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 Nomadic Labs , < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
Testing
-------
Component : Client keys
Invocation : dune exec / tests / main.exe -- --file client_keys.ml
Subject : Checks client wallet commands
-------
Component: Client keys
Invocation: dune exec tezt/tests/main.exe -- --file client_keys.ml
Subject: Checks client wallet commands
*)
module BLS_aggregate_wallet = struct
let check_shown_account ~__LOC__ (expected : Account.aggregate_key)
(shown : Account.aggregate_key) =
if expected.aggregate_public_key_hash <> shown.aggregate_public_key_hash
then
Test.fail
~__LOC__
"Expecting %s, got %s as public key hash from the client "
expected.aggregate_public_key_hash
shown.aggregate_public_key_hash
else if expected.aggregate_public_key <> shown.aggregate_public_key then
Test.fail
~__LOC__
"Expecting %s, got %s as public key from the client "
expected.aggregate_public_key
shown.aggregate_public_key
else if expected.aggregate_secret_key <> shown.aggregate_secret_key then
let sk = Account.uri_of_secret_key shown.aggregate_secret_key in
let expected_sk = Account.uri_of_secret_key shown.aggregate_secret_key in
Test.fail
~__LOC__
"Expecting %s, got %s as secret key from the client "
expected_sk
sk
else return ()
let test_bls_import_secret_key () =
Test.register
~__FILE__
~tags:["aggregate"; "client"; "keys"]
~title:"Import BLS secret key in aggregate wallet"
(fun () ->
let* client = Client.init () in
let* () =
Client.bls_import_secret_key Constant.aggregate_tz4_account client
in
let* shown_account =
Client.bls_show_address
~alias:Constant.aggregate_tz4_account.Account.aggregate_alias
client
in
check_shown_account
~__LOC__
Constant.aggregate_tz4_account
shown_account)
let test_bls_show_address () =
Test.register
~__FILE__
~tags:["aggregate"; "client"; "keys"]
~title:"Shows the address of a registered BLS account in aggregate wallet"
(fun () ->
let* client = Client.init () in
let* () =
Client.bls_import_secret_key Constant.aggregate_tz4_account client
in
let* shown_account =
Client.bls_show_address
~alias:Constant.aggregate_tz4_account.Account.aggregate_alias
client
in
check_shown_account
~__LOC__
Constant.aggregate_tz4_account
shown_account)
let test_bls_gen_keys () =
Test.register
~__FILE__
~tags:["aggregate"; "client"; "keys"]
~title:"Generates new tz4 keys in aggregate wallet"
(fun () ->
let* client = Client.init () in
let* alias = Client.bls_gen_keys client in
let* _account = Client.bls_show_address ~alias client in
return ())
let test_bls_list_keys () =
Test.register
~__FILE__
~tags:["aggregate"; "client"; "keys"]
~title:"Lists known BLS aliases in the client's aggregate wallet"
(fun () ->
let* client = Client.init () in
let Account.{aggregate_alias; aggregate_public_key_hash; _} =
Constant.aggregate_tz4_account
in
let* () =
Client.bls_import_secret_key Constant.aggregate_tz4_account client
in
let* maybe_keys = Client.bls_list_keys client in
let expected_keys = [(aggregate_alias, aggregate_public_key_hash)] in
if List.equal ( = ) expected_keys maybe_keys then return ()
else
let pp ppf l =
Format.pp_print_list
~pp_sep:(fun ppf () -> Format.fprintf ppf "\n")
(fun ppf (a, k) -> Format.fprintf ppf "%s: %s" a k)
ppf
l
in
Test.fail
~__LOC__
"Expecting\n@[%a@]\ngot\n@[%a@]\nas keys from the client "
pp
expected_keys
pp
maybe_keys)
let register_protocol_independent () =
test_bls_import_secret_key () ;
test_bls_show_address () ;
test_bls_gen_keys () ;
test_bls_list_keys ()
end
module BLS_normal_wallet = struct
let check_shown_account ~__LOC__ (expected : Account.key)
(shown : Account.key) =
if expected.public_key_hash <> shown.public_key_hash then
Test.fail
~__LOC__
"Expecting %s, got %s as public key hash from the client "
expected.public_key_hash
shown.public_key_hash
else if expected.public_key <> shown.public_key then
Test.fail
~__LOC__
"Expecting %s, got %s as public key from the client "
expected.public_key
shown.public_key
else if expected.secret_key <> shown.secret_key then
let sk = Account.uri_of_secret_key shown.secret_key in
let expected_sk = Account.uri_of_secret_key shown.secret_key in
Test.fail
~__LOC__
"Expecting %s, got %s as secret key from the client "
expected_sk
sk
else return ()
let test_bls_import_secret_key () =
Test.register
~__FILE__
~tags:["bls"; "client"; "keys"]
~title:"Import BLS secret key"
(fun () ->
let* client = Client.init () in
let* () = Client.import_secret_key client Constant.tz4_account in
let* shown_account =
Client.show_address ~alias:Constant.tz4_account.Account.alias client
in
check_shown_account ~__LOC__ Constant.tz4_account shown_account)
let test_bls_show_address () =
Test.register
~__FILE__
~tags:["bls"; "client"; "keys"]
~title:"Shows the address of a registered BLS account"
(fun () ->
let* client = Client.init () in
let* () = Client.import_secret_key client Constant.tz4_account in
let* shown_account =
Client.show_address ~alias:Constant.tz4_account.Account.alias client
in
check_shown_account ~__LOC__ Constant.tz4_account shown_account)
let test_bls_gen_keys () =
Test.register
~__FILE__
~tags:["bls"; "client"; "keys"]
~title:"Generates new tz4 keys"
(fun () ->
let* client = Client.init () in
let* alias = Client.gen_keys ~sig_alg:"bls" client in
let* _account = Client.show_address ~alias client in
return ())
let register_protocol_independent () =
test_bls_import_secret_key () ;
test_bls_show_address () ;
test_bls_gen_keys ()
end
module Wallet = struct
let test_duplicate_alias () =
Test.register
~__FILE__
~tags:["client"; "keys"; "duplicate"]
~title:"Add a duplicate address"
@@ fun () ->
let* client = Client.init () in
let* (_ : string) = Client.gen_keys client ~alias:"foo" in
let* account_foo = Client.show_address client ~alias:"foo" in
let msg =
rex
"this public key hash is already aliased as foo, use --force to insert \
duplicate"
in
let* () =
Client.spawn_add_address client ~alias:"baz" ~src:account_foo.alias
|> Process.check_error ~msg
in
let* () =
Client.spawn_add_address
client
~alias:"baz"
~src:account_foo.public_key_hash
|> Process.check_error ~msg
in
let* _alias2 =
Client.add_address client ~force:true ~alias:"baz" ~src:"foo"
in
(* Check that we can read the secret key of [foo],
and that the original [foo] is equal to [baz]
(modulo the alias) *)
let* account_foo2 = Client.show_address ~alias:"foo" client in
let* account_baz = Client.show_address ~alias:"baz" client in
Check.(
(account_foo = account_foo2)
Account.key_typ
~__LOC__
~error_msg:"Expected %R, got %L") ;
Check.(
(account_foo = {account_baz with alias = "foo"})
Account.key_typ
~__LOC__
~error_msg:"Expected %R, got %L") ;
return ()
let test_remember_contract =
Protocol.register_test
~__FILE__
~tags:["client"; "contract"; "remember"]
~title:"Test remember contract"
@@ fun protocol ->
let* client = Client.init_mockup ~protocol () in
[
("test", "KT1BuEZtb68c1Q4yjtckcNjGELqWt56Xyesc");
("test-2", "KT1TZCh8fmUbuDqFxetPWC2fsQanAHzLx4W9");
]
|> Lwt_list.iter_s @@ fun (alias, address) ->
let* () = Client.remember_contract client ~alias ~address in
let* () = Client.remember_contract client ~force:true ~alias ~address in
let* () =
Client.spawn_remember_contract client ~alias ~address
|> Process.check_error
~msg:(rex ("The contract alias " ^ alias ^ " already exists"))
in
unit
(* Checks that the keys are correctly imported from a mnemonic. *)
let test_import_key_mnemonic () =
Test.register
~__FILE__
~title:"Wallet: Import key mnemonic"
~tags:["client"; "keys"; "import"; "mnemonic"]
@@ fun () ->
let mnemonic =
[
"seek";
"paddle";
"siege";
"sting";
"siege";
"sick";
"kidney";
"detect";
"coral";
"because";
"comfort";
"long";
"enforce";
"napkin";
"enter";
]
in
let* client = Client.init () in
Log.info "Test a simple import." ;
let* () =
Client.import_keys_from_mnemonic
~force:true
client
~alias:"zebra"
~mnemonic:
[
"release";
"easy";
"pulp";
"drop";
"select";
"attack";
"false";
"math";
"cook";
"angry";
"spin";
"ostrich";
"round";
"dress";
"acoustic";
]
in
let* addresses = Client.list_known_addresses client in
Check.(
(List.assoc_opt "zebra" addresses
= Some "tz1aGUKE72eN21iWztoDEeH4FeKaxWb7SAUb")
(option string)
~__LOC__
~error_msg:"Expected %R, got %L") ;
Log.info "Test that importing fails if the alias is already present." ;
let alias = "super_original" in
let* () =
Client.import_keys_from_mnemonic ~force:true client ~alias ~mnemonic
in
let* () =
let process, output_channel =
Client.spawn_import_keys_from_mnemonic client ~alias
in
let stdin = String.concat " " mnemonic ^ "\n\n" in
let* () = Lwt_io.write_line output_channel stdin in
let* () = Lwt_io.close output_channel in
Process.check_error
process
~msg:(rex "The secret_key alias super_original already exists.")
in
Log.info "Test an import where the user specifies a passphrase." ;
let passphrase = "very_secure_passphrase" in
let* () =
Client.import_keys_from_mnemonic
~force:true
client
~alias:"key"
~mnemonic
~passphrase
in
let* addresses = Client.list_known_addresses client in
Check.(
(List.assoc_opt "key" addresses
= Some "tz1QSF4TSVzaosgbaxnFJpRbs7798Skeb8Re")
(option string)
~__LOC__
~error_msg:"Expected %R, got %L") ;
Log.info "Test an import where the user wants to encrypt the key." ;
let* () =
let alias = "cryptkey" in
let encryption_password = "imgonnaencryptthiskeysohard" in
let* () =
Client.import_keys_from_mnemonic
~force:true
~encryption_password
client
~alias
~mnemonic
~passphrase
in
let* addresses = Client.list_known_addresses client in
Check.(
(List.assoc_opt alias addresses
= Some "tz1QSF4TSVzaosgbaxnFJpRbs7798Skeb8Re")
(option string)
~__LOC__
~error_msg:"Expected %R, got %L") ;
let* account = Client.show_address ~alias client in
match account.secret_key with
| Encrypted _ -> unit
| Unencrypted _ -> Test.fail "Expected an encrypted secret key"
in
Log.info "Test that the command fails if the user gives a bad mnemonic." ;
let* () =
let process, output_channel =
Client.spawn_import_keys_from_mnemonic client ~alias:"alias"
in
let stdin = "hello\n\n" in
let* () = Lwt_io.write_line output_channel stdin in
let* () = Lwt_io.close output_channel in
Process.check_error
process
~msg:(rex "\"hello\" is not a valid BIP39 mnemonic.")
in
unit
let register_protocol_independent () =
test_duplicate_alias () ;
test_import_key_mnemonic ()
let register protocols = test_remember_contract protocols
end
let register_protocol_independent () =
BLS_aggregate_wallet.register_protocol_independent () ;
BLS_normal_wallet.register_protocol_independent () ;
Wallet.register_protocol_independent ()
let register ~protocols = Wallet.register protocols
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/123f067d73d29774537076eab28ffe44e2be6a3b/tezt/tests/client_keys.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
Check that we can read the secret key of [foo],
and that the original [foo] is equal to [baz]
(modulo the alias)
Checks that the keys are correctly imported from a mnemonic. | Copyright ( c ) 2022 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
Testing
-------
Component : Client keys
Invocation : dune exec / tests / main.exe -- --file client_keys.ml
Subject : Checks client wallet commands
-------
Component: Client keys
Invocation: dune exec tezt/tests/main.exe -- --file client_keys.ml
Subject: Checks client wallet commands
*)
module BLS_aggregate_wallet = struct
let check_shown_account ~__LOC__ (expected : Account.aggregate_key)
(shown : Account.aggregate_key) =
if expected.aggregate_public_key_hash <> shown.aggregate_public_key_hash
then
Test.fail
~__LOC__
"Expecting %s, got %s as public key hash from the client "
expected.aggregate_public_key_hash
shown.aggregate_public_key_hash
else if expected.aggregate_public_key <> shown.aggregate_public_key then
Test.fail
~__LOC__
"Expecting %s, got %s as public key from the client "
expected.aggregate_public_key
shown.aggregate_public_key
else if expected.aggregate_secret_key <> shown.aggregate_secret_key then
let sk = Account.uri_of_secret_key shown.aggregate_secret_key in
let expected_sk = Account.uri_of_secret_key shown.aggregate_secret_key in
Test.fail
~__LOC__
"Expecting %s, got %s as secret key from the client "
expected_sk
sk
else return ()
let test_bls_import_secret_key () =
Test.register
~__FILE__
~tags:["aggregate"; "client"; "keys"]
~title:"Import BLS secret key in aggregate wallet"
(fun () ->
let* client = Client.init () in
let* () =
Client.bls_import_secret_key Constant.aggregate_tz4_account client
in
let* shown_account =
Client.bls_show_address
~alias:Constant.aggregate_tz4_account.Account.aggregate_alias
client
in
check_shown_account
~__LOC__
Constant.aggregate_tz4_account
shown_account)
let test_bls_show_address () =
Test.register
~__FILE__
~tags:["aggregate"; "client"; "keys"]
~title:"Shows the address of a registered BLS account in aggregate wallet"
(fun () ->
let* client = Client.init () in
let* () =
Client.bls_import_secret_key Constant.aggregate_tz4_account client
in
let* shown_account =
Client.bls_show_address
~alias:Constant.aggregate_tz4_account.Account.aggregate_alias
client
in
check_shown_account
~__LOC__
Constant.aggregate_tz4_account
shown_account)
let test_bls_gen_keys () =
Test.register
~__FILE__
~tags:["aggregate"; "client"; "keys"]
~title:"Generates new tz4 keys in aggregate wallet"
(fun () ->
let* client = Client.init () in
let* alias = Client.bls_gen_keys client in
let* _account = Client.bls_show_address ~alias client in
return ())
let test_bls_list_keys () =
Test.register
~__FILE__
~tags:["aggregate"; "client"; "keys"]
~title:"Lists known BLS aliases in the client's aggregate wallet"
(fun () ->
let* client = Client.init () in
let Account.{aggregate_alias; aggregate_public_key_hash; _} =
Constant.aggregate_tz4_account
in
let* () =
Client.bls_import_secret_key Constant.aggregate_tz4_account client
in
let* maybe_keys = Client.bls_list_keys client in
let expected_keys = [(aggregate_alias, aggregate_public_key_hash)] in
if List.equal ( = ) expected_keys maybe_keys then return ()
else
let pp ppf l =
Format.pp_print_list
~pp_sep:(fun ppf () -> Format.fprintf ppf "\n")
(fun ppf (a, k) -> Format.fprintf ppf "%s: %s" a k)
ppf
l
in
Test.fail
~__LOC__
"Expecting\n@[%a@]\ngot\n@[%a@]\nas keys from the client "
pp
expected_keys
pp
maybe_keys)
let register_protocol_independent () =
test_bls_import_secret_key () ;
test_bls_show_address () ;
test_bls_gen_keys () ;
test_bls_list_keys ()
end
module BLS_normal_wallet = struct
let check_shown_account ~__LOC__ (expected : Account.key)
(shown : Account.key) =
if expected.public_key_hash <> shown.public_key_hash then
Test.fail
~__LOC__
"Expecting %s, got %s as public key hash from the client "
expected.public_key_hash
shown.public_key_hash
else if expected.public_key <> shown.public_key then
Test.fail
~__LOC__
"Expecting %s, got %s as public key from the client "
expected.public_key
shown.public_key
else if expected.secret_key <> shown.secret_key then
let sk = Account.uri_of_secret_key shown.secret_key in
let expected_sk = Account.uri_of_secret_key shown.secret_key in
Test.fail
~__LOC__
"Expecting %s, got %s as secret key from the client "
expected_sk
sk
else return ()
let test_bls_import_secret_key () =
Test.register
~__FILE__
~tags:["bls"; "client"; "keys"]
~title:"Import BLS secret key"
(fun () ->
let* client = Client.init () in
let* () = Client.import_secret_key client Constant.tz4_account in
let* shown_account =
Client.show_address ~alias:Constant.tz4_account.Account.alias client
in
check_shown_account ~__LOC__ Constant.tz4_account shown_account)
let test_bls_show_address () =
Test.register
~__FILE__
~tags:["bls"; "client"; "keys"]
~title:"Shows the address of a registered BLS account"
(fun () ->
let* client = Client.init () in
let* () = Client.import_secret_key client Constant.tz4_account in
let* shown_account =
Client.show_address ~alias:Constant.tz4_account.Account.alias client
in
check_shown_account ~__LOC__ Constant.tz4_account shown_account)
let test_bls_gen_keys () =
Test.register
~__FILE__
~tags:["bls"; "client"; "keys"]
~title:"Generates new tz4 keys"
(fun () ->
let* client = Client.init () in
let* alias = Client.gen_keys ~sig_alg:"bls" client in
let* _account = Client.show_address ~alias client in
return ())
let register_protocol_independent () =
test_bls_import_secret_key () ;
test_bls_show_address () ;
test_bls_gen_keys ()
end
module Wallet = struct
let test_duplicate_alias () =
Test.register
~__FILE__
~tags:["client"; "keys"; "duplicate"]
~title:"Add a duplicate address"
@@ fun () ->
let* client = Client.init () in
let* (_ : string) = Client.gen_keys client ~alias:"foo" in
let* account_foo = Client.show_address client ~alias:"foo" in
let msg =
rex
"this public key hash is already aliased as foo, use --force to insert \
duplicate"
in
let* () =
Client.spawn_add_address client ~alias:"baz" ~src:account_foo.alias
|> Process.check_error ~msg
in
let* () =
Client.spawn_add_address
client
~alias:"baz"
~src:account_foo.public_key_hash
|> Process.check_error ~msg
in
let* _alias2 =
Client.add_address client ~force:true ~alias:"baz" ~src:"foo"
in
let* account_foo2 = Client.show_address ~alias:"foo" client in
let* account_baz = Client.show_address ~alias:"baz" client in
Check.(
(account_foo = account_foo2)
Account.key_typ
~__LOC__
~error_msg:"Expected %R, got %L") ;
Check.(
(account_foo = {account_baz with alias = "foo"})
Account.key_typ
~__LOC__
~error_msg:"Expected %R, got %L") ;
return ()
let test_remember_contract =
Protocol.register_test
~__FILE__
~tags:["client"; "contract"; "remember"]
~title:"Test remember contract"
@@ fun protocol ->
let* client = Client.init_mockup ~protocol () in
[
("test", "KT1BuEZtb68c1Q4yjtckcNjGELqWt56Xyesc");
("test-2", "KT1TZCh8fmUbuDqFxetPWC2fsQanAHzLx4W9");
]
|> Lwt_list.iter_s @@ fun (alias, address) ->
let* () = Client.remember_contract client ~alias ~address in
let* () = Client.remember_contract client ~force:true ~alias ~address in
let* () =
Client.spawn_remember_contract client ~alias ~address
|> Process.check_error
~msg:(rex ("The contract alias " ^ alias ^ " already exists"))
in
unit
let test_import_key_mnemonic () =
Test.register
~__FILE__
~title:"Wallet: Import key mnemonic"
~tags:["client"; "keys"; "import"; "mnemonic"]
@@ fun () ->
let mnemonic =
[
"seek";
"paddle";
"siege";
"sting";
"siege";
"sick";
"kidney";
"detect";
"coral";
"because";
"comfort";
"long";
"enforce";
"napkin";
"enter";
]
in
let* client = Client.init () in
Log.info "Test a simple import." ;
let* () =
Client.import_keys_from_mnemonic
~force:true
client
~alias:"zebra"
~mnemonic:
[
"release";
"easy";
"pulp";
"drop";
"select";
"attack";
"false";
"math";
"cook";
"angry";
"spin";
"ostrich";
"round";
"dress";
"acoustic";
]
in
let* addresses = Client.list_known_addresses client in
Check.(
(List.assoc_opt "zebra" addresses
= Some "tz1aGUKE72eN21iWztoDEeH4FeKaxWb7SAUb")
(option string)
~__LOC__
~error_msg:"Expected %R, got %L") ;
Log.info "Test that importing fails if the alias is already present." ;
let alias = "super_original" in
let* () =
Client.import_keys_from_mnemonic ~force:true client ~alias ~mnemonic
in
let* () =
let process, output_channel =
Client.spawn_import_keys_from_mnemonic client ~alias
in
let stdin = String.concat " " mnemonic ^ "\n\n" in
let* () = Lwt_io.write_line output_channel stdin in
let* () = Lwt_io.close output_channel in
Process.check_error
process
~msg:(rex "The secret_key alias super_original already exists.")
in
Log.info "Test an import where the user specifies a passphrase." ;
let passphrase = "very_secure_passphrase" in
let* () =
Client.import_keys_from_mnemonic
~force:true
client
~alias:"key"
~mnemonic
~passphrase
in
let* addresses = Client.list_known_addresses client in
Check.(
(List.assoc_opt "key" addresses
= Some "tz1QSF4TSVzaosgbaxnFJpRbs7798Skeb8Re")
(option string)
~__LOC__
~error_msg:"Expected %R, got %L") ;
Log.info "Test an import where the user wants to encrypt the key." ;
let* () =
let alias = "cryptkey" in
let encryption_password = "imgonnaencryptthiskeysohard" in
let* () =
Client.import_keys_from_mnemonic
~force:true
~encryption_password
client
~alias
~mnemonic
~passphrase
in
let* addresses = Client.list_known_addresses client in
Check.(
(List.assoc_opt alias addresses
= Some "tz1QSF4TSVzaosgbaxnFJpRbs7798Skeb8Re")
(option string)
~__LOC__
~error_msg:"Expected %R, got %L") ;
let* account = Client.show_address ~alias client in
match account.secret_key with
| Encrypted _ -> unit
| Unencrypted _ -> Test.fail "Expected an encrypted secret key"
in
Log.info "Test that the command fails if the user gives a bad mnemonic." ;
let* () =
let process, output_channel =
Client.spawn_import_keys_from_mnemonic client ~alias:"alias"
in
let stdin = "hello\n\n" in
let* () = Lwt_io.write_line output_channel stdin in
let* () = Lwt_io.close output_channel in
Process.check_error
process
~msg:(rex "\"hello\" is not a valid BIP39 mnemonic.")
in
unit
let register_protocol_independent () =
test_duplicate_alias () ;
test_import_key_mnemonic ()
let register protocols = test_remember_contract protocols
end
let register_protocol_independent () =
BLS_aggregate_wallet.register_protocol_independent () ;
BLS_normal_wallet.register_protocol_independent () ;
Wallet.register_protocol_independent ()
let register ~protocols = Wallet.register protocols
|
6ba5b623bd3507f9b5128b9c128fc4ee9ad98a97cc962485ddad838f5f13a852 | mbj/stratosphere | ModelInputProperty.hs | module Stratosphere.SageMaker.ModelPackage.ModelInputProperty (
ModelInputProperty(..), mkModelInputProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data ModelInputProperty
= ModelInputProperty {dataInputConfig :: (Value Prelude.Text)}
mkModelInputProperty :: Value Prelude.Text -> ModelInputProperty
mkModelInputProperty dataInputConfig
= ModelInputProperty {dataInputConfig = dataInputConfig}
instance ToResourceProperties ModelInputProperty where
toResourceProperties ModelInputProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::ModelPackage.ModelInput",
supportsTags = Prelude.False,
properties = ["DataInputConfig" JSON..= dataInputConfig]}
instance JSON.ToJSON ModelInputProperty where
toJSON ModelInputProperty {..}
= JSON.object ["DataInputConfig" JSON..= dataInputConfig]
instance Property "DataInputConfig" ModelInputProperty where
type PropertyType "DataInputConfig" ModelInputProperty = Value Prelude.Text
set newValue ModelInputProperty {}
= ModelInputProperty {dataInputConfig = newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/ModelPackage/ModelInputProperty.hs | haskell | module Stratosphere.SageMaker.ModelPackage.ModelInputProperty (
ModelInputProperty(..), mkModelInputProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data ModelInputProperty
= ModelInputProperty {dataInputConfig :: (Value Prelude.Text)}
mkModelInputProperty :: Value Prelude.Text -> ModelInputProperty
mkModelInputProperty dataInputConfig
= ModelInputProperty {dataInputConfig = dataInputConfig}
instance ToResourceProperties ModelInputProperty where
toResourceProperties ModelInputProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::ModelPackage.ModelInput",
supportsTags = Prelude.False,
properties = ["DataInputConfig" JSON..= dataInputConfig]}
instance JSON.ToJSON ModelInputProperty where
toJSON ModelInputProperty {..}
= JSON.object ["DataInputConfig" JSON..= dataInputConfig]
instance Property "DataInputConfig" ModelInputProperty where
type PropertyType "DataInputConfig" ModelInputProperty = Value Prelude.Text
set newValue ModelInputProperty {}
= ModelInputProperty {dataInputConfig = newValue, ..} | |
f6754302c728931eed7e04b82bf1b9d67479f869cc625642f111c57bb4cc0586 | active-group/reacl | project.clj | (defproject reacl "2.2.10"
:description "ClojureScript wrappers for programming with React"
:url "-group/reacl"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:jvm-opts ^:replace ["-Xmx512m" "-server"]
:dependencies [[org.clojure/clojure "1.9.0" :scope "provided"]
[org.clojure/clojurescript "1.10.439" :scope "provided"]
[cljsjs/react "16.13.0-0"]
[cljsjs/react-dom "16.13.0-0"]
[cljsjs/create-react-class "15.6.3-0" :exclusions [cljsjs/react]]
[cljsjs/prop-types "15.6.2-0" :exclusions [cljsjs/react]]
[cljsjs/react-test-renderer "16.13.0-3" :exclusions [cljsjs/react]]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-doo "0.1.10"]
[lein-codox "0.10.5"]
[lein-auto "0.1.3"]]
:profiles {:dev {:dependencies [[de.active-group/active-clojure "0.37.1" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-doo "0.1.7"]
[codox-theme-rdash "0.1.2"]
[com.bhauman/figwheel-main "0.2.0"]
[com.bhauman/rebel-readline-cljs "0.1.4"]]
:resource-paths ["target" "dev-resources"]}
:test {:source-paths ["src" "test-nodom" "test-dom" "examples"]}
:test-dom {:source-paths ["src" "test-dom"]}
:test-nodom {:source-paths ["src" "test-nodom"]}}
;; open :9500/figwheel-extra-main/auto-testing for the tests.
;; open :9500/figwheel-extra-main/todo and others for the examples
:aliases {"fig" ["trampoline" "with-profile" "+dev,+test" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
;; google-chrome-stable seems to be broken at the moment:
;; -main/issues/159
;; we start chrome headless in karma in travis.yml
;; "figtest-dom-travis" ["trampoline" "with-profile" "+dev,+test-dom" "run" "-m" "figwheel.main" "-fwo" "{:launch-js [\"google-chrome-stable\" \"--no-sandbox\" \"--headless\" \"--disable-gpu\" \"--repl\" :open-url] :repl-eval-timeout 30000}" "-co" "test-dom.cljs.edn" "-m" reacl2.test.figwheel-test-runner]
;; "figtest-nodom-travis" ["trampoline" "with-profile" "+dev,+test-nodom" "run" "-m" "figwheel.main" "-fwo" "{:launch-js [\"google-chrome-stable\" \"--no-sandbox\" \"--headless\" \"--disable-gpu\" \"--repl\" :open-url] :repl-eval-timeout 30000}" "-co" "test-nodom.cljs.edn" "-m" reacl2.test.figwheel-test-runner]
}
:codox {:language :clojurescript
:metadata {:doc/format :markdown}
:themes [:rdash]
:src-dir-uri "-group/reacl/blob/master/"
:src-linenum-anchor-prefix "L"}
:clean-targets ^{:protect false} [:target-path "out" "target"]
;; for test driven development use
> auto do clean , doo chrome - headless test - nodom once , doo chrome - headless test - dom once
:auto {:default {:paths ["src" "test-dom" "test-nodom" "examples"]}}
:cljsbuild
{ :builds [{:id "test-dom"
:source-paths ["src" "test-dom"]
:compiler {:output-to "target/test-dom.js"
:output-dir "target/test-dom"
:main reacl2.test.runner
:optimizations :whitespace}}
{:id "test-nodom"
:source-paths ["src" "test-nodom"]
:compiler {:output-to "target/test-nodom.js"
:output-dir "target/test-nodom"
:main reacl2.test.runner
}}
;; examples
{:id "products"
:source-paths ["src" "examples/products"]
:compiler {:output-to "target/products/main.js"
:output-dir "target/products/out"
:source-map "target/products/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "todo"
:source-paths ["src" "examples/todo"]
:compiler {:output-to "target/todo/main.js"
:output-dir "target/todo/out"
:source-map "target/todo/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "todo-reacl1"
:source-paths ["src" "examples/todo-reacl1"]
:compiler {:output-to "target/todo-reacl1/main.js"
:output-dir "target/todo-reacl1/out"
:source-map "target/todo-reacl1/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "comments"
:source-paths ["src" "examples/comments"]
:compiler {:output-to "target/comments/main.js"
:output-dir "target/comments/out"
:source-map "target/comments/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "tabs"
:source-paths ["src" "examples/tabs"]
:compiler {:output-to "target/tabs/main.js"
:output-dir "target/tabs/out"
:source-map "target/tabs/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "arranger"
:source-paths ["src" "examples/arranger"]
:compiler {:output-to "target/arranger/main.js"
:output-dir "target/arranger/out"
:source-map "target/arranger/main.map"
:optimizations :whitespace
:parallel-build true}}]}
)
| null | https://raw.githubusercontent.com/active-group/reacl/ee0cc720e038dcd7822d0251b0aba9e0995dd177/project.clj | clojure | open :9500/figwheel-extra-main/auto-testing for the tests.
open :9500/figwheel-extra-main/todo and others for the examples
google-chrome-stable seems to be broken at the moment:
-main/issues/159
we start chrome headless in karma in travis.yml
"figtest-dom-travis" ["trampoline" "with-profile" "+dev,+test-dom" "run" "-m" "figwheel.main" "-fwo" "{:launch-js [\"google-chrome-stable\" \"--no-sandbox\" \"--headless\" \"--disable-gpu\" \"--repl\" :open-url] :repl-eval-timeout 30000}" "-co" "test-dom.cljs.edn" "-m" reacl2.test.figwheel-test-runner]
"figtest-nodom-travis" ["trampoline" "with-profile" "+dev,+test-nodom" "run" "-m" "figwheel.main" "-fwo" "{:launch-js [\"google-chrome-stable\" \"--no-sandbox\" \"--headless\" \"--disable-gpu\" \"--repl\" :open-url] :repl-eval-timeout 30000}" "-co" "test-nodom.cljs.edn" "-m" reacl2.test.figwheel-test-runner]
for test driven development use
examples | (defproject reacl "2.2.10"
:description "ClojureScript wrappers for programming with React"
:url "-group/reacl"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:jvm-opts ^:replace ["-Xmx512m" "-server"]
:dependencies [[org.clojure/clojure "1.9.0" :scope "provided"]
[org.clojure/clojurescript "1.10.439" :scope "provided"]
[cljsjs/react "16.13.0-0"]
[cljsjs/react-dom "16.13.0-0"]
[cljsjs/create-react-class "15.6.3-0" :exclusions [cljsjs/react]]
[cljsjs/prop-types "15.6.2-0" :exclusions [cljsjs/react]]
[cljsjs/react-test-renderer "16.13.0-3" :exclusions [cljsjs/react]]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-doo "0.1.10"]
[lein-codox "0.10.5"]
[lein-auto "0.1.3"]]
:profiles {:dev {:dependencies [[de.active-group/active-clojure "0.37.1" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-doo "0.1.7"]
[codox-theme-rdash "0.1.2"]
[com.bhauman/figwheel-main "0.2.0"]
[com.bhauman/rebel-readline-cljs "0.1.4"]]
:resource-paths ["target" "dev-resources"]}
:test {:source-paths ["src" "test-nodom" "test-dom" "examples"]}
:test-dom {:source-paths ["src" "test-dom"]}
:test-nodom {:source-paths ["src" "test-nodom"]}}
:aliases {"fig" ["trampoline" "with-profile" "+dev,+test" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
}
:codox {:language :clojurescript
:metadata {:doc/format :markdown}
:themes [:rdash]
:src-dir-uri "-group/reacl/blob/master/"
:src-linenum-anchor-prefix "L"}
:clean-targets ^{:protect false} [:target-path "out" "target"]
> auto do clean , doo chrome - headless test - nodom once , doo chrome - headless test - dom once
:auto {:default {:paths ["src" "test-dom" "test-nodom" "examples"]}}
:cljsbuild
{ :builds [{:id "test-dom"
:source-paths ["src" "test-dom"]
:compiler {:output-to "target/test-dom.js"
:output-dir "target/test-dom"
:main reacl2.test.runner
:optimizations :whitespace}}
{:id "test-nodom"
:source-paths ["src" "test-nodom"]
:compiler {:output-to "target/test-nodom.js"
:output-dir "target/test-nodom"
:main reacl2.test.runner
}}
{:id "products"
:source-paths ["src" "examples/products"]
:compiler {:output-to "target/products/main.js"
:output-dir "target/products/out"
:source-map "target/products/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "todo"
:source-paths ["src" "examples/todo"]
:compiler {:output-to "target/todo/main.js"
:output-dir "target/todo/out"
:source-map "target/todo/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "todo-reacl1"
:source-paths ["src" "examples/todo-reacl1"]
:compiler {:output-to "target/todo-reacl1/main.js"
:output-dir "target/todo-reacl1/out"
:source-map "target/todo-reacl1/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "comments"
:source-paths ["src" "examples/comments"]
:compiler {:output-to "target/comments/main.js"
:output-dir "target/comments/out"
:source-map "target/comments/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "tabs"
:source-paths ["src" "examples/tabs"]
:compiler {:output-to "target/tabs/main.js"
:output-dir "target/tabs/out"
:source-map "target/tabs/main.map"
:optimizations :whitespace
:parallel-build true}}
{:id "arranger"
:source-paths ["src" "examples/arranger"]
:compiler {:output-to "target/arranger/main.js"
:output-dir "target/arranger/out"
:source-map "target/arranger/main.map"
:optimizations :whitespace
:parallel-build true}}]}
)
|
aa5ba65035864a99ff82a7bab73f829ada9437ed664c5570afe1de2c1dadaef6 | marineschimel/ilqr_vae | covariance.ml | open Base
open Owl
include Covariance_typ
module Covariance = struct
module P = Owl_parameters.Make (Covariance_P)
open Covariance_P
let init
?(no_triangle = false)
?(pin_diag = false)
?(sigma2 = 1.)
(set : Owl_parameters.setter)
n
=
let d = Mat.create 1 n Maths.(sqrt sigma2) in
let t = AD.Mat.zeros n n in
{ d = (if pin_diag then Owl_parameters.pinned else set) ~above:0.0001 (AD.pack_arr d)
; t = (if no_triangle then Owl_parameters.pinned else set) t
}
let to_chol_factor c =
let t = Owl_parameters.extract c.t in
let d = Owl_parameters.extract c.d in
AD.Maths.(triu ~k:1 t + diagm d)
let invert c =
let ell = c |> to_chol_factor in
let ell_inv = AD.Linalg.linsolve ~typ:`u ell AD.Mat.(eye (row_num ell)) in
let d = AD.Maths.diag ell in
let t = ell_inv in
let open Owl_parameters in
let d =
match c.d with
| Pinned _ -> Pinned d
| Learned_bounded (_, lb, None) -> Learned_bounded (d, lb, None)
| _ -> failwith "oooops"
in
let t =
match c.d with
| Pinned _ -> Pinned t
| _ -> Learned t
in
Covariance_P.{ d; t }
end
| null | https://raw.githubusercontent.com/marineschimel/ilqr_vae/8bdda2bfcf0729f965b2ab9e5aab5042a240c64d/lib/covariance.ml | ocaml | open Base
open Owl
include Covariance_typ
module Covariance = struct
module P = Owl_parameters.Make (Covariance_P)
open Covariance_P
let init
?(no_triangle = false)
?(pin_diag = false)
?(sigma2 = 1.)
(set : Owl_parameters.setter)
n
=
let d = Mat.create 1 n Maths.(sqrt sigma2) in
let t = AD.Mat.zeros n n in
{ d = (if pin_diag then Owl_parameters.pinned else set) ~above:0.0001 (AD.pack_arr d)
; t = (if no_triangle then Owl_parameters.pinned else set) t
}
let to_chol_factor c =
let t = Owl_parameters.extract c.t in
let d = Owl_parameters.extract c.d in
AD.Maths.(triu ~k:1 t + diagm d)
let invert c =
let ell = c |> to_chol_factor in
let ell_inv = AD.Linalg.linsolve ~typ:`u ell AD.Mat.(eye (row_num ell)) in
let d = AD.Maths.diag ell in
let t = ell_inv in
let open Owl_parameters in
let d =
match c.d with
| Pinned _ -> Pinned d
| Learned_bounded (_, lb, None) -> Learned_bounded (d, lb, None)
| _ -> failwith "oooops"
in
let t =
match c.d with
| Pinned _ -> Pinned t
| _ -> Learned t
in
Covariance_P.{ d; t }
end
| |
ab7a747c8db422a4203ef8c9b9616761599f8dad95968aea4a2c707af820b2c9 | mbutterick/aoc-racket | input.rkt | #lang reader "lang.rkt"
420604416-480421096
172102328-195230700
613677102-639635955
1689844284-1724152701
3358865073-3365629764
1333423844-1344930397
2519115700-2535290065
698684483-723211151
979757052-1003200781
4165068842-4190472815
2020267004-2045214369
2979897715-3004836346
2110213890-2115506975
2970017340-2973461626
2236378365-2258142409
3423992974-3426380317
1462489107-1490036931
2189940955-2198476022
2417413696-2430182746
3624276792-3633790184
1005063612-1009015074
1061038892-1061410454
2276099915-2310172070
1202572862-1215598809
1783724555-1785267178
1262810964-1264200367
592924330-594021870
1981502514-2001291898
3639371125-3691832997
751455858-758389721
575870144-588215938
2707934395-2711294609
2271125072-2271532092
723211153-745881341
291750706-293834948
3846273818-3846421786
1798292566-1840652756
907920869-908496244
2979008391-2984333350
3120502195-3140695376
1316734884-1323407408
4013388816-4015102290
4211041074-4243535195
3264591092-3270165984
1356324132-1369836240
3500337320-3511856741
2675082203-2680516758
269092398-286582232
9214023-16864642
3496293771-3507984426
789173169-790658193
1589657426-1592447273
3018889533-3040428852
3190582871-3209497449
2582019510-2592221443
452701865-462658183
581072273-585497818
2885687081-2887027444
405199391-406037773
1926405498-1961345770
1591447330-1595803034
2075061753-2117082859
2738757089-2739984421
1758742902-1766649306
1598451138-1603784829
904873440-933144524
743128701-751089192
2946510215-2953128493
4258067806-4258357961
2162946809-2194271963
2502065462-2529412983
1794208357-1812728725
2399604728-2399751734
2675639614-2686964361
1243509131-1261449357
1334629713-1360716911
490307573-506198210
3865783894-3882438935
1355288427-1356825096
4080632471-4085694027
1069989320-1079328173
1261530547-1263095027
1864453415-1864536898
500660752-513276733
859810764-865812062
4054243009-4055337105
795048590-839560602
2708730392-2712322515
3642043390-3653718654
2350724230-2355301182
663974525-698684482
734062708-734919764
2004656983-2006812551
987361385-989501665
3621608802-3622545302
1133546243-1135802698
147516310-150573031
2271038167-2271338460
3912004191-3947848898
2301820906-2338108229
2361989797-2363651982
3867365-5819500
3702314080-3703559974
4134127328-4135370466
756306610-770493891
2079529322-2090642509
3981814383-3992802961
4031189022-4042698219
1560502437-1565573103
408025952-414757361
137808459-150920914
3393581407-3411447948
2151896844-2162946807
4201010521-4201471695
3713302577-3725874062
142387170-154849830
2166232094-2205567227
3291340751-3298984606
938375497-943547413
4055961596-4110367884
136677359-137609692
3037464396-3044180771
2691576247-2691980924
1009015076-1045645521
789113477-790592023
899519940-911794289
2137437783-2155776766
1399083500-1402900021
1469947218-1479256900
2944855925-2953686693
2910064491-2920533014
144173340-148094230
2360899146-2362380838
2013535209-2049558890
1109489564-1124585673
2756379565-2767828753
1060568096-1073644115
1691100485-1728041197
1592871439-1600233767
1516639981-1518466748
2098130915-2098541161
3704291842-3706581331
962586078-1003763244
527697837-533713889
1856931843-1873776214
2399693233-2399917980
2055406323-2063623078
240041628-275447727
1513843540-1521844727
1648487379-1649719916
2087056931-2102042862
3717079814-3719847466
1500211877-1510297315
407413483-415066321
3596458788-3618072868
218197655-228951780
643659026-656047997
1603704290-1614650204
2358880422-2366638177
3004836348-3015765511
3046845638-3046851095
3305333257-3307471995
2401731427-2405370552
4017360677-4027723482
557056664-575870142
609440078-615655979
1139493162-1151170381
428962141-483384245
2293357845-2334971307
3091700546-3119568633
1864347502-1864482912
1749751448-1750782554
420140812-420604414
1317387394-1324899402
3623998911-3629315327
4150451309-4152623876
434323808-454005042
1858560120-1864845209
2009686203-2018214121
605094405-611343970
4256094197-4258455116
1177692263-1227426205
4011096895-4014427778
39304785-47673299
498903368-524596608
605553131-610691072
3048424158-3066041482
153238649-154812518
1317950434-1324244958
3355309684-3360596455
2409598473-2428168849
2946469763-2949510201
543235050-544883779
1079837788-1081762723
3600722024-3622452566
4257178957-4258853576
1922845451-1979527610
1162924278-1217904821
1854156984-1867582222
2573163840-2578960281
1159211723-1163517189
1490036932-1500211875
482764386-488744315
235990048-265498430
1714315712-1724421861
958737616-962586076
790658195-851798647
2019736814-2021017547
2162802-8327007
787368380-789171975
3467221232-3469771790
3416813106-3439834312
906735025-908389759
64489226-70116603
1908532718-1922845449
1234754192-1245016567
3287320754-3296095689
3031537491-3039742613
3769892977-3785548652
1645238060-1655418015
612066331-620597775
2905104738-2920311121
2014785668-2022435799
3844301667-3844798343
2828382380-2863199622
2676931732-2682206642
171451625-218197654
2153052343-2156659109
610691073-636761246
2604642896-2615712599
1589965559-1603704289
2935029177-2942217574
186697135-187447861
1986224726-1986550701
770493893-789113476
3557491384-3562596711
2898302199-2920593201
934606912-955515749
1855368372-1872942514
2570443173-2571696675
186869593-188420012
1029668904-1048703657
3284676192-3295161434
3955266215-3977053319
2476141495-2479329360
4276025347-4283606977
534415917-569504381
2263536298-2268109489
1200129331-1210019228
3971350693-3990304290
489813454-495749644
1743364359-1768398619
3924729773-3931294732
105847925-111482255
794582284-818505469
1811415389-1838855885
1890243027-1898852651
1986067335-1986471617
104143552-106052965
772703103-776359533
3911720342-3933921905
395790945-398705617
2258142410-2267980008
613561861-616915116
3310135636-3330660281
2061419260-2061539636
2624281089-2626673183
1877477043-1884442706
2933979446-2949991401
543661669-563658372
197557686-226037744
613176712-618285697
4265278830-4278950571
3556799964-3560580457
1116126837-1122976017
1187703503-1205238834
983871724-1001238917
3887842382-3903790188
2641349279-2643172883
3583057749-3587680646
2601030398-2608486868
4157885743-4168988833
1162830362-1167726097
2514929623-2525222702
3291107480-3295972867
2151518630-2154613192
3046851552-3046878017
325969068-334085941
189084100-189886055
3650880042-3683085757
2453733029-2471942669
1662489961-1666626344
44287139-49449042
1400982930-1421830420
2546953607-2554587873
2639634659-2672001824
641036962-646629131
1236906461-1244507638
1331784152-1367083336
506198211-527697835
255997224-260755488
2588563930-2611385666
3599734818-3614926593
2285367719-2289556931
1088850011-1109811497
3586236383-3589929173
2399595142-2399763869
1385676603-1390665612
3513146704-3513797148
2738224131-2740166097
2869889938-2880215300
2005865698-2011251487
3046872422-3055338791
2940602932-2944294443
3711823219-3713306331
327670367-327738352
2793738-2841656
3807120966-3836270308
3711433856-3712911001
592896405-592954516
688452447-718340962
2063048458-2068052789
4162162406-4167839641
2049558892-2064994876
20968691-38549168
2497497428-2510517683
1583336096-1589657424
1143974607-1155771407
2381952303-2397368087
2009571163-2013286329
942853383-944865487
951722030-952400166
200197723-215328622
3106021045-3120502193
4140023055-4149617577
1668895062-1671431568
2626673185-2653038422
1841289175-1846422485
335754679-386244011
4062044458-4068497802
331356502-332799273
3307471997-3371549847
2018475560-2021933871
150920915-171451623
2194931559-2195514567
4089933248-4090707368
4157463945-4165762209
4100746531-4104107984
3411013858-3416813104
3374946441-3393581406
2552376718-2552429766
725947111-751643934
2473774976-2490564633
3566405121-3581497459
2683823262-2693090640
2734605142-2742827358
3441986164-3442398493
1524044927-1541206072
4254311927-4257287997
2411062371-2425081809
3666577856-3698298724
440803690-480698287
1614650206-1663590083
4257850447-4258201271
2637194180-2658593345
1269282838-1312761281
2522666665-2525818042
141503475-143914340
364934589-385277316
24026223-27879741
3557755338-3564098914
2943664323-2954588780
1571687539-1572996177
957113399-959367378
3585168986-3592657057
1356305980-1369637926
3630349604-3639371123
2570730499-2575580881
2459213065-2486172460
814620199-829988953
1983439516-1984861942
3800496806-3833569562
2841657-3867364
1706481656-1713944571
454683370-473903295
2697862561-2701781892
1451637419-1454646761
501104716-523461517
3304490686-3306418502
3846192081-3846304020
4191662000-4235899383
4096574372-4111227622
480421097-485653417
3762938052-3790582378
701786054-705861635
1214808315-1215006746
364434099-382831881
3713276399-3714579266
1336679025-1347883722
1979527611-1979886571
2090642510-2129888576
3624144511-3633098213
2097515227-2098217363
1851357581-1859249610
3021641379-3030459043
860720178-867061373
4053454232-4055923518
591971809-592927822
899570088-914232296
3171743426-3178833535
1767780850-1769461322
1648285748-1664437761
2756023351-2772357724
1841385621-1851357579
1764427585-1768013247
3968976986-3979761882
204898529-205069325
1192059065-1225447718
204967480-205140904
3191614963-3205521380
2687221525-2690406018
3713502419-3714707176
859460566-860824071
2761514667-2765543032
3357906031-3364349724
3275219921-3282195064
3391484605-3394594750
406732797-420140811
4273899514-4281205511
3083762422-3113295478
2193854781-2195333482
4203706684-4251257733
384194709-397192696
3591265505-3596458786
1102914397-1124045826
2310172071-2344149963
3066041483-3069828748
2635666365-2641585945
1060740916-1061127459
3774707512-3782147573
1743737707-1779166247
246638755-280110373
851798648-859460564
605075197-611133696
2293962494-2298136342
3460740393-3471166317
3280182044-3284676190
14791161-17348573
2691399120-2691637915
1728558700-1733098513
3461545676-3473725502
3751769544-3774673277
772066259-780246746
3356968359-3362991077
1605924820-1613022664
4015102292-4053454231
4206207007-4214797098
1335854520-1363709511
823795603-854558918
3290449369-3304490685
2540570240-2570730498
749722515-756306609
3442398495-3465001104
4229168442-4235745839
150802546-151838496
1380772851-1392292807
4190472817-4203706683
1466784263-1498319230
50105778-54260393
0-2793737
2956453641-2979008390
2552426525-2553141195
3069828750-3083762421
2800389226-2809306363
2275201948-2301909928
670647362-674039479
2639146472-2642836023
3846421788-3895249037
326561664-329333434
188182835-189612566
4253790781-4254533752
1804500603-1806558363
2405370554-2428432104
3608464545-3623946707
2353553540-2360491647
1325917396-1352060617
3577002908-3585168985
1864487525-1877898802
2535505356-2540570238
2012841949-2013535208
4122773972-4147066021
2221253241-2227916854
3996989806-4013388815
1118808237-1118876034
406730726-412027046
2830200680-2841462745
4009639150-4012108169
3387543681-3395550318
2412794571-2444576238
1022924735-1024398890
643270862-663974523
907974347-909753482
4148481231-4151899399
2061333796-2061422413
3844115908-3844704314
296503398-319176563
2743436711-2744991704
1024231444-1050533093
2976066221-2982350583
3913440938-3921340086
2546064716-2552639130
647510635-649788184
1861939256-1878905542
1119182827-1127962138
4176776277-4185432506
1728041199-1736154206
1905044208-1915920572
1860265438-1881626361
2934389290-2943526097
1068791968-1074539223
3124236778-3149982255
286582234-304243327
2100258789-2123748546
3432475911-3432766967
82082661-88073370
2327755908-2338617065
734803505-734970787
4225862764-4241303856
1352060618-1372691007
2552301217-2552408303
3873980245-3908789488
734733934-734933525
913241510-934606910
1746136669-1783130039
3478455269-3482503593
2300261034-2307782855
3248901770-3254155181
651662856-660523209
1118827933-1118873914
3495324533-3508390070
3614090639-3630342601
4152623878-4165068841
4251257735-4252768738
740064940-744628705
2663526-7317845
3173018368-3173033650
840243299-850630387
874982768-893955653
4195369814-4215042523
3712999015-3713605711
3167305950-3179505229
68345070-74894937
3467499056-3471357060
623795984-626879791
533357402-536413407
3551720149-3555281211
3933921906-3941710756
1732833292-1736931431
1172618521-1194746246
2011668991-2019214712
4173423213-4185833738
4129967821-4130008117
2025432624-2029847095
1663590084-1670239922
1677571493-1698026005
1167726098-1232818725
3785872097-3790663631
3140695377-3166258968
2971784945-2974988576
538998996-562454834
4225819511-4229474556
610567638-613651106
2462186480-2480650826
75973934-91434042
2688408664-2707934393
228951782-267685402
1783130040-1784614561
1872942515-1880846327
1262147457-1263932136
4024512115-4053495116
579938959-585172735
602874206-610295015
403990885-414323983
1730191207-1736990500
3623946708-3627097897
1350246834-1362835856
232836175-284581763
1569378906-1570007725
3026358814-3033526682
1636906011-1655244443
1346904336-1351608843
363534678-372420875
3465001105-3471897467
3934746154-3952361164
7208229-13983082
3469317144-3474090343
4280938719-4290730270
2020957337-2022484776
1692136283-1719643620
4032740692-4053771021
2972345930-2975812534
140067848-159037627
3630086418-3634626029
3252572678-3274451634
77141551-85341019
692066237-700847528
3552713357-3558885449
3075915215-3085817045
4162664504-4169419288
124626946-135046727
1884442708-1905044207
3703243550-3704832207
2220909545-2224015721
2692074751-2692885915
1069864185-1073578735
2691786564-2692864691
1737853571-1745347739
95461456-115187423
143224398-144838969
2138286928-2151694571
867061374-882471488
983262449-1001173152
4129969371-4130354697
3470641201-3487201657
2051110734-2064915382
747750272-758258548
3333190532-3365085965
3015765512-3029456808
3265304770-3277560812
546123550-551416184
3622334530-3628645995
1927820889-1967493838
3871603105-3889565720
529055056-557056663
2061323456-2061416792
614047849-615723475
1421830422-1438217488
893955655-899822408
2836598019-2847622397
3513797149-3566405119
2073594551-2086857816
3848735454-3851859716
2350779348-2362218008
1157368724-1159211721
1472023233-1491740523
409000134-412025522
973866742-991888713
1668403284-1669772137
499560567-510329898
267685403-276025076
1214847765-1215067953
2969721904-2972007967
585291343-591565800
1232818727-1248762127
2829953392-2835562942
3581151256-3592382743
3138701074-3144007132
1411308101-1412230389
2005544666-2044382522
3588499596-3590044644
409649298-412147889
2729008724-2746584170
2271068854-2273711594
3908832580-3914932215
335104351-395790944
1473266198-1475735364
91434044-136650095
2061500256-2061621366
3046851992-3046857394
1045645522-1053843281
3062437124-3066285848
2953128494-2956453639
2287457295-2292066307
670003013-672161332
999493075-1005063611
2468468433-2475614015
1784620864-1794208355
1840652757-1842609020
2736112937-2745142809
445972682-455985981
1400181442-1408982387
2727005736-2744339492
1372691009-1399083499
1258925192-1259447558
3572543625-3573210768
2855143621-2872648483
3524287180-3550477388
2401321114-2401936589
188464419-190820937
873632167-889945153
6333787-9214022
866108152-883525080
588215939-596870293
6123882-6333786
1945222555-1965326766
1450943271-1455273678
1071513900-1075274877
4066257746-4107013454
3743897533-3750360675
2210516312-2243489046
739672099-743664201
1190706188-1231785159
1541206073-1552994486
3512385624-3513610248
4004909328-4014105124
1552994488-1583336095
2691601784-2692559045
2959924467-2960061300
2065049768-2073594549
2928347959-2948232651
2737697310-2739140372
3440216783-3442065814
137081234-137703805
1455284245-1455810565
1261449358-1261530545
3839728048-3846372390
4054367050-4055961594
3439834313-3441586831
608984617-613222255
499254004-518922214
2175403815-2205135632
1454597594-1455393440
693379909-700041190
1736154207-1737853569
4010049861-4012151447
3836393111-3838773709
1506443565-1527056312
334384992-335104349
3432143787-3438801061
600863019-608705787
136650096-136849627
3836270310-3838516660
3746890560-3764006100
791648716-794185505
987754526-999694763
2099169385-2119583372
641698158-648180068
3460880474-3481616563
3813294403-3818142124
1317229673-1321947166
2017066792-2036619196
1169805608-1194307388
702695743-722588266
19217566-33973125
32718247-42062630
210053297-217544318
3911504558-3933321555
3975617006-3984996156
551283440-558238333
1127962140-1141935253
1136611230-1157368723
2379700479-2401127625
54260395-75973933
1952020827-1967209978
1264200368-1316734882
1397096904-1403128933
1258173114-1259068731
989260243-995310756
1799866888-1833669063
137517987-137808457
3730940245-3762938051
2963015846-2980970857
600863799-603995952
338151951-378904722
3027117516-3030869045
2785828139-2786645836
1079328174-1079992013
1053843283-1069416181
1060967066-1061236944
3487201659-3496293770
3347750745-3362523105
1338305534-1352171648
1438217489-1462489105
4197364536-4222741711
3189733030-3234111514
451903598-461106580
2097704515-2099471338
304243328-325969066
2086846158-2113069670
2545746395-2547066650
3895249038-3906283534
895659434-904873439
1856927180-1866112900
2775894269-2810724921
1324244959-1325601021
846667177-848199595
3505699661-3506197363
871734319-878294262
4258853578-4294967295
3880214909-3895480719
1986216334-1986348856
742290938-753736254
3234111516-3258189066
3383899774-3396452612
3501809450-3512385622
3378934393-3392160599
3079010157-3098817100
1803429736-1805049104
2166530895-2176167104
1317292508-1322866502
1832462772-1847638033
333679750-334384991
72032218-76605612
17348575-50105777
484459786-489813452
3046849434-3046856389
3467134484-3473562579
2803678490-2810293665
3794709054-3822236055
3186979605-3189733029
2695314106-2700550784
1699535593-1705619603
2237090616-2240620274
1448226508-1452768177
2397634923-2402113900
3900871909-3908832578
4277179118-4284467979
869824885-875039223
3193444038-3195088604
2098172269-2099552847
3166258970-3174350156
3713306332-3730940243
3790663633-3807120965
3193807148-3198905625
2686964362-2695658937
3046846149-3046946514
605656762-611150528
3489750890-3497886462
397630917-403990883
3074826378-3080783127
492235894-493663068
642025801-643219257
788627002-789236451
3084604998-3115741036
3371549848-3374946439
3874793389-3876408934
1139585817-1143207799
3174350157-3186979603
639635957-642849593
1597646197-1612855132
1382702163-1398831616
684158166-713176675
1894143091-1917115741
2089306322-2114752226
2578960283-2621599896
1532015022-1546127235
1324354899-1325917394
2416646543-2437368922
2269877523-2275201946
1992225975-2000270993
640306549-643270861
3044180773-3051507071
2775774779-2793333778
1691451382-1692811369
939103383-944332736
1888996559-1920171303
2268109491-2269877522
2215835480-2260579751
602969274-607505129
1604071710-1613863780
3050099422-3052240627
3628771809-3629905363
3875733031-3886920632
1079554232-1083825209
4121927827-4137657636
1185125973-1212455950
3691832998-3711433854
3128913327-3142493871
4136061085-4148481230
183514025-223274420
1692066643-1696528120
666994178-678090088
2754770797-2759197512
3628299759-3628932735
596038993-600863017
2166543044-2179778402
787127754-788139041
2552150503-2552363008
3258189067-3269060433
2282238677-2289889500
2833059982-2837278958
2887027445-2928347957
2012405876-2032624685
787098717-787195228
1468456416-1495861617
1677947927-1720886831
2345295255-2357276476
3982867112-3996989804
3952361166-3982867111
2822115640-2865481783
748108837-753342957
3838773710-3843041501
2129888578-2151896843
859599485-871063826
3258061263-3260134830
3333184176-3370719083
4252768739-4258730892
2621599897-2626383698
3691176288-3710040996
3294271054-3294614974
1297573835-1313952886
1689064095-1727538616
4111227623-4121927825
3377701672-3394223952
3457691408-3475080606
1439643724-1454465680
2050656519-2065049767
3915610103-3945886566
451360431-486638413
1979886573-1992225974
1081566438-1088850009
2656393854-2668773976
3294056463-3294326494
3242916477-3253418464
1341083507-1344391028
2110664130-2123875999
2049746107-2050500846
3841089640-3844211293
3837279464-3842572520
2865481784-2885687079
2271061510-2272621997
2269988720-2270241311
1202018544-1229602920
2712322516-2753492383
1257333433-1258706059
2653038423-2675082201
955515750-959548963
1285036550-1301703071
2769057410-2775774777
2428432105-2446718114
2446718116-2468468432
2344149965-2353553539
1427316534-1430111473
2205135633-2210516310
2753492385-2769057409
1886236958-1909206855
465545077-470595473
4270417833-4279802697
1516656167-1519514351
2810724922-2822115638
1992340399-2004656981
1109811498-1124752055
1390540334-1390759638
3377856394-3382045950
2366638179-2397634922
1118808079-1118848239
5926527-6123881
1671674170-1691100484
5819501-6106336
2490564635-2514000009
311106391-314727280
314059640-315255926
4010827162-4011730305
4010139590-4011598075
1803265906-1803834597
2497969870-2535505355
1671431570-1689108789
151189360-154214893 | null | https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/2016/day20/input.rkt | racket | #lang reader "lang.rkt"
420604416-480421096
172102328-195230700
613677102-639635955
1689844284-1724152701
3358865073-3365629764
1333423844-1344930397
2519115700-2535290065
698684483-723211151
979757052-1003200781
4165068842-4190472815
2020267004-2045214369
2979897715-3004836346
2110213890-2115506975
2970017340-2973461626
2236378365-2258142409
3423992974-3426380317
1462489107-1490036931
2189940955-2198476022
2417413696-2430182746
3624276792-3633790184
1005063612-1009015074
1061038892-1061410454
2276099915-2310172070
1202572862-1215598809
1783724555-1785267178
1262810964-1264200367
592924330-594021870
1981502514-2001291898
3639371125-3691832997
751455858-758389721
575870144-588215938
2707934395-2711294609
2271125072-2271532092
723211153-745881341
291750706-293834948
3846273818-3846421786
1798292566-1840652756
907920869-908496244
2979008391-2984333350
3120502195-3140695376
1316734884-1323407408
4013388816-4015102290
4211041074-4243535195
3264591092-3270165984
1356324132-1369836240
3500337320-3511856741
2675082203-2680516758
269092398-286582232
9214023-16864642
3496293771-3507984426
789173169-790658193
1589657426-1592447273
3018889533-3040428852
3190582871-3209497449
2582019510-2592221443
452701865-462658183
581072273-585497818
2885687081-2887027444
405199391-406037773
1926405498-1961345770
1591447330-1595803034
2075061753-2117082859
2738757089-2739984421
1758742902-1766649306
1598451138-1603784829
904873440-933144524
743128701-751089192
2946510215-2953128493
4258067806-4258357961
2162946809-2194271963
2502065462-2529412983
1794208357-1812728725
2399604728-2399751734
2675639614-2686964361
1243509131-1261449357
1334629713-1360716911
490307573-506198210
3865783894-3882438935
1355288427-1356825096
4080632471-4085694027
1069989320-1079328173
1261530547-1263095027
1864453415-1864536898
500660752-513276733
859810764-865812062
4054243009-4055337105
795048590-839560602
2708730392-2712322515
3642043390-3653718654
2350724230-2355301182
663974525-698684482
734062708-734919764
2004656983-2006812551
987361385-989501665
3621608802-3622545302
1133546243-1135802698
147516310-150573031
2271038167-2271338460
3912004191-3947848898
2301820906-2338108229
2361989797-2363651982
3867365-5819500
3702314080-3703559974
4134127328-4135370466
756306610-770493891
2079529322-2090642509
3981814383-3992802961
4031189022-4042698219
1560502437-1565573103
408025952-414757361
137808459-150920914
3393581407-3411447948
2151896844-2162946807
4201010521-4201471695
3713302577-3725874062
142387170-154849830
2166232094-2205567227
3291340751-3298984606
938375497-943547413
4055961596-4110367884
136677359-137609692
3037464396-3044180771
2691576247-2691980924
1009015076-1045645521
789113477-790592023
899519940-911794289
2137437783-2155776766
1399083500-1402900021
1469947218-1479256900
2944855925-2953686693
2910064491-2920533014
144173340-148094230
2360899146-2362380838
2013535209-2049558890
1109489564-1124585673
2756379565-2767828753
1060568096-1073644115
1691100485-1728041197
1592871439-1600233767
1516639981-1518466748
2098130915-2098541161
3704291842-3706581331
962586078-1003763244
527697837-533713889
1856931843-1873776214
2399693233-2399917980
2055406323-2063623078
240041628-275447727
1513843540-1521844727
1648487379-1649719916
2087056931-2102042862
3717079814-3719847466
1500211877-1510297315
407413483-415066321
3596458788-3618072868
218197655-228951780
643659026-656047997
1603704290-1614650204
2358880422-2366638177
3004836348-3015765511
3046845638-3046851095
3305333257-3307471995
2401731427-2405370552
4017360677-4027723482
557056664-575870142
609440078-615655979
1139493162-1151170381
428962141-483384245
2293357845-2334971307
3091700546-3119568633
1864347502-1864482912
1749751448-1750782554
420140812-420604414
1317387394-1324899402
3623998911-3629315327
4150451309-4152623876
434323808-454005042
1858560120-1864845209
2009686203-2018214121
605094405-611343970
4256094197-4258455116
1177692263-1227426205
4011096895-4014427778
39304785-47673299
498903368-524596608
605553131-610691072
3048424158-3066041482
153238649-154812518
1317950434-1324244958
3355309684-3360596455
2409598473-2428168849
2946469763-2949510201
543235050-544883779
1079837788-1081762723
3600722024-3622452566
4257178957-4258853576
1922845451-1979527610
1162924278-1217904821
1854156984-1867582222
2573163840-2578960281
1159211723-1163517189
1490036932-1500211875
482764386-488744315
235990048-265498430
1714315712-1724421861
958737616-962586076
790658195-851798647
2019736814-2021017547
2162802-8327007
787368380-789171975
3467221232-3469771790
3416813106-3439834312
906735025-908389759
64489226-70116603
1908532718-1922845449
1234754192-1245016567
3287320754-3296095689
3031537491-3039742613
3769892977-3785548652
1645238060-1655418015
612066331-620597775
2905104738-2920311121
2014785668-2022435799
3844301667-3844798343
2828382380-2863199622
2676931732-2682206642
171451625-218197654
2153052343-2156659109
610691073-636761246
2604642896-2615712599
1589965559-1603704289
2935029177-2942217574
186697135-187447861
1986224726-1986550701
770493893-789113476
3557491384-3562596711
2898302199-2920593201
934606912-955515749
1855368372-1872942514
2570443173-2571696675
186869593-188420012
1029668904-1048703657
3284676192-3295161434
3955266215-3977053319
2476141495-2479329360
4276025347-4283606977
534415917-569504381
2263536298-2268109489
1200129331-1210019228
3971350693-3990304290
489813454-495749644
1743364359-1768398619
3924729773-3931294732
105847925-111482255
794582284-818505469
1811415389-1838855885
1890243027-1898852651
1986067335-1986471617
104143552-106052965
772703103-776359533
3911720342-3933921905
395790945-398705617
2258142410-2267980008
613561861-616915116
3310135636-3330660281
2061419260-2061539636
2624281089-2626673183
1877477043-1884442706
2933979446-2949991401
543661669-563658372
197557686-226037744
613176712-618285697
4265278830-4278950571
3556799964-3560580457
1116126837-1122976017
1187703503-1205238834
983871724-1001238917
3887842382-3903790188
2641349279-2643172883
3583057749-3587680646
2601030398-2608486868
4157885743-4168988833
1162830362-1167726097
2514929623-2525222702
3291107480-3295972867
2151518630-2154613192
3046851552-3046878017
325969068-334085941
189084100-189886055
3650880042-3683085757
2453733029-2471942669
1662489961-1666626344
44287139-49449042
1400982930-1421830420
2546953607-2554587873
2639634659-2672001824
641036962-646629131
1236906461-1244507638
1331784152-1367083336
506198211-527697835
255997224-260755488
2588563930-2611385666
3599734818-3614926593
2285367719-2289556931
1088850011-1109811497
3586236383-3589929173
2399595142-2399763869
1385676603-1390665612
3513146704-3513797148
2738224131-2740166097
2869889938-2880215300
2005865698-2011251487
3046872422-3055338791
2940602932-2944294443
3711823219-3713306331
327670367-327738352
2793738-2841656
3807120966-3836270308
3711433856-3712911001
592896405-592954516
688452447-718340962
2063048458-2068052789
4162162406-4167839641
2049558892-2064994876
20968691-38549168
2497497428-2510517683
1583336096-1589657424
1143974607-1155771407
2381952303-2397368087
2009571163-2013286329
942853383-944865487
951722030-952400166
200197723-215328622
3106021045-3120502193
4140023055-4149617577
1668895062-1671431568
2626673185-2653038422
1841289175-1846422485
335754679-386244011
4062044458-4068497802
331356502-332799273
3307471997-3371549847
2018475560-2021933871
150920915-171451623
2194931559-2195514567
4089933248-4090707368
4157463945-4165762209
4100746531-4104107984
3411013858-3416813104
3374946441-3393581406
2552376718-2552429766
725947111-751643934
2473774976-2490564633
3566405121-3581497459
2683823262-2693090640
2734605142-2742827358
3441986164-3442398493
1524044927-1541206072
4254311927-4257287997
2411062371-2425081809
3666577856-3698298724
440803690-480698287
1614650206-1663590083
4257850447-4258201271
2637194180-2658593345
1269282838-1312761281
2522666665-2525818042
141503475-143914340
364934589-385277316
24026223-27879741
3557755338-3564098914
2943664323-2954588780
1571687539-1572996177
957113399-959367378
3585168986-3592657057
1356305980-1369637926
3630349604-3639371123
2570730499-2575580881
2459213065-2486172460
814620199-829988953
1983439516-1984861942
3800496806-3833569562
2841657-3867364
1706481656-1713944571
454683370-473903295
2697862561-2701781892
1451637419-1454646761
501104716-523461517
3304490686-3306418502
3846192081-3846304020
4191662000-4235899383
4096574372-4111227622
480421097-485653417
3762938052-3790582378
701786054-705861635
1214808315-1215006746
364434099-382831881
3713276399-3714579266
1336679025-1347883722
1979527611-1979886571
2090642510-2129888576
3624144511-3633098213
2097515227-2098217363
1851357581-1859249610
3021641379-3030459043
860720178-867061373
4053454232-4055923518
591971809-592927822
899570088-914232296
3171743426-3178833535
1767780850-1769461322
1648285748-1664437761
2756023351-2772357724
1841385621-1851357579
1764427585-1768013247
3968976986-3979761882
204898529-205069325
1192059065-1225447718
204967480-205140904
3191614963-3205521380
2687221525-2690406018
3713502419-3714707176
859460566-860824071
2761514667-2765543032
3357906031-3364349724
3275219921-3282195064
3391484605-3394594750
406732797-420140811
4273899514-4281205511
3083762422-3113295478
2193854781-2195333482
4203706684-4251257733
384194709-397192696
3591265505-3596458786
1102914397-1124045826
2310172071-2344149963
3066041483-3069828748
2635666365-2641585945
1060740916-1061127459
3774707512-3782147573
1743737707-1779166247
246638755-280110373
851798648-859460564
605075197-611133696
2293962494-2298136342
3460740393-3471166317
3280182044-3284676190
14791161-17348573
2691399120-2691637915
1728558700-1733098513
3461545676-3473725502
3751769544-3774673277
772066259-780246746
3356968359-3362991077
1605924820-1613022664
4015102292-4053454231
4206207007-4214797098
1335854520-1363709511
823795603-854558918
3290449369-3304490685
2540570240-2570730498
749722515-756306609
3442398495-3465001104
4229168442-4235745839
150802546-151838496
1380772851-1392292807
4190472817-4203706683
1466784263-1498319230
50105778-54260393
0-2793737
2956453641-2979008390
2552426525-2553141195
3069828750-3083762421
2800389226-2809306363
2275201948-2301909928
670647362-674039479
2639146472-2642836023
3846421788-3895249037
326561664-329333434
188182835-189612566
4253790781-4254533752
1804500603-1806558363
2405370554-2428432104
3608464545-3623946707
2353553540-2360491647
1325917396-1352060617
3577002908-3585168985
1864487525-1877898802
2535505356-2540570238
2012841949-2013535208
4122773972-4147066021
2221253241-2227916854
3996989806-4013388815
1118808237-1118876034
406730726-412027046
2830200680-2841462745
4009639150-4012108169
3387543681-3395550318
2412794571-2444576238
1022924735-1024398890
643270862-663974523
907974347-909753482
4148481231-4151899399
2061333796-2061422413
3844115908-3844704314
296503398-319176563
2743436711-2744991704
1024231444-1050533093
2976066221-2982350583
3913440938-3921340086
2546064716-2552639130
647510635-649788184
1861939256-1878905542
1119182827-1127962138
4176776277-4185432506
1728041199-1736154206
1905044208-1915920572
1860265438-1881626361
2934389290-2943526097
1068791968-1074539223
3124236778-3149982255
286582234-304243327
2100258789-2123748546
3432475911-3432766967
82082661-88073370
2327755908-2338617065
734803505-734970787
4225862764-4241303856
1352060618-1372691007
2552301217-2552408303
3873980245-3908789488
734733934-734933525
913241510-934606910
1746136669-1783130039
3478455269-3482503593
2300261034-2307782855
3248901770-3254155181
651662856-660523209
1118827933-1118873914
3495324533-3508390070
3614090639-3630342601
4152623878-4165068841
4251257735-4252768738
740064940-744628705
2663526-7317845
3173018368-3173033650
840243299-850630387
874982768-893955653
4195369814-4215042523
3712999015-3713605711
3167305950-3179505229
68345070-74894937
3467499056-3471357060
623795984-626879791
533357402-536413407
3551720149-3555281211
3933921906-3941710756
1732833292-1736931431
1172618521-1194746246
2011668991-2019214712
4173423213-4185833738
4129967821-4130008117
2025432624-2029847095
1663590084-1670239922
1677571493-1698026005
1167726098-1232818725
3785872097-3790663631
3140695377-3166258968
2971784945-2974988576
538998996-562454834
4225819511-4229474556
610567638-613651106
2462186480-2480650826
75973934-91434042
2688408664-2707934393
228951782-267685402
1783130040-1784614561
1872942515-1880846327
1262147457-1263932136
4024512115-4053495116
579938959-585172735
602874206-610295015
403990885-414323983
1730191207-1736990500
3623946708-3627097897
1350246834-1362835856
232836175-284581763
1569378906-1570007725
3026358814-3033526682
1636906011-1655244443
1346904336-1351608843
363534678-372420875
3465001105-3471897467
3934746154-3952361164
7208229-13983082
3469317144-3474090343
4280938719-4290730270
2020957337-2022484776
1692136283-1719643620
4032740692-4053771021
2972345930-2975812534
140067848-159037627
3630086418-3634626029
3252572678-3274451634
77141551-85341019
692066237-700847528
3552713357-3558885449
3075915215-3085817045
4162664504-4169419288
124626946-135046727
1884442708-1905044207
3703243550-3704832207
2220909545-2224015721
2692074751-2692885915
1069864185-1073578735
2691786564-2692864691
1737853571-1745347739
95461456-115187423
143224398-144838969
2138286928-2151694571
867061374-882471488
983262449-1001173152
4129969371-4130354697
3470641201-3487201657
2051110734-2064915382
747750272-758258548
3333190532-3365085965
3015765512-3029456808
3265304770-3277560812
546123550-551416184
3622334530-3628645995
1927820889-1967493838
3871603105-3889565720
529055056-557056663
2061323456-2061416792
614047849-615723475
1421830422-1438217488
893955655-899822408
2836598019-2847622397
3513797149-3566405119
2073594551-2086857816
3848735454-3851859716
2350779348-2362218008
1157368724-1159211721
1472023233-1491740523
409000134-412025522
973866742-991888713
1668403284-1669772137
499560567-510329898
267685403-276025076
1214847765-1215067953
2969721904-2972007967
585291343-591565800
1232818727-1248762127
2829953392-2835562942
3581151256-3592382743
3138701074-3144007132
1411308101-1412230389
2005544666-2044382522
3588499596-3590044644
409649298-412147889
2729008724-2746584170
2271068854-2273711594
3908832580-3914932215
335104351-395790944
1473266198-1475735364
91434044-136650095
2061500256-2061621366
3046851992-3046857394
1045645522-1053843281
3062437124-3066285848
2953128494-2956453639
2287457295-2292066307
670003013-672161332
999493075-1005063611
2468468433-2475614015
1784620864-1794208355
1840652757-1842609020
2736112937-2745142809
445972682-455985981
1400181442-1408982387
2727005736-2744339492
1372691009-1399083499
1258925192-1259447558
3572543625-3573210768
2855143621-2872648483
3524287180-3550477388
2401321114-2401936589
188464419-190820937
873632167-889945153
6333787-9214022
866108152-883525080
588215939-596870293
6123882-6333786
1945222555-1965326766
1450943271-1455273678
1071513900-1075274877
4066257746-4107013454
3743897533-3750360675
2210516312-2243489046
739672099-743664201
1190706188-1231785159
1541206073-1552994486
3512385624-3513610248
4004909328-4014105124
1552994488-1583336095
2691601784-2692559045
2959924467-2960061300
2065049768-2073594549
2928347959-2948232651
2737697310-2739140372
3440216783-3442065814
137081234-137703805
1455284245-1455810565
1261449358-1261530545
3839728048-3846372390
4054367050-4055961594
3439834313-3441586831
608984617-613222255
499254004-518922214
2175403815-2205135632
1454597594-1455393440
693379909-700041190
1736154207-1737853569
4010049861-4012151447
3836393111-3838773709
1506443565-1527056312
334384992-335104349
3432143787-3438801061
600863019-608705787
136650096-136849627
3836270310-3838516660
3746890560-3764006100
791648716-794185505
987754526-999694763
2099169385-2119583372
641698158-648180068
3460880474-3481616563
3813294403-3818142124
1317229673-1321947166
2017066792-2036619196
1169805608-1194307388
702695743-722588266
19217566-33973125
32718247-42062630
210053297-217544318
3911504558-3933321555
3975617006-3984996156
551283440-558238333
1127962140-1141935253
1136611230-1157368723
2379700479-2401127625
54260395-75973933
1952020827-1967209978
1264200368-1316734882
1397096904-1403128933
1258173114-1259068731
989260243-995310756
1799866888-1833669063
137517987-137808457
3730940245-3762938051
2963015846-2980970857
600863799-603995952
338151951-378904722
3027117516-3030869045
2785828139-2786645836
1079328174-1079992013
1053843283-1069416181
1060967066-1061236944
3487201659-3496293770
3347750745-3362523105
1338305534-1352171648
1438217489-1462489105
4197364536-4222741711
3189733030-3234111514
451903598-461106580
2097704515-2099471338
304243328-325969066
2086846158-2113069670
2545746395-2547066650
3895249038-3906283534
895659434-904873439
1856927180-1866112900
2775894269-2810724921
1324244959-1325601021
846667177-848199595
3505699661-3506197363
871734319-878294262
4258853578-4294967295
3880214909-3895480719
1986216334-1986348856
742290938-753736254
3234111516-3258189066
3383899774-3396452612
3501809450-3512385622
3378934393-3392160599
3079010157-3098817100
1803429736-1805049104
2166530895-2176167104
1317292508-1322866502
1832462772-1847638033
333679750-334384991
72032218-76605612
17348575-50105777
484459786-489813452
3046849434-3046856389
3467134484-3473562579
2803678490-2810293665
3794709054-3822236055
3186979605-3189733029
2695314106-2700550784
1699535593-1705619603
2237090616-2240620274
1448226508-1452768177
2397634923-2402113900
3900871909-3908832578
4277179118-4284467979
869824885-875039223
3193444038-3195088604
2098172269-2099552847
3166258970-3174350156
3713306332-3730940243
3790663633-3807120965
3193807148-3198905625
2686964362-2695658937
3046846149-3046946514
605656762-611150528
3489750890-3497886462
397630917-403990883
3074826378-3080783127
492235894-493663068
642025801-643219257
788627002-789236451
3084604998-3115741036
3371549848-3374946439
3874793389-3876408934
1139585817-1143207799
3174350157-3186979603
639635957-642849593
1597646197-1612855132
1382702163-1398831616
684158166-713176675
1894143091-1917115741
2089306322-2114752226
2578960283-2621599896
1532015022-1546127235
1324354899-1325917394
2416646543-2437368922
2269877523-2275201946
1992225975-2000270993
640306549-643270861
3044180773-3051507071
2775774779-2793333778
1691451382-1692811369
939103383-944332736
1888996559-1920171303
2268109491-2269877522
2215835480-2260579751
602969274-607505129
1604071710-1613863780
3050099422-3052240627
3628771809-3629905363
3875733031-3886920632
1079554232-1083825209
4121927827-4137657636
1185125973-1212455950
3691832998-3711433854
3128913327-3142493871
4136061085-4148481230
183514025-223274420
1692066643-1696528120
666994178-678090088
2754770797-2759197512
3628299759-3628932735
596038993-600863017
2166543044-2179778402
787127754-788139041
2552150503-2552363008
3258189067-3269060433
2282238677-2289889500
2833059982-2837278958
2887027445-2928347957
2012405876-2032624685
787098717-787195228
1468456416-1495861617
1677947927-1720886831
2345295255-2357276476
3982867112-3996989804
3952361166-3982867111
2822115640-2865481783
748108837-753342957
3838773710-3843041501
2129888578-2151896843
859599485-871063826
3258061263-3260134830
3333184176-3370719083
4252768739-4258730892
2621599897-2626383698
3691176288-3710040996
3294271054-3294614974
1297573835-1313952886
1689064095-1727538616
4111227623-4121927825
3377701672-3394223952
3457691408-3475080606
1439643724-1454465680
2050656519-2065049767
3915610103-3945886566
451360431-486638413
1979886573-1992225974
1081566438-1088850009
2656393854-2668773976
3294056463-3294326494
3242916477-3253418464
1341083507-1344391028
2110664130-2123875999
2049746107-2050500846
3841089640-3844211293
3837279464-3842572520
2865481784-2885687079
2271061510-2272621997
2269988720-2270241311
1202018544-1229602920
2712322516-2753492383
1257333433-1258706059
2653038423-2675082201
955515750-959548963
1285036550-1301703071
2769057410-2775774777
2428432105-2446718114
2446718116-2468468432
2344149965-2353553539
1427316534-1430111473
2205135633-2210516310
2753492385-2769057409
1886236958-1909206855
465545077-470595473
4270417833-4279802697
1516656167-1519514351
2810724922-2822115638
1992340399-2004656981
1109811498-1124752055
1390540334-1390759638
3377856394-3382045950
2366638179-2397634922
1118808079-1118848239
5926527-6123881
1671674170-1691100484
5819501-6106336
2490564635-2514000009
311106391-314727280
314059640-315255926
4010827162-4011730305
4010139590-4011598075
1803265906-1803834597
2497969870-2535505355
1671431570-1689108789
151189360-154214893 | |
f2411703d1313a58564e5837e2661b1548ea37cae7d36c97993f87a2a9abc202 | bufferswap/ViralityEngine | closure.lisp | (in-package #:vutils)
The following is an implementation of " Pandoric Macros " , documented by
in " Let Over Lambda " . Some minor improvements and style changes are
;;; applied to the reference version.
(defun plet/get (args)
`(case symbol
,@(mapcar
(lambda (x)
`(,(car x) ,(car x)))
args)
(t (error "Unknown pandoric getter: ~a." symbol))))
(defun plet/set (args)
`(case symbol
,@(mapcar
(lambda (x)
`(,(car x) (setf ,(car x) value)))
args)
(t (error "Unknown pandoric setter: ~a." symbol))))
(defun pget (box symbol)
(funcall box :getter symbol))
(defsetf pget (box symbol) (value)
`(progn
(funcall ,box :setter ,symbol ,value)
,value))
(defmacro dlambda (&body ds)
(alexandria:with-gensyms (args)
`(lambda (&rest ,args)
(case (car ,args)
,@(mapcar
(lambda (x)
(destructuring-bind (name . rest) x
`(,name
(apply
(lambda ,@rest)
,(if (eq name t)
args
`(cdr ,args))))))
ds)))))
(defmacro with-pvars (symbols box &body body)
(alexandria:once-only (box)
`(symbol-macrolet (,@(mapcar
(lambda (x)
`(,x (pget ,box ',x)))
symbols))
,@body)))
(defmacro plambda (args exports &body body)
(let ((exports (mapcar #'list exports)))
`(let (this self)
(setf this (lambda ,args ,@body)
self (dlambda
(:getter (symbol) ,(plet/get exports))
(:setter (symbol value) ,(plet/set exports))
(t (&rest args) (apply this args)))))))
(defmacro define-pfun (name args &body body)
(multiple-value-bind (body decls doc)
(alexandria:parse-body body :documentation t)
`(defun ,name (self)
,@(when doc `(,doc))
,@decls
,(if args
`(with-pvars ,args self ,@body)
`(progn ,@body)))))
| null | https://raw.githubusercontent.com/bufferswap/ViralityEngine/df7bb4dffaecdcb6fdcbfa618031a5e1f85f4002/support/vutils/src/closure.lisp | lisp | applied to the reference version. | (in-package #:vutils)
The following is an implementation of " Pandoric Macros " , documented by
in " Let Over Lambda " . Some minor improvements and style changes are
(defun plet/get (args)
`(case symbol
,@(mapcar
(lambda (x)
`(,(car x) ,(car x)))
args)
(t (error "Unknown pandoric getter: ~a." symbol))))
(defun plet/set (args)
`(case symbol
,@(mapcar
(lambda (x)
`(,(car x) (setf ,(car x) value)))
args)
(t (error "Unknown pandoric setter: ~a." symbol))))
(defun pget (box symbol)
(funcall box :getter symbol))
(defsetf pget (box symbol) (value)
`(progn
(funcall ,box :setter ,symbol ,value)
,value))
(defmacro dlambda (&body ds)
(alexandria:with-gensyms (args)
`(lambda (&rest ,args)
(case (car ,args)
,@(mapcar
(lambda (x)
(destructuring-bind (name . rest) x
`(,name
(apply
(lambda ,@rest)
,(if (eq name t)
args
`(cdr ,args))))))
ds)))))
(defmacro with-pvars (symbols box &body body)
(alexandria:once-only (box)
`(symbol-macrolet (,@(mapcar
(lambda (x)
`(,x (pget ,box ',x)))
symbols))
,@body)))
(defmacro plambda (args exports &body body)
(let ((exports (mapcar #'list exports)))
`(let (this self)
(setf this (lambda ,args ,@body)
self (dlambda
(:getter (symbol) ,(plet/get exports))
(:setter (symbol value) ,(plet/set exports))
(t (&rest args) (apply this args)))))))
(defmacro define-pfun (name args &body body)
(multiple-value-bind (body decls doc)
(alexandria:parse-body body :documentation t)
`(defun ,name (self)
,@(when doc `(,doc))
,@decls
,(if args
`(with-pvars ,args self ,@body)
`(progn ,@body)))))
|
f96d4c2b42fe4f1937e1d065c2e3194fecc3c434d0907e9b8458b07bf26ebb72 | lilactown/react-repl | project.clj | (defproject town.lilac/react-repl "0.0.1"
:description "Tools for interacting with a React app from a ClojureScript REPL"
:url "-repl"
:license {:name "Apache2 License"
:url "-2.0"}
:source-paths ["src"]
:dependencies [[cljs-bean "1.5.0"]]
:deploy-repositories [["snapshots" {:sign-releases false :url ""}]])
| null | https://raw.githubusercontent.com/lilactown/react-repl/30425f2a5d1dd3f6a8d91231e4875c6e75c0b761/project.clj | clojure | (defproject town.lilac/react-repl "0.0.1"
:description "Tools for interacting with a React app from a ClojureScript REPL"
:url "-repl"
:license {:name "Apache2 License"
:url "-2.0"}
:source-paths ["src"]
:dependencies [[cljs-bean "1.5.0"]]
:deploy-repositories [["snapshots" {:sign-releases false :url ""}]])
| |
d0db13d0d91052c73dba3111fad89eb04393181e13b967a61abd2bb2e6b35890 | pingles/bandit | bayes_test.clj | (ns bandit.algo.bayes-test
(:use [expectations]
[bandit.algo.bayes])
(:require [bandit.arms :as arms]))
(let [a (arms/arm :arm1)]
(given a
(expect :pulls 0
:value 0))
(given (estimate-value (arms/pulled a))
(expect :pulls 1
:value 0
:alpha 1.0
:beta 2.0))
(given (estimate-value (-> a (arms/pulled) (reward 1)))
(expect :pulls 1
:value 1
:alpha 2.0
:beta 1.0)))
| null | https://raw.githubusercontent.com/pingles/bandit/795666f3938e28f389691094bb1e07e4202290f6/bandit-core/test/bandit/algo/bayes_test.clj | clojure | (ns bandit.algo.bayes-test
(:use [expectations]
[bandit.algo.bayes])
(:require [bandit.arms :as arms]))
(let [a (arms/arm :arm1)]
(given a
(expect :pulls 0
:value 0))
(given (estimate-value (arms/pulled a))
(expect :pulls 1
:value 0
:alpha 1.0
:beta 2.0))
(given (estimate-value (-> a (arms/pulled) (reward 1)))
(expect :pulls 1
:value 1
:alpha 2.0
:beta 1.0)))
| |
0cc8330d1c2c93dfc3f686dcc246a6296e6391128ed7b5586de2bc65eda3e6b3 | returntocorp/semgrep | Conf.mli | (*
Runtime configuration options defining a regexp dialect.
*)
type t = {
Match all characters with ' . ' , including LF which otherwise is
excluded . Same as PCRE_DOTALL .
excluded. Same as PCRE_DOTALL. *)
pcre_dotall : bool;
(* If enabled, '^' and '$' will match only that the beginning and at the
end of the input, respectively. Same as PCRE_MULTILINE. *)
pcre_multiline : bool;
If enabled , some sets of characters like ' \w ' or ' [: alnum :] ' are extended
with non - ascii unicode characters . Same as PCRE_UCP .
with non-ascii unicode characters. Same as PCRE_UCP. *)
pcre_ucp : bool;
Tweaks for JavaScript compatibility . Same as PCRE_JAVASCRIPT_COMPAT .
pcre_javascript_compat : bool;
(* Support comments in the form of '(?# ... )' *)
with_comment_groups : bool;
Ignore whitespace outside of character classes .
Must use ' \s ' to match a space character etc .
This corresponds to ' /x ' in perl and PCRE_EXTENDED in PCRE .
Must use '\s' to match a space character etc.
This corresponds to '/x' in perl and PCRE_EXTENDED in PCRE. *)
ignore_whitespace : bool;
(* Ignore whitespace in character classes. *)
ignore_whitespace_in_char_classes : bool;
(* Ignore any '#' character and what follows until the end of the line. *)
ignore_hash_comments : bool;
}
| null | https://raw.githubusercontent.com/returntocorp/semgrep/00f1e67bbb80f00e29db3381288fc00398b6868a/languages/regexp/Conf.mli | ocaml |
Runtime configuration options defining a regexp dialect.
If enabled, '^' and '$' will match only that the beginning and at the
end of the input, respectively. Same as PCRE_MULTILINE.
Support comments in the form of '(?# ... )'
Ignore whitespace in character classes.
Ignore any '#' character and what follows until the end of the line. |
type t = {
Match all characters with ' . ' , including LF which otherwise is
excluded . Same as PCRE_DOTALL .
excluded. Same as PCRE_DOTALL. *)
pcre_dotall : bool;
pcre_multiline : bool;
If enabled , some sets of characters like ' \w ' or ' [: alnum :] ' are extended
with non - ascii unicode characters . Same as PCRE_UCP .
with non-ascii unicode characters. Same as PCRE_UCP. *)
pcre_ucp : bool;
Tweaks for JavaScript compatibility . Same as PCRE_JAVASCRIPT_COMPAT .
pcre_javascript_compat : bool;
with_comment_groups : bool;
Ignore whitespace outside of character classes .
Must use ' \s ' to match a space character etc .
This corresponds to ' /x ' in perl and PCRE_EXTENDED in PCRE .
Must use '\s' to match a space character etc.
This corresponds to '/x' in perl and PCRE_EXTENDED in PCRE. *)
ignore_whitespace : bool;
ignore_whitespace_in_char_classes : bool;
ignore_hash_comments : bool;
}
|
6ad177580e3d4c274491558264643a998159655568b9f7c29ab0201f1f0e0760 | digikar99/numericals | internals.lisp | (in-package :sbcl-numericals.internals)
;;; See
;;; for a tutorial on what this macro is up to.
;;; We want to abstract just "the right amount" - we don't want to
;;; abstract too much to introduce layers and layers of complexity;
;;; but enough to avert code repetition.
(defmacro define-binary-vectorized-op (name base-op element-type mode
(dest &rest args)
&body assembly-instructions)
(with-gensyms (vop-name
loop-var
loop-final-var)
(destructuring-bind (register-type
simd-pack-type
vop-arg-type
vop-wrapper-name
array-type
loop-step-size
vector-accessor)
(eswitch ((list element-type mode) :test 'equalp)
('(:double :avx2) (list 'sb-vm::double-avx2-reg
'(simd-pack-256 double-float)
'sb-vm::simd-pack-256-double
(intern (concatenate 'string "D4"
(symbol-name base-op))
:sbcl-numericals.internals)
'(simple-array double-float)
4
'd4-ref))
('(:single :avx2) (list 'sb-vm::single-avx2-reg
'(simd-pack-256 single-float)
'sb-vm::simd-pack-256-single
(intern (concatenate 'string "S8"
(symbol-name base-op))
:sbcl-numericals.internals)
'(simple-array single-float)
8
's8-ref))
('(:double :sse) (list 'sb-vm::double-sse-reg
'(simd-pack double-float)
'sb-vm::simd-pack-double
(intern (concatenate 'string "D2"
(symbol-name base-op))
:sbcl-numericals.internals)
'(simple-array double-float)
2
'd2-ref))
('(:single :sse) (list 'sb-vm::single-sse-reg
'(simd-pack single-float)
'sb-vm::simd-pack-single
(intern (concatenate 'string "S4"
(symbol-name base-op))
:sbcl-numericals.internals)
'(simple-array single-float)
4
's4-ref)))
`(progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(defknown (,vop-name)
,(make-list (length args)
:initial-element simd-pack-type)
,simd-pack-type
(movable flushable always-translatable)
:overwrite-fndb-silently t)
(define-vop (,vop-name)
(:translate ,vop-name)
(:policy :fast-safe)
(:args ,@(loop for arg-name in args
collect `(,arg-name :scs (,register-type))))
(:arg-types ,@(make-list (length args)
:initial-element vop-arg-type))
(:results (,dest :scs (,register-type)))
(:result-types ,vop-arg-type)
(:generator 1 ;; what should be the cost?
,@assembly-instructions)))
(declaim (inline ,vop-wrapper-name))
(defun ,vop-wrapper-name ,args
(declare (optimize (speed 3)))
(,vop-name ,@args))
(defun ,name (,@args
,dest)
(declare (optimize (speed 3))
(type ,array-type ,@args ,dest))
(if (not (and ,@(loop for arg in args
collect `(equalp (array-dimensions ,dest)
(array-dimensions ,arg)))))
(error "Arrays cannot have different dimensions!"))
(let ((,dest (array-storage-vector ,dest))
,@(loop for arg in args
collect `(,arg (array-storage-vector ,arg))))
(loop for ,loop-var fixnum
below (- (length ,dest) ,loop-step-size)
by ,loop-step-size
do (setf (,vector-accessor ,dest ,loop-var)
(,vop-wrapper-name ,@(loop for arg in args
collect `(,vector-accessor ,arg ,loop-var))))
finally
(loop for ,loop-final-var from ,loop-var below (length ,dest)
do (setf (aref ,dest ,loop-final-var)
(,base-op ,@(loop for arg in args
collect `(aref ,arg ,loop-final-var)))))))
,dest)))))
| null | https://raw.githubusercontent.com/digikar99/numericals/4f82b74e32b054f65110ee62ba080603c92ac103/sbcl-numericals/src/internals.lisp | lisp | See
for a tutorial on what this macro is up to.
We want to abstract just "the right amount" - we don't want to
abstract too much to introduce layers and layers of complexity;
but enough to avert code repetition.
what should be the cost? | (in-package :sbcl-numericals.internals)
(defmacro define-binary-vectorized-op (name base-op element-type mode
(dest &rest args)
&body assembly-instructions)
(with-gensyms (vop-name
loop-var
loop-final-var)
(destructuring-bind (register-type
simd-pack-type
vop-arg-type
vop-wrapper-name
array-type
loop-step-size
vector-accessor)
(eswitch ((list element-type mode) :test 'equalp)
('(:double :avx2) (list 'sb-vm::double-avx2-reg
'(simd-pack-256 double-float)
'sb-vm::simd-pack-256-double
(intern (concatenate 'string "D4"
(symbol-name base-op))
:sbcl-numericals.internals)
'(simple-array double-float)
4
'd4-ref))
('(:single :avx2) (list 'sb-vm::single-avx2-reg
'(simd-pack-256 single-float)
'sb-vm::simd-pack-256-single
(intern (concatenate 'string "S8"
(symbol-name base-op))
:sbcl-numericals.internals)
'(simple-array single-float)
8
's8-ref))
('(:double :sse) (list 'sb-vm::double-sse-reg
'(simd-pack double-float)
'sb-vm::simd-pack-double
(intern (concatenate 'string "D2"
(symbol-name base-op))
:sbcl-numericals.internals)
'(simple-array double-float)
2
'd2-ref))
('(:single :sse) (list 'sb-vm::single-sse-reg
'(simd-pack single-float)
'sb-vm::simd-pack-single
(intern (concatenate 'string "S4"
(symbol-name base-op))
:sbcl-numericals.internals)
'(simple-array single-float)
4
's4-ref)))
`(progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(defknown (,vop-name)
,(make-list (length args)
:initial-element simd-pack-type)
,simd-pack-type
(movable flushable always-translatable)
:overwrite-fndb-silently t)
(define-vop (,vop-name)
(:translate ,vop-name)
(:policy :fast-safe)
(:args ,@(loop for arg-name in args
collect `(,arg-name :scs (,register-type))))
(:arg-types ,@(make-list (length args)
:initial-element vop-arg-type))
(:results (,dest :scs (,register-type)))
(:result-types ,vop-arg-type)
,@assembly-instructions)))
(declaim (inline ,vop-wrapper-name))
(defun ,vop-wrapper-name ,args
(declare (optimize (speed 3)))
(,vop-name ,@args))
(defun ,name (,@args
,dest)
(declare (optimize (speed 3))
(type ,array-type ,@args ,dest))
(if (not (and ,@(loop for arg in args
collect `(equalp (array-dimensions ,dest)
(array-dimensions ,arg)))))
(error "Arrays cannot have different dimensions!"))
(let ((,dest (array-storage-vector ,dest))
,@(loop for arg in args
collect `(,arg (array-storage-vector ,arg))))
(loop for ,loop-var fixnum
below (- (length ,dest) ,loop-step-size)
by ,loop-step-size
do (setf (,vector-accessor ,dest ,loop-var)
(,vop-wrapper-name ,@(loop for arg in args
collect `(,vector-accessor ,arg ,loop-var))))
finally
(loop for ,loop-final-var from ,loop-var below (length ,dest)
do (setf (aref ,dest ,loop-final-var)
(,base-op ,@(loop for arg in args
collect `(aref ,arg ,loop-final-var)))))))
,dest)))))
|
a19d53c113f99f3fe8bf101b4b6abb8463e641b1fbc34e02caf663bdea5d6634 | rabbitmq/rabbitmq-federation | rabbit_federation_app.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_federation_app).
-behaviour(application).
-export([start/2, stop/1]).
Dummy supervisor - see comment at
-library-applications-without-processes-td2094473.html
%% All of our actual server processes are supervised by
%% rabbit_federation_sup, which is started by a rabbit_boot_step
%% (since it needs to start up before queue / exchange recovery, so it
%% can't be part of our application).
%%
%% However, we still need an application behaviour since we need to
know when our application has started since then the Erlang client
%% will have started and we can therefore start our links going. Since
%% the application behaviour needs a tree of processes to supervise,
%% this is it...
-behaviour(supervisor).
-export([init/1]).
start(_Type, _StartArgs) ->
rabbit_federation_exchange_link:go(),
rabbit_federation_queue_link:go(),
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
stop(_State) ->
ok.
%%----------------------------------------------------------------------------
init([]) -> {ok, {{one_for_one, 3, 10}, []}}.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-federation/960b8214487ae2495cd39afbbd3a2c4d9ea37985/src/rabbit_federation_app.erl | erlang |
All of our actual server processes are supervised by
rabbit_federation_sup, which is started by a rabbit_boot_step
(since it needs to start up before queue / exchange recovery, so it
can't be part of our application).
However, we still need an application behaviour since we need to
will have started and we can therefore start our links going. Since
the application behaviour needs a tree of processes to supervise,
this is it...
---------------------------------------------------------------------------- | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_federation_app).
-behaviour(application).
-export([start/2, stop/1]).
Dummy supervisor - see comment at
-library-applications-without-processes-td2094473.html
know when our application has started since then the Erlang client
-behaviour(supervisor).
-export([init/1]).
start(_Type, _StartArgs) ->
rabbit_federation_exchange_link:go(),
rabbit_federation_queue_link:go(),
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
stop(_State) ->
ok.
init([]) -> {ok, {{one_for_one, 3, 10}, []}}.
|
89f579d33e239dedb916ab55b95c73f408fbcda0213b2e552cc3d6a947410d78 | htm-community/clortex | viz_test.clj | (ns clortex.viz-test
(:use midje.sweet)
(:require [quil.core :as q]
[clortex.viz.core :as v]))
(q/defsketch example
:title "Clortex Vizualisation"
:setup v/setup
:draw v/draw
:size [1600 800]
:key-typed v/key-press)
| null | https://raw.githubusercontent.com/htm-community/clortex/69003a352140510f47c6b8e18ad6a98a7b5a3bba/test/clortex/viz_test.clj | clojure | (ns clortex.viz-test
(:use midje.sweet)
(:require [quil.core :as q]
[clortex.viz.core :as v]))
(q/defsketch example
:title "Clortex Vizualisation"
:setup v/setup
:draw v/draw
:size [1600 800]
:key-typed v/key-press)
| |
c9bd8577c24999e73bad555b051e5f555263ceae43a8b01997d84322358b42c2 | 8c6794b6/guile-tjit | x-mazefun.scm | Mazefun from racket benchmark .
(define iota
(lambda (n)
(iota-iter n '())))
(define iota-iter
(lambda (n lst)
(if (= n 0)
lst
(iota-iter (- n 1) (cons n lst)))))
(define foldr
(lambda (f base lst)
(define foldr-aux
(lambda (lst)
(if (null? lst)
base
(f (car lst) (foldr-aux (cdr lst))))))
(foldr-aux lst)))
(define foldl
(lambda (f base lst)
(define foldl-aux
(lambda (base lst)
(if (null? lst)
base
(foldl-aux (f base (car lst)) (cdr lst)))))
(foldl-aux base lst)))
(define for
(lambda (lo hi f)
(define for-aux
(lambda (lo)
(if (< lo hi)
(cons (f lo) (for-aux (+ lo 1)))
'())))
(for-aux lo)))
(define concat
(lambda (lists)
(foldr append '() lists)))
(define list-read
(lambda (lst i)
(if (= i 0)
(car lst)
(list-read (cdr lst) (- i 1)))))
(define list-write
(lambda (lst i val)
(if (= i 0)
(cons val (cdr lst))
(cons (car lst) (list-write (cdr lst) (- i 1) val)))))
(define list-remove-pos
(lambda (lst i)
(if (= i 0)
(cdr lst)
(cons (car lst) (list-remove-pos (cdr lst) (- i 1))))))
(define duplicates?
(lambda (lst)
(if (null? lst)
#f
(or (member (car lst) (cdr lst))
(duplicates? (cdr lst))))))
; Manipulation de matrices.
(define make-matrix
(lambda (n m init)
(for 0 n (lambda (i) (for 0 m (lambda (j) (init i j)))))))
(define matrix-read
(lambda (mat i j)
(list-read (list-read mat i) j)))
(define matrix-write
(lambda (mat i j val)
(list-write mat i (list-write (list-read mat i) j val))))
(define matrix-size
(lambda (mat)
(cons (length mat) (length (car mat)))))
(define matrix-map
(lambda (f mat)
(map (lambda (lst) (map f lst)) mat)))
(define initial-random 0)
(define next-random
(lambda (current-random)
(remainder (+ (* current-random 3581) 12751) 131072)))
(define shuffle
(lambda (lst)
(shuffle-aux lst initial-random)))
(define shuffle-aux
(lambda (lst current-random)
(if (null? lst)
'()
(let ((new-random (next-random current-random)))
(let ((i (modulo new-random (length lst))))
(cons (list-read lst i)
(shuffle-aux (list-remove-pos lst i)
new-random)))))))
(define make-maze
(lambda (n m) ; n and m must be odd
(if (not (and (odd? n) (odd? m)))
'error
(let ((cave
(make-matrix n m (lambda (i j)
(if (and (even? i) (even? j))
(cons i j)
#f))))
(possible-holes
(concat
(for 0 n (lambda (i)
(concat
(for 0 m (lambda (j)
(if (equal? (even? i) (even? j))
'()
(list (cons i j)))))))))))
(cave-to-maze (pierce-randomly (shuffle possible-holes) cave))))))
(define cave-to-maze
(lambda (cave)
(matrix-map (lambda (x) (if x '_ '*)) cave)))
(define pierce
(lambda (pos cave)
(let ((i (car pos)) (j (cdr pos)))
(matrix-write cave i j pos))))
(define pierce-randomly
(lambda (possible-holes cave)
(if (null? possible-holes)
cave
(let ((hole (car possible-holes)))
(pierce-randomly (cdr possible-holes)
(try-to-pierce hole cave))))))
(define try-to-pierce
(lambda (pos cave)
(let ((i (car pos)) (j (cdr pos)))
(let ((ncs (neighboring-cavities pos cave)))
(if (duplicates?
(map (lambda (nc) (matrix-read cave (car nc) (cdr nc))) ncs))
cave
(pierce pos
(foldl (lambda (c nc) (change-cavity c nc pos))
cave
ncs)))))))
(define change-cavity
(lambda (cave pos new-cavity-id)
(let ((i (car pos)) (j (cdr pos)))
(change-cavity-aux cave pos new-cavity-id (matrix-read cave i j)))))
(define change-cavity-aux
(lambda (cave pos new-cavity-id old-cavity-id)
(let ((i (car pos)) (j (cdr pos)))
(let ((cavity-id (matrix-read cave i j)))
(if (equal? cavity-id old-cavity-id)
(foldl (lambda (c nc)
(change-cavity-aux c nc new-cavity-id old-cavity-id))
(matrix-write cave i j new-cavity-id)
(neighboring-cavities pos cave))
cave)))))
(define neighboring-cavities
(lambda (pos cave)
(let ((size (matrix-size cave)))
(let ((n (car size)) (m (cdr size)))
(let ((i (car pos)) (j (cdr pos)))
(append (if (and (> i 0) (matrix-read cave (- i 1) j))
(list (cons (- i 1) j))
'())
(if (and (< i (- n 1)) (matrix-read cave (+ i 1) j))
(list (cons (+ i 1) j))
'())
(if (and (> j 0) (matrix-read cave i (- j 1)))
(list (cons i (- j 1)))
'())
(if (and (< j (- m 1)) (matrix-read cave i (+ j 1)))
(list (cons i (+ j 1)))
'())))))))
(define (run-loop k)
(let loop ((n 60) (v 0))
(if (zero? n)
v
(loop (- n 1) (make-maze 15 k)))))
(run-loop 15)
| null | https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/test-suite/tjit/x-mazefun.scm | scheme | Manipulation de matrices.
n and m must be odd | Mazefun from racket benchmark .
(define iota
(lambda (n)
(iota-iter n '())))
(define iota-iter
(lambda (n lst)
(if (= n 0)
lst
(iota-iter (- n 1) (cons n lst)))))
(define foldr
(lambda (f base lst)
(define foldr-aux
(lambda (lst)
(if (null? lst)
base
(f (car lst) (foldr-aux (cdr lst))))))
(foldr-aux lst)))
(define foldl
(lambda (f base lst)
(define foldl-aux
(lambda (base lst)
(if (null? lst)
base
(foldl-aux (f base (car lst)) (cdr lst)))))
(foldl-aux base lst)))
(define for
(lambda (lo hi f)
(define for-aux
(lambda (lo)
(if (< lo hi)
(cons (f lo) (for-aux (+ lo 1)))
'())))
(for-aux lo)))
(define concat
(lambda (lists)
(foldr append '() lists)))
(define list-read
(lambda (lst i)
(if (= i 0)
(car lst)
(list-read (cdr lst) (- i 1)))))
(define list-write
(lambda (lst i val)
(if (= i 0)
(cons val (cdr lst))
(cons (car lst) (list-write (cdr lst) (- i 1) val)))))
(define list-remove-pos
(lambda (lst i)
(if (= i 0)
(cdr lst)
(cons (car lst) (list-remove-pos (cdr lst) (- i 1))))))
(define duplicates?
(lambda (lst)
(if (null? lst)
#f
(or (member (car lst) (cdr lst))
(duplicates? (cdr lst))))))
(define make-matrix
(lambda (n m init)
(for 0 n (lambda (i) (for 0 m (lambda (j) (init i j)))))))
(define matrix-read
(lambda (mat i j)
(list-read (list-read mat i) j)))
(define matrix-write
(lambda (mat i j val)
(list-write mat i (list-write (list-read mat i) j val))))
(define matrix-size
(lambda (mat)
(cons (length mat) (length (car mat)))))
(define matrix-map
(lambda (f mat)
(map (lambda (lst) (map f lst)) mat)))
(define initial-random 0)
(define next-random
(lambda (current-random)
(remainder (+ (* current-random 3581) 12751) 131072)))
(define shuffle
(lambda (lst)
(shuffle-aux lst initial-random)))
(define shuffle-aux
(lambda (lst current-random)
(if (null? lst)
'()
(let ((new-random (next-random current-random)))
(let ((i (modulo new-random (length lst))))
(cons (list-read lst i)
(shuffle-aux (list-remove-pos lst i)
new-random)))))))
(define make-maze
(if (not (and (odd? n) (odd? m)))
'error
(let ((cave
(make-matrix n m (lambda (i j)
(if (and (even? i) (even? j))
(cons i j)
#f))))
(possible-holes
(concat
(for 0 n (lambda (i)
(concat
(for 0 m (lambda (j)
(if (equal? (even? i) (even? j))
'()
(list (cons i j)))))))))))
(cave-to-maze (pierce-randomly (shuffle possible-holes) cave))))))
(define cave-to-maze
(lambda (cave)
(matrix-map (lambda (x) (if x '_ '*)) cave)))
(define pierce
(lambda (pos cave)
(let ((i (car pos)) (j (cdr pos)))
(matrix-write cave i j pos))))
(define pierce-randomly
(lambda (possible-holes cave)
(if (null? possible-holes)
cave
(let ((hole (car possible-holes)))
(pierce-randomly (cdr possible-holes)
(try-to-pierce hole cave))))))
(define try-to-pierce
(lambda (pos cave)
(let ((i (car pos)) (j (cdr pos)))
(let ((ncs (neighboring-cavities pos cave)))
(if (duplicates?
(map (lambda (nc) (matrix-read cave (car nc) (cdr nc))) ncs))
cave
(pierce pos
(foldl (lambda (c nc) (change-cavity c nc pos))
cave
ncs)))))))
(define change-cavity
(lambda (cave pos new-cavity-id)
(let ((i (car pos)) (j (cdr pos)))
(change-cavity-aux cave pos new-cavity-id (matrix-read cave i j)))))
(define change-cavity-aux
(lambda (cave pos new-cavity-id old-cavity-id)
(let ((i (car pos)) (j (cdr pos)))
(let ((cavity-id (matrix-read cave i j)))
(if (equal? cavity-id old-cavity-id)
(foldl (lambda (c nc)
(change-cavity-aux c nc new-cavity-id old-cavity-id))
(matrix-write cave i j new-cavity-id)
(neighboring-cavities pos cave))
cave)))))
(define neighboring-cavities
(lambda (pos cave)
(let ((size (matrix-size cave)))
(let ((n (car size)) (m (cdr size)))
(let ((i (car pos)) (j (cdr pos)))
(append (if (and (> i 0) (matrix-read cave (- i 1) j))
(list (cons (- i 1) j))
'())
(if (and (< i (- n 1)) (matrix-read cave (+ i 1) j))
(list (cons (+ i 1) j))
'())
(if (and (> j 0) (matrix-read cave i (- j 1)))
(list (cons i (- j 1)))
'())
(if (and (< j (- m 1)) (matrix-read cave i (+ j 1)))
(list (cons i (+ j 1)))
'())))))))
(define (run-loop k)
(let loop ((n 60) (v 0))
(if (zero? n)
v
(loop (- n 1) (make-maze 15 k)))))
(run-loop 15)
|
ec93360edd36b2812292437055c0d5cd6ca3e181c57ab71fab5c41376bf8f956 | qfpl/applied-fp-course | Conf.hs | {-# LANGUAGE OverloadedStrings #-}
module Level04.Conf
( Conf (..)
, firstAppConfig
) where
-- We'll do more with this later, but we can easily stub it to keep things
-- rolling and come back to refactor it later.
data Conf = Conf
{ dbFilePath :: FilePath
}
-- A simple default that we could just inline this right where we need it. But
-- types are so cheap that we can easily prepare ourselves for "doing the right
-- thing".
firstAppConfig :: Conf
firstAppConfig = Conf "app_db.db"
| null | https://raw.githubusercontent.com/qfpl/applied-fp-course/d5a94a9dcee677bc95a5184c2ed13329c9f07559/src/Level04/Conf.hs | haskell | # LANGUAGE OverloadedStrings #
We'll do more with this later, but we can easily stub it to keep things
rolling and come back to refactor it later.
A simple default that we could just inline this right where we need it. But
types are so cheap that we can easily prepare ourselves for "doing the right
thing". | module Level04.Conf
( Conf (..)
, firstAppConfig
) where
data Conf = Conf
{ dbFilePath :: FilePath
}
firstAppConfig :: Conf
firstAppConfig = Conf "app_db.db"
|
500401333b7071733a276bebdcfecd9b880704a06430a119fe2faa160b968815 | achirkin/vulkan | VK_AMD_rasterization_order.hs | # OPTIONS_HADDOCK not - home #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MagicHash #-}
# LANGUAGE PatternSynonyms #
{-# LANGUAGE Strict #-}
{-# LANGUAGE ViewPatterns #-}
module Graphics.Vulkan.Ext.VK_AMD_rasterization_order
(AHardwareBuffer(), ANativeWindow(), CAMetalLayer(), VkBool32(..),
VkDeviceAddress(..), VkDeviceSize(..), VkFlags(..),
VkSampleMask(..), VkCullModeBitmask(..), VkCullModeFlagBits(),
VkCullModeFlags(), VkFrontFace(..),
VkAndroidSurfaceCreateFlagsKHR(..), VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..),
VkPipelineRasterizationStateCreateInfo,
VkPipelineRasterizationStateRasterizationOrderAMD,
VkPolygonMode(..), VkRasterizationOrderAMD(..),
VkStructureType(..), -- > #include "vk_platform.h"
VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION,
pattern VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION,
VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME,
pattern VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.CullModeFlags
import Graphics.Vulkan.Types.Enum.FrontFace
import Graphics.Vulkan.Types.Enum.PolygonMode
import Graphics.Vulkan.Types.Enum.RasterizationOrderAMD
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Struct.Pipeline (VkPipelineRasterizationStateCreateInfo,
VkPipelineRasterizationStateRasterizationOrderAMD)
pattern VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION :: (Num a, Eq a) =>
a
pattern VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION = 1
type VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION = 1
pattern VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME :: CString
pattern VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME <-
(is_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME -> True)
where
VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
= _VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
# INLINE _ VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME #
_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME :: CString
_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
= Ptr "VK_AMD_rasterization_order\NUL"#
# INLINE is_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME #
is_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME :: CString -> Bool
is_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
= (EQ ==) . cmpCStrings _VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
type VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME =
"VK_AMD_rasterization_order"
pattern VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD
= VkStructureType 1000018000
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_AMD_rasterization_order.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE Strict #
# LANGUAGE ViewPatterns #
> #include "vk_platform.h" | # OPTIONS_HADDOCK not - home #
# LANGUAGE PatternSynonyms #
module Graphics.Vulkan.Ext.VK_AMD_rasterization_order
(AHardwareBuffer(), ANativeWindow(), CAMetalLayer(), VkBool32(..),
VkDeviceAddress(..), VkDeviceSize(..), VkFlags(..),
VkSampleMask(..), VkCullModeBitmask(..), VkCullModeFlagBits(),
VkCullModeFlags(), VkFrontFace(..),
VkAndroidSurfaceCreateFlagsKHR(..), VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..),
VkPipelineRasterizationStateCreateInfo,
VkPipelineRasterizationStateRasterizationOrderAMD,
VkPolygonMode(..), VkRasterizationOrderAMD(..),
VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION,
pattern VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION,
VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME,
pattern VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.CullModeFlags
import Graphics.Vulkan.Types.Enum.FrontFace
import Graphics.Vulkan.Types.Enum.PolygonMode
import Graphics.Vulkan.Types.Enum.RasterizationOrderAMD
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Struct.Pipeline (VkPipelineRasterizationStateCreateInfo,
VkPipelineRasterizationStateRasterizationOrderAMD)
pattern VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION :: (Num a, Eq a) =>
a
pattern VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION = 1
type VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION = 1
pattern VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME :: CString
pattern VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME <-
(is_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME -> True)
where
VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
= _VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
# INLINE _ VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME #
_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME :: CString
_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
= Ptr "VK_AMD_rasterization_order\NUL"#
# INLINE is_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME #
is_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME :: CString -> Bool
is_VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
= (EQ ==) . cmpCStrings _VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME
type VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME =
"VK_AMD_rasterization_order"
pattern VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD
= VkStructureType 1000018000
|
ddf6f2cf2e70990014aeff540841ff03fd97170661798f035b97bee40aa4d2d3 | haskell-numerics/hmatrix | error.hs | import Numeric.GSL
import Numeric.GSL.Special
import Numeric.LinearAlgebra
import Prelude hiding (catch)
import Control.Exception
test x = catch
(print x)
(\e -> putStrLn $ "captured ["++ show (e :: SomeException) ++"]")
main = do
setErrorHandlerOff
test $ log_e (-1)
test $ 5 + (fst.exp_e) 1000
test $ bessel_zero_Jnu_e (-0.3) 2
test $ (inv 0 :: Matrix Double)
test $ (linearSolveLS 5 (sqrt (-1)) :: Matrix Double)
putStrLn "Bye"
| null | https://raw.githubusercontent.com/haskell-numerics/hmatrix/2694f776c7b5034d239acb5d984c489417739225/examples/error.hs | haskell | import Numeric.GSL
import Numeric.GSL.Special
import Numeric.LinearAlgebra
import Prelude hiding (catch)
import Control.Exception
test x = catch
(print x)
(\e -> putStrLn $ "captured ["++ show (e :: SomeException) ++"]")
main = do
setErrorHandlerOff
test $ log_e (-1)
test $ 5 + (fst.exp_e) 1000
test $ bessel_zero_Jnu_e (-0.3) 2
test $ (inv 0 :: Matrix Double)
test $ (linearSolveLS 5 (sqrt (-1)) :: Matrix Double)
putStrLn "Bye"
| |
6f27d8e30fe66da3d0c7575acc597114599e5fe4618a806272e35c7b7fcace16 | bluelisp/hemlock | package.lisp | ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
(defpackage "SPELL"
(:use "COMMON-LISP")
(:export #:spell-try-word #:spell-root-word #:spell-collect-close-words
#:correct-spelling
#:+max-entry-length+
#:spell-read-dictionary #:spell-add-entry #:spell-root-flags
#:spell-remove-entry)) | null | https://raw.githubusercontent.com/bluelisp/hemlock/47e16ba731a0cf4ffd7fb2110e17c764ae757170/unused/spell/package.lisp | lisp | -*- Mode: Lisp; indent-tabs-mode: nil -*- |
(defpackage "SPELL"
(:use "COMMON-LISP")
(:export #:spell-try-word #:spell-root-word #:spell-collect-close-words
#:correct-spelling
#:+max-entry-length+
#:spell-read-dictionary #:spell-add-entry #:spell-root-flags
#:spell-remove-entry)) |
0e99130385e6fa6f1ec6abee8c43e566fde404cebf63635fcb37b9ec831c5875 | rabbitmq/rabbitmq-management-agent | rabbit_mgmt_db_handler.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_mgmt_db_handler).
-include_lib("rabbit_common/include/rabbit.hrl").
%% Make sure our database is hooked in *before* listening on the network or
%% recovering queues (i.e. so there can't be any events fired before it starts).
-rabbit_boot_step({rabbit_mgmt_db_handler,
[{description, "management agent"},
{mfa, {?MODULE, add_handler, []}},
{cleanup, {gen_event, delete_handler,
[rabbit_event, ?MODULE, []]}},
{requires, rabbit_event},
{enables, recovery}]}).
-behaviour(gen_event).
-export([add_handler/0, gc/0, rates_mode/0]).
-export([init/1, handle_call/2, handle_event/2, handle_info/2,
terminate/2, code_change/3]).
%%----------------------------------------------------------------------------
add_handler() ->
ok = ensure_statistics_enabled(),
gen_event:add_handler(rabbit_event, ?MODULE, []).
gc() ->
erlang:garbage_collect(whereis(rabbit_event)).
rates_mode() ->
case rabbit_mgmt_agent_config:get_env(rates_mode) of
undefined -> basic;
Mode -> Mode
end.
handle_force_fine_statistics() ->
case rabbit_mgmt_agent_config:get_env(force_fine_statistics) of
undefined ->
ok;
X ->
rabbit_log:warning(
"force_fine_statistics set to ~p; ignored.~n"
"Replaced by {rates_mode, none} in the rabbitmq_management "
"application.~n", [X])
end.
%%----------------------------------------------------------------------------
ensure_statistics_enabled() ->
ForceStats = rates_mode() =/= none,
handle_force_fine_statistics(),
{ok, StatsLevel} = application:get_env(rabbit, collect_statistics),
rabbit_log:info("Management plugin: using rates mode '~p'~n", [rates_mode()]),
case {ForceStats, StatsLevel} of
{true, fine} ->
ok;
{true, _} ->
application:set_env(rabbit, collect_statistics, fine);
{false, none} ->
application:set_env(rabbit, collect_statistics, coarse);
{_, _} ->
ok
end,
ok = rabbit:force_event_refresh(erlang:make_ref()).
%%----------------------------------------------------------------------------
init([]) ->
{ok, []}.
handle_call(_Request, State) ->
{ok, not_understood, State}.
handle_event(#event{type = Type} = Event, State)
when Type == connection_closed; Type == channel_closed; Type == queue_deleted;
Type == exchange_deleted; Type == vhost_deleted;
Type == consumer_deleted; Type == node_node_deleted;
Type == channel_consumer_deleted ->
gen_server:cast(rabbit_mgmt_metrics_gc:name(Type), {event, Event}),
{ok, State};
handle_event(_, State) ->
{ok, State}.
handle_info(_Info, State) ->
{ok, State}.
terminate(_Arg, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-management-agent/d5951e181fb78dcd4c6a9d90762d0fe0a832e1a8/src/rabbit_mgmt_db_handler.erl | erlang |
Make sure our database is hooked in *before* listening on the network or
recovering queues (i.e. so there can't be any events fired before it starts).
----------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_mgmt_db_handler).
-include_lib("rabbit_common/include/rabbit.hrl").
-rabbit_boot_step({rabbit_mgmt_db_handler,
[{description, "management agent"},
{mfa, {?MODULE, add_handler, []}},
{cleanup, {gen_event, delete_handler,
[rabbit_event, ?MODULE, []]}},
{requires, rabbit_event},
{enables, recovery}]}).
-behaviour(gen_event).
-export([add_handler/0, gc/0, rates_mode/0]).
-export([init/1, handle_call/2, handle_event/2, handle_info/2,
terminate/2, code_change/3]).
add_handler() ->
ok = ensure_statistics_enabled(),
gen_event:add_handler(rabbit_event, ?MODULE, []).
gc() ->
erlang:garbage_collect(whereis(rabbit_event)).
rates_mode() ->
case rabbit_mgmt_agent_config:get_env(rates_mode) of
undefined -> basic;
Mode -> Mode
end.
handle_force_fine_statistics() ->
case rabbit_mgmt_agent_config:get_env(force_fine_statistics) of
undefined ->
ok;
X ->
rabbit_log:warning(
"force_fine_statistics set to ~p; ignored.~n"
"Replaced by {rates_mode, none} in the rabbitmq_management "
"application.~n", [X])
end.
ensure_statistics_enabled() ->
ForceStats = rates_mode() =/= none,
handle_force_fine_statistics(),
{ok, StatsLevel} = application:get_env(rabbit, collect_statistics),
rabbit_log:info("Management plugin: using rates mode '~p'~n", [rates_mode()]),
case {ForceStats, StatsLevel} of
{true, fine} ->
ok;
{true, _} ->
application:set_env(rabbit, collect_statistics, fine);
{false, none} ->
application:set_env(rabbit, collect_statistics, coarse);
{_, _} ->
ok
end,
ok = rabbit:force_event_refresh(erlang:make_ref()).
init([]) ->
{ok, []}.
handle_call(_Request, State) ->
{ok, not_understood, State}.
handle_event(#event{type = Type} = Event, State)
when Type == connection_closed; Type == channel_closed; Type == queue_deleted;
Type == exchange_deleted; Type == vhost_deleted;
Type == consumer_deleted; Type == node_node_deleted;
Type == channel_consumer_deleted ->
gen_server:cast(rabbit_mgmt_metrics_gc:name(Type), {event, Event}),
{ok, State};
handle_event(_, State) ->
{ok, State}.
handle_info(_Info, State) ->
{ok, State}.
terminate(_Arg, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
4e085d50329062d3c829d133b4e0e4200ad37339f70f7c402b8b114b3d4d3496 | adacapo21/plutusPioneerProgram | TestStateMachine.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE NumericUnderscores #-}
# LANGUAGE OverloadedStrings #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module Week07.TestStateMachine where
import Control.Monad hiding (fmap)
import Control.Monad.Freer.Extras as Extras
import Data.Default (Default (..))
import Ledger
import Ledger.TimeSlot
import Plutus.Trace.Emulator as Emulator
import PlutusTx.Prelude
import Prelude (IO, Show (..))
import Wallet.Emulator.Wallet
import Week07.StateMachine
test :: IO ()
test = do
test' Zero Zero
test' Zero One
test' One Zero
test' One One
test' :: GameChoice -> GameChoice -> IO ()
test' c1 c2 = runEmulatorTraceIO $ myTrace c1 c2
myTrace :: GameChoice -> GameChoice -> EmulatorTrace ()
myTrace c1 c2 = do
Extras.logInfo $ "first move: " ++ show c1 ++ ", second move: " ++ show c2
h1 <- activateContractWallet (Wallet 1) endpoints
h2 <- activateContractWallet (Wallet 2) endpoints
let pkh1 = pubKeyHash $ walletPubKey $ Wallet 1
pkh2 = pubKeyHash $ walletPubKey $ Wallet 2
stake = 5_000_000
deadline1 = slotToEndPOSIXTime def 5
deadline2 = slotToEndPOSIXTime def 10
fp = FirstParams
{ fpSecond = pkh2
, fpStake = stake
, fpPlayDeadline = deadline1
, fpRevealDeadline = deadline2
, fpNonce = "SECRETNONCE"
, fpChoice = c1
}
callEndpoint @"first" h1 fp
tt <- getTT h1
let sp = SecondParams
{ spFirst = pkh1
, spStake = stake
, spPlayDeadline = deadline1
, spRevealDeadline = deadline2
, spChoice = c2
, spToken = tt
}
void $ Emulator.waitNSlots 3
callEndpoint @"second" h2 sp
void $ Emulator.waitNSlots 10
where
getTT :: ContractHandle (Last ThreadToken) GameSchema Text -> EmulatorTrace ThreadToken
getTT h = do
void $ Emulator.waitNSlots 1
Last m <- observableState h
case m of
Nothing -> getTT h
Just tt -> Extras.logInfo ("read thread token " ++ show tt) >> return tt
| null | https://raw.githubusercontent.com/adacapo21/plutusPioneerProgram/fc9a7b8ea8eb0fe913ce0c246e026ffd27b37f9c/week07/src/Week07/TestStateMachine.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE NumericUnderscores #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators # | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Week07.TestStateMachine where
import Control.Monad hiding (fmap)
import Control.Monad.Freer.Extras as Extras
import Data.Default (Default (..))
import Ledger
import Ledger.TimeSlot
import Plutus.Trace.Emulator as Emulator
import PlutusTx.Prelude
import Prelude (IO, Show (..))
import Wallet.Emulator.Wallet
import Week07.StateMachine
test :: IO ()
test = do
test' Zero Zero
test' Zero One
test' One Zero
test' One One
test' :: GameChoice -> GameChoice -> IO ()
test' c1 c2 = runEmulatorTraceIO $ myTrace c1 c2
myTrace :: GameChoice -> GameChoice -> EmulatorTrace ()
myTrace c1 c2 = do
Extras.logInfo $ "first move: " ++ show c1 ++ ", second move: " ++ show c2
h1 <- activateContractWallet (Wallet 1) endpoints
h2 <- activateContractWallet (Wallet 2) endpoints
let pkh1 = pubKeyHash $ walletPubKey $ Wallet 1
pkh2 = pubKeyHash $ walletPubKey $ Wallet 2
stake = 5_000_000
deadline1 = slotToEndPOSIXTime def 5
deadline2 = slotToEndPOSIXTime def 10
fp = FirstParams
{ fpSecond = pkh2
, fpStake = stake
, fpPlayDeadline = deadline1
, fpRevealDeadline = deadline2
, fpNonce = "SECRETNONCE"
, fpChoice = c1
}
callEndpoint @"first" h1 fp
tt <- getTT h1
let sp = SecondParams
{ spFirst = pkh1
, spStake = stake
, spPlayDeadline = deadline1
, spRevealDeadline = deadline2
, spChoice = c2
, spToken = tt
}
void $ Emulator.waitNSlots 3
callEndpoint @"second" h2 sp
void $ Emulator.waitNSlots 10
where
getTT :: ContractHandle (Last ThreadToken) GameSchema Text -> EmulatorTrace ThreadToken
getTT h = do
void $ Emulator.waitNSlots 1
Last m <- observableState h
case m of
Nothing -> getTT h
Just tt -> Extras.logInfo ("read thread token " ++ show tt) >> return tt
|
cbdc0915e8100ce378519a4f335f6ec3a8ad0c932a9d9d7b7aca9d47c2ccacbb | berkeley-cs164-2022/class-compiler-f22 | util.ml |
let gensym : string -> string =
let counter = ref 0 in
fun s ->
let symbol = Printf.sprintf "%s__%d" s !counter in
counter := !counter + 1 ;
symbol
module ST = Map.Make (struct
type t = string
let compare = compare
end)
module Symtab = struct
include ST
let of_list l = l |> List.to_seq |> of_seq
let add_list tab l = List.fold_left (fun tab (k, v) -> add k v tab) tab l
end
type 'a symtab = 'a Symtab.t
let rec input_all (ch : in_channel) : string =
try
let c = input_char ch in
String.make 1 c ^ input_all ch
with End_of_file -> ""
let defn_label s =
let nasm_char c =
match c with
| 'a' .. 'z'
| 'A' .. 'Z'
| '0' .. '9'
| '_'
| '$'
| '#'
| '@'
| '~'
| '.'
| '?' ->
c
| _ ->
'_'
in
Printf.sprintf "function_%s_%d" (String.map nasm_char s) (Hashtbl.hash s) | null | https://raw.githubusercontent.com/berkeley-cs164-2022/class-compiler-f22/89b4e7c0aa186d49406f5130f6c1e587e8c4d6bc/lib/util.ml | ocaml |
let gensym : string -> string =
let counter = ref 0 in
fun s ->
let symbol = Printf.sprintf "%s__%d" s !counter in
counter := !counter + 1 ;
symbol
module ST = Map.Make (struct
type t = string
let compare = compare
end)
module Symtab = struct
include ST
let of_list l = l |> List.to_seq |> of_seq
let add_list tab l = List.fold_left (fun tab (k, v) -> add k v tab) tab l
end
type 'a symtab = 'a Symtab.t
let rec input_all (ch : in_channel) : string =
try
let c = input_char ch in
String.make 1 c ^ input_all ch
with End_of_file -> ""
let defn_label s =
let nasm_char c =
match c with
| 'a' .. 'z'
| 'A' .. 'Z'
| '0' .. '9'
| '_'
| '$'
| '#'
| '@'
| '~'
| '.'
| '?' ->
c
| _ ->
'_'
in
Printf.sprintf "function_%s_%d" (String.map nasm_char s) (Hashtbl.hash s) | |
c547ec9af495294bb72167d01bef6f5e29f08b3b77556c2b45a2055ff5795081 | plexus/chestnut | ui.cljs | (ns {{project-ns}}.components.ui
(:require [com.stuartsierra.component :as component]
[{{project-ns}}.core :refer [render]]))
(defrecord UIComponent []
component/Lifecycle
(start [component]
(render)
component)
(stop [component]
component))
(defn new-ui-component []
(map->UIComponent {}))
| null | https://raw.githubusercontent.com/plexus/chestnut/684b668141586ed5ef4389f94a4dc7f4fde13112/src/leiningen/new/chestnut/src/cljs/chestnut/components/ui.cljs | clojure | (ns {{project-ns}}.components.ui
(:require [com.stuartsierra.component :as component]
[{{project-ns}}.core :refer [render]]))
(defrecord UIComponent []
component/Lifecycle
(start [component]
(render)
component)
(stop [component]
component))
(defn new-ui-component []
(map->UIComponent {}))
| |
7edc188d7fa6083de608fc0db44b6d848aa9962b942f84b5095e80166ac12457 | Clozure/ccl-tests | case.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Fri Oct 18 19:56:44 2002
;;;; Contains: Tests of CASE
(in-package :cl-test)
(deftest case.1
(case 'a)
nil)
(deftest case.2
(case 10 (10 'a))
a)
(deftest case.3
(case (copy-seq "abc") ("abc" 'a))
nil)
(deftest case.4
(case 'z ((a b c) 1)
((d e) 2)
((f z g) 3)
(t 4))
3)
(deftest case.5
(case (1+ most-positive-fixnum)
(#.(1+ most-positive-fixnum) 'a))
a)
(deftest case.6
(case nil (nil 'a) (t 'b))
b)
(deftest case.7
(case nil ((nil) 'a) (t 'b))
a)
(deftest case.8
(case 'a (b 0) (a (values 1 2 3)) (t nil))
1 2 3)
(deftest case.9
(case 'c (b 0) (a (values 1 2 3)) (t (values 'x 'y 'z)))
x y z)
(deftest case.10
(case 'z (b 1) (a 2) (z (values)) (t nil)))
(deftest case.11
(case 'z (b 1) (a 2) (t (values))))
(deftest case.12
(case t (a 10))
nil)
(deftest case.13
(case t ((t) 10) (t 20))
10)
(deftest case.14
(let ((x (list 'a 'b)))
(eval `(case (quote ,x) ((,x) 1) (t 2))))
1)
(deftest case.15
(case 'otherwise ((t) 10))
nil)
(deftest case.16
(case t ((otherwise) 10))
nil)
(deftest case.17
(case 'a (b 0) (c 1) (otherwise 2))
2)
(deftest case.18
(case 'a (b 0) (c 1) ((otherwise) 2))
nil)
(deftest case.19
(case 'a (b 0) (c 1) ((t) 2))
nil)
(deftest case.20
(case #\a
((#\b #\c) 10)
((#\d #\e #\A) 20)
(() 30)
((#\z #\a #\y) 40))
40)
(deftest case.21 (case 1 (1 (values))))
(deftest case.22 (case 2 (t (values))))
(deftest case.23 (case 1 (1 (values 'a 'b 'c)))
a b c)
(deftest case.24 (case 2 (t (values 'a 'b 'c)))
a b c)
;;; Show that the key expression is evaluated only once.
(deftest case.25
(let ((x 0))
(values
(case (progn (incf x) 'c)
(a 1)
(b 2)
(c 3)
(t 4))
x))
3 1)
Repeated keys are allowed ( all but the first are ignored )
(deftest case.26
(case 'b ((a b c) 10) (b 20))
10)
(deftest case.27
(case 'b (b 20) ((a b c) 10))
20)
(deftest case.28
(case 'b (b 20) (b 10) (t 0))
20)
There are implicit progns
(deftest case.29
(let ((x nil))
(values
(case 2
(1 (setq x 'a) 'w)
(2 (setq x 'b) 'y)
(t (setq x 'c) 'z))
x))
y b)
(deftest case.30
(let ((x nil))
(values
(case 10
(1 (setq x 'a) 'w)
(2 (setq x 'b) 'y)
(t (setq x 'c) 'z))
x))
z c)
(deftest case.31
(case (values 'b 'c) (c 0) ((a b) 10) (t 20))
10)
(deftest case.32
(case 'a (a) (t 'b))
nil)
(deftest case.33
(case 'a (b 'b) (t))
nil)
(deftest case.34
(case 'a (b 'b) (otherwise))
nil)
;;; No implicit tagbody
(deftest case.35
(block done
(tagbody
(case 'a (a (go 10)
10
(return-from done 'bad)))
10
(return-from done 'good)))
good)
(deftest case.36
(block done
(tagbody
(case 'b
(a 'bad)
(otherwise (go 10)
10
(return-from done 'bad)))
10
(return-from done 'good)))
good)
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest case.37
(macrolet
((%m (z) z))
(case (expand-in-current-env (%m :b))
(:a :bad1)
(:b :good)
(:c :bad2)
(t :bad3)))
:good)
;;; (deftest case.error.1
;;; (signals-error (case) program-error)
;;; t)
(deftest case.error.1
(signals-error (funcall (macro-function 'case))
program-error)
t)
(deftest case.error.2
(signals-error (funcall (macro-function 'case) '(case t))
program-error)
t)
(deftest case.error.3
(signals-error (funcall (macro-function 'case) '(case t) nil nil)
program-error)
t)
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/case.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of CASE
Show that the key expression is evaluated only once.
No implicit tagbody
Test that explicit calls to macroexpand in subforms
are done in the correct environment
(deftest case.error.1
(signals-error (case) program-error)
t) | Author :
Created : Fri Oct 18 19:56:44 2002
(in-package :cl-test)
(deftest case.1
(case 'a)
nil)
(deftest case.2
(case 10 (10 'a))
a)
(deftest case.3
(case (copy-seq "abc") ("abc" 'a))
nil)
(deftest case.4
(case 'z ((a b c) 1)
((d e) 2)
((f z g) 3)
(t 4))
3)
(deftest case.5
(case (1+ most-positive-fixnum)
(#.(1+ most-positive-fixnum) 'a))
a)
(deftest case.6
(case nil (nil 'a) (t 'b))
b)
(deftest case.7
(case nil ((nil) 'a) (t 'b))
a)
(deftest case.8
(case 'a (b 0) (a (values 1 2 3)) (t nil))
1 2 3)
(deftest case.9
(case 'c (b 0) (a (values 1 2 3)) (t (values 'x 'y 'z)))
x y z)
(deftest case.10
(case 'z (b 1) (a 2) (z (values)) (t nil)))
(deftest case.11
(case 'z (b 1) (a 2) (t (values))))
(deftest case.12
(case t (a 10))
nil)
(deftest case.13
(case t ((t) 10) (t 20))
10)
(deftest case.14
(let ((x (list 'a 'b)))
(eval `(case (quote ,x) ((,x) 1) (t 2))))
1)
(deftest case.15
(case 'otherwise ((t) 10))
nil)
(deftest case.16
(case t ((otherwise) 10))
nil)
(deftest case.17
(case 'a (b 0) (c 1) (otherwise 2))
2)
(deftest case.18
(case 'a (b 0) (c 1) ((otherwise) 2))
nil)
(deftest case.19
(case 'a (b 0) (c 1) ((t) 2))
nil)
(deftest case.20
(case #\a
((#\b #\c) 10)
((#\d #\e #\A) 20)
(() 30)
((#\z #\a #\y) 40))
40)
(deftest case.21 (case 1 (1 (values))))
(deftest case.22 (case 2 (t (values))))
(deftest case.23 (case 1 (1 (values 'a 'b 'c)))
a b c)
(deftest case.24 (case 2 (t (values 'a 'b 'c)))
a b c)
(deftest case.25
(let ((x 0))
(values
(case (progn (incf x) 'c)
(a 1)
(b 2)
(c 3)
(t 4))
x))
3 1)
Repeated keys are allowed ( all but the first are ignored )
(deftest case.26
(case 'b ((a b c) 10) (b 20))
10)
(deftest case.27
(case 'b (b 20) ((a b c) 10))
20)
(deftest case.28
(case 'b (b 20) (b 10) (t 0))
20)
There are implicit progns
(deftest case.29
(let ((x nil))
(values
(case 2
(1 (setq x 'a) 'w)
(2 (setq x 'b) 'y)
(t (setq x 'c) 'z))
x))
y b)
(deftest case.30
(let ((x nil))
(values
(case 10
(1 (setq x 'a) 'w)
(2 (setq x 'b) 'y)
(t (setq x 'c) 'z))
x))
z c)
(deftest case.31
(case (values 'b 'c) (c 0) ((a b) 10) (t 20))
10)
(deftest case.32
(case 'a (a) (t 'b))
nil)
(deftest case.33
(case 'a (b 'b) (t))
nil)
(deftest case.34
(case 'a (b 'b) (otherwise))
nil)
(deftest case.35
(block done
(tagbody
(case 'a (a (go 10)
10
(return-from done 'bad)))
10
(return-from done 'good)))
good)
(deftest case.36
(block done
(tagbody
(case 'b
(a 'bad)
(otherwise (go 10)
10
(return-from done 'bad)))
10
(return-from done 'good)))
good)
(deftest case.37
(macrolet
((%m (z) z))
(case (expand-in-current-env (%m :b))
(:a :bad1)
(:b :good)
(:c :bad2)
(t :bad3)))
:good)
(deftest case.error.1
(signals-error (funcall (macro-function 'case))
program-error)
t)
(deftest case.error.2
(signals-error (funcall (macro-function 'case) '(case t))
program-error)
t)
(deftest case.error.3
(signals-error (funcall (macro-function 'case) '(case t) nil nil)
program-error)
t)
|
a675bd146d226c0df8517e5463bbe403810cfcc531beaa78198c34d2561bc32d | eglaysher/rldev | expr.ml |
Rlc : expression transformations
Copyright ( C ) 2006 Haeleth
This program is free software ; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation ; either version 2 of the License , or ( at your option ) any later
version .
This program is distributed in the hope that it will be useful , but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple
Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
Rlc: expression transformations
Copyright (C) 2006 Haeleth
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
*)
pp ./pa_matches.cmo
(* Order of evaluation of functions within an expression, and arguments within
a function call, is undefined; it will normally be left-to-right, but this
is NOT guaranteed. *)
open Printf
open KeTypes
open KeAst
open ExtList
type 'inferred transform_aux_struct =
{ get_id: unit -> int;
tempvars: (int, assignable) Hashtbl.t;
pre_code: (int * 'inferred) DynArray.t;
mutable redef_store: assignable option;
contains_store: bool Lazy.t }
let make_transform_aux e =
{ get_id = (let i = ref 0 in fun () -> incr i; !i);
tempvars = Hashtbl.create 0;
pre_code = DynArray.create ();
redef_store = None;
contains_store = lazy (exists_in_expr is_store e); }
(* Operator utilities *)
let prec : arith_op -> int =
Actual precedences in RealLive bytecode
function
| `Add | `Sub -> 10
| `Mul | `Div | `Mod | `And | `Or | `Xor | `Shl | `Shr -> 20
let apply_arith a b : arith_op -> int32 =
function
| `Add -> Int32.add a b | `Sub -> Int32.sub a b | `Mul -> Int32.mul a b | `Div -> Int32.div a b
| `Mod -> Int32.rem a b | `And -> Int32.logand a b | `Or -> Int32.logor a b | `Xor -> Int32.logxor a b
| `Shl -> Int32.shift_left a (Int32.to_int b) | `Shr -> Int32.shift_right a (Int32.to_int b)
let apply_unary i : unary_op -> int32 =
function
| `Sub -> Int32.neg i
| `Not -> if i = 0l then 1l else 0l
| `Inv -> Int32.logxor i Int32.minus_one
let apply_cond a b op =
let c = match op with
`Equ -> a = b | `Neq -> a <> b | `Ltn -> a < b | `Lte -> a <= b | `Gtn -> a > b | `Gte -> a >= b
in
if c then 1l else 0l
let reverse_cond : boolean_op -> boolean_op =
function
| `Equ -> `Neq
| `Neq -> `Equ
| `Ltn -> `Gte
| `Lte -> `Gtn
| `Gtn -> `Lte
| `Gte -> `Ltn
(* Utility traversals *)
let expr_disambiguate =
function
| `VarOrFn (loc, s, t)
-> if not (Memory.defined t) then
if Intrinsic.is_builtin t then
Intrinsic.eval_as_expr (loc, s, t, [], None)
else try
ignore (ver_fun "" (Hashtbl.find_all functions t));
`Func (loc, s, t, [], None)
with Not_found ->
(* Either a user function or an undefined symbol. *)
(* TODO: ultimately we want to implement user functions. *)
TODO : do we want to look for variables here too ?
ksprintf (error loc) "undeclared identifier `%s'" s
else
Memory.get_as_expression ~loc ~s t
| `Deref (loc, s, t, offset)
-> if not (Memory.defined t) then
ksprintf (error loc)
(if Intrinsic.is_builtin t || Hashtbl.mem functions t
then format_of_string "`%s' is not an array"
else format_of_string "undeclared identifier `%s'") s
else
Memory.get_deref_as_expression ~loc ~s t offset
| `Func (loc, s, t, parms, label)
-> assert (Memory.defined t || Intrinsic.is_builtin t);
assert (label == None);
if Memory.defined t then
let mf =
function
| `Simple (_, e) -> e
| `Complex (l, _)
| `Special (l, _, _) -> error l "expected expression as parameter to inline expansion"
in
Memory.get_as_expression ~loc ~s t ~args:(List.map mf parms)
else
Intrinsic.eval_as_expr (loc, s, t, parms, None)
let map_func_param f aux =
function
| `Simple (l, e) -> `Simple (l, f aux e)
| `Complex (l, p) -> `Complex (l, List.map (f aux) p)
| `Special (l, i, p) -> `Special (l, i, List.map (f aux) p)
let map_sel_param f aux =
function
| `Always (l, e) -> `Always (l, f aux e)
| `Special (l, cl, e)
-> let g =
function
| `Flag _ as flag -> flag
| `NonCond (l, s, t, e) -> `NonCond (l, s, t, f aux e)
| `Cond (l, s, t, p, e) -> `Cond (l, s, t, Option.map (f aux) p, f aux e)
in
`Special (l, List.map g cl, f aux e)
let rec unary_to_logop l =
function
| `LogOp (l, a, op, b) -> `LogOp (l, a, reverse_cond op, b)
| `Unary (l, `Not, e) -> conditional_unit e
| e -> `LogOp (l, e, `Equ, `Int (nowhere, 0l))
and conditional_unit =
function
| (`LogOp _ | `AndOr _) as c -> c
| `Unary (l, `Not, e) -> unary_to_logop l (conditional_unit e) (* TODO: check: is this correct? *)
| `Parens (l, c) -> `Parens (l, conditional_unit c)
| (`VarOrFn (_, _, t) | `Deref (_, _, t, _) | `Func (_, _, t, _, None)) as fc
when Memory.defined t || Intrinsic.is_builtin t -> conditional_unit (expr_disambiguate fc)
| c -> `LogOp (loc_of_expr c, c, `Neq, `Int (nowhere, 0l))
let rec equal_branch =
function
| `Int (_, i), `Int (_, j) -> i = j
| `Store _, `Store _ -> true
| `Op (_, a, o, b), `Op (_, c, p, d) -> o = p && equal_branch (a, c) && equal_branch (b, d)
| `LogOp (_, a, o, b), `LogOp (_, c, p, d) -> o = p && equal_branch (a, c) && equal_branch (b, d)
| `AndOr (_, a, o, b), `AndOr (_, c, p, d) -> o = p && equal_branch (a, c) && equal_branch (b, d)
| `Unary (_, o, i), `Unary (_, p, j) -> o = p && equal_branch (i, j)
| `IVar (_, i, a), `IVar (_, j, b)
| `SVar (_, i, a), `SVar (_, j, b) -> i = j && equal_branch (a, b)
| `Parens (_, a), b | a, `Parens (_, b) -> equal_branch (a, b)
| _ -> false
let rec type_of_traversed =
function
| `Int _ | `IVar _ | `Store _ | `ExFunc _ -> `Int
| `IStr _ | `Res _ | `SVar _ | `SChain _ -> `Str
| `FuncCall (_, e, _, _, _, _)
| `Parens (_, e)
| `Unary (_, _, e)
| `Op (_, e, _, _)
| `LogOp (_, e, _, _)
| `AndOr (_, e, _, _) -> type_of_traversed e
| `Func (l, s, _, _, _) -> ksprintf (error l) "`%s' is not a function valid in expressions" s
let loc_of_traversed =
function
| `Int (l, _) | `IVar (l, _, _) | `Store l | `ExFunc (l, _)
| `IStr (l, _) | `Res (l, _) | `SVar (l, _, _) | `SChain (l, _)
| `FuncCall (l, _, _, _, _, _)
| `Unary (l, _, _)
| `Op (l, _, _, _)
| `LogOp (l, _, _, _)
| `AndOr (l, _, _, _)
| `Parens (l, _) -> l
| `Func (l, s, _, _, _) -> ksprintf (error l) "`%s' is not a function valid in expressions" s
Utilities for generated code
let last_store_ref { pre_code = c } =
let rec loop n =
if n < 0 then None
else match DynArray.get c n with
| _, `FuncCall (_, `Store _, _, _, _, _)
| _, `Select (_, `Store _, _, _, _, _) -> Some n
| _ -> loop (n - 1)
in
loop (DynArray.length c - 1)
let add_store_func aux last_ref loc rv =
begin match last_ref with
(* If STORE is actually used in the expression and this has not been
rectified before, give those uses temporary variables *)
| None -> if Lazy.force aux.contains_store then
let ti = Memory.get_temp_int () in
assert (aux.redef_store = None);
aux.redef_store <- Some ti
(* Alternatively, if STORE has been used before, give the previous
reference a temporary variable instead *)
| Some n ->
let tv = Memory.get_temp_int () in
match DynArray.get aux.pre_code n with
| id, `FuncCall (l, `Store _, s, t, p, lbl)
-> Hashtbl.replace aux.tempvars id tv;
DynArray.set aux.pre_code n (id, `FuncCall (l, tv, s, t, p, lbl))
| id, `Select (l, `Store _, s, i, w, p)
-> Hashtbl.replace aux.tempvars id tv;
DynArray.set aux.pre_code n (id, `Select (l, tv, s, i, w, p))
| _ -> assert false
end;
(* Either way, lift the current function out to modify STORE *)
let id = aux.get_id () in
DynArray.add aux.pre_code (id, rv);
Hashtbl.add aux.tempvars id (`Store Memory.temploc);
`ExFunc (loc, id)
let add_int_of_conditional { pre_code = c } cond =
let tv = Memory.get_temp_int ()
and lb = Codegen.unique_label nowhere in
DynArray.add c (-1, `Assign (nowhere, tv, `Set, `Int (nowhere, 0l)));
DynArray.add c (-1, `ProcCall (nowhere, "goto_unless", Text.ident "goto_unless", [`Simple (nowhere, cond)], Some lb));
DynArray.add c (-1, `Assign (nowhere, tv, `Set, `Int (nowhere, 1l)));
DynArray.add c (-1, `Label lb);
tv
(* Functions to traverse and normalise an expression *)
let rec transform ?(as_cond = false) ~reject e =
let aux = make_transform_aux e in
let e = traverse aux (if as_cond then conditional_unit e else e) ~as_cond ~reject in
e, aux
and traverse ?(as_cond = false) ?(keep_unknown_funcs = false) ~reject aux =
function
(* Return atomic elements unchanged *)
| `Int (l, i)
-> if reject = `Int then error l "type mismatch: integer in string expression"; `Int (l, i)
| `Store l
-> if reject = `Int then error l "type mismatch: integer in string expression"; `Store l
(* Handle string literals *)
| `Str (l, s)
-> if reject = `Str then error l "type mismatch: string constant in integer expression";
`IStr (l, traverse_str_tokens aux s)
(* Expand resource strings *)
| `Res (l, t)
-> if reject = `Str then error l "type mismatch: #res<> in integer expression";
let t, l = Global.get_resource l (Text.to_err t, t) in
traverse aux (`Str (l, t)) ~as_cond ~keep_unknown_funcs ~reject
(* Remove superfluous parentheses *)
| `Parens (l, e)
->(match traverse aux e ~as_cond ~reject with
| (`Store _ | `IStr _ | `Int _ | `IVar _ | `SVar _ | `ExFunc _) as atom -> atom
| `Parens (_, e) | e -> if reject = `Int then e else `Parens (l, e))
(* Nothing of great interest happens to memory references *)
| `SVar (l, i, e)
-> if reject = `Str then error l "type mismatch: string variable in integer expression";
`SVar (l, i, traverse aux e ~reject:`Str)
| `IVar (l, i, e)
-> if reject = `Int then error l "type mismatch: integer variable in string expression";
`IVar (l, i, traverse aux e ~reject:`Str)
Disambiguate identifiers
| (`Deref _ | `VarOrFn _) as vof
-> traverse aux (expr_disambiguate vof) ~reject
(* Move function calls out of expressions *)
| `Func (l, s, t, parms, label as f) as fc
-> (* TODO: ultimately we want to implement user functions. *)
if Memory.defined t || Intrinsic.is_builtin t
then traverse aux (expr_disambiguate fc) ~reject
else traverse_func aux f ~reject ~keep_unknown_funcs
| `SelFunc f
-> traverse_select aux f ~reject
Fold constants ( for trivial cases only - we do n't simplify things like " 1 + x + 1 " )
| `Op (l, a, op, b)
->(let simple_a = traverse aux a ~reject in
if type_of_traversed simple_a = `Int then
Integer operations
let simple_b = traverse aux b ~reject:`Str in
match op, simple_a, simple_b with
(* Detect errors *)
| (`Div | `Mod), _, `Int (_, 0l) -> error l "division by zero"
Eliminate meaningless operations
| `And, e, `Int (_, -1l) | `And, `Int (_, -1l), e
| (`Or | `Xor), e, `Int (_, 0l) | (`Or | `Xor), `Int (_, 0l), e
| (`Add | `Sub), e, `Int (_, 0l) | `Add, `Int (_, 0l), e
| (`Mul | `Div), e, `Int (_, 1l) | `Mul, `Int (_, 1l), e -> e
| (`And | `Mul), _, `Int (_, 0l) | (`And | `Mul | `Div | `Mod), `Int (_, 0l), _ -> `Int (l, 0l)
| (`And | `Or), i, j when equal_branch (i, j) -> i
| (`Sub | `Xor | `Mod), i, j when equal_branch (i, j) -> `Int (l, 0l)
| `Div, i, j when equal_branch (i, j) -> `Int (l, 1l)
(* Fold constants *)
| _, `Int (_, i), `Int (_, j) -> `Int (l, apply_arith i j op)
(* Simplify expressions involving unary minus *)
| `Add, _, `Int (lb, i) when i < 0l -> `Op (l, simple_a, `Sub, `Int (lb, Int32.neg i))
| `Sub, _, `Int (lb, i) when i < 0l -> `Op (l, simple_a, `Add, `Int (lb, Int32.neg i))
| `Add, _, `Unary (_, `Sub, i) -> `Op (l, simple_a, `Sub, i)
| `Sub, _, `Unary (_, `Sub, i) -> `Op (l, simple_a, `Add, i)
| (`Div | `Mul), `Unary (_, `Sub, i), `Unary (_, `Sub, j) -> `Op (l, i, op, j)
(* Return ops for other cases *)
| _ -> let a =
match simple_a with
| `Op (_, _, aop, _) when prec aop < prec op -> `Parens (l, simple_a)
| _ -> simple_a
and b =
match simple_b with
| `Op (_, _, bop, _) when prec bop <= prec op -> `Parens (l, simple_b)
| _ -> simple_b
in
`Op (l, a, op, b)
else
(* String operations *)
let simple_b = traverse aux b ~reject:`Int in
if op <> `Add then ksprintf (error l) "invalid operator `%s' in string expression" (string_of_op op);
match simple_a, simple_b with
| `IStr (_, i), `IStr (_, j) -> let n = DynArray.copy i in DynArray.append j n; `IStr (l, n)
| `IStr (_, i), e | e, `IStr (_, i) when DynArray.length i = 0 -> e
(* Special cases for select_* functions *)
| `SChain (l, a), `SChain (_, b) -> `SChain (l, a @ b)
| a, `SChain (_, b) -> `SChain (loc_of_traversed a, a :: b)
| `SChain (l, a), b -> `SChain (l, a @ [b])
| a, b -> `SChain (loc_of_traversed a, [a; b])
(* end of `Op *))
| `Unary (l, op, e)
->(if reject = `Int then ksprintf (error l) "invalid operator `%s' in string expression" (string_of_op op);
match op, traverse aux e ~reject:`Str with
| _, `Int (_, i) -> `Int (l, apply_unary i op)
| _, `Unary (_, op', e) when op' = op -> e
| `Sub, e
-> let e = if (e matches `Op _) then `Parens (l, e) else e in
`Unary (l, `Sub, e)
| `Inv, e
-> let e =
match e with
| `Op (_, _, op, _) when prec op < prec `Xor -> `Parens (l, e)
| _ -> e
in
`Op (l, e, `Xor, `Int (nowhere, -1l))
| `Not, `Unary (_, `Sub, e)
| `Not, e -> let rv = `LogOp (l, e, `Equ, `Int (nowhere, 0l)) in
if as_cond then rv else add_int_of_conditional aux rv
(* end of `Unary *))
(* Potentially lift out logical and boolean operators *)
| `LogOp (l, a, op, b)
->(if reject = `Int then ksprintf (error l) "invalid operator `%s' in string expression" (string_of_op op);
let simple_b = traverse aux b ~reject:`None in
if type_of_traversed simple_b = `Int then
let simple_a = traverse aux a ~reject:`Str in
match op, simple_a, simple_b with
| _, `Int (_, i), `Int (_, j) -> `Int (l, apply_cond i j op)
| (`Equ | `Gte | `Lte), i, j when equal_branch (i, j) -> `Int (l, 1l)
| (`Neq | `Gtn | `Ltn), i, j when equal_branch (i, j) -> `Int (l, 0l)
| _ -> let rv = `LogOp (l, simple_a, op, simple_b) in
if as_cond then rv else add_int_of_conditional aux rv
else
(* String comparisons. *)
let simple_a = traverse aux a ~reject:`Int in
let v =
add_store_func aux (last_store_ref aux) nowhere
(`FuncCall (nowhere, `Store nowhere, "strcmp", Text.ident "strcmp",
[`Simple (nowhere, simple_a); `Simple (nowhere, simple_b)], None))
in
if op = `Neq && not as_cond then
v
else
let rv = `LogOp (l, v, op, `Int (nowhere, 0l)) in
if as_cond then rv else add_int_of_conditional aux rv
end of ` LogOp
| `AndOr (l, a, op, b)
->(if reject = `Int then ksprintf (error l) "invalid operator `%s' in string expression" (string_of_op op);
let simple_a = traverse aux (conditional_unit a) ~as_cond:true ~reject:`Str in
let simple_b = traverse aux (conditional_unit b) ~as_cond:true ~reject:`Str in
let return rv =
match rv with
| `LogOp _ | `AndOr _ when not as_cond -> add_int_of_conditional aux rv
| _ -> rv
in
match op, simple_a, simple_b with
| `LAnd, `Int (_, i), `Int (_, j) -> if i <> 0l && j <> 0l then `Int (l, 1l) else `Int (l, 0l)
| `LAnd, e, `Int (_, i) | `LAnd, `Int (_, i), e when i <> 0l -> return e
| `LAnd, e, `Int (_, i) | `LAnd, `Int (_, i), e when i = 0l -> `Int (l, 0l)
| `LOr, `Int (_, i), `Int (_, j) -> if i <> 0l || j <> 0l then `Int (l, 1l) else `Int (l, 0l)
| `LOr, e, `Int (_, i) | `LOr, `Int (_, i), e when i = 0l -> return e
| `LOr, e, `Int (_, i) | `LOr, `Int (_, i), e when i <> 0l -> `Int (l, 1l)
| _, i, j when equal_branch (i, j) -> return i
It appears that & & and || have equal precedence . This should fix the
discrepancy with Kepago , I hope .
discrepancy with Kepago, I hope. *)
let a =
match simple_a with
| `AndOr (_, _, `LAnd, _) when op = `LOr -> `Parens (l, simple_a)
| _ -> simple_a
and b =
match simple_b with
| `AndOr _ when op = `LOr -> `Parens (l, simple_b)
| _ -> simple_b
in
return (`AndOr (l, a, op, b))
(* end of `AndOr *))
| `ExprSeq (l, id, defs, smts)
-> (*FIXME: This evaluates the contents of the sequence: it has to do so in order that
constant return values can be treated as constants. This MAY cause subtle bugs, so
maybe this needs rethinking... *)
(*TODO: The "correct" behaviour would be for evaluation to halt as soon as anything is
encountered that alters any state whatsoever outside the sequence, and everything
then to be added to aux.pre_code instead. *)
if DynArray.empty smts then ksprintf (error l) "inline block `%s' expands to empty sequence: this is invalid in expressions" (Text.to_sjs id);
let last = DynArray.last smts in
DynArray.delete_last smts;
assert (Memory.defined id);
let sym = Memory.pull_sym id in
Memory.open_scope ();
Memory.define (Text.ident "__INLINE_CALL__") (`Macro (`Int (nowhere, 1l))) ~scoped:true;
Memory.define (Text.ident "__CALLER_FILE__") (`Macro (`Str (nowhere, Global.dynArray (`Text (nowhere, `Sbcs, Text.of_err l.file))))) ~scoped:true;
Memory.define (Text.ident "__CALLER_LINE__") (`Macro (`Int (nowhere, Int32.of_int l.line))) ~scoped:true;
List.iter (fun (i, e) -> Memory.define i (`Macro e) ~scoped:true) defs;
Meta.parse smts;
let rv = traverse aux (expr_of_statement last) ~as_cond ~reject ~keep_unknown_funcs in
Memory.close_scope ();
Memory.replace_sym id sym;
rv
and traverse_str_tokens aux tkns =
let rv = DynArray.create () in
DynArray.iter
begin function
| `Code (l, i, e, p) when i = Text.ident "s"
-> if e <> None then KeTypes.error l "length specifier invalid in \\s{}";
let add_str_elt =
function
| `SVar _ as sv -> DynArray.add rv (`Code (l, Text.ident "s", None, [`Simple (l, sv)]))
| `IStr (_, elts) -> DynArray.append elts rv
| _ -> assert false
in
(match List.map (map_func_param (traverse ~reject:`None) aux) p with
(* Expand \s{"string"} by lifting out its contents. *)
| [`Simple (_, `SChain (_, c))] -> List.iter add_str_elt c
| [`Simple (_, (`SVar _ | `IStr _ as elt))] -> add_str_elt elt
| p -> DynArray.add rv (`Code (l, i, None, p)))
| `Code (l, i, e, p)
-> let args = List.map (map_func_param (traverse ~reject:`None) aux) p in
if i = Text.ident "i"
&& Option.default true (Option.map normalised_expr_is_const e)
&& (args matches [`Simple (_, `Int (_, v))]) then
(* Expand \i{const} by converting to string *)
let s =
Text.of_sjs
(Global.int32_to_string_padded
(Int32.to_int (Option.default 0l (Option.map int_of_normalised_expr e)))
(match args with [`Simple (_, `Int (_, v))] -> v | _ -> assert false))
in
DynArray.add rv (`Text (l, `Sbcs, s))
else
DynArray.add rv (`Code (l, i, Option.map (traverse aux ~reject:`Str) e, args))
| `Gloss (l, g, s, r)
-> let rl, rs =
match r with
| `Closed rl_rs -> rl_rs
| `ResStr (kl, k) -> let a, b = Global.get_resource kl (Text.to_sjs k, k) in b, a
in
DynArray.add rv (`Gloss (l, g, traverse_str_tokens aux s, `Closed (rl, traverse_str_tokens aux rs)))
| `Name (l, lg, e, w)
-> DynArray.add rv (`Name (l, lg, traverse aux e ~reject:`Str, Option.map (traverse aux ~reject:`Str) w))
| #strtoken_non_expr as e -> DynArray.add rv e
end
tkns;
rv
and traverse_func ~keep_unknown_funcs ~reject aux (l, s, t, p, label) =
if Intrinsic.is_builtin t then error l "internal error: intrinsic call reached Expr.traverse_func";
match
try
Some (ver_fun "" (Hashtbl.find_all functions t))
with Not_found ->
if keep_unknown_funcs
then None
else ksprintf (error l) "unable to find an appropriate definition for the function `%s'" s
with
(* No prototype found: assume this is a special. *)
| None -> `Func (l, s, t, List.map (map_func_param (traverse ~reject:`None) aux) p, label)
(* Found a prototype: treat as a normal function call. *)
| Some f ->
(* Find out whether the function in question modifies a variable directly, or
whether it sets STORE instead. *)
let argc = List.length p + if List.mem KfnTypes.PushStore f.flags then 0 else 1 in
let overload = FuncAsm.choose_overload l f argc in
let prototype = f.prototypes.(overload) in
let return_as =
try
match
List.find
(fun (_, pattrs) -> List.mem KfnTypes.Return pattrs)
(Option.get prototype)
with
| KfnTypes.Int, _
-> if reject = `Int
then ksprintf (error l) "type mismatch: function `%s' returns an integer, but is here used in a string expression" s
else `Int
| KfnTypes.Str, _
-> if reject = `Str
then ksprintf (error l) "type mismatch: function `%s' returns a string, but is here used in an integer expression" s
else `Str
| _ -> ksprintf Optpp.sysError "error in reallive.kfn: invalid return type for function `%s'" s
with _ ->
if List.mem KfnTypes.PushStore f.flags
then `Store
else ksprintf (error l) "function `%s' has no return value: it cannot be used in expressions" s
in
(* Determine whether a previous function in the current expression
has made use of STORE *)
let last_ref = last_store_ref aux in
(* If it has parameters, transform expressions in them *)
let as_cond = List.mem KfnTypes.IsCond f.flags in
let p =
if as_cond
then List.map (function `Simple (l, e) -> `Simple (l, conditional_unit e) | x -> x) p
else p
in
let p = List.map (map_func_param (traverse ~keep_unknown_funcs:true ~reject:`None ~as_cond) aux) p in
(* Handle return value according to type *)
match return_as with
| `Store
-> add_store_func aux last_ref l (`FuncCall (l, `Store nowhere, s, t, p, label))
| `Int
-> let id = aux.get_id () in
let tv, rv =
if last_ref = None && not (Lazy.force aux.contains_store) then
(* TODO: check: is this correct? *)
(Hashtbl.add aux.tempvars id (`Store Memory.temploc);
`Store Memory.temploc, `ExFunc (l, id))
else
let tv = Memory.get_temp_int () in
tv, tv
in
DynArray.add aux.pre_code (id, `FuncCall (l, tv, s, t, p, label));
rv
| `Str
-> let tv = Memory.get_temp_str () in
DynArray.add aux.pre_code (-1, `FuncCall (l, tv, s, t, p, label));
tv
and traverse_select ~reject aux (l, s, i, w, p) =
if reject = `Int then
ksprintf (error l) "type mismatch: function `%s' returns an integer, but is here used in a string expression" s;
(* Determine whether a previous function in the current expression
has made use of STORE *)
let last_ref = last_store_ref aux in
(* Transform expressions in parameters *)
let w = Option.map (traverse aux ~reject:`Str) w
and p =
List.map
(function
| `Always (ll, e)
-> `Always (ll, traverse aux e ~reject:`Int)
| `Special (ll, cl, e)
-> let f =
function
| `Flag _ as flag -> flag
| `NonCond (l, s, t, e)
-> `NonCond (l, s, t, traverse aux e ~reject:`Str)
| `Cond (l, s, t, e, c)
-> `Cond (l, s, t, Option.map (traverse aux ~reject:`Str) e,
traverse aux (conditional_unit c) ~reject:`Str ~as_cond:true)
in
`Special (ll, List.map f cl, traverse aux e ~reject:`Int))
p
in
(* Handle return value *)
add_store_func aux last_ref l (`Select (l, `Store nowhere, s, i, w, p))
(* Function taking the results of a transformation and returning a valid expression *)
let rec finalise aux : 'inferred -> expression =
function
| `Store _ as s -> (match aux.redef_store with Some tempvar -> (tempvar :> expression) | None -> s)
| `IStr (l, s) -> `Str (l, DynArray.map (finalise_str_tokens aux) s)
| `Int _ as i -> (i :> expression)
| `IVar (l, i, e) -> `IVar (l, i, finalise aux e)
| `SVar (l, i, e) -> `SVar (l, i, finalise aux e)
| `Parens (l, e) -> `Parens (l, finalise aux e)
| `Unary (l, op, e) -> `Unary (l, op, finalise aux e)
| `Op (l, a, op, b) -> `Op (l, finalise aux a, op, finalise aux b)
| `LogOp (l, a, op, b) -> `LogOp (l, finalise aux a, op, finalise aux b)
| `AndOr (l, a, op, b) -> `AndOr (l, finalise aux a, op, finalise aux b)
| `Func (l, s, t, p, d) -> `Func (l, s, t, List.map (map_func_param finalise aux) p, d)
| `ExFunc (_, id) -> (try (Hashtbl.find aux.tempvars id :> expression) with _ -> assert false)
| `SChain (l, chain)
-> let s = DynArray.create () in
List.iter
(function
| `IStr (_, t) -> DynArray.append (DynArray.map (finalise_str_tokens aux) t) s
| `SVar (l, i, e)
-> DynArray.add s (`Code (l, Text.of_sjs "s", None, [`Simple (l, `SVar (l, i, finalise aux e))]));
| _ -> error l "expected string")
chain;
`Str (l, s)
and finalise_str_tokens aux =
function
| `Code (l, i, e, p) -> `Code (l, i, Option.map (finalise aux) e, List.map (map_func_param finalise aux) p)
| `Gloss (l, g, s, `Closed (cl, r)) -> `Gloss (l, g, DynArray.map (finalise_str_tokens aux) s, `Closed (cl, DynArray.map (finalise_str_tokens aux) r))
| `Gloss (_, _, _, `ResStr _) -> assert false
| `Name (l, lg, e, cidx) -> `Name (l, lg, finalise aux e, Option.map (finalise aux) cidx)
| #strtoken_non_expr as e -> e
let finalise_generated_code aux (_, s) : statement =
match s with
| `Assign (l, d, op, e) -> `Assign (l, d, op, finalise aux e)
| `ProcCall (l, s, t, p, lbl) -> `FuncCall (l, None, s, t, List.map (map_func_param finalise aux) p, lbl)
| `FuncCall (l, d, s, t, p, lbl) -> `FuncCall (l, Some d, s, t, List.map (map_func_param finalise aux) p, lbl)
| `Select (l, d, s, i, w, p) -> `Select (l, d, s, i, Option.map (finalise aux) w, List.map (map_sel_param finalise aux) p)
| (`Label _) as a -> a
Function taking a potentially complex assignment statement and returning a list of statements
representing valid RealLive code
representing valid RealLive code *)
let normalise_assignment (`Assign (loc, dest, op, e): assignment) =
let dest, is_int, reject =
let rec disambiguate =
function
| `Store _ as elt -> elt, true, `Str
| `IVar _ as elt -> elt, true, `Str
| `SVar _ as elt -> elt, false, `Int
| `Func (l, s, t, p, d) when Intrinsic.is_builtin t -> disambiguate (Intrinsic.eval_as_expr (l, s, t, p, d))
| `Deref (l, s, t, offset)
-> disambiguate
(try Memory.get_deref_as_expression ~loc:l ~s t offset with Not_found ->
ksprintf (error l) "undeclared identifier `%s'" s)
| `VarOrFn (l, s, t)
-> disambiguate
(if Intrinsic.is_builtin t then
Intrinsic.eval_as_expr (l, s, t, [], None)
else try
if not (Intrinsic.is_builtin t) then ignore (ver_fun "" (Hashtbl.find_all functions t));
ksprintf (error l) "function `%s' is not valid as the left-hand side of an assignment" s
with Not_found ->
try Memory.get_as_expression t with Not_found ->
(* TODO: ultimately we want to issue a different error message for user functions *)
ksprintf (error l) "undeclared identifier `%s'" s)
| _ -> error loc "the left-hand side of an assignment must be a variable or memory reference"
in
disambiguate (dest :> expression)
in
let e, aux = transform e ~reject in
let dest = traverse aux dest ~reject in
let e = match finalise aux e with `Parens (_, e) | e -> e in
let dest =
match finalise aux dest with
| #assignable as a -> a
| _ -> error loc "internal error: LHS normalised to non-assignable"
in
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
let result =
if is_int then
match e, try DynArray.last d with _ -> `Null with
| `Store _, `Assign (_, `Store _, `Set, expr)
-> `Replace (`Assign (loc, dest, op, expr))
| `Store _, `FuncCall (l, Some (`Store _), s, t, p, lbl)
when op = `Set
-> `Replace (`FuncCall (l, Some dest, s, t, p, lbl))
| `Store _, `Select (l, `Store _, s, i, w, p)
when op = `Set
-> `Replace (`Select (l, dest, s, i, w, p))
| `Store _, _
when op = `Set && is_store dest
-> `Neither
| _
when op = `Set && equal_branch (e, dest)
-> `Neither
| _
-> match e with
| `Op (_, a, op, b) when equal_branch (a, dest) -> `Append (`Assign (loc, dest, (op :> assign_op), b))
| _ -> `Append (`Assign (loc, dest, op, e))
else
match e, try DynArray.last d with _ -> `Null with
| `SVar (sl1, _, _), `FuncCall (l, Some (`SVar (sl2, _, _)), s, t, p, lbl)
when op = `Set && sl1 = Memory.temploc && sl1 = sl2
-> `Replace (`FuncCall (l, Some dest, s, t, p, lbl))
| _
-> let dest = match dest with `SVar _ as sv -> (sv :> expression) | _ -> assert false in
(* Handle non-initial occurrences of lval on RHS *)
let e, op =
match e with
| `Str (loc, text) when DynArray.length text > 1
-> let tempvar = ref None in
let f =
function
| `Simple (l, e) when equal_exprs e dest
-> let v =
match !tempvar with
| Some v -> v
| None -> let v = Memory.get_temp_str () ~useloc:l in
tempvar := Some v;
v
in `Simple (l, v)
| p -> p
in
let g =
function
| `Code (l, s, o, parms) -> `Code (l, s, o, List.map f parms)
| elt -> elt
in
let chop =
if op = `Set
&& (match DynArray.get text 0 with `Code (_, _, _, [`Simple (_, e)]) -> equal_exprs e dest | _ -> false)
then (DynArray.delete text 0; true)
else false
in
let ntext = DynArray.map g text in
(match !tempvar with
| None -> ()
| Some v -> DynArray.insert d 0
(`FuncCall (loc, None, "strcpy", Text.ident "strcpy",
[`Simple (loc, v); `Simple (loc, dest)], None)));
`Str (loc, ntext), if chop then `Add else op
| _ -> e, op
in
(* Replace with a function call. *)
if op = `Set then
if equal_branch (dest, e)
then `Neither
else `Append (`FuncCall (loc, None, "strcpy", Text.ident "strcpy", [`Simple (loc, dest); `Simple (loc, e)], None))
else if op = `Add then
`Append (`FuncCall (loc, None, "strcat", Text.ident "strcat", [`Simple (loc, dest); `Simple (loc, e)], None))
else
ksprintf (error loc) "assignment operator `%s' is not valid for strings" (string_of_assign_op op)
in
match result with
| `Replace smt -> DynArray.set d (DynArray.length d - 1) smt; d
| `Append smt -> DynArray.add d smt; d
| `Neither -> d
(* As normalise_assignment, but for function calls *)
let normalise_funccall (`FuncCall (loc, dest, s_ident, t_ident, params, label)) =
assert (dest matches None | Some (`Store _));
let aux = make_transform_aux (`Func (loc, s_ident, t_ident, params, label)) in
let as_cond =
try
List.mem KfnTypes.IsCond (ver_fun "" (Hashtbl.find_all functions t_ident)).flags
with Not_found ->
false
in
let p =
if as_cond
then List.map (function `Simple (l, e) -> `Simple (l, conditional_unit e) | x -> x) params
else params
in
let p = List.map (map_func_param (traverse ~keep_unknown_funcs:true ~reject:`None ~as_cond) aux) p in
DynArray.add aux.pre_code (-1, `ProcCall (loc, s_ident, t_ident, p, label));
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
d
let normalise_unknown (`UnknownOp (loc, fn, overload, params)) =
let aux =
{ (make_transform_aux (`Store nowhere))
with
contains_store = lazy (exists_in_expr is_store (`Func (loc, fn.ident, Text.of_arr [||], params, None))) }
in
let p = List.map (map_func_param (traverse ~keep_unknown_funcs:true ~reject:`None) aux) params in
let p = List.map (map_func_param finalise aux) p in
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
DynArray.add d (`UnknownOp (loc, fn, overload, p));
d
let normalise_select (`Select (loc, dest, s_ident, opcode, window, params)) =
let aux = make_transform_aux (`SelFunc (loc, s_ident, opcode, window, params)) in
let w = Option.map (traverse aux ~reject:`Str) window
and p =
List.map
(function
| `Always (ll, e)
-> `Always (ll, traverse aux e ~reject:`Int)
| `Special (ll, cl, e)
-> let f =
function
| `Flag _ as flag -> flag
| `NonCond (l, s, t, e) -> `NonCond (l, s, t, traverse aux e ~reject:`Str)
| `Cond (l, s, t, e, c) -> `Cond (l, s, t, Option.map (traverse aux ~reject:`Str) e,
traverse aux (conditional_unit c) ~reject:`Str ~as_cond:true)
in
`Special (ll, List.map f cl, traverse aux e ~reject:`Int))
params
in
DynArray.add aux.pre_code (-1, `Select (loc, dest, s_ident, opcode, w, p));
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
d
As normalise_assignment , but for calls
let normalise_gotocase (`GotoCase (loc, jump_type, e, cases)) =
let aux =
let all_exprs = e :: List.filter_map (function `Default _ -> None | `Match (e, _) -> Some e) cases in
{ (make_transform_aux (`Store nowhere))
with
contains_store = lazy (List.exists (exists_in_expr is_store) all_exprs) }
in
let e = traverse aux e ~reject:`Str in
let cases =
List.map
(function
| `Default _ as d -> d
| `Match (e, l) -> `Match (traverse aux e ~reject:`Str, l))
cases
in
let e = match finalise aux e with `Parens (_, e) | e -> e in
let cases =
List.map
(function
| `Default _ as d -> d
| `Match (e, l) -> `Match ((match finalise aux e with `Parens (_, e) | e -> e), l))
cases
in
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
DynArray.add d (`GotoCase (loc, jump_type, e, cases));
d
(* As normalise_assignment, but for other statements with expressions in *)
let normalise_nonassignment s =
let e, aux =
match s with
| `GotoOn (_, _, e, _) -> transform e ~reject:`Str
| `Return (_, _, e) -> transform e ~reject:`None
| `LoadFile (_, e) -> transform e ~reject:`Int
| `Directive (_, _, tp, e) -> transform e ~reject:(if tp = `Str then `Int else if tp = `Int then `Str else `None);
| `DConst (_, _, _, _, e) -> transform e ~reject:`None
in
let e = match finalise aux e with `Parens (_, e) | e -> e in
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
DynArray.add d
begin match s with
| `GotoOn (l, jt, _, lb) -> `GotoOn (l, jt, e, lb)
| `Return (l, b, _) -> `Return (l, b, e)
| `LoadFile (l, _) -> `LoadFile (l, e)
| `Directive (l, s, tp, _) -> `Directive (l, s, tp, e)
| `DConst (l, s, t, tp, _) -> `Define (l, s, t, tp = `Bind, e)
end;
d
Generic normalisation : takes any statement and returns a normalised form .
NOTE : If normalisation was performed , a new scope is opened but NOT
closed ; the caller must close it when finished .
NOTE: If normalisation was performed, a new scope is opened but NOT
closed; the caller must close it when finished. *)
let normalise =
let call f e =
Memory.open_scope ();
let m = f e in
if DynArray.length m = 0
then (Memory.close_scope (); `Nothing)
else `Multiple m
in
function
| #assignment as a -> call normalise_assignment a
| `FuncCall (_, (None | Some (`Store _)), _, _, _, _) as p -> call normalise_funccall p
| `FuncCall (l, Some rv, s, t, p, d) -> call normalise_assignment (`Assign (l, rv, `Set, `Func (l, s, t, p, d)))
| `UnknownOp _ as u -> call normalise_unknown u
| `GotoCase _ as g -> call normalise_gotocase g
| `Select _ as s -> call normalise_select s
| `DConst (_, _, _, (`Bind | `EBind), _)
| #normalisable as n -> call normalise_nonassignment n
| #statement as elt -> `Single elt
(* Expression-level normalisation, for constant expressions. *)
let normalise_and_get_const ?(abort_on_fail = true) ?(expect = `None) e =
let fail = `Op (nowhere, `Store nowhere, `Add, `Store nowhere) in (* non-constant expression to force a failure *)
let pre_len = DynArray.length Codegen.Output.bytecode in
let e, aux = transform e ~reject:`None in
let e =
if DynArray.length aux.pre_code <> 0 then fail else finalise aux e
in
let e =
if DynArray.length Codegen.Output.bytecode > pre_len then (
DynArray.delete_range Codegen.Output.bytecode pre_len (DynArray.length Codegen.Output.bytecode - pre_len);
fail
) else e
in
const_of_normalised_expr e ~expect ~abort_on_fail
let normalise_and_get_int ?(abort_on_fail = true) e =
match normalise_and_get_const e ~expect:`Int ~abort_on_fail with
| `Integer i -> i
| _ -> assert false
let normalise_and_get_str ?(abort_on_fail = true) e =
match normalise_and_get_const e ~expect:`Str ~abort_on_fail with
| `String s -> s
| _ -> assert false
| null | https://raw.githubusercontent.com/eglaysher/rldev/e59103b165e1c20bd940942405b2eee767933c96/src/rlc/expr.ml | ocaml | Order of evaluation of functions within an expression, and arguments within
a function call, is undefined; it will normally be left-to-right, but this
is NOT guaranteed.
Operator utilities
Utility traversals
Either a user function or an undefined symbol.
TODO: ultimately we want to implement user functions.
TODO: check: is this correct?
If STORE is actually used in the expression and this has not been
rectified before, give those uses temporary variables
Alternatively, if STORE has been used before, give the previous
reference a temporary variable instead
Either way, lift the current function out to modify STORE
Functions to traverse and normalise an expression
Return atomic elements unchanged
Handle string literals
Expand resource strings
Remove superfluous parentheses
Nothing of great interest happens to memory references
Move function calls out of expressions
TODO: ultimately we want to implement user functions.
Detect errors
Fold constants
Simplify expressions involving unary minus
Return ops for other cases
String operations
Special cases for select_* functions
end of `Op
end of `Unary
Potentially lift out logical and boolean operators
String comparisons.
end of `AndOr
FIXME: This evaluates the contents of the sequence: it has to do so in order that
constant return values can be treated as constants. This MAY cause subtle bugs, so
maybe this needs rethinking...
TODO: The "correct" behaviour would be for evaluation to halt as soon as anything is
encountered that alters any state whatsoever outside the sequence, and everything
then to be added to aux.pre_code instead.
Expand \s{"string"} by lifting out its contents.
Expand \i{const} by converting to string
No prototype found: assume this is a special.
Found a prototype: treat as a normal function call.
Find out whether the function in question modifies a variable directly, or
whether it sets STORE instead.
Determine whether a previous function in the current expression
has made use of STORE
If it has parameters, transform expressions in them
Handle return value according to type
TODO: check: is this correct?
Determine whether a previous function in the current expression
has made use of STORE
Transform expressions in parameters
Handle return value
Function taking the results of a transformation and returning a valid expression
TODO: ultimately we want to issue a different error message for user functions
Handle non-initial occurrences of lval on RHS
Replace with a function call.
As normalise_assignment, but for function calls
As normalise_assignment, but for other statements with expressions in
Expression-level normalisation, for constant expressions.
non-constant expression to force a failure |
Rlc : expression transformations
Copyright ( C ) 2006 Haeleth
This program is free software ; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation ; either version 2 of the License , or ( at your option ) any later
version .
This program is distributed in the hope that it will be useful , but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple
Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
Rlc: expression transformations
Copyright (C) 2006 Haeleth
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
*)
pp ./pa_matches.cmo
open Printf
open KeTypes
open KeAst
open ExtList
type 'inferred transform_aux_struct =
{ get_id: unit -> int;
tempvars: (int, assignable) Hashtbl.t;
pre_code: (int * 'inferred) DynArray.t;
mutable redef_store: assignable option;
contains_store: bool Lazy.t }
let make_transform_aux e =
{ get_id = (let i = ref 0 in fun () -> incr i; !i);
tempvars = Hashtbl.create 0;
pre_code = DynArray.create ();
redef_store = None;
contains_store = lazy (exists_in_expr is_store e); }
let prec : arith_op -> int =
Actual precedences in RealLive bytecode
function
| `Add | `Sub -> 10
| `Mul | `Div | `Mod | `And | `Or | `Xor | `Shl | `Shr -> 20
let apply_arith a b : arith_op -> int32 =
function
| `Add -> Int32.add a b | `Sub -> Int32.sub a b | `Mul -> Int32.mul a b | `Div -> Int32.div a b
| `Mod -> Int32.rem a b | `And -> Int32.logand a b | `Or -> Int32.logor a b | `Xor -> Int32.logxor a b
| `Shl -> Int32.shift_left a (Int32.to_int b) | `Shr -> Int32.shift_right a (Int32.to_int b)
let apply_unary i : unary_op -> int32 =
function
| `Sub -> Int32.neg i
| `Not -> if i = 0l then 1l else 0l
| `Inv -> Int32.logxor i Int32.minus_one
let apply_cond a b op =
let c = match op with
`Equ -> a = b | `Neq -> a <> b | `Ltn -> a < b | `Lte -> a <= b | `Gtn -> a > b | `Gte -> a >= b
in
if c then 1l else 0l
let reverse_cond : boolean_op -> boolean_op =
function
| `Equ -> `Neq
| `Neq -> `Equ
| `Ltn -> `Gte
| `Lte -> `Gtn
| `Gtn -> `Lte
| `Gte -> `Ltn
let expr_disambiguate =
function
| `VarOrFn (loc, s, t)
-> if not (Memory.defined t) then
if Intrinsic.is_builtin t then
Intrinsic.eval_as_expr (loc, s, t, [], None)
else try
ignore (ver_fun "" (Hashtbl.find_all functions t));
`Func (loc, s, t, [], None)
with Not_found ->
TODO : do we want to look for variables here too ?
ksprintf (error loc) "undeclared identifier `%s'" s
else
Memory.get_as_expression ~loc ~s t
| `Deref (loc, s, t, offset)
-> if not (Memory.defined t) then
ksprintf (error loc)
(if Intrinsic.is_builtin t || Hashtbl.mem functions t
then format_of_string "`%s' is not an array"
else format_of_string "undeclared identifier `%s'") s
else
Memory.get_deref_as_expression ~loc ~s t offset
| `Func (loc, s, t, parms, label)
-> assert (Memory.defined t || Intrinsic.is_builtin t);
assert (label == None);
if Memory.defined t then
let mf =
function
| `Simple (_, e) -> e
| `Complex (l, _)
| `Special (l, _, _) -> error l "expected expression as parameter to inline expansion"
in
Memory.get_as_expression ~loc ~s t ~args:(List.map mf parms)
else
Intrinsic.eval_as_expr (loc, s, t, parms, None)
let map_func_param f aux =
function
| `Simple (l, e) -> `Simple (l, f aux e)
| `Complex (l, p) -> `Complex (l, List.map (f aux) p)
| `Special (l, i, p) -> `Special (l, i, List.map (f aux) p)
let map_sel_param f aux =
function
| `Always (l, e) -> `Always (l, f aux e)
| `Special (l, cl, e)
-> let g =
function
| `Flag _ as flag -> flag
| `NonCond (l, s, t, e) -> `NonCond (l, s, t, f aux e)
| `Cond (l, s, t, p, e) -> `Cond (l, s, t, Option.map (f aux) p, f aux e)
in
`Special (l, List.map g cl, f aux e)
let rec unary_to_logop l =
function
| `LogOp (l, a, op, b) -> `LogOp (l, a, reverse_cond op, b)
| `Unary (l, `Not, e) -> conditional_unit e
| e -> `LogOp (l, e, `Equ, `Int (nowhere, 0l))
and conditional_unit =
function
| (`LogOp _ | `AndOr _) as c -> c
| `Parens (l, c) -> `Parens (l, conditional_unit c)
| (`VarOrFn (_, _, t) | `Deref (_, _, t, _) | `Func (_, _, t, _, None)) as fc
when Memory.defined t || Intrinsic.is_builtin t -> conditional_unit (expr_disambiguate fc)
| c -> `LogOp (loc_of_expr c, c, `Neq, `Int (nowhere, 0l))
let rec equal_branch =
function
| `Int (_, i), `Int (_, j) -> i = j
| `Store _, `Store _ -> true
| `Op (_, a, o, b), `Op (_, c, p, d) -> o = p && equal_branch (a, c) && equal_branch (b, d)
| `LogOp (_, a, o, b), `LogOp (_, c, p, d) -> o = p && equal_branch (a, c) && equal_branch (b, d)
| `AndOr (_, a, o, b), `AndOr (_, c, p, d) -> o = p && equal_branch (a, c) && equal_branch (b, d)
| `Unary (_, o, i), `Unary (_, p, j) -> o = p && equal_branch (i, j)
| `IVar (_, i, a), `IVar (_, j, b)
| `SVar (_, i, a), `SVar (_, j, b) -> i = j && equal_branch (a, b)
| `Parens (_, a), b | a, `Parens (_, b) -> equal_branch (a, b)
| _ -> false
let rec type_of_traversed =
function
| `Int _ | `IVar _ | `Store _ | `ExFunc _ -> `Int
| `IStr _ | `Res _ | `SVar _ | `SChain _ -> `Str
| `FuncCall (_, e, _, _, _, _)
| `Parens (_, e)
| `Unary (_, _, e)
| `Op (_, e, _, _)
| `LogOp (_, e, _, _)
| `AndOr (_, e, _, _) -> type_of_traversed e
| `Func (l, s, _, _, _) -> ksprintf (error l) "`%s' is not a function valid in expressions" s
let loc_of_traversed =
function
| `Int (l, _) | `IVar (l, _, _) | `Store l | `ExFunc (l, _)
| `IStr (l, _) | `Res (l, _) | `SVar (l, _, _) | `SChain (l, _)
| `FuncCall (l, _, _, _, _, _)
| `Unary (l, _, _)
| `Op (l, _, _, _)
| `LogOp (l, _, _, _)
| `AndOr (l, _, _, _)
| `Parens (l, _) -> l
| `Func (l, s, _, _, _) -> ksprintf (error l) "`%s' is not a function valid in expressions" s
Utilities for generated code
let last_store_ref { pre_code = c } =
let rec loop n =
if n < 0 then None
else match DynArray.get c n with
| _, `FuncCall (_, `Store _, _, _, _, _)
| _, `Select (_, `Store _, _, _, _, _) -> Some n
| _ -> loop (n - 1)
in
loop (DynArray.length c - 1)
let add_store_func aux last_ref loc rv =
begin match last_ref with
| None -> if Lazy.force aux.contains_store then
let ti = Memory.get_temp_int () in
assert (aux.redef_store = None);
aux.redef_store <- Some ti
| Some n ->
let tv = Memory.get_temp_int () in
match DynArray.get aux.pre_code n with
| id, `FuncCall (l, `Store _, s, t, p, lbl)
-> Hashtbl.replace aux.tempvars id tv;
DynArray.set aux.pre_code n (id, `FuncCall (l, tv, s, t, p, lbl))
| id, `Select (l, `Store _, s, i, w, p)
-> Hashtbl.replace aux.tempvars id tv;
DynArray.set aux.pre_code n (id, `Select (l, tv, s, i, w, p))
| _ -> assert false
end;
let id = aux.get_id () in
DynArray.add aux.pre_code (id, rv);
Hashtbl.add aux.tempvars id (`Store Memory.temploc);
`ExFunc (loc, id)
let add_int_of_conditional { pre_code = c } cond =
let tv = Memory.get_temp_int ()
and lb = Codegen.unique_label nowhere in
DynArray.add c (-1, `Assign (nowhere, tv, `Set, `Int (nowhere, 0l)));
DynArray.add c (-1, `ProcCall (nowhere, "goto_unless", Text.ident "goto_unless", [`Simple (nowhere, cond)], Some lb));
DynArray.add c (-1, `Assign (nowhere, tv, `Set, `Int (nowhere, 1l)));
DynArray.add c (-1, `Label lb);
tv
let rec transform ?(as_cond = false) ~reject e =
let aux = make_transform_aux e in
let e = traverse aux (if as_cond then conditional_unit e else e) ~as_cond ~reject in
e, aux
and traverse ?(as_cond = false) ?(keep_unknown_funcs = false) ~reject aux =
function
| `Int (l, i)
-> if reject = `Int then error l "type mismatch: integer in string expression"; `Int (l, i)
| `Store l
-> if reject = `Int then error l "type mismatch: integer in string expression"; `Store l
| `Str (l, s)
-> if reject = `Str then error l "type mismatch: string constant in integer expression";
`IStr (l, traverse_str_tokens aux s)
| `Res (l, t)
-> if reject = `Str then error l "type mismatch: #res<> in integer expression";
let t, l = Global.get_resource l (Text.to_err t, t) in
traverse aux (`Str (l, t)) ~as_cond ~keep_unknown_funcs ~reject
| `Parens (l, e)
->(match traverse aux e ~as_cond ~reject with
| (`Store _ | `IStr _ | `Int _ | `IVar _ | `SVar _ | `ExFunc _) as atom -> atom
| `Parens (_, e) | e -> if reject = `Int then e else `Parens (l, e))
| `SVar (l, i, e)
-> if reject = `Str then error l "type mismatch: string variable in integer expression";
`SVar (l, i, traverse aux e ~reject:`Str)
| `IVar (l, i, e)
-> if reject = `Int then error l "type mismatch: integer variable in string expression";
`IVar (l, i, traverse aux e ~reject:`Str)
Disambiguate identifiers
| (`Deref _ | `VarOrFn _) as vof
-> traverse aux (expr_disambiguate vof) ~reject
| `Func (l, s, t, parms, label as f) as fc
if Memory.defined t || Intrinsic.is_builtin t
then traverse aux (expr_disambiguate fc) ~reject
else traverse_func aux f ~reject ~keep_unknown_funcs
| `SelFunc f
-> traverse_select aux f ~reject
Fold constants ( for trivial cases only - we do n't simplify things like " 1 + x + 1 " )
| `Op (l, a, op, b)
->(let simple_a = traverse aux a ~reject in
if type_of_traversed simple_a = `Int then
Integer operations
let simple_b = traverse aux b ~reject:`Str in
match op, simple_a, simple_b with
| (`Div | `Mod), _, `Int (_, 0l) -> error l "division by zero"
Eliminate meaningless operations
| `And, e, `Int (_, -1l) | `And, `Int (_, -1l), e
| (`Or | `Xor), e, `Int (_, 0l) | (`Or | `Xor), `Int (_, 0l), e
| (`Add | `Sub), e, `Int (_, 0l) | `Add, `Int (_, 0l), e
| (`Mul | `Div), e, `Int (_, 1l) | `Mul, `Int (_, 1l), e -> e
| (`And | `Mul), _, `Int (_, 0l) | (`And | `Mul | `Div | `Mod), `Int (_, 0l), _ -> `Int (l, 0l)
| (`And | `Or), i, j when equal_branch (i, j) -> i
| (`Sub | `Xor | `Mod), i, j when equal_branch (i, j) -> `Int (l, 0l)
| `Div, i, j when equal_branch (i, j) -> `Int (l, 1l)
| _, `Int (_, i), `Int (_, j) -> `Int (l, apply_arith i j op)
| `Add, _, `Int (lb, i) when i < 0l -> `Op (l, simple_a, `Sub, `Int (lb, Int32.neg i))
| `Sub, _, `Int (lb, i) when i < 0l -> `Op (l, simple_a, `Add, `Int (lb, Int32.neg i))
| `Add, _, `Unary (_, `Sub, i) -> `Op (l, simple_a, `Sub, i)
| `Sub, _, `Unary (_, `Sub, i) -> `Op (l, simple_a, `Add, i)
| (`Div | `Mul), `Unary (_, `Sub, i), `Unary (_, `Sub, j) -> `Op (l, i, op, j)
| _ -> let a =
match simple_a with
| `Op (_, _, aop, _) when prec aop < prec op -> `Parens (l, simple_a)
| _ -> simple_a
and b =
match simple_b with
| `Op (_, _, bop, _) when prec bop <= prec op -> `Parens (l, simple_b)
| _ -> simple_b
in
`Op (l, a, op, b)
else
let simple_b = traverse aux b ~reject:`Int in
if op <> `Add then ksprintf (error l) "invalid operator `%s' in string expression" (string_of_op op);
match simple_a, simple_b with
| `IStr (_, i), `IStr (_, j) -> let n = DynArray.copy i in DynArray.append j n; `IStr (l, n)
| `IStr (_, i), e | e, `IStr (_, i) when DynArray.length i = 0 -> e
| `SChain (l, a), `SChain (_, b) -> `SChain (l, a @ b)
| a, `SChain (_, b) -> `SChain (loc_of_traversed a, a :: b)
| `SChain (l, a), b -> `SChain (l, a @ [b])
| a, b -> `SChain (loc_of_traversed a, [a; b])
| `Unary (l, op, e)
->(if reject = `Int then ksprintf (error l) "invalid operator `%s' in string expression" (string_of_op op);
match op, traverse aux e ~reject:`Str with
| _, `Int (_, i) -> `Int (l, apply_unary i op)
| _, `Unary (_, op', e) when op' = op -> e
| `Sub, e
-> let e = if (e matches `Op _) then `Parens (l, e) else e in
`Unary (l, `Sub, e)
| `Inv, e
-> let e =
match e with
| `Op (_, _, op, _) when prec op < prec `Xor -> `Parens (l, e)
| _ -> e
in
`Op (l, e, `Xor, `Int (nowhere, -1l))
| `Not, `Unary (_, `Sub, e)
| `Not, e -> let rv = `LogOp (l, e, `Equ, `Int (nowhere, 0l)) in
if as_cond then rv else add_int_of_conditional aux rv
| `LogOp (l, a, op, b)
->(if reject = `Int then ksprintf (error l) "invalid operator `%s' in string expression" (string_of_op op);
let simple_b = traverse aux b ~reject:`None in
if type_of_traversed simple_b = `Int then
let simple_a = traverse aux a ~reject:`Str in
match op, simple_a, simple_b with
| _, `Int (_, i), `Int (_, j) -> `Int (l, apply_cond i j op)
| (`Equ | `Gte | `Lte), i, j when equal_branch (i, j) -> `Int (l, 1l)
| (`Neq | `Gtn | `Ltn), i, j when equal_branch (i, j) -> `Int (l, 0l)
| _ -> let rv = `LogOp (l, simple_a, op, simple_b) in
if as_cond then rv else add_int_of_conditional aux rv
else
let simple_a = traverse aux a ~reject:`Int in
let v =
add_store_func aux (last_store_ref aux) nowhere
(`FuncCall (nowhere, `Store nowhere, "strcmp", Text.ident "strcmp",
[`Simple (nowhere, simple_a); `Simple (nowhere, simple_b)], None))
in
if op = `Neq && not as_cond then
v
else
let rv = `LogOp (l, v, op, `Int (nowhere, 0l)) in
if as_cond then rv else add_int_of_conditional aux rv
end of ` LogOp
| `AndOr (l, a, op, b)
->(if reject = `Int then ksprintf (error l) "invalid operator `%s' in string expression" (string_of_op op);
let simple_a = traverse aux (conditional_unit a) ~as_cond:true ~reject:`Str in
let simple_b = traverse aux (conditional_unit b) ~as_cond:true ~reject:`Str in
let return rv =
match rv with
| `LogOp _ | `AndOr _ when not as_cond -> add_int_of_conditional aux rv
| _ -> rv
in
match op, simple_a, simple_b with
| `LAnd, `Int (_, i), `Int (_, j) -> if i <> 0l && j <> 0l then `Int (l, 1l) else `Int (l, 0l)
| `LAnd, e, `Int (_, i) | `LAnd, `Int (_, i), e when i <> 0l -> return e
| `LAnd, e, `Int (_, i) | `LAnd, `Int (_, i), e when i = 0l -> `Int (l, 0l)
| `LOr, `Int (_, i), `Int (_, j) -> if i <> 0l || j <> 0l then `Int (l, 1l) else `Int (l, 0l)
| `LOr, e, `Int (_, i) | `LOr, `Int (_, i), e when i = 0l -> return e
| `LOr, e, `Int (_, i) | `LOr, `Int (_, i), e when i <> 0l -> `Int (l, 1l)
| _, i, j when equal_branch (i, j) -> return i
It appears that & & and || have equal precedence . This should fix the
discrepancy with Kepago , I hope .
discrepancy with Kepago, I hope. *)
let a =
match simple_a with
| `AndOr (_, _, `LAnd, _) when op = `LOr -> `Parens (l, simple_a)
| _ -> simple_a
and b =
match simple_b with
| `AndOr _ when op = `LOr -> `Parens (l, simple_b)
| _ -> simple_b
in
return (`AndOr (l, a, op, b))
| `ExprSeq (l, id, defs, smts)
if DynArray.empty smts then ksprintf (error l) "inline block `%s' expands to empty sequence: this is invalid in expressions" (Text.to_sjs id);
let last = DynArray.last smts in
DynArray.delete_last smts;
assert (Memory.defined id);
let sym = Memory.pull_sym id in
Memory.open_scope ();
Memory.define (Text.ident "__INLINE_CALL__") (`Macro (`Int (nowhere, 1l))) ~scoped:true;
Memory.define (Text.ident "__CALLER_FILE__") (`Macro (`Str (nowhere, Global.dynArray (`Text (nowhere, `Sbcs, Text.of_err l.file))))) ~scoped:true;
Memory.define (Text.ident "__CALLER_LINE__") (`Macro (`Int (nowhere, Int32.of_int l.line))) ~scoped:true;
List.iter (fun (i, e) -> Memory.define i (`Macro e) ~scoped:true) defs;
Meta.parse smts;
let rv = traverse aux (expr_of_statement last) ~as_cond ~reject ~keep_unknown_funcs in
Memory.close_scope ();
Memory.replace_sym id sym;
rv
and traverse_str_tokens aux tkns =
let rv = DynArray.create () in
DynArray.iter
begin function
| `Code (l, i, e, p) when i = Text.ident "s"
-> if e <> None then KeTypes.error l "length specifier invalid in \\s{}";
let add_str_elt =
function
| `SVar _ as sv -> DynArray.add rv (`Code (l, Text.ident "s", None, [`Simple (l, sv)]))
| `IStr (_, elts) -> DynArray.append elts rv
| _ -> assert false
in
(match List.map (map_func_param (traverse ~reject:`None) aux) p with
| [`Simple (_, `SChain (_, c))] -> List.iter add_str_elt c
| [`Simple (_, (`SVar _ | `IStr _ as elt))] -> add_str_elt elt
| p -> DynArray.add rv (`Code (l, i, None, p)))
| `Code (l, i, e, p)
-> let args = List.map (map_func_param (traverse ~reject:`None) aux) p in
if i = Text.ident "i"
&& Option.default true (Option.map normalised_expr_is_const e)
&& (args matches [`Simple (_, `Int (_, v))]) then
let s =
Text.of_sjs
(Global.int32_to_string_padded
(Int32.to_int (Option.default 0l (Option.map int_of_normalised_expr e)))
(match args with [`Simple (_, `Int (_, v))] -> v | _ -> assert false))
in
DynArray.add rv (`Text (l, `Sbcs, s))
else
DynArray.add rv (`Code (l, i, Option.map (traverse aux ~reject:`Str) e, args))
| `Gloss (l, g, s, r)
-> let rl, rs =
match r with
| `Closed rl_rs -> rl_rs
| `ResStr (kl, k) -> let a, b = Global.get_resource kl (Text.to_sjs k, k) in b, a
in
DynArray.add rv (`Gloss (l, g, traverse_str_tokens aux s, `Closed (rl, traverse_str_tokens aux rs)))
| `Name (l, lg, e, w)
-> DynArray.add rv (`Name (l, lg, traverse aux e ~reject:`Str, Option.map (traverse aux ~reject:`Str) w))
| #strtoken_non_expr as e -> DynArray.add rv e
end
tkns;
rv
and traverse_func ~keep_unknown_funcs ~reject aux (l, s, t, p, label) =
if Intrinsic.is_builtin t then error l "internal error: intrinsic call reached Expr.traverse_func";
match
try
Some (ver_fun "" (Hashtbl.find_all functions t))
with Not_found ->
if keep_unknown_funcs
then None
else ksprintf (error l) "unable to find an appropriate definition for the function `%s'" s
with
| None -> `Func (l, s, t, List.map (map_func_param (traverse ~reject:`None) aux) p, label)
| Some f ->
let argc = List.length p + if List.mem KfnTypes.PushStore f.flags then 0 else 1 in
let overload = FuncAsm.choose_overload l f argc in
let prototype = f.prototypes.(overload) in
let return_as =
try
match
List.find
(fun (_, pattrs) -> List.mem KfnTypes.Return pattrs)
(Option.get prototype)
with
| KfnTypes.Int, _
-> if reject = `Int
then ksprintf (error l) "type mismatch: function `%s' returns an integer, but is here used in a string expression" s
else `Int
| KfnTypes.Str, _
-> if reject = `Str
then ksprintf (error l) "type mismatch: function `%s' returns a string, but is here used in an integer expression" s
else `Str
| _ -> ksprintf Optpp.sysError "error in reallive.kfn: invalid return type for function `%s'" s
with _ ->
if List.mem KfnTypes.PushStore f.flags
then `Store
else ksprintf (error l) "function `%s' has no return value: it cannot be used in expressions" s
in
let last_ref = last_store_ref aux in
let as_cond = List.mem KfnTypes.IsCond f.flags in
let p =
if as_cond
then List.map (function `Simple (l, e) -> `Simple (l, conditional_unit e) | x -> x) p
else p
in
let p = List.map (map_func_param (traverse ~keep_unknown_funcs:true ~reject:`None ~as_cond) aux) p in
match return_as with
| `Store
-> add_store_func aux last_ref l (`FuncCall (l, `Store nowhere, s, t, p, label))
| `Int
-> let id = aux.get_id () in
let tv, rv =
if last_ref = None && not (Lazy.force aux.contains_store) then
(Hashtbl.add aux.tempvars id (`Store Memory.temploc);
`Store Memory.temploc, `ExFunc (l, id))
else
let tv = Memory.get_temp_int () in
tv, tv
in
DynArray.add aux.pre_code (id, `FuncCall (l, tv, s, t, p, label));
rv
| `Str
-> let tv = Memory.get_temp_str () in
DynArray.add aux.pre_code (-1, `FuncCall (l, tv, s, t, p, label));
tv
and traverse_select ~reject aux (l, s, i, w, p) =
if reject = `Int then
ksprintf (error l) "type mismatch: function `%s' returns an integer, but is here used in a string expression" s;
let last_ref = last_store_ref aux in
let w = Option.map (traverse aux ~reject:`Str) w
and p =
List.map
(function
| `Always (ll, e)
-> `Always (ll, traverse aux e ~reject:`Int)
| `Special (ll, cl, e)
-> let f =
function
| `Flag _ as flag -> flag
| `NonCond (l, s, t, e)
-> `NonCond (l, s, t, traverse aux e ~reject:`Str)
| `Cond (l, s, t, e, c)
-> `Cond (l, s, t, Option.map (traverse aux ~reject:`Str) e,
traverse aux (conditional_unit c) ~reject:`Str ~as_cond:true)
in
`Special (ll, List.map f cl, traverse aux e ~reject:`Int))
p
in
add_store_func aux last_ref l (`Select (l, `Store nowhere, s, i, w, p))
let rec finalise aux : 'inferred -> expression =
function
| `Store _ as s -> (match aux.redef_store with Some tempvar -> (tempvar :> expression) | None -> s)
| `IStr (l, s) -> `Str (l, DynArray.map (finalise_str_tokens aux) s)
| `Int _ as i -> (i :> expression)
| `IVar (l, i, e) -> `IVar (l, i, finalise aux e)
| `SVar (l, i, e) -> `SVar (l, i, finalise aux e)
| `Parens (l, e) -> `Parens (l, finalise aux e)
| `Unary (l, op, e) -> `Unary (l, op, finalise aux e)
| `Op (l, a, op, b) -> `Op (l, finalise aux a, op, finalise aux b)
| `LogOp (l, a, op, b) -> `LogOp (l, finalise aux a, op, finalise aux b)
| `AndOr (l, a, op, b) -> `AndOr (l, finalise aux a, op, finalise aux b)
| `Func (l, s, t, p, d) -> `Func (l, s, t, List.map (map_func_param finalise aux) p, d)
| `ExFunc (_, id) -> (try (Hashtbl.find aux.tempvars id :> expression) with _ -> assert false)
| `SChain (l, chain)
-> let s = DynArray.create () in
List.iter
(function
| `IStr (_, t) -> DynArray.append (DynArray.map (finalise_str_tokens aux) t) s
| `SVar (l, i, e)
-> DynArray.add s (`Code (l, Text.of_sjs "s", None, [`Simple (l, `SVar (l, i, finalise aux e))]));
| _ -> error l "expected string")
chain;
`Str (l, s)
and finalise_str_tokens aux =
function
| `Code (l, i, e, p) -> `Code (l, i, Option.map (finalise aux) e, List.map (map_func_param finalise aux) p)
| `Gloss (l, g, s, `Closed (cl, r)) -> `Gloss (l, g, DynArray.map (finalise_str_tokens aux) s, `Closed (cl, DynArray.map (finalise_str_tokens aux) r))
| `Gloss (_, _, _, `ResStr _) -> assert false
| `Name (l, lg, e, cidx) -> `Name (l, lg, finalise aux e, Option.map (finalise aux) cidx)
| #strtoken_non_expr as e -> e
let finalise_generated_code aux (_, s) : statement =
match s with
| `Assign (l, d, op, e) -> `Assign (l, d, op, finalise aux e)
| `ProcCall (l, s, t, p, lbl) -> `FuncCall (l, None, s, t, List.map (map_func_param finalise aux) p, lbl)
| `FuncCall (l, d, s, t, p, lbl) -> `FuncCall (l, Some d, s, t, List.map (map_func_param finalise aux) p, lbl)
| `Select (l, d, s, i, w, p) -> `Select (l, d, s, i, Option.map (finalise aux) w, List.map (map_sel_param finalise aux) p)
| (`Label _) as a -> a
Function taking a potentially complex assignment statement and returning a list of statements
representing valid RealLive code
representing valid RealLive code *)
let normalise_assignment (`Assign (loc, dest, op, e): assignment) =
let dest, is_int, reject =
let rec disambiguate =
function
| `Store _ as elt -> elt, true, `Str
| `IVar _ as elt -> elt, true, `Str
| `SVar _ as elt -> elt, false, `Int
| `Func (l, s, t, p, d) when Intrinsic.is_builtin t -> disambiguate (Intrinsic.eval_as_expr (l, s, t, p, d))
| `Deref (l, s, t, offset)
-> disambiguate
(try Memory.get_deref_as_expression ~loc:l ~s t offset with Not_found ->
ksprintf (error l) "undeclared identifier `%s'" s)
| `VarOrFn (l, s, t)
-> disambiguate
(if Intrinsic.is_builtin t then
Intrinsic.eval_as_expr (l, s, t, [], None)
else try
if not (Intrinsic.is_builtin t) then ignore (ver_fun "" (Hashtbl.find_all functions t));
ksprintf (error l) "function `%s' is not valid as the left-hand side of an assignment" s
with Not_found ->
try Memory.get_as_expression t with Not_found ->
ksprintf (error l) "undeclared identifier `%s'" s)
| _ -> error loc "the left-hand side of an assignment must be a variable or memory reference"
in
disambiguate (dest :> expression)
in
let e, aux = transform e ~reject in
let dest = traverse aux dest ~reject in
let e = match finalise aux e with `Parens (_, e) | e -> e in
let dest =
match finalise aux dest with
| #assignable as a -> a
| _ -> error loc "internal error: LHS normalised to non-assignable"
in
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
let result =
if is_int then
match e, try DynArray.last d with _ -> `Null with
| `Store _, `Assign (_, `Store _, `Set, expr)
-> `Replace (`Assign (loc, dest, op, expr))
| `Store _, `FuncCall (l, Some (`Store _), s, t, p, lbl)
when op = `Set
-> `Replace (`FuncCall (l, Some dest, s, t, p, lbl))
| `Store _, `Select (l, `Store _, s, i, w, p)
when op = `Set
-> `Replace (`Select (l, dest, s, i, w, p))
| `Store _, _
when op = `Set && is_store dest
-> `Neither
| _
when op = `Set && equal_branch (e, dest)
-> `Neither
| _
-> match e with
| `Op (_, a, op, b) when equal_branch (a, dest) -> `Append (`Assign (loc, dest, (op :> assign_op), b))
| _ -> `Append (`Assign (loc, dest, op, e))
else
match e, try DynArray.last d with _ -> `Null with
| `SVar (sl1, _, _), `FuncCall (l, Some (`SVar (sl2, _, _)), s, t, p, lbl)
when op = `Set && sl1 = Memory.temploc && sl1 = sl2
-> `Replace (`FuncCall (l, Some dest, s, t, p, lbl))
| _
-> let dest = match dest with `SVar _ as sv -> (sv :> expression) | _ -> assert false in
let e, op =
match e with
| `Str (loc, text) when DynArray.length text > 1
-> let tempvar = ref None in
let f =
function
| `Simple (l, e) when equal_exprs e dest
-> let v =
match !tempvar with
| Some v -> v
| None -> let v = Memory.get_temp_str () ~useloc:l in
tempvar := Some v;
v
in `Simple (l, v)
| p -> p
in
let g =
function
| `Code (l, s, o, parms) -> `Code (l, s, o, List.map f parms)
| elt -> elt
in
let chop =
if op = `Set
&& (match DynArray.get text 0 with `Code (_, _, _, [`Simple (_, e)]) -> equal_exprs e dest | _ -> false)
then (DynArray.delete text 0; true)
else false
in
let ntext = DynArray.map g text in
(match !tempvar with
| None -> ()
| Some v -> DynArray.insert d 0
(`FuncCall (loc, None, "strcpy", Text.ident "strcpy",
[`Simple (loc, v); `Simple (loc, dest)], None)));
`Str (loc, ntext), if chop then `Add else op
| _ -> e, op
in
if op = `Set then
if equal_branch (dest, e)
then `Neither
else `Append (`FuncCall (loc, None, "strcpy", Text.ident "strcpy", [`Simple (loc, dest); `Simple (loc, e)], None))
else if op = `Add then
`Append (`FuncCall (loc, None, "strcat", Text.ident "strcat", [`Simple (loc, dest); `Simple (loc, e)], None))
else
ksprintf (error loc) "assignment operator `%s' is not valid for strings" (string_of_assign_op op)
in
match result with
| `Replace smt -> DynArray.set d (DynArray.length d - 1) smt; d
| `Append smt -> DynArray.add d smt; d
| `Neither -> d
let normalise_funccall (`FuncCall (loc, dest, s_ident, t_ident, params, label)) =
assert (dest matches None | Some (`Store _));
let aux = make_transform_aux (`Func (loc, s_ident, t_ident, params, label)) in
let as_cond =
try
List.mem KfnTypes.IsCond (ver_fun "" (Hashtbl.find_all functions t_ident)).flags
with Not_found ->
false
in
let p =
if as_cond
then List.map (function `Simple (l, e) -> `Simple (l, conditional_unit e) | x -> x) params
else params
in
let p = List.map (map_func_param (traverse ~keep_unknown_funcs:true ~reject:`None ~as_cond) aux) p in
DynArray.add aux.pre_code (-1, `ProcCall (loc, s_ident, t_ident, p, label));
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
d
let normalise_unknown (`UnknownOp (loc, fn, overload, params)) =
let aux =
{ (make_transform_aux (`Store nowhere))
with
contains_store = lazy (exists_in_expr is_store (`Func (loc, fn.ident, Text.of_arr [||], params, None))) }
in
let p = List.map (map_func_param (traverse ~keep_unknown_funcs:true ~reject:`None) aux) params in
let p = List.map (map_func_param finalise aux) p in
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
DynArray.add d (`UnknownOp (loc, fn, overload, p));
d
let normalise_select (`Select (loc, dest, s_ident, opcode, window, params)) =
let aux = make_transform_aux (`SelFunc (loc, s_ident, opcode, window, params)) in
let w = Option.map (traverse aux ~reject:`Str) window
and p =
List.map
(function
| `Always (ll, e)
-> `Always (ll, traverse aux e ~reject:`Int)
| `Special (ll, cl, e)
-> let f =
function
| `Flag _ as flag -> flag
| `NonCond (l, s, t, e) -> `NonCond (l, s, t, traverse aux e ~reject:`Str)
| `Cond (l, s, t, e, c) -> `Cond (l, s, t, Option.map (traverse aux ~reject:`Str) e,
traverse aux (conditional_unit c) ~reject:`Str ~as_cond:true)
in
`Special (ll, List.map f cl, traverse aux e ~reject:`Int))
params
in
DynArray.add aux.pre_code (-1, `Select (loc, dest, s_ident, opcode, w, p));
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
d
As normalise_assignment , but for calls
let normalise_gotocase (`GotoCase (loc, jump_type, e, cases)) =
let aux =
let all_exprs = e :: List.filter_map (function `Default _ -> None | `Match (e, _) -> Some e) cases in
{ (make_transform_aux (`Store nowhere))
with
contains_store = lazy (List.exists (exists_in_expr is_store) all_exprs) }
in
let e = traverse aux e ~reject:`Str in
let cases =
List.map
(function
| `Default _ as d -> d
| `Match (e, l) -> `Match (traverse aux e ~reject:`Str, l))
cases
in
let e = match finalise aux e with `Parens (_, e) | e -> e in
let cases =
List.map
(function
| `Default _ as d -> d
| `Match (e, l) -> `Match ((match finalise aux e with `Parens (_, e) | e -> e), l))
cases
in
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
DynArray.add d (`GotoCase (loc, jump_type, e, cases));
d
let normalise_nonassignment s =
let e, aux =
match s with
| `GotoOn (_, _, e, _) -> transform e ~reject:`Str
| `Return (_, _, e) -> transform e ~reject:`None
| `LoadFile (_, e) -> transform e ~reject:`Int
| `Directive (_, _, tp, e) -> transform e ~reject:(if tp = `Str then `Int else if tp = `Int then `Str else `None);
| `DConst (_, _, _, _, e) -> transform e ~reject:`None
in
let e = match finalise aux e with `Parens (_, e) | e -> e in
let d = DynArray.map (finalise_generated_code aux) aux.pre_code in
Option.may (fun ti -> DynArray.insert d 0 (`Assign (nowhere, ti, `Set, `Store nowhere))) aux.redef_store;
DynArray.add d
begin match s with
| `GotoOn (l, jt, _, lb) -> `GotoOn (l, jt, e, lb)
| `Return (l, b, _) -> `Return (l, b, e)
| `LoadFile (l, _) -> `LoadFile (l, e)
| `Directive (l, s, tp, _) -> `Directive (l, s, tp, e)
| `DConst (l, s, t, tp, _) -> `Define (l, s, t, tp = `Bind, e)
end;
d
Generic normalisation : takes any statement and returns a normalised form .
NOTE : If normalisation was performed , a new scope is opened but NOT
closed ; the caller must close it when finished .
NOTE: If normalisation was performed, a new scope is opened but NOT
closed; the caller must close it when finished. *)
let normalise =
let call f e =
Memory.open_scope ();
let m = f e in
if DynArray.length m = 0
then (Memory.close_scope (); `Nothing)
else `Multiple m
in
function
| #assignment as a -> call normalise_assignment a
| `FuncCall (_, (None | Some (`Store _)), _, _, _, _) as p -> call normalise_funccall p
| `FuncCall (l, Some rv, s, t, p, d) -> call normalise_assignment (`Assign (l, rv, `Set, `Func (l, s, t, p, d)))
| `UnknownOp _ as u -> call normalise_unknown u
| `GotoCase _ as g -> call normalise_gotocase g
| `Select _ as s -> call normalise_select s
| `DConst (_, _, _, (`Bind | `EBind), _)
| #normalisable as n -> call normalise_nonassignment n
| #statement as elt -> `Single elt
let normalise_and_get_const ?(abort_on_fail = true) ?(expect = `None) e =
let pre_len = DynArray.length Codegen.Output.bytecode in
let e, aux = transform e ~reject:`None in
let e =
if DynArray.length aux.pre_code <> 0 then fail else finalise aux e
in
let e =
if DynArray.length Codegen.Output.bytecode > pre_len then (
DynArray.delete_range Codegen.Output.bytecode pre_len (DynArray.length Codegen.Output.bytecode - pre_len);
fail
) else e
in
const_of_normalised_expr e ~expect ~abort_on_fail
let normalise_and_get_int ?(abort_on_fail = true) e =
match normalise_and_get_const e ~expect:`Int ~abort_on_fail with
| `Integer i -> i
| _ -> assert false
let normalise_and_get_str ?(abort_on_fail = true) e =
match normalise_and_get_const e ~expect:`Str ~abort_on_fail with
| `String s -> s
| _ -> assert false
|
6c7c6e383f8be3e7834874a8bdb0187d24358097e4ba39806141f3e38f53f35b | robrix/sequoia | Implicative.hs | {-# LANGUAGE ConstraintKinds #-}
module Sequoia.Calculus.Implicative
* rules
ImplicativeIntro
, funLSub
, subLFun
-- * Re-exports
, module Sequoia.Calculus.Function
, module Sequoia.Calculus.Subtraction
) where
import Prelude hiding (init)
import Sequoia.Calculus.Context
import Sequoia.Calculus.Core
import Sequoia.Calculus.Function
import Sequoia.Calculus.Structural
import Sequoia.Calculus.Subtraction
import Sequoia.Polarity
type ImplicativeIntro s = (FunctionIntro s, SubtractionIntro s)
funLSub
:: (Weaken s, Exchange s, FunctionIntro s, SubtractionIntro s, Pos a, Neg b)
=> _Γ ⊣s e r⊢ _Δ > b >-Sub r-~ a
-- -----------------------------------------------
-> a ~~Fun r~> b < _Γ ⊣s e r⊢ _Δ
funLSub s = wkL s >>> subL (exL (init ->⊢ init))
subLFun
:: (Weaken s, Exchange s, FunctionIntro s, SubtractionIntro s, Pos a, Neg b)
=> _Γ ⊣s e r⊢ _Δ > a ~~Fun r~> b
-- -----------------------------------------------
-> b >-Sub r-~ a < _Γ ⊣s e r⊢ _Δ
subLFun s = wkL s >>> subL (wkR init) ->⊢ exL (subL (wkL init))
| null | https://raw.githubusercontent.com/robrix/sequoia/e4fae1100fa977a656f2fc654762f23d4448ad76/src/Sequoia/Calculus/Implicative.hs | haskell | # LANGUAGE ConstraintKinds #
* Re-exports
-----------------------------------------------
----------------------------------------------- | module Sequoia.Calculus.Implicative
* rules
ImplicativeIntro
, funLSub
, subLFun
, module Sequoia.Calculus.Function
, module Sequoia.Calculus.Subtraction
) where
import Prelude hiding (init)
import Sequoia.Calculus.Context
import Sequoia.Calculus.Core
import Sequoia.Calculus.Function
import Sequoia.Calculus.Structural
import Sequoia.Calculus.Subtraction
import Sequoia.Polarity
type ImplicativeIntro s = (FunctionIntro s, SubtractionIntro s)
funLSub
:: (Weaken s, Exchange s, FunctionIntro s, SubtractionIntro s, Pos a, Neg b)
=> _Γ ⊣s e r⊢ _Δ > b >-Sub r-~ a
-> a ~~Fun r~> b < _Γ ⊣s e r⊢ _Δ
funLSub s = wkL s >>> subL (exL (init ->⊢ init))
subLFun
:: (Weaken s, Exchange s, FunctionIntro s, SubtractionIntro s, Pos a, Neg b)
=> _Γ ⊣s e r⊢ _Δ > a ~~Fun r~> b
-> b >-Sub r-~ a < _Γ ⊣s e r⊢ _Δ
subLFun s = wkL s >>> subL (wkR init) ->⊢ exL (subL (wkL init))
|
a5b4fea2ef3f098e71e1456f048c59ed28dae2841da4c1f2451f6fb120873725 | cuplv/dai | daig.mli | open Dai.Import
open Domain
open Frontend
open Syntax
module type Sig = sig
type absstate
* names are opaque from outside a DAIG , except for comparison , hashing , and sexp utilities ( for use in hashsets / maps )
module Name : sig
type t [@@deriving compare, hash, sexp_of]
val pp : t pp
end
module Ref : sig
type t =
| Stmt of { mutable stmt : Ast.Stmt.t; name : Name.t }
| AState of { mutable state : absstate option; name : Name.t }
[@@deriving sexp_of, equal, compare]
val name : t -> Name.t
val hash : t -> int
val pp : t pp
end
module Comp : sig
type t = [ `Transfer | `Join | `Widen | `Fix | `Transfer_after_fix of Cfg.Loc.t ]
[@@deriving compare, equal, hash, sexp_of]
val pp : t pp
val to_string : t -> string
end
module Opaque_ref : module type of struct
include Regular.Std.Opaque.Make (Ref)
type t = Ref.t
end
module G : module type of Graph.Make (Opaque_ref) (Comp)
type t = G.t
val of_cfg : entry_state:absstate -> cfg:Cfg.t -> fn:Cfg.Fn.t -> t
* Construct a DAIG for a procedure with body [ cfg ] and metadata [ fn ] , with [ init_state ] at the procedure entry
val apply_edit :
daig:t -> cfg_edit:Tree_diff.cfg_edit_result -> fn:Cfg.Fn.t -> Tree_diff.edit -> t
(** apply the specified [Tree_diff.edit] to the input [daig]; [cfg_edit] and [fn] are passed as additional information needed for certain types of edit *)
val dirty : Name.t -> t -> t
(** dirty all dependencies of some name (including that name itself) *)
val dump_dot : filename:string -> ?loc_labeller:(Cfg.Loc.t -> string option) -> t -> unit
* dump a DOT representation of a DAIG to [ filename ] , decorating abstract - state cells according to [ loc_labeller ] if provided
val is_solved : Cfg.Loc.t -> t -> bool
(** true iff an abstract state is available at the given location *)
type 'a or_summary_query =
| Result of 'a
| Summ_qry of { callsite : Ast.Stmt.t; caller_state : absstate }
* sum type representing the possible cases when a query is issued to a DAIG :
( case 1 : Result ) the result is available or can be computed with no new method summaries
( case 2 : Summ_qry ) additional method summaries are needed to evaluate some [ callsite ] in [ caller_state ]
(case 1: Result) the result is available or can be computed with no new method summaries
(case 2: Summ_qry) additional method summaries are needed to evaluate some [callsite] in [caller_state]
*)
type summarizer = callsite:Ast.Stmt.t * Name.t -> absstate -> absstate option
exception Ref_not_found of [ `By_loc of Cfg.Loc.t | `By_name of Name.t ]
val get_by_loc : ?summarizer:summarizer -> Cfg.Loc.t -> t -> absstate or_summary_query * t
val get_by_name : ?summarizer:summarizer -> Name.t -> t -> absstate or_summary_query * t
(** GET functions attempt to compute the requested value, analyzing its backward dependencies *)
val read_by_loc : Cfg.Loc.t -> t -> absstate option
val read_by_name : Name.t -> t -> absstate option
(** READ functions return the current contents of the requested cell, performing no analysis computation*)
val write_by_name : Name.t -> absstate -> t -> t
(** WRITE functions write the given [absstate] to the cell named by the given [Name.t], dirtying any forward dependencies *)
val pred_state_exn : Name.t -> t -> absstate
* returns the predecessor absstate of the cell named by the given [ Name.t ] , if there is exactly one
val assert_wf : t -> unit
val total_astate_refs : t -> int
val nonempty_astate_refs : t -> int
end
module Make (Dom : Abstract.Dom) : Sig with type absstate := Dom.t
| null | https://raw.githubusercontent.com/cuplv/dai/b2bdb518ad6e7893b96aa2dd60b42b2ae6dd14ad/src/analysis/daig.mli | ocaml | * apply the specified [Tree_diff.edit] to the input [daig]; [cfg_edit] and [fn] are passed as additional information needed for certain types of edit
* dirty all dependencies of some name (including that name itself)
* true iff an abstract state is available at the given location
* GET functions attempt to compute the requested value, analyzing its backward dependencies
* READ functions return the current contents of the requested cell, performing no analysis computation
* WRITE functions write the given [absstate] to the cell named by the given [Name.t], dirtying any forward dependencies | open Dai.Import
open Domain
open Frontend
open Syntax
module type Sig = sig
type absstate
* names are opaque from outside a DAIG , except for comparison , hashing , and sexp utilities ( for use in hashsets / maps )
module Name : sig
type t [@@deriving compare, hash, sexp_of]
val pp : t pp
end
module Ref : sig
type t =
| Stmt of { mutable stmt : Ast.Stmt.t; name : Name.t }
| AState of { mutable state : absstate option; name : Name.t }
[@@deriving sexp_of, equal, compare]
val name : t -> Name.t
val hash : t -> int
val pp : t pp
end
module Comp : sig
type t = [ `Transfer | `Join | `Widen | `Fix | `Transfer_after_fix of Cfg.Loc.t ]
[@@deriving compare, equal, hash, sexp_of]
val pp : t pp
val to_string : t -> string
end
module Opaque_ref : module type of struct
include Regular.Std.Opaque.Make (Ref)
type t = Ref.t
end
module G : module type of Graph.Make (Opaque_ref) (Comp)
type t = G.t
val of_cfg : entry_state:absstate -> cfg:Cfg.t -> fn:Cfg.Fn.t -> t
* Construct a DAIG for a procedure with body [ cfg ] and metadata [ fn ] , with [ init_state ] at the procedure entry
val apply_edit :
daig:t -> cfg_edit:Tree_diff.cfg_edit_result -> fn:Cfg.Fn.t -> Tree_diff.edit -> t
val dirty : Name.t -> t -> t
val dump_dot : filename:string -> ?loc_labeller:(Cfg.Loc.t -> string option) -> t -> unit
* dump a DOT representation of a DAIG to [ filename ] , decorating abstract - state cells according to [ loc_labeller ] if provided
val is_solved : Cfg.Loc.t -> t -> bool
type 'a or_summary_query =
| Result of 'a
| Summ_qry of { callsite : Ast.Stmt.t; caller_state : absstate }
* sum type representing the possible cases when a query is issued to a DAIG :
( case 1 : Result ) the result is available or can be computed with no new method summaries
( case 2 : Summ_qry ) additional method summaries are needed to evaluate some [ callsite ] in [ caller_state ]
(case 1: Result) the result is available or can be computed with no new method summaries
(case 2: Summ_qry) additional method summaries are needed to evaluate some [callsite] in [caller_state]
*)
type summarizer = callsite:Ast.Stmt.t * Name.t -> absstate -> absstate option
exception Ref_not_found of [ `By_loc of Cfg.Loc.t | `By_name of Name.t ]
val get_by_loc : ?summarizer:summarizer -> Cfg.Loc.t -> t -> absstate or_summary_query * t
val get_by_name : ?summarizer:summarizer -> Name.t -> t -> absstate or_summary_query * t
val read_by_loc : Cfg.Loc.t -> t -> absstate option
val read_by_name : Name.t -> t -> absstate option
val write_by_name : Name.t -> absstate -> t -> t
val pred_state_exn : Name.t -> t -> absstate
* returns the predecessor absstate of the cell named by the given [ Name.t ] , if there is exactly one
val assert_wf : t -> unit
val total_astate_refs : t -> int
val nonempty_astate_refs : t -> int
end
module Make (Dom : Abstract.Dom) : Sig with type absstate := Dom.t
|
5c557383af2741d6d9c760ca7d0764241f2f28b92946f2bd291e3e3fdb4d56cc | mzp/coq-ide-for-ios | ideutils.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
val read_stdout : unit -> string
val flash_info : ?delay:int -> string -> unit
checks if two file names refer to the same ( existing ) file
checks if two file names refer to the same (existing) file
*)
val same_file : string -> string -> bool
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/ide/ideutils.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
val read_stdout : unit -> string
val flash_info : ?delay:int -> string -> unit
checks if two file names refer to the same ( existing ) file
checks if two file names refer to the same (existing) file
*)
val same_file : string -> string -> bool
|
29b00cc457a6307654b4394cf3152523d8a3fba9a0907dbf9a664de385c990f9 | clojuredus/clojure-coding-dojo | specs.clj | (ns tiny-maze.specs
(:require [clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as stest]))
;; From our gilded-rose kata, just for orientation and base functions
;; (s/def ::item-name string?)
;; (s/def ::sell-in integer?)
;; (s/def ::quality integer?)
;; (s/def ::item (s/keys :req-un [::item-name ::sell-in ::quality]))
;; (s/fdef gilded-rose.core/item
;; :args (s/cat :name string? :sell-in integer? :quality integer?)
: ret : : item )
;; (stest/instrument 'gilded-rose.core/item)
;; (s/exercise-fn `gilded-rose.core/item)
( stest / abbrev - result ( first ( stest / check ` gilded-rose.core/item ) ) )
| null | https://raw.githubusercontent.com/clojuredus/clojure-coding-dojo/21a60a3a4be825544b9a07eb7cd9c9c83a112b01/tiny-maze/src/tiny_maze/specs.clj | clojure | From our gilded-rose kata, just for orientation and base functions
(s/def ::item-name string?)
(s/def ::sell-in integer?)
(s/def ::quality integer?)
(s/def ::item (s/keys :req-un [::item-name ::sell-in ::quality]))
(s/fdef gilded-rose.core/item
:args (s/cat :name string? :sell-in integer? :quality integer?)
(stest/instrument 'gilded-rose.core/item)
(s/exercise-fn `gilded-rose.core/item) | (ns tiny-maze.specs
(:require [clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as stest]))
: ret : : item )
( stest / abbrev - result ( first ( stest / check ` gilded-rose.core/item ) ) )
|
8d5a1b3eb13870b5cd27fb24122944e4b8db31d5600ea036be0f24da0c4acc69 | tnelson/Forge | forge_ex.rkt | #lang forge
sig Node {edges: set Node}
pred isUndirectedTree {
(Node->Node) in *(edges + ~edges)
edges in ~edges
not (some iden & edges)
all n1, n2: Node | (n1 in n2.edges implies n1 not in n2.^(edges - (n2->n1)))
}
-- Now defined in forge_ex_test.rkt
--udt: run isUndirectedTree for 7 Node | null | https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/amalgam/tests/forge_ex.rkt | racket | #lang forge
sig Node {edges: set Node}
pred isUndirectedTree {
(Node->Node) in *(edges + ~edges)
edges in ~edges
not (some iden & edges)
all n1, n2: Node | (n1 in n2.edges implies n1 not in n2.^(edges - (n2->n1)))
}
-- Now defined in forge_ex_test.rkt
--udt: run isUndirectedTree for 7 Node | |
df133e7cb39d036987a793b0c8af273a25479032167652aa5437362d0f546715 | lisp/de.setf.resource | wilbur-mediator.lisp | -*- Mode : lisp ; Syntax : ansi - common - lisp ; Base : 10 ; Package : de.setf.resource.implementation ; -*-
(in-package :de.setf.resource.implementation)
(:documentation
"This file defines tests for the wilbur interface for the `de.setf.resource` Common Lisp library."
(copyright
"Copyright 2010 [james anderson](mailto:) All Rights Reserved"
"'de.setf.resource' is free software: you can redistribute it and/or modify it under the terms of version 3
of the GNU Affero General Public License as published by the Free Software Foundation.
'de.setf.resource' 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 Affero General Public License for more details.
A copy of the GNU Affero General Public License should be included with 'de.setf.resource' as `agpl.txt`.
If not, see the GNU [site](/)."))
;;; (test:execute-test :resource.wilbur-mediator.**)
(test:test resource.wilbur-mediator.class
(let ((mediator (make-instance 'wilbur-mediator)))
(and (typep mediator 'rdf:repository-mediator)
(eq (mediator-repository mediator) (wilbur-db)))))
(test:test resource.wilbur-mediator.delete-object
"verify object enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(uri (de.setf.rdf:uri p))
(m (object-repository p)))
(setf (property-value p 'height) 100)
(dolist (s (de.setf.rdf:query m :subject uri)) (de.setf.rdf:delete-statement m s))
(de.setf.rdf:project-graph p m)
(and (de.setf.rdf:has-object? m "name")
(de.setf.rdf:has-object? m 1)
(de.setf.rdf:has-object? m 100)
(progn (de.setf.rdf:delete-object m "name")
(de.setf.rdf:delete-object m 1)
(de.setf.rdf:delete-object m 100)
(not (de.setf.rdf:has-object? m "name"))
(not (de.setf.rdf:has-object? m 1))
(not (de.setf.rdf:has-object? m 100))))))
(test:test resource.wilbur-mediator.delete-predicate
"verify subject enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(uri (de.setf.rdf:uri p))
(m (object-repository p)))
(setf (property-value p 'height) 100)
(dolist (s (de.setf.rdf:query m :subject uri)) (de.setf.rdf:delete-statement m s))
(de.setf.rdf:project-graph p m)
(and (de.setf.rdf:has-predicate? m '{foaf}firstName)
(de.setf.rdf:has-predicate? m '{foaf}age)
(de.setf.rdf:has-predicate? m 'height)
(progn (de.setf.rdf:delete-predicate m '{foaf}firstName)
(de.setf.rdf:delete-predicate m '{foaf}age)
(de.setf.rdf:delete-predicate m 'height)
(not (de.setf.rdf:has-predicate? m '{foaf}firstName))
(not (de.setf.rdf:has-predicate? m '{foaf}age))
(not (de.setf.rdf:has-predicate? m 'height))))))
(test:test resource.wilbur-mediator.delete-subject
"verify subject enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(uri (de.setf.rdf:uri p))
(m (object-repository p)))
(setf (property-value p 'height) 100)
(dolist (s (de.setf.rdf:query m :subject uri)) (de.setf.rdf:delete-statement m s))
(de.setf.rdf:project-graph p m)
(and (de.setf.rdf:has-subject? m p)
(progn (de.setf.rdf:delete-subject m uri)
(not (de.setf.rdf:has-subject? m uri))))))
(test:test resource.wilbur-mediator.delete-statement
(let ((m (repository-mediator 'wilbur-mediator))
(s (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object"))))
;; ensure the triple is not there
(dolist (s (wilbur:db-query (mediator-repository m)
(wilbur:triple-subject s)
(wilbur:triple-predicate s)
(wilbur:triple-object s)))
(de.setf.rdf:delete-statement m s))
;; then add/delete it and test existence
(de.setf.rdf:insert-statement m s)
(and (de.setf.rdf:has-statement? m s)
(progn (de.setf.rdf:delete-statement m s)
(null (de.setf.rdf:has-statement? m s))))))
(test:test resource.wilbur-mediator.find-instance
"Verify instance registration in the class' mediator. Remove and verify removal."
(let* ((instance (de.setf.rdf:ensure-instance 'resource '{}self))
(mediator (object-repository instance)))
(and (typep instance 'resource-object)
(eq instance (de.setf.rdf:find-instance 'resource '{}self))
(eq instance (de.setf.rdf:find-instance mediator '{}self))
(de.setf.rdf:equal instance '{}self)
(null (de.setf.rdf:find-instance mediator '{}self_2))
(null (setf (de.setf.rdf:find-instance instance '{}self) nil))
(null (de.setf.rdf:find-instance mediator '{}self)))))
(test:test resource.wilbur-mediator.has-statement
(let ((m (repository-mediator 'wilbur-mediator))
(s (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object"))))
;; ensure the triple is not there
(dolist (s (wilbur:db-query (mediator-repository m)
(wilbur:triple-subject s)
(wilbur:triple-predicate s)
(wilbur:triple-object s)))
(de.setf.rdf:delete-statement m s))
;; then add/delete it and test existence
(de.setf.rdf:insert-statement m s)
(and (de.setf.rdf:has-statement? m s)
(progn (de.setf.rdf:delete-statement m s)
(null (de.setf.rdf:has-statement? m s))))))
(test:test resource.wilbur-mediator.has-subject
"verify subject enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(s (object-repository p)))
(setf (property-value p 'height) 100)
(de.setf.rdf:project-graph p s)
(and (de.setf.rdf:has-subject? s p)
(de.setf.rdf:has-subject? s (de.setf.rdf:uri p))
(de.setf.rdf:has-subject? s (wilbur:node (uri-namestring (de.setf.rdf:uri p)))))))
(test:test resource.wilbur-mediator.has-object
"verify object enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(s (object-repository p)))
(setf (property-value p 'height) 100)
(de.setf.rdf:project-graph p s)
(and (de.setf.rdf:has-object? s "name")
(de.setf.rdf:has-object? s 1)
(de.setf.rdf:has-object? s 100))))
(test:test resource.wilbur-mediator.has-predicate
"verify predicate enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(s (object-repository p)))
(setf (property-value p 'height) 100)
(de.setf.rdf:project-graph p s)
(and (de.setf.rdf:has-predicate? s '{foaf}firstName)
(de.setf.rdf:has-predicate? s '{foaf}age)
(de.setf.rdf:has-predicate? s 'height))))
(test:test resource.wilbur-mediator.literal.1
(let ((source (make-instance 'wilbur-mediator)))
(every #'(lambda (v) (equal v (de.setf.rdf:model-value source (de.setf.rdf:repository-value source v))))
'(1 "1" 1.0s0 1.0d0))))
(test:test resource.wilbur-mediator.literal.2
(let ((source (make-instance 'wilbur-mediator)))
(equal (mapcar #'(lambda (v) (wilbur:literal-datatype (de.setf.rdf:repository-value source v)))
'(1 "1" 1.0s0 1.0d0))
'(|xsd|:|integer| |xsd|:|string| |xsd|:|float| |xsd|:|double|))))
(test:test resource.wilbur-mediator.statement.1
"When placing a native triple, either the context must be provided, or the search must use a wild context."
(let* ((m (repository-mediator 'wilbur-mediator))
(new (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object")
(repository-value m (mediator-default-context m)))))
(wilbur:add-triple new)
(let ((found (first (de.setf.rdf:query m :subject '{rdf}subject :predicate '{rdf}predicate :object '{rdf}object))))
(and found
(eq (de.setf.rdf:subject new) (de.setf.rdf:subject found))
(eq (de.setf.rdf:predicate new) (de.setf.rdf:predicate found))
(eq (de.setf.rdf:object new) (de.setf.rdf:object found))))))
(test:test resource.wilbur-mediator.statement.2
"When placing a native triple, either the context must be provided, or the search must use a wild context."
(let* ((m (repository-mediator 'wilbur-mediator))
(new (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object"))))
(wilbur:add-triple new)
(let ((found (first (de.setf.rdf:query m :subject '{rdf}subject :predicate '{rdf}predicate :object '{rdf}object
:context nil))))
(and found
(eq (de.setf.rdf:subject new) (de.setf.rdf:subject found))
(eq (de.setf.rdf:predicate new) (de.setf.rdf:predicate found))
(eq (de.setf.rdf:object new) (de.setf.rdf:object found))))))
(test:test resource.wilbur-mediator.statement.namestring
(de.setf.rdf:namestring (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object"))))
(test:test resource.wilbur-mediator.triple
(let ((s (wilbur:triple 1 "2" |xsd|:|string|)))
(and (eq (wilbur:triple-subject s) (de.setf.rdf:subject s))
(eq (wilbur:triple-predicate s) (de.setf.rdf:predicate s))
(eq (wilbur:triple-object s) (de.setf.rdf:object s))
(eq (first (wilbur:triple-sources s)) (de.setf.rdf:context s)))))
| null | https://raw.githubusercontent.com/lisp/de.setf.resource/27bf6dfb3b3ca99cfd5a6feaa5839d99bfb4d29e/test/wilbur-mediator.lisp | lisp | Syntax : ansi - common - lisp ; Base : 10 ; Package : de.setf.resource.implementation ; -*-
without even the
(test:execute-test :resource.wilbur-mediator.**)
ensure the triple is not there
then add/delete it and test existence
ensure the triple is not there
then add/delete it and test existence |
(in-package :de.setf.resource.implementation)
(:documentation
"This file defines tests for the wilbur interface for the `de.setf.resource` Common Lisp library."
(copyright
"Copyright 2010 [james anderson](mailto:) All Rights Reserved"
"'de.setf.resource' is free software: you can redistribute it and/or modify it under the terms of version 3
of the GNU Affero General Public License as published by the Free Software Foundation.
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the Affero General Public License for more details.
A copy of the GNU Affero General Public License should be included with 'de.setf.resource' as `agpl.txt`.
If not, see the GNU [site](/)."))
(test:test resource.wilbur-mediator.class
(let ((mediator (make-instance 'wilbur-mediator)))
(and (typep mediator 'rdf:repository-mediator)
(eq (mediator-repository mediator) (wilbur-db)))))
(test:test resource.wilbur-mediator.delete-object
"verify object enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(uri (de.setf.rdf:uri p))
(m (object-repository p)))
(setf (property-value p 'height) 100)
(dolist (s (de.setf.rdf:query m :subject uri)) (de.setf.rdf:delete-statement m s))
(de.setf.rdf:project-graph p m)
(and (de.setf.rdf:has-object? m "name")
(de.setf.rdf:has-object? m 1)
(de.setf.rdf:has-object? m 100)
(progn (de.setf.rdf:delete-object m "name")
(de.setf.rdf:delete-object m 1)
(de.setf.rdf:delete-object m 100)
(not (de.setf.rdf:has-object? m "name"))
(not (de.setf.rdf:has-object? m 1))
(not (de.setf.rdf:has-object? m 100))))))
(test:test resource.wilbur-mediator.delete-predicate
"verify subject enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(uri (de.setf.rdf:uri p))
(m (object-repository p)))
(setf (property-value p 'height) 100)
(dolist (s (de.setf.rdf:query m :subject uri)) (de.setf.rdf:delete-statement m s))
(de.setf.rdf:project-graph p m)
(and (de.setf.rdf:has-predicate? m '{foaf}firstName)
(de.setf.rdf:has-predicate? m '{foaf}age)
(de.setf.rdf:has-predicate? m 'height)
(progn (de.setf.rdf:delete-predicate m '{foaf}firstName)
(de.setf.rdf:delete-predicate m '{foaf}age)
(de.setf.rdf:delete-predicate m 'height)
(not (de.setf.rdf:has-predicate? m '{foaf}firstName))
(not (de.setf.rdf:has-predicate? m '{foaf}age))
(not (de.setf.rdf:has-predicate? m 'height))))))
(test:test resource.wilbur-mediator.delete-subject
"verify subject enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(uri (de.setf.rdf:uri p))
(m (object-repository p)))
(setf (property-value p 'height) 100)
(dolist (s (de.setf.rdf:query m :subject uri)) (de.setf.rdf:delete-statement m s))
(de.setf.rdf:project-graph p m)
(and (de.setf.rdf:has-subject? m p)
(progn (de.setf.rdf:delete-subject m uri)
(not (de.setf.rdf:has-subject? m uri))))))
(test:test resource.wilbur-mediator.delete-statement
(let ((m (repository-mediator 'wilbur-mediator))
(s (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object"))))
(dolist (s (wilbur:db-query (mediator-repository m)
(wilbur:triple-subject s)
(wilbur:triple-predicate s)
(wilbur:triple-object s)))
(de.setf.rdf:delete-statement m s))
(de.setf.rdf:insert-statement m s)
(and (de.setf.rdf:has-statement? m s)
(progn (de.setf.rdf:delete-statement m s)
(null (de.setf.rdf:has-statement? m s))))))
(test:test resource.wilbur-mediator.find-instance
"Verify instance registration in the class' mediator. Remove and verify removal."
(let* ((instance (de.setf.rdf:ensure-instance 'resource '{}self))
(mediator (object-repository instance)))
(and (typep instance 'resource-object)
(eq instance (de.setf.rdf:find-instance 'resource '{}self))
(eq instance (de.setf.rdf:find-instance mediator '{}self))
(de.setf.rdf:equal instance '{}self)
(null (de.setf.rdf:find-instance mediator '{}self_2))
(null (setf (de.setf.rdf:find-instance instance '{}self) nil))
(null (de.setf.rdf:find-instance mediator '{}self)))))
(test:test resource.wilbur-mediator.has-statement
(let ((m (repository-mediator 'wilbur-mediator))
(s (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object"))))
(dolist (s (wilbur:db-query (mediator-repository m)
(wilbur:triple-subject s)
(wilbur:triple-predicate s)
(wilbur:triple-object s)))
(de.setf.rdf:delete-statement m s))
(de.setf.rdf:insert-statement m s)
(and (de.setf.rdf:has-statement? m s)
(progn (de.setf.rdf:delete-statement m s)
(null (de.setf.rdf:has-statement? m s))))))
(test:test resource.wilbur-mediator.has-subject
"verify subject enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(s (object-repository p)))
(setf (property-value p 'height) 100)
(de.setf.rdf:project-graph p s)
(and (de.setf.rdf:has-subject? s p)
(de.setf.rdf:has-subject? s (de.setf.rdf:uri p))
(de.setf.rdf:has-subject? s (wilbur:node (uri-namestring (de.setf.rdf:uri p)))))))
(test:test resource.wilbur-mediator.has-object
"verify object enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(s (object-repository p)))
(setf (property-value p 'height) 100)
(de.setf.rdf:project-graph p s)
(and (de.setf.rdf:has-object? s "name")
(de.setf.rdf:has-object? s 1)
(de.setf.rdf:has-object? s 100))))
(test:test resource.wilbur-mediator.has-predicate
"verify predicate enquiry of a wilbur repository for intrinsic slots and augmentation with a property."
(let* ((p (make-instance 'person :name "name" :age 1 :parents nil))
(s (object-repository p)))
(setf (property-value p 'height) 100)
(de.setf.rdf:project-graph p s)
(and (de.setf.rdf:has-predicate? s '{foaf}firstName)
(de.setf.rdf:has-predicate? s '{foaf}age)
(de.setf.rdf:has-predicate? s 'height))))
(test:test resource.wilbur-mediator.literal.1
(let ((source (make-instance 'wilbur-mediator)))
(every #'(lambda (v) (equal v (de.setf.rdf:model-value source (de.setf.rdf:repository-value source v))))
'(1 "1" 1.0s0 1.0d0))))
(test:test resource.wilbur-mediator.literal.2
(let ((source (make-instance 'wilbur-mediator)))
(equal (mapcar #'(lambda (v) (wilbur:literal-datatype (de.setf.rdf:repository-value source v)))
'(1 "1" 1.0s0 1.0d0))
'(|xsd|:|integer| |xsd|:|string| |xsd|:|float| |xsd|:|double|))))
(test:test resource.wilbur-mediator.statement.1
"When placing a native triple, either the context must be provided, or the search must use a wild context."
(let* ((m (repository-mediator 'wilbur-mediator))
(new (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object")
(repository-value m (mediator-default-context m)))))
(wilbur:add-triple new)
(let ((found (first (de.setf.rdf:query m :subject '{rdf}subject :predicate '{rdf}predicate :object '{rdf}object))))
(and found
(eq (de.setf.rdf:subject new) (de.setf.rdf:subject found))
(eq (de.setf.rdf:predicate new) (de.setf.rdf:predicate found))
(eq (de.setf.rdf:object new) (de.setf.rdf:object found))))))
(test:test resource.wilbur-mediator.statement.2
"When placing a native triple, either the context must be provided, or the search must use a wild context."
(let* ((m (repository-mediator 'wilbur-mediator))
(new (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object"))))
(wilbur:add-triple new)
(let ((found (first (de.setf.rdf:query m :subject '{rdf}subject :predicate '{rdf}predicate :object '{rdf}object
:context nil))))
(and found
(eq (de.setf.rdf:subject new) (de.setf.rdf:subject found))
(eq (de.setf.rdf:predicate new) (de.setf.rdf:predicate found))
(eq (de.setf.rdf:object new) (de.setf.rdf:object found))))))
(test:test resource.wilbur-mediator.statement.namestring
(de.setf.rdf:namestring (wilbur:triple (wilbur:node "-rdf-syntax-ns#subject")
(wilbur:node "-rdf-syntax-ns#predicate")
(wilbur:node "-rdf-syntax-ns#object"))))
(test:test resource.wilbur-mediator.triple
(let ((s (wilbur:triple 1 "2" |xsd|:|string|)))
(and (eq (wilbur:triple-subject s) (de.setf.rdf:subject s))
(eq (wilbur:triple-predicate s) (de.setf.rdf:predicate s))
(eq (wilbur:triple-object s) (de.setf.rdf:object s))
(eq (first (wilbur:triple-sources s)) (de.setf.rdf:context s)))))
|
bc565fad32e2c0b2097e90e77d0a45d402a6248ea4dbb14573a7aa82159643fa | metrics-clojure/metrics-clojure | core.clj | (ns metrics.health.core
(:require [clojure.set :as set]
[metrics.core :refer [default-registry metric-name]]
[metrics.utils :refer [desugared-title]])
(:import clojure.lang.IFn
[com.codahale.metrics MetricRegistry Gauge]
[com.codahale.metrics.health HealthCheck HealthCheck$Result HealthCheckRegistry]))
(def ^{:tag HealthCheckRegistry :doc "Default health check registry used by public API functions when no explicit registry argument is given"}
default-healthcheck-registry
(HealthCheckRegistry.))
(defn healthy
"Returns a healthy result."
([] (HealthCheck$Result/healthy))
([^String message & args]
(HealthCheck$Result/healthy (apply format message args))))
(defn unhealthy
"Returns a unhealthy result."
([^String message & args]
(HealthCheck$Result/unhealthy ^String (apply format message args))))
(defn new-hc
"Wrap a fn to ensure it returns healthy/unhealthy. Any exception or
non-healthy result is considered unhealthy and returned as such."
([^IFn hc-fn] (proxy [HealthCheck] []
(check []
(let [result (hc-fn)]
(if (instance? HealthCheck$Result result)
result
(unhealthy (str "Bad HealthCheck result: " result))))))))
(defn healthcheck-fn
"Create and register a new healthcheck. hc-fn must return
healthy/unhealthy; any other result, (including an exception), will
be considered unhealthy."
([title ^IFn hc-fn]
(healthcheck-fn default-healthcheck-registry title hc-fn))
([^HealthCheckRegistry reg title ^IFn hc-fn]
(let [hc (new-hc hc-fn)
s (metric-name title)]
;; REVIEW: Should this automatically remove a previous check of
the same title ? ( jw 14 - 08 - 28 )
(.register reg s hc)
hc)))
(defmacro defhealthcheck
"Define a new Healthcheck metric with the given title and a function.
to call to retrieve the value of the Healthcheck.
The title uses some basic desugaring to let you concisely define metrics:
; Define a healthcheck titled \"default.default.foo\" into var foo
(defhealthcheck foo ,,,)
(defhealthcheck \"foo\" ,,,)
; Define a healthcheck titled \"a.b.c\" into var c
(defhealthcheck [a b c] ,,,)
(defhealthcheck [\"a\" \"b\" \"c\"] ,,,)
(defhealthcheck [a \"b\" c] ,,,)
"
([title ^clojure.lang.IFn f]
(let [[s title] (desugared-title title)]
`(def ~s (healthcheck-fn '~title ~f))))
([^HealthCheckRegistry reg title ^clojure.lang.IFn f]
(let [[s title] (desugared-title title)]
`(def ~s (healthcheck-fn ~reg '~title ~f)))))
(defn check
"Run a given HealthCheck."
[^HealthCheck h]
(.execute h))
(defn check-all
"Returns a map with the keys :healthy & :unhealthy, each containing
the associated checks. Note that the items of each vector are of
type
java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry,
but key & val work on it."
([] (check-all default-healthcheck-registry))
([^HealthCheckRegistry reg]
(let [results (.runHealthChecks reg)
group-results (group-by #(.isHealthy ^HealthCheck$Result (val %)) results)]
(set/rename-keys group-results {true :healthy false :unhealthy}))))
| null | https://raw.githubusercontent.com/metrics-clojure/metrics-clojure/a1dbacc748a1f8165f0094e2229c84f228efe29b/metrics-clojure-health/src/metrics/health/core.clj | clojure | any other result, (including an exception), will
REVIEW: Should this automatically remove a previous check of
Define a healthcheck titled \"default.default.foo\" into var foo
Define a healthcheck titled \"a.b.c\" into var c | (ns metrics.health.core
(:require [clojure.set :as set]
[metrics.core :refer [default-registry metric-name]]
[metrics.utils :refer [desugared-title]])
(:import clojure.lang.IFn
[com.codahale.metrics MetricRegistry Gauge]
[com.codahale.metrics.health HealthCheck HealthCheck$Result HealthCheckRegistry]))
(def ^{:tag HealthCheckRegistry :doc "Default health check registry used by public API functions when no explicit registry argument is given"}
default-healthcheck-registry
(HealthCheckRegistry.))
(defn healthy
"Returns a healthy result."
([] (HealthCheck$Result/healthy))
([^String message & args]
(HealthCheck$Result/healthy (apply format message args))))
(defn unhealthy
"Returns a unhealthy result."
([^String message & args]
(HealthCheck$Result/unhealthy ^String (apply format message args))))
(defn new-hc
"Wrap a fn to ensure it returns healthy/unhealthy. Any exception or
non-healthy result is considered unhealthy and returned as such."
([^IFn hc-fn] (proxy [HealthCheck] []
(check []
(let [result (hc-fn)]
(if (instance? HealthCheck$Result result)
result
(unhealthy (str "Bad HealthCheck result: " result))))))))
(defn healthcheck-fn
"Create and register a new healthcheck. hc-fn must return
be considered unhealthy."
([title ^IFn hc-fn]
(healthcheck-fn default-healthcheck-registry title hc-fn))
([^HealthCheckRegistry reg title ^IFn hc-fn]
(let [hc (new-hc hc-fn)
s (metric-name title)]
the same title ? ( jw 14 - 08 - 28 )
(.register reg s hc)
hc)))
(defmacro defhealthcheck
"Define a new Healthcheck metric with the given title and a function.
to call to retrieve the value of the Healthcheck.
The title uses some basic desugaring to let you concisely define metrics:
(defhealthcheck foo ,,,)
(defhealthcheck \"foo\" ,,,)
(defhealthcheck [a b c] ,,,)
(defhealthcheck [\"a\" \"b\" \"c\"] ,,,)
(defhealthcheck [a \"b\" c] ,,,)
"
([title ^clojure.lang.IFn f]
(let [[s title] (desugared-title title)]
`(def ~s (healthcheck-fn '~title ~f))))
([^HealthCheckRegistry reg title ^clojure.lang.IFn f]
(let [[s title] (desugared-title title)]
`(def ~s (healthcheck-fn ~reg '~title ~f)))))
(defn check
"Run a given HealthCheck."
[^HealthCheck h]
(.execute h))
(defn check-all
"Returns a map with the keys :healthy & :unhealthy, each containing
the associated checks. Note that the items of each vector are of
type
java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry,
but key & val work on it."
([] (check-all default-healthcheck-registry))
([^HealthCheckRegistry reg]
(let [results (.runHealthChecks reg)
group-results (group-by #(.isHealthy ^HealthCheck$Result (val %)) results)]
(set/rename-keys group-results {true :healthy false :unhealthy}))))
|
5669d0317c5d66719f3df5ec80475a8a4fef0eab9e0bbedf7bb68e18efead4e5 | cac-t-u-s/om-sharp | collections.lisp | ;============================================================================
; om#: visual programming language for computer-assisted music composition
;============================================================================
;
; This program is free software. For information on usage
; and redistribution, see the "LICENSE" file in this distribution.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
;
;============================================================================
File author :
;============================================================================
(in-package :om)
;;;===========================
;;; COLLECTION = A SET OF OBJECTS OF A SAME TYPE
;;;===========================
(defclass* collection (named-object)
((obj-type :accessor obj-type :initform nil)
(obj-list :initarg :obj-list :accessor obj-list :initform nil))
(:documentation "Container holding a set of several objects of the same type.
Displays/enable editing the list of objects in a single 'collection editor'.
The desired type can be specified as the first input (e.g. typing 'collection BPF').
If this is done, this type is used to initialize or convert the input list of objects (if possible)."
))
(defmethod get-properties-list ((self collection))
'(("COLLECTION attibutes"
(:name "Name" :text name))))
;;; the collection box has same additional attributes as the object it contains (if any)
(defmethod additional-box-attributes ((self collection))
(additional-box-attributes (car (obj-list self))))
(defmethod homogenize-collection (model list) nil)
(defmethod om-init-instance ((self collection) &optional initargs)
(let ((initial-list (loop for item in (list! (obj-list self))
collect (om-init-instance item))))
(setf (obj-list self)
(if (obj-type self)
;;; coerce all object to the specified type
(remove nil
(mapcar
#'(lambda (obj)
(om-init-instance (objfromobjs obj (make-instance (obj-type self)))))
initial-list))
(om-copy initial-list))))
(when (obj-list self)
;;; check if all items are of the same type
(if (list-typep (obj-list self) (type-of (car (obj-list self))))
(progn
(setf (obj-type self) (type-of (car (obj-list self))))
(homogenize-collection (car (obj-list self)) (obj-list self)))
(progn
(om-beep-msg "WARNING: ELEMENTS IN COLLECTION ARE NOT OF THE SAME TYPE!!")
(setf (obj-type self) nil))))
self)
;;;===========================
;;; BOX
;;;===========================
(defmethod object-default-edition-params ((self collection))
(append
'((:show-all t))
(object-default-edition-params (car (obj-list self)))))
(defmethod special-box-p ((name (eql 'collection))) t)
(defmethod special-box-type ((class-name (eql 'collection))) 'CollectionBox)
(defclass MultiCacheBoxEditCall (OMBoxEditCall)
((multi-cache-display :accessor multi-cache-display :initform nil)))
(defclass CollectionBox (MultiCacheBoxEditCall) ())
(defmethod omNG-make-special-box ((reference (eql 'collection)) pos &optional init-args)
(let ((type (and init-args (find-class (car init-args) nil)))
(val (make-instance 'collection)))
(when type (setf (obj-type val) (class-name type)))
(let ((box (omNG-make-new-boxcall (find-class 'collection) pos val)))
(setf (name box) "...")
(setf (value (car (inputs box))) (obj-type val))
box)))
(defmethod objfromobjs ((model symbol) (target collection))
(if (find-class model nil)
(setf (obj-type target) model)
(om-beep-msg "WARNING: class not found for collection: ~S" model))
target)
(defmethod draw-type-of-object ((object collection))
(string+ (string-upcase (type-of object)) " OF " (string-upcase (obj-type object))))
(defmethod get-object-type-name ((object collection))
(and (obj-type object)
(string+ "COLLECTION OF " (string-upcase (obj-type object))
"s (" (number-to-string (length (obj-list object))) ")")))
(defmethod object-box-label ((object collection))
(string+ (string-upcase (type-of object)) " of "
(number-to-string (length (obj-list object))) " "
(if (obj-type object) (string-upcase (obj-type object)) "?")
(if (> (length (obj-list object)) 1) "s" "")
))
(defmethod display-modes-for-object ((self collection)) '(:mini-view :text :hidden))
(defmethod get-cache-display-for-text ((self collection) box)
(declare (ignore box))
(loop for obj in (obj-list self)
for i = 0 then (1+ i)
collect (list (format nil "[~D]" i) obj)))
CollectionBox has a little hack on cache - display to store a different cache for each object
;;; The multi-cache display is a list of list (object cache)
;;; collection boxes create "multi-cache" by calling get-collection-cache-display on internbal objects
(defmethod get-cache-display-for-draw ((object collection) box)
(declare (ignore box))
(unless (multi-cache-display box)
(setf (multi-cache-display box)
(get-collection-cache-display (car (obj-list object)) (obj-list object) box)))
nil)
;;; CAN BE REDEFINED FOR SPECIFIC OBJECTS:
;;; type is an object used for specialization
(defmethod get-collection-cache-display ((type t) list box)
(loop for o in list collect (list o (get-cache-display-for-draw o box))))
(defmethod reset-cache-display ((self CollectionBox))
(setf (multi-cache-display self) nil)
(call-next-method))
(defmethod ensure-cache-display-draw ((box CollectionBox) object)
(if (typep object 'collection)
(call-next-method) ;;; will eventually store some cache
;;; called on elements of the collection:
(progn
(unless (cache-display box) (setf (cache-display box) (make-cache-display)))
(unless (cache-display-draw (cache-display box))
;;; this is just an access in memory: no need to redo the cache
;;; set the general cache to the item in the multi-cache
(setf (cache-display-draw (cache-display box))
(cadr (find object (multi-cache-display box) :key #'car))))
(cache-display-draw (cache-display box)))))
;;; type is an object used for specialization
;;; otherwise, calls draw-mini-view for every object
(defmethod collection-draw-mini-view ((type t) list box x y w h time)
(when list
(let ((ho (/ h (length list))))
(loop for o in list
for yo = y then (+ yo ho) do
(setf (cache-display box) nil)
(draw-mini-view o box x yo w ho time))
)))
(defmethod draw-mini-view ((self collection) (box t) x y w h &optional time)
(ensure-cache-display-draw box self)
(collection-draw-mini-view
(car (obj-list self))
(obj-list self)
box x y w h time))
;;; used for display etc.
(defmethod get-obj-dur ((self collection))
(apply #'max (or (remove nil (mapcar #'get-obj-dur (obj-list self))) '(0))))
(defmethod miniview-time-to-pixel ((object collection) box (view omboxframe) time)
;;; take the longer object as reference
(miniview-time-to-pixel
(reduce #'(lambda (o1 o2) (if (>= (get-obj-dur o1) (get-obj-dur o2)) o1 o2))
(obj-list object))
box view time))
;;;===========================
;;; EDITOR
;;;===========================
(defclass collection-editor (OMEditor undoable-editor-mixin)
((internal-editor :accessor internal-editor :initform nil)
(current :accessor current :initform 0)))
(defmethod object-has-editor ((self collection)) t)
(defmethod get-editor-class ((self collection)) 'collection-editor)
(defmethod object-value ((self collection-editor))
(nth (current self) (obj-list (get-value-for-editor (object self)))))
(defmethod undoable-object ((self collection-editor))
(get-value-for-editor (object self)))
(defmethod get-obj-to-play ((self collection-editor)) (object-value self))
(defmethod editor-play-state ((self collection-editor))
(editor-play-state (internal-editor self)))
(defmethod editor-close ((self collection-editor))
(editor-close (internal-editor self))
(call-next-method))
;;;==================================
;multidisplay API
(defclass multi-display-editor-mixin ()
((multi-display-p :accessor multi-display-p :initarg :multi-display-p :initform nil)
(multi-obj-list :accessor multi-obj-list :initform nil)))
(defmethod handle-multi-display ((self t)) nil)
(defmethod handle-multi-display ((self multi-display-editor-mixin)) t)
(defmethod enable-multi-display ((self t) obj-list) nil)
(defmethod enable-multi-display ((self multi-display-editor-mixin) obj-list)
(setf (multi-display-p self) t
(multi-obj-list self) obj-list))
(defmethod disable-multi-display ((self t)) nil)
(defmethod disable-multi-display ((self multi-display-editor-mixin))
(setf (multi-display-p self) nil)
(setf (multi-obj-list self) nil))
(defmethod update-multi-display ((editor collection-editor) t-or-nil)
(if t-or-nil
(enable-multi-display (internal-editor editor) (obj-list (get-value-for-editor (object editor))))
(disable-multi-display (internal-editor editor)))
(update-to-editor (internal-editor editor) editor)
(editor-invalidate-views (internal-editor editor))
)
;;;==================================
(defmethod init-editor ((editor collection-editor))
(let* ((collection (get-value-for-editor (object editor)))
(current-object (and (obj-type collection) (nth (current editor) (obj-list collection))))
(abs-container (make-instance 'OMAbstractContainer :contents current-object)))
(setf (internal-editor editor)
(make-instance (get-editor-class current-object)
:container-editor editor
:object abs-container))
(setf (edition-params abs-container) (edition-params (object editor)))
;;; will share the same list in principle
(init-editor (internal-editor editor))
))
(defmethod init-editor-window ((editor collection-editor))
(call-next-method)
(init-editor-window (internal-editor editor))
(when (editor-get-edit-param editor :show-all)
(update-multi-display editor t)))
(defmethod make-editor-window-contents ((editor collection-editor))
(let* ((collection (get-value-for-editor (object editor)))
(text (format-current-text editor))
(current-text (let ((font (om-def-font :large-b)))
(om-make-graphic-object
'om-item-text
:size (omp (om-string-size text font) 16)
:text text :font font)))
(prev-button (om-make-graphic-object
'om-icon-button
:size (omp 16 16) :position (omp 0 0)
:icon :l-arrow :icon-pushed :l-arrow-pushed :icon-disabled :l-arrow-disabled
:lock-push nil :enabled (> (length (obj-list collection)) 1)
:action #'(lambda (b)
(declare (ignore b))
(set-current-previous editor)
)))
(next-button (om-make-graphic-object
'om-icon-button
:size (omp 16 16) :position (omp 0 0)
:icon :r-arrow :icon-pushed :r-arrow-pushed :icon-disabled :r-arrow-disabled
:lock-push nil :enabled (> (length (obj-list collection)) 1)
:action #'(lambda (b)
(declare (ignore b))
(set-current-next editor)
)))
(-button (om-make-graphic-object
'om-icon-button
:size (omp 16 16) :position (omp 0 0)
:icon :- :icon-pushed :--pushed :icon-disabled :--disabled
:lock-push nil :enabled (obj-list collection)
:action #'(lambda (b)
(remove-current-object editor)
(let ((coll (get-value-for-editor (object editor))))
(if (obj-list coll)
(update-multi-display editor (editor-get-edit-param editor :show-all))
(button-disable b))
(when (<= (length (obj-list coll)) 1)
(button-disable prev-button) (button-disable next-button))
))
))
(+button (om-make-graphic-object
'om-icon-button
:size (omp 16 16) :position (omp 0 0)
:icon :+ :icon-pushed :+-pushed :icon-disabled :+-disabled
:lock-push nil
:enabled (and (obj-type (get-value-for-editor (object editor)))
(subtypep (obj-type (get-value-for-editor (object editor))) 'standard-object))
:action #'(lambda (b)
(declare (ignore b))
(add-new-object editor)
(let ((coll (get-value-for-editor (object editor))))
(button-enable -button) ;; in case it was disabled..
(when (> (length (obj-list coll)) 1)
(button-enable prev-button) (button-enable next-button)))
(update-multi-display editor (editor-get-edit-param editor :show-all))
)))
(showall-check
(when (handle-multi-display (internal-editor editor))
(om-make-di
'om-check-box
:text " Show All" :size (omp 80 16) :font (om-def-font :gui)
:checked-p (editor-get-edit-param editor :show-all) :focus nil :default nil
:di-action #'(lambda (item)
(editor-set-edit-param editor :show-all (om-checked-p item))
(update-multi-display editor (om-checked-p item)))
)))
)
(set-g-component editor :current-text current-text)
(om-make-layout
'om-column-layout
:ratios '(1 99)
:subviews
(list
(om-make-layout
'om-row-layout
:delta 0
:ratios '(1 1 1 10 1 10 1)
:align :top
:subviews
(list
(om-make-layout
'om-row-layout :delta 0
:subviews
(list (om-make-view 'om-view :size (omp 16 16) :subviews (list prev-button))
(om-make-view 'om-view :size (omp 16 16) :subviews (list next-button)))
)
(om-make-graphic-object 'om-item-view :size (omp 20 20))
showall-check
nil
current-text
nil
(om-make-layout
'om-row-layout :delta 0
:subviews
(list (om-make-view 'om-view :size (omp 16 16) :subviews (list +button))
(om-make-view 'om-view :size (omp 16 16) :subviews (list -button))
))
))
(if (object-value (internal-editor editor))
(setf (main-view (internal-editor editor))
(make-editor-window-contents (internal-editor editor))))
))
))
(defmethod set-window-contents ((editor collection-editor))
(when (window editor)
(om-remove-subviews (window editor) (main-view editor))
(om-add-subviews (window editor)
(setf (main-view editor)
(make-editor-window-contents editor)))
))
;;; when updated from the box (eval)
(defmethod update-to-editor ((editor collection-editor) (from OMBox))
(let ((collection (get-value-for-editor (object editor))))
(when (not (equal (type-of (internal-editor editor)) ;;; the new object has not the same editor
(get-editor-class (nth (current editor) (obj-list collection)))))
;;; need to close/reset the internal editor
(editor-close (internal-editor editor))
(init-editor editor)
(setf (current editor) 0)
(set-window-contents editor)
))
;;; with reset the virtual object for internal-editor
(update-collection-editor editor)
(set-current-text editor)
(update-to-editor (internal-editor editor) from)
(update-multi-display editor (editor-get-edit-param editor :show-all))
(call-next-method)
)
(defmethod format-current-text ((editor collection-editor))
(let ((collection (get-value-for-editor (object editor))))
(if (obj-list collection)
(format nil "Current ~A: ~D/~D" ;; [~A]
(string-upcase (obj-type collection))
(1+ (current editor)) (length (obj-list collection))
;(name (nth (current editor) (obj-list collection)))
)
"[empty collection]")))
(defmethod editor-invalidate-views ((editor collection-editor))
(when (internal-editor editor)
(om-invalidate-view (internal-editor editor))))
(defmethod set-current-text ((editor collection-editor))
(let ((text-component (get-g-component editor :current-text)))
(when text-component
(let ((text (format-current-text editor)))
(om-set-view-size text-component
(omp (+ 20 (om-string-size text (om-get-font text-component))) 16))
(om-set-text text-component text)))))
(defmethod update-collection-editor ((editor collection-editor))
(declare (special *general-player*))
(set-current-text editor)
(let ((internal-editor (internal-editor editor)))
(when (and (boundp '*general-player*) *general-player*)
(editor-stop internal-editor))
(setf (selection internal-editor) nil)
(let ((abs-container (object internal-editor))) ;; in principle this is an OMAbstractContainer
(setf (contents abs-container)
(nth (current editor) (obj-list (get-value-for-editor (object editor))))))
(update-default-view internal-editor)
(update-to-editor internal-editor editor)
(editor-invalidate-views internal-editor)))
(defmethod set-current-nth ((editor collection-editor) n)
(let ((collection (get-value-for-editor (object editor))))
(when (obj-list collection)
(setf (current editor) n))
(update-collection-editor editor)))
(defmethod set-current-next ((editor collection-editor))
(let ((collection (get-value-for-editor (object editor))))
(when (obj-list collection)
(set-current-nth editor (mod (1+ (current editor)) (length (obj-list collection))))
)))
(defmethod set-current-previous ((editor collection-editor))
(let ((collection (get-value-for-editor (object editor))))
(when (obj-list collection)
(set-current-nth editor (mod (1- (current editor)) (length (obj-list collection))))
)))
(defmethod remove-current-object ((editor collection-editor))
(let ((collection (get-value-for-editor (object editor))))
;;; update the obj-list
(when (obj-list collection)
(setf (obj-list collection) (remove (nth (current editor) (obj-list collection)) (obj-list collection)))
(setf (current editor) (max 0 (min (current editor) (1- (length (obj-list collection)))))))
;;; if no more objects...
(if (null (obj-list collection))
(progn
;;; close the internal editor
(editor-close (internal-editor editor))
(setf (contents (object (internal-editor editor))) nil)
(init-editor editor) ;; need to init the editor (reset to an empty omeditor)
;;; rest the (empty) window
(set-window-contents editor))
;;; othewise just update the editor
(update-collection-editor editor))
(report-modifications editor)
))
(defmethod add-new-object ((editor collection-editor))
(let* ((collection (get-value-for-editor (object editor)))
(new? (null (obj-list collection))))
(setf (obj-list collection)
(append (obj-list collection)
(list (om-init-instance (make-instance (obj-type collection))))))
(setf (current editor) (1- (length (obj-list collection))))
(when new? ;;; need to (re)initialize an editor
(init-editor editor)
(set-window-contents editor)
(init-editor-window (internal-editor editor)))
(update-collection-editor editor)
(update-multi-display editor (editor-get-edit-param editor :show-all)) ;; will add the new object to te multi-display list
(report-modifications editor)
))
;;;=========================
;;; DISPATCH ACTIONS...
;;;=========================
(defmethod editor-key-action ((editor collection-editor) key)
(cond ((and (om-command-key-p) (equal key :om-key-left))
(set-current-previous editor)
(update-collection-editor editor))
((and (om-command-key-p) (equal key :om-key-right))
(set-current-next editor)
(update-collection-editor editor))
(t (editor-key-action (internal-editor editor) key))
))
(defmethod select-all-command ((self collection-editor))
#'(lambda ()
(when (and (internal-editor self) (select-all-command (internal-editor self)))
(funcall (select-all-command (internal-editor self))))))
| null | https://raw.githubusercontent.com/cac-t-u-s/om-sharp/80f9537368471d0e6e4accdc9fff01ed277b879e/src/visual-language/tools/collections.lisp | lisp | ============================================================================
om#: visual programming language for computer-assisted music composition
============================================================================
This program is free software. For information on usage
and redistribution, see the "LICENSE" file in this distribution.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
============================================================================
============================================================================
===========================
COLLECTION = A SET OF OBJECTS OF A SAME TYPE
===========================
the collection box has same additional attributes as the object it contains (if any)
coerce all object to the specified type
check if all items are of the same type
===========================
BOX
===========================
The multi-cache display is a list of list (object cache)
collection boxes create "multi-cache" by calling get-collection-cache-display on internbal objects
CAN BE REDEFINED FOR SPECIFIC OBJECTS:
type is an object used for specialization
will eventually store some cache
called on elements of the collection:
this is just an access in memory: no need to redo the cache
set the general cache to the item in the multi-cache
type is an object used for specialization
otherwise, calls draw-mini-view for every object
used for display etc.
take the longer object as reference
===========================
EDITOR
===========================
==================================
multidisplay API
==================================
will share the same list in principle
in case it was disabled..
when updated from the box (eval)
the new object has not the same editor
need to close/reset the internal editor
with reset the virtual object for internal-editor
[~A]
(name (nth (current editor) (obj-list collection)))
in principle this is an OMAbstractContainer
update the obj-list
if no more objects...
close the internal editor
need to init the editor (reset to an empty omeditor)
rest the (empty) window
othewise just update the editor
need to (re)initialize an editor
will add the new object to te multi-display list
=========================
DISPATCH ACTIONS...
========================= | File author :
(in-package :om)
(defclass* collection (named-object)
((obj-type :accessor obj-type :initform nil)
(obj-list :initarg :obj-list :accessor obj-list :initform nil))
(:documentation "Container holding a set of several objects of the same type.
Displays/enable editing the list of objects in a single 'collection editor'.
The desired type can be specified as the first input (e.g. typing 'collection BPF').
If this is done, this type is used to initialize or convert the input list of objects (if possible)."
))
(defmethod get-properties-list ((self collection))
'(("COLLECTION attibutes"
(:name "Name" :text name))))
(defmethod additional-box-attributes ((self collection))
(additional-box-attributes (car (obj-list self))))
(defmethod homogenize-collection (model list) nil)
(defmethod om-init-instance ((self collection) &optional initargs)
(let ((initial-list (loop for item in (list! (obj-list self))
collect (om-init-instance item))))
(setf (obj-list self)
(if (obj-type self)
(remove nil
(mapcar
#'(lambda (obj)
(om-init-instance (objfromobjs obj (make-instance (obj-type self)))))
initial-list))
(om-copy initial-list))))
(when (obj-list self)
(if (list-typep (obj-list self) (type-of (car (obj-list self))))
(progn
(setf (obj-type self) (type-of (car (obj-list self))))
(homogenize-collection (car (obj-list self)) (obj-list self)))
(progn
(om-beep-msg "WARNING: ELEMENTS IN COLLECTION ARE NOT OF THE SAME TYPE!!")
(setf (obj-type self) nil))))
self)
(defmethod object-default-edition-params ((self collection))
(append
'((:show-all t))
(object-default-edition-params (car (obj-list self)))))
(defmethod special-box-p ((name (eql 'collection))) t)
(defmethod special-box-type ((class-name (eql 'collection))) 'CollectionBox)
(defclass MultiCacheBoxEditCall (OMBoxEditCall)
((multi-cache-display :accessor multi-cache-display :initform nil)))
(defclass CollectionBox (MultiCacheBoxEditCall) ())
(defmethod omNG-make-special-box ((reference (eql 'collection)) pos &optional init-args)
(let ((type (and init-args (find-class (car init-args) nil)))
(val (make-instance 'collection)))
(when type (setf (obj-type val) (class-name type)))
(let ((box (omNG-make-new-boxcall (find-class 'collection) pos val)))
(setf (name box) "...")
(setf (value (car (inputs box))) (obj-type val))
box)))
(defmethod objfromobjs ((model symbol) (target collection))
(if (find-class model nil)
(setf (obj-type target) model)
(om-beep-msg "WARNING: class not found for collection: ~S" model))
target)
(defmethod draw-type-of-object ((object collection))
(string+ (string-upcase (type-of object)) " OF " (string-upcase (obj-type object))))
(defmethod get-object-type-name ((object collection))
(and (obj-type object)
(string+ "COLLECTION OF " (string-upcase (obj-type object))
"s (" (number-to-string (length (obj-list object))) ")")))
(defmethod object-box-label ((object collection))
(string+ (string-upcase (type-of object)) " of "
(number-to-string (length (obj-list object))) " "
(if (obj-type object) (string-upcase (obj-type object)) "?")
(if (> (length (obj-list object)) 1) "s" "")
))
(defmethod display-modes-for-object ((self collection)) '(:mini-view :text :hidden))
(defmethod get-cache-display-for-text ((self collection) box)
(declare (ignore box))
(loop for obj in (obj-list self)
for i = 0 then (1+ i)
collect (list (format nil "[~D]" i) obj)))
CollectionBox has a little hack on cache - display to store a different cache for each object
(defmethod get-cache-display-for-draw ((object collection) box)
(declare (ignore box))
(unless (multi-cache-display box)
(setf (multi-cache-display box)
(get-collection-cache-display (car (obj-list object)) (obj-list object) box)))
nil)
(defmethod get-collection-cache-display ((type t) list box)
(loop for o in list collect (list o (get-cache-display-for-draw o box))))
(defmethod reset-cache-display ((self CollectionBox))
(setf (multi-cache-display self) nil)
(call-next-method))
(defmethod ensure-cache-display-draw ((box CollectionBox) object)
(if (typep object 'collection)
(progn
(unless (cache-display box) (setf (cache-display box) (make-cache-display)))
(unless (cache-display-draw (cache-display box))
(setf (cache-display-draw (cache-display box))
(cadr (find object (multi-cache-display box) :key #'car))))
(cache-display-draw (cache-display box)))))
(defmethod collection-draw-mini-view ((type t) list box x y w h time)
(when list
(let ((ho (/ h (length list))))
(loop for o in list
for yo = y then (+ yo ho) do
(setf (cache-display box) nil)
(draw-mini-view o box x yo w ho time))
)))
(defmethod draw-mini-view ((self collection) (box t) x y w h &optional time)
(ensure-cache-display-draw box self)
(collection-draw-mini-view
(car (obj-list self))
(obj-list self)
box x y w h time))
(defmethod get-obj-dur ((self collection))
(apply #'max (or (remove nil (mapcar #'get-obj-dur (obj-list self))) '(0))))
(defmethod miniview-time-to-pixel ((object collection) box (view omboxframe) time)
(miniview-time-to-pixel
(reduce #'(lambda (o1 o2) (if (>= (get-obj-dur o1) (get-obj-dur o2)) o1 o2))
(obj-list object))
box view time))
(defclass collection-editor (OMEditor undoable-editor-mixin)
((internal-editor :accessor internal-editor :initform nil)
(current :accessor current :initform 0)))
(defmethod object-has-editor ((self collection)) t)
(defmethod get-editor-class ((self collection)) 'collection-editor)
(defmethod object-value ((self collection-editor))
(nth (current self) (obj-list (get-value-for-editor (object self)))))
(defmethod undoable-object ((self collection-editor))
(get-value-for-editor (object self)))
(defmethod get-obj-to-play ((self collection-editor)) (object-value self))
(defmethod editor-play-state ((self collection-editor))
(editor-play-state (internal-editor self)))
(defmethod editor-close ((self collection-editor))
(editor-close (internal-editor self))
(call-next-method))
(defclass multi-display-editor-mixin ()
((multi-display-p :accessor multi-display-p :initarg :multi-display-p :initform nil)
(multi-obj-list :accessor multi-obj-list :initform nil)))
(defmethod handle-multi-display ((self t)) nil)
(defmethod handle-multi-display ((self multi-display-editor-mixin)) t)
(defmethod enable-multi-display ((self t) obj-list) nil)
(defmethod enable-multi-display ((self multi-display-editor-mixin) obj-list)
(setf (multi-display-p self) t
(multi-obj-list self) obj-list))
(defmethod disable-multi-display ((self t)) nil)
(defmethod disable-multi-display ((self multi-display-editor-mixin))
(setf (multi-display-p self) nil)
(setf (multi-obj-list self) nil))
(defmethod update-multi-display ((editor collection-editor) t-or-nil)
(if t-or-nil
(enable-multi-display (internal-editor editor) (obj-list (get-value-for-editor (object editor))))
(disable-multi-display (internal-editor editor)))
(update-to-editor (internal-editor editor) editor)
(editor-invalidate-views (internal-editor editor))
)
(defmethod init-editor ((editor collection-editor))
(let* ((collection (get-value-for-editor (object editor)))
(current-object (and (obj-type collection) (nth (current editor) (obj-list collection))))
(abs-container (make-instance 'OMAbstractContainer :contents current-object)))
(setf (internal-editor editor)
(make-instance (get-editor-class current-object)
:container-editor editor
:object abs-container))
(setf (edition-params abs-container) (edition-params (object editor)))
(init-editor (internal-editor editor))
))
(defmethod init-editor-window ((editor collection-editor))
(call-next-method)
(init-editor-window (internal-editor editor))
(when (editor-get-edit-param editor :show-all)
(update-multi-display editor t)))
(defmethod make-editor-window-contents ((editor collection-editor))
(let* ((collection (get-value-for-editor (object editor)))
(text (format-current-text editor))
(current-text (let ((font (om-def-font :large-b)))
(om-make-graphic-object
'om-item-text
:size (omp (om-string-size text font) 16)
:text text :font font)))
(prev-button (om-make-graphic-object
'om-icon-button
:size (omp 16 16) :position (omp 0 0)
:icon :l-arrow :icon-pushed :l-arrow-pushed :icon-disabled :l-arrow-disabled
:lock-push nil :enabled (> (length (obj-list collection)) 1)
:action #'(lambda (b)
(declare (ignore b))
(set-current-previous editor)
)))
(next-button (om-make-graphic-object
'om-icon-button
:size (omp 16 16) :position (omp 0 0)
:icon :r-arrow :icon-pushed :r-arrow-pushed :icon-disabled :r-arrow-disabled
:lock-push nil :enabled (> (length (obj-list collection)) 1)
:action #'(lambda (b)
(declare (ignore b))
(set-current-next editor)
)))
(-button (om-make-graphic-object
'om-icon-button
:size (omp 16 16) :position (omp 0 0)
:icon :- :icon-pushed :--pushed :icon-disabled :--disabled
:lock-push nil :enabled (obj-list collection)
:action #'(lambda (b)
(remove-current-object editor)
(let ((coll (get-value-for-editor (object editor))))
(if (obj-list coll)
(update-multi-display editor (editor-get-edit-param editor :show-all))
(button-disable b))
(when (<= (length (obj-list coll)) 1)
(button-disable prev-button) (button-disable next-button))
))
))
(+button (om-make-graphic-object
'om-icon-button
:size (omp 16 16) :position (omp 0 0)
:icon :+ :icon-pushed :+-pushed :icon-disabled :+-disabled
:lock-push nil
:enabled (and (obj-type (get-value-for-editor (object editor)))
(subtypep (obj-type (get-value-for-editor (object editor))) 'standard-object))
:action #'(lambda (b)
(declare (ignore b))
(add-new-object editor)
(let ((coll (get-value-for-editor (object editor))))
(when (> (length (obj-list coll)) 1)
(button-enable prev-button) (button-enable next-button)))
(update-multi-display editor (editor-get-edit-param editor :show-all))
)))
(showall-check
(when (handle-multi-display (internal-editor editor))
(om-make-di
'om-check-box
:text " Show All" :size (omp 80 16) :font (om-def-font :gui)
:checked-p (editor-get-edit-param editor :show-all) :focus nil :default nil
:di-action #'(lambda (item)
(editor-set-edit-param editor :show-all (om-checked-p item))
(update-multi-display editor (om-checked-p item)))
)))
)
(set-g-component editor :current-text current-text)
(om-make-layout
'om-column-layout
:ratios '(1 99)
:subviews
(list
(om-make-layout
'om-row-layout
:delta 0
:ratios '(1 1 1 10 1 10 1)
:align :top
:subviews
(list
(om-make-layout
'om-row-layout :delta 0
:subviews
(list (om-make-view 'om-view :size (omp 16 16) :subviews (list prev-button))
(om-make-view 'om-view :size (omp 16 16) :subviews (list next-button)))
)
(om-make-graphic-object 'om-item-view :size (omp 20 20))
showall-check
nil
current-text
nil
(om-make-layout
'om-row-layout :delta 0
:subviews
(list (om-make-view 'om-view :size (omp 16 16) :subviews (list +button))
(om-make-view 'om-view :size (omp 16 16) :subviews (list -button))
))
))
(if (object-value (internal-editor editor))
(setf (main-view (internal-editor editor))
(make-editor-window-contents (internal-editor editor))))
))
))
(defmethod set-window-contents ((editor collection-editor))
(when (window editor)
(om-remove-subviews (window editor) (main-view editor))
(om-add-subviews (window editor)
(setf (main-view editor)
(make-editor-window-contents editor)))
))
(defmethod update-to-editor ((editor collection-editor) (from OMBox))
(let ((collection (get-value-for-editor (object editor))))
(get-editor-class (nth (current editor) (obj-list collection)))))
(editor-close (internal-editor editor))
(init-editor editor)
(setf (current editor) 0)
(set-window-contents editor)
))
(update-collection-editor editor)
(set-current-text editor)
(update-to-editor (internal-editor editor) from)
(update-multi-display editor (editor-get-edit-param editor :show-all))
(call-next-method)
)
(defmethod format-current-text ((editor collection-editor))
(let ((collection (get-value-for-editor (object editor))))
(if (obj-list collection)
(string-upcase (obj-type collection))
(1+ (current editor)) (length (obj-list collection))
)
"[empty collection]")))
(defmethod editor-invalidate-views ((editor collection-editor))
(when (internal-editor editor)
(om-invalidate-view (internal-editor editor))))
(defmethod set-current-text ((editor collection-editor))
(let ((text-component (get-g-component editor :current-text)))
(when text-component
(let ((text (format-current-text editor)))
(om-set-view-size text-component
(omp (+ 20 (om-string-size text (om-get-font text-component))) 16))
(om-set-text text-component text)))))
(defmethod update-collection-editor ((editor collection-editor))
(declare (special *general-player*))
(set-current-text editor)
(let ((internal-editor (internal-editor editor)))
(when (and (boundp '*general-player*) *general-player*)
(editor-stop internal-editor))
(setf (selection internal-editor) nil)
(setf (contents abs-container)
(nth (current editor) (obj-list (get-value-for-editor (object editor))))))
(update-default-view internal-editor)
(update-to-editor internal-editor editor)
(editor-invalidate-views internal-editor)))
(defmethod set-current-nth ((editor collection-editor) n)
(let ((collection (get-value-for-editor (object editor))))
(when (obj-list collection)
(setf (current editor) n))
(update-collection-editor editor)))
(defmethod set-current-next ((editor collection-editor))
(let ((collection (get-value-for-editor (object editor))))
(when (obj-list collection)
(set-current-nth editor (mod (1+ (current editor)) (length (obj-list collection))))
)))
(defmethod set-current-previous ((editor collection-editor))
(let ((collection (get-value-for-editor (object editor))))
(when (obj-list collection)
(set-current-nth editor (mod (1- (current editor)) (length (obj-list collection))))
)))
(defmethod remove-current-object ((editor collection-editor))
(let ((collection (get-value-for-editor (object editor))))
(when (obj-list collection)
(setf (obj-list collection) (remove (nth (current editor) (obj-list collection)) (obj-list collection)))
(setf (current editor) (max 0 (min (current editor) (1- (length (obj-list collection)))))))
(if (null (obj-list collection))
(progn
(editor-close (internal-editor editor))
(setf (contents (object (internal-editor editor))) nil)
(set-window-contents editor))
(update-collection-editor editor))
(report-modifications editor)
))
(defmethod add-new-object ((editor collection-editor))
(let* ((collection (get-value-for-editor (object editor)))
(new? (null (obj-list collection))))
(setf (obj-list collection)
(append (obj-list collection)
(list (om-init-instance (make-instance (obj-type collection))))))
(setf (current editor) (1- (length (obj-list collection))))
(init-editor editor)
(set-window-contents editor)
(init-editor-window (internal-editor editor)))
(update-collection-editor editor)
(report-modifications editor)
))
(defmethod editor-key-action ((editor collection-editor) key)
(cond ((and (om-command-key-p) (equal key :om-key-left))
(set-current-previous editor)
(update-collection-editor editor))
((and (om-command-key-p) (equal key :om-key-right))
(set-current-next editor)
(update-collection-editor editor))
(t (editor-key-action (internal-editor editor) key))
))
(defmethod select-all-command ((self collection-editor))
#'(lambda ()
(when (and (internal-editor self) (select-all-command (internal-editor self)))
(funcall (select-all-command (internal-editor self))))))
|
eecd4e318848636fa671b83092c070ba9e3cbfb6bf39888116b0f039dc6662b1 | sangkilc/ofuzz | comblib.ml | (* ofuzz - ocaml fuzzing platform *)
* combinatorial apis
@author < sangkil.cha\@gmail.com >
@since 2014 - 03 - 19
@author Sang Kil Cha <sangkil.cha\@gmail.com>
@since 2014-03-19
*)
Copyright ( c ) 2014 ,
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution .
* Neither the name of the < organization > nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND
ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL SANG KIL CHA BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
Copyright (c) 2014, Sang Kil Cha
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL SANG KIL CHA BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
*)
let get_partition_ratio = Libcomb.get_partition_ratio
let get_random_partition r n k =
let r = Random.State.float r 1.0 in
let rec loop pos accratio =
let accratio = accratio +. (get_partition_ratio n k pos) in
if r <= accratio then pos
else loop (pos-1) accratio
in
loop k 0.0
let set = Hashtbl.create 7901
* 's algorithm for random k subset
let floyds_sampling r n k =
Hashtbl.clear set;
for j = n - k + 1 to n do
let t = (Random.State.int r j) + 1 in
if Hashtbl.mem set t then (Hashtbl.add set j true)
else (Hashtbl.add set t true)
done;
set
| null | https://raw.githubusercontent.com/sangkilc/ofuzz/ba53cc90cc06512eb90459a7159772d75ebe954f/src/comblib.ml | ocaml | ofuzz - ocaml fuzzing platform |
* combinatorial apis
@author < sangkil.cha\@gmail.com >
@since 2014 - 03 - 19
@author Sang Kil Cha <sangkil.cha\@gmail.com>
@since 2014-03-19
*)
Copyright ( c ) 2014 ,
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution .
* Neither the name of the < organization > nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND
ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL SANG KIL CHA BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
Copyright (c) 2014, Sang Kil Cha
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL SANG KIL CHA BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
*)
let get_partition_ratio = Libcomb.get_partition_ratio
let get_random_partition r n k =
let r = Random.State.float r 1.0 in
let rec loop pos accratio =
let accratio = accratio +. (get_partition_ratio n k pos) in
if r <= accratio then pos
else loop (pos-1) accratio
in
loop k 0.0
let set = Hashtbl.create 7901
* 's algorithm for random k subset
let floyds_sampling r n k =
Hashtbl.clear set;
for j = n - k + 1 to n do
let t = (Random.State.int r j) + 1 in
if Hashtbl.mem set t then (Hashtbl.add set j true)
else (Hashtbl.add set t true)
done;
set
|
3cb2e6c04d576f6960975894b3663a43ea52d98e1da9652bcfc43dc521a846bf | ocaml-sf/learn-ocaml-corpus | cnf_exception.ml | (* ------------------------------------------------------------------------------ *)
(* Building formulae. *)
let var x =
FVar x
let falsity =
FConst false
let truth =
FConst true
let const sense =
if sense then truth else falsity
(* [FConst sense] would work too, but would allocate memory *)
let neg f =
match f with
| FConst sense ->
const (not sense)
| FNeg f ->
f
| _ ->
FNeg f
let conn sense f1 f2 =
match f1, f2 with
| FConst sense', f
| f, FConst sense' ->
if sense = sense' then
f
else
FConst sense'
| _, _ ->
FConn (sense, f1, f2)
let conj f1 f2 =
conn true f1 f2
let disj f1 f2 =
conn false f1 f2
(* ------------------------------------------------------------------------------ *)
(* Evaluating formulae. *)
let rec eval (env : env) (f : formula) : bool =
match f with
| FConst b ->
b
| FConn (true, f1, f2) ->
eval env f1 && eval env f2
| FConn (false, f1, f2) ->
eval env f1 || eval env f2
| FNeg f ->
not (eval env f)
| FVar x ->
env x
let foreach_env (n : int) (body : env -> unit) : unit =
(* We assume [n < Sys.word_size - 1]. *)
for i = 0 to 1 lsl n - 1 do
let env x =
assert (0 <= x && x < n);
i land (1 lsl x) <> 0
in
body env
done
let satisfiable (n : int) (f : formula) : bool =
let exception SAT in
try
foreach_env n (fun env ->
if eval env f then
raise SAT
);
false
with SAT ->
true
let valid (n : int) (f : formula) : bool =
not (satisfiable n (neg f))
(* ------------------------------------------------------------------------------ *)
(* Converting formulae to conjunctive normal form. *)
module CNF (X : sig
type clause
val empty: clause
val cons: bool -> var -> clause -> clause
val new_var: (unit) -> var
val new_clause: clause -> unit
end)
= struct
open X
(* The conjunction of the clauses emitted by [cnf s f c] must be logically
equivalent to the formula [s.f \/ c]. *)
(* It is permitted to assume that [c] is small and therefore to duplicate
it. It is not permitted to duplicate [f]. *)
let rec cnf (s : bool) (f : formula) (c : clause) : unit =
match f with
| FConst s' when s = s' ->
(* The formula [s.f] is True, therefore the disjunction [s.f \/ c] is
true. No clauses need be emitted. *)
()
| FConn (s', f1, f2) when s = s' ->
(* The formula [s.f] can be written as a conjunction [s.f1 /\ s.f2].
The disjunction [_ \/ c] can be distributed onto this conjunction.
Thus, the formula [s.f \/ c] is logically equivalent to the
conjunction of [s.f1 \/ c] and [s.f2 \/ c]. *)
cnf s f1 c;
cnf s f2 c
| FNeg f1 ->
(* The formula [s.f] is equivalent to [(not s).f1]. *)
cnf (not s) f1 c
| _ ->
(* The formula [s.f] is False or a disjunction or a variable.
Transform it into a single clause and emit this clause. *)
new_clause (clause s f c)
(* The clause returned by [clause s f c], in conjunction with any
emitted clauses, must be logically equivalent to [s.f \/ c]. *)
and clause (s : bool) (f : formula) (c : clause) : clause =
match f with
| FConst s' when s <> s' ->
(* The formula [s.f] is False, so [s.f \/ c] is equivalent to [c]. *)
c
| FConn (s', f1, f2) when s <> s' ->
(* The formula [s.f] can be written as the disjunction [s.f1 \/ s.f2].
Therefore [s.f \/ c] is equivalent to [s.f1 \/ s.f2 \/ c]. *)
clause s f1 (clause s f2 c)
| FNeg f1 ->
(* The formula [s.f] is equivalent to [(not s).f1]. *)
clause (not s) f1 c
| FVar x ->
(* [s.x \/ c] is a valid clause. Return it. *)
cons s x c
| FConst s' ->
assert (s = s');
(* The formula [s.f] is True. Our assumption is violated. *)
assert false
| FConn (s', f1, f2) ->
assert (s = s');
invalid_arg "Gotcha!" (* wrong *)
(* The main entry point. *)
let cnf (f : formula) : unit =
cnf true f empty
end
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/sat/wrong/cnf_exception.ml | ocaml | ------------------------------------------------------------------------------
Building formulae.
[FConst sense] would work too, but would allocate memory
------------------------------------------------------------------------------
Evaluating formulae.
We assume [n < Sys.word_size - 1].
------------------------------------------------------------------------------
Converting formulae to conjunctive normal form.
The conjunction of the clauses emitted by [cnf s f c] must be logically
equivalent to the formula [s.f \/ c].
It is permitted to assume that [c] is small and therefore to duplicate
it. It is not permitted to duplicate [f].
The formula [s.f] is True, therefore the disjunction [s.f \/ c] is
true. No clauses need be emitted.
The formula [s.f] can be written as a conjunction [s.f1 /\ s.f2].
The disjunction [_ \/ c] can be distributed onto this conjunction.
Thus, the formula [s.f \/ c] is logically equivalent to the
conjunction of [s.f1 \/ c] and [s.f2 \/ c].
The formula [s.f] is equivalent to [(not s).f1].
The formula [s.f] is False or a disjunction or a variable.
Transform it into a single clause and emit this clause.
The clause returned by [clause s f c], in conjunction with any
emitted clauses, must be logically equivalent to [s.f \/ c].
The formula [s.f] is False, so [s.f \/ c] is equivalent to [c].
The formula [s.f] can be written as the disjunction [s.f1 \/ s.f2].
Therefore [s.f \/ c] is equivalent to [s.f1 \/ s.f2 \/ c].
The formula [s.f] is equivalent to [(not s).f1].
[s.x \/ c] is a valid clause. Return it.
The formula [s.f] is True. Our assumption is violated.
wrong
The main entry point. |
let var x =
FVar x
let falsity =
FConst false
let truth =
FConst true
let const sense =
if sense then truth else falsity
let neg f =
match f with
| FConst sense ->
const (not sense)
| FNeg f ->
f
| _ ->
FNeg f
let conn sense f1 f2 =
match f1, f2 with
| FConst sense', f
| f, FConst sense' ->
if sense = sense' then
f
else
FConst sense'
| _, _ ->
FConn (sense, f1, f2)
let conj f1 f2 =
conn true f1 f2
let disj f1 f2 =
conn false f1 f2
let rec eval (env : env) (f : formula) : bool =
match f with
| FConst b ->
b
| FConn (true, f1, f2) ->
eval env f1 && eval env f2
| FConn (false, f1, f2) ->
eval env f1 || eval env f2
| FNeg f ->
not (eval env f)
| FVar x ->
env x
let foreach_env (n : int) (body : env -> unit) : unit =
for i = 0 to 1 lsl n - 1 do
let env x =
assert (0 <= x && x < n);
i land (1 lsl x) <> 0
in
body env
done
let satisfiable (n : int) (f : formula) : bool =
let exception SAT in
try
foreach_env n (fun env ->
if eval env f then
raise SAT
);
false
with SAT ->
true
let valid (n : int) (f : formula) : bool =
not (satisfiable n (neg f))
module CNF (X : sig
type clause
val empty: clause
val cons: bool -> var -> clause -> clause
val new_var: (unit) -> var
val new_clause: clause -> unit
end)
= struct
open X
let rec cnf (s : bool) (f : formula) (c : clause) : unit =
match f with
| FConst s' when s = s' ->
()
| FConn (s', f1, f2) when s = s' ->
cnf s f1 c;
cnf s f2 c
| FNeg f1 ->
cnf (not s) f1 c
| _ ->
new_clause (clause s f c)
and clause (s : bool) (f : formula) (c : clause) : clause =
match f with
| FConst s' when s <> s' ->
c
| FConn (s', f1, f2) when s <> s' ->
clause s f1 (clause s f2 c)
| FNeg f1 ->
clause (not s) f1 c
| FVar x ->
cons s x c
| FConst s' ->
assert (s = s');
assert false
| FConn (s', f1, f2) ->
assert (s = s');
let cnf (f : formula) : unit =
cnf true f empty
end
|
019b430c921f64d150164159b9bf5f79d354281ab68e0362cbc0d6d761079e43 | andorp/bead | Page.hs | {-# LANGUAGE OverloadedStrings #-}
module Bead.View.Content.NewTestScript.Page (
newTestScript
, modifyTestScript
) where
import Control.Arrow ((***))
import Data.String (fromString)
import Data.String.Utils (replace)
import Text.Blaze.Html5 as H hiding (map)
import qualified Bead.Controller.Pages as Pages
import qualified Bead.Controller.UserStories as Story
import Bead.View.Content
import qualified Bead.View.Content.Bootstrap as Bootstrap
import qualified Bead.View.UserActions as UA
-- * Content Handlers
data PageData
= Create [(CourseKey, Course)]
-- ^ Create a new test script
| Modify String TestScriptKey TestScript
^ Modify an existing test script with CourseName Key Script
pageDataCata
create
modify
p = case p of
Create cs -> create cs
Modify cn tk ts -> modify cn tk ts
newTestScript :: ViewModifyHandler
newTestScript = ViewModifyHandler newTestScriptPage postNewTestScript
modifyTestScript :: ViewModifyHandler
modifyTestScript = ViewModifyHandler modifyTestScriptPage postModifyTestScript
newTestScriptPage :: GETContentHandler
newTestScriptPage = do
cs <- userStory Story.administratedCourses
return $ testScriptContent (Create cs)
postNewTestScript :: POSTContentHandler
postNewTestScript = do
script' <- TestScript
<$> (getParameter (stringParameter (fieldName testScriptNameField) "Test Script Name"))
<*> (getParameter (stringParameter (fieldName testScriptDescField) "Test Script Description"))
<*> (getParameter (stringParameter (fieldName testScriptNotesField) "Test Script Notes"))
<*> (replaceCrlf <$> getParameter (stringParameter (fieldName testScriptScriptField) "Test Script"))
ck <- getParameter (jsonParameter (fieldName testScriptCourseKeyField) "Course Key")
script <- userStory $ do
Story.isAdministratedCourse ck
(course,_groupkeys) <- Story.loadCourse ck
return (script' $ courseTestScriptType course)
return $ UA.CreateTestScript ck script
modifyTestScriptPage :: GETContentHandler
modifyTestScriptPage = do
tsk <- getParameter testScriptKeyPrm
(course, script) <- userStory $ do
Story.isAdministratedTestScript tsk
(script, ck) <- Story.loadTestScript tsk
(course, _gk) <- Story.loadCourse ck
return (course, script)
return $ testScriptContent (Modify (courseName course) tsk script)
postModifyTestScript :: POSTContentHandler
postModifyTestScript = do
script' <- TestScript
<$> (getParameter (stringParameter (fieldName testScriptNameField) "Test Script Name"))
<*> (getParameter (stringParameter (fieldName testScriptDescField) "Test Script Description"))
<*> (getParameter (stringParameter (fieldName testScriptNotesField) "Test Script Notes"))
<*> (replaceCrlf <$> getParameter (stringParameter (fieldName testScriptScriptField) "Test Script"))
tsk <- getParameter testScriptKeyPrm
script <- userStory $ do
(testscript, _coursekey) <- Story.loadTestScript tsk
return (script' $ tsType testscript)
return $ UA.ModifyTestScript tsk script
testScriptContent :: PageData -> IHtml
testScriptContent pd = pageDataCata checkIfThereCourses modify pd
where
checkIfThereCourses [] = hasNoCourses pd
checkIfThereCourses _ = pageContent pd
modify _ _ _ = pageContent pd
hasNoCourses :: PageData -> IHtml
hasNoCourses pd = do
msg <- getI18N
return $ do
let pageTitle = pageDataCata (const $ msg_LinkText_NewTestScript "New Test") (const3 $ msg_LinkText_ModifyTestScript "Modify Test Script") pd
Bootstrap.rowColMd12 $ p $
fromString . msg $ msg_NewTestScript_HasNoCourses "This user cannot administer any courses."
pageContent :: PageData -> IHtml
pageContent pd = do
msg <- getI18N
let textField param label valueSelector = pageDataCata
(const $ Bootstrap.textInput (fieldName param) (msg label) "")
(\_name _key script -> Bootstrap.textInputWithDefault (fieldName param) (msg label) (valueSelector script))
pd
let textArea param label valueSelector = pageDataCata
(const $ Bootstrap.textArea (fieldName param) (msg label) "")
(\_name _key script -> Bootstrap.textArea (fieldName param) (msg label) (fromString (valueSelector script)))
pd
let utf8TextArea param label valueSelector = pageDataCata
(const $ Bootstrap.utf8TextArea (fieldName param) (msg label) "")
(\_name _key script -> Bootstrap.utf8TextArea (fieldName param) (msg label) (fromString (valueSelector script)))
pd
let name = textField testScriptNameField (msg_NewTestScript_Name "Name") tsName
let description = textField testScriptDescField (msg_NewTestScript_Description "Description") tsDescription
let help = textArea testScriptNotesField (msg_NewTestScript_Notes "Help for writing test cases") tsNotes
let script = textArea testScriptScriptField (msg_NewTestScript_Script "Test script") tsScript
return $ do
postForm (routeOf $ testScriptPage pd) $ do
course msg
name
description
help
script
Bootstrap.submitButton (fieldName testScriptSaveButton) (fromString . msg $ msg_NewTestScript_Save "Commit")
Bootstrap.turnSelectionsOn
where
testScriptPage = pageDataCata (const (Pages.newTestScript ())) (\_name key _script -> Pages.modifyTestScript key ())
course msg = pageDataCata
(Bootstrap.selectionWithLabel (fieldName testScriptCourseKeyField) (msg $ msg_NewTestScript_Course "Course:")
(const False) . map (id *** courseNameAndType))
(\courseName _key _script -> fromString courseName)
pd
where
courseNameAndType c = concat
[courseName c, " - ", courseTypeStr $ courseTestScriptType c]
courseTypeStr = msg . testScriptTypeCata
(msg_TestScriptTypeSimple "Textual")
(msg_TestScriptTypeZipped "Binary")
-- Helper
replaceCrlf :: String -> String
replaceCrlf = replace "\r\n" "\n"
| null | https://raw.githubusercontent.com/andorp/bead/280dc9c3d5cfe1b9aac0f2f802c705ae65f02ac2/src/Bead/View/Content/NewTestScript/Page.hs | haskell | # LANGUAGE OverloadedStrings #
* Content Handlers
^ Create a new test script
Helper | module Bead.View.Content.NewTestScript.Page (
newTestScript
, modifyTestScript
) where
import Control.Arrow ((***))
import Data.String (fromString)
import Data.String.Utils (replace)
import Text.Blaze.Html5 as H hiding (map)
import qualified Bead.Controller.Pages as Pages
import qualified Bead.Controller.UserStories as Story
import Bead.View.Content
import qualified Bead.View.Content.Bootstrap as Bootstrap
import qualified Bead.View.UserActions as UA
data PageData
= Create [(CourseKey, Course)]
| Modify String TestScriptKey TestScript
^ Modify an existing test script with CourseName Key Script
pageDataCata
create
modify
p = case p of
Create cs -> create cs
Modify cn tk ts -> modify cn tk ts
newTestScript :: ViewModifyHandler
newTestScript = ViewModifyHandler newTestScriptPage postNewTestScript
modifyTestScript :: ViewModifyHandler
modifyTestScript = ViewModifyHandler modifyTestScriptPage postModifyTestScript
newTestScriptPage :: GETContentHandler
newTestScriptPage = do
cs <- userStory Story.administratedCourses
return $ testScriptContent (Create cs)
postNewTestScript :: POSTContentHandler
postNewTestScript = do
script' <- TestScript
<$> (getParameter (stringParameter (fieldName testScriptNameField) "Test Script Name"))
<*> (getParameter (stringParameter (fieldName testScriptDescField) "Test Script Description"))
<*> (getParameter (stringParameter (fieldName testScriptNotesField) "Test Script Notes"))
<*> (replaceCrlf <$> getParameter (stringParameter (fieldName testScriptScriptField) "Test Script"))
ck <- getParameter (jsonParameter (fieldName testScriptCourseKeyField) "Course Key")
script <- userStory $ do
Story.isAdministratedCourse ck
(course,_groupkeys) <- Story.loadCourse ck
return (script' $ courseTestScriptType course)
return $ UA.CreateTestScript ck script
modifyTestScriptPage :: GETContentHandler
modifyTestScriptPage = do
tsk <- getParameter testScriptKeyPrm
(course, script) <- userStory $ do
Story.isAdministratedTestScript tsk
(script, ck) <- Story.loadTestScript tsk
(course, _gk) <- Story.loadCourse ck
return (course, script)
return $ testScriptContent (Modify (courseName course) tsk script)
postModifyTestScript :: POSTContentHandler
postModifyTestScript = do
script' <- TestScript
<$> (getParameter (stringParameter (fieldName testScriptNameField) "Test Script Name"))
<*> (getParameter (stringParameter (fieldName testScriptDescField) "Test Script Description"))
<*> (getParameter (stringParameter (fieldName testScriptNotesField) "Test Script Notes"))
<*> (replaceCrlf <$> getParameter (stringParameter (fieldName testScriptScriptField) "Test Script"))
tsk <- getParameter testScriptKeyPrm
script <- userStory $ do
(testscript, _coursekey) <- Story.loadTestScript tsk
return (script' $ tsType testscript)
return $ UA.ModifyTestScript tsk script
testScriptContent :: PageData -> IHtml
testScriptContent pd = pageDataCata checkIfThereCourses modify pd
where
checkIfThereCourses [] = hasNoCourses pd
checkIfThereCourses _ = pageContent pd
modify _ _ _ = pageContent pd
hasNoCourses :: PageData -> IHtml
hasNoCourses pd = do
msg <- getI18N
return $ do
let pageTitle = pageDataCata (const $ msg_LinkText_NewTestScript "New Test") (const3 $ msg_LinkText_ModifyTestScript "Modify Test Script") pd
Bootstrap.rowColMd12 $ p $
fromString . msg $ msg_NewTestScript_HasNoCourses "This user cannot administer any courses."
pageContent :: PageData -> IHtml
pageContent pd = do
msg <- getI18N
let textField param label valueSelector = pageDataCata
(const $ Bootstrap.textInput (fieldName param) (msg label) "")
(\_name _key script -> Bootstrap.textInputWithDefault (fieldName param) (msg label) (valueSelector script))
pd
let textArea param label valueSelector = pageDataCata
(const $ Bootstrap.textArea (fieldName param) (msg label) "")
(\_name _key script -> Bootstrap.textArea (fieldName param) (msg label) (fromString (valueSelector script)))
pd
let utf8TextArea param label valueSelector = pageDataCata
(const $ Bootstrap.utf8TextArea (fieldName param) (msg label) "")
(\_name _key script -> Bootstrap.utf8TextArea (fieldName param) (msg label) (fromString (valueSelector script)))
pd
let name = textField testScriptNameField (msg_NewTestScript_Name "Name") tsName
let description = textField testScriptDescField (msg_NewTestScript_Description "Description") tsDescription
let help = textArea testScriptNotesField (msg_NewTestScript_Notes "Help for writing test cases") tsNotes
let script = textArea testScriptScriptField (msg_NewTestScript_Script "Test script") tsScript
return $ do
postForm (routeOf $ testScriptPage pd) $ do
course msg
name
description
help
script
Bootstrap.submitButton (fieldName testScriptSaveButton) (fromString . msg $ msg_NewTestScript_Save "Commit")
Bootstrap.turnSelectionsOn
where
testScriptPage = pageDataCata (const (Pages.newTestScript ())) (\_name key _script -> Pages.modifyTestScript key ())
course msg = pageDataCata
(Bootstrap.selectionWithLabel (fieldName testScriptCourseKeyField) (msg $ msg_NewTestScript_Course "Course:")
(const False) . map (id *** courseNameAndType))
(\courseName _key _script -> fromString courseName)
pd
where
courseNameAndType c = concat
[courseName c, " - ", courseTypeStr $ courseTestScriptType c]
courseTypeStr = msg . testScriptTypeCata
(msg_TestScriptTypeSimple "Textual")
(msg_TestScriptTypeZipped "Binary")
replaceCrlf :: String -> String
replaceCrlf = replace "\r\n" "\n"
|
9b54e7e638e042e1451e8869ef93a1c89dd5b0418fc4da1769e92bb98e77578f | silky/quipper | PDF.hs | This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the
-- file COPYRIGHT for a list of authors, copyright holders, licensing,
-- and other details. All rights reserved.
--
-- ======================================================================
-- ----------------------------------------------------------------------
-- | This tool reads a circuit from standard input and converts it to
-- the graphical PDF format. The converted circuit is written to
-- standard output.
module Main where
import Quipper
import QuipperLib.QuipperASCIIParser
| Main function : read from ' stdin ' and write to ' stdout ' .
main :: IO ()
main = do
(ins,circuit) <- parse_from_stdin
print_generic PDF circuit ins
| null | https://raw.githubusercontent.com/silky/quipper/1ef6d031984923d8b7ded1c14f05db0995791633/Programs/Tools/PDF.hs | haskell | file COPYRIGHT for a list of authors, copyright holders, licensing,
and other details. All rights reserved.
======================================================================
----------------------------------------------------------------------
| This tool reads a circuit from standard input and converts it to
the graphical PDF format. The converted circuit is written to
standard output. | This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the
module Main where
import Quipper
import QuipperLib.QuipperASCIIParser
| Main function : read from ' stdin ' and write to ' stdout ' .
main :: IO ()
main = do
(ins,circuit) <- parse_from_stdin
print_generic PDF circuit ins
|
c916732f29c7e3bf42995b547477082263daaa8916f769da072e53beff0e0ab4 | YoshikuniJujo/markdown2svg | SVG.hs | # LANGUAGE QuasiQuotes #
module Image.SVG (isSVG, svgSize) where
import Control.Applicative
import Text.Papillon
import Data.Char
doctype0 :: DocType
doctype0 = DocType "svg" "-//W3C//DTD SVG 1.1//EN" ""
xmlns0 :: String
xmlns0 = ""
isSVG :: String -> Bool
isSVG svg = case getSVGHeader svg of
Just (_, d, SVG s) -> d == doctype0 && isValueOf xmlns0 s "xmlns"
_ -> False
svgSize :: String -> Maybe (Double, Double)
svgSize svg = case getSVGHeader svg of
Just (_, _, SVG s) ->
(,) <$> (read <$> lookup "width" s) <*> (read <$> lookup "height" s)
_ -> Nothing
isValueOf :: String -> [(String, String)] -> String -> Bool
isValueOf v0 dict key = case lookup key dict of
Just v -> v == v0
_ -> False
getSVGHeader :: String -> Maybe (Header, DocType, SVG)
getSVGHeader src = case runError $ svgHeader $ parse src of
Right (sh, _) -> Just sh
_ -> Nothing
getHeader :: String -> Maybe Header
getHeader src = case runError $ header $ parse src of
Right (h, _) -> Just h
_ -> Nothing
getComment :: String -> Maybe String
getComment src = case runError $ comment $ parse src of
Right (c, _) -> Just c
_ -> Nothing
getDocType :: String -> Maybe DocType
getDocType src = case runError $ doctype $ parse src of
Right (d, _) -> Just d
_ -> Nothing
data Header = Header [(String, String)] deriving Show
data DocType = DocType String String String deriving (Eq, Show)
data SVG = SVG [(String, String)] deriving Show
[papillon|
svgHeader :: (Header, DocType, SVG)
= h:header _:spccmm d:doctype _:spccmm s:svg
{ (h, d, s) }
= h : header _ : d : doctype _ : s : svg
-- { (h, d, s) }
header :: Header
= '<' '?' 'x' 'm' 'l' _:space+ vss:(vs:varstr _:space* { vs })*
'?' '>'
{ Header vss }
varstr :: (String, String)
= v:name '=' s:string { (v, s) }
name :: String
= v:variable ':' n:name { v ++ ":" ++ n }
/ v:variable { v }
variable :: String
= v:<isLower>+ { v }
string :: String
= '\'' s:<(/= '\'')>+ '\'' { s }
/ '"' s:<(/= '"')>+ '"' { s }
spccmm :: () = _:(_:space / _:comment)*
space :: ()
= _:<isSpace>
comment :: String
= '<' '!' '-' '-' cm:(!_:('-' '-' '>') c { c })* '-' '-' '>'
{ cm }
doctype :: DocType
= '<' '!' 'D' 'O' 'C' 'T' 'Y' 'P' 'E' _:space+ v:variable _:space+
'P' 'U' 'B' 'L' 'I' 'C' _:space* s1:string _:space*
s2:string _:space* '>'
{ DocType v s1 s2 }
svg :: SVG
= '<' 's' 'v' 'g' _:space+ vss:(vs:varstr _:space* { vs })* '>'
{ SVG vss }
|]
| null | https://raw.githubusercontent.com/YoshikuniJujo/markdown2svg/a4a53d2f669c124684e8beee5c1c271d9699f952/src/Image/SVG.hs | haskell | { (h, d, s) } | # LANGUAGE QuasiQuotes #
module Image.SVG (isSVG, svgSize) where
import Control.Applicative
import Text.Papillon
import Data.Char
doctype0 :: DocType
doctype0 = DocType "svg" "-//W3C//DTD SVG 1.1//EN" ""
xmlns0 :: String
xmlns0 = ""
isSVG :: String -> Bool
isSVG svg = case getSVGHeader svg of
Just (_, d, SVG s) -> d == doctype0 && isValueOf xmlns0 s "xmlns"
_ -> False
svgSize :: String -> Maybe (Double, Double)
svgSize svg = case getSVGHeader svg of
Just (_, _, SVG s) ->
(,) <$> (read <$> lookup "width" s) <*> (read <$> lookup "height" s)
_ -> Nothing
isValueOf :: String -> [(String, String)] -> String -> Bool
isValueOf v0 dict key = case lookup key dict of
Just v -> v == v0
_ -> False
getSVGHeader :: String -> Maybe (Header, DocType, SVG)
getSVGHeader src = case runError $ svgHeader $ parse src of
Right (sh, _) -> Just sh
_ -> Nothing
getHeader :: String -> Maybe Header
getHeader src = case runError $ header $ parse src of
Right (h, _) -> Just h
_ -> Nothing
getComment :: String -> Maybe String
getComment src = case runError $ comment $ parse src of
Right (c, _) -> Just c
_ -> Nothing
getDocType :: String -> Maybe DocType
getDocType src = case runError $ doctype $ parse src of
Right (d, _) -> Just d
_ -> Nothing
data Header = Header [(String, String)] deriving Show
data DocType = DocType String String String deriving (Eq, Show)
data SVG = SVG [(String, String)] deriving Show
[papillon|
svgHeader :: (Header, DocType, SVG)
= h:header _:spccmm d:doctype _:spccmm s:svg
{ (h, d, s) }
= h : header _ : d : doctype _ : s : svg
header :: Header
= '<' '?' 'x' 'm' 'l' _:space+ vss:(vs:varstr _:space* { vs })*
'?' '>'
{ Header vss }
varstr :: (String, String)
= v:name '=' s:string { (v, s) }
name :: String
= v:variable ':' n:name { v ++ ":" ++ n }
/ v:variable { v }
variable :: String
= v:<isLower>+ { v }
string :: String
= '\'' s:<(/= '\'')>+ '\'' { s }
/ '"' s:<(/= '"')>+ '"' { s }
spccmm :: () = _:(_:space / _:comment)*
space :: ()
= _:<isSpace>
comment :: String
= '<' '!' '-' '-' cm:(!_:('-' '-' '>') c { c })* '-' '-' '>'
{ cm }
doctype :: DocType
= '<' '!' 'D' 'O' 'C' 'T' 'Y' 'P' 'E' _:space+ v:variable _:space+
'P' 'U' 'B' 'L' 'I' 'C' _:space* s1:string _:space*
s2:string _:space* '>'
{ DocType v s1 s2 }
svg :: SVG
= '<' 's' 'v' 'g' _:space+ vss:(vs:varstr _:space* { vs })* '>'
{ SVG vss }
|]
|
d9612e2a78dfca410685d7fbe6e49c948b866a836b509c2a27443d8d16f24c74 | standardsemiconductor/lion | Spi.hs | |
Module : Spi
Description : Lion SoC SPI peripheral
Copyright : ( c ) , 2021
License : BSD-3 - Clause
Maintainer :
Register Map
| 31 ------- 24 | 23 ------------------------------ 16 | 15 --------- 0 |
| SysBus Status | SysBus Read / Write OR SysBus Received | SysBus Command |
SysBus Status 0 = Empty , otherwise Busy
SysBus Read / Write 0 = Read , 1 = Write
SysBus Command address = bits 15 - 8 , data=7 - 0
Module : Spi
Description : Lion SoC SPI peripheral
Copyright : (c) David Cox, 2021
License : BSD-3-Clause
Maintainer :
Register Map
| 31 ------- 24 | 23 ------------------------------ 16 | 15 --------- 0 |
| SysBus Status | SysBus Read/Write OR SysBus Received | SysBus Command |
SysBus Status 0=Empty, otherwise Busy
SysBus Read/Write 0=Read, 1=Write
SysBus Command address=bits 15-8, data=7-0
-}
module Spi where
import Clash.Prelude
import Control.Monad.RWS
import Control.Lens hiding (Index)
import Data.Maybe ( fromMaybe, isJust )
import Data.Monoid.Generic
import qualified Ice40.Spi as S
import Ice40.IO
import Bus
data SpiIO = SpiIO ("biwo" ::: Bit)
("bowi" ::: Bit)
("wck" ::: Bit)
("cs" ::: Bit)
deriving stock (Generic, Show, Eq)
deriving anyclass NFDataX
data ToSysBus = ToSysBus
{ _sbAckO :: Bool
, _sbDatO :: BitVector 8
, _fromCore :: BusIn 'Spi
}
makeLenses ''ToSysBus
data FromSysBus = FromSysBus
{ _sbRWI :: First Bool
, _sbStbI :: First Bool
, _sbAdrI :: First (BitVector 8)
, _sbDatI :: First (BitVector 8)
, _toCore :: First (BitVector 32)
}
deriving stock (Generic, Show, Eq)
deriving anyclass NFDataX
deriving Semigroup via GenericSemigroup FromSysBus
deriving Monoid via GenericMonoid FromSysBus
makeLenses ''FromSysBus
data SysBus = SysBus
{ _sbInstr :: Maybe (BitVector 8, Maybe (BitVector 8))
, _sbRecv :: BitVector 8
}
deriving stock (Generic, Show, Eq)
deriving anyclass NFDataX
makeLenses ''SysBus
mkSysBus :: SysBus
mkSysBus = SysBus Nothing 0
sysBusM :: RWS ToSysBus FromSysBus SysBus ()
sysBusM = do
instr <- use sbInstr
-- output sysbus signals
scribe sbRWI $ First $ isJust . snd <$> instr
scribe sbStbI $ First $ True <$ instr
scribe sbAdrI $ First $ fst <$> instr
scribe sbDatI $ First $ snd =<< instr
-- when ack received, set instr to Nothing indicating done
and store sbDatO in sbRecv
isAck <- view sbAckO
when isAck $ do
sbInstr .= Nothing
sbRecv <~ view sbDatO
-- handle memory requests
view fromCore >>= \case
ToSpi $(bitPattern "1111") (Just wr) -> -- command
case instr of
Just _ -> return () -- busy, ignore command
Nothing -> -- idle, execute command
let isWrite = bitToBool $ wr!(16 :: Index 32)
adri = slice d15 d8 wr
dati = slice d7 d0 wr
in sbInstr ?= if isWrite
then (adri, Just dati)
else (adri, Nothing)
ToSpi $(bitPattern "0100") Nothing -> -- read received
scribe toCore . First . Just =<< uses sbRecv ((`shiftL` 16).zeroExtend)
_ -> -- read status, default instruction
scribe toCore $ First $ Just $ if isJust instr
then 0x01000000
else 0x00000000
sysBus
:: HiddenClockResetEnable dom
=> Signal dom ToSysBus
-> Signal dom FromSysBus
sysBus = mealy sysBusMealy mkSysBus
where
sysBusMealy s i = (s', o)
where
((), s', o) = runRWS sysBusM i s
# NOINLINE spi #
spi
:: HiddenClockResetEnable dom
=> Signal dom (BusIn 'Spi)
-> Unbundled dom (SpiIO, BusOut 'Spi)
spi toSpi = (spiIO, fromSpi)
where
fromSpi = fmap (FromSpi . fromMaybe 0) $ register Nothing $ getFirst . _toCore <$> fromSysBus
fromSysBus = sysBus $ ToSysBus <$> sbacko
<*> sbdato
<*> toSpi
spiIO = SpiIO <$> biwo <*> bowi <*> wck <*> cs
(biwo, bi) = biwoIO woe wo
(bowi, wi) = bowiIO boe bo
(wck, wcki) = wckIO wckoe wcko
(cs, wcsni) = csIO bcsnoe bcsno
rwi = fromMaybe False . getFirst . _sbRWI <$> fromSysBus
stbi = fromMaybe False . getFirst . _sbStbI <$> fromSysBus
adri = fromMaybe 0 . getFirst . _sbAdrI <$> fromSysBus
dati = fromMaybe 0 . getFirst . _sbDatI <$> fromSysBus
(sbdato, sbacko, _, _, wo, woe, bo, boe, wcko, wckoe, bcsno, bcsnoe)
= S.spi "0b0000"
rwi
stbi
adri
dati
bi
wi
wcki
wcsni
# NOINLINE biwoIO #
biwoIO
:: HiddenClock dom
=> Signal dom Bit
-> Signal dom Bit
-> Unbundled dom (Bit, Bit)
biwoIO woe wo = (biwo, bi)
where
(biwo, bi, _) = io PinInput
PinNoOutput
0 -- pullUp
negTrigger
SBLVCMOS
0
0
hasClock
hasClock
woe
wo
0
# NOINLINE bowiIO #
bowiIO
:: HiddenClock dom
=> Signal dom Bit
-> Signal dom Bit
-> Unbundled dom (Bit, Bit)
bowiIO boe bo = (bowi, wi)
where
(bowi, wi, _) = io PinInput
PinOutputTristate
0 -- pullup
negTrigger
SBLVCMOS
latchInputValue
0 -- clock enable
hasClock
hasClock
boe -- output enable
bo -- dOut0
0
# NOINLINE wckIO #
wckIO
:: HiddenClock dom
=> Signal dom Bit
-> Signal dom Bit
-> Unbundled dom (Bit, Bit)
wckIO wckoe wcko = (wck, wcki)
where
(wck, wcki, _) = io PinInput
PinOutputTristate
1 -- pullUp
negTrigger
SBLVCMOS
latchInputValue
0 -- clock enable
hasClock
hasClock
wckoe
wcko
0
{-# NOINLINE csIO #-}
csIO
:: HiddenClock dom
=> Signal dom (BitVector 4)
-> Signal dom (BitVector 4)
-> Unbundled dom (Bit, Bit)
csIO bcsnoe bcsno = (cs, wcsni)
where
(cs, wcsni, _) = io PinInput
PinOutputTristate
1 -- pullUp
negTrigger
SBLVCMOS
0 -- latch input value
0 -- clock enable
hasClock
hasClock
((! (3 :: Index 4)) <$> bcsnoe) -- output enable
((! (3 :: Index 4)) <$> bcsno) -- dOut0
0 -- dOut1
| null | https://raw.githubusercontent.com/standardsemiconductor/lion/dc7bf7e6f86c752eac4cdbb75748dd18a161d777/lion-soc/src/Spi.hs | haskell | ----- 24 | 23 ------------------------------ 16 | 15 --------- 0 |
----- 24 | 23 ------------------------------ 16 | 15 --------- 0 |
output sysbus signals
when ack received, set instr to Nothing indicating done
handle memory requests
command
busy, ignore command
idle, execute command
read received
read status, default instruction
pullUp
pullup
clock enable
output enable
dOut0
pullUp
clock enable
# NOINLINE csIO #
pullUp
latch input value
clock enable
output enable
dOut0
dOut1 | |
Module : Spi
Description : Lion SoC SPI peripheral
Copyright : ( c ) , 2021
License : BSD-3 - Clause
Maintainer :
Register Map
| SysBus Status | SysBus Read / Write OR SysBus Received | SysBus Command |
SysBus Status 0 = Empty , otherwise Busy
SysBus Read / Write 0 = Read , 1 = Write
SysBus Command address = bits 15 - 8 , data=7 - 0
Module : Spi
Description : Lion SoC SPI peripheral
Copyright : (c) David Cox, 2021
License : BSD-3-Clause
Maintainer :
Register Map
| SysBus Status | SysBus Read/Write OR SysBus Received | SysBus Command |
SysBus Status 0=Empty, otherwise Busy
SysBus Read/Write 0=Read, 1=Write
SysBus Command address=bits 15-8, data=7-0
-}
module Spi where
import Clash.Prelude
import Control.Monad.RWS
import Control.Lens hiding (Index)
import Data.Maybe ( fromMaybe, isJust )
import Data.Monoid.Generic
import qualified Ice40.Spi as S
import Ice40.IO
import Bus
data SpiIO = SpiIO ("biwo" ::: Bit)
("bowi" ::: Bit)
("wck" ::: Bit)
("cs" ::: Bit)
deriving stock (Generic, Show, Eq)
deriving anyclass NFDataX
data ToSysBus = ToSysBus
{ _sbAckO :: Bool
, _sbDatO :: BitVector 8
, _fromCore :: BusIn 'Spi
}
makeLenses ''ToSysBus
data FromSysBus = FromSysBus
{ _sbRWI :: First Bool
, _sbStbI :: First Bool
, _sbAdrI :: First (BitVector 8)
, _sbDatI :: First (BitVector 8)
, _toCore :: First (BitVector 32)
}
deriving stock (Generic, Show, Eq)
deriving anyclass NFDataX
deriving Semigroup via GenericSemigroup FromSysBus
deriving Monoid via GenericMonoid FromSysBus
makeLenses ''FromSysBus
data SysBus = SysBus
{ _sbInstr :: Maybe (BitVector 8, Maybe (BitVector 8))
, _sbRecv :: BitVector 8
}
deriving stock (Generic, Show, Eq)
deriving anyclass NFDataX
makeLenses ''SysBus
mkSysBus :: SysBus
mkSysBus = SysBus Nothing 0
sysBusM :: RWS ToSysBus FromSysBus SysBus ()
sysBusM = do
instr <- use sbInstr
scribe sbRWI $ First $ isJust . snd <$> instr
scribe sbStbI $ First $ True <$ instr
scribe sbAdrI $ First $ fst <$> instr
scribe sbDatI $ First $ snd =<< instr
and store sbDatO in sbRecv
isAck <- view sbAckO
when isAck $ do
sbInstr .= Nothing
sbRecv <~ view sbDatO
view fromCore >>= \case
case instr of
let isWrite = bitToBool $ wr!(16 :: Index 32)
adri = slice d15 d8 wr
dati = slice d7 d0 wr
in sbInstr ?= if isWrite
then (adri, Just dati)
else (adri, Nothing)
scribe toCore . First . Just =<< uses sbRecv ((`shiftL` 16).zeroExtend)
scribe toCore $ First $ Just $ if isJust instr
then 0x01000000
else 0x00000000
sysBus
:: HiddenClockResetEnable dom
=> Signal dom ToSysBus
-> Signal dom FromSysBus
sysBus = mealy sysBusMealy mkSysBus
where
sysBusMealy s i = (s', o)
where
((), s', o) = runRWS sysBusM i s
# NOINLINE spi #
spi
:: HiddenClockResetEnable dom
=> Signal dom (BusIn 'Spi)
-> Unbundled dom (SpiIO, BusOut 'Spi)
spi toSpi = (spiIO, fromSpi)
where
fromSpi = fmap (FromSpi . fromMaybe 0) $ register Nothing $ getFirst . _toCore <$> fromSysBus
fromSysBus = sysBus $ ToSysBus <$> sbacko
<*> sbdato
<*> toSpi
spiIO = SpiIO <$> biwo <*> bowi <*> wck <*> cs
(biwo, bi) = biwoIO woe wo
(bowi, wi) = bowiIO boe bo
(wck, wcki) = wckIO wckoe wcko
(cs, wcsni) = csIO bcsnoe bcsno
rwi = fromMaybe False . getFirst . _sbRWI <$> fromSysBus
stbi = fromMaybe False . getFirst . _sbStbI <$> fromSysBus
adri = fromMaybe 0 . getFirst . _sbAdrI <$> fromSysBus
dati = fromMaybe 0 . getFirst . _sbDatI <$> fromSysBus
(sbdato, sbacko, _, _, wo, woe, bo, boe, wcko, wckoe, bcsno, bcsnoe)
= S.spi "0b0000"
rwi
stbi
adri
dati
bi
wi
wcki
wcsni
# NOINLINE biwoIO #
biwoIO
:: HiddenClock dom
=> Signal dom Bit
-> Signal dom Bit
-> Unbundled dom (Bit, Bit)
biwoIO woe wo = (biwo, bi)
where
(biwo, bi, _) = io PinInput
PinNoOutput
negTrigger
SBLVCMOS
0
0
hasClock
hasClock
woe
wo
0
# NOINLINE bowiIO #
bowiIO
:: HiddenClock dom
=> Signal dom Bit
-> Signal dom Bit
-> Unbundled dom (Bit, Bit)
bowiIO boe bo = (bowi, wi)
where
(bowi, wi, _) = io PinInput
PinOutputTristate
negTrigger
SBLVCMOS
latchInputValue
hasClock
hasClock
0
# NOINLINE wckIO #
wckIO
:: HiddenClock dom
=> Signal dom Bit
-> Signal dom Bit
-> Unbundled dom (Bit, Bit)
wckIO wckoe wcko = (wck, wcki)
where
(wck, wcki, _) = io PinInput
PinOutputTristate
negTrigger
SBLVCMOS
latchInputValue
hasClock
hasClock
wckoe
wcko
0
csIO
:: HiddenClock dom
=> Signal dom (BitVector 4)
-> Signal dom (BitVector 4)
-> Unbundled dom (Bit, Bit)
csIO bcsnoe bcsno = (cs, wcsni)
where
(cs, wcsni, _) = io PinInput
PinOutputTristate
negTrigger
SBLVCMOS
hasClock
hasClock
|
c1e73cb52d4e16d34ccd8f1e33a86f731c311d2748f37dcd46e51bad71b26f0f | jellelicht/guix | r.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix build-system r)
#:use-module (guix store)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix derivations)
#:use-module (guix search-paths)
#:use-module (guix build-system)
#:use-module (guix build-system gnu)
#:use-module (ice-9 match)
#:use-module (srfi srfi-26)
#:export (%r-build-system-modules
r-build
r-build-system
cran-uri
bioconductor-uri))
;; Commentary:
;;
;; Standard build procedure for R packages.
;;
;; Code:
(define (cran-uri name version)
"Return a list of URI strings for the R package archive on CRAN for the
release corresponding to NAME and VERSION. As only the most recent version is
available via the first URI, the second URI points to the archived version."
(list (string-append "mirror/"
name "_" version ".tar.gz")
(string-append "mirror/"
name "/" name "_" version ".tar.gz")))
(define (bioconductor-uri name version)
"Return a URI string for the R package archive on Bioconductor for the
release corresponding to NAME and VERSION."
(string-append "/"
name "_" version ".tar.gz"))
(define %r-build-system-modules
;; Build-side modules imported by default.
`((guix build r-build-system)
,@%gnu-build-system-modules))
(define (default-r)
"Return the default R package."
;; Lazily resolve the binding to avoid a circular dependency.
(let ((r-mod (resolve-interface '(gnu packages statistics))))
(module-ref r-mod 'r)))
(define* (lower name
#:key source inputs native-inputs outputs system target
(r (default-r))
#:allow-other-keys
#:rest arguments)
"Return a bag for NAME."
(define private-keywords
'(#:source #:target #:inputs #:native-inputs))
(and (not target) ;XXX: no cross-compilation
(bag
(name name)
(system system)
(host-inputs `(,@(if source
`(("source" ,source))
'())
,@inputs
;; Keep the standard inputs of 'gnu-build-system'.
,@(standard-packages)))
(build-inputs `(("r" ,r)
,@native-inputs))
(outputs outputs)
(build r-build)
(arguments (strip-keyword-arguments private-keywords arguments)))))
(define* (r-build store name inputs
#:key
(tests? #t)
(test-target "tests")
(configure-flags ''())
(phases '(@ (guix build r-build-system)
%standard-phases))
(outputs '("out"))
(search-paths '())
(system (%current-system))
(guile #f)
(imported-modules %r-build-system-modules)
(modules '((guix build r-build-system)
(guix build utils))))
"Build SOURCE with INPUTS."
(define builder
`(begin
(use-modules ,@modules)
(r-build #:name ,name
#:source ,(match (assoc-ref inputs "source")
(((? derivation? source))
(derivation->output-path source))
((source)
source)
(source
source))
#:configure-flags ,configure-flags
#:system ,system
#:tests? ,tests?
#:test-target ,test-target
#:phases ,phases
#:outputs %outputs
#:search-paths ',(map search-path-specification->sexp
search-paths)
#:inputs %build-inputs)))
(define guile-for-build
(match guile
((? package?)
(package-derivation store guile system #:graft? #f))
(#f ; the default
(let* ((distro (resolve-interface '(gnu packages commencement)))
(guile (module-ref distro 'guile-final)))
(package-derivation store guile system #:graft? #f)))))
(build-expression->derivation store name builder
#:inputs inputs
#:system system
#:modules imported-modules
#:outputs outputs
#:guile-for-build guile-for-build))
(define r-build-system
(build-system
(name 'r)
(description "The standard R build system")
(lower lower)))
;;; r.scm ends here
| null | https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/guix/build-system/r.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Commentary:
Standard build procedure for R packages.
Code:
Build-side modules imported by default.
Lazily resolve the binding to avoid a circular dependency.
XXX: no cross-compilation
Keep the standard inputs of 'gnu-build-system'.
the default
r.scm ends here | Copyright © 2015 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix build-system r)
#:use-module (guix store)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix derivations)
#:use-module (guix search-paths)
#:use-module (guix build-system)
#:use-module (guix build-system gnu)
#:use-module (ice-9 match)
#:use-module (srfi srfi-26)
#:export (%r-build-system-modules
r-build
r-build-system
cran-uri
bioconductor-uri))
(define (cran-uri name version)
"Return a list of URI strings for the R package archive on CRAN for the
release corresponding to NAME and VERSION. As only the most recent version is
available via the first URI, the second URI points to the archived version."
(list (string-append "mirror/"
name "_" version ".tar.gz")
(string-append "mirror/"
name "/" name "_" version ".tar.gz")))
(define (bioconductor-uri name version)
"Return a URI string for the R package archive on Bioconductor for the
release corresponding to NAME and VERSION."
(string-append "/"
name "_" version ".tar.gz"))
(define %r-build-system-modules
`((guix build r-build-system)
,@%gnu-build-system-modules))
(define (default-r)
"Return the default R package."
(let ((r-mod (resolve-interface '(gnu packages statistics))))
(module-ref r-mod 'r)))
(define* (lower name
#:key source inputs native-inputs outputs system target
(r (default-r))
#:allow-other-keys
#:rest arguments)
"Return a bag for NAME."
(define private-keywords
'(#:source #:target #:inputs #:native-inputs))
(bag
(name name)
(system system)
(host-inputs `(,@(if source
`(("source" ,source))
'())
,@inputs
,@(standard-packages)))
(build-inputs `(("r" ,r)
,@native-inputs))
(outputs outputs)
(build r-build)
(arguments (strip-keyword-arguments private-keywords arguments)))))
(define* (r-build store name inputs
#:key
(tests? #t)
(test-target "tests")
(configure-flags ''())
(phases '(@ (guix build r-build-system)
%standard-phases))
(outputs '("out"))
(search-paths '())
(system (%current-system))
(guile #f)
(imported-modules %r-build-system-modules)
(modules '((guix build r-build-system)
(guix build utils))))
"Build SOURCE with INPUTS."
(define builder
`(begin
(use-modules ,@modules)
(r-build #:name ,name
#:source ,(match (assoc-ref inputs "source")
(((? derivation? source))
(derivation->output-path source))
((source)
source)
(source
source))
#:configure-flags ,configure-flags
#:system ,system
#:tests? ,tests?
#:test-target ,test-target
#:phases ,phases
#:outputs %outputs
#:search-paths ',(map search-path-specification->sexp
search-paths)
#:inputs %build-inputs)))
(define guile-for-build
(match guile
((? package?)
(package-derivation store guile system #:graft? #f))
(let* ((distro (resolve-interface '(gnu packages commencement)))
(guile (module-ref distro 'guile-final)))
(package-derivation store guile system #:graft? #f)))))
(build-expression->derivation store name builder
#:inputs inputs
#:system system
#:modules imported-modules
#:outputs outputs
#:guile-for-build guile-for-build))
(define r-build-system
(build-system
(name 'r)
(description "The standard R build system")
(lower lower)))
|
847145ff8b4d6a60cb5585a3cc5ce6459a3195ca9431dbb94bd9fd98fdc99f1a | 2600hz-archive/whistle | ts_cdr.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2010 - 2011 , VoIP INC
%%% @doc
Receive a callmgr CDR and augment it with Trunkstore - specific fields ,
%%% storing it in the database.
If the CDR is already stored ( from another Trunkstore app ) , the save_doc/2
%%% should cause the process to crash, not storing it again.
%%% @end
Created : 24 Nov 2010 by < >
%%%-------------------------------------------------------------------
-module(ts_cdr).
-export([start_link/0, store_cdr/3, fetch_cdr/2, store/1]).
-include("ts.hrl").
start_link() ->
{ok, proc_lib:spawn_link(fun cdr_init/0)}.
cdr_init() ->
{_, {H,Min,S}} = calendar:universal_time(),
MillisecsToMidnight = ?MILLISECS_PER_DAY - timer:hms(H,Min,S),
_ = create_cdr_db(ts_util:todays_db_name(?TS_CDR_PREFIX)),
cdr_loop(MillisecsToMidnight).
cdr_loop(Timeout) ->
receive
after
Timeout ->
_ = create_cdr_db(ts_util:todays_db_name(?TS_CDR_PREFIX)),
cdr_loop(?MILLISECS_PER_DAY)
end.
create_cdr_db(DB) ->
couch_mgr:db_create(DB),
case couch_mgr:load_doc_from_file(DB, trunkstore, <<"ts_cdr.json">>) of
{ok, _} -> ok;
{error, _} -> couch_mgr:update_doc_from_file(DB, trunkstore, <<"ts_cdr.json">>)
end.
-spec store/1 :: (CDR) -> tuple(ok, json_object()) | tuple(error, atom()) when
CDR :: json_object().
store(CDR) ->
DB = ts_util:todays_db_name(?TS_CDR_PREFIX),
CDR1 = wh_json:set_value(<<"_id">>, wh_json:get_value(<<"Call-ID">>, CDR), CDR),
couch_mgr:save_doc(DB, CDR1).
-spec(store_cdr/3 :: (CDR :: json_object(), Flags :: #route_flags{}, DB :: binary()) -> no_return()).
store_cdr({struct, CDRProp}=CDRJObj, #route_flags{routes_generated=RGs, direction=Dir, account_doc_id=DocID, rate_name=RateName}, DB) ->
TScdr = [{<<"_id">>, wh_json:get_value(<<"Call-ID">>, CDRJObj)}
,{<<"Routes-Available">>, RGs}
,{<<"Route-Used">>, find_route_used(Dir, wh_json:get_value(<<"To-Uri">>, CDRJObj), RGs)}
,{<<"Rate-Used">>, RateName}
,{<<"Customer-Account-ID">>, DocID}
| CDRProp],
couch_mgr:save_doc(DB, TScdr).
-spec find_route_used/3 :: (Direction, ToUri, Routes) -> json_object() when
Direction :: binary(),
ToUri :: binary(),
Routes :: json_object() | json_objects().
find_route_used(Dir, To, {struct,_}=Route) ->
find_route_used(Dir, To, [Route]);
find_route_used(<<"outbound">>, ToUri, Routes) ->
[ToUser, _ToDomain] = binary:split(ToUri, <<"@">>),
lists:foldl(fun(RouteJObj, Acc) ->
case wh_json:get_value(<<"Route">>, RouteJObj) of
<<"sip:", DS/binary>> ->
[DSUser, DSDomain] = binary:split(DS, <<"@">>),
DS_IP = wh_util:to_binary(ts_util:find_ip(DSDomain)),
case binary:match(<<DSUser/bitstring, "@", DS_IP/bitstring>>, ToUri) =/= nomatch orelse
binary:match(DS, ToUri) of
true -> RouteJObj; % Matched by IP
nomatch -> Acc; % neither matched
_ -> RouteJObj % matched by hostname
end;
[<<"user:", _U/binary>>, DID] ->
case wh_util:to_e164(ToUser) =:= wh_util:to_e164(DID) of
true -> RouteJObj;
false -> Acc
end
end
end, ?EMPTY_JSON_OBJECT, Routes);
find_route_used(<<"inbound">>, _, _) -> ?EMPTY_JSON_OBJECT.
-spec fetch_cdr/2 :: (CallID, DB) -> {'error', 'not_found'} | {'ok', json_object()} when
CallID :: binary(),
DB :: binary().
fetch_cdr(CallID, DB) ->
case couch_mgr:open_doc(DB, CallID) of
{error, _} ->
{error, not_found};
{ok, _}=Resp ->
Resp
end.
| null | https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/whistle_apps/apps/trunkstore/src/ts_cdr.erl | erlang | -------------------------------------------------------------------
@doc
storing it in the database.
should cause the process to crash, not storing it again.
@end
-------------------------------------------------------------------
Matched by IP
neither matched
matched by hostname | @author < >
( C ) 2010 - 2011 , VoIP INC
Receive a callmgr CDR and augment it with Trunkstore - specific fields ,
If the CDR is already stored ( from another Trunkstore app ) , the save_doc/2
Created : 24 Nov 2010 by < >
-module(ts_cdr).
-export([start_link/0, store_cdr/3, fetch_cdr/2, store/1]).
-include("ts.hrl").
start_link() ->
{ok, proc_lib:spawn_link(fun cdr_init/0)}.
cdr_init() ->
{_, {H,Min,S}} = calendar:universal_time(),
MillisecsToMidnight = ?MILLISECS_PER_DAY - timer:hms(H,Min,S),
_ = create_cdr_db(ts_util:todays_db_name(?TS_CDR_PREFIX)),
cdr_loop(MillisecsToMidnight).
cdr_loop(Timeout) ->
receive
after
Timeout ->
_ = create_cdr_db(ts_util:todays_db_name(?TS_CDR_PREFIX)),
cdr_loop(?MILLISECS_PER_DAY)
end.
create_cdr_db(DB) ->
couch_mgr:db_create(DB),
case couch_mgr:load_doc_from_file(DB, trunkstore, <<"ts_cdr.json">>) of
{ok, _} -> ok;
{error, _} -> couch_mgr:update_doc_from_file(DB, trunkstore, <<"ts_cdr.json">>)
end.
-spec store/1 :: (CDR) -> tuple(ok, json_object()) | tuple(error, atom()) when
CDR :: json_object().
store(CDR) ->
DB = ts_util:todays_db_name(?TS_CDR_PREFIX),
CDR1 = wh_json:set_value(<<"_id">>, wh_json:get_value(<<"Call-ID">>, CDR), CDR),
couch_mgr:save_doc(DB, CDR1).
-spec(store_cdr/3 :: (CDR :: json_object(), Flags :: #route_flags{}, DB :: binary()) -> no_return()).
store_cdr({struct, CDRProp}=CDRJObj, #route_flags{routes_generated=RGs, direction=Dir, account_doc_id=DocID, rate_name=RateName}, DB) ->
TScdr = [{<<"_id">>, wh_json:get_value(<<"Call-ID">>, CDRJObj)}
,{<<"Routes-Available">>, RGs}
,{<<"Route-Used">>, find_route_used(Dir, wh_json:get_value(<<"To-Uri">>, CDRJObj), RGs)}
,{<<"Rate-Used">>, RateName}
,{<<"Customer-Account-ID">>, DocID}
| CDRProp],
couch_mgr:save_doc(DB, TScdr).
-spec find_route_used/3 :: (Direction, ToUri, Routes) -> json_object() when
Direction :: binary(),
ToUri :: binary(),
Routes :: json_object() | json_objects().
find_route_used(Dir, To, {struct,_}=Route) ->
find_route_used(Dir, To, [Route]);
find_route_used(<<"outbound">>, ToUri, Routes) ->
[ToUser, _ToDomain] = binary:split(ToUri, <<"@">>),
lists:foldl(fun(RouteJObj, Acc) ->
case wh_json:get_value(<<"Route">>, RouteJObj) of
<<"sip:", DS/binary>> ->
[DSUser, DSDomain] = binary:split(DS, <<"@">>),
DS_IP = wh_util:to_binary(ts_util:find_ip(DSDomain)),
case binary:match(<<DSUser/bitstring, "@", DS_IP/bitstring>>, ToUri) =/= nomatch orelse
binary:match(DS, ToUri) of
end;
[<<"user:", _U/binary>>, DID] ->
case wh_util:to_e164(ToUser) =:= wh_util:to_e164(DID) of
true -> RouteJObj;
false -> Acc
end
end
end, ?EMPTY_JSON_OBJECT, Routes);
find_route_used(<<"inbound">>, _, _) -> ?EMPTY_JSON_OBJECT.
-spec fetch_cdr/2 :: (CallID, DB) -> {'error', 'not_found'} | {'ok', json_object()} when
CallID :: binary(),
DB :: binary().
fetch_cdr(CallID, DB) ->
case couch_mgr:open_doc(DB, CallID) of
{error, _} ->
{error, not_found};
{ok, _}=Resp ->
Resp
end.
|
7a969e39ebaa45265382673097c1914926aea9d6c026f6923403cb9ef19228cd | rjohnsondev/haskellshop | Categories.hs | # LANGUAGE OverloadedStrings , ScopedTypeVariables #
module Admin.Categories where
import Admin.Feedback
import Application
import Control.Applicative
import FormUtil
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Heist
import qualified Data.Map as M
import qualified Data.Text.Encoding as DTE
import qualified ShopData.Category as Cat
handleNewCategory :: AppHandler ()
handleNewCategory = do
name <- getFormByteString "category-name" ""
pcid <- getFormInt "new-category-parent-id" 0
let pcidm = if pcid == 0 then Nothing
else Just pcid
with db $ Cat.addCategory (DTE.decodeUtf8 name) pcidm
infoRedirect "/admin/categories" "New Category Added"
handleDelCategory :: AppHandler ()
handleDelCategory = do
cid <- getFormInt "del-category-id" 0
ncid <- getFormInt "del-new-category-id" 0
resp ncid cid
where
resp ncid cid
| ncid == 0 = dangerRedirect "/admin/categories"
"Refusing to move products to non-existant category"
| ncid == cid = dangerRedirect "/admin/categories"
"Refusing to move products to category you are deleting!"
| otherwise = do
with db $ Cat.delCategory cid ncid
infoRedirect "/admin/categories" "Category Deleted"
moveCategory :: Bool -> AppHandler ()
moveCategory down = do
let key = if down then "category-move-down" else "category-move-up"
cid <- getFormInt key 0
if cid == 0
then dangerRedirect "/admin/categories" "Attempted to move missing category"
else do
mc <- with db $ Cat.getCategory cid
case mc of Nothing -> return ()
Just c -> with db $ Cat.moveCategory c down
infoRedirect "/admin/categories" "Category Moved"
handleCategories :: AppHandler ()
handleCategories = method GET handleCategoriesGet <|> method POST handleCategoriesPost
where
handleCategoriesGet = cRender "admin/_categories"
handler p
| "category-move-down" `M.member` p = moveCategory True
| "category-move-up" `M.member` p = moveCategory False
| "new-category" `M.member` p = handleNewCategory
| "del-category-id" `M.member` p = handleDelCategory
| otherwise = redirect "/admin/categories"
handleCategoriesPost = do
p <- getParams
handler p
| null | https://raw.githubusercontent.com/rjohnsondev/haskellshop/645f9e40b9843fc987d37a0ee58460929ef50aae/src/Admin/Categories.hs | haskell | # LANGUAGE OverloadedStrings , ScopedTypeVariables #
module Admin.Categories where
import Admin.Feedback
import Application
import Control.Applicative
import FormUtil
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Heist
import qualified Data.Map as M
import qualified Data.Text.Encoding as DTE
import qualified ShopData.Category as Cat
handleNewCategory :: AppHandler ()
handleNewCategory = do
name <- getFormByteString "category-name" ""
pcid <- getFormInt "new-category-parent-id" 0
let pcidm = if pcid == 0 then Nothing
else Just pcid
with db $ Cat.addCategory (DTE.decodeUtf8 name) pcidm
infoRedirect "/admin/categories" "New Category Added"
handleDelCategory :: AppHandler ()
handleDelCategory = do
cid <- getFormInt "del-category-id" 0
ncid <- getFormInt "del-new-category-id" 0
resp ncid cid
where
resp ncid cid
| ncid == 0 = dangerRedirect "/admin/categories"
"Refusing to move products to non-existant category"
| ncid == cid = dangerRedirect "/admin/categories"
"Refusing to move products to category you are deleting!"
| otherwise = do
with db $ Cat.delCategory cid ncid
infoRedirect "/admin/categories" "Category Deleted"
moveCategory :: Bool -> AppHandler ()
moveCategory down = do
let key = if down then "category-move-down" else "category-move-up"
cid <- getFormInt key 0
if cid == 0
then dangerRedirect "/admin/categories" "Attempted to move missing category"
else do
mc <- with db $ Cat.getCategory cid
case mc of Nothing -> return ()
Just c -> with db $ Cat.moveCategory c down
infoRedirect "/admin/categories" "Category Moved"
handleCategories :: AppHandler ()
handleCategories = method GET handleCategoriesGet <|> method POST handleCategoriesPost
where
handleCategoriesGet = cRender "admin/_categories"
handler p
| "category-move-down" `M.member` p = moveCategory True
| "category-move-up" `M.member` p = moveCategory False
| "new-category" `M.member` p = handleNewCategory
| "del-category-id" `M.member` p = handleDelCategory
| otherwise = redirect "/admin/categories"
handleCategoriesPost = do
p <- getParams
handler p
| |
2c6ad2c3729ed935caa05bbaed4de93759533417015deb8530988fb220d332a3 | kyleburton/clj-xpath | core.clj | (ns clj-xpath.test.core
(:use [clojure.test]
[clj-xpath.core :as xp
:only [$x $x:tag $x:text $x:attrs $x:attrs* $x:node $x:tag? $x:text? $x:tag+ $x:text+ xp:compile tag xml->doc *xpath-compiler* *namespace-aware* nscontext xmlnsmap-from-root-node with-namespace-context abs-path]]))
(def xml-fixtures {:simple (tag :top-tag "this is a foo")
:attrs (tag [:top-tag :name "bobby tables"]
"drop tables")
:nested (tag :top-tag
(tag :inner-tag
(tag :more-inner "inner tag body")))
:namespaces (slurp "fixtures/namespace1.xml")})
(deftest test-xml->doc
(is (isa? (class (xp/xml->doc (:simple xml-fixtures))) org.w3c.dom.Document))
(is (isa? (class (xp/xml->doc (.getBytes ^String (:simple xml-fixtures))))
org.w3c.dom.Document))
(is (isa? (class (xp/xml->doc (xp/xml->doc (:simple xml-fixtures))))
org.w3c.dom.Document)))
(deftest test-$x-top-tag
(is (= :top-tag
($x:tag "/*" (:simple xml-fixtures)))))
(deftest test-$x-get-body
(is (= "this is a foo"
($x:text "/*" (:simple xml-fixtures)))))
(deftest test-$x-get-attrs
(is (= "bobby tables"
(:name
($x:attrs "/*" (:attrs xml-fixtures))))))
(deftest test-$x-attrs*
(is (= [{:name "bobby tables"}]
($x:attrs* "/*" (:attrs xml-fixtures))))
(is (= ["bobby tables"]
($x:attrs* "/*" (:attrs xml-fixtures) :name))))
(deftest test-$x-node
(is (= "top-tag"
(.getNodeName ^org.w3c.dom.Node ($x:node "/*" (:simple xml-fixtures))))))
(deftest test-$x-on-result
(is (= :more-inner
($x:tag "./*"
($x:node "/top-tag/*" (:nested xml-fixtures))))))
(deftest compile-should-compile-strings
(is (isa?
(class (xp:compile "//*"))
javax.xml.xpath.XPathExpression)))
(deftest compile-should-return-compiled-xpath-expr
(is (isa?
(class (xp:compile (xp:compile "//*")))
javax.xml.xpath.XPathExpression)))
(deftest $x-should-support-precompiled-xpath-expressions
(let [expr (xp:compile "/*")
doc (xml->doc (:simple xml-fixtures))]
(is (= :top-tag
($x:tag expr doc)))))
(deftest should-support-input-stream-as-xml-source
(with-open [istr (java.io.ByteArrayInputStream. (.getBytes ^String (:simple xml-fixtures)))]
(is (= :top-tag
($x:tag "/*" istr)))))
(deftest test-zero-or-one-results
(is (not ($x:tag? "/foo" (:simple xml-fixtures))))
(is (= :top-tag ($x:tag? "/*" (:simple xml-fixtures))))
(is (not ($x:text? "/foo" (:simple xml-fixtures))))
(is (= "this is a foo" ($x:text? "/*" (:simple xml-fixtures)))))
(deftest test-zero-or-more-results
(is (thrown? Exception ($x:tag+ "/foo" (:simple xml-fixtures))))
(is (= :top-tag (first ($x:tag+ "/*" (:simple xml-fixtures)))))
(is (thrown? Exception ($x:text+ "/foo" (:simple xml-fixtures))))
(is (= "this is a foo" (first ($x:text+ "/*" (:simple xml-fixtures))))))
(deftest test-namespace
(.setNamespaceContext
*xpath-compiler*
(nscontext {"atom" ""}))
(binding [*namespace-aware* true]
(is (= "BookingCollection" ($x:text "//atom:title" (:namespaces xml-fixtures))))))
(deftest test-with-ns-context-macro
(with-namespace-context
(xmlnsmap-from-root-node (:namespaces xml-fixtures))
(is (= "BookingCollection" ($x:text "//atom:title" (:namespaces xml-fixtures))))))
;; *clojure-version*
{ : major 1 , : minor 5 , : incremental 1 , : qualifier nil }
(defmacro compile-when-1.3-or-greater [& body]
(if (and
(>= (:major *clojure-version*) 1)
(>= (:minor *clojure-version*) 3))
`(do
~@body)
nil))
(deftest test-lazy-children
(is (nil? (:children ($x "/top-tag/*" (:simple xml-fixtures)))))
(compile-when-1.3-or-greater
(is (not (realized? (:children (first ($x "/top-tag/*" (:nested xml-fixtures))))))))
(is (= "inner tag body" (:text (first (deref (:children (first ($x "/top-tag/*" (:nested xml-fixtures))))))))))
(def labels-xml "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<labels>
<label added=\"2003-06-20\">
<quote>
<emph>Midwinter Spring</emph> is its own season…
</quote>
<name>Thomas Eliot</name>
<address>
<street>3 Prufrock Lane</street>
<city>Stamford</city>
<state>CT</state>
</address>
</label>
<label added=\"2003-06-10\">
<name>Ezra Pound</name>
<address>
<street>45 Usura Place</street>
<city>Hailey</city>
<state>ID</state>
</address>
</label>
</labels>")
(deftest test-absolute-paths
(let [dom (xml->doc labels-xml)
root (first ($x "/labels" dom))
children @(:children root)
attrs ($x "//attribute::*" dom)]
(is (= "/labels[1]" (abs-path root)))
(is (= "/labels[1]/text()[1]" (abs-path (first children))))
(is (= "/labels[1]/label[1]" (abs-path (second children))))
(is (= "/labels[1]/text()[2]" (abs-path (nth children 2))))
(is (= "/labels[1]/label[2]" (abs-path (nth children 3))))
(is (= "/labels[1]/text()[3]" (abs-path (nth children 4))))
(is (= "/labels[1]/label[1]/@added" (abs-path (first attrs))))
(is (= "/labels[1]/label[2]/@added" (abs-path (second attrs))))))
(def dtd-xml
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE eSearchResult PUBLIC \"-//NLM//DTD esearch 20060628//EN\" \"\">
<eSearchResult><Count>21486</Count><RetMax>10</RetMax><RetStart>0</RetStart><IdList>
<Id>26651117</Id><Id>26651111</Id><Id>26651108</Id><Id>26651106</Id>
<Id>26651105</Id><Id>26651078</Id><Id>26651075</Id><Id>26651033</Id></IdList></eSearchResult>")
(deftest test-external-dtd-skipping
(let [opts {:disallow-doctype-decl false}]
;; should not throw
(is (not (false? (try (xml->doc dtd-xml opts)
(catch Exception e false)))))))
The document soap1.xml uses 3 namepsaces . The 3rd is implicit / blank in the SOAP Body element .
(deftest test-with-blank-ns
(let [xml (slurp "fixtures/soap1.xml")]
(xp/with-namespace-awareness
(let [doc (xp/xml->doc xml)]
(xp/set-namespace-context! (xp/xmlnsmap-from-document doc))
(is (= :OTA_HotelAvailRQ (xp/$x:tag "/soapenv:Envelope/soapenv:Body/:OTA_HotelAvailRQ" doc)))))))
#_(deftest test-abs-path-with-blank-namespace
(let [xml (slurp "fixtures/soap1.xml")]
(xp/with-namespace-awareness
(let [doc (xp/xml->doc xml)]
(xp/set-namespace-context! (xp/xmlnsmap-from-document doc))
(is (= "/soapenv:Envelope[1]/soapenv:Body[1]/:OTA_HotelAvailRQ[1]"
(xp/abs-path (first (xp/$x "/soapenv:Envelope[1]/soapenv:Body[1]/:OTA_HotelAvailRQ[1]" doc)))))))))
(deftest test-owasp-xxe-processing-vulnerability
(is
(thrown?
org.xml.sax.SAXParseException
(xml->doc
"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY xxe SYSTEM \"file\">
]><foo>&xxe;</foo>")))
(is
(not
(nil?
(xml->doc
"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY xxe SYSTEM \"file\">
]><foo>&xxe;</foo>"
{:disallow-doctype-decl false})))))
(comment
(test-owasp-xxe-processing-vulnerability)
(test-with-blank-ns)
(with-namespace-context {"atom" ""}
($x:text "//atom:title" (:namespaces xml-fixtures)))
(with-namespace-context (xmlnsmap-from-root-node (:namespaces xml-fixtures))
($x:text "//atom:title" (:namespaces xml-fixtures)))
(run-tests)
(let [doc (slurp "sabre.xml")
xp (str "/soapenv:Envelope/soapenv:Body/:OTA_HotelAvailRQ/"
":AvailRequestSegments/:AvailRequestSegment/"
":HotelSearchCriteria/:Criterion/:HotelRef")
ns-map {"soapenv" "/"
"head" "/"
"" ""}]
(xp/with-namespace-context ns-map
(xp/$x:attrs* xp doc :HotelCode)))
= > ( " 11206 " )
(let [doc (slurp "sabre.xml")
ns-map {"soapenv" "/"
"head" "/"}]
(xp/with-namespace-context ns-map
(let [node (xp/$x:node "/soapenv:Envelope/soapenv:Body/*" doc)]
#_(xp/set-namespace-context! {"" ""})
(xp/xmlnsmap-from-node node)
#_(xp/$x:tag "./:OTA_HotelAvailRQ" node))))
(defn get-soap-body [xml]
(xp/with-namespace-awareness
(let [doc (xp/xml->doc xml)]
(xp/set-namespace-context! (xp/xmlnsmap-from-root-node doc))
(xp/node->xml (xp/$x:node "/soapenv:Envelope/soapenv:Body/*" doc)))))
(let [orig-xml (slurp "sabre.xml")
body-xml (xp/xml->doc (get-soap-body orig-xml))]
(xp/$x:attrs* "/OTA_HotelAvailRQ/AvailRequestSegments/AvailRequestSegment/HotelSearchCriteria/Criterion/HotelRef" body-xml :HotelCode))
("11206")
)
| null | https://raw.githubusercontent.com/kyleburton/clj-xpath/24f7067e418e08eec9d412c5abb9f4983fa21f10/test/clj_xpath/test/core.clj | clojure | *clojure-version*
should not throw
</foo>")))
</foo>" | (ns clj-xpath.test.core
(:use [clojure.test]
[clj-xpath.core :as xp
:only [$x $x:tag $x:text $x:attrs $x:attrs* $x:node $x:tag? $x:text? $x:tag+ $x:text+ xp:compile tag xml->doc *xpath-compiler* *namespace-aware* nscontext xmlnsmap-from-root-node with-namespace-context abs-path]]))
(def xml-fixtures {:simple (tag :top-tag "this is a foo")
:attrs (tag [:top-tag :name "bobby tables"]
"drop tables")
:nested (tag :top-tag
(tag :inner-tag
(tag :more-inner "inner tag body")))
:namespaces (slurp "fixtures/namespace1.xml")})
(deftest test-xml->doc
(is (isa? (class (xp/xml->doc (:simple xml-fixtures))) org.w3c.dom.Document))
(is (isa? (class (xp/xml->doc (.getBytes ^String (:simple xml-fixtures))))
org.w3c.dom.Document))
(is (isa? (class (xp/xml->doc (xp/xml->doc (:simple xml-fixtures))))
org.w3c.dom.Document)))
(deftest test-$x-top-tag
(is (= :top-tag
($x:tag "/*" (:simple xml-fixtures)))))
(deftest test-$x-get-body
(is (= "this is a foo"
($x:text "/*" (:simple xml-fixtures)))))
(deftest test-$x-get-attrs
(is (= "bobby tables"
(:name
($x:attrs "/*" (:attrs xml-fixtures))))))
(deftest test-$x-attrs*
(is (= [{:name "bobby tables"}]
($x:attrs* "/*" (:attrs xml-fixtures))))
(is (= ["bobby tables"]
($x:attrs* "/*" (:attrs xml-fixtures) :name))))
(deftest test-$x-node
(is (= "top-tag"
(.getNodeName ^org.w3c.dom.Node ($x:node "/*" (:simple xml-fixtures))))))
(deftest test-$x-on-result
(is (= :more-inner
($x:tag "./*"
($x:node "/top-tag/*" (:nested xml-fixtures))))))
(deftest compile-should-compile-strings
(is (isa?
(class (xp:compile "//*"))
javax.xml.xpath.XPathExpression)))
(deftest compile-should-return-compiled-xpath-expr
(is (isa?
(class (xp:compile (xp:compile "//*")))
javax.xml.xpath.XPathExpression)))
(deftest $x-should-support-precompiled-xpath-expressions
(let [expr (xp:compile "/*")
doc (xml->doc (:simple xml-fixtures))]
(is (= :top-tag
($x:tag expr doc)))))
(deftest should-support-input-stream-as-xml-source
(with-open [istr (java.io.ByteArrayInputStream. (.getBytes ^String (:simple xml-fixtures)))]
(is (= :top-tag
($x:tag "/*" istr)))))
(deftest test-zero-or-one-results
(is (not ($x:tag? "/foo" (:simple xml-fixtures))))
(is (= :top-tag ($x:tag? "/*" (:simple xml-fixtures))))
(is (not ($x:text? "/foo" (:simple xml-fixtures))))
(is (= "this is a foo" ($x:text? "/*" (:simple xml-fixtures)))))
(deftest test-zero-or-more-results
(is (thrown? Exception ($x:tag+ "/foo" (:simple xml-fixtures))))
(is (= :top-tag (first ($x:tag+ "/*" (:simple xml-fixtures)))))
(is (thrown? Exception ($x:text+ "/foo" (:simple xml-fixtures))))
(is (= "this is a foo" (first ($x:text+ "/*" (:simple xml-fixtures))))))
(deftest test-namespace
(.setNamespaceContext
*xpath-compiler*
(nscontext {"atom" ""}))
(binding [*namespace-aware* true]
(is (= "BookingCollection" ($x:text "//atom:title" (:namespaces xml-fixtures))))))
(deftest test-with-ns-context-macro
(with-namespace-context
(xmlnsmap-from-root-node (:namespaces xml-fixtures))
(is (= "BookingCollection" ($x:text "//atom:title" (:namespaces xml-fixtures))))))
{ : major 1 , : minor 5 , : incremental 1 , : qualifier nil }
(defmacro compile-when-1.3-or-greater [& body]
(if (and
(>= (:major *clojure-version*) 1)
(>= (:minor *clojure-version*) 3))
`(do
~@body)
nil))
(deftest test-lazy-children
(is (nil? (:children ($x "/top-tag/*" (:simple xml-fixtures)))))
(compile-when-1.3-or-greater
(is (not (realized? (:children (first ($x "/top-tag/*" (:nested xml-fixtures))))))))
(is (= "inner tag body" (:text (first (deref (:children (first ($x "/top-tag/*" (:nested xml-fixtures))))))))))
(def labels-xml "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<labels>
<label added=\"2003-06-20\">
<quote>
</quote>
<name>Thomas Eliot</name>
<address>
<street>3 Prufrock Lane</street>
<city>Stamford</city>
<state>CT</state>
</address>
</label>
<label added=\"2003-06-10\">
<name>Ezra Pound</name>
<address>
<street>45 Usura Place</street>
<city>Hailey</city>
<state>ID</state>
</address>
</label>
</labels>")
(deftest test-absolute-paths
(let [dom (xml->doc labels-xml)
root (first ($x "/labels" dom))
children @(:children root)
attrs ($x "//attribute::*" dom)]
(is (= "/labels[1]" (abs-path root)))
(is (= "/labels[1]/text()[1]" (abs-path (first children))))
(is (= "/labels[1]/label[1]" (abs-path (second children))))
(is (= "/labels[1]/text()[2]" (abs-path (nth children 2))))
(is (= "/labels[1]/label[2]" (abs-path (nth children 3))))
(is (= "/labels[1]/text()[3]" (abs-path (nth children 4))))
(is (= "/labels[1]/label[1]/@added" (abs-path (first attrs))))
(is (= "/labels[1]/label[2]/@added" (abs-path (second attrs))))))
(def dtd-xml
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE eSearchResult PUBLIC \"-//NLM//DTD esearch 20060628//EN\" \"\">
<eSearchResult><Count>21486</Count><RetMax>10</RetMax><RetStart>0</RetStart><IdList>
<Id>26651117</Id><Id>26651111</Id><Id>26651108</Id><Id>26651106</Id>
<Id>26651105</Id><Id>26651078</Id><Id>26651075</Id><Id>26651033</Id></IdList></eSearchResult>")
(deftest test-external-dtd-skipping
(let [opts {:disallow-doctype-decl false}]
(is (not (false? (try (xml->doc dtd-xml opts)
(catch Exception e false)))))))
The document soap1.xml uses 3 namepsaces . The 3rd is implicit / blank in the SOAP Body element .
(deftest test-with-blank-ns
(let [xml (slurp "fixtures/soap1.xml")]
(xp/with-namespace-awareness
(let [doc (xp/xml->doc xml)]
(xp/set-namespace-context! (xp/xmlnsmap-from-document doc))
(is (= :OTA_HotelAvailRQ (xp/$x:tag "/soapenv:Envelope/soapenv:Body/:OTA_HotelAvailRQ" doc)))))))
#_(deftest test-abs-path-with-blank-namespace
(let [xml (slurp "fixtures/soap1.xml")]
(xp/with-namespace-awareness
(let [doc (xp/xml->doc xml)]
(xp/set-namespace-context! (xp/xmlnsmap-from-document doc))
(is (= "/soapenv:Envelope[1]/soapenv:Body[1]/:OTA_HotelAvailRQ[1]"
(xp/abs-path (first (xp/$x "/soapenv:Envelope[1]/soapenv:Body[1]/:OTA_HotelAvailRQ[1]" doc)))))))))
(deftest test-owasp-xxe-processing-vulnerability
(is
(thrown?
org.xml.sax.SAXParseException
(xml->doc
"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY xxe SYSTEM \"file\">
(is
(not
(nil?
(xml->doc
"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY xxe SYSTEM \"file\">
{:disallow-doctype-decl false})))))
(comment
(test-owasp-xxe-processing-vulnerability)
(test-with-blank-ns)
(with-namespace-context {"atom" ""}
($x:text "//atom:title" (:namespaces xml-fixtures)))
(with-namespace-context (xmlnsmap-from-root-node (:namespaces xml-fixtures))
($x:text "//atom:title" (:namespaces xml-fixtures)))
(run-tests)
(let [doc (slurp "sabre.xml")
xp (str "/soapenv:Envelope/soapenv:Body/:OTA_HotelAvailRQ/"
":AvailRequestSegments/:AvailRequestSegment/"
":HotelSearchCriteria/:Criterion/:HotelRef")
ns-map {"soapenv" "/"
"head" "/"
"" ""}]
(xp/with-namespace-context ns-map
(xp/$x:attrs* xp doc :HotelCode)))
= > ( " 11206 " )
(let [doc (slurp "sabre.xml")
ns-map {"soapenv" "/"
"head" "/"}]
(xp/with-namespace-context ns-map
(let [node (xp/$x:node "/soapenv:Envelope/soapenv:Body/*" doc)]
#_(xp/set-namespace-context! {"" ""})
(xp/xmlnsmap-from-node node)
#_(xp/$x:tag "./:OTA_HotelAvailRQ" node))))
(defn get-soap-body [xml]
(xp/with-namespace-awareness
(let [doc (xp/xml->doc xml)]
(xp/set-namespace-context! (xp/xmlnsmap-from-root-node doc))
(xp/node->xml (xp/$x:node "/soapenv:Envelope/soapenv:Body/*" doc)))))
(let [orig-xml (slurp "sabre.xml")
body-xml (xp/xml->doc (get-soap-body orig-xml))]
(xp/$x:attrs* "/OTA_HotelAvailRQ/AvailRequestSegments/AvailRequestSegment/HotelSearchCriteria/Criterion/HotelRef" body-xml :HotelCode))
("11206")
)
|
825dcd17e5504f11e85096ddcc862af1bf39a12984d2fc5e5ecf4891ba254974 | spawnfest/eep49ers | ssl_api_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2019 - 2019 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%
-module(ssl_api_SUITE).
-behaviour(ct_suite).
-include_lib("common_test/include/ct.hrl").
-include_lib("ssl/src/ssl_api.hrl").
%% Common test
-export([all/0,
groups/0,
init_per_suite/1,
init_per_group/2,
init_per_testcase/2,
end_per_suite/1,
end_per_group/2,
end_per_testcase/2
]).
%% Test cases
-export([conf_signature_algs/0,
conf_signature_algs/1,
no_common_signature_algs/0,
no_common_signature_algs/1,
default_reject_anonymous/0,
default_reject_anonymous/1,
connection_information_with_srp/0,
connection_information_with_srp/1,
peercert/0,
peercert/1,
peercert_with_client_cert/0,
peercert_with_client_cert/1,
connection_information/0,
connection_information/1,
secret_connection_info/0,
secret_connection_info/1,
keylog_connection_info/0,
keylog_connection_info/1,
versions/0,
versions/1,
active_n/0,
active_n/1,
dh_params/0,
dh_params/1,
prf/0,
prf/1,
hibernate/0,
hibernate/1,
hibernate_right_away/0,
hibernate_right_away/1,
listen_socket/0,
listen_socket/1,
peername/0,
peername/1,
recv_active/0,
recv_active/1,
recv_active_once/0,
recv_active_once/1,
recv_active_n/0,
recv_active_n/1,
recv_no_active_msg/0,
recv_no_active_msg/1,
recv_timeout/0,
recv_timeout/1,
recv_close/0,
recv_close/1,
controlling_process/0,
controlling_process/1,
controller_dies/0,
controller_dies/1,
controlling_process_transport_accept_socket/0,
controlling_process_transport_accept_socket/1,
close_with_timeout/0,
close_with_timeout/1,
close_in_error_state/0,
close_in_error_state/1,
call_in_error_state/0,
call_in_error_state/1,
close_transport_accept/0,
close_transport_accept/1,
abuse_transport_accept_socket/0,
abuse_transport_accept_socket/1,
honor_server_cipher_order/0,
honor_server_cipher_order/1,
honor_client_cipher_order/0,
honor_client_cipher_order/1,
honor_client_cipher_order_tls13/0,
honor_client_cipher_order_tls13/1,
honor_server_cipher_order_tls13/0,
honor_server_cipher_order_tls13/1,
ipv6/0,
ipv6/1,
der_input/0,
der_input/1,
new_options_in_handshake/0,
new_options_in_handshake/1,
max_handshake_size/0,
max_handshake_size/1,
invalid_certfile/0,
invalid_certfile/1,
invalid_cacertfile/0,
invalid_cacertfile/1,
invalid_keyfile/0,
invalid_keyfile/1,
options_not_proplist/0,
options_not_proplist/1,
invalid_options/0,
invalid_options/1,
cb_info/0,
cb_info/1,
log_alert/0,
log_alert/1,
getstat/0,
getstat/1,
handshake_continue/0,
handshake_continue/1,
handshake_continue_timeout/0,
handshake_continue_timeout/1,
handshake_continue_change_verify/0,
handshake_continue_change_verify/1,
hello_client_cancel/0,
hello_client_cancel/1,
hello_server_cancel/0,
hello_server_cancel/1,
handshake_continue_tls13_client/0,
handshake_continue_tls13_client/1,
rizzo_disabled/0,
rizzo_disabled/1,
rizzo_zero_n/0,
rizzo_zero_n/1,
rizzo_one_n_minus_one/0,
rizzo_one_n_minus_one/1,
supported_groups/0,
supported_groups/1,
client_options_negative_version_gap/0,
client_options_negative_version_gap/1,
client_options_negative_dependency_version/0,
client_options_negative_dependency_version/1,
client_options_negative_dependency_stateless/0,
client_options_negative_dependency_stateless/1,
client_options_negative_dependency_role/0,
client_options_negative_dependency_role/1,
client_options_negative_early_data/0,
client_options_negative_early_data/1,
server_options_negative_early_data/0,
server_options_negative_early_data/1,
server_options_negative_version_gap/0,
server_options_negative_version_gap/1,
server_options_negative_dependency_role/0,
server_options_negative_dependency_role/1,
invalid_options_tls13/0,
invalid_options_tls13/1,
cookie/0,
cookie/1
]).
%% Apply export
-export([connection_information_result/1,
connection_info_result/1,
secret_connection_info_result/1,
keylog_connection_info_result/2,
check_srp_in_connection_information/3,
check_connection_info/2,
prf_verify_value/4,
try_recv_active/1,
try_recv_active_once/1,
controlling_process_result/3,
controller_dies_result/3,
send_recv_result_timeout_client/1,
send_recv_result_timeout_server/1,
do_recv_close/1,
tls_close/1,
no_recv_no_active/1,
ssl_getstat/1,
%%TODO Keep?
run_error_server/1,
run_error_server_close/1,
run_client_error/1
]).
-define(SLEEP, 500).
%%--------------------------------------------------------------------
%% Common Test interface functions -----------------------------------
%%--------------------------------------------------------------------
all() ->
[
{group, 'tlsv1.3'},
{group, 'tlsv1.2'},
{group, 'tlsv1.1'},
{group, 'tlsv1'},
{group, 'dtlsv1.2'},
{group, 'dtlsv1'}
].
groups() ->
[
{'tlsv1.3', [], ((gen_api_tests() ++ tls13_group() ++
handshake_paus_tests()) --
[dh_params,
honor_server_cipher_order,
honor_client_cipher_order,
new_options_in_handshake,
handshake_continue_tls13_client,
invalid_options])
++ (since_1_2() -- [conf_signature_algs])},
{'tlsv1.2', [], gen_api_tests() ++ since_1_2() ++ handshake_paus_tests() ++ pre_1_3()},
{'tlsv1.1', [], gen_api_tests() ++ handshake_paus_tests() ++ pre_1_3()},
{'tlsv1', [], gen_api_tests() ++ handshake_paus_tests() ++ pre_1_3() ++ beast_mitigation_test()},
{'dtlsv1.2', [], (gen_api_tests() --
[invalid_keyfile, invalid_certfile, invalid_cacertfile,
invalid_options, new_options_in_handshake]) ++
handshake_paus_tests() -- [handshake_continue_tls13_client] ++ pre_1_3()},
{'dtlsv1', [], (gen_api_tests() --
[invalid_keyfile, invalid_certfile, invalid_cacertfile,
invalid_options, new_options_in_handshake]) ++
handshake_paus_tests() -- [handshake_continue_tls13_client] ++ pre_1_3()}
].
since_1_2() ->
[
conf_signature_algs,
no_common_signature_algs
].
pre_1_3() ->
[
default_reject_anonymous,
connection_information_with_srp,
prf
].
gen_api_tests() ->
[
peercert,
peercert_with_client_cert,
connection_information,
secret_connection_info,
keylog_connection_info,
versions,
active_n,
dh_params,
hibernate,
hibernate_right_away,
listen_socket,
peername,
recv_active,
recv_active_once,
recv_active_n,
recv_no_active_msg,
recv_timeout,
recv_close,
controlling_process,
controller_dies,
controlling_process_transport_accept_socket,
close_with_timeout,
close_in_error_state,
call_in_error_state,
close_transport_accept,
abuse_transport_accept_socket,
honor_server_cipher_order,
honor_client_cipher_order,
ipv6,
der_input,
new_options_in_handshake,
max_handshake_size,
invalid_certfile,
invalid_cacertfile,
invalid_keyfile,
options_not_proplist,
invalid_options,
cb_info,
log_alert,
getstat
].
handshake_paus_tests() ->
[
handshake_continue,
handshake_continue_timeout,
handshake_continue_change_verify,
hello_client_cancel,
hello_server_cancel,
handshake_continue_tls13_client
].
%% Only relevant for SSL 3.0 and TLS 1.0
beast_mitigation_test() ->
[%% Original option
rizzo_disabled,
%% Same effect as disable
rizzo_zero_n,
%% Same as default
rizzo_one_n_minus_one
].
tls13_group() ->
[
supported_groups,
honor_server_cipher_order_tls13,
honor_client_cipher_order_tls13,
client_options_negative_version_gap,
client_options_negative_dependency_version,
client_options_negative_dependency_stateless,
client_options_negative_dependency_role,
client_options_negative_early_data,
server_options_negative_early_data,
server_options_negative_version_gap,
server_options_negative_dependency_role,
invalid_options_tls13,
cookie
].
init_per_suite(Config0) ->
catch crypto:stop(),
try crypto:start() of
ok ->
ssl_test_lib:clean_start(),
ssl_test_lib:make_rsa_cert(Config0)
catch _:_ ->
{skip, "Crypto did not start"}
end.
end_per_suite(_Config) ->
ssl:stop(),
application:unload(ssl),
application:stop(crypto).
init_per_group(GroupName, Config) ->
case ssl_test_lib:is_protocol_version(GroupName) of
true ->
ssl_test_lib:init_per_group(GroupName,
[{client_type, erlang},
{server_type, erlang},
{version, GroupName}
| Config]);
false ->
Config
end.
end_per_group(GroupName, Config) ->
ssl_test_lib:end_per_group(GroupName, Config).
init_per_testcase(prf, Config) ->
ssl_test_lib:ct_log_supported_protocol_versions(Config),
ct:timetrap({seconds, 10}),
Version = ssl_test_lib:protocol_version(Config),
PRFS = [md5, sha, sha256, sha384, sha512],
All are the result of running tls_v1 : prf(PrfAlgo , < < > > , < < > > , < < > > , 16 )
with the specified PRF algorithm
ExpectedPrfResults =
[{md5, <<96,139,180,171,236,210,13,10,28,32,2,23,88,224,235,199>>},
{sha, <<95,3,183,114,33,169,197,187,231,243,19,242,220,228,70,151>>},
{sha256, <<166,249,145,171,43,95,158,232,6,60,17,90,183,180,0,155>>},
{sha384, <<153,182,217,96,186,130,105,85,65,103,123,247,146,91,47,106>>},
{sha512, <<145,8,98,38,243,96,42,94,163,33,53,49,241,4,127,28>>},
TLS 1.0 and 1.1 PRF :
{md5sha, <<63,136,3,217,205,123,200,177,251,211,17,229,132,4,173,80>>}],
TestPlan = prf_create_plan(Version, PRFS, ExpectedPrfResults),
[{prf_test_plan, TestPlan} | Config];
init_per_testcase(handshake_continue_tls13_client, Config) ->
case ssl_test_lib:sufficient_crypto_support('tlsv1.3') of
true ->
ssl_test_lib:ct_log_supported_protocol_versions(Config),
ct:timetrap({seconds, 10}),
Config;
false ->
{skip, "Missing crypto support: TLS 1.3 not supported"}
end;
init_per_testcase(connection_information_with_srp, Config) ->
PKAlg = proplists:get_value(public_keys, crypto:supports()),
case lists:member(srp, PKAlg) of
true ->
Config;
false ->
{skip, "Missing SRP crypto support"}
end;
init_per_testcase(conf_signature_algs, Config) ->
case ssl_test_lib:appropriate_sha(crypto:supports()) of
sha256 ->
ssl_test_lib:ct_log_supported_protocol_versions(Config),
ct:timetrap({seconds, 10}),
Config;
sha ->
{skip, "Tests needs certs with sha256"}
end;
init_per_testcase(_TestCase, Config) ->
ssl_test_lib:ct_log_supported_protocol_versions(Config),
ct:timetrap({seconds, 10}),
Config.
end_per_testcase(internal_active_n, _Config) ->
application:unset_env(ssl, internal_active_n);
end_per_testcase(_TestCase, Config) ->
Config.
%%--------------------------------------------------------------------
%% Test Cases --------------------------------------------------------
%%--------------------------------------------------------------------
peercert() ->
[{doc,"Test API function peercert/1"}].
peercert(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
{mfa, {ssl, peercert, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl, peercert, []}},
{options, ClientOpts}]),
CertFile = proplists:get_value(certfile, ServerOpts),
[{'Certificate', BinCert, _}]= ssl_test_lib:pem_to_der(CertFile),
ServerMsg = {error, no_peercert},
ClientMsg = {ok, BinCert},
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ServerMsg, Client, ClientMsg),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
peercert_with_client_cert() ->
[{doc,"Test API function peercert/1"}].
peercert_with_client_cert(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
{mfa, {ssl, peercert, []}},
{options, [{verify, verify_peer} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl, peercert, []}},
{options, ClientOpts}]),
ServerCertFile = proplists:get_value(certfile, ServerOpts),
[{'Certificate', ServerBinCert, _}]= ssl_test_lib:pem_to_der(ServerCertFile),
ClientCertFile = proplists:get_value(certfile, ClientOpts),
[{'Certificate', ClientBinCert, _}]= ssl_test_lib:pem_to_der(ClientCertFile),
ServerMsg = {ok, ClientBinCert},
ClientMsg = {ok, ServerBinCert},
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ServerMsg, Client, ClientMsg),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
connection_information() ->
[{doc,"Test the API function ssl:connection_information/1"}].
connection_information(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, connection_information_result, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, connection_information_result, []}},
{options, ClientOpts}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
connection_information_with_srp() ->
[{doc,"Test the result of API function ssl:connection_information/1"
"includes srp_username."}].
connection_information_with_srp(Config) when is_list(Config) ->
run_conn_info_srp_test(srp_anon, 'aes_128_cbc', Config).
run_conn_info_srp_test(Kex, Cipher, Config) ->
Version = ssl_test_lib:protocol_version(Config),
TestCiphers = ssl_test_lib:test_ciphers(Kex, Cipher, Version),
case TestCiphers of
[] ->
{skip, {not_sup, Kex, Cipher, Version}};
[TestCipher | _T] ->
do_run_conn_info_srp_test(TestCipher, Version, Config)
end.
do_run_conn_info_srp_test(ErlangCipherSuite, Version, Config) ->
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
SOpts = [{user_lookup_fun, {fun ssl_test_lib:user_lookup/3, undefined}}],
COpts = [{srp_identity, {"Test-User", "secret"}}],
ServerOpts = ssl_test_lib:ssl_options(SOpts, Config),
ClientOpts = ssl_test_lib:ssl_options(COpts, Config),
ct:log("Erlang Cipher Suite is: ~p~n", [ErlangCipherSuite]),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, check_srp_in_connection_information, [<<"Test-User">>, server]}},
{options, [{versions, [Version]}, {ciphers, [ErlangCipherSuite]} |
ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client(
[{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, check_srp_in_connection_information, [<<"Test-User">>, client]}},
{options, [{versions, [Version]}, {ciphers, [ErlangCipherSuite]} |
ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
secret_connection_info() ->
[{doc,"Test the API function ssl:connection_information/2"}].
secret_connection_info(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, secret_connection_info_result, []}},
{options, [{verify, verify_peer} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, secret_connection_info_result, []}},
{options, [{verify, verify_peer} |ClientOpts]}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, true, Client, true),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
keylog_connection_info() ->
[{doc,"Test the API function ssl:connection_information/2"}].
keylog_connection_info(Config) when is_list(Config) ->
keylog_connection_info(Config, true),
keylog_connection_info(Config, false).
keylog_connection_info(Config, KeepSecrets) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, keylog_connection_info_result, [KeepSecrets]}},
{options, [{verify, verify_peer}, {keep_secrets, KeepSecrets} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, keylog_connection_info_result, [KeepSecrets]}},
{options, [{verify, verify_peer}, {keep_secrets, KeepSecrets} |ClientOpts]}]),
ct:log("Testcase ~p, KeepSecrets ~p Client ~p Server ~p ~n",
[self(), KeepSecrets, Client, Server]),
ServerKeylog = receive
{Server, {ok, Keylog}} ->
Keylog;
{Server, ServerError} ->
ct:fail({server, ServerError})
after 5000 ->
ct:fail({server, timeout})
end,
receive
{Client, {ok, ServerKeylog}} ->
ok;
{Client, {ok, ClientKeylog}} ->
ct:fail({mismatch, {ServerKeylog, ClientKeylog}});
{Client, ClientError} ->
ct:fail({client, ClientError})
after 5000 ->
ct:fail({client, timeout})
end,
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
prf() ->
[{doc,"Test that ssl:prf/5 uses the negotiated PRF."}].
prf(Config) when is_list(Config) ->
Version = ssl_test_lib:protocol_version(Config),
TestPlan = proplists:get_value(prf_test_plan, Config),
lists:foreach(fun(Test) ->
C = proplists:get_value(ciphers, Test),
E = proplists:get_value(expected, Test),
P = proplists:get_value(prf, Test),
prf_run_test(Config, Version, C, E, P)
end, TestPlan).
%%--------------------------------------------------------------------
dh_params() ->
[{doc,"Test to specify DH-params file in server."}].
dh_params(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
DataDir = proplists:get_value(data_dir, Config),
DHParamFile = filename:join(DataDir, "dHParam.pem"),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{dhfile, DHParamFile} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options,
[{ciphers,[{dhe_rsa,aes_256_cbc,sha}]} |
ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
conf_signature_algs() ->
[{doc,"Test to set the signature_algs option on both client and server"}].
conf_signature_algs(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options, [{active, false}, {signature_algs, [{sha256, rsa}]},
{versions, ['tlsv1.2']} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options, [{active, false}, {signature_algs, [{sha256, rsa}]},
{versions, ['tlsv1.2']} | ClientOpts]}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
no_common_signature_algs() ->
[{doc,"Set the signature_algs option so that there client and server does not share any hash sign algorithms"}].
no_common_signature_algs(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, [{signature_algs, [{sha256, rsa}]}
| ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, [{signature_algs, [{sha384, rsa}]}
| ClientOpts]}]),
ssl_test_lib:check_server_alert(Server, Client, insufficient_security).
%%--------------------------------------------------------------------
handshake_continue() ->
[{doc, "Test API function ssl:handshake_continue/3"}].
handshake_continue(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ssl_test_lib:ssl_options([{reuseaddr, true},
{log_level, debug},
{verify, verify_peer},
{handshake, hello} | ServerOpts
],
Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}
]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ClientOpts
],
Config)},
{continue_options, proplists:delete(reuseaddr, ClientOpts)}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
handshake_continue_tls13_client() ->
[{doc, "Test API function ssl:handshake_continue/3 with fixed TLS 1.3 client"}].
handshake_continue_tls13_client(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
SCiphers = ssl:filter_cipher_suites(ssl:cipher_suites(all, 'tlsv1.3'),
[{key_exchange, fun(srp_rsa) -> false;
(srp_anon) -> false;
(srp_dss) -> false;
(_) -> true end}]),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ssl_test_lib:ssl_options([{reuseaddr, true},
{log_level, debug},
{verify, verify_peer},
{ciphers, SCiphers},
{handshake, hello} | ServerOpts
],
Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}
]),
Port = ssl_test_lib:inet_port(Server),
DummyTicket =
<<131,116,0,0,0,5,100,0,4,104,107,100,102,100,0,6,115,104,97,51,
56,52,100,0,3,112,115,107,109,0,0,0,48,150,90,38,127,26,12,5,
228,180,235,229,214,215,27,236,149,182,82,14,140,50,81,0,150,
248,152,180,193,207,80,52,107,196,200,2,77,4,96,140,65,239,205,
224,125,129,179,147,103,100,0,3,115,110,105,107,0,25,112,114,
111,117,100,102,111,111,116,46,111,116,112,46,101,114,105,99,
115,115,111,110,46,115,101,100,0,6,116,105,99,107,101,116,104,6,
100,0,18,110,101,119,95,115,101,115,115,105,111,110,95,116,105,
99,107,101,116,98,0,0,28,32,98,127,110,83,249,109,0,0,0,8,0,0,0,
0,0,0,0,5,109,0,0,0,113,112,154,74,26,27,0,111,147,51,110,216,
43,45,4,100,215,152,195,118,96,22,34,1,184,170,42,166,238,109,
187,138,196,147,102,205,116,83,241,174,227,232,156,148,60,153,3,
175,128,115,192,36,103,191,239,58,222,192,172,190,239,92,8,131,
195,0,217,187,222,143,104,6,86,53,93,27,218,198,205,138,223,202,
11,55,168,104,6,219,228,217,157,37,52,205,252,165,135,167,116,
216,172,231,222,189,84,97,0,8,106,108,88,47,114,48,116,0,0,0,0,
100,0,9,116,105,109,101,115,116,97,109,112,98,93,205,0,44>>,
Send dummy session ticket to trigger sending of pre_shared_key and
%% psk_key_exchange_modes extensions.
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{session_tickets, manual},
{use_ticket, [DummyTicket]},
{versions, ['tlsv1.3',
'tlsv1.2',
'tlsv1.1',
'tlsv1'
]},
{ciphers, ssl:cipher_suites(all, 'tlsv1.3')},
{verify, verify_peer} | ClientOpts
],
Config)},
{continue_options, proplists:delete(reuseaddr, ClientOpts)}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%------------------------------------------------------------------
handshake_continue_timeout() ->
[{doc, "Test API function ssl:handshake_continue/3 with short timeout"}].
handshake_continue_timeout(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{timeout, 1},
{options, ssl_test_lib:ssl_options([{reuseaddr, true}, {handshake, hello},
{verify, verify_peer} | ServerOpts],
Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}
]),
Port = ssl_test_lib:inet_port(Server),
ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, [{verify, verify_peer} | ClientOpts]}]),
ssl_test_lib:check_result(Server, {error,timeout}),
ssl_test_lib:close(Server).
handshake_continue_change_verify() ->
[{doc, "Test API function ssl:handshake_continue with updated verify option. "
"Use a verification that will fail to make sure verification is run"}].
handshake_continue_change_verify(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server(
[{node, ServerNode}, {port, 0},
{from, self()},
{options, ssl_test_lib:ssl_options(
[{handshake, hello},
{verify, verify_peer} | ServerOpts], Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client_error(
[{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ssl_test_lib:ssl_options(
[{handshake, hello},
{server_name_indication, "foobar"}
| ClientOpts], Config)},
{continue_options, [{verify, verify_peer} | ClientOpts]}]),
ssl_test_lib:check_client_alert(Client, handshake_failure).
%%--------------------------------------------------------------------
hello_client_cancel() ->
[{doc, "Test API function ssl:handshake_cancel/1 on the client side"}].
hello_client_cancel(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ServerOpts], Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}]),
Port = ssl_test_lib:inet_port(Server),
%% That is ssl:handshake_cancel returns ok
{connect_failed, ok} =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ClientOpts], Config)},
{continue_options, cancel}]),
ssl_test_lib:check_server_alert(Server, user_canceled).
%%--------------------------------------------------------------------
hello_server_cancel() ->
[{doc, "Test API function ssl:handshake_cancel/1 on the server side"}].
hello_server_cancel(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ServerOpts
], Config)},
{continue_options, cancel}]),
Port = ssl_test_lib:inet_port(Server),
ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ClientOpts
], Config)},
{continue_options, proplists:delete(reuseaddr, ClientOpts)}]),
ssl_test_lib:check_result(Server, ok).
%%--------------------------------------------------------------------
versions() ->
[{doc,"Test API function versions/0"}].
versions(Config) when is_list(Config) ->
[_|_] = Versions = ssl:versions(),
ct:log("~p~n", [Versions]).
%%--------------------------------------------------------------------
Test case adapted from gen_tcp_misc_SUITE .
active_n() ->
[{doc,"Test {active,N} option"}].
active_n(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
Port = ssl_test_lib:inet_port(node()),
N = 3,
LS = ok(ssl:listen(Port, [{active,N}|ServerOpts])),
[{active,N}] = ok(ssl:getopts(LS, [active])),
active_n_common(LS, N),
Self = self(),
spawn_link(fun() ->
S0 = ok(ssl:transport_accept(LS)),
{ok, S} = ssl:handshake(S0),
ok = ssl:setopts(S, [{active,N}]),
[{active,N}] = ok(ssl:getopts(S, [active])),
ssl:controlling_process(S, Self),
Self ! {server, S}
end),
C = ok(ssl:connect("localhost", Port, [{active,N}|ClientOpts])),
[{active,N}] = ok(ssl:getopts(C, [active])),
S = receive
{server, S0} -> S0
after
1000 ->
exit({error, connect})
end,
active_n_common(C, N),
active_n_common(S, N),
ok = ssl:setopts(C, [{active,N}]),
ok = ssl:setopts(S, [{active,N}]),
ReceiveMsg = fun(Socket, Msg) ->
receive
{ssl,Socket,Msg} ->
ok;
{ssl,Socket,Begin} ->
receive
{ssl,Socket,End} ->
Msg = Begin ++ End,
ok
after 1000 ->
exit(timeout)
end
after 1000 ->
exit(timeout)
end
end,
repeat(3, fun(I) ->
Msg = "message "++integer_to_list(I),
ok = ssl:send(C, Msg),
ReceiveMsg(S, Msg),
ok = ssl:send(S, Msg),
ReceiveMsg(C, Msg)
end),
receive
{ssl_passive,S} ->
[{active,false}] = ok(ssl:getopts(S, [active]))
after
1000 ->
exit({error,ssl_passive})
end,
receive
{ssl_passive,C} ->
[{active,false}] = ok(ssl:getopts(C, [active]))
after
1000 ->
exit({error,ssl_passive})
end,
LS2 = ok(ssl:listen(0, [{active,0}])),
receive
{ssl_passive,LS2} ->
[{active,false}] = ok(ssl:getopts(LS2, [active]))
after
1000 ->
exit({error,ssl_passive})
end,
ok = ssl:close(LS2),
ok = ssl:close(C),
ok = ssl:close(S),
ok = ssl:close(LS),
ok.
hibernate() ->
[{doc,"Check that an SSL connection that is started with option "
"{hibernate_after, 1000} indeed hibernates after 1000ms of "
"inactivity"}].
hibernate(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
{Client, #sslsocket{pid=[Pid|_]}} = ssl_test_lib:start_client([return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{hibernate_after, 1000}|ClientOpts]}]),
{current_function, _} =
process_info(Pid, current_function),
ssl_test_lib:check_result(Server, ok, Client, ok),
ct:sleep(1500),
{current_function, {erlang, hibernate, 3}} =
process_info(Pid, current_function),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
hibernate_right_away() ->
[{doc,"Check that an SSL connection that is configured to hibernate "
"after 0 or 1 milliseconds hibernates as soon as possible and not "
"crashes"}].
hibernate_right_away(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
StartServerOpts = [{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ServerOpts}],
StartClientOpts = [return_socket,
{node, ClientNode},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}}],
Server1 = ssl_test_lib:start_server(StartServerOpts),
Port1 = ssl_test_lib:inet_port(Server1),
{Client1, #sslsocket{pid = [Pid1|_]}} = ssl_test_lib:start_client(StartClientOpts ++
[{port, Port1}, {options, [{hibernate_after, 0}|ClientOpts]}]),
ssl_test_lib:check_result(Server1, ok, Client1, ok),
ct:sleep(1000), %% Schedule out
{current_function, {erlang, hibernate, 3}} =
process_info(Pid1, current_function),
ssl_test_lib:close(Server1),
ssl_test_lib:close(Client1),
Server2 = ssl_test_lib:start_server(StartServerOpts),
Port2 = ssl_test_lib:inet_port(Server2),
{Client2, #sslsocket{pid = [Pid2|_]}} = ssl_test_lib:start_client(StartClientOpts ++
[{port, Port2}, {options, [{hibernate_after, 1}|ClientOpts]}]),
ssl_test_lib:check_result(Server2, ok, Client2, ok),
ct:sleep(1000), %% Schedule out
{current_function, {erlang, hibernate, 3}} =
process_info(Pid2, current_function),
ssl_test_lib:close(Server2),
ssl_test_lib:close(Client2).
listen_socket() ->
[{doc,"Check error handling and inet compliance when calling API functions with listen sockets."}].
listen_socket(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ok, ListenSocket} = ssl:listen(0, ServerOpts),
%% This can be a valid thing to do as
%% options are inherited by the accept socket
ok = ssl:controlling_process(ListenSocket, self()),
{ok, _} = ssl:sockname(ListenSocket),
{error, enotconn} = ssl:send(ListenSocket, <<"data">>),
{error, enotconn} = ssl:recv(ListenSocket, 0),
{error, enotconn} = ssl:connection_information(ListenSocket),
{error, enotconn} = ssl:peername(ListenSocket),
{error, enotconn} = ssl:peercert(ListenSocket),
{error, enotconn} = ssl:renegotiate(ListenSocket),
{error, enotconn} = ssl:prf(ListenSocket, 'master_secret', <<"Label">>, [client_random], 256),
{error, enotconn} = ssl:shutdown(ListenSocket, read_write),
ok = ssl:close(ListenSocket).
%%--------------------------------------------------------------------
peername() ->
[{doc,"Test API function peername/1"}].
peername(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server(
[
{node, ServerNode}, {port, 0},
{from, self()},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
{Client, CSocket} = ssl_test_lib:start_client(
[return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ClientOpts}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
Server ! get_socket,
SSocket =
receive
{Server, {socket, Socket}} ->
Socket
end,
{ok, ServerPeer} = ssl:peername(SSocket),
ct:log("Server's peer: ~p~n", [ServerPeer]),
{ok, ClientPeer} = ssl:peername(CSocket),
ct:log("Client's peer: ~p~n", [ClientPeer]),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
recv_active() ->
[{doc,"Test recv on active socket"}].
recv_active(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, try_recv_active, []}},
{options, [{active, true} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, try_recv_active, []}},
{options, [{active, true} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
recv_active_once() ->
[{doc,"Test recv on active (once) socket"}].
recv_active_once(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, try_recv_active_once, []}},
{options, [{active, once} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, try_recv_active_once, []}},
{options, [{active, once} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
recv_active_n() ->
[{doc,"Test recv on active (n) socket"}].
recv_active_n(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, try_recv_active_once, []}},
{options, [{active, 1} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, try_recv_active_once, []}},
{options, [{active, 1} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
recv_timeout() ->
[{doc,"Test ssl:recv timeout"}].
recv_timeout(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, send_recv_result_timeout_server, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE,
send_recv_result_timeout_client, []}},
{options, [{active, false} | ClientOpts]}]),
ssl_test_lib:check_result(Client, ok, Server, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
recv_close() ->
[{doc,"Special case of call error handling"}].
recv_close(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, do_recv_close, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
{_Client, #sslsocket{} = SslSocket} = ssl_test_lib:start_client([return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, no_result, []}},
{options, ClientOpts}]),
ssl:close(SslSocket),
ssl_test_lib:check_result(Server, ok).
%%--------------------------------------------------------------------
recv_no_active_msg() ->
[{doc,"If we have a passive socket and do not call recv and peer closes we should no get"
"receive an active message"}].
recv_no_active_msg(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, no_recv_no_active, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, no_result, []}},
{options, ClientOpts}]),
ssl_test_lib:close(Client),
ssl_test_lib:check_result(Server, ok).
%%--------------------------------------------------------------------
controlling_process() ->
[{doc,"Test API function controlling_process/2"}].
controlling_process(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
ClientMsg = "Server hello",
ServerMsg = "Client hello",
Server = ssl_test_lib:start_server([
{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE,
controlling_process_result, [self(),
ServerMsg]}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
{Client, CSocket} = ssl_test_lib:start_client([return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE,
controlling_process_result, [self(),
ClientMsg]}},
{options, ClientOpts}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ServerMsg = ssl_test_lib:active_recv(CSocket, length(ServerMsg)),
We do not have the TLS server socket but all messages form the client
%% socket are now read, so ramining are form the server socket
ClientMsg = ssl_active_recv(length(ClientMsg)),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
controller_dies() ->
[{doc,"Test that the socket is closed after controlling process dies"}].
controller_dies(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
ClientMsg = "Hello server",
ServerMsg = "Hello client",
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE,
controller_dies_result, [self(),
ServerMsg]}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE,
controller_dies_result, [self(),
ClientMsg]}},
{options, ClientOpts}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n", [self(), Client, Server]),
ct:sleep(?SLEEP), %% so that they are connected
process_flag(trap_exit, true),
%% Test that clients die
exit(Client, killed),
get_close(Client, ?LINE),
%% Test that clients die when process disappear
Server ! listen,
Tester = self(),
Connect = fun(Pid) ->
{ok, Socket} = ssl:connect(Hostname, Port, ClientOpts),
%% Make sure server finishes and verification
%% and is in coonection state before
%% killing client
ct:sleep(?SLEEP),
Pid ! {self(), connected, Socket},
receive die_nice -> normal end
end,
Client2 = spawn_link(fun() -> Connect(Tester) end),
receive {Client2, connected, _Socket} -> Client2 ! die_nice end,
get_close(Client2, ?LINE),
%% Test that clients die when the controlling process have changed
Server ! listen,
Client3 = spawn_link(fun() -> Connect(Tester) end),
Controller = spawn_link(fun() -> receive die_nice -> normal end end),
receive
{Client3, connected, Socket} ->
ok = ssl:controlling_process(Socket, Controller),
Client3 ! die_nice
end,
ct:log("Wating on exit ~p~n",[Client3]),
receive {'EXIT', Client3, normal} -> ok end,
Client3 is dead but that does n't matter , socket should not be closed .
Unexpected ->
ct:log("Unexpected ~p~n",[Unexpected]),
ct:fail({line, ?LINE-1})
after 1000 ->
ok
end,
Controller ! die_nice,
get_close(Controller, ?LINE),
%% Test that servers die
Server ! listen,
LastClient = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE,
controller_dies_result, [self(),
ClientMsg]}},
{options, ClientOpts}]),
ct:sleep(?SLEEP), %% so that they are connected
exit(Server, killed),
get_close(Server, ?LINE),
process_flag(trap_exit, false),
ssl_test_lib:close(LastClient).
%%--------------------------------------------------------------------
controlling_process_transport_accept_socket() ->
[{doc,"Only ssl:handshake and ssl:controlling_process is allowed for transport_accept:sockets"}].
controlling_process_transport_accept_socket(Config) when is_list(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server_transport_control([{node, ServerNode},
{port, 0},
{from, self()},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
_Client = ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server, ok),
ssl_test_lib:close(Server).
%%--------------------------------------------------------------------
close_with_timeout() ->
[{doc,"Test normal (not downgrade) ssl:close/2"}].
close_with_timeout(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, tls_close, []}},
{options,[{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, tls_close, []}},
{options, [{active, false} |ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok).
%%--------------------------------------------------------------------
close_in_error_state() ->
[{doc,"Special case of closing socket in error state"}].
close_in_error_state(Config) when is_list(Config) ->
ServerOpts0 = ssl_test_lib:ssl_options(server_opts, Config),
ServerOpts = [{cacertfile, "foo.pem"} | proplists:delete(cacertfile, ServerOpts0)],
ClientOpts = ssl_test_lib:ssl_options(client_opts, Config),
_ = spawn(?MODULE, run_error_server_close, [[self() | ServerOpts]]),
receive
{_Pid, Port} ->
spawn_link(?MODULE, run_client_error, [[Port, ClientOpts]])
end,
receive
ok ->
ok;
Other ->
ct:fail(Other)
end.
%%--------------------------------------------------------------------
call_in_error_state() ->
[{doc,"Special case of call error handling"}].
call_in_error_state(Config) when is_list(Config) ->
ServerOpts0 = ssl_test_lib:ssl_options(server_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_opts, Config),
ServerOpts = [{cacertfile, "foo.pem"} | proplists:delete(cacertfile, ServerOpts0)],
Pid = spawn(?MODULE, run_error_server, [[self() | ServerOpts]]),
receive
{Pid, Port} ->
spawn_link(?MODULE, run_client_error, [[Port, ClientOpts]])
end,
receive
{error, closed} ->
ok;
Other ->
ct:fail(Other)
end.
%%--------------------------------------------------------------------
close_transport_accept() ->
[{doc,"Tests closing ssl socket when waiting on ssl:transport_accept/1"}].
close_transport_accept(Config) when is_list(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{_ClientNode, ServerNode, _Hostname} = ssl_test_lib:run_where(Config),
Port = 0,
Opts = [{active, false} | ServerOpts],
{ok, ListenSocket} = rpc:call(ServerNode, ssl, listen, [Port, Opts]),
spawn_link(fun() ->
ct:sleep(?SLEEP),
rpc:call(ServerNode, ssl, close, [ListenSocket])
end),
case rpc:call(ServerNode, ssl, transport_accept, [ListenSocket]) of
{error, closed} ->
ok;
Other ->
exit({?LINE, Other})
end.
%%--------------------------------------------------------------------
abuse_transport_accept_socket() ->
[{doc,"Only ssl:handshake and ssl:controlling_process is allowed for transport_accept:sockets"}].
abuse_transport_accept_socket(Config) when is_list(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server_transport_abuse_socket([{node, ServerNode},
{port, 0},
{from, self()},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, no_result, []}},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
invalid_keyfile() ->
[{doc,"Test what happens with an invalid key file"}].
invalid_keyfile(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
BadKeyFile = filename:join([proplists:get_value(priv_dir, Config),
"badkey.pem"]),
BadOpts = [{keyfile, BadKeyFile}| proplists:delete(keyfile, ServerOpts)],
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, BadOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client_error([{node, ClientNode},
{port, Port}, {host, Hostname},
{from, self()}, {options, ClientOpts}]),
File = proplists:get_value(keyfile,BadOpts),
ssl_test_lib:check_result(Server,
{error,{options, {keyfile, File, {error,enoent}}}}, Client,
{error, closed}).
%%--------------------------------------------------------------------
honor_server_cipher_order() ->
[{doc,"Test API honor server cipher order."}].
honor_server_cipher_order(Config) when is_list(Config) ->
ClientCiphers = [#{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf},
#{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac => sha,
prf => default_prf}],
ServerCiphers = [#{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac =>sha,
prf => default_prf},
#{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf}],
honor_cipher_order(Config, true, ServerCiphers,
ClientCiphers, #{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac => sha,
prf => default_prf}).
%%--------------------------------------------------------------------
honor_client_cipher_order() ->
[{doc,"Test API honor server cipher order."}].
honor_client_cipher_order(Config) when is_list(Config) ->
ClientCiphers = [#{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf},
#{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac => sha,
prf => default_prf}],
ServerCiphers = [#{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac =>sha,
prf => default_prf},
#{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf}],
honor_cipher_order(Config, false, ServerCiphers,
ClientCiphers, #{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf}).
%%--------------------------------------------------------------------
ipv6() ->
[{require, ipv6_hosts},
{doc,"Test ipv6."}].
ipv6(Config) when is_list(Config) ->
{ok, Hostname0} = inet:gethostname(),
case lists:member(list_to_atom(Hostname0), ct:get_config(ipv6_hosts)) of
true ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} =
ssl_test_lib:run_where(Config, ipv6),
Server = ssl_test_lib:start_server([{node, ServerNode},
{port, 0}, {from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options,
[inet6, {active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode},
{port, Port}, {host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options,
[inet6, {active, false} | ClientOpts]}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client);
false ->
{skip, "Host does not support IPv6"}
end.
%%--------------------------------------------------------------------
der_input() ->
[{doc,"Test to input certs and key as der"}].
der_input(Config) when is_list(Config) ->
DataDir = proplists:get_value(data_dir, Config),
DHParamFile = filename:join(DataDir, "dHParam.pem"),
{status, _, _, StatusInfo} = sys:get_status(whereis(ssl_manager)),
[_, _,_, _, Prop] = StatusInfo,
State = ssl_test_lib:state(Prop),
[CADb | _] = element(5, State),
ct:sleep(?SLEEP*2), %%Make sure there is no outstanding clean cert db msg in manager
Size = ets:info(CADb, size),
ct:pal("Size ~p", [Size]),
SeverVerifyOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ServerCert, ServerKey, ServerCaCerts, DHParams} = der_input_opts([{dhfile, DHParamFile} |
SeverVerifyOpts]),
ClientVerifyOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientCert, ClientKey, ClientCaCerts, DHParams} = der_input_opts([{dhfile, DHParamFile} |
ClientVerifyOpts]),
ServerOpts = [{verify, verify_peer}, {fail_if_no_peer_cert, true},
{dh, DHParams},
{cert, ServerCert}, {key, ServerKey}, {cacerts, ServerCaCerts}],
ClientOpts = [{verify, verify_peer}, {fail_if_no_peer_cert, true},
{dh, DHParams},
{cert, ClientCert}, {key, ClientKey}, {cacerts, ClientCaCerts}],
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options, [{active, false} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client),
Using only DER input should not increase file indexed DB
Size = ets:info(CADb, size).
%%--------------------------------------------------------------------
invalid_certfile() ->
[{doc,"Test what happens with an invalid cert file"}].
invalid_certfile(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
BadCertFile = filename:join([proplists:get_value(priv_dir, Config),
"badcert.pem"]),
ServerBadOpts = [{certfile, BadCertFile}| proplists:delete(certfile, ServerOpts)],
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, ServerBadOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client_error([{node, ClientNode},
{port, Port}, {host, Hostname},
{from, self()},
{options, ClientOpts}]),
File = proplists:get_value(certfile, ServerBadOpts),
ssl_test_lib:check_result(Server, {error,{options, {certfile, File, {error,enoent}}}},
Client, {error, closed}).
%%--------------------------------------------------------------------
invalid_cacertfile() ->
[{doc,"Test what happens with an invalid cacert file"}].
invalid_cacertfile(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
BadCACertFile = filename:join([proplists:get_value(priv_dir, Config),
"badcacert.pem"]),
ServerBadOpts = [{cacertfile, BadCACertFile}| proplists:delete(cacertfile, ServerOpts)],
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server0 =
ssl_test_lib:start_server_error([{node, ServerNode},
{port, 0}, {from, self()},
{options, ServerBadOpts}]),
Port0 = ssl_test_lib:inet_port(Server0),
Client0 =
ssl_test_lib:start_client_error([{node, ClientNode},
{port, Port0}, {host, Hostname},
{from, self()},
{options, ClientOpts}]),
File0 = proplists:get_value(cacertfile, ServerBadOpts),
ssl_test_lib:check_result(Server0, {error, {options, {cacertfile, File0,{error,enoent}}}},
Client0, {error, closed}),
File = File0 ++ "do_not_exit.pem",
ServerBadOpts1 = [{cacertfile, File}|proplists:delete(cacertfile, ServerBadOpts)],
Server1 =
ssl_test_lib:start_server_error([{node, ServerNode},
{port, 0}, {from, self()},
{options, ServerBadOpts1}]),
Port1 = ssl_test_lib:inet_port(Server1),
Client1 =
ssl_test_lib:start_client_error([{node, ClientNode},
{port, Port1}, {host, Hostname},
{from, self()},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server1, {error, {options, {cacertfile, File,{error,enoent}}}},
Client1, {error, closed}),
ok.
%%--------------------------------------------------------------------
new_options_in_handshake() ->
[{doc,"Test that you can set ssl options in handshake/3 and not only in tcp upgrade"}].
new_options_in_handshake(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
Version = ssl_test_lib:protocol_version(Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Ciphers = [_, Cipher | _] = ssl:filter_cipher_suites(ssl:cipher_suites(all, Version),
[{key_exchange,
fun(dhe_rsa) ->
true;
(ecdhe_rsa) ->
true;
(rsa) ->
false;
(_) ->
false
end
}]),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{ssl_extra_opts, [{versions, [Version]},
To be set in handshake/3
{mfa, {?MODULE, connection_info_result, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, connection_info_result, []}},
{options, [{ciphers, Ciphers} | ClientOpts]}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ServerMsg = ClientMsg = {ok, {Version, Cipher}},
ssl_test_lib:check_result(Server, ServerMsg, Client, ClientMsg),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%-------------------------------------------------------------------
max_handshake_size() ->
[{doc,"Test that we can set max_handshake_size to max value."}].
max_handshake_size(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{max_handshake_size, 8388607} |ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{max_handshake_size, 8388607} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok).
%%-------------------------------------------------------------------
options_not_proplist() ->
[{doc,"Test what happens if an option is not a key value tuple"}].
options_not_proplist(Config) when is_list(Config) ->
BadOption = {client_preferred_next_protocols,
client, [<<"spdy/3">>,<<"http/1.1">>], <<"http/1.1">>},
{option_not_a_key_value_tuple, BadOption} =
ssl:connect("twitter.com", 443, [binary, {active, false},
BadOption]).
%%-------------------------------------------------------------------
invalid_options() ->
[{doc,"Test what happens when we give invalid options"}].
invalid_options(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Check = fun(Client, Server, {versions, [sslv2, sslv3]} = Option) ->
ssl_test_lib:check_result(Server,
{error, {options, {sslv2, Option}}},
Client,
{error, {options, {sslv2, Option}}});
(Client, Server, Option) ->
ssl_test_lib:check_result(Server,
{error, {options, Option}},
Client,
{error, {options, Option}})
end,
TestOpts =
[{versions, [sslv2, sslv3]},
{verify, 4},
{verify_fun, function},
{fail_if_no_peer_cert, 0},
{depth, four},
{certfile, 'cert.pem'},
{keyfile,'key.pem' },
{password, foo},
{cacertfile, ""},
{dhfile,'dh.pem' },
{ciphers, [{foo, bar, sha, ignore}]},
{reuse_session, foo},
{reuse_sessions, 0},
{renegotiate_at, "10"},
{mode, depech},
{packet, 8.0},
{packet_size, "2"},
{header, a},
{active, trice},
{key, 'key.pem' }],
TestOpts2 =
[{[{anti_replay, '10k'}],
%% anti_replay is a server only option but tested with client
%% for simplicity
{options,dependency,{anti_replay,{versions,['tlsv1.3']}}}},
{[{cookie, false}],
{options,dependency,{cookie,{versions,['tlsv1.3']}}}},
{[{supported_groups, []}],
{options,dependency,{supported_groups,{versions,['tlsv1.3']}}}},
{[{use_ticket, [<<1,2,3,4>>]}],
{options,dependency,{use_ticket,{versions,['tlsv1.3']}}}},
{[{verify, verify_none}, {fail_if_no_peer_cert, true}],
{options, incompatible,
{verify, verify_none},
{fail_if_no_peer_cert, true}}}],
[begin
Server =
ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, [TestOpt | ServerOpts]}]),
%% Will never reach a point where port is used.
Client =
ssl_test_lib:start_client_error([{node, ClientNode}, {port, 0},
{host, Hostname}, {from, self()},
{options, [TestOpt | ClientOpts]}]),
Check(Client, Server, TestOpt),
ok
end || TestOpt <- TestOpts],
[begin
start_client_negative(Config, TestOpt, ErrorMsg),
ok
end || {TestOpt, ErrorMsg} <- TestOpts2],
ok.
%%-------------------------------------------------------------------
default_reject_anonymous()->
[{doc,"Test that by default anonymous cipher suites are rejected "}].
default_reject_anonymous(Config) when is_list(Config) ->
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
Version = ssl_test_lib:protocol_version(Config),
TLSVersion = ssl_test_lib:tls_version(Version),
[CipherSuite | _] = ssl_test_lib:ecdh_dh_anonymous_suites(TLSVersion),
Server = ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options,
[{ciphers,[CipherSuite]} |
ClientOpts]}]),
ssl_test_lib:check_server_alert(Server, Client, insufficient_security).
%%-------------------------------------------------------------------
cb_info() ->
[{doc,"Test that we can set cb_info."}].
cb_info(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
Protocol = proplists:get_value(protocol, Config, tls),
CbInfo =
case Protocol of
tls ->
{cb_info, {gen_tcp, tcp, tcp_closed, tcp_error}};
dtls ->
{cb_info, {gen_udp, udp, udp_closed, udp_error}}
end,
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [CbInfo | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [CbInfo | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok).
%%-------------------------------------------------------------------
log_alert() ->
[{doc,"Test that we can set log_alert and that it translates to correct log_level"
" that has replaced this option"}].
log_alert(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{log_alert, true} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
{Client, CSock} = ssl_test_lib:start_client([return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{log_alert, false} | ClientOpts]}]),
{ok, [{log_level, none}]} = ssl:connection_information(CSock, [log_level]),
ssl_test_lib:check_result(Server, ok, Client, ok).
%%-------------------------------------------------------------------
%% Note that these test only test that the options are valid to set. As application data
%% is a stream you can not test that the send acctually splits it up as when it arrives
%% again at the user layer it may be concatenated. But COVER can show that the split up
%% code has been run.
rizzo_disabled() ->
[{doc, "Test original beast mitigation disable option for SSL 3.0 and TLS 1.0"}].
rizzo_disabled(Config) ->
ClientOpts = [{beast_mitigation, disabled} | ssl_test_lib:ssl_options(client_rsa_opts, Config)],
ServerOpts = [{beast_mitigation, disabled} | ssl_test_lib:ssl_options(server_rsa_opts, Config)],
ssl_test_lib:basic_test(ClientOpts, ServerOpts, Config).
%%-------------------------------------------------------------------
rizzo_zero_n() ->
[{doc, "Test zero_n beast mitigation option (same affect as original disable option) for SSL 3.0 and TLS 1.0"}].
rizzo_zero_n(Config) ->
ClientOpts = [{beast_mitigation, zero_n} | ssl_test_lib:ssl_options(client_rsa_opts, Config)],
ServerOpts = [{beast_mitigation, zero_n} | ssl_test_lib:ssl_options(server_rsa_opts, Config)],
ssl_test_lib:basic_test(ClientOpts, ServerOpts, Config).
%%-------------------------------------------------------------------
rizzo_one_n_minus_one () ->
[{doc, "Test beast_mitigation option one_n_minus_one (same affect as default) for SSL 3.0 and TLS 1.0"}].
rizzo_one_n_minus_one (Config) ->
ClientOpts = [{beast_mitigation, one_n_minus_one } | ssl_test_lib:ssl_options(client_rsa_opts, Config)],
ServerOpts = [{beast_mitigation, one_n_minus_one} | ssl_test_lib:ssl_options(server_rsa_opts, Config)],
ssl_test_lib:basic_test(ClientOpts, ServerOpts, Config).
%%-------------------------------------------------------------------
supported_groups() ->
[{doc,"Test the supported_groups option in TLS 1.3."}].
supported_groups(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{supported_groups, [x448, x25519]} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{supported_groups,[x448]} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
%%--------------------------------------------------------------------
honor_client_cipher_order_tls13() ->
[{doc,"Test API honor server cipher order in TLS 1.3."}].
honor_client_cipher_order_tls13(Config) when is_list(Config) ->
ClientCiphers = [#{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384},
#{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256}],
ServerCiphers = [#{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256},
#{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384}],
honor_cipher_order(Config, false, ServerCiphers, ClientCiphers, #{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384}).
%%--------------------------------------------------------------------
client_options_negative_version_gap() ->
[{doc,"Test client options with faulty version gap."}].
client_options_negative_version_gap(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1', 'tlsv1.3']}],
{options, missing_version,
{'tlsv1.2', {versions,[tlsv1, 'tlsv1.3']}}}).
%%--------------------------------------------------------------------
client_options_negative_dependency_version() ->
[{doc,"Test client options with faulty version dependency."}].
client_options_negative_dependency_version(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1.1', 'tlsv1.2']},
{session_tickets, manual}],
{options,dependency,
{session_tickets,{versions,['tlsv1.3']}}}).
%%--------------------------------------------------------------------
client_options_negative_dependency_stateless() ->
[{doc,"Test client options with faulty 'session_tickets' option."}].
client_options_negative_dependency_stateless(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{anti_replay, '10k'},
{session_tickets, manual}],
{options,dependency,
{anti_replay,{session_tickets,[stateless]}}}).
%%--------------------------------------------------------------------
client_options_negative_dependency_role() ->
[{doc,"Test client options with faulty role."}].
client_options_negative_dependency_role(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, stateless}],
{options,role,
{session_tickets,{stateless,{client,[disabled,manual,auto]}}}}).
%%--------------------------------------------------------------------
client_options_negative_early_data() ->
[{doc,"Test client option early_data."}].
client_options_negative_early_data(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1.2']},
{early_data, "test"}],
{options,dependency,
{early_data,{versions,['tlsv1.3']}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{early_data, "test"}],
{options,dependency,
{early_data,{session_tickets,[manual,auto]}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, stateful},
{early_data, "test"}],
{options,role,
{session_tickets,
{stateful,{client,[disabled,manual,auto]}}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, disabled},
{early_data, "test"}],
{options,dependency,
{early_data,{session_tickets,[manual,auto]}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual},
{early_data, "test"}],
{options,dependency,
{early_data, use_ticket}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual},
{use_ticket, [<<"ticket">>]},
{early_data, "test"}],
{options, type,
{early_data, {"test", not_binary}}}),
%% All options are ok but there is no server
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual},
{use_ticket, [<<"ticket">>]},
{early_data, <<"test">>}],
econnrefused),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, auto},
{early_data, "test"}],
{options, type,
{early_data, {"test", not_binary}}}),
%% All options are ok but there is no server
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, auto},
{early_data, <<"test">>}],
econnrefused).
%%--------------------------------------------------------------------
server_options_negative_early_data() ->
[{doc,"Test server option early_data."}].
server_options_negative_early_data(Config) when is_list(Config) ->
start_server_negative(Config, [{versions, ['tlsv1.2']},
{early_data, "test"}],
{options,dependency,
{early_data,{versions,['tlsv1.3']}}}),
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{early_data, "test"}],
{options,dependency,
{early_data,{session_tickets,[stateful,stateless]}}}),
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual},
{early_data, "test"}],
{options,role,
{session_tickets,
{manual,{server,[disabled,stateful,stateless]}}}}),
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, disabled},
{early_data, "test"}],
{options,dependency,
{early_data,{session_tickets,[stateful,stateless]}}}),
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, stateful},
{early_data, "test"}],
{options,role,
{early_data,{"test",{server,[disabled,enabled]}}}}).
%%--------------------------------------------------------------------
server_options_negative_version_gap() ->
[{doc,"Test server options with faulty version gap."}].
server_options_negative_version_gap(Config) when is_list(Config) ->
start_server_negative(Config, [{versions, ['tlsv1', 'tlsv1.3']}],
{options, missing_version,
{'tlsv1.2', {versions,[tlsv1, 'tlsv1.3']}}}).
%%--------------------------------------------------------------------
server_options_negative_dependency_role() ->
[{doc,"Test server options with faulty role."}].
server_options_negative_dependency_role(Config) when is_list(Config) ->
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual}],
{options,role,
{session_tickets,{manual,{server,[disabled,stateful,stateless]}}}}).
%%--------------------------------------------------------------------
honor_server_cipher_order_tls13() ->
[{doc,"Test API honor server cipher order in TLS 1.3."}].
honor_server_cipher_order_tls13(Config) when is_list(Config) ->
ClientCiphers = [#{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384},
#{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256}],
ServerCiphers = [#{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256},
#{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384}],
honor_cipher_order(Config, true, ServerCiphers,
ClientCiphers, #{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256}).
%%--------------------------------------------------------------------
getstat() ->
[{doc, "Test that you use ssl:getstat on a TLS socket"}].
getstat(Config) when is_list(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Port0 = ssl_test_lib:inet_port(ServerNode),
{ok, ListenSocket} = ssl:listen(Port0, [ServerOpts]),
{ok, _} = ssl:getstat(ListenSocket),
ssl:close(ListenSocket),
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, ssl_getstat, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, ssl_getstat, []}},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server, ok, Client, ok).
invalid_options_tls13() ->
[{doc, "Test invalid options with TLS 1.3"}].
invalid_options_tls13(Config) when is_list(Config) ->
TestOpts =
[{{beast_mitigation, one_n_minus_one},
{options, dependency,
{beast_mitigation,{versions,[tlsv1]}}},
common},
{{next_protocols_advertised, [<<"http/1.1">>]},
{options, dependency,
{next_protocols_advertised,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
server},
{{client_preferred_next_protocols,
{client, [<<"http/1.1">>]}},
{options, dependency,
{client_preferred_next_protocols,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
client},
{{client_renegotiation, false},
{options, dependency,
{client_renegotiation,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
server
},
{{cookie, false},
{option , server_only, cookie},
client
},
{{padding_check, false},
{options, dependency,
{padding_check,{versions,[tlsv1]}}},
common},
{{psk_identity, "Test-User"},
{options, dependency,
{psk_identity,{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
common},
{{user_lookup_fun,
{fun ssl_test_lib:user_lookup/3, <<1,2,3>>}},
{options, dependency,
{user_lookup_fun,{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
common},
{{reuse_session, fun(_,_,_,_) -> false end},
{options, dependency,
{reuse_session,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
server},
{{reuse_session, <<1,2,3,4>>},
{options, dependency,
{reuse_session,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
client},
{{reuse_sessions, true},
{options, dependency,
{reuse_sessions,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
common},
{{secure_renegotiate, false},
{options, dependency,
{secure_renegotiate,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
common},
{{srp_identity, false},
{options, dependency,
{srp_identity,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
client}
],
Fun = fun(Option, ErrorMsg, Type) ->
case Type of
server ->
start_server_negative(Config,
[Option,{versions, ['tlsv1.3']}],
ErrorMsg);
client ->
start_client_negative(Config,
[Option,{versions, ['tlsv1.3']}],
ErrorMsg);
common ->
start_server_negative(Config,
[Option,{versions, ['tlsv1.3']}],
ErrorMsg),
start_client_negative(Config,
[Option,{versions, ['tlsv1.3']}],
ErrorMsg)
end
end,
[Fun(Option, ErrorMsg, Type) || {Option, ErrorMsg, Type} <- TestOpts].
cookie() ->
[{doc, "Test cookie extension in TLS 1.3"}].
cookie(Config) when is_list(Config) ->
cookie_extension(Config, true),
cookie_extension(Config, false).
Checker functions
connection_information_result(Socket) ->
{ok, Info = [_ | _]} = ssl:connection_information(Socket),
case length(Info) > 3 of
true ->
%% Atleast one ssl_option() is set
ct:log("Info ~p", [Info]),
ok;
false ->
ct:fail(no_ssl_options_returned)
end.
secret_connection_info_result(Socket) ->
{ok, [{protocol, Protocol}]} = ssl:connection_information(Socket, [protocol]),
{ok, ConnInfo} = ssl:connection_information(Socket, [client_random, server_random, master_secret]),
check_connection_info(Protocol, ConnInfo).
keylog_connection_info_result(Socket, KeepSecrets) ->
{ok, [{protocol, Protocol}]} = ssl:connection_information(Socket, [protocol]),
{ok, ConnInfo} = ssl:connection_information(Socket, [keylog]),
check_keylog_info(Protocol, ConnInfo, KeepSecrets).
check_keylog_info('tlsv1.3', [{keylog, ["CLIENT_HANDSHAKE_TRAFFIC_SECRET"++_,_|_]=Keylog}], true) ->
{ok, Keylog};
check_keylog_info('tlsv1.3', []=Keylog, false) ->
{ok, Keylog};
check_keylog_info('tlsv1.2', [{keylog, ["CLIENT_RANDOM"++_]=Keylog}], _) ->
{ok, Keylog};
check_keylog_info(NotSup, [], _) when NotSup == 'tlsv1.1'; NotSup == tlsv1; NotSup == 'dtlsv1.2'; NotSup == dtlsv1 ->
{ok, []};
check_keylog_info(_, Unexpected, _) ->
{unexpected, Unexpected}.
check_srp_in_connection_information(_Socket, _Username, client) ->
ok;
check_srp_in_connection_information(Socket, Username, server) ->
{ok, Info} = ssl:connection_information(Socket),
ct:log("Info ~p~n", [Info]),
case proplists:get_value(srp_username, Info, not_found) of
Username ->
ok;
not_found ->
ct:fail(srp_username_not_found)
end.
In TLS 1.3 the master_secret field is used to store multiple secrets from the key schedule and it is a tuple .
%% client_random and server_random are not used in the TLS 1.3 key schedule.
check_connection_info('tlsv1.3', [{client_random, ClientRand}, {master_secret, {master_secret, MasterSecret}}]) ->
is_binary(ClientRand) andalso is_binary(MasterSecret);
check_connection_info('tlsv1.3', [{server_random, ServerRand}, {master_secret, {master_secret, MasterSecret}}]) ->
is_binary(ServerRand) andalso is_binary(MasterSecret);
check_connection_info(_, [{client_random, ClientRand}, {server_random, ServerRand}, {master_secret, MasterSecret}]) ->
is_binary(ClientRand) andalso is_binary(ServerRand) andalso is_binary(MasterSecret);
check_connection_info(_, _) ->
false.
prf_verify_value(Socket, TlsVer, Expected, Algo) ->
Ret = ssl:prf(Socket, <<>>, <<>>, [<<>>], 16),
case TlsVer of
sslv3 ->
case Ret of
{error, undefined} -> ok;
_ ->
{error, {expected, {error, undefined},
got, Ret, tls_ver, TlsVer, prf_algorithm, Algo}}
end;
_ ->
case Ret of
{ok, Expected} -> ok;
{ok, Val} -> {error, {expected, Expected, got, Val, tls_ver, TlsVer,
prf_algorithm, Algo}}
end
end.
try_recv_active(Socket) ->
ssl:send(Socket, "Hello world"),
{error, einval} = ssl:recv(Socket, 11),
ok.
try_recv_active_once(Socket) ->
{error, einval} = ssl:recv(Socket, 11),
ok.
controlling_process_result(Socket, Pid, Msg) ->
ok = ssl:controlling_process(Socket, Pid),
%% Make sure other side has evaluated controlling_process
%% before message is sent
ct:sleep(?SLEEP),
ssl:send(Socket, Msg),
no_result_msg.
controller_dies_result(_Socket, _Pid, _Msg) ->
receive Result -> Result end.
send_recv_result_timeout_client(Socket) ->
{error, timeout} = ssl:recv(Socket, 11, 500),
{error, timeout} = ssl:recv(Socket, 11, 0),
ssl:send(Socket, "Hello world"),
receive
Msg ->
io:format("Msg ~p~n",[Msg])
after 500 ->
ok
end,
{ok, "Hello world"} = ssl:recv(Socket, 11, 500),
ok.
send_recv_result_timeout_server(Socket) ->
ssl:send(Socket, "Hello"),
{ok, "Hello world"} = ssl:recv(Socket, 11),
ssl:send(Socket, " world"),
ok.
do_recv_close(Socket) ->
{error, closed} = ssl:recv(Socket, 11),
receive
{_,{error,closed}} ->
error_extra_close_sent_to_user_process
after 500 ->
ok
end.
tls_close(Socket) ->
ok = ssl_test_lib:send_recv_result(Socket),
case ssl:close(Socket, 10000) of
ok ->
ok;
{error, closed} ->
ok;
Other ->
ct:fail(Other)
end.
run_error_server_close([Pid | Opts]) ->
{ok, Listen} = ssl:listen(0, Opts),
{ok,{_, Port}} = ssl:sockname(Listen),
Pid ! {self(), Port},
{ok, Socket} = ssl:transport_accept(Listen),
Pid ! ssl:close(Socket).
run_error_server([ Pid | Opts]) ->
{ok, Listen} = ssl:listen(0, Opts),
{ok,{_, Port}} = ssl:sockname(Listen),
Pid ! {self(), Port},
{ok, Socket} = ssl:transport_accept(Listen),
Pid ! ssl:controlling_process(Socket, self()).
run_client_error([Port, Opts]) ->
ssl:connect("localhost", Port, Opts).
no_recv_no_active(Socket) ->
receive
{ssl_closed, Socket} ->
ct:fail(received_active_msg)
after 5000 ->
ok
end.
connection_info_result(Socket) ->
{ok, Info} = ssl:connection_information(Socket, [protocol, selected_cipher_suite]),
{ok, {proplists:get_value(protocol, Info), proplists:get_value(selected_cipher_suite, Info)}}.
%%--------------------------------------------------------------------
Internal functions ------------------------------------------------
%%--------------------------------------------------------------------
prf_create_plan(TlsVer, _PRFs, Results) when TlsVer == tlsv1
orelse TlsVer == 'tlsv1.1'
orelse TlsVer == 'dtlsv1' ->
Ciphers = prf_get_ciphers(TlsVer, default_prf),
{_, Expected} = lists:keyfind(md5sha, 1, Results),
[[{ciphers, Ciphers}, {expected, Expected}, {prf, md5sha}]];
prf_create_plan(TlsVer, PRFs, Results) when TlsVer == 'tlsv1.2' orelse TlsVer == 'dtlsv1.2' ->
lists:foldl(
fun(PRF, Acc) ->
Ciphers = prf_get_ciphers(TlsVer, PRF),
case Ciphers of
[] ->
ct:log("No ciphers for PRF algorithm ~p. Skipping.", [PRF]),
Acc;
Ciphers ->
{_, Expected} = lists:keyfind(PRF, 1, Results),
[[{ciphers, Ciphers}, {expected, Expected}, {prf, PRF}] | Acc]
end
end, [], PRFs).
prf_get_ciphers(TlsVer, PRF) ->
PrfFilter = fun(Value) -> Value =:= PRF end,
RSACertNoSpecialConf = fun(rsa) ->
true;
(ecdhe_rsa) ->
lists:member(ecdh, crypto:supports(public_keys));
(dhe_rsa) ->
true;
(_) ->
false
end,
ssl:filter_cipher_suites(ssl:cipher_suites(default, TlsVer), [{key_exchange, RSACertNoSpecialConf},
{prf, PrfFilter}]).
prf_run_test(_, TlsVer, [], _, Prf) ->
ct:comment(lists:flatten(io_lib:format("cipher_list_empty Ver: ~p PRF: ~p", [TlsVer, Prf])));
prf_run_test(Config, TlsVer, Ciphers, Expected, Prf) ->
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
BaseOpts = [{active, true}, {versions, [TlsVer]}, {ciphers, Ciphers}, {protocol, tls_or_dtls(TlsVer)}],
ServerOpts = BaseOpts ++ proplists:get_value(server_rsa_opts, Config, []),
ClientOpts = BaseOpts ++ proplists:get_value(client_rsa_opts, Config, []),
Server = ssl_test_lib:start_server(
[{node, ServerNode}, {port, 0}, {from, self()},
{mfa, {?MODULE, prf_verify_value, [TlsVer, Expected, Prf]}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client(
[{node, ClientNode}, {port, Port},
{host, Hostname}, {from, self()},
{mfa, {?MODULE, prf_verify_value, [TlsVer, Expected, Prf]}},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
tls_or_dtls('dtlsv1') ->
dtls;
tls_or_dtls('dtlsv1.2') ->
dtls;
tls_or_dtls(_) ->
tls.
active_n_common(S, N) ->
ok = ssl:setopts(S, [{active,-N}]),
receive
{ssl_passive, S} -> ok
after
1000 ->
error({error,ssl_passive_failure})
end,
[{active,false}] = ok(ssl:getopts(S, [active])),
ok = ssl:setopts(S, [{active,0}]),
receive
{ssl_passive, S} -> ok
after
1000 ->
error({error,ssl_passive_failure})
end,
ok = ssl:setopts(S, [{active,32767}]),
{error,{options,_}} = ssl:setopts(S, [{active,1}]),
{error,{options,_}} = ssl:setopts(S, [{active,-32769}]),
ok = ssl:setopts(S, [{active,-32768}]),
receive
{ssl_passive, S} -> ok
after
1000 ->
error({error,ssl_passive_failure})
end,
[{active,false}] = ok(ssl:getopts(S, [active])),
ok = ssl:setopts(S, [{active,N}]),
ok = ssl:setopts(S, [{active,true}]),
[{active,true}] = ok(ssl:getopts(S, [active])),
receive
_ -> error({error,active_n})
after
0 ->
ok
end,
ok = ssl:setopts(S, [{active,N}]),
ok = ssl:setopts(S, [{active,once}]),
[{active,once}] = ok(ssl:getopts(S, [active])),
receive
_ -> error({error,active_n})
after
0 ->
ok
end,
{error,{options,_}} = ssl:setopts(S, [{active,32768}]),
ok = ssl:setopts(S, [{active,false}]),
[{active,false}] = ok(ssl:getopts(S, [active])),
ok.
ok({ok,V}) -> V.
repeat(N, Fun) ->
repeat(N, N, Fun).
repeat(N, T, Fun) when is_integer(N), N > 0 ->
Fun(T-N),
repeat(N-1, T, Fun);
repeat(_, _, _) ->
ok.
get_close(Pid, Where) ->
receive
{'EXIT', Pid, _Reason} ->
receive
{_, {ssl_closed, Socket}} ->
ct:log("Socket closed ~p~n",[Socket]);
Unexpected ->
ct:log("Unexpected ~p~n",[Unexpected]),
ct:fail({line, ?LINE-1})
after 5000 ->
ct:fail({timeout, {line, ?LINE, Where}})
end;
Unexpected ->
ct:log("Unexpected ~p~n",[Unexpected]),
ct:fail({line, ?LINE-1})
after 5000 ->
ct:fail({timeout, {line, ?LINE, Where}})
end.
ssl_active_recv(N) ->
ssl_active_recv(N, []).
ssl_active_recv(0, Acc) ->
Acc;
ssl_active_recv(N, Acc) ->
receive
{ssl, _, Bytes} ->
ssl_active_recv(N-length(Bytes), Acc ++ Bytes)
end.
honor_cipher_order(Config, Honor, ServerCiphers, ClientCiphers, Expected) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, connection_info_result, []}},
{options, [{ciphers, ServerCiphers}, {honor_cipher_order, Honor}
| ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, connection_info_result, []}},
{options, [{ciphers, ClientCiphers}
| ClientOpts]}]),
Version = ssl_test_lib:protocol_version(Config),
ServerMsg = ClientMsg = {ok, {Version, Expected}},
ssl_test_lib:check_result(Server, ServerMsg, Client, ClientMsg),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
cookie_extension(Config, Cookie) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
15 bytes
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Trigger a HelloRetryRequest
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{options, [{supported_groups, [x448,
secp256r1,
secp384r1]},
{cookie, Cookie}|ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ClientOpts}]),
ok = ssl_test_lib:send(Client, Data),
Data = ssl_test_lib:check_active_receive(Server, Data),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
start_client_negative(Config, Options, Error) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Port = ssl_test_lib:inet_port(ServerNode),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{return_error, econnrefused},
{mfa, {?MODULE, connection_info_result, []}},
{options, Options ++ ClientOpts}]),
ct:pal("Actual: ~p~nExpected: ~p", [Client, {connect_failed, Error}]),
{connect_failed, Error} = Client.
start_server_negative(Config, Options, Error) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{_, ServerNode, _} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, connection_info_result, []}},
{options, Options ++ ServerOpts}]),
ct:pal("Actual: ~p~nExpected: ~p", [Server,Error]),
Error = Server.
der_input_opts(Opts) ->
Certfile = proplists:get_value(certfile, Opts),
CaCertsfile = proplists:get_value(cacertfile, Opts),
Keyfile = proplists:get_value(keyfile, Opts),
Dhfile = proplists:get_value(dhfile, Opts),
[{_, Cert, _}] = ssl_test_lib:pem_to_der(Certfile),
[{Asn1Type, Key, _}] = ssl_test_lib:pem_to_der(Keyfile),
[{_, DHParams, _}] = ssl_test_lib:pem_to_der(Dhfile),
CaCerts =
lists:map(fun(Entry) ->
{_, CaCert, _} = Entry,
CaCert
end, ssl_test_lib:pem_to_der(CaCertsfile)),
{Cert, {Asn1Type, Key}, CaCerts, DHParams}.
ssl_getstat(Socket) ->
ssl:send(Socket, "From Erlang to Erlang"),
{ok, Stats} = ssl:getstat(Socket),
List = lists:dropwhile(fun({_, 0}) ->
true;
({_, _}) ->
false
end, Stats),
case List of
[] ->
nok;
_ ->
ok
end.
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssl/test/ssl_api_SUITE.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
Common test
Test cases
Apply export
TODO Keep?
--------------------------------------------------------------------
Common Test interface functions -----------------------------------
--------------------------------------------------------------------
Only relevant for SSL 3.0 and TLS 1.0
Original option
Same effect as disable
Same as default
--------------------------------------------------------------------
Test Cases --------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
psk_key_exchange_modes extensions.
------------------------------------------------------------------
--------------------------------------------------------------------
That is ssl:handshake_cancel returns ok
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Schedule out
Schedule out
This can be a valid thing to do as
options are inherited by the accept socket
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
socket are now read, so ramining are form the server socket
--------------------------------------------------------------------
so that they are connected
Test that clients die
Test that clients die when process disappear
Make sure server finishes and verification
and is in coonection state before
killing client
Test that clients die when the controlling process have changed
Test that servers die
so that they are connected
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Make sure there is no outstanding clean cert db msg in manager
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
anti_replay is a server only option but tested with client
for simplicity
Will never reach a point where port is used.
-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
Note that these test only test that the options are valid to set. As application data
is a stream you can not test that the send acctually splits it up as when it arrives
again at the user layer it may be concatenated. But COVER can show that the split up
code has been run.
-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
All options are ok but there is no server
All options are ok but there is no server
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Atleast one ssl_option() is set
client_random and server_random are not used in the TLS 1.3 key schedule.
Make sure other side has evaluated controlling_process
before message is sent
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright Ericsson AB 2019 - 2019 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(ssl_api_SUITE).
-behaviour(ct_suite).
-include_lib("common_test/include/ct.hrl").
-include_lib("ssl/src/ssl_api.hrl").
-export([all/0,
groups/0,
init_per_suite/1,
init_per_group/2,
init_per_testcase/2,
end_per_suite/1,
end_per_group/2,
end_per_testcase/2
]).
-export([conf_signature_algs/0,
conf_signature_algs/1,
no_common_signature_algs/0,
no_common_signature_algs/1,
default_reject_anonymous/0,
default_reject_anonymous/1,
connection_information_with_srp/0,
connection_information_with_srp/1,
peercert/0,
peercert/1,
peercert_with_client_cert/0,
peercert_with_client_cert/1,
connection_information/0,
connection_information/1,
secret_connection_info/0,
secret_connection_info/1,
keylog_connection_info/0,
keylog_connection_info/1,
versions/0,
versions/1,
active_n/0,
active_n/1,
dh_params/0,
dh_params/1,
prf/0,
prf/1,
hibernate/0,
hibernate/1,
hibernate_right_away/0,
hibernate_right_away/1,
listen_socket/0,
listen_socket/1,
peername/0,
peername/1,
recv_active/0,
recv_active/1,
recv_active_once/0,
recv_active_once/1,
recv_active_n/0,
recv_active_n/1,
recv_no_active_msg/0,
recv_no_active_msg/1,
recv_timeout/0,
recv_timeout/1,
recv_close/0,
recv_close/1,
controlling_process/0,
controlling_process/1,
controller_dies/0,
controller_dies/1,
controlling_process_transport_accept_socket/0,
controlling_process_transport_accept_socket/1,
close_with_timeout/0,
close_with_timeout/1,
close_in_error_state/0,
close_in_error_state/1,
call_in_error_state/0,
call_in_error_state/1,
close_transport_accept/0,
close_transport_accept/1,
abuse_transport_accept_socket/0,
abuse_transport_accept_socket/1,
honor_server_cipher_order/0,
honor_server_cipher_order/1,
honor_client_cipher_order/0,
honor_client_cipher_order/1,
honor_client_cipher_order_tls13/0,
honor_client_cipher_order_tls13/1,
honor_server_cipher_order_tls13/0,
honor_server_cipher_order_tls13/1,
ipv6/0,
ipv6/1,
der_input/0,
der_input/1,
new_options_in_handshake/0,
new_options_in_handshake/1,
max_handshake_size/0,
max_handshake_size/1,
invalid_certfile/0,
invalid_certfile/1,
invalid_cacertfile/0,
invalid_cacertfile/1,
invalid_keyfile/0,
invalid_keyfile/1,
options_not_proplist/0,
options_not_proplist/1,
invalid_options/0,
invalid_options/1,
cb_info/0,
cb_info/1,
log_alert/0,
log_alert/1,
getstat/0,
getstat/1,
handshake_continue/0,
handshake_continue/1,
handshake_continue_timeout/0,
handshake_continue_timeout/1,
handshake_continue_change_verify/0,
handshake_continue_change_verify/1,
hello_client_cancel/0,
hello_client_cancel/1,
hello_server_cancel/0,
hello_server_cancel/1,
handshake_continue_tls13_client/0,
handshake_continue_tls13_client/1,
rizzo_disabled/0,
rizzo_disabled/1,
rizzo_zero_n/0,
rizzo_zero_n/1,
rizzo_one_n_minus_one/0,
rizzo_one_n_minus_one/1,
supported_groups/0,
supported_groups/1,
client_options_negative_version_gap/0,
client_options_negative_version_gap/1,
client_options_negative_dependency_version/0,
client_options_negative_dependency_version/1,
client_options_negative_dependency_stateless/0,
client_options_negative_dependency_stateless/1,
client_options_negative_dependency_role/0,
client_options_negative_dependency_role/1,
client_options_negative_early_data/0,
client_options_negative_early_data/1,
server_options_negative_early_data/0,
server_options_negative_early_data/1,
server_options_negative_version_gap/0,
server_options_negative_version_gap/1,
server_options_negative_dependency_role/0,
server_options_negative_dependency_role/1,
invalid_options_tls13/0,
invalid_options_tls13/1,
cookie/0,
cookie/1
]).
-export([connection_information_result/1,
connection_info_result/1,
secret_connection_info_result/1,
keylog_connection_info_result/2,
check_srp_in_connection_information/3,
check_connection_info/2,
prf_verify_value/4,
try_recv_active/1,
try_recv_active_once/1,
controlling_process_result/3,
controller_dies_result/3,
send_recv_result_timeout_client/1,
send_recv_result_timeout_server/1,
do_recv_close/1,
tls_close/1,
no_recv_no_active/1,
ssl_getstat/1,
run_error_server/1,
run_error_server_close/1,
run_client_error/1
]).
-define(SLEEP, 500).
all() ->
[
{group, 'tlsv1.3'},
{group, 'tlsv1.2'},
{group, 'tlsv1.1'},
{group, 'tlsv1'},
{group, 'dtlsv1.2'},
{group, 'dtlsv1'}
].
groups() ->
[
{'tlsv1.3', [], ((gen_api_tests() ++ tls13_group() ++
handshake_paus_tests()) --
[dh_params,
honor_server_cipher_order,
honor_client_cipher_order,
new_options_in_handshake,
handshake_continue_tls13_client,
invalid_options])
++ (since_1_2() -- [conf_signature_algs])},
{'tlsv1.2', [], gen_api_tests() ++ since_1_2() ++ handshake_paus_tests() ++ pre_1_3()},
{'tlsv1.1', [], gen_api_tests() ++ handshake_paus_tests() ++ pre_1_3()},
{'tlsv1', [], gen_api_tests() ++ handshake_paus_tests() ++ pre_1_3() ++ beast_mitigation_test()},
{'dtlsv1.2', [], (gen_api_tests() --
[invalid_keyfile, invalid_certfile, invalid_cacertfile,
invalid_options, new_options_in_handshake]) ++
handshake_paus_tests() -- [handshake_continue_tls13_client] ++ pre_1_3()},
{'dtlsv1', [], (gen_api_tests() --
[invalid_keyfile, invalid_certfile, invalid_cacertfile,
invalid_options, new_options_in_handshake]) ++
handshake_paus_tests() -- [handshake_continue_tls13_client] ++ pre_1_3()}
].
since_1_2() ->
[
conf_signature_algs,
no_common_signature_algs
].
pre_1_3() ->
[
default_reject_anonymous,
connection_information_with_srp,
prf
].
gen_api_tests() ->
[
peercert,
peercert_with_client_cert,
connection_information,
secret_connection_info,
keylog_connection_info,
versions,
active_n,
dh_params,
hibernate,
hibernate_right_away,
listen_socket,
peername,
recv_active,
recv_active_once,
recv_active_n,
recv_no_active_msg,
recv_timeout,
recv_close,
controlling_process,
controller_dies,
controlling_process_transport_accept_socket,
close_with_timeout,
close_in_error_state,
call_in_error_state,
close_transport_accept,
abuse_transport_accept_socket,
honor_server_cipher_order,
honor_client_cipher_order,
ipv6,
der_input,
new_options_in_handshake,
max_handshake_size,
invalid_certfile,
invalid_cacertfile,
invalid_keyfile,
options_not_proplist,
invalid_options,
cb_info,
log_alert,
getstat
].
handshake_paus_tests() ->
[
handshake_continue,
handshake_continue_timeout,
handshake_continue_change_verify,
hello_client_cancel,
hello_server_cancel,
handshake_continue_tls13_client
].
beast_mitigation_test() ->
rizzo_disabled,
rizzo_zero_n,
rizzo_one_n_minus_one
].
tls13_group() ->
[
supported_groups,
honor_server_cipher_order_tls13,
honor_client_cipher_order_tls13,
client_options_negative_version_gap,
client_options_negative_dependency_version,
client_options_negative_dependency_stateless,
client_options_negative_dependency_role,
client_options_negative_early_data,
server_options_negative_early_data,
server_options_negative_version_gap,
server_options_negative_dependency_role,
invalid_options_tls13,
cookie
].
init_per_suite(Config0) ->
catch crypto:stop(),
try crypto:start() of
ok ->
ssl_test_lib:clean_start(),
ssl_test_lib:make_rsa_cert(Config0)
catch _:_ ->
{skip, "Crypto did not start"}
end.
end_per_suite(_Config) ->
ssl:stop(),
application:unload(ssl),
application:stop(crypto).
init_per_group(GroupName, Config) ->
case ssl_test_lib:is_protocol_version(GroupName) of
true ->
ssl_test_lib:init_per_group(GroupName,
[{client_type, erlang},
{server_type, erlang},
{version, GroupName}
| Config]);
false ->
Config
end.
end_per_group(GroupName, Config) ->
ssl_test_lib:end_per_group(GroupName, Config).
init_per_testcase(prf, Config) ->
ssl_test_lib:ct_log_supported_protocol_versions(Config),
ct:timetrap({seconds, 10}),
Version = ssl_test_lib:protocol_version(Config),
PRFS = [md5, sha, sha256, sha384, sha512],
All are the result of running tls_v1 : prf(PrfAlgo , < < > > , < < > > , < < > > , 16 )
with the specified PRF algorithm
ExpectedPrfResults =
[{md5, <<96,139,180,171,236,210,13,10,28,32,2,23,88,224,235,199>>},
{sha, <<95,3,183,114,33,169,197,187,231,243,19,242,220,228,70,151>>},
{sha256, <<166,249,145,171,43,95,158,232,6,60,17,90,183,180,0,155>>},
{sha384, <<153,182,217,96,186,130,105,85,65,103,123,247,146,91,47,106>>},
{sha512, <<145,8,98,38,243,96,42,94,163,33,53,49,241,4,127,28>>},
TLS 1.0 and 1.1 PRF :
{md5sha, <<63,136,3,217,205,123,200,177,251,211,17,229,132,4,173,80>>}],
TestPlan = prf_create_plan(Version, PRFS, ExpectedPrfResults),
[{prf_test_plan, TestPlan} | Config];
init_per_testcase(handshake_continue_tls13_client, Config) ->
case ssl_test_lib:sufficient_crypto_support('tlsv1.3') of
true ->
ssl_test_lib:ct_log_supported_protocol_versions(Config),
ct:timetrap({seconds, 10}),
Config;
false ->
{skip, "Missing crypto support: TLS 1.3 not supported"}
end;
init_per_testcase(connection_information_with_srp, Config) ->
PKAlg = proplists:get_value(public_keys, crypto:supports()),
case lists:member(srp, PKAlg) of
true ->
Config;
false ->
{skip, "Missing SRP crypto support"}
end;
init_per_testcase(conf_signature_algs, Config) ->
case ssl_test_lib:appropriate_sha(crypto:supports()) of
sha256 ->
ssl_test_lib:ct_log_supported_protocol_versions(Config),
ct:timetrap({seconds, 10}),
Config;
sha ->
{skip, "Tests needs certs with sha256"}
end;
init_per_testcase(_TestCase, Config) ->
ssl_test_lib:ct_log_supported_protocol_versions(Config),
ct:timetrap({seconds, 10}),
Config.
end_per_testcase(internal_active_n, _Config) ->
application:unset_env(ssl, internal_active_n);
end_per_testcase(_TestCase, Config) ->
Config.
peercert() ->
[{doc,"Test API function peercert/1"}].
peercert(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
{mfa, {ssl, peercert, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl, peercert, []}},
{options, ClientOpts}]),
CertFile = proplists:get_value(certfile, ServerOpts),
[{'Certificate', BinCert, _}]= ssl_test_lib:pem_to_der(CertFile),
ServerMsg = {error, no_peercert},
ClientMsg = {ok, BinCert},
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ServerMsg, Client, ClientMsg),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
peercert_with_client_cert() ->
[{doc,"Test API function peercert/1"}].
peercert_with_client_cert(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
{mfa, {ssl, peercert, []}},
{options, [{verify, verify_peer} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl, peercert, []}},
{options, ClientOpts}]),
ServerCertFile = proplists:get_value(certfile, ServerOpts),
[{'Certificate', ServerBinCert, _}]= ssl_test_lib:pem_to_der(ServerCertFile),
ClientCertFile = proplists:get_value(certfile, ClientOpts),
[{'Certificate', ClientBinCert, _}]= ssl_test_lib:pem_to_der(ClientCertFile),
ServerMsg = {ok, ClientBinCert},
ClientMsg = {ok, ServerBinCert},
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ServerMsg, Client, ClientMsg),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
connection_information() ->
[{doc,"Test the API function ssl:connection_information/1"}].
connection_information(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, connection_information_result, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, connection_information_result, []}},
{options, ClientOpts}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
connection_information_with_srp() ->
[{doc,"Test the result of API function ssl:connection_information/1"
"includes srp_username."}].
connection_information_with_srp(Config) when is_list(Config) ->
run_conn_info_srp_test(srp_anon, 'aes_128_cbc', Config).
run_conn_info_srp_test(Kex, Cipher, Config) ->
Version = ssl_test_lib:protocol_version(Config),
TestCiphers = ssl_test_lib:test_ciphers(Kex, Cipher, Version),
case TestCiphers of
[] ->
{skip, {not_sup, Kex, Cipher, Version}};
[TestCipher | _T] ->
do_run_conn_info_srp_test(TestCipher, Version, Config)
end.
do_run_conn_info_srp_test(ErlangCipherSuite, Version, Config) ->
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
SOpts = [{user_lookup_fun, {fun ssl_test_lib:user_lookup/3, undefined}}],
COpts = [{srp_identity, {"Test-User", "secret"}}],
ServerOpts = ssl_test_lib:ssl_options(SOpts, Config),
ClientOpts = ssl_test_lib:ssl_options(COpts, Config),
ct:log("Erlang Cipher Suite is: ~p~n", [ErlangCipherSuite]),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, check_srp_in_connection_information, [<<"Test-User">>, server]}},
{options, [{versions, [Version]}, {ciphers, [ErlangCipherSuite]} |
ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client(
[{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, check_srp_in_connection_information, [<<"Test-User">>, client]}},
{options, [{versions, [Version]}, {ciphers, [ErlangCipherSuite]} |
ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
secret_connection_info() ->
[{doc,"Test the API function ssl:connection_information/2"}].
secret_connection_info(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, secret_connection_info_result, []}},
{options, [{verify, verify_peer} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, secret_connection_info_result, []}},
{options, [{verify, verify_peer} |ClientOpts]}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, true, Client, true),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
keylog_connection_info() ->
[{doc,"Test the API function ssl:connection_information/2"}].
keylog_connection_info(Config) when is_list(Config) ->
keylog_connection_info(Config, true),
keylog_connection_info(Config, false).
keylog_connection_info(Config, KeepSecrets) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, keylog_connection_info_result, [KeepSecrets]}},
{options, [{verify, verify_peer}, {keep_secrets, KeepSecrets} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, keylog_connection_info_result, [KeepSecrets]}},
{options, [{verify, verify_peer}, {keep_secrets, KeepSecrets} |ClientOpts]}]),
ct:log("Testcase ~p, KeepSecrets ~p Client ~p Server ~p ~n",
[self(), KeepSecrets, Client, Server]),
ServerKeylog = receive
{Server, {ok, Keylog}} ->
Keylog;
{Server, ServerError} ->
ct:fail({server, ServerError})
after 5000 ->
ct:fail({server, timeout})
end,
receive
{Client, {ok, ServerKeylog}} ->
ok;
{Client, {ok, ClientKeylog}} ->
ct:fail({mismatch, {ServerKeylog, ClientKeylog}});
{Client, ClientError} ->
ct:fail({client, ClientError})
after 5000 ->
ct:fail({client, timeout})
end,
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
prf() ->
[{doc,"Test that ssl:prf/5 uses the negotiated PRF."}].
prf(Config) when is_list(Config) ->
Version = ssl_test_lib:protocol_version(Config),
TestPlan = proplists:get_value(prf_test_plan, Config),
lists:foreach(fun(Test) ->
C = proplists:get_value(ciphers, Test),
E = proplists:get_value(expected, Test),
P = proplists:get_value(prf, Test),
prf_run_test(Config, Version, C, E, P)
end, TestPlan).
dh_params() ->
[{doc,"Test to specify DH-params file in server."}].
dh_params(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
DataDir = proplists:get_value(data_dir, Config),
DHParamFile = filename:join(DataDir, "dHParam.pem"),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{dhfile, DHParamFile} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options,
[{ciphers,[{dhe_rsa,aes_256_cbc,sha}]} |
ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
conf_signature_algs() ->
[{doc,"Test to set the signature_algs option on both client and server"}].
conf_signature_algs(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options, [{active, false}, {signature_algs, [{sha256, rsa}]},
{versions, ['tlsv1.2']} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options, [{active, false}, {signature_algs, [{sha256, rsa}]},
{versions, ['tlsv1.2']} | ClientOpts]}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
no_common_signature_algs() ->
[{doc,"Set the signature_algs option so that there client and server does not share any hash sign algorithms"}].
no_common_signature_algs(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, [{signature_algs, [{sha256, rsa}]}
| ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, [{signature_algs, [{sha384, rsa}]}
| ClientOpts]}]),
ssl_test_lib:check_server_alert(Server, Client, insufficient_security).
handshake_continue() ->
[{doc, "Test API function ssl:handshake_continue/3"}].
handshake_continue(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ssl_test_lib:ssl_options([{reuseaddr, true},
{log_level, debug},
{verify, verify_peer},
{handshake, hello} | ServerOpts
],
Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}
]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ClientOpts
],
Config)},
{continue_options, proplists:delete(reuseaddr, ClientOpts)}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
handshake_continue_tls13_client() ->
[{doc, "Test API function ssl:handshake_continue/3 with fixed TLS 1.3 client"}].
handshake_continue_tls13_client(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
SCiphers = ssl:filter_cipher_suites(ssl:cipher_suites(all, 'tlsv1.3'),
[{key_exchange, fun(srp_rsa) -> false;
(srp_anon) -> false;
(srp_dss) -> false;
(_) -> true end}]),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ssl_test_lib:ssl_options([{reuseaddr, true},
{log_level, debug},
{verify, verify_peer},
{ciphers, SCiphers},
{handshake, hello} | ServerOpts
],
Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}
]),
Port = ssl_test_lib:inet_port(Server),
DummyTicket =
<<131,116,0,0,0,5,100,0,4,104,107,100,102,100,0,6,115,104,97,51,
56,52,100,0,3,112,115,107,109,0,0,0,48,150,90,38,127,26,12,5,
228,180,235,229,214,215,27,236,149,182,82,14,140,50,81,0,150,
248,152,180,193,207,80,52,107,196,200,2,77,4,96,140,65,239,205,
224,125,129,179,147,103,100,0,3,115,110,105,107,0,25,112,114,
111,117,100,102,111,111,116,46,111,116,112,46,101,114,105,99,
115,115,111,110,46,115,101,100,0,6,116,105,99,107,101,116,104,6,
100,0,18,110,101,119,95,115,101,115,115,105,111,110,95,116,105,
99,107,101,116,98,0,0,28,32,98,127,110,83,249,109,0,0,0,8,0,0,0,
0,0,0,0,5,109,0,0,0,113,112,154,74,26,27,0,111,147,51,110,216,
43,45,4,100,215,152,195,118,96,22,34,1,184,170,42,166,238,109,
187,138,196,147,102,205,116,83,241,174,227,232,156,148,60,153,3,
175,128,115,192,36,103,191,239,58,222,192,172,190,239,92,8,131,
195,0,217,187,222,143,104,6,86,53,93,27,218,198,205,138,223,202,
11,55,168,104,6,219,228,217,157,37,52,205,252,165,135,167,116,
216,172,231,222,189,84,97,0,8,106,108,88,47,114,48,116,0,0,0,0,
100,0,9,116,105,109,101,115,116,97,109,112,98,93,205,0,44>>,
Send dummy session ticket to trigger sending of pre_shared_key and
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{session_tickets, manual},
{use_ticket, [DummyTicket]},
{versions, ['tlsv1.3',
'tlsv1.2',
'tlsv1.1',
'tlsv1'
]},
{ciphers, ssl:cipher_suites(all, 'tlsv1.3')},
{verify, verify_peer} | ClientOpts
],
Config)},
{continue_options, proplists:delete(reuseaddr, ClientOpts)}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
handshake_continue_timeout() ->
[{doc, "Test API function ssl:handshake_continue/3 with short timeout"}].
handshake_continue_timeout(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{timeout, 1},
{options, ssl_test_lib:ssl_options([{reuseaddr, true}, {handshake, hello},
{verify, verify_peer} | ServerOpts],
Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}
]),
Port = ssl_test_lib:inet_port(Server),
ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, [{verify, verify_peer} | ClientOpts]}]),
ssl_test_lib:check_result(Server, {error,timeout}),
ssl_test_lib:close(Server).
handshake_continue_change_verify() ->
[{doc, "Test API function ssl:handshake_continue with updated verify option. "
"Use a verification that will fail to make sure verification is run"}].
handshake_continue_change_verify(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server(
[{node, ServerNode}, {port, 0},
{from, self()},
{options, ssl_test_lib:ssl_options(
[{handshake, hello},
{verify, verify_peer} | ServerOpts], Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client_error(
[{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ssl_test_lib:ssl_options(
[{handshake, hello},
{server_name_indication, "foobar"}
| ClientOpts], Config)},
{continue_options, [{verify, verify_peer} | ClientOpts]}]),
ssl_test_lib:check_client_alert(Client, handshake_failure).
hello_client_cancel() ->
[{doc, "Test API function ssl:handshake_cancel/1 on the client side"}].
hello_client_cancel(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ServerOpts], Config)},
{continue_options, proplists:delete(reuseaddr, ServerOpts)}]),
Port = ssl_test_lib:inet_port(Server),
{connect_failed, ok} =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ClientOpts], Config)},
{continue_options, cancel}]),
ssl_test_lib:check_server_alert(Server, user_canceled).
hello_server_cancel() ->
[{doc, "Test API function ssl:handshake_cancel/1 on the server side"}].
hello_server_cancel(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ServerOpts
], Config)},
{continue_options, cancel}]),
Port = ssl_test_lib:inet_port(Server),
ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ssl_test_lib:ssl_options([{handshake, hello},
{verify, verify_peer} | ClientOpts
], Config)},
{continue_options, proplists:delete(reuseaddr, ClientOpts)}]),
ssl_test_lib:check_result(Server, ok).
versions() ->
[{doc,"Test API function versions/0"}].
versions(Config) when is_list(Config) ->
[_|_] = Versions = ssl:versions(),
ct:log("~p~n", [Versions]).
Test case adapted from gen_tcp_misc_SUITE .
active_n() ->
[{doc,"Test {active,N} option"}].
active_n(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
Port = ssl_test_lib:inet_port(node()),
N = 3,
LS = ok(ssl:listen(Port, [{active,N}|ServerOpts])),
[{active,N}] = ok(ssl:getopts(LS, [active])),
active_n_common(LS, N),
Self = self(),
spawn_link(fun() ->
S0 = ok(ssl:transport_accept(LS)),
{ok, S} = ssl:handshake(S0),
ok = ssl:setopts(S, [{active,N}]),
[{active,N}] = ok(ssl:getopts(S, [active])),
ssl:controlling_process(S, Self),
Self ! {server, S}
end),
C = ok(ssl:connect("localhost", Port, [{active,N}|ClientOpts])),
[{active,N}] = ok(ssl:getopts(C, [active])),
S = receive
{server, S0} -> S0
after
1000 ->
exit({error, connect})
end,
active_n_common(C, N),
active_n_common(S, N),
ok = ssl:setopts(C, [{active,N}]),
ok = ssl:setopts(S, [{active,N}]),
ReceiveMsg = fun(Socket, Msg) ->
receive
{ssl,Socket,Msg} ->
ok;
{ssl,Socket,Begin} ->
receive
{ssl,Socket,End} ->
Msg = Begin ++ End,
ok
after 1000 ->
exit(timeout)
end
after 1000 ->
exit(timeout)
end
end,
repeat(3, fun(I) ->
Msg = "message "++integer_to_list(I),
ok = ssl:send(C, Msg),
ReceiveMsg(S, Msg),
ok = ssl:send(S, Msg),
ReceiveMsg(C, Msg)
end),
receive
{ssl_passive,S} ->
[{active,false}] = ok(ssl:getopts(S, [active]))
after
1000 ->
exit({error,ssl_passive})
end,
receive
{ssl_passive,C} ->
[{active,false}] = ok(ssl:getopts(C, [active]))
after
1000 ->
exit({error,ssl_passive})
end,
LS2 = ok(ssl:listen(0, [{active,0}])),
receive
{ssl_passive,LS2} ->
[{active,false}] = ok(ssl:getopts(LS2, [active]))
after
1000 ->
exit({error,ssl_passive})
end,
ok = ssl:close(LS2),
ok = ssl:close(C),
ok = ssl:close(S),
ok = ssl:close(LS),
ok.
hibernate() ->
[{doc,"Check that an SSL connection that is started with option "
"{hibernate_after, 1000} indeed hibernates after 1000ms of "
"inactivity"}].
hibernate(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
{Client, #sslsocket{pid=[Pid|_]}} = ssl_test_lib:start_client([return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{hibernate_after, 1000}|ClientOpts]}]),
{current_function, _} =
process_info(Pid, current_function),
ssl_test_lib:check_result(Server, ok, Client, ok),
ct:sleep(1500),
{current_function, {erlang, hibernate, 3}} =
process_info(Pid, current_function),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
hibernate_right_away() ->
[{doc,"Check that an SSL connection that is configured to hibernate "
"after 0 or 1 milliseconds hibernates as soon as possible and not "
"crashes"}].
hibernate_right_away(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
StartServerOpts = [{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, ServerOpts}],
StartClientOpts = [return_socket,
{node, ClientNode},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}}],
Server1 = ssl_test_lib:start_server(StartServerOpts),
Port1 = ssl_test_lib:inet_port(Server1),
{Client1, #sslsocket{pid = [Pid1|_]}} = ssl_test_lib:start_client(StartClientOpts ++
[{port, Port1}, {options, [{hibernate_after, 0}|ClientOpts]}]),
ssl_test_lib:check_result(Server1, ok, Client1, ok),
{current_function, {erlang, hibernate, 3}} =
process_info(Pid1, current_function),
ssl_test_lib:close(Server1),
ssl_test_lib:close(Client1),
Server2 = ssl_test_lib:start_server(StartServerOpts),
Port2 = ssl_test_lib:inet_port(Server2),
{Client2, #sslsocket{pid = [Pid2|_]}} = ssl_test_lib:start_client(StartClientOpts ++
[{port, Port2}, {options, [{hibernate_after, 1}|ClientOpts]}]),
ssl_test_lib:check_result(Server2, ok, Client2, ok),
{current_function, {erlang, hibernate, 3}} =
process_info(Pid2, current_function),
ssl_test_lib:close(Server2),
ssl_test_lib:close(Client2).
listen_socket() ->
[{doc,"Check error handling and inet compliance when calling API functions with listen sockets."}].
listen_socket(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ok, ListenSocket} = ssl:listen(0, ServerOpts),
ok = ssl:controlling_process(ListenSocket, self()),
{ok, _} = ssl:sockname(ListenSocket),
{error, enotconn} = ssl:send(ListenSocket, <<"data">>),
{error, enotconn} = ssl:recv(ListenSocket, 0),
{error, enotconn} = ssl:connection_information(ListenSocket),
{error, enotconn} = ssl:peername(ListenSocket),
{error, enotconn} = ssl:peercert(ListenSocket),
{error, enotconn} = ssl:renegotiate(ListenSocket),
{error, enotconn} = ssl:prf(ListenSocket, 'master_secret', <<"Label">>, [client_random], 256),
{error, enotconn} = ssl:shutdown(ListenSocket, read_write),
ok = ssl:close(ListenSocket).
peername() ->
[{doc,"Test API function peername/1"}].
peername(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server(
[
{node, ServerNode}, {port, 0},
{from, self()},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
{Client, CSocket} = ssl_test_lib:start_client(
[return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ClientOpts}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
Server ! get_socket,
SSocket =
receive
{Server, {socket, Socket}} ->
Socket
end,
{ok, ServerPeer} = ssl:peername(SSocket),
ct:log("Server's peer: ~p~n", [ServerPeer]),
{ok, ClientPeer} = ssl:peername(CSocket),
ct:log("Client's peer: ~p~n", [ClientPeer]),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
recv_active() ->
[{doc,"Test recv on active socket"}].
recv_active(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, try_recv_active, []}},
{options, [{active, true} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, try_recv_active, []}},
{options, [{active, true} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
recv_active_once() ->
[{doc,"Test recv on active (once) socket"}].
recv_active_once(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, try_recv_active_once, []}},
{options, [{active, once} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, try_recv_active_once, []}},
{options, [{active, once} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
recv_active_n() ->
[{doc,"Test recv on active (n) socket"}].
recv_active_n(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, try_recv_active_once, []}},
{options, [{active, 1} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, try_recv_active_once, []}},
{options, [{active, 1} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
recv_timeout() ->
[{doc,"Test ssl:recv timeout"}].
recv_timeout(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, send_recv_result_timeout_server, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE,
send_recv_result_timeout_client, []}},
{options, [{active, false} | ClientOpts]}]),
ssl_test_lib:check_result(Client, ok, Server, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
recv_close() ->
[{doc,"Special case of call error handling"}].
recv_close(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, do_recv_close, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
{_Client, #sslsocket{} = SslSocket} = ssl_test_lib:start_client([return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, no_result, []}},
{options, ClientOpts}]),
ssl:close(SslSocket),
ssl_test_lib:check_result(Server, ok).
recv_no_active_msg() ->
[{doc,"If we have a passive socket and do not call recv and peer closes we should no get"
"receive an active message"}].
recv_no_active_msg(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, no_recv_no_active, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, no_result, []}},
{options, ClientOpts}]),
ssl_test_lib:close(Client),
ssl_test_lib:check_result(Server, ok).
controlling_process() ->
[{doc,"Test API function controlling_process/2"}].
controlling_process(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
ClientMsg = "Server hello",
ServerMsg = "Client hello",
Server = ssl_test_lib:start_server([
{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE,
controlling_process_result, [self(),
ServerMsg]}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
{Client, CSocket} = ssl_test_lib:start_client([return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE,
controlling_process_result, [self(),
ClientMsg]}},
{options, ClientOpts}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ServerMsg = ssl_test_lib:active_recv(CSocket, length(ServerMsg)),
We do not have the TLS server socket but all messages form the client
ClientMsg = ssl_active_recv(length(ClientMsg)),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
controller_dies() ->
[{doc,"Test that the socket is closed after controlling process dies"}].
controller_dies(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
ClientMsg = "Hello server",
ServerMsg = "Hello client",
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE,
controller_dies_result, [self(),
ServerMsg]}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE,
controller_dies_result, [self(),
ClientMsg]}},
{options, ClientOpts}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n", [self(), Client, Server]),
process_flag(trap_exit, true),
exit(Client, killed),
get_close(Client, ?LINE),
Server ! listen,
Tester = self(),
Connect = fun(Pid) ->
{ok, Socket} = ssl:connect(Hostname, Port, ClientOpts),
ct:sleep(?SLEEP),
Pid ! {self(), connected, Socket},
receive die_nice -> normal end
end,
Client2 = spawn_link(fun() -> Connect(Tester) end),
receive {Client2, connected, _Socket} -> Client2 ! die_nice end,
get_close(Client2, ?LINE),
Server ! listen,
Client3 = spawn_link(fun() -> Connect(Tester) end),
Controller = spawn_link(fun() -> receive die_nice -> normal end end),
receive
{Client3, connected, Socket} ->
ok = ssl:controlling_process(Socket, Controller),
Client3 ! die_nice
end,
ct:log("Wating on exit ~p~n",[Client3]),
receive {'EXIT', Client3, normal} -> ok end,
Client3 is dead but that does n't matter , socket should not be closed .
Unexpected ->
ct:log("Unexpected ~p~n",[Unexpected]),
ct:fail({line, ?LINE-1})
after 1000 ->
ok
end,
Controller ! die_nice,
get_close(Controller, ?LINE),
Server ! listen,
LastClient = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE,
controller_dies_result, [self(),
ClientMsg]}},
{options, ClientOpts}]),
exit(Server, killed),
get_close(Server, ?LINE),
process_flag(trap_exit, false),
ssl_test_lib:close(LastClient).
controlling_process_transport_accept_socket() ->
[{doc,"Only ssl:handshake and ssl:controlling_process is allowed for transport_accept:sockets"}].
controlling_process_transport_accept_socket(Config) when is_list(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server_transport_control([{node, ServerNode},
{port, 0},
{from, self()},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
_Client = ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server, ok),
ssl_test_lib:close(Server).
close_with_timeout() ->
[{doc,"Test normal (not downgrade) ssl:close/2"}].
close_with_timeout(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, tls_close, []}},
{options,[{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, tls_close, []}},
{options, [{active, false} |ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok).
close_in_error_state() ->
[{doc,"Special case of closing socket in error state"}].
close_in_error_state(Config) when is_list(Config) ->
ServerOpts0 = ssl_test_lib:ssl_options(server_opts, Config),
ServerOpts = [{cacertfile, "foo.pem"} | proplists:delete(cacertfile, ServerOpts0)],
ClientOpts = ssl_test_lib:ssl_options(client_opts, Config),
_ = spawn(?MODULE, run_error_server_close, [[self() | ServerOpts]]),
receive
{_Pid, Port} ->
spawn_link(?MODULE, run_client_error, [[Port, ClientOpts]])
end,
receive
ok ->
ok;
Other ->
ct:fail(Other)
end.
call_in_error_state() ->
[{doc,"Special case of call error handling"}].
call_in_error_state(Config) when is_list(Config) ->
ServerOpts0 = ssl_test_lib:ssl_options(server_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_opts, Config),
ServerOpts = [{cacertfile, "foo.pem"} | proplists:delete(cacertfile, ServerOpts0)],
Pid = spawn(?MODULE, run_error_server, [[self() | ServerOpts]]),
receive
{Pid, Port} ->
spawn_link(?MODULE, run_client_error, [[Port, ClientOpts]])
end,
receive
{error, closed} ->
ok;
Other ->
ct:fail(Other)
end.
close_transport_accept() ->
[{doc,"Tests closing ssl socket when waiting on ssl:transport_accept/1"}].
close_transport_accept(Config) when is_list(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{_ClientNode, ServerNode, _Hostname} = ssl_test_lib:run_where(Config),
Port = 0,
Opts = [{active, false} | ServerOpts],
{ok, ListenSocket} = rpc:call(ServerNode, ssl, listen, [Port, Opts]),
spawn_link(fun() ->
ct:sleep(?SLEEP),
rpc:call(ServerNode, ssl, close, [ListenSocket])
end),
case rpc:call(ServerNode, ssl, transport_accept, [ListenSocket]) of
{error, closed} ->
ok;
Other ->
exit({?LINE, Other})
end.
abuse_transport_accept_socket() ->
[{doc,"Only ssl:handshake and ssl:controlling_process is allowed for transport_accept:sockets"}].
abuse_transport_accept_socket(Config) when is_list(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server_transport_abuse_socket([{node, ServerNode},
{port, 0},
{from, self()},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, no_result, []}},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
invalid_keyfile() ->
[{doc,"Test what happens with an invalid key file"}].
invalid_keyfile(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
BadKeyFile = filename:join([proplists:get_value(priv_dir, Config),
"badkey.pem"]),
BadOpts = [{keyfile, BadKeyFile}| proplists:delete(keyfile, ServerOpts)],
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, BadOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client_error([{node, ClientNode},
{port, Port}, {host, Hostname},
{from, self()}, {options, ClientOpts}]),
File = proplists:get_value(keyfile,BadOpts),
ssl_test_lib:check_result(Server,
{error,{options, {keyfile, File, {error,enoent}}}}, Client,
{error, closed}).
honor_server_cipher_order() ->
[{doc,"Test API honor server cipher order."}].
honor_server_cipher_order(Config) when is_list(Config) ->
ClientCiphers = [#{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf},
#{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac => sha,
prf => default_prf}],
ServerCiphers = [#{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac =>sha,
prf => default_prf},
#{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf}],
honor_cipher_order(Config, true, ServerCiphers,
ClientCiphers, #{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac => sha,
prf => default_prf}).
honor_client_cipher_order() ->
[{doc,"Test API honor server cipher order."}].
honor_client_cipher_order(Config) when is_list(Config) ->
ClientCiphers = [#{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf},
#{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac => sha,
prf => default_prf}],
ServerCiphers = [#{key_exchange => dhe_rsa,
cipher => aes_256_cbc,
mac =>sha,
prf => default_prf},
#{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf}],
honor_cipher_order(Config, false, ServerCiphers,
ClientCiphers, #{key_exchange => dhe_rsa,
cipher => aes_128_cbc,
mac => sha,
prf => default_prf}).
ipv6() ->
[{require, ipv6_hosts},
{doc,"Test ipv6."}].
ipv6(Config) when is_list(Config) ->
{ok, Hostname0} = inet:gethostname(),
case lists:member(list_to_atom(Hostname0), ct:get_config(ipv6_hosts)) of
true ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} =
ssl_test_lib:run_where(Config, ipv6),
Server = ssl_test_lib:start_server([{node, ServerNode},
{port, 0}, {from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options,
[inet6, {active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode},
{port, Port}, {host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options,
[inet6, {active, false} | ClientOpts]}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client);
false ->
{skip, "Host does not support IPv6"}
end.
der_input() ->
[{doc,"Test to input certs and key as der"}].
der_input(Config) when is_list(Config) ->
DataDir = proplists:get_value(data_dir, Config),
DHParamFile = filename:join(DataDir, "dHParam.pem"),
{status, _, _, StatusInfo} = sys:get_status(whereis(ssl_manager)),
[_, _,_, _, Prop] = StatusInfo,
State = ssl_test_lib:state(Prop),
[CADb | _] = element(5, State),
Size = ets:info(CADb, size),
ct:pal("Size ~p", [Size]),
SeverVerifyOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ServerCert, ServerKey, ServerCaCerts, DHParams} = der_input_opts([{dhfile, DHParamFile} |
SeverVerifyOpts]),
ClientVerifyOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientCert, ClientKey, ClientCaCerts, DHParams} = der_input_opts([{dhfile, DHParamFile} |
ClientVerifyOpts]),
ServerOpts = [{verify, verify_peer}, {fail_if_no_peer_cert, true},
{dh, DHParams},
{cert, ServerCert}, {key, ServerKey}, {cacerts, ServerCaCerts}],
ClientOpts = [{verify, verify_peer}, {fail_if_no_peer_cert, true},
{dh, DHParams},
{cert, ClientCert}, {key, ClientKey}, {cacerts, ClientCaCerts}],
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options, [{active, false} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result, []}},
{options, [{active, false} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client),
Using only DER input should not increase file indexed DB
Size = ets:info(CADb, size).
invalid_certfile() ->
[{doc,"Test what happens with an invalid cert file"}].
invalid_certfile(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
BadCertFile = filename:join([proplists:get_value(priv_dir, Config),
"badcert.pem"]),
ServerBadOpts = [{certfile, BadCertFile}| proplists:delete(certfile, ServerOpts)],
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server =
ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, ServerBadOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client =
ssl_test_lib:start_client_error([{node, ClientNode},
{port, Port}, {host, Hostname},
{from, self()},
{options, ClientOpts}]),
File = proplists:get_value(certfile, ServerBadOpts),
ssl_test_lib:check_result(Server, {error,{options, {certfile, File, {error,enoent}}}},
Client, {error, closed}).
invalid_cacertfile() ->
[{doc,"Test what happens with an invalid cacert file"}].
invalid_cacertfile(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
BadCACertFile = filename:join([proplists:get_value(priv_dir, Config),
"badcacert.pem"]),
ServerBadOpts = [{cacertfile, BadCACertFile}| proplists:delete(cacertfile, ServerOpts)],
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server0 =
ssl_test_lib:start_server_error([{node, ServerNode},
{port, 0}, {from, self()},
{options, ServerBadOpts}]),
Port0 = ssl_test_lib:inet_port(Server0),
Client0 =
ssl_test_lib:start_client_error([{node, ClientNode},
{port, Port0}, {host, Hostname},
{from, self()},
{options, ClientOpts}]),
File0 = proplists:get_value(cacertfile, ServerBadOpts),
ssl_test_lib:check_result(Server0, {error, {options, {cacertfile, File0,{error,enoent}}}},
Client0, {error, closed}),
File = File0 ++ "do_not_exit.pem",
ServerBadOpts1 = [{cacertfile, File}|proplists:delete(cacertfile, ServerBadOpts)],
Server1 =
ssl_test_lib:start_server_error([{node, ServerNode},
{port, 0}, {from, self()},
{options, ServerBadOpts1}]),
Port1 = ssl_test_lib:inet_port(Server1),
Client1 =
ssl_test_lib:start_client_error([{node, ClientNode},
{port, Port1}, {host, Hostname},
{from, self()},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server1, {error, {options, {cacertfile, File,{error,enoent}}}},
Client1, {error, closed}),
ok.
new_options_in_handshake() ->
[{doc,"Test that you can set ssl options in handshake/3 and not only in tcp upgrade"}].
new_options_in_handshake(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
Version = ssl_test_lib:protocol_version(Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Ciphers = [_, Cipher | _] = ssl:filter_cipher_suites(ssl:cipher_suites(all, Version),
[{key_exchange,
fun(dhe_rsa) ->
true;
(ecdhe_rsa) ->
true;
(rsa) ->
false;
(_) ->
false
end
}]),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{ssl_extra_opts, [{versions, [Version]},
To be set in handshake/3
{mfa, {?MODULE, connection_info_result, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, connection_info_result, []}},
{options, [{ciphers, Ciphers} | ClientOpts]}]),
ct:log("Testcase ~p, Client ~p Server ~p ~n",
[self(), Client, Server]),
ServerMsg = ClientMsg = {ok, {Version, Cipher}},
ssl_test_lib:check_result(Server, ServerMsg, Client, ClientMsg),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
max_handshake_size() ->
[{doc,"Test that we can set max_handshake_size to max value."}].
max_handshake_size(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{max_handshake_size, 8388607} |ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{max_handshake_size, 8388607} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok).
options_not_proplist() ->
[{doc,"Test what happens if an option is not a key value tuple"}].
options_not_proplist(Config) when is_list(Config) ->
BadOption = {client_preferred_next_protocols,
client, [<<"spdy/3">>,<<"http/1.1">>], <<"http/1.1">>},
{option_not_a_key_value_tuple, BadOption} =
ssl:connect("twitter.com", 443, [binary, {active, false},
BadOption]).
invalid_options() ->
[{doc,"Test what happens when we give invalid options"}].
invalid_options(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_verify_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Check = fun(Client, Server, {versions, [sslv2, sslv3]} = Option) ->
ssl_test_lib:check_result(Server,
{error, {options, {sslv2, Option}}},
Client,
{error, {options, {sslv2, Option}}});
(Client, Server, Option) ->
ssl_test_lib:check_result(Server,
{error, {options, Option}},
Client,
{error, {options, Option}})
end,
TestOpts =
[{versions, [sslv2, sslv3]},
{verify, 4},
{verify_fun, function},
{fail_if_no_peer_cert, 0},
{depth, four},
{certfile, 'cert.pem'},
{keyfile,'key.pem' },
{password, foo},
{cacertfile, ""},
{dhfile,'dh.pem' },
{ciphers, [{foo, bar, sha, ignore}]},
{reuse_session, foo},
{reuse_sessions, 0},
{renegotiate_at, "10"},
{mode, depech},
{packet, 8.0},
{packet_size, "2"},
{header, a},
{active, trice},
{key, 'key.pem' }],
TestOpts2 =
[{[{anti_replay, '10k'}],
{options,dependency,{anti_replay,{versions,['tlsv1.3']}}}},
{[{cookie, false}],
{options,dependency,{cookie,{versions,['tlsv1.3']}}}},
{[{supported_groups, []}],
{options,dependency,{supported_groups,{versions,['tlsv1.3']}}}},
{[{use_ticket, [<<1,2,3,4>>]}],
{options,dependency,{use_ticket,{versions,['tlsv1.3']}}}},
{[{verify, verify_none}, {fail_if_no_peer_cert, true}],
{options, incompatible,
{verify, verify_none},
{fail_if_no_peer_cert, true}}}],
[begin
Server =
ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, [TestOpt | ServerOpts]}]),
Client =
ssl_test_lib:start_client_error([{node, ClientNode}, {port, 0},
{host, Hostname}, {from, self()},
{options, [TestOpt | ClientOpts]}]),
Check(Client, Server, TestOpt),
ok
end || TestOpt <- TestOpts],
[begin
start_client_negative(Config, TestOpt, ErrorMsg),
ok
end || {TestOpt, ErrorMsg} <- TestOpts2],
ok.
default_reject_anonymous()->
[{doc,"Test that by default anonymous cipher suites are rejected "}].
default_reject_anonymous(Config) when is_list(Config) ->
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
Version = ssl_test_lib:protocol_version(Config),
TLSVersion = ssl_test_lib:tls_version(Version),
[CipherSuite | _] = ssl_test_lib:ecdh_dh_anonymous_suites(TLSVersion),
Server = ssl_test_lib:start_server_error([{node, ServerNode}, {port, 0},
{from, self()},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client_error([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options,
[{ciphers,[CipherSuite]} |
ClientOpts]}]),
ssl_test_lib:check_server_alert(Server, Client, insufficient_security).
cb_info() ->
[{doc,"Test that we can set cb_info."}].
cb_info(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
Protocol = proplists:get_value(protocol, Config, tls),
CbInfo =
case Protocol of
tls ->
{cb_info, {gen_tcp, tcp, tcp_closed, tcp_error}};
dtls ->
{cb_info, {gen_udp, udp, udp_closed, udp_error}}
end,
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [CbInfo | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [CbInfo | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok).
log_alert() ->
[{doc,"Test that we can set log_alert and that it translates to correct log_level"
" that has replaced this option"}].
log_alert(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{log_alert, true} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
{Client, CSock} = ssl_test_lib:start_client([return_socket,
{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{log_alert, false} | ClientOpts]}]),
{ok, [{log_level, none}]} = ssl:connection_information(CSock, [log_level]),
ssl_test_lib:check_result(Server, ok, Client, ok).
rizzo_disabled() ->
[{doc, "Test original beast mitigation disable option for SSL 3.0 and TLS 1.0"}].
rizzo_disabled(Config) ->
ClientOpts = [{beast_mitigation, disabled} | ssl_test_lib:ssl_options(client_rsa_opts, Config)],
ServerOpts = [{beast_mitigation, disabled} | ssl_test_lib:ssl_options(server_rsa_opts, Config)],
ssl_test_lib:basic_test(ClientOpts, ServerOpts, Config).
rizzo_zero_n() ->
[{doc, "Test zero_n beast mitigation option (same affect as original disable option) for SSL 3.0 and TLS 1.0"}].
rizzo_zero_n(Config) ->
ClientOpts = [{beast_mitigation, zero_n} | ssl_test_lib:ssl_options(client_rsa_opts, Config)],
ServerOpts = [{beast_mitigation, zero_n} | ssl_test_lib:ssl_options(server_rsa_opts, Config)],
ssl_test_lib:basic_test(ClientOpts, ServerOpts, Config).
rizzo_one_n_minus_one () ->
[{doc, "Test beast_mitigation option one_n_minus_one (same affect as default) for SSL 3.0 and TLS 1.0"}].
rizzo_one_n_minus_one (Config) ->
ClientOpts = [{beast_mitigation, one_n_minus_one } | ssl_test_lib:ssl_options(client_rsa_opts, Config)],
ServerOpts = [{beast_mitigation, one_n_minus_one} | ssl_test_lib:ssl_options(server_rsa_opts, Config)],
ssl_test_lib:basic_test(ClientOpts, ServerOpts, Config).
supported_groups() ->
[{doc,"Test the supported_groups option in TLS 1.3."}].
supported_groups(Config) when is_list(Config) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{supported_groups, [x448, x25519]} | ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {ssl_test_lib, send_recv_result_active, []}},
{options, [{supported_groups,[x448]} | ClientOpts]}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
honor_client_cipher_order_tls13() ->
[{doc,"Test API honor server cipher order in TLS 1.3."}].
honor_client_cipher_order_tls13(Config) when is_list(Config) ->
ClientCiphers = [#{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384},
#{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256}],
ServerCiphers = [#{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256},
#{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384}],
honor_cipher_order(Config, false, ServerCiphers, ClientCiphers, #{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384}).
client_options_negative_version_gap() ->
[{doc,"Test client options with faulty version gap."}].
client_options_negative_version_gap(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1', 'tlsv1.3']}],
{options, missing_version,
{'tlsv1.2', {versions,[tlsv1, 'tlsv1.3']}}}).
client_options_negative_dependency_version() ->
[{doc,"Test client options with faulty version dependency."}].
client_options_negative_dependency_version(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1.1', 'tlsv1.2']},
{session_tickets, manual}],
{options,dependency,
{session_tickets,{versions,['tlsv1.3']}}}).
client_options_negative_dependency_stateless() ->
[{doc,"Test client options with faulty 'session_tickets' option."}].
client_options_negative_dependency_stateless(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{anti_replay, '10k'},
{session_tickets, manual}],
{options,dependency,
{anti_replay,{session_tickets,[stateless]}}}).
client_options_negative_dependency_role() ->
[{doc,"Test client options with faulty role."}].
client_options_negative_dependency_role(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, stateless}],
{options,role,
{session_tickets,{stateless,{client,[disabled,manual,auto]}}}}).
client_options_negative_early_data() ->
[{doc,"Test client option early_data."}].
client_options_negative_early_data(Config) when is_list(Config) ->
start_client_negative(Config, [{versions, ['tlsv1.2']},
{early_data, "test"}],
{options,dependency,
{early_data,{versions,['tlsv1.3']}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{early_data, "test"}],
{options,dependency,
{early_data,{session_tickets,[manual,auto]}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, stateful},
{early_data, "test"}],
{options,role,
{session_tickets,
{stateful,{client,[disabled,manual,auto]}}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, disabled},
{early_data, "test"}],
{options,dependency,
{early_data,{session_tickets,[manual,auto]}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual},
{early_data, "test"}],
{options,dependency,
{early_data, use_ticket}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual},
{use_ticket, [<<"ticket">>]},
{early_data, "test"}],
{options, type,
{early_data, {"test", not_binary}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual},
{use_ticket, [<<"ticket">>]},
{early_data, <<"test">>}],
econnrefused),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, auto},
{early_data, "test"}],
{options, type,
{early_data, {"test", not_binary}}}),
start_client_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, auto},
{early_data, <<"test">>}],
econnrefused).
server_options_negative_early_data() ->
[{doc,"Test server option early_data."}].
server_options_negative_early_data(Config) when is_list(Config) ->
start_server_negative(Config, [{versions, ['tlsv1.2']},
{early_data, "test"}],
{options,dependency,
{early_data,{versions,['tlsv1.3']}}}),
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{early_data, "test"}],
{options,dependency,
{early_data,{session_tickets,[stateful,stateless]}}}),
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual},
{early_data, "test"}],
{options,role,
{session_tickets,
{manual,{server,[disabled,stateful,stateless]}}}}),
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, disabled},
{early_data, "test"}],
{options,dependency,
{early_data,{session_tickets,[stateful,stateless]}}}),
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, stateful},
{early_data, "test"}],
{options,role,
{early_data,{"test",{server,[disabled,enabled]}}}}).
server_options_negative_version_gap() ->
[{doc,"Test server options with faulty version gap."}].
server_options_negative_version_gap(Config) when is_list(Config) ->
start_server_negative(Config, [{versions, ['tlsv1', 'tlsv1.3']}],
{options, missing_version,
{'tlsv1.2', {versions,[tlsv1, 'tlsv1.3']}}}).
server_options_negative_dependency_role() ->
[{doc,"Test server options with faulty role."}].
server_options_negative_dependency_role(Config) when is_list(Config) ->
start_server_negative(Config, [{versions, ['tlsv1.2', 'tlsv1.3']},
{session_tickets, manual}],
{options,role,
{session_tickets,{manual,{server,[disabled,stateful,stateless]}}}}).
honor_server_cipher_order_tls13() ->
[{doc,"Test API honor server cipher order in TLS 1.3."}].
honor_server_cipher_order_tls13(Config) when is_list(Config) ->
ClientCiphers = [#{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384},
#{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256}],
ServerCiphers = [#{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256},
#{key_exchange => any,
cipher => aes_256_gcm,
mac => aead,
prf => sha384}],
honor_cipher_order(Config, true, ServerCiphers,
ClientCiphers, #{key_exchange => any,
cipher => aes_128_gcm,
mac => aead,
prf => sha256}).
getstat() ->
[{doc, "Test that you use ssl:getstat on a TLS socket"}].
getstat(Config) when is_list(Config) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Port0 = ssl_test_lib:inet_port(ServerNode),
{ok, ListenSocket} = ssl:listen(Port0, [ServerOpts]),
{ok, _} = ssl:getstat(ListenSocket),
ssl:close(ListenSocket),
Server = ssl_test_lib:start_server([{node, ClientNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, ssl_getstat, []}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ServerNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, ssl_getstat, []}},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server, ok, Client, ok).
invalid_options_tls13() ->
[{doc, "Test invalid options with TLS 1.3"}].
invalid_options_tls13(Config) when is_list(Config) ->
TestOpts =
[{{beast_mitigation, one_n_minus_one},
{options, dependency,
{beast_mitigation,{versions,[tlsv1]}}},
common},
{{next_protocols_advertised, [<<"http/1.1">>]},
{options, dependency,
{next_protocols_advertised,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
server},
{{client_preferred_next_protocols,
{client, [<<"http/1.1">>]}},
{options, dependency,
{client_preferred_next_protocols,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
client},
{{client_renegotiation, false},
{options, dependency,
{client_renegotiation,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
server
},
{{cookie, false},
{option , server_only, cookie},
client
},
{{padding_check, false},
{options, dependency,
{padding_check,{versions,[tlsv1]}}},
common},
{{psk_identity, "Test-User"},
{options, dependency,
{psk_identity,{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
common},
{{user_lookup_fun,
{fun ssl_test_lib:user_lookup/3, <<1,2,3>>}},
{options, dependency,
{user_lookup_fun,{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
common},
{{reuse_session, fun(_,_,_,_) -> false end},
{options, dependency,
{reuse_session,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
server},
{{reuse_session, <<1,2,3,4>>},
{options, dependency,
{reuse_session,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
client},
{{reuse_sessions, true},
{options, dependency,
{reuse_sessions,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
common},
{{secure_renegotiate, false},
{options, dependency,
{secure_renegotiate,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
common},
{{srp_identity, false},
{options, dependency,
{srp_identity,
{versions,[tlsv1,'tlsv1.1','tlsv1.2']}}},
client}
],
Fun = fun(Option, ErrorMsg, Type) ->
case Type of
server ->
start_server_negative(Config,
[Option,{versions, ['tlsv1.3']}],
ErrorMsg);
client ->
start_client_negative(Config,
[Option,{versions, ['tlsv1.3']}],
ErrorMsg);
common ->
start_server_negative(Config,
[Option,{versions, ['tlsv1.3']}],
ErrorMsg),
start_client_negative(Config,
[Option,{versions, ['tlsv1.3']}],
ErrorMsg)
end
end,
[Fun(Option, ErrorMsg, Type) || {Option, ErrorMsg, Type} <- TestOpts].
cookie() ->
[{doc, "Test cookie extension in TLS 1.3"}].
cookie(Config) when is_list(Config) ->
cookie_extension(Config, true),
cookie_extension(Config, false).
Checker functions
connection_information_result(Socket) ->
{ok, Info = [_ | _]} = ssl:connection_information(Socket),
case length(Info) > 3 of
true ->
ct:log("Info ~p", [Info]),
ok;
false ->
ct:fail(no_ssl_options_returned)
end.
secret_connection_info_result(Socket) ->
{ok, [{protocol, Protocol}]} = ssl:connection_information(Socket, [protocol]),
{ok, ConnInfo} = ssl:connection_information(Socket, [client_random, server_random, master_secret]),
check_connection_info(Protocol, ConnInfo).
keylog_connection_info_result(Socket, KeepSecrets) ->
{ok, [{protocol, Protocol}]} = ssl:connection_information(Socket, [protocol]),
{ok, ConnInfo} = ssl:connection_information(Socket, [keylog]),
check_keylog_info(Protocol, ConnInfo, KeepSecrets).
check_keylog_info('tlsv1.3', [{keylog, ["CLIENT_HANDSHAKE_TRAFFIC_SECRET"++_,_|_]=Keylog}], true) ->
{ok, Keylog};
check_keylog_info('tlsv1.3', []=Keylog, false) ->
{ok, Keylog};
check_keylog_info('tlsv1.2', [{keylog, ["CLIENT_RANDOM"++_]=Keylog}], _) ->
{ok, Keylog};
check_keylog_info(NotSup, [], _) when NotSup == 'tlsv1.1'; NotSup == tlsv1; NotSup == 'dtlsv1.2'; NotSup == dtlsv1 ->
{ok, []};
check_keylog_info(_, Unexpected, _) ->
{unexpected, Unexpected}.
check_srp_in_connection_information(_Socket, _Username, client) ->
ok;
check_srp_in_connection_information(Socket, Username, server) ->
{ok, Info} = ssl:connection_information(Socket),
ct:log("Info ~p~n", [Info]),
case proplists:get_value(srp_username, Info, not_found) of
Username ->
ok;
not_found ->
ct:fail(srp_username_not_found)
end.
In TLS 1.3 the master_secret field is used to store multiple secrets from the key schedule and it is a tuple .
check_connection_info('tlsv1.3', [{client_random, ClientRand}, {master_secret, {master_secret, MasterSecret}}]) ->
is_binary(ClientRand) andalso is_binary(MasterSecret);
check_connection_info('tlsv1.3', [{server_random, ServerRand}, {master_secret, {master_secret, MasterSecret}}]) ->
is_binary(ServerRand) andalso is_binary(MasterSecret);
check_connection_info(_, [{client_random, ClientRand}, {server_random, ServerRand}, {master_secret, MasterSecret}]) ->
is_binary(ClientRand) andalso is_binary(ServerRand) andalso is_binary(MasterSecret);
check_connection_info(_, _) ->
false.
prf_verify_value(Socket, TlsVer, Expected, Algo) ->
Ret = ssl:prf(Socket, <<>>, <<>>, [<<>>], 16),
case TlsVer of
sslv3 ->
case Ret of
{error, undefined} -> ok;
_ ->
{error, {expected, {error, undefined},
got, Ret, tls_ver, TlsVer, prf_algorithm, Algo}}
end;
_ ->
case Ret of
{ok, Expected} -> ok;
{ok, Val} -> {error, {expected, Expected, got, Val, tls_ver, TlsVer,
prf_algorithm, Algo}}
end
end.
try_recv_active(Socket) ->
ssl:send(Socket, "Hello world"),
{error, einval} = ssl:recv(Socket, 11),
ok.
try_recv_active_once(Socket) ->
{error, einval} = ssl:recv(Socket, 11),
ok.
controlling_process_result(Socket, Pid, Msg) ->
ok = ssl:controlling_process(Socket, Pid),
ct:sleep(?SLEEP),
ssl:send(Socket, Msg),
no_result_msg.
controller_dies_result(_Socket, _Pid, _Msg) ->
receive Result -> Result end.
send_recv_result_timeout_client(Socket) ->
{error, timeout} = ssl:recv(Socket, 11, 500),
{error, timeout} = ssl:recv(Socket, 11, 0),
ssl:send(Socket, "Hello world"),
receive
Msg ->
io:format("Msg ~p~n",[Msg])
after 500 ->
ok
end,
{ok, "Hello world"} = ssl:recv(Socket, 11, 500),
ok.
send_recv_result_timeout_server(Socket) ->
ssl:send(Socket, "Hello"),
{ok, "Hello world"} = ssl:recv(Socket, 11),
ssl:send(Socket, " world"),
ok.
do_recv_close(Socket) ->
{error, closed} = ssl:recv(Socket, 11),
receive
{_,{error,closed}} ->
error_extra_close_sent_to_user_process
after 500 ->
ok
end.
tls_close(Socket) ->
ok = ssl_test_lib:send_recv_result(Socket),
case ssl:close(Socket, 10000) of
ok ->
ok;
{error, closed} ->
ok;
Other ->
ct:fail(Other)
end.
run_error_server_close([Pid | Opts]) ->
{ok, Listen} = ssl:listen(0, Opts),
{ok,{_, Port}} = ssl:sockname(Listen),
Pid ! {self(), Port},
{ok, Socket} = ssl:transport_accept(Listen),
Pid ! ssl:close(Socket).
run_error_server([ Pid | Opts]) ->
{ok, Listen} = ssl:listen(0, Opts),
{ok,{_, Port}} = ssl:sockname(Listen),
Pid ! {self(), Port},
{ok, Socket} = ssl:transport_accept(Listen),
Pid ! ssl:controlling_process(Socket, self()).
run_client_error([Port, Opts]) ->
ssl:connect("localhost", Port, Opts).
no_recv_no_active(Socket) ->
receive
{ssl_closed, Socket} ->
ct:fail(received_active_msg)
after 5000 ->
ok
end.
connection_info_result(Socket) ->
{ok, Info} = ssl:connection_information(Socket, [protocol, selected_cipher_suite]),
{ok, {proplists:get_value(protocol, Info), proplists:get_value(selected_cipher_suite, Info)}}.
Internal functions ------------------------------------------------
prf_create_plan(TlsVer, _PRFs, Results) when TlsVer == tlsv1
orelse TlsVer == 'tlsv1.1'
orelse TlsVer == 'dtlsv1' ->
Ciphers = prf_get_ciphers(TlsVer, default_prf),
{_, Expected} = lists:keyfind(md5sha, 1, Results),
[[{ciphers, Ciphers}, {expected, Expected}, {prf, md5sha}]];
prf_create_plan(TlsVer, PRFs, Results) when TlsVer == 'tlsv1.2' orelse TlsVer == 'dtlsv1.2' ->
lists:foldl(
fun(PRF, Acc) ->
Ciphers = prf_get_ciphers(TlsVer, PRF),
case Ciphers of
[] ->
ct:log("No ciphers for PRF algorithm ~p. Skipping.", [PRF]),
Acc;
Ciphers ->
{_, Expected} = lists:keyfind(PRF, 1, Results),
[[{ciphers, Ciphers}, {expected, Expected}, {prf, PRF}] | Acc]
end
end, [], PRFs).
prf_get_ciphers(TlsVer, PRF) ->
PrfFilter = fun(Value) -> Value =:= PRF end,
RSACertNoSpecialConf = fun(rsa) ->
true;
(ecdhe_rsa) ->
lists:member(ecdh, crypto:supports(public_keys));
(dhe_rsa) ->
true;
(_) ->
false
end,
ssl:filter_cipher_suites(ssl:cipher_suites(default, TlsVer), [{key_exchange, RSACertNoSpecialConf},
{prf, PrfFilter}]).
prf_run_test(_, TlsVer, [], _, Prf) ->
ct:comment(lists:flatten(io_lib:format("cipher_list_empty Ver: ~p PRF: ~p", [TlsVer, Prf])));
prf_run_test(Config, TlsVer, Ciphers, Expected, Prf) ->
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
BaseOpts = [{active, true}, {versions, [TlsVer]}, {ciphers, Ciphers}, {protocol, tls_or_dtls(TlsVer)}],
ServerOpts = BaseOpts ++ proplists:get_value(server_rsa_opts, Config, []),
ClientOpts = BaseOpts ++ proplists:get_value(client_rsa_opts, Config, []),
Server = ssl_test_lib:start_server(
[{node, ServerNode}, {port, 0}, {from, self()},
{mfa, {?MODULE, prf_verify_value, [TlsVer, Expected, Prf]}},
{options, ServerOpts}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client(
[{node, ClientNode}, {port, Port},
{host, Hostname}, {from, self()},
{mfa, {?MODULE, prf_verify_value, [TlsVer, Expected, Prf]}},
{options, ClientOpts}]),
ssl_test_lib:check_result(Server, ok, Client, ok),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
tls_or_dtls('dtlsv1') ->
dtls;
tls_or_dtls('dtlsv1.2') ->
dtls;
tls_or_dtls(_) ->
tls.
active_n_common(S, N) ->
ok = ssl:setopts(S, [{active,-N}]),
receive
{ssl_passive, S} -> ok
after
1000 ->
error({error,ssl_passive_failure})
end,
[{active,false}] = ok(ssl:getopts(S, [active])),
ok = ssl:setopts(S, [{active,0}]),
receive
{ssl_passive, S} -> ok
after
1000 ->
error({error,ssl_passive_failure})
end,
ok = ssl:setopts(S, [{active,32767}]),
{error,{options,_}} = ssl:setopts(S, [{active,1}]),
{error,{options,_}} = ssl:setopts(S, [{active,-32769}]),
ok = ssl:setopts(S, [{active,-32768}]),
receive
{ssl_passive, S} -> ok
after
1000 ->
error({error,ssl_passive_failure})
end,
[{active,false}] = ok(ssl:getopts(S, [active])),
ok = ssl:setopts(S, [{active,N}]),
ok = ssl:setopts(S, [{active,true}]),
[{active,true}] = ok(ssl:getopts(S, [active])),
receive
_ -> error({error,active_n})
after
0 ->
ok
end,
ok = ssl:setopts(S, [{active,N}]),
ok = ssl:setopts(S, [{active,once}]),
[{active,once}] = ok(ssl:getopts(S, [active])),
receive
_ -> error({error,active_n})
after
0 ->
ok
end,
{error,{options,_}} = ssl:setopts(S, [{active,32768}]),
ok = ssl:setopts(S, [{active,false}]),
[{active,false}] = ok(ssl:getopts(S, [active])),
ok.
ok({ok,V}) -> V.
repeat(N, Fun) ->
repeat(N, N, Fun).
repeat(N, T, Fun) when is_integer(N), N > 0 ->
Fun(T-N),
repeat(N-1, T, Fun);
repeat(_, _, _) ->
ok.
get_close(Pid, Where) ->
receive
{'EXIT', Pid, _Reason} ->
receive
{_, {ssl_closed, Socket}} ->
ct:log("Socket closed ~p~n",[Socket]);
Unexpected ->
ct:log("Unexpected ~p~n",[Unexpected]),
ct:fail({line, ?LINE-1})
after 5000 ->
ct:fail({timeout, {line, ?LINE, Where}})
end;
Unexpected ->
ct:log("Unexpected ~p~n",[Unexpected]),
ct:fail({line, ?LINE-1})
after 5000 ->
ct:fail({timeout, {line, ?LINE, Where}})
end.
ssl_active_recv(N) ->
ssl_active_recv(N, []).
ssl_active_recv(0, Acc) ->
Acc;
ssl_active_recv(N, Acc) ->
receive
{ssl, _, Bytes} ->
ssl_active_recv(N-length(Bytes), Acc ++ Bytes)
end.
honor_cipher_order(Config, Honor, ServerCiphers, ClientCiphers, Expected) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, connection_info_result, []}},
{options, [{ciphers, ServerCiphers}, {honor_cipher_order, Honor}
| ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{mfa, {?MODULE, connection_info_result, []}},
{options, [{ciphers, ClientCiphers}
| ClientOpts]}]),
Version = ssl_test_lib:protocol_version(Config),
ServerMsg = ClientMsg = {ok, {Version, Expected}},
ssl_test_lib:check_result(Server, ServerMsg, Client, ClientMsg),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
cookie_extension(Config, Cookie) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
15 bytes
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Trigger a HelloRetryRequest
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{options, [{supported_groups, [x448,
secp256r1,
secp384r1]},
{cookie, Cookie}|ServerOpts]}]),
Port = ssl_test_lib:inet_port(Server),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{options, ClientOpts}]),
ok = ssl_test_lib:send(Client, Data),
Data = ssl_test_lib:check_active_receive(Server, Data),
ssl_test_lib:close(Server),
ssl_test_lib:close(Client).
start_client_negative(Config, Options, Error) ->
ClientOpts = ssl_test_lib:ssl_options(client_rsa_opts, Config),
{ClientNode, ServerNode, Hostname} = ssl_test_lib:run_where(Config),
Port = ssl_test_lib:inet_port(ServerNode),
Client = ssl_test_lib:start_client([{node, ClientNode}, {port, Port},
{host, Hostname},
{from, self()},
{return_error, econnrefused},
{mfa, {?MODULE, connection_info_result, []}},
{options, Options ++ ClientOpts}]),
ct:pal("Actual: ~p~nExpected: ~p", [Client, {connect_failed, Error}]),
{connect_failed, Error} = Client.
start_server_negative(Config, Options, Error) ->
ServerOpts = ssl_test_lib:ssl_options(server_rsa_opts, Config),
{_, ServerNode, _} = ssl_test_lib:run_where(Config),
Server = ssl_test_lib:start_server([{node, ServerNode}, {port, 0},
{from, self()},
{mfa, {?MODULE, connection_info_result, []}},
{options, Options ++ ServerOpts}]),
ct:pal("Actual: ~p~nExpected: ~p", [Server,Error]),
Error = Server.
der_input_opts(Opts) ->
Certfile = proplists:get_value(certfile, Opts),
CaCertsfile = proplists:get_value(cacertfile, Opts),
Keyfile = proplists:get_value(keyfile, Opts),
Dhfile = proplists:get_value(dhfile, Opts),
[{_, Cert, _}] = ssl_test_lib:pem_to_der(Certfile),
[{Asn1Type, Key, _}] = ssl_test_lib:pem_to_der(Keyfile),
[{_, DHParams, _}] = ssl_test_lib:pem_to_der(Dhfile),
CaCerts =
lists:map(fun(Entry) ->
{_, CaCert, _} = Entry,
CaCert
end, ssl_test_lib:pem_to_der(CaCertsfile)),
{Cert, {Asn1Type, Key}, CaCerts, DHParams}.
ssl_getstat(Socket) ->
ssl:send(Socket, "From Erlang to Erlang"),
{ok, Stats} = ssl:getstat(Socket),
List = lists:dropwhile(fun({_, 0}) ->
true;
({_, _}) ->
false
end, Stats),
case List of
[] ->
nok;
_ ->
ok
end.
|
59383dcdca1f90c9637733213af2d7b0aed70b18cc61ea8959df1c3423a5351f | jafingerhut/clojure-benchmarks | knucleotide.clj-17.clj | The Computer Language Benchmarks Game
;; /
contributed by
(ns knucleotide
(:gen-class))
(set! *warn-on-reflection* true)
(definterface IByteString
(calculateHash [buf offset])
(incCount [])
(^int hashCode [])
(^int getCount [])
(^boolean equals [obj2])
(^String toString [])
)
(deftype ByteString [^{:unsynchronized-mutable true :tag bytes} byteArr
^{:unsynchronized-mutable true :tag int} hash
^{:unsynchronized-mutable true :tag int} cnt
]
IByteString
(calculateHash [this b offset]
(let [^bytes buf b
len (int (alength byteArr))]
(loop [i (int 0)
offset (int offset)
temp (int 0)]
(if (== i len)
(set! hash temp)
;; else
(let [b (int (aget buf offset))
bb (byte b)]
(aset byteArr i bb)
(recur (unchecked-inc i) (unchecked-inc offset)
(unchecked-add (unchecked-multiply temp 31) b)))))))
(incCount [this]
(set! cnt (unchecked-inc cnt)))
(hashCode [this]
hash)
(getCount [this]
cnt)
(equals [this obj2]
(let [^ByteString obj2 obj2
^bytes byteArr2 (.byteArr obj2)]
(java.util.Arrays/equals byteArr byteArr2)))
(toString [this]
(apply str (map char (seq byteArr))))
)
(defn my-lazy-map [f coll]
(lazy-seq
(when-let [s (seq coll)]
(cons (f (first s)) (my-lazy-map f (rest s))))))
modified - pmap is like pmap from Clojure 1.1 , but with only as much
;; parallelism as specified by the parameter num-threads. Uses
;; my-lazy-map instead of map from core.clj, since that version of map
;; can use unwanted additional parallelism for chunked collections,
;; like ranges.
(defn modified-pmap
([num-threads f coll]
(if (== num-threads 1)
(map f coll)
(let [n (if (>= num-threads 2) (dec num-threads) 1)
rets (my-lazy-map #(future (f %)) coll)
step (fn step [[x & xs :as vs] fs]
(lazy-seq
(if-let [s (seq fs)]
(cons (deref x) (step xs (rest s)))
(map deref vs))))]
(step rets (drop n rets)))))
([num-threads f coll & colls]
(let [step (fn step [cs]
(lazy-seq
(let [ss (my-lazy-map seq cs)]
(when (every? identity ss)
(cons (my-lazy-map first ss)
(step (my-lazy-map rest ss)))))))]
(modified-pmap num-threads #(apply f %) (step (cons coll colls))))))
;; Return true when the line l is a FASTA description line
(defn fasta-description-line [l]
(= \> (first (seq l))))
;; Return true when the line l is a FASTA description line that begins
;; with the string desc-str.
(defn fasta-description-line-beginning [desc-str l]
(and (fasta-description-line l)
(= desc-str (subs l 1 (min (count l) (inc (count desc-str)))))))
Take a sequence of lines from a FASTA format file , and a string
;; desc-str. Look for a FASTA record with a description that begins
;; with desc-str, and if one is found, return its DNA sequence as a
;; single (potentially quite long) string. If input file is big,
;; you'll save lots of memory if you call this function in a with-open
;; for the file, and don't hold on to the head of the lines parameter.
(defn fasta-dna-str-with-desc-beginning [desc-str lines]
(when-let [x (drop-while
(fn [l] (not (fasta-description-line-beginning desc-str l)))
lines)]
(when-let [x (seq x)]
(let [y (take-while (fn [l] (not (fasta-description-line l)))
(map (fn [#^java.lang.String s] (.toUpperCase s))
(rest x)))]
(apply str y)))))
(defn tally-dna-subs-with-len [len ^bytes dna-bytes]
(let [last-index (inc (- (alength dna-bytes) len))
last - index ( - ( ) len )
tally (java.util.HashMap.)]
;; (println "tally-dna-subs-with-len len=" len
" ( " ( )
;; " last-index=" last-index
;; )
(loop [offset (int 0)
;;offset (int last-index)
key (ByteString. (byte-array len) 0 1)]
;; (if (neg? offset)
(if (== offset last-index)
tally
(do
(.calculateHash key dna-bytes offset)
;; (print "key " offset " to search: byteArr=" (.toString key)
;; " hash=" (.hashCode key)
;; " count=" (.getCount key)
;; " -- "
;; )
(if-let [^ByteString found-key (get tally key)]
(do
(.incCount found-key)
;; (println "found key: byteArr=" (.toString found-key)
;; " count=" (.getCount found-key))
(recur (unchecked-inc offset) key))
(do
(.put tally key key)
;; (println "no key found: inserted it")
(recur (unchecked-inc offset)
(ByteString. (byte-array len) 0 1)))))))))
(defn getcnt [^ByteString k]
(.getCount k))
(defn all-tally-to-str [tally]
(with-out-str
(let [total (reduce + (map getcnt (vals tally)))
cmp (fn [k1 k2]
;; Return negative integer if k1 should come earlier
;; in the sort order than k2, 0 if they are equal,
;; otherwise a positive integer.
(let [v1 (get tally k1)
v2 (get tally k2)
cnt1 (int (getcnt v1))
cnt2 (int (getcnt v2))]
(if (not= cnt1 cnt2)
(- cnt2 cnt1)
(.compareTo (.toString v1) (.toString v2)))))]
(doseq [^ByteString k
(sort cmp (keys tally))]
(printf "%s %.3f\n" (.toString k)
(double (* 100 (/ (getcnt (get tally k)) total))))))))
(defn ascii-str-to-bytes [^String s]
(let [result (byte-array (count s))]
(dotimes [i (count s)]
(aset result i (byte (int (nth s i)))))
result))
(defn one-tally-to-str [dna-str tally]
(let [key-bytes (ascii-str-to-bytes dna-str)
key (let [init (ByteString. (byte-array (count dna-str)) 0 1)]
(.calculateHash init key-bytes 0)
init)
occurrences (if-let [val (get tally key)]
(getcnt val)
0)]
(format "%d\t%s" occurrences dna-str)))
(defn compute-one-part [dna-bytes part]
(.println System/err (format "Starting part %d" part))
(let [ret-val
[part
(condp = part
0 (all-tally-to-str (tally-dna-subs-with-len 1 dna-bytes))
1 (all-tally-to-str (tally-dna-subs-with-len 2 dna-bytes))
2 (one-tally-to-str "GGT"
(tally-dna-subs-with-len 3 dna-bytes))
3 (one-tally-to-str "GGTA"
(tally-dna-subs-with-len 4 dna-bytes))
4 (one-tally-to-str "GGTATT"
(tally-dna-subs-with-len 6 dna-bytes))
5 (one-tally-to-str "GGTATTTTAATT"
(tally-dna-subs-with-len 12 dna-bytes))
6 (one-tally-to-str "GGTATTTTAATTTATAGT"
(tally-dna-subs-with-len 18 dna-bytes)))]]
(.println System/err (format "Finished part %d" part))
ret-val))
(def *default-modified-pmap-num-threads*
(+ 2 (.. Runtime getRuntime availableProcessors)))
(defn -main [& args]
(let [num-threads (if (>= (count args) 1)
(. Integer valueOf (nth args 0) 10)
*default-modified-pmap-num-threads*)]
(with-open [br (java.io.BufferedReader. *in*)]
(let [dna-bytes (ascii-str-to-bytes
(fasta-dna-str-with-desc-beginning "THREE" (line-seq br)))
;; Select the order of computing parts such that it is
unlikely that parts 5 and 6 will be computed
concurrently . Those are the two that take the most
memory . It would be nice if we could specify a DAG for
;; which jobs should finish before others begin -- then we
could prevent those two parts from running
;; simultaneously.
results (map second
(sort #(< (first %1) (first %2))
(modified-pmap num-threads
#(compute-one-part dna-bytes %)
'(0 5 6 1 2 3 4)
)))]
( dotimes [ i ( ) ]
( print " " ( aget dna - bytes i ) ) )
;; (println " eol")
(doseq [r results]
(println r)
(flush)))))
(shutdown-agents))
| null | https://raw.githubusercontent.com/jafingerhut/clojure-benchmarks/474a8a4823727dd371f1baa9809517f9e0b508d4/knucleotide/knucleotide.clj-17.clj | clojure | /
else
parallelism as specified by the parameter num-threads. Uses
my-lazy-map instead of map from core.clj, since that version of map
can use unwanted additional parallelism for chunked collections,
like ranges.
Return true when the line l is a FASTA description line
Return true when the line l is a FASTA description line that begins
with the string desc-str.
desc-str. Look for a FASTA record with a description that begins
with desc-str, and if one is found, return its DNA sequence as a
single (potentially quite long) string. If input file is big,
you'll save lots of memory if you call this function in a with-open
for the file, and don't hold on to the head of the lines parameter.
(println "tally-dna-subs-with-len len=" len
" last-index=" last-index
)
offset (int last-index)
(if (neg? offset)
(print "key " offset " to search: byteArr=" (.toString key)
" hash=" (.hashCode key)
" count=" (.getCount key)
" -- "
)
(println "found key: byteArr=" (.toString found-key)
" count=" (.getCount found-key))
(println "no key found: inserted it")
Return negative integer if k1 should come earlier
in the sort order than k2, 0 if they are equal,
otherwise a positive integer.
Select the order of computing parts such that it is
which jobs should finish before others begin -- then we
simultaneously.
(println " eol") | The Computer Language Benchmarks Game
contributed by
(ns knucleotide
(:gen-class))
(set! *warn-on-reflection* true)
(definterface IByteString
(calculateHash [buf offset])
(incCount [])
(^int hashCode [])
(^int getCount [])
(^boolean equals [obj2])
(^String toString [])
)
(deftype ByteString [^{:unsynchronized-mutable true :tag bytes} byteArr
^{:unsynchronized-mutable true :tag int} hash
^{:unsynchronized-mutable true :tag int} cnt
]
IByteString
(calculateHash [this b offset]
(let [^bytes buf b
len (int (alength byteArr))]
(loop [i (int 0)
offset (int offset)
temp (int 0)]
(if (== i len)
(set! hash temp)
(let [b (int (aget buf offset))
bb (byte b)]
(aset byteArr i bb)
(recur (unchecked-inc i) (unchecked-inc offset)
(unchecked-add (unchecked-multiply temp 31) b)))))))
(incCount [this]
(set! cnt (unchecked-inc cnt)))
(hashCode [this]
hash)
(getCount [this]
cnt)
(equals [this obj2]
(let [^ByteString obj2 obj2
^bytes byteArr2 (.byteArr obj2)]
(java.util.Arrays/equals byteArr byteArr2)))
(toString [this]
(apply str (map char (seq byteArr))))
)
(defn my-lazy-map [f coll]
(lazy-seq
(when-let [s (seq coll)]
(cons (f (first s)) (my-lazy-map f (rest s))))))
modified - pmap is like pmap from Clojure 1.1 , but with only as much
(defn modified-pmap
([num-threads f coll]
(if (== num-threads 1)
(map f coll)
(let [n (if (>= num-threads 2) (dec num-threads) 1)
rets (my-lazy-map #(future (f %)) coll)
step (fn step [[x & xs :as vs] fs]
(lazy-seq
(if-let [s (seq fs)]
(cons (deref x) (step xs (rest s)))
(map deref vs))))]
(step rets (drop n rets)))))
([num-threads f coll & colls]
(let [step (fn step [cs]
(lazy-seq
(let [ss (my-lazy-map seq cs)]
(when (every? identity ss)
(cons (my-lazy-map first ss)
(step (my-lazy-map rest ss)))))))]
(modified-pmap num-threads #(apply f %) (step (cons coll colls))))))
(defn fasta-description-line [l]
(= \> (first (seq l))))
(defn fasta-description-line-beginning [desc-str l]
(and (fasta-description-line l)
(= desc-str (subs l 1 (min (count l) (inc (count desc-str)))))))
Take a sequence of lines from a FASTA format file , and a string
(defn fasta-dna-str-with-desc-beginning [desc-str lines]
(when-let [x (drop-while
(fn [l] (not (fasta-description-line-beginning desc-str l)))
lines)]
(when-let [x (seq x)]
(let [y (take-while (fn [l] (not (fasta-description-line l)))
(map (fn [#^java.lang.String s] (.toUpperCase s))
(rest x)))]
(apply str y)))))
(defn tally-dna-subs-with-len [len ^bytes dna-bytes]
(let [last-index (inc (- (alength dna-bytes) len))
last - index ( - ( ) len )
tally (java.util.HashMap.)]
" ( " ( )
(loop [offset (int 0)
key (ByteString. (byte-array len) 0 1)]
(if (== offset last-index)
tally
(do
(.calculateHash key dna-bytes offset)
(if-let [^ByteString found-key (get tally key)]
(do
(.incCount found-key)
(recur (unchecked-inc offset) key))
(do
(.put tally key key)
(recur (unchecked-inc offset)
(ByteString. (byte-array len) 0 1)))))))))
(defn getcnt [^ByteString k]
(.getCount k))
(defn all-tally-to-str [tally]
(with-out-str
(let [total (reduce + (map getcnt (vals tally)))
cmp (fn [k1 k2]
(let [v1 (get tally k1)
v2 (get tally k2)
cnt1 (int (getcnt v1))
cnt2 (int (getcnt v2))]
(if (not= cnt1 cnt2)
(- cnt2 cnt1)
(.compareTo (.toString v1) (.toString v2)))))]
(doseq [^ByteString k
(sort cmp (keys tally))]
(printf "%s %.3f\n" (.toString k)
(double (* 100 (/ (getcnt (get tally k)) total))))))))
(defn ascii-str-to-bytes [^String s]
(let [result (byte-array (count s))]
(dotimes [i (count s)]
(aset result i (byte (int (nth s i)))))
result))
(defn one-tally-to-str [dna-str tally]
(let [key-bytes (ascii-str-to-bytes dna-str)
key (let [init (ByteString. (byte-array (count dna-str)) 0 1)]
(.calculateHash init key-bytes 0)
init)
occurrences (if-let [val (get tally key)]
(getcnt val)
0)]
(format "%d\t%s" occurrences dna-str)))
(defn compute-one-part [dna-bytes part]
(.println System/err (format "Starting part %d" part))
(let [ret-val
[part
(condp = part
0 (all-tally-to-str (tally-dna-subs-with-len 1 dna-bytes))
1 (all-tally-to-str (tally-dna-subs-with-len 2 dna-bytes))
2 (one-tally-to-str "GGT"
(tally-dna-subs-with-len 3 dna-bytes))
3 (one-tally-to-str "GGTA"
(tally-dna-subs-with-len 4 dna-bytes))
4 (one-tally-to-str "GGTATT"
(tally-dna-subs-with-len 6 dna-bytes))
5 (one-tally-to-str "GGTATTTTAATT"
(tally-dna-subs-with-len 12 dna-bytes))
6 (one-tally-to-str "GGTATTTTAATTTATAGT"
(tally-dna-subs-with-len 18 dna-bytes)))]]
(.println System/err (format "Finished part %d" part))
ret-val))
(def *default-modified-pmap-num-threads*
(+ 2 (.. Runtime getRuntime availableProcessors)))
(defn -main [& args]
(let [num-threads (if (>= (count args) 1)
(. Integer valueOf (nth args 0) 10)
*default-modified-pmap-num-threads*)]
(with-open [br (java.io.BufferedReader. *in*)]
(let [dna-bytes (ascii-str-to-bytes
(fasta-dna-str-with-desc-beginning "THREE" (line-seq br)))
unlikely that parts 5 and 6 will be computed
concurrently . Those are the two that take the most
memory . It would be nice if we could specify a DAG for
could prevent those two parts from running
results (map second
(sort #(< (first %1) (first %2))
(modified-pmap num-threads
#(compute-one-part dna-bytes %)
'(0 5 6 1 2 3 4)
)))]
( dotimes [ i ( ) ]
( print " " ( aget dna - bytes i ) ) )
(doseq [r results]
(println r)
(flush)))))
(shutdown-agents))
|
809e51fb4c1c91b9227b95b8d91b18f023309eeeac671b6e853c664199ee8746 | damballa/parkour | mapred.clj | (ns parkour.io.dseq.mapred
{:private true}
(:require [clojure.core.protocols :as ccp]
[clojure.core.reducers :as r]
[parkour (conf :as conf) (wrapper :as w)]
[parkour.util :refer [doto-let returning]]
[parkour.mapreduce (source :as src)]
[parkour.util :refer [returning]])
(:import [clojure.lang Seqable]
[java.io Closeable]
[org.apache.hadoop.conf Configuration Configurable]
[org.apache.hadoop.mapred InputFormat RecordReader Reporter]))
(defn input-format?
[klass] (isa? klass InputFormat))
(defn rr?
[rr] (instance? RecordReader rr))
(deftype RecordReaderTupleSource
[^Configuration conf ^InputFormat ifi
^:unsynchronized-mutable splits
^:unsynchronized-mutable ^RecordReader rr
^:unsynchronized-mutable key
^:unsynchronized-mutable val]
Configurable
(getConf [_] conf)
src/TupleSource
(key [_] key)
(val [_] val)
(next-keyval [this]
(if (and rr (or (.next rr key val) (returning false (.close rr))))
true
(if-not (empty? splits)
(let [split (first splits)]
(set! splits (rest splits))
(set! rr (.getRecordReader ifi split conf Reporter/NULL))
(set! key (.createKey rr))
(set! val (.createValue rr))
(recur)))))
(-initialize [_])
(-close [_] (.close rr))
(-nsplits [_] 1)
(-splits [this] [this])
java.io.Closeable
(close [this] (src/-close this))
ccp/CollReduce
(coll-reduce [this f] (ccp/coll-reduce this f (f)))
(coll-reduce [this f init] (src/source-reduce this f init))
r/CollFold
(coll-fold [this _ combinef reducef]
(src/source-fold this combinef reducef))
Seqable
(seq [this] (src/source-seq this)))
(defn tuple-source
{:tag `RecordReaderTupleSource}
[job klass]
(let [conf (conf/ig job)
^InputFormat ifi (w/new-instance conf klass)
splits (seq (.getSplits ifi conf 1))]
(RecordReaderTupleSource. conf ifi splits nil nil nil)))
| null | https://raw.githubusercontent.com/damballa/parkour/2b3c5e1987e18b4c4284dfd4fcdaba267a4d7fbc/src/clojure/parkour/io/dseq/mapred.clj | clojure | (ns parkour.io.dseq.mapred
{:private true}
(:require [clojure.core.protocols :as ccp]
[clojure.core.reducers :as r]
[parkour (conf :as conf) (wrapper :as w)]
[parkour.util :refer [doto-let returning]]
[parkour.mapreduce (source :as src)]
[parkour.util :refer [returning]])
(:import [clojure.lang Seqable]
[java.io Closeable]
[org.apache.hadoop.conf Configuration Configurable]
[org.apache.hadoop.mapred InputFormat RecordReader Reporter]))
(defn input-format?
[klass] (isa? klass InputFormat))
(defn rr?
[rr] (instance? RecordReader rr))
(deftype RecordReaderTupleSource
[^Configuration conf ^InputFormat ifi
^:unsynchronized-mutable splits
^:unsynchronized-mutable ^RecordReader rr
^:unsynchronized-mutable key
^:unsynchronized-mutable val]
Configurable
(getConf [_] conf)
src/TupleSource
(key [_] key)
(val [_] val)
(next-keyval [this]
(if (and rr (or (.next rr key val) (returning false (.close rr))))
true
(if-not (empty? splits)
(let [split (first splits)]
(set! splits (rest splits))
(set! rr (.getRecordReader ifi split conf Reporter/NULL))
(set! key (.createKey rr))
(set! val (.createValue rr))
(recur)))))
(-initialize [_])
(-close [_] (.close rr))
(-nsplits [_] 1)
(-splits [this] [this])
java.io.Closeable
(close [this] (src/-close this))
ccp/CollReduce
(coll-reduce [this f] (ccp/coll-reduce this f (f)))
(coll-reduce [this f init] (src/source-reduce this f init))
r/CollFold
(coll-fold [this _ combinef reducef]
(src/source-fold this combinef reducef))
Seqable
(seq [this] (src/source-seq this)))
(defn tuple-source
{:tag `RecordReaderTupleSource}
[job klass]
(let [conf (conf/ig job)
^InputFormat ifi (w/new-instance conf klass)
splits (seq (.getSplits ifi conf 1))]
(RecordReaderTupleSource. conf ifi splits nil nil nil)))
| |
a0ff4d06ba1dfedac53c58e05e57b471f4a6ebffb32a00b7f5a60fce2240d0fa | huangjs/cl | ans96.lisp | Simple inefficient answer to Qual 96 programming question
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The parser
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( PARSE input - words ) = > sorted list of scored target concepts
;;;
;;; Example:
;;;
> ( PARSE ' ( RAKE THE GARDEN ) )
( ( 30 M - RAKE - GARDEN ) ( 5 M - REMOVE - WEEDS - FROM - GARDEN ) ( 5 M - WATER - GARDEN ) )
;;;
PARSE takes an input text ( list of words ) and returns a list
;;; of target concepts that had index sets that intersected with
;;; concepts referred to by the input. How well those index sets
;;; intersect with the input concepts is reflected in the score.
(defun parse (input-words)
(get-targets (get-input-concepts input-words)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; From input words to concepts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; (GET-INPUT-CONCEPTS words) => list of concepts
;;; Returns the concepts referred to by the phrases and concepts
;;; in input-words.
(defun get-input-concepts (input-words)
(loop for words on input-words
until (null words)
append (get-initial-phrase-concepts words)))
;;; (GET-INITIAL-PHRASE-CONCEPTS words) => list of concepts
;;; Returns the concepts referred to by all phrases that match
words , starting with the first word in words .
;;;
;;; Data structures:
;;; pc (phrase concepts) = a phrase and a list of concepts
(defun get-initial-phrase-concepts (words)
(loop for pc in (get-all-phrases)
when (phrase-match-p (pc-phrase pc) words)
append (pc-concepts pc)))
;;; (PHRASE-MATCH-P phrase words) => true or false
Returns true if words starts with the first item in phrase
;;; and contains the remaining items in the same order.
(defun phrase-match-p (phrase words)
(or (null phrase)
(and (not (null words))
(eql (first phrase) (first words))
(phrase-match-p (rest phrase)
(member (first (rest phrase)) words)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; From input concepts to target concepts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; (GET-TARGETS concepts) => list of scored concepts
;;; Returns a list of scored concepts, sorted by scores, highest
scores first .
;;;
;;; Data structures:
;;; ic (indexed concepts = an index-set and a list of concepts
;;; sc (scored concepts) = a score and a list of concepts
(defun get-targets (input-pool)
(sort (get-scored-concepts input-pool)
#'> :key #'sc-score))
(defun get-scored-concepts (input-pool)
(loop for ic in (get-all-indexed-concepts)
for score = (score-index-set (ic-index-set ic) input-pool)
unless (null score)
collect (make-sc score (ic-concepts ic))))
(defun score-index-set (indices input)
(let ((indices-used (count-indices-used indices input))) ;;; p+s
(cond ((zerop indices-used) nil)
(t (score-match indices-used
(count-inputs-unused indices input) ;;; p-s
(- (length indices) indices-used)))))) ;;; s-p
(defun count-indices-used (indices input)
(count-if #'(lambda (c) (member c input :test #'abstp)) indices))
(defun count-inputs-unused (indices input)
(count-if-not #'(lambda (c) (member c indices :test #'specp)) input))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; From here on, we're past the official part of the qual answer
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Scoring matches
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
's summation formula is more complex . It also takes into
;;; account the "information value" of each concept. This could
;;; be handled in this code by changing the counting functions above.
(defun score-match (p+s p-s s-p)
(- (* 10 p+s) p-s s-p))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Memory functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Global variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Everything is stored in lists for easy initialization and
;;; iteration.
(defvar *absts* nil)
(defvar *indices* nil)
(defvar *phrases* nil)
;;; Abstractions
(defun abstp (a s)
(or (eql a s)
(member a (rest (absts-of s)))))
(defun specp (s a) (abstp a s))
(defun absts-of (s) (assoc s *absts*))
;;; Indexed concepts
(defun get-all-indexed-concepts () *indices*)
(defun ic-index-set (ic) (first ic))
(defun ic-concepts (ic) (rest ic))
;;; Scored concepts
(defun sc-score (sc) (first sc))
(defun sc-targets (sc) (rest sc))
(defun make-sc (score concepts) (cons score concepts))
;;; Phrases
(defun get-all-phrases () *phrases*)
(defun pc-phrase (pc) (first pc))
(defun pc-concepts (pc) (rest pc))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Robot gardener memory base
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq *absts*
'((m-rake m-object)
(m-weed m-plant m-object)
(m-move m-action)
(m-move-rake m-move m-action)
(m-rake-garden m-move-rake m-move m-action)
(m-transfer m-action)
(m-transfer-water m-transfer m-action)
(m-water-garden m-transfer-water m-transfer m-action)
(m-remove m-action)
(m-remove-weeds m-remove m-action)
(m-remove-weeds-from-garden m-remove-weeds m-remove m-action)
))
(setq *indices*
'(((m-rake m-move-rake m-garden) m-rake-garden)
((m-weed m-remove m-garden) m-remove-weeds-from-garden)
((m-water m-transfer-water m-garden) m-water-garden)
))
(setq *phrases*
'(((garden) m-garden)
((water) m-water m-transfer-water)
((water garden) m-water-garden)
((rake) m-rake m-move-rake)
((rake garden) m-rake-garden)
((weed) m-weed m-remove-weeds)
((weed garden) m-remove-weeds-from-garden)
)) | null | https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/other-code/cs325/www.cs.northwestern.edu/%7Eriesbeck/quals/ans96.lisp | lisp |
The parser
Example:
of target concepts that had index sets that intersected with
concepts referred to by the input. How well those index sets
intersect with the input concepts is reflected in the score.
From input words to concepts
(GET-INPUT-CONCEPTS words) => list of concepts
Returns the concepts referred to by the phrases and concepts
in input-words.
(GET-INITIAL-PHRASE-CONCEPTS words) => list of concepts
Returns the concepts referred to by all phrases that match
Data structures:
pc (phrase concepts) = a phrase and a list of concepts
(PHRASE-MATCH-P phrase words) => true or false
and contains the remaining items in the same order.
From input concepts to target concepts
(GET-TARGETS concepts) => list of scored concepts
Returns a list of scored concepts, sorted by scores, highest
Data structures:
ic (indexed concepts = an index-set and a list of concepts
sc (scored concepts) = a score and a list of concepts
p+s
p-s
s-p
From here on, we're past the official part of the qual answer
Scoring matches
account the "information value" of each concept. This could
be handled in this code by changing the counting functions above.
Memory functions
Global variables
Everything is stored in lists for easy initialization and
iteration.
Abstractions
Indexed concepts
Scored concepts
Phrases
Robot gardener memory base
| Simple inefficient answer to Qual 96 programming question
( PARSE input - words ) = > sorted list of scored target concepts
> ( PARSE ' ( RAKE THE GARDEN ) )
( ( 30 M - RAKE - GARDEN ) ( 5 M - REMOVE - WEEDS - FROM - GARDEN ) ( 5 M - WATER - GARDEN ) )
PARSE takes an input text ( list of words ) and returns a list
(defun parse (input-words)
(get-targets (get-input-concepts input-words)))
(defun get-input-concepts (input-words)
(loop for words on input-words
until (null words)
append (get-initial-phrase-concepts words)))
words , starting with the first word in words .
(defun get-initial-phrase-concepts (words)
(loop for pc in (get-all-phrases)
when (phrase-match-p (pc-phrase pc) words)
append (pc-concepts pc)))
Returns true if words starts with the first item in phrase
(defun phrase-match-p (phrase words)
(or (null phrase)
(and (not (null words))
(eql (first phrase) (first words))
(phrase-match-p (rest phrase)
(member (first (rest phrase)) words)))))
scores first .
(defun get-targets (input-pool)
(sort (get-scored-concepts input-pool)
#'> :key #'sc-score))
(defun get-scored-concepts (input-pool)
(loop for ic in (get-all-indexed-concepts)
for score = (score-index-set (ic-index-set ic) input-pool)
unless (null score)
collect (make-sc score (ic-concepts ic))))
(defun score-index-set (indices input)
(cond ((zerop indices-used) nil)
(t (score-match indices-used
(defun count-indices-used (indices input)
(count-if #'(lambda (c) (member c input :test #'abstp)) indices))
(defun count-inputs-unused (indices input)
(count-if-not #'(lambda (c) (member c indices :test #'specp)) input))
's summation formula is more complex . It also takes into
(defun score-match (p+s p-s s-p)
(- (* 10 p+s) p-s s-p))
(defvar *absts* nil)
(defvar *indices* nil)
(defvar *phrases* nil)
(defun abstp (a s)
(or (eql a s)
(member a (rest (absts-of s)))))
(defun specp (s a) (abstp a s))
(defun absts-of (s) (assoc s *absts*))
(defun get-all-indexed-concepts () *indices*)
(defun ic-index-set (ic) (first ic))
(defun ic-concepts (ic) (rest ic))
(defun sc-score (sc) (first sc))
(defun sc-targets (sc) (rest sc))
(defun make-sc (score concepts) (cons score concepts))
(defun get-all-phrases () *phrases*)
(defun pc-phrase (pc) (first pc))
(defun pc-concepts (pc) (rest pc))
(setq *absts*
'((m-rake m-object)
(m-weed m-plant m-object)
(m-move m-action)
(m-move-rake m-move m-action)
(m-rake-garden m-move-rake m-move m-action)
(m-transfer m-action)
(m-transfer-water m-transfer m-action)
(m-water-garden m-transfer-water m-transfer m-action)
(m-remove m-action)
(m-remove-weeds m-remove m-action)
(m-remove-weeds-from-garden m-remove-weeds m-remove m-action)
))
(setq *indices*
'(((m-rake m-move-rake m-garden) m-rake-garden)
((m-weed m-remove m-garden) m-remove-weeds-from-garden)
((m-water m-transfer-water m-garden) m-water-garden)
))
(setq *phrases*
'(((garden) m-garden)
((water) m-water m-transfer-water)
((water garden) m-water-garden)
((rake) m-rake m-move-rake)
((rake garden) m-rake-garden)
((weed) m-weed m-remove-weeds)
((weed garden) m-remove-weeds-from-garden)
)) |
a20ac6fe742bf3b0232412c76d8171cf78f8d2ea4f40468d7402e6b50ca3b153 | 8c6794b6/guile-tjit | punify.scm | ;;; punify --- Display Scheme code w/o unnecessary comments / whitespace
Copyright ( C ) 2001 , 2006 Free Software Foundation , Inc.
;;
;; This program is free software; 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 ; either version 3 , or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
You should have received a copy of the GNU Lesser General Public
License along with this software ; see the file . If
not , write to the Free Software Foundation , Inc. , 51 Franklin
Street , Fifth Floor , Boston , USA
Author :
;;; Commentary:
Usage : punify FILE1 ...
;;
;; Each file's forms are read and written to stdout.
;; The effect is to remove comments and much non-essential whitespace.
;; This is useful when installing Scheme source to space-limited media.
;;
;; Example:
$ wc ./punify ; ./punify ./punify | wc
89 384 ./punify
0 42 920
;;
TODO : Read from stdin .
;; Handle vectors.
;; Identifier punification.
;;; Code:
(define-module (scripts punify)
:export (punify))
(define %include-in-guild-list #f)
(define %summary "Strip comments and whitespace from a Scheme file.")
(define (write-punily form)
(cond ((and (list? form) (not (null? form)))
(let ((first (car form)))
(display "(")
(write-punily first)
(let loop ((ls (cdr form)) (last-was-list? (list? first)))
(if (null? ls)
(display ")")
(let* ((new-first (car ls))
(this-is-list? (list? new-first)))
(and (not last-was-list?)
(not this-is-list?)
(display " "))
(write-punily new-first)
(loop (cdr ls) this-is-list?))))))
((and (symbol? form)
(let ((ls (string->list (symbol->string form))))
(and (char=? (car ls) #\:)
(not (memq #\space ls))
(list->string (cdr ls)))))
=> (lambda (symbol-name-after-colon)
(display #\:)
(display symbol-name-after-colon)))
(else (write form))))
(define (punify-one file)
(with-input-from-file file
(lambda ()
(let ((toke (lambda () (read (current-input-port)))))
(let loop ((form (toke)))
(or (eof-object? form)
(begin
(write-punily form)
(loop (toke)))))))))
(define (punify . args)
(for-each punify-one args))
(define main punify)
;;; punify ends here
| null | https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/scripts/punify.scm | scheme | punify --- Display Scheme code w/o unnecessary comments / whitespace
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
either version 3 , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
see the file . If
Commentary:
Each file's forms are read and written to stdout.
The effect is to remove comments and much non-essential whitespace.
This is useful when installing Scheme source to space-limited media.
Example:
./punify ./punify | wc
Handle vectors.
Identifier punification.
Code:
punify ends here |
Copyright ( C ) 2001 , 2006 Free Software Foundation , Inc.
You should have received a copy of the GNU Lesser General Public
not , write to the Free Software Foundation , Inc. , 51 Franklin
Street , Fifth Floor , Boston , USA
Author :
Usage : punify FILE1 ...
89 384 ./punify
0 42 920
TODO : Read from stdin .
(define-module (scripts punify)
:export (punify))
(define %include-in-guild-list #f)
(define %summary "Strip comments and whitespace from a Scheme file.")
(define (write-punily form)
(cond ((and (list? form) (not (null? form)))
(let ((first (car form)))
(display "(")
(write-punily first)
(let loop ((ls (cdr form)) (last-was-list? (list? first)))
(if (null? ls)
(display ")")
(let* ((new-first (car ls))
(this-is-list? (list? new-first)))
(and (not last-was-list?)
(not this-is-list?)
(display " "))
(write-punily new-first)
(loop (cdr ls) this-is-list?))))))
((and (symbol? form)
(let ((ls (string->list (symbol->string form))))
(and (char=? (car ls) #\:)
(not (memq #\space ls))
(list->string (cdr ls)))))
=> (lambda (symbol-name-after-colon)
(display #\:)
(display symbol-name-after-colon)))
(else (write form))))
(define (punify-one file)
(with-input-from-file file
(lambda ()
(let ((toke (lambda () (read (current-input-port)))))
(let loop ((form (toke)))
(or (eof-object? form)
(begin
(write-punily form)
(loop (toke)))))))))
(define (punify . args)
(for-each punify-one args))
(define main punify)
|
1d2922bc995418aafb8240d91d4d307952d8b0b495bc087493b1779674e50126 | GaloisInc/HaNS | Ethernet.hs | # LANGUAGE RecordWildCards #
module Hans.Ethernet (
module Exports,
module Hans.Ethernet
) where
import Hans.Device.Types
import Hans.Ethernet.Types as Exports
import Hans.Serialize (runPutPacket)
import Control.Concurrent.BoundedChan (tryWriteChan)
import Control.Monad (unless)
import qualified Data.ByteString.Lazy as L
-- | Send a message out via a device.
sendEthernet :: Device -> Mac -> EtherType -> L.ByteString -> IO ()
sendEthernet Device { .. } eDest eType payload =
do let packet = runPutPacket 14 100 payload
$ putEthernetHeader EthernetHeader { eSource = devMac, .. }
-- if the packet is too big for the device, throw it away
if (fromIntegral (L.length packet) > dcMtu devConfig + 14)
then updateError statTX devStats
else do queued <- tryWriteChan devSendQueue packet
unless queued (updateDropped statTX devStats)
| null | https://raw.githubusercontent.com/GaloisInc/HaNS/2af19397dbb4f828192f896b223ed2b77dd9a055/src/Hans/Ethernet.hs | haskell | | Send a message out via a device.
if the packet is too big for the device, throw it away | # LANGUAGE RecordWildCards #
module Hans.Ethernet (
module Exports,
module Hans.Ethernet
) where
import Hans.Device.Types
import Hans.Ethernet.Types as Exports
import Hans.Serialize (runPutPacket)
import Control.Concurrent.BoundedChan (tryWriteChan)
import Control.Monad (unless)
import qualified Data.ByteString.Lazy as L
sendEthernet :: Device -> Mac -> EtherType -> L.ByteString -> IO ()
sendEthernet Device { .. } eDest eType payload =
do let packet = runPutPacket 14 100 payload
$ putEthernetHeader EthernetHeader { eSource = devMac, .. }
if (fromIntegral (L.length packet) > dcMtu devConfig + 14)
then updateError statTX devStats
else do queued <- tryWriteChan devSendQueue packet
unless queued (updateDropped statTX devStats)
|
66aefcfe496b1ac6e2b12c273567c367c2fd002689bc983141122db51b5e9c93 | chetmurthy/poly-protobuf | test17_ml.ml | module T = Test17_types
module Pb = Test17_pb
module Pp = Test17_pp
let decode_ref_data () = T.({
m1 = { i1 = 1; i2 = 2; };
m2 = 1;
m3 = 1;
o = M4 4;
})
let mode = Test_util.parse_args ()
let () =
match mode with
| Test_util.Decode ->
Test_util.decode "test17.c2ml.data" Pb.decode_m Pp.pp_m (decode_ref_data ())
| Test_util.Encode ->
Test_util.encode "test17.ml2c.data" Pb.encode_m (decode_ref_data ())
| null | https://raw.githubusercontent.com/chetmurthy/poly-protobuf/1f80774af6472fa30ee2fb10d0ef91905a13a144/tests/testdata/integration-tests/test17_ml.ml | ocaml | module T = Test17_types
module Pb = Test17_pb
module Pp = Test17_pp
let decode_ref_data () = T.({
m1 = { i1 = 1; i2 = 2; };
m2 = 1;
m3 = 1;
o = M4 4;
})
let mode = Test_util.parse_args ()
let () =
match mode with
| Test_util.Decode ->
Test_util.decode "test17.c2ml.data" Pb.decode_m Pp.pp_m (decode_ref_data ())
| Test_util.Encode ->
Test_util.encode "test17.ml2c.data" Pb.encode_m (decode_ref_data ())
| |
f055c8b14ad91fc35148924a7b99e08a24ac555119cd25f7de707aefaf53c9b2 | tlaplus/tlapm | method_old.ml |
* method_old.ml --- abstraction of methods : old version to keep fingerprints compatibility
*
*
* Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation
* method_old.ml --- abstraction of methods : old version to keep fingerprints compatibility
*
*
* Copyright (C) 2008-2010 INRIA and Microsoft Corporation
*)
open Ext
type t =
| Isabelle of string
| Zenon of zenon
| Smt | Yices | Z3 | Cooper
| Sorry (*| Fail*)
and zenon = { zenon_timeout : float ;
zenon_fallback : t}
let default_zenon = { zenon_timeout = 10.0 ;
zenon_fallback = Isabelle "auto" }
type status_type = Trivial | BeingProved | Success of t | Fail of t | Checked | Interrupted of t
open Format
let rec pp_print_method ff meth =
fprintf ff "@[<h>(*{ by %a }*)@]"
pp_print_tactic meth
and pp_print_tactic ff = function
| Isabelle is ->
fprintf ff "@[<h>(%s)@]" is
| Zenon zen ->
fprintf ff "@[<h>(%a)@]" pp_print_zenon zen
| Smt ->
fprintf ff "(smt)"
| Yices ->
fprintf ff "(yices)"
| Z3 ->
fprintf ff "(z3)"
| Cooper ->
fprintf ff "(cooper)"
| Sorry ->
fprintf ff "(sorry)"
| Fail - >
ff " ( fail ) "
fprintf ff "(fail)"*)
and pp_print_zenon ff zen =
fprintf ff "zenon %g %a"
zen.zenon_timeout
pp_print_tactic zen.zenon_fallback
let pp_print_tactic_fp ff = function
| Isabelle is ->
fprintf ff "isabelle=%s" is
| Zenon zen ->
fprintf ff "zenon=%g" zen.zenon_timeout
| Smt ->
fprintf ff "smt= "
| Yices ->
fprintf ff "yices= "
| Z3 ->
fprintf ff "z3= "
| Cooper ->
fprintf ff "cooper= "
| Sorry ->
fprintf ff "sorry= "
| Fail - >
ff " fail= "
fprintf ff "fail= "*)
| null | https://raw.githubusercontent.com/tlaplus/tlapm/b82e2fd049c5bc1b14508ae16890666c6928975f/src/method_old.ml | ocaml | | Fail |
* method_old.ml --- abstraction of methods : old version to keep fingerprints compatibility
*
*
* Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation
* method_old.ml --- abstraction of methods : old version to keep fingerprints compatibility
*
*
* Copyright (C) 2008-2010 INRIA and Microsoft Corporation
*)
open Ext
type t =
| Isabelle of string
| Zenon of zenon
| Smt | Yices | Z3 | Cooper
and zenon = { zenon_timeout : float ;
zenon_fallback : t}
let default_zenon = { zenon_timeout = 10.0 ;
zenon_fallback = Isabelle "auto" }
type status_type = Trivial | BeingProved | Success of t | Fail of t | Checked | Interrupted of t
open Format
let rec pp_print_method ff meth =
fprintf ff "@[<h>(*{ by %a }*)@]"
pp_print_tactic meth
and pp_print_tactic ff = function
| Isabelle is ->
fprintf ff "@[<h>(%s)@]" is
| Zenon zen ->
fprintf ff "@[<h>(%a)@]" pp_print_zenon zen
| Smt ->
fprintf ff "(smt)"
| Yices ->
fprintf ff "(yices)"
| Z3 ->
fprintf ff "(z3)"
| Cooper ->
fprintf ff "(cooper)"
| Sorry ->
fprintf ff "(sorry)"
| Fail - >
ff " ( fail ) "
fprintf ff "(fail)"*)
and pp_print_zenon ff zen =
fprintf ff "zenon %g %a"
zen.zenon_timeout
pp_print_tactic zen.zenon_fallback
let pp_print_tactic_fp ff = function
| Isabelle is ->
fprintf ff "isabelle=%s" is
| Zenon zen ->
fprintf ff "zenon=%g" zen.zenon_timeout
| Smt ->
fprintf ff "smt= "
| Yices ->
fprintf ff "yices= "
| Z3 ->
fprintf ff "z3= "
| Cooper ->
fprintf ff "cooper= "
| Sorry ->
fprintf ff "sorry= "
| Fail - >
ff " fail= "
fprintf ff "fail= "*)
|
50f616a44dd3f61f53c2d05628e08db3713f958ba57e1aa92c1eda40389fbcde | silviucpp/erlcass | load_test.erl | -module(load_test).
-include("erlcass.hrl").
-export([
profile/2,
profile/3,
prepare_load_test_table/0
]).
-define(KEYSPACE, <<"load_test_erlcass">>).
-define(QUERY, {<<"SELECT col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14 FROM test_table WHERE col1 =?">>, ?CASS_CONSISTENCY_ONE}).
-define(QUERY_ARGS, [<<"hello">>]).
-define(CLUSTER_NAME, <<"dc-beta">>).
start() ->
case application:ensure_all_started(erlcass) of
{ok, [_|_]} ->
ok;
UnexpectedError ->
UnexpectedError
end.
prepare_load_test_table() ->
start(),
erlcass:query(<<"DROP KEYSPACE ", (?KEYSPACE)/binary>>),
ok = erlcass:query(<<"CREATE KEYSPACE ", (?KEYSPACE)/binary, " WITH replication = {'class': 'NetworkTopologyStrategy', '", (?CLUSTER_NAME)/binary, "': 3 }">>),
Cols = datatypes_columns([ascii, bigint, blob, boolean, decimal, double, float, int, timestamp, uuid, varchar, varint, timeuuid, inet]),
Sql = <<"CREATE TABLE ", (?KEYSPACE)/binary, ".test_table(", Cols/binary, " PRIMARY KEY(col1));">>,
io:format(<<"exec: ~p ~n">>,[Sql]),
ok = erlcass:query(Sql),
InsertQuery = <<"INSERT INTO ", (?KEYSPACE)/binary, ".test_table(col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)">>,
ok = erlcass:add_prepare_statement(add_load_test_record, InsertQuery),
AsciiValBin = <<"hello">>,
BigIntPositive = 9223372036854775807,
Blob = <<1,2,3,4,5,6,7,8,9,10>>,
BooleanTrue = true,
DecimalPositive = {erlang:integer_to_binary(1234), 5},
DoublePositive = 5.1235131241221e-6,
FloatPositive = 5.12351e-6,
IntPositive = 2147483647,
Timestamp = 2147483647,
{ok, Uuid} = erlcass_uuid:gen_random(),
Varchar1 = <<"Юникод"/utf8>>,
Varint1 = erlang:integer_to_binary(1928301970128391280192830198049113123),
{ok, Timeuuid} = erlcass_uuid:gen_time(),
Inet = <<"127.0.0.1">>,
ok = erlcass:execute(add_load_test_record, [
AsciiValBin,
BigIntPositive,
Blob,
BooleanTrue,
DecimalPositive,
DoublePositive,
FloatPositive,
IntPositive,
Timestamp,
Uuid,
Varchar1,
Varint1,
Timeuuid,
Inet
]).
profile(NrProc, RequestsNr) ->
start(),
profile(NrProc, RequestsNr, 1).
profile(NrProc, RequestsNr, RepeatNumber) ->
start(),
Fun = fun() -> do_profiling(NrProc, RequestsNr, RepeatNumber) end,
spawn(Fun).
do_profiling(NrProc, RequestsNr, RepeatNumber) ->
erlcass:add_prepare_statement(execute_query, ?QUERY),
eprof:start(),
eprof:start_profiling([self()]),
ok = application:set_env(erlcass, keyspace, ?KEYSPACE),
start(),
ProcsList = lists:seq(1, NrProc),
{Time, _} = timer:tc( fun() -> run_test(RepeatNumber, NrProc, RequestsNr, ProcsList) end),
io:format("Cpp Driver Metrics: ~p ~n", [erlcass:get_metrics()]),
eprof:stop_profiling(),
eprof:analyze(total),
io:format("Time to complete: ~p ms ~n", [Time/1000]).
run_test(0, _NrProc, _RequestsNr, _ProcsList) ->
ok;
run_test(RepeatNr, NrProc, RequestsNr, ProcsList) ->
load_test(NrProc, RequestsNr, ProcsList),
run_test(RepeatNr -1, NrProc, RequestsNr, ProcsList).
load_test(1, NrReq, _ProcsList) ->
producer_loop(NrReq),
consumer_loop(0, 0, 0, NrReq);
load_test(NrProcesses, NrReq, ProcsList) ->
ReqPerProcess = round(NrReq/NrProcesses),
Self = self(),
Fun = fun() ->
producer_loop(ReqPerProcess),
consumer_loop(0, 0, 0, ReqPerProcess),
Self ! {self(), done}
end,
wait_finish(Fun, ProcsList).
wait_finish(Fun, ProcsList) ->
Pids = [spawn_link(Fun) || _ <- ProcsList],
[receive {Pid, done} -> ok end || Pid <- Pids],
ok.
consumer_loop(TotalResults, SuccessResults, FailedResults, 0) ->
io:format("**** Test Completed => results: ~p success: ~p failed: ~p **** ~n",[TotalResults, SuccessResults, FailedResults]),
ok;
consumer_loop(TotalResults, SuccessResults, FailedResults, LimitReq) ->
receive
%success results
{execute_statement_result, _Tag, {ok, _Cols, _Rows}} ->
%io:format("Result:~p ~n", [Result]),
display_progress(TotalResults),
consumer_loop(TotalResults +1 , SuccessResults +1, FailedResults, LimitReq -1);
%failed results
{execute_statement_result, _Tag, Result} ->
io:format("Result:~p ~n", [Result]),
display_progress(TotalResults),
consumer_loop(TotalResults +1 , SuccessResults, FailedResults + 1, LimitReq -1)
end.
producer_loop(0) ->
ok;
producer_loop(NumRequests) ->
erlcass:async_execute(execute_query, ?QUERY_ARGS),
producer_loop(NumRequests -1).
display_progress(Results) ->
if
Results rem 10000 =:= 0 ->
io:format("Executed ~p requests ~n", [Results]);
true ->
ok
end.
datatypes_columns(Cols) ->
datatypes_columns(1, Cols, <<>>).
datatypes_columns(_I, [], Bin) -> Bin;
datatypes_columns(I, [ColumnType|Rest], Bin) ->
Column = list_to_binary(io_lib:format("col~B ~s, ", [I, ColumnType])),
datatypes_columns(I+1, Rest, << Bin/binary, Column/binary >>).
| null | https://raw.githubusercontent.com/silviucpp/erlcass/4a18c9bcb89b70ce7284c610def12c646284c2e1/benchmarks/load_test.erl | erlang | success results
io:format("Result:~p ~n", [Result]),
failed results | -module(load_test).
-include("erlcass.hrl").
-export([
profile/2,
profile/3,
prepare_load_test_table/0
]).
-define(KEYSPACE, <<"load_test_erlcass">>).
-define(QUERY, {<<"SELECT col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14 FROM test_table WHERE col1 =?">>, ?CASS_CONSISTENCY_ONE}).
-define(QUERY_ARGS, [<<"hello">>]).
-define(CLUSTER_NAME, <<"dc-beta">>).
start() ->
case application:ensure_all_started(erlcass) of
{ok, [_|_]} ->
ok;
UnexpectedError ->
UnexpectedError
end.
prepare_load_test_table() ->
start(),
erlcass:query(<<"DROP KEYSPACE ", (?KEYSPACE)/binary>>),
ok = erlcass:query(<<"CREATE KEYSPACE ", (?KEYSPACE)/binary, " WITH replication = {'class': 'NetworkTopologyStrategy', '", (?CLUSTER_NAME)/binary, "': 3 }">>),
Cols = datatypes_columns([ascii, bigint, blob, boolean, decimal, double, float, int, timestamp, uuid, varchar, varint, timeuuid, inet]),
Sql = <<"CREATE TABLE ", (?KEYSPACE)/binary, ".test_table(", Cols/binary, " PRIMARY KEY(col1));">>,
io:format(<<"exec: ~p ~n">>,[Sql]),
ok = erlcass:query(Sql),
InsertQuery = <<"INSERT INTO ", (?KEYSPACE)/binary, ".test_table(col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)">>,
ok = erlcass:add_prepare_statement(add_load_test_record, InsertQuery),
AsciiValBin = <<"hello">>,
BigIntPositive = 9223372036854775807,
Blob = <<1,2,3,4,5,6,7,8,9,10>>,
BooleanTrue = true,
DecimalPositive = {erlang:integer_to_binary(1234), 5},
DoublePositive = 5.1235131241221e-6,
FloatPositive = 5.12351e-6,
IntPositive = 2147483647,
Timestamp = 2147483647,
{ok, Uuid} = erlcass_uuid:gen_random(),
Varchar1 = <<"Юникод"/utf8>>,
Varint1 = erlang:integer_to_binary(1928301970128391280192830198049113123),
{ok, Timeuuid} = erlcass_uuid:gen_time(),
Inet = <<"127.0.0.1">>,
ok = erlcass:execute(add_load_test_record, [
AsciiValBin,
BigIntPositive,
Blob,
BooleanTrue,
DecimalPositive,
DoublePositive,
FloatPositive,
IntPositive,
Timestamp,
Uuid,
Varchar1,
Varint1,
Timeuuid,
Inet
]).
profile(NrProc, RequestsNr) ->
start(),
profile(NrProc, RequestsNr, 1).
profile(NrProc, RequestsNr, RepeatNumber) ->
start(),
Fun = fun() -> do_profiling(NrProc, RequestsNr, RepeatNumber) end,
spawn(Fun).
do_profiling(NrProc, RequestsNr, RepeatNumber) ->
erlcass:add_prepare_statement(execute_query, ?QUERY),
eprof:start(),
eprof:start_profiling([self()]),
ok = application:set_env(erlcass, keyspace, ?KEYSPACE),
start(),
ProcsList = lists:seq(1, NrProc),
{Time, _} = timer:tc( fun() -> run_test(RepeatNumber, NrProc, RequestsNr, ProcsList) end),
io:format("Cpp Driver Metrics: ~p ~n", [erlcass:get_metrics()]),
eprof:stop_profiling(),
eprof:analyze(total),
io:format("Time to complete: ~p ms ~n", [Time/1000]).
run_test(0, _NrProc, _RequestsNr, _ProcsList) ->
ok;
run_test(RepeatNr, NrProc, RequestsNr, ProcsList) ->
load_test(NrProc, RequestsNr, ProcsList),
run_test(RepeatNr -1, NrProc, RequestsNr, ProcsList).
load_test(1, NrReq, _ProcsList) ->
producer_loop(NrReq),
consumer_loop(0, 0, 0, NrReq);
load_test(NrProcesses, NrReq, ProcsList) ->
ReqPerProcess = round(NrReq/NrProcesses),
Self = self(),
Fun = fun() ->
producer_loop(ReqPerProcess),
consumer_loop(0, 0, 0, ReqPerProcess),
Self ! {self(), done}
end,
wait_finish(Fun, ProcsList).
wait_finish(Fun, ProcsList) ->
Pids = [spawn_link(Fun) || _ <- ProcsList],
[receive {Pid, done} -> ok end || Pid <- Pids],
ok.
consumer_loop(TotalResults, SuccessResults, FailedResults, 0) ->
io:format("**** Test Completed => results: ~p success: ~p failed: ~p **** ~n",[TotalResults, SuccessResults, FailedResults]),
ok;
consumer_loop(TotalResults, SuccessResults, FailedResults, LimitReq) ->
receive
{execute_statement_result, _Tag, {ok, _Cols, _Rows}} ->
display_progress(TotalResults),
consumer_loop(TotalResults +1 , SuccessResults +1, FailedResults, LimitReq -1);
{execute_statement_result, _Tag, Result} ->
io:format("Result:~p ~n", [Result]),
display_progress(TotalResults),
consumer_loop(TotalResults +1 , SuccessResults, FailedResults + 1, LimitReq -1)
end.
producer_loop(0) ->
ok;
producer_loop(NumRequests) ->
erlcass:async_execute(execute_query, ?QUERY_ARGS),
producer_loop(NumRequests -1).
display_progress(Results) ->
if
Results rem 10000 =:= 0 ->
io:format("Executed ~p requests ~n", [Results]);
true ->
ok
end.
datatypes_columns(Cols) ->
datatypes_columns(1, Cols, <<>>).
datatypes_columns(_I, [], Bin) -> Bin;
datatypes_columns(I, [ColumnType|Rest], Bin) ->
Column = list_to_binary(io_lib:format("col~B ~s, ", [I, ColumnType])),
datatypes_columns(I+1, Rest, << Bin/binary, Column/binary >>).
|
0e21ab4c075bab37e23b00814fe4f79f9f65b551f4f819bff6591163a64d3727 | movio/spaceapps-streamgazer | webservice.clj | (ns crawler.webservice
(:require [clojure.data.csv :as csv]
[clj-http.client :as http]
[clojure.java.io :as io]))
(def station-search-url "")
(def result-search-url "")
(defn read-csv-as-map [input]
(let [data (csv/read-csv input)
column-names (first data)
data (rest data)]
(map #(zipmap column-names %) data)))
(defn- params [geo-loc start-date end-date]
{"bBox" (apply str (interpose "," geo-loc))
"startDateLo" start-date
"startDateHi" end-date
"mimeType" "csv"})
(defn search-sites [geo-loc start-date end-date]
(let [q (params geo-loc start-date end-date)
resp (http/get station-search-url {:query-params q
:as :stream})
reader (io/reader (:body resp))]
;(println (dissoc resp :body))
(->> reader
read-csv-as-map
(map (fn [m]
[(get m "MonitoringLocationIdentifier")
(select-keys m ["LatitudeMeasure" "LongitudeMeasure"])]))
(into {}))))
(def characteristics
["Depth"
"Current speed"
"Temperature, water"
"Stream width measure"
"Stream flow, mean. daily"
"Stream velocity"])
(def result-columns
[[["ActivityIdentifier"]
(fn [v] [:activity-id v])]
[["MonitoringLocationIdentifier"]
(fn [v] [:loc-id v])]
[["CharacteristicName"]
(fn [v] [:name v])]
[["ResultMeasureValue"]
(fn [v] [:value v])]
[["ResultMeasure/MeasureUnitCode"]
(fn [v] [:unit v])]
[["ActivityStartDate"
"ActivityStartTime/Time"]
(fn [date time] [:date-time (str date "T" time)])]
[["LatitudeMeasure"
"LongitudeMeasure"]
(fn [lat lon] [:geo-loc (str lat "," lon)])]])
(defn transform-item [m]
(->> result-columns
(map (fn [[cols f]]
(->> (map #(get m %) cols)
(apply f))))
(into {})))
(defn search-results [geo-loc start-date end-date]
(let [sites (future (search-sites geo-loc start-date end-date))
q (assoc (params geo-loc start-date end-date)
"characteristicName"
(apply str (interpose ";" characteristics)))
resp (http/get result-search-url {:query-params q
:as :stream})
reader (io/reader (:body resp))]
(->> reader
read-csv-as-map
(map (fn [m]
(let [m (select-keys m (mapcat first result-columns))
site-id (get m "MonitoringLocationIdentifier")]
(if-let [loc (get @sites site-id)]
(->> loc
(into m)
transform-item))))))))
| null | https://raw.githubusercontent.com/movio/spaceapps-streamgazer/4a19a054c2198aceaadbebca85ea37712f96d855/crawler/src/crawler/webservice.clj | clojure | (println (dissoc resp :body)) | (ns crawler.webservice
(:require [clojure.data.csv :as csv]
[clj-http.client :as http]
[clojure.java.io :as io]))
(def station-search-url "")
(def result-search-url "")
(defn read-csv-as-map [input]
(let [data (csv/read-csv input)
column-names (first data)
data (rest data)]
(map #(zipmap column-names %) data)))
(defn- params [geo-loc start-date end-date]
{"bBox" (apply str (interpose "," geo-loc))
"startDateLo" start-date
"startDateHi" end-date
"mimeType" "csv"})
(defn search-sites [geo-loc start-date end-date]
(let [q (params geo-loc start-date end-date)
resp (http/get station-search-url {:query-params q
:as :stream})
reader (io/reader (:body resp))]
(->> reader
read-csv-as-map
(map (fn [m]
[(get m "MonitoringLocationIdentifier")
(select-keys m ["LatitudeMeasure" "LongitudeMeasure"])]))
(into {}))))
(def characteristics
["Depth"
"Current speed"
"Temperature, water"
"Stream width measure"
"Stream flow, mean. daily"
"Stream velocity"])
(def result-columns
[[["ActivityIdentifier"]
(fn [v] [:activity-id v])]
[["MonitoringLocationIdentifier"]
(fn [v] [:loc-id v])]
[["CharacteristicName"]
(fn [v] [:name v])]
[["ResultMeasureValue"]
(fn [v] [:value v])]
[["ResultMeasure/MeasureUnitCode"]
(fn [v] [:unit v])]
[["ActivityStartDate"
"ActivityStartTime/Time"]
(fn [date time] [:date-time (str date "T" time)])]
[["LatitudeMeasure"
"LongitudeMeasure"]
(fn [lat lon] [:geo-loc (str lat "," lon)])]])
(defn transform-item [m]
(->> result-columns
(map (fn [[cols f]]
(->> (map #(get m %) cols)
(apply f))))
(into {})))
(defn search-results [geo-loc start-date end-date]
(let [sites (future (search-sites geo-loc start-date end-date))
q (assoc (params geo-loc start-date end-date)
"characteristicName"
(apply str (interpose ";" characteristics)))
resp (http/get result-search-url {:query-params q
:as :stream})
reader (io/reader (:body resp))]
(->> reader
read-csv-as-map
(map (fn [m]
(let [m (select-keys m (mapcat first result-columns))
site-id (get m "MonitoringLocationIdentifier")]
(if-let [loc (get @sites site-id)]
(->> loc
(into m)
transform-item))))))))
|
5f790d21a4e82385e17ccd002826cd093f590b317c29f00c6ebd23ab807abc6d | erlangonrails/devdb | yaws_jsonrpc.erl | Copyright ( C ) 2003 < > .
%% All rights reserved.
%%
Copyright ( C ) 2006 < >
< >
%% All rights reserved.
%%
%%
%% Redistribution and use in source and binary forms, with or without
%% modification, are permitted provided that the following conditions
%% are met:
%%
1 . Redistributions of source code must retain the above copyright
%% notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above
%% copyright notice, this list of conditions and the following
%% disclaimer in the documentation and/or other materials provided
%% with the distribution.
%%
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS
%% OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
%% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%% ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
%% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
%% GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
%% WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
%% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
%% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-module(yaws_jsonrpc).
-author("Gaspar Chilingarov <>, Gurgen Tumanyan <>").
-export([handler/2]).
-export([handler_session/2, handler_session/3]).
-define(debug , 1 ) .
%-include("../../yaws/src/yaws_debug.hrl").
-include("../include/yaws_api.hrl").
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
%%% public interface
%%%
%%%
use jsonrpc handler which can automagically start sessions if we need
%%%
handler_session(Args, Handler) ->
handler_session(Args, Handler, 'SID').
%%%
%%% allow overriding session Cookie name
%%%
handler_session(Args, Handler, SID_NAME) when is_atom(SID_NAME) ->
handler_session(Args, Handler, atom_to_list(SID_NAME));
handler_session(Args, Handler, SID_NAME) ->
handler(Args, Handler, {session, SID_NAME}). % go to generic handler
%%%
%%% xmlrpc:handler compatible call
%%% no session support will be available
handler(Args, Handler) ->
handler(Args, Handler, simple).
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
%%% private functions
%%%
%%% we should be called from yaws page or module
handler(Args, Handler, Type) when is_record(Args, arg) -> % {{{
case parse_request(Args) of
ok ->
handle_payload(Args, Handler, Type);
{status, StatusCode} -> % cannot parse request
send(Args, StatusCode)
end. % }}}
-define(ERROR_LOG(Reason),
error_logger:error_report({?MODULE, ?LINE, Reason})).
%%%
%%% check that request come in reasonable protocol version and reasonable method
%%%
parse_request(Args) -> % {{{
case {(Args#arg.req)#http_request.method, (Args#arg.req)#http_request.version} of
{'POST', {1,0}} ->
% ?Debug("HTTP Version 1.0~n", []),
ok;
{'POST', {1,1}} ->
? Debug("HTTP Version 1.1 ~ n " , [ ] ) ,
ok;
{'POST', _HTTPVersion} -> {status, 505};
{_Method, {1,1}} -> {status, 501};
_ -> {status, 400}
end. % }}}
handle_payload(Args, Handler, Type) -> % {{{
Payload = binary_to_list(Args#arg.clidata),
? plaintext call ~p ~n " , [ Payload ] ) ,
case decode_handler_payload(Payload) of
{ok, DecodedPayload, ID} ->
? Debug("json2erl decoded call ~p ~n " , [ DecodedPayload ] ) ,
eval_payload(Args, Handler, DecodedPayload, Type, ID);
{error, Reason} ->
?ERROR_LOG({html, json2erl, Payload, Reason}),
send(Args, 400)
end. % }}}
%%%
%%% call handler/3 and provide session support
eval_payload(Args, {M, F}, Payload, {session, CookieName},ID) -> % {{{
{SessionValue, Cookie} = case yaws_api:find_cookie_val(CookieName, (Args#arg.headers)#headers.cookie) of
[] -> % have no session started, just call handler
{undefined, undefined};
Cookie2 -> % get old session data
case yaws_api:cookieval_to_opaque(Cookie2) of
{ok, OP} ->
yaws_api:cookieval_to_opaque(Cookie2),
{OP, Cookie2};
{error, _ErrMsg} -> % cannot get corresponding session
{undefined, undefined}
end
end,
case catch M:F(Args#arg.state, Payload, SessionValue) of
{'EXIT', Reason} ->
?ERROR_LOG({M, F, {'EXIT', Reason}}),
send(Args, 500);
{error, Reason} ->
?ERROR_LOG({M, F, Reason}),
send(Args, 500);
{false, ResponsePayload} ->
% do not have updates in session data
encode_send(Args, 200, ResponsePayload, [], ID);
{true, _NewTimeout, NewSessionValue, ResponsePayload} -> % be compatible with xmlrpc module
CO = case NewSessionValue of
undefined when Cookie == undefined -> []; % nothing to do
undefined -> % rpc handler requested session delete
yaws_api:delete_cookie_session(Cookie), []; % XXX: may be return set-cookie with empty val?
_ -> % any other value will stored in session
case SessionValue of
undefined -> % got session data and should start new session now
Cookie1 = yaws_api:new_cookie_session(NewSessionValue),
return set_cookie header
_ ->
yaws_api:replace_cookie_session(Cookie, NewSessionValue),
[] % nothing to add to yaws data
end
end,
encode_send(Args, 200, ResponsePayload, CO, ID)
end; % }}}
%%%
%%% call handler/2 without session support
%%%
eval_payload(Args, {M, F}, Payload, simple, ID) -> % {{{
case catch M:F(Args#arg.state, Payload) of
{'EXIT', Reason} ->
?ERROR_LOG({M, F, {'EXIT', Reason}}),
send(Args, 500);
{error, Reason} ->
?ERROR_LOG({M, F, Reason}),
send(Args, 500);
{false, ResponsePayload} ->
encode_send(Args, 200, ResponsePayload, [],ID);
{true, _NewTimeout, _NewState, ResponsePayload} ->
encode_send(Args, 200, ResponsePayload, [],ID)
end. % }}}
XXX compatibility with XMLRPC handlers
%%% XXX - potential bug here?
encode_send(Args, StatusCode, [Payload], AddOn, ID) -> % {{{
encode_send(Args, StatusCode, Payload, AddOn, ID); % }}}
encode_send(Args, StatusCode, Payload, AddOn, ID) -> % {{{
{ok, EncodedPayload} = encode_handler_payload(Payload, ID),
send(Args, StatusCode, EncodedPayload, AddOn).
send(Args, StatusCode) -> send(Args, StatusCode, "", []). % {{{
send(Args, StatusCode, Payload, AddOnData) when not is_list(AddOnData) ->
send(Args, StatusCode, Payload, [AddOnData]);
send(_Args, StatusCode, Payload, AddOnData) ->
A = [
{status, StatusCode},
{content, "text/xml", Payload},
{header, {content_length, lists:flatlength(Payload) }}
] ++ AddOnData,
A
. % }}}
encode_handler_payload({response, [ErlStruct]},ID) -> % {{{
encode_handler_payload({response, ErlStruct}, ID);
encode_handler_payload({response, ErlStruct},ID) ->
StructStr = json:encode({struct, [ {result, ErlStruct}, {id, ID}]}),
{ok, StructStr}. % }}}
decode_handler_payload(JSonStr) -> %{{{
try
{ok, JSON} = json:decode_string(JSonStr),
Method = list_to_atom(jsonrpc:s(JSON, method)),
{array, Args} = jsonrpc:s(JSON, params),
ID = jsonrpc:s(JSON, id),
{ok, {call, Method, Args}, ID}
catch
error:Err -> {error, Err}
end.%}}}
% vim: tabstop=4 ft=erlang
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/scalaris/contrib/yaws/src/yaws_jsonrpc.erl | erlang | All rights reserved.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-include("../../yaws/src/yaws_debug.hrl").
public interface
allow overriding session Cookie name
go to generic handler
xmlrpc:handler compatible call
no session support will be available
private functions
we should be called from yaws page or module
{{{
cannot parse request
}}}
check that request come in reasonable protocol version and reasonable method
{{{
?Debug("HTTP Version 1.0~n", []),
}}}
{{{
}}}
call handler/3 and provide session support
{{{
have no session started, just call handler
get old session data
cannot get corresponding session
do not have updates in session data
be compatible with xmlrpc module
nothing to do
rpc handler requested session delete
XXX: may be return set-cookie with empty val?
any other value will stored in session
got session data and should start new session now
nothing to add to yaws data
}}}
call handler/2 without session support
{{{
}}}
XXX - potential bug here?
{{{
}}}
{{{
{{{
}}}
{{{
}}}
{{{
}}}
vim: tabstop=4 ft=erlang | Copyright ( C ) 2003 < > .
Copyright ( C ) 2006 < >
< >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
-module(yaws_jsonrpc).
-author("Gaspar Chilingarov <>, Gurgen Tumanyan <>").
-export([handler/2]).
-export([handler_session/2, handler_session/3]).
-define(debug , 1 ) .
-include("../include/yaws_api.hrl").
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
use jsonrpc handler which can automagically start sessions if we need
handler_session(Args, Handler) ->
handler_session(Args, Handler, 'SID').
handler_session(Args, Handler, SID_NAME) when is_atom(SID_NAME) ->
handler_session(Args, Handler, atom_to_list(SID_NAME));
handler_session(Args, Handler, SID_NAME) ->
handler(Args, Handler) ->
handler(Args, Handler, simple).
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
case parse_request(Args) of
ok ->
handle_payload(Args, Handler, Type);
send(Args, StatusCode)
-define(ERROR_LOG(Reason),
error_logger:error_report({?MODULE, ?LINE, Reason})).
case {(Args#arg.req)#http_request.method, (Args#arg.req)#http_request.version} of
{'POST', {1,0}} ->
ok;
{'POST', {1,1}} ->
? Debug("HTTP Version 1.1 ~ n " , [ ] ) ,
ok;
{'POST', _HTTPVersion} -> {status, 505};
{_Method, {1,1}} -> {status, 501};
_ -> {status, 400}
Payload = binary_to_list(Args#arg.clidata),
? plaintext call ~p ~n " , [ Payload ] ) ,
case decode_handler_payload(Payload) of
{ok, DecodedPayload, ID} ->
? Debug("json2erl decoded call ~p ~n " , [ DecodedPayload ] ) ,
eval_payload(Args, Handler, DecodedPayload, Type, ID);
{error, Reason} ->
?ERROR_LOG({html, json2erl, Payload, Reason}),
send(Args, 400)
{SessionValue, Cookie} = case yaws_api:find_cookie_val(CookieName, (Args#arg.headers)#headers.cookie) of
{undefined, undefined};
case yaws_api:cookieval_to_opaque(Cookie2) of
{ok, OP} ->
yaws_api:cookieval_to_opaque(Cookie2),
{OP, Cookie2};
{undefined, undefined}
end
end,
case catch M:F(Args#arg.state, Payload, SessionValue) of
{'EXIT', Reason} ->
?ERROR_LOG({M, F, {'EXIT', Reason}}),
send(Args, 500);
{error, Reason} ->
?ERROR_LOG({M, F, Reason}),
send(Args, 500);
{false, ResponsePayload} ->
encode_send(Args, 200, ResponsePayload, [], ID);
CO = case NewSessionValue of
case SessionValue of
Cookie1 = yaws_api:new_cookie_session(NewSessionValue),
return set_cookie header
_ ->
yaws_api:replace_cookie_session(Cookie, NewSessionValue),
end
end,
encode_send(Args, 200, ResponsePayload, CO, ID)
case catch M:F(Args#arg.state, Payload) of
{'EXIT', Reason} ->
?ERROR_LOG({M, F, {'EXIT', Reason}}),
send(Args, 500);
{error, Reason} ->
?ERROR_LOG({M, F, Reason}),
send(Args, 500);
{false, ResponsePayload} ->
encode_send(Args, 200, ResponsePayload, [],ID);
{true, _NewTimeout, _NewState, ResponsePayload} ->
encode_send(Args, 200, ResponsePayload, [],ID)
XXX compatibility with XMLRPC handlers
{ok, EncodedPayload} = encode_handler_payload(Payload, ID),
send(Args, StatusCode, EncodedPayload, AddOn).
send(Args, StatusCode, Payload, AddOnData) when not is_list(AddOnData) ->
send(Args, StatusCode, Payload, [AddOnData]);
send(_Args, StatusCode, Payload, AddOnData) ->
A = [
{status, StatusCode},
{content, "text/xml", Payload},
{header, {content_length, lists:flatlength(Payload) }}
] ++ AddOnData,
A
encode_handler_payload({response, ErlStruct}, ID);
encode_handler_payload({response, ErlStruct},ID) ->
StructStr = json:encode({struct, [ {result, ErlStruct}, {id, ID}]}),
try
{ok, JSON} = json:decode_string(JSonStr),
Method = list_to_atom(jsonrpc:s(JSON, method)),
{array, Args} = jsonrpc:s(JSON, params),
ID = jsonrpc:s(JSON, id),
{ok, {call, Method, Args}, ID}
catch
error:Err -> {error, Err}
|
2ee5499d755fcf578ba309c8a80b7979fb2adb48b02a19eb3fc4177a19080eb0 | chicken-mobile/chicken-sdl2-android-builder | general.scm | ;;
chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2
;;
Copyright © 2013 , 2015 - 2016 .
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR FOR ANY DIRECT ,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; GENERAL
(define-foreign-constants int
SDL_ENABLE
SDL_DISABLE
SDL_QUERY
SDL_IGNORE
SDL_BYTEORDER
SDL_BIG_ENDIAN
SDL_LIL_ENDIAN)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
INIT / SUBSYSTEMS
(export init-flag->symbol
symbol->init-flag
pack-init-flags
unpack-init-flags)
(define-enum-mappings
type: Uint32
value->symbol: init-flag->symbol
symbol->value: symbol->init-flag
((SDL_INIT_TIMER timer)
(SDL_INIT_AUDIO audio)
(SDL_INIT_VIDEO video)
(SDL_INIT_JOYSTICK joystick)
(SDL_INIT_HAPTIC haptic)
(SDL_INIT_GAMECONTROLLER game-controller)
(SDL_INIT_EVENTS events)
(SDL_INIT_EVERYTHING everything)))
(define-enum-mask-packer pack-init-flags
symbol->init-flag)
(define-enum-mask-unpacker unpack-init-flags
init-flag->symbol
(list SDL_INIT_TIMER
SDL_INIT_AUDIO
SDL_INIT_VIDEO
SDL_INIT_JOYSTICK
SDL_INIT_HAPTIC
SDL_INIT_GAMECONTROLLER
SDL_INIT_EVENTS
SDL_INIT_EVERYTHING))
| null | https://raw.githubusercontent.com/chicken-mobile/chicken-sdl2-android-builder/90ef1f0ff667737736f1932e204d29ae615a00c4/eggs/sdl2/lib/sdl2-internals/enums/general.scm | scheme |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
GENERAL
| chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2
Copyright © 2013 , 2015 - 2016 .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT HOLDER OR FOR ANY DIRECT ,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
(define-foreign-constants int
SDL_ENABLE
SDL_DISABLE
SDL_QUERY
SDL_IGNORE
SDL_BYTEORDER
SDL_BIG_ENDIAN
SDL_LIL_ENDIAN)
INIT / SUBSYSTEMS
(export init-flag->symbol
symbol->init-flag
pack-init-flags
unpack-init-flags)
(define-enum-mappings
type: Uint32
value->symbol: init-flag->symbol
symbol->value: symbol->init-flag
((SDL_INIT_TIMER timer)
(SDL_INIT_AUDIO audio)
(SDL_INIT_VIDEO video)
(SDL_INIT_JOYSTICK joystick)
(SDL_INIT_HAPTIC haptic)
(SDL_INIT_GAMECONTROLLER game-controller)
(SDL_INIT_EVENTS events)
(SDL_INIT_EVERYTHING everything)))
(define-enum-mask-packer pack-init-flags
symbol->init-flag)
(define-enum-mask-unpacker unpack-init-flags
init-flag->symbol
(list SDL_INIT_TIMER
SDL_INIT_AUDIO
SDL_INIT_VIDEO
SDL_INIT_JOYSTICK
SDL_INIT_HAPTIC
SDL_INIT_GAMECONTROLLER
SDL_INIT_EVENTS
SDL_INIT_EVERYTHING))
|
00db9e3279b4963ddce9e5914ab97d36ec4436518af6f57f0557cae43fb15042 | nedap/speced.def | pre_post.cljc | (ns unit.nedap.speced.def.defn.pre-post
"This ns duplicates `unit.nedap.speced.def.defn`, but adding a 'manual' :pre/:post map to each example defn.
That way the tests can remain comprehensible."
(:require
#?(:clj [clojure.spec.alpha :as spec] :cljs [cljs.spec.alpha :as spec])
#?(:clj [clojure.test :refer [deftest testing are is use-fixtures]] :cljs [cljs.test :refer-macros [deftest testing is are] :refer [use-fixtures]])
[nedap.speced.def :as sut]
[unit.nedap.test-helpers :refer [every-and-at-least-one?]]))
(do
#?@(:clj
[(spec/def ::age pos?)
(spec/def ::temperature double?)
(spec/def ::name (spec/and string? (fn [x]
(-> x count (< 10)))))
(defn present? [x]
(some? x))
(spec/def ::present? present?)
(doseq [[k v] {:no-metadata '(sut/defn no-metadata [x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
:no-metadata-n '(sut/defn no-metadata-n
([x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
([x y]
{:pre [:pre]
:post [:post]}
(-> x (* y) str)))
:concise-metadata '(sut/defn ^::present?
concise-metadata
^::name
[^::age x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
:concise-metadata-n '(sut/defn ^::present?
concise-metadata-n
(^::name
[^::age x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
(^::name
[^::age x ^::temperature y]
{:pre [:pre]
:post [:post]}
(-> x (* y) str)))
:explicit-metadata '(sut/defn ^{::sut/spec ::present?}
explicit-metadata
^{::sut/spec ::name}
[^{::sut/spec ::age} x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
:explicit-metadata-n '(sut/defn ^{::sut/spec ::present?}
explicit-metadata-n
(^{::sut/spec ::name}
[^{::sut/spec ::age} x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
(^{::sut/spec ::name}
[^{::sut/spec ::age} x
^{::sut/spec ::temperature} y]
{:pre [:pre]
:post [:post]}
(-> x (* y) str)))
:type-hinted-metadata '(sut/defn
type-hinted-metadata
^String
[^Double x]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* x) str)))
:type-hinted-metadata-n '(sut/defn
type-hinted-metadata-n
(^String [^Double x]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* x) str)))
(^String [^Double x ^Double y]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* y) str))))
:inline-function '(sut/defn ^present?
inline-function
^string?
[^double? x]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* x) str)))
:inline-function-n '(sut/defn ^present?
inline-function-n
(^string? [^double? x]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* x) str)))
(^string? [^double? x ^double? y]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* y) str))))}]
(eval v)
(eval `(def ~(-> k
name
(str "-macroexpansion")
symbol)
~(list 'quote (macroexpand v)))))
(deftest macroexpansion
(testing "It macroexpands to known-good (and evidently-good) forms"
(are [x y] (= x y)
no-metadata-macroexpansion '(def no-metadata (clojure.core/fn ([x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))))
no-metadata-n-macroexpansion '(def no-metadata-n
(clojure.core/fn
([x]
{:pre [:pre], :post [:post]}
(-> x (* x) str))
([x y]
{:pre [:pre], :post [:post]}
(-> x (* y) str))))
concise-metadata-macroexpansion '(def concise-metadata
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* x) str))))
concise-metadata-n-macroexpansion '(def concise-metadata-n
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* x) str))
([x y]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x
:unit.nedap.speced.def.defn.pre-post/temperature y)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* y) str))))
explicit-metadata-macroexpansion '(def explicit-metadata
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* x) str))))
explicit-metadata-n-macroexpansion '(def explicit-metadata-n
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* x) str))
([x y]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x
:unit.nedap.speced.def.defn.pre-post/temperature y)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* y) str))))
type-hinted-metadata-macroexpansion '(def type-hinted-metadata
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! (fn [x]
(if (clojure.core/class? Double)
(clojure.core/instance? Double x)
(clojure.core/satisfies? Double x)))
x)],
:post
[:post
(nedap.utils.spec.api/check! (fn [x]
(if (clojure.core/class? String)
(clojure.core/instance? String x)
(clojure.core/satisfies? String x)))
%)]}
(when (< 0 x 100)
(-> x (* x) str)))))
type-hinted-metadata-n-macroexpansion '(def type-hinted-metadata-n
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check!
(fn [x]
(if (clojure.core/class? Double)
(clojure.core/instance? Double x)
(clojure.core/satisfies? Double x)))
x)],
:post
[:post
(nedap.utils.spec.api/check!
(fn [x]
(if (clojure.core/class? String)
(clojure.core/instance? String x)
(clojure.core/satisfies? String x)))
%)]}
(when (< 0 x 100)
(-> x (* x) str)))
([x y]
{:pre
[:pre
(nedap.utils.spec.api/check!
(fn [x]
(if (clojure.core/class? Double)
(clojure.core/instance? Double x)
(clojure.core/satisfies? Double x)))
x
(fn [x]
(if (clojure.core/class? Double)
(clojure.core/instance? Double x)
(clojure.core/satisfies? Double x)))
y)],
:post
[:post
(nedap.utils.spec.api/check!
(fn [x]
(if (clojure.core/class? String)
(clojure.core/instance? String x)
(clojure.core/satisfies? String x)))
%)]}
(when (< 0 x 100)
(-> x (* y) str)))))
inline-function-macroexpansion '(def inline-function
(clojure.core/fn
([x]
{:pre [:pre
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
double?
(fn [x]
(if (clojure.core/class? java.lang.Double)
(clojure.core/instance? java.lang.Double x)
(clojure.core/satisfies? java.lang.Double x))))
x)],
:post
[:post
(nedap.utils.spec.api/check! present? %)
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
string?
(fn [x]
(if (clojure.core/class? java.lang.String)
(clojure.core/instance? java.lang.String x)
(clojure.core/satisfies? java.lang.String x))))
%)]}
(when (< 0 x 100)
(-> x (* x) str)))))
inline-function-n-macroexpansion '(def
inline-function-n
(clojure.core/fn
([x]
{:pre [:pre
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
double?
(fn [x]
(if (clojure.core/class? java.lang.Double)
(clojure.core/instance? java.lang.Double x)
(clojure.core/satisfies? java.lang.Double x))))
x)],
:post
[:post
(nedap.utils.spec.api/check! present? %)
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
string?
(fn [x]
(if (clojure.core/class? java.lang.String)
(clojure.core/instance? java.lang.String x)
(clojure.core/satisfies? java.lang.String x))))
%)]}
(when (< 0 x 100)
(-> x (* x) str)))
([x y]
{:pre [:pre
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
double?
(fn [x]
(if (clojure.core/class? java.lang.Double)
(clojure.core/instance? java.lang.Double x)
(clojure.core/satisfies? java.lang.Double x))))
x
(clojure.spec.alpha/and
double?
(fn [x]
(if (clojure.core/class? java.lang.Double)
(clojure.core/instance? java.lang.Double x)
(clojure.core/satisfies? java.lang.Double x))))
y)],
:post
[:post
(nedap.utils.spec.api/check! present? %)
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
string?
(fn [x]
(if (clojure.core/class? java.lang.String)
(clojure.core/instance? java.lang.String x)
(clojure.core/satisfies? java.lang.String x))))
%)]}
(when (< 0 x 100)
(-> x (* y) str))))))))
(deftest correct-execution
(testing "Arity 1"
(are [f] (testing f
(= "64.0" (f 8.0)))
no-metadata
no-metadata-n
concise-metadata
concise-metadata-n
explicit-metadata
explicit-metadata-n
type-hinted-metadata
type-hinted-metadata-n
inline-function
inline-function-n))
(testing "Arity 2"
(are [f] (testing f
(= "16.0" (f 8.0 2.0)))
no-metadata-n
concise-metadata-n
explicit-metadata-n
type-hinted-metadata-n
inline-function-n)))
(deftest preconditions-are-checked
(testing "Arity 1"
(with-out-str
(let [arg 0]
(are [expectation f] (testing f
(case expectation
:not-thrown (= "0" (f arg))
:thrown (try
(f arg)
false
(catch #?(:clj Exception :cljs js/Error) e
(-> e ex-data :spec)))))
:not-thrown no-metadata
:not-thrown no-metadata-n
:thrown concise-metadata
:thrown concise-metadata-n
:thrown explicit-metadata
:thrown explicit-metadata-n
:thrown type-hinted-metadata
:thrown type-hinted-metadata-n
:thrown inline-function
:thrown inline-function-n))))
(testing "Arity 2"
(with-out-str
(let [arg 0]
(are [expectation f] (testing f
(case expectation
:not-thrown (= "0" (f arg))
:thrown (try
(f arg 1)
false
(catch #?(:clj Exception :cljs js/Error) e
(-> e ex-data :spec)))))
:not-thrown no-metadata-n
:thrown concise-metadata-n
:thrown explicit-metadata-n
:thrown type-hinted-metadata-n
:thrown inline-function-n)))))
(deftest postconditions-are-checked
(testing "Arity 1"
(with-out-str
(let [arg 99999]
(are [expectation f] (testing f
(case expectation
:not-thrown (= "9999800001" (f arg))
:thrown (try
(f arg)
false
(catch #?(:clj Exception :cljs js/Error) e
(-> e ex-data :spec)))))
:not-thrown no-metadata
:not-thrown no-metadata-n
:thrown concise-metadata
:thrown concise-metadata-n
:thrown explicit-metadata
:thrown explicit-metadata-n
:thrown type-hinted-metadata
:thrown type-hinted-metadata-n
:thrown inline-function
:thrown inline-function-n))))
(testing "Arity 2"
(with-out-str
(let [arg1 99999
arg2 100000]
(are [expectation f] (testing f
(case expectation
:not-thrown (= "9999900000" (f arg1 arg2))
:thrown (try
(f arg1 arg2)
false
(catch #?(:clj Exception :cljs js/Error) e
(-> e ex-data :spec)))))
:not-thrown no-metadata-n
:thrown concise-metadata-n
:thrown explicit-metadata-n
:thrown type-hinted-metadata-n
:thrown inline-function-n)))))
(deftest type-hint-emission
(testing "Type hints are preserved or emitted"
(testing "Return value hinting for single-arity functions"
(are [v] (testing v
(-> v meta :tag #{String}))
#'type-hinted-metadata
#'type-hinted-metadata-n
#'inline-function
#'inline-function-n))
(testing "Arglist hinting for single-arity functions"
(are [v] (testing v
(-> v meta :arglists first meta :tag #{String}))
#'type-hinted-metadata
#'inline-function))
(testing "Arglist hinting for single-arity functions"
(are [v] (testing v
(-> v meta :arglists ffirst meta :tag #{`Double}))
#'type-hinted-metadata
#'inline-function))
(testing "Return value hinting for multi-arity functions"
(are [v] (testing v
(->> v
meta
:arglists
(map meta)
(map :tag)
(every-and-at-least-one? #{String})))
#'type-hinted-metadata-n
#'inline-function-n))
(testing "Arguments hinting for multi-arity functions"
(are [v] (testing v
(->> v
meta
:arglists
(map (fn [arglist]
(->> arglist
(map meta)
(map :tag)
(every-and-at-least-one? #{`Double}))))
(every-and-at-least-one? true?)))
#'type-hinted-metadata-n
#'inline-function-n))))]))
| null | https://raw.githubusercontent.com/nedap/speced.def/55053e53e749f77753294f3ee8d4639470840f8c/test/unit/nedap/speced/def/defn/pre_post.cljc | clojure | (ns unit.nedap.speced.def.defn.pre-post
"This ns duplicates `unit.nedap.speced.def.defn`, but adding a 'manual' :pre/:post map to each example defn.
That way the tests can remain comprehensible."
(:require
#?(:clj [clojure.spec.alpha :as spec] :cljs [cljs.spec.alpha :as spec])
#?(:clj [clojure.test :refer [deftest testing are is use-fixtures]] :cljs [cljs.test :refer-macros [deftest testing is are] :refer [use-fixtures]])
[nedap.speced.def :as sut]
[unit.nedap.test-helpers :refer [every-and-at-least-one?]]))
(do
#?@(:clj
[(spec/def ::age pos?)
(spec/def ::temperature double?)
(spec/def ::name (spec/and string? (fn [x]
(-> x count (< 10)))))
(defn present? [x]
(some? x))
(spec/def ::present? present?)
(doseq [[k v] {:no-metadata '(sut/defn no-metadata [x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
:no-metadata-n '(sut/defn no-metadata-n
([x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
([x y]
{:pre [:pre]
:post [:post]}
(-> x (* y) str)))
:concise-metadata '(sut/defn ^::present?
concise-metadata
^::name
[^::age x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
:concise-metadata-n '(sut/defn ^::present?
concise-metadata-n
(^::name
[^::age x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
(^::name
[^::age x ^::temperature y]
{:pre [:pre]
:post [:post]}
(-> x (* y) str)))
:explicit-metadata '(sut/defn ^{::sut/spec ::present?}
explicit-metadata
^{::sut/spec ::name}
[^{::sut/spec ::age} x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
:explicit-metadata-n '(sut/defn ^{::sut/spec ::present?}
explicit-metadata-n
(^{::sut/spec ::name}
[^{::sut/spec ::age} x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))
(^{::sut/spec ::name}
[^{::sut/spec ::age} x
^{::sut/spec ::temperature} y]
{:pre [:pre]
:post [:post]}
(-> x (* y) str)))
:type-hinted-metadata '(sut/defn
type-hinted-metadata
^String
[^Double x]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* x) str)))
:type-hinted-metadata-n '(sut/defn
type-hinted-metadata-n
(^String [^Double x]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* x) str)))
(^String [^Double x ^Double y]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* y) str))))
:inline-function '(sut/defn ^present?
inline-function
^string?
[^double? x]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* x) str)))
:inline-function-n '(sut/defn ^present?
inline-function-n
(^string? [^double? x]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* x) str)))
(^string? [^double? x ^double? y]
{:pre [:pre]
:post [:post]}
(when (< 0 x 100)
(-> x (* y) str))))}]
(eval v)
(eval `(def ~(-> k
name
(str "-macroexpansion")
symbol)
~(list 'quote (macroexpand v)))))
(deftest macroexpansion
(testing "It macroexpands to known-good (and evidently-good) forms"
(are [x y] (= x y)
no-metadata-macroexpansion '(def no-metadata (clojure.core/fn ([x]
{:pre [:pre]
:post [:post]}
(-> x (* x) str))))
no-metadata-n-macroexpansion '(def no-metadata-n
(clojure.core/fn
([x]
{:pre [:pre], :post [:post]}
(-> x (* x) str))
([x y]
{:pre [:pre], :post [:post]}
(-> x (* y) str))))
concise-metadata-macroexpansion '(def concise-metadata
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* x) str))))
concise-metadata-n-macroexpansion '(def concise-metadata-n
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* x) str))
([x y]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x
:unit.nedap.speced.def.defn.pre-post/temperature y)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* y) str))))
explicit-metadata-macroexpansion '(def explicit-metadata
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* x) str))))
explicit-metadata-n-macroexpansion '(def explicit-metadata-n
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* x) str))
([x y]
{:pre
[:pre
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/age x
:unit.nedap.speced.def.defn.pre-post/temperature y)],
:post
[:post
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/present? %)
(nedap.utils.spec.api/check! :unit.nedap.speced.def.defn.pre-post/name %)]}
(-> x (* y) str))))
type-hinted-metadata-macroexpansion '(def type-hinted-metadata
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check! (fn [x]
(if (clojure.core/class? Double)
(clojure.core/instance? Double x)
(clojure.core/satisfies? Double x)))
x)],
:post
[:post
(nedap.utils.spec.api/check! (fn [x]
(if (clojure.core/class? String)
(clojure.core/instance? String x)
(clojure.core/satisfies? String x)))
%)]}
(when (< 0 x 100)
(-> x (* x) str)))))
type-hinted-metadata-n-macroexpansion '(def type-hinted-metadata-n
(clojure.core/fn
([x]
{:pre
[:pre
(nedap.utils.spec.api/check!
(fn [x]
(if (clojure.core/class? Double)
(clojure.core/instance? Double x)
(clojure.core/satisfies? Double x)))
x)],
:post
[:post
(nedap.utils.spec.api/check!
(fn [x]
(if (clojure.core/class? String)
(clojure.core/instance? String x)
(clojure.core/satisfies? String x)))
%)]}
(when (< 0 x 100)
(-> x (* x) str)))
([x y]
{:pre
[:pre
(nedap.utils.spec.api/check!
(fn [x]
(if (clojure.core/class? Double)
(clojure.core/instance? Double x)
(clojure.core/satisfies? Double x)))
x
(fn [x]
(if (clojure.core/class? Double)
(clojure.core/instance? Double x)
(clojure.core/satisfies? Double x)))
y)],
:post
[:post
(nedap.utils.spec.api/check!
(fn [x]
(if (clojure.core/class? String)
(clojure.core/instance? String x)
(clojure.core/satisfies? String x)))
%)]}
(when (< 0 x 100)
(-> x (* y) str)))))
inline-function-macroexpansion '(def inline-function
(clojure.core/fn
([x]
{:pre [:pre
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
double?
(fn [x]
(if (clojure.core/class? java.lang.Double)
(clojure.core/instance? java.lang.Double x)
(clojure.core/satisfies? java.lang.Double x))))
x)],
:post
[:post
(nedap.utils.spec.api/check! present? %)
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
string?
(fn [x]
(if (clojure.core/class? java.lang.String)
(clojure.core/instance? java.lang.String x)
(clojure.core/satisfies? java.lang.String x))))
%)]}
(when (< 0 x 100)
(-> x (* x) str)))))
inline-function-n-macroexpansion '(def
inline-function-n
(clojure.core/fn
([x]
{:pre [:pre
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
double?
(fn [x]
(if (clojure.core/class? java.lang.Double)
(clojure.core/instance? java.lang.Double x)
(clojure.core/satisfies? java.lang.Double x))))
x)],
:post
[:post
(nedap.utils.spec.api/check! present? %)
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
string?
(fn [x]
(if (clojure.core/class? java.lang.String)
(clojure.core/instance? java.lang.String x)
(clojure.core/satisfies? java.lang.String x))))
%)]}
(when (< 0 x 100)
(-> x (* x) str)))
([x y]
{:pre [:pre
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
double?
(fn [x]
(if (clojure.core/class? java.lang.Double)
(clojure.core/instance? java.lang.Double x)
(clojure.core/satisfies? java.lang.Double x))))
x
(clojure.spec.alpha/and
double?
(fn [x]
(if (clojure.core/class? java.lang.Double)
(clojure.core/instance? java.lang.Double x)
(clojure.core/satisfies? java.lang.Double x))))
y)],
:post
[:post
(nedap.utils.spec.api/check! present? %)
(nedap.utils.spec.api/check!
(clojure.spec.alpha/and
string?
(fn [x]
(if (clojure.core/class? java.lang.String)
(clojure.core/instance? java.lang.String x)
(clojure.core/satisfies? java.lang.String x))))
%)]}
(when (< 0 x 100)
(-> x (* y) str))))))))
(deftest correct-execution
(testing "Arity 1"
(are [f] (testing f
(= "64.0" (f 8.0)))
no-metadata
no-metadata-n
concise-metadata
concise-metadata-n
explicit-metadata
explicit-metadata-n
type-hinted-metadata
type-hinted-metadata-n
inline-function
inline-function-n))
(testing "Arity 2"
(are [f] (testing f
(= "16.0" (f 8.0 2.0)))
no-metadata-n
concise-metadata-n
explicit-metadata-n
type-hinted-metadata-n
inline-function-n)))
(deftest preconditions-are-checked
(testing "Arity 1"
(with-out-str
(let [arg 0]
(are [expectation f] (testing f
(case expectation
:not-thrown (= "0" (f arg))
:thrown (try
(f arg)
false
(catch #?(:clj Exception :cljs js/Error) e
(-> e ex-data :spec)))))
:not-thrown no-metadata
:not-thrown no-metadata-n
:thrown concise-metadata
:thrown concise-metadata-n
:thrown explicit-metadata
:thrown explicit-metadata-n
:thrown type-hinted-metadata
:thrown type-hinted-metadata-n
:thrown inline-function
:thrown inline-function-n))))
(testing "Arity 2"
(with-out-str
(let [arg 0]
(are [expectation f] (testing f
(case expectation
:not-thrown (= "0" (f arg))
:thrown (try
(f arg 1)
false
(catch #?(:clj Exception :cljs js/Error) e
(-> e ex-data :spec)))))
:not-thrown no-metadata-n
:thrown concise-metadata-n
:thrown explicit-metadata-n
:thrown type-hinted-metadata-n
:thrown inline-function-n)))))
(deftest postconditions-are-checked
(testing "Arity 1"
(with-out-str
(let [arg 99999]
(are [expectation f] (testing f
(case expectation
:not-thrown (= "9999800001" (f arg))
:thrown (try
(f arg)
false
(catch #?(:clj Exception :cljs js/Error) e
(-> e ex-data :spec)))))
:not-thrown no-metadata
:not-thrown no-metadata-n
:thrown concise-metadata
:thrown concise-metadata-n
:thrown explicit-metadata
:thrown explicit-metadata-n
:thrown type-hinted-metadata
:thrown type-hinted-metadata-n
:thrown inline-function
:thrown inline-function-n))))
(testing "Arity 2"
(with-out-str
(let [arg1 99999
arg2 100000]
(are [expectation f] (testing f
(case expectation
:not-thrown (= "9999900000" (f arg1 arg2))
:thrown (try
(f arg1 arg2)
false
(catch #?(:clj Exception :cljs js/Error) e
(-> e ex-data :spec)))))
:not-thrown no-metadata-n
:thrown concise-metadata-n
:thrown explicit-metadata-n
:thrown type-hinted-metadata-n
:thrown inline-function-n)))))
(deftest type-hint-emission
(testing "Type hints are preserved or emitted"
(testing "Return value hinting for single-arity functions"
(are [v] (testing v
(-> v meta :tag #{String}))
#'type-hinted-metadata
#'type-hinted-metadata-n
#'inline-function
#'inline-function-n))
(testing "Arglist hinting for single-arity functions"
(are [v] (testing v
(-> v meta :arglists first meta :tag #{String}))
#'type-hinted-metadata
#'inline-function))
(testing "Arglist hinting for single-arity functions"
(are [v] (testing v
(-> v meta :arglists ffirst meta :tag #{`Double}))
#'type-hinted-metadata
#'inline-function))
(testing "Return value hinting for multi-arity functions"
(are [v] (testing v
(->> v
meta
:arglists
(map meta)
(map :tag)
(every-and-at-least-one? #{String})))
#'type-hinted-metadata-n
#'inline-function-n))
(testing "Arguments hinting for multi-arity functions"
(are [v] (testing v
(->> v
meta
:arglists
(map (fn [arglist]
(->> arglist
(map meta)
(map :tag)
(every-and-at-least-one? #{`Double}))))
(every-and-at-least-one? true?)))
#'type-hinted-metadata-n
#'inline-function-n))))]))
| |
6dfab05f076145cedbc015b541407c713ac981bcf70a86bc5e65b56c3bd8fa04 | KULeuven-CS/CPL | 2.9.rkt | #lang eopl
(require rackunit)
(define empty-env
(lambda () '()))
(define extend-env
(lambda(var val env)
(cons (cons var val) env)))
Exercise 2.9
(define has-binding?
(lambda (env search-var)
(if (empty-env? env)
#f
(if (equal? (caar env) search-var)
#t
(has-binding? (cdr env) search-var)))))
(check-equal? (has-binding? (extend-env 'a 'b (empty-env)) 'a) #t)
(check-equal? (has-binding? (extend-env 'c 'd (extend-env 'a 'b (empty-env))) 'a) #t)
(check-equal? (has-binding? (extend-env 'a 'b (empty-env)) 'x) #f)
(check-equal? (has-binding? (extend-env 'c 'd (extend-env 'a 'b (empty-env))) 'x) #f)
| null | https://raw.githubusercontent.com/KULeuven-CS/CPL/0c62cca832edc43218ac63c4e8233e3c3f05d20a/chapter2/2.9.rkt | racket | #lang eopl
(require rackunit)
(define empty-env
(lambda () '()))
(define extend-env
(lambda(var val env)
(cons (cons var val) env)))
Exercise 2.9
(define has-binding?
(lambda (env search-var)
(if (empty-env? env)
#f
(if (equal? (caar env) search-var)
#t
(has-binding? (cdr env) search-var)))))
(check-equal? (has-binding? (extend-env 'a 'b (empty-env)) 'a) #t)
(check-equal? (has-binding? (extend-env 'c 'd (extend-env 'a 'b (empty-env))) 'a) #t)
(check-equal? (has-binding? (extend-env 'a 'b (empty-env)) 'x) #f)
(check-equal? (has-binding? (extend-env 'c 'd (extend-env 'a 'b (empty-env))) 'x) #f)
| |
471de7563087f7945b57dd688954f6be2c5ec20ad8797edd95b0b335a35c60f2 | dnsimple/erldns-metrics | erldns_metrics_app.erl | %% Copyright (c) DNSimple Corporation
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@doc The erldns OTP application .
-module(erldns_metrics_app).
-behavior(application).
% Application hooks
-export([start/2, stop/1]).
start(_Type, _Args) ->
lager:debug("Starting erldns_metrics application"),
erldns_metrics_sup:start_link().
stop(_State) ->
lager:info("Stop erldns_metrics application"),
ok.
| null | https://raw.githubusercontent.com/dnsimple/erldns-metrics/5985cbc76f2dd3a2c3608f3d36a930cf59bd5d92/src/erldns_metrics_app.erl | erlang | Copyright (c) DNSimple Corporation
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Application hooks | THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
@doc The erldns OTP application .
-module(erldns_metrics_app).
-behavior(application).
-export([start/2, stop/1]).
start(_Type, _Args) ->
lager:debug("Starting erldns_metrics application"),
erldns_metrics_sup:start_link().
stop(_State) ->
lager:info("Stop erldns_metrics application"),
ok.
|
2013a6d2bbb027e90654ab9efc5f46eed68d543030ff8cbecf19574d930ec56a | evolutics/haskell-formatter | Output.hs | predecessor = predecessor
-- |comment before
successor :: a
successor = successor
| null | https://raw.githubusercontent.com/evolutics/haskell-formatter/3919428e312db62b305de4dd1c84887e6cfa9478/testsuite/resources/source/comments/depends_on_displacement/single_annotation/single_line/before/Output.hs | haskell | |comment before | predecessor = predecessor
successor :: a
successor = successor
|
2a995cc859b465fd37ef70b5b8d76a4b55616b4626b89c940a323e5b5db04641 | Vaguery/klapaucius | to_tagspace_test.clj | (ns push.instructions.standard.to_tagspace_test
(:require [push.interpreter.core :as i]
[push.type.core :as t])
(:use midje.sweet)
(:use [push.util.test-helpers])
(:use [push.instructions.aspects])
(:use [push.type.definitions.tagspace])
(:use push.type.item.tagspace)
(:use push.instructions.aspects.to-tagspace)
)
(let
[foo-type (t/make-type :foo)
fixed-foo (t/attach-instruction foo-type (to-tagspace foo-type))]
(tabular
(fact "`:foo->tagspace` pops a :foo and two :scalar values, and makes a new :tagspace"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks fixed-foo ?instruction) => (contains ?expected))
?new-stacks ?instruction ?expected
{:foo '([1 2 3 4 5])
:scalar '(7 2)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{2 1, 13/4 2, 9/2 3, 23/4 4, 7 5}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '([1 2 3 4 5])
:scalar '(2 7)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{7 1, 13/4 4, 9/2 3, 23/4 2, 2 5}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '([1 2 3 4 5])
:scalar '(7 8)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{8 1, 29/4 4, 15/2 3, 31/4 2, 7 5}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '([1 2 3 4 5])
:scalar '(8 8)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace {8 5}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '([1 2 3 4 5])
:scalar '(10.5 5/2)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace {5/2 1, 4.5 2, 6.5 3, 8.5 4, 10.5 5}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '("hello")
:scalar '(1.25 2.5)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{1.25 \o, 1.5625 \l, 1.875 \l, 2.1875 \e, 2.5 \h}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '("")
:scalar '(2.0 8.0)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '("live")
:scalar '(-1.5 9.0)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{-1.5 \e, 2.0 \v, 5.5 \i, 9.0 \l}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '("fire")
:scalar '(10.25 7.25)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{7.25 \f, 8.25 \i, 9.25 \r, 10.25 \e}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:foo '("fire")
:scalar '(10.25 10.25)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{10.25 \e}))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
))
(let
[foo-type (t/make-type :foo)
fixed-foo (t/attach-instruction foo-type (to-tagspace foo-type))]
(tabular
(fact "`:foo->tagspace` consumes arguments but reports runtime errors if they occur"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks fixed-foo ?instruction) => (contains ?expected))
?new-stacks ?instruction ?expected
{:foo '([1 2 3 4 5])
:scalar '(7M 2/3)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list (make-tagspace))
:error '({:item "Non-terminating decimal expansion; no exact representable decimal result.", :step 0})}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
))
| null | https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/test/push/instructions/standard/to_tagspace_test.clj | clojure | (ns push.instructions.standard.to_tagspace_test
(:require [push.interpreter.core :as i]
[push.type.core :as t])
(:use midje.sweet)
(:use [push.util.test-helpers])
(:use [push.instructions.aspects])
(:use [push.type.definitions.tagspace])
(:use push.type.item.tagspace)
(:use push.instructions.aspects.to-tagspace)
)
(let
[foo-type (t/make-type :foo)
fixed-foo (t/attach-instruction foo-type (to-tagspace foo-type))]
(tabular
(fact "`:foo->tagspace` pops a :foo and two :scalar values, and makes a new :tagspace"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks fixed-foo ?instruction) => (contains ?expected))
?new-stacks ?instruction ?expected
{:foo '([1 2 3 4 5])
:scalar '(7 2)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{2 1, 13/4 2, 9/2 3, 23/4 4, 7 5}))}
{:foo '([1 2 3 4 5])
:scalar '(2 7)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{7 1, 13/4 4, 9/2 3, 23/4 2, 2 5}))}
{:foo '([1 2 3 4 5])
:scalar '(7 8)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{8 1, 29/4 4, 15/2 3, 31/4 2, 7 5}))}
{:foo '([1 2 3 4 5])
:scalar '(8 8)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace {8 5}))}
{:foo '([1 2 3 4 5])
:scalar '(10.5 5/2)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace {5/2 1, 4.5 2, 6.5 3, 8.5 4, 10.5 5}))}
{:foo '("hello")
:scalar '(1.25 2.5)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{1.25 \o, 1.5625 \l, 1.875 \l, 2.1875 \e, 2.5 \h}))}
{:foo '("")
:scalar '(2.0 8.0)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{}))}
{:foo '("live")
:scalar '(-1.5 9.0)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{-1.5 \e, 2.0 \v, 5.5 \i, 9.0 \l}))}
{:foo '("fire")
:scalar '(10.25 7.25)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{7.25 \f, 8.25 \i, 9.25 \r, 10.25 \e}))}
{:foo '("fire")
:scalar '(10.25 10.25)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list
(make-tagspace
{10.25 \e}))}
))
(let
[foo-type (t/make-type :foo)
fixed-foo (t/attach-instruction foo-type (to-tagspace foo-type))]
(tabular
(fact "`:foo->tagspace` consumes arguments but reports runtime errors if they occur"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks fixed-foo ?instruction) => (contains ?expected))
?new-stacks ?instruction ?expected
{:foo '([1 2 3 4 5])
:scalar '(7M 2/3)
:tagspace '()} :foo->tagspace {:foo '()
:scalar '()
:exec (list (make-tagspace))
:error '({:item "Non-terminating decimal expansion; no exact representable decimal result.", :step 0})}
))
| |
144ebfcd1e5bf5fbe79bd884f0aefe1958c45e784b6ea509f6d909a79eb2994e | gorillalabs/sparkling | transform.clj | (ns sparkling.ml.transform
(:import [org.apache.spark.ml.feature StandardScaler]))
(defn standard-scaler
"Scales the input-col to have a range between 0 and 1"
[{:keys [input-col output-col] :as m}]
{:pre [(every? m [:input-col :output-col])]}
(doto (StandardScaler.)
(.setInputCol input-col)
(.setOutputCol output-col)))
| null | https://raw.githubusercontent.com/gorillalabs/sparkling/ffedcc70fd46bf1b48405be8b1f5a1e1c4f9f578/src/clojure/sparkling/ml/transform.clj | clojure | (ns sparkling.ml.transform
(:import [org.apache.spark.ml.feature StandardScaler]))
(defn standard-scaler
"Scales the input-col to have a range between 0 and 1"
[{:keys [input-col output-col] :as m}]
{:pre [(every? m [:input-col :output-col])]}
(doto (StandardScaler.)
(.setInputCol input-col)
(.setOutputCol output-col)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.